query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Get nomecalles geopandas dfs and put them in a list so that it's easier to work with them.
def get_dfs(d): dfs, nombres = [], [] for folder in tqdm(os.listdir(d), desc="GETTING DFS"): try: nombre = [ f for f in os.listdir(f"{d}/{folder}/".replace(".zip", "")) if ".shp" in f ][0] dfs.append( gpd...
[ "def get_offfending_maps():\n # create a template data frame to populate\n df_maps = pd.DataFrame(columns=['organization', 'map_name', 'map_link', 'layer_name', 'layer_item_link',\n 'layer_url'])\n\n # iterate the rows in teh data frame.\n for web_gis in df_web_gis.ite...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Computes the closest point and the distance to that point between a node and a bunch of nodes.
def closest_node(node, nodes): nodes = np.asarray(nodes) deltas = nodes - node dist_2 = np.einsum("ij,ij->i", deltas, deltas) return np.argmin(dist_2), np.min(dist_2)
[ "def closest_node(self,x,y):\n closest_dist = 1000000000\n closest = 0\n idx = 0\n nx = 0\n ny = 0\n for idx in self.nodes.keys():\n n = self.nodes[idx]\n dist = (x - n[0]) * (x - n[0])\n dist = dist + ((y - n[1]) * (y - n[1]))\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Takes a name and, looking for the lat and lon inside the dictionary of that name, it applies a cluster over them and therefore we obtain a cluster assignation per observation. This is no longer used, as finally the nomecalles variables are merged by postal code, not by cluster.
def get_clusters(nombre): lon, lat = mydic[nombre]["lon"], mydic[nombre]["lat"] scaled_lon = scaler_lon.transform(np.array(lon).reshape(-1, 1)) scaled_lat = scaler_lat.transform(np.array(lat).reshape(-1, 1)) clusters = kmeans.predict( pd.DataFrame({"x": [l for l in scaled_lat], "y": [l for l in ...
[ "def get_cluster(name: str) -> dict:\n return ECS.get_clusters([name])[0]", "def __get_coords_from(self, name):\n geolocator = Nominatim(user_agent=\"spanish\")\n geocode = RateLimiter(geolocator.geocode, min_delay_seconds=1)\n location = geocode(name)\n return {\n \"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load a DOT file.
def load_dot(self, dot_file): # print("Loading " + dot_file + "...") self.load_data_from_filename(dot_file) if self.name == None: return self.generate_signatures() self.load_graph(dot_file) if not self.is_graph_loaded(): return self.add_...
[ "def __loadDotFile(self):\n # Load the dot file into memory\n self.__graph = pgv.AGraph(self.__dotFile)\n\n self.__allNodes = self.__graph.nodes()\n\n # Prune the graph, as desired\n if len(self.__selectedNode) > 0:\n neighbors = self.__getNodeNeighbors(\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add an ellipse node at the beginning of the method to mark its signature.
def add_title_node(self): entry_nodes = self.get_entry_nodes() if len(entry_nodes) > 1: print("Warning: more than one entry node in this function") self.graph.add_node( self.signature, label = self.signature, shape = "ellipse", soot_sig = self.soot_signature ...
[ "def addEllipse(self, *__args): # real signature unknown; restored from __doc__ with multiple overloads\r\n pass", "def _add_mark(image, point, color=(255, 0, 0), size=5):\n x, y = point\n ImageDraw.Draw(image).ellipse((x - size // 2, y - size // 2, x + size // 2, y + size // 2), fill=color)", "def...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get entry point nodes of the method (nodes without preds).
def get_entry_nodes(self): top_nodes = [] for node in self.graph.nodes_iter(): if len(self.graph.predecessors(node)) == 0: top_nodes.append(node) return top_nodes
[ "def input_nodes(self):\n pass", "def get_all_nodes(self):\n pass", "def starting_nodes(self):\r\n return self.start_node", "def starting_nodes(self):\n return self.starting_nodes_ #abstract requires this exists!", "def _nodes(self):\n G = self.monodromy_graph()\n r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Removes useless attributes left by Soot, like method labels.
def strip_useless_attributes(self): graph_dict = self.graph.graph if "node" in graph_dict and "label" in graph_dict["node"]: graph_dict["node"].pop("label") if "graph" in graph_dict: graph_dict.pop("graph")
[ "def strip_attributes(tree_or_element, *attribute_names): # real signature unknown; restored from __doc__\n pass", "def _remove_attributes(self):\n for attribute in self.ignored_attributes:\n if attribute in self.data.columns.tolist():\n self.data.drop(attribute, axis=1, inplac...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Apply GridPerslayWeight on a ragged tensor containing a list of persistence diagrams.
def call(self, diagrams): grid_shape = self.grid.shape indices = [] for dim in range(2): [m,M] = self.grid_bnds[dim] coords = tf.expand_dims(diagrams[:,:,dim],-1) ids = grid_shape[dim]*(coords-m)/(M-m) indices.append(tf.cast(ids, tf.int32)) ...
[ "def test_to_ragged(self, fn_name, fn_args, proto_list_key):\n self.run_benchmarks(fn_name, _get_prensor_to_ragged_tensor_fn, fn_args,\n proto_list_key)", "def chunk_tensor(\n self,\n tensor: torch.Tensor,\n rank: int,\n world_size: int,\n num_devices_p...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Apply PowerPerslayWeight on a ragged tensor containing a list of persistence diagrams.
def call(self, diagrams): weight = self.constant * tf.math.pow(tf.math.abs(diagrams[:,:,1]-diagrams[:,:,0]), self.power) return weight
[ "def partial_pgs(dset: admix.Dataset, weight: np.ndarray):\n pass", "def wavelet_transform(tensor): # Check pytorch wavelets doc for more info\n transformer = DWTForward(J=1, mode='symmetric', wave='db3')\n ll_band_image,low_band = transformer(tensor) \n return ll_band_image,low_band[0][:,:,0,:,:],lo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
initializing the retry count here
def __init__(self, retry_count): self.retry_count = retry_count
[ "def retry_count(self, retry_count):\n\n self._retry_count = retry_count", "def test_retry_run(self):\n pass", "def set_retry(self, num_retries: int):\n\n self.num_retries = num_retries\n return self", "def set_retry_timeout(self, retry_timeout):", "def __init__(self, retry_policy):\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
pull csv from path, using usecols, and then agg and sum using groupvar
def pull_data_aian(path, usecols, groupvar): df = pd.read_csv(path, usecols = usecols) df = df.groupby(groupvar).sum() df = df.rename(columns=rename).reset_index() return df
[ "def compute_aggregate_load_data():\n\n # get a list of all the csv file names in the 'system_load_by_region' directory\n files = get_all_csv_files_in_directory('system_load_by_region')\n\n # Todo: Encapsulate this process into a helper function\n if len(files) == 0:\n\n # Unzip all files in curr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
assuming the formatting of the jun20 DAS state files, add location cols
def add_loc_cols(df): df['STATE'] = [int(i[1:3]) for i in df.gisjoin] df['COUNTY'] = [int(i[4:7]) for i in df.gisjoin] df['TRACT'] = [int(i[7:-4]) for i in df.gisjoin] df['BLOCK'] = [int(i[-4:]) for i in df.gisjoin] if df.STATE[0] > 9: raise Exception("Warning! Code might be incorrect for states with f...
[ "def copy_state(year):\n\n state_list = ['state']\n\n for filename in sorted(os.listdir('States')):\n state_raw = os.path.join('States',filename)\n state_name = filename[:len(filename)-4]\n all_state_info = state_name + '\\n'\n\n f = open(state_raw)\n csv_f = csv.reader(f)\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A LazySubprocessTester that should fail.
def unavailable_process(**kwargs): return LazySubprocessTester([sys.executable, "-c", "import sys; sys.exit(1)"], **kwargs)
[ "async def test_subprocess_exceptions(\n caplog: pytest.LogCaptureFixture, hass: HomeAssistant\n) -> None:\n\n with patch(\n \"homeassistant.components.command_line.notify.subprocess.Popen\"\n ) as check_output:\n check_output.return_value.__enter__ = check_output\n check_output.return...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Context manager that mocks out the availability checker for a given dependency checker. The context manager returns the mockedout method.
def mock_availability_test(feature): # We have to be careful with what we patch because the dependency managers define `__slots__`. return mock.patch.object(type(feature), "_is_available", wraps=feature._is_available)
[ "def patch_mock_deck_conflict_check(\n decoy: Decoy, monkeypatch: pytest.MonkeyPatch\n) -> None:\n mock = decoy.mock(func=deck_conflict.check)\n monkeypatch.setattr(deck_conflict, \"check\", mock)", "def oracle_arg_check(f):\n\n @functools.wraps(f)\n def wrapper(*args, **kwargs):\n getattr(a...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check that the test of availability is only performed once.
def test_check_occurs_once(self, test_generator): feature = test_generator() with mock_availability_test(feature) as check: check.assert_not_called() if feature: pass check.assert_called_once() if feature: feature.require_n...
[ "def is_available():", "def check_availability(self):\n if self.num_copies > 0:\n return True\n else:\n return False", "def allready(antReady) :\n return numNotready(antReady) == 0", "def _check_all_systems_ready(self):", "def this_needs_work_test_ensure_our_presence(s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check that the callback is only called once.
def test_callback_occurs_once(self, test_generator): callback = mock.MagicMock() feature = test_generator(callback=callback) callback.assert_not_called() if feature: pass callback.assert_called_once_with(bool(feature)) callback.reset_mock() if featu...
[ "def run_once(func):\n @wraps(func)\n def wrapper(*args, **kwargs):\n if not wrapper.has_run:\n result = func(*args, **kwargs)\n wrapper.has_run = True\n return result\n wrapper.has_run = False\n return wrapper", "def run_once(func):\n def wrapper(*args, **kw...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that the unavailable loaders loudly raise when the inner functions of decorators are called, and not before, and raise each time they are called.
def test_require_in_call_raises_for_unavailable_tests(self, test_generator): # pylint: disable=function-redefined with self.subTest("direct decorator"): feature = test_generator() with mock_availability_test(feature) as check: check.assert_not_called() ...
[ "def test_bad_decorator(self) -> None:\n with pytest.raises(TypeError):\n\n @with_roles({'all'}) # type: ignore[operator]\n def f():\n pass", "def test_tolerate_decorated_function_raise_if_disabled():\n def test_function():\n raise AttributeError()\n fn = ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that the unavailable loaders loudly raise when the inner classes of decorators are instantiated, and not before, and raise each time they are instantiated.
def test_require_in_instance_raises_for_unavailable_tests(self, test_generator): # pylint: disable=function-redefined with self.subTest("direct decorator"): feature = test_generator() with mock_availability_test(feature) as check: check.assert_not_called() ...
[ "def test_require_in_call_raises_for_unavailable_tests(self, test_generator):\n # pylint: disable=function-redefined\n\n with self.subTest(\"direct decorator\"):\n feature = test_generator()\n with mock_availability_test(feature) as check:\n check.assert_not_called...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check that the import tester can accept a dictionary mapping module names to attributes, and that these can be fetched.
def test_import_allows_attributes_successful(self): name_map = { "_qiskit_dummy_module_1_": ("attr1", "attr2"), "_qiskit_dummy_module_2_": ("thing1", "thing2"), } mock_modules = {} for module, attributes in name_map.items(): # We could go through the r...
[ "def test_import_allows_attributes_failure(self):\n # We can just use existing modules for this.\n name_map = {\n \"sys\": (\"executable\", \"path\"),\n \"builtins\": (\"list\", \"_qiskit_dummy_attribute_\"),\n }\n\n feature = LazyImportTester(name_map)\n sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check that the import tester can accept a dictionary mapping module names to attributes, and that these are recognised when they are missing.
def test_import_allows_attributes_failure(self): # We can just use existing modules for this. name_map = { "sys": ("executable", "path"), "builtins": ("list", "_qiskit_dummy_attribute_"), } feature = LazyImportTester(name_map) self.assertFalse(feature)
[ "def assert_attributes_exist(name, module_dict, attributes):\n for attribute in attributes:\n assert attribute in module_dict, \\\n f'{name} should define {attribute} in its __init__.py file.'", "def test_import_allows_attributes_successful(self):\n name_map = {\n \"_qiskit_dumm...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
converting documents to list
def docs_to_list(documents): texts = [] for doc in documents: texts.append(doc.split()) print (("The collection of documents contains {} documents").format(len(texts))) return texts
[ "def transform(self, docs):\n return [doc for doc in docs]", "def get_all(self):\n return [DocumentCorpus(self.collection, document) for document in self.collection.find()]", "def transform(self, documents):\n document_list = []\n for document in documents:\n document_list.app...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
We ask user how long password he needs and check his input.
def ask_user(): password_lenght = 0 while password_lenght == 0: try: password_lenght = int(input("How long password you want? Enter the number... ")) if password_lenght <= 0: print("Try to enter any number greater than 0...") continue ...
[ "def pwd_len():\r\n while True:\r\n password_length = input('How much length for password u want ? Minimum length is 6 and Maximum length is 25 : ')\r\n try:\r\n password_length = int(password_length)\r\n if 6 <= password_length <= 25:\r\n break\r\n e...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checking input data and generating password of a given length.
def password_generator(password_lenght): password = "" try: if password_lenght >=1: for i in range(password_lenght): choice = random.choice(symbols) password += str(choice) print(f"Your password is: {password} \nTnank you!") ...
[ "def test_length(self):\n for length in range(2, 30):\n self.assertEqual(len(generate_password(length)), length)", "def gen_password(length: int):\n letters: str = \"abcdefghijklmnopqrstuvwxyz\"\n numbers: str = \"1234567890\"\n symbols: str = \"!&^#*%$@\"\n\n _all = letters + letter...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compose payload for Google geocoding request from latitude and longitude
def build_google_payload(latitude, longitude): coordinates = latitude + ',' + longitude payload = 'latlng=' + coordinates + "&language=es&client=" + GOOGLE_INFO['client'] + "&signature=" + GOOGLE_INFO['signature'] + "=&result_type=route" return payload
[ "def api_geocode():\n\n address = request.args['address']\n url = \"https://maps.googleapis.com/maps/api/geocode/json?\" \n resp = requests.get(url,\n params={\"key\": API_KEY, \"address\": address})\n json_data = resp.json()\n return jsonify(json_data)", "def reverse_geocode(param_dict):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compose payload for OSM geocoding request from latitude and longitude
def build_osm_payload(latitude, longitude): payload = 'format=json&lat=' + latitude + '&lon=' + longitude + '&accept-language=es' return payload
[ "def build_google_payload(latitude, longitude):\n coordinates = latitude + ',' + longitude\n payload = 'latlng=' + coordinates + \"&language=es&client=\" + GOOGLE_INFO['client'] + \"&signature=\" + GOOGLE_INFO['signature'] + \"=&result_type=route\"\n return payload", "def form_params(self, lat, long):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Extract util information (formatted_adddress) from Google geocoding response
def extract_data_from_google_response(geocoding_response): root = ET.fromstring(geocoding_response) for result in root.findall('result'): data = result.find('formatted_address').text if data != '': return data return 'Dirección desconocida'
[ "def extract_data_from_nominatim_response(geocoding_response):\n root = ET.fromstring(geocoding_response)\n for result in root.findall('result'):\n data = result.find('formatted_address').text\n if data != '':\n return data\n return 'Dirección desconocida'", "def get_address(addr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Extract util information (formatted_adddress) from local Nominatim geocoding response
def extract_data_from_nominatim_response(geocoding_response): root = ET.fromstring(geocoding_response) for result in root.findall('result'): data = result.find('formatted_address').text if data != '': return data return 'Dirección desconocida'
[ "def extract_data_from_google_response(geocoding_response):\n root = ET.fromstring(geocoding_response)\n for result in root.findall('result'):\n data = result.find('formatted_address').text\n if data != '':\n return data\n return 'Dirección desconocida'", "def get_address(address...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get coordinates for tracking_id or event_id previously saved at MongoDB
def get_coordinates_from_id(tracking_id=None, event_id=None): if tracking_id: json_document = mongo.read_single_document(collection='TRACKING', filter={'_id':ObjectId(tracking_id)}, projection={'coordinates':True}) if not json_document: json_document = mongo.read_single_document(collecti...
[ "def get_coords(data, id):\n return data[id]['lat'], data[id]['lon']", "def coordinates(self):\n\t\tlocation = self.current['geometry']['location']\n\t\treturn location['lat'], location['lng']", "def get_coordinates(id):\n response = urllib2.urlopen('http://maps.googleapis.com/maps' + \\\n\t\t'/api/geocod...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set geocoding for one tracking_id or/and event_id already saved at mongo
def sync_set_geocoding(provider, tracking_id, event_id): coordinates = get_coordinates_from_id(tracking_id=tracking_id, event_id=event_id) geocoding = None if coordinates: if not provider or provider == 'osm': geocoding = get_osm_geocoding(coordinates) if geocoding == None: ...
[ "def async_set_geocoding(provider, tracking_id=None, event_id=None):\n loop = asyncio.get_event_loop()\n loop.run_in", "def upsert_location(self, location):", "def event_update_loc(id: int, lon: float, lat: float):\r\n # Create a cursor object\r\n cur = conn.cursor()\r\n # Create a cursor object\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Async set geocoding for one tracking_id or/and event_id already saved at mongo
def async_set_geocoding(provider, tracking_id=None, event_id=None): loop = asyncio.get_event_loop() loop.run_in
[ "def sync_set_geocoding(provider, tracking_id, event_id):\n coordinates = get_coordinates_from_id(tracking_id=tracking_id, event_id=event_id)\n geocoding = None\n if coordinates:\n if not provider or provider == 'osm':\n geocoding = get_osm_geocoding(coordinates)\n if geocoding...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a feature stack from a given image.
def generate_feature_stack(image, features_specification : Union[str, PredefinedFeatureSet] = None): image = cle.push(image) # default features if features_specification is None: blurred = cle.gaussian_blur(image, sigma_x=2, sigma_y=2, sigma_z=2) edges = cle.sobel(blurred) stack = ...
[ "def _make_features(self, features, image = None):\n if isinstance(features, str):\n self.feature_specification = features\n if image is None:\n raise TypeError(\"If features are provided as string, an image must be given as well to generate features.\")\n feat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Runs a function (successfully) only once. The running can be reset by setting the `has_run` attribute to False
def run_once(f): @wraps(f) def wrapper(*args, **kwargs): if not wrapper.has_run: result = f(*args, **kwargs) wrapper.has_run = True wrapper.result = result return wrapper.result wrapper.has_run = False return wrapper
[ "def run_once(func):\n @wraps(func)\n def wrapper(*args, **kwargs):\n if not wrapper.has_run:\n result = func(*args, **kwargs)\n wrapper.has_run = True\n return result\n wrapper.has_run = False\n return wrapper", "def run_once(f):\n @functools.wraps(f)\n d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieves the given name from the symbolserver and places it in cache. Will fetch and extract compressed pdb versions if possible. Returns true if pdb was successfully retrieved and cached.
def retrievePdbFrom(name, guid, symbolserver): # Try fetching compressed version debug("Trying to fetch '%s' with GUID %s from '%s'", name, guid, symbolserver) # What we currently have cached is outdated or non-existent, delete it # so we don't clutter up the cache with stuff we'll never use a...
[ "def retrievePdb(name, guid):\r\n symbolservers = ['http://symbols.hacst.net/', 'http://mumble.info:8080/symbols/']\r\n \r\n for symbolserver in symbolservers:\r\n if retrievePdbFrom(name, guid, symbolserver):\r\n return True\r\n \r\n return False", "def download_pdb(pdb_name):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Attempts to retrieve the pdb from the known symbol servers. Returns true if the pdb was retrieved and is now in cache.
def retrievePdb(name, guid): symbolservers = ['http://symbols.hacst.net/', 'http://mumble.info:8080/symbols/'] for symbolserver in symbolservers: if retrievePdbFrom(name, guid, symbolserver): return True return False
[ "def retrievePdbFrom(name, guid, symbolserver):\r\n # Try fetching compressed version\r\n debug(\"Trying to fetch '%s' with GUID %s from '%s'\", name, guid, symbolserver)\r\n \r\n # What we currently have cached is outdated or non-existent, delete it\r\n # so we don't clutter up the cache with stuff ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Assembles the GUID used by symstore for symbolserver paths from the debug information in a plugins PE header and returns it. If no GUID can be extracted, the function returns None.
def getSymbolserverPdbGUID(filename): path = cachePath(filename) pe = pefile.PE(path) # Find the CodeView entry in the PE file's debug directory. header = None for entry in getattr(pe, 'DIRECTORY_ENTRY_DEBUG', []): dbgtype = entry.struct.Type if pefile.DEBUG_TYPE.g...
[ "def debug_guid(pe):\n if hasattr(pe, 'DIRECTORY_ENTRY_DEBUG'):\n for i in pe.DIRECTORY_ENTRY_DEBUG:\n if hasattr(i.entry, 'Signature_Data1'):\n return '{:08x}-{:04x}-{:-4x}-{}-{}{}'.format(\n i.entry.Signature_Data1,\n i.entry.Signature_Data...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns true if the given file is in cache and its hash matches the given one.
def isCached(filename, hash): path = cachePath(filename) if not os.path.exists(path): return False return hash == hashlib.sha1(open(path, 'rb').read()).hexdigest()
[ "def isvalid(self, filename):\n key = filename\n if key not in self.cache:\n return False\n cachehash = self.cache[key][0]\n with io.open(filename, 'rb') as f:\n filebytes = f.read()\n currhash = md5(filebytes).hexdigest()\n return cachehash == currhas...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Downloads the given file from the public plugin server into the replacement cache. By default, this fetches the plugin from the Mumble
def cachePlugin(filename, fullpath=None): path = cachePath(filename) url = 'http://mumble.info:8080' if fullpath is not None: url += fullpath else: url += '/plugins/' + filename res = requests.get(url) if not res.ok: raise Exception("Failed to fetch '%s'"...
[ "def download_plugin():\n\t\tfilename = 'CloudStag.crx'\n\t\treturn send_from_directory(app.static_folder, filename, as_attachment=True)", "def _DownloadPlugin(*args):\n url = \"\".join(args)\n egg = None\n try:\n try:\n if Profile_Get('USE_PROXY', default=False):\n proxy...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Makes sure the local cache contains all old plugin versions and collects their creation dates. The return value is a tuple consisting of the oldest creation datetime of all plugins and a dict of dll name to creation date mappings.
def collectPluginCreationDates(limitTo = None): creation_dates = {} oldest = None info("Collecting plugin creation dates") plugins = getPluginList(ver = args.version, os = args.os, abi = args.abi) for plugin in plugins.findall('plugin'): name = plugin.attrib['name'] hash...
[ "def determineUnchangedPlugins(oldest, creation_dates):\r\n info(\"Checking repo for new revisions\")\r\n \r\n old_plugins_to_use = creation_dates.copy()\r\n repo = git.Repo(args.repo)\r\n \r\n pluginmatch = re.compile(r'^plugins/(\\w+)/')\r\n \r\n for commit in repo.iter_commits(rev = args....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks the repository history for changes to the plugins cpp/pro file. If such changes are found and they are newer than the creation date of the plugin it is assumed the plugin needs to be updated.
def determineUnchangedPlugins(oldest, creation_dates): info("Checking repo for new revisions") old_plugins_to_use = creation_dates.copy() repo = git.Repo(args.repo) pluginmatch = re.compile(r'^plugins/(\w+)/') for commit in repo.iter_commits(rev = args.rev, paths = 'plugins/')...
[ "def check_changes(self):\n for filename in self.files:\n revision = os.path.getmtime(filename)\n metadata = plug.get_metadata(filename)\n\n # If the file is more recent\n if revision > metadata.revision:\n metadata.revision = os.path.getmtime(metada...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
saves file in given directory in fiven format
def quicksavefile(directory, text, format=".out"): print(text) print(directory) directory = directory.split(".") del directory[-1] directory.append(format) s = "".join(directory) file = open(s, "w") file.write(text) file.close()
[ "def save(self, directory):\n pass # pragma: no cover", "def save(self):\r\n self.__ensure_dir__(self.dir)\r\n wavfile.write(os.path.join(self.dir, self.filename), self.fs, self.data)", "def save(self, path, *args, **kwargs):\n\n file_format = path.split(\".\")[-1].lower()\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
cuts tworow data into two seperate lists. Items are formatted as float
def cut_data(data): out = [[], []] data = data.split("\n") for line in data: line = line.split(" ") line = remove_empty(line) try: out[0].append(float(line[0])) out[1].append(float(line[1])) except IndexError: pass file = open("test.txt...
[ "def convert_redis_data_to_floats(range_data2):\n \n raw_temp_list = []\n \n for data in range_data2:\n temp_floats = convert_tempstring_to_floats(data)\n raw_temp_list.append(temp_floats)\n return raw_temp_list", "def clean_serial_data(data):\n clean_data = []\n line_data = []\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
deletes empty elements with "space" in it
def del_empty_space(list): for x in range(len(list)): if " " in list[x - 1]: del list[x - 1] return list
[ "def clean_empty(l):\n return list(filter(lambda x: x != \"\", l))", "def clean_list(self, l):\n ret = []\n for e in l:\n if e != \"\" and e != ' ':\n ret.append(e)\n return ret", "def filter_empty(string):\n\n content = string.split()\n content = [filter(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
clears "" and " " in list
def clear_list(list): for x in range(len(list)): try: list.remove("") except ValueError: pass try: list.remove(" ") except ValueError: pass return list
[ "def cleanup_list(l):\n s = set(l)\n if \"\" in s:\n s.remove(\"\")\n l = list(s)\n for i, val in enumerate(l):\n l[i] = l[i].strip()\n return l", "def clean_list(self, l):\n ret = []\n for e in l:\n if e != \"\" and e != ' ':\n ret.append(e)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns list with elements without char
def get_without(list, char="#"): s = [] for line in list: if char not in line: s.append(line) return s
[ "def clean_list(self, l):\n ret = []\n for e in l:\n if e != \"\" and e != ' ':\n ret.append(e)\n return ret", "def non_zero_components(self) :\n return list(self.parent().characters())", "def lstrip(self, chars=None):\n return asarray(lstrip(self, ch...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create and execute a CHARMM script for the IPRO suite of programs.
def execute_CHARMM_script(script, procedure = None, gn = None): # Validate that the script is a string so it can be written to a file if not isinstance(script, str): text = "The execute_CHARMM_script requires a string as the 'script' " text += "input to function, not:\n" + str(script) ra...
[ "def fusion_generate_mmmc_script(x: hammer_vlsi.HammerTool) -> str:\n mmmc_output = [] # type: List[str]\n\n def append_mmmc(cmd: str) -> None:\n x.verbose_tcl_append(cmd, mmmc_output)\n\n # Create an Innovus constraint mode.\n constraint_mode = \"my_constraint_mode\"\n sdc_files = [] # type...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Make sure the specified procedure can be used in naming things.
def validate_procedure(procedure): # If it is not a string, use "charmm" if not isinstance(procedure, str): return "charmm" else: # Split on white space and replace it with underscores items = procedure.split() procedure = '' for i, item in enumerate(items): ...
[ "def _validate_procedure( procedure ):\n from Component.models import Procedure\n \n if not isinstance(procedure, Procedure):\n raise TypeError('_validate_procedure() requires param of Procedure Type')\n \n return procedure", "def testDefineCreateProc(self):\n\t\tcur = con.cursor()\n\n\t\tnu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load the Topology and Parameter input files in a CHARMM script.
def load_input_files(experiment = None): # Loop through topology and parameter data sets = [["Topology", defaultCHARMMTopologies, "rtf"], \ ["Parameter", defaultCHARMMParameters, "para"]] # Store the output in this string output = '' for set in sets: # Get the list of files that ...
[ "def load_params_from_file(self, input_file):\n\n ### FILL IN ###", "def setup_from_file(self, dir):\n self.shared_resources.load(os.path.join(dir, \"shared_resources\"))\n self.input_module.setup()\n self.input_module.load(os.path.join(dir, \"input_module\"))\n self.model_modul...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create text to load Molecules in a CHARMM script.
def load_molecules(molecules, procedure, who = defaultUser, which = "all"): # This function assumes that the molecules and procedure have already been # validated. # Validate the which input if which not in ['all', 'ALL', True, False]: text = "The load_molecules function does not recognize the f...
[ "def _vmd_script_molecule(mole, filename=\"molecule.xyz\"):\n output = \"# load new molecule\\n\"\n if len(mole.atom) == 0:\n raise ValueError(\"Need at least one molecule file with coordinates.\")\n atoms = mole.atom\n natoms = len(mole.atom[0:, 0])\n f = open(filename, \"w\")\n f.write(st...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate the text to run an energy minimization in CHARMM.
def minimize(molecules, experiment, procedure, gn): # It is assumed that the molecules and procedure have already been validated # Get information about how and whether solvation should be used solvation = SOLVATION.get_string(experiment, procedure) # Don't include harmonic, NOE, or CDIH restraints duri...
[ "def regimes(self):\n coupling = self.coupling()\n quantum_theta = self.quantum_theta()\n\n if coupling <= 0.01:\n coupling_str = f\"Weakly coupled regime: Gamma = {coupling}.\"\n elif coupling >= 100:\n coupling_str = f\"Strongly coupled regime: Gamma = {coupling}....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tell CHARMM to output the structures of Molecules.
def output_molecules(molecules, procedure, which = "all"): # This function assumes the molecules and procedure have already been # validated # Validate the which input if which not in ['all', 'ALL', True, False]: text = "The output_molecules function does not recognize the following " te...
[ "def print_molecule(self):\n mol = self.molecule\n if mol:\n # xyz = '\\n'.join(at.str(symbol=True, space=11, decimal=5) for at in mol.atoms)\n ret = ' $data\\ntitle\\nC1\\n'\n for at in mol.atoms:\n ret += \"{} {} {}\\n\".format(at.symbol, at.atnum, a...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load the structures of Molecules after a CHARMM script.
def load_structures(molecules, procedure, which = "all"): # It is assumed that the molecules and procedure have been validated # Check the which input if which not in ['all', 'ALL', True, False]: text = "The load_structures function does not recognize " + str(which) text += " as a valid whic...
[ "def _load_molecule(self):\n self.pymol = pybel.readstring(self.input_format, self.file_dic['input'])", "def load_molecules(molecules, procedure, who = defaultUser, which = \"all\"):\n # This function assumes that the molecules and procedure have already been\n # validated.\n # Validate the which ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add missing Atoms to Molecules.
def Missing_Atoms(molecules, experiment = None): # Validate the Molecules molecules, gn = validate_molecules(molecules) # Declare the procedure, making sure it is OK (it is, but whatever) procedure = validate_procedure("add_missing_atoms") # Determine who is running this experiment try: ...
[ "def test_add_atoms_and_bonds(self, molecule):\n molecule_copy = Molecule()\n for atom in molecule.atoms:\n molecule_copy.add_atom(\n atom.atomic_number,\n atom.formal_charge,\n atom.is_aromatic,\n stereochemistry=atom.stereochemis...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Use CHARMM to calculate the complex energy of a group of Molecules.
def Energy(molecules, experiment = None, which = "all"): # Validate the molecules molecules, gn = validate_molecules(molecules) # Create the procedure procedure = validate_procedure("energy") # Determine who is doing the calculation try: user = experiment["User"] except (KeyError, Ty...
[ "def compute_hydration_energies(molecules, parameters):\n\n energies = dict() # energies[index] is the computed solvation energy of molecules[index]\n\n platform = openmm.Platform.getPlatformByName(\"Reference\")\n\n for molecule in molecules:\n # Create OpenMM System.\n system = openmm.Syste...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
`/farms/{pk}/joinfarm/` Add the currently logged in `User` to this `Farm`.
def join_farm(self, request, pk): farm = self.get_object() user = request.user farm.add_member(user) return Response({}, status=status.HTTP_202_ACCEPTED)
[ "def add_member(self, request, pk):\n farm = self.get_object()\n user = request.data.get('user')\n farm.add_member(user)\n return Response({}, status=status.HTTP_202_ACCEPTED)", "def join(self, user):\n self.players.add(user)\n if user.pk not in self.queue:\n s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
`/farms/{pk}/leavefarm/` Remove the currently logged in `User` from this `Farm`.
def leave_farm(self, request, pk): farm = self.get_object() user = request.user farm.remove_member(user) return Response({}, status=status.HTTP_204_NO_CONTENT)
[ "def remove_member(self, request, pk):\n farm = self.get_object()\n user = request.data.get('user')\n farm.remove_member(user)\n return Response({}, status=status.HTTP_204_NO_CONTENT)", "def loan_remove(request, id):\n loan = User.objects.get(id=id)\n loan.delete()\n return re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
`/farms/{pk]/addmember/` Invite the specified `User` to join this `Farm`.
def add_member(self, request, pk): farm = self.get_object() user = request.data.get('user') farm.add_member(user) return Response({}, status=status.HTTP_202_ACCEPTED)
[ "def join_farm(self, request, pk):\n farm = self.get_object()\n user = request.user\n farm.add_member(user)\n return Response({}, status=status.HTTP_202_ACCEPTED)", "def add_member(self, user):\n if user is self.owner:\n raise ValidationError('A trip owner cannot also...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
`/farms/{pk}/removemember/` Remove the specified `User` from this `Farm`.
def remove_member(self, request, pk): farm = self.get_object() user = request.data.get('user') farm.remove_member(user) return Response({}, status=status.HTTP_204_NO_CONTENT)
[ "def delete_member():\n client = RequestManager()\n client.set_method(\"DELETE\")\n member_id = STORED_ID[\"member_id\"]\n client.set_endpoint(\"/accounts/{0}/memberships/{1}\".format(CONFIG_DATA['account_id'], member_id))\n client.execute_request()", "def team_remove_member(req...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Converts a time range (ex. '1m', '5', 'max') to a datetime ojbect
def __time_range_to_date(time_range : str) -> dt.datetime: if time_range.lower() == 'max': return dt.datetime(1900,1,1) multiplier, period = re.search("(\d+)([dwmy])", time_range.lower()).groups() multiplier = int(multiplier) if period == 'd': return dt.datetime.now() + relativedelta.relativede...
[ "def __time_range_to_date(time_range : str) -> dt.datetime:\n\n if time_range.lower() == 'max':\n return dt.datetime(1900,1,1)\n\n multiplier, period = re.search(\"(\\d+)([dwmy])\", time_range.lower()).groups()\n multiplier = int(multiplier)\n\n if period == 'd': return dt.datetime.now() + relative...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function will retrieve historical trading data for the symbol and over the time range specified in a pandas DataFrame object. Returns None if the data is not retrievable
def GetHistoricalData(symbol : str, time_range : str) -> Optional[DataFrame]: time_format = "%Y-%m-%d" start_date = Equity.__time_range_to_date(time_range) end_date = dt.datetime.now() symbol_could_not_be_fixed = False while True: try: df = DataReader(symbol, data_source='yahoo', st...
[ "def get_stock(symbol, interval):\n \n try:\n \n time_interval = TIME_INTERVALS[interval]\n \n if(time_interval == TIME_INTERVALS['Intraday']):\n json_data = requests.request('GET', 'https://www.alphavantage.co'+\n '/query?function=TIME_SERIES_INTR...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function will get the percent change of equity share price of a set of different time ranges.
def GetPercentChangeOverTimeRanges(symbol : str, time_ranges : List[str]) -> List[dict]: def get_percent_change(pd_dataframe): """ This will calculate the percent change of a share over some time frame by reading DataFrame values """ time_format = "%Y-%m-%d" open_val = pd_datafra...
[ "def percent_changes(self):\n\n # close_t = float(val[\"klines\"][\"1m\"].get(self.mw.cfg_manager.pair, {})[-5][4])\n klines_data = self.mw.klines.get(\"1m\")\n coin_data = klines_data.get(self.mw.cfg_manager.pair)\n\n if isinstance(coin_data, list):\n close_5m = float(self.mw...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This will calculate the percent change of a share over some time frame by reading DataFrame values
def get_percent_change(pd_dataframe): time_format = "%Y-%m-%d" open_val = pd_dataframe.iloc[0]['Open'] close_val = pd_dataframe.iloc[-1]['Adj Close'] if open_val == 0: return "N/A" else: return round((close_val - open_val) / open_val * 100, 2)
[ "def pchange(df):\r\n df[\"pchange\"] = df.close.pct_change()\r\n df[\"change\"] = df.close.diff()\r\n\r\n return df", "def pct_change(value: Series, period: int) -> Series:\n return value.pct_change(periods=period)\n # 정확한 시간 측정을 통해 빠른 연산을 선택해야\n # return value / value.shift(period) - 1", "de...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Converts a time range (ex. '1m', '5', 'max') to a datetime ojbect
def __time_range_to_date(time_range : str) -> dt.datetime: if time_range.lower() == 'max': return dt.datetime(1900,1,1) multiplier, period = re.search("(\d+)([dwmy])", time_range.lower()).groups() multiplier = int(multiplier) if period == 'd': return dt.datetime.now() + relativedelta.relativede...
[ "def __time_range_to_date(time_range : str) -> dt.datetime:\n\n if time_range.lower() == 'max':\n return dt.datetime(1900,1,1)\n\n multiplier, period = re.search(\"(\\d+)([dwmy])\", time_range.lower()).groups()\n multiplier = int(multiplier)\n\n if period == 'd': return dt.datetime.now() + relative...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function returns the BlackScholes call value for an options contract
def CallValue(contract : 'Contract') -> float: return Option.__call_value(contract.underlyingPrice, contract.strikePrice, contract.interestRate / 100, contract.daysToExpiration / 365, contract.volatility / 100)
[ "def value(self):\n \n print(\"Cannot calculate value for base class BSOption.\" )\n return 0", "def testCallOptionCreation(self):\n callOption = call.Call(underlyingTicker='SPY', strikePrice=250, delta=0.3,\n dateTime=datetime.datetime.strptime('01/01/2021', \"%m...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function will use the TD Ameritrade API to retrieve Option(s) for the symbol available up to the specified to_date
def GetOptions(td_ameritrade_api_key : str, symbol : str, to_date : str) -> List['Option']: options_url = 'https://api.tdameritrade.com/v1/marketdata/chains' request = requests.get(url = options_url, params = { 'apikey' : td_ameritrade_api_key, 'symbol' : symbol, 'contractType' : "ALL", ...
[ "def get_options(ticker, exp_date, typ):\n std_date = datetime(2020, 8, 14)\n std_sec = 1597363200\n dt = exp_date - std_date\n target_sec = std_sec + int(dt.total_seconds())\n # An URL for specific asset at a expiration date is created.\n url = f\"finance.yahoo.com/quote/{ticker}/options?date={ta...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Finds the corresponding table name for the security specified
def __get_table_name(security : Union[Equity, Option, SecurityType]) -> str: if isinstance(security, Equity): return 'Equities' elif isinstance(security, Option): return 'Options' elif isinstance(security, EquityListing): return "ListedEquities" elif isinstance(security, SecurityTy...
[ "def table_name() -> str:\n pass", "def get_table(tname, request):\n pyramid_sacrud_models = get_models_from_settings(request)\n try:\n models = dict(pyramid_sacrud_models)\n except ValueError:\n models = dict((pyramid_sacrud_models, ))\n finally:\n models = models.values()...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Assure that the column name is SQL valid
def _validate_column_name(col_name : str) -> str: if col_name[0].isdigit(): return f'"{col_name}"' return col_name
[ "def _valid_column(column_name):\n return str(column_name)", "def _validate_column_name(self, name, purpose):\n if purpose == 'order_by':\n return name in self.columns and\\\n self.columns[name].sortable\n else:\n return True", "def _check_dynamic_columns...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Takes the conditions in tuple format and converts it to a proper SQL WHERE clause
def __convert_to_sql_where(conditions : List[Tuple[Any, RelationalOperator, Any]]) -> str: formatted_identifiers = [] for identifier in conditions: col_name, relation, value = identifier if relation == RelationalOperator.Between and len(value) != 2: raise ValueError("Between relational op...
[ "def parse_condition(self):\n sql = \"\"\n sql_values = []\n if self._where:\n where = self._where\n if isinstance(self._where, dict):\n where = \"\"\n for k in self._where.keys():\n v = self._where[k]\n i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adds security to corresponding table in database
def AddNewSecurity(self, security : Union[Equity, Option, EquityListing]) -> None: table_name = self.__get_table_name(security) self.Insert(table_name, security.__dict__.keys(), security.__dict__.values())
[ "def init_security():\n user_datastore = SQLAlchemySessionUserDatastore(db.session, User, Role)\n Security(current_app, user_datastore)", "def add_security(self, security: AbstractSecurity, weight: float) -> None:\n pass", "def storeSecurityDetail(self, security):\n pass", "def security(se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Changes security entry that fits the condition parameter to the new security parameter. The condition
def ModifySecurities(self, new_security : Union[Equity, Option], condition : Tuple[Any, RelationalOperator, Any]) -> None: table_name = self.__get_table_name(new_security) set_clause = ", ".join([f"{self._validate_column_name(key)} = '{value}'" for key, value in new_security.__di...
[ "def condition(self,condition):\n self._check_condition(condition)\n # change data in each factor\n for factor in self._factors.values():\n factor.data_restrict(condition)\n # change data in each separator\n for sep in self._separators.values():\n sep.data_re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Delete security from the database.
def DeleteSecurity(self, security : Union[Equity, Option]) -> None: table_name = self.__get_table_name(security) # Query for the security with all matching key, value pairs where_clause = self.__convert_to_sql_where([(key, RelationalOperator.EqualTo, value) for key, value in security.__dict__.items()]) ...
[ "def delete_db_security_group(DBSecurityGroupName=None):\n pass", "def dbDelete(self) -> Result:\n\t\treturn CSE.storage.deleteResource(self)", "def delete():\n\n from slicr.extensions import db\n\n click.echo('deleting database...')\n\n db.drop_all()", "def deleteUser(self):\n db.session.d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Deletes securities from database according to the conditions provided
def DeleteSecuritiesConditional(self, security_type : SecurityType, conditions : List[Tuple[Any, RelationalOperator, Any]] = None) -> None: table_name = self.__get_table_name(security_type) where_clause = self.__convert_to_sql_where(conditions) self.__cursor.execute(f"""DELETE FROM {table_name} ...
[ "def DeleteSecurity(self, security : Union[Equity, Option]) -> None:\n\n table_name = self.__get_table_name(security)\n\n # Query for the security with all matching key, value pairs\n where_clause = self.__convert_to_sql_where([(key, RelationalOperator.EqualTo, value) for key, value in security.__dict__.it...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Finds all securities of type security_type with the specified conditions and ordering by columns
def GetSecurities(self, security_type : SecurityType, conditions : Optional[List[Tuple[Any, RelationalOperator, Any]]] = None, order_by_cols : Optional[List[Tuple[str, Ordering]]] = None) -> List[Union[Equity, Option]]: table_name = self.__get_table_name(security_...
[ "def securities(self):\n return self._query_api_object(Security, \"/rest/securities\", collection_name=\"securities\")", "def DeleteSecuritiesConditional(self, security_type : SecurityType, conditions : List[Tuple[Any, RelationalOperator, Any]] = None) -> None:\n \n table_name = self.__get_table_name...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates an empty customer database
def create_empty_db(): drop_db() database.create_tables([Customer]) database.close()
[ "def create_customer(self):\n try:\n db.create_all()\n except OperationalError as e:\n logging.error(getattr(e, 'message', repr(e)))\n sys.exit(1)\n cust=Customer(self.cust_id,self.name,self.email,self.phone)\n logging.info('New Customer Created Id:{} name:{...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests customer search function
def test_search_customer(self): create_empty_db() add_customer(**user_1) test_map = {'name': user_1['name'], 'lastname': user_1['lastname'], 'email': user_1['email_address'], 'phone_number': user_1['phone_number']} self.assertEqual(test_map, ...
[ "def test_search_customer_pass(self):\n add_customer(customers[1][0], customers[1][1], customers[1][2], customers[1][3],\n customers[1][4], customers[1][5], customers[1][6], customers[1][7])\n self.assertEqual(search_customer('SC0198'), {'name': 'Stormy', 'last_name': 'Calmy',\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests the display of all customers in database
def test_display_customers(self): create_empty_db() self.assertEqual([], display_customers()) add_customer(**user_1) add_customer(**user_2) add_customer(**user_3) self.assertEqual(['Post Malone', 'Howard Moon', 'Vince Noir'], display_custom...
[ "def test_list_customers(self):\n\n # Add an active customer\n bo.add_customer(**TEST_USER1)\n\n # Add an inactive customer\n bo.add_customer(**TEST_USER2)\n\n # Print the active customers\n active_customers = bo.list_active_customers()\n self.assertEqual(active_cust...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adding a ColorField to a model should not fail in 2.2LTS.
def test_model_formfield_doesnt_raise(self): try: fields_for_model(Color()) except AttributeError: self.fail("Raised Attribute Error")
[ "def add_color(self, color, id):", "def validate_color(self, field):\n if match(r'^[A-Fa-f0-9]{0,6}$', field.data):\n field.data = field.data.lower()\n else:\n raise ValidationError('Field is not a valid hexadecimal color code.')", "def add_color(color_name, rgb_triplet):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks that supplying a ColorField with both samples and choices options fails (mutually exclusive).
def test_model_formfield_with_samples_and_choices_fails(self): with self.assertRaises(ImproperlyConfigured): ColorField(choices=COLOR_PALETTE, samples=COLOR_PALETTE)
[ "def test_clean_field_samples(self):\n # 1. Test with predefined choice\n obj = ColorSamples()\n obj.color = ColorSamples.COLOR_SAMPLES[0][0]\n try:\n obj.full_clean()\n except ValidationError as e:\n self.fail(\n \"Failed to assign predefined ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks that supplying a ColorField with the samples kwarg works, and that it accepts valid values outside the predefined choices.
def test_clean_field_samples(self): # 1. Test with predefined choice obj = ColorSamples() obj.color = ColorSamples.COLOR_SAMPLES[0][0] try: obj.full_clean() except ValidationError as e: self.fail( "Failed to assign predefined palette choice...
[ "def test_model_formfield_with_samples_and_choices_fails(self):\n with self.assertRaises(ImproperlyConfigured):\n ColorField(choices=COLOR_PALETTE, samples=COLOR_PALETTE)", "def _is_color_valid(self, color):\n # make sure it is a tuple\n if type(color).__name__ != 'tuple':\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a dictionary of all timeline state items whose start/duration includes time_elapsed.
def GetItemsAtTime(self, time_elapsed): items = [] if self.data == None: raise Exception('TimelineData: Trying to GetState when data==None') # Go through each of our items for item in self.data: # Ignore items that cant be retrieved by time_elapsed if 'start' not in item or 'duration...
[ "def _starttime_dict(self):\n\n completed_ids = [key\n for key in self.job_dict.keys()\n if self.job_dict[key] == 'COMPLETED']\n response_list = [self._request('GET',\n CosmoSim.QUERY_URL + \"/{}\".format(i),\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
For read access, download the file into a local buffer.
async def _download(self) -> None: # do request async with aiohttp.ClientSession() as session: async with session.get(self.url, auth=self._auth, timeout=self._timeout) as response: # check response if response.status == 200: # get data and...
[ "def _download_file(self, artifact_path, local_path):\n full_path = self.base_artifact_path / artifact_path\n with self.managed_folder.get_file(str(full_path)) as remote_file:\n with open(local_path, \"wb\") as local_file:\n for line in remote_file:\n local...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Import the module "_data/[dataset_name]_dataset.py". In the file, the class called DatasetNameDataset() will be instantiated. It has to be a subclass of BaseDataset, and it is caseinsensitive.
def find_dataset_using_name(dataset_name): dataset_filename = "datasets." + dataset_name + "_dataset" datasetlib = importlib.import_module(dataset_filename) dataset = None target_dataset_name = dataset_name.replace('_', '') + 'dataset' for name, cls in datasetlib.__dict__.items(): if 'datase...
[ "def importDataset():\n module_path = os.path.join(path, \"dataset\")\n module_path = os.path.join(module_path, \"dataset.py\")\n dataset_class = importClass(\"Dataset\", \"dataset\", module_path)\n return dataset_class", "def find_dataset_using_name(dataset_name):\r\n dataset_filename = \"data.\" ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
resize image into (target_width,target_height) target_width/target_height = ow/oh raise ValueError, if target_height<=0 or target_width<=0
def __scale_width_height(img, target_width=None, target_height=None, method=Image.BICUBIC): if target_height > 0 and target_width: raise ValueError( f"Expected target_width>0 and target_height>0, but got target_width={target_width}, target_height={target_height}") ow, oh = img.size if t...
[ "def calculate_image_scale(source_width, source_height, target_width, target_height):\n if source_width == target_width and source_height == target_height:\n return 1.0\n\n source_ratio = source_width / source_height\n target_ratio = target_width / target_height\n\n if target_ratio < source_ratio...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
crop the image at position [pos,pos+size]
def __crop(img, pos, size): ow, oh = img.size x1, y1 = pos tw = th = size if (ow > tw or oh > th): return img.crop((x1, y1, x1 + tw, y1 + th)) return img
[ "def crop(img, size=(320,320)):\n xstart = int((img.shape[0]-size[0])/2)\n xend = int(img.shape[0]-xstart)\n ystart = int((img.shape[1]-size[1])/2)\n yend = int(img.shape[1]-ystart)\n return img[xstart:xend, ystart:yend]", "def crop(img, size, point=(0, 0)):\n y, x = point\n w, h = size\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
flip the image if flip is True
def __flip(img, flip, flip_type=Image.FLIP_LEFT_RIGHT): if flip: return img.transpose(flip_type) return img
[ "def flip(self, flip): \n self.data.d = np.asarray(self.im).copy()\n if flip == 0:\n return\n if flip<0:\n self.data.d = np.fliplr(self.data.d)\n flip = -flip\n for _ in range(flip):\n self.data.d = np.rot90(self.data.d)", "def ___flipHelper...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Print warning information about image size(only print once)
def __print_size_warning(ow, oh, w, h): if not hasattr(__print_size_warning, 'has_printed'): logging.warning( f"The loaded image size was ({ow}, {oh}), so it was adjusted to ({w}, {h}).This adjustment will be done to all label2ImagePaths") __print_size_warning.has_printed = True
[ "def _print_img_size(self, img):\n width, height = img.size\n print('{}, {}'.format(width, height))", "def __print_size_warning(self, ow, oh, w, h):\n if not hasattr(self.__print_size_warning, 'has_printed'):\n print(\"The image size needs to be a multiple of 4. \"\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a 1D CNN regressor to predict the next value in a `timeseries` using the preceding `window_size` elements as input features and evaluate its performance.
def evaluate_timeseries(timeseries, window_size): filter_length = 5 nb_filter = 4 timeseries = np.atleast_2d(timeseries) if timeseries.shape[0] == 1: timeseries = timeseries.T # Convert 1D vectors to 2D column vectors nb_samples, nb_series = timeseries.shape print('\n\nTimeseries ...
[ "def create_window_generator(window, batch_size, train_x, train_y, test_x, test_y, prediction_mode):\n train_generator = k.preprocessing.sequence.TimeseriesGenerator(train_x, train_y,\n length=window,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Instantiate with the Pi and gpio to which the sensor is connected.
def __init__(self, pi, gpio): self.pi = pi self.gpio = gpio self._start_tick = None self._last_tick = None self._low_ticks = 0 self._high_ticks = 0 pi.set_mode(gpio, pigpio.INPUT) self._cb = pi.callback(gpio, pigpio.EITHER_EDGE, self._cbf)
[ "def __get_pi_gpio():\n if Sensor.__pi_gpio_instance is None:\n print(\"Attempting to connect to Raspberry Pi GPIO...\")\n Sensor.__pi_gpio_instance = pigpio.pi('pi3.local')\n\n if not Sensor.__pi_gpio_instance.connected:\n print(\"Failed to connect to pi GPIO ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculates the percentage low pulse time and calibrated concentration in particles per 1/100th of a cubic foot since the last read. For proper calibration readings should be made over 30 second intervals. Returns a tuple of gpio, percentage, and concentration.
def read(self): interval = self._low_ticks + self._high_ticks if interval > 0: ratio = float(self._low_ticks)/float(interval)*100.0 conc = 1.1*pow(ratio,3)-3.8*pow(ratio,2)+520*ratio+0.62; else: ratio = 0 conc = 0.0 self._start_tick = None self._last_t...
[ "def get_servo_pct(pi, pin):\n return pulsewidth2pct(pi.get_servo_pulsewidth(pin))", "def pulse_width_percent(self) -> float:", "def calcSpinConc(calibrationFile):#{{{\n openFile = open(calibrationFile,'rt')\n lines = openFile.readlines()\n lines = lines[0].split('\\r')\n lines.pop(0)\n concL ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert concentration of PM2.5 particles per 0.01 cubic feet to ug/ metre cubed this method outlined by Drexel University students (2009) and is an approximation does not contain correction factors for humidity and rain
def pcs_to_ugm3(self, concentration_pcf): if concentration_pcf < 0: raise ValueError('Concentration cannot be a negative number') # Assume all particles are spherical, with a density of 1.65E12 ug/m3 densitypm25 = 1.65 * math.pow(10, 12) # Assume the...
[ "def _pcs_to_ugm3(concentration_pcf):\n\n if concentration_pcf < 0:\n raise ValueError('Concentration cannot be a negative number')\n\n # Assume all particles are spherical, with a density of 1.65E12 ug/m3\n densitypm25 = 1.65 * math.pow(10, 12)\n\n # Assume the radius of a particle in the PM2.5 ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parse command line args for `saml` module
def saml_args(subparsers: argparse.ArgumentParser) -> argparse.ArgumentParser: example_usage = """example usage: ticketsplease saml --adfs-config '...' --target-user-guid '...' --dkm-key '...' --assertion ticketsplease saml --adfs-config-file config.bin --domain company.com --target-user tUser --domain-use...
[ "def parse_arguments(args):", "def _init_argparser():\n desc = 'SES status and metrics reporting utility (part of sasutils).'\n parser = argparse.ArgumentParser(description=desc)\n parser.add_argument('-d', '--debug', action=\"store_true\",\n help='enable debugging')\n\n group =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test unitario que verifica que se guarda un socio de forma permanente
def test_guardar_socio(self): con = ConexionSocio() socio = Socio("49116666Q", "Don Juan", "Tenorio", "634824490", "daswirdaendern@jetzt.de") con.guardar_socio(socio) link = os.path.dirname(__file__) link = link[:-5] + 'src/files/socios.csv' tmp_file = open(link, 'r') ...
[ "def test_guardar_reserva(self):\n socio = mock(Socio)\n con = ConexionReserva(mock(ConexionSocio), mock(ConexionInstalacion))\n inst = mock(Instalacion)\n when(socio).get_dni().thenReturn('11111111K')\n when(inst).get_instalacion_id().thenReturn('inst02')\n fecha = datetim...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a random alternative
def random_alternative(self, fmt_string): # Find alternatives try: alts = self[fmt_string] except KeyError: # There are no alternatives for this string return fmt_string return random.choice(alts)
[ "def randomHelmet():\n return random.choice(HELMETS)", "def rs():\n return random.choice([-1,1])", "def get_random_phrase():\n return random.choices(PHRASES, WEIGHTS, k=1)[0]", "def randomLeggings():\n return random.choice(LEGGINGS)", "def getRandomRarity():\n r = random.randint(1,100)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Scan the alternatives directory and return dict
def read_files(): alts = Alternatives() alt_dir = join(dirname(__file__), "alternatives") fmt_str = "Retrieving alternative strings from file %s" for dirpath, dirnames, filenames in walk(alt_dir, followlinks=True): for filename in filenames: if filename.lower().endswith(".json"): ...
[ "def scan_directory(self):\n root_dir = self.gait_directory.rstrip(os.sep)\n\n directory_dict = {}\n for gait in os.listdir(root_dir):\n gait_path = os.path.join(root_dir, gait)\n\n if os.path.isdir(gait_path):\n gait_dict = {'image': os.path.join(gait_path,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Verifies the endpoint creates a new entry in the users_sensors_mobiles table
def test_create_sensor_mobile_pair(): headers['content-type'] = 'application/json' # user_id = '3a07c79a-2e9f-487f-aef7-555954537e29' # Needs to match JWT token above # user_id = '19bfad75-9d95-4fff-aec9-de4a93da214d' user_id = 'e8514489-8de9-47e0-b3d5-b15da244783f' sensor_mobile_info = {'sensor_pi...
[ "def insert_mobileverification(self, request):\n input_json, output_json, payload = request, {}, {'Payload': None}\n if 'uuid_id_id' in input_json and 'uuid_id' not in input_json:\n input_json['uuid_id'] = input_json['uuid_id_id']\n if 'uuid_id' in input_json and 'uuid_id_id' not in ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates listening sockets bound to the given port and address. Returns a list of socket objects (multiple sockets are returned if the given address maps to multiple IP addresses, which is most common for mixed IPv4 and IPv6 use). Address may be either an IP address or hostname. If it's a hostname, the server will liste...
def bind_sockets(port, address=None, family=socket.AF_UNSPEC, backlog=_DEFAULT_BACKLOG, flags=None, reuse_port=False): if reuse_port and not hasattr(socket, "SO_REUSEPORT"): raise ValueError("the platform doesn't support SO_REUSEPORT") sockets = [] if address == "": address...
[ "def listen(\n self,\n port: int,\n address: Optional[str] = None,\n family: socket.AddressFamily = socket.AF_UNSPEC,\n backlog: int = _DEFAULT_BACKLOG,\n flags: Optional[int] = None,\n reuse_port: bool = False,\n ) -> None:\n sockets = bind_sockets(\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adds an `.IOLoop` event handler to accept new connections on ``sock``. When a connection is accepted, ``callback(connection, address)`` will be run (``connection`` is a socket object, and ``address`` is the address of the other end of the connection). Note that this signature is different from the ``callback(fd, events...
def add_accept_handler(sock, callback): io_loop = IOLoop.current() removed = [False] def accept_handler(_fd, _events): # More connections may come in while we're handling callbacks; # to prevent starvation of other tasks we must limit the number # of connections we accept at a time....
[ "def add_accept_handler(sock, callback, io_loop=None):\n if io_loop is None:\n io_loop = IOLoop.instance()\n def accept_handler(fd, events):\n while True:\n try:\n connection, address = sock.accept()\n except socket.error, e:\n if e.args[0] in ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test a plain text file for miscellaneous issues.
def test_plain_text(): source_file = os.path.join(_TESTS_DIR, 'plain_text_sample.txt') file_reports = psca.analyze([source_file], _SETTINGS_FILE, profile='test_04') reports = file_reports[0].reports # The elements of the found_errors and expected_errors sets are # tup...
[ "def assertFileContents(self, path, text):\n text = self.dedent(text)\n with open(path, 'r') as stream:\n self.assertEqual(stream.read(), text)", "def test_file_read():\n expected = [\"scorevideo LOG\\n\", \"File: log.mat\"]\n with open(TEST_RES + \"/file_read.txt\", 'r') as file:\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
compare two hmacs, with double hmac verification
def macsEqual(mac1, mac2): cmpKey = os.urandom(32) # log.debug("macsEqual lengths:%s:%s:%s", len(cmpKey), len(mac1), len(mac2)) hmac1 = hmac.new(cmpKey, mac1, 'sha256').digest() hmac2 = hmac.new(cmpKey, mac2, 'sha256').digest() return hmac1 == hmac2
[ "def verify_hmac(self, payload):\r\n \r\n new_hmac = hmac.new(bytes(self.passphrase), b'%s'%(payload['eiv']) , hashlib.sha224)\r\n new_hmac.update(b'%s'%(payload['enid']))\r\n new_hmac.update(b'%s'%(payload['ed']))\r\n new_hmac.update(self.sessionID)\r\n #print(new_hmac.digest...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
decryptEncryptionKey returns encryptionKey and macKey
def decryptEncryptionKey(cipherString, key): encryptionType, iv, cipherText, mac = decodeCipherString(cipherString) # log.debug("mac:%s", mac) # log.debug("iv:%s", iv) # log.debug("ct:%s", cipherText) assert mac is None if encryptionType != 0: raise UnimplementedError("can not decrypt type:%s" % encryptionType...
[ "def extract_aes_key(self) -> bytes:\r\n log(\"extract_aes_key start\")\r\n try:\r\n key_base64_raw: bytes = self.file_lines[0]\r\n except IndexError:\r\n # shouldn't be reachable due to test for emptiness prior in code, keep around anyway.\r\n log(\"extract_aes...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
The complete id of the course we're configured to test with. This function is evaluated once per locust client and its return value is cached on a perclient basis (due to the decorator). It randomly selects a course from the "courses" dict specified in the settings file. The "ratio" keys of every course are used to con...
def course_id(self): courses = settings.data['courses'] course_ratio_pairs = \ [(cid, cdata['ratio']) for cid, cdata in courses.iteritems()] return util.choice_with_distribution(course_ratio_pairs)
[ "def _getRandomSetCourseID(self):\n while True:\n courseID = random.randint(0, self._courseCount - 1)\n if len(self._chromosome[courseID]) > 0:\n return courseID", "def set_rand_course_id(self) -> None:\n if len(self.courses) == 0:\n self.set_courses()...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }