query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Returns a LaTeX bmatrix | def _repr_latex_(self):
if len(self.shape) > 2:
raise ValueError("bmatrix can at most display two dimensions")
def fmt(x):
if x == 0:
return "."
if np.abs(x) < EPS:
return "0."
return "{:.2g}".format(x)
temp_string... | [
"def bmatrix(a):\n if len(a.shape) > 2:\n raise ValueError('bmatrix can at most display two dimensions')\n lines = str(a).replace('[', '').replace(']', '').splitlines()\n rv = [r'\\begin{bmatrix}']\n rv += [' ' + ' & '.join(l.split()) + r'\\\\' for l in lines]\n rv += [r'\\end{bmatrix}']\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to generate a slab firework. Returns a TransmuterFW if bulk_structure is specified, constructing the necessary transformations from the slab and slab generator parameters, or an OptimizeFW if only a slab is specified. | def get_slab_fw(
slab,
transmuter=False,
db_file=None,
vasp_input_set=None,
parents=None,
vasp_cmd="vasp",
name="",
add_slab_metadata=True,
):
vasp_input_set = vasp_input_set or MPSurfaceSet(slab)
# If a bulk_structure is specified, generate the set of transformations,
# els... | [
"def get_wf_slab(\n slab,\n include_bulk_opt=False,\n adsorbates=None,\n ads_structures_params=None,\n vasp_cmd=\"vasp\",\n db_file=None,\n add_molecules_in_box=False,\n):\n fws, parents = [], []\n\n if adsorbates is None:\n adsorbates = []\n\n if ads_structures_params is None:\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets a set of slab transformation params | def get_slab_trans_params(slab):
slab = slab.copy()
if slab.site_properties.get("surface_properties"):
adsorbate_indices = [
slab.index(s)
for s in slab
if s.properties["surface_properties"] == "adsorbate"
]
slab.remove_sites(adsorbate_indices)
# ... | [
"def get_affine_params(self):\n params = {'scales': [], 'shifts': []}\n for transform in reversed(self.transforms):\n if '_scale' in dir(transform):\n params['scales'].append(transform._scale)\n params['shifts'].append(transform._shift)\n return params",... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets a workflow corresponding to a slab calculation along with optional adsorbate calcs and precursor oriented unit cell optimization | def get_wf_slab(
slab,
include_bulk_opt=False,
adsorbates=None,
ads_structures_params=None,
vasp_cmd="vasp",
db_file=None,
add_molecules_in_box=False,
):
fws, parents = [], []
if adsorbates is None:
adsorbates = []
if ads_structures_params is None:
ads_structure... | [
"def get_slab_trans_params(slab):\n slab = slab.copy()\n if slab.site_properties.get(\"surface_properties\"):\n adsorbate_indices = [\n slab.index(s)\n for s in slab\n if s.properties[\"surface_properties\"] == \"adsorbate\"\n ]\n slab.remove_sites(adsorba... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get list of spoke drivers. | def spoke_drivers(self):
location = "spokedrivers"
return self.send_get(location,
params={}) | [
"def list_drivers(self):\n return self.ironic_client.driver.list()",
"def list_drivers():\n return jsonify(drivers)",
"def get_driver_list():\n return list(object_store.ObjectStorageDriver.registry.keys())",
"def getDrivers(self):\n\t\treturn self.__drivers",
"def get_driver_names():\n retur... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Delete a pin property. | def pin_delete(self, pin_id=None, path=None):
if path == None:
path = []
if pin_id != None:
path.insert(0, pin_id)
path.insert(0, "pin")
location = '/'.join(path)
return self.send_delete(location,
params={}) | [
"def DeleteProperty(*args, **kwargs):\n return _xrc.XmlNode_DeleteProperty(*args, **kwargs)",
"def delete_property(self, prop: Property) -> None:\n if type(prop) is not Property:\n raise TypeError(\"property {} is not of type Property!\".format(str(prop)))\n\n try:\n sel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add or delete schedule entry for pin. | def pin_schedule(self, pin_id, new_entry=None, entry_index=None):
if new_entry == None:
new_entry = {}
if new_entry != {} and entry_index != None: #can't create & delete
return False
elif entry_index != None: #delete the entry
return self.pin_delete(pin_id=pin... | [
"def put_schedule(self, name, schedule):\n self.__schedules[name] = schedule",
"def add(self, schedule):\n try:\n if schedule in self.set:\n self.log.error(\"%s has already been added to this Scheduler.\" %\n schedule)\n return\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
GET/PUT for pin object. | def pin(self, pin_id=None, path=None, value=None, **kwargs):
if path == None:
path = []
if pin_id != None:
path.insert(0, pin_id)
path.insert(0, "pin")
location = '/'.join(path)
if value != None:
decoded_json_response = self.send_put(location,... | [
"def get(self, pin):\n\t\treturn self.accounts.get(pin, None)",
"def get(self, name, pin):\r\n key = self.makeKey(name, pin)\r\n return self.accounts.get(key, None)",
"def getPin(self):\r\n return self.pin",
"def getPin(self):\n\t\treturn self.pin",
"def link(self, pin):\n hea... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Grab garage controller driver list. | def garage_controller_drivers(self):
location = "garagecontrollerdrivers"
return self.send_get(location, params={}) | [
"def camera_controller_drivers(self):\n location = \"cameracontrollerdrivers\"\n return self.send_get(location, params={})",
"def get_driver_list():\n return list(object_store.ObjectStorageDriver.registry.keys())",
"def list_drivers(self):\n return self.ironic_client.driver.list()",
"d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
GET/PUT for garage controller. | def garage_controller(self, garage_controller_id=None,
path=None, value=None, **kwargs):
if path == None:
path = []
if garage_controller_id != None:
path.insert(0, garage_controller_id)
path.insert(0, "garagecontroller")
location = '/'.jo... | [
"def GET(self):\n pass",
"def ng_get(self, request, *args, **kwargs):\r\n return self.build_json_response(self.get_object())",
"def method(self):\n return \"GET\"",
"def http_method_get():\n return 'GET'",
"def http_method_put():\n return 'PUT'",
"def _get(self, *args, *... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a new garage controller. | def garage_controller_create(self, name=None,
driver=None, driver_info=None):
location = "garagecontroller"
return self.send_post(location, params={"name":name,
"driver":driver,
... | [
"def create_controller() -> Controller:\n _controller = Controller()\n return _controller",
"def camera_controller_create(self, name=None,\n driver=None, driver_info=None):\n location = \"cameracontroller\"\n return self.send_post(location, params={\"name\":name... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Delete a garage controller. | def garage_controller_delete(self, garage_controller_id=None, path=None):
if path == None:
path = []
if garage_controller_id:
path.insert(0, garage_controller_id)
path.insert(0, "garagecontroller")
location = '/'.join(path)
return self.send_del... | [
"def delete_controller(cls, args, config):\n # print \"MOLNSProvider.delete_provider(args={0}, config={1})\".format(args, config)\n if len(args) == 0:\n raise MOLNSException(\"USAGE: molns cluser delete name\")\n config.delete_object(name=args[0], kind='Controller')",
"def camera_c... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Grab camera controller driver list. | def camera_controller_drivers(self):
location = "cameracontrollerdrivers"
return self.send_get(location, params={}) | [
"def get_cameras_list():\n lib.initlib()\n return lib.is_GetCameraList()",
"def cameras(self):\n return self._devices(\"cameras\")",
"def list_available_cameras():\n graph = FilterGraph()\n device_names = graph.get_input_devices()\n return device_names",
"def get_camera_list(cls):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
GET/PUT for camera controller. | def camera_controller(self, camera_controller_id=None,
path=None, value=None, **kwargs):
if path == None:
path = []
if camera_controller_id != None:
path.insert(0, camera_controller_id)
path.insert(0, "cameracontroller")
location = '/'.jo... | [
"async def update(self):\n _LOGGER.debug('Updating properties for camera %s', self.name)\n\n url = '%s/%s' % (ACCESSORIES_ENDPOINT, self.id)\n camera = await self._logi._fetch(\n url=url, method='GET')\n\n self._set_attributes(camera)",
"def camera(self):\r\n return s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a new camera controller. | def camera_controller_create(self, name=None,
driver=None, driver_info=None):
location = "cameracontroller"
return self.send_post(location, params={"name":name,
"driver":driver,
... | [
"def create():\n video_capture = cv2.VideoCapture(0)\n return Camera(video_capture)",
"def create_camera(self):\n pass",
"def createCamera():\n prefs = getPreferences()\n\n # Remove any pre-existing preview camera.\n if CAM_NAME in bpy.data.cameras:\n bpy.data.cameras.remove... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Delete a camera controller. | def camera_controller_delete(self, camera_controller_id=None, path=None):
if path == None:
path = []
if camera_controller_id:
path.insert(0, camera_controller_id)
path.insert(0, "cameracontroller")
location = '/'.join(path)
return self.send_del... | [
"async def delete_camera(camera_id: str):\n config_dict = extract_config()\n camera_names = [x for x in config_dict.keys() if x.startswith(\"Source\")]\n cameras = [map_camera(x, config_dict) for x in camera_names]\n cameras_ids = [camera[\"id\"] for camera in cameras]\n try:\n index = cameras... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
this method returns a onehot vector of the given size, where the 1 is placed in the ind entry. | def get_one_hot(size, ind):
one_hot = np.zeros((size,))
one_hot[ind] = 1
return one_hot | [
"def get_one_hot_vector(i, size=3):\n vec = np.zeros(size)\n vec[i] = 1\n return vec",
"def one_hot(length, index):\n result = np.zeros(length)\n result[index] = 1\n return result",
"def one_hot(idx, length):\n one_hot = np.zeros(length, dtype=np.bool)\n one_hot[idx] = True\n return one_hot... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
this method gets a sentence, and a mapping between words to indices, and returns the average onehot embedding of the tokens in the sentence. | def average_one_hots(sent, word_to_ind):
known_words = 0
size = len(word_to_ind.keys())
sum_vec = np.zeros((size,))
for token in sent.text: #going over all tokens and summing their embeddings
if (token in word_to_ind):
sum_vec += get_one_hot(size, word_to_ind[token])
know... | [
"def sentence_to_avg(sentence, word_to_vec_map):\n\n ### START CODE HERE ###\n # Step 1: Split sentence into list of lower case words (鈮?1 line)\n words = sentence.lower().split()\n\n # Initialize the average word vector, should have the same shape as your word vectors.\n avg = np.zeros((50,))\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
this function gets a dictionary mapping words to their counts, and returns a mapping between words to their index. Words that come after the cutoff | def get_word_to_ind (count_dict, cutoff = 0):
word_to_ind = {}
if (not cutoff):
cutoff = len(count_dict.keys())
#sorting the words by their count:
sorted_tuples = list(reversed(sorted(count_dict.items(), key=operator.itemgetter(1))))
for i in range(cutoff):
cur_word = sorted_tuples[i... | [
"def word_map(words, find):\n wordMap = {}\n # initialize the wordmap\n for word in find:\n wordMap[word.lower()] = 0\n\n #count the words in our list of words\n for w in words:\n w = w.strip(string.punctuation + string.whitespace)\n if w in find:\n wordMap[w] += 1\n\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function calculates the efficiency of exchange for a plate heat exchanger according to the NTU method of AShRAE 90.1 | def calc_plate_HEX(NTU, cr):
eff = 1 - scipy.exp((1 / cr) * (NTU ** 0.22) * (scipy.exp(-cr * (NTU) ** 0.78) - 1))
return eff | [
"def manipulate_heat_data(self): \n self.exh.T_array = ( 0.5 * (self.exh.T_inlet_array +\n self.exh.T_outlet_array) + 273.15)\n self.exh.delta_T_array = ( self.exh.T_inlet_array -\n self.exh.T_outlet_array )\n \n self.cool.delta_T_array = ( self.cool.T_inlet_array -... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that a made up long hand configurable is ignored | def testFakeLongHandConfigurables(self):
config = self.getBaseConfiguration()
# The following should be ignored by the configure step
config.Webtools.section_('foo')
config.Webtools.foo.bar = 'baz'
config.Webtools.section_('stuff')
config.Webtools.stuff = 'things'
... | [
"def test_checkCustoms(self):\n self.failUnlessEqual(self.nice.opts['myflag'], \"PONY!\")\n self.failUnlessEqual(self.nice.opts['myparam'], \"Tofu WITH A PONY!\")",
"def test_set_defaults(self):\r\n self.assertEqual(self.config.values['option1'], 1337)\r\n self.assertNotIn('option2', s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check that changing the proxy base via tools.proxy.base does actually change the proxy base | def testLongHandProxyBase(self):
test_proxy_base = '/unit_test'
config = self.getBaseConfiguration()
config.Webtools.section_('tools')
config.Webtools.tools.section_('proxy')
config.Webtools.tools.proxy.base = test_proxy_base
config.Webtools.tools.proxy.on = True
... | [
"def testShortHandProxyBase(self):\n test_proxy_base = '/unit_test'\n\n config = self.getBaseConfiguration()\n # Set the proxy base with a short hand cfg variable\n config.Webtools.proxy_base = test_proxy_base\n server = Root(config)\n\n server.start(blocking=False)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check that changing the proxy_base via the short hand config variable does actually change the proxy base | def testShortHandProxyBase(self):
test_proxy_base = '/unit_test'
config = self.getBaseConfiguration()
# Set the proxy base with a short hand cfg variable
config.Webtools.proxy_base = test_proxy_base
server = Root(config)
server.start(blocking=False)
self.assertE... | [
"def testLongHandProxyBase(self):\n test_proxy_base = '/unit_test'\n\n config = self.getBaseConfiguration()\n config.Webtools.section_('tools')\n config.Webtools.tools.section_('proxy')\n config.Webtools.tools.proxy.base = test_proxy_base\n config.Webtools.tools.proxy.on = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Change the port the server runs on long hand, then over ride it with the short hand equivalent | def testShortHandPortOverride(self):
test_port = 8010
config = self.getBaseConfiguration()
# Set the port the long handed way
config.Webtools.section_('server')
config.Webtools.server.socket_port = test_port - 1
# then override
config.Webtools.port = test_port
... | [
"def set_port(port):\n update_options_file(\"Deployment\", \"HTTP_PORT\", port)",
"def set_port(self, port):\n \tself._port = port",
"def set_server_port(self,server_port: int):\n self.server_port = server_port\n return self",
"def server_port(self, server_port):\n\n self._server_po... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Use the filter tool to prevent unexpected accesses from unsupported methods TODO | def testUsingFilterTool(self):
pass | [
"def _filter(self):",
"def filter(ctx):\n pass",
"def filter_method( self, name ):\n return name[0] == '_'",
"def filter(fn):\n fn.is_filter = True\n return fn",
"def filter(self, filters):",
"def _filter(self, filter_condition):",
"def filterRansac():\n pass",
"def filter_request()... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
use the chemical formulas from the InChIs to verify that each and every reaction is balanced | def balance_reactions(self):
element_df = ccache.get_element_data_frame(self.cids)
# find all reactions that contain only compounds that have formulae
cpd_with_formulae = (element_df != 0).any(axis=1)
logger.info('# compounds without a formula: %d'
% sum(~cpd_with_fo... | [
"def test_chemical_formula(self):\n self.assertEqual(self.structure.chemical_formula, \"Ag2 U\")",
"def test_consumable(self):\n\n # Create an assembly part\n assembly = Part.objects.create(name=\"An assembly\", description=\"Made with parts\", assembly=True)\n\n # No BOM information i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculate the reverse transform for all reactions in training_data. | def reverse_transform(self):
self.reaction_df['dG0'] = self.reaction_df['dG0_prime']
for i, rxn in self.iterreactions():
aq_cond = self.reaction_df.loc[i, ['pH', 'I', 'T']]
self.reaction_df.at[i, 'dG0'] -= rxn.get_transform_ddG0(*aq_cond) | [
"def to_reversible(self):\n\n def get_rir_examples(examples):\n return [\n Example(example.utterance, self.f_reversible(example))\n for example in examples\n ]\n\n return get_rir_examples(self.train_examples), get_rir_examples(\n self.test_examples)",
"def apply_inverse_pr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Load a data frame with information from the TECRdb (NIST). The componentcontribution package distributes data tables with information on the 'thermodynamics of enzymecatalyzed reactions'[1, 2]_ that are used as training data. Returns pandas.DataFrame References .. [1] Goldberg, Robert N., Yadu B. Tewari, and Talapady N... | def read_tecrdb():
with resource_stream('component_contribution',
FullTrainingData.REACTION_ENERGY_FNAME) as fp:
tecr_df = pd.read_csv(gzip.GzipFile(fileobj=fp))
for col in ["T", "I", "pH", "pMg", "K'"]:
tecr_df[col] = tecr_df[col].apply(float)
... | [
"def _fetch_dataframe(self):\n\n df = pd.DataFrame([self._reshape(component) for component in self._get_trial_components()])\n return df",
"def load_data() -> pd.DataFrame:\n index_cols = [\"level\", \"country\", \"region\", \"sub_region\", \"date\"]\n ts_df = time_series_formatter(fetch_time_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Read the Formation Energy data from literature data [16] Returns pandas.DataFrame References .. [1] Alberty (2006) .. [2] Maden (2000) .. [3] Thauer (1977) .. [4] Wagman (1982) .. [5] Dolfing (1992) .. [6] Dolfing (1994) | def read_formations():
with resource_stream('component_contribution',
FullTrainingData.FORMATION_ENERGY_FNAME) as fp:
formation_df = pd.read_csv(gzip.GzipFile(fileobj=fp))
cids_that_dont_decompose = set(
formation_df.loc[formation_df['decompose'] ==... | [
"def read_life_expectancy() -> pd.DataFrame:\n\n life_df = pd.read_csv(\"data/API_SP.DYN.LE00.IN_DS2_en_csv_v2_988752.csv\",\n header=2, usecols=[0,62], names=[\"Country\", \"Life expectancy\"])\n\n index = life_df[life_df[\"Country\"]==\"Iran, Islamic Rep.\"].index.values[0]\n lif... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Read the Reduction potential from literature data [18] Returns pandas.DataFrame References .. [1] CRC biochemistry (2010) .. [2] Prince (1987) .. [3] Thauer (1977) .. [4] CRC biochemistry (2010) .. [5] Alberty (2006) .. [6] Deppenmeier (2008) .. [7] Saeki (1985) .. [8] Unden (1997) | def read_redox():
with resource_stream('component_contribution',
FullTrainingData.OXIDATION_POTENTIAL_FNAME) as fp:
redox_df = pd.read_csv(gzip.GzipFile(fileobj=fp))
delta_nH = redox_df['nH_red'] - redox_df['nH_ox']
delta_charge = redox_df['charge_red'] ... | [
"def read_tecrdb():\n with resource_stream('component_contribution',\n FullTrainingData.REACTION_ENERGY_FNAME) as fp:\n tecr_df = pd.read_csv(gzip.GzipFile(fileobj=fp))\n\n for col in [\"T\", \"I\", \"pH\", \"pMg\", \"K'\"]:\n tecr_df[col] = tecr_df[co... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
create a dictionary for one hot vector representation of valence electrons | def dict_shell_v_electrons_for_one_hot_vector():
# s1 - f14 is notated as shell_v_electons
# number in s1 ... f14 indicates how many valence electrons are in that shell,
# ex: p5 indicates that there are 5 valence electrons in the p shell
# value in the dict corresponds to index of the one-hot-vector
... | [
"def create_one_hot(eles):\n\tone_hot = {}\n\tfor i, l in enumerate(eles):\n\t\tbits = [0]*len(eles);\t#Every element in the string/list is assigned 0\n\t\tbits[i] = 1;\t#Only one bit is set to \"ON\"\n\t\tone_hot[l] = bits \t#Actual assignment is made\n\treturn one_hot",
"def atom_to_hot_vector(self, elem: str):... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
get valence electrons for an element in the structure | def get_shell_v_electrons(element):
# s1 - f14 is notated as shell_v_electons
# get shell_v_electons for corresponding element
if element == 'H':
return ['s1']
elif element == 'He':
return ['s2']
else:
valence_electrons = periodic_table.Element(element).electronic_structure[5... | [
"def valence_electron(element):\n configuration = element.data[\"Electronic structure\"]\n list_split = configuration.split('.')\n\n valence_electrons = 0\n\n for i in range(len(list_split)):\n if 'sup' in list_split[i]:\n electrons = re.search('<sup>(.*)</sup>', list_split[i])\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
get polyhedras for each of the sites in the structure return a list | def get_polyhedras_for_all_sites(structure):
# index of list = index of the structure site
# given an index returns a list of dictionaries
# index correspods to the site of the central atom and dictionary has all neighbors as key and corresponding angle ratios as values
v_polyhedra_sites = []
for i ... | [
"def _get_legislatures():\n catalog = api.portal.get_tool('portal_catalog')\n results = catalog(object_provides=ILegislature.__identifier__)\n\n if not results:\n return []\n\n results = [r.getObject() for r in results]\n results = sorted(results, key=lambda l: l.start_date, reverse=True)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The compute_FAR method is used to compute the False Acceptance Rate (FAR). | def compute_FAR(self, impostor_score, thresholds=0.01):
print('Computing FAR')
condition = lambda score, thr: score > thr
return self._F_performance(np.squeeze(np.array(impostor_score)), thresholds, condition) | [
"def calculate_FAR_of_thresh(self, threshold, livetime, groundtype):\n\t\t#Find FAR from number of events above a threshold\n\t\tFAR = float(np.sum(self.LLR_above_thresh(threshold=threshold, groundtype=groundtype)))/float(livetime)\n\t\t\n\t\t#If FAR is null, choose FAR to be that of the most extreme background eve... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The compute_FRR method is used to compute the False Rejection Rate (FRR). | def compute_FRR(self, genuine_score, thresholds=0.01):
print('Computing FRR')
condition = lambda score, thr: score <= thr
return self._F_performance(genuine_score, thresholds, condition) | [
"def getF_and_R(self):\n R = self.getR()\n # Treat the laminar case: f = 64/R\n if R < 2000: # R < 2000 implies flow is laminar\n if R > 0:\n f = 64/R # Darcy's equation for friction factor\n return {\"R\": R, \"f\": f}\n elif R == 0:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The _compute_thresholds method computes the list of thresholds to use in computing FAR and FRR (FOR INTERNAL USE ONLY). | def _compute_thresholds(self, thresholds):
thr = thresholds
limit = int(1 / thresholds)
thresholds = [x * thr for x in range(limit)]
thresholds.append(1)
return thresholds | [
"def compute_thresholds(self):\n if self.mode == 'exponential' and self.source_min <= 0:\n self.warnings['nonposmin'] = 'non-positive minimum'\n self.mode = 'linear'\n\n if self.mode == 'linear':\n thresholds = self.linear_thresholds\n elif self.mode == 'sinh':\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The compute_EER method computes the Equal Error Rate (EER) through the False Acceptance Rate (FAR) and the False Rejection Rate (FRR). | def compute_EER(self, FAR, FRR):
print('Computing EER')
distance = abs(FAR - FRR)
min_distance = min(distance)
idx = np.where(distance == min_distance)
return np.mean((FAR[idx] + FRR[idx]) / 2) | [
"def compute_EER(Pfa, Pmiss):\n fpr, fnr = Pfa, Pmiss\n diff_pm_fa = fnr - fpr\n x1 = np.flatnonzero(diff_pm_fa >= 0)[0]\n x2 = np.flatnonzero(diff_pm_fa < 0)[-1]\n a = (fnr[x1] - fpr[x1]) / (fpr[x2] - fpr[x1] - (fnr[x2] - fnr[x1]))\n return fnr[x1] + a * (fnr[x2] - fnr[x1])",
"def evaluate_eGFR(data: Dict[... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The compute_AUC method computes the Area Under the Curve (AUC) value from the False Acceptance Rate (FAR) and the Correct Acceptance Rate (CAR). | def compute_AUC(self, FAR, CAR):
print('Computing AUC')
return abs(np.trapz(CAR, FAR)) | [
"def _calculate_roc(self):\n if self.testing:\n visualize_heatmap_cf(self.y, self.y_hat, save_location=self.test_folder)\n else:\n visualize_heatmap_cf(self.y, self.y_hat, save_location=self.folder)\n print('Area under the curve: {:0.5f}'.format(roc_auc(self.y, self.y_hat)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The compute_CRR method computes the Correct Rejection Rate (CRR) from the False Acceptance Rate (FAR). | def compute_CRR(self, FAR):
print('Computing CRR')
return (np.ones((1, len(FAR))) - FAR)[0] | [
"def compute_CAR(self, FRR):\r\n print('Computing CAR')\r\n return (np.ones((1, len(FRR))) - FRR)[0]",
"def roc(ground_truth, pred_result):\n assert len(ground_truth)==len(pred_result)\n tp, fp, tn, fn = 1e-8, 1e-8, 1e-8, 1e-8\n for i in range(len(ground_truth)):\n if ground_truth[i]... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The compute_CAR method computes the Correct Acceptance Rate (CAR) from the False Rejection Rate (FRR). | def compute_CAR(self, FRR):
print('Computing CAR')
return (np.ones((1, len(FRR))) - FRR)[0] | [
"def compute_CRR(self, FAR):\r\n print('Computing CRR')\r\n return (np.ones((1, len(FAR))) - FAR)[0]",
"def compute_AUC(self, FAR, CAR):\r\n print('Computing AUC')\r\n return abs(np.trapz(CAR, FAR))",
"def FRET_efficiency(radius, R0):\n return 1 / (1 + (radius / R0) ** 6)",
"def... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The compute_performance_analysis method computes the False Acceptance Rate (FAR), the False Rejection Rate (FRR), the Correct Rejection Rate (CRR), the Correct Acceptance Rate (CAR) for each threshold value, the Equal Error Rate (EER) and the Area Under the Curve (AUC) on a genuine scores array and an impostor scores a... | def compute_performance_analysis(self, G, I, thresholds=0.01):
FAR = self.compute_FAR(I, thresholds)
FRR = self.compute_FRR(G, thresholds)
CRR = self.compute_CRR(FAR)
CAR = self.compute_CAR(FRR)
EER = self.compute_EER(FAR, FRR)
AUC = self.compute_AUC(FAR, CAR)
... | [
"def compute_analysis(self, data, labels, distance, thresholds=None):\r\n print(' Computing genuine and impostor scores')\r\n scores = self.compute_scores(data, distance)\r\n if thresholds is None:\r\n G, I, thresholds = self.genuines_and_impostors(scores, labels)\r\n else:\r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The compute_analysis method computes the False Acceptance Rate (FAR), the False Rejection Rate (FRR), the Correct Rejection Rate (CRR), the Correct Acceptance Rate (CAR) for each threshold value, the Equal Error Rate (EER) and the Area Under the Curve on a data matrix. | def compute_analysis(self, data, labels, distance, thresholds=None):
print(' Computing genuine and impostor scores')
scores = self.compute_scores(data, distance)
if thresholds is None:
G, I, thresholds = self.genuines_and_impostors(scores, labels)
else:
G, ... | [
"def compute_performance_analysis(self, G, I, thresholds=0.01):\r\n FAR = self.compute_FAR(I, thresholds)\r\n FRR = self.compute_FRR(G, thresholds)\r\n CRR = self.compute_CRR(FAR)\r\n CAR = self.compute_CAR(FRR)\r\n EER = self.compute_EER(FAR, FRR)\r\n AUC = self.compute_AU... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The genuines_and_impostors method computes the genuine scores and the impostor scores. | def genuines_and_impostors(self, scores, labels):
print('Computing genuine scores and impostor scores')
scores_dimension, genuine_dimension, impostor_dimension = self._define_dimensions(scores, labels)
genuine_score = np.zeros(shape=(genuine_dimension, 1))
impostor_score = np.zeros(s... | [
"def compute_scores():\n\n prediction_table = load_predictions(\"all\")\n\n # ROC AUC scores\n roc_aucs = compute_score(prediction_table, roc_auc_score)\n roc_aucs = roc_aucs.round(4)\n save_evaluation(roc_aucs, \"roc_auc\")\n\n # Brier loss scores\n brier_losses = compute_score(prediction_tabl... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The scores_statiscics computes a set of descriptive statistical parameters (mean, median, standard deviation) on the array of similarity scores. | def scores_statistics(self, scores):
aux_scores = np.array(scores)
return np.mean(aux_scores), np.median(aux_scores), np.std(aux_scores) | [
"def __attributes_statistics(dataset):\n\t\tattr_summaries = np.empty([dataset[0, :].size - 1, 2])\n\t\tfor i in range(0, dataset[0, :].size-1):\n\t\t\tattr_summaries[i,0] = np.mean(dataset[:, i])\n\t\t\tattr_summaries[i,1] = np.std(dataset[:, i])\n\t\treturn attr_summaries",
"def scores_stat(scores, N):\n\n s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
returns the value of the node at nth position from the end of the list | def value_n_from_end(self, n):
# check the validity of the input
if n > self.n-1:
print(f"Error; n is greater than the length of the list = {self.n-1}")
return
temp_node = self.head # store head
for _ in range((self.n-1) - n):
temp_node = te... | [
"def nth_node_from_end(self, n):\n\n length = 0\n\n if self.head:\n current = self.head\n while current:\n length += 1\n current = current.next\n\n count = 0\n current = self.head\n while count < (length - n): \n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Delete the entire linked list | def delete_list(self):
temp_node = self.head
while temp_node is not None:
prev_node = temp_node
temp_node = temp_node.next
# prev_node.val += ": deleted" # for sanity check
# reset data
prev_node.val = None
prev_node.next = None | [
"def __del__(self):\n cur = self.head\n prev = None\n while cur is not None:\n prev = cur\n cur = cur.next\n # Remove all references from prev\n prev.next = None\n del prev\n # end of while\n self.head = None",
"def list_del... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Converts the string s to unicode if it is of type bytes. | def to_unicode(s, encoding="utf-8"):
if isinstance(s, six.text_type):
return s
elif isinstance(s, bytes):
return s.decode(encoding)
# TODO: warning? Exception?
return s | [
"def asunicode(s):\n if isinstance(s, bytes):\n return s.decode('utf-8', 'replace')\n else:\n return s",
"def force_unicode(s):\n if isinstance(s, str):\n return s.decode(\"utf8\")\n return s",
"def force_unicode(s):\n return (s.decode('utf8')\n if isinstance(s, st... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test case for create_currency_using_post | def test_create_currency_using_post(self):
pass | [
"def test_currency_post(self):\n\n data = {\"code\": \"BYN\", \"name\": \"Belarusian rubles\"}\n response = self.post_currency(data)\n\n currency = Currency.objects.get(code=data[\"code\"])\n\n assert response.status_code == status.HTTP_201_CREATED\n assert Currency.objects.count(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test case for get_currency_all_using_get | def test_get_currency_all_using_get(self):
pass | [
"def test_get_currency_using_get(self):\n pass",
"def test_market_currencies_get(self):\n pass",
"def getCurrencies():",
"def test_get_currency_values_retrieves_existing(self):\n values = get_currency_values(self.test_date)\n self.assertEqual(values[\"HAF\"], 0.5)\n self.ass... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test case for get_currency_using_get | def test_get_currency_using_get(self):
pass | [
"def test_get_currency_all_using_get(self):\n pass",
"def test_market_currencies_get(self):\n pass",
"def getValue(currency=None):",
"def getUserCurrency():",
"def test_search_currency_conversion(self):\n pass",
"def getCurrencies():",
"def test_get_currency_values_retrieves_existin... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test case for update_currency_using_put | def test_update_currency_using_put(self):
pass | [
"def test_currency_put_update(self):\n\n data = {\"code\": \"BYN\", \"name\": \"Belarusian rubles\"}\n response = self.post_currency(data)\n\n url = reverse(\"currency-detail\", None, {response.data[\"id\"]})\n new_data = {\n \"code\": \"EUR\",\n \"name\": \"Euro\",... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Constructor for Battleship class Populates shipes list with random coordinates | def __init__(self):
# self.ships = [
# (1, 1),
# (1, 2),
# (3, 4),
# (4, 5),
# ] | [
"def __init__(self):\n self.total_ships = 0\n self.starting_position = None\n self.total_rows_req = 0\n self.total_column_req = 0\n self.shipList = []",
"def __init__(self, player, missing_ships, mode_spread):\n self.player = player\n\n self.attack_pos = []\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Handshake with a v11 server. Server sends version after authentication | def test_handshakeV11(self):
user=padString('hello')
host=padString('world')
self.sfact.program= \
[('recv',CAmessage(dtype=0, count=CA_VERSION)),
('recv',CAmessage(cmd=20, size=len(user), body=user)),
('recv',CAmessage(cmd=21, size=len(host), body... | [
"def handshake(self):\n version = Version()\n version_serial = VersionSerializer()\n self.send_message(version, version_serial)",
"def _negotiateVersion(self):\n \n assert self._connect()\n \n server_ver_data = self.SOCK.recv(BUFFER_SIZE)\n server_version = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given the location of a log directory, returns all of the Method logs in a list to have their data imported. | def importMethodFileNames(directory):
allfileNames = os.listdir(directory)
methodsRunList = []
for filename in allfileNames:
if "_MethodRunLog_" in filename:
methodsRunList.append(filename)
return methodsRunList | [
"def importAllLogData(directory):\n\n listofRunData = []\n filenames = importMethodFileNames(directory)\n\n for name in filenames:\n listofRunData.append(importTestData(directory +'/' + name))\n\n return listofRunData",
"def all_logs(self):\n return os.listdir(LOGS_BASE_PATH)",
"def ge... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a log directory by the user returns lists of all the recorded data from the logs resulting log is a three dimensional array | def importAllLogData(directory):
listofRunData = []
filenames = importMethodFileNames(directory)
for name in filenames:
listofRunData.append(importTestData(directory +'/' + name))
return listofRunData | [
"def get_access_logs(file_dir=log_dir):\n \n file_list = []\n for myfile in glob.glob1(file_dir, 'access_log*'):\n file_list.append('%s/%s' % (file_dir, myfile))\n# print file_list\n return file_list",
"def getLogData():\r\n # Read contents\r\n logData = readTxtFile()\r\n return log... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If a selling transaction has been started, this view will display an address and request the details necessary from the user for the chosen payment processor | def selling_page_2(request, tx_id):
# get the transaction from the passed id
tx = get_object_or_404(Transactions, id=tx_id)
# get the payment_processor name from the tx
payment_processor = None
for pp in globs.PAYMENT_PROCESSORS:
if pp[0] == tx.payment_processor:
payment_processo... | [
"def checkout_shipping_address_view(request):\n if not request.session.get(\"cart\"):\n empty_cart_modal(request)\n return redirect(\"products\")\n if request.method == \"POST\":\n customer_shipping = CustomerShippingForm(request.POST)\n if customer_shipping.is_valid():\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
False unless node is a h1h6 node containing an anchor. | def is_headline(node):
pass | [
"def isAnchor(node):\n # TODO What is considered an anchor needs to be subject to an option\n return bool((isinstance(node, nodes.target)\n or isinstance(node, nodes.Structural))\n and node[DuAttrIds]\n and not node.get(DuAttrRefuri, None))",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The text in headline node (text of anchor element). | def headline_text(node):
pass | [
"def headline(self):\n \n return self._headline",
"def is_headline(node):\n pass",
"def get_node_text(self):\n return self.node_text",
"def getNodeTitle(self, node):\n return node.title()",
"def link_text(self):\n return self._link_text",
"def add_headline(self, selec... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A list of all headlines in html_root_node. | def all_headlines(html_root_node):
pass | [
"def get_headlines(self, kw = None):\r\n\t\tif kw:\r\n\t\t\treturn self.get_headlines_with_keyword(kw)\r\n\t\telse:\r\n\t\t\treturn self.get_all_headlines()",
"def headings(self):\n return [el for el in self.elements if isinstance(el, Heading)]",
"def all_headlines_from(url):\n pass",
"def heads(sel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Open url using `urlib` and extract all the headlines from it. | def all_headlines_from(url):
pass | [
"def get_headlines(url):\n feed = feedparser.parse(url)\n headlines = [x['title'] for x in feed['entries']]\n return headlines",
"def gather_headlines(urls):\n pass",
"def read_web(url):\n f = urllib.request.urlopen(url)\n contents = f.read()\n return contents",
"def fetch(url):\n line... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the aggregate list of every headline found in each url in `urls`. | def gather_headlines(urls):
pass | [
"def get_titles(urls):\n\n titles = []\n for url in urls:\n with urlopen(url) as response:\n encoding = response.info().get_content_charset(failobj=\"utf-8\")\n html = response.read().decode(encoding)\n title_parser = TitleParser()\n title_parser.feed(html)\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function fills GENERO table by values recorded in genre_list (extractionTitleBasics function) | def insertionGenero (cur, conn, genre_list):
for genre in genre_list :
idGenero = genre[0]
genero=genre[1]
# print(generoInsert.format(idTitulo,genero))
# REGISTER DATA IN GENERO TABLE
cur.execute(generoInsert.format(idGenero,genero))
conn.commit() | [
"def fill_genre(conn, cur, genresraw, m_id):\n\t# Statement to use to insert into the genres table\n\n\tginsert = \"INSERT IGNORE INTO movies.genres(genre_id, genre_name) VALUES (%s, %s)\"\n\t# Statement to use to insert into the movies_genres table\n\tmginsert = \"INSERT INTO movies.movies_genres (genre_id, movie_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Merge the metadata on the obj (module) with whatever is in the dom parameter. From the spec. what should be replaced and what we should just add to. | def mergeMetadata(self, obj, dom):
self.update_semantics = 'merge'
# create a metadata dict that has all the values from obj, overridden
# by the current dom values.
metadata = self.getModuleMetadata(obj, {})
metadata.update(self.getMetadata(dom, METADATA_MAPPING))
... | [
"def PopulateModuleMetadata(self, mod, mojom_file):\n mod.name = os.path.basename(mojom_file.file_name)\n mod.path = mojom_file.file_name\n mod.namespace = mojom_file.module_namespace\n if mojom_file.attributes:\n mod.attributes = {attr.key: attr.value for attr in mojom_file.attributes}",
"def _p... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compute the updated roles just the list of userids and roles in the xml Compute the deleted roles collaborators that are currently on the object, but not in the xml Compute the cancelled roles pending collaboration request for which there are no roles in the xml | def updateRoles(self, obj, dom):
domRoles = self.validateRoles(self.getRolesFromDOM(dom))
moduleRoles = self.validateRoles(self.getRolesFromModule(obj))
updateRoles = {}
deleteUsers = []
cancelRoles = []
if self.action == 'create' or self.update_semantics == 're... | [
"def recalculate_roles(worker):\n for gspd in worker.source.administrator_page.participant_group.groupspecificparticipantdata_set.all():\n gspd.recalculate_roles()\n worker.unilog(\"All roles are recalculated, to update the leaderboard run /recreate_leaderboard command.\")",
"def get_roles():\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
we override init in order to add DELETE as a legitemate call in RhaptosSword land. | def __init__(self, context, request):
EditMedia.__init__(self, context, request)
SWORDTreatmentMixin.__init__(self, context, request)
self.callmap.update({'DELETE': self.DELETE,}) | [
"def _initDeleteEntryDocument(self, atomDoc): #@UnusedVariable #$NON-NLS-1$\r\n pass",
"def before_delete(self, obj, st):\n pass",
"def __init__(self, *args, **kwargs):\n super(RebuildDeleteObjects, self).__init__(*args, **kwargs)\n self.punched_obj_indices = None\n self.punch... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Bully Election Algrorithm, largest id becomes the primary copy at failure to connect to primary copy the server sends a election message to each replication server if a server has a higher ID it replies with an election message then sends another election message else if no server replies then server becomes the primar... | def election(epoch, counter):
election_msg="ELECTION {} {}".format(epoch, counter)
has_highest_id=True
for neighbor_id, neighbor in setting['neighbor'].items():
try:
neighbor.send(election_msg)
response = neighbor.recv(1024)
print "response {} = {}\n".format(neig... | [
"def testPrimaryElectionCase2(case2Setup, looper, txnPoolNodeSet):\n A, B, C, D = txnPoolNodeSet\n\n looper.run(checkNodesConnected(txnPoolNodeSet))\n\n # Node B sends multiple NOMINATE msgs but only after A has nominated itself\n timeout = waits.expectedPoolNominationTimeout(len(txnPoolNodeSet))\n l... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Remove all occurrence data that is beyond the timeframe away | def garbage_collect(self, timestamp):
stale_keys = []
for key, window in list(self.occurrences.items()):
if timestamp - lookup_es_key(window.data[-1][0], self.ts_field) > self.rules['timeframe']:
stale_keys.append(key)
list(map(self.occurrences.pop, stale_keys)) | [
"def remove_obsolete_values(self) -> None:\n now: float = self._time_func()\n threshold = now - self._window_size_seconds\n while len(self._window) > 0 and self._window[0].timestamp < threshold:\n self._window.popleft()",
"def remove_incomplete_dates(X):",
"def remove_gap_expnums... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Menu window for connection options. | def QuickClient():
window = Toplevel(root)
window.title("Connection options")
window.grab_set()
Label(window, text="Server IP:").grid(row=0)
destination = Entry(window)
destination.grid(row=0, column=1)
go = Button(window, text="Connect", command=lambda:
client_options_go(des... | [
"def client_options_window(master):\n top = Toplevel(master)\n top.title(\"Connection options\")\n top.protocol(\"WM_DELETE_WINDOW\", lambda: optionDelete(top))\n top.grab_set()\n Label(top, text=\"Server IP:\").grid(row=0)\n location = Entry(top)\n location.grid(row=0, column=1)\n location.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Asks the user to select a mirror or region | def select_mirror_regions(preset_values: Dict[str, Any] = {}) -> Dict[str, Any]:
if preset_values is None:
preselected = None
else:
preselected = list(preset_values.keys())
mirrors = list_mirrors()
selected_mirror = Menu(
_('Select one of the regions to download packages from'),
list(mirrors.keys()),
pres... | [
"def _PromptForRegion():\n\n if not console_io.CanPrompt():\n return None\n all_regions = constants.SUPPORTED_REGIONS_WITH_GLOBAL\n idx = console_io.PromptChoice(\n all_regions, message=('Please specify a region:\\n'\n '(For the global endpoint the region needs to be '\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Allows the user to select additional repositories (multilib, and testing) if desired. | def select_additional_repositories(preset: List[str]) -> List[str]:
repositories = ["multilib", "testing"]
choice = Menu(
_('Choose which optional additional repositories to enable'),
repositories,
sort=False,
multi=True,
preset_values=preset,
raise_error_on_interrupt=True
).run()
match choice.type_:... | [
"def create_default_repo_choice(self, default_repo):\n return (default_repo, default_repo)",
"def repository_activate():\n db = flask.current_app.container.get('db')\n gh_api = flask.current_app.container.get(\n 'gh_api', token=flask.session['github_token']\n )\n\n full_name = flask.requ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
returns a dictionary representing the given css string | def css2dict(css):
cssdict = {}
if None == css:
return cssdict
for pair in css.split(';'): #TODO: what about escaped separators
if pair.find(':') >= 0:
key, value = pair.split(':')
cssdict[ key.strip() ] = value.strip()
return cssdict | [
"def stylecrunch(stystr):\n return dict(pair.split(\":\") for pair in semicolons.findall(stystr))",
"def GenerateSelectorsDict(css):\n\n selector_regex = re.compile(r'\\.(\\w+)\\s+{', re.I)\n counters = {}\n selectors = {}\n for each in selector_regex.findall(css):\n firstletter = each.split... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
converts css color definition (a hexa code with leading or 'rgb()') to eps color definition | def cssColor2Eps(cssColor, colors='RGB'):
if '#' == cssColor[0]:
r = float(int(cssColor[1:3],16)) / 255
g = float(int(cssColor[3:5],16)) / 255
b = float(int(cssColor[5:7],16)) / 255
else:
# assume 'rgb()' color
rgb = re.sub('[^0-9]+', ' ', cssColor).strip().split()
... | [
"def toPdColor(red, green, blue):\n\n return (red * -65536) + (green * -256) + (blue * -1)",
"def rgb(rgb):\r\n return \"#%02x%02x%02x\" % rgb",
"def color_to_hex(color):\n if color.startswith(\"#\"):\n return x256.from_hex(color.strip(\"#\"))\n else:\n return x256.from_html_na... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
converts svgLength to eps length using the current transformation matrix | def lengthConv(self, svgLength):
matrix = self.matrices[-1]
epsx = matrix[0] * svgLength
epsy = matrix[1] * svgLength
return math.sqrt(epsx*epsx + epsy*epsy) | [
"def length(texel):\n return texel.weights[1]",
"def fixNonScalingStroke(path):\n svg, w, h = openSVG(path)\n groups = svg.getElementsByTagName(\"g\")\n # first remove childless groups\n childless = [g for g in groups if len([el for el in g.childNodes if el.nodeType != 3]) == 0] # 3 is the value o... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
converts svgx, svgy coordinates to eps coordinates using the current transformation matrix | def coordConv(self, svgx, svgy, relative=False):
if relative:
svgx = float(svgx) + self.curPoint[0]
svgy = float(svgy) + self.curPoint[1]
else:
svgx = float(svgx)
svgy = float(svgy)
matrix = self.matrices[-1]
epsx = matrix[0] * svgx + matri... | [
"def test_get_convert_svg_to_xps(self):\n name = \"Map-World.svg\"\n try:\n # Upload file to storage\n res = TestHelper.upload_file(name)\n self.assertTrue(len(res.uploaded) == 1)\n self.assertTrue(len(res.errors) == 0)\n\n # Convert document to x... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
multiplies matrix with matrix2 | def matrixMul(self, matrix, matrix2):
matrix0 = matrix[:]
matrix[0] = matrix0[0] * matrix2[0] + matrix0[2]*matrix2[1] # + matrix0[4]*0
matrix[1] = matrix0[1] * matrix2[0] + matrix0[3]*matrix2[1] # + matrix0[5]*0
matrix[2] = matrix0[0] * matrix2[2] + matrix0[2]*matrix2[3] # + matrix0[4]*0... | [
"def matrix_mult(m1, m2):\n pass",
"def matrix_mult( m1, m2 ):\n temp = new_matrix(len(m1), len(m2[0]))\n for row in range(len(temp)):\n for col in range(len(temp[0])):\n for i in range(len(m1[0])):\n temp[row][col] += m1[row][i] * m2[i][col]\n i = 0\n while i < len(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
should be called when a path segment end is reached in a element | def endPathSegment(self, elem):
if self.removeStrayPoints and self.segmentCommands <= 1:
self.alert("removing stray point", elem)
self.epspath = self.epspath[:self.segmentStartIndex]
return
if self.autoClose and (self.closeOp == 'f' or self.closeOp == 'b'):
... | [
"def endPath(self):\n if hasattr(self, \"_pointToSegmentPen\"):\n # its been used in a point pen world\n pointToSegmentPen = self._pointToSegmentPen\n del self._pointToSegmentPen\n pointToSegmentPen.endPath()\n else:\n # with NSBezierPath, nothing... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
transforms matrix using svg transform attribute | def attrTransform(self, matrix, transform):
for ttype, targs in self.reTransformFind.findall(transform):
targs = list(map(lambda x: float(x), self.reNumberFind.findall(targs)))
if ttype == 'matrix':
newmatrix = [ targs[0], targs[1],
targs[2], ... | [
"def transform(self, transformMatrix):\n aT = AppKit.NSAffineTransform.transform()\n aT.setTransformStruct_(transformMatrix[:])\n self._path.transformUsingAffineTransform_(aT)",
"def convertTransform(self, svgAttr):\n\n line = svgAttr.strip()\n\n ops = line[:]\n brackets ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
writes used gradient definitions into self.epsSetup | def gradientSetup(self):
gradientNum = 0
epsGradients = ""
for gradientId, gradient in self.gradients.items():
if gradient['linUseCount'] > 0:
gradientNum += 1
epsGradients += ("\n%%AI5_BeginGradient: (l_%s)" + \
"\n(l_%s) 0 %d Bd\... | [
"def _set_regressors(self) :\n\t\tlogging.debug(\"Setting regressors\")\n\t\n\t\tnvars = len(self.ss.variables)\t\t\n\n\t\tself.regressors_true = []\n\t\tfor eqn in self.ss.equations : \n\t\t\tprod= self._find_regressors(eqn,'g')\n\t\t\tdegrad = self._find_regressors(eqn,'h')\n\t\t\tself.regressors_true.append({\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The JSON file holds the definitions for all of the available bundles. | def get_bundle_definitions(bundleFile):
try:
with open(bundleFile) as fh_json:
bundleDefinitions = json.load(fh_json, object_pairs_hook=check_for_duplicate_key)
except IOError as err:
logging.error("Failed to access JSON file: '{0}'".format(bundleFile))
sys.exit(1)
exc... | [
"def show_bundle_definitions(bundleDefinitions):\n\n logging.info(\"\\n#{0}\\nBundle defintions read from JSON file\".format('-'*60))\n for bundle in sorted(bundleDefinitions):\n logging.info(\" BUNDLE : {0}\".format(bundle))\n\n for item in bundleDefinitions[bundle]['not_supported_configs']:... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Identify any bundles listed in the 'bundle_dependency' section which do not have definitons. | def find_undeclared_bundles(bundleDefinitions):
logging.info("\n#{0}\nChecking for undeclared dependencies".format('-'*60))
undeclared = []
for bundle in bundleDefinitions:
logging.info(' {0}'.format(bundle))
for dependentBundle in bundleDefinitions[bundle]['bundle_dependency']:
... | [
"def check_loaded_configured_bundles(single_app_info):\n l_bundles = set([bundle.split('@')[0] for bundle in single_app_info['loaded_bundles']])\n c_bundles = set(single_app_info['configured_bundles'])\n\n for bundle in sorted(list(c_bundles.difference(l_bundles))):\n if bundle == 'themes':\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Identify any circular dependencies by constructing the dependency paths. Any item added to a path must not alread be in the path. | def find_circular_dependencies(bundleDefinitions, undeclared):
logging.info("\n#{0}\nChecking for circular dependencies".format('-'*60))
circularDependencies = []
for bundle in sorted(bundleDefinitions):
# Don't continue with check if the bundle is already part of a circular dependency
i... | [
"def add_dependency(bundle, dependencyPath, bundleDefinitions, undeclared, circularDependencies):\n\n if bundle in dependencyPath:\n dependencyPath.append(bundle) # Add the path, so circular dependency report shows full loop\n dependencyPath.append(\"_STOP_\") # Ad... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks whether a bundle is part of an already discovered circular dependency. If it is then there is no need to check again!! | def bundle_already_in_circ_dep(bundle, circularDependencies):
for circDep in circularDependencies:
if bundle in circDep:
return True
return False | [
"def no_circular_dependencies(self):\r\n try:\r\n self._complete_dependencies()\r\n return True\r\n except CircularDependencyException:\r\n return False",
"def check_circular(self, mod_name: Optional[str] = None):\n mod_name = mod_name or self.mod_name\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Build up the dependency path. A circular dependency occurs if the bundle to be added is already in the path. Any undeclared dependencies.wil be ignored. | def add_dependency(bundle, dependencyPath, bundleDefinitions, undeclared, circularDependencies):
if bundle in dependencyPath:
dependencyPath.append(bundle) # Add the path, so circular dependency report shows full loop
dependencyPath.append("_STOP_") # Add a marker ... | [
"def dependency_dir(self) -> Path:",
"def dependency_path(self, agent_version):\n return f\"{self.import_path}@{self.__version(agent_version)}\"",
"def add_dependency(self, parent: str, child: str):",
"def dependency_path(ctx, name):\n return waf_resolve_context.dependency_cache[name]['path']",
"d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate the list of bundles to be generated for the specified build configuration. Only the bundles supported by the requested build configuration are added.to the list. The list is in the correct order to cope with bundle dependencies. | def determine_bundles_for_config(buildConfig, bundleDefinitions):
logging.info("\n#{0}\nDetermining bundle order for {1}".format('-'*60, buildConfig))
bundlesForConfig = []
for bundle in sorted(bundleDefinitions):
bundleReqdForConfig = True
for unsupported in bundleDefinitions[bundle]['not... | [
"def show_bundles_for_config(buildConfig, bundlesForConfig):\n\n logging.info(\"\\n#{0}\\nOrdered list of bundles to be generated for {1}\".format('-'*60, buildConfig))\n logging.info(' {0}\\n'.format( '\\n '.join(str(x) for x in bundlesForConfig)))",
"def bundles(conf, dlcs, **opts):\n\n bundles =... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Insert the target bundle into the list in the correct place to allow for bundle dependecies. This is a recursive function which will consider any dependencies that the target bundle has. The recurseDepth is used for output formatting only (only seen when logging set to INFO) The '.bdl' suffix is stripped off when addin... | def insert_bundle_in_list (bundle, bundlesForConfig, bundleDefinitions, recurseDepth):
logging.info('{0}Processing bundle : {1}'.format(' '*recurseDepth, bundle))
bundleNoSuffix = re.sub('\.bdl$', '', bundle)
if not bundleNoSuffix in bundlesForConfig:
if len(bundleDefinitions[bundle]['bundle_d... | [
"def add_dependency(bundle, dependencyPath, bundleDefinitions, undeclared, circularDependencies):\n\n if bundle in dependencyPath:\n dependencyPath.append(bundle) # Add the path, so circular dependency report shows full loop\n dependencyPath.append(\"_STOP_\") # Ad... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Output the ordered list of bundles for the requested build configuration. This is written to stdout, or to the specified file. | def output_result(bundlesForConfig, ofile):
result = ('{0}\n'.format('\n'.join(str(x) for x in bundlesForConfig)))
if ofile:
try:
with open(ofile, "w") as outfile:
outfile.write(result)
except IOError as err:
logging.error("{0}".format(err))
... | [
"def show_bundles_for_config(buildConfig, bundlesForConfig):\n\n logging.info(\"\\n#{0}\\nOrdered list of bundles to be generated for {1}\".format('-'*60, buildConfig))\n logging.info(' {0}\\n'.format( '\\n '.join(str(x) for x in bundlesForConfig)))",
"def bundles(conf, dlcs, **opts):\n\n bundles =... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Show supplied command line parameters | def show_parameters(args):
logging.basicConfig(format='%(message)s', level=args.logging)
logging.info('\n#{0}'.format('-'*60))
logging.info('BUILD CONFIG : {0}'.format(args.config))
logging.info('BUNDLE FILE : {0}'.format(args.bfile)) | [
"def print_usage():\n print(\"usage: \" + sys.argv[0] + \" -m model | -t | -r request\")\n print(\"Options and arguments:\")\n print(\"-m --model\\t: research model chosen for the search. ['b','boolean', 'v', 'vector']\")\n print(\"-t\\t\\t: enable the time record.\")",
"def PrintOurUsage():\n print ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Show the bundle definitions that have been read from the JSON file. | def show_bundle_definitions(bundleDefinitions):
logging.info("\n#{0}\nBundle defintions read from JSON file".format('-'*60))
for bundle in sorted(bundleDefinitions):
logging.info(" BUNDLE : {0}".format(bundle))
for item in bundleDefinitions[bundle]['not_supported_configs']:
logg... | [
"def get_bundle_definitions(bundleFile):\n\n try:\n with open(bundleFile) as fh_json:\n bundleDefinitions = json.load(fh_json, object_pairs_hook=check_for_duplicate_key)\n\n except IOError as err:\n logging.error(\"Failed to access JSON file: '{0}'\".format(bundleFile))\n sys.e... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Show the list of the bundles needed for the specified build configuration. The bundles should be generated in the order shown. | def show_bundles_for_config(buildConfig, bundlesForConfig):
logging.info("\n#{0}\nOrdered list of bundles to be generated for {1}".format('-'*60, buildConfig))
logging.info(' {0}\n'.format( '\n '.join(str(x) for x in bundlesForConfig))) | [
"def bundles(conf, dlcs, **opts):\n\n bundles = dlcs.bundles_all()['bundles']\n for bundle in bundles:\n print bundle['name'],\n\n print",
"def list_bundles():\n response = houston.get(\"/zipline/bundles\")\n\n houston.raise_for_status_with_json(response)\n return response.json()",
"def... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Validate word against the Oxford | def validate_word(word: str) -> bool:
if word:
url = f'{OXFORD_DICT_BASE_URL}{OXFORD_DICT_ENTRY_URL}/en-us/{word.lower()}'
headers = {
'app_id': settings.OXFORD_APP_ID,
'app_key': settings.OXFORD_API_KEY,
}
logger.info(f'validating {word} against oxford dicti... | [
"def customwordcheck(word):\r\n result = True\r\n if len(word) >= 3 and len(word) <= 15:\r\n result = True\r\n else:\r\n return False\r\n word = word.lower()\r\n for letter in word:\r\n if letter not in \"abcdefghijklmnopqrstuvwxyz\":\r\n return False\r\n else:\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initialize the board with a 2D list of random characters Return 2D list and game id | def init_board(user_name:str) -> Tuple[List[List[str]], str]:
game = Game.objects.create(user_name=user_name)
board = []
for _ in range(GAME_BOARD_SIZE):
row = []
for _ in range(GAME_BOARD_SIZE):
random_letter = random.choice(string.ascii_uppercase)
row.append(rando... | [
"def initialize_board(self):\n self.board = []\n for row in range(0, self.size):\n self.board.append([])\n for col in range(0, self.size):\n self.board[row].append(random.choice(LETTERS))",
"def init_board():\n board = ['#', 1, 2, 3, 4, 5, 6, 7, 8, 9]\n ret... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a dataframe with the location and the category + subcategory information | def counter(data, location):
df = pd.DataFrame(data)
df.columns = ['Path']
df['Category'] = df['Sub-Category'] = ''
# Split in categories and sub-categories
for i in range(len(df)):
tmp_categories = df['Path'][i].split(location)[1].split("\\")[1:3]
df['Category'].iat[i] = tmp_categ... | [
"def categories_dataframe():\n all_data = list()\n for businesses in BUSINESSES.values():\n for business in businesses:\n business_id = business['business_id']\n categories = business['categories']\n \n # add to the data collected so far\n all_data.append([busines... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compute shapes based on pyramid levels. | def compute_shape(image_shape, pyramid_levels):
image_shape = np.array(image_shape[:2])
image_shapes = [(image_shape + 2 ** x - 1) // (2 ** x) for x in pyramid_levels]
return image_shapes | [
"def guess_shapes(image_shape, pyramid_levels):\n image_shape = np.array(image_shape[:2])\n image_shapes = [(image_shape + 2 ** x - 1) // (2 ** x) for x in pyramid_levels]\n return image_shapes",
"def guess_shapes(image_shape, pyramid_levels):\n image_shape = np.array(image_shape[:2])\n feature_map... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Split mass_mailing and mass_mailing_sms activities in systray by removing the single mailing.mailing activity represented and doing a new query to split them by mailing_type. | def systray_get_activities(self):
activities = super(Users, self).systray_get_activities()
for activity in activities:
if activity.get('model') == 'mailing.mailing':
activities.remove(activity)
query = """SELECT m.mailing_type, count(*), act.res_model as model... | [
"def convert_links(self):\n res = {}\n done = self.env['mailing.mailing']\n for mass_mailing in self:\n if self.env.context.get('default_marketing_activity_id'):\n activity = self.env['marketing.activity'].browse(self.env.context['default_marketing_activity_id'])\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
load a batch of test images for inference | def load_test_batch(self, image_sequence_names):
def _parse_test_img(img_path):
with tf.device('/cpu:0'):
img_buffer = tf.read_file(img_path)
image_decoded = tf.image.decode_jpeg(img_buffer)
return image_decoded
image_dataset = tf.data.Dataset.fro... | [
"def load_scraped_food_images(ROOT):\n Xtr, Ytr = load_food_image_batch(os.path.join(ROOT, 'train'),50000)\n Xte, Yte = load_food_image_batch(os.path.join(ROOT, 'test'),10000)\n return Xtr, Ytr, Xte, Yte",
"def load_test_data():\n\n images, cls = _load_data(filename=\"test_batch\")\n\n return images, cls... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compile the url for Historical Data from Yahoo Finance for Jan 1, 2020 to March 31, 2021. Frequency set to Daily. | def get_url(ticker: str, period: int) -> str:
periods = {
1: 'period1=1577836800&period2=1585699200', # First Quarter 2020
2: 'period1=1585699200&period2=1593561600', # Second Quarter 2020
3: 'period1=1593561600&period2=1601510400', # Third Quarter 2020
4: 'period1=1601510400&pe... | [
"def stock_url(stock_symbol, day=None, month=None, year=None):\r\n\r\n page = \"http://ichart.finance.yahoo.com/table.csv?\"\r\n page = ''.join([page, 's=', stock_symbol])\r\n now = datetime.datetime.now()\r\n if day == None:\r\n day = now.day\r\n if month == None:\r\n month = now.month... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
When passed raw HTML from Yahoo Finance, will convert the table of Historical Stock data into a list of dictionary objects for each day of data. | def convert_html_to_list(html: str) -> List[dict]:
soup = BeautifulSoup(html, 'html.parser')
if not (tbodies := soup.find_all('tbody')): # Find the Table
raise ValueError('No tables found in the HTML passed!')
index_column_map = {
1: 'date',
2: 'open',
3: 'high',
4:... | [
"def scrape_data():\n soup = get_page_source_code(\"https://www.tradingview.com/markets/stocks-usa/market-movers-active/\")\n stock_table = soup.select(\".tv-data-table__tbody tr\")\n \n stock_data = []\n\n for data in stock_table:\n stock_name = data.find(\"a\").get_text(strip=True)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Will paginate through all 5 quarters of interest for the provided ticker, combining all of the records into a single list and saving that list as a JSON file saved at the provided path. | def create_json_for_ticker(ticker: str, path: str) -> bool:
stock_data = [] # Will have to paginate over the data, one financial quarter at a time
for period in range(1, 6): # 5 financial quarter period
response = requests.get(get_url(ticker, period))
stock_data += convert_html_to_list(str(res... | [
"def write_csv(ticker):\n f = open('./data/'+ticker+'.csv', 'w+')\n try:\n print(yqd.load_yahoo_quote(ticker, '20150102', '20160104'), file=f)\n print('Write Succeed')\n except error.HTTPError:\n print('<'+ticker+'> not found or HTTP cant resolve the token')\n f.close()",
"def _do... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the connected signs | def signs(self) -> Dict[str, HanoverSign]:
return self._signs | [
"def _connectivity(self):\n if not self.is_connected():\n raise gfapy.ArgumentError(\n \"Cannot compute the connectivity of {}\\n\".format(self)+\n \"Segment is not connected to a GFA instance\")\n return self._connectivity_symbols(len(self.dovetails_L),\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Broadcasts the test signs start command All signs connected to the serial port will loop the test sequence. | def start_test_signs(self):
self._write(TestSignsStartPacket()) | [
"def testSimStart(self):\n\t\tpass",
"def test_start_test(self):\n self.protocol.startTest(self.test)\n self.assertEqual(self.io.getvalue(), compat._b(\n \"test: %s\\n\" % self.test.id()))",
"def SendStartScanSignal(self):\n pass",
"def startsim(self):\n self.set_led(8, ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |