query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Concatenate the data from different files in the file list. This function assumes that each file in file_list stores a dictionary and each element of that dictionary is an array with the zeroth dimension being the batch dimension.
def concatenate_file_data(self, file_list): # Get all the tags in the data if self.data_tags is None: self.get_data_tags(file_list[0]) # Create all the keys data = {} for tag in self.data_tags: data[tag] = [] # Load the data ...
[ "def concat_files(self, list_of_files, outfile):\n with open(outfile, 'w') as fout:\n if self.args['outfmt'] == 'lsjson':\n concat_cmd = ['cat'] + list_of_files\n subprocess.run(concat_cmd, stdout=fout)\n elif self.args['outfmt'] == 'json':\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the data corresponding to a given indices.
def get_data_from_indices(self, data_dictionary, indices): data = {} for tag in self.data_tags: try: data[tag] = data_dictionary[tag][indices] except KeyError: print("no this key in the current data file!") return data
[ "def get_data_by_indexes(indexes: list, data: np.ndarray) -> np.ndarray:\n return np.asarray([data[i, j] for i, j in indexes])", "def get_data(features, labels_aud, labels_foc, files, indices):\n features = [features[idx] for idx in indices]\n labels_aud = [labels_aud[idx] for idx in indices]\n labels...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a new unique ID for a Bokeh object. Normally this function will return UUIDs to use for identifying Bokeh objects. This is especally important for Bokeh objects stored on a Bokeh server. However, it is convenient to have more humanreadable IDs during development, so this behavior can be overridden by setting the...
def make_id(): global _simple_id import uuid from ..settings import settings if settings.simple_ids(False): _simple_id += 1 new_id = _simple_id else: new_id = uuid.uuid4() return str(new_id)
[ "def _get_id():\n return str(uuid.uuid4())", "def unique_id(cls, obj):\n return cls.unique_id_map[obj].int", "def unique_id(self) -> str:\n return self._id", "def unique_id(self) -> str:\n return (\n f\"{self._doorbell.device_id}_\"\n f\"{SENSOR_TYPES_DOORBELL[self....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test whether a given Bokeh object graph fragment is a reference. A Bokeh "reference" is a ``dict`` with ``"type"`` and ``"id"`` keys.
def is_ref(frag): return isinstance(frag, dict) and \ frag.get('type') and \ frag.get('id')
[ "def isReference(node):\n return bool(isinstance(node, nodes.Referential)\n and node.get(DuAttrRefid, None))", "def has_dangling_references(graph):\n for obj in graph.values():\n for _, obj_id in stix2generator.utils.find_references(obj):\n if obj_id not in graph:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Apply a function to JSON fragments that match the given predicate and return the collected results. Recursively traverses a nested collection of ``dict`` and ``list``, applying ``check_func`` to each fragment. If True, then collect ``func(fragment)`` in the final output
def json_apply(fragment, check_func, func): if check_func(fragment): return func(fragment) elif isinstance(fragment, list): output = [] for val in fragment: output.append(json_apply(val, check_func, func)) return output elif isinstance(fragment, dict): out...
[ "def iterate_json_list(input_file, filter_func=None):\n with open(input_file, mode=\"r\") as f_in:\n for line in f_in:\n item = json.loads(line.strip())\n if filter_func is not None:\n if filter_func(item):\n yield item\n else:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
transforms pandas series into array of values
def transform_series(obj): vals = obj.values return transform_array(vals)
[ "def _convert_to_numpy_array(series):\n if hasattr(series, \"values\"):\n return series.values\n elif isinstance(series, np.ndarray):\n return series", "def value_series(self):\n return self._series.to_numpy(copy=True)", "def as_series(self, arraylike: Iterable) -> pd.Series:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
recursively dig until a flat list is found if numpy is available convert the flat list to a numpy array and send off to transform_array() to handle nan, inf, inf otherwise iterate through items in array converting nonjson items
def traverse_data(datum, is_numpy=is_numpy, use_numpy=True): is_numpy = is_numpy and use_numpy if is_numpy and not any(isinstance(el, (list, tuple)) for el in datum): return transform_array(np.asarray(datum)) datum_copy = [] for item in datum: if isinstance(item, (list, tuple)): ...
[ "def _coerce_to_np_array(\n data: list | np.ndarray | pd.Series,\n output_type: dt.Struct,\n index: pd.Index | None = None,\n) -> np.ndarray:\n return np.array(data)", "def do_flatten(obj):\n if type(obj) == list:\n return np.array(obj).flatten()\n return obj.flatten()", "def flatte...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
iterate through the data of a ColumnSourceData object replacing nonJSONcompliant objects with compliant ones
def transform_column_source_data(data): data_copy = {} for key in iterkeys(data): if is_pandas and isinstance(data[key], (pd.Series, pd.Index)): data_copy[key] = transform_series(data[key]) elif isinstance(data[key], np.ndarray): data_copy[key] = transform_array(data[key]...
[ "def clean_data(xl_json):\n cleaned_col_values = []\n col_values = xl_json['col values']\n for k,v in xl_json['consistent type'].items():\n if not v:\n col_type = guess_type(col_values[k])\n cleaned_col_values.append(fix_type(col_type, col_values[k]))\n xl_json['cons...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a new empty Hamiltonian dictionary with specified system level and qubit number.
def createHam(title: str, dt: float, qubitNum: int, sysLevel: Union[int, List[int]]) -> Dict[str, Any]: ham = {"file": { "title": title }, "circuit": { "dt": dt, "qubits": qubitNum, "sys_level": sysLevel, "max_time_dt": 0, "max_time_ns": 0 }, "drift": {},...
[ "def createQHamiltonian(self, frame: str = \"rot\") -> QHamiltonian:\n\n # Initialize the hamiltonian\n\n ham = QHamiltonian(subSysNum=self.subSysNum, sysLevel=self.sysLevel, dt=self.dt)\n\n # Create the system Hamiltonian in the lab frame\n\n if frame == \"lab\":\n\n self._ge...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
r""" Add a coupling term to the Hamiltonian.
def addCoupling(ham: Dict[str, Any], name: str, onQubits: Union[int, List[int]], g: float = 1.0) -> None: assert len(onQubits) == 2, "Coupling term should be defined on two qubits." # Obtain the system energy level. if isinstance(ham["circuit"]["sys_level"], int): d = ham["circuit"]["sys_level"] ...
[ "def _generateCoupTerm(self, ham: QHamiltonian) -> None:\n\n for index, value in self.couplingMap.items():\n\n # Calculate the detuning of qubit i and qubit j\n\n deltaOmega = self.qubitFreq[index[0]] - self.qubitFreq[index[1]]\n\n ai = QOperator('ai')\n aj = QOper...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
r""" Add a control term to the Hamiltonian.
def addControl(ham: Dict[str, Any], name: str, onQubits: Union[int, List[int]] = None, matrices: Union[numpy.ndarray, List[numpy.ndarray]] = None) -> None: sysLevel = ham["circuit"]["sys_level"] qubitNum = ham["circuit"]["qubits"] if onQubits is None: # Input the complete matrices d...
[ "def add_control(operation, num_ctrl_qubits, label):\n if isinstance(operation, UnitaryGate):\n # attempt decomposition\n operation._define()\n if _control_definition_known(operation, num_ctrl_qubits):\n return _control_predefined(operation, num_ctrl_qubits)\n return control(operation,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Extract a specified subsystem from a given Hamiltonian. The drift and control terms local to the specified subsystem remains.
def subSystem(ham: Dict[str, Any], onQubits: Union[int, List[int]], title: str = "") -> Dict[str, Any]: subHam = copy.deepcopy(ham) # clear cache clearCache(subHam) # Set title if title == "": subHam["file"]["title"] = f"{ham['file']['title']} (extracted)" else: subHam["file"][...
[ "def get_minimum_phase_system(system, *args, **kwargs):\r\n if isinstance(system, scipy.signal.lti):\r\n return get_minimum_phase_system_continuous(system, *args, **kwargs)\r\n elif isinstance(system, scipy.signal.dlti):\r\n return get_minimum_phase_system_discrete(system, *args, **kwargs)\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check whether all the items in listB are in listA
def allIn(listA: Union[int, List[int]], listB: Union[int, List[int]]) -> bool: if isinstance(listA, int): listA = [listA] if isinstance(listB, int): return listB in listA else: for item in listB: if item not in listA: return...
[ "def is_subset(listA,listB):\n all(item in listA for item in listB)", "def all_in_list (list1, list2):\n return all(map(lambda c: c in list2, list1) )", "def is_in_list(list_one, list_two):\n \n for element in list_one:\n if element in list_two:\n return True\n return False", "d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove all waveforms in the specified control terms. If names is None, remove all waveforms in all control terms.
def clearWaves(ham: Dict[str, Any], names: Union[str, List[str]] = None) -> None: if names is None: for name in ham["control"].keys(): ham["control"][name]["waveforms"] = [] elif isinstance(names, str): ham["control"][names]["waveforms"] = [] elif isinstance(names, list): ...
[ "def deleteWaveforms(self, Names):\n if isinstance(Names, basestring):\n dlmsg='WLISt:WAVeform:DELete \"'+Names+'\"'\n else:\n try:\n dlmsg=[]\n for name in Names:\n dlmsg.append('WLISt:WAVeform:DELete \"'+name+'\"')\n e...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add waveforms to the control terms by waveData (generated by ``Utils.Waveforms.makeWaveData()``). Quanlse provides this function to add waveforms by dictionary data. In this way, users can save the wave data as a dictionary or a JSON string and import the wave batch by one function.
def addWaveData(ham: Dict[str, Any], waveData: Union[Dict[str, Any], List[Dict[str, Any]]]) -> None: if isinstance(waveData, list): for wave in waveData: addWave(ham, wave['name'], t0=wave['insert_ns'], t=wave['duration_ns'], f=wave['func'], para=wave['para']) elif isinstance(waveData, dic...
[ "def AddWave(self, wave_data):\n wave = OpBasedWave(wave_data, self)\n self._waves[wave.GetId()] = wave\n return wave", "def add_waveform_analog(self):\r\n # make sure that the square wave tab is active now\r\n channel_keyword = self.current_Analog_channel.currentText()\r\n\r\n #----...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove a specified drift term from the Hamiltonian.
def removeDrift(ham: Dict[str, Any], names: Union[str, List[str]]) -> None: if isinstance(names, str): assert names in ham["drift"].keys(), "Term does not exist." # We first extract necessary information of the circuit from Hamiltonian dictionary ham["drift"].pop(names) else: for...
[ "def remove(self, time):\n try:\n del self._d[time]\n except KeyError:\n raise KeyError('no measurement at %s' % time)", "def remove_time(self, index):\n self.times.remove(index)", "def removeCoupling(ham: Dict[str, Any], names: Union[str, List[str]]) -> None:\n if ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove a specified coupling term from Hamiltonian.
def removeCoupling(ham: Dict[str, Any], names: Union[str, List[str]]) -> None: if isinstance(names, str): assert names in ham["drift"].keys(), "Term does not exist." # We first extract necessary information of the circuit from Hamiltonian dictionary ham["drift"].pop(names) ham["drift...
[ "def remove_coupling(self, coupling):\n self.system.remove_object(coupling)", "def removeControl(ham: Dict[str, Any], names: Union[str, List[str]]) -> None:\n if isinstance(names, str):\n assert names in ham[\"control\"].keys(), \"Term does not exist.\"\n # We first extract necessary infor...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove a specified control term from the Hamiltonian.
def removeControl(ham: Dict[str, Any], names: Union[str, List[str]]) -> None: if isinstance(names, str): assert names in ham["control"].keys(), "Term does not exist." # We first extract necessary information of the circuit from Hamiltonian dictionary ham["control"].pop(names) else: ...
[ "def removeControl(*args):", "def remove_control(self, control):\n\n if control in self._controls:\n self._controls.remove(control)", "def remove_tactic(self):\n tactic_removed = input(\"Enter a tactic to be removed: \")\n self.proof.tactics.remove(tactic_removed)\n for ge...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate the cache for further usage. In this function, we run ``buildOperatorCache()`` and ``buildSequenceCache()`` to build the global operator matrices and the pulse sequences before saving them to cache.
def buildCache(ham: Dict[str, Any]) -> None: # Initialize the Hamiltonian clearCache(ham) # Build operators and sequences buildOperatorCache(ham) buildSequenceCache(ham)
[ "def setup_cache(self):\n train_cache_path = self.cache.get_cache_path_and_check(TRAIN_STR, self.task_name)\n dev_cache_path = self.cache.get_cache_path_and_check(DEV_STR, self.task_name)\n test_cache_path = self.cache.get_cache_path_and_check(TEST_STR, self.task_name)\n\n self.train_cache_writer = None...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Transform a string (generated by ``toJson()``) to the Hamiltonian dictionary.
def createFromJson(jsonStr: str) -> Dict[str, Any]: jham = json.loads(jsonStr) clearCache(jham) # Transform the control operators for key in jham["control"]: ctrls = jham["control"][key] # Modify the matrices if isinstance(ctrls["matrices"], list): mats = [] ...
[ "def parse_hamiltonian_input(input_data):\n # Get the input\n coeffs = []\n pauli_terms = []\n\n # Go through line by line and build up the Hamiltonian\n for line in input_data.split(\"S\"):\n line = line.strip()\n tokens = line.split(\" \")\n\n # Parse coefficients\n sign...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
return the detection probability as a function of the single exposure efficiencies
def detectionProb(efficiency, trigger=1): if trigger > 1.: raise ValueError('Trigger > 1 not implemented yet\n') q = 1.0 - np.asarray(efficiency) # probability of 0 detections logq = np.log(q) logpiq = logq.sum() piq = np.exp(logpiq) return 1.0 - piq
[ "def discoveryMetric(self, trigger=1):\n\tefficiency = self.lightcurve.DetectionEfficiency.astype(float)\n\tif trigger > 1.:\n raise ValueError('Trigger > 1 not implemented yet\\n')\n # probability of not being detected visit by visit\n\tq = 1.0 - np.asarray(efficiency)\n\n\n #print type(q)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a dictionary specifying the defaults for this form. This dictionary shall be used to inject the initial values for an Angular controller using the directive 'nginit={{thisform.get_initial_data|js|safe}}'.
def get_initial_data(self): data = {} for name, field in self.fields.items(): if hasattr(field, 'widget') and 'ng-model' in field.widget.attrs: data[name] = self.initial and self.initial.get(name) or field.initial return data
[ "def your_reservation_defaults(self, defaults):\n\n default_email = self.email()\n if default_email:\n defaults['email'] = self.email()\n\n data = self.additional_data()\n\n if not data:\n return defaults\n\n for form in data:\n if form in self.con...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determine the kind of input field and create a list of potential errors which may occur during validation of that field. This list is returned to be displayed in '$dirty' state if the field does not validate for that criteria.
def get_field_errors(self, bound_field): errors = super(NgFormValidationMixin, self).get_field_errors(bound_field) identifier = format_html('{0}.{1}', self.form_name, self.add_prefix(bound_field.name)) errors_function = '{0}_angular_errors'.format(bound_field.field.__class__.__name__) ...
[ "def full_clean(self, *args, **kwargs):\n super().full_clean(*args, **kwargs)\n for field in self.errors:\n if field != NON_FIELD_ERRORS:\n self.apply_widget_invalid_options(field)", "def validate(self):\n for name, field in self._get_fields().items():\n f...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a dictionary of all methods for the current View of this request, marked with the decorator. The return string can be used directly to initialize the AngularJS provider, such as ``djangoRMIProvider.configure({­% djng_current_rmi %­});``
def djng_current_rmi(context): return mark_safe(json.dumps(get_current_remote_methods(context['view'])))
[ "def _get_methods(self):\n\n return {\n 'debian_package_install': jinja_methods.debian_package_install,\n 'handle_repos': jinja_methods.handle_repos,\n }", "def _parse_methods(config):\n out = {\"views\": {}}\n for k, v in config.items():\n # if all upper case, the...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Build ModelForm from model
def get_form_class(self): return modelform_factory(self.model)
[ "def instantiate_form(self, model, *args, **kwargs) -> Form:\n return Form.instantiate(self=model, *args, **kwargs)", "def select2_modelform(\n model, attrs=None, form_class=es2_forms.FixedModelForm):\n classname = '%sForm' % model._meta.object_name\n meta = select2_modelform_meta(model, attrs...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Used when angular's query() method is called Build an array of all objects, return json response
def ng_query(self, request, *args, **kwargs): return self.build_json_response(self.get_queryset())
[ "def get_all_data():\n return jsonify(service.get_all_data())", "def ng_get(self, request, *args, **kwargs):\r\n return self.build_json_response(self.get_object())", "def toall_get(self, request):\n _view = _object_view(self, request)\n queried = ToAllChannelPostings(request.params.mixed()).quer...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Used when angular's get() method is called Returns a JSON response of a single object dictionary
def ng_get(self, request, *args, **kwargs): return self.build_json_response(self.get_object())
[ "def json_get(self, *args, **kwargs):\n return self._do_json_method(self.http_get, *args, **kwargs)", "def _ext_get(self, url, key=None, status=200):\n\n resp, body = self.get(url)\n body = json.loads(body)\n self.expected_success(status, resp.status)\n\n if not key:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Evaluate log density at th, which is (2,) or (n_samples, 2) np.array
def log_prob(self, th): if len(th.shape) == 1: th1, th2 = th[0], th[1] elif len(th.shape) == 2: th1, th2 = th[:,0], th[:,1] else: raise RuntimeError("th must be either (2,) or (n_samples, 2)") mask = ( (th1 >= -2.) * (th1 <= 2.) * (th2 >= -1 - th1) * (th2 >= th1 - 1) * (th2 <= ...
[ "def log_density_logistic(logalphas, y_sample, temp):\n exp_term = logalphas + y_sample * -temp\n log_prob = exp_term + np.log(temp) - 2. * tf.nn.softplus(exp_term)\n return log_prob", "def logpdf(self, x):\n reg = self(x)\n nelem = tf.cast(tf.size(x), x.dtype)\n logz = nelem * (-math.log(self.s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a tuple expected by Requests from file path
def file_entry(file_path: str) -> Tuple[str, Any, str]: file_name = os.path.split(file_path)[1] file_handler = open(file_path, "rb") content_type = "application/octet-stream" return (file_name, file_handler, content_type)
[ "def _get_data(self, path_to_file):\n READSTREAM = open(self.dir_path.joinpath(path_to_file), \"r\")\n FILE_CONTENTS = READSTREAM.read().split(\"\\n\")\n NAME = FILE_CONTENTS[0][FILE_CONTENTS[0].index(\":\") + 2 : -1]\n URL = FILE_CONTENTS[1][FILE_CONTENTS[1].index(\":\") + 2 : -1]\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns aStr cropped to maxLen if necessary. Cropped strings are returned with an ellipsis marker.
def makeEllipsis(aStr, maxLen=60): if len(aStr)>maxLen: return aStr[:maxLen-3]+"..." return aStr
[ "def makeLeftEllipsis(aStr, maxLen=60):\n\tif len(aStr)>maxLen:\n\t\treturn \"...\"+aStr[-maxLen+3:]\n\treturn aStr", "def ellipsize(text, max_length):\n # Convert input text to string, just in case\n text = str(text)\n return (text[: max_length - 3] + \"...\") if len(text) > max_length else text", "de...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns aStr shortened to maxLen by dropping prefixes if necessary. Cropped strings are returned with an ellipsis marker. >>> makeLeftEllipsis("0123456789"2, 11) '...23456789'
def makeLeftEllipsis(aStr, maxLen=60): if len(aStr)>maxLen: return "..."+aStr[-maxLen+3:] return aStr
[ "def makeEllipsis(aStr, maxLen=60):\n\tif len(aStr)>maxLen:\n\t\treturn aStr[:maxLen-3]+\"...\"\n\treturn aStr", "def ellipsis(s, maxlen=232):\n s = stringify(s)\n if len(s) > maxlen:\n return s[:maxlen - 3] + '...'\n else:\n return s\n\n # TODO: do we really want ... at end, or in middl...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns the file stem of a file path. The base name is what remains if you take the base name and split off extensions. The extension here starts with the last dot in the file name, except up to one of some common compression extensions (.gz, .xz, .bz2, .Z, .z) is stripped off the end if present before determining the ...
def getFileStem(fPath): for ext in [".gz", ".xz", ".bz2", ".Z", ".z"]: if fPath.endswith(ext): fPath = fPath[:-len(ext)] break return os.path.splitext(os.path.basename(fPath))[0]
[ "def get_stem(fp) -> str:\n return os.path.splitext(os.path.split(fp)[1])[0]", "def true_stem(path: Path) -> str:\n ts = path.stem\n while path.suffixes:\n ts = path.stem\n path = Path(ts)\n return ts", "def stem(self, name):\n\t\tif self.stemmer is False:\n\t\t\treturn name\n\t\tretur...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns a string containing a text representation of tabular data. All columns of data are simply stringified, then the longest member determines the width of the text column. The behaviour if data does not contain rows of equal length is unspecified; data must contain at least one row. If you have serialised the value...
def formatSimpleTable(data, stringify=True): if stringify: data = [[str(v) for v in row] for row in data] if not data: return "" colWidthes = [max(len(row[colInd]) for row in data) for colInd in range(len(data[0]))] fmtStr = " ".join("%%%ds"%w for w in colWidthes) table = "\n".join(fmtStr%tuple(row) for r...
[ "def _formatted_table(t):\n\n try:\n digit_padding = 0\n for row in t:\n for v in row:\n digit_padding = max(len(str(v)), digit_padding)\n out = \"\"\n for row in t:\n out += '|'\n row_string = ''\n for v in row:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns rest if fullPath has the form rootPath/rest and raises an exception otherwise. Pass liberalChars=False to make this raise a ValueError when URLdangerous characters (blanks, amperands, pluses, nonASCII, and similar) are present in the result. This is mainly for products.
def getRelativePath(fullPath, rootPath, liberalChars=True): if not fullPath.startswith(rootPath): raise ValueError( "Full path %s does not start with resource root %s"%(fullPath, rootPath)) res = fullPath[len(rootPath):].lstrip("/") if not liberalChars and not _SAFE_FILENAME.match(res): raise ValueError("File...
[ "def test_get_path_with_special_chars(self):\n\n self.assertEqual(\n jsonxs(self.d, 'feed.short\\.desc'),\n 'A feed'\n )", "def test_get_resource_full_url_slash_ending(self):\n base_url = \"https://example.com/\"\n resource_url = \"/static/img/image.png\"\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
joins relPath to rootPath and makes sure the result really is in rootPath.
def resolvePath(rootPath, relPath): relPath = relPath.lstrip("/") fullPath = os.path.realpath(os.path.join(rootPath, relPath)) if not fullPath.startswith(rootPath): raise ValueError( "Full path %s does not start with resource root %s"%(fullPath, rootPath)) if not os.path.exists(fullPath): raise ValueError( ...
[ "def safe_join(root, path): \n\n # prepending a '/' ensures '..' does not traverse past the root\n # of the path\n if not path.startswith('/'):\n path = '/' + path\n normpath = os.path.normpath(path)\n\n return root + normpath", "def get_verified_path(root_path, rel_path):\n normalized_ro...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns code with all whitespace from governingLine removed from every line and newIndent prepended to every line. governingLine lets you select a line different from the first one for the determination of the leading white space. Lines before that line are left alone. >>> fixIndentation(" foo\\n bar", "") 'foo\\nbar' ...
def fixIndentation(code, newIndent, governingLine=0): codeLines = [line for line in code.split("\n")] reserved, codeLines = codeLines[:governingLine], codeLines[governingLine:] while codeLines: if codeLines[0].strip(): firstIndent = re.match("^\s*", codeLines[0]).group() break else: reserved.append(code...
[ "def _indent_line(self, line, stripspace = ''):\r\n return re.sub(r\"^%s\" % stripspace, self.indentstring * self.indent, line)", "def fix_indentation(code, new_indents):\r\n min_indents = find_minimum_indents(code)\r\n return indent_lines(code, new_indents - min_indents)", "def fix_indents(self):\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns a name mapping dictionary from a list of assignments. This is the preferred form of communicating a mapping from external names to field names in records to macros in a string that contains
def parseAssignments(assignments): return dict([(lead, trail) for lead, trail in [litPair.split(":") for litPair in assignments.split()]])
[ "def collectAssignments(lines):\n assignments = dict()\n try:\n while True:\n name, value = catchAssignment(lines)\n assignments[name] = value\n except (TypeError, IndexError):\n return assignments", "def map_subm...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns the time angle (h m s.decimals) as a float in degrees. >>> "%3.8f"%hmsToDeg("22 23 23.3") '335.84708333'
def hmsToDeg(hms, sepChar=None): hms = hms.strip() try: if sepChar=="": parts = hms[:2], hms[2:4], hms[4:] else: parts = hms.split(sepChar) if len(parts)==3: hours, minutes, seconds = parts elif len(parts)==2: hours, minutes = parts seconds = 0 else: raise ValueError("Too many parts") ti...
[ "def heightToDeg(height):\n return ((height / 960) * 180) - 90", "def fracHoursToDeg(fracHours):\n\treturn float(fracHours)*360./24.", "def decimal_deg2dms_deg(decimal_deg):\n mnt, sec = divmod(decimal_deg * 3600,60)\n deg, mnt = divmod(mnt, 60)\n\n return deg, mnt, sec", "def dmsToDeg(dmsAngle,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns the degree minutes secondsspecified dmsAngle as a float in degrees. >>> "%3.8f"%dmsToDeg("45 30.6") '45.51000000'
def dmsToDeg(dmsAngle, sepChar=None): dmsAngle = dmsAngle.strip() sign = 1 if dmsAngle.startswith("+"): dmsAngle = dmsAngle[1:].strip() elif dmsAngle.startswith("-"): sign, dmsAngle = -1, dmsAngle[1:].strip() try: if sepChar=="": parts = dmsAngle[:2], dmsAngle[2:4], dmsAngle[4:] else: parts = dmsAngl...
[ "def dms_deg2decimal_deg(dms_deg):\n decimal_deg = float( dms_deg[0]) + float( dms_deg[1])/60 + float(dms_deg[2])/36000\n return dms_deg", "def dms_fractions_to_deg(gps_dms):\n DMS = namedtuple('DMS', ['deg', 'min', 'sec', 'hem'])\n FRAC = namedtuple('Time', ['num', 'den'])\n\n lat = DMS._make([FRA...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns the time angle fracHours given in decimal hours in degrees.
def fracHoursToDeg(fracHours): return float(fracHours)*360./24.
[ "def to_float_hours(hours,minutes,seconds):\n return hours+(minutes/60)+(seconds/3600)", "def HourAngle(solar_time):\n return solar_time*15 - 180", "def hour_angle(solar_time):\n ha = pi / 12 * (solar_time - 12)\n\n return ha", "def solar_hours(t):\n return t * 0.9972695663", "def hour_angle(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
converts a float angle in degrees to a sexagesimal string. >>> degToDms(0) '+0 00 00.00' >>> degToDms(0.25) '0 15 00.00' >>> degToDms(23.50, secondFracs=4) '23 30 00.0000'
def degToDms(deg, sepChar=" ", secondFracs=2): sign = '+' if deg<0: sign = "-" deg = -deg rest, degs = math.modf(deg) rest, minutes = math.modf(rest*60) if secondFracs==0: secondFracs = -1 return sepChar.join(["%s%d"%(sign, int(degs)), "%02d"%abs(int(minutes)), "%0*.*f"%(secondFracs+3, secondFracs, abs(r...
[ "def dms(angle):\n d,m,s = decimal_to_sexagesimal(angle)\n return \"%dd%dm%2.2f\" % (d,m,s)", "def convertToDMS(dec):\n\n if isinstance(dec, (float, int)):\n dec = Angle(degrees=dec)\n\n if isinstance(dec, str):\n return ''\n\n t = Angle.signed_dms(dec)\n sign = '+' if dec.degrees ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns an RFC2616 date string for UTC seconds since unix epoch.
def formatRFC2616Date(secs=None): if secs is None: secs = time.time() return emailutils.formatdate(secs, localtime=False, usegmt=True)
[ "def http_date(epoch_seconds=None):\n return formatdate(epoch_seconds, usegmt=True)", "def epoch2UTCstr(timestamp=time(), fmat=\"%Y-%m-%d %H:%M:%S\"):\n return strftime(fmat, gmtime(timestamp))", "def _utc_date(self):\n if self.date_stamp == '0':\n return '0'\n else:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns a datetime object for a ISO time literal. There's no real timezone support yet, but we accept and ignore various ways of specifying UTC. >>> parseISODT("19981214") datetime.datetime(1998, 12, 14, 0, 0)
def parseISODT(literal): # temporary hack while ESAVO registry is broken: literal = literal.rstrip("Z") mat = _isoDTRE.match(literal.strip()) if not mat: raise ValueError("Bad ISO datetime literal: %s"%literal) parts = mat.groupdict() if parts["hour"] is None: parts["hour"] = parts["minute"] = parts["seconds"...
[ "def parse_iso_datetime(dtstring, tzinfo=local_timezone):\n if dtstring[-1] != 'Z':\n raise UTCRequiredException()\n dt = datetime.datetime(*map(int, re.split('[^\\d]',dtstring)[:-1]), \n tzinfo=utc_timezone)\n return dt.astimezone(tzinfo).replace(tzinfo=None)", "def date...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns some ISO8601 representation of a datetime instance. The reason for preferring this function over a simple str is that datetime's default representation is too difficult for some other code (e.g., itself); hence, this code suppresses any microsecond part and always adds a Z (where strftime works, utils.isoTimest...
def formatISODT(dt): if dt is None: return None return dt.replace(microsecond=0, tzinfo=None).isoformat()+"Z"
[ "def get_datetime_iso_str(date_time_obj):\n\n try:\n datetime_ios_str = date_time_obj.isoformat()\n return datetime_ios_str\n except iso8601.ParseError:\n return None", "def isoformat(dt):\n # allow null timestamps to remain None without\n # having to check if ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns s with exactly one trailing slash.
def ensureOneSlash(s): return s.rstrip("/")+"/"
[ "def slashappend(s):\r\n if s and not s.endswith('/'):\r\n return s + '/'\r\n else:\r\n return s", "def fix_trailing_slashes(s):\n s = s.strip() # first remove spaces\n while s[-1] == '/':\n s = s.strip('/')\n return(s)", "def ends_slash(url):\n return url if url.endswith...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
r""" Calculate budget harmonized trajectory.
def budget(df, df_hist, harmonize_year="2015"): harmonize_year = int(harmonize_year) df = df.set_axis(df.columns.astype(int), axis="columns") df_hist = df_hist.set_axis(df_hist.columns.astype(int), axis="columns") data_years = df.columns hist_years = df_hist.columns years = data_years[data_y...
[ "def budget():\n pass", "def _distribute_budget(self, workflow_uuid: str, budget: float) -> None:\n\n workflow = self.workflows[workflow_uuid]\n eeoq = deepcopy(workflow.eeoq)\n\n while budget > 0 and eeoq:\n # Take first task from queue.\n task = eeoq.pop(0)\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns coefficient of variation of a Series.
def coeff_of_var(s): x = np.diff(s.values) return np.abs(np.std(x) / np.mean(x))
[ "def coefficient_variation(data):\n return numpy.std(data, ddof=1) / numpy.mean(data)", "def coefficient_variation(self):\n std, mean = self.std()\n coefficient_variation = std/mean\n print(f\"Coefficient of Variation is: {coefficient_variation}\")\n return coefficient_variation", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Method should return the bestCluster of the matrix passed in to the evaluate method in the validation class
def getBestCluster(): global bestCluster return bestCluster
[ "def testEvaluate(self):\n\n HierarchicalClustering.Clustering(typeVector=\"uni\", behaviour=\"b\")\n bestCluster = HierarchicalClustering.getBestCluster()\n\n import cPickle as pickle\n\n path = '../lists/uni-gram/Syscalls and Ioctls/Bit Vector'\n\n fileName = path + \"\\heights....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Method should set the bestCluster variable to the values passed in
def setBestCluster(cluster): global bestCluster bestCluster = cluster
[ "def getBestCluster():\r\n global bestCluster\r\n return bestCluster", "def find_best_cluster(X, y, model_names, param_1, param_2, param_3, param_4):\r\n\r\n best_result_1 = {'silhouette score': None, 'silhouette param': None, 'silhouette idx': None,\r\n 'purity': None, 'purity param'...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute the selfgenerated electric field.
def compute_electric_field(self): self.set_grid() rho = self.grid.distribute(self.bunch.positions) rho *= self.bunch.line_charge_density * 4 # unknown origin phi = self.solver.get_potential(rho, self.bunch.line_charge_density) Ex, Ey = self.grid.gradient(-phi) self.fields...
[ "def GenerateElectricField(self, affectedParticle):\n return self.electricField.GenerateField(affectedParticle)", "def compute_rf_field(self, r):\r\n\t\tE = np.zeros((3))\r\n\t\tfor nam, e in self.rf_electrode_list:\r\n\t\t\tE += e.compute_electric_field(r)\r\n\t\treturn E", "def electric_field(self, xyz...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Store bunch coordinates or statistics.
def store(self): store_moments = self.steps_performed % self.meas_every[0] == 0 store_coords = self.steps_performed % self.meas_every[1] == 0 if not (store_moments or store_coords): return Xp = np.copy(self.bunch.X[:, [1, 3]]) self.kick(+0.5 * self.ds) # sync position...
[ "def _write_data_to_buffer(self, bunch):\n\n ps_coords = {'x': None, 'xp': None, 'y': None,\n 'yp': None, 'z': None, 'dp': None}\n for coord in ps_coords:\n ps_coords[coord] = getattr(bunch, coord)\n if pm.device == 'GPU':\n stream = next(gpu_ut...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Send the chosen wild card color to the game logic.
def process_color(self, color): self.controller.game.receive_color(color) self.parent.parent.update_stat_frame() self.parent.parent.update_table_frame() self.parent.parent.end_turn()
[ "async def ask_for_new_color(self, game):\r\n\r\n # Check if the player is an ai\r\n if self.is_ai:\r\n await sleep(2)\r\n return choice(COLOR_CARDS)\r\n\r\n # The player is a real person\r\n else:\r\n\r\n # Send a message asking the player which card the...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update the current weight with the given weight delta
def update_weights(self, weight_delta): self._weights = math_util.vector_sum(self._weights, weight_delta)
[ "def update_weights(self):\n self.w = self.w + self.delta_w", "def update_weight(self, multiplier):\n self.weight = self.weight * multiplier", "def update_weight(dblW, dblLearningRate, dblInput, dblDelta):\n return(dblW + dblLearningRate * dblInput * dblDelta)", "def update_weights(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate the neuron response from the given input vector
def get_response(self, input_vector): if len(input_vector) == 0: raise Exception("Error: Empty input") sum_value = math_util.weighted_sum(input_vector, self._weights) # print(sum_value) return math_util.logistic_function(sum_value)
[ "def Response(self, input_vector):\n return self.output_function(np.dot(np.transpose(self.output_weight_matrix), \n np.concatenate((self.current_state, input_vector), axis=0)))", "def run(self, input_vector):\n \n # turning the input vector into a column vector\n input_vecto...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Draws the provided values of state on the canvas.
def draw_values_of_states(self, values): if self.update_animation: self.canvas.delete("values") for state, value in values.items(): row, col = state x1 = col * self.GRID_ROW_HEIGHT y1 = row * self.GRID_ROW_HEIGHT self.canva...
[ "def _render_state(self, state: np.ndarray, **kwargs) -> np.ndarray:\n pass", "def plot_state(self, **kwargs):\n raise NotImplementedError", "def set_state(canvas, state):\n for key, value in state.items():\n set_attribute(canvas, key, value)", "def draw_vals(self, dc):\n dc.Set...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Draws the provided values of action on the canvas.
def draw_values_of_action(self, values): if self.update_animation: self.canvas.delete("actions") for key, value in values.items(): state, action = key row, col = state x1 = col * self.GRID_ROW_HEIGHT y1 = row * self.GRID_RO...
[ "def draw_action(self, action):\n if action[\"type\"] == \"Point\":\n draw_point(action[\"params\"], self.__screen)\n if action[\"type\"] == \"Line\":\n draw_line(action[\"params\"], self.__screen)\n if action[\"type\"] == \"Text_box\":\n draw_textbox(action[\"p...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Draws arrows indicating the current policy for movement on the grid world.
def draw_policy(self, policy): if self.update_animation: self.canvas.delete("policy") for state, action in policy.items(): row, col = state if self.GRID_MAP[row][col] != "H" and self.GRID_MAP[row][col] != "G": x1 = (col * self.GRID_ROW...
[ "def draw_arrows(self):\n # We draw black arrows from each open or closed state to its predecessor.\n for r in range(self.rows):\n for c in range(self.columns):\n tail = head = cell = self.Cell(r, c)\n # If the current cell is an open state, or is a closed stat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Draws the provided softmax probabilities values on canvas
def draw_softmax_probabilities(self, values): if self.update_animation: self.canvas.delete("probabilities") for state, probs in values.items(): row, col = state x1 = col * self.GRID_ROW_HEIGHT y1 = row * self.GRID_ROW_HEIGHT ...
[ "def draw_policy(self, Policy):\r\n deterministic_policy = np.array([np.argmax(Policy[row,:]) for row in range(Policy.shape[0])])\r\n self.draw_deterministic_policy(deterministic_policy)", "def display_yolo(img, out, threshold):\n import numpy as np\n numClasses = 20\n anchors = [1.08, 1.19, 3.42, ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Takes in a formatted csv, parses concepts into lists, metadata into a dict, then returns a dataframe.
def initial_csv_wrangling(csv_file): df = pd.read_csv(csv_file) df = df.fillna('') columns = list(df.columns) # check that "url" column exists (required) if 'url' not in columns: raise Exception('Input csv file requires a "url" column, which does not seem to exist. Exiting.') # check if "pos_concepts"...
[ "def gen_concepts(self):\n with open(self.dataset_fp, 'r', encoding='utf-8') as f:\n reader = csv.DictReader(f, dialect=self.ConceptDatasetDialect)\n for line in reader:\n yield self.Concept('', line['Name'],\n line['Portuguese'], line['S...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
For each track, draw it on the poster.
def draw(self, dr: svgwrite.Drawing, size: XY, offset: XY): cell_size, (count_x, count_y) = utils.compute_grid(len(self.poster.tracks), size) spacing_x = 0 if count_x <= 1 else (size.x - cell_size * count_x) / (count_x - 1) spacing_y = 0 if count_y <= 1 else (size.y - cell_size * count_y) / (cou...
[ "def draw(self):\n self.surface.set_colorkey((0, 255, 0))\n self.surface.fill((0,255,0))\n\n for container in range(0, 2):\n if len(self.track_points[container]) > 0:\n last = self.track_points[container][len(self.track_points[container]) - 1]\n for x, y...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
If the provided HTTP request header contains a 'updatedSince' value, parses the value and returns it as a number of seconds since 1970.
def resolveUpdatedSinceArg(request): if 'updatedSince' in request.arguments: us = request.arguments['updatedSince'][0] # value space of US is an XML Schema DateTime #return time.strptime(us, "%Y-%m-%dT%H:%M:%S%Z") ma = dateTimeRE.match(us) m = ma.groupdict() year = 0 if m['year']: ...
[ "def _updated_to_seconds(updated):\n return (\n time.mktime(updated.timetuple()) - time.timezone +\n updated.microsecond / 1000000.0)", "def _parse_last_updated(self, doc):\n return datetime.now()", "def seconds_from_last_update(self):\n return (datetime.utcnow() - self.last_updat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate a 10x10km spatial grid for the chosen country.
def generate_grid(country): filename = 'national_outline_{}.shp'.format(country) country_outline = gpd.read_file(os.path.join(SHAPEFILE_DIR, filename)) country_outline.crs = "epsg:4326" country_outline = country_outline.to_crs("epsg:3857") xmin,ymin,xmax,ymax = country_outline.total_bounds #1...
[ "def create_grid():\n xmin, ymin, xmax, ymax = fn.open(path.join(DATA_DIR, SETTINGS['city_border']['preprocessed'])).bounds\n grid_width = 0.009039\n grid_height = 0.009039\n rows = (ymax - ymin) / grid_height\n cols = (xmax - xmin) / grid_width\n ring_xleft_origin = xmin\n ring_xright_origin =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Query the settlement layer to get an estimated population for each grid square.
def query_settlement_layer(grid): path = os.path.join(SHAPEFILE_DIR, f'{COUNTRY_ABBRV}.tif') grid['population'] = pd.DataFrame( zonal_stats(vectors=grid['geometry'], raster=path, stats='sum'))['sum'] grid = grid.replace([np.inf, -np.inf], np.nan) return grid
[ "def mine_all(self):\n\n # Query databse\n query_string = \"SELECT * from planets_in_range;\"\n self.conn_cur.execute(query_string)\n results = self.conn_cur.fetchall()\n\n # Check planets in range\n for ship in results:\n self.mine(str(ship[0]), str(ship[1]))", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
这里用 gevent 的 wsgi 来跑 tornado 写的 application.
def main(): application = app.get() wsgi_app = tornado.wsgi.WSGIAdapter(application) server = pywsgi.WSGIServer( (ADDRESS, PORT), wsgi_app ) server.serve_forever()
[ "def make_app():\n _LOGGER.info(\"Initializing Tornado Web App\")\n return tornado.web.Application([\n (r\"/prometheus\", MainHandler),\n (r\"/health\", HealthHandler),\n (r\"/\", MainHandler)\n ])", "def wsgi_app():\n return bottle.default_app()", "def application(environ, star...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Instantiate connections between populations
def make_connection(self, pre_pop, post_pop): #if pre_pop == None and post_pop == None: # pre_pop = self.S.filter_units(pre_pop_tags) # post_pop = self.S.filter_units(post_pop_tags) # iterate through connections for pre_tags, post_tags, pre_portID, post_portID in self.conn...
[ "def connections():\r\n\r\n individuals = range(1,variables.number_individuals+1)\r\n individuals = [each_individual for each_individual in individuals for i in range(variables.margin_neighbors)]\r\n individuals_to_connect = []\r\n\r\n #Construct a regular network\r\n for each_individual in range(0, ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
source and dest must be list type.
def __init__(self, source=None, dest=None): if source == None: self._source_list = [] else: self._source_list = source if dest == None: self._dest_list = [] else: self._dest_list = dest
[ "def VarListCopy(DestinationList, DesitnationStart, SourceList, SourceStart, NumToCopy=0):\n pass", "def copy(liste_source):\n #print \"dans copy\" #debug : affichage de contrÙle\n liste_a_retourner=[] #initialisation de la structure mÈmorisant la liste ‡ retourner\n #print \"initialisation effectue\"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
1.if src_repo does not exist or is not dir, return False; 2.if dst_repo absent, return True; 3.if dst_repo is a file, retrun False; 4.if src_repo is younger than dst_repo, return True; 5.anything else, it will return False.
def _check_youngest(self, src_repo, dst_repo): try: if not (os.path.exists(src_repo)): logging.warn('repository %s does not exist.' % src_repo) return False if not os.path.isdir(src_repo): logging.warn('repository %s should be directory.' %...
[ "def check_repo_dir():\n if input_cfg.workingdir != \"\" and os.path.isdir(input_cfg.workingdir) is not True:\n input_cfg.errmsg = \"repo directory does not exist: \" + input_cfg.workingdir", "def repository_exists(dirname):\n return os.path.isdir(dirname) \\\n or os.path.isdir(os.path.join...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
creates all existing lines in each polygon. Lines within polygon are also created to distinguish possible paths that lie on the edge of the polygon vs illegal paths through the polygon
def create_lines(polygons): lines = [] for polygon in polygons: curr_lines = [] for idx in range(0, len(polygon)): for idx_ in range(idx, len(polygon)): curr_line = Line(polygon[idx], polygon[idx_]) curr_lines.append(curr_line) lines.append(cur...
[ "def polygon_to_lines(geometry):\r\n line_list = []\r\n last_point = geometry.exterior.coords[0]\r\n for point in geometry.exterior.coords[1::]:\r\n if point == last_point:\r\n continue\r\n line_list.append(shapely.geometry.LineString([last_point, point]))\r\n last_point = p...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the SARIF Result representation of this diagnostic.
def sarif(self) -> sarif.Result: message = self.message or self.rule.message_default_template if self.additional_message: message_markdown = ( f"{message}\n\n## Additional Message:\n\n{self.additional_message}" ) else: message_markdown = messag...
[ "def result(self):\n if self.__json:\n return self.__json[\"result\"]\n else:\n return {}", "def getResult(self):\r\n return self._domInstance.getAttribute('result')", "def result(self):\n\n if len(self.values) != 1:\n raise ValueError(\"Could not par...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adds a location to the diagnostic.
def with_location(self: _Diagnostic, location: infra.Location) -> _Diagnostic: self.locations.append(location) return self
[ "def add_location(self, **kwargs):\n \n self.options.update(kwargs)\n self.options['action'] = 'locator.location.add'\n return self.call(self.options)", "def add_ue_location(self, add_ue_location):\n\n self._add_ue_location = add_ue_location", "def add_location(self, location:...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adds a thread flow location to the diagnostic.
def with_thread_flow_location( self: _Diagnostic, location: infra.ThreadFlowLocation ) -> _Diagnostic: self.thread_flow_locations.append(location) return self
[ "def with_location(self: _Diagnostic, location: infra.Location) -> _Diagnostic:\n self.locations.append(location)\n return self", "def add_ue_location(self, add_ue_location):\n\n self._add_ue_location = add_ue_location", "def add_location(self, **kwargs):\n \n self.options.upd...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adds a stack to the diagnostic.
def with_stack(self: _Diagnostic, stack: infra.Stack) -> _Diagnostic: self.stacks.append(stack) return self
[ "def add_stacks(self, stacks):\n if not isinstance(stacks, list):\n stacks = [stacks]\n\n self.stacks.extend(stacks)", "def stack_push(self, value):\n self.stack.append(value)", "def exp_push(self, what: Any) -> None:\n self.exp_stack.appendleft(what)", "def test_push(se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adds a graph to the diagnostic.
def with_graph(self: _Diagnostic, graph: infra.Graph) -> _Diagnostic: self.graphs.append(graph) return self
[ "def add_graph(self, graph):\n graph.init(self.event, self.time, self.data)\n self.graphs.append(graph)", "def add_graph(self, graph={}, name=\"main\"):\n if name in self.ssa.functions:\n print(\"Failed adding graph! Name already exist in the NNSSA network!\")\n else:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adds an additional message to the diagnostic.
def with_additional_message(self: _Diagnostic, message: str) -> _Diagnostic: if self.additional_message is None: self.additional_message = message else: self.additional_message = f"{self.additional_message}\n{message}" return self
[ "def add_warning(self, message):\n self.warnings.append(message)", "def add_validation_message(self, message):\n self.args[0].append(message)", "def _add_warning_message(self, message_list, message, severity):\n message_list.append({'message': message, 'severity': severity})", "def add_er...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adds the source exception to the diagnostic.
def with_source_exception(self: _Diagnostic, exception: Exception) -> _Diagnostic: self.source_exception = exception return self
[ "def Exception(self, source, e=None, quiet=False, stack_offset=0):\n if e is None:\n e = sys.exc_info()[1]\n self.Error(source, str(e), quiet=quiet, stack_offset=stack_offset+1)", "def error_source(self, error_source):\n\n self._error_source = error_source", "def _add_source(self, source: \"So...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Records the current Python call stack.
def record_python_call_stack(self, frames_to_skip: int) -> infra.Stack: frames_to_skip += 1 # Skip this function. stack = utils.python_call_stack(frames_to_skip=frames_to_skip) self.with_stack(stack) if len(stack.frames) > 0: self.with_location(stack.frames[0].location) ...
[ "def callstack_push(*frame):\n callstack_now().append(frame)", "def log_stack(self, signal, frame):\n ...", "def _debug_stack(self):\n debug(\"current stack: %s\" % self.calc.stack)", "def trace(self, *args, **kwargs):\n res = Stack(args, kwargs).trace(*self)\n Print(repr(res) +...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Records a python call as one thread flow step.
def record_python_call( self, fn: Callable, state: Mapping[str, str], message: Optional[str] = None, frames_to_skip: int = 0, ) -> infra.ThreadFlowLocation: frames_to_skip += 1 # Skip this function. stack = utils.python_call_stack(frames_to_skip=frames_to_ski...
[ "def callFromThread(self, func, *args):\n pass", "def process_thread(self):", "def callInStep(self, fn, *args):\n self._to_call_list.append((fn, args))", "def _RunAndRecord(self, func: Callable, *args: Any, **kwargs: Any) -> None:\n func(*args, **kwargs)\n with self._state_lock:\n sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the SARIF Log object.
def sarif_log(self) -> sarif.SarifLog: # type: ignore[name-defined] return sarif.SarifLog( version=sarif_version.SARIF_VERSION, schema_uri=sarif_version.SARIF_SCHEMA_LINK, runs=[self.sarif()], )
[ "def saslog(self):\n return self._log", "def getCurrentLog(self):\n return LogReader(self.path)", "def create_log(self):\n from settings import evidence_path\n test_case = self.__class__.__name__\n log_extension = '.log'\n if evidence_path is not None:\n log_pa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Pushes a diagnostic to the inflight diagnostics stack.
def push_inflight_diagnostic(self, diagnostic: Diagnostic) -> None: self._inflight_diagnostics.append(diagnostic)
[ "def append_diagnostic(self, diagnostic):\n self._diagnostics_list.append(diagnostic)", "def diagnostic(self, diagnostic):\n\n self._diagnostic = diagnostic", "def with_stack(self: _Diagnostic, stack: infra.Stack) -> _Diagnostic:\n self.stacks.append(stack)\n return self", "def dia...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Pops the last diagnostic from the inflight diagnostics stack.
def pop_inflight_diagnostic(self) -> Diagnostic: return self._inflight_diagnostics.pop()
[ "def back(self):\n if self.last is not None:\n self.stack.append(self.last)\n self.last = None\n else:\n print(\"No value was remove from the stack\")", "def discard(self,):\n self.stack.pop()", "def pop(self):\n value = self.stack[-1]\n del se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prints the diagnostics in a humanreadable format.
def pretty_print( self, verbose: Optional[bool] = None, log_level: Optional[infra.Level] = None ) -> None: if verbose is None: verbose = self.options.log_verbose if log_level is None: log_level = self.options.log_level formatter.pretty_print_title( ...
[ "def pretty_print(self, warnings=False):\n msg = []\n if (warnings) and (len(self.warnings) > 0):\n msg.append(u\"Warnings:\")\n for warning in self.warnings:\n msg.append(u\" %s\" % warning)\n if len(self.errors) > 0:\n msg.append(u\"Errors:\")\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find an item within this queue as indexed by its URI.
def __getitem__(self, uri): # The queue is empty, so return None if self.qsize() == 0: return # Iterate through the queue grabbing a worker, comparing its URI with the one provided # and putting it back if they do not match. Note that this implementation assumes that # all workers are equal and therefore ...
[ "def find(cls, item_id):\n app.logger.info(\"Processing lookup for id %s ...\", item_id)\n return cls.query.get(item_id)", "def get_item_with_href(self, href):\n for item in self.get_items():\n if item.get_name() == href:\n return item\n\n return None", "def...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Close the worker identified by the passed URI
def _close_worker(self, uri): if uri in self._running: # If worker is running, it can be accessed directly print('WARNING: Worker {} is shutting down while still processing a job'.format(uri)) proxy = self._running.pop(uri) self._shutdown_proxy(proxy) else: # Get proxy from the idle queue of workers ...
[ "def close(self):\n self.worker.close()\n if self._own_loop:\n self.loop.close()", "async def _close(self):\n for w in self.workers:\n w.cancel()\n\n await self.session.close()", "def _shutdown_proxy(self, proxy):\n\t\tif proxy is None:\n\t\t\tprint('Worker {} i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Shutdown a proxy and release the connection
def _shutdown_proxy(self, proxy): if proxy is None: print('Worker {} is not present in the pool'.format(uri)) return proxy.shutdown() proxy.close() del proxy
[ "def shutdown(opts):\n\tlog.debug(\"rapyutaio proxy shutdown() called...\")", "def release(self):\n if self.count == 1:\n reactor.callLater(PROXY_DISCONNECT_TIMEOUT, self.__close__)\n else:\n self.count -= 1", "def disconnect(self):\n if not self.linked:\n r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the environment config file.
def get_env_conf(self): conf = os.path.join(self.juju_home, 'environments.yaml') if not os.path.exists(conf): raise ConfigError("Juju environments.yaml not found %s" % conf) return conf
[ "def get_env_config() -> baenv.EnvConfig:\n import baenv\n\n return baenv.get_config()", "def get_config_path() -> Path:\n config = os.getenv('TOM_CONFIG', '')\n return Path(config)", "def get_cli_config_file():\n return get_cli_config_dir() + '/config.json'", "def get_config_file(self):\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
check if exception of type `exc` is raised with content
def assert_exc_contains(exc, content): try: yield except Exception as e: assert type(e) == exc message = e.args[0] # warning might not always work if isinstance(content, str): assert content in message else: assert all(m in message for m in conten...
[ "def isexception(x):\n return isinstance(x, Exception)", "def exc_match(self, exc_type, exception):\n return (isinstance(exc_type, exception) or\n issubclass(exception, exc_type))", "def _handle_exception(self, exc):\n if isinstance(exc, APIError):\n self.return_api_erro...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convenience method to return an Instagram object with the default credentials/setup
def default_client(): credential_manager = CredentialManager() current_directory = os.path.abspath(inspect.getfile(inspect.currentframe())) save_file_path = os.path.dirname(current_directory) insta_username, insta_password = credential_manager.get_account('Instagram') mon...
[ "def __init__(self, username = None, password = None):\n self.username = config['AUTH']['USERNAME']\n self.password = config['AUTH']['PASSWORD']\n self.login = config['URL']['LOGIN']\n self.nav_url = config['URL']['NAV']\n self.tag_url = config['URL']['TAGS']\n self.direct_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Delegate binary operations (+,,,/) performed on a workspace depending on type. Unwrap mantid workspace (_raw_ws), perform operation, then rewrap.
def _binary_op(self, other, algorithm, result_info, inplace, reverse): if isinstance(other, list): other = np.asarray(other) if isinstance(other, self.__class__): if _check_dimensions(self, other): inner_res = _do_binary_operation(algorithm, self._raw_ws, other._raw_ws, result_info, ...
[ "def _rewrite_default_unary(self, node: saldag.UnaryOpNode):\n\n # TODO: can there be a case when children have different stored_with sets?\n warnings.warn(\"hacky insert store ops\")\n in_stored_with = node.get_in_rel().stored_with\n out_stored_with = node.out_rel.stored_with\n i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
check if a workspace has the same number of bins as self for each dimension
def _check_dimensions(self, workspace_to_check): for i in range(self._raw_ws.getNumDims()): if self._raw_ws.getDimension(i).getNBins() != workspace_to_check._raw_ws.getDimension(i).getNBins(): return False return True
[ "def checkbinning(self,other):\n if(self.ndata != other.ndata):\n return 1\n if (np.fabs(self.svec.flatten()[0:self.ndata] - other.svec.flatten()[0:self.ndata]) > 2.0e-4).any():\n return 1\n return 0", "def _same_size(self, *arrs):\n counts = [np.size(ar) for ar in arrs]\n if(len(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Starts a loop that constantly polls for cards
def _poll_loop(self): nt = nfc.nfc_target() #res = nfc.nfc_initiator_poll_target(self.__device, self.__modulations, len(self.__modulations), 10, 2, # ctypes.byref(nt)) res = nfc.nfc_initiator_poll_target(self.__device, self.__modulations, len(self.__mod...
[ "async def game_loop(self, ctx):\n global ingame_channels\n game_msg = await self.bot.say('Starting blackjack in 15 seconds.\\n'\n 'Use `join` command to join the queue.'\n )\n await asyncio.sleep(15.0)\n await self.bot.delete_message(game_msg)\n while (self.queu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Selects a card after a failed authentication attempt (aborted communications) Returns the UID of the card selected
def select_card(self): nt = nfc.nfc_target() _ = nfc.nfc_initiator_select_passive_target(self.__device, self.__modulations[0], None, 0, ctypes.byref(nt)) uid = "".join([chr(nt.nti.nai.abtUid[i]) for i in range(nt.nti.nai.szUidLen)]) return uid
[ "def waitForCardPresent():\n while not card.uid:\n card.select()\n time.sleep(0.1)", "def select_card(self, cards):\n idx = -1 # should not be inital value\n while True:\n print(\"Please select a card by index:\")\n inpt = self.input(list(enumerate(cards)))\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets all the NFC device settings for reading from Mifare cards
def _setup_device(self): if nfc.nfc_device_set_property_bool(self.__device, nfc.NP_ACTIVATE_CRYPTO1, True) < 0: raise Exception("Error setting Crypto1 enabled") if nfc.nfc_device_set_property_bool(self.__device, nfc.NP_INFINITE_SELECT, False) < 0: raise Exception("Error setting S...
[ "def reset_to_factory(self):\n self._log_msg_start(\"Reset to factory settings\")\n # Order of execution is clear, save, load. This will copy the factory default\n # settings from ROM to flash, load from flash, and activate.\n device_mask_dict = dict(\n deviceDevBbr=1, # devS...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Authenticates to a particular block using a specified key
def _authenticate(self, block, uid, key = "\xff\xff\xff\xff\xff\xff", use_b_key = False): if nfc.nfc_device_set_property_bool(self.__device, nfc.NP_EASY_FRAMING, True) < 0: raise Exception("Error setting Easy Framing property") abttx = (ctypes.c_uint8 * 12)() abttx[0] = self.MC_AUTH_...
[ "def auth_and_read(self, block, uid, key = \"\\xff\\xff\\xff\\xff\\xff\\xff\"):\n # Reselect the card so that we can reauthenticate\n self.select_card()\n res = self._authenticate(block, uid, key)\n if res >= 0:\n return self._read_block(block)\n return ''", "def auth...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Authenticates and then reads a block Returns '' if the authentication failed
def auth_and_read(self, block, uid, key = "\xff\xff\xff\xff\xff\xff"): # Reselect the card so that we can reauthenticate self.select_card() res = self._authenticate(block, uid, key) if res >= 0: return self._read_block(block) return ''
[ "def auth_in_stage2(self,stanza):\r\n self.lock.acquire()\r\n try:\r\n if \"plain\" not in self.auth_methods and \"digest\" not in self.auth_methods:\r\n iq=stanza.make_error_response(\"not-allowed\")\r\n self.send(iq)\r\n return\r\n\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Authenticates and then writes a block
def auth_and_write(self, block, uid, data, key = "\xff\xff\xff\xff\xff\xff"): res = self._authenticate(block, uid, key) if res >= 0: return self.__write_block(block, data) self.select_card() return ""
[ "def commit_block(self, block):\n raise NotImplementedError('commit_block: Implementation of this method is required.')", "def __handleDownload(self,block):\n self.file.write(block)", "def auth_and_read(self, block, uid, key = \"\\xff\\xff\\xff\\xff\\xff\\xff\"):\n # Reselect the card so th...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Takes a uid, reads the card and return data for use in writing the card
def read_card(self, uid): key = "\xff\xff\xff\xff\xff\xff" print "Reading card", uid.encode("hex") self._card_uid = self.select_card() self._authenticate(0x00, uid, key) block = 0 for block in range(64): data = self.auth_and_read(block, uid, key) p...
[ "def write_card(self, uid, data):\n raise NotImplementedError", "def GetCard(UID):\n CardsDB = GetCardsDB()\n return copy.deepcopy(CardsDB.get(UID, None))", "def card():\n\n get_updatedby(usr)\n get_cardid(usr)\n newmode = None\n\n # We have an ID, is it a newbie or a renewal?\n #\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Accepts data of the recently read card with UID uid, and writes any changes necessary to it
def write_card(self, uid, data): raise NotImplementedError
[ "def read_card(self, uid):\n key = \"\\xff\\xff\\xff\\xff\\xff\\xff\"\n print \"Reading card\", uid.encode(\"hex\")\n self._card_uid = self.select_card()\n self._authenticate(0x00, uid, key)\n block = 0\n for block in range(64):\n data = self.auth_and_read(block,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Ask all websocket clients to refresh themselves. Requires admin access.
def refresh(): socketio.emit('refresh') return status()
[ "def __call__(self):\n self.update()\n return self.websockets", "def update_clients(self):\n pass", "def notify_web_clients(self, event):\n async def send_event(websocket):\n try:\n await websocket.send(str(event))\n except Exception as e:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Try to find and coerce value in a Flask request, returning an API error if missing or invalid.
def try_arg(request, arg, typ=None): if not request.values or arg not in request.values: error("Missing '{}' argument".format(arg)) if typ is None: return request.values[arg] try: return typ(request.values[arg]) except ValueError: error("Invalid '{}' argument".format(arg))
[ "async def _parse_and_validate_request(\n self, req: Request, request_type: dataclass\n ) -> Any:\n try:\n return validate_request_type(await req.json(), request_type)\n except Exception as e:\n logger.info(f\"Got invalid request type: {e}\")\n return Respons...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
checks whether the corners have been visited
def isGoalState(self, state): coordinates = state[0] edges = state[1] corners = self.corners TotalCorners = 4 if(len(edges) == TotalCorners): return True else: if coordinates in corners: if not coordinates in edges: ...
[ "def is_in_corners(move, corners):\n return move in corners", "def check_corners(self, vertices, corners):\n assert_allclose(vertices['ul'], corners[0])\n assert_allclose(vertices['ur'], corners[1])\n assert_allclose(vertices['lr'], corners[2])\n assert_allclose(vertices['ll'], corn...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }