query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Finds a single fit range given an array defining a group of Lorentzians.
def find_full_fit_range(lorentz_params_array): (f_low_stop_list, f_low_list, f_high_list, f_high_stop_list) = find_all_fit_ranges(lorentz_params_array) f_low_stop = min(f_low_stop_list) f_low = min(f_low_list) f_high = max(f_high_list) f_high_stop = max(f_high_stop_list) return (f_low_stop,...
[ "def find_all_fit_ranges(lorentz_params_array):\n f_low_stop_list = []\n f_low_list = []\n f_high_list = []\n f_high_stop_list = []\n for i in range(0, lorentz_params_array.shape[0]):\n fit_range = find_single_fit_range(lorentz_params_array[i])\n f_low_stop_list.append(fit_range[0])\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a list of fit ranges for any number of Lorentzians.
def find_all_fit_ranges(lorentz_params_array): f_low_stop_list = [] f_low_list = [] f_high_list = [] f_high_stop_list = [] for i in range(0, lorentz_params_array.shape[0]): fit_range = find_single_fit_range(lorentz_params_array[i]) f_low_stop_list.append(fit_range[0]) f_low_l...
[ "def find_partitioned_fit_ranges(lorentz_params_list):\n fit_range_list = []\n for a in lorentz_params_list:\n fit_range_list.append(find_full_fit_range(a))\n return fit_range_list", "def find_full_fit_range(lorentz_params_array):\n (f_low_stop_list, f_low_list, f_high_list,\n f_high_stop_l...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Counts how many Lorentzians from the 2D array are within the fit range.
def count_lorentz(fit_range, lorentz_array_2d): counter = 0 for i in range(0, lorentz_array_2d.shape[0]): f0 = lorentz_array_2d[i][1] if f0 > fit_range[1] and f0 < fit_range[2]: counter += 1 return counter
[ "def count(self):\n return np.sum(self.grid != 0)", "def number_of_carnivores_island(self):\n return np.sum(self.carnivores_on_island)", "def count_placeholders(peaks: Sequence[FittedPeak]) -> int:\n i = 0\n for peak in peaks:\n if peak.intensity <= 1:\n i += 1\n return ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a list of fit ranges from the provided Lorentzians.
def find_partitioned_fit_ranges(lorentz_params_list): fit_range_list = [] for a in lorentz_params_list: fit_range_list.append(find_full_fit_range(a)) return fit_range_list
[ "def find_all_fit_ranges(lorentz_params_array):\n f_low_stop_list = []\n f_low_list = []\n f_high_list = []\n f_high_stop_list = []\n for i in range(0, lorentz_params_array.shape[0]):\n fit_range = find_single_fit_range(lorentz_params_array[i])\n f_low_stop_list.append(fit_range[0])\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determines if the provided fit ranges are violated.
def evaluate_fit_range(predicted, fit_range): test1 = (predicted[0] >= fit_range[0]) test2 = (predicted[0] <= fit_range[1]) test3 = (predicted[1] >= fit_range[2]) test4 = (predicted[1] <= fit_range[3]) return all([test1, test2, test3, test4])
[ "def isRangeValid(self) -> bool:\n ...", "def evaluate_all_fit_ranges(predicted, fit_range_list):\n tests = []\n for i in range(0, len(fit_range_list)):\n tests.append(evaluate_fit_range(predicted[i], fit_range_list[i]))\n return all(tests)", "def test_interval_out_of_bound_risk(x_range, ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a list of fit ranges, will check all of them to see how much they overlap and are violated.
def evaluate_all_fit_ranges(predicted, fit_range_list): tests = [] for i in range(0, len(fit_range_list)): tests.append(evaluate_fit_range(predicted[i], fit_range_list[i])) return all(tests)
[ "def find_overlap(min_ls, max_ls, check_ls):\n value = []\n for i in check_ls:\n if min(min_ls) <= i <= max(max_ls):\n value.append(i)\n percentage = (len(value) / len(check_ls)) * 100\n return percentage", "def evaluate_fit_range(predicted, fit_range):\n test1 = (predicted[0] >= ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Normalizes indices around the provided scale values.
def normalize_index(x, input_scale, output_scale): return np.round(x / input_scale[2] * output_scale[2])
[ "def normalize_scale(self):\n for b in self.bases:\n b.co = (self.scale / self.true_scale) * b.co\n self.scale = self.true_scale", "def normalize(values, figure):\n if figure.vars.get(\"scale_to_filter\", False):\n idx_filter, _ = figure.do_filter()\n else:\n idx_filte...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Separates all data from the provided list of data arrays.
def separate_all_data(data_arrays_list): separated_data_list = [] for i in range(0, len(data_arrays_list)): separated_data_list.append(separate_data(data_arrays_list[i])) return separated_data_list
[ "def split_data(self, data):\n l = len(data)\n sec_len = int(np.ceil(l / self.num_break))\n return np.array_split(data, self.num_break)", "def split_data(coordinates):\n data_1 = coordinates[0]\n data_2 = coordinates[1]\n data_3 = coordinates[2]\n data_4 = coordinates[3]\n data...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Equalizes the provided data with the provided labels.
def equalize_data(class_labels, class_data): a1 = class_data[np.where(class_labels == 1)[0]] a2 = class_data[np.where(class_labels == 2)[0]] max_len = min(len(a1), len(a2)) a1 = a1[0:max_len] a2 = a2[0:max_len] arr = np.concatenate((a1, a2)) b1 = np.ones((max_len, 1)) * 0 b2 = np.ones((m...
[ "def set_labels(self, data: base.DataType, labels: base.DataType) -> None:\n for doc, label in zip(data, labels):\n setattr(doc, 'label', label)", "def assure_all_labels_occur(data, num_classes, multi_label=False):\n label_list = [labels for *_, labels in data\n if isinstance...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Zooms in on the data from the provided array given the start and end values (not indices).
def scale_zoom(x, start, end): length = len(x) start_index = int(np.round(length * start)) end_index = int(np.round(length * end)) if start_index >= end_index: if start_index <= 3: start_index = 0 end_index = 3 else: start_index = end_index - 3 ret...
[ "def zoom(self,xmin,xmax,xlen,ymin,ymax,ylen):\n\n self.xmin = xmin\n self.xmax = xmax\n self.xlen = xlen\n self.ymin = ymin\n self.ymax = ymax\n self.ylen = ylen\n r = np.linspace(self.xmin, self.xmax,self.xlen)\n q = np.linspace(self.ymin, self.ymax, s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This method creates sample objects with id, list of genes values and label. Finally adds each object into a set.
def create_samples(self): for s_id in range(len(self.data["sample"])): self.samples.add(Sample(s_id, [self.data[key][s_id] for key in self.data.keys() if key not in WRONG_KEYS], self.data["label"][s_id]))
[ "def create_samples(self):\n sample_list = []\n genes = []\n for record in range(len(self.data_dict[\"samples\"])):\n sample_id = self.data_dict[\"samples\"][record]\n genes_cols = list(self.data_dict.keys())[2:]\n for gene in genes_cols:\n genes....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
bert_out [batch_size, num_pieces, bert_dim] ner_labels [batch_size, num_tokens, num_tokens] logits [batch_size, num_entities_max, bert_bim or cell_dim 2] num_entities [batch_size]
def _get_entities_representation(self, bert_out: tf.Tensor, ner_labels: tf.Tensor) -> Tuple[tf.Tensor, tf.Tensor]: # dropout bert_out = self.bert_dropout(bert_out, training=self.training_ph) # pieces -> tokens x = tf.gather_nd(bert_out, self.first_pieces_coords_ph) # [batch_size, num_t...
[ "def _get_entities_representation(self, bert_out: tf.Tensor, ner_labels: tf.Tensor) -> Tuple[tf.Tensor, tf.Tensor]:\n # dropout\n bert_out = self.bert_dropout(bert_out, training=self.training_ph)\n\n # pieces -> tokens\n x = tf.gather_nd(bert_out, self.first_pieces_coords_ph) # [batch_s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initialize the parameters of the redshift distribution
def __init__(self, *args, gals_per_arcmin2=1.0, zmax=10.0, **kwargs): self._norm = None self._gals_per_arcmin2 = gals_per_arcmin2 super(redshift_distribution, self).__init__(*args, zmax=zmax, **kwargs)
[ "def init_params(self):\n GAOperator.init_params(self)", "def init_parameters():\n return {'w': random.uniform(-1, 1) * 0.001, 'b': 0}", "def __init__(self, size, parameters):\n\n self.weights = self.init_weights(size)\n self.alpha = parameters['alpha']\n self.epsilon = parameters...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Computes the normalized n(z)
def __call__(self, z): if self._norm is None: self._norm = simps(lambda t: self.pz_fn(t), 0.0, self.config["zmax"], 256) return self.pz_fn(z) / self._norm
[ "def updated_normalize(x, n_n):\n if n_n == \"n\":\n return x\n elif n_n == \"c\":\n return matutils.unitvec(x)", "def _normalizeState(self, Z : vector) -> vector:\n return Z * self.D", "def norms(Z):\n return Z.view(Z.shape[0], -1).norm(dim=1)[:,None,None,None]", "def z_normaliz...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sends a command to the controller and reads response till sentinel. ...
async def send_command(self, message, sentinel=None): content = None reader = None writer = None try: reader, writer = await asyncio.open_connection(self.ip, self.port) await reader.readuntil('Shade Controller'.encode()) writer.write(message.encode()...
[ "def do_command(command):\n send_command(command)\n # time.sleep(0.1) # may be required on slow machines\n response = get_response()\n print(\"Rcvd: <<< \" + response)\n return response", "def do_command(command):\n send_command(command)\n response = get_response()\n print(\"Rcvd: <<< \\n\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a shade or list of shades by id, name or room. ...
def get_shade(self, name=None, id=None, room=None): if(name): return self.shades[name] if name in self.shades else None if(id): return next((v for (k,v) in self.shades.items() if v.id == id), None) if(room): return [value for (key, value) in self.shades.item...
[ "def _get_shading(idf):\n shading_types = [\n 'SHADING:ZONE:DETAILED',\n ]\n shading = []\n for shading_type in shading_types:\n shading.extend(idf.idfobjects[shading_type])\n\n return shading", "def _get_shading(idf):\n shading_types = [\"SHADING:ZONE:DETAILED\", \"SHADING:SITE:DE...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a scene by id, name. ...
def get_scene(self, name=None, id=None): if(name): return self.scenes[name] if name in self.scenes else None if(id): return next((v for (k,v) in self.scenes.items() if v.id == id), None) return None
[ "def get_scene(self, scenename):\n return self.scenes.get(scenename)", "def get_scene(self, label: str) -> Scene:\r\n return self._get_resource(label, self._scenes, \"scene\")", "def _resolve_scene(self, name):\n all_scenes = self.__try_to_get(self.bridge.scenes)\n if not all_scenes:...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a room by id, name. ...
def get_room(self, name=None, id=None): if(name): return self.rooms[name] if name in self.rooms else None if(id): return next((v for (k,v) in self.rooms.items() if v.id == id), None) return None
[ "def get_room_by_id(self, id):\n if not isinstance(id, int):\n id = int(id)\n if self.rooms.has_key(id):\n return self.rooms[id]\n raise RuntimeError, \"Room not known\"", "def getRoomById(self, id):\n for room in self.rooms:\n if room.id == id:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Moves a shade to a certain level ...
async def set_level(self, hd_value): if "up" == hd_value: move_value = 255 elif "down" == hd_value: move_value = 0 else: if hd_value.isdigit(): move_value = min(int(round(int(hd_value)*255.0/100)),255) else: ...
[ "def set_shade(self, shade):\n self.pen_shade = shade", "def dimmer_switch(turtle, color):\n turtle.fillcolor(color + \"4\")", "def set_level(self,level):\r\n \r\n self.level = level", "def decrement_floor(self):\r\n self.current_elevation = self.current_elevation - 1\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
expects a single video_descriptors object. videos_desciptors objects are defined in IDT_feature.py fv_file is the full path to the fisher vector that is created. this single video_desc contains the (trajs, hogs, hofs, mbhs) np.ndarrays
def create_fisher_vector(gmm_list, video_desc, fv_file, fv_sqrt=False, fv_l2=False): vid_desc_list = [] vid_desc_list.append(video_desc.traj) vid_desc_list.append(video_desc.hog) vid_desc_list.append(video_desc.hof) vid_desc_list.append(video_desc.mbh) # For each video create and normalize a fis...
[ "def extract_video_feature(video_directory, feature_path):\n h5file = tables.open_file(\n feature_path, 'w', 'Extracted video features of the MSRVTT-QA dataset.')\n vgg_features = extract_resnet(video_directory)\n h5file.create_array('/', 'vgg', vgg_features, 'vgg16 feature')\n #c3d_features = ex...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests whether ``ApplicationCommandOptionMetadataNested.copy`` works as intended.
def test__ApplicationCommandOptionMetadataNested__copy(): options = [ ApplicationCommandOption('nue', 'nue', ApplicationCommandOptionType.string), ApplicationCommandOption('seija', 'seija', ApplicationCommandOptionType.integer), ] option_metadata = ApplicationCommandOptionMetadataNested...
[ "def test__ApplicationCommandOptionMetadataNested__copy_with__0():\n options = [\n ApplicationCommandOption('nue', 'nue', ApplicationCommandOptionType.string),\n ApplicationCommandOption('seija', 'seija', ApplicationCommandOptionType.integer),\n ]\n \n option_metadata = ApplicationCommandO...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests whether ``ApplicationCommandOptionMetadataNested.copy_with`` works as intended.
def test__ApplicationCommandOptionMetadataNested__copy_with__0(): options = [ ApplicationCommandOption('nue', 'nue', ApplicationCommandOptionType.string), ApplicationCommandOption('seija', 'seija', ApplicationCommandOptionType.integer), ] option_metadata = ApplicationCommandOptionMetada...
[ "def test__ApplicationCommandOptionMetadataNested__copy_with__1():\n old_options = [\n ApplicationCommandOption('nue', 'nue', ApplicationCommandOptionType.string),\n ApplicationCommandOption('seija', 'seija', ApplicationCommandOptionType.integer),\n ]\n \n new_options = [\n Applicat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests whether ``ApplicationCommandOptionMetadataNested.copy_with`` works as intended.
def test__ApplicationCommandOptionMetadataNested__copy_with__1(): old_options = [ ApplicationCommandOption('nue', 'nue', ApplicationCommandOptionType.string), ApplicationCommandOption('seija', 'seija', ApplicationCommandOptionType.integer), ] new_options = [ ApplicationCommandOp...
[ "def test__ApplicationCommandOptionMetadataNested__copy_with__0():\n options = [\n ApplicationCommandOption('nue', 'nue', ApplicationCommandOptionType.string),\n ApplicationCommandOption('seija', 'seija', ApplicationCommandOptionType.integer),\n ]\n \n option_metadata = ApplicationCommandO...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests whether ``ApplicationCommandOptionMetadataNested.copy_with_keyword_parameters`` works as intended.
def test__ApplicationCommandOptionMetadataNested__copy_with_keyword_parameters__0(): options = [ ApplicationCommandOption('nue', 'nue', ApplicationCommandOptionType.string), ApplicationCommandOption('seija', 'seija', ApplicationCommandOptionType.integer), ] option_metadata = Application...
[ "def test__ApplicationCommandOptionMetadataNested__copy_with_keyword_parameters__1():\n old_options = [\n ApplicationCommandOption('nue', 'nue', ApplicationCommandOptionType.string),\n ApplicationCommandOption('seija', 'seija', ApplicationCommandOptionType.integer),\n ]\n \n new_options = ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests whether ``ApplicationCommandOptionMetadataNested.copy_with_keyword_parameters`` works as intended.
def test__ApplicationCommandOptionMetadataNested__copy_with_keyword_parameters__1(): old_options = [ ApplicationCommandOption('nue', 'nue', ApplicationCommandOptionType.string), ApplicationCommandOption('seija', 'seija', ApplicationCommandOptionType.integer), ] new_options = [ A...
[ "def test__ApplicationCommandOptionMetadataNested__copy_with_keyword_parameters__0():\n options = [\n ApplicationCommandOption('nue', 'nue', ApplicationCommandOptionType.string),\n ApplicationCommandOption('seija', 'seija', ApplicationCommandOptionType.integer),\n ]\n \n option_metadata = ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Converts field value according to Proto3 JSON Specification.
def _FieldToJsonObject(self, field, value): if field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE: return self._MessageToJsonObject(value) elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_ENUM: if self.use_integers_for_enums: return value if field.enum_type.full_name...
[ "def _FieldToJsonObject(self, field, value):\n if field.cpp_type == json_format.descriptor.FieldDescriptor.CPPTYPE_MESSAGE:\n return self._MessageToJsonObject(value)\n elif field.cpp_type == json_format.descriptor.FieldDescriptor.CPPTYPE_ENUM:\n if self.use_integers_for_enums:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Converts Value message according to Proto3 JSON Specification.
def _ValueMessageToJsonObject(self, message): which = message.WhichOneof('kind') # If the Value message is not set treat as null_value when serialize # to JSON. The parse back result will be different from original message. if which is None or which == 'null_value': return None if which == 'li...
[ "def _ConvertValueMessage(self, value, message):\n if isinstance(value, dict):\n self._ConvertStructMessage(value, message.struct_value)\n elif isinstance(value, list):\n self._ConvertListValueMessage(value, message.list_value)\n elif isinstance(value, (datetime, date)):\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Converts ListValue message according to Proto3 JSON Specification.
def _ListValueMessageToJsonObject(self, message): return [self._ValueMessageToJsonObject(value) for value in message.values]
[ "def _ConvertListValueMessage(self, value, message, path):\n if not isinstance(value, list):\n raise ParseError('ListValue must be in [] which is {0} at {1}'.format(\n value, path))\n message.ClearField('values')\n for index, item in enumerate(value):\n self._ConvertValueMessage(item, me...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Converts Struct message according to Proto3 JSON Specification.
def _StructMessageToJsonObject(self, message): fields = message.fields ret = {} for key in fields: ret[key] = self._ValueMessageToJsonObject(fields[key]) return ret
[ "def _proto2object(\n proto: UpdateSetupMessage_PB,\n ) -> \"UpdateSetupMessage\":\n\n return UpdateSetupMessage(\n msg_id=_deserialize(blob=proto.msg_id),\n address=_deserialize(blob=proto.address),\n content=json.loads(proto.content),\n reply_to=_deseri...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a message from a type URL.
def _CreateMessageFromTypeUrl(type_url, descriptor_pool): db = symbol_database.Default() pool = db.pool if descriptor_pool is None else descriptor_pool type_name = type_url.split('/')[-1] try: message_descriptor = pool.FindMessageTypeByName(type_name) except KeyError: raise TypeError( 'Can not...
[ "def create_message(self, phrase, task_type, url):\n # Tweet V3\n if task_type == self.TASK_TYPE_DETAILS:\n tweet = \"Help the community understand \\\"{}\\\" by \" +\\\n \"enriching #stackoverflow with youtube videos \" +\\\n \"you know of {} #stackann...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert a JSON representation into Any message.
def _ConvertAnyMessage(self, value, message, path): if isinstance(value, dict) and not value: return try: type_url = value['@type'] except KeyError: raise ParseError( '@type is missing when parsing any message at {0}'.format(path)) try: sub_message = _CreateMessageFrom...
[ "def parse(cls, json: Dict) -> Any:\n raise NotImplementedError # pragma: no cover", "def parse(message):\n try:\n return json.loads(message)\n except TypeError:\n print(\"Ignoring message because it did not contain valid JSON.\")", "def any2text(any):\n if isinsta...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert a JSON representation into ListValue message.
def _ConvertListValueMessage(self, value, message, path): if not isinstance(value, list): raise ParseError('ListValue must be in [] which is {0} at {1}'.format( value, path)) message.ClearField('values') for index, item in enumerate(value): self._ConvertValueMessage(item, message.value...
[ "def _ListValueMessageToJsonObject(self, message):\n return [self._ValueMessageToJsonObject(value)\n for value in message.values]", "def createList( self, list_json ):\n return List(\n trello_client = self,\n list_id = list_json['id'].encode('utf-8'),\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert map field value for a message map field.
def _ConvertMapFieldValue(self, value, message, field, path): if not isinstance(value, dict): raise ParseError( 'Map field {0} must be in a dict which is {1} at {2}'.format( field.name, value, path)) key_field = field.message_type.fields_by_name['key'] value_field = field.messa...
[ "def _ConvertMapFieldValue(self, value, message, field):\n if not isinstance(value, dict):\n raise ParseError(\n 'Map field {0} must be in a dict which is {1}.'.format(\n field.name, value))\n key_field = field.message_type.fields_by_name['key']\n value_field = field.message_type...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert a single scalar field value.
def _ConvertScalarFieldValue(value, field, path, require_str=False): try: if field.cpp_type in _INT_TYPES: return _ConvertInteger(value) elif field.cpp_type in _FLOAT_TYPES: return _ConvertFloat(value, field) elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_BOOL: return _Convert...
[ "def _ConvertScalarFieldValue(value, field, require_str=False):\n if field.cpp_type in _INT_TYPES:\n return _ConvertInteger(value)\n elif field.cpp_type in _FLOAT_TYPES:\n return _ConvertFloat(value)\n elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_BOOL:\n return _ConvertBool(value, require_s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tries each provider uri in provider_uris until the command succeeds
def add_provider_uri_fallback_loop(python_callable, provider_uris): def python_callable_with_fallback(**kwargs): for index, provider_uri in enumerate(provider_uris): kwargs['provider_uri'] = provider_uri try: python_callable(**kwargs) break ...
[ "def run_providers(self, argv):\n\n for name, provider in self.providermanager:\n provider = provider(self)\n self.produce_output(provider.title,\n provider.location,\n provider.run(argv))", "def test_provider(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the x,y coordinates. Convert_to may be set to 'deg' or 'rad' for convenience.
def coordsxy(self, convert_to=False): if convert_to == 'rad': return (self.x*3.14159/180., self.y*3.14159/180.) elif convert_to == 'deg': return (self.x/3.14159*180., self.y/3.14159*180.) else: return (self.x, self.y)
[ "def to_coordinates(self, point, to_coords_type='ball'):\n return Hyperbolic.change_coordinates_system(point,\n self.coords_type,\n to_coords_type)", "def coords(self, to_sys=None):\n if to_sys:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the compass azimuth from self to other in degrees, measured clockwise with north at 0.
def azimuth(self, other, projected=True): x0, y0 = self.x, self.y if self.crs != other.crs: x1, y1 = other.get_vertex(self.crs)[:2] else: x1, y1 = other.x, other.y if (x0, y0) == (x1, y1): az = np.nan elif projected and not isinstance(self.crs...
[ "def azimuth(self):\n return self.get_azimuth()", "def azimuth_calculator(pnt1: QgsPointXY, pnt2: QgsPointXY) -> float:\n azimuth = pnt1.azimuth(pnt2)\n if azimuth < 0:\n azimuth += 360\n return azimuth", "def get_azimuth(self):\n self.degrees = self.azimuth_encoder.get_degrees()\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Whether bounding box overlaps with that of another Geometry.
def _bbox_overlap(self, other): reg0 = self.bbox reg1 = other.bbox return (reg0[0] <= reg1[2] and reg1[0] <= reg0[2] and reg0[1] <= reg1[3] and reg1[1] <= reg0[3])
[ "def overlaps(self, other: 'BBox') -> bool:\n\t\treturn (self.pMax.x >= other.pMin.x) and (self.pMin.x <= other.pMax.x) and \\\n\t\t (self.pMax.y >= other.pMin.y) and (self.pMin.y <= other.pMax.y) and \\\n\t\t (self.pMax.z >= other.pMin.z) and (self.pMin.z <= other.pMax.z)", "def bbox_overlap(bbox_1: ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Shift geometry in space.
def shift(self, shift_vector, inplace=False): if len(self.vertices) == 0: raise GGeoError('cannot shift zero length geometry') if len(shift_vector) != len(self.vertices[0]): raise GGeoError('shift vector length must equal geometry rank') if inplace: self.vert...
[ "def shift(self, offset):\n self.bounding_box.shift(offset)", "def shift_to_origin(layout):\n mini = min( i for (i,j) in layout[\"coords\"].keys() ) \n minj = min( j for (i,j) in layout[\"coords\"].keys() )\n shift(layout,-mini,-minj)", "def shift(self, offset):\n self.x += offset[1]\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Apply an affine transform given by matrix M to data and return a new geometry.
def apply_affine_transform(self, M): vertices = [] for x,y in self.get_vertices(): vertices.append(tuple(np.dot(M, [x, y, 1])[:2])) return type(self)(vertices, properties=self.properties, crs=self.crs)
[ "def affine_transform(geom, matrix):\n if geom.is_empty:\n return geom\n if len(matrix) == 6:\n ndim = 2\n a, b, d, e, xoff, yoff = matrix\n if geom.has_z:\n ndim = 3\n i = 1.0\n c = f = g = h = zoff = 0.0\n matrix = a, b, c, d, e, f, g, ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the "flat Earth" distance from each vertex to a point.
def flat_distances_to(self, pt): A = np.array(self.vertices) P = np.tile(np.array(pt.vertex), (A.shape[0], 1)) d = np.sqrt(np.sum((A-P)**2, 1)) return d
[ "def get_distances(centroid, points):\r\n return np.linalg.norm(points - centroid, axis=1)", "def point_distances(self, params=None):\n if params is None:\n params = self.collocation_points()\n with self.fix_evaluator():\n pts = np.array([self(la) for la in params])\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the index of the vertex that is nearest to a point. If two points are equidistant, only one will be returned.
def nearest_vertex_to(self, point): distances = self.distances_to(point) idx = np.argmin(distances) return idx
[ "def nearest_point_index(self, point):\n return _nearest_point_index(self._points, point)", "def _nearest_point_index(points, point):\n distance = sys.float_info.max\n index = None\n for i, p in enumerate(points):\n temp = _vec_distance(p, point)\n if temp < distance:\n di...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return whether any vertices are inside poly
def any_within_poly(self, poly): for pt in self: if poly.contains(pt): return True return False
[ "def polygon_contains(self, poly_outer, poly_inner):\n inner_list = self.poly_to_list(poly_inner, \"Global\")\n contain_list = []\n\n # Loop over all points in the inner polygon to see if they are contained by the outer polygon\n for point in inner_list:\n # Points are defined...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a Polygon representing the convex hull. Not implemented for geographical coordinate systems.
def convex_hull(self): if isinstance(self.crs, GeographicalCRS): raise CRSError("not implemented for geographical coordinate " "systems. Project to a projected coordinate system.") points = [pt for pt in self] # Find the lowermost (left?) point pt...
[ "def convex_hull(self) -> 'Polygon':\n if self.is_convex:\n return self\n else:\n context = self._context\n border = context.contour_cls(context.points_convex_hull(\n self.border.vertices\n ))\n return context.polygon_cls(border...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Datelineaware get_bbox for geometries consisting of connected vertices.
def get_bbox(self, crs=None): if (isinstance(self.crs, GeographicalCRS) and (crs is None or isinstance(crs, GeographicalCRS))): x, y = self.get_coordinate_lists(crs=crs) return _cdateline.dateline_bbox(np.array(x, dtype=np.float64), ...
[ "def get_bbox(self):\n return self.to_linestring().bounds # (minx, miny, maxx, maxy)", "def get_bbox(self):\n min_x = 0\n max_x = 0\n min_y = 0\n max_y = 0\n for i in self._id_to_position.values():\n min_x = min(min_x, i.x)\n min_y = min(min_y, i.y)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns an generator of adjacent line segments as coordinate tuples.
def segment_tuples(self): return ((self.vertices[i], self.vertices[i+1]) for i in range(len(self.vertices)-1))
[ "def segment_tuples(self):\n return ((self.vertices[i-1], self.vertices[i])\n for i in range(len(self.vertices)))", "def lines(self):\n for pair in pairs(self.points):\n yield Line(pair, shape=self)", "def iter_coords():\n yield (0, 0)\n incr = 0\n x = 1\n y =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return whether an intersection exists with another geometry.
def intersects(self, other): if isinstance(self.crs, CartesianCRS): if not self._bbox_overlap(other): return False interx = _cintersection.all_intersections(self.vertices, other.vertices) return len(interx) != 0 else: for a in self.segment_...
[ "def is_on_intersection(intersection, coord):\n return intersection.is_on_intersection(coord)", "def intersects(self, other):\n\n return bool(\n self.__class__ is other.__class__\n and set(self.positions) & set(other.positions)\n )", "def intersects(self, other): # -> boo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the intersections with another geometry as a Multipoint.
def intersections(self, other, keep_duplicates=False): if isinstance(self.crs, CartesianCRS): interx = _cintersection.all_intersections(self.vertices, other.vertices) if not keep_duplicates: interx = list(set(interx)) return Multipoint(interx, crs=self.crs) ...
[ "def intersection(self, other): # -> BaseGeometry:\n ...", "def intersection(self, other):\n return self._geomgen(capi.geom_intersection, other)", "def intersection(self, other):\n from pyresample.spherical_geometry import intersection_polygon\n return intersection_polygon(self.corn...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a tuple of the shortest distance on the geometry boundary to a point, and the vertex at that location. If necessary, project coordinates to the local coordinate system.
def _nearest_to_point(self, point): ptvertex = point.get_vertex(crs=self.crs) segments = zip(self.vertices.slice(0, -1), self.vertices.slice(1, 0)) if isinstance(self.crs, CartesianCRS): func = _cvectorgeo.pt_nearest_planar def func(seg): return _cvectorg...
[ "def vertexDistance(X,Vp,return_points=False):\n # Compute the distances\n dist = length(X[:,newaxis]-Vp)\n # Get the shortest distances\n OKdist = dist.min(-1)\n if return_points:\n # Get the closest points matching X\n minid = dist.argmin(-1)\n OKpoints = Vp[minid]\n ret...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the shortest distance from any position on the geometry boundary to a point.
def shortest_distance_to(self, pt): return self._nearest_to_point(pt)[0]
[ "def distance_x(self, point):\n # Check if point is already on the edge\n if self.contains(point):\n return 0\n\n a, b, x_boundaries, y_boundaries = self.get_equation_params()\n \n if not(y_boundaries[0] <= point.y <= y_boundaries[1]):\n # y is outside of the...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the position on the geometry boundary that is nearest to a point. If two points are equidistant, only one will be returned.
def nearest_on_boundary(self, point): _, minpt = self._nearest_to_point(point) return Point(minpt, crs=self.crs)
[ "def _nearest_to_point(self, point):\n ptvertex = point.get_vertex(crs=self.crs)\n segments = zip(self.vertices.slice(0, -1), self.vertices.slice(1, 0))\n\n if isinstance(self.crs, CartesianCRS):\n func = _cvectorgeo.pt_nearest_planar\n def func(seg):\n retu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test whether a point is within distance geometry.
def within_distance(self, point, distance): return all(distance >= seg.shortest_distance_to(point) for seg in self.segments)
[ "def isinsidepointXY(x,p):\n \n return dist(x,p) < epsilon", "def _contains_point(obj: Any, point: array_like, **kwargs: float) -> bool:\n distance = obj.distance_point(point)\n\n return math.isclose(distance, 0, **kwargs)", "def d_within(\n self,\n right: GeoSpatialValue,\n dis...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a boolean that indicates whether any segment crosses the dateline
def crosses_dateline(self): if not isinstance(self.crs, GeographicalCRS): raise CRSError("Dateline detection only defined for geographical " "coordinates") return any(self._seg_crosses_dateline(seg) for seg in self.segments)
[ "def has_crossing_line(image):\n # TODO: future task\n return False", "def is_cross(self, wnd):\r\n return (self.start <= wnd.end and\r\n self.end >= wnd.start and\r\n wnd.line == self.line)", "def line_segment_touches_or_crosses_line(a: LineSegment, b: LineSegment) ->...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return n equally spaced Point instances along line.
def to_npoints(self, n): segments = self.segments Ltotal = self.cumulength()[-1] step = Ltotal / float(n-1) step_remaining = step vertices = [self[0].get_vertex()] x = 0.0 pos = self[0] seg = next(segments) seg_remaining = seg.displacement() ...
[ "def GetLinePoints(n,x0,x1,y0,y1):\n\t\n\txs = pl.linspace(x0,x1,n)\n\tys = pl.linspace(y0,y1,n)\n\t\n\treturn xs,ys", "def scatter_points(n):\r\n P1 = np.random.randn(int(np.ceil(n/2)), 2) - 4\r\n P2 = 3 * np.random.rand(int(np.ceil(n/4)), 2) - np.array([10, 0])\r\n P3 = np.random.randn(int(np.ceil(n/4)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a generator of adjacent line segments as coordinate tuples.
def segment_tuples(self): return ((self.vertices[i-1], self.vertices[i]) for i in range(len(self.vertices)))
[ "def segment_tuples(self):\n return ((self.vertices[i], self.vertices[i+1])\n for i in range(len(self.vertices)-1))", "def lines(self):\n for pair in pairs(self.points):\n yield Line(pair, shape=self)", "def iter_coords():\n yield (0, 0)\n incr = 0\n x = 1\n y...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the perimeter of the polygon. If there are subpolygons, their perimeters are added recursively.
def perimeter(self): return sum(seg.length for seg in self.segments) + \ sum([p.perimeter for p in self.subs])
[ "def perimeter(polygon):\n\tperimeter = 0\n\tpoints = polygon + [polygon[0]]\n\tfor i in range(len(polygon)):\n\t\tperimeter += distance(points[i], points[i+1])\n\treturn perimeter", "def polygonal_perimeter(shape, tolerance=1):\n contours = find_contours(shape, 0.5, fully_connected=\"high\")\n total = 0\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return Multipoint subset that is within a polygon.
def within_polygon(self, poly): if hasattr(self, "quadtree"): bbox = poly.get_bbox(crs=self.crs) candidate_indices = self.quadtree.search_within(*bbox) confirmed_indices = [] for i in candidate_indices: if poly.contains(self[i]): ...
[ "def intersects(self, polygon):\n return intersects(self, polygon)", "def get_subset(p_in, f_shp, f_out='s1a_subset.dim'):\n WKTReader = snappy.jpy.get_type('com.vividsolutions.jts.io.WKTReader')\n wkt = get_poly(f_shp)\n geom = WKTReader().read(wkt)\n param = HashMap()\n param.put('geoRegio...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return sign of 2D cross product a x b
def _signcross(a, b): c = (a[0]*b[1]) - (a[1]*b[0]) if c != 0: return c/abs(c) else: return 0
[ "def cross(a, b):\n return np.array([a[1]*b[2] - a[2]*b[1],\n a[2]*b[0] - a[0]*b[2],\n a[0]*b[1] - a[1]*b[0]])", "def crossproduct(a: Point, b: Point) -> float:\n return a.x * b.y - b.x * a.y", "def cross_product(p0,p1,p2):\n\treturn (((p1[0]-p0[0])*(p2[1]-p0[1]))-(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Merge singlepart geometries into a multipart geometry. Properties contained by all inputs are stored in Multipart data attribute.
def multipart_from_singleparts(parts, crs=None): if len(parts) == 0: raise ValueError("cannot construct multipart from zero singleparts") if crs is None: crs = parts[0].crs keys = list(parts[0].properties.keys()) for part in parts[1:]: for key in keys: if key not in...
[ "def _multigeometry(self, ogr_geometry):\n\n geo_type = ogr_geometry.GetGeometryType()\n\n if geo_type == ogr.wkbPolygon:\n return ogr.ForceToMultiPolygon(ogr_geometry)\n elif geo_type == ogr.wkbPoint:\n return ogr.ForceToMultiPoint(ogr_geometry)\n elif geo_type in ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the (z, x, y) locator for an OpenStreetMap tile containing a point.
def get_tile_tuple(point, zoom): z = int(zoom) dlon = 256 dlat = 256 lon0, lat0 = point.crs.project(*point.vertex[:2], inverse=True) c = 128/math.pi * 2**z x0 = c * (lon0*math.pi/180+math.pi) y0 = c * (math.pi-math.log(math.tan(math.pi/4+lat0*math.pi/360))) x = int(x0 // dlon) y = ...
[ "def locate(self, point: Point[Scalar]) -> Location:", "def coords_of_tile(state, tile_to_find):\n\tfor x, column in enumerate(state):\n\t\tfor y, tile in enumerate(column):\n\t\t\tif tile == tile_to_find:\n\t\t\t\treturn x, y\n\traise ValueError(\"tile \" + str(tile_to_find) + \" does not exist in state \" + str...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate a bank name.
def bank(self) -> str: return self.random_element(self.banks)
[ "def account_name_generator():\n return 'jdoe-' + str(uuid()).lower()[:16]", "def bank_name(self):\n return self.__bank_name", "def get_name():\n return \"{}:{}\".format(random.choice(NAMES), random.randint(10000, 99999))", "def name_generator():\n firsts = [\"Albrecht\", \"Lysa\", \"Yvette\",...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load ROOT 1D histogram RHist1D specified by `path`.
def get_rhist1d(self, path): raise NotImplementedError
[ "def histogram_from_file(root_file_names, path_to_histograms, x_bins=None, y_bins=None, z_bins=None, name=None):\n\n\t\tif isinstance(root_file_names, basestring):\n\t\t\troot_file_names = [root_file_names]\n\t\tif isinstance(path_to_histograms, basestring):\n\t\t\tpath_to_histograms = [path_to_histograms]\n\n\t\t#...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load ROOT 2D histogram RHist2D specified by `path`.
def get_rhist2d(self, path): raise NotImplementedError
[ "def get_rhist1d(self, path):\n raise NotImplementedError", "def get2d(infile, histname, subdir='',verbose=False): \n\n ## 2d Histogram\n Hist = getter(infile,histname,subdir,verbose)\n\n nbinsX, nbinsY = Hist.GetNbinsX(), Hist.GetNbinsY()\n Arr = np.zeros((nbinsY,nbinsX))\n dArr = np.zeros(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Blogger Page view. Get logged Blogger and retrieve Posts
def bloggerView(request): blogger = request.user.blogger posts = blogger.post_set.all() paginator = Paginator(posts, 6) # Show 6 posts per page. page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) context = { 'blogger': blogger, 'posts': posts, ...
[ "def get(self):\n blog_posts = db.GqlQuery(\"SELECT * FROM Blogpost ORDER BY created DESC\")\n\n logged_in = False\n if get_user(self):\n logged_in = True\n\n self.render(\"mainpage.html\", blog_posts=blog_posts, logged_in=logged_in)", "def bloggerVisitView(request, pk):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create Blog view. Uses BloggerForm
def createBlogView(request): data = { 'user': request.user, 'email': request.user.email, } bloggerForm = BloggerForm(initial=data) if request.method == "POST": bloggerForm = BloggerForm(request.POST, request.FILES) if bloggerForm.is_valid(): bloggerForm.save...
[ "def get(self):\n return self.render({'action': 'create-blog'}, 'blog-form.html')", "def blog_create(request):\n entry = BlogRecord()\n form = BlogCreateForm(request.POST)\n if request.method == 'POST' and form.validate():\n form.populate_obj(entry)\n request.dbsession.add(entry)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Perform a Blogger search based on a given name
def searchResultsView(request): bloggerName = request.GET.get("search_blogger") bloggers = Blogger.objects.all().filter(name__icontains=bloggerName) context = { "bloggers": bloggers, } return render(request, "blog/search_results.html", context)
[ "def SearchDemo(name, keyword):", "def search(self, term):", "def searchSite(search_name):\n for obj in obj_list:\n if search_name == obj.name:\n print(obj)\n break\n else:\n print(\"No climbing site with that name found... Returning to main menu.\")\n menu()", "de...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Blogger Visit view. User cannot edit an object as a visitor.
def bloggerVisitView(request, pk): blogger = Blogger.objects.get(id=pk) posts = blogger.post_set.all() paginator = Paginator(posts, 6) # Show 6 posts per page. page_number = request.GET.get('page') page_obj = paginator.get_page(page_number) context = { "blogger": blogger, "post...
[ "def can_view(self, user):\r\n return True", "def internal_blog_visitor(request):\n if request.user.is_authenticated():\n return redirect(reverse('debra.account_views.home'))\n return HttpResponse(\"<html><body>Welcome to <a href='http://www.theshelf.com'>TheShelf.com</a>. This is an internal ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Devuelve el primer elemento de la lista l
def _primerElem(l): return l[0]
[ "def _sel_entry(i, l):\n return l[min(i, len(l)-1)] if type(l) == list else l", "def getElement(self,l):\n if not l:\n return self\n h, *t = l\n try:\n return self.children[h].getElement(t)\n except KeyError:\n return None", "def getElement(sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Elimina el elemento de la posicion pos de la lista l
def _del(pos, l): if pos == 0: return l[1:] elif pos == len(l) - 1: return l[:pos] else: return l[0:pos] + l[pos+1:]
[ "def deleteLL(self,pos):\n pos.next = pos.next.next", "def _primerElem(l):\n return l[0]", "def remove(self, item):\n\t\tif self.len == 0:\n\t\t\traise ValueError(\"Lista vacia\")\n\t\tif self.prim.dato == item:\n\t\t\tself.borrar_primero()\n\t\t\treturn\n\t\tanterior = self.prim\n\t\tactual =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Store a copy of given cuds_object in the session. Return the stored object.
def _store(self, cuds_object): assert cuds_object.session == self self._registry.put(cuds_object) for t in cuds_object._graph: self.graph.add(t) cuds_object._graph = self.graph if self.root is None: self.root = cuds_object.uid
[ "def raw_save_session(self, session):\n dict_session = dict(session)\n self._mosession.storage.collection.save(dict_session)\n self._mosession.cache.set(session.sid, dict_session)", "def add(self, obj):\n self.getSession().add(obj)\n self.commit() # paranoially\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load the cuds_objects with the given iris.
def load_from_iri(self, *iris): return self.load(*[uid_from_iri(iri) for iri in iris])
[ "def load_iris_dataset():\n \n # Location and file name for the dataset\n file_location = 'iris'\n data_file = file_location + os.sep + 'iris.data'\n \n # We have to map the categorical class names to numbers\n mapping = { 'Iris-setosa':'0', 'Iris-versicolor':'1', 'Iris-virginica':'2'}\n \n # Prepare a...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove all elements not reachable from the sessions root. Only consider given relationship and its subclasses.
def prune(self, rel=None): deleted = self._registry._get_not_reachable(self.root, rel=rel) for d in deleted: self._delete_cuds_triples(d)
[ "def _remove_relations(self):\n self.tree = etree.parse(self.output_file)\n\n for tlink in self.tree.xpath(\"//TLINK\"):\n tlink.getparent().remove(tlink)", "def clear_relations(self):\n self.children = {}\n self.parents = {}", "def delete_relatives(self):\n categor...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove a CUDS object. Will not delete the cuds objects contained.
def delete_cuds_object(self, cuds_object): from osp.core.namespaces import cuba if cuds_object.session != self: cuds_object = next(self.load(cuds_object.uid)) if cuds_object.get(rel=cuba.relationship): cuds_object.remove(rel=cuba.relationship) self._delete_cuds_t...
[ "def remove_cuds_object(cuds_object):\n # Method does not allow deletion of the root element of a container\n for elem in cuds_object.iter(rel=cuba.relationship):\n cuds_object.remove(elem.uid, rel=cuba.relationship)", "def _delete_cuds_triples(self, cuds_object):\n del self._registry[cuds_obj...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Delete the triples of a given cuds object from the session's graph.
def _delete_cuds_triples(self, cuds_object): del self._registry[cuds_object.uid] t = self.graph.value(cuds_object.iri, rdflib.RDF.type) self.graph.remove((cuds_object.iri, None, None)) cuds_object._graph = rdflib.Graph() cuds_object._graph.set((cuds_object.iri, rdflib.RDF.type, t...
[ "def delete_cuds_object(self, cuds_object):\n from osp.core.namespaces import cuba\n\n if cuds_object.session != self:\n cuds_object = next(self.load(cuds_object.uid))\n if cuds_object.get(rel=cuba.relationship):\n cuds_object.remove(rel=cuba.relationship)\n self._d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Notify the session that some object has been deleted.
def _notify_delete(self, cuds_object):
[ "def _objectDeleted(self, obj):\n pass", "def after_delete(self, obj, st):\n pass", "def delete(self, obj):", "def ticket_deleted(self, ticket):", "def delete(self, request, *args, **kwargs):\n self.object = self.get_object()\n success_url = self.get_success_url()\n self.s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Notify the session that some object has been updated.
def _notify_update(self, cuds_object):
[ "def update(self, observerable, object):\n print(f'observer 1: update from observable notify: {object}')", "def update(self, observerable, object):\n print(f'observer 2: update from observable notify: {object}')", "def after_update(self, obj, st):\n pass", "def changedInBackend(self, obj)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Notify the session that given cuds object has been read. This method is called when the user accesses the attributes or the relationships of the cuds_object cuds_object.
def _notify_read(self, cuds_object):
[ "def _notify_update(self, cuds_object):", "def mark_read(self):\n\n self._topic()._rcache[int(self.id)] = True", "def read(self):\n if self.status == 'read':\n return\n self.status = 'read'\n self.emit('read')\n self.emit('modified')", "def _notify_delete(self, cu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a toc_path, write rst and return a file object.
def rst_for_module(toc_path): f = open(toc_path + '.rst', 'w+') heading = ":mod:`{}`".format(os.path.basename(toc_path)) dotted = toc_path.replace('/', '.') w(f, heading) w(f, "=" * len(heading)) w(f, ".. automodule:: {}", dotted) return f
[ "def test_writetofile():\n sat_before_nuc = \\\n t('circumstance', [\n ('S', ['sat first']),\n ('N', ['nuc second'])\n ])\n\n tempfile = NamedTemporaryFile()\n rstc.write_rstlatex(sat_before_nuc, tempfile.name)\n\n with open(tempfile.name, 'r') as rstlatex_file:\n asse...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given ../mylib/path/to/package and lists of dir/file names, write rst.
def rst_for_package(root, dirs, files): doc_path = root[3:] if not os.path.isdir(doc_path): os.mkdir(doc_path) # Start a rst doc for this package. # ================================= f = rst_for_module(doc_path) # Add a table of contents. # ======================== w(f, "....
[ "def writedocs(dir, pkgpath='', done=None):\n if done is None: done = {}\n for importer, modname, ispkg in pkgutil.walk_packages([dir], pkgpath):\n writedoc(modname)\n return", "def generate_dir_rst(dir, fhindex, example_dir, root_dir, plot_gallery):\n if not dir == '.':\n target_dir = o...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a generator for skimming lines in this file
def skim_generator(lines, file): total_length = 0 count = 0 seekable = True # Try and seek in the file. If it's a stream, we can't do it try: file.seek(0, WHENCE_RELATIVE) except IOError, e: seekable = False log.debug("File is not seekable, falling back to reading") ...
[ "def skim(lines, file):\n for line in skim_generator(lines, file):\n sys.stdout.write(line)", "def line_generator(self):\n for V in self.ambient_Vrepresentation():\n if V.is_line():\n yield V", "def kmer(self):\n with open(self._file, 'r') as f:\n lin...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Skim through the provided file printing out one line in every (lines)
def skim(lines, file): for line in skim_generator(lines, file): sys.stdout.write(line)
[ "def display_enumerated_lines(filename):", "def print_file(path):\n contents = open(path, 'r').read()\n print('| ' + '\\n| '.join(contents.split('\\n')))\n return", "def print_solutions(file_):\n with open(file_, 'r') as inp:\n for line in inp:\n print(line[:-5] + str(process_lin...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adds a new wall picture to the node definition Launches a dialog, and validates and posts the entered information to the repository for the creation of a new wall picture for the node that is being edited
def _add_new_wall_pic(self, pic=None): # Display the dialogue results = pic if results is None: results = NodePictureDialog(self) results = results._entries item_id = results["name"] item = results # Extract the return values try: ...
[ "def add_new_from_picture(self, database):\n pic = self.take_picture()\n desc = self.find_faces(pic, database)\n desc = desc[0]\n warnings.filterwarnings(\"ignore\", \".*GUI is implemented.*\")\n try:\n plt.pause(0.5)\n except Exception:\n pass\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove the wall picture that is currently selected
def _remove_wall_pic(self): # Retrieve the item that was selected key = self._listbox.get(ACTIVE) # Post a delete notice to the manager self._remove(key)
[ "def deselect(self):\n if self.selected:\n self.selected = False\n global pinList\n pinList.remove(self)\n self.path = \"Images/\" + self.color + \".png\"\n pinList.append(self)", "def click_remove_file(self):\n if self.attached_file is not None...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Slow, naive solution. The available coins are 1, 3, and 4. Takes input m (amount to arrive at) and returns the minimum number of moves to arrive there.
def get_change_recursive(m): if m < 0: raise ValueError("Invalid negative amount") if m == 0: raise ValueError("ok 0 moves, but this shouldn't happen either.") if m in [1, 3, 4]: return 1 alt_paths = [get_change_recursive(m-1)] if m > 3: alt_paths.append(get_change...
[ "def get_change(m, coins: list = [1, 3, 4]):\n min_num_coins = {0: 0}\n for m in range(1, m + 1):\n min_num_coins[m] = math.inf\n for coin in coins:\n if m >= coin:\n num_coins = min_num_coins[m - coin] + 1\n if num_coins < min_num_coins[m]:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
QMdiArea.addSubWindow(QWidget, Qt.WindowFlags flags=0) > QMdiSubWindow
def addSubWindow(self, QWidget, Qt_WindowFlags_flags=0): # real signature unknown; restored from __doc__ return QMdiSubWindow
[ "def mdi_wrap(self):\n from glue.app.qt.mdi_area import GlueMdiSubWindow\n sub = GlueMdiSubWindow()\n sub.setWidget(self)\n self.destroyed.connect(sub.close)\n self.window_closed.connect(sub.close)\n sub.resize(self.size())\n self._mdi_wrapper = sub\n\n return...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
QMdiArea.eventFilter(QObject, QEvent) > bool
def eventFilter(self, QObject, QEvent): # real signature unknown; restored from __doc__ return False
[ "def eventFilter(self, qobject, event):\n return False", "def event(self, QEvent): # real signature unknown; restored from __doc__\n return False", "def viewportEvent(self, QEvent): # real signature unknown; restored from __doc__\n return False", "def eventFilter(self, widget: QObject, ev...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
QMdiArea.subWindowList(QMdiArea.WindowOrder order=QMdiArea.CreationOrder) > listofQMdiSubWindow
def subWindowList(self, QMdiArea_WindowOrder_order=None): # real signature unknown; restored from __doc__ pass
[ "def _get_mdi_windows(self):\n isinst = isinstance\n windows = (c for c in self.children if isinst(c, MdiWindow))\n return tuple(windows)", "def _windows(session, exclude=None):\n if exclude is None:\n exclude = []\n wins = [w for w in session.handles if w not in exclude]\n re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This method is for editing the record of a status
def edit_status(self,id,type,status): current_user = get_jwt_identity() try: con = init_db() cur = con.cursor() cur.execute("SELECT is_admin FROM users WHERE email = %s",(current_user,)) user = cur.fetchall() user_role = user[0][0] ...
[ "def update_status(status):", "def update_status(self, status):\n pass", "def _update_status(self):\n self._db_update({'status': self.status})", "def updateStatus(self, status):\n pass", "def changestatus(request, complaint_id, status):\n if status == '3':\n StudentComplain.ob...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a list of query_results, asks feedback to the user and adds it to each JSON in the list
def ask_feedback(query_results): print('Google Search Results:') print('======================') for i, result in enumerate(query_results): print('Result ', i+1) print('[') print('URL: ', result['url']) print('Title: ', result['title']) print('Summary: ', result['su...
[ "def add_results(self, results):\n\n # We add all reddit posts which are not in our DB. We\n # check if a post from results is in the DB based on ID\n # ID = key\n\n json_data = self.data\n\n for key in results.keys():\n if key in json_data.keys():\n body...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function gets called when a player presses Buzz.
def buzz(self, name): self.server.buzzMutex.lock() if self.server.buzzed == False: self.server.buzzed = True else: self.server.buzzMutex.unlock() return self.server.buzzMutex.unlock() self.server.changeStatus(name, 'Answering') for player in self.server.players.items(): try: player[1][0].d...
[ "def on_buy(self, args):\n if self._phase is PHASE_BUYING and self.buys > 0 and 'name' in args:\n card_name = args['name']\n self._game.player_buy(self, self.coins, card_name)\n else:\n logger.error('Player %s asked to buy,' % self.name\n + ' bu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Turn the phrase into a list of skipgrams and index them with their offset(s) as values.
def _index_skipgrams(self) -> None: for skipgram in self.skipgrams: self.skipgram_index[skipgram.string] += [skipgram] for skipgram in self.skipgrams_lower: self.skipgram_index_lower[skipgram.string] += [skipgram]
[ "def skipgram_offsets(self, skipgram_string: str) -> Union[None, List[int]]:\n if not self.has_skipgram(skipgram_string):\n return None\n return [skipgram.offset for skipgram in self.skipgram_index[skipgram_string]]", "def skipgram(_input: List[str], N: int, skip: Optional[int] = None,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set the label(s) of a phrase. Labels must be string and can be a single string or a list.
def set_label(self, label: Union[str, List[str]]) -> None: if not is_valid_label(label): raise ValueError("phrase label must be a single string or a list of strings:", label) self.label = label if isinstance(label, str): self.label_set = {label} self.label_lis...
[ "def labels(self, labels):\n self._instructions_setter('LABEL', labels)", "def AddLabelsFromString(self, labels):\n if self.labels is None:\n self.labels = set()\n\n self.labels = self.labels.union([x.strip() for x in labels.split(',')])", "def set_labels(self, labels):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add key/value pairs as metadata for this phrase.
def add_metadata(self, metadata_dict: Dict[str, any]) -> None: for key in metadata_dict: self.metadata[key] = metadata_dict[key] if key == "label": self.set_label(metadata_dict[key]) elif key == "max_offset": self.add_max_offset(metadata_dict["...
[ "def add_metadata(self, key, value):\n self.metadata[key] = value", "def addMetadata(self, key, value):\n self.metadata[key] = value", "def add_meta(self, key: Hashable, value) -> None:\n self.meta[key] = value", "def add_meta_data(self, key, data):\n self._meta_data[key] = data", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a maximum offset for matching a phrase in a text.
def add_max_offset(self, max_offset: int) -> None: if not isinstance(max_offset, int): raise TypeError("max_offset must be a positive integer") if max_offset < 0: raise ValueError("max_offset must be positive") self.max_offset = max_offset self.max_end = self.max_...
[ "def highlight_next_match(self):\n self.text.tag_remove('found.focus', '1.0',\n tk.END) # remove existing tag\n try:\n start, end = self.text.tag_nextrange('found', self.start, tk.END)\n self.text.tag_add('found.focus', start, end)\n self.t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
For a given skipgram, return boolean whether it is in the index
def has_skipgram(self, skipgram: str) -> bool: return skipgram in self.skipgram_index.keys()
[ "def __contains__(self, ngram):\n return ngram in self._ngrams", "def __contains__(self, ngram):\n return ngram in self.root", "def is_early_skipgram(self, skipgram: str) -> bool:\n return skipgram in self.early_skipgram_index", "def is_pos(self, term):\n return term in self.pos", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
For a given skipgram return the list of offsets at which it appears.
def skipgram_offsets(self, skipgram_string: str) -> Union[None, List[int]]: if not self.has_skipgram(skipgram_string): return None return [skipgram.offset for skipgram in self.skipgram_index[skipgram_string]]
[ "def _index_skipgrams(self) -> None:\n for skipgram in self.skipgrams:\n self.skipgram_index[skipgram.string] += [skipgram]\n for skipgram in self.skipgrams_lower:\n self.skipgram_index_lower[skipgram.string] += [skipgram]", "def get_offsets(word, raw_text):\n try:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
For a given skipgram, return boolean whether it appears early in the phrase.
def is_early_skipgram(self, skipgram: str) -> bool: return skipgram in self.early_skipgram_index
[ "def has_skipgram(self, skipgram: str) -> bool:\n return skipgram in self.skipgram_index.keys()", "def should_skip(self, text):\n return self.skipper and self.skipper.match(text)", "def has_next_Ngram(self, label):\n return label in self.next_grams", "def check_followup(query):\n if co...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Connect postgresql and create a table for index.
def create_new_index(self, dict_pg_info): # ! Setting if fun can use default setting ruler = Rules() str_conn = ruler.pg_info_rules(dict_pg_info) conn = psycopg2.connect(str_conn) with conn: with conn.cursor() as cur: str_create_table = "CREATE TABLE ...
[ "def create_index():", "def create_indices(self):\n\t\tself.pg_eng.build_idx_ddl()\n\t\tself.pg_eng.create_indices()", "def create_indices(conn, verbose=False):\n \n if verbose:\n sys.stderr.write(\"Creating indices\\n\")\n\n tables = {\n \"nodes\": {\"tidparentrank\" : [\"tax_id\", \"pa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Function for clearing log file.
def _clear_log(log_path): with logging._lock: with open(log_path, 'w'): pass
[ "def clearLog():\n logPath = getLogPath()\n\n with open(logPath, 'w') as f:\n f.write('')", "def clearFile(self):\n with open(self.LOGPATH + self.logfile, \"w\"):\n pass", "def clear_log(button):\n \n with open(LOG_FILE, 'wt') as f:\n pass # c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create another instance of the same class with another DELAYED.
def duplicate(self, delayed): return self.__class__(delayed)
[ "def __init__(self, *args):\n this = _libsbml.new_Delay(*args)\n try: self.this.append(this)\n except: self.this = this", "def __init__(self, delay=0):\n self.delay = delay", "def createDelay(self):\n return _libsbml.Model_createDelay(self)", "def clone(self):\n return _l...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }