query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Remove obsolete apicall records and insert into Analytics DB provided information about API call. Moved from AbstractService. Updated so that we do not have multiple records when performing forced updates (ie, the old record is not yet expired) now look for an existing record with the same parameters (I'm hoping the fa... | def insert_apicall(self, system, query, url, api, api_params, expire):
msg = 'query=%s, url=%s,' % (query, url)
msg += 'api=%s, args=%s, expire=%s' % (api, api_params, expire)
self.logger.debug(msg)
expire = expire_timestamp(expire)
query = encode_mongo_query(query)
qhash... | [
"def update_apicall(self, query, das_dict):\n msg = 'DBSAnalytics::update_apicall, query=%s, das_dict=%s'\\\n % (query, das_dict)\n self.logger.debug(msg)\n spec = {'apicall.qhash':genkey(encode_mongo_query(query))}\n record = self.col.find_one(spec)\n self.col.upda... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Update apicall record with provided DAS dict. Moved from AbstractService | def update_apicall(self, query, das_dict):
msg = 'DBSAnalytics::update_apicall, query=%s, das_dict=%s'\
% (query, das_dict)
self.logger.debug(msg)
spec = {'apicall.qhash':genkey(encode_mongo_query(query))}
record = self.col.find_one(spec)
self.col.update({'_id':Ob... | [
"def update_response(self,iSurveyID, aResponseData):",
"def _update(self):\n for key in self.keys:\n # self.show.<key> = namedtuple\n setattr(self._show\n , key\n , self._db[key]\n ) \n # self.pull.<key> = dict\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Update records for given system/query. | def update(self, system, query):
if isinstance(query, dict):
query = encode_mongo_query(query)
msg = 'system=%s, query=%s' % (system, query)
self.logger.debug(msg)
qhash = genkey(query)
if system:
cond = {'qhash':qhash, 'system':system}
else:
... | [
"def update(self, sql):",
"def update(self, q={}, values={}):\n self.store.update(q, values, multi=True, upsert=True)",
"def update_system_details(cursor, system_uid, data):\n if len(data) > 0:\n # Explicitly check all parameters to sanitize what\n # goes into the database\n param... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get popular queries based on provided spec, which can be in a form of time stamp range, etc. | def get_popular_queries(self, spec):
cond = {'counter':{'$exists':True}}
for row in self.col.find(fields=['qhash'], spec=cond).\
sort('counter', DESCENDING):
spec = {'qhash': row['qhash'], 'counter':{'$exists': False}}
for res in self.col.find(spec=spec):
... | [
"def queries_popular():\n query_queries_popular(current_app.extensions['sqlalchemy'].db)",
"def _fetch_by_query(self, query: str) -> Dict[str, Any]:\n resp = requests.get(\n self.url + \"/api/v1/query_range\",\n {\"query\": query, \"start\": self.start, \"end\": self.end, \"step\":... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieve API counter from analytics DB. User must supply API name and optional dict of parameters. | def api_counter(self, api, args=None):
cond = {'api.name': api}
if args:
for key, val in args.iteritems():
cond[key] = val
return self.col.find_one(cond, ['counter'])['counter'] | [
"async def stat(request: web.Request) -> web.json_response:\n\n data = dict(request.query)\n cleaned_data = ForStat().load(data)\n result = await Views(request).track_count(**cleaned_data)\n result_response = QueryString().dump(result, many=True)\n return web.json_response(data=re... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate a local_config.py with necessary settings | def create_local_config():
local_config_path = os.path.join(app.root_path, '../config/local_config.py')
if os.path.exists(local_config_path):
app.logger.info("local_config.py exists")
if not prompt_bool("Overwrite"):
return
config_items = {}
if prompt_bool("Generate SECRET_KE... | [
"def create_local_configs():\r\n print \"Local configuration files will be generated in %(build_path)s\" % env\r\n create_config_files()\r\n _interpolate_templates()",
"def generate_local_setup() -> List[str]:\n import inspect\n import re\n at_declare = re.compile(r'^@declare_config.*$', flags=r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
starts a beaver daemon for transmitting log files to the redis/logstash | def start_beaver():
pid_path = os.path.join(app.root_path, '../.beaver.pid')
if os.path.exists(pid_path):
with open(pid_path, 'r') as pid:
raise Exception("looks like another beaver process is running: %s" % pid.read())
config_path = os.path.join(app.root_path, '../config/be... | [
"def start_logging():\n stream.push_application()\n file.push_application()",
"def start_daemon():\n attach_madz()\n\n import madz.live_script as madz\n\n daemon = madz.Daemon(**madz_config)\n print(\"Configuring Server...\")\n daemon.configure()\n print(\"Starting Server\")\n daemon.st... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
stops a running beaver daemon identified by the pid in app.root_path/.beaver.pid | def stop_beaver():
import signal
pid_path = os.path.join(app.root_path, '../.beaver.pid')
if not os.path.exists(pid_path):
raise Exception("There doesn't appear to be a pid file for a running beaver instance")
pid = int(open(pid_path,'r').read())
os.kill(pid, signal.SIGTERM)
sleep(1)
... | [
"def start_beaver():\n pid_path = os.path.join(app.root_path, '../.beaver.pid')\n if os.path.exists(pid_path):\n with open(pid_path, 'r') as pid:\n raise Exception(\"looks like another beaver process is running: %s\" % pid.read())\n \n config_path = os.path.join(app.root_path, ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Write a TeX formated table of regions | def regionTable(net, regions=None, file=None):
file = file or sys.stdout
if regions is None:
regions = list(net.regionList)
ctx = dict(regions=[])
cs = net.particleStatistics()
annotate = False
for r in regions:
annotate |= r.annotation is not None
ctx['regions'].appen... | [
"def region_table_body(data):\n region_names = (\n 'Andaman and Nicobar Islands',\n 'Andhra Pradesh',\n 'Arunachal Pradesh',\n 'Assam',\n 'Bihar',\n 'Chandigarh',\n 'Chhattisgarh',\n 'Dadra and Nagar Haveli and Daman and Diu',\n 'Delhi',\n 'Go... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Write a TeX formated table of reactions | def reactionTable(net, rxns=None, file=None):
file = file or sys.stdout
if rxns is None:
rxns = list(net.reactionList)
ctx = dict(rxns=[])
annotate = False
for r in rxns:
annotate |= r.annotation is not None or r.rate.annotation is not None
ctx['rxns'].append(dict(annotation... | [
"def _reactions_table(reaction, tables):\n values = {\n 'reaction_id': reaction.reaction_id,\n 'serialized': reaction.SerializeToString().hex()\n }\n try:\n values['reaction_smiles'] = message_helpers.get_reaction_smiles(\n reaction)\n except ValueError:\n pass\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Pulls the stdout from the denormalized KVStore and returns it to the user. Returns Optional[str] The requested stdout, none if no stderr present. | def get_stdout(self) -> Optional[str]:
return self._kvstore_getter("stdout") | [
"def ReadStdout(self):\n return self._rpc.subprocess.ReadStdout(self._key)",
"def retrieve_stdout(self):\n\n return self.compl_proc.stdout.decode('UTF-8').rstrip()",
"def get_stdout(host: Hostname, output: pssh.output.HostOutput) -> Optional[str]:\n try:\n host_result = output[host]\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Pulls the stderr from the denormalized KVStore and returns it to the user. Returns Optional[str] The requested stderr, none if no stderr present. | def get_stderr(self) -> Optional[str]:
return self._kvstore_getter("stderr") | [
"def err(self):\n if os.path.exists(self.stderr.name):\n return read_file(self.stderr.name)\n return \"\"",
"def ReadStderr(self):\n return self._rpc.subprocess.ReadStderr(self._key)",
"def stderr_str(self):\n return self.stderr.decode(\"utf-8\")",
"def stderr(self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Pulls the stderr from the denormalized KVStore and returns it to the user. Returns Optional[qcel.models.ComputeError] The requested compute error, none if no error present. | def get_error(self) -> Optional[qcel.models.ComputeError]:
value = self._kvstore_getter("error")
if value:
return qcel.models.ComputeError(**value)
else:
return value | [
"def get_compute_unit_stderr(self, compute_unit_uid):\n return self._dbs.get_compute_unit_stderr(compute_unit_uid)",
"def err(self):\n if os.path.exists(self.stderr.name):\n return read_file(self.stderr.name)\n return \"\"",
"def ReadStderr(self):\n return self._rpc.subprocess... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a OptimizationInput schema. | def build_schema_input(self,
initial_molecule: 'Molecule',
qc_keywords: Optional['KeywordsSet']=None,
checks: bool=True) -> 'OptimizationInput':
if checks:
assert self.initial_molecule == initial_molecule.id
... | [
"def __init__(__self__, *,\n input_schema: 'outputs.ApplicationInputSchema',\n name_prefix: str,\n input_parallelism: Optional['outputs.ApplicationInputParallelism'] = None,\n input_processing_configuration: Optional['outputs.ApplicationInputProcessing... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The final energy of the geometry optimization. Returns float The optimization molecular energy. | def get_final_energy(self):
return self.energies[-1] | [
"def energy(self):\n return self.kinetic() + self.potential()",
"def generationEnergy(self):\n return self.energy + BULLETKEFACTOR * self.energy * self.relativevelocity ** 2",
"def getEnergy(self) -> float:\n ...",
"def _compute_kinetic_energy_cell(self):\n return self.b_masses_cel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a TextLocationRange corresponding to the range starting from the first single location (included) until the second single location (excluded). | def __sub__(self, other):
assert self.filename == other.filename
assert (self.line, self.column) <= (other.line, other.column)
return TextLocationRange(
self.filename, self.line, self.column,
other.line, other.column - 1,
) | [
"def location_range(start: int, end: int) -> Iterable[int]:\n step = 1\n if start > end:\n step = -1\n\n return range(start, end + step, step)",
"def between(text, begin, end):\n \n idx1 = text.find(begin)\n idx2 = text.find(end,idx1)\n \n if idx1 == -1 or idx2 == -1:\n retur... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Augment original data with corresponding transforms | def augment(self, aug_transform=None):
# Get a copy of the original data
data = copy.deepcopy(self.data)
if isinstance(aug_transform, list):
# For more than one transform, apply in sequence
for at in aug_transform:
data.extend([at(elm) for elm in ... | [
"def augmentation_transform(self, data):\n for aug in self.auglist:\n data = [ret for src in data for ret in aug(src)]\n \n return data",
"def transform(self, data):\n\t\t\n\t\tfor t in self.transformer_list:\n\t\t\tdata = t.transform(data)\n\t\t\t\n\t\treturn data",
"def _transf... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Implement FizzBuzz algorithm on a binary tree. | def FizzBuzzTree(tree):
if tree.left is not None:
FizzBuzzTree(tree.left)
if tree.val is not None:
# if so, the tree is empty
if tree.val % 15 == 0:
tree.val = 'FizzBuzz'
elif tree.val % 3 == 0 and tree.val % 5 != 0:
tree.val = 'Fizz'
elif tree.... | [
"def fizz_buzz(tree):\n def fizz_buzz_operation(node):\n # if node.val % 3 == 0 and node.val % 5 == 0:\n # node.val = 'fizzbuzz'\n # elif node.val % 3 == 0:\n # node.val = 'fizz'\n # elif node.val % 5 == 0:\n # node.val = 'buzz'\n # else:\n # ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Process CSV exports from Goodreads into JSON records. | def main(csv_path: str) -> None:
real_csv_path = Path(csv_path)
deviant_sorted_books = _process_csv_export(real_csv_path)
print(json.dumps([_.as_record() for _ in deviant_sorted_books])) | [
"def conversion(path, delim, json_filename):\n csv_input = []\n\n try:\n #Conversion csv to json\n with open(path,\"rt\") as csv_file:\n reader = csv.reader(csv_file, delimiter=delim, quoting=csv.QUOTE_ALL)\n fieldnames = next(reader)\n reader = csv.DictReader(cs... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculate corrections, i.e. build and solve Eq. (40) of [DillyNonlinearIRCorrections2023]_. Corrections are performed by grouping RDTs with common correctors. If possible, these are ordered from the highest order to lowest, to be able to update optics and include their feeddown. | def solve(rdt_maps: Sequence[RDTMap], optics_seq: Sequence[Optics],
accel: str, ips: Sequence[int], update_optics: bool, ignore_corrector_settings: bool,
feeddown: int, iterations: int, solver: str) -> Sequence[IRCorrector]:
all_correctors: Sequence[IRCorrector] = []
remaining_rdt_maps: Sequ... | [
"def computeCorrection(self):\n self.discrete_op.computeCorrection()",
"def doCorrections(self):\n\n self.Asave = self.difference + self.addOnCorrect\n self.corrected = self.Asave + self.buoyanCorrect\n\n if self.debug:\n print 'Buoyancy correction:'\n print self.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a new rdt_map with all rdt's that share correctors. This function is called in a whileloop, `so rdt_maps` is the `remaining_rdt_maps` from the last loop. The whileloop is interrupted when no remaining rdts are left. | def get_current_rdt_maps(rdt_maps: Sequence[RDTMap]) -> Tuple[Sequence[RDTMap], Sequence[RDTMap], Set[str]]:
n_maps = len(rdt_maps) # should be number of optics given
new_rdt_map = [{} for _ in range(n_maps)] # don't use [{}] * n_maps!!
# get the next set of correctors from the first rdt in the first
... | [
"def getResonanceAtomMap (namingSystemName, nmrConstraintStore, shiftListObj=None, **keywds):\n\n fixedResonances = nmrConstraintStore.sortedFixedResonances()\n resonanceToAtoms = DataFormat.getResonanceAtomMap(namingSystemName,\n fixedResonances, **keywds)\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the available correctors by checking for their presence in the optics. If the corrector is not found in this ip, the ip is skipped. If only one corrector (left or right) is present a warning is issued. If one corrector is present in only one optics (and not in the other) an Environment Error is raised. | def get_available_correctors(field_components: Set[str], accel: str, ip: int,
optics_seq: Sequence[Optics]) -> List[IRCorrector]:
correctors = []
for field_component in field_components:
corrector_not_found = []
corrector_names = []
for side in SIDES:
... | [
"def solve(rdt_maps: Sequence[RDTMap], optics_seq: Sequence[Optics],\n accel: str, ips: Sequence[int], update_optics: bool, ignore_corrector_settings: bool,\n feeddown: int, iterations: int, solver: str) -> Sequence[IRCorrector]:\n all_correctors: Sequence[IRCorrector] = []\n remaining_rdt_m... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Save original corrector values from optics (for later restoration, only if ``update_optics`` is ``False``) and if ``ignore_settings`` is ``True``, the corrector values in the optics are set to ``0``. Otherwise, the corrector object value is initialized with the value from the optics. An error is thrown if the optics di... | def init_corrector_and_optics_values(correctors: Sequence[IRCorrector], optics_seq: Sequence[Optics],
update_optics: bool, ignore_settings: bool) -> Dict[IRCorrector, Sequence[float]]:
saved_values = {}
for corrector in correctors:
values = [optic.twiss.loc[correcto... | [
"def saveSettings(self):\n cache_path = fullPath(self.dir_path, \"settings\")\n createFolder(cache_path)\n cache_file = fullPath(cache_path, \"calibration.info\")\n if self.calSettings is None:\n self.calSettings = {}\n\n if self.paramGrp.isChecked():\n self.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Builds equation system as in Eq. (40) of [DillyNonlinearIRCorrections2023]_ for a given ip for all given optics and error files (i.e. beams) and grouped RDTs, i.e. RDTs that share correctors. | def build_equation_system(rdt_maps: Sequence[RDTMap], correctors: Sequence[IRCorrector], ip: int,
optics_seq: Sequence[Optics], feeddown: int) -> Tuple[ArrayLike, ArrayLike]:
n_rdts = sum(len(rdt_map.keys()) for rdt_map, _ in zip(rdt_maps, optics_seq))
b_matrix = np.zeros([n_rdts, len(... | [
"def solve(rdt_maps: Sequence[RDTMap], optics_seq: Sequence[Optics],\n accel: str, ips: Sequence[int], update_optics: bool, ignore_corrector_settings: bool,\n feeddown: int, iterations: int, solver: str) -> Sequence[IRCorrector]:\n all_correctors: Sequence[IRCorrector] = []\n remaining_rdt_m... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculate the RDT integral for all elements of the IP. These are the entries on the rhs of Eq. (40) of [DillyNonlinearIRCorrections2023]_, including sign. | def get_elements_integral(rdt: RDT, ip: int, optics: Optics, feeddown: int) -> float:
integral = 0
lm, jk = rdt.l + rdt.m, rdt.j + rdt.k
twiss_df, errors_df = optics.twiss.copy(), optics.errors.copy() # copy just to be safe
# Integral on side ---
for side in SIDES:
LOG.debug(f" - Integral o... | [
"def get_integral(self):\r\n \r\n # unpack deque of tuples (time, value) into 2 lists [time], [values]\r\n time_val_list = list(self.integr_deque)\r\n unzip = list(zip(*time_val_list))\r\n actual_time_list = unzip[0]\r\n actual_val_list = unzip[1]\r\n \r\n # c... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Assigns calculated values to the correctors. | def _assign_corrector_values(correctors: Sequence[IRCorrector], values: Sequence):
for corrector, val in zip(correctors, values):
if len(val) > 1:
raise ValueError(f"Multiple Values for corrector {str(corrector)} found."
f" There should be only one.")
LOG.deb... | [
"def update_calculated_properties(self):\n self.value = self.calc_value()\n self.rarity_class = self.calc_rarity_class()\n self.save()",
"def update_calculated_properties(self) -> float:\n self.value = self.calc_value()\n self.is_jackpot = self.calc_is_jackpot()\n self.sa... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Updates the corrector strength values in the current optics. | def optics_update(correctors: Sequence[IRCorrector], optics_seq: Sequence[Optics]) -> None:
for optics in optics_seq:
for corrector in correctors:
sign = -1 if is_even(optics.beam) and is_anti_mirror_symmetric(corrector.strength_component) else 1
optics.twiss.loc[corrector.name, corr... | [
"def change_strength(self, amount):\n self.strength += amount\n self.strength = max([0, min([self.max_strength, self.strength])])",
"def currents_to_quad_strengths(self):\n quad_settings = np.zeros_like(self.quad_settings)\n for i_c, currents in enumerate(self.currents_optimised):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Log the correction initial and final value of this iteration. | def _log_correction(integral_before: np.array, integral_after: np.array, rdt_maps: Sequence[dict],
optics_seq: Sequence[Optics], iteration: int, ip: int):
LOG.info(f"RDT change in IP{ip:d}, iteration {iteration+1:d}:")
integral_iter = zip(integral_before, integral_after)
for idx_optics, ... | [
"def update_loglike(self, iteration):\n # todo: implement log-like\n # Hint: use scipy.special.gammaln (imported as gammaln) for log(gamma)\n\n #theta prior and phi prior\n theta_prior = self.n_docs * (gammaln(self.n_topics * self.alpha) - self.n_docs * self.n_topics * gammaln(self.alpha... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
clean bad images in root directory | def clean_bad_imgs(root):
for d in os.listdir(root):
if os.path.isdir(os.path.join(root, d)):
clean_bad_imgs(os.path.join(root, d))
else:
filename = os.path.join(root, d)
if filename.endswith('.jpg') or filename.endswith('.png') or filename.endswith('.jpeg'):
... | [
"def clean(image_name):\n logging.info('Cleaning image \\'' + image_name + '\\' files')",
"def _clean(self):\n if self.verbose:\n print(\"Removing all individual tif images\")\n tifs = glob.glob('%s*' % (self.indiv_page_prefix)) # all individual tifd\n for tif in tifs:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Allow the parent app to authenticate user's access to the dashboard with it's own auth_handler method that must return True or False | def authentication_hook():
auth_handler = current_app.extensions['rq-dashboard'].auth_handler
if 'AUTH_USER' in current_app.config and 'AUTH_PASS' in current_app.config:
auth = request.authorization
if not auth or not auth_handler(auth.username, auth.password):
return Response('The u... | [
"def _protect(self):\n\n server = self.app.server\n\n @server.before_request\n def before_request_auth():\n\n # Check whether the request is authorised\n if self.is_authorized():\n return None\n\n # Otherwise, ask the user to log in\n r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function creates bag of words vectors for the iterable Returns the vectoriterable and the transformers if specified | def bag_of_words(iterable, max_features, ngram_range = (1,1), tfidf=True, return_transformers = False):
vectorizer = CountVectorizer()
vectorized = vectorizer.fit_transform(iterable, max_features = max_features, ngram_range = ngram_range)
transformer = None
if tfidf:
transformer = TfidfTransform... | [
"def make_vectorizers():\n \"\"\"Make various vectorizers based on parameter permutations, return a\n list of them.\n\n `testing` parameter only returns one vectorizer.\n \"\"\"\n vectorizers_list = []\n vectorizer_opts = [\n # {'analyzer_opt': 'char_wb',\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Maximum delta in list of values going forward (max value cannot occur in list before min value) | def get_max_delta(values):
mind = {'index': None, 'value': None}
maxd = {'index': None, 'value': None}
for (index, n) in enumerate(values):
if mind['value'] is None or n < mind['value']:
mind['index'] = index
mind['value'] = n
if (maxd['value'] is None or n > ma... | [
"def max_value(my_list):\n aux = ordered_values(my_list)\n return aux[len(aux) - 1]",
"def peak_to_peak(alist):\n return max(alist) - min(alist)",
"def data_range(xs: List[float]) -> float:\n return max(xs) - min(xs)",
"def calculate_max_drawdown(values):\n maxes = np.maximum.accumulate(values... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
To encoded by rsa | def encode_rsa(content,machine_code):
message = machine_code
file_detail = open("private.pem","rb")
rsakey = RSA.importKey(file_detail.read(),passphrase='secret#code')
file_detail.close()
signer = Signature_pkcs1_v1_5.new(rsakey)
digest = SHA.new()
digest.update(message.encode("utf-8"))
... | [
"def rsa_encrypt(msg, public_key):\n pass",
"def to_rsa(self):\n numbers = [self.n, self.e]\n if self.type == self.PRIVATE:\n numbers.append(self.d)\n return RSA.construct(tuple(self.b64_to_int(n) for n in numbers))",
"def get_public_key() -> bytes:\n return b64encode(rsa_i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The memoized version of the function. Takes all args and kwargs, and converts them into a single tuple. This tuple is used as the key to the cache. If the tuple exists in the cache's keys, the cached value is returned. If not, the function is executed, the returned value is cached for later retrieval, and then returned... | def memoized(*args, **kwargs):
arguments = args + tuple((a, b) for a, b in kwargs.items())
if arguments not in cache:
cache[arguments] = function(*args, **kwargs)
return cache[arguments] | [
"def _Memoize(func):\n l = threading.Lock()\n cache = {}\n def _Caller(*args, **kwargs):\n with l:\n params = repr((args, kwargs))\n try:\n return cache[params]\n except KeyError:\n result = func(*args, **kwargs)\n cache[params] = result\n return result\n return _Ca... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns True if `value` contains every digit 1n exactly once, or False otherwise. Ensure `value` is a string first. Works on ints and strings. | def is_n_digit_pandigital(value, n):
value = str(value)
return (len(value) == n) and (set('123456789'[:n]) == set(value)) | [
"def safe(n: int) -> bool:\n # isolate ones digit\n ones = n % 10\n # isolate tens digit\n tens = int((n - ones) / 10)\n\n # checks to make sure whether n is not divisible by 9 and does not contain 9 as a digit\n return (n % 9 != 0) & (ones != 9) & (tens != 9)",
"def check_digit_duplicate(iterab... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Converts list of timestapms from string format to datetime or unix | def convert_from_str_timestamps(original_timestamps, target_format):
if target_format == "datetime":
output_timestamps = [parser.parse(elem)
for elem in original_timestamps]
elif target_format == "unix":
output_timestamps \
= [round(datetime.strptime(el... | [
"def convert_from_unix_timestamps(original_timestamps, target_format):\n\n if target_format == \"datetime\":\n output_timestamps = [datetime.fromtimestamp(elem)\n for elem in original_timestamps]\n elif target_format == \"str\":\n output_timestamps \\\n = [... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Converts list of timestapms from unix format to datetime or string | def convert_from_unix_timestamps(original_timestamps, target_format):
if target_format == "datetime":
output_timestamps = [datetime.fromtimestamp(elem)
for elem in original_timestamps]
elif target_format == "str":
output_timestamps \
= [datetime.fromtime... | [
"def convertUnixTime(self, time):\n\t\treturn datetime.datetime.utcfromtimestamp(time) # unixtime --> datetime",
"def convert_from_str_timestamps(original_timestamps, target_format):\n\n if target_format == \"datetime\":\n output_timestamps = [parser.parse(elem)\n for elem i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Callback for light updates from the RFXtrx gateway. | def light_update(event):
if not isinstance(event.device, rfxtrxmod.LightingDevice) or \
not event.device.known_to_be_dimmable:
return
new_device = rfxtrx.get_new_device(event, config, RfxtrxLight)
if new_device:
add_devices([new_device])
rfxtrx.a... | [
"def lighting_process(db, controls):\n try:\n # Get the current hour & the corresponding RGB data\n hour = str(datetime.datetime.now().hour)\n rgb_data = db['RGB_data'][hour]\n red = rgb_data['R']\n green = rgb_data['G']\n blue = rgb_data['B']\n\n # Check for manu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a size n and and nlength list of reward by distance (starting from the nearest spot and ending with the farthest), generates an output file with the corresponding MDP. | def generate_parking_mdp(n, distance_rewards, name):
assert(len(distance_rewards) == n)
num_actions = 2 # drive, park
rewards = []
# state organization. always drive from state j to j + 1, clockwise
for i in range(n - 1, -1, -1): # n - 1, n - 2, ..., 0
# A[i], unoccupied, unparked = state... | [
"def write_policy_file():\n global maze\n\n for r in range(rows):\n for c in range(cols):\n max_reward = max(q_table[r, c])\n\n if max_reward != 0:\n action = list(q_table[r, c]).index(max_reward)\n action = actions[action]\n\n maze[r, ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Resolve the matched key and process it's value based on the supplied renderer | def resolve_key(self, match):
args = match.group(1).split('|')
key = args[0]
processor_funcs = args[1:]
value = self.args.get(key, '')
for func_name in processor_funcs:
# get renderer func or use to string func
value = ALIASES.get(func_name, str)(value)
... | [
"def __getitem__(self, key):\n if type(key) == str:\n return self.act2templ[key]\n elif type(key) == Template:\n return self.templ2act[key]",
"def _ParseKey(self, mediator, registry_key, value_name):",
"def renderer():",
"def _process_match_formatter(self, match, child=Fals... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
finds variable names from the provided line and calls the resolve_key method with eventual matches It replaces the match with the resolved value and returns the line | def _parse_line(self, line):
pattern = r'{{(.*?)}}'
line = re.sub(pattern, self.resolve_key, line)
return line | [
"def resolve_deferred_str(self, line):\n\n resolved_line = []\n offset = 0\n\n match = self.DEFERRED_VAR_RE.search(line, offset)\n\n # Walk through the line, and lookup the real value of\n # each matched deferred variable.\n while match is not None:\n resolved_li... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Walk the template dir, read the template files and parse them replacing variables in the files with values given in the context dictionary. Return a list of directories and files with their parsed content basically the output of os.walk. | def parse(self):
dir_content = []
for cur_path, dirs, files in os.walk(self.template_dir):
new_path = cur_path.replace(self.template_dir, self.dest_dir)
path = self._parse_path(new_path)
file_paths = [self._parse_path(fp) for fp in files]
file_contents =... | [
"def _load_templates(self):\n assert self.dumped_context is not None\n\n say('loading templates...')\n\n context = self.dumped_context\n templates_path = build_embryo_filepath(self.path, 'templates')\n templates = {}\n\n if not os.path.isdir(templates_path):\n re... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Do when teleoperated mode is started. | def teleopInit(self):
pass | [
"def teleop_enabled_callback(self, msg: Bool):\n self.teleop_enabled = msg.data",
"def on_start(self, event):\n pass",
"def start(self):\n self.running = True",
"def start(self):\n self.device.execute_command(\"monkey -p {pkg} 1\".format(pkg=self.package_name), args=[], shell=True)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Uploads a dataframe to a remote staging location | def export_dataframe_to_staging_location(
df: pd.DataFrame, staging_location_uri: str
) -> str:
# Validate staging location
uri = urlparse(staging_location_uri)
if uri.scheme == "gs":
dir_path, file_name, source_path = export_dataframe_to_local(df)
upload_file_to_gcs(
source... | [
"def upload_output(df_output):",
"def send_dataframe_to_gcp(filename, file_location, processed_df):\n\n file_str = file_location + filename\n # storage blob complete\n storage_blob = storage.Blob(file_str, storage_bucket)\n # create in-memory csv string\n csv_str = processed_df.to_csv(index=False)\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Upload a file from the local file system to Google Cloud Storage (GCS) | def upload_file_to_gcs(local_path: str, bucket: str, remote_path: str):
storage_client = storage.Client(project=None)
bucket = storage_client.get_bucket(bucket)
blob = bucket.blob(remote_path)
blob.upload_from_filename(local_path) | [
"def upload_to_gcs(self, url, gcs_bucket, filename):\n url_file_to_gcs.url_file_to_gcs(url, None, gcs_bucket, filename)",
"def upload_file_to_gcs(service, bucket_name, file_content, filename):\n try:\n upload = MediaIoBaseUpload(file_content, mimetype='application/json',\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get input file or directory from the command line argument, and create a list of input files | def get_arguments() -> List[Path]:
parser = argparse.ArgumentParser()
parser.add_argument('input',
help='input docx file or directory')
args = parser.parse_args()
# Check input
cwd = Path.cwd()
input_path = cwd / args.input
if input_path.is_file():
if not is... | [
"def get_input_list_from_file(file_name):\n\treturn []",
"def get_input_files(par_data):\n #inp_file_list = None\n from_ifiles = []\n from_infilelist = []\n if 'ifile' in par_data['main']:\n inp_file_str = par_data['main']['ifile'].split('#', 2)[0]\n cleaned_str = re.sub(r'[\\t,:\\[\\]()... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
STAGE 2 MIN MAX [[min,max],[min,max]....,[min,max]] | def stage2(self):
grouped = self.df_smalltrain.groupby('num_class')
normal = grouped.get_group(1) # normal
normal_max_list = list(normal.max())
normal_min_list = list(normal[normal > 0].min())
normal_min_list = list(map(int, normal_min_list))
self.min_max = map(list, zip... | [
"def _get_buffering_subregion_minmax(ip, pmin, pmax, rmax):\n if ip == -1:\n smin, smax = pmin - rmax, pmin\n elif ip == 0:\n smin, smax = pmin, pmax\n elif ip == 1:\n smin, smax = pmax, pmax + rmax\n return smin, smax",
"def get_min_max_values(self):\n\n min_val = min(self... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns all the properties from C{udi} | def get_properties_from_udi(self, udi):
obj = self.bus.get_object('org.freedesktop.Hal', udi)
dev = dbus.Interface(obj, 'org.freedesktop.Hal.Device')
return dev.GetAllProperties() | [
"def get_properties_from_udi(udi):\n obj = self.bus.get_object('org.freedesktop.Hal', udi)\n dev = dbus.Interface(obj, 'org.freedesktop.Hal.Device')\n return dev.GetAllProperties()",
"def get_devices_properties():\n return [get_properties_from_udi(udi)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns all the properties from all devices registed in HAL | def get_devices_properties(self):
return [self.get_properties_from_udi(udi)
for udi in self.manager.GetAllDevices()] | [
"def get_devices_properties():\n return [get_properties_from_udi(udi)\n for udi in self.manager.GetAllDevices()]",
"def get_properties_from_udi(udi):\n obj = self.bus.get_object('org.freedesktop.Hal', udi)\n dev = dbus.Interface(obj, 'org.freedesktop.Hal.Dev... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Called when a device has been added | def device_added(self, udi):
if self.device:
# if we already have an active device, ignore the new device
return
# leave it alone four seconds so the device can settle and register
# itself with the kernel properly
reactor.callLater(4, self.process_device... | [
"def add_device(self, device):\n self.device_list.append(device)",
"def add_device(self):\n detected_device = self.usb.list_usb()\n if bool(detected_device):\n for device in detected_device:\n self.ui.comboBox.addItem(str(device))\n if self.ui.comboBox... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Called when a device has been removed | def device_removed(self, udi):
if not self.device:
return
if IRemoteDevicePlugin.providedBy(self.device):
log.msg("DEVICE %s REMOVED" % udi)
return
if self.device.udi == udi:
louie.send(notifications.SIG_DEVICE_REMOVED, None)
... | [
"def disconnect(self, device):",
"def remove_device(self, id: uuid):\n raise NotImplementedError()",
"def remove_device(device_uid):\n return runtime.remove_device(device_uid)",
"def destroy(self):\n for item in self.__dict__:\n self.removeDevice(item)",
"def _cb_interfaces_remov... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns all the properties from C{udi} | def get_properties_from_udi(udi):
obj = self.bus.get_object('org.freedesktop.Hal', udi)
dev = dbus.Interface(obj, 'org.freedesktop.Hal.Device')
return dev.GetAllProperties() | [
"def get_properties_from_udi(self, udi):\n obj = self.bus.get_object('org.freedesktop.Hal', udi)\n dev = dbus.Interface(obj, 'org.freedesktop.Hal.Device')\n return dev.GetAllProperties()",
"def get_devices_properties():\n return [get_properties_from_udi(udi)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns all the properties from all devices registed in HAL | def get_devices_properties():
return [get_properties_from_udi(udi)
for udi in self.manager.GetAllDevices()] | [
"def get_devices_properties(self):\n return [self.get_properties_from_udi(udi)\n for udi in self.manager.GetAllDevices()]",
"def get_properties_from_udi(udi):\n obj = self.bus.get_object('org.freedesktop.Hal', udi)\n dev = dbus.Interface(obj, 'org.freedesktop.Hal.De... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the type of the metric | def get_metric_type(self):
search_for_metric = self.raw_metric['type']
if search_for_metric in self.supported_metrics.keys():
return self.supported_metrics[search_for_metric].get('type', "gauge")
return "unknown" | [
"def gettype(self, v):\n return _measures.measures_gettype(self, v)",
"def unit_to_metric_type(unit: MeasuredUnit) -> Type[MetricWrapperBase]:\n if unit is MeasuredUnit.COUNT:\n return Counter\n else:\n return Histogram",
"def comettype(self):\n return _measures.measures_comett... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
a bit out of place here and should eventially be moved... alpha_d = alpha_dueterium(T) returns the isotopic fraction coefficient alpha defined from alpha = r_w/r_g where r_w is the isotopic ratio in the water phase and r_g is isotopic ratio in the gas phase. The fraction factor is a function of T the temperature in Cel... | def alpha_deuterium(T):
#table of dueterium partition coeficients from truesdell 1977
#ln_alpha = array([106.,81.5,61.3,46.4,36.1,27.8,21.5,16.3,11.7,7.4,3.5,0.1,-2.2,-3.6,-4.,-3.4,-2.2,-1.3,-0.5]);
#T_alpha = arange(0,361,20);
#ln_alpha_T = interpolate.interpolate.spline(T_alpha,ln_alpha,T);
T... | [
"def R_dc_T(R_dc, T_0, T_1, alpha_0):\n\tR_dc_1 = R_dc*(1 + alpha_0*(T_1 - T_0))\n\treturn R_dc_1",
"def liquid_fraction_from_temperature(t: tf.Tensor) -> tf.Tensor:\n return tf.where(\n tf.greater(t, self._t_freeze), tf.ones_like(t),\n tf.where(\n tf.less_equal(t, self._t_icen... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initialize a new EventPubSub object | def __init__(self, uri=None):
if not uri: uri = "(EventPubSub %u)"%(id(self))
Trace("%s Init"%(uri), context="EventLib.EventPubSub")
super(EventPubSub, self).__init__(uri)
# Subscription table for local delivery of events
self._sub = EventTypeSourceDict()
self._sub... | [
"def __init__(self):\n self._events = self._create_event_objects()",
"def _pubsub_factory() -> PubSub:\n p = PubSub(skip_core_undo=True)\n p.registry_initialize()\n for capability in CAPABILITIES:\n p.register_capability(capability.value)\n return p",
"def _create_event_subscriber(self... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Subscribe an event handler to an event/source combination. 'interval' is a time interval, in seconds, for which the subscription is to be maintained if zero, no subscription is created, and any existing subscription is cancelled. Returns a Deferred status value is returned indicating the outcome of the operation. | def subscribe(self, interval, handler, evtype=None, source=None):
Trace("%s subscribe %us, handler %s to (%s,%s)"%
(self.getUri(), interval, str(handler), evtype, source),
context="EventLib.EventPubSub")
sts = self.unsubscribe(handler, evtype, source)
if interval... | [
"def subscribe(handler: Handler, predicate: Optional[Predicate] = None) -> None:\n if (predicate, handler) not in _subscriptions:\n _subscriptions.append((predicate, handler))",
"def makeSubscribeEvent(subtype, subscriber, interval, evtype, source):\n payload = [interval, evtype, source]\n return ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Unsubscribe an event handler from an event/source combination. A Deferred status value is returned indicating the outcome of the unsubscribe operation. | def unsubscribe(self, handler, evtype=None, source=None):
Trace("%s unsubscribe (%s,%s) from %s"%(self.getUri(), evtype, source, str(handler)),
context="EventLib.EventPubSub")
removed = self._sub.remove(evtype, source, handler)
Trace("removed: %s"%(map(str,removed)), context="Even... | [
"def unsubscribe(handler: Handler, predicate: Optional[Predicate] = None) -> None:\n if (predicate, handler) in _subscriptions:\n _subscriptions.remove((predicate, handler))",
"def unsubscribe(self, handle, callback=None):\r\n pass",
"def unsubscribe(request, source_id):\n try:\n src ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Terminate request to receive notice of subscribe/unsubscribe events for a given event type. | def endWatch(self, handler, evtype=None):
Trace("%s endWatch %s from %s"%(self.getUri(), evtype, str(handler)),
context="EventLib.EventPubSub")
return self.unsubscribe(handler, evtype=URI.EventSubscribeType, source=evtype) | [
"def stop_subscription(event):\n _LOGGER.info(\"Shutting down subscriptions.\")\n VERA_CONTROLLER.stop()",
"def stop_wemo(event):\n _LOGGER.info(\"Shutting down subscriptions.\")\n SUBSCRIPTION_REGISTRY.stop()",
"def unsubscribe(self, handler, evtype=None, source=None):\n Trac... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return count of current subscriptions. This function is provided for testing purposes | def getSubscriptionCount(self):
assert self._subcount == self._sub.count()
return self._subcount | [
"def subscribers_count(self) -> str:\n return self._statistics.get('subscriberCount')",
"def subscriber_count(self):\n return len(self._subscribers)",
"def generate_subscription_counts(conn):\n with conn.cursor() as cur:\n try:\n cur.execute(\n \"\"\"\n S... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Publish an event. The event source is taken from the event itself; the 'agent' parameter provides an EventAgent context that may be used for diagnostic or security purposes. Note that self.publish has the same interface as an event callback function provided to makeHandler Returns a Deferred object with the final statu... | def publish(self, agent, event):
Trace("%s publish (%s,%s,%s) from %s"%
(self.getUri(), event.getType(), event.getSource(), event.getPayload(), agent),
context="EventLib.EventPubSub")
sts = self.deliver(event)
if sts.syncValue() == StatusVal.OK:
sts = sel... | [
"def publish_event(self, event):\n if not isinstance(event, Event):\n self.logger.error('Wrong event data')\n self._dispatcher.send(event=event,\n signal=event.type)\n # self.logger.info(f'Event published: {event}')",
"def publish(self, event: BaseEvent... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Local delivery of an event. Returns a Deferred object with the final status of the deliver operation. | def deliver(self, event):
Trace("%s deliver (%s,%s,%s)"%
(self.getUri(), event.getType(), event.getSource(), event.getPayload()),
context="EventLib.EventPubSub")
(evtyp, evsrc) = getEventTypeSource(event)
if isSubscribeEvent(evtyp):
for (e,t,handler) in s... | [
"def forward(self, event, envelope):\n return makeDeferred(StatusVal.OK)",
"def delivered_on_a(self):\n return self._delivered_on_a",
"def status_delivery(self):\n return self._status_delivery",
"def test_async(self):\n o = LocalRemoteTest()\n o = LocalRemoteTest()\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Forward an event to any external event routers that have subscribers for this event. This version is a dummy function that must be overridden for event distribution nodes that may route events to other nodes. Returns a Deferred object with the final status of the forward operation. | def forward(self, event, envelope):
return makeDeferred(StatusVal.OK) | [
"def forward(self, event, envelope):\n Trace(\"%s forward %s\"%(self.getUri(),str(event)), \"EventLib.EventRouter\")\n sub = openSubscribeEvent(isSubscribeEvent, event)\n if sub:\n # Subscribe events routed per static routing table and subscribed event type/source\n for ro... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initialize a new event router object | def __init__(self, uri=None):
if not uri: uri = "(EventRouter %u)"%(id(self))
super(EventRouter, self).__init__(uri)
# Forward routing table: this is effectively a static routing table
# for event forwarding, indicating the sources to subscribe to for
# relaying of given event t... | [
"def __init__(self, router):\n self.router = router\n self.state = Starting(self) # Router is initialized in the starting state\n self.transition = None",
"def __init__(self):\n self._events = self._create_event_objects()",
"def __init__(self):\n module, class_name = conf.eve... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Forward an event to any external event routers that have subscribers for this event. The event to be delivered is supplied bare and also wrapped in a forwarding envelope, which contains additional information about the event delivery path that is used, possibly among other things, to detect event forwarding loops. Retu... | def forward(self, event, envelope):
Trace("%s forward %s"%(self.getUri(),str(event)), "EventLib.EventRouter")
sub = openSubscribeEvent(isSubscribeEvent, event)
if sub:
# Subscribe events routed per static routing table and subscribed event type/source
for router in self._... | [
"def forward(self, event, envelope):\n return makeDeferred(StatusVal.OK)",
"def deliver(self, event):\n Trace(\"%s deliver (%s,%s,%s)\"%\n (self.getUri(), event.getType(), event.getSource(), event.getPayload()), \n context=\"EventLib.EventPubSub\")\n (evtyp, evsrc) =... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Receive an event from an external event router. The event received is wrapped in a forwarding envelope, which contains additional information about the event delivery path that is used, possibly among other things, to detect event forwarding loops. Returns a Deferred object with the final status of the receive operatio... | def receive(self, fromrouter, envelope):
sts = makeDeferred(StatusVal.OK)
event = envelope.unWrap(self.getUri()) # unWrap handles loop-detection
if event:
Trace("%s receive %s from %s"%(self.getUri(),str(event), fromrouter), "EventLib.EventRouter")
self.deliver(eve... | [
"def forward(self, event, envelope):\n Trace(\"%s forward %s\"%(self.getUri(),str(event)), \"EventLib.EventRouter\")\n sub = openSubscribeEvent(isSubscribeEvent, event)\n if sub:\n # Subscribe events routed per static routing table and subscribed event type/source\n for ro... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Define event routing. When a subscription is received for an event matching the supplied type and source, a new subscription to the specified router is established so that events can be received from that router and republished to local subscribers. (Remember the old programmer's joke about the COME FROM in Fortran? Th... | def routeEventFrom(self,evtype=None,source=None,router=None):
### Trace("%s routeEventFrom: (%s,%s) from %s"%(self.getUri(),evtype,source,str(router)), context="EventLib.EventRouter")
self._fwdroute.insert(evtype,source,router)
Trace("%s _fwdroute inserted: (%s,%s) -> %s"%(self.getUri(),evtype,s... | [
"def __init__(self, uri=None):\n if not uri: uri = \"(EventRouter %u)\"%(id(self))\n super(EventRouter, self).__init__(uri)\n # Forward routing table: this is effectively a static routing table\n # for event forwarding, indicating the sources to subscribe to for \n # relaying of g... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Insert value into the dictionary indexed by evtype and evsrc. Returns a resulting list of values for the given indexex. | def insert(self, evtype, evsrc, value):
# Local function updates the "WildDict" entry for the indicated event type,
# which is a list of "WildDict" values mapping event sources to subscription lists
def upd(srcd):
if not srcd: srcd = (WildDict(evtype),) # Tuple of 1 prevents addi... | [
"def findEntry(self, evtype, evsrc):\n # Local functions simply returns the entry value list as the result and \n # for the new entry value.\n def upd(srcd):\n if srcd:\n entry = srcd[0].findEntry(evsrc)\n else:\n entry = []\n retur... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Find an entry matching exactly the supplied event type and event source (either of which may be None). Returns the list of values for this entry, or an empty list. | def findEntry(self, evtype, evsrc):
# Local functions simply returns the entry value list as the result and
# for the new entry value.
def upd(srcd):
if srcd:
entry = srcd[0].findEntry(evsrc)
else:
entry = []
return (entry, src... | [
"def find(self, evtype, evsrc):\n return list(self.iterate(evtype, evsrc))",
"async def find_event(self, event_type: str, start_index: int = 0, **kwargs: Any) -> Optional[Event]:\n\n events = await self.events(start_index)\n events = [e for e in events if e.type == event_type]\n for e ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a list of values in the table, including catchall values, matching the supplied event type and source. | def find(self, evtype, evsrc):
return list(self.iterate(evtype, evsrc)) | [
"def _extract_events(self, df: DataFrame) -> DataFrame:\n return df.filter(df.event == self.event_type)",
"def values(self):\n for item in self.table:\n if item:\n yield item.value",
"def GetSources(self, event_object):\n if self.DATA_TYPE != event_object.data_type:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns an interator over entries matching the supplied event type and source; that is, all entries with the specified values, and also all wildcard entries. The iterator returns wildcard entries after nonwildcard entries, with wildcard event values after wildcard source values. | def iterate(self, evtype, evsrc):
for d in self._sub.iterate(evtype):
for v in d.iterate(evsrc):
yield v
return | [
"def find(self, evtype, evsrc):\n return list(self.iterate(evtype, evsrc))",
"def iterSources(self):\n for row in self.iterDictQuery(\"%s ORDER BY name\" % self.sourceQuery):\n yield ThermSource(self, **row)",
"def match(self, source: 'frame.Source') -> Provider:\n for feed in se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a list of entries matching the supplied key; that is, all entries with the specified key, and also all wildcard entries. The list contains wildcard entries after nonwildcard entries. If key is None, then only wildcard entries are returned. | def find(self, key):
return list(self.iterate(key)) | [
"def items_by_pattern(self, key_pattern):\n items = self.items()\n filtered_items = [(k, v) for k, v in items if re.search(key_pattern, k)]\n return filtered_items",
"def search(key=None, value=None):\n if key and value:\n result = LDAP_CONN.search_s(\n LDAP_T... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns an interator over entries matching the supplied key; that is, all entries with the specified key, and also all wildcard entries. The iterator returns wildcard entries after nonwildcard entries. If the supplied key is None, it is treated as a wildcard and all entries are returned. | def iterateWild(self, key):
if key: return self.iterateKey(key)
return self.iterateAll() | [
"def iterateKey(self, key):\n if key and key in self._keyed:\n for v in self._keyed[key]: yield (key, v)\n for v in self._wild: yield (None, v)\n return",
"def find(self, key):\n return list(self.iterate(key))",
"def __getitem__(self, key: Union[Any, Sequence[Any]]) -> Uni... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns an interator over entries matching the supplied key; that is, all entries with the specified key, and also all wildcard entries. The iterator returns wildcard entries after nonwildcard entries. If the supplied key is None, only wildcard table entries are returned. | def iterateKey(self, key):
if key and key in self._keyed:
for v in self._keyed[key]: yield (key, v)
for v in self._wild: yield (None, v)
return | [
"def iterateWild(self, key):\n if key: return self.iterateKey(key)\n return self.iterateAll()",
"def find(self, key):\n return list(self.iterate(key))",
"def __iter__(self):\n for item in self._table:\n yield item._key # yield the key",
"def get_wildc... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return an event object to convey the supplied subscription details. interval=0 for unsubscribe. | def makeSubscribeEvent(subtype, subscriber, interval, evtype, source):
payload = [interval, evtype, source]
return makeEvent(subtype, subscriber, payload) | [
"def getSubscription(subscriber):",
"def subscribe(self, interval, handler, evtype=None, source=None):\n Trace(\"%s subscribe %us, handler %s to (%s,%s)\"%\n (self.getUri(), interval, str(handler), evtype, source), \n context=\"EventLib.EventPubSub\")\n sts = self.unsub... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return details from a subscribe event, or None if it is not a subscribe event. 'subtype' is a function that tests if the supplied event type is a subscription event type. | def openSubscribeEvent(subtype, event):
if subtype(event.getType()):
evsrc = event.getSource()
evsub = event.getPayload()
if evsub != None: return [event.getType(),evsrc]+evsub
return None | [
"def makeSubscribeEvent(subtype, subscriber, interval, evtype, source):\n payload = [interval, evtype, source]\n return makeEvent(subtype, subscriber, payload)",
"def getEventTypeSource(event):\n evtyp = event.getType()\n evsrc = event.getSource()\n if isSubscribeEvent(evtyp):\n evsub = even... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the event type and source for the supplied eventy, taking account of different source rules for subscription releated events. | def getEventTypeSource(event):
evtyp = event.getType()
evsrc = event.getSource()
if isSubscribeEvent(evtyp):
evsub = event.getPayload() # [interval, type, source]
if evsub:
evsrc = evsub[1]
return (evtyp,evsrc) | [
"def GetSources(self, event_object):\n if self.DATA_TYPE != event_object.data_type:\n raise errors.WrongFormatter(u'Unsupported data type: {0:s}.'.format(\n event_object.data_type))\n\n source_long = getattr(event_object, u'source_long', u'UNKNOWN')\n source_append = getattr(event_object, u's... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Fetch all intervals that overlap the given start/stop in the given chromosome. | def overlaps(self, chromosome: str, start: int, stop: int) -> ty.Iterable[ty.List]:
query = "{chromosome}:{start}-{stop}"
process = sp.Popen(["tabix", str(self.info.compressed), query])
for line in process.stdout:
yield line.strip().split() | [
"def find(self, start, stop):\n overlapping = [i for i in self.intervals if i[1] >= start and i[0] <= stop]\n\n if self.left and start <= self.center:\n overlapping += self.left.find(start, stop)\n\n if self.right and stop >= self.center:\n overlapping += self.right.find(s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns index into the site for given r | def idx( self, r ):
assert( 0 <= r )
assert( self.length > r )
if 0 == r: return self.gap_idx + 1 # did we hit the gap?
if r - 1 <= self.gap_idx: return r - 1 # are we below the gap?
else: return r # we are above the gap | [
"def _indices(self, r):\n bits = (2 * (r - self.r0[newaxis, :]) / self.lengths[newaxis, :])\n bits = bits.astype('i')\n\n # We do not want to exclude the boundaries with higher values\n bits = where(bits < 2, bits, 1)\n\n p2 = array([4, 2, 1])\n\n # This is the index of th... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convenience function to set ACL on an entity for a user or team based on permission levels (view, download...) | def set_entity_permissions(syn, entity, principalid, permission_level="download"):
# Get the entity to check for access / validity of entity
entity = syn.get(entity, downloadFile=False)
_set_permissions(syn, entity, principalid, permission_level) | [
"def setAccessControlList(acl):",
"def test_update_team_acl(self):\n pass",
"def setacl(self, mailbox, who, what):\n return self._simple_command('SETACL', mailbox, who, what)",
"def grant_permissions(self):\n assign_perm(\"context.view_context\", self.team.group, self)\n assign_per... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initialise or update the pixmap images for the minefield cells. | def init_or_update_cell_images(cell_images, size, styles, required=CellImageType.ALL):
# @@@LG Currently only allows setting button styles.
btn_style = styles[CellImageType.BUTTONS]
if required & CellImageType.BUTTONS:
cell_images["btn_up"] = make_pixmap("buttons", btn_style, "btn_up.png", size)... | [
"def set_cell_image(self, coord: Coord_T, state) -> None:\r\n x, y = coord\r\n b = self.scene.addPixmap(self.cell_images[state])\r\n b.setPos(x * self.btn_size, y * self.btn_size)",
"def initialize_sprites(self):\n self.player = game.items.Player(0, 0, 'images/mac_gyver.png')\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Left button was double clicked. Call callback to remove any flags that were on the cell. | def left_button_double_down(self, coord: Coord_T) -> None:
self.ctrlr.remove_cell_flags(coord) | [
"def double_left_click_obvious_cells(self):\n for cell in self.list_active_cells():\n if self.neighboring_flags(cell.row, cell.column) == self.neighboring_bombs(cell.row, cell.column):\n cell.double_left_click()\n self.remove_active_cell(cell)\n self.up... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Left mouse button moved after a double click. | def left_button_double_move(self, coord: Coord_T) -> None:
if self.drag_select:
self.left_button_double_down(coord) | [
"def mouse_double_clicked(self, x, y, modifiers):\n return False",
"def double_click_input(self, button =\"left\", coords = (None, None)):\n self.click_input(button, coords, double=True)",
"def left_click(self):\n self.node.left_click()",
"def item_double_clicked(self, item): \n if... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Right mouse button was moved. Change display as appropriate. | def right_button_move(self, coord: Coord_T) -> None:
if coord is not None and self.drag_select:
if self.unflag_on_right_drag:
self.ctrlr.remove_cell_flags(coord)
else:
self.ctrlr.flag_cell(coord, flag_only=True) | [
"def move_right(self):\n self.lcd_byte(\n self.LCD_CURSORSHIFT | self.LCD_DISPLAYMOVE | self.LCD_MOVERIGHT,\n self.LCD_CMD)",
"def OnRightEvent(self, event):\n self.click = 'RIGHT'\n self.ProcessClick(event)",
"def move_right(self, event):\n self.control.canvas.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set an unclicked cell to appear sunken. | def sink_unclicked_cell(self, coord: Coord_T) -> None:
if self._game_state.finished():
return
if self._board[coord] == CellUnclicked():
self.set_cell_image(coord, "btn_down")
self.sunken_cells.add(coord)
if self.sunken_cells:
self.at_risk_si... | [
"def raise_all_sunken_cells(self) -> None:\r\n while self.sunken_cells:\r\n coord = self.sunken_cells.pop()\r\n if self._board[coord] == CellUnclicked():\r\n self.set_cell_image(coord, \"btn_up\")",
"def toggle_flag(self, coords):\n if invalid_coords(coords): ret... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reset all sunken cells to appear raised. | def raise_all_sunken_cells(self) -> None:
while self.sunken_cells:
coord = self.sunken_cells.pop()
if self._board[coord] == CellUnclicked():
self.set_cell_image(coord, "btn_up") | [
"def clear(self):\r\n\t\tfor cellarrays in self.cells:\r\n\t\t\tfor cell in cellarrays:\r\n\t\t\t\tcell.alive = False",
"def reveal_all_clear_cells_from(self, x, y) :\n\n assert x in range(0, self.__width), \"x must be between 0 and the game width\"\n assert y in range(0, self.__height), \"y must be... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set the image of a cell. | def set_cell_image(self, coord: Coord_T, state) -> None:
x, y = coord
b = self.scene.addPixmap(self.cell_images[state])
b.setPos(x * self.btn_size, y * self.btn_size) | [
"def set_image(self):\r\n self.sc.set_image()",
"def setImage(self, path):\n\t\tpass",
"def setImage(self, image: 'SbImage') -> \"void\":\n return _coin.SoVRMLImageTexture_setImage(self, image)",
"def setCell(self, m, n, value):\n\tself.grid[m][n] = value",
"def setImage(self, img, regions, si... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
requestServerTime(self, int8 context) This message is sent from the client to the AI to initiate a synchronization phase. The AI should immediately report back with its current time. The client will then measure the round trip. | def requestServerTime(self, context):
timestamp = globalClockDelta.getRealNetworkTime(bits=32)
requesterId = self.air.getAvatarIdFromSender()
timeOfDay = int(time.time())
self.sendUpdateToAvatarId(requesterId, "serverTime",
[context, timestamp, timeOfDay... | [
"async def get_server_time(self):\r\n return await self.client_helper(\"get_server_time\")",
"def get_server_time():\n r = requests.get(CurrencyComConstants.SERVER_TIME_ENDPOINT)\n\n return r.json()",
"def request_time(self) -> float:\n if self._finish_time is None:\n retu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
setDisconnectReason(self, uint8 disconnectCode) This method is called by the client just before it leaves a shard to alert the AI as to the reason it's going. If the AI doesn't get this message, it can assume the client aborted messily or its internet connection was dropped. | def setDisconnectReason(self, disconnectCode):
requesterId = self.air.getAvatarIdFromSender()
self.notify.info("Client %s leaving for reason %s (%s)." % (
requesterId, disconnectCode,
OTPGlobals.DisconnectReasons.get(disconnectCode,
'i... | [
"def disconnect_code(self) -> int:\n ...",
"def disconnect(self, reason: str = ''):\r\n reason_b = reason.encode(ENCODING)\r\n self.send(self.Enum.INF_DISCONNECT, reason_b) # Send inform_disconnect message with 'reason'\r\n self.transport.close() # Close the connection. Waits to send... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
setExceptionInfo(self, string info) In the case of the client leaving for a Python exception, we also follow up the above message with this one, which just sends a text string describing the exception for the AI log. | def setExceptionInfo(self, info):
requesterId = self.air.getAvatarIdFromSender()
self.notify.info("Client %s exception: %s" % (requesterId, info))
serverVersion = simbase.config.GetString('server-version','')
self.air.writeServerEvent('client-exception', requesterId, '%s|%s' % (serverVer... | [
"def update_entry_with_exc(entry, exc_info):\n if not exc_info:\n return\n\n error = exc_info[1]\n error_extras = getattr(error, 'extras', {})\n entry['task_payload'] = (\n entry.get('task_payload') or error_extras.pop('task_payload', None))\n entry['extras'].update(error_extras)\n entry['serviceConte... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This method is called by the client at startup time, to send the xrc signature and the prc hash to the AI for logging in case the client does anything suspicious. | def setSignature(self, signature, hash, pyc):
if signature:
requesterId = self.air.getAvatarIdFromSender()
prcHash = HashVal()
prcHash.setFromBin(hash)
info = '%s|%s' % (signature, prcHash.asHex())
self.notify.info('Client %s signature: %s' % (requeste... | [
"def connectionMade(self):\n peer = self.transport.getPeer()\n pubkey1 = self.pki.publicKey.hex().encode()\n self.transport.write(pubkey1)",
"def start_challenge(self):\r\n\t\tif self.state=='KEY_EXCHANGE':\r\n\r\n\t\t\tlogger.info(\"Starting Challenge\")\r\n\t\t\tnonce = os.urandom(16)\r\n\t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This method is called by the client at startup time, to send the detailed CPU information to the server for logging. | def setCpuInfo(self, info, cacheStatus):
requesterId = self.air.getAvatarIdFromSender()
self.notify.info('client-cpu %s|%s' % (requesterId, info))
self.air.writeServerEvent('client-cpu', requesterId, info)
# We call this cacheStatus, but really it's the mac address or
# other cl... | [
"def displayCpuReport(self):\n cpuReport = self.getTopCpu()\n self.pprint.white('\\tTop CPU Consuming Processes : ')\n self.displayReport(cpuReport)\n print('')",
"def monitor_cpu(self) -> None:\n last_write = 0\n _ = psutil.cpu_percent()\n _ = self.process.cpu_per... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reads a CSV file and returns dictionaries for authors and tagnames. | def read_csv(has_head=True):
csvfile = open('%s%s.csv' % (DATA_DIR, CSV_FILENAME))
authorsdict = dict()
tagnamesdict = dict()
lines = csvfile.readlines()
if has_head:
lines = lines[1 : ]
for line in lines:
(idAuthor, tagName) = line.split(',')
idAuthor = int(idAuthor.st... | [
"def readcsv():\n\n with open(INPUT_CSV, newline = '') as csvfile:\n # Skips the first row\n next(csvfile)\n csvdata = csv.reader(csvfile)\n\n # Itterates over each row, adding the rating and year to the dictionary\n for row in csvdata:\n rating = row[1]\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Opens the signal monitor window for the given devices. | def open_monitor(self, devs):
for dev in devs:
self.monitors[dev.properties['name']]['widget'].show()
self.monitors[dev.properties['name']]['widget'].clear_data() | [
"def open_sensor_dialog(self):\n self.sensorDialog = SensorDialog(parent=self.dlg)\n self.sensorDialog.ui.pb_oksensor.clicked.connect(self.collect_sensor)\n self.sensorDialog.ui.pb_close.clicked.connect(self.sensorDialog.close)\n self.sensorDialog.show()",
"def open_parameters_window(s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Saves the data of all the checked monitors. | def save_all_monitors(self, directory=None):
devs_to_monitor = self.get_devices_checked()
for dev in devs_to_monitor:
if directory is not None:
self.monitors[dev.properties['name']]['widget'].directory = directory
self.monitors[dev.properties['name']]['widget... | [
"def save_sensors(self):\n for sensor in self.sensors:\n sensor.save()",
"def save(self, *args, **kwargs):\n self._update_fields()\n super(Monitor, self).save(*args, **kwargs)",
"async def save_sensors(self):\n\n await self._execute_command('#saveSensors')",
"def record_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Updates the data to the different monitors. It is an intermadiate step that may not be needed. | def update_signal_values(self, data):
for dev in data:
self.monitors[dev]['widget'].set_ydata(data[dev]) | [
"def open_monitor(self, devs):\r\n for dev in devs:\r\n self.monitors[dev.properties['name']]['widget'].show()\r\n self.monitors[dev.properties['name']]['widget'].clear_data()",
"def _monitor_loop(self):\n # First check if monitor is allowed to start\n if self._busy or n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Stop the subsystem and any background services. | def stop(self):
if self.__state != runlevel.STATE_RUNNING:
raise SubsystemStateError('can not stop subsystem %s: subsystem is not running.'.format(self.__class__.__name__))
self._stop() | [
"async def stop(self):\n sv_type = \"service\" if self.depth < 2 else \"sub-service\"\n self.logger.debug(self.indented(f\"Stopping {sv_type} {self.name}.\"))\n\n # Stop the sub-services\n for name, service in tuple(self.services.items()):\n await service.stop()\n d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Subsysteminternal method to indicate that the system is starting. | def _starting(self):
self.__state = runlevel.STATE_STARTING | [
"def _started(self):\n\n self.active = True\n self.stopped = False",
"def start(self):\n self.logger.debug('Server - td-agent-bit - start call.')\n self.change_service_status(\"start\")",
"def _is_started(self):\n cmd = \"sudo service watchdog status\"\n run_process(cmd... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Subsysteminternal method to indicate that the system is stopping. | def _stopping(self):
self.__state = runlevel.STATE_STOPPING | [
"def request_stop(self):\n self._stop_requested = True",
"def stop(self):\n \n if self.__state != runlevel.STATE_RUNNING:\n raise SubsystemStateError('can not stop subsystem %s: subsystem is not running.'.format(self.__class__.__name__))\n \n self._stop()",
"def stop(se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test Discriminator Creation to run without error. | def test_discriminator_creation(self):
input_image_width = 40
input_channels = 1
self.discriminator = Discriminator(
input_image_width=input_image_width,
input_channels=input_channels
) | [
"def test_create(self):\n harmonized_trait = factories.HarmonizedTraitFactory.create()\n self.assertIsInstance(harmonized_trait, models.HarmonizedTrait)",
"def make_discriminator():\n\n input_data = Input(shape=(IMG_DIM[0], IMG_DIM[1], 1))\n x = Conv2D(D, (5, 5), strides=(2,2), padding='same')... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |