query
stringlengths
9
9.05k
document
stringlengths
10
222k
metadata
dict
negatives
sequencelengths
30
30
negative_scores
sequencelengths
30
30
document_score
stringlengths
4
10
document_rank
stringclasses
2 values
Changing sizes of the fields CharField and TextField
def fieldSize(size, rows, cols): formfield_overrides = { models.CharField: {'widget': TextInput(attrs={'size': str(size)})}, models.TextField: {'widget': Textarea(attrs={'rows': rows, 'cols': cols})}, } return formfield_overrides
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def __updateSize(self, *args):\n bottom, top = self.getRange()\n nbchar = max(len(str(bottom)), len(str(top)))\n font = self.font()\n font.setStyle(qt.QFont.StyleItalic)\n fontMetrics = qt.QFontMetrics(font)\n self.setMaximumWidth(\n fontMetrics.boundingRect('0' * (nbchar + 1)).width()\n )\n self.setMaxLength(nbchar)", "def field_creator(self, size=(1600, 900)) -> None:\n # size[0] - строк; size[1] - столбцов\n # 80 - оптимальное значение на данный момент\n with open(normpath('levels/level/lvl1' + '_field.py'), 'w') as f:\n f.write('Field = [' + '\\n')\n for i in range(0, size[1], settings.precision):\n buf_mas = list()\n for j in range(0, size[0], settings.precision):\n tmp = False\n for item in self.objects:\n if (item.collidepoint(j, i)):\n tmp = True\n break\n if tmp:\n buf_mas.append(-1)\n else:\n buf_mas.append(0)\n f.write(' '+str(buf_mas) + ',\\n')\n f.write(']')", "def field_width(self, field_width):\n\n self._field_width = field_width", "def field_width(self, field_width):\n\n self._field_width = field_width", "def on_size(self, event):\r\n event.Skip()\r\n self.text_info.Label = conf.InfoText\r\n wx.CallAfter(lambda: self and\r\n (self.text_info.Wrap(self.mediactrl.Size.width),\r\n self.text_info.Parent.Layout()))", "def test_prep_charfield_size(self):\n pass", "def text_changed(self, new_text):\n if resizing:\n text_width = self.fm.width(new_text)\n new_width = text_width + 15 # add some buffer\n self.setFixedWidth(min(\n max(new_width, self.base_width),\n self.max_width\n ))\n self.node_gui.update_shape()\n self.on_widget_val_changed(self.val)", "def text_changed(self, new_text):\n if resizing:\n text_width = self.fm.width(new_text)\n new_width = text_width + 15 # add some buffer\n self.setFixedWidth(min(\n max(new_width, self.base_width),\n self.max_width\n ))\n self.node_gui.update_shape()\n self.on_widget_val_changed(self.val)", "def TextFieldOptionsAddFontSize(builder, fontSize):\n return AddFontSize(builder, fontSize)", "def __init__(self, *args, **kwargs):\n super(MonkeyTyperForm, self).__init__(*args, **kwargs)\n self.fields['typedField'].widget = forms.Textarea(attrs={'cols': self.instance.dieImage.bitWidth+2,\n 'rows': self.instance.dieImage.bitHeight+2,\n 'style': 'font-family:monospace;'})", "def FloatingSize(self, size):\r\n \r\n self.floating_size = wx.Size(*size)\r\n return self", "def set_size(self, w, h):\n\t\tpass", "def change_size(self, width, height):\n oldw = float(self.size().width())\n oldh = float(self.size().height())\n\n if self.indicator_type == 'session':\n neww = int(oldw + oldw * (width / 100.0))\n if neww > 0:\n self.setFixedSize(neww, oldh)\n elif self.indicator_type == 'unit':\n newh = int(oldh + oldh * (height / 100.0))\n if newh > 0:\n self.setFixedSize(oldw, newh)\n\n self.set_font_size()", "def lala(self):\n\n var = str(self.lineEdit.text())\n self.layout.addWidget(self.textEdit)\n self.layout.addWidget(self.button1)\n\n self.textEdit.document().setPlainText(nuke_info(var))\n\n font = self.textEdit.document().defaultFont()\n fontMetrics = QFontMetrics(font)\n textSize = fontMetrics.size(0, self.textEdit.toPlainText())\n\n w = textSize.width() + 10\n h = textSize.height() + 10\n self.resize(800, h * 3)\n if self.height() <= 350:\n self.resize(800, 350)\n else:\n pass\n self.textEdit.setReadOnly(True)\n self.setMinimumHeight(350)\n self.setMaximumHeight(700)", "def setWidth(*args):", "def setWidth(*args):", "def setWidth(*args):", "def setWidth(*args):", "def setWidth(*args):", "def setWidth(*args):", "def setWidth(*args):", "def setWidth(*args):", "def setWidth(*args):", "def setWidth(*args):", "def setWidth(*args):", "def form_TextAreaColsAndRows(request):\n schema = schemaish.Structure()\n schema.add('textAreaCustom', schemaish.String())\n\n form = formish.Form(schema, 'form')\n form['textAreaCustom'].widget = formish.TextArea(cols=20,rows=4)\n return form", "def set_size(self, value='S'):\n upper = value.upper()\n\n if upper == 'M': # Medium: double height\n # size = 0x01\n # charHeight = 48\n # maxColumn = 32\n self.double_height_on()\n self.double_width_off()\n elif upper == 'L': # Large: double width and height\n # size = 0x11\n # charHeight = 48\n # maxColumn = 16\n self.double_height_on()\n self.double_width_on()\n else: # Small: standard width and height\n # size = 0x00\n # charHeight = 24\n # maxColumn = 32\n self.double_width_off()\n self.double_height_off()\n # writeBytes(ASCII_GS, '!', size)\n # prevByte = '\\n' # Setting the size adds a linefeed", "def add_field(self, name, fieldType=\"C\", size=\"50\", decimal=0):\n if not size:\n size = \"50\"\n field_name = field_name = unicodedata.normalize('NFKD', name).encode('ascii', 'ignore')\n self.w.field(field_name, fieldType, str(size), decimal) #field name cannot be unicode, must be str()", "def fl_set_form_size(ptr_flform, width, height):\n _fl_set_form_size = library.cfuncproto(\n library.load_so_libforms(), \"fl_set_form_size\", \\\n None, [cty.POINTER(xfdata.FL_FORM), xfdata.FL_Coord,\n xfdata.FL_Coord], \\\n \"\"\"void fl_set_form_size(FL_FORM * form, FL_Coord w, FL_Coord h)\"\"\")\n library.check_if_flinitialized()\n library.verify_flformptr_type(ptr_flform)\n i_width = library.convert_to_FL_Coord(width)\n i_height = library.convert_to_FL_Coord(height)\n library.keep_elem_refs(ptr_flform, width, i_width, height, i_height)\n _fl_set_form_size(ptr_flform, i_width, i_height)", "def width(self):\n\t\tpass" ]
[ "0.59937036", "0.59723264", "0.59423476", "0.59423476", "0.5840828", "0.5839777", "0.583722", "0.583722", "0.5796603", "0.5787035", "0.5785973", "0.577334", "0.57362247", "0.5730432", "0.5689748", "0.5689748", "0.5689748", "0.5689748", "0.5689748", "0.5689748", "0.5689748", "0.5689748", "0.5689748", "0.5689748", "0.5689748", "0.5663705", "0.5640115", "0.5617053", "0.561245", "0.55970246" ]
0.7416564
0
Just compute the logits and outputs given activations.
def compute_asa_output(self, activations): asa_logits = tf.contrib.layers.linear( activations, 1, weights_initializer=tf.random_uniform_initializer(-0.01, 0.01), scope='ASALogits') self.asa_output = tf.nn.relu(asa_logits, name='ASA_output_relu') return asa_logits
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _compute_outputs(self, *args, **kwargs):\n pass\n # self.outputs = self.model(input_ids=self.input_ids, masked_lm_labels=self.input_ids)\n # self.logits = self.outputs[0][0]\n # self.probs = torch.softmax(self.logits, 1)", "def logistic(self, data, weights, biases):\n\n state_weight_prods = np.dot(data, weights)\n print(-state_weight_prods - biases)\n activations = 1.0 / (1 + np.exp(-state_weight_prods - biases))\n plt.plot(state_weight_prods, activations)\n plt.show()\n return activations", "def logistic_no_bias(self, data, weights, biases):\n\n state_weight_prods = np.dot(data, weights)\n activations = 1.0 / (1 + np.exp(-state_weight_prods))\n #plt.plot(state_weight_prods, activations)\n #plt.show()\n return activations", "def compute(self, inputs):\n\t\tres = inputs\n\t\tfor layer in range(self.layersNumber):\n\t\t\tweight = self.weights[layer]\n\t\t\tbias = self.biases[layer]\n\t\t\tres = fActivation(np.dot(weight, res) + bias)\n\t\treturn res", "def feedforward(self, inputs):\n # hidden activations\n # a_hidden = self.transfer(np.dot(self.w_input, inputs))\n a_hidden = self.transfer(np.dot(inputs, self.w_input))\n \n #a_output = self.transfer(np.dot(self.w_output, a_hidden))\n dots = (np.dot(a_hidden, self.w_output))\n a_output = self.transfer(np.asarray(dots))\n\n return (a_hidden, a_output)", "def calculate(self, inputs):\r\n inputs_with_bias = (*inputs, 1)\r\n return [self._activation_function(num) for num in self.weights @ inputs_with_bias] # @ means matrix multiplication\r", "def activates(self, inputs):\n total = self.weights[0] * self.bias\n for i in range(len(inputs)):\n total += inputs[i] * self.weights[i + 1]\n return sigmoid(total)", "def feedforward(self, inputs):\n # hidden activations\n # a_hidden = self.transfer(np.dot(self.w_input, inputs))\n a_hidden1 = self.transfer(np.dot(inputs, self.w_input))\n \n dots1 = (np.dot(a_hidden1, self.w_middle))\n a_hidden2 = self.transfer(np.asarray(dots1))\n \n #a_output = self.transfer(np.dot(self.w_output, a_hidden))\n dots2 = (np.dot(a_hidden2, self.w_output))\n a_output = self.transfer(np.asarray(dots2))\n \n return (a_hidden1, a_hidden2, a_output)", "def activate(self, inputs):\n # Calculate values of hidden nodes\n hidden_values = []\n for i in range(self.hidden_layer_size):\n hidden_node_value = 0\n bias_weight = self.bias_weights[i]\n hidden_node_value += bias_weight\n for j in range(self.input_values):\n weight = self.input_to_hidden_layer_weights[i][j]\n hidden_node_value += inputs[j] * weight\n\n # ReLU activation function\n hidden_node_value = max(hidden_node_value, 0)\n\n hidden_values.append(hidden_node_value)\n\n # Calculate output value\n output_value = 0\n for i in range(self.hidden_layer_size):\n output_value += hidden_values[i] * \\\n self.hidden_to_output_layer_weights[i]\n\n return output_value", "def engage(self):\n # no sigmoid for the inputs and bias\n if layer != 0:\n self.outputValue = sigmoid(inputSum);\n\n for connection in self.outputConnections:\n if connection.enabled == True:\n #connection will have toNode\n connection.toNode.inputSum += connection.weight * self.outputValue;", "def evaluate(observations, model, states=None, log=False):\r\n N = model.N\r\n T = observations.shape[0]\r\n A = numpy.log(model.A)\r\n B = numpy.log(model.B)\r\n\r\n if states is None:\r\n alphas = forward_path(observations, numpy.log(model.pi), A, B, T, N)\r\n\r\n \"\"\" Termination \"\"\"\r\n result = add_logs(alphas[T-1, :])\r\n if log:\r\n return result\r\n else:\r\n return math.exp(result)\r\n\r\n else:\r\n result = 0\r\n for i in range(T):\r\n result += B[states[i], observations[i]]\r\n\r\n if log:\r\n return result\r\n else:\r\n return math.exp(result)", "def __call__(self, inputs):\n return self._hidden_activation(inputs)", "def initialiseActivationFunctions(self):\n\n\t\t###uniform for output units\n\t\tif self._outputActivationFunctions == None or self._outputActivationDerivatives == None:\t\n\t\n\t\t\tself._outputActivationFunctions = []\n\t\t\tself._outputActivationDerivatives = []\n\n\t\t\tactFunc = lambda x : x\n\t\t\tdActFunc = lambda x : 1.0\n\t\n\t\t\tfor i in range(self.nOutputs):\n\t\t\t\t\n\t\t\t\tself._outputActivationFunctions.append(actFunc)\n\t\t\t\tself._outputActivationDerivatives.append(dActFunc)\n\n\t\t\tself._outputActivationFunctions = np.array(self._outputActivationFunctions)\n\t\t\tself._outputActivationDerivatives = np.array(self._outputActivationDerivatives)\n\t\t\t\n\n\t\tif self._hiddenActivationFunctions == None or self._hiddenActivationDerivatives == None:\n\n\t\t\tself._hiddenActivationFunctions = []\n\t\t\tself._hiddenActivationDerivatives = []\n\n\t\t\tfor i in range(self.nHiddenLayers):\n\n\t\t\t\tfTemp = []\n\t\t\t\tdTemp = []\n\t\t\t\t\n\t\t\t\t#Make the default sigmoid the one suggested in LeCun et al 1998\n\t\t\t\ttwist = 0.01\n\t\t\t\ta = 1.7159\n\t\t\t\tc = 2.0/3.0\n\n\t\t\t\tactFunc = lambda x : a*np.tanh(c*x) + twist*x\n\t\t\t\tdActFunc = lambda x : twist + a*c*(1.0 - (np.tanh(c*x)**2.0))\n\n#\t\t\t\tactFunc = lambda x : np.tanh(x)\n#\t\t\t\tdActFunc = lambda x : 1.0 - np.tanh(x)**2.0\n\n\t\t\t\t#plus all of the bias\n\t\t\t\tfor j in range(self.nUnitsPerLayer+1):\n\t\t\t\t\t\n\t\t\t\t\tfTemp.append(actFunc)\n\t\t\t\t\tdTemp.append(dActFunc)\n\t\t\t\t\n\t\t\t\tself._hiddenActivationFunctions.append(fTemp)\n\t\t\t\tself._hiddenActivationDerivatives.append(dTemp)\n\t\t\t\n\t\t\tself._hiddenActivationFunctions = np.array(self._hiddenActivationFunctions)\n\t\t\tself._hiddenActivationDerivatives = np.array(self._hiddenActivationDerivatives)", "def forward_propagate(self, inputs):\n\n activations = inputs\n self.activations[0] = inputs\n\n for i, w in enumerate(self.weights):\n # Calculate the net inputs\n net_inputs = np.dot(activations, w)\n\n # Calculate the activations\n activations = self._sigmoid(net_inputs)\n self.activations[i+1] = activations\n\n return activations", "def calculate(self, inputs:[bool]):\n\n w_som = 0\n outputs = []\n for i in range(len(inputs)):# iterate through the index inputs e.g [0,0]\n weight = self.weights[i] # get weight \n x = inputs[i] # get x\n\n w_som += (weight*x) # increment w_som with the multiplication of weighti and xi\n output = self.activation(w_som) # apply the step function to w_Som\n #print(outputs)\n return output", "def call(self, inputs):\n\n x = tf.matmul(inputs, self.w) + self.b\n x = self.activation(x)\n\n return x", "def activate(self, inputs: Tuple[float, ...]) -> Tuple[float, ...]:\n self.z = [Math.dot(self.w[i], inputs) + self.b[i]\n for i in range(len(self.w))]\n self.a = [self.g(real) for real in self.z]\n return tuple(self.a)", "def __call__(self, inputs: np.ndarray):\n # Denote the impact the inputs have directly on the outputs\n output_inputs: np.ndarray = np.matmul(self.in2out, inputs.transpose()).transpose()\n \n # Denote the impact hidden nodes have on the outputs, if there are hidden nodes\n if self.n_hidden > 0:\n # Nice to know:\n # - np.transpose() will transpose the tensor\n # - np.matmul(tensor1, tensor2) will perform a matrix multiplication between tensor and tensor2\n \n # The activation is defined by:\n # - the inputs mapping to the hidden nodes\n # - the hidden nodes mapping to themselves\n # - the hidden nodes' biases\n \n # 1) Propagate the hidden nodes\n self.hidden_act = self.act_f(np.matmul(self.in2hid, inputs.transpose()).transpose() +\n np.matmul(self.hid2hid, self.hidden_act.transpose()).transpose() +\n self.hidden_biases)\n \n # 2) Execute the RNN nodes if they exists (updating current hidden state)\n for i, rnn_idx in enumerate(self.rnn_idx):\n self.rnn_state[:, i] = self.rnn_array[i](\n np.concatenate((self.in2hid[rnn_idx] * inputs,\n self.hid2hid[rnn_idx] * self.hidden_act),\n axis=1)[self.rnn_map[i]].reshape(self.bs, self.rnn_array[i].input_size)\n )\n self.hidden_act[:, rnn_idx] = self.rnn_state[:, i, 0]\n \n # 3) Propagate hidden-values to the outputs\n output_inputs += np.matmul(self.hid2out, self.hidden_act.transpose()).transpose()\n \n # Define the values of the outputs, which is the sum of their received inputs and their corresponding bias\n self.output_act = self.act_f(output_inputs + self.output_biases)\n return self.output_act", "def forward(self, features):\n activations = {}\n for index, layer in enumerate(self.layers):\n if index == 0:\n activations[index] = layer(features)\n else:\n activations[index] = layer(activations[index - 1])\n logits = activations[len(activations) - 1]\n return logits", "def apply_neurons(self):\n for neuron in range(self.n_outputs):\n self.uf_activate(neuron)", "def call(self, inputs, states):\r\n (out_prev, Vm_prev) = states\r\n\r\n #Vm = Vm_prev * (1.0 - out_prev)\r\n #Lateral inhibition logic:\r\n Vm = Vm_prev * (1.0 - tf.reduce_max(out_prev))\r\n\r\n Vm = Vm * self.decay\r\n Vm = Vm + tf.matmul(inputs, self.kernel)\r\n if self.recurrent:\r\n Vm = Vm + tf.matmul(out_prev, self.recurrent_kernel)\r\n Vm = self.g(Vm)\r\n overVth = Vm - self.bias\r\n out = self.activation(overVth)\r\n return out, (out, Vm)", "def get_outputs():\n all_hidden_states = get_states()\n all_attention = tf.map_fn(get_attention, all_hidden_states)\n a_values = tf.nn.softmax(all_attention, axis = 0)\n final_hidden_state = tf.einsum('ijk,ijl->jkl', a_values, \n all_hidden_states)\n output = tf.nn.sigmoid(tf.matmul(final_hidden_state[:,0,:], Wo) + bo, \n name='outputs')\n return output, a_values", "def call(self, inputs):\n # print(f'type(inputs)={type(inputs)}.')\n # Transform a, e, and R from log to linear\n a = self.get_a()\n e = self.get_e()\n inc = self.get_inc()\n Omega = self.get_Omega()\n omega = self.get_omega()\n f = self.get_f()\n R = self.get_R()\n return a, e, inc, Omega, omega, f, self.epoch, R", "def inference(net, inputs):\n \n hidden = np.zeros(net.hidden)\n \n logits = []\n for s in range(len(inputs)):\n \n val, hidden = net.forward(inputs[s], hidden)\n \n logits.append(val)\n \n \n return np.array(logits)", "def neural_net_predict(self, inputs):\n for W, b in self.params:\n outputs = np.dot(inputs, W) + b\n inputs = np.tanh(outputs)\n return outputs # - logsumexp(outputs, axis=1, keepdims=True)", "def __call__(self,logits):\n \n #sample from Gumbel(0, 1)\n uniform = self._srng.uniform(logits.shape,low=0,high=1)\n gumbel = -T.log(-T.log(uniform + self.eps) + self.eps)\n \n #draw a sample from the Gumbel-Softmax distribution\n return T.nnet.softmax((logits + gumbel) / self.temperature)", "def logistic(weights, data, targets, hyperparameters):\n\n # TODO: Finish this function\n\n return f, df, y", "def compute_act(self, x):\n self.p = self.weights @ x.T #+ self.bias\n self.z = self.__act_f(self.p)\n \n return self.z", "def forward(self, logits, temperature):\n flat = logits.view(logits.shape[:-2] + (-1,))\n weights = F.softmax(flat / temperature, dim=-1).view_as(logits)\n\n x = (weights.sum(-2) * torch.linspace(-1, 1, logits.shape[-1]).type_as(logits)).sum(-1)\n y = (weights.sum(-1) * torch.linspace(-1, 1, logits.shape[-2]).type_as(logits)).sum(-1)\n\n return torch.stack((x, y), -1), weights", "def on_train_begin(self, logs={}):\n self.losses = []\n self.accuracies = []" ]
[ "0.67076755", "0.6531197", "0.6527088", "0.64616674", "0.6449939", "0.63124216", "0.628669", "0.6226123", "0.6211575", "0.62114877", "0.62107086", "0.61876786", "0.61538976", "0.61358494", "0.61024755", "0.6069556", "0.60633683", "0.6017902", "0.5952135", "0.59489363", "0.5947253", "0.59101075", "0.588101", "0.58748716", "0.58603877", "0.58570844", "0.5848905", "0.5824499", "0.58190775", "0.5816454" ]
0.69602144
0
Find the positions for a city with a top and a bottom
def test_find_city(self): # Given game_state: CarcassonneGameState = CarcassonneGameState() city_top = base_tiles["city_top"] city_bottom = city_top.turn(2) game_state.board = [[None for column in range(1)] for row in range(2)] game_state.board[0][0] = city_bottom game_state.board[1][0] = city_top # When city: City = CityUtil.find_city( game_state=game_state, city_position=CoordinateWithSide(Coordinate(0, 0), Side.BOTTOM) ) # Then self.assertTrue(city.finished) self.assertEqual(2, len(city.city_positions)) self.assertIn(CoordinateWithSide(Coordinate(0, 0), Side.BOTTOM), city.city_positions) self.assertIn(CoordinateWithSide(Coordinate(1, 0), Side.TOP), city.city_positions)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_city_points(city):\n for item in coordinate_list:\n if item[0] == city:\n return (item[1], item[2])", "def test_find_donut_city(self):\n\n # Given\n game_state: CarcassonneGameState = self.create_donut_city_board()\n\n # When\n city: City = CityUtil.find_city(\n game_state=game_state,\n city_position=CoordinateWithSide(Coordinate(0, 0), Side.BOTTOM)\n )\n\n # Then\n self.assertTrue(city.finished)\n self.assertEqual(16, len(city.city_positions))\n self.assertIn(CoordinateWithSide(Coordinate(0, 0), Side.BOTTOM), city.city_positions)\n self.assertIn(CoordinateWithSide(Coordinate(0, 0), Side.RIGHT), city.city_positions)\n self.assertIn(CoordinateWithSide(Coordinate(0, 1), Side.LEFT), city.city_positions)\n self.assertIn(CoordinateWithSide(Coordinate(0, 1), Side.RIGHT), city.city_positions)\n self.assertIn(CoordinateWithSide(Coordinate(0, 2), Side.LEFT), city.city_positions)\n self.assertIn(CoordinateWithSide(Coordinate(0, 2), Side.BOTTOM), city.city_positions)\n self.assertIn(CoordinateWithSide(Coordinate(1, 0), Side.TOP), city.city_positions)\n self.assertIn(CoordinateWithSide(Coordinate(1, 0), Side.BOTTOM), city.city_positions)\n self.assertIn(CoordinateWithSide(Coordinate(1, 2), Side.TOP), city.city_positions)\n self.assertIn(CoordinateWithSide(Coordinate(1, 2), Side.BOTTOM), city.city_positions)\n self.assertIn(CoordinateWithSide(Coordinate(2, 0), Side.TOP), city.city_positions)\n self.assertIn(CoordinateWithSide(Coordinate(2, 0), Side.RIGHT), city.city_positions)\n self.assertIn(CoordinateWithSide(Coordinate(2, 1), Side.LEFT), city.city_positions)\n self.assertIn(CoordinateWithSide(Coordinate(2, 1), Side.RIGHT), city.city_positions)\n self.assertIn(CoordinateWithSide(Coordinate(2, 2), Side.LEFT), city.city_positions)\n self.assertIn(CoordinateWithSide(Coordinate(2, 2), Side.TOP), city.city_positions)", "def test_find_cities(self):\n\n # Given\n game_state: CarcassonneGameState = CarcassonneGameState()\n\n city_one_side_straight_road = base_tiles[\"city_top_straight_road\"].turn(3)\n city_with_road = inns_and_cathedrals_tiles[\"ic_15\"].turn(3)\n\n game_state.board = [[None for column in range(2)] for row in range(1)]\n\n game_state.board[0][0] = city_with_road\n game_state.board[0][1] = city_one_side_straight_road\n\n # When\n cities: [City] = CityUtil.find_cities(\n game_state=game_state,\n coordinate=Coordinate(0, 0)\n )\n\n # Then\n self.assertEqual(1, len(cities))\n self.assertEqual(2, len(cities[0].city_positions))\n self.assertTrue(cities[0].finished)", "def get_near(self,map):\n near_cells = []\n for i in range(self.x-1, self.x+2):\n for j in range(self.y-1, self.y+2):\n if(i>=0 and i<map.size and j>=0 and j<map.size): near_cells.append(map.search(i,j))\n return near_cells", "def get_coordinates_for_city(city, state=None):\n search_str = ', '.join([city, state]) if state else city\n db_coords = get_coordinates_from_db(search_str)\n if db_coords:\n return (search_str, db_coords)\n else:\n page_title, coords = get_coordinates_from_wikipedia(search_str)\n add_coordinates_to_db(coords, search_str)\n return (page_title, coords)", "def get_bounds(self, ped_pos):\n top_left_x = ped_pos[:, 0] - self.neighborhood_size / 2\n top_left_y = ped_pos[:, 1] + self.neighborhood_size / 2\n bottom_right_x = ped_pos[:, 0] + self.neighborhood_size / 2\n bottom_right_y = ped_pos[:, 1] - self.neighborhood_size / 2\n\n top_left = torch.stack([top_left_x, top_left_y], dim=1)\n bottom_right = torch.stack([bottom_right_x, bottom_right_y], dim=1)\n\n return top_left, bottom_right", "def best_coords(self):\n lat, lon = None, None\n for term in self.terms:\n # print(term)\n # print(term['weight'])\n geo = term.get(\"geo\")\n if geo:\n osm = geo['osm']\n gm = geo['gm']\n geo_data = None\n if osm:\n geo_data = osm\n elif gm:\n geo_data = gm\n if geo_data:\n g = geo_data[0]\n lat, lon = g['latitude'], g['longitude']\n break\n return lat, lon, self.region", "def get_grid_locations(self, top_left, other_pos):\n cell_x = torch.floor(((other_pos[:, 0] - top_left[:, 0]) / self.neighborhood_size) *self.grid_size)\n\n # Added this part to implementation, otherwise the pooling is going to run into an indexing error\n cell_x[cell_x == self.grid_size] -= 1\n cell_y = torch.floor(((top_left[:, 1] - other_pos[:, 1]) / self.neighborhood_size) *self.grid_size)\n cell_y[cell_y == self.grid_size] -= 1\n grid_pos = cell_x + cell_y * self.grid_size\n\n return grid_pos", "def getCityLimitsBoundingBox(city, expandBy=0.0):\n url = \"https://nominatim.openstreetmap.org/search?city={}&format=json&addressdetails=1&limit=1\".format(city)\n r = requests.get(url=url)\n bbox_coords = r.json()[0]['boundingbox']\n top = [float(bbox_coords[3]), float(bbox_coords[1])]\n right = top\n bot = [float(bbox_coords[2]), float(bbox_coords[0])]\n left = bot\n\n # enlarge bounding box in order to include the entire neighborhood of the respectve pilot \n if expandBy > 0.0:\n diff_y = top[1]-bot[1]\n top[1] = top[1]+(diff_y*expandBy)\n bot[1] = bot[1]-(diff_y*expandBy)\n diff_x = left[0]-right[0]\n right[0] = right[0]+(diff_x*expandBy)\n left[0] = left[0]-(diff_x*expandBy)\n return top, right, bot, left", "def getSearchSpaceCoords(self):", "def get_city_base(city_map = CHICAGO_NEIGHBORHOOD):\n shapes = shp.Reader(city_map).shapeRecords()\n x,y = [],[]\n for shape in shapes:\n inner_x,inner_y = list(zip(*shape.shape.points))\n x.append(inner_x)\n y.append(inner_y)\n x_flat = [item for sublist in x for item in sublist]\n y_flat = [item for sublist in y for item in sublist]\n return x_flat,y_flat", "def test_d2_get_neighborhood_small(self):\n config.NR_COLS = 3\n config.NR_ROWS = 3\n gamefield = [\n [1, 0, 0],\n [1, 0, 0],\n [0, 1, 1],\n ]\n # top left\n nh = logic.get_neighborhood(gamefield, 0, 0)\n self.assertEqual(nh, 3)\n # top right\n nh = logic.get_neighborhood(gamefield, 0, 2)\n self.assertEqual(nh, 4)\n # bottom left\n nh = logic.get_neighborhood(gamefield, 2, 0)\n self.assertEqual(nh, 4)\n # bottom right\n nh = logic.get_neighborhood(gamefield, 2, 2)\n self.assertEqual(nh, 3)\n # center\n nh = logic.get_neighborhood(gamefield, 1, 1)\n self.assertEqual(nh, 4)", "def neighbours_of_position(coords):\n row = coords[0]\n col = coords[1]\n \n #assign each of neighbours corrds\n #top left to top rigt\n top_left = (row - 1, col - 1)\n top_center = (row - 1, col)\n top_right = (row - 1, col + 1)\n \n # left to right (center)\n left = (row, col - 1)\n # the (row, col) cordinates passed into this function are situated here\n right = (row, col + 1)\n \n #bottom-left to bottom-right\n bottom_left = (row +1, col -1)\n bottom_center = (row +1, col)\n bottom_right = (row +1, col +1)\n \n return [top_left, top_center, top_right,\n left , right ,\n bottom_left, bottom_center, bottom_right]", "def get_head_and_tail(street):\r\n def is_end(location):\r\n num_adj = 0\r\n adj = get_orthogonal(location)\r\n for merchant in street:\r\n if merchant != location and merchant in adj:\r\n num_adj += 1\r\n return num_adj <= 1\r\n return [loc for loc in street if is_end(loc)]", "def determine_region(x, y, width, height):\n xs = [0, width / 3, 2 * width / 3, width]\n ys = [0, height / 3, 2 * height / 3, height]\n for i in range(3):\n for j in range(3):\n if (x >= xs[j] and x < xs[j + 1]) and (y >= ys[i] and y < ys[i + 1]):\n return i * 3 + j", "def find_obstacle_loc(self, obstacle_list):\n\n x_obst = []\n y_obst = []\n #x_obst_append = x_obst.append\n #y_obst_append = y_obst.append\n locs = []\n\n for x in obstacle_list:\n if x < self.width:\n x_obst.append(x*self.resolution + self.resolution/2)\n else:\n x_obst.append((x % self.width)*self.resolution + self.resolution/2)\n\n for y in obstacle_list:\n y_obst.append((y/self.width)*self.resolution + self.resolution/2)\n\n locs = map(lambda x: x, zip(x_obst, y_obst))\n\n return(locs)", "def locate_neighbors(grouped, row, column, width, height, reach):\n neighbors = []\n for row_val in range(2*int(reach) + 1):\n for col_val in range(2*int(reach) + 1):\n row_final = row - int(reach) + row_val\n col_final = column - int(reach) + col_val\n if col_final == column and row_final == row:\n continue\n if col_final >= width or col_final < 0:\n continue\n if row_final >= height or row_final < 0:\n continue\n row_num = (row_final * width) + col_final\n final_int = grouped[row_num][0]\n neighbors.append(final_int)\n return neighbors", "def get_top_station_csv(city):\n list_index = np.load(\"/home/ryj/renyajie/exp/NETL/data/spider_data/station_list/final_list_index.npy\",\n allow_pickle=True)\n list_remap = np.load(\"/home/ryj/renyajie/exp/NETL/data/exp_data/station_list/list_remap_{}.npy\".format(city),\n allow_pickle=True)\n list_index = dict(list_index.tolist())\n list_remap = dict(list_remap.tolist())\n\n # get longitude and latitude\n geo_map = {}\n with open(\"/home/ryj/renyajie/exp/NETL/data/spider_data/station_list/final_list_{}.csv\".format(city)) as f:\n reader = csv.reader(f)\n for line in reader:\n geo_map[int(line[0])] = (float(line[1]), float(line[2]))\n\n with open(\"/home/ryj/renyajie/exp/NETL/data/exp_data/station_list/list_{}.csv\".format(city), \"w\") as f:\n writer = csv.writer(f)\n for old_index, new_index in list_remap.items():\n if old_index in list_index[city]:\n writer.writerow([new_index, geo_map[old_index][0], geo_map[old_index][1], list_index[city][old_index]])\n pass", "def findPlacesToMove():\n movesDestinations = [];\n \n curY = curBlank[0];\n curX = curBlank[1];\n\n if(curY-1 >= 1): #UP\n movesDestinations.append((curY-1, curX));\n if(curY+1 <= n): #DOWN\n movesDestinations.append((curY+1, curX));\n if(curX-1 >= 1): #LEFT\n movesDestinations.append((curY, curX-1));\n if(curX+1 <= n): #RIGHT\n movesDestinations.append((curY, curX+1));\n \n return movesDestinations;", "def get_neighbourhood(indices, map_shape):\n if isinstance(map_shape, int):\n nx = 1\n size = map_shape\n elif len(map_shape) == 2:\n nx = map_shape[1]\n size = map_shape[0] * map_shape[1]\n else:\n print(\"Check your `map_shape` value.\")\n return\n extended = list(indices)\n for s in extended:\n susjedi = np.unique(\n np.array([s-2*nx,\n s-nx-1, s-nx, s-nx+1,\n s-2, s-1, s, s+1, s+2,\n s+nx-1, s+nx, s+nx+1,\n s+2*nx]))\n susjedi_cor = susjedi[(susjedi >= 0) & (susjedi < size)]\n extended = extended + list(susjedi_cor)\n return np.sort(np.unique(extended))", "def find_yolo_coordinates(y_top, y_bottom, x_left, x_right, width, height):\n w = (width - x_left - x_right) / width # width of bounding box\n h = (height - y_top - y_bottom) / height # height of bounding box\n x = (1 - w / 2) - x_right / width # x center of box (distance right from UL)\n y = (1 - h / 2) - y_bottom / height # y center of box (distance down from UL)\n\n return x,y,w,h", "def get_locs(pins_stats, ball_stats):\n return np.vstack((pins_stats[:, :3], np.array([ball_stats[0], ball_stats[1], R_BALL])))", "def checked_positions():\n for base_position in chain([me.shipyard], me.get_dropoffs()):\n x_shipyard = base_position.position.x\n y_shipyard = base_position.position.y\n for x in range(-search_range, search_range):\n for y in range(-search_range, search_range):\n yield hlt.Position(\n x=x_shipyard + x,\n y=y_shipyard + y)", "def get_all_roads_starting_from(network, city):\n return network[1][city][0]", "def find_nn(self, city, list):\n start_city = self.get_coordinates_from_city(city)\n return min((euclidean_distance(start_city, self.get_coordinates_from_city(rest)), rest) for rest in\n list)", "def getCitySightings(catalog,city):\n cities=catalog['cities']\n keyset=om.keySet(cities)\n selected_city=om.get(cities,city)['value']\n match=lt.newList(datastructure='ARRAY_LIST')\n max_sightings=0\n max_city=\"\"\n #Para obtener la ciudad con mas cantidad de avistamientos toca recorrer todo el arbol.\n #De esto se encarga el siguiente for-\n for c in lt.iterator(keyset):\n city_sightings=lt.size(om.get(cities, c)['value'])\n if city_sightings>max_sightings:\n max_sightings=city_sightings\n max_city=c\n \n #Añade todo los avistamientos de la ciudad ingresada a una lista.\n for sight in lt.iterator(selected_city):\n lt.addLast(match,sight)\n total=lt.size(match)\n ms.sort(match,compareDateTime)\n \n #Hacer la lista en caso de que halla mas que 6\n if total>6:\n joined=lt.subList(match,1,3)\n last=lt.subList(match,total-3,3)\n for a in lt.iterator(last):\n lt.addLast(joined, a)\n else:\n joined=lt.subList(match,1,total)\n return total, joined, max_sightings, max_city", "def findPlacements(self,start,size):\n\n possible = []\n isViableX = True\n isViableY = True\n for x in range(1-size,size):\n if ((start[0]+x,start[1]) in self.ships): # Checks for Valid Horizontal Positions\n isViableX = False\n if ((start[0],start[1]+x) in self.ships): # Checks for Valid Vertical Positions\n isViableY = False\n if x == 0 or x== size-1:\n if isViableX:\n possible.append((start[0]-size+1 if x==0 else start[0]+size-1,start[1]))\n if isViableY:\n possible.append((start[0],start[1]-size+1 if x==0 else start[1]+size-1))\n isViableX = True\n isViableY = True\n print(possible)\n return(possible)", "def calculateTopCityPopulation(self, x, y):\t\t\n\t\tiBestCityValue = 0\n\t\tpCurrent = gc.getMap().plot( x, y )\n\t\tif (pCurrent.isCity()):\n\t\t\tbestCity = pCurrent.getPlotCity()\n\t\t\tfor iPlayerLoop in range(gc.getMAX_PLAYERS()):\n\t\t\t\tapCityList = PyPlayer(iPlayerLoop).getCityList()\n\t\t\t\tfor pCity in apCityList:\n\t\t\t\t\tiTotalCityValue = pCity.getPopulation()\n\t\t\t\t\tif (iTotalCityValue > iBestCityValue and not pCity.isBarbarian()):\n\t\t\t\t\t\tbestCity = pCity\n\t\t\t\t\t\tiBestCityValue = iTotalCityValue\n\t\t\treturn bestCity\n\t\treturn -1", "def biggest_city(self):\r\n biggest = 0\r\n for code, node in self.vertices.items():\r\n if node.population > biggest:\r\n biggest = node.population\r\n city_code = node.code\r\n name = node.name\r\n return city_code, name, biggest", "def get_top_station_set(city):\n s = {}\n for file in os.listdir(exp_data_path + os.sep + 'station' + os.sep + city):\n with open(exp_data_path + os.sep + 'station' + os.sep + city + os.sep + file) as f:\n reader = csv.reader(f)\n for row in reader:\n if row[0] not in s:\n s[row[0]] = 1\n else:\n s[row[0]] = s[row[0]] + 1\n\n sort_s = dict(sorted(s.items(), key=lambda x : x[1], reverse=True))\n first = True\n res = []\n for k, v in sort_s.items():\n if first:\n top = v\n first = False\n if top - v <= 30:\n res.append(k)\n print('before', len(sort_s))\n print('after', len(res))\n\n # restore new map [old_index, new_index]\n list_remap = {}\n new_index = 0\n for index in range(0, data_length[city]):\n if str(index) in res:\n list_remap[index] = new_index\n new_index = new_index + 1\n\n # print(list_remap)\n check_path(exp_data_path + os.sep + 'station_list')\n file_name = exp_data_path + os.sep + 'station_list' + os.sep + 'list_remap_{}'.format(city) + '.npy'\n if os.path.exists(file_name):\n os.remove(file_name)\n np.save(file_name, list_remap)" ]
[ "0.6479767", "0.6087169", "0.6083894", "0.6046743", "0.60243106", "0.6016493", "0.5994365", "0.5983197", "0.5905748", "0.58899623", "0.5857768", "0.5781798", "0.5723718", "0.5706854", "0.56964326", "0.56894207", "0.5657274", "0.5609153", "0.5604276", "0.559685", "0.5595108", "0.55905044", "0.5582189", "0.55312824", "0.551872", "0.55156875", "0.5513197", "0.5499984", "0.5497", "0.5495539" ]
0.66049397
0
Find the positions for a donut shaped city
def test_find_donut_city(self): # Given game_state: CarcassonneGameState = self.create_donut_city_board() # When city: City = CityUtil.find_city( game_state=game_state, city_position=CoordinateWithSide(Coordinate(0, 0), Side.BOTTOM) ) # Then self.assertTrue(city.finished) self.assertEqual(16, len(city.city_positions)) self.assertIn(CoordinateWithSide(Coordinate(0, 0), Side.BOTTOM), city.city_positions) self.assertIn(CoordinateWithSide(Coordinate(0, 0), Side.RIGHT), city.city_positions) self.assertIn(CoordinateWithSide(Coordinate(0, 1), Side.LEFT), city.city_positions) self.assertIn(CoordinateWithSide(Coordinate(0, 1), Side.RIGHT), city.city_positions) self.assertIn(CoordinateWithSide(Coordinate(0, 2), Side.LEFT), city.city_positions) self.assertIn(CoordinateWithSide(Coordinate(0, 2), Side.BOTTOM), city.city_positions) self.assertIn(CoordinateWithSide(Coordinate(1, 0), Side.TOP), city.city_positions) self.assertIn(CoordinateWithSide(Coordinate(1, 0), Side.BOTTOM), city.city_positions) self.assertIn(CoordinateWithSide(Coordinate(1, 2), Side.TOP), city.city_positions) self.assertIn(CoordinateWithSide(Coordinate(1, 2), Side.BOTTOM), city.city_positions) self.assertIn(CoordinateWithSide(Coordinate(2, 0), Side.TOP), city.city_positions) self.assertIn(CoordinateWithSide(Coordinate(2, 0), Side.RIGHT), city.city_positions) self.assertIn(CoordinateWithSide(Coordinate(2, 1), Side.LEFT), city.city_positions) self.assertIn(CoordinateWithSide(Coordinate(2, 1), Side.RIGHT), city.city_positions) self.assertIn(CoordinateWithSide(Coordinate(2, 2), Side.LEFT), city.city_positions) self.assertIn(CoordinateWithSide(Coordinate(2, 2), Side.TOP), city.city_positions)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_city_points(city):\n for item in coordinate_list:\n if item[0] == city:\n return (item[1], item[2])", "def test_find_city(self):\n\n # Given\n game_state: CarcassonneGameState = CarcassonneGameState()\n\n city_top = base_tiles[\"city_top\"]\n city_bottom = city_top.turn(2)\n\n game_state.board = [[None for column in range(1)] for row in range(2)]\n\n game_state.board[0][0] = city_bottom\n game_state.board[1][0] = city_top\n\n # When\n city: City = CityUtil.find_city(\n game_state=game_state,\n city_position=CoordinateWithSide(Coordinate(0, 0), Side.BOTTOM)\n )\n\n # Then\n self.assertTrue(city.finished)\n self.assertEqual(2, len(city.city_positions))\n self.assertIn(CoordinateWithSide(Coordinate(0, 0), Side.BOTTOM), city.city_positions)\n self.assertIn(CoordinateWithSide(Coordinate(1, 0), Side.TOP), city.city_positions)", "def get_city_base(city_map = CHICAGO_NEIGHBORHOOD):\n shapes = shp.Reader(city_map).shapeRecords()\n x,y = [],[]\n for shape in shapes:\n inner_x,inner_y = list(zip(*shape.shape.points))\n x.append(inner_x)\n y.append(inner_y)\n x_flat = [item for sublist in x for item in sublist]\n y_flat = [item for sublist in y for item in sublist]\n return x_flat,y_flat", "def test_find_cities(self):\n\n # Given\n game_state: CarcassonneGameState = CarcassonneGameState()\n\n city_one_side_straight_road = base_tiles[\"city_top_straight_road\"].turn(3)\n city_with_road = inns_and_cathedrals_tiles[\"ic_15\"].turn(3)\n\n game_state.board = [[None for column in range(2)] for row in range(1)]\n\n game_state.board[0][0] = city_with_road\n game_state.board[0][1] = city_one_side_straight_road\n\n # When\n cities: [City] = CityUtil.find_cities(\n game_state=game_state,\n coordinate=Coordinate(0, 0)\n )\n\n # Then\n self.assertEqual(1, len(cities))\n self.assertEqual(2, len(cities[0].city_positions))\n self.assertTrue(cities[0].finished)", "def getSearchSpaceCoords(self):", "def get_coordinates_for_city(city, state=None):\n search_str = ', '.join([city, state]) if state else city\n db_coords = get_coordinates_from_db(search_str)\n if db_coords:\n return (search_str, db_coords)\n else:\n page_title, coords = get_coordinates_from_wikipedia(search_str)\n add_coordinates_to_db(coords, search_str)\n return (page_title, coords)", "def obs_ijpos(gridfile,lons,lats,coor):\n\n gfh= netCDF4.Dataset(gridfile)\n cartesian=0\n if (coor=='r'):\n try:\n \n latr=gfh.variables['lat_rho'][:,:]\n lonr=gfh.variables['lon_rho'][:,:]\n except:\n latr=gfh.variables['latitude'][:,:]\n lonr=gfh.variables['longitude'][:,:]\n \n\n try:\n xr=gfh.variables['xi_rho'][:]\n yr=gfh.variables['eta_rho'][:]\n except:\n try:\n xr=gfh.variables['x_rho'][:]\n yr=gfh.variables['y_rho'][:]\n except:\n print('Neither xi_rho/eta_rho or x_rho/y_rho on file.')\n print('This might slow down the calculations')\n\n\n elif (coor=='u'):\n latr=gfh.variables['lat_u'][:,:]\n lonr=gfh.variables['lon_u'][:,:]\n try:\n xr=gfh.variables['xi_u'][:]\n yr=gfh.variables['eta_u'][:]\n except:\n xr=gfh.variables['x_u'][:]\n yr=gfh.variables['y_u'][:]\n elif (coor=='v'):\n latr=gfh.variables['lat_v'][:,:]\n lonr=gfh.variables['lon_v'][:,:]\n try:\n xr=gfh.variables['xi_v'][:]\n yr=gfh.variables['eta_v'][:]\n except:\n xr=gfh.variables['x_v'][:]\n yr=gfh.variables['y_v'][:]\n\n IN = point_in_polygon(lonr, latr, lons, lats)\n ind=np.where(IN)[0]\n \n if lats.size >1: \n lons=lons[ind]; lats=lats[ind]\n # If there's no lons, lats left at this stage, return oipos, ojpos with -999 everywhere\n if not len(lons):\n return np.ones_like(IN)*-999, np.ones_like(IN)*-999\n \n try:\n try:\n mapstr=str(gfh.variables['h'].getncattr('mapping'))\n except:\n try:\n mapstr=str(gfh.variables['h'].getncattr('grid_mapping'))\n except:\n pass\n try:\n projstring=(gfh.variables[mapstr]).getncattr('proj4')\n except:\n try:\n projstring=(gfh.variables[mapstr]).getncattr('proj4string')\n except:\n pass\n try:\n projstring=(gfh.variables['grid_mapping']).getncattr('proj4')\n except:\n try:\n projstring=(gfh.variables['grid_mapping']).getncattr('proj4string')\n except:\n pass\n\n gridproj=proj.Proj(str(projstring))\n hasproj=1\n except:\n hasproj=0\n\n # Check if lat, lon spacing is uniform\n dx1=np.abs(lonr[0,1]-lonr[0,0])\n dx2=np.abs(lonr[0,-1]-lonr[0,-2])\n n=int(np.round(lonr.shape[1]/2))\n dx3=np.abs(lonr[0,n]-lonr[0,n-1])\n\n dy1=np.abs(latr[1,0]-latr[0,0])\n dy2=np.abs(latr[-1,0]-latr[-2,0])\n n=int(np.round(latr.shape[0]/2))\n dy3=np.abs(latr[n,0]-latr[n-1,0])\n\n if ( (dx1 == dx2) & (dx1==dx3) & (dx2==dx3) & (dy1 == dy2) & (dy1==dy3) & (dy2==dy3) ):\n cartesian=1\n gridproj=proj.Proj(\"+proj=latlong +datum=WGS84\")\n \n\n \n if hasproj:\n dx=xr[1]-xr[0]\n dy=yr[1]-yr[0]\n [x,y]=gridproj(lons,lats)\n ipos=(x-xr[0])/dx\n jpos=(y-yr[0])/dy\n\n elif cartesian:\n [x1,y1]=gridproj(lonr[0,0],latr[0,0])\n [x2,y2]=gridproj(lonr[0,1],latr[0,1])\n dx=x2-x1\n [x2,y2]=gridproj(lonr[1,0],latr[1,0])\n dy=y2-y1\n [x,y]=gridproj(lons,lats)\n [x0,y0]=gridproj(lonr[0,0],latr[0,0])\n\n ipos=(x-x0)/dx\n jpos=(y-y0)/dy\n\n else:\n x=np.linspace(0,lonr.shape[1]-1,lonr.shape[1])\n y=np.linspace(0,lonr.shape[0]-1,lonr.shape[0])\n xi=np.zeros_like(lonr); yi=np.zeros([lonr.shape[1],lonr.shape[0]])\n xi[:,:]=x; yi[:,:]=y; yi=np.swapaxes(yi,1,0)\n zi=scipy.interpolate.griddata((lonr.flatten(),latr.flatten()),xi.flatten(),(lons,lats))\n ipos=zi\n zi=scipy.interpolate.griddata((lonr.flatten(),latr.flatten()),yi.flatten(),(lons,lats))\n jpos=zi\n \n if 'ind' in locals():\n oipos=np.ones(IN.shape)*-999.; ojpos=np.ones(IN.shape)*-999.\n oipos[ind]=ipos; ojpos[ind]=jpos\n else:\n oipos=ipos\n ojpos=jpos\n if not IN:\n oipos = np.array([-999.])\n ojpos = np.array([-999.])\n gfh.close()\n return oipos,ojpos", "def find_coordinates(self):\n\n raise NotImplementedError", "def find_coordinates(self):\n\n raise NotImplementedError", "def moore_neighbourhood(self, grid_position: tuple, radius: int) -> list:\n result = []\n u = [grid_position[0] - radius, grid_position[1] - radius]\n for i in range(2 * radius + 1):\n for j in range(2 * radius + 1):\n # This does not make much sense, since u is a list and i and j are integers\n result.append([u + i, u + j])\n return result", "def generate_all_locations(grid, shape):", "def extract_locations(self):\n default_pos_columns = common_cfg.coord_col_names\n if set(default_pos_columns).issubset(set(self._raw_data.columns)):\n print('Location data found')\n # check and drop units outside provided city boundary\n geometry = [shapely.geometry.Point(xy) for xy in zip(\n self._raw_data[default_pos_columns[0]], # Long\n self._raw_data[default_pos_columns[1]])] # Lat\n b_within_boundary = np.array(list(map(\n lambda p: p.within(self.model_city.convhull), geometry)))\n\n if not all(b_within_boundary):\n print('%s -- dropping %i units outside city.' %\n (self.servicetype,\n sum(np.bitwise_not(b_within_boundary))))\n self._raw_data = self._raw_data.iloc[\n b_within_boundary, :].reset_index()\n\n # store geolocations as geopy Point\n locations = [geopy.Point(yx) for yx in zip(\n self._raw_data[default_pos_columns[1]], # Lat\n self._raw_data[default_pos_columns[0]])] # Long\n\n propert_data = self._raw_data.drop(default_pos_columns, axis=1)\n\n else:\n raise NotImplementedError('Locations not found - not implemented!')\n\n return propert_data, locations", "def FindDHopCities(self, X, d):\n # G = nx.Graph()\n # G.add_nodes_from(self.nodes)\n # G.add_edges_from(self.edges)\n\n # airports_id_in_city = self.airports.loc[self.airports['city'] == X, 'airport_id'].to_list()\n\n # cities_h_hop = set()\n # for airport in airports_id_in_city:\n # airports_h_hop = nx.descendants_at_distance(G, airport, h)\n # for airport_h_hop in airports_h_hop:\n # cities_h_hop.add(self.GetCityFromAirportId(airport_h_hop))\n\n # return cities_h_hop\n\n graph_adj = self.graph\n\n airports_id_in_city = self.airports.loc[self.airports['city'] == X, 'airport_id'].to_list()\n cities_d_hop = set()\n for airport in airports_id_in_city:\n airports_d_hop = set()\n current_distance = 0\n queue = {airport}\n visited = {airport}\n \n # BFS\n while queue:\n if current_distance == d:\n airports_d_hop.update(queue)\n\n current_distance += 1\n\n current_path = set()\n for poped_node in queue:\n for child in graph_adj[poped_node]:\n if child not in visited:\n visited.add(child)\n current_path.add(child)\n\n queue = current_path\n \n for airport_d_hop in airports_d_hop:\n cities_d_hop.add(self.GetCityFromAirportId(airport_d_hop))\n\n return cities_d_hop", "def test_find_meeples_in_donut_city(self):\n\n # Given\n game_state: CarcassonneGameState = self.create_donut_city_board()\n game_state.placed_meeples = [[], [], []]\n game_state.placed_meeples[0].append(MeeplePosition(meeple_type=MeepleType.NORMAL, coordinate_with_side=CoordinateWithSide(Coordinate(2, 1), Side.RIGHT)))\n game_state.placed_meeples[0].append(MeeplePosition(meeple_type=MeepleType.NORMAL, coordinate_with_side=CoordinateWithSide(Coordinate(0, 1), Side.LEFT)))\n game_state.placed_meeples[1].append(MeeplePosition(meeple_type=MeepleType.BIG, coordinate_with_side=CoordinateWithSide(Coordinate(1, 2), Side.TOP)))\n game_state.players = 3\n\n # When\n city: City = CityUtil.find_city(\n game_state=game_state,\n city_position=CoordinateWithSide(Coordinate(0, 0), Side.BOTTOM)\n )\n\n meeples: [[MeeplePosition]] = CityUtil.find_meeples(game_state, city)\n\n # Then\n self.assertEqual(3, len(meeples))\n self.assertEqual(2, len(meeples[0]))\n self.assertEqual(1, len(meeples[1]))\n self.assertEqual(0, len(meeples[2]))\n self.assertIn(MeeplePosition(MeepleType.NORMAL, CoordinateWithSide(Coordinate(2, 1), Side.RIGHT)), meeples[0])\n self.assertIn(MeeplePosition(MeepleType.NORMAL, CoordinateWithSide(Coordinate(0, 1), Side.LEFT)), meeples[0])\n self.assertIn(MeeplePosition(MeepleType.BIG, CoordinateWithSide(Coordinate(1, 2), Side.TOP)), meeples[1])", "def calculateFoodPositions(self, state):\n foodPos = [9999999] * state.getNumFood()\n if(state.getNumFood() > 0):\n # minDistance = 900000\n # pacmanPosition = state.getPacmanPosition()\n counter = 0\n for i in range(state.data.layout.width):\n for j in range(state.data.layout.height):\n if state.hasFood(i, j):\n foodPos[counter] = (i,j)\n counter += 1\n # distance = util.manhattanDistance(pacmanPosition, foodPosition)\n # if distance < minDistance:\n # minDistance = distance\n return foodPos\n\n else:\n return None", "def get_neighbourhood(indices, map_shape):\n if isinstance(map_shape, int):\n nx = 1\n size = map_shape\n elif len(map_shape) == 2:\n nx = map_shape[1]\n size = map_shape[0] * map_shape[1]\n else:\n print(\"Check your `map_shape` value.\")\n return\n extended = list(indices)\n for s in extended:\n susjedi = np.unique(\n np.array([s-2*nx,\n s-nx-1, s-nx, s-nx+1,\n s-2, s-1, s, s+1, s+2,\n s+nx-1, s+nx, s+nx+1,\n s+2*nx]))\n susjedi_cor = susjedi[(susjedi >= 0) & (susjedi < size)]\n extended = extended + list(susjedi_cor)\n return np.sort(np.unique(extended))", "def fermionic_cells(self):\n cells = self.cells()\n cells_and_circles = self.all_cells()\n circles = [x for x in cells_and_circles if x not in cells]\n coords = [(i, jprime)\n for iprime, jprime in circles\n for i, j in circles\n if iprime > i\n ]\n coords.sort()\n return coords", "def find_obstacle_loc(self, obstacle_list):\n\n x_obst = []\n y_obst = []\n #x_obst_append = x_obst.append\n #y_obst_append = y_obst.append\n locs = []\n\n for x in obstacle_list:\n if x < self.width:\n x_obst.append(x*self.resolution + self.resolution/2)\n else:\n x_obst.append((x % self.width)*self.resolution + self.resolution/2)\n\n for y in obstacle_list:\n y_obst.append((y/self.width)*self.resolution + self.resolution/2)\n\n locs = map(lambda x: x, zip(x_obst, y_obst))\n\n return(locs)", "def neighbours_of_position(coords):\n row = coords[0]\n col = coords[1]\n \n #assign each of neighbours corrds\n #top left to top rigt\n top_left = (row - 1, col - 1)\n top_center = (row - 1, col)\n top_right = (row - 1, col + 1)\n \n # left to right (center)\n left = (row, col - 1)\n # the (row, col) cordinates passed into this function are situated here\n right = (row, col + 1)\n \n #bottom-left to bottom-right\n bottom_left = (row +1, col -1)\n bottom_center = (row +1, col)\n bottom_right = (row +1, col +1)\n \n return [top_left, top_center, top_right,\n left , right ,\n bottom_left, bottom_center, bottom_right]", "def spot_coords(self,spot):\n if spot == '1':\n return (330 - 60 ,335 - 15)\n if spot == '2':\n return (419 - 60, 335 - 15)\n if spot == '3':\n return (591 - 60, 159 - 15)\n if spot == '4':\n return (588 - 60, 248 - 15)", "def coordinates(self):", "def research_pos(self, map_list, character): \n list_pos = []\n for y in range(15): \n for x, c in enumerate(map_list[y]):\n if character in c and c == character:\n list_pos.append((x*50, y*50)) \n return list_pos", "def determine_animal_pos(self, plot, latitude, longitude):\r\n x = convert_fraction_lat(\r\n\r\n str(return_values(plot, latitude)\r\n )\r\n )[0] * self.space.x_max\r\n\r\n y = convert_fraction_long(\r\n str(return_values(plot, longitude)\r\n )\r\n )[0] * self.space.y_max\r\n pos = (x, y)\r\n return pos", "def get_coordinates_from_city(self, city):\n return self.cities_dict.get(city)", "def best_coords(self):\n lat, lon = None, None\n for term in self.terms:\n # print(term)\n # print(term['weight'])\n geo = term.get(\"geo\")\n if geo:\n osm = geo['osm']\n gm = geo['gm']\n geo_data = None\n if osm:\n geo_data = osm\n elif gm:\n geo_data = gm\n if geo_data:\n g = geo_data[0]\n lat, lon = g['latitude'], g['longitude']\n break\n return lat, lon, self.region", "def coordinates(self):\n ships_coors = []\n if self._dir in (Direction.UP, Direction.DOWN):\n for val in range(self._len):\n new_y = self._y_pos + val\n ships_coors.append((self._x_pos, new_y))\n elif self._dir in (Direction.LEFT, Direction.RIGHT):\n for val in range(self._len):\n new_x = self._x_pos + val\n ships_coors.append((new_x, self._y_pos))\n return ships_coors", "def computePosition(self, state):\n d = 0\n if state[5] == \"East\":\n d = 0\n elif state[5] == \"West\":\n d = 1\n elif state[5] == \"North\":\n d = 2\n else:\n d = 3\n return state[0]*64+state[1]*32+state[2]*16+state[3]*8+state[4]*4+d", "def coord (i, j):\r\n return j, i", "def get_near(self,map):\n near_cells = []\n for i in range(self.x-1, self.x+2):\n for j in range(self.y-1, self.y+2):\n if(i>=0 and i<map.size and j>=0 and j<map.size): near_cells.append(map.search(i,j))\n return near_cells", "def __get_position(self, value, state):\n coords = np.argwhere(state == value).flatten()\n return coords" ]
[ "0.6695276", "0.6203773", "0.6144273", "0.6093429", "0.60021555", "0.58367753", "0.5835113", "0.5829337", "0.5829337", "0.58179224", "0.5796318", "0.57576895", "0.5756332", "0.57547903", "0.57539165", "0.5744328", "0.5703674", "0.5703478", "0.56935674", "0.5677695", "0.5676533", "0.5673108", "0.5663495", "0.5632375", "0.56093645", "0.55878323", "0.5581149", "0.55717444", "0.5555329", "0.5545894" ]
0.6870112
0
Find meeple positions for a donut shaped city
def test_find_meeples_in_donut_city(self): # Given game_state: CarcassonneGameState = self.create_donut_city_board() game_state.placed_meeples = [[], [], []] game_state.placed_meeples[0].append(MeeplePosition(meeple_type=MeepleType.NORMAL, coordinate_with_side=CoordinateWithSide(Coordinate(2, 1), Side.RIGHT))) game_state.placed_meeples[0].append(MeeplePosition(meeple_type=MeepleType.NORMAL, coordinate_with_side=CoordinateWithSide(Coordinate(0, 1), Side.LEFT))) game_state.placed_meeples[1].append(MeeplePosition(meeple_type=MeepleType.BIG, coordinate_with_side=CoordinateWithSide(Coordinate(1, 2), Side.TOP))) game_state.players = 3 # When city: City = CityUtil.find_city( game_state=game_state, city_position=CoordinateWithSide(Coordinate(0, 0), Side.BOTTOM) ) meeples: [[MeeplePosition]] = CityUtil.find_meeples(game_state, city) # Then self.assertEqual(3, len(meeples)) self.assertEqual(2, len(meeples[0])) self.assertEqual(1, len(meeples[1])) self.assertEqual(0, len(meeples[2])) self.assertIn(MeeplePosition(MeepleType.NORMAL, CoordinateWithSide(Coordinate(2, 1), Side.RIGHT)), meeples[0]) self.assertIn(MeeplePosition(MeepleType.NORMAL, CoordinateWithSide(Coordinate(0, 1), Side.LEFT)), meeples[0]) self.assertIn(MeeplePosition(MeepleType.BIG, CoordinateWithSide(Coordinate(1, 2), Side.TOP)), meeples[1])
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_find_donut_city(self):\n\n # Given\n game_state: CarcassonneGameState = self.create_donut_city_board()\n\n # When\n city: City = CityUtil.find_city(\n game_state=game_state,\n city_position=CoordinateWithSide(Coordinate(0, 0), Side.BOTTOM)\n )\n\n # Then\n self.assertTrue(city.finished)\n self.assertEqual(16, len(city.city_positions))\n self.assertIn(CoordinateWithSide(Coordinate(0, 0), Side.BOTTOM), city.city_positions)\n self.assertIn(CoordinateWithSide(Coordinate(0, 0), Side.RIGHT), city.city_positions)\n self.assertIn(CoordinateWithSide(Coordinate(0, 1), Side.LEFT), city.city_positions)\n self.assertIn(CoordinateWithSide(Coordinate(0, 1), Side.RIGHT), city.city_positions)\n self.assertIn(CoordinateWithSide(Coordinate(0, 2), Side.LEFT), city.city_positions)\n self.assertIn(CoordinateWithSide(Coordinate(0, 2), Side.BOTTOM), city.city_positions)\n self.assertIn(CoordinateWithSide(Coordinate(1, 0), Side.TOP), city.city_positions)\n self.assertIn(CoordinateWithSide(Coordinate(1, 0), Side.BOTTOM), city.city_positions)\n self.assertIn(CoordinateWithSide(Coordinate(1, 2), Side.TOP), city.city_positions)\n self.assertIn(CoordinateWithSide(Coordinate(1, 2), Side.BOTTOM), city.city_positions)\n self.assertIn(CoordinateWithSide(Coordinate(2, 0), Side.TOP), city.city_positions)\n self.assertIn(CoordinateWithSide(Coordinate(2, 0), Side.RIGHT), city.city_positions)\n self.assertIn(CoordinateWithSide(Coordinate(2, 1), Side.LEFT), city.city_positions)\n self.assertIn(CoordinateWithSide(Coordinate(2, 1), Side.RIGHT), city.city_positions)\n self.assertIn(CoordinateWithSide(Coordinate(2, 2), Side.LEFT), city.city_positions)\n self.assertIn(CoordinateWithSide(Coordinate(2, 2), Side.TOP), city.city_positions)", "def get_city_points(city):\n for item in coordinate_list:\n if item[0] == city:\n return (item[1], item[2])", "def fermionic_cells(self):\n cells = self.cells()\n cells_and_circles = self.all_cells()\n circles = [x for x in cells_and_circles if x not in cells]\n coords = [(i, jprime)\n for iprime, jprime in circles\n for i, j in circles\n if iprime > i\n ]\n coords.sort()\n return coords", "def calculateFoodPositions(self, state):\n foodPos = [9999999] * state.getNumFood()\n if(state.getNumFood() > 0):\n # minDistance = 900000\n # pacmanPosition = state.getPacmanPosition()\n counter = 0\n for i in range(state.data.layout.width):\n for j in range(state.data.layout.height):\n if state.hasFood(i, j):\n foodPos[counter] = (i,j)\n counter += 1\n # distance = util.manhattanDistance(pacmanPosition, foodPosition)\n # if distance < minDistance:\n # minDistance = distance\n return foodPos\n\n else:\n return None", "def get_near(self,map):\n near_cells = []\n for i in range(self.x-1, self.x+2):\n for j in range(self.y-1, self.y+2):\n if(i>=0 and i<map.size and j>=0 and j<map.size): near_cells.append(map.search(i,j))\n return near_cells", "def test_find_city(self):\n\n # Given\n game_state: CarcassonneGameState = CarcassonneGameState()\n\n city_top = base_tiles[\"city_top\"]\n city_bottom = city_top.turn(2)\n\n game_state.board = [[None for column in range(1)] for row in range(2)]\n\n game_state.board[0][0] = city_bottom\n game_state.board[1][0] = city_top\n\n # When\n city: City = CityUtil.find_city(\n game_state=game_state,\n city_position=CoordinateWithSide(Coordinate(0, 0), Side.BOTTOM)\n )\n\n # Then\n self.assertTrue(city.finished)\n self.assertEqual(2, len(city.city_positions))\n self.assertIn(CoordinateWithSide(Coordinate(0, 0), Side.BOTTOM), city.city_positions)\n self.assertIn(CoordinateWithSide(Coordinate(1, 0), Side.TOP), city.city_positions)", "def determine_animal_pos(self, plot, latitude, longitude):\r\n x = convert_fraction_lat(\r\n\r\n str(return_values(plot, latitude)\r\n )\r\n )[0] * self.space.x_max\r\n\r\n y = convert_fraction_long(\r\n str(return_values(plot, longitude)\r\n )\r\n )[0] * self.space.y_max\r\n pos = (x, y)\r\n return pos", "def _neuron_locations(self, m, n):\n #Nested iterations over both dimensions\n #to generate all 2-D locations in the map\n for i in range(m):\n for j in range(n):\n yield np.array([i, j])", "def _neuron_locations(self, m, n):\n #Nested iterations over both dimensions\n #to generate all 2-D locations in the map\n for i in range(m):\n for j in range(n):\n yield np.array([i, j])", "def get_city_base(city_map = CHICAGO_NEIGHBORHOOD):\n shapes = shp.Reader(city_map).shapeRecords()\n x,y = [],[]\n for shape in shapes:\n inner_x,inner_y = list(zip(*shape.shape.points))\n x.append(inner_x)\n y.append(inner_y)\n x_flat = [item for sublist in x for item in sublist]\n y_flat = [item for sublist in y for item in sublist]\n return x_flat,y_flat", "def moore_neighbourhood(self, grid_position: tuple, radius: int) -> list:\n result = []\n u = [grid_position[0] - radius, grid_position[1] - radius]\n for i in range(2 * radius + 1):\n for j in range(2 * radius + 1):\n # This does not make much sense, since u is a list and i and j are integers\n result.append([u + i, u + j])\n return result", "def generate_all_locations(grid, shape):", "def get_atom_pos(self, data):\n\n\n if 'neighborhood_size' in self.args:\n neighborhood_size = self.args['neighborhood_size']\n else:\n neighborhood_size = 30\n if 'threshold' in self.args:\n threshold = self.args['threshold']\n else:\n threshold = 30\n\n #Use filters to calculate peaks\n data_max = filters.maximum_filter(data, neighborhood_size)\n maxima = (data == data_max)\n data_min = filters.minimum_filter(data, neighborhood_size)\n diff = ((data_max - data_min) > threshold)\n maxima[diff == 0] = 0\n\n labeled, num_objects = ndimage.label(maxima)\n slices = ndimage.find_objects(labeled)\n x, y = [], []\n for dy,dx in slices:\n x_center = (dx.start + dx.stop - 1)/2\n x.append(x_center)\n y_center = (dy.start + dy.stop - 1)/2\n y.append(y_center)\n\n\n posiitons=[x,y]\n\n return positions", "def calcPosition (lat, lon):\n nauticalMilePerLat = 60.00721\n nauticalMilePerLongitude = 60.10793\n rad = math.pi / 180.0\n milesPerNauticalMile = 1.15078\n \n y = lat * nauticalMilePerLat\n x = math.cos(lat * rad) * lon * nauticalMilePerLongitude\n\n return x * milesPerNauticalMile * 1609.344, y * milesPerNauticalMile * 1609.344", "def beam_positions(closepack=False):\n \n x_pos, y_pos = [], []\n\n x=0\n for j in range(0,6,1):\n x += 0.1\n y=0\n for k in range(0,6,2):\n y += 0.2\n x_pos.append(x+(0.05 if closepack else 0))\n y_pos.append(y)\n y += 0.2\n x_pos.append(x)\n y_pos.append(y)\n\n return x_pos, y_pos", "def find(Map, PosI, PosF):\n \n # Pour les tests, cf. Pathfinding et Pathfinding2 \n \n InitialPosI = PosI\n InitialPosF = PosF\n Chemin = []\n \n Hvalue = np.zeros((np.shape(Map))) #Distance\n Gvalue = np.zeros((np.shape(Map))) #Movement Cost\n Fvalue = np.zeros((np.shape(Map))) #G+H \n Gvalue[:] = np.nan #initialiser Gvalue à une matrice NaN\n \n OpenList = [(InitialPosI,'N')]\n CloseList = []\n \n # Initialisation de Hvalue\n for i in range(np.shape(Hvalue)[0]):\n for j in range(np.shape(Hvalue)[1]):\n if Map[i,j] !=1:\n Hvalue[i,j] = abs(i-PosF[0]) + abs(j-PosF[1])\n else:\n Hvalue[i,j] = np.nan\n\n### Round 1 (+initialisations)\n \n CloseList.append(tuple(PosI))\n \n if PosI[0]-1>=0 and Map[PosI[0]-1,PosI[1]] != 1 and ((PosI[0]-1,PosI[1]) not in OpenList) and ((PosI[0]-1,PosI[1]) not in CloseList): #Check vertical haut\n OpenList.append(((PosI[0]-1,PosI[1]),'D')) #D : fleche vers le bas..\n if PosI[0]+1<=np.shape(Map)[0]-1 and Map[PosI[0]+1,PosI[1]] != 1 and ((PosI[0]+1,PosI[1]) not in OpenList) and ((PosI[0]+1,PosI[1]) not in CloseList): #Check vertical bas\n OpenList.append(((PosI[0]+1,PosI[1]),'U')) \n if PosI[1]-1>=0 and Map[PosI[0],PosI[1]-1] != 1 and ((PosI[0],PosI[1]-1) not in OpenList) and ((PosI[0],PosI[1]-1) not in CloseList): #Check horiz gauche\n OpenList.append(((PosI[0],PosI[1]-1),'R'))\n if PosI[1]+1<=np.shape(Map)[1]-1 and Map[PosI[0],PosI[1]+1] != 1 and ((PosI[0],PosI[1]+1) not in OpenList) and ((PosI[0],PosI[1]+1) not in CloseList): #Check horiz droit\n OpenList.append(((PosI[0],PosI[1]+1),'L'))\n \n \n for OV in OpenList: #OV pour OpenValue \n Gvalue[OV[0][0],OV[0][1]] = 10\n \n Fvalue = np.copy(Gvalue + Hvalue)\n for CV in CloseList: #CV pour ClosedValue\n Fvalue[CV[0],CV[1]] = np.nan\n \n\n#### Round NEXT \n ###Vers le min de Fvalue:\n while PosF not in CloseList and PosI != PosF:\n \n if np.all(np.isnan(Fvalue)): #Check si F est égale à une matrice Full NaN\n# print('Pas de chemin')\n return(False) # soit return False, soit return la position init, donc bon..\n \n Index = np.argwhere(Fvalue == np.nanmin(Fvalue))\n PosI = Index.tolist()[0]\n \n CloseList.append(tuple(PosI))\n if PosI[0]-1>=0 and Map[PosI[0]-1,PosI[1]] != 1 and ((PosI[0]-1,PosI[1]) not in OpenList) and ((PosI[0]-1,PosI[1]) not in CloseList): #Check vertical haut\n OpenList.append(((PosI[0]-1,PosI[1]),'D')) #DOWN (fleche vers le bas..)\n if PosI[0]+1<=np.shape(Map)[0]-1 and Map[PosI[0]+1,PosI[1]] != 1 and ((PosI[0]+1,PosI[1]) not in OpenList) and ((PosI[0]+1,PosI[1]) not in CloseList): #Check vertical bas\n OpenList.append(((PosI[0]+1,PosI[1]),'U')) #Up\n if PosI[1]-1>=0 and Map[PosI[0],PosI[1]-1] != 1 and ((PosI[0],PosI[1]-1) not in OpenList) and ((PosI[0],PosI[1]-1) not in CloseList): #Check horiz gauche\n OpenList.append(((PosI[0],PosI[1]-1),'R')) #Right\n if PosI[1]+1<=np.shape(Map)[1]-1 and Map[PosI[0],PosI[1]+1] != 1 and ((PosI[0],PosI[1]+1) not in OpenList) and ((PosI[0],PosI[1]+1) not in CloseList): #Check horiz droit\n OpenList.append(((PosI[0],PosI[1]+1),'L')) #Left\n \n for OV in OpenList:\n Gvalue[OV[0][0],OV[0][1]] = 10\n \n Fvalue = np.copy(Gvalue + Hvalue)\n for CV in CloseList:\n Fvalue[CV[0],CV[1]] = np.nan\n \n\n \n############## TRACING BACK \n PosF = InitialPosF\n\n while InitialPosI not in Chemin:\n \n for Trace in OpenList:\n if Trace[0] == PosF:\n Chemin.append(PosF)\n if Trace[1] == 'U':\n PosF = (PosF[0]-1,PosF[1]) #Go up\n elif Trace[1] == 'D':\n PosF = (PosF[0]+1,PosF[1]) #Go down\n elif Trace[1] == 'L':\n PosF = (PosF[0],PosF[1]-1) #Go left\n elif Trace[1] == 'R':\n PosF = (PosF[0],PosF[1]+1) #Go right\n# else:\n# print(Chemin)\n Chemin.reverse()\n return(Chemin)", "def moles(board):\n return (pos for pos in range(1, length+1) if at(board, pos))", "def obs_ijpos(gridfile,lons,lats,coor):\n\n gfh= netCDF4.Dataset(gridfile)\n cartesian=0\n if (coor=='r'):\n try:\n \n latr=gfh.variables['lat_rho'][:,:]\n lonr=gfh.variables['lon_rho'][:,:]\n except:\n latr=gfh.variables['latitude'][:,:]\n lonr=gfh.variables['longitude'][:,:]\n \n\n try:\n xr=gfh.variables['xi_rho'][:]\n yr=gfh.variables['eta_rho'][:]\n except:\n try:\n xr=gfh.variables['x_rho'][:]\n yr=gfh.variables['y_rho'][:]\n except:\n print('Neither xi_rho/eta_rho or x_rho/y_rho on file.')\n print('This might slow down the calculations')\n\n\n elif (coor=='u'):\n latr=gfh.variables['lat_u'][:,:]\n lonr=gfh.variables['lon_u'][:,:]\n try:\n xr=gfh.variables['xi_u'][:]\n yr=gfh.variables['eta_u'][:]\n except:\n xr=gfh.variables['x_u'][:]\n yr=gfh.variables['y_u'][:]\n elif (coor=='v'):\n latr=gfh.variables['lat_v'][:,:]\n lonr=gfh.variables['lon_v'][:,:]\n try:\n xr=gfh.variables['xi_v'][:]\n yr=gfh.variables['eta_v'][:]\n except:\n xr=gfh.variables['x_v'][:]\n yr=gfh.variables['y_v'][:]\n\n IN = point_in_polygon(lonr, latr, lons, lats)\n ind=np.where(IN)[0]\n \n if lats.size >1: \n lons=lons[ind]; lats=lats[ind]\n # If there's no lons, lats left at this stage, return oipos, ojpos with -999 everywhere\n if not len(lons):\n return np.ones_like(IN)*-999, np.ones_like(IN)*-999\n \n try:\n try:\n mapstr=str(gfh.variables['h'].getncattr('mapping'))\n except:\n try:\n mapstr=str(gfh.variables['h'].getncattr('grid_mapping'))\n except:\n pass\n try:\n projstring=(gfh.variables[mapstr]).getncattr('proj4')\n except:\n try:\n projstring=(gfh.variables[mapstr]).getncattr('proj4string')\n except:\n pass\n try:\n projstring=(gfh.variables['grid_mapping']).getncattr('proj4')\n except:\n try:\n projstring=(gfh.variables['grid_mapping']).getncattr('proj4string')\n except:\n pass\n\n gridproj=proj.Proj(str(projstring))\n hasproj=1\n except:\n hasproj=0\n\n # Check if lat, lon spacing is uniform\n dx1=np.abs(lonr[0,1]-lonr[0,0])\n dx2=np.abs(lonr[0,-1]-lonr[0,-2])\n n=int(np.round(lonr.shape[1]/2))\n dx3=np.abs(lonr[0,n]-lonr[0,n-1])\n\n dy1=np.abs(latr[1,0]-latr[0,0])\n dy2=np.abs(latr[-1,0]-latr[-2,0])\n n=int(np.round(latr.shape[0]/2))\n dy3=np.abs(latr[n,0]-latr[n-1,0])\n\n if ( (dx1 == dx2) & (dx1==dx3) & (dx2==dx3) & (dy1 == dy2) & (dy1==dy3) & (dy2==dy3) ):\n cartesian=1\n gridproj=proj.Proj(\"+proj=latlong +datum=WGS84\")\n \n\n \n if hasproj:\n dx=xr[1]-xr[0]\n dy=yr[1]-yr[0]\n [x,y]=gridproj(lons,lats)\n ipos=(x-xr[0])/dx\n jpos=(y-yr[0])/dy\n\n elif cartesian:\n [x1,y1]=gridproj(lonr[0,0],latr[0,0])\n [x2,y2]=gridproj(lonr[0,1],latr[0,1])\n dx=x2-x1\n [x2,y2]=gridproj(lonr[1,0],latr[1,0])\n dy=y2-y1\n [x,y]=gridproj(lons,lats)\n [x0,y0]=gridproj(lonr[0,0],latr[0,0])\n\n ipos=(x-x0)/dx\n jpos=(y-y0)/dy\n\n else:\n x=np.linspace(0,lonr.shape[1]-1,lonr.shape[1])\n y=np.linspace(0,lonr.shape[0]-1,lonr.shape[0])\n xi=np.zeros_like(lonr); yi=np.zeros([lonr.shape[1],lonr.shape[0]])\n xi[:,:]=x; yi[:,:]=y; yi=np.swapaxes(yi,1,0)\n zi=scipy.interpolate.griddata((lonr.flatten(),latr.flatten()),xi.flatten(),(lons,lats))\n ipos=zi\n zi=scipy.interpolate.griddata((lonr.flatten(),latr.flatten()),yi.flatten(),(lons,lats))\n jpos=zi\n \n if 'ind' in locals():\n oipos=np.ones(IN.shape)*-999.; ojpos=np.ones(IN.shape)*-999.\n oipos[ind]=ipos; ojpos[ind]=jpos\n else:\n oipos=ipos\n ojpos=jpos\n if not IN:\n oipos = np.array([-999.])\n ojpos = np.array([-999.])\n gfh.close()\n return oipos,ojpos", "def getSearchSpaceCoords(self):", "def find_center(garden):\n\n # Find center: j is 'row', i is 'col'\n # Initialize j and i, rows and cols\n j, i = -1, -1\n num_rows = len(garden)\n num_cols = len(garden[0])\n\n # This section should be cleaned up before pushing\n if num_rows % 2 != 0:\n j = num_rows // 2\n else:\n j1, j2 = num_rows // 2, num_rows // 2 - 1\n\n if j != -1:\n if num_cols % 2 != 0:\n i = num_cols // 2\n else:\n # Find the most carrots near the center of the row j\n i = garden[j].index(max(garden[j][num_cols//2], garden[j][num_cols//2]-1))\n\n else:\n if num_cols % 2 != 0:\n i1 = garden[j1][num_cols//2]\n i2 = garden[j2][num_cols//2]\n else:\n i1 = max(garden[j1][num_cols//2], garden[j1][num_cols//2]-1)\n i2 = max(garden[j2][num_cols//2], garden[j2][num_cols//2]-1)\n\n ival = max(i1, i2)\n if ival == i1:\n j = j1\n else:\n j = j2\n\n i = garden[j].index(ival)\n\n return (j, i)", "def find_loc_indices(loc, dir, tile):\n #returns the indices of the nearest neighbor point in the given tile, the lon/lat of the nearest neighbor, \n #and the distance (m) from the given point to the nearest neighbor grid cell\n \n filename_pattern = '*grid.tile{0}.nc'.format(tile)\n for f_name in os.listdir(dir):\n if fnmatch.fnmatch(f_name, filename_pattern):\n filename = f_name\n if not filename:\n message = 'No filenames matching the pattern {0} found in {1}'.format(filename_pattern,dir)\n logging.critical(message)\n raise Exception(message)\n \n nc_file = Dataset('{0}/{1}'.format(dir,filename))\n #read in supergrid longitude and latitude\n lon_super = np.array(nc_file['x']) #[lat,lon] or [y,x] #.swapaxes(0,1)\n lat_super = np.array(nc_file['y']) #[lat,lon] or [y,x] #.swapaxes(0,1)\n #get the longitude and latitude data for the grid centers by slicing the supergrid \n #and taking only odd-indexed values\n longitude = lon_super[1::2,1::2]\n latitude = lat_super[1::2,1::2]\n nc_file.close()\n \n adj_long = False \n #look for reversal of longitude; if found, adjust longitude so that 0-360 transition doesn't exist\n temp_loc = copy.deepcopy(loc)\n for row in longitude:\n if not (np.all(np.diff(row) >= 0) or np.all(np.diff(row) <= 0)):\n adj_long = True\n if adj_long:\n longitude[longitude < 180] += 360\n if loc[0] < 180:\n temp_loc[0] += 360\n \n #set up an array to hold the euclidean distance between the given point and every grid cell\n eucl_dist = np.zeros((longitude.shape[0],longitude.shape[1]))\n \n #get the Cartesian location of the given point\n cart_loc = np.array(sph2cart(math.radians(temp_loc[0]), math.radians(temp_loc[1]), earth_radius))\n \n for i in range(len(longitude)):\n for j in range(len(longitude[i])):\n #get the Cartesian location of all grid points\n cart_cell = np.array(sph2cart(math.radians(longitude[i,j]), math.radians(latitude[i,j]), earth_radius))\n \n #calculate the euclidean distance from the given point to the current grid cell\n eucl_dist[i,j] = np.linalg.norm(cart_loc - cart_cell)\n \n #get the indices of the grid point with the minimum euclidean distance to the given point\n i,j = np.unravel_index(eucl_dist.argmin(), eucl_dist.shape)\n \n return (i,j,longitude[i,j]%360.0, latitude[i,j], eucl_dist[i,j])", "def encontrar_picos(self, guess, delta_ppm):\r\n # La idea es esta:\r\n # dado el delta en cada direccion, defino una region cuadrada donde\r\n # busco el maximo. Luego, con los indices del maximo encuentro el pico.\r\n # es importante que el guess sea bueno! \r\n ppmDir = self.ppmGridDir[0,:]\r\n ppmInd = self.ppmGridInd[:,0]\r\n \r\n x,y = guess \r\n x_index = find_nearest(ppmDir, x)\r\n y_index = find_nearest(ppmInd, y)\r\n \r\n # cuantos ppm son un paso en cada direccion\r\n stepDir = np.abs(ppmDir[1]-ppmDir[0])\r\n stepInd = np.abs(ppmInd[1]-ppmInd[0]) \r\n nx = int(delta_ppm[0]/stepDir)\r\n ny = int(delta_ppm[1]/stepInd)\r\n \r\n spec_reduced = self.spec[y_index-ny:y_index+ny, x_index-nx:x_index+nx]\r\n ppmDir_reduced = ppmDir[x_index-nx:x_index+nx]\r\n ppmInd_reduced = ppmInd[y_index-ny:y_index+ny]\r\n \r\n maximo = spec_reduced.max()\r\n y, x = np.where(spec_reduced==maximo)\r\n \r\n x = ppmDir_reduced[x[0]]\r\n y = ppmInd_reduced[y[0]]\r\n \r\n x_index = find_nearest(ppmDir, x)\r\n y_index = find_nearest(ppmInd, y)\r\n \r\n #plt.contourf(ppmDir_reduced,ppmInd_reduced,spec_reduced)\r\n return x_index, y_index", "def research_pos(self, map_list, character): \n list_pos = []\n for y in range(15): \n for x, c in enumerate(map_list[y]):\n if character in c and c == character:\n list_pos.append((x*50, y*50)) \n return list_pos", "def coords_from_cell(cell, lon = [-8.73, -8.50], lat = [41.10, 41.25], N = 100, M = 75):\n lon_step = (lon[1] - lon[0]) / N \n lat_step = (lat[1] - lat[0]) / M\n \n middle_lon = lon[0] + cell[0] * lon_step + lon_step / 2\n middle_lat = lat[0] + cell[1] * lat_step + lat_step / 2\n \n return [middle_lon, middle_lat]", "def coord (i, j):\r\n return j, i", "def get_neighbours(lat, long):\n # ns = north east, ew = east west (ratio between 1 feet and degree) \n # its different on diferent places on earth (sphere)!!\n ns = 0.0025\n ew = 0.0025\n walk = []\n for i in range(-2, 3):\n for j in range(-2, 3):\n thiscell = CellId.from_lat_lng(LatLng.from_degrees(lat + ns*i, long + ew*j)).parent(S2_CELL_LEVEL)\n if abs(i * j) < 4:\n walk.append(thiscell.id())\n return sorted(walk)", "def tinyMazeSearch(problem):\n from game import Directions\n s = Directions.SOUTH\n w = Directions.WEST\n return [s,s,w,s,w,w,s,w]", "def tinyMazeSearch(problem):\n from game import Directions\n s = Directions.SOUTH\n w = Directions.WEST\n return [s,s,w,s,w,w,s,w]", "def tinyMazeSearch(problem):\n from game import Directions\n s = Directions.SOUTH\n w = Directions.WEST\n return [s,s,w,s,w,w,s,w]", "def tinyMazeSearch(problem):\n from game import Directions\n s = Directions.SOUTH\n w = Directions.WEST\n return [s,s,w,s,w,w,s,w]" ]
[ "0.63763857", "0.6294268", "0.5994749", "0.58479625", "0.5692342", "0.56698024", "0.5659775", "0.56519175", "0.56519175", "0.56280005", "0.562039", "0.5616189", "0.56113046", "0.5585523", "0.55844796", "0.5576134", "0.5575527", "0.5563845", "0.5553286", "0.5546779", "0.5539142", "0.55324674", "0.55239505", "0.552384", "0.55220056", "0.5503274", "0.547931", "0.547931", "0.547931", "0.547931" ]
0.6835468
0
Find cities left and right
def test_find_cities(self): # Given game_state: CarcassonneGameState = CarcassonneGameState() city_one_side_straight_road = base_tiles["city_top_straight_road"].turn(3) city_with_road = inns_and_cathedrals_tiles["ic_15"].turn(3) game_state.board = [[None for column in range(2)] for row in range(1)] game_state.board[0][0] = city_with_road game_state.board[0][1] = city_one_side_straight_road # When cities: [City] = CityUtil.find_cities( game_state=game_state, coordinate=Coordinate(0, 0) ) # Then self.assertEqual(1, len(cities)) self.assertEqual(2, len(cities[0].city_positions)) self.assertTrue(cities[0].finished)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def check_right(nodeL, nodeR, city):\n A = get_node_points(nodeL)\n B = get_node_points(nodeR)\n C = get_city_points(city)\n slope = _slope(A, B)\n (F, G) = calibrator(A, B, slope)\n sign = math.copysign(1, ((G[0] - F[0]) * (C[1] - F[1]) - (G[1] - F[1]) * (C[0] - F[0])))\n\n if slope == \"horizontal\":\n if sign == -1:\n if A[0] > B[0]:\n return (nodeR, nodeL)\n else:\n return (nodeL, nodeR)\n else:\n if A[0] < B[0]:\n return (nodeR, nodeL)\n else:\n return (nodeL, nodeR)\n\n if slope == \"vertical\":\n if sign == -1:\n if A[1] < B[1]:\n return (nodeR, nodeL)\n else:\n return (nodeL, nodeR)\n else:\n if A[1] > B[1]:\n return (nodeR, nodeL)\n else:\n return (nodeL, nodeR)\n\n if slope == \"inclined\":\n if sign == -1:\n if A[1] < B[1]:\n return (nodeR, nodeL)\n else:\n return (nodeL, nodeR)\n else:\n if A[1] > B[1]:\n return (nodeR, nodeL)\n else:\n return (nodeL, nodeR)\n\n if slope == \"declined\":\n if sign == -1:\n if A[1] < B[1]:\n return (nodeR, nodeL)\n else:\n return (nodeL, nodeR)\n else:\n if A[1] > B[1]:\n return (nodeR, nodeL)\n else:\n return (nodeL, nodeR)", "def get_all_roads_starting_from(network, city):\n return network[1][city][0]", "def test_find_donut_city(self):\n\n # Given\n game_state: CarcassonneGameState = self.create_donut_city_board()\n\n # When\n city: City = CityUtil.find_city(\n game_state=game_state,\n city_position=CoordinateWithSide(Coordinate(0, 0), Side.BOTTOM)\n )\n\n # Then\n self.assertTrue(city.finished)\n self.assertEqual(16, len(city.city_positions))\n self.assertIn(CoordinateWithSide(Coordinate(0, 0), Side.BOTTOM), city.city_positions)\n self.assertIn(CoordinateWithSide(Coordinate(0, 0), Side.RIGHT), city.city_positions)\n self.assertIn(CoordinateWithSide(Coordinate(0, 1), Side.LEFT), city.city_positions)\n self.assertIn(CoordinateWithSide(Coordinate(0, 1), Side.RIGHT), city.city_positions)\n self.assertIn(CoordinateWithSide(Coordinate(0, 2), Side.LEFT), city.city_positions)\n self.assertIn(CoordinateWithSide(Coordinate(0, 2), Side.BOTTOM), city.city_positions)\n self.assertIn(CoordinateWithSide(Coordinate(1, 0), Side.TOP), city.city_positions)\n self.assertIn(CoordinateWithSide(Coordinate(1, 0), Side.BOTTOM), city.city_positions)\n self.assertIn(CoordinateWithSide(Coordinate(1, 2), Side.TOP), city.city_positions)\n self.assertIn(CoordinateWithSide(Coordinate(1, 2), Side.BOTTOM), city.city_positions)\n self.assertIn(CoordinateWithSide(Coordinate(2, 0), Side.TOP), city.city_positions)\n self.assertIn(CoordinateWithSide(Coordinate(2, 0), Side.RIGHT), city.city_positions)\n self.assertIn(CoordinateWithSide(Coordinate(2, 1), Side.LEFT), city.city_positions)\n self.assertIn(CoordinateWithSide(Coordinate(2, 1), Side.RIGHT), city.city_positions)\n self.assertIn(CoordinateWithSide(Coordinate(2, 2), Side.LEFT), city.city_positions)\n self.assertIn(CoordinateWithSide(Coordinate(2, 2), Side.TOP), city.city_positions)", "def test_find_city(self):\n\n # Given\n game_state: CarcassonneGameState = CarcassonneGameState()\n\n city_top = base_tiles[\"city_top\"]\n city_bottom = city_top.turn(2)\n\n game_state.board = [[None for column in range(1)] for row in range(2)]\n\n game_state.board[0][0] = city_bottom\n game_state.board[1][0] = city_top\n\n # When\n city: City = CityUtil.find_city(\n game_state=game_state,\n city_position=CoordinateWithSide(Coordinate(0, 0), Side.BOTTOM)\n )\n\n # Then\n self.assertTrue(city.finished)\n self.assertEqual(2, len(city.city_positions))\n self.assertIn(CoordinateWithSide(Coordinate(0, 0), Side.BOTTOM), city.city_positions)\n self.assertIn(CoordinateWithSide(Coordinate(1, 0), Side.TOP), city.city_positions)", "def parse_citystate(self):\n \n index = self.index\n \n if self.words[index]['tag'] != Vocabulary.NAME:\n return None, None, 0, 0\n \n if self.words[index]['word'] == 'mt':\n city = \"mountain\"\n else:\n city = self.words[index]['word']\n start = index\n \n index += 1\n if index == self.length:\n return None, None, 0, 0\n \n if self.words[index]['word'] == ',':\n index += 1\n if index == self.length:\n return None, None, 0, 0\n elif self.words[index]['tag'] == Vocabulary.NAME: \n # Hack\n state, n = self.state_hack(index)\n if n > 0:\n index += n\n return city, state, index - start + 1, index\n \n #if self.words[index]['word'] == 'medical doctor':\n #return city, \"ISO3166-2:US-MD\", index - start + 1, index\n try:\n state = self._state_dict[self.words[index]['word']]\n return city, state, index - start + 1, index\n except:\n city += ' ' + self.words[index]['word']\n index += 1\n if index == self.length:\n return None, None, 0, 0\n \n if self.words[index]['word'] == ',':\n index += 1\n if index == self.length:\n return None, None, 0, 0\n\n # Hack\n state, n = self.state_hack(index)\n if n > 0:\n index += n\n if index == self.length: index -= 1 # Hack\n return city, state, index - start + 1, index\n \n if self.words[index]['tag'] not in [Vocabulary.NAME, Vocabulary.ACRONYM]:\n return None, None, 0, 0\n \n try:\n state = self._state_dict[self.words[index]['word']]\n return city, state, index - start + 1, index\n except: \n return None, None, 0, 0", "def get_city_points(city):\n for item in coordinate_list:\n if item[0] == city:\n return (item[1], item[2])", "def get_coordinates_for_city(city, state=None):\n search_str = ', '.join([city, state]) if state else city\n db_coords = get_coordinates_from_db(search_str)\n if db_coords:\n return (search_str, db_coords)\n else:\n page_title, coords = get_coordinates_from_wikipedia(search_str)\n add_coordinates_to_db(coords, search_str)\n return (page_title, coords)", "def sub_run2(node_left, node, city):\n [nodeL, nodeR, new_city, distance] = connect_distance(node_left, node, city[1])\n if [nodeL, nodeR, new_city, distance] == [\"a\", \"b\", \"c\", \"d\"]:\n oR = optimize_right((node, node.right, city[1], 0))\n oL = optimize_left((node_left, node, city[1], 0))\n [nodeL, nodeR, new_city, distance] = is_smaller(oR, oL)\n\n if intersect(nodeL, nodeR, new_city) == True:\n oR = optimize_right((nodeL, nodeL.right, city[1], 0))\n oL = optimize_left((nodeR, nodeR.left, city[1], 0))\n [nodeL, nodeR, new_city, distance] = is_smaller(oR, oL)\n else:\n pass\n new_node = add_node(nodeL, nodeR, new_city)\n sub_run1(new_node, distance)", "def connect_left(nodeL, new_city):\n a = dic_list[nodeL.value - 1].get(nodeL.value).get(nodeL.left.value)\n b = dic_list[nodeL.value - 1].get(nodeL.value).get(new_city)\n c = dic_list[nodeL.left.value - 1].get(nodeL.left.value).get(new_city)\n shortest = b + c - a\n return (nodeL.left, nodeL, new_city, shortest)", "def connect_right(nodeR, new_city):\n a = dic_list[nodeR.value - 1].get(nodeR.value).get(nodeR.right.value)\n b = dic_list[nodeR.value - 1].get(nodeR.value).get(new_city)\n c = dic_list[nodeR.right.value - 1].get(nodeR.right.value).get(new_city)\n shortest = b + c - a\n return (nodeR, nodeR.right, new_city, shortest)", "def find_nn(self, city, list):\n start_city = self.get_coordinates_from_city(city)\n return min((euclidean_distance(start_city, self.get_coordinates_from_city(rest)), rest) for rest in\n list)", "def getCitySightings(catalog,city):\n cities=catalog['cities']\n keyset=om.keySet(cities)\n selected_city=om.get(cities,city)['value']\n match=lt.newList(datastructure='ARRAY_LIST')\n max_sightings=0\n max_city=\"\"\n #Para obtener la ciudad con mas cantidad de avistamientos toca recorrer todo el arbol.\n #De esto se encarga el siguiente for-\n for c in lt.iterator(keyset):\n city_sightings=lt.size(om.get(cities, c)['value'])\n if city_sightings>max_sightings:\n max_sightings=city_sightings\n max_city=c\n \n #Añade todo los avistamientos de la ciudad ingresada a una lista.\n for sight in lt.iterator(selected_city):\n lt.addLast(match,sight)\n total=lt.size(match)\n ms.sort(match,compareDateTime)\n \n #Hacer la lista en caso de que halla mas que 6\n if total>6:\n joined=lt.subList(match,1,3)\n last=lt.subList(match,total-3,3)\n for a in lt.iterator(last):\n lt.addLast(joined, a)\n else:\n joined=lt.subList(match,1,total)\n return total, joined, max_sightings, max_city", "def best_coords(self):\n lat, lon = None, None\n for term in self.terms:\n # print(term)\n # print(term['weight'])\n geo = term.get(\"geo\")\n if geo:\n osm = geo['osm']\n gm = geo['gm']\n geo_data = None\n if osm:\n geo_data = osm\n elif gm:\n geo_data = gm\n if geo_data:\n g = geo_data[0]\n lat, lon = g['latitude'], g['longitude']\n break\n return lat, lon, self.region", "def lcs_le(x: List, y: List) -> Tuple[Matrix, atrix]:\n m = len(x)\n n = len(y)\n lcs_matrix = [[None]*(n+1) for i in range(m+1)\n # each index is a optimal solution for each subproblem\n direction_matrix = [[None]*n for i in range(m)]\n # if either indecd is 0 then each element is 0\n for i n ranage(1, m+1):\n lcs_matrix[i][0] = 0\n for j in range(n+1):\n lcs_matrix[0][j] = 0\n for i in range(m):\n for j in range(n):\n if x[i] == y[j]:\n lcs_matrix[i+1][j+1] = lcs_matrix[i][j]+1\n direction_matrix[i][j] = Direction.UPPER_LEFT\n elif lcs_matrix[i][j+1] >= lcs_matrix[i+1][j]:\n lcs_matrix[i+1][j+1] = lcs_matrix[i][j+1]\n direction_matrix[i][j] = Direction.UP\n else:\n lcs_matrix[i+1][j+1] = lcs_matrix[i+1][j]\n direction_matrix[i][j] = Direction.LEFT\n return lcs_matrix, index_matrix", "def FindDHopCities(self, X, d):\n # G = nx.Graph()\n # G.add_nodes_from(self.nodes)\n # G.add_edges_from(self.edges)\n\n # airports_id_in_city = self.airports.loc[self.airports['city'] == X, 'airport_id'].to_list()\n\n # cities_h_hop = set()\n # for airport in airports_id_in_city:\n # airports_h_hop = nx.descendants_at_distance(G, airport, h)\n # for airport_h_hop in airports_h_hop:\n # cities_h_hop.add(self.GetCityFromAirportId(airport_h_hop))\n\n # return cities_h_hop\n\n graph_adj = self.graph\n\n airports_id_in_city = self.airports.loc[self.airports['city'] == X, 'airport_id'].to_list()\n cities_d_hop = set()\n for airport in airports_id_in_city:\n airports_d_hop = set()\n current_distance = 0\n queue = {airport}\n visited = {airport}\n \n # BFS\n while queue:\n if current_distance == d:\n airports_d_hop.update(queue)\n\n current_distance += 1\n\n current_path = set()\n for poped_node in queue:\n for child in graph_adj[poped_node]:\n if child not in visited:\n visited.add(child)\n current_path.add(child)\n\n queue = current_path\n \n for airport_d_hop in airports_d_hop:\n cities_d_hop.add(self.GetCityFromAirportId(airport_d_hop))\n\n return cities_d_hop", "def get_city_from_osm(city_name, network_type=\"drive\"):\n city_paths_nodes = None\n for which_result in range(1, 4):\n try:\n city_boundaries = ox.gdf_from_place(city_name, which_result=which_result)\n city_paths_nodes = ox.osm_net_download(city_boundaries['geometry'].unary_union, network_type=network_type)\n break\n except Exception as e:\n logger.exception(e)\n return None\n\n return city_paths_nodes", "def get_others(map_, r, c):\n nums = 0\n # your code here\n if r == 0 and c == 0: #top left corder\n nums += 2\n if len(map_[0]) > 1:\n if map_[r][c+1] == 0:\n nums += 1\n if map_[r+1][c] == 0:\n nums += 1\n elif r == 0 and c == len(map_[0])-1: #top right corner\n nums += 2\n if len(map_[0]) > 1:\n if map_[r][c-1] == 0:\n nums += 1\n if map_[r+1][c] == 0:\n nums += 1\n elif r == len(map_)-1 and c == 0: #bottom left corder\n nums += 2\n if len(map_[0]) > 1:\n if map_[r][c+1] == 0:\n nums += 1\n if map_[r-1][c] == 0:\n nums += 1\n elif r == len(map_)-1 and c == len(map_[0])-1: #bottom right corner\n nums += 2\n if map_[r][c-1] == 0:\n nums += 1\n if map_[r-1][c] == 0:\n nums += 1\n elif r == 0: # top edge, excluding corner\n nums += 1\n if map_[r][c-1] == 0:\n nums += 1\n if map_[r][c+1] == 0:\n nums += 1\n if len(map_) > r and map_[r+1][c] == 0:\n nums += 1\n elif r == len(map_)-1: # bottom edge, excluding corner\n nums += 1\n if map_[r][c-1] == 0:\n nums += 1\n if map_[r][c+1] == 0:\n nums += 1\n if map_[r-1][c] == 0:\n nums += 1\n elif c == 0: # left edge, excluding corner\n nums += 1\n if map_[r-1][c] == 0:\n nums += 1\n if map_[r+1][c] == 0:\n nums += 1\n if len(map_[0]) > c and map_[r][c+1] == 0:\n nums += 1\n elif c == len(map_[0])-1: # right edge. excluding corner\n nums += 1\n if map_[r-1][c] == 0:\n nums += 1\n if map_[r+1][c] == 0:\n nums += 1\n if map_[r][c-1] == 0:\n nums += 1\n else: # the rest, excluding edge and corner\n if map_[r-1][c] == 0:\n nums += 1\n if map_[r+1][c] == 0:\n nums += 1\n if map_[r][c-1] == 0:\n nums += 1\n if map_[r][c+1] == 0:\n nums += 1\n return nums", "def inner(pos, camefrom):\r\n\t\tlabyrinth[pos[0]][pos[1]] = VISITED\r\n\t\tif pos == GOAL:\r\n\t\t\treturn [pos], True\r\n\t\tfor neighbour in neighbours(pos):\r\n\t\t\tif neighbour != camefrom and is_inside(neighbour):\r\n\t\t\t\tif labyrinth[neighbour[0]][neighbour[1]] != BLOCKED and labyrinth[neighbour[0]][neighbour[1]] != VISITED:\r\n\t\t\t\t\tway, success = inner(neighbour, pos)\r\n\t\t\t\t\tif success == True:\r\n\t\t\t\t\t\treturn [pos]+way, True\r\n\t\treturn None, False", "def get_city_base(city_map = CHICAGO_NEIGHBORHOOD):\n shapes = shp.Reader(city_map).shapeRecords()\n x,y = [],[]\n for shape in shapes:\n inner_x,inner_y = list(zip(*shape.shape.points))\n x.append(inner_x)\n y.append(inner_y)\n x_flat = [item for sublist in x for item in sublist]\n y_flat = [item for sublist in y for item in sublist]\n return x_flat,y_flat", "def alltours(cities):\n start = first(cities)\n return [[start] + Tour(rest)\n for rest in itertools.permutations(cities - {start})]", "def parse_streetdir(self):\n \n first = self.words[self.index]['word']\n if self.index + 1 < self.length:\n second = self.words[self.index+1]['word']\n else:\n second = None\n \n if first in ['northwest', 'northeast', 'southwest', 'southeast']:\n return first, 1 \n elif first == 'nw':\n return \"northwest\", 1\n elif first == 'ne':\n return \"northeast\", 1\n elif first == 'sw':\n return \"southwest\", 1\n elif first == 'se':\n return \"southeast\", 1\n \n if first in ['n', 'north']:\n if second in ['w', 'west']:\n return \"northwest\", 2\n elif second in ['e', 'east']:\n return \"northeast\", 2\n else:\n return \"north\", 1\n elif first in ['s', 'south']:\n if second in ['w', 'west']:\n return \"southwest\", 2\n elif second in ['e', 'east']:\n return \"southeast\", 2\n else:\n return \"south\", 1\n elif first in ['e', 'east']:\n return \"east\", 1\n elif first in ['w', 'west']:\n return \"west\", 1\n \n return None,0", "def get_head_and_tail(street):\r\n def is_end(location):\r\n num_adj = 0\r\n adj = get_orthogonal(location)\r\n for merchant in street:\r\n if merchant != location and merchant in adj:\r\n num_adj += 1\r\n return num_adj <= 1\r\n return [loc for loc in street if is_end(loc)]", "def nn_tsp(cities, start=None):\n if start is None: start = first(cities)\n tour = [start]\n unvisited = set(cities - {start})\n while unvisited:\n C = nearest_neighbor(tour[-1], unvisited)\n tour.append(C)\n unvisited.remove(C)\n return tour", "def cities(self):\n return [value for value in models.storage.all(City).values()\n if value.state_id == self.id]", "def common_cities(members, city_sets):\n\n common_cities = city_sets[members[0]]\n\n for i in range(1, len(members)):\n\n new_cities = city_sets[members[i]]\n common_cities = list(set(common_cities).intersection(new_cities))\n\n # print common_cities\n return common_cities", "def reachable_province(self, ctx):\n return self.reachable_tiles(ctx)", "def neighbors(districts, r, c):\r\n n_list = []\r\n if r>0:\r\n n_list += [districts[r-1,c]]\r\n if r<4:\r\n n_list += [districts[r+1,c]]\r\n if c>0:\r\n n_list += [districts[r,c-1]]\r\n if c<4:\r\n n_list += [districts[r,c+1]]\r\n return n_list", "def leftright_neighbors(j, chain) :\n i, k = find_neighbors(j, chain.bridges_dict)\n if chain.lumens_dict[i].pos <= chain.lumens_dict[k].pos :\n return [i, k]\n else :\n return [k, i]", "def binary_search_transition(\n self,\n tz: Any,\n dt_left: datetime,\n dt_right: datetime,\n ) -> Tuple[datetime, datetime]:\n dt_left_local = dt_left.astimezone(tz)\n while True:\n delta_minutes = int((dt_right - dt_left) / timedelta(minutes=1))\n delta_minutes //= 2\n if delta_minutes == 0:\n break\n\n dt_mid = dt_left + timedelta(minutes=delta_minutes)\n mid_dt_local = dt_mid.astimezone(tz)\n if self.is_transition(dt_left_local, mid_dt_local):\n dt_right = dt_mid\n else:\n dt_left = dt_mid\n dt_left_local = mid_dt_local\n\n return dt_left, dt_right", "def find_nearby_cities(graph: TeleportGraph, city: str, num_hops: int = 1) -> set:\n\n if num_hops == 0:\n return set()\n\n start_city_node = graph.find_city_node(city)\n\n city_nodes = {start_city_node}\n\n for i in range(num_hops):\n related_cities = set()\n\n # for every city in the current set, find all its related cities and add them to the global list of cities\n for city in city_nodes:\n related_cities |= city.related_cities\n\n city_nodes |= related_cities\n\n # The starting city cannot be near itself. It will always be added to the set because we have\n # bi-directional (undirected) edges between cities.\n city_nodes.remove(start_city_node)\n return {city.name for city in city_nodes}" ]
[ "0.58423823", "0.5793729", "0.5751381", "0.5717831", "0.5653619", "0.55346805", "0.54687995", "0.5438168", "0.5415307", "0.54040617", "0.53798175", "0.5343393", "0.53421456", "0.5333387", "0.5331795", "0.53222567", "0.5321915", "0.5293763", "0.52919155", "0.52559435", "0.52501076", "0.52436805", "0.52340144", "0.5193033", "0.5184245", "0.51778287", "0.5155977", "0.5147799", "0.5106368", "0.50868905" ]
0.60894334
0
Create an Edge between two vertices using an anchor. This is useful to have a better representation of the direction of the edge.
def from_anchor( cls, anchor: Vertex, other: Vertex, label: str = "", direction: str = "out", ) -> "Edge": has_direction = direction != "none" if has_direction is True: if direction == "out": start = anchor end = other elif direction == "in": start = other end = anchor else: raise ValueError("Direction is either 'in', 'out' or 'none'") else: # No need to sort here, the __init__ do it already. start = anchor end = other edge = cls(start, end, label=label, has_direction=has_direction) edge._anchor = anchor edge._other = other edge._direction = direction return edge
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def make_edge(self, a, b):\n try: e = self.G.new_edge(a, b)\n except: return self.G.new_edge(a,b)\n\n try: self.G.set_edge_attribute(e, \"arrow\", \"true\")\n except: return self.G.new_edge(a,b)\n\n try: self.G.set_edge_attribute(e, \"spline\", \"false\")\n except: return self.G.new_edge(a,b)\n return e", "def MakeEdge(self, *args):\n return _ShapeBuild.ShapeBuild_Edge_MakeEdge(self, *args)", "def __init__(\n self,\n start: Vertex,\n end: Vertex,\n label: str = \"\",\n has_direction: bool = True,\n ):\n if not start.is_inserted or not end.is_inserted:\n raise VertexInsertionException(\n \"Both vertices must be inserted to make an Edge\"\n )\n\n if has_direction is True:\n self._start = start\n self._end = end\n else:\n # If the Edge has no direction, the start and end vertices are\n # sorted by place for consistant use.\n self._start, self._end = sorted(\n (start, end), key=lambda v: v.place\n )\n self._label = label\n self._has_direction = has_direction\n\n self._anchor: Optional[Vertex] = None\n self._other: Optional[Vertex] = None\n self._direction: Optional[str] = None\n\n self.is_inserted = False", "def e(src, dst):\n edge = pydot.Edge(src, dst)\n graph.add_edge(edge)", "def create(cls, outV, inV, *args, **kwargs):\r\n return super(Edge, cls).create(outV, inV, *args, **kwargs)", "def add_edge(self, v1, v2):\n pass # TODO", "def change_anchor(self, anchor: Vertex) -> None:\n if not self.has_vertex(anchor):\n raise ValueError(\"The given anchor doesn't belong to the edge\")\n\n self._anchor = anchor\n if self._has_direction is False:\n self._other = (\n self._end if self._anchor is self._start else self._start\n )\n self._direction = \"none\"\n else:\n if self._start is self._anchor:\n self._other = self._end\n self._direction = \"out\"\n else:\n self._other = self._start\n self._direction = \"in\"", "def define_edge(self):\n\n self.canvas_edge = Line(\n points=[\n self.canvas_nodes[0].pos[0] + self.nodesize[0] / 2,\n self.canvas_nodes[0].pos[1] + self.nodesize[1] / 2,\n self.canvas_nodes[1].pos[0] + self.nodesize[0] / 2,\n self.canvas_nodes[1].pos[1] + self.nodesize[1] / 2\n ],\n joint='round',\n cap='round',\n width=3\n )", "def add_edge(self, a, b, label=\"\", color=\"black\", length=100, arrows=\"to\"):\n\n\t\tm = self.edgesPairs.count((a, b))\n\n\t\tif m == 0 :\n\t\t\tcolor = color\n\t\tif m == 1:\n\t\t\tcolor = \"red\"\n\t\tif m == 2:\n\t\t\tcolor = \"blue\"\n\n\t\tself.edgesPairs.append((a, b))\n\t\tself.edgesPairsId[self.edgesIdsCounter] = (a, b)\n\t\tself.edgesLabelsId[self.edgesIdsCounter] = label\n\n\t\tself.edges.append({\"id\": self.edgesIdsCounter,\n\t\t\t\t\t\t\"from\": a,\n\t\t\t\t\t\t\"to\": b,\n\t\t\t\t\t\t\"label\": label,\n\t\t\t\t\t\t\"arrows\": arrows,\n\t\t\t\t\t\t\"color\": color,\n\t\t\t\t\t\t\"length\": length\n\t\t\t\t\t\t})\n\t\tself.edgesIdsCounter += 1", "def createEdge(lines, list):\n res = lines.split('\\\\n')\n mains = res[0].split(' ')\n sid = mains[3]\n sid = sid[4:-1]\n ssource = mains[4]\n ssource = ssource[8:-1]\n starget = mains[5]\n starget = starget[8:-2]\n slabel = ''\n i = 2\n\n while ('key=' in res[i]):\n i = i + 1\n\n if ('EdgeLabel' in res[i + 4]):\n slabels = res[i + 4].split('>')\n slabel = slabels[1]\n slabel = slabel.split('<')[0]\n slabel = umlautHelper(slabel)\n\n source = findInList(ssource, list)\n target = findInList(starget, list)\n\n nline = Edge(sid, source, target)\n nline.setLabel(slabel)\n\n j = i + 1\n while ('Path' in res[j] or 'Point' in res[j]):\n j = j + 1\n\n allarrows = res[j + 1]\n if ('source=\"standard' in allarrows or 'source=\"delta' in allarrows):\n nline.setArrowSource(True)\n if ('target=\"standard' in allarrows or 'target=\"delta' in allarrows):\n nline.setArrowTarget(True)\n\n if (type(source) == Entity and type(target) == Attribute):\n source.addAttribute(target)\n if (type(target) == Entity and type(source) == Attribute):\n target.addAttribute(source)\n if (type(source) == Relation and type(target) == Attribute):\n source.addAttribute(target)\n if (type(target) == Relation and type(source) == Attribute):\n target.addAttribute(source)\n list.append(nline)", "def test_create_edge(self):\n n1, n2 = Node('a'), Node('b')\n n1 | n2\n self.assertEqual(n1.eout, [Edge(n1, n2)])\n self.assertEqual(n1.ein, [])\n self.assertEqual(n2.ein, [Edge(n1, n2)])\n self.assertEqual(n2.eout, [])", "def makeEdgeVertex(self, f, v):\n newV = self.addVertex(0, 0, 0)\n newE = self.addEdge(v, newV)\n newE.pFace = f\n return (newE, newV)", "def add_edge(self, v1, v2):\n # TODO\n\n # add directed edges\n self.vertices[v1].add(v2)\n # self.vertices[v2].add(v1)", "def add_edge(self, start_node, label, end_node, properties=None, **kwargs):\r\n\t\tif properties is None:\r\n\t\t\tproperties = {}\r\n\t\tedge = Edge(self._nextid, start_node, label, end_node, properties, **kwargs)\r\n\t\tself._edges[self._nextid] = edge\r\n\t\tself._nextid += 1\r\n\t\treturn edge", "def add_edge(self, vertex1, vertex2):\n\n vertex1.add_outgoing_node(vertex2)\n vertex2.add_incoming_node(vertex1)", "def create_edge(from_node, to_node, label, edge_schema, add_ts=False):\n edge_record = {}\n edge_record[\"label\"] = label\n edge_record[\"fromNode\"] = from_node\n edge_record[\"toNode\"] = to_node\n\n # Add a timestamp to the properties if the caller requested it.\n if add_ts:\n edge_record[\"properties\"] = {}\n edge_record[\"properties\"][\"timestamp\"] = \\\n Utils._get_time_milliseconds()\n\n return edge_record", "def create_edge(src_node: Node, dst_node: Node, out_port: int = 0, in_port: int = 0, edge_attrs: dict = None):\n # edges must belong to the same graph\n assert src_node.graph is dst_node.graph\n graph = src_node.graph\n\n if edge_attrs is None:\n edge_attrs = dict()\n else:\n edge_attrs = edge_attrs.copy()\n edge_attrs.update({'in': in_port, 'out': out_port, 'in_attrs': ['in'], 'out_attrs': ['out'],\n 'data_attrs': ['fw_tensor_debug_info']})\n\n graph.add_edges_from([(src_node.id, dst_node.id, edge_attrs)])", "def _edge(u, v):\n return (u, v) if u < v else (v, u)", "def edge_direction(a, b):\n if a[0] == b[0]:\n return -1, 1\n elif a[0] == b[1]:\n return -1, -1\n elif a[1] == b[0]:\n return 1, 1\n elif a[1] == b[1]:\n return 1, -1\n else:\n constants.log.debug('\\n'.join([\n 'edges not connected!',\n 'vertex path %s',\n 'entity path: %s',\n 'entity[a]: %s,',\n 'entity[b]: %s']),\n vertex_path,\n entity_path,\n entities[ea].points,\n entities[eb].points)\n\n return None, None", "def add_edge (self, src, dst, link):\n raise NotImplementedError", "def addEdge(self, e):\n v = e.either()\n w = e.other(v)\n self._validateVertex(v)\n self._validateVertex(w)\n self._adj[v].add(e)\n self._adj[w].add(e)\n self._E += 1", "def link(self, node1, node2, edge_type = None, **attr):\n if edge_type is None:\n edge_type = relations[node1.element_type][node2.element_type]\n edge = getattr(self.graph, edge_type).create(node1, node2, **attr)\n return edge", "def add_edge(self, node_from, node_to, weight=0):\n self.edges.append(Edge(node_from, node_to, weight, self.directed))\n self.nodes.update([node_from, node_to])\n return self", "def add_edge(self, key_a, key_b, distance=1, bidirectional=True):\n # Check that both keys exist\n if (not key_a in self.vertices) or (not key_b in self.vertices):\n raise ValueError('Key not found')\n \n # Add edge to the vertex lists\n edge = GraphEdge(distance, bidirectional)\n self.vertices[key_a].edges_out[key_b] = edge \n self.vertices[key_b].edges_in[key_a] = edge \n if bidirectional:\n self.vertices[key_b].edges_out[key_a] = edge \n self.vertices[key_a].edges_in[key_b] = edge", "def new_edge(self, parent, child):\n self.add_edge( Edge(parent,child) )", "def _add_edge(self, a, b):\n e = Edge2(a, b)\n i = bisect(self.edges, e)\n \n # if edge between these vertices exists just return it\n if len(self.edges) > i and self.edges[i] == e:\n return self.edges[i]\n \n # otherwise add new edge in sorted position and return it\n self.edges.insert(i, e)\n return e", "def add_edge(self, v1, v2):\n # Check if they exist\n # if v1 in self.vertices and v2 in self.vertices:\n if v1 in self.vertices:\n # Add the edge\n self.vertices[v1].add(v2)\n else:\n print(f\"ERROR ADDING EDGE between {v1} and {v2} : Vertex not found\")", "def add_edge(self, e):\n x = min(e)\n y = max(e)\n if x not in self._vertices:\n self.add_vertex(x)\n if y not in self._vertices:\n self.add_vertex(y)\n self._edges.add( (x, y) )", "def add_edge(source, sink, label=\"\"):\n source.add_outgoing_edge(sink, label)\n sink.add_incoming_edge(source, label)", "def add_edge(self, v1, v2):\n if v2 in self.vertices:\n self.vertices[v1].add(v2)\n else:\n raise ValueError(f\"The second Vertices you provided: {v2} is not in the graph. You can't link to a vertices that isn't in the graph.\")" ]
[ "0.6983778", "0.66082233", "0.65253586", "0.6465049", "0.6457213", "0.63240004", "0.6193088", "0.614468", "0.6093483", "0.60523874", "0.60418546", "0.6033494", "0.6029768", "0.6016275", "0.5921528", "0.57524085", "0.57500446", "0.5746553", "0.57396865", "0.5726155", "0.56953615", "0.56881344", "0.56875914", "0.56690556", "0.566532", "0.5664493", "0.56475705", "0.5647377", "0.5643592", "0.56274426" ]
0.7591544
0
Create an Edge between two vertices using a pack (4tuple).
def from_pack(cls, pack: Tuple[int, int, str, bool], db) -> "Edge": start_place, end_place, label, has_direction = pack start = db[start_place] end = db[end_place] return cls(start, end, label, has_direction)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def create_edge(vertex_1, vertex_2, edge_type, strand, edges):\n # Check if the edge exists, and return the ID if it does\n query = \",\".join([str(vertex_1), str(vertex_2), edge_type,strand])\n if query in edges.keys():\n existing_edge_id = edges[query][0]\n return existing_edge_id, edges\n\n # In the case of no match, create the edge \n # Get ID number from counter\n edge_id = edges[\"counter\"] + 1\n edges[\"counter\"] += 1\n new_edge = (edge_id, vertex_1, vertex_2, edge_type, strand)\n keyname = \",\".join([str(vertex_1), str(vertex_2), edge_type, strand])\n edges[keyname] = new_edge\n\n return edge_id, edges", "def add_edge(self, vertices: Iterable[\"Vertex\"]) -> None:\n vertices = list(vertices)\n if len(vertices) == 2:\n self.edges.append(self.add_vertices(vertices)) # type: ignore\n else:\n raise DXFValueError(\n \"Invalid vertices count, expected two vertices.\"\n )", "def add_edge(self, v1, v2):\n pass # TODO", "def test_create_edge(self):\n n1, n2 = Node('a'), Node('b')\n n1 | n2\n self.assertEqual(n1.eout, [Edge(n1, n2)])\n self.assertEqual(n1.ein, [])\n self.assertEqual(n2.ein, [Edge(n1, n2)])\n self.assertEqual(n2.eout, [])", "def __new__(cls, *vs):\n if len(vs) != 2:\n raise ValueError, 'Edges must connect exactly two vertices.'\n return tuple.__new__(cls, vs)", "def e(src, dst):\n edge = pydot.Edge(src, dst)\n graph.add_edge(edge)", "def MakeEdge(self, *args):\n return _ShapeBuild.ShapeBuild_Edge_MakeEdge(self, *args)", "def make_edge(self, a, b):\n try: e = self.G.new_edge(a, b)\n except: return self.G.new_edge(a,b)\n\n try: self.G.set_edge_attribute(e, \"arrow\", \"true\")\n except: return self.G.new_edge(a,b)\n\n try: self.G.set_edge_attribute(e, \"spline\", \"false\")\n except: return self.G.new_edge(a,b)\n return e", "def create(cls, outV, inV, *args, **kwargs):\r\n return super(Edge, cls).create(outV, inV, *args, **kwargs)", "def add_vertex_edge(self, vertices):\n if len(vertices) < 2:\n raise Exception('Cannot have a single vertex')\n self.add_vertex(vertices[0])\n length_array = len(vertices)\n for iterator in range(1, length_array):\n num = vertices[iterator]\n is_number = False\n try:\n int(num)\n is_number = True\n except ValueError:\n pass\n if is_number:\n self.add_edge(vertices[0], num)", "def _edge(u, v):\n return (u, v) if u < v else (v, u)", "def reverse_edge(e: tuple) -> tuple:\n (u, v, data) = e\n return (v, u, data)", "def add_edge(self, e):\n v, w = e\n self[v][w] = e\n self[w][v] = e", "def add_edge(self, v1, v2):\n pass # TODO\n # both vertices have to exist to make connection(e.g. directed edge)\n\n if v1 in self.vertices and v2 in self.vertices:\n # print(f' type(vertices) is {type(self.vertices)}')\n self.vertices[v1].add(v2) # using set .add() method to append\n else:\n # print(f'ERROR: vertex {v1} or {v2} does not exist') \n raise ValueError(\"Vertex not yet created\")\n # print(f'ERROR: vertex {v1} or {v2} does not exist')\n\n #### not quite\n # try:\n # if v1 in self.vertices or v2 in self.vertices:\n # self.vertices[v1].add(v2)\n # except:\n # raise ValueError(\" BAD VERTEX !!\")\n\n\n if v1 not in self.vertices or v2 not in self.vertices:\n raise ValueError(\" BAD VERTEX !!\")\n else:\n self.vertices[v1].add(v2)", "def add_edge(self, e):\n a, b = e\n self[a][b] = e\n self[b][a] = e", "def edgify(vertices:list)->list:\n edges = []\n for k in range(0, len(vertices) - 1):\n edges.append([vertices[k], vertices[k + 1]])\n return edges", "def createEdge(lines, list):\n res = lines.split('\\\\n')\n mains = res[0].split(' ')\n sid = mains[3]\n sid = sid[4:-1]\n ssource = mains[4]\n ssource = ssource[8:-1]\n starget = mains[5]\n starget = starget[8:-2]\n slabel = ''\n i = 2\n\n while ('key=' in res[i]):\n i = i + 1\n\n if ('EdgeLabel' in res[i + 4]):\n slabels = res[i + 4].split('>')\n slabel = slabels[1]\n slabel = slabel.split('<')[0]\n slabel = umlautHelper(slabel)\n\n source = findInList(ssource, list)\n target = findInList(starget, list)\n\n nline = Edge(sid, source, target)\n nline.setLabel(slabel)\n\n j = i + 1\n while ('Path' in res[j] or 'Point' in res[j]):\n j = j + 1\n\n allarrows = res[j + 1]\n if ('source=\"standard' in allarrows or 'source=\"delta' in allarrows):\n nline.setArrowSource(True)\n if ('target=\"standard' in allarrows or 'target=\"delta' in allarrows):\n nline.setArrowTarget(True)\n\n if (type(source) == Entity and type(target) == Attribute):\n source.addAttribute(target)\n if (type(target) == Entity and type(source) == Attribute):\n target.addAttribute(source)\n if (type(source) == Relation and type(target) == Attribute):\n source.addAttribute(target)\n if (type(target) == Relation and type(source) == Attribute):\n target.addAttribute(source)\n list.append(nline)", "def makeEdgeVertex(self, f, v):\n newV = self.addVertex(0, 0, 0)\n newE = self.addEdge(v, newV)\n newE.pFace = f\n return (newE, newV)", "def add_edge(self, v1, v2):\n # TODO\n\n # add directed edges\n self.vertices[v1].add(v2)\n # self.vertices[v2].add(v1)", "def add_edge(self, vertex1, vertex2):\n\n vertex1.add_outgoing_node(vertex2)\n vertex2.add_incoming_node(vertex1)", "def add_edge(self,from_vertex_id, to_vertex_id, edge_type, edge_id):\n # ‘EdgeProto‘ defines defaults for other attributes.\n\n old_edge = 0\n for old_edge_id in self.vertex[from_vertex_id].edge_out:\n if self.edge[old_edge_id].type != 'skip_connection':\n old_edge = old_edge_id\n\n if edge_type == 'conv':\n\n \"\"\"\n Insert convolution layer in two step:\n 1. Insert a new vertex between from_vertex and the identity or convolution edge.\n 2. Insert a convolution edge between from_vertex and new vertex\n 3. add the new vertex and new edge to dna graph \n \n \"\"\"\n #1.add a new vertex first\n new_vertex_proto = Vertex_Protocol()\n new_vertex_proto.type = random.choice(['relu_bn', 'linear'])\n new_vertex = Vertex(new_vertex_proto)\n\n #2.add conv edge\n new_edge_proto= Edge_Protocol()\n new_edge_proto.type = 'conv'\n new_edge = Edge(new_edge_proto)\n new_edge.type = edge_type\n new_edge.ID = edge_id\n\n #config input and output for new_edge and new_vertex\n\n new_edge.from_vertex=from_vertex_id\n new_edge.to_vertex = new_vertex.ID\n\n new_vertex.input_mutable = True\n new_vertex.output_mutable = True\n new_vertex.edge_in.add(new_edge.ID)\n new_vertex.edge_out.add(old_edge)\n\n self.edge[old_edge].from_vertex = new_vertex.ID\n\n\n self.vertex[new_vertex.ID] = new_vertex\n self.edge[new_edge.ID] = new_edge\n\n\n elif edge_type == 'identity':\n\n \"\"\"\n Insert convolution layer in two step:\n 1. Insert a new vertex between from_vertex and the identity or convolution edge.\n 2. Insert an identity edge between from_vertex and new vertex\n 3. add the new vertex and new edge to dna graph \n \n \"\"\"\n # 1.add a new vertex first\n\n new_vertex_proto = Vertex_Protocol()\n new_vertex_proto.type = 'linear'\n new_vertex = Vertex(new_vertex_proto)\n\n # 2.add identity edge\n\n new_edge = Edge(Edge_Protocol())\n new_edge.type = edge_type\n new_edge.ID = edge_id\n\n new_vertex.input_mutable = True\n new_vertex.output_mutable = True\n new_vertex.edge_in.add(new_edge.ID)\n new_vertex.edge_out.add(old_edge)\n\n self.edge[old_edge].from_vertex = new_vertex.ID\n\n self.vertex[new_vertex.ID] = new_vertex\n self.edge[new_edge.ID] = new_edge\n\n elif edge_type=='skip_connection':\n\n \"\"\"\n Add a skip connection between from_vertex and to_vertex\n \"\"\"\n self.vertex[from_vertex_id].edge_out.add(edge_id)\n self.vertex[to_vertex_id].edge_in.add(edge_id)\n\n edge_proto = Protocol_Buffer.Edge_Protocol()\n edge_proto.type = edge_type\n edge_proto.ID = edge_id\n edge_proto.from_vertex = from_vertex_id\n edge_proto.to_vertex = to_vertex_id\n self.edge[edge_id] = Edge(edge_proto)", "def CreateEdges(Nodes, Edges, Graph):\n setOfEdges, multiSetOfEdges = EdgesSetCreate(Edges)\n weights = EdgeWeights(setOfEdges, multiSetOfEdges)\n for edge in setOfEdges:\n if (edge[0] in Nodes) and (edge[1] in Nodes):\n Graph.add_edge(Nodes[edge[0]], Nodes[edge[1]],\n weight=weights[edge])\n return Graph", "def twoEdgesIntoSamePort(self):\n graph = self.graph\n makeLayer = self.makeLayer\n eastWestEdgeFromTo = self.eastWestEdgeFromTo\n addNodeToLayer = self.addNodeToLayer\n addPortOnSide = self.addPortOnSide\n addEdgeBetweenPorts = self.addEdgeBetweenPorts\n\n leftLayer = makeLayer(graph)\n rightLayer = makeLayer(graph)\n\n topLeft = addNodeToLayer(leftLayer)\n bottomLeft = addNodeToLayer(leftLayer)\n topRight = addNodeToLayer(rightLayer)\n bottomRight = addNodeToLayer(rightLayer)\n\n eastWestEdgeFromTo(topLeft, bottomRight)\n bottomLeftFirstPort = addPortOnSide(bottomLeft, PortSide.EAST)\n bottomLeftSecondPort = addPortOnSide(bottomLeft, PortSide.EAST)\n topRightFirstPort = addPortOnSide(topRight, PortSide.WEST)\n topRightSecondPort = addPortOnSide(topRight, PortSide.WEST)\n\n addEdgeBetweenPorts(bottomLeftFirstPort, topRightFirstPort)\n addEdgeBetweenPorts(bottomLeftSecondPort, topRightSecondPort)\n\n return graph", "def _add_edge(self, graph: Graph, vertex1: Vertex, vertex2: Vertex) \\\n -> None:\n new_edge = Edge(vertex1, vertex2)\n graph.add(new_edge)", "def add_edge(self, v1, v2):\n # Check if they exist\n # if v1 in self.vertices and v2 in self.vertices:\n if v1 in self.vertices:\n # Add the edge\n self.vertices[v1].add(v2)\n else:\n print(f\"ERROR ADDING EDGE between {v1} and {v2} : Vertex not found\")", "def add_edge(u, v):\n adj[u].append(v)\n adj[v].append(u)", "def add_edge(u, v):\n adj[u].append(v)\n adj[v].append(u)", "def test_create_two_named_edges(self):\n n1, n2 = Node('a'), Node('b')\n result = n1 * 'foo' | 'bar' * n2\n self.assertEqual(result, n2)\n self.assertEqual(n1.eout, [Edge(n1, n2, 'foo', 'bar')])\n self.assertEqual(n2.ein, [Edge(n1, n2, 'foo', 'bar')])", "def __init__(self, vertices=[], edges=[]):\n for vertex in vertices:\n self.add_vertex(vertex)\n for edge in edges:\n self.add_edge(edge)", "def edge(self, v, d):\n # method here" ]
[ "0.6660539", "0.65261745", "0.65147144", "0.64800143", "0.64572924", "0.6405685", "0.634937", "0.63491523", "0.63377154", "0.63239527", "0.63221407", "0.6290063", "0.6218834", "0.6176455", "0.61461127", "0.6144521", "0.6127656", "0.61104333", "0.6051926", "0.60435635", "0.5970322", "0.59668934", "0.5957849", "0.59541535", "0.5929608", "0.5861019", "0.5861019", "0.584878", "0.58481115", "0.58270186" ]
0.6592813
1
Change the anchor vertex, thus the perspective of the edge. The ``anchor``, ``other`` and ``direction`` attributes are recalculated.
def change_anchor(self, anchor: Vertex) -> None: if not self.has_vertex(anchor): raise ValueError("The given anchor doesn't belong to the edge") self._anchor = anchor if self._has_direction is False: self._other = ( self._end if self._anchor is self._start else self._start ) self._direction = "none" else: if self._start is self._anchor: self._other = self._end self._direction = "out" else: self._other = self._start self._direction = "in"
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def setAnchor(self,a):\n self.anchor = a", "def set_transformation_anchor(self, mode: ViewportAnchorStr | mod.ViewportAnchor):\n self.setTransformationAnchor(VIEWPORT_ANCHOR.get_enum_value(mode))", "def setAnchor(self, anchor):\r\n self.pack(anchor=anchor)", "def setAnchor(self, anchor):\r\n self.pack(anchor=anchor)", "def setAnchor(self, anchor):\r\n self.pack(anchor=anchor)", "def anchor(self) -> Optional[Vertex]:\n return self._anchor", "def set_angel(self):\n self.angle = math.degrees(math.atan2(self.next.y - self.y, self.next.x - self.x)\n - math.atan2(self.prev.y - self.y, self.prev.x - self.x))\n\n if self.angle < 0:\n self.angle += 360", "def from_anchor(\n cls,\n anchor: Vertex,\n other: Vertex,\n label: str = \"\",\n direction: str = \"out\",\n ) -> \"Edge\":\n has_direction = direction != \"none\"\n\n if has_direction is True:\n if direction == \"out\":\n start = anchor\n end = other\n elif direction == \"in\":\n start = other\n end = anchor\n else:\n raise ValueError(\"Direction is either 'in', 'out' or 'none'\")\n else:\n # No need to sort here, the __init__ do it already.\n start = anchor\n end = other\n\n edge = cls(start, end, label=label, has_direction=has_direction)\n\n edge._anchor = anchor\n edge._other = other\n edge._direction = direction\n\n return edge", "def _do_anchor(self, anchor):\n if anchor:\n for x in anchor.split(\"-\"):\n A, P = None, None\n if x.startswith(\"A\") and len(self.chunks) > 0: # anchor\n A, P = x, x.replace(\"A\",\"P\")\n self._anchors[A] = self.chunks[-1]\n if x.startswith(\"P\") and len(self.pnp) > 0: # attachment (PNP)\n A, P = x.replace(\"P\",\"A\"), x\n self._anchors[P] = self.pnp[-1]\n if A in self._anchors and P in self._anchors and not self._anchors[P].anchor:\n pnp = self._anchors[P]\n pnp.anchor = self._anchors[A]\n pnp.anchor.attachments.append(pnp)", "def showAnchor(self):\n dot = gr.Circle(gr.Point(self.anchor[0]*self.scale,\n self.win.getHeight()-self.anchor[1]*self.scale), self.radius * self.scale)\n dot.draw(self.win)", "def adjust_anchors(self):\n pass", "def setPos(self, x, y, anchor='ll'):\n self.transform.setPos(glm.vec3(x, y, 0))\n if anchor == 'ul':\n offx = 0\n offy = - self.font.table['ascent']\n elif anchor == 'uc':\n offx = - self._labelWidth / 2\n offy = - self.font.table['ascent']\n elif anchor == 'ur':\n offx = - self._labelWidth\n offy = - self.font.table['ascent']\n elif anchor == 'cl':\n offx = 0\n offy = self._labelHeight / 2 - self.font.table['ascent']\n elif anchor == 'cc':\n offx = - self._labelWidth / 2\n offy = self._labelHeight / 2 - self.font.table['ascent']\n elif anchor == 'cr':\n offx = - self._labelWidth\n offy = self._labelHeight / 2 - self.font.table['ascent']\n elif anchor == 'll':\n offx = 0\n offy = self._labelHeight - self.font.table['ascent']\n elif anchor == 'lc':\n offx = - self._labelWidth / 2\n offy = self._labelHeight - self.font.table['ascent']\n elif anchor == 'lr':\n offx = - self._labelWidth\n offy = self._labelHeight - self.font.table['ascent']\n else:\n raise SystemExit(f\"Unimplemented anchor '{anchor}'\")\n self.model.setPos(glm.vec3(offx, offy, 0))", "def makeEdgeVertex(self, f, v):\n newV = self.addVertex(0, 0, 0)\n newE = self.addEdge(v, newV)\n newE.pFace = f\n return (newE, newV)", "def update_position(self):\n p1, p2 = connection_points_between_figure_elements(self.vertex1,\n self.vertex2)\n self.set_xdata((p1.x, p2.x))\n self.set_ydata((p1.y, p2.y))\n self.arrow.remove()\n self.arrow = create_directional_arrow(self)\n self.axes.add_patch(self.arrow)", "def add_edge(self, e):\n v, w = e\n self[v][w] = e\n self[w][v] = e", "def set_adjoint_op(self, adjoint_op):\r\n self.adjoint_op = adjoint_op\r\n adjoint_op.adjoint_op = self", "def new_edge(self, parent, child):\n self.add_edge( Edge(parent,child) )", "def addEdge(self,x,y):\r\n self.matr[x][y] = True\r\n self.matr[y][x] = True", "def set_axial_view(self):\n self.renderer.ResetCamera()\n fp = self.renderer.GetActiveCamera().GetFocalPoint()\n p = self.renderer.GetActiveCamera().GetPosition()\n dist = math.sqrt((p[0] - fp[0]) ** 2 + (p[1] - fp[1]) ** 2 + (p[2] - fp[2]) ** 2)\n self.renderer.GetActiveCamera().SetPosition(fp[0], fp[1], fp[2] + dist)\n self.renderer.GetActiveCamera().SetViewUp(0.0, 1.0, 0.0)\n self.renderer.GetActiveCamera().Zoom(1.8)\n self.render_window.Render()", "def set_resize_anchor(self, mode: ViewportAnchorStr | mod.ViewportAnchor):\n self.setResizeAnchor(VIEWPORT_ANCHOR.get_enum_value(mode))", "def define_edge(self):\n\n self.canvas_edge = Line(\n points=[\n self.canvas_nodes[0].pos[0] + self.nodesize[0] / 2,\n self.canvas_nodes[0].pos[1] + self.nodesize[1] / 2,\n self.canvas_nodes[1].pos[0] + self.nodesize[0] / 2,\n self.canvas_nodes[1].pos[1] + self.nodesize[1] / 2\n ],\n joint='round',\n cap='round',\n width=3\n )", "def reflect(self):\n self.vertices[-1, :] = self.reflected", "def Adjust(self):\r\n if not self.srcNode() or not self.destNode():\r\n return \r\n\r\n self.prepareGeometryChange()\r\n\r\n self.setSrcPoint(self.mapFromItem(self.srcNode(), self.srcNode().outputConnectionPoint()))\r\n self.setDestPoint(self.mapFromItem(self.destNode(), self.destNode().inputConnectionPoint()))", "def __init__(self, eye=vec([0, 0, 0]), target=vec([0, 0, -1]), up=vec([0, 1, 0]),\n vfov=90.0, aspect=1.0):\n self.eye = eye\n self.aspect = aspect\n # TODO A5 copy implementation from A4\n self.target = target\n self.vfov = np.radians(vfov)\n self.w = normalize(eye - target)\n self.u = normalize(np.cross(up, self.w))\n self.v = np.cross(self.w, self.u)", "def adjustOrient(joint, target):\n\n inv_x = target.translateX.get() < 0\n x_axis = {\n False: (1, 0, 0),\n True: (-1, 0, 0)\n }\n\n orientJoint(joint, target.getTranslation(ws=True), aim_axis=x_axis[inv_x],\n world_up=joint.getMatrix(ws=True)[1][:3])", "def setModeAddEdge(self):\n self.scene().mode = fsScene.MODE_ADDEDGE", "def e(src, dst):\n edge = pydot.Edge(src, dst)\n graph.add_edge(edge)", "def represent_link(ax, x,y, x_neighbour, y_neighbour):\n \n dx = x_neighbour-x\n dy = y_neighbour-y\n # Draw a black arrow between (x, y) and (x+dx, y+dy)\n ax.arrow(x, y, dx, dy, head_width=0.1, head_length=0.2, length_includes_head = True, fc='k')", "def mirror(self, about_x=False, about_y=False, about_axis=False):\n if about_axis:\n c = (0, 0)\n elif about_axis is False:\n c = self.center()\n\n if about_y:\n x_new = []\n for p in self.x:\n x_new.append(c[0] + (c[0] - p))\n else:\n x_new = self.x\n\n if about_x:\n y_new = []\n for p in self.y:\n y_new.append(c[1] + (c[1] - p))\n else:\n y_new = self.y\n\n return Route(x_new, y_new, z=self.z)", "def adjustToNewAngle(self):\n\n self.a,self.b,self.c = parametersFromPointAngle( 0.5*(self.point1+self.pointN), self.newAngle)\n\n #print 'adjustToNewAngle ', self, self.angle, self.newAngle\n self.angle = self.newAngle\n self.normalv = numpy.array( [ self.a, self.b ])\n self.unitv = numpy.array( [ self.b, -self.a ])\n if abs(self.angle) > numpy.pi/2 :\n if self.b > 0: self.unitv *= -1\n elif self.b<0 : self.unitv *= -1\n\n self.point1 = self.projectPoint(self.point1) # reset point1 \n if self.next is None or not self.next.isSegment():\n # move the last point (no intersect with next)\n\n pN = self.projectPoint(self.pointN)\n dirN = pN - self.point1 \n lN = length(pN, self.point1)\n self.pointN = dirN/lN*self.length + self.point1\n #print ' ... adjusting last seg angle ',p.dump() , ' normalv=', p.normalv, 'unitv ', p.unitv\n else:\n self.setIntersectWithNext()" ]
[ "0.613399", "0.60137486", "0.5749917", "0.5749917", "0.5749917", "0.5731453", "0.55341566", "0.5467825", "0.52504694", "0.5230639", "0.52012956", "0.51814395", "0.5119678", "0.5112798", "0.5108198", "0.51019514", "0.5035828", "0.50141704", "0.49247175", "0.49093834", "0.4896181", "0.486253", "0.48583838", "0.48415786", "0.48308682", "0.48170376", "0.47737208", "0.47627342", "0.47547284", "0.47484604" ]
0.7595603
0
Do additional process when the Edge is inserted in a database. This callback method can be overriden when subclassing the Edge class. It is called by the DocNetDB object when inserting this Edge.
def on_insert(self) -> None:
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def post_database_node_create(self, resource_dict):\n pass", "def on_insert(self, callback):\n self._insert_callback = callback if callable(callback) else _void", "def on_publish_edge(self):\n logging.debug(\"Edge data published\")", "def process_IN_CREATE(self, event):", "def save_edge(self, edge: Edge) -> Edge:", "def __saveEdges(self, edges):", "def after_insert(self, obj, st):\n pass", "def add_edge(self, ed):\n self.edge.append(ed)\n self.update_node2edge()", "def save(self, db):\n pass", "def insert(self):\n self.getDbRecord().insert()\n\n return", "def addChild(self, edge):\n self.child_edges[edge.getId()] = edge", "def save(self, *args, **kwargs):\r\n super(Edge, self).save(*args, **kwargs)\r\n return self._save_edge(self._outV,\r\n self._inV,\r\n self.get_label(),\r\n self.as_save_params(),\r\n exclusive=self.__exclusive__)[0]", "def post(self):\n blob_key = self.request.get(\"blobkey\")\n\n database_creation.run(blob_key)", "def _during_execute(self, db):\n pass", "def _after_execute(self, db, entity):\n pass", "def _after_execute(self, db, entity):\n pass", "def save_event(self, data):\n rdb.table(self.rdb_table).insert(data)", "def trigger_onInserted(self, record):\n\n method_lists = METHODS_LISTS.get(record.get('method', ''), None)\n\n if method_lists is None:\n return\n\n board_id = record['id']\n lst_tbl = self.db.table('base.list')\n lst_to_add = []\n now = datetime.now()\n\n for i, lst_name in enumerate(method_lists):\n lst_to_add.append({\n '__ins_ts': now, '__mod_ts': now, 'id': lst_tbl.newPkeyValue(),\n 'name': lst_name, 'position': i, 'board_id': board_id\n })\n\n try:\n lst_tbl.insertMany(lst_to_add)\n lst_tbl.db.commit()\n except Exception as e:\n print e", "def insert_data(self):\n\n pass", "def save_edge(self, edge: Union[dict, Edge]):", "def pre_database_node_create(self, resource_dict):\n pass", "def save_db(self) -> None:", "def _during_execute(self, db, entity):\n pass", "def _after_execute(self, db):\n pass", "def save(self, *args, **kwargs):\n super(self.__class__, self).save(*args, **kwargs)", "def save(self, *args, **kwargs):\n super().save(*args, **kwargs)", "def save(self, *args, **kwargs):\n super().save(*args, **kwargs)", "def add_edge_field(self,name,data,on_exists='fail'):\n if name in np.dtype(self.edge_dtype).names:\n if on_exists == 'fail':\n raise GridException(\"Edge field %s already exists\"%name)\n elif on_exists == 'pass':\n return\n elif on_exists == 'overwrite':\n self.edges[name] = data\n else:\n self.edges=recarray_add_fields(self.edges,\n [(name,data)])\n self.edge_dtype=self.edges.dtype", "def on_create(self):", "def write_edge(self, record) -> None:\n pass" ]
[ "0.5794349", "0.57343805", "0.5708902", "0.5656077", "0.5542931", "0.5499471", "0.54518545", "0.54497755", "0.5391843", "0.53787625", "0.5335628", "0.5284934", "0.5263634", "0.52613235", "0.5238483", "0.5238483", "0.52286077", "0.52163917", "0.5213748", "0.5213024", "0.52031916", "0.5194059", "0.51934654", "0.5178872", "0.51786584", "0.51780605", "0.51780605", "0.5171152", "0.51302904", "0.51294357" ]
0.6171724
0
Readonly property for the has_direction attribute.
def has_direction(self) -> bool: return self._has_direction
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_direction(self):\r\n return self.__direction", "def direction(self):\n return self._direction.copy()", "def get_direction(self):\n return self.direction", "def direction(self):\n _direction = self._custom.get(\"direction\")\n if _direction is not None:\n return _direction\n\n _direction = self._infer_direction()\n self._custom[\"direction\"] = _direction\n\n return _direction", "def set_direction(self, direction):\n\n def same_axis(direction1, direction2):\n y_axis = [Direction.Y_POSITIVE, Direction.Y_NEGATIVE]\n x_axis = [Direction.X_POSITIVE, Direction.X_NEGATIVE]\n return ((direction1 in x_axis and direction2 in x_axis)\n or (direction1 in y_axis and direction2 in y_axis))\n\n if direction is None:\n return\n elif not same_axis(self.direction, direction):\n self.direction = direction", "def setdirection(self, *args, **kwargs):\n return _coordsys.coordsys_setdirection(self, *args, **kwargs)", "def set_direction(self, dir):\n if dir == 0:\n self.direction = [0, -1]\n elif dir == 1:\n self.direction = [1, 0]\n elif dir == 2:\n self.direction = [0, 1]\n elif dir == 3:\n self.direction = [-1, 0]", "def direction(self) -> Optional[str]:\n return self._direction", "def direction(self):\n return None if not bool(self.relation) else (self.s_end <= self.o_start)", "def direction(self) -> np.ndarray:\n return self._direction", "def direction(self, direction):\n allowed_values = [\"supports\", \"does_not_support\"] # noqa: E501\n if direction not in allowed_values:\n raise ValueError(\n \"Invalid value for `direction` ({0}), must be one of {1}\" # noqa: E501\n .format(direction, allowed_values)\n )\n\n self._direction = direction", "def direction(self):\n return self.cfg.direction", "def getDirection(self, direction: str):\n return direction", "def direction(self) -> int:\n return self._direction", "def direction(self) -> Optional[pulumi.Input[str]]:\n return pulumi.get(self, \"direction\")", "def getRobotDirection(self):\n return self.direction\n #raise NotImplementedError", "def getRobotDirection(self):\n return self.direction\n #raise NotImplementedError", "def directionRight(self):\n return self.__directionRight", "def directionLeft(self):\n return self.__directionLeft", "def read_direction(self):\n global motor_direction\n with self._lock:\n return motor_direction", "def getDirection(self):\n if 'N' in str(self.trip_update.trip.trip_id):\n direction = 'northbound'\n if 'S' in str(self.trip_update.trip.trip_id):\n direction = 'southbound'\n return direction", "def direction(self) -> str:\n return pulumi.get(self, \"direction\")", "def test_direction(self):\n\n # Default initialized direction is forward.\n self.assertEqual(self.group_tr.getDirection(),\n OCIO.TRANSFORM_DIR_FORWARD)\n\n for direction in OCIO.TransformDirection.__members__.values():\n self.group_tr.setDirection(direction)\n self.assertEqual(self.group_tr.getDirection(), direction)\n\n # Wrong type tests.\n for invalid in (None, 1, 'test'):\n with self.assertRaises(TypeError):\n self.group_tr.setDirection(invalid)", "def set_direction(self, right_or_left):\r\n if right_or_left == \"r\":\r\n self.__direction = self.__direction - 7\r\n elif right_or_left == \"l\":\r\n self.__direction = self.__direction + 7", "def direction(self) -> pulumi.Input[str]:\n return pulumi.get(self, \"direction\")", "def direction(self, direction):\n\n self._direction = direction", "def getRobotDirection(self):\n return self.direction", "def getRobotDirection(self):\n return self.direction", "def update_player_direction(self,direction):\n pass", "def get_direction(self):\n directions = dict(ACTIVITY_DIRECTION_CHOICES)\n return directions.get(self.direction, \"N/A\")" ]
[ "0.68509877", "0.67023075", "0.66625434", "0.65358186", "0.6429286", "0.631484", "0.62817025", "0.619135", "0.6172699", "0.6124396", "0.6123484", "0.612275", "0.60402006", "0.60147136", "0.5984809", "0.5958099", "0.5958099", "0.5938603", "0.5921282", "0.58906907", "0.5875808", "0.5865335", "0.5851287", "0.585086", "0.58352333", "0.5823254", "0.57809997", "0.57809997", "0.5771086", "0.57613313" ]
0.748902
0
Test that SLURM environment variables are properly checked for rank_zero_only.
def test_rank_zero_known_cluster_envs(env_vars: Mapping[str, str]): from pytorch_lightning.utilities.distributed import _get_rank, rank_zero_only rank_zero_only.rank = _get_rank() with mock.patch.dict(os.environ, env_vars): from pytorch_lightning.utilities.distributed import _get_rank, rank_zero_only rank_zero_only.rank = _get_rank() @rank_zero_only def foo(): # The return type is optional because on non-zero ranks it will not be called return 1 x = foo() assert x == 1
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _assert_local_rank_set(self):\n assert self.local_rank >= 0, 'The environment variable LOCAL_RANK is not set, thus the coordinator is not aware of the local rank of the current process.'", "def test_rank_zero_none_set(rank_key, rank):\n\n with mock.patch.dict(os.environ, {rank_key: rank}):\n from pytorch_lightning.utilities.distributed import _get_rank, rank_zero_only\n\n rank_zero_only.rank = _get_rank()\n\n @rank_zero_only\n def foo():\n return 1\n\n x = foo()\n assert x is None", "def test_rank_zero_only():\n os.environ[\"RANK\"] = \"0\"\n # check that wrapping instance work\n timer = pt_clb.rank_zero_only(pt_clb.Timer())\n assert hasattr(timer, \"timer\")\n\n os.environ[\"RANK\"] = \"1\"\n # check that wrapping class also works\n timer = pt_clb.rank_zero_only(pt_clb.Timer)()\n assert not hasattr(timer, \"timer\")", "def rank():\n return int(os.environ['RANK'])", "def is_torch_distributed_launch_via_environment_variables() -> bool:\n\n env_vars = os.environ\n is_using_environment_vars: bool = (\n \"RANK\" in env_vars\n and \"MASTER_ADDR\" in env_vars\n and \"MASTER_PORT\" in env_vars\n and \"WORLD_SIZE\" in env_vars\n )\n\n return is_using_environment_vars", "def validate_and_init() -> bool:\n env_vars_absent = [\n env\n for env in REQUIRED_ENVS\n if env not in os.environ or len(os.environ[env]) == 0\n ]\n if env_vars_absent:\n print(f\"Please define {env_vars_absent} in your github secrets. Aborting...\")\n return False\n\n if not (\n ENV_VAR_STATS_TYPE in os.environ\n and len(os.environ[ENV_VAR_STATS_TYPE]) > 0\n and os.environ[ENV_VAR_STATS_TYPE] in ALLOWED_STATS_TYPES\n ):\n print(f\"Using default stats type: {DEFAULT_STATS_TYPE}\")\n os.environ[ENV_VAR_STATS_TYPE] = DEFAULT_STATS_TYPE\n\n return True", "def _setup_test_infra(world_rank, world_size):\n os.environ['RANK'] = str(world_rank)\n os.environ['WORLD_SIZE'] = str(world_size)\n os.environ['MASTER_ADDR'] = '127.0.0.1'\n os.environ['MASTER_PORT'] = '29500'\n\n set_cuda_device_id(world_rank)\n\n dist.init_process_group(backend='nccl', world_size=world_size, rank=world_rank)", "def local_rank():\n return int(os.environ['LOCAL_RANK'])", "def test_local_env_pass_implicit(fileutils) -> None:\n exp_value = str(uuid.uuid4())\n env_key = \"test_local_env_pass_implicit\"\n os.environ[env_key] = exp_value\n\n test_dir = fileutils.make_test_dir()\n exp_dir = f\"{test_dir}/exp\"\n os.makedirs(exp_dir)\n script = fileutils.get_test_conf_path(\"check_env.py\")\n\n exp = Experiment(\"LRZ\", exp_path=exp_dir, launcher=\"slurm\")\n\n exe_name = \"python\"\n exe_args = [script, env_key]\n\n # Create the RunSettings associated with the workload manager (WLM) run command\n run_args = {\"--nodes\": 1, \"--ntasks\": 1, \"--time\": \"00:01:00\"}\n # NOTE: not passing env_args into run_settings here, relying on --export=ALL default\n settings = RunSettings(exe_name, exe_args, run_command=\"srun\", run_args=run_args)\n app_name = \"echo_app\"\n app = exp.create_model(app_name, settings)\n\n # generate the experiment structure and start the model\n exp.generate(app, overwrite=True)\n exp.start(app, block=True, summary=False)\n\n assert env_key not in settings.env_vars\n os.environ.pop(env_key)\n\n with open(f\"{exp_dir}/{app_name}/{app_name}.out\") as app_outfile:\n app_output = app_outfile.read()\n \n # verify application was able to access the env var\n assert f\"{env_key}=={exp_value}\" in app_output", "def _set(env_var: str) -> bool:\n return os.getenv(env_var) not in [None, \"0\"]", "def _check_dist_env() -> bool:\n env_required = (\n os.environ.get(\"MASTER_PORT\"),\n os.environ.get(\"MASTER_ADDR\"),\n os.environ.get(\"WORLD_SIZE\"),\n os.environ.get(\"RANK\"),\n )\n return all(env is not None for env in env_required)", "def init_distributed_mode(params):\n params.is_slurm_job = 'SLURM_JOB_ID' in os.environ \n has_local_rank = hasattr(params, 'local_rank')\n\n # SLURM job\n if params.is_slurm_job and has_local_rank:\n\n assert params.local_rank == -1 # on the cluster, this is handled by SLURM\n\n SLURM_VARIABLES = [\n 'SLURM_JOB_ID',\n 'SLURM_JOB_NODELIST', 'SLURM_JOB_NUM_NODES', 'SLURM_NTASKS', 'SLURM_TASKS_PER_NODE',\n 'SLURM_MEM_PER_NODE', 'SLURM_MEM_PER_CPU',\n 'SLURM_NODEID', 'SLURM_PROCID', 'SLURM_LOCALID', 'SLURM_TASK_PID'\n ]\n\n PREFIX = \"%i - \" % int(os.environ['SLURM_PROCID'])\n for name in SLURM_VARIABLES:\n value = os.environ.get(name, None)\n #print(PREFIX + \"%s: %s\" % (name, str(value)))\n\n # # job ID\n # params.job_id = os.environ['SLURM_JOB_ID']\n\n # number of nodes / node ID\n params.n_nodes = int(os.environ['SLURM_JOB_NUM_NODES'])\n params.node_id = int(os.environ['SLURM_NODEID'])\n\n # local rank on the current node / global rank\n params.local_rank = int(os.environ['SLURM_LOCALID'])\n params.global_rank = int(os.environ['SLURM_PROCID'])\n\n # number of processes / GPUs per node\n params.world_size = int(os.environ['SLURM_NTASKS'])\n params.n_gpu_per_node = params.world_size // params.n_nodes\n\n # define master address and master port\n hostnames = subprocess.check_output(['scontrol', 'show', 'hostnames', os.environ['SLURM_JOB_NODELIST']])\n params.main_addr = hostnames.split()[0].decode('utf-8')\n assert 10001 <= params.main_port <= 20000 or params.world_size == 1\n #print(PREFIX + \"Master address: %s\" % params.master_addr)\n #print(PREFIX + \"Master port : %i\" % params.master_port)\n\n # set environment variables for 'env://'\n os.environ['MASTER_ADDR'] = params.main_addr\n os.environ['MASTER_PORT'] = str(params.main_port)\n os.environ['WORLD_SIZE'] = str(params.world_size)\n os.environ['RANK'] = str(params.global_rank)\n params.is_distributed = True\n\n\n # multi-GPU job (local or multi-node) - jobs started with torch.distributed.launch\n elif has_local_rank and params.local_rank != -1:\n\n assert params.main_port == -1\n\n # read environment variables\n params.global_rank = int(os.environ['RANK'])\n params.world_size = int(os.environ['WORLD_SIZE'])\n params.n_gpu_per_node = int(os.environ['NGPU'])\n\n # number of nodes / node ID\n params.n_nodes = params.world_size // params.n_gpu_per_node\n params.node_id = params.global_rank // params.n_gpu_per_node\n params.is_distributed = True\n\n else:\n n_gpu = torch.cuda.device_count()\n params.n_nodes = 1\n params.node_id = 0\n params.local_rank = 0\n params.global_rank = 0\n params.world_size = n_gpu\n params.n_gpu_per_node = n_gpu\n params.is_distributed = False\n\n # define whether this is the master process / if we are in distributed mode\n params.is_main = params.node_id == 0 and params.local_rank == 0\n params.multi_node = params.n_nodes > 1\n params.multi_gpu = params.world_size > 1\n\n # summary\n PREFIX = \"%i - \" % params.global_rank\n\n # set GPU device\n if params.is_distributed:\n torch.cuda.set_device(params.local_rank)\n device = torch.device(\"cuda\", params.local_rank)\n else:\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n params.device = device\n\n # summary\n PREFIX = \"%i - \" % params.global_rank\n print(PREFIX + \"Number of nodes: %i\" % params.n_nodes)\n print(PREFIX + \"Node ID : %i\" % params.node_id)\n print(PREFIX + \"Local rank : %i\" % params.local_rank)\n print(PREFIX + \"Global rank : %i\" % params.global_rank)\n print(PREFIX + \"World size : %i\" % params.world_size)\n print(PREFIX + \"GPUs per node : %i\" % params.n_gpu_per_node)\n print(PREFIX + \"Multi-node : %s\" % str(params.multi_node))\n print(PREFIX + \"Multi-GPU : %s\" % str(params.multi_gpu))\n print(PREFIX + \"Hostname : %s\" % socket.gethostname())\n\n # initialize multi-GPU\n if params.is_distributed:\n\n # http://pytorch.apachecn.org/en/0.3.0/distributed.html#environment-variable-initialization\n # 'env://' will read these environment variables:\n # MASTER_PORT - required; has to be a free port on machine with rank 0\n # MASTER_ADDR - required (except for rank 0); address of rank 0 node\n # WORLD_SIZE - required; can be set either here, or in a call to init function\n # RANK - required; can be set either here, or in a call to init function\n\n #print(\"Initializing PyTorch distributed ...\")\n torch.distributed.init_process_group(\n init_method='env://',\n backend='nccl',\n )", "def i_am_root():\n try:\n return True if mpi_rank() == 0 else False\n except AttributeError:\n # not running MPI\n return True", "def test_empty(self):\n df = dep.read_env(get_path('empty_env.txt'))\n self.assertEquals(len(df.index), 0)", "def test_local_env_pass_explicit(fileutils) -> None:\n exp_value = str(uuid.uuid4())\n env_key = \"test_local_env_pass_explicit\"\n\n assert env_key not in os.environ\n\n test_dir = fileutils.make_test_dir()\n script = fileutils.get_test_conf_path(\"check_env.py\")\n\n exp_dir = f\"{test_dir}/exp\"\n os.makedirs(exp_dir)\n exp = Experiment(\"LRZ\", exp_path=exp_dir, launcher=\"slurm\")\n\n exe_name = \"python\"\n exe_args = [script, env_key]\n\n # Create the RunSettings associated with the workload manager (WLM) run command\n run_args = {\"--nodes\": 1, \"--ntasks\": 1, \"--time\": \"00:01:00\"}\n env_vars = {env_key: exp_value} # <-- explicitly passing a new env var to task\n settings = RunSettings(\n exe_name, exe_args, run_command=\"srun\", run_args=run_args, env_vars=env_vars\n )\n app_name = \"echo_app\"\n app = exp.create_model(app_name, settings)\n\n # generate the experiment structure and start the model\n exp.generate(app, overwrite=True)\n exp.start(app, block=True, summary=False)\n\n assert env_key in settings.env_vars\n\n with open(f\"{exp_dir}/{app_name}/{app_name}.out\") as app_outfile:\n app_output = app_outfile.read()\n \n # verify application was able to access the env var\n assert f\"{env_key}=={exp_value}\" in app_output", "def check_environment() -> None:\n for item in ['IB_USER', 'IB_PASSWORD', 'IB_URL']:\n if os.getenv(item) is None:\n raise click.UsageError(f'{item} environment variable must be set before using ib.')", "def test_no_D2_ENVIRONMENT(self):\n self.assertIsNone(os.environ.get('D2_ENVIRONMENT'))", "def test_no_D2_ENVIRONMENT(self):\n self.assertIsNone(os.environ.get('D2_ENVIRONMENT'))", "def autoset_numerical_parameters():\n testenv = env(\n Ndim=N_DIMS,\n lambda_over_dx=LAMBDA_OVER_DX,\n R_dt=R_DT,\n norm_Poisson=NORM_POISSON,\n Ngrid=N_GRID,\n Nhits=N_HITS,\n dummy=True,\n )\n if STOP_t is None:\n if N_DIMS == 1:\n stop_t = int(round(4 * testenv.N))\n else:\n if testenv.mu0_Poisson < 1e-3:\n stop_t = 10 * testenv.N ** N_DIMS\n elif testenv.mu0_Poisson < 1:\n stop_t = int(round(5 * 10 ** N_DIMS * LAMBDA_OVER_DX / np.sqrt(testenv.mu0_Poisson)))\n else:\n stop_t = int(round(5 * 10 ** N_DIMS * LAMBDA_OVER_DX))\n else:\n stop_t = STOP_t\n\n if N_RUNS is None:\n # predefined for REL_TOL = 0.01\n if N_DIMS == 1:\n Nruns = 16000\n elif N_DIMS == 2:\n Nruns = 6400\n elif N_DIMS == 3:\n Nruns = 25600\n elif N_DIMS == 4:\n Nruns = 102400\n else:\n raise Exception(\"Nruns not pre-defined for N_DIMS > 4\")\n Nruns = int(Nruns * (0.01 / REL_TOL) ** 2)\n else:\n Nruns = N_RUNS\n\n if MAX_N_RUNS is None:\n max_Nruns = MAX_N_RUNS\n else:\n max_Nruns = 10 * Nruns\n\n if ADAPTIVE_N_RUNS or WITH_MPI:\n Nruns = int(N_PARALLEL * (np.ceil(Nruns / N_PARALLEL))) # make it multiple of N_PARALLEL\n max_Nruns = int(N_PARALLEL * (np.ceil(max_Nruns / N_PARALLEL))) # make it multiple of N_PARALLEL\n\n return testenv.N, testenv.Nhits, stop_t, Nruns, max_Nruns, testenv.mu0_Poisson", "def _check_initialization_value(arg_dict, mode):\n valid_values = [\"host\" , \"network\"]\n given_value = arg_dict[mode].lower()\n if given_value in valid_values:\n return 0\n else:\n return -1", "def test_workflow_environment():\n config = {\n \"workflow-name\": \"workflow\",\n \"cluster-type\": CLUSTER_TYPE,\n \n \"environment-variables\": {\n \"FOO\": \"BAR\",\n \"FOO2\": \"BAR2\"\n }\n }\n \n template_dir = tempfile.mkdtemp(suffix=\"test-workflow-environment-template\")\n with open(f\"{template_dir}/workflow.yaml\", 'w') as f:\n yaml.dump(config, f)\n \n @checkrun\n def execute(workflow_inst):\n def _check():\n assert os.environ['FOO'] == \"BAR\"\n assert os.environ[\"OMP_NUM_THREADS\"] == '1'\n return True\n \n # driver env\n _check()\n \n # worker env\n assert all(workflow_inst.run_on_each_worker(_check).values())\n \n os.environ['FOO'] = 'ORIGINAL_FOO'\n _execution_dir, _workflow = launch_flow(template_dir, 1, _custom_execute_fn=execute)\n assert execute.didrun\n \n # Environment is restored after execution is finished.\n assert os.environ['FOO'] == 'ORIGINAL_FOO'\n assert 'FOO2' not in os.environ", "def check_envs(env, pol):\n assert env.Ndim == N_DIMS\n assert env.lambda_over_dx == LAMBDA_OVER_DX\n assert env.R_dt == R_DT\n assert env.mu0_Poisson == MU0_POISSON\n assert env.norm_Poisson == NORM_POISSON\n assert env.N == N_GRID\n assert env.Nhits == N_HITS\n assert not env.draw_source\n \n assert pol.env == env\n assert pol.policy_index == POLICY\n if POLICY != -1:\n assert pol.steps_ahead == STEPS_AHEAD", "def test_is_empty_nc_mode_env(self) -> None:\n if os.environ.get(\"NC_MODE\", None) is not None:\n del os.environ[\"NC_MODE\"]\n is_develop = is_development_env()\n self.assertFalse(is_develop)", "def guarantee_initialized_variables(self):\n\n global_vars = tf.global_variables()\n is_not_initialized = self.sess.run([tf.is_variable_initialized(var) for var in global_vars])\n not_initialized_vars = [v for (v, f) in zip(global_vars, is_not_initialized) if not f]\n\n for x in ['[#] Initialized: ' + str(i.name) for i in\n not_initialized_vars]:\n print(x)\n\n if len(not_initialized_vars):\n self.sess.run(tf.variables_initializer(not_initialized_vars))\n return True\n else:\n return False", "def test_rank(self):\n self.assertEqual(self.vectors.rank('dog.n.01', 'dog.n.01'), 1)\n self.assertEqual(self.vectors.rank('dog.n.01', 'carnivore.n.01'), 3)", "def test_no_existing_value(self):\n var_name = \"PICCOLO_TEST_1\"\n\n # Make sure it definitely doesn't exist already\n if os.environ.get(var_name) is not None:\n del os.environ[var_name]\n\n new_value = \"hello world\"\n\n with set_env_var(var_name=var_name, temp_value=new_value):\n self.assertEqual(os.environ.get(var_name), new_value)\n\n self.assertEqual(os.environ.get(var_name), None)", "def validateRedditEnvironment():\r\n\r\n env_variables = ['REDDIT_CLIENT_ID', 'REDDIT_CLIENT_SECRET']\r\n missingEnvVariable = False\r\n\r\n for variable in env_variables:\r\n variableValue = os.environ.get(variable)\r\n if (variableValue == None):\r\n print(\"Missing env variable: \" + variable)\r\n missingEnvVariable = True\r\n\r\n return not missingEnvVariable", "def _validate_env(self) -> None:\n use_ovs = self.config.get(\"ovs\") == \"1\"\n for requirement in get_requirements(use_ovs):\n utils.which(requirement, required=True)", "def verify_environment():\n reqs = ['NAME', 'RECIPIENT', 'SUBJECT', 'MESSAGE',\n 'MAILGUN_API_KEY', 'MAILGUN_DOMAIN']\n for req in reqs:\n if not os.getenv(req):\n logging.error('Environment variable ' + req + ' is not set')\n sys.exit(2)", "def test_int(self, env: yaenv.Env):\n _val = env.int('INT_VAR')\n assert _val == 1 and type(_val) == int\n _val = env.int('MISSING', -2)\n assert _val == -2 and type(_val) == int\n with pytest.raises(yaenv.EnvError) as err:\n _ = env.int('LIST_VAR')\n assert 'Invalid integer' in str(err.value)\n assert env.int('MISSING') is None" ]
[ "0.6818698", "0.6449645", "0.61541635", "0.57703334", "0.5661064", "0.5612566", "0.5535392", "0.5509749", "0.5493569", "0.54028124", "0.5381893", "0.5332986", "0.5329292", "0.5304521", "0.52791685", "0.52758074", "0.52317387", "0.52317387", "0.52295375", "0.52202594", "0.51899344", "0.5182167", "0.51657504", "0.5165395", "0.5156173", "0.514878", "0.5144014", "0.5131102", "0.5130741", "0.5117312" ]
0.7357966
0
Test that function is not called when rank environment variables are not global zero.
def test_rank_zero_none_set(rank_key, rank): with mock.patch.dict(os.environ, {rank_key: rank}): from pytorch_lightning.utilities.distributed import _get_rank, rank_zero_only rank_zero_only.rank = _get_rank() @rank_zero_only def foo(): return 1 x = foo() assert x is None
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_rank_zero_known_cluster_envs(env_vars: Mapping[str, str]):\n from pytorch_lightning.utilities.distributed import _get_rank, rank_zero_only\n\n rank_zero_only.rank = _get_rank()\n\n with mock.patch.dict(os.environ, env_vars):\n from pytorch_lightning.utilities.distributed import _get_rank, rank_zero_only\n\n rank_zero_only.rank = _get_rank()\n\n @rank_zero_only\n def foo(): # The return type is optional because on non-zero ranks it will not be called\n return 1\n\n x = foo()\n assert x == 1", "def test_rank_zero_only():\n os.environ[\"RANK\"] = \"0\"\n # check that wrapping instance work\n timer = pt_clb.rank_zero_only(pt_clb.Timer())\n assert hasattr(timer, \"timer\")\n\n os.environ[\"RANK\"] = \"1\"\n # check that wrapping class also works\n timer = pt_clb.rank_zero_only(pt_clb.Timer)()\n assert not hasattr(timer, \"timer\")", "def _assert_local_rank_set(self):\n assert self.local_rank >= 0, 'The environment variable LOCAL_RANK is not set, thus the coordinator is not aware of the local rank of the current process.'", "def ignore_builtin_verification():\n return not current_space().skip_builtin_verification", "def validate_unity_env(func):\n\n def wrapper(cls, *args, **kwargs):\n if cls.state == EnvEnum.dead:\n msg = \"Must Reset Kernel - due to bug in UnityAgents\"\n print(msg)\n return func(cls, *args, **kwargs)\n\n return wrapper", "def test_special_zero(self):\n x = py_function(0)\n if x != 100:\n self.fail(\"Zero is special, py_function(0) did not return 100\")", "def test_empty_functions():", "def global_check(self):\n return None", "def test_ns_fail2():\n env = NsSimPyEnvironment()\n env.process(some_process(env, 4e-29))\n env.run()", "def test_global():\n global_assumptions.add(x > 0)\n assert (x > 0) in global_assumptions\n global_assumptions.remove(x > 0)\n assert not (x > 0) in global_assumptions\n # same with multiple of assumptions\n global_assumptions.add(x > 0, y > 0)\n assert (x > 0) in global_assumptions\n assert (y > 0) in global_assumptions\n global_assumptions.clear()\n assert not (x > 0) in global_assumptions\n assert not (y > 0) in global_assumptions", "def test_ns_fail():\n env = NsSimPyEnvironment()\n env.process(some_process(env, 10.1))\n env.run()", "def nottest(func):\n func.__test__ = False\n return func", "def rank_zero_only(fn):\n\n def wrapped(*args, **kwargs):\n if rank() == 0:\n return fn(*args, **kwargs)\n\n return wrapped", "def test_find_unused_parameters_when_unused_parameters_empty(self):\n\n class FindUnusedParamModule(nn.Module):\n def __init__(self):\n super().__init__()\n self.t0 = Task()\n self.t1 = Task()\n\n def task_parameters(self):\n return (self.t0.p, self.t1.p)\n\n def forward(self, x, rank):\n return self.t1(self.t0(x)) if rank == 0 else self.t1(x)\n\n def run_and_verify_grad(model):\n # Run forward\n output = model(8, self.rank)\n\n # The grads of all parameters should be None at this point.\n [self.assertIsNone(t_p.grad) for t_p in model.module.task_parameters()]\n\n # Run backward\n output.mean().backward()\n\n # Now locally unused parameter should have grad updated on all ranks.\n [self.assertIsNotNone(t_p.grad) for t_p in model.module.task_parameters()]\n\n process_group = self._get_process_group()\n\n # Test on CPU\n cpu_model = DistributedDataParallel(\n FindUnusedParamModule().cpu(),\n process_group=process_group,\n find_unused_parameters=True,\n )\n run_and_verify_grad(cpu_model)\n\n # Test on GPU\n device_id = gpus_for_rank(self.world_size)[self.rank][0]\n gpu_model = DistributedDataParallel(\n FindUnusedParamModule().to(device_id),\n device_ids=[device_id],\n process_group=process_group,\n find_unused_parameters=True,\n )\n run_and_verify_grad(gpu_model)", "def test_is_empty_nc_mode_env(self) -> None:\n if os.environ.get(\"NC_MODE\", None) is not None:\n del os.environ[\"NC_MODE\"]\n is_develop = is_development_env()\n self.assertFalse(is_develop)", "def rank_zero_only(fn):\n\n @wraps(fn)\n def wrapped_fn(self, *args, **kwargs):\n if self.rank == 0:\n fn(self, *args, **kwargs)\n\n return wrapped_fn", "def test_rng_null(self):\n assert check_random_state(None) is np.random.mtrand._rand", "def global_exists(self, global_name):\n return self.evaluate('!(typeof %s === \"undefined\");' %\n global_name)", "def test_noop(self):\n base_env = _DiscreteEnvironmentOneReward(\n action_dtype=np.int64,\n reward_spec=specs.Array(dtype=np.float32, shape=()))\n wrapped_env = wrappers.DelayedRewardWrapper(base_env, accumulation_period=1)\n base_episode_reward = _episode_reward(base_env)\n wrapped_episode_reward = _episode_reward(wrapped_env)\n self.assertEqual(base_episode_reward, wrapped_episode_reward)", "def test_no_default_value(self):\n dim = Integer(\"yolo\", \"uniform\", -3, 4)\n assert dim.default_value is None", "def test_no_D2_ENVIRONMENT(self):\n self.assertIsNone(os.environ.get('D2_ENVIRONMENT'))", "def test_no_D2_ENVIRONMENT(self):\n self.assertIsNone(os.environ.get('D2_ENVIRONMENT'))", "def test_no_existing_value(self):\n var_name = \"PICCOLO_TEST_1\"\n\n # Make sure it definitely doesn't exist already\n if os.environ.get(var_name) is not None:\n del os.environ[var_name]\n\n new_value = \"hello world\"\n\n with set_env_var(var_name=var_name, temp_value=new_value):\n self.assertEqual(os.environ.get(var_name), new_value)\n\n self.assertEqual(os.environ.get(var_name), None)", "def nulltest():", "def testMonitorInitGlobalAttributes(self):\n self.assertEquals(monitor.monitor_request, None)\n self.assertEquals(monitor.monitor_memory, None)", "def _message_when_root(func):\n\n def decorated(*args, **kwargs):\n from armi import MPI_RANK\n\n if MPI_RANK == 0:\n func(*args, **kwargs)\n\n return decorated", "def test_defaults():\n config = Config(\n env_var='DO_NOT_USE',\n env_prefix='DO_NOT_USE',\n entry_point_name='DO_NOT_USE',\n )\n\n assert not config.keys()", "def test_no_default_value(self):\n dim = Real(\"yolo\", \"uniform\", -3, 4)\n assert dim.default_value is None", "def test_no_var_init(self):\n self._test_reports_helper({\"--no-var-init-profiling\": \"\"},\n [\"report.txt\"])", "def test_without_parameters():\n assert divide() is math.nan" ]
[ "0.7123143", "0.63766265", "0.62233394", "0.5965803", "0.5875504", "0.5828639", "0.58116204", "0.56961274", "0.56833506", "0.5677485", "0.56677", "0.5659446", "0.56122255", "0.56006694", "0.55998755", "0.559386", "0.55727184", "0.55625874", "0.5549769", "0.55450904", "0.5526652", "0.5526652", "0.5506102", "0.548529", "0.5471954", "0.5463142", "0.5450702", "0.54425263", "0.5427786", "0.54221874" ]
0.6874552
1
Read SQuAD data, and filter by passage and question length.
def read_data(squad_train_path, squad_dev_path, max_passage_length, max_question_length, min_token_count): squad_reader = SquadReader() # Read SQuAD train set train_dataset = squad_reader.read(squad_train_path) logger.info("Read {} training examples".format(len(train_dataset))) # Filter out examples with passage length greater than max_passage_length # or question length greater than max_question_length logger.info("Filtering out examples in train set with passage length " "greater than {} or question length greater than {}".format( max_passage_length, max_question_length)) train_dataset = [ instance for instance in tqdm(train_dataset) if len(instance.fields["passage"].tokens) <= max_passage_length and len(instance.fields["question"].tokens) <= max_question_length] logger.info("{} training examples remain after filtering".format( len(train_dataset))) # Make a vocabulary object from the train set train_vocab = Vocabulary.from_instances( train_dataset, min_count={'min_token_count': min_token_count}) # Read SQuAD validation set logger.info("Reading SQuAD validation set at {}".format( squad_dev_path)) validation_dataset = squad_reader.read(squad_dev_path) logger.info("Read {} validation examples".format( len(validation_dataset))) # Filter out examples with passage length greater than max_passage_length # or question length greater than max_question_length logger.info("Filtering out examples in validation set with passage length " "greater than {} or question length greater than {}".format( max_passage_length, max_question_length)) validation_dataset = [ instance for instance in tqdm(validation_dataset) if len(instance.fields["passage"].tokens) <= max_passage_length and len(instance.fields["question"].tokens) <= max_question_length] logger.info("{} validation examples remain after filtering".format( len(validation_dataset))) return train_dataset, train_vocab, validation_dataset
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def read(self, input_file, remove_evidence=False, remove_question=False, remove_passage=False, remove_dict=None):\n logger.info('Reading data set from {}...'.format(input_file))\n logger.info('Remove evidence during test: {}'.format(remove_evidence))\n with open(input_file, \"r\", encoding='utf-8') as reader:\n input_data = json.load(reader)\n\n def is_whitespace(ch):\n if ch == \" \" or ch == \"\\t\" or ch == \"\\r\" or ch == \"\\n\" or ord(ch) == 0x202F:\n return True\n return False\n\n examples = []\n for instance in tqdm(input_data):\n sentences = instance['article']\n article_id = instance['id']\n\n sentence_start_list, sentence_end_list = [], []\n passage = ''\n for sentence in sentences:\n sentence = sentence.strip()\n sentence_start_list.append(len(passage))\n passage = passage + sentence + ' '\n sentence_end_list.append(len(passage) - 1)\n assert sentence_start_list[-1] <= sentence_end_list[-1]\n # if len(examples) == 453:\n # print(sentence)\n # print(sentence_start_list[-1], sentence_end_list[-1])\n\n doc_tokens = []\n prev_is_whitespace = True\n char_to_word_offset = []\n for c in passage:\n if is_whitespace(c):\n prev_is_whitespace = True\n else:\n if prev_is_whitespace:\n doc_tokens.append(c)\n else:\n doc_tokens[-1] += c\n prev_is_whitespace = False\n char_to_word_offset.append(len(doc_tokens) - 1)\n\n # Split context into sentences\n # sentence_start_list, sentence_end_list = utils.split_sentence(passage, self.sentence_tokenizer)\n sentence_span_list = []\n for c_start, c_end in zip(sentence_start_list, sentence_end_list):\n t_start = char_to_word_offset[c_start]\n t_end = char_to_word_offset[c_end]\n sentence_span_list.append((t_start, t_end))\n assert t_start <= t_end\n\n questions = instance['questions']\n answers = instance['answers']\n options = instance['options']\n evidences = instance['evidences']\n # multi_sents = instance['multi_sents']\n\n for q_id, (question, option_list, option_answer_list, evidence) in enumerate(zip(questions, options, answers, evidences)):\n\n if remove_evidence:\n new_doc_tokens, new_sentence_span_list = utils.remove_all_evidence(sentence_span_list, doc_tokens, evidence)\n evidence = []\n else:\n new_doc_tokens = doc_tokens\n new_sentence_span_list = sentence_span_list\n\n # qas_id = f\"{article_id}--{q_id}\"\n for op_id, (option, answer) in enumerate(zip(option_list, option_answer_list)):\n qas_id = f\"{article_id}--{q_id}--{op_id}\"\n example = MultiRCExample(\n qas_id=qas_id,\n # doc_tokens=doc_tokens,\n doc_tokens=new_doc_tokens,\n question_text=question,\n # sentence_span_list=sentence_span_list,\n sentence_span_list=new_sentence_span_list,\n option_text=option,\n answer=answer,\n sentence_ids=evidence\n )\n examples.append(example)\n\n logger.info('Finish reading {} examples from {}'.format(len(examples), input_file))\n return examples", "def load_as_raw(self):\n\n # Q & A\n questions, answers = self.get_questions_answers()\n\n # Get vocabs\n\n # Step 4: cleaning the questions\n pprint('---- Step 4 cleaning questions ----')\n\n clean_questions = []\n for question in questions:\n clean_questions.append(clean_text(question))\n\n pprint(clean_questions, stream=Head(5))\n print('\\n\\n')\n \"\"\"\n Step 5: Clean the answers\n \"\"\"\n\n pprint('---- Step 5 cleaning answers ----')\n clean_answers = []\n for answer in answers:\n clean_answers.append(clean_text(answer))\n\n pprint(clean_answers, stream=Head(5))\n print('\\n\\n')\n \"\"\"\n Step 6: Creating a dictionary that maps each word to its number of occurences\n \"\"\"\n\n word2count = {}\n pprint('------ Step 6: counting words in questions ----')\n\n word2count = convert_word_to_count(word2count, clean_questions)\n\n pprint(word2count, stream=Head(5))\n print('\\n\\n')\n \"\"\"\n Step 7:\n For example, for a question: can we make this quick roxanne korrine and andrew barrett are having an incredibly horrendous public break up on the quad again\n It counts each word occurence such as \"can\" and accumulates the count into word2count dict\n \"\"\"\n pprint('------ Step 6: counting words in answers ----')\n\n word2count = convert_word_to_count(word2count, clean_answers)\n\n pprint(word2count, stream=Head(5))\n print('\\n\\n')\n\n keys = ['<unk>', '<s>', '</s>']\n\n \"\"\"\n Step 8: Creating word 2 int(count) by filtering words that are greater than the threshold\n \"\"\"\n\n pprint(\n '------ Step 8: questions_vocabs filtered by threshold (>) ----')\n threshold_questions = 20\n questions_vocabs = [] + keys\n for word, count in word2count.items():\n if count >= threshold_questions:\n if not word in questions_vocabs:\n questions_vocabs.append(word)\n\n pprint(questions_vocabs, stream=Head(5))\n print('\\n\\n')\n \"\"\"\n Step 9: Same as step 8 but for answers\n \"\"\"\n pprint(\n '------ Step 9: answers_vocabs filtered by threshold (>) ----')\n threshold_answers = 20\n answers_vocabs = [] + keys\n for word, count in word2count.items():\n if count >= threshold_answers:\n if not word in answers_vocabs:\n answers_vocabs.append(word)\n\n pprint(answers_vocabs, stream=Head(5))\n\n return questions, answers, questions_vocabs, answers_vocabs", "def read_squad_examples(input_file, return_answers, context_only=False, question_only=False,\n draft=False, draft_num_examples=12, append_title=False):\n with open(input_file, \"r\") as reader:\n input_data = json.load(reader)[\"data\"]\n\n examples = []\n ans_cnt = 0\n no_ans_cnt = 0\n\n # Only word-based tokenization is peformed (whitespace based)\n for doc_idx, entry in enumerate(input_data):\n title = entry['title'][0] if type(entry['title']) == list else entry['title']\n assert type(title) == str\n\n for par_idx, paragraph in enumerate(entry[\"paragraphs\"]):\n # Do not load context for question only\n if not question_only:\n paragraph_text = paragraph[\"context\"]\n title_offset = 0\n if append_title:\n title_str = '[ ' + ' '.join(title.split('_')) + ' ] '\n title_offset += len(title_str)\n paragraph_text = title_str + paragraph_text\n # Note that we use the term 'word' for whitespace based words, and 'token' for subtokens (for BERT input)\n doc_words, char_to_word_offset = context_to_words_and_offset(paragraph_text)\n\n # 1) Context only ends here\n if context_only:\n metadata = {}\n if \"pubmed_id\" in entry:\n entry_keys = [\n \"pubmed_id\", \"sha\", \"title_original\", \"title_entities\",\n \"journal\", \"authors\", \"article_idx\"\n ]\n para_keys = [\"context_entities\"]\n for entry_key in entry_keys:\n if entry_key in entry:\n metadata[entry_key] = entry[entry_key]\n for para_key in para_keys:\n if para_key in paragraph:\n metadata[para_key] = paragraph[para_key]\n # metadata[\"pubmed_id\"] = (metadata[\"pubmed_id\"] if not pd.isnull(metadata[\"pubmed_id\"])\n # else 'NaN')\n example = SquadExample(\n doc_words=doc_words,\n title=title,\n doc_idx=doc_idx,\n par_idx=par_idx,\n metadata=metadata)\n examples.append(example)\n\n if draft and len(examples) == draft_num_examples:\n return examples\n continue\n\n # 2) Question only or 3) context/question pair\n else:\n for qa in paragraph[\"qas\"]:\n qas_id = str(qa[\"id\"])\n question_text = qa[\"question\"]\n\n # Noisy question skipping\n if len(question_text.split(' ')) == 1:\n logger.info('Skipping a single word question: {}'.format(question_text))\n continue\n if \"I couldn't could up with another question.\" in question_text:\n logger.info('Skipping a strange question: {}'.format(question_text))\n continue\n\n start_position = None\n end_position = None\n orig_answer_text = None\n\n # For pre-processing that should return answers together\n if return_answers:\n assert type(qa[\"answers\"]) == dict or type(qa[\"answers\"]) == list, type(qa[\"answers\"])\n if type(qa[\"answers\"]) == dict:\n qa[\"answers\"] = [qa[\"answers\"]]\n\n # No answers\n if len(qa[\"answers\"]) == 0:\n orig_answer_text = \"\"\n start_position = -1 # Word-level no-answer => -1\n end_position = -1\n no_ans_cnt += 1\n # Answer exists\n else:\n answer = qa[\"answers\"][0]\n ans_cnt += 1\n\n orig_answer_text = answer[\"text\"]\n answer_offset = answer[\"answer_start\"] + title_offset\n answer_length = len(orig_answer_text)\n start_position = char_to_word_offset[answer_offset]\n end_position = char_to_word_offset[answer_offset + answer_length - 1]\n\n # Only add answers where the text can be exactly recovered from the context\n actual_text = \" \".join(doc_words[start_position:(end_position + 1)])\n cleaned_answer_text = \" \".join(\n tokenization.whitespace_tokenize(orig_answer_text)) # word based tokenization\n if actual_text.find(cleaned_answer_text) == -1:\n logger.warning(\"Could not find answer: '%s' vs. '%s'\",\n actual_text, cleaned_answer_text)\n continue\n\n # Question only ends here\n if question_only:\n example = SquadExample(\n qas_id=qas_id,\n question_text=question_text)\n\n # Context/question pair ends here\n else:\n example = SquadExample(\n qas_id=qas_id,\n question_text=question_text,\n paragraph_text=paragraph_text,\n doc_words=doc_words,\n orig_answer_text=orig_answer_text,\n start_position=start_position,\n end_position=end_position,\n title=title,\n doc_idx=doc_idx,\n par_idx=par_idx)\n examples.append(example)\n\n if draft and len(examples) == draft_num_examples:\n return examples\n\n # Testing for shuffled draft (should comment out above 'draft' if-else statements)\n if draft:\n random.shuffle(examples)\n logger.info(str(len(examples)) + ' were collected before draft for shuffling')\n return examples[:draft_num_examples]\n\n logger.info('Answer/no-answer stat: %d vs %d'%(ans_cnt, no_ans_cnt))\n return examples", "def condolidateReads(options):\n input_filename=options.adapter_trimmed_filename\n output_filename=options.consolidated_filename\n fhw=open(output_filename,\"w\")\n #original_data=readFastqFile(input_filename)\n fhr=open(input_filename,\"r\")\n data={}\n while True:\n line=fhr.readline().strip()\n if not line:\n break\n id=line\n seq=fhr.readline().strip()\n useless=fhr.readline()\n quality=fhr.readline()\n if seq not in data:\n data[seq]=1\n else:\n data[seq]+=1\n for seq_num,seq in enumerate(data):\n fhw.write(\">read_\"+str(seq_num+1)+\"_\"+str(data[seq])+\"\\n\"+seq+\"\\n\")\n fhw.close()", "def readlen(store, cutoff=30, filter_srrs=None, keep_srrs=None):\n df = store['prealn/workflow/fastq'].copy()\n df.reset_index(inplace=True)\n df = remove_rows(df, 'srr', filter_srrs)\n df = keep_rows(df, 'srr', keep_srrs)\n df['len'] = df[['avgLen_R1', 'avgLen_R2']].max(axis=1)\n\n return df.loc[df['len'] >= cutoff, ['srx', 'srr']]", "def test_reader(qn_filepath, answers_dirpath):\n qns = get_questions(qn_filepath)\n for qn in qns:\n if qn.qid == 100:\n q = qn\n break\n assert q\n docs = get_documents(answers_dirpath, q.qid)\n print docs\n print docs[0].content", "def readability_measurements(passage: str):\n results = readability.getmeasures(passage, lang='en')\n \n chars_per_word = results['sentence info']['characters_per_word']\n syll_per_word = results['sentence info']['syll_per_word']\n words_per_sent = results['sentence info']['words_per_sentence']\n \n kincaid = results['readability grades']['Kincaid']\n ari = results['readability grades']['ARI']\n coleman_liau = results['readability grades']['Coleman-Liau']\n flesch = results['readability grades']['FleschReadingEase']\n gunning_fog = results['readability grades']['GunningFogIndex']\n lix = results['readability grades']['LIX']\n smog = results['readability grades']['SMOGIndex']\n rix = results['readability grades']['RIX']\n dale_chall = results['readability grades']['DaleChallIndex']\n \n tobeverb = results['word usage']['tobeverb']\n auxverb = results['word usage']['auxverb']\n conjunction = results['word usage']['conjunction']\n pronoun = results['word usage']['pronoun']\n preposition = results['word usage']['preposition']\n nominalization = results['word usage']['nominalization']\n \n pronoun_b = results['sentence beginnings']['pronoun']\n interrogative = results['sentence beginnings']['interrogative']\n article = results['sentence beginnings']['article']\n subordination = results['sentence beginnings']['subordination']\n conjunction_b = results['sentence beginnings']['conjunction']\n preposition_b = results['sentence beginnings']['preposition']\n \n return [chars_per_word, syll_per_word, words_per_sent,\n kincaid, ari, coleman_liau, flesch, gunning_fog, lix, smog, rix, dale_chall,\n tobeverb, auxverb, conjunction, pronoun, preposition, nominalization,\n pronoun_b, interrogative, article, subordination, conjunction_b, preposition_b]", "def _read_qfile(qfile, periods):\n\n with open(qfile, 'r') as fid:\n n_lines = int(fid.readline())\n\n qf = pd.read_csv(qfile, header=None, skiprows=n_lines+1, sep='\\s+')\n qf.columns = ['n', 'l', 'w_mHz', 'Q', 'phi', 'ph_vel',\n 'gr_vel', 'ph_vel_qcorrected', 'T_qcorrected', 'T_sec']\n qf = qf[::-1]\n qf = qf[qf['n'] == 0] # Fundamental mode only\n qf.reset_index(drop=True, inplace=True)\n\n ph_vel = np.interp(periods, qf.T_qcorrected, qf.ph_vel_qcorrected)\n\n return ph_vel", "def import_squad_data():\n\n squad_url = (\n \"https://rajpurkar.github.io/SQuAD-explorer/dataset/dev-v2.0.json\"\n )\n squad_file = squad_url.split(\"/\")[-1] # last part of URL\n\n urllib.request.urlretrieve(squad_url, squad_file)\n\n if not os.path.isfile(squad_file):\n sys.exit(\"Dataset %s does not exist!\" % squad_file)\n\n with open(squad_file) as squad_file_handle:\n squad_data = json.load(squad_file_handle)[\"data\"]\n\n title_list = []\n ident_list = []\n context_list = []\n question_list = []\n impossible_list = []\n answer_start_list = []\n answer_text_list = []\n\n # 'data' contains title and paragraph list\n for it_art in squad_data:\n title = it_art[\"title\"]\n\n # 'paragraphs' contains context (the copy) and Q&A sets\n for it_par in it_art[\"paragraphs\"]:\n context = it_par[\"context\"]\n\n # 'qas' contains questions and reference answers\n for it_que in it_par[\"qas\"]:\n question = it_que[\"question\"]\n impossible = it_que[\"is_impossible\"]\n ident = it_que[\"id\"]\n\n # 'answers' contains the answer text and location in 'context'\n for it_ans in it_que[\"answers\"]:\n answer_start = it_ans[\"answer_start\"]\n text = it_ans[\"text\"]\n\n # set an empty answer for an impossible question\n if impossible:\n text = \"\"\n\n # add details of this answer to the list\n title_list.append(title)\n ident_list.append(ident)\n context_list.append(context)\n question_list.append(question)\n impossible_list.append(impossible)\n answer_start_list.append(answer_start)\n answer_text_list.append(text)\n\n squad_data_final = pandas.DataFrame(\n {\n \"id\": ident_list,\n \"subject\": title_list,\n \"context\": context_list,\n \"question\": question_list,\n \"clean_question\": [clean(question) for question in question_list],\n \"impossible\": impossible_list,\n \"answer_start\": answer_start_list,\n \"answer\": answer_text_list,\n }\n )\n\n return squad_data_final.drop_duplicates(keep=\"first\")", "def read_transcript_data(fn):\n\n def _read_lines(fn):\n # NC_000007.13\tRefSeq\tcDNA_match\t50344265\t50344518\t254\t+\t.\tID=aln58042;Target=NM_001220765.2 1 254 +;gap_count=0;identity=0.0691326;idty=1;num_ident=428;num_mismatch=0;pct_coverage=6.91326;pct_identity_gap=100;pct_identity_ungap=100;score=254\n # NC_000002.11 RefSeq cDNA_match 179671939 179672150 212 - . ID=ed951d46-194c-477a-a480-4bc64530c5ba;Target=NM_001267550.2 1 212 +;gap_count=0;identity=0.999991;idty=1;num_ident=109223;num_mismatch=1;pct_coverage=100;pct_identity_gap=99.9991;pct_identity_ungap=99.9991\n line_re = re.compile(\n \"(?P<ref_ac>\\S+)\\s+(?P<origin>\\S+)\\s+(?P<match_type>\\S+)\\s+\"\n \"(?P<g_start>\\d+)\\s+(?P<g_end>\\d+)\\s+(?P<score>\\S+)\\s+\"\n \"(?P<strand>[-+])\\s+\\.\\s+ID=(?P<aln>[^;]+);Target=(?P<tx_ac>\\S+)\"\n \"\\s+(?P<tx_start>\\d+)\\s+(?P<tx_end>\\d+).+?\"\n \"pct_coverage=(?P<pct_coverage>[^;]+);\"\n \"pct_identity_gap=(?P<pct_identity_gap>[^;]+);\"\n \"pct_identity_ungap=(?P<pct_identity_ungap>[^;]+)\"\n )\n fh = io.open(fn, \"rb\")\n while fh.peek(1)[0] == \"#\":\n fh.readline()\n while fh.peek(3)[0:3] != \"###\":\n line = fh.readline()\n try:\n yield line_re.match(line).groupdict()\n except AttributeError:\n raise Exception(\"Failed at\", line)\n raise StopIteration\n def _key(e):\n return (e[\"tx_ac\"], not e[\"ref_ac\"].startswith(\"NC_\"), e[\"ref_ac\"], e[\"aln\"])\n return itertools.groupby(sorted(_read_lines(fn), key=_key), key=_key)", "def parse_question_data(self):\n section = ''\n subsection = ''\n quest = ''\n # The data falls into 4 cases\n # 1. Sections\n # 2. subsections\n # 3. questions\n # 4. answers.\n\n for line in self.question_data: \n\n if \":\" in line: # case #2\n subsection = line.split(\":\")[1] # split the line on the : into an array but only take the [1] element\n debug(\"Subsection: %s\" % subsection)\n \n elif \".\" in line: # this is either a question or an answer?\n \n if line.split(\".\")[0].isdigit(): # case #3 it's a question, split on . into an array and take the element to the left and ask if it's a digit.\n quest = line # Since we know it's something like \"3. Are you a warlock?\" we stick that in the quest varable.\n debug(\"Question: %s\" % quest)\n # Create a question object and stick it in the dictonary with the key being the question (since we know it'll be unique)\n self.questions[quest] = question(section, subsection, quest) # I know it's redundant to have the key and have a value.\n \n elif line.startswith(\".\"): # case #4 answer All the answers startswith \".\" \n debug(\"Answer: %s\" % line)\n # take the question and append it to the answers array in the question object.\n self.questions[quest].answers.append(line[2:]) # Trim the first two characters off the answer since it's \". the answer\"\n \n else: # case #1 # This is section like AMERICAN DEMOCRACY\n section = line # load the line from the file into the section variable\n debug(\"Section = %s\" % section)", "def get_question():\n\n fi = open('nlpcc-iccpol-2016.kbqa.training-data','r',encoding='utf8')\n fii = open('nlpcc-iccpol-2016.kbqa.testing-data','r',encoding='utf8')\n\n q=''\n\n train = []\n countChar = {}\n m_word = 0\n i = 0\n for line in fi:\n# print(f'line: {line}')\n if line[1] == 'q':\n# print(f'line Q: {line}')\n q = line[line.index('\\t') + 1:].strip()\n if len(q) > m_word:\n m_word = len(q)\n train.append(q)\n# print(f'filtered Q: {q}')\n for char in q:\n if char not in countChar:\n countChar[char] = 1\n else:\n countChar[char] += 1\n# elif line[1] == 't':\n# print(f'line P: {line}')\n# sub = line[line.index('\\t') + 1:line.index(' |||')].strip()\n# qNSub = line[line.index(' ||| ') + 5:]\n# pre = qNSub[:qNSub.index(' |||')]\n# print(f'sub:{sub}')\n# print(f'qNSub:{qNSub}')\n# print(f'pre:{pre}')\n\n test = []\n for line in fii:\n# print(f'line: {line}')\n if line[1] == 'q':\n# print(f'line Q: {line}')\n q = line[line.index('\\t') + 1:].strip()\n if len(q) > m_word:\n m_word = len(q)\n test.append(q)\n# print(f'filtered Q: {q}')\n for char in q:\n if char not in countChar:\n countChar[char] = 1\n else:\n countChar[char] += 1\n \n \n with open('train.txt', 'w', encoding='utf-8') as f:\n f.write('\\n'.join(train))\n with open('test.txt', 'w', encoding='utf-8') as f:\n f.write('\\n'.join(test))\n \n # Save\n np.save('words.npy', countChar)\n \n print(m_word)\n\n# # Load npy dict\n# read_dictionary = np.load('my_file.npy').item()\n# print(read_dictionary['hello']) # displays \"world\"\n \n \n return m_word", "def read(self, sacc_data: sacc.Sacc) -> None:", "def read(self, sacc_data: sacc.Sacc) -> None:", "def read(self, sacc_data: sacc.Sacc) -> None:", "def readFastq(filename):\n sequences = []\n qualities = []\n \n with open(filename) as fh:\n while True:\n fh.readline() # skip name line\n seq = fh.readline().rstrip() #read base sequence\n fh.readline() # skip placeholder line\n qual = fh.readline().rstrip() # base quality line\n if len(seq) == 0:\n break\n sequences.append(seq)\n qualities.append(qual)\n \n return sequences, qualities", "def read_txt(self, widths=[3, 21, 4, 6, 4, 6, 12, 12]):\n cols = ['ID', 'SSSSSSSS.mmmuuun', 'AMP', 'THR', 'A-FRQ', 'R-FRQ', 'SIG STRNGTH', 'ABS-ENERGY']\n\n widths = widths\n self.data = pd.read_fwf(self.data_file, widths=widths, header=None, skiprows=self.skip_rows)\n self.data.columns = cols\n\n self.data = self.data.loc[self.data['ID'] == 1]\n self.skip_rows += len(self.data)", "def readFastq(filename):\n\tsequences = []\n\tqualities = []\n\twith open(filename, 'r') as f:\n\t\twhile True: \n\t\t\tf.readline() # skip name line\n\t\t\tseq = f.readline().rstrip()\n\t\t\tf.readline() # skip place holder line \n\t\t\tq = f.readline().rstrip()\n\t\t\tif len(seq) ==0:\n\t\t\t\tbreak \n\t\t\tsequences.append(seq)\n\t\t\tqualities.append(q)\n\treturn sequences, qualities", "def slice_from_reading(reading_path, waveforms_path, slice_duration=5, archive_definitions=[], output_level=0):\n if output_level >= 5:\n logging.info('Reading file: ' + reading_path)\n\n try:\n events = nordic_reader.read_nordic(reading_path, True) # Events tuple: (event.Catalog, [waveforms file names])\n except nordic_reader.NordicParsingError as error:\n if output_level >= 2:\n logging.warning('In ' + reading_path + ': ' + str(error))\n return -1\n except ValueError as error:\n if output_level >= 2:\n logging.warning('In ' + reading_path + ': ' + str(error))\n return -1\n except AttributeError as error:\n if output_level >= 2:\n logging.warning('In ' + reading_path + ': ' + str(error))\n return -1\n\n index = -1\n slices = []\n picks_line = \"STAT SP IPHASW\"\n for event in events[0].events:\n index += 1\n\n f = open(reading_path)\n l = [line.strip() for line in f]\n\n id = None\n picks_started = False\n picks_amount = len(event.picks)\n picks_read = 0\n picks_distance = []\n if config.seconds_high_precision:\n start_seconds = []\n for line in l:\n if picks_started and picks_read < picks_amount and len(line) >= 74:\n try:\n dist = float(line[70:74])\n except ValueError as e:\n dist = None\n picks_distance.append(dist)\n\n if config.seconds_high_precision:\n try:\n seconds = float(line[21:27])\n except ValueError as e:\n seconds = None\n start_seconds.append(seconds)\n\n if len(line) > 73:\n title = line[0:6]\n if title == \"ACTION\":\n id_title = line[56:59]\n if id_title == \"ID:\":\n id_str = line[59:73]\n id = int(id_str)\n\n if len(line) > 25:\n if line[0:len(picks_line)] == picks_line:\n picks_started = True\n\n # Min magnitude check\n if len(event.magnitudes) > 0:\n if event.magnitudes[0].mag < config.min_magnitude:\n continue\n\n # Max depth check\n if len(event.origins) > 0:\n if event.origins[0].depth is None:\n continue\n if event.origins[0].depth > config.max_depth:\n continue\n\n try:\n if len(event.picks) > 0: # Only for files with picks\n if output_level >= 3:\n logging.info('File: ' + reading_path + ' Event #' + str(index) + ' Picks: ' + str(len(event.picks)))\n\n picks_index = -1\n for pick in event.picks:\n if output_level >= 3:\n logging.info('\\t' + str(pick))\n\n picks_index += 1\n if config.seconds_high_precision:\n if picks_index < len(start_seconds):\n start_seconds_pick = start_seconds[picks_index]\n else:\n start_seconds_pick = pick.time.second\n print(\"OUT OF BOUNDS START SECONDS PICK\")\n print(\"FILE: \" + reading_path)\n print(\"PICKS: \")\n for pick_print in event.picks:\n print(str(pick_print))\n else:\n start_seconds_pick = pick.time.seconds\n pick_time = UTCDateTime(pick.time.year, pick.time.month, pick.time.day, pick.time.hour,\n pick.time.minute, start_seconds_pick)\n\n if picks_index < len(picks_distance) and picks_distance[picks_index] is not None:\n if picks_distance[picks_index] > config.max_dist:\n continue\n\n # Check phase\n if pick.phase_hint != 'S' and pick.phase_hint != 'P':\n logging.info('\\t' + 'Neither P nor S phase. Skipping.')\n continue\n\n if output_level >= 3:\n logging.info('\\t' + 'Slices:')\n\n # Checking archives\n found_archive = False\n if len(archive_definitions) > 0:\n station = pick.waveform_id.station_code\n station_archives = seisan.station_archives(archive_definitions, station)\n\n channel_slices = []\n for x in station_archives:\n if x[4] <= pick_time:\n if x[5] is not None and pick_time > x[5]:\n continue\n else:\n archive_file_path = seisan.archive_path(x, pick_time.year, pick_time.julday,\n config.archives_path, output_level)\n\n if os.path.isfile(archive_file_path):\n try:\n arch_st = read(archive_file_path)\n except TypeError as error:\n if output_level >= 2:\n logging.warning('In ' + archive_file_path + ': ' + str(error))\n return -1\n\n # arch_st.normalize(global_max=config.global_max_normalizing) # remove that\n # arch_st.filter(\"highpass\", freq=config.highpass_filter_df) # remove that\n # line later\n for trace in arch_st:\n pick_start_time = pick_time\n if trace.stats.starttime > pick_time or pick_time + slice_duration >= trace.stats.endtime:\n logging.info('\\t\\tArchive ' + archive_file_path +\n ' does not cover required slice interval')\n continue\n\n shifted_time = pick_time - config.static_slice_offset\n end_time = shifted_time + slice_duration\n\n found_archive = True\n\n trace_slice = trace.slice(shifted_time, end_time)\n if output_level >= 3:\n logging.info('\\t\\t' + str(trace_slice))\n\n trace_file = x[0] + str(x[4].year) + str(x[4].julday) + x[1] + x[2] + x[3]\n event_id = x[0] + str(x[4].year) + str(x[4].julday) + x[2] + x[3]\n slice_name_station_channel = (trace_slice, trace_file, x[0], x[1], event_id,\n pick.phase_hint, id_str)\n\n # print(\"ID \" + str(id_str))\n # if id_str == '20140413140958':\n # print(x[0])\n # if True:#x[0] == 'NKL':\n # trace.integrate()\n # trace_slice.integrate()\n # trace.normalize()\n # trace_slice.normalize()\n # print('FOUND ID! NORMALIZED')\n # print('ARCHIVE: ' + archive_file_path)\n # print('FILE: ' + trace_file)\n # print('SLICE: ' + str(trace_slice))\n # print('TIME: ' + str(shifted_time) + ' till ' + str(end_time))\n # print('TRACE: ' + str(trace))\n # print('DATA: ' + str(trace_slice.data))\n\n # trace_slice.filter(\"highpass\", freq=config.highpass_filter_df)\n # patho = \"/seismo/seisan/WOR/chernykh/plots/part/\"\n # patho2 = \"/seismo/seisan/WOR/chernykh/plots/whole/\"\n\n # plt.plot(trace_slice.data)\n # plt.ylabel('Amplitude')\n # plt.savefig(patho + trace_file)\n # plt.figure()\n\n # plt.plot(trace.data)\n # plt.ylabel('Amplitude')\n # plt.savefig(patho2 + trace_file)\n # plt.figure()\n\n if len(trace_slice.data) >= 400:\n channel_slices.append(slice_name_station_channel)\n\n # Read and slice waveform\n if found_archive:\n if len(channel_slices) > 0:\n slices.append(channel_slices)\n continue\n\n except ValueError as error:\n if output_level >= 2:\n logging.warning('In ' + reading_path + ': ' + str(error))\n continue\n\n return sort_slices(slices)", "def _read_analogies(self):\n questions = []\n questions_skipped = 0\n with open(self._options.eval_data, \"rb\") as analogy_f:\n for line in analogy_f:\n if line.startswith(\":\"): # Skip comments.\n continue\n words = line.strip().lower().split(\" \")\n # print words\n ids = [self._cate2id.get(w.strip()) for w in words]\n # print ids\n if None in ids or len(ids) != 4:\n questions_skipped += 1\n else:\n questions.append(np.array(ids))\n print(\"Eval analogy file: \", self._options.eval_data)\n print(\"Questions: \", len(questions))\n print(\"Skipped: \", questions_skipped)\n questions = np.array(questions, dtype=np.int32)\n self._analogy_questions = questions\n self._target_field = np.array(\n list(set(questions[:, 3])), dtype=np.int32)\n np.random.shuffle(self._analogy_questions)", "def read_stream(stream, prefix=None):\n f = stream.splitlines()\n p_data = {}\n # This first line is the header for the entire file.\n try:\n line = f.pop(0)\n except IndexError:\n print 'datareader.read_stream(): Empty file.'\n # XXX: Haven't decided how to handle all the potential errors.\n raise\n line = line.strip()\n # prev_line = line\n top_header = line.split(',')\n if not top_header:\n # Don't parse this for now.\n pass\n # Now read in per-participant data.\n while True:\n word_list = []\n all_words_data = {}\n # The first line for the participant is a header.\n try:\n line = f.pop(0)\n except IndexError:\n # We had previously read everything, so we're done.\n break\n line = line.strip()\n p_header = line.split(',')\n\n # The participant's ID # comes first.\n p_id = p_header[0]\n if not p_id:\n # This happens when the previous participant didn't answer.\n \"\"\"\n print 'previous line:', prev_line\n print 'current line:', line\n print 'p header:', p_header\n print\n \"\"\"\n continue\n if prefix:\n p_id = prefix + p_id\n # print 'SN #', p_id\n # The number of N/A's this p is at 28.\n try:\n p_nas = int(p_header[28])\n except ValueError:\n # This happens when an RA messes up the file.\n \"\"\"\n print 'nas: previous line:', prev_line\n print 'nas: current line:', line\n print 'nas: p header:', p_header\n print\n \"\"\"\n raise\n # print \"NA's: #\", p_nas\n # Check if this participant left everything blank.\n # XXX: Have to hard-code this.\n if p_nas == 20:\n p_data[p_id] = {'words': None,\n 'word_data': None,\n 'nas': None,\n 'overall': None}\n continue\n # The next line after the header has both the data\n # for the first word and overall statistics.\n # prev_line = line\n try:\n line = f.pop(0)\n except StopIteration:\n # We had previously read everything, so we're done.\n break\n line = line.strip()\n word, word_data, overall_data = parse_first_line(line.split(','))\n word_list.append(word)\n all_words_data[word] = word_data\n # Now read data for the rest of the words.\n for line in f:\n line = line.strip()\n word, word_data = parse_data_lines(line.split(','))\n if word == '':\n \"\"\"\n print \"loop's previous line:\", prev_line\n print \"loop's current line:\", line\n print\n \"\"\"\n # prev_line = line\n break\n word_list.append(word)\n all_words_data[word] = word_data\n # prev_line = line\n # Compute per-word averages\n all_total_avg, future_total_avg, past_total_avg = \\\n datacomputer.compute_all_future_past(all_words_data)\n overall_data['all'] = all_total_avg\n overall_data['future'] = future_total_avg\n overall_data['past'] = past_total_avg\n p_data[p_id] = {'words': word_list,\n 'word_data': all_words_data,\n 'nas': p_nas,\n 'overall': overall_data}\n # print 'p_data'\n # print p_data[p_id]\n # print\n print \"Processed {} participants' data\".format(len(p_data))\n return p_data", "def read_qvalues(namefile):\n db = shelve.open(namefile)\n hashes = db['hashes']\n nif = db['nif']\n qvalue = db['qvalue']\n year = db['year']\n methodvalues = db['methodvalues']\n db.close()\n return hashes, nif, year, qvalue, methodvalues", "def read_some(self):\n self.process_rawq()\n while not self.cookedq and not self.eof:\n self.fill_rawq()\n self.process_rawq()\n buf = self.cookedq\n self.cookedq = b''\n return buf", "def load_data(squad_per_lang):\n question_set = QuestionSet()\n candidate_set = CandidateSet()\n\n for lang, squad in squad_per_lang.items():\n for question, answer, context, context_sentences, xling_id, context_id in (\n generate_examples(squad, lang)):\n question = Question(question, xling_id, lang)\n question_set.add(question)\n assert answer in context_sentences, (\n \"answer doesn't appear in context_sentences\")\n for sent_pos, sentence in enumerate(context_sentences):\n candidate = Candidate(sentence, context, lang, context_id, sent_pos)\n candidate = candidate_set.add_or_retrieve_candidate(candidate)\n if sentence == answer:\n candidate_set.update_xling_id(candidate, xling_id)\n print(\"Totals across languages: questions={}, candidates={}\".format(\n len(question_set.as_list()), len(candidate_set.as_list())))\n\n return question_set, candidate_set", "def read(self):\n # open the .SPE file\n with open(self._input_file_path, 'rb') as f:\n lines = f.readlines()\n # Create an empty dictionary for the metadata\n metadata_dictionary = {}\n\n # Search through the file for the needed metadata\n metadata_dictionary['date_acquired'] = re.search(b'date=\"(.*?)\"', lines[1])[1].decode('ANSI') \n metadata_dictionary['width'] = int(re.search(b'width=\"(.*?)\"', lines[1])[1])\n metadata_dictionary['height'] = int(re.search(b'height=\"(.*?)\"', lines[1])[1])\n metadata_dictionary['size'] = metadata_dictionary['width']*metadata_dictionary['height']\n metadata_dictionary['exposure_time'] = int(re.search(b'<ExposureTime type=\"Double\">(.*?)</ExposureTime>', lines[1])[1])\n metadata_dictionary['excitation_wavelength'] = float(re.search(b'laserLine=\"(.*?)\"',lines[1])[1])\n metadata_dictionary['center_wavelength'] = float(re.search(b'<CenterWavelength type=\"Double\">(.*?)</CenterWavelength>',lines[1])[1])\n metadata_dictionary['orientation'] = re.search(b'orientation=\"(.*?)\"',lines[1])[1].decode('ANSI')\n\n # Get the wavelength and intensity\n wavelength_string = re.search(b'<Wavelength xml:space=\"preserve\">(.*?)</Wavelength>',lines[1])[1].decode('utf-8')\n wavelength = np.array(wavelength_string.split(','), dtype=np.float64)\n\n f.seek(4100)\n intensity = np.fromfile(f,dtype=np.float32,count=metadata_dictionary['size'])\n\n raman_shift_wavenumbers = 1e7*(1/metadata_dictionary['excitation_wavelength'] - 1/wavelength)\n\n f.close()\n \n # create the sidpy dataset\n data_set = Dataset.from_array(intensity, name='Raman Spectra')\n\n data_set.data_type = 'spectrum'\n data_set.units = 'counts'\n data_set.quantity = 'Intensity'\n\n # set dimensions\n data_set.set_dimension(0, Dimension(raman_shift_wavenumbers, name='Raman Shift',\n units = 'cm-1',\n quantity='Raman shift',\n dimension_type='spectral'))\n data_set.set_dimension(1, Dimension(intensity, name='Intensity',\n units = 'counts',\n quantity='intensity',\n dimension_type='spectral')) \n\n data_set.metadata = metadata_dictionary\n\n return data_set", "def print_squad_questions(subject=None):\n\n squad_data = import_squad_data()\n\n if subject:\n if subject == \"all\":\n squad_records = squad_data\n else:\n squad_records = squad_data.loc[squad_data[\"subject\"] == subject]\n if squad_records.empty:\n print(\"Subject not found in SQuAD dev-v2.0 dataset.\")\n return\n else:\n print(squad_data[\"subject\"].unique())\n print(\n \"Please specify a subject from the list above, or choose 'all', e.g. print_squad_questions(nlp.import_squad_data(), subject='Normans'\"\n )\n return\n\n for _, row in squad_records.iterrows():\n print(\"\\n=============================\")\n print(\"Id: \", row[\"id\"])\n print(\"Reading from: \", row[\"subject\"])\n print(\"\\nContext: \", row[\"context\"])\n print(\"--\")\n print(\"Question: \", row[\"question\"])\n print(\"Answer: \", row[\"answer\"])", "def test_fastq_read_length():\n cluster = clust.Clustering.from_fastq(TMP + 'simple.fastq', 4, 'ACGT',\n threshold=0, prefix=1, read_length=25)\n uid1_expect = 'AAAACCCC'\n uid2_expect = 'CCCCAAAA'\n seq1_expect = 'ACCTCTCCCTGTGGGTCATGTGACT'\n seq2_expect = 'TTGTTTGAAAAACCTCGAAAGTAAC'\n\n assert uid1_expect in cluster, \"%r not in %r\" % (uid1_expect, list(cluster.keys()))\n assert uid2_expect in cluster, \"%r not in %r\" % (uid2_expect, list(cluster.keys()))\n assert cluster[uid1_expect].sequence.sequence == seq1_expect, \\\n \"%r != %r\" % (cluster[uid1_expect].sequence.sequence, seq1_expect)\n assert cluster[uid2_expect].sequence.sequence == seq2_expect, \\\n \"%r != %r\" % (cluster[uid2_expect].sequence.sequence, seq2_expect)", "def test_psl_34_004(self, testf=\"psl_34_004.psl\", pslx=False):\n blat_file = get_file(testf)\n self.qresults = list(parse(blat_file, FMT, pslx=pslx))\n self.assertEqual(1, len(self.qresults))\n # check common attributes\n for qresult in self.qresults:\n for hit in qresult:\n self.assertEqual(qresult.id, hit.query_id)\n for hsp in hit:\n self.assertEqual(hit.id, hsp.hit_id)\n self.assertEqual(qresult.id, hsp.query_id)\n\n # test first qresult\n qresult = self.qresults[0]\n self.assertEqual(\"hg19_dna\", qresult.id)\n self.assertEqual(\"blat\", qresult.program)\n self.assertEqual(50, qresult.seq_len)\n self.assertEqual(10, len(qresult))\n # first qresult, first hit\n hit = qresult[0]\n self.assertEqual(\"chr9\", hit.id)\n self.assertEqual(141213431, hit.seq_len)\n self.assertEqual(1, len(hit.hsps))\n # first qresult, first hit, first hsp\n hsp = qresult[0].hsps[0]\n self.assertEqual(38, hsp.match_num)\n self.assertEqual(0, hsp.match_rep_num)\n self.assertEqual(3, hsp.mismatch_num)\n self.assertEqual(0, hsp.n_num)\n self.assertEqual(0, hsp.query_gapopen_num)\n self.assertEqual(0, hsp.query_gap_num)\n self.assertEqual(0, hsp.hit_gapopen_num)\n self.assertEqual(0, hsp.hit_gap_num)\n self.assertEqual(1, hsp[0].query_strand)\n self.assertEqual(9, hsp.query_start)\n self.assertEqual(85737865, hsp.hit_start)\n self.assertEqual(50, hsp.query_end)\n self.assertEqual(85737906, hsp.hit_end)\n self.assertEqual(1, len(hsp))\n self.assertEqual([41], hsp.query_span_all)\n self.assertEqual([41], hsp.hit_span_all)\n self.assertEqual([(9, 50)], hsp.query_range_all)\n self.assertEqual([(85737865, 85737906)], hsp.hit_range_all)\n # first qresult, second hit\n hit = qresult[1]\n self.assertEqual(\"chr8\", hit.id)\n self.assertEqual(146364022, hit.seq_len)\n self.assertEqual(1, len(hit.hsps))\n # first qresult, second hit, first hsp\n hsp = qresult[1].hsps[0]\n self.assertEqual(41, hsp.match_num)\n self.assertEqual(0, hsp.match_rep_num)\n self.assertEqual(0, hsp.mismatch_num)\n self.assertEqual(0, hsp.n_num)\n self.assertEqual(0, hsp.query_gapopen_num)\n self.assertEqual(0, hsp.query_gap_num)\n self.assertEqual(0, hsp.hit_gapopen_num)\n self.assertEqual(0, hsp.hit_gap_num)\n self.assertEqual(1, hsp[0].query_strand)\n self.assertEqual(8, hsp.query_start)\n self.assertEqual(95160479, hsp.hit_start)\n self.assertEqual(49, hsp.query_end)\n self.assertEqual(95160520, hsp.hit_end)\n self.assertEqual(1, len(hsp))\n self.assertEqual([41], hsp.query_span_all)\n self.assertEqual([41], hsp.hit_span_all)\n self.assertEqual([(8, 49)], hsp.query_range_all)\n self.assertEqual([(95160479, 95160520)], hsp.hit_range_all)\n # first qresult, third hit\n hit = qresult[2]\n self.assertEqual(\"chr22\", hit.id)\n self.assertEqual(51304566, hit.seq_len)\n self.assertEqual(2, len(hit.hsps))\n # first qresult, third hit, first hsp\n hsp = qresult[2].hsps[0]\n self.assertEqual(33, hsp.match_num)\n self.assertEqual(0, hsp.match_rep_num)\n self.assertEqual(3, hsp.mismatch_num)\n self.assertEqual(0, hsp.n_num)\n self.assertEqual(0, hsp.query_gapopen_num)\n self.assertEqual(0, hsp.query_gap_num)\n self.assertEqual(0, hsp.hit_gapopen_num)\n self.assertEqual(0, hsp.hit_gap_num)\n self.assertEqual(1, hsp[0].query_strand)\n self.assertEqual(11, hsp.query_start)\n self.assertEqual(42144400, hsp.hit_start)\n self.assertEqual(47, hsp.query_end)\n self.assertEqual(42144436, hsp.hit_end)\n self.assertEqual(1, len(hsp))\n self.assertEqual([36], hsp.query_span_all)\n self.assertEqual([36], hsp.hit_span_all)\n self.assertEqual([(11, 47)], hsp.query_range_all)\n self.assertEqual([(42144400, 42144436)], hsp.hit_range_all)\n # first qresult, third hit, second hsp\n hsp = qresult[2].hsps[1]\n self.assertEqual(35, hsp.match_num)\n self.assertEqual(0, hsp.match_rep_num)\n self.assertEqual(2, hsp.mismatch_num)\n self.assertEqual(0, hsp.n_num)\n self.assertEqual(0, hsp.query_gapopen_num)\n self.assertEqual(0, hsp.query_gap_num)\n self.assertEqual(0, hsp.hit_gapopen_num)\n self.assertEqual(0, hsp.hit_gap_num)\n self.assertEqual(-1, hsp[0].query_strand)\n self.assertEqual(12, hsp.query_start)\n self.assertEqual(48997405, hsp.hit_start)\n self.assertEqual(49, hsp.query_end)\n self.assertEqual(48997442, hsp.hit_end)\n self.assertEqual(1, len(hsp))\n self.assertEqual([37], hsp.query_span_all)\n self.assertEqual([37], hsp.hit_span_all)\n self.assertEqual([(12, 49)], hsp.query_range_all)\n self.assertEqual([(48997405, 48997442)], hsp.hit_range_all)\n # first qresult, fourth hit\n hit = qresult[3]\n self.assertEqual(\"chr2\", hit.id)\n self.assertEqual(243199373, hit.seq_len)\n self.assertEqual(2, len(hit.hsps))\n # first qresult, fourth hit, first hsp\n hsp = qresult[3].hsps[0]\n self.assertEqual(43, hsp.match_num)\n self.assertEqual(0, hsp.match_rep_num)\n self.assertEqual(1, hsp.mismatch_num)\n self.assertEqual(0, hsp.n_num)\n self.assertEqual(1, hsp.query_gapopen_num)\n self.assertEqual(4, hsp.query_gap_num)\n self.assertEqual(0, hsp.hit_gapopen_num)\n self.assertEqual(0, hsp.hit_gap_num)\n self.assertEqual(1, hsp[0].query_strand)\n self.assertEqual(1, hsp.query_start)\n self.assertEqual(183925984, hsp.hit_start)\n self.assertEqual(49, hsp.query_end)\n self.assertEqual(183926028, hsp.hit_end)\n self.assertEqual(2, len(hsp))\n self.assertEqual([6, 38], hsp.query_span_all)\n self.assertEqual([6, 38], hsp.hit_span_all)\n self.assertEqual([(1, 7), (11, 49)], hsp.query_range_all)\n self.assertEqual(\n [(183925984, 183925990), (183925990, 183926028)], hsp.hit_range_all\n )\n # first qresult, fourth hit, second hsp\n hsp = qresult[3].hsps[1]\n self.assertEqual(35, hsp.match_num)\n self.assertEqual(0, hsp.match_rep_num)\n self.assertEqual(1, hsp.mismatch_num)\n self.assertEqual(0, hsp.n_num)\n self.assertEqual(0, hsp.query_gapopen_num)\n self.assertEqual(0, hsp.query_gap_num)\n self.assertEqual(0, hsp.hit_gapopen_num)\n self.assertEqual(0, hsp.hit_gap_num)\n self.assertEqual(-1, hsp[0].query_strand)\n self.assertEqual(13, hsp.query_start)\n self.assertEqual(120641740, hsp.hit_start)\n self.assertEqual(49, hsp.query_end)\n self.assertEqual(120641776, hsp.hit_end)\n self.assertEqual(1, len(hsp))\n self.assertEqual([36], hsp.query_span_all)\n self.assertEqual([36], hsp.hit_span_all)\n self.assertEqual([(13, 49)], hsp.query_range_all)\n self.assertEqual([(120641740, 120641776)], hsp.hit_range_all)\n # first qresult, fifth hit\n hit = qresult[4]\n self.assertEqual(\"chr19\", hit.id)\n self.assertEqual(59128983, hit.seq_len)\n self.assertEqual(3, len(hit.hsps))\n # first qresult, fifth hit, first hsp\n hsp = qresult[4].hsps[0]\n self.assertEqual(34, hsp.match_num)\n self.assertEqual(0, hsp.match_rep_num)\n self.assertEqual(2, hsp.mismatch_num)\n self.assertEqual(0, hsp.n_num)\n self.assertEqual(0, hsp.query_gapopen_num)\n self.assertEqual(0, hsp.query_gap_num)\n self.assertEqual(1, hsp.hit_gapopen_num)\n self.assertEqual(134, hsp.hit_gap_num)\n self.assertEqual(1, hsp[0].query_strand)\n self.assertEqual(10, hsp.query_start)\n self.assertEqual(35483340, hsp.hit_start)\n self.assertEqual(46, hsp.query_end)\n self.assertEqual(35483510, hsp.hit_end)\n self.assertEqual(2, len(hsp))\n self.assertEqual([25, 11], hsp.query_span_all)\n self.assertEqual([25, 11], hsp.hit_span_all)\n self.assertEqual([(10, 35), (35, 46)], hsp.query_range_all)\n self.assertEqual(\n [(35483340, 35483365), (35483499, 35483510)], hsp.hit_range_all\n )\n # first qresult, fifth hit, second hsp\n hsp = qresult[4].hsps[1]\n self.assertEqual(39, hsp.match_num)\n self.assertEqual(0, hsp.match_rep_num)\n self.assertEqual(0, hsp.mismatch_num)\n self.assertEqual(0, hsp.n_num)\n self.assertEqual(0, hsp.query_gapopen_num)\n self.assertEqual(0, hsp.query_gap_num)\n self.assertEqual(0, hsp.hit_gapopen_num)\n self.assertEqual(0, hsp.hit_gap_num)\n self.assertEqual(-1, hsp[0].query_strand)\n self.assertEqual(10, hsp.query_start)\n self.assertEqual(54017130, hsp.hit_start)\n self.assertEqual(49, hsp.query_end)\n self.assertEqual(54017169, hsp.hit_end)\n self.assertEqual(1, len(hsp))\n self.assertEqual([39], hsp.query_span_all)\n self.assertEqual([39], hsp.hit_span_all)\n self.assertEqual([(10, 49)], hsp.query_range_all)\n self.assertEqual([(54017130, 54017169)], hsp.hit_range_all)\n # first qresult, fifth hit, third hsp\n hsp = qresult[4].hsps[2]\n self.assertEqual(36, hsp.match_num)\n self.assertEqual(0, hsp.match_rep_num)\n self.assertEqual(3, hsp.mismatch_num)\n self.assertEqual(0, hsp.n_num)\n self.assertEqual(0, hsp.query_gapopen_num)\n self.assertEqual(0, hsp.query_gap_num)\n self.assertEqual(0, hsp.hit_gapopen_num)\n self.assertEqual(0, hsp.hit_gap_num)\n self.assertEqual(-1, hsp[0].query_strand)\n self.assertEqual(10, hsp.query_start)\n self.assertEqual(553742, hsp.hit_start)\n self.assertEqual(49, hsp.query_end)\n self.assertEqual(553781, hsp.hit_end)\n self.assertEqual(1, len(hsp))\n self.assertEqual([39], hsp.query_span_all)\n self.assertEqual([39], hsp.hit_span_all)\n self.assertEqual([(10, 49)], hsp.query_range_all)\n self.assertEqual([(553742, 553781)], hsp.hit_range_all)", "def read_audiofile(audio_name,cutToLength):\n fs, data = wavfile.read(audio_name)\n # sa.play_buffer(audio_data, num_channels, bydeftes_per_sample,sample_rate)\n #play_obj = sa.play_buffer(data,1,2,fs)\n #play_obj.stop()\n # delete one column. Make mono channel\n if data.shape[1]>1:\n data = numpy.delete(data,1,1)\n #downsample if signal is broad\n if fs>24000:\n data = numpy.delete(data, numpy.s_[::2], 0)\n fs = int(fs/2)\n \n data = data[data!=0]\n data = numpy.delete(data,numpy.s_[ int(cutToLength*fs):len(data)] )\n return data", "def mina1_reader():\n with open(MINA1_FILE_PATH, 'r') as voc_file:\n\n voc_list = []\n lesson_list = []\n\n voc_count = 0\n lesson_count = 0\n\n for voc_line in voc_file:\n if voc_line.find(\"大家日语\") != -1:\n voc_len = len(voc_list)\n if voc_len > 0:\n lesson_list.append(voc_list)\n\n voc_list = []\n voc_count = 0\n lesson_count = lesson_count + 1\n elif voc_line != \"\\n\":\n voc_line.strip()\n\n voc_split = voc_line.split(\"\\t\")\n while '' in voc_split:\n voc_split.remove('')\n\n if len(voc_split) < 3:\n continue\n\n voc_dict = {\n \"Ext\": voc_split[0],\n \"Voc\": voc_split[1],\n \"Type\": \"\",\n \"Meaning\": voc_split[2]\n }\n\n if not voc_dict.has_key(\"Voc\"):\n print voc_line\n continue\n\n voc_count = voc_count + 1\n voc_list.append(voc_dict)\n\n voc_len = len(voc_list)\n if voc_len > 0:\n lesson_list.append(voc_list)\n\n return lesson_list" ]
[ "0.5752212", "0.5749095", "0.56410015", "0.5553645", "0.55321485", "0.53939885", "0.5328976", "0.5213072", "0.5181305", "0.5114432", "0.5081804", "0.5073686", "0.50505215", "0.50505215", "0.50505215", "0.50038326", "0.4980892", "0.49647292", "0.49619284", "0.49582574", "0.49451908", "0.49172917", "0.49040854", "0.48794165", "0.4868015", "0.48645234", "0.4842137", "0.48108456", "0.4795948", "0.47876447" ]
0.64043224
0
trap += min(left_high, right_high) own bar
def trap(self, height: List[int]) -> int: # Make a left highest list left_highest = [0]*(len(height)+1) # left_highest[0] = 0 for i,x in enumerate(height): left_highest[i+1] = max(x,left_highest[i]) print (left_highest) # right_highest = [0] * (len(height)+1) trap = 0 right_highest = 0 for i in range(len(height)-1,-1,-1): right_highest = max(height[i], right_highest) trap += max(min(left_highest[i],right_highest) - height[i], 0) return trap
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def trapArea(base1, base2, height):\n return base1 + base2 * 1/2 * height", "def trap(height: List[int]) -> int:\n # No heights passed!\n if not height:\n return 0\n # Max from left\n max_L = 0\n L = len(height)\n left = [0] * L\n for i in range(L):\n if height[i] > max_L:\n max_L = height[i]\n left[i] = max_L\n # Max from right\n max_R = 0\n right = [0] * L\n for i in range(L-1, -1, -1):\n if height[i] > max_R:\n max_R = height[i]\n right[i] = max_R\n # Get water height / area at each point on map\n area = 0\n for i in range(1, L-1):\n area += max(0, min(left[i-1], right[i+1]) - height[i])\n return area", "def area_under_curve(x, y):\n return torch.trapz(x=x, y=y)", "def low(self):", "def fix_range(l_left, l_right, over_value=0):\n\n def innner_fix_range(v):\n try:\n return v if l_right > float(v) > l_left else over_value\n except ValueError:\n return over_value\n\n return innner_fix_range", "def gauge(ax, row, col, params):\n if col == \"high\":\n if pd.notna(row[\"high_record\"]):\n params.maxval = row[\"high_record\"]\n if pd.notna(row[\"high_normal\"]):\n params.avgval = row[\"high_normal\"]\n else:\n if pd.notna(row[\"low_record\"]):\n params.minval = float(row[\"low_record\"])\n if pd.notna(row[\"low_normal\"]):\n params.avgval = row[\"low_normal\"]\n\n # Polar coordinates, so 0 is maxval and pi is minval\n colors = [\"#BE0000\", \"#E48900\", \"#B6EB7A\", \"#0F4CBB\", \"#1B262C\"]\n # Okay, the chart will go from maxval (rad=pi) to maxval (rad=0)\n bar_ends = [\n float(params.avgval + 2 * params.stddev),\n float(params.avgval + params.stddev),\n float(params.avgval - params.stddev),\n float(params.avgval - 2 * params.stddev),\n params.minval,\n ]\n labels = [r\"2$\\sigma$\", r\"$\\sigma$\", r\"-$\\sigma$\", r\"-2$\\sigma$\", \"\"]\n pos = 0\n positive_delta = float(params.maxval - params.avgval)\n negative_delta = float(params.avgval - params.minval)\n if positive_delta == 0:\n positive_delta = 0.01\n if negative_delta == 0:\n negative_delta = 0.01\n for val, color, label in zip(bar_ends, colors, labels):\n if val > params.avgval:\n ha = \"left\"\n if val > params.maxval:\n continue\n pos2 = (params.maxval - val) / positive_delta * pi / 2.0\n else:\n ha = \"right\"\n if val < params.minval:\n continue\n pos2 = pi / 2.0 + (\n (params.avgval - val) / negative_delta * pi / 2.0\n )\n ax.add_patch(Rectangle((pos, 1), pos2 - pos, 2, color=color))\n if abs(val - params.minval) > 1 and abs(val - params.maxval) > 1:\n ax.text(pos2, 3.1, f\"{val:.0f}\", ha=ha)\n ax.text(\n pos2,\n 0.8,\n label,\n va=\"center\",\n ha=\"left\" if ha == \"right\" else \"right\",\n )\n pos = pos2\n # manual placement of max/min\n ax.text(\n 0 if col == \"low\" else pi,\n 3.1,\n f\"{params.maxval:.0f}\" if col == \"low\" else f\"{params.minval:.0f}\",\n ha=\"left\" if col == \"low\" else \"right\",\n )\n\n # Add ticks for percentiles 10 through 90\n for val in params.ptiles:\n if val > params.avgval:\n pos = (params.maxval - val) / positive_delta * pi / 2.0\n else:\n pos = pi / 2.0 + (\n (params.avgval - val) / negative_delta * pi / 2.0\n )\n ax.add_patch(Rectangle((pos, 1), 0.001, 2, color=\"white\"))\n\n # Tick for params.avgval\n ax.add_patch(Rectangle((pi / 2.0, 1), 0.001, 2, color=\"k\"))\n # Median\n val = params.ptiles[4]\n if val > params.avgval:\n pos = (params.maxval - val) / positive_delta * pi / 2.0\n else:\n pos = pi / 2.0 + ((params.avgval - val) / negative_delta * pi / 2.0)\n ax.add_patch(Rectangle((pos, 1), 0.001, 2, color=\"r\"))\n\n ax.grid(False)\n ax.set_xlim(0, pi)\n ax.set_xticks([])\n if row[col] >= params.avgval:\n theta = (params.maxval - row[col]) / positive_delta * (pi / 2.0)\n theta = max([0, theta])\n else:\n theta = (pi / 2.0) + (params.avgval - row[col]) / negative_delta * (\n pi / 2.0\n )\n theta = min([pi, theta])\n ax.text(\n -0.05 if col == \"high\" else pi + 0.05,\n 2,\n f\"Record: \"\n rf\"{miss(row[col + '_record'])}$^\\circ$F\"\n f\"\\n{', '.join([str(s) for s in row[col + '_record_years']])}\",\n va=\"top\",\n ha=\"left\" if col == \"high\" else \"right\",\n )\n ax.text(\n pi / 2,\n 3.25,\n \"Avg:\\n\" + f\"{miss(row[f'{col}_normal'])}\" + r\"$^\\circ$F\",\n ha=\"center\",\n )\n ax.set_rorigin(-4.5)\n ax.set_yticks([])\n ax.arrow(\n theta,\n -4.5,\n 0,\n 5.5,\n width=0.1,\n head_width=0.2,\n head_length=1,\n fc=\"yellow\",\n ec=\"k\",\n clip_on=False,\n )\n ax.text(\n theta,\n -4.5,\n rf\"{row[col]}$^\\circ$F\" f\"\\n@{row[col + '_time']} LST\",\n ha=\"center\",\n va=\"top\",\n fontsize=14,\n )", "def bar(x, y):", "def bar(x, y):", "def bar(x, y):", "def bar(self):\n return self.val * 1.0", "def _origin_shift(axis_range: Sequence[float]) -> float:\n if axis_range[0] > 0:\n # min greater than 0\n return axis_range[0]\n if axis_range[1] < 0:\n # max less than 0\n return axis_range[1]\n else:\n return 0", "def stepup(self, lowUnit, highUnit, higherBound):\n if lowUnit >= higherBound:\n highUnit += lowUnit / higherBound #PYTHON3 //\n lowUnit = lowUnit % higherBound\n\n elif lowUnit < 0:\n highUnit += (lowUnit / higherBound) - 1 #PYTHON3 //\n lowUnit += abs(lowUnit / higherBound * lowUnit) + higherBound\n\n return lowUnit, highUnit", "def high(self):", "def threshold(self, side):\n if side == 0:\n return int(sum(self.thresholds_left) / len(self.thresholds_left))\n elif side == 1:\n return int(sum(self.thresholds_right) / len(self.thresholds_right))", "def instruction_gt(self, register, left_hand, right_hand):\n if Vm.is_register(left_hand):\n left_hand = self.get_register(left_hand)\n\n if Vm.is_register(right_hand):\n right_hand = self.get_register(right_hand)\n\n if left_hand > right_hand:\n self.set_register(register, 1)\n else:\n self.set_register(register, 0)", "def process_pain(x, lb, ub):\n x = x.abs()\n x.loc[(x > ub)] = 8\n x.loc[(x < lb) | (x > ub)] = np.nan\n return x", "def fix_point(h, lower, upper):\n return brentq(lambda x: x - h(x), lower, upper)", "def rect_signal(t, t1, t2):\n return np.where(np.logical_and(t>=t1, t<=t2), 1, 0)", "def trap(f, lower, upper, numberOfPoly):\r\n def f(x):\r\n return 3*(x**2)\r\n \r\n h = (upper-lower)/numberOfPoly\r\n print(h)\r\n result = (0.5*(f(lower))) + (0.5*(f(upper)))\r\n print(result)\r\n for i in range (1, int(numberOfPoly)):\r\n result += f(lower + i*h)\r\n \r\n result *= h\r\n print('result = %f' % result)\r\n return result", "def bar(self, value):\r\n if value < 0:\r\n raise ValueError(\"Must be >= 0\")\r\n self.x = value", "def map_bound(value, in_low, in_high, out_low, out_high):\n result = None\n\n if value <= in_low:\n result = out_low\n else:\n if value >= in_high:\n result = out_high\n else:\n # http://stackoverflow.com/a/5650012/574981\n result = out_low + (\n (out_high - out_low) * (value - in_low) / (in_high - in_low)\n )\n return result", "def increase_right_boundary(self):\n self.R = self.R + 1.0\n self.Ne = self.Ne + 1", "def set_threshold(values, curr_thrsh):\n newThrsh = -max(values)\n for v in values:\n tempValue = v\n if (tempValue > newThrsh) & (tempValue <= curr_thrsh):\n newThrsh = tempValue\n return newThrsh", "def getRawThrottle():\n val = leftDriverStick.getY()\n if val != 0.0:\n val *= -1.0\n return val", "def lower_right(self) -> Tuple[decimal.Decimal, decimal.Decimal]:\n return self.right, self.bottom", "def lower_bound(self) -> float:\n ...", "def clooge_bump_properties(self):\n # First cut out the initial rise of the bump.\n timespace = self._arr\n space_maxes = np.amax(timespace, axis=1)\n ix_time_with_max = np.argmax(space_maxes)\n timespace = timespace[ix_time_with_max:,:]\n n_time = timespace.shape[0]\n n_space = timespace.shape[1]\n # Then similarly cut the already calculated amplitudes\n amplitude = space_maxes[ix_time_with_max:]\n # Find the change in amplitude through time\n delta_amplitudes = math.shift_subtract(amplitude, axis=0)\n # When this amplitude stops changing, say the bump is dead\n # More properly we would say \"when the amplitude is close to zero,\"\n # but there is a certain resting activity.\n ix_time_bump_dies = np.nonzero(np.isclose(delta_amplitudes,\n 0,atol=1e-5))[0]\n # Calculate the locations of the peak\n peak_ix = np.argmax(timespace, axis=1)\n # Calculate the velocity in terms of d index/d frame\n velocity = math.shift_subtract(peak_ix, axis=0)\n # Calculate the widths\n space_indices = np.tile(range(n_space), (n_time, 1))\n peak_ix_expanded = np.tile(peak_ix[...,np.newaxis],\n (1,n_space))\n assert any(map(any, np.logical_and(timespace <= (amplitude[...,np.newaxis] / 2),\n space_indices < peak_ix_expanded)))\n # right_ix = nonzero_first(np.logical_and(\n # timespace <= (amplitude[...,np.newaxis] / 2),\n # space_indices > peak_ix_expanded),\n # axis=1)\n left_ix = nonzero_last(np.logical_and(\n timespace <= (amplitude[...,np.newaxis] / 2),\n space_indices < peak_ix_expanded),\n axis=1)\n # Trim undefined widths\n if -1 in left_ix:\n first_undefined_width = np.nonzero(left_ix == -1)[0][0]\n else:\n first_undefined_width = len(left_ix)\n ix_defined_width = range(first_undefined_width)\n width = peak_ix[ix_defined_width] - left_ix[ix_defined_width]\n return {\n 'width': width,\n 'amplitude': amplitude[ix_defined_width],\n 'peak_ix': peak_ix[ix_defined_width],\n 'velocity': velocity[ix_defined_width[:-1]]\n }", "def _get_observation_lower_bound(self):\n lower_bound = -self._get_observation_upper_bound()\n lower_bound[-7] = 0.0\n lower_bound[-2:] = [self.min_speed, self.min_side_speed]\n return lower_bound", "def crosser(ind: pd.Series, threshold: float) -> pd.Series:\n df = pd.DataFrame({\"ind\": ind})\n df[\"above_below\"] = (df[\"ind\"] >= threshold) * 1 - (df[\"ind\"] < threshold) * 1\n df[\"blip\"] = ((df[\"above_below\"].shift() + df[\"above_below\"]) == 0) * df[\n \"above_below\"\n ]\n df = df.dropna()\n return df[\"blip\"]", "def integrate(chrom, a, b):\n chrom = chrom[(chrom.tme > a) | (chrom.tme <= b)]\n return integrate.cumtrapz(chrom.tic)" ]
[ "0.6273298", "0.58288777", "0.56634337", "0.5574212", "0.5464066", "0.5402058", "0.5370418", "0.5370418", "0.5370418", "0.5317396", "0.52973926", "0.5267531", "0.5262715", "0.52284837", "0.52092624", "0.51587045", "0.5144264", "0.51428884", "0.5125576", "0.5123592", "0.5104839", "0.50942075", "0.5085765", "0.508553", "0.50807124", "0.5078978", "0.50636345", "0.5060034", "0.50470614", "0.50318974" ]
0.610084
1
private function for preparing command string with extras
def __joinCmdStringWithExtras (self,cmdString,extras): if (extras != ""): self._log("joining-extras").debug4("joining cmd '%s' with extra params '%s'",cmdString,extras) cmdString += " " + extras return cmdString
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _build_direct_command(self, cmd, arg):\n return \"%s%s\" % (arg, self._newline)", "def _build_command(self, cmd, unit):\n return '#' + unit + cmd + NEWLINE", "def StringifyCommand(cmd):\n ret = ''\n grouping = 0\n for a in cmd:\n if grouping == 0 and len(ret) > 0:\n ret += \" \\\\\\n \"\n elif grouping > 0:\n ret += \" \"\n if grouping == 0:\n grouping = 1\n if a.startswith('-') and len(a) == 2:\n grouping = 2\n ret += a\n grouping -= 1\n return ret", "def _buildCmd(self, cmd, cmdArg=0x00):\n res = [cmd, cmdArg]\n if self.USE_SUFFIX:\n return res + [self.CMD_SUFFIX]\n return res", "def test_commandRepr(self):\n repr(imap4.Command(b\"COMMAND\", [b\"arg\"], (b'extra')))", "def prepare_command(self) -> Tuple[Command, Command]:\n raise NotImplementedError", "def formatCommand(command):\n cmdstr=\"\"\n logging.debug(repr(command))\n for arg in command:\n if \" \" in arg:\n cmdstr=cmdstr+\" \\\"\"+arg+\"\\\"\"\n else:\n cmdstr=cmdstr+\" \"+arg\n return cmdstr", "def _build_simple_command(self, cmd):\n return cmd+SBE37_NEWLINE", "def _build_send_optode_command(self, cmd, command):\n return \"%s=%s%s\" % (cmd, command, self._newline)", "def command_and_args(self) -> str:\n if self.command and self.args:\n rtn = f'{self.command} {self.args}'\n elif self.command:\n # there were no arguments to the command\n rtn = self.command\n else:\n rtn = ''\n return rtn", "def _extract_command(fields: List[bytes]) -> Tuple[Any, List[Any]]:\n cmd = encode_command(fields[0])\n if cmd in COMMANDS_WITH_SUB and len(fields) >= 2:\n cmd += \" \" + encode_command(fields[1])\n cmd_arguments = fields[2:]\n else:\n cmd_arguments = fields[1:]\n return cmd, cmd_arguments", "def _build_solo_command(self, cmd):\n return COMMAND_CHAR[cmd]", "def makecmd(self, options):", "def __init__(self, cmd):\n # Build command + options \n self.cmd = cmd \n setattr(self, 'command', \"%s\" % (cmd))", "def __build_command_string(self, cmd):\n cmd_string = cmd.command\n\n # if we know the number of frames that this command returns,\n # only wait for exactly that number. This avoids some harsh\n # timeouts from the ELM, thus speeding up queries.\n\n\n return cmd_string", "def rebuild_command(args):\n return \"%s\\n\" % (\" \".join(args)).replace(\"\\\\\", \"\\\\\\\\\")", "def parse_command(self) -> None:\n\n # Verify the command length and existence\n if self.command_str is not None and len(self.command_str) >= 1:\n\n # Split the command into two parts\n tmp_list: list = self.command_str.split(\" \", 1)\n\n # Verify the command format\n if tmp_list[0][0] == \"!\":\n self.name = tmp_list[0]\n if len(tmp_list) == 2:\n self.arg = tmp_list[1]", "def prepareCommand(self, client):\n # No command, just create the dirs\n return ''", "def _build_menu_command(self, cmd):\n if COMMAND_CHAR[cmd]:\n return COMMAND_CHAR[cmd]+self._newline\n else:\n raise InstrumentProtocolException(\"Unknown command character for %s\" % cmd)", "def _make_cmdline(self, line):\n if isinstance(line, list):\n parts = line\n else:\n parts = line.split(\" \", 1)\n cmd = parts[0]\n exe = os.path.join(BINDIR, cmd)\n\n python_cmds = [\"samba-tool\",\n \"samba_dnsupdate\",\n \"samba_upgradedns\",\n \"script/traffic_replay\",\n \"script/traffic_learner\"]\n\n if os.path.exists(exe):\n parts[0] = exe\n if cmd in python_cmds and os.getenv(\"PYTHON\", None):\n parts.insert(0, os.environ[\"PYTHON\"])\n\n if not isinstance(line, list):\n line = \" \".join(parts)\n\n return line", "def cmd_stru(args):", "def _build_command(self, command_name, hardware_address = '', comp_var_dict = None):\n # Start command adn set name\n command = \"<Command><Name>{command_name}</Name>\".format(command_name=command_name)\n\n if hardware_address:\n command += \"<DeviceDetails><HardwareAddress>{hardware_address}</HardwareAddress></DeviceDetails>\".format(hardware_address=hardware_address)\n\n if comp_var_dict is not None:\n comp_keys = comp_var_dict.keys()\n if len(comp_keys) > 0:\n for comp_key in comp_keys:\n # Build requested variable list\n command += \"<Components><Component><Name>{comp_key}</Name><Variables>\".format(comp_key=comp_key)\n variables = comp_var_dict[comp_key]\n for var in variables:\n command += \"<Variable><Name>{var}</Name></Variable>\".format(var=var)\n command += \"</Variables></Component></Components>\"\n else:\n # Request all variables from all components\n command += \"<Components><All>Y</All></Components>\"\n\n # Close command\n command += \"</Command>\"\n \n return command", "def buildCommand(self, kwargs):\r\n self.command = \"\"\r\n try:\r\n if not self.isEnabled():\r\n return\r\n except Exception, e:\r\n print \"<ERROR>\", e\r\n return\r\n self.command = self.app\r\n \r\n \r\n \r\n # filename should be last in the command, so iterate again\r\n for key in kwargs:\r\n if key == 'filename':\r\n if type(kwargs[key]) == str:\r\n f = kwargs[key]\r\n if os.path.exists(f):\r\n self.command += \" \" + str(f)\r\n else:\r\n self.command = \"\"\r\n raise Exception, \"File does not exist!\"\r\n else:\r\n self.command = \"\"\r\n raise Exception, \"File needs to be a string.\"", "def prepare_executable_cmd(args: dict):\n return [str(args[\"executable\"].resolve(strict=True)),\n \"-m\", str(args[\"model\"].resolve(strict=True)),\n \"-d\", args[\"device\"]]", "def gen_command(process):\n cmd = \"{} \".format(process.name)\n for o in process.options.opt_list:\n i = 0\n opt = \"\"\n for el in o: \n if el and el != \"input\" and el != \"output\" and i != 3:\n opt += str(el)\n if opt[-1] != \"=\" and opt[-1] != \"'\": # command without space\n opt += \" \" # space\n i += 1\n cmd += opt\n return cmd", "def generate_command_string(self, operation, *args, **kwargs):\n cmd = [self.terraform_binary_path, operation]\n\n for key, value in kwargs.items():\n if key == \"var\":\n for varkey, varval in value.items():\n option = \"-var=\"\n option += \"'%s=%s'\" % (varkey, varval)\n cmd.append(option)\n else:\n option = \"\"\n if \"_\" in key:\n key = key.replace(\"_\", \"-\")\n\n if value == \"IsFlag\":\n option = \"-%s\" % key\n else:\n option = \"-%s=%s\" % (key, value)\n cmd.append(option)\n\n if len(args) > 0:\n for arg in args:\n cmd.append(arg)\n\n return \" \".join(cmd)", "def cmd(self, cmd):\n return cmd", "def build_command_depricated(device_dict, command_tuple):\n command = \" \" # The final command which should be send in the end\n return_list = [] # Is list of commands which can be returned if need be\n only_command = False # Flag if only a command was passed, important if such a command doesnt need syntax!\n\n if (\n type(command_tuple) == type(u\"Unicode\")\n or type(command_tuple) == str\n or type(command_tuple) == float\n or type(command_tuple) == int\n ):\n command_tuple = (str(command_tuple), \"\") # so only tuple are now prevelent\n only_command = True\n elif type(command_tuple[1]) == list:\n command_tuple = (\n command_tuple[0],\n [str(x) for x in command_tuple[1]],\n ) # so no unicode is present\n\n # Preparations\n # look for a syntax (paranteses and so on)\n if \"syntax\" in device_dict:\n syntax = str(device_dict[\"syntax\"])\n syntax = syntax.split(\"###\")\n if not syntax[0]:\n syntax = [\"\", \"\"] # Most devices have no paranteses or whatsoever\n else:\n syntax = [\"\", \"\"] # Most devices have no paranteses or whatsoever\n\n # Looks if a separator is needed to sepatare mulitple orders\n if \"separator\" in device_dict:\n sepa = str(device_dict[\"separator\"])\n else:\n sepa = \" \" # This should be the standard for most devices\n\n if command_tuple[0] in device_dict:\n # here all the magic happens\n # First look if the order is swichted or not (command value, or value command)\n\n # Check if multiple commands so list or so\n if type(device_dict[command_tuple[0]]) == str or type(\n device_dict[command_tuple[0]]\n ) == type(u\"Unicode\"):\n command_list = [device_dict[command_tuple[0]]]\n else:\n command_list = device_dict[command_tuple[0]]\n\n for command_item in command_list:\n command_item = str(command_item)\n command = \"\"\n\n # Value -> Command\n if int(device_dict.get(\"command_order\", 1)) == -1:\n # Now look if a csv structure is necessary for the command to work\n start_ind = command_tuple[0].find(\n \"_\"\n ) # finds the index of the command, to search for\n if (\n \"CSV\" + command_tuple[0][start_ind:] in device_dict\n ): # looks if an actual csv-command is there\n # Todo: test CSV command\n csv_commands = device_dict[\n \"CSV\" + str(command_tuple[0])[start_ind:]\n ]\n csv_commands = (\n csv_commands.strip()\n .strip(\"(\")\n .strip(\")\")\n .strip(\"[\")\n .strip(\"]\")\n .strip()\n ) # get rid of some caracters which should not be there\n csv_commands = csv_commands.split(\n \",\"\n ) # now split it for easy access\n\n # Make sure you always got a list of the next commandblock will fail\n if (\n type(command_tuple[1]) == list\n or type(command_tuple[1]) == tuple\n ):\n value_list = command_tuple[1]\n elif type(command_tuple[1]) == str or type(command_tuple) == type(\n u\"Unicode\"\n ):\n value_list = (\n command_tuple[1]\n .strip()\n .strip(\"(\")\n .strip(\")\")\n .strip(\"[\")\n .strip(\"]\")\n .strip()\n .replace(\" \", \"\")\n )\n value_list = value_list.split(\",\")\n\n csv_list = (\n \",\".join(map(str, value_list))\n .strip()\n .strip(\"(\")\n .strip(\")\")\n .strip(\"[\")\n .strip(\"]\")\n .strip()\n )\n csv_list = csv_list.split(\",\")\n\n for i, com in enumerate(csv_list):\n # here the input will be checked if enough parameters are passed for this command.\n # If not a 0 will be entered and a warning will be printed\n command += str(csv_list[i]).strip() + sepa\n\n if i + 1 < len(csv_commands) and len(csv_commands) > 1:\n for j in range(\n i + 1, len(csv_commands)\n ): # Fill the rest of the missing paramters\n l.error(\n \"Warning: Not enough parameters passed for function: \"\n + str(command_item)\n + \" the command must consist of \"\n + str(csv_commands)\n + \" '\"\n + str(csv_commands[j])\n + \"' is missing! Inserted 0 instead.\"\n )\n command += \"0\" + sepa\n\n command = command.strip(\" \").strip(\",\") # to get rid of last comma\n\n else: # So if no CSV was found for this command, just build the command with the value and the separator\n # First check if a List is present or so\n if (\n type(command_tuple[1]) == list\n or type(command_tuple[1]) == tuple\n ):\n string = \"\"\n for item in command_tuple[1]:\n command = syntax[1] + str(item) + \" \" + command_item\n command = command.strip()\n # Add a command terminator if one is needed and the last part of the syntax\n command += device_dict.get(\"execution_terminator\", \"\")\n return_list.append(command)\n return return_list\n\n else: # If only a command was passed\n string = str(command_tuple[1])\n command += syntax[1] + str(string).strip()\n\n if (\n only_command\n and device_dict.get(\"no_syntax_with_single_commmand\", False)\n and syntax[1] != \" \"\n and syntax[0] != \" \"\n ):\n command = command.replace(syntax[1], \"\")\n command = command.replace(syntax[0], \"\")\n\n # command += \" \" + str(device_dict[str(command_item)]).strip() + syntax[0] # adds the order to the command\n command += (\n \" \" + str(command_item).strip() + syntax[0]\n ) # adds the order to the command\n # Add a command terminator if one is needed and the last part of the syntax\n command = command.strip()\n command += device_dict.get(\"execution_terminator\", \"\")\n # command += syntax[0] # adds the order to the command\n return_list.append(command)\n\n # Command -> Value\n else:\n command += (\n str(command_item).strip() + \" \" + syntax[0]\n ) # adds the order to the command\n\n # Now look if a csv structure is necessary for the command to work\n start_ind = command_tuple[0].find(\n \"_\"\n ) # finds the index of the command, to search for\n if (\n \"CSV\" + command_tuple[0][start_ind:] in device_dict\n ): # looks if an actual csv-command is there\n # Todo: test CSV command\n csv_commands = device_dict[\n \"CSV\" + str(command_tuple[0])[start_ind:]\n ]\n csv_commands = (\n csv_commands.strip()\n .strip(\"(\")\n .strip(\")\")\n .strip(\"[\")\n .strip(\"]\")\n .strip()\n ) # get rid of some caracters which should not be there\n csv_commands = csv_commands.split(\n \",\"\n ) # now split it for easy access\n\n # Make sure you always got a list of the next commandblock will fail\n if (\n type(command_tuple[1]) == list\n or type(command_tuple[1]) == tuple\n ):\n value_list = command_tuple[1]\n elif type(command_tuple[1]) == str or type(command_tuple) == type(\n u\"Unicode\"\n ):\n value_list = (\n command_tuple[1]\n .strip()\n .strip(\"(\")\n .strip(\")\")\n .strip(\"[\")\n .strip(\"]\")\n .strip()\n .replace(\" \", \"\")\n )\n value_list = value_list.split(\",\")\n\n csv_list = (\n \",\".join(map(str, value_list))\n .strip()\n .strip(\"(\")\n .strip(\")\")\n .strip(\"[\")\n .strip(\"]\")\n .strip()\n )\n csv_list = csv_list.split(\",\")\n\n for i, com in enumerate(csv_list):\n # here the input will be checked if enough parameters are passed for this command.\n # If not a 0 will be entered and a warning will be printed\n command += str(csv_list[i]).strip() + sepa + \" \"\n\n if i + 1 < len(csv_commands) and len(csv_commands) > 1:\n for j in range(\n i + 1, len(csv_commands)\n ): # Fill the rest of the missing paramters\n l.warning(\n \"Not enough parameters passed for function: \"\n + str(command_tuple[0])\n + \" the command must consist of \"\n + str(csv_commands)\n + \" '\"\n + str(csv_commands[j])\n + \"' is missing! Inserted 0 instead.\"\n )\n command += \" \" + \"0\" + sepa\n\n command = command.strip(\" \").strip(\n \",\"\n ) # to get rid of last comma and space at the end if csv\n command += syntax[1]\n\n else: # So if no CSV was found for this command, just build the command with the value and the separator\n # First check if a List is present or so\n if (\n type(command_tuple[1]) == list\n or type(command_tuple[1]) == tuple\n ):\n string = \"\"\n for item in command_tuple[1]:\n command = str(item) + \" \" + command_item + syntax[1]\n command = command.strip()\n # Add a command terminator if one is needed and the last part of the syntax\n command += device_dict.get(\"execution_terminator\", \"\")\n return_list.append(command)\n return return_list\n\n else: # If its just one value or no value\n string = str(command_tuple[1])\n command += string.strip() + syntax[1]\n command = command.strip()\n\n if (\n only_command\n and device_dict.get(\"no_syntax_with_single_commmand\", False)\n and syntax[1] != \" \"\n and syntax[0] != \" \"\n ):\n command = command.replace(syntax[1], \"\")\n command = command.replace(syntax[0], \"\")\n\n # Add a command terminator if one is needed and the last part of the syntax\n command += device_dict.get(\"execution_terminator\", \"\")\n return_list.append(command.strip())\n else:\n # If the command is not found in the device only command tuple will be send\n l.error(\n \"Command \"\n + str(command_tuple[0])\n + \" was not found in device! Unpredictable behavior may happen. No commad build!\"\n )\n return \"\"\n\n # Add a command terminator if one is needed and the last part of the syntax\n # command += device_dict.get(\"execution_terminator\",\"\")\n\n # Todo: multiple commands return\n if len(return_list) > 1:\n return return_list\n else:\n return str(return_list[0])", "def query_cmdline():", "def build_command_string(self):\n if self._regex_helper.search_compiled(W._re_h, self.options):\n if self._regex_helper.group(\"SOLO\"):\n self.options = self.options.replace('-h', '')\n else:\n self.options = self.options.replace('h', '')\n\n cmd = \"{} {}\".format(\"w\", self.options)\n else:\n cmd = \"{}\".format(\"w\")\n return cmd" ]
[ "0.69066787", "0.67727035", "0.6672051", "0.6502448", "0.6478234", "0.6404473", "0.63872284", "0.6364261", "0.63335603", "0.6307962", "0.6271431", "0.62701386", "0.6237365", "0.6220038", "0.6126546", "0.609141", "0.6057912", "0.6043142", "0.6036063", "0.6033363", "0.59979045", "0.5996315", "0.59863937", "0.59809667", "0.5977673", "0.5953311", "0.59483", "0.5931251", "0.5929959", "0.5905942" ]
0.7013613
0
set the reserved block percentage parameter
def _setReservedBlockPercentage (self,blockDevice,percentage,timer): if not (0 <= percentage <= 100): self._log("bad-param-for-set-reserved").error("%s is no a valid parameter for setting reserved block percentage!",percentage) return ReturnCodes.kGeneralError setReservedBlockPercentageCmd = "tune2fs -m %d %s"%(percentage,blockDevice) stdout,stderr,rc = self._runCommand(setReservedBlockPercentageCmd,timer) if (rc != 0): self._log("set-reserved-cmd-fail").error("set-reserved-block command '%s' failed! stderr=%s",setReservedBlockPercentageCmd,stderr) return ReturnCodes.kGeneralError self._log("set-reserved-success").debug2("set-reserved-block ('%s') was successful!",setReservedBlockPercentageCmd) return ReturnCodes.kOk
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def setPercent(*args):", "def setPercent(*args):", "def SetValue(self, percent):\n pass", "def set_percent(self, percent):\n self.percent = percent\n self.set_bars()", "def SetPercentage( self, percent, total ):\n self.percentageView = percent\n self.total = total \n self.Refresh()", "def percentage(self, percentage):\n\n self._percentage = percentage", "def percentage(self, percentage):\n\n self._percentage = percentage", "def percentage(self, percentage):\n\n self._percentage = percentage", "def percentage(self, percentage):\n\n self._percentage = percentage", "def update_percent(self):", "def set_limits_percent(self, percent=95):\n low = np.nanmin(self.datasource.data[\"values\"])\n high = np.nanmax(self.datasource.data[\"values\"])\n\n frac = percent / 100.0\n self.set_limits_minmax(low, high - (1.0 - frac) * (high - low))", "def get_free_set_percentage(self, params):\n raise NotImplementedError()", "def percent_space(self):\n self.custom_space(*[0,0,100,100])", "def _set_percentage(self):\n\n step = float(self.step)\n end = float(self.end)\n self.percentage = format((100 * step / end), '.1f')", "def fillinpercent(self, n):\n sp = self.pcspins[n]\n v = self.currentpercents[n]\n sp.setValue(v)\n st = 1.0\n diff = round(100.0 - v, 3)\n for p in (0.1, 0.01, 0.001):\n if diff > st: break\n st = p\n sp.setSingleStep(st)", "def percent_pf(self, percent_pf):\n\n self._percent_pf = percent_pf", "def set_limits_percent(self, percent=95):\n zmin = np.nanmin(self.pixels.get_array())\n zmax = np.nanmax(self.pixels.get_array())\n dz = zmax - zmin\n frac = percent / 100.0\n self.autoscale = False\n self.set_limits_minmax(zmin, zmax - (1.0 - frac) * dz)", "def __init__(__self__, *,\n percentage: Optional[pulumi.Input['GoogleTypeDecimalArgs']] = None):\n if percentage is not None:\n pulumi.set(__self__, \"percentage\", percentage)", "def setBlockMassParams(self):\n for b in self.getBlocks():\n b.p.kgHM = b.getHMMass() / units.G_PER_KG\n b.p.kgFis = b.getFissileMass() / units.G_PER_KG\n b.p.puFrac = (\n b.getPuMoles() / b.p.molesHmBOL if b.p.molesHmBOL > 0.0 else 0.0\n )", "def bid_percentage(self, bid_percentage):\n\n self._bid_percentage = bid_percentage", "def percent(self, value) -> 'Size':\n raise_not_number(value)\n self.maximum = '{}%'.format(value)\n return self", "async def async_set_percentage(self, percentage: int) -> None:\n self._device.fan_speed = math.ceil(\n percentage_to_ranged_value(self._device.fan_speed_limits, percentage)\n )", "def percent_b(self, percent_b: float):\n\n self._percent_b = percent_b", "def percentage_limiter(percentage: float):\n if percentage < 0:\n return 0\n elif 0 <= percentage <= 1:\n return percentage\n else:\n return 1", "def penblock(self, block):\n self.block = block", "def _set_weight_percent_positions(self):\n \n #################################################################################################################################################\n # Sets the fuel weight percent in each autofilled element position. At the moment, 0.211% is the only option.\n self.fuel_wgt_positions ={\n 'C___1':'0.211%', 'B___1':'0.211%', 'A___1':'0.211%',\n 'C___2':'0.211%', 'B___2':'0.211%', 'A___2':'0.211%',\n 'C___3':'0.211%', 'B___3':'0.211%', 'A___3':'0.211%',\n }", "def setPosePercentage(self, percent, part):\n\n # get network node\n networkNode = self.returnNetworkNode\n\n # get reference pose attributes\n modelPoseData = json.loads(cmds.getAttr(networkNode + \".modelPose\"))\n rigPoseData = json.loads(cmds.getAttr(networkNode + \".rigPose\"))\n\n # get the data for each mover\n for poseData in modelPoseData:\n\n mover = poseData.get(\"mover\")\n translate = poseData.get(\"translate\")\n rotate = poseData.get(\"rotate\")\n\n if part != None:\n if part == mover:\n self.setPosePercentage_Part(percent, mover, modelPoseData, rigPoseData, poseData, translate, rotate)\n else:\n self.setPosePercentage_Part(percent, mover, modelPoseData, rigPoseData, poseData, translate, rotate)", "def percent(self, per: float):\r\n per = self._pwm_percent_limits(per)\r\n self._percent = per\r\n self.percent_hist.append(per)\r\n\r\n if self.percent_hist[-2] != per and self._daq:\r\n msg = Message(\"percent\", per, self.checksum).message_bytes\r\n self._daq.asynch.transmit(msg)", "def height_percent(self, height_percent):\n\n self.container['height_percent'] = height_percent", "def _pwm_percent_limits(self, limit_per: float):\r\n # Check if the input percent is an int or float\r\n try:\r\n limit_per = float(limit_per)\r\n except (ValueError, TypeError):\r\n # make new error here?\r\n raise ValueError(\"Not a valid input percent\")\r\n\r\n if limit_per > self.max_pwm:\r\n # Set to previous percent\r\n setpoint = self.percent\r\n elif limit_per < 0:\r\n # Set to 0 if negative\r\n setpoint = 0\r\n else:\r\n # Changes setpoint to be multiple of 0.5\r\n setpoint = self.percent_step * round(limit_per / self.percent_step)\r\n\r\n # FIXME: only change this for if checksum if False\r\n # Changes setpoint from 63 to 62.5% if checksum mode is disabled\r\n if setpoint in _PERCENT_TRANSFORMS:\r\n setpoint = _PERCENT_TRANSFORMS[setpoint]\r\n\r\n # TODO: make this to logging instead?\r\n print(\"Setpoint is {0}%\".format(setpoint))\r\n return setpoint" ]
[ "0.7321322", "0.7321322", "0.68597203", "0.6715722", "0.6561971", "0.6426917", "0.6426917", "0.6426917", "0.6426917", "0.63940376", "0.6321565", "0.62884337", "0.6281122", "0.62152314", "0.62088424", "0.6119454", "0.6082144", "0.6046596", "0.6023594", "0.59494066", "0.59190226", "0.59058267", "0.58772033", "0.58442223", "0.58372384", "0.5827583", "0.58213776", "0.58024234", "0.580045", "0.5793805" ]
0.82864237
0
entire mounting sequence with pre and post commands
def _mount (self,blockDevice,mountingPoint,blockDeviceReadahead,timer): # pre-mount command preMountCmd = self._activeCommandsConfig.preMount preMountCmdExtras = self._activeCommandsConfig.preMountExtras preMountCmdString = self.__joinCmdStringWithExtras(preMountCmd,preMountCmdExtras) if (preMountCmdString != ""): stdout,stderr,rc = self._runCommand(preMountCmdString,timer) if (rc != 0): self._log("pre-mount-cmd-fail").error("pre-mount command '%s' failed! stderr=%s",preMountCmdString,stderr) return ReturnCodes.kGeneralError # mount command mountCmd = self._activeCommandsConfig.mount mountCmdExtras = self._activeCommandsConfig.mountExtras mountCmdString = mountCmd%{self.MOUNTING_POINT_COMMAND_ELEMENT:mountingPoint,self.BLOCK_DEVICE_COMMAND_ELEMENT:blockDevice} mountCmdString = self.__joinCmdStringWithExtras(mountCmdString,mountCmdExtras) stdout,stderr,rc = self._runCommand(mountCmdString,timer) if (rc != 0): self._log("mount-cmd-fail").error("mount command '%s' failed! stderr=%s",mountCmdString,stderr) # TODO: consider insertion os pre and post commands cancelation commands - since we don't know what they do... return ReturnCodes.kGeneralError # post-mount command postMountCmd = self._activeCommandsConfig.preMount postMountCmdExtras = self._activeCommandsConfig.preMountExtras postMountCmdString = postMountCmd%{self.BLOCK_DEVICE_COMMAND_ELEMENT:blockDevice,self.SECTORS_COMMAND_ELEMENT:blockDeviceReadahead} postMountCmdString = self.__joinCmdStringWithExtras(postMountCmdString,postMountCmdExtras) if (postMountCmdString != ""): stdout,stderr,rc = self._runCommand(postMountCmdString,timer) if (rc != 0): self._log("post-mount-cmd-fail").error("post-mount command '%s' failed! stderr=%s",postMountCmdString,stderr) return ReturnCodes.kGeneralError # full success self._log("mount-sequence-success").debug2("full mount sequence was successful!") return ReturnCodes.kOk
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def preloop(self):\n super(CoreCommand, self).preloop() # sets up command completion", "def on_pre_enter(self):\n self.setup()\n self.start()", "def at_pre_cmd(self):\n pass", "def main():\n parser = specify_parser()\n args = parser.parse_args()\n\n mapping = init_data(args.datafile[0])\n loaded_data = read(args.input)\n\n mount(mapping, loaded_data)", "def commands():", "def setup(self):\n MG.setup(self)\n\n proc_dirs = MG4.dir_map[self.name].split(os.sep)\n src = os.path.join(self.madgraph_dir, proc_dirs[0], proc_dirs[1])\n dest = proc_dirs[1]\n logger.debug(\"Copying '%s' to '%s'\" % (src, dest))\n shutil.copytree(src, dest, symlinks=True)\n\n self.event_dir = os.path.join(self.rundir, proc_dirs[1], proc_dirs[2], \"Events\")\n if not os.path.isdir(self.event_dir):\n os.makedirs(self.event_dir)\n\n self.command = os.path.join(os.getcwd(), proc_dirs[1], proc_dirs[2], \"bin\", \"generate_events\")\n logger.debug(\"Command set to '%s'\" % self.command)\n\n run_card_src = os.path.join(self.madgraph_dir, proc_dirs[0], self.run_card)\n run_card_dest = os.path.join(self.rundir, proc_dirs[1], proc_dirs[2], \"Cards\", \"run_card.dat\")\n logger.debug(\"Copying run card from '%s' to '%s'\" % (run_card_src, run_card_dest))\n shutil.copyfile(run_card_src, run_card_dest)\n\n self.make_run_card(run_card_dest)\n\n param_card_src = os.path.join(self.madgraph_dir, proc_dirs[0], self.param_card)\n param_card_dest = os.path.join(self.rundir, proc_dirs[1], proc_dirs[2], \"Cards\", \"param_card.dat\")\n logger.debug(\"Copying param card from '%s' to '%s'\" % (param_card_src, param_card_dest))\n shutil.copyfile(param_card_src, param_card_dest)\n\n self.make_param_card(param_card_dest)", "def start_args():\n\n brick_device = os.environ.get(\"BRICK_DEVICE\", None)\n brick_path = os.environ[\"BRICK_PATH\"]\n if brick_device is not None and brick_device != \"\":\n brickfs = os.environ.get(\"BRICK_FS\", \"xfs\")\n create_and_mount_brick(brick_device, brick_path, brickfs)\n\n volume_id = os.environ[\"VOLUME_ID\"]\n brick_path_name = brick_path.strip(\"/\").replace(\"/\", \"-\")\n volname = os.environ[\"VOLUME\"]\n nodename = os.environ[\"HOSTNAME\"]\n\n create_brickdir(brick_path)\n verify_brickdir_xattr_support(brick_path)\n set_volume_id_xattr(brick_path, volume_id)\n\n volfile_id = \"%s.%s.%s\" % (volname, nodename, brick_path_name)\n storage_unit_volfile_path = os.path.join(VOLFILES_DIR, \"%s.vol\" % volfile_id)\n client_volfile_path = os.path.join(VOLFILES_DIR, \"%s.vol\" % volname)\n\n info_file_path = os.path.join(VOLINFO_DIR, \"%s.info\" % volname)\n data = {}\n with open(info_file_path) as info_file:\n data = json.load(info_file)\n\n create_brick_volfile(storage_unit_volfile_path, volname, volume_id, brick_path, data)\n create_client_volfile(client_volfile_path, data)\n\n # UID is stored at the time of installation in configmap.\n uid = None\n with open(os.path.join(VOLINFO_DIR, \"uid\")) as uid_file:\n uid = uid_file.read()\n\n # Send Analytics Tracker\n # The information from this analytics is available for\n # developers to understand and build project in a better way\n send_analytics_tracker(\"server\", uid)\n\n return Proc(\n \"glusterfsd\",\n \"/opt/sbin/glusterfsd\",\n [\n \"-N\",\n \"--volfile-id\", volfile_id,\n \"-p\", \"/var/run/gluster/glusterfsd-%s.pid\" % brick_path_name,\n \"-S\", \"/var/run/gluster/brick.socket\",\n \"--brick-name\", brick_path,\n \"-l\", \"-\", # Log to stderr\n \"--xlator-option\",\n \"*-posix.glusterd-uuid=%s\" % os.environ[\"NODEID\"],\n \"--process-name\", \"brick\",\n \"--brick-port\", \"24007\",\n \"--xlator-option\",\n \"%s-server.listen-port=24007\" % volname,\n \"-f\", storage_unit_volfile_path\n ]\n )", "def pre_start(self):\n self.make_runpath_dirs()", "def bootup(debug_port, lines):\n lines.skip_until(\"Booting...\")\n lines.skip_until(\"Loading blocks...\")\n lines.skip_until(\"Starting user space\")\n authenticate(debug_port, lines)\n lines.expect_next(\"Enter command\")", "def _do_mount(self, cmd, ensure):\n try:\n self._execute(*cmd, run_as_root=True)\n except exception.ProcessExecutionError as exc:\n if ensure and 'already mounted' in exc.stderr:\n LOG.warn(_LW(\"%s is already mounted\"),\n self.gluster_manager.export)\n else:\n raise exception.GlusterfsException(\n 'Unable to mount Gluster volume'\n )", "def start_process(self):\n\n self.pre_process_information() # process the information based on config files\n\n self.get_config_file() # extract config file(yaml or string) data in self.main_file\n\n self.check_diff_as_arg()\n # if self.args.diff is true, check if snap file (yaml) details are provided and process it\n\n host_dict = (\n {}\n ) # an empty dictionary created in which we will store lists of hosts\n\n if self.args.pre_snapfile is not None:\n output_file = self.args.pre_snapfile\n elif self.args.snapcheck is True:\n output_file = \"snap_temp\"\n self.snap_del = True\n else:\n output_file = \"\"\n\n self.extract_device_information(\n host_dict\n ) # extract information from the config file or arguments\n\n config_data = self.main_file\n self.connect_multiple_device(host_dict, config_data, output_file)\n # connect to list of devices extracted in the host_dict", "def boot(self):\n\n pass", "def generate_debootstrap_rootfs(self):\n\n logging.info(\"starting to generate debootstrap rootfs\")\n\n # Generate the base debootstrap command\n debootstrap_command = \"sudo debootstrap --no-check-gpg\"\n\n # Add the foreign and arch only if they are different from host, and\n # thus if use_qemu_static is True\n if self.use_qemu_static:\n logging.info(\"running debootstrap stage 1\")\n debootstrap_command += \" --foreign --arch=\" + self.project.target_arch\n else:\n logging.info(\"running debootstrap\")\n\n # Add the target, mount point and repository url to the debootstrap command\n debootstrap_command += \" \" + self.project.target_version + \" \"\n debootstrap_command += self.project.rootfs_mountpoint + \" \"\n debootstrap_command += self.project.project_definition[\"project-definition\"][\"debootstrap-repository\"]\n\n # Finally run the subprocess\n self.execute_command(debootstrap_command)\n\n # Check if we are working with foreign arch, then ...\n if self.use_qemu_static:\n # QEMU is used, and we have to install it into the target\n self.setup_qemu()\n\n # And second stage must be run\n logging.info(\"doing debootstrap stage 2\")\n debootstrap_command = \"LANG=C sudo chroot \" + self.project.rootfs_mountpoint\n debootstrap_command += \" /debootstrap/debootstrap --second-stage\"\n self.execute_command(debootstrap_command)\n\n\n # Mount bind /proc into the rootfs mountpoint\n sudo_command = \"sudo mount --bind --make-rslave /proc \" + self.project.rootfs_mountpoint + \"/proc\"\n self.execute_command(sudo_command)\n self.proc_is_mounted = True\n\n # Mount bind /dev/pts into the rootfs mountpoint\n sudo_command = \"sudo mount --bind --make-rslave /dev/pts \" + self.project.rootfs_mountpoint + \"/dev/pts\"\n self.execute_command(sudo_command)\n self.devpts_is_mounted = True\n\n # Mount bind /dev/shm into the rootfs mountpoint\n sudo_command = \"sudo mount --bind --make-rslave /dev/shm \" + self.project.rootfs_mountpoint + \"/dev/shm\"\n self.execute_command(sudo_command)\n self.devshm_is_mounted = True\n\n # Update the APT sources\n self.generate_apt_sources_configuration()\n\n # Then update the list of packages\n apt_command = \"sudo chroot \" + self.project.rootfs_mountpoint + \" /usr/bin/apt-get update\"\n self.execute_command(apt_command)\n\n # Install extra packages into the chroot\n apt_command = \"sudo chroot \" + self.project.rootfs_mountpoint + \" /usr/bin/apt-get install --no-install-recommends --yes --allow-unauthenticated apt-utils ansible\"\n self.execute_command(apt_command)\n\n # Generate a unique build timestamp into /etc/dft_version\n self.generate_build_number()", "def testMakeMountCommands(self):\n self.maxDiff = None\n container_obj = self.explorer_object.GetContainer(\n '7b02fb3e8a665a63e32b909af5babb7d6ba0b64e10003b2d9534c7d5f2af8966')\n commands = container_obj.storage_object.MakeMountCommands(\n container_obj, '/mnt')\n commands = [' '.join(x) for x in commands]\n expected_commands = [\n (\n '/bin/mount -t aufs -o ro,br=test_data/docker/aufs/diff/test_data/'\n 'docker/aufs/diff/'\n 'b16a494082bba0091e572b58ff80af1b7b5d28737a3eedbe01e73cd7f4e01d23'\n '=ro+wh none /mnt'),\n (\n '/bin/mount -t aufs -o ro,remount,append:test_data/docker/aufs/diff/'\n 'b16a494082bba0091e572b58ff80af1b7b5d28737a3eedbe01e73cd7f4e01d23'\n '-init=ro+wh none /mnt'),\n (\n '/bin/mount -t aufs -o ro,remount,append:test_data/docker/aufs/diff/'\n 'd1c54c46d331de21587a16397e8bd95bdbb1015e1a04797c76de128107da83ae'\n '=ro+wh none /mnt'),\n (\n '/bin/mount --bind -o ro test_data/docker/volumes/'\n '28297de547b5473a9aff90aaab45ed108ebf019981b40c3c35c226f54c13ac0d/'\n '_data /mnt/var/jenkins_home')\n ]\n self.assertEqual(expected_commands, commands)", "def testMountCommand(self):\n with self.assertRaises(FilePathException):\n File().getGirderMountFilePath(self.file)\n self.assertIsNone(File().getGirderMountFilePath(self.file, validate=False))\n mountPath = tempfile.mkdtemp()\n subprocess.check_call(['girder', 'mount', mountPath, '-d', os.environ['GIRDER_TEST_DB']])\n endTime = time.time() + 10 # maximum time to wait\n while time.time() < endTime:\n if os.path.exists(os.path.join(mountPath, 'user')):\n break\n time.sleep(0.1)\n filePath = os.path.join(mountPath, 'user', 'admin', 'Public', 'test', 'file1a.txt')\n self.assertEqual(File().getGirderMountFilePath(self.file), filePath)\n self.assertNotEqual(File().getGirderMountFilePath(self.file),\n File().getLocalFilePath(self.file))\n self.assertTrue(os.path.exists(filePath))\n self.assertEqual(open(filePath).read().strip(), 'File 1A')\n subprocess.check_call(['girder', 'mount', mountPath, '-u'])\n endTime = time.time() + 10 # maximum time to wait\n while time.time() < endTime:\n if not os.path.exists(os.path.join(mountPath, 'user')):\n break\n time.sleep(0.1)\n self.assertFalse(os.path.exists(filePath))\n os.rmdir(mountPath)\n with self.assertRaises(FilePathException):\n File().getGirderMountFilePath(self.file)", "def test_pre_post_hooks(self):\n os.makedirs('/tmp/localhost/pacha_pre')\n os.makedirs('/tmp/localhost/pacha_post')\n pre_script = open('/tmp/localhost/pacha_pre/foo.sh', 'w')\n pre_script.write('''touch /tmp/localhost/pre_got_executed.txt''')\n pre_script.close()\n post_script = open('/tmp/localhost/pacha_post/bar.sh', 'w')\n post_script.write('''touch /tmp/localhost/post_got_executed.txt''')\n post_script.close()\n run = rebuild.Rebuild(hostname='localhost') \n run.pre_hooks()\n run.post_hooks()\n self.assertTrue(os.path.isfile('/tmp/localhost/post_got_executed.txt'))\n self.assertTrue(os.path.isfile('/tmp/localhost/pre_got_executed.txt'))", "def cat_cmd(server, client, line):\n if len(line.split(' ')) > 1 and line.split(' ')[1] == \"/proc/mounts\":\n path = os.path.dirname(os.path.realpath(__file__))\n path = path[:-7] # shaves off /engine\n with open(\"{}/fakefiles/proc%mounts\".format(path), \"r\") as f:\n response = f.read()\n client.exit_status = 0\n else:\n response = client.run_in_container(line)\n client.send(response)", "def mount(self):\n return self._mount", "def testMakeMountCommands(self):\n container_obj = self.explorer_object.GetContainer(\n 'de44dd97cfd1c8d1c1aad7f75a435603991a7a39fa4f6b20a69bf4458809209c')\n commands = container_obj.storage_object.MakeMountCommands(\n container_obj, '/mnt')\n commands = [' '.join(x) for x in commands]\n expected_commands = [\n (\n '/bin/mount -t aufs -o ro,br=test_data/'\n 'docker/aufs/diff/'\n 'de44dd97cfd1c8d1c1aad7f75a435603991a7a39fa4f6b20a69bf4458809209c'\n '=ro+wh none /mnt'),\n (\n '/bin/mount -t aufs -o ro,remount,append:test_data/docker/aufs/diff/'\n 'de44dd97cfd1c8d1c1aad7f75a435603991a7a39fa4f6b20a69bf4458809209c'\n '-init=ro+wh none /mnt'),\n (\n '/bin/mount -t aufs -o ro,remount,append:test_data/docker/aufs/diff/'\n '1cee97b18f87b5fa91633db35f587e2c65c093facfa2cbbe83d5ebe06e1d9125'\n '=ro+wh none /mnt'),\n (\n '/bin/mount -t aufs -o ro,remount,append:test_data/docker/aufs/diff/'\n 'df557f39d413a1408f5c28d8aab2892f927237ec22e903ef04b331305130ab38'\n '=ro+wh none /mnt')\n ]\n self.assertEqual(expected_commands, commands)", "def command_mount_all(self):\n has_failed = False\n for system_id in self.environment.get_unmounted_ids():\n try:\n system = SystemModel.create_by_id(system_id, self.environment)\n controller = SystemControllerModel(system, self.environment)\n controller.mount()\n except SftpConfigException as e:\n sys.stderr.write('Cannot mount %s: %s\\n\\n' % (system_id, str(e)))\n has_failed = True\n except SftpMountException as e:\n sys.stderr.write('Cannot mount %s!\\n\\n' % system_id)\n sys.stderr.write('Mount command: \\n%s\\n\\n' % e.mount_cmd)\n sys.stderr.write('Command output: \\n%s\\n\\n' % e.mount_cmd_output)\n sys.exit(0 if not has_failed else 1)", "def commands():\n pass", "def commands():\n pass", "def commands():\n pass", "def commands():\n pass", "def post_run_cmds(self, host: str) -> tp.List[types.ShellCmdSpec]:\n raise NotImplementedError", "def testMakeMountCommands(self):\n container_obj = self.explorer_object.GetContainer(\n '5dc287aa80b460652a5584e80a5c8c1233b0c0691972d75424cf5250b917600a')\n commands = container_obj.storage_object.MakeMountCommands(\n container_obj, '/mnt')\n commands = [' '.join(cmd) for cmd in commands]\n expected_commands = [(\n '/bin/mount -t overlay overlay -o ro,lowerdir='\n 'test_data/docker/overlay/974e2b994f9db74e1ddd6fc546843bc65920e786612'\n 'a388f25685acf84b3fed1/upper:'\n 'test_data/docker/overlay/a94d714512251b0d8a9bfaacb832e0c6cb70f71cb71'\n '976cca7a528a429336aae/root '\n '/mnt')]\n self.assertEqual(expected_commands, commands)", "def testMakeMountCommands(self):\n self.maxDiff = None\n container_obj = self.explorer_object.GetContainer(\n '8e8b7f23eb7cbd4dfe7e91646ddd0e0f524218e25d50113559f078dfb2690206')\n commands = container_obj.storage_object.MakeMountCommands(\n container_obj, '/mnt')\n commands = [' '.join(cmd) for cmd in commands]\n expected_commands = [(\n '/bin/mount -t overlay overlay -o ro,lowerdir='\n 'test_data/docker/overlay2/'\n '92fd3b3e7d6101bb701743c9518c45b0d036b898c8a3d7cae84e1a06e6829b53/diff:'\n 'test_data/docker/overlay2/l/OTFSLJCXWCECIG6FVNGRTWUZ7D:'\n 'test_data/docker/overlay2/l/CH5A7XWSBP2DUPV7V47B7DOOGY /mnt')]\n self.assertEqual(expected_commands, commands)", "def __init__(self, connection, options=None, device=None, directory=None, prompt=None, newline_chars=None,\n runner=None):\n super(Mount, self).__init__(connection=connection, prompt=prompt, newline_chars=newline_chars, runner=runner)\n\n # Parameters defined by calling the command\n self.options = options\n self.device = device\n self.directory = directory\n\n # Internal variables\n self.current_ret['RESULT'] = list()\n self.current_ret['ON'] = dict()", "def onSpawn(self):\n self.spawned = True\n self._interactor.initialiseDevices()", "def run(self):\n\n self.steer()\n self.drive()" ]
[ "0.59750396", "0.5799191", "0.5756659", "0.56043506", "0.55664533", "0.5534101", "0.55339694", "0.5528653", "0.5525409", "0.5490769", "0.5465857", "0.546551", "0.5461396", "0.54246646", "0.5414721", "0.5411846", "0.53944814", "0.53874266", "0.53799397", "0.536231", "0.53342664", "0.53342664", "0.53342664", "0.53342664", "0.53294647", "0.5328204", "0.53191257", "0.5296806", "0.5295157", "0.5263722" ]
0.6451285
0
create the file system on the block device.
def _mkfs (self,blockDevice,timer): # build command string fsTypeString = None if (self._activeFileSystemConfig.fileSystemType == blinky_generated_enums.FileSystemTypeType.kExt3): fsTypeString = "ext3" if (self._activeFileSystemConfig.fileSystemType == blinky_generated_enums.FileSystemTypeType.kExt4): fsTypeString = "ext4" else: self._log("unsupported-fs-type").error("file system %s doesn't support type %s",self._activeFileSystemConfig.fileSystemType) return ReturnCodes.kGeneralError mkfsCmd = self._activeCommandsConfig.mkfs mkfsCmdExtras = self._activeCommandsConfig.mkfsExtras cmdString = mkfsCmd%{self.BLOCK_DEVICE_COMMAND_ELEMENT:blockDevice,self.TYPE_COMMAND_ELEMENT:fsTypeString} # update with extra parameters cmdString = self.__joinCmdStringWithExtras(cmdString,mkfsCmdExtras) # run stdout,stderr,rc = self._runCommand(cmdString,timer) if (rc == 0): self._log("fs-created").debug2("file system was successfully created on block device '%s'",blockDevice) return ReturnCodes.kOk else: self._log("fs-creation-failed").error("file system creation on block device '%s' failed! stderr=%s",blockDevice,stderr) return ReturnCodes.kGeneralError
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def create(self):\n self.create_file()", "def create(self, filesystem=None):\n raise NotImplementedError()", "def create(self, directory):\n\n if not self.preallocated:\n if directory:\n self.filename = '%s/%s' % (directory, self.filename)\n logging.info('Creating disk image: %s' % self.filename)\n qemu_img_output = run_cmd(qemu_img_path(), 'create', '-f', 'raw', self.filename, '%dM' % self.size)\n if not os.path.exists(self.filename): \n logging.info(\"Problem while creating raw image: %s\" % qemu_img_output)\n raise Exception(\"Problem while creating raw image: %s\" % qemu_img_output)\n\n # From here, we assume that self.filename refers to whatever holds the disk image,\n # be it a file, a partition, logical volume, actual disk..\n\n logging.info('Adding partition table to disk image: %s' % self.filename)\n run_cmd('parted', '--script', self.filename, 'mklabel', 'msdos')\n\n # Partition the disk \n for part in self.partitions:\n part.create(self)\n\n logging.info('Creating loop devices corresponding to the created partitions')\n self.vm.add_clean_cb(lambda : self.unmap(ignore_fail=True))\n kpartx_output = run_cmd('kpartx', '-av', self.filename)\n parts = []\n for line in kpartx_output.split('\\n'):\n if line == \"\" or line.startswith(\"gpt:\") or line.startswith(\"dos:\"):\n continue\n if line.startswith(\"add\"):\n parts.append(line)\n continue\n logging.error('Skipping unknown line in kpartx output (%s)' % line)\n mapdevs = []\n for line in parts:\n mapdevs.append(line.split(' ')[2])\n for (part, mapdev) in zip(self.partitions, mapdevs):\n part.mapdev = '/dev/mapper/%s' % mapdev\n\n # At this point, all partitions are created and their mapping device has been\n # created and set as .mapdev\n\n # Adds a filesystem to the partition\n logging.info(\"Creating file systems\")\n for part in self.partitions:\n part.mkfs()", "def disk_create(context, values):\n return NotImplemented", "def _create_regular_file(self, nms, path, size):\n block_size_mb = 1\n block_count = size * units.Gi / (block_size_mb * units.Mi)\n\n LOG.info('Creating regular file: %s.'\n 'This may take some time.', path)\n\n nms.appliance.execute(\n 'dd if=/dev/zero of=%(path)s bs=%(bs)dM count=%(count)d' % {\n 'path': path,\n 'bs': block_size_mb,\n 'count': block_count\n }\n )\n\n LOG.info('Regular file: %s created.', path)", "def create_files(self):\n self._do_action_under_lock(self._create_files)", "def generate_common_mount(self, working_file_name):\n\n # Reopenthe working file\n working_file = open(working_file_name, \"a\")\n\n # Check that the stack definition is in the configuration file\n if \"stack-definition\" not in self.project.firmware_definition[\"layout\"]:\n self.project.logging.critical(\"The stack definition is not in the configuration file\")\n exit(1)\n\n # Iterates the stack items\n for item in self.project.firmware_definition[\"layout\"][\"stack-definition\"]:\n # Generate the mount point creation code\n working_file.write(\"# Create the mount point for \" + item[\"stack-item\"][\"type\"] +\n \" '\" + item[\"stack-item\"][\"name\"] + \"'\\n\")\n working_file.write(\"mkdir -p /mnt/dft/\" + item[\"stack-item\"][\"name\"] + \"\\n\")\n working_file.write(\"\\n\")\n\n # Generate the mount commands\n working_file.write(\"# Mount item \" + item[\"stack-item\"][\"type\"] + \" '\" +\n item[\"stack-item\"][\"name\"] + \"'\\n\")\n\n # Generate the tmpfs specific mount command\n if item[\"stack-item\"][\"type\"] == \"tmpfs\":\n working_file.write(\"mount -t tmpfs \")\n\n # Is there some defined options ?\n if \"mount-options\" in item[\"stack-item\"]:\n # Yes, then append the options to the command\n working_file.write(\"-o \" + item[\"stack-item\"][\"mount-options\"] + \" \")\n\n # Complete the mount command\n working_file.write(\"tmpfs /mnt/dft/\" + item[\"stack-item\"][\"name\"] + \"\\n\")\n\n # Generate the tmpfs specific mount command\n if item[\"stack-item\"][\"type\"] == \"squashfs\":\n working_file.write(\"mount -t squashfs \")\n\n # Is there some defined options ?\n if \"mount-options\" in item[\"stack-item\"]:\n # Yes, then append the options to the command\n working_file.write(\"-o \" + item[\"stack-item\"][\"mount-options\"] + \" \")\n\n # Complete the mount command\n working_file.write(item[\"stack-item\"][\"squashfs-file\"] + \" /mnt/dft/\" +\n item[\"stack-item\"][\"name\"] + \" -o loop\\n\")\n\n # Generate the tmpfs specific mount command\n if item[\"stack-item\"][\"type\"] == \"partition\":\n working_file.write(\"mount \")\n\n # Is there some defined options ?\n if \"mount-options\" in item[\"stack-item\"]:\n # Yes, then append the options to the command\n working_file.write(\"-o \" + item[\"stack-item\"][\"mount-options\"] + \" \")\n\n # Complete the mount command\n working_file.write(item[\"stack-item\"][\"partition\"] + \" /mnt/dft/\" +\n item[\"stack-item\"][\"name\"] + \"\\n\")\n\n working_file.write(\"\\n\")\n\n # We are done here, now close the file\n working_file.close()", "def create_and_mount_brick(brick_device, brick_path, brickfs):\n\n # If brick device path is not starts with /dev then use\n # /brickdev prefix. Brick device directory passed by the user\n # is mounted as /brickdev to avoid mixing with any other\n # dirs inside container.\n if not brick_device.startswith(\"/dev/\"):\n brick_device = \"/brickdev/\" + os.path.basename(brick_device)\n\n mountdir = os.path.dirname(brick_path)\n os.makedirs(mountdir,\n mode=0o755,\n exist_ok=True)\n\n try:\n execute(\"mount\", brick_device, mountdir)\n logging.info(logf(\n \"Successfully mounted device on path\",\n fstype=brickfs,\n device=brick_device,\n mountdir=mountdir,\n ))\n except CommandException as err:\n logging.info(logf(\n \"Failed to mount device, continuing with mkfs\",\n err=err,\n fstype=brickfs,\n device=brick_device,\n mountdir=mountdir,\n ))\n if 'wrong fs type' in err.err:\n # This error pops up when we do mount on an empty device or wrong fs\n # Try doing a mkfs and try mount\n try:\n execute(MKFS_XFS_CMD, brick_device)\n logging.info(logf(\n \"Successfully created xfs file system on device\",\n fstype=brickfs,\n device=brick_device,\n ))\n except CommandException as err:\n if \"appears to contain an existing filesystem\" not in err.err:\n logging.error(logf(\n \"Failed to create file system\",\n fstype=brickfs,\n device=brick_device,\n error=err,\n ))\n sys.exit(1)\n else:\n logging.info(logf(\n \"Failed to perform mkfs on device. continuing with mount\",\n err=err,\n device=brick_device,\n mountdir=mountdir,\n ))\n try:\n execute(\"mount\", brick_device, mountdir)\n logging.info(logf(\n \"Successfully mounted device on path\",\n fstype=brickfs,\n device=brick_device,\n mountdir=mountdir,\n ))\n except CommandException as err:\n logging.error(logf(\n \"Failed to mount export brick (after mkfs)\",\n fstype=brickfs,\n device=brick_device,\n mountdir=mountdir,\n error=err,\n ))\n sys.exit(1)\n\n elif 'already mounted' not in err.err:\n logging.error(logf(\n \"Failed to mount export brick\",\n fstype=brickfs,\n device=brick_device,\n mountdir=mountdir,\n error=err,\n ))\n sys.exit(1)\n\n else:\n pass", "def bdev_uring_create(client, filename, name, block_size=None):\n params = {'name': name,\n 'filename': filename}\n\n if block_size:\n params['block_size'] = block_size\n\n return client.call('bdev_uring_create', params)", "def auto_create_filesystem(self):\n\n key = self.km.gpg_key['fingerprint']\n root = yield BuddyNode.get_node(self.start_port, self.known_ip,\n self.known_port).get_root(key)\n\n if root:\n self.tree.register_root_inode(root)\n else:\n logger.info('Did not find existing root inode pointer.'\n ' Generating new root inode pointer.')\n self.tree.generate_root_inode()", "def bdev_aio_create(client, filename, name, block_size=None, readonly=False):\n params = {'name': name,\n 'filename': filename}\n\n if block_size:\n params['block_size'] = block_size\n\n if readonly:\n params['readonly'] = readonly\n\n return client.call('bdev_aio_create', params)", "def createDisk(self , name):\n return", "def makeFs(partitionDevice, fsType, label=None, force=False, options=None):\n if force and os.path.exists(partitionDevice):\n path = partitionDevice\n else:\n path = '/dev/{0}'.format(partitionDevice)\n if not os.path.exists(path):\n raise IOError('{0} does not exist'.format(path))\n if not S_ISBLK(os.stat(path).st_mode):\n raise IOError('{0} is not a block device'.format(path))\n if fsType not in ('ext2', 'ext3', 'ext4', 'xfs', 'reiserfs', 'jfs', 'btrfs', 'ntfs', 'fat16', 'fat32', 'swap'):\n raise Exception('{0} is not a recognized filesystem.'.format(fsType))\n if fsType in ('ext2', 'ext3', 'ext4'):\n return _makeExtFs(path, int(fsType[3]), label, options, force)\n elif fsType == 'xfs':\n return _makeXfs(path, label, options, force)\n elif fsType == 'reiserfs':\n return _makeReiserfs(path, label, options, force)\n elif fsType == 'jfs':\n return _makeJfs(path, label, options, force)\n elif fsType == 'btrfs':\n return _makeBtrfs(path, label, options, force)\n elif fsType == 'ntfs':\n return _makeNtfs(path, label, options, force)\n elif fsType in ('fat16', 'fat32'):\n return _makeFat(path, fsType == 'fat32', label, options, force)\n elif fsType == 'swap':\n return _makeSwap(path, label, options, force)\n return None # should not append", "def mount_block(block):\n # type: (str) -> str\n\n dir_path = tempfile.mkdtemp(prefix='mount-')\n _mount(block, dir_path)\n\n return dir_path", "def create_system(sys_structure):\n pass", "def mkfs(fs, path, label=None):\n if fs == 'swap':\n args = ['mkswap']\n else:\n args = ['mkfs', '-t', fs]\n # add -F to force no interactive execute on non-block device.\n if fs in ('ext3', 'ext4'):\n args.extend(['-F'])\n if label:\n if fs in ('msdos', 'vfat'):\n label_opt = '-n'\n else:\n label_opt = '-L'\n args.extend([label_opt, label])\n args.append(path)\n execute(*args)", "def test_post_creation(self):\n host = synthetic_host(\"myserver\")\n self.create_simple_filesystem(host)\n\n spare_volume = synthetic_volume_full(host)\n\n response = self.api_client.post(\n \"/api/target/\", data={\"kind\": \"OST\", \"filesystem_id\": self.fs.id, \"volume_id\": spare_volume.id}\n )\n self.assertHttpAccepted(response)", "def set_file_system( # pylint: disable=too-many-arguments\n self,\n user_open,\n user_close,\n user_read,\n user_seek,\n user_async_read,\n user_async_cancel,\n block_align=-1,\n ):\n self._call_fmod(\n \"FMOD_System_SetFileSystem\",\n FILE_OPEN_CALLBACK(user_open),\n FILE_CLOSE_CALLBACK(user_close),\n FILE_READ_CALLBACK(user_read),\n FILE_SEEK_CALLBACK(user_seek),\n FILE_ASYNCREAD_CALLBACK(user_async_read),\n FILE_ASYNCCANCEL_CALLBACK(user_async_cancel),\n block_align,\n )", "def __init__(self, backend, open_nonblock=True):\n\n (self._path_in, self._path_out) = get_vsys_fifo_names(backend)\n self._open_nonblock = open_nonblock\n self._fd_in = None\n self._fd_out = None\n\n # Check that file exists.\n if (not vsys_fifo_exists(self._path_in) or\n not vsys_fifo_exists(self._path_out)):\n raise VsysCreateException('vsys FIFOs not found: %s, %s' %\n (self._path_in, self._path_out))", "def create_volume(self, node_name, init_values, *files):\n node_folder = os.path.join(self.TMP_FOLDER, node_name)\n os.makedirs(node_folder)\n\n for file in files:\n shutil.copyfile(file, os.path.join(node_folder, os.path.basename(file)))\n\n self._create_init_values_file(node_folder, init_values)\n self._create_config_file(node_name, node_folder)\n\n return node_folder", "def new_file():\n if port != '5000':\n values = request.get_json()\n if not values:\n response = {\n 'message': 'No data found'\n }\n return jsonify(response), 400\n if 'name' not in values or 'path' not in values or 'chunk_size' not in values:\n response = {\n 'message': 'Name, path or chunk size was not found'\n }\n return jsonify(response), 400\n \n #get the information to create a new file object\n name = values['name']\n path = values['path']\n chunk_size = values['chunk_size']\n\n #reset the file object\n file.chunks = []\n file.fat = []\n file.file_size = 0\n file.name = name\n file.path = path\n file.chunk_size = int(chunk_size)\n file.owner = str(port)\n if file.isFile():\n fat_file = {\n 'file_name': file.name,\n 'file_owner': file.owner,\n 'fat': []\n }\n hash_table.fat.append(fat_file)\n\n #split the file into chunks of data to distribute between peers\n chunk_hashes = file.split_to_chunks()\n\n MT = MerkleTreeHash()\n root_hash = MT.find_merkle_hash(chunk_hashes)\n\n #make a new blockchain for the file that was crreated\n new_blockchain = Blockchain('', '')\n\n #update some of its properties \n new_blockchain.file_name = file.name\n new_blockchain.file_size = file.file_size\n new_blockchain.chunk_number = len(file.chunks)\n new_blockchain.last_chunk_size = file.file_size%int(chunk_size)\n new_blockchain.root_node = root_hash\n\n\n url = 'http://localhost:5000/new-file'\n try:\n response = requests.post(url, json={\n 'file_name': new_blockchain.file_name,\n 'file_size': new_blockchain.file_size,\n 'chunk_number': new_blockchain.chunk_number,\n 'last_chunk_size': new_blockchain.last_chunk_size,\n 'root_node': new_blockchain.root_node})\n if response.status_code == 400 or response.status_code == 500:\n print('Sending files declined')\n return False\n except requests.exceptions.ConnectionError:\n print('connection exception handled')\n return False\n \n\n url = 'http://localhost:5000/get-dht-size'\n value = requests.get(url)\n json_value = value.json()\n dht_size = json_value['dht_size']\n file.distribute_chunks(int(dht_size))\n\n\n\n #update blockchain files with the new information\n \n\n \n response = {\n 'message': 'File added successfully',\n 'file_name': file.name,\n 'file_size': file.file_size,\n 'file_path': path + name,\n 'number_of_chunks': len(file.chunks),\n 'chunks': file.print_chunks(),\n 'chunk_size': chunk_size,\n 'last_chunk_size': file.file_size%int(chunk_size),\n 'file_creator': 'localhost:' + str(port)\n }\n return jsonify(response), 201\n response = {\n 'message': 'Something went wrong'\n }\n return jsonify(response), 400", "def create(self):\n self.file = open(self.filename, \"xb\", buffering=self.bufferSize)", "def create(self, spec, force_cache):\n\n instance_id = self.get_instance_id(spec)\n instance_dir = os.path.join(self.directory, instance_id)\n # create the directory to hold all the bits\n logger.info(\"Creating directory %s\" % (instance_dir, ))\n os.mkdir(instance_dir)\n\n logger.info(\"Creating virtual machine\")\n self.vboxmanage(\"createvm\", name=instance_id, directory=self.directory, ostype=self.ostype[spec.image.distro])\n self.vboxmanage(\"configurevm\", name=instance_id, memsize=spec.hardware.memory)\n network = self.guess_network()\n network.configurevm(instance_id)\n\n logger.info(\"Creating disk image from %s\" % (spec.image, ))\n # create the disk image and attach it\n disk = os.path.join(instance_dir, instance_id + \"_disk1.vdi\")\n self.qemu_img(\"convert\", source=spec.image.fetch(self.image_dir, force_cache), destination=disk, format=\"vdi\")\n self.vboxmanage(\"create_sata\", name=instance_id)\n self.vboxmanage(\"attach_disk\", name=instance_id, disk=disk)\n\n # create the seed ISO\n logger.info(\"Creating cloudinit seed\")\n config_class = self.configs[spec.image.distro]\n cloud_config = config_class(spec)\n meta_data = MetaData(spec.name)\n seed = Seed(instance_dir, cloud_config=cloud_config, meta_data=meta_data)\n seed.write()\n\n logger.info(\"Attaching devices\")\n # connect the seed ISO and the tools ISO\n self.vboxmanage(\"create_ide\", name=instance_id)\n self.vboxmanage(\"attach_ide\", name=instance_id, port=\"0\", device=\"0\", filename=seed.pathname)\n self.vboxmanage(\"attach_ide\", name=instance_id, port=\"0\", device=\"1\", filename=\"/usr/share/virtualbox/VBoxGuestAdditions.iso\")\n logger.info(\"Machine created\")\n\n logger.info(\"Mounting host drive\")\n hostpath = os.path.expanduser(\"~\")\n self.vboxmanage(\"mount\", name=instance_id, hostpath=hostpath)\n return self.load(instance_id)", "def generate_debootstrap_rootfs(self):\n\n logging.info(\"starting to generate debootstrap rootfs\")\n\n # Generate the base debootstrap command\n debootstrap_command = \"sudo debootstrap --no-check-gpg\"\n\n # Add the foreign and arch only if they are different from host, and\n # thus if use_qemu_static is True\n if self.use_qemu_static:\n logging.info(\"running debootstrap stage 1\")\n debootstrap_command += \" --foreign --arch=\" + self.project.target_arch\n else:\n logging.info(\"running debootstrap\")\n\n # Add the target, mount point and repository url to the debootstrap command\n debootstrap_command += \" \" + self.project.target_version + \" \"\n debootstrap_command += self.project.rootfs_mountpoint + \" \"\n debootstrap_command += self.project.project_definition[\"project-definition\"][\"debootstrap-repository\"]\n\n # Finally run the subprocess\n self.execute_command(debootstrap_command)\n\n # Check if we are working with foreign arch, then ...\n if self.use_qemu_static:\n # QEMU is used, and we have to install it into the target\n self.setup_qemu()\n\n # And second stage must be run\n logging.info(\"doing debootstrap stage 2\")\n debootstrap_command = \"LANG=C sudo chroot \" + self.project.rootfs_mountpoint\n debootstrap_command += \" /debootstrap/debootstrap --second-stage\"\n self.execute_command(debootstrap_command)\n\n\n # Mount bind /proc into the rootfs mountpoint\n sudo_command = \"sudo mount --bind --make-rslave /proc \" + self.project.rootfs_mountpoint + \"/proc\"\n self.execute_command(sudo_command)\n self.proc_is_mounted = True\n\n # Mount bind /dev/pts into the rootfs mountpoint\n sudo_command = \"sudo mount --bind --make-rslave /dev/pts \" + self.project.rootfs_mountpoint + \"/dev/pts\"\n self.execute_command(sudo_command)\n self.devpts_is_mounted = True\n\n # Mount bind /dev/shm into the rootfs mountpoint\n sudo_command = \"sudo mount --bind --make-rslave /dev/shm \" + self.project.rootfs_mountpoint + \"/dev/shm\"\n self.execute_command(sudo_command)\n self.devshm_is_mounted = True\n\n # Update the APT sources\n self.generate_apt_sources_configuration()\n\n # Then update the list of packages\n apt_command = \"sudo chroot \" + self.project.rootfs_mountpoint + \" /usr/bin/apt-get update\"\n self.execute_command(apt_command)\n\n # Install extra packages into the chroot\n apt_command = \"sudo chroot \" + self.project.rootfs_mountpoint + \" /usr/bin/apt-get install --no-install-recommends --yes --allow-unauthenticated apt-utils ansible\"\n self.execute_command(apt_command)\n\n # Generate a unique build timestamp into /etc/dft_version\n self.generate_build_number()", "def bdev_daos_create(client, num_blocks, block_size, pool, cont, name, oclass=None, uuid=None):\n params = {'num_blocks': num_blocks, 'block_size': block_size, 'pool': pool, 'cont': cont, 'name': name}\n if uuid:\n params['uuid'] = uuid\n if oclass:\n params['oclass'] = oclass\n return client.call('bdev_daos_create', params)", "def attach_file_system(self, user_open, user_close, user_read, user_seek):\n if user_open:\n user_open = FILE_OPEN_CALLBACK(user_open)\n if user_close:\n user_close = FILE_CLOSE_CALLBACK(user_close)\n if user_read:\n user_read = FILE_READ_CALLBACK(user_read)\n if user_seek:\n user_seek = FILE_SEEK_CALLBACK(user_seek)\n self._call_fmod(\n \"FMOD_System_AttachFileSystem\", user_open, user_close, user_read, user_seek\n )\n self._user_open = user_open\n self._user_close = user_close\n self._user_read = user_read\n self._user_seek = user_seek", "def mkfs(fs, path, label=None):\n if fs == 'swap':\n args = ['mkswap']\n else:\n args = ['mkfs', '-t', fs]\n # add -F to force no interactive execute on non-block device.\n if fs in ('ext3', 'ext4'):\n args.extend(['-F'])\n if label:\n if fs in ('msdos', 'vfat'):\n label_opt = '-n'\n else:\n label_opt = '-L'\n args.extend([label_opt, label])\n args.append(path)\n try:\n execute(*args, run_as_root=True, use_standard_locale=True)\n except processutils.ProcessExecutionError as e:\n with excutils.save_and_reraise_exception() as ctx:\n if os.strerror(errno.ENOENT) in e.stderr:\n ctx.reraise = False\n LOG.exception('Failed to make file system. '\n 'File system %s is not supported.', fs)\n raise exception.FileSystemNotSupported(fs=fs)\n else:\n LOG.exception('Failed to create a file system '\n 'in %(path)s. Error: %(error)s',\n {'path': path, 'error': e})", "def crear_fs(raiz, nvol):\n if nvol == None:\n nvol = \"NUEVO_VOL\"\n size_nvol = len(nvol)\n if size_nvol < 15:\n sobrante_nvol = 15 - size_nvol\n with open(raiz,\"w+\") as f:\n f.write((\"\\x00\"*(512*1440)))\n filesys = mmap.mmap(f.fileno(),0)\n filesys[0:8] = \"FiUnamFS\".encode('ascii')\n filesys[10:13] = \"0.7\".encode('ascii')\n filesys[20:35] = str((\"0\"*sobrante_nvol)+nvol).encode('ascii')\n filesys[40:45] = \"00512\".encode('ascii')\n filesys[47:49] = \"04\".encode('ascii')\n filesys[52:60] = \"00001440\".encode('ascii')\n for i in range(64):\n self.escribir_indir(filesys,i)\n filesys[512*5:] = str(\"\\x00\"*(512*1435)).encode('ascii')\n f.close()", "def fs(tmp_path_factory):\n dir_ = tmp_path_factory.mktemp(\"\")\n for key, val in file_dirs.fs1.items():\n d_ = dir_ / key\n d_.mkdir()\n for v in val:\n f = d_ / v\n f.write_text(v)\n\n return dir_", "def create_block_file(blockTxns):\n textfile = open(\"/content/block.txt\", \"w\")\n for element in blockTxns:\n textfile.write(element + \"\\n\")\n textfile. close()" ]
[ "0.6528467", "0.651849", "0.6473016", "0.6375333", "0.62772226", "0.61223996", "0.6070813", "0.6032275", "0.59915876", "0.59814245", "0.59137577", "0.5885163", "0.58850354", "0.5881064", "0.58809644", "0.58729494", "0.584595", "0.5844075", "0.58207464", "0.5786709", "0.5760435", "0.5742951", "0.57260317", "0.57194334", "0.5703354", "0.5692844", "0.5667153", "0.56642675", "0.5642703", "0.5636323" ]
0.7982237
0
Parses the first line of a log record.
def _ParseRecordStart(self, structure): self._event_data = APTHistoryLogEventData() time_elements_structure = self._GetValueFromStructure( structure, 'date_time') self._event_data.start_time = self._ParseTimeElements( time_elements_structure)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def __init__(self, line):\n # Throw an exception if we don't see the parenthesis that mark a history entry\n if not line[108] == '(':\n raise ParsingException\n if not line[138:139] == ')':\n raise ParsingException\n\n self.status = line[109:122].strip()\n self.time_stamp = datetime.strptime(line[122:138], '%m/%d/%Y %H:%M')", "def parse_line(log_line):\n\n logger = logging.getLogger(__name__)\n\n REGEX = [\n # universal-transcoder\n re.compile('.*GET\\s\\/music\\/:\\/transcode\\/universal\\/start\\.mp3.*metadata%2F(\\d+)\\&.*'),\n # stream based transcoder\n re.compile('.*\\sDEBUG\\s-\\sLibrary\\sitem\\s(\\d+)\\s\\'.*\\'\\sgot\\splayed\\sby\\saccount.*')\n ]\n\n for regex in REGEX:\n m = regex.match(log_line)\n\n if m:\n logger.info('Found played song and extracted library id \"{l_id}\" from plex log '.format(l_id=m.group(1)))\n return m.group(1)", "def parse_line_from(self, match):\n self.line = match.group(3)\n self.filename = match.group(2)\n self.message = match.group(1)\n self.eoli = match.group(4)\n\n self.fix_filename()\n self.fix_namespaces()\n self.fix_nonerrors()\n\n if self.filename is None or self.line is None:\n return \"\"\n else:\n return \"{} {}:{}{}\\n\".format(self.message, self.filename, self.line, self.eoli)", "def parseLog(self, log):\n return 0", "def parse_line(self, line):\n if self.signal_eof:\n return \"\"\n\n match = re.search(\"^([\\w\\s]+from) ([^:]+):(\\d+)(:|,)$\", line)\n if match:\n return self.parse_line_from(match)\n\n match = re.search(\"^([^:]+):(?:((?:\\d+:)?\\d+):)?(?:(error|warning|note):)?(.+)$\", line)\n if match:\n return self.parse_line_err(match)\n\n return line", "def parse_log_entry(line):\n\n line_pattern = r\"^(?P<host>.*) - - \\[(?P<timestamp>.*)\\] \" \\\n \"\\\"(?P<request>.*)\\\" (?P<http_code>\\d\\d\\d) (?P<bytes>.*)$\"\n line_groups = re.match(line_pattern, line)\n request_pattern = r\"^(?P<request_method>[A-Z]*) (?P<resource>\\S+) ?.*$\"\n request_groups = re.match(request_pattern, line_groups.group('request'))\n host = line_groups.group('host')\n timestamp = line_groups.group('timestamp')\n timestamp = parse_date(line_groups.group('timestamp'))\n http_code = int(line_groups.group('http_code'))\n num_bytes = line_groups.group('bytes')\n num_bytes = 0 if num_bytes == '-' else int(num_bytes)\n if request_groups:\n request_method = request_groups.group('request_method')\n resource = request_groups.group('resource')\n else:\n request_method = None\n resource = None\n return ParsedRequest(\n host, timestamp, request_method,\n resource, http_code, num_bytes)", "def parse(self, line):\n try:\n (year, month, day, hour, minute, second, microseconds, offset_hour, offset_minute, source, process, logentry) = re.match('^(\\d\\d\\d\\d)-(\\d\\d)-(\\d\\d)T(\\d\\d):(\\d\\d):(\\d\\d)\\.([\\d]+)\\+(\\d\\d):(\\d\\d) ([a-z]+)\\[([a-zA-Z0-9_.]+)\\]: ([0-9a-z-A-Z\\-_\\.\\[\\]:\\?\\#\\\",/\\ ={}\\'\\(\\)<>]+)$', line).groups()\n except:\n pass\n \n try:\n parsed_data = dict()\n parsed_data['timestamp'] = \" \".join([\"-\".join([year, month, day]), \":\".join([hour, minute, second])])\n parsed_data['log_time'] = datetime.datetime(int(year), int(month), int(day), int(hour), int(minute), int(second))\n parsed_data['log_source'] = source\n parsed_data['log_type'] = process\n except (AttributeError, UnboundLocalError):\n PARSE_ERRORS.append(line)\n return False\n\n #TODO: This still needs work on spaces in values surrounded by \" \" \n if parsed_data['log_source'] == \"heroku\":\n if logentry.__len__() > 1:\n logentry = re.sub(', ', ',', logentry)\n line_chunks = re.split(' ', logentry)\n for chunk in line_chunks:\n line_chunks = re.split('=', chunk)\n if line_chunks.__len__() > 2:\n #fwd and path are a little clunky to parse\n pass\n elif line_chunks.__len__() > 1:\n parsed_data[line_chunks[0]] = line_chunks[1]\n else:\n pass\n else:\n return False\n else:\n # TODO: [app] \n # Needs parsing. Do that here.\n return False\n\n return parsed_data", "def processLogLine(logline):\n logline = logline.split()\n log = LogLine(logline[0], logline[1], logline[2], logline[4],\\\n float(logline[6]), float(logline[8]), float(logline[10]), logline[12])\n return log", "def read_linelog():", "def parse_log_file(filename, job_name):\n\n time_re = \"(\\d{4}/\\d{2}/\\d{2} \\d{2}:\\d{2}:\\d{2})\"\n time_pat = re.compile(time_re)\n pat = re.compile(time_re + \".*RUM\\.Workflow.*(START|FINISH)\\s+(.*)\")\n\n time_fmt = \"%Y/%m/%d %H:%M:%S\"\n\n first_time = None\n \n with open(filename) as f:\n for line in f:\n if first_time is None:\n m = time_pat.match(line)\n if m is None:\n raise Exception(\"Couldn't parse time from \" + line)\n tm = m.group(1)\n print \"TM is \" + str(tm)\n first_time = time.strptime(tm, time_fmt)\n print \"First time is \" + str(first_time)\n\n yield Event(first_time, 'START', 'log', job_name, filename)\n m = pat.match(line)\n if (m is not None):\n (tm, type, step) = m.groups()\n t = time.strptime(tm, time_fmt)\n e = Event(t, type, step, job_name, filename)\n yield e", "def parse_line(line):\n log_line = LogLine(line)\n dt = datetime.datetime.strptime(log_line.line[0], \"%Y-%m-%d %H:%M:%S\")\n # make a tuple with dt and the rest (splatted)\n return (dt, *log_line.line[1:])", "def parse_header(line):\n # 2015-09-27 14:55:41 UTC [192.0.2.1]:56721 -> [192.0.2.2]:443 (37):\n m = re.match(r'(\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2} \\S+) \\[(.+?)\\]:(\\d+) -> \\[(.+?)\\]:(\\d+) \\((\\d+|EOF)\\):?', line)\n if not m:\n raise LogSyntaxError(line)\n res = {}\n res['timestamp'] = m.group(1)\n res['src_addr'] = m.group(2)\n res['src_port'] = int(m.group(3))\n res['dst_addr'] = m.group(4)\n res['dst_port'] = int(m.group(5))\n if m.group(6) == 'EOF':\n res['eof'] = True\n else:\n res['eof'] = False\n res['size'] = int(m.group(6))\n return res", "def process_log_line(self, line):\n int_map = self.int_map\n timestamp = line[0:26]\n if len(timestamp) >= 26:\n msg = {}\n try:\n # %Y-%m-%d %H:%M:%S.%f - 2017-06-27 13:46:10.048844\n day = int_map[timestamp[8:10]]\n hour = int_map[timestamp[11:13]]\n minute = int_map[timestamp[14:16]]\n second = int_map[timestamp[17:19]]\n usecond = int_map[timestamp[20:22]] * 10000 + \\\n int_map[timestamp[22:24]] * 100 + int_map[timestamp[24:26]]\n event_time = (hour * 3600.0 + minute * 60.0 + second) + (usecond / 1000000)\n if day == self.start_day:\n elapsed = event_time - self.start_time\n else:\n elapsed = event_time + (float(3600 * 24) - self.start_time)\n msg['timestamp'] = elapsed\n if msg['timestamp'] >= 0:\n offset = line.find(']: ', 32)\n if offset >= 0:\n try:\n thread = line[34:offset]\n separator = thread.find(':')\n if separator >= 0:\n thread = thread[separator + 1:].strip()\n msg['thread'] = thread\n msg['level'] = line[offset + 3:offset + 4]\n msg_start = line.find(' ', offset + 5)\n if msg_start >= 0:\n msg['category'] = line[offset + 5:msg_start]\n msg['message'] = line[msg_start + 1:]\n if msg['category'] == 'nsHttp':\n if msg['thread'] == 'Main Thread':\n self.main_thread_http_entry(msg)\n elif msg['thread'] == 'Socket Thread':\n self.socket_thread_http_entry(msg)\n elif msg['category'] == 'nsSocketTransport':\n self.socket_transport_entry(msg)\n elif msg['category'] == 'nsHostResolver':\n self.dns_entry(msg)\n except Exception:\n logging.exception('Error processing log line')\n except Exception:\n pass", "def first_line(self):\n with open(self.file_path) as file:\n return file.readline()", "def to_line_start(self):\n # type: () -> LineNo\n metadata = self.safely_parse_metadata()\n return metadata[-1][0]", "def parse(file):\n logger.info('parsing DL7 dive log data')\n log = Log()\n content = file.readline()\n while not content == '':\n __parse_line(log, content)\n content = file.readline()\n return log", "def parse(self):\n i = 0\n while i < len(self.__lines):\n line = self.__lines[i]\n dt = re.match(r\"(\\d{4}-\\d{1,2}-\\d{1,2}\\s\\d{1,2}:\\d{1,2}:\\d{1,2})\", line)\n if not dt:\n i += 1\n continue\n log = {\n \"datetime\": dt.group()\n }\n line = line[dt.end()+1:].rstrip(\"\\n\")[::-1]\n qq_flag = line.find(\"(\")\n log[\"qq\"] = line[qq_flag-1:0:-1]\n log[\"name\"] = line[:qq_flag:-1].strip(\" \")\n i += 1\n log[\"content\"] = self.__lines[i].rstrip(\"\\n\")\n while self.__lines[i+1] != \"\\n\":\n i += 1\n log[\"content\"] += \" \" + self.__lines[i].rstrip(\"\\n\")\n self.__logs.append(log)\n i += 2", "def parse_file(self):\n # read the first line in the file\n line = self._stream_handle.readline()\n\n while line:\n # check for a data line or a dcl logger line we specifically ignore\n data_match = DATA_LINE_MATCHER.match(line)\n ignore_match = IGNORE_LINE_MATCHER.match(line)\n\n if data_match:\n # found a data line, extract this particle\n # DCL controller timestamp is the port_timestamp\n dcl_controller_timestamp = data_match.groups()[DCL_TIMESTAMP_GROUP]\n port_timestamp = dcl_time_to_ntp(dcl_controller_timestamp)\n\n particle = self._extract_sample(self.particle_class,\n None,\n data_match,\n port_timestamp=port_timestamp,\n preferred_ts=DataParticleKey.PORT_TIMESTAMP)\n\n self._record_buffer.append(particle)\n\n elif not ignore_match:\n # we found a line with an unknown format, call an exception\n error_message = 'Found line with unknown format %s' % line\n log.warn(error_message)\n self._exception_callback(SampleException(error_message))\n\n # read the next line\n line = self._stream_handle.readline()", "def parse_line(self, line: str) -> None:\n self._count += 1", "def _next_record(self, next_line):\n record = self.loader.parse_record_stream(self.reader,\n next_line,\n self.known_format)\n\n self.member_info = None\n\n # Track known format for faster parsing of other records\n self.known_format = record.format\n\n return record", "def decodeline(self, line):\n result = ApacheLogLine()\n result.full_line = line\n linepatternmatch = self._linepattern.match(line)\n if linepatternmatch:\n result.hostname = linepatternmatch.group(1)\n result.user = linepatternmatch.group(2)\n if result.user == '-':\n result.user = ''\n (result.accesstime_seconds, result.serveroffset) = self.parsedate(linepatternmatch.group(3))\n result.accesstime_string = stringdate(result.accesstime_seconds, offset=result.serveroffset)\n result.file = linepatternmatch.group(4)\n result.code = linepatternmatch.group(5)\n result.code_description = self._codetranslator.get_description(result.code)\n result.size = linepatternmatch.group(6)\n if result.size == '-':\n result.size = 0\n result.referer = linepatternmatch.group(7)\n if result.referer == '-':\n result.referer = ''\n result.browser = linepatternmatch.group(8)\n else:\n self._notparsable += 1\n warn(\"The line '%s' could not be parsed\" % line)\n return None\n if self._line_fits_pattern(result):\n self._acceptedlines += 1\n return result\n else:\n self._rejectedlines += 1\n return None", "def parse_log_start_time(log_data):\n try:\n # Get the log starting time\n time_match = search(\n r\"Log Started at (\\w+, \\w+ \\d{2}, \\d{4} \\d{2}:\\d{2}:\\d{2})\",\n log_data)\n log_start_time = datetime.strptime(\n time_match.group(1), \"%A, %B %d, %Y %H:%M:%S\")\n\n # Get the timezone of the log\n timezone_match = search(\n r\"<\\d{2}:\\d{2}> \\w+ \\w+: [(]g_timezone,([^)]*)[)]\", log_data)\n timezone_info = timezone(timedelta(hours=int(timezone_match.group(1))))\n\n return log_start_time.replace(tzinfo=timezone_info)\n except Exception:\n print(\"Something is wrong with the log file!\")", "def ParseRecord(self, parser_mediator, key, structure):\n if key != 'log_entry':\n raise errors.ParseError(\n 'Unable to parse record, unknown structure: {0:s}'.format(key))\n\n month_string = self._GetValueFromStructure(structure, 'month')\n\n year = self._GetValueFromStructure(structure, 'year')\n month = self.MONTHS.get(month_string)\n day = self._GetValueFromStructure(structure, 'day')\n hours = self._GetValueFromStructure(structure, 'hours')\n minutes = self._GetValueFromStructure(structure, 'minutes')\n seconds = self._GetValueFromStructure(structure, 'seconds')\n\n event_data = IOSSysdiagLogEventData()\n event_data.process_identifier = self._GetValueFromStructure(\n structure, 'process_identifier')\n event_data.severity = self._GetValueFromStructure(structure, 'severity')\n event_data.originating_call = self._GetValueFromStructure(\n structure, 'originating_call')\n event_data.body = self._GetValueFromStructure(structure, 'body')\n\n try:\n date_time = dfdatetime_time_elements.TimeElements(\n time_elements_tuple=(year, month, day, hours, minutes, seconds))\n except (TypeError, ValueError):\n parser_mediator.ProduceExtractionWarning('invalid date time value')\n return\n\n event = time_events.DateTimeValuesEvent(\n date_time, definitions.TIME_DESCRIPTION_MODIFICATION)\n\n parser_mediator.ProduceEventWithEventData(event, event_data)", "def parse_line(self, line):\n raise NotImplementedError", "def __parse(self):\n lines = self.file.readlines()\n name_idx = 2\n name_idx_found = False\n pathre = re.compile(r\"^[A-Z]:[\\\\/]\\w+\")\n for i in range(0, len(lines)):\n line = lines[i]\n if line.strip() != \"\": # check if line isn't empty\n if pathre.match(line):\n self.path = line.strip()\n continue\n tokens = line.split()\n time_str = tokens[0] + \" \" + tokens[1]\n try:\n time = datetime.strptime(time_str, \"%m/%d/%y %H:%M:%S\")\n except ValueError:\n raise LogParseError('Invalid log format. Date must be first \\\n token for each log event.') \n if not name_idx_found:\n name_idx = tokens.index('Monitoring')\n name_idx_found = True\n name = \"\"\n if tokens[name_idx].strip() == 'Monitoring':\n name = tokens[name_idx].lower() + \" \" + tokens[name_idx + 1].lower()\n duration = 0.0\n else:\n name = tokens[name_idx].lower()\n duration = tokens[name_idx + 1]\n self.events[name] = Event(time, name, duration)\n self.start = self.events['monitoring started']\n self.end = self.events['monitoring stopped']", "def ParseLine(line):\n words = line.split()\n date = words[0][1:] + \" \" + words[1][:-1]\n parsed_date = parse(date)\n year = parsed_date.year\n month = parsed_date.month\n day = parsed_date.day\n hour = parsed_date.hour\n mins = parsed_date.minute\n\n #print (year, month, day, hour, mins)\n shift_start = False\n guard_id = 0\n falls_asleep = False\n wakes = False\n if (words[2] == \"Guard\"):\n shift_start = True\n guard_id = int(words[3][1:])\n elif (words[2] == \"wakes\"):\n wakes = True\n guard_id = 0\n elif (words[2] == \"falls\"):\n falls_asleep = True\n guard_id = 0\n return Record(date, year, month, day, hour, mins, shift_start, guard_id, falls_asleep, wakes)", "def parse_record(self, record):\n raise NotImplementedError()", "def _ParseRecord(self, parser_mediator, key, structure):\n time_elements_structure = self._GetValueFromStructure(\n structure, 'date_time')\n\n event_data = MacOSWiFiLogEventData()\n event_data.added_time = self._ParseTimeElements(time_elements_structure)\n event_data.agent = self._GetValueFromStructure(structure, 'agent')\n event_data.function = self._GetValueFromStructure(structure, 'function')\n event_data.text = self._GetStringValueFromStructure(structure, 'text')\n\n if key == 'known_function_log_line':\n event_data.action = self._GetAction(event_data.function, event_data.text)\n\n parser_mediator.ProduceEventData(event_data)", "def parseLog(self, log_lines):\n abstract", "def first(self, trace):\n return trace[0]" ]
[ "0.6299794", "0.62642795", "0.623273", "0.6208043", "0.61811304", "0.6137225", "0.6113412", "0.60875434", "0.6070435", "0.6058054", "0.60519", "0.6039214", "0.59604293", "0.59400874", "0.59321016", "0.5927462", "0.59130496", "0.58992994", "0.5885058", "0.58600867", "0.58596116", "0.5849142", "0.58194274", "0.5811447", "0.5800982", "0.5763466", "0.5760632", "0.57565916", "0.5745543", "0.57341254" ]
0.70170045
0
Helper that tests that two sets of cards are identical up to ordering. As an added bonus, this can handle any combination of card lists and card dicts.
def cards_are_same(hand1, hand2): hand1_dict = {} hand2_dict = {} # List -> Dict conversion if isinstance(hand1, dict): hand1_dict = hand1 else: for card in hand1: hand1_dict[card] = hand1_dict.get(card, 0) + 1 if isinstance(hand2, dict): hand2_dict = hand2 else: for card in hand2: hand2_dict[card] = hand2_dict.get(card, 0) + 1 return hand1_dict == hand2_dict
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def compare_element(self, card1, card2, card3, element):\n e1 = card1[element]\n e2 = card2[element]\n e3 = card3[element]\n if (e1 == e2 and e2 == e3) or (e1 != e2 and e1 != e3 and e2 != e3):\n # All the same or all different.\n return 1\n return 0", "def __eq__(self, other: Card) -> bool:\n return compare_map[self.number] == compare_map[other.number]", "def build_deck_screen_my_deck_check_duplicate(card, local_store_list):\n for cd in local_store_list:\n if card.set_number == cd.set_number and card.card_number == cd.card_number:\n return True\n break\n return False", "def assert_same(result, expect):\n assert sorted(result) == sorted(expect)", "def test_sort_cards(a_list, result):\n assert sort_cards(a_list) == result", "def test_hand_has_two_pair(hand, card_list, expected):\n hand.add_cards(card_list)\n assert hand.has_two_pair() == expected", "def test_deck_contains_all_cards(self):\n\n # I'm using collections.Counter so that the order is ignored (as in a\n # set) but that multiples are accounted for.\n expected = collections.Counter([\n ('r', 'i'), ('r', 'i'), ('r', 'i'),\n ('r', 2), ('r', 3), ('r', 4), ('r', 5), ('r', 6), \n ('r', 7), ('r', 8), ('r', 9), ('r', 10),\n\n ('g', 'i'), ('g', 'i'), ('g', 'i'),\n ('g', 2), ('g', 3), ('g', 4), ('g', 5), ('g', 6),\n ('g', 7), ('g', 8), ('g', 9), ('g', 10),\n\n ('b', 'i'), ('b', 'i'), ('b', 'i'),\n ('b', 2), ('b', 3), ('b', 4), ('b', 5), ('b', 6),\n ('b', 7), ('b', 8), ('b', 9), ('b', 10),\n\n ('y', 'i'), ('y', 'i'), ('y', 'i'),\n ('y', 2), ('y', 3), ('y', 4), ('y', 5), ('y', 6),\n ('y', 7), ('y', 8), ('y', 9), ('y', 10),\n\n ('w', 'i'), ('w', 'i'), ('w', 'i'),\n ('w', 2), ('w', 3), ('w', 4), ('w', 5), ('w', 6),\n ('w', 7), ('w', 8), ('w', 9), ('w', 10), ])\n\n self.assertEqual(expected, collections.Counter(deck.deck_gen()))", "def test_duplicate_cards(hand, card_list):\n with pytest.raises(AssertionError):\n hand.add_cards(card_list)", "def test_hand_has_all_unique_ranks(hand, card_list, expected):\n hand.add_cards(card_list)\n assert hand.has_all_unique_ranks() == expected", "def test_sufficient_shuffle(self):\n cards = self.deck.cards[:]\n self.deck.shuffle()\n self.assertNotEqual(cards, self.deck.cards)\n self.assertEqual(self.deck.count(), 52)", "def test_shuffle():\n deck1 = Shoe()\n deck2 = Shoe()\n deck1.shuffle_shoe()\n deck2.shuffle_shoe()\n assert deck1.shuffle_shoe() != deck2.shuffle_shoe()", "def test_shuffle_deck_isolation(self):\n rand = random.Random(64)\n deck = models.Deck(rand)\n \n deck.add_card(models.Card(models.Suit.hearts, models.Rank.ace))\n deck.add_card(models.Card(models.Suit.clubs, models.Rank.ace))\n deck.add_card(models.Card(models.Suit.diamonds, models.Rank.ace))\n deck.add_card(models.Card(models.Suit.hearts, models.Rank.two))\n deck.add_card(models.Card(models.Suit.clubs, models.Rank.two))\n deck.add_card(models.Card(models.Suit.diamonds, models.Rank.two))\n \n rand2 = random.Random(8765)\n deck2 = models.Deck(rand2)\n\n deck2.add_card(models.Card(models.Suit.hearts, models.Rank.ace))\n deck2.add_card(models.Card(models.Suit.clubs, models.Rank.ace))\n deck2.add_card(models.Card(models.Suit.diamonds, models.Rank.ace))\n deck2.add_card(models.Card(models.Suit.hearts, models.Rank.two))\n\n deck2.shuffle()\n \n Suit = models.Suit\n Rank = models.Rank\n\n deck.shuffle()\n\n self.assertEquals(models.Card(Suit.clubs, Rank.ace), deck.deal_card())\n self.assertEquals(models.Card(Suit.hearts, Rank.two), deck.deal_card())\n self.assertEquals(models.Card(Suit.hearts, Rank.ace), deck.deal_card())", "def test_equal(self):\r\n\r\n a_players = [ZeroPlayer(1), ZeroPlayer(2)]\r\n a_x_dist = 3\r\n a_y_dist = 3\r\n a_num_to_win = 1\r\n a_game = Game(a_players, a_x_dist, a_y_dist, a_num_to_win)\r\n\r\n b_players = [ZeroPlayer(1), ZeroPlayer(2)]\r\n b_x_dist = 3\r\n b_y_dist = 3\r\n b_num_to_win = 1\r\n b_game = Game(b_players, b_x_dist, b_y_dist, b_num_to_win)\r\n\r\n c_players = [ZeroPlayer(1), ZeroPlayer(2)]\r\n c_x_dist = 3\r\n c_y_dist = 3\r\n c_num_to_win = 1\r\n c_game = Game(c_players, c_x_dist, c_y_dist, c_num_to_win)\r\n\r\n self.assertTrue(b_game == a_game == c_game)\r\n\r\n a_game.play_game()\r\n b_game.play_game()\r\n\r\n self.assertTrue(a_game == b_game)\r\n self.assertFalse(c_game == a_game)\r\n\r\n c_game.play_game()\r\n\r\n self.assertTrue(b_game == a_game == c_game)", "def test_case_1(self):\n print(\"-------------------shuffle-----------------------------------\")\n for _ in range(10):\n deck_size = np.random.randint(low=1, high=100000)\n deck = np.arange(deck_size)\n shuffle_deck = shuffle(deck)\n self.assertEqual(sum(shuffle_deck), deck_size * (deck_size - 1) // 2)\n self.assertEqual(len(deck), len(shuffle_deck))\n self.assertSetEqual(set(shuffle_deck), set(deck))\n\n print(\"input sequence preserve ok: PASS\")\n print(\"shuffle contain unique value ok: PASS\")\n print(\"shuffle contain same set of value as deck ok: PASS\")", "def test_only_two_card_petitions(self):\n f = gtrutils.check_petition_combos\n\n self.assertTrue( f( 0, 0, [0], True, False))\n\n self.assertFalse( f( 1, 0, [], True, False))\n self.assertFalse( f( 1, 0, [1], True, False))\n self.assertTrue( f( 1, 0, [2], True, False))\n self.assertFalse( f( 1, 0, [3], True, False))\n self.assertFalse( f( 1, 0, [4], True, False))\n\n self.assertTrue( f( 1, 1, [], True, False))\n self.assertFalse( f( 1, 1, [2], True, False))\n\n self.assertFalse( f( 2, 0, [2], True, False))\n self.assertFalse( f( 2, 0, [3], True, False))\n self.assertTrue( f( 2, 0, [4], True, False))\n self.assertFalse( f( 2, 0, [5], True, False))\n \n self.assertTrue( f( 2, 1, [2], True, False))\n self.assertFalse( f( 2, 1, [3], True, False))\n self.assertFalse( f( 2, 1, [4], True, False))\n\n self.assertTrue( f(13, 26, [], True, False))\n self.assertTrue( f(13, 0, [26], True, False))\n self.assertTrue( f(13, 14, [12], True, False))\n self.assertTrue( f(13, 13, [10], True, False))\n self.assertFalse( f(13, 15, [11], True, False))\n\n self.assertFalse( f( 6, 1, [2,4,6], True, False))\n self.assertTrue( f( 7, 1, [2,4,6], True, False))\n self.assertFalse( f( 8, 1, [2,4,6], True, False))", "def equal_multiset(vec_1, vec_2):\n lst_1, lst_2 = sorted(list(vec_1)), sorted(list(vec_2))\n if len(lst_1) != len(lst_2):\n return False\n for i, j in list(zip(lst_1, lst_2)):\n if i != j:\n return False\n return True", "def test_hand_has_one_pair(hand, card_list, expected):\n hand.add_cards(card_list)\n assert hand.has_one_pair() == expected", "def same(d1: Sequence[Any], d2: Sequence[Any]) -> bool:\n if len(d1) != len(d2):\n return False\n for i in range(len(d1)):\n if d1[i] != d2[i]:\n return False\n return True", "def test_keys_eq(self):\n self.assertListEqual(self.result, self.expected)", "def sequence_equals(sequence1, sequence2):\n assert len(sequence1) == len(sequence2), (len(sequence1), len(sequence2))\n for item_from_s1, item_from_s2 in zip(sequence1, sequence2):\n assert item_from_s1 == item_from_s2, (item_from_s1, item_from_s2)\n\n return True", "def differentiate_cards(card):\n\t\tdef High_Card(numbers,colors):\n\t\t\treturn len(set(numbers)) == 5\n\t\tdef One_Pair(numbers,colors):\n\t\t\treturn len(set(numbers)) == 4\n\t\tdef Two_Pairs(numbers,colors):\n\t\t\tif len(set(numbers)) != 3:\n\t\t\t\treturn False\n\t\t\treturn [numbers.count(i) for i in numbers].count(2) == 4\n\t\tdef Three_of_a_Kind(numbers,colors):\n\t\t\tif len(set(numbers)) != 3:\n\t\t\t\treturn False\n\t\t\tfor i in numbers:\n\t\t\t\tif numbers.count(i) == 3:\n\t\t\t\t\treturn True\n\t\t\treturn False\n\t\tdef Straight(numbers,colors):\n\t\t\tfor i in xrange(1,len(numbers)):\n\t\t\t\tif numbers[i] - numbers[i-1] != 1:\n\t\t\t\t\treturn False\n\t\t\treturn True\n\t\tdef Flush(numbers,colors):\n\t\t\treturn len(set(colors)) == 1\n\t\tdef Full_House(numbers,colors):\n\t\t\tnumbers_set = set(numbers)\n\t\t\tif len(numbers_set) != 2:\n\t\t\t\treturn False\n\t\t\ta = numbers[0]\n\t\t\tb= [x for x in numbers if x != a][0]\n\t\t\treturn (numbers.count(a) == 2 and numbers.count(b) == 3) or\\\n\t\t\t\t(numbers.count(a) == 3 and numbers.count(b) == 2)\n\t\tdef Four_of_a_Kind(numbers,colors):\n\t\t\tfor i in set(numbers):\n\t\t\t\tif numbers.count(i) == 4:\n\t\t\t\t\treturn True\n\t\t\treturn False\n\t\tdef Straight_Flush(numbers,colors):\n\t\t\treturn Straight(numbers,colors) and Flush(numbers,colors)\n\t\tdef Royal_Flush(numbers,colors):\n\t\t\tRoyal = [10,11,12,13,14]\n\t\t\treturn numbers == Royal and Flush(numbers,colors)\n\n\t\tcards = {'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9,\n\t\t 'T':10,'t':10,'J':11,'j':11,'Q':12,'q':12,'K':13,'k':13,'A':14,'a':14}\n\t\tnumbers = [cards[i[0]] for i in card]\n\t\tnumbers.sort()\n\t\tcolors = [i[1] for i in card]\n\t\t\n\t\tif Royal_Flush(numbers,colors):return 9\n\t\telif Straight_Flush(numbers,colors):return 8\n\t\telif Four_of_a_Kind(numbers,colors):return 7\n\t\telif Full_House(numbers,colors):return 6\n\t\telif Flush(numbers,colors):return 5\n\t\telif Straight(numbers,colors):return 4\n\t\telif Three_of_a_Kind(numbers,colors):return 3\n\t\telif Two_Pairs(numbers,colors):return 2\n\t\telif One_Pair(numbers,colors):return 1\n\t\telif High_Card(numbers,colors):return 0", "def check_places_are_same(places_original: List[Place], places_new: List[Place]):\n return len(places_original) == len(places_new) and len(\n [item for item in places_original if any(\n [item.is_equal(item2['node']) for item2 in places_new])]) == len(places_original)", "def test_multi_same(nothing_list):\n result = multi_same_list(nothing_list)\n assert result[1][2] == 0\n assert result[0][2] == 0", "def __eq__(self, card2):\n return self.suit == card2.suit and self.rank == card2.rank", "def validate_cards(self, cards_list):\n return set(self.hand).issubset(set(cards_list))", "def are_clone_sequences(atoms1, atoms2):\n\n for a1, a2 in it.zip_longest(atoms1, atoms2):\n assert a1 is not a2\n assert a1.get_id() == a2.get_id()\n assert a1.get_charge() == a2.get_charge()\n assert a1.__class__ is a2.__class__", "def __eq__(self, vs) -> bool:\n return {*map(tuple, self.__elements)} == {*map(tuple, vs)}", "def check_equivalent(self, a, b):\n assert len(a) == len(b)\n for x, y in zip(a, b):\n assert self.is_equal(x, y)", "def check_equivalent(self, a, b):\n assert set(a) == set(b)\n for key in a:\n assert self.is_equal(a[key], b[key])", "def same_rows(rows_list_1, rows_list_2):\n return sorted(rows_list_1) == sorted(rows_list_2)" ]
[ "0.65992314", "0.657484", "0.64334226", "0.64320785", "0.6430725", "0.6417162", "0.6396451", "0.63866633", "0.6370803", "0.6362378", "0.6356536", "0.632622", "0.6239135", "0.6231354", "0.6228795", "0.6206319", "0.6168011", "0.61559004", "0.6144484", "0.6099852", "0.6090382", "0.6068184", "0.60608447", "0.6059641", "0.60501516", "0.60248697", "0.5989314", "0.59859407", "0.59763366", "0.59730905" ]
0.71126974
0
Helper that tests if a deck is the same as a set of cards. Assumes that cards is a dict.
def deck_has_cards(deck, cards): deck_dict = collections.defaultdict(int) for card in itertools.chain(deck.draw_pile, deck.discard_pile, deck.hand): deck_dict[card] += 1 return deck_dict == cards
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def build_deck_screen_my_deck_check_duplicate(card, local_store_list):\n for cd in local_store_list:\n if card.set_number == cd.set_number and card.card_number == cd.card_number:\n return True\n break\n return False", "def validate_cards(self, cards_list):\n return set(self.hand).issubset(set(cards_list))", "def is_valid_deck(deck):\n \n flag = True\n test_deck = []\n for i in range(1, len(deck) + 1):\n test_deck.append(i)\n for value in deck:\n if value not in test_deck:\n flag = False\n return flag", "def test_is_set(self):\n cards = numpy.array([[1,1,1,2,0],\n [0,1,2,2,2],\n [0,1,2,2,2],\n [0,1,2,2,2]])\n\n self.assertTrue(set_solver.is_set(cards, [0, 1, 2]))\n self.assertFalse(set_solver.is_set(cards, [0, 1, 3]))\n self.assertTrue(set_solver.is_set(cards, [2, 3, 4]))", "def is_valid_deck(deck_of_cards):\n new_deck = deck_of_cards[:]\n new_deck.sort()\n \n for i in range(len(new_deck)):\n if new_deck[i] != (i + 1):\n return False\n return True\n # Checks to see if each value from 1 to number of cards in the given deck \n # appears once.", "def test_deck_contains_all_cards(self):\n\n # I'm using collections.Counter so that the order is ignored (as in a\n # set) but that multiples are accounted for.\n expected = collections.Counter([\n ('r', 'i'), ('r', 'i'), ('r', 'i'),\n ('r', 2), ('r', 3), ('r', 4), ('r', 5), ('r', 6), \n ('r', 7), ('r', 8), ('r', 9), ('r', 10),\n\n ('g', 'i'), ('g', 'i'), ('g', 'i'),\n ('g', 2), ('g', 3), ('g', 4), ('g', 5), ('g', 6),\n ('g', 7), ('g', 8), ('g', 9), ('g', 10),\n\n ('b', 'i'), ('b', 'i'), ('b', 'i'),\n ('b', 2), ('b', 3), ('b', 4), ('b', 5), ('b', 6),\n ('b', 7), ('b', 8), ('b', 9), ('b', 10),\n\n ('y', 'i'), ('y', 'i'), ('y', 'i'),\n ('y', 2), ('y', 3), ('y', 4), ('y', 5), ('y', 6),\n ('y', 7), ('y', 8), ('y', 9), ('y', 10),\n\n ('w', 'i'), ('w', 'i'), ('w', 'i'),\n ('w', 2), ('w', 3), ('w', 4), ('w', 5), ('w', 6),\n ('w', 7), ('w', 8), ('w', 9), ('w', 10), ])\n\n self.assertEqual(expected, collections.Counter(deck.deck_gen()))", "def is_valid_deck(deck: List[int]) -> bool:\n check_deck = []\n check_deck.extend(deck)\n check_deck.sort()\n return len(check_deck) >= 3 and \\\n all(isinstance(item, int) for item in check_deck) \\\n and len(check_deck) == check_deck[-1]", "def cards_are_same(hand1, hand2):\n hand1_dict = {}\n hand2_dict = {}\n\n # List -> Dict conversion\n if isinstance(hand1, dict):\n hand1_dict = hand1\n else:\n for card in hand1:\n hand1_dict[card] = hand1_dict.get(card, 0) + 1\n if isinstance(hand2, dict):\n hand2_dict = hand2\n else:\n for card in hand2:\n hand2_dict[card] = hand2_dict.get(card, 0) + 1\n\n return hand1_dict == hand2_dict", "def flush(hand):\n return len(set([suit for value, suit in hand])) == 1", "def is_match(self, card):\n\t\treturn self.suit == card.suit or self.value == card.value", "def check_cards(self, cards):\n if len(cards) != 3:\n return False\n\n match = 0\n card1 = cards[0][1]\n card2 = cards[1][1]\n card3 = cards[2][1]\n\n match += self.compare_element(card1, card2, card3, 'shape')\n match += self.compare_element(card1, card2, card3, 'colour')\n match += self.compare_element(card1, card2, card3, 'count')\n match += self.compare_element(card1, card2, card3, 'fill')\n\n return match == 4", "def hasGroupsSizeX(self, deck):\n return reduce(lambda a, b: gcd(a, b), Counter(deck).values()) > 1", "def check_valid(self, cards):\n\n if len(cards) == 1: # one card\n return True\n if len(cards) == 2: # two cards\n if ((self.num_to_card(int(cards[0])) == self.num_to_card(int(cards[1]))) or # two same cards\n (int(cards[0]) > 51) or # any card and a joker\n (int(cards[1])) > 51): # any card and a joker\n return True\n return False\n\n # 3 or more: all same number/ascending order\n # check how many jokers\n jokers = 0\n for card in cards:\n #print(int(card))\n #print(self.num_to_card(card))\n if int(card) > 51:\n jokers += 1\n #print(\"YESSSSSSSSSSIR\")\n #print(f'[THERE ARE {jokers} JOKERS]')\n\n # check if all same number\n sort = sorted(cards)\n #print(f'[THE SORTED CARDS: {sort}]')\n index = 0\n for card in sort:\n if self.num_to_card(int(card)) == self.num_to_card(int(sort[0])) or int(card) > 51:\n index += 1\n if index == len(cards):\n return True\n\n # check ascend order\n if not self.is_same_sign(cards):\n print('Here')\n return False\n\n #print(\"accend left\")\n return self.ascend(cards, jokers)", "def equal_sets(S):\n s0 = S[0]\n res = True\n for i in range(1, len(S)):\n res = res and s0 == S[i]\n return res", "def equal_sets(S):\n s0 = S[0]\n res = True\n for i in range(1, len(S)):\n res = res and s0 == S[i]\n return res", "def is_same_set(self, item1, item2):\n res = False\n for s in self._data:\n if item1 in s and item2 in s:\n res = True\n break\n return res", "def differentiate_cards(card):\n\t\tdef High_Card(numbers,colors):\n\t\t\treturn len(set(numbers)) == 5\n\t\tdef One_Pair(numbers,colors):\n\t\t\treturn len(set(numbers)) == 4\n\t\tdef Two_Pairs(numbers,colors):\n\t\t\tif len(set(numbers)) != 3:\n\t\t\t\treturn False\n\t\t\treturn [numbers.count(i) for i in numbers].count(2) == 4\n\t\tdef Three_of_a_Kind(numbers,colors):\n\t\t\tif len(set(numbers)) != 3:\n\t\t\t\treturn False\n\t\t\tfor i in numbers:\n\t\t\t\tif numbers.count(i) == 3:\n\t\t\t\t\treturn True\n\t\t\treturn False\n\t\tdef Straight(numbers,colors):\n\t\t\tfor i in xrange(1,len(numbers)):\n\t\t\t\tif numbers[i] - numbers[i-1] != 1:\n\t\t\t\t\treturn False\n\t\t\treturn True\n\t\tdef Flush(numbers,colors):\n\t\t\treturn len(set(colors)) == 1\n\t\tdef Full_House(numbers,colors):\n\t\t\tnumbers_set = set(numbers)\n\t\t\tif len(numbers_set) != 2:\n\t\t\t\treturn False\n\t\t\ta = numbers[0]\n\t\t\tb= [x for x in numbers if x != a][0]\n\t\t\treturn (numbers.count(a) == 2 and numbers.count(b) == 3) or\\\n\t\t\t\t(numbers.count(a) == 3 and numbers.count(b) == 2)\n\t\tdef Four_of_a_Kind(numbers,colors):\n\t\t\tfor i in set(numbers):\n\t\t\t\tif numbers.count(i) == 4:\n\t\t\t\t\treturn True\n\t\t\treturn False\n\t\tdef Straight_Flush(numbers,colors):\n\t\t\treturn Straight(numbers,colors) and Flush(numbers,colors)\n\t\tdef Royal_Flush(numbers,colors):\n\t\t\tRoyal = [10,11,12,13,14]\n\t\t\treturn numbers == Royal and Flush(numbers,colors)\n\n\t\tcards = {'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9,\n\t\t 'T':10,'t':10,'J':11,'j':11,'Q':12,'q':12,'K':13,'k':13,'A':14,'a':14}\n\t\tnumbers = [cards[i[0]] for i in card]\n\t\tnumbers.sort()\n\t\tcolors = [i[1] for i in card]\n\t\t\n\t\tif Royal_Flush(numbers,colors):return 9\n\t\telif Straight_Flush(numbers,colors):return 8\n\t\telif Four_of_a_Kind(numbers,colors):return 7\n\t\telif Full_House(numbers,colors):return 6\n\t\telif Flush(numbers,colors):return 5\n\t\telif Straight(numbers,colors):return 4\n\t\telif Three_of_a_Kind(numbers,colors):return 3\n\t\telif Two_Pairs(numbers,colors):return 2\n\t\telif One_Pair(numbers,colors):return 1\n\t\telif High_Card(numbers,colors):return 0", "def SetFunction():\r\n s2 = []\r\n s3 = []\r\n s4 = []\r\n s2 = { i for i in range(21) if i%2 == 0}\r\n s3 = { i for i in range(21) if i%3 == 0}\r\n s4 = { i for i in range(21) if i%4 == 0}\r\n s2 = set(s2)\r\n s3 = set(s3)\r\n s4 = set(s4)\r\n print s3.issubset(s2)\r\n print s4.issubset(s2)", "def is_straight(hand):\n # same suite\n suite = hand[0][1]\n vals = []\n for c in hand:\n vals.append(cards[c[0]])\n # check if vals are consecutive or not\n if is_contiguous(vals):\n return True\n else:\n return False", "def is_royal_flush(hand):\n\n # same suit\n suite = hand[0][1]\n count = {c:0 for c in cards.keys()}\n for c in hand:\n if suite != c[1]:\n return False\n count[c[0]] += 1\n # all in same suit\n for c in 'T J Q K A'.split():\n if count[c] != 1:\n return False\n return True", "def check_legality(session, player, set_name, trade_sets=False):\n excluded_sets = set(session.taken.keys())\n if trade_sets:\n excluded_sets.discard(trade_sets[0])\n excluded_sets.discard(trade_sets[1])\n for grouping in session.exclusives:\n if player.sets.intersection(grouping):\n excluded_sets.update(grouping)\n return set_name not in excluded_sets", "def is_same_sign(self, cards):\n\n jokers = 0\n w_o_jokers = []\n for card in cards:\n if self.num_to_card(int(card)) == 0:\n jokers += 1\n else:\n w_o_jokers.append(int(card))\n\n w_o_jokers = sorted(w_o_jokers)\n print(\"whitout jokers: \", w_o_jokers)\n if w_o_jokers[0] <= 12: # if the cards are CLUBS\n if w_o_jokers[-1] > 12:\n return False\n if w_o_jokers[0] <= 25: # if the cards are DIAMONDS\n if w_o_jokers[-1] > 25:\n return False\n if w_o_jokers[0] <= 38: # HEARTS\n if w_o_jokers[-1] > 38:\n return False\n if w_o_jokers[0] <= 51:\n if w_o_jokers[-1] > 51:\n return False\n return True", "def test_hand_has_all_unique_ranks(hand, card_list, expected):\n hand.add_cards(card_list)\n assert hand.has_all_unique_ranks() == expected", "def __eq__(self, other_card):\n if self.rank == other_card.rank or self.suit == other_card.suit:\n return True\n else:\n return False", "def unique(combo, out):\n # This lets us find only minimally covering payments (you should never add cards to a payment that already\n # satisfies the charge)\n for el in out:\n if set(el).issubset(combo):\n return False\n return True", "def check_color_card(player, color):\n for card in player.cards:\n if card.suit == color:\n return True", "def test_find_sets(self):\n cards = numpy.array([[1,1,1,2,0],\n [0,1,2,2,2],\n [0,1,2,2,2],\n [0,1,2,2,2]])\n\n set_indices = set_solver.find_sets(cards)\n self.assertEqual(len(set_indices), 2)\n self.assertTrue((0, 1, 2) in set_indices)\n self.assertTrue((2, 3, 4) in set_indices)", "def inSet(stack):\n assertArity(stack, 2)\n rhs, lhs = stack.pop(), stack.pop()\n assertType(rhs, Set)\n return lhs in rhs", "def __eq__(self, anotherset):\r\n if not isinstance(anotherset, LR0ItemSet):\r\n raise TypeError\r\n if len(self.itemlist) != len(anotherset.itemlist):\r\n return False\r\n for element in self.itemlist:\r\n if element not in anotherset.itemlist:\r\n return False\r\n return True", "def notInSet(stack):\n assertArity(stack, 2)\n rhs, lhs = stack.pop(), stack.pop()\n assertType(rhs, Set)\n return lhs not in rhs" ]
[ "0.7119846", "0.7076654", "0.69705415", "0.68710893", "0.68217534", "0.66353387", "0.6516489", "0.6278403", "0.617272", "0.6160348", "0.615524", "0.60827607", "0.60686934", "0.60345966", "0.60345966", "0.59672284", "0.59543985", "0.5945144", "0.58992213", "0.5891211", "0.58509856", "0.58450127", "0.5785868", "0.57737195", "0.5767363", "0.57511216", "0.5727767", "0.57157147", "0.57082903", "0.5667186" ]
0.75060856
0
Returns an authorized API client by discovering the IoT API and creating a service object using the service account credentials JSON.
def get_client(service_account_json): api_scopes = ['https://www.googleapis.com/auth/cloud-platform'] api_version = 'v1' discovery_api = 'https://cloudiot.googleapis.com/$discovery/rest' service_name = 'cloudiotcore' credentials = service_account.Credentials.from_service_account_file( service_account_json) scoped_credentials = credentials.with_scopes(api_scopes) discovery_url = '{}?version={}'.format( discovery_api, api_version) return discovery.build( service_name, api_version, discoveryServiceUrl=discovery_url, credentials=scoped_credentials)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_service(api_name, api_version, scope, client_secrets_path):\n # Parse command-line arguments.\n parser = argparse.ArgumentParser(\n formatter_class=argparse.RawDescriptionHelpFormatter,\n parents=[tools.argparser])\n flags = parser.parse_args([])\n\n # Set up a Flow object to be used if we need to authenticate.\n flow = client.flow_from_clientsecrets(\n client_secrets_path, scope=scope,\n message=tools.message_if_missing(client_secrets_path))\n\n # Prepare credentials, and authorize HTTP object with them.\n # If the credentials don't exist or are invalid run through the native client\n # flow. The Storage object will ensure that if successful the good\n # credentials will get written back to a file.\n storage = file.Storage(api_name + '.dat')\n credentials = storage.get()\n if credentials is None or credentials.invalid:\n credentials = tools.run_flow(flow, storage, flags)\n http = credentials.authorize(http=httplib2.Http())\n\n # Build the service object.\n service = build(api_name, api_version, http=http)\n\n return service", "def client(\n service_name: str, version: str = \"v1\", secrets: Secrets = None\n) -> Resource:\n credentials = load_credentials(secrets=secrets)\n return build(service_name, version=version, credentials=credentials)", "def get_authenticated_service(api_name: str, api_version: str) -> Resource:\n\n if CREDS_FILENAME.exists():\n credentials = Credentials.from_authorized_user_file(str(CREDS_FILENAME))\n # TODO make request to the access token endpoint???\n\n # FIXME verifying token\n # credentials.refresh(requests.Request())\n # print(credentials.token, credentials.expiry)\n\n # idinfo = id_token.verify_oauth2_token(\n # credentials.token, requests.Request(), credentials.client_id)\n\n # if idinfo['iss'] not in ['accounts.google.com',\n # 'https://accounts.google.com']:\n # # CREDS_FILENAME.unlink()\n # raise ValueError('Wrong issuer.')\n\n else:\n flow = InstalledAppFlow.from_client_secrets_file(CLIENT_SECRETS_FILE, SCOPES)\n credentials = flow.run_local_server(\n host=\"localhost\",\n port=8080,\n authorization_prompt_message=\"Please visit this URL: {url}\",\n success_message=\"The auth flow is complete; you may close this window.\",\n open_browser=True,\n )\n\n creds_data = {\n \"token\": None,\n \"refresh_token\": credentials.refresh_token,\n \"token_uri\": credentials.token_uri,\n \"client_id\": credentials.client_id,\n \"client_secret\": credentials.client_secret,\n \"scopes\": credentials.scopes,\n }\n\n with CREDS_FILENAME.open(\"w\") as outfile:\n json.dump(creds_data, outfile)\n\n return build(api_name, api_version, credentials=credentials)", "def GetApiClient(creds, api_service_name=None, api_version=None):\n if api_service_name is None:\n api_service_name = DEFAULT_API_SERVICE_NAME\n if api_version is None:\n api_version = DEFAULT_API_VERSION\n\n base_http_client = httplib2.Http()\n auth_http_client = creds.authorize(base_http_client)\n ab_client = apiclient.discovery.build(api_service_name, api_version,\n http=auth_http_client)\n return ab_client", "def api_client() -> APIClient:\n return APIClient()", "def api_client() -> APIClient:\n\n return APIClient()", "def make_rest_client(\n service_key, options=None,\n app_name=None, app_version=None, version=None,\n **kwargs):\n cloud = get_config(\n service_key=service_key, options=options,\n app_name=app_name, app_version=app_version,\n **kwargs)\n return cloud.get_session_client(service_key, version=version)", "def get_service(\n service_name: str,\n version: str = \"v1\",\n configuration: Configuration = None,\n secrets: Secrets = None,\n) -> Resource:\n return client(service_name, version=version, secrets=secrets)", "def client():\n return Client(**common_data.AUTH_ARGS)", "def get_client():\n return Client(__address, authkey='strumamor')", "def get_apiclient():\n api_server = [(fgt_info['address'], fgt_info['port'],\n 'https' == fgt_info['protocol'])]\n return client.FortiosApiClient(\n api_server, fgt_info['username'], fgt_info['password'])", "def create_service_object(credentials):\n http_auth = httplib2.Http()\n http_auth = credentials.authorize(http_auth)\n service = discovery.build('analytics', 'v3', http=http_auth)\n return service", "def create_service():\n creds = None\n # The file token.pickle stores the user's access and refresh tokens, and is\n # created automatically when the authorization flow completes for the first\n # time.\n if os.path.exists('token.pickle'):\n with open('token.pickle', 'rb') as token:\n creds = pickle.load(token)\n # If there are no (valid) credentials available, let the user log in.\n if not creds or not creds.valid:\n if creds and creds.expired and creds.refresh_token:\n creds.refresh(Request())\n else:\n flow = InstalledAppFlow.from_client_secrets_file('credentials.json'\n , SCOPES)\n creds = flow.run_local_server(port=9797)\n # Save the credentials for the next run\n with open('token.pickle', 'wb') as token:\n pickle.dump(creds, token)\n\n service = build('drive', 'v3', credentials=creds)\n return service", "def get_service(api_name, api_version, scopes, key_file_location):\n\n credentials = ServiceAccountCredentials.from_json_keyfile_name(\n key_file_location, scopes=scopes)\n\n # Build the service object.\n service = build(api_name, api_version, credentials=credentials)\n\n return service", "def create_api_client(base_path, access_token):\n api_client = ApiClient()\n api_client.host = base_path\n api_client.set_default_header(header_name=\"Authorization\",\n header_value=f\"Bearer {access_token}\")\n return api_client", "def get_service(api_name, api_version, scopes, key_file_location):\r\n\r\n credentials = ServiceAccountCredentials.from_json_keyfile_name(\r\n key_file_location, scopes=scopes)\r\n\r\n # Build the service object.\r\n service = build(api_name, api_version, credentials=credentials)\r\n\r\n return service", "def create_client(service, region, access_key_id, secret_access_key):\n client = boto3.client(service,\n region_name=region,\n aws_access_key_id=access_key_id,\n aws_secret_access_key=secret_access_key\n )\n return client", "def create_client(service, region, access_key_id, secret_access_key):\n client = boto3.client(service,\n region_name=region,\n aws_access_key_id=access_key_id,\n aws_secret_access_key=secret_access_key\n )\n return client", "def _get_client(self):\n credentials = service_account.Credentials.from_service_account_info(self.service_account_info)\n client = googleapiclient.discovery.build('container', 'v1', credentials=credentials)\n\n return client", "def _get_api() -> Mobileclient:\n\n api = Mobileclient()\n device_id = _get_device_id(api)\n api.oauth_login(device_id)\n\n return api", "def get_service():\n \n creds = None\n # The file token.pickle stores the user's access and refresh tokens, and is\n # created automatically when the authorization flow completes for the first\n # time.\n token_path = f\"{sys.path[0]}/creds/token.pickle\"\n if os.path.exists(token_path):\n with open(token_path, 'rb') as token:\n creds = pickle.load(token)\n # If there are no (valid) credentials available, let the user log in.\n if not creds or not creds.valid:\n if creds and creds.expired and creds.refresh_token:\n creds.refresh(Request())\n else:\n cred_path = f\"{sys.path[0]}/creds/credentials.json\"\n flow = InstalledAppFlow.from_client_secrets_file(\n cred_path, SCOPES)\n creds = flow.run_local_server(port=0)\n # Save the credentials for the next run\n with open(token_path, 'wb') as token:\n pickle.dump(creds, token)\n\n service = build('calendar', 'v3', credentials=creds)\n\n return service", "def get_api_client():\n\n global _API_CLIENT_HANDLE\n\n if not _API_CLIENT_HANDLE:\n context = get_context()\n server_config = context.get_server_config()\n\n pc_ip = server_config.get(\"pc_ip\")\n pc_port = server_config.get(\"pc_port\")\n username = server_config.get(\"pc_username\")\n password = server_config.get(\"pc_password\")\n\n update_api_client(host=pc_ip, port=pc_port, auth=(username, password))\n\n return _API_CLIENT_HANDLE", "def get_keystone_client():\n username = os.environ.get('OS_USERNAME')\n password = os.environ.get('OS_PASSWORD')\n tenant = os.environ.get('OS_TENANT_NAME')\n url = os.environ.get('OS_AUTH_URL')\n assert username is not None\n assert password is not None\n assert tenant is not None\n assert url is not None\n cl = client.Client(username=username, password=password,\n tenant_name=tenant, auth_url=url)\n return cl", "def get_service(credentials_folder, version='v3'):\n credentials = get_credentials(credentials_folder)\n http = credentials.authorize(httplib2.Http(cache=\".cache\"))\n service = discovery.build('drive', version, http=http)\n return service", "def make_client(instance):\n network_client = utils.get_client_class(\n API_NAME,\n instance._api_version[API_NAME],\n API_VERSIONS)\n LOG.debug('Instantiating network client: %s', network_client)\n\n endpoint = instance.get_endpoint_for_service_type(\n API_NAME,\n region_name=instance._region_name,\n )\n\n return network_client(\n username=instance._username,\n tenant_name=instance._project_name,\n password=instance._password,\n region_name=instance._region_name,\n auth_url=instance._auth_url,\n endpoint_url=endpoint,\n token=instance.auth.get_token(instance.session),\n insecure=instance._insecure,\n ca_cert=instance._cacert,\n )", "def _keystone_client(context, version=(3, 0)):\n auth_plugin = token.Token(\n auth_url=CONF.keystone_authtoken.auth_uri,\n token=context.auth_token,\n project_id=context.project_id)\n client_session = session.Session(auth=auth_plugin,\n verify=False if\n CONF.keystone_authtoken.insecure else\n (CONF.keystone_authtoken.cafile or True))\n return client.Client(auth_url=CONF.keystone_authtoken.auth_uri,\n session=client_session, version=version)", "def init_api(self):\n creds = None\n # The file token.pickle stores the user's access and refresh tokens, and is\n # created automatically when the authorization flow completes for the first\n # time.\n if os.path.exists(self.gdrive_config.TOKEN_PICK_PATH):\n with open(self.gdrive_config.TOKEN_PICK_PATH, 'rb') as token:\n creds = pickle.load(token)\n # If there are no (valid) credentials available, let the user log in.\n if not creds or not creds.valid:\n if creds and creds.expired and creds.refresh_token:\n creds.refresh(Request())\n else:\n flow = InstalledAppFlow.from_client_secrets_file(\n self.gdrive_config.CREDENTIAL_PATH, self.gdrive_config.SCOPES)\n creds = flow.run_local_server(port=0)\n # Save the credentials for the next run\n with open(self.gdrive_config.TOKEN_PICK_PATH, 'wb') as token:\n pickle.dump(creds, token)\n\n service = build('drive', 'v3', credentials=creds)\n return service", "def get_client(credentials: Credentials, subscription_id: str) -> StorageManagementClient:\n client = StorageManagementClient(credentials, subscription_id)\n return client", "def build_service():\n creds = None\n\n # the file token.json stores the user's access and refresh tokens, and is \n # created automatically when the authorization flow completes for the first time\n \n if os.path.exists('../creds/token.json'):\n creds = Credentials.from_authorized_user_file('../creds/token.json', SCOPES)\n\n # if there are no (valid) credentials, ask the user to login\n if not creds or not creds.valid:\n if creds and creds.expired and creds.refresh_token:\n creds.refresh(Request())\n else:\n flow = InstalledAppFlow.from_client_secrets_file(\n '../creds/credentials.json', SCOPES)\n creds = flow.run_local_server(port=0)\n with open('../creds/token.json', 'w') as token:\n token.write(creds.to_json())\n\n service = build('drive', 'v3', credentials=creds)\n return service", "def InitializeTurbiniaApiClient(\n self, credentials: Credentials) -> turbinia_api_lib.ApiClient:\n self.client_config = turbinia_api_lib.Configuration(host=self.turbinia_api)\n if not self.client_config:\n self.ModuleError('Unable to configure Turbinia API server', critical=True)\n # Check if Turbinia requires authentication.\n if self.turbinia_auth:\n if not credentials:\n self.credentials = self.GetCredentials(\n self.credentials_path, self.client_secrets_path)\n if self.credentials and self.credentials.id_token:\n self.client_config.access_token = self.credentials.id_token\n else:\n self.ModuleError(\n 'Unable to obtain id_token from identity provider', critical=True)\n return turbinia_api_lib.ApiClient(self.client_config)" ]
[ "0.70476496", "0.6967219", "0.68839943", "0.6839995", "0.6822203", "0.6819169", "0.6687449", "0.6609617", "0.6607141", "0.65145785", "0.6481238", "0.6416878", "0.6413384", "0.6408897", "0.64063555", "0.6363026", "0.63294923", "0.63294923", "0.63169473", "0.6308933", "0.6297794", "0.62193257", "0.62098277", "0.6206199", "0.6182989", "0.6182767", "0.6159924", "0.6155636", "0.6126138", "0.6108033" ]
0.7558698
0
Generic media edit view. Handles some existence and permission checks that apply to all media types, then delegates to a more type specific implementation.
def media_edit(request, mediatype, username, slug): # verify the object exists and fetch it, if so user = get_object_or_404(authmodels.User, username=username) mediatype = mediatype_deplural.get(mediatype) klass = models.mediatype_map.get(mediatype, {}).get('klass') if not klass: return HttpResponseNotFound() resource = get_object_or_404(klass, owner=user, slug=slug) # permission check edit_perm = 'gallery.change_%s' % klass.__name__.lower() if not request.user.has_perm(edit_perm): # not a special privs account, have to check for ownership and # status if (request.user != resource.owner or resource.status not in ('uploaded', 'submitted')): # nope. REJECTED! raise PermissionDenied template_map = dict(image=resource) try: resource.clean_fields(exclude=['caption']) except ValidationError: pass else: template_map['can_cancel'] = True batch_length = request.REQUEST.get('batch_length') ids = request.REQUEST.get('ids', []) if batch_length: # we're in a batch upload process template_map['batch_length'] = batch_length if ids: ids = [int(i) for i in ids.split(',')] if resource.id in ids: ids.remove(resource.id) if ids: template_map['ids'] = ','.join([str(i) for i in ids]) template_map['num_remaining'] = len(ids) + 1 form_klass = mediatype_forms.get(mediatype) if request.method == 'POST': if 'cancel' in request.POST: request.notifications.add(_('Edit canceled.')) return HttpResponseRedirect(resource.get_absolute_url()) form = form_klass(request.POST, request.FILES, instance=resource) try: form.save() except ValueError: request.notifications.add(_('Save failed.')) # falls through to the template rendering else: request.notifications.add(_('%s edited.' % resource.title)) if ids: next_resource = None for id_ in ids: try: next_resource = klass.objects.get(id=id_) except klass.DoesNotExist: continue break if next_resource is not None: url = '%s/edit' % next_resource.get_absolute_url() url = '%s?batch_length=%s&ids=%s' % (url, batch_length, template_map['ids']) return HttpResponseRedirect(url) elif batch_length: # last one in the series, redirect to unsubmitted view url = reverse('bm.gallery.views.browse') url = '%s?status=uploaded&owner=%s' % (url, request.user.username) return HttpResponseRedirect(url) return HttpResponseRedirect(resource.get_absolute_url()) else: form = form_klass(instance=resource) template_map['form'] = form context = RequestContext(request, template_map) return render_to_response('gallery/image_edit.html', context_instance=context)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def updateMedia(request, form, update, m, mt, expires, members, vendors, employees, contractors, filesize):\n\tis360 = False\n\tif 'is_360' in request.POST:\n\t\tis360 = request.POST['is_360']\n\tif update:\n\t\tif m.user == request.user.username or request.user.is_superuser: #need to make sure id is not spoofed\n\t\t\ttry:\n\t\t\t\tm = Media.objects.filter(id=request.POST['formid'])\n\t\t\t\tm.update(name=request.POST['name'].encode('utf-8'), short_description=request.POST['name'].encode('utf-8'),\n\t\t\t\t\t\t description=request.POST['description'].encode('utf-8'), expires=expires,\n\t\t\t\t\t\t retention=request.POST['retention'], visibility=request.POST['privacy'],\n\t\t\t\t\t\t members=members, vendors=vendors, employees=employees, contractors=contractors,is_360=is360)\n\t\t\t\tm = m.get()\n\t\t\t\tprocessTags(request, m, form, update)\n\t\t\t\tprocessCategories(request, m, form, update)\n\t\t\t\treturn m\n\t\t\texcept ObjectDoesNotExist:\n\t\t\t\tpass\n\t\telse:\n\t\t\tsys.exit()\n\telse:\n\t\tm = Media(name=request.POST['name'].encode('utf-8'), short_description=request.POST['name'].encode('utf-8'),\n\t\t\t\t description=request.POST['description'].encode('utf-8'), expires=expires, retention=request.POST['retention'],\n\t\t\t\t upload_date=datetime.datetime.now(), visibility=request.POST['privacy'],\n\t\t\t\t user=request.user.username, views=0, mediatype=mt, filesize=filesize, members=members,\n\t\t\t\t vendors=vendors, employees=employees, contractors=contractors, file=request.FILES['file'],\n\t\t\t\t duration='0',is_360=is360)\n\t\tm.save()\n\t\tprocessTags(request, m, form, update)\n\t\tprocessCategories(request, m, form, update)\n\t\treturn m", "def media(id):\n event = Event.query.get_or_404(id)\n if not current_user.is_organizer(event) and not current_user.is_administrator():\n return redirect(url_for(\"main.index\"))\n\n # Instantiate forms\n upload_video_form = UploadVideoForm()\n remove_video_form = RemoveVideoForm()\n image_form = MultipleImageForm()\n remove_image_form = RemoveImageForm()\n\n # Get data from user session\n upload_video_form.video_url.errors = session.pop(\"upload_video_form_errors\", [])\n upload_video_form.video_url.data = session.pop(\"video_url\", \"\")\n image_form.images.errors = session.pop(\"image_form_errors\", [])\n \n \n return render_template(\n \"events/media.html\",\n upload_video_form=upload_video_form,\n remove_video_form=remove_video_form,\n image_form=image_form,\n remove_image_form=remove_image_form,\n video=event.video,\n misc_image_paths=event.misc_images(),\n event=event,\n )", "def edit_photo(request, object_id):\n character = get_character_from_ob(object_id)\n user = request.user\n if not (user == character.player_ob or user.is_staff):\n raise Http404(\"Only owners or staff may edit photos.\")\n try:\n photo = Photo.objects.get(pk=request.POST[\"select_photo\"])\n title = request.POST[\"title\"]\n alt_text = request.POST[\"alt_text\"]\n except Exception as err:\n raise Http404(err)\n photo.title = title\n photo.alt_text = alt_text\n photo.save()\n return HttpResponseRedirect(reverse(\"character:gallery\", args=(object_id,)))", "def edit_record(request, slug, pk):\n # Try except to make sure the user is a member of this project\n try:\n ProjectMember.objects.get(user=request.user, project=Project.objects.get(slug=slug))\n except ObjectDoesNotExist:\n # User is not a member.\n return HttpResponse(\"You're trying to access a project you're not a member of or a project that does not exist.\")\n else:\n # User is a member,\n project = get_object_or_404(models.Project, slug=slug)\n record = get_object_or_404(models.Record, pk=pk)\n pm = ProjectMember.objects.get(user=request.user, project=project)\n\n # Access control.. if not owner or editor - access denied.\n if pm.is_owner or pm.is_editor:\n # User has access\n if request.method == 'POST':\n # User submits data\n form1 = forms.GeneralRecordForm(request.POST)\n form2 = forms.SpecificRecordForm(request.POST, entry=request.POST['entry_type'])\n context = {\n 'form1':form1,\n 'project':project,\n 'form':form2,\n }\n if form2.is_valid() and form1.is_valid():\n fields = [f.name for f in models.Record._meta.get_fields()]\n data1 = form1.clean()\n data2 = form2.clean()\n # Additional form validation.\n if data1['entry_type'] == 'book':\n if data2['author']== '' and data2['editor'] == '':\n context['err'] = True\n context['errmessage'] = \"Fill in either Author or Editor\"\n return render(request, 'records/record_edit.html', context)\n elif data1['entry_type'] == 'inbook':\n if data2['author'] == '' and data2['editor'] == '':\n context['err'] = True\n context['errmessage'] = \"Fill in either Author or Editor\"\n return render(request, 'records/record_edit.html', context)\n elif data2['chapter'] == '' and data2['pages'] == '':\n context['err'] = True\n context['errmessage'] = \"Fill in either Chapter or Pages\"\n return render(request, 'records/record_edit.html', context)\n # Form is valid .. save into new record\n # making sure no one has edited the record while session is running\n if record.last_edited.__str__() == request.COOKIES.get('last_edited'):\n # No conflict, go on save changes.\n record.entry_type = data1['entry_type']\n record.cite_key = data1['cite_key']\n record.project = project\n for fieldname in fields:\n if fieldname in data2:\n setattr(record, fieldname, data2[fieldname])\n record.last_edited = timezone.now()\n record.save()\n # Send user back to project detail, the overview of all records in the project.\n return redirect('projects:single', slug=slug)\n else:\n # someone changed the record before the user managed to save\n data = forms.ShowRecordForm(data=model_to_dict(record), entry=record.entry_type)\n context = {\n 'old_record':record,\n 'form1':form1,\n 'project':project,\n 'form':form2,\n 'data':data\n }\n # send user to the conflict page.\n return render(request, 'records/record_conflict.html', context)\n\n else:\n # Form is not valid\n context = {\n 'form1':form1,\n 'project':project,\n 'form':form2,\n 'err':True\n }\n return render(request, 'records/record_edit.html', context)\n else:\n # User hasn't submitted any data yet\n # Form filled in with data for selected record.\n form1 = forms.GeneralRecordForm(data=model_to_dict(record))\n form2 = forms.SpecificRecordForm(data=model_to_dict(record),entry=record.entry_type)\n context = {\n 'form1':form1,\n 'form2':form2,\n 'project':project,\n 'record':record\n }\n # Create response in order to set cookie\n response = render(request, 'records/record_edit.html', context)\n # set cookie to enable later check for conlfict\n response.set_cookie('last_edited', record.last_edited.__str__())\n return response\n else:\n # Access denied.\n return HttpResponse(\"You don't have the permission to do this\")", "def baseView(*args, itemInfo: Union[AnyStr, bool]=\"\", itemList: bool=True, viewDescription:\n bool=True, viewLabel: bool=True, viewList: bool=True, viewName: Union[AnyStr,\n bool]=\"\", q=True, query=True, e=True, edit=True, **kwargs)->Union[None, Any]:\n pass", "def __init__(self, context, request):\n EditMedia.__init__(self, context, request)\n SWORDTreatmentMixin.__init__(self, context, request)\n self.callmap.update({'DELETE': self.DELETE,})", "def edit(self, **kwargs):\n ...", "def edit(self, name, mimetypes, extensions, icon_path, binary=0,\n REQUEST=None):\n # if mimetypes and extensions are string instead of lists, split them on new lines\n if type(mimetypes) in (type(''), type(u'')):\n mimetypes = [mts.strip() for mts in mimetypes.split('\\n') if mts.strip()]\n if type(extensions) in (type(''), type(u'')):\n extensions = [mts.strip() for mts in extensions.split('\\n') if mts.strip()]\n self.__name__ = self.id = name\n self.mimetypes = mimetypes\n self.extensions = extensions\n self.binary = binary\n self.icon_path = icon_path\n if REQUEST is not None:\n REQUEST['RESPONSE'].redirect(self.absolute_url()+'/manage_main')", "def _editHandler(self) -> None:\n if self._editItemType:\n self._createDir()\n else:\n self._renameDir()", "def edit_podcast(request, slug):\n user, manager, editor, webmaster = user_role_check(request, slug)\n\n if not manager and not user.is_superuser:\n message = \"\"\"I'm sorry {0}, I'm afraid I can't let you\n edit {1}\"\"\".format(user, slug)\n\n messages.warning(request, message)\n return_url = reverse('podcast_show', kwargs={'slug': slug})\n return render(request,\n 'podmin/site/denied.html',\n {'return_url': return_url})\n\n podcast = Podcast.objects.get(slug=slug)\n form = PodcastForm(instance=podcast)\n\n form.fields['slug'].widget.attrs['readonly'] = True\n\n if request.method == 'POST':\n form = PodcastForm(request.POST, request.FILES, instance=podcast)\n if form.is_valid():\n messages.success(request, '{0} updated.'.format(podcast.title))\n podcast = form.save()\n podcast.publish()\n return HttpResponseRedirect(reverse('podcast_show',\n kwargs={'slug': slug}))\n\n context = {'form': form, 'slug': slug, 'podcast': podcast}\n\n return render(request, 'podmin/podcast/podcast_edit.html', context)", "def edit(request):\n if 'image_id' not in request.GET:\n return HttpResponseRedirect('/imgmanip')\n image_id = request.GET['image_id']\n image = get_object_or_404(Image, pk=image_id)\n return render(request, 'imgmanip/edit.html', {'image': image, 'image_id': image_id})", "def edit(self, name, mimetypes, extensions, icon_path,\n binary=0, globs=None, REQUEST=None):\n # if mimetypes and extensions are string instead of lists,\n # split them on new lines\n if isinstance(mimetypes, basestring):\n mimetypes = [mts.strip() for mts in mimetypes.split('\\n')\n if mts.strip()]\n if isinstance(extensions, basestring):\n extensions = [mts.strip() for mts in extensions.split('\\n')\n if mts.strip()]\n if isinstance(globs, basestring):\n globs = [glob.strip() for glob in globs.split('\\n')\n if glob.strip()]\n self.__name__ = self.id = name\n self.mimetypes = mimetypes\n self.globs = globs\n self.extensions = extensions\n self.binary = binary\n self.icon_path = icon_path\n if REQUEST is not None:\n REQUEST['RESPONSE'].redirect(self.absolute_url()+'/manage_main')", "def edit_file_permission(request, app=None, priv=None):\n pass", "def handle_media( environ ):\n # TODO: implement me\n return 200, [], _html.format(\n title = 'MEDIA',\n head = '',\n body = 'MEDIA'\n )", "async def async_play_media(\n self, media_type: MediaType | str, media_id: str, **kwargs: Any\n ) -> None:\n await self._volumio.replace_and_play(json.loads(media_id))", "def edit_attachments(request, id):\n content = get_object_or_404(MathContent, id=id)\n result = check_edit_attachments_permissions(request.user, content)\n if not result.allowed:\n return 404 # Could be 403 in some cases.\n\n if request.method == 'POST':\n if 'delete_attachment_id' in request.POST:\n try:\n attachment = Attachment.objects.get(\n id=request.POST['delete_attachment_id']\n )\n except Attachment.DoesNotExist:\n return 403 # Always 403.\n if attachment.content_id != content.id:\n return 403 # Always 403.\n\n attachment.content = content # Reuse.\n attachment.delete_file()\n attachment.delete()\n content.html = None\n content.save()\n\n # Redirect to avoid form resubmission.\n return (content.get_edit_attachments_url(),)\n\n attachment, form = check_and_save_attachment(request, content)\n if attachment is not None:\n # Redirect to avoid form resubmission.\n return (content.get_edit_attachments_url(),)\n else:\n form = AttachmentForm()\n\n assert (\n result.task is not None\n ), \"assuming for now only Task MathContents can have attachments\"\n data = {\n 'content': content,\n 'form': form,\n 'task': result.task,\n }\n data.update(get_task_folder_data(result.task, request.user))\n\n return data", "def edit(self, obj):\n for handle in self.selected_handles():\n object = self.dbstate.db.get_object_from_handle(handle)\n try:\n EditMedia(self.dbstate, self.uistate, [], object)\n except WindowActiveError:\n pass", "def handle_content_edit(content_id):\n\n # instance of ContentForm is available to both GET and POST requests\n form = ContentForm()\n\n # content will be None if it cannot be found\n content = Content.find_by_id(content_id)\n\n # POST - for handling the edit content form\n if form.validate_on_submit():\n\n # validation - owner email must exist\n owner_email = form.owner_email.data\n owner_obj = Owner.find_by_email(owner_email)\n if not owner_obj:\n flash(f'Owner with the email {owner_email} does not exist!',\n 'danger')\n # if owner not exist, edit page is reloaded with same content id\n return redirect(url_for('content_edit', content_id=content.id))\n\n # content type choice is extracted from the form\n choice = form.content_type.data # user choice\n choices = dict(ContentForm.SELECT_CHOICES) # all possible choices\n\n # content is updated with form values and saved to the database\n content.content_name = form.content_name.data.title()\n content.content_type = choices.get(choice)\n content.valid_months = form.valid_months.data\n content.updated_at = date.today() # today's date becomes last updated\n content.owner_id = owner_obj.id\n\n # saving content errors handled\n try:\n content.save_content()\n except HTTPException:\n return \"Server cannot update the content at this time\", 500\n\n # user is redirected to the main content page with success msg\n flash(f'{content.content_name} has been updated!', 'success')\n return redirect(url_for('content'))\n\n # GET - display the form\n # form is pre-populated with existing content data\n form.content_name.data = content.content_name\n form.owner_email.data = Owner.find_by_id(content.owner_id).owner_email\n form.valid_months.data = content.valid_months\n form.submit.data = \"Update Content\"\n\n # content type stored in this content is looked up against all types\n # each choice is a tuple pair - (stored choice, displayed choice)\n for form_type in ContentForm.SELECT_CHOICES:\n # choice becomes default value on form if it matches the stored value\n if form_type[1] == content.content_type:\n form.content_type.data = form_type[0]\n\n return render_template('content_edit.html',\n content_name=content.content_name,\n form=form)", "def test_list_media_type(self):\n\n # check if documentalist has access to list media-types\n self.login_documentalist()\n response = self.client.get('/multimedia/media-types/' )\n\n # 403 = unauthorized\n self.assertEqual(response.status_code, 403)\n\n self.client.logout()\n self.login_admin()\n\n response = self.client.get('/multimedia/media-types/')\n self.assertContains(response, \"Video\")", "def detail(request, post_id, post_type):\n\n\tuser_additional_info = UserAdditionalInfo.objects.get(user_id = 1)\n\tuser = User.objects.get(id=1)\n\ttry:\n\t\tif post_type == \"i\": # i represents images\n\t\t\tpost = ImagePost.objects.get(id = post_id)\n\t\telse:\n\t\t\tpost = VideoPost.objects.get(id = post_id)\n\texcept (ImagePost.DoesNotExist, VideoPost.DoesNotExist):\n\t\tlogger.error('Something went wrong!')\n\t\traise Http404(\"Post does not exist\")\n\treturn render(request, 'devblog/post_detail.html', {'post':post, 'extra_info':user_additional_info,'author':user})", "def config_media_type(self):\n pass", "def config_media_type(self):\n pass", "def get_resumable_edit_media_link(self):\n return self.get_link(RESUMABLE_EDIT_MEDIA_LINK_REL)", "def view_file(self):\n\n index_list = self.ui.tableWidget.selectionModel().selectedIndexes()\n index = None\n if len(index_list) > 0:\n index = index_list[0].row()\n if index is None:\n return\n\n # Need the data as a dictionary to view images and audio/video\n dictionary = {'name': self.allfiles[index][NAME], 'mediapath': self.allfiles[index][MEDIAPATH],\n 'owner': self.allfiles[index][OWNER], 'id': self.allfiles[index][0],\n 'date': self.allfiles[index][DATE],\n 'memo': self.allfiles[index][MEMO], 'fulltext': self.allfiles[index][FULLTEXT],\n 'av_text_id': self.allfiles[index][AV_TEXT_ID]}\n # Mediapath will be None for a .transcribed empty text media entry, and 'docs:' for a linked text document\n if self.allfiles[index][MEDIAPATH] is None or self.allfiles[index][MEDIAPATH][0:5] == 'docs:':\n return\n # Added checks to test for media presence\n if self.allfiles[index][MEDIAPATH][:6] in (\"/video\", \"video:\"):\n if self.allfiles[index][MEDIAPATH][:6] == \"video:\":\n abs_path = self.allfiles[index][MEDIAPATH].split(':')[1]\n if not os.path.exists(abs_path):\n return\n if self.allfiles[index][MEDIAPATH][:6] == \"/video\":\n abs_path = self.app.project_path + self.allfiles[index][MEDIAPATH]\n if not os.path.exists(abs_path):\n return\n ui_av = DialogViewAV(self.app, dictionary)\n ui_av.exec()\n if self.allfiles[index][MEDIAPATH][:6] in (\"/audio\", \"audio:\"):\n if self.allfiles[index][MEDIAPATH][0:6] == \"audio:\":\n abs_path = self.allfiles[index][MEDIAPATH].split(':')[1]\n if not os.path.exists(abs_path):\n return\n if self.allfiles[index][MEDIAPATH][0:6] == \"/audio\":\n abs_path = self.app.project_path + self.allfiles[index][MEDIAPATH]\n if not os.path.exists(abs_path):\n return\n ui_av = DialogViewAV(self.app, dictionary)\n ui_av.exec()\n if self.allfiles[index][MEDIAPATH][:7] in (\"/images\", \"images:\"):\n if self.allfiles[index][MEDIAPATH][0:7] == \"images:\":\n abs_path = self.allfiles[index][MEDIAPATH].split(':')[1]\n if not os.path.exists(abs_path):\n return\n if self.allfiles[index][MEDIAPATH][0:7] == \"/images\":\n abs_path = self.app.project_path + self.allfiles[index][MEDIAPATH]\n if not os.path.exists(abs_path):\n return\n # Requires {name, mediapath, owner, id, date, memo, fulltext}\n ui_img = DialogViewImage(self.app, dictionary)\n ui_img.exec()", "def media_file_upload(request, manifest_id):\n manifest = get_object_or_404(Manifest, id=manifest_id)\n\n manifest_files = MediaFile.objects.filter(manifest=manifest)\n total_files_count = manifest_files.count()\n files_needing_upload = manifest_files.filter(file='')\n files_needing_upload_count = files_needing_upload.count()\n\n file_to_upload = files_needing_upload.first()\n\n # If no files left to upload, mark the manifest complete and move on\n if files_needing_upload_count < 1:\n Manifest.objects.filter(id=manifest.id).update(all_media_present=True)\n return HttpResponseRedirect(reverse('manifest-view', args=(manifest.id,)))\n\n form = MediaFileForm(request.POST or None, request.FILES or None, instance=file_to_upload)\n\n if form.is_valid():\n form.save()\n return HttpResponseRedirect(reverse('file-upload', args=(manifest.id,))) # Refresh view\n\n return render(request, 'file_manager/file_upload.html', {\n 'form': form,\n 'upload_number': total_files_count - files_needing_upload_count + 1, # Which place in order of upload e.g. 2 of 3\n 'total_files_count': manifest_files.count(),\n 'file_to_upload': file_to_upload,\n })", "def edit_permission(request, patient_id, record_id, perm_id):\n if (request.user.patient_username.id != patient_id):\n Logs.objects.create(type='READ', user_id=request.user.uid, interface='PATIENT', status=STATUS_ERROR, details='[Edit Permission] Logged in user does not match ID in URL. URL ID: ' + str(patient_id))\n return redirect('/patient/login/')\n\n patient = patient_does_not_exists(patient_id)\n\n try:\n record = get_record(record_id)\n record = record[0]\n except IndexError:\n Logs.objects.create(type='READ', user_id=patient.username.uid, interface='PATIENT', status=STATUS_ERROR, details='[Edit Permission] Record ID is invalid. Invalid ID: ' + str(record_id))\n return redirect('show_all_records', patient_id=patient_id)\n\n model = get_model(record)\n\n if (model == \"Readings\"):\n try:\n permission = ReadingsPerm.objects.filter(id = perm_id)\n permission = permission[0]\n except IndexError:\n Logs.objects.create(type='READ', user_id=patient.username.uid, interface='PATIENT', status=STATUS_ERROR, details='[Edit Permission] Permission ID is invalid. Invalid ID: ' + str(perm_id))\n return redirect('show_all_records', patient_id=patient_id)\n\n form = ReadingsPermissionEditForm(request.POST or None, instance=permission)\n if request.method == 'POST':\n if form.is_valid():\n permission.save()\n Logs.objects.create(type='UPDATE', user_id=patient.username.uid, interface='PATIENT', status=STATUS_OK, details='[Edit Permission] Edit Permission ' + str(perm_id))\n return redirect('show_record', patient_id=patient_id, record_id=record_id)\n else:\n Logs.objects.create(type='UPDATE', user_id=patient.username.uid, interface='PATIENT', status=STATUS_ERROR, details='[Edit Permission] Invalid Form')\n context = {\n 'form': form,\n 'patient': patient,\n 'record': record,\n 'permission': permission\n }\n return render(request, 'edit_permission.html', context)\n elif (model == \"TimeSeries\"):\n try:\n permission = TimeSeriesPerm.objects.filter(id = perm_id)\n permission = permission[0]\n except IndexError:\n Logs.objects.create(type='READ', user_id=patient.username.uid, interface='PATIENT', status=STATUS_ERROR, details='[Edit Permission] Permission ID is invalid. Invalid ID: ' + str(perm_id))\n return redirect('show_all_records', patient_id=patient_id)\n\n form = TimeSeriesPermissionEditForm(request.POST or None, instance=permission)\n if request.method == 'POST':\n if form.is_valid():\n permission.save()\n Logs.objects.create(type='UPDATE', user_id=patient.username.uid, interface='PATIENT', status=STATUS_OK, details='[Edit Permission] Edit Permission ' + str(perm_id))\n return redirect('show_record', patient_id=patient_id, record_id=record_id)\n else:\n Logs.objects.create(type='UPDATE', user_id=patient.username.uid, interface='PATIENT', status=STATUS_ERROR, details='[Edit Permission] Invalid Form')\n context = {\n 'form': form,\n 'patient': patient,\n 'record': record,\n 'permission': permission\n }\n return render(request, 'edit_permission.html', context)\n elif (model == \"Documents\"):\n try:\n permission = DocumentsPerm.objects.filter(id = perm_id)\n permission = permission[0]\n except IndexError:\n Logs.objects.create(type='READ', user_id=patient.username.uid, interface='PATIENT', status=STATUS_ERROR, details='[Edit Permission] Permission ID is invalid. Invalid ID: ' + str(perm_id))\n return redirect('show_all_records', patient_id=patient_id)\n\n form = DocumentsPermissionEditForm(request.POST or None, instance=permission)\n if request.method == 'POST':\n if form.is_valid():\n permission.save()\n Logs.objects.create(type='UPDATE', user_id=patient.username.uid, interface='PATIENT', status=STATUS_OK, details='[Edit Permission] Edit Permission ' + str(perm_id))\n return redirect('show_record', patient_id=patient_id, record_id=record_id)\n else:\n Logs.objects.create(type='UPDATE', user_id=patient.username.uid, interface='PATIENT', status=STATUS_ERROR, details='[Edit Permission] Invalid Form')\n context = {\n 'form': form,\n 'patient': patient,\n 'record': record,\n 'permission': permission\n }\n return render(request, 'edit_permission.html', context)\n elif (model == \"Videos\"):\n try:\n permission = VideosPerm.objects.filter(id = perm_id)\n permission = permission[0]\n except IndexError:\n Logs.objects.create(type='READ', user_id=patient.username.uid, interface='PATIENT', status=STATUS_ERROR, details='[Edit Permission] Permission ID is invalid. Invalid ID: ' + str(perm_id))\n return redirect('show_all_records', patient_id=patient_id)\n\n form = VideosPermissionEditForm(request.POST or None, instance=permission)\n if request.method == 'POST':\n if form.is_valid():\n permission.save()\n Logs.objects.create(type='UPDATE', user_id=patient.username.uid, interface='PATIENT', status=STATUS_OK, details='[Edit Permission] Edit Permission ' + str(perm_id))\n return redirect('show_record', patient_id=patient_id, record_id=record_id)\n else:\n Logs.objects.create(type='UPDATE', user_id=patient.username.uid, interface='PATIENT', status=STATUS_ERROR, details='[Edit Permission] Invalid Form')\n context = {\n 'form': form,\n 'patient': patient,\n 'record': record,\n 'permission': permission\n }\n return render(request, 'edit_permission.html', context)\n elif (model == \"Images\"):\n try:\n permission = ImagesPerm.objects.filter(id = perm_id)\n permission = permission[0]\n except IndexError:\n Logs.objects.create(type='READ', user_id=patient.username.uid, interface='PATIENT', status=STATUS_ERROR, details='[Edit Permission] Permission ID is invalid. Invalid ID: ' + str(perm_id))\n return redirect('show_all_records', patient_id=patient_id)\n\n form = ImagesPermissionEditForm(request.POST or None, instance=permission)\n if request.method == 'POST':\n if form.is_valid():\n permission.save()\n Logs.objects.create(type='UPDATE', user_id=patient.username.uid, interface='PATIENT', status=STATUS_OK, details='[Edit Permission] Edit Permission ' + str(perm_id))\n return redirect('show_record', patient_id=patient_id, record_id=record_id)\n else:\n Logs.objects.create(type='UPDATE', user_id=patient.username.uid, interface='PATIENT', status=STATUS_ERROR, details='[Edit Permission] Invalid Form')\n context = {\n 'form': form,\n 'patient': patient,\n 'record': record,\n 'permission': permission\n }\n return render(request, 'edit_permission.html', context)\n\n Logs.objects.create(type='READ', user_id=patient.username.uid, interface='PATIENT', status=STATUS_OK, details='[Edit Permission] Render Form')\n\n context = {\n 'form': form,\n 'patient': patient,\n 'record': record,\n 'permission': permission\n }\n\n return render(request, 'edit_permission.html', context)", "def edit_traits ( self, view = None, parent = None,\n kind = None, context = None,\n handler = None, id = '',\n scrollable = None, **args ):\n if context is None:\n context = self\n view = self.trait_view( view )\n return view.ui( context, parent, kind, self.trait_view_elements(),\n handler, id, scrollable, args )", "def edit(request, id, model, decorator = lambda x:x,\r\n post_save_redirect='', template_name=''):\r\n record = get_or_404(request, model, id)\r\n \r\n FormClass = decorator(\r\n forms.form_for_instance(\r\n record,\r\n fields = get_allowed_fields(request, model),\r\n ), \r\n request,\r\n instance = record\r\n )\r\n \r\n template_name = template_name or _make_template_name(model, 'form')\r\n\r\n #import pdb; pdb.set_trace()\r\n if request.method == 'POST':\r\n form = FormClass(request.POST)\r\n if form.is_valid():\r\n record = form.save()\r\n return HttpResponseRedirect(\r\n post_save_redirect or record.get_absolute_url()\r\n )\r\n else:\r\n form = FormClass()\r\n return render_to_response(\r\n template_name,\r\n context_instance = RequestContext(\r\n request,\r\n {\r\n 'form': form,\r\n }\r\n )\r\n )", "def edit(self):\n\n pass", "async def async_play_media(self, media_type, media_id, **kwargs):\n if media_id.isdigit():\n currentgallery_id = self._gallery_status[\"current_gallery\"]\n currentitems = await self.local_meural.send_get_items_by_gallery(currentgallery_id)\n in_playlist = next((g[\"title\"] for g in currentitems if g[\"id\"] == media_id), None)\n if in_playlist is None:\n# _LOGGER.warning(\"Item %s is not in current playlist, trying to play via remote API.\", media_id)\n await self.meural.device_load_item(self.meural_device_id, media_id)\n else:\n# _LOGGER.warning(\"Item %s in current playlist %s, loading locally.\", media_id, self._gallery_status[\"current_gallery_name\"])\n await self.local_meural.send_change_item(media_id)\n else:\n _LOGGER.warning(\"Can't play media: %s is not an item ID\", media_id)" ]
[ "0.62852633", "0.54435855", "0.5440475", "0.5382883", "0.5344347", "0.5296331", "0.5240183", "0.52306396", "0.5207163", "0.5171759", "0.5161495", "0.5148306", "0.5147011", "0.5133456", "0.51291484", "0.5108886", "0.5098199", "0.506505", "0.5042118", "0.5030467", "0.5025438", "0.5025438", "0.5018678", "0.50168335", "0.49623463", "0.49460363", "0.49324864", "0.49156302", "0.49009046", "0.4893638" ]
0.7646887
0
If POST, either add to or remove from press gallery. If GET, redirect to the browse page w/ a properly formed press gallery query.
def press_gallery(request): press_gallery_path = settings.PRESS_GALLERY_PATH if request.method == 'POST': if not request.user.has_perm('gallery.can_review'): raise PermissionDenied photo = models.Photo.objects.get(id=request.POST.get('id')) if photo is None: return handler400(request) if not os.path.exists(press_gallery_path): os.makedirs(press_gallery_path) action = request.POST.get('press_gallery', '').lower() filename = os.path.split(photo.image.name)[-1] press_photo_path = '%s%s' % (press_gallery_path, filename) if action == 'remove': if os.path.exists(press_photo_path): os.remove(press_photo_path) photo.in_press_gallery = False photo.save() request.notifications.add(_('Image removed from press gallery.')) elif action == 'add': shutil.copy(photo.image.file.name, press_photo_path) photo.in_press_gallery = True photo.save() request.notifications.add(_('Image added to press gallery.')) return HttpResponseRedirect(photo.get_absolute_url()) # Redirect to a browse page query if not request.user.has_perm('gallery.can_see_press_gallery'): raise PermissionDenied url = '%s?press_gallery=true' % reverse('bm.gallery.views.browse') return HttpResponseRedirect(url)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def browse(request):\n klass = media_klass_from_request(request)\n filter_args, filter_kwargs = filter_args_from_request(request)\n press_gallery = request.GET.get('press_gallery', '')\n press_gallery = press_gallery.lower() == 'true'\n if press_gallery:\n if not request.user.has_perm('gallery.can_see_press_gallery'):\n raise PermissionDenied\n # for now we only allow photos in the press gallery, not\n # artifacts or any other types. it's okay if the search query\n # doesn't specify a type, or if it specifies the photo type,\n # but we disallow other types of searches. it's a little ugly\n # to be doing explicit type checking, but expedience demands\n # it :P\n if klass is models.MediaBase:\n klass = models.Photo\n if klass is not models.Photo:\n return handler400(request)\n filter_kwargs['in_press_gallery'] = True\n status = request.GET.get('status')\n if not status:\n filter_kwargs['status'] = 'approved'\n elif status != 'approved':\n if not request.user.has_perm('gallery.can_review'):\n # only reviewers can arbitrarily query based on status;\n # non-reviewers are restricted to seeing their own\n # submissions if they search on a status other than\n # 'approved'\n if request.user.is_anonymous():\n raise PermissionDenied\n filter_kwargs['owner'] = request.user\n filter_kwargs['status'] = status\n else:\n filter_kwargs['status'] = status\n\n full_results = klass.objects.filter(*filter_args, **filter_kwargs)\n # reverse the order so most recent is first\n full_results = full_results.order_by('id').reverse()\n tag = request.GET.get('tag')\n if tag:\n full_results = tagmodels.TaggedItem.objects.get_by_model(full_results,\n tag)\n text = request.GET.get('text')\n if text:\n full_results = apply_searchable_text_filter(full_results, text)\n paginator = BetterPaginator(full_results, settings.PAGINATION_BATCH_SIZE)\n try:\n page = int(request.GET.get('page', '1'))\n except ValueError:\n page = 1\n try:\n page_results = paginator.page(page)\n except (InvalidPage, EmptyPage):\n page_results = paginator.page(paginator.num_pages)\n query_string = request.META.get('QUERY_STRING')\n # remove 'page' from query string so it doesn't get used in the template\n query_map = parse_qs(query_string)\n query_map.pop('page', None)\n query_string = urlencode(query_map, doseq=True)\n for extra_filter in ('owner', 'tag', 'press_gallery'):\n if extra_filter in query_map:\n del(query_map[extra_filter])\n qs_no_extra_filters = urlencode(query_map, doseq=True)\n no_extra_filters_url = reverse('bm.gallery.views.browse')\n if qs_no_extra_filters:\n no_extra_filters_url = '%s?%s' % (no_extra_filters_url,\n qs_no_extra_filters)\n template_map = {'page_results': page_results,\n 'total_count': full_results.count(),\n 'query_string': query_string,\n 'no_extra_filters_url': no_extra_filters_url,\n 'paginator': paginator.get_context(page),\n 'page': page}\n owner_username = request.GET.get('owner')\n if owner_username:\n template_map['owner'] = authmodels.User.objects.get(username=owner_username)\n if tag:\n template_map['tag'] = tag\n if press_gallery:\n template_map['press_gallery'] = True\n context = RequestContext(request, template_map)\n return render_to_response('gallery/browse.html', context)", "def get(self, request):\n success_message = ''\n form = PhotoForm()\n\n context = {\n 'form': form,\n 'msg': success_message\n }\n return render(request, 'photos/add.html', context)", "def post(self):\n query = self.request.get('search')\n if query:\n self.redirect('/searchdemo/charlie?' + urllib.urlencode(\n #{'query': query}))\n {'query': query.encode('utf-8')}))\n else:\n self.redirect('/searchdemo/charlie/')", "def upload_page():\n if not g.user:\n return redirect(url_for('login'))\n if request.method == \"GET\":\n return redirect(url_for('landing'))\n elif request.method == \"POST\":\n if 'image' not in request.files:\n return redirect(url_for('landing'))\n file = request.files['image']\n if file.filename == '':\n return redirect(url_for('landing'))\n if file:\n filename = secure_filename(file.filename)\n if is_dog(file):\n file.seek(0)\n upload_blob(file,g.user)\n flash(\"Image uploaded successfully!\")\n else:\n flash(\"You can only upload dog pictures!\")\n #file.save(os.path.join('static', 'UserPictures', g.user, filename))\n return redirect(url_for('landing'))", "def gallery(request):\n gallery = Gallery.objects.all()\n user = Profile.objects.all()\n if request.method == 'POST':\n form = ImageForm(request.POST, request.FILES)\n if form.is_valid():\n form.save()\n return redirect(reverse('gallery'))\n else:\n form = ImageForm()\n\n context = {\n 'gallery': gallery,\n 'form': form,\n 'user': user,\n }\n\n return render(request, 'gallery.html', context)", "def post(self):\n\n upload_files = self.get_uploads('file')\n blob_info = upload_files[0]\n self.redirect('/?upload_info=%s' % urllib.quote(blob_info.filename))", "def post(request, slug, username):\n add_contributor_album(slug, username)\n response = redirect(reverse(\"resource_contributoralbum\", args=[slug, username]))\n response['Cache-Control'] = 'no-cache'\n return response", "def post(request):\r\n\r\n if 'submitSearch' in request.POST:\r\n searchValue = request.POST['submitSearch']\r\n values = searchValue.replace(' ', '+')\r\n\r\n return HttpResponseRedirect('/feedreader/search/?keywords=' + values)\r\n\r\n\r\n return HttpResponseRedirect('/feedreader/manage')", "def gallery(request):\n # Build search query if the form is filled out, otherwise use defaults\n if request.method == 'POST' and 'clear' not in request.POST:\n search_form = search.Search(request.POST)\n if search_form.is_valid():\n query = search_form.cleaned_data\n where, order_by = search.handle_search(query)\n else:\n search_form = search.Search()\n where, order_by = None, 'ORDER BY id DESC' # Default: select all, order by date (desc)\n\n # Select items\n try:\n items = SELECT('item', where=where, extra=order_by)\n except:\n items = []\n # If only one item returned, make it a list to avoid edgecases on the frontend template\n if not isinstance(items, list):\n items = [items]\n\n context = {\n 'items': items,\n 'search': search_form\n }\n return render(request, 'gallery.html', context)", "def post(self) :\n self.redirect('/admin')", "def add():\n if request.method == 'GET':\n return render_template('add.html')\n elif request.method == 'POST':\n data = {}\n for key in ('h', 'name', 'summary', 'content', 'published', 'updated', 'category',\n 'slug', 'location', 'in-reply-to', 'repost-of', 'syndication'):\n data[key] = None\n\n for title in request.form:\n data[title] = request.form[title]\n\n for title in request.files:\n data[title] = request.files[title].read()\n\n try:\n photo = request.files['photo']\n except:\n photo = None\n\n for key in data:\n if data[key] == \"\":\n data[key] = None\n\n data['published'] = datetime.now()\n\n location = create_entry(data, image=data['photo'], g=g)\n\n if data['in-reply-to']:\n send_mention('http://' + DOMAIN_NAME + '/e/'+location, data['in-reply-to'])\n\n if request.form.get('twitter'):\n t = Timer(30, bridgy_twitter, [location])\n t.start()\n\n if request.form.get('facebook'):\n t = Timer(30, bridgy_facebook, [location])\n t.start()\n return redirect(location)\n else:\n return redirect('/404'), 404", "def upload():\r\n\r\n if not os.path.isdir(TO_SEGMENT):\r\n os.mkdir(TO_SEGMENT)\r\n else:\r\n print(\"could not create upload directory: {}\".format(TO_SEGMENT))\r\n print(request.files.getlist(\"file\"))\r\n\r\n for upload in request.files.getlist(\"file\"):\r\n filename = upload.filename\r\n destination = \"/\".join([TO_SEGMENT, filename])\r\n upload.save(destination)\r\n\r\n return redirect(url_for('get_gallery'))", "def response_post_save_add(self, request, obj):\n opts = self.model._meta\n\n if \"next\" in request.GET:\n return HttpResponseRedirect(request.GET['next'])\n\n if self.has_change_permission(request, None):\n post_url = reverse('admin:%s_%s_changelist' %\n (opts.app_label, opts.module_name),\n args=(quote(self.prescription.pk),),\n current_app=self.admin_site.name)\n else:\n post_url = reverse('admin:index',\n current_app=self.admin_site.name)\n\n return HttpResponseRedirect(post_url)", "def drinks_submit():\n drink = {\n 'name': request.form.get('name'),\n 'price': request.form.get('price'),\n 'description': request.form.get('description'),\n 'images': request.form.get('images').split()\n }\n drink_id = drinks_collection.insert_one(drink).inserted_id\n return redirect(url_for('drinks_show', drink_id=drink_id))", "def do_POST(self):\r\n self.do_GET()", "def add_image(request):\n\n if not request.user.is_superuser:\n messages.error(\n request,\n \"Access denied! Only store admin can add an image.\")\n return redirect(reverse(\"home\"))\n\n if request.method == \"POST\":\n form = GalleryForm(request.POST, request.FILES)\n if form.is_valid():\n image = form.save()\n messages.success(request, \"Image added sucessfully!\")\n return redirect(reverse(\"image\", args=[image.id]))\n else:\n messages.error(\n request, (\"Adding new image failed. \"\n \"Check if the form is valid.\"))\n else:\n form = GalleryForm()\n\n template = \"gallery/add_image.html\"\n context = {\n \"form\": form,\n }\n return render(request, template, context)", "def post(self, request, *args, **kwargs):\n try:\n files = request.session['__ddoc_files']\n\n except KeyError:\n files = {}\n\n action = request.POST.get('action', 'add_file')\n\n if action == 'remove_file':\n file_name = request.POST.get('file_name', '')\n\n n_files = {}\n for key, file in files.items():\n if key != file_name:\n n_files[key] = file\n\n files = n_files\n\n else:\n for key, file in request.FILES.items():\n file_name = file.name\n\n idx = 1\n while file_name in files.keys():\n file_name = '%d_%s' % (idx, file_name)\n idx += 1\n\n files[file_name] = dict(\n content=force_text(base64.b64encode(file.read())),\n content_type=file.content_type,\n size=file.size,\n )\n\n request.session['__ddoc_files'] = files\n\n return HttpResponseRedirect('.')", "def use_uploadpy(request):\n if request.method == 'POST':\n return HttpResponseRedirect(reverse(customized_upload_py))\n return respond(request, 'use_uploadpy.html')", "def post(self):\n self.get_or_post(method='POST')", "def post(self):\n user = users.get_current_user()\n if user:\n user_obj = utils.get_user(user)\n args = self.request.arguments()\n feeds = [x for x in args if x != 'delete' and x != 'modify']\n delete = self.request.get('delete')\n if delete:\n utils.delete_feeds(feeds, user_obj)\n self.redirect('/')", "def post(self):\n if self.data.GET.get('cbox'):\n cbox = True\n else:\n cbox = False\n\n if self.validate():\n self.redirect.program()\n self.redirect.to('edit_gci_program', validated=True, cbox=cbox)\n else:\n self.get()", "def add_post():\n user = get_user()\n if not user:\n return 'Error: not logged in.', 401\n url = app.config['POSTS_ENDPOINT'] + 'add'\n form_data = dict(**request.form.to_dict(), author_id=user['user_id'])\n images = ((img.filename, img.read())\n for img in request.files.getlist(\"images\") if img.filename != '')\n response = requests.post(\n url, data=form_data, files=images)\n if response.status_code == 201:\n # upload successful, redirect to index\n return redirect(url_for(\"index\"))\n return response.content, response.status_code", "def add():\n if request.method == \"POST\":\n result = add_post(\n request.form[\"title\"],\n request.form[\"body\"]\n )\n flash(result)\n return redirect(url_for(\"show\"))\n else:\n return render_template(\"add.html\")", "def upload_success(request, form, original):\n return redirect(original)", "def services_gadget_addrem(request, action):\n if request.method == u'POST':\n if action and u'gadgetid' in request.POST:\n gadget_id = request.POST[u'gadgetid']\n if action == u'add':\n try:\n gadget = Gadget.objects.for_user(request.user).get(pk=gadget_id)\n except ObjectDoesNotExist:\n return HttpResponse(400)\n ug = gadget.add_to_user(request.user)\n ret = request.GET.get('ret', 'snippet')\n if ret == 'id':\n return HttpResponse(ug.id)\n ugsnip = render(request, u'dreamdesktop/dialog-services-usergadget.html', {u'usergadget' : ug})\n return HttpResponse(ugsnip, status=200)\n else:\n qs = UserGadget.objects.filter(gadget=gadget_id, user=request.user)\n if qs.count() == 0:\n return HttpResponse(status=400)\n usergadget = qs[0]\n ugid = usergadget.id\n usergadget.delete()\n return HttpResponse(ugid, status=200)\n return HttpResponse(status=400)", "def add_animal_process():\n\n email = session['current_admin']\n admin = c.get_admin_by_session(email)\n admin_id = admin.admin_id\n\n if request.method == 'POST':\n # Check if the post request has the file part\n if 'file' not in request.files:\n flash('No file part')\n return redirect('/admin/' + str(admin_id))\n # Get the name of the uploaded file\n uploaded_file = request.files['file']\n # If user does not select a file, browser also\n # submits an empty part without filename\n if uploaded_file.filename == '':\n flash('No selected file')\n return redirect('/admin/' + str(admin_id))\n # Check if the file is one of the allowed types/extensions\n if uploaded_file and c.allowed_file(uploaded_file.filename, ALLOWED_EXTENSIONS):\n # passing the request and session object\n animal = c.add_animal(request, session, app.config['UPLOAD_FOLDER'])\n\n return redirect('/rescue/' + str(animal.rescue_id))", "def post():\n pass", "def delete(request):\n wfsxml = request.POST.get('wfsxml', False) # FOR GEOSERVER\n uuid = request.POST.get('uuid', False)\n # MAKE GEOSERVER WFS TRANSACTION\n error = post_to_geoserver(wfsxml, GeoPostBase.wfsURL)\n # ALL GOOD\n if error:\n return server_error(error)\n # IF WFS TRANSACTION ERROR\n else:\n pass\n # Delete photo from bucket\n delete_from_bucket(uuid, GeoPostBase.imageBucket)\n return HttpResponseRedirect(reverse('geopost_home'))", "def post(self, request, pk):\n action_key = request.POST.get(\"action\")\n _, method = self.actions[action_key]\n getattr(self, method)()\n return HttpResponseRedirect(reverse(\"event_admin\", kwargs={\"pk\": pk}))", "async def gallery_post(self, num: int) -> GalleryPost:\n return GalleryPost(**await self.get(f\"/gallery/view/{num}\"))" ]
[ "0.6142033", "0.59063977", "0.5835408", "0.568863", "0.5672334", "0.56279814", "0.55793434", "0.55041337", "0.5490576", "0.5481275", "0.5449348", "0.54288334", "0.53872204", "0.53834766", "0.5364756", "0.52974206", "0.5286496", "0.5253664", "0.52518123", "0.5241001", "0.52392626", "0.5235043", "0.51928246", "0.5189487", "0.51802456", "0.51483625", "0.512439", "0.5118621", "0.51065195", "0.5093473" ]
0.72716916
0
View that accepts ajax upload requests, returning a JSON response
def upload_ajax(request): log.debug('upload ajax view') if not request.user.has_perm('gallery.can_upload'): return None #videoPerm = request.user.has_perm('gallery.can_review') if request.method != "POST": return JSONResponse(False, {}, response_mimetype(request)) log.debug("Batch: %s" % request.POST['batch']) batchid = request.POST.get('batch', None) if not batchid: log.warn('no Batch') raise PermissionDenied try: batch = models.Batch.objects.get(uuid=batchid) except models.Batch.DoesNotExist: log.warn('No such batch: %s', batchid) raise PermissionDenied if batch.user != request.user: log.warn('User %s cannot edit batch %s', request.user, batch) raise PermissionDenied batchname = request.POST.get('batchname', None) if batchname: batch.name = batchname log.debug('updating batch %s to name: %s', batch, batchname) batch.save() uploaded = request.FILES.get('file') f, ext = uploaded.name.rsplit('.',1) ext = ext.lower() if ext in ('zip','tar','tar.gz','tgz','tbz','tar.bz'): log.debug('saving ArchiveFile') instance = models.ArchiveFile.objects.create( owner = request.user, filefield = uploaded, batch = batch) data = [{'name': uploaded.name, 'url': '', 'thumbnail_url': '', 'delete_url': reverse('gallery_delete_ajax', args=['archive', instance.id]), 'delete_type': "DELETE", 'batchid' : batch.uuid, 'batchname' : batch.name}] else: instance = models.media_from_file(uploaded, batch, request.user) if instance is None: data = [{'error' : 'Could not read file: %s, perhaps it is corrupt' % uploaded.name}] else: data = [{'name': uploaded.name, 'url': instance.image.url, 'thumbnail_url': instance.thumbnail_image.url, 'delete_url': reverse('gallery_delete_ajax', args=[instance.mediatype(), instance.id]), 'delete_type': "DELETE", 'batchid' : batch.uuid, 'batchname' : batch.name}] response = JSONResponse(data, {}, response_mimetype(request)) response['Content-Disposition'] = 'inline; filename=files.json' return response
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def handle_check_upload_files(request):\n\n files = []\n for filename, file in request.FILES.items():\n files.append(file)\n\n json_message = check_uploaded_files(files)\n return JsonResponse(json_message)", "def handle_upload_files(request):\n\n files = []\n for filename, file in request.FILES.items():\n files.append(file)\n overwrite = request.POST.get('overwrite',None)\n\n if overwrite == 'false':\n overwrite = False\n elif overwrite == 'true':\n overwrite = True\n\n json_message = upload_files(files,request.session['username'],overwrite)\n return JsonResponse(json_message)", "def insert_filedetails_ajax(request):\n try:\n file_path = request.GET.get('file_path')\n file_name, extension = splitext(file_path)\n date_time = datetime.datetime.now().strftime(\"%Y.%m.%d_%H:%M:%S\")\n json_obj = {\"file_path\": file_path, \"extension\": extension, \"date_ingested\": date_time}\n inserted_data = insert(json_obj)\n return JsonResponse({\"data_inserted\": inserted_data, \"message\": \"Success\", \"status_code\": \"200\"})\n except Exception as e:\n print(\"Insert Error : \", e)\n return False", "def upload_file():\n retVal = None \n if request.method == 'POST' and upload_validated(request):\n retVal = render_successful_upload(request) \n else:\n retVal = render_index()\n return retVal", "def upload_file_view(user_data, cache):\n return UploadFilesCtrl(cache, user_data, request).to_response()", "def upload_file_view(user_data, cache):\n return UploadFilesCtrl(cache, user_data, request).to_response()", "def xmodule_handler(self, request, suffix=None):\r\n class FileObjForWebobFiles(object):\r\n \"\"\"\r\n Turn Webob cgi.FieldStorage uploaded files into pure file objects.\r\n\r\n Webob represents uploaded files as cgi.FieldStorage objects, which\r\n have a .file attribute. We wrap the FieldStorage object, delegating\r\n attribute access to the .file attribute. But the files have no\r\n name, so we carry the FieldStorage .filename attribute as the .name.\r\n\r\n \"\"\"\r\n def __init__(self, webob_file):\r\n self.file = webob_file.file\r\n self.name = webob_file.filename\r\n\r\n def __getattr__(self, name):\r\n return getattr(self.file, name)\r\n\r\n # WebOb requests have multiple entries for uploaded files. handle_ajax\r\n # expects a single entry as a list.\r\n request_post = MultiDict(request.POST)\r\n for key in set(request.POST.iterkeys()):\r\n if hasattr(request.POST[key], \"file\"):\r\n request_post[key] = map(FileObjForWebobFiles, request.POST.getall(key))\r\n\r\n response_data = self.handle_ajax(suffix, request_post)\r\n return Response(response_data, content_type='application/json')", "def update_filedetails_ajax(request):\n try:\n document_id = request.GET.get('document_id')\n tag = request.GET.get('tag')\n get_index = find_index_with_document(document_id)\n updated_data = update(get_index, document_id, tag)\n return JsonResponse({\"fs_metadata\": updated_data, \"message\": \"Success\", \"status_code\": \"200\"})\n except Exception as e:\n print(\"Update Error : \", e)\n return False", "def get_allfiles_ajax(request):\n try:\n get_all = fetch_all()\n return JsonResponse({\"fs_metadata\": get_all['hits']['hits'], \"message\": \"Success\", \"status_code\": \"200\"})\n except Exception as e:\n print(\"Get All Documents Error : \", e)\n return False", "def delete(self, request, *args, **kwargs):\n self.object = self.get_object()\n self.object.delete()\n if request.is_ajax():\n response = JSONResponse(True, {}, response_mimetype(self.request))\n response['Content-Disposition'] = 'inline; filename=files.json'\n return response\n else:\n return HttpResponseRedirect('/upload/new')", "def handle_upload(request):\n storage = DefaultStorage()\n\n if request.method=='POST' and request.FILES:\n f = request.FILES.values()[0]\n name = settings.MEDIA_URL + handle_uploaded_file(storage,f,'')\n else:\n name = False;\n \n data = \"\"\"\n {\n error: '',\n filename: '%s',\n }\n \"\"\" % (name)\n \n return HttpResponse(data)", "def upload(request):\n # We pass the 'file_id' in the query string as a GET parameter. If\n # we read it from the POSTed data, WebOb would read all POSTed\n # data, which has various features and traps (like setting the\n # \"Content-Length\" header to 0) that we do not need since we are\n # going to read the data ourselves anyway.\n file_id = request.GET['X-Progress-ID']\n input_file, file_size, filename = get_file_from_request(request)\n session = DBSession()\n u = session.query(Upload).filter_by(id=file_id).one()\n upload_dir = request.registry.settings['poulda.upload_dir']\n user_id = authenticated_userid(request)\n # We use a temporary path to detect unfinished uploads (post\n # mortem, not in the application itself).\n path = os.path.join(upload_dir, '_'.join((user_id, file_id)))\n u.tmp_path = path\n u.started = int(time.time())\n u.size = file_size\n u.state = u'uploading'\n session.flush()\n # We need to commit the transaction so that changes to the Upload\n # object can be seen by the other threads (which will serve the\n # 'progress' JSON view called by the upload page).\n transaction.commit()\n with open(path, 'w') as output:\n # We must read only 'file_size' bytes from the 'input_file',\n # not all of it since it also contains the MIME boundary.\n copy_to_file(input_file, file_size, output)\n final_path = filename[1 + filename.rfind(os.sep):]\n final_path = os.path.join(upload_dir, final_path)\n os.rename(path, final_path)\n session = DBSession()\n u = session.query(Upload).filter_by(id=file_id).one()\n u.state = u'done'\n u.final_path = unicode(final_path, 'utf-8')\n return HTTPFound(location='success')", "def use_uploadpy(request):\n if request.method == 'POST':\n return HttpResponseRedirect(reverse(customized_upload_py))\n return respond(request, 'use_uploadpy.html')", "def file_upload(self, req, folder_path):\n\t\tresult, filename = self.handle_upload(req, folder_path)\n\t\tfile_url = self.selected_root['url_callback'](req, folder_path, filename)\n\t\t\n\t\tself.content_type = 'text/html'\n\t\tself.content = [str(tags.script(type=\"text/javascript\")[\n\t\t\t\t\t\t\"window.parent.frames['frmUpload'].OnUploadCompleted(%s, '%s');\\n\" % (result, filename)\n\t\t\t\t\t\t])]", "def dna_file_uploaded_view(request):\n\n data = request.data\n\n user = User.objects.get(username=request.user)\n directory = Directory.objects.get(user=user)\n\n directory_name = getattr(directory, 'name')\n data[\"directory\"] = getattr(directory, 'id')\n\n dna_file_uploaded_serializer = DNAFileUploadedSerializer(data=data)\n\n # validate request\n if dna_file_uploaded_serializer.is_valid():\n\n file_name = data['file_name']\n dna_file_instance = DNAFile.objects.get(\n file_name=file_name, directory=directory)\n\n if data['is_uploaded']:\n if user.username == DEFAULT_USERNAME:\n generate_kmer_forest.delay(dna_file_instance.id, True)\n else:\n generate_kmer_forest.delay(dna_file_instance.id, False)\n else:\n dna_file_instance.delete()\n\n return Response(status=HTTP_200_OK)\n else:\n return Response(dna_file_uploaded_serializer.errors,\n status=HTTP_400_BAD_REQUEST)", "def upload():\n return handle_upload(app, request)", "def handle_ajax(self):\r\n pass", "def complete_upload(self, request, **kwargs):\n\n self.method_check(request, allowed=[\"get\"])\n self.is_authenticated(request)\n\n if not self.check_dfo(request, kwargs[\"dfo_id\"]):\n return self.handle_error(\"Invalid object or access denied.\")\n\n dfo = DataFileObject.objects.get(id=kwargs[\"dfo_id\"])\n\n if not dfo.verified:\n # Async task as we can't wait until file is ready\n tasks.complete_chunked_upload.apply_async(args=[dfo.id])\n\n data = {\n \"success\": True,\n \"verified\": dfo.verified\n }\n\n return JsonResponse(data, status=200)", "def post(self, request: HttpRequest) -> HttpResponse:\n if \"id\" in request.POST and \"imagedata\" in request.FILES:\n # Instantiate BrowserObjectView to use handle_post_file\n upload_view = BrowserObjectView()\n upload, created = upload_view.handle_post_file(request.FILES[\"imagedata\"])\n if created:\n # Run auto-claim\n if CONFIG.y(\"auto_claim_enabled\", False) and \"username\" in request.POST:\n matching = get_user_model().objects.filter(\n username=request.POST.get(\"username\")\n )\n if matching.exists():\n upload.user = matching.first()\n LOGGER.debug(\n \"Auto-claimed upload to user '%s'\",\n request.POST.get(\"username\"),\n )\n upload.save()\n # Count initial view\n ObjectViewFile.count_view(upload, request)\n LOGGER.info(\"Uploaded %s\", upload.filename)\n # Generate url for client to open\n default_return_view = CONFIG.y(\"default_return_view\", \"sha256\").replace(\n \"view_\", \"\"\n )\n upload_hash = getattr(upload, default_return_view, \"sha256\")\n url = reverse(\n \"view_\" + default_return_view,\n kwargs={\"file_hash\": upload_hash},\n )\n return HttpResponse(request.build_absolute_uri(url))\n return HttpResponse(status=400)", "def delete_filedetails_ajax(request):\n try:\n document_id = request.GET.get('document_id')\n get_index = find_index_with_document(document_id)\n deleted_data = delete(get_index, document_id)\n return JsonResponse({\"document_id\": document_id, \"message\": \"Success\", \"status_code\": \"200\"})\n except Exception as e:\n print(\"Delete Error : \", e)\n return False", "def crop_success(request, form, original, cropped):\n if request.is_ajax():\n return HttpResponse(\n simplejson.dumps({\n 'image': {\n 'url': cropped.image.url,\n 'width': cropped.w,\n 'height': cropped.h,\n } \n }),\n mimetype='application/x-json',\n ) \n\n return render(request, 'cropper/crop.html', {\n 'form' : form,\n 'cropped' : cropped,\n 'original' : original,\n })\n \n return redirect(original)", "def html_files_upload(request):\n if request.method == \"POST\":\n \n html_files = request.FILES.getlist('html_file')\n fs = [i for i in os.listdir('temp/html_files') if 'html' in i]\n #delete old files\n for f in fs:\n os.remove('temp/html_files/{}'.format(f))\n for i, f in enumerate(html_files):\n handle_uploaded_file(f, 'temp/html_files/html_file_{}.html'.format(i+1))\n\n return _start_analysis(request)\n else:\n return HttpResponse(\n json.dumps({\"error\": \"error, GET request not supported\"}),\n content_type=\"application/json\"\n )", "def upload(request):\n if request.method == 'POST':\n sender = request.POST.get('sender')\n recipient = request.POST.get('recipient')\n subject = request.POST.get('subject', '')\n \n body_html = request.POST.get('body-html', '')\n body_plain = request.POST.get('body-plain', '')\n\n for key in request.FILES:\n file = request.FILES[key]\n # do_something_cool_with(file)\n\n # Returned text is ignored but HTTP status code matters: \n # Mailgun wants to see 200, otherwise it will make another attempt\n return HttpResponse('OK')", "def upload_file(self):\n request = copy.deepcopy(self.request_template)\n data = json.dumps(request)\n curr_file = {\n 'request': data,\n 'file': open(self.file_path, 'rb')\n }\n print(\"Sending Upload request of av for file {}\".format(self.file_name))\n try:\n response = requests.post(url=self.url + \"upload\", files=curr_file, verify=False)\n except Exception as E:\n print(\"Upload file failed. file: {} , failure: {}\".format(self.file_name, E))\n raise\n response_j = response.json()\n print(\"av Upload response status for file {} : {}\".format(self.file_name,\n response_j[\"response\"][0][\"status\"][\"label\"]))\n return response_j", "def submitFiles(self):\n formData =__new__(FormData)();\n \"\"\"\n Iteate over any file sent over appending the files\n to the form data.\n \"\"\"\n i=0\n console.log(self.vue.files)\n while i < self.vue.files.length:\n file = self.vue.files[i];\n formData.append('files[' + i + ']', file);\n i+=1\n \"\"\"\n Make the request to the POST /file-drag-drop URL\n \"\"\"\n formData.append(\"type\",\"upload\")\n __pragma__ ('jsiter') \n fetch('/json/plugins/',\n {\n \"method\":\"POST\",\n \"body\":formData,\n })\\\n .then(lambda res:res.json())\\\n .then(self.uploaded)\\\n .catch(lambda e:console.log('FAILURE!!',e));\n __pragma__ ('nojsiter')", "def post_avatar_view(request):\n msg = {}\n msg['Code'] = False\n try:\n username = request.user.username\n user_this = request.user\n avatar = request.FILES.get('avatar', None)\n print(1)\n if not avatar:\n print(2)\n return HttpResponse(json.dumps(msg),\n content_type='application/json')\n tmp = open(os.path.join(MEDIA_ROOT, username, \"tmp\"), mode='w')\n tmp.close()\n destination = open(os.path.join(MEDIA_ROOT, username, \"tmp\"),\n 'wb+') # 打开特定的文件进行二进制的写操作\n for chunk in avatar.chunks(): # 分块写入文件\n destination.write(chunk)\n user_this.extension.avatar.save(avatar.name, destination)\n destination.close()\n os.remove(os.path.join(MEDIA_ROOT, username, \"tmp\"))\n msg['Code'] = True\n msg['Message'] = 'media/' + str(user_this.extension.avatar)\n except Exception as e:\n msg['Message'] = str(e)\n pass\n return JsonResponse(msg)", "def api_upload():\n return make_response(file_manager.save_uploaded_file(), 200)", "def check_input_files(request):\n\n reports = []\n labels = []\n pubmedfiles = []\n concepts = []\n type1 = request.POST.get('type',None)\n username = request.POST.get('username',None)\n # email = request.POST.get('email',None)\n password = request.POST.get('password',None)\n for filename, file in request.FILES.items():\n if filename.startswith('reports'):\n reports.append(file)\n if filename.startswith('pubmed'):\n pubmedfiles.append(file)\n elif filename.startswith('concepts'):\n concepts.append(file)\n elif filename.startswith('labels'):\n labels.append(file)\n jsonDisp = request.POST.get('json_disp','')\n jsonAnn = request.POST.get('json_ann','')\n load_concepts = request.POST.get('exa_concepts',None)\n load_labels = request.POST.get('exa_labels',None)\n jsonResp = check_file(reports,pubmedfiles,labels,concepts,jsonDisp,jsonAnn,username,password,load_concepts,load_labels)\n\n # print(jsonResp)\n\n return JsonResponse(jsonResp)", "def fpupload(request, dataset_id):\n\n dataset = Dataset.objects.get(id=dataset_id)\n logger.debug('called fpupload')\n\n if request.method == 'POST':\n logger.debug('got POST')\n for key, val in request.POST.items():\n splits = val.split(\",\")\n for url in splits:\n try:\n fp = FilepickerFile(url)\n except ValueError:\n pass\n else:\n picked_file = fp.get_file()\n filepath = write_uploaded_file_to_dataset(dataset,\n picked_file)\n datafile = Dataset_File(dataset=dataset,\n filename=picked_file.name,\n size=picked_file.size)\n replica = Replica(datafile=datafile,\n url=filepath,\n protocol='',\n location=Location.get_default_location())\n replica.verify(allowEmptyChecksums=True)\n datafile.save()\n replica.datafile = datafile\n replica.save()\n\n return HttpResponse(json.dumps({\"result\": True}))", "def new_upload_image():\n log_request(request)\n\n if not valid_params(['username', 'session_id'], request.form) or\\\n not valid_params(['file'], request.files):\n logging.debug(\"Missing parameters\")\n return jsonify({'error' : 500})\n \n username = request.form['username']\n sId = request.form['session_id']\n fil = request.files['file']\n\n \n # check session before upload\n if not user.verify(username, sId):\n logging.debug(\"Invalid username or session id\")\n return jsonify({'error' : 101})\n\n if fil and allowed_file(fil.filename):\n # get the file extension\n ext = os.path.splitext(fil.filename)[1]\n # create a temporary file\n f = tempfile.NamedTemporaryFile(delete=False, dir=\"/var/www/resources/tmp/\", suffix=\"{0}\".format(ext))\n os.chmod(f.name, 0644)\n name = os.path.basename(f.name)\n f.write(fil.read())\n f.close()\n # get the dividing points for the page\n i = Image.open(f.name)\n divs = divLines(i)\n del i\n # return the dividing points and the name of the page in json form\n return jsonify(\n name = name,\n divs = divs,\n error = 0)\n else:\n logging.debug(\"Image processing failed, invalid filetype?\")\n return jsonify({'error' : 200})" ]
[ "0.68334264", "0.66960365", "0.65871376", "0.6556745", "0.6499524", "0.6499524", "0.6397053", "0.63761085", "0.6338587", "0.63231015", "0.6295487", "0.6197913", "0.6195067", "0.6190436", "0.6165591", "0.615164", "0.6142574", "0.60224116", "0.5988723", "0.5988673", "0.59264004", "0.5923921", "0.58998656", "0.5882591", "0.5879595", "0.58753175", "0.5873975", "0.5856601", "0.5815828", "0.5798213" ]
0.7459421
0
Generate random expression and return correct answer and question.
def calc(): randnum1 = randint(1, 100) randnum2 = randint(1, 100) operator = choice('+-*') question = '{0} {1} {2}'.format(randnum1, operator, randnum2) if operator == '+': answer = randnum1 + randnum2 elif operator == '-': answer = randnum1 - randnum2 elif operator == '*': answer = randnum1 * randnum2 return answer, question
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def generate_question_and_answer(): # noqa: WPS210\n start_number = random.randint(1, 100)\n progression_step = random.randint(1, 10)\n progression_length = random.randint(5, 10)\n progression = generate_progression(\n start_number, progression_step, progression_length,\n )\n return hide_number(progression)", "def choose_question():\r\n random_index_question = randint(1, question.num_question + 1)\r\n random_question = question.question[random_index_question]\r\n correct_answer = question.answer[random_index_question]\r\n return random_question, correct_answer", "def get_question_and_answer():\n question = random.randint(MIN_VALUE, MAX_VALUE)\n correct_answer = 'yes' if is_even(question) else 'no'\n return question, correct_answer", "def data_generation():\n num1 = random.randint(1, 100)\n num2 = random.randint(1, 100)\n correct_answer = math.gcd(num1, num2)\n expression = f'{num1} {num2}'\n return expression, str(correct_answer)", "def get_question():\n last_line = '\\n'\n question = \"\"\n\n print(\"Type in your question here:\")\n while last_line != \"\":\n current_line = input()\n if current_line == \"\":\n break\n question += current_line + \"\\n\"\n\n variables = {}\n\n # Special syntax variables\n rand = random.randint\n\n array_of_lines = question.split(\"\\n\")\n\n question_is_present = False\n\n for line in array_of_lines:\n if \"QUESTION\" in line:\n question_is_present = True\n break\n\n if question_is_present:\n variable_lines = []\n secret_lines = []\n question_lines = []\n\n for index in range(len(array_of_lines)):\n if array_of_lines[index] == \"SECRET\":\n secret_index = index\n if array_of_lines[index] == \"QUESTION\":\n question_index = index\n break\n\n # Adds variables to variable_lines\n for index in range(secret_index):\n variable_lines.append(array_of_lines[index])\n\n # Adds answer to secret_lines\n for index in range(secret_index + 1, question_index):\n secret_lines.append(array_of_lines[index])\n\n # Adds question lines to question_lines\n for index in range(question_index + 1, len(array_of_lines)):\n question_lines.append(array_of_lines[index])\n\n for line in variable_lines:\n variable, value = line.split(\"=\")\n variables[\"$\" + variable] = str(eval(value)).replace(\"_\", \" \")\n\n for index in range(len(secret_lines)):\n secret_lines[index] = science_utils.multiple_replace(line, variables)\n variable, value = secret_lines[index].split(\"=\")\n variables[\"answer\"] = str(eval(value)).replace(\"_\", \" \")\n\n for line in question_lines:\n question_lines[question_lines.index(line)] = science_utils.multiple_replace(line, variables)\n\n return question_lines, variables[\"answer\"]\n\n # This is the backup method, for when there is no QUESTION line found\n else:\n # Calculate values\n for word in array_of_lines:\n if \"=\" in word:\n variable, value = word.split(\"=\")\n variables[\"$\" + variable] = str(eval(value)).replace(\"_\", \" \")\n\n for words in array_of_lines:\n array_of_lines[array_of_lines.index(words)] = science_utils.multiple_replace(words, variables)\n\n to_return = []\n for line in array_of_lines:\n if \"=\" not in line:\n to_return.append(line)", "def evaluate_my_number(guess, random_number):", "def sentence():\n res = random.choice(no_result)\n adr = random.choice(address)\n wik = random.choice(wiki)\n return {'res': res, 'adr': adr, 'wik': wik}", "def get_random_arithmetic_expr() -> Tuple[str, str, str]:\n\n left = random.choice([\"a\", \"b\"])\n right = \"b\" if left == \"a\" else \"a\"\n return (left, random.choice(ARITHMETIC_OPERATORS), right)", "def random_operation():\r\n operation = random.choice([\"add\",\"subtract\",\"multiply\",\"divide\"])\r\n return operation", "def get_random_phrase():\n return random.choices(PHRASES, WEIGHTS, k=1)[0]", "def test_quick_answer(self):\n pass", "def generate_answer(self):\n\n for model in Response.get_all_models():\n match = model.matches(self.request.question, self.request.element)\n if match: return model.solve(self.request.question, self.request.element)\n\n return \"I am unable to answer this question. If you think I should be able to answer\\n\" + \\\n \"this, please submit an issue or pull request at:\\n\" + \\\n \"https://github.com/jackcook/the-scientist/compare\"", "def test_exponential_answer(self):\r\n answer = 50\r\n correct_responses = [\r\n \"50\", \"50.0\", \"5e1\", \"5e+1\",\r\n \"50e0\", \"50.0e0\", \"500e-1\"\r\n ]\r\n incorrect_responses = [\"\", \"3.9\", \"4.1\", \"0\", \"5.01e1\"]\r\n\r\n for input_str in correct_responses:\r\n result = calc.evaluator({}, {}, input_str)\r\n fail_msg = \"Expected '{0}' to equal {1}\".format(\r\n input_str, answer\r\n )\r\n self.assertEqual(answer, result, msg=fail_msg)\r\n\r\n for input_str in incorrect_responses:\r\n result = calc.evaluator({}, {}, input_str)\r\n fail_msg = \"Expected '{0}' to not equal {1}\".format(\r\n input_str, answer\r\n )\r\n self.assertNotEqual(answer, result, msg=fail_msg)", "def question(func):\n return FillInTheBlank(_text_from_func(func), correct=Answer(repr(func()), is_code=True), is_code=True)", "def correctAnswer(randomNumberOne, randomNumberTwo, problemType):\n if problemType == \"*\":\n return randomNumberOne * randomNumberTwo\n elif problemType == \"-\":\n return randomNumberOne - randomNumberTwo\n else:\n return randomNumberOne + randomNumberTwo", "def get_random_query() -> str:\n\n # Generate a list of random columns.\n columns = get_random_columns()\n arithmetic_exprs = [get_random_arithmetic_expr()\n for _ in range(random.randint(0, 2))]\n arithmetic_exprs = [\n f\"{expr[0]}{expr[1]}{expr[2]}\" for expr in arithmetic_exprs]\n columns.extend(arithmetic_exprs)\n columns = [f\"\\\"{column}\\\"\" for column in columns]\n\n # Generate a nested query?\n if get_random_bool():\n inner_q, new_columns = _get_random_query(columns, \"t\")\n q, _ = _get_random_query(new_columns, inner_q)\n else:\n q, _ = _get_random_query(columns, \"t\")\n\n return f\"{q};\"", "def challenge() : \n\treturn [random.randint(1,9) for i in range(5)]", "def get_chaser_answer(self, q):\n rand_num = random.randint(1, 4)\n if rand_num <= 3: # 75%\n return q.get_answer() # give right answer\n else: # 15% - give wrong answer\n options = [1, 2, 3, 4] # all option\n options.pop(q.get_answer()-1) # pop right option\n return options[random.randint(0, 2)] # return random wrong option", "def get_random_inspirational_quote(self):\n return random.choice(self.inspirational_quotes)", "def get_random_question(self):\n available_qs = self.available_qs\n if available_qs.exists():\n return random.choice(available_qs)", "def random(ctx, type=\"str\", nchars=\"\", special_chars=string.punctuation):\n\n pool_lookup = {\n \"str\": string.ascii_letters + string.digits + \"-_\",\n \"int\": string.digits,\n \"loweralpha\": string.ascii_lowercase,\n \"upperalpha\": string.ascii_uppercase,\n \"loweralphanum\": string.ascii_lowercase + string.digits,\n \"upperalphanum\": string.ascii_uppercase + string.digits,\n \"special\": string.ascii_letters + string.digits + special_chars,\n }\n\n default_nchars_lookup = {\n \"str\": 43,\n \"int\": 16,\n }\n\n # get pool of given type\n pool = pool_lookup.get(type, None)\n if not pool:\n raise RefError(\n \"{}: unknown random type used. Choose one of {}\".format(type, [key for key in pool_lookup])\n )\n\n # get default value for nchars if nchars is not specified\n if not nchars:\n nchars = default_nchars_lookup.get(type, 8)\n else:\n # check input for nchars\n try:\n nchars = int(nchars)\n except ValueError:\n raise RefError(f\"Ref error: eval_func: {nchars} cannot be converted into integer.\")\n\n # check if any special characters are specified without using type special\n if type != \"special\" and special_chars != string.punctuation:\n raise RefError(\n \"Ref error: eval_func: {} has no option to use special characters. Use type special instead, i.e. ||random:special:{}\".format(\n type, special_chars\n )\n )\n\n # check if pool is valid, eliminates duplicates\n allowed_pool = string.ascii_letters + string.digits + string.punctuation\n pool = \"\".join(set(pool).intersection(allowed_pool))\n\n # generate string based on given pool\n generated_str = \"\".join(secrets.choice(pool) for i in range(nchars))\n\n # set ctx.data to generated string\n ctx.data = generated_str", "def main_questions(money, grain, people):\n quest_buy = [Q1, Q2, Q3, Q6, Q7]\n question = random.choice(quest_buy)\n print(question)\n answer = input()\n while answer.isdigit() is False:\n print(INPUT_INT_VALUE)\n answer = input()\n answer = int(answer)\n if question == Q1:\n money = money - answer * 12\n elif question == Q2:\n money -= answer * 14\n elif question == Q3:\n money -= answer * 13\n elif question == Q6:\n money -= answer * 10\n elif question == Q7:\n money -= answer * 15\n grain += answer\n\n quest_sell = [Q4, Q5, Q8, Q9, Q10]\n question_2 = random.choice(quest_sell)\n print(question_2)\n answer = input()\n while answer.isdigit() is False:\n print(INPUT_INT_VALUE)\n answer = input()\n answer = int(answer)\n if question == Q4:\n money += answer * 7\n elif question == Q5:\n money += answer * 5\n elif question == Q8:\n money += answer * 6\n elif question == Q9:\n money += answer * 9\n elif question == Q10:\n money += 8\n grain -= answer\n\n print(DISTRIBUTION_OF_GRAIN)\n answer_3 = input()\n while answer_3.isdigit() is False:\n print(INPUT_INT_VALUE)\n answer_3 = input()\n answer_3 = int(answer)\n grain -= answer_3\n if grain / people > 90:\n people *= 1.1\n elif grain / people < 40:\n people *= 0.9\n return int(money), int(grain), int(people)", "def create_challenge():\n\treturn os.urandom(12)", "def random_conditional_quiz_selector():\n\n go_again = True\n while go_again:\n number = random.randint(1, 2)\n if number == 1:\n begin_conditionalpr_are_ere_quiz()\n if number == 2:\n begin_conditionalpr_ire_quiz()\n again = input(\"Continue? Y/N\\n\").lower()\n if again == \"n\":\n go_again = False", "def genQuestion(line):\r\n if type(line) is str: # If the passed variable is of type string.\r\n line = TextBlob(line) # Create object of type textblob.blob.TextBlob\r\n \r\n bucket = {} # Create an empty dictionary\r\n \r\n subject_list = []\r\n question_subject=\"\"\r\n answer_subject=\"\"\r\n for i,j in enumerate(line.tags): # line.tags are the parts-of-speach in English \r\n question_subject += j[0] + \" \"\r\n if (j[1] == \"NNP\" or j[1] == \"NNS\"): \r\n subject_list.append(j[0])\r\n if j[1] not in bucket:\r\n bucket[j[1]] = i # Add all tags to the dictionary or bucket variable\r\n \r\n if len(subject_list):\r\n random_subject_val = random.randint(0, len(subject_list)-1)\r\n question_subject = question_subject.replace(str(subject_list[random_subject_val]), \"______\")\r\n answer_subject = str(subject_list[random_subject_val])\r\n \r\n return question_subject, answer_subject", "def generate_answer(self, question):\n\n # Recognize intent of the question using `intent_recognizer`.\n # Don't forget to prepare question and calculate features for the question.\n \n prepared_question = text_prepare(question)\n features = self.tfidf_vectorizer.transform([prepared_question])\n intent = self.intent_recognizer.Main(question)\n #intent='gcs'\n # Chit-chat part: \n if intent == 'dialogue':\n \"\"\"\n # Pass question to chitchat_bot to generate a response.\n reply=self.college.Main(question)\n if reply !=\"Please refer GCS facebook page or ask you mentor for more info :)\":\n return reply\n else: \n \"\"\"\n reply=self.college.Main(question)\n if reply!=\"Please refer GCS facebook page or ask you mentor for more info :)\":\n return reply\n else:\n reply=self.programming.Main(question)\n if reply!=\"Please refer kammand prompt discord or ask you mentor for more info :)\":\n return reply\n else:\n response = str(self.chatbot.get_response(prepared_question))\n temp=np.random.choice(2,p=[0.5,0.5])\n times=np.random.choice([1,2,3,4],p=[0.5,0.3,0.1,0.1])\n if temp==0:\n print(\"EMOJI!!!!!\")\n response= response + times*(label_to_emoji(emojifyer.predict_emoji(model,response,word_to_index)).strip())\n return response\n elif intent==\"mandi\":\n reply=self.college.Main(question)\n return reply\n # Goal-oriented part:\n elif intent==\"stackoverflow\":\n tag = self.tag_classifier.predict(features)[0]\n reply = self.thread_ranker.get_best_thread(prepared_question, tag)\n return reply", "def evaluate_random_function(f, x, y, t=0):\n if f[0] == \"x\":\n return x\n elif f[0] == \"y\":\n return y\n elif f[0] == \"t\":\n return t\n elif f[0] == \"prod\": \n return evaluate_random_function(f[1], x, y, t)*evaluate_random_function(f[2], x, y, t)\n elif f[0] == \"avg\":\n return 0.5*(evaluate_random_function(f[1], x, y, t)+evaluate_random_function(f[2], x, y, t))\n elif f[0] == \"cos_pi\":\n return cos(pi*evaluate_random_function(f[1], x, y, t))\n elif f[0] == \"sin_pi\":\n return sin(pi*evaluate_random_function(f[1], x, y, t))\n elif f[0] == \"hypot\":\n first = evaluate_random_function(f[1], x, y, t)\n second = evaluate_random_function(f[1], x, y, t)\n tester = first*abs(first) + second*abs(second)\n if tester >= 0:\n return sqrt(first**2 + second**2)/sqrt(2)\n else:\n return -sqrt(first**2 + second**2)/sqrt(2)\n elif f[0] == \"pow\":\n val = evaluate_random_function(f[1], x, y, t)\n if val >= 0:\n return 1-val**val\n else:\n return -(1-abs(val)**abs(val))\n elif f[0] == \"add\":\n first = evaluate_random_function(f[1], x, y, t)\n second = evaluate_random_function(f[1], x, y, t)\n if first + second > 1:\n return (1 - (first+second) + 1)\n elif first + second < -1:\n return (-2 - (first+second))\n else:\n return (first + second)\n elif f[0] == \"cube\":\n return evaluate_random_function(f[1], x, y, t)**3", "def main():\n min_random = 10 #keeping constant for the min random number range\n max_random = 99 #keeping constant for the max random number range\n count = 0 #creating a counter variable to keep track of user's answers in a row\n\n\n while count != 3: #this loop will keep goin until user get 3 answers correct in a row\n num1 = random.randint(min_random, max_random) #generating a random number each new equations\n num2 = random.randint(min_random, max_random)\n\n print(\"What is \" + str(num1) + \"+\" + str(num2) + \"?\")\n user_input = int(input(\"Your answer is: \")) #takign the user's input and converting it into an integer\n\n total = num1 + num2 #keeping track of the actual answer to compare with the user's response", "def ask_and_evaluate(self):\n\n print self.question\n user_answer = raw_input(\"> \")\n\n # Evaluate answer, provide feedback and return True or False depending\n # on correctness\n if user_answer == self.correct_answer:\n print \"Correct.\"\n print\n return True\n else:\n print \"Incorrect. Correct answer: {}\".format(self.correct_answer)\n print\n return False", "def random_test(self):\r\n return 1" ]
[ "0.69674486", "0.6796805", "0.6784748", "0.6760564", "0.6284866", "0.62717825", "0.6146464", "0.6050245", "0.6044953", "0.6043534", "0.599811", "0.59578353", "0.5931196", "0.5915013", "0.58821046", "0.5855784", "0.5849916", "0.58499056", "0.58317935", "0.5807753", "0.5769087", "0.5761896", "0.5749238", "0.5735152", "0.57241094", "0.57230455", "0.56997216", "0.56897944", "0.56856966", "0.5671361" ]
0.70223653
0
Returns the full path to the test data directory
def test_data_dir(self): return os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data')
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_test_data_path():\n return os.path.abspath(os.path.join(os.path.dirname(__file__), \"data\") + os.path.sep)", "def data_dir():\n return os.path.join(os.path.dirname(_here), 'test', 'data')", "def data_dir():\n return os.path.join(os.path.dirname(__file__), 'test', 'data')", "def test_data_directory(test_directory):\n return os.path.join(test_directory, \"test_data\")", "def get_test_path():\n path, name = os.path.split(__file__)\n return os.path.join(path,\"..\", 'test-data')", "def data_dir():\n return os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data')", "def data_dir(uncover):\n return os.path.join(uncover, 'tests', 'test_data')", "def get_sample_data_dir():\n \n return resource_filename('cdat_lite.test.test_cdms', 'sample_data')", "def get_data_path():\n\n import rospkg\n rospack = rospkg.RosPack()\n return os.path.join(rospack.get_path('testing_tools'), 'data')", "def get_data_path():\n return os.getcwd() + \"/data/\"", "def data_dir():\n #data_path = os.path.dirname(intervene.__file__)\n #data_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'example_data')\n #print(data_path)\n return os.path.join(os.path.dirname(__file__), 'example_data')", "def get_data_dir():\n return Path(current_app.config[\"USER_DIR\"]) / \"data\"", "def getDataPath():\n\treturn \"..\" + os.sep + \"data\" + os.sep", "def __dir_test_data():\n if Util.__calculated_dir_test_data is None:\n if (os.path.basename(os.path.abspath(os.path.curdir))) == Util.__C_DIR_TESTS:\n Util.__calculated_dir_test_data = Util.__C_DIR_TEST_DATA\n else:\n Util.__calculated_dir_test_data = os.path.join(Util.__C_DIR_TESTS,\n Util.__C_DIR_TEST_DATA)\n return Util.__calculated_dir_test_data", "def data_dir():\n return _config.datadir", "def data_directory(self):\n\n return self.get_raw(\"data_directory\")", "def get_data_dir(self):\n return self.data_dir", "def data_dir(self) -> Path:\n return self._data_dir", "def get_data_path():\n\n # Get pathname absolute or relative.\n path = os.path.join(\n os.path.dirname(__file__), __malstor_data_directory__)\n\n abs_data_path = os.path.abspath(path)\n if not os.path.exists(abs_data_path):\n raise project_path_not_found\n\n return abs_data_path", "def get_data_path():\n\treturn _paths[_DATA_DIRECTORY_KEY]", "def get_data_dir(\n test_dir_name: str = 'tests', data_dir_name: str = 'data') -> str:\n path = ''\n\n # Get the current path and reduce to a list\n path_parts = os.path.abspath(__file__).split(os.path.sep)\n\n # Try to find the tests directory.\n # If not found, log an error and return an empty string\n try:\n tests_subdir = path_parts.index(test_dir_name)\n\n except ValueError:\n logging.error(\"Unable to determine test directory\")\n\n # If found, rebuild path up to the tests directory and add the data\n # subdirectory to the path\n else:\n tests_dir = os.path.sep.join(path_parts[:tests_subdir + 1])\n path = os.path.sep.join([tests_dir, data_dir_name])\n\n return path", "def get_data_dir():\n\n data_dir = Path(get_project_dir() / 'data')\n data_dir.mkdir(parents=True, exist_ok=True)\n return data_dir", "def _get_data_directory(self):\n\n return self.data_directory", "def get_test_file_path(self):\n xml_file_path_prefix = \"./tests/\"\n return xml_file_path_prefix + self.test_name + \"_data/\"", "def test_dir():\n return os.path.abspath(os.path.dirname(__file__))", "def GetTestData():\n return os.path.join(GetSrc(), 'chrome', 'test', 'data')", "def data_dir(self):\r\n return self._data_dir", "def data_dir(self):\n return self._data_dir", "def data_dir(self):\n return self._data_dir", "def datadir():\n return '../data/'" ]
[ "0.91113776", "0.90987366", "0.887621", "0.86290467", "0.8481252", "0.8396891", "0.831865", "0.826754", "0.8233042", "0.8229824", "0.8090345", "0.80200744", "0.80070865", "0.7992242", "0.7949754", "0.7906792", "0.7864156", "0.7812648", "0.7732339", "0.77273315", "0.7723905", "0.7701847", "0.76879716", "0.76648927", "0.7657418", "0.7632948", "0.76138383", "0.76123595", "0.76123595", "0.76066357" ]
0.92368877
0
Returns the full paath to the test task directory
def test_task_dir(self): return os.path.join(os.path.dirname(os.path.abspath(__file__)), 'tasks')
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_dir():\n return os.path.abspath(os.path.dirname(__file__))", "def get_test_path():\n path, name = os.path.split(__file__)\n return os.path.join(path,\"..\", 'test-data')", "def test():\n return os.path.dirname(__file__)", "def testnodes_path() -> str:\n return os.path.abspath(\n os.path.join(os.path.dirname(__file__), \"..\", \"test\", \"testnodes\")\n )", "def get_tests_directory() -> str:\n module_file_path = os.path.abspath(__file__)\n return os.path.dirname(module_file_path)", "def get_pytest():\n return path.join(TaskCreator.bin_dir, \"py.test\")", "def tests_dirpath():\n execdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))\n return os.path.join(execdir, \"tests\")", "def get_test_file_path(self):\n xml_file_path_prefix = \"./tests/\"\n return xml_file_path_prefix + self.test_name + \"_data/\"", "def get_test_data_path():\n return os.path.abspath(os.path.join(os.path.dirname(__file__), \"data\") + os.path.sep)", "def tests_path(self, version):\n base = self.version_path(version)\n return osp.normpath(osp.join(base, os.pardir, os.pardir,\n \"share\", \"aster\", \"tests\"))", "def get_test_filepath(filename):\n parent_dir = Path(__file__).parent\n return parent_dir / filename", "def test_root() -> Path:\n return TEST_ROOT", "def path_finder(cls, *args):\n safe_test_data = os.path.join(\n os.path.dirname(__file__),\n '../tasks/tests/data')\n safe_test_data = os.path.abspath(safe_test_data)\n return os.path.join(safe_test_data, *args)", "def get_path():\n return path.abspath(path.dirname(path.dirname(__file__)))", "def get_path() -> str:\n return os.path.dirname(os.path.realpath(__file__))", "def GetTaskOutputRelativeDir(cls, task):\n task = os.path.dirname(cls.TaskRelativeName(task))\n if not task: return ''\n\n parts = task.split(os.sep)\n res_parts = []\n for part in parts:\n priority_name = part.split('_', 1)\n res_parts += [priority_name[1]]\n return os.sep.join(res_parts)", "def test_data_dir(self):\n return os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data')", "def getTmpdir(self):\n pass", "def dir_tests():\n return abspath('tests')", "def _get_path(): # THIS IS JUST FOR GETTING THE FILE\n return os.path.dirname(os.path.abspath(__file__)) + '/'", "def test_get_working_directory():\n\n working_directory = application_services.get_working_directory()\n assert os.path.abspath('.') == working_directory", "def location(self):\n\n p = os.path.abspath(__file__)\n pathSP = os.path.split(p)\n return pathSP", "def return_testvideo_path():\r\n\tpath = '{}/Downloads/Test_videos/BigBuckBunny.mp4'.format(os.environ['USERPROFILE'] if os.name == 'nt' else os.environ['HOME'])\r\n\treturn os.path.abspath(path)", "def get_log_dir():\n base_dir = os.path.realpath(cfg.CONF.ruiner.log_dir.rstrip('/'))\n return os.path.join(base_dir, test_start_time_tag())", "def track_path(self, filename):\n return os.path.join(os.path.dirname(__file__), 'testdata', filename)", "def track_path(self, filename):\n return os.path.join(os.path.dirname(__file__), 'testdata', filename)", "def track_path(self, filename):\n return os.path.join(os.path.dirname(__file__), 'testdata', filename)", "def get_test_path(bname, test_dir=TEST_CASE_DIR):\n return abspath(join(test_dir, bname))", "def getmp_rootdir():\n return os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))", "def output_path():\n folder = path.join(path.curdir, \"stages\")\n folder = path.abspath(folder)\n return ensure_path(folder)" ]
[ "0.7674695", "0.7589369", "0.71511745", "0.7132654", "0.7118378", "0.70436317", "0.7012108", "0.69527984", "0.6950599", "0.6936121", "0.689541", "0.6856171", "0.6844601", "0.68313617", "0.67896086", "0.67874813", "0.6763031", "0.67000246", "0.66965204", "0.66603136", "0.66419643", "0.6603825", "0.6585512", "0.6577892", "0.6557989", "0.6557989", "0.6557989", "0.65311044", "0.6508356", "0.6506255" ]
0.85292554
0
Abstract method for generating python toolboxes from test tasks.
def setup_toolbox(self, engine_name, task_name, toolbox_name): pass
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def generate_tasks(self, task):", "def main():\n\n parser = argparse.ArgumentParser(description=\"generateTestStubs\")\n\n parser.add_argument(\"taskFile\",\n help=\"Path for assignment file.\")\n\n args = parser.parse_args()\n\n if not os.path.exists(args.taskFile):\n print(\"Task file does not exist.\")\n sys.exit(1)\n\n taskMgr = EEWebLPProject()\n taskMgr.initLP()\n\n #taskMgr.listProjects()\n #taskMgr.loadTree([\"project_id=8008922\"])\n tasks = taskMgr.getTasks([\"project_id=6890048\"],parent_id=8008922)\n\n fileByAssignee = taskMgr.getTaskOwners(args.taskFile)\n taskMgr.updateTaskOwners(fileByAssignee,tasks)", "def create_analysis_tools(self):\r\n raise NotImplementedError()", "def create_task(testset_path):\n task_suite = unittest.TestSuite() # 测试套件\n testsets = load_testcases_by_path(testset_path)\n print('testsets ----> %s\\n' % testsets)\n for testset in testsets:\n print('testset ----> %s\\n' % testset)\n suite = create_suite(testset)", "def main():\n tbx = Toolbox()\n tool = FieldName()\n tool.execute(tool.getParameterInfo(), None)", "def task_generate_tasks():\n \n yield {\n 'basename': 'generate_tasks',\n 'name': None,\n # 'doc': 'docs for X',\n 'watch': ['trains/'],\n 'task_dep': ['create_folders'],\n }\n \n for root, dirs, files in os.walk('trains/',topdown=False):\n for f in files:\n #print(f)\n yield template_train_model(os.path.join(root,f))", "def test_generate_all_testing(self):\n pass", "def test_testutils():\n build()\n sh(\"%s psutil\\\\tests\\\\test_testutils.py\" % PYTHON)", "def create_additional_tasks(testcase):\n # No need to create progression task. It is automatically created by the cron\n # handler.\n task_creation.create_impact_task_if_needed(testcase)\n task_creation.create_regression_task_if_needed(testcase)\n task_creation.create_symbolize_task_if_needed(testcase)\n task_creation.create_variant_tasks_if_needed(testcase)", "def __init__(self):\n self.label = \"Python ToolBox\"\n self.alias = \"\"\n\n # List of tool classes associated with this toolbox\n self.tools = [Tool]", "def prepare_run(self, **kwargs):\n assert self.cloud\n LOGGER.debug('Validating run tests...')\n for test in kwargs.get('tests', self.stests):\n if test in self.stests:\n self.tests.append(test)\n else:\n raise Exception(f\"Test name '{test}' is invalid\")\n\n if not os.path.exists(self.task_dir):\n os.makedirs(self.task_dir)\n\n task = os.path.join(self.rally_dir, 'task.yaml')\n if not os.path.exists(task):\n LOGGER.error(\"Task file '%s' does not exist.\", task)\n raise Exception(f\"Task file '{task}' does not exist.\")\n self.task_file = os.path.join(self.task_dir, 'task.yaml')\n shutil.copyfile(task, self.task_file)\n\n task_macro = os.path.join(self.rally_dir, 'macro')\n if not os.path.exists(task_macro):\n LOGGER.error(\"Task macro dir '%s' does not exist.\", task_macro)\n raise Exception(f\"Task macro dir '{task_macro}' does not exist.\")\n macro_dir = os.path.join(self.task_dir, 'macro')\n if os.path.exists(macro_dir):\n shutil.rmtree(macro_dir)\n shutil.copytree(task_macro, macro_dir)\n\n self.update_keystone_default_role()\n self.compute_cnt = self.count_hypervisors()\n self.network_extensions = self.cloud.get_network_extensions()\n self.flavor_alt = self.create_flavor_alt()\n self.services = [service.name for service in\n functest_utils.list_services(self.cloud)]\n\n LOGGER.debug(\"flavor: %s\", self.flavor_alt)", "def __init__(self):\n self.label = \"Create\"\n self.alias = \"\"\n\n # List of tool classes associated with this toolbox\n if core.get_pass():\n self.tools = [Fbound, Roads, Diekdikisi]\n else:\n self.tools = []", "def makeTestProcessingTool(test_processing_tool_path, test_processing_factory_path):\r\n\r\n className = splitext(basename(test_processing_tool_path))[0]\r\n factory_name = splitext(basename(test_processing_factory_path))[0]\r\n\r\n with open(test_processing_tool_path, 'w') as f:\r\n f.write(\"\"\"\\\r\n'''\r\nTest processing tool class - should be deleted upon completion of test\r\n'''\r\n\r\n'''___Built-In Modules___'''\r\nimport sys\r\nfrom os.path import dirname\r\n\r\n'''___Third-Party Modules___'''\r\n\r\n'''___NPL Modules___'''\r\ndataProcessing_directory = dirname(dirname(dirname(dirname(__file__))))\r\nsys.path.append(dataProcessing_directory)\r\nfrom AbstractProcessingTool import AbstractProcessingTool\r\n\r\nsys.path.append(dirname(__file__))\r\nfrom %s import %s\r\n\r\n\r\nclass %s(AbstractProcessingTool):\r\n\r\n def setProcessingFactory(self, product_string):\r\n processingFactory = %s\r\n return processingFactory\r\n\r\n\r\nif __name__ == \"__main__\":\r\n pass\r\n\"\"\" % (factory_name, factory_name, className, factory_name))\r\n\r\n return 0", "def get_tools(cls):\n pass", "def __init__(self):\n \n self.label = \"ArcSDM Tools\"\n self.alias = \"ArcSDM\" \n\n # List of tool classes associated with this toolbox\n self.tools = [PartitionNNInputFiles, CombineNNOutputFiles, NeuralNetworkOutputFiles, NeuralNetworkInputFiles, \n CalculateWeightsTool,SiteReductionTool,CategoricalMembershipToool,\n CategoricalAndReclassTool, TOCFuzzificationTool, CalculateResponse, LogisticRegressionTool, Symbolize, \n ROCTool, AgterbergChengCITest, AreaFrequencyTable, GetSDMValues, GrandWofe]", "def task_gen(self):\n pass", "def gen_tasks(self):\n self.kw = {\n 'image_srcset_sizes': self.site.config['IMAGE_SRCSET_SIZES'],\n 'image_srcset_format': self.site.config['IMAGE_SRCSET_FORMAT'],\n 'extra_image_extensions': self.site.config['EXTRA_IMAGE_EXTENSIONS'],\n 'max_image_size': self.site.config['MAX_IMAGE_SIZE'],\n 'image_folders': self.site.config['IMAGE_FOLDERS'],\n 'output_folder': self.site.config['OUTPUT_FOLDER'],\n 'filters': self.site.config['FILTERS'],\n 'preserve_exif_data': self.site.config['PRESERVE_EXIF_DATA'],\n 'exif_whitelist': self.site.config['EXIF_WHITELIST'],\n 'preserve_icc_profiles': self.site.config['PRESERVE_ICC_PROFILES'],\n }\n\n self.image_ext_list = self.image_ext_list_builtin\n self.image_ext_list.extend(self.site.config.get('EXTRA_IMAGE_EXTENSIONS', []))\n\n yield self.group_task()\n for src in self.kw['image_folders']:\n dst = self.kw['output_folder']\n filters = self.kw['filters']\n real_dst = os.path.join(dst, self.kw['image_folders'][src])\n for task in self.process_tree(src, real_dst):\n task['basename'] = self.name\n task['uptodate'] = [utils.config_changed(self.kw)]\n yield utils.apply_filters(task, filters)", "def installTools(self, out):\r\n # Check that the tool has not been added using its id\r\n if not hasattr(self, 'selenium_ft_tool'):\r\n addTool = self.manage_addProduct['Selenium'].manage_addTool\r\n # Add the tool by its meta_type\r\n addTool('Selenium Functional Test Tool')\r\n out.write('Successfully added Selenium Functional Test Tool.\\n')", "def __init__(self):\n self.label = \"Toolbox\"\n self.alias = \"\"\n\n # List of tool classes associated with this toolbox\n self.tools = [FilesWithin, UpdateAiracInfo, CalculatePolygonRotationUTM33, CalculatePolygonRotationLCC10E, SetLayoutsNorAirac, SetLayoutsSweAirac, SetLayoutsFinDnkAirac, Export330charts]", "def __init__(self):\r\n\t\tself.label = \"Toolbox\"\r\n\t\tself.alias = \"\"\r\n\r\n\t\t# List of tool classes associated with this toolbox\r\n\t\tself.tools = [LinkedDataSpatialQuery, LinkedDataPropertyEnrich, MergeBatchNoFunctionalProperty, MergeSingleNoFunctionalProperty, LocationPropertyPath, RelFinder]", "def _generate_examples(self, folders, split):\n raise NotImplementedError(\"TODO\")", "def task_test():\n return {\n 'actions': ['py.test tests/'],\n }", "def test_quick_build(self):\n pass", "def make_all():\n\n if not MASTER.exists():\n os.makedirs(MASTER)\n members = inspect.getmembers(sys.modules[__name__])\n members = [f for f in members if 'test_' in f[0]]\n for member in members:\n print('Running %s...' % member[0], end='')\n member[1](master=True)\n print('done!')", "def make_all():\n\n if not MASTER.exists():\n os.makedirs(MASTER)\n members = inspect.getmembers(sys.modules[__name__])\n members = [f for f in members if 'test_' in f[0]]\n for member in members:\n print('Running %s...' % member[0], end='')\n member[1](master=True)\n print('done!')", "def task_test(argv):\n run_tests(\"python2\", argv)\n run_tests(\"python3\", argv)", "def task_generate_virtual_samples():\n metadata_files = Path(__file__).parent.glob('*_meta.yaml')\n data_files = Path(__file__).parent.glob('*_data.yaml')\n\n script = Path(__file__).parents[0] / \"virtual_experiment.py\"\n\n return {\n \"actions\": [f\"{PYTHON_EXE} {script}\"],\n \"file_dep\": [script, *metadata_files],\n \"verbosity\": 2, # show stdout\n \"targets\": [*data_files],\n \"setup\": [\"generate_virtual_metadata\"],\n \"clean\": [clean_targets]\n }", "def register_other_tools(self):\n self.add_tool(SaveAsTool)\n self.add_tool(CopyToClipboardTool)\n self.add_tool(PrintTool)\n self.add_tool(HelpTool)", "def create_task():", "def test_explant(install_test_files, data_dir):\n with make_workdir() as workdir:\n cl = [\"bcbio_nextgen.py\",\n get_post_process_yaml(data_dir, workdir),\n os.path.join(data_dir, os.pardir, \"1_explant\"),\n os.path.join(data_dir, \"run_info-explant.yaml\")]\n subprocess.check_call(cl)" ]
[ "0.66955596", "0.6265931", "0.62322456", "0.618248", "0.6164758", "0.61037296", "0.6079226", "0.6002927", "0.59454316", "0.5785487", "0.5765015", "0.57604563", "0.5711359", "0.5682157", "0.56809783", "0.56793827", "0.56743544", "0.5657822", "0.5649914", "0.5636607", "0.5615363", "0.5608671", "0.55500525", "0.5540303", "0.5540303", "0.55376434", "0.5495772", "0.5484125", "0.5462426", "0.54587936" ]
0.73740774
0
Removes the toolbox file from disk
def remove_toolbox(self, toolbox_file): toolbox_file = os.path.splitext(toolbox_file)[0] for tb_file in glob.glob(toolbox_file + '.*'): os.remove(tb_file)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _remove(self):\n self._system.remove(self.get_install_path())\n self._system.remove(self._source_path)", "def cleanUp(self, f):\n os.system('rm ' + f)", "def cleanUp(self):\n import evoware.fileutil as F\n F.tryRemove(self.f_project, verbose=(self.VERBOSITY>1), tree=1)", "def remove(self):\n self.remove_file()", "def clean(self):\n os.remove(\"temp.py\") # Delete the file \"temp.py\", to free up disk space", "def cleanup_file(path_to_file):\n print \"Removing generated file: %s\" % path_to_file\n os.remove(path_to_file)", "def remove():\n run('pew rm {0}'.format(package_name()))", "def cleanup_file(name: str):\n if os.path.exists(name) and os.path.isfile(name): # h5\n os.remove(name)\n elif os.path.exists(name) and os.path.isdir(name): # tf\n shutil.rmtree(name)", "def unload(self):\n\n #print \"** UNLOAD TFB_Tools3\"\n \n for action in self.actions:\n self.iface.removePluginVectorMenu(\n self.tr(u'&TFB_Tools3'),\n action)\n self.iface.removeToolBarIcon(action)\n # remove the toolbar\n del self.toolbar\n\n # self.writeDefaultPath()", "def remove(self): \n self.doRoot(self.removeDir)\n settings.getChanged('mosh.resourceReplacer.applied').remove(self.file)", "def clean(self):\n actual_output_file = path.splitext(self.source_name)[0] + \".actual\"\n if path.exists(self.binary_name):\n os.unlink(self.binary_name)\n if path.exists(actual_output_file):\n os.unlink(actual_output_file)", "def cleanup(self):\n if os.path.exists(self.tgzfile):\n os.remove(self.tgzfile)\n\n if os.path.exists(self.dirname):\n shutil.rmtree(self.dirname)", "def clean(self):\n os.remove(self.apk_path)", "def delete_file(self):\n os.remove(self.id+\"-input.txt\")\n if(self.lang == \"PYTHON\"):\n os.remove(self.id+\".py\")\n elif(self.lang == \"C\"):\n os.remove(self.id+\".c\")\n if(self.status == 1):\n os.remove(self.id+\"_c\")\n elif(self.lang == 'CPP'):\n os.remove(self.id+\".cpp\")\n if(self.status == 1):\n os.remove(self.id+\"_cpp\")\n elif(self.lang == 'JAVA'):\n os.remove(self.id+\".java\")\n if(self.status == 1):\n os.remove(self.id+\"_java\") \n elif(self.lang == \"JS\"):\n os.remove(self.id+\".js\")\n # if(self.status == 1):\n # os.remove(self.id+\"_js\")s", "def _removeFile(self, filename):\n try:\n #delete the output file\n os.remove(filename)\n except:\n #print (\"Failed to remove the file: \" + filename)\n pass", "def remove_docker_compose_file():\n os.remove(DOCKER_COMPOSE_FILE)", "def tearDown(self):\n try:\n remove(\"file.json\")\n except:\n pass", "def __del__(self):\n shutil.rmtree(self.epub_dir)", "def test_remove(self):\n test_file = os.path.join(self._system.get_temporary_path(), \"nusoft.test\")\n with open(test_file, 'a'):\n os.utime(test_file, None)\n self.assertTrue(os.path.exists(test_file))\n self._system.remove(test_file)\n self.assertFalse(os.path.exists(test_file))", "def delete(self):\n if os.path.isfile(TESTS_PATH + \"/\" + self.name):\n os.remove(TESTS_PATH + \"/\" + self.name)", "def tearDown(self):\n if os.path.exists(\"file.json\"):\n os.remove(\"file.json\")", "def tearDown(self):\n if os.path.exists(\"file.json\"):\n os.remove(\"file.json\")", "def CleanUp(self, path):\n try:\n if os.path.exists(path):\n os.remove(path)\n except (OSError, IOError) as e:\n logging.info(\"Failed to remove temporary file %s. Err: %s\", path, e)", "def tearDown(self):\n if os.path.exists('file.json'):\n os.remove(\"file.json\")", "def cleanup(self):\n if os.path.exists(f\"{self.save_path}{self.name}\"):\n shutil.rmtree(f\"{self.save_path}{self.name}\")", "def teardown(self):\n folder = os.path.join(expanduser('~'), '.drupdates', 'plugins')\n if os.path.isdir(folder):\n shutil.rmtree(folder)", "def tearDown(self):\n os.remove(self._file)", "def _clean_workdir(self):\n\t\ttoremove = [self._get_config_filepath(), self._get_params_filepath(), self._get_conv_filepath(), self._get_psf_filepath()]\n\t\tfor filepath in toremove:\n\t\t\tif os.path.exists(filepath):\t\n\t\t\t\tlogger.debug(\"Removing existing file %s...\" % (filepath))\n\t\t\t\tos.remove(filepath)", "def delete(self):\n if self.is_running:\n raise errors.ChalmersError(\"Can not remove running program (must be stopped)\")\n\n if path.isfile(self.definition_filename):\n os.unlink(self.definition_filename)\n\n if path.isfile(self.state_filename):\n os.unlink(self.state_filename)", "def remove_file(self):\n if self.file_exists:\n os.remove(self.file_name)" ]
[ "0.7031161", "0.7022566", "0.6924097", "0.689578", "0.68619317", "0.6856123", "0.68492395", "0.6763925", "0.6706439", "0.6685907", "0.66433996", "0.6638025", "0.65897125", "0.65406245", "0.65248865", "0.6520881", "0.64963454", "0.64885324", "0.6474568", "0.6458304", "0.6456034", "0.6456034", "0.6453291", "0.64419746", "0.64366674", "0.64310473", "0.64310366", "0.64292824", "0.64047015", "0.6403812" ]
0.7411929
0
Compares two text files. Removes whitespace, empty lines, and newline chars Empty string as a return value mean file are the same Open, read lines to string list, remove any newline chars, and filter out empty strings/lines.
def compare_text_files(self, file1, file2): text1 = list(filter(None, map(str.rstrip, open(file1, 'U').readlines()))) text2 = list(filter(None, map(str.rstrip, open(file2, 'U').readlines()))) return ''.join(difflib.unified_diff(text1, text2))
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def compare_contents(first, second):\n def strip_lines(lines):\n return [line.strip() + '\\n' for line in lines]\n\n try:\n with open(first, mode='r', encoding='utf_8') as file:\n content1 = strip_lines(file.readlines())\n except IOError:\n return 'failed to load first file: ' + first\n\n try:\n with open(second, mode='r', encoding='utf_8') as file:\n content2 = strip_lines(file.readlines())\n except IOError:\n return 'failed to load second file: ' + second\n\n diff = unified_diff(content1, content2,\n fromfile=first, tofile=second, lineterm='\\n')\n diff_content = ''.join(list(diff))\n if diff_content:\n return 'unexpected file differences\\n{}'.format(diff_content)\n\n return None", "def cmp_lines(path_1, path_2):\n l1 = l2 = ' '\n with open(path_1, 'U') as f1:\n with open(path_2, 'U') as f2:\n while l1 != '' and l2 != '':\n l1 = f1.readline()\n l2 = f2.readline()\n if l1 != l2:\n return False\n return True", "def compareFiles(baseFile_path, testTempFile):\n baseFile = open(baseFile_path, \"r\")\n testTempFile.seek(0) \n## only lines that have changed\n testoutput = []\n testTempFile.seek(0) \n baseFile.seek(0)\n m_base = baseFile.readlines()\n clean_base = []\n m_temp = testTempFile.readlines() \n clean_temp = []\n ignore_chars = '\\n\\t '\n for line in m_base:\n if not line == '\\n':\n clean_base += [line.strip(ignore_chars)]\n for line in m_temp: \n if not line == '\\n':\n clean_temp += [line.strip(ignore_chars)] \t\n for line in difflib.context_diff(clean_base, clean_temp):\n testoutput += [line] \n \n## all lines diff \n# diff = difflib.ndiff(baseFile.readlines(), testTempFile.readlines())\n# print ''.join(diff)\n baseFile.close() \n diffFile_name = baseFile_path.replace(\"_Base.output\",\".diff\")\n diffFile = open(diffFile_name, \"w\")\n \n if len(testoutput) > 1:\n for line in difflib.context_diff(m_base, m_temp):\n print line\n diffFile.write(line)\n diffFile.close() \n assert ( len(testoutput) == 1 )", "def text_files_equal(path_a: pathlib.Path, path_b: pathlib.Path) -> bool:\n try:\n with open(path_a, 'r') as file_a:\n with open(path_b, 'r') as file_b:\n lines_a = file_a.readlines()\n lines_b = file_b.readlines()\n nlines = len(lines_a)\n if nlines != len(lines_b):\n logger.info(f'n lines differ: {len(lines_a)} vs. {len(lines_b)}')\n return False\n for ii in range(nlines):\n if lines_a[ii].rstrip('\\r\\n') != lines_b[ii].rstrip('\\r\\n'):\n logger.info('lines differ:')\n logger.info(lines_a[ii])\n logger.info(lines_b[ii])\n return False\n except Exception:\n return False\n return True", "def compare(text1, text2):\n diff = difflib.ndiff(text1.splitlines(True), text2.splitlines(True))\n return '\\n' + '\\n'.join(diff)", "def cmp(f1, f2):\n with open(f1) as f1, open(f2) as f2:\n return f1.read() == f2.read()", "def _compare_texts(self, text_a, text_b):\n\n text_ref_a = {\n 'author' : text_a['author'],\n 'language' : text_a['language'],\n 'work' : text_a['title']\n }\n text_ref_b = {\n 'author' : text_b['author'],\n 'language' : text_b['language'],\n 'work' : text_b['title']\n }\n\n print(\" -- comparing\", text_a['author'], text_a['title'], \"to\", text_b['author'], text_b['title'])\n\n # Instantiate new TextReuse with metadata about both texts being compared\n t = TextReuse(text_ref_a, text_ref_b, sanitize_input=True)\n\n # Create comparisons from both texts\n comparisons = t.compare_sliding_window(text_a['text'], text_b['text'])\n\n # Save the comparisons to the self.comparisons_dbname database\n self._save_comparisons(comparisons)\n\n return", "def merge(left, right):\n with open('numbers.txt', 'a+') as sorted_numbers, open('numbers.txt', 'r+') as f, open('numbers.txt', 'r+') as f_2:\n\n files = [f, f_2]\n files[0].seek(left.tell())\n files[1].seek(right.tell())\n\n strings = ['', '']\n\n sym1 = files[0].read(1)\n sym2 = files[1].read(1)\n symbols = [sym1, sym2]\n\n while True:\n\n while symbols[0] != ' ' and symbols[0] != '\\n':\n strings[0] += symbols[0]\n symbols[0] = files[0].read(1)\n\n while symbols[1] != ' ' and symbols[1] != '\\n':\n strings[1] += symbols[1]\n symbols[1] = files[1].read(1)\n\n if int(strings[0]) <= int(strings[1]):\n index = 0\n else:\n index = 1\n\n strings[index] += ' '\n sorted_numbers.write(strings[index])\n strings[index] = ''\n\n if symbols[index] != '\\n':\n symbols[index] = files[index].read(1)\n else:\n sorted_numbers.write(strings[1 - index])\n while symbols[1 - index] != '\\n':\n sorted_numbers.write(symbols[1 - index])\n symbols[1 - index] = files[1 - index].read(1)\n\n sorted_numbers.write(symbols[1 - index])\n symbols[1 - index] = files[1 - index].read(1)\n break\n\n files[0].readline()\n files[1].readline()\n return files[0].tell(), files[1].tell()", "def compare_files(fp1, fp2):\n\n line1 = fp1.readline()\n line2 = fp2.readline()\n\n while line1 and line2:\n if line1.startswith('#') and line2.startswith('#'):\n pass\n elif not line1 == line2:\n return False\n \n line1 = fp1.readline()\n line2 = fp2.readline()\n\n if line1 or line2:\n return False\n\n return True", "def lines(a, b):\n # Turn split versions of both files into sets to remove duplicates\n # Split Lines used to automatically split at the end of a line. No need for \"\\n\" this way\n a1 = set(a.splitlines())\n b1 = set(b.splitlines())\n\n return a1 & b1", "def __CompareText1(self, s1, s2,result):\n # lines with tag that are excluded by hand (by the user) \n s0_excluded=list()\n for l0 in self.excluded_lines.splitlines():\n s0_excluded.append(l0.strip()) \n\n s1_filtered=list()\n s2_filtered=list() \n for l1 in s1.splitlines(): \n if l1.__contains__(self.stdout_tag): \n check=0\n for k in s0_excluded: \n if l1.__contains__(k): check=check+1 \n if check==0: s1_filtered.append(l1.strip())\n for l2 in s2.splitlines(): \n if l2.__contains__(self.stdout_tag): \n check=0\n for k in s0_excluded: \n if l2.__contains__(k): check=check+1 \n if check==0: s2_filtered.append(l2.strip())\n # some debug: shows the lines which will be compared \n mm=''\n nTot=0\n nDif=0\n nMis=0\n for l in range(max(len(s1_filtered),len(s2_filtered))): \n nTot=nTot+1\n if ( l>len(s1_filtered)-1 ): # ref[l] exists but log[l] does not\n nMis=nMis+1\n if ( nMis<=5 ) : # print only the first 5 missing lines\n mm=mm+'\\n%5i'%l\n if ( nMis<5 ) :\n mm=mm+'-> log: ...MISSING('+repr(nMis)+')...'+'\\n' \n else:\n mm=mm+'-> log: ...MISSING(5)... SKIP THE REST'+'\\n' \n if(l<=len(s2_filtered)-1):\n mm=mm+' ref: '+s2_filtered[l]+'\\n'\n else:\n mm=mm+' ref: '+'\\n'\n elif( l>len(s2_filtered)-1 or # log[l] exists but ref[l] does not\n s1_filtered[l] != s2_filtered[l] ): # log[l] != ref[l]\n nDif=nDif+1\n mm=mm+'\\n%5i'%l\n mm=mm+'-> log: '+s1_filtered[l]+'\\n'\n if(l<=len(s2_filtered)-1):\n mm=mm+' ref: '+s2_filtered[l]+'\\n' \n else:\n mm=mm+' ref: '+'\\n' \n if(nDif>0 or nMis>0): mm=mm+'\\nSummary: '+repr(nDif)+' lines differ and '+repr(nMis)+' are missing out of '+repr(nTot)+' lines\\n'\n result[\"ExecTest.stdout_VS_expected_stdout\"] = result.Quote(mm)\n logger.debug('ExecTestBase2:__CompareTest1: '+mm) \n # Comparision of filtered sets \n # - filtered sets should have the same length: if this is not the \n # case the test will stop here \n if not(len(s1_filtered)==len(s2_filtered)): \n self.causes.append(' Different number of tagged lines to compare \\n'+\\\n 'in the stdout and ref_stdout')\n return False \n # Scan of the s1 and ref_s1=s2 looking for the '=' \n s1_filtered_equals=list()\n s2_filtered_equals=list() \n for i in range(len(s1_filtered)):\n if s1_filtered[i].__contains__('='):\n s1_filtered_equals.append(s1_filtered[i].replace(\\\n self.stdout_tag,'').strip())\n if s2_filtered[i].__contains__('='):\n s2_filtered_equals.append(s2_filtered[i].replace(\\\n self.stdout_tag,'').strip()) \n # - in case there is not '=' the strings have to be the same \n if(not(s1_filtered[i].__contains__('=')) and \n s2_filtered[i].__contains__('=')): return False \n if(not(s1_filtered[i].__contains__('=')) and \n not(s2_filtered[i].__contains__('=')) and \n not(s1_filtered[i]==s2_filtered[i])): return False \n\n # Analysis of lines with '='\n fail_cond=True \n logger.debug('ExecTestBase2:__CompareTest1: # lines with = is '+\\\n repr(len(s1_filtered_equals))) \n for i in range(len(s1_filtered_equals)):\n s1_split_list=s1_filtered_equals[i].split('=')\n s2_split_list=s2_filtered_equals[i].split('=')\n logger.debug('ExecTestBase2:__CompareTest1: right side of = for '+\\\n repr(i)+' are '+s1_split_list[1]+' '+s2_split_list[1])\n # - No local tolerance marked with '+-' in the s2\n if not(s2_split_list[1].__contains__('+-')):\n try: # integer and float to float\n s1_split_list_1=float(s1_split_list[1].strip())\n s2_split_list_1=float(s2_split_list[1].strip())\n # - comparison with global tolerance (if any) \n if(s1_split_list_1!=0.): \n if(not(s1_split_list[0]==s2_split_list[0]) or \n not((s1_split_list_1==s2_split_list_1) or \n ((s1_split_list_1<s2_split_list_1+\\\n s2_split_list_1*float(self.stdout_tol)/100) and \n (s1_split_list_1>s2_split_list_1-\n s2_split_list_1*float(self.stdout_tol)/100))) \n ): fail_cond=fail_cond and False \n else: # case = 0 \n if(not(s1_split_list[0]==s2_split_list[0]) or \n not((s1_split_list_1==s2_split_list_1) or \n ((s1_split_list_1<s2_split_list_1+\\\n float(self.stdout_tol)/100) and \n (s1_split_list_1>s2_split_list_1-\n float(self.stdout_tol)/100))) \n ): fail_cond=fail_cond and False \n logger.debug('ExecTestBase2:__CompareTest1: right side of = for '+\\\n repr(i)+' are '+repr(s1_split_list_1)+' '+\\\n repr(s2_split_list_1)+' with global tol (%) '+\\\n repr(self.stdout_tol)+' '+repr(fail_cond) )\n except: # strings\n s1_split_list[1]=s1_split_list[1].strip() \n s2_split_list[1]=s2_split_list[1].strip() \n logger.debug('ExecTestBase2:__CompareTest1: right side of = for '+\\\n repr(i)+' are '+s1_split_list[1]+' '+\\\n s2_split_list[1])\n if(not(s1_split_list[0]==s2_split_list[0]) or \n not(s1_split_list[1]==s2_split_list[1]) ): fail_cond=fail_cond and False \n else: \n # - comparison with local tolerance \n print 'mgallas, to be done local tolerance'\n return fail_cond\n\n for j in range(len(self.causes)):\n print 'mgallas causes '+causes[j]\n \n return True", "def compare_files_text(file1, file2, regex=\"\"):\n if regex:\n write_log(\"start finding regex : {0} ,it may spend times\".format(regex), True)\n result1 = find_regex(file1, regex)\n result2 = find_regex(file2, regex)\n compare_sid('\\n'.join(result1), '\\n'.join(result2))\n else:\n compare_sid(file1, file2)", "def approximateDiff(file_name_1, file_name_2, tolerance):\n\n def approximatelyEqual(x, y, tolerance):\n if x == y:\n return True\n\n try:\n if abs(float(x) - float(y)) < tolerance:\n return True\n except:\n return False\n\n file_1 = open(file_name_1, \"r\")\n file_2 = open(file_name_2, \"r\")\n lines_1 = file_1.readlines()\n lines_2 = file_2.readlines()\n difference = False\n any_difference = False\n\n diff_output = []\n\n # ==== Check file lengths ====\n # --------------------------------------------------------------------\n # A problem here will indicate that something is structurally wrong.\n # --------------------------------------------------------------------\n if not (len(lines_1) == len(lines_2)):\n diff_output.append(\"Files are of different length\")\n\n # ==== Check line by line ====\n # ----------------------------------------------------------------------\n # This is where numerical differences will be highlighted. Also, if\n # the files are comparable up to a certain point, this will show where\n # they begin to diverge.\n # ----------------------------------------------------------------------\n for i in range(min(len(lines_1), len(lines_2))):\n split_1 = lines_1[i].split()\n split_2 = lines_2[i].split()\n\n if len(split_1) == len(split_2):\n # -----------------------------------------------------------\n # If lines have the same number of elements, then check for\n # numerical differences.\n # -----------------------------------------------------------\n for j in range(len(split_1)):\n if not (approximatelyEqual(split_1[j], split_2[j], tolerance)):\n diff_output.append(\n \" Line \" + str(i + 1) + \", element \" + str(j + 1) + \" differs\"\n )\n diff_output.append(\" \" + file_name_1.rjust(40) + \": \" + split_1[j])\n diff_output.append(\" \" + file_name_2.rjust(40) + \": \" + split_2[j])\n else:\n # -----------------------------------------------------------\n # If lines have a different number of elements, then print\n # their contents.\n # -----------------------------------------------------------\n diff_output.append(\" Line \" + str(i + 1) + \": number of elements differs\")\n diff_output.append(\" \" + file_name_1.rjust(40) + \": \" + lines_1[i])\n diff_output.append(\" \" + file_name_2.rjust(40) + \": \" + lines_2[i])\n\n return diff_output", "def merge_files(file_one, file_two):\n\n merged_lines = []\n line1 = file_one.readline()\n line2 = file_two.readline()\n\n while line1 != '' and line2 != '':\n if line1 < line2:\n merged_lines.append(line1)\n line1 = file_one.readline()\n else:\n merged_lines.append(line2)\n line2 = file_two.readline()\n\n if file_one == '':\n merged_lines.append(line2)\n lastlines = file_two.readlines()\n else:\n merged_lines.append(line1)\n lastlines = file_one.readlines()\n \n merged_lines.extend(lastlines)\n\n return merged_lines", "def lines(a, b):\n\n same_lines = []\n\n # creating a list with all the lines in file1\n linesA = a.split(\"\\n\")\n linesA = [i.rstrip(\"\\r\") for i in linesA]\n\n # creating a list with all the lines in file2\n linesB = b.split(\"\\n\")\n linesB = [i.rstrip(\"\\r\") for i in linesB]\n\n for line in linesA:\n if line in linesB and line not in same_lines:\n same_lines.append(line)\n\n return same_lines", "def __compare_files(self, filename1, filename2):\n self.assertTrue(os.path.isfile(filename1))\n self.assertTrue(os.path.isfile(filename2))\n self.assertEqual(os.path.getsize(filename1), os.path.getsize(filename2))\n with open(filename1, \"rb\") as f1:\n with open(filename2, \"rb\") as f2:\n n_blocks = int(self.args.size) // self.max_block_size\n for i in range(n_blocks):\n self.assertEqual(f1.read(self.max_block_size), \\\n f2.read(self.max_block_size))\n remaining = int(self.args.size) % self.max_block_size\n if remaining > 0:\n self.assertEqual(f1.read(remaining), \\\n f2.read(remaining))", "def comparefiles(LHS, RHS):\n LHSlines = set([l.strip() for l in open(LHS).read().split(\"\\n\")])\n RHSlines = set([l.strip() for l in open(RHS).read().split(\"\\n\")])\n print(\"In {} not in {}\".format(LHS, RHS))\n for line in LHSlines - RHSlines:\n print(line)\n print(\"\\n\\nIn {} not in {}\".format(RHS, LHS))\n for line in RHSlines - LHSlines:\n print(line)", "def __CompareText(self, s1, s2):\n # The \"splitlines\" method works independently of the line ending\n # convention in use.\n return s1.splitlines() == s2.splitlines()", "def compare_contents(lhs, rhs):\n for filename in (lhs, rhs):\n if not os.path.exists(filename):\n return False\n\n with open(lhs, \"r\") as lhs_file, open(rhs, \"r\") as rhs_file:\n return lhs_file.read() == rhs_file.read()", "def compare(file1, file2):\n process = subprocess.Popen([PBWT_BIN, 'compare', file1, file2],\n stdout=subprocess.PIPE)\n process_results(str(process.communicate()[0]))", "def assert_all_lines_same(path_1, path_2):\n line1 = line2 = ' '\n linenum = 0\n with open(path_1, 'r') as file1, open(path_2, 'r') as file2:\n while line1 != '' and line2 != '':\n line1 = file1.readline()\n line2 = file2.readline()\n if line1 != line2:\n mess = \"\"\"files {} and {} differ on line {}\n \"{}\" !=\n \"{}\"\n \"\"\".format(path_1, path_2, linenum, line1, line2)\n raise AssertionError(mess)\n linenum += 1\n return None", "def html_file_diff(lhs, rhs):\n with open(lhs, encoding='utf-8') as lhs_file:\n lhs_text = lhs_file.read()\n with open(rhs, encoding='utf-8') as rhs_file:\n rhs_text = rhs_file.read()\n return html_diff(lhs, lhs_text, rhs, rhs_text)", "def cmpfile(file_left, file_right):\n nobv.visual_comparefile(file_left, file_right)", "def unified_diff(expected_text, actual_text, expected_filename,\n actual_filename):\n # The filenames show up in the diff output, make sure they're\n # raw bytes and not unicode, so that they don't trigger join()\n # trying to decode the input.\n if six.PY2:\n expected_filename = six.ensure_binary(expected_filename)\n actual_filename = six.ensure_binary(actual_filename)\n\n diff = difflib.unified_diff(expected_text.splitlines(True),\n actual_text.splitlines(True),\n expected_filename, actual_filename)\n return ''.join(_diff_fixup(diff))", "def find_unique_words(text1, text2):\n with open(text1) as file1:\n with open(text2) as file2:\n # Split the files in to a list of words\n words1 = remove_punctuation(file1.read()).split()\n words2 = remove_punctuation(file2.read()).split()\n\n # Create sets of unique words for each file\n unique_words1 = {*words1}\n unique_words2 = {*words2}\n\n # Make a set for the words they have in common\n common_words = set()\n\n for word in unique_words1:\n if word in unique_words2:\n common_words.add(word)\n\n # Remove common words from unique words list\n unique_words1 = unique_words1.difference(common_words)\n unique_words2 = unique_words2.difference(common_words)\n\n print(f\"{text1} contains these unique words: {unique_words1}\\n\")\n print(f\"{text2} contains these unique words: {unique_words2}\")", "def compare(file1, file2):\n\tfrom os.path import exists\n\tresult = False\n\t\n\tfile1 = adaptPath(file1)\n\tfile2 = adaptPath(file2)\n\t\n\t# If two files existing\n\tif exists(file1) and exists(file2):\n\t\t# If the date and size equal\n\t\tif getFileSize(file1) == getFileSize(file2):\n\t\t\ttry:\n\t\t\t\t# Read the content of first file\n\t\t\t\tcontent1 = open(file1, \"rb\").read()\n\t\t\t\ttry:\n\t\t\t\t\t# Read the content of second file\n\t\t\t\t\tcontent2 = open(file2, \"rb\").read()\n\t\t\t\t\t# If content differs\n\t\t\t\t\tif content1 == content2:\n\t\t\t\t\t\tresult = True\n\t\t\t\texcept IOError:\n\t\t\t\t\tpass\n\t\t\texcept IOError:\n\t\t\t\tpass\n\treturn result", "def merge(fileHandle1, fileHandle2, outputFileHandle):\n line2 = fileHandle2.readline()\n for line1 in fileHandle1.readlines():\n while line2 != '' and line2 <= line1:\n outputFileHandle.write(line2)\n line2 = fileHandle2.readline()\n outputFileHandle.write(line1)\n while line2 != '':\n outputFileHandle.write(line2)\n line2 = fileHandle2.readline()", "def shared_words_from_filenames(filename1, filename2):\r\n\r\n \"\"\"\r\n filename1 = tokenize(text1)\r\n filename2 = tokenize(text2)\r\n\r\n list3 = set(filename1) & set(filename2)\r\n\r\n return list3\r\n\r\n \"\"\"\r\n with open(filename1, encoding=\"utf8\") as f1, open(filename2, encoding=\"utf8\") as f2:\r\n\r\n wordsFile1 = [];\r\n wordsFile2 = [];\r\n result = [];\r\n\r\n lines = [line.strip() for line in f1] # create a set of words from file 1\r\n for line in lines:\r\n tokenizedline = tokenize(line.replace('\\ufeff', ''));\r\n for word in tokenizedline:\r\n wordsFile1.append(word);\r\n\r\n lines = [line.strip() for line in f2] # create a set of words from file 1\r\n for line in lines:\r\n tokenizedline = tokenize(line.replace('\\ufeff', ''));\r\n for word in tokenizedline:\r\n wordsFile2.append(word);\r\n\r\n # now loop over each line of other file\r\n\r\n for word in wordsFile1:\r\n if word in wordsFile2 and word != ' ': # if word in File 1 is found in File 2 then print it\r\n result.append(word)\r\n\r\n return result", "def compare_output(file1, file2):\n output = subprocess.getoutput(f\"diff -u -b {file1} {file2} | sed -n '12d;/^[-+]/p'\")\n\n if not output.strip():\n name = file1.rsplit('/', 1)[-1]\n print('Equivalent:', name)\n else:\n print(output)", "def _compare_files(self, first_file, second_file):\n\n self.log.info('-' * 80)\n self.log.info('Compare files')\n\n code, out = cmd_exec(['cmp', str(first_file), str(second_file)], shell=False, log=self.log)\n if code:\n self.log.warning('md5 checksum IS NOT SAME with ffmpeg sw decode')\n self.log.warning(out)\n return False\n\n self.log.info('md5 checksum IS SAME with ffmpeg sw decode')\n return True" ]
[ "0.7229945", "0.7133003", "0.65655166", "0.653714", "0.651467", "0.64735854", "0.64228237", "0.6375053", "0.6353911", "0.6302926", "0.62963974", "0.6286208", "0.62219095", "0.62118894", "0.62079155", "0.61327523", "0.6097942", "0.60494936", "0.6049022", "0.599863", "0.5989535", "0.5969712", "0.5904526", "0.5903049", "0.58638626", "0.5856607", "0.58199275", "0.579711", "0.5796695", "0.5747862" ]
0.7781031
0
Override the default arcpy workspace and scratch workspace
def setup_workspace(self, workspace_dir): if not os.path.isdir(workspace_dir): os.mkdir(workspace_dir) arcpy.env.workspace = workspace_dir scratch_workspace = os.path.join(workspace_dir, 'scratch') if not os.path.isdir(scratch_workspace): os.mkdir(scratch_workspace) arcpy.env.scratchWorkspace = scratch_workspace
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def addWorkspace(self, dryrun):\n pass", "def PrepareWorkspace():\n \n # define expected file paths for file gdb folder, fgdb, taxi feature class \n fgdb_folder = constants.fgdb_folder\n fgdb_name = constants.taxi_fgdb_name\n file_gdb = os.path.join(fgdb_folder, fgdb_name)\n taxi_feature_class_name = \"TaxiLocations\"\n taxi_feature_class = os.path.join(file_gdb, taxi_feature_class_name)\n \n out_coordinate_system = arcpy.SpatialReference('WGS 1984') # define output spatial reference\n \n if not os.path.exists(fgdb_folder): # if file gdb folder has not been created\n os.mkdir(fgdb_folder) # create the folder\n if not arcpy.Exists(file_gdb): # if file gdb has not been created\n arcpy.CreateFileGDB_management(fgdb_folder, fgdb_name) # create the file gdb\n \n if not arcpy.Exists(taxi_feature_class): # if the taxi feature class does not exist\n # create the point feature class in WGS84 spatial reference\n arcpy.CreateFeatureclass_management(file_gdb, \n taxi_feature_class_name, \n \"Point\", \n spatial_reference=out_coordinate_system) # create a point feature class with defined coordinate system\n \n arcpy.TruncateTable_management(taxi_feature_class) # delete existing features in the feature class\n \n return file_gdb, taxi_feature_class # return fgdb and feature class path to main\n \n \n # %%", "def set_up_workspace():\n # Avoid Error #15: Initializing libiomp5.dylib, but found libiomp5.dylib already initialized.\n # https://stackoverflow.com/questions/53014306/error-15-initializing-libiomp5-dylib-but-found-libiomp5-dylib-already-initial\n os.environ['KMP_DUPLICATE_LIB_OK'] = 'True'\n\n # Magic command for inline plotting\n # %matplotlib inline\n # %config InlineBackend.figure_format = 'retina'", "def init_workspace(ocp):\n\n workspace = dict()\n workspace['independent_var'] = ocp.get_independent()['symbol']\n workspace['independent_var_units'] = ocp.get_independent()['unit']\n workspace['states'] = [s['symbol'] for s in ocp.states()]\n workspace['states_rates'] = [s['eom'] for s in ocp.states()]\n workspace['states_units'] = [s['unit'] for s in ocp.states()]\n workspace['controls'] = [u['symbol'] for u in ocp.get_controls()]\n workspace['controls_units'] = [u['unit'] for u in ocp.get_controls()]\n workspace['constants'] = [k['symbol'] for k in ocp.get_constants()]\n workspace['constants_values'] = [k['value'] for k in ocp.get_constants()]\n workspace['constants_units'] = [k['unit'] for k in ocp.get_constants()]\n workspace['constants_of_motion'] = [k['symbol'] for k in ocp.constants_of_motion()]\n workspace['constants_of_motion_values'] = [k['function'] for k in ocp.constants_of_motion()]\n workspace['constants_of_motion_units'] = [k['unit'] for k in ocp.constants_of_motion()]\n workspace['symmetries'] = [k['function'] for k in ocp.get_symmetries()]\n workspace['parameters'] = [k['name'] for k in ocp.parameters()]\n workspace['parameters_units'] = [k['unit'] for k in ocp.parameters()]\n\n constraints = ocp.constraints()\n constraints['path'] = ocp.get_path_constraints()\n\n workspace['constraints'] = {c_type: [sympify(c_obj['function']) for c_obj in c_list]\n for c_type, c_list in constraints.items()}\n\n workspace['constraints_units'] = {c_type: [sympify(c_obj['unit']) for c_obj in c_list]\n for c_type, c_list in constraints.items()}\n\n workspace['constraints_lower'] = {c_type: [sympify(c_obj['lower']) for c_obj in c_list]\n for c_type, c_list in constraints.items() if c_type == 'path'}\n\n workspace['constraints_upper'] = {c_type: [sympify(c_obj['upper']) for c_obj in c_list]\n for c_type, c_list in constraints.items() if c_type == 'path'}\n\n workspace['constraints_activators'] = {c_type: [sympify(c_obj['activator']) for c_obj in c_list]\n for c_type, c_list in constraints.items() if c_type == 'path'}\n\n workspace['constraints_method'] = {c_type: [c_obj['method'] for c_obj in c_list]\n for c_type, c_list in constraints.items() if c_type == 'path'}\n\n if 'initial' not in workspace['constraints'].keys():\n workspace['constraints']['initial'] = []\n workspace['constraints_units']['initial'] = []\n\n if 'terminal' not in workspace['constraints'].keys():\n workspace['constraints']['terminal'] = []\n workspace['constraints_units']['terminal'] = []\n\n if 'path' not in workspace['constraints'].keys():\n workspace['constraints']['path'] = []\n workspace['constraints_units']['path'] = []\n workspace['constraints_lower']['path'] = []\n workspace['constraints_upper']['path'] = []\n\n workspace['path_constraints'] = [sympify(c_obj['function']) for c_obj in constraints.get('path', [])]\n workspace['switches'] = []\n workspace['switches_values'] = []\n workspace['switches_conditions'] = []\n workspace['switches_tolerance'] = []\n for q in ocp.get_switches():\n workspace['switches'] += [sympify(q['name'])]\n if isinstance(q['value'], list):\n workspace['switches_values'] += [[sympify(v) for v in q['value']]]\n main_condition = []\n for cond in q['conditions']:\n if not isinstance(cond, list):\n raise ValueError('Conditions for switches must be a list of lists')\n main_condition += [[sympify(v) for v in cond]]\n workspace['switches_conditions'] += [main_condition]\n workspace['switches_tolerance'] += [sympify(q['tolerance'])]\n else:\n workspace['switches_values'] += [sympify(q['value'])]\n workspace['switches_conditions'] += [None]\n workspace['switches_tolerance'] += [None]\n\n if ocp.get_initial_cost() is not None:\n workspace['initial_cost'] = ocp.get_initial_cost()['function']\n workspace['initial_cost_units'] = ocp.get_initial_cost()['unit']\n else:\n workspace['initial_cost'] = 0\n workspace['initial_cost_units'] = 1\n\n if ocp.get_path_cost() is not None:\n workspace['path_cost'] = ocp.get_path_cost()['function']\n workspace['path_cost_units'] = ocp.get_path_cost()['unit']\n else:\n workspace['path_cost'] = 0\n workspace['path_cost_units'] = 1\n\n if ocp.get_terminal_cost() is not None:\n workspace['terminal_cost'] = ocp.get_terminal_cost()['function']\n workspace['terminal_cost_units'] = ocp.get_terminal_cost()['unit']\n else:\n workspace['terminal_cost'] = 0\n workspace['terminal_cost_units'] = 1\n return workspace", "def test_default_isolated_workspace():\n rally = Rally(server=RALLY, user=RALLY_USER, password=RALLY_PSWD, server_ping=False, isolated_workspace=True)\n context1 = rally.contextHelper.currentContext()\n workspace = rally.getWorkspace()\n project = rally.getProject()\n context2 = rally.contextHelper.currentContext()\n assert context1 == context2\n assert context1.workspace == DEFAULT_WORKSPACE\n assert workspace.Name == DEFAULT_WORKSPACE\n assert context1.project == DEFAULT_PROJECT\n assert project.Name == DEFAULT_PROJECT\n url = makeResourceUrl(rally, 'Defect')\n #print(url)\n expected_workspace_clause = 'workspace=workspace/%s' % str(workspace.oid)\n assert expected_workspace_clause in url\n\n problem_text = 'No reset of of the Workspace is permitted when the isolated_workspace option is specified'\n with py.test.raises(Exception) as excinfo:\n rally.setWorkspace(ALTERNATE_WORKSPACE)\n actualErrVerbiage = excinfo.value.args[0] \n assert excinfo.value.__class__.__name__ == 'RallyRESTAPIError'\n assert actualErrVerbiage == problem_text", "def workspace(*args, active: bool=True, baseWorkspace: Union[AnyStr, bool]=\"\", create:\n AnyStr=\"\", directory: Union[AnyStr, bool]=\"\", expandName: Union[AnyStr, bool]=\"\",\n fileRule: Union[List[AnyStr, AnyStr], bool]=None, fileRuleEntry: Union[AnyStr,\n bool]=\"\", fileRuleList: bool=True, filter: bool=True, fullName: bool=True, list:\n bool=True, listFullWorkspaces: bool=True, listWorkspaces: bool=True,\n newWorkspace: bool=True, objectType: Union[List[AnyStr, AnyStr], bool]=None,\n objectTypeEntry: Union[AnyStr, bool]=\"\", objectTypeList: bool=True,\n openWorkspace: bool=True, projectPath: Union[AnyStr, bool]=\"\",\n removeFileRuleEntry: AnyStr=\"\", removeVariableEntry: AnyStr=\"\", renderType:\n Union[List[AnyStr, AnyStr], bool]=None, renderTypeEntry: Union[AnyStr, bool]=\"\",\n renderTypeList: bool=True, rootDirectory: bool=True, saveWorkspace: bool=True,\n shortName: bool=True, update: bool=True, updateAll: bool=True, variable:\n Union[List[AnyStr, AnyStr], bool]=None, variableEntry: Union[AnyStr, bool]=\"\",\n variableList: bool=True, q=True, query=True, **kwargs)->Union[AnyStr, Any]:\n pass", "def set_workspace(self):\n try:\n chdir(self._path_temp) # assure we stay in the workspace\n except FileNotFoundError:\n raise MissingContextError(\"Context does not exist!\") from None", "def main():\n\n # Script arguments... \n \"\"\" If running as standalone, hardcode theWorkspace and inFile \"\"\"\n theWorkspace = arcpy.GetParameterAsText(0)\n if not theWorkspace:\n theWorkspace = r\"d:\\_dataTest\"\n arcpy.env.workspace = theWorkspace\n arcpy.env.overwriteOutput = True\t\n\n inFile = arcpy.GetParameterAsText(1)\n if not inFile:\n inFile = \"updateMultipleSourcePaths.csv\"\n inFile = r\"\\\\dfg.alaska.local\\gis\\Anchorage\\GISStaff\\___gisStaffConnections\\RepairBrokenSrcAug242015.csv\"\n\n outWorkspace = arcpy.GetParameterAsText(2)\n if not outWorkspace:\n outWorkspace = os.path.join(theWorkspace, \"_repaired\")\n '''if not os.path.isdir(outWorkspace): \n os.makedirs(outWorkspace)\n myMsgs(\"created new directory {0} \\n\".format(outWorkspace))'''\n\n # Create .txt Report of what it thinks was fixed, tagged with YYYYMMDD_HHMM\n outFile = \"FixedReport\"\n fileDateTime = curFileDateTime()\n currentDate = curDate()\n outfileTXT = os.path.join(theWorkspace, outFile) + fileDateTime + \".txt\" \n myMsgs (outFile)\n reportFile = open(outfileTXT, 'w')\n myMsgs( \"File {0} is open? {1}\".format(outfileTXT, str(not reportFile.closed)))\n outText = \"Report for what it THINKS it repaired in {0}, on {1} \\n \".format(theWorkspace, currentDate)\n outText += \" Includes coverages (pts, poly, arc, anno), shapes, and FGDB data.\" + '\\n'\n outText += \"-----------------------------------------------------\" + '\\n' \n reportFile.write(outText)\t\n\n mxd = None\n outMXDName = \"none\"\n updatePath = []\n cvrList = [r\"\\arc\", r\"\\polygon\", r\"\\region\", r\"\\point\", r\"\\tic\" ]\n lstExtDatatype = [[\".shp\", \"SHAPEFILE_WORKSPACE\" ], [\".sde\",\"SDE_WORKSPACE\"], \n [\".mdb\", \"ACCESS_WORKSPACE\" ], [\".gdb\", \"FILEGDB_WORKSPACE\"], \n [\"cover\", \"ARCINFO_WORKSPACE\"]]\t\n cntMXD = 0\n cntFixed = 0\n cntTotalFixed = 0\n\n # makes sure the .csv file exists\n if arcpy.Exists(inFile):\n myMsgs (\"->Using {0} to repair paths.\\n==============================\".format(inFile))\n # walks thru the workspace to create list of files \n for root, dirs, files in os.walk(theWorkspace): \t\t\n for fileName in files:\n if root == outWorkspace: # don't process mxd's in the target directory\n pass\n else:\n fullPath = os.path.join(root, fileName)\n basename, extension = os.path.splitext(fileName)\n # Only process .mxd files\n if extension == \".mxd\":\n myMsgs(\"\\nReviewing MXD: {0}\".format(fullPath))\n reportFile.write(\"\\nReviewing MXD: {0}\".format(fullPath))\n mxd = arcpy.mapping.MapDocument(fullPath)\n dfs = arcpy.mapping.ListDataFrames(mxd)\n cntMXD += 1\n cntFixed = 0\n basename, extension = os.path.splitext(fileName)\n # New output mxd name....\n outMXDName = os.path.join(outWorkspace, (str(basename) + \".mxd\")) #\"_fix.mxd\"))\n # create list of the tables since they are handle differently\n theTables = arcpy.mapping.ListTableViews(mxd)\n # Loops thru dataframes so adding and deleting Services will work.\n for df in dfs:\n # Loops thru layers, checks for broken links and tries to repair\n lyrList = arcpy.mapping.ListLayers(mxd, \"\", df)\n for lyr in lyrList:\n if lyr.isBroken:\n if not lyr.supports(\"DATASOURCE\") and not lyr.isServiceLayer:\n myMsgs(\" ->Skipping {0} not a Service layer, and does not support DATASOURCE\".format(lyr.name))\n pass #continue\n elif not lyr.supports(\"DATASOURCE\") and lyr.isServiceLayer:\n myMsgs(\" -Broken Service: {0}\".format(lyr.name))\n else:\n myMsgs(\" -Broken: {0}\".format(lyr.dataSource))\n #myMsgs(\"layer is Group {0} or ServiceLayer {1}\".format(lyr.isGroupLayer, lyr.isServiceLayer))\n if (lyr.isGroupLayer or (\"Events\" in lyr.name)) and (not lyr.isServiceLayer): # Groups and Event FC skipped\n myMsgs(\" ...skipping group or event: {0}\".format(lyr.name))\n reportFile.write(\"\\n *skipping group or event: {0} \\n\".format(lyr.name))\n pass #break\n elif lyr.isServiceLayer: # services might have to be handle differently\n if lyr.supports(\"SERVICEPROPERTIES\"):\n for spType, spName in lyr.serviceProperties.iteritems():\n myMsgs(\" Service Properties: {0}: {1}\".format(spType, spName ))\n if spType == \"URL\": \n dataSource = str(spName)\n lyrType = (\"service_{}\".format(lyr.name))\n break\n myMsgs(\" ->this ia a service....using add and remove layer\")\n updatePath = findUpdatePath(inFile, dataSource, lyrType.strip().lower())\n newDSPath, newDSName = os.path.split(updatePath[0])\n if (\"service\" in updatePath[3]) and (\"service\" in updatePath[1]):\n insertLayer = arcpy.mapping.Layer(updatePath[0])\n print(\"dataframe: {0}\".format(df))\n arcpy.mapping.InsertLayer(df, lyr, insertLayer, \"AFTER\")\n arcpy.mapping.RemoveLayer(df, lyr)\n reportFile.write(\"\\n ->sees this as service....{0} \\n\".format(dataSource))\n # will still look at deleted version after insert, not the new version..\n # isBroken will give false info even if fixed, so \n # don't use myMsgs(\"Still broken? {0}\".format(lyr.isBroken)) \n else:\n myMsgs(\" --> a service layer but no SERVICE PROPERTIES\")\n elif lyr.supports(\"DATASOURCE\") and lyr.supports(\"DATASETNAME\"): \n # not a group, event or what it thinks is a service\n updatePath = findUpdatePath(inFile, lyr.dataSource, \"\")\n newDSPath, newDSName = os.path.split(updatePath[0])\n sameType = updatePath[2] \n for cvr in cvrList: #checks to see if the source layer is a coverage...must handle different\n if cvr in lyr.dataSource:\n sourceIsCoverage = True\n break\n else:\n sourceIsCoverage = False\n # updatePath[1] is False if there wasn't a match\n # so \"not update[1]\" means no match was found, and moves to next layer\t\t\t\t\t\t\t\t\n if not updatePath[1]: # if no match was found\n myMsgs(\" !! no match to: {0} \".format(lyr.dataSource))\n updateStatus = \"no match, not changed\" # used for message only\n pass\n elif updatePath[1].strip().lower() == \"drive\":\n myMsgs(\" skipping drive-letter matches for now: {0}\".format(lyr.dataSource))\n updateStatus = \"can only find drive match...look into it)\"\n pass\n elif updatePath[1].strip().lower() == \"_review\":\n myMsgs(\" no new source assigned yet for: {0}\".format(lyr.dataSource))\n updateStatus = (\"review and update {0}\".format(inFile))\n pass\n else: #if lyr.supports(\"DATASOURCE\") and lyr.supports(\"DATASETNAME\"):\n updateStatus = str(updatePath[0]) # used for message only\n if lyr in theTables:\n #myMsgs(\" thinks its a table....using findAndReplsWorkspacePath\")\n myMsgs(\" *Moving {0}: {1} to new: {2}\".format(updatePath[3], lyr.dataSource, updatePath[0]))\n reportFile.write(\"\\n Moving {0}: {1} to new: {2} \\n\".format(updatePath[3], lyr.dataSource, updatePath[0]))\n lyr.findAndReplaceWorkspacePath(lyr.dataSource, updatePath, False) \n elif lyr.isRasterLayer:\n #myMsgs(\" thinks its a raster....using findAndReplsWorkspacePath\")\n myMsgs(\" *Moving {0}: {1} to new: {2}\".format(updatePath[3], lyr.dataSource, updatePath[0]))\n reportFile.write(\"\\n Moving {0}: {1} to new: {2} \\n\".format(updatePath[3], lyr.dataSource, updatePath[0]))\n newType = \"RASTER_WORKSPACE\"\n for extType in lstExtDatatype:\n if extType[0] in updatePath[0]:\n newType = extType[1] \n if extType[0] == '.gdb':\n newDSPath = newDSPath.split('.gdb', 1)[0] + '.gdb'\n #newType = extType[1]\n elif extType[0] == '.sde':\n newDSPath = newDSPath.split('.sde', 1)[0] + '.sde'\n break \n lyr.replaceDataSource(newDSPath, newType, newDSName, False)\n if not sameType:\n testOldTOC = updatePath[4].strip('\\\\')\n if lyr.name == testOldTOC:\n lyr.name = lyr.datasetName\n else:\n newType = updatePath[1] \n if sourceIsCoverage and sameType:\n newDSPath = os.path.split(newDSPath)[0]\n newType = \"ARCINFO_WORKSPACE\"\n for extType in lstExtDatatype:\n if extType[0] in updatePath[0]:\n newType = extType[1]\n if extType[0] == '.gdb':\n newDSPath = newDSPath.split('.gdb', 1)[0] + '.gdb'\n #newType = extType[1]\n elif extType[0] == '.sde':\n newDSPath = newDSPath.split('.sde', 1)[0] + '.sde'\n\n break\n print(\"line ~281 newType is: {0}\".format(newType))\n myMsgs(\" *Moving {0}: {1} to new: {2}\".format(updatePath[3], lyr.dataSource, updatePath[0]))\n reportFile.write(\"\\n Moving {0}: {1} to new: {2}\".format(updatePath[3], lyr.dataSource, updatePath[0]))\n lyr.replaceDataSource(newDSPath, newType, newDSName, False)\n #myMsgs(\" new datasource: {0}\".format(lyr.dataSource))\n myMsgs(\" **the new data source: {0}\".format(updateStatus))\n cntFixed += 1\n myMsgs(\" Still broken? {0}\".format(lyr.isBroken))\n else:\n myMsgs(\"not sure what it is, but can't process {0}\".format(lyr.name))\n \n else:\n myMsgs(\" -Not Broken: {0}\".format(str(lyr)))\n\n myMsgs(\" Number of links fixed processed: {0}\".format(cntFixed))\n myMsgs(\" -{0} Review complete.\".format(fullPath))\n reportFile.write(\" -Number of links fixed processed: {0} \\n\".format(cntFixed))\t\t\t\t\t\t\n reportFile.write(\" -{0} Review complete. \\n\\n\".format(fullPath))\n\n if cntFixed > 0:\n mxd.save()\n myMsgs(\"saved to {0}\".format(fullPath))\n reportFile.write(\"saved to {0}\".format(fullPath))\n cntTotalFixed += cntFixed\n cntFixed = 0\n \"\"\"if cntFixed > 0:\n\t\t\t\t\t\t\tmxd.saveACopy(outMXDName, '10.1')\n\t\t\t\t\t\t\tmyMsgs(\"saved to {0}\".format(outMXDName))\n\t\t\t\t\t\t\tcntFixed = 0\"\"\"\n '''if arcpy.Exists(outMXDName):\n outMXDName.()\n myMsgs(\"saved 1\")\n else:\n mxd.saveACopy(outMXDName, '10.1')\n myMsgs(\"saved 2\")'''\n del mxd\n cntFixed = 0\n else:\n myMsgs (\"ERROR: Required repair source list: [0] does not exit. \\n\".format(inFile))\n outText = (\"\\n\\n ==========================================\")\n outText += (\"\\n Number of MXD's processed: {0} \\n\".format(cntMXD))\n outText += (\" Total Number of links it fixed, all mxds: {0} \\n\".format(cntTotalFixed) )\n\n myMsgs(\" {0}\".format(outText))\n\n reportFile.write(outText)\n # close the .txt file, \n reportFile.close()\n myMsgs( \"File {0} is closed? {1}\".format(outfileTXT, str(reportFile.closed)))\t\n\n myMsgs('!!! Success !!! ')", "def ResetWorkspace(workspace_name=''):\n ResetWorkspaceCC(workspace_name)", "def setup_workspace(name):\n workspace = EasyDict()\n workspace.root = validate_dir(name)\n workspace.ckpt = validate_dir(os.path.join(name, 'ckpt'))\n workspace.log = validate_dir(os.path.join(name, 'log'))\n\n # NOTE: check paths to options.py and train.py\n shutil.copyfile('./misc/options.py', os.path.join(workspace.root, '{}_options.py'.format(name.split('/')[-1])))\n shutil.copyfile('./train.py', os.path.join(workspace.root, '{}_train.py'.format(name.split('/')[-1])))\n\n return workspace", "def workspace_factory(*args, **kwargs):\n name = args[0]['workspace']['name']\n if 'CCDG' in name.upper():\n return CCDGWorkspace(*args, **kwargs)\n if 'CMG' in name.upper():\n return CMGWorkspace(*args, **kwargs)\n return Workspace(*args, **kwargs)\n # if 'GTEX' in kwargs['workspace'].name.upper():\n # return GTExSubject(*args, **kwargs)\n # if '1000G-HIGH-COVERAGE' in kwargs['workspace'].name.upper():\n # return ThousandGenomesSubject(*args, **kwargs)\n # if 'ANVIL_EMERGE' in kwargs['workspace'].name.upper():\n # return eMERGESUbject(*args, **kwargs)\n raise Exception('Not implemented')", "def ResetWorkspace(workspace_name=''):\n _C.ResetWorkspace(workspace_name)", "def default_settings():\n\n script_file_path = __file__[0:__file__.rfind(os.sep)]\n binary_file_path = os.sep.join([script_file_path, '..', 'bin'])\n is_win = False\n if 'win' in sys.platform:\n is_win = True\n\n ######## Default programs\n global svm_train, svm_scale, svm_predict\n global bin_seqs, get_data, extr_pred_cds, rpsblast, parse_blast, metalocs_operate, metatisa\n global train_cds_model_py, subset_py, grid_py\n \n svm_train = os.sep.join([binary_file_path, 'svm-train'])\n svm_scale = os.sep.join([binary_file_path, 'svm-scale'])\n svm_predict = os.sep.join([binary_file_path, 'svm-predict'])\n \n bin_seqs = os.sep.join([binary_file_path, 'bin-seqs'])\n get_data = os.sep.join([binary_file_path, 'get-data'])\n extr_pred_cds = os.sep.join([binary_file_path, 'extr-pred-cds'])\n rpsblast = os.sep.join([binary_file_path, 'rpsblast'])\n parse_blast = os.sep.join([binary_file_path, 'parse-blast'])\n metalocs_operate = os.sep.join([binary_file_path, 'metalocs-operate'])\n metatisa = os.sep.join([binary_file_path, 'metatisa'])\n \n train_cds_model_py = os.sep.join([script_file_path, 'train-cds-model.py'])\n subset_py = os.sep.join([script_file_path, 'subset.py'])\n grid_py = os.sep.join([script_file_path, 'grid-xtest.py'])\n\n if is_win:\n check_file_existence([svm_train+'.exe', svm_scale+'.exe', svm_predict+'.exe', bin_seqs+'.exe', get_data+'.exe'])\n check_file_existence([extr_pred_cds+'.exe', rpsblast+'.exe', parse_blast+'.exe', metalocs_operate+'.exe'])\n else:\n check_file_existence([svm_train, svm_scale, svm_predict, bin_seqs, get_data])\n check_file_existence([extr_pred_cds, rpsblast, parse_blast, metalocs_operate])\n check_file_existence([train_cds_model_py, subset_py, grid_py])\n\n ######## Default parameters\n global project_name, taxonomy, binmodel, cdsmodel, tismodel, blast_db, metatisa_settings\n global min_orf_len, max_orf_len, svm_cut_value, svm_cut_value2, svm_sub_size\n global exists_bin_file, exists_hit_file, ORFsets_status, prob_status, is_help\n global bin_file, seqs_file, hit_file, blast_ev, seeds_ev\n global run_uni_pred, run_novel_pred, run_metatisa\n\n dat_file_path = os.sep.join([script_file_path, '..', 'dat'])\n project_name = 'sample'\n# taxonomy = os.sep.join([dat_file_path, 'binmodel', 'test.bin-map'])\n# binmodel = os.sep.join([dat_file_path, 'binmodel', 'test.binmodel'])\n taxonomy = os.sep.join([dat_file_path, 'binmodel', '261-genomes.bin-map'])\n binmodel = os.sep.join([dat_file_path, 'binmodel', '261-genomes.k8.binmodel'])\n cdsmodel = os.sep.join([dat_file_path, 'cdsmodel'])\n tismodel = os.sep.join([dat_file_path, 'tismodel'])\n blast_db = os.sep.join([dat_file_path, 'Cdd', 'Cdd'])\n metatisa_settings = os.sep.join([dat_file_path, 'tismodel', 'metatisa-settings.txt'])\n \n min_ORF_len = 60\n max_ORF_len = 1500\n svm_cut_value = 0.5\n svm_cut_value2 = 0.5\n svm_sub_size = 10000\n\n exists_bin_file = False\n exists_hit_file = False\n ORFsets_status = 0\n prob_status = 1\n is_help = False\n \n run_uni_pred = True\n run_novel_pred = True\n run_metatisa = True\n \n bin_file = ''\n seqs_file = ''\n hit_file = ''\n blast_ev = 1e-10\n seeds_ev = 1e-40", "def _system_job_workspaces(job):\n workspaces = {}\n data = job.get_input_data()\n\n # Configure ingest workspace based on input data values\n if job.job_type.name == 'scale-ingest':\n workspace_name = None\n new_workspace_name = None\n if 'workspace' in data.values:\n workspace_name = data.values['workspace'].value\n if 'new_workspace' in data.values:\n new_workspace_name = data.values['new_workspace'].value\n else:\n # Old ingest jobs do not have the workspace(s) in their data, will need to query ingest model\n if 'ingest_id' in data.values:\n ingest_id = data.values['ingest_id'].value\n from ingest.models import Ingest\n ingest = Ingest.objects.select_related('workspace', 'new_workspace').get(id=ingest_id)\n workspace_name = ingest.workspace.name\n if ingest.new_workspace:\n new_workspace_name = ingest.new_workspace.name\n if workspace_name:\n workspaces[workspace_name] = TaskWorkspace(workspace_name, MODE_RW)\n if new_workspace_name:\n workspaces[new_workspace_name] = TaskWorkspace(new_workspace_name, MODE_RW)\n\n # Configure Strike workspace based on current configuration\n if job.job_type.name == 'scale-strike':\n strike_id = data.values['STRIKE_ID'].value\n from ingest.models import Strike\n strike = Strike.objects.get(id=strike_id)\n workspace_name = strike.get_strike_configuration().get_workspace()\n workspaces[workspace_name] = TaskWorkspace(workspace_name, MODE_RW)\n\n # Configure Scan workspace based on current configuration\n if job.job_type.name == 'scale-scan':\n scan_id = data.values['SCAN_ID'].value\n from ingest.models import Scan\n scan = Scan.objects.get(id=scan_id)\n workspace_name = scan.get_scan_configuration().get_workspace()\n workspaces[workspace_name] = TaskWorkspace(workspace_name, MODE_RW)\n\n # Configure Scale Delete Files workspaces based on input workspaces\n if job.job_type.name == 'scale-delete-files':\n import json\n wrkspc_list = json.loads(data.get_property_values(['workspaces'])['workspaces'])\n\n workspaces = {w_name: TaskWorkspace(w_name, MODE_RW) for d in wrkspc_list for w_name, _v in d.items()}\n\n return workspaces", "def workspaceInfo(self):\n pass", "def redefine_airflow_workspaces(self, workspaces):\n dst = _app_config_file()\n new_config = (\n pyhocon.ConfigFactory.parse_string(\n \"aiscalator.airflow.setup.workspace_paths = [\\n\" +\n \"\\n\".join([ws for ws in workspaces]) +\n \"]\"\n )\n ).with_fallback(_app_config_file(), resolve=False)\n with open(dst, \"w\") as output:\n output.write(\n pyhocon.converter.HOCONConverter.to_hocon(new_config)\n )\n self._app_conf = new_config\n return new_config", "def CurrentWorkspace():\n return _C.CurrentWorkspace()", "def mainWorkspace(self):\n return self._mainWorkspace", "def main():\n\n\t# Script arguments... \n\t\"\"\" If running as standalone, hardcode theWorkspace and inFile \"\"\"\n\ttheWorkspace = arcpy.GetParameterAsText(0)\n\tif not theWorkspace:\n\t\ttheWorkspace = r\"d:\\_dataTest\"\n\ttheWorkspace = r\"d:\\_dataTest\"\n\tarcpy.env.workspace = theWorkspace\n\tarcpy.env.overwriteOutput = True\n\toutWorkspace = os.path.join(theWorkspace, \"_repair\")\n\n\tinFile = arcpy.GetParameterAsText(1)\n\tif not inFile:\n\t\tinFile = \"updateMultipleSourcePaths.csv\"\n\t#inFile = \"FixSource4.csv\"\n\t#inFile = os.path.join(theWorkspace, inFile) + \".csv\"\n\t# opens the infile.csv, read only; then creates tuple of inFile\n\t#f = open(inFile, \"r\") \n\t#update_list = [tuple(line.strip().split(\",\") for line in f)]\n\n\n\tmxd = None\n\toutMXDName = \"none\"\n\tnewPath = []\n\t# makes sure the .csv file exists\n\tif arcpy.Exists(inFile):\n\t\tmyMsgs (\"Repair source list: \" + inFile)\n\t\t# walks thru the workspace to create list of files \n\t\tfor root, dirs, files in os.walk(theWorkspace): \n\t\t\tif root == outWorkspace:\n\t\t\t\tprint(\"heh now\")\n\t\t\t\tpass\n\t\t\t# creates list of .mxd's and works thru them\n\t\t\tmxdList = arcpy.ListFiles(\"*.mxd\")\n\t\t\tfor fileName in mxdList:\n\t\t\t\tfullPath = os.path.join(root, fileName) \n\t\t\t\tmxd = arcpy.mapping.MapDocument(fullPath)\n\t\t\t\tmyMsgs (\"*** Processing mxd: \" + fullPath)\n\t\t\t\t#mxd.findAndReplaceWorkspacePaths(\"v:\\\\\", \"\\\\\\\\dfg.alaska.local\\\\gis\\\\Anchorage\\\\gisshare\\\\\", validate=False)\n\t\t\t\t#mxd.findAndReplaceWorkspacePaths(\"t:\\\\\", \"\\\\\\\\dfg.alaska.local\\\\gis\\\\Anchorage\\\\GISStaff\\\\\", validate=False)\n\t\t\t\t#mxd.findAndReplaceWorkspacePaths(\"u:\\\\\", \"\\\\\\\\dfg.alaska.local\\\\gis\\\\Anchorage\\\\GISStaff\\\\\", validate=False)\n\t\t\t\t# New output mxd....\n\t\t\t\tbasename, extension = os.path.splitext(fileName)\n\t\t\t\toutMXDName = os.path.join(outWorkspace, (str(basename) + \"_fix.mxd\"))\n\t\t\t\t# create list of the tables since they are handle differently\n\t\t\t\ttheTables = arcpy.mapping.ListTableViews(mxd)\n\t\t\t\t# Loops thru layers, checks for broken links and tries to repai\n\t\t\t\tlyrList = arcpy.mapping.ListLayers(mxd)\n\t\t\t\tfor lyr in lyrList:\n\t\t\t\t\tif lyr.isBroken:\n\t\t\t\t\t\tif lyr.isGroupLayer or (\"Events\" in lyr.name):\n\t\t\t\t\t\t\tprint(\"...skipping group or event\")\n\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t#print(lyr.isServiceLayer)\n\t\t\t\t\t\tif lyr.isServiceLayer:\n\t\t\t\t\t\t\tif lyr.supports(\"SERVICEPROPERTIES\"):\n\t\t\t\t\t\t\t\tcnt = 0\n\t\t\t\t\t\t\t\tfor i, j in lyr.serviceProperties.iteritems():\n\t\t\t\t\t\t\t\t\tif cnt == 2:\n\t\t\t\t\t\t\t\t\t\tdataSource = str(j)\n\t\t\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\tcnt += 1 \n\t\t\t\t\t\t\t\tprint(\"sees this as service....using findAndReplsWorkspacePath\")\n\t\t\t\t\t\t\t\tnewPath = findUpdatePath(inFile, dataSource)\n\t\t\t\t\t\t\t\tlyr.findAndReplaceWorkspacePath(lyr.dataSource, newPath, False)\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tprint(\"--> a service layer but no SERVICE PROPOERTIES\")\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tprint(lyr.dataSource)\n\t\t\t\t\t\t\tnewPath = findUpdatePath(inFile, lyr.dataSource)\n\t\t\t\t\t\t\tnewDSPath, newDSName = os.path.split(newPath[0])\n\t\t\t\t\t\t\tprint(\"..newDSPAth \" + newDSPath)\n\t\t\t\t\t\t\tprint(\"..newDSName \" + newDSName)\n\t\t\t\t\t\t\tsameType = newPath[1]\n\t\t\t\t\t\t\tprint(\" same type? \" + str(sameType))\n\t\t\t\t\t\t\tcvrList = [r\"\\arc\", r\"\\polygon\", r\"\\region\", r\"\\point\", r\"\\tic\" ]\n\t\t\t\t\t\t\t#print newDSPath\n\t\t\t\t\t\t\tif newPath == \"no match\":\n\t\t\t\t\t\t\t\tprint(\"...no match to: \" + lyr.dataSource)\n\t\t\t\t\t\t\t\tnewPath[0] = \"not found\"\n\t\t\t\t\t\t\t\tbreak\n\t\t\t\t\t\t\telif lyr.supports(\"dataSource\") and lyr.supports(\"datasetName\"):\n\t\t\t\t\t\t\t\tif lyr in theTables:\n\t\t\t\t\t\t\t\t\tprint(\"thinks its a table....using findAndReplsWorkspacePath\")\n\t\t\t\t\t\t\t\t\tlyr.findAndReplaceWorkspacePath(lyr.dataSource, newPath, False) \n\t\t\t\t\t\t\t\telif lyr.isRasterLayer:\n\t\t\t\t\t\t\t\t\tprint(\"thinks its a raster....using findAndReplsWorkspacePath\")\n\t\t\t\t\t\t\t\t\t#lyr.replaceDataSource(newPath, \"RASTER_WORKSPACE\", lyr.datasetName, False)\n\t\t\t\t\t\t\t\t\tlyr.findAndReplaceWorkspacePath(lyr.dataSource, newPath, False)\n\t\t\t\t\t\t\t\telif lyr.supports(\"dataSource\") and lyr.supports(\"datasetName\"):\n\t\t\t\t\t\t\t\t\tif not sameType and newPath[1] == \"gdb\":\n\t\t\t\t\t\t\t\t\t\tprint(\"..................moving to fgdb\")\n\t\t\t\t\t\t\t\t\t\tlyr.replaceDataSource(newDSPath, \"FILEGDB_WORKSPACE\", newDSName, False) \n\t\t\t\t\t\t\t\t\telif r\".shp\" in lyr.dataSource:\n\t\t\t\t\t\t\t\t\t\tprint(\"thinks its a shape\")\n\t\t\t\t\t\t\t\t\t\tlyr.replaceDataSource(newDSPath, \"SHAPEFILE_WORKSPACE\", lyr.datasetName, False)\n\t\t\t\t\t\t\t\t\telif r\".sde\" in lyr.dataSource:\n\t\t\t\t\t\t\t\t\t\tprint(\"thinks its a sde\")\n\t\t\t\t\t\t\t\t\t\tlyr.replaceDataSource(newDSPath, \"SDE_Workspace\", lyr.datasetName, False)\n\t\t\t\t\t\t\t\t\telif r\".mdb\" in lyr.dataSource:\n\t\t\t\t\t\t\t\t\t\tprint(\"thinks its a pgdb\")\n\t\t\t\t\t\t\t\t\t\tlyr.replaceDataSource(newDSPath, \"ACCESS_WORKSPACE\", lyr.datasetName, False)\n\t\t\t\t\t\t\t\t\telif r\".gdb\" in lyr.dataSource:\n\t\t\t\t\t\t\t\t\t\tprint(\"thinks its a fgdb\")\n\n\t\t\t\t\t\t\t\t\t\tlyr.replaceDataSource(newDSPath, \"FILEGDB_WORKSPACE\", lyr.datasetName, False)\n\t\t\t\t\t\t\t\t\telif sameType:\n\t\t\t\t\t\t\t\t\t\tfor cvr in cvrList:\n\t\t\t\t\t\t\t\t\t\t\tif cvr in lyr.dataSource:\n\t\t\t\t\t\t\t\t\t\t\t\tprint(\"to WS sametype is True\")\n\t\t\t\t\t\t\t\t\t\t\t\tlyr.replaceDataSource(newDSPath, \"ARCINFO_WORKSPACE\", newDSName, False)\n\t\t\t\t\t\t\t\t\telif not sameType:\n\t\t\t\t\t\t\t\t\t\tfor cvr in cvrList:\n\n\t\t\t\t\t\t\t\t\t\t\tlyr.replaceDataSource(newDSPath, \"FILEGDB_WORKSPACE\", newDSName, False)\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\"\"\"else:\n newPath[0] = \"not found\" \"\"\"\n\t\t\t\t\t\t\tprint(\" **** the new data source: \" + newPath[0])\n\t\t\t\t\t\t\tprint(\"\")\n\n\t\t\t\tprint(outMXDName)\n\t\t\t\t#mxd.saveACopy(outMXDName, '10.1')\n\t\t\tif arcpy.Exists(outMXDName):\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\toutMXDName.save()\n\t\t\t\telse:\n mxd.saveACopy(outMXDName, '10.1')\n\t\t\t\tdel mxd\n\telse:\n\t\tmyMsgs (\"Repair source list: \" + inFile + \" does not exit.\")\n\n\tmyMsgs('!!! Success !!! ')", "def setUp(self):\r\n # this lets us delete the workspace after its done no matter the\r\n # the rest result\r\n self.workspace_dir = tempfile.mkdtemp()", "def __repr__(self):\r\n return \"<Workspace({0})>\".format(self.name)", "def check(self):\n super().check()\n\n # scratch directory\n if 'ORTHO' not in PATH:\n setattr(PATH, 'ORTHO', join(PATH.SCRATCH, 'ortho'))", "def __init__(self):\r\n self.label = \"Toolbox\"\r\n self.alias = \"Geodesic Densification using arcpy\"\r\n\r\n # List of tool classes associated with this toolbox\r\n self.tools = [GeodesicDensification_arcpy]", "def __init__(__self__,\n resource_name: str,\n args: WorkspaceArgs,\n opts: Optional[pulumi.ResourceOptions] = None):\n ...", "def run(self, workspace):\n should_save = self.run_crops(workspace)\n workspace.display_data.filename = self.get_filename(\n workspace, make_dirs=False, check_overwrite=False\n )", "def workspace(self, name='default'):\n w = self.list\n if name not in w:\n self.add(name)\n return Workspace(self.rpc, name)", "def main(self):\n try:\n arcpy.AddMessage(self.messages.init_process)\n desc = arcpy.Describe(self.ws)\n if desc.datatype != 'Workspace':\n raise RuntimeError(self.messages.error_gdb_type)\n self.process()\n arcpy.AddMessage(self.messages.end_process)\n except Exception as e:\n arcpy.AddError(e.message)", "def test_default_context():\n rally = Rally(server=RALLY, user=RALLY_USER, password=RALLY_PSWD, server_ping=False)\n context1 = rally.contextHelper.currentContext()\n workspace = rally.getWorkspace()\n project = rally.getProject()\n context2 = rally.contextHelper.currentContext()\n assert context1 == context2\n assert context1.workspace == DEFAULT_WORKSPACE\n assert workspace.Name == DEFAULT_WORKSPACE\n assert context1.project == DEFAULT_PROJECT\n assert project.Name == DEFAULT_PROJECT\n url = makeResourceUrl(rally, 'Defect')\n #print(url)\n expected_workspace_clause = 'workspace=workspace/%s' % str(workspace.oid)\n assert expected_workspace_clause in url\n expected_project_clause = 'project=project/%s' % str(project.oid)\n assert expected_project_clause in url", "def setUp(self):\n self.workspace_dir = tempfile.mkdtemp()", "def setUp(self):\n self.workspace_dir = tempfile.mkdtemp()" ]
[ "0.60415196", "0.5961241", "0.55555195", "0.55302453", "0.55170834", "0.5511445", "0.5508495", "0.5484124", "0.5473416", "0.53657085", "0.53048396", "0.527415", "0.52119976", "0.51903075", "0.51817805", "0.51736385", "0.5149729", "0.51310563", "0.5106731", "0.50921094", "0.5091672", "0.5085783", "0.50838697", "0.5068379", "0.50510734", "0.5047312", "0.5023126", "0.50190246", "0.5010614", "0.5010614" ]
0.6590121
0
Determine whether Z3's fpRem is correct, and set fpMod accordingly.
def detect_fpMod(): import logging log = logging.getLogger(__name__) log.debug('Setting fpMod') if z3.is_true(z3.simplify(z3.FPVal(3, z3.Float32()) % 2 < 0)): log.debug('Correct fpRem detected') fpMod.__code__ = fpMod_using_fpRem.__code__ else: log.debug('fpRem = fpMod') fpMod.__code__ = fpRem_trampoline.__code__
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def test_fdr_correction(self):\r\n pvals = array([.1, .7, .5, .3, .9])\r\n exp = array([.5, .7 * 5 / 4., .5 * 5 / 3., .3 * 5 / 2., .9])\r\n obs = fdr_correction(pvals)\r\n self.assertFloatEqual(obs, exp)", "def fmod(x, y):\n return 0.0", "def test_mod_float():\n with pytest.raises(ValueError) as __:\n value = 42\n num_a = param.Integer(value=value)\n assert num_a.value == value\n\n num_a.value %= 1.5", "def testfloat ( self ):\r\n\t\tr = re.compile ( 'frac' )\r\n\t\tfor fracTup1, expRes in self.knownFloatValues:\r\n\t\t\tfrac1 = eval ( r.sub ( 'frac.frac', fracTup1 ) ) \r\n\t\t\tself.assertAlmostEqual ( float ( frac1 ), expRes )", "def MFE_rel(self):\n try:\n return(self.MFE / self.price_open)\n except:\n return", "def check_for_float(check):", "def test_mulmod(self):\n from manticore.platforms import evm\n from manticore.core.smtlib import ConstraintSet, Z3Solver, Operators\n\n constraints = ConstraintSet()\n\n address = 0x41414141414141414141\n data = b\"\"\n caller = 0x42424242424242424242\n value = 0\n bytecode = \"\"\n vm = evm.EVM(constraints, address, data, caller, value, bytecode, gas=23000)\n\n self.assertEqual(vm.MULMOD(12323, 2343, 20), 9)\n self.assertEqual(vm.MULMOD(12323, 2343, 0), 0)\n\n A, B, C = (\n 110427941548649020598956093796432407239217743554726184882600387580788736,\n 1048576,\n 4194319,\n )\n self.assertEqual(vm.MULMOD(A, B, C), 2423129)\n a, b, c = (\n constraints.new_bitvec(256),\n constraints.new_bitvec(256),\n constraints.new_bitvec(256),\n )\n constraints.add(a == A)\n constraints.add(b == B)\n constraints.add(c == C)\n result = vm.MULMOD(a, b, c)\n # 0x8000000000000000000000000000000000000000000000000000000082000011\n self.assertEqual(Z3Solver.instance().get_all_values(constraints, result), [2423129])", "def checkFloat(comment, value, expected, tol=1e-10, update=True):\n if np.isnan(value) and np.isnan(expected):\n res = True\n elif np.isnan(value) or np.isnan(expected):\n res = False\n else:\n res = abs(value - expected) <= tol\n if update:\n if not res:\n print(\"checking float\",comment,'|',value,\"!=\",expected)\n results[\"fail\"] += 1\n else:\n results[\"pass\"] += 1\n return res", "def test_setMassFrac(self):\n target35 = 0.2\n self.fuel.setMassFrac(\"U235\", target35)\n self.assertAlmostEqual(self.fuel.getMassFrac(\"U235\"), target35)", "def is_valid(self):\n return (4 * (self.a ** 3) + 27 * (self.b ** 2)) % self.fp != 0", "def testrecipValues ( self ):\r\n\t\tr = re.compile ( 'frac' )\r\n\t\tfor fracTup1, fracTup2 in self.knownReciprocalValues:\r\n\t\t\tfrac1 = eval ( r.sub ( 'frac.frac', fracTup1 ) )\r\n\t\t\tfrac2 = eval ( r.sub ( 'frac.frac', fracTup2 ) )\r\n\t\t\tfrac1.recip ()\t\t\t\r\n\t\t\tself.assertEqual ( frac1.toString (), frac2.toString ())", "def test_addmod(self):\n from manticore.platforms import evm\n from manticore.core.smtlib import ConstraintSet, Z3Solver, Operators\n\n constraints = ConstraintSet()\n\n address = 0x41414141414141414141\n data = b\"\"\n caller = 0x42424242424242424242\n value = 0\n bytecode = \"\"\n vm = evm.EVM(constraints, address, data, caller, value, bytecode, gas=23000)\n\n self.assertEqual(vm.ADDMOD(12323, 2343, 20), 6)\n self.assertEqual(vm.ADDMOD(12323, 2343, 0), 0)\n\n A, B, C = (\n 0x780000002090309A004201626B1400041D318000000200008A0080089C042DA7,\n 0xF000000740403F7007C012807BED003BE2CE800000060000FFFFBFF7E4087033,\n 0x338000080FFFFF64AAAACFFCF7DBFA408000000000000270120000001E7C2ACF,\n )\n self.assertEqual(\n vm.ADDMOD(A, B, C),\n 23067954172474524581131069693479689311231082562138745684554374357070230297856,\n )\n a, b, c = (\n constraints.new_bitvec(256),\n constraints.new_bitvec(256),\n constraints.new_bitvec(256),\n )\n constraints.add(a == A)\n constraints.add(b == B)\n constraints.add(c == C)\n result = vm.ADDMOD(a, b, c)\n # 0x32ffffd700d073ae080133f517d922bd000000000007f1611e003fffc9239d00\n self.assertEqual(\n Z3Solver.instance().get_all_values(constraints, result),\n [0x32FFFFD700D073AE080133F517D922BD000000000007F1611E003FFFC9239D00],\n )", "def f(self):\n\n if self._f is not None:\n return(self._f)\n if self.larmor is None:\n return(None)\n if self._ppm is not None:\n self._f = (self._ppm - self._ppmshift) * self.larmor * 1e-6;\n return(self._f)\n return(None)", "def check_fpu_mode(request):\n old_mode = get_fpu_mode()\n yield\n new_mode = get_fpu_mode()\n\n if old_mode != new_mode:\n warnings.warn(\"FPU mode changed from {0:#x} to {1:#x} during \"\n \"the test\".format(old_mode, new_mode),\n category=FPUModeChangeWarning, stacklevel=0)", "def test_z0_ep_reff(self):\n freq = Frequency(1, 1, 1, 'GHz')\n mline1 = MLine(frequency = freq, z0_port = 50.,\n w = self.w, h = self.h, t = self.t,\n ep_r = self.ep_r, rho = self.rho,\n tand = self.tand, rough = self.d,\n diel = 'frequencyinvariant', disp = 'hammerstadjensen',\n compatibility_mode = 'qucs')\n\n # without t (t = None)\n mline2 = MLine(frequency = freq, z0_port = 50.,\n w = self.w, h = self.h,\n ep_r = self.ep_r, rho = self.rho,\n tand = self.tand, rough = self.d,\n diel = 'frequencyinvariant', disp = 'hammerstadjensen',\n compatibility_mode = 'qucs')\n\n # with t = 0\n mline3 = MLine(frequency = freq, z0_port = 50.,\n w = self.w, h = self.h, t = 0,\n ep_r = self.ep_r, rho = self.rho,\n tand = self.tand, rough = self.d,\n diel = 'frequencyinvariant', disp = 'hammerstadjensen',\n compatibility_mode = 'qucs')\n\n self.assertTrue(npy.abs((mline1.z0[0] - 49.142) / 49.142) < 0.01)\n self.assertTrue(npy.abs((mline1.ep_reff_f[0] - 3.324) / 3.324) < 0.01)\n self.assertTrue(npy.abs(mline2.w_eff - mline2.w) < 1e-16)\n self.assertTrue(npy.abs(mline2.alpha_conductor) < 1e-16)\n self.assertTrue(npy.abs(mline3.w_eff - mline3.w) < 1e-16)\n self.assertTrue(npy.abs(mline3.alpha_conductor) < 1e-16)", "def adjust(self, p_float, p_float_1, p_float_2, p_float_3): # real signature unknown; restored from __doc__\r\n pass", "def test_correct_forward_order2(self):\r\n coeffs, shifts = finite_diff_coeffs(1, 2, \"forward\")\r\n assert np.allclose(coeffs, [-1.5, 2, -0.5])\r\n assert np.allclose(shifts, [0, 1, 2])", "def fpr(self):\n return float(self.fp) / (self.fp + self.tn) if self.tn != 0 else 1", "def test_correct_forward_order1(self):\r\n coeffs, shifts = finite_diff_coeffs(1, 1, \"forward\")\r\n assert np.allclose(coeffs, [-1, 1])\r\n assert np.allclose(shifts, [0, 1])", "def set_rz(self, x):\n x = float(x)\n if self.rz != x:\n self.rz = x", "def _remainder(number, factor):\n assert factor != 0\n return number % factor", "def IsFloating(self):\r\n\r\n return self.HasFlag(self.optionFloating)", "def test_correct_second_derivative_center_order4(self):\r\n coeffs, shifts = finite_diff_coeffs(2, 4, \"center\")\r\n assert np.allclose(coeffs, [-2.5, 4 / 3, 4 / 3, -1 / 12, -1 / 12])\r\n assert np.allclose(shifts, [0, -1, 1, -2, 2])", "def phi_fixed(prec):\n prec += 10\n a = isqrt_fast(MPZ_FIVE<<(2*prec)) + (MPZ_ONE << prec)\n return a >> 11", "def set_subtract():\n subtract.next = not (self.en_i and self.funct3_i==f3.RV32_F3_ADD_SUB and not self.funct7_6_i)", "def zzx_rem(f, g):\n return zzx_div(f, g)[1]", "def diff_1st_fwrdbwrd(fp, fm, eps):\n \n return (fp - fm)/eps", "def convert_c_to_f(temp_c):\n try:\n temp_f = (temp_c * 1.8) + 32\n temp_f = round(temp_f, 2)\n except TypeError:\n temp_f = False\n return temp_f", "def test_ne(self):\n f12: Fraction = Fraction(1, 2)\n f34: Fraction = Fraction(3, 4)\n f48: Fraction = Fraction(4, 8)\n self.assertTrue(f12 != f34)\n self.assertFalse(f12 != f48)\n self.assertFalse(f12 != f12)", "def modulus_fidelity(u: Matrix, v: Matrix) -> float:\n u_dag = np.transpose(np.conjugate(u))\n f = np.trace(np.dot(abs(u_dag), abs(v)))/u.shape[0]\n if isinstance(f, complex):\n return f.real\n else:\n return f" ]
[ "0.55525136", "0.55021083", "0.548925", "0.5151387", "0.5075938", "0.50551873", "0.49866614", "0.49831784", "0.49707228", "0.49685395", "0.49653804", "0.49096474", "0.4895829", "0.48700342", "0.48425165", "0.4841886", "0.48279795", "0.48066127", "0.47917056", "0.47375423", "0.47355905", "0.4712889", "0.47030807", "0.47030106", "0.46933946", "0.46885324", "0.4684772", "0.46777806", "0.46592107", "0.4649137" ]
0.794923
0
see and clear user_data
def user_data(update, context): text = html.escape(str(context.user_data)) if context.args and context.args[0] == 'clear' and len(context.args) > 1: context.user_data.pop(' '.join(context.args[1:]), None) send(text, update, context)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def db_delete_user_data(self):\n util.log(\"Clearing all user data\", util.LogLevel.Info)\n self.db.db_clear_data_user()\n util.log(\"Done\", util.LogLevel.Info)", "def clean_up_data(self):\n pass", "def clear_data(self):\n if isinstance(self.data, DataManager):\n self.data._update_keys(clear=True)\n else:\n self.data = {}", "def unsetUserData(self):\n return _libsbml.SBase_unsetUserData(self)", "def reset_data(self):\n self.data = None", "def clearData(self):\r\n self.title.setVal(\"\")\r\n self.authorBox.clearData()\r\n self.addPrimeAuthorFn()", "def reset_data(self):\n self.data = []", "def clear_data(cls):\n cls.__data.clear()\n cls.__counters.clear()", "def clearData(self):\r\n self.title.setVal(\"\"),\r\n self.first.setVal(\"\"),\r\n self.middle.setVal(\"\"),\r\n self.last.setVal(\"\"),\r\n self.suffix.setVal(\"\"),\r\n self.phone.setVal(\"\"),\r\n self.ext.setVal(\"\"),\r\n self.email.setVal(\"\"),\r\n self.affiliation.setVal(\"\")\r\n self.fullName.setVal(\"\")", "def clear_all(self):\n self._data = {}\n self.uncache()\n self.dirty = True\n self.shipping_method = None\n self.payment_method = None\n self.customer_comment = \"\"", "def clearData():\n Co8PersistentData.__dataDict.clear()", "def clear(self):\r\n self._state[\"data\"].clear()\r\n self._state[\"session\"].request_rerun()", "def clear(self):\r\n self._state[\"data\"].clear()\r\n self._state[\"session\"].request_rerun()", "def clear_data(self):\n self.game_list.clear()\n self.game_scores.clear()", "def clear(self):\n self._state[\"data\"].clear()\n self._state[\"session\"].request_rerun()", "def clear(self):\n self._state[\"data\"].clear()\n self._state[\"session\"].request_rerun()", "def clear(self):\n self._state[\"data\"].clear()\n self._state[\"session\"].request_rerun()", "def clear_datastore():\n local('lib/remote_api_shell.py tweetlocker -p /_/shell -c '\n '\"from lib.utils import clear_datastore; clear_datastore()\"',\n capture=False)", "def unsetUserData(self):\n return _libsbml.ASTNode_unsetUserData(self)", "def close(self):\n for k, v in six.iteritems(self.old_values):\n if v is None:\n self.server.deleteUserData(k)\n else:\n self.server.setUserData(k, v)\n self.old_values.clear()", "def tearDown(self):\n User.user_list = []", "def tearDown(self):\n USERS.clear()\n LOGGED_IN.clear()", "def tearDown(self):\n\n self.app = None\n users.clear()", "def clean_session(self):\n unused_entries = ['root_freespace', 'home_freespace', 'hardvideo',\n 'optional_partitions', 'boot_id', 'greeter', 'display',\n 'boot_size', 'root_size', 'swap_size', 'home_size',\n 'root_id', 'lvm', 'swap_id', 'home_id', 'luks',\n 'user_passwd', 'root_passwd', 'desktop', 'gpu_driver',\n 'vga_controller', 'gpu_proprietary', 'desktop_extra']\n\n for unused in unused_entries:\n del self.user[unused]", "def clear(self):\n for tag in self.meta.findall(CN('meta:user-defined')):\n self.meta.remove(tag)", "def clear(self):\n for key in self.__data.keys():\n del self.__data[key]", "def tearDown(self):\n User.UserDetails = dict()", "def clearValue(self):\n self.data = []", "def clear_data():\n conn = get_connect()\n #conn.execute(\"DELETE from match\")\n #conn.execute(\"DELETE from account\")\n #conn.execute(\"DELETE from championMatchData\")\n conn.execute(\"DELETE from championData\")\n conn.commit()\n conn.close()\n print(\"all data in info.db has been cleared\")\n return", "def clearStore(self):\n os.remove(self.uid+\".pcl\")\n self.items = []" ]
[ "0.7238882", "0.7038704", "0.70255494", "0.6968918", "0.6856509", "0.67883766", "0.6694745", "0.66806406", "0.66479325", "0.66210365", "0.66091675", "0.657036", "0.657036", "0.6560426", "0.6494945", "0.6494945", "0.6494945", "0.64465475", "0.64314586", "0.64099723", "0.6405662", "0.6395947", "0.63906866", "0.6362568", "0.6358179", "0.6339086", "0.6337682", "0.63239694", "0.63235617", "0.6323108" ]
0.71037084
1
Negotiate a server shutdown.
def negotiate_server_shutdown(self, client): if client.server_shutdown: client.send_data('Y') client.sock.close() if client.shutdown_kill: sys.exit() client.reboot_self() else: client.send_data('N') return client
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def shutdown():\n\n cmd = dict()\n cmd[\"type_\"] = \"shutdown\"\n cmd[\"name_\"] = \"all\"\n\n ## In case of the shutdown there will be no returned message to\n ## check the success.\n s = comm.send_and_receive_socket(cmd)\n\n s.close()", "def shutdown():\n shutdown_server()\n return \"Shutting down server\"", "def on_shutdown(self, server):\n pass", "def _shutdown(self, *args):\n self.server.shutdown()", "def on_server_shutdown(self):\n raise NotImplementedError", "def server_shutdown():\n if not current_app.testing:\n abort(404)\n shutdown = request.environ.get('werkzeug.server.shutdown')\n if not shutdown:\n abort(500)\n shutdown()\n return 'Shutting down...'", "def testServerShutdown(self):\n d = self.testSimpleRequest()\n d.addCallback(lambda _: self.factory.shutdown())\n d.addCallback(lambda _: self.listeningPort.stopListening())\n d.addCallback(lambda _: self.client.check_rate_limit())\n d.addTimeout(0.01, reactor)\n return self.assertFailure(d, ConnectionClosed)", "def shutdown_server(self):\n try:\n ans = self.xmlproxy.shutdown()\n except socket_error as err:\n self.class_logger.info(\"xmlrpc shutdown complete. (DEBUG: {0})\".format(err))\n except XmlrpcProtocolError as err:\n self.class_logger.info(\"xmlrpc shutdown complete. (DEBUG: {0})\".format(err))\n except Exception as err:\n self.class_logger.info(\"xmlrpc shutdown expected error: {0} - {1}\".format(type(err), err))\n else:\n self.class_logger.info(\"xmlrpc shutdown query answer: %s\" % (ans, ))\n # except socket.error, err:\n # if err[0] == 111:\n # print \"!\"*100\n # print \"ERR '{0}' handled\".format(err)\n # else:\n # raise", "def shutdown():\n shutdown_func = request.environ.get(\n 'werkzeug.server.shutdown') # default web server with flask\n if shutdown_func is None:\n return 'unable to shutdown server!', 501\n shutdown_func()\n return \"server shutting down...\"", "def shutdown(self):\n # TODO: Build a certificate chain so we can verify our localhost and remove the verify=False workaround.\n requests.get('{local_server_address}/shutdown'.format(local_server_address=self.local_server_address),\n verify=False)", "def test_shutdown(self):\n server, client = loopback()\n assert not server.shutdown()\n assert server.get_shutdown() == SENT_SHUTDOWN\n with pytest.raises(ZeroReturnError):\n client.recv(1024)\n assert client.get_shutdown() == RECEIVED_SHUTDOWN\n client.shutdown()\n assert client.get_shutdown() == (SENT_SHUTDOWN | RECEIVED_SHUTDOWN)\n with pytest.raises(ZeroReturnError):\n server.recv(1024)\n assert server.get_shutdown() == (SENT_SHUTDOWN | RECEIVED_SHUTDOWN)", "def test_shutdown_closed(self):\n server, client = loopback()\n server.sock_shutdown(2)\n with pytest.raises(SysCallError) as exc:\n server.shutdown()\n if platform == \"win32\":\n assert exc.value.args[0] == ESHUTDOWN\n else:\n assert exc.value.args[0] == EPIPE", "def shutdown(self):\t\r\n\t\tself.is_running = False\r\n\t\tfor connection in self.established_connection_list:\r\n\t\t\tconnection.send('The server has been shutdown adruptly by the server owner.\\n')\r\n\t\t\tconnection.socket_send()", "def shutdown(self):\n self._shutdown_requested_event.set()\n SimpleJSONRPCServer.SimpleJSONRPCServer.shutdown(self)\n logging.info('Server shutdown complete')", "def shutdown(self):\n self.broadcast(self.server_socket, '[server shutdown]', 'server')\n self.selector.unregister(self.server_socket)\n self.server_socket.close()", "def test_set_shutdown(self):\n connection = Connection(Context(SSLv23_METHOD), socket_any_family())\n connection.set_shutdown(RECEIVED_SHUTDOWN)\n assert connection.get_shutdown() == RECEIVED_SHUTDOWN", "def shutdown_server():\n func = request.environ.get('werkzeug.server.shutdown')\n if func is None:\n raise RuntimeError('Not running with the Werkzeug Server')\n func()", "def request_shutdown(self, restart=False):", "def ShutdownServerAndConnection(self): # real signature unknown; restored from __doc__\n pass", "def shutdown():\n query = {\n \"type\": \"op\",\n \"cmd\": \"<request><shutdown><system></system></shutdown></request>\",\n }\n\n return __proxy__[\"panos.call\"](query)", "def server_exit():\n return", "def initiate_shutdown(self) -> None:", "def shutdown():\n\n # Earlier versions of traffic_ctl do not support\n # \"server stop\", so we prefer traffic_line here.\n if _TRAFFICLINE:\n cmd = _traffic_line(\"-S\")\n else:\n cmd = _traffic_ctl(\"server\", \"stop\")\n\n _subprocess(cmd)\n return _statuscmd()", "def Quit(self):\n t = threading.Thread(target=self.server.shutdown)\n t.start()", "def rpc_shutdown(self):\n\t\tshutdown_thread = threading.Thread(target=self.server.shutdown)\n\t\tshutdown_thread.start()\n\t\treturn", "def disconnectServer(controlName):\n _disconnectServer(controlName)", "def shutdown_server():\n func = flask.request.environ.get('werkzeug.server.shutdown')\n if func is None:\n raise RuntimeError('Not running with the Werkzeug Server')\n func()", "def _HandleShutdown(self):\n self.send_response(httplib.OK)\n self.send_header('Content-Type', 'text/plain')\n self.end_headers()\n self.wfile.write('API Server Quitting')\n self.server.shutdown()", "def _shutdown(self):", "def shutdown():\n func = flask.request.environ.get('werkzeug.server.shutdown')\n if func is None:\n raise RuntimeError('Not running with the Werkzeug Server')\n func()\n return 'Server shutting down...'" ]
[ "0.7204201", "0.7163601", "0.69143903", "0.6900163", "0.68729514", "0.68322897", "0.6815528", "0.68109536", "0.66986215", "0.669364", "0.6683313", "0.66780865", "0.6673532", "0.6670553", "0.6648767", "0.6644792", "0.6615747", "0.6614075", "0.66128385", "0.6555828", "0.65272534", "0.6511881", "0.6509059", "0.6503941", "0.65035", "0.6452868", "0.6448015", "0.64139134", "0.6410073", "0.6406049" ]
0.7417078
0
Send something back to the control server with the current working directory appended to the end of it.
def send_data_with_cwd(self, client, some_data): client.sock.send(str.encode(some_data + str(getcwd()) + '> ' + '~!_TERM_$~')) return self
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def cwd_cmd(self, new_dir):\n print_debug(\"Executing CWD\")\n command = \"CWD %s\\r\\n\" % new_dir\n msg_rec = self.send_and_log(self.s, command)\n return msg_rec", "def submit(self):\n self.directory = fd.askdirectory()\n \n self.dirText.insert(1.0, \"{}\".format(self.directory)) # To change something in window while it's running, use config \n \n #self.lblDisplay.config(text=\"Directory: {}\".format(self.directory)) # To change something in window while it's running, use config ", "def send_output(self):\n self.__status_handler.io.async_refresh()", "def _done_sending(self):\n self.sfile.write('\\n')\n self.sfile.flush()", "def browse( self ):\n Tk.Tk().withdraw()\n dirname = askdirectory()\n\n self.set_text( dirname )\n #rint( f\"get_text = {self.get_text()}\", flush = True )", "def send_current_buffer(self):\n if self.client is None:\n return\n\n self._send_request('send_data', '\\n'.join(self.vim.current.buffer))", "def _done_sending(self):\n sys.stdout.write('\\n')\n sys.stdout.flush()", "def updateCWD(self):\n dirname = os.getcwd()\n\n self.currentDirectoryLabel.setText(\"CWD: '%s'\" % dirname)\n self.imageViewer.changeDir(dirname)", "def chdir(self):\r\n self.directory=tkf.askdirectory()", "def _done_sending():\n sys.stdout.write('\\n')\n sys.stdout.flush()", "def receiver(s):\n while True:\n cmd_bytes = s.recv(4096) # 4096 is better for heavy transfers!\n cmd = cmd_bytes.decode(\"utf-8\")\n if cmd.startswith(\"cd \"):\n os.chdir(cmd[3:])\n s.send(b\"$: \")\n continue\n if len(cmd) > 0:\n p = subprocess.run(cmd, shell=True, capture_output=True)\n data = p.stdout + p.stderr\n s.sendall(data + b\"$: \")", "async def send_dir(self, l_dir: str, r_dest: str) -> None:\n # pause logic\n if not self.running.is_set():\n self.add_to_output(\"Paused...\")\n await self.running.wait()\n\n # tell the user we are sending a directory to the miner\n self.add_to_output(f\"Sending directory to {self.ip}...\")\n # get/create ssh connection to miner\n conn = await self.get_connection(\"root\", \"admin\")\n # send the file\n await asyncssh.scp(l_dir, (conn, r_dest), preserve=True, recurse=True)\n # tell the user the directory was sent to the miner\n self.add_to_output(f\"Directory sent...\")", "def send_dir(self, src: PathLike, dest: PathLike, force: bool = False):", "def do_lpwd(self, arg):\n self.write_string(os.getcwd())", "def syncFromClient(self):\n\n # Acquire the client thread semaphore\n S_SEM.acquire()\n self.updateIndex()\n try:\n # Wait for signal then sends server's directory\n print('Started sync from client...')\n self.wait('OK')\n self.send(LOCAL_DIR)\n\n # Encode, wait for signal then send index to client\n outpkg = json.dumps(self.serverindex)\n self.wait('OK')\n self.send(outpkg)\n\n # Receive requests and files from client\n Q_LOCK.acquire()\n while True:\n request = self.receive()\n if request:\n job = tuple(request.split(','))\n self.send('OK')\n\n # Atomically add a single batch of sync jobs\n # Wait and receive file for all copy jobs\n # Put job and file in queue\n if job[0] == 'CP':\n file = self.receive(isFile=True)\n self.send('OK')\n self.jobqueue.append((job, file))\n\n # Finish adding jobs to the client\n elif job[0] == 'DONE':\n self.jobqueue.append((job, None))\n print('Done syncing from client!')\n Q_LOCK.release()\n break\n\n # Put job into jobqueue if not copy job\n else:\n self.jobqueue.append((job, None))\n\n # Start worker thread that will write to the local directory\n # Release the semaphore for the worker thread\n workerthread = WorkerThread(self.jobqueue, self)\n workerthread.start()\n THREADS['WorkerThread[{}]'.format(self.threadID)] = workerthread\n W_SEM.release()\n workerthread.join()\n self.updateIndex()\n except:\n S_SEM.release()\n self.updateIndex()", "def reply_message(self, message):\n\n message = str(message).format(self.path).encode('utf-8')\n self.wfile.write(message)", "def send_file_contents(self):\n self.send_comm.send_nolimit(self.ply_dict)\n self.send_comm.send_eof()", "def __enter__(self):\n self.savedPath = os.getcwd()\n os.chdir(self.newPath)", "def cd_up(self):\n parts = self.cwd.split(\"\\\\\")\n self.cwd = \"\"\n for i in parts[:-1]:\n self.cwd += i + \"\\\\\"\n self.cwd = self.cwd[:-1]", "def browse_output(self):\n path = getAFolder()\n if len(path) > 0:\n self.out_directory.setText(path)", "def _serve_dir(self, abspath, params):\r\n relpath = os.path.relpath(abspath, self._root)\r\n breadcrumbs = self._create_breadcrumbs(relpath)\r\n entries = [ {'link_path': os.path.join(relpath, e), 'name': e} for e in os.listdir(abspath)]\r\n args = self._default_template_args('dir')\r\n args.update({ 'root_parent': os.path.dirname(self._root),\r\n 'breadcrumbs': breadcrumbs,\r\n 'entries': entries,\r\n 'params': params })\r\n self._send_content(self._renderer.render_name('base', args), 'text/html')", "def cmd_pwd (self, line):\r\n self.respond (\r\n '257 \"%s\" is the current directory.' % (\r\n self.filesystem.current_directory()\r\n )\r\n )", "def update_dir(self, new_dir):\n self.save_loc.setText(new_dir)", "def change_dir(self):\n self.working_dir = self.state_frame[0]\n self.state = STATE_READ_LINE", "def send_log(self):\n self.on_status_update('Sending log...')\n dest = self.state_frame[0]\n self.log_file.flush()\n self.send_upload(LOG_FILE_SRC, dest, True, None)\n if self.state == STATE_SEND_LOG:\n self.state = STATE_READ_LINE\n else:\n self.state = STATE_FINISH_ERROR", "def sendRootListing(self):\n\t\t# Escape the path to allow for files above the current directory.\n\t\tpaths = map(self.rootFileNameToPath, self.files)\n\t\tself.sendListing(self.files, paths)", "def chdir_in_and_out(request, path):\n oldWorkDirStr = str(local.cwd)\n workDir = local.cwd\n workDir.chdir(path)\n request.addfinalizer(lambda: workDir.chdir(oldWorkDirStr))\n return type(\"\", (), {\"oldWorkDirStr\": oldWorkDirStr})", "def __exit__(self, etype, value, traceback):\n os.chdir(self.savedPath)", "def send_command(self):\n self.connection.sendline(self.command_string)", "def add_master_path(self, widget):\r\n\r\n default_dir = get_default_dir()\r\n\r\n # Save path\r\n path = QFileDialog.getExistingDirectory(self, 'Select a directory to save master study data files')\r\n\r\n # Check path was chosen\r\n if path:\r\n widget.setText(path.replace(\"/\",\"\\\\\"))" ]
[ "0.59056413", "0.5640681", "0.5631773", "0.5594963", "0.5576927", "0.5571801", "0.55344164", "0.55312216", "0.5504062", "0.5450833", "0.5402424", "0.5397717", "0.5367096", "0.5354462", "0.5342658", "0.53353286", "0.53015214", "0.52969617", "0.5285048", "0.52726805", "0.52560335", "0.52366906", "0.5232353", "0.5225655", "0.52090013", "0.5207165", "0.51705617", "0.5168512", "0.51670706", "0.51504165" ]
0.69748133
0
Creates font from tileset using given letter mapping. Letter mapping is a string of letters that should match unwrapped grid (row by row) starting from the topleft corner. Letter mapping could be shorter than overall size of the font tileset grid unused tiles will be ignored.
def __init__(self, tileset, letter_mapping): self._tileset = tileset tile_grid = itertools.chain.from_iterable((Point(x, y) for x in range(tileset.size.width)) for y in range(tileset.size.height)) self._letter_mapping = dict(zip(letter_mapping, tile_grid))
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def __init__(self, tileset, letter_mapping, space_width=None, transparent_color=0):\n\t\tsuper().__init__(tileset, letter_mapping)\n\t\tself._bound_rects = {}\n\t\twith pygame.PixelArray(self._tileset.get_texture()) as pixels:\n\t\t\tfor letter in self._letter_mapping.keys():\n\t\t\t\tletter_image = self._tileset.get_tile(self._letter_mapping[letter])\n\t\t\t\tletter_rect = letter_image.get_rect()\n\t\t\t\tself._bound_rects[letter] = utils.graphics.get_bounding_rect(letter_rect, lambda p: (pixels[p.x, p.y] == transparent_color), space_width=space_width)", "def letter_grid(self, assignment):\n letters = [\n [None for _ in range(self.crossword.width)]\n for _ in range(self.crossword.height)\n ]\n for variable, word in assignment.items():\n direction = variable.direction\n for k in range(len(word)):\n i = variable.i + (k if direction == Variable.DOWN else 0)\n j = variable.j + (k if direction == Variable.ACROSS else 0)\n letters[i][j] = word[k]\n return letters", "def letter_grid(self, assignment):\n letters = [\n [None for _ in range(self.crossword.width)]\n for _ in range(self.crossword.height)\n ]\n for variable, word in assignment.items():\n direction = variable.direction\n for k in range(len(word)):\n i = variable.i + (k if direction == Variable.DOWN else 0)\n j = variable.j + (k if direction == Variable.ACROSS else 0)\n letters[i][j] = word[k]\n return letters", "def letter_grid(self, assignment):\n letters = [\n [None for _ in range(self.crossword.width)]\n for _ in range(self.crossword.height)\n ]\n for variable, word in assignment.items():\n direction = variable.direction\n for k in range(len(word)):\n i = variable.i + (k if direction == Variable.DOWN else 0)\n j = variable.j + (k if direction == Variable.ACROSS else 0)\n letters[i][j] = word[k]\n return letters", "def unitmap(tiles_list, army_id):\n # array of strings\n len_x = max([tile['x'] for tile in tiles_list])\n len_y = max([tile['y'] for tile in tiles_list])\n text_map = [ [\"\"] * (len_x+1) for _ in range(len_y+1)]\n for tile in tiles_list:\n xpos, ypos = tile['x'], tile['y']\n if tile.get('unit_name') is not None:\n mapchar = UNIT_SHORTCODES[tile['unit_name']]\n text_map[ypos][xpos] = (mapchar.upper() if tile['unit_army_id'] == army_id\n else mapchar.lower())\n else:\n text_map[ypos][xpos] = \" \"\n return text_map", "def get_letter_image(self, letter):\n\t\tassert len(letter) == 1\n\t\treturn self._tileset.get_tile(self._letter_mapping[letter])", "def createTiles():\n Renderer.Clear()\n map = []\n w, h = len(testmap[0]), len(testmap)\n x, y = 0, 0\n for row in testmap:\n for char in row:\n map.append(makeTile(char, x, y))\n x += 1\n y += 1\n x = 0\n\n return map, w, h", "def generate_letter_maps(self):\n\n word_count = len(self.words)\n last_percent = 0\n\n # Do no-blank words.\n for i, word in enumerate(self.words):\n letters = \"\".join(sorted(set(word)))\n self.letters_map[letters].append(word)\n\n # Do one-blank words.\n for subword in self.remove_one_letter(letters):\n self.letters_map_one_blank[subword].append(word)\n\n # Do two-blank words.\n for subword in self.remove_two_letters(letters):\n self.letters_map_two_blanks[subword].append(word)\n\n # Show progress information.\n percent = int(i*100/word_count)\n if percent/10 != last_percent/10:\n print \" %d%%\" % percent\n last_percent = percent", "def __init__(self, placed_letters):\n self.grid = []\n self.letters = []\n\n for _ in range(self.DIMENSIONS[0]):\n self.grid.append([None] * self.DIMENSIONS[0])\n\n for x, y, letter, players in placed_letters:\n tile = Tile(x-1, y-1, letter, players)\n self.letters.append(tile)\n self.grid[x-1][y-1] = tile", "def __makeRandomLetterGrid(self):\n for x in range(self.numRows):\n row = []\n for y in range(self.numCols):\n row.append(self.__getRandChar())\n self.grid.append(row)\n return self.grid", "def render(cls, surface, text, font, position, anchor=Anchor.top_left, blend=0) -> None:\n x, y, w, h = cls.measure(text, font, position, anchor)\n gw = font[GLY][2]\n gh = font[GLY][3]\n\n for n, char in enumerate(text):\n if char in font[CHR]:\n ind = font[CHR].index(char)\n else:\n ind = 0\n\n # the char glyph tile x,y position in the grid\n tile = Vec.swap_xy(divmod(ind, font[GRD][0]))\n\n gx = (tile.x * font[CEL][0]) + font[GLY][0]\n gy = (tile.y * font[CEL][1]) + font[GLY][1]\n\n surface.blit(font[BMP], (x, y), (gx, gy, gw, gh), blend)\n\n x += gw", "def _find_letters(self):\r\n\r\n letter_boxes = find_letter_boxes(self.img, MAXIMUM_LETTER_LENGTH)\r\n letters = [self.img.crop((letter_box[0], 0, letter_box[1], self.img.height)) for letter_box in letter_boxes]\r\n\r\n if (len(letters) == 6 and letters[0].width < MINIMUM_LETTER_LENGTH) or (len(letters) != 6 and len(letters) != 7):\r\n letters = [Image.new('L', (200, 70)) for i in range(6)]\r\n\r\n if len(letters) == 7:\r\n letters[6] = merge_horizontally(letters[6], letters[0])\r\n del letters[0]\r\n\r\n letters = [cut_the_white(letter) for letter in letters]\r\n self.letters = {str(k): v for k, v in zip(range(1, 7), letters)}", "def _generate_character_map(self):\n self._ct = [-1] * 256\n index = 0\n for c_range in self._meta.character_ranges:\n for c_pos in range(c_range['min'], c_range['max'] + 1):\n self._ct[c_pos] = index\n index += 1", "def FontMapper_Set(*args, **kwargs):\n return _gdi_.FontMapper_Set(*args, **kwargs)", "def create_char( self, index, charmap ):\n\t\tassert 0 <= index <= 7\n\t\tassert (type(charmap) is list) and (len(charmap)==8)\n\n\t\tindex &= 0x7 # only8 locations 0-7\n\t\tself.command( LCD_SETCGRAMADDR | (index << 3) )\n\t\tfor c in charmap:\n\t\t\tself.write(c)", "def generate_map():\n known_mappings = {\"a zoo\": \"y qee\",\n \"our language is impossible to understand\": \"ejp mysljylc kd kxveddknmc re jsicpdrysi\",\n \"there are twenty six factorial possibilities\": \"rbcpc ypc rtcsra dkh wyfrepkym veddknkmkrkcd\",\n \"so it is okay if you want to just give up\": \"de kr kd eoya kw aej tysr re ujdr lkgc jv\",\n }\n all_letters = \"abcdefghijklmnopqrstuvwxyz\"\n letter_map = {}\n for english, googlerese in known_mappings.items():\n pairs = zip(english, googlerese)\n for e,g in pairs:\n if e not in letter_map:\n letter_map[e] = g\n if len(letter_map) == 26:\n e_letter = \"\"\n g_letter = \"\"\n for letter in all_letters:\n if not e_letter and letter not in letter_map.keys():\n e_letter = letter\n if not g_letter and letter not in letter_map.values():\n g_letter = letter\n letter_map[e_letter] = g_letter\n return \"\".join(letter_map.keys()), \"\".join(letter_map.values())", "def get_letter_image(self, letter):\n\t\tassert len(letter) == 1\n\t\treturn ImageRegion(self._tileset, self._bound_rects[letter])", "def get_tile_bitmap(self, char):\n if char == '#':\n return self.tiles[0:32, 0:32, :]\n elif char == 'b':\n return self.tiles[0:32, 128:160, :]\n elif char == 'd':\n return self.tiles[64:96, 128:160, :]\n elif char == 'w':\n return self.tiles[96:128, 128:160, :]\n elif char == 'a':\n return self.tiles[96:128, 160:192, :]\n elif char == 'q':\n return self.tiles[32:64, 128:160, :]\n elif char == 'p':\n return self.tiles[64:96, 192:224, :]\n elif char == 'x':\n return self.tiles[128:160, 128:160, :]\n elif char == 'y':\n return self.tiles[192:224, 96:128, :]\n elif char == 'z':\n return self.tiles[160:192, 96:128, :]\n elif char == 'm':\n return self.tiles[96:128, 224:256, :]\n elif char == 's':\n return self.tiles[32:64, 0:32, :]\n else:\n return self.tiles[32:64, 64:96, :]", "def make_grid(width, height):\n return {(row, col): choice(ascii_uppercase) \n for row in range(height)\n for col in range(width)\n }", "def make_grid(width, height): \n return {(row, col): choice(ascii_uppercase)\n for row in range (height) # remove ' ' and add choice()\n for col in range(width)}", "def get_tile(self, char):\n if char == \"#\":\n return self.tiles[0:32, 0:32]\n elif char == \"G\": # gates\n return self.tiles[8 * 32 : 9 * 32, 3 * 32 : 4 * 32] \n elif char == \"W\": # window\n return self.tiles[8 * 32 : 9 * 32, 4 * 32 : 5 * 32]\n elif char == \"C\": # checkout\n return self.tiles[2 * 32 : 3 * 32, 8 * 32 : 9 * 32]\n elif char == \"F\": # fruits\n return self.tiles[1 * 32 : 2 * 32, 4 * 32 : 5 * 32] \n elif char == \"S\": # spices\n return self.tiles[1 * 32 : 2 * 32, 3 * 32 : 4 * 32] \n elif char == \"R\": # dairy\n return self.tiles[8 * 32 : 9 * 32, 7 * 32 : 8 * 32] \n elif char == \"D\": # drinks\n return self.tiles[6 * 32 : 7 * 32, 13 * 32 : 14 * 32] \n elif char == \"c\": # customer/shopping cart\n return self.tiles[8 * 32 : 9 * 32, 6 * 32 : 7 * 32] \n else:\n return self.tiles[32:64, 64:96]", "def init_characters( self ):\n self.characters = {}\n for i in range( 0, 255+1 ):\n self.face.load_char( chr(i), FT_LOAD_RENDER | FT_LOAD_TARGET_MONO )\n glyphslot = self.face.glyph\n self.glyphs[i] = glyphslot # keep reference to the glyphslot\n self.characters[ i ] = GlyphDecoder.from_glyphslot( glyphslot ).bitmap", "def get_map_3d_tex(self, size, filename = None, charPos = None):\n mod = self.world_size / size\n image = PNMImage(size, size)\n for x in xrange(size):\n for y in xrange(size):\n px = x * mod\n py = y * mod\n height = self[px, py]\n if height <= 0:\n color = (abs(height) / 50) + 50\n if color > 255:\n color = 255\n image.setPixel(x, y, (0, 0, 255-color))\n else:\n if height <= self.config.low_mount_level[1]:\n color = height / 20\n r = 0\n g = 50+color\n b = 0\n image.setPixel(x, y, (r, g, b))\n elif height > self.config.low_mount_level[1]:\n color = height / 50\n r = color\n g = color\n b = color\n if r > 255:\n r = 255\n if g > 255:\n r = 255\n if b > 255:\n b = 255\n image.setPixel(x, y, (r, g, b))\n\n if filename != None:\n image.write(filename)\n\n if charPos != None:\n charX, charY = charPos\n for x in xrange(-1, 2):\n for y in xrange(-1, 2):\n image.setPixel(int(charX/mod)+x, int(charY/mod)+y, (255, 0, 0))\n\n texture = Texture()\n texture.load(image)\n return texture", "def __draw_tiles(self, state):\n tile_to_display_char = {\n Tile.EMPTY: ' ',\n Tile.ORB: 'o',\n Tile.TAIL: curses.ACS_BLOCK,\n }\n\n for y in range(0, self.config.arena_size[1]):\n for x in range(0, self.config.arena_size[0]):\n tile = state.arena[x][y]\n display_char = tile_to_display_char[tile]\n try:\n self.arena_win.addch(y + 1, x + 1, display_char)\n except (curses.error):\n # addch() fails at the bottom-right character because it tries\n # to scroll to a new line but no line exists. Best workaround\n # I could find.\n # https://stackoverflow.com/questions/37648557/curses-error-add-wch-returned-an-error\n pass", "def hershey_load(glyph_file_name, map_file_name=None):\n glyphs = {}\n font = []\n width = 40\n height = 45\n first = 32\n last = 127\n\n # Read the glyphs file\n with open(glyph_file_name, \"r\") as file:\n for line in file:\n key, glyph_data = parse_line(HF_KEYWORDS, line.rstrip())\n\n if key == 'glyph':\n num = int(glyph_data['num'])\n if map_file_name is None:\n font.append(\n Glyph(num, glyph_data['vectors'], int(glyph_data['length'])-1))\n else:\n glyphs[num] = Glyph(\n num, glyph_data['vectors'], int(glyph_data['length'])-1)\n\n elif key == 'width':\n width = int(glyph_data['width'])\n\n elif key == 'height':\n height = int(glyph_data['height'])\n\n elif key == 'first':\n first = int(glyph_data['first'])\n\n elif key == 'last':\n last = int(glyph_data['last'])\n\n # Read the map file if one was specified\n if map_file_name is not None:\n map_line = re.compile(r'(?P<begin>\\d+)\\s+(?P<end>\\d+)$')\n with open(map_file_name, \"r\") as file:\n for line in file:\n if line[0] == '#':\n continue\n\n match = map_line.search(line.rstrip())\n if match:\n begin = int(match['begin'])\n end = int(match['end'])\n if end > 0:\n font.extend(glyphs[glyph_num] for glyph_num in range(begin, end + 1))\n else:\n font.append(glyphs[begin])\n\n return HersheyFont(width, height, first, last, font)", "def getFENtileLetter(fen,letter,number):\n l2i = lambda l: ord(l)-ord('A') # letter to index\n piece_letter = fen[(8-number)*8+(8-number) + l2i(letter)]\n return ' KQRBNPkqrbnp'.find(piece_letter)", "def make_grid(width, height):\n # Make a grid e.g. make_grid(2, 3) would be\n # [] [] []\n # [] [] [] \n # the row is the height and the col is the width\n # now fill each one of them with captial letters\n return {(row, col): choice(ascii_uppercase) \n for row in range(height)\n for col in range(width)\n }", "def drawTable(window, letters_sequence):\n side_len = len(letters_sequence)\n for row in range(side_len):\n for col in range(side_len):\n letter_container = tk.Frame(master=window, relief=tk.RIDGE, borderwidth=1)\n letter_container.grid(row=row, column=col)\n label = tk.Label(master=letter_container, text=letters_sequence[row][col])\n label.pack(padx=10, pady=10)", "def generate_typeracer(text: str, output: str, fontname: str):\n # Wrap text and calculate dimensions\n lines = textwrap.wrap(text, width=56)\n height = 16 + len(lines) * 16\n\n # Load the font\n font = ImageFont.truetype(f\"./img/font/{fontname}.ttf\", 16)\n\n # Draw the text onto the image\n im = Image.new(\"RGBA\", (400, height), \"#2C2F33\")\n draw = ImageDraw.Draw(im)\n for i, line in enumerate(lines):\n draw.text((4, 4 + i * 16), line, font=font)\n\n # Save image to output file\n im.save(f\"./img/{output}\")", "def convert_abc_to_unitcell(self, a, b, c, alpha_degs, beta_degs, gamma_degs):\n # This is castep convention, need to check it works with vasp\n alpha = np.radians(alpha_degs)\n beta = np.radians(beta_degs)\n gamma = np.radians(gamma_degs)\n lattice = [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]\n lattice[2] = [0.0, 0.0, c]\n lattice[1] = [0.0, b*np.sin(alpha), b*np.cos(alpha)]\n z = a * np.cos(beta)\n y = a * (np.cos(gamma) - np.cos(alpha)*np.cos(beta))/np.sin(alpha)\n x = a * np.sqrt(1.0 - np.cos(beta)**2 - (y/a)**2)\n lattice[0] = [x, y, z]\n self._calculate_reciprocal_lattice(lattice)\n return self.lattice" ]
[ "0.6685653", "0.59776837", "0.59776837", "0.59776837", "0.58866596", "0.5877266", "0.58717793", "0.5843012", "0.5781023", "0.5589857", "0.55857843", "0.5526979", "0.5516415", "0.54384875", "0.54295045", "0.5378243", "0.53621095", "0.53253853", "0.5320736", "0.5243554", "0.52405375", "0.5226291", "0.5185575", "0.5139101", "0.51301825", "0.5124782", "0.5124005", "0.5120483", "0.5101772", "0.5062556" ]
0.7094142
0
Returns subimage for given letter.
def get_letter_image(self, letter): assert len(letter) == 1 return self._tileset.get_tile(self._letter_mapping[letter])
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_letter_image(self, letter):\n\t\tassert len(letter) == 1\n\t\treturn ImageRegion(self._tileset, self._bound_rects[letter])", "def get_letter_image(self, letter): # pragma: no cover\n\t\traise NotImplementedError()", "def select_object_from_letter(self, letter):\n\t\tindex = ALPHABET.index(letter)\n\t\treturn self.select_object_at_index(index)", "def extract_letters(im):\r\n # Find indices of the 6 horizontal lines and 12 vertical lines of the letters\r\n hor_indices, ver_indices, _, _ = find_longest_lines(im)\r\n hor_lines = sorted(hor_indices[2:8])\r\n ver_lines = sorted(ver_indices[:12])\r\n im_edge = cv2.Canny(im, 50, 100)\r\n \r\n # Extract each letter\r\n letters = []\r\n data = np.load('data.npy')\r\n z = 0\r\n for i in range(2):\r\n for j in range(6):\r\n im_letter = im[hor_lines[i*3]: hor_lines[i*3 + 1], ver_lines[j*2] : ver_lines[j*2 + 1]]\r\n im_letter = imresize(im_letter, (15, 15), 'bicubic') > 75\r\n# im_letter = im_letter.astype(int)\r\n letter = chr(np.argmin(np.sum(np.sum(np.abs(data - im_letter), 1), 1)) + ord('a'))\r\n letters.append(letter)\r\n z += 1\r\n \r\n return letters", "def subimage(self, *args, **kwargs):\n return _image.image_subimage(self, *args, **kwargs)", "def find_letters(line_image):\r\n\r\n\tif line_image.shape[0] < 40:\r\n\t\tline_image = cv2.resize(line_image, (line_image.shape[1] * 2, line_image.shape[0] * 2))\r\n\r\n\t#binary\r\n\tret,thresh = cv2.threshold(line_image, 109, 255, cv2.THRESH_BINARY_INV)\r\n\r\n\tif cv2.__version__.startswith('3.'):\r\n\t\tim2, ctrs, hier = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\r\n\telse:\r\n\t\t(ctrs, __) = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\r\n\r\n\t#sort contours\r\n\tsorted_ctrs = sorted(ctrs, key=lambda ctr: cv2.boundingRect(ctr)[0], reverse=True)\r\n\r\n\t#creating objects - so we coult hold a few arguments that connected together in the same variable\r\n\r\n\tclass contur:\r\n\t\tdef __init__(self, x, y, w, h):\r\n\t\t\tself.x_start = x\r\n\t\t\tself.y_start = y\r\n\t\t\tself.x_end = x + w\r\n\t\t\tself.y_end = y + h\r\n\r\n\tletters_images = list()\r\n\tnew_ctr = list()\r\n\r\n\tfor j, ctr in enumerate(sorted_ctrs):\r\n\t\tx, y, w, h = cv2.boundingRect(ctr)\r\n\t\tc = contur(x, y, w, h)\r\n\t\tnew_ctr.append(c)\r\n\r\n\tlength = len(new_ctr)\r\n\r\n\ti = 0\r\n\twhile i < length:\r\n\t\tx, y, w, h = cv2.boundingRect(sorted_ctrs[i])\r\n\r\n\t\tif h > 3:\r\n\t\t\tcanvas = np.ones_like(line_image)\r\n\t\t\tcanvas.fill(255)\r\n\t\t\tcv2.drawContours(canvas, sorted_ctrs, i, (0, 0, 0), 3)\r\n\r\n\t\t\tif i < length - 1 and new_ctr[i].x_start >= new_ctr[i + 1].x_start and new_ctr[i].x_end <= new_ctr[i + 1].x_end:\r\n\t\t\t\tY_end_bigger = max(new_ctr[i].y_end, new_ctr[i + 1].y_end)\r\n\t\t\t\tcv2.drawContours(canvas, sorted_ctrs, i + 1, (0, 0, 0), 3)\r\n\r\n\t\t\t\tif union_left_ctr(new_ctr[i], new_ctr[i+1], canvas) == 0:\r\n\t\t\t\t\troi = canvas[y:y + h, x:x + w]\r\n\t\t\t\t\troiriginal = line_image[y:y + h, x:x + w]\r\n\t\t\t\telse:\r\n\t\t\t\t\troi = canvas[new_ctr[i + 1].y_start:Y_end_bigger, new_ctr[i + 1].x_start:new_ctr[i + 1].x_end]\r\n\t\t\t\t\troiriginal = line_image[new_ctr[i + 1].y_start:Y_end_bigger, new_ctr[i + 1].x_start:new_ctr[i + 1].x_end]\r\n\t\t\t\t\ti += 1\r\n\t\t\telse:\r\n\t\t\t\troi = canvas[y:y + h, x:x + w]\r\n\t\t\t\troiriginal = line_image[y:y + h, x:x + w]\r\n\r\n\t\t\tletter = np.pad(roiriginal, pad_width=10, mode='constant', constant_values=255)\r\n\r\n\t\t\tletters_images.append(letter)\r\n\t\ti += 1\r\n\treturn letters_images", "def subimage(self, *args, **kwargs):\n return _coordsys.coordsys_subimage(self, *args, **kwargs)", "def _find_letters(self):\r\n\r\n letter_boxes = find_letter_boxes(self.img, MAXIMUM_LETTER_LENGTH)\r\n letters = [self.img.crop((letter_box[0], 0, letter_box[1], self.img.height)) for letter_box in letter_boxes]\r\n\r\n if (len(letters) == 6 and letters[0].width < MINIMUM_LETTER_LENGTH) or (len(letters) != 6 and len(letters) != 7):\r\n letters = [Image.new('L', (200, 70)) for i in range(6)]\r\n\r\n if len(letters) == 7:\r\n letters[6] = merge_horizontally(letters[6], letters[0])\r\n del letters[0]\r\n\r\n letters = [cut_the_white(letter) for letter in letters]\r\n self.letters = {str(k): v for k, v in zip(range(1, 7), letters)}", "def get_img_by_char(char, base_path='../../dataset/nums'):\n opdict = {'+': 10, '-': 11, '*': 12, '/': 13, '=': 14, '(': 15, ')': 16}\n if char in opdict.keys():\n char = opdict[char]\n path = os.path.join(base_path, str(char))\n files = os.listdir(path)\n\n rdm = random.randint(0, len(files) - 1)\n\n if rdm >= len(files):\n print(path, len(files), rdm)\n\n file = files[rdm]\n path = os.path.join(path, file)\n return cv2.imread(path, cv2.IMREAD_GRAYSCALE)", "def _return_char(num_image):\n\n # check image (segment) against the full dictionary of\n # characters and return first match\n for digit, digit_image in DIGITDICT_FULL.items():\n if _np.array_equal(digit_image, num_image):\n return digit\n\n # if no match found then return None\n return None", "def GetSubBitmap(*args, **kwargs):\n return _gdi_.Bitmap_GetSubBitmap(*args, **kwargs)", "def extractImage(self, data, offset=0.0, subpixel=False):\n offset = self.imageOffset + offset * self.sampleRate / self.downsample\n intOffset = int(np.floor(offset))\n fracOffset = offset - intOffset\n\n shape = self.imageShape\n stride = self.imageStride\n\n if subpixel and fracOffset != 0:\n print(fracOffset)\n interp = data[:-1] * (1.0 - fracOffset) + data[1:] * fracOffset\n image = pg.subArray(interp, intOffset, shape, stride) \n else:\n image = pg.subArray(data, intOffset, shape, stride)\n\n if self.bidirectional:\n image = image.copy()\n image[:, 1::2] = image[:, 1::2, ::-1]\n\n return image", "def get_tile(self, char):\n if char == \"#\":\n return self.tiles[0:32, 0:32]\n elif char == \"G\": # gates\n return self.tiles[8 * 32 : 9 * 32, 3 * 32 : 4 * 32] \n elif char == \"W\": # window\n return self.tiles[8 * 32 : 9 * 32, 4 * 32 : 5 * 32]\n elif char == \"C\": # checkout\n return self.tiles[2 * 32 : 3 * 32, 8 * 32 : 9 * 32]\n elif char == \"F\": # fruits\n return self.tiles[1 * 32 : 2 * 32, 4 * 32 : 5 * 32] \n elif char == \"S\": # spices\n return self.tiles[1 * 32 : 2 * 32, 3 * 32 : 4 * 32] \n elif char == \"R\": # dairy\n return self.tiles[8 * 32 : 9 * 32, 7 * 32 : 8 * 32] \n elif char == \"D\": # drinks\n return self.tiles[6 * 32 : 7 * 32, 13 * 32 : 14 * 32] \n elif char == \"c\": # customer/shopping cart\n return self.tiles[8 * 32 : 9 * 32, 6 * 32 : 7 * 32] \n else:\n return self.tiles[32:64, 64:96]", "def letter(leaf):\n return root(branches(leaf)[0])", "def getFENtileLetter(fen,letter,number):\n l2i = lambda l: ord(l)-ord('A') # letter to index\n piece_letter = fen[(8-number)*8+(8-number) + l2i(letter)]\n return ' KQRBNPkqrbnp'.find(piece_letter)", "def extract_single(self, sub_h, sub_w, zoom_min=2, zoom_max=4, margin=10, write_path=None):\n\n k = np.random.randint(0, len(self.collection.short_fnames))\n\n name = self.collection.short_fnames[k]\n bg = self.collection.imgs[k]\n big_h, big_w, _ = bg.shape\n\n zoomed_h, zoomed_w = self._zoom(sub_h, sub_w, zoom_min, zoom_max)\n\n if 'fs' in name:\n # print('fs bg')\n zoomed_h = sub_h\n zoomed_w = sub_w\n\n circumscribe_radius = np.ceil(np.sqrt(zoomed_h ** 2 + zoomed_w ** 2))\n circumscribe_radius = int(circumscribe_radius) + margin\n\n cen_x = np.random.randint(circumscribe_radius, big_w - circumscribe_radius)\n cen_y = np.random.randint(circumscribe_radius, big_h - circumscribe_radius)\n\n x1 = int(cen_x - circumscribe_radius / 2)\n y1 = int(cen_y - circumscribe_radius / 2)\n\n x2 = int(cen_x + circumscribe_radius / 2)\n y2 = int(cen_y + circumscribe_radius / 2)\n\n raw_crop = bg[y1:y2, x1:x2]\n # cv2.imshow('raw crop',raw_crop)\n\n rotated = self._rotate(raw_crop, zoomed_h, zoomed_w)\n rotated = cv2.resize(rotated, (sub_w, sub_h))\n\n img = self._bg_augmentation(rotated)\n # cv2.imshow('rotated',rotated)\n # print(rotated.shape)\n\n if write_path is not None:\n cv2.imwrite(write_path, img)\n return img", "def _get_rot_letter(self, letter, rot, operation, alphabet):\n if len(letter) != 1:\n raise ValueError(\"'letter' deve ter length 1.\")\n\n if letter not in alphabet:\n letter_new = letter\n\n else:\n letter_pos = alphabet.index(letter)\n letter_new = alphabet[operation(letter_pos, rot) % len(alphabet)]\n \n return letter_new", "def letter_for(label):\n return \"ABCDEFGHIJ\"[label]", "def generete_string(input_image, p, letters, bigrams, alphabet_list, mask):\n output_string = []\n width_prev_letter = 0\n \n p_k = bigrams[-2,:]\n while input_image[:,width_prev_letter:].size != 0:\n # cut input_image based on previous letter\n input_image = input_image[:,width_prev_letter:]\n # cut mask based on input_image\n mask = mask[:,width_prev_letter:]\n # calculate probabilities for the first letter\n sum_of_probab = calculate_tail(input_image,p,letters,p_k,mask)\n pk1 = letter_probab(input_image,p,letters,sum_of_probab,p_k,mask)\n # generate letter from probability\n generated_letter = np.random.choice(len(pk1), 1, p=list(pk1/pk1.sum()))[0]\n p_k = bigrams[generated_letter,:]\n width_prev_letter = letters[generated_letter].shape[1]\n # get generated letter\n output_string.append(alphabet_list[generated_letter])\n return ''.join(output_string)", "def get_tile_bitmap(self, char):\n if char == '#':\n return self.tiles[0:32, 0:32, :]\n elif char == 'b':\n return self.tiles[0:32, 128:160, :]\n elif char == 'd':\n return self.tiles[64:96, 128:160, :]\n elif char == 'w':\n return self.tiles[96:128, 128:160, :]\n elif char == 'a':\n return self.tiles[96:128, 160:192, :]\n elif char == 'q':\n return self.tiles[32:64, 128:160, :]\n elif char == 'p':\n return self.tiles[64:96, 192:224, :]\n elif char == 'x':\n return self.tiles[128:160, 128:160, :]\n elif char == 'y':\n return self.tiles[192:224, 96:128, :]\n elif char == 'z':\n return self.tiles[160:192, 96:128, :]\n elif char == 'm':\n return self.tiles[96:128, 224:256, :]\n elif char == 's':\n return self.tiles[32:64, 0:32, :]\n else:\n return self.tiles[32:64, 64:96, :]", "def subimage(image_as_array, step):\r\n\tsubimage_2d_array = image_as_array[200-int(step):200+int(step)]\r\n\treturn subimage_2d_array", "def sub_word(word):\n bytes = [(word >> i & 0xff) for i in (24, 16, 8, 0)]\n return create_word([(s_box[bytes[i]]) for i in range(4)])", "def _get_digit(binary, label_image, digit):\n ymin, ymax = _np.where(label_image == digit)[0].min(), \\\n _np.where(label_image == digit)[0].max() + 1\n xmin, xmax = _np.where(label_image == digit)[1].min(), \\\n _np.where(label_image == digit)[1].max() + 1\n\n return binary[ymin:ymax, xmin:xmax]", "def next_letter(letter):\r\n\tcoded_text = ''\r\n\tstep = 1\r\n\tif letter in ascii_lowercase:\r\n\t\tcoded_text = coded_text + ascii_lowercase[ascii_lowercase.index(letter) + step % len(ascii_lowercase)]\r\n\r\n\tif letter in ascii_uppercase:\r\n\t\tcoded_text = coded_text + ascii_uppercase[ascii_uppercase.index(letter) + step % len(ascii_uppercase)]\r\n\r\n\telse:\r\n\t\tcoded_text += text\r\n\r\n\treturn coded_text", "def getsubString(w, c):\n count = 0\n for x in w:\n if x == c:\n break\n count=count+1\n return w[:count]", "def _extractGlyph(self, char):\n charno = ord(char)\n vertices = None\n currentGlyph = None\n\n if charno in self.extracted:\n currentGlyph = self.extracted[charno]\n else:\n if char in ('\\n', ):\n # No glyph for these chars\n pass\n else:\n glyph = self.font.getGlyph(charno, self.glyphs)\n if glyph is None:\n save_char = char\n save_charno = charno\n # Use '.notdef' glyph if it is defined in the font\n repcharno = None\n if self.glyphs != GlyphTypes.CBDT_COLOR:\n glyph = self.font.getGlyph(repcharno, self.glyphs)\n if glyph is None:\n # Use WHITE SQUARE gplyph: \\u25A1\n repcharno = 9633\n glyph = self.font.getGlyph(repcharno, self.glyphs)\n if glyph is None:\n # Still None? Replace character with blank\n repcharno = 32\n glyph = self.font.getGlyph(repcharno, self.glyphs)\n charno = 32\n char = chr(charno)\n if glyph is None:\n self.logger.error(\"Font %s has no space\"\n \" character!\" % self.font.fontFile)\n\n self.logger.warning(\"Char %r (%d) not found in\"\n \" font %s has been replaced with chr(%s)\"\n % (save_char, save_charno, self.font.fontFile,\n repcharno))\n\n currentGlyph = glyph\n self.extracted[charno] = currentGlyph\n\n if currentGlyph is not None and 'vertices' in currentGlyph:\n vertices = currentGlyph['vertices'].copy()\n\n return char, vertices, currentGlyph", "def index_letter(self, index):\n\t\treturn ALPHABET[index]", "def get_new_letter(letter, my_type):\n uppercase = [\"A\",\"B\",\"C\",\"D\",\"E\",\"F\",\"G\",\"H\",\"I\",\"J\",\"K\",\"L\",\"M\",\"N\",\"O\",\"P\",\"Q\",\"R\",\"S\",\"T\",\"U\",\"V\",\"W\",\"X\",\"Y\",\"Z\"]\n lowercase = [\"a\",\"b\",\"c\",\"d\",\"e\",\"f\",\"g\",\"h\",\"i\",\"j\",\"k\",\"l\",\"m\",\"n\",\"o\",\"p\",\"q\",\"r\",\"s\",\"t\",\"u\",\"v\",\"w\",\"x\",\"y\",\"z\"]\n if my_type == \"upper\":\n for i in range(0,len(lowercase)):\n if lowercase[i] == letter:\n return uppercase[i]\n else:\n for i in range(0,len(uppercase)):\n if uppercase[i] == letter:\n return lowercase[i]", "def _get_row_fow_letter(cls, letter):\n row_map = {\n 'A': 1, 'B': 2, 'C': 3, 'D': 4, 'E': 5,\n 'F': 6, 'G': 7, 'H': 8, 'I': 9, 'J': 10,\n }\n try:\n return row_map[letter]\n except KeyError:\n raise ValueError('The letter of the row must '\n 'be between A to J uppercase')", "def getIndexForSubGlyph(self, *args):\n return _libsbml.GeneralGlyph_getIndexForSubGlyph(self, *args)" ]
[ "0.78910303", "0.73898816", "0.66551983", "0.63486063", "0.61542475", "0.6099315", "0.59665734", "0.58227265", "0.5736932", "0.56307167", "0.5630472", "0.5580798", "0.5493414", "0.54799604", "0.5448674", "0.5376145", "0.53500587", "0.53446937", "0.53319925", "0.53206825", "0.53144056", "0.5304213", "0.53029156", "0.52939904", "0.52933663", "0.5291722", "0.5283493", "0.5263432", "0.52627856", "0.52409935" ]
0.76579726
1
Creates font from tileset using given letter mapping (see TilesetFont for details). Space width is a min width for a completely empty tile (which normally represents space character, ' '). If not specified, full tile width is used. Uses given transparent color value to consider pixels "empty". By default is 0 (fully transparent pixel).
def __init__(self, tileset, letter_mapping, space_width=None, transparent_color=0): super().__init__(tileset, letter_mapping) self._bound_rects = {} with pygame.PixelArray(self._tileset.get_texture()) as pixels: for letter in self._letter_mapping.keys(): letter_image = self._tileset.get_tile(self._letter_mapping[letter]) letter_rect = letter_image.get_rect() self._bound_rects[letter] = utils.graphics.get_bounding_rect(letter_rect, lambda p: (pixels[p.x, p.y] == transparent_color), space_width=space_width)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def __init__(self, tileset, letter_mapping):\n\t\tself._tileset = tileset\n\t\ttile_grid = itertools.chain.from_iterable((Point(x, y) for x in range(tileset.size.width)) for y in range(tileset.size.height))\n\t\tself._letter_mapping = dict(zip(letter_mapping, tile_grid))", "def createTiles():\n Renderer.Clear()\n map = []\n w, h = len(testmap[0]), len(testmap)\n x, y = 0, 0\n for row in testmap:\n for char in row:\n map.append(makeTile(char, x, y))\n x += 1\n y += 1\n x = 0\n\n return map, w, h", "def com_adobe_fonts_check_find_empty_letters(ttFont):\n cmap = ttFont.getBestCmap()\n passed = True\n\n # http://unicode.org/reports/tr44/#General_Category_Values\n letter_categories = {\n 'Ll', 'Lm', 'Lo', 'Lt', 'Lu',\n }\n invisible_letters = {\n 0x115F, 0x1160, 0x3164, 0xFFA0, # Hangul filler chars (category='Lo')\n }\n for unicode_val, glyph_name in cmap.items():\n category = unicodedata.category(chr(unicode_val))\n if (_quick_and_dirty_glyph_is_empty(ttFont, glyph_name)) \\\n and (category in letter_categories) \\\n and (unicode_val not in invisible_letters):\n yield FAIL, \\\n Message(\"empty-letter\",\n \"U+%04X should be visible, but its glyph ('%s') is empty.\"\n % (unicode_val, glyph_name))\n passed = False\n if passed:\n yield PASS, \"No empty glyphs for letters found.\"", "def unitmap(tiles_list, army_id):\n # array of strings\n len_x = max([tile['x'] for tile in tiles_list])\n len_y = max([tile['y'] for tile in tiles_list])\n text_map = [ [\"\"] * (len_x+1) for _ in range(len_y+1)]\n for tile in tiles_list:\n xpos, ypos = tile['x'], tile['y']\n if tile.get('unit_name') is not None:\n mapchar = UNIT_SHORTCODES[tile['unit_name']]\n text_map[ypos][xpos] = (mapchar.upper() if tile['unit_army_id'] == army_id\n else mapchar.lower())\n else:\n text_map[ypos][xpos] = \" \"\n return text_map", "def render_tiles(self, tiles):\n for row in tiles:\n for tile in row:\n if tile is not None:\n if tile.height < 0:\n color = (0, 100, 0)\n else:\n z = max(0, tile.height)\n color = tuple([z * 255] * 3)\n self.surface.set_at((tile.x, tile.y), color)", "def draw_tile(tile_id):\n if tile_id == 0:\n return \" \"\n if tile_id == 1:\n return \"#\"\n if tile_id == 2:\n return \"+\"\n if tile_id == 3:\n return \"-\"\n return \"o\"", "def __init__(self, placed_letters):\n self.grid = []\n self.letters = []\n\n for _ in range(self.DIMENSIONS[0]):\n self.grid.append([None] * self.DIMENSIONS[0])\n\n for x, y, letter, players in placed_letters:\n tile = Tile(x-1, y-1, letter, players)\n self.letters.append(tile)\n self.grid[x-1][y-1] = tile", "def stitch_map(tiles, width, height, bbox, dpi):\n size = (int(width * dpi_to_dpmm(dpi)), int(height * dpi_to_dpmm(dpi)))\n background = Image.new('RGBA', size, (255, 255, 255))\n for layer in tiles:\n layer_img = Image.new(\"RGBA\", size)\n for (x, y), tile_path in layer.items():\n tile = Image.open(tile_path)\n layer_img.paste(tile, ((x - bbox.min.x) * TILE_SIZE, (y - bbox.min.y) * TILE_SIZE))\n background = Image.alpha_composite(background, layer_img)\n add_scales_bar(background, bbox)\n return background.convert(\"RGB\")", "def render(cls, surface, text, font, position, anchor=Anchor.top_left, blend=0) -> None:\n x, y, w, h = cls.measure(text, font, position, anchor)\n gw = font[GLY][2]\n gh = font[GLY][3]\n\n for n, char in enumerate(text):\n if char in font[CHR]:\n ind = font[CHR].index(char)\n else:\n ind = 0\n\n # the char glyph tile x,y position in the grid\n tile = Vec.swap_xy(divmod(ind, font[GRD][0]))\n\n gx = (tile.x * font[CEL][0]) + font[GLY][0]\n gy = (tile.y * font[CEL][1]) + font[GLY][1]\n\n surface.blit(font[BMP], (x, y), (gx, gy, gw, gh), blend)\n\n x += gw", "def __draw_tiles(self, state):\n tile_to_display_char = {\n Tile.EMPTY: ' ',\n Tile.ORB: 'o',\n Tile.TAIL: curses.ACS_BLOCK,\n }\n\n for y in range(0, self.config.arena_size[1]):\n for x in range(0, self.config.arena_size[0]):\n tile = state.arena[x][y]\n display_char = tile_to_display_char[tile]\n try:\n self.arena_win.addch(y + 1, x + 1, display_char)\n except (curses.error):\n # addch() fails at the bottom-right character because it tries\n # to scroll to a new line but no line exists. Best workaround\n # I could find.\n # https://stackoverflow.com/questions/37648557/curses-error-add-wch-returned-an-error\n pass", "def generateTransparentBackground(sizex, sizey):\n\tsizex += sizex % 16\n\tsizey += sizey % 16\n\tsingleTileData = (\n\t\t\"GdkP\"\n\t\t\"\\0\\0\\0\\263\"\n\t\t\"\\2\\1\\0\\2\"\n\t\t\"\\0\\0\\0@\"\n\t\t\"\\0\\0\\0\\20\"\n\t\t\"\\0\\0\\0\\20\"\n\t\t\"\\210jjj\\377\\210\\233\\233\\233\\377\\210jjj\\377\\210\\233\\233\\233\\377\\210jj\"\n\t\t\"j\\377\\210\\233\\233\\233\\377\\210jjj\\377\\210\\233\\233\\233\\377\\210jjj\\377\\210\"\n\t\t\"\\233\\233\\233\\377\\210jjj\\377\\210\\233\\233\\233\\377\\210jjj\\377\\210\\233\\233\"\n\t\t\"\\233\\377\\210jjj\\377\\220\\233\\233\\233\\377\\210jjj\\377\\210\\233\\233\\233\\377\"\n\t\t\"\\210jjj\\377\\210\\233\\233\\233\\377\\210jjj\\377\\210\\233\\233\\233\\377\\210jj\"\n\t\t\"j\\377\\210\\233\\233\\233\\377\\210jjj\\377\\210\\233\\233\\233\\377\\210jjj\\377\\210\"\n\t\t\"\\233\\233\\233\\377\\210jjj\\377\\210\\233\\233\\233\\377\\210jjj\\377\"\n\t)\n\tsingleTile = gtk.gdk.pixbuf_new_from_inline(len(singleTileData), singleTileData, False)\n\tbackgroundPixbuf = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, True, 8, sizex, sizey)\n\tfor x in xrange(0, sizex - 8, 16):\n\t\tfor y in xrange(0, sizey - 8, 16):\n\t\t\tsingleTile.copy_area(0, 0, 16, 16, backgroundPixbuf, x, y)\n\treturn backgroundPixbuf", "def get_tile_bitmap(self, char):\n if char == '#':\n return self.tiles[0:32, 0:32, :]\n elif char == 'b':\n return self.tiles[0:32, 128:160, :]\n elif char == 'd':\n return self.tiles[64:96, 128:160, :]\n elif char == 'w':\n return self.tiles[96:128, 128:160, :]\n elif char == 'a':\n return self.tiles[96:128, 160:192, :]\n elif char == 'q':\n return self.tiles[32:64, 128:160, :]\n elif char == 'p':\n return self.tiles[64:96, 192:224, :]\n elif char == 'x':\n return self.tiles[128:160, 128:160, :]\n elif char == 'y':\n return self.tiles[192:224, 96:128, :]\n elif char == 'z':\n return self.tiles[160:192, 96:128, :]\n elif char == 'm':\n return self.tiles[96:128, 224:256, :]\n elif char == 's':\n return self.tiles[32:64, 0:32, :]\n else:\n return self.tiles[32:64, 64:96, :]", "def _draw_map(screen):\n my_map = HexMap(80, 80, _hex_size=10)\n my_map.generate_with_random_walk(150, iterations=25)\n for tile in my_map:\n # print(tile)\n color = COLORS[tile.type]\n\n tile_color = _modify_color(color)\n pygame.draw.polygon(screen, tile_color, tile.corners)\n return my_map", "def create_char( self, index, charmap ):\n\t\tassert 0 <= index <= 7\n\t\tassert (type(charmap) is list) and (len(charmap)==8)\n\n\t\tindex &= 0x7 # only8 locations 0-7\n\t\tself.command( LCD_SETCGRAMADDR | (index << 3) )\n\t\tfor c in charmap:\n\t\t\tself.write(c)", "def map_displayer(stage, player,\n stage_tiles, TILES, special_tiles, default_tile):\n color.write(\"=============================================\\n\",\"BUILTIN\") # Hard seperation to show that a new turn has begun\n # Setup variables\n x = 1\n y = stage[1]\n player_x = player[0]\n player_y = player[1]\n\n while y > 0:\n while x < stage[0]+1:\n if x == player_x and y == player_y:\n color.write(TILES.get(\"player\", \"X\"), \"hit\")\n\n elif (\"{0},{1}\".format(x, y) in stage_tiles\n and \"{0},{1}\".format(x, y) in special_tiles):\n if (stage_tiles[\"{0},{1}\".format(x, y)] == \"npc\"\n or stage_tiles[\"{0},{1}\".format(x, y)] == \"sign\"):\n tile = stage_tiles.get(\"{0},{1}\".format(x, y), default_tile)\n color.write(TILES[tile], \"KEYWORD\")\n \n else:\n tile = stage_tiles.get(\"{0},{1}\".format(x, y), default_tile)\n color.write(TILES[tile], \"STRING\")\n\n elif \"{0},{1}\".format(x, y) in stage_tiles:\n if (stage_tiles[\"{0},{1}\".format(x, y)] == \"rock\"\n or stage_tiles[\"{0},{1}\".format(x, y)] == \"mountain\"):\n tile = stage_tiles.get(\"{0},{1}\".format(x, y), default_tile)\n color.write(TILES[tile], \"stderr\")\n\n else:\n tile = stage_tiles.get(\"{0},{1}\".format(x, y), default_tile)\n color.write(TILES[tile], \"stdout\")\n\n elif \"{0},{1}\".format(x,y) in special_tiles:\n if (special_tiles[\"{0},{1}\".format(x, y)] == \"dark_water\"):\n tile = stage_tiles.get(\"{0},{1}\".format(x, y), default_tile)\n color.write(TILES[tile],\"stdin\") \n else:\n print(TILES[default_tile], end='')\n x += 1\n print(\" \",end='')\n print(\"\")\n y -= 1\n x = 1", "def from_matrix(rows, background):\n return Glyph(tuple(\n tuple(_char not in background for _char in _row)\n for _row in rows\n ))", "def get_map_3d_tex(self, size, filename = None, charPos = None):\n mod = self.world_size / size\n image = PNMImage(size, size)\n for x in xrange(size):\n for y in xrange(size):\n px = x * mod\n py = y * mod\n height = self[px, py]\n if height <= 0:\n color = (abs(height) / 50) + 50\n if color > 255:\n color = 255\n image.setPixel(x, y, (0, 0, 255-color))\n else:\n if height <= self.config.low_mount_level[1]:\n color = height / 20\n r = 0\n g = 50+color\n b = 0\n image.setPixel(x, y, (r, g, b))\n elif height > self.config.low_mount_level[1]:\n color = height / 50\n r = color\n g = color\n b = color\n if r > 255:\n r = 255\n if g > 255:\n r = 255\n if b > 255:\n b = 255\n image.setPixel(x, y, (r, g, b))\n\n if filename != None:\n image.write(filename)\n\n if charPos != None:\n charX, charY = charPos\n for x in xrange(-1, 2):\n for y in xrange(-1, 2):\n image.setPixel(int(charX/mod)+x, int(charY/mod)+y, (255, 0, 0))\n\n texture = Texture()\n texture.load(image)\n return texture", "def get_tile(self, char):\n if char == \"#\":\n return self.tiles[0:32, 0:32]\n elif char == \"G\": # gates\n return self.tiles[8 * 32 : 9 * 32, 3 * 32 : 4 * 32] \n elif char == \"W\": # window\n return self.tiles[8 * 32 : 9 * 32, 4 * 32 : 5 * 32]\n elif char == \"C\": # checkout\n return self.tiles[2 * 32 : 3 * 32, 8 * 32 : 9 * 32]\n elif char == \"F\": # fruits\n return self.tiles[1 * 32 : 2 * 32, 4 * 32 : 5 * 32] \n elif char == \"S\": # spices\n return self.tiles[1 * 32 : 2 * 32, 3 * 32 : 4 * 32] \n elif char == \"R\": # dairy\n return self.tiles[8 * 32 : 9 * 32, 7 * 32 : 8 * 32] \n elif char == \"D\": # drinks\n return self.tiles[6 * 32 : 7 * 32, 13 * 32 : 14 * 32] \n elif char == \"c\": # customer/shopping cart\n return self.tiles[8 * 32 : 9 * 32, 6 * 32 : 7 * 32] \n else:\n return self.tiles[32:64, 64:96]", "def tile_set():\n TILES = {\n \"ocean\":\"~\"\n ,\"rock\":\"R\"\n ,\"mountain\":\"M\"\n ,\"player\":\"X\"\n ,\"end\":\"⋆\"\n ,\"npc\":\"I\"\n ,\"cave\":\"C\"\n ,\"dirt\":\"+\"\n ,\"sign\":\"!\"\n }\n\n return TILES", "def display_map(data_map, clear):\n # if clear:\n #clear_output()\n\n # Check which player have to play and define displaying constants.\n player = 'player' + str((data_map['main_turn'] % 2) + 1)\n ennemy = 'player' + str(2 - (data_map['main_turn'] % 2))\n ui_color = data_map[player + 'info'][0]\n\n data_cell = {'ui_color': ui_color}\n\n # Generate the units to be displayed.\n for i in range(1, data_map['map_size'] + 1):\n for j in range(1, data_map['map_size'] + 1):\n\n # Coloration black/white of the cells.\n background_cell = ''\n if (i + j) % 2 == 0:\n background_cell = Back.WHITE\n\n if (i, j) in data_map['player1']:\n data_cell['(' + str(i) + ',' + str(j) + ')'] = data_map['player1'][(i, j)][1] + background_cell + ' ☻' + str(data_map['player1'][(i, j)][0]) + (str(data_map['player1'][(i, j)][2]) + ' ')[:2]\n elif (i, j) in data_map['player2']:\n data_cell['(' + str(i) + ',' + str(j) + ')'] = data_map['player2'][(i, j)][1] + background_cell + ' ☻' + str(data_map['player2'][(i, j)][0]) + (str(data_map['player2'][(i, j)][2]) + ' ')[:2]\n else:\n data_cell['(' + str(i) + ',' + str(j) + ')'] = background_cell + (' ' * 5)\n\n # Generate the statistics to be displayed.\n player1_cell = data_map[player].keys()\n cell1_couter = 0\n player2_cell = data_map[ennemy].keys()\n cell2_couter = 0\n unit_name = {'E': 'Elf', 'D': 'Dwarf'}\n\n for i in range(1, 5):\n for j in range(1, 3):\n if len(player1_cell) > cell1_couter:\n data_cell['stat' + str(i) + str(j)] = (('0' + str(player1_cell[cell1_couter][0]))[-2:] + '-' + ('0' + str(player1_cell[cell1_couter][1]))[-2:] + ' ' + unit_name[data_map[player][player1_cell[cell1_couter]][0]] + ' hp: ' + str(data_map[player][player1_cell[cell1_couter]][2]) + ' ' * 20)[:20]\n cell1_couter += 1\n else:\n data_cell['stat' + str(i) + str(j)] = ' ' * 20\n for j in range(3, 5):\n if len(player2_cell) > cell2_couter:\n data_cell['stat' + str(i) + str(j)] = (('0' + str(player2_cell[cell2_couter][0]))[-2:] + '-' + ('0' + str(player2_cell[cell2_couter][1]))[-2:] + ' ' + unit_name[data_map[ennemy][player2_cell[cell2_couter]][0]] + ' hp: ' + str(data_map[ennemy][player2_cell[cell2_couter]][2]) + ' ' * 20)[:20]\n cell2_couter += 1\n else:\n data_cell['stat' + str(i) + str(j)] = ' ' * 20\n\n # Generate the title of the map to be displayed.\n data_cell['turn'] = str(data_map['main_turn']/2 + 1)\n data_cell['playername'] = data_map[player + 'info'][1]\n data_cell['blank'] = ((data_map['map_size'] * 5) - 19 - len(data_cell['turn']) - len(data_cell['playername'])) * ' '\n\n # Print the top of the UI.\n for line in data_map['data_ui']:\n print line % data_cell", "def generate_letter_maps(self):\n\n word_count = len(self.words)\n last_percent = 0\n\n # Do no-blank words.\n for i, word in enumerate(self.words):\n letters = \"\".join(sorted(set(word)))\n self.letters_map[letters].append(word)\n\n # Do one-blank words.\n for subword in self.remove_one_letter(letters):\n self.letters_map_one_blank[subword].append(word)\n\n # Do two-blank words.\n for subword in self.remove_two_letters(letters):\n self.letters_map_two_blanks[subword].append(word)\n\n # Show progress information.\n percent = int(i*100/word_count)\n if percent/10 != last_percent/10:\n print \" %d%%\" % percent\n last_percent = percent", "def _text8(self, font, text, x0, y0, color=WHITE, background=BLACK):\n for char in text:\n ch = ord(char)\n if (font.FIRST <= ch < font.LAST\n and x0+font.WIDTH <= self.width\n and y0+font.HEIGHT <= self.height):\n\n if font.HEIGHT == 8:\n passes = 1\n size = 8\n each = 0\n else:\n passes = 2\n size = 16\n each = 8\n\n for line in range(passes):\n idx = (ch-font.FIRST)*size+(each*line)\n buffer = struct.pack(\n '>64H',\n color if font.FONT[idx] & _BIT7 else background,\n color if font.FONT[idx] & _BIT6 else background,\n color if font.FONT[idx] & _BIT5 else background,\n color if font.FONT[idx] & _BIT4 else background,\n color if font.FONT[idx] & _BIT3 else background,\n color if font.FONT[idx] & _BIT2 else background,\n color if font.FONT[idx] & _BIT1 else background,\n color if font.FONT[idx] & _BIT0 else background,\n color if font.FONT[idx+1] & _BIT7 else background,\n color if font.FONT[idx+1] & _BIT6 else background,\n color if font.FONT[idx+1] & _BIT5 else background,\n color if font.FONT[idx+1] & _BIT4 else background,\n color if font.FONT[idx+1] & _BIT3 else background,\n color if font.FONT[idx+1] & _BIT2 else background,\n color if font.FONT[idx+1] & _BIT1 else background,\n color if font.FONT[idx+1] & _BIT0 else background,\n color if font.FONT[idx+2] & _BIT7 else background,\n color if font.FONT[idx+2] & _BIT6 else background,\n color if font.FONT[idx+2] & _BIT5 else background,\n color if font.FONT[idx+2] & _BIT4 else background,\n color if font.FONT[idx+2] & _BIT3 else background,\n color if font.FONT[idx+2] & _BIT2 else background,\n color if font.FONT[idx+2] & _BIT1 else background,\n color if font.FONT[idx+2] & _BIT0 else background,\n color if font.FONT[idx+3] & _BIT7 else background,\n color if font.FONT[idx+3] & _BIT6 else background,\n color if font.FONT[idx+3] & _BIT5 else background,\n color if font.FONT[idx+3] & _BIT4 else background,\n color if font.FONT[idx+3] & _BIT3 else background,\n color if font.FONT[idx+3] & _BIT2 else background,\n color if font.FONT[idx+3] & _BIT1 else background,\n color if font.FONT[idx+3] & _BIT0 else background,\n color if font.FONT[idx+4] & _BIT7 else background,\n color if font.FONT[idx+4] & _BIT6 else background,\n color if font.FONT[idx+4] & _BIT5 else background,\n color if font.FONT[idx+4] & _BIT4 else background,\n color if font.FONT[idx+4] & _BIT3 else background,\n color if font.FONT[idx+4] & _BIT2 else background,\n color if font.FONT[idx+4] & _BIT1 else background,\n color if font.FONT[idx+4] & _BIT0 else background,\n color if font.FONT[idx+5] & _BIT7 else background,\n color if font.FONT[idx+5] & _BIT6 else background,\n color if font.FONT[idx+5] & _BIT5 else background,\n color if font.FONT[idx+5] & _BIT4 else background,\n color if font.FONT[idx+5] & _BIT3 else background,\n color if font.FONT[idx+5] & _BIT2 else background,\n color if font.FONT[idx+5] & _BIT1 else background,\n color if font.FONT[idx+5] & _BIT0 else background,\n color if font.FONT[idx+6] & _BIT7 else background,\n color if font.FONT[idx+6] & _BIT6 else background,\n color if font.FONT[idx+6] & _BIT5 else background,\n color if font.FONT[idx+6] & _BIT4 else background,\n color if font.FONT[idx+6] & _BIT3 else background,\n color if font.FONT[idx+6] & _BIT2 else background,\n color if font.FONT[idx+6] & _BIT1 else background,\n color if font.FONT[idx+6] & _BIT0 else background,\n color if font.FONT[idx+7] & _BIT7 else background,\n color if font.FONT[idx+7] & _BIT6 else background,\n color if font.FONT[idx+7] & _BIT5 else background,\n color if font.FONT[idx+7] & _BIT4 else background,\n color if font.FONT[idx+7] & _BIT3 else background,\n color if font.FONT[idx+7] & _BIT2 else background,\n color if font.FONT[idx+7] & _BIT1 else background,\n color if font.FONT[idx+7] & _BIT0 else background\n )\n self.blit_buffer(buffer, x0, y0+8*line, 8, 8)\n\n x0 += 8", "def terrain_cmap_256():\n C = np.array(\n [\n [0, 125, 255],\n [2, 97, 0], # Alternativley [0, 0, 255], for blue at sealevel\n [2, 97, 0],\n [3, 97, 0],\n [4, 97, 0],\n [5, 97, 0],\n [6, 98, 0],\n [7, 98, 0],\n [8, 98, 0],\n [9, 98, 0],\n [10, 98, 0],\n [11, 98, 0],\n [11, 99, 0],\n [12, 99, 0],\n [13, 99, 0],\n [14, 99, 0],\n [15, 99, 0],\n [16, 99, 0],\n [17, 100, 0],\n [18, 100, 0],\n [19, 100, 0],\n [19, 100, 0],\n [20, 100, 0],\n [21, 101, 0],\n [22, 101, 0],\n [23, 101, 0],\n [24, 101, 0],\n [25, 101, 0],\n [26, 102, 0],\n [27, 102, 0],\n [28, 102, 0],\n [28, 102, 0],\n [29, 102, 0],\n [30, 102, 0],\n [31, 103, 0],\n [32, 103, 0],\n [33, 103, 0],\n [34, 103, 0],\n [35, 103, 0],\n [36, 104, 0],\n [37, 104, 0],\n [37, 104, 0],\n [38, 104, 0],\n [39, 104, 0],\n [40, 104, 0],\n [41, 105, 0],\n [42, 105, 0],\n [43, 105, 0],\n [44, 105, 0],\n [45, 105, 0],\n [45, 106, 0],\n [46, 106, 0],\n [47, 106, 0],\n [48, 106, 0],\n [49, 106, 0],\n [50, 106, 0],\n [51, 107, 0],\n [52, 107, 0],\n [53, 107, 0],\n [54, 107, 0],\n [54, 107, 0],\n [55, 108, 0],\n [56, 108, 0],\n [57, 108, 0],\n [58, 108, 0],\n [59, 108, 0],\n [60, 108, 1],\n [61, 109, 1],\n [62, 109, 2],\n [63, 109, 2],\n [64, 109, 3],\n [65, 109, 3],\n [66, 110, 4],\n [67, 110, 4],\n [68, 110, 4],\n [69, 110, 5],\n [70, 110, 5],\n [71, 110, 6],\n [72, 111, 6],\n [73, 111, 7],\n [74, 111, 7],\n [75, 111, 8],\n [76, 111, 8],\n [77, 112, 9],\n [78, 112, 9],\n [79, 112, 10],\n [80, 112, 10],\n [81, 112, 11],\n [82, 112, 11],\n [83, 113, 12],\n [84, 113, 12],\n [85, 113, 13],\n [85, 113, 13],\n [86, 113, 14],\n [87, 114, 14],\n [88, 114, 15],\n [89, 114, 15],\n [90, 114, 16],\n [91, 114, 16],\n [92, 114, 17],\n [93, 115, 17],\n [94, 115, 18],\n [95, 115, 18],\n [96, 115, 19],\n [97, 115, 19],\n [98, 115, 20],\n [99, 116, 20],\n [100, 116, 20],\n [101, 116, 21],\n [102, 116, 21],\n [103, 116, 22],\n [104, 117, 22],\n [105, 117, 23],\n [106, 117, 23],\n [107, 117, 24],\n [108, 117, 24],\n [109, 118, 25],\n [110, 118, 25],\n [111, 118, 26],\n [112, 118, 26],\n [113, 118, 27],\n [114, 118, 27],\n [115, 119, 28],\n [116, 119, 28],\n [117, 119, 29],\n [118, 119, 29],\n [119, 119, 30],\n [120, 120, 30],\n [121, 120, 31],\n [122, 120, 31],\n [123, 120, 32],\n [124, 121, 32],\n [125, 121, 32],\n [126, 121, 33],\n [127, 122, 33],\n [128, 122, 34],\n [129, 122, 34],\n [130, 123, 35],\n [131, 123, 35],\n [132, 123, 36],\n [133, 124, 36],\n [134, 124, 37],\n [135, 124, 37],\n [136, 125, 37],\n [137, 125, 38],\n [138, 125, 38],\n [139, 126, 39],\n [139, 126, 39],\n [140, 126, 40],\n [141, 126, 40],\n [142, 127, 41],\n [143, 127, 41],\n [144, 127, 41],\n [145, 128, 42],\n [146, 128, 42],\n [147, 128, 43],\n [148, 129, 43],\n [149, 129, 44],\n [150, 129, 44],\n [151, 130, 45],\n [152, 130, 45],\n [153, 130, 45],\n [154, 131, 46],\n [155, 131, 46],\n [156, 131, 47],\n [157, 132, 47],\n [158, 132, 48],\n [159, 132, 48],\n [160, 133, 49],\n [161, 133, 49],\n [162, 133, 50],\n [163, 134, 50],\n [164, 134, 50],\n [165, 134, 51],\n [166, 135, 51],\n [167, 135, 52],\n [168, 135, 52],\n [169, 136, 53],\n [170, 136, 53],\n [171, 136, 54],\n [172, 137, 54],\n [173, 137, 54],\n [174, 137, 55],\n [175, 138, 55],\n [176, 138, 56],\n [177, 138, 56],\n [178, 139, 57],\n [179, 139, 57],\n [180, 139, 58],\n [181, 140, 58],\n [182, 140, 58],\n [183, 140, 59],\n [184, 141, 59],\n [185, 142, 62],\n [186, 144, 65],\n [187, 146, 68],\n [188, 147, 71],\n [189, 149, 74],\n [190, 151, 77],\n [192, 153, 80],\n [193, 155, 83],\n [194, 156, 86],\n [195, 158, 90],\n [196, 160, 93],\n [197, 162, 96],\n [198, 164, 99],\n [199, 165, 102],\n [201, 167, 105],\n [202, 169, 108],\n [203, 171, 111],\n [204, 173, 114],\n [205, 174, 117],\n [206, 176, 120],\n [207, 178, 123],\n [208, 180, 126],\n [210, 182, 130],\n [211, 184, 133],\n [212, 185, 136],\n [213, 187, 139],\n [214, 189, 142],\n [215, 191, 145],\n [216, 193, 148],\n [217, 194, 151],\n [219, 196, 154],\n [220, 198, 157],\n [221, 200, 160],\n [222, 202, 163],\n [223, 203, 166],\n [224, 205, 170],\n [225, 207, 173],\n [226, 209, 176],\n [228, 211, 179],\n [229, 212, 182],\n [230, 214, 185],\n [231, 216, 188],\n [232, 218, 191],\n [233, 220, 194],\n [234, 221, 197],\n [235, 223, 200],\n [237, 225, 203],\n [238, 227, 207],\n [239, 229, 210],\n [240, 230, 213],\n [241, 232, 216],\n [242, 234, 219],\n [243, 236, 222],\n [245, 238, 225],\n [246, 240, 228],\n [247, 241, 231],\n [248, 243, 234],\n [249, 245, 237],\n [250, 247, 240],\n [251, 249, 243],\n [252, 250, 247],\n [254, 252, 250],\n [255, 254, 253],\n [255, 255, 255],\n ]\n )\n\n cm = ListedColormap(C / 255.0)\n return cm", "def make_cell(dim, color, text, pos):\n text = SVG(\"text\", SVG(\"tspan\", text), x = pos[0], y = pos[1], stroke = \"none\", fill = color - 0x100)\n rect = SVG(\"rect\", x = pos[0], y = pos[1], width = dim, height = dim, fill = color)\n return Fig(text, rect).SVG()", "def _generate_character_map(self):\n self._ct = [-1] * 256\n index = 0\n for c_range in self._meta.character_ranges:\n for c_pos in range(c_range['min'], c_range['max'] + 1):\n self._ct[c_pos] = index\n index += 1", "def create_tile(self, mines, row, col):\n if row * self.cols + col in mines:\n return Tiles.mine\n return Tiles.zero", "def _text16(self, font, text, x0, y0, color=WHITE, background=BLACK):\n for char in text:\n ch = ord(char)\n if (font.FIRST <= ch < font.LAST\n and x0+font.WIDTH <= self.width\n and y0+font.HEIGHT <= self.height):\n\n each = 16\n if font.HEIGHT == 16:\n passes = 2\n size = 32\n else:\n passes = 4\n size = 64\n\n for line in range(passes):\n idx = (ch-font.FIRST)*size+(each*line)\n buffer = struct.pack(\n '>128H',\n color if font.FONT[idx] & _BIT7 else background,\n color if font.FONT[idx] & _BIT6 else background,\n color if font.FONT[idx] & _BIT5 else background,\n color if font.FONT[idx] & _BIT4 else background,\n color if font.FONT[idx] & _BIT3 else background,\n color if font.FONT[idx] & _BIT2 else background,\n color if font.FONT[idx] & _BIT1 else background,\n color if font.FONT[idx] & _BIT0 else background,\n color if font.FONT[idx+1] & _BIT7 else background,\n color if font.FONT[idx+1] & _BIT6 else background,\n color if font.FONT[idx+1] & _BIT5 else background,\n color if font.FONT[idx+1] & _BIT4 else background,\n color if font.FONT[idx+1] & _BIT3 else background,\n color if font.FONT[idx+1] & _BIT2 else background,\n color if font.FONT[idx+1] & _BIT1 else background,\n color if font.FONT[idx+1] & _BIT0 else background,\n color if font.FONT[idx+2] & _BIT7 else background,\n color if font.FONT[idx+2] & _BIT6 else background,\n color if font.FONT[idx+2] & _BIT5 else background,\n color if font.FONT[idx+2] & _BIT4 else background,\n color if font.FONT[idx+2] & _BIT3 else background,\n color if font.FONT[idx+2] & _BIT2 else background,\n color if font.FONT[idx+2] & _BIT1 else background,\n color if font.FONT[idx+2] & _BIT0 else background,\n color if font.FONT[idx+3] & _BIT7 else background,\n color if font.FONT[idx+3] & _BIT6 else background,\n color if font.FONT[idx+3] & _BIT5 else background,\n color if font.FONT[idx+3] & _BIT4 else background,\n color if font.FONT[idx+3] & _BIT3 else background,\n color if font.FONT[idx+3] & _BIT2 else background,\n color if font.FONT[idx+3] & _BIT1 else background,\n color if font.FONT[idx+3] & _BIT0 else background,\n color if font.FONT[idx+4] & _BIT7 else background,\n color if font.FONT[idx+4] & _BIT6 else background,\n color if font.FONT[idx+4] & _BIT5 else background,\n color if font.FONT[idx+4] & _BIT4 else background,\n color if font.FONT[idx+4] & _BIT3 else background,\n color if font.FONT[idx+4] & _BIT2 else background,\n color if font.FONT[idx+4] & _BIT1 else background,\n color if font.FONT[idx+4] & _BIT0 else background,\n color if font.FONT[idx+5] & _BIT7 else background,\n color if font.FONT[idx+5] & _BIT6 else background,\n color if font.FONT[idx+5] & _BIT5 else background,\n color if font.FONT[idx+5] & _BIT4 else background,\n color if font.FONT[idx+5] & _BIT3 else background,\n color if font.FONT[idx+5] & _BIT2 else background,\n color if font.FONT[idx+5] & _BIT1 else background,\n color if font.FONT[idx+5] & _BIT0 else background,\n color if font.FONT[idx+6] & _BIT7 else background,\n color if font.FONT[idx+6] & _BIT6 else background,\n color if font.FONT[idx+6] & _BIT5 else background,\n color if font.FONT[idx+6] & _BIT4 else background,\n color if font.FONT[idx+6] & _BIT3 else background,\n color if font.FONT[idx+6] & _BIT2 else background,\n color if font.FONT[idx+6] & _BIT1 else background,\n color if font.FONT[idx+6] & _BIT0 else background,\n color if font.FONT[idx+7] & _BIT7 else background,\n color if font.FONT[idx+7] & _BIT6 else background,\n color if font.FONT[idx+7] & _BIT5 else background,\n color if font.FONT[idx+7] & _BIT4 else background,\n color if font.FONT[idx+7] & _BIT3 else background,\n color if font.FONT[idx+7] & _BIT2 else background,\n color if font.FONT[idx+7] & _BIT1 else background,\n color if font.FONT[idx+7] & _BIT0 else background,\n color if font.FONT[idx+8] & _BIT7 else background,\n color if font.FONT[idx+8] & _BIT6 else background,\n color if font.FONT[idx+8] & _BIT5 else background,\n color if font.FONT[idx+8] & _BIT4 else background,\n color if font.FONT[idx+8] & _BIT3 else background,\n color if font.FONT[idx+8] & _BIT2 else background,\n color if font.FONT[idx+8] & _BIT1 else background,\n color if font.FONT[idx+8] & _BIT0 else background,\n color if font.FONT[idx+9] & _BIT7 else background,\n color if font.FONT[idx+9] & _BIT6 else background,\n color if font.FONT[idx+9] & _BIT5 else background,\n color if font.FONT[idx+9] & _BIT4 else background,\n color if font.FONT[idx+9] & _BIT3 else background,\n color if font.FONT[idx+9] & _BIT2 else background,\n color if font.FONT[idx+9] & _BIT1 else background,\n color if font.FONT[idx+9] & _BIT0 else background,\n color if font.FONT[idx+10] & _BIT7 else background,\n color if font.FONT[idx+10] & _BIT6 else background,\n color if font.FONT[idx+10] & _BIT5 else background,\n color if font.FONT[idx+10] & _BIT4 else background,\n color if font.FONT[idx+10] & _BIT3 else background,\n color if font.FONT[idx+10] & _BIT2 else background,\n color if font.FONT[idx+10] & _BIT1 else background,\n color if font.FONT[idx+10] & _BIT0 else background,\n color if font.FONT[idx+11] & _BIT7 else background,\n color if font.FONT[idx+11] & _BIT6 else background,\n color if font.FONT[idx+11] & _BIT5 else background,\n color if font.FONT[idx+11] & _BIT4 else background,\n color if font.FONT[idx+11] & _BIT3 else background,\n color if font.FONT[idx+11] & _BIT2 else background,\n color if font.FONT[idx+11] & _BIT1 else background,\n color if font.FONT[idx+11] & _BIT0 else background,\n color if font.FONT[idx+12] & _BIT7 else background,\n color if font.FONT[idx+12] & _BIT6 else background,\n color if font.FONT[idx+12] & _BIT5 else background,\n color if font.FONT[idx+12] & _BIT4 else background,\n color if font.FONT[idx+12] & _BIT3 else background,\n color if font.FONT[idx+12] & _BIT2 else background,\n color if font.FONT[idx+12] & _BIT1 else background,\n color if font.FONT[idx+12] & _BIT0 else background,\n color if font.FONT[idx+13] & _BIT7 else background,\n color if font.FONT[idx+13] & _BIT6 else background,\n color if font.FONT[idx+13] & _BIT5 else background,\n color if font.FONT[idx+13] & _BIT4 else background,\n color if font.FONT[idx+13] & _BIT3 else background,\n color if font.FONT[idx+13] & _BIT2 else background,\n color if font.FONT[idx+13] & _BIT1 else background,\n color if font.FONT[idx+13] & _BIT0 else background,\n color if font.FONT[idx+14] & _BIT7 else background,\n color if font.FONT[idx+14] & _BIT6 else background,\n color if font.FONT[idx+14] & _BIT5 else background,\n color if font.FONT[idx+14] & _BIT4 else background,\n color if font.FONT[idx+14] & _BIT3 else background,\n color if font.FONT[idx+14] & _BIT2 else background,\n color if font.FONT[idx+14] & _BIT1 else background,\n color if font.FONT[idx+14] & _BIT0 else background,\n color if font.FONT[idx+15] & _BIT7 else background,\n color if font.FONT[idx+15] & _BIT6 else background,\n color if font.FONT[idx+15] & _BIT5 else background,\n color if font.FONT[idx+15] & _BIT4 else background,\n color if font.FONT[idx+15] & _BIT3 else background,\n color if font.FONT[idx+15] & _BIT2 else background,\n color if font.FONT[idx+15] & _BIT1 else background,\n color if font.FONT[idx+15] & _BIT0 else background\n )\n self.blit_buffer(buffer, x0, y0+8*line, 16, 8)\n x0 += font.WIDTH", "def __init__(self, font, color=(255,255,255,255)):\r\n if not font.endswith('.png'):\r\n font += '.png'\r\n super(Pngfont, self).__init__(\"fonts/%s\" % font)\r\n self.font = font\r\n pixels = self.im.load()\r\n\r\n self.glyph_table = {}\r\n # Extract font information from top scanline of font image; create width,\r\n # height, tex_coord and vertices for each character.\r\n for v in range(95):\r\n x = (pixels[v * 2, 0][0] * 2.0) / self.ix\r\n y = ((pixels[v * 2, 0][1] + 8) * 2.0) / self.iy\r\n width = float(pixels[v * 2 + 1, 0][0])\r\n height = float(pixels[v * 2 + 1, 0][1])\r\n width_scale = width / self.ix\r\n height_scale = height / self.iy\r\n\r\n self.glyph_table[v] = [width, height,\r\n [(x + width_scale, y - height_scale),\r\n (x, y - height_scale),\r\n (x, y),\r\n (x + width_scale, y)],\r\n [(width, 0, 0), (0, 0, 0), (0, -height, 0), (width, -height, 0)]]\r\n\r\n alph = self.im.split()[-1] #keep alpha\r\n draw = ImageDraw.Draw(self.im)\r\n draw.rectangle((0, 1, self.ix, self.iy), fill=color)\r\n self.im.putalpha(alph)\r\n\r\n RGBs = 'RGBA' if self.alpha else 'RGB'\r\n self.image = self.im.convert(RGBs).tostring('raw', RGBs)\r\n self._tex = ctypes.c_int()", "def create_char(self, location, bitmap):\n if not (0 <= location <= 7):\n raise ValueError('Only locations 0-7 are valid.')\n if len(bitmap) != 8:\n raise ValueError('Bitmap should have exactly 8 rows.')\n\n # Store previous position\n pos = self.cursor_pos\n\n # Write character to CGRAM\n self.command(_LCD_SETCGRAMADDR | location << 3)\n for row in bitmap:\n self._send(row, _RS_DATA)\n\n # Restore cursor pos\n self.cursor_pos = pos", "def create_char(self, location, bitmap):\n assert 0 <= location <= 7, 'Only locations 0-7 are valid.'\n assert len(bitmap) == 8, 'Bitmap should have exactly 8 rows.'\n\n # Store previous position\n pos = self.cursor_pos\n\n # Write character to CGRAM\n self.command(self.LCD_SETCGRAMADDR | location << 3)\n for row in bitmap:\n self._send(row, self.RS_DATA)\n\n # Restore cursor pos\n self.cursor_pos = pos" ]
[ "0.58362615", "0.5499941", "0.53657395", "0.5182974", "0.5153799", "0.51268566", "0.51066536", "0.50781935", "0.507169", "0.501892", "0.50151426", "0.49879408", "0.4963365", "0.49593616", "0.49591786", "0.49389654", "0.4933736", "0.4921736", "0.49056354", "0.48952273", "0.48916602", "0.4874848", "0.48567742", "0.48419046", "0.48336518", "0.48250902", "0.48124605", "0.4809267", "0.480823", "0.4778646" ]
0.66264325
0
Returns subimage for given letter.
def get_letter_image(self, letter): assert len(letter) == 1 return ImageRegion(self._tileset, self._bound_rects[letter])
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_letter_image(self, letter):\n\t\tassert len(letter) == 1\n\t\treturn self._tileset.get_tile(self._letter_mapping[letter])", "def get_letter_image(self, letter): # pragma: no cover\n\t\traise NotImplementedError()", "def select_object_from_letter(self, letter):\n\t\tindex = ALPHABET.index(letter)\n\t\treturn self.select_object_at_index(index)", "def extract_letters(im):\r\n # Find indices of the 6 horizontal lines and 12 vertical lines of the letters\r\n hor_indices, ver_indices, _, _ = find_longest_lines(im)\r\n hor_lines = sorted(hor_indices[2:8])\r\n ver_lines = sorted(ver_indices[:12])\r\n im_edge = cv2.Canny(im, 50, 100)\r\n \r\n # Extract each letter\r\n letters = []\r\n data = np.load('data.npy')\r\n z = 0\r\n for i in range(2):\r\n for j in range(6):\r\n im_letter = im[hor_lines[i*3]: hor_lines[i*3 + 1], ver_lines[j*2] : ver_lines[j*2 + 1]]\r\n im_letter = imresize(im_letter, (15, 15), 'bicubic') > 75\r\n# im_letter = im_letter.astype(int)\r\n letter = chr(np.argmin(np.sum(np.sum(np.abs(data - im_letter), 1), 1)) + ord('a'))\r\n letters.append(letter)\r\n z += 1\r\n \r\n return letters", "def subimage(self, *args, **kwargs):\n return _image.image_subimage(self, *args, **kwargs)", "def find_letters(line_image):\r\n\r\n\tif line_image.shape[0] < 40:\r\n\t\tline_image = cv2.resize(line_image, (line_image.shape[1] * 2, line_image.shape[0] * 2))\r\n\r\n\t#binary\r\n\tret,thresh = cv2.threshold(line_image, 109, 255, cv2.THRESH_BINARY_INV)\r\n\r\n\tif cv2.__version__.startswith('3.'):\r\n\t\tim2, ctrs, hier = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\r\n\telse:\r\n\t\t(ctrs, __) = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\r\n\r\n\t#sort contours\r\n\tsorted_ctrs = sorted(ctrs, key=lambda ctr: cv2.boundingRect(ctr)[0], reverse=True)\r\n\r\n\t#creating objects - so we coult hold a few arguments that connected together in the same variable\r\n\r\n\tclass contur:\r\n\t\tdef __init__(self, x, y, w, h):\r\n\t\t\tself.x_start = x\r\n\t\t\tself.y_start = y\r\n\t\t\tself.x_end = x + w\r\n\t\t\tself.y_end = y + h\r\n\r\n\tletters_images = list()\r\n\tnew_ctr = list()\r\n\r\n\tfor j, ctr in enumerate(sorted_ctrs):\r\n\t\tx, y, w, h = cv2.boundingRect(ctr)\r\n\t\tc = contur(x, y, w, h)\r\n\t\tnew_ctr.append(c)\r\n\r\n\tlength = len(new_ctr)\r\n\r\n\ti = 0\r\n\twhile i < length:\r\n\t\tx, y, w, h = cv2.boundingRect(sorted_ctrs[i])\r\n\r\n\t\tif h > 3:\r\n\t\t\tcanvas = np.ones_like(line_image)\r\n\t\t\tcanvas.fill(255)\r\n\t\t\tcv2.drawContours(canvas, sorted_ctrs, i, (0, 0, 0), 3)\r\n\r\n\t\t\tif i < length - 1 and new_ctr[i].x_start >= new_ctr[i + 1].x_start and new_ctr[i].x_end <= new_ctr[i + 1].x_end:\r\n\t\t\t\tY_end_bigger = max(new_ctr[i].y_end, new_ctr[i + 1].y_end)\r\n\t\t\t\tcv2.drawContours(canvas, sorted_ctrs, i + 1, (0, 0, 0), 3)\r\n\r\n\t\t\t\tif union_left_ctr(new_ctr[i], new_ctr[i+1], canvas) == 0:\r\n\t\t\t\t\troi = canvas[y:y + h, x:x + w]\r\n\t\t\t\t\troiriginal = line_image[y:y + h, x:x + w]\r\n\t\t\t\telse:\r\n\t\t\t\t\troi = canvas[new_ctr[i + 1].y_start:Y_end_bigger, new_ctr[i + 1].x_start:new_ctr[i + 1].x_end]\r\n\t\t\t\t\troiriginal = line_image[new_ctr[i + 1].y_start:Y_end_bigger, new_ctr[i + 1].x_start:new_ctr[i + 1].x_end]\r\n\t\t\t\t\ti += 1\r\n\t\t\telse:\r\n\t\t\t\troi = canvas[y:y + h, x:x + w]\r\n\t\t\t\troiriginal = line_image[y:y + h, x:x + w]\r\n\r\n\t\t\tletter = np.pad(roiriginal, pad_width=10, mode='constant', constant_values=255)\r\n\r\n\t\t\tletters_images.append(letter)\r\n\t\ti += 1\r\n\treturn letters_images", "def subimage(self, *args, **kwargs):\n return _coordsys.coordsys_subimage(self, *args, **kwargs)", "def _find_letters(self):\r\n\r\n letter_boxes = find_letter_boxes(self.img, MAXIMUM_LETTER_LENGTH)\r\n letters = [self.img.crop((letter_box[0], 0, letter_box[1], self.img.height)) for letter_box in letter_boxes]\r\n\r\n if (len(letters) == 6 and letters[0].width < MINIMUM_LETTER_LENGTH) or (len(letters) != 6 and len(letters) != 7):\r\n letters = [Image.new('L', (200, 70)) for i in range(6)]\r\n\r\n if len(letters) == 7:\r\n letters[6] = merge_horizontally(letters[6], letters[0])\r\n del letters[0]\r\n\r\n letters = [cut_the_white(letter) for letter in letters]\r\n self.letters = {str(k): v for k, v in zip(range(1, 7), letters)}", "def get_img_by_char(char, base_path='../../dataset/nums'):\n opdict = {'+': 10, '-': 11, '*': 12, '/': 13, '=': 14, '(': 15, ')': 16}\n if char in opdict.keys():\n char = opdict[char]\n path = os.path.join(base_path, str(char))\n files = os.listdir(path)\n\n rdm = random.randint(0, len(files) - 1)\n\n if rdm >= len(files):\n print(path, len(files), rdm)\n\n file = files[rdm]\n path = os.path.join(path, file)\n return cv2.imread(path, cv2.IMREAD_GRAYSCALE)", "def _return_char(num_image):\n\n # check image (segment) against the full dictionary of\n # characters and return first match\n for digit, digit_image in DIGITDICT_FULL.items():\n if _np.array_equal(digit_image, num_image):\n return digit\n\n # if no match found then return None\n return None", "def GetSubBitmap(*args, **kwargs):\n return _gdi_.Bitmap_GetSubBitmap(*args, **kwargs)", "def extractImage(self, data, offset=0.0, subpixel=False):\n offset = self.imageOffset + offset * self.sampleRate / self.downsample\n intOffset = int(np.floor(offset))\n fracOffset = offset - intOffset\n\n shape = self.imageShape\n stride = self.imageStride\n\n if subpixel and fracOffset != 0:\n print(fracOffset)\n interp = data[:-1] * (1.0 - fracOffset) + data[1:] * fracOffset\n image = pg.subArray(interp, intOffset, shape, stride) \n else:\n image = pg.subArray(data, intOffset, shape, stride)\n\n if self.bidirectional:\n image = image.copy()\n image[:, 1::2] = image[:, 1::2, ::-1]\n\n return image", "def get_tile(self, char):\n if char == \"#\":\n return self.tiles[0:32, 0:32]\n elif char == \"G\": # gates\n return self.tiles[8 * 32 : 9 * 32, 3 * 32 : 4 * 32] \n elif char == \"W\": # window\n return self.tiles[8 * 32 : 9 * 32, 4 * 32 : 5 * 32]\n elif char == \"C\": # checkout\n return self.tiles[2 * 32 : 3 * 32, 8 * 32 : 9 * 32]\n elif char == \"F\": # fruits\n return self.tiles[1 * 32 : 2 * 32, 4 * 32 : 5 * 32] \n elif char == \"S\": # spices\n return self.tiles[1 * 32 : 2 * 32, 3 * 32 : 4 * 32] \n elif char == \"R\": # dairy\n return self.tiles[8 * 32 : 9 * 32, 7 * 32 : 8 * 32] \n elif char == \"D\": # drinks\n return self.tiles[6 * 32 : 7 * 32, 13 * 32 : 14 * 32] \n elif char == \"c\": # customer/shopping cart\n return self.tiles[8 * 32 : 9 * 32, 6 * 32 : 7 * 32] \n else:\n return self.tiles[32:64, 64:96]", "def letter(leaf):\n return root(branches(leaf)[0])", "def getFENtileLetter(fen,letter,number):\n l2i = lambda l: ord(l)-ord('A') # letter to index\n piece_letter = fen[(8-number)*8+(8-number) + l2i(letter)]\n return ' KQRBNPkqrbnp'.find(piece_letter)", "def extract_single(self, sub_h, sub_w, zoom_min=2, zoom_max=4, margin=10, write_path=None):\n\n k = np.random.randint(0, len(self.collection.short_fnames))\n\n name = self.collection.short_fnames[k]\n bg = self.collection.imgs[k]\n big_h, big_w, _ = bg.shape\n\n zoomed_h, zoomed_w = self._zoom(sub_h, sub_w, zoom_min, zoom_max)\n\n if 'fs' in name:\n # print('fs bg')\n zoomed_h = sub_h\n zoomed_w = sub_w\n\n circumscribe_radius = np.ceil(np.sqrt(zoomed_h ** 2 + zoomed_w ** 2))\n circumscribe_radius = int(circumscribe_radius) + margin\n\n cen_x = np.random.randint(circumscribe_radius, big_w - circumscribe_radius)\n cen_y = np.random.randint(circumscribe_radius, big_h - circumscribe_radius)\n\n x1 = int(cen_x - circumscribe_radius / 2)\n y1 = int(cen_y - circumscribe_radius / 2)\n\n x2 = int(cen_x + circumscribe_radius / 2)\n y2 = int(cen_y + circumscribe_radius / 2)\n\n raw_crop = bg[y1:y2, x1:x2]\n # cv2.imshow('raw crop',raw_crop)\n\n rotated = self._rotate(raw_crop, zoomed_h, zoomed_w)\n rotated = cv2.resize(rotated, (sub_w, sub_h))\n\n img = self._bg_augmentation(rotated)\n # cv2.imshow('rotated',rotated)\n # print(rotated.shape)\n\n if write_path is not None:\n cv2.imwrite(write_path, img)\n return img", "def _get_rot_letter(self, letter, rot, operation, alphabet):\n if len(letter) != 1:\n raise ValueError(\"'letter' deve ter length 1.\")\n\n if letter not in alphabet:\n letter_new = letter\n\n else:\n letter_pos = alphabet.index(letter)\n letter_new = alphabet[operation(letter_pos, rot) % len(alphabet)]\n \n return letter_new", "def letter_for(label):\n return \"ABCDEFGHIJ\"[label]", "def generete_string(input_image, p, letters, bigrams, alphabet_list, mask):\n output_string = []\n width_prev_letter = 0\n \n p_k = bigrams[-2,:]\n while input_image[:,width_prev_letter:].size != 0:\n # cut input_image based on previous letter\n input_image = input_image[:,width_prev_letter:]\n # cut mask based on input_image\n mask = mask[:,width_prev_letter:]\n # calculate probabilities for the first letter\n sum_of_probab = calculate_tail(input_image,p,letters,p_k,mask)\n pk1 = letter_probab(input_image,p,letters,sum_of_probab,p_k,mask)\n # generate letter from probability\n generated_letter = np.random.choice(len(pk1), 1, p=list(pk1/pk1.sum()))[0]\n p_k = bigrams[generated_letter,:]\n width_prev_letter = letters[generated_letter].shape[1]\n # get generated letter\n output_string.append(alphabet_list[generated_letter])\n return ''.join(output_string)", "def get_tile_bitmap(self, char):\n if char == '#':\n return self.tiles[0:32, 0:32, :]\n elif char == 'b':\n return self.tiles[0:32, 128:160, :]\n elif char == 'd':\n return self.tiles[64:96, 128:160, :]\n elif char == 'w':\n return self.tiles[96:128, 128:160, :]\n elif char == 'a':\n return self.tiles[96:128, 160:192, :]\n elif char == 'q':\n return self.tiles[32:64, 128:160, :]\n elif char == 'p':\n return self.tiles[64:96, 192:224, :]\n elif char == 'x':\n return self.tiles[128:160, 128:160, :]\n elif char == 'y':\n return self.tiles[192:224, 96:128, :]\n elif char == 'z':\n return self.tiles[160:192, 96:128, :]\n elif char == 'm':\n return self.tiles[96:128, 224:256, :]\n elif char == 's':\n return self.tiles[32:64, 0:32, :]\n else:\n return self.tiles[32:64, 64:96, :]", "def subimage(image_as_array, step):\r\n\tsubimage_2d_array = image_as_array[200-int(step):200+int(step)]\r\n\treturn subimage_2d_array", "def sub_word(word):\n bytes = [(word >> i & 0xff) for i in (24, 16, 8, 0)]\n return create_word([(s_box[bytes[i]]) for i in range(4)])", "def _get_digit(binary, label_image, digit):\n ymin, ymax = _np.where(label_image == digit)[0].min(), \\\n _np.where(label_image == digit)[0].max() + 1\n xmin, xmax = _np.where(label_image == digit)[1].min(), \\\n _np.where(label_image == digit)[1].max() + 1\n\n return binary[ymin:ymax, xmin:xmax]", "def next_letter(letter):\r\n\tcoded_text = ''\r\n\tstep = 1\r\n\tif letter in ascii_lowercase:\r\n\t\tcoded_text = coded_text + ascii_lowercase[ascii_lowercase.index(letter) + step % len(ascii_lowercase)]\r\n\r\n\tif letter in ascii_uppercase:\r\n\t\tcoded_text = coded_text + ascii_uppercase[ascii_uppercase.index(letter) + step % len(ascii_uppercase)]\r\n\r\n\telse:\r\n\t\tcoded_text += text\r\n\r\n\treturn coded_text", "def getsubString(w, c):\n count = 0\n for x in w:\n if x == c:\n break\n count=count+1\n return w[:count]", "def _extractGlyph(self, char):\n charno = ord(char)\n vertices = None\n currentGlyph = None\n\n if charno in self.extracted:\n currentGlyph = self.extracted[charno]\n else:\n if char in ('\\n', ):\n # No glyph for these chars\n pass\n else:\n glyph = self.font.getGlyph(charno, self.glyphs)\n if glyph is None:\n save_char = char\n save_charno = charno\n # Use '.notdef' glyph if it is defined in the font\n repcharno = None\n if self.glyphs != GlyphTypes.CBDT_COLOR:\n glyph = self.font.getGlyph(repcharno, self.glyphs)\n if glyph is None:\n # Use WHITE SQUARE gplyph: \\u25A1\n repcharno = 9633\n glyph = self.font.getGlyph(repcharno, self.glyphs)\n if glyph is None:\n # Still None? Replace character with blank\n repcharno = 32\n glyph = self.font.getGlyph(repcharno, self.glyphs)\n charno = 32\n char = chr(charno)\n if glyph is None:\n self.logger.error(\"Font %s has no space\"\n \" character!\" % self.font.fontFile)\n\n self.logger.warning(\"Char %r (%d) not found in\"\n \" font %s has been replaced with chr(%s)\"\n % (save_char, save_charno, self.font.fontFile,\n repcharno))\n\n currentGlyph = glyph\n self.extracted[charno] = currentGlyph\n\n if currentGlyph is not None and 'vertices' in currentGlyph:\n vertices = currentGlyph['vertices'].copy()\n\n return char, vertices, currentGlyph", "def index_letter(self, index):\n\t\treturn ALPHABET[index]", "def get_new_letter(letter, my_type):\n uppercase = [\"A\",\"B\",\"C\",\"D\",\"E\",\"F\",\"G\",\"H\",\"I\",\"J\",\"K\",\"L\",\"M\",\"N\",\"O\",\"P\",\"Q\",\"R\",\"S\",\"T\",\"U\",\"V\",\"W\",\"X\",\"Y\",\"Z\"]\n lowercase = [\"a\",\"b\",\"c\",\"d\",\"e\",\"f\",\"g\",\"h\",\"i\",\"j\",\"k\",\"l\",\"m\",\"n\",\"o\",\"p\",\"q\",\"r\",\"s\",\"t\",\"u\",\"v\",\"w\",\"x\",\"y\",\"z\"]\n if my_type == \"upper\":\n for i in range(0,len(lowercase)):\n if lowercase[i] == letter:\n return uppercase[i]\n else:\n for i in range(0,len(uppercase)):\n if uppercase[i] == letter:\n return lowercase[i]", "def _get_row_fow_letter(cls, letter):\n row_map = {\n 'A': 1, 'B': 2, 'C': 3, 'D': 4, 'E': 5,\n 'F': 6, 'G': 7, 'H': 8, 'I': 9, 'J': 10,\n }\n try:\n return row_map[letter]\n except KeyError:\n raise ValueError('The letter of the row must '\n 'be between A to J uppercase')", "def getIndexForSubGlyph(self, *args):\n return _libsbml.GeneralGlyph_getIndexForSubGlyph(self, *args)" ]
[ "0.76579726", "0.73898816", "0.66551983", "0.63486063", "0.61542475", "0.6099315", "0.59665734", "0.58227265", "0.5736932", "0.56307167", "0.5630472", "0.5580798", "0.5493414", "0.54799604", "0.5448674", "0.5376145", "0.53500587", "0.53446937", "0.53319925", "0.53206825", "0.53144056", "0.5304213", "0.53029156", "0.52939904", "0.52933663", "0.5291722", "0.5283493", "0.5263432", "0.52627856", "0.52409935" ]
0.78910303
0
removes list of outliers keys from dict object
def remove_outlier(keys): for key in keys: data_dict.pop(key, 0)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def remove_outlier(dict_object, keys):\n for key in keys:\n dict_object.pop(key, 0)", "def remove_outlier(dict_object, keys):\r\n for key in keys:\r\n dict_object.pop(key, 0)", "def prune(candidate_aspect_list, min_sup):\n l_k = deepcopy(candidate_aspect_list)\n for key, value in list(l_k.items()):\n if value < min_sup:\n del l_k[key]\n return l_k", "def evictOldkeys(self, cutOff):\n for key in self.values.keys():\n time = self.values[key][3]\n if time < cutOff:\n del self.values[key]", "def remove_keys_from_dict(dictionary, keys):\n\n # Copy dictionary\n dictionary_updated = dictionary.copy()\n try:\n [dictionary_updated.pop(key) for key in keys]\n except:\n print(\"Error: No ratio and sampling strategy parameters\")\n return dictionary_updated", "def declutter(vector):\n for key in vector:\n clutter_values = [value for value in vector[key] if vector[key][value]<2] # gather everything with a value less than two and save it in a list\n for feature in clutter_values: # remove everything in the clutter values from a dictionary\n vector[key].pop(feature,None)\n return vector", "def outlierCleaner(predictions, ages, net_worths):\n import operator\n cleaned_data = []\n temp = {}\n ### your code goes here\n \n for i in range(len(ages)):\n error = predictions[i] - net_worths[i]\n temp[i] = error\n #print temp\n sorted_x = sorted(temp.items(), key=operator.itemgetter(1))\n sorted_x.reverse() \n #print sorted_x\n ten_p = (int)(0.1*len(ages))\n poop = sorted_x[(ten_p):]\n \n for item in poop:\n idx = item[0]\n cleaned_data.append((ages[idx],net_worths[idx],item[1][0]))\n \n return cleaned_data", "def eliminate(self):\n deleteKey = []\n for key,value in self._sets[self._currentSet].items():\n if value < self._minSupport:\n deleteKey.append(key)\n \n for key in deleteKey:\n del self._sets[self._currentSet][key]", "def cut(d, k):\n\tif isinstance(d, dict):\n\t\tn = d.copy()\n\t\tif k in n:\n\t\t\tdel n[k]\n\t\treturn n\n\treturn [v for v in d if v != k]", "def remove_spikes(spt_dict, remove_dict, tolerance):\n spt_data = spt_dict['data']\n spt_remove = remove_dict['data']\n\n mn, mx = tolerance\n\n for t in spt_remove:\n spt_data = spt_data[(spt_data > (t + mx)) | (spt_data < (t + mn))]\n\n spt_ret = spt_dict.copy()\n spt_ret['data'] = spt_data\n return spt_ret", "def clean_dict_stats(stats):\n for i in range(len(stats)):\n if 'plots' in stats[i].keys():\n del stats[i]['plots']\n\n return stats", "def _filter_dict(src_dict, key_set):\n for k in set(src_dict.keys()) - key_set:\n src_dict.pop(k)", "def remove_outlier_lengths(data, quantile: float = 0.995):\n throw_away_ixs = {}\n for dataset, splits in data.items():\n throw_away_ixs[dataset] = {}\n for split, split_set in splits.items():\n if split == 'test':\n # we don't want to remove test samples.\n continue\n lengths = np.array([len(example.text) for example in split_set.examples])\n keep_lengths = lengths < np.quantile(lengths, quantile)\n throw_away = (keep_lengths == 0).nonzero()[0]\n for ix in throw_away:\n del split_set.examples[ix]\n throw_away_ixs[dataset][split] = throw_away\n return throw_away_ixs", "def clean(self):\n newDict = {}\n for element, value in self.focals.items():\n if value >= MassFunction.precision:\n newDict[element] = value\n self.focals = newDict", "def sup_dicti(self, x, y):\n for key in self.dict_possiblity:\n if x in self.dict_possiblity[key]:\n self.dict_possiblity[key].remove(x)\n if y in self.dict_possiblity[key]:\n self.dict_possiblity[key].remove(y)\n del self.dict_possiblity[y]\n del self.dict_possiblity[x]", "def filter_dic_by_keys(dic,allowed_keys):\n new_dic = {}\n for key in dic:\n if key in allowed_keys:\n new_dic[key] = dic[key]\n return new_dic", "def clean_up_map(self):\n self.items = [i for i in self.items if i.quantity != 0]", "def _dict_clean(self, obj: list[tuple[str, Any]]) -> dict[str, Any]:\n\n result = {}\n for k, v in obj:\n if v is None and k in ['revenue', 'value', 'tags', 'decisions']:\n continue\n else:\n result[k] = v\n return result", "def clearKeys(self):\n for attr in self._filter():\n pm.cutKey(attr)", "def remove_unused_keys(cop):\n delete_these = [\n 'officer_atty',\n 'officer_atty_firm',\n 'case_id',\n 'cop_first_name',\n 'cop_middle_initial',\n 'cop_last_name',\n 'entered_by',\n 'entered_when',\n 'fact_checked_by',\n 'fact_checked_when',\n 'matched_by',\n 'matched_when'\n ]\n\n for key in delete_these:\n del cop[key]\n\n return cop", "def delete_outliers_after_incognito(data: np.ndarray, k: int, qi_indices: np.ndarray):\n c = Counter(str(e) for e in data[:, qi_indices])\n to_eliminate = {t: count for t, count in c.items() if count < k}\n\n idx_to_del = []\n done = False\n for key in to_eliminate:\n for j in range(data.shape[0]):\n if str(data[j, qi_indices]) == str(key):\n if not done:\n idx_to_del = j\n done = True\n else:\n idx_to_del = np.append(idx_to_del, j)\n return np.delete(data, idx_to_del, axis=0)", "def purge_outlying_trials(self, trial_nums, thresh=5.0):\n for injkey in self.values.keys():\n for fit_key in self.values[injkey].keys():\n points = np.array(self.values[injkey][\n fit_key]['metric_val']['vals'])\n if len(points.shape) == 1:\n points = points[:, None]\n median = np.median(points, axis=0)\n diff = np.sum((points - median)**2, axis=-1)\n diff = np.sqrt(diff)\n med_abs_deviation = np.median(diff)\n modified_z_score = 0.6745 * diff / med_abs_deviation\n good_trials = modified_z_score < thresh\n if not np.all(good_trials):\n bad_trials = np.where(not good_trials)[0]\n logging.warning(\n 'Outlier(s) detected for %s in trial(s) %s. Will be '\n 'removed. If you think this should not happen, please '\n 'change the value of the threshold used for the '\n 'decision (currently set to %.2e).'%(\n fit_key, trial_nums[bad_trials], thresh\n )\n )\n for fitkey in self.values[injkey].keys():\n for param in self.values[injkey][fitkey].keys():\n new_vals = np.delete(\n np.array(self.values[injkey][\n fitkey][param]['vals']),\n bad_trials\n )\n self.values[injkey][\n fitkey][param]['vals'] = new_vals", "def _remove_additional_elements(self):\n # Produces a list of keys in sample sorted by seed\n sorted_elements = sorted(self.elements.items(), key=lambda x: x[1][0])\n\n # Removes the keys with largest seed values (beyond the\n # first k keys)\n for i in range(self.k, len(sorted_elements)):\n del self.elements[sorted_elements[i][0]]", "def task_2_remove_dict_fields(data: DT, redundant_keys: List[str]) -> DT:\n return [{key: value for key, value in dic.items() if key not in redundant_keys} for dic in data]", "def _remove_additional_elements(self):\n # Produces a list of keys in sample sorted by seed\n sorted_elements = sorted(self.elements.items(), key=lambda x: x[1][0])\n\n # Removes the keys with largest seed values (beyond the first k keys)\n for i in range(self.k, len(sorted_elements)):\n del self.elements[sorted_elements[i][0]]", "def _filter_denies(self, filtered_ref):\n for deny in self.denies_:\n if not deny:\n continue\n\n for ref_key in filtered_ref.ref_keys(deny):\n del filtered_ref[ref_key]", "def prune(bushy: dict) -> dict:\n pruned = dict()\n for key in bushy:\n if bushy[key]:\n pruned[key] = bushy[key]\n return pruned", "def prune_result(self, mc_res):\n mc_res_prune = {}\n for v in list(mc_res.keys()):\n mc_res_prune[(v[1], v[2])] = mc_res[v]\n return mc_res_prune", "def remove_updated_from_dicts(fit, dicts, squares_coords):\n row, col, n = fit\n rm, cm, sm = dicts\n sq = squares_coords\n rm[row].remove(n)\n cm[col].remove(n)\n sm[squares_coords[row, col]].remove(n)\n del sq[(row, col)]\n return dicts", "def _removeInsufficientTransformer(self, working_stats, params):\n\n for choice, subsets in working_stats.items():\n sufficient_values = [value for value in subsets if value > 0]\n if not sufficient_values:\n del working_stats[choice]\n\n return working_stats" ]
[ "0.7666286", "0.764993", "0.6490826", "0.62917334", "0.61497504", "0.60963714", "0.60686636", "0.60594124", "0.60409945", "0.6001855", "0.59809375", "0.59354466", "0.5890583", "0.5846965", "0.5815032", "0.58145547", "0.58056134", "0.58049035", "0.57859176", "0.5770592", "0.5738165", "0.5731691", "0.57183754", "0.5702619", "0.5690311", "0.5667594", "0.5643695", "0.5638865", "0.5632025", "0.5631308" ]
0.794232
0
Calculate a bitmap for use as a wx frame background with rounded corners.
def _get_round_edges_bitmap(width: int, height: int, radius: int): mask_color = opts['gui']['attrs']['mask_color'] background_color = opts['gui']['attrs']['background_color'] bitmap = wx.Bitmap(width, height) dc = wx.MemoryDC(bitmap) dc.SetBrush(wx.Brush(mask_color)) dc.DrawRectangle(0, 0, width, height) dc.SetBrush(wx.Brush(background_color)) dc.SetPen(wx.Pen(background_color)) dc.DrawRoundedRectangle(0, 0, width, height, radius) bitmap.SetMaskColour(mask_color) return bitmap
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def GetRoundBitmap(w, h, r):\n maskColor = wx.Colour(0, 0, 0)\n shownColor = wx.Colour(5, 5, 5)\n b = wx.Bitmap(w, h)\n dc = wx.MemoryDC(b)\n dc.SetBrush(wx.Brush(maskColor))\n dc.DrawRectangle(0, 0, w, h)\n dc.SetBrush(wx.Brush(shownColor))\n dc.SetPen(wx.Pen(shownColor))\n dc.DrawRoundedRectangle(0, 0, w, h, r)\n dc.SelectObject(wx.NullBitmap)\n b.SetMaskColour(maskColor)\n return b", "def render_background(self, width=608, height=342):\n img_path = IMG_PATH + os.sep + CARD_BACKGROUND\n bg_img = Image.open(img_path)\n bg_img = bg_img.resize((width, height))\n bg_img = self._add_corners(bg_img, rad=30)\n return bg_img", "def CreateBitmap(self):\r\n\r\n memory = wx.MemoryDC()\r\n\r\n bitmap = wx.EmptyBitmap(self._total_w, self._total_h)\r\n memory.SelectObject(bitmap)\r\n\r\n if wx.Platform == '__WXMAC__':\r\n memory.SetBackground(wx.TRANSPARENT_BRUSH)\r\n else:\r\n memory.SetBackground(wx.Brush(self._backgroundColour))\r\n memory.SetBackgroundMode(wx.TRANSPARENT)\r\n memory.SetFont(self._font)\r\n memory.SetTextForeground(self._colour)\r\n memory.Clear()\r\n\r\n if self._itemimage:\r\n memory.DrawBitmap(self._itemimage, self._ximagepos, self._yimagepos, True)\r\n\r\n if self._itemcheck:\r\n memory.DrawBitmap(self._itemcheck, self._xcheckpos, self._ycheckpos, True)\r\n\r\n textrect = wx.Rect(self._xtextpos, self._ytextpos+self._extraH, self._textwidth, self._textheight)\r\n memory.DrawLabel(self._text, textrect)\r\n\r\n memory.SelectObject(wx.NullBitmap)\r\n \r\n # Gtk and Windows unfortunatly don't do so well with transparent\r\n # drawing so this hack corrects the image to have a transparent\r\n # background.\r\n if wx.Platform != '__WXMAC__':\r\n timg = bitmap.ConvertToImage()\r\n if not timg.HasAlpha():\r\n timg.InitAlpha()\r\n for y in xrange(timg.GetHeight()):\r\n for x in xrange(timg.GetWidth()):\r\n pix = wx.Colour(timg.GetRed(x, y),\r\n timg.GetGreen(x, y),\r\n timg.GetBlue(x, y))\r\n if pix == self._backgroundColour:\r\n timg.SetAlpha(x, y, 0)\r\n bitmap = timg.ConvertToBitmap()\r\n return bitmap", "def PaneCreateStippleBitmap():\r\n\r\n data = [0, 0, 0, 192, 192, 192, 192, 192, 192, 0, 0, 0]\r\n img = wx.EmptyImage(2, 2)\r\n counter = 0\r\n \r\n for ii in xrange(2):\r\n for jj in xrange(2):\r\n img.SetRGB(ii, jj, data[counter], data[counter+1], data[counter+2])\r\n counter = counter + 3\r\n \r\n return img.ConvertToBitmap()", "def background_maker():\n background = GRect(window.width, window.height)\n background.filled = True\n background.fill_color = '0xFFFCEC'\n background.color = '0xFFFCEC'\n return background", "def draw_background(self):\n back = pygame.Surface(self.size)\n width, height = self.size\n self.shapes['gradient'] = shapes.gen_gradient(\n (width, height / 2),\n self.colors[3],\n self.colors[4]\n )\n back.blit(self.shapes['gradient'], (0, height - self.sh('gradient')))\n\n # TODO: Don't use static path/icon\n image = '/usr/share/icons/Tango/scalable/mimetypes/audio-x-generic.svg'\n self.shapes['musicimg'] = load_svg(image, [height/2]*2)\n back.blit(\n self.shapes['musicimg'],\n (width / 10, (height - self.sh('musicimg')) / 2)\n )\n return back", "def __create_background(self, filename):\n if self._bgcolor:\n self.c[\"bg\"] = self._bgcolor\n im = Image.open(filename).convert(\"RGBA\")\n self._imwidth, self._imheight = im.size\n self._cw = self.c.winfo_width()\n self._ch = self.c.winfo_height()\n if self._bgscale and (self._imwidth > self._cw or self._imheight > self._ch):\n # need increasing of image\n im = im.resize((min(self._imwidth, self._cw), min(self._imheight, self._ch)))\n self._im = ImageTk.PhotoImage(im)\n self._im.im = im\n x, y = tkutils.anchor_coords(0, 0, self._cw, self._ch, self._bganchor)\n self.tag = self.c.create_image(x, y, image=self._im, anchor=self._bganchor)\n self.c.tag_lower(self.tag, ALL) # or some symbol tag instead of ALL???\n # size of scheme\n self.width, self.height = im.size", "def _build_background(self):\n if self._background_image:\n bg = Image.open(self._background_image)\n image, _, _ = self._image_resize_keep_ratio(bg, self.width, self.height, True)\n else:\n image = Image.new('RGB', (self.width, self.height), color=self._background_color)\n return image", "def generateTransparentBackground(sizex, sizey):\n\tsizex += sizex % 16\n\tsizey += sizey % 16\n\tsingleTileData = (\n\t\t\"GdkP\"\n\t\t\"\\0\\0\\0\\263\"\n\t\t\"\\2\\1\\0\\2\"\n\t\t\"\\0\\0\\0@\"\n\t\t\"\\0\\0\\0\\20\"\n\t\t\"\\0\\0\\0\\20\"\n\t\t\"\\210jjj\\377\\210\\233\\233\\233\\377\\210jjj\\377\\210\\233\\233\\233\\377\\210jj\"\n\t\t\"j\\377\\210\\233\\233\\233\\377\\210jjj\\377\\210\\233\\233\\233\\377\\210jjj\\377\\210\"\n\t\t\"\\233\\233\\233\\377\\210jjj\\377\\210\\233\\233\\233\\377\\210jjj\\377\\210\\233\\233\"\n\t\t\"\\233\\377\\210jjj\\377\\220\\233\\233\\233\\377\\210jjj\\377\\210\\233\\233\\233\\377\"\n\t\t\"\\210jjj\\377\\210\\233\\233\\233\\377\\210jjj\\377\\210\\233\\233\\233\\377\\210jj\"\n\t\t\"j\\377\\210\\233\\233\\233\\377\\210jjj\\377\\210\\233\\233\\233\\377\\210jjj\\377\\210\"\n\t\t\"\\233\\233\\233\\377\\210jjj\\377\\210\\233\\233\\233\\377\\210jjj\\377\"\n\t)\n\tsingleTile = gtk.gdk.pixbuf_new_from_inline(len(singleTileData), singleTileData, False)\n\tbackgroundPixbuf = gtk.gdk.Pixbuf(gtk.gdk.COLORSPACE_RGB, True, 8, sizex, sizey)\n\tfor x in xrange(0, sizex - 8, 16):\n\t\tfor y in xrange(0, sizey - 8, 16):\n\t\t\tsingleTile.copy_area(0, 0, 16, 16, backgroundPixbuf, x, y)\n\treturn backgroundPixbuf", "def DrawBackground(self, dc, wnd, rect):\r\n\r\n self._buttonRect = wx.Rect()\r\n\r\n # draw background\r\n agwFlags = self.GetAGWFlags()\r\n if agwFlags & AUI_NB_BOTTOM:\r\n r = wx.Rect(rect.x, rect.y, rect.width+2, rect.height)\r\n\r\n # TODO: else if (agwFlags & AUI_NB_LEFT) \r\n # TODO: else if (agwFlags & AUI_NB_RIGHT) \r\n else: #for AUI_NB_TOP\r\n r = wx.Rect(rect.x, rect.y, rect.width+2, rect.height-3)\r\n\r\n dc.GradientFillLinear(r, self._background_top_colour, self._background_bottom_colour, wx.SOUTH)\r\n\r\n # draw base lines\r\n\r\n dc.SetPen(self._border_pen)\r\n y = rect.GetHeight()\r\n w = rect.GetWidth()\r\n\r\n if agwFlags & AUI_NB_BOTTOM:\r\n dc.SetBrush(wx.Brush(self._background_bottom_colour))\r\n dc.DrawRectangle(-1, 0, w+2, 4)\r\n\r\n # TODO: else if (agwFlags & AUI_NB_LEFT) \r\n # TODO: else if (agwFlags & AUI_NB_RIGHT)\r\n \r\n else: # for AUI_NB_TOP\r\n dc.SetBrush(self._base_colour_brush)\r\n dc.DrawRectangle(-1, y-4, w+2, 4)", "def get_background(self):\n\n return (240, 240, 240)", "def build_pcb(self, bg=None):", "def _build_background(self):\n if self._background_image:\n bg = cv2.cvtColor(cv2.imread(self._background_image), cv2.COLOR_BGR2RGB)\n image, _, _ = self._image_resize_keep_ratio(bg, self.width, self.height, True)\n else:\n # Small optimization for all white or all black (or all grey...) background\n if self._background_color[0] == self._background_color[1] and self._background_color[1] == self._background_color[2]:\n image = np.full((self.height, self.width, 3), self._background_color[0], np.uint8)\n else:\n image = np.zeros((self.height, self.width, 3), np.uint8)\n image[:] = (self._background_color[0], self._background_color[1], self._background_color[2])\n\n return image", "def pixelcode(self):\n\n maxX, maxY = self.size()\n result = bitmap((2*maxX, 2*maxY))\n for x in range(maxX):\n for y in range(maxY):\n pixel = self.get(x,y)\n result.set(2*x,2*y, pixel)\n result.set(2*x,2*y+1, not pixel)\n result.set(2*x+1,2*y, not pixel)\n result.set(2*x+1,2*y+1, pixel)\n return result", "def _set_frame_shape(self) -> None:\n width, height = self.GetSize()\n self.SetShape(wx.Region(_get_round_edges_bitmap(width, height, 10)))", "def _set_frame_shape(self) -> None:\n width, height = self.GetSize()\n self.SetShape(wx.Region(_get_round_edges_bitmap(width, height, 10)))", "def TileBackground(self, dc):\r\n\r\n sz = self.GetClientSize()\r\n w = self._backgroundImage.GetWidth()\r\n h = self._backgroundImage.GetHeight()\r\n\r\n x = 0\r\n\r\n while x < sz.width:\r\n y = 0\r\n\r\n while y < sz.height:\r\n dc.DrawBitmap(self._backgroundImage, x, y, True)\r\n y = y + h\r\n\r\n x = x + w", "def drawBackground(self,screen):\n pygame.draw.rect(screen,(240,240,240),(self.basepos[0],self.basepos[1],204,504))\n pygame.draw.rect(screen,(0,0,0),(self.basepos[0]+2,self.basepos[1]+2,200,500))", "def CreateSubBitmap(*args, **kwargs):\n return _gdi_.GraphicsRenderer_CreateSubBitmap(*args, **kwargs)", "def draw_bg(self):\n for y in range(WIN_HEIGHT/32): #TODO: make sure this process is correct and efficient.\n for x in range(WIN_WIDTH/32):\n self.screen_image.blit(self.bg, (x * 32, y * 32))", "def RescaleScreenShot(bmp, thumbnail_size=200):\r\n\r\n bmpW, bmpH = bmp.GetWidth(), bmp.GetHeight()\r\n img = bmp.ConvertToImage()\r\n\r\n newW, newH = bmpW, bmpH\r\n \r\n if bmpW > bmpH:\r\n if bmpW > thumbnail_size:\r\n ratio = bmpW/float(thumbnail_size)\r\n newW, newH = int(bmpW/ratio), int(bmpH/ratio)\r\n img.Rescale(newW, newH, wx.IMAGE_QUALITY_HIGH)\r\n else:\r\n if bmpH > thumbnail_size:\r\n ratio = bmpH/float(thumbnail_size)\r\n newW, newH = int(bmpW/ratio), int(bmpH/ratio)\r\n img.Rescale(newW, newH, wx.IMAGE_QUALITY_HIGH)\r\n\r\n newBmp = img.ConvertToBitmap()\r\n otherBmp = wx.EmptyBitmap(newW+5, newH+5) \r\n\r\n memDC = wx.MemoryDC()\r\n memDC.SelectObject(otherBmp)\r\n memDC.SetBackground(wx.WHITE_BRUSH)\r\n memDC.Clear()\r\n \r\n memDC.SetPen(wx.TRANSPARENT_PEN)\r\n\r\n pos = 0\r\n for i in xrange(5, 0, -1):\r\n brush = wx.Brush(wx.Colour(50*i, 50*i, 50*i))\r\n memDC.SetBrush(brush)\r\n memDC.DrawRoundedRectangle(0, 0, newW+5-pos, newH+5-pos, 2)\r\n pos += 1\r\n\r\n memDC.DrawBitmap(newBmp, 0, 0, True)\r\n \r\n # Select the Bitmap out of the memory DC by selecting a new\r\n # uninitialized Bitmap\r\n memDC.SelectObject(wx.NullBitmap)\r\n\r\n return otherBmp", "def CreateBitmap(self, notebook, page, button_state, tabArt):\r\n\r\n control = page.control\r\n memory = wx.MemoryDC(wx.EmptyBitmap(1, 1))\r\n\r\n tab_size, x_extent = tabArt.GetTabSize(memory, notebook, page.caption, page.bitmap, page.active,\r\n button_state, control)\r\n \r\n tab_width, tab_height = tab_size\r\n rect = wx.Rect(0, 0, tab_width, tab_height)\r\n\r\n bitmap = wx.EmptyBitmap(tab_width+1, tab_height+1)\r\n memory.SelectObject(bitmap)\r\n\r\n if wx.Platform == \"__WXMAC__\":\r\n memory.SetBackground(wx.TRANSPARENT_BRUSH)\r\n else:\r\n memory.SetBackground(wx.Brush(self._backgroundColour))\r\n \r\n memory.SetBackgroundMode(wx.TRANSPARENT)\r\n memory.Clear()\r\n\r\n paint_control = wx.Platform != \"__WXMAC__\"\r\n tabArt.DrawTab(memory, notebook, page, rect, button_state, paint_control=paint_control)\r\n \r\n memory.SetBrush(wx.TRANSPARENT_BRUSH)\r\n memory.SetPen(wx.BLACK_PEN)\r\n memory.DrawRoundedRectangle(0, 0, tab_width+1, tab_height+1, 2)\r\n\r\n memory.SelectObject(wx.NullBitmap)\r\n \r\n # Gtk and Windows unfortunatly don't do so well with transparent\r\n # drawing so this hack corrects the image to have a transparent\r\n # background.\r\n if wx.Platform != '__WXMAC__':\r\n timg = bitmap.ConvertToImage()\r\n if not timg.HasAlpha():\r\n timg.InitAlpha()\r\n for y in xrange(timg.GetHeight()):\r\n for x in xrange(timg.GetWidth()):\r\n pix = wx.Colour(timg.GetRed(x, y),\r\n timg.GetGreen(x, y),\r\n timg.GetBlue(x, y))\r\n if pix == self._backgroundColour:\r\n timg.SetAlpha(x, y, 0)\r\n bitmap = timg.ConvertToBitmap()\r\n return bitmap", "def get_raw_background(char_pos, size=394):\n full_back = Image.open(WORLD_MAP).convert(\"RGBA\")\n # get terrain part in radius size/2 from your position\n cropbox = (char_pos[0] - size//2, char_pos[1] - size//2, char_pos[0] + size//2, char_pos[1] + size//2)\n full_back = full_back.crop(cropbox)\n return full_back", "def GetImage( self, w, h, imdata ):\n global biBitCount\n\n if biBitCount == 32:\n ## 32-bit: BGRA.\n image = Image.frombytes('RGBA', (w, h), imdata, 'raw', 'BGRA', 0, -1)\n elif biBitCount == 24:\n ## 24-bit: BGR.\n image = Image.frombytes('RGB', (w, h), imdata, 'raw', 'BGR', 0, -1)\n ## Fix error screen (background isn't trasparent).\n ## Get max color (background).\n backg = max(image.getcolors(w * h))[1] \n ## Put trasparency where's background.\n image = image.convert('RGBA')\n data = numpy.array(image)\n red, green, blue, alpha = data.T\n areas = (red == backg[0]) & (green == backg[1]) & (blue == backg[2])\n data[areas.T] = (backg[0], backg[1], backg[2], 0)\n image = Image.fromarray(data)\n \n return image", "def initImg(self):\n self.img = Image.new('RGBA',(self.width,self.height),color='#' + getConfigPart(self.theme,\"bg\"))\n self.draw = ImageDraw.Draw(self.img)", "def paintScreen(self):\n imgPath = GG.genteguada.GenteGuada.getInstance().getDataPath(BACKGROUND_LEFT)\n self.imgBackgroundLeft = guiobjects.OcempImageMapTransparent(imgPath)\n self.window.add_child(self.imgBackgroundLeft)\n imgPath = GG.genteguada.GenteGuada.getInstance().getDataPath(BACKGROUND_RIGHT)\n imgBackgroundRight = guiobjects.OcempImageMapTransparent(imgPath)\n imgBackgroundRight.topleft = 297, 0\n self.window.add_child(imgBackgroundRight)", "def generate_image(self):\n\n if not has_pillow:\n raise RuntimeError(\"requires https://pypi.org/project/pillow/\")\n\n background = self.get_background()\n foreground = self.get_foreground()\n\n matrix = self.generate_matrix()\n\n image = Image.new(\"RGB\", (420, 420), background)\n draw = ImageDraw.Draw(image)\n\n for (i, row) in enumerate(matrix):\n for (j, bit) in enumerate(row):\n x = 35 + j * 70\n y = 35 + i * 70\n\n if bit:\n draw.rectangle((x, y, x + 70, y + 70), foreground)\n\n return image", "def get_image(self):\n image = Image.new('1', (8, 16))\n draw = ImageDraw.Draw(image)\n for x in xrange(8):\n for y in xrange(16):\n draw.point((x,y),self.get_pixel(x, y))\n return image", "def DrawBackground(self, dc):\r\n\r\n rect = self.GetClientRect()\r\n\r\n dc.SetPen(wx.TRANSPARENT_PEN)\r\n dc.SetBrush(wx.Brush(colourTargetBackground))\r\n dc.DrawRectangleRect(rect)\r\n\r\n dc.SetPen(wx.Pen(colourTargetBorder))\r\n\r\n left = rect.GetLeft()\r\n top = rect.GetTop()\r\n right = rect.GetRight()\r\n bottom = rect.GetBottom()\r\n\r\n if self._direction != wx.CENTER:\r\n \r\n if not self._center or self._direction != wx.BOTTOM:\r\n dc.DrawLine(left, top, right+1, top)\r\n if not self._center or self._direction != wx.RIGHT:\r\n dc.DrawLine(left, top, left, bottom+1)\r\n if not self._center or self._direction != wx.LEFT:\r\n dc.DrawLine(right, top, right, bottom+1)\r\n if not self._center or self._direction != wx.TOP:\r\n dc.DrawLine(left, bottom, right+1, bottom)\r\n\r\n dc.SetPen(wx.Pen(colourTargetShade))\r\n\r\n if self._direction != wx.RIGHT:\r\n dc.DrawLine(left + 1, top + 1, left + 1, bottom)\r\n if self._direction != wx.BOTTOM:\r\n dc.DrawLine(left + 1, top + 1, right, top + 1)", "def draw_borders(img):\n ret = img.copy()\n ret[0, :] = GRAY # top\n ret[-1, :] = GRAY # bottom\n ret[:, 0] = GRAY # left\n ret[:, -1] = GRAY # right\n return ret" ]
[ "0.6974992", "0.63787454", "0.62973994", "0.6074198", "0.6049358", "0.6016021", "0.5992435", "0.5903606", "0.58498806", "0.5837642", "0.57610255", "0.5738808", "0.573359", "0.5661286", "0.56497365", "0.56497365", "0.5610528", "0.5558927", "0.55396557", "0.55325127", "0.55223614", "0.55151963", "0.549663", "0.54869074", "0.54774815", "0.5464927", "0.53918314", "0.5377324", "0.5360711", "0.53599906" ]
0.7052649
0
Updates the list of displayed attribute text inputs.
def _update_attr_list(self) -> None: old_flex_grid = self.flex_grid self.flex_grid = wx.FlexGridSizer(cols=3, vgap=5, hgap=10) wx_elements = [] for attr_id in self.attr_ids: button = self.attr_buttons[attr_id] label_input = self.attr_labels[attr_id] value_input = self.attr_values[attr_id] wx_elements.extend([ (button, 0, wx.ALIGN_CENTER_VERTICAL), (label_input, 0, wx.EXPAND), (value_input, 1, wx.EXPAND) ]) self.flex_grid.AddGrowableCol(2, 1) self.flex_grid.AddMany(wx_elements) if old_flex_grid is not None: self.box.Replace(old_flex_grid, self.flex_grid) self.box.Layout()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _update_attr_list(self) -> None:\n old_flex_grid = self.flex_grid\n self.flex_grid = wx.FlexGridSizer(cols=3, vgap=5, hgap=10)\n wx_elements = []\n for attr_id in self.attr_req_ids:\n button = self.attr_req_buttons[attr_id]\n attr_req_label_ctrl = self.attr_req_labels[attr_id]\n attr_req_element_ctrl = self.attr_req_elements[attr_id]\n wx_elements.extend([\n (button, 0, wx.ALIGN_CENTER_VERTICAL),\n (attr_req_label_ctrl, 0, wx.EXPAND),\n (attr_req_element_ctrl, 1, wx.EXPAND)\n ])\n self.flex_grid.AddMany(wx_elements)\n if old_flex_grid is not None:\n self.box.Replace(old_flex_grid, self.flex_grid)\n self.box.Layout()", "def update_values(self):\n for key in self.inputs.keys():\n value = self.inputs[key]['entry'].get()\n self.inputs[key]['value'] = value", "def change_display(self, func, text):\n for i in range(3, 5):\n Input.clear_display(self, self.entries[i])\n func.insert(INSERT, text)\n for i in range(3, 5):\n self.entries[i].configure(state='readonly')", "def _save_attrs(self) -> None:\n for attr_id in self.attr_ids:\n orig_label = self.attr_ids[attr_id]\n attr_label = self.attr_labels[attr_id].GetValue()\n attr_value = self.attr_values[attr_id].GetValue()\n if attr_label == '':\n continue\n if orig_label != attr_label and orig_label != '':\n self.element.attr.pop(orig_label)\n self.attr_ids[attr_id] = attr_label\n if attr_label not in self.element.attr \\\n or self.element.attr[attr_label] != attr_value:\n self.element.attr[attr_label] = attr_value", "def update_set(self):\n for field in self.children:\n if issubclass(field.__class__, MyTextField):\n val = field.get_field().value\n setattr(self.set, field.get_field().name, val if val != \"\" else None)", "def update_displays(self):\n for key, value in self.lnp.settings:\n if key in list(self.controls.keys()):\n if isinstance(self.controls[key], Entry):\n self.controls[key].delete(0, END)\n self.controls[key].insert(0, value)\n else:\n self.controls[key][\"text\"] = (\n self.controls[key][\"text\"].split(':')[0] + ': ' +\n value)", "def _load_attrs(self) -> None:\n self.attr_ids.clear()\n for attr_label, attr_value in self.element.attr.items():\n self.add_attr(None, attr_label, attr_value)\n self._update_attr_list()", "def set_inputs(self, inputs):\n self.attributes[\"inputs\"] = inputs", "def update_elements(self, viewer):\n for i in range(self.num_labels):\n lbl = self.lbls[i]\n # get data coord equivalents\n x, y = self.get_data_xy(viewer, (lbl.x, lbl.y))\n # format according to user's preference\n lbl.text = self.format_value(x)", "def storeListWidgetValues(self):\n\n\t\twidget = self.sender()\n\t\tcategory, attr = self.getWidgetMeta(widget)\n\t\titems = []\n\t\tfor i in range(widget.count()):\n\t\t\titems.append(widget.item(i).text())\n\t\tself.storeValue(category, attr, items)", "def OnAttributesUpdated():\n pass", "def update(self, attributes):\n for key in attributes:\n k = key.lower()\n if not isinstance(attributes[key], str) or attributes[key] != '':\n k_ = k.strip(' =:\\t\\n').replace('', '')\n self.attributes.update({k_: attributes[key]})\n elif k in self.attributes:\n del self.attributes[k]", "def _save_attrs(self) -> None:\n for attr_req_id in self.attr_req_ids:\n orig_label = self.attr_req_ids[attr_req_id]\n attr_req_label = self.attr_req_labels[attr_req_id].GetValue()\n attr_req_element = self.attr_requirements[self.element][orig_label]\n if attr_req_label == '':\n continue\n if orig_label != attr_req_label and orig_label != '':\n self.attr_requirements[self.element].pop(orig_label)\n self.attr_req_ids[attr_req_id] = attr_req_label\n if attr_req_label not in self.attr_requirements[self.element] \\\n or self.attr_requirements[self.element][\n attr_req_label] != attr_req_element:\n self.attr_requirements[self.element][\n attr_req_label] = attr_req_element", "def _update_field_list(self, value):\n # Convert sets (e.g. draw/display/navmesh groups) to sorted lists so empty sets appear pretty.\n value_text = repr(sorted(value)) if not isinstance(value, list) else repr(value)\n self.value_label.var.set(value_text)\n self._activate_value_widget(self.value_label)", "def updateAttributesAfterAdding(self):\n layer = self.sender()\n while self.addedFeatures:\n featureId = self.addedFeatures.pop()\n #begining the edit command\n # layer.beginEditCommand(self.tr(\"DSG Tools reclassification tool: adjusting feature's attributes\"))\n #accessing added features\n editBuffer = layer.editBuffer()\n features = editBuffer.addedFeatures()\n for key in features.keys():\n #just checking the newly added feature, the other I don't care\n if key == featureId:\n feature = features[key]\n #setting the attributes using the reclassification dictionary\n self.setFeatureAttributes(feature, editBuffer)\n layer.endEditCommand()", "def update_list(self, text):\n self.text_region.config(state=Tk.NORMAL)\n self.text_region.delete(1.0, Tk.END)\n self.text_region.insert(Tk.END, text)\n self.text_region.config(state=Tk.DISABLED)", "def searchAttributes(self):\n search_string = self.attr_search.text()\n for rowIndex in range(self.attributeTable.rowCount()):\n twItem = self.attributeTable.item(rowIndex, 0)\n if twItem.text().startswith(search_string):\n self.attributeTable.setRowHidden(rowIndex, False)\n else:\n self.attributeTable.setRowHidden(rowIndex, True)", "def _set_attributes(self):", "def __editAutoCompleteFromAll(self):\n self.activeWindow().autoCompleteFromAll()", "def __editAutoComplete(self):\n self.activeWindow().autoComplete()", "def edit(self, **kwargs):\r\n for attr in self.EDITABLE_ATTR:\r\n kwarg = kwargs.pop(attr, self._WILDCARD)\r\n if kwarg is not self._WILDCARD:\r\n setattr(self, attr, kwarg)\r\n logger.debug(\"Attribute '{}' changed to '{}'.\".format(attr, kwarg))\r\n\r\n for p_attr in self.EDITABLE_PRIVATE_ATTR:\r\n kwarg = kwargs.pop(p_attr, self._WILDCARD)\r\n if kwarg is not self._WILDCARD:\r\n setattr(self, \"_\" + p_attr, kwarg)\r\n logger.debug(\"Private attribute '{}' changed to '{}'.\".format(p_attr, kwarg))\r\n logger.debug(\"Configuration edited.\")", "def update_field_value_display(self, new_value):\n self.field_update_method(new_value)\n self._set_field_fg(new_value)\n self.link_missing = self.field_links and not any(link.name for link in self.field_links)\n self.build_field_context_menu()", "def __editAutoCompleteFromAPIs(self):\n self.activeWindow().autoCompleteFromAPIs()", "def load_input_fields(self):\n self.ui.boxNumberInput.setText(str(self.data[0]))\n self.ui.shelfNumberInput.setText(self.data[1])", "def refresh_attributes(self):\n if self.skill_tree_displaying:\n return\n player_panel_renderer.draw_attributes(self.player_dict['attributes'], self.level_up_points, refresh=True)\n if self.level_up_points > 0:\n player_panel_renderer.draw_attribute_level_up_buttons(self.level_up_points)", "def update_steps_display(self):\r\n self.steps_display[\"text\"] = str(self.steps.get())", "def reset_attributes(input_object, attr_name_list = None):\n if attr_name_list is None:\n attr_name_list = []\n if len(attr_name_list) > 0:\n attr_list = [input_object.attr(attr_name) for attr_name in attr_name_list]\n else:\n attr_list = general.get_channelbox_attributes(input_object)\n\n for attr in attr_list:\n # def_val = attr.get(default = True)\n def_val = pm.attributeQuery(attr.plugAttr(), node = attr.node(), listDefault = True)[0]\n if attr.isSettable():\n attr.set(def_val)", "def adjust_display(self, display: typing.List[typing.List[str]]):", "def refreshAttrStr(self):\n self.attributes_str = ';'.join(['='.join(\n [attr, self.attributes[attr]]) for attr in self.attributes_order])", "def on_submit(self, text):\n self.pp = [float(i.text) for i in self.text_boxes]\n self.pp_values = self.pp.copy()\n self.pp_mapping()\n self.redraw()" ]
[ "0.6138667", "0.58394015", "0.57136977", "0.5605623", "0.5420066", "0.5399311", "0.53753835", "0.5258919", "0.5243419", "0.5237437", "0.5222367", "0.521364", "0.5211479", "0.52040356", "0.5188745", "0.51685643", "0.5158266", "0.5157293", "0.5097068", "0.50787485", "0.50495744", "0.5044085", "0.5038987", "0.5024078", "0.50203884", "0.5017842", "0.50146794", "0.50021863", "0.5001006", "0.4992909" ]
0.6706066
0
Load the attributes from the connected element.
def _load_attrs(self) -> None: self.attr_ids.clear() for attr_label, attr_value in self.element.attr.items(): self.add_attr(None, attr_label, attr_value) self._update_attr_list()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def load_attrs(self):\n return loads(self.get_attr().GetObject()) or {}", "def load(self):\r\n self.domain.get_attributes(self.name, item=self)", "def get_attributes(self):\n\t\treturn dict(list(self.__element.items()))", "def prepare_node_attrs(self):", "def read_attributes(self, dataset):\n if 'attributes' in self.configs:\n for key, value in self.configs['attributes'].items():\n setattr(dataset, key, value)", "def _init_node_attributes(self):\n assert False", "def fromElement(self, element):\n from comoonics.ComProperties import Properties\n props=element.getElementsByTagName(Properties.TAGNAME)\n #log.debug(\"fromElement: %s, %u\" %(element, len(props)))\n if len(props)>=1:\n self.properties=Properties(props[0])\n for propertyname in self.properties.keys():\n self.log.debug(\"fromElement: Setting attribute %s, %s\" %(propertyname, self.properties[propertyname].getAttribute(\"value\")))\n setattr(self, propertyname, self.properties[propertyname].getAttribute(\"value\"))\n for attribute in element.attributes:\n self.__dict__[attribute.name]=attribute.value", "def load(self):\n return loads(self.get_attr().Value())", "def attributes(self):\n ...", "def getElementProperties():", "def get_image_attributes(self, element):", "def fill_attributes(ml_file, other_file):\n with xr.load_dataset(other_file) as other:\n with xr.open_dataset(ml_file) as ml:\n for variable in other.variables:\n if variable in ml.variables:\n other[variable].attrs = ml[variable].attrs\n other.to_netcdf(other_file)", "def load_attributes():\n\n # <attribute_id> <attribute_name>\n attributes_file = open(PROJECT_ROOT +'/data/attributes.txt').readlines()\n attributes_file = [i.strip().split() for i in attributes_file]\n\n # <certainty_id> <certainty_name>\n certainties_file = open(PROJECT_ROOT +'/data/CUB_200_2011/attributes/certainties.txt').readlines()\n certainties_file = [i.strip().split() for i in certainties_file]\n\n # <image_id> <attribute_id> <is_present> <certainty_id> <time>\n labels_file = open(PROJECT_ROOT +'/data/CUB_200_2011/attributes/image_attribute_labels.txt').readlines()\n labels_file = [i.strip().split() for i in labels_file]\n\n attribute_ids = {}\n for i in attributes_file:\n attribute_ids[i[1]] = int(i[0])\n\n certainty_ids = {}\n for i in certainties_file:\n certainty_ids[i[1]] = int(i[0])\n\n label_ids = {}\n for i in labels_file:\n label_ids[(int(i[0]), int(i[1]))] = list(map(lambda x:int(float(x)), i[2:]))\n\n return attribute_ids, certainty_ids, labels_file, label_ids", "def load_attribute_dict(parent_element, tag_name):\n loaded_element = parent_element.find(tag_name)\n attribute_dict = {attr[0] : convert_to_int_if_numeric(attr[1])\n for attr in loaded_element.items()}\n return attribute_dict", "def _set_attributes(self):", "def _load_attrs_requirements(self) -> None:\n if self.element not in self.attr_requirements:\n return\n self.attr_req_ids.clear()\n for attr_req_label, attr_req_value in \\\n self.attr_requirements[self.element].items():\n self.add_attr_requirement(None, attr_req_label, attr_req_value)\n self._update_attr_list()", "def attributes(self):", "def set_attr_values(self):\n ats = self.attributes # convenient short name\n for aid in ats:\n value = ats[aid]['nv'] if 'nv' in ats[aid] else (\n ats[aid]['value'] if 'value' in ats[aid] else None)\n if value is not None:\n# self.h5node.attrs[aid] = value\n #- self.file.file_pointer[self.full_path].attrs[aid] = value\n self.file.set_attribute(self.full_path, aid, value)\n #- self.file.h5save_attribute(self.full_path, aid, value)\n #- self.file.h5commands.append(\"set attribute(%s:%s)-%s\" % (self.full_path,\n #- aid, value))", "def getAttributes(self):\n pass", "def attrib(self) -> Any:\n return self.attributes", "def get_attributes(self) -> Dict[str, str]:\n pass", "def attributes(self):\n return self.host.attributes", "def init_attrs(self):\n raise NotImplementedError", "def _init_attributes(self):\n if os.name == \"nt\":\n if \"64\" in platform.architecture()[0]:\n platform_arch = \"x86_64\"\n elif \"32\" in platform.architecture()[0]:\n platform_arch = \"i386\"\n else:\n platform_arch = platform.architecture()\n os_ver = f\"Windows-{platform.win32_ver()[1]}\"\n else:\n platform_arch = platform.machine()\n if platform.system() == \"Darwin\":\n os_ver = f\"macOS-{platform.mac_ver()[0]}\"\n else:\n os_ver = \"-\".join(linux_distribution()[0:2])\n\n license_chunks = LICENSE.split(\" \")\n if license_chunks[0] == \"GPLv2\":\n client_license = \"GPL-2.0\"\n else:\n client_license = \"Commercial\"\n\n default_attributes = {\n # Process id\n \"_pid\": str(os.getpid()),\n # Platform architecture\n \"_platform\": platform_arch,\n # OS version\n \"_os\": os_ver,\n # Hostname of the local machine\n \"_source_host\": socket.gethostname(),\n # Client's name\n \"_client_name\": \"mysql-connector-python\",\n # Client's version\n \"_client_version\": \".\".join([str(x) for x in VERSION[0:3]]),\n # Client's License identifier\n \"_client_license\": client_license,\n }\n self._settings[\"attributes\"].update(default_attributes)\n\n if \"connection-attributes\" in self._settings:\n for attr_name in self._settings[\"connection-attributes\"]:\n attr_value = self._settings[\"connection-attributes\"][attr_name]\n # Validate name type\n if not isinstance(attr_name, str):\n raise InterfaceError(\n f\"Attribute name '{attr_name}' must be a string type\"\n )\n # Validate attribute name limit 32 characters\n if len(attr_name) > 32:\n raise InterfaceError(\n f\"Attribute name '{attr_name}' exceeds 32 characters \"\n \"limit size\"\n )\n # Validate names in connection-attributes cannot start with \"_\"\n if attr_name.startswith(\"_\"):\n raise InterfaceError(\n \"Key names in 'session-connect-attributes' cannot \"\n f\"start with '_', found: {attr_name}\"\n )\n # Validate value type\n if not isinstance(attr_value, str):\n raise InterfaceError(\n f\"Attribute name '{attr_name}' value '{attr_value}' \"\n \" must be a string type\"\n )\n\n # Validate attribute value limit 1024 characters\n if len(attr_value) > 1024:\n raise InterfaceError(\n f\"Attribute name '{attr_name}' value: '{attr_value}' \"\n \"exceeds 1024 characters limit size\"\n )\n\n self._settings[\"attributes\"][attr_name] = attr_value", "def _init_attributes(self):\n self.attr = {\n 'name': None,\n 'tags': [],\n 'openHours': None,\n 'type': None,\n 'parent': None,\n 'locationId': None,\n 'bannerAbbreviation': None,\n 'arcGisAbbreviation': None,\n 'geoLocation': None,\n 'geometry': None,\n 'summary': None,\n 'description': None,\n 'descriptionHtml': None,\n 'address': None,\n 'city': None,\n 'state': None,\n 'zip': None,\n 'county': None,\n 'telephone': None,\n 'fax': None,\n 'thumbnails': [],\n 'images': [],\n 'departments': [],\n 'website': None,\n 'sqft': None,\n 'calendar': None,\n 'campus': None,\n 'girCount': None,\n 'girLimit': False,\n 'girLocations': None,\n 'synonyms': [],\n 'bldgId': None,\n 'parkingZoneGroup': None,\n 'propId': None,\n 'adaParkingSpaceCount': None,\n 'motorcycleParkingSpaceCount': None,\n 'evParkingSpaceCount': None,\n 'weeklyMenu': None,\n 'notes': None,\n 'labels': {},\n 'steward': None,\n 'shape': {}\n }", "def get_extra_attributes(self, device: str) -> dict:\n raise NotImplementedError()", "def _set_attr(self):\n self.as_skeletal = self._import_as_skeleton()\n self.materials = self._import_materials()\n self.textures = self._import_textures()", "def _save_attrs(self) -> None:\n for attr_id in self.attr_ids:\n orig_label = self.attr_ids[attr_id]\n attr_label = self.attr_labels[attr_id].GetValue()\n attr_value = self.attr_values[attr_id].GetValue()\n if attr_label == '':\n continue\n if orig_label != attr_label and orig_label != '':\n self.element.attr.pop(orig_label)\n self.attr_ids[attr_id] = attr_label\n if attr_label not in self.element.attr \\\n or self.element.attr[attr_label] != attr_value:\n self.element.attr[attr_label] = attr_value", "def _loadData(self, data):\n self._data = data\n self.id = utils.cast(int, data.attrib.get('id'))\n self.accountID = utils.cast(int, data.attrib.get('accountID'))\n self.serverId = utils.cast(int, data.attrib.get('serverId'))\n self.machineIdentifier = data.attrib.get('machineIdentifier')\n self.name = data.attrib.get('name')\n self.lastSeenAt = utils.toDatetime(data.attrib.get('lastSeenAt'))\n self.numLibraries = utils.cast(int, data.attrib.get('numLibraries'))\n self.allLibraries = utils.cast(bool, data.attrib.get('allLibraries'))\n self.owned = utils.cast(bool, data.attrib.get('owned'))\n self.pending = utils.cast(bool, data.attrib.get('pending'))", "def load_attribute_data():\n global attr_value_counts, attr_counts, value_counts, \\\n attr_value_ratios, attrs\n\n print \"Loading extraction data...\"\n with open('./data/common_extractions.json') as f:\n place_data = json.loads(f.read())\n for place in place_data:\n for attr in place_data[place]:\n if attr not in attr_value_counts:\n attrs.add(attr)\n attr_value_counts[attr] = {}\n attr_counts[attr] = 0\n for value in place_data[place][attr]:\n c = place_data[place][attr][value]\n value_counts[value] = value_counts.get(value, 0) + c\n attr_counts[attr] += c\n attr_value_counts[attr][value] = \\\n attr_value_counts[attr].get(value, 0) + c\n \n for attr in attrs:\n attr_value_ratios[attr] = {}\n for value in attr_value_counts[attr]:\n attr_value_ratios[attr][value] = float(attr_value_counts[attr][value]) \\\n / attr_counts[attr]" ]
[ "0.6402216", "0.63636845", "0.5951157", "0.57516307", "0.56711984", "0.56089693", "0.5590862", "0.5546388", "0.5435026", "0.541997", "0.5352226", "0.52861327", "0.52834237", "0.52810484", "0.5278922", "0.5264512", "0.52519834", "0.5222196", "0.52052623", "0.51943564", "0.51771355", "0.51493776", "0.51485044", "0.51317555", "0.50814915", "0.50740606", "0.5051591", "0.5012795", "0.5000113", "0.4997933" ]
0.6939825
0
Save the changes to the attributes to the connected element.
def _save_attrs(self) -> None: for attr_id in self.attr_ids: orig_label = self.attr_ids[attr_id] attr_label = self.attr_labels[attr_id].GetValue() attr_value = self.attr_values[attr_id].GetValue() if attr_label == '': continue if orig_label != attr_label and orig_label != '': self.element.attr.pop(orig_label) self.attr_ids[attr_id] = attr_label if attr_label not in self.element.attr \ or self.element.attr[attr_label] != attr_value: self.element.attr[attr_label] = attr_value
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _save(self):\n for attrib in self.attribs:\n setattr(self, attrib, getattr(self.obj, attrib))", "def store_attrs(self, attrs):\n self.get_attr().SetObject(dumps(attrs), False)", "def _save_attrs(self) -> None:\n for attr_req_id in self.attr_req_ids:\n orig_label = self.attr_req_ids[attr_req_id]\n attr_req_label = self.attr_req_labels[attr_req_id].GetValue()\n attr_req_element = self.attr_requirements[self.element][orig_label]\n if attr_req_label == '':\n continue\n if orig_label != attr_req_label and orig_label != '':\n self.attr_requirements[self.element].pop(orig_label)\n self.attr_req_ids[attr_req_id] = attr_req_label\n if attr_req_label not in self.attr_requirements[self.element] \\\n or self.attr_requirements[self.element][\n attr_req_label] != attr_req_element:\n self.attr_requirements[self.element][\n attr_req_label] = attr_req_element", "def save(self):\n self.lock.acquire()\n try:\n self.xml.set(\"name\",self.name)\n self.xml.set(\"room\",self.room)\n self.xml.set(\"type\",self.type)\n self.xml.find(\"address\").text = \":\".join([str(x) for x in self.address])\n if self.pos is not None:\n self.xml.find(\"pos\").text = \" \".join([str(x) for x in self.pos])\n self.xml.find(\"icon\").text = self.icon\n \n finally:\n self.lock.release()\n \n self.house.save_devices()", "def set_attr_values(self):\n ats = self.attributes # convenient short name\n for aid in ats:\n value = ats[aid]['nv'] if 'nv' in ats[aid] else (\n ats[aid]['value'] if 'value' in ats[aid] else None)\n if value is not None:\n# self.h5node.attrs[aid] = value\n #- self.file.file_pointer[self.full_path].attrs[aid] = value\n self.file.set_attribute(self.full_path, aid, value)\n #- self.file.h5save_attribute(self.full_path, aid, value)\n #- self.file.h5commands.append(\"set attribute(%s:%s)-%s\" % (self.full_path,\n #- aid, value))", "def save_attribute(self, attr):\n self._send_attribute_value_to_results_db(attr, opt=\"X\")", "def save(self):\n # TODO (Pierre): code", "def setAttributes(self, attrDict):\n self.graph.saveExtendedAttributes(self.entityId, attrDict)", "def save(self):\n self.network.save()", "def merge_attrs(self):\n for aid in self.attrs:\n new_val = self.attrs[aid]\n if aid in self.attributes:\n if ('value' in self.attributes[aid] and\n self.attributes[aid]['value'] != new_val):\n pass\n # print \"Updating attribute %s[%s] %s -> %s\" % (\n # self.name, aid, self.attributes[aid]['value'], new_val)\n else:\n # print \"** Warning: non-declaired attribute %s['%s'] set to:\\n'%s'\" % (\n # self.name, aid, new_val)\n self.remember_custom_attribute(self.name, aid, new_val)\n self.attributes[aid] = {}\n self.attributes[aid]['nv'] = new_val", "def _set_attributes(self):", "def save(self, *args, **kwargs):\r\n super(Vertex, self).save(*args, **kwargs)\r\n params = self.as_save_params()\r\n params['element_type'] = self.get_element_type()\r\n result = self._save_vertex(params)[0]\r\n self.eid = result.eid\r\n for k,v in self._values.items():\r\n v.previous_value = result._values[k].previous_value\r\n return result", "def save(self):\n if self.iid is not None:\n self.db().update(self.iid, self._attributes)\n else:\n self.iid = self.db().add(self._attributes)", "def save(self):\n\n pass", "def save (self):\n pass", "def save(self):\n with self.open(self.filename, 'wt') as fd:\n for node in self.elements:\n fd.write(node.text)", "def save(self, replace=True):\r\n self.domain.put_attributes(self.name, self, replace)\r\n # Delete any attributes set to \"None\"\r\n if replace:\r\n del_attrs = []\r\n for name in self:\r\n if self[name] == None:\r\n del_attrs.append(name)\r\n if len(del_attrs) > 0:\r\n self.domain.delete_attributes(self.name, del_attrs)", "def save(self):\n pass", "def save(self):\n pass", "def save(self):\n pass", "def save(self):\n pass", "def save(self):\n pass", "def set(self, **attrs):\n self.graph._setattrs(handle=self.handle, **attrs)", "def update(self):\r\n self._revit_object.SetElementIds(self.as_element_id_list)", "def save_attributes(self):\n Credentials.credentials_list.append(self)", "def save(self):\n data = (\n self.Joints,\n self.Links,\n self.joint_syms,\n self.global_syms,\n self.name,\n self.sym_prefix,\n )\n cloudpickle.dump(data, open(self.save_filename, \"wb\"))", "def save(self):\n\n or_none = lambda x: x if x is not None else \"none\"\n with h5py.File(self.filename, \"a\") as hf:\n for attr in self._SAVE_ATTRS + self._save_attrs:\n hf.attrs[attr] = or_none(getattr(self, attr, None))", "def AssignAttributes(self, attr):\r\n \r\n self.SetAttributes(attr)\r\n self._ownsAttr = True", "def write(self, value):\n self.get_attr().SetValue(value)", "def saveToXml(self) -> org.jdom.Element:\n ..." ]
[ "0.678142", "0.6351419", "0.6286748", "0.6224528", "0.6134093", "0.610638", "0.59863436", "0.58716166", "0.5859173", "0.58556986", "0.5841143", "0.5747278", "0.5647891", "0.5641672", "0.5629725", "0.5609513", "0.56082225", "0.5603071", "0.5603071", "0.5603071", "0.5603071", "0.5603071", "0.5596231", "0.55812687", "0.5572564", "0.55242145", "0.546169", "0.5457588", "0.5438957", "0.5437737" ]
0.7135137
0
Remove the specified attribute from the element and the gui.
def remove_attr(self, event: Union[wx.CommandEvent, None], attr_id: Union[int, None]) -> None: self.attr_buttons.pop(attr_id).Destroy() self.attr_values.pop(attr_id).Destroy() self.attr_labels.pop(attr_id).Destroy() attr_label = self.attr_ids.pop(attr_id) if attr_label != '': self.element.attr.pop(attr_label) if event is not None: self._update_attr_list()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def remove_attribute(self, attribute) -> None:\n logging.info(f\"remove element attribute. {self.desc}\")\n js = f\"\"\"var elm = document.querySelectorAll(\"{self.css}\")[{self.index}];\n elm.removeAttribute(\"{attribute}\");\"\"\"\n self._execute_javascript(js)", "def remove_attribute(self, attribute: str) -> None:\n attr_index = self.__attr_index(attribute)\n if attr_index is not None:\n self.yaml_node.value.pop(attr_index)", "def remove_attr(self, event: Union[wx.CommandEvent, None],\n attr_id: Union[int, None]) -> None:\n self.attr_req_buttons.pop(attr_id).Destroy()\n self.attr_req_elements.pop(attr_id).Destroy()\n self.attr_req_labels.pop(attr_id).Destroy()\n attr_label = self.attr_req_ids.pop(attr_id)\n if attr_label != '':\n self.attr_requirements[self.element].pop(attr_label)\n if event is not None:\n self._update_attr_list()", "def remove_attribute(self, name):\n\n pass", "def remove_attribute(self, attribute):\n if attribute in self.attributes:\n self.attributes.remove(attribute)\n self.attribute_list.remove(attribute)\n return self", "def remove_attribute(self, attribute_key):\n self.attributes.__delitem__(attribute_key) # delete the input key-value pair", "def remove_attribute(self, attribute_key):\n self.attributes.__delitem__(attribute_key) # delete the input key-value pair", "def remove_attribute(self, attribute_key):\n self.attributes.__delitem__(attribute_key) # delete the input key-value pair", "def del_attrib(self, key):\n self.aux_attrib.pop(key)\n self.aux_attrib_args.pop(key)", "def removeattribute(self, uid, field):\n\n raise NotImplementedError", "def deleteAttr(*args, attribute: AnyStr=\"\", name: AnyStr=\"\", q=True, query=True, e=True,\n edit=True, **kwargs)->Union[None, Any]:\n pass", "def delete(self, attribute):\n self.__delattr__(attribute)", "def removeAttr(self, *args):\n return _libsbml.XMLToken_removeAttr(self, *args)", "def del_attr(self, elt, localName, ns=None):\n for (pyname, (qname, ns_)) in elt.xml_attributes.items():\n _, name = SplitQName(qname)\n if ns_ == ns and name == localName:\n delattr(elt, pyname)", "def remove(self, *args):\n return _libsbml.XMLAttributes_remove(self, *args)", "def test_remove_a_single_attribute(self):\n pass", "def unobserve(self, attr: str | tuple[str, ...]):\n if isinstance(attr, str):\n attr = (attr,)\n path = self._path + attr\n return self._get_top_parent().unobserve(path)", "def remove(self, attributeIndexOrName) -> None:\n ...", "def __delattr__(self, attribute: str) -> None:\n try:\n object.__delattr__(self, attribute)\n except AttributeError:\n try:\n object.__delattr__(self.contents, attribute)\n except AttributeError:\n raise AttributeError(f'{attribute} is not in {self.__name__}')", "def clear(self, attrname):\n self.__dict__['_'+attrname] = False", "def remove(self, attr: str):\n self._includes.remove(attr)\n self._regex = None", "def drop_attr(self, attr_name): # DONE\n self.data.drop(attr_name, axis=1, inplace=True)\n print(self.data)", "def removeID(self, attr):\n if attr is None: attr__o = None\n else: attr__o = attr._o\n ret = libxml2mod.xmlRemoveID(self._o, attr__o)\n return ret", "def remove_element(self, element=None):\n pass", "def remove_key(attr):\n pm.cutKey(attr, clear=True, time=pm.currentTime())", "def remove_animation(attr):\n pm.cutKey(attr, clear=True)", "def clear_attrs(self):\n self._attributes.clear()", "def removeAttributeByIndex(self, index):\n\n if self._checkAttributeIndex(index) is not True:\n return False\n\n del self._attributes[index]\n\n return True", "def reset_attribute(attr_config):\n obj = pm.PyNode(attr_config[\"ctl\"])\n attr = attr_config[\"longName\"]\n\n attribute.reset_selected_channels_value(objects=[obj], attributes=[attr])", "def _maybe_del_attr(da, attr):\n if attr in da.attrs:\n del da.attrs[attr]\n\n return da" ]
[ "0.81728333", "0.7617282", "0.75242573", "0.75183755", "0.7310464", "0.7302848", "0.7302848", "0.7302848", "0.7192179", "0.71326095", "0.7076926", "0.7030358", "0.6921169", "0.6725303", "0.66307867", "0.66302186", "0.6618078", "0.66085863", "0.6600818", "0.645934", "0.6452364", "0.63676655", "0.6302015", "0.62695694", "0.6228433", "0.6220418", "0.6201146", "0.61717075", "0.6112062", "0.6106021" ]
0.78135085
1
Override to save changes to arguments before closing the frame.
def Close(self, *args, **kwargs): self._save_attrs() super().Close(*args, **kwargs)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def restore(self, arguments):\n puts_err(colored.red(\"Not implemented!\"))", "def close_extras(self, **kwargs):\n pass", "def close(*args):", "def close(*args):", "def close(*args):", "def close(*args):", "def close(*args):", "def _exit(self, save_vars):\n raise NotImplementedError()", "def close(self) -> None:\n if self.hit:\n logger.warning(\"No value provided for argument %r\", self.namestr())", "def OnClose(self):\n self.SaveData()\n self.destroy()", "def closed(self, *args, **kwargs) -> Any:\n pass", "def on_close(self, event):\n # Save pos and size\n x, y = self.GetPosition()\n width, height = self.GetSize()\n self.__config.set('window.x', x)\n self.__config.set('window.y', y)\n self.__config.set('window.width', width)\n self.__config.set('window.height', height)\n\n # Style\n style = self.GetWindowStyle()\n self.__config.set('window.style', style)\n\n self.__config.save()\n\n # Stop monitoring\n self.__cor.stop_monitor()\n\n # Kill graph as it seems to be stopping script from ending\n self.__graph = None\n\n # End\n event.Skip()", "def on_closing(self, *args):\n pass", "def close(self):\n\n self.config.worldinfo_w = self.width()\n self.config.worldinfo_h = self.height()\n super().close()", "def quit(self, *args, **kwargs):\n pass", "def close(self, **kw) -> None:\n super().close(**kw)", "def onSceneStartClose(self, caller, event):\n\t\t# Parameter node will be reset, do not use it anymore\n\t\tself.setParameterNode(None)", "def closeEvent(self, event):\n self.force_blurrer_quit()\n self.save()\n print(\"saved settings\")\n QMainWindow.closeEvent(self, event)", "def onSceneEndClose(self, caller, event):\n\t\t# If this module is shown while the scene is closed then recreate a new parameter node immediately\n\t\tif self.parent.isEntered:\n\t\t\tself.initializeParameterNode()", "def _set_arguments(self):\n self._arguments = []", "def closeEvent(self, event):\n\n self.settings.setValue('geometry', self.saveGeometry())\n self.settings.setValue('windowState', self.saveState())\n # TODO: need to modify\n # self.save_drawing_if_necessary()\n AppDocData.instance().clear()\n event.accept()", "def __window_close(self):\n pass", "def save_args(self, args) -> None:\n name = self._make_filepath(\"hparams.json\")\n with open(name, \"w\") as file:\n json.dump(vars(args), file)", "def frame_off_args(*args):\n return _ida_frame.frame_off_args(*args)", "def OnClose(self, event):\r\n pos.app.main.Exit()", "def end(self, *args):\n return _ida_hexrays.lvar_saved_infos_t_end(self, *args)", "def exit(self):\n\t\t# Do not react to parameter node changes (GUI wlil be updated when the user enters into the module)\n\t\tself.removeObserver(self._parameterNode, vtk.vtkCommand.ModifiedEvent, self.updateGUIFromParameterNode)", "def change_args(self, args):\n self.modified_args = args", "def goodbye(self, args):\n\t\tself.write_line(\"GOODBYE\")\n\t\tself.close();", "def __call__(self, connection, window_info, original_kwargs):\n raise NotImplementedError" ]
[ "0.6397291", "0.6238765", "0.62264043", "0.62264043", "0.62264043", "0.62264043", "0.62264043", "0.6015775", "0.6008856", "0.60076225", "0.5912482", "0.5897535", "0.5865324", "0.5848845", "0.58236265", "0.57882524", "0.577333", "0.57647246", "0.5741745", "0.57246125", "0.56510425", "0.56354386", "0.56258166", "0.56130946", "0.5596472", "0.55917746", "0.55736655", "0.5570463", "0.55202407", "0.549209" ]
0.6632843
0
Sets this frames shape to a rounded rectangle.
def _set_frame_shape(self) -> None: width, height = self.GetSize() self.SetShape(wx.Region(_get_round_edges_bitmap(width, height, 10)))
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def SetRoundShape(self):\n w, h = self.GetSize()\n self.SetShape(GetRoundShape(w, h, 10))", "def draw_rounded_rect(self, context, x, y, width, height, radius, lineWidth):\n from math import pi\n degrees = pi / 180\n\n context.set_line_width(lineWidth)\n context.set_source_rgba(0.5, 0.0, 0.0, 1.0) # Red\n\n # cr.new_sub_path()\n context.arc(x + width - radius, y + radius, radius, -90 * degrees, 0 * degrees)\n context.arc(x + width - radius, y + height - radius, radius, 0 * degrees, 90 * degrees)\n context.arc(x + radius, y + height - radius, radius, 90 * degrees, 180 * degrees)\n context.arc(x + radius, y + radius, radius, 180 * degrees, 270 * degrees)\n context.close_path()\n context.stroke_preserve()\n context.set_source_rgba(0.0, 0.5, 0.5, 1.0)\n # and use it to fill the path (that we had kept)\n context.fill()\n context.stroke()", "def set_rscale(self, top, bottom=0, round_up=False):\n if self.shape == 'circle':\n r = top\n elif self.shape == 'polygon':\n angle_of_slice = 2 * np.pi / self.size\n r = top / np.cos(angle_of_slice / 2.)\n if round_up:\n r = np.ceil(r)\n else:\n # this should never happen since this is checked for in class\n # creation\n raise ValueError('unknown value for `frame`: %s' % self.shape)\n self.set_ylim(bottom, r)", "def DrawRoundedRectangle(*args, **kwargs):\n return _gdi_.DC_DrawRoundedRectangle(*args, **kwargs)", "def DrawRoundedRectangle(*args, **kwargs):\n return _gdi_.GraphicsContext_DrawRoundedRectangle(*args, **kwargs)", "def DrawRoundedRectangleRect(*args, **kwargs):\n return _gdi_.DC_DrawRoundedRectangleRect(*args, **kwargs)", "def set_rect(self, rect):\n pass", "def DrawRoundedRectangleRect(*args, **kwargs):\n return _gdi_.PseudoDC_DrawRoundedRectangleRect(*args, **kwargs)", "def setRoundingRadius( self, radius ):\n self._roundingRadius = radius\n self.setDirty()", "def DrawRoundedRectangle(*args, **kwargs):\n return _gdi_.PseudoDC_DrawRoundedRectangle(*args, **kwargs)", "def addRoundedRect(self, *__args): # real signature unknown; restored from __doc__ with multiple overloads\r\n pass", "def addRoundRect(self, *__args): # real signature unknown; restored from __doc__ with multiple overloads\r\n pass", "def rounded_border_box(self):\n return self.rounded_box(0, 0, 0, 0)", "def round_rect(self, surface, rect, color, rad=20, border=0, inside=(0,0,0,0)):\n rect = pygame.Rect(rect)\n zeroed_rect = rect.copy()\n zeroed_rect.topleft = 0,0\n image = pygame.Surface(rect.size).convert_alpha()\n image.fill((0,0,0,0))\n self.render_region(image, zeroed_rect, color, rad)\n if border:\n zeroed_rect.inflate_ip(-2*border, -2*border)\n self.render_region(image, zeroed_rect, inside, rad)\n surface.blit(image, rect)", "def aa_round_rect(surface, rect, color, rad=20, border=0, inside=(0, 0, 0)):\n rect = pg.Rect(rect)\n _aa_render_region(surface, rect, color, rad)\n if border:\n rect.inflate_ip(-2 * border, -2 * border)\n _aa_render_region(surface, rect, inside, rad)", "def AddRoundedRectangle(*args, **kwargs):\n return _gdi_.GraphicsPath_AddRoundedRectangle(*args, **kwargs)", "def __init__(self, size=None, color=None, clip=None,\n radius=0.):\n BasicFrame.__init__(self, size, color, clip)\n self.radius_value = style.DEF_RADIUS if radius is None else radius\n if 0. <= radius <= 1.:\n self.radius_value = min(self.size) * radius", "def draw_round_rect(self, x, y, w, h, r, color=None, aa=False):\n self._draw_fast_hline(x + r, y, w - 2 * r, color, aa) # Top\n self._draw_fast_hline(x + r, y + h - 1, w - 2 * r, color, aa) # Bottom\n self._draw_fast_vline(x, y + r, h - 2 * r, color, aa) # Left\n self._draw_fast_vline(x + w - 1, y + r, h - 2 * r, color, aa) # Right\n # draw four corners\n self._draw_circle_helper(x + r, y + r, r, 1, color)\n self._draw_circle_helper(x + w - r - 1, y + r, r, 2, color)\n self._draw_circle_helper(x + w - r - 1, y + h - r - 1, r, 4, color)\n self._draw_circle_helper(x + r, y + h - r - 1, r, 8, color)", "def SetItemRect(self, r):\r\n\r\n self.rect = r", "def DrawRoundedRectanglePointSize(*args, **kwargs):\n return _gdi_.DC_DrawRoundedRectanglePointSize(*args, **kwargs)", "def draw_shape_rounded_rectangle(self, rect, xform, colour):\n for shape in rect.as_arcs_lines():\n getattr(self, 'draw_shape_%s' % shape.type)(shape, xform, colour)", "def draw_round_rect_filled(self, x, y, w, h, r, color=None, aa=False):\n self.draw_rect_filled(x + r, y, w - 2 * r, h, color, aa)\n self._draw_circle_filled_helper(x + w - r - 1, y + r, r,\n 1, h - 2 * r - 1, color)\n self._draw_circle_filled_helper(x + r, y + r, r, 2, h - 2 * r - 1, color)", "def setRect(self, p_float, p_float_1, p_float_2, p_float_3): # real signature unknown; restored from __doc__\r\n pass", "def set_radius(self, radius):\n self.__begin.set_radius(radius)\n self.__end.set_radius(radius)", "def DrawRoundedRectanglePointSize(*args, **kwargs):\n return _gdi_.PseudoDC_DrawRoundedRectanglePointSize(*args, **kwargs)", "def setR(self, radius):\n self.radius = radius", "def rounded_rectangle(src: np.array, top_left: tuple, bottom_right: tuple, cornerRadius: int = cornerRadius, color: tuple = (255,255,255), thickness: int = 1, lineType: int=cv2.LINE_AA) -> Any:\r\n # corners:\r\n # p1 - p2\r\n # | |\r\n # p4 - p3\r\n\r\n p1 = Point(top_left[0], top_left[1])\r\n p2 = Point(bottom_right[0], top_left[1])\r\n p3 = Point(bottom_right[0], bottom_right[1])\r\n p4 = Point(top_left[0], bottom_right[1])\r\n\r\n # Fill\r\n if thickness < 0:\r\n main_rect = [Point(p1.x + cornerRadius, p1.y), Point(p3.x - cornerRadius, p3.y)]\r\n left_rect = [Point(p1.x + cornerRadius, p1.y + cornerRadius), Point(p4.x, p4.y - cornerRadius)]\r\n right_rect = [Point(p2.x - cornerRadius, p2.y + cornerRadius), Point(p3.x, p3.y - cornerRadius)]\r\n\r\n [cv2.rectangle(src, rect[0].toTuple(), rect[1].toTuple(), color, thickness) for rect in [main_rect, left_rect, right_rect]]\r\n\r\n # Outline\r\n cv2.line(src, (p1.x+cornerRadius,p1.y), (p2.x-cornerRadius,p2.y), color, abs(thickness), lineType);\r\n cv2.line(src, (p2.x,p2.y+cornerRadius), (p3.x,p3.y-cornerRadius), color, abs(thickness), lineType);\r\n cv2.line(src, (p4.x+cornerRadius,p4.y), (p3.x-cornerRadius,p3.y), color, abs(thickness), lineType);\r\n cv2.line(src, (p1.x,p1.y+cornerRadius), (p4.x,p4.y-cornerRadius), color, abs(thickness), lineType);\r\n\r\n # Arc\r\n cv2.ellipse(src, (p1+Point(cornerRadius, cornerRadius)).toTuple(), (cornerRadius, cornerRadius), 180.0, 0, 90, color, thickness, lineType);\r\n cv2.ellipse(src, (p2+Point(-cornerRadius, cornerRadius)).toTuple(), (cornerRadius, cornerRadius), 270.0, 0, 90, color, thickness, lineType);\r\n cv2.ellipse(src, (p3+Point(-cornerRadius, -cornerRadius)).toTuple(), (cornerRadius, cornerRadius), 0.0, 0, 90, color, thickness, lineType);\r\n cv2.ellipse(src, (p4+Point(cornerRadius, -cornerRadius)).toTuple(), (cornerRadius, cornerRadius), 90.0, 0, 90, color, thickness, lineType);", "def round_corner(self,radius, fill):\r\n corner = Image.new('RGBA', (radius, radius), (0, 0, 0, 0))\r\n draw = ImageDraw.Draw(corner)\r\n draw.pieslice((0, 0, radius * 2, radius * 2), 180, 270, fill=fill)\r\n return corner", "def set_radius(self, radius):\n self._radius = radius\n self._reset_slot_bounds()", "def rounded_box(self, bt, br, bb, bl):\n tlrx, tlry = self.border_top_left_radius\n trrx, trry = self.border_top_right_radius\n brrx, brry = self.border_bottom_right_radius\n blrx, blry = self.border_bottom_left_radius\n\n tlrx = max(0, tlrx - bl)\n tlry = max(0, tlry - bt)\n trrx = max(0, trrx - br)\n trry = max(0, trry - bt)\n brrx = max(0, brrx - br)\n brry = max(0, brry - bb)\n blrx = max(0, blrx - bl)\n blry = max(0, blry - bb)\n\n x = self.border_box_x() + bl\n y = self.border_box_y() + bt\n width = self.border_width() - bl - br\n height = self.border_height() - bt - bb\n\n # Fix overlapping curves\n # See https://www.w3.org/TR/css-backgrounds-3/#corner-overlap\n ratio = min([1] + [\n extent / sum_radii\n for extent, sum_radii in (\n (width, tlrx + trrx),\n (width, blrx + brrx),\n (height, tlry + blry),\n (height, trry + brry),\n )\n if sum_radii > 0\n ])\n return (\n x, y, width, height,\n (tlrx * ratio, tlry * ratio),\n (trrx * ratio, trry * ratio),\n (brrx * ratio, brry * ratio),\n (blrx * ratio, blry * ratio))" ]
[ "0.79114413", "0.6763416", "0.6615487", "0.6506466", "0.6503821", "0.6501542", "0.6364012", "0.6357104", "0.6332116", "0.6317095", "0.62739325", "0.62622", "0.6216487", "0.61987716", "0.61970615", "0.61883825", "0.60820854", "0.6080519", "0.6069578", "0.6019931", "0.6009432", "0.60034645", "0.59890157", "0.59706897", "0.5926115", "0.59003204", "0.5892712", "0.58340275", "0.57703805", "0.5736647" ]
0.71043444
1
Updates the list of displayed attribute text inputs.
def _update_attr_list(self) -> None: old_flex_grid = self.flex_grid self.flex_grid = wx.FlexGridSizer(cols=3, vgap=5, hgap=10) wx_elements = [] for attr_id in self.attr_req_ids: button = self.attr_req_buttons[attr_id] attr_req_label_ctrl = self.attr_req_labels[attr_id] attr_req_element_ctrl = self.attr_req_elements[attr_id] wx_elements.extend([ (button, 0, wx.ALIGN_CENTER_VERTICAL), (attr_req_label_ctrl, 0, wx.EXPAND), (attr_req_element_ctrl, 1, wx.EXPAND) ]) self.flex_grid.AddMany(wx_elements) if old_flex_grid is not None: self.box.Replace(old_flex_grid, self.flex_grid) self.box.Layout()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _update_attr_list(self) -> None:\n old_flex_grid = self.flex_grid\n self.flex_grid = wx.FlexGridSizer(cols=3, vgap=5, hgap=10)\n wx_elements = []\n for attr_id in self.attr_ids:\n button = self.attr_buttons[attr_id]\n label_input = self.attr_labels[attr_id]\n value_input = self.attr_values[attr_id]\n wx_elements.extend([\n (button, 0, wx.ALIGN_CENTER_VERTICAL),\n (label_input, 0, wx.EXPAND),\n (value_input, 1, wx.EXPAND)\n ])\n self.flex_grid.AddGrowableCol(2, 1)\n self.flex_grid.AddMany(wx_elements)\n if old_flex_grid is not None:\n self.box.Replace(old_flex_grid, self.flex_grid)\n self.box.Layout()", "def update_values(self):\n for key in self.inputs.keys():\n value = self.inputs[key]['entry'].get()\n self.inputs[key]['value'] = value", "def change_display(self, func, text):\n for i in range(3, 5):\n Input.clear_display(self, self.entries[i])\n func.insert(INSERT, text)\n for i in range(3, 5):\n self.entries[i].configure(state='readonly')", "def _save_attrs(self) -> None:\n for attr_id in self.attr_ids:\n orig_label = self.attr_ids[attr_id]\n attr_label = self.attr_labels[attr_id].GetValue()\n attr_value = self.attr_values[attr_id].GetValue()\n if attr_label == '':\n continue\n if orig_label != attr_label and orig_label != '':\n self.element.attr.pop(orig_label)\n self.attr_ids[attr_id] = attr_label\n if attr_label not in self.element.attr \\\n or self.element.attr[attr_label] != attr_value:\n self.element.attr[attr_label] = attr_value", "def update_set(self):\n for field in self.children:\n if issubclass(field.__class__, MyTextField):\n val = field.get_field().value\n setattr(self.set, field.get_field().name, val if val != \"\" else None)", "def update_displays(self):\n for key, value in self.lnp.settings:\n if key in list(self.controls.keys()):\n if isinstance(self.controls[key], Entry):\n self.controls[key].delete(0, END)\n self.controls[key].insert(0, value)\n else:\n self.controls[key][\"text\"] = (\n self.controls[key][\"text\"].split(':')[0] + ': ' +\n value)", "def _load_attrs(self) -> None:\n self.attr_ids.clear()\n for attr_label, attr_value in self.element.attr.items():\n self.add_attr(None, attr_label, attr_value)\n self._update_attr_list()", "def set_inputs(self, inputs):\n self.attributes[\"inputs\"] = inputs", "def update_elements(self, viewer):\n for i in range(self.num_labels):\n lbl = self.lbls[i]\n # get data coord equivalents\n x, y = self.get_data_xy(viewer, (lbl.x, lbl.y))\n # format according to user's preference\n lbl.text = self.format_value(x)", "def storeListWidgetValues(self):\n\n\t\twidget = self.sender()\n\t\tcategory, attr = self.getWidgetMeta(widget)\n\t\titems = []\n\t\tfor i in range(widget.count()):\n\t\t\titems.append(widget.item(i).text())\n\t\tself.storeValue(category, attr, items)", "def OnAttributesUpdated():\n pass", "def update(self, attributes):\n for key in attributes:\n k = key.lower()\n if not isinstance(attributes[key], str) or attributes[key] != '':\n k_ = k.strip(' =:\\t\\n').replace('', '')\n self.attributes.update({k_: attributes[key]})\n elif k in self.attributes:\n del self.attributes[k]", "def _save_attrs(self) -> None:\n for attr_req_id in self.attr_req_ids:\n orig_label = self.attr_req_ids[attr_req_id]\n attr_req_label = self.attr_req_labels[attr_req_id].GetValue()\n attr_req_element = self.attr_requirements[self.element][orig_label]\n if attr_req_label == '':\n continue\n if orig_label != attr_req_label and orig_label != '':\n self.attr_requirements[self.element].pop(orig_label)\n self.attr_req_ids[attr_req_id] = attr_req_label\n if attr_req_label not in self.attr_requirements[self.element] \\\n or self.attr_requirements[self.element][\n attr_req_label] != attr_req_element:\n self.attr_requirements[self.element][\n attr_req_label] = attr_req_element", "def _update_field_list(self, value):\n # Convert sets (e.g. draw/display/navmesh groups) to sorted lists so empty sets appear pretty.\n value_text = repr(sorted(value)) if not isinstance(value, list) else repr(value)\n self.value_label.var.set(value_text)\n self._activate_value_widget(self.value_label)", "def updateAttributesAfterAdding(self):\n layer = self.sender()\n while self.addedFeatures:\n featureId = self.addedFeatures.pop()\n #begining the edit command\n # layer.beginEditCommand(self.tr(\"DSG Tools reclassification tool: adjusting feature's attributes\"))\n #accessing added features\n editBuffer = layer.editBuffer()\n features = editBuffer.addedFeatures()\n for key in features.keys():\n #just checking the newly added feature, the other I don't care\n if key == featureId:\n feature = features[key]\n #setting the attributes using the reclassification dictionary\n self.setFeatureAttributes(feature, editBuffer)\n layer.endEditCommand()", "def update_list(self, text):\n self.text_region.config(state=Tk.NORMAL)\n self.text_region.delete(1.0, Tk.END)\n self.text_region.insert(Tk.END, text)\n self.text_region.config(state=Tk.DISABLED)", "def searchAttributes(self):\n search_string = self.attr_search.text()\n for rowIndex in range(self.attributeTable.rowCount()):\n twItem = self.attributeTable.item(rowIndex, 0)\n if twItem.text().startswith(search_string):\n self.attributeTable.setRowHidden(rowIndex, False)\n else:\n self.attributeTable.setRowHidden(rowIndex, True)", "def _set_attributes(self):", "def __editAutoCompleteFromAll(self):\n self.activeWindow().autoCompleteFromAll()", "def __editAutoComplete(self):\n self.activeWindow().autoComplete()", "def edit(self, **kwargs):\r\n for attr in self.EDITABLE_ATTR:\r\n kwarg = kwargs.pop(attr, self._WILDCARD)\r\n if kwarg is not self._WILDCARD:\r\n setattr(self, attr, kwarg)\r\n logger.debug(\"Attribute '{}' changed to '{}'.\".format(attr, kwarg))\r\n\r\n for p_attr in self.EDITABLE_PRIVATE_ATTR:\r\n kwarg = kwargs.pop(p_attr, self._WILDCARD)\r\n if kwarg is not self._WILDCARD:\r\n setattr(self, \"_\" + p_attr, kwarg)\r\n logger.debug(\"Private attribute '{}' changed to '{}'.\".format(p_attr, kwarg))\r\n logger.debug(\"Configuration edited.\")", "def update_field_value_display(self, new_value):\n self.field_update_method(new_value)\n self._set_field_fg(new_value)\n self.link_missing = self.field_links and not any(link.name for link in self.field_links)\n self.build_field_context_menu()", "def __editAutoCompleteFromAPIs(self):\n self.activeWindow().autoCompleteFromAPIs()", "def load_input_fields(self):\n self.ui.boxNumberInput.setText(str(self.data[0]))\n self.ui.shelfNumberInput.setText(self.data[1])", "def refresh_attributes(self):\n if self.skill_tree_displaying:\n return\n player_panel_renderer.draw_attributes(self.player_dict['attributes'], self.level_up_points, refresh=True)\n if self.level_up_points > 0:\n player_panel_renderer.draw_attribute_level_up_buttons(self.level_up_points)", "def update_steps_display(self):\r\n self.steps_display[\"text\"] = str(self.steps.get())", "def reset_attributes(input_object, attr_name_list = None):\n if attr_name_list is None:\n attr_name_list = []\n if len(attr_name_list) > 0:\n attr_list = [input_object.attr(attr_name) for attr_name in attr_name_list]\n else:\n attr_list = general.get_channelbox_attributes(input_object)\n\n for attr in attr_list:\n # def_val = attr.get(default = True)\n def_val = pm.attributeQuery(attr.plugAttr(), node = attr.node(), listDefault = True)[0]\n if attr.isSettable():\n attr.set(def_val)", "def adjust_display(self, display: typing.List[typing.List[str]]):", "def refreshAttrStr(self):\n self.attributes_str = ';'.join(['='.join(\n [attr, self.attributes[attr]]) for attr in self.attributes_order])", "def on_submit(self, text):\n self.pp = [float(i.text) for i in self.text_boxes]\n self.pp_values = self.pp.copy()\n self.pp_mapping()\n self.redraw()" ]
[ "0.6706066", "0.58394015", "0.57136977", "0.5605623", "0.5420066", "0.5399311", "0.53753835", "0.5258919", "0.5243419", "0.5237437", "0.5222367", "0.521364", "0.5211479", "0.52040356", "0.5188745", "0.51685643", "0.5158266", "0.5157293", "0.5097068", "0.50787485", "0.50495744", "0.5044085", "0.5038987", "0.5024078", "0.50203884", "0.5017842", "0.50146794", "0.50021863", "0.5001006", "0.4992909" ]
0.6138667
1
Override to save changes to arguments before closing the frame.
def Close(self, *args, **kwargs): self._save_attrs() super().Close(*args, **kwargs)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def restore(self, arguments):\n puts_err(colored.red(\"Not implemented!\"))", "def close_extras(self, **kwargs):\n pass", "def close(*args):", "def close(*args):", "def close(*args):", "def close(*args):", "def close(*args):", "def _exit(self, save_vars):\n raise NotImplementedError()", "def close(self) -> None:\n if self.hit:\n logger.warning(\"No value provided for argument %r\", self.namestr())", "def OnClose(self):\n self.SaveData()\n self.destroy()", "def closed(self, *args, **kwargs) -> Any:\n pass", "def on_close(self, event):\n # Save pos and size\n x, y = self.GetPosition()\n width, height = self.GetSize()\n self.__config.set('window.x', x)\n self.__config.set('window.y', y)\n self.__config.set('window.width', width)\n self.__config.set('window.height', height)\n\n # Style\n style = self.GetWindowStyle()\n self.__config.set('window.style', style)\n\n self.__config.save()\n\n # Stop monitoring\n self.__cor.stop_monitor()\n\n # Kill graph as it seems to be stopping script from ending\n self.__graph = None\n\n # End\n event.Skip()", "def on_closing(self, *args):\n pass", "def close(self):\n\n self.config.worldinfo_w = self.width()\n self.config.worldinfo_h = self.height()\n super().close()", "def quit(self, *args, **kwargs):\n pass", "def close(self, **kw) -> None:\n super().close(**kw)", "def onSceneStartClose(self, caller, event):\n\t\t# Parameter node will be reset, do not use it anymore\n\t\tself.setParameterNode(None)", "def closeEvent(self, event):\n self.force_blurrer_quit()\n self.save()\n print(\"saved settings\")\n QMainWindow.closeEvent(self, event)", "def onSceneEndClose(self, caller, event):\n\t\t# If this module is shown while the scene is closed then recreate a new parameter node immediately\n\t\tif self.parent.isEntered:\n\t\t\tself.initializeParameterNode()", "def _set_arguments(self):\n self._arguments = []", "def closeEvent(self, event):\n\n self.settings.setValue('geometry', self.saveGeometry())\n self.settings.setValue('windowState', self.saveState())\n # TODO: need to modify\n # self.save_drawing_if_necessary()\n AppDocData.instance().clear()\n event.accept()", "def __window_close(self):\n pass", "def save_args(self, args) -> None:\n name = self._make_filepath(\"hparams.json\")\n with open(name, \"w\") as file:\n json.dump(vars(args), file)", "def frame_off_args(*args):\n return _ida_frame.frame_off_args(*args)", "def OnClose(self, event):\r\n pos.app.main.Exit()", "def end(self, *args):\n return _ida_hexrays.lvar_saved_infos_t_end(self, *args)", "def exit(self):\n\t\t# Do not react to parameter node changes (GUI wlil be updated when the user enters into the module)\n\t\tself.removeObserver(self._parameterNode, vtk.vtkCommand.ModifiedEvent, self.updateGUIFromParameterNode)", "def change_args(self, args):\n self.modified_args = args", "def goodbye(self, args):\n\t\tself.write_line(\"GOODBYE\")\n\t\tself.close();", "def __call__(self, connection, window_info, original_kwargs):\n raise NotImplementedError" ]
[ "0.6397291", "0.6238765", "0.62264043", "0.62264043", "0.62264043", "0.62264043", "0.62264043", "0.6015775", "0.6008856", "0.60076225", "0.5912482", "0.5897535", "0.5865324", "0.5848845", "0.58236265", "0.57882524", "0.577333", "0.57647246", "0.5741745", "0.57246125", "0.56510425", "0.56354386", "0.56258166", "0.56130946", "0.5596472", "0.55917746", "0.55736655", "0.5570463", "0.55202407", "0.549209" ]
0.6632843
1
Setup all the visual setting of the matplotlib canvas, figure and subplot. This function needs to be called every time the mpl figure is redrawn because clearing the figure allso resets all these visual settings.
def setup_mpl_visuals(self, axes=None) -> None: if axes is None: axes = self.subplot axes.patch.set_facecolor('white') axes.set_aspect('equal', 'box') axes.set_xlim(-10, 10, auto=True) axes.set_ylim(-10, 10, auto=True) # TODO: Make XYLim confort to window size/dimensions axes.set_xticks([]) axes.set_yticks([]) self.figure.subplots_adjust(bottom=0, top=1, left=0, right=1) axes.axis('off')
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _InitAxes( self ):\n self.ax = self.fig.add_subplot( 111 )", "def _setup_figure(self):\n\n plt.figure(1)\n plt.clf()\n\n # Two main axes\n self._tsne_window = plt.axes([0.05, 0.05, 0.4, 0.4])\n self._main_window = plt.axes([0.05, 0.55, 0.4, 0.4])\n\n # Nine sub axes\n self._sub_windows = []\n for row in range(3):\n for col in range(3):\n tt = plt.axes([0.5+0.17*col, 0.75-0.25*row, 0.15, 0.15])\n tt.set_xticks([])\n tt.set_yticks([])\n self._sub_windows.append(tt)\n\n # Register the button click\n self._cid = plt.figure(1).canvas.mpl_connect('button_press_event', self._onclick)\n\n # Text\n plt.figure(1).text(0.6, 0.2, 'Click with 2nd or 3rd mouse button to select image...')\n plt.figure(1).text(0.05, 0.5, 'Click in main image or tSNE plot to find similar cutouts...')\n plt.figure(1).text(0.6, 0.05, 'The tSNE data reduction calculated from data run through {}'.format(self._model_name), fontsize=8)\n\n # Show\n plt.figure(1).show()\n plt.figure(1).canvas.draw()", "def set_figure_variables(self):\n #self.fig.canvas.manager.full_screen_toggle()\n self.gs = self.fig.add_gridspec(2, 3)\n self.ax1 = self.fig.add_subplot(self.gs[0, 0])\n self.ax2 = self.fig.add_subplot(self.gs[0, 1])\n self.ax3 = self.fig.add_subplot(self.gs[0, 2])\n self.ax4 = self.fig.add_subplot(self.gs[1, 0])\n self.ax5 = self.fig.add_subplot(self.gs[1, 1])\n self.ax6 = self.fig.add_subplot(self.gs[1, 2])\n # histogram with indicator scoring\n self.ax1.set_xlabel(\"indicators\")\n self.ax1.set_ylabel(\"score (%)\")\n # graph with flood safety levels\n self.ax2.set_xlabel(\"dike section\")\n self.ax2.set_ylabel(\"chance of flooding occurrence\")\n # graph with water levels vs dike height\n self.ax3.set_xlabel(\"river length (meters)\")\n self.ax3.set_ylabel(\"height (meters)\")\n # graph with overall costs made\n self.ax6.set_ylabel(\"million Euros\")\n \n self.ax1.set_ylim([0, 100])\n self.ax2.set_ylim([0, 100])\n self.ax3.set_ylim([14, 18])\n self.ax6.set_ylim([0, 25000000])\n \n self.ax1.set_title(\"Overall score on indicators\")\n self.ax2.set_title(\"Flood safety levels\")\n self.ax3.set_title(\"Normative water levels vs dike crest height\")\n self.ax6.set_title(\"Budget spent\")\n \n self.x_pos = np.arange(len(self.indicators))\n self.ax1.set_xticks(self.x_pos)\n self.ax1.set_xticklabels(self.indicators)\n \n flood_safety_levels = [100, 200, 400, 600, 800, 1000, 1250]\n self.ax2.set_yticks(flood_safety_levels)\n self.ax2.set_yticklabels([\"1/\"+str(value) for value in flood_safety_levels])\n \n self.plot1 = None\n self.plot2 = None\n self.plot3 = None\n self.plot4 = None\n self.plot5 = None\n self.plot6 = None\n return", "def plot_finalize():\n global figure\n global axes\n\n plot_refresh()\n plt.ioff()\n plt.show()\n\n figure, axes = None, None", "def figure(self):\n if self._figure is None:\n\n self._figure, ax = plt.subplots(nrows=1, dpi=self._dpi)\n if self._verbose:\n print(f\" Figure dpi set to {self._dpi}\")\n\n self._figure.set_size_inches(self._size)\n if self._verbose:\n print(\" Figure size set to \" + str(self._size) + \" inches.\")\n\n for model in self._models:\n xs, ys, _ = zip(*model._nodes)\n\n for face in model._elements:\n xf = tuple(xs[k - 1] for k in face) # 1-base index to 0-base index\n yf = tuple(ys[k - 1] for k in face)\n # plt.fill(\n # xf,\n # yf,\n # linestyle=\"dotted\",\n # edgecolor=\"magenta\",\n # alpha=0.5,\n # facecolor=\"gray\",\n # )\n plt.fill(\n xf,\n yf,\n alpha=model._alpha,\n edgecolor=model._edgecolor,\n facecolor=model._facecolor,\n linestyle=model._linestyle,\n linewidth=model._linewidth,\n )\n\n if self._xticks:\n ax.set_xticks(self._xticks)\n\n if self._yticks:\n ax.set_yticks(self._yticks)\n\n if self._xlim:\n ax.set_xlim(self._xlim)\n\n if self._ylim:\n ax.set_ylim(self._ylim)\n\n if self._xlabel:\n ax.set_xlabel(self._xlabel)\n\n if self._ylabel:\n ax.set_ylabel(self._ylabel)\n\n # set frame on or off based on the Bool \"frame\" in .json input\n ax.set_frame_on(b=self._frame)\n if len(self._tick_params) > 0:\n ax.tick_params(**self._tick_params)\n\n if self._display:\n plt.show()\n\n if self._serialize:\n self.serialize(self._folder, self._file)\n\n plt.close(\"all\")\n self._figure = None", "def _plot_setup(self, fig, ax):\n\n self._check_data_valid()\n\n if ax:\n self.fig = fig\n self.ax = ax\n else:\n self.fig = plt.figure()\n self.ax = self.fig.add_subplot(111, projection=self.wcs)\n\n # Set basic figure display options\n if self.options.get('grid', True):\n self.ax.coords.grid(color='white', alpha=0.5)\n\n if self.options.get('title', True):\n title = self.options.get('title', self.surveyname)\n self.ax.set_title(title, fontdict={'fontsize': 20, 'fontweight': 10})\n\n self.set_xlabel('RA (J2000)')\n self.set_ylabel('Dec (J2000)')\n\n # Set compact or extended label / tick configuration\n if self.options.get('compact', False):\n tickcolor = 'k' if np.nanmax(np.abs(self.data)) == np.nanmax(self.data) else 'gray'\n\n lon = self.ax.coords[0]\n lat = self.ax.coords[1]\n\n lon.display_minor_ticks(True)\n lat.display_minor_ticks(True)\n\n lon.set_ticks(number=5)\n lat.set_ticks(number=5)\n\n self.ax.tick_params(axis='both', direction='in', length=5, color=tickcolor)\n self.padlevel = self.options.get('ylabelpad', 5)\n\n # Set colourmap normalisation\n self.norm = self._get_cmap_normalisation()", "def _UpdatePlotImpl( self ):\n if self.ax is not None:\n self.axline = None\n self.cursorLine = \\\n self.cursorLine2 = None\n\n# self.ax.clear()\n# if hasattr( self, 'ax2' ) and self.ax2 is not None:\n# self.ax2.clear()\n self.fig.clear()\n self._InitAxes()\n\n#\t\t-- Scale fonts\n#\t\t--\n wd, ht = self.GetClientSize()\n label_font_size = 14\n tick_font_size = 12\n self.titleFontSize = 16\n if 'wxMac' not in wx.PlatformInfo and wd < 800:\n\tdecr = (800 - wd) / 50.0\n\tlabel_font_size -= decr\n\ttick_font_size -= decr\n\tself.titleFontSize -= decr\n\n# self.ax.grid(\n# True, 'both', 'both',\n#\t color = '#c8c8c8', linestyle = ':', linewidth = 1\n#\t )\n self._DoUpdatePlot( wd, ht )\n self._DoUpdateRedraw()\n self.canvas.draw()\n #end if", "def _doPlots(self):\n ax = self.sp.ax\n if ax: ax.helper.doPlots()\n # Setting calls now use new local options\n self.opts.newLocal()", "def _setFig(self):\n self.p.background_fill_color = grey['light']\n self.p.xgrid.grid_line_color = None\n self.p.ygrid.grid_line_color = None\n self.p.ygrid.grid_line_dash = 'dotted'\n self.p.ygrid.grid_line_dash = 'dotted'\n\n self.p.xgrid.minor_grid_line_color = grey['median']\n self.p.ygrid.minor_grid_line_color = grey['median']\n self.p.xgrid.minor_grid_line_dash = 'dotted'\n self.p.ygrid.minor_grid_line_dash = 'dotted'\n\n self.p.xaxis.axis_label = \"tsne_feature_0\"\n self.p.yaxis.axis_label = \"tsne_feature_1\"", "def set_canvas(self):\n self.ui.figure = plt.figure(figsize=(10, 10))\n self.ui.figure.patch.set_facecolor('None')\n self.ui.canvas = FigureCanvas(self.ui.figure)\n self.ui.canvas.setStyleSheet('background-color:transparent;')\n # Matplotlib toolbar\n self.ui.toolbar = NavigationToolbar(self.ui.canvas, self)\n self.ui.toolbar.setMaximumHeight(30)\n self.ui.figureLayout.addWidget(self.ui.toolbar)\n self.ui.figureLayout.addWidget(self.ui.canvas)\n self.ui.canvas.mpl_connect('button_press_event', self.onclick)\n self.ui.canvas.mpl_connect('pick_event', self.onclick_pick)", "def plot_settings(clear = True, grid = True):\n if clear:\n plt.clf() # Clears any previous figures\n\n # Setting figure size\n figure = plt.gcf()\n figure.set_size_inches(18, 10)\n\n # Setting size of plot elements\n plt.rc('axes', labelsize = 22, titlesize = 24) \n plt.rc('xtick', labelsize = 18) \n plt.rc('ytick', labelsize = 18) \n plt.rc('legend', fontsize = 20)\n plt.rc('axes', axisbelow = True) # Ensures that the grid is behind any graph elements\n if grid:\n plt.grid() # Adds a grid to the plot", "def redraw(self):\n dummy_figure = plt.figure()\n new_manager = dummy_figure.canvas.manager\n new_manager.canvas.figure = self.figure\n self.figure.set_canvas(new_manager.canvas)\n plt.show(block=False)", "def plot_clear():\n plt.cla()", "def createFigure(self,numSubplots,figWidth,figHeight):\r\n#\t\tif self.makeTB:\r\n#\t\t\tself.createToolbar(self.vbox)\r\n#\t\tself.vbox.pack_start(self.myTB,False,False)\r\n\t\tself.axisList=[]\r\n\t\tself.axis=None\r\n\t\t# define handles to widgets\r\n\r\n\t\t############## FIGURE\r\n\t\tself.figure = Figure(dpi=60)\t\t\r\n\t\tself.figure.set_facecolor(figBgColour)\r\n\t\tself.figure.set_edgecolor(figBgColour)\r\n\r\n\t\t#self.axis.set_title('Graph')\r\n\r\n\t\tself.canvas = FigureCanvas(self.figure)\r\n\t\tself.canvas.set_size_request(figWidth,figHeight)\r\n\t\tself.canvas.show()\r\n\t\tself.buttonCallback=self.canvas.mpl_connect('button_press_event', self.OnPress)\r\n#\t\tself.canvas.mpl_connect('resize_event', onAutoScale, None, self.axis, self.canvas)\r\n\r\n \r\n\t\t############## AXIS\r\n\t\t#self.axis=self.figure.add_axes(plotPosition,axisbg=axisColour)\r\n\t\tsubplotList=[]\r\n\t\tfor m in range(numSubplots[0]*numSubplots[1]):\r\n\t\t\tsubplotList.append(numSubplots[0]*100 + numSubplots[1] * 10 + m+1)\r\n\r\n\t\tif len(subplotList)==1:\r\n\t\t\tself.axisList.append(self.figure.add_subplot(111,axisbg=axisColour,polar=self.plotPolar))\r\n\t\t\tself.axisList[0].set_position(PLOT_POSITION)\r\n\t\telse:\r\n\t\t\tfor x in subplotList:\r\n\t\t\t\tself.axisList.append(self.figure.add_subplot(x,axisbg=axisColour))\r\n\r\n\t\tself.axis=self.axisList[0]\r\n\r\n\t\t# format each axis correctly\r\n\t\tfor axis in self.axisList:\r\n\t#\t\tself.axis.grid(True,which='major')\r\n\t\t\taxis.grid(True)\r\n\t#\t\tself.axis.grid(True,which='minor',color='r', linestyle='-', linewidth=2)\r\n\t#\t\tself.axis.set_position(plotPosition)\r\n\r\n\t\t\txax=axis.get_xticklabels()\r\n\t\t\tyax=axis.get_yticklabels()\r\n\r\n\t\t\tfor tick in xax:\r\n\t\t\t\ttick.set_fontsize(axisTextSize)\r\n\r\n\t\t\tfor tick in yax:\r\n\t\t\t\ttick.set_fontsize(axisTextSize)\t\t\r\n\r\n\t\t\r\n\t\tself.legendStr=[]\r\n\t\tself.gaList=[]\r\n\r\n\t\t## add cursor function to axis when mouse is over it\r\n#\t\tself.cursor = Cursor(self.axis, useblit=True, color='red', linewidth=1)\r\n\r\n\t\tself.canvas.draw()\r\n\r\n\t\t# plot a transparent rectangle just on axis 1\r\n\t\tcurrXlim=self.axis.get_xlim()\r\n\t\tdx=abs(currXlim[1]-currXlim[0])\r\n\t\tx0=currXlim[0]\r\n\t\tcurrYlim=self.axis.get_ylim()\r\n\t\tdy=abs(currYlim[1]-currYlim[0])\r\n\t\ty0=currYlim[0]\r\n\r\n\t\tself.axis.r1=plotRect(self.axis,self.canvas,(x0,y0),dx,dy,showRect=self.showRect)\r\n\r\n\t\t#self.axis.cla()\r\n\r\n\t\t\r\n\t\t############## TOOLBAR\r\n\t\t# use a custom version of the matplotlib toolbar\r\n#\t\ttoolbar = NavigationToolbar2(self.canvas, self.win)\r\n\t\tself.toolbar = PlotToolbar(self.canvas,self.win,self.axis)\r\n\t\tzoomtoolbar = PlotZoomToolbar(self.canvas,self.win,self.axis,)\r\n\r\n\t\t# make a TB menu\r\n\t\tmenuList=['|FFT|','Normalised |FFT|','|FFT| & arg(FFT)','|T| & <T','Re & Im (T)','Re & Im (1/T - 1)','n & alpha']\r\n\t\tmnuBtn = MenuToolButtonWidget(menuList, icon=gtk.STOCK_SELECT_COLOR, label='FFT')\r\n\t\tmnuBtn.btn.connect(\"clicked\",self.newFFTwin2,0)\r\n\t\tfor m in range(len(menuList)):\r\n\t\t\tmnuBtn.menuItems[m].connect(\"activate\",self.newFFTwin,m)\r\n\r\n\t\tmnuBtn.btn.set_tooltip_text('Take windowed FFT of ALL lines.')\r\n\t\tself.toolbar.add(mnuBtn.btn)\r\n\r\n\r\n\r\n\t\tsep=gtk.SeparatorToolItem()\r\n\t\tself.toolbar.insert(sep,1)\r\n\r\n\r\n\t\tbtn6=gtk.ToolButton(gtk.STOCK_CLEAR)\r\n\t\tbtn6.connect(\"clicked\",self.OnClear)\r\n\t\tbtn6.set_label('Clear')\r\n\t\tbtn6.set_tooltip_text('Clear the axis.')\r\n\t\tself.toolbar.insert(btn6,1)\r\n\r\n\t\tbtn0=gtk.ToolButton(gtk.STOCK_SAVE_AS)\r\n\t\tbtn0.connect(\"clicked\",self.OnExport)\r\n\t\tbtn0.set_label('Export')\r\n\t\tbtn0.set_tooltip_text('Export data from a curve.')\r\n\t\tself.toolbar.insert(btn0,1)\r\n\r\n\r\n\t\t# make a TB menu\r\n\t\tfitMenuList=['Linear','Polynomial','Exp decay','Subtract exp']\r\n\t\tfitmnuBtn = MenuToolButtonWidget(fitMenuList, icon=gtk.STOCK_ABOUT, label='Fit')\r\n\t\tfitmnuBtn.btn.connect(\"clicked\",self.fitPolynomial,0)\r\n\t\tfor m in range(len(fitMenuList)):\r\n\t\t\tfitmnuBtn.menuItems[m].connect(\"activate\",self.fitPolynomial,m)\r\n\r\n\t\tfitmnuBtn.btn.set_tooltip_text('Fits a polynomial to data (default is a linear fit).')\r\n\t\tself.toolbar.add(fitmnuBtn.btn)\r\n\r\n\r\n\t\tbtn7=gtk.ToolButton(gtk.STOCK_CONVERT)\r\n\t\tbtn7.connect(\"clicked\",self.getBeamWidth)\r\n\t\tbtn7.set_label('Beamwidth')\r\n\t\tbtn7.set_tooltip_text('Get the beamwidth (fits Gaussian to dy/dx).')\r\n\t\tself.toolbar.add(btn7)\r\n\r\n\t\tbtn8=gtk.ToolButton(gtk.STOCK_EDIT)\r\n\t\tbtn8.connect(\"clicked\",self.editPlotParams)\r\n\t\tbtn8.set_label('Axes')\r\n\t\tbtn8.set_tooltip_text('Edit plot parameters.')\r\n\t\tself.toolbar.add(btn8)\r\n\r\n\t\tbtn9=gtk.ToolButton(gtk.STOCK_PROPERTIES)\r\n\t\tbtn9.connect(\"clicked\",self.editLegend)\r\n\t\tbtn9.set_label('Legend')\r\n\t\tbtn9.set_tooltip_text('Edit legend.')\r\n\t\tself.toolbar.add(btn9)\r\n\r\n#\t\tself.toolbar.set_style(gtk.TOOLBAR_BOTH) # make toolbar icons and labels visible\r\n\r\n\t\tif self.makeTB:\r\n\t\t\tself.vbox.pack_start(self.toolbar,False,False)\r\n\r\n\t\tself.vbox.pack_start(self.canvas,True,True)\r\n\t\tself.vbox.pack_start(zoomtoolbar,False,False)\r\n\r\n\t\t####### Line selector/axis alteration toolbar\r\n\t\thbox=gtk.HBox(homogeneous=False, spacing=0)\r\n\r\n\t\tparamNames = ['Line:']\r\n\t\tparamTypes = ['cmb']\r\n\t\tparamDefaultValues = [[]]\r\n\r\n\t\tparamBox = ParamWidget(paramNames,paramTypes,paramDefaultValues)\r\n\t\tself.cmbBox = paramBox.objectList[0]\r\n#\t\tself.cmbBox.connect('changed',self.line_changed)\r\n\r\n\t\tself.hideBtn = gtk.ToggleToolButton(gtk.STOCK_NO)\r\n\t\tself.hideBtn.set_tooltip_text('Hide')\r\n\t\tself.hideBtn.connect('clicked',self.toggle_line)\r\n\t\tparamBox.table.attach(self.hideBtn,0,1,0,1,xoptions=gtk.EXPAND,yoptions=gtk.EXPAND)\r\n\t\t\r\n\t\tself.colourBtn = gtk.ToolButton(gtk.STOCK_COLOR_PICKER)\r\n\t\tself.colourBtn.set_tooltip_text('Colour')\r\n\t\tself.colourBtn.connect('clicked',self.change_colour)\r\n\t\tself.color=gtk.gdk.Color(red=0,green=0,blue=1)\r\n\r\n\t\tparamBox.table.attach(self.colourBtn,1,2,0,1,xoptions=gtk.EXPAND,yoptions=gtk.EXPAND)\r\n\t\t\r\n\t\tself.cmbStyle = gtk.combo_box_new_text()\r\n\r\n\t\tfor style in STYLES:\r\n\t\t\tself.cmbStyle.append_text(style)\r\n\t\tself.cmbStyle.set_active(0)\r\n#\t\tself.style.set_tooltip_text('Line style')\r\n\t\tself.cmbStyle.connect('changed',self.change_style)\r\n\r\n\t\tparamBox.table.attach(self.cmbStyle,2,3,0,1,xoptions=gtk.EXPAND,yoptions=gtk.EXPAND)\r\n\r\n\t\tself.removeBtn = gtk.ToolButton(gtk.STOCK_DELETE)\r\n\t\tself.removeBtn.set_tooltip_text('Remove')\r\n\t\tself.removeBtn.connect('clicked',self.remove_line)\r\n\r\n\t\tparamBox.table.attach(self.removeBtn,3,4,0,1,xoptions=gtk.EXPAND,yoptions=gtk.EXPAND)\r\n\r\n\r\n\t\thbox.pack_start(paramBox.frame,False,False)\r\n\r\n\t\tparamNames = ['Axis:','Left-click sets:']\r\n\t\tparamTypes = ['lbl','cmb']\r\n\t\tparamDefaultValues = ['',['Nothing','Window left','Window right','Axis left','Axis right','Plots point']]\r\n\r\n\t\tparamBox = ParamWidget(paramNames,paramTypes,paramDefaultValues)\r\n\t\thbox.pack_start(paramBox.frame,False,False)\r\n\t\t\r\n\t\tself.cmbBtn = paramBox.objectList[1]\r\n\t\tself.cmbBtn.set_active(0)\r\n\t\tself.cmbBtn.connect(\"changed\", self.onModeChanged)\r\n\r\n\t\thbox.show_all()\r\n\r\n#\t\tself.canvas.mpl_connect('axes_enter_event', self.enter_axes)\r\n#\t\tself.canvas.mpl_connect('axes_leave_event', self.leave_axes)\r\n\r\n\t\tif self.makeTB:\r\n#\t\t\tself.connectToolbar()\r\n\t\t\tself.vbox.pack_start(hbox,False,False)", "def reset(self):\n try:\n self.ax.cla()\n except Exception as e:\n print 'Exception BasePlot:', e\n raise e\n \n self._plotbuffer = { pat: [0 for _ in range(self._plotlength)] for pat in self._patterns }\n self._timestampbuffer = { pat: [0 for _ in range(self._plotlength)] for pat in self._patterns }\n self.ax.set_axis_bgcolor('black')\n self.ax.set_xticks([])\n self.ax.set_yticks([])", "def setup_figure(self):\n \n # connect ui widgets to measurement/hardware settings or functions\n self.ui.start_pushButton.clicked.connect(self.start)\n self.ui.interrupt_pushButton.clicked.connect(self.interrupt)\n self.settings.save_h5.connect_to_widget(self.ui.save_h5_checkBox)\n self.settings.save_movie.connect_to_widget(self.ui.save_movie_checkBox)\n \n # Set up pyqtgraph graph_layout in the UI\n self.graph_layout=pg.GraphicsLayoutWidget()\n self.ui.plot_groupBox.layout().addWidget(self.graph_layout)\n \n self.aux_graph_layout=pg.GraphicsLayoutWidget()\n self.ui.aux_plot_groupBox.layout().addWidget(self.aux_graph_layout)\n \n self.camera_layout=pg.GraphicsLayoutWidget()\n self.ui.camera_groupBox.layout().addWidget(self.camera_layout)\n\n # Create PlotItem object (a set of axes) \n \n self.plot1 = self.graph_layout.addPlot(row=1,col=1,title=\"Lick\")\n self.plot2 = self.graph_layout.addPlot(row=2,col=1,title=\"breathing\")\n\n # Create PlotDataItem object ( a scatter plot on the axes )\n self.breathing_plot = self.plot2.plot([0])\n self.lick_plot_0 = self.plot1.plot([0])\n self.lick_plot_1 = self.plot1.plot([1]) \n \n self.lick_plot_0.setPen('y')\n self.lick_plot_1.setPen('g')\n \n self.T=np.linspace(0,10,10000)\n self.k=0\n \n self.camera_view=pg.ViewBox()\n self.camera_layout.addItem(self.camera_view)\n self.camera_image=pg.ImageItem()\n self.camera_view.addItem(self.camera_image)", "def redraw(self, **kwargs):\n #src_dict = self.data_sources\n #self.remove_sources(src_dict.keys())\n self.renderers = {}\n #self.renderers = {}\n self.figure = self.draw_figure(**kwargs)\n #self.add_sources(src_dict)\n # todo does the old figure linger on?\n self.render_sources(self.data_sources)\n self.bk_pane.object = self.figure", "def redraw_figures(self):\n pass", "def redraw_figures(self):\n pass", "def _setup_plot(x: float, y: float) -> plt.figure:\n LOG.debug(\"Initializing plot.\")\n plt.ion()\n fig = plt.figure(figsize=(x, y), num=\"GlacierFlowModel\")\n fig.patch.set_facecolor(\"black\")\n return fig", "def __init__(self, container, app):\n\n super(PlotCanvas, self).__init__()\n\n self.app = app\n\n # Options\n self.x_margin = 15 # pixels\n self.y_margin = 25 # Pixels\n\n # Parent container\n self.container = container\n\n # Plots go onto a single matplotlib.figure\n self.figure = Figure(dpi=50) # TODO: dpi needed?\n self.figure.patch.set_visible(False)\n\n # These axes show the ticks and grid. No plotting done here.\n # New axes must have a label, otherwise mpl returns an existing one.\n self.axes = self.figure.add_axes([0.05, 0.05, 0.9, 0.9], label=\"base\", alpha=0.0)\n self.axes.set_aspect(1)\n self.axes.grid(True)\n\n # The canvas is the top level container (FigureCanvasQTAgg)\n self.canvas = FigureCanvas(self.figure)\n # self.canvas.setFocusPolicy(QtCore.Qt.ClickFocus)\n # self.canvas.setFocus()\n\n #self.canvas.set_hexpand(1)\n #self.canvas.set_vexpand(1)\n #self.canvas.set_can_focus(True) # For key press\n\n # Attach to parent\n #self.container.attach(self.canvas, 0, 0, 600, 400) # TODO: Height and width are num. columns??\n self.container.addWidget(self.canvas) # Qt\n\n # Copy a bitmap of the canvas for quick animation.\n # Update every time the canvas is re-drawn.\n self.background = self.canvas.copy_from_bbox(self.axes.bbox)\n\n ### Bitmap Cache\n self.cache = CanvasCache(self, self.app)\n self.cache_thread = QtCore.QThread()\n self.cache.moveToThread(self.cache_thread)\n super(PlotCanvas, self).connect(self.cache_thread, QtCore.SIGNAL(\"started()\"), self.cache.run)\n # self.connect()\n self.cache_thread.start()\n self.cache.new_screen.connect(self.on_new_screen)\n\n # Events\n self.canvas.mpl_connect('button_press_event', self.on_mouse_press)\n self.canvas.mpl_connect('button_release_event', self.on_mouse_release)\n self.canvas.mpl_connect('motion_notify_event', self.on_mouse_move)\n #self.canvas.connect('configure-event', self.auto_adjust_axes)\n self.canvas.mpl_connect('resize_event', self.auto_adjust_axes)\n #self.canvas.add_events(Gdk.EventMask.SMOOTH_SCROLL_MASK)\n #self.canvas.connect(\"scroll-event\", self.on_scroll)\n self.canvas.mpl_connect('scroll_event', self.on_scroll)\n self.canvas.mpl_connect('key_press_event', self.on_key_down)\n self.canvas.mpl_connect('key_release_event', self.on_key_up)\n self.canvas.mpl_connect('draw_event', self.on_draw)\n\n self.mouse = [0, 0]\n self.key = None\n\n self.pan_axes = []\n self.panning = False", "def init_plot(self):\n self.dpi = 100\n self.fig = Figure((5.0, 5.0), dpi = self.dpi)\n\n self.main_plot = self.fig.add_subplot(111)\n self.main_plot.set_axis_bgcolor('black')\n self.main_plot.set_title('Dynamic venous flow view', size = 12)\n\n pylab.setp(self.main_plot.get_xticklabels(), fontsize = 8)\n pylab.setp(self.main_plot.get_yticklabels(), fontsize = 8)\n\n # Plot the data as a green line\n self.plot_data = self.main_plot.plot(\n self.daq.data0,\n linewidth = 1,\n color = (0, 1, 0),\n )[0]\n self.main_plot.grid(True, color='gray')", "def clear(self):\n\n # Clear\n self.axes.cla()\n try:\n self.figure.clf()\n except KeyError:\n FlatCAMApp.App.log.warning(\"KeyError in MPL figure.clf()\")\n\n # Re-build\n self.figure.add_axes(self.axes)\n self.axes.set_aspect(1)\n self.axes.grid(True)\n\n # Re-draw\n self.canvas.draw_idle()", "def set_up(self):\n self.h, = self.ax.plot(self.x, lw=2)\n self.ax.set_ylim(0,100)\n self.ax.set_xlim(0,100)\n self.ax.title.set_text(self.config[\"title\"])\n self.ax.set_xlabel(self.config[\"x_label\"])\n self.ax.set_ylabel(self.config[\"y_label\"])", "def setup_layout(self):\n\n # check if we should animate plot\n anim = self.get_option(self.sctn,'animate')\n if anim != None:\n self.animate = anim.lower() in ['t','true','1']\n else:\n self.animate = False\n self.anim_range=[]\n t = self.get_option(self.sctn,'anim_start')\n if t!=None:\n self.anim_range.append(int(t))\n else:\n self.anim_range.append(0)\n t = self.get_option(self.sctn,'anim_end')\n if t!=None:\n self.anim_range.append(int(t))\n else:\n self.anim_range.append(5)\n \n self.times = self.get_option(self.sctn,'times')\n if self.times == \"None\":\n self.times = [None]\n else:\n self.times = self.times.split()\n \n if len(self.variables)>1:\n self.numdata = len(self.variables)\n else:\n self.numdata = len(self.times)\n try:\n self.numcol = int(self.get_option(self.sctn,'ncol'))\n except:\n self.numcol = self.numdata\n if len(self.variables)>1:\n self.numrow = len(self.times)\n else:\n self.numrow = 1", "def setup(self, flags):\n self.figure = pylab.figure(1)\n self.axes = {}\n self.stream_data = {}\n self.flags = flags", "def initialize(self) -> None:\n # Only do matplotlib import when necessary\n super().initialize()\n from matplotlib import pyplot as plt\n self.fig, self.ax = plt.subplots()\n if self.state_map is not None:\n self._add_state_map(self.state_map)\n else:\n self.categories = self.simulation.state_list", "def init_axes(self):\n plt.switch_backend(\"cairo\")\n fig = plt.figure(figsize=(15,10))\n ax = fig.add_axes([0.05, 0.15, 0.9, 0.80,])\n return (fig, ax)", "def __init__(self, parent_frame, plt_props=None):\n tk.Frame.__init__(self, master=parent_frame)\n if self.matplotlib_ready():\n \"\"\" the import statements are scoped so make new ones\"\"\"\n import matplotlib\n import matplotlib.pyplot as plt\n from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg\n\n\n self.figure_bed = plt.figure(figsize=(7, 3.5))\n self.axis = self.figure_bed.add_subplot(111)\n\n if plt_props:\n for key, value in plt_props.iteritems():\n eval(\"plt.\" + key + \"(\" + value + \")\")\n # self.axis.set_axis_bgcolor('red')\n self.figure_bed.set_facecolor('white')\n self.canvas = FigureCanvasTkAgg(self.figure_bed, master=self)\n self.canvas._tkcanvas.config(highlightthickness=0)\n self.canvas.draw()\n self.canvas.get_tk_widget().pack(side='top')\n\n # self.make_matplotlib_area(parent, plt_props)\n self.embed_matplotlib()\n self.type = 'matplotlib'\n # TODO ADD TO THIS\n else:\n graph = tk.Canvas(master=self)\n graph.pack(side='left', expand=True, fill=tk.BOTH)\n self.type = 'canvas'", "def initialize_plots(self):\r\n #============================Draw circuit canvas=================================#\r\n # Draw Canvas with hardcoded width 600 and adjustable height to circuit input\r\n ckt_max_x = 600\r\n ckt_max_y = (ckt_max_x*(self.rows))/self.cols\r\n scale_x = round(ckt_max_x / self.cols)\r\n scale_y = round(ckt_max_y / self.rows)\r\n self.canvasCirkt = tk.Canvas(self.master,width=ckt_max_x+scale_x,height=(ckt_max_y*2)+int(scale_y))\r\n self.canvasCirkt.grid(row=1,column=1,columnspan=4)\r\n\r\n # Draw border\r\n self.canvasCirkt.create_rectangle(1, 1, (ckt_max_x+2)/2, (ckt_max_y*2)+int(scale_y))\r\n self.canvasCirkt.create_rectangle(((ckt_max_x+2)/2)+scale_x, 1, ckt_max_x+scale_x, (ckt_max_y*2)+int(scale_y))\r\n \r\n # Draw cell rows and columns in two groups\r\n blockIndex=0\r\n for cut in range(int(scale_y), int(ckt_max_y*2), int(scale_y)*2):\r\n for cut2 in range(1, int(ckt_max_x), int(scale_x)):\r\n if (cut2>ckt_max_x/2):\r\n cut2+=scale_x\r\n # Coordinates for top and bottom points of rectangle\r\n points = (cut2, cut, cut2+scale_x-1, cut+scale_y)\r\n blockObj = partitionGUI.Block(self.canvasCirkt,points,blockIndex,self.rows,self.cols)\r\n blockIndex+=1\r\n if (cut2>ckt_max_x/2):\r\n self.blocksB.append(blockObj)\r\n else:\r\n self.blocksA.append(blockObj)\r\n \r\n \r\n #===================================Draw Plots================================#\r\n # Draw Figure for 2 subplots (Connections Graph and Cost Function) \r\n self.figure, self.axes = plt.subplots(2, facecolor=\"white\")\r\n self.figure.set_figwidth(4)\r\n self.axGraph = self.axes[0]\r\n self.axCost = self.axes[1]\r\n \r\n # Initial condition for connection Graph\r\n self.axGraph.set_visible(False)\r\n \r\n # Select Cost Plot as current Axis. Get lines to use for plot updates\r\n plt.sca(self.axCost) \r\n self.lines, = self.axCost.plot([],[])\r\n self.axCost.set_xlabel(\"Time\")\r\n self.axCost.set_title(\"Cost\")\r\n\r\n # Draw Cost function Plot\r\n self.canvasPlot = FigureCanvasTkAgg(self.figure, master=self.master)\r\n self.canvasPlot.get_tk_widget().grid(row=1,column=0)\r\n \r\n # Draw Tool Bar\r\n self.toolbarFrame = tk.Frame(self.master)\r\n self.toolbarFrame.grid(row=2,column=0,columnspan=3,sticky=\"W\")\r\n self.toolbarPlot = NavigationToolbar2TkAgg(self.canvasPlot,self.toolbarFrame)" ]
[ "0.70345396", "0.7023591", "0.6718693", "0.6701137", "0.65575993", "0.6535653", "0.65306026", "0.6503289", "0.63787425", "0.6369504", "0.6320576", "0.63002175", "0.6274523", "0.6248552", "0.6243613", "0.62430453", "0.62426406", "0.620692", "0.620692", "0.6132402", "0.61245346", "0.611989", "0.6111479", "0.6066929", "0.6048197", "0.60420096", "0.60202503", "0.6013418", "0.60116524", "0.59982246" ]
0.71893555
0
Add newly available free spaces adjacent to pos to the list if they are not already present.
def add_new_free_spaces(pos: Tuple[int, int], free_spaces: MutableSequence[ Tuple[int, int]]) -> None: offset = 2 possible_positions = [ (pos[0] + offset, pos[1] + offset), (pos[0] + offset, pos[1]), (pos[0] + offset, pos[1] - offset), (pos[0], pos[1] - offset), (pos[0] - offset, pos[1] - offset), (pos[0] - offset, pos[1]), (pos[0] - offset, pos[1] + offset), (pos[0], pos[1] + offset) ] for candidate in possible_positions: if candidate not in free_spaces: free_spaces.append(candidate)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def autoreveal_empty_spaces(self, position):\n revealed = []\n zero_spaces = []\n check_stack = [position]\n checked = []\n\n while len(check_stack) > 0:\n pos = x, y = check_stack.pop()\n if self.get_num_mines_around_position(x, y) == 0:\n zero_spaces.append(pos)\n \n # Add spaces around\n for ay in range(y-1, y+2):\n for ax in range(x-1, x+2):\n if ay >= 0 and ax >= 0 and ay < len(self.mine_map) and ax < len(self.mine_map[ay]): # Don't check spaces that are outside of the array\n apos = ax, ay\n if apos not in checked:\n check_stack.append(apos)\n revealed.append(apos)\n checked.append(pos)\n \n self.revealed.extend(revealed)", "def __free_spots(self, pos: Tuple[int, int], tree: int) -> List:\n x, y = pos\n possible_slots = []\n\n if x + 2 == self.__width:\n if self.__exit is None:\n # if we are next to the right edge and the exit is not set, connect and return\n self.__activate(x + 1, y, tree)\n self.__exit = (x + 1, y)\n return []\n\n elif self.__check_row(x + 1, y):\n # iterate through this row and compare maze assignments\n if self.__check_and_join_row(x, y, tree, 1):\n possible_slots.append((x + 1, y))\n\n if x > 1:\n if self.__check_row(x - 1, y):\n if self.__check_and_join_row(x, y, tree, -1):\n possible_slots.append((x - 1, y))\n\n elif self.__entry is None:\n # if we are on the left edge and there's no entry, connect\n self.__activate(0, y, tree)\n self.__entry = (0, y)\n return []\n\n # check left and right.\n if y + 2 < self.__height and self.__check_col(x, y + 1):\n if self.__check_and_join_col(x, y, tree, 1):\n possible_slots.append((x, y + 1))\n\n if y > 1 and self.__check_col(x, y - 1):\n if self.__check_and_join_col(x, y, tree, -1):\n possible_slots.append((x, y - 1))\n\n return possible_slots", "def set_free(self, pos: tuple):\n if self.within_map(pos):\n self.map[round(pos[0]), round(pos[1])] = FREE\n return True\n else:\n return False", "def allocate_room_space(self):\n if self._is_full == True:\n return -1\n else:\n self.allocated_spaces += 1\n\n self.unallocated_spaces = self.capacity - self.allocated_spaces\n return \"Room Allocated\"", "def wander(self):\n \n has_new_pos = False\n while not has_new_pos:\n move = random.choice(self.moves)\n new_pos = add_lists(move, self.position)\n has_new_pos = check_bounds(new_pos, self.grid_size)\n return new_pos", "def position_append(self, pos, gtid):\n return None", "def placeQueen(valid_positions, pos, boardsize):\n if isInList(valid_positions, pos): #IS a valid position!\n invalid_positions = generateQueenAttacks(boardsize, pos)\n #update valid_positions\n for pos in invalid_positions:\n temp = isInList(valid_positions, pos)\n if temp:\n valid_positions.remove(temp)\n return True\n return False", "def available_positions(self):\n if len([x for x in self.grid.values() if x[0] != None]) < 13:\n return [x for x in assignable_positions if self.grid[x][1] == \"---\"]\n else:\n return []", "def find_free_ortho_spaces(self):\r\n for pos, ortho in ORTHOGONAL_POSITIONS.items():\r\n if self.board[pos[0]][pos[1]].color != 0:\r\n for p in ortho:\r\n if self.board[p[0]][p[1]].color == 0:\r\n if (pos[0], pos[1]) in self.free_pos.keys():\r\n self.free_pos[(pos[0], pos[1])].add(p)\r\n else:\r\n self.free_pos[(pos[0], pos[1])] = {p}", "def push_addr_reservation_list(self, lst_new):\n self.__not_implemented()", "def insert(self, item):\r\n if not self.is_full():\r\n for i in range(1,len(self.items)):\r\n if self.items[i] is None:\r\n self.items[i] = item\r\n self.size += 1\r\n self.perc_up(i)\r\n return True\r\n return False", "def prep_spaceships(self):\n self.spaceships = Group()\n for spaceship_number in range(self.stats.spaceships_left):\n spaceship = SmallSpaceship(self.ai_game)\n spaceship.rect.x = 20 + (spaceship_number * \n spaceship.rect.width) + (spaceship_number * 10)\n spaceship.rect.y = 20\n self.spaceships.add(spaceship)", "def fill_gap(previous, current, from_address,\n to_address) -> Tuple[str, List]:\n size = to_address - from_address\n if (previous is None or previous.symbol in start_unused\n or current.symbol in end_unused):\n use = 'unused'\n name = memdf.name.unused(from_address, size)\n else:\n use = 'gap'\n name = memdf.name.gap(from_address, size)\n return (use, filler(name, from_address, size, previous, current))", "def add_to_free_cell_list(self, cell: Cell):\r\n assert isinstance(cell, Cell)\r\n self.free_cell_list.append(cell)", "def explore(self):\n \n has_new_pos = False\n while not has_new_pos:\n move = self.biased_choice()\n new_pos = add_lists(move, self.position)\n has_new_pos = check_bounds(new_pos, self.grid_size)\n return new_pos", "def find_free_space(graph, position=(pos_x, pos_y)):\n # SET THE POSITION USING LIST COMPREHENSION\n position_x, position_y = position[0], position[1]\n # TRANSFORM THE POSITION TO THE PYGAME VECTOR\n position = vec(position_x, position_y)\n # IMPORT THE DEQUE TO PUT THE NODES\n frontier = deque()\n # APPEND THE FRONTIER WITH THE POSITION\n frontier.append(position)\n print(f'Frontier: {frontier}')\n # THE LIST OF VISITED NODES\n visited = []\n print(f'Visited: {visited}')\n # THE POSITION WILL BE PUT AT THE VISITED QUEUE (IS WHERE WE ARE)\n visited.append(position)\n # START OUR LOOP\n #* As long there's nodes on the frontier do\n while len(frontier) > 0:\n # THE CURRENT NODE WE WANT TO LOOK IS THE NEXT NODE\n #* Pop's the next on the queue list\n current = frontier.popleft()\n print(f'Current: {current}')\n print(graph.find_neighbors(vec(current)))\n # THE NEIGHBOORS OF THE CURRENT TILE\n for next in graph.find_neighbors(current):\n print(\"OK! Entered in the For LOOP\")\n # IF THE NEXT NODE IS NOT VISITED\n if next not in visited:\n # ADD THE NODE TO THE FRONTIER LIST\n frontier.append(next)\n # PUT ON THE VISITED NODES\n visited.append(next)\n # PRINT ALL THE VISITED NODES\n print(f'The Visited Nodes are:\\n{visited}')", "def set_pos(self, newpos : list) :\n if len(newpos) == 2 :\n self.pos = list(newpos).copy()\n else :\n raise UserWarning('wrong position passed')", "def insert(self, pos, length):\n if pos in self.insertions:\n self.insertions[pos] += length\n else:\n self.insertions[pos] = length", "def updated_occupied_locations(self):\n if len(self.occupiedLocations) > self.currentTurn:\n self.occupiedLocations[self.currentTurn] += [self.character.path[-1]]\n else:\n self.occupiedLocations += [[self.character.path[-1]]]", "def leftaddlistitems(self, items, pos):\n self._leftlist.insert(pos, items)", "def _list_list_only_set_rel_pos(self, rel_pos):\n if self.staticneighs is not True:\n assert(self.ks is not None)\n n_ks = len(self.ks)\n self.sp_relative_pos = [rel_pos]*n_ks\n else:\n self.sp_relative_pos = rel_pos", "def grow(self):\n old = self.data # keep track of existing list\n self.capacity = self.capacity*2\n self.data = [None] * (self.capacity) # allocate list with new capacity\n walk = self.head\n for k in range(self.size): # only consider existing elements\n self.data[k] = old[walk] # intentionally shift indices\n walk = (1 + walk) % len(old) # use old size as modulus\n self.head = 0 # front has been realigned", "def grow(self):\r\n # Double the physical size if no more room for items\r\n # and add the fillValue to the new cells in the underlying list\r\n for count in range(len(self)):\r\n self._items.append(self._fillValue)", "def add_objects_to_space(self):\n self.anti_spacecraft.add_to_space(self.space) # Anti-spacecraft Parts (represent the whole vehicle)\n self.space.add(self.spacecraft.body, self.spacecraft.shape) # Spacecraft body and shape\n self.space.add(self.pm_landing_pad) # Landing pad", "def add_to_list(item):\n show_list()\n\n if len(shopping_list):\n position = input(\"Where should I add {}?\\n\"\n \"Press ENTER to add to the end of the list\\n\"\n \"> \".format(item))\n else:\n position = 0\n\n try:\n position = abs(int(position))\n except ValueError:\n position = None\n if position is not None:\n shopping_list.insert(position - 1, item)\n else:\n shopping_list.append(item)\n\n show_list()", "def make_free_cell_list():\r\n for row in range(9):\r\n for col in range(9):\r\n if (application.ui.__getattribute__(f'cell{col+1}{row+1}')).text() == \"\":\r\n lst_free_cells.append(Point(row, col))", "def insert(self, item):\n self.heaplist.append(item)\n self.currentsize += 1\n self.shift_item_up(self.currentsize)", "def check_disk_free_space_reserved(self):\n if self.skip_disk_space_check:\n return True\n disk_partition_size = util.disk_partition_size(self.outfile_dir)\n free_disk_space = util.disk_partition_free(self.outfile_dir)\n free_space_factor = self.free_space_reserved_percent / 100\n free_space_reserved = disk_partition_size * free_space_factor\n if free_disk_space < free_space_reserved:\n raise OSCError(\n \"NOT_ENOUGH_SPACE\",\n {\n \"need\": util.readable_size(free_space_reserved),\n \"avail\": util.readable_size(free_disk_space),\n },\n )", "def update_spaces_threatened(self):\n # The threatened spaces will always be it's corners\n current_row = self.position[0]\n current_column = self.position[1]\n corner1 = (current_row + 1 * self.direction, current_column - 1)\n corner2 = (current_row + 1 * self.direction, current_column + 1)\n current_spaces_threatened = [corner1, corner2]\n self.spaces_threatened = current_spaces_threatened\n update_threatening_king(self)", "def get_available_moves(self):\n available = []\n row, col = tuple(self.current_pos)\n if row - 1 >= 0 and self.maze[row - 1][col] != 'x':\n available.append('n')\n if row + 1 < len(self.maze) and self.maze[row + 1][col] != 'x':\n available.append('s')\n if col - 1 >= 0 and self.maze[row][col - 1] != 'x':\n available.append('w')\n if col + 1 < len(self.maze[row]) and self.maze[row][col + 1] != 'x':\n available.append('e')\n return available" ]
[ "0.60795987", "0.5536707", "0.5347553", "0.5315331", "0.52387303", "0.5216414", "0.5211053", "0.51984644", "0.51950127", "0.51828325", "0.5182313", "0.51762885", "0.51726806", "0.51522017", "0.51186055", "0.50984484", "0.5096328", "0.5086424", "0.50736445", "0.50462025", "0.5032953", "0.50282514", "0.50276804", "0.49747524", "0.49693793", "0.4966698", "0.4936173", "0.4904392", "0.48929334", "0.4888275" ]
0.82575357
0
Annotate a FigureElement. This is a convenience function so you don't need to pass all three arguments separately, they are all taken from the passed element.
def annotate_element(self, element: 'FigureElement') -> plt.Annotation: if element.annotation is not None: element.annotation.set_text(element.get_hover_text()) return element.annotation else: return self.annotate(element.get_hover_text(), element.get_center(), element.axes)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def annotate(*args, point: List[float, float, float]=None, text: AnyStr=\"\", **kwargs)->AnyStr:\n pass", "def annotate(axis, text, x, y):\n text_annotation = Annotation(text, xy=(x, y), xycoords='data')\n axis.add_artist(text_annotation)", "def annotate(args):\n prism.annotate.run(\n input_fp=args.input,\n output_fp=args.output,\n bed_fps=args.beds,\n annotation_names=args.annotation_names,\n output_figure_fp=args.figure,\n width=args.width,\n height=args.height,\n scale=args.scale,\n font_family=args.font_family,\n )", "def setup_annotation(self):\n annotation = self.ax_fig.annotate(\n '', xy=(0, 0), ha='left',\n xytext=(-20, 20), textcoords='offset points', va='bottom',\n bbox=dict(\n boxstyle='round,pad=0.5', fc='yellow', alpha=0.2),\n arrowprops=dict(\n arrowstyle='->', connectionstyle='arc3,rad=0'))\n return annotation", "def updateAnnot( xdata, ydata, pixels, annot, rawdata, **kwargs):\n\ty, x = pol2cart( ydata/180, xdata, pixels )\n\tannot.xy = ( xdata, ydata )\n\t# Inconsistent wrapping; plot the right variable.\n\tif xdata < 0:\n\t\txdata += 2 * np.pi\n\ttext = 'Az=' + str( round( xdata * 180 / np.pi, 1 ) )+ ', El=' + str( round( np.arccos( ydata/180 ) * 180/np.pi, 1) ) + u'\\xb0' + '\\nInt.=' + '{:.3E}'.format((rawdata[int(y),int(x)]))\n\tannot.set_text( text )\n\tannot.get_bbox_patch().set_alpha( 0.66 )\n\tannot.set_color('black')", "def setAnnotation(self, *args):\n return _libsbml.SBase_setAnnotation(self, *args)", "def _add_annotation(raw_fig):\n data_ax = raw_fig.mne.ax_main\n\n key_event = KeyEvent(name=\"Annotation\", canvas=raw_fig.canvas, key=\"a\")\n raw_fig.canvas.callbacks.process(\"key_press_event\", key_event)\n\n ann_fig = raw_fig.mne.fig_annotation\n for key in \"test\": # Annotation will be named: BAD_test\n key_event = KeyEvent(name=\"Bad\", canvas=ann_fig.canvas, key=key)\n ann_fig.canvas.callbacks.process(\"key_press_event\", key_event)\n\n key_event = KeyEvent(name=\"Enter\", canvas=ann_fig.canvas, key=\"enter\")\n ann_fig.canvas.callbacks.process(\"key_press_event\", key_event)\n\n # Draw a 4 second long Annotation.\n _fake_click(raw_fig, data_ax, [1.0, 1.0], xform=\"data\", button=1, kind=\"press\")\n _fake_click(raw_fig, data_ax, [5.0, 1.0], xform=\"data\", button=1, kind=\"motion\")\n _fake_click(raw_fig, data_ax, [5.0, 1.0], xform=\"data\", button=1, kind=\"release\")", "def annotate(self):\n annotations = {}\n\n text_keys = ['fontsize', 'family']\n text_config = self.config.filter(keys=text_keys, prefix='text_')\n\n # suptitle\n suptitle = self.config.get('suptitle')\n if suptitle is not None:\n suptitle_config = self.config.filter(prefix='suptitle_')\n suptitle_config.update(text_config, skip_duplicates=True)\n\n suptitle_wrap_config = suptitle_config.filter(prefix='wrap_')\n if suptitle_wrap_config:\n suptitle = wrap_by_delimiter(suptitle, **suptitle_wrap_config)\n\n annotations['suptitle'] = self.figure.suptitle(suptitle, **suptitle_config)\n\n self.figure.tight_layout()\n\n return annotations", "def annotate(self, mode):\n # pylint: disable=too-many-branches\n annotations = {}\n\n if not self.ax.axison:\n self.enable()\n\n text_keys = ['fontsize', 'family']\n text_config = self.config.filter(keys=text_keys, prefix='text_')\n\n # title\n title = self.config.get('title')\n if title is not None:\n if isinstance(title, list):\n title = ', '.join(title)\n\n title_config = self.config.filter(prefix='title_')\n title_config.update(text_config, skip_duplicates=True)\n\n title_wrap_config = title_config.filter(prefix='wrap_', retrieve='pop')\n if title_wrap_config:\n title = wrap_by_delimiter(title, **title_wrap_config)\n\n annotations['title'] = self.ax.set_title(title, **title_config)\n\n # xlabel\n xlabel = self.config.get('xlabel')\n if xlabel is not None:\n xlabel_config = self.config.filter(prefix='xlabel_')\n xlabel_config.update(text_config, skip_duplicates=True)\n xlabel_wrap_config = xlabel_config.filter(prefix='wrap_', retrieve='pop')\n if xlabel_wrap_config:\n xlabel = wrap_by_delimiter(xlabel, **xlabel_wrap_config)\n annotations['xlabel'] = self.ax.set_xlabel(xlabel=xlabel, **xlabel_config)\n\n # ylabel\n ylabel = self.config.get('ylabel')\n if ylabel is not None:\n ylabel_config = self.config.filter(prefix='ylabel_')\n ylabel_config.update(text_config, skip_duplicates=True)\n ylabel_wrap_config = ylabel_config.filter(prefix='wrap_', retrieve='pop')\n if ylabel_wrap_config:\n ylabel = wrap_by_delimiter(ylabel, **ylabel_wrap_config)\n annotations['ylabel'] = self.ax.set_ylabel(ylabel=ylabel, **ylabel_config)\n\n # xticks\n xtick_config = self.config.filter(prefix='xtick_')\n if 'locations' in xtick_config:\n xtick_locations = xtick_config.pop('locations')\n self.ax.set_xticks(xtick_locations)\n\n if xtick_config:\n if 'labels' not in xtick_config:\n xtick_config['labels'] = [item.get_text() for item in self.ax.get_xticklabels()]\n if 'size' in xtick_config:\n xtick_config['fontsize'] = xtick_config.pop('size')\n annotations['xticks'] = self.ax.set_xticklabels(**xtick_config)\n\n # yticks\n ytick_config = self.config.filter(prefix='ytick_')\n if 'locations' in ytick_config:\n xtick_locations = ytick_config.pop('locations')\n self.ax.set_yticks(xtick_locations)\n\n if ytick_config:\n if 'labels' not in ytick_config:\n ytick_config['labels'] = [item.get_text() for item in self.ax.get_yticklabels()]\n if 'size' in ytick_config:\n ytick_config['fontsize'] = ytick_config.pop('size')\n annotations['xticks'] = self.ax.set_yticklabels(**ytick_config)\n\n # ticks\n tick_keys = ['labeltop', 'labelright', 'labelcolor']\n tick_config = self.config.filter(keys=tick_keys, prefix='tick_')\n if tick_config:\n self.ax.tick_params(**tick_config)\n\n # Change visibility of xaxis/yaxis\n self.ax.get_xaxis().set_visible(self.config.get('xaxis_visible', True))\n self.ax.get_yaxis().set_visible(self.config.get('yaxis_visible', True))\n\n # Change scale of axis, if needed\n if self.config.get('log') or self.config.get('log_loss'):\n self.ax.set_yscale('log')\n\n if self.config.get('log_lr'):\n self.lr_ax.set_yscale('log')\n\n # Change x-axis limits\n xlim = self.config.get('xlim')\n self.ax.set_xlim(xlim)\n\n # Change y-axis limits\n ylim = self.config.get('ylim')\n self.ax.set_ylim(ylim)\n\n # Add image colorbar\n colorbar = self.config.get('colorbar')\n if colorbar is not None and self.main_object is not None:\n colorbar_config = self.config.filter(prefix='colorbar_')\n\n colorbar_config['fake'] = not colorbar\n\n if 'pad' not in colorbar_config:\n pad = 0.4\n labelright = self.config.get('labelright', None)\n if labelright:\n ax_x1 = self.plotter.get_bbox(self.ax).x1\n yticklabels = self.ax.get_yticklabels()\n max_ytick_label_x1 = max(self.plotter.get_bbox(label).x1\n for label in yticklabels[len(yticklabels)//2:])\n pad += (max_ytick_label_x1 - ax_x1) # account for width of yticklabels to the right of the subplot\n colorbar_config['pad'] = pad\n\n annotations['colorbar'] = self.add_colorbar(image=self.main_object, **colorbar_config)\n\n # Add legend\n if mode in ('loss', 'curve'):\n self.config['label'] = [obj for layer in self.layers for obj in layer.objects]\n\n label = self.config.get('label')\n if label is not None:\n if not isinstance(label, list):\n label = [label]\n\n legend_config = self.config.filter(prefix='legend_')\n\n if 'color' not in legend_config:\n color_key = 'cmap' if mode in ('image', 'matrix') else 'color'\n legend_config['color'] = [layer.config[color_key] for layer in self]\n\n if 'alpha' not in legend_config:\n legend_config['alpha'] = [layer.config['alpha'] for layer in self]\n\n annotations['legend'] = self.add_legend(mode=mode, label=label, **legend_config)\n\n # Add grid\n grid = self.config.get('grid', None)\n grid_config = self.config.filter(prefix='grid_')\n\n if grid in (None, False):\n self.ax.grid(False)\n\n if grid in ('minor', 'both'):\n minor_grid_config = self.config.filter(prefix='minor_grid_')\n minor_grid_config = minor_grid_config.update(grid_config, skip_duplicates=True)\n self.add_grid(grid_type='minor', **minor_grid_config)\n\n if grid in ('major', 'both'):\n major_grid_config = self.config.filter(prefix='major_grid_')\n major_grid_config = major_grid_config.update(grid_config, skip_duplicates=True)\n self.add_grid(grid_type='major', **major_grid_config)\n\n # Set whether axis ticks and gridlines are above or below most artists.\n self.ax.set_axisbelow(self.config.get('axisbelow', False))\n\n # Change facecolor\n facecolor = self.config.get('facecolor', None)\n if facecolor is not None:\n self.ax.set_facecolor(facecolor)\n\n return annotations", "def setAnnotation(self, *args):\n return _libsbml.SpeciesReference_setAnnotation(self, *args)", "def appendAnnotation(self, *args):\n return _libsbml.SBase_appendAnnotation(self, *args)", "def add_stat_annot(fig, ax, x_start_list, x_end_list,\n y_start_list=None, y_end_list=None,\n line_height=2, stat_list=['*'],\n text_y_offset=0.2, text_x_offset=-0.01):\n\n if type(x_start_list) is not list:\n x_start_list = [x_start_list]\n\n for x_start, x_end, y_start, y_end, stat in zip(x_start_list, x_end_list,\n y_start_list, y_end_list, stat_list):\n\n if y_start is None:\n y_start = get_axes_object_max(ax, x_loc=x_start, object_type='line') + line_height\n if y_end is None:\n max_at_x_end = get_axes_object_max(ax, x_loc=x_end, object_type='line')\n print(max_at_x_end)\n y_end = max_at_x_end + line_height\n\n y_start_end_max = np.max([y_start, y_end])\n\n sig_line = ax.plot([x_start, x_start, x_end, x_end],\n [y_start, y_start_end_max + line_height, y_start_end_max + line_height, y_end],\n linewidth=1, color='k')\n\n ax.text(x=(x_start + x_end) / 2 + text_x_offset,\n y=y_start_end_max + line_height + text_y_offset,\n s=stat, horizontalalignment='center')\n\n return fig, ax", "def annotate(self, text: str, position: Tuple[int, int],\n axes: plt.Axes = None) -> Union[plt.Annotation, None]:\n if text == '':\n return None\n if axes is None:\n axes = self.subplot\n annotation = axes.annotate(text,\n xy=position,\n xytext=(10, 10),\n textcoords='offset pixels',\n arrowprops=dict(\n arrowstyle='->'),\n bbox=dict(\n boxstyle='round',\n fc='w'),\n zorder=20)\n annotation.set_visible(True)\n return annotation", "def annotate(self, ax):\n annotation = ax.annotate(self.template, xy=(0, 0), ha='right',\n xytext=self.offsets, textcoords='offset points', va='bottom',\n bbox=dict(boxstyle='round,pad=0.5', fc='yellow', alpha=0.5),\n arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=0')\n )\n annotation.set_visible(False)\n return annotation", "def annotate(self, ax):\n annotation = ax.annotate(self.template, xy=(0, 0), ha='right',\n xytext=self.offsets, textcoords='offset points', va='bottom',\n bbox=dict(boxstyle='round,pad=0.5', fc='yellow', alpha=0.5),\n arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=0')\n )\n annotation.set_visible(False)\n return annotation", "def update_annot(cls, ind):\n gen = ind + FigureControl.minPossibleGenNumber\n for cplot in gs.cloud_plots:\n fitness = cplot.update_annot(gen)\n\n text = \"{}\".format(gen)\n gs.fitness_plot.floating_annot.xy = (gen, fitness)\n gs.fitness_plot.floating_annot.set_text(text)", "def annotate(*x, x_value=20, text=\"None\", color=\"red\", fontproperties='FZShuTi', fontsize=13, alpha=0.8, rotation=3):\n\n x = x\n # If user doesn't submit submit x, it will create a default DataSet.\n if x == ():\n x = np.linspace(0, 70, 5000)\n else:\n x = x[0]\n\n plt.plot(x, create(x), linewidth=3)\n\n x_val = x_value\n t = text\n c = color\n fp = fontproperties\n fs = fontsize\n a = alpha\n\n plt.rcParams[\"figure.figsize\"] = [12, 6]\n plt.scatter(x_val, create(x_val), color=\"blue\")\n plt.text(x_val, create(x_val), t, color=c, fontproperties=fp, fontsize=fs, alpha=a, rotation=rotation)", "def annotate_point(x, y, text, offset=5, offset_x=None, offset_y=None,\n text_kw={}):\n if offset_x is None or offset_y is None:\n offset_x = offset\n offset_y = offset\n ax = plt.gca()\n trans_offset = transforms.offset_copy(ax.transData, units='dots',\n x=offset_x, y=offset_y)\n\n plt.text(x, y, text, transform=trans_offset, **text_kw)", "def annotate(self, **annotations):\n _check_annotations(annotations)\n self.annotations.update(annotations)", "def setAnnotation(self, *args):\n return _libsbml.Model_setAnnotation(self, *args)", "def figure_name(name):\n def decorator(func):\n func.figure_name = name\n return func\n return decorator", "def update_annot(self, ind, plt_ref, ref_label):\r\n\r\n # Get selected data coordinates\r\n pos = plt_ref._xy[ind[\"ind\"][0]]\r\n\r\n # Shift annotation box left or right depending on which half of the axis the pos x is located and the\r\n # direction of x increasing.\r\n if plt_ref.axes.viewLim.intervalx[0] < plt_ref.axes.viewLim.intervalx[1]:\r\n if pos[0] < (plt_ref.axes.viewLim.intervalx[0] + plt_ref.axes.viewLim.intervalx[1]) / 2:\r\n self.annot._x = -20\r\n else:\r\n self.annot._x = -80\r\n else:\r\n if pos[0] < (plt_ref.axes.viewLim.intervalx[0] + plt_ref.axes.viewLim.intervalx[1]) / 2:\r\n self.annot._x = -80\r\n else:\r\n self.annot._x = -20\r\n\r\n # Shift annotation box up or down depending on which half of the axis the pos y is located and the\r\n # direction of y increasing.\r\n if plt_ref.axes.viewLim.intervaly[0] < plt_ref.axes.viewLim.intervaly[1]:\r\n if pos[1] > (plt_ref.axes.viewLim.intervaly[0] + plt_ref.axes.viewLim.intervaly[1]) / 2:\r\n self.annot._y = -40\r\n else:\r\n self.annot._y = 20\r\n else:\r\n if pos[1] > (plt_ref.axes.viewLim.intervaly[0] + plt_ref.axes.viewLim.intervaly[1]) / 2:\r\n self.annot._y = 20\r\n else:\r\n self.annot._y = -40\r\n\r\n self.annot.xy = pos\r\n\r\n # Format and display text\r\n text = 'x: {:.2f}, {}: {:.2f}'.format(pos[0], ref_label, pos[1])\r\n self.annot.set_text(text)", "def _render_annotation(self, index, el):\r\n attr = {}\r\n attr.update(self._get_annotation_class_attr(index, el))\r\n attr.update(self._get_annotation_data_attr(index, el))\r\n\r\n el.tag = 'span'\r\n\r\n for key in attr.keys():\r\n el.set(key, attr[key]['value'])\r\n if '_delete' in attr[key] and attr[key]['_delete'] is not None:\r\n delete_key = attr[key]['_delete']\r\n del el.attrib[delete_key]", "def onclick(event, annot, pltObj, pixels, rawdata, **kwargs):\n\tvis = annot.get_visible()\n\tif event.inaxes == pltObj:\n\t\tif not vis:\n\t\t\tupdateAnnot(event.xdata, event.ydata, pixels, annot, rawdata)\n\t\t\tannot.set_visible( True )\n\t\t\tevent.canvas.draw()\n\t\telse:\n\t\t\tannot.set_visible( False )\n\t\t\tevent.canvas.draw()", "def annotate(row, ax, x='x', y='y', text='name', xytext=(7, -5), textcoords='offset points', **kwargs):\n # idx = row.name\n text = row[text] if text in row else str(text)\n x = row[x] if x in row else float(x)\n y = row[y] if y in row else float(y)\n ax.annotate(text, (row[x], row[y]), xytext=xytext, textcoords=textcoords, **kwargs)\n return row[text]", "def appendAnnotation(self, *args):\n return _libsbml.SpeciesReference_appendAnnotation(self, *args)", "def __draw_annotations(self):\n final = self.__resolve_annotation_conflicts(self.annotations)\n\n shrinkB = self.settings.rcParams[\"lines.markersize\"]+self.settings.rcParams[\"lines.markeredgewidth\"]\n for a in final:\n if a.put_circle_around_point:\n self.ax.plot(a.event_point.x, a.event_point.y, marker='o', markeredgecolor=a.color,\n ms=self.settings.rcParams[\"lines.markersize\"]*2.0)\n\n if a.marker is not None:\n self.ax.plot(\n a.marker.x, a.marker.y, markeredgecolor=a.marker.color, marker=a.marker.marker)\n\n self.ax.annotate(a.text, xy=(a.event_point.x, a.event_point.y), xytext=(a.x, a.y),\n weight='bold', color=a.color, va='center', ha='left',\n arrowprops=dict(arrowstyle='-',\n connectionstyle='arc3',\n color=a.color,\n shrinkA=self.settings.otherParams[\"annotation.shrinkA\"],\n shrinkB=shrinkB,\n # search for 'relpos' on https://matplotlib.org/tutorials/text/annotations.html\n relpos=a.relpos,\n linewidth=self.settings.otherParams[\"annotation.line.width\"]))", "def annotate(self, *args, **kwargs):\n self._not_support_combined_queries(\"annotate\")\n return self._annotate(args, kwargs, select=True)", "def annotate(self, annotation_=None):\n # Important: Need a copy, not the reference to the original object\n annotation_ = copy.deepcopy(annotation_)\n annotation_.annotate(self, from_dataset=True)\n history_record = annotation_.create_history_record()\n self.annotations.append(history_record)\n self._append_task(kind='annotation', task=history_record)", "def __call__(self, event):\n # Rather than trying to interpolate, just display the clicked coords\n # This will only be called if it's within \"tolerance\", anyway.\n x, y = event.mouseevent.xdata, event.mouseevent.ydata\n annotation = self.annotations[event.artist.axes]\n if x is not None:\n if not self.display_all:\n # Hide any other annotation boxes...\n for ann in self.annotations.values():\n ann.set_visible(False)\n # Update the annotation in the current axis..\n annotation.xy = x, y\n # Is borders enabled, update x, y were necessary\n (x_offset, y_offset, pixelValue) = (0, 0, -1)\n pixelValue = self.imageData[y, x]\n \n annotation.set_text(self.template % (x+x_offset, y+y_offset, pixelValue))\n annotation.set_visible(True)\n event.canvas.draw()" ]
[ "0.66608083", "0.63205814", "0.60229737", "0.58094853", "0.5672598", "0.561528", "0.5587976", "0.54985315", "0.5394095", "0.5393415", "0.538822", "0.5365531", "0.5352155", "0.53486985", "0.53486985", "0.5328886", "0.5327457", "0.52940744", "0.5276026", "0.5244312", "0.5231723", "0.52315974", "0.52088165", "0.5174559", "0.51622415", "0.51575744", "0.51461685", "0.5139869", "0.5115293", "0.5113014" ]
0.7454883
0
Clears the current drawing and dicts/lists referencing the drawn elements.
def _clear_drawing(self) -> None: self.vertices.clear() self.edges.clear() self.subplot.clear() self.selected_element = None self.pressed_elements.clear()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _clear_drawing(self) -> None:\n self.vertices.clear()\n self.edges.clear()\n self.subplot.clear()\n self.subplot2.clear()", "def _clear(self):\n self._fillitem = self._fillpath = None\n for item in self.items:\n self.screen._delete(item)\n self.currentLineItem = self.screen._createline()\n self.currentLine = []\n if self._drawing:\n self.currentLine.append(self._position)\n self.items = [self.currentLineItem]\n self.clearstamps()", "def clear_selected_shapes(self):\n self.shapes_to_draw = []", "def clear(self):\n for i in range(len(self.canvas)):\n self.canvas[i] = 0", "def clear(self):\n self._plt.clear()\n self._layer_items = {}", "def clear_canvas():\n self.parent_class.canvas.delete(\"all\")", "def clear(self):\n try:\n # This causes stupid errors with tkagg, so just wrap it in\n # try-except for now\n self.fig.clear()\n except: pass\n self.annotators.clear()\n self.dims.clear()\n self.ph.remove(self.ID)", "def clear(self):\n self._x_prev = None\n self._y_prev = None", "def clear(self):\n self.canvas = [[self.style] * self.cols for _ in range(self.lines)]", "def clear_visualization(self) -> None:\n if self._drawing_handle is not None:\n sim.simAddDrawingObjectItem(self._drawing_handle, None)", "def clearCanvas():\n global c, coordinates\n c.delete(\"all\")\n drawMusicLines()\n coordinates.clear()", "def clear(self):\n self._grid = [[None]]", "def clear(self):\n self.animation.stop()\n self.draw(0, 0, 0, 0, 0)", "def clear(self):\n self._frame.clear()\n self._turtles = []\n self._gpens = []", "def clear(self):\n if self.flag == 0:\n for coord in INDICES:\n self.kill(coord)\n self.chart[coord] = DEAD", "def clear(self):\n self.clear_markers()\n self.l_marker.remove()\n self.l_line.remove()\n self.r_marker.remove()\n self.r_line.remove()", "def clear_drawn_objects(self, view_manager):\n view = view_manager.get_view()\n for item in self._drawnObjects:\n view.removeItem(item)\n # clear the list:\n self._drawnObjects = []", "def clear(self):\n self.raster_path_line.clear()\n self.labels_path.clear()\n self.shapefile_path.clear()\n self.costumelabels.clear()\n self.layer_name.clear()\n self.class_name.clear()\n self.idfield.clear()", "def clear(self):\n black = neo.Color(0,0,0)\n self.set_all(black)\n self.draw()", "def clear(self):\n for key in self.__columns:\n self.__widths[key] = 0\n self.__data = []\n self.__selectedRow = -1\n self.__formatString = \"\"\n self._window.clear()\n self.drawBorder()", "def clear(self):\n lines = self._lines\n image, bkg_image = self.image, self._image\n for line in lines: line.clear(image, bkg_image) #prej bkg_img\n self._cursor = 0", "def clear(self):\n self._plots[:] = []", "def clear(self):\r\n\t\tself.grid.fill(False)", "def undraw(self):\n \n if not self.canvas: return\n if not self.canvas.isClosed():\n #self.canvas.delete(self.id)\n _tkExec(self.canvas.delete, self.id)\n if self.canvas.autoflush:\n #_root.update()\n _tkCall(_root.update)\n pass\n self.canvas = None\n self.id = None", "def clear(self):\n self._delayvalue = _CFG[\"delay\"]\n self._colormode = _CFG[\"colormode\"]\n self._delete(\"all\")\n self._bgpic = self._createimage(\"\")\n self._bgpicname = \"nopic\"\n self._tracing = 1\n self._updatecounter = 0\n self._turtles = []\n self.bgcolor(\"white\")\n for btn in 1, 2, 3:\n self.onclick(None, btn)\n self.onkeypress(None)\n for key in self._keys[:]:\n self.onkey(None, key)\n self.onkeypress(None, key)\n Myturtle._pen = None", "def clear(self):\r\n\r\n # Clear the widgets list\r\n self.widgets_list = []\r\n\r\n # Refresh the scroll area\r\n self._refresh()", "def clear(self):\n self._turtle.clear()", "def clear(self):\n self._turtle.clear()", "def clear_geometries(self):", "def _clear(self, event):\n if self.ignore(event) or self._changed_canvas():\n return\n self._background = self.canvas.copy_from_bbox(self.ax.bbox)\n self.ax.draw_artist(self._buttons)\n if hasattr(self, \"_circles\"):\n for circle in self._circles:\n self.ax.draw_artist(circle)" ]
[ "0.82706034", "0.79316634", "0.7764828", "0.76532316", "0.7638401", "0.75774086", "0.7515265", "0.7456398", "0.74527353", "0.742205", "0.7401441", "0.7380618", "0.7338083", "0.7337927", "0.73297036", "0.729089", "0.72666776", "0.72562766", "0.7228562", "0.72144085", "0.72106487", "0.717251", "0.7171161", "0.7165129", "0.71584547", "0.7157541", "0.71261865", "0.71261865", "0.7105422", "0.7086848" ]
0.8798906
0
Redraw the currently loaded graph.
def _redraw_graph(self) -> None: self._clear_drawing() self.draw_graph()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _redraw_graph(self) -> None:\n self._clear_drawing()\n self.draw_graph(graph=self.graph, axes=self.subplot)\n self.draw_graph(graph=self.graph2, axes=self.subplot2)\n self.draw_mappings(self.mapping)", "def _update_current_graph(self, **kwargs):\n\n self.current_graph.redraw()", "def plot_refresh():\n figure.canvas.draw()", "def redraw_figures(self):\n pass", "def redraw_figures(self):\n pass", "def redraw(self):\n self._create()", "def redraw(self, **kwargs):\n #src_dict = self.data_sources\n #self.remove_sources(src_dict.keys())\n self.renderers = {}\n #self.renderers = {}\n self.figure = self.draw_figure(**kwargs)\n #self.add_sources(src_dict)\n # todo does the old figure linger on?\n self.render_sources(self.data_sources)\n self.bk_pane.object = self.figure", "def redraw(self) -> None:\n self.canvas.draw_idle()\n self.Refresh()", "def redraw(self):\n raise NotImplementedError()", "def redraw(self):\n dummy_figure = plt.figure()\n new_manager = dummy_figure.canvas.manager\n new_manager.canvas.figure = self.figure\n self.figure.set_canvas(new_manager.canvas)\n plt.show(block=False)", "def update_graph(self):\n if self.update_callback:\n self.update_callback()", "def update_figure(self):\n\n self.draw()", "def redraw(self):\r\n self.c.update()", "def redraw(self):\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)\n for shape in self.shapes:\n shape.redraw()\n glFlush()\n self.SwapBuffers()", "def redraw(self):\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)\n for shape in self.shapes:\n shape.redraw()\n glFlush()\n self.SwapBuffers()", "def redraw(self):\n self.vispy_widget.canvas.update()", "def redraw(self):\n self.vispy_viewer.canvas.update()", "def update(self):\n self.redraw()\n self._changed = False", "def update(self):\n self.redraw()\n self._changed = False", "def force_update_graph(self):\n self.updated_data = 1\n self.update_graph()", "def refresh(self):\n\n # Set Graphics scene\n self.setScene(QtGui.QGraphicsScene())\n self._connections = set()\n self._nodes = {}\n self._selection = set()\n self._manipulation_mode = 0\n self._selection_rect = None", "def update_plot():\n pass", "def update(self):\r\n self.g = self.create_graph()", "def redraw(self):\n self.scene.redraw()\n self.SwapBuffers()", "def draw(self):\n draw(self.graph)", "def refresh(self):\n\n self.ax.relim()\n self.ax.autoscale_view()\n self.canvas.draw()", "def reload_processgraph_view(self):\n #widget = self.processgraphWidget\n #self.load_dict_into_widget(widget, self.processgraph.graph)\n self.processgraphEdit.setText(json.dumps(self.processgraph.graph, indent=2, sort_keys=True))\n #widget.show()", "def update_visualization(self) -> None:\n pass", "def refresh_svg_canvas(self):\n if self.ui.tabWidget.currentIndex() == 0:\n self.ui.svg_canvas.build_schematic()\n self.ui.svg_canvas.viewport().update()\n elif self.ui.tabWidget.currentIndex() in (1,2):\n self.ui.svg_canvas.build_pcb()\n self.ui.svg_canvas.viewport().update()\n else:\n raise Exception(\"Unknown view to draw\")", "def redraw_viz():\n\tglobal g_last_draw\n\tif (rospy.Time.now().to_sec() > (refresh_rate + g_last_draw)):\n\t\tg_last_draw = rospy.Time.now().to_sec()\n\t\t# redraw imu box\n\t\tdoDraw()" ]
[ "0.82990897", "0.80580974", "0.7624843", "0.76079607", "0.76079607", "0.7428141", "0.74012005", "0.73839015", "0.73257685", "0.7198118", "0.71539146", "0.7142096", "0.7136589", "0.7117135", "0.7117135", "0.70529664", "0.7042666", "0.7020045", "0.7020045", "0.700638", "0.70062435", "0.6994467", "0.6960846", "0.6947124", "0.693493", "0.6929315", "0.689172", "0.6811036", "0.6800968", "0.67713386" ]
0.84994626
0
Load and display the passed graph.
def load_graph(self, graph: Graph) -> None: self.graph = graph self._redraw_graph()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def load(self, **kwargs):\n self.graph = self.get_graph(**kwargs)\n self.graph.load(**kwargs)", "def loadgraph(self, path):\n\n raise NotImplementedError", "def show_graph(self):\n graph_file = self.dump_graph()\n subprocess.check_output(shlex.split(f'gwenview {graph_file}'))", "def disp_graph(graph, output_filename):\n dot = Graph(name=\"Graph\", format=\"png\") # instantiate a graph object\n for node in graph.keys(): # add nodes to the graph\n dot.node(str(node))\n for node in graph.keys(): # for every node in the input graph\n # for every other node in the input graph that the first node is connected to\n for other_node in graph[node].keys():\n dot.edge(str(node), str(other_node)) # create the edge\n dot.render(output_filename, view=True) # visualize the graph and save it", "def plot_graph(self) -> None:", "def load(self):\n self._web_view.load_graph(\n options=self._options, styles=self._styles, stencils=self._stencils\n )", "def show_graph(g):\r\n net.draw(g,with_labels= True,font_size=16)\r\n plt.show()", "def do_printgraph(self, args):\n self.currentGraph.printGraph()", "def show_custom_graph(self):\n pass", "def graph(graph_file):\n return render_template(graph_file)", "def draw(self):\n draw(self.graph)", "def load_graph(self, filename):\n try:\n file_extention = list(filename.split(\".\"))[-1]\n if file_extention == \"gml\":\n self.graph = nx.read_gml(filename)\n if file_extention == \"adjlist\":\n self.graph = nx.read_adjlist(filename)\n if file_extention == \"yaml\":\n self.graph = nx.read_yaml(filename)\n except Exception as e:\n print(\"Error in loading Graph file: The error is\", e)", "def showGraph(self, file_name = \"\"):\n \n # prepare edges and weights for visualization\n edges = self.graph.edges()\n weights = [self.graph_data[u]['pheromones'][v] for u,v in edges]\n weights_sum = sum(weights)\n weights = [ (w/weights_sum)*50 for w in weights]\n \n # prepare different shades of red to be used to optionally differentiate\n # between edges with different costs\n # to show more informatiion on the same graph\n colors = []\n max_cost = max([self.graph_data[u]['costs'][v] for u,v in edges])\n for u,v in edges:\n if self.graph_data[u]['costs'][v] <= max_cost/32:\n colors.append('#ff7f7f')\n continue\n if self.graph_data[u]['costs'][v] <= max_cost/16:\n colors.append('#ff6666')\n continue\n if self.graph_data[u]['costs'][v] <= max_cost/8:\n colors.append('#ff4c4c')\n continue\n if self.graph_data[u]['costs'][v] <= max_cost/4:\n colors.append('#ff3232')\n continue\n if self.graph_data[u]['costs'][v] <= max_cost/2:\n colors.append('#ff1919')\n continue\n if self.graph_data[u]['costs'][v] <= max_cost:\n colors.append('#ff0000')\n continue\n \n # print the graph \n pos=nx.circular_layout(self.graph)\n nx.draw( self.graph,pos=pos,node_size=200,node_color='#A8A8A8', with_labels=True,edges=edges, edge_color=colors,edge_cmap=plt.cm.Blues, width=weights)\n if file_name != \"\":\n path = \"img/\"+file_name\n plt.savefig(path, format=\"PNG\")\n plt.show()", "def read_graph_ui(self):\n filename = input('enter filename: ')\n try:\n self._graph = read_graph(filename)\n except FileNotFoundError:\n print('invalid filename! ')", "def display_graph(variables, relations):\n graph = as_networkx_graph(variables, relations)\n\n # Do not crash if matplotlib is not installed\n try:\n import matplotlib.pyplot as plt\n\n nx.draw_networkx(graph, with_labels=True)\n # nx.draw_random(graph)\n # nx.draw_circular(graph)\n # nx.draw_spectral(graph)\n plt.show()\n except ImportError:\n print(\"ERROR: cannot display graph, matplotlib is not installed\")", "def load_graph(self,\n graph_data: Tuple[Graph, Mapping, Graph, Dict]) -> None:\n self.graph = graph_data[0]\n self.graph2 = graph_data[2]\n self.mapping = graph_data[1]\n self.attr_requirements: \\\n Dict[GraphElement, Dict[str, GraphElement]] = graph_data[3]\n self._clear_drawing()\n self._redraw_graph()", "def load_graph(self, path):\n if path.split('.')[-1]=='gexf':\n self.graph = nx.read_gexf(path)\n else:\n self.graph = nx.read_gpickle(path)", "def populate_graph(self):", "def print_graph() -> None:\n raise NotImplementedError", "def show_graph(graph_def = None, max_const_size=32, height=800):\n\n if graph_def is None:\n graph_def = tf.get_default_graph().as_graph_def()\n if hasattr(graph_def, 'as_graph_def'):\n graph_def = graph_def.as_graph_def()\n\n strip_def = strip_graph_consts(graph_def, max_const_size=max_const_size)\n\n code = f\"\"\"\n <script>\n function load() {{\n document.getElementById(\"tf-graph\").pbtxt = {repr(str(strip_def))};\n }}\n </script>\n <link rel=\"import\" href=\"https://tensorboard.appspot.com/tf-graph-basic.build.html\" onload=load()>\n <div style=\"height: {height}px\">\n <tf-graph-basic id=\"tf-graph\"></tf-graph-basic>\n </div>\n \"\"\"\n\n code = code.replace('\"', '&quot;')\n iframe = f\"\"\"\n <iframe seamless style=\"width:1200px;height:{height}px;border:0\" srcdoc=\"{code}\"></iframe>\n \"\"\"\n display(HTML(iframe))", "def draw_graph(self):\n\t\tif None in self.graph:\n\t\t\tdel self.graph[None]\n\n\t\tfor vs in self.graph.itervalues():\n\t\t\tto_delete = []\n\t\t\tfor i in xrange(len(vs)):\n\t\t\t\tif vs[i] is None:\n\t\t\t\t\tto_delete.append(i)\n\n\t\t\tfor i in reversed(to_delete):\n\t\t\t\tdel vs[i]\n\n\t\tself.G=nx.Graph(self.graph)\n\n\t\tfor k,v in self.labels.iteritems():\n\t\t\tif v[:6] == 'Module':\n\t\t\t\troot = k\n\t\t\t\tbreak\n\n\t\treturn self.__dfs_plot(root)", "def displayGraph(self):\n self.dto.displayVerticalGraph()\n print(\"Vertical Bar Graph displayed.\")", "def _load_from_path(self):\n logging.info(\"Loading graph data from %r\", self.path)\n self._load_vconstraints_from_path(self.vertices_constraints_path)\n self._load_vertices_from_path(self.vertices_path)\n self._load_edges_from_path(self.edges_path)\n logging.info(\"Completed %r graph import\", self.path)", "def render_graph(self, view=True):\n\n log.debug(\"Rendering Graph to image file [%s]\" % 'NOT_IMPLEMENTED')\n\n if view:\n self.graph.view()\n else:\n self.graph.render()", "def visualize_dependency_graph(self):\n if self.graph is None:\n self.logger.error(\"Graph value none cannot be plotted\")\n return\n\n nx.draw(self.graph, cmap=plt.get_cmap('jet'), with_labels=True)\n plt.show()", "def graphs():\n return render_template(\"graphs.html\")", "def load_graph( gname ):\n return NX.read_gpickle( gname )", "def base_visualization(self, filename, save_format='jpg', cfg=None):\n # TODO and detailed mode for the visualization function\n # in which the graph will also contain all the weights/bias\n # information.\n # if not cfg:\n # cfg = {}\n # graph = graphviz.Digraph(format=save_format)\n # self.visited.clear()\n # for _input in self.graph.inputs():\n # if _input.type().kind() == CLASSTYPE_KIND:\n # continue\n # self.visual_traverse(_input, graph, None, cfg)\n # graph.render(filename)\n pass", "def show_graphs(self):\n self.frequency_plot_graph.show()\n self.resistance_graph.show()\n self.temperature_plot_graph.show()\n self.pressure_plot_graph.show()\n self.humidity_plot_graph.show()\n self.overview_graph.show()\n self.overview_graph.setXRange(-1000, 5000)", "def plot_graph(self):\n g = self.get_graph()\n plt.title(\"Our graph:\" + g.__str__())\n plt.xlabel(\"X\")\n plt.ylabel(\"-<\") # I should flip 'Y' letter so I decided to write it by a tricky way. :)\n for src, node in g.get_all_v().items():\n # Print the node point\n if node.location is None:\n pos = self.get_random_location() # get a elegant location\n node.location = GeoLocation(pos)\n plt.plot(node.location.x, node.location.y, marker='o', markerfacecolor='red', markersize=3, color='yellow')\n plt.text(node.location.x, node.location.y, str(node.key))\n # Print the edge line\n for dest in g.all_out_edges_of_node(src).keys():\n x1 = g.get_all_v()[src].location.x\n y1 = g.get_all_v()[src].location.y\n if g.get_all_v()[dest].location is None:\n pos = self.get_random_location()\n g.get_all_v()[dest].location = GeoLocation(pos)\n g.get_all_v()[dest].location = GeoLocation(pos)\n x2 = g.get_all_v()[dest].location.x\n y2 = g.get_all_v()[dest].location.y\n plt.arrow(x1, y1, x2 - x1, y2 - y1, width=0.00001, linewidth=0.05)\n plt.show()" ]
[ "0.7156698", "0.68800837", "0.6848133", "0.6830049", "0.6730292", "0.66468304", "0.6600777", "0.654772", "0.6512795", "0.6414203", "0.6403494", "0.63959014", "0.6333781", "0.63320535", "0.62774754", "0.6231875", "0.6223195", "0.61864907", "0.6167505", "0.61524636", "0.61355907", "0.6069638", "0.6061869", "0.6060004", "0.60578835", "0.6054658", "0.5960824", "0.59382033", "0.59349006", "0.592593" ]
0.72175366
0
Return the graph that is represented by the specified axes.
def _get_connected_graph(self, axes: plt.Axes) -> Graph: if axes == self.subplot: return self.graph else: raise KeyError('Specified Axes could not be found.')
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _get_connected_graph(self, axes: plt.Axes) -> Graph:\n if axes == self.subplot:\n return self.graph\n elif axes == self.subplot2:\n return self.graph2\n else:\n raise KeyError('Specified Axes could not be found.')", "def axes(self) -> np.ndarray: # array[Axes]\n return self._axes", "def get_axes(self) -> VGroup:\n return self.axes", "def get_axes(self) -> VGroup:\n return self.axes", "def axes(self):\n return self._axes", "def axes(self):\n return self._axes", "def allAxes( mv ):\n if mv is None: return None\n return mv.getAxisList()", "def getPlot(self):\n return self.axes", "def axes(*x: Iterable[int]):\n return [_ti_core.Axis(i) for i in x]", "def __init__(self, axes=()):\n self._axes = []\n self._dimension = 0\n for axis in axes:\n self.add_axis(axis)", "def split(self, axis):\n if axis not in self.axes_names:\n raise Exception('Axis %s not found. Available axes: %s'\n % (axis, self.axes_names))\n\n return OrderedDict((dv, self.sub_cuboid(**{axis: dv}))\n for dv in self.axes_domains[axis])", "def getAxis(self,axis):\n\n\t\tif axis == \"u\":\n\t\t\tif len(self.usr) != 0:\n\t\t\t\treturn np.append([0], self.usr)\n\n\t\tif axis == \"s\":\n\t\t\tif len(self.seg) != 0:\n\t\t\t\tif self.radiograph:\n\t\t\t\t\treturn self.seg\n\t\t\t\telse:\n\t\t\t\t\tfirst = self.seg[0] - 1.\n\t\t\t\t\treturn np.append([first], self.seg)\n\n\t\tif axis == \"c\":\n\t\t\tif len(self.cos) != 0:\n\t\t\t\tif self.radiograph:\n\t\t\t\t\treturn self.cos\n\t\t\t\telse:\n\t\t\t\t\tfirst = -1.\n\t\t\t\t\treturn np.append([first], self.cos)\n\n\t\tif axis == \"e\":\n\t\t\tif len(self.erg) != 0:\n\t\t\t\tfirst = self.erg[0] - 1.\n\t\t\t\treturn np.append([first], self.erg)\n\n\t\tif axis == \"t\":\n\t\t\tif len(self.tim) != 0:\n\t\t\t\tfirst = self.tim[0] - 1.\n\t\t\t\treturn np.append([first], self.tim)\n\n\t\tif axis == \"i\":\n\t\t\treturn self.cora\n\n\t\tif axis == \"j\":\n\t\t\treturn self.corb\n\n\t\tif axis == \"k\":\n\t\t\treturn self.corc\n\n\t\treturn []", "def maybe_get_ax(*args, **kwargs):\n\n if 'ax' in kwargs:\n ax = kwargs.pop('ax')\n elif len(args) == 0:\n fig = plt.gcf()\n ax = plt.gca()\n elif isinstance(args[0], mpl.axes.Axes):\n ax = args[0]\n args = args[1:]\n else:\n ax = plt.gca()\n return ax, args, dict(kwargs)", "def _get_graph(nodes: Nodes, edges: np.ndarray):\n\n graph = nx.Graph()\n graph.add_nodes_from(nodes['id'])\n attrs = nodes.set_index('id').to_dict('index')\n nx.set_node_attributes(graph, attrs)\n graph.add_edges_from(edges)\n\n return graph", "def make_2axis_graph():\n d = curdoc()\n _remove_fig(d)\n graph_val = d.get_model_by_name(GRAPH_SELECTION).value\n model_id, message_name, _ = run_handlers.get_modelid_messagename_type(d)\n\n xval = d.get_model_by_name(X_AXIS_SELECTION).value\n yval = d.get_model_by_name(Y_AXIS_SELECTION).value\n\n if xval != DEFAULT_UNSELECTED and yval != DEFAULT_UNSELECTED:\n plot = figure(plot_width=400, plot_height=400, name=FIGURE_MODEL)\n sind = run_handlers.get_source_index(d.session_context.id, model_id, message_name)\n _install_callback_and_cds(sind, model_id, message_name, stream_limit=100000)\n\n # get the field name back from the pretty field : meta string formed above\n x = xval.split(\" :\")[0]\n y = yval.split(\" :\")[0]\n\n if graph_val == \"line\":\n plot.line(x=x, y=y, color=\"firebrick\", line_width=2, source=d.get_model_by_name(sind))\n plot.x_range.follow = \"end\" # don't jam all the data into the graph; \"window\" it\n plot.x_range.follow_interval = 100\n plot.x_range.range_padding = 0\n if graph_val == \"scatter\":\n plot.cross(x=x, y=y, size=20, color=\"firebrick\", line_width=2, source=d.get_model_by_name(sind))\n if graph_val == \"step\":\n plot.step(x=x, y=y, color=\"#FB8072\", source=d.get_model_by_name(sind))\n\n d.add_root(plot)", "def format_graph(axis):\r\n if isinstance(axis, np.ndarray):\r\n return [format_axis(ax) for ax in axis.flat]\r\n else:\r\n return format_axis(axis)", "def graphs(self):\n return self.__graphs", "def graph(self, *links):\n\n groups = self._model_terms(links)\n fig, ax = plt.subplots()\n for group in groups:\n for term in group:\n termdata = self._term_data[term]\n termdata.graph(ax)\n\n return ax", "def get_graph(self, engine, args):\n raise NotImplementedError(\"Override in subclass\")", "def get_data(self):\n return [self.axes]", "def _axes_domain(self, *args, **kwargs):\n # See _add_gridline_label for detials\n lon_0 = self.axes.projection.proj4_params.get('lon_0', 0)\n x_range, y_range = type(self)._axes_domain(self, *args, **kwargs)\n x_range = np.asarray(x_range) + lon_0\n return x_range, y_range", "def get_graph(self):\n return self._graph", "def gexf_graph():\n # you must replace these lines and supply your own graph\n my_gexf = Gexf(\"author\", \"title\")\n gexf.addGraph(\"undirected\", \"static\", \"I'm an empty graph\")\n return gexf.graphs[0]", "def findaxis(self, world=True, axis=0):\n return _coordsys.coordsys_findaxis(self, world, axis)", "def format_graph(axis):\n if isinstance(axis, numpy.ndarray):\n return [format_axis(ax) for ax in axis.flat]\n else:\n return format_axis(axis)", "def from_cartesian(self, coordinates, *axes):", "def _combine_domains(self, axes):\n def stack_dvalues(prev, x):\n if 0:\n print 'stack_dvalues ...'\n print 'prev:', prev\n print 'x:', x\n res = prev + [list(np.tile(x, len(prev) == 0 or len(prev[-1])))]\n if 0:\n print 'result:', res\n print ''\n return res\n return reduce(stack_dvalues, [self.axes_domains[a] for a in axes], [])", "def get_domain(self, axis_id):\n if axis_id in self.axes_domains:\n return self.axes_domains[axis_id]\n else:\n raise Exception('Unknow axis %s' % axis_id)", "def getGraph(self):\n\t\treturn self.graph", "def _get_axis(axis):\n\n def axis_getter(self):\n ErrorMessage.default_to_pandas(f\"DataFrame.get_axis({axis})\")\n return self.to_pandas().axes[axis]\n\n return axis_getter" ]
[ "0.6946097", "0.5786139", "0.5764504", "0.5764504", "0.57531923", "0.57531923", "0.5719589", "0.5469798", "0.5383216", "0.53713644", "0.5342922", "0.52830964", "0.52605724", "0.5249076", "0.5199109", "0.5196632", "0.51746565", "0.51670814", "0.5148048", "0.5135304", "0.51338637", "0.5128643", "0.5124559", "0.51228726", "0.51223123", "0.51064175", "0.5104479", "0.5096259", "0.5078219", "0.5067992" ]
0.7047026
0
Adds a vertex to the graph at the position defined by the mpl event.
def add_vertex(self, event: matplotlib.backend_bases.LocationEvent) \ -> None: transform_func = event.inaxes.transData.inverted().transform new_coords = transform_func((event.x, event.y)) log.info(f'Adding Vertex @ {event.x} - {event.y}, axis: ' f'{new_coords}') graph = self._get_connected_graph(event.inaxes) vertex = Vertex() vertex.attr['x'] = float(new_coords[0]) vertex.attr['y'] = float(new_coords[1]) graph.add(vertex) self._redraw_graph()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def add_vertex(self, vertex):\n raise NotImplementedError", "def add_vertex(self, vertex_id):\n pass # TODO", "def add_vertex(self, vertex):\n self.vertices.append(vertex)\n self.vertex_edge[vertex] = []", "def add_vertex(self, label):\n\n if label in self._vertices:\n raise RuntimeError(\"vertex = '{}'\".format(label) + \n \" is already a vertex in this directed graph\")\n self._vertices[label] = Vertex(label)", "def add_vertex(self, vertex_name: n):\n new_vertex = Vertex(vertex_name)\n self._graph[new_vertex.name] = new_vertex", "def add_vertex(self, vertex):\n if vertex.id not in self.vertices.keys():\n self.vertices[vertex.id] = vertex", "def add_vertex(self, vertex):\n if isinstance(vertex, Vertex):\n self.vertices.append(vertex)\n return\n raise TypeError('Is not vertex instance!')", "def add_vertex(self):\n self.visited_node += [False]\n self.V = self.V + 1\n self.adjacency_list.append(list())", "def __add__(self, vertex):\n\n if isinstance(vertex, Vertex):\n vName = vertex.name\n self._vertices[vName] = vertex", "def add_vertex(self, item: Any, kind: str) -> None:\n if item not in self._vertices:\n self._vertices[item] = _Vertex(item, kind)", "def add_vertex(self, u, val):\n raise NotImplementedError()", "def add_vertex(self, v):\n v = {'x': v[0], 'y': v[1]}\n if v not in self:\n self.append(v)\n return len(self)-1\n return self.index(v)", "def add_vertex(self, vertex: Vertex) -> None:\n self._vertices.add(vertex)\n if not vertex.predicate:\n self._entities.add(vertex)", "def add_vertex(self, vertex):\n if vertex not in self.__graph_dict:\n self.__graph_dict[vertex] = []", "def add_vertex(self, vertex):\n if vertex not in self.__graph_dict:\n self.__graph_dict[vertex] = []", "def add_vertex(self,vertex):\n if vertex not in self.__graph_dict:\n self.__graph_dict[vertex] = []\n # logging.debug(\"vertex being initialized ..\", vertex)\n else:\n # logging.debug(\"vertex not added ..\", vertex)\n pass", "def addVertex(self, v: Vertex):\n if v is not None:\n self._vertices.add(v)\n\n # Possibly need to recalculate genus/core/etc.\n self.invalidateCaches()", "def add_vertex(self, vertex_name, vertex_type=None):\n if vertex_name not in self._vertex_dict:\n self._labels.InsertNextValue(vertex_name)\n self._vertex_dict[vertex_name] = self.vertex_tuple(Vertex(vertex_name, vertex_type),\n self._graph.AddVertex())\n if vertex_type not in self._color_dict:\n self._color_dict[vertex_type] = self._vertex_types\n self._vertex_types += 1\n self._colors.append(self._color_dict[vertex_type])", "def add_vertex(self, vertex):\n if vertex not in self.graph_dict:\n self.graph_dict[vertex] = []", "def add_vertex(self, key):\n vertex = Vertex(key)\n self.vertices[key] = vertex", "def add_vertex(self, vertex):\n try:\n vertex_idx = self.vertices.index(vertex)\n # print \"{} already in {}\".format(vertex, self.vertices)\n return self.vertices[vertex_idx]\n except Exception:\n self.vertices.append(vertex)\n # print \"adding {} to {}\".format(vertex, self.vertices)\n return vertex", "def add_vertex(self, key):\n self.vertCount += 1\n addedVertex = vertex.Vertex(key)\n self.vertList[key] = addedVertex\n return addedVertex", "def add_vertex(self, key):\n if key in self.vertices:\n raise ValueError('Key is already in use')\n \n # Create vertex\n self.vertices[key] = GraphVertex(key=key)", "def add_vertex(self, vertex):\n if vertex not in self.graph_dict:\n self.graph_dict[vertex] = []\n return vertex", "def add_vertex(self, vertex):\r\n if vertex not in self.__graph_dict:\r\n self.__graph_dict[vertex] = {}", "def add_vertex(self, vertex_id):\n # add new vertex in vertices\n self.vertices[vertex_id] = set()\n\n # increment len\n self.len += 1", "def add_vertex(self, vertex):\n if self.contains(vertex):\n return None\n if self.is_weighted():\n self._graph[vertex] = dict()\n else:\n self._graph[vertex] = set()\n return True", "def add_node(self,node):\n \n vertex = Vertex(node)\n \n self.nodes[node] = vertex\n self.numNodes += 1", "def add_vertex(self, vertex):\r\n if self.is_vertex_in_graph(vertex):\r\n raise GraphException(\"The vertex already exists.\")\r\n self.__neighbours[vertex] = []", "def add_vertex(self, x, y):\n\n if not isinstance(x, int) and not isinstance(x, float):\n raise TypeError(\"x must be numeric, not '%s'\" % x)\n if not isinstance(y, int) and not isinstance(y, float):\n raise TypeError(\"y must be numeric, not '%s'\" % y)\n self._coordinates.append(x)\n self._coordinates.append(y)" ]
[ "0.7563129", "0.723222", "0.7161543", "0.7156355", "0.71207875", "0.71198916", "0.7035426", "0.6999496", "0.6957054", "0.69250786", "0.6904555", "0.6765922", "0.67454743", "0.66659695", "0.66659695", "0.6649009", "0.66469586", "0.66432774", "0.66098505", "0.6546472", "0.652673", "0.6499873", "0.6466947", "0.64412737", "0.6435604", "0.64216405", "0.64116794", "0.63983893", "0.6360676", "0.6357908" ]
0.8221702
0
Add a mapping between the two elements to the production.
def _add_mapping(self, mother_element: GraphElement, daughter_element: GraphElement) -> None: pass
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _add_mapping(self, mother_element: GraphElement,\n daughter_element: GraphElement) -> None:\n self.mapping[mother_element] = daughter_element", "def __add__(self, other: MapValue) -> MapValue:\n return ops.MapMerge(self, other).to_expr()", "def __radd__(self, other: MapValue) -> MapValue:\n return ops.MapMerge(self, other).to_expr()", "def applyMapping(self):\n pass", "def product_map(xs1, xs2):\n return jax.vmap(lambda x1: jax.vmap(lambda x2: pair_product(x1, x2))(xs2))(xs1)", "def Map(a, b):\n out = {}\n for key, value in a.items():\n if key in b:\n out[value] = b[key]\n return out", "def extend(self, mappings):\n if isinstance(mappings, self.__class__):\n mappings = mappings.maps\n for m in mappings:\n if self.mapper is not None:\n m = self.mapper(m)\n self.append(m)", "def addMapping(mapping):\n defaultMapping_.addMapping(mapping)", "def extend_map(self,\n other_map,\n overwrite_existing=False,\n extend_existing=False):\n self.taxon_seq_map.extend(other_map,\n overwrite_existing=overwrite_existing,\n extend_existing=extend_existing)\n self.update_taxon_set()", "def convert_mapping(self, mapping, comp1, comp2, var1, var2):\n model = self.model\n # Check for being already converted\n var_pair = frozenset([var1, var2])\n if var_pair in self._converted_mappings:\n DEBUG('units-converter', 'Skipping already converted mapping', var1, '<->', var2)\n return\n else:\n self._converted_mappings.add(var_pair)\n # Ensure mapping is var1 := var2; swap vars if needed\n swapped = False\n try:\n if var2.get_source_variable() is var1:\n swapped = True\n var1, var2 = var2, var1\n comp1, comp2 = comp2, comp1\n except TypeError:\n pass\n # Get units\n u1 = var1.get_units()\n u2 = var2.get_units()\n DEBUG('units-converter', \"Converting mapping of\", var1, \":=\", var2,\n \"(units:\", repr(u1), repr(u2), \")\")\n if not u1.equals(u2):\n # We need a conversion\n # Add a copy of var1 to comp1, with units as var2\n if getattr(var1, u'public_interface', '') == u'in':\n in_interface = u'public'\n else:\n in_interface = u'private'\n var1_converter = self.add_variable(comp1, var1.name + u'_converter', u2, interfaces={in_interface: u'in'})\n var1._cml_var_type = VarTypes.Computed\n var1._cml_source_var = None\n delattr(var1, in_interface + u'_interface')\n var1_converter._set_source_variable(var2)\n # Add assignment maths for var1 := var1_converter\n app = mathml_apply.create_new(model, u'eq', [var1.name, var1_converter.name])\n self.add_expr_to_comp(comp1, app)\n var1._cml_depends_on = [app]\n app._cml_assigns_to = var1\n # Update mapping to var1_converter := var2\n if swapped:\n mapping.variable_2 = var1_converter.name\n else:\n mapping.variable_1 = var1_converter.name\n # Fix usage counts - var1_converter is only used by app, and so var2 usage decreases\n var1_converter._used()\n for _ in xrange(var1.get_usage_count()):\n var2._decrement_usage_count()\n # Apply units conversion to the assignment\n self.convert_assignments([app])\n # Add the assignment into the sorted list\n assignments = model.get_assignments()\n idx = assignments.index(var1)\n assignments[idx:idx+1] = [var1_converter, app]", "def intercambiar(mapa, mapa2):\n for e in mapa.bloqueadas:\n mapa2.bloqueadas.append(e)", "def extend(primary: Mapping, *others: Mapping, in_place=False):\n others = flatten(others)\n if not in_place:\n primary = dict(primary or {})\n for other in others:\n if other is None:\n continue\n for key, value in other.items():\n primary[key] = value\n return primary", "def addMapping(self, baseType, refType):\n if not self.apiName(baseType) or not self.apiName(refType):\n self.logMsg('diag', 'ScriptOutputGenerator::addMapping: IGNORE map from', baseType, '<->', refType)\n return\n\n self.logMsg('diag', 'ScriptOutputGenerator::addMapping: map from',\n baseType, '<->', refType)\n\n if baseType not in self.mapDict:\n baseDict = {}\n self.mapDict[baseType] = baseDict\n else:\n baseDict = self.mapDict[baseType]\n if refType not in self.mapDict:\n refDict = {}\n self.mapDict[refType] = refDict\n else:\n refDict = self.mapDict[refType]\n\n baseDict[refType] = None\n refDict[baseType] = None", "def _do_mapping(self):\n pass", "def push(self, mapping):\n self.mappings.append(mapping)", "def add_prod(self, lhs, rhs):\n prods = rhs.split('|')\n for prod in prods:\n self.prod[lhs].append(tuple(prod.split()))", "def add_prod(self, lhs, rhs):\n prods = rhs.split('|')\n for prod in prods:\n self.prod[lhs].append(tuple(prod.split()))", "def put_map(self, elem_map):\n ierr = exolib.py_expmap(self.exoid, elem_map + self._o)\n if ierr:\n raise ExodusIIWriterError(\"Error putting element map\")", "def _declare_auto_variable_mapping(self):\n if self.name not in self.nlp.variable_mappings:\n self.nlp.variable_mappings[self.name] = BiMapping(\n range(len(self.name_elements)), range(len(self.name_elements))\n )", "def map2(inKey, inVal):\n return [([inKey[0]],inKey[1:]+inVal)]", "def add_descriptors(self, mapping):\n for key, desc in mapping.iteritems():\n self.descriptors[int(key, 16)] = desc", "def add_descriptors(self, mapping):\n for key, desc in mapping.iteritems():\n self.descriptors[int(key, 16)] = desc", "def draw_mappings(self, mapping: Mapping) -> None:\n for graph_element1, graph_element2 in mapping.items():\n figure_element1 = self.graph_to_figure[graph_element1]\n figure_element2 = self.graph_to_figure[graph_element2]\n p1, p2 = mapping_points_between_figure_elements(figure_element1,\n figure_element2)\n patch = ConnectionPatch(\n xyA=(p1.x, p1.y),\n xyB=(p2.x, p2.y),\n coordsA=\"data\",\n coordsB=\"data\",\n axesA=self.subplot,\n axesB=self.subplot2,\n arrowstyle=\"->\",\n clip_on=False,\n )\n figure_element1.mapping_left = patch\n figure_element2.mapping_right = patch\n self.mappings.add(patch)\n self.subplot.add_artist(patch)\n self.redraw()", "def mapping_for_switch(mapping):\n return {key[0]: value for key, value in mapping.items()}", "def edge_mapping(self):\n ...", "def _combine(mappings):\n return {k: v for d in mappings for k, v in d.items()}", "def alias(new_field, existing_field):\n mapping[new_field] = mapping[existing_field]", "def map(self, attr1, attr2):\n return dict(zip(getattr(self, attr1), getattr(self, attr2)))", "def map(self, attr1, attr2):\n return dict(zip(getattr(self, attr1), getattr(self, attr2)))", "def mapping(self, mapping):\n self.set_mapping(mapping)" ]
[ "0.7042673", "0.6301587", "0.608117", "0.6053467", "0.60229", "0.5890286", "0.587229", "0.58372045", "0.58208764", "0.5736256", "0.5708055", "0.56233305", "0.5622347", "0.5588315", "0.55871934", "0.55576986", "0.55576986", "0.5500496", "0.5489049", "0.5449521", "0.54427195", "0.54427195", "0.5427086", "0.54229593", "0.54149336", "0.5394763", "0.5378424", "0.53769654", "0.53769654", "0.53757966" ]
0.7386965
0
Adds an attribute requirement between the two specified elements.
def _add_attr_requirement(self, mother_element: GraphElement, daughter_element: GraphElement) -> None:
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _add_attr_requirement(self, mother_element: GraphElement,\n daughter_element: GraphElement) -> None:\n if not daughter_element in self.attr_requirements:\n self.attr_requirements[daughter_element] = {}\n requirement_num = len(self.attr_requirements[daughter_element])\n requirement_name = f'arg{requirement_num}'\n self.attr_requirements[daughter_element][requirement_name] = mother_element", "def add_attr_requirement(self, event: Union[wx.CommandEvent, None],\n attr_req_label: str = '',\n attr_req_element: GraphElement = None) -> None:\n new_id = len(self.attr_req_ids)\n self.attr_req_ids[new_id] = attr_req_label\n button_remove = wx.Button(self, wx.ID_ANY, label='-')\n self.Bind(wx.EVT_BUTTON, partial(self.remove_attr, attr_id=new_id),\n button_remove)\n attr_req_label_ctrl = wx.TextCtrl(self, value=attr_req_label)\n attr_req_element_ctrl = wx.StaticText(self, label=str(attr_req_element))\n self.attr_req_labels[new_id] = attr_req_label_ctrl\n self.attr_req_elements[new_id] = attr_req_element_ctrl\n self.attr_req_buttons[new_id] = button_remove\n if event is not None:\n self._update_attr_list()", "def add_attribute(a, name, other):\n raise TypeError(\"can't add new attribute\")", "def add(element1, element2):\n \n newtag = Tag.addTags(element1.tag, element2.tag)\n \n #have to wrap the attributes in dict() to avoid a bus error\n newattribs = Attrib.addAttribs(dict(element1.attrib), dict(element2.attrib))\n \n element1.tag = newtag\n element1.text = Text.addText(element1.text, element2.text)\n element1.tail = Text.addText(element1.tail, element2.tail)\n \n for i in element1.attrib:\n del element1.attrib[i]\n for key in newattribs.keys():\n try:\n element1.set(key, newattribs[key])\n except TypeError:\n log = logging.getLogger()\n log.error('TypeError: %s' % str(sys.exc_info()[1]))\n log.error('key = %s\\tnewattribs[key] = %s' % (str(key), str(newattribs[key])))\n raise\n \n return element1", "def _load_attrs_requirements(self) -> None:\n if self.element not in self.attr_requirements:\n return\n self.attr_req_ids.clear()\n for attr_req_label, attr_req_value in \\\n self.attr_requirements[self.element].items():\n self.add_attr_requirement(None, attr_req_label, attr_req_value)\n self._update_attr_list()", "def _xml_requires(self, ele):\n ef = element('{http://linux.duke.edu/metadata/rpm}requires')\n used = 0\n\n for prco in sorted(self.requires):\n if prco.name.startswith('rpmlib('):\n continue\n\n # this drops out requires that the pkg provides for itself.\n if prco.name in [p.name for p in self.provides] or (prco.name.startswith('/') and (prco.name in [file.name for file in self.filelist])):\n if not prco.flags:\n continue\n else:\n if prco in self.provides:\n continue\n\n entry = element('{http://linux.duke.edu/metadata/rpm}entry', {'name': prco.name})\n if prco.str_flags:\n entry.set('flags', prco.str_flags)\n e, v, r = prco.version\n if e:\n entry.set('epoch', str(e))\n if v:\n entry.set('ver', v)\n if r:\n entry.set('rel', r)\n if prco.flags & 1600:\n entry.set('pre', '1')\n\n ef.append(entry)\n used += 1\n\n if used != 0:\n ele.append(ef)", "def addExpectedAttributes(self, *args):\n return _libsbml.MultiASTPlugin_addExpectedAttributes(self, *args)", "def addExpectedAttributes(self, *args):\n return _libsbml.ASTBasePlugin_addExpectedAttributes(self, *args)", "def blendTwoAttr(*args, attribute: Union[AnyStr, List[AnyStr]]=\"\", attribute0: Union[name,\n bool]=None, attribute1: Union[name, bool]=None, blender: Union[name,\n bool]=None, controlPoints: bool=False, driver: Union[int, bool]=0, name:\n Union[AnyStr, bool]=\"\", shape: bool=True, time: timerange=None, q=True,\n query=True, e=True, edit=True, **kwargs)->Union[List[AnyStr], Any]:\n pass", "def attrCompatibility(*args, addAttr: bool=True, clear: bool=True, dumpTable: bool=True,\n enable: bool=True, nodeRename: AnyStr=\"\", pluginNode: AnyStr=\"\",\n removeAttr: bool=True, renameAttr: AnyStr=\"\", type: AnyStr=\"\", version:\n AnyStr=\"\", **kwargs)->None:\n pass", "def addExpectedAttributes(self, *args):\n return _libsbml.FbcModelPlugin_addExpectedAttributes(self, *args)", "def add_requirements(self, fgraph):\r\n pass", "def add_multi_link_attributes(self, attr1,attr2, attr3):\n i = 0\n for (u, v) in self.G.edges():\n if self.checkKey(attr1, (u,v)) and self.checkKey(attr2, (u,v)) and self.checkKey(attr3, (u,v)):\n self.G.add_edge(u,v,w=attr1[(u,v)],c1=attr2[(u,v)], c2= attr3[(u,v)])\n elif self.checkKey(attr1, (v,u)) and self.checkKey(attr2, (v,u)) and self.checkKey(attr3, (v,u)):\n self.G.add_edge(u,v,w=attr1[(v,u)],c1=attr2[(v,u)], c2= attr3[(v,u)])\n else:\n if not self.checkKey(attr1, (u,v)) and not self.checkKey(attr1, (v,u)):\n raise Exception(\"Weight edge list has missing value for \", u, v)\n if not self.checkKey(attr2, (u,v)) and not self.checkKey(attr2, (v,u)):\n raise Exception(\"Concave edge list has missing value for \", u, v)\n if not self.checkKey(attr3, (u,v)) and not self.checkKey(attr3, (v,u)):\n raise Exception(\"CPU edge has list missing value for \", u, v)\n i = i+1 \n return self.G", "def add_pair (self, first, second):\n self.constraints_.append ((first, second))", "def add_attrib(self, key, func, func_args):\n if key in self.aux_attrib:\n raise KeyError(\"Attribute '{0}' already exists, please use 'set_attrib'.\".format(key))\n else:\n self.set_attrib(key, func, func_args)", "def add_required(self, name, checkfunc=None, params=None):\n\tself._required.append((name, checkfunc, params))", "def attr_imply(self):\n if not self._modifier_exists(IMPLIED_KEY):\n return\n implications = self[CONFIG_KEY][SAMPLE_MODS_KEY][IMPLIED_KEY]\n if not isinstance(implications, list):\n raise InvalidConfigFileException(\n \"{}.{} has to be a list of key-value pairs\".\n format(SAMPLE_MODS_KEY, IMPLIED_KEY)\n )\n _LOGGER.debug(\"Sample attribute implications: {}\".format(implications))\n for implication in implications:\n if not all([key in implication for key in IMPLIED_COND_KEYS]):\n raise InvalidConfigFileException(\n \"{}.{} section is invalid: {}\".\n format(SAMPLE_MODS_KEY, IMPLIED_KEY, implication)\n )\n implier_attrs = list(implication[IMPLIED_IF_KEY].keys())\n implied_attrs = list(implication[IMPLIED_THEN_KEY].keys())\n for sample in self.samples:\n _LOGGER.debug(\"Setting Sample attributes implied by '{}'\".\n format(implier_attrs))\n for implier_attr in implier_attrs:\n implier_val = implication[IMPLIED_IF_KEY][implier_attr]\n if implier_attr not in sample:\n _LOGGER.debug(\"Sample lacks implier attr ({}), \"\n \"skipping:\".format(implier_attr))\n break\n sample_val = sample[implier_attr]\n if sample_val not in implier_val:\n _LOGGER.debug(\n \"Sample attr value does not match any of implier \"\n \"requirements ({} not in {}), skipping\".\n format(sample_val, implier_val))\n break\n else:\n # only executed if the inner loop did NOT break\n for implied_attr in implied_attrs:\n imp_val = implication[IMPLIED_THEN_KEY][implied_attr]\n _LOGGER.debug(\"Setting implied attr: '{}={}'\".\n format(implied_attr, imp_val))\n sample.__setitem__(implied_attr, imp_val)", "def add_attribute(node_proto, name, value):\n node_proto.attribute.extend([make_attribute(name, value)])", "def attributeDecl(self, elem, name, type, defi, defaultValue, nameList):\n pass", "def add_requirements(self, fgraph):\r\n # Added by default\r\n #fgraph.attach_feature(toolbox.ReplaceValidate())\r\n pass", "def merge_requirements(req1, req2):\n if req1 is not None and req2 is None:\n return req1\n if req2 is not None and req1 is None:\n return req2\n\n req1_name_norm = normalize_project_name(req1.name)\n if req1_name_norm != normalize_project_name(req2.name):\n raise ValueError(\"Reqs don't match: {} != {}\".format(req1, req2))\n all_specs = set(req1.specs or []) | set(req2.specs or [])\n\n # Handle markers\n if req1.marker and req2.marker:\n if str(req1.marker) != str(req2.marker):\n if str(req1.marker) in str(req2.marker):\n new_marker = \";\" + str(req1.marker)\n elif str(req2.marker) in str(req1.marker):\n new_marker = \";\" + str(req2.marker)\n else:\n new_marker = \"\"\n else:\n new_marker = \";\" + str(req1.marker)\n else:\n new_marker = \"\"\n\n extras = merge_extras(req1.extras, req2.extras)\n extras_str = \"\"\n if extras:\n extras_str = \"[\" + \",\".join(extras) + \"]\"\n req_str = (\n req1_name_norm\n + extras_str\n + \",\".join(\"\".join(parts) for parts in all_specs)\n + new_marker\n )\n return parse_requirement(req_str)", "def merge_attribute_defs(self, dest, source, changes = {}):\n # print \"in merge_attribute_defs, dest =\"\n # pp.pprint(dest)\n # print \"source =\"\n # pp.pprint(source)\n for aid in source.keys():\n if aid not in dest.keys():\n # copy attribute, then check for append\n dest[aid] = copy.deepcopy(source[aid])\n if 'value' in dest[aid]:\n if type(dest[aid]['value']) is str and dest[aid]['value'][0]=='+':\n dest[aid]['value'] = dest[aid]['value'].lstrip('+')\n changes[aid] = dest[aid]['value']\n continue \n if 'value' not in dest[aid]:\n if 'value' in source[aid]:\n dest[aid]['value'] = source[aid]['value']\n if (type(dest[aid]['value']) is str and dest[aid]['value'][0] == '+'):\n dest[aid]['value'] = dest[aid]['value'].lstrip('+') \n changes[aid] = dest[aid]['value']\n continue\n else:\n print (\"** Error, merging attribute '%s' but value not specified in source\"\n \" or destination\") % aid\n traceback.print_stack()\n sys.exit(1) \n else:\n if 'value' in source[aid]: \n # value given in both source and destination\n self.append_or_replace(dest[aid], source[aid], 'value', \"attribute %s\" % aid)\n changes[aid] = dest[aid]['value'] # save changed value\n else:\n print (\"** Warning, node at:\\n%s\\nmerging attribute '%s'\" \n \" but value to merge not specified.\") % (self.full_path, aid)\n print \"source attributes:\"\n pp.pprint(source)\n print \"dest attributes:\"\n pp.pprint(dest)", "def add_attributes(self, attrs):\n self.attrs.add_attributes(attrs)", "def addConstraint(self, *args):\n return _libsbml.Model_addConstraint(self, *args)", "def add(self, *args):\n return _libsbml.XMLAttributes_add(self, *args)", "def in_attr_list(self, attrs):\n for other in attrs:\n if other.matches(self): return True\n return False", "def add(self, a: 'PFElement', b: 'PFElement') -> 'PFElement':\n return self(self._pf_add(a.value, b.value, self.additive_group))", "def test_attribute_order(self):\n element = Element(\"div\")\n element.set_attribute(\"def\", \"\")\n element.set_attribute(\"abc\", \"\")\n element.set_attribute(\"ghi\", \"\")\n assert_equal(\n [b'<div abc=\"\" def=\"\" ghi=\"\">', b\"</div>\"], list(iter(element))\n )", "def addElem2Specie():\n elnames = []\n for elem in Elems:\n elnames.append(elem.name)\n # Build the list of elements for each specie\n for speci in Species:\n elemlst = []\n nam = speci.name\n if nam.endswith(\"2+\") or nam.endswith(\"3+\") or nam.endswith(\"4+\"):\n nam = nam[:-2]\n elif nam.endswith('+') or nam.endswith('-'):\n nam = nam[:-1]\n if nam in elnames:\n # It is easy, there is only one element\n elemlst.append((nam, 1))\n else:\n while len(nam):\n find = False\n for elnam in elnames:\n if nam.startswith(elnam):\n l = len(elnam)\n if len(nam) > l and IsNumber(nam[l]):\n n = int(nam[l])\n nam = nam[l + 1:]\n else:\n n = 1\n nam = nam[l:]\n elemlst.append((elnam, n))\n find = True\n break\n if not find:\n msg = \"Missing element required by {0} specie\".format(speci.name)\n QtWidgets.QMessageBox.critical(None, appName, msg)\n return False\n speci.elem = copy.copy(elemlst)\n return True", "def add_attributes(self, attrs):\n for attr in attrs:\n self.add_attribute(attr)" ]
[ "0.7101804", "0.6230195", "0.6216398", "0.6155128", "0.59988314", "0.5600701", "0.545208", "0.5447197", "0.5264721", "0.5214643", "0.52116716", "0.52106464", "0.5197594", "0.51585436", "0.5156553", "0.50689334", "0.50541675", "0.50425434", "0.5041376", "0.5033299", "0.5023482", "0.5018939", "0.50078815", "0.5003548", "0.50013477", "0.4990316", "0.49886045", "0.4978481", "0.49593082", "0.49581635" ]
0.739838
0
Connects any two elements if it makes sense in context. Adds a new Edge between two vertices, if self.selected_element is not None and both vertices are in the same axes. If selected_element is None then it sets self.selected_element to the vertex passed as argument. If two edges are in the same axes nothing happens. If any two elements are in two different axes then a mapping is created between them.
def connect_elements(self, event: matplotlib.backend_bases.LocationEvent, element: 'FigureElement') -> None: if self.selected_element is None: self.selected_element = element element.add_extra_path_effect('selection', pe.Stroke(linewidth=5, foreground='b')) return graph = self._get_connected_graph(event.inaxes) element1 = self.graph_to_figure.inverse[self.selected_element][0] element2 = self.graph_to_figure.inverse[element][0] if self.selected_element.axes != element.axes: if event.guiEvent.CmdDown(): log.debug('Adding Attribute Requirement.') self._add_attr_requirement(element1, element2) else: log.debug('Adding Mapping.') self._add_mapping(element1, element2) elif isinstance(element1, Vertex) and isinstance(element2, Vertex): log.debug('Connecting Vertices.') self._add_edge(graph, element1, element2) self.selected_element.remove_extra_path_effect('selection') self.selected_element = None self._redraw_graph()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def add_edge(self, v1, v2):\n pass # TODO", "def add_edge(self, item1: Any, item2: Any, weight: Union[int, float]) -> None:\n if item1 in self._vertices and item2 in self._vertices:\n v1 = self._vertices[item1]\n v2 = self._vertices[item2]\n\n # Add the new edge\n v1.neighbours[v2] = weight\n v2.neighbours[v1] = weight\n else:\n # We didn't find an existing vertex for both items.\n raise ValueError", "def add_edge(self, nodes, X, U, V):\n assert(nodes[0] in self.nodes)\n assert(nodes[1] in self.nodes)\n\n if nodes[0] != nodes[1]:\n\n self.edges[nodes] = Graph.new_path([X, U, V])\n self.nodes[nodes[0]].linked_to.append(nodes[1])\n self.join_connex_groups(self.connex_elements[nodes[0]],\n self.connex_elements[nodes[1]])", "def add_edge(self, name1: Any, name2: Any, weight: float = 1.0) -> None:\n if name1 in self._vertices and name2 in self._vertices:\n v1 = self._vertices[name1]\n v2 = self._vertices[name2]\n\n # Add the new edge\n v1.neighbours[v2] = weight\n v2.neighbours[v1] = weight\n else:\n # We didn't find an existing vertex for both items.\n raise ValueError", "def add_edge(source, target, label, side_label):\n if (elements is not self and\n target not in elements):\n return\n if simple:\n result.add_edge([source, target])\n elif side == \"twosided\":\n result.add_edge([source, target, (label, side_label)])\n else:\n result.add_edge([source, target, label])", "def add_edge(self, v1, v2):\n\n (x1, y1) = v1\n (x2, y2) = v2\n\n if not self.has_vertex(x1, y1) or not self.has_vertex(x2, y2): return\n if v1 not in self.get_neighbors(x2, y2): return\n\n self._reachable[v1].add(v2)\n self._reachable[v2].add(v1)", "def add_edge(i, j):\n if (i, j) in edges or (j, i) in edges:\n # Si ya esta agregado en la lista no agrega nada\n return\n edges.add( (i, j) )\n edge_points.append(points[ [i, j] ])", "def add_edge(self, v1, v2):\n if v1 in self.vertices and v2 in self.vertices:\n self.vertices[v1].add(v2)\n else:\n raise IndexError('nonexistent vertex/node')", "def add_edge(self, v1, v2):\n if v1 in self.vertices and v2 in self.vertices:\n self.vertices[v1].add(v2)\n else:\n print(\"ERROR ADDING EDGE: Vrtes not found\")", "def add_edge(self, v1, v2):\n if v1 in self.vertices and v2 in self.vertices:\n self.vertices[v1].edges.add(v2)\n self.vertices[v2].edges.add(v1)\n else:\n raise IndexError(\"That vertex does not exist!\")", "def add_edge(self, v1, v2):\n if v1 in self.vertices and v2 in self.vertices:\n self.vertices[v1].add(v2)\n else:\n raise IndexError(\"That vertex does not exist!\")", "def add_directed_edge(self, v1, v2):\n if v1 in self.vertices:\n self.vertices[v1].edges.add(v2)\n else:\n raise IndexError(\"That vertex does not exist!\")", "def add_edge(self, v1, v2):\n # First we check to see if the vertices we're trying to connect exist\n if v1 in self.vertices and v2 in self.vertices:\n # If they do exist, we add v2 as a neighbor to v1\n self.vertices[v1].add(v2)\n else:\n # If v1 or v2 does not exist, we raise an error\n raise IndexError(\"Vertex does not exist\")", "def add_edge(self, v1, v2):\n if v1 in self.vertices and v2 in self.vertices:\n self.vertices[v1].add(v2)\n else:\n raise IndexError('That vertex does not exist')", "def add_Edge(self, node1, node2, weight=1):\n if node1 and node2 in self._adjacency_list:\n self._adjacency_list[node1].append(Edge(node2, weight))", "def e(src, dst):\n edge = pydot.Edge(src, dst)\n graph.add_edge(edge)", "def add_edge(self, vertex1, vertex2):\n\n vertex1.add_outgoing_node(vertex2)\n vertex2.add_incoming_node(vertex1)", "def add_edge(self, v1, v2):\n # add the 2nd node to the list of edges for the first node\n if v1 in self.vertices and v2 in self.vertices:\n\n self.vertices[v1].add(v2)", "def addEdge(self, vertex1, vertex2):\n self.addVertex(vertex1) \n self.addVertex(vertex2)\n\n if vertex2 not in self.adjList[vertex1]:\n self.adjList[vertex1].append(vertex2)", "def add_edge(self, v1, v2):\n # TODO\n\n # add directed edges\n self.vertices[v1].add(v2)\n # self.vertices[v2].add(v1)", "def add_edge(self, v1, v2):\n # Check if they exist\n # if v1 in self.vertices and v2 in self.vertices:\n if v1 in self.vertices:\n # Add the edge\n self.vertices[v1].add(v2)\n else:\n print(f\"ERROR ADDING EDGE between {v1} and {v2} : Vertex not found\")", "def add_edge(self, v1, v2):\n if v2 in self.vertices:\n self.vertices[v1].add(v2)\n else:\n raise ValueError(f\"The second Vertices you provided: {v2} is not in the graph. You can't link to a vertices that isn't in the graph.\")", "def add_edge_between(self, a: tuple, b: tuple):\n if a not in self.graph:\n self.graph[a] = set()\n if b not in self.graph:\n self.graph[b] = set()\n self.graph[a].add(b)\n self.graph[b].add(a)", "def add_edge(self, e, k):\n assert len(self.e2k) == self.VEK[1] - 1\n assert len(self.k2e) == self.VEK[1] - 1\n v1, v2 = self.grid[1:, k]\n assert self.components[v1] != self.components[v2]\n self.k2e[k] = e\n self.e2k[e] = k\n self.neighbors[v1].add(v2)\n self.neighbors[v2].add(v1)\n self.components[:] = False\n assert len(self.e2k) == self.VEK[1]\n assert len(self.k2e) == self.VEK[1]", "def ConnectByEdge(self, edge, arrow=False):\n return self.Connect(edge.node1.index, edge.node2.index,arrow, edge.weight)", "def add_edge(self, v1, v2):\n if v1 in self.vertices and v2 in self.vertices: self.vertices[v1].add(v2)\n else: raise IndexError(\"Nonexistant Vert.\")", "def add_edge(self, e):\n a, b = e\n self[a][b] = e\n self[b][a] = e", "def add_edge(self, weight, attributes, first_incident_node, second_incident_node):\n # if the first incident node is not in the nodeset\n if first_incident_node.get_name() not in self.get_node_names():\n self.add_node(first_incident_node) # add the first incident node\n\n # if the second incident node is not in the nodeset\n if second_incident_node.get_name() not in self.get_node_names():\n self.add_node(second_incident_node) # add the second incident node\n\n edge = Edge(weight, attributes, first_incident_node, second_incident_node) # create the Edge object\n\n first_incident_node.add_incident_edge(edge) # connect the first and second incident nodes using the edge\n second_incident_node.add_incident_edge(edge)\n\n self.__check_validity() # check if graph is valid - throws exception if not\n\n return edge # return the newly added edge", "def add_edge(self, id1: int, id2: int, weight: float) -> bool:\n\n if id1 not in self.nodes or id2 not in self.nodes or weight<0 or id1==id2:\n return False\n try:\n self.edges_out[id1][id2]\n return False\n except:\n e = Edge(id1, id2, weight)\n self.edges_out[id1].update({id2: e})\n self.edges_in[id2].update({id1: e})\n self.edges_on_graph += 1\n self.mode_changes += 1\n self.get_nodes(id1).out_e += 1\n self.get_nodes(id2).in_e += 1\n return True", "def addEdge(this, a, b):\n if not a in this.m:\n this.m[a]=set()\n this.m[a].add(b)" ]
[ "0.5999846", "0.59856063", "0.5815487", "0.57965994", "0.57955956", "0.57671285", "0.57221603", "0.5625872", "0.5615395", "0.5603937", "0.5591767", "0.55876136", "0.5574401", "0.55651414", "0.5539157", "0.55012083", "0.54722184", "0.5467264", "0.5466253", "0.5464435", "0.54572535", "0.5445389", "0.54451305", "0.54435647", "0.54218185", "0.5410571", "0.5404114", "0.5399681", "0.5391063", "0.53888047" ]
0.750268
0
Removes the hovered Elements from the graph.
def delete_element(self, event: matplotlib.backend_bases.LocationEvent) \ -> None: log.info(f'Removing Element(s) @ {event.x} - {event.y}') graph = self._get_connected_graph(event.inaxes) to_remove = {x for x in self.elements if x.contains(event)[0]} log.info(f'Elements to remove are {to_remove}') for element in to_remove: graph.remove(self.graph_to_figure.inverse[element][0]) self._redraw_graph()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def on_unhover(self) -> None:", "def unisolvent_nodes(self):\r\n pass", "def disconnect_nodes(self):\n for src_id, trg_id in itertools.product(self.selected_nodes, repeat=2):\n if src_id != trg_id:\n # `discard` ignores non-existing elements (unlike `remove`)\n app.edges[src_id].discard(trg_id)\n self.mark_as_unsaved()\n self.update()", "def clear_elements(self):\n\n pass", "def prune_unlinked(self):\n linked_ids = set()\n for (link_from, link_to, link_style, link_tail) in self.links:\n linked_ids.add(link_from)\n linked_ids.add(link_to)\n nodes_to_delete = []\n for name, node in self.nodes.items():\n if node.node_id not in linked_ids:\n nodes_to_delete.append(name)\n for name in nodes_to_delete:\n del self.nodes[name]", "def _removeUnusedElements(self, element):\n self.log(\"element:%r\" % element)\n for pad in element.src_pads():\n if pad.is_linked():\n peer = pad.get_peer().get_parent()\n self._removeUnusedElements(peer)\n if not peer in self._validelements:\n self.log(\"removing %s\" % peer.get_name())\n pad.unlink(pad.get_peer())\n peer.set_state(gst.STATE_NULL)\n self.remove(peer)", "def discard(self):\r\n self.pushes.pop()", "def clean_edges(self):", "def drop_unattached(self):\n for x in range(self.size):\n for y in range(self.size):\n coords = (x, y)\n if self.is_cell_unattached(coords):\n self.drop([coords])", "def cleanGraph(self,graph):\n i=0\n while i+1<len(graph):\n if self.getDistance(graph[i],graph[i+1])==0:\n del graph[i+1]\n else:\n i+=1\n return graph", "def clear(self):\r\n ElementSet.clear(self)\r\n self.update()", "def clear_crossfilter2(self):\n print ('Trigger clear')\n self.query_dict = {}\n self.plot_data = None\n self.create_figure_new()\n layout_doc.children[4].children[1] = self.p", "def onChartRemoveSeries(self):\n self.chart().removeAllSeries()\n self.series = {}\n self.yaxis = {}\n self.pen = {}\n self.ymin = {}\n self.ymax = {}", "def remove_old_graphs(self):\r\n widgets = self.winfo_children()\r\n graph_frames = []\r\n\r\n for widget in widgets:\r\n if type(widget) == tk.Frame:\r\n graph_frames.append(widget)\r\n\r\n for frame in range(len(graph_frames) - 1):\r\n graph_frames[frame].destroy()", "def clearMouseSelection(self):\n pass", "def resetSelectionArea(self):\n for legend in self._selectionAreas:\n self.plot.remove(legend, kind='item')\n self._selectionAreas = set()", "def clear(self):\n while len(self.nodes) > 0:\n self.nodes[0].remove()\n\n self.has_been_modified = False", "def _onRemove(self, event):\n index = self.colorlist.GetSelection()\n del self.graphColors[index]\n self._tupleListToStrings()\n if len(self.graphColors) > 0:\n self.colorlist.SetSelection(0)\n self._updateButtons(None)", "def clear_crossfilter1(self):\n print ('Trigger clear')\n self.query_dict = {}\n self.plot_data = None\n self.create_figure_new()\n layout_doc.children[4].children[0] = self.p", "def deleteAllNeedlesFromScene(self):\n #productive #onButton\n profprint()\n while slicer.util.getNodes('python-catch-round_'+str(self.round)+'*') != {}:\n nodes = slicer.util.getNodes('python-catch-round_'+str(self.round)+'*')\n for node in nodes.values():\n slicer.mrmlScene.RemoveNode(node)", "def clear(self):\n self._plt.clear()\n self._layer_items = {}", "def remove(self, board):\n for c in board.copy():\n while self in c:\n index = tuple(c.inputs.values()).index(self)\n key = tuple(c.inputs.keys())[index]\n c.inputs[key] = None\n # fixes possible memory leak\n self.inputs = {k: None for k, v in self.inputs.items()}", "def mouse_out(self):\n pass", "def destroy(self):\n\t\tfor team in range(len(self.dots)): #will cycle through each team\n\t\t\tfor i in range(len(self.dots[team])): #will cycle through each member of the team\n\t\t\t\tdot = self.dots[team][i]\n\t\t\t\tdot.removeNode()\n\t\tself.mousePosition.removeNode()\n\t\tself.mapimage.removeNode()\n\t\tself.map.removeNode()", "def remove_nodes(self, properties, **kwargs):\r\n\t\traise NotImplementedError", "def _clear_drawing(self) -> None:\n self.vertices.clear()\n self.edges.clear()\n self.subplot.clear()\n self.selected_element = None\n self.pressed_elements.clear()", "def clearReplacedElements(self):\n return _libsbml.CompSBasePlugin_clearReplacedElements(self)", "def clear(self):\n self.pointscontroller.pop(self.currentlyadded)", "def _pair_based_graph_cut(self, graph):\n for node in self._find_paired_nodes(graph):\n graph.remove_node(node)\n return", "def clear(self):\n self._plots[:] = []" ]
[ "0.69784325", "0.6411747", "0.6281012", "0.61337537", "0.6083778", "0.60492814", "0.59661543", "0.5953363", "0.5932168", "0.58861417", "0.586513", "0.5794916", "0.57807744", "0.57794785", "0.57381606", "0.57132536", "0.57085484", "0.57056797", "0.57054806", "0.5690846", "0.56832284", "0.56516683", "0.56362224", "0.562074", "0.56106734", "0.56083566", "0.5602356", "0.5581874", "0.5557953", "0.5554825" ]
0.64425635
1
Display a window that allows for editing of an elements attributes.
def open_attr_editing(self, element) -> None: if self.attr_editing_window is not None: self.close_attr_editing() else: position = wx.GetMousePosition() self.attr_editing_window = AttributeEditingFrame(self, wx.ID_ANY, position=position, element=element) figure_element = self.graph_to_figure[element] figure_element.annotation = self.annotate_element(figure_element)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def open_attr_req_editing(self, element) -> None:\n if self.attr_req_editing_window is not None:\n self.close_attr_editing()\n else:\n position = wx.GetMousePosition()\n self.attr_req_editing_window = AttributeRequirementEditingFrame(\n self, wx.ID_ANY,\n position=position,\n element=element,\n attr_requirements=self.attr_requirements\n )", "def show(self, window):\r\n\r\n return", "def show(self):\n self.wid.show()", "def open_attr_req_editing(self, element) -> None:\n pass", "def showSettings(self):\n self.c.show()", "def showBasic(self):\n self.setWindowIcon(QIcon(self.icon))\n self.setWindowTitle(self.title)\n self.setGeometry(*self.posXY, *self.windowSize)\n self.show()", "def show_file_attributes(self,type_info='dataset'):\n dialog=QtWidgets.QDialog()\n vlayout=QtWidgets.QVBoxLayout()\n tree = ParameterTree()\n tree.setMinimumWidth(400)\n tree.setMinimumHeight(500)\n if type_info=='scan':\n tree.setParameters(self.scan_attributes, showTop=False)\n elif type_info=='dataset':\n tree.setParameters(self.dataset_attributes, showTop=False)\n\n\n vlayout.addWidget(tree)\n dialog.setLayout(vlayout)\n buttonBox = QtWidgets.QDialogButtonBox(parent=dialog)\n buttonBox.addButton('Cancel', buttonBox.RejectRole)\n buttonBox.addButton('Apply', buttonBox.AcceptRole)\n buttonBox.rejected.connect(dialog.reject)\n buttonBox.accepted.connect(dialog.accept)\n\n vlayout.addWidget(buttonBox)\n dialog.setWindowTitle('Fill in information about this {}'.format(type_info))\n res=dialog.exec()\n return res", "def show(self):\n\n self.serial = self.parent.board.serial\n self.deiconify() # Show window\n self.visible = True\n\n self.input_entry.focus()\n\n self.start_repl()", "def show(self):\n # * displays the window, after using either the iconify or the withdraw methods\n self.wm_deiconify()\n # * this method can be called after the event which needs to happen before the window event\n self.wait_window()", "def mouseDoubleClickEvent(self, e):\n self.win = items.edit.Edit(self)\n self.win.setModal(True)\n self.win.show()", "def createCameraAttributeBrowser(container, camSerial):\n nb = ttk.Notebook(container)\n nb.grid(row=0)\n tooltipLabel = ttk.Label(container, text=\"temp\")\n tooltipLabel.grid(row=1)\n\n attributes = getAllCamerasAttribute(camSerial=camSerial);\n widgets = createAttributeBrowserNode(attributes, nb, tooltipLabel, 1)", "def showUI(cls):\r\n win = cls()\r\n win.create()\r\n return win", "def showKey():\n\tnewWindow=topWindow(window)\n\t#Config Context Bar\n\tnewWindow.context.removePlaceholder(0)\n\t#Context commands\n\tnewWindow.context.updateContextButton(0,command=lambda n=newWindow: n.grab_release())\n\tnewWindow.context.updateContextButton(1,command=lambda n=newWindow: n.destroy())\n\t#Add Table\n\tnewTable=table(newWindow,\"Pod Templates\",False)\n\tnewTable.pack(fill=BOTH,expand=True)\n\t#Add the content to the table\n\tfor t in podTemplate.templateColours:\n\t\trowName=t+\" colour:\"\n\t\trowColour=podTemplate.templateColours[t]\n\t\tnewTable.addRow(rowName,t,rowColour)\n\n\tnewWindow.run()", "def inicialUI(self):\r\n\r\n self.setGeometry(500, 500, 500, 500)\r\n self.setWindownTitle(\"Pesquisa\")\r\n self.displayWidgets()\r\n\r\n self.show()", "def show_window(self):\n self.show()", "def iniciaUI(self):\n\n self.setGeometry(100,100, 300, 200)\n self.setWindowTitle(\"Formulario\")\n self.displayWidgets()\n\n self.show()", "def seq_display_settings(self):\n # Open a new window for setting the restriction enzymes\n\n self.seq_display_setupwin=Toplevel()\n self.seq_display_setupwin.geometry('+300+450')\n self.seq_display_setupwin.title('Sequence Display Setup')\n\n # Spacing between bases\n row=1\n lblspace=Label(self.seq_display_setupwin,text='Bases Spacing:')\n lblspace.grid(row=row,column=0,padx=3,pady=2)\n bscaleentry=Scale(self.seq_display_setupwin,from_=8,to=20,resolution=1,orient='horizontal',\n relief='ridge',variable=self.base_scale,label='scale factor')\n bscaleentry.grid(row=row,column=1, sticky='wens', padx=3,pady=2)\n row=2\n lblfont=Label(self.seq_display_setupwin,text='Seq Font:')\n lblfont.grid(row=row,column=0,padx=3,pady=2)\n fontentry_button=Menubutton(self.seq_display_setupwin,textvariable=self.seqfont,\n\t\t\t\t\trelief=RAISED,width=16)\n restr_fontentry_button=Menubutton(self.seq_display_setupwin,textvariable=self.restr_font,\n\t\t\t\t\trelief=RAISED,width=16)\n fontentry_menu=Menu(fontentry_button,tearoff=0)\n restr_fontentry_menu=Menu(restr_fontentry_button,tearoff=0)\n fontentry_button['menu']=fontentry_menu\n restr_fontentry_button['menu']=restr_fontentry_menu\n\n # Other fonts available\n fts=['Arial','Courier','Verdana','Fixed','Times']\n for text in fts:\n #text='Font '+text\n fontentry_menu.add_radiobutton(label=text,\n variable=self.seqfont,\n value=text,\n indicatoron=1)\n restr_fontentry_menu.add_radiobutton(label=text,\n variable=self.restr_font,\n value=text,\n indicatoron=1)\n fontentry_button.grid(row=row,column=1, sticky='nes', padx=3,pady=2)\n\n row=3\n lblfontsize=Label(self.seq_display_setupwin,text='Sequence Font Size:')\n lblfontsize.grid(row=row,column=0,padx=3,pady=2)\n fontsizeentry=Scale(self.seq_display_setupwin,from_=8,to=20,resolution=1,orient='horizontal',\n relief='ridge',variable=self.seqfontsize)\n\n fontsizeentry.grid(row=row,column=1, sticky='wens',padx=3,pady=2)\n row=4\n frame = Frame(self.seq_display_setupwin)\n fontstyle_label = Label(frame, text='Font Style:')\n fontstyle_label.grid(row=0,column=0)\n fontstyle = Radiobutton(frame, text=\"plain\", variable=self.fontstyle, value=0)\n fontstyle1 = Radiobutton(frame, text=\"bold\", variable=self.fontstyle, value=1)\n fontstyle2 = Radiobutton(frame, text=\"italic\", variable=self.fontstyle, value=2)\n fontstyle.grid(row=0,column=1)\n fontstyle1.grid(row=0,column=2)\n fontstyle2.grid(row=0,column=3)\n frame.grid(row=row,column=0,columnspan=2,sticky='news', padx=3,pady=2)\n\n row=5\n self.backgrcolorbutton = Button(self.seq_display_setupwin, text='background color',\n bg=self.backgrcolor.get(),\n command=self.setbackgrcolor)\n self.backgrcolorbutton.grid(row=row,column=1, sticky='nes', padx=3,pady=2)\n row=6\n restrfont=Label(self.seq_display_setupwin,text='Restr. Site Font:')\n restrfont.grid(row=row,column=0,padx=3,pady=2)\n restr_fontentry_button.grid(row=row,column=1, sticky='nes', padx=3,pady=2)\n row=7\n\n # Apply Button\n b = Button(self.seq_display_setupwin, text=\"Apply Settings\", command=self.update_window_formatting)\n b.grid(row=row,column=1,sticky='wens',padx=4,pady=4)\n\n # Close button\n c=Button(self.seq_display_setupwin,text='Close',command=self.close_seq_display_setupwin)\n c.grid(row=row,column=0,sticky='wens',padx=4,pady=4)\n\n # Save Settings button\n row=8\n c=Button(self.seq_display_setupwin,text='Save as Default',command=self.save_preferences)\n c.grid(row=row,column=0,columnspan=2,sticky='wens',padx=4,pady=4)\n return", "def __editShowCodeInfo(self):\n self.showEditorInfo(self.activeWindow())", "def show(self):\n self.Show()", "def XPShowWidget(inWidget):\n pass", "def showEditorWindow(parent, title, allowEditting = True):\n frame = wx.Frame(parent, -1, title, size=(630, 320), style = wx.DEFAULT_FRAME_STYLE)\n panel = RichTextPanel(allowEditting, frame, -1)\n #frame.Fit()\n #frame.SetMinSize(frame.GetSize())\n frame.Show()\n return panel", "def display_window(self):\n frame = tk.Frame(master=self.param_window)\n frame.grid(padx=10, pady=20, columnspan=2)\n tk.Label(master=frame, text=\"Enter simulation parameters\").pack()\n\n self.status_text = tk.StringVar()\n self.status_text.set(\"Status message\")\n \n self.rows = 1\n for input_key in self.inputs.keys():\n input_dict = self.inputs[input_key]\n \n frame = tk.Frame(master=self.param_window)\n frame.grid(row=self.rows, column=0, padx=10, pady=1)\n input_dict['label'] = tk.Label(master=frame, text=input_dict['label'])\n input_dict['label'].pack()\n\n frame = tk.Frame(master=self.param_window)\n frame.grid(row=self.rows, column=1, padx=10, pady=1)\n input_dict['entry'] = tk.Entry(master=frame, width=10)\n input_dict['entry'].insert(0, input_dict['default'])\n input_dict['entry'].pack()\n \n self.rows += 1\n\n frame = tk.Frame(master=self.param_window)\n frame.grid(padx=10, pady=20, columnspan = 2)\n self.submit_btn = tk.Button(master=frame, text=\"Submit\", width=10)\n self.submit_btn.pack()\n self.submit_btn.bind(\"<Button-1>\", self.submit_values)\n\n self.param_window.mainloop()\n return self.parameters", "def show(self,window):\n self.showFunctions(window)", "def showUI(cls):\r\n win = cls(uiFile)\r\n win.create()\r\n return win", "def abrir_demo(self, widget, data=None):\n\t\tself.w3.hide()\n\t\tself.w5.show_all()", "def widgets(self):\r\n self.setWindowTitle(\"PyCrypt\")\r\n self.setMinimumSize(QSize(500, 500))\r\n self.setMaximumSize(QSize(500, 500))\r\n# Adding the sub def for widgets etc\r\n self.add_menus_and_status()\r\n self.add_buttons()", "def display_dialog(txt_plantuml):\n\n class EditDialog(DialogPlantUmlText):\n # Custom dialog built via wxformbuilder - subclass it first, to hook up event handlers\n def OnClassNameEnter(self, event):\n self.EndModal(wx.ID_OK)\n\n # change cwd so that dialog can find the 'pro' image jpg which is relative to dialogs/\n # when deployed via pyinstaller, this path is a bit tricky to find, so use this func.\n dir = dialog_path_pyinstaller_push(frame = self)\n try:\n dialog = EditDialog(None)\n dialog.txt_plantuml.Value = txt_plantuml\n dialog.txt_plantuml.SetFocus()\n dialog.txt_plantuml.Enable(not unregistered)\n dialog.ShowModal()\n # dialog.Show()\n dialog.Destroy()\n finally:\n dialog_path_pyinstaller_pop()", "def show(self):\r\n self.wf.Show()", "def UpdateDisplay(self):\n ##Jconf\n self.chJconf.Clear()\n for name in self.state.GetSurface(\"JconfDict\").GetNames():\n self.chJconf.Append(name)\n self.chJconf.SetStringSelection(self.state.GetSurface(\"JconfSelection\"))\n self.chJconf.Enable(self.state.IsEnabled(\"JconfDict\") == True and\n self.state.IsEnabled(\"JconfSelection\") == True and\n self.state.GetSurface(\"Xplorer\") == True)\n self.bEditJconf.Enable(self.state.IsEnabled(\"JconfDict\") and\n self.state.GetSurface(\"Xplorer\") == True)\n ##Name Server\n self.cbNameServer.SetValue(self.state.GetSurface(\"NameServer\"))\n self.cbNameServer.Enable(self.state.IsEnabled(\"NameServer\"))\n ##Conductor\n self.cbConductor.SetValue(self.state.GetSurface(\"Conductor\"))\n self.cbConductor.Enable(self.state.IsEnabled(\"Conductor\"))\n ##Xplorer\n self.cbXplorer.SetValue(self.state.GetSurface(\"Xplorer\"))\n self.cbXplorer.Enable(self.state.IsEnabled(\"Xplorer\"))\n ##Desktop Mode\n self.cbDesktop.SetValue(self.state.GetSurface(\"DesktopMode\"))\n self.cbDesktop.Enable(self.state.IsEnabled(\"DesktopMode\"))\n ##Xplorer Type\n if self.state.GetSurface(\"DesktopMode\"):\n self.rbXplorer.SetSelection(0)\n else:\n if (self.state.GetSurface(\"XplorerType\") == \"OSG-VEP\"):\n self.rbXplorer.SetSelection(0)\n else:\n self.rbXplorer.SetSelection(1)\n self.rbXplorer.Enable(self.state.IsEnabled(\"XplorerType\") == True and\n self.state.GetSurface(\"DesktopMode\") == False and\n self.state.GetSurface(\"Xplorer\") == True)\n ##Cluster Node button\n self.bCluster.Enable(CLUSTER_ENABLED and\n self.state.GetSurface(\"Xplorer\") == True and\n self.state.GetSurface(\"DesktopMode\") == False and\n self.state.GetSurface(\"XplorerType\") == \"OSG-VEPC\")\n return", "def show_gui():\n pass" ]
[ "0.6659311", "0.6169691", "0.59491926", "0.58992946", "0.58726037", "0.5852599", "0.5716457", "0.5696189", "0.5662377", "0.5640791", "0.56367207", "0.5632048", "0.5631164", "0.5622477", "0.5620895", "0.56067353", "0.5592529", "0.55700505", "0.5557119", "0.5548776", "0.5534905", "0.551958", "0.5510207", "0.5503337", "0.54592323", "0.54584044", "0.5453407", "0.54333127", "0.54322314", "0.5428922" ]
0.6958823
0
Closes an opened element attribute editing window.
def close_attr_editing(self) -> None: self.attr_editing_window.Close() self.attr_editing_window = None
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def close_attr_req_editing(self) -> None:\n self.attr_req_editing_window.Close()\n self.attr_req_editing_window = None", "def close_attr_req_editing(self) -> None:\n pass", "def open_attr_editing(self, element) -> None:\n if self.attr_editing_window is not None:\n self.close_attr_editing()\n else:\n position = wx.GetMousePosition()\n self.attr_editing_window = AttributeEditingFrame(self, wx.ID_ANY,\n position=position,\n element=element)\n figure_element = self.graph_to_figure[element]\n figure_element.annotation = self.annotate_element(figure_element)", "def open_attr_req_editing(self, element) -> None:\n if self.attr_req_editing_window is not None:\n self.close_attr_editing()\n else:\n position = wx.GetMousePosition()\n self.attr_req_editing_window = AttributeRequirementEditingFrame(\n self, wx.ID_ANY,\n position=position,\n element=element,\n attr_requirements=self.attr_requirements\n )", "def open_attr_req_editing(self, element) -> None:\n pass", "def Close(self, *args, **kwargs):\n self._save_attrs()\n super().Close(*args, **kwargs)", "def Close(self, *args, **kwargs):\n self._save_attrs()\n super().Close(*args, **kwargs)", "def close(event):\n event.widget.destroy()", "def close(self):\n self.parent.activate()", "def close_pop_up_windows(self):\n self.button_click(self.DECLINE_BUTTON)\n self.button_click(self.CLOSE_POPUP_BUTTON)", "def close(self):\n closeI1Display()", "def closing(self, cancelable=False):\r\n filenames = []\r\n for editortabwidget in self.editortabwidgets:\r\n filenames += [finfo.filename for finfo in editortabwidget.data]\r\n CONF.set(self.ID, 'filenames', filenames)\r\n CONF.set(self.ID, 'current_filename', self.get_current_filename())\r\n CONF.set(self.ID, 'recent_files', self.recent_files)\r\n is_ok = True\r\n for editortabwidget in self.editortabwidgets:\r\n is_ok = is_ok and editortabwidget.save_if_changed(cancelable)\r\n if not is_ok and cancelable:\r\n break\r\n return is_ok", "def close(self):\n\n\t\tself._window.close()", "def __window_close(self):\n pass", "def close(self):\n self._command = \"close\"", "def close(self):\n self._close_viewer_window()\n self.env.close()", "def close_apply_keyword_modal(self):\n self._basket.close_apply_keyword_modal()", "def close(self, *obj):\n self._save_size()\n self.clean_up()\n self.uistate.gwm.close_track(self.track)\n self.opened = False\n self.parent_window.present()", "def mouseDoubleClickEvent(self, e):\n self.win = items.edit.Edit(self)\n self.win.setModal(True)\n self.win.show()", "def close(self):\n\n self.driver.close_window(self.handle)", "def close_modal(self):\n locator = lex_locators[\"modal\"][\"close\"]\n self._jsclick(locator)", "def close_details_window(self, instance: Union[Nobleman, Location]):\n self.manager.prepare_to_save(instance)\n self.unregister_extra_window(instance)", "def closeWindow(self):\n cmdId = self.executeCommand(Command.CLOSE)\n return cmdId", "def close_launcher(self):\n self.misc.go_to_win(self.misc.bufwinnr(self.name))\n if self.misc.bufname() == self.name:\n vim.command('bd')\n self.misc.go_to_win(self.misc.bufwinnr(self.curr_buf.number))\n if self.nohidden_set:\n vim.command(\"set nohidden\")\n self.reset_launcher()", "def close_column(self):\n\n self._close_layouting_element(\"Column\")", "def closeConfiguration(self):\n self.parent.closeDresser()", "def _close_window(self):\n render_window = self._iren.GetRenderWindow()\n render_window.Finalize()\n self._iren.TerminateApp()\n\n del render_window, self._iren, self._ren, self._renWin", "def close(self):\n self.is_open = False", "def closeDisplay(j):\n displayMessage(j, \"j.CloseDisplay(%s)\" % j.id)\n j.CloseDisplay(j.id)", "def close(self):\n self._isOpen = False" ]
[ "0.7997215", "0.7141961", "0.6551061", "0.6231262", "0.59630466", "0.5795215", "0.5795215", "0.5771843", "0.56921726", "0.5654888", "0.5469147", "0.5466623", "0.5452029", "0.5451822", "0.5445185", "0.5425771", "0.541461", "0.5413825", "0.5386832", "0.53592354", "0.53446835", "0.53284556", "0.5320063", "0.5268221", "0.52472657", "0.5210568", "0.520116", "0.51921254", "0.5187592", "0.5168884" ]
0.8355211
0
Test if an event is inside the axes of this Panel.
def event_in_axes(self, event: matplotlib.backend_bases.LocationEvent) \ -> bool: return event.inaxes == self.subplot
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def axes_enabled(self):\n if hasattr(self, 'axes_widget'):\n return bool(self.axes_widget.GetEnabled())\n return False", "def _check_axes(axes):\n _check_type(axes, (Axes, np.ndarray), \"axes\")\n if isinstance(axes, np.ndarray):\n if axes.ndim == 1:\n for ax in axes:\n _check_type(ax, (Axes,))\n assert hasattr(ax, \"plot\") # sanity-check\n elif axes.ndim == 2:\n for i, j in product(range(axes.shape[0]), range(axes.shape[1])):\n _check_type(axes[i, j], (Axes,))\n assert hasattr(axes[i, j], \"plot\") # sanity-check\n else:\n raise ValueError(\n \"Argument 'axes' should be a matplotib axes or a \"\n \"1D or 2D numpy array of matplotlib axes.\"\n )\n else:\n # sanity-check\n assert hasattr(axes, \"plot\")\n return axes", "def hasAxisUnits(self, unit):\n return self.__axis_units__.__contains__(unit)", "def is_wcsaxes(axes):\n return isinstance(axes, wcsaxes.WCSAxes)", "def axes_contains(ax, obj_list):\n # Get plot elements\n elems = ax.get_children()\n\n # Loop over list of objects that should be in the plot\n contains_all = False\n for obj in obj_list:\n objtype, num_expected = obj\n num = 0\n for elem in elems:\n if isinstance(elem, objtype): num += 1\n if num != num_expected:\n return False\n\n # Return True if no problems found\n return True", "def isscalar(self):\n return not self.axes", "def is_within_phase_space(self, events: np.ndarray) -> Tuple[bool]:\n raise NotImplementedError", "def _validate_axes(self):\n if not (\n np.abs(self.axis_u.dot(self.axis_v) < 1e-6)\n and np.abs(self.axis_v.dot(self.axis_w) < 1e-6)\n and np.abs(self.axis_w.dot(self.axis_u) < 1e-6)\n ):\n raise ValueError(\"axis_u, axis_v, and axis_w must be orthogonal\")\n return True", "def _inside(self, x, y):\n wx, wy, w, h = self._raw_graph_window_dim()\n if wx <= x < wx + w and wy <= y < wy + h:\n return True\n return False", "def joy_axis_x_right(event: EventType, widget: WidgetType) -> bool:\n return event.axis == JOY_AXIS_X and event.value > JOY_DEADZONE", "def isEvent(*args):\n return _libsbml.SBO_isEvent(*args)", "def joy_axis_x_left(event: EventType, widget: WidgetType) -> bool:\n return event.axis == JOY_AXIS_X and event.value < -JOY_DEADZONE", "def is_robot_in_canvas(self, robot):\n return robot in self.__robots", "def IsMouseWellOutsideWindow(self):\r\n \r\n screen_rect = self.GetScreenRect() \r\n screen_rect.Inflate(50, 50)\r\n \r\n return not screen_rect.Contains(wx.GetMousePosition())", "def is_event(self):\n return self._is_name_type(self.EVENT)", "def match_axis_command(self, c, axes):\n if len(axes) == 0 or not 'axes' in self.command_list[c] or len(self.command_list[c]['axes']) == 0 or \\\n len(axes) <= max(int(cmd_axis) for cmd_axis, value in self.command_list[c]['axes'].items()):\n return False\n\n # We know there are enough axes that we *might* match. Iterate through\n # each of the incoming axes, and if they are totally pressed (1.0),\n # we have a match and should run the command.\n for cmd_axis, value in self.command_list[c]['axes'].items():\n if axes[int(cmd_axis)] == value:\n return True\n\n return False", "def on_press(self, event):\n if event.inaxes is None:\n return\n mX = event.xdata\n mY = event.ydata\n index = None\n for i in range(len(self.x)):\n if self.is_inside(mX, mY, (self.x[i], self.y[i])):\n index = i\n break\n self.current_point = index", "def SBO_isEvent(*args):\n return _libsbml.SBO_isEvent(*args)", "def isOver(self, pos):\n # Pos is the mouse position or a tuple of (x,y) coordinates\n if self.x < pos[0] < self.x + self.width:\n if self.y < pos[1] < self.y + self.height:\n return True\n return False", "def axes(self):\n return self._axes", "def axes(self):\n return self._axes", "def axes(self) -> np.ndarray: # array[Axes]\n return self._axes", "def is_inside(self, x: int, y: int) -> bool:\n pass", "def particle_is_inside(self, particle):\n return self.in_box_bounds(particle.position)", "def check_inside(self, pos):\n x,y = pos\n return x >= self.posx and x <= self.posx + self.sizex and y >= self.posy and y <= self.posy + self.sizey", "def is_event_annotated(self, name):\n return name in self._annotations.keys()", "def sceneEvent(self, QEvent): # real signature unknown; restored from __doc__\n return False", "def isOnCanvas(self, x, y):\n return 0 <= x < self.width and 0 <= y < self.height", "def isInside(self, point):\n # we rotate back the point to the frame parallel to the axis of the ellipse\n rotatedPoint = self.rotatePoint(point)\n # we check if each point is inside the associated liquid drop\n return ((rotatedPoint[:, :, 0]/self.axisA[:, None])**2 + (rotatedPoint[:, :, 1]/self.axisB[:, None])**2 < 1)", "def check_edges(self):\n screen_rect = self.screen.get_rect()\n if self.rect.right >= screen_rect.right or self.rect.left <= 0:\n return True" ]
[ "0.671091", "0.6208423", "0.6156233", "0.61335844", "0.60991186", "0.6088695", "0.60207427", "0.57926714", "0.57722473", "0.5760292", "0.57368016", "0.5726686", "0.562051", "0.56115305", "0.5580775", "0.5571055", "0.5563919", "0.5550448", "0.5470026", "0.5459179", "0.5459179", "0.545872", "0.54339653", "0.54317594", "0.5409415", "0.5376751", "0.5366775", "0.535909", "0.5356901", "0.53543615" ]
0.8854843
0
Clears the current drawing and dicts/lists referencing the drawn elements.
def _clear_drawing(self) -> None: self.vertices.clear() self.edges.clear() self.subplot.clear() self.subplot2.clear()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _clear_drawing(self) -> None:\n self.vertices.clear()\n self.edges.clear()\n self.subplot.clear()\n self.selected_element = None\n self.pressed_elements.clear()", "def _clear(self):\n self._fillitem = self._fillpath = None\n for item in self.items:\n self.screen._delete(item)\n self.currentLineItem = self.screen._createline()\n self.currentLine = []\n if self._drawing:\n self.currentLine.append(self._position)\n self.items = [self.currentLineItem]\n self.clearstamps()", "def clear_selected_shapes(self):\n self.shapes_to_draw = []", "def clear(self):\n for i in range(len(self.canvas)):\n self.canvas[i] = 0", "def clear(self):\n self._plt.clear()\n self._layer_items = {}", "def clear_canvas():\n self.parent_class.canvas.delete(\"all\")", "def clear(self):\n try:\n # This causes stupid errors with tkagg, so just wrap it in\n # try-except for now\n self.fig.clear()\n except: pass\n self.annotators.clear()\n self.dims.clear()\n self.ph.remove(self.ID)", "def clear(self):\n self._x_prev = None\n self._y_prev = None", "def clear(self):\n self.canvas = [[self.style] * self.cols for _ in range(self.lines)]", "def clear_visualization(self) -> None:\n if self._drawing_handle is not None:\n sim.simAddDrawingObjectItem(self._drawing_handle, None)", "def clearCanvas():\n global c, coordinates\n c.delete(\"all\")\n drawMusicLines()\n coordinates.clear()", "def clear(self):\n self._grid = [[None]]", "def clear(self):\n self.animation.stop()\n self.draw(0, 0, 0, 0, 0)", "def clear(self):\n self._frame.clear()\n self._turtles = []\n self._gpens = []", "def clear(self):\n if self.flag == 0:\n for coord in INDICES:\n self.kill(coord)\n self.chart[coord] = DEAD", "def clear(self):\n self.clear_markers()\n self.l_marker.remove()\n self.l_line.remove()\n self.r_marker.remove()\n self.r_line.remove()", "def clear_drawn_objects(self, view_manager):\n view = view_manager.get_view()\n for item in self._drawnObjects:\n view.removeItem(item)\n # clear the list:\n self._drawnObjects = []", "def clear(self):\n self.raster_path_line.clear()\n self.labels_path.clear()\n self.shapefile_path.clear()\n self.costumelabels.clear()\n self.layer_name.clear()\n self.class_name.clear()\n self.idfield.clear()", "def clear(self):\n black = neo.Color(0,0,0)\n self.set_all(black)\n self.draw()", "def clear(self):\n for key in self.__columns:\n self.__widths[key] = 0\n self.__data = []\n self.__selectedRow = -1\n self.__formatString = \"\"\n self._window.clear()\n self.drawBorder()", "def clear(self):\n lines = self._lines\n image, bkg_image = self.image, self._image\n for line in lines: line.clear(image, bkg_image) #prej bkg_img\n self._cursor = 0", "def clear(self):\n self._plots[:] = []", "def clear(self):\r\n\t\tself.grid.fill(False)", "def undraw(self):\n \n if not self.canvas: return\n if not self.canvas.isClosed():\n #self.canvas.delete(self.id)\n _tkExec(self.canvas.delete, self.id)\n if self.canvas.autoflush:\n #_root.update()\n _tkCall(_root.update)\n pass\n self.canvas = None\n self.id = None", "def clear(self):\n self._delayvalue = _CFG[\"delay\"]\n self._colormode = _CFG[\"colormode\"]\n self._delete(\"all\")\n self._bgpic = self._createimage(\"\")\n self._bgpicname = \"nopic\"\n self._tracing = 1\n self._updatecounter = 0\n self._turtles = []\n self.bgcolor(\"white\")\n for btn in 1, 2, 3:\n self.onclick(None, btn)\n self.onkeypress(None)\n for key in self._keys[:]:\n self.onkey(None, key)\n self.onkeypress(None, key)\n Myturtle._pen = None", "def clear(self):\r\n\r\n # Clear the widgets list\r\n self.widgets_list = []\r\n\r\n # Refresh the scroll area\r\n self._refresh()", "def clear(self):\n self._turtle.clear()", "def clear(self):\n self._turtle.clear()", "def clear_geometries(self):", "def _clear(self, event):\n if self.ignore(event) or self._changed_canvas():\n return\n self._background = self.canvas.copy_from_bbox(self.ax.bbox)\n self.ax.draw_artist(self._buttons)\n if hasattr(self, \"_circles\"):\n for circle in self._circles:\n self.ax.draw_artist(circle)" ]
[ "0.8798906", "0.79316634", "0.7764828", "0.76532316", "0.7638401", "0.75774086", "0.7515265", "0.7456398", "0.74527353", "0.742205", "0.7401441", "0.7380618", "0.7338083", "0.7337927", "0.73297036", "0.729089", "0.72666776", "0.72562766", "0.7228562", "0.72144085", "0.72106487", "0.717251", "0.7171161", "0.7165129", "0.71584547", "0.7157541", "0.71261865", "0.71261865", "0.7105422", "0.7086848" ]
0.82706034
1
Redraw the currently loaded graphs.
def _redraw_graph(self) -> None: self._clear_drawing() self.draw_graph(graph=self.graph, axes=self.subplot) self.draw_graph(graph=self.graph2, axes=self.subplot2) self.draw_mappings(self.mapping)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _redraw_graph(self) -> None:\n self._clear_drawing()\n self.draw_graph()", "def redraw_figures(self):\n pass", "def redraw_figures(self):\n pass", "def plot_refresh():\n figure.canvas.draw()", "def _update_current_graph(self, **kwargs):\n\n self.current_graph.redraw()", "def redraw(self, **kwargs):\n #src_dict = self.data_sources\n #self.remove_sources(src_dict.keys())\n self.renderers = {}\n #self.renderers = {}\n self.figure = self.draw_figure(**kwargs)\n #self.add_sources(src_dict)\n # todo does the old figure linger on?\n self.render_sources(self.data_sources)\n self.bk_pane.object = self.figure", "def redraw(self):\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)\n for shape in self.shapes:\n shape.redraw()\n glFlush()\n self.SwapBuffers()", "def redraw(self):\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)\n for shape in self.shapes:\n shape.redraw()\n glFlush()\n self.SwapBuffers()", "def redraw(self) -> None:\n self.canvas.draw_idle()\n self.Refresh()", "def update_plot():\n pass", "def redraw(self):\n dummy_figure = plt.figure()\n new_manager = dummy_figure.canvas.manager\n new_manager.canvas.figure = self.figure\n self.figure.set_canvas(new_manager.canvas)\n plt.show(block=False)", "def refresh_all(self):\n\t\t\n\t\tself.symbolsList.set_datasource(self.source)\n\t\tself.symbolsList.refresh()\n\t\t\n\t\tself.plotFrame.set_datasource(self.source)\n\t\tself.plotFrame.refresh()", "def refresh(self):\n\n self.ax.relim()\n self.ax.autoscale_view()\n self.canvas.draw()", "def redraw(self):\n self._create()", "def update_figure(self):\n\n self.draw()", "def redraw(self):\n raise NotImplementedError()", "def refresh_plot(self):\n self.ax.relim() # recompute the data limits\n self.ax.autoscale_view() # automatic axis scaling\n self.fig.canvas.flush_events()", "def redraw(self):\n x2, y2 = [[] for i in range(len(self.x))], \\\n [[] for i in range(len(self.x))]\n game_point = [random.randint(1, 100),\n random.randint(1, 100)]\n for i in range(self.generations):\n x2, y2, game_point = self.move(x2, y2, game_point)\n for i in range(10): # Czyszczenie starych wykresow\n self.plots[i].set_xdata([])\n self.plots[i].set_ydata([])\n self.plots2[i].set_xdata([])\n self.plots2[i].set_ydata([])\n for i in range(len(self.x)): # Nowe dane wykresow\n self.plots[i].set_xdata(self.x[i])\n self.plots[i].set_ydata(self.y[i])\n self.plots2[i].set_xdata(x2[i])\n self.plots2[i].set_ydata(y2[i])\n self.fig.canvas.draw_idle()", "def refresh_svg_canvas(self):\n if self.ui.tabWidget.currentIndex() == 0:\n self.ui.svg_canvas.build_schematic()\n self.ui.svg_canvas.viewport().update()\n elif self.ui.tabWidget.currentIndex() in (1,2):\n self.ui.svg_canvas.build_pcb()\n self.ui.svg_canvas.viewport().update()\n else:\n raise Exception(\"Unknown view to draw\")", "def update_visualization(self) -> None:\n pass", "def refresh(self):\n\n # Set Graphics scene\n self.setScene(QtGui.QGraphicsScene())\n self._connections = set()\n self._nodes = {}\n self._selection = set()\n self._manipulation_mode = 0\n self._selection_rect = None", "def update_graph(self):\n if self.update_callback:\n self.update_callback()", "def redraw(self):\r\n self.c.update()", "def redraw(self):\n self.vispy_viewer.canvas.update()", "def redraw(self):\n self.vispy_widget.canvas.update()", "def redraw_viz():\n\tglobal g_last_draw\n\tif (rospy.Time.now().to_sec() > (refresh_rate + g_last_draw)):\n\t\tg_last_draw = rospy.Time.now().to_sec()\n\t\t# redraw imu box\n\t\tdoDraw()", "def updatePlot(self):\n self.axes.clear()\n self.axes.plot(self.data[0], self.data[1], linestyle='-', color='blue')\n self.axes.plot(self.data[0], self.data[2], linestyle='-', color='red')\n self.axes.plot(self.data[0], self.data[3], linestyle='-', color='gray')\n self.canvas.draw()", "def updatePlot(self):\n self.axes.clear()\n self.axes.plot(self.data[0], self.data[1], linestyle='-', color='gray')\n self.axes.plot(self.data[0], self.data[2], linestyle='-', color='blue')\n self.axes.plot(self.data[0], self.data[3], linestyle='-', color='darkgreen')\n self.canvas.draw()", "def updatePlot(self):\n self.axes.clear()\n self.axes.plot(self.data[0], self.data[1], linestyle='-', color='gray')\n self.axes.plot(self.data[0], self.data[2], linestyle='-', color='blue')\n self.axes.plot(self.data[0], self.data[3], linestyle='-', color='darkgreen')\n self.canvas.draw()", "def updatePlot(self):\n self.axes.clear()\n self.axes.plot(self.data[0], self.data[1], linestyle='-', color='gray')\n self.axes.plot(self.data[0], self.data[2], linestyle='-', color='blue')\n self.axes.plot(self.data[0], self.data[3], linestyle='-', color='darkgreen')\n self.canvas.draw()" ]
[ "0.812659", "0.7936349", "0.7936349", "0.77163017", "0.75561", "0.73383135", "0.70364344", "0.70364344", "0.703126", "0.69579417", "0.69479334", "0.69155383", "0.6909802", "0.69051296", "0.6891078", "0.6877941", "0.68396044", "0.6830217", "0.68077636", "0.6800429", "0.6766062", "0.67487735", "0.67232317", "0.66879165", "0.6674979", "0.66714215", "0.66587114", "0.66524833", "0.66524833", "0.66524833" ]
0.8057434
1
Display a window that allows for editing the requirements of attributes of a specific element.
def open_attr_req_editing(self, element) -> None: if self.attr_req_editing_window is not None: self.close_attr_editing() else: position = wx.GetMousePosition() self.attr_req_editing_window = AttributeRequirementEditingFrame( self, wx.ID_ANY, position=position, element=element, attr_requirements=self.attr_requirements )
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def open_attr_editing(self, element) -> None:\n if self.attr_editing_window is not None:\n self.close_attr_editing()\n else:\n position = wx.GetMousePosition()\n self.attr_editing_window = AttributeEditingFrame(self, wx.ID_ANY,\n position=position,\n element=element)\n figure_element = self.graph_to_figure[element]\n figure_element.annotation = self.annotate_element(figure_element)", "def open_attr_req_editing(self, element) -> None:\n pass", "def show_file_attributes(self,type_info='dataset'):\n dialog=QtWidgets.QDialog()\n vlayout=QtWidgets.QVBoxLayout()\n tree = ParameterTree()\n tree.setMinimumWidth(400)\n tree.setMinimumHeight(500)\n if type_info=='scan':\n tree.setParameters(self.scan_attributes, showTop=False)\n elif type_info=='dataset':\n tree.setParameters(self.dataset_attributes, showTop=False)\n\n\n vlayout.addWidget(tree)\n dialog.setLayout(vlayout)\n buttonBox = QtWidgets.QDialogButtonBox(parent=dialog)\n buttonBox.addButton('Cancel', buttonBox.RejectRole)\n buttonBox.addButton('Apply', buttonBox.AcceptRole)\n buttonBox.rejected.connect(dialog.reject)\n buttonBox.accepted.connect(dialog.accept)\n\n vlayout.addWidget(buttonBox)\n dialog.setWindowTitle('Fill in information about this {}'.format(type_info))\n res=dialog.exec()\n return res", "def seq_display_settings(self):\n # Open a new window for setting the restriction enzymes\n\n self.seq_display_setupwin=Toplevel()\n self.seq_display_setupwin.geometry('+300+450')\n self.seq_display_setupwin.title('Sequence Display Setup')\n\n # Spacing between bases\n row=1\n lblspace=Label(self.seq_display_setupwin,text='Bases Spacing:')\n lblspace.grid(row=row,column=0,padx=3,pady=2)\n bscaleentry=Scale(self.seq_display_setupwin,from_=8,to=20,resolution=1,orient='horizontal',\n relief='ridge',variable=self.base_scale,label='scale factor')\n bscaleentry.grid(row=row,column=1, sticky='wens', padx=3,pady=2)\n row=2\n lblfont=Label(self.seq_display_setupwin,text='Seq Font:')\n lblfont.grid(row=row,column=0,padx=3,pady=2)\n fontentry_button=Menubutton(self.seq_display_setupwin,textvariable=self.seqfont,\n\t\t\t\t\trelief=RAISED,width=16)\n restr_fontentry_button=Menubutton(self.seq_display_setupwin,textvariable=self.restr_font,\n\t\t\t\t\trelief=RAISED,width=16)\n fontentry_menu=Menu(fontentry_button,tearoff=0)\n restr_fontentry_menu=Menu(restr_fontentry_button,tearoff=0)\n fontentry_button['menu']=fontentry_menu\n restr_fontentry_button['menu']=restr_fontentry_menu\n\n # Other fonts available\n fts=['Arial','Courier','Verdana','Fixed','Times']\n for text in fts:\n #text='Font '+text\n fontentry_menu.add_radiobutton(label=text,\n variable=self.seqfont,\n value=text,\n indicatoron=1)\n restr_fontentry_menu.add_radiobutton(label=text,\n variable=self.restr_font,\n value=text,\n indicatoron=1)\n fontentry_button.grid(row=row,column=1, sticky='nes', padx=3,pady=2)\n\n row=3\n lblfontsize=Label(self.seq_display_setupwin,text='Sequence Font Size:')\n lblfontsize.grid(row=row,column=0,padx=3,pady=2)\n fontsizeentry=Scale(self.seq_display_setupwin,from_=8,to=20,resolution=1,orient='horizontal',\n relief='ridge',variable=self.seqfontsize)\n\n fontsizeentry.grid(row=row,column=1, sticky='wens',padx=3,pady=2)\n row=4\n frame = Frame(self.seq_display_setupwin)\n fontstyle_label = Label(frame, text='Font Style:')\n fontstyle_label.grid(row=0,column=0)\n fontstyle = Radiobutton(frame, text=\"plain\", variable=self.fontstyle, value=0)\n fontstyle1 = Radiobutton(frame, text=\"bold\", variable=self.fontstyle, value=1)\n fontstyle2 = Radiobutton(frame, text=\"italic\", variable=self.fontstyle, value=2)\n fontstyle.grid(row=0,column=1)\n fontstyle1.grid(row=0,column=2)\n fontstyle2.grid(row=0,column=3)\n frame.grid(row=row,column=0,columnspan=2,sticky='news', padx=3,pady=2)\n\n row=5\n self.backgrcolorbutton = Button(self.seq_display_setupwin, text='background color',\n bg=self.backgrcolor.get(),\n command=self.setbackgrcolor)\n self.backgrcolorbutton.grid(row=row,column=1, sticky='nes', padx=3,pady=2)\n row=6\n restrfont=Label(self.seq_display_setupwin,text='Restr. Site Font:')\n restrfont.grid(row=row,column=0,padx=3,pady=2)\n restr_fontentry_button.grid(row=row,column=1, sticky='nes', padx=3,pady=2)\n row=7\n\n # Apply Button\n b = Button(self.seq_display_setupwin, text=\"Apply Settings\", command=self.update_window_formatting)\n b.grid(row=row,column=1,sticky='wens',padx=4,pady=4)\n\n # Close button\n c=Button(self.seq_display_setupwin,text='Close',command=self.close_seq_display_setupwin)\n c.grid(row=row,column=0,sticky='wens',padx=4,pady=4)\n\n # Save Settings button\n row=8\n c=Button(self.seq_display_setupwin,text='Save as Default',command=self.save_preferences)\n c.grid(row=row,column=0,columnspan=2,sticky='wens',padx=4,pady=4)\n return", "def show(self, window):\r\n\r\n return", "def display_dialog(txt_plantuml):\n\n class EditDialog(DialogPlantUmlText):\n # Custom dialog built via wxformbuilder - subclass it first, to hook up event handlers\n def OnClassNameEnter(self, event):\n self.EndModal(wx.ID_OK)\n\n # change cwd so that dialog can find the 'pro' image jpg which is relative to dialogs/\n # when deployed via pyinstaller, this path is a bit tricky to find, so use this func.\n dir = dialog_path_pyinstaller_push(frame = self)\n try:\n dialog = EditDialog(None)\n dialog.txt_plantuml.Value = txt_plantuml\n dialog.txt_plantuml.SetFocus()\n dialog.txt_plantuml.Enable(not unregistered)\n dialog.ShowModal()\n # dialog.Show()\n dialog.Destroy()\n finally:\n dialog_path_pyinstaller_pop()", "def show(self):\n # * displays the window, after using either the iconify or the withdraw methods\n self.wm_deiconify()\n # * this method can be called after the event which needs to happen before the window event\n self.wait_window()", "def show(self):\n self.wid.show()", "def optionsWindow():\n\t# create the main interface\n\tif cmds.window(kSetupOptionsWindow, q=True, ex=True):\n\t\tcmds.deleteUI(kSetupOptionsWindow)\n\tmainWindow = cmds.window(kSetupOptionsWindow, title='%s Options'%kToolName, menuBar=True, wh=(545,350))\n\t\n\t# build the menu bar\n\tcmds.menu(label='Help')\n\tamui.helpMenuItem(kToolName, __file__)\n\tamui.aboutMenuItem(kToolName, kVersionNumber, kVersionDate)\n\t\n\tmainForm = cmds.formLayout(nd=100)\n\t\n\t# build the section to get information about the new twist joints\n\tif_suffixName = cmds.textFieldGrp(text='_Twist', label='Suffix of New Twist Joints:')\n\tif_numberTwistJoints = cmds.intSliderGrp(v=3, min=1, max=10, fmn=1, fmx=100, label='Number of Twist Joints:', field=True)\n\t\n\t# position the input fields for the twist joints\n\tcmds.formLayout(mainForm, edit=True, attachForm=[(if_suffixName, 'left', 30), (if_suffixName, 'top', 5)], attachNone=[(if_suffixName, 'right'), (if_suffixName, 'bottom')])\n\tcmds.formLayout(mainForm, edit=True, attachForm=[(if_numberTwistJoints, 'left', 30)], attachNone=[(if_numberTwistJoints, 'right'), (if_numberTwistJoints, 'bottom')], attachControl=[(if_numberTwistJoints, 'top', 5, if_suffixName)])\n\t\n\t# build the section to get information for the hip constraint\n\tconstraintFrame = eval('cmds.frameLayout(collapsable=True, label=\"Hip Constraint Options:\" %s)'%amui.__frameAlignCenter__)\n\tconstraintForm = cmds.formLayout(nd=100)\n\t\n\t# attempt to guess what the pelvis is if there is a selection when the GUI is created\n\tpelvisText = 'CenterRoot'\n\tsel = cmds.ls(sl=True, l=True, type='transform')\n\tif sel and len(sel) > 0: # BUG: in Maya 8.5, a selection of length 0 returns None rather than an empty list\n\t\ttry:\n\t\t\thip = cmds.listRelatives(sel[0], p=True, f=True) # just use the first knee in the selection\n\t\t\tpelvis = cmds.listRelatives(hip[0], p=True, f=True)\n\t\t\tpelvisText = pelvis[0]\n\t\texcept: pass\n\t\t\n\tif_pelvis = cmds.textFieldGrp(label='Pelvis Object:', tx=pelvisText)\n\tif_hipAimAxis = cmds.floatFieldGrp(v1=1, v2=0, v3=0, nf=3, pre=4, label='Hip Aim Axis:')\n\tif_hipFrontAxis = cmds.floatFieldGrp(v1=0, v2=0, v3=1, nf=3, pre=4, label='Hip Front Axis:')\n\tif_pelvisAimAxis = cmds.floatFieldGrp(v1=0, v2=1, v3=0, nf=3, pre=4, label='Pelvis Aim Axis:')\n\tif_pelvisFrontAxis = cmds.floatFieldGrp(v1=0, v2=0, v3=1, nf=3, pre=4, label='Pelvis Front Axis:')\n\t\n\t# position the input fields for the hip constraint\n\tcmds.formLayout(constraintForm, edit=True, attachForm=[(if_pelvis, 'left', 30), (if_pelvis, 'top', 5)], attachNone=[(if_pelvis, 'right'), (if_pelvis, 'bottom')])\n\tcmds.formLayout(constraintForm, edit=True, attachForm=[(if_hipAimAxis, 'left', 30)], attachNone=[(if_hipAimAxis, 'right'), (if_hipAimAxis, 'bottom')], attachControl=[(if_hipAimAxis, 'top', 5, if_pelvis)])\n\tcmds.formLayout(constraintForm, edit=True, attachForm=[(if_hipFrontAxis, 'left', 30)], attachNone=[(if_hipFrontAxis, 'right'), (if_hipFrontAxis, 'bottom')], attachControl=[(if_hipFrontAxis, 'top', 5, if_hipAimAxis)])\n\tcmds.formLayout(constraintForm, edit=True, attachForm=[(if_pelvisAimAxis, 'left', 30)], attachNone=[(if_pelvisAimAxis, 'right'), (if_pelvisAimAxis, 'bottom')], attachControl=[(if_pelvisAimAxis, 'top', 5, if_hipFrontAxis)])\n\tcmds.formLayout(constraintForm, edit=True, attachForm=[(if_pelvisFrontAxis, 'left', 30)], attachNone=[(if_pelvisFrontAxis, 'right'), (if_pelvisFrontAxis, 'bottom')], attachControl=[(if_pelvisFrontAxis, 'top', 5, if_pelvisAimAxis)])\n\t\n\tcmds.setParent('..') # go up to constraintForm\n\tcmds.setParent('..') # go up to mainForm\n\t\n\t# position the frame for the hip constraint\n\tcmds.formLayout(mainForm, edit=True, attachPosition=[(constraintFrame, 'left', -1, 0), (constraintFrame, 'right', -1, 100)], attachControl=[(constraintFrame, 'top', 5, if_numberTwistJoints)], attachNone=[(constraintFrame, 'bottom')])\n\t\n\t# create the buttons to execute the script\n\tcmd_create='amTools.rigging.hipSetup.doOptions (\"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\", \"%s\")'%(\n\t\tif_suffixName, \n\t\tif_numberTwistJoints, \n\t\tif_pelvis, \n\t\tif_hipAimAxis, \n\t\tif_hipFrontAxis, \n\t\tif_pelvisAimAxis, \n\t\tif_pelvisFrontAxis)\n\tutils.ui.threeButtonLayout(mainForm, mainWindow, cmd_create)\n\t\n\tcmds.showWindow(mainWindow)", "def showBasic(self):\n self.setWindowIcon(QIcon(self.icon))\n self.setWindowTitle(self.title)\n self.setGeometry(*self.posXY, *self.windowSize)\n self.show()", "def show_popup(self, view, docstring, location=None):", "def showKey():\n\tnewWindow=topWindow(window)\n\t#Config Context Bar\n\tnewWindow.context.removePlaceholder(0)\n\t#Context commands\n\tnewWindow.context.updateContextButton(0,command=lambda n=newWindow: n.grab_release())\n\tnewWindow.context.updateContextButton(1,command=lambda n=newWindow: n.destroy())\n\t#Add Table\n\tnewTable=table(newWindow,\"Pod Templates\",False)\n\tnewTable.pack(fill=BOTH,expand=True)\n\t#Add the content to the table\n\tfor t in podTemplate.templateColours:\n\t\trowName=t+\" colour:\"\n\t\trowColour=podTemplate.templateColours[t]\n\t\tnewTable.addRow(rowName,t,rowColour)\n\n\tnewWindow.run()", "def mouseDoubleClickEvent(self, e):\n self.win = items.edit.Edit(self)\n self.win.setModal(True)\n self.win.show()", "def toolPropertyWindow(*args, field: Union[AnyStr, bool]=\"\", helpButton: Union[AnyStr, bool]=\"\",\n icon: Union[AnyStr, bool]=\"\", inMainWindow: bool=True, location:\n Union[AnyStr, bool]=\"\", noviceMode: bool=True, resetButton: Union[AnyStr,\n bool]=\"\", restore: bool=True, selectCommand: Union[AnyStr, bool]=\"\",\n showCommand: Union[AnyStr, bool]=\"\", q=True, query=True, e=True,\n edit=True, **kwargs)->Union[None, Any]:\n pass", "def showSettings(self):\n self.c.show()", "def launchHelpWindow(self):\r\n self.popup(\"Help\",HELP,geom=\"350x200\")", "def display_window(self):\n frame = tk.Frame(master=self.param_window)\n frame.grid(padx=10, pady=20, columnspan=2)\n tk.Label(master=frame, text=\"Enter simulation parameters\").pack()\n\n self.status_text = tk.StringVar()\n self.status_text.set(\"Status message\")\n \n self.rows = 1\n for input_key in self.inputs.keys():\n input_dict = self.inputs[input_key]\n \n frame = tk.Frame(master=self.param_window)\n frame.grid(row=self.rows, column=0, padx=10, pady=1)\n input_dict['label'] = tk.Label(master=frame, text=input_dict['label'])\n input_dict['label'].pack()\n\n frame = tk.Frame(master=self.param_window)\n frame.grid(row=self.rows, column=1, padx=10, pady=1)\n input_dict['entry'] = tk.Entry(master=frame, width=10)\n input_dict['entry'].insert(0, input_dict['default'])\n input_dict['entry'].pack()\n \n self.rows += 1\n\n frame = tk.Frame(master=self.param_window)\n frame.grid(padx=10, pady=20, columnspan = 2)\n self.submit_btn = tk.Button(master=frame, text=\"Submit\", width=10)\n self.submit_btn.pack()\n self.submit_btn.bind(\"<Button-1>\", self.submit_values)\n\n self.param_window.mainloop()\n return self.parameters", "def adv_new_window(self):\n adv=workflow.advancedoptions_w.ADialog()\n adv.exec_()", "def XPShowWidget(inWidget):\n pass", "def menu_design_a_gui_with_wxglade(self, event=None):\n self.parentPanel.design_a_gui_with_wxglade()", "def showUI(cls):\r\n win = cls()\r\n win.create()\r\n return win", "def showAboutDialog(self, event):\r\n info = wx.adv.AboutDialogInfo()\r\n info.SetName(\"Square Crop\")\r\n info.SetVersion(\"0.0.1\")\r\n info.SetDevelopers([\"Tianyi (Tiger) Cao\"])\r\n info.SetDescription(\"A program to crop a picture into a square.\")\r\n\r\n wx.adv.AboutBox(info)", "def widgets(self):\r\n self.setWindowTitle(\"PyCrypt\")\r\n self.setMinimumSize(QSize(500, 500))\r\n self.setMaximumSize(QSize(500, 500))\r\n# Adding the sub def for widgets etc\r\n self.add_menus_and_status()\r\n self.add_buttons()", "def UpdateDisplay(self):\n ##Jconf\n self.chJconf.Clear()\n for name in self.state.GetSurface(\"JconfDict\").GetNames():\n self.chJconf.Append(name)\n self.chJconf.SetStringSelection(self.state.GetSurface(\"JconfSelection\"))\n self.chJconf.Enable(self.state.IsEnabled(\"JconfDict\") == True and\n self.state.IsEnabled(\"JconfSelection\") == True and\n self.state.GetSurface(\"Xplorer\") == True)\n self.bEditJconf.Enable(self.state.IsEnabled(\"JconfDict\") and\n self.state.GetSurface(\"Xplorer\") == True)\n ##Name Server\n self.cbNameServer.SetValue(self.state.GetSurface(\"NameServer\"))\n self.cbNameServer.Enable(self.state.IsEnabled(\"NameServer\"))\n ##Conductor\n self.cbConductor.SetValue(self.state.GetSurface(\"Conductor\"))\n self.cbConductor.Enable(self.state.IsEnabled(\"Conductor\"))\n ##Xplorer\n self.cbXplorer.SetValue(self.state.GetSurface(\"Xplorer\"))\n self.cbXplorer.Enable(self.state.IsEnabled(\"Xplorer\"))\n ##Desktop Mode\n self.cbDesktop.SetValue(self.state.GetSurface(\"DesktopMode\"))\n self.cbDesktop.Enable(self.state.IsEnabled(\"DesktopMode\"))\n ##Xplorer Type\n if self.state.GetSurface(\"DesktopMode\"):\n self.rbXplorer.SetSelection(0)\n else:\n if (self.state.GetSurface(\"XplorerType\") == \"OSG-VEP\"):\n self.rbXplorer.SetSelection(0)\n else:\n self.rbXplorer.SetSelection(1)\n self.rbXplorer.Enable(self.state.IsEnabled(\"XplorerType\") == True and\n self.state.GetSurface(\"DesktopMode\") == False and\n self.state.GetSurface(\"Xplorer\") == True)\n ##Cluster Node button\n self.bCluster.Enable(CLUSTER_ENABLED and\n self.state.GetSurface(\"Xplorer\") == True and\n self.state.GetSurface(\"DesktopMode\") == False and\n self.state.GetSurface(\"XplorerType\") == \"OSG-VEPC\")\n return", "def show_popup(self, data):\r\n store = get_store()\r\n self.ids.inlayout.rows = 1\r\n self.ids.inlayout.add_widget(CEToolBoxLabel(text=add_color(\"Viscosity :\", \"FFFFFF\")))\r\n value = round(store.get('Viscosity')[\"value\"], 2)\r\n viscotext = str(value)+\" \"+store.get('Viscosity')[\"unit\"]\r\n self.ids.inlayout.add_widget(CEToolBoxLabel(text=add_color(viscotext, \"FFFFFF\")))\r\n self.open()", "def show():\n dialog = SkinIODialog(getMayaWindow())\n dialog.show()", "def showASGattributesDialog( self, atom3i ):\r\n \r\n # No ASG? Ehhhh\r\n if( len( self.__trackASG ) == 0 ): \r\n return\r\n \r\n # One ASG, show dialog\r\n elif( len( self.__trackASG ) == 1 ): \r\n ASG, typeList = self.__trackASG.values()[0] #<--get the first & only value\r\n ATOM3TypeDialog(atom3i, ASG )\r\n \r\n # Many ASG's\r\n else:\r\n stringList = [] \r\n for ASGname in self.__trackASG.keys():\r\n stringList.append( ASGname )\r\n stringList.append( 'Cancel' )\r\n \r\n title = 'Meta Attributes'\r\n text = 'Edit attributes of meta-model...'\r\n default = 0\r\n response = Dialog.Dialog(atom3i.parent, \r\n {'title': title, 'text': text, 'bitmap': '',\r\n 'default': default, 'strings': stringList}).num\r\n if( response >= len(stringList) -1 ): \r\n return\r\n else:\r\n ASGname = stringList[response]\r\n ATOM3TypeDialog(atom3i, self.__trackASG[ASGname][0] )", "def details_window(self, instance: Union[Nobleman, Location]):\n window = tk.Toplevel()\n window.title(instance.name)\n window.protocol(\"WM_DELETE_WINDOW\",\n partial(self.close_details_window, instance))\n self.register_extra_window(instance, window)\n self.generate_window_content(instance, window)", "def window(*args, width: int = 200, height: int = 200, autosize: bool = False,\n no_resize: bool = False, no_title_bar: bool = False, no_move: bool = False, no_scrollbar: bool = False,\n no_collapse: bool = False, horizontal_scrollbar: bool = False, no_focus_on_appearing: bool = False,\n no_bring_to_front_on_focus: bool = False, menubar: bool = False, no_close: bool = False,\n no_background: bool = False, label: str = '', show: bool = True, collapsed: bool = False,\n modal: bool = False, popup: bool = False,\n on_close: Callable = None, min_size: List[int]=[32, 32], max_size: List[int] = [30000, 30000], id:str=''):\n try:\n\n widget = internal_dpg.add_window(*args, width=width, height=height, autosize=autosize,\n no_resize=no_resize, no_title_bar=no_title_bar, no_move=no_move,\n no_scrollbar=no_scrollbar, no_collapse=no_collapse,\n horizontal_scrollbar=horizontal_scrollbar,\n no_focus_on_appearing=no_focus_on_appearing,\n no_bring_to_front_on_focus=no_bring_to_front_on_focus,\n menubar=menubar, no_close=no_close,\n no_background=no_background, label=label, show=show, \n collapsed=collapsed, on_close=on_close,\n min_size=min_size, max_size=max_size, id=id, modal=modal,\n popup=popup)\n internal_dpg.push_container_stack(widget)\n yield widget\n\n finally:\n internal_dpg.pop_container_stack()", "def show_popup(self, data):\r\n store = get_store()\r\n self.ids.inlayout.rows = 1\r\n self.ids.inlayout.add_widget(CEToolBoxLabel(text=add_color(\"Conductivity :\", \"FFFFFF\")))\r\n value = round(store.get('Conductivity')[\"value\"], 2)\r\n conductivitytext = str(value)+\" \"+store.get('Conductivity')[\"unit\"]\r\n self.ids.inlayout.add_widget(CEToolBoxLabel(text=add_color(conductivitytext, \"FFFFFF\")))\r\n self.open()" ]
[ "0.68413615", "0.65508693", "0.5571642", "0.5496969", "0.54830647", "0.5474354", "0.53333175", "0.5329269", "0.5287009", "0.52479637", "0.52346814", "0.5229036", "0.5212956", "0.51698345", "0.51592696", "0.51546735", "0.5137302", "0.5124626", "0.5122872", "0.5102492", "0.50705034", "0.5046635", "0.50448084", "0.5033555", "0.50302213", "0.5028785", "0.50279605", "0.502361", "0.5022188", "0.50199866" ]
0.7490717
0
Closes an opened element attribute requirement editing window.
def close_attr_req_editing(self) -> None: self.attr_req_editing_window.Close() self.attr_req_editing_window = None
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def close_attr_editing(self) -> None:\n self.attr_editing_window.Close()\n self.attr_editing_window = None", "def close_attr_req_editing(self) -> None:\n pass", "def open_attr_req_editing(self, element) -> None:\n if self.attr_req_editing_window is not None:\n self.close_attr_editing()\n else:\n position = wx.GetMousePosition()\n self.attr_req_editing_window = AttributeRequirementEditingFrame(\n self, wx.ID_ANY,\n position=position,\n element=element,\n attr_requirements=self.attr_requirements\n )", "def open_attr_req_editing(self, element) -> None:\n pass", "def open_attr_editing(self, element) -> None:\n if self.attr_editing_window is not None:\n self.close_attr_editing()\n else:\n position = wx.GetMousePosition()\n self.attr_editing_window = AttributeEditingFrame(self, wx.ID_ANY,\n position=position,\n element=element)\n figure_element = self.graph_to_figure[element]\n figure_element.annotation = self.annotate_element(figure_element)", "def close(self):\n self.parent.activate()", "def close_apply_keyword_modal(self):\n self._basket.close_apply_keyword_modal()", "def close_pop_up_windows(self):\n self.button_click(self.DECLINE_BUTTON)\n self.button_click(self.CLOSE_POPUP_BUTTON)", "def close(event):\n event.widget.destroy()", "def Close(self, *args, **kwargs):\n self._save_attrs()\n super().Close(*args, **kwargs)", "def Close(self, *args, **kwargs):\n self._save_attrs()\n super().Close(*args, **kwargs)", "def close_modal(self):\n locator = lex_locators[\"modal\"][\"close\"]\n self._jsclick(locator)", "def _close(self, event):\n self.EndModal(wx.ID_OK)", "def close(self):\n\n\t\tself._window.close()", "def close(self, *obj):\n self._save_size()\n self.clean_up()\n self.uistate.gwm.close_track(self.track)\n self.opened = False\n self.parent_window.present()", "def close(self):\n\n self.driver.close_window(self.handle)", "def on_closed(self, event):\n # The closed signal is only emitted when the widget is closed\n # by the user, so there is no need for a loopback guard.\n self.declaration.visible = False\n self.declaration.closed()", "def close_column(self):\n\n self._close_layouting_element(\"Column\")", "def close(self):\n self._close_viewer_window()\n self.env.close()", "def __window_close(self):\n pass", "def close_row(self):\n self._close_layouting_element(\"Row\")", "def close(self):\n closeI1Display()", "def force_close(self):\n\n\t\tself._window.force_close()", "def close_UI(self):", "def mouseDoubleClickEvent(self, e):\n self.win = items.edit.Edit(self)\n self.win.setModal(True)\n self.win.show()", "def close(self):\n self.tl.withdraw()\n self.lumpy.quit()", "def _close_window(self):\n render_window = self._iren.GetRenderWindow()\n render_window.Finalize()\n self._iren.TerminateApp()\n\n del render_window, self._iren, self._ren, self._renWin", "def close(self):\n self._command = \"close\"", "def close_2(self):\n self.pop_up_amount.destroy()", "def CloseDynamicsI(self):\n self.__NcIO_dyn.CloseI()" ]
[ "0.79165214", "0.7444396", "0.68249637", "0.6152994", "0.6150109", "0.5953293", "0.5739249", "0.5689546", "0.5680209", "0.5583001", "0.5583001", "0.5564221", "0.5481616", "0.5457909", "0.5449019", "0.54295856", "0.54149216", "0.5407903", "0.5404366", "0.53568083", "0.52921045", "0.5291268", "0.5259707", "0.5257639", "0.5256655", "0.5248478", "0.5246475", "0.52461386", "0.5234292", "0.5206592" ]
0.8197979
0
Add a mapping between the two elements to the production.
def _add_mapping(self, mother_element: GraphElement, daughter_element: GraphElement) -> None: self.mapping[mother_element] = daughter_element
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _add_mapping(self, mother_element: GraphElement,\n daughter_element: GraphElement) -> None:\n pass", "def __add__(self, other: MapValue) -> MapValue:\n return ops.MapMerge(self, other).to_expr()", "def __radd__(self, other: MapValue) -> MapValue:\n return ops.MapMerge(self, other).to_expr()", "def applyMapping(self):\n pass", "def product_map(xs1, xs2):\n return jax.vmap(lambda x1: jax.vmap(lambda x2: pair_product(x1, x2))(xs2))(xs1)", "def Map(a, b):\n out = {}\n for key, value in a.items():\n if key in b:\n out[value] = b[key]\n return out", "def extend(self, mappings):\n if isinstance(mappings, self.__class__):\n mappings = mappings.maps\n for m in mappings:\n if self.mapper is not None:\n m = self.mapper(m)\n self.append(m)", "def addMapping(mapping):\n defaultMapping_.addMapping(mapping)", "def extend_map(self,\n other_map,\n overwrite_existing=False,\n extend_existing=False):\n self.taxon_seq_map.extend(other_map,\n overwrite_existing=overwrite_existing,\n extend_existing=extend_existing)\n self.update_taxon_set()", "def convert_mapping(self, mapping, comp1, comp2, var1, var2):\n model = self.model\n # Check for being already converted\n var_pair = frozenset([var1, var2])\n if var_pair in self._converted_mappings:\n DEBUG('units-converter', 'Skipping already converted mapping', var1, '<->', var2)\n return\n else:\n self._converted_mappings.add(var_pair)\n # Ensure mapping is var1 := var2; swap vars if needed\n swapped = False\n try:\n if var2.get_source_variable() is var1:\n swapped = True\n var1, var2 = var2, var1\n comp1, comp2 = comp2, comp1\n except TypeError:\n pass\n # Get units\n u1 = var1.get_units()\n u2 = var2.get_units()\n DEBUG('units-converter', \"Converting mapping of\", var1, \":=\", var2,\n \"(units:\", repr(u1), repr(u2), \")\")\n if not u1.equals(u2):\n # We need a conversion\n # Add a copy of var1 to comp1, with units as var2\n if getattr(var1, u'public_interface', '') == u'in':\n in_interface = u'public'\n else:\n in_interface = u'private'\n var1_converter = self.add_variable(comp1, var1.name + u'_converter', u2, interfaces={in_interface: u'in'})\n var1._cml_var_type = VarTypes.Computed\n var1._cml_source_var = None\n delattr(var1, in_interface + u'_interface')\n var1_converter._set_source_variable(var2)\n # Add assignment maths for var1 := var1_converter\n app = mathml_apply.create_new(model, u'eq', [var1.name, var1_converter.name])\n self.add_expr_to_comp(comp1, app)\n var1._cml_depends_on = [app]\n app._cml_assigns_to = var1\n # Update mapping to var1_converter := var2\n if swapped:\n mapping.variable_2 = var1_converter.name\n else:\n mapping.variable_1 = var1_converter.name\n # Fix usage counts - var1_converter is only used by app, and so var2 usage decreases\n var1_converter._used()\n for _ in xrange(var1.get_usage_count()):\n var2._decrement_usage_count()\n # Apply units conversion to the assignment\n self.convert_assignments([app])\n # Add the assignment into the sorted list\n assignments = model.get_assignments()\n idx = assignments.index(var1)\n assignments[idx:idx+1] = [var1_converter, app]", "def intercambiar(mapa, mapa2):\n for e in mapa.bloqueadas:\n mapa2.bloqueadas.append(e)", "def extend(primary: Mapping, *others: Mapping, in_place=False):\n others = flatten(others)\n if not in_place:\n primary = dict(primary or {})\n for other in others:\n if other is None:\n continue\n for key, value in other.items():\n primary[key] = value\n return primary", "def addMapping(self, baseType, refType):\n if not self.apiName(baseType) or not self.apiName(refType):\n self.logMsg('diag', 'ScriptOutputGenerator::addMapping: IGNORE map from', baseType, '<->', refType)\n return\n\n self.logMsg('diag', 'ScriptOutputGenerator::addMapping: map from',\n baseType, '<->', refType)\n\n if baseType not in self.mapDict:\n baseDict = {}\n self.mapDict[baseType] = baseDict\n else:\n baseDict = self.mapDict[baseType]\n if refType not in self.mapDict:\n refDict = {}\n self.mapDict[refType] = refDict\n else:\n refDict = self.mapDict[refType]\n\n baseDict[refType] = None\n refDict[baseType] = None", "def _do_mapping(self):\n pass", "def push(self, mapping):\n self.mappings.append(mapping)", "def add_prod(self, lhs, rhs):\n prods = rhs.split('|')\n for prod in prods:\n self.prod[lhs].append(tuple(prod.split()))", "def add_prod(self, lhs, rhs):\n prods = rhs.split('|')\n for prod in prods:\n self.prod[lhs].append(tuple(prod.split()))", "def put_map(self, elem_map):\n ierr = exolib.py_expmap(self.exoid, elem_map + self._o)\n if ierr:\n raise ExodusIIWriterError(\"Error putting element map\")", "def _declare_auto_variable_mapping(self):\n if self.name not in self.nlp.variable_mappings:\n self.nlp.variable_mappings[self.name] = BiMapping(\n range(len(self.name_elements)), range(len(self.name_elements))\n )", "def map2(inKey, inVal):\n return [([inKey[0]],inKey[1:]+inVal)]", "def add_descriptors(self, mapping):\n for key, desc in mapping.iteritems():\n self.descriptors[int(key, 16)] = desc", "def add_descriptors(self, mapping):\n for key, desc in mapping.iteritems():\n self.descriptors[int(key, 16)] = desc", "def draw_mappings(self, mapping: Mapping) -> None:\n for graph_element1, graph_element2 in mapping.items():\n figure_element1 = self.graph_to_figure[graph_element1]\n figure_element2 = self.graph_to_figure[graph_element2]\n p1, p2 = mapping_points_between_figure_elements(figure_element1,\n figure_element2)\n patch = ConnectionPatch(\n xyA=(p1.x, p1.y),\n xyB=(p2.x, p2.y),\n coordsA=\"data\",\n coordsB=\"data\",\n axesA=self.subplot,\n axesB=self.subplot2,\n arrowstyle=\"->\",\n clip_on=False,\n )\n figure_element1.mapping_left = patch\n figure_element2.mapping_right = patch\n self.mappings.add(patch)\n self.subplot.add_artist(patch)\n self.redraw()", "def mapping_for_switch(mapping):\n return {key[0]: value for key, value in mapping.items()}", "def edge_mapping(self):\n ...", "def _combine(mappings):\n return {k: v for d in mappings for k, v in d.items()}", "def alias(new_field, existing_field):\n mapping[new_field] = mapping[existing_field]", "def map(self, attr1, attr2):\n return dict(zip(getattr(self, attr1), getattr(self, attr2)))", "def map(self, attr1, attr2):\n return dict(zip(getattr(self, attr1), getattr(self, attr2)))", "def mapping(self, mapping):\n self.set_mapping(mapping)" ]
[ "0.7386965", "0.6301587", "0.608117", "0.6053467", "0.60229", "0.5890286", "0.587229", "0.58372045", "0.58208764", "0.5736256", "0.5708055", "0.56233305", "0.5622347", "0.5588315", "0.55871934", "0.55576986", "0.55576986", "0.5500496", "0.5489049", "0.5449521", "0.54427195", "0.54427195", "0.5427086", "0.54229593", "0.54149336", "0.5394763", "0.5378424", "0.53769654", "0.53769654", "0.53757966" ]
0.7042673
1
Adds an attribute requirement between the two specified elements.
def _add_attr_requirement(self, mother_element: GraphElement, daughter_element: GraphElement) -> None: if not daughter_element in self.attr_requirements: self.attr_requirements[daughter_element] = {} requirement_num = len(self.attr_requirements[daughter_element]) requirement_name = f'arg{requirement_num}' self.attr_requirements[daughter_element][requirement_name] = mother_element
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _add_attr_requirement(self, mother_element: GraphElement,\n daughter_element: GraphElement) -> None:", "def add_attr_requirement(self, event: Union[wx.CommandEvent, None],\n attr_req_label: str = '',\n attr_req_element: GraphElement = None) -> None:\n new_id = len(self.attr_req_ids)\n self.attr_req_ids[new_id] = attr_req_label\n button_remove = wx.Button(self, wx.ID_ANY, label='-')\n self.Bind(wx.EVT_BUTTON, partial(self.remove_attr, attr_id=new_id),\n button_remove)\n attr_req_label_ctrl = wx.TextCtrl(self, value=attr_req_label)\n attr_req_element_ctrl = wx.StaticText(self, label=str(attr_req_element))\n self.attr_req_labels[new_id] = attr_req_label_ctrl\n self.attr_req_elements[new_id] = attr_req_element_ctrl\n self.attr_req_buttons[new_id] = button_remove\n if event is not None:\n self._update_attr_list()", "def add_attribute(a, name, other):\n raise TypeError(\"can't add new attribute\")", "def add(element1, element2):\n \n newtag = Tag.addTags(element1.tag, element2.tag)\n \n #have to wrap the attributes in dict() to avoid a bus error\n newattribs = Attrib.addAttribs(dict(element1.attrib), dict(element2.attrib))\n \n element1.tag = newtag\n element1.text = Text.addText(element1.text, element2.text)\n element1.tail = Text.addText(element1.tail, element2.tail)\n \n for i in element1.attrib:\n del element1.attrib[i]\n for key in newattribs.keys():\n try:\n element1.set(key, newattribs[key])\n except TypeError:\n log = logging.getLogger()\n log.error('TypeError: %s' % str(sys.exc_info()[1]))\n log.error('key = %s\\tnewattribs[key] = %s' % (str(key), str(newattribs[key])))\n raise\n \n return element1", "def _load_attrs_requirements(self) -> None:\n if self.element not in self.attr_requirements:\n return\n self.attr_req_ids.clear()\n for attr_req_label, attr_req_value in \\\n self.attr_requirements[self.element].items():\n self.add_attr_requirement(None, attr_req_label, attr_req_value)\n self._update_attr_list()", "def _xml_requires(self, ele):\n ef = element('{http://linux.duke.edu/metadata/rpm}requires')\n used = 0\n\n for prco in sorted(self.requires):\n if prco.name.startswith('rpmlib('):\n continue\n\n # this drops out requires that the pkg provides for itself.\n if prco.name in [p.name for p in self.provides] or (prco.name.startswith('/') and (prco.name in [file.name for file in self.filelist])):\n if not prco.flags:\n continue\n else:\n if prco in self.provides:\n continue\n\n entry = element('{http://linux.duke.edu/metadata/rpm}entry', {'name': prco.name})\n if prco.str_flags:\n entry.set('flags', prco.str_flags)\n e, v, r = prco.version\n if e:\n entry.set('epoch', str(e))\n if v:\n entry.set('ver', v)\n if r:\n entry.set('rel', r)\n if prco.flags & 1600:\n entry.set('pre', '1')\n\n ef.append(entry)\n used += 1\n\n if used != 0:\n ele.append(ef)", "def addExpectedAttributes(self, *args):\n return _libsbml.MultiASTPlugin_addExpectedAttributes(self, *args)", "def addExpectedAttributes(self, *args):\n return _libsbml.ASTBasePlugin_addExpectedAttributes(self, *args)", "def blendTwoAttr(*args, attribute: Union[AnyStr, List[AnyStr]]=\"\", attribute0: Union[name,\n bool]=None, attribute1: Union[name, bool]=None, blender: Union[name,\n bool]=None, controlPoints: bool=False, driver: Union[int, bool]=0, name:\n Union[AnyStr, bool]=\"\", shape: bool=True, time: timerange=None, q=True,\n query=True, e=True, edit=True, **kwargs)->Union[List[AnyStr], Any]:\n pass", "def attrCompatibility(*args, addAttr: bool=True, clear: bool=True, dumpTable: bool=True,\n enable: bool=True, nodeRename: AnyStr=\"\", pluginNode: AnyStr=\"\",\n removeAttr: bool=True, renameAttr: AnyStr=\"\", type: AnyStr=\"\", version:\n AnyStr=\"\", **kwargs)->None:\n pass", "def addExpectedAttributes(self, *args):\n return _libsbml.FbcModelPlugin_addExpectedAttributes(self, *args)", "def add_requirements(self, fgraph):\r\n pass", "def add_multi_link_attributes(self, attr1,attr2, attr3):\n i = 0\n for (u, v) in self.G.edges():\n if self.checkKey(attr1, (u,v)) and self.checkKey(attr2, (u,v)) and self.checkKey(attr3, (u,v)):\n self.G.add_edge(u,v,w=attr1[(u,v)],c1=attr2[(u,v)], c2= attr3[(u,v)])\n elif self.checkKey(attr1, (v,u)) and self.checkKey(attr2, (v,u)) and self.checkKey(attr3, (v,u)):\n self.G.add_edge(u,v,w=attr1[(v,u)],c1=attr2[(v,u)], c2= attr3[(v,u)])\n else:\n if not self.checkKey(attr1, (u,v)) and not self.checkKey(attr1, (v,u)):\n raise Exception(\"Weight edge list has missing value for \", u, v)\n if not self.checkKey(attr2, (u,v)) and not self.checkKey(attr2, (v,u)):\n raise Exception(\"Concave edge list has missing value for \", u, v)\n if not self.checkKey(attr3, (u,v)) and not self.checkKey(attr3, (v,u)):\n raise Exception(\"CPU edge has list missing value for \", u, v)\n i = i+1 \n return self.G", "def add_pair (self, first, second):\n self.constraints_.append ((first, second))", "def add_attrib(self, key, func, func_args):\n if key in self.aux_attrib:\n raise KeyError(\"Attribute '{0}' already exists, please use 'set_attrib'.\".format(key))\n else:\n self.set_attrib(key, func, func_args)", "def add_required(self, name, checkfunc=None, params=None):\n\tself._required.append((name, checkfunc, params))", "def attr_imply(self):\n if not self._modifier_exists(IMPLIED_KEY):\n return\n implications = self[CONFIG_KEY][SAMPLE_MODS_KEY][IMPLIED_KEY]\n if not isinstance(implications, list):\n raise InvalidConfigFileException(\n \"{}.{} has to be a list of key-value pairs\".\n format(SAMPLE_MODS_KEY, IMPLIED_KEY)\n )\n _LOGGER.debug(\"Sample attribute implications: {}\".format(implications))\n for implication in implications:\n if not all([key in implication for key in IMPLIED_COND_KEYS]):\n raise InvalidConfigFileException(\n \"{}.{} section is invalid: {}\".\n format(SAMPLE_MODS_KEY, IMPLIED_KEY, implication)\n )\n implier_attrs = list(implication[IMPLIED_IF_KEY].keys())\n implied_attrs = list(implication[IMPLIED_THEN_KEY].keys())\n for sample in self.samples:\n _LOGGER.debug(\"Setting Sample attributes implied by '{}'\".\n format(implier_attrs))\n for implier_attr in implier_attrs:\n implier_val = implication[IMPLIED_IF_KEY][implier_attr]\n if implier_attr not in sample:\n _LOGGER.debug(\"Sample lacks implier attr ({}), \"\n \"skipping:\".format(implier_attr))\n break\n sample_val = sample[implier_attr]\n if sample_val not in implier_val:\n _LOGGER.debug(\n \"Sample attr value does not match any of implier \"\n \"requirements ({} not in {}), skipping\".\n format(sample_val, implier_val))\n break\n else:\n # only executed if the inner loop did NOT break\n for implied_attr in implied_attrs:\n imp_val = implication[IMPLIED_THEN_KEY][implied_attr]\n _LOGGER.debug(\"Setting implied attr: '{}={}'\".\n format(implied_attr, imp_val))\n sample.__setitem__(implied_attr, imp_val)", "def add_attribute(node_proto, name, value):\n node_proto.attribute.extend([make_attribute(name, value)])", "def attributeDecl(self, elem, name, type, defi, defaultValue, nameList):\n pass", "def add_requirements(self, fgraph):\r\n # Added by default\r\n #fgraph.attach_feature(toolbox.ReplaceValidate())\r\n pass", "def merge_requirements(req1, req2):\n if req1 is not None and req2 is None:\n return req1\n if req2 is not None and req1 is None:\n return req2\n\n req1_name_norm = normalize_project_name(req1.name)\n if req1_name_norm != normalize_project_name(req2.name):\n raise ValueError(\"Reqs don't match: {} != {}\".format(req1, req2))\n all_specs = set(req1.specs or []) | set(req2.specs or [])\n\n # Handle markers\n if req1.marker and req2.marker:\n if str(req1.marker) != str(req2.marker):\n if str(req1.marker) in str(req2.marker):\n new_marker = \";\" + str(req1.marker)\n elif str(req2.marker) in str(req1.marker):\n new_marker = \";\" + str(req2.marker)\n else:\n new_marker = \"\"\n else:\n new_marker = \";\" + str(req1.marker)\n else:\n new_marker = \"\"\n\n extras = merge_extras(req1.extras, req2.extras)\n extras_str = \"\"\n if extras:\n extras_str = \"[\" + \",\".join(extras) + \"]\"\n req_str = (\n req1_name_norm\n + extras_str\n + \",\".join(\"\".join(parts) for parts in all_specs)\n + new_marker\n )\n return parse_requirement(req_str)", "def merge_attribute_defs(self, dest, source, changes = {}):\n # print \"in merge_attribute_defs, dest =\"\n # pp.pprint(dest)\n # print \"source =\"\n # pp.pprint(source)\n for aid in source.keys():\n if aid not in dest.keys():\n # copy attribute, then check for append\n dest[aid] = copy.deepcopy(source[aid])\n if 'value' in dest[aid]:\n if type(dest[aid]['value']) is str and dest[aid]['value'][0]=='+':\n dest[aid]['value'] = dest[aid]['value'].lstrip('+')\n changes[aid] = dest[aid]['value']\n continue \n if 'value' not in dest[aid]:\n if 'value' in source[aid]:\n dest[aid]['value'] = source[aid]['value']\n if (type(dest[aid]['value']) is str and dest[aid]['value'][0] == '+'):\n dest[aid]['value'] = dest[aid]['value'].lstrip('+') \n changes[aid] = dest[aid]['value']\n continue\n else:\n print (\"** Error, merging attribute '%s' but value not specified in source\"\n \" or destination\") % aid\n traceback.print_stack()\n sys.exit(1) \n else:\n if 'value' in source[aid]: \n # value given in both source and destination\n self.append_or_replace(dest[aid], source[aid], 'value', \"attribute %s\" % aid)\n changes[aid] = dest[aid]['value'] # save changed value\n else:\n print (\"** Warning, node at:\\n%s\\nmerging attribute '%s'\" \n \" but value to merge not specified.\") % (self.full_path, aid)\n print \"source attributes:\"\n pp.pprint(source)\n print \"dest attributes:\"\n pp.pprint(dest)", "def add_attributes(self, attrs):\n self.attrs.add_attributes(attrs)", "def addConstraint(self, *args):\n return _libsbml.Model_addConstraint(self, *args)", "def add(self, *args):\n return _libsbml.XMLAttributes_add(self, *args)", "def in_attr_list(self, attrs):\n for other in attrs:\n if other.matches(self): return True\n return False", "def add(self, a: 'PFElement', b: 'PFElement') -> 'PFElement':\n return self(self._pf_add(a.value, b.value, self.additive_group))", "def test_attribute_order(self):\n element = Element(\"div\")\n element.set_attribute(\"def\", \"\")\n element.set_attribute(\"abc\", \"\")\n element.set_attribute(\"ghi\", \"\")\n assert_equal(\n [b'<div abc=\"\" def=\"\" ghi=\"\">', b\"</div>\"], list(iter(element))\n )", "def addElem2Specie():\n elnames = []\n for elem in Elems:\n elnames.append(elem.name)\n # Build the list of elements for each specie\n for speci in Species:\n elemlst = []\n nam = speci.name\n if nam.endswith(\"2+\") or nam.endswith(\"3+\") or nam.endswith(\"4+\"):\n nam = nam[:-2]\n elif nam.endswith('+') or nam.endswith('-'):\n nam = nam[:-1]\n if nam in elnames:\n # It is easy, there is only one element\n elemlst.append((nam, 1))\n else:\n while len(nam):\n find = False\n for elnam in elnames:\n if nam.startswith(elnam):\n l = len(elnam)\n if len(nam) > l and IsNumber(nam[l]):\n n = int(nam[l])\n nam = nam[l + 1:]\n else:\n n = 1\n nam = nam[l:]\n elemlst.append((elnam, n))\n find = True\n break\n if not find:\n msg = \"Missing element required by {0} specie\".format(speci.name)\n QtWidgets.QMessageBox.critical(None, appName, msg)\n return False\n speci.elem = copy.copy(elemlst)\n return True", "def add_attributes(self, attrs):\n for attr in attrs:\n self.add_attribute(attr)" ]
[ "0.739838", "0.6230195", "0.6216398", "0.6155128", "0.59988314", "0.5600701", "0.545208", "0.5447197", "0.5264721", "0.5214643", "0.52116716", "0.52106464", "0.5197594", "0.51585436", "0.5156553", "0.50689334", "0.50541675", "0.50425434", "0.5041376", "0.5033299", "0.5023482", "0.5018939", "0.50078815", "0.5003548", "0.50013477", "0.4990316", "0.49886045", "0.4978481", "0.49593082", "0.49581635" ]
0.7101804
1
Return the graph that is represented by the specified axes.
def _get_connected_graph(self, axes: plt.Axes) -> Graph: if axes == self.subplot: return self.graph elif axes == self.subplot2: return self.graph2 else: raise KeyError('Specified Axes could not be found.')
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _get_connected_graph(self, axes: plt.Axes) -> Graph:\n if axes == self.subplot:\n return self.graph\n else:\n raise KeyError('Specified Axes could not be found.')", "def axes(self) -> np.ndarray: # array[Axes]\n return self._axes", "def get_axes(self) -> VGroup:\n return self.axes", "def get_axes(self) -> VGroup:\n return self.axes", "def axes(self):\n return self._axes", "def axes(self):\n return self._axes", "def allAxes( mv ):\n if mv is None: return None\n return mv.getAxisList()", "def getPlot(self):\n return self.axes", "def axes(*x: Iterable[int]):\n return [_ti_core.Axis(i) for i in x]", "def __init__(self, axes=()):\n self._axes = []\n self._dimension = 0\n for axis in axes:\n self.add_axis(axis)", "def split(self, axis):\n if axis not in self.axes_names:\n raise Exception('Axis %s not found. Available axes: %s'\n % (axis, self.axes_names))\n\n return OrderedDict((dv, self.sub_cuboid(**{axis: dv}))\n for dv in self.axes_domains[axis])", "def getAxis(self,axis):\n\n\t\tif axis == \"u\":\n\t\t\tif len(self.usr) != 0:\n\t\t\t\treturn np.append([0], self.usr)\n\n\t\tif axis == \"s\":\n\t\t\tif len(self.seg) != 0:\n\t\t\t\tif self.radiograph:\n\t\t\t\t\treturn self.seg\n\t\t\t\telse:\n\t\t\t\t\tfirst = self.seg[0] - 1.\n\t\t\t\t\treturn np.append([first], self.seg)\n\n\t\tif axis == \"c\":\n\t\t\tif len(self.cos) != 0:\n\t\t\t\tif self.radiograph:\n\t\t\t\t\treturn self.cos\n\t\t\t\telse:\n\t\t\t\t\tfirst = -1.\n\t\t\t\t\treturn np.append([first], self.cos)\n\n\t\tif axis == \"e\":\n\t\t\tif len(self.erg) != 0:\n\t\t\t\tfirst = self.erg[0] - 1.\n\t\t\t\treturn np.append([first], self.erg)\n\n\t\tif axis == \"t\":\n\t\t\tif len(self.tim) != 0:\n\t\t\t\tfirst = self.tim[0] - 1.\n\t\t\t\treturn np.append([first], self.tim)\n\n\t\tif axis == \"i\":\n\t\t\treturn self.cora\n\n\t\tif axis == \"j\":\n\t\t\treturn self.corb\n\n\t\tif axis == \"k\":\n\t\t\treturn self.corc\n\n\t\treturn []", "def maybe_get_ax(*args, **kwargs):\n\n if 'ax' in kwargs:\n ax = kwargs.pop('ax')\n elif len(args) == 0:\n fig = plt.gcf()\n ax = plt.gca()\n elif isinstance(args[0], mpl.axes.Axes):\n ax = args[0]\n args = args[1:]\n else:\n ax = plt.gca()\n return ax, args, dict(kwargs)", "def _get_graph(nodes: Nodes, edges: np.ndarray):\n\n graph = nx.Graph()\n graph.add_nodes_from(nodes['id'])\n attrs = nodes.set_index('id').to_dict('index')\n nx.set_node_attributes(graph, attrs)\n graph.add_edges_from(edges)\n\n return graph", "def make_2axis_graph():\n d = curdoc()\n _remove_fig(d)\n graph_val = d.get_model_by_name(GRAPH_SELECTION).value\n model_id, message_name, _ = run_handlers.get_modelid_messagename_type(d)\n\n xval = d.get_model_by_name(X_AXIS_SELECTION).value\n yval = d.get_model_by_name(Y_AXIS_SELECTION).value\n\n if xval != DEFAULT_UNSELECTED and yval != DEFAULT_UNSELECTED:\n plot = figure(plot_width=400, plot_height=400, name=FIGURE_MODEL)\n sind = run_handlers.get_source_index(d.session_context.id, model_id, message_name)\n _install_callback_and_cds(sind, model_id, message_name, stream_limit=100000)\n\n # get the field name back from the pretty field : meta string formed above\n x = xval.split(\" :\")[0]\n y = yval.split(\" :\")[0]\n\n if graph_val == \"line\":\n plot.line(x=x, y=y, color=\"firebrick\", line_width=2, source=d.get_model_by_name(sind))\n plot.x_range.follow = \"end\" # don't jam all the data into the graph; \"window\" it\n plot.x_range.follow_interval = 100\n plot.x_range.range_padding = 0\n if graph_val == \"scatter\":\n plot.cross(x=x, y=y, size=20, color=\"firebrick\", line_width=2, source=d.get_model_by_name(sind))\n if graph_val == \"step\":\n plot.step(x=x, y=y, color=\"#FB8072\", source=d.get_model_by_name(sind))\n\n d.add_root(plot)", "def format_graph(axis):\r\n if isinstance(axis, np.ndarray):\r\n return [format_axis(ax) for ax in axis.flat]\r\n else:\r\n return format_axis(axis)", "def graphs(self):\n return self.__graphs", "def graph(self, *links):\n\n groups = self._model_terms(links)\n fig, ax = plt.subplots()\n for group in groups:\n for term in group:\n termdata = self._term_data[term]\n termdata.graph(ax)\n\n return ax", "def get_graph(self, engine, args):\n raise NotImplementedError(\"Override in subclass\")", "def get_data(self):\n return [self.axes]", "def _axes_domain(self, *args, **kwargs):\n # See _add_gridline_label for detials\n lon_0 = self.axes.projection.proj4_params.get('lon_0', 0)\n x_range, y_range = type(self)._axes_domain(self, *args, **kwargs)\n x_range = np.asarray(x_range) + lon_0\n return x_range, y_range", "def get_graph(self):\n return self._graph", "def gexf_graph():\n # you must replace these lines and supply your own graph\n my_gexf = Gexf(\"author\", \"title\")\n gexf.addGraph(\"undirected\", \"static\", \"I'm an empty graph\")\n return gexf.graphs[0]", "def findaxis(self, world=True, axis=0):\n return _coordsys.coordsys_findaxis(self, world, axis)", "def format_graph(axis):\n if isinstance(axis, numpy.ndarray):\n return [format_axis(ax) for ax in axis.flat]\n else:\n return format_axis(axis)", "def from_cartesian(self, coordinates, *axes):", "def _combine_domains(self, axes):\n def stack_dvalues(prev, x):\n if 0:\n print 'stack_dvalues ...'\n print 'prev:', prev\n print 'x:', x\n res = prev + [list(np.tile(x, len(prev) == 0 or len(prev[-1])))]\n if 0:\n print 'result:', res\n print ''\n return res\n return reduce(stack_dvalues, [self.axes_domains[a] for a in axes], [])", "def get_domain(self, axis_id):\n if axis_id in self.axes_domains:\n return self.axes_domains[axis_id]\n else:\n raise Exception('Unknow axis %s' % axis_id)", "def getGraph(self):\n\t\treturn self.graph", "def _get_axis(axis):\n\n def axis_getter(self):\n ErrorMessage.default_to_pandas(f\"DataFrame.get_axis({axis})\")\n return self.to_pandas().axes[axis]\n\n return axis_getter" ]
[ "0.7047026", "0.5786139", "0.5764504", "0.5764504", "0.57531923", "0.57531923", "0.5719589", "0.5469798", "0.5383216", "0.53713644", "0.5342922", "0.52830964", "0.52605724", "0.5249076", "0.5199109", "0.5196632", "0.51746565", "0.51670814", "0.5148048", "0.5135304", "0.51338637", "0.5128643", "0.5124559", "0.51228726", "0.51223123", "0.51064175", "0.5104479", "0.5096259", "0.5078219", "0.5067992" ]
0.6946097
1
Get and return the onhover text of the element.
def get_hover_text(self) -> str: if self.graph_element is None: return '' text = '' for name, value in self.graph_element.attr.items(): if name in ('x', 'y') or name.startswith('.'): continue text += f'{name}: {value}\n' return text[:-1]
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_tooltip_text(self): # real signature unknown; restored from __doc__\n return \"\"", "def GetToolTip(self):\r\n\r\n return self._label", "def hover(mouse):\n nonlocal desc_label\n\n smallest_element = get_element(mouse)\n\n with data_lock:\n if smallest_element:\n output = [f\"{k}={str(v)}\" for k, v in smallest_element.metadata.items() if k != \"text\"]\n desc_label.config(text=\", \".join(output))\n else:\n desc_label.config(text=str(\"{}\"))", "def mouseover_timeplot(self):\n return str(self.mouseover).lower()", "def on_hover(self) -> None:", "def get_tooltip_markup(self): # real signature unknown; restored from __doc__\n return \"\"", "def build_hover_text(labels):\n\ttext = str()\n\tfor k, v in labels.items():\n\t\tif v is not None:\n\t\t\ttext += '{k}: {v}<br>'.format(k=k, v=str(v))\n\n\treturn text.strip('<br>')", "def get_tooltip ( self, object ):\n return self.tooltip", "def get_text(self, selector):\n el = self.locate_element(selector)\n return el.text", "def _CreateToolTipText( self, ev ):\n return ''", "def get_element_text(self) -> str:\n return self.element.text", "def text(self):\n return self.label.text()", "def GetItemToolTip(self):\n \n return self.choices[0].GetToolTip()", "def _get_element_text(self, selector):\r\n text_list = self._find_within(selector).text\r\n return text_list[0] if text_list else None", "def tooltip(self) -> str:\n return self._tooltip", "def get_element_text(self, element: Union[WebElement, Tuple[By, str]]) -> str:\n element = self.find_element(element)\n return element.get_attribute('innerText')", "def get_name(self, element):\n return element.find_elements_by_class_name(\"wrap-text\")[0].get_attribute(\"innerHTML\").strip()", "def get_node_text(self):\n return self.node_text", "def _get_tooltip_text(ip_entity):\n return \"<br>\".join(\n str(line)\n for line in [\n ip_entity.Address,\n ip_entity.Location.City or \"Unknown city\",\n ip_entity.Location.CountryCode or \"Unknown country\",\n *(list(ip_entity.AdditionalData.items())),\n ]\n )", "def editorToolTip(self):\n return self._editor.toolTip()", "def get_inner_text(self, css_selector):\n element = self.driver.find_elements_by_css_selector(css_selector)\n if len(element) > 0:\n information = element[0].get_attribute(\"innerText\").strip()\n return information", "def GetHoverBitmap(self):\r\n \r\n return self.hover_bitmap", "def get_text(self):\n return self.get_property('text')", "def get_text(self):\n logging.getLogger(__name__).info(\"Element text: {}\\nby = {}\\nvalue = {}\".format(\n self.driver.find_element(self.by, self.value).text, self.by, self.value))\n return self.driver.find_element(self.by, self.value).text", "def buttonToolTip(self):\n return self.__button.toolTip()", "def label(self):\r\n return self._text", "def getElementName(self):\n return _libsbml.TextGlyph_getElementName(self)", "def text(self):\n logger.debug(\"Getting text property\")\n return self.web_element.text", "def get_text(self):\n text_element = self.page.find(id=self.text_location)\n return text_element.get_text()", "def getText(self):\n return _libsbml.TextGlyph_getText(self)" ]
[ "0.6931978", "0.6610155", "0.6458537", "0.64448744", "0.64009815", "0.6232814", "0.6061276", "0.60440975", "0.60406834", "0.60304356", "0.6012522", "0.5991501", "0.59678483", "0.59628785", "0.5956597", "0.5904038", "0.5879372", "0.5839806", "0.5836077", "0.57789415", "0.57775307", "0.5770383", "0.57611305", "0.5734332", "0.57254535", "0.5719095", "0.57086587", "0.56938237", "0.5679112", "0.5667787" ]
0.81764066
0
Removes the path effect with the specified name from the element.
def remove_extra_path_effect(self, name: str): self.extra_path_effects.pop(name)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def remove_extra_path_effect(self, name: str):\n super().remove_extra_path_effect(name)\n self.update_path_effects()", "def remove_extra_path_effect(self, name: str):\n super().remove_extra_path_effect(name)\n self.update_path_effects()", "def remove(name):", "def remove_asset(self, name):\n if name in self.assets:\n del self.assets[name]", "def remove(self, name: str) -> None:\n del self.components[name]", "def remove_mix(self, name: str) -> None:\n self.remove(name)", "def remove_curve(self, name):\n self._curve_reg.__delitem__(name)", "def remove(self, name):\n raise NotImplementedError", "def remove_attribute(self, name):\n\n pass", "def drem(self, name):\n return self.rem(name)", "def rm(self, name: str) -> None:\n path = self.get_path(name)\n if os.path.exists(path):\n os.remove(path)", "def lrem(self, name):\n return self.rem(name)", "def remove(path):", "def remove_operation(self, name):\n\n del self.operations[name]", "def remove(self, name):\n for var in self.inputs:\n if var.name == name:\n self.inputs.remove(var)\n return\n for var in self.outputs:\n if var.name == name:\n self.outputs.remove(var)\n return", "def remove_pattern(self, name):\n self._pattern_reg.__delitem__(name)", "def remove_input(self, name):\n if name in self._inputs:\n del self._inputs[name]", "def remove(self, name, source):\n self.m.path.assert_absolute(source)\n self._run(name, ['remove', source])\n self.m.path.mock_remove_paths(source)", "def remove(self, name):\n if self.circles.has_key(name):\n del self.circles[name]\n self.cursor.execute(\"\"\"DELETE FROM sensors_powersensor WHERE target=%s\"\"\", (name,))", "def remove(self, name):\n cont = getattr(self, name)\n self.disconnect(name)\n self._exprmapper.remove(name)\n if has_interface(cont, IComponent):\n self._depgraph.remove(name)\n for obj in self.__dict__.values():\n if obj is not cont and is_instance(obj, Driver):\n obj.workflow.remove(name)\n obj.remove_references(name)\n\n return super(Assembly, self).remove(name)", "def remove(name, send_events=True, moving=False):", "def remove(self, name):\n if hasattr(self, name):\n site = getattr(self, name)\n if isinstance(site, IconSite):\n delattr(self, name)\n self._typeDict[site.type].remove(name)", "def pop_aspect(name):\n\t_aspects[name].pop()", "def removeAssetByName(self, name):\n try:\n del self.__assets[name]\n except KeyError:\n return True", "def delete_file(self, name):\n del self.files[name]", "def remove_control(self, name):\n del self._controls[name]", "def remove_light(self, name):\n if name in self._lights:\n del self._lights[name]\n else:\n raise ValueError('Light {} not in scene!'.format(name))", "def del_image(self, name):\r\n if self.images is None or name not in self.images:\r\n return\r\n l = self.images\r\n self.images = None\r\n l.setdefault('/empties/', [])\r\n # push the number on the empties list\r\n l['/empties/'].append(l[name])\r\n del l[name]\r\n self.images = l", "def unwatch(self, path):\n path_obj = Path(path)\n if not path_obj.exists():\n raise FileObserverException(\"Can not unwatch non exist path\")\n parent_path = str(path_obj.parent)\n child_paths = self._watch_dog_observed_paths.get(parent_path, [])\n if path in child_paths:\n child_paths.remove(path)\n self._observed_paths.pop(path, None)\n if not child_paths:\n self._watch_dog_observed_paths.pop(parent_path, None)\n if self._observed_watches[parent_path]:\n self._observer.unschedule(self._observed_watches[parent_path])\n self._observed_watches.pop(parent_path, None)", "def remove(self, path):\n self.__remove.append(path)\n return self" ]
[ "0.75836045", "0.75836045", "0.6658393", "0.66141933", "0.6609292", "0.65412486", "0.64385855", "0.6330571", "0.6297923", "0.6283011", "0.6278286", "0.60900366", "0.60307115", "0.6020726", "0.59730655", "0.5940002", "0.5930177", "0.59114444", "0.58867127", "0.58836484", "0.5874422", "0.5841428", "0.5764166", "0.576313", "0.5722573", "0.5697867", "0.56928796", "0.5649853", "0.5642659", "0.5635432" ]
0.82098126
0
Called when the element is hovered.
def on_hover(self) -> None:
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def mouse_over(self):\n pass", "def hovered(self, *args, **kwargs): # real signature unknown\n pass", "def hoverEnterEvent( self, event ):\n # process the parent event\n super(XNode, self).hoverEnterEvent(event)\n \n # hover over a hotspot\n hotspot = self.hotspotAt(event.pos())\n if not hotspot:\n hotspot = self.dropzoneAt(event.pos())\n \n old_spot = self._hoverSpot\n \n if hotspot and hotspot != old_spot:\n # update the new hotspot\n self._hoverSpot = hotspot\n \n if old_spot:\n old_spot.hoverLeaveEvent(event)\n \n if hotspot.hoverEnterEvent(event):\n self.update()\n \n elif old_spot and not hotspot:\n self._hoverSpot = None\n \n if old_spot.hoverLeaveEvent(event):\n self.update()", "def on_hovered(self):\n if not self.is_selected:\n self.colour = self.hover_colour\n self.is_hovered = True\n self.redraw()", "def MouseOverItem(self,item):\r\n pass", "def on_unhover(self) -> None:", "def mouse_enter(self):\n pass", "def handle_equipment_mouseover(self):\n if self.skill_tree_displaying:\n return\n mouse_pos = pg.mouse.get_pos()\n slot_moused_over = ''\n for slot in self.equipment_tiles:\n if self.equipment_tiles[slot].collidepoint(mouse_pos):\n slot_moused_over = slot\n break\n\n if slot_moused_over:\n self.tooltip_focus = self.equipment_tiles[slot_moused_over]\n if self.player_dict['equipment'][slot_moused_over]: # i.e. if there is an item equipped in the slot\n equipment_dict = self.player_dict['equipment'][slot_moused_over].to_dict()\n else:\n equipment_dict = None\n player_panel_renderer.draw_equipment_details(equipment_dict, slot_moused_over)", "def hoverEnterEvent(self, event: QGraphicsSceneHoverEvent):\n self.setCursor(Qt.ArrowCursor)", "def hoverEnterEvent(self, event: QGraphicsSceneHoverEvent):\n self.setCursor(Qt.ArrowCursor)", "def _hover(self, event):\n if self.ignore(event):\n return\n\n if self._active_handle is not None or not self._selection_completed:\n # Do nothing if button is pressed and a handle is active, which may\n # occur with drag_from_anywhere=True.\n # Do nothing if selection is not completed, which occurs when\n # a selector has been cleared\n return\n\n _, e_dist = self._edge_handles.closest(event.x, event.y)\n self._set_cursor(e_dist <= self.grab_range)", "def hover(self):\n\n element = self.element()\n\n if element:\n\n try:\n\n if not element.is_displayed():\n self.scroll_to()\n\n return ActionChains(self.driver).move_to_element(element).perform()\n\n except (ElementNotVisibleException, WebDriverException):\n pass", "def hoverLeaveEvent(self, moveEvent):\n self.setCursor(Qt.ArrowCursor)\n super().hoverLeaveEvent(moveEvent)", "def hoverEnterEvent(self, event: 'QGraphicsSceneHoverEvent'):\n QApplication.instance().setOverrideCursor(Qt.OpenHandCursor)", "def _action_hovered(self, action):\n self._emit_signal_for_action(self.action_hovered, action)", "def handle_attributes_mouseover(self):\n pass", "def hoverLeaveEvent(self, event):\n if self._hoverSpot:\n if self._hoverSpot.hoverLeaveEvent(event):\n self.update()\n \n self._hoverSpot = None\n \n super(XNode, self).hoverLeaveEvent(event)", "def hoverEnterEvent(self, event):\n if not self.isSelected():\n for hs in self.hs:\n hs.setOpacity(1)\n super(DiagramItem, self).hoverEnterEvent(event)", "def hover_over(self, id):\n el = self.wait_n_get(By.ID, id)\n hover = ActionChains(self.driver).move_to_element(el)\n hover.perform()", "def onMouseOver(self,mouseEvent):\n\t\tself.canvas.nodeOver(self)", "def hoverMoveEvent(self, event):\n # process the parent event\n super(XNode, self).hoverMoveEvent(event)\n \n # hover over a hotspot\n hotspot = self.hotspotAt(event.pos())\n if not hotspot:\n hotspot = self.dropzoneAt(event.pos())\n \n old_spot = self._hoverSpot\n \n if hotspot and hotspot != old_spot:\n # update the new hotspot\n self._hoverSpot = hotspot\n \n if old_spot:\n old_spot.hoverLeaveEvent(event)\n \n if hotspot.hoverEnterEvent(event):\n self.update()\n \n elif old_spot and not hotspot:\n self._hoverSpot = None\n \n if old_spot.hoverLeaveEvent(event):\n self.update()", "def handle_inventory_mouseover(self):\n if self.skill_tree_displaying:\n return\n item_index = None\n item_tile = None\n mouse_pos = pg.mouse.get_pos()\n for i, item_tile in enumerate(self.inventory_tiles):\n # This loop checks if the tile being moused over currently holds an actual item, and if so, returns index.\n if item_tile.collidepoint(mouse_pos) and len(self.player_dict['inventory']) >= i + 1:\n item_index = i\n break\n\n if item_index is not None:\n self.tooltip_focus = item_tile\n self.active_item_index = item_index\n player_panel_renderer.draw_item_details(self.player_dict['inventory'][item_index].to_dict(),\n self.player_dict['attributes'],\n self.player_dict['equipment'])", "def mouseOver(self, element_tuple):\n self.log_info(f\"Browser.mouseOver: Moving mouse over {element_tuple}\")\n ActionChains(self.CORE).move_to_element(self.CORE.find_element(*self.format_element(element_tuple))).perform()\n return", "def hover_over_element(driver, selector, by=By.XPATH):\r\n element = driver.find_element(by=by, value=selector) \r\n hover = ActionChains(driver).move_to_element(element)\r\n hover.perform()", "def hoverLeaveEvent(self, event):\n if not self.isSelected():\n for hs in self.hs:\n hs.setOpacity(0.01)\n super(DiagramItem, self).hoverLeaveEvent(event)", "def hover(cls, event):\n if event.canvas == gs.fitness_plot.fig.canvas:\n if event.inaxes == gs.fitness_plot.ax:\n cls.update(event, gs.fitness_plot.curve, -1)\n else:\n cplot = gs.canvas2cloud_plot[event.canvas]\n if event.inaxes == cplot.main_ax:\n cls.update(event, cplot.main_curve, 0)", "def mouse_not_over(self):\n pass", "def hoverLeaveEvent(self, event: 'QGraphicsSceneHoverEvent'):\n QApplication.instance().restoreOverrideCursor()", "def hover(mouse):\n nonlocal desc_label\n\n smallest_element = get_element(mouse)\n\n with data_lock:\n if smallest_element:\n output = [f\"{k}={str(v)}\" for k, v in smallest_element.metadata.items() if k != \"text\"]\n desc_label.config(text=\", \".join(output))\n else:\n desc_label.config(text=str(\"{}\"))", "def _hover_callback(self, feature, **kwargs): # pylint: disable=unused-argument\n try:\n # self.logger.debug(\"HoverWidget callback called.\")\n new_value = (\n widget_utils.create_html_header(\"Current Patch\").value\n + \"\"\"</br>\n <b>Class label:</b> {}</br>\n <b>Area:</b> {:.2f} ha</br>\n <b>Perimeter:</b> {:.2f} km</br>\n <b>Shape index:</b> {:.2f}</br>\n <b>Fractal dim.:</b> {:.2f}\n \"\"\".format(\n feature[\"properties\"][\"class_label\"],\n feature[\"properties\"][\"area\"] / 1e4,\n feature[\"properties\"][\"perimeter\"] / 1e3,\n feature[\"properties\"][\"shape_index\"],\n feature[\"properties\"][\"fractal_dimension\"],\n )\n )\n if \"node_dynamic\" in feature[\"properties\"].keys():\n new_value += \"</br><b>Node dyanmic:</b> {}\".format(\n feature[\"properties\"][\"node_dynamic\"]\n )\n if \"absolute_growth\" in feature[\"properties\"].keys():\n new_value += \"</br><b>Abs. growth:</b> {:.2f} ha/yr\".format(\n feature[\"properties\"][\"absolute_growth\"] / 1e4\n )\n self.hover_html.value = new_value\n except: # pylint: disable=bare-except\n self.logger.exception(\"Exception in hover callback.\")" ]
[ "0.7412773", "0.7237632", "0.6906489", "0.68526864", "0.6812145", "0.67659557", "0.66197455", "0.66132617", "0.6613236", "0.6613236", "0.6557558", "0.64740694", "0.6457405", "0.64437896", "0.641706", "0.6406154", "0.6402043", "0.6388164", "0.63690585", "0.6352717", "0.6292873", "0.62815917", "0.6242064", "0.62394625", "0.6236173", "0.6221703", "0.6161545", "0.6147376", "0.60661507", "0.6058279" ]
0.83767354
0
Called when an element stops being hovered.
def on_unhover(self) -> None:
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def mouse_out(self):\n pass", "def hoverLeaveEvent(self, event):\n if self._hoverSpot:\n if self._hoverSpot.hoverLeaveEvent(event):\n self.update()\n \n self._hoverSpot = None\n \n super(XNode, self).hoverLeaveEvent(event)", "def on_hover(self) -> None:", "def hoverLeaveEvent(self, event: 'QGraphicsSceneHoverEvent'):\n QApplication.instance().restoreOverrideCursor()", "def hoverLeaveEvent(self, moveEvent):\n self.setCursor(Qt.ArrowCursor)\n super().hoverLeaveEvent(moveEvent)", "def on_mouse_leave (self, event):\n\n\t\tif not self.clicked:\n\n\t\t\tself.cursor_position = [-1,-1]\n\t\t\tself.redraw_canvas()\n\t\t\tself.hide_tip()#self.timer1 = gobject.timeout_add(2000, self.hide_tip)", "def mouse_not_over(self):\n pass", "def on_mouse_leave(self, event):\n global controller\n if self == controller:\n self.set_help_text(None)\n if self.task:\n self.task.stop()\n self.task = None\n controller = None", "def mouse_over(self):\n pass", "def mouse_out(self, event):\r\n self['background'] = self.defaultBackground", "def stop(self):\n self.on_stop()", "def stop(self):\n self._stop_event.set()", "def on_tag_hover(self, _tag, _textview, event, _textiter, halfmove):\n if event.type == Gdk.EventType.BUTTON_RELEASE:\n self.emit(\"step\", halfmove)", "def hovered(self, *args, **kwargs): # real signature unknown\n pass", "def stop(self):\n self.stop_event.set()", "def stop(self):\n self.stop_event.set()", "def OnLeaveWindow(self, event):\r\n \r\n if self._hover_button:\r\n self._hover_button.cur_state = AUI_BUTTON_STATE_NORMAL\r\n self._hover_button = None\r\n self.Refresh()\r\n self.Update()", "def stop_emission(self, detailed_signal): # reliably restored by inspect\n pass", "def stop_emission(self, detailed_signal): # reliably restored by inspect\n pass", "def stop_emission(self, detailed_signal): # reliably restored by inspect\n pass", "def stop_emission(self, detailed_signal): # reliably restored by inspect\n pass", "def stop_emission(self, detailed_signal): # reliably restored by inspect\n pass", "def stop_emission(self, detailed_signal): # reliably restored by inspect\n pass", "def stop_emission(self, detailed_signal): # reliably restored by inspect\n pass", "def stop_emission(self, detailed_signal): # reliably restored by inspect\n pass", "def stop_emission(self, detailed_signal): # reliably restored by inspect\n pass", "def stop_emission(self, detailed_signal): # reliably restored by inspect\n pass", "def stop_emission(self, detailed_signal): # reliably restored by inspect\n pass", "def stop_emission(self, detailed_signal): # reliably restored by inspect\n pass", "def stop_emission(self, detailed_signal): # reliably restored by inspect\n pass" ]
[ "0.651642", "0.63788223", "0.615204", "0.60260147", "0.5947012", "0.58971274", "0.5630406", "0.55071926", "0.5495076", "0.5430006", "0.53661186", "0.53160745", "0.52913845", "0.52894986", "0.5289293", "0.5289293", "0.52844995", "0.527896", "0.527896", "0.527896", "0.527896", "0.527896", "0.527896", "0.527896", "0.527896", "0.527896", "0.527896", "0.527896", "0.527896", "0.527896" ]
0.70880145
0
Is called when the Position of an Element is changed.
def on_position_change(self) -> None: pass
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def position_changed(self, position):\n pass", "def _pos_changed(self, timestamp=None, value=None, **kwargs):\n self._set_position(value)", "def update_position(position):\n pass", "def set_position(self, updated):\n self.buff_x = updated[0]\n self.buff_y = updated[1]", "def motorPositionChanged(self, absolutePosition):\n pass", "def on_increased_position(self, order) -> None:\n pass", "def update(self, pos):\n\t\tpass", "def setPosition(position):", "def _on_frame_changed(self, change):\n self._set_coordinates(self.frame)", "def set_position(self):\n raise RuntimeError(\"the 'set_position' method must be overriden\")", "def position(self):\r\n pass", "def setPosition(self,newPos):\n self._position = newPos", "def set_new_location(self, xPos, yPos):", "def GetPosition(self):\n ...", "def set_position(self, new_pos):\n self._position = new_pos", "def update_pos(self, new_position: Tuple[float, float]) -> None:\n\n new_value = self.__function(new_position)\n if new_value < self.__value:\n self.__value = new_value\n self.__position = new_position", "def updatePos(self):\n self.setPos(self.centerX-self.boundingRect().width()/2.0,\n self.centerY-self.boundingRect().height()/2.0)", "def set_position(self, position):\n raise NotImplementedError()", "def updatePositionAndClean(self):\n raise NotImplementedError # don't change this!", "def set_position(self, az_pos, el_pos):\n raise NotImplementedError()", "def move(self, newPosition):\n oldPosition = self.position\n self.position = newPosition\n\n xOffset = newPosition[0] - oldPosition[0]\n yOffset = newPosition[1] - oldPosition[1]\n\n for element in self.elements:\n element.move((element.getPosition()[0] + xOffset, element.getPosition()[1] + yOffset))\n \n self.create()", "def updatePositionAndClean(self):\n raise NotImplementedError", "def updatePositionAndClean(self):\n raise NotImplementedError", "def update_position(self, p):\n if self.track:\n our_p = self.c.p\n assert self.gnx == our_p.gnx\n else:\n our_p = self.get_position()\n\n if p.gnx == our_p.gnx:\n self.update_position_edit(p)\n if self.update:\n self.update_position_view(p)", "def set_position(self, position):\n self.position = position", "async def on_block_updated(\n self, position: typing.Tuple[float, float, float], itself=True\n ):\n raise NotImplementedError", "def setPosition(*args):", "def setPosition(*args):", "def setPosition(*args):", "def setPosition(*args):" ]
[ "0.8156067", "0.7252104", "0.7039363", "0.69174737", "0.681203", "0.67029595", "0.66832906", "0.6652416", "0.6515981", "0.6392963", "0.63458174", "0.63199514", "0.6239177", "0.6238975", "0.6185581", "0.6180617", "0.61575466", "0.6155134", "0.6139133", "0.60846967", "0.6080966", "0.6078466", "0.6078466", "0.60765404", "0.6070912", "0.6060324", "0.60481924", "0.60481924", "0.60481924", "0.60481924" ]
0.8031221
1
Updates the applied path effects.
def update_path_effects(self) -> None: effects = list(self.extra_path_effects.values()) effects.append(pe.Normal()) self.set_path_effects(effects)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _post_update_paths(self, **kwargs):\n\n files_updated = kwargs.get('files_updated', list())\n if not files_updated:\n return\n\n maya_utils.reload_textures(files_updated)\n\n # Dependencies are already reloaded during update paths process\n # maya_utils.reload_dependencies(files_updated)", "def add_extra_path_effect(self, name: str,\n effect: pe.AbstractPathEffect) -> None:\n super().add_extra_path_effect(name, effect)\n self.update_path_effects()", "def add_extra_path_effect(self, name: str,\n effect: pe.AbstractPathEffect) -> None:\n super().add_extra_path_effect(name, effect)\n self.update_path_effects()", "def update(self, paths):\n raise NotImplementedError", "def remove_extra_path_effect(self, name: str):\n super().remove_extra_path_effect(name)\n self.update_path_effects()", "def remove_extra_path_effect(self, name: str):\n super().remove_extra_path_effect(name)\n self.update_path_effects()", "def applyModifiers(self):\n if not self.getScopeUpdated():\n self.updateScopes()\n targets = self.getConTextModeNodes(\"target\")\n modifiers = self.getConTextModeNodes(\"modifier\")\n for target in targets:\n for modifier in modifiers:\n if modifier.applyRule(target):\n if self.getVerbose():\n print(\"applying relationship between\", modifier, target)\n\n self.add_edge(modifier, target)", "def update_path():\n #TODO update path information\n pass", "def add_extra_path_effect(self, name: str,\n effect: pe.AbstractPathEffect) -> None:\n self.extra_path_effects[name] = effect", "def update(self, **vars):\n for name in vars:\n # Use __setitem__ for all effects\n self[name] = vars[name]", "def set(self, new_path):\n\n for i in range(self.depth):\n self.path[i] = new_path[self.max_input*i:self.max_input*(i + 1)]", "def UpdateLayers(self):\n pass", "def post_load(self):\r\n for _, effect in self._effects.items():\r\n effect.post_load()", "def update(self):\n tracing = self._tracing\n self._tracing = True\n for t in self.turtles():\n t._update_data()\n t._drawturtle()\n self._tracing = tracing\n self._update()", "def update(self, **kwargs):\n for name, item in itertools.chain(\n self._cal_objs.items(),\n self._noise_objs.items()):\n logger.debug(\"update {}\".format(item))\n item.update(**kwargs)", "def update(self, *args):\n return _osgAnimation.Animation_update(self, *args)", "def apply_effects(self, item_name):\n item = self.get(item_name)\n\n # Enable commands\n for command in item.effects.get(\"enable_commands\", []):\n if command not in self.game.state.commands_enabled:\n self.game.alert(\"You unlocked the `{}` command\", command)\n self.game.state.commands_enabled.append(command)\n\n # Enable resouces\n for resources in item.effects.get(\"enable_resources\", []):\n if resources not in self.game.state.resources_enabled:\n self.game.alert(\"You can now mine *{}*.\", resources)\n self.game.state.resources_enabled.append(resources)\n\n # Enable items\n for item_name in item.effects.get(\"enable_items\", []):\n if item_name not in self.game.state.tools_enabled:\n self.game.alert(\"You can now craft ${}$.\", item_name)\n self.game.state.tools_enabled.append(item_name)\n\n # Enable research\n for research in item.effects.get(\"enable_research\", []):\n if research not in self.game.state.research_enabled:\n self.game.alert(\"You can now research @{}@.\", research)\n self.game.state.research_enabled.append(research)\n\n # Trigger flags\n for trigger in item.effects.get(\"triggers\", []):\n if trigger not in self.game.state.triggers:\n self.game.state.triggers.append(trigger)\n\n # Grant resources\n for resource in RESOURCES:\n if resource in item.effects:\n value = to_float(item.effects[resource])\n self.game.resources.add(resource, value)\n if value > 0:\n self.game.alert(\"You found *{} {}*.\", value, resource)\n else:\n self.game.alert(\"You lost *{} {}*.\", -value, resource)\n\n # Change mining difficulty\n for resource in RESOURCES:\n change = item.effects.get(f\"{resource}_mining_difficulty\", None)\n if change:\n change = to_float(change)\n self.game.mining_difficulty.multiply(resource, 1 - change)\n self.game.alert(\n \"*{}* mining difficulty reduced by {:.0%}.\", resource, change\n )\n\n # Trigger events\n self.game.events.trigger(*item.effects.get(\"events\", []))", "def update(self) -> None:\n self.all_sprites.update()", "def update(self, *args):\n return _osgAnimation.AnimationManagerBase_update(self, *args)", "def effect(self):\n # Get script's \"--what\" option value.\n what = self.options.what / 10.\n negative_kerf = False\n if what < 0.:\n what = -what\n negative_kerf = True\n\n kerf_in_mm = self.unittouu(str(what) + \" mm\")\n\n operation_list = [\"StrokeToPath\", \"SelectionUnion\",\n \"SelectionBreakApart\", \"SelectionUnion\", \"SelectionBreakApart\"]\n if negative_kerf:\n operation_list[-2] = \"SelectionIntersect\"\n\n join_ext = metaext.MetaEffect(operation_list)\n\n if not self.set_appropriate_width(kerf_in_mm):\n objectify = metaext.MetaEffect([\"ObjectToPath\"])\n objectify.effect(self.document, self.selected, self.doc_ids)\n if not self.set_appropriate_width(kerf_in_mm):\n inkex.error(\"Didn't found any selected path, breaking\")\n return\n \n join_ext.effect(self.document, self.selected, self.doc_ids)\n\n for _, node in self.selected.iteritems():\n #inkex.debug(\"node %s\" % inkex.etree.tostring(node))\n if node.tag == inkex.addNS('path', 'svg'):\n new_width = self.unittouu(\"0.5mm\")\n colour = '#ff0000' if negative_kerf else '#000000'\n style = {'stroke-width': new_width, 'fill': 'none',\n 'stroke': colour}\n style = simplestyle.formatStyle(style)\n node.set('style', style)\n # inkex.debug(\"node %s\" % inkex.etree.tostring(node))", "def update(self, *args):\n return _osgAnimation.BasicAnimationManager_update(self, *args)", "def loadPaths(self):\n for ij in self.link:\n self.link[ij].flow = 0\n for p in self.path:\n for ij in self.path[p].links:\n self.link[ij].flow += self.path[p].flow\n for ij in self.link:\n self.link[ij].updateCost()\n for p in self.path:\n self.path[p].updateCost()", "def update_path(self, action: Action, kg: KnowledgeGraph, offset=None):\n\n def offset_path_history(p, offset):\n for i, x in enumerate(p):\n if type(x) is tuple:\n new_tuple = tuple([_x[:, offset, :] for _x in x])\n p[i] = new_tuple\n else:\n p[i] = x[offset, :]\n\n # update action history\n if self.relation_only_in_path:\n action_embedding = kg.get_relation_embeddings(action.rel)\n else:\n action_embedding = self.get_action_embedding(action, kg)\n if offset is not None:\n offset_path_history(self.path, offset)\n\n self.path.append(\n self.path_encoder(action_embedding.unsqueeze(1), self.path[-1])[1]\n )", "def modify_sky(path, name, number, op, value):\n os.chdir(path)\n sky_levels = get(name, 'sky')\n sky_level = sky_levels[number]\n if op == '+':\n new_sky_level = sky_level + value\n elif op == '-':\n new_sky_level = sky_level - value\n sky_levels[number] = new_sky_level\n write(name, 'sky', sky_levels)\n generate_sky(name, number, new_sky_level)", "def _apply_effects(state, lifted_effects, assignments):\n new_literals = set(state.literals)\n determinized_lifted_effects = []\n # Handle probabilistic effects.\n for lifted_effect in lifted_effects:\n if isinstance(lifted_effect, ProbabilisticEffect):\n chosen_effect = lifted_effect.sample()\n if chosen_effect == \"NOCHANGE\":\n continue\n if isinstance(chosen_effect, LiteralConjunction):\n for lit in chosen_effect.literals:\n determinized_lifted_effects.append(lit)\n else:\n determinized_lifted_effects.append(chosen_effect)\n else:\n determinized_lifted_effects.append(lifted_effect)\n\n for lifted_effect in determinized_lifted_effects:\n effect = ground_literal(lifted_effect, assignments)\n # Negative effect\n if effect.is_anti:\n literal = effect.inverted_anti\n if literal in new_literals:\n new_literals.remove(literal)\n for lifted_effect in determinized_lifted_effects:\n effect = ground_literal(lifted_effect, assignments)\n if not effect.is_anti:\n new_literals.add(effect)\n return state.with_literals(new_literals)", "def product_update(self, action):\n\n # if not isinstance(action, Action):\n # raise TypeError\n\n worlds = []; to_remove = [] # to_remove will be used to remove edges from tensor product\n name = 0\n for world in self.worlds:\n for event in action.events:\n assignment = copy.deepcopy(world.assignment)\n if event.precondition.semantic(self, world):\n if not event.postcondition == None:\n for i in event.postcondition.keys():\n assignment[i] = event.postcondition[i]\n world = World(name, assignment)\n worlds.append(world)\n if self.point == world.name and action.point == event.name:\n self.point = name # point in modified Kripke model\n name += 1\n else:\n to_remove.append((world.name, event.name))\n self.worlds = worlds\n\n for agent in self.agents:\n event_adj = list2mat(action.relations[agent]) # adj corresponds to adjacency matrix\n world_adj = list2mat(self.relations[agent])\n updated_adj = np.kron(world_adj, event_adj) # updated Kripke relations\n for w_e in to_remove:\n i = w_e[0]*len(action.events) + w_e[1] # index of corresponding (world, event) pair in kronecker matrix\n for j in range(updated_adj.shape[0]):\n updated_adj[i][j] = updated_adj[j][i] = 0 # deleting edges to the removed nodes / worlds\n self.relations[agent] = mat2list(updated_adj)\n\n return", "def update(self, obs, actions, rewards, new_obs):\n a0, a1 = actions\n r0, _ = rewards\n\n self.Dir[a1] += 1 # Update beliefs about adversary\n\n aux = np.max( np.dot( self.Q[new_obs], self.Dir/np.sum(self.Dir) ) )\n self.Q[obs, a0, a1] = (1 - self.alpha)*self.Q[obs, a0, a1] + self.alpha*(r0 + self.gamma*aux)", "def updateForces(self):\n for atom1 in range(0, self.numAtoms-1):\n for atom2 in range(atom1+1, self.numAtoms):\n self.calculateForce(atom1, atom2)\n \n # Multiply by constants \n for atom in range(0, self.numAtoms):\n self.atoms[atom].fx *= 48*self.e\n self.atoms[atom].fy *= 48*self.e\n self.atoms[atom].fz *= 48*self.e\n self.atoms[atom].potential *= 4*self.e", "def turn_effects(self):\n if self.side_effects[\"shield\"] > 0:\n self.side_effects[\"shield\"] -= 1", "def update_layers(self):\n\n # Para cada layer atualiza utilizando o gradiente descendente e o learning rate\n for layer in self.layers:\n layer.update_layer(self.learning_rate)" ]
[ "0.61469114", "0.61446667", "0.61446667", "0.5958415", "0.574662", "0.574662", "0.557207", "0.5543527", "0.54779965", "0.5468949", "0.5436489", "0.5336085", "0.530303", "0.52836776", "0.5258503", "0.52316934", "0.52080363", "0.51516473", "0.5130554", "0.512807", "0.51250166", "0.51148593", "0.5104589", "0.5102215", "0.50882137", "0.5076745", "0.50387347", "0.50348806", "0.5019284", "0.49864563" ]
0.87097293
0
Add an extra path effect to the element.
def add_extra_path_effect(self, name: str, effect: pe.AbstractPathEffect) -> None: super().add_extra_path_effect(name, effect) self.update_path_effects()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def add_extra_path_effect(self, name: str,\n effect: pe.AbstractPathEffect) -> None:\n self.extra_path_effects[name] = effect", "def update_path_effects(self) -> None:\n effects = list(self.extra_path_effects.values())\n effects.append(pe.Normal())\n self.set_path_effects(effects)", "def update_path_effects(self) -> None:\n effects = list(self.extra_path_effects.values())\n effects.append(pe.Normal())\n self.set_path_effects(effects)", "def remove_extra_path_effect(self, name: str):\n super().remove_extra_path_effect(name)\n self.update_path_effects()", "def remove_extra_path_effect(self, name: str):\n super().remove_extra_path_effect(name)\n self.update_path_effects()", "def addPath(self, path=[]):\n if path:\n path = [\n self.transform_reverse.transformPoints(pts) for pts in path\n ]\n if self.trace:\n self.path.append(path)\n else:\n self.drawPath(path)", "def add_to_path(self, additional_path):\n\n return self.__class__(f\"{additional_path}/{self.full_path}\")", "def addPath(newList, refnode):\n ele = inkex.etree.Element('{http://www.w3.org/2000/svg}path')\n ele.set('d', simplepath.formatPath(newList))\n refnode.xpath('..')[0].append(ele)\n return ele", "def remove_extra_path_effect(self, name: str):\n self.extra_path_effects.pop(name)", "def AddPath(*args, **kwargs):\n return _gdi_.GraphicsPath_AddPath(*args, **kwargs)", "def add_path(self, path):\n\n for i in range(1, len(path)):\n self.add_edge(path[i], path[i - 1])", "def add_path(self, path: Path):\n self._paths.append(path)\n path.set_end_of_line_callback(self.end_of_line)", "def add_path_for_monitoring(self, path, prefix):\n pass", "def append(self, path):\n self.paths.append(path)\n self.time += path.time", "def extend_path(self, ext):\n ext = str(ext)\n self._path.append(ext)", "def add_path(self, path_name):\n path = PathInfo()\n path._path = path_name\n self._paths.append(path)\n return path", "def path(self):\n self.renderer.begin_rendering(\"path\")\n self.renderer.draw_polyline_3d(self.guides, self.renderer.white())\n self.renderer.end_rendering()", "def path(self, new_path):\n if new_path == self.path:\n return\n\n self._path.append(new_path)", "def _addpath(d, atend=None):\n if atend:\n sys.path = sys.path + [d]\n else:\n sys.path = [d] + sys.path", "def _addpath(d, atend=None):\n if atend:\n sys.path = sys.path + [d]\n else:\n sys.path = [d] + sys.path", "def add_path(self, path, path_item):\n if path not in self._swagger:\n self._swagger[path] = path_item\n else:\n for method, definition in path_item.items():\n if definition is not None:\n setattr(self._swagger[path], method, definition)", "def add(self, path):\r\n return self.paths.append(path)", "def AddPath(self, path):\n self.paths.append(str(path))\n self.paths.sort()", "def _add_ends(self):\n\n del self.extension_patch1\n del self.extension_patch2\n\n path1, path2 = self.ax.get_axes_locator().get_path_ends()\n fc=mpl.rcParams['axes.facecolor']\n ec=mpl.rcParams['axes.edgecolor']\n linewidths=0.5*mpl.rcParams['axes.linewidth']\n self.extension_patch1 = PathPatch(path1,\n fc=fc, ec=ec, lw=linewidths,\n zorder=2.,\n transform=self.ax.transAxes,\n clip_on=False)\n self.extension_patch2 = PathPatch(path2,\n fc=fc, ec=ec, lw=linewidths,\n zorder=2.,\n transform=self.ax.transAxes,\n clip_on=False)\n self.ax.add_artist(self.extension_patch1)\n self.ax.add_artist(self.extension_patch2)", "def append_to_path(existing, addition):\n if existing == Path.rootPath():\n return Path.rootPath() + addition\n return \"{}.{}\".format(existing, addition)", "def create_path(self, attrs, style=None, parent=None):\n if parent is None:\n parent = self.current_parent\n if parent is not None:\n if style:\n attrs['style'] = style\n return etree.SubElement(parent, svgns('path'), attrs)", "def appendleft(self, path):\n self.paths.appendleft(path)\n self.time += path.time", "def add_path(self, adapter: str, wwpn: str):\n self.paths.append((adapter, wwpn))", "def append_to_path(path, name):\n if path[-1] == '/' or path[-1] == ':':\n return path + name\n else:\n return str(path) + str('/') + str(name)", "def pathStyle(self, elem):\n if self.clipPath:\n self.closeOp = 'h n'\n return\n\n css = self.cssStack[-1]\n if 'stroke' in css and css['stroke'] != 'none':\n self.closeOp = 's'\n self.pathCloseOp = 's'\n if '#' == css['stroke'][0] or 'rgb' == css['stroke'][0:3]:\n self.epspath += ' ' + cssColor2Eps(css['stroke']) + ' XA'\n elif 'url' == css['stroke'][0:3]:\n self.alert(\"gradient strokes not supported\", elem)\n if 'fill' in css and css['fill'] != 'none':\n if self.closeOp == 's':\n self.closeOp = 'b'\n else:\n self.closeOp = 'f'\n if '#' == css['fill'][0] or 'rgb' == css['fill'][0:3]:\n self.epspath += ' ' + cssColor2Eps(css['fill']) + ' Xa'\n elif 'url' == css['fill'][0:3]:\n self.gradientFill(elem, css['fill'][5:-1])\n\n\n if 'fill-rule' in css:\n if css['fill-rule'] == 'evenodd':\n self.epspath += \" 1 XR\"\n else:\n self.epspath += \" 0 XR\"\n if 'stroke-width' in css:\n self.epspath += \" %f w\" % (self.lengthConv(self.unitConv(css['stroke-width'], 'uu')), )\n if 'stroke-linecap' in css:\n if css['stroke-linecap'] == 'butt':\n self.epspath += \" 0 J\"\n elif css['stroke-linecap'] == 'round':\n self.epspath += \" 1 J\"\n elif css['stroke-linecap'] == 'square':\n self.epspath += \" 2 J\"\n if 'stroke-linejoin' in css:\n if css['stroke-linejoin'] == 'miter':\n self.epspath += \" 0 j\"\n elif css['stroke-linejoin'] == 'round':\n self.epspath += \" 1 j\"\n elif css['stroke-linejoin'] == 'bevel':\n self.epspath += \" 2 j\"\n if 'stroke-miterlimit' in css:\n self.epspath += \" \" + css['stroke-miterlimit'] + \" M\"\n if 'stroke-dasharray' in css:\n phase = 0\n if css['stroke-dasharray'] == 'none':\n dashArray = []\n if css['stroke-dasharray'] != 'none':\n dashArrayIn = css['stroke-dasharray'].replace(',', ' ').split()\n dashArray = list(map(lambda x: \"%f\" % (x,), filter(lambda x: x > 0, map(lambda x: self.lengthConv(float(x)), dashArrayIn))))\n if 'stroke-dashoffset' in css:\n phase = float(css['stroke-dashoffset'])\n\n self.epspath += ' [ %s ] %f d' % (' '.join(dashArray), phase)" ]
[ "0.7660745", "0.6776474", "0.6776474", "0.67419755", "0.67419755", "0.640628", "0.612771", "0.6119774", "0.6047129", "0.58292586", "0.57328755", "0.5724404", "0.5654173", "0.564765", "0.56371963", "0.5637085", "0.5551509", "0.5488044", "0.5342429", "0.5342429", "0.53235936", "0.52900934", "0.52759117", "0.5241334", "0.5218745", "0.51984566", "0.51960963", "0.5188893", "0.5133224", "0.5085471" ]
0.774229
0
Update the position of the Edge based on the connected Edges.
def update_position(self): p1, p2 = connection_points_between_figure_elements(self.vertex1, self.vertex2) self.set_xdata((p1.x, p2.x)) self.set_ydata((p1.y, p2.y)) self.arrow.remove() self.arrow = create_directional_arrow(self) self.axes.add_patch(self.arrow)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _update_coords(self, change=None):\n if self.node_id:\n x, y = self.layout[self.node_id]\n self.coords = (x - self.dist, x + self.dist, y - self.dist, y + self.dist)", "def update_cell_edges(self):\n self.cells['edges'] = -1\n for c in range(self.Ncells()):\n for i,(a,b) in enumerate(circular_pairs(self.cell_to_nodes(c))):\n self.cells['edges'][c,i] = self.nodes_to_edge(a,b)", "def update(self):\n\n for node in self.nodes:\n for edge in node.edges:\n for i, edge_node in enumerate(edge.nodes):\n if edge_node.id != node.id:\n edge_node.add_edge(edge)\n\n return self", "def update(self, edges) -> None:\n for v1, v2 in edges:\n self.add(v1, v2)", "def edges(self, e):\n self._edges = e", "def _handleEdge(self):\r\n if self._aliensdown == False:\r\n for row in self.getAliens():\r\n for alien in row:\r\n if not alien is None:\r\n alien.y -= ALIEN_V_WALK\r\n self._direction = (-1)*self._direction\r\n self._aliensdown = True\r\n else:\r\n for row in self.getAliens():\r\n for alien in row:\r\n if not alien is None:\r\n alien.x += self._direction*ALIEN_H_WALK\r\n self._aliensdown = False", "def Adjust(self):\r\n if not self.srcNode() or not self.destNode():\r\n return \r\n\r\n self.prepareGeometryChange()\r\n\r\n self.setSrcPoint(self.mapFromItem(self.srcNode(), self.srcNode().outputConnectionPoint()))\r\n self.setDestPoint(self.mapFromItem(self.destNode(), self.destNode().inputConnectionPoint()))", "def update_E(self):\n self.grid.E[0, :, :, :] = self.grid.E[-1, :, :, :]", "def updateEdgeEditEmit(self):\n self.updateEdgeEdit.emit()", "def add_edge(self, e):\n v, w = e\n self[v][w] = e\n self[w][v] = e", "def update_verts(self, dx, dy):\n self._x += dx\n self._y += dy\n if self._vertex_list:\n vertices = self._vertex_list.vertices[:]\n vertices[0::2] = [x + dx for x in vertices[0::2]]\n vertices[1::2] = [y + dy for y in vertices[1::2]]\n self._vertex_list.vertices[:] = vertices\n if self._label:\n self._label.x += dx\n self._label.y += dy", "def set_right_edges(self):\n for v in self:\n for e in v.edges_list:\n e.linked[0]=v\n e.linked[1]=self[self.search_index_by_coordinates(e.linked[1].coordinates)]\n for e in self.list_of_edges:\n e.linked[0]=self[self.search_index_by_coordinates(e.linked[0].coordinates)]\n e.linked[1]=self[self.search_index_by_coordinates(e.linked[1].coordinates)]", "def addEdge(self,x,y):\r\n self.matr[x][y] = True\r\n self.matr[y][x] = True", "def add_edge(self, e):\n a, b = e\n self[a][b] = e\n self[b][a] = e", "def add_edge(self, ed):\n self.edge.append(ed)\n self.update_node2edge()", "def relativize_coordinates(self):\n if len(self.nodes) + len(self.connecting) < 1:\n return\n smallest_c = (self.nodes+self.connecting)[0].c\n for node in self.nodes+self.connecting:\n if node.c < smallest_c:\n smallest_c = node.c\n for node in self.nodes+self.connecting:\n node.c = node.c - smallest_c", "def _update_graph(self, main_graph, target_graph, radius):\n graph_connected = False\n new_node_xy = [np.random.randint(0, self.x_dim), np.random.randint(0, self.y_dim)]\n # It samples random point, and finds the closest vertex that the graph has to the sampled point\n closest_node_xy, dist = find_closest_node(main_graph, new_node_xy)\n # finds a direction vector from the found closest point, and the sampled random point\n diff = new_node_xy - closest_node_xy\n dir_vec = diff / np.linalg.norm(diff)\n # Places a new vertex by taking a step in the direction by factor of \"radius\"\n dir_vec = dir_vec * radius\n new_node_xy = closest_node_xy + dir_vec\n new_node_xy = new_node_xy.astype(int)\n if not self.check_collision(new_node_xy, closest_node_xy):\n main_graph[tuple(closest_node_xy)].append((new_node_xy, dist))\n main_graph[tuple(new_node_xy)] = []\n main_graph[tuple(new_node_xy)].append((closest_node_xy, dist))\n\n # finds the closest node from the opposing graph from the new vertex\n closest_node_from_target_xy, dist_2 = find_closest_node(target_graph, new_node_xy)\n if dist_2 < radius:\n # If the newly updated point is also close enough to the opposite graph, the two graph is connected\n if not self.check_collision(new_node_xy, closest_node_from_target_xy):\n target_graph[tuple(closest_node_from_target_xy)].append((new_node_xy, dist_2))\n target_graph[tuple(new_node_xy)] = []\n target_graph[tuple(new_node_xy)].append((closest_node_from_target_xy, dist_2))\n stack = []\n stack.append((closest_node_from_target_xy, dist_2))\n visited = set()\n while stack:\n print(stack)\n coord, dist = stack.pop()\n key = tuple(coord)\n visited.add(key)\n connections = target_graph[key]\n if key in main_graph:\n main_graph[key] = main_graph[key] + connections\n else:\n main_graph[key] = connections\n for node in connections:\n if (tuple(node[0])) not in visited:\n stack.append(node)\n graph_connected = True\n return graph_connected", "def update_E(self):\n self.grid.E[:, 0, :, :] = self.grid.E[:, -1, :, :]", "def update(self):\r\n self.g = self.create_graph()", "def update_E(self):\n self.grid.E[:, :, 0, :] = self.grid.E[:, :, -1, :]", "def update(self):\n # Move left/right=====\n self.rect.x += self.change_x\n self.rect.y += self.change_y\n visited[int(self.rect.x/32)][int(self.rect.y/32)].append(self.id)\n\n self.path.append((int(self.rect.x/32), int(self.rect.y/32)))\n\n # if(self.rect.x == goal_x) & (self.rect.y == goal_y):\n # pygame.quit()\n # sys.exit(0)\n\n self.change_x = 0\n self.change_y = 0", "def add_adj_nodes(self):\n\n for x, row in enumerate(self.grid):\n for y, cell in enumerate(row):\n if x-1 >= 0:\n cell.above = self.grid[x-1][y]\n if y+1 < len(self.grid[0]):\n cell.right = self.grid[x][y+1]\n if x+1 < len(self.grid):\n cell.below = self.grid[x+1][y]\n if y-1 >= 0:\n cell.left = self.grid[x][y-1]", "def pheromone_update(self):\n #Ordenar la lista de acuerdo con el tamaño de la lista\n self.sort_paths()\n for i, path in enumerate(self.paths):\n for j, element in enumerate(path):\n for edge in self.map.nodes_array[element[0]][element[1]].edges:\n if (j+1) < len(path):\n if edge['FinalNode'] == path[j+1]:\n edge['Pheromone'] = (1.0 - self.evaporation_factor)*edge['Pheromone'] + \\\n self.pheromone_adding_constant/float(len(path))\n else:\n edge['Pheromone'] = (1.0 - self.evaporation_factor)*edge['Pheromone']", "def draw_edges(self):\n nx.draw_networkx_edges(self.G, pos=self.positions)", "def edges(self, edges):\n\n self._edges = edges", "def update_pos(self):\n self.imgx=self.pathX[min(self.x,len(self.pathX)-1)]\\\n [min(self.y,len(self.pathX[self.x])-1)]\n self.imgy=self.pathY[min(self.x,len(self.pathY)-1)]\\\n [min(self.y,len(self.pathY[self.x])-1)]", "def mutateEdge(g, edges, directed, connected):\n if ((directed and g.e == g.n ** 2 - g.n)\n or (not directed and g.e == (g.n ** 2 - g.n) / 2)): # Complete graph\n return\n\n if (g.e > edges):\n while g.e != edges:\n removeEdge(g, directed)\n g.e -= 1\n elif (g.e < edges):\n while g.e != edges:\n addEdge(g, directed, connected)\n g.e += 1\n else: # Edge count is correct, just do an edge swap for the mutation\n removeEdge(g, directed)\n addEdge(g, directed, connected)", "def connect(self, selected):\n # Mise a jour de la matrice laplacienne\n self.LaplacianMatrix[selected[0],selected[1]] = -1\n self.LaplacianMatrix[selected[1],selected[0]] = -1\n for i in selected[0] : self.LaplacianMatrix[i,i] += 1 \n for i in selected[1] : self.LaplacianMatrix[i,i] += 1 \n # Mise a jour de la liste d'adjacence\n self.addEdge(selected[0],selected[1])\n self.addEdge(selected[1],selected[0])", "def define_edge(self):\n\n self.canvas_edge = Line(\n points=[\n self.canvas_nodes[0].pos[0] + self.nodesize[0] / 2,\n self.canvas_nodes[0].pos[1] + self.nodesize[1] / 2,\n self.canvas_nodes[1].pos[0] + self.nodesize[0] / 2,\n self.canvas_nodes[1].pos[1] + self.nodesize[1] / 2\n ],\n joint='round',\n cap='round',\n width=3\n )", "def _walk_on_edge(self, coordinates_of_edge):\n sorted_edge = list()\n edge_points = list()\n\n self.distance_matrix = cdist(coordinates_of_edge, coordinates_of_edge, metric='euclidean')\n self.distance_matrix[self.distance_matrix == 0] = 100\n\n cur_point = list(min(coordinates_of_edge, key=lambda t: t[1]))\n sorted_edge.append(cur_point)\n while 1:\n try:\n new_point, flag = self._find_closest_point(coordinates_of_edge, cur_point, sorted_edge)\n except TypeError:\n plt.scatter(sorted_edge, s=1)\n plt.xlim((0, 256))\n plt.ylim((-256, 0))\n self._save_failed_qc_image('Search for new point failed')\n break\n\n if flag:\n edge_points.append(cur_point)\n if len(edge_points) == 2:\n break\n sorted_edge.reverse()\n cur_point = sorted_edge[-1]\n else:\n cur_point = new_point\n sorted_edge.append(cur_point)\n\n basal_septal_edge = min(edge_points, key=lambda x: x[0])\n if np.all(basal_septal_edge != sorted_edge[0]):\n sorted_edge.reverse()\n\n return sorted_edge" ]
[ "0.64629555", "0.641795", "0.63651884", "0.6266439", "0.6243622", "0.6069046", "0.5965587", "0.5938171", "0.5910652", "0.589336", "0.5868739", "0.58291113", "0.58093846", "0.57940036", "0.578529", "0.57735974", "0.5755373", "0.5742247", "0.57411766", "0.5723811", "0.56988275", "0.5687816", "0.56870455", "0.5647842", "0.5643584", "0.56277037", "0.562746", "0.56219465", "0.56181955", "0.5615069" ]
0.6516109
0
Updates the applied path effects.
def update_path_effects(self) -> None: effects = list(self.extra_path_effects.values()) effects.append(pe.Normal()) self.set_path_effects(effects)
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _post_update_paths(self, **kwargs):\n\n files_updated = kwargs.get('files_updated', list())\n if not files_updated:\n return\n\n maya_utils.reload_textures(files_updated)\n\n # Dependencies are already reloaded during update paths process\n # maya_utils.reload_dependencies(files_updated)", "def add_extra_path_effect(self, name: str,\n effect: pe.AbstractPathEffect) -> None:\n super().add_extra_path_effect(name, effect)\n self.update_path_effects()", "def add_extra_path_effect(self, name: str,\n effect: pe.AbstractPathEffect) -> None:\n super().add_extra_path_effect(name, effect)\n self.update_path_effects()", "def update(self, paths):\n raise NotImplementedError", "def remove_extra_path_effect(self, name: str):\n super().remove_extra_path_effect(name)\n self.update_path_effects()", "def remove_extra_path_effect(self, name: str):\n super().remove_extra_path_effect(name)\n self.update_path_effects()", "def applyModifiers(self):\n if not self.getScopeUpdated():\n self.updateScopes()\n targets = self.getConTextModeNodes(\"target\")\n modifiers = self.getConTextModeNodes(\"modifier\")\n for target in targets:\n for modifier in modifiers:\n if modifier.applyRule(target):\n if self.getVerbose():\n print(\"applying relationship between\", modifier, target)\n\n self.add_edge(modifier, target)", "def update_path():\n #TODO update path information\n pass", "def add_extra_path_effect(self, name: str,\n effect: pe.AbstractPathEffect) -> None:\n self.extra_path_effects[name] = effect", "def update(self, **vars):\n for name in vars:\n # Use __setitem__ for all effects\n self[name] = vars[name]", "def set(self, new_path):\n\n for i in range(self.depth):\n self.path[i] = new_path[self.max_input*i:self.max_input*(i + 1)]", "def UpdateLayers(self):\n pass", "def post_load(self):\r\n for _, effect in self._effects.items():\r\n effect.post_load()", "def update(self):\n tracing = self._tracing\n self._tracing = True\n for t in self.turtles():\n t._update_data()\n t._drawturtle()\n self._tracing = tracing\n self._update()", "def update(self, **kwargs):\n for name, item in itertools.chain(\n self._cal_objs.items(),\n self._noise_objs.items()):\n logger.debug(\"update {}\".format(item))\n item.update(**kwargs)", "def update(self, *args):\n return _osgAnimation.Animation_update(self, *args)", "def apply_effects(self, item_name):\n item = self.get(item_name)\n\n # Enable commands\n for command in item.effects.get(\"enable_commands\", []):\n if command not in self.game.state.commands_enabled:\n self.game.alert(\"You unlocked the `{}` command\", command)\n self.game.state.commands_enabled.append(command)\n\n # Enable resouces\n for resources in item.effects.get(\"enable_resources\", []):\n if resources not in self.game.state.resources_enabled:\n self.game.alert(\"You can now mine *{}*.\", resources)\n self.game.state.resources_enabled.append(resources)\n\n # Enable items\n for item_name in item.effects.get(\"enable_items\", []):\n if item_name not in self.game.state.tools_enabled:\n self.game.alert(\"You can now craft ${}$.\", item_name)\n self.game.state.tools_enabled.append(item_name)\n\n # Enable research\n for research in item.effects.get(\"enable_research\", []):\n if research not in self.game.state.research_enabled:\n self.game.alert(\"You can now research @{}@.\", research)\n self.game.state.research_enabled.append(research)\n\n # Trigger flags\n for trigger in item.effects.get(\"triggers\", []):\n if trigger not in self.game.state.triggers:\n self.game.state.triggers.append(trigger)\n\n # Grant resources\n for resource in RESOURCES:\n if resource in item.effects:\n value = to_float(item.effects[resource])\n self.game.resources.add(resource, value)\n if value > 0:\n self.game.alert(\"You found *{} {}*.\", value, resource)\n else:\n self.game.alert(\"You lost *{} {}*.\", -value, resource)\n\n # Change mining difficulty\n for resource in RESOURCES:\n change = item.effects.get(f\"{resource}_mining_difficulty\", None)\n if change:\n change = to_float(change)\n self.game.mining_difficulty.multiply(resource, 1 - change)\n self.game.alert(\n \"*{}* mining difficulty reduced by {:.0%}.\", resource, change\n )\n\n # Trigger events\n self.game.events.trigger(*item.effects.get(\"events\", []))", "def update(self) -> None:\n self.all_sprites.update()", "def update(self, *args):\n return _osgAnimation.AnimationManagerBase_update(self, *args)", "def effect(self):\n # Get script's \"--what\" option value.\n what = self.options.what / 10.\n negative_kerf = False\n if what < 0.:\n what = -what\n negative_kerf = True\n\n kerf_in_mm = self.unittouu(str(what) + \" mm\")\n\n operation_list = [\"StrokeToPath\", \"SelectionUnion\",\n \"SelectionBreakApart\", \"SelectionUnion\", \"SelectionBreakApart\"]\n if negative_kerf:\n operation_list[-2] = \"SelectionIntersect\"\n\n join_ext = metaext.MetaEffect(operation_list)\n\n if not self.set_appropriate_width(kerf_in_mm):\n objectify = metaext.MetaEffect([\"ObjectToPath\"])\n objectify.effect(self.document, self.selected, self.doc_ids)\n if not self.set_appropriate_width(kerf_in_mm):\n inkex.error(\"Didn't found any selected path, breaking\")\n return\n \n join_ext.effect(self.document, self.selected, self.doc_ids)\n\n for _, node in self.selected.iteritems():\n #inkex.debug(\"node %s\" % inkex.etree.tostring(node))\n if node.tag == inkex.addNS('path', 'svg'):\n new_width = self.unittouu(\"0.5mm\")\n colour = '#ff0000' if negative_kerf else '#000000'\n style = {'stroke-width': new_width, 'fill': 'none',\n 'stroke': colour}\n style = simplestyle.formatStyle(style)\n node.set('style', style)\n # inkex.debug(\"node %s\" % inkex.etree.tostring(node))", "def update(self, *args):\n return _osgAnimation.BasicAnimationManager_update(self, *args)", "def loadPaths(self):\n for ij in self.link:\n self.link[ij].flow = 0\n for p in self.path:\n for ij in self.path[p].links:\n self.link[ij].flow += self.path[p].flow\n for ij in self.link:\n self.link[ij].updateCost()\n for p in self.path:\n self.path[p].updateCost()", "def update_path(self, action: Action, kg: KnowledgeGraph, offset=None):\n\n def offset_path_history(p, offset):\n for i, x in enumerate(p):\n if type(x) is tuple:\n new_tuple = tuple([_x[:, offset, :] for _x in x])\n p[i] = new_tuple\n else:\n p[i] = x[offset, :]\n\n # update action history\n if self.relation_only_in_path:\n action_embedding = kg.get_relation_embeddings(action.rel)\n else:\n action_embedding = self.get_action_embedding(action, kg)\n if offset is not None:\n offset_path_history(self.path, offset)\n\n self.path.append(\n self.path_encoder(action_embedding.unsqueeze(1), self.path[-1])[1]\n )", "def modify_sky(path, name, number, op, value):\n os.chdir(path)\n sky_levels = get(name, 'sky')\n sky_level = sky_levels[number]\n if op == '+':\n new_sky_level = sky_level + value\n elif op == '-':\n new_sky_level = sky_level - value\n sky_levels[number] = new_sky_level\n write(name, 'sky', sky_levels)\n generate_sky(name, number, new_sky_level)", "def _apply_effects(state, lifted_effects, assignments):\n new_literals = set(state.literals)\n determinized_lifted_effects = []\n # Handle probabilistic effects.\n for lifted_effect in lifted_effects:\n if isinstance(lifted_effect, ProbabilisticEffect):\n chosen_effect = lifted_effect.sample()\n if chosen_effect == \"NOCHANGE\":\n continue\n if isinstance(chosen_effect, LiteralConjunction):\n for lit in chosen_effect.literals:\n determinized_lifted_effects.append(lit)\n else:\n determinized_lifted_effects.append(chosen_effect)\n else:\n determinized_lifted_effects.append(lifted_effect)\n\n for lifted_effect in determinized_lifted_effects:\n effect = ground_literal(lifted_effect, assignments)\n # Negative effect\n if effect.is_anti:\n literal = effect.inverted_anti\n if literal in new_literals:\n new_literals.remove(literal)\n for lifted_effect in determinized_lifted_effects:\n effect = ground_literal(lifted_effect, assignments)\n if not effect.is_anti:\n new_literals.add(effect)\n return state.with_literals(new_literals)", "def product_update(self, action):\n\n # if not isinstance(action, Action):\n # raise TypeError\n\n worlds = []; to_remove = [] # to_remove will be used to remove edges from tensor product\n name = 0\n for world in self.worlds:\n for event in action.events:\n assignment = copy.deepcopy(world.assignment)\n if event.precondition.semantic(self, world):\n if not event.postcondition == None:\n for i in event.postcondition.keys():\n assignment[i] = event.postcondition[i]\n world = World(name, assignment)\n worlds.append(world)\n if self.point == world.name and action.point == event.name:\n self.point = name # point in modified Kripke model\n name += 1\n else:\n to_remove.append((world.name, event.name))\n self.worlds = worlds\n\n for agent in self.agents:\n event_adj = list2mat(action.relations[agent]) # adj corresponds to adjacency matrix\n world_adj = list2mat(self.relations[agent])\n updated_adj = np.kron(world_adj, event_adj) # updated Kripke relations\n for w_e in to_remove:\n i = w_e[0]*len(action.events) + w_e[1] # index of corresponding (world, event) pair in kronecker matrix\n for j in range(updated_adj.shape[0]):\n updated_adj[i][j] = updated_adj[j][i] = 0 # deleting edges to the removed nodes / worlds\n self.relations[agent] = mat2list(updated_adj)\n\n return", "def update(self, obs, actions, rewards, new_obs):\n a0, a1 = actions\n r0, _ = rewards\n\n self.Dir[a1] += 1 # Update beliefs about adversary\n\n aux = np.max( np.dot( self.Q[new_obs], self.Dir/np.sum(self.Dir) ) )\n self.Q[obs, a0, a1] = (1 - self.alpha)*self.Q[obs, a0, a1] + self.alpha*(r0 + self.gamma*aux)", "def updateForces(self):\n for atom1 in range(0, self.numAtoms-1):\n for atom2 in range(atom1+1, self.numAtoms):\n self.calculateForce(atom1, atom2)\n \n # Multiply by constants \n for atom in range(0, self.numAtoms):\n self.atoms[atom].fx *= 48*self.e\n self.atoms[atom].fy *= 48*self.e\n self.atoms[atom].fz *= 48*self.e\n self.atoms[atom].potential *= 4*self.e", "def turn_effects(self):\n if self.side_effects[\"shield\"] > 0:\n self.side_effects[\"shield\"] -= 1", "def update_layers(self):\n\n # Para cada layer atualiza utilizando o gradiente descendente e o learning rate\n for layer in self.layers:\n layer.update_layer(self.learning_rate)" ]
[ "0.61469114", "0.61446667", "0.61446667", "0.5958415", "0.574662", "0.574662", "0.557207", "0.5543527", "0.54779965", "0.5468949", "0.5436489", "0.5336085", "0.530303", "0.52836776", "0.5258503", "0.52316934", "0.52080363", "0.51516473", "0.5130554", "0.512807", "0.51250166", "0.51148593", "0.5104589", "0.5102215", "0.50882137", "0.5076745", "0.50387347", "0.50348806", "0.5019284", "0.49864563" ]
0.87097293
1
Add an extra path effect to the element.
def add_extra_path_effect(self, name: str, effect: pe.AbstractPathEffect) -> None: super().add_extra_path_effect(name, effect) self.update_path_effects()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def add_extra_path_effect(self, name: str,\n effect: pe.AbstractPathEffect) -> None:\n self.extra_path_effects[name] = effect", "def update_path_effects(self) -> None:\n effects = list(self.extra_path_effects.values())\n effects.append(pe.Normal())\n self.set_path_effects(effects)", "def update_path_effects(self) -> None:\n effects = list(self.extra_path_effects.values())\n effects.append(pe.Normal())\n self.set_path_effects(effects)", "def remove_extra_path_effect(self, name: str):\n super().remove_extra_path_effect(name)\n self.update_path_effects()", "def remove_extra_path_effect(self, name: str):\n super().remove_extra_path_effect(name)\n self.update_path_effects()", "def addPath(self, path=[]):\n if path:\n path = [\n self.transform_reverse.transformPoints(pts) for pts in path\n ]\n if self.trace:\n self.path.append(path)\n else:\n self.drawPath(path)", "def add_to_path(self, additional_path):\n\n return self.__class__(f\"{additional_path}/{self.full_path}\")", "def addPath(newList, refnode):\n ele = inkex.etree.Element('{http://www.w3.org/2000/svg}path')\n ele.set('d', simplepath.formatPath(newList))\n refnode.xpath('..')[0].append(ele)\n return ele", "def remove_extra_path_effect(self, name: str):\n self.extra_path_effects.pop(name)", "def AddPath(*args, **kwargs):\n return _gdi_.GraphicsPath_AddPath(*args, **kwargs)", "def add_path(self, path):\n\n for i in range(1, len(path)):\n self.add_edge(path[i], path[i - 1])", "def add_path(self, path: Path):\n self._paths.append(path)\n path.set_end_of_line_callback(self.end_of_line)", "def add_path_for_monitoring(self, path, prefix):\n pass", "def append(self, path):\n self.paths.append(path)\n self.time += path.time", "def extend_path(self, ext):\n ext = str(ext)\n self._path.append(ext)", "def add_path(self, path_name):\n path = PathInfo()\n path._path = path_name\n self._paths.append(path)\n return path", "def path(self):\n self.renderer.begin_rendering(\"path\")\n self.renderer.draw_polyline_3d(self.guides, self.renderer.white())\n self.renderer.end_rendering()", "def path(self, new_path):\n if new_path == self.path:\n return\n\n self._path.append(new_path)", "def _addpath(d, atend=None):\n if atend:\n sys.path = sys.path + [d]\n else:\n sys.path = [d] + sys.path", "def _addpath(d, atend=None):\n if atend:\n sys.path = sys.path + [d]\n else:\n sys.path = [d] + sys.path", "def add_path(self, path, path_item):\n if path not in self._swagger:\n self._swagger[path] = path_item\n else:\n for method, definition in path_item.items():\n if definition is not None:\n setattr(self._swagger[path], method, definition)", "def add(self, path):\r\n return self.paths.append(path)", "def AddPath(self, path):\n self.paths.append(str(path))\n self.paths.sort()", "def _add_ends(self):\n\n del self.extension_patch1\n del self.extension_patch2\n\n path1, path2 = self.ax.get_axes_locator().get_path_ends()\n fc=mpl.rcParams['axes.facecolor']\n ec=mpl.rcParams['axes.edgecolor']\n linewidths=0.5*mpl.rcParams['axes.linewidth']\n self.extension_patch1 = PathPatch(path1,\n fc=fc, ec=ec, lw=linewidths,\n zorder=2.,\n transform=self.ax.transAxes,\n clip_on=False)\n self.extension_patch2 = PathPatch(path2,\n fc=fc, ec=ec, lw=linewidths,\n zorder=2.,\n transform=self.ax.transAxes,\n clip_on=False)\n self.ax.add_artist(self.extension_patch1)\n self.ax.add_artist(self.extension_patch2)", "def append_to_path(existing, addition):\n if existing == Path.rootPath():\n return Path.rootPath() + addition\n return \"{}.{}\".format(existing, addition)", "def create_path(self, attrs, style=None, parent=None):\n if parent is None:\n parent = self.current_parent\n if parent is not None:\n if style:\n attrs['style'] = style\n return etree.SubElement(parent, svgns('path'), attrs)", "def appendleft(self, path):\n self.paths.appendleft(path)\n self.time += path.time", "def add_path(self, adapter: str, wwpn: str):\n self.paths.append((adapter, wwpn))", "def append_to_path(path, name):\n if path[-1] == '/' or path[-1] == ':':\n return path + name\n else:\n return str(path) + str('/') + str(name)", "def pathStyle(self, elem):\n if self.clipPath:\n self.closeOp = 'h n'\n return\n\n css = self.cssStack[-1]\n if 'stroke' in css and css['stroke'] != 'none':\n self.closeOp = 's'\n self.pathCloseOp = 's'\n if '#' == css['stroke'][0] or 'rgb' == css['stroke'][0:3]:\n self.epspath += ' ' + cssColor2Eps(css['stroke']) + ' XA'\n elif 'url' == css['stroke'][0:3]:\n self.alert(\"gradient strokes not supported\", elem)\n if 'fill' in css and css['fill'] != 'none':\n if self.closeOp == 's':\n self.closeOp = 'b'\n else:\n self.closeOp = 'f'\n if '#' == css['fill'][0] or 'rgb' == css['fill'][0:3]:\n self.epspath += ' ' + cssColor2Eps(css['fill']) + ' Xa'\n elif 'url' == css['fill'][0:3]:\n self.gradientFill(elem, css['fill'][5:-1])\n\n\n if 'fill-rule' in css:\n if css['fill-rule'] == 'evenodd':\n self.epspath += \" 1 XR\"\n else:\n self.epspath += \" 0 XR\"\n if 'stroke-width' in css:\n self.epspath += \" %f w\" % (self.lengthConv(self.unitConv(css['stroke-width'], 'uu')), )\n if 'stroke-linecap' in css:\n if css['stroke-linecap'] == 'butt':\n self.epspath += \" 0 J\"\n elif css['stroke-linecap'] == 'round':\n self.epspath += \" 1 J\"\n elif css['stroke-linecap'] == 'square':\n self.epspath += \" 2 J\"\n if 'stroke-linejoin' in css:\n if css['stroke-linejoin'] == 'miter':\n self.epspath += \" 0 j\"\n elif css['stroke-linejoin'] == 'round':\n self.epspath += \" 1 j\"\n elif css['stroke-linejoin'] == 'bevel':\n self.epspath += \" 2 j\"\n if 'stroke-miterlimit' in css:\n self.epspath += \" \" + css['stroke-miterlimit'] + \" M\"\n if 'stroke-dasharray' in css:\n phase = 0\n if css['stroke-dasharray'] == 'none':\n dashArray = []\n if css['stroke-dasharray'] != 'none':\n dashArrayIn = css['stroke-dasharray'].replace(',', ' ').split()\n dashArray = list(map(lambda x: \"%f\" % (x,), filter(lambda x: x > 0, map(lambda x: self.lengthConv(float(x)), dashArrayIn))))\n if 'stroke-dashoffset' in css:\n phase = float(css['stroke-dashoffset'])\n\n self.epspath += ' [ %s ] %f d' % (' '.join(dashArray), phase)" ]
[ "0.7660745", "0.6776474", "0.6776474", "0.67419755", "0.67419755", "0.640628", "0.612771", "0.6119774", "0.6047129", "0.58292586", "0.57328755", "0.5724404", "0.5654173", "0.564765", "0.56371963", "0.5637085", "0.5551509", "0.5488044", "0.5342429", "0.5342429", "0.53235936", "0.52900934", "0.52759117", "0.5241334", "0.5218745", "0.51984566", "0.51960963", "0.5188893", "0.5133224", "0.5085471" ]
0.774229
1
Removes the path effect with the specified name from the element.
def remove_extra_path_effect(self, name: str): super().remove_extra_path_effect(name) self.update_path_effects()
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def remove_extra_path_effect(self, name: str):\n self.extra_path_effects.pop(name)", "def remove(name):", "def remove_asset(self, name):\n if name in self.assets:\n del self.assets[name]", "def remove(self, name: str) -> None:\n del self.components[name]", "def remove_mix(self, name: str) -> None:\n self.remove(name)", "def remove_curve(self, name):\n self._curve_reg.__delitem__(name)", "def remove(self, name):\n raise NotImplementedError", "def remove_attribute(self, name):\n\n pass", "def drem(self, name):\n return self.rem(name)", "def rm(self, name: str) -> None:\n path = self.get_path(name)\n if os.path.exists(path):\n os.remove(path)", "def lrem(self, name):\n return self.rem(name)", "def remove(path):", "def remove_operation(self, name):\n\n del self.operations[name]", "def remove(self, name):\n for var in self.inputs:\n if var.name == name:\n self.inputs.remove(var)\n return\n for var in self.outputs:\n if var.name == name:\n self.outputs.remove(var)\n return", "def remove_pattern(self, name):\n self._pattern_reg.__delitem__(name)", "def remove_input(self, name):\n if name in self._inputs:\n del self._inputs[name]", "def remove(self, name, source):\n self.m.path.assert_absolute(source)\n self._run(name, ['remove', source])\n self.m.path.mock_remove_paths(source)", "def remove(self, name):\n if self.circles.has_key(name):\n del self.circles[name]\n self.cursor.execute(\"\"\"DELETE FROM sensors_powersensor WHERE target=%s\"\"\", (name,))", "def remove(self, name):\n cont = getattr(self, name)\n self.disconnect(name)\n self._exprmapper.remove(name)\n if has_interface(cont, IComponent):\n self._depgraph.remove(name)\n for obj in self.__dict__.values():\n if obj is not cont and is_instance(obj, Driver):\n obj.workflow.remove(name)\n obj.remove_references(name)\n\n return super(Assembly, self).remove(name)", "def remove(name, send_events=True, moving=False):", "def remove(self, name):\n if hasattr(self, name):\n site = getattr(self, name)\n if isinstance(site, IconSite):\n delattr(self, name)\n self._typeDict[site.type].remove(name)", "def pop_aspect(name):\n\t_aspects[name].pop()", "def removeAssetByName(self, name):\n try:\n del self.__assets[name]\n except KeyError:\n return True", "def delete_file(self, name):\n del self.files[name]", "def remove_control(self, name):\n del self._controls[name]", "def remove_light(self, name):\n if name in self._lights:\n del self._lights[name]\n else:\n raise ValueError('Light {} not in scene!'.format(name))", "def del_image(self, name):\r\n if self.images is None or name not in self.images:\r\n return\r\n l = self.images\r\n self.images = None\r\n l.setdefault('/empties/', [])\r\n # push the number on the empties list\r\n l['/empties/'].append(l[name])\r\n del l[name]\r\n self.images = l", "def unwatch(self, path):\n path_obj = Path(path)\n if not path_obj.exists():\n raise FileObserverException(\"Can not unwatch non exist path\")\n parent_path = str(path_obj.parent)\n child_paths = self._watch_dog_observed_paths.get(parent_path, [])\n if path in child_paths:\n child_paths.remove(path)\n self._observed_paths.pop(path, None)\n if not child_paths:\n self._watch_dog_observed_paths.pop(parent_path, None)\n if self._observed_watches[parent_path]:\n self._observer.unschedule(self._observed_watches[parent_path])\n self._observed_watches.pop(parent_path, None)", "def remove(self, path):\n self.__remove.append(path)\n return self", "def remove_cat(self, path: Path):\n if not self.active:\n return\n if path is None:\n return\n for i, coord in enumerate(path.path):\n self.cat[coord[1]][coord[0]].remove((path.identifier, i))" ]
[ "0.82098126", "0.6658393", "0.66141933", "0.6609292", "0.65412486", "0.64385855", "0.6330571", "0.6297923", "0.6283011", "0.6278286", "0.60900366", "0.60307115", "0.6020726", "0.59730655", "0.5940002", "0.5930177", "0.59114444", "0.58867127", "0.58836484", "0.5874422", "0.5841428", "0.5764166", "0.576313", "0.5722573", "0.5697867", "0.56928796", "0.5649853", "0.5642659", "0.5635432", "0.5628144" ]
0.75836045
1
Return the two points connecting the edges of two circles with the shortest straight line between them.
def connection_points_between_circles(center1: Vec, center2: Vec, radius1: float, radius2: float ) -> Tuple[Vec, Vec]: dir_vec = normalize(Vec(vec1=center1, vec2=center2)) p1 = center1 + dir_vec * radius1 p2 = center2 - dir_vec * radius2 return p1, p2
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def _distance2_line_endpoints(line1, line2):\n (A,B),(C,D) = line1, line2\n R2=lambda u,v: (u[0]-v[0])**2+(u[1]-v[1])**2\n pairs = zip((A,A,B,B),(C,D,C,D))\n r2 = [R2(pair[0],pair[1]) for pair in pairs]\n mini=sorted(zip(r2,pairs),key=lambda a,b: a)[0]\n #R2_min = min((R2(A,C), R2(A,D), R2(B,C), R2(B,D)))\n return mini[0], mini[1][0], mini[1][1]", "def __two_nearest_line__(b1, b2):\n distances = []\n for p in b1:\n for q in b2:\n distances.append([__distance__(p, q), (p, q)])\n distances = sorted(distances, key=lambda d: d[0])\n a1, b1 = distances[0][1][0], distances[0][1][1]\n a2, b2 = distances[1][1][0], distances[1][1][1]\n a1 = (a1[0] + (a2[0] - a1[0]) * 1 / 14, a1[1] + (a2[1] - a1[1]) * 1 / 14)\n b1 = (b1[0] + (b2[0] - b1[0]) * 1 / 14, b1[1] + (b2[1] - b1[1]) * 1 / 14)\n a2 = (a2[0] + (a1[0] - a2[0]) * 1 / 14, a2[1] + (a1[1] - a2[1]) * 1 / 14)\n b2 = (b2[0] + (b1[0] - b2[0]) * 1 / 14, b2[1] + (b1[1] - b2[1]) * 1 / 14)\n return (a1, b1), (a2, b2)", "def connection_points_between_figure_elements(element1: FigureElement,\n element2: FigureElement\n ) -> Tuple[Vec, Vec]:\n if isinstance(element1, FigureVertex):\n center1 = Vec(x1=element1.center[0], y1=element1.center[1])\n radius1 = element1.get_radius() + opts['gui']['attrs']['linewidth_offset']\n elif isinstance(element1, FigureEdge):\n x, y = element1.get_center()\n center1 = Vec(x1=x, y1=y)\n radius1 = element1.get_linewidth()\n else:\n raise ValueError\n if isinstance(element2, FigureVertex):\n center2 = Vec(x1=element2.center[0], y1=element2.center[1])\n radius2 = element2.get_radius() + opts['gui']['attrs']['linewidth_offset']\n elif isinstance(element2, FigureEdge):\n x, y = element2.get_center()\n center2 = Vec(x1=x, y1=y)\n radius2 = element2.get_linewidth()\n else:\n raise ValueError\n p1, p2 = connection_points_between_circles(center1,\n center2,\n radius1,\n radius2)\n return p1, p2", "def line_line_shortest_dist_unbounded(r1: np.ndarray, v1: np.ndarray, r2: np.ndarray, v2: np.ndarray,\n eps: float = 1e-5) -> Tuple[float, Tuple[float, float]]:\n\n # check that lines are not parallel\n # normalised dot product must not be 1 or -1\n if np.abs(np.dot(v1, v2)) < np.linalg.norm(v1) * np.linalg.norm(v2) - eps:\n R = r2 - r1\n A = np.array([[np.dot(v1, v1), -np.dot(v1, v2)],\n [np.dot(v2, v1), -np.dot(v2, v2)]])\n b = np.array([np.dot(R, v1), np.dot(R, v2)])\n t1, t2 = np.matmul(np.linalg.inv(A), b)\n d = np.linalg.norm((r1 + v1 * t1) - (r2 + v2 * t2))\n else:\n # case where two lines are parallel\n # then fix one point and find shortest distance to that point\n t1 = 0\n d, t2 = line_point_shortest_dist(r2, v2, r1)\n\n return d, (t1, t2)", "def mapping_points_between_figure_elements(element1: FigureElement,\n element2: FigureElement\n ) -> Tuple[Vec, Vec]:\n if isinstance(element1, FigureVertex):\n center1 = Vec(x1=element1.center[0], y1=element1.center[1])\n radius1 = element1.get_radius()\n elif isinstance(element1, FigureEdge):\n x, y = element1.get_center()\n center1 = Vec(x1=x, y1=y)\n radius1 = element1.get_linewidth()\n else:\n raise ValueError\n if isinstance(element2, FigureVertex):\n center2 = Vec(x1=element2.center[0], y1=element2.center[1])\n radius2 = element2.get_radius()\n elif isinstance(element2, FigureEdge):\n x, y = element2.get_center()\n center2 = Vec(x1=x, y1=y)\n radius2 = element2.get_linewidth()\n else:\n raise ValueError\n # p1, p2 = connection_points_between_circles(center1,\n # center2,\n # radius1,\n # radius2)\n p1, p2 = center1, center2\n return p1, p2", "def intersect_two_circles(x0, y0, r0, x1, y1, r1):\n # circle 1: (x0, y0), radius r0\n # circle 2: (x1, y1), radius r1\n\n d = math.sqrt((x1 - x0) ** 2 + (y1 - y0) ** 2)\n\n if d > r0 + r1:\n raise ValueError(\"non-intersecting\")\n\n if d < abs(r0 - r1):\n raise ValueError(\"one circle within the other\")\n\n if d == 0 and r0 == r1:\n raise ValueError(\"coincident circles\")\n\n a = (r0 ** 2 - r1 ** 2 + d ** 2) / (2 * d)\n h = math.sqrt(r0 ** 2 - a ** 2)\n x2 = x0 + a * (x1 - x0) / d\n y2 = y0 + a * (y1 - y0) / d\n x3 = x2 + h * (y1 - y0) / d\n y3 = y2 - h * (x1 - x0) / d\n\n x4 = x2 - h * (y1 - y0) / d\n y4 = y2 + h * (x1 - x0) / d\n\n return ((x3, y3), (x4, y4))", "def findPointOnLine(node1, node2, distance):\n m, b, _ = geometry.lineSpec(node1, node2)\n \n xy = []\n if m == True: # parallel to y axis\n xy.append(node1[0])\n if node1[1] <= node2[1]:\n xy.append(node1[1] + distance)\n else:\n xy.append(node1[1] - distance)\n \n elif m == False: # parallel to x axis\n if node1[0] <= node2[0]:\n xy.append(node1[0] + distance)\n else:\n xy.append(node1[0] - distance)\n xy.append(node1[1])\n \n else:\n x = sp.Symbol('x')\n z = (x-node1[0])**2 + (m*x+b-node1[1])**2 - distance**2\n xSolution = sp.solve(z, x)\n \n for xSol in xSolution:\n if (xSol >= node1[0] and xSol <= node2[0]) or (xSol <= node1[0] and xSol >= node2[0]):\n xy.append(xSol)\n xy.append(xSol*m + b)\n return xy", "def findNearPointOnLine(node1, node2, point):\n p=point[0]\n q=point[1]\n a=node1[0]\n b=node1[1]\n c=node2[0]\n d=node2[1]\n \n x = ((a-p)*(d-b) + (q-b)*(c-a)) / ((d-b)**2+(c-a)**2) * (d-b) + p\n y = ((a-p)*(d-b) + (q-b)*(c-a)) / ((d-b)**2+(c-a)**2) * (a-c) + q\n \n return x, y", "def get_shortest_path_edge(\n self,\n xP0,\n yP0,\n xP1,\n yP1,\n npoint_ref=1,\n debug_info=False,\n ):\n # find indices of endpoints\n if self.on_sphere:\n idxP0 = get_index_lonlat(xP0, yP0, self.xvertex, self.yvertex)\n idxP1 = get_index_lonlat(xP1, yP1, self.xvertex, self.yvertex)\n else:\n idxP0 = get_index_xy(xP0, yP0, self.xvertex, self.yvertex)\n idxP1 = get_index_xy(xP1, yP1, self.xvertex, self.yvertex)\n print('Vertex closest to P0: {:8.5f} {:8.5f}'.format(self.xvertex[idxP0], self.yvertex[idxP0]))\n print('Vertex closest to P1: {:8.5f} {:8.5f}'.format(self.xvertex[idxP1], self.yvertex[idxP1]))\n # find reference points\n x_ref, y_ref = gc_interpolate(self.xvertex[idxP0], self.yvertex[idxP0],\n self.xvertex[idxP1], self.yvertex[idxP1], npoint_ref+2)\n if self.on_sphere:\n x_ref = np.mod(x_ref[1:-1], 360)\n y_ref = np.mod(y_ref[1:-1], 360)\n # initialize an empty path\n out = EdgePath()\n # loop over reference points, find the path between these points\n idx_sp0 = idxP0\n for i in np.arange(npoint_ref):\n idx_vertex = np.minimum(i,1)\n idx_sp1 = get_index_xy(x_ref[i], y_ref[i], self.xvertex, self.yvertex)\n print(' - Vertex closest to RefP{:d}: {:8.5f} {:8.5f}'.format(i+1, self.xvertex[idx_sp1], self.yvertex[idx_sp1]))\n out_i = get_path_edge(idx_sp0, idx_sp1,\n self.vertexid, self.xvertex, self.yvertex,\n self.edgeid, self.xedge, self.yedge,\n self.edges_vertex, self.vertices_edge,\n self.on_sphere, debug_info)\n out = out + out_i\n idx_sp0 = idx_sp1\n # last path, start from end points P1\n out_n = get_path_edge(idxP1, idx_sp1,\n self.vertexid, self.xvertex, self.yvertex,\n self.edgeid, self.xedge, self.yedge,\n self.edges_vertex, self.vertices_edge,\n self.on_sphere, debug_info)\n out = out + out_n.reverse()\n return out", "def _circleCircleTangentsXY(c1,c2):\n\n a = c1[1][0]\n b = c2[1][0]\n if a>b:\n bigIsOne=True\n bigC = c1\n smallC = c2\n else:\n bigIsOne=False\n bigC = c2\n smallC = c1\n ## Consdier the triangle created by the center of the small\n ## circle, the center of the large circle, and the point at the 90\n ## degree intersection of the line from the center of the small\n ## circle to the radian of the tangent point on the large circle.\n ## This is a right triangle with one leg of length d (distance of\n ## centers), one leg of length bigR-smallR, and one leg of unknown\n ## length, beta. theta is the angle formed by d and beta, which is\n ## also the angle of one of the the tangent lines, the other being\n ## -theta.\n ## \n ## we will calulate theta as follows:\n ## beta^2 - (r2-r1)^2 = d^2\n ## beta = sqrt( d^2 - (r2-r1)^2 )\n ## theta = atan ((r2-r1)/beta)\n \n r1 = smallC[1][0]\n r2 = bigC[1][0]\n\n d = dist(c1[0],c2[0])\n mpd = mpm.mpf(d)\n dr = r2-r1\n mpdr = mpm.mpf(dr)\n\n if d <= dr: #centers too close\n raise ValueError('circleCircleTangentsXY: centers of circles too close')\n \n beta = mpm.sqrt( mpd*mpd - mpdr*mpdr)\n theta = float(mpm.atan2(dr,beta))\n\n ## now, figure out the angle created by the center of the large\n ## circle with respect to the small circle\n dd = sub(bigC[0],smallC[0])\n phi = atan2(dd[1],dd[0])\n\n ## the two lines have angle phi+theta, and phi-theta. The\n ## intersection point of these lines is at the point on the circle\n ## phi+theta+90', and phi-theta-90'\n gamma1 = phi+theta+pi/2\n gamma2 = phi-theta-pi/2\n n1 = point(cos(gamma1),sin(gamma1))\n n2 = point(cos(gamma2),sin(gamma2))\n p1 = add(scale3(n1,r1),smallC[0])\n p2 = add(scale3(n1,r2),bigC[0])\n p3 = add(scale3(n2,r1),smallC[0])\n p4 = add(scale3(n2,r2),bigC[0])\n\n l1 = l2 = []\n if bigIsOne:\n l1=line(p2,p1)\n l2=line(p4,p3)\n else:\n l1 = line(p1,p2)\n l2 = line(p3,p4)\n\n return [l1,l2]", "def find_circle_line_intersection(P0, r0, P1):\n\t\n\tx_offset, y_offset = P0\n\tx0, y0 = 0, 0\n\tx1, y1 = P1\n\n\tx1, y1 = x1 - x_offset, y1 - y_offset\n\n\tdx = x1 - x0\n\tdy = y1 - y0\n\tdr = math.sqrt(dx*dx + dy*dy)\n\n\tD = x0*y1 - x1*y0\n\n\tdelta0 = r0*r0*dr*dr - D*D\n\n\tx2 = (D*dy + sgn(dy)*dx*math.sqrt(delta0)) / (dr*dr)\n\ty2 = (D*dx + math.fabs(dy)*math.sqrt(delta0)) / (dr*dr)\n\n\tx3 = (D*dy - sgn(dy)*dx*math.sqrt(delta0)) / (dr*dr)\n\ty3 = (D*dx - math.fabs(dy)*math.sqrt(delta0)) / (dr*dr)\n\n\tx2 += x_offset\n\tx3 += x_offset\n\ty2 += y_offset\n\ty3 += y_offset\n\n\treturn np.array([[x2, y2], [x3, y3]])", "def shortest_line_to_point(point_a, point_b, point_c): # where a and b are on spin axis, c is the point spinning round\n axis_vect = np.subtract(point_a, point_b)\n axis_mag = magnitude(point_a, point_b)\n unit_axis = np.divide(axis_vect, axis_mag) # unit of pp\n # pp' constants - p\n\n # pp dot u\n t = np.sum(np.dot(unit_axis, unit_axis))\n c = np.sum(np.dot(np.subtract(point_b, point_c), unit_axis))\n p = -c / t\n project_point_on_axis_add = (np.multiply(unit_axis, p))\n project_point_on_axis = project_point_on_axis_add + point_b\n distance = magnitude(point_c, project_point_on_axis)\n return distance, project_point_on_axis", "def find_circle_intersection(shape0_name, r0, shape1_name, r1):\n\n\tP0 = shape_name_to_coordinates[shape0_name]\n\tP1 = shape_name_to_coordinates[shape1_name]\n\n\t# distance_between_centers\n\td = np.linalg.norm(P0 - P1)\n\n\tif d > r0 + r1:\n\n\t\tfirst_circle = find_circle_line_intersection(P0, r0, P1)\n\t\tsecond_circle = find_circle_line_intersection(P1, r1, P0)\n\t\tpoints = np.concatenate((first_circle, second_circle))\n\t\tclose = find_closest_two_points(points)\n\t\treturn close\n\n\n\ta = 0.5 * (r0 * r0 - r1 * r1 + d * d ) / d\n\tP2 = P0 + a * (P1 - P0) / d\n\t\n\th = math.sqrt(r0 * r0 - a * a)\n\n\tx0, y0 = P0\n\tx1, y1 = P1\n\tx2, y2 = P2\n\n\tx3 = x2 + h * (y1 - y0) / d\n\ty3 = y2 - h * (x1 - x0) / d\n\n\tx4 = x2 - h * (y1 - y0) / d\n\ty4 = y2 + h * (x1 - x0) / d\n\n\treturn np.array([[x3, y3], [x4, y4]])", "def free_line(p, eps, s, dps1, dps2, ds):\n px = p[0]\n py = p[1]\n s1x = s[0, 0]\n s1y = s[0, 1]\n s2x = s[1, 0]\n s2y = s[1, 1]\n if s1x == s2x and s1y == s2y:\n if eucl_dist(p, s[0]) > eps:\n lf = [-1, -1]\n else:\n lf = [0, 1]\n else:\n if point_to_seg(p, s[0], s[1], dps1, dps2, ds) > eps:\n # print(\"No Intersection\")\n lf = [-1, -1]\n else:\n segl = eucl_dist(s[0], s[1])\n segl2 = segl * segl\n intersect = circle_line_intersection(px, py, s1x, s1y, s2x, s2y, eps)\n if intersect[0][0] != intersect[1][0] or intersect[0][1] != intersect[1][1]:\n i1x = intersect[0, 0]\n i1y = intersect[0, 1]\n u1 = (((i1x - s1x) * (s2x - s1x)) + ((i1y - s1y) * (s2y - s1y))) / segl2\n\n i2x = intersect[1, 0]\n i2y = intersect[1, 1]\n u2 = (((i2x - s1x) * (s2x - s1x)) + ((i2y - s1y) * (s2y - s1y))) / segl2\n ordered_point = sorted((0, 1, u1, u2))\n lf = ordered_point[1:3]\n else:\n if px == s1x and py == s1y:\n lf = [0, 0]\n elif px == s2x and py == s2y:\n lf = [1, 1]\n else:\n i1x = intersect[0][0]\n i1y = intersect[0][1]\n u1 = (((i1x - s1x) * (s2x - s1x)) + ((i1y - s1y) * (s2y - s1y))) / segl2\n if 0 <= u1 <= 1:\n lf = [u1, u1]\n else:\n lf = [-1, -1]\n return lf", "def _distance2_line_segments(line1, line2, h_line1=None, h_line2=None):\n h_line1 = _homogenous_line(*line1) if h_line1 is None else h_line1\n h_line2 = _homogenous_line(*line2) if h_line2 is None else h_line2\n\n r_11 = _distance2_point_to_h_line(line1[0], h_line2), line2\n r_12 = _distance2_point_to_h_line(line1[1], h_line2), line2\n r_21 = _distance2_point_to_h_line(line2[0], h_line1), line1\n r_22 = _distance2_point_to_h_line(line2[1], h_line1), line1\n\n tests = sorted((r_11,r_12,r_21,r_22), key=lambda x: x[0][0])\n # check for validity starting with the closest point\n for (r2, ps), line in tests:\n if _point_within_bounds(line,ps):\n return r2, ps, line #0 if line==line1 else 1\n\n # none of the corner points is close to any of the line\n # --> line separation is simply the closest distance of\n # corner points\n\n r2, p1, p2 = _distance2_line_endpoints(line1, line2)\n\n return r2, p1, p2", "def getIntersection(line1, line2):\r\n\r\n rho1, theta1 = line1[0]\r\n rho2, theta2 = line2[0]\r\n\r\n a = np.array([\r\n [np.cos(theta1), np.sin(theta1)],\r\n [np.cos(theta2), np.sin(theta2)]\r\n ])\r\n\r\n b = np.array([[rho1], [rho2]])\r\n\r\n x, y = np.linalg.solve(a, b)\r\n\r\n x = int(x[0])\r\n y = int(y[0])\r\n\r\n return [np.round(y), np.round(x)]", "def TwoPoints(self, p1, p2):\n\n p1 = base.getvector(p1)\n if len(p1) == 2:\n p1 = np.r_[p1, 1]\n p2 = base.getvector(p2)\n if len(p2) == 2:\n p2 = np.r_[p2, 1]\n\n return Line2(np.cross(p1, p2))", "def connect_lines(horizontal_lines, vertical_lines):\n horizontal = []\n vertical = []\n\n for x1,y1,x2,y2 in horizontal_lines:\n closest_vertical_left = 20000\n closest_vertical_right = 20000\n for v_x1,v_y1,v_x2,v_y2 in vertical_lines:\n if abs(x1 - v_x1) < abs(closest_vertical_left):\n closest_vertical_left = x1 - v_x1\n if abs(x2 - v_x1) < abs(closest_vertical_right):\n closest_vertical_right = x2 - v_x1\n x1 = x1 - closest_vertical_left\n x2 = x2 - closest_vertical_right\n horizontal.append((x1,y1,x2,y2))\n\n for x1,y1,x2,y2 in vertical_lines:\n closest_horizontal_up = 20000\n closest_horizontal_down = 20000\n for h_x1,h_y1,h_x2,h_y2 in horizontal_lines:\n if abs(y1 - h_y1) < abs(closest_horizontal_up):\n closest_horizontal_up = y1 - h_y1\n if abs(y2 - h_y1) < abs(closest_horizontal_down):\n closest_horizontal_down = y2 - h_y1\n y1 = y1 - closest_horizontal_up\n y2 = y2 - closest_horizontal_down\n vertical.append((x1,y1,x2,y2))\n\n return (horizontal, vertical)", "def line(x1, y1, x2, y2):\r\n\r\n x1 = normalize(x1)\r\n y1 = normalize(y1)\r\n x2 = normalize(x2)\r\n y2 = normalize(y2)\r\n\r\n xdiff = max(x1, x2) - min(x1, x2)\r\n ydiff = max(y1, y2) - min(y1, y2)\r\n xdir = 1 if x1 <= x2 else -1\r\n ydir = 1 if y1 <= y2 else -1\r\n\r\n r = max(xdiff, ydiff)\r\n\r\n for i in range(r+1):\r\n x = x1\r\n y = y1\r\n\r\n if ydiff:\r\n y += (float(i) * ydiff) / r * ydir\r\n if xdiff:\r\n x += (float(i) * xdiff) / r * xdir\r\n\r\n yield (x, y)", "def twoRoadConnect(data, x1, y1, x2, y2):\n flag = False\n points = [[x1, y1]]\n if not data[y1][x1] == data[y2][x2]:\n return False, []\n if YRoadConnect(data, x1, y1, x1, y2) and XRoadConnect(data, x2, y2, x1, y2) and data[y2][x1] == 0:\n flag = True\n points.append([x1, y2])\n elif XRoadConnect(data, x1, y1, x2, y1) and YRoadConnect(data, x2, y2, x2, y1) and data[y1][x2] == 0:\n flag = True\n points.append([x2, y1])\n if flag:\n data[y1][x1] = data[y2][x2] = 0\n points.append([x2, y2])\n print(data)\n print(2)\n return flag, points", "def line_points(start, end):\n # Setup initial conditions\n x1, y1 = start.astuple()\n x2, y2 = end.astuple()\n dx = x2 - x1\n dy = y2 - y1\n \n # Determine how steep the line is\n is_steep = abs(dy) > abs(dx)\n \n # Rotate line\n if is_steep:\n x1, y1 = y1, x1\n x2, y2 = y2, x2\n \n # Swap start and end points if necessary and store swap state\n swapped = False\n if x1 > x2:\n x1, x2 = x2, x1\n y1, y2 = y2, y1\n swapped = True\n \n # Recalculate differentials\n dx = x2 - x1\n dy = y2 - y1\n \n # Calculate error\n error = int(dx / 2.0)\n ystep = 1 if y1 < y2 else -1\n \n # Iterate over bounding box generating points between start and end\n y = y1\n points = []\n for x in range(x1, x2 + 1):\n coord = Int2(y, x) if is_steep else Int2(x, y)\n points.append(coord)\n error -= abs(dy)\n if error < 0:\n y += ystep\n error += dx\n \n # Reverse the list if the coordinates were swapped\n if swapped:\n points.reverse()\n return points", "def get_closest_points_2d(P1, P2):\r\n\r\n A_1 = []\r\n A_2 = []\r\n\r\n for p1_id in range(0,len(P1)):\r\n d_i = 100000\r\n d_f = 0\r\n\r\n Point = []\r\n\r\n for p2_id in range(0,len(P2)):\r\n d_f = euclidean_distance_2(P1[p1_id],P2[p2_id])\r\n\r\n if d_f < d_i:\r\n Point = P2[p2_id]\r\n d_i = d_f\r\n\r\n A_1.append(Point)\r\n A_2.append(d_i)\r\n\r\n return A_1, A_2", "def intersection(line1, line2):\r\n rho1, theta1 = line1[0]\r\n rho2, theta2 = line2[0]\r\n A = np.array([[np.cos(theta1), np.sin(theta1)], [np.cos(theta2), np.sin(theta2)]])\r\n b = np.array([[rho1], [rho2]])\r\n x0, y0 = np.linalg.solve(A, b)\r\n x0, y0 = int(np.round(x0)), int(np.round(y0))\r\n return [[x0, y0]]", "def connect(ends):\n d = np.diff(ends, axis=0)[0]\n j = np.argmax(np.abs(d))\n D = d[j]\n aD = np.abs(D)\n return ends[0] + (np.outer(np.arange(aD + 1), d) + (aD >> 1)) // aD", "def get_intersect_points(line1, line2):\n intersect_points = matrix.matrix_sol([line1, line2])\n return intersect_points", "def intersection(line1, line2):\n\n rho1, theta1 = line1[0]\n rho2, theta2 = line2[0]\n A = np.array([\n [np.cos(theta1), np.sin(theta1)],\n [np.cos(theta2), np.sin(theta2)]\n ])\n b = np.array([[rho1], [rho2]])\n x0, y0 = np.linalg.solve(A, b)\n x0, y0 = int(np.round(x0)), int(np.round(y0))\n\n return [x0, y0]", "def crossLine(self, other):\n a, b = self.point\n c, d = other.point\n m, n = self.vector\n o, p = other.vector\n if n * o == m * p: # The lines are parallels\n return None\n elif self.angle == -math.pi / 2:\n return Point(a, d)\n elif other.angle == -math.pi / 2:\n return Point(b, c)\n else:\n x = (a * n * o - b * m * o - c * m * p + d * m * o) / (n * o - m * p)\n y = (x - a) * n / m + b\n return Point(x, y)", "def on_line_and_between_endpoints_2d(pt1, pt2, pt, tol=None):\r\n if tol is None:\r\n tol = get_tol_2d()\r\n return geometry.gmOnLineAndBetweenEndpointsWithTol(pt1, pt2, pt, tol)", "def great_circle_distance(pnt1, pnt2, radius):\n\t\t\tlat1 = radians(pnt1[0])\n\t\t\tlat2 = radians(pnt2[0])\n\t\t\tdLat = lat2 - lat1\n\t\t\tdLon = radians(pnt2[1]) - radians(pnt1[1])\n\t\t\ta = sin(dLat / 2.0) ** 2 + cos(lat1) * cos(lat2) * sin(dLon / 2.0) ** 2\n\t\t\treturn 2 * asin(min(1, sqrt(a))) * radius * 57.2957795", "def path(self, first, second):\r\n if not((0 <= first < self.size) and (0 <= second < self.size)):\r\n raise ValueError(\"Cannot find distances for nodes not in the graph\")\r\n if first == second:\r\n return 0\r\n dist_tracker = self._perform_dijkstra(first, second)\r\n first_dist = dist_tracker.get_min_distance(first)\r\n second_dist = dist_tracker.get_min_distance(second)\r\n if first_dist == float('inf') or second_dist == float('inf'):\r\n return []\r\n furthest = first if first_dist > second_dist else second\r\n potential_path = dist_tracker.get_min_path(furthest)\r\n if first in potential_path and second in potential_path:\r\n return potential_path\r\n return []" ]
[ "0.6925683", "0.67373735", "0.64805984", "0.64763045", "0.6326114", "0.6269599", "0.62621427", "0.6218426", "0.6215204", "0.6210706", "0.61912256", "0.61775285", "0.6175741", "0.6126969", "0.610556", "0.6078402", "0.6052879", "0.60473776", "0.5969025", "0.5966519", "0.5963086", "0.59581995", "0.5951309", "0.5943359", "0.59413624", "0.59347504", "0.5928645", "0.59262466", "0.59141386", "0.59053725" ]
0.7133297
0
Returns the two points connecting the centers of the two elements with a straight line, taking into account the circumference of the figure elements.
def connection_points_between_figure_elements(element1: FigureElement, element2: FigureElement ) -> Tuple[Vec, Vec]: if isinstance(element1, FigureVertex): center1 = Vec(x1=element1.center[0], y1=element1.center[1]) radius1 = element1.get_radius() + opts['gui']['attrs']['linewidth_offset'] elif isinstance(element1, FigureEdge): x, y = element1.get_center() center1 = Vec(x1=x, y1=y) radius1 = element1.get_linewidth() else: raise ValueError if isinstance(element2, FigureVertex): center2 = Vec(x1=element2.center[0], y1=element2.center[1]) radius2 = element2.get_radius() + opts['gui']['attrs']['linewidth_offset'] elif isinstance(element2, FigureEdge): x, y = element2.get_center() center2 = Vec(x1=x, y1=y) radius2 = element2.get_linewidth() else: raise ValueError p1, p2 = connection_points_between_circles(center1, center2, radius1, radius2) return p1, p2
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def mapping_points_between_figure_elements(element1: FigureElement,\n element2: FigureElement\n ) -> Tuple[Vec, Vec]:\n if isinstance(element1, FigureVertex):\n center1 = Vec(x1=element1.center[0], y1=element1.center[1])\n radius1 = element1.get_radius()\n elif isinstance(element1, FigureEdge):\n x, y = element1.get_center()\n center1 = Vec(x1=x, y1=y)\n radius1 = element1.get_linewidth()\n else:\n raise ValueError\n if isinstance(element2, FigureVertex):\n center2 = Vec(x1=element2.center[0], y1=element2.center[1])\n radius2 = element2.get_radius()\n elif isinstance(element2, FigureEdge):\n x, y = element2.get_center()\n center2 = Vec(x1=x, y1=y)\n radius2 = element2.get_linewidth()\n else:\n raise ValueError\n # p1, p2 = connection_points_between_circles(center1,\n # center2,\n # radius1,\n # radius2)\n p1, p2 = center1, center2\n return p1, p2", "def circumcenter(self) -> Point:\n e1, e2, e3 = self.edges\n bisector1 = e1._line.perpendicular(e1.midpoint, plane=self._plane)\n bisector2 = e2._line.perpendicular(e2.midpoint, plane=self._plane)\n return bisector1.meet(bisector2)", "def calc_centroid(x1, y1, x2, y2):\n x = x1 + ((x2 - x1) / 2.0)\n y = y1 + ((y2 - y1) / 2.0)\n return [x, y]", "def calculate_center(self):\n return [(self.startX + self.endX) / 2., (self.startY + self.endY) / 2.]", "def midpoint_line(a, b):\n return scale_vector(add_vectors(a, b), 0.5)", "def getCartesianPoints2(r, theta, center):\n x = r * np.cos(theta) + center[0]\n y = r * np.sin(theta) + center[1]\n\n return x, y", "def crossLine(self, other):\n a, b = self.point\n c, d = other.point\n m, n = self.vector\n o, p = other.vector\n if n * o == m * p: # The lines are parallels\n return None\n elif self.angle == -math.pi / 2:\n return Point(a, d)\n elif other.angle == -math.pi / 2:\n return Point(b, c)\n else:\n x = (a * n * o - b * m * o - c * m * p + d * m * o) / (n * o - m * p)\n y = (x - a) * n / m + b\n return Point(x, y)", "def center(self) -> Tuple[int, int]:\n center_x = int((self.x1 + self.x2) // 2)\n center_y = int((self.y1 + self.y2) // 2)\n return (center_x, center_y)", "def linecenter(l):\n return scale3(add(l[0],l[1]),0.5)", "def _center_distance(self):\n # Split positions in segments of two points :\n cut = np.vsplit(self.a_position, int(self.a_position.shape[0]/2))\n # Get center position and starting line position :\n center = np.mean(cut, axis=1)\n\n # ============ EUCLIDIAN DISTANCE ============\n diff = np.sqrt(np.square(center[:, np.newaxis, :] - center).sum(2))\n diff[np.tril_indices_from(diff)] = np.inf\n\n return center, diff", "def _get_x_center_pts(halfway_x, halfway_y):\n return reduce(iconcat, _get_pt_tuple(range(1, halfway_x),\n range(1, halfway_y)))", "def midpoint(p1, p2):\n return np.array([(p1[0] + p2[0]) / 2, (p1[1] + p2[1]) / 2, (p1[2] + p2[2]) / 2])", "def separation(lon1, lat1, lon2, lat2):\n lon1, lat1, lon2, lat2 = map(radians, (lon1, lat1, lon2, lat2))\n mu = (cos(lat1) * cos(lon1) * cos(lat2) * cos(lon2)\n + cos(lat1) * sin(lon1) * cos(lat2) * sin(lon2) +\n sin(lat1) * sin(lat2))\n return degrees(arccos(mu))", "def centers(self):\n return self.xc, self.yc", "def midpoint_euclidean(self, x1, y1, x2, y2):\n dist_x = abs(x1 - x2) / 2.\n dist_y = abs(y1 - y2) / 2.\n res_x = x1 - dist_x if x1 > x2 else x2 - dist_x\n res_y = y1 - dist_y if y1 > y2 else y2 - dist_y\n return res_x, res_y", "def intersect_point(self,m1,c1,m2,c2):\n\n x = (c2 - c1)/(m1 - m2)\n y = m1*x + c1\n return x, y", "def discretized_line(x_start, y_start, x_end, y_end, n_elements):\n n_pts = n_elements + 1\n x = np.linspace(x_start, x_end, n_pts)\n y = np.linspace(y_start, y_end, n_pts)\n x1 = x[:-1]\n y1 = y[:-1]\n x2 = x[1:]\n y2 = y[1:]\n return x1, y1, x2, y2", "def connection_points_between_circles(center1: Vec, center2: Vec,\n radius1: float, radius2: float\n ) -> Tuple[Vec, Vec]:\n dir_vec = normalize(Vec(vec1=center1, vec2=center2))\n p1 = center1 + dir_vec * radius1\n p2 = center2 - dir_vec * radius2\n return p1, p2", "def get_points_for_thick_line(start_x: float, start_y: float,\r\n end_x: float, end_y: float,\r\n line_width: float):\r\n vector_x = start_x - end_x\r\n vector_y = start_y - end_y\r\n perpendicular_x = vector_y\r\n perpendicular_y = -vector_x\r\n length = math.sqrt(vector_x * vector_x + vector_y * vector_y)\r\n if length == 0:\r\n normal_x = 1.0\r\n normal_y = 1.0\r\n else:\r\n normal_x = perpendicular_x / length\r\n normal_y = perpendicular_y / length\r\n r1_x = start_x + normal_x * line_width / 2\r\n r1_y = start_y + normal_y * line_width / 2\r\n r2_x = start_x - normal_x * line_width / 2\r\n r2_y = start_y - normal_y * line_width / 2\r\n r3_x = end_x + normal_x * line_width / 2\r\n r3_y = end_y + normal_y * line_width / 2\r\n r4_x = end_x - normal_x * line_width / 2\r\n r4_y = end_y - normal_y * line_width / 2\r\n points = (r1_x, r1_y), (r2_x, r2_y), (r4_x, r4_y), (r3_x, r3_y)\r\n return points", "def center(self):\n xc = (self.x.max() + self.x.min())/2.\n yc = (self.y.max() + self.y.min())/2.\n return (xc, yc)", "def points_on_circumference(center=(0, 0), r=50, n=100):\n\treturn [\n (\n center[0]+(cos(2 * pi / n * x) * r), \n center[1] + (sin(2 * pi / n * x) * r) \n\n ) for x in range(0, n + 1)]", "def midpoint(point1, point2):\n\n x, y = (int((point1[0] + point2[0]) / 2), int((point1[1] + point2[1]) / 2))\n return (x, y)", "def mid(self, line):\n return [(line.x1 + line.x2) // 2, (line.y1 + line.y2) // 2]", "def midpoint(ptA, ptB):\n return( (ptA[0] + ptB[0]) * 0.5, (ptA[1]+ ptB[1]) * 0.5 )", "def circle_center(top_aerofoil_points, bottom_aerofoil_points):\n q = np.array(top_aerofoil_points[0].coordinates) - np.array(top_aerofoil_points[1].coordinates)\n r = np.array(bottom_aerofoil_points[-1].coordinates) - np.array(bottom_aerofoil_points[-2].coordinates)\n c = np.cross(q, [0, 0, -1]) / np.linalg.norm(q)\n d = np.cross(r, [0, 0, 1]) / np.linalg.norm(r)\n radius = (q[1] - r[1]) / (d[1] - c[1])\n s = q + radius * c\n return Point(tuple(-s))", "def compute_half_arc_points(center, a, b, theta1, theta2, num_points=DEFAULT_ARC_POINTS):\n # ToDo: Add input validation to make sure we stay within a single quadrant.\n x_coords = numpy.empty(num_points)\n y_coords = numpy.empty(num_points)\n\n for i in range(0, num_points):\n theta = (theta2 - theta1) * (i / max(num_points - 1, 1)) + theta1\n fi = numpy.pi / 2 - numpy.arctan(numpy.tan(theta))\n x = center[0] + a * numpy.cos(fi)\n y = center[1] + b * numpy.sin(fi)\n x_coords[i] = x\n y_coords[i] = y\n\n return x_coords, y_coords", "def centre(self):\n n = len(self.point)\n return Point(\n sum(map(lambda p: p.x, self.point)) / n,\n sum(map(lambda p: p.y, self.point)) / n\n )", "def get_arc_center(self):\n # First two anchors and handles\n a1, h1, h2, a2 = self.points[:4]\n # Tangent vectors\n t1 = h1 - a1\n t2 = h2 - a2\n # Normals\n n1 = rotate_vector(t1, TAU / 4)\n n2 = rotate_vector(t2, TAU / 4)\n try:\n return line_intersection(\n line1=(a1, a1 + n1),\n line2=(a2, a2 + n2),\n )\n except Exception:\n warnings.warn(\"Can't find Arc center, using ORIGIN instead\")\n return np.array(ORIGIN)", "def _lines_intersection(self, other):\n\n the_slope, the_y_intercept = False, False\n\n # parallel?\n if self.slope == other.slope:\n return (\n self.y_intercept == other.y_intercept and\n self.x_value == other.x_value\n )\n\n if self.is_vertical():\n x = self.x_value\n the_slope = other.slope\n the_y_intercept = other.y_intercept\n elif other.is_vertical():\n x = other.x_value\n else:\n x = (other.y_intercept - self.y_intercept) / (self.slope - other.slope)\n\n if the_slope is None or the_slope is False:\n the_slope = self.slope\n the_y_intercept = self.y_intercept\n\n y = the_slope * x + the_y_intercept\n\n return Point(x, y)", "def _middle_point(p1, p2):\n x = int((p1.x + p2.x) / 2)\n y = int((p1.y + p2.y) / 2)\n return (x, y)" ]
[ "0.66054904", "0.64072263", "0.6248832", "0.62166214", "0.62028444", "0.61827886", "0.612428", "0.6113595", "0.6099789", "0.6065092", "0.60411304", "0.6020374", "0.60182923", "0.5980456", "0.59705496", "0.595651", "0.5934626", "0.5933855", "0.5900288", "0.58866364", "0.5885135", "0.58670765", "0.5848721", "0.5847839", "0.58434844", "0.58420396", "0.58256155", "0.58252966", "0.5824323", "0.58204" ]
0.65649503
1
This function is similar to the connection_points_between_figure_elements() function, but takes two elements in different subplots and calculates the connection points for mapping arrows between them. Because each subplot has a different coordinate system the calculations are more complicated.
def mapping_points_between_figure_elements(element1: FigureElement, element2: FigureElement ) -> Tuple[Vec, Vec]: if isinstance(element1, FigureVertex): center1 = Vec(x1=element1.center[0], y1=element1.center[1]) radius1 = element1.get_radius() elif isinstance(element1, FigureEdge): x, y = element1.get_center() center1 = Vec(x1=x, y1=y) radius1 = element1.get_linewidth() else: raise ValueError if isinstance(element2, FigureVertex): center2 = Vec(x1=element2.center[0], y1=element2.center[1]) radius2 = element2.get_radius() elif isinstance(element2, FigureEdge): x, y = element2.get_center() center2 = Vec(x1=x, y1=y) radius2 = element2.get_linewidth() else: raise ValueError # p1, p2 = connection_points_between_circles(center1, # center2, # radius1, # radius2) p1, p2 = center1, center2 return p1, p2
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def connection_points_between_figure_elements(element1: FigureElement,\n element2: FigureElement\n ) -> Tuple[Vec, Vec]:\n if isinstance(element1, FigureVertex):\n center1 = Vec(x1=element1.center[0], y1=element1.center[1])\n radius1 = element1.get_radius() + opts['gui']['attrs']['linewidth_offset']\n elif isinstance(element1, FigureEdge):\n x, y = element1.get_center()\n center1 = Vec(x1=x, y1=y)\n radius1 = element1.get_linewidth()\n else:\n raise ValueError\n if isinstance(element2, FigureVertex):\n center2 = Vec(x1=element2.center[0], y1=element2.center[1])\n radius2 = element2.get_radius() + opts['gui']['attrs']['linewidth_offset']\n elif isinstance(element2, FigureEdge):\n x, y = element2.get_center()\n center2 = Vec(x1=x, y1=y)\n radius2 = element2.get_linewidth()\n else:\n raise ValueError\n p1, p2 = connection_points_between_circles(center1,\n center2,\n radius1,\n radius2)\n return p1, p2", "def draw_mappings(self, mapping: Mapping) -> None:\n for graph_element1, graph_element2 in mapping.items():\n figure_element1 = self.graph_to_figure[graph_element1]\n figure_element2 = self.graph_to_figure[graph_element2]\n p1, p2 = mapping_points_between_figure_elements(figure_element1,\n figure_element2)\n patch = ConnectionPatch(\n xyA=(p1.x, p1.y),\n xyB=(p2.x, p2.y),\n coordsA=\"data\",\n coordsB=\"data\",\n axesA=self.subplot,\n axesB=self.subplot2,\n arrowstyle=\"->\",\n clip_on=False,\n )\n figure_element1.mapping_left = patch\n figure_element2.mapping_right = patch\n self.mappings.add(patch)\n self.subplot.add_artist(patch)\n self.redraw()", "def compare(self, other, scale=1.0):\n import matplotlib.pyplot as plt\n from matplotlib.collections import PatchCollection\n from matplotlib.patches import Polygon, FancyArrow\n\n fig = plt.figure(figsize=(10, 10))\n ax = fig.add_subplot(1, 1, 1)\n\n rects = []\n arrows = []\n for p, module in enumerate(self.modules):\n for a, fragment in enumerate(module):\n corners = fragment.corners()[:, :2] # Drop the Z dimension\n corner1, corner1_opp = corners[0], corners[2]\n\n rects.append(Polygon(corners))\n if a in {0, 7}:\n cx, cy, _ = fragment.centre()\n ax.text(cx, cy, str(a),\n verticalalignment='center',\n horizontalalignment='center')\n elif a == 4:\n cx, cy, _ = fragment.centre()\n ax.text(cx, cy, 'p{}'.format(p),\n verticalalignment='center',\n horizontalalignment='center')\n\n panel2 = other.modules[p][a]\n corners2 = panel2.corners()[:, :2]\n corner2, corner2_opp = corners2[0], corners2[2]\n dx, dy = corner2 - corner1\n if not (dx == dy == 0):\n sx, sy = corner1\n arrows.append(FancyArrow(\n sx, sy, scale * dx, scale * dy, width=5, head_length=4\n ))\n\n dx, dy = corner2_opp - corner1_opp\n if not (dx == dy == 0):\n sx, sy = corner1_opp\n arrows.append(FancyArrow(\n sx, sy, scale * dx, scale * dy, width=5, head_length=5\n ))\n\n pc = PatchCollection(rects, facecolor=(0.75, 1.0, 0.75), edgecolor=None)\n ax.add_collection(pc)\n ac = PatchCollection(arrows)\n ax.add_collection(ac)\n\n # Set axis limits to fit all shapes, with some margin\n all_x = np.concatenate([s.xy[:, 0] for s in arrows + rects])\n all_y = np.concatenate([s.xy[:, 1] for s in arrows + rects])\n ax.set_xlim(all_x.min() - 20, all_x.max() + 20)\n ax.set_ylim(all_y.min() - 40, all_y.max() + 20)\n\n ax.set_title('Geometry comparison: {} → {}'\n .format(self.filename, other.filename))\n ax.text(1, 0, 'Arrows scaled: {}×'.format(scale),\n horizontalalignment=\"right\", verticalalignment=\"bottom\",\n transform=ax.transAxes)\n return ax", "def connect_elements(self, event: matplotlib.backend_bases.LocationEvent,\n element: 'FigureElement') -> None:\n if self.selected_element is None:\n self.selected_element = element\n element.add_extra_path_effect('selection',\n pe.Stroke(linewidth=5,\n foreground='b'))\n return\n graph = self._get_connected_graph(event.inaxes)\n element1 = self.graph_to_figure.inverse[self.selected_element][0]\n element2 = self.graph_to_figure.inverse[element][0]\n if self.selected_element.axes != element.axes:\n if event.guiEvent.CmdDown():\n log.debug('Adding Attribute Requirement.')\n self._add_attr_requirement(element1, element2)\n else:\n log.debug('Adding Mapping.')\n self._add_mapping(element1, element2)\n elif isinstance(element1, Vertex) and isinstance(element2, Vertex):\n log.debug('Connecting Vertices.')\n self._add_edge(graph, element1, element2)\n self.selected_element.remove_extra_path_effect('selection')\n self.selected_element = None\n self._redraw_graph()", "def plot_links_2d_intra(epo1: mne.Epochs, epo2: mne.Epochs,\n C1: np.ndarray, C2: np.ndarray,\n threshold: str='auto', steps: int=2):\n\n # extract sensor infos and transform loc to fit with headmodel\n loc1 = copy(np.array([ch['loc'][:3] for ch in epo1.info['chs']]))\n loc1 = transform_2d_intra(loc1, traX=-0.178, traY=0.012, traZ=0, rotZ=(-np.pi/2))\n\n loc2 = copy(np.array([ch['loc'][:3] for ch in epo2.info['chs']]))\n loc2 = transform_2d_intra(loc2, traX=0.178, traY=0.012, traZ=0, rotZ=(-np.pi/2))\n\n ctr1 = np.nanmean(loc1, 0)\n ctr2 = np.nanmean(loc2, 0)\n \n # Calculate vmin and vmax for colormap as min and max [C1, C2]\n Cmax1=np.nanmax(C1[:])\n Cmax2=np.nanmax(C2[:])\n Cmax=[]\n Cmax=[Cmax1, Cmax2]\n vmax=np.nanmax(Cmax)\n Cmin1=np.nanmin(C1[:])\n Cmin2=np.nanmin(C2[:])\n Cmin=[]\n Cmin=[Cmin1, Cmin2]\n vmin=np.min(Cmin)\n\n # Calculate automatic threshold\n if threshold == 'auto':\n threshold = np.max([np.median(C1, 0),np.median(C2,0)])+np.max([np.std(C1, 0),np.std(C2, 0)])\n else:\n threshold = threshold\n \n\n # Define colormap for both participant\n cmap_p = matplotlib.cm.get_cmap('Reds')\n norm_p = matplotlib.colors.Normalize(vmin=threshold, vmax=vmax)\n cmap_n = matplotlib.cm.get_cmap('Blues_r')\n norm_n = matplotlib.colors.Normalize(vmin=vmin, vmax=-threshold)\n\n # plot links\n for e1 in range(len(loc1)):\n x1 = loc1[e1, 0]\n y1 = loc1[e1, 1]\n for e2 in range(len(loc1)):\n x2 = loc1[e2, 0]\n y2 = loc1[e2, 1]\n if C1[e1, e2] >= threshold:\n color_p = cmap_p(norm_p(C1[e1, e2]))\n if steps <= 2:\n weight = 0.2 +1.6*((C1[e1, e2]-threshold)/(np.nanmax(vmax-threshold)))\n plt.plot([loc1[e1, 0], loc1[e2, 0]],\n [loc1[e1, 1], loc1[e2, 1]],\n '-', color=color_p, linewidth=weight)\n else:\n alphas = np.linspace(0, 1, steps)\n weight = 0.2 +1.6*((C1[e1, e2]-threshold)/(np.nanmax(vmax-threshold)))\n for idx in range(len(alphas)-1):\n a = alphas[idx]\n b = alphas[idx+1]\n xn = ((1-a)**3 * x1 +\n 3 * (1-a)**2 * a * (2 * x1 - ctr1[0]) +\n 3 * (1-a) * a**2 * (2 * x2 - ctr1[0]) +\n a**3 * x2)\n xnn = ((1-b)**3 * x1 +\n 3 * (1-b)**2 * b * (2 * x1 - ctr1[0]) +\n 3 * (1-b) * b**2 * (2 * x2 - ctr1[0]) +\n b**3 * x2)\n yn = ((1-a)**3 * y1 +\n 3 * (1-a)**2 * a * (2 * y1 - ctr1[1]) +\n 3 * (1-a) * a**2 * (2 * y2 - ctr1[1]) +\n a**3 * y2)\n ynn = ((1-b)**3 * y1 +\n 3 * (1-b)**2 * b * (2 * y1 - ctr1[1]) +\n 3 * (1-b) * b**2 * (2 * y2 - ctr1[1]) +\n b**3 * y2)\n plt.plot([xn, xnn], [yn, ynn],\n '-', color=color_p, linewidth=weight)\n if C1[e1, e2] <= -threshold:\n color_n = cmap_n(norm_n(C1[e1, e2]))\n if steps <= 2:\n weight = 0.2 +1.6*((-C1[e1, e2]-threshold)/(np.nanmax(vmax-threshold)))\n plt.plot([loc1[e1, 0], loc1[e2, 0]],\n [loc1[e1, 1], loc1[e2, 1]],\n '-', color=color_n, linewidth=weight)\n else:\n alphas = np.linspace(0, 1, steps)\n weight = 0.2 +1.6*((-C1[e1, e2]-threshold)/(np.nanmax(vmax-threshold)))\n for idx in range(len(alphas)-1):\n a = alphas[idx]\n b = alphas[idx+1]\n xn = ((1-a)**3 * x1 +\n 3 * (1-a)**2 * a * (2 * x1 - ctr1[0]) +\n 3 * (1-a) * a**2 * (2 * x2 - ctr1[0]) +\n a**3 * x2)\n xnn = ((1-b)**3 * x1 +\n 3 * (1-b)**2 * b * (2 * x1 - ctr1[0]) +\n 3 * (1-b) * b**2 * (2 * x2 - ctr1[0]) +\n b**3 * x2)\n yn = ((1-a)**3 * y1 +\n 3 * (1-a)**2 * a * (2 * y1 - ctr1[1]) +\n 3 * (1-a) * a**2 * (2 * y2 - ctr1[1]) +\n a**3 * y2)\n ynn = ((1-b)**3 * y1 +\n 3 * (1-b)**2 * b * (2 * y1 - ctr1[1]) +\n 3 * (1-b) * b**2 * (2 * y2 - ctr1[1]) +\n b**3 * y2)\n plt.plot([xn, xnn], [yn, ynn],\n '-', color=color_n, linewidth=weight)\n\n for e1 in range(len(loc2)):\n x1 = loc2[e1, 0]\n y1 = loc2[e1, 1]\n for e2 in range(len(loc2)):\n x2 = loc2[e2, 0]\n y2 = loc2[e2, 1]\n if C2[e1, e2] >= threshold:\n color_p = cmap_p(norm_p(C2[e1, e2]))\n if steps <= 2:\n weight = 0.2 +1.6*((C2[e1, e2]-threshold)/(np.nanmax(vmax-threshold)))\n plt.plot([loc2[e1, 0], loc2[e2, 0]],\n [loc2[e1, 1], loc2[e2, 1]],\n '-', color=color_p, linewidth=weight)\n else:\n alphas = np.linspace(0, 1, steps)\n weight = 0.2 +1.6*((C2[e1, e2]-threshold)/(np.nanmax(vmax-threshold)))\n for idx in range(len(alphas)-1):\n a = alphas[idx]\n b = alphas[idx+1]\n xn = ((1-a)**3 * x1 +\n 3 * (1-a)**2 * a * (2 * x1 - ctr2[0]) +\n 3 * (1-a) * a**2 * (2 * x2 - ctr2[0]) +\n a**3 * x2)\n xnn = ((1-b)**3 * x1 +\n 3 * (1-b)**2 * b * (2 * x1 - ctr2[0]) +\n 3 * (1-b) * b**2 * (2 * x2 - ctr2[0]) +\n b**3 * x2)\n yn = ((1-a)**3 * y1 +\n 3 * (1-a)**2 * a * (2 * y1 - ctr2[1]) +\n 3 * (1-a) * a**2 * (2 * y2 - ctr2[1]) +\n a**3 * y2)\n ynn = ((1-b)**3 * y1 +\n 3 * (1-b)**2 * b * (2 * y1 - ctr2[1]) +\n 3 * (1-b) * b**2 * (2 * y2 - ctr2[1]) +\n b**3 * y2)\n plt.plot([xn, xnn], [yn, ynn],\n '-', color=color_p, linewidth=weight)\n if C2[e1, e2] <= -threshold:\n color_n = cmap_n(norm_n(C2[e1, e2]))\n if steps <= 2:\n weight = 0.2 +1.6*((-C2[e1, e2]-threshold)/(np.nanmax(vmax-threshold)))\n plt.plot([loc2[e1, 0], loc2[e2, 0]],\n [loc2[e1, 1], loc2[e2, 1]],\n '-', color=color_n, linewidth=weight)\n else:\n alphas = np.linspace(0, 1, steps)\n weight = 0.2 +1.6*((-C2[e1, e2]-threshold)/(np.nanmax(vmax-threshold)))\n for idx in range(len(alphas)-1):\n a = alphas[idx]\n b = alphas[idx+1]\n xn = ((1-a)**3 * x1 +\n 3 * (1-a)**2 * a * (2 * x1 - ctr2[0]) +\n 3 * (1-a) * a**2 * (2 * x2 - ctr2[0]) +\n a**3 * x2)\n xnn = ((1-b)**3 * x1 +\n 3 * (1-b)**2 * b * (2 * x1 - ctr2[0]) +\n 3 * (1-b) * b**2 * (2 * x2 - ctr2[0]) +\n b**3 * x2)\n yn = ((1-a)**3 * y1 +\n 3 * (1-a)**2 * a * (2 * y1 - ctr2[1]) +\n 3 * (1-a) * a**2 * (2 * y2 - ctr2[1]) +\n a**3 * y2)\n ynn = ((1-b)**3 * y1 +\n 3 * (1-b)**2 * b * (2 * y1 - ctr2[1]) +\n 3 * (1-b) * b**2 * (2 * y2 - ctr2[1]) +\n b**3 * y2)\n plt.plot([xn, xnn], [yn, ynn],\n '-', color=color_n, linewidth=weight)", "def plot_links_2d_inter(epo1: mne.Epochs, epo2: mne.Epochs, C: np.ndarray, threshold: str='auto', steps: int=10):\n\n # extract sensor infos and transform loc to fit with headmodel\n loc1 = copy(np.array([ch['loc'][:3] for ch in epo1.info['chs']]))\n loc1 = transform(loc1, traX=-0.17, traY=0, traZ=0.08, rotY=(-np.pi/12), rotZ=(-np.pi/2))\n\n loc2 = copy(np.array([ch['loc'][:3] for ch in epo2.info['chs']]))\n loc2 = transform(loc2, traX=0.17, traY=0, traZ=0.08, rotY=(np.pi/12), rotZ=np.pi/2)\n\n ctr1 = np.nanmean(loc1, 0)\n ctr2 = np.nanmean(loc2, 0)\n\n # Calculate automatic threshold\n if threshold == 'auto':\n threshold = np.max(np.median(C, 0))+np.max(np.std(C, 0))\n else:\n threshold = threshold\n\n # define colormap\n cmap_p = matplotlib.cm.get_cmap('Reds')\n norm_p = matplotlib.colors.Normalize(vmin=threshold, vmax=np.nanmax(C[:]))\n cmap_n = matplotlib.cm.get_cmap('Blues_r')\n norm_n = matplotlib.colors.Normalize(vmin=np.min(C[:]), vmax=-threshold)\n\n # plot links\n for e1 in range(len(loc1)):\n x1 = loc1[e1, 0]\n y1 = loc1[e1, 1]\n for e2 in range(len(loc2)):\n x2 = loc2[e2, 0]\n y2 = loc2[e2, 1]\n if C[e1, e2] >= threshold:\n color_p = cmap_p(norm_p(C[e1, e2]))\n if steps <= 2:\n weight = 0.2 +1.6*((C[e1, e2]-threshold)/(np.nanmax(C[:]-threshold)))\n plt.plot([loc1[e1, 0], loc2[e2, 0]],\n [loc1[e1, 1], loc2[e2, 1]],\n '-', color=color_p, linewidth=weight)\n else:\n alphas = np.linspace(0, 1, steps)\n weight = 0.2 +1.6*((C[e1, e2]-threshold)/(np.nanmax(C[:]-threshold)))\n for idx in range(len(alphas)-1):\n a = alphas[idx]\n b = alphas[idx+1]\n xn = ((1-a)**3 * x1 +\n 3 * (1-a)**2 * a * (2 * x1 - ctr1[0]) +\n 3 * (1-a) * a**2 * (2 * x2 - ctr2[0]) +\n a**3 * x2)\n xnn = ((1-b)**3 * x1 +\n 3 * (1-b)**2 * b * (2 * x1 - ctr1[0]) +\n 3 * (1-b) * b**2 * (2 * x2 - ctr2[0]) +\n b**3 * x2)\n yn = ((1-a)**3 * y1 +\n 3 * (1-a)**2 * a * (2 * y1 - ctr1[1]) +\n 3 * (1-a) * a**2 * (2 * y2 - ctr2[1]) +\n a**3 * y2)\n ynn = ((1-b)**3 * y1 +\n 3 * (1-b)**2 * b * (2 * y1 - ctr1[1]) +\n 3 * (1-b) * b**2 * (2 * y2 - ctr2[1]) +\n b**3 * y2)\n plt.plot([xn, xnn], [yn, ynn],\n '-', color=color_p, linewidth=weight)\n if C[e1, e2] <= -threshold:\n color_n = cmap_n(norm_n(C[e1, e2]))\n if steps <= 2:\n weight = 0.2 +1.6*((-C[e1, e2]-threshold)/(np.nanmax(C[:]-threshold)))\n plt.plot([loc1[e1, 0], loc2[e2, 0]],\n [loc1[e1, 1], loc2[e2, 1]],\n '-', color=color_n, linewidth=weight)\n else:\n alphas = np.linspace(0, 1, steps)\n weight = 0.2 +1.6*((-C[e1, e2]-threshold)/(np.nanmax(C[:]-threshold)))\n for idx in range(len(alphas)-1):\n a = alphas[idx]\n b = alphas[idx+1]\n xn = ((1-a)**3 * x1 +\n 3 * (1-a)**2 * a * (2 * x1 - ctr1[0]) +\n 3 * (1-a) * a**2 * (2 * x2 - ctr2[0]) +\n a**3 * x2)\n xnn = ((1-b)**3 * x1 +\n 3 * (1-b)**2 * b * (2 * x1 - ctr1[0]) +\n 3 * (1-b) * b**2 * (2 * x2 - ctr2[0]) +\n b**3 * x2)\n yn = ((1-a)**3 * y1 +\n 3 * (1-a)**2 * a * (2 * y1 - ctr1[1]) +\n 3 * (1-a) * a**2 * (2 * y2 - ctr2[1]) +\n a**3 * y2)\n ynn = ((1-b)**3 * y1 +\n 3 * (1-b)**2 * b * (2 * y1 - ctr1[1]) +\n 3 * (1-b) * b**2 * (2 * y2 - ctr2[1]) +\n b**3 * y2)\n plt.plot([xn, xnn], [yn, ynn],\n '-', color=color_n, linewidth=weight)", "def arrows(points_from, points_to, color='k',\n width=None, width_ratio=0.002,\n label=None, label_kw={}, margin_ratio=None, **kw):\n # convert and valid check of the points\n points_from = asarray(points_from, float)\n points_to = asarray(points_to, float)\n num_points = len(points_from)\n if len(points_to) != num_points:\n raise ValueError('Length of two group of points unmatched')\n if not width: #auto adjust arrow widt\n min_range = min(asarray(xlim()).ptp(), asarray(ylim()).ptp())\n width = min_range * width_ratio\n #vectorize colors and width if necessary\n color = kw.pop('c', color)\n if isscalar(color): color = [color] * num_points\n if isscalar(width): width = [width] * num_points\n #draw each arrow\n #?? length_include_head=True will break??\n default = {'length_includes_head':False, 'alpha':0.75}\n kw = dict(default, **kw)\n for (x0, y0), (x1, y1), w, c in zip(points_from, points_to, width, color):\n pylab.arrow(x0, y0, x1-x0, y1-y0,\n edgecolor=c, facecolor=c, width=w, **kw)\n if label: #label the arrow heads\n text_points(points_to, label, **label_kw)\n #hack fix of axis limits, otherwise some of the arrows will be invisible\n #not neccessary if the points were also scattered\n if margin_ratio is not None:\n x, y = concatenate((points_from, points_to)).T #all the points\n xmargin = x.ptp() * margin_ratio\n ymargin = y.ptp() * margin_ratio\n xlim(x.min()-xmargin, x.max()+xmargin)\n ylim(y.min()-ymargin, y.max()+xmargin)\n return", "def plot_links_3d_intra(ax: str, epo1: mne.Epochs, epo2: mne.Epochs,\n C1: np.ndarray, C2: np.ndarray, threshold: str='auto',\n steps: int=10):\n \n # extract sensor infos and transform loc to fit with headmodel \n loc1 = copy(np.array([ch['loc'][:3] for ch in epo1.info['chs']]))\n loc1 = transform(loc1, traX=0, traY=0, traZ=0.04, rotY=0, rotZ=(-np.pi/2))\n \n\n loc2 = copy(np.array([ch['loc'][:3] for ch in epo2.info['chs']]))\n loc2 = transform(loc2, traX=0, traY=0.5, traZ=0.04, rotY=0, rotZ=(-np.pi/2))\n \n\n ctr1 = np.nanmean(loc1, 0)\n ctr1[2] -= 0.2\n ctr2 = np.nanmean(loc2, 0)\n ctr2[2] -= 0.2\n\n # Calculate vmin and vmax for colormap as min and max [C1, C2]\n Cmax1=np.nanmax(C1[:])\n Cmax2=np.nanmax(C2[:])\n Cmax=[]\n Cmax=[Cmax1, Cmax2]\n vmax=np.nanmax(Cmax)\n Cmin1=np.nanmin(C1[:])\n Cmin2=np.nanmin(C2[:])\n Cmin=[]\n Cmin=[Cmin1, Cmin2]\n vmin=np.min(Cmin)\n\n # Calculate automatic threshold\n if threshold == 'auto':\n threshold = np.max([np.median(C1, 0),np.median(C2,0)])+np.max([np.std(C1, 0),np.std(C2, 0)])\n else:\n threshold = threshold\n\n # Define colormap for both participant\n cmap_p = matplotlib.cm.get_cmap('Reds')\n norm_p = matplotlib.colors.Normalize(vmin=threshold, vmax=vmax)\n cmap_n = matplotlib.cm.get_cmap('Blues_r')\n norm_n = matplotlib.colors.Normalize(vmin=vmin, vmax=-threshold)\n\n for e1 in range(len(loc1)):\n x1 = loc1[e1, 0]\n y1 = loc1[e1, 1]\n z1 = loc1[e1, 2]\n for e2 in range(len(loc1)):\n x2 = loc1[e2, 0]\n y2 = loc1[e2, 1]\n z2 = loc1[e2, 2]\n if C1[e1, e2] >= threshold:\n color_p = cmap_p(norm_p(C1[e1, e2]))\n if steps <= 2:\n weight = 0.2 +1.6*((C1[e1, e2]-threshold)/(np.nanmax(vmax-threshold)))\n ax.plot([loc1[e1, 0], loc1[e2, 0]],\n [loc1[e1, 1], loc1[e2, 1]],\n [loc1[e1, 2], loc1[e2, 2]],\n '-', color=color_p, linewidth=weight)\n else:\n alphas = np.linspace(0, 1, steps)\n weight = 0.2 +1.6*((C1[e1, e2]-threshold)/(np.nanmax(vmax-threshold)))\n for idx in range(len(alphas)-1):\n a = alphas[idx]\n b = alphas[idx+1]\n xn = ((1-a)**3 * x1 +\n 3 * (1-a)**2 * a * (2 * x1 - ctr1[0]) +\n 3 * (1-a) * a**2 * (2 * x2 - ctr1[0]) +\n a**3 * x2)\n xnn = ((1-b)**3 * x1 +\n 3 * (1-b)**2 * b * (2 * x1 - ctr1[0]) +\n 3 * (1-b) * b**2 * (2 * x2 - ctr1[0]) +\n b**3 * x2)\n yn = ((1-a)**3 * y1 +\n 3 * (1-a)**2 * a * (2 * y1 - ctr1[1]) +\n 3 * (1-a) * a**2 * (2 * y2 - ctr1[1]) +\n a**3 * y2)\n ynn = ((1-b)**3 * y1 +\n 3 * (1-b)**2 * b * (2 * y1 - ctr1[1]) +\n 3 * (1-b) * b**2 * (2 * y2 - ctr1[1]) +\n b**3 * y2)\n zn = ((1-a)**3 * z1 +\n 3 * (1-a)**2 * a * (2 * z1 - ctr1[2]) +\n 3 * (1-a) * a**2 * (2 * z2 - ctr1[2]) +\n a**3 * z2)\n znn = ((1-b)**3 * z1 +\n 3 * (1-b)**2 * b * (2 * z1 - ctr1[2]) +\n 3 * (1-b) * b**2 * (2 * z2 - ctr1[2]) +\n b**3 * z2)\n ax.plot([xn, xnn], [yn, ynn], [zn, znn],\n '-', color=color_p, linewidth=weight)\n if C1[e1, e2] <= -threshold:\n color_n = cmap_n(norm_n(C1[e1, e2]))\n if steps <= 2:\n weight = 0.2 +1.6*((-C1[e1, e2]-threshold)/(np.nanmax(vmax-threshold)))\n ax.plot([loc1[e1, 0], loc1[e2, 0]],\n [loc1[e1, 1], loc1[e2, 1]],\n [loc1[e1, 2], loc1[e2, 2]],\n '-', color=color_n, linewidth=weight)\n else:\n alphas = np.linspace(0, 1, steps)\n weight = 0.2 +1.6*((-C1[e1, e2]-threshold)/(np.nanmax(vmax-threshold)))\n for idx in range(len(alphas)-1):\n a = alphas[idx]\n b = alphas[idx+1]\n xn = ((1-a)**3 * x1 +\n 3 * (1-a)**2 * a * (2 * x1 - ctr1[0]) +\n 3 * (1-a) * a**2 * (2 * x2 - ctr1[0]) +\n a**3 * x2)\n xnn = ((1-b)**3 * x1 +\n 3 * (1-b)**2 * b * (2 * x1 - ctr1[0]) +\n 3 * (1-b) * b**2 * (2 * x2 - ctr1[0]) +\n b**3 * x2)\n yn = ((1-a)**3 * y1 +\n 3 * (1-a)**2 * a * (2 * y1 - ctr1[1]) +\n 3 * (1-a) * a**2 * (2 * y2 - ctr1[1]) +\n a**3 * y2)\n ynn = ((1-b)**3 * y1 +\n 3 * (1-b)**2 * b * (2 * y1 - ctr1[1]) +\n 3 * (1-b) * b**2 * (2 * y2 - ctr1[1]) +\n b**3 * y2)\n zn = ((1-a)**3 * z1 +\n 3 * (1-a)**2 * a * (2 * z1 - ctr1[2]) +\n 3 * (1-a) * a**2 * (2 * z2 - ctr1[2]) +\n a**3 * z2)\n znn = ((1-b)**3 * z1 +\n 3 * (1-b)**2 * b * (2 * z1 - ctr1[2]) +\n 3 * (1-b) * b**2 * (2 * z2 - ctr1[2]) +\n b**3 * z2)\n ax.plot([xn, xnn], [yn, ynn], [zn, znn],\n '-', color=color_n, linewidth=weight)\n \n for e1 in range(len(loc2)):\n x1 = loc2[e1, 0]\n y1 = loc2[e1, 1]\n z1 = loc2[e1, 2]\n for e2 in range(len(loc2)):\n x2 = loc2[e2, 0]\n y2 = loc2[e2, 1]\n z2 = loc2[e2, 2]\n if C2[e1, e2] >= threshold:\n color_p = cmap_p(norm_p(C2[e1, e2]))\n if steps <= 2:\n weight = 0.2 +1.6*((C2[e1, e2]-threshold)/(np.nanmax(vmax-threshold)))\n ax.plot([loc2[e1, 0], loc2[e2, 0]],\n [loc2[e1, 1], loc2[e2, 1]],\n [loc2[e1, 2], loc2[e2, 2]],\n '-', color=color_p, linewidth=weight)\n else:\n alphas = np.linspace(0, 1, steps)\n weight = 0.2 +1.6*((C2[e1, e2]-threshold)/(np.nanmax(vmax-threshold)))\n for idx in range(len(alphas)-1):\n a = alphas[idx]\n b = alphas[idx+1]\n xn = ((1-a)**3 * x1 +\n 3 * (1-a)**2 * a * (2 * x1 - ctr2[0]) +\n 3 * (1-a) * a**2 * (2 * x2 - ctr2[0]) +\n a**3 * x2)\n xnn = ((1-b)**3 * x1 +\n 3 * (1-b)**2 * b * (2 * x1 - ctr2[0]) +\n 3 * (1-b) * b**2 * (2 * x2 - ctr2[0]) +\n b**3 * x2)\n yn = ((1-a)**3 * y1 +\n 3 * (1-a)**2 * a * (2 * y1 - ctr2[1]) +\n 3 * (1-a) * a**2 * (2 * y2 - ctr2[1]) +\n a**3 * y2)\n ynn = ((1-b)**3 * y1 +\n 3 * (1-b)**2 * b * (2 * y1 - ctr2[1]) +\n 3 * (1-b) * b**2 * (2 * y2 - ctr2[1]) +\n b**3 * y2)\n zn = ((1-a)**3 * z1 +\n 3 * (1-a)**2 * a * (2 * z1 - ctr2[2]) +\n 3 * (1-a) * a**2 * (2 * z2 - ctr2[2]) +\n a**3 * z2)\n znn = ((1-b)**3 * z1 +\n 3 * (1-b)**2 * b * (2 * z1 - ctr2[2]) +\n 3 * (1-b) * b**2 * (2 * z2 - ctr2[2]) +\n b**3 * z2)\n ax.plot([xn, xnn], [yn, ynn], [zn, znn],\n '-', color=color_p, linewidth=weight)\n if C2[e1, e2] <= -threshold:\n color_n = cmap_n(norm_n(C2[e1, e2]))\n if steps <= 2:\n weight = 0.2 +1.6*((-C2[e1, e2]-threshold)/(np.nanmax(vmax-threshold)))\n ax.plot([loc2[e1, 0], loc2[e2, 0]],\n [loc2[e1, 1], loc2[e2, 1]],\n [loc2[e1, 2], loc2[e2, 2]],\n '-', color=color_n, linewidth=weight)\n else:\n alphas = np.linspace(0, 1, steps)\n weight = 0.2 +1.6*((-C2[e1, e2]-threshold)/(np.nanmax(vmax-threshold)))\n for idx in range(len(alphas)-1):\n a = alphas[idx]\n b = alphas[idx+1]\n xn = ((1-a)**3 * x1 +\n 3 * (1-a)**2 * a * (2 * x1 - ctr2[0]) +\n 3 * (1-a) * a**2 * (2 * x2 - ctr2[0]) +\n a**3 * x2)\n xnn = ((1-b)**3 * x1 +\n 3 * (1-b)**2 * b * (2 * x1 - ctr2[0]) +\n 3 * (1-b) * b**2 * (2 * x2 - ctr2[0]) +\n b**3 * x2)\n yn = ((1-a)**3 * y1 +\n 3 * (1-a)**2 * a * (2 * y1 - ctr2[1]) +\n 3 * (1-a) * a**2 * (2 * y2 - ctr2[1]) +\n a**3 * y2)\n ynn = ((1-b)**3 * y1 +\n 3 * (1-b)**2 * b * (2 * y1 - ctr2[1]) +\n 3 * (1-b) * b**2 * (2 * y2 - ctr2[1]) +\n b**3 * y2)\n zn = ((1-a)**3 * z1 +\n 3 * (1-a)**2 * a * (2 * z1 - ctr2[2]) +\n 3 * (1-a) * a**2 * (2 * z2 - ctr2[2]) +\n a**3 * z2)\n znn = ((1-b)**3 * z1 +\n 3 * (1-b)**2 * b * (2 * z1 - ctr2[2]) +\n 3 * (1-b) * b**2 * (2 * z2 - ctr2[2]) +\n b**3 * z2)\n ax.plot([xn, xnn], [yn, ynn], [zn, znn],\n '-', color=color_n, linewidth=weight)", "def demonstrate(points, connections, ax=None):\n\n n = connections.shape[0]\n\n if ax is None:\n ax = plt.gca()\n\n ax.plot()\n\n ax.scatter(*points, c='k', alpha=.2)\n [ax.annotate(i, (points[0, i], points[1, i])) for i in range(n)]\n\n for i in range(n):\n for j in range(n):\n if connections[i, j]:\n ax.plot([points[0, i], points[0, j]], [points[1, i], points[1, j]], 'k', alpha=0.2)", "def viz_2D_topomap_intra (epo1: mne.Epochs, epo2: mne.Epochs,\n C1: np.ndarray, C2: np.ndarray,\n threshold: float=0.95, steps: int=2,\n lab: bool = False):\n\n # defining head model and adding sensors\n fig = plt.figure()\n ax = fig.add_subplot(111, aspect = 1)\n ax.axis(\"off\")\n plot_2d_topomap_intra(ax)\n # bads are represented as squares\n plot_sensors_2d_intra(epo1, epo2, lab = lab)\n # plotting links according to sign (red for positive values,\n # blue for negative) and value (line thickness increases\n # with the strength of connectivity)\n plot_links_2d_intra(epo1, epo2, C1=C1, C2=C2, threshold=threshold, steps=steps)\n plt.tight_layout()\n plt.show()\n\n return (ax)", "def draw_matches(img1, keypoints1, img2, keypoints2, plot_title=\"\"):\n figure = plt.figure(figsize=(10, 5))\n ax1 = plt.subplot(1, 2, 1)\n ax2 = plt.subplot(1, 2, 2)\n img1 = cv2.drawKeypoints(img1, keypoints1, None)\n img2 = cv2.drawKeypoints(img2, keypoints2, None)\n ax1.imshow(img1)\n ax2.imshow(img2)\n for kp1, kp2 in zip(keypoints1, keypoints2):\n con = ConnectionPatch(xyA=kp2.pt, xyB=kp1.pt,\n coordsA=\"data\", coordsB=\"data\",\n axesA=ax2, axesB=ax1, color=np.random.rand(3, ))\n ax2.add_patch(con)\n\n plt.title(plot_title)\n plt.show()\n figure.savefig(\"data/results/\" + plot_title.replace(\" \", \"-\").replace(\".\", \"-\") + '.png', dpi=100,\n bbox_inches='tight')", "def interface_endpoints_coords(cell_a, cell_b):\n corners_mask = interface_endpoints_mask(cell_a, cell_b)\n corners_mask = binary_dilation(corners_mask, selem=np.ones((5, 5)))\n if np.all(~corners_mask):\n raise Exception(\"Zero endpoints found between these cells\")\n # Label the corners and use their centroids as coordinates of the cell interface\n corner_labels = label(corners_mask)\n total = np.max(corner_labels)\n if total == 2:\n centroid_0 = regionprops(corner_labels)[0].centroid\n centroid_1 = regionprops(corner_labels)[1].centroid\n endpoints = (centroid_0, centroid_1)\n else:\n raise Exception(f\"Expected 2 corner mask regions; found {total}\")\n\n return endpoints", "def plot_links_3d_inter(ax: str, epo1: mne.Epochs, epo2: mne.Epochs, C: np.ndarray, threshold: str='auto', steps: int=10):\n \n # extract sensor infos and transform loc to fit with headmodel \n loc1 = copy(np.array([ch['loc'][:3] for ch in epo1.info['chs']]))\n loc1 = transform(loc1, traX=-0.17, traY=0, traZ=0.08, rotY=(-np.pi/12), rotZ=(-np.pi/2))\n \n\n loc2 = copy(np.array([ch['loc'][:3] for ch in epo2.info['chs']]))\n loc2 = transform(loc2, traX=0.17, traY=0, traZ=0.08, rotY=(np.pi/12), rotZ=np.pi/2)\n \n\n ctr1 = np.nanmean(loc1, 0)\n ctr1[2] -= 0.2\n ctr2 = np.nanmean(loc2, 0)\n ctr2[2] -= 0.2\n\n # Calculate automatic threshold\n if threshold == 'auto':\n threshold = np.max(np.median(C, 0))+np.max(np.std(C, 0))\n else:\n threshold = threshold\n\n # define colormap\n cmap_p = matplotlib.cm.get_cmap('Reds')\n norm_p = matplotlib.colors.Normalize(vmin=threshold, vmax=np.nanmax(C[:]))\n cmap_n = matplotlib.cm.get_cmap('Blues_r')\n norm_n = matplotlib.colors.Normalize(vmin=np.min(C[:]), vmax=-threshold)\n\n # plot links\n for e1 in range(len(loc1)):\n x1 = loc1[e1, 0]\n y1 = loc1[e1, 1]\n z1 = loc1[e1, 2]\n for e2 in range(len(loc2)):\n x2 = loc2[e2, 0]\n y2 = loc2[e2, 1]\n z2 = loc2[e2, 2]\n if C[e1, e2] >= threshold:\n color_p = cmap_p(norm_p(C[e1, e2]))\n if steps <= 2:\n weight = 0.2 +1.6*((C[e1, e2]-threshold)/(np.nanmax(C[:]-threshold)))\n ax.plot([loc1[e1, 0], loc2[e2, 0]],\n [loc1[e1, 1], loc2[e2, 1]],\n [loc1[e1, 2], loc2[e2, 2]],\n '-', color=color_p, linewidth=weight)\n else:\n alphas = np.linspace(0, 1, steps)\n weight = 0.2 +1.6*((C[e1, e2]-threshold)/(np.nanmax(C[:]-threshold)))\n for idx in range(len(alphas)-1):\n a = alphas[idx]\n b = alphas[idx+1]\n xn = ((1-a)**3 * x1 +\n 3 * (1-a)**2 * a * (2 * x1 - ctr1[0]) +\n 3 * (1-a) * a**2 * (2 * x2 - ctr2[0]) +\n a**3 * x2)\n xnn = ((1-b)**3 * x1 +\n 3 * (1-b)**2 * b * (2 * x1 - ctr1[0]) +\n 3 * (1-b) * b**2 * (2 * x2 - ctr2[0]) +\n b**3 * x2)\n yn = ((1-a)**3 * y1 +\n 3 * (1-a)**2 * a * (2 * y1 - ctr1[1]) +\n 3 * (1-a) * a**2 * (2 * y2 - ctr2[1]) +\n a**3 * y2)\n ynn = ((1-b)**3 * y1 +\n 3 * (1-b)**2 * b * (2 * y1 - ctr1[1]) +\n 3 * (1-b) * b**2 * (2 * y2 - ctr2[1]) +\n b**3 * y2)\n zn = ((1-a)**3 * z1 +\n 3 * (1-a)**2 * a * (2 * z1 - ctr1[2]) +\n 3 * (1-a) * a**2 * (2 * z2 - ctr2[2]) +\n a**3 * z2)\n znn = ((1-b)**3 * z1 +\n 3 * (1-b)**2 * b * (2 * z1 - ctr1[2]) +\n 3 * (1-b) * b**2 * (2 * z2 - ctr2[2]) +\n b**3 * z2)\n ax.plot([xn, xnn], [yn, ynn], [zn, znn],\n '-', color=color_p, linewidth=weight)\n if C[e1, e2] <= -threshold:\n color_n = cmap_n(norm_n(C[e1, e2]))\n if steps <= 2:\n weight = 0.2 +1.6*((-C[e1, e2]-threshold)/(np.nanmax(C[:]-threshold)))\n ax.plot([loc1[e1, 0], loc2[e2, 0]],\n [loc1[e1, 1], loc2[e2, 1]],\n [loc1[e1, 2], loc2[e2, 2]],\n '-', color=color_n, linewidth=weight)\n else:\n alphas = np.linspace(0, 1, steps)\n weight = 0.2 +1.6*((-C[e1, e2]-threshold)/(np.nanmax(C[:]-threshold)))\n for idx in range(len(alphas)-1):\n a = alphas[idx]\n b = alphas[idx+1]\n xn = ((1-a)**3 * x1 +\n 3 * (1-a)**2 * a * (2 * x1 - ctr1[0]) +\n 3 * (1-a) * a**2 * (2 * x2 - ctr2[0]) +\n a**3 * x2)\n xnn = ((1-b)**3 * x1 +\n 3 * (1-b)**2 * b * (2 * x1 - ctr1[0]) +\n 3 * (1-b) * b**2 * (2 * x2 - ctr2[0]) +\n b**3 * x2)\n yn = ((1-a)**3 * y1 +\n 3 * (1-a)**2 * a * (2 * y1 - ctr1[1]) +\n 3 * (1-a) * a**2 * (2 * y2 - ctr2[1]) +\n a**3 * y2)\n ynn = ((1-b)**3 * y1 +\n 3 * (1-b)**2 * b * (2 * y1 - ctr1[1]) +\n 3 * (1-b) * b**2 * (2 * y2 - ctr2[1]) +\n b**3 * y2)\n zn = ((1-a)**3 * z1 +\n 3 * (1-a)**2 * a * (2 * z1 - ctr1[2]) +\n 3 * (1-a) * a**2 * (2 * z2 - ctr2[2]) +\n a**3 * z2)\n znn = ((1-b)**3 * z1 +\n 3 * (1-b)**2 * b * (2 * z1 - ctr1[2]) +\n 3 * (1-b) * b**2 * (2 * z2 - ctr2[2]) +\n b**3 * z2)\n ax.plot([xn, xnn], [yn, ynn], [zn, znn],\n '-', color=color_n, linewidth=weight)", "def connect_points(clipped, side1, side2, window):\n edge = side1\n while edge != side2:\n clipped.append(window.points[0][edge])\n edge = (edge - 1) % 4", "def viz_2D_topomap_inter (epo1: mne.Epochs, epo2: mne.Epochs, C: np.ndarray, threshold: float=0.95, steps: int=10, lab: bool = False):\n\n # defining head model and adding sensors\n fig = plt.figure()\n ax = fig.add_subplot(111, aspect = 1)\n ax.axis(\"off\")\n plot_2d_topomap_inter(ax)\n plot_sensors_2d_inter(epo1, epo2, lab = lab) # bads are represented as squares\n # plotting links according to sign (red for positive values,\n # blue for negative) and value (line thickness increases\n # with the strength of connectivity)\n plot_links_2d_inter(epo1, epo2, C=C, threshold=threshold, steps=steps)\n plt.tight_layout()\n plt.show()\n\n return (ax)", "def plot_traj2D_NEA(r_NEA,t_pos,n_arrows,arrow_size,dest_folder=None):\n \n import plotting_utilities as plut\n\n fig = plt.figure(figsize=(12.3,10))\n\n # View from above\n ax1 = fig.add_subplot(2,1,1)\n traj2D = ax1.plot(r_NEA[1,:], r_NEA[0,:], ls='solid', color='#006633', label='') # trajectory\n ax1.plot(r_NEA[1,0], r_NEA[0,0], ls='solid', color='#006633', # start marker\n marker='o', markersize=4*arrow_size, markerfacecolor='#006633', markeredgecolor='#006633') \n ax1.plot(r_NEA[1,-1], r_NEA[0,-1], ls='solid', color='#006633', # end marker\n marker='o', markersize=4*arrow_size, markerfacecolor='w', markeredgecolor='#006633') \n plut.add_arrow_to_line2D(ax1,traj2D, # arrows\n arrow_locs=np.linspace(1/(n_arrows+1),n_arrows/(n_arrows+1),n_arrows),\n arrowsize=arrow_size) \n\n ax1.set_title(\"Ground Track, to scale\") \n ax1.set_xlabel('East (m)')\n ax1.set_ylabel('North (m)')\n ax1.minorticks_on()\n\n plt.axis('equal')\n plt.axis([1.02*min(r_NEA[1,:]), 1.02*max(r_NEA[1,:]), 1.02*min(r_NEA[0,:]), 1.02*max(r_NEA[0,:])])\n plt.tight_layout()\n\n # Altitude\n ax2 = fig.add_subplot(2,1,2)\n hhist = ax2.plot(t_pos, r_NEA[2,:], ls='solid', color='#006633', label='') # altitude history\n ax2.plot(t_pos[0], r_NEA[2,0], ls='solid', color='#006633', # start marker\n marker='o', markersize=4*arrow_size, markerfacecolor='#006633', markeredgecolor='#006633') \n ax2.plot(t_pos[-1], r_NEA[2,-1], ls='solid', color='#006633', # end marker\n marker='o', markersize=4*arrow_size, markerfacecolor='w', markeredgecolor='#006633') \n plut.add_arrow_to_line2D(ax2,hhist, # arrows\n arrow_locs=np.linspace(1/(n_arrows+1),n_arrows/(n_arrows+1),n_arrows),\n arrowsize=arrow_size) \n\n ax2.set_title(\"Altitude history\") \n ax2.set_xlabel(r'$t$ (s)')\n ax2.set_ylabel(r'$h_\\mathrm{SL}$ (m)')\n ax2.minorticks_on()\n\n ax2.set_xlim([1.02*min(t_pos), 1.02*max(t_pos)])\n plt.tight_layout()\n \n # Export\n if dest_folder != None:\n plt.savefig(dest_folder+'plot_Traj2D_NEA.pdf')", "def update_position(self):\n p1, p2 = connection_points_between_figure_elements(self.vertex1,\n self.vertex2)\n self.set_xdata((p1.x, p2.x))\n self.set_ydata((p1.y, p2.y))\n self.arrow.remove()\n self.arrow = create_directional_arrow(self)\n self.axes.add_patch(self.arrow)", "def display2Dpointsets(A, B, ax = None):\n if not ax:\n fig = plt.figure()\n ax = fig.add_subplot(111)\n\n ax.plot(A[:,0],A[:,1],'yo',markersize=8,mew=1)\n ax.plot(B[:,0],B[:,1],'b+',markersize=8,mew=1)\n #pylab.setp(pylab.gca(), 'xlim', [-0.15,0.6])\n labels = plt.getp(plt.gca(), 'xticklabels')\n plt.setp(labels, color='k', fontweight='bold')\n labels = plt.getp(plt.gca(), 'yticklabels')\n plt.setp(labels, color='k', fontweight='bold')", "def corner_pos(self, connection1, connection2, lastConnection):\n d1=(connection1.this.pos - connection1.other.pos).normalize()\n d2=(connection2.other.pos - connection1.other.pos).normalize()\n w1=self.get_width(connection1,connection1.other)/2\n w2=self.get_width(connection2,connection2.this)/2\n if abs(d1.dot(d2) +1) < 0.0001:\n b=0\n # catch case when it is the end of a single rod\n elif abs(d1.dot(d2) -1) < 0.0001:\n b=0\n return [[w2*rotate(d1,90), w2*rotate(d1,-90)], d1.cross(d2)[2]]\n else:\n if (d1[1]*d2[0]-d1[0]*d2[1])==0:\n raise ValueError(\"connections in the same place\"+str(connection1.this.pos )+\" \"+str(connection1.other.pos)+\" \"+str(connection2.other.pos))\n b = (d2[0]*d1[0]*w2 + w1*d1[0]**2 + w1*d1[1]**2 + w2*d1[1]*d2[1]) / (d1[1]*d2[0]-d1[0]*d2[1])\n# rotate direction can be correct if connection1 &2 are always in same rotational order\n return [ (b*d1 + w2*rotate(d1,90)), d1.cross(d2)[2] ]", "def plt_connecting_lines():\n\n for i in range(0, Molecule.connection_count):\n tmp1 = Molecule.right_endpt[Molecule.left_connection[i] - 1]\n tmp2 = Molecule.left_endpt[Molecule.right_connection[i] - 1]\n tmp3 = Molecule.energy[Molecule.left_connection[i] - 1]\n tmp4 = Molecule.energy[Molecule.right_connection[i] - 1]\n\n plt.plot([tmp1, tmp2], [tmp3, tmp4], color=PlotParameter.connection_line_color,\n lw=PlotParameter.connection_line_width, linestyle='--')\n\n return None", "def annotate_connection_style(ax, x1y1, x2y2, connectionstyle=\"angle3,angleA=0,angleB=90\",\n xycoords='figure_fraction', textcoords='figure_fraction', color=\"0.5\",\n label=None):\n if label is not None:\n add_at(ax, label, loc=2)\n\n x1, y1 = x1y1\n x2, y2 = x2y2\n\n ax.annotate(\"\",\n xy=(x1, y1), xycoords=xycoords,\n xytext=(x2, y2), textcoords=textcoords,\n arrowprops=dict(arrowstyle=\"simple\", # linestyle=\"dashed\",\n color=color,\n shrinkA=5,\n shrinkB=5,\n patchA=None,\n patchB=None,\n connectionstyle=connectionstyle,\n ),\n )", "def snap_connect_nodes(\n self,\n two_nodes,\n subsections=None,\n spacing=None,\n boundary_id=-1,\n ):\n two_nodes = np.asarray(two_nodes)\n if two_nodes.shape[0] != 2:\n raise ValueError(\"`two_nodes` takes two nodes only.\")\n\n # Abuse KDT since it is fast enough for this.\n kdt = KDTree(self.nodes_)\n _, nn_ind = kdt.query(two_nodes) # there are two indices\n logging.debug(\n \"Segment - Snapping and connecting [{ni}] nodes: {n}.\".format(\n ni=nn_ind,\n n=self.nodes[nn_ind]\n )\n )\n\n self.connect_nodes(\n nn_ind,\n reference_nodes=False,\n subsections=subsections,\n spacing=spacing,\n boundary_id=boundary_id,\n )", "def connect_poly(self):\n # connect pmos1 poly\n nmos_gate = (self.nmos_position1 \n + self.nmos.poly_positions[0]\n + vector(0.5 * drc[\"minwidth_poly\"], 0))\n for i in range(len(self.pmos.poly_positions)):\n pmos_gate = (self.pmos_position1 \n + self.pmos.poly_positions[i]\n + vector(0.5 * drc[\"minwidth_poly\"], 0))\n mid1 = [pmos_gate.x, pmos_gate.y - drc[\"poly_to_active\"]]\n self.add_path(\"poly\", [nmos_gate, mid1, pmos_gate])\n\n # connect pmos2 poly\n nmos_gate = vector(self.nmos_position2[0] \n + self.nmos.poly_positions[0].x\n + 0.5 * drc[\"minwidth_poly\"], \n self.nmos_position1.y \n + self.nmos.poly_positions[0].y)\n for i in range(len(self.pmos.poly_positions)):\n pmos_gate = (self.pmos_position2\n + self.pmos.poly_positions[i]\n + vector(0.5 * drc[\"minwidth_poly\"], 0))\n mid1 = vector(pmos_gate.x,\n nmos_gate.y + self.nmos.height \n + drc[\"poly_to_active\"])\n self.add_path(\"poly\", [nmos_gate, mid1, pmos_gate])", "def get_diagram(self):\n self_nodes=self.nodes.all()\n self_arrows=self.arrows.all()\n \n \n if len(self_nodes)==0:\n return False\n \n nodes = [n.get_icon_obj() for n in self_nodes]\n node_liens = [n.liens.all() for n in self_nodes]\n \n pairs = []\n for n,n_liens in zip(nodes,node_liens):\n if len(n_liens)==0:\n liens = Lien.objects.filter(cause__id=n.target_id).all()\n liens = [l.consequence.id for l in liens]\n temp = [(n,target) for target in nodes if target.target_id in liens]\n pairs.extend(temp)\n else:\n ids=set([(i.cause.id,i.consequence.id) for i in n_liens])\n for n in nodes:\n pairs.extend([(n,i) for i in nodes if i is not n and \n (n.target_id,i.target_id) in ids])\n ids = set([(i.cause.id,i.consequence.id) for i in self_arrows])\n pairs = [p for p in pairs if (p[0].target_id,p[1].target_id) not in ids]\n \n lines=[]\n arrows=[]\n for obj in self_arrows:\n \n n0=[i for i in nodes if i.node_id==obj.cause.id]\n n1=[i for i in nodes if i.node_id==obj.consequence.id]\n if len(n0)!=1 or len(n1)!=1:\n continue\n n0=n0[0]\n n1=n1[0]\n \n pt=[(obj.X0, obj.Y0), (obj.X1,obj.Y1)]\n pt=[np.array(i) for i in pt if None not in i]\n if len(pt)==0:\n pairs.append((n0,n1))\n continue\n pairs = [p for p in pairs if (p[0].node_id,p[1].node_id)!=(n0.node_id,n1.node_id)]\n vect = pt[0]-np.array(n0.pos)\n first_pt = np.array(n0.pos)+vect*n0.size/np.sqrt(sum(vect*vect))\n vect = np.array(n1.pos) - pt[-1]\n last_pt = np.array(n1.pos)-vect*n1.size/np.sqrt(sum(vect*vect))\n pt=[first_pt,*pt,last_pt]\n \n lines.extend([((*i,*j),n0.color) for i,j in zip(pt[:-1],pt[1:])])\n arrows.append(((*pt[-2],*pt[-1]),n0.color))\n \n \n margin=10\n line_width=2\n \n diagram=DiagramObj(self.id,nodes,pairs,margin,\n self.width,self.height,line_width)\n diagram.add_arrows(arrows,lines)\n print(diagram.lines)\n return diagram", "def connect_lines(horizontal_lines, vertical_lines):\n horizontal = []\n vertical = []\n\n for x1,y1,x2,y2 in horizontal_lines:\n closest_vertical_left = 20000\n closest_vertical_right = 20000\n for v_x1,v_y1,v_x2,v_y2 in vertical_lines:\n if abs(x1 - v_x1) < abs(closest_vertical_left):\n closest_vertical_left = x1 - v_x1\n if abs(x2 - v_x1) < abs(closest_vertical_right):\n closest_vertical_right = x2 - v_x1\n x1 = x1 - closest_vertical_left\n x2 = x2 - closest_vertical_right\n horizontal.append((x1,y1,x2,y2))\n\n for x1,y1,x2,y2 in vertical_lines:\n closest_horizontal_up = 20000\n closest_horizontal_down = 20000\n for h_x1,h_y1,h_x2,h_y2 in horizontal_lines:\n if abs(y1 - h_y1) < abs(closest_horizontal_up):\n closest_horizontal_up = y1 - h_y1\n if abs(y2 - h_y1) < abs(closest_horizontal_down):\n closest_horizontal_down = y2 - h_y1\n y1 = y1 - closest_horizontal_up\n y2 = y2 - closest_horizontal_down\n vertical.append((x1,y1,x2,y2))\n\n return (horizontal, vertical)", "def comparekp (left, right, kp1, kp2):\n subplot (121)\n arx = array ([kp1.pt[0]])\n ary = array ([kp1.pt[1]])\n hold(True)\n imshow(left)\n scatter (arx, ary)\n\n subplot (122)\n arx = array ([kp2.pt[0]])\n ary = array ([kp2.pt[1]])\n hold(True)\n imshow(right)\n scatter (arx, ary)\n\n show()", "def represent_link(ax, x,y, x_neighbour, y_neighbour):\n \n dx = x_neighbour-x\n dy = y_neighbour-y\n # Draw a black arrow between (x, y) and (x+dx, y+dy)\n ax.arrow(x, y, dx, dy, head_width=0.1, head_length=0.2, length_includes_head = True, fc='k')", "def twoEdgesIntoSamePortResolvesCrossingWhenSwitched(self):\n graph = self.graph\n makeLayer = self.makeLayer\n eastWestEdgeFromTo = self.eastWestEdgeFromTo\n addNodeToLayer = self.addNodeToLayer\n addPortOnSide = self.addPortOnSide\n addEdgeBetweenPorts = self.addEdgeBetweenPorts\n\n leftLayer = makeLayer(graph)\n rightLayer = makeLayer(graph)\n\n topLeft = addNodeToLayer(leftLayer)\n bottomLeft = addNodeToLayer(leftLayer)\n topRight = addNodeToLayer(rightLayer)\n bottomRight = addNodeToLayer(rightLayer)\n\n topLeftPort = addPortOnSide(topLeft, PortSide.EAST)\n bottomLeftPort = addPortOnSide(bottomLeft, PortSide.EAST)\n bottomRightPort = addPortOnSide(bottomRight, PortSide.WEST)\n\n addEdgeBetweenPorts(topLeftPort, bottomRightPort)\n addEdgeBetweenPorts(bottomLeftPort, bottomRightPort)\n\n eastWestEdgeFromTo(bottomLeft, topRight)\n\n return graph", "def cell_edges2d_cartesian(self, axis2):", "def connect_nodes(\n self,\n indices,\n reference_nodes=True,\n subsections=None,\n spacing=None,\n boundary_id=-1,\n ):\n assert len(indices) == 2, \"I can only connect two nodes at a time.\"\n\n # Get first/last indices and vertices\n if reference_nodes:\n ind_first = self.reference_nodes[indices[0]]\n ind_last = self.reference_nodes[indices[1]]\n else:\n ind_first = indices[0]\n ind_last = indices[1]\n vertex_first = self.nodes[ind_first]\n vertex_last = self.nodes[ind_last]\n\n # Get subsections\n subsections = self.compute_subsections_(\n subsections,\n spacing,\n compute_distance(vertex_first, vertex_last)\n )\n\n # Get nodes and connectivity\n new_nodes = np.linspace(\n vertex_first,\n vertex_last,\n (subsections+1)\n )[1:-1]\n\n num_additional_nodes = len(new_nodes)\n logging.debug(\n 'Segment - Connecting node with {nan} additional node(s)'.format(\n nan=num_additional_nodes\n )\n )\n\n if num_additional_nodes == 0:\n new_connectivity = np.array([[ind_first, ind_last]])\n elif num_additional_nodes == 1:\n new_connectivity = np.array(\n [[ind_first, self.nodes.shape[0]],\n [self.nodes.shape[0], ind_last]]\n )\n else:\n last_added_node_ind = self.nodes.shape[0] + num_additional_nodes - 1\n\n first_con = np.array([[ind_first, self.nodes.shape[0]]])\n mid_con = utils.open_loop_index_train(\n (self.nodes.shape[0], # This points to the first new node.\n last_added_node_ind)\n )\n last_con = np.array(\n [[last_added_node_ind, ind_last]] \n )\n new_connectivity = np.vstack(\n (first_con,\n mid_con,\n last_con)\n )\n\n # Stack them!\n if num_additional_nodes >= 1:\n self.nodes_ = np.vstack(\n (self.nodes,\n new_nodes)\n )\n\n if self.connectivity is None:\n self.connectivity = new_connectivity\n else:\n self.connectivity = np.vstack(\n (self.connectivity,\n new_connectivity)\n )\n\n # Take care of boundary ids\n num_boundary_ids = len(new_connectivity)\n self.add_boundary_id(boundary_id, num_boundary_ids, facet=False)" ]
[ "0.6324668", "0.6066518", "0.59506184", "0.58509564", "0.5810313", "0.569868", "0.5489544", "0.548774", "0.54173046", "0.54137576", "0.53784466", "0.5377732", "0.53768015", "0.5362857", "0.5308323", "0.5304957", "0.5276873", "0.5269564", "0.5238408", "0.52253467", "0.52139115", "0.519937", "0.5153162", "0.5137038", "0.51331085", "0.5116471", "0.5109477", "0.5080762", "0.5057109", "0.50489295" ]
0.6332839
0
Calculates the starting point and the offset for an arrow placed at the end of an edge.
def calc_edge_arrow_data(edge: FigureEdge) -> Tuple[Vec, Vec]: p1, p2 = connection_points_between_figure_elements(edge.vertex1, edge.vertex2) arrow_offset = opts['gui']['arrows']['arrow_start_offset'] start = p2 - normalize(Vec(vec1=p1, vec2=p2)) * arrow_offset offset = p2 - start return start, offset
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_arrowhead(self, direction: str, x: int, y: int, end: int) -> str:\n if direction == \"left\":\n p1, p2, p3 = (x, x - self.arrow_width + 2, x + self.arrow_width - 2)\n else:\n p1, p2, p3 = (end, end + self.arrow_width - 2, end - self.arrow_width + 2)\n return f\"M{p1},{y + 2} L{p2},{y - self.arrow_width} {p3},{y - self.arrow_width}\"", "def d_midpoint(edge):\n v0, v1 = EDGES[edge]\n v0_pos = VERTICES[v0]\n v1_pos = VERTICES[v1]\n return ((x+y) for (x,y) in zip(v0_pos, v1_pos))", "def get_elevation_along_edge(self, from_, to):\n pass", "def edge_dxy(self):\r\n loc = self.loc\r\n rect = loc.coord\r\n p1 = rect[0]\r\n p2 = rect[1]\r\n edx = p2[0] - p1[0] # Find edge direction\r\n edy = p2[1] - p1[1]\r\n return edx, edy", "def get_quiver_arrows(self):\n dif_x = [i - j for i, j in zip(self.end_x, self.x)]\n dif_y = [i - j for i, j in zip(self.end_y, self.y)]\n\n # Get barb lengths(default arrow length = 30% barb length)\n barb_len = [None] * len(self.x)\n for index in range(len(barb_len)):\n barb_len[index] = math.hypot(dif_x[index] / self.scaleratio, dif_y[index])\n\n # Make arrow lengths\n arrow_len = [None] * len(self.x)\n arrow_len = [i * self.arrow_scale for i in barb_len]\n\n # Get barb angles\n barb_ang = [None] * len(self.x)\n for index in range(len(barb_ang)):\n barb_ang[index] = math.atan2(dif_y[index], dif_x[index] / self.scaleratio)\n\n # Set angles to create arrow\n ang1 = [i + self.angle for i in barb_ang]\n ang2 = [i - self.angle for i in barb_ang]\n\n cos_ang1 = [None] * len(ang1)\n for index in range(len(ang1)):\n cos_ang1[index] = math.cos(ang1[index])\n seg1_x = [i * j for i, j in zip(arrow_len, cos_ang1)]\n\n sin_ang1 = [None] * len(ang1)\n for index in range(len(ang1)):\n sin_ang1[index] = math.sin(ang1[index])\n seg1_y = [i * j for i, j in zip(arrow_len, sin_ang1)]\n\n cos_ang2 = [None] * len(ang2)\n for index in range(len(ang2)):\n cos_ang2[index] = math.cos(ang2[index])\n seg2_x = [i * j for i, j in zip(arrow_len, cos_ang2)]\n\n sin_ang2 = [None] * len(ang2)\n for index in range(len(ang2)):\n sin_ang2[index] = math.sin(ang2[index])\n seg2_y = [i * j for i, j in zip(arrow_len, sin_ang2)]\n\n # Set coordinates to create arrow\n for index in range(len(self.end_x)):\n point1_x = [i - j * self.scaleratio for i, j in zip(self.end_x, seg1_x)]\n point1_y = [i - j for i, j in zip(self.end_y, seg1_y)]\n point2_x = [i - j * self.scaleratio for i, j in zip(self.end_x, seg2_x)]\n point2_y = [i - j for i, j in zip(self.end_y, seg2_y)]\n\n # Combine lists to create arrow\n empty = [None] * len(self.end_x)\n arrow_x = utils.flatten(zip(point1_x, self.end_x, point2_x, empty))\n arrow_y = utils.flatten(zip(point1_y, self.end_y, point2_y, empty))\n return arrow_x, arrow_y", "def calculate_distance_edge(self):\n if self.mu > 0:\n # right interface is intersected next\n dx = self.cell_xr - self.x\n self.next_cell_index = self.cell_index + 1\n else:\n # left interface is intersected next\n dx = self.cell_xl - self.x\n self.next_cell_index = self.cell_index - 1\n\n return dx / self.mu", "def create_directional_arrow(edge: FigureEdge) -> FancyArrow:\n arrow_start, arrow_offset = calc_edge_arrow_data(edge)\n arrow_width = opts['gui']['arrows']['arrow_width']\n arrow_head_width = opts['gui']['arrows']['head_width']\n arrow_head_length = opts['gui']['arrows']['head_length']\n arrow_color = opts['gui']['arrows']['color']\n arrow = FancyArrow(arrow_start.x, arrow_start.y,\n arrow_offset.x, arrow_offset.y,\n color=arrow_color,\n width=arrow_width,\n head_width=arrow_head_width,\n head_length=arrow_head_length,\n length_includes_head=True)\n return arrow", "def get_arrowhead(self, direction, x, y, end):\n if direction is 'left':\n pos1, pos2, pos3 = (x, x-self.arrow_width+2, x+self.arrow_width-2)\n else:\n pos1, pos2, pos3 = (end, end+self.arrow_width-2,\n end-self.arrow_width+2)\n arrowhead = (pos1, y+2, pos2, y-self.arrow_width, pos3,\n y-self.arrow_width)\n return \"M{},{} L{},{} {},{}\".format(*arrowhead)", "def _calculate_h(self, end):\n return PATH_COST * (abs(self.x - end.x) + abs(self.y - end.y))", "def getEdgeDistance():\n '''\n a\n ◿\n b c\n\n hypotenuse\n ◿ adjacent\n opposite\n\n tan(a) = opposite/adjacent\n adjacent * tan(a) = opposite\n '''\n\n # An estimated multiplier to take into account the larger infrared dot\n # observed when further away from as surface - think torch beam onto a\n # wall getting larger as it gets further away, but only the radius\n # (center downwards) being relevant.\n # TODO: Maybe move into infrared sensor code?\n MULTI = 1.2\n\n edgeDistance = BOT_HEIGHT * math.tan(math.radians(getEdgeAngle()))\n edgeDistance *= MULTI\n\n if DEBUG:\n print \"Distance to edge: \", int(round(edgeDistance))\n\n return edgeDistance", "def total_edge_angle(e1, e2):\n e1_source = section.index(e1[0])\n e2_target = section.index(e2[1])\n\n \"\"\" Given a pair of vertices, call angle_delta between them. \"\"\"\n f = lambda pair: utils.angle_delta(self.node_heading[pair[0]], self.node_heading[pair[1]])\n\n \"\"\" Map f onto each pair of adjacent vertices, and return the abs of the summed result. \"\"\"\n return abs(sum(map(f, zip(section[e1_source + 1:e2_target], section[e1_source + 2:e2_target + 1]))))", "def calculate_distance_edge(self):\n mu_star = -np.sqrt(1. - (self.cell_xl / self.x)**2)\n\n if self.mu <= mu_star:\n\n l_edge = (-self.mu * self.x -\n np.sqrt(self.mu**2 * self.x**2 -\n self.x**2 + self.cell_xl**2))\n self.next_cell_index = self.cell_index - 1\n\n else:\n\n l_edge = (-self.mu * self.x +\n np.sqrt(self.mu**2 * self.x**2 -\n self.x**2 + self.cell_xr**2))\n self.next_cell_index = self.cell_index + 1\n\n return l_edge", "def getEdgeAngle():\n '''\n returns angle a\n a\n ◿\n b c\n '''\n ANGLE_OFFSET = 8 # How far off the angle measurements are in degrees.\n THRESHOLD = 220 # How much light must be reflected to 'notice' the desk.\n angle = 0\n while angle < panTilt.TLT_RANGE:\n angle += 1\n panTilt.tilt(int(angle))\n deskDetected = ir.readWithDelay()\n # print \"Angle:\", angle + ANGLE_OFFSET, \", ir reading:\", deskDetected\n if deskDetected > THRESHOLD or angle == panTilt.TLT_RANGE:\n # print \"-----------------------\"\n break # Break out of looking downwards loop\n panTilt.up() # Look up again\n return 90 - angle - ANGLE_OFFSET", "def _handleEdge(self):\r\n if self._aliensdown == False:\r\n for row in self.getAliens():\r\n for alien in row:\r\n if not alien is None:\r\n alien.y -= ALIEN_V_WALK\r\n self._direction = (-1)*self._direction\r\n self._aliensdown = True\r\n else:\r\n for row in self.getAliens():\r\n for alien in row:\r\n if not alien is None:\r\n alien.x += self._direction*ALIEN_H_WALK\r\n self._aliensdown = False", "def getOffsetLine(self, distance, side=c.INSIDE):\n StartA = np.array([self.start.x, self.start.y])\n EndA = np.array([self.end.x, self.end.y])\n r = StartA - EndA #The slope vector of self\n rn = np.array([-r[c.Y], r[c.X]]) #flip x and y and inverse y to get the normal vector of the slope\n rn = rn/np.linalg.norm(rn)*distance #normalize by dividing by its magnitude and multipy by distance to get the correct length\n \n if side == c.INSIDE:\n return self.translate(-rn[c.X], -rn[c.Y]) #the \"minus\" side line is the left side which is inside.\n \n return self.translate(rn[c.X], rn[c.Y]) #the \"Plus\" side of the line is the right side which is outside.", "def find_edge(point, offset, max_dist, hi, lo, bgArray):\n for i in range(1, max_dist):\n next = (point[0] + i * offset[0], point[1] + i * offset[1])\n if is_edge(next, hi, lo, bgArray):\n return (next, i)\n return None", "def get_starting_direction_vector(self):\n\n total_length = len(self.pixel_list)\n\n if total_length < 2:\n return None\n elif total_length < 15:\n delta_x = self.pixel_list[-1].x - self.pixel_list[0].x\n delta_y = self.pixel_list[-1].y - self.pixel_list[0].y\n return delta_y, delta_x\n else:\n delta_x = self.pixel_list[-15].x - self.pixel_list[0].x\n delta_y = self.pixel_list[-15].y - self.pixel_list[0].y\n return delta_y, delta_x", "def find_edges(starting_point, max_dist, hi, lo, bgArray):\n try:\n b = fetch_val(bgArray, starting_point)\n except IndexError:\n return None\n offsets = [(0,1), (1,0), (0,-1), (-1,0)]\n edgePoints = []\n for offset in offsets:\n first_result = find_edge(starting_point, offset, max_dist, hi, lo, bgArray)\n if first_result is not None:\n edgePoints.append(first_result[0])\n if b < lo or b > hi:\n # Try to find second point, since starting click was outside threshold\n second_result = find_edge(first_result[0], offset, max_dist - first_result[1], hi, lo, bgArray)\n if second_result is not None:\n edgePoints.append(second_result[0])\n return edgePoints", "def downleft(self):\n return Coord([self.x - 1, self.y + 1])", "def _get_edges(self) -> Tuple[Line]:\n if self.side == 'right':\n return Line((self.left_bound, self.bottom_bound), (self.left_bound, self.top_bound)),\n elif self.side == 'left':\n return Line((self.right_bound, self.bottom_bound), (self.right_bound, self.top_bound)),", "def get_ending_direction_vector(self):\n\n total_length = len(self.pixel_list)\n\n if total_length < 2:\n return None\n elif total_length < 15:\n delta_x = self.pixel_list[-1].x - self.pixel_list[0].x\n delta_y = self.pixel_list[-1].y - self.pixel_list[0].y\n return delta_y, delta_x\n else:\n delta_x = self.pixel_list[-15].x - self.pixel_list[-1].x\n delta_y = self.pixel_list[-15].y - self.pixel_list[-1].y\n return delta_y, delta_x", "def get_arrow(mark, arrow, yaxis, sz, opt):\n from rplot.fixes import ROOT\n if yaxis:\n return ROOT.TArrow(arrow[0], mark, arrow[0], arrow[1], sz, opt)\n else:\n return ROOT.TArrow(mark, arrow[1], arrow[0], arrow[1], sz, opt)", "def edge_direction(a, b):\n if a[0] == b[0]:\n return -1, 1\n elif a[0] == b[1]:\n return -1, -1\n elif a[1] == b[0]:\n return 1, 1\n elif a[1] == b[1]:\n return 1, -1\n else:\n constants.log.debug('\\n'.join([\n 'edges not connected!',\n 'vertex path %s',\n 'entity path: %s',\n 'entity[a]: %s,',\n 'entity[b]: %s']),\n vertex_path,\n entity_path,\n entities[ea].points,\n entities[eb].points)\n\n return None, None", "def edge_point(self, edge, parallel, orthogonal):\n if edge is Direction.up:\n return Point(parallel, self.top + orthogonal)\n elif edge is Direction.down:\n return Point(parallel, self.bottom - orthogonal)\n elif edge is Direction.left:\n return Point(self.left + orthogonal, parallel)\n elif edge is Direction.right:\n return Point(self.right - orthogonal, parallel)\n raise ValueError(\"Expected an orthogonal direction\")", "def getOrdinate(self):\n return self.point.y - self.slope * self.point.x", "def draw_arrow(axes, startx, starty, orient, arrow_len=5.0, color='black', lw=2.0):\n xy = (startx, starty)\n dxy = (np.cos(orient) * arrow_len, np.sin(orient) * arrow_len)\n xytext = tuple(map(sum, zip(xy, dxy)))\n axes.annotate(\n \"\",\n xy=xy,\n xytext=xytext,\n arrowprops=dict(arrowstyle=\"<-\", lw=lw),\n color=color,\n )", "def walk_away_from_end(start, stop,\n direction, walk=3):\n if direction == \"+\":\n # changed as this is the gene end\n current_start = int(end)\n current_end = int(end) + int(walk)\n else:\n assert direction == \"-\", \"direction does sign error!\"\n current_end = start\n current_start = int(start) - int(walk)\n return current_start, current_end", "def build_vertical_path_with_increments(coord1, coord2, horizontal_increment, vertical_increment, start_alt, end_alt,\n max_point):\n\n if not isinstance(coord1, GPSCoord):\n raise ValueError('Parameter coord1 have to be a GPSCoord')\n\n if not isinstance(coord2, GPSCoord):\n raise ValueError('Parameter coord2 have to be a GPSCoord')\n\n if coord1 == coord2:\n raise ValueError('The coordinates have the same position')\n\n horizontal_increment = float(horizontal_increment)\n vertical_increment = float(vertical_increment)\n start_alt = float(start_alt)\n end_alt = float(end_alt)\n max_point = int(max_point)\n\n base_line = build_line_with_increment(coord1, coord2, horizontal_increment, max_point, start_alt)\n\n result = []\n result.extend(base_line)\n\n current_alt = start_alt + vertical_increment\n do_reverse = True\n\n while len(result) < max_point and current_alt <= end_alt:\n if do_reverse:\n new_line = build_line_with_increment(coord2, coord1, horizontal_increment, max_point - len(result),\n current_alt)\n\n else:\n new_line = build_line_with_increment(coord1, coord2, horizontal_increment, max_point - len(result),\n current_alt)\n\n do_reverse = not do_reverse\n result.extend(new_line)\n current_alt += vertical_increment\n\n return result", "def generate_obstacle_point(start, end):\n top_left = (start[0], start[1] - _OBSTACLE_SIZE)\n top_right = (end[0], end[1] - _OBSTACLE_SIZE)\n return start, end, top_right, top_left", "def angle_between_edges_2d(endpoint1, common_point, endpoint2):\r\n return geometry.gmAngleBetweenEdges(endpoint1, common_point, endpoint2)" ]
[ "0.62411326", "0.6234753", "0.6191948", "0.6077081", "0.607508", "0.6027296", "0.60175747", "0.600105", "0.59105873", "0.5842727", "0.5818897", "0.5693497", "0.5648054", "0.5632693", "0.56246793", "0.5540439", "0.5520203", "0.5511624", "0.54976594", "0.54948705", "0.54892325", "0.5475772", "0.54680824", "0.5432969", "0.5413745", "0.5394875", "0.53918916", "0.5376028", "0.53608423", "0.53573364" ]
0.77951217
0
Instantiates a new FancyArrow with the correct configuration for adding a direction to a FigureEdge.
def create_directional_arrow(edge: FigureEdge) -> FancyArrow: arrow_start, arrow_offset = calc_edge_arrow_data(edge) arrow_width = opts['gui']['arrows']['arrow_width'] arrow_head_width = opts['gui']['arrows']['head_width'] arrow_head_length = opts['gui']['arrows']['head_length'] arrow_color = opts['gui']['arrows']['color'] arrow = FancyArrow(arrow_start.x, arrow_start.y, arrow_offset.x, arrow_offset.y, color=arrow_color, width=arrow_width, head_width=arrow_head_width, head_length=arrow_head_length, length_includes_head=True) return arrow
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def make_edge(self, a, b):\n try: e = self.G.new_edge(a, b)\n except: return self.G.new_edge(a,b)\n\n try: self.G.set_edge_attribute(e, \"arrow\", \"true\")\n except: return self.G.new_edge(a,b)\n\n try: self.G.set_edge_attribute(e, \"spline\", \"false\")\n except: return self.G.new_edge(a,b)\n return e", "def __init__(self, origin=None, end=None,\n filled=False, arrowType=NormalArrow, parent=None):\n super(E5ArrowItem, self).__init__(parent)\n \n self._origin = QPointF() if origin is None else QPointF(origin)\n self._end = QPointF() if end is None else QPointF(end)\n self._filled = filled\n self._type = arrowType\n \n self._halfLength = 13.0\n \n self.setFlag(QGraphicsItem.ItemIsMovable, True)\n self.setFlag(QGraphicsItem.ItemIsSelectable, True)", "def add_arrow(self, ax, node1, node2, prob=None):\n # x,y start of the arrow\n x_start = node1.x + np.sign(node2.x-node1.x) * node1.radius\n y_start = node1.y + np.sign(node2.y-node1.y) * node1.radius\n\n # arrow length\n dx = abs(node1.x - node2.x) - 2.5* node1.radius\n dy = abs(node1.y - node2.y) - 2.5* node1.radius\n\n # we don't want xoffset and yoffset to both be non-nul\n yoffset = 0.4 * self.node_radius * np.sign(node2.x-node1.x)\n if yoffset == 0:\n xoffset = 0.4 * self.node_radius * np.sign(node2.y-node1.y)\n else:\n xoffset = 0\n\n arrow = mpatches.FancyArrow(\n x_start + xoffset,\n y_start + yoffset,\n dx * np.sign(node2.x-node1.x),\n dy * np.sign(node2.y-node1.y),\n width = self.arrow_width,\n head_width = self.arrow_head_width\n )\n p = PatchCollection(\n [arrow],\n edgecolor = self.arrow_edgecolor,\n facecolor = self.arrow_facecolor\n )\n ax.add_collection(p)\n\n # Probability to add?\n x_prob = x_start + xoffset + 0.2*dx*np.sign(node2.x-node1.x)\n y_prob = y_start + yoffset + 0.2*dy*np.sign(node2.y-node1.y)\n if prob:\n ax.annotate(str(prob), xy=(x_prob, y_prob), color='#000000', **self.text_args)", "def __init__(self, name, edge, start_node, end_node, pipe_model,\n allow_flow_reversal,\n temperature_driven, repr_days=None):\n\n self.logger = logging.getLogger('modesto.Edge')\n self.logger.info('Initializing Edge {}'.format(name))\n\n self.repr_days = repr_days\n\n self.name = name\n self.edge = edge\n\n self.start_node = start_node\n self.end_node = end_node\n self.length = self.get_length()\n\n self.temperature_driven = temperature_driven\n\n self.pipe_model = pipe_model\n self.pipe = self.build(pipe_model,\n allow_flow_reversal) # TODO Better structure possible?", "def define_edge(self):\n\n self.canvas_edge = Line(\n points=[\n self.canvas_nodes[0].pos[0] + self.nodesize[0] / 2,\n self.canvas_nodes[0].pos[1] + self.nodesize[1] / 2,\n self.canvas_nodes[1].pos[0] + self.nodesize[0] / 2,\n self.canvas_nodes[1].pos[1] + self.nodesize[1] / 2\n ],\n joint='round',\n cap='round',\n width=3\n )", "def add_edge(self, position):\n raise NotImplementedError()", "def __init__(self, startItem, endItem, parent=None, scene=None, \n arrow_start_point = None, arrow_end_point = None, \n toHotspotId=None, fromHotspotId=None):\n Logger.ClassLogger.__init__(self)\n if QtHelper.IS_QT5:\n super(Arrow, self).__init__(parent)\n else:\n super(Arrow, self).__init__(parent, scene)\n\n self.arrowHead = QPolygonF()\n\n # get hotspot directly on creation\n self.toHotspotId = toHotspotId\n self.fromHotspotId = fromHotspotId\n\n # save id on paint\n self.toHotspotID = 0\n self.fromHotspotID = 0\n\n self.myStartItem = startItem\n self.myEndItem = endItem\n\n self.setFlag(QGraphicsItem.ItemIsSelectable, True)\n self.myColor = Qt.black\n self.setPen(QPen(self.myColor, 1, Qt.SolidLine, Qt.RoundCap, Qt.RoundJoin))\n\n self.arrow_start_point = arrow_start_point\n self.arrow_end_point = arrow_end_point\n \n self.startingPoint = None\n self.endingPoint = None\n\n self.text = \"\"", "def MakeEdge(self, *args):\n return _ShapeBuild.ShapeBuild_Edge_MakeEdge(self, *args)", "def add_edge(self, a, b, label=\"\", color=\"black\", length=100, arrows=\"to\"):\n\n\t\tm = self.edgesPairs.count((a, b))\n\n\t\tif m == 0 :\n\t\t\tcolor = color\n\t\tif m == 1:\n\t\t\tcolor = \"red\"\n\t\tif m == 2:\n\t\t\tcolor = \"blue\"\n\n\t\tself.edgesPairs.append((a, b))\n\t\tself.edgesPairsId[self.edgesIdsCounter] = (a, b)\n\t\tself.edgesLabelsId[self.edgesIdsCounter] = label\n\n\t\tself.edges.append({\"id\": self.edgesIdsCounter,\n\t\t\t\t\t\t\"from\": a,\n\t\t\t\t\t\t\"to\": b,\n\t\t\t\t\t\t\"label\": label,\n\t\t\t\t\t\t\"arrows\": arrows,\n\t\t\t\t\t\t\"color\": color,\n\t\t\t\t\t\t\"length\": length\n\t\t\t\t\t\t})\n\t\tself.edgesIdsCounter += 1", "def polySlideEdge(*args, absolute: bool=True, direction: int=0, edgeDirection: float=0.0,\n symmetry: bool=True, **kwargs)->bool:\n pass", "def __init__(self, *args):\n _snap.TNGraphEdgeI_swiginit(self, _snap.new_TNGraphEdgeI(*args))", "def edge(cls, edge):\n return cls(Lnk.EDGE, int(edge))", "def new_edge(self, parent, child):\n self.add_edge( Edge(parent,child) )", "def __init__(self):\n super(StandardArrowHead, self).__init__()\n self._length = 10\n self._width = 0.4", "def shape(self):\n path = super(Arrow, self).shape()\n path.addPolygon(self.arrowHead)\n return path", "def from_anchor(\n cls,\n anchor: Vertex,\n other: Vertex,\n label: str = \"\",\n direction: str = \"out\",\n ) -> \"Edge\":\n has_direction = direction != \"none\"\n\n if has_direction is True:\n if direction == \"out\":\n start = anchor\n end = other\n elif direction == \"in\":\n start = other\n end = anchor\n else:\n raise ValueError(\"Direction is either 'in', 'out' or 'none'\")\n else:\n # No need to sort here, the __init__ do it already.\n start = anchor\n end = other\n\n edge = cls(start, end, label=label, has_direction=has_direction)\n\n edge._anchor = anchor\n edge._other = other\n edge._direction = direction\n\n return edge", "def __init__(self, graph, head_vertex, tail_vertex):\n super(DirectedGraphEdge, self).__init__(\n graph, head_vertex, tail_vertex)\n self.directed = True", "def add_arrow(self, arrow):\n self.arrows.append(arrow)", "def addEdge(self, edge):\n Digraph.addEdge(self, edge)\n rev = Edge(edge.getDestination(), edge.getSource())\n Digraph.addEdge(self, rev)", "def create(cls, outV, inV, *args, **kwargs):\r\n return super(Edge, cls).create(outV, inV, *args, **kwargs)", "def add_edge(self, edge):\n self[edge[0]][edge[1]] = edge\n self[edge[1]][edge[0]] = edge", "def create_new_arrow(self, coords, **options):\n\n if 'fill' not in options:\n options['fill'] = self.variables.foreground_color\n if 'width' not in options:\n options['width'] = self.variables.line_width\n if 'arrow' not in options:\n options['arrow'] = tkinter.LAST\n\n shape_id = self.create_line(*coords, **options)\n self.variables.vector_objects[str(shape_id)] = VectorObject(SHAPE_TYPES.ARROW, options)\n self.variables.shape_ids.append(shape_id)\n self.set_shape_pixel_coords_from_canvas_coords(shape_id, coords)\n self.variables.current_shape_id = shape_id\n return shape_id", "def __init__(\n self,\n start: Vertex,\n end: Vertex,\n label: str = \"\",\n has_direction: bool = True,\n ):\n if not start.is_inserted or not end.is_inserted:\n raise VertexInsertionException(\n \"Both vertices must be inserted to make an Edge\"\n )\n\n if has_direction is True:\n self._start = start\n self._end = end\n else:\n # If the Edge has no direction, the start and end vertices are\n # sorted by place for consistant use.\n self._start, self._end = sorted(\n (start, end), key=lambda v: v.place\n )\n self._label = label\n self._has_direction = has_direction\n\n self._anchor: Optional[Vertex] = None\n self._other: Optional[Vertex] = None\n self._direction: Optional[str] = None\n\n self.is_inserted = False", "def get_quiver_arrows(self):\n dif_x = [i - j for i, j in zip(self.end_x, self.x)]\n dif_y = [i - j for i, j in zip(self.end_y, self.y)]\n\n # Get barb lengths(default arrow length = 30% barb length)\n barb_len = [None] * len(self.x)\n for index in range(len(barb_len)):\n barb_len[index] = math.hypot(dif_x[index] / self.scaleratio, dif_y[index])\n\n # Make arrow lengths\n arrow_len = [None] * len(self.x)\n arrow_len = [i * self.arrow_scale for i in barb_len]\n\n # Get barb angles\n barb_ang = [None] * len(self.x)\n for index in range(len(barb_ang)):\n barb_ang[index] = math.atan2(dif_y[index], dif_x[index] / self.scaleratio)\n\n # Set angles to create arrow\n ang1 = [i + self.angle for i in barb_ang]\n ang2 = [i - self.angle for i in barb_ang]\n\n cos_ang1 = [None] * len(ang1)\n for index in range(len(ang1)):\n cos_ang1[index] = math.cos(ang1[index])\n seg1_x = [i * j for i, j in zip(arrow_len, cos_ang1)]\n\n sin_ang1 = [None] * len(ang1)\n for index in range(len(ang1)):\n sin_ang1[index] = math.sin(ang1[index])\n seg1_y = [i * j for i, j in zip(arrow_len, sin_ang1)]\n\n cos_ang2 = [None] * len(ang2)\n for index in range(len(ang2)):\n cos_ang2[index] = math.cos(ang2[index])\n seg2_x = [i * j for i, j in zip(arrow_len, cos_ang2)]\n\n sin_ang2 = [None] * len(ang2)\n for index in range(len(ang2)):\n sin_ang2[index] = math.sin(ang2[index])\n seg2_y = [i * j for i, j in zip(arrow_len, sin_ang2)]\n\n # Set coordinates to create arrow\n for index in range(len(self.end_x)):\n point1_x = [i - j * self.scaleratio for i, j in zip(self.end_x, seg1_x)]\n point1_y = [i - j for i, j in zip(self.end_y, seg1_y)]\n point2_x = [i - j * self.scaleratio for i, j in zip(self.end_x, seg2_x)]\n point2_y = [i - j for i, j in zip(self.end_y, seg2_y)]\n\n # Combine lists to create arrow\n empty = [None] * len(self.end_x)\n arrow_x = utils.flatten(zip(point1_x, self.end_x, point2_x, empty))\n arrow_y = utils.flatten(zip(point1_y, self.end_y, point2_y, empty))\n return arrow_x, arrow_y", "def add_edge(self, start_node, label, end_node, properties=None, **kwargs):\r\n\t\tif properties is None:\r\n\t\t\tproperties = {}\r\n\t\tedge = Edge(self._nextid, start_node, label, end_node, properties, **kwargs)\r\n\t\tself._edges[self._nextid] = edge\r\n\t\tself._nextid += 1\r\n\t\treturn edge", "def _create_edge_ist(self) -> EdgeList:\r\n return EdgeList(self)", "def add_edge(self, e):\n a, b = e\n self[a][b] = e\n self[b][a] = e", "def add_edge(self, e):\n v, w = e\n self[v][w] = e\n self[w][v] = e", "def __init__(self, *args):\n _snap.TUNGraphEdgeI_swiginit(self, _snap.new_TUNGraphEdgeI(*args))", "def ConnectByEdge(self, edge, arrow=False):\n return self.Connect(edge.node1.index, edge.node2.index,arrow, edge.weight)" ]
[ "0.6377767", "0.57696813", "0.57174975", "0.55853325", "0.55731285", "0.55496216", "0.5487053", "0.5478329", "0.54537594", "0.5447913", "0.5423972", "0.54171115", "0.53919244", "0.5359261", "0.5346887", "0.5345027", "0.5339781", "0.53128153", "0.5301507", "0.528697", "0.527141", "0.52515155", "0.52117", "0.52111727", "0.5181256", "0.51711124", "0.51636064", "0.5147942", "0.51453745", "0.5117476" ]
0.75913894
0
adds config file and Connection creating object to ctx This will prepare the context for other commands. It reads the config file and adds the file to the Context. It also instantiates the CreateConnection class which allows for lazy loading of the Youtrack connection so that we only try to connect if we are required to.
def youtrack(ctx, url, username, password): class CreateConnection(object): def __init__(self, url, username, password, cfg): if not url: url = cfg.get('connection', 'url') if not username: username = cfg.get('connection', 'username') self.url = url self.username = username self.password = password def create(self): if not self.password: message = "Please enter the password for the YouTrack user {0}".format(self.username) self.password = click.prompt(message, hide_input=True) return Connection(self.url, self.username, self.password) ctx.obj = dict() cfg = read_config() ctx.obj['cfg'] = cfg if 'config' != ctx.invoked_subcommand: try: ctx.obj['create_connection'] = CreateConnection(url, username, password, cfg) except NoOptionError as e: ctx.fail("No configuration set for connection to YouTrack. " "Please add your url and username to the config by using the following commands:\n\n" "youtrack config add connection.username <username>\n" "youtrack config add connection.url <url>\n")
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def config_create():\r\n\r\n \"\"\"\r\n global CONSUMER_KEY \r\n global CONSUMER_SECRET \r\n global ACCESS_KEY \r\n global ACCESS_SECRET\r\n global TweetBotName \r\n global StreamL \r\n global TweetL \r\n global NSFW \r\n global SFW \r\n global searchterm \r\n global tMax \r\n global tMin \r\n global tStep\r\n \r\n config = configparser.ConfigParser()\r\n with open('botconfig.ini', 'r') as configfile:\r\n config.read_file(configfile)\r\n CONSUMER_KEY = config.get('Auth', 'CONSUMER_KEY') \r\n CONSUMER_SECRET = config.get('Auth', 'CONSUMER_SECRET').encode('utf-8') \r\n ACCESS_KEY = config.get('Auth', 'ACCESS_KEY').encode('utf-8')\r\n ACCESS_SECRET = config.get('Auth', 'ACCESS_SECRET').encode('utf-8')\r\n TweetBotName = config.get('Auth', 'BotName')\r\n StreamL = config.get('Log', 'Log1')\r\n TweetL = config.get('Log', 'Log2')\r\n NSFW = config.get('Filter', 'String1')\r\n SFW = config.get('Filter', 'String2')\r\n searchterm = config.get('Filter', 'Search')\r\n tMax = int(float(config.get('Tweet_Delay', 'Max')))\r\n tMin = int(float(config.get('Tweet_Delay', 'Min')))\r\n tStep = int(float(config.get('Tweet_Delay', 'Step')))\r\n global api \r\n\r\n \"\"\"\r\n config = configparser.ConfigParser()\r\n with open('botconfig.ini', 'r') as configfile:\r\n config.readfp(configfile)\r\n return config", "async def setup(self, ctx):\n pass", "def _create_ssl_context(cfg):\n ctx = ssl.SSLContext(cfg.ssl_version)\n ctx.load_cert_chain(cfg.certfile, cfg.keyfile)\n ctx.verify_mode = cfg.cert_reqs\n if cfg.ca_certs:\n ctx.load_verify_locations(cfg.ca_certs)\n if cfg.ciphers:\n ctx.set_ciphers(cfg.ciphers)\n return ctx", "async def _create_context(self) -> ssl.SSLContext:\n context = utils.server_context_modern()\n\n await self.cloud.run_executor(\n context.load_cert_chain,\n self._acme.path_fullchain,\n self._acme.path_private_key,\n )\n\n return context", "def setupResources(self):\r\n if self.initialized == True: return\r\n try:\r\n LOG(\"Configuring driver for context \" + repr(self.contextName))\r\n DriverManager.instance().setup(self.contextName)\r\n self.initialized = True\r\n \r\n except SpellException,ex:\r\n traceback.print_exc( file = sys.stderr )\r\n LOG(\"Could not setup driver: \" + repr(ex), LOG_ERROR)\r\n self.errorMessage = ex.message\r\n self.errorReason = ex.reason\r\n raise ex", "def create_config(self) -> None:\n if self.is_config_exist() is False:\n file = open(file=self.connection_string, mode=\"w+\")\n file.close()", "def __init__(self, config_file, ssl=False, plugin_config = {}):\n self.config_file = config_file\n self.botconfig = self.load_config(config_file)\n auth = self.botconfig.find('auth')\n logging.info(\"Logging in as %s\" % auth.attrib['jid'])\n sleekxmpp.ClientXMPP.__init__(self, auth.attrib['jid'], auth.attrib['pass'], auth.get('ssl', True), plugin_config)\n storageXml = self.botconfig.find('storage')\n if storageXml is not None:\n self.store = store(storageXml.attrib['file'])\n else:\n logging.warning(\"No storage element found in config file - proceeding with no persistent storage, plugin behaviour may be undefined.\")\n self.rooms = {}\n self.add_event_handler(\"session_start\", self.handle_session_start, threaded=True)\n self.register_xmpp_plugins()\n CommandBot.__init__(self)\n PlugBot.__init__(self, default_package = 'sleekbot.plugins')\n self.register_adhocs()", "def setup(self, ctxConfig, drvConfig):\n superClass.setup(self, ctxConfig, drvConfig)\n # TODO Your startup stuff here", "async def launch(config, session, context, connection_file):\n raise NotImplementedError(\"launch must be implemented\")", "def __setup_conn__(self, **kwargs):\n self.ext_conn = setup_conn(**kwargs)", "def connect(self) -> ContextManager[Connection]:", "def load_config(self, context: ResourceCommandContext, config_file_location: str) -> None:\n enqueue_keep_alive(context)\n self.handler.load_config(context, config_file_location)", "def work(self):\n self.config_file = self.args.config\n self.init_config()\n self.init_db()\n\n self.kickoff()", "async def do_config():\n\n\n async def cfg_add():\n try:\n if config[message.server.id]:\n await bot.send_message(c, 'The channel is already configured.')\n return\n except:\n config[message.server.id] = {\n 'server_api_1': '',\n 'server_api_2': '',\n 'welcome_msg enabled': False,\n 'welcome_msg': '',\n }\n\n async def cfg_ip():\n ip = message.content.split()[2]\n config[message.server.id]['server_api_1'] = f'https://mcapi.us/server/status?ip={ip}'\n config[message.server.id]['server_api_2'] = f'https://eu.mc-api.net/v3/server/ping/{ip}'\n\n async def cfg_port():\n port = message.content.split()[2]\n try:\n config.get(message.server.id, 'server_api_1')\n config.get(message.server.id, 'server_api_2')\n except:\n await bot.send_message(c, 'IP not configured.')\n return\n config[message.server.id]['server_api_1'] += f'&port={port}'\n config[message.server.id]['server_api_2'] += f'%3A{port}'\n\n async def cfg_wmsg():\n msg = message.content.split('wmsg')[1].strip()\n config[message.server.id]['welcome_msg'] = msg\n\n subcommands = {\n 'add': cfg_add,\n 'ip': cfg_ip,\n 'port': cfg_port,\n 'wmsg': cfg_wmsg,\n }\n\n appinfo = await bot.application_info()\n\n if message.author.display_name != appinfo.owner.name and not message.author.server_permissions.manage_server:\n await bot.send_message(c, 'You don\\'t have the proper permissions to configure this bot.')\n return\n\n for i in subcommands:\n if message.content.split()[1] == i:\n await subcommands[i]()\n with open('dbot_config.ini', 'w') as f:\n config.write(f)\n await bot.send_message(c, 'Success.')", "def init(self, args, **kwargs):\n # Retrieve configuration file and directory or set defaults.\n conf_file = os.path.expanduser(\n args._get('conf_file', kwargs.pop('conf_file', DEFAULT_CONF_FILE)))\n conf_dir = os.path.expanduser(\n args._get('conf_dir', kwargs.pop('conf_dir', DEFAULT_CONF_DIR)))\n commands = [value for (arg, value) in sorted(args) if arg.startswith('command')]\n\n # Load main configuration file.\n if os.path.exists(conf_file):\n self.load_cmd_file(conf_file)\n\n # Load intermediary configuration files.\n if os.path.isdir(conf_dir):\n self.load_dir(conf_dir, clg.config, commands)", "def connect(self):\n # Load the config into a Object\n config = yaml.load(self.read_yaml(), yaml.FullLoader)\n gl = gitlab.Gitlab(url=config[\"gitlab-url\"], private_token=config[\"auth-token\"])\n self.gl = gl\n self.config = config", "def setup(cls):\n cls.runner = CliRunner()\n cls.agent_name = \"myagent\"\n cls.cwd = os.getcwd()\n cls.t = tempfile.mkdtemp()\n # copy the 'packages' directory in the parent of the agent folder.\n shutil.copytree(Path(CUR_PATH, \"..\", \"packages\"), Path(cls.t, \"packages\"))\n\n os.chdir(cls.t)\n result = cls.runner.invoke(\n cli,\n [*CLI_LOG_OPTION, \"init\", \"--author\", AUTHOR],\n standalone_mode=False,\n )\n assert result.exit_code == 0\n result = cls.runner.invoke(\n cli,\n [*CLI_LOG_OPTION, \"create\", \"--local\", cls.agent_name],\n standalone_mode=False,\n )\n assert result.exit_code == 0\n os.chdir(cls.agent_name)\n # add connection first time", "def config(ctx):\n return", "def __init__(self, ctx: Context) -> None:\n self.ctx = ctx\n self.driver = self.ctx.driver", "def setup_class(cls):\n cls.cwd = os.getcwd()\n cls.t = tempfile.mkdtemp()\n os.chdir(cls.t)\n\n temp_dir = os.path.join(cls.t, \"temp_dir_node\")\n os.mkdir(temp_dir)\n cls.connection_node = _make_libp2p_connection(data_dir=temp_dir, delegate=True)\n temp_dir_client = os.path.join(cls.t, \"temp_dir_client\")\n os.mkdir(temp_dir_client)\n cls.connection = _make_libp2p_client_connection(\n data_dir=temp_dir_client, peer_public_key=cls.connection_node.node.pub\n )", "def setup(args):\n cfg = get_cfg()\n cfg.merge_from_file(args.config_file)\n cfg.merge_from_list(args.opts)\n cfg.freeze()\n default_setup(cfg, args)\n return cfg", "def setup(args):\n cfg = get_cfg()\n cfg.merge_from_file(args.config_file)\n cfg.merge_from_list(args.opts)\n cfg.freeze()\n default_setup(cfg, args)\n return cfg", "def setup(args):\n cfg = get_cfg()\n cfg.merge_from_file(args.config_file)\n cfg.merge_from_list(args.opts)\n cfg.freeze()\n default_setup(cfg, args)\n return cfg", "def __init__(self, **kwargs):\n configPath = kwargs.get(\"configPath\", \"exdb-config-example.yml\")\n self.__configName = kwargs.get(\"configName\", \"site_info_remote_configuration\")\n mockTopPath = kwargs.get(\"mockTopPath\", None)\n self.__cfgOb = ConfigUtil(configPath=configPath, defaultSectionName=self.__configName, mockTopPath=mockTopPath)\n self.__workPath = kwargs.get(\"workPath\", HERE)\n self.__cachePath = kwargs.get(\"cachePath\", os.path.join(self.__workPath, \"CACHE\"))\n #\n self.__stashRemotePrefix = kwargs.get(\"stashRemotePrefix\", None)\n #\n self.__debugFlag = kwargs.get(\"debugFlag\", False)\n self.__startTime = time.time()\n if self.__debugFlag:\n logger.setLevel(logging.DEBUG)\n logger.debug(\"Starting at %s\", time.strftime(\"%Y %m %d %H:%M:%S\", time.localtime()))\n #", "def connect(self):\n config.base_url = self.get_config('host')\n config.client_connection_attempts = 1\n config.assume_untrusted = False\n if self.get_config('insecure'):\n config.assume_untrusted = True\n\n config.credentials = utils.PseudoNamespace({\n 'default': {\n 'username': self.get_config('username'),\n 'password': self.get_config('password'),\n }\n })\n\n _, remainder = self.parser.parse_known_args()\n if remainder and remainder[0] == 'config':\n # the config command is special; it doesn't require\n # API connectivity\n return\n # ...otherwise, set up a awxkit connection because we're\n # likely about to do some requests to /api/v2/\n self.root = api.Api()\n try:\n self.fetch_version_root()\n except RequestException:\n # If we can't reach the API root (this usually means that the\n # hostname is wrong, or the credentials are wrong)\n if self.help:\n # ...but the user specified -h...\n known, unknown = self.parser.parse_known_args(self.argv)\n if len(unknown) == 1 and os.path.basename(unknown[0]) == 'awx':\n return\n raise", "def __init__(self, *args, **kwargs):\n self.context = kwargs.get(\"config\")\n if hasattr(self.context, 'database'):\n # XXX this should be replaced with connection_context instead\n self.context.database['database_host'] = \\\n self.context.database.database_hostname\n self.context.database['database_port'] = \\\n self.context.database.database_port\n self.context.database['database_name'] = \\\n self.context.database.database_name\n self.context.database['database_username'] = \\\n self.context.database.database_username\n self.context.database['database_password'] = \\\n self.context.database.database_password\n self.database = db.Database(self.context.database)\n else:\n # the old middleware\n self.database = db.Database(self.context)", "def __init__(self, configfile=None):\n self.withwith = ('2.5' in psycopg2.__version__)\n self.conn = None\n self.setdefaults()\n if configfile is not None:\n self.loadconfig(configfile)", "def __init__(self, config_file_name=\"config.json\"):\n self.config_file_name = config_file_name\n self._config = self._open_config_file()", "def get_config_file(self):\n\n conf_file = self.args.file\n if conf_file is not None:\n if os.path.isfile(conf_file):\n config_file = open(conf_file, \"r\")\n self.main_file = yaml.load(config_file, Loader=yaml.FullLoader)\n elif os.path.isfile(\n os.path.join(get_path(\"DEFAULT\", \"config_file_path\"), conf_file)\n ):\n fpath = get_path(\"DEFAULT\", \"config_file_path\")\n config_file = open(os.path.join(fpath, conf_file), \"r\")\n self.main_file = yaml.load(config_file, Loader=yaml.FullLoader)\n else:\n self.logger.error(\n colorama.Fore.RED\n + \"ERROR!! Config file '%s' is not present \" % conf_file,\n extra=self.log_detail,\n )\n sys.exit(1)\n else:\n if self.args.hostname and self.args.testfiles:\n temp_dict = {\n \"hosts\": [{\"device\": \"\", \"username\": \"\", \"passwd\": \"\"}],\n \"tests\": [],\n }\n temp_dict[\"hosts\"][0][\"device\"] = self.args.hostname\n temp_dict[\"hosts\"][0][\"username\"] = self.args.login\n temp_dict[\"hosts\"][0][\"passwd\"] = self.args.passwd\n for tfile in self.args.testfiles:\n temp_dict[\"tests\"].append(tfile)\n self.main_file = temp_dict\n\n if (\n self.main_file.__contains__(\"sqlite\")\n and self.main_file[\"sqlite\"]\n and self.main_file[\"sqlite\"][0]\n ):\n self.chk_database(\n self.main_file,\n self.args.pre_snapfile,\n self.args.post_snapfile,\n self.args.check,\n self.args.snap,\n )\n else:\n # if --check option is given for sqlite, then snap file name is not compulsory\n # else exit the function saying arguments not correct\n if self.args.check is True and (\n self.args.pre_snapfile is None or self.args.post_snapfile is None\n ):\n self.logger.error(\n colorama.Fore.RED\n + \"Arguments not given correctly, Please refer help message\",\n extra=self.log_detail,\n )\n self.parser.print_help()\n sys.exit(1)", "def cli(ctx):\n config = get_config_data()\n\n ctx.obj = config" ]
[ "0.5525787", "0.55179673", "0.5470595", "0.54597384", "0.54575396", "0.5417419", "0.5349808", "0.5319401", "0.5318282", "0.5314346", "0.5311134", "0.5266186", "0.52488166", "0.5244951", "0.52314883", "0.5213098", "0.517702", "0.5170664", "0.51704514", "0.5147311", "0.5133716", "0.5133716", "0.5133716", "0.5123173", "0.51161176", "0.5087751", "0.5084941", "0.5047947", "0.503949", "0.5027203" ]
0.6027475
0
view command for config if no subcommand called
def config(ctx): if not ctx.invoked_subcommand: cfg = ctx.obj['cfg'] for section in cfg.sections(): print("[", section, "]") for option in cfg[section]: print(option, " = ", cfg[section][option])
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def command():\n return _config.command", "def subcommand_foo(self):\n print('foo: ')\n baz.print_configuration()", "def main(ctx):\n\n print(\"Mode:\", ctx.invoked_subcommand)", "def config_mode(self, config_command=\"config\", pattern=\">config\"):\n return super().config_mode(config_command=config_command, pattern=pattern)", "def cmdopt(request):\n return request.config.getoption(\"-c\")", "def cli(ctx: click.Context) -> None:\n if ctx.invoked_subcommand is None:\n click.echo('Unable to find blowhole configuration.', err=True)\n click.echo('Nothing is implemented here.', err=True)", "async def config(self, ctx):\n await ctx.send_help(ctx.command)", "def cli():\n pass # do nothing here, it just defines the name for other subcommands", "def print_config_option(args, run):\n print_config(run)\n print(\"-\" * 79)", "def additional_command(self):\n pass", "def _find_subcommand(args):\n subcmd = args[1]\n if subcmd in [\n \"cfg\"\n # , 'init',\n ]:\n return subcmd\n else:\n return None", "def is_configured(command):\n return command in COMMANDS", "def do_config(self, args):\n self.config_command.cmdloop(\"Enter to config mode\")", "def __str__(self):\n if not self._args and not self.subcommand:\n return self.cmd\n elif not self._args and self.subcommand:\n return '{} {}'.format(\n self.cmd, self.subcommand)\n elif self._args and not self.subcommand:\n return '{} {}'.format(\n self.cmd, ' '.join(self._args))\n else:\n return '{} {} {}'.format(\n self.cmd, self.subcommand, ' '.join(self._args))", "def command():\n pass", "def help_help(self):\n print(\"List commands or print details about a command\")", "def _MocaCtlShowConfig(self):\n mc = subprocess.Popen([MOCACTL, 'show', '--config'], stdout=subprocess.PIPE)\n out, _ = mc.communicate(None)\n return out.splitlines()", "def get_command(self, context, name):\n\t\tif name not in self.commands:\n\t\t\tclue = lnk.errors.Message('Did you mess up the default settings?',\n\t\t\t\t\t\t\t\t\t level=0)\n\t\t\ttry_message = lnk.errors.Message(\"See what 'lnk config -k service'\"\n\t\t\t\t\t\t\t\t\t \t\t \" says.\", level=1)\n\t\t\traise lnk.errors.UsageError('Invalid default service.',\n\t\t\t\t\t\t\t\t\t\tClue=clue,\n\t\t\t\t\t\t\t\t\t\tTry=try_message)\n\t\treturn self.commands[name]", "def command_short():\n pass", "def cli(ctx):\n if ctx.invoked_subcommand not in ['configure', 'generate_key', 'start_agent']:\n config = get_config_file()\n if config is None:\n raise click.UsageError(\"Configuration not found!\"\n \"Please run configure before first use\")", "def __gitShowConfig(self):\n self.vcs.gitShowConfig(self.project.getProjectPath())", "def _get_config(self, *args, **kwargs):\n # Just need to show the parameter screen...the parser for the command\n # does the update_many()\n self._go_to_root_menu()\n self._navigate(SubMenu.SHOW_PARAM)\n self._go_to_root_menu()", "def cmd(self):", "def showcommands(command=None, showall=None):\n # pydoc.help(ixnetPyCli)\n if command == None:\n print('\\nCommand list:\\n')\n else:\n print('\\tHelp on command usage: {0}'.format(command))\n\n for name,obj in inspect.getmembers(sys.modules[__name__]):\n if name in ['completer', 'runixncfgconfig', 'runjsonconfig', 'getInput', 'configIxNetworkFromScratch']: continue\n #if inspect.isfunction(obj) and eval(name+'.__doc__') is not None:\n if inspect.isfunction(obj):\n parameters = inspect.getargspec(eval(name))\n\n if parameters[0] == []:\n parameters = ''\n if command is None:\n print('\\t{0}({1})'.format(name, parameters))\n else:\n parameters = ' '.join(parameters[0][0:])\n if command != None and name == command:\n print('\\n\\t{0}({1})'.format(name, parameters))\n if command == None:\n print('\\t{0} ({1})'.format(name, parameters))\n\n if showall is not None:\n print('\\t{0}'.format(eval(name+'.__doc__')))\n print()\n print()\n\n if command == None:\n print('\\n\\n Example:')\n print('\\tThe first thing you need to do is create a preference file in the /Preferences directory.')\n print('\\tMake a copy of the provided template.py and give it a meaningful name.')\n print('\\t Ex: joe.py')\n\n print('\\n\\t1> Enter: setpreferences(\"Your preference file\")')\n print('\\n\\t2> For Windows chassis connection, enter: connecttowindows()')\n print('\\t For Linux chassis connection, enter: connecttolinux()')\n print('\\t To connect to an existing Linx session ID: connecttolinux(resume=True, sessionId=<id>)')\n print() \n print('\\t3> To load a saved config file and use the chassisIp/ports saved in the config file:')\n print('\\t Enter: loadsavedconfig(\"ConfigFiles/<config file>\")')\n print()\n print('\\t To load a saved config file and optionally assign chassis and ports:')\n print('\\t Enter: loadsavedconfig(\"ConfigFiles/<config file>\", chassisIp=<ip>, ')\n print('\\t portList=[[ixChassisIp, \"1\", \"1\"], [ixChassisIp, \"2\", \"1\"]])')\n print()\n print('\\t To create a configuration from scratch:')\n print('\\t Enter: config(\"ConfigFiles/<params file>\")')\n print()", "def market(ctx):\n if ctx.invoked_subcommand is None:\n logger.info(ctx.command.get_help(ctx))", "def process_command(self, cmd, config):\n return None, None", "def print_usage_command(self):\n print self.get_usage_command()", "def print_usage_command(self):\n print self.get_usage_command()", "def command(self):\n raise NotImplementedError", "def do_display_config(self, *arg):\n try:\n if self.pocs and self.pocs.config:\n pprint(self.pocs.config)\n else:\n print_warning(\"No config file for POCS.\")\n\n except AttributeError:\n print_warning(\"Please run `setup_pocs` before trying to run `display_config`\")" ]
[ "0.73776984", "0.68675506", "0.65850604", "0.655881", "0.64289594", "0.6370118", "0.62698364", "0.62263596", "0.613195", "0.6106364", "0.60411704", "0.6039722", "0.6039082", "0.60292476", "0.60105103", "0.59776926", "0.59661555", "0.59473556", "0.59448", "0.594449", "0.59385127", "0.59176844", "0.5900457", "0.5899971", "0.5898587", "0.5858567", "0.58511513", "0.58511513", "0.5850049", "0.5840142" ]
0.7026435
1
Called by get_all_poll_data, gets poll data from rcp site
def get_rcp_poll_data(website_url): all_races = dict() page = requests.get(website_url) page.raise_for_status() bs_obj = bs4.BeautifulSoup(page.text, 'html.parser') td_race = bs_obj.find_all("td", "lp-race") td_poll = bs_obj.find_all("td", "lp-poll") td_results = bs_obj.find_all("td", "lp-results") td_spread = bs_obj.find_all("td", "lp-spread") td_index = 0 for race_val in td_race: if race_val.string not in all_races: new_race = data_structures.RaceData(race_val.string) new_race.race_poll_str_data.append(td_results[td_index].string) new_race.race_spread_str_data.append(td_spread[td_index].string) new_race.poll_source_str.append(td_poll[td_index].string) all_races[race_val.string] = new_race else: old_race = all_races[race_val.string] old_race.race_poll_str_data.append(td_results[td_index].string) old_race.race_spread_str_data.append(td_spread[td_index].string) old_race.poll_source_str.append(td_poll[td_index].string) td_index+=1 return all_races
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_all_poll_data():\n\trcp_poll_race_dict = get_rcp_poll_data('http://www.realclearpolitics.com/epolls/latest_polls/') # realclearpolotics poll data\n\treturn rcp_poll_race_dict", "def polling_call(self) -> global___Snippet.ClientCall:", "def poll(self):\n self.get_peers()\n self.get_trackers()\n self.get_files()", "def getSitesData( self ):\n if self.lastDataRetrievalTime - time.time() < 300:\n result = self.__getRPCClient().getSitesData()\n if 'rpcStub' in result:\n del( result[ 'rpcStub' ] )\n if not result[ 'OK' ]:\n return result\n self.sitesData = result[ 'Value' ]\n if self.sitesData:\n self.lastDataRetrievalTime = time.time()\n return S_OK( self.sitesData )", "def poll(self):\n self.poll_function(self.connection)", "def poll(self, poll_input):", "def _get_poll_info(self, poll_id):\n url = 'https://strawpoll.me/api/v2/polls/{}'.format(poll_id)\n for attempt in range(5):\n try:\n r = requests.get(url)\n poll_options = r.json()['options']\n poll_votes = r.json()['votes']\n except ValueError:\n continue\n except TypeError:\n continue\n else:\n return poll_options, poll_votes\n else:\n self._add_to_chat_queue(\n \"Sorry, there was a problem talking to the strawpoll api. Maybe wait a bit and retry your command?\")", "def get_poll_data(game_type_id, poll_id):\n\n poll_response = requests.get(\n url=f'{settings.GAME_SETUP_URL}/next-poll/{game_type_id}/{poll_id}/',\n timeout=5 # in sec\n )\n if poll_response.status_code == 200:\n return poll_response.json()\n return {}", "def crawl(self):\n retrievedSubs = []\n reddit = praw.Reddit(\n client_id='QRl_4bwjckcg9A',\n client_secret='dsavqFoOk5NgWEOWtMf9NknwxRIoIw',\n password='P@ssword123',\n user_agent='cluelessv1',\n username='theclueless1009'\n )\n submissions = reddit.subreddit('all').search(self.keyword, sort='relevance', limit=50, time_filter='week')\n\n for sub in submissions:\n self.data = [sub.selftext, sub.upvote_ratio, sub.score,\n sub.title, sub.id, sub.total_awards_received, sub.created_utc]\n self.data = tuple(self.data)\n retrievedSubs.append(self.data)\n\n return retrievedSubs", "def get_poll(game_type_id, poll_id):\n\n # get data for the poll from cache\n poll_key = settings.POLL_DATA_KEY.format(id=poll_id)\n print('Selected poll ID: ', poll_id)\n poll_data = cache.get(poll_key)\n if not poll_data:\n poll_data = get_poll_data(game_type_id, poll_id)\n shuffle(poll_data.get('answers'))\n return poll_data", "def webScraper(self):\n try:\n self.covid_df = pd.read_csv(self.COVID_URL)\n except:\n sys.exit('COVID data is unavailable at source.')\n \n latest_date = self.covid_df['date'].max()\n earliest_date = self.covid_df['date'].min()\n self.covid_df = self.covid_df[self.covid_df['date'] == self.date.strftime('%Y-%m-%d')]\n \n if self.covid_df.empty:\n exit_string = 'Requested date not available. Latest date available is ' + latest_date + ' while earliest is ' + earliest_date\n sys.exit(exit_string)\n else:\n self.covid_df = self.covid_df[self.covid_df['location'] != 'World']\n \n try:\n self.countries_centroids = pd.read_html(self.CENTROIDS_URL, header=0, index_col='country')[0]\n except:\n sys.exit('Central coordinates data for countries unavailable from Google developers.')\n \n try:\n self.geo_data = requests.get(self.GEOJSON_URL).json()\n except:\n sys.exit('GeoJSON data unavailable to draw country polygons.')", "def get_poll(self, poll_key):\n if poll_key[:5] != 'poll_':\n raise Exception('Incorrect key passed to get_poll(): ' + poll_key)\n poll_data = self.client.get(poll_key)\n if poll_data is None:\n return None\n else:\n return loads(poll_data)", "def poll(self) -> None:\n self._resolve_rdates()\n self._resolve_queries()\n self._process_special_cells()\n self._fetch_queries()", "def fetch_data(self, pre_site_method_url, params):\n\n # Create the main body of Api url with the pre_site_method part\n url = \"{}{}\".format(self._body_url, pre_site_method_url)\n\n data = []\n while True:\n # Request to api with the url that created and params\n response = requests.get(url, params=params)\n response.encoding = 'utf-8-sig'\n response = response.json()\n data.append(response)\n # If 'has_more' at the end of the response\n # param page increase by 1 and a new request is created\n if 'has_more' in response and response['has_more']:\n params[\"page\"] += 1\n else:\n break\n if 'error_id' in response.keys():\n raise ValueError('Api blocks me to get data.Api return error_name: throttle_violation')\n\n r = []\n for d in data:\n r.extend(d['items'])\n\n return list(chain(r))", "def _fetch_data(self):\n pass", "def _poll(self):\n return self.zmq_core.poll(10)", "async def _refresh(context):\n url = \"https://wotd.transparent.com/rss/pt-widget.xml\"\n while True:\n try:\n transport = httpx.AsyncHTTPTransport(retries=3)\n async with httpx.AsyncClient(transport=transport, timeout=10) as client:\n response = await client.get(url)\n response.raise_for_status()\n data = _parse(response.text)\n await context.post_event(\"refresh\", data)\n context.vote_connected()\n except httpx.TransportError as ex:\n # https://www.python-httpx.org/exceptions/\n context.vote_disconnected(ex)\n _logger.exception(\"Network error getting word-of-the-day data.\")\n except Exception: # pylint: disable=broad-except\n _logger.exception(\"Error getting word-of-the-day data.\")\n\n await sleep(REFRESH_INTERVAL.total_seconds())", "def load_data(self):\n try:\n df = self.live_quote_arg_func(self.tickers)\n for index, ticker in enumerate(self.tickers):\n ticker_info = df.loc[index]\n self.ticker_dict[ticker].append(ticker_info['price'],\n ticker_info['volume'],\n ticker_info['amount'],\n ticker_info['time'])\n except Exception:\n raise ValueError('Polling thread exception')", "def get_html(self):\r\n params = {\r\n 'element_id': self.location.html_id(),\r\n 'element_class': self.location.category,\r\n 'ajax_url': self.system.ajax_url,\r\n 'configuration_json': self.dump_poll(),\r\n }\r\n self.content = self.system.render_template('poll.html', params)\r\n return self.content", "def poll(self):\n log.msg('JsonPoller.poll')\n if self._password:\n postdata = urllib.urlencode({'password': self._password})\n else:\n postdata = ''\n headers = {'Content-Type': 'application/x-www-form-urlencoded'}\n d = client.getPage(self._url, method='POST',\n postdata=postdata, headers=headers)\n d.addCallback(self._handleJobs)\n d.addErrback(log.err, 'error in JsonPoller.poll')\n return d", "def poll(self):\n raise NotImplementedError()", "def poll_price_data():\n resp = requests.get(COINDESK_ENDPOINT) # Powered by CoinDesk\n if resp.status_code == 200:\n logging.info(\"GET request succeeded\")\n data = resp.json()\n data_dict = {\n \"id\": str(uuid.uuid1()),\n \"time\": data['time']['updated'],\n \"currency\": data['bpi']['USD']['code'],\n \"price\": data['bpi']['USD']['rate']\n }\n return data_dict\n else:\n logging.error(\"GET request failed\")", "def grab_server_data(self):\n\n for server, channels in self.servers.items():\n for channel in channels:\n cutoff = self.get_last_scrape_date(server, channel)\n print('grabbing data for {} : {} back to {} ...'.format(server, channel, cutoff.isoformat()))\n message_data = self.grab_channel_data(server, channel, cutoff)\n self.merge_and_save(message_data, server, channel)", "def getnewdata():\n try:\n os.remove(cachepath)\n except os.error:\n pass\n tdelta = int(EPGHOURS)*60*60\n now = time.time()\n later = now + tdelta\n # 2020-03-24%2021%3A00%3A00.000%2B0000\n starttime = urllib.parse.quote(datetime.fromtimestamp(now).\n strftime('%Y-%m-%d %H:00:00.000+0000'))\n # 2020-03-25%2005%3A00%3A00.000%2B0000\n stoptime = urllib.parse.quote(datetime.fromtimestamp(later).\n strftime('%Y-%m-%d %H:00:00.000+0000'))\n url = \"http://api.pluto.tv/v2/channels?start=\" + starttime + \"&stop=\" + stoptime\n\n if debugmode:\n logging.debug(url)\n\n logging.debug(\"Using api.pluto.tv, writing %s.\", CACHEFILE)\n\n try:\n wget.download(url, out=cachepath)\n except IOError:\n logging.error(\"There was an issue downloading EPG data. Exiting.\")\n sys.exit()", "def _handle_poll(self, relpath, params):\r\n request = json.loads(params.get('q')[0])\r\n ret = {}\r\n # request is a polling request for multiple files. For each file:\r\n # - id is some identifier assigned by the client, used to differentiate the results.\r\n # - path is the file to poll.\r\n # - pos is the last byte position in that file seen by the client.\r\n for poll in request:\r\n _id = poll.get('id', None)\r\n path = poll.get('path', None)\r\n pos = poll.get('pos', 0)\r\n if path:\r\n abspath = os.path.normpath(os.path.join(self._root, path))\r\n if os.path.isfile(abspath):\r\n with open(abspath, 'r') as infile:\r\n if pos:\r\n infile.seek(pos)\r\n content = infile.read()\r\n ret[_id] = content\r\n self._send_content(json.dumps(ret), 'application/json')", "def pull_latest_rcp(out_file : str = \"~/Data/gt_vis_project/clean_data/polls.csv\"):\n# \n\n rcp_jsons = {\"North Carolina\" : \"https://www.realclearpolitics.com/epolls/json/6744_historical.js?1602635842295&callback=return_json\",\n \"Wisconsin\" : \"https://www.realclearpolitics.com/epolls/json/6849_historical.js?1602638476165&callback=return_json\",\n \"Florida\" : \"https://www.realclearpolitics.com/epolls/json/6841_historical.js?1602638538981&callback=return_json\",\n \"Michigan\": \"https://www.realclearpolitics.com/epolls/json/6761_historical.js?1602638561657&callback=return_json\",\n \"Pennsylvania\" : \"https://www.realclearpolitics.com/epolls/json/6861_historical.js?1602638584280&callback=return_json\",\n \"Arizona\" : \"https://www.realclearpolitics.com/epolls/json/6807_historical.js?1602638600473&callback=return_json\",\n \"Ohio\": \"https://www.realclearpolitics.com/epolls/json/6765_historical.js?1602638729359&callback=return_json\",\n \"Minnesota\" : \"https://www.realclearpolitics.com/epolls/json/6966_historical.js?1602638770015&callback=return_json\",\n \"Iowa\": \"https://www.realclearpolitics.com/epolls/json/6787_historical.js?1602638787908&callback=return_json\",\n \"Texas\" : \"https://www.realclearpolitics.com/epolls/json/6818_historical.js?1602638819149&callback=return_json\",\n \"Georgia\" : \"https://www.realclearpolitics.com/epolls/json/6974_historical.js?1602638840551&callback=return_json\",\n # Nothing from Virgina or Nevada or Colorado, or new mexico.\n \"New Hampshire\" : \"https://www.realclearpolitics.com/epolls/json/6779_historical.js?1602638879306&callback=return_json\",\n \"Maine\" : \"https://www.realclearpolitics.com/epolls/json/6922_historical.js?1602638900859&callback=return_json\",\n \"National\" :\"https://www.realclearpolitics.com/epolls/json/6247_historical.js?1602638622255&callback=return_json\"\n }\n final_df = pd.DataFrame()\n for state, url in rcp_jsons.items():\n print(state)\n # Pull in raw json\n rv = requests.get(url)\n rv = rv.content.decode('utf-8') # byte to string\n # 12:2 is to remove the return_json() characters.\n print(\"converting to dict\")\n raw_poll_json = json.loads(rv[12:-2]) # string to dict.\n \n # Convert to df\n print(\"converting to df\")\n tmp_df = poll_to_df(raw_poll_json)\n tmp_df['state'] = state\n final_df = final_df.append(tmp_df)\n final_df[\"state\"] = [us_state_abbrev[state] if state in us_state_abbrev.keys() else state for state in final_df[\"state\"]]\n final_df[\"date\"] = pd.to_datetime(final_df[\"date\"], utc = True).dt.date\n final_df.to_csv(out_file, index = False)\n\n return final_df", "def poll(self):\n log.info(\"==>\")\n # TODO exception\n self.put_event(self.SubscriptionEvent.SAMPLE)\n log.info(\"<==\")", "def scrape(site=''):\n scraper.scrape(get_site_config(site))", "async def get_contents(self):\n if self._recon < 0:\n raise ValueError('Reconnection time needs to be positive!')\n urls = self._urls\n proxy_list = await self._pool.get_proxies(self._recon + 1)\n \n for count in range(self._recon + 1):\n proxy = proxy_list[count]\n if count > 0: # perform reconnection\n if not self._re_urls:\n print('No need to reconnect.')\n break\n else:\n if count == 1:\n print('Reconnecting...')\n print('\\n----------------------------------------------------------')\n print(ordinal[count].capitalize() + ' reconnection...\\n')\n urls = self._re_urls\n\n result_list = await self._connect(urls, proxy=proxy, which_site=True)\n\n self._re_urls.clear() # empty the reconnect urls list \n for result in result_list:\n url, soup, status, site = result\n if not self._error(url, soup, status, site, True):\n self._result += self._get_plain_text(url, soup, site)\n fail_num = len(self._re_urls)\n if count == self._recon:\n print('Failed to crawl ' + str(fail_num) + (' website.' if fail_num==1 else ' websites.'))\n\n self._result = re.sub(r'\\s+', '', self._result) # trim whitespaces\n self._result = self._rm_duplicate(self._result)", "def get_political_handles(list_file=['files/inc_handles.txt', 'files/bjp_handles.txt'], get_online=True):\n ls_fin = []\n for i in range(1, 23):\n url = \"https://www.socialbakers.com/statistics/twitter/profiles/india/society/politics/page-\" + \\\n str(i) + \"/?showMoreList-from=1&do=platformList-renderAjax&json\"\n html = urllib.request.urlopen(url)\n soup = BeautifulSoup(html, 'html.parser')\n intm = soup.find_all('h2')\n for y in intm:\n for x in y.find_all('span'):\n ls_fin.append(x.text.split(\n '(')[-1].replace(')', '').replace('@', ''))\n for file in list_file:\n with open(file) as f:\n for i in f:\n if i:\n ls_fin.append(i.strip())\n logging.info(str(len(ls_fin)) + \" IDs crawled\")\n return (ls_fin)" ]
[ "0.71145755", "0.5876649", "0.58502626", "0.56043375", "0.55491203", "0.5527701", "0.5467159", "0.5448426", "0.5352088", "0.53126615", "0.5300438", "0.528354", "0.52794904", "0.5267711", "0.52276313", "0.5127261", "0.5117422", "0.51122195", "0.5105585", "0.5096877", "0.5070374", "0.50509244", "0.5021489", "0.50200945", "0.4998284", "0.49882314", "0.49826872", "0.49768275", "0.4975246", "0.49665803" ]
0.61796045
1
Called by get_all_headline_data, Parse the headline html data for one news site and make each headline into a Headline object.
def get_headline_data(website_url, source): page = requests.get(website_url) page.raise_for_status() all_headlines = [] bs_obj = bs4.BeautifulSoup(page.text, 'html.parser') item_list = bs_obj.select('item') printable = set(string.printable) for curr_item in item_list: item_title = curr_item.title.string followup_link = curr_item.select('link')[0].string datestamp = curr_item.select('pubdate')[0].string item_title = item_title.replace("&apos;", "'") followup_link = followup_link.replace(u"\u2018", "'").replace(u"\u2019", "'") item_title = item_title.encode('utf-8', errors='ignore') new_headline = data_structures.Headline(item_title, followup_link, source, datestamp) all_headlines.append(new_headline) return all_headlines
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_all_headline_data():\n\twebsites = database.get_website_URLs()\n\tall_headlines_arr = []\n\tfor curr_elt in websites:\n\t\tcurr_website = curr_elt[0]\n\t\tsource = curr_elt[1]\n\t\tcurr_headline_arr = get_headline_data(curr_website, source)\n\t\tall_headlines_arr.append(curr_headline_arr)\n\treturn all_headlines_arr", "def get_headlines(outlet):\n if outlet == \"BBC\":\n parser = news_parser.BBC(\"https://www.bbc.co.uk\")\n elif outlet == \"DailyMail\":\n parser = news_parser.DailyMail(\"https://www.dailymail.co.uk\")\n elif outlet == \"Guardian\":\n parser = news_parser.Guardian(\"https://www.theguardian.com\")\n elif outlet == \"Metro\":\n parser = news_parser.Metro(\"https://www.metro.co.uk\")\n elif outlet == \"Mirror\":\n parser = news_parser.Mirror(\"https://www.mirror.co.uk/news/\")\n elif outlet == \"Reuters\":\n parser = news_parser.Reuters(\"https://uk.reuters.com\")\n elif outlet == \"Sun\":\n parser = news_parser.Sun(\"https://www.thesun.co.uk\")\n elif outlet == \"Independent\":\n parser = news_parser.Independent(\"https://www.independent.co.uk\")\n else:\n parser = news_parser.BBC(\"https://www.bbc.co.uk/news\")\n \n index = outlets.index(outlet)\n url_list = []\n while len(url_list) < 50:\n opts = {\n 'language': ['en'],\n 'source_id': [ids[index]],\n 'published_at_start':'NOW-1DAY',\n 'published_at_end':'NOW',\n 'sort_by': 'hotness',\n 'sort_direction': 'desc',\n 'cursor': '*',\n 'per_page': 100\n }\n\n try:\n api_response = api_instance.list_stories(**opts)\n for story in api_response.stories:\n url = story.links.permalink\n if url:\n url_list.append(url)\n except ApiException as e:\n print(\"Exception when calling DefaultApi->list_stories: %s\\n\" %e)\n \n opts['cursor'] = api_response.next_page_cursor\n \n url_list = url_list[:50]\n \n articles_list = []\n for url in url_list:\n raw_article = parser.get_article(url)\n if raw_article is not None:\n articles_list.append(raw_article)\n\n articles = []\n for article in articles_list:\n parsed_article = parser.parse(article)\n if parsed_article is not None:\n articles.append(parsed_article)\n \n if len(articles) > 30:\n articles = articles[:30]\n\n return articles", "def test_single_headline(self):\n\n text = \"Example headline\"\n\n for i in range(1,6):\n headline_str = '*' * i + ' ' + text\n doc = parser.parse(headline_str)\n\n headline_node = doc.children()[0]\n\n self.assertTrue(isinstance(headline_node, parser.HeadlineNode))\n self.assertEqual(headline_node.level, i)\n self.assertEqual(headline_node.text, text)", "def topheadlines():\n newsSource = click.prompt(\"Please enter your choice from listsources\")\n \n main_url = \"https://newsapi.org/v2/top-headlines?apiKey=f45fa2c71932483f832f0cc745af0325&sources=\"+newsSource\n\n\t# fetching data in json format \n open_headline = requests.get(main_url).json() \n\n\t# getting all headlines in a string articles \n headline = open_headline[\"articles\"] \n\n\t# empty list which will \n\t# contain all trending newssources \n output = [] \n\t\n for h in headline: \n click.echo('\\n')\n click.secho(click.style('TITLE: ' + h['title'], fg='red'))\n click.secho(click.wrap_text(h['description']))\n click.secho(click.style('DOMAIN: ' + h['url'], fg='blue'))\n \n \t\n for i in output[:11]:\n print(i)", "def get_headlines(newssource):\n \n \n newssource_dict = {}\n url = 'https://newsapi.org/v1/articles?source=' + newssource + '&sortBy=top&apiKey=' + api\n request = http.request('GET',url,timeout=4.0)\n\n headline = json.loads(request.data)\n \n if not headline['articles']:\n return \"NewsAPI can not receive information from\" + newsource + \"right now\"\n \n newssource_dict['url'] = headline['articles'][0]['url']\n newssource_dict['title']= headline['articles'][0]['title']\n newssource_dict['description'] = headline['articles'][0]['description']\n \n \n return newssource_dict", "def get_headlines(id):\n get_headlines_url = secondary_url.format(id,api_key)\n\n with urllib.request.urlopen(get_headlines_url) as url:\n get_headlines_data = url.read()\n get_headlines_response= json.loads(get_headlines_data)\n\n headlines_results = None\n\n if get_headlines_response['articles']:\n headlines_results_list = get_headlines_response['articles']\n headlines_results = process_headlines(headlines_results_list)\n\n return headlines_results", "def parse_news(self, response):\n \n loader = NewsLoader(item=NewsItem(), response=response)\n loader.add_xpath('title', '//header//h1/text()')\n author = ''.join(response.xpath('//span[@class=\"byline\"]').extract())\n author = remove_tags(author).replace(\"by\", '').replace(' and ', ', ')\n loader.add_value('author', author)\n timestamp = response.xpath('//meta[@name=\"DC.date.issued\"][1]/@content').extract()[0]\n timestamp = du.normalize_timestamp(timestamp)\n loader.add_value('date', timestamp.split(' ')[0])\n loader.add_value('time', timestamp.split(' ')[1])\n list_of_contents = response.xpath(\n '//div[@id=\"storytext\"]/*[not(@class=\"cnnplayer\") and '\n 'not(@class=\"storytimestamp\")]').extract()\n content = ' '.join(list_of_contents)\n loader.add_value('content', content)\n loader.add_xpath('tags', '//meta[@name=\"keywords\"]/@content')\n return loader.load_item()", "def get_headline_search(query):\n query = query.replace(' ',\"\")\n category=\"\"\n get_headlines_url = 'https://newsapi.org/v2/top-headlines?category={}&query={}&language=en&apiKey={}'.format(category,query,api_key)\n headlines_results = []\n with urllib.request.urlopen(get_headlines_url) as url:\n get_headlines_data = url.read()\n get_headlines_response = json.loads(get_headlines_data)\n if get_headlines_response['articles']:\n headlines_result_list=get_headlines_response['articles']\n for headline in headlines_result_list:\n headlines_results.append(headline)\n return headlines_results", "def __folha(soup):\n news = []\n\n # We have to get the data from a script tag and process the raw text...\n data = soup.select('#folha-top')[0].next_sibling.next_sibling.string\n\n # Line by line...\n lines = data.split('\\n')\n\n # For each line...\n for i, line in enumerate(lines):\n # If we reach the end of the array, we break from the loop\n if \"]\" in line:\n break\n\n if line.strip().startswith('title'):\n # We get the title and the link of the news\n title = __folha_get_script_content(line, is_title=True)\n link = __folha_get_script_content(lines[i + 1])\n news.append(dict(title=title, link=link))\n\n return news", "def __cnn(soup): \n news = []\n headers = soup.find_all('h3', class_='most__read__title') \n for h3 in headers:\n title = h3.a['title']\n link = h3.a['href'] \n news.append(dict(title=title, link=link))\n \n return news", "def fetch_headlines(self, retry=False):\n top_headlines_res = None\n try:\n top_headlines_res = self.news_api.get_top_headlines(\n country='in', page_size=100)\n except newsapi.newsapi_exception.NewsAPIException as err:\n print('NewsAPI Exception==', err)\n if not retry:\n print('Retrying with another key...')\n self.api_key = os.getenv('NEWS_API_KEY_BACKUP')\n self.configure_news_api()\n top_headlines_res = self.fetch_headlines(retry=True)\n else:\n return None\n except Exception as err:\n print('Exception occurred==', err)\n return None\n headlines = {}\n if top_headlines_res and top_headlines_res['status'] == 'ok':\n headlines = top_headlines_res\n else:\n headlines = None\n return headlines", "def top_headlines():\n source = \"google-news\" # TODO: Add option to choose source\n try:\n r = requests.get(\"https://newsapi.org/v2/top-headlines?sources=\" + source + \"&apiKey=\" + NEWS_API_TOKEN)\n data = r.json()\n # TODO: Find a way to include multiple articles instead of a random one\n article = data['articles'][randint(0, len(data['articles']) - 1)]\n imageurl = article['urlToImage'].replace('\\\\', '')\n embed = discord.Embed(\n title=article['title'],\n description=article['description'],\n url=article['url'],\n image_url=imageurl\n )\n embed.set_image(url=imageurl)\n embed.set_footer(text=\"Powered by NewsAPI! (newsapi.org)\")\n return embed\n except Exception as e:\n print(e)\n return discord.Embed(title=\"Something went wrong\")", "def get_headlines(driver,site,URL_exclusions):\r\n links = get_all_links(driver,site,URL_exclusions)\r\n headlines = []\r\n n=0\r\n for link in links:\r\n driver = make_driver_obj() #get_all_links quits driver when finished.\r\n try:\r\n while True:\r\n try:\r\n driver.get(link) #No need to accept cookies to don't need return_search\r\n break\r\n except:\r\n continue\r\n except: #If we can't open the URL for any reason.\r\n driver.quit()\r\n continue\r\n n += 1\r\n headline = get_headline(driver)\r\n if headline != '':\r\n headlines.append(headline) #Only append if able to identify headline text\r\n #print(n)\r\n #print(headline)\r\n #print()\r\n driver.quit()\r\n return headlines", "def all_headlines_from(url):\n pass", "def extract_news(parser):\n news_list = []\n titles = []\n authors = []\n urls = []\n coms = []\n scores = []\n mya = parser.find_all('a', class_='storylink')\n for a in mya:\n titles.append(a.contents[0])\n author = parser.find_all('a', class_='hnuser')\n for a in author:\n authors.append(a.contents[0])\n myurl = parser.find_all('a', class_='storylink')\n for a in myurl:\n urls.append(a['href'])\n comments = parser.find_all('td', class_='subtext')\n for td in comments:\n coms.append(td.find_all('a')[-1].contents[0])\n score = parser.find_all('span', class_='score')\n for span in score:\n scores.append(span.contents[0])\n for i in range(len(titles)):\n new = {}\n new['title'] = titles[i]\n new['author'] = authors[i]\n new['urls'] = urls[i]\n new['comments'] = coms[i]\n new['score'] = scores[i]\n news_list.append(new)\n return news_list", "def test_headlines_successors(self):\n headline_str = \"* First level\\n** Second level\\n*** Third level\"\n doc = parser.parse(headline_str)\n self.assertEqual(len(doc.children()), 1)\n\n h1 = doc.children()[0]\n self.assertEqual(len(h1.children), 1)\n\n h2 = h1.children[0]\n self.assertEqual(len(h2.children), 1)\n\n h3 = h2.children[0]\n self.assertEqual(len(h3.children), 0)", "def gather_headlines(urls):\n pass", "def headline(self, new_headline):\n\n # Check a type of 'new_headline' parametr\n if not isinstance(new_headline, basestring):\n raise TypeError('string type expected')\n self._headline = new_headline", "def unique_headlines(self):\n\n all_headlines = sorted(self.headlines, key=lambda x: x.datetime, reverse=True)\n unique_headlines = list(dict((headline.headline_string, headline)\n for headline in all_headlines).values())\n\n return HeadlineData(unique_headlines)", "def test_headlines_predecessors(self):\n headline_str = \"* One\\n** Two\\n*** Three\\n** Two\\n*** Three\\n* One\"\n\n doc = parser.parse(headline_str)\n self.assertEqual(len(doc.children()), 2)\n\n h1_1 = doc.children()[0]\n h1_2 = doc.children()[1]\n\n self.assertEqual(len(h1_1.children), 2)\n self.assertEqual(len(h1_2.children), 0)\n\n h2_1 = h1_1.children[0]\n h2_2 = h1_1.children[1]\n\n self.assertEqual(len(h2_1.children), 1)\n self.assertEqual(len(h2_2.children), 1)", "def process(url):\n feed = feedparser.parse(url)\n entries = feed.entries\n ret = []\n for entry in entries:\n print entry\n guid = entry.guid\n title = translate_html(entry.title)\n link = entry.link\n summary = translate_html(entry.summary)\n try:\n subject = translate_html(entry.tags[0]['term'])\n except AttributeError:\n subject = \"\"\n newsStory = NewsStory(guid, title, subject, summary, link)\n ret.append(newsStory)\n return ret", "def get_headlines():\n country = request.args.get('country', type=str)\n if country is not None:\n data = te.getNews(country=country).dropna()\n return jsonify(data.to_dict(orient='records'))\n data = te.getNews()\n return jsonify(te.getNews().dropna().to_dict(orient='records'))", "def extract_news(parser):\n news_list = []\n\n titles = parser.find_all(\"tr\", class_=\"athing\")\n subtext = parser.find_all(\"td\", class_=\"subtext\")\n\n for i in range(len(titles)):\n x = titles[i].find_all(\"td\", class_=\"title\")[1]\n title = x.a.text\n url = x.a[\"href\"]\n c = subtext[i].find_all(\"a\")[4]\n if c.text == \"discuss\":\n comments = 0\n else:\n comments = c.text\n author = subtext[i].find(\"a\", class_=\"hnuser\").get_text()\n point = subtext[i].find(\"span\", class_=\"score\").text\n points = point.split(' ')[0]\n\n news_list.append({\"author\": author, \"comments\": comments, \"points\": points, \"title\": title, \"url\": url})\n\n return news_list", "def scrape(self):\n\n self.url = self.headline.url\n\n # Should raise exception...\n if not self.parsing_template:\n return None, None, None, None, None\n\n try:\n response = self.download()\n self.source = response.text\n except:\n return None, None, None, None, None\n\n soup = BeautifulSoup(response.content, \"html.parser\")\n\n if soup:\n return self.parse(soup)\n else:\n return None, None, None, None, None", "def __metro(soup):\n news = []\n container = soup.select('.m-title')\n\n for item in container:\n a = item.a\n title = a.string\n link = a['href']\n news.append(dict(title=title, link=link))\n if len(news) == 10:\n break\n return news", "def all_headlines(html_root_node):\n pass", "def headline(self):\r\n return '%s%s %s%s' % (BLUE, self.title,\r\n NORMAL, self.link)", "def get_news(news_url):\n news_final = []\n try:\n news_handler = urllib.urlopen(news_url)\n news = news_handler.read()\n news = nl2br(news)\n news = string.split(news, '<br/>')\n\n news_array = {}\n value = {}\n for newsweb in news:\n value = string.split(newsweb, '|')\n if len(value[0]) > 1:\n news_array[value[0]] = value[1]\n\n info = {}\n for k in news_array:\n info = k[0:int(k.find(\"http://\") - 1)]\n info = string.split(k, ' - ')\n news_final.append((info[0], info[1], news_array[k]))\n\n news_handler.close()\n except IndexError:\n pass\n except IOError:\n pass\n\n return news_final", "def parse_headlines(self):\n headlines = re.findall(r\"^\\.\\.\\.(.*?)\\.\\.\\.[ ]?\\n\\n\", self.unixtext,\n re.M | re.S)\n headlines = [\" \".join(h.replace(\"...\",\n \", \").replace(\"\\n\", \" \").split())\n for h in headlines]\n return headlines", "async def news(self):\n url = f\"https://newsapi.org/v2/top-headlines?country=nz&apiKey={self.bot.news_api_key}\"\n async with ClientSession() as session:\n async with session.get(url) as response:\n r = await response.json()\n firstArticle = r[\"articles\"][0]\n nSource = firstArticle[\"source\"][\"name\"]\n nTitle = firstArticle[\"title\"]\n nTimestamp = firstArticle[\"publishedAt\"]\n embed = discord.Embed(\n title=f\"News Title: {nTitle}\", description=f\"News Source: {nSource}\"\n )\n embed.add_field(name=\"News Content\", value=firstArticle[\"description\"])\n embed.set_image(url=firstArticle[\"urlToImage\"])\n embed.set_footer(text=f\"News Timestamp: {nTimestamp}\")\n\n channel = self.bot.get_channel(self.bot.main_channel_id)\n await channel.send(embed=embed)" ]
[ "0.6478179", "0.6475193", "0.6362648", "0.635065", "0.6339492", "0.6281099", "0.6231646", "0.61889184", "0.61672", "0.60695523", "0.60031974", "0.6001032", "0.5983614", "0.5980124", "0.5951432", "0.5941756", "0.5933869", "0.5879412", "0.5856849", "0.5823046", "0.5822084", "0.58105415", "0.5750073", "0.5731022", "0.57085365", "0.5682771", "0.56487143", "0.5640883", "0.5633528", "0.5628819" ]
0.7263744
0
Gets all headlines in a 2d array of headline objects
def get_all_headline_data(): websites = database.get_website_URLs() all_headlines_arr = [] for curr_elt in websites: curr_website = curr_elt[0] source = curr_elt[1] curr_headline_arr = get_headline_data(curr_website, source) all_headlines_arr.append(curr_headline_arr) return all_headlines_arr
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_headlines(self, kw = None):\r\n\t\tif kw:\r\n\t\t\treturn self.get_headlines_with_keyword(kw)\r\n\t\telse:\r\n\t\t\treturn self.get_all_headlines()", "def get_all_headlines(self):\r\n\t\tlist_vals = list(self.keyword_headlines().values())\r\n\t\tuniq_headlines = set()\r\n\t\tfor list_val in list_vals:\r\n\t\t\tfor headlineobj in list_val:\r\n\t\t\t\tuniq_headlines.add(headlineobj.headlineid.content)\r\n\r\n\t\treturn list(uniq_headlines)", "def get_headlines(driver,site,URL_exclusions):\r\n links = get_all_links(driver,site,URL_exclusions)\r\n headlines = []\r\n n=0\r\n for link in links:\r\n driver = make_driver_obj() #get_all_links quits driver when finished.\r\n try:\r\n while True:\r\n try:\r\n driver.get(link) #No need to accept cookies to don't need return_search\r\n break\r\n except:\r\n continue\r\n except: #If we can't open the URL for any reason.\r\n driver.quit()\r\n continue\r\n n += 1\r\n headline = get_headline(driver)\r\n if headline != '':\r\n headlines.append(headline) #Only append if able to identify headline text\r\n #print(n)\r\n #print(headline)\r\n #print()\r\n driver.quit()\r\n return headlines", "def all_headlines(html_root_node):\n pass", "def get_headlines(id):\n get_headlines_url = secondary_url.format(id,api_key)\n\n with urllib.request.urlopen(get_headlines_url) as url:\n get_headlines_data = url.read()\n get_headlines_response= json.loads(get_headlines_data)\n\n headlines_results = None\n\n if get_headlines_response['articles']:\n headlines_results_list = get_headlines_response['articles']\n headlines_results = process_headlines(headlines_results_list)\n\n return headlines_results", "def get_headline_search(query):\n query = query.replace(' ',\"\")\n category=\"\"\n get_headlines_url = 'https://newsapi.org/v2/top-headlines?category={}&query={}&language=en&apiKey={}'.format(category,query,api_key)\n headlines_results = []\n with urllib.request.urlopen(get_headlines_url) as url:\n get_headlines_data = url.read()\n get_headlines_response = json.loads(get_headlines_data)\n if get_headlines_response['articles']:\n headlines_result_list=get_headlines_response['articles']\n for headline in headlines_result_list:\n headlines_results.append(headline)\n return headlines_results", "def all_headlines_from(url):\n pass", "def get_headlines_with_keyword(self, kw):\r\n\t\tkey_head = self.keyword_headlines()\r\n\r\n\t\theadlines = set()\r\n\r\n\t\tfor headlinekw in key_head[kw]:\r\n\t\t\tcontent = headlinekw.headlineid.content\r\n\t\t\theadlines.add(content)\r\n\r\n\t\treturn list(headlines)", "def fetch_headlines(self, retry=False):\n top_headlines_res = None\n try:\n top_headlines_res = self.news_api.get_top_headlines(\n country='in', page_size=100)\n except newsapi.newsapi_exception.NewsAPIException as err:\n print('NewsAPI Exception==', err)\n if not retry:\n print('Retrying with another key...')\n self.api_key = os.getenv('NEWS_API_KEY_BACKUP')\n self.configure_news_api()\n top_headlines_res = self.fetch_headlines(retry=True)\n else:\n return None\n except Exception as err:\n print('Exception occurred==', err)\n return None\n headlines = {}\n if top_headlines_res and top_headlines_res['status'] == 'ok':\n headlines = top_headlines_res\n else:\n headlines = None\n return headlines", "def topheadlines():\n newsSource = click.prompt(\"Please enter your choice from listsources\")\n \n main_url = \"https://newsapi.org/v2/top-headlines?apiKey=f45fa2c71932483f832f0cc745af0325&sources=\"+newsSource\n\n\t# fetching data in json format \n open_headline = requests.get(main_url).json() \n\n\t# getting all headlines in a string articles \n headline = open_headline[\"articles\"] \n\n\t# empty list which will \n\t# contain all trending newssources \n output = [] \n\t\n for h in headline: \n click.echo('\\n')\n click.secho(click.style('TITLE: ' + h['title'], fg='red'))\n click.secho(click.wrap_text(h['description']))\n click.secho(click.style('DOMAIN: ' + h['url'], fg='blue'))\n \n \t\n for i in output[:11]:\n print(i)", "def get_headlines():\n country = request.args.get('country', type=str)\n if country is not None:\n data = te.getNews(country=country).dropna()\n return jsonify(data.to_dict(orient='records'))\n data = te.getNews()\n return jsonify(te.getNews().dropna().to_dict(orient='records'))", "def get_headlines(outlet):\n if outlet == \"BBC\":\n parser = news_parser.BBC(\"https://www.bbc.co.uk\")\n elif outlet == \"DailyMail\":\n parser = news_parser.DailyMail(\"https://www.dailymail.co.uk\")\n elif outlet == \"Guardian\":\n parser = news_parser.Guardian(\"https://www.theguardian.com\")\n elif outlet == \"Metro\":\n parser = news_parser.Metro(\"https://www.metro.co.uk\")\n elif outlet == \"Mirror\":\n parser = news_parser.Mirror(\"https://www.mirror.co.uk/news/\")\n elif outlet == \"Reuters\":\n parser = news_parser.Reuters(\"https://uk.reuters.com\")\n elif outlet == \"Sun\":\n parser = news_parser.Sun(\"https://www.thesun.co.uk\")\n elif outlet == \"Independent\":\n parser = news_parser.Independent(\"https://www.independent.co.uk\")\n else:\n parser = news_parser.BBC(\"https://www.bbc.co.uk/news\")\n \n index = outlets.index(outlet)\n url_list = []\n while len(url_list) < 50:\n opts = {\n 'language': ['en'],\n 'source_id': [ids[index]],\n 'published_at_start':'NOW-1DAY',\n 'published_at_end':'NOW',\n 'sort_by': 'hotness',\n 'sort_direction': 'desc',\n 'cursor': '*',\n 'per_page': 100\n }\n\n try:\n api_response = api_instance.list_stories(**opts)\n for story in api_response.stories:\n url = story.links.permalink\n if url:\n url_list.append(url)\n except ApiException as e:\n print(\"Exception when calling DefaultApi->list_stories: %s\\n\" %e)\n \n opts['cursor'] = api_response.next_page_cursor\n \n url_list = url_list[:50]\n \n articles_list = []\n for url in url_list:\n raw_article = parser.get_article(url)\n if raw_article is not None:\n articles_list.append(raw_article)\n\n articles = []\n for article in articles_list:\n parsed_article = parser.parse(article)\n if parsed_article is not None:\n articles.append(parsed_article)\n \n if len(articles) > 30:\n articles = articles[:30]\n\n return articles", "def get_headline_data(website_url, source):\n\tpage = requests.get(website_url)\n\tpage.raise_for_status()\n\tall_headlines = []\n\tbs_obj = bs4.BeautifulSoup(page.text, 'html.parser')\n\titem_list = bs_obj.select('item')\n\tprintable = set(string.printable)\n\tfor curr_item in item_list:\n\t\titem_title = curr_item.title.string\n\t\tfollowup_link = curr_item.select('link')[0].string\n\t\tdatestamp = curr_item.select('pubdate')[0].string\n\t\titem_title = item_title.replace(\"&apos;\", \"'\")\n\t\tfollowup_link = followup_link.replace(u\"\\u2018\", \"'\").replace(u\"\\u2019\", \"'\")\n\t\titem_title = item_title.encode('utf-8', errors='ignore')\n\t\tnew_headline = data_structures.Headline(item_title, followup_link, source, datestamp)\n\t\tall_headlines.append(new_headline)\n\treturn all_headlines", "def parse_headlines(self):\n headlines = re.findall(r\"^\\.\\.\\.(.*?)\\.\\.\\.[ ]?\\n\\n\", self.unixtext,\n re.M | re.S)\n headlines = [\" \".join(h.replace(\"...\",\n \", \").replace(\"\\n\", \" \").split())\n for h in headlines]\n return headlines", "def reddit_headlines(reddit):\n\n # Set metadata to make request:\n url = \"https://www.reddit.com/r/{}/.json?limit=10\".format(reddit)\n headers = {'User-Agent': '{} Reddit headlines'.format(reddit)}\n\n # Consume Reddit's API to gather info:\n html = requests.get(url, headers=headers)\n\n # If status code is OK:\n if html.status_code == requests.codes.ok:\n # Parse resonse:\n info = json.loads(html.content.decode('utf-8'))\n # pprint(info)\n\n # Get relevant info:\n child = info['data']['children']\n titles = [unidecode(elem['data']['title']) for elem in child]\n titles = \"... \".join([title for title in titles])\n else:\n titles = None\n\n return titles", "def heads(self) -> \"IterableList[Head]\":\n return Head.list_items(self)", "def org_headlines(self, org):\n\n if org in self.organisations:\n return HeadlineData([headline for headline in self.headlines if\n headline.organisation == org])\n\n raise ValueError(\"Organisation '{}' not found.\".format(org))", "def top_headlines():\n source = \"google-news\" # TODO: Add option to choose source\n try:\n r = requests.get(\"https://newsapi.org/v2/top-headlines?sources=\" + source + \"&apiKey=\" + NEWS_API_TOKEN)\n data = r.json()\n # TODO: Find a way to include multiple articles instead of a random one\n article = data['articles'][randint(0, len(data['articles']) - 1)]\n imageurl = article['urlToImage'].replace('\\\\', '')\n embed = discord.Embed(\n title=article['title'],\n description=article['description'],\n url=article['url'],\n image_url=imageurl\n )\n embed.set_image(url=imageurl)\n embed.set_footer(text=\"Powered by NewsAPI! (newsapi.org)\")\n return embed\n except Exception as e:\n print(e)\n return discord.Embed(title=\"Something went wrong\")", "def gather_headlines(urls):\n pass", "def getHeadParts(self):\n return self.headParts", "def return_xy_subset(X, y, headlines_arr, nobs=10, train=True):\n \n X_subset = np.zeros((0, X.shape[1]))\n y_subset = np.zeros((0, y.shape[1]))\n filtered_hlines_arr = headlines_arr\n hlines_to_predict = headlines_arr[:nobs]\n\n row_idx = 0\n for headline in hlines_to_predict: \n len_hline = len(headline)\n X_ob, y_ob = X[row_idx:(row_idx + 1)], y[row_idx:(row_idx + 1)]\n X_subset = np.concatenate([X_subset, X_ob])\n y_subset = np.concatenate([y_subset, y_ob])\n row_idx += len_hline\n\n if not train: \n X = X[row_idx:]\n y = y[row_idx:]\n filtered_hlines_arr = headlines_arr[nobs:]\n\n return X_subset, y_subset, X, y, hlines_to_predict, filtered_hlines_arr", "def column_headlines(self):\n elements = self._selenium.find_elements_by_xpath(\n '//div[@id=\"content\"]/table/thead/tr/th/a')\n return [x.text for x in elements]", "def keyword_headlines(self):\r\n\t\td = {}\r\n\r\n\t\tfor q in self.keyword_queryset:\r\n\t\t\td[q.content] = self.headlinekeyword_queryset.filter(keywordid = q.id)\r\n\r\n\t\treturn d", "def unique_headlines(self):\n\n all_headlines = sorted(self.headlines, key=lambda x: x.datetime, reverse=True)\n unique_headlines = list(dict((headline.headline_string, headline)\n for headline in all_headlines).values())\n\n return HeadlineData(unique_headlines)", "def ActiveHlt2Lines(self) :\n return []", "def test_headlines_predecessors(self):\n headline_str = \"* One\\n** Two\\n*** Three\\n** Two\\n*** Three\\n* One\"\n\n doc = parser.parse(headline_str)\n self.assertEqual(len(doc.children()), 2)\n\n h1_1 = doc.children()[0]\n h1_2 = doc.children()[1]\n\n self.assertEqual(len(h1_1.children), 2)\n self.assertEqual(len(h1_2.children), 0)\n\n h2_1 = h1_1.children[0]\n h2_2 = h1_1.children[1]\n\n self.assertEqual(len(h2_1.children), 1)\n self.assertEqual(len(h2_2.children), 1)", "def store_headlines():\n for outlet in outlets:\n articles = get_headlines(outlet)\n connect_db.store_headlines(articles,outlet)", "def draw_lh_lines(data):\n #hnd = extract_left_hand(data);\n hnd = np.array(data['crop']);\n hand.draw_hand_lines(hnd,data['lhkpss'][data['i']]);\n return hnd;", "def get_headlines_from_one_page(driver,site,URL_exclusions):\r\n headlines = []\r\n links = get_links_from_one_page(driver,site,URL_exclusions)\r\n for i in range(len(links)):\r\n start = time.time()\r\n timeout = 0\r\n while timeout < 120: #Someimtes the page doesn't load. Quit the page after two minutes.\r\n try:\r\n results = driver.find_elements_by_class_name(\"g\") #Pages contained in class=\"g\" elements\r\n button = results[i].find_element_by_tag_name(\"a\") #Links under <a> tag\r\n link = button.get_attribute('href') #URL contained under 'href' \r\n if link.find(site) != -1: #Some \"g\" elements are not search results\r\n find = np.zeros(len(URL_exclusions))\r\n for j in range(len(URL_exclusions)):\r\n find[j] = bool(link.find(URL_exclusions[j]) == -1)\r\n if all(find) == True: #If no exclusion words found in UR\r\n button.click()\r\n sleep_time = np.random.random() * np.random.randint(1,6) #Sleep for random time between 1 and 5s to reduce chance of bot detection.\r\n time.sleep(sleep_time)\r\n headline = get_headline(driver)\r\n if headline != '': #Only interested if we succesfully find headline\r\n headlines.append(headline)\r\n driver.back()\r\n sleep_time = np.random.random() * np.random.randint(1,6)\r\n time.sleep(sleep_time) #Slow down to avoid bot detection\r\n break\r\n except:\r\n end = time.time()\r\n timeout = end - start\r\n if timeout >= 120:\r\n break #If results hasn't loaded after 120 seconds, we need to break the for loop\r\n return headlines", "def extract_head(data):\n tl = data['tls'][data['i']];\n br = data['brs'][data['i']];\n head = extract_area(data,(tl,br));\n return head;" ]
[ "0.6805288", "0.66681826", "0.64414334", "0.63071424", "0.62891537", "0.627671", "0.6207181", "0.61054546", "0.60500246", "0.59685016", "0.59470963", "0.59354955", "0.5918765", "0.59022444", "0.5855261", "0.58342147", "0.5818049", "0.5792158", "0.5789079", "0.5785733", "0.57816744", "0.5730446", "0.5715554", "0.5599706", "0.54849356", "0.5419814", "0.5393296", "0.5389915", "0.53753304", "0.5336641" ]
0.74649847
0
Gets all poll data from websites, just rcp right now
def get_all_poll_data(): rcp_poll_race_dict = get_rcp_poll_data('http://www.realclearpolitics.com/epolls/latest_polls/') # realclearpolotics poll data return rcp_poll_race_dict
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_rcp_poll_data(website_url):\n\tall_races = dict()\n\tpage = requests.get(website_url)\n\tpage.raise_for_status()\n\tbs_obj = bs4.BeautifulSoup(page.text, 'html.parser')\n\ttd_race = bs_obj.find_all(\"td\", \"lp-race\")\n\ttd_poll = bs_obj.find_all(\"td\", \"lp-poll\")\n\ttd_results = bs_obj.find_all(\"td\", \"lp-results\")\n\ttd_spread = bs_obj.find_all(\"td\", \"lp-spread\")\n\ttd_index = 0\n\tfor race_val in td_race:\n\t\tif race_val.string not in all_races:\n\t\t\tnew_race = data_structures.RaceData(race_val.string)\n\t\t\tnew_race.race_poll_str_data.append(td_results[td_index].string)\n\t\t\tnew_race.race_spread_str_data.append(td_spread[td_index].string)\n\t\t\tnew_race.poll_source_str.append(td_poll[td_index].string)\n\t\t\tall_races[race_val.string] = new_race\n\t\telse:\n\t\t\told_race = all_races[race_val.string]\n\t\t\told_race.race_poll_str_data.append(td_results[td_index].string)\n\t\t\told_race.race_spread_str_data.append(td_spread[td_index].string)\n\t\t\told_race.poll_source_str.append(td_poll[td_index].string)\n\t\ttd_index+=1\n\treturn all_races", "def poll(self):\n self.get_peers()\n self.get_trackers()\n self.get_files()", "def fetch_website_list(self):\r\n # Clear list\r\n self.website_list = []\r\n\r\n # Open websites overview\r\n self.browser.open(self.config[\"base_url\"] + \"websites\")\r\n\r\n # Find table and iterate over rows\r\n for table_row in self.browser.get_current_page().select(\"table tr\"):\r\n\r\n # Fetch cells\r\n cells = table_row.findAll('td')\r\n\r\n # Iterate over cells\r\n if(len(cells) > 0):\r\n\r\n # Get website ID\r\n website_id = table_row['data-id']\r\n # Get website name\r\n name = cells[1].text.strip()\r\n # Get website domain name\r\n domain = cells[2].text.strip()\r\n\r\n # Build website object\r\n website = {'id': website_id,\r\n 'name': name, 'domain': domain}\r\n\r\n # Add website object to list\r\n self.website_list.append(website)", "def getSitesData( self ):\n if self.lastDataRetrievalTime - time.time() < 300:\n result = self.__getRPCClient().getSitesData()\n if 'rpcStub' in result:\n del( result[ 'rpcStub' ] )\n if not result[ 'OK' ]:\n return result\n self.sitesData = result[ 'Value' ]\n if self.sitesData:\n self.lastDataRetrievalTime = time.time()\n return S_OK( self.sitesData )", "async def get_contents(self):\n if self._recon < 0:\n raise ValueError('Reconnection time needs to be positive!')\n urls = self._urls\n proxy_list = await self._pool.get_proxies(self._recon + 1)\n \n for count in range(self._recon + 1):\n proxy = proxy_list[count]\n if count > 0: # perform reconnection\n if not self._re_urls:\n print('No need to reconnect.')\n break\n else:\n if count == 1:\n print('Reconnecting...')\n print('\\n----------------------------------------------------------')\n print(ordinal[count].capitalize() + ' reconnection...\\n')\n urls = self._re_urls\n\n result_list = await self._connect(urls, proxy=proxy, which_site=True)\n\n self._re_urls.clear() # empty the reconnect urls list \n for result in result_list:\n url, soup, status, site = result\n if not self._error(url, soup, status, site, True):\n self._result += self._get_plain_text(url, soup, site)\n fail_num = len(self._re_urls)\n if count == self._recon:\n print('Failed to crawl ' + str(fail_num) + (' website.' if fail_num==1 else ' websites.'))\n\n self._result = re.sub(r'\\s+', '', self._result) # trim whitespaces\n self._result = self._rm_duplicate(self._result)", "def get_websites_to_monitor(self):\n websites = []\n\n while True:\n\n website_instance = self.create_website()\n if website_instance:\n websites.append(website_instance)\n self.console_writer.add_dashboard(website_instance.dashboard)\n print(f\"Your website has been added to the monitoring list\")\n\n if not self.user_wants_more(websites):\n break\n\n return websites", "def _get_poll_info(self, poll_id):\n url = 'https://strawpoll.me/api/v2/polls/{}'.format(poll_id)\n for attempt in range(5):\n try:\n r = requests.get(url)\n poll_options = r.json()['options']\n poll_votes = r.json()['votes']\n except ValueError:\n continue\n except TypeError:\n continue\n else:\n return poll_options, poll_votes\n else:\n self._add_to_chat_queue(\n \"Sorry, there was a problem talking to the strawpoll api. Maybe wait a bit and retry your command?\")", "def get_political_handles(list_file=['files/inc_handles.txt', 'files/bjp_handles.txt'], get_online=True):\n ls_fin = []\n for i in range(1, 23):\n url = \"https://www.socialbakers.com/statistics/twitter/profiles/india/society/politics/page-\" + \\\n str(i) + \"/?showMoreList-from=1&do=platformList-renderAjax&json\"\n html = urllib.request.urlopen(url)\n soup = BeautifulSoup(html, 'html.parser')\n intm = soup.find_all('h2')\n for y in intm:\n for x in y.find_all('span'):\n ls_fin.append(x.text.split(\n '(')[-1].replace(')', '').replace('@', ''))\n for file in list_file:\n with open(file) as f:\n for i in f:\n if i:\n ls_fin.append(i.strip())\n logging.info(str(len(ls_fin)) + \" IDs crawled\")\n return (ls_fin)", "def fetch_web_cont(self):\n with open(self.input_file) as input_file:\n data = yaml.load(input_file, yaml.FullLoader)\n url_list = data.get(self.url_access)\n regex_list = data.get(self.regex_access)\n\n print('Fetching data:')\n\n for url in url_list:\n # This restores the same behavior as before.\n # Enabling certificate verification by default for stdlib http clients\n context = ssl._create_unverified_context()\n run_time = datetime.now().strftime(\"Date: %d-%m-%Y Time: %I:%M:%S:%f_%p\")\n start = time.perf_counter()\n web_resp = request.urlopen(url, context=context)\n respData = web_resp.read()\n resp_time = '%0.2f s' % (time.perf_counter() - start)\n\n for regex in regex_list:\n contents = re.findall(regex, str(respData))\n with open(self.output_file, 'a') as file:\n if not contents:\n print(run_time, ' | URL: ', url, '| content not found with this regex: ', regex,\n file=file)\n\n else:\n for content in contents:\n print(run_time, ' | URL: ', url, ' | Response Time: ', resp_time,\n url, ' | Contents: ', content, file=file)\n \n with open(self.output_file, 'a') as file:\n \n print('\\n#################################\\n', file=file)", "def list_websites(self):\r\n\r\n # Fetch websites\r\n self.fetch_website_list()\r\n\r\n # Print website data\r\n for website in self.website_list:\r\n print(\"ID: {0} | Domain: {1} | Name: {2}\".format(\r\n website['id'], website['domain'], website['name']))", "def _get_data_in_api(url: str) -> list:\n\n try:\n resp = requests.request('GET', url, timeout=10)\n resp.raise_for_status\n\n return Froxy._data_filter(resp.text)\n\n except (\n requests.ConnectionError,\n requests.ConnectTimeout,\n requests.HTTPError,\n requests.ReadTimeout\n ) as err:\n sys.exit(err)", "def crawl(self):\n retrievedSubs = []\n reddit = praw.Reddit(\n client_id='QRl_4bwjckcg9A',\n client_secret='dsavqFoOk5NgWEOWtMf9NknwxRIoIw',\n password='P@ssword123',\n user_agent='cluelessv1',\n username='theclueless1009'\n )\n submissions = reddit.subreddit('all').search(self.keyword, sort='relevance', limit=50, time_filter='week')\n\n for sub in submissions:\n self.data = [sub.selftext, sub.upvote_ratio, sub.score,\n sub.title, sub.id, sub.total_awards_received, sub.created_utc]\n self.data = tuple(self.data)\n retrievedSubs.append(self.data)\n\n return retrievedSubs", "def polling_call(self) -> global___Snippet.ClientCall:", "def get_available_polls(game_type_id):\n\n poll_response = requests.get(\n url=f'{settings.GAME_SETUP_URL}/all-polls/{game_type_id}/',\n timeout=5 # in sec\n )\n if poll_response.status_code == 200:\n return poll_response.json()\n return {}", "def get_poll_data(game_type_id, poll_id):\n\n poll_response = requests.get(\n url=f'{settings.GAME_SETUP_URL}/next-poll/{game_type_id}/{poll_id}/',\n timeout=5 # in sec\n )\n if poll_response.status_code == 200:\n return poll_response.json()\n return {}", "def get_data_from_web():\n pass", "def _getall(cliargs=CliArg(), heap=HeapGate()):\n site = 'http://'+cliargs._site \n recomp = re.compile(r'<td class=\\'vg_table_row_[0-1].*?\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}.*?Total.*?Ping:.*?Logging\\spolicy.*?\\n')\n count = 0\n try:\n response = urllib2.urlopen(site)\n data = response.read()\n except:\n print(\" unable to establish network connection.\\\n \\n .....\\\n \\n check network connectivity and site status.\")\n sys.exit(1)\n \"check verbose -v requirement\"\n if cliargs._verbose:\n print(\" . . .\\n parsing...\\n . . .\") \n cliargs.__str__()\n print(' . . .')\n for x in re.findall(recomp, data):\n \"parse each vpn on site and add to heap\"\n count += _parse(x, cliargs, heap)\n \"check if further parsing needed\"\n if heap._countries:\n for x in heap._countries:\n print(x)\n sys.exit(0)\n \"check verbose -v requirement\"\n if cliargs._verbose:\n print(\" found {0} matching VPNs\\n . . .\".format(count))\n heap.__str__()\n _getbest(cliargs, heap)", "def webScraper(self):\n try:\n self.covid_df = pd.read_csv(self.COVID_URL)\n except:\n sys.exit('COVID data is unavailable at source.')\n \n latest_date = self.covid_df['date'].max()\n earliest_date = self.covid_df['date'].min()\n self.covid_df = self.covid_df[self.covid_df['date'] == self.date.strftime('%Y-%m-%d')]\n \n if self.covid_df.empty:\n exit_string = 'Requested date not available. Latest date available is ' + latest_date + ' while earliest is ' + earliest_date\n sys.exit(exit_string)\n else:\n self.covid_df = self.covid_df[self.covid_df['location'] != 'World']\n \n try:\n self.countries_centroids = pd.read_html(self.CENTROIDS_URL, header=0, index_col='country')[0]\n except:\n sys.exit('Central coordinates data for countries unavailable from Google developers.')\n \n try:\n self.geo_data = requests.get(self.GEOJSON_URL).json()\n except:\n sys.exit('GeoJSON data unavailable to draw country polygons.')", "def get_urls():\r\n return []", "def getnewdata():\n try:\n os.remove(cachepath)\n except os.error:\n pass\n tdelta = int(EPGHOURS)*60*60\n now = time.time()\n later = now + tdelta\n # 2020-03-24%2021%3A00%3A00.000%2B0000\n starttime = urllib.parse.quote(datetime.fromtimestamp(now).\n strftime('%Y-%m-%d %H:00:00.000+0000'))\n # 2020-03-25%2005%3A00%3A00.000%2B0000\n stoptime = urllib.parse.quote(datetime.fromtimestamp(later).\n strftime('%Y-%m-%d %H:00:00.000+0000'))\n url = \"http://api.pluto.tv/v2/channels?start=\" + starttime + \"&stop=\" + stoptime\n\n if debugmode:\n logging.debug(url)\n\n logging.debug(\"Using api.pluto.tv, writing %s.\", CACHEFILE)\n\n try:\n wget.download(url, out=cachepath)\n except IOError:\n logging.error(\"There was an issue downloading EPG data. Exiting.\")\n sys.exit()", "def get_all_crawlers(self):\n try:\n conn = psycopg2.connect(\"dbname='{0}'\".format(DATABASE))\n cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor)\n cur.execute(\"SELECT * FROM host WHERE type = 'Crawler';\")\n results = cur.fetchall()\n cur.close()\n return results\n except Exception as e:\n print(e)", "async def poll(self) -> List[Message]:\n if not self._session:\n await self._create_session()\n \n res = await self._session.get(self._network.SERVER_ADDR + '/api/poll')\n obj = await res.json()\n self._network.connected_robots = obj['robots']\n ret = []\n for m in obj['messages']:\n ret.append(Message.from_dict(m))\n return ret", "def main():\n\n print(\"Retreiving BBC playlists for dates between {} and {}\".\n format(start_date.strftime(\"%Y-%m-%d\"), end_date.strftime(\"%Y-%m-%d\")))\n\n # Get daily schedule URLs within date range\n radio6_schedule_list = helpers.bbc_daily_schedule_urls(bbc_radio6_url, helpers.get_date_list(start_date, end_date))\n\n # Get all show URLS\n all_program_urls = []\n for url in radio6_schedule_list:\n all_program_urls += helpers.bbc_program_urls(url)\n\n # Get all track playlists from program URLs\n track_lists = []\n for url in all_program_urls:\n program_playlist = helpers.get_playlist(url)\n track_lists.append(program_playlist)\n\n print(track_lists)\n return track_lists", "def polls_list(request):\n\n polls = Poll.objects.all()[:MAX_OBJECTS]\n data = {\n 'result': list(polls.values('question', 'created_by__username', 'pub_date'))\n }\n return JsonResponse(data)", "async def _refresh(context):\n url = \"https://wotd.transparent.com/rss/pt-widget.xml\"\n while True:\n try:\n transport = httpx.AsyncHTTPTransport(retries=3)\n async with httpx.AsyncClient(transport=transport, timeout=10) as client:\n response = await client.get(url)\n response.raise_for_status()\n data = _parse(response.text)\n await context.post_event(\"refresh\", data)\n context.vote_connected()\n except httpx.TransportError as ex:\n # https://www.python-httpx.org/exceptions/\n context.vote_disconnected(ex)\n _logger.exception(\"Network error getting word-of-the-day data.\")\n except Exception: # pylint: disable=broad-except\n _logger.exception(\"Error getting word-of-the-day data.\")\n\n await sleep(REFRESH_INTERVAL.total_seconds())", "def fetch_all_lta(url):\n results = []\n while True:\n new_results = requests.get(\n url,\n headers = headers,\n params = {'$skip': len(results)}\n ).json()['value']\n if new_results == []:\n break\n else:\n results += new_results\n return results", "def run(self) -> None:\n self.urls_list = self._create_api_ulr_list()\n self.results = self._sort_results(\n AsyncGetAPI(\n self.urls_list, self.threads, max_requests=self.max_requests\n ).results\n )", "def get_results():\n # store info in a dictionary {name -> shortname}\n res = {}\n session = requests.Session()\n handle_url('http://www.gocomics.com/features', session, res)\n handle_url('http://www.gocomics.com/explore/editorial_list', session, res)\n handle_url('http://www.gocomics.com/explore/sherpa_list', session, res)\n save_result(res, json_file)", "def start_requests(self):\n # This predefined list of URLs is chosen to include all types of\n # inquiries possible in the Austrian parliament in order to provide a\n # suitable testing surface for new functions.\n # urls = [\"https://www.parlament.gv.at/PAKT/VHG/XXV/JPR/JPR_00019/index.shtml\", \"https://www.parlament.gv.at/PAKT/VHG/XXV/JPR/JPR_00016/index.shtml\", \"https://www.parlament.gv.at/PAKT/VHG/XXV/J/J_06954/index.shtml\", \"https://www.parlament.gv.at/PAKT/VHG/XXV/M/M_00178/index.shtml\", \"https://www.parlament.gv.at/PAKT/VHG/XXV/JEU/JEU_00003/index.shtml\", \"https://www.parlament.gv.at/PAKT/VHG/XXV/J/J_06758/index.shtml\", \"https://www.parlament.gv.at/PAKT/VHG/BR/J-BR/J-BR_03089/index.shtml\",\n # \"https://www.parlament.gv.at/PAKT/VHG/BR/J-BR/J-BR_03091/index.shtml\", \"http://www.parlament.gv.at/PAKT/VHG/BR/J-BR/J-BR_01155/index.shtml\", \"http://www.parlament.gv.at/PAKT/VHG/XX/J/J_06110/index.shtml\", \"http://www.parlament.gv.at/PAKT/VHG/XX/J/J_06651/index.shtml\", \"http://www.parlament.gv.at/PAKT/VHG/XX/J/J_04024/index.shtml\", \"http://www.parlament.gv.at/PAKT/VHG/XX/J/J_04025/index.shtml\", \"https://www.parlament.gv.at/PAKT/VHG/XX/M/M_00178/index.shtml\"]\n urls = [] if not self.url_override else [self.url_override]\n\n if self.LLP and not self.url_override:\n for i in self.LLP:\n for nrbr in ['NR', 'BR']:\n roman_numeral = roman.toRoman(i)\n options = self.URLOPTIONS.copy()\n options['GP'] = roman_numeral\n options['NRBR'] = nrbr\n url_options = urlencode(options)\n url_llp = \"{}?{}\".format(self.BASE_URL, url_options)\n rss = feedparser.parse(url_llp)\n\n self.logger.info(\"GP {}: {} inquiries from {}\".format(\n roman_numeral, len(rss['entries']), nrbr)\n )\n urls = urls + [entry['link'] for entry in rss['entries']]\n self.TOTAL_COUNTER = len(urls)\n for url in urls:\n yield self.make_requests_from_url(url)", "def get_requests(url, user, passwd):\n \n #get\n r = requests.get(url, auth=HTTPBasicAuth(user, passwd))\n \n #if timout\n if r.status_code == 403:\n print(\"LIMIT EXCEEDED\")\n print(\"WAIT AN HOUR\")\n i=1\n while r.status_code != 200:\n time.sleep(60)\n r = requests.get(url, auth=HTTPBasicAuth(user, passwd))\n print(\"{} MINUTES ELAPSED\".format(i))\n i+=1\n elif r.status_code != 200:\n print(r.status_code)\n return []\n #return data\n data = r.json()\n return data" ]
[ "0.64626014", "0.6146017", "0.607786", "0.60068434", "0.59178555", "0.5915178", "0.5807954", "0.5772672", "0.5762507", "0.5743239", "0.572163", "0.5704955", "0.5704645", "0.5699589", "0.5688857", "0.56837356", "0.56790507", "0.567832", "0.56728864", "0.5632242", "0.5624435", "0.5611755", "0.55942214", "0.55846864", "0.5581716", "0.5580783", "0.55726135", "0.5566662", "0.5561169", "0.5560252" ]
0.7451158
0
returns string s where all spelled out numbers between 0 and 99 are converted to numbers
def spelledout_numbers_to_numbers(self, s): numbers_1to9 = 'one two three four five six seven eight nine'.split() mappings_1to9 = {t[0]: str(t[1]) for t in zip(numbers_1to9, range(1,10))} mappings_10to19 = {t[0]: str(t[1]) for t in zip("""ten eleven twelve thirteen fourteen fifteen sixteen seventeen eighteen nineteen""".split(), range(10,20))} numbers_20to90 = 'twenty thirty forty fifty sixty seventy eighty ninety'.split() mappings_20to90 = {t[0]: str(t[1]) for t in zip(numbers_20to90, range(20,100,10))} # produce numbers like twenty one, fifty seven, etc. numbers_21to99 = [' '.join([s,p]) for s in numbers_20to90 for p in numbers_1to9] """ create an ordered dictionary mapping spelled numbers to numbers in digits; note that the order is important because we want to search for spelled numbers starting from the compound ones like twenty two, then try to find the rest """ od = OrderedDict({t[0]:t[1] for t in zip(numbers_21to99, # create a list [21,22,..,29,31,..,39,41,..,99] [_ for _ in chain.from_iterable([[str(_) for _ in range(int(d)*10 + 1,int(d+1)*10)] for d in range(2,10)])])}) od.update(mappings_20to90) od.update(mappings_10to19) od.update(mappings_1to9) for w_ in od: s = re.sub(r'\b' + w_ + r'\b', od[w_], s) return s
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def spelled_num_to_digits(spelled_num):\n words = re.split(r\",?\\s+|-\", spelled_num.lower())\n major = 0\n units = 0\n for w in words:\n x = SMALL.get(w, None)\n if x is not None:\n units += x\n elif w == \"hundred\":\n units *= 100\n elif w == \"and\":\n continue\n else:\n x = MAGNITUDE.get(w, None)\n if x is not None:\n major += units * x\n units = 0\n else:\n raise NumberException(\"Unknown number: %s\" % w)\n return major + units", "def transform(s):\r\n return 'digit ' + str(s)", "def replace_spelled_numbers(sentence):\n def try_spelled_num_to_digits(text):\n try:\n return spelled_num_to_digits(text)\n except NumberError:\n return text\n return SPELLED_NUMBER_RE.sub(\n lambda m: str(try_spelled_num_to_digits(m.group())), sentence)", "def transform(s):\n return 'digit ' + str(s)", "def _naturalize_numbers(self, string):\n\n def naturalize_int_match(match):\n return \"%08d\" % (int(match.group(0)),)\n\n string = re.sub(r\"\\d+\", naturalize_int_match, string)\n\n return string", "def clean_numbers(text):\n return regex.sub(\"\\d+\", ' NUM', text)", "def hundreds_conversion(positive_int):\n positive_int = str(positive_int)\n if int(positive_int[-3]) < 4:\n return 'C' * int(positive_int[-3])\n if int(positive_int[-3]) == 4:\n return 'CD'\n if int(positive_int[-3]) == 5:\n return 'D'\n if int(positive_int[-3]) == 6:\n return 'DC'\n if int(positive_int[-3]) == 7:\n return 'DCC'\n if int(positive_int[-3]) == 8:\n return 'DCCC'\n if int(positive_int[-3]) == 9:\n return 'CM'", "def convert_numerals(input_str):\n # credit to: http://code.activestate.com/recipes/81611-roman-numerals/\n copy = input_str[:]\n copy = copy.split(\" \")\n\n nums = ['m', 'd', 'c', 'l', 'x', 'v', 'i']\n ints = [1000, 500, 100, 50, 10, 5, 1]\n places = []\n\n for i in range(len(copy)):\n is_valid = True\n\n if \".\" in copy[i]:\n copy[i] = copy[i].replace(\".\", \"\")\n else:\n # . must be appended to end of string to signify it is a roman\n # numeral\n is_valid = False\n\n if \"xix\" in copy[i] or \"xviii\" in copy[i]:\n is_valid = True\n\n for c in copy[i].lower():\n if c not in nums:\n # return original\n is_valid = False\n\n if is_valid is False:\n continue\n\n for char_index in range(len(copy[i])):\n c = copy[i][char_index].lower()\n value = ints[nums.index(c)]\n # If the next place holds a larger number, this value is negative.\n try:\n nextvalue = ints[nums.index(copy[i][char_index + 1].lower())]\n if nextvalue > value:\n value *= -1\n except IndexError:\n # there is no next place.\n pass\n places.append(value)\n\n out = 0\n\n for n in places:\n out += n\n\n copy[i] = str(out)\n\n return \" \".join(copy)", "def zh_num2digit(string):\n for match in zh_nums_iter(string):\n num_str = match.group(0)\n digit_num = parse_zh_num(num_str)\n if digit_num is None:\n continue\n string = string.replace(num_str, str(digit_num), 1)\n return string", "def fixNumber(sval):\n\n r, val = VALID_RE.match(sval.strip()).groups()\n parts = VALPARTS_RE.findall(val)\n dpart = parts.pop(-1)\n if parts:\n return (r or \"\") + \"\".join(parts) + \".\" + dpart\n return (r or \"\") + dpart", "def normalize(ccNumString):\n allChars=string.maketrans(\"\", \"\")\n badchars=string.translate(allChars, allChars, string.digits)\n return string.translate(ccNumString, allChars, badchars)", "def split_num(s):\n i = 0\n while i < len(s):\n if s[i] < '0' or s[i] > '9':\n break\n i += 1\n if s[i:]:\n return (int(s[:i]), s[i:], )\n return (int(s[:i]), )", "def string_to_int(s):\n return functools.reduce(lambda running_sum, c: running_sum * 10 + string.digits.index(c),\n s[s[0] == '-':], 0) * (-1 if s[0] == '' else 1)", "def zero_digits(s):\n return re.sub('\\d', '0', s)", "def to_number_wrap(s: str) -> str:\n return f\"to_number({s})\"", "def _fix_surprising_number(val, s):\n if (\n isinstance(val, (int, float)) and \"!!\" not in s\n and _contains_non_numeric_chars(s)\n ):\n return s\n return val", "def to_10(s):\n s = re.sub(r'\\w', '1', s)\n s = re.sub(r'\\s', '0', s)\n return s", "def extract_numbers_safe(cls, s, decimals=False):\n if decimals:\n tmp = ''.join([i for i in cls.escape(s) if ((i >= '0') and (i <= '9') or i == '.')])\n\n parts = tmp.split('.')\n\n try:\n output = '{a}.{b}'.format(a=parts[0], b=parts[1])\n except IndexError:\n output = parts[0]\n\n else:\n output = ''.join([i for i in cls.escape(s) if (i >= '0') and (i <= '9')])\n\n try:\n if s[0] == '-':\n output = '-{s}'.format(s=output)\n except:\n pass\n\n return output", "def num(s, filt=float):\n if not s:\n return \"\"\n try:\n return filt(s)\n except ValueError:\n return \"\"", "def transforme(n):\n if n<10 :\n return '0'+str(n)\n else :\n return str(n)", "def find_number(self, string):\n #string = string.encode('ascii', 'ignore')\n #return int(filter(str.isdigit, string))\n s = (re.findall('\\d+', string))\n return int(''.join(s))", "def spell_number(num):\n tens, units = num / 10, num % 10\n tens_str = NUMBERS_10[tens]\n units_str = NUMBERS_1[units]\n if tens == 1:\n return NUMBERS_TEEN[units]\n elif tens:\n if units:\n return \"{t} {u}\".format(t=tens_str, u=units_str)\n return \"{t}\".format(t=tens_str)\n else:\n return units_str", "def letter_to_num(self, string, dict_):\n #dict_= {'A': '0', 'C': '1', 'D': '2', 'E': '3', 'F': '4', 'G': '5', 'H': '6', 'I': '7', 'K': '8', 'L': '9', 'M': '10', 'N': '11', 'P': '12', 'Q': '13', 'R': '14', 'S': '15', 'T': '16', 'V': '17', 'W': '18', 'Y': '19'}\n patt = re.compile('[' + ''.join(dict_.keys()) + ']')\n num_string = patt.sub(lambda m: dict_[m.group(0)] + ' ', string)\n #print(num_string)\n #print(type(num_string))\n num = [int(i) for i in num_string.split()]\n return num", "def tweet_clean_numbers(word):\n if not re.search(r'[0-9]+', word):\n return word\n if len(word)==4 and re.search(r'[0-9]{4}', word) and 1900 < int(word) < 2019:\n return word\n word = re.sub(r'^([0-9]|[\\+\\-%/\\*\\.:])+[0-9%/\\+\\*\\.x:]*$', '<number>', word)\n return word", "def letter_to_num(string, dict_):\n patt = re.compile('[' + ''.join(dict_.keys()) + ']')\n num_string = patt.sub(lambda m: dict_[m.group(0)] + ' ', string)\n num = [int(i) for i in num_string.split()]\n return num", "def broken(inp):\n return inp.translate(str.maketrans(\"01\", \"10\"))", "def integers_only(text) -> str:\n return ''.join(x for x in text if x.isdigit())", "def to_digit(s: str) -> Union[float, str, int]:\n out = s.strip()\n f_twin = r'\\d+[,.]\\d{2,} {0,}- {0,}\\d+[.,]\\d{2,}'\n f_rank = r'\\d/10'\n f_score = r'[ ]{0,}\\d+[ ]{0,}'\n f_date = r'\\d\\d\\.\\d\\d\\.\\d\\d\\d\\d'\n f_main = r'(-?\\d*\\,?\\d+\\.?\\d*)[%BM]?'\n\n if isinstance(s, str) and re.findall(f_date, s) == [] and len(s) < 50 and s != '-':\n try: # begin from big one, because bigs consist small re\n\n if re.search(f_main, s) is not None:\n res = re.search(f_main, s.strip()).groups()[0]\n if res == '-':\n return '-'\n k = 1\n mul = 1\n after_point = res.split('.')\n if len(after_point) == 2:\n k = 10 ** len(after_point[1].replace(',', ''))\n\n mul = 1000000000 if s.find('B') > 0 else mul # found Billions\n mul = 1000000 if s.find('M') > 0 else mul # found Millions\n mul = 0.01 if s.find('%') > 0 else mul # found Percent format\n mul = mul * -1 if s.find(')') > 0 else mul # financial format to show minus : -192.34 = (192.34)\n\n return round(float(res.replace('.', '').replace(',', '')), 2) * mul / k if k > 1 else \\\n int(res.replace('.', '').replace(',', '')) * mul\n\n if len(re.findall(f_twin, s)) > 0: # format range xxx.xx - xxx.xx\n return float(re.findall(f_twin, s)[0]\n .replace(' ', '')\n .split('-')[0]\n .replace(',', '')\n .replace('.', '')) / 100\n\n if len(re.findall(f_rank, s)) > 0: # format score like 9/10 -> 9\n return int(re.findall(f_rank, s)[0].split('/')[0])\n\n if len(re.findall(f_score, s)) > 0: # format one digit score like ' 5 ' -> 5\n return int(re.findall(f_score, s)[0].replace(' ', ''))\n\n except Exception as e:\n\n logging.error(f\"Error in to_digit(). Input {s}, Out \")\n return out", "def normalise_num(version_num, normal_len):\n version_num = str(version_num).replace(\".\", \"\")\n if len(version_num) < normal_len:\n for i in range(len(version_num), normal_len):\n version_num = version_num + \"0\"\n return int(version_num) if version_num.isdigit() else 0", "def convert_to_numerals(number):\n assert number < 4000\n expression = factorize(int(number), ROMAN_NUMERALS)\n result = list(numeral(f) * c for c, f in normalize(expression))\n return \"\".join(result)" ]
[ "0.6682553", "0.6589257", "0.65729326", "0.65535784", "0.639042", "0.63530743", "0.63379157", "0.63367224", "0.6257592", "0.6254087", "0.6237117", "0.61532366", "0.6119005", "0.6051259", "0.6035944", "0.6022159", "0.601946", "0.59924936", "0.596444", "0.5929257", "0.5909929", "0.58982736", "0.5896288", "0.58921325", "0.5875429", "0.5864312", "0.585813", "0.5856352", "0.58390695", "0.5824962" ]
0.73115116
0
unfold abbreviations in string st
def deabbreviate(self, st): abbrs = {'gws': 'greater western sydney giants', 'gwsg': 'greater western sydney giants', 'afl': 'australian football league', 'nrc': 'national rugby championship', 'nrl': 'national rugby league', 'syd': 'sydney', 'mel': 'melbourne', 'melb': 'melbourne', 'bris': 'brisbane', 'brisb': 'brisbane', 'gc': 'gold coast', 'adel': 'adelaide', 'canb': 'canberra', 'mt': 'mount', 'utd': 'united', 'cty': 'city', 'football club': 'fc', 'snr': 'senior', 'jr': 'junion', 'nsw': 'new south wales' , 'vic': 'victoria', 'tas' : 'tasmania', 'sa': 'south australia', 'wa': 'western australia', 'act': 'australian capital territory', 'nt': 'northern territory', 'qld': 'queensland', 'champs': 'championships', 'champ': 'championship', 'soc': 'society', 'ent': 'entertainment', 'intl': 'international', 'int': 'international', 'aust': 'australian'} # first replace full state names by abbreviations; for ab in abbrs: st = re.sub(r'\b' + ab + r'\b', abbrs[ab], st) return st
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def convert_abbrev_in_text(text):\r\n tokens = word_tokenize(text)\r\n tokens = [convert_abbrev(word) for word in tokens]\r\n text = ' '.join(tokens)\r\n return text", "def convert_abbrev(word):\r\n return abbreviations[word.lower()] if word.lower() in abbreviations.keys() else word", "def combine_state_names_and_abbreviations():\n return sorted(us_state_abbrev.values())[:10] + sorted(states)[-10:]", "def filter_words(st):\n\n filtered = \" \".join(st.capitalize().split())\n return filtered", "def expand_abbrevs(name):\n key = name.upper()\n for abbrev, word in ABBREVS.iteritems():\n key = re.sub(abbrev, word, key)\n \n #Remove (.*) from the street name\n key = re.sub(r'\\(.*?(:?\\)|$)', '', key)\n \n #Unify names\n key = NUMBER_IN_NAMES_REGEX.sub(lambda i: i.group(1) + \" \", key)\n key = re.sub(u\"Ё\", u\"Е\", key)\n key = re.sub(u\"[\\\"'«»№]\", u\" \", key)\n\n # remove \"им\" prefix\n key = re.sub(ur'[^\\s]ИМ[\\.\\s]+', u' ', key)\n\n #Change name parts order\n words = key.split(r\" \")\n words.sort()\n key = \" \".join(words)\n\n key = re.sub(u\"\\s+\", u\" \", key).strip()\n\n logging.debug(\"Street name %s was converted to %s\" % (name, key))\n \n return key", "def abbreviate(x: str) -> str:\n i = 0\n abbreviation: str = \"\"\n while i < len(x):\n if x[i].isupper():\n abbreviation += x[i]\n i += 1\n return abbreviation", "def combine_state_names_and_abbreviations():\n lst=[]\n for k,v in us_state_abbrev.items():\n lst.append(v)\n lst = sorted(lst[:10])\n state = sorted(states)\n print(lst+state[-10:])\n return", "def normalize_acronym(self, acronym: str):\n return self.tknzr.tokenize(acronym, to_lower=False)", "def unscorize(s):\n return s.replace(\" \", \"_\")", "def normalize(s):\r\n def remove_articles(text):\r\n return re.sub(r'\\b(a|an|the)\\b', ' ', text)\r\n\r\n def white_space_fix(text):\r\n return ' '.join(text.split())\r\n\r\n def remove_punc(text):\r\n exclude = set(string.punctuation)\r\n return ''.join(ch for ch in text if ch not in exclude)\r\n\r\n def lower(text):\r\n return text.lower()\r\n\r\n return white_space_fix(remove_articles(remove_punc(lower(s))))", "def normalize(s):\r\n def remove_articles(text):\r\n return re.sub(r'\\b(a|an|the)\\b', ' ', text)\r\n\r\n def white_space_fix(text):\r\n return ' '.join(text.split())\r\n\r\n def remove_punc(text):\r\n exclude = set(string.punctuation)\r\n return ''.join(ch for ch in text if ch not in exclude)\r\n\r\n def lower(text):\r\n return text.lower()\r\n\r\n return white_space_fix(remove_articles(remove_punc(lower(s))))", "def abbreviate_title(s):\n if u'Group ' in s:\n return s.replace(u'Group ', u'')\n else:\n parts = s.split(None, 1)\n if len(parts) < 2:\n return s\n genus, rest = s.split(None, 1)\n return u'%s. %s' % (genus[0], rest)", "def normalize(s):\n def remove_articles(text):\n return re.sub(r'\\b(a|an|the)\\b', ' ', text)\n\n def white_space_fix(text):\n return ' '.join(text.split())\n\n# def remove_punc(text):\n# exclude = set(string.punctuation)\n# return ''.join(ch for ch in text if ch not in exclude)\n\n def lower(text):\n return text.lower()\n\n return white_space_fix(remove_articles(lower(s)))", "def infer_spaces(s):\n global unfolded\n if s in unfolded:\n return unfolded[s]\n\n # Find the best match for the i first characters, assuming cost has\n # been built for the i-1 first characters.\n # Returns a pair (match_cost, match_length).\n def best_match(i):\n candidates = enumerate(reversed(cost[max(0, i-maxword):i]))\n return min((c + wordcost.get(s[i-k-1:i], 9e999), k+1) for k,c in candidates)\n\n # Build the cost array.\n cost = [0]\n for i in range(1,len(s)+1):\n c,k = best_match(i)\n cost.append(c)\n\n # Backtrack to recover the minimal-cost string.\n out = []\n i = len(s)\n while i>0:\n c,k = best_match(i)\n assert c == cost[i]\n out.append(s[i-k:i])\n i -= k\n \n unfolded[s] = ' '.join(reversed(out))\n return ' '.join(reversed(out))", "def abbr_2_st(state_series, abbr_2_st=True):\n us_state_abbrev = {\n 'Alabama': 'AL',\n 'Alaska': 'AK',\n 'American Samoa': 'AS',\n 'Arizona': 'AZ',\n 'Arkansas': 'AR',\n 'California': 'CA',\n 'Colorado': 'CO',\n 'Connecticut': 'CT',\n 'Delaware': 'DE',\n 'District of Columbia': 'DC',\n 'Florida': 'FL',\n 'Georgia': 'GA',\n 'Guam': 'GU',\n 'Hawaii': 'HI',\n 'Idaho': 'ID',\n 'Illinois': 'IL',\n 'Indiana': 'IN',\n 'Iowa': 'IA',\n 'Kansas': 'KS',\n 'Kentucky': 'KY',\n 'Louisiana': 'LA',\n 'Maine': 'ME',\n 'Maryland': 'MD',\n 'Massachusetts': 'MA',\n 'Michigan': 'MI',\n 'Minnesota': 'MN',\n 'Mississippi': 'MS',\n 'Missouri': 'MO',\n 'Montana': 'MT',\n 'Nebraska': 'NE',\n 'Nevada': 'NV',\n 'New Hampshire': 'NH',\n 'New Jersey': 'NJ',\n 'New Mexico': 'NM',\n 'New York': 'NY',\n 'North Carolina': 'NC',\n 'North Dakota': 'ND',\n 'Northern Mariana Islands':'MP',\n 'Ohio': 'OH',\n 'Oklahoma': 'OK',\n 'Oregon': 'OR',\n 'Pennsylvania': 'PA',\n 'Puerto Rico': 'PR',\n 'Rhode Island': 'RI',\n 'South Carolina': 'SC',\n 'South Dakota': 'SD',\n 'Tennessee': 'TN',\n 'Texas': 'TX',\n 'Utah': 'UT',\n 'Vermont': 'VT',\n 'Virgin Islands': 'VI',\n 'Virginia': 'VA',\n 'Washington': 'WA',\n 'West Virginia': 'WV',\n 'Wisconsin': 'WI',\n 'Wyoming': 'WY'\n}\n if abbr_2_st == True:\n inv_map = {v: k for k, v in us_state_abbrev.items()}\n full_names = []\n for abbv in state_series:\n full_names.append(inv_map[abbv])\n return full_names\n else:\n # Return Abbreviation\n abbvs = []\n for full_name in state_series:\n abbvs.append(us_state_abbrev[full_name])\n return abbvs", "def normalize(address):\n replacement = re.sub('\\W+', SEPARATOR, address.lower())\n\n processed = []\n for p in replacement.split(SEPARATOR):\n if not p:\n continue\n\n if p in ABBRS:\n processed.append(ABBRS[p])\n else:\n processed.append(p)\n\n processed.sort()\n\n normalized = SEPARATOR.join(processed)\n return normalized", "def state_to_abbreviation(state: str, df: pd.DataFrame) -> str:\n\n return df.loc[df['State Name'] == state.title(), 'State Abbreviation'].iloc[0]", "def descorize(s):\n return s.replace(\"_\", \" \")", "def _normalize_answer(s):\n\n def remove_articles(text):\n return re.sub(r'\\b(a|an|the)\\b', ' ', text)\n\n def white_space_fix(text):\n return ' '.join(text.split())\n\n def remove_punc(text):\n exclude = set(string.punctuation)\n return ''.join(ch for ch in text if ch not in exclude)\n\n def lower(text):\n return text.lower()\n\n return white_space_fix(remove_articles(remove_punc(lower(s))))", "def dflagize_subregional(text: str) -> str:\r\n\r\n return standard.dflagize_subregional(text)", "def state_abbreviated():\r\n\r\n cursor.execute('SELECT * FROM american_cities_with_states \\\r\n order by RANDOM() limit 1;')\r\n return (cursor.fetchone()[0])[-2:]", "def normalize_answer(s):\n def remove_articles(text):\n regex = re.compile(r'\\b(a|an|the)\\b', re.UNICODE)\n return re.sub(regex, ' ', text)\n def white_space_fix(text):\n return ' '.join(text.split())\n def remove_punc(text):\n exclude = set(string.punctuation)\n return ''.join(ch for ch in text if ch not in exclude)\n def lower(text):\n return text.lower()\n return white_space_fix(remove_articles(remove_punc(lower(s))))", "def _normalize_text(s: str) ->str:\n\n def remove_articles(text: str) ->str:\n return re.sub('\\\\b(a|an|the)\\\\b', ' ', text)\n\n def white_space_fix(text: str) ->str:\n return ' '.join(text.split())\n\n def remove_punc(text: str) ->str:\n exclude = set(string.punctuation)\n return ''.join(ch for ch in text if ch not in exclude)\n\n def lower(text: str) ->str:\n return text.lower()\n return white_space_fix(remove_articles(remove_punc(lower(s))))", "def proper_title_case(s):\n nocaps = [\"the\"] # This needs to be extended.", "def expand_abbreviation(abbr, doc_type = 'html', profile_name = 'plain'):\n\ttree = parse_into_tree(abbr, doc_type)\n\tif tree:\n\t\treturn replace_variables(re.sub('\\|', insertion_point, tree.to_string(profile_name) or ''))\n\t\t\n\treturn ''", "def translate(self,string):\n out = list()\n for l in list(string):\n if l == ' ':\n if out[-1] == \"_interword\": out.pop()\n out.append('_intraword')\n else:\n out.extend(self.xlate(l))\n out.append('_interword')\n if out and out[-1] == '_interword': out.pop() # pop off last interword\n return out", "def normalize(word):\n word = word.lower()\n # removing plural, it facilitates the matching\n if len(word)>0 and word[-1] == 's':\n return word[0:-1]\n return word", "def find_abecedarian_words():\n pass", "def getStateAbbreviations():\n state_abbrev = {\n \"01\": \"AL\",\n \"02\": \"AK\",\n \"04\": \"AZ\",\n \"05\": \"AR\",\n \"06\": \"CA\",\n \"08\": \"CO\",\n \"09\": \"CT\",\n \"10\": \"DE\",\n \"11\": \"DC\",\n \"12\": \"FL\",\n \"13\": \"GA\",\n \"15\": \"HI\",\n \"16\": \"ID\",\n \"17\": \"IL\",\n \"18\": \"IN\",\n \"19\": \"IA\",\n \"20\": \"KS\",\n \"21\": \"KY\",\n \"22\": \"LA\",\n \"23\": \"ME\",\n \"24\": \"MD\",\n \"25\": \"MA\",\n \"26\": \"MI\",\n \"27\": \"MN\",\n \"28\": \"MS\",\n \"29\": \"MO\",\n \"30\": \"MT\",\n \"31\": \"NE\",\n \"32\": \"NV\",\n \"33\": \"NH\",\n \"34\": \"NJ\",\n \"35\": \"NM\",\n \"36\": \"NY\",\n \"37\": \"NC\",\n \"38\": \"ND\",\n \"39\": \"OH\",\n \"40\": \"OK\",\n \"41\": \"OR\",\n \"42\": \"PA\",\n \"44\": \"RI\",\n \"45\": \"SC\",\n \"46\": \"SD\",\n \"47\": \"TN\",\n \"48\": \"TX\",\n \"49\": \"UT\",\n \"50\": \"VT\",\n \"51\": \"VA\",\n \"53\": \"WA\",\n \"54\": \"WV\",\n \"55\": \"WI\",\n \"56\": \"WY\",\n \"72\": \"PR\"\n }\n return state_abbrev", "def normalize_answer(s):\n\n def remove_articles(text):\n return re.sub(r\"\\b(a|an|the)\\b\", \" \", text)\n\n def white_space_fix(text):\n return \" \".join(text.split())\n\n def remove_punc(text):\n exclude = set(string.punctuation)\n return \"\".join(ch for ch in text if ch not in exclude)\n\n def lower(text):\n return text.lower()\n\n return white_space_fix(remove_articles(remove_punc(lower(s))))" ]
[ "0.6166929", "0.61277133", "0.6118352", "0.5967223", "0.5957388", "0.5905005", "0.5876301", "0.5796989", "0.5763699", "0.57412267", "0.57412267", "0.5737245", "0.5723872", "0.5700332", "0.5695759", "0.56211364", "0.5612642", "0.5579643", "0.5558237", "0.5548861", "0.54835266", "0.54823154", "0.54719996", "0.5463241", "0.54604816", "0.54484534", "0.5439673", "0.5433492", "0.54289126", "0.5425856" ]
0.782033
0
Get the geolocation data from the request.
def get_geo_data(request): # Note that geoip2 (from maximind) doesn't work on GAE because there is a # C lib in there apparently. # We can use Appengine's added headers to do that work though thankfully. geo = dict() geo['region'] = request.headers.get("X-AppEngine-Region", "unknown") geo['city'] = request.headers.get("X-AppEngine-City", "unknown") geo['country'] = request.headers.get("X-AppEngine-Country", "unknown") geo['city_lat_long'] = request.headers.get("X-AppEngine-CityLatLong", "unknown") return geo
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def get_geolocation(self, location):\n\n response = self.request(dict(\n method=\"GET\",\n query=dict(location=location),\n ))\n\n return response['data']", "def getLocation(self):\n send_url = 'https://ipinfo.io'\n r = requests.get(send_url)\n resp = json.loads(r.text)\n logging.info(\"GeoLoc: {}\".format(resp))\n return resp", "def getGeo(self):\n command = f'curl -s -m 5 http://ip-api.com/json/' + self.ip\n result = subprocess.run(command.split(), capture_output=True)\n data = result.stdout.decode(\"utf-8\").replace('\\n','')\n try:\n data = json.loads(data)\n except json.decoder.JSONDecodeError:\n # Error from ip-api.com\n data = None\n if data:\n # {\"status\":\"success\",\"country\":\"Yemen\",\"countryCode\":\"YE\",\"region\":\"SA\",\"regionName\":\"Amanat Alasimah\",\"city\":\"Sanaa\",\"zip\":\"\",\"lat\":15.3522,\"lon\":44.2095,\"timezone\":\"Asia/Aden\",\"isp\":\"Public Telecommunication Corporation\",\"org\":\"YemenNet\",\"as\":\"AS30873 Public Telecommunication Corporation\",\"query\":\"134.35.218.63\"}\n self.geodata = data\n else:\n self.geodata = None", "def get_address_coordinates_from_geolocation(mycity_request) -> dict:\n user_address = None\n if mycity_request.device_has_geolocation:\n if mycity_request.geolocation_permission:\n user_address = location_services_utils.convert_mycity_coordinates_to_arcgis(mycity_request)\n return user_address", "def fetchGeoData():\n if request.method ==\"POST\":\n result = {}\n if request.get_json():\n post_requests = request.get_json()\n print(post_requests)\n result = db.getmapdata(post_requests['attr']) \n return result", "def _set_appengine_geolocation(self, request):\n if message.HEADER_CITY in request.headers:\n self._gae_city = request.headers[message.HEADER_CITY]\n if message.HEADER_COUNTRY in request.headers:\n self._gae_country = request.headers[message.HEADER_COUNTRY]\n if message.HEADER_LAT_LONG in request.headers:\n lat_long = request.headers[message.HEADER_LAT_LONG]\n try:\n self._gae_latitude, self._gae_longitude = [\n float(x) for x in lat_long.split(',')\n ]\n except ValueError:\n logging.error('GAE provided bad lat/long %s.', lat_long)", "def location_data(self) -> pulumi.Output[Optional['outputs.LocationDataResponse']]:\n return pulumi.get(self, \"location_data\")", "def location_data(self) -> Optional[pulumi.Input['LocationDataArgs']]:\n return pulumi.get(self, \"location_data\")", "def locate(self):\n if self.location == '':\n return None\n if self.coords is not None:\n return self.coords\n\n loc = urlencode({'address': self.location})\n urldoc = urlopen(User._GMAP_URL.format(query=loc))\n jsObj = json.loads(urldoc.readall().decode('utf-8'))\n if len(jsObj['results']) > 0:\n # discard commercial results\n locTypes = jsObj['results'][0]['address_components'][0]['types']\n if not 'premise' in locTypes and not 'route' in locTypes and not 'establishment' in locTypes and not 'subpremise' in locTypes:\n self.coords = jsObj['results'][0]['geometry']['location']\n return self.coords\n # still here? it's all rubbish\n return None", "def _get_location_details(self, location):\n resp = requests.get(\n self.base_url,\n params = {\n 'address': ''.join(location.split(' ')),\n 'key': GOOGLE_API_KEY,\n }\n )\n return resp.json()", "def post(self):\n data = json.dumps(request.get_json())\n lat = json.loads(data)['lat']\n lon = json.loads(data)['lon']\n response = hereService.getWeatherByLatLong(lat, lon)\n return response", "def get_user_location():\r\n \r\n # API endpoint\r\n url = 'http://ip-api.com/json/'\r\n\r\n # API call\r\n response = requests.get(url)\r\n\r\n # Collect response in json format\r\n data = response.json()\r\n\r\n # Return data gathered\r\n if data['status'] == 'success':\r\n return {\r\n 'success': data['status'] == 'success', # Should exaluate to True\r\n 'city': data['city'],\r\n 'state': data['regionName'],\r\n 'ip_coordinates': str(data['lat']) + ', ' + str(data['lon']),\r\n 'lat': data['lat'],\r\n 'lon': data['lon'],\r\n 'ip_address': data['query']\r\n }\r\n else:\r\n return {\r\n 'success': data['status'] == 'success', # Should exaluate to False\r\n 'ip_address': data['query']\r\n }", "def geolocation(self):\n return self.get_property('geolocation', GeolocationColumn())", "def __get_geocoded_data(self, ip_address):\n location = None\n if ip_address in self.locations:\n location = self.locations[ip_address]\n else:\n location = self.get_location(ip_address)\n self.locations[ip_address] = location\n \n return location", "def get_location(self, ip_address):\n location = None\n url = \"http://dazzlepod.com/ip/{0}.json\".format(ip_address)\n status_code, json_data = self.urlopen(url)\n if status_code == 200 and json_data:\n tmp_location = json.loads(json_data)\n if 'latitude' in tmp_location and 'longitude' in tmp_location:\n location = tmp_location\n return location", "def getting_user_location():\n\n geoplugin_request = requests.get(\"http://www.geoplugin.net/json.gp\")\n\n if geoplugin_request.status_code != 200:\n print(\"It was not possible to obtain your current location. Please, try again later!\")\n exit()\n \n else:\n geo_plugin_response = geoplugin_request.json()\n latitude = geo_plugin_response['geoplugin_latitude']\n longitude = geo_plugin_response['geoplugin_longitude']\n\n user_location_info = tuple([latitude, longitude])\n\n return user_location_info", "def getlocation(location):\n response = requests.get(location)\n return LocationData(size=len(response.content), elapsed=response.elapsed)", "def get(self, request):\n return Response(services.get_gsa_locations(request.query_params, request.META['HTTP_JWT']))", "def get_location(self):\n return self.request({\n \"path\": \"/\" + UUID + \"/location\"\n })", "def geolocation(self):\n if self.latitude and self.longitude:\n return self.longitude, self.latitude", "def get_location(self):\r\n request = self.request_dict()\r\n\r\n if not request:\r\n return None\r\n\r\n location = self.json_request(request)\r\n\r\n if not location:\r\n return None\r\n\r\n if location.has_key(\"access_token\"):\r\n self.access_token = location[\"access_token\"]\r\n\r\n return self.location_from_dict(location)", "def get_location(self):\n # h = b'\\r\\nAT-MSGEO\\r\\r\\n-MSGEO: -3936,3464,-3612,7402d50c\\r\\n\\r\\n'\n # an example of the string returned from the AT-MSGEO used for testing.\n h = self.acquire_response(b'AT-MSGEO')\n if isinstance(h, bytes):\n h = h.decode('utf-8')\n h = h.strip()\n h = h.split(':')\n h = h[1].split(',')\n x = int(h[0])*1000 # Convert coordinates to meters.\n y = int(h[1])*1000\n z = int(h[2])*1000\n else:\n print('Location not available')\n\n # 'geocent' refers to the geo-centered frame that the co-ordinates are returned in\n inProj = Proj(proj='geocent', ellps='WGS84', datum='WGS84')\n\n # 'latlong' is the frame to be converted to\n outProj = Proj(proj='latlong', ellps='WGS84', datum='WGS84')\n\n # Convert X, Y, Z to latitude, longitude and altitude\n long, lat, alt = transform(inProj, outProj, x, y, z, radians=False)\n # l = [str(long), str(lat), str(alt)]\n return long, lat, alt", "def get(self):\n street = self.request.args.get(\"street\", \"\")\n zip = self.request.args.get(\"zip\",\"\")\n city = self.request.args.get(\"city\",\"\")\n country = self.request.args.get(\"country\",\"Germany\")\n\n if street==\"\" or city==\"\" or country==\"\":\n return {'success': False, \n 'msg': self._(\"no full address was given\")\n }\n try:\n lat, lng = self.retrieve_location(street, zip, city, country)\n except LocationNotFound:\n return {'success': False, \n 'msg': self._(\"we couldn't lookup a geo coordinates for this address\")\n }\n return {\n 'success' : True,\n 'lat' : lat,\n 'lng' : lng\n }", "def get_latlong():\r\n info = urllib.request.urlopen(\"https://ipinfo.io\").read()\r\n decoded = json.loads(info)\r\n print(decoded[\"loc\"])\r\n return decoded[\"loc\"]", "def GetLocation():\n IPinfoRequest = requests.get('https://ipinfo.io/')\n IPinfo = IPinfoRequest.json()\n Location = IPinfo['loc'].split(',')\n Latitude = Location[0]\n Longitude = Location[1]\n LocationForOpenweather = \"lat=\"+Latitude+\"&lon=\"+Longitude\n return(LocationForOpenweather)", "def __call__(self, request: HttpRequest) -> HttpResponse:\n ip_address = remote_addr(request)\n request.geo_data = self.geo_data(ip_address)\n response = self.get_response(request)\n if self.add_response_headers(request):\n annotate_response(response, request.geo_data)\n return response", "def get_data(location):\n # This is factored out so we can use a different retrieval method if required.\n # Originally used urllib2, but it had SSL issues on my machine\n response = requests.get(location)\n return response.content", "def get_current_locate(self) -> dict:\r\n geolocate: dict = self.gmaps.geolocate()\r\n return geolocate", "def geocode(self, request):\n latlng = request.query_params.get('latlng')\n if not latlng:\n raise RequiredParameter('latlng')\n try:\n lat = float(latlng.split(',')[0])\n lng = float(latlng.split(',')[1])\n except Exception:\n raise InvalidParameter('latlng', _('Invalid `latlng`'))\n ip = get_real_ip(request)\n location = location_controller.from_location_index(lat, lng, ip)\n return Response(location)", "def get_location_data(address=None):\n params = {\n 'address': address,\n 'sensor': 'false'\n }\n\n # Do the request and get the response data\n req = requests.get(GOOGLE_MAPS_API_URL, params=params)\n res = req.json()\n\n # Use the first result\n result = res['results'][0]\n\n try:\n geodata = dict()\n geodata['Latitude'] = result['geometry']['location']['lat']\n geodata['Longitude'] = result['geometry']['location']['lng']\n return geodata\n except Exception:\n return None" ]
[ "0.7609283", "0.70273775", "0.67268974", "0.6568262", "0.65253556", "0.6492344", "0.6459893", "0.64520943", "0.6426659", "0.6425953", "0.6342649", "0.63417333", "0.63356334", "0.63080126", "0.6297456", "0.62643236", "0.62602955", "0.6233702", "0.6208337", "0.6201374", "0.61947066", "0.6181225", "0.61655384", "0.61513007", "0.6085891", "0.60760355", "0.6062696", "0.6036958", "0.6036135", "0.601779" ]
0.7446573
1
Request Polly speech given text and language.
def polly_request_speech(intext: str, intlanguage: str): session = Session(profile_name="default") polly = session.client("polly") try: response = polly.synthesize_speech(Text=intext,LanguageCode = intlanguage,OutputFormat="mp3",VoiceId="Joanna") print(response) except (BotoCoreError, ClientError) as error: print(error) sys.exit(1) return response
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "async def speaklang(ctx, language, *, message: commands.clean_content):\n await _speak(ctx, language, \"com\", message)", "def generate_audio():\n text, lang = introduction()\n ses = boto3.Session(profile_name=\"default\")\n pol = ses.client(\"polly\")\n res = pol.synthesize_speech(Text=text, LanguageCode=lang, OutputFormat=\"mp3\", VoiceId=VOICE)\n return res", "def text_to_speech(self, text, file, voice_name=None, language=None):\n endpoint = 'CreateSpeech'\n\n data = {\n 'Input': {\n 'Data': text,\n },\n 'OutputFormat': {\n 'Codec': self.codec.upper(),\n },\n 'Parameters': {\n 'Rate': self.rate,\n 'Volume': self.volume,\n 'SentenceBreak': self.sentence_break,\n 'ParagraphBreak': self.paragraph_break,\n },\n 'Voice': {\n 'Name': voice_name or self.voice_name,\n 'Language': language or self.language,\n },\n }\n\n response = self._get_response('post', endpoint, data)\n\n file.write(response.content)", "def voice():\n resp = VoiceResponse()\n\n gather = Gather(num_digits=1, action='/gather')\n gather.say(\n 'For Spanish press 1, for Italian press 2, for German press 3, for French press 4, for Mandarin Chinese '\n 'press 5, for Japanese press 6, to manually enter a language press 9', voice='Alice', language=languages[source][2])\n resp.append(gather)\n\n # If the user doesn't select an option, redirect them into a loop\n resp.redirect('/voice')\n\n return str(resp)", "def sayText(text, voiceLang=\"es\"):\n cmd = f\"say --voice \\\"{languages[voiceLang]}\\\" \\\"{text}\\\"\"\n print(\"running command ->\",cmd)\n bash_command(cmd)", "def get_speech(self, phrase):\n src = os.path.join(constants.CONFIG_PATH, self.voice)\n text = phrase\n\n def preprocess(syllables):\n temp = []\n for syllable in syllables:\n for p in self.punctuation:\n syllable = syllable.replace(p, \"\")\n if syllable.isdigit():\n syllable = atc.num2chinese(syllable)\n new_sounds = lazy_pinyin(syllable, style=pypinyin.TONE3)\n for e in new_sounds:\n temp.append(e)\n else:\n temp.append(syllable)\n return temp\n \n if not os.path.exists(src):\n logger.error('{} 合成失败: 请先下载 syllables.zip (https://sourceforge.net/projects/hantts/files/?source=navbar) 并解压到 ~/.wukong 目录下'.format(self.SLUG))\n return None\n logger.debug(\"{} 合成中...\".format(self.SLUG))\n delay = 0\n increment = 355 # milliseconds\n pause = 500 # pause for punctuation\n syllables = lazy_pinyin(text, style=pypinyin.TONE3)\n syllables = preprocess(syllables)\n \n # initialize to be complete silence, each character takes up ~500ms\n result = AudioSegment.silent(duration=500*len(text))\n for syllable in syllables:\n path = os.path.join(src, syllable+\".wav\")\n sound_file = Path(path)\n # insert 500 ms silence for punctuation marks\n if syllable in self.punctuation:\n short_silence = AudioSegment.silent(duration=pause)\n result = result.overlay(short_silence, position=delay)\n delay += increment\n continue\n # skip sound file that doesn't exist\n if not sound_file.is_file():\n continue\n segment = AudioSegment.from_wav(path)\n result = result.overlay(segment, position=delay)\n delay += increment\n\n tmpfile = ''\n with tempfile.NamedTemporaryFile() as f:\n tmpfile = f.name\n result.export(tmpfile, format=\"wav\")\n logger.info('{} 语音合成成功,合成路径:{}'.format(self.SLUG, tmpfile))\n return tmpfile", "def get_tts(input_text, bookname, audio_number):\n session = requests.Session()\n session.trust_env = False\n audio_path = ''\n url = \"http://10.2.16.111:5000/get_tts\"\n payload = {\n \"input_text\": input_text,\n \"book\": bookname,\n \"audio_number\": audio_number\n }\n try:\n r = session.post(url, data=payload)\n print(\"Response: \", r.content.decode())\n j = json.loads(r.text)\n print(j)\n audio_path = get_pre_loaded_xml(j[\"ocr_text\"], page_position, bookname, page_number)\n except Exception as e:\n print(\"Error message is: \" + str(e))\n return audio_path", "def speak(text):\r\n engine.say(text)\r\n engine.runAndWait()\r\n print(text)", "def request_endpoint(audio, speech_config, output_directory, lexical):\n audio_config = speechsdk.audio.AudioConfig(filename = audio)\n speech_recognizer = speechsdk.SpeechRecognizer(speech_config = speech_config, audio_config = audio_config)\n result = speech_recognizer.recognize_once()\n filename = audio[audio.rindex('\\\\')+1:]\n text = process_recognition(result, filename, output_directory, lexical)\n return text, filename", "def speak(text):\r\n engine=pyttsx3.init('sapi5')\r\n voices= engine.getProperty(\"voices\")\r\n engine.setProperty(\"voice\",voices[0].id)\r\n engine.say(text)\r\n engine.runAndWait()\r\n return text", "async def request_to_speak(self) -> None:\n if self.voice is None or self.voice.channel is None:\n raise ClientException('Cannot request to speak while not connected to a voice channel.')\n\n payload = {\n 'channel_id': self.voice.channel.id,\n 'request_to_speak_timestamp': datetime.datetime.utcnow().isoformat(),\n }\n\n if self._state.self_id != self.id:\n payload['suppress'] = False\n await self._state.http.edit_voice_state(self.guild.id, self.id, payload)\n else:\n await self._state.http.edit_my_voice_state(self.guild.id, payload)", "def POST(self, text):\n lang = guess_language(text)\n return {'language': lang}", "def api_speech(data, ua):\n # Random header\n headers = {\n 'Content-Type': 'audio/x-flac; rate=16000;',\n 'User-Agent': ua['google chrome'],\n }\n params = (\n ('client', 'chromium'),\n ('pFilter', '0'),\n ('lang', 'en'),\n ('key', 'AIzaSyBOti4mM-6x9WDnZIjIeyEU21OpBXqWBgw'),\n )\n\n proxies = None\n\n if len(data) == 0:\n return\n\n # api call\n try:\n response = requests.post('http://www.google.com/speech-api/v2/recognize',\n proxies=proxies,\n headers=headers,\n params=params,\n data=data)\n except Exception as inst:\n print(inst)\n\n # Parse api response\n try:\n transcript = extract_transcript(response.text)\n return transcript\n except Exception as inst:\n print(inst)\n return", "def speak(audio):\n engine.say(audio)\n engine.runAndWait()", "def speak(audio):\n engine.say(audio)\n engine.runAndWait()", "def __pronounce(self, text, language):\n if not text or not language:\n return\n \n if self.__translatorRequest is None:\n from .TranslatorRequest import TranslatorRequest\n self.__translatorRequest = TranslatorRequest(self)\n \n if self.__mediaPlayer is None:\n self.__mediaPlayer = QMediaPlayer(self)\n self.__mediaPlayer.stateChanged.connect(\n self.__mediaPlayerStateChanged)\n \n if self.__mediaPlayer.state() == QMediaPlayer.PlayingState:\n return\n \n self.__ensureTranslationEngineReady()\n if self.__translationEngine is not None:\n if not self.__translationEngine.hasTTS():\n E5MessageBox.critical(\n self,\n self.tr(\"Translation Error\"),\n self.tr(\"The selected translation service does not\"\n \" support the Text-to-Speech function.\"))\n return\n \n data, ok = self.__translationEngine.getTextToSpeechData(\n self.__translatorRequest, text, language)\n if ok:\n self.__mediaFile = QTemporaryFile(self)\n self.__mediaFile.open()\n self.__mediaFile.setAutoRemove(False)\n self.__mediaFile.write(data)\n \n self.__mediaPlayer.setMedia(QMediaContent(), self.__mediaFile)\n self.__mediaPlayer.play()\n else:\n E5MessageBox.critical(\n self,\n self.tr(\"Translation Error\"),\n data)", "def createTTSGoal(text, lang_id='', wait_before_speaking=rospy.Duration(0.0)):\n sound_goal = SoundGoal()\n sound_goal.text=text\n sound_goal.lang_id=lang_id\n sound_goal.wait_before_speaking=wait_before_speaking\n return sound_goal", "def speak(self, text):\r\n self.engine.say(text)\r\n self.engine.runAndWait()", "def get_user_speech_input(self):\n\t\twith sr.Microphone() as source:\n\t\t\tprint \"You can speak!\"\n\t\t\taudio = self.recog.listen(source, 5)\n\t\t\t\n\t\t#WIT_AI_KEY = \"4KKA5EH6VFWPMWYZTSFHNJJZYCZHGTAQ\"\n\t\tprint \"sending it\"\n\t\ttry:\n\t\t\tprint \"Google thinks: \" + self.recog.recognize_google(audio)\n\t\texcept sr.UnknownValueError:\n\t\t\tprint(\"Google Speech Recognition could not understand audio\")\n\t\texcept sr.RequestError as e:\n\t\t\tprint(\"Could not request results from Google Speech Recognition service; {0}\".format(e))", "async def speak(ctx, *, message: commands.clean_content):\n await _speak(ctx, \"en\", \"com\", message)", "def speak(self, text):\n\n try:\n tts.speak(text)\n except NotImplementedError:\n popup = Popup(title='TTS Not Implemented',\n content=Label(text='Sorry. TTS is not available.'),\n size_hint=(None, None),\n size=(300, 300))\n popup.open()", "def text_to_speech(entry):\n text = entry.get_text()\n if text:\n subprocess.call([\"milena_say\", text])", "def do_speak(goal):\n rospy.loginfo('speech goal: {}'.format(goal))\n\n res = do_synthesize(goal)\n rospy.loginfo('synthesizer returns: {}'.format(res))\n\n try:\n r = json.loads(res.result)\n except Exception as e:\n s = 'Expecting JSON from synthesizer but got {}'.format(res.result)\n rospy.logerr('{}. Exception: {}'.format(s, e))\n finish_with_result(s)\n return\n\n result = ''\n\n if 'Audio File' in r:\n audio_file = r['Audio File']\n rospy.loginfo('Will play {}'.format(audio_file))\n play(audio_file)\n result = audio_file\n\n if 'Exception' in r:\n result = '[ERROR] {}'.format(r)\n rospy.logerr(result)\n\n finish_with_result(result)", "async def speak(self, ctx, *, text: str):\n state = self.get_voice_state(ctx.message.server)\n opts = {\n 'quiet': True,\n 'user-agent': 'stagefright/1.2 (Linux;Android 6.0)',\n 'referer': 'https://translate.google.com/'\n }\n base_url = 'http://translate.google.com/translate_tts'\n if len(text) > 400:\n await self.bot.say('Hmm, that text is too long. I\\'ll cut it to 400 characters.')\n text = text[:400]\n rounds = textwrap.wrap(text, width=100)\n\n if state.voice is None:\n success = await ctx.invoke(self.summon)\n if not success:\n return\n if state.voice.channel != ctx.message.author.voice_channel:\n await self.bot.say('You can only modify the queue if you\\'re in the same channel as me!')\n return\n if len(state.songs._queue) >= 6:\n await self.bot.say('There can only be up to 6 items in queue!')\n return\n\n for intxt in rounds:\n g_args = {\n 'ie': 'UTF-8',\n 'q': intxt,\n 'tl': 'en-us',\n 'client': 'tw-ob',\n 'idx': '0',\n 'total': '1',\n 'textlen': '12',\n 'tk': str(self.tokenizer.calculate_token(intxt))\n }\n await self.bot.say('Adding to voice queue:```' + intxt + '```**It may take up to *10 seconds* to queue.**')\n player = await state.voice.create_ytdl_player(base_url + '?' + urlencode(g_args), ytdl_options=opts, after=state.toggle_next)\n player.volume = 0.75\n entry = VoiceEntry(ctx.message, player, False)\n await state.songs.put(entry)\n await self.bot.say('Queued **Speech**! :smiley:')\n await asyncio.sleep(1)", "def generate(self, text):\n self.__params['text']=text\n self._data = requests.get(self.TTS_URL, params=self.__params,\n stream=False).iter_content()", "def get_language(language_id):\n\n api = (api_name, 'language')\n args_params = (str(language_id), )\n \n response = make_request(*args_params, api=api, action='get', **{})\n status_code = response.status_code\n content = response.text\n\n msg = str(status_code) + ' : ' + content\n \n if status_code >= 300:\n\n click.echo(\"response error message: %s \" % msg)\n raise click.Abort()\n \n\n logger.debug(\"response from spanglish get_language: {}\".format(response))\n logger.debug(\"response msg from spanglish get_language: {}\".format(msg))\n\n click.echo(\"response message: %s \" % msg)", "def _get_speech(self, source):\n response = requests.get(source)\n xml = response.content\n\n speech = self._parse_xml(xml)\n return speech", "def text_to_speech(\n host: Text,\n out: Text,\n format: Text,\n language: Text,\n samplerate: int,\n speech_rate: float,\n jwt_file: Text,\n username: Text,\n password: Text,\n insecure: bool,\n auth_host: Text,\n cert: Optional[Text],\n namespace: Text,\n service: Text,\n port: Text,\n debug: bool,\n speech: Tuple[Text],\n) -> None:\n global audio_fifo, CHUNK_SIZE\n\n CHUNK_SIZE = samplerate // 10\n audio_fifo = AudioFifo(CHUNK_SIZE)\n\n if not speech:\n speech = DEFAULT_SPEECH\n\n print(f\" Speech: {speech}\")\n print(f\" Host: {host}\")\n print(f\"Sampling rate: {samplerate}\")\n if out:\n print(\"Saving speech to '{args.out}'\")\n print()\n\n count = 1 # packet counter\n audio = b\"\" # buffer where the audio data is collected\n\n if insecure:\n grpc_channel = grpc.insecure_channel(host)\n else:\n if cert:\n with open(cert, \"rb\") as f:\n creds = grpc.ssl_channel_credentials(f.read())\n else:\n creds = grpc.ssl_channel_credentials()\n\n grpc_channel = grpc.secure_channel(host, creds)\n if username and not password:\n password = getpass()\n keycloak = KeyCloak(auth_host=auth_host, cert=cert)\n persistent_token = PersistentAccessToken(keycloak, username, password, jwt_file)\n\n try:\n access_token = persistent_token.get_token()\n except Exception as e:\n print(e)\n sys.exit(1)\n\n print(f\"Using access_token: {access_token}\")\n\n with grpc_channel as ctx:\n tts = TextToSpeechStub(ctx)\n\n if format == \"pcm\":\n # With PCM we can instantly play back the synthesized speech\n stream = sd.OutputStream(\n samplerate=samplerate,\n blocksize=CHUNK_SIZE,\n channels=1,\n dtype=np.int16,\n callback=callback,\n finished_callback=stop_event.set,\n )\n with stream:\n print(\"Synthesizing and instantly playing back speech...\")\n for response in tts.synthesize(\n TextToSpeechRequest(\n text=\" \".join(speech),\n language=language,\n audio_format=AudioFormat(\n encoding=AUDIO_FORMATS[format], samplerate=samplerate\n ),\n debug=debug,\n ),\n metadata=[\n (\"accesstoken\", access_token),\n (\"namespace\", namespace),\n (\"service\", service),\n (\"port\", port),\n ],\n ):\n print(\n f\"Received audio chunk #{count} ({len(response.audio)} bytes)\"\n )\n audio_fifo.put(np.frombuffer(response.audio, dtype=np.int16))\n if out:\n # Buffer the speech only if it should be saved into a file\n audio += response.audio\n count += 1\n\n if response.HasField(\"debug_info\"):\n print(\"#### DEBUG INFO ####\")\n pprint(MessageToDict(response.debug_info))\n print(\"#\" * 20)\n\n audio_fifo.flush()\n stop_event.wait()\n else:\n # Some other format than PCM is buffered and played back after the whole file is\n # received.\n print(\"Synthesizing speech...\")\n for response in tts.synthesize(\n TextToSpeechRequest(\n text=\" \".join(speech),\n language=language,\n speech_rate=speech_rate,\n audio_format=AudioFormat(\n encoding=AUDIO_FORMATS[format], samplerate=samplerate\n ),\n debug=debug,\n ),\n metadata=[\n (\"accesstoken\", access_token),\n (\"namespace\", namespace),\n (\"service\", service),\n (\"port\", port),\n ],\n ):\n print(f\"Received audio chunk #{count} ({len(response.audio)} bytes)\")\n audio += response.audio\n count += 1\n\n if response.HasField(\"debug_info\"):\n print(\"#### DEBUG INFO ####\")\n pprint(MessageToDict(response.debug_info))\n print(\"#\" * 20)\n\n print(\"Playing back speech...\")\n playback_audio, samplerate = sf.read(BytesIO(audio), dtype=\"int16\")\n sd.play(playback_audio, samplerate=samplerate, blocking=True)\n\n if out and audio:\n # Save the synthesized speech to a file\n print(f\"Saving {len(audio)} bytes to {out}\")\n with open(out, \"wb\") as f:\n f.write(audio)\n\n print(\"Done.\")", "async def app_say() -> Response:\n voice = request.args.get(\"voice\", \"\")\n assert voice, \"No voice provided\"\n\n # cache=false or cache=0 disables WAV cache\n use_cache = request.args.get(\"cache\", \"\").strip().lower() not in {\"false\", \"0\"}\n\n # Text can come from POST body or GET ?text arg\n if request.method == \"POST\":\n text = request.data.decode()\n else:\n text = request.args.get(\"text\")\n\n assert text, \"No text provided\"\n\n vocoder = request.args.get(\"vocoder\")\n denoiser_strength = request.args.get(\"denoiserStrength\")\n if denoiser_strength is not None:\n denoiser_strength = float(denoiser_strength)\n\n wav_bytes = await text_to_wav(\n text,\n voice,\n vocoder=vocoder,\n denoiser_strength=denoiser_strength,\n use_cache=use_cache,\n )\n\n return Response(wav_bytes, mimetype=\"audio/wav\")", "def stt(self, audio, language, limit):\n\n return self.request({\n \"method\": \"POST\",\n \"headers\": {\"Content-Type\": \"audio/x-flac\"},\n \"query\": {\"lang\": language, \"limit\": limit},\n \"data\": audio\n })" ]
[ "0.70442706", "0.6185518", "0.6089862", "0.6000693", "0.59898984", "0.59892875", "0.5983067", "0.59538555", "0.5942186", "0.5904593", "0.589987", "0.5897557", "0.5882125", "0.5855573", "0.5855573", "0.58457834", "0.5836635", "0.5835496", "0.5825341", "0.58195424", "0.5769832", "0.576617", "0.5751383", "0.57259154", "0.5720924", "0.5675942", "0.563825", "0.562276", "0.5614329", "0.56090397" ]
0.81863856
0
Reset dims values to initial states.
def reset(self): # Don't reset axis labels self.range = ((0, 2, 1),) * self.ndim self.current_step = (0,) * self.ndim self.order = tuple(range(self.ndim))
{ "objective": { "self": [], "paired": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
[ "def reset_states(self):\n K.batch_set_value([(v, 0) for v in self.variables])", "def reset_state(self):\n for row in range(len(self.state)):\n for column in range(len(self.state[row])):\n self.state[row][column] = None", "def reset_all(self):\n self._stepsize = _stepsize\n self.reset_f()\n self.reset_s()\n self.reset_u()", "def reset_state(self):\n self.s = np.copy(self.s_i)", "def reset(self):\n self._previous_v = 0\n self._previous_m = 0\n self._previous_shape = 0", "def reset(self):\n for i in range(0, len(self.current_state)):\n self.current_state[i] = 0\n\n for i in range(0, len(self.weights)):\n self.weights[i] = 0", "def reset(self):\r\n self.A = np.zeros(self.A.shape)", "def reset(self):\n self.position = np.zeros(self.ndegres)\n self.velocity = np.zeros(self.ndegres)\n self.state = np.zeros(2*self.ndegres)\n self.flag = 0\n self.h_ref = np.array([self.ref for _ in range(self.horizon)])\n self.action = np.zeros(self.ACTION_DIM) \n self.h_action = np.zeros(self.ACTION_DIM*self.horizon)", "def reset_values(self):\n\n self.values = np.array([])", "def reset(self):\n self.F = 0\n self.M = 0\n self.w = np.zeros(self.n)\n self.z = np.zeros(self.n)", "def reset_reservoir(self):\n self.state = np.zeros((self.state_size,1),dtype=self.typefloat)", "def restart(self):\n self.grid = np.zeros((3, 3), dtype=int)\n self.state = 0", "def _reset(self, env_id: np.ndarray) -> None:", "def reset(self):\n self.state.fill(EMPTY)", "def _clear(self):\n self.xi.ravel()[:] = 0\n self.xi_im.ravel()[:] = 0\n self.meanr.ravel()[:] = 0\n self.meanlogr.ravel()[:] = 0\n self.weight.ravel()[:] = 0\n self.npairs.ravel()[:] = 0\n self._varxi = None\n self._cov = None", "def reset(self):\n \n #initiate all tiles' value to 0\n self._grid_2048 = [[0 for dummy_col in range(self._grid_width)] for dummy_row in range(self._grid_height)]\n \n # two new tiles\n self.new_tile()\n self.new_tile()", "def reset(self):\n previous_solution_values = tf.constant(np.tile((self._action_lower_bound + self._action_upper_bound) / 2,\n [self._planning_horizon * self._num_agents, 1]), dtype=tf.float32)\n previous_solution_values = tf.reshape(previous_solution_values, [-1])\n solution_variance_values = tf.constant(\n np.tile(np.square(self._action_lower_bound - self._action_upper_bound) / 16,\n [self._planning_horizon * self._num_agents, 1]), dtype=tf.float32)\n solution_variance_values = tf.reshape(solution_variance_values, [-1])\n self._m.assign(previous_solution_values)\n self._sigma.assign(tf.math.sqrt(solution_variance_values))", "def reset(self):\r\n self.grid = [[0 for dummy_col in range(self.grid_width)] for dummy_row in range(self.grid_height)]\r\n self.new_tile()\r\n self.new_tile()", "def reset(self):\n self.z = rand(*self.z.shape)\n self.c = ones_like(self.c)", "def reset(self):\n self.reset_image_estimate()\n self.init_m_aux()\n self.reset_hessian_and_bias()\n self.reset_adadelta_variables()", "def reset(self):\n self.__init__(self.subDomainnumMonomers, self.dim, self.b, self.subDomainNc, self.keepCL, position = self.positions)", "def _reset_dimensional_data(self, dataset):\n # local reference to input data\n raw = dataset.get_source_data('prep')\n\n nfids = raw.shape[-2]\n \n nfids = int(nfids/self.set.fids_to_average)\n \n data_shape = list(raw.shape)\n data_shape[-2] = nfids\n\n self.frequency_shift = np.zeros([nfids])\n self.phase_0 = np.zeros([nfids])\n self.measure_time = np.arange(nfids)\n\n self.data = np.zeros(data_shape, dtype=raw.dtype)\n if self.chain is not None:\n self.chain.reset_results_arrays()", "def reset(self):\n self.train_loss.reset_states()\n self.train_accuracy.reset_states()\n self.val_loss.reset_states()\n self.val_accuracy.reset_states()\n self.train_mIoU.reset_states()\n self.val_mIoU.reset_states()", "def reset(self):\n self.x_prev = np.zeros_like(self.mu)", "def reset(self):\r\n self.state = copy.copy(self.mu)", "def reset(self):\n self.items = np.arange(self.ratings.shape[1])", "def reset(self):\n self._grid = [[0] * self._width for _ in range(self._height)]\n self.new_tile()\n self.new_tile()", "def reset(self):\n self._grid = [[0 for dummy_col in range(self._width)]\n for dummy_row in range(self._height)]\n self.new_tile()\n self.new_tile()", "def reset(self):\n self.dims.clear()\n self.xlabels.clear()\n self.annotators.clear()\n self._figTitle = None\n self.tbmTitle = None\n self._isSubplot = False\n self._universal_xlabel = False\n self._plotter = None\n self.Nsp = 0", "def reset(self):\n self.state = copy.copy(self.mu)" ]
[ "0.72302496", "0.6860482", "0.6855735", "0.67577887", "0.67106414", "0.66854584", "0.6611975", "0.6588729", "0.6568128", "0.6565924", "0.65548766", "0.65257764", "0.65088725", "0.6506533", "0.6469049", "0.6465789", "0.64638746", "0.6454795", "0.6448066", "0.64407986", "0.643706", "0.6428473", "0.64120966", "0.64118356", "0.6408417", "0.63991815", "0.6398069", "0.63975984", "0.6385731", "0.6376084" ]
0.6904098
1