query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Parses the provided filelike object. The parser will process the data and trigger the corresponding events in the eventhandler which was passed at initialization. | def parse(self, fobj: Union[TextIO, str]):
isfilename = isinstance(fobj, str)
if isfilename:
fp = open(fobj, "r")
self._fname = fobj
else:
fp = fobj
for line in fp.readlines():
self._parse(line)
self._currline += 1
if is... | [
"def parse(cls, fileobj): # -> Self@BaseDescriptor:\n ...",
"def feed(self, fileobj):\n self._parser.feed(fileobj)",
"def ParseFileObject(self, parser_mediator, file_object):\n filename = parser_mediator.GetFilename()\n\n if filename != self._FILENAME:\n raise errors.WrongParser('Not a... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generating prediction of image url | def predict(self,url):
# get image
response = requests.get(url)
img = Image.open(BytesIO(response.content))
transform = transforms.Compose([transforms.Grayscale(),
transforms.Resize((128,128)),
t... | [
"def image_url_to_prediction(self, img_url):\n absolute = settings.BASE_DIR + img_url\n img = Image.open(absolute)\n flat = np.array(img).flatten()\n flat = np.array(flat) / 255.0\n return self.predict_instance(flat)",
"def predict_url(*args): \n return gennet.predict_url(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Fetch the first occurance of the roundtrip time of a traceroute output | def extract_rtt_from_line(self, line):
if line:
rtt = line.split(' ms')[0].split()[-1]
return rtt
else:
return None | [
"def roundtrip_time(self) -> Optional[float]:\n return self._latest_roundtrip_time",
"def get_time(network, road_id):\n return network[0][road_id][4]",
"def get_traceroute_output(self):\n url = self.source['url']\n if 'post_data' in self.source:\n context = self.source['post_dat... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Use Naive Bayes classification to classify the email in the given file. Inputs | def classify_new_email(filename,probabilities_by_category,prior_by_category):
### TODO: Write your code here
spam_distribution = 0
ham_distribution = 0
word_frequency = util.get_word_freq([filename])
for w in word_frequency:
if w in probabilities_by_category[0]:
spam_distributio... | [
"def classify (classes, filename):\n answers = []\n print 'Classifying', filename\n moneytag = re.compile('($)|(%)|(\\d+.\\d{2})|(\\d+)')\n for c in classes:\n score = 0\n #***\n # Here, compute the naive bayes score for a file for a given class by:\n # 1. Reading in each wor... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set aesthetic figure dimensions to avoid scaling in latex. | def set_size(width, fraction=1):
# Width of figure
fig_width_pt = width * fraction
# Convert from pt to inches
inches_per_pt = 1 / 72.27
# Golden ratio to set aesthetic figure height
golden_ratio = (5**.5 - 1) / 2
# Figure width in inches
fig_width_in = fi... | [
"def change_dimensions(self, event):\n width = self.parent.winfo_width()/self.Fig.get_dpi()\n height = self.parent.winfo_height()/self.Fig.get_dpi()\n self.Fig.set_size_inches(w=width, h=height)",
"def change_dimensions(self, event):\n width = event.width/self.Fig.get_dpi()\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the path to the 'history' directory of a run if it exists. | def history_path(root):
history = os.path.join(root, "history")
if os.path.isdir(history):
return history
else:
raise ValueError(f"Directory {root} is not a valid root directory.") | [
"def history_path(base_path: Path, training_run):\n return base_path / _TRAINING_RUNS_DIR / training_run / _HISTORY_FILE_NAME",
"def histpath(self):\n from os import path\n from fortpy import settings\n return path.join(settings.cache_directory, \"autotest-history\")",
"def get_history_f... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the absolute paths of all completed segments of the run. | def segment_paths(root):
directories = []
history = history_path(root)
for d in os.listdir(history):
path = os.path.join(history, d)
if os.path.isdir(path):
directories.append(path)
return sorted(directories) | [
"def fsPathsComplete(self):\n return [os.path.join(self.mountPoint, path) for path in self.fsPaths]",
"def get_all_fullpaths(self):\n files = []\n for mf in self.manifests:\n files.extend(self.manifests[mf].get_fullpaths())\n return files",
"def get_all(self):\n ret... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a list of files that are present in all segment directories. This means that if only some segments have outputs combined via mppnccombine, they will not show up in the list. | def filenames(root, combined=None):
segments = segment_paths(root)
globname = "*.nc*" if combined is None else "*.nc"
files = []
for segment in segments:
globstring = os.path.join(segment, globname)
segment_files = sorted(glob.glob(globstring))
segment_files = [os.path.basename(f... | [
"def output_files(self):\n output_files = []\n for split in self.split_files:\n output_files.extend(split.filepaths)\n return output_files",
"def files_missing(rootdir):\n missing = set()\n for asset in assets:\n path = joinpaths(rootdir, asset)\n if not os.path.isfile(path):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to get the probe function based on input args kev=Electron energy in keV ap = Objective aperture semiangle in mrad Cc = Chromatic aberration coefficient in mm dE = Delta E in eV ds=Source size in Angstroms rmax=Size of slice in Angstroms Cs=Spherical aberration Cs in mm df=Defocus in Angstroms nx=number of pix... | def get_probe_function(self, args):
keV = args['electron_energy']
ap = args['aperture_semiangle']
try:
Cc = args['chromatic_aberration_coefficient']
except:
Cc = 0.0
try:
dE = args['delta_E']
except:
dE = 0.0
#Cs=ar... | [
"def EKV(V_d, V_g, V_s = 0, V_t = 26*1e-3 ,V_tn = 0.4, V_am = 50*1e6, L=540*1e-9, my=380*1e-5):\n e_ox = 3.45*1e-11\n t_ox = 2.7*1e-9\n C_ox = e_ox/t_ox\n k_n = my*C_ox\n I_s = 2*k_n*(V_t**2)\n \n Lam = 1/(V_am*L) #proceess paramterer V_a' * Channel length Im gonna make this 0.8 to start\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
function V = stempot(xmax,ymax,nx,ny,potfile) % STEMPOT Generate a Projected Potential % inputs xmax, ymax are the size of the slice in angstroms % nx,ny are the number of pixels in the x and y directions | def stempot(self,xmax,ymax,nx,ny,atms,pixelshift,scalefactor):
#zed=2 for rutherford scattering of the nucleus, less for screening
zed = 1.7
ix = numpy.arange(1.0,nx)
iy = numpy.arange(1.0,ny)
dx = xmax/nx
dy = ymax/ny
rx = numpy.arange(0,xmax-dx,dx)
ry =... | [
"def SectPhot(conf, dataimg, n_sectors = 19, minlevel = 0):\n\n\n maskb = dataimg.mask\n\n eps = 1 - conf.qarg\n\n #if ellconf.dplot:\n plt.clf()\n print(\"\")\n\n ############\n # I have to switch x and y values because they are different axes for\n # numpy:\n #if ellconf.flagmodel == Fa... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Setup to repair ships | def pressrepairships(self):
self.mode.systemmenu.press5()
self.mode.systemmenu.createRepairShipsGui() | [
"def repair(self):\n\t\tfor ship in self.states['shiplist']:\n\t\t\tship.repair\n\t\t\t\n\t\texisting_Fleets.extend([self])\n\t\treturn 'Whee'",
"def createShips(self):\n for shipID, myShipDict in self.shipBattle.shipsDict.iteritems():\n myShip = anwp.war.ship.Ship(myShipDict)\n myShi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Setup to upgrade ships | def pressupgradeships(self):
self.mode.systemmenu.press5()
self.mode.systemmenu.createUpgradeShipsGui() | [
"def upgrade():\n config = ConfigManager()\n apps = config['apps']\n for i, app in progressbar(enumerate(apps), redirect_stdout=True):\n z = Zap(app)\n if i == 0:\n z.update(show_spinner=False)\n else:\n z.update(check_appimage_update=False, show_spinner=False)",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Context manager that uses the current SSH confg to switch Fabric to a specific hostname. Updates hostname and port. | def this_hostname(hostname):
host_config = ssh_config(hostname)
host_string = hostname
port = host_config.get("port", env.default_port)
with settings(host_string=host_string,
port=port):
yield | [
"def hostname_set():\n try:\n new_hostname = request_parsers.hostname.parse_hostname(flask.request)\n hostname.change(new_hostname)\n return json_response.success()\n except request_parsers.errors.Error as e:\n return json_response.error('Invalid input: %s' % str(e)), 200\n exce... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retreive the EnvironmentDefinition from the fabric env. | def _get_environmentdef():
if 'environmentdef' not in env:
abort("Environment needs to be configured")
environmentdef = env.environmentdef
# If we're running via `fab`, we should restrict the environment
# to the current host.
if env.host_string:
environmentdef = environmentdef.wit... | [
"def get_environment(env_name: str) -> Environment:\n _check_active_client()\n envs = _merlin_client.list_environment() # type: ignore\n for env in envs:\n if env.name == env_name:\n return env\n return None # type: ignore",
"def _get_environment(self):\n if self._cache.get(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Iterate over all hosts in the configured environment. | def iter_hosts():
environmentdef = _get_environmentdef()
for host in environmentdef.hosts():
# fabric needs the host if we're calling from main()
with this_hostname(host.host):
yield host | [
"def iter_hosts_and_roles():\n environmentdef = _get_environmentdef()\n\n for host_and_role in environmentdef.all():\n # fabric needs the host if we're calling from main()\n with this_hostname(host_and_role.host):\n yield host_and_role",
"def get_allhosts():\n connection, tab... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Iterate over all hosts and roles in the configured environment. | def iter_hosts_and_roles():
environmentdef = _get_environmentdef()
for host_and_role in environmentdef.all():
# fabric needs the host if we're calling from main()
with this_hostname(host_and_role.host):
yield host_and_role | [
"def iter_hosts():\n environmentdef = _get_environmentdef()\n\n for host in environmentdef.hosts():\n # fabric needs the host if we're calling from main()\n with this_hostname(host.host):\n yield host",
"def hostroles(restrict=None):\n for role in env.roles:\n if not restr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This method configures the self.log entity for log handling. | def _configure_logging(self):
self.log_level = Scaffold.LOG_LEVEL_MAP.get(self.log_level, ERROR)
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
# assign the windmill instance logger
#logging.basicConfig()
self.log = logging.getLogger(self.n... | [
"def _configure_logging(self):\n pass",
"def set_log(self, log):\n self.log = log",
"def set_logger(self, log):\n self.log = log",
"def _configure_logger(self,o_log=None):\n\n assert type(o_log) in [type(None),str,PyposmatLogFile]\n\n if type(o_log) is PyposmatLogFile:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Collect and configure the configuration options for instantiation of Scaffold and child classes. This method operates by taking an argument list in ArgParse format and creating an argument list. The argument list is created by invoking the configuration_option method defined by each of the progenitor classes derived fr... | def _execute_configuration(self, argv=None):
if argv is None:
argv = [] # just create an empty arg list
arg_parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
# if this is the command line args directly, them we need to remove the
... | [
"def defineConfiguration(self):\n def validate(value, datatype):\n if type(value) is not dict:\n raise olof.tools.validation.ValidationError()\n\n d = {}\n for i in value:\n if type(i) is str and type(value[i]) is datatype:\n d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Validate inputs that might depend on each other and cannot be validated by the spec. Also define dictionary `inputs` in the context, that will contain the inputs for the calculation that will be launched in the `run_calculation` step. | def validate_inputs(self):
self.ctx.inputs = AttributeDict(self.exposed_inputs(FleurCalculation))
self.ctx.max_queue_nodes = self.inputs.add_comp_para['max_queue_nodes']
self.ctx.max_queue_wallclock_sec = self.inputs.add_comp_para['max_queue_wallclock_sec']
input_options = self.inputs.... | [
"def validate_inputs(inputs, ctx=None): # pylint: disable=unused-argument",
"def validate_inputs(self): # pylint: disable=too-many-branches, too-many-statements\n self.ctx.inputs = AttributeDict({\n 'structure': self.inputs.calc.structure,\n 'code': self.inputs.calc.code,\n }... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This routine checks if the total number of requested cpus is a factor of kpts and makes an optimisation. If suggested number of num_mpiprocs_per_machine is 60% smaller than requested, it throws an exit code and calculation stop withour submission. | def check_kpts(self):
if 'fleurinp' in self.ctx.inputs:
fleurinp = self.ctx.inputs.fleurinp
else:
fleurinp = get_fleurinp_from_remote_data(self.ctx.inputs.parent_folder)
only_even_MPI = self.inputs.add_comp_para['only_even_MPI']
forbid_single_mpi = self.inputs.ad... | [
"def _modify_cpu_questions(self, node, total_cpus, numa_nodes):\n\n print(\n \"\\nYour system has {} core(s) and {} Numa Nodes.\".format(\n total_cpus, len(numa_nodes)\n )\n )\n print(\n \"To begin, we suggest not reserving any cores for \"\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculation failed for unknown reason. | def _handle_general_error(self, calculation):
self.ctx.restart_calc = calculation
self.ctx.is_finished = True
self.report('Calculation failed for a reason that can not be resolved automatically')
self.results()
return ProcessHandlerReport(True, self.exit_codes.ERROR_SOMETHING_WEN... | [
"def erro_quantizacao(sinal,sinal_quantificado):\r\n return sinal-sinal_quantificado",
"def _handle_unexpected_failure(self, calculation, exception=None):\n if exception:\n self.report('{}'.format(exception))\n\n # if self.ctx.unexpected_failure:\n # self.report(\n # ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sometimes relaxation calculation fails with Diraq problem which is usually caused by problems with reusing charge density. In this case we resubmit the calculation, dropping the input cdn. | def _handle_dirac_equation(self, calculation):
# try to drop remote folder and see if it helps
is_fleurinp_from_relax = False
if 'fleurinp' in self.ctx.inputs:
if 'relax.xml' in self.ctx.inputs.fleurinp.files:
is_fleurinp_from_relax = True
if 'parent_folder'... | [
"def _invalidate_cdns(comparison: wood.comparison.Comparison, domain: str) \\\n -> None:\n # first, as closest to the source\n cloudfront = wood.cloudfront.Invalidator(\n CF_CLIENT,\n os.environ['CLOUDFRONT_DISTRIBUTION'],\n 'Deploying ' + os.environ['TRAVIS_TAG'])\n cloudfront.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculation failed due to lack of memory. Probably works for JURECA only, has to be tested for other systems. | def _handle_not_enough_memory(self, calculation):
if not self.ctx.can_be_optimised:
self.ctx.restart_calc = calculation
self.ctx.is_finished = True
self.report('I am not allowed to optimize your settings. Consider providing at least'
'num_machines and... | [
"def test_out_of_memory(self):\n code = '[0] * 999999999999999'\n self.throws(code, MEMORYERROR)",
"def _check_memory_errors(self, global_data, total_allocatable_memory, quantity_, aggregate_memory_failures):\n aggregate_memory_data = {}\n error_msg = \"\"\n msg = ''\n to... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If calculation fails due to time limits, we simply resubmit it. | def _handle_time_limits(self, calculation):
from aiida.common.exceptions import NotExistent
# if previous calculation failed for the same reason, do not restart
try:
prev_calculation_remote = calculation.base.links.get_incoming().get_node_by_label('parent_folder')
prev_c... | [
"def _resubmit(self, *args, **kwargs):\n self.retry()",
"def handle_rate_limit():\n now = datetime.now()\n requests = RequestAPI.objects.last()\n if requests is None:\n requests = RequestAPI.objects.create(total_request=1, date=now)\n\n date_windows_request = now - re... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check whether the remote folder of the given calculation can be resubmitted | def _is_remote_reusable(inputs, calculation):
can_use_remote = False
#If no charge density file is available to restart from the calculation will except
#with a not nice error message. So we can only reuse the charge density if these files are available
retrieved_filenames = calculation.base.links.get_o... | [
"def has_required_remote_permission(self, state, action):\n if self.subnet_public(action.target[0]):\n return True\n\n for src_addr in self.address_space:\n if not state.host_compromised(src_addr):\n continue\n if action.is_scan() and \\\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the names for each theme. | def theme_names(self):
return [theme.get('name', 'Error') for theme in self.themes] | [
"def get_theme_names() -> Collection[str]:\n\n return get_themes().keys()",
"def get_themes(self):\n return self.style.theme_names()",
"def list_themes():\n\n theme_list = os.listdir(path.dirname(path.abspath(__file__))+'/themes/')\n theme_list = [x.split(\".\")[0] for x in theme_list if \"__\" ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the theme named name. Paramters | def theme_named(self, name):
for theme in self.themes:
if theme.get('name', 'Error') == name:
return theme | [
"def get_theme(self) -> str:\n return self.theme or self.account.theme",
"def theme_name(context):\n return {'THEME_NAME': settings.THEME_NAME}",
"def _get_theme_selected():\n\n try:\n theme_selected = Configuration.objects.filter(group='theme', key='selected')[0]\n theme_name = theme... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
create a list of num_visualize most frequent words to visualize on TensorBoard. saved to visualization/vocab_[num_visualize].tsv | def most_common_words(visual_fld, num_visualize):
words = open(os.path.join(visual_fld, 'vocab.tsv'), 'r').readlines()[:num_visualize]
words = [word for word in words]
file = open(os.path.join(visual_fld, 'vocab_' + str(num_visualize) + '.tsv'), 'w')
for word in words:
file.write(word)
file.... | [
"def most_common_words(n):\n with open(os.path.join('visualization', 'vocab.tsv')) as fd:\n words = fd.readlines()[:n]\n words = [word for word in words]\n save_path = os.path.join('visualization', 'vocab_' + str(n) + '.tsv')\n with open(save_path, 'w') as fd:\n for word in words:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compute a gradient clipping coefficient based on gradient norm. | def clip_gradient(model, clip):
totalnorm = 0
for p in model.parameters():
modulenorm = p.grad.data.norm()
totalnorm += modulenorm ** 2
totalnorm = math.sqrt(totalnorm)
return min(1, clip / (totalnorm + 1e-6)) | [
"def clip_gradient(parameters, clip):\n totalnorm = 0\n for p in parameters:\n modulenorm = p.grad.data.norm()\n totalnorm += modulenorm ** 2\n totalnorm = math.sqrt(totalnorm)\n return min(1, clip / (totalnorm + 1e-6))",
"def clip_gradient(model, clip_norm):\n totalnorm = 0\n for ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sends mail through localhost. Takes error message and intended recipient as arguments. | def sendmail(message, recipient):
import smtplib
fromaddr = "pythonprogram@someaddress.com"
toaddrs = recipient + "@someaddress.com"
# Add the From: and To: headers at the start!
msg = ("From: %s\r\nTo: %s\r\n\r\n" %(fromaddr, ", ".join(toaddrs)))
msg = msg + str(message[0]) + message[1]... | [
"def send_email():\n send_mail(\"You've got some problem.\", 'REPAIR IT', 'dimazarj2009@rambler.ru',\n ['dimazarj2009@rambler.ru'], fail_silently=False,)",
"def sendEmail(sender, recipient, msg):\n\n ## Create a mailer object \n smtp = smtplib.SMTP()\n\n ## Connect to the outgoing mail se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Forms the MySQL statement according to the type of statement | def form(self, table, column, info):
info = info.replace(" ","")
data = info.split(',')
value = "'" + data[0]
for i in xrange(1, len(data)):
value = value + "', '" + data[i]
value = value + "'"
if self.type == "select":
statement = """SELECT * FRO... | [
"def mogrify_sql_statement(self, content):\n sql = content[0]\n args = content[1]\n\n if self.dbmi.__name__ == \"psycopg2\":\n if len(args) == 0:\n return sql\n else:\n if self.connected:\n try:\n retu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The main function creates and controls the MySQLStatement instance in accordance with the user's input. | def main():
request = MySQLStatement()
try:
request.type(statement_type)
phrase = request.form(table, columns, values)
cur = connection(database)
results = request.execute(phrase, table, cur)
print "Results:\n", results
except MySQLdb.Error, e:
sendmail(... | [
"def main():\n cur, conn = create_database()\n \n drop_tables(cur, conn)\n create_tables(cur, conn)\n\n conn.close()",
"def main():\n cur, conn = create_database()\n \n drop_tables(cur, conn)\n create_tables(cur, conn)\n\n cur.close();\n conn.close()",
"def run (self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A shortcut to create a program from a list of nodes. | def make_program(*nodes: base.Node, name: str = 'launchpad'):
program = Program(name)
for node in nodes:
program.add_node(node)
return program | [
"def gen_program(program):\n cmd_stack = []\n\n cmd = (LABEL, \"__main__\")\n cmd_stack.append(cmd)\n\n mapping = Mappings(START_REG_VAR_MAP, [], [], [])\n\n phrases = program.get_phrases()\n main_function = ast_generator_c.DeclareFunc(None, ast_generator_c.Function(\n ast_generator_c.VarVa... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
returns the probability of a loss | def get_probability_loss(self):
return sum(self._loss)/len(self._loss) | [
"def get_loss(self):\n return self.loss / self.cnt",
"def calculate_perplexity(loss):\n return math.exp(float(loss)) if loss < 300 else float(\"inf\")",
"def compute_perplexity(self,loss: float):\n return math.exp(loss)",
"def fnn_policy_loss(cumulative_return, value_estimated, prob_action, p... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Applies a variety of morphological operations to improve the detection of worms in the image. Takes 0.030 s on MUSSORGSKY for a typical frame region Takes 0.030 s in MATLAB too | def applyMorphologicalCleaning(self, image): | [
"def step_1_isolate_worms(img, is_w1=True):\n # w2 can cause border problems, setting the outside area to similar to the border colour\n # begins to alleviate this issue\n if not is_w1:\n img[img < 20] = 50\n\n # create binary image, where worms are white, background is black (w2 keeps border, wh... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the expected length of a worm in pixels | def expectedWormLengthPixels(self):
return self.expectedWormLength * self.pixelSize | [
"def expectedWormWidthPixels(self):\n return self.expectedWormWidth * self.pixelSize",
"def expectedWormAreaPixels(self):\n return (self.expectedWormLengthPixels() *\n self.expectedWormWidthPixels())",
"def get_size(self):\n return len(self.glowworms)",
"def pixel_len(self)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the expected width of a worm in pixels | def expectedWormWidthPixels(self):
return self.expectedWormWidth * self.pixelSize | [
"def expectedWormLengthPixels(self):\n return self.expectedWormLength * self.pixelSize",
"def expectedWormAreaPixels(self):\n return (self.expectedWormLengthPixels() *\n self.expectedWormWidthPixels())",
"def getWidth(self):\n wsum = 0.0\n for quad in self._quadrilater... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the expected area of a worm in pixels^2 | def expectedWormAreaPixels(self):
return (self.expectedWormLengthPixels() *
self.expectedWormWidthPixels()) | [
"def expectedWormLengthPixels(self):\n return self.expectedWormLength * self.pixelSize",
"def expectedWormWidthPixels(self):\n return self.expectedWormWidth * self.pixelSize",
"def area_of_my_square(self):\n return self.width * self.width",
"def pixel_area(self):\n # FIXME: Correct... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
identifies 1connected pixels in image | def find1Cpixels(bwImage):
# fills pixels matching the following neighborhoods:
hoods = [[[1, 0, 0],
[0, 1, 0],
[0, 0, 0]],
[[0, 1, 0],
[0, 1, 0],
[0, 0, 0]],
[[0, 0, 1],
[0, 1, 0],
[0, 0, 0]],
... | [
"def get_connected_components(img):\n already_labeled = []\n connected_components = []\n pixel_queue = []\n\n def get_fg_neighbors(row,col):\n neighbors = []\n min_row = max(row-1,0)\n max_row = min(row+1, len(img)-1)\n min_col = max(col-1,0)\n max_col = min(col+1, len... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Pass derivatives for ``BCEWithLogitsLoss``. | def __init__(self):
super().__init__(derivatives=BCELossWithLogitsDerivatives()) | [
"def logit_deriv(y):\n# if y.any() < 0.0 or y.any() > 1.0:\n# raise Exception\n\n return y*(1-y)",
"def grad_log(self, X):\n # \"\"\"\n # Evaluate the gradients (with respect to the input) of the log density at\n # each of the n points in X. This is the score function.\n\n # X... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Finds a contour around the receipt in the given image. Returns the bounding box and the binary image | def find_receipt_box(image):
# gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
gray = cv.medianBlur(image, 15, 0)
_, thresh = cv.threshold(gray, 255, 125, cv.THRESH_BINARY | cv.THRESH_OTSU)
k = np.ones((25, 25))
thresh = cv.erode(thresh, k, iterations=1)
thresh = cv.dilate(thresh, k, iterations=1)
... | [
"def find_bbox(self):\n lower_wal = (17, 250, 241) # (25, 22, 19) (22, 255, 246)\n upper_wal = (27, 256, 251) # (25, 22, 19)\n lower_bp = (99, 211, 241) # (98, 90, 77) (104, 216, 246)\n upper_bp = (109, 221, 251) # (98, 90, 77)\n lower_rc = (99, 211, 208) # (39, 35, 25) (104, 216,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test init with non json key file and missing email. | def test_init_non_json_missing_email(self, mock_creds):
file_data = 'non json file data'
file_mock = mock.mock_open(read_data=file_data)
with mock.patch.object(moves.builtins, 'open', file_mock):
self.assertRaises(errors.Credentials,
credentials.Credenti... | [
"def test_init__no_sdk_key_no_datafile__fails(self, _):\n self.assertRaisesRegex(\n optimizely_exceptions.InvalidInputException,\n enums.Errors.MISSING_SDK_KEY,\n config_manager.PollingConfigManager,\n sdk_key=None,\n datafile=None,\n )",
"def t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test authorization property calls get_access_token only once. | def test_authorization_multiple_accesses(self, mock_init, mock_get_token):
creds = credentials.Credentials('file')
# On real init we would have had access_token set to None
creds.access_token = None
auth = creds.authorization
mock_get_token.reset_mock()
# Second access t... | [
"def test_get_access_token(self):\n pass",
"def test_read_o_auth_access_token(self):\n pass",
"def test_patch_o_auth_access_token(self):\n pass",
"def test_list_o_auth_access_token(self):\n pass",
"def test_replace_o_auth_access_token(self):\n pass",
"def test_user_obtai... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Extract all the concets in VIVO and organize them into a dictionary keyed by concept uri. Data for the concept includes the concet name and all concepts cooccuring withthe concept and the count of the cooccurances | def make_concordance(debug=False):
query = """
SELECT ?uri ?name
WHERE {
?uri a skos:Concept .
?uri rdfs:label ?name .
}"""
result = vivo_sparql_query(query)
if 'results' in result and 'bindings' in result['results']:
rows = result["results"]["bindings"]
else:
... | [
"def list_ec_vit(self):\n dico_vit = {}\n for term in self.result: # itère les termes\n if term.predicate == \"enzymeV\": # ne retient que les terms enzymeV\n dico_vit[term.arguments[0]] = dico_vit.get(term.arguments[0], []) + [term.arguments[1]]\n # si la cl... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculate the Spin Husimi Q function with several different methods | def spin_husimi_qfunc(density_op, theta, phi, *, method="su2"):
if method == "qutip":
Q, *_ = spin_q_function(density_op, theta, phi)
return Q
elif method == "vectorised":
return my_spin_q_func(density_op, theta, phi)
elif method == "su2":
st = np.sin(theta / 2)
ct = ... | [
"def sCurves(qubit,jba,variable = \"p1x\",data = None,ntimes = 20,optimize = \"v20\"):\n def getVoltageBounds(v0,jba,variable,ntimes):\n v = v0\n jba.setVoltage(v)\n acqiris.bifurcationMap(ntimes = ntimes)\n p = acqiris.Psw()[variable]\n \n while p > 0.03 and v < v0*2.0:\n v*=1.05\n jba... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
three dimensional ring == donut | def getDonut(width=2, size=(25, 25, 25)):
x, y, z = size
assert width < z / 2
# This is a single planr slice of ring
ringPlane = getRing(0.25, 0.5, size=(x, y))
# Stack up those slices starting form the center
donutArray = np.zeros(size, dtype=np.uint8)
zStart = z // 2
for n in range(w... | [
"def stokes_right_circular():\n return np.array([1, 0, 0, 1])",
"def ring3(render=OpenMayaRender.MGL_LINE_STRIP):\n gl_ft.glBegin(render)\n gl_ft.glVertex3f(-0.484769016504, 1.49011611938e-08, -0.661362051964)\n gl_ft.glVertex3f(-0.398055821657, 1.49011611938e-08, -0.716904640198)\n gl_ft.glVertex3... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Handles listing of a suppression | def handleList(self, confInfo):
# Get requested action
actionStr = str(self.requestedAction)
if actionStr in Suppressions.REQUESTED_ACTIONS:
actionStr = Suppressions.REQUESTED_ACTIONS[actionStr]
logger.info('Entering %s', actionStr)
self.handleRe... | [
"def suppressionlist(self, page=1, page_size=1000, order_field=\"email\", order_direction=\"asc\"):\n params = {\n \"page\": page,\n \"pagesize\": page_size,\n \"orderfield\": order_field,\n \"orderdirection\": order_direction}\n response = self._get(self.ur... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set all children of the mother. | def set_children(self, mother, list_of_children):
# convert name to Member node (should check for validity)
mom_node = self.names_to_nodes[mother]
# add each child
for c in list_of_children:
# create Member node for a child
c_member = Member(c) ... | [
"def setChildren(self, children):\n self.children = children",
"def children(self, children):\n self._children = children",
"def children(self, children):\n\n self._children = children",
"def children(self, values):\n self._children = values",
"def mother(self, mother):\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns True or False whether mother is parent of kid. | def is_parent(self, mother, kid):
mom_node = self.names_to_nodes[mother]
child_node = self.names_to_nodes[kid]
return child_node.is_parent(mom_node) | [
"def is_child(self, kid, mother): \n mom_node = self.names_to_nodes[mother] \n child_node = self.names_to_nodes[kid]\n return mom_node.is_child(child_node)",
"def _is_parent(a, b):\n # type: (PredContext, PredContext) -> bool\n while b and a is not b:\n b = getattr(b, 'p... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns True or False whether kid is child of mother. | def is_child(self, kid, mother):
mom_node = self.names_to_nodes[mother]
child_node = self.names_to_nodes[kid]
return mom_node.is_child(child_node) | [
"def is_parent(self, mother, kid):\n mom_node = self.names_to_nodes[mother]\n child_node = self.names_to_nodes[kid]\n return child_node.is_parent(mom_node)",
"def is_child_of(self,child_obj_id,parent_obj_id):\n obj = self[child_obj_id]\n return obj['parent'] == parent_obj_id",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Plays a rock paper scissor game. | def rock_paper_scissors():
rps = ["rock", "paper", "scissors"]
wannaplay = input("do you want to play rock paper scissors? ")
if wannaplay == "yes":
computerpick = random.choice(rps)
playerpick = input("what do you choose?")
if computerpick == "rock":
if playerpick == "sc... | [
"def rps_function():\n randNumber = random.randint(1,3)\n companswer = \"Scissor\"\n if randNumber == 1:\n companswer = \"Rock\"\n elif randNumber == 2:\n companswer = \"Paper\"\n\n answer = q.select(\"Select Rock, Paper or Scissors\", choices=[\"Rock\", \"Paper\", \"Scissor\"]).ask()\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the key through a value. | def get(cls, value):
for k in cls:
if k.value == value:
return k
raise KeyError(f'Cannot get key by value "{value}" of {cls}') | [
"def get_key(self, value, default=None):\n return self._reverse_map.get(value, default)",
"def get_keyed_item(seq, value, key=\"name\"):\n for s in seq:\n if s[key] == value:\n return s",
"def get_key(value, key, key_mapping):\n # return corrected key if necessary\n if value in... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Handle coreutils sort program calls. kwargs are passed directly from the calling method (self.coreutils_sort). This method figures out, given how this BedTool was constructed, what to send to BEDTools programs for example, an open file to stdin with the `` argument, or a filename with the `a` argument. instream can be ... | def handle_coreutils_sort_kwargs(self, prog='sort', instream=None, **kwargs):
pybedtools.logger.debug(
'BedTool.handle_coreutils_sort_kwargs() got these kwargs:\n%s',
pprint.pformat(kwargs))
stdin = None
# Decide how to send instream to sort.
# If it's a BedTool, then get underlying st... | [
"def start_unix_sort(mem):\n cmdline = shlex.split(\"sort -S%s -k1,1g -\" % mem)\n logging.info(\"sort call: %s\", cmdline)\n sortproc = subprocess.Popen(cmdline, stdin = subprocess.PIPE, \n stdout = subprocess.PIPE, shell = False)\n cutproc = subprocess.Popen(shlex.split(\"cut -f2-\"), \n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
self.X = self.scale ((self.I+.5)/self.dims) + self.translate[0] self.Y = self.scale ((self.J+.5)/self.dims) + self.translate[1] self.Z = self.scale ((self.K+.5)/self.dims) + self.translate[2] klopt dit, centroid vs vertice? | def getVerticePosition(self):
#def getvoxelpos(model,scale,dims,translate,i,j,k): #centroid!
return(self.X,self.Y,self.Z) | [
"def update_transform(self):\n\n self.a = self.scale * self.pixel_size * math.cos(self.angle)\n self.d = self.scale * self.pixel_size * math.sin(self.angle)\n self.b = self.d\n self.e = -self.a\n self.c = self.point.x() - self.a*self.width/2.0 - self.b*self.height/2.0\n sel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the unit vector of the vector. | def unit_vector(vector):
#print 'unit_vector'
#print vector
#print type(vector)
#npvector = np.array(vector)
return vector / np.linalg.norm(vector) | [
"def unitVector(self): \n return self.scale(1/self.vectorLength())",
"def unit_vector(vector):\n mag_vec = mag(vector)\n uv = vector/mag_vec\n return uv",
"def _get_unit_vector(self, v):\n return v / np.linalg.norm(v)",
"def unit_vector(vector):\n print 'VECTOR: {}'.format(vector)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Save model to a pickle located at `path` | def save(self, path=None):
if path is None:
path = os.path.join(logger.get_dir(), "model.pkl")
with tempfile.TemporaryDirectory() as td:
save_state(os.path.join(td, "model"))
arc_name = os.path.join(td, "packed.zip")
with zipfile.ZipFile(arc_name, 'w') as... | [
"def save(path_to_model):\n pass",
"def serialize(self, path):\r\n newModelFitter = self.copy()\r\n with open(path, \"wb\") as fd:\r\n rpickle.dump(newModelFitter, fd)",
"def save_model(model, model_filepath):\n with open(model_filepath,'wb') as f:\n pickle.dump(model,f... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns solar noon in UTC based on 15degree timezones 0+7.5 LonDegE degrees longitude (180, 180) | def solar_noon_utc(LonDegE):
_timezone = array([-180, -172.5, -157.5, -142.5, -127.5, -112.5, -97.5, -82.5, -67.5, -52.5, -37.5, -22.5, -7.5, 7.5, 22.5, 37.5, 52.5, 67.5, 82.5, 97.5, 112.5, 127.5, 142.5, 157.5, 172.5, 180]).repeat(2, 0)[1:-1].reshape(-1, 2)
for i, (low, high) in enumer... | [
"def solar_noon_utc(self, date, longitude):\n \n julianday = self._julianday(date.day, date.month, date.year)\n\n newt = self._jday_to_jcentury(julianday + 0.5 + longitude / 360.0)\n\n eqtime = self._eq_of_time(newt)\n timeUTC = 720.0 + (longitude * 4.0) - eqtime\n\n timeUT... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return H2O in molecules/cm3 from RH (0100) and TEMP in K | def h2o_from_rh_and_temp(RH, TEMP):
TC = TEMP - 273.15
frh = RH / 100.
svp_millibar = 6.11 * 10**((7.5 * TC)/(TC+237.3))
svp_pa = svp_millibar * 100
vp_pa = svp_pa * frh
molecule_per_cubic_m = vp_pa * Avogadro / R / TEMP
molecule_per_cubic_cm = molecule_per_cubic_m * centi**3
#print RH, ... | [
"def calculate_delta_C_H2O(T, RH, wv_dict):\n\n deltaT = float(constants['deltaT'])\n \n c_H2O_sat_out=float(wv_dict[str(round(T-273.15))]) # convert from Kelvin to Celsius for lookup table\n c_H2O_sat_in=float(wv_dict[str(round(T-273.15+ deltaT))])\n \n deltaC_H2O = c_H2O_sat_in - (c_H2O_sat_out ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initialize a std environemnt | def initstdenv(TEMP = 298., P = 101325., ):
defenv = dict(TEMP = TEMP, P = P)
Update_M(None, defenv)
update_func_world(None, defenv)
del defenv | [
"def setup_environ(self):\n for k, v in six.iteritems(self.override_env):\n os.environ[k] = v\n self.env = dict((k, os.pathsep.join(os.path.normpath(p) for p in ps if p)) for k, ps in six.iteritems(self.env))\n for k, v in six.iteritems(self.env):\n sep = os.pathsep if (k.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
It executes the operational command specified in ExecuteOpCommandRequest. This is a streaming api | def ExecuteOpCommand(self, request, context):
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!') | [
"def _ExecuteOp(self, op):\r\n # If necessary, wait until back-off has expired before execution begins.\r\n if op.backoff is not None:\r\n yield gen.Task(IOLoop.current().add_timeout, op.backoff)\r\n\r\n # Enter execution scope for this operation, so that it can be accessed in OpContext, and so that o... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This RPC will return the configuration in the ephemeral database for Path specified in the request | def GetEphemeralConfig(self, request, context):
context.set_code(grpc.StatusCode.UNIMPLEMENTED)
context.set_details('Method not implemented!')
raise NotImplementedError('Method not implemented!') | [
"def get_config(self):\n return self.db_config",
"def get(self, path):\n\n config = get_config(self.config, path)\n\n return config",
"def config_store(self):\n url = self._url + \"/configStore\"\n params = {'f' : 'json'}\n return self._con.get(url, params)",
"def get... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Loads a vtk legacy file containing a ``POLYDATA`` data set. | def loadVTKPolydataFile(infile):
lines = None
with open(infile, 'rt') as f:
lines = f.readlines()
lines = [l.strip() for l in lines]
if lines[3] != 'DATASET POLYDATA':
raise ValueError('Only the POLYDATA data type is supported')
nVertices = int(lines[4].split()[1])
nPolygons... | [
"def loadAsVtkPolyData(self, file_name):\n vtk_data = self.loadAsVtkData(file_name)\n if self.file_format == 'vtk':\n if self.vtk_dataset_type == 'POLYDATA':\n vtk_poly_data = vtk_data\n else:\n vtk_poly_data = self.convertToPolyData(vtk_data)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test deleting a node from the Linked List given the node | def test_delete_node(self):
myObj = DLinkedList()
myObj.append(120)
myObj.append(100)
myObj.detete_node(myObj.head.next)
myObj.detete_node(myObj.head)
self.assertEqual(myObj.get_head(), None)
self.assertEqual(myObj.get_tail(), None) | [
"def test_delete(self):\n delete_test_list = DoubleLinkedList()\n delete_test_list.push(12)\n delete_test_list.push(123)\n delete_test_list.push(1234)\n delete_test_list.push(12345)\n delete_test_list.delete(123)\n self.assertEqual(delete_test_list.get_list()[1].get_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the relative path to a key, and interpolate any variables. | def relative(self, key):
return key.format(**self.variables) | [
"def json_full_path(base_path, key):\n if base_path is None or base_path == \"\":\n return key\n else:\n return f'{base_path}.{key}'",
"def _key_to_path(self, key: str) -> str:\n return os.path.abspath(os.path.normpath(os.path.join(self._directory, key)))",
"def resolve_full_gcp_key_p... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes file as input & returns a dictionary having name of layers with their code | def ret_layer_index(file):
names={}
for i in range(len(file[0])):
print(file[0][i][0][0][0])
names[file[0][i][0][0][0][0]]=i
print("Success layer_index")
return names | [
"def get_layers(layer_data: Dict[str, Any]) -> List[Layer]:\n try:\n l_data = layer_data['kicad_pcb']\n l_data = get_dict_by_key(l_data, 'layers')\n res: List[Layer] = list()\n for layer in l_data['layers']:\n layer_data = list(layer.values())[0]\n new_layer = La... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Asks for Layer Name & returns its weights & bias | def weight(layer_name):
layer_no=names[layer_name]
wb =file[0][layer_no][0][0][2]
w=wb[0][0]
b=wb[0][1]
name=file[0][layer_no][0][0][0]
assert name==layer_name
print("Success weight")
return w,b | [
"def __weights(self,layer, expected_layer_name):\r\n wb = self.__vgg_layers[0][layer][0][0][2]\r\n W = wb[0][0]\r\n b = wb[0][1]\r\n layer_name = self.__vgg_layers[0][layer][0][0][0][0]\r\n assert layer_name == expected_layer_name\r\n return W, b",
"def get_weights(mode... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Factory method that creates instances of Commands. | def create_command(cmd, args):
for cls in BaseCommand.__subclasses__():
if cls.cmd() == cmd:
return cls(args)
return None | [
"def factory(cmd, **default_kwargs):\n cmd = resolve_command(cmd)\n return Command(cmd)",
"def create_command(request: RequestTypes) -> Command:\n return Command(request=request)",
"def commandFactory(tuple):\n\n # Look up the command type from the type map and instantiate it\n # ``You ar... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initialize traced object, if no ancestors set as original. Params | def __init__(self, ancestors=None, **kwargs):
super().__init__(**kwargs)
if ancestors is None:
self.ancestors = {self.id}
# if given a set of traced objects
elif all(hasattr(a, 'ancestors') for a in ancestors):
self.ancestors = set(a for a.ance... | [
"def _initialize_ancestors(self, activity):\n for ancestor in self._ancestors:\n if ancestor.provenance is None:\n if os.path.exists(ancestor.provenance_file):\n ancestor.restore_provenance()\n else:\n ancestor.initialize_provenan... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculates the diff between left and right descriptors of a given ID and remove those descriptors if they're found (even if the data lenght is not the same and no diff is made) | def diff_right_left(id):
all_diff_data = ID.diff(id, ["left","right"])
if not all_diff_data or not all_diff_data["left_right"]:
abort(400)
ID.remove_all(id, ["left","right"])
return jsonify(all_diff_data["left_right"]) | [
"def diffmeld(self, other):\n srcelements = self.findmelds()\n tgtelements = other.findmelds()\n srcids = [ x.meldid() for x in srcelements ]\n tgtids = [ x.meldid() for x in tgtelements ]\n \n removed = []\n for srcelement in srcelements:\n if srcelement.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns true only if value only has base64 chars (AZ,az,09,+ or /) | def _is_base64(value):
#http://stackoverflow.com/questions/12315398/verify-is-a-string-is-encoded-in-base64-python
try:
enc = base64.b64encode(base64.b64decode(value)).strip()
return enc == value
except TypeError:
return False | [
"def is_base64(string):\n return (not re.match('^[0-9]+$', string)) and \\\n (len(string) % 4 == 0) and \\\n re.match('^[A-Za-z0-9+/]+[=]{0,2}$', string)",
"def is_base64(content: str) -> bool:\n try:\n sb_bytes = bytes(content, \"ascii\")\n base64.b64decode(sb_bytes)\n except... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method for getting spec (slope, intercept, and distance)of a line between two input nodes | def lineSpec(node1, node2):
if node1 == node2:
m = 0
b = 0
d = -1
return m, b, d
elif node1[0] == node2[0]: # parallel to y axis
m = True
b = node1[0]
d = abs(node2[1] - node1[1])
return... | [
"def get_line(p1, p2):\r\n slope = get_slope(p1, p2)\r\n intercept = get_intercept(p1, p2)\r\n\r\n return slope, intercept",
"def getLine(p1, p2):\r\n try:\r\n slope = float((p1[1] - p2[1]) / (p1[0] - p2[0]))\r\n yint = float((-1 * (p1[0])) * slope + p1[1])\r\n ret... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method for check if a point is on a line of two input nodes | def isPointOnLine(node1, node2, point):
m, b, d = geometry.lineSpec(node1, node2)
if d == -1: # if two nodes are the same
if node1 == point:
return True
else:
return False
else:
if m == True: # parallel to y axis
... | [
"def is_point_on_line(a: LineSegment, b: Point) -> bool:\n # Move the image, so that a.p1 is on (0|0)\n p2 = Point(a.p2.x - a.p1.x, a.p2.y - a.p1.y)\n a_tmp = LineSegment(Point(0, 0), p2)\n b_tmp = Point(b.x - a.p1.x, b.y - a.p1.y)\n r = crossproduct(a_tmp.p2, b_tmp)\n return abs(r) < EPSILON",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method for finding the nearest point on a straight infinite line form by two nodes from a point. This cannot guarantee the output point is on the line created by the two nodes. | def findNearPointOnLine(node1, node2, point):
p=point[0]
q=point[1]
a=node1[0]
b=node1[1]
c=node2[0]
d=node2[1]
x = ((a-p)*(d-b) + (q-b)*(c-a)) / ((d-b)**2+(c-a)**2) * (d-b) + p
y = ((a-p)*(d-b) + (q-b)*(c-a)) / ((d-b)**2+(c-a)**2) * (a-c) + q
... | [
"def _nearest_point_on_line(begin, end, point):\n b2e = _vec_sub(end, begin)\n b2p = _vec_sub(point, begin)\n nom = _vec_dot(b2p, b2e)\n denom = _vec_dot(b2e, b2e)\n if denom == 0.0:\n return begin\n u = nom / denom\n if u <= 0.0:\n return begin\n elif u >= 1.0:\n return... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method for finding a point aparting distance from node1 on the line of node1 and node2 | def findPointOnLine(node1, node2, distance):
m, b, _ = geometry.lineSpec(node1, node2)
xy = []
if m == True: # parallel to y axis
xy.append(node1[0])
if node1[1] <= node2[1]:
xy.append(node1[1] + distance)
else:
xy.appe... | [
"def _distance(point, line_point1, line_point2):\n vec1 = line_point1 - point\n vec2 = line_point2 - point\n distance = np.abs(np.cross(vec1,vec2)) / np.linalg.norm(line_point1-line_point2)\n return distance",
"def dist(self, node_0, node_1):\n coord_0, coord_1 =... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method for adding distance of edges in the input polyline graph | def addDistance(graph):
distanceList = graphCalculate._calculateDistance(graph)
for dist, edge in zip(distanceList, graph.edges(data=True)):
edge[2]['distance'] = dist | [
"def add_dist_edge(graph, node1, node2, unit = \"ft\"):\n\n coords1 = graph.nodes()[node1][\"coords\"]\n coords2 = graph.nodes()[node2][\"coords\"]\n\n\n graph.add_edge(node1, node2, weight = haversine(coords1,coords2, unit=unit))",
"def polyline_to_euclidean_distance(polyline):\n return [ox.euclidean... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method for adding center point coordinate of edges in the input polyline graph | def addCenter(graph, decimals=6):
for edge in graph.edges(data=True):
prevVertex = None
distnaceToGo = (edge[2]['distance']) / 2
for ind, vertex in enumerate(edge[2]['coordinates']):
if ind == 0:
prevVertex = vertex
else:
... | [
"def create_centerline(self):\n\n minx = int(min(self.inputGEOM.envelope.exterior.xy[0]))\n miny = int(min(self.inputGEOM.envelope.exterior.xy[1]))\n #加密边界\n border = np.array(self.densify_border(self.inputGEOM, minx, miny))\n #用边界生成Voronoi图\n vor = Voronoi(border)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method for split a polyline type graph at individual points of input point list | def splitLineAtPoint_backup(lineGraph, pointGraph, decimals=6):
lineGraphCopy = lineGraph.copy()
attrs = set(list(lineGraphCopy.edges(data=True)[0][2].keys()))
remains = set(['Ind', 'coordinates'] + list(attrs))
delAttrs = attrs.difference(remains)
for edge in lineGraphC... | [
"def _splitPoints(self, points, split):\n # validate split\n if not split:\n return [points]\n\n # complete split with adding start and end frames\n if split[0] != 0:\n split.insert(0, 0)\n\n if split[-1] != len(points):\n split.append(len(points))... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method for finding the nearest polyline feature and assign its id to the point feature | def nearest(pntGraph, lineGraph, criterion='', threshold=0):
_, spatialJoinDict = spatialjoin._spatialjoin(pntGraph, lineGraph, criterion, threshold)
for point in pntGraph.nodes(data=True):
point[1]['nearEdge'] = spatialJoinDict[point[1]['Ind']]
print('The Ind of the nearest polyline... | [
"def get_feature(feature_db, point):\n for feature in feature_db:\n if feature.location == point:\n return feature\n return None",
"def FindClosestPoint(self, ):\n ...",
"def GetClosestPoint(self):\n ...",
"def closest_point(self, point):\n return self.point_on_lin... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method for calculating Kernel Density Estimate using lixel graph and lixel center graph | def graphKDE(lixelGraph, lxcenterGraph, bandwidth, kernel = 'gaussian', diverge=True):
lookupDict, neighborsDict = interpolate._initiaize(lixelGraph, lxcenterGraph)
kernelDensity = []
for edge in lixelGraph.edges(data=True):
# extract center
center = edg... | [
"def get_kerneldensity_mapplot(self) -> None:",
"def kde_sklearn(x, x_grid, bandwidth=0.8, **kwargs):\n \n kde_skl = KernelDensity(bandwidth=bandwidth, **kwargs)\n #kde_skl = KernelDensity()\n kde_skl.fit(x[:, np.newaxis])\n # score_samples() returns the log-likelihood of the samples\n log_pdf =... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Build an (unmatched) Instruction, associating it with its position in the basic block inst is the underlying instruction bl is the basicblock ind is the index within the block | def __init__(self, inst: ghidra.program.model.listing.Instruction, bl: ghidra.program.model.correlate.Block, ind: int):
... | [
"def locate_in_basic_block(\n instr: Instr, instr_offset: int, basic_block: list[Instr], bb_offset: int\n ) -> int:\n for index, instruction in enumerate(basic_block):\n if instruction == instr and instr_offset == bb_offset:\n return index\n bb_offset += 2\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the names of all methods in instance. | def get_all_methods(instance):
return [m for m in dir(instance) if callable(getattr(instance, m))] | [
"def method_names(self) -> List[str]:\n return list(sorted(self._methods.keys()))",
"def all_methods( self, obj ):\n temp = []\n for name in dir( obj ):\n func = getattr( obj, name )\n if hasattr( func, '__call__' ):\n tem... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns all superclasses of a given class. Omits root 'object' superclass. | def get_all_superclasses(cls):
classes = []
for superclass in cls.__bases__:
for c in get_all_superclasses(superclass):
if c is not object and c not in classes:
classes.append(c)
for superclass in cls.__bases__:
if superclass is not object and superclass not in classes:
classes.append(... | [
"def get_all_subclasses(python_class):\n python_class.__subclasses__()\n\n subclasses = set()\n check_these = [python_class]\n\n while check_these:\n parent = check_these.pop()\n for child in parent.__subclasses__():\n if child not in subclasses:\n subclasses.add(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Decorator for subclasses of SpirvTest. This decorator checks that a class meets the requirements (see below) for a test case class, and then puts the class in a certain testsuite. The class needs to be a subclass of SpirvTest. The class needs to have spirv_args defined as a list. The class needs to define at least one ... | def inside_spirv_testsuite(testsuite_name):
def actual_decorator(cls):
if not inspect.isclass(cls):
raise SpirvTestException('Test case should be a class')
if not issubclass(cls, SpirvTest):
raise SpirvTestException(
'All test cases should be subclasses of SpirvTest')
if 'spirv_args... | [
"def instantiate_for_spirv_args(self, testcase):\n raise PlaceHolderException('Subclass should implement this function.')",
"def stresstest(*args, **kwargs):\n def decorator(f):\n if 'class_setup_per' in kwargs:\n setattr(f, \"st_class_setup_per\", kwargs['class_setup_per'])\n else:... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Call this to notify the manager of the results of a test run. | def notify_result(self, test_case, success, message):
self.num_successes += 1 if success else 0
self.num_failures += 0 if success else 1
counter_string = str(self.num_successes + self.num_failures) + '/' + str(
self.num_tests)
print('%-10s %-40s ' % (counter_string, test_case.test.name()) +
... | [
"def notifyTestFinished(self, test):\n pass",
"def notify_runner_results(\n self,\n measure_candidates: List[\"MeasureCandidate\"],\n results: List[\"RunnerResult\"],\n ) -> None:\n if self.search_strategy is None:\n raise ValueError(\n \"search_stra... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add this to the current list of test cases. | def add_test(self, testsuite, test):
self.tests[testsuite].append(TestCase(test, self))
self.num_tests += 1 | [
"def addTest(self, test):\r\n self.tests.append(test)\r\n return",
"def add_test_case(self, test_case, thunk):\n self.test_cases.append((test_case, thunk))",
"def _add_test_case(self, name, failure=None, duration=None):\n if not self._test_class:\n return\n\n self.c... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Transform data in R2 to R3 using (x0, x1, x02 + x12) | def to_r3(x0, x1):
assert isinstance(x0, np.ndarray) and isinstance(x1, np.ndarray)
x2 = x0**2 + x1**2
return np.column_stack((x0, x1, x2)) | [
"def transform3D(x: float, y: float, z: float, R: np.array) -> np.array:\n T = np.zeros((4, 4))\n T[:3, :3] = R\n T[:, 3] = [x, y, z, 1.0]\n\n return T",
"def Transform_from3DRotation(*args):\n return _almathswig.Transform_from3DRotation(*args)",
"def rotorconversion(x):\n return cf.MultiVector(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Plot the maximal margin hyperplane | def maximal_margin_hyperplane(svc, X, y, margins=True, support_vectors=True):
assert isinstance(svc, sklearn.svm.classes.SVC)
assert X.shape[1] == 2, 'X must be of shape (n_samples, 2)'
x_min = X[:, 0].min()
x_max = X[:, 0].max()
w = svc.coef_[0]
a = -w[0] / w[1]
xx = np.linspace(x_min * 2, ... | [
"def plot_hyperplane(w, xmin, xmax, iter = None, alpha=None, color=None,linestyle=None):\n # Find the points on the dividing hyperplane\n # using p[0]w[0] + p[1]w[1] = -w[2], or p[1] = (-p[0]w[0] - w[2])/w[1]\n x_points = [xmin, xmax]\n y_points = [(-xmin * w[0] - w[2]) / w[1], (-xmax * w[0] - w[2])... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Resize images in a directory to (96, 96) | def resize_multiple_images(src_path, dst_path):
for filename in os.listdir(src_path):
img=Image.open(src_path+'/'+filename)
new_img = img.resize((96,96,))
#new_img.resize(96,96,1)
if not os.path.exists(dst_path):
os.makedirs(dst_path)
new_img.save(dst_path+'/'+fil... | [
"def resizePics(dir_path, basewidth):\n\tdir = os.listdir(dir_path)\n\n\tfor image in dir:\n\t\tim = Image.open(dir_path + '/' + image)\n\t\tim = resizePic(im, basewidth)\n\t\tim.save(dir_path + '/' + image)",
"def resize_folder(image_dir, output_dir):\n print \"processing \" + image_dir\n if not os.path.is... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the list of points that form a diamond around the origin Makes concentric diamonds around a point (up to the specified radius), and returns all points within that diamond. | def diamond_points(self, x, y):
points = []
orig_x = x
orig_y = y
# Origin
points.append((x, y))
for i in range(1, self.blur_radius + 1):
# Top
points.append((orig_x, orig_y - i))
# NE side
for x, y in zip(range(0, i), ... | [
"def filled_diamond(origin_x, origin_y, size):\n perimeter = get_diamond(origin_x, origin_y, size)\n points = []\n for line in perimeter:\n for point in line:\n line = Line.get_line(origin_x, origin_y, point[0], point[1])\n if line not in points:\n points.append(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sorts a directory of images based on color Opens a directory, gets the file list, and determines the color at specific points in the images (using a simple blur), downsamples to a lower bitdepth and stores the filename in a dictionary, based on the color signature. When completed, it will rename the files based on the ... | def sort(self):
img_files = os.listdir(self.path)
img_list = {}
for img_file in img_files:
filename = os.path.join(self.path, img_file)
try:
img = Image.open(filename)
except:
continue
print "Analyzing %s" % img... | [
"def main():\n images = os.listdir(IMAGE_DIR)\n\n for i, item in enumerate(images):\n images[i] = RGBImage(item)\n\n images.sort(key=lambda image: image.mode)\n print(images)\n\n for i, item in enumerate(images):\n shutil.copyfile(IMAGE_DIR + item.filename,\n DEST... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculates period payment for a participant/investor | def period_payment(yearly_payments_percentage, client_cost_reduction,
days_with_payments, days_for_discount_rate):
yearly_payments_percentage = Fraction(str(yearly_payments_percentage))
client_cost_reduction = Fraction(str(client_cost_reduction))
if days_with_payments == 0:
paym... | [
"def _payment_per_period(self):\n loan_principal = self._loan_principal()\n insurance_cost = self._insurance_cost(loan_principal)\n new_loan_principal = loan_principal + insurance_cost\n return round(new_loan_principal * self._interest_amount(), 2)",
"def calculate(self):\r\n if... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check what a calendar will produce over time Simulates the check over time each `interval` hours for the given number of days. Results are printed to stdout. | def check_plan(url: str = None, start=None, days: int = 7, interval: int = 1):
if start is None:
start = autoscaler.utcnow()
if url is None:
url = os.environ["PLACEHOLDER_ICS_URL"]
if url.startswith("http"):
try:
import requests_cache
except ImportError:
... | [
"def check(self):\n\t\tfails = 0\n\t\tworktime_month = timedelta(hours=0)\n\t\tworktime_homeoffice = timedelta(hours=0)\n\t\tfor num in self.workdays:\n\t\t\tday = self.workdays[num]\n\t\t\tif day.daytype == DayType.work:\t\n\t\t\t\tfails += day.check(num)\n\t\t\t\tworktime = day.getWorkingTime()\n\t\t\t\tworktime_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Removing job from the machine by job number | def removeJob(self, job_number):
job = self.retrieveJob(job_number)
job_type = job.getType() - 1
del (self.assigned_jobs[job_number])
self.span -= job.getLength()
self.types[job_type] = self.types[job_type] - 1
self.types_sums[job_type] = self.types_sums[job_type] - job.l... | [
"def remove_job(data, job):\n for j in data.queue:\n if job.proc_id == j:\n del j\n return",
"def remove_job(path):\n with open(path + 'job_id.txt', 'r') as f:\n job_id = f.read().strip()\n r = requests.post(ip + \"/work_done\", data=dict(job_id=job_id, key=server_key)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check how many different types do I have | def checkDiffTypes(self):
count = 0
for t in self.types:
if t > 0:
count = count + 1
return count | [
"def get_types_count():\n return len(type_dict.keys())",
"def number_types(corpus):\n number_of_types = len(set(corpus))\n return number_of_types",
"def _only_one_type(self):\n num_larger_than_1 = 0\n for symb, indices in self.atoms_indx.items():\n if len(indices) > 0:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates and returns a machines list | def createMachines():
machines = []
for i in range(0, num_of_machines):
cur_machine = Machine(i)
machines.append(cur_machine)
return machines | [
"def get_machines():\r\n return listMachinesFomFile",
"def machines(self):\n from VirtualMachine import VirtualMachine\n return [VirtualMachine(vm) for vm in self._getArray('machines')]",
"def create_machines(self):\n logging.debug(\"create_machines called\")\n machines = self.inf... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create and returns a list of jobs objects | def createJobs():
jobs_list = []
for job in raw_jobs:
cur_job = Job(int(job[0]), int(job[1]), int(job[2]))
print("Created job: index:", cur_job.number, "Length:", cur_job.length, "Type", cur_job.type, file=debug_file)
jobs_list.append(cur_job)
print("-----------------FINISHED CREATIN... | [
"def list():\n\treturn _jobs.all()",
"def jobs():\n result = []\n out = subprocess.check_output([\"/bin/launchctl\", \"list\"]).decode()\n for row in out.splitlines()[1:]:\n result.append(Job(row))\n return result",
"def job_list():\n user = auth.username()\n job_db = JobDb()\n\n if ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
creating a chromosome returning a list of size num_of_jobs , each index is job number, value is the assigned machine | def createChrom():
ch = [0]*num_of_jobs
for i in range(num_of_jobs):
legal = False
while not legal:
machine_rand = randint(0,num_of_machines-1)
ch[i] = machine_rand
machines_list[machine_rand].addJob(jobs_list[i])
if machines_list[machine_rand].isL... | [
"def createChromosomes(self) -> ChromList:\n raise NotImplementedError",
"def jobGenerator(machines,sections):\n job_dict = {}\n for machine in range(1,machines+1):\n key = machine\n lst = []\n \n for section in range(1,sections+1):\n lst.append(('Move','m'+str(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
returns current maximum makespan | def makeSpan():
max_span = 0
for machine in machines_list:
if machine.span > max_span:
max_span = machine.span
return max_span | [
"def long_span():\n return int(parameters['long_span'])",
"def get_span(array):\n return array.max() - array.min()",
"def get_max(self):",
"def max(self) -> int:",
"def _max_in_bounds(self, max):\n if max >= self.valmax:\n if not self.closedmax:\n return self.val[1]\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Prints a given population | def printPop(population: list):
for p in population:
print(p) | [
"def population_print(population, value):\n increase_amount = population_increase(population)\n decrease_amount = population_decrease(population)\n print(\"{0} gophers were born. {1} died.\".format(int(increase_amount), int(decrease_amount)))\n population = population + int(increase_amount) - int(decre... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
selections of parent according to a given probavilities | def selection(probs):
# pick 2 parents out of this distribution
t = [i for i in range(len(probs))]
draw = choice(t, 2, p=probs, replace=False)
return draw | [
"def select_parent(self):",
"def select_parents(self):\n self.parents = []\n parent_population_size = int(self.config.settings['parent_population_size'])\n\n if int(self.config.settings['use_uniform_random_parent_selection']):\n # Select parents using a uniform random approach\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |