query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Set next handler of the chain | def set_next(self, handler):
self.next = handler
return handler | [
"def set_handler(self, handler):\n self.next_handler = handler",
"def _handler_changed(self, handler):\n if self.next is not None:\n self.next.handler = handler",
"def handle_next(self, payload: str) -> None:\n data = json_loads(payload)\n data['hashes'] = [bytes.fromhex(h... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
G_in:入力関数のyデータ [1us刻み] G_input_x:入力関数のx軸(ms) GIRF:伝達関数のyデータ(complex) GIRF_x:周波数軸(kHz) | def GIRF_Interpolation(G_in,G_input_x, GIRF, GIRF_x):
"""
G_INを1us刻みでGIRFに合わせて延長
周波数分解能を逆数をとる
"""
"""
戻り値:
G_input_long: 入力関数をGIRF関数の逆数の時間Tまで延長したもの
G_input_x_long: ↑の時間軸(x軸) [ms]
GIRF_interp: GIRF関数の周波数軸を、入力関数の周波数軸に合わせてinterpolateしたもの
fG_input_x: ↑の周波数軸(x軸) [kHz]
... | [
"def Char_Gate(NV,res ,B_field=400):\n\n\n #data = np.loadtxt(\"NV_Sim_8.dat\") #Placeholder data to test the script\n #NV = np.vstack((data[:,3],data[:,4]))\n #physical constants\n gamma_c = 1.071e3 #g-factor for C13 in Hz/G\n #Model parameters\n omega_larmor = 2*np.pi*gamma_c*B_field\n tau_la... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Look for and return any unexplored point including the given seed. Calling map.find_above(MSS) after map.block_down(MSS) will thus find strict supersets of the MSS, as the MSS itself has been blocked. | def find_above(self, seed):
superset_exists = self.solver.solve((i + 1) for i in seed)
if superset_exists:
return self.get_seed()
else:
return None | [
"def solve_seed(seed: int):\n return solve(Position.deal(seed), GOAL)",
"def get_species_saddle_point(self):\n energies = [self.species[i].energy for i in range(self.n_points)]\n\n if any(energy is None for energy in energies):\n raise FitFailed\n\n # Peaks have lower energies b... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Maximize a given seed within the current set of constraints. The Boolean direction parameter specifies up (True) or down (False) | def maximize_seed(self, seed, direction):
while True:
comp = self.complement(seed)
x = self.solver.new_var() + 1
if direction:
# search for a solution w/ all of the current seed plus at
# least one from the current complement.
s... | [
"def minimax_agent(board, d, model):\n max = -9999998\n for move in list(board.legal_moves):\n board.push(chess.Move.from_uci(str(move)))\n value_i = -negaMax(board, d - 1, model)\n board.pop()\n if value_i > max:\n max = value_i\n best_move = move\n print(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the complement of a given set w.r.t. the set of mapped constraints. | def complement(self, aset):
return self.all_n.difference(aset) | [
"def get_complement(seta):\n complement_set = set()\n\n for elem in seta:\n new_elem_tuple = (elem[0], 1 - elem[1])\n complement_set.add(new_elem_tuple)\n\n return complement_set",
"def complement(self) -> 'RangeSet':\n return RangeSet(Range()) - self",
"def get_complement(seta):\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add a given clause to the Map solver. | def add_clause(self, clause):
self.solver.add_clause(clause)
if self.dump is not None:
self.dump.write(" ".join(map(str, clause)) + " 0\n") | [
"def add_clause(self, clause):\n return self._compile(clause)",
"def add_clause(self, clause):\n self.abstract_clauses.append(clause)",
"def add_clause(self, clause):\n # TODO: Do some simplifications, and check whether clause contains p\n # and -p at the same time.\n\n if not... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sends a POST request containing `data` to url. `auth` should be a tuple containing (username, password). | def post(url, data, auth=None, retries=10):
if not url.startswith('http://'):
url = 'http://' + url
request = urllib2.Request(url)
if auth:
request.add_header('Authorization', 'Basic %s' % b64encode('%s:%s' % auth))
params = urllib.urlencode(data)
response = urllib2.urlopen(request... | [
"async def post(self, url, data, header, auth: Union[BasicAuth, Dict], timeout: int) \\\n -> Union[ClientBackendResponse, Dict]:\n if isinstance(auth, Dict):\n login = auth.get(\"username\", \"\")\n password = auth.get(\"password\", \"\")\n auth_method = BasicAuth(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Collect characters while within a source record | def characters(self, content):
if self.in_source: self.chars += content | [
"def characters(self, data):\n pass",
"def extractCharacters(self):\n \n length, high=self.getSize() ##geting size of LineFrame object - high and length\n vHisto = self.vLinesHistogram()\n spaceLength = findSpaceLength(vHisto,high) ##finding of expected length of Space in line\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create connection line constraint between item's handle and the port. | def constraint(self, item, handle, glue_item):
start = MatrixProjection(self.start, glue_item.matrix_i2c)
end = MatrixProjection(self.end, glue_item.matrix_i2c)
point = MatrixProjection(handle.pos, item.matrix_i2c)
cx = EqualsConstraint(point.x, start.x)
cy = BetweenConstraint(p... | [
"def test_line_constraint(self):\n item = Item()\n pos = Variable(1), Variable(2)\n line = (Variable(3), Variable(4)), (Variable(5), Variable(6))\n item.constraint(line=(pos, line))\n self.assertEquals(1, len(item._constraints))\n\n c = item._constraints[0]\n self.as... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Draw lifeline. We always draw the lifeline's head. We only draw the lifeline's lifetime when the lifetime is visible. | def draw_lifeline(self, box, context, bounding_box):
cr = context.cairo
cr.rectangle(0, 0, self.width, self.height)
stroke(context)
if (
context.hovered
or context.focused
or context.dropzone
or self._lifetime.visible
):
... | [
"def draw_line():\n\n # Small Size Line\n glLineWidth(0.1)\n glColor3f(0.5, 1.0, 0.9)\n wid = 0\n while wid <= width:\n length = 0\n while length <= height:\n glBegin(GL_LINES)\n glVertex3f(0.0, length, 0.0)\n glVertex3f(wid, length, 0)\n glEn... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Load data from CSV files and return them as numpy arrays The use_labels parameter indicates whether one should read the first column (containing class labels). If false, return all 0s. | def load_data(filename, use_labels=True):
# load column 1 to 8 (ignore last one)
data = np.loadtxt(open( filename), delimiter=',',
usecols=range(1, 9), skiprows=1)
if use_labels:
labels = np.loadtxt(open( filename), delimiter=',',
usecols=[0], skipro... | [
"def load_labels():\n labels = pd.read_csv(PATH_DATA_RAW / LABEL_PATH)\n labels = labels.iloc[:, 1:4].to_numpy()\n return labels",
"def get_data(data_file,label_file):\r\n with open(data_file,\"r\") as data, open(label_file,\"r\") as label:\r\n data_reader = csv.reader(data)\r\n label_re... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a vector of predictions, save results in CSV format. | def save_results(predictions, filename):
with open(filename, 'w') as f:
f.write("id,ACTION\n")
for i, pred in enumerate(predictions):
f.write("%d,%f\n" % (i + 1, pred)) | [
"def export_predictions(self):\n with open('prediction/submission.csv', 'w', newline='') as csvfile:\n writer = csv.writer(csvfile, delimiter=',')\n for i in range(len(self.test_predictions)):\n writer.writerow([str(i) + \", \" + self.test_predictions[i]])",
"def write_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The following function is used to format the numbers. In the beginning "th, st, nd, rd" are removed | def clean_numbers(self, x):
# remove "th" after a number
matches = re.findall(r'\b\d+\s*th\b', x)
if len(matches) != 0:
x = re.sub(r'\s*th\b', " ", x)
# remove "rd" after a number
matches = re.findall(r'\b\d+\s*rd\b', x)
if len(matches) != 0:
x =... | [
"def format(number):\n return compact(number)",
"def remove_formatting(value):\n if isinstance(value, (int, float)):\n return value\n\n if not value:\n return 0\n\n formatting = [\",\", \"$\", \"ft\", \"yds\"]\n\n value = value.lower()\n for format_type in formatting:\n valu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function is used to replace "yr,yrs" by year and "hr,hrs" by hour. | def year_and_hour(self, text):
# Find matches for "yr", "yrs", "hr", "hrs"
matches_year = re.findall(r'\b\d+\s*yr\b', text)
matches_years = re.findall(r'\b\d+\s*yrs\b', text)
matches_hour = re.findall(r'\b\d+\s*hr\b', text)
matches_hours = re.findall(r'\b\d+\s*hrs\b', text)
... | [
"def replace_time(text, ori):\n r = ori\n if '**' in text:\n r = 'xxhour'\n else:\n try:\n # handle exceptions with custom rules\n f, s = text.split()\n s = 'am' if s[0] == 'a' else 'pm'\n l, r = f.split(':')\n if l == '' or l == '00':\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Performs an HTTP request set in 'method'. Returns requests object The method will try to catch some of the typical errors and gather error messages from Newrelic API Each known error has a corresponding exception. All exceptions are inherited from generic NewRelicException If HTTP return code is not known a generic New... | def _request(self, method, *args, **kwargs):
try:
r = getattr(requests, method)(*args, **kwargs)
except AttributeError:
raise NewRelicException(
'Method {} is unsupported by requests module'
.format(method)
)
except requests.exc... | [
"def _make_request(self):\n try:\n self.response = requests.request(\n method=self.method,\n url=self.url,\n params=self.params,\n data=self.data,\n )\n\n logger.debug(f\"Request URL: {self.response.url}\")\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Wrapper for requests GET method | def _get(self, *args, **kwargs):
return self._request('get', *args, **kwargs) | [
"def _get(self, *args, **kwargs):\n return self._request(requests.get, *args, **kwargs)",
"def _get(self, url, **data):\n return self._request('GET', url, **data)",
"def http_method_get():\n return 'GET'",
"def get(self, *path, **data):\n\t\treturn self.request('GET', *path, **data)",
"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Wrapper for requests POST method | def _post(self, *args, **kwargs):
return self._request('post', *args, **kwargs) | [
"def post_request(dummy_request):\n dummy_request.method = \"POST\"\n return dummy_request",
"def post_requests():",
"def http_method_post():\n return 'POST'",
"def http_post(self, **kwargs):\n return self.rabjcallable.post(**kwargs)",
"def test_post(self):\n return self.doRequest... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Wrapper for requests PUT method | def _put(self, *args, **kwargs):
return self._request('put', *args, **kwargs) | [
"def http_method_put():\n return 'PUT'",
"def do_PUT(self,):\n self.http_method = 'PUT'\n # Nothing to do for now.\n pass",
"def put(self, *args, **kw):\n kw['method'] = 'PUT'\n return self.open(*args, **kw)",
"def http_put(self, **kwargs):\n return self.rabjca... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Wrapper for requests DELETE method | def _delete(self, *args, **kwargs):
return self._request('delete', *args, **kwargs) | [
"def http_delete(self, **kwargs):\n return self.rabjcallable.delete(**kwargs)",
"def httpDelete(self, url='', data='', params={}, headers={}):\n\n return self.httpRequest('DELETE', url, data, params, headers)",
"def perform_delete_request():\n url = 'https://httpbin.org/delete'\n pass",
"a... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Load JSON as a protobuf (pb2) object. Any calls to load protobuf objects from JSON in this repository should be through this function. Returns `None` if the loading failed. | def open_pbobject(path, pb_class):
assert path.endswith(".json"), 'File extension for {} needs to be json.'.format(path)
if path.startswith('s3://'):
return open_remote_pb_object(path, pb_class)
assert os.path.exists(path), f'Path not found: {path}'
with open(path, 'r', encoding='UTF-8') as json... | [
"def _parse_json(\n protocol_contents: str, filename: str = None) -> JsonProtocol:\n protocol_json = json.loads(protocol_contents)\n version, validated = validate_json(protocol_json)\n return JsonProtocol(\n text=protocol_contents, filename=filename, contents=validated,\n schema_versio... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Like open_pboject but source can be a path or a bytestring | def parse_pbobject(source, pb_class):
if isinstance(source, str):
return open_pbobject(source, pb_class)
elif isinstance(source, bytes):
pb_object = pb_class()
pb_object.ParseFromString(source)
return pb_object
else:
logging.error(f'cannot parse type {type(source)}') | [
"def _open(self, source):\r\n if hasattr(source, 'read'):\r\n return source\r\n else:\r\n from io import StringIO\r\n return StringIO(source)",
"def load_object(source):\n print(\"Loading pickle object\")\n with open(source, 'rb') as s:\n return pickle.l... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Save protobuf (pb2) object to JSON file with our standard indent, key ordering, and other settings. Any calls to save protobuf objects to JSON in this repository should be through this function. | def save_pbobject_as_json(pb_object, save_path):
if os.path.isdir(save_path):
save_path = os.path.join(save_path, generate_uid_from_pbobject(pb_object) + ".json")
assert save_path.endswith(".json"), 'File extension for {} needs to be json.'.format(save_path)
with open(save_path, "w", encoding='UTF-... | [
"def _save(self):\n json_file = json.dumps(self.data, separators=(',', ':'))\n with open(self.path2save, \"w\") as outfile:\n outfile.write(json_file)\n outfile.close()",
"def save(self):\n tojson = {}\n for key in self.__objects:\n tojson[key] = self._... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Open ontology objects, first attempt to open V2 before trying V1. | def open_ontology_pbobject(ontology_file):
try:
ontology = parse_pbobject(ontology_file, OntologyV2Pb2)
if ontology is not None:
logging.info('Successfully loaded Ontology V2 spec.')
return ontology
except Exception:
logging.error('Failed to load ontology file wit... | [
"def test_read_owl2():\n t = Transformer()\n s = OwlSource(t)\n\n g = s.parse(\n os.path.join(RESOURCE_DIR, \"goslim_generic.owl\"),\n provided_by=\"GO slim generic\",\n knowledge_source=\"GO slim generic\",\n )\n nodes = {}\n edges = {}\n for rec in g:\n if rec:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Open feature ontology objects. | def open_feature_ontology_pbobject(ontology_file):
try:
ontology = open_pbobject(ontology_file, FeatureOntologyPb2)
if ontology is not None:
logging.info('Successfully loaded FeatureOntology spec.')
return ontology
except Exception:
logging.error('Failed to load o... | [
"def openTypeFeatures(self, features):\n #raise NotImplementedError",
"def import_from_file(self):\n\n onto_path.append(self.config.ontology_file)\n\n self.ontology = get_ontology(\"file://\" + self.config.ontology_file).load()\n\n with self.ontology:\n\n # Redefine relevant... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
From a list of 'scene.json' and/or 'scene_.json' paths in s3, return a Scene object for the one with the latest timestamp. | def get_latest_scene(s3_scene_jsons):
# Fetch all 'scene*.json' files and load Scenes
scenes = [open_remote_pb_object(scene_json, Scene) for scene_json in s3_scene_jsons]
# Find Scene with latest creation timestamp
creation_ts = [_s.creation_date.ToMicroseconds() for _s in scenes]
index = creation_... | [
"def get_latest_year_month_day_prefix(s3_path):\n latest = date.min\n keys = get_contents_of_directory(s3_path)\n\n for key in keys:\n search = re.search(r'.*year=(\\d{4}).*month=(\\d{2}).*day=(\\d{2})', key)\n if search:\n year, month, day = search.groups()\n bucket_dat... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
It builds the configuration space with the needed hyperparameters. It is easily possible to implement different types of hyperparameters. Beside floathyperparameters on a log scale, it is also able to handle categorical input parameter. | def get_configspace():
cs = CS.ConfigurationSpace()
# Learning rate hyperparameter
lr = CSH.UniformFloatHyperparameter('lr', lower=1e-6, upper=1e-1, default_value='1e-2', log=True)
# Stochastic gradient descent momentum as parameter.
sgd_momentum = CSH.Unifo... | [
"def get_configspace():\r\n cs = CS.ConfigurationSpace()\r\n\r\n lr = CSH.UniformFloatHyperparameter('lr', lower=1e-6, upper=1e-1, default_value='1e-2', log=True)\r\n\r\n # For demonstration purposes, we add different optimizers as categorical hyperparameters.\r\n # To sh... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method computes lookup tables of the cumulative ``galprop`` PDF defined by ``input_galaxy_table``. | def build_one_point_lookup_table(self, **kwargs):
galaxy_table = kwargs['input_galaxy_table']
prim_galprop_bins = kwargs['prim_galprop_bins']
self.one_point_lookup_table = np.zeros(
len(prim_galprop_bins)+1, dtype=object)
binned_prim_galprop = np.digitize(
galax... | [
"def _process_distribute_lookuptable(self, param_grads):\n from paddle.distributed.distribute_lookup_table import (\n find_distributed_lookup_table,\n )\n\n program = framework.default_main_program()\n global_block = framework.default_main_program().global_block()\n tab... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method creates ``self.param_dict`` regulating the strength of the correlation between sec_haloprop and galprop at each value of prim_galprop. | def _build_param_dict(self, **kwargs):
if 'correlation_strength' in kwargs.keys():
correlation_strength = kwargs['correlation_strength']
if custom_len(correlation_strength) > 1:
try:
self.correlation_strength_abcissa = kwargs['correlation_str... | [
"def _initialize_param_dict(self):\n self.param_dict={}\n for ipar, val in enumerate(self.ordinates):\n key = self._get_param_key(ipar)\n self.param_dict[key] = val",
"def _sample_params(self, trial: Trial) -> dict:\n # pseudocode\n # . hyparams = dict loop self.p... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method uses the current values in the param_dict to update the strength of the correlation between sec_haloprop and galprop at each value of prim_galprop. | def _set_correlation_strength(self):
if hasattr(self, 'correlation_strength_abcissa'):
abcissa = self.correlation_strength_abcissa
ordinates = [self.param_dict['correlation_param'+str(i+1)] for i in range(len(abcissa))]
correlation_strength_spline = model_helpers.custom_spli... | [
"def _update_pars(self, p):\n self._prevalence = p\n self._beta_p = self.rng.normal()\n\n self.cl.prevalence = p\n self.cl._beta_p = self._beta_p",
"def parameters_update(self, learning_rate):\n for i in range(1, self.L):\n #print('dW' + str(i))\n #print(se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method calls ``new_haloprop_func_dict`` to create new halo properties as columns to the mock catalog, if applicable. | def add_new_haloprops(self, galaxy_table):
if hasattr(self, 'new_haloprop_func_dict'):
d = self.new_haloprop_func_dict
for key, func in d.iteritems():
if key not in galaxy_table.keys():
galaxy_table[key] = func(galaxy_table=galaxy_table) | [
"def test_make_hmp(self):\n table_factory = DataTableFactory(PACKET_DIR)\n table_factory.hmp()",
"def _parse_constructor_kwargs(self, **kwargs):\n\n try:\n halo_id = np.array(kwargs['halo_id'])\n assert type(halo_id) is np.ndarray\n Nhalos = custom_len(halo_id... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Currently not implemented First print returns date of modifications to the video file Second print prints date of Creation of the video file, literally time when it was written to folder | def creation_date_video(path_to_file):
print("Last modified: %s" % time.ctime(os.path.getmtime(path_to_file)))
print("Created: %s" % time.ctime(os.path.getctime(path_to_file)))
# return os.path.getctime(path_to_file) | [
"def add_timestamps(dir_video):\n print(\"Adding creation dates to file names\")\n os.chdir(dir_video)\n # get only top level dir info\n dir_data_video_files = next(os.walk(dir_video))\n list_video_files = dir_data_video_files[2] # get file list\n for f_name in list_video_files:\n if GOPRO... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Actions for Diffrn objects. | def action_diffrn(obj: Diffrn, thread: QtCore.QThread):
w_actions = []
f_setup = obj.is_attribute("setup")
f_diffrn_radiation = obj.is_attribute("diffrn_radiation")
f_diffrn_orient_matrix = obj.is_attribute("diffrn_orient_matrix")
f_diffrn_refln = obj.is_attribute("diffrn_refln")
f_phase = obj.... | [
"def diff(self, **kargs):\n refs, count, objs = self.collect() ## refs contains the list of ALL objects\n \n ## Which refs have disappeared since call to start() (these are only displayed once, then forgotten.)\n delRefs = {}\n for i in list(self.startRefs.keys()):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method to scan product. Adds the product order to the list of orders. | def scan(self, product_code):
self.order.add_product(product_code) | [
"def add_product(self, product):\n self.products.append(product)",
"def add(self, product):\n pass",
"def add_product(self, product):\n return self._inventory.append(product)",
"def orderWatch(self, order):\r\n\t\tself.orders.append(order)",
"def process_orders(self, file_name: str) -> ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Attribute which calculates the total amount on the order after deducting discounts. | def total(self):
total_price = self.get_total_amount()
discounts = self.get_total_discount()
return total_price - discounts | [
"def total_order_discounts(order):\n total_discounts = D('0.0')\n\n discounts = order.basket_discounts\n\n for discount in discounts:\n total_discounts += discount.amount\n\n return total_discounts",
"def discount_amount(self):\r\n customer = self.records.find_customers(str(self.__custom... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculates total discount applicable on this order. | def get_total_discount(self):
total_discount = 0.00
for promotion in self.pricing_rules:
discount = promotion.get_discount(self.order)
total_discount += discount
return total_discount | [
"def discount_amount(self):\r\n customer = self.records.find_customers(str(self.__customer).strip())\r\n order_value = self.order_value\r\n discount = customer.get_discount(order_value)\r\n return discount",
"def calculate_total(self):\n if self.total_price == 0:\n fo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return total but in a pretty format with Euro sign. | def get_total_display(self):
total = self.total
return '%.2f\N{euro sign}' % total | [
"def formatted_price(self) -> str:\n return fmt_money(self.price)",
"def display_price(self):\n return '$ '+str(self.price)",
"def total_str(self, total):\n return \"{:>{}} {:{}.2f}\".format(\n \"Total:\", self._an + self._ac + self._ap + 2,\n total, self._ast)",
"de... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
MessagingCampaign a model defined in Swagger | def __init__(self):
self.swagger_types = {
'id': 'str',
'name': 'str',
'date_created': 'datetime',
'date_modified': 'datetime',
'version': 'int',
'division': 'DomainEntityRef',
'campaign_status': 'str',
'callable_tim... | [
"def _measurement_campaign():\n return {\n 'type' : 'class',\n 'name' : 'measurement_campaign',\n 'base' : 'activity.activity',\n 'is_abstract' : False,\n 'doc' : None,\n 'properties' : [\n # todo - clarify type\n ('duration', 'int', '1.1', None),\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the date_created of this MessagingCampaign. | def date_created(self, date_created):
self._date_created = date_created | [
"def date_created(self, date_created: datetime):\n\n self._date_created = date_created",
"def date_created(self, date_created):\n\n self._date_created = date_created",
"def datecreated(self, datecreated):\n\n self._datecreated = datecreated",
"def created_date(self, created_date):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the date_modified of this MessagingCampaign. | def date_modified(self):
return self._date_modified | [
"def date_modified(self) -> datetime:\n return self._date_modified",
"def modified_date(self):\n return self._modified_date",
"def last_modified(self) -> datetime:\n return self._last_modified",
"def modification_date_time(self):\n return self._modification_date_time",
"def date_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the date_modified of this MessagingCampaign. | def date_modified(self, date_modified):
self._date_modified = date_modified | [
"def date_modified(self, date_modified):\n\n self._date_modified = date_modified",
"def modified_date(self, modified_date):\n \n self._modified_date = modified_date",
"def modified_date(self, modified_date):\n\n self._modified_date = modified_date",
"def last_modified_date(self, la... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the version of this MessagingCampaign. Required for updates, must match the version number of the most recent update | def version(self, version):
self._version = version | [
"def version(self, version):\n self._version = version",
"def set_version(self, version: str) -> None:\n if self.current_version == version:\n return\n self.current_version = version\n self._del_cached_property(\"version\")",
"def version(self, version):\n\n self._v... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the division of this MessagingCampaign. The division this entity belongs to. | def division(self):
return self._division | [
"def get_group(self):\n return self._group",
"def get_division(id_, cache_time=5):\n s = session(cache_time)\n res = s.get(f'{BASE_URL}/division?id={id_}')\n return check_network_response(res)",
"def get_sent_folder(self):\n try:\n return self.get_sent_folders()[0]\n exc... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the division of this MessagingCampaign. The division this entity belongs to. | def division(self, division):
self._division = division | [
"def division(self, division):\n\n self._division = division",
"def setSyncDiv(self, syncDivider):\n self._settings['syncDivider'] = syncDivider\n self._api.setSyncDiv(syncDivider)",
"def set_divide(self, a_divide):\n self.set_parameter('divide', a_divide)\n return self",
"d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the campaign_status of this MessagingCampaign. The current status of the messaging campaign. A messaging campaign may be turned 'on' or 'off'. | def campaign_status(self):
return self._campaign_status | [
"def get_status(self):\n return self._status",
"def campaign_status(self, campaign_status):\n allowed_values = [\"on\", \"stopping\", \"off\", \"complete\", \"invalid\"]\n if campaign_status.lower() not in map(str.lower, allowed_values):\n # print(\"Invalid value for campaign_statu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the campaign_status of this MessagingCampaign. The current status of the messaging campaign. A messaging campaign may be turned 'on' or 'off'. | def campaign_status(self, campaign_status):
allowed_values = ["on", "stopping", "off", "complete", "invalid"]
if campaign_status.lower() not in map(str.lower, allowed_values):
# print("Invalid value for campaign_status -> " + campaign_status)
self._campaign_status = "outdated_sdk... | [
"def campaign_status(self, campaign_status):\n\n self._campaign_status = campaign_status",
"def campaign_status(self):\n return self._campaign_status",
"def set_status(self, status):\n self.status = status\n self.save()",
"def set_status(self, status: str) -> None:\n\n try:\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the callable_time_set of this MessagingCampaign. The callable time set for this messaging campaign. | def callable_time_set(self):
return self._callable_time_set | [
"def callable_time_set(self, callable_time_set):\n \n self._callable_time_set = callable_time_set",
"def getScheduleOnset(self):\n return DPxGetMicSchedOnset()",
"def schedule_times(self) -> Optional[Sequence[str]]:\n return pulumi.get(self, \"schedule_times\")",
"def getScheduleOn... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the callable_time_set of this MessagingCampaign. The callable time set for this messaging campaign. | def callable_time_set(self, callable_time_set):
self._callable_time_set = callable_time_set | [
"def callable_time_set(self):\n return self._callable_time_set",
"def setScheduleOnset(self, onset):\n DPxSetMicSchedOnset(onset)",
"def set_time(self, set_time):\n\n self._set_time = set_time",
"def setScheduleOnset(self, onset):\n DPxSetDinSchedOnset(onset)",
"def set_scheduled... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the contact_list of this MessagingCampaign. The contact list that this messaging campaign will send messages for. | def contact_list(self):
return self._contact_list | [
"def get_contacts(self):\n\n\t\treturn self.__contacts",
"def get_contacts_list(self):\n return [(id + 1, contact) for id, contact in enumerate(self.contact_list)]",
"def getContacts(self):\n return self._getContactsFromList(FORWARD_LIST)",
"def contact_lists(self):\n from hubspot3.contac... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the contact_list of this MessagingCampaign. The contact list that this messaging campaign will send messages for. | def contact_list(self, contact_list):
self._contact_list = contact_list | [
"def contacts(self, contacts):\n\n self._contacts = contacts",
"def contact_list(self):\n return self._contact_list",
"def update_contacts(self, contact_list):\n updated_contacts = 0\n request_list = list()\n\n # stale_contacts contains all old contacts at first, all current\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the dnc_lists of this MessagingCampaign. The dnc lists to check before sending a message for this messaging campaign. | def dnc_lists(self):
return self._dnc_lists | [
"def get_mailing_lists(self):\n return self.get(\"mailinglists\")",
"def get_dmarc_messages(self):\n messages = []\n try:\n if self.opt_use_ssl:\n self.server = poplib.POP3_SSL(self.opt_pop3_server)\n self.server.user(self.opt_global_account[\"username... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the dnc_lists of this MessagingCampaign. The dnc lists to check before sending a message for this messaging campaign. | def dnc_lists(self, dnc_lists):
self._dnc_lists = dnc_lists | [
"def dns_list(self, dns_list):\n self._dns_list = dns_list",
"def SetDomainsList(self, domainsList) :\n\t\t...",
"def communications_campaign_names(self, communications_campaign_names):\n\n self._communications_campaign_names = communications_campaign_names",
"def checklists(self, checklists):\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the always_running of this MessagingCampaign. Whether this messaging campaign is always running | def always_running(self):
return self._always_running | [
"def get_running(self):\n return self.running",
"def isScheduleRunning(self):\n if DPxIsMicSchedRunning() == 0:\n schedule_running = False\n else:\n schedule_running = True\n return schedule_running",
"def running(self):\n return self.scheduler.running",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the always_running of this MessagingCampaign. Whether this messaging campaign is always running | def always_running(self, always_running):
self._always_running = always_running | [
"def always_running(self):\n return self._always_running",
"def set_running(self, boolean):\n self.running = boolean",
"def always_on(self) -> bool:\n return pulumi.get(self, \"always_on\")",
"def always_run(self, always_run: bool = True) -> Self:\n self._always_run = always_run\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the contact_sorts of this MessagingCampaign. The order in which to sort contacts for dialing, based on up to four columns. | def contact_sorts(self):
return self._contact_sorts | [
"def contact_sorts(self, contact_sorts):\n \n self._contact_sorts = contact_sorts",
"def sortByDistance(self, contact_list):\n ExpensiveSort(contact_list, self.distance.to_contact).sort()",
"def get_contacts(self):\n contacts = Membership.objects.filter(entity = self, key_contact = T... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the contact_sorts of this MessagingCampaign. The order in which to sort contacts for dialing, based on up to four columns. | def contact_sorts(self, contact_sorts):
self._contact_sorts = contact_sorts | [
"def contact_sorts(self):\n return self._contact_sorts",
"def sort_fields(self, sort_fields):\n\n self._sort_fields = sort_fields",
"def sortByDistance(self, contact_list):\n ExpensiveSort(contact_list, self.distance.to_contact).sort()",
"def sort_orders(self, sort_orders):\n\n sel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the messages_per_minute of this MessagingCampaign. How many messages this messaging campaign will send per minute. | def messages_per_minute(self):
return self._messages_per_minute | [
"def messages_per_minute(self, messages_per_minute):\n \n self._messages_per_minute = messages_per_minute",
"def requests_per_minute(self) -> int:\n if len(self.requests) == 0 or self.total_time == 0:\n return 0\n return round(60 * len(self.requests) / self.total_time)",
"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the messages_per_minute of this MessagingCampaign. How many messages this messaging campaign will send per minute. | def messages_per_minute(self, messages_per_minute):
self._messages_per_minute = messages_per_minute | [
"def messages_per_minute(self):\n return self._messages_per_minute",
"def set_limit_per_second(self, rate_limit_per_second):\n pass",
"def minutes(self, minutes):\n\n self._minutes = minutes",
"def kills_per_min(self, kills_per_min):\n\n self._kills_per_min = kills_per_min",
"def... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the errors of this MessagingCampaign. A list of current error conditions associated with this messaging campaign. | def errors(self, errors):
self._errors = errors | [
"def errors(self, errors):\n\n self._errors = errors",
"def errors(self, errors):\n self._errors = errors",
"def validation_errors(self, validation_errors):\n\n self._validation_errors = validation_errors",
"def validation_errors(self, validation_errors):\n self._validation_errors ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the sms_config of this MessagingCampaign. Configuration for this messaging campaign to send SMS messages. | def sms_config(self):
return self._sms_config | [
"def sms_config(self, sms_config):\n \n self._sms_config = sms_config",
"def get_smtp_config(self):\n\t\treturn self.smtp_config",
"def sms(self):\n return self._sms",
"def get_smtp_config(self):\n if self.smtp:\n config = {}\n config['mailfrom'] = self.smtp.m... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the sms_config of this MessagingCampaign. Configuration for this messaging campaign to send SMS messages. | def sms_config(self, sms_config):
self._sms_config = sms_config | [
"def sms_config(self):\n return self._sms_config",
"def sms(self, sms):\n\n self._sms = sms",
"def sms_enabled(self, sms_enabled):\n\n self._sms_enabled = sms_enabled",
"def send_sms(self, sms):\n pass",
"def sms_phone_number(self, sms_phone_number):\n\n self._sms_phone_nu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Serializes C{result} to JSON and writes it to C{request}. | def _writeJSONResponse(result, request, code=CODE.SUCCESS, status=http.OK):
response = {
u'code': code.value,
u'result': result}
request.setHeader('content-type', 'application/json')
request.setResponseCode(status)
request.write(json.dumps(response))
request.finish() | [
"def _convert_to_JSON(result):\n response = make_response(json.dumps(result))\n response.headers['Access-Control-Allow-Origin'] = \"*\"\n response.mimetype = \"application/json\"\n return response",
"def make_response(request, result):\n response = request.response\n response.text = json.dumps(r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Maps a L{CODE} constant to a HTTP code. | def _mapErrorCodeToStatus(code):
if code == 103:
return http.NOT_FOUND
return http.INTERNAL_SERVER_ERROR | [
"def mapStatusCode(self, status_code):\n # Calibrator uses LSF status codes natively, so do nothing here.\n return status_code",
"def mapStatusCode(self, status_code):\n return self.STATUS_MAP[status_code]",
"def setResponseCode(code, message=None):",
"def http_status(code):\n return \... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Verify PayPal IPN data. | def verify(self, request):
paypalURL = 'https://www.sandbox.paypal.com/cgi-bin/webscr'
if not self.SANDBOX:
paypalURL = 'https://www.paypal.com/cgi-bin/webscr'
def _cb(response):
if response == 'INVALID':
raise PaypalError(
'IPN data i... | [
"def verify_ipn(data):\n data = dict(data)\n data['cmd'] = '_notify-validate'\n resp = requests.post(app.config['PAYPAL']['endpoint'], data=data)\n if resp.text == 'VERIFIED':\n return True\n return False",
"def test_paypal_email_check(self, mock_postback):\n mock_postback.return_valu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieve a list of recent donations. | def recent(self, limit):
def _cb(players, donations):
donators = []
for donation in donations:
player = players[donation.donator.steamID].copy()
player['date'] = donation.date.asPOSIXTimestamp()
player['amount'] = str(donation.amount)
... | [
"def donation(self):\n donations = self.donations.filter(expiration__gte=datetime.date.today()).order_by('-amount')\n return donations[0] if donations else None",
"def list_of_donations():\n try:\n database.connect()\n query = (Donors\n .select(Donors, Donations)\n .... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks that certain pipeline files are not modified from template output. Iterates through the pipeline's directory content and compares specified files against output from the template using the pipeline's metadata. File content should not be modified / missing. | def files_unchanged(self):
passed = []
failed = []
ignored = []
fixed = []
could_fix = False
# Check that we have the minimum required config
required_pipeline_config = {"manifest.name", "manifest.description", "manifest.author"}
missing_pipeline_config = required_pipeline_config.diffe... | [
"def validate_modified_files(self, modified_files, tag='master'): # noqa: C901\n click.secho(\"\\n================= Running validation on modified files =================\", fg='bright_cyan')\n _modified_files = set()\n for mod_file in modified_files:\n if isinstance(mod_file, tuple... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
добавляет файлы, необходимые для выполнения пакета принимает один параметр files полностью аналогичный одноименному параметру для AddJob | def AddFiles(self, files, retries=1):
JobPacketInfo(self.conn, self.id).AddFiles(files, retries) | [
"def add_files(self, files):\n pass",
"def associateFiles(self):\n files = WMJob.getFiles(self, type=\"id\")\n\n if len(files) > 0:\n addAction = self.daofactory(classname=\"Jobs.AddFiles\")\n addAction.execute(self[\"id\"], files, conn=self.getDBConn(),\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
возвращает объект для работы с очередью c именем qname (см. класс Queue) | def Queue(self, qname):
return Queue(self, qname) | [
"def get_queue(self):\n return Queue(self.name, connection=self.connection, serializer=self.serializer)",
"def get_queue(self, name):\n\t\treturn StyxQueue(self.pool, name)",
"def get(queue_name: str, **kwargs) -> Queue:\n return Queue(queue_name, **kwargs)",
"def __getitem__(self, name):\n r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
создает новый пакет с именем pckname priority приоритет выполнения пакета notify_emails список почтовых адресов, для уведомления об ошибках wait_tags список тэгов, установка которых является необходимым условием для начала выполнения пакета set_tag тэг, устанавливаемый по завершении работы пакеты kill_all_jobs_on_error... | def Packet(self, pckname, priority=MAX_PRIORITY, notify_emails=[], wait_tags=(), set_tag=None,
check_tag_uniqueness=False, resetable=True, kill_all_jobs_on_error=True, run_as=''):
try:
if isinstance(wait_tags, str):
raise AttributeError("wrong wait_tags attribute type"... | [
"def prioritize(self, model: str = None, priority: bool = True):\n priority = bool(priority)\n jobs = self._find_jobs(model)\n for job in jobs:\n job.priority = priority",
"def submit_unequal_priority_jobs(default_condor, path_to_sleep):\n cluster = default_condor.submit(\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
возвращает объект для работы с тэгом tagname (см. класс Tag) | def Tag(self, tagname):
return Tag(self, tagname) | [
"def lookup_tag(cls, name):\n tag = cls.query.filter_by(name=name).first()\n return tag",
"def __init__(self, tag):\r\n self.tag = tag.lower()",
"def tag(tag_name, parser):\n return parser >> (lambda x: Tag(tag_name, x))",
"def get(self, tagname):\n return self.tags.setdefault(t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
возвращает объект для манипуляций с пакетом (см. класс JobPacketInfo) принимает один параметр объект типа JobPacket | def PacketInfo(self, packet):
pck_id = packet.id if isinstance(packet, JobPacket) \
else packet if isinstance(packet, str) \
else None
if pck_id is None:
raise RuntimeError("can't create PacketInfo instance from %r" % packet)
return JobPacketInfo(self, pck_id) | [
"def Packet(self, pckname, priority=MAX_PRIORITY, notify_emails=[], wait_tags=(), set_tag=None,\n check_tag_uniqueness=False, resetable=True, kill_all_jobs_on_error=True, run_as=''):\n try:\n if isinstance(wait_tags, str):\n raise AttributeError(\"wrong wait_tags attri... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
generates initial hidden states for each agent | def generate_initial_hidden_states(self, batch_size, test_mode=False, caller=None):
# Set up hidden states for all levels - and propagate through the runner!
hidden_dict = {}
hidden_dict["level1"] = th.stack([Variable(th.zeros(batch_size, 1, self.args.agents_hidden_state_size)) for _
... | [
"def initial_agent_states(self) -> Dict[str, \"AgentState\"]:\n return self._initial_agent_states",
"def init_hidden_state(self, images):\n mean_images = images.mean(dim=1)\n h = self.init_h(mean_images) # (batch_size, decoder_dim)\n c = self.init_c(mean_images)\n return h, c",... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initializes and returns an LSL outlet | def initializeOutlet(interface):
info = StreamInfo('OpenBCI_EEG', 'EEG', 4, 256, 'float32', 'openbci12345')
outlet = StreamOutlet(info)
return outlet | [
"def connect_ls_to_lr(ls, lr, rp, rp_ip, rp_mac, db):\n ovn_nbctl(\"-- --id=@lrp create Logical_Router_port name=%s network=%s \"\n \"mac=%s -- add Logical_Router %s ports @lrp -- lsp-add %s \"\n \"rp-%s\" % (rp, rp_ip, rp_mac, lr, ls, rp), db)\n ovn_nbctl(\"set Logical-Switch-Port r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function recursively builds a string of manager to employee relationships starting from the managers that do not have managers. | def findHierarchy(self):
def __recursiveHelper(key_name, output, indent):
if key_name in self.relations:
for employee in self.relations[key_name].employees:
output += " " * indent + str(employee) +"\n"
# return __recursiveHelper(employee, out... | [
"def recursive_str(root, res, tab):\n for node in root.childs:\n if len(node.childs) == 0:\n res.append(tab + node.name)\n else:\n res.append(tab + '{')\n Tree.recursive_str(node, res, tab + '\\t')\n res.append(tab + '}')",
"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Extract zipfile to a directory if password is correct. | def extractfile(file, passwd):
try:
zipf = zipfile.ZipFile(file)
zipf.extractall(path=os.path.join(file[:-4]), pwd=str.encode(passwd))
print('Password: {}'.format(passwd))
except:
pass | [
"def extract_zipfile(filename, extract_dir):\n util.file.maybe_rmtree(extract_dir)\n shutil.unpack_archive(filename, extract_dir, 'zip')",
"def extract_zip(zipfile, output_dir):\n output_dir = Path(output_dir)\n if zipfile.testzip() is None:\n for m in zipfile.namelist():\n fldr, nam... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculate Profit of Order | def calculate_profit(self): | [
"def profit(self) -> float:\n total_profit = 0.\n for s in self.book:\n total_profit += s.profit_\n return total_profit",
"def profit(self):\n retail_value = 0\n wholesale_value = 0\n for bike in self.sold:\n retail_value += bike.total_cost() + (\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Removes a service from a list of existing services. | def RemoveServiceFromEndpoints(service_name, services):
new_services = []
if not isinstance(services, list):
return new_services
# TODO(user): Consider throwing an exception if the service is not
# already configured in the list of endpoints.
for service in services:
if not isinstance(service, dict) ... | [
"def DeleteServices(self):\n for service in self.services.values():\n service.Delete()",
"def remove_from_service(self):\n pass",
"def remove(self, service):\n os.remove(os.path.join(self.directory, service))",
"def _purge_deleted_services(self):\n base_url = self.bleemeo_base_url... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return distance of two keys in qwerty keyboard based on manhattan or euclidean distance. | def key_distance(self, x, y, type="manhattan"):
if type == "manhattan":
return self.manhattan_dist_matrix[self.keys.index(x), self.keys.index(y)]
elif type == "euclidean":
return self.euclidean_dist_matrix[self.keys.index(x), self.keys.index(y)] | [
"def get_distance(self, button1, button2):\n return int(math.sqrt(sum([(i - j)*(i - j) for i, j in zip(button1, button2)])))",
"def qwerty_distance():\n from collections import defaultdict\n import math\n R = defaultdict(dict)\n R['-']['-'] = 0\n zones = [\"dfghjk\", \"ertyuislcvbnm\", \"qwa... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a dataframe of distance matrix of x and y. Indexes are letters of x and columns are letters of y. | def distance_dataframe(self, x, y, keyboard_weight=None):
dist_matrix = self.distance_matrix(x, y, keyboard_weight)
dist_df = pd.DataFrame(dist_matrix, index=["", *list(x)],
columns=["", *list(y)])
return dist_df | [
"def make_dist_matrix(x, y):\r\n N = len(x)\r\n xx = np.vstack( (x,)*N )\r\n yy = np.vstack( (y,)*N )\r\n return np.sqrt( (xx - xx.T)**2 + (yy - yy.T)**2 )",
"def distance_2d(df1, df2, x, y):\n\n d1_coordinates = {'x': df1[x], 'y': df1[y]}\n df1_loc = pd.DataFrame(data=d1_coordinates)\n df1_l... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the token and dsn from a key Generate a simple SHA1 hash of the key key is a 64bits integer Token is a 32bits integer, dsn is a 64bits integer | def key2tokenAndDSN(self, key):
import binascii
import struct
import hashlib
self.keystr = struct.pack("!Q", key)
self.h = hashlib.sha1(self.keystr.rjust(8,'\00'))
self.shastr=self.h.digest() # binary
#shastr = struct.pack("!IIIII", *struct.unpack("@IIIII",shastr)) #to net
self.... | [
"def make_digest(key):\r\n return sha1(key.encode('utf-8')).hexdigest()",
"def fnv1(self, key):\n # hash = 0xff\n hash = 0xcbf29ce484222325\n for n in key.encode():\n # print(n)\n hash = hash ^ n\n hash = hash * 0x100000001b3\n\n # print(hash)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Identify distinct MPTCP Connections that reached Successful handshake Look for Ack packets with MPTCP option Header For each MPTCP connection report Receiver's token value which acts as the connectionID | def mptcp_connections(self, pkts):
count = 0
#MPTCP_Capable = 0x0
#MPTCP_CapableACK ---> successful handshake
print "======================================================================"
print "Successful Handshake --- Look for Ack packets with MPTCP option Header"
print """Token = connectionID = SHA1(key... | [
"def process_mptcp_pkt_from_client(ts_delta, acks, conn_acks, mptcp_connections, tcp, ip, saddr, daddr, sport, dport):\n dss, dack, dss_is_8_bytes = get_dss_and_data_ack(tcp)\n conn_id = acks[saddr, sport, daddr, dport][co.CONN_ID]\n flow_id = acks[saddr, sport, daddr, dport][co.FLOW_ID]\n if conn_acks[... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
return the current schema_org schema version | def get_schema_org_version():
return _get_schemaorg_version() | [
"def get_schemaorg_version():\n try:\n version = get_latest_schemaorg_version()\n except ValueError:\n version = SCHEMAORG_DEFAULT_VERSION\n return version",
"def schema_version(self):\n # return self._parsed[\"schemaVersion\"]\n # does not exist in manifest reference\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
get all classes and label them if they are referenced if include_ref is False, only "defined" classes are included. | def get_classes(self, include_ref=True):
defs = self._get_class_defs()
ans = {}
ans.update(defs)
if include_ref:
refs = self._get_class_refs()
ans.update(refs)
return list(ans.values()) | [
"def _find_all_referenced_classes(self):\n\n referenced_classes = set()\n searched_classes = set()\n\n search_pattern = \"import\\s+.+;\"\n extract_pattern = \"import\\s+([^;]+)\"\n white_list = [\"^import\\s+com.izforge.izpack.*;$\", \"^import\\s+java.*;$\"]\n\n izclass_co... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
return validation errors as a list of dictionaries | def get_validation_errors(self):
return [err.to_dict() for err in self._schema.validator.validation_errors] | [
"def compact_form_errors(form):\n errors = {}\n\n for name, validationerror in form.errors.as_data().items():\n errors[name] = [item.code for item in validationerror]\n\n return errors",
"def errors_as_dict(self):\n errors = []\n for e in self.errors:\n errors.append({\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Faster Wavelenght selector If passed lists it will return lists. If passed np arrays it will return arrays Fastest is using np.ndarrays fast_wav_selector ~10002000 quicker than wav_selector | def fast_wav_selector(wav, flux, wav_min, wav_max):
if isinstance(wav, list): # if passed lists
wav_sel = [value for value in wav if(wav_min < value < wav_max)]
flux_sel = [value[1] for value in zip(wav,flux) if(wav_min < value[0] < wav_max)]
elif isinstance(wav, np.ndarray):
# Super... | [
"def wav_selector(wav, flux, wav_min, wav_max, verbose=False):\n if isinstance(wav, list): # if passed lists\n wav_sel = [wav_val for wav_val in wav if (wav_min < wav_val < wav_max)]\n flux_sel = [flux_val for wav_val, flux_val in zip(wav,flux) if (wav_min < wav_val < wav_max)]\n elif isinst... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Downloads a FASTA file for the proteome by organism ID | def get_fasta_by_id(proteome_id, output_file):
taxid_pattern = re.compile('^\d{1,7}$')
# if not taxid_pattern.match(proteome_id): # fetch file from Uniprot
# raise ValueError(str(proteome_id) + ' is not a valid proteome identifier')
url = UNIPROT_BASE_URL + proteome_id
attempts = 0
while at... | [
"def download_refseq_reference(reference_id, download_path):\n\n def mash_reference_id_to_ncbi_ftp_path(reference_id):\n \"\"\"\n Args:\n query_id (str): Mash reference ID (column 1 of mash dist report)\n Returns:\n list: Directory names used to locate reference genome\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gapfill a model using probabilistic weights | def probabilistic_gapfill(model, universal_model, reaction_probabilities, clean_exchange_rxns=True, default_penalties=None, dm_rxns=False, ex_rxns=False, **solver_parameters):
universal_model = universal_model.copy()
model = clean_exchange_reactions(model) if clean_exchange_rxns else model.copy()
if default... | [
"def gap2d(_w_in):\n return nn.AdaptiveAvgPool2d((1, 1))",
"def gap2d(w_in):\n return nn.AdaptiveAvgPool2d((1,1))",
"def xgboost_weight(x, y, subprob_num, iter_num):\n data = x\n d_size = data.shape\n vim = np.zeros((d_size[1], subprob_num)).tolist() # vim: weights of Regulatory network\n\n f... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Exports the given reaction probabilities into a JSON formatted file, saved at filename | def export_json(rxn_probs, filename):
with open(filename, 'w') as f:
f.write(json.dumps(rxn_probs))
return filename | [
"def save(statistic_entries):\n with open('learn.json', 'w') as file:\n json.dump(statistic_entries, file, indent=2)",
"def save_outcomes():\n all_data = gen_outcomes()\n with open(\"result.json\", \"w\", encoding='utf-8') as jsonfile:\n json.dump(all_data, jsonfile, ensure_ascii=False)",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
return the probability of a given reaction | def get_probability(self, reaction):
return self.__getitem__(reaction) | [
"def probability(self):\n\t\ta0 = 0\n\t\ta = []\n\t\tfor reaction in self.reactions:\n\t\t\tfor colony in reaction.colonies:\n\t\t\t\tname = colony.name\n\t\t\t\ttry:\n\t\t\t\t\tnum = reaction.reactants[name]\n\t\t\t\t\tprob = choose(colony.size, num)*reaction.rate\n\t\t\t\t\ta.append(prob)\n\t\t\t\t\ta0 += prob\n\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Deserialize a ReactionProbabilities from a JSON file | def from_json_file(path):
with open(path, 'r') as f:
return ReactionProbabilities.from_json(f.read()) | [
"def load_priors(file_name):\n with open(file_name, \"r\") as fp:\n priors = json.load(fp)\n return priors",
"def read_classification_json(fn):\n with open(fn) as f:\n classification_data = json.load(f)\n f.close()\n \n return classification_data",
"def load_priors(self, ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Updates the Reaction Probabilities | def update(self, rxn_probs):
pass | [
"def update_probabilities(self):\n self.probabilities = self.pheromones**self.EXP_PH * self.mcv**self.EXP_MCV",
"def update(probabilities, one_gene, two_genes, have_trait, p):\n for person in probabilities:\n person_gene = get_gene(person, one_gene, two_genes)\n person_trait = get_trait(pe... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes a big limit as an integer and get all the prime numbers in that range, including the limit itself. Returns a numpy array of the primes. Fragmentation is an int that multiplies the sqrt of the limit to increase the fragment size. Bigger fragmentation consumes more memory and less time. Fragmentation limit = sqrt o... | def get_primes_in_big_limit(limit, fragmentation=1):
print("Getting primes...")
print("Fragmentation set to", fragmentation)
fragment_limit = int(np.sqrt(limit))
fragment_lowest = 0
fragment_highest = fragment_lowest + fragment_limit
primes_in_limit = np.array([], dtype=int)
while fragment_h... | [
"def get_primes_in(limit):\n range_limit = np.arange(limit)\n prime_mask = np.ones(limit, dtype=bool)\n prime_mask[0:2] = False\n for i in range_limit[:int(np.sqrt(limit))+1]:\n if prime_mask[i]:\n prime_mask[2*i::i] = False\n return range_limit[prime_mask]",
"def eratosthenes(lim... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes a limit as an integer and get all the prime numbers in that range, NOT including the limit itself. Returns a numpy array of the primes. | def get_primes_in(limit):
range_limit = np.arange(limit)
prime_mask = np.ones(limit, dtype=bool)
prime_mask[0:2] = False
for i in range_limit[:int(np.sqrt(limit))+1]:
if prime_mask[i]:
prime_mask[2*i::i] = False
return range_limit[prime_mask] | [
"def eratosthenes(limit):\n if isinstance(limit, (int, float)) and limit == int(limit):\n limit = int(limit)\n else:\n raise ValueError\n primes = []\n mask = [1]*(limit+1)\n for i in range(2, limit+1):\n if mask[i]:\n primes.append(i)\n for j in range(i*i, ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes fragment lowest and highest limits as an integers and get all the prime numbers in that range, NOT including the limit itself. Returns a numpy array of the primes. Needs the primes from the first fragment of the program as input. | def get_primes_in_fragment(fragment_lowest, fragment_highest,
primes_in_first_fragment):
fragment_range = np.arange(fragment_lowest, fragment_highest)
prime_mask = np.ones(len(fragment_range), dtype=bool)
for p in primes_in_first_fragment:
if fragment_lowest % p == 0:
... | [
"def get_primes_in_big_limit(limit, fragmentation=1):\n print(\"Getting primes...\")\n print(\"Fragmentation set to\", fragmentation)\n fragment_limit = int(np.sqrt(limit))\n fragment_lowest = 0\n fragment_highest = fragment_lowest + fragment_limit\n primes_in_limit = np.array([], dtype=int)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes a tuple where the first element is the dividend and the second element is the divisor. Both element sould be int. Performs a long division | def long_division(dividend_divisor_tuple, decimal_limit=5):
natural, decimal = [], []
dividend, divisor = dividend_divisor_tuple[0], dividend_divisor_tuple[1]
assert isinstance(dividend, int), "Dividend not int"
assert isinstance(divisor, int), "Divisor not int"
floor_div = dividend // divisor
... | [
"def div_mod(dividend: int, divisor: int) -> Tuple[int, int]:\n try:\n quotient = int(dividend) // int(divisor)\n remainder = int(dividend) % int(divisor)\n except (TypeError, ValueError, ZeroDivisionError):\n raise Exception(\n \"The dividend and divisor must be interger, \"\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get length of number in digits. | def get_number_length(number):
return len(str(number)) | [
"def numdigits(n):\n return len(str(n))",
"def number_of_digits(a: int) -> int:\n # suggested solution\n return len(str(a))",
"def get_length_of_number(self, number, precision):\n number_format = \"{:.\" + str(precision) + \"f}\"\n return len(number_format.format(number))",
"def count_d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
opens the chosen exceldocument and returns it as sheet | def get_excel(exceldocument):
sheet = xlrd.open_workbook(exceldocument).sheet_by_index(0)
return sheet | [
"def openExcelSheet(outputFileName):\n workbook = Workbook()\n worksheet = workbook.add_sheet(\"Sheet 1\")\n return workbook, worksheet",
"def open_excelr(self):\n try:\n data = xlrd.open_workbook(self.file)\n return data\n except Exception as e:\n print(str(e))\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
creates an xml structure with root and motherelements | def createxmlmall():
root = ET.Element("state")
model = ET.SubElement(root, "model")
model.text = r""
dataid = ET.SubElement(root, "dataids")
application = ET.SubElement(root, "application")
application.text = "SIBS Configurator"
safecookie = ET.SubElement(root, "safecookie")
... | [
"def createTree(self,root):\n if AMOEBA_SET_FUNDAMENTALS_DEBUG:\n print \"Experiment fundamentals, Write to XML.\"\n #Create the element tree.\n root.attrib['name']=str(self.name)\n root.attrib['reading']=str(self.reading)\n root.attrib['sync']=str(self.sync)\n r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a folder and saves xml tree in a specific path | def save_xml(tree, file_name, folder_name):
import os # ändrar plats för filer
os.chdir(folder_name)
tree.write(file_name) # Namnet på ny fil
| [
"def create_folder(self,path):\r\n path = utils.resourceref.remove_begin_slash(path)\r\n path = utils.resourceref.join_refs([self.get_path(), self.get_current_path(), path])\r\n if not os.path.exists(path):\r\n os.makedirs(path)",
"def create_folder(path):\n command = ['mkdir', ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculate the approximation of a contour shape to another shape with less number of vertices depending upon the precision we specify. | def __CalculateApproximation(self, contour):
epsilon = 0.1 * cv2.arcLength(contour, True)
return cv2.approxPolyDP(contour, epsilon, True) | [
"def flatten(self, precision=RELATIVE):\n if precision == RELATIVE:\n precision = RELATIVE_PRECISION\n contours = [[]]\n x0, y0 = None, None\n closeto = None\n for pt in self:\n if (pt.cmd == LINETO or pt.cmd == CURVETO) and x0 == y0 is None:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculate the contour area by the function cv2.contourArea() or from moments, M["m00"]. | def __CalculateArea(self, contour):
return cv2.contourArea(contour) | [
"def area(cnt):\n return cv2.contourArea(cnt)",
"def area(cnt):\n\treturn cv2.contourArea(cnt)",
"def findarea(src, n):\n temp1 = src\n #finding all contours in the image.\n contour, hierarchy = cv2.findContours(src,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)\n tmoment = cv2.moments(contour[n])\n s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |