query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Take the addressLocality field in each object, tokenize it by space and comma, lower case it and convert to set of words. use each token in that set as a 'key' for the cluster. We'll start by analyzing those. | def cluster_by_addressLocality(input_file, output_file=None):
pass | [
"def prepare_cluster_to_word_map(brown_cluster_file):\n mapping = defaultdict(set)\n for l in line_reader(brown_cluster_file):\n c_id, w, fq = l.strip().split(\"\\t\")\n mapping[c_id].add(w) # keep string cluster ids\n\n return mapping",
"def addresses( data ) :\n return list( set(chain... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Access the fA Function object | def fA(self):
pass | [
"def get_function(self, name):",
"def _function_class(self):\n return FriCASExpectFunction",
"def get_function(self):\n return SSAFunction(self.get_graph())",
"def get_function(self):\n return self.func",
"def function(self):\n obj = self.module\n for part in self.function... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Access the fAT Function object | def fAT(self):
pass | [
"def function(self):\n obj = self.module\n for part in self.function_name.split('.'):\n ## FIXME: better error handling:\n try:\n obj = getattr(obj, part)\n except AttributeError, e:\n raise Exception(\n \"Could not get ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Access the fG Function object | def fG(self):
pass | [
"def get_function(self):\n return SSAFunction(self.get_graph())",
"def get_function(self):\n return self.func",
"def getFunc(self):\n\t\treturn self.initFunc()(self.x)",
"def get_function(self, name):",
"def times(self, g):\n assert isinstance(g, Function)\n dim = self.input_dim(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Questions Card Update Form | def admin_card_update(card_id):
mongo_collection = mongo_database["questions"]
card = mongo_collection.find_one({"id": card_id})
return render_template(
"admin_card_update.html",
card=card,
datetime=date_today.strftime("%x"),
admin_logged=session.get('logged_in'),
adm... | [
"def update_question(self, question_form):\n pass",
"def update_answer(self, answer_form):\n pass",
"def _edit_question(request, question):\n latest_revision = question.get_latest_revision()\n preview = None\n revision_form = None\n if request.method == 'POST':\n if 'select_revi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate the closest possible SEO friendly path for this campaign. Note that these paths are only generated for campaigns which are already published. | def generate_seo_friendly_path(self, base_pathname_string='', campaignx_we_vote_id='', campaignx_title=None):
from politician.controllers_generate_seo_friendly_path import generate_seo_friendly_path_generic
return generate_seo_friendly_path_generic(
base_pathname_string=base_pathname_string,... | [
"def generate_path(self):\n ontology = []\n for item in self.parent.get_ancestors():\n if item.level != 0:\n ontology.append(item.slug)\n\n if self.parent.level != 0:\n ontology.append(self.parent.slug)\n\n ontology.append(self.slug)\n\n return... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function calculates the information gain, where ig(f1, f2) = H(f1) H(f1\f2) | def information_gain(f1, f2):
ig = ee.entropyd(f1) - conditional_entropy(f1, f2)
return ig | [
"def get_info_gain(new_split, old_data):\n ratio_old_data = get_counts(old_data)\n ratio_split1 = get_counts(new_split[0])\n ratio_split2 = get_counts(new_split[1])\n\n\n new_entropy = (float(len(new_split[0]))/len(old_data)) * entropy(ratio_split1) +\\\n (float(len(new_split[1]))/len(o... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function calculates the conditional entropy, where ce = H(f1) I(f1;f2) | def conditional_entropy(f1, f2):
ce = ee.entropyd(f1) - ee.midd(f1, f2)
return ce | [
"def conditional_entropy_hyper(self) -> float:\n pass",
"def conditional_entropy(x: np.array, y: np.array):\n c_x_y = joint_entropy(x, y) - entropy(y)\n return c_x_y",
"def information_gain(f1, f2):\n\n ig = ee.entropyd(f1) - conditional_entropy(f1, f2)\n return ig",
"def _conditional_entro... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function calculates the symmetrical uncertainty, where su(f1,f2) = 2IG(f1,f2)/(H(f1)+H(f2)) | def su_calculation(f1, f2):
# calculate information gain of f1 and f2, t1 = ig(f1, f2)
t1 = information_gain(f1, f2)
# calculate entropy of f1
t2 = ee.entropyd(f1)
# calculate entropy of f2
t3 = ee.entropyd(f2)
su = 2.0 * t1 / (t2 + t3)
return su | [
"def py_chi_square(h1, h2):\n\n d = 0\n for i in range(h1.shape[0]):\n if h1[i] != h2[i]: d += int(((h1[i] - h2[i])**2) / (h1[i] + h2[i]))\n return d",
"def halluncertainty(x1,x2,dx1,dx2,varx1x2):\n\n # derivative of Sigmah wrt average energy\n denom = 16 + x1**2\n dsh_dx1 = 18 * x1**(0.85) / denom... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Chooses the appropriate rpc class based on the address format. Does not work for EtherscanRPC because there is no good way to check if an api_key is valid. If you know you have an apikey for Etherscan, instantiate the EtherscanRPC client directly. | def rpc_factory(address, verbose):
if not isinstance(address, str):
raise RPCError('The address must be a string: {!r}'.format(address))
if _os.path.exists(address) and _stat.S_ISSOCK(_os.stat(address).st_mode):
return IPCRPC(address, verbose)
elif _HTTP.match(address):
return HTTPR... | [
"def from_str(cls, address: str) -> Optional[Address]:\n if len(address) < 26 or len(address) > 35:\n return None\n # decode\n data = base58_decode(address)\n if data is None or len(data) != 25:\n return None\n # check code\n prefix = data[:21]\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Locates the specified datafiles and returns the matches in a data_files compatible format. source is the root of the source data tree. Use '' or '.' for current directory. target is the root of the target data tree. Use '' or '.' for the distribution directory. patterns is a sequence of globpatterns for the files you w... | def find_data_files(source, target, patterns):
if glob.has_magic(source) or glob.has_magic(target):
raise ValueError("Magic not allowed in src, target")
ret = {}
for pattern in patterns:
pattern = os.path.join(source, pattern)
for filename in glob.glob(pattern):
if... | [
"def find_data_files(source,target,patterns):\r\n if glob.has_magic(source) or glob.has_magic(target):\r\n raise ValueError(\"Magic not allowed in src, target\")\r\n ret = {}\r\n for pattern in patterns:\r\n pattern = os.path.join(source,pattern)\r\n for filename in glob.glob(pattern):... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Matches template image in a target grayscaled image | def match_template(img, template, threshold=0.9):
#print(img)
#print(template)
res = cv2.matchTemplate(img, template, cv2.TM_CCOEFF_NORMED)
matches = np.where(res >= threshold)
return matches | [
"def template_match(image,template):\n # Padding scale image array\n pad_im_array = np.zeros(shape=(image.shape[0] + template.shape[0] - 1, image.shape[1] + template.shape[1] -1))\n pad_im_array[:image.shape[0], :image.shape[1]] = image\n # Hamming distance of template and patch calculation\n im_matc... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Try to load the part this method is called by the connect method of this object and by cltremote.RemoteBase RemoteBase | def load_part(self, partname, remoteclassname):
success = False
logger.info(u"{} Loading of part: {}".format(self.uid, partname))
try:
module = importlib.import_module("parts.{p}.{p}Remote".format(
p=partname))
logger.info(
le2mtrans(u"{j}... | [
"def _load(self, pkgpart, part_dict):\n # call parent to do generic aspects of load\n super(SlideMaster, self)._load(pkgpart, part_dict)\n\n # selectively unmarshal relationships for now\n for rel in self._relationships:\n # log.debug(\"SlideMaster Relationship %s\", rel._relt... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Load the rlhuboplus model and a scene into openhubo. Returns a servocontroller and a reference robot to show desired movements vs. actual pose. The returned tuple contains the robots, controller, and a nametojointindex converter. | def load_rlhuboplus(env,scenename=None,stop=False):
return _oh.load_scene(env,'rlhuboplus.robot.xml',scenename,stop) | [
"def load_model():\n model = torch.hub.load('ultralytics/yolov5', 'yolov5s', pretrained=True)\n #self.model.to(self.device)\n return model.to(torch_device), model.names",
"def load(self):\n # Intercept load message via mock LCM.\n mock_lcm = DrakeMockLcm()\n DispatchLoadMessage(self.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A closure to easily convert from a string joint name to the robot's actual DOF index. | def makeNameToIndexConverter(robot,autotranslate=True):
return _oh.make_name_to_index_converter(robot,autotranslate) | [
"def makeNameToIndexConverter(robot):\n def convert(name):\n return robot.GetJoint(name).GetDOFIndex()\n return convert",
"def jointName(self, joint_idx: int) -> str:\n raise NotImplementedError()",
"def get_joint_idx(self, joint_id):\n pass",
"def index_from_dof(dof):\n return 6... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Load up and configure the simpleFloor environment for hacking with physics. Sets some useful defaults. | def load_simplefloor(env):
return _oh.load_scene(env,None,'simpleFloor.env.xml',True) | [
"def load_simplefloor(env):\n with env:\n #Since physics are defined within the XML file, stop simulation\n env.StopSimulation()\n env.Load('simpleFloor.env.xml')\n collisionChecker = RaveCreateCollisionChecker(env,'ode')\n env.SetCollisionChecker(collisionChecker)\n rob... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set tweaked finger torque for grasping experiment. Deprecated due to new torquebased servo control. | def set_finger_torque(robot,maxT,fingers):
#Super kludgy...
for f in fingers:
if robot.GetJoint(f):
robot.GetJoint(f).SetTorqueLimits([maxT])
robot.GetJoint(f).SetVelocityLimits([3])
robot.GetJoint(f).SetAccelerationLimits([30]) | [
"def torque(self, torque):\n\n r = lib.il_servo_torque_set(self._servo, torque)\n raise_err(r)",
"def setMotorTorque(self, torque):\r\n if torque < 0.0:\r\n torque = 0.0\r\n elif torque > 1.0:\r\n torque = 1.0\r\n torque *= self.maxTorque\r\n if self... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns recipe does not exist message | def _does_not_exist():
response_payload = dict(
message="Recipe does not exist!"
)
response_payload = jsonify(response_payload)
return make_response(response_payload, 404) | [
"def non_existing_recipe_error_test(self):\n client = TestClient()\n error = client.run(\"upload Pkg/0.1@user/channel\", ignore_error=True)\n self.assertTrue(error)\n self.assertIn(\"ERROR: There is no local conanfile exported as Pkg/0.1@user/channel\",\n client.user... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parse the traceroute result | def parseTraceroute(self, stdoutputdata):
itemlist = stdoutputdata.split("\n")
res = defaultdict(list)
for item in itemlist:
re_ip = re.search(r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}', item)
if re_ip:
ip = re_ip.group(0)
res["route"].append(ip)
res["route"].append(self.task["destination"])
res["des... | [
"def get_traceroute_output(self):\n url = self.source['url']\n if 'post_data' in self.source:\n context = self.source['post_data']\n else:\n context = None\n status_code, content = self.urlopen(url, context=context)\n content = content.strip()\n regex ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Symmetric decorrelation i.e. W < (W W.T) ^{1/2} W | def _sym_decorrelation(W):
s, u = linalg.eigh(np.dot(W, W.T))
# Avoid sqrt of negative values because of rounding errors. Note that
# np.sqrt(tiny) is larger than tiny and therefore this clipping also
# prevents division by zero in the next step.
s = np.clip(s, a_min=np.finfo(W.dtype).tiny, a_max=No... | [
"def wcorr(self):\n sig1 = self.sig1 # f0\n w1 = self.w1 # pov\n w2 = self.w2 # energy\n w12 = self.w12\n if w12 is None:\n w12 = w1 * w2\n\n sig2 = self.sig2 # atoms\n\n if sig2.ndim == 1: # an array is passed\n top = np.sum(w12 * sig1 * s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Grab the name of the binary we're running in. | def get_binary_name():
return os.path.basename(inspect.stack()[-1][1])[:16] | [
"def _get_program_name():\n return __name__",
"def get_program_name():\n program_name = sys.argv[0]\n if not program_name.startswith(\"./\"):\n program_name = os.path.basename(program_name)\n return program_name",
"def bin_name() -> str:\n # NB: This will be called at import-time in severa... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds a named chain to the table. The chain name is wrapped to be unique for the component creating it, so different components of Nova can safely create identically named chains without interfering with one another. At the moment, its wrapped name is , so if novacompute creates a chain named 'OUTPUT', it'll actually en... | def add_chain(self, name, wrap=True):
if wrap:
self.chains.add(name)
else:
self.unwrapped_chains.add(name)
self.dirty = True | [
"def add_chain(self, name, wrap=True):\n name = get_chain_name(name, wrap)\n if wrap:\n self.chains.add(name)\n else:\n self.unwrapped_chains.add(name)",
"def chain_name(self) -> str:\n return pulumi.get(self, \"chain_name\")",
"def append(self, chain):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Remove named chain. This removal "cascades". All rule in the chain are removed, as are all rules in other chains that jump to it. If the chain is not found, this is merely logged. | def remove_chain(self, name, wrap=True):
if wrap:
chain_set = self.chains
else:
chain_set = self.unwrapped_chains
if name not in chain_set:
return
self.dirty = True
# non-wrapped chains and rules need to be dealt with specially,
# so... | [
"def remove_chain(self, name, wrap=True):\n name = get_chain_name(name, wrap)\n chain_set = self._select_chain_set(wrap)\n\n if name not in chain_set:\n LOG.debug('Attempted to remove chain %s which does not exist',\n name)\n return\n\n chain_se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add a rule to the table. This is just like what you'd feed to iptables, just without the 'A ' bit at the start. However, if you need to jump to one of your wrapped chains, prepend its name with a '$' which will ensure the wrapping is applied correctly. | def add_rule(self, chain, rule, wrap=True, top=False):
if wrap and chain not in self.chains:
raise ValueError(_('Unknown chain: %r') % chain)
if '$' in rule:
rule = ' '.join(map(self._wrap_target_chain, rule.split(' ')))
rule_obj = IptablesRule(chain, rule, wrap, top)
... | [
"def add_rule(self, chain, rule, wrap=True, top=False, tag=None,\n comment=None):\n chain = get_chain_name(chain, wrap)\n if wrap and chain not in self.chains:\n raise LookupError(_('Unknown chain: %r') % chain)\n\n if '$' in rule:\n rule = ' '.join(\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Remove a rule from a chain. | def remove_rule(self, chain, rule, wrap=True, top=False):
try:
self.rules.remove(IptablesRule(chain, rule, wrap, top))
if not wrap:
self.remove_rules.append(IptablesRule(chain, rule, wrap, top))
self.dirty = True
except ValueError:
pass | [
"def remove_rule(self, chain, rule, wrap=True, top=False, comment=None):\n chain = get_chain_name(chain, wrap)\n try:\n if '$' in rule:\n rule = ' '.join(\n self._wrap_target_chain(e, wrap) for e in rule.split(' '))\n\n self.rules.remove(Ebtables... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Remove all rules matching regex. | def remove_rules_regex(self, regex):
if isinstance(regex, six.string_types):
regex = re.compile(regex)
num_rules = len(self.rules)
self.rules = filter(lambda r: not regex.match(str(r)), self.rules)
removed = num_rules - len(self.rules)
if removed > 0:
self... | [
"def reset_selective(self, regex=None):\n if regex is not None:\n try:\n m = re.compile(regex)\n except TypeError as e:\n raise TypeError('regex must be a string or compiled pattern') from e\n # Search for keys in each namespace that match the gi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Remove all rules from a chain. | def empty_chain(self, chain, wrap=True):
chained_rules = [rule for rule in self.rules
if rule.chain == chain and rule.wrap == wrap]
if chained_rules:
self.dirty = True
for rule in chained_rules:
self.rules.remove(rule) | [
"def empty_chain(self, chain, wrap=True):\n chained_rules = self._get_chain_rules(chain, wrap)\n for rule in chained_rules:\n self.rules.remove(rule)",
"def remove_chain(self, chain):\n assert isinstance(chain, Chain)\n self.model_dict[chain.model_id].remove_chain(chain)",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Apply the current inmemory set of iptables rules. This will blow away any rules left over from previous runs of the same component of Nova, and replace them with our current set of rules. This happens atomically, thanks to iptablesrestore. | def _apply(self):
s = [(iptables_save, iptables_restore, self.ipv4)]
if self.use_ipv6:
s += [(ip6tables_save, ip6tables_restore, self.ipv6)]
for save, restore, tables in s:
all_tables, _err = save()
all_lines = all_tables.split('\n')
for table_nam... | [
"def iptables_apply():\n\n with settings(warn_only=True):\n run(\"sudo iptables-restore < /etc/iptables.rules\")",
"def update_rules():\n update_all_rules()\n return \"OK\"",
"def update_rules(self, context, physical_network, isoflat_rules):",
"def update_rule_list(self):\n self.rules =... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Instantiates a finite grid. The limits are specified as a list of tuples of (low, high) values, one for each grid vector. | def __init__(self, origin, grid_vectors, limits):
assert len(grid_vectors) == len(limits)
Grid.__init__(self, origin, grid_vectors)
self._Limits = limits | [
"def create_grid(xlim, ylim, step):\n x_range = np.arange(xlim[0], xlim[1], step)\n y_range = np.arange(ylim[0], ylim[1], step)\n return x_range, y_range",
"def grid(x_min, x_max, y_min, y_max, N):\r\n\timport numpy as np\r\n\r\n\tx1 = np.linspace(x_min, x_max, N)\r\n\tx2 = np.linspace(y_min, y_max, N)\r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the number of grid intervals in each direction. | def grid_point_count(self):
return pytools.product(self.grid_point_counts()) | [
"def getNumTiles(self):\n return len(list(product(list(range(self.width+1))[1:], list(range(self.height+1))[1:])))",
"def _number_of_intervals(self):\n return self._number_of_levels - 1",
"def _get_num_states(self):\n g = self.grid.grid_size\n c = self.grid.capacity + 1\n num_stat... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Const method for initializing the applet | def init(self):
# Configuration interface support comes with plasma
self.setHasConfigurationInterface(False)
# Aspect ratio defined in Plasma
self.setAspectRatioMode(Plasma.IgnoreAspectRatio)
# Theme is a const variable holds Applet Theme
self.theme = Plasma.Svg(self)
... | [
"def __init__(self):\n\n self.parms = _init_parms()\n self.prefs = _init_prefs()",
"def initialize(self):\n winsparkle_init()",
"def initialize(self,tape):\n\t\tpass",
"def initialize(self, args):\n\t\tpass",
"def __init__(self):\n\n self.logger = utils.get_logger()\n\n # ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds a data point to the logger object. Datapoints are added sequentially, so add your variables in the same sequence that you want them to show up in on the CSV | def addDataPoint(self, variableName):
if self.initialized == False:
if str(variableName) in self.currentLog:
raise IndexError("datapoiont already initialized")
else:
self.variables += 1
self.variableDescriptions.append(variableName)
... | [
"def add_point(self, line):\n arr = line.split(',')\n name = arr[0]\n timestamp = dt.datetime.strptime(arr[1], '%m/%d/%y %H:%M:%S')\n vals = []\n dtypes = []\n self._sensor_name = name\n\n data = arr[2:]\n context = []\n i = 0\n for datum in data... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
records a variable to the current log, DOES NOT LOG AUTOMATICALLY | def recordVariable(self, variableName, data):
if str(variableName) in self.currentLog:
# if self.currentLog[str(variableName)] != None:
# raise Warning(f'data point {str(variableName)} is being overwritten!')
self.currentLog[str(variableName)] = data
else:
... | [
"def log_example(var):\n\n log.info('example code started')\n log.debug('calling settings')\n test_settings()\n log2.error('there is no error this is example ')\n log2.info('finished')",
"def logger(self, value):\n pass",
"def log(self):\n pass",
"def _add_recorder(self, variable)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initializes the CSV file and prepares it for writing. | def initCSV(self, makeFile, overWrite):
self.initialized = True
os.chdir(os.path.dirname(os.path.abspath(__file__)))
if os.path.exists(str(self.fileName)):
f = open(str(self.fileName), "r")
if not f.read():
f.close()
f = open(str(self.... | [
"def __open_csv(self):\n self.__csv_file = open(self.__csv_file_name, 'w', encoding='utf-8')\n self.__csv_writer = csv.writer(self.__csv_file, delimiter=',', )",
"def _prepare_csv_file(self):\n # Write fieldnames into csv header\n with open(self.csv_filename, 'w') as csvfile:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test stripping the line | def test_line_strip():
for _x in range(100):
l_str = " ".join([random_str(5, 10) for x in range(30)])
l_str = (" " * randint(0, 10)) + l_str + (" " * randint(0, 10))
line = Line(l_str, random_str(10, 20), randint(1, 10000))
# Strip the string
l_stripped = line.strip()
... | [
"def test_line_location(line, allowEmptyLocation=True) :\n if allowEmptyLocation :\n if not line.outputLocation() or line.outputLocation() =='':\n return\n assert 'Stripping'+line.outputLocation().split('/')[-2] == line.name()",
"def should_keep_line(line):\n return not should_ignore_li... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test concatenating different lines | def test_line_concat():
for _x in range(100):
strings = [random_str(30, 50) for _x in range(10)]
l_file = random_str(10, 20)
l_num = randint(1, 10000)
lines = [Line(x, l_file, l_num) for x in strings]
# Concatenate the lines
l_full = lines[0]
for line in ... | [
"def testAppendTwoLines(self):\n s = MultilineString()\n s.append('test1')\n s.append('test2')\n self.assertEqual('test1\\ntest2', str(s))",
"def testAppendOneLine(self):\n s = MultilineString()\n s.append('test')\n self.assertEqual('test', str(s))",
"def testExt... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Run code quality check | def codeqa():
try:
sh('flake8 h5_validator')
except BuildFailure:
pep8_fail = True
else:
pep8_fail = False
try:
sh("pydocstyle h5_validator")
except BuildFailure:
docstring_fail = True
else:
docstring_fail = False
if pep8_fail or docstring_f... | [
"def main():\n coverage = calculate_code_coverage()\n platform = os.uname()[0]\n if coverage < CODE_COVERAGE_GOAL[platform]:\n data = {\n 'expected': CODE_COVERAGE_GOAL[platform],\n 'observed': coverage,\n }\n print '\\033[91mFAIL: %(observed).2f%% does not meet g... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Build the Sphinx documentation | def docs():
sh('sphinx-build -W -b html docs docs/_build/html') | [
"def run(self):\n\t\tself.sphinx_instance.build(force_all=False, filenames=None)\n\t\treturn None",
"def build(ctx, cmd='help'):\n ctx.run('sphinx-build -M {} {} {}'.format(cmd, source, dest))",
"def build():\n print(\"=== Build HTML Docs from ReST Files ===\")\n subprocess.check_call([\n \"sphi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Update an existing asset. | def update_asset(cls, id, asset_data):
return ph_base._update_record('asset', id, asset_data) | [
"def update_asset(self, asset_node: \"Asset\"):\n pass",
"def update(self) -> requests.request:\n # Check if id is set\n if self.args.id is None:\n raise Exception('Provide id of asset you want to update')\n\n # Check URL validity\n if self.args.url is not None and se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks if the number of images is equal to the number of labels in the path. Input | def _check_images_and_labels(self, image_dir, label_dir):
return len(os.listdir(image_dir))==len(os.listdir(label_dir)) | [
"def check_number_of_labels(repository):\n\n list_of_bad_files = []\n filenames = os.listdir(repository)\n for file in filenames:\n image = Image.open(os.path.join(repository, file))\n arr = np.asarray(image)\n # find the unique values\n unique = np.unique(arr)\n control ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given the file handle of the file containing image data, it returns a list of the objects contained in the image. Returns objects (list(object)), where object is a dict. Currently, object has only one key, namely 'polygon' which is a list of points in clockwise order. | def _get_objects(self,label_fh):
objects = []
for line in label_fh.readlines():
try:
object = {}
line = line.replace(u'\ufeff', '')
if line != '':
x1, y1, x2, y2, x3, y3, x4, y4= [int(i) for i in line.split(',')[:-1]]
... | [
"def read_geometry_from_obj_file(filename):\n obj_file = open(filename, 'r')\n vertices = []\n faces = []\n for line in obj_file:\n if line.startswith('v'):\n vertex_coords = map(float, line.split(' ')[1:])\n if len(vertex_coords) < 4:\n vertex_coords.append(1... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given the list of objects, it returns an array mapping object ids to their respective classes. Background has class 0 and text has class 1. | def _get_object_classes(self,objects):
object_class = [1 for object in objects]
object_class.insert(0, 0)
return object_class | [
"def get_object_classes(predictions):\n classes = [pred['label'] for pred in predictions]\n return set(classes)",
"def get_classes(self):\n classes = []\n for item in self.data:\n if item[1] not in classes:\n classes.append(item[1])\n\n # Sort them.\n cl... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Make an Orders request, store the page count and process the response data. | def first_request(self):
response_data = self.make_order_request(1)
self.page_count = response_data[self.DATA][self.LAST_PAGE]
self.add_orders(response_data) | [
"def request_orders(self):\n self.enqueue_http_request(\"private/OpenOrders\", {}, \"orders\")",
"def make_order_request(self, page):\n return api_methods.Orders(\n page=page,\n per_page=self.PER_PAGE,\n from_date=self.from_date,\n start_date=self.start_da... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add the orders from a the response to an Orders request to self.orders. | def add_orders(self, response_data):
orders = response_data[self.DATA][self.DATA]
for order in orders:
self.orders.append(self.process_order_data(order)) | [
"async def handle_new_order_response(self, response: RequesterResponse\n ) -> HitbtcOrderModel:",
"def orders(self, orders):\n\n self._orders = orders",
"async def handle_get_active_orders_response(self, response: RequesterResponse\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the response to an Orders request for a page of orders. | def make_order_request(self, page):
return api_methods.Orders(
page=page,
per_page=self.PER_PAGE,
from_date=self.from_date,
start_date=self.start_date,
end_date=self.end_date,
deal_id=self.deal_id,
).call() | [
"def return_to_orders_page(self):\n raise NotImplementedError",
"def get_orders(self, **kwargs) -> ApiResponse:\n return self._request(kwargs.pop('path'), params={**kwargs})",
"def request_orders(self):\n self.enqueue_http_request(\"private/OpenOrders\", {}, \"orders\")",
"async def handl... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test case for tarfile bundling and unbundling | def testTarBundling(self):
try:
tP = os.path.join(self.__workPath, "t0.tar.gz")
dirPath = os.path.join(self.__inpDirPath, "topdir")
ok = self.__fileU.bundleTarfile(tP, [dirPath], mode="w:gz", recursive=True)
self.assertTrue(ok)
numBytes = self.__file... | [
"def test_pristine_tar_checkout():",
"def test_unpack(self):\n if not os.path.isfile(akrr_tar_gz):\n raise Exception(\"Should do test_packager first\")\n \n if os.path.exists(cfg.akrr_home):\n shutil.rmtree(cfg.akrr_home)\n \n if verbosity>=3: print \"\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test case for copying ("put") and moving ("replace") local files | def testMoveAndCopyFile(self):
try:
remoteLocator = self.__pathPdbxDictionaryFile
fn = self.__fileU.getFileName(remoteLocator)
# _, fn = os.path.split(remoteLocator)
lPath = os.path.join(self.__workPath, fn)
ok = self.__fileU.get(remoteLocator, lPath)
... | [
"def test_cp(tmp_path):\n source = tmp_path / 'source'\n data = 'hello'\n with open(source, 'w', encoding='utf-8') as file_handle:\n file_handle.write(data)\n destination = tmp_path / 'destination'\n local_filestore.cp(str(source), str(destination))\n with open(destination, encoding='utf-8'... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test case for downloading remote zip file and extracting contents. | def testZipUrl(self):
try:
remoteLocator = self.__zipFileUrl
# fn = self.__fileU.getFileName(remoteLocator)
ok = self.__fileU.isLocal(remoteLocator)
self.assertFalse(ok)
#
lPath = os.path.join(self.__workPath, self.__fileU.getFileName(self.... | [
"def _fetch_remote_data(remote, download_dir, data_home):\n\n file_path = '{}.zip'.format(download_dir)\n if not Path(file_path).exists():\n urllib.request.urlretrieve(remote.url, file_path)\n _unzip_dataset( file_path, data_home)",
"def test_unpack_zip_success(self) -> None:\n files = [\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test case for downloading remote file ftp protocol and extracting contents. | def testFtpUrl(self):
try:
remoteLocator = self.__ftpFileUrl
# fn = self.__fileU.getFileName(remoteLocator)
ok = self.__fileU.isLocal(remoteLocator)
self.assertFalse(ok)
#
dirPath = os.path.join(self.__workPath, "chem_comp_models")
... | [
"def do_download(ftp):\n # Active (PORT), Passive (PASV), ExtActive (EPRT), or ExtPassive (EPSV)?\n output, sock, transfer_type = get_transfer_output_and_socket(ftp)\n print_debug(output + \"\\n\")\n\n # What file to download?\n path = raw_input(\"What file do you want to download?\\n> \")\n while... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test case for extracting contents from xz file | def testXzFile(self):
try:
remoteLocator = self.__xzFile
fn = self.__fileU.getFileName(remoteLocator)
lPath = os.path.join(self.__workPath, fn)
ok = self.__fileU.get(remoteLocator, lPath)
self.assertTrue(ok)
ok = self.__fileU.exists(lPath)
... | [
"def test__extract_filenames_from_zip(self):\n\n expected = [\n \"Birdman of Alcatraz - 1.srt\",\n \"Birdman of Alcatraz - 2.srt\",\n ]\n\n test_file = os.path.join(_test_data_dir(), \"4130212.zip\")\n\n with open(test_file, \"rb\") as tfile:\n\n arch... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Activation function of hidden layers. | def forward_hidden_activation(self, X):
return np.tanh(X) | [
"def __activation__(self,inputs):\n activation=0\n for counter in range(self.num_inputs):\n activation+=self.weights[counter]*inputs[counter]\n return self.__sigmoid__(activation)\n #return activation+self.bias",
"def compute_activation(self):\r\n\r\n x=0\r\n e... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Derivative of the activation function of hidden layers. | def backward_hidden_activation(self, Y, d):
# y = tanh(x) ==> dy/dx = (1 - tanh(x)^2) = (1 - y^2)
return d * (1 - Y ** 2) | [
"def activationDerivative(self):\n\n\t\treturn self._activationDerivative",
"def transfer_function_derivative(weighted_sum):\n # derivative of tanh(x) is (1 - tanh(x)^2)\n # The weighted sum is already tanh(x) so we just return 1 - weighted_sum ^ 2\n return 1.0 - (weighted_sum ** 2)\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test the gradient of the activation function. | def test_activation_gradient():
np.random.seed(7477)
cnn = CNNTanh([1, 1])
X = np.random.randn(10, 1)
Y = cnn.forward_hidden_activation(X)
eps = 1e-7
Y1 = cnn.forward_hidden_activation(X + eps)
D = cnn.backward_hidden_activation(Y, np.ones_like(Y))
D1 = (Y1 - Y) / eps
error = np.abs(... | [
"def test_gradient(self):\n a = ann.ANN([2,5,7,3,2], [af.sigmoid, af.tanh, af.lin, af.squash])\n inputs = np.array([[1, 4], [2, 3], [3, 1]])\n targets = np.array([[0.4, 0.6], [0.5, 0.5], [0.8, 0.2]])\n dw1 = a.gradient(inputs, targets)\n dw2 = a._gradient_finite_difference(inputs,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test the gradient of the loss wrt the parameters. | def test_parameter_gradients(net, X, Y, name, p, grad_p, loss, index):
eps = 1e-7
backup = p[index]
p[index] += eps
A1 = net.forward(X)
loss1 = net.loss(Y, A1[-1])
ratio = (loss1 - loss) / eps
assert np.isclose(grad_p[index], ratio)
p[index] = backup | [
"def check_layer_gradient(layer, x, delta=1e-5, tol=1e-4):\n output = layer.forward(x)\n np.random.seed(10)\n #output_weight = np.random.randn(*output.shape)\n output_weight = np.ones_like(output)\n #print('output_weight',output_weight)\n\n def helper_func(x):\n output = layer.forward(x)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Swaps elements A and B in a list. | def listSwapElement(lst, indexa, indexb):
temp = lst[indexa]
lst[indexa] = lst[indexb]
lst[indexb] = temp | [
"def _swap(mylist, a, b):\n temp = mylist[a]\n mylist[a] = mylist[b]\n mylist[b] = temp",
"def swap(the_list,i,j):\r\n the_list[i],the_list[j] = the_list[j], the_list[i]",
"def swap(aList, iIndex, jIndex):\n aList[iIndex], aList[jIndex] = aList[jIndex], aList[iIndex]",
"def swap_elements(i: int... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Execute a list of plans, this list is returned when solving a task. | def execute_plans(robot, plans):
# make sure the robot is actually in the home position
# before executing a plan
robot.mg.set_joint_value_target(
plans[0].joint_trajectory.points[0].positions)
robot.mg.go(wait=True)
print("Moved to home, start executing task.")
# TODO quick fix, add fi... | [
"def execute_plan(self, args: List, result_ids: List[Union[str, int]]):\n # We build the plan only if needed\n if not self.is_built:\n self._build(args)\n\n if len(self.locations):\n plan_name = f\"plan{self.id}\"\n # args, _, _ = hook_args.unwrap_args_from_func... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Deletes a business_report from the table with the specified id | def delete_by_id(id: int) -> List:
business_report = BusinessNotificationService.get_by_id(id)
if not business_report:
return []
db.session.delete(business_report)
db.session.commit()
return [id] | [
"def delete_sql_report(request, sql_report_id):\r\n return create_update.delete_object(request, SQLReport,\r\n post_delete_redirect=reverse('sql_report_list'),\r\n object_id=sql_report_id, template_object_name='sql_report',\r\n template_name='sql_reports/delete_sql_report.html')",
"def del... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
uses list1 as the reference, returns list of items not in list2 | def list_difference(list1, list2):
diff_list = []
for item in list1:
if not item in list2:
diff_list.append(item)
return diff_list | [
"def __difference(lst1, lst2):\n return [i for i in lst1 if i not in lst2]",
"def diff_list(self, list1, list2):\n list2 = set(list2)\n return [result for result in list1 if result not in list2]",
"def exclusiveListTwo(L1, L2):\n \n L3 = [x for x in L2 if x not in L1]\n return L3",... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a new SDGraphObjectFrame instance in the specified graph | def sNew(sdGraph):
outSDGraphObjectFrame = ctypes.c_void_p()
_res = sd.getContext().SDGraphObjectFrame_sNew(sdGraph.mHandle, ctypes.byref(outSDGraphObjectFrame))
if _res != SDApiError.NoError.value:
if _res == SDApiError.NoErrorOutputParamNotSet.value:
return None
... | [
"def from_graph(cls, G):\n return cls(G)",
"def create_graph(self, *args, **kwargs):\n return Graph(*args, **kwargs)",
"def ggml_new_graph(ctx: ffi.CData) -> ffi.CData:\n ...",
"def from_dict(cls, graph: Dict[str, Any], name: str = 'UDS') -> 'UDSGraph':\n return cls(adjacency_graph... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the SDGraphObjectFrame title | def getTitle(self):
outValue = ctypes.c_char_p()
_res = self.mAPIContext.SDGraphObjectFrame_getTitle(self.mHandle, ctypes.byref(outValue))
if _res != SDApiError.NoError.value:
if _res == SDApiError.NoErrorOutputParamNotSet.value:
return None
raise APIExcep... | [
"def _get_title(fig):\n ax = fig.get_axes()[0] # assume first ax is correct\n title = ax.title.get_text()\n return title",
"def title(self):\n return self.figure.canvas.get_window_title()",
"def get_title(self):\n return self.metadata['title']",
"def getTitle(self):\n return self... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the SDGraphObjectFrame color | def getColor(self):
outValue = ColorRGBA()
_res = self.mAPIContext.SDGraphObjectFrame_getColor(self.mHandle, ctypes.byref(outValue))
if _res != SDApiError.NoError.value:
if _res == SDApiError.NoErrorOutputParamNotSet.value:
return None
raise APIException(S... | [
"def get_color(self) -> Optional[Tuple[int, int, int, int]]:\n if self.has_object_color():\n return None # object color\n else:\n return int2color(self._mode_color)[:3]",
"def get_color(self):\n return self.color",
"def GetDrawColor(self):\n ...",
"def fl_get... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set the SDGraphObjectFrame color | def setColor(self, value):
_res = self.mAPIContext.SDGraphObjectFrame_setColor(self.mHandle, ctypes.byref(value))
if _res != SDApiError.NoError.value:
if _res == SDApiError.NoErrorOutputParamNotSet.value:
return None
raise APIException(SDApiError(_res))
re... | [
"def set_framecolor(self, color):\n self.framecolor = color\n self.canvas.figure.set_facecolor(color)\n if callable(self.theme_color_callback):\n self.theme_color_callback(color, 'frame')",
"def colorFrame(self, _color):\n\t\tif self.frame:\n\t\t\tfor nr, i in enumerate(self.frame)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the SDGraphObjectFrame size | def getSize(self):
outSize = float2()
_res = self.mAPIContext.SDGraphObjectFrame_getSize(self.mHandle, ctypes.byref(outSize))
if _res != SDApiError.NoError.value:
if _res == SDApiError.NoErrorOutputParamNotSet.value:
return None
raise APIException(SDApiErr... | [
"def getFrameSize(self):\n \n return self.frame_size",
"def get_size_of_object(self):\n return self.size_of_objects",
"def fl_get_object_size(ptr_flobject):\n _fl_get_object_size = library.cfuncproto(\n library.load_so_libforms(), \"fl_get_object_size\", \\\n None, [cty.POI... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set the SDGraphObjectFrame size | def setSize(self, value):
_res = self.mAPIContext.SDGraphObjectFrame_setSize(self.mHandle, ctypes.byref(value))
if _res != SDApiError.NoError.value:
if _res == SDApiError.NoErrorOutputParamNotSet.value:
return None
raise APIException(SDApiError(_res))
retu... | [
"def setFrameSize(self, frame_size):\n \n self.frame_size = frame_size",
"def set_size(self, size):\n self.size_of_objects = size",
"def setDescriptorSize(self, dsize): # real signature unknown; restored from __doc__\n pass",
"def fl_set_object_size(ptr_flobject, width, height):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test working ssdp flow. | async def test_flow_ssdp(hass):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": SOURCE_SSDP}, data=SSDP_DATA,
)
assert result["type"] == "form"
assert result["step_id"] == "init"
assert result["description_placeholders"] == {
CONF_NAME: FRIENDLY_NAME,
... | [
"async def test_form_ssdp(hass: HomeAssistant) -> None:\n\n result = await hass.config_entries.flow.async_init(\n UNIFI_DOMAIN,\n context={\"source\": config_entries.SOURCE_SSDP},\n data=ssdp.SsdpServiceInfo(\n ssdp_usn=\"mock_usn\",\n ssdp_st=\"mock_st\",\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compile a model of URI's and Curies and then test the various types | def test_uri_and_curie(self):
self.single_file_generator('py', PythonGenerator, filtr=metadata_filter,
comparator=lambda exp, act: compare_python(exp, act, self.env.expected_path('foo.py')))
# Check that the interpretations are correct
self.single_file_generat... | [
"def test_resnet18():\n model = RestNet18()\n assert type(model) == RestNet18",
"def test_resolve_model_type(self):\n\n person = {\n \"type\": \"Person\"\n }\n\n self.assertEqual(\n People.resolve_model_type(person),\n (\"people\", \"Person\")\n )... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Splits document text into a list of sentences, given some model. | def get_sentences_list(text: str, model_type: str) -> t.List[str]:
sentences = []
sent_offsets = []
stok = SentenceTokenizer.from_type(model_type)
if isinstance(text, list):
sentences, sent_offsets = list(zip(*map(stok.tokenize, text)))
elif isinstance(text, str):
sentences, sent_off... | [
"def split_sentences(text):\n # Apply spacy language model\n doc = nlp(text)\n # Split sentences into list\n sentences = [sent.string.strip() for sent in doc.sents]\n\n return sentences",
"def sentences(doc):\n return [s.strip() for s in doc.split('. ')]",
"def split_into_sentences(text):\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
creates a vertical line in the diagram, reaching from the xaxis to the plot at a given time t | def create_time_line(self, axes, t, y, time_value, label):
# don't create lines on the very left
if time_value == t[-1]:
return
# create timeLine
time_line = Line2D([time_value, time_value],
[np.min(y), y[t.index(time_value)]],
... | [
"def vertical_line(t, n):\n lt(t)\n fd(t,n)\n rt(t)",
"def add_vertical_lines_for_time_points(ax, time_points, color, linewidth = 4):\n for tp in time_points:\n ax.axvline(x = tp, color = color, linewidth = linewidth)",
"def _line_plot(self):\n plt.plot(self._timestamps, self._values)\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate a coordinate moved by the provided `shift` parameters from the current Coordinate. | def move_to(self, shift: Move) -> Coordinate:
if shift.direction == "U":
new_coordinate = Coordinate(x=self.x, y=self.y + shift.dist)
elif shift.direction == "D":
new_coordinate = Coordinate(x=self.x, y=self.y - shift.dist)
elif shift.direction == "L":
new_coo... | [
"def shifted(self, shift):\n new_location = None if self.location is None else self.location + shift\n reference = None if self.reference is None else self.reference + shift\n return self.copy_with_changes(\n location=new_location, reference=reference, derived_from=self,\n )",... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return True if segments share start & end points, accounting for flipping. | def __eq__(self, other: Segment) -> bool:
return any(
(
self.start == other.start and self.end == other.end,
self.start == other.end and self.end == other.start,
)
) | [
"def segment_is_repeat(video_segment, video_segments_used):\n segment_overlaps = False\n used_segment_overlapped = None\n for used_segment in video_segments_used:\n start_overlaps = video_segment.src_start_time >= used_segment.src_start_time and \\\n video_segment.src_start_t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Wire a segment from the end of the current Segment using the provides `shift`. | def wire_to(self, shift: Move) -> Segment:
return Segment(self.end, self.end.move_to(shift)) | [
"def shift(self, shift):\n # TODO: track down other uses of this function and check them\n self.ts += shift",
"def shift(self, delay):\n self.__begin.shift(delay)\n self.__end.shift(delay)",
"def shift(self, shift):\n\n self._shift = shift",
"def shifted(self, shift):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Build wire segments from the internal wiring diagram. | def build_wires(self) -> List[Segment]:
segments = [Segment(self.ORIGIN, self.ORIGIN.move_to(self._diagram[0]))]
for step in self._diagram[1:]:
segments.append(segments[-1].wire_to(step))
return segments | [
"def construct_segments(self):\n for strand in self.strand_list:\n strand.construct_segment()",
"def generate(self, diagram):",
"def populate_segments(self, resolution):\n theta = pi/resolution\n normal = array([0, self.radius, 0])\n chord = array([-2*self.radius*sin(theta... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Find the closest intersection to the origin, by Manahattan distance, of two Wires. | def closest_intersect_manhattan(self, other: Wire) -> Tuple[Coordinate, int]:
intersection = sorted(self.intersect(other), key=lambda x: self.ORIGIN.dist(x.location))[0]
return intersection, self.ORIGIN.dist(intersection.location) | [
"def get_closest_intersection(wire1, wire2):\n pass",
"def distance(wires) -> int:\n\n wire_0_pos = get_positions(wires[0])\n wire_1_pos = get_positions(wires[1])\n\n # find intersections\n intersections = list(set(wire_0_pos).intersection(set(wire_1_pos)))\n # ignore the 0,0 intersect\n inte... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Find the closest intersection to the origin, by step distance, of two Wires. | def closest_intersect_steps(self, other: Wire) -> Tuple[Intersection, int]:
intersections = self.intersect(other)
# For each intersection, iterate along each wire's path until the intersection is
# encountered, keeping track of the number of steps taken
distances = []
for inters... | [
"def get_closest_intersection(wire1, wire2):\n pass",
"def closest_intersect_manhattan(self, other: Wire) -> Tuple[Coordinate, int]:\n intersection = sorted(self.intersect(other), key=lambda x: self.ORIGIN.dist(x.location))[0]\n\n return intersection, self.ORIGIN.dist(intersection.location)",
"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parse the input wiring diagram into a list of Move named tuples. Wiring diagrams are assumed to be of the form "R8,U15,L5,D23" | def _parse_diagram(wiring_diagram: str) -> List[Move]:
return [
Move(direction=shift[0], dist=int(shift[1:])) for shift in wiring_diagram.split(",")
] | [
"def parse_moves(moves):\n possible_moves = []\n for move in moves:\n if move == 'W':\n possible_moves.append('UP')\n elif move == 'D':\n possible_moves.append('RIGHT')\n elif move == 'S':\n possible_moves.append('DOWN')\n elif move == 'A':\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Simulates a smooth mouse drag | def drag(source, dest, speed=1000):
m = PyMouse()
m.press(*source)
time.sleep(0.1)
# number of intermediate movements to make for our given speed
npoints = int(sqrt((dest[0]-source[0])**2 + (dest[1]-source[1])**2 ) / (speed/1000))
for i in range(npoints):
x = int(source[0] + ((dest[0]-... | [
"def drag(x0, y0, x1, y1, delay=0):\n click(x0, y0, click=False)\n win32api.mouse_event(win32con.MOUSEEVENTF_LEFTDOWN,x0,y0,0,0)\n time.sleep(delay)\n click(x1, y1, click=False)\n win32api.mouse_event(win32con.MOUSEEVENTF_LEFTUP,x1,y1,0,0)",
"def mouseDragged():\n if mousePressed:\n mouse... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Simulates a mouse double click | def doubleclick(point):
m = PyMouse()
m.press(*point)
m.release(*point)
m.press(*point)
m.release(*point) | [
"def on_mouse_double_click(event):\n pass",
"def double_click(self):\n self._lutron.send(Lutron.OP_EXECUTE, Keypad._CMD_TYPE, self._keypad.id,\n self.component_number, Button._ACTION_DOUBLE_CLICK)",
"def double_click(button='left', coords=(0, 0)):\n _perform_click_input(but... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Stimulates typing a string of characters | def type_msg(string):
k = PyKeyboard()
k.type_string(string) | [
"def typing(text, speed):\n for char in text:\n sys.stdout.write(char)\n sys.stdout.flush()\n time.sleep(speed)",
"def chars(self, chars):\n\n self._chars = chars",
"def characters(self, data):\n pass",
"def slow_type(element, text):\n for character in text:\n e... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Simulates a mouse wheel movement | def wheel(ticks):
m = PyMouse()
m.scroll(ticks) | [
"def ev_mousewheel(self, event: MouseWheel) -> None:",
"def MouseWheelEvent(self, vtkContextMouseEvent, p_int):\n ...",
"def on_mouse_wheel(self, event):\n self.translate -= event.delta[1]\n self.game_program['u_view'] = self.view\n\n self.yaw, self.pitch = 0, 0\n\n self.rot_y... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compresses a byte array with the xz binary | def compress(value):
process = Popen(["xz", "--compress", "--force"], stdin=PIPE, stdout=PIPE)
return process.communicate(value)[0] | [
"def bytearray_to_postings(self, inverted_list_binary, compressed, df):",
"def byteswap_array(array):\n array_out = array.byteswap().newbyteorder()\n return array_out",
"def byteswap(self, *args, **kwargs): # real signature unknown\n pass",
"def swap_byte(byte_array, index):\n\n if byte_array[... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compress the file at 'path' with the xz binary | def compress_file(path):
process = Popen(["xz", "--compress", "--force", "--stdout", path], stdout=PIPE)
return process.communicate()[0] | [
"def compress_gzip(file_path, out_path):\n with open(file_path, 'rb') as f, gzip.open(out_path, 'wb') as out:\n shutil.copyfileobj(f, out)\n return out_path",
"def compress(infile):\r\n cmd = ' '.join([\"gzip\", \"-f\", infile])\r\n pipe = subprocess.run(cmd, shell=True,\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Shows a specific plane within 3D data. | def show_plane(axis, plane, cmap="gray", title=None):
axis.imshow(plane, cmap=cmap)
axis.set_xticks([])
axis.set_yticks([])
if title:
axis.set_title(title)
return None | [
"def plot_plane(self, debug=1,plane=0, linecolor='gray', hold=0, **plkwargs):\n xyz = self.xyz[plane*self.npoints:(plane+1)*self.npoints]\n pl.plot(xyz[:,0],xyz[:,2], '+', hold=hold, **plkwargs)\n ax=pl.gca()\n ax.set_aspect('equal')\n current_col = ax.get_lines()[-1].get_color()\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Allows to explore 2D slices in 3D data. | def slice_explorer(data, cmap='gray'):
data_len = len(data)
@interact(plane=(0, data_len-1), continuous_update=False)
def display_slice(plane=data_len/2):
fig, axis = plt.subplots(figsize=(20, 7))
axis_3d = fig.add_subplot(133, projection='3d')
show_plane(axis, data[plane], title='P... | [
"def take_slice(img_3D, view):\n input_type = isinstance(img_3D, np.ndarray)\n if input_type:\n img_3D = [img_3D]\n img_shape = img_3D[0].shape\n if view == \"sag\":\n slice_pos = np.random.randint(int(0.2 * img_shape[0]), int(0.8 * img_shape[0]))\n imgs_2D = [imgg_3D[slice_pos, :, ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generates a 3D surface plot for the specified region. | def plot_3d_surface(data, labels, region=3, spacing=(1.0, 1.0, 1.0)):
properties = measure.regionprops(labels, intensity_image=data)
# skimage.measure.marching_cubes expects ordering (row, col, plane).
# We need to transpose the data:
volume = (labels == properties[region].label).transpose(1, 2, 0)
... | [
"def DrawSurface(fig, varxrange, varyrange, function):\n ax = fig.gca(projection='3d')\n # ax = fig.add_subplot(111, projection='3d', proj_type='ortho')\n xx, yy = np.meshgrid(varxrange, varyrange, sparse=False)\n z = function(xx, yy)\n # ax.plot_surface(xx, yy, z, cmap='RdBu') # color map can be a... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Connect current container to the environment containers network. | def connect_to_containers_network():
logging.info("Connecting to the environment network")
container_id = get_current_container_id()
subprocess.check_output(
'docker network connect subsystem_tests-network {container_id}'.format(container_id=container_id),
shell=True) | [
"def connect_container(self, network_name):\n cmd_line = 'docker network connect %s %s' % (\n network_name, self.build_conf.container_name)\n return subprocess.check_call(cmd_line.split())",
"def connect(self, container_name: str, aliases: list[str] = None,\n ipv4: str | No... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Overrides Die.roll() so that in addition to rolling the dice, it sets the die's value based on the currentValue. | def roll(self):
self.currentValue = choice(self.possibleValues)
self.value = AngryDie.ANGRY_VALUES[self.currentValue]
return self.currentValue | [
"def roll(self):\n self.value = randint(1, 6)",
"def test_currentValue_is_updated_to_roll_value(self):\n rolled_value = self.new_die.roll()\n if rolled_value == self.new_die.currentValue:\n self.assertTrue(True, \"currentValue {} matches the rolled value\".format(self.new_die.curre... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A helper method that, given a valid faceValue, will update the die's currentValue and value to match the passed faceValue. | def setDieFaceValue(self, faceValue):
if faceValue in AngryDie.ANGRY_VALUES:
self.currentValue = faceValue
self.value = AngryDie.ANGRY_VALUES[faceValue] | [
"def face_value(self, face_value):\n self._face_value = face_value",
"def value(self, new_value):\n if (new_value > self.max_value):\n raise ValueError(\"This value is higher than the die's max value\")\n self._value = new_value",
"def test_face_value(self):\n\n # Setup th... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Roll the dice passed in the list. | def roll_the_dice(self, dice):
if type(dice) == list:
for die in dice:
die.roll() | [
"def roll(dice):\n rolled_dice = []\n for die in dice[1]:\n rolled_dice.append(randint(1, CUBE_DICE_MAX_VALUE()))\n dice[1] = rolled_dice\n return dice",
"def rollDices():\n for i in range(5):\n dices[i] = randint(1, 6)",
"def roll(self) -> 'Roll':\n rolls = {\n di... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Print both die values, as well as the current stage. | def print_dice(self):
stage_to_print = 3 if self.current_stage == 4 else self.current_stage
print("You rolled:\n a = [ {} ]\n b = [ {} ]\n\nYou are in Stage {}"
.format(self.die_a, self.die_b, stage_to_print)) | [
"def display_current_dice(self):\n print(\"You rolled:\\n a = [ {} ]\\n b = [ {} ]\\n\".\n format(self.die_a, self.die_b))",
"def __str__(self):\n return \"Die with {} sides. Result : {}\".format(self._sides, self._value)",
"def print_values(self):\n print \"Money %s, ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Prompt the user for input, and return the dice they want to roll. | def determine_roll(self):
dice_to_roll = []
to_roll = input("Roll dice: ")
if 'a' in to_roll:
dice_to_roll.append(self.die_a)
if 'b' in to_roll:
dice_to_roll.append(self.die_b)
return dice_to_roll | [
"def interactive_dice():\n return get_int('Result of dice roll: ', 1)",
"def roll_dice(player: int) -> int:\n sides = 6\n roll_again = input(\"Player {}: Press ENTER to roll your dice...\".format(player))\n num_rolled = roll(sides)\n print(\"You rolled {}.\".format(num_rolled))\n return num_roll... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check the state of the game and if conditions are met to advance the player to the next stage. | def check_stage(self):
#Initalize target and goal_stage to stage1 values
target = 3
goal_stage = 2
# Set target and goal_stage if current stage is not 1
if self.current_stage == 2:
target = 7
goal_stage = 3
elif self.current_stage == 3:
target = 11
... | [
"def advance(self):\r\n \r\n self.state += 1\r\n \r\n if self.state >= len(self.states):\r\n player.clear_puzzle()\r\n self.state = 1",
"def test_is_advancing_to_next_stage_yes(self):\n\n # test_input_cases =\n # [(die_a_value, die_b_value, stage, ok... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks to see if both dice are Angry, if so, sets current_stage to 1 | def check_angry(self):
if self.die_a.value == 3 and self.die_b.value == 3:
print("WOW, you're ANGRY!\nTime to go back to Stage 1!")
self.current_stage = 1 | [
"def handle_angry_dice(self):\n if self.die_a.current_value == \"ANGRY\" and self.die_b.current_value == \"ANGRY\":\n print(\"WOW, you're ANGRY!\\nTime to go back to Stage 1!\")\n self.game_stage = 1",
"def check_stage(self):\n\n #Initalize target and goal_stage to stage1 values\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
In Stage 3, they can only hold a 5 valued die. If they hold a 6, they'll be found cheating and thus, cannot win, or advance to the next stage. | def check_cheating(self, dice=[]):
#Assume they're not cheating until proven guilty
self.cheating = False
if self.current_stage == 3:
if self.die_a not in dice and (self.die_a.value == 6):
print("You're cheating! You cannot lock a 6! You cannot win "
"until you... | [
"def check_stage(self):\n\n #Initalize target and goal_stage to stage1 values\n target = 3\n goal_stage = 2\n\n # Set target and goal_stage if current stage is not 1\n if self.current_stage == 2:\n target = 7\n goal_stage = 3\n elif self.current_stage == 3:\n ta... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function locates all nearby cities within num_hops from the given city. It maintains a set of all the cities visited from the starting city at each hop. After completion, it removes the original city from the list of results | def find_nearby_cities(graph: TeleportGraph, city: str, num_hops: int = 1) -> set:
if num_hops == 0:
return set()
start_city_node = graph.find_city_node(city)
city_nodes = {start_city_node}
for i in range(num_hops):
related_cities = set()
# for every city in the current set,... | [
"def FindDHopCities(self, X, d):\n # G = nx.Graph()\n # G.add_nodes_from(self.nodes)\n # G.add_edges_from(self.edges)\n\n # airports_id_in_city = self.airports.loc[self.airports['city'] == X, 'airport_id'].to_list()\n\n # cities_h_hop = set()\n # for airport in airports_id_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function determines if two cities can be reached in the graph. This algorithm uses a breadthfirst search approach | def does_route_exist(graph: TeleportGraph, start_city: str, end_city: str) -> bool:
queue = Queue()
start_city_node = graph.find_city_node(start_city)
queue.put(start_city_node)
# keep track of the nodes we've visited - if we do not do this, we'll wind up in an infinite loop because since
# we're ... | [
"def are_connected(self, person1, person2):\n\n possible_nodes = Queue()\n seen = set()\n possible_nodes.enqueue(person1)\n seen.add(person1)\n\n while not possible_nodes.is_empty():\n person = possible_nodes.dequeue()\n print(\"checking\", person)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes a list of words as input and returns a list of the n most frequently occurring words ordered from most to least frequently occurring. | def get_top_n_words(word_list, n):
#Uses Counter function to create tuples of words and number of instances of word
wordCount = Counter(word_list)
topWords = []
orderedByFrequency = sorted(wordCount, key=wordCount.get, reverse=True)
#create list of inputted 'n' top words
for i in range (0 , n):
topWords.app... | [
"def get_top_n_words(word_list, n):\n\n\t# Creates a histogram of how often the same word appears in the book\n\tword_histogram = dict()\n\tfor word in word_list:\n\t\tword_histogram[word] = 1 + word_histogram.get(word, 0)\n\n\t# Converts the dictionary into a tuple and sorts the tuple by the frequency of each word... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert hex colorrange to RGBA. | def hex2rgba(colors):
if 'str' in str(type(colors)):
colors = np.array([colors])
rgbcolors = list(map(lambda x: matplotlib.colors.to_rgba(x), colors))
return np.array(rgbcolors) | [
"def hex_to_rgba(h, alpha):\n return tuple([int(h.lstrip('#')[i:i + 2], 16) for i in (0, 2, 4)] + [alpha])",
"def hex2rgb(hexcode):\n\treturn tuple(map(ord, hexcode[1:].decode('hex')))",
"def hex_to_xrgba(color):\r\n col = color.lower().strip(\"#\")\r\n return \"%s%s/%s%s/%s%s/ff\" % (*col,)",
"def h... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate colors from input list. This function creates unique colors based on the input list y and the cmap. When the gradient hex color is defined, such as '000000', a gradient coloring space is created between two colors. The start color of the particular y, using the cmap and The end color is the defined gradient, s... | def fromlist(y, X=None, cmap='Set1', gradient=None, method='matplotlib', scheme='rgb', opaque_type='per_class', verbose='info'):
# Set the logger
set_logger(verbose=verbose)
# make unique
y = np.array(y)
uiy = np.unique(y)
# Get colors
colors_unique = generate(len(uiy), cmap=cmap, method=me... | [
"def create_color_map():\n cmap = plt.cm.get_cmap('tab20b')\n\n crange_2D = np.linspace(0.3, 1.0, num=7)\n crange_3D = np.linspace(0.3, 1.0, num=8)\n crange_sem = np.linspace(0.5, 1.0, num=3)\n\n cmap2D = []\n cmap3D = []\n cmapsem = []\n\n for color in crange_2D:\n cmap2D.append((0, ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a gradient list of (n) colors between two hex colors. start_hex and finish_hex should be the full sixdigit color string, inlcuding the number sign ("FFFFFF") | def linear_gradient(start_hex, finish_hex="#FFFFFF", n=10):
if finish_hex=='opaque': finish_hex=start_hex
# Starting and ending colors in RGB form
s = _hex2rgb(start_hex)
f = _hex2rgb(finish_hex)
# Initilize a list of the output colors with the starting color
RGB_list = [s]
# Calcuate a colo... | [
"def gradient(text, start_color, end_color):\n length = len(text)\n\n # the delta of each color\n delta_r = start_color.r - end_color.r\n delta_g = start_color.g - end_color.g\n delta_b = start_color.b - end_color.b\n\n # the \"step\" sizes for each of the colors\n step_r = delta_r / length\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Color to dictionary. Takes in a list of RGB sublists and returns dictionary of colors in RGB and hex form for use in a graphing function defined later on. | def _color_dict(gradient):
hex_colors = [_rgb2hex(RGB) for RGB in gradient]
rgb_colors = np.c_[[RGB[0] for RGB in gradient], [RGB[1] for RGB in gradient], [RGB[2] for RGB in gradient]]
return {'hex': hex_colors, 'rgb': rgb_colors} | [
"def convert_to_color_dict_list(colors: list) -> list:\n color_dict_list = []\n\n for color in colors:\n hex_color = []\n for color_index in range(0, 3):\n hex_color_part = hex(color[color_index]).replace(\"0x\", \"\")\n if len(hex_color_part) == 1:\n hex_col... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |