// // A private method to add vertices to the terrain tile topology. // public virtual object _addVertices(object vertices) { vertices = this._assureCounterClockWise(vertices); var face = new List <object>(); foreach (var vertex in vertices) { var lookupKey = ",".join(new List <string> { "{:.14f}".format(vertex[0]), "{:.14f}".format(vertex[1]), "{:.14f}".format(vertex[2]) }); var faceIndex = this._lookupVertexIndex(lookupKey); if (faceIndex != null) { // Sometimes we can have triangles with zero area // (due to unfortunate clipping) // In that case skip them // if faceIndex in face: // break face.append(faceIndex); } else { this.vertices.append(vertex); this.cartesianVertices.append(LLH2ECEF(vertex[0], vertex[1], vertex[2])); faceIndex = this.vertices.Count - 1; this.verticesLookup[lookupKey] = faceIndex; face.append(faceIndex); } } // if len(face) == 3: this.faces.append(face); }
public PythonScriptHost(bool debugmode = false) { ResetEngine(debugmode); //ScriptRuntimeSetup setup = new ScriptRuntimeSetup(); //setup.DebugMode = debugmode; //setup.LanguageSetups.Add(Python.CreateLanguageSetup(null)); //ScriptRuntime runtime = new ScriptRuntime(setup); //_python = runtime.GetEngineByTypeName(typeof(PythonContext).AssemblyQualifiedName); List path = _python.Runtime.GetSysModule().GetVariable("path"); string standardlib = @"C:\Program Files\IronPython 2.7\Lib"; if (!path.Contains(standardlib)) { path.append(standardlib); } standardlib = standardlib + @"\site-packages"; if (!path.Contains(standardlib)) { path.append(standardlib); } standardlib = @"C:\Python27\Lib"; if (!path.Contains(standardlib)) { path.append(standardlib); } //_python.Runtime.GetClrModule().GetVariable("AddReference")("Prefab"); }
public void updateTasks(List creates, List updates) { List batch = new List(); foreach (PythonDictionary task in creates) { task["project"] = new PythonDictionary() { { "type", "Project" }, { "id", Properties.Settings.Default.ShotgunProject } }; batch.append(new PythonDictionary() { { "request_type", "create" }, { "entity_type", "Task" }, { "data", task } }); } foreach (PythonDictionary task in updates) { int id = (int)task["id"]; task.Remove("id"); batch.append(new PythonDictionary() { { "request_type", "update" }, { "entity_type", "Task" }, { "entity_id", id }, { "data", task } }); } dynamic connection = connect(); // record this most-recent activity timestamp on the 'project_plugin' script in Shotgun List filter = new List() { new List() { "salted_password", "is", connection.config.api_key } }; List fields = new List() { "type", "id" }; PythonDictionary script = connection.find_one("ApiUser", filter, fields: fields); String now = DateTime.Now.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ"); PythonDictionary timestamp = new PythonDictionary() { { "sg_last_run", now } }; batch.append(new PythonDictionary() { { "request_type", "update" }, { "entity_type", script["type"] }, { "entity_id", script["id"] }, { "data", timestamp } }); connection.batch(batch); }
public override void GetValues(List lst) { lst.append(First); foreach (var item in this) { item.GetValues(lst); } lst.append(Last); }
public tuple get_juice() { // return juice level of (face, FrontUp, BackUp, FrontDown, BackDown) in tuple var jInfo = new List <object>(); jInfo.append(this.objctrl.GetSiruFlags(SiruParts.SiruKao)); jInfo.append(this.objctrl.GetSiruFlags(SiruParts.SiruFrontUp)); jInfo.append(this.objctrl.GetSiruFlags(SiruParts.SiruBackUp)); jInfo.append(this.objctrl.GetSiruFlags(SiruParts.SiruFrontDown)); jInfo.append(this.objctrl.GetSiruFlags(SiruParts.SiruBackDown)); return(tuple(jInfo)); }
private const int RIGHT_ABOVE = 4; // Diagonal /^ /// <sumary> /// Finds all legal attack moves for the current player with /// king pieces /// </sumary> /// <param name="lastPos"> /// All piece movents until now /// </param> /// <param name="pos"> /// Current position /// </param> /// <param name="dir"> /// Last direction /// </param> /// <param name="color"> /// Current player color /// </param> /// <param name="enemy"> /// Enemy piece's color /// </param> /// <value> /// A list with all the valid attack moves /// </value> private List kingAttack(List lastPos, int pos, int dir, int color, int enemy) { List tempMoves, moves = new List(); if (dir != RIGHT_BELOW) { tempMoves = kingDiagAttack(lastPos, pos, color, enemy, 1, 1); if (notNull(tempMoves)) { moves.append(tempMoves); } } if (dir != LEFT_ABOVE) { tempMoves = kingDiagAttack(lastPos, pos, color, enemy, -1, -1); if (notNull(tempMoves)) { moves.append(tempMoves); } } if (dir != RIGHT_ABOVE) { tempMoves = kingDiagAttack(lastPos, pos, color, enemy, 1, -1); if (notNull(tempMoves)) { moves.append(tempMoves); } } if (dir != LEFT_BELOW) { tempMoves = kingDiagAttack(lastPos, pos, color, enemy, -1, 1); if (notNull(tempMoves)) { moves.append(tempMoves); } } return(moves); }
/// <sumary> /// Finds all legal attack moves for the current player /// with simple pieces /// </sumary> /// <param name="pos"> /// Current piece position /// </param> /// <param name="color"> /// Current player color /// </param> /// <param name="enemy"> /// Enemy piece's color /// </param> /// <value> /// A list with all the valid attack moves /// </value> private List simpleAttack(int pos, int color, int enemy) { int x = posToCol(pos); int y = posToLine(pos); int i; List moves = new List(); List tempMoves; int enemyPos, nextPos; i = (color == WHITE) ? -1 : 1; // See the diagonals /^ e \v if (x < 6 && y + i > 0 && y + i < 7) { enemyPos = colLineToPos(x + 1, y + i); nextPos = colLineToPos(x + 2, y + 2 * i); if ((pieces [enemyPos] & ~KING) == enemy && pieces [nextPos] == EMPTY) { tempMoves = simpleAttack(nextPos, color, enemy); moves.append(addMove(new Move(pos, nextPos), tempMoves)); } } // See the diagonals v/ e ^\ if (x > 1 && y + i > 0 && y + i < 7) { enemyPos = colLineToPos(x - 1, y + i); nextPos = colLineToPos(x - 2, y + 2 * i); if ((pieces [enemyPos] & ~KING) == enemy && pieces [nextPos] == EMPTY) { tempMoves = simpleAttack(nextPos, color, enemy); moves.append(addMove(new Move(pos, nextPos), tempMoves)); } } if (moves.isEmpty()) { moves.push_back(new List()); } return(moves); }
public static (float ade, float fde) calculate_ADE_FDE_numpy(NDArray pred, NDArray GT) { float ade, fde; if (len(pred.shape) == 3) { // [K, pred, 2] var ade_list = new List <float>(); var fde_list = new List <float>(); for (int index = 0; index < len(pred); index++) { var p = pred[index]; var all_loss = np.mean(np.sqrt(np.square(p - GT)), axis: 1); ade_list.append(np.mean(all_loss)); fde_list.append(all_loss[-1]); } var min_index = np.argmin(np.array(ade_list)); ade = ade_list[min_index]; fde = fde_list[min_index]; // # # ADE of the mean traj // # mean_traj = np.mean(pred, axis=0) // # mean_traj_loss = np.linalg.norm(mean_traj - GT, ord=2, axis=1) // # ade = np.mean(mean_traj_loss) // # fde = mean_traj_loss[-1] } else { var all_loss = np.mean(np.sqrt(np.square(pred - GT)), axis: 1); ade = np.mean(all_loss); fde = all_loss[-1]; } return(ade, fde); }
private static ITensorOrOperation[] _GatherReturnElements(string[] requested_return_elements, Graph graph, TF_ImportGraphDefResults results) { var return_outputs = results.return_tensors; var return_opers = results.return_opers; var combined_return_elements = new List <ITensorOrOperation>(); int outputs_idx = 0; int opers_idx = 0; foreach (var name in requested_return_elements) { if (name.Contains(":")) { combined_return_elements.append(graph.get_tensor_by_tf_output(return_outputs[outputs_idx])); outputs_idx += 1; } else { throw new NotImplementedException("_GatherReturnElements"); // combined_return_elements.append(graph._get_operation_by_tf_operation(return_opers[opers_idx])); } } return(combined_return_elements.ToArray()); }
/// <summary> /// Computes the overall loss. /// </summary> /// <param name="y_true"></param> /// <param name="y_pred"></param> public Tensor Call(Tensor y_true, Tensor y_pred) { if (!_built) { Build(y_pred); } var loss_value = _losses.Call(y_true, y_pred); var loss_metric_value = loss_value; var batch_dim = array_ops.shape(y_true)[0]; var loss_values = new List <Tensor>(); var loss_metric_values = new List <Tensor>(); /*if (_losses.Reduction == ReductionV2.SUM_OVER_BATCH_SIZE || _losses.Reduction == ReductionV2.AUTO) || loss_value = losses_utils.scale_loss_for_distribution(loss_value);*/ loss_values.append(loss_value); loss_metric_values.append(loss_metric_value); if (loss_values.Count > 0) { var total_loss_metric_value = math_ops.add_n(loss_metric_values.ToArray()); _loss_metric.update_state(total_loss_metric_value, batch_dim); // loss_values = losses_utils.cast_losses_to_common_dtype(loss_values); var total_loss = math_ops.add_n(loss_values.ToArray()); return(total_loss); } else { // Ok for a model to have no compiled loss. return(array_ops.zeros(new TensorShape())); } }
void _init_graph_network(Tensors inputs, Tensors outputs) { _is_graph_network = true; this.inputs = inputs; this.outputs = outputs; built = true; _build_input_shape = inputs.shape; _compute_output_and_mask_jointly = true; _expects_training_arg = true; _expects_mask_arg = true; // A graph network does not autocast inputs, as its layers will cast them instead. _autocast = false; if (outputs.Any(x => x.KerasHistory == null)) { base_layer_utils.create_keras_history(outputs); } // Build self._output_layers: foreach (var x in outputs) { var(layer, node_index, tensor_index) = x.KerasHistory; _output_layers.append(layer); _output_coordinates.append(new KerasHistory(layer, node_index, tensor_index, x)); } // Build self._input_layers: foreach (var x in inputs) { var(layer, node_index, tensor_index) = x.KerasHistory; _input_layers.append(layer); _input_coordinates.append(new KerasHistory(layer, node_index, tensor_index, x)); } }
public static Tensors get_source_inputs(Tensor tensor, ILayer layer = null, int node_index = -1) { if (layer == null) { (layer, node_index, _) = tensor.KerasHistory; } if (layer.InboundNodes == null || layer.InboundNodes.Count == 0) { return(tensor); } else { var node = layer.InboundNodes[node_index]; if (node.is_input) { return(node.input_tensors); } else { var source_tensors = new List <Tensor>(); foreach (var _layer in node.iterate_inbound()) { (layer, node_index, tensor) = (_layer.Item1, _layer.Item2, _layer.Item4); var previous_sources = get_source_inputs(tensor, layer, node_index); foreach (var x in previous_sources) { // should be check if exist? source_tensors.append(x); } } return(source_tensors); } } }
private static ITensorOrOperation[] _GatherReturnElements(string[] requested_return_elements, Graph graph, TF_ImportGraphDefResults results) { var return_outputs = results.return_tensors; var return_opers = results.return_opers; var combined_return_elements = new List<ITensorOrOperation>(); int outputs_idx = 0; #pragma warning disable CS0219 // Variable is assigned but its value is never used int opers_idx = 0; #pragma warning restore CS0219 // Variable is assigned but its value is never used foreach(var name in requested_return_elements) { if (name.Contains(":")) { combined_return_elements.append(graph.get_tensor_by_tf_output(return_outputs[outputs_idx])); outputs_idx += 1; } else { throw new NotImplementedException("_GatherReturnElements"); // combined_return_elements.append(graph._get_operation_by_tf_operation(return_opers[opers_idx])); } } return combined_return_elements.ToArray(); }
public static List nlargest(CodeContext /*!*/ context, int n, object iterable) { if (n <= 0) { return(new List()); } List ret = new List(Math.Min(n, 4000)); // don't allocate anything too huge IEnumerator en = PythonOps.GetEnumerator(iterable); // populate list with first n items for (int i = 0; i < n; i++) { if (!en.MoveNext()) { // fewer than n items; finish up here HeapSort(context, ret, true); return(ret); } ret.append(en.Current); } // go through the remainder of the iterator, maintaining a min-heap of the n largest values DoHeapify(context, ret); while (en.MoveNext()) { DoPushPop(context, ret, en.Current); } // return the largest items, in descending order HeapSort(context, ret, true); return(ret); }
// def AddWhileContext(self, op, between_op_list, between_ops): // """Add the grad state for the while loop that op belongs to. // Note that op is an Exit, and this method must be called in // the control flow context where gradients() is called. // Note that this method modifies `between_op_list` and `between_ops`. // """ // forward_ctxt = _GetWhileContext(op) // grad_state = self._map.get(forward_ctxt) // if grad_state is None: // # This is a new while loop so create a grad state for it. // outer_forward_ctxt = forward_ctxt.outer_context // if outer_forward_ctxt: // outer_forward_ctxt = outer_forward_ctxt.GetWhileContext() // outer_grad_state = None // if outer_forward_ctxt: // outer_grad_state = self._map.get(outer_forward_ctxt) // grad_state = GradLoopState(forward_ctxt, outer_grad_state) // self._map[forward_ctxt] = grad_state // # We need to include all exits of a loop for backprop. // for loop_exit in grad_state.forward_loop_exits: // if loop_exit.op not in between_ops: // between_ops.add(loop_exit.op) // between_op_list.append(loop_exit.op) public void AddWhileContext(Operation op, List <Operation> between_op_list, List <Operation> between_ops) { var forward_ctxt = op.GetWhileContext(); var grad_state = _map.ContainsKey(forward_ctxt) ? _map[forward_ctxt] : null; if (grad_state == null) { GradLoopState outer_grad_state = null; var outer_forward_ctxt = forward_ctxt.outer_context; if (outer_forward_ctxt != null) { outer_forward_ctxt = outer_forward_ctxt.GetWhileContext(); } if (outer_forward_ctxt != null) { outer_grad_state = _map[outer_forward_ctxt]; } grad_state = new GradLoopState(forward_ctxt, outer_grad_state); _map[forward_ctxt] = grad_state; // We need to include all exits of a loop for backprop. foreach (var loop_exit in grad_state.forward_loop_exits) { if (!between_ops.Contains(loop_exit.op)) { between_ops.add(loop_exit.op); between_op_list.append(loop_exit.op); } } } }
Py_InitModule4(string name, IntPtr methodsPtr, string doc, IntPtr selfPtr, int apiver) { name = this.FixImportName(name); PythonDictionary methodTable = new PythonDictionary(); PythonModule module = new PythonModule(); this.AddModule(name, module); this.CreateModulesContaining(name); PythonDictionary __dict__ = module.Get__dict__(); __dict__["__doc__"] = doc; __dict__["__name__"] = name; string __file__ = this.importFiles.Peek(); __dict__["__file__"] = __file__; List __path__ = new List(); if (__file__ != null) { __path__.append(Path.GetDirectoryName(__file__)); } __dict__["__path__"] = __path__; __dict__["_dispatcher"] = new Dispatcher(this, methodTable, selfPtr); StringBuilder moduleCode = new StringBuilder(); moduleCode.Append(CodeSnippets.USEFUL_IMPORTS); CallableBuilder.GenerateFunctions(moduleCode, methodsPtr, methodTable); this.ExecInModule(moduleCode.ToString(), module); return(this.Store(module)); }
public virtual object dropEvent(object @event) { if (@event.mimeData().hasUrls) { @event.setDropAction(QtCore.Qt.CopyAction); @event.accept(); // to get a list of files: var drop_list = new List <object>(); foreach (var url in @event.mimeData().urls()) { drop_list.append(str(url.toLocalFile())); } // handle the list here foreach (var f in drop_list) { try { if (!f.endswith(".cbr") && !f.endswith(".cbz") && !f.endswith(".zip") && !f.endswith(".rar")) { Image.open(f); } shutil.copy(f, this._tmpinputfolder); } catch { } } } else { @event.ignore(); } }
/// <sumary> /// Finds all legal attack moves for the current player. /// </sumary> /// <param name="color"> /// Current player color /// </param> /// <param name="enemy"> /// Enemy piece's color /// </param> /// <value> /// A list with all the valid attack moves /// </value> private List generateAttackMoves(int color, int enemy) { List moves = new List(); List tempMoves; for (int k = 0; k < 32; k++) { if ((pieces [k] & ~KING) == currentPlayer) { if ((pieces [k] & KING) == 0) // Simple piece { tempMoves = simpleAttack(k, color, enemy); } else // It's a king piece { List lastPos = new List(); lastPos.push_back(k); tempMoves = kingAttack(lastPos, k, NONE, color, enemy); } if (notNull(tempMoves)) { moves.append(tempMoves); } } } return(moves); }
Py_InitModule4(string name, IntPtr methodsPtr, string doc, IntPtr selfPtr, int apiver) { name = this.FixImportName(name); PythonDictionary methodTable = new PythonDictionary(); PythonModule module = new PythonModule(); this.AddModule(name, module); this.CreateModulesContaining(name); PythonDictionary __dict__ = module.Get__dict__(); __dict__["__doc__"] = doc; __dict__["__name__"] = name; string __file__ = this.importFiles.Peek(); __dict__["__file__"] = __file__; List __path__ = new List(); if (__file__ != null) { __path__.append(Path.GetDirectoryName(__file__)); } __dict__["__path__"] = __path__; __dict__["_dispatcher"] = new Dispatcher(this, methodTable, selfPtr); StringBuilder moduleCode = new StringBuilder(); moduleCode.Append(CodeSnippets.USEFUL_IMPORTS); CallableBuilder.GenerateFunctions(moduleCode, methodsPtr, methodTable); this.ExecInModule(moduleCode.ToString(), module); return this.Store(module); }
public static object meshgrid2(params object [] arrs) { arrs = tuple(reversed(arrs)); var lens = map(len, arrs); var dim = arrs.Count; var sz = 1; foreach (var s in lens) { sz *= s; } var ans = new List <object>(); foreach (var _tup_1 in arrs.Select((_p_1, _p_2) => Tuple.Create(_p_2, _p_1))) { var i = _tup_1.Item1; var arr = _tup_1.Item2; var slc = new List <int> { 1 } *dim; slc[i] = lens[i]; var arr2 = asarray(arr).reshape(slc); foreach (var _tup_2 in lens.Select((_p_3, _p_4) => Tuple.Create(_p_4, _p_3))) { var j = _tup_2.Item1; sz = _tup_2.Item2; if (j != i) { arr2 = arr2.repeat(sz, axis: j); } } ans.append(arr2); } return(tuple(ans)); }
public static object checkByColumn() { foreach (var i in Enumerable.Range(0, 9)) { var numbers = Enumerable.Range(1, 10 - 1); var locations = new List <object>(); foreach (var j in Enumerable.Range(0, 9)) { if (b[j][i] == 0) { locations.append(new List <int> { i, j }); } else { numbers.remove(b[j][i]); } } foreach (var n in numbers) { var l = findLocationColumn(n, locations); if (l != 0) { writeNumber(n, l); } } } }
PyList_Append(IntPtr listPtr, IntPtr itemPtr) { PyListObject listStruct = (PyListObject)Marshal.PtrToStructure(listPtr, typeof(PyListObject)); if (listStruct.ob_type != this.PyList_Type) { this.LastException = PythonOps.TypeError("PyList_Append: not a list"); return(-1); } if (listStruct.ob_item == IntPtr.Zero) { this.IC_PyList_Append_Empty(listPtr, ref listStruct, itemPtr); } else { this.IC_PyList_Append_NonEmpty(listPtr, ref listStruct, itemPtr); } List list = (List)this.Retrieve(listPtr); list.append(this.Retrieve(itemPtr)); this.IncRef(itemPtr); return(0); }
public static object _iterUnpackWatermaskRow(object f, object extensionLength, object structType) { var i = 0; var xyCount = 0; var row = new List <object>(); while (xyCount != extensionLength) { row.append(unpackEntry(f, structType)); if (i == 255) { yield return(row); i = 0; row = new List <object>(); } else { i += 1; } xyCount += 1; } if (row) { yield return(row); } }
void _create_ordered_metrics() { _metrics_in_order = new List <Metric>(); foreach (var m in _metrics) { _metrics_in_order.append(m); } }
public void AddPath(string path) { List pythonpaths = _python.Runtime.GetSysModule().GetVariable("path"); if (!pythonpaths.Contains(path)) { pythonpaths.append(path); } }
/// <summary> /// Reconstructs graph from config object. /// </summary> /// <param name="config"></param> /// <returns></returns> static (Tensors, Tensors, Dictionary <string, ILayer>) reconstruct_from_config(ModelConfig config) { // Layer instances created during the graph reconstruction process. var created_layers = new Dictionary <string, ILayer>(); var node_index_map = new Dictionary <(string, int), int>(); var node_count_by_layer = new Dictionary <ILayer, int>(); var unprocessed_nodes = new Dictionary <ILayer, NodeConfig>(); // First, we create all layers and enqueue nodes to be processed foreach (var layer_data in config.Layers) { process_layer(created_layers, layer_data, unprocessed_nodes, node_count_by_layer); } // Then we process nodes in order of layer depth. // Nodes that cannot yet be processed (if the inbound node // does not yet exist) are re-enqueued, and the process // is repeated until all nodes are processed. while (unprocessed_nodes.Count > 0) { foreach (var layer_data in config.Layers) { var layer = created_layers[layer_data.Name]; if (unprocessed_nodes.ContainsKey(layer)) { var node_data = unprocessed_nodes[layer]; // foreach (var node_data in unprocessed_nodes[layer]) { process_node(layer, node_data, created_layers, node_count_by_layer, node_index_map); unprocessed_nodes.Remove(layer); } } } } var input_tensors = new List <Tensor>(); foreach (var layer_data in config.InputLayers) { var(layer_name, node_index, tensor_index) = (layer_data.Name, layer_data.NodeIndex, layer_data.TensorIndex); var layer = created_layers[layer_name]; var layer_output_tensors = layer.InboundNodes[node_index].Outputs; input_tensors.append(layer_output_tensors[tensor_index]); } var output_tensors = new List <Tensor>(); foreach (var layer_data in config.OutputLayers) { var(layer_name, node_index, tensor_index) = (layer_data.Name, layer_data.NodeIndex, layer_data.TensorIndex); var layer = created_layers[layer_name]; var layer_output_tensors = layer.InboundNodes[node_index].Outputs; output_tensors.append(layer_output_tensors[tensor_index]); } return(input_tensors, output_tensors, created_layers); }
///FUNCTION_NAME: getForwardDataset_onlyTraj ///<summary> /// Get inputs for models who only takes `obs_traj` as input. /// ///</summary> ///<param name="input_agents"> a list of input agents, type = `List[Agent]` </param> public static Tensors getForwardDataset_onlyTraj(List <TrainAgentManager> input_agents) { var trajs = new List <NDArray>(); foreach (var agent in input_agents) { trajs.append(agent.traj); } return(new Tensor(np.stack(trajs.ToArray()), tf.float32)); }
// 座標追加 private void append() { optiP.append(optiP()); optiR.append(optiR()); Vector3[] axi = axiDrawClient.GetVec(); axiP.append(axi[0]); axiR.append(axi[1]); }
public List <NDArray> get_neighbor_traj_linear_linear() { var results = new List <NDArray>(); foreach (var item in this._neighbor_traj_linear_pred) { results.append(np.array(item).astype(np.float32)); } return(results); }
public static object squaredDistances(object coordsPairs) { var sDistances = new List <object>(); foreach (var coordsPair in coordsPairs) { sDistances.append(c3d.distanceSquared(coordsPair[0], coordsPair[1])); } return(sDistances); }
public static Tensor tf_batch_matmul(Tensor left_low, Tensor right_high) { var temp = new List <Tensor>(); for (int index = 0; index < right_high.shape[0]; index++) { temp.append(tf.matmul(left_low, right_high[index])); } return(tf.stack(temp.ToArray())); }
public static object Get__file__(NamespaceTracker self) { if (self.PackageAssemblies.Count == 1) { return self.PackageAssemblies[0].FullName; } List res = new List(); for (int i = 0; i < self.PackageAssemblies.Count; i++) { res.append(self.PackageAssemblies[i].FullName); } return res; }
public static List getaddrinfo( CodeContext/*!*/ context, string host, object port, [DefaultParameterValue((int)AddressFamily.Unspecified)] int family, [DefaultParameterValue(0)] int socktype, [DefaultParameterValue((int)ProtocolType.IP)] int proto, [DefaultParameterValue((int)SocketFlags.None)] int flags ) { int numericPort; if (port == null) { numericPort = 0; } else if (port is int) { numericPort = (int)port; } else if (port is Extensible<int>) { numericPort = ((Extensible<int>)port).Value; } else if (port is string) { if (!Int32.TryParse((string)port, out numericPort)) { // TODO: also should consult GetServiceByName throw PythonExceptions.CreateThrowable(gaierror(context), "getaddrinfo failed"); } } else if (port is ExtensibleString) { if (!Int32.TryParse(((ExtensibleString)port).Value, out numericPort)) { // TODO: also should consult GetServiceByName throw PythonExceptions.CreateThrowable(gaierror(context), "getaddrinfo failed"); } } else { throw PythonExceptions.CreateThrowable(gaierror(context), "getaddrinfo failed"); } if (socktype != 0) { // we just use this to validate; socketType isn't actually used System.Net.Sockets.SocketType socketType = (System.Net.Sockets.SocketType)Enum.ToObject(typeof(System.Net.Sockets.SocketType), socktype); if (socketType == System.Net.Sockets.SocketType.Unknown || !Enum.IsDefined(typeof(System.Net.Sockets.SocketType), socketType)) { throw PythonExceptions.CreateThrowable(gaierror(context), PythonTuple.MakeTuple((int)SocketError.SocketNotSupported, "getaddrinfo failed")); } } AddressFamily addressFamily = (AddressFamily)Enum.ToObject(typeof(AddressFamily), family); if (!Enum.IsDefined(typeof(AddressFamily), addressFamily)) { throw PythonExceptions.CreateThrowable(gaierror(context), PythonTuple.MakeTuple((int)SocketError.AddressFamilyNotSupported, "getaddrinfo failed")); } // Again, we just validate, but don't actually use protocolType Enum.ToObject(typeof(ProtocolType), proto); IPAddress[] ips = HostToAddresses(context, host, addressFamily); List results = new List(); foreach (IPAddress ip in ips) { results.append(PythonTuple.MakeTuple( (int)ip.AddressFamily, socktype, proto, "", EndPointToTuple(new IPEndPoint(ip, numericPort)) )); } return results; }
public List getRGB() { List list = new List(); list.append(this.red); list.append(this.green); list.append(this.blue); return list; }
/// <summary> /// Process a sequence of objects that are compatible with ObjectToSocket(). Return two /// things as out params: an in-order List of sockets that correspond to the original /// objects in the passed-in sequence, and a mapping of these socket objects to their /// original objects. /// /// The socketToOriginal mapping is generated because the CPython select module supports /// passing to select either file descriptor numbers or an object with a fileno() method. /// We try to be faithful to what was originally requested when we return. /// </summary> private static void ProcessSocketSequence(CodeContext context, object sequence, out List socketList, out Dictionary<Socket, object> socketToOriginal) { socketToOriginal = new Dictionary<Socket, object>(); socketList = new List(); IEnumerator cursor = PythonOps.GetEnumerator(sequence); while (cursor.MoveNext()) { object original = cursor.Current; Socket socket = ObjectToSocket(context, original); socketList.append(socket); socketToOriginal[socket] = original; } }
public List readlines([DefaultParameterValue(-1)]int size) { EnsureOpen(); List lines = new List(); for (Bytes line = readline(-1); line.Count > 0; line = readline(-1)) { lines.append(line); if (size > 0) { size -= line.Count; if (size <= 0) { break; } } } return lines; }
public static List nsmallest(CodeContext/*!*/ context, int n, object iterable) { if (n <= 0) { return new List(); } List ret = new List(Math.Min(n, 4000)); // don't allocate anything too huge IEnumerator en = PythonOps.GetEnumerator(iterable); // populate list with first n items for (int i = 0; i < n; i++) { if (!en.MoveNext()) { // fewer than n items; finish up here HeapSort(context, ret); return ret; } ret.append(en.Current); } // go through the remainder of the iterator, maintaining a max-heap of the n smallest values DoHeapifyMax(context, ret); while (en.MoveNext()) { DoPushPopMax(context, ret, en.Current); } // return the smallest items, in ascending order HeapSort(context, ret); return ret; }
public override List readlines([DefaultParameterValue(null)]object hint) { _checkClosed(); int size = GetInt(hint, -1); List lines = new List(); for (Bytes line = readline(-1); line.Count > 0; line = readline(-1)) { lines.append(line); if (size > 0) { size -= line.Count; if (size <= 0) { break; } } } return lines; }
public IEnumerator GetEnumerator() { List results = new List(); try { while(true) results.append(this.next(this.context)); } catch(StopIterationException) { } return results.GetEnumerator(); }
public List keys() { List list = new List(); for(int i = 0; i < data.Count; ++i) { list.append(((PythonTuple)description[i])[0]); } return list; }
public List getRGB(int x, int y) { /* Returns a triple (r,g,b) of the red, green, and blue intensities of the pixel at (x,y). Intensity values are in range(256). */ byte r, g, b; unsafe { byte *pixels = (byte *)this.pixbuf.Pixels; r = pixels[x * bytesPerPixel + y * pixbuf.Rowstride + 0]; g = pixels[x * bytesPerPixel + y * pixbuf.Rowstride + 1]; b = pixels[x * bytesPerPixel + y * pixbuf.Rowstride + 2]; } List list = new List(); list.append((int)r); list.append((int)g); list.append((int)b); return list; }
private void ActualiseList(IntPtr ptr) { if (this.listsBeingActualised.ContainsKey(ptr)) { throw new Exception("Fatal error: PythonMapper.listsBeingActualised is somehow corrupt"); } List newList = new List(); this.listsBeingActualised[ptr] = newList; int length = CPyMarshal.ReadIntField(ptr, typeof(PyListObject), "ob_size"); if (length != 0) { IntPtr itemPtrPtr = CPyMarshal.ReadPtrField(ptr, typeof(PyListObject), "ob_item"); for (int i = 0; i < length; i++) { IntPtr itemPtr = CPyMarshal.ReadPtr(itemPtrPtr); if (itemPtr == IntPtr.Zero) { // We have *no* idea what to do here. throw new ArgumentException("Attempted to Retrieve uninitialised PyListObject -- expect strange bugs"); } if (this.listsBeingActualised.ContainsKey(itemPtr)) { newList.append(this.listsBeingActualised[itemPtr]); } else { newList.append(this.Retrieve(itemPtr)); } itemPtrPtr = CPyMarshal.Offset(itemPtrPtr, CPyMarshal.PtrSize); } } this.listsBeingActualised.Remove(ptr); this.incompleteObjects.Remove(ptr); this.map.Associate(ptr, newList); }