query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Get features (for regression) based on this bikedata's weather data
def get_weather_features(self): if self.weather_features is None: raise Exception("Weather features not made yet.") ### self.make_weather_features() else: return self.weather_features
[ "def load_weather():\n filename = (\n \"https://api.featurelabs.com/datasets/daily-min-temperatures.csv?library=evalml&version=\"\n + evalml.__version__\n )\n X, y = load_data(filename, index=None, target=\"Temp\")\n return X, y", "def compute_features(daily):\n\n features = {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Publish response to kafka topic
def publish_response(class_label): client = KProducer(config=publisher_config) client.produce(class_label, PUBLISHER_TOPIC)
[ "def publish_to_kafka(response, args):\n for persuasion in response:\n if args.get(\"push_to_es\", \"false\") == \"true\":\n watson_kafka_response = KafkaServices.publish_to_watson_kafka(persuasion)\n logger.info(watson_kafka_response)\n if args.get(\"push_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the ``BatchStats`` for a specific batch.
def get_batch_stats(self, batch): return self.batch_stats[batch]
[ "def build_batch_stats():\n\n # We use the moving mean as an estimate of the mean in order to perform\n # a more numerically stable calculation of the batch mean.\n # Copy for better stability.\n shift = tf.add(self._moving_mean, 0)\n counts, shifted_sum_x, shifted_sum_x2, _ = tf.nn.suffici...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convenience method that sums up all the sentences across all batches.
def get_total_sentences(self): # loop through batches and add up all their individual sentence counts total_sentences = 0 for batch in self.batch_stats: total_sentences += self.batch_stats[batch].total_sentences return total_sentences
[ "def calculate_texts(self) -> None:\n texts = []\n for text in self.texts:\n paragraphs = list(filter(lambda x: x != \"\", text.split(\"\\n\\n\")))\n for paragraph in paragraphs:\n text = paragraph.replace(\"\\n\", \" \").strip()\n if len(text) > sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adds ``documents`` to the document inventory, writing to disk in batches of 500,000.
def add_documents(self, documents): # flag for StopIteration exceptions more_documents = True # loop while there are still documents in the iterator while more_documents: # increment batch number batch = len(self.batch_stats) + 1 # count sentences sentences_count = 0 # create temporary batch d...
[ "def upload(self, documents: List[Document], vectorise_func) -> None:\n\n # Add doc_store to documents\n for d in documents:\n d.doc_store = self\n # Check ID uniqueness\n check_duplicate_documents(documents)\n # Check type consistency\n check_document_types(docu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Loads a document database with the specified version from the directory.
def load(db_path="data/documents/trigrams", version=None): # create database at the desired path and with the desired version db = DocumentDatabase(db_path, version) # loop through batches for batch in db._get_batches(): # get the path to the stats file stats_file = db._get_batch_stat_file(batch) ...
[ "def load_db():\n return", "def db_load(file_path=Path(\"./song_database.pkl\")):\n with open(file_path, mode=\"rb\") as database:\n return pickle.load(database)", "def load_database(db_file):\n f = Path(db_file)\n if f.is_file():\n filehandle = open(db_file, 'rb')\n db = pi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the latest version of the documents inventory at the specified path.
def get_latest_version(db_path): # create a file system and return latest version return VersionedFile(db_path).get_latest_version()
[ "def current_version(self):\n try:\n return self.versions.latest()\n except DocumentVersion.DoesNotExist:\n return None", "def get_current_version(file_path):\n\n raise RuntimeError('get_current_version function not implemented in Artella Abstract API!')", "def get_latest_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A.K.I 가 생성된 유저를 조회하면서 stale user 를 삭제하는 메서드
def delete_staleuser(): # 이 함수가 users.models 에서 쓰이기 때문에, global 선언은 로드될 때 충돌을 야기한다. from users.models import ActivationKeyInfo for aki in ActivationKeyInfo.objects.all(): if aki.user.is_active is False and aki.expires_at < timezone.now(): aki.delete()
[ "def forget(self, uid):", "def delete_user(self):\n\n \tUser.user_list.remove(self)", "def cleanup(self, lifetime):\n c = self.db.cursor()\n cur = c.execute(\"select login from users where created < date('now', ? || ' days')\",\n (-lifetime,))\n for (login,) in cur...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns OAuth2 credentials if we have valid credentials in the session. This is a 'truthy' value. Return None if we don't have credentials, or if they have expired or are otherwise invalid. This is a 'falsy' value.
def valid_credentials(): if 'credentials' not in flask.session: return None credentials = client.OAuth2Credentials.from_json( flask.session['credentials']) if (credentials.invalid or credentials.access_token_expired): return None return credentials
[ "def valid_credentials():\n if 'credentials' not in flask.session:\n return None\n\n credentials = client.OAuth2Credentials.from_json(\n flask.session['credentials'])\n\n if credentials.invalid or credentials.access_token_expired:\n return None\n return credentials", "def valid_cr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Read time in a humancompatible format and interpret as ISO format with local timezone. May throw exception if time can't be interpreted. In that case it will also flash a message explaining accepted formats.
def interpret_time( text ): app.logger.debug("Decoding time '{}'".format(text)) time_formats = ["ha", "h:mma", "h:mm a", "H:mm"] try: as_arrow = arrow.get(text, time_formats).replace(tzinfo=tz.tzlocal()) as_arrow = as_arrow.replace(year=2016) #HACK see below app.logger.debug("Succe...
[ "def interpret_time( text ):\n app.logger.debug(\"Decoding time '{}'\".format(text))\n time_formats = [\"ha\", \"h:mma\", \"h:mm a\", \"H:mm\"]\n try: \n as_arrow = arrow.get(text, time_formats).replace(tzinfo=tz.tzlocal())\n as_arrow = as_arrow.replace(year=2016) #HACK see below\n ap...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert text of date to ISO format used internally, with the local time zone.
def interpret_date( text ): try: as_arrow = arrow.get(text, "MM/DD/YYYY").replace( tzinfo=tz.tzlocal()) except: flask.flash("Date '{}' didn't fit expected format 12/31/2001") raise return as_arrow.isoformat()
[ "def date_to_iso(string):\r\n\r\n # disregard tokenisation, if it's there, to make this an easier conversion for GUTime\r\n string = re.sub(r'<([^~]*)~.+?>', r'\\1 ', string)\r\n\r\n # Defaults\r\n d = None\r\n m = None\r\n y = None\r\n h = None\r\n min = None\r\n s = None\r\n fs = Non...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a google 'service' object, return a list of calendars. Each calendar is represented by a dict. The returned list is sorted to have the primary calendar first, and selected (that is, displayed in Google Calendars web app) calendars before unselected calendars.
def list_calendars(service): app.logger.debug("Entering list_calendars") calendar_list = service.calendarList().list().execute()["items"] result = [ ] for cal in calendar_list: kind = cal["kind"] id = cal["id"] if "description" in cal: desc = cal["description"] ...
[ "def list_calendars(service):\n app.logger.debug(\"Entering list_calendars with service\")\n calendar_list = service.calendarList().list().execute()[\"items\"]\n app.logger.debug(\"Got calendar list\")\n result = []\n for cal in calendar_list:\n kind = cal[\"kind\"]\n id = cal[\"id\"]\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A helper method that generates a dictionary of arguments needed to instantiate a BaseBoto object. The purpose of this method is to abstract out the code to handle optional CLI arguments and not duplicate the None handling code.
def __get_arguments(args=None, logger=None, stats=None): if not args: parser = get_parser() add_boto_cli_arguments(parser) # Parse only the known arguments added by add_boto_cli_arguments(). # We only need those arguments to create Boto object, nothing else. # parse_known_ar...
[ "def get_default_arg_dict(customizable_class: Any) -> Dict[str, Any]:\n init_arg_dicts = get_extra_argument_dicts(customizable_class)\n found_opts: Dict[str, Any] = {}\n for arg_group in init_arg_dicts:\n for arg_name, arg_attributes in arg_group[\"args\"].items():\n found_opts[arg_name] ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a usable Boto object without creating a class around it. In the context of a krux.cli (or similar) interface the 'args', 'logger' and 'stats' objects should already be present. If you don't have them, however, we'll attempt to provide usable ones for the boto setup. (If you omit the add_boto_cli_arguments() call...
def get_boto(args=None, logger=None, stats=None): return Boto(**__get_arguments(args, logger, stats))
[ "def get_boto3(args=None, logger=None, stats=None):\n return Boto3(**__get_arguments(args, logger, stats))", "def __get_arguments(args=None, logger=None, stats=None):\n\n if not args:\n parser = get_parser()\n add_boto_cli_arguments(parser)\n # Parse only the known arguments added by ad...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return a usable Boto3 object without creating a class around it. In the context of a krux.cli (or similar) interface the 'args', 'logger' and 'stats' objects should already be present. If you don't have them, however, we'll attempt to provide usable ones for the boto setup. (If you omit the add_boto_cli_arguments() cal...
def get_boto3(args=None, logger=None, stats=None): return Boto3(**__get_arguments(args, logger, stats))
[ "def get_boto(args=None, logger=None, stats=None):\n return Boto(**__get_arguments(args, logger, stats))", "def __get_arguments(args=None, logger=None, stats=None):\n\n if not args:\n parser = get_parser()\n add_boto_cli_arguments(parser)\n # Parse only the known arguments added by add_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Extract plastic class label from Image Name and return it
def ExtractLabel(ImgName): # Each img has name notation "*****a0X*" where X is PlasticType PlasticType = ImgName[7] return { '1': 0, # PET '2': 1, # HDPE '4': 2, # LDPE '5': 3, # PP '6': 4, # PS '7': 5, # Other }[PlasticType]
[ "def true_class_label(img_path):\n for i in img_path.split('/'):\n if i in classlabels:\n return i", "def name_to_label(self, name):\n\t\t\treturn self.classes[name]", "def find_label_from_image(image):\n print(\"detecting label\")\n image = Image.open(BytesIO(base64.b64decode(image))...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Support the following DHCP DeviceManager calls. self.plugin.release_dhcp_port(network.id, self.get_device_id(network))
def release_dhcp_port(self, network_id, device_id): LOG.debug("release_dhcp_port: %s %s", network_id, device_id)
[ "def release_dhcp_port(self, network_id, device_id):\n return self.call(self.context,\n self.make_msg('release_dhcp_port',\n network_id=network_id,\n device_id=device_id,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Construct and return an empty network model.
def empty_network(network_id=NETWORK_ID): return make_net_model({"id": network_id, "subnets": [], "ports": [], "tenant_id": "calico", "mtu": neutron_constants.DEFAULT_NETWORK_MTU})
[ "def create_model_one(self):\n self.network_1 = Model(inputs=self.shared.input, outputs=self.shared.output)\n self.network_1.compile(loss='sparse_categorical_crossentropy',\n optimizer='adam',\n metrics=['acc'])\n self.network_1.summar...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Ensure that the cache has a NetModel and subnets for PORT.
def _ensure_net_and_subnets(self, port): # Gather the subnet IDs that we need for this port, and get the # NetModel if we already have it in the cache. needed_subnet_ids = set() net = None for fixed_ip in port['fixed_ips']: subnet_id = fixed_ip.get('subnet_id') ...
[ "def _check_config(self):\n\n if self._stb_ip == None:\n raise RuntimeError('Cannot do HTTP request without setting STB IP')", "def _fix_network_cache_port_lookup(agent, network_id):\n\n # If there is an existing NetModel for this network ID, ensure that all\n # its ports are in the port_l...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Start/stop/restart Dnsmasq for NETWORK_ID.
def _update_dnsmasq(self, network_id): # Check whether we should really do the following processing. if self.suppress_dnsmasq_updates: LOG.debug("Don't update dnsmasq yet;" " must be processing a snapshot") self.dirty_networks.add(network_id) re...
[ "def restart_dnsmasq(self, config):\n\n # TODO currently only supports systemd, add upstart support\n command = ['systemctl', 'restart', 'dnsmasq.service']\n try:\n self.run_command(command, config)\n except Exception, e:\n raise e", "def startServices():\n # d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fix NetworkCache before removing or replacing a network. neutron.agent.dhcp.agent is bugged in that it adds the DHCP port into the cache without updating the cache's port_lookup dict, but then NetworkCache.remove() barfs if there is a port in network.ports but not in that dict... NetworkCache.put() implicitly does a re...
def _fix_network_cache_port_lookup(agent, network_id): # If there is an existing NetModel for this network ID, ensure that all # its ports are in the port_lookup dict. if network_id in agent.cache.cache: for port in agent.cache.cache[network_id].ports: agent.cache.port_lookup[port.id] =...
[ "def _ensure_net_and_subnets(self, port):\n\n # Gather the subnet IDs that we need for this port, and get the\n # NetModel if we already have it in the cache.\n needed_subnet_ids = set()\n net = None\n for fixed_ip in port['fixed_ips']:\n subnet_id = fixed_ip.get('subne...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Run the EtcdWatcher loop.
def run(self): self.etcd.start()
[ "def watch_forever(self):\n\n while True:\n try:\n self.do_tick()\n if self.etcd_elector:\n self.etcd_elector.wait_until_elected()\n self.do_watch()\n except Exception:\n LOG.exception('%s: etcd threw excepti...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compiles robot from given file and returns class object
def compile_robot(file_name, module_name = "contestant_module"): global counter_module module_name += str(counter_module) counter_module += 1 mod = importCode(file_name, module_name) compiled_class = None for symbol in dir(mod): if hasattr(getattr(mod, symbol), "act") and getattr(mod, s...
[ "def compile(self, filename=None):\n\n code = CodeGen()\n code.append(\"\"\"\n # generated by Construct, this source is for inspection only! do not import!\n\n from construct import *\n from construct.lib import *\n from io import BytesIO\n import...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prepare normalized image and label.
def _prepare_image_and_label(self, data): image = tf.io.decode_image(data['image/encoded'], channels=3) label = tf.io.decode_image(data['image/segmentation/class/encoded'], channels=1) height = data['image/height'] width = data['image/width'] image = tf.reshape(image, ...
[ "def prep_images(self):\n self.prep_score()\n self.prep_high_score()\n self.prep_level()\n self.prep_rockets()", "def prep_image_data(arg_dict):\n cat_df = pd.read_csv(arg_dict['category_file'],\n skiprows=1,\n sep='\\s+')\n bbox_df...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parses data for prediction.
def _parse_predict_data(self, data): image, labels = self._parse_eval_data(data) return { 'images': image, 'labels': labels }
[ "def predict(self, datafile):", "def predict(self, data):\n pass", "def _parse_fit_and_predict_result(result):\n if len(result) > 1 and result[1] and not isinstance(result[1], str):\n # Scores object does not resemble a label prediction (always string)\n y = result[0]\n scores = r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
If an iteriter_op is given an iterator as input, no exception should be thrown, and we should return the wrapped function's output.
def test_iteriter_op_1(): @ops.iteriter_op def f(x): return iter([4, 5, 6]) result = f(iter([1, 2, 3])) # Passing in an iterator, as expected assert(isinstance(result, collections.abc.Iterator)), f"{result}" assert(list(result) == [4, 5, 6])
[ "def test_iteriter_op_3():\n\n @ops.iteriter_op\n def f(x):\n return [4, 5, 6] # Returning a list instead of an iterator\n\n with pytest.raises(ValueError):\n result = f(iter([1, 2, 3]))", "def test_iteriter_op_2():\n\n @ops.iteriter_op\n def f(x):\n return iter([4, 5, 6])\n\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
If an iteriter_op is given something besides an iterator as input, raise a ValueError.
def test_iteriter_op_2(): @ops.iteriter_op def f(x): return iter([4, 5, 6]) with pytest.raises(ValueError): f([1, 2, 3]) # Passing in a list instead of an iterator
[ "def test_iteriter_op_3():\n\n @ops.iteriter_op\n def f(x):\n return [4, 5, 6] # Returning a list instead of an iterator\n\n with pytest.raises(ValueError):\n result = f(iter([1, 2, 3]))", "def test_listiter_op_2():\n\n @ops.listiter_op\n def f(x):\n return iter([4, 5, 6])\n\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
If an iteriter_op returns something besides an iterator as output, raise a ValueError.
def test_iteriter_op_3(): @ops.iteriter_op def f(x): return [4, 5, 6] # Returning a list instead of an iterator with pytest.raises(ValueError): result = f(iter([1, 2, 3]))
[ "def test_iteriter_op_2():\n\n @ops.iteriter_op\n def f(x):\n return iter([4, 5, 6])\n\n with pytest.raises(ValueError):\n f([1, 2, 3]) # Passing in a list instead of an iterator", "def test_listiter_op_2():\n\n @ops.listiter_op\n def f(x):\n return iter([4, 5, 6])\n\n with...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
If a listlist_op is given a list as input, no exception should be thrown, and we should return the wrapped function's output.
def test_listlist_op_1(): @ops.listlist_op def f(x): return [4, 5, 6] result = f([1, 2, 3]) # Passing in a list, as expected assert(isinstance(result, list)), f"{result}" assert(result == [4, 5, 6])
[ "def test_listlist_op_3():\n\n @ops.listlist_op\n def f(x):\n return iter([4, 5, 6]) # Returning an iterator instead of an list\n\n with pytest.raises(ValueError):\n result = f([1, 2, 3])", "def test_listlist_op_2():\n\n @ops.listlist_op\n def f(x):\n return [4, 5, 6]\n\n w...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
If a listlist_op is given something besides a list as input, raise a ValueError.
def test_listlist_op_2(): @ops.listlist_op def f(x): return [4, 5, 6] with pytest.raises(ValueError): f(iter([1, 2, 3])) # Passing in an iterator instead of an list
[ "def test_listlist_op_3():\n\n @ops.listlist_op\n def f(x):\n return iter([4, 5, 6]) # Returning an iterator instead of an list\n\n with pytest.raises(ValueError):\n result = f([1, 2, 3])", "def is_listing(op):\n return isinstance(op, (list, tuple))", "def test_listlist_op_1():\n\n @...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
If a listlist_op returns something besides a list as output, raise a ValueError.
def test_listlist_op_3(): @ops.listlist_op def f(x): return iter([4, 5, 6]) # Returning an iterator instead of an list with pytest.raises(ValueError): result = f([1, 2, 3])
[ "def test_listlist_op_2():\n\n @ops.listlist_op\n def f(x):\n return [4, 5, 6]\n\n with pytest.raises(ValueError):\n f(iter([1, 2, 3])) # Passing in an iterator instead of an list", "def test_listlist_op_1():\n\n @ops.listlist_op\n def f(x):\n return [4, 5, 6]\n\n result = ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
If a listiter_op is given a list as input, no exception should be thrown, and we should return the wrapped function's output.
def test_listiter_op_1(): @ops.listiter_op def f(x): return iter([4, 5, 6]) result = f([1, 2, 3]) # Passing in a list, as expected assert(isinstance(result, collections.abc.Iterator)), f"{result}" assert(list(result) == [4, 5, 6])
[ "def test_iterlist_op_1():\n\n @ops.iterlist_op\n def f(x):\n return [4, 5, 6]\n\n result = f(iter([1, 2, 3])) # Passing in an iterator, as expected\n\n assert(isinstance(result, list)), f\"{result}\"\n assert(result == [4, 5, 6])", "def test_listlist_op_3():\n\n @ops.listlist_op\n de...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
If a listiter_op is given something besides a list as input, raise a ValueError.
def test_listiter_op_2(): @ops.listiter_op def f(x): return iter([4, 5, 6]) with pytest.raises(ValueError): f(iter([1, 2, 3])) # Passing in an iterator instead of a list
[ "def test_listlist_op_2():\n\n @ops.listlist_op\n def f(x):\n return [4, 5, 6]\n\n with pytest.raises(ValueError):\n f(iter([1, 2, 3])) # Passing in an iterator instead of an list", "def test_listlist_op_3():\n\n @ops.listlist_op\n def f(x):\n return iter([4, 5, 6]) # Returni...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
If an iterlist_op is given an iterator as input, no exception should be thrown, and we should return the wrapped function's output.
def test_iterlist_op_1(): @ops.iterlist_op def f(x): return [4, 5, 6] result = f(iter([1, 2, 3])) # Passing in an iterator, as expected assert(isinstance(result, list)), f"{result}" assert(result == [4, 5, 6])
[ "def test_listiter_op_2():\n\n @ops.listiter_op\n def f(x):\n return iter([4, 5, 6])\n\n with pytest.raises(ValueError):\n f(iter([1, 2, 3])) # Passing in an iterator instead of a list", "def test_listiter_op_1():\n\n @ops.listiter_op\n def f(x):\n return iter([4, 5, 6])\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
If a pool of size 3 is used, the first 3 individuals in the input iterator should be collected into a list.
def test_pool(): pop = iter([ 'a', 'b', 'c', 'd', 'e' ]) pop = ops.pool(pop, size=3) assert(len(pop) == 3) assert(pop == [ 'a', 'b', 'c' ])
[ "def n_wise(x: List[Any], size: Optional[int] = 2) -> Iterable:\n\n iterator = iter(x)\n\n return iter(lambda: tuple(islice(iterator, size)), ())", "def batch_iterator(iterator, batch_size):\n it = iter(iterator)\n item = list(itertools.islice(it, batch_size))\n while item:\n yield item\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Converts a wave to a vector of prosodic features. offset (in ms) determines where the signal will be sampled. window_len is ignored.
def wav_to_prosodic(path, sr=16000, offset=10): sound = parselmouth.Sound(path) pitch = sound.to_pitch() #timestep, pitch_floor, pitch_ceiling intensity = sound.to_intensity() features = [] max_time = sound.get_total_duration() for time in np.arange(0, max_time, 0.001): f0 = pitch.get...
[ "def _choose_wavelength_slice(self, offset):\n if 'WAVE' not in self.axes_wcs.wcs.ctype:\n raise cu.CubeError(2, \"Spectral dimension not present\")\n if self.data.ndim == 4:\n raise cu.CubeError(4, \"Can only work with 3D cubes\")\n\n axis = -2 if self.axes_wcs.wcs.ctype[...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Print percentage of rows that have been processed.
def _print_stat_rows(title,rows_before,rows_after): self.strprint(str(title)+" : Percent of processed rows = %1.2F"\ %(np.abs(rows_before-rows_after)*100/rows_before))
[ "def printProgress(self, percentage):\n #print '%s\\r' % ' '*20, # clean up row\n #print '%3d%% ' % percentage, # ending with comma prevents newline from being appended\n sys.stdout.flush()", "def printProgress(self, percentage):\n print('%s\\r' % ' ' * 20,) # clean up row\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove raws with countries other then 'United Kingdom' then remove Country feature.
def _feature_country_process(self): if 'Country' not in self._df_invoice_line.columns: return list_countries_keep = ['United Kingdom'] rows_before = self._df_invoice_line.shape[0] df_invoice_line_new = pd.DataFrame() for country in list_countries_keep : df_invoic...
[ "def delete_countries() -> None:\n remove_all_countries()", "def apply_feature_filter(self):\n self.features = set()\n for language in self.data.values():\n features_in_data = set(language.keys())\n features_to_keep = features_in_data & self.feature_filter\n self....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Builds for each customer, RFM scores and encode scores. When this method is called during building data_model step, then dataframe handling new RFM features is dumped into a file.
def data_transform_rfm(self) : is_built_step = False if self._encoder_rfm is None: is_built_step = True #------------------------------------------------------------------------- # RFM feature is built #--------------------------------------------------------------...
[ "def df_customers_fileRead(self):\n \n #-------------------------------------------------------------------------\n # RFM features are restored\n #-------------------------------------------------------------------------\n df_customers_rfm \\\n = p5_util.object_load(self.df_customer...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates new features from Description feature thanks to NLTK, a NLP package. NLP features are handled into a dataframe. A PCA reduction is applied on this dataframe. Features from dataframe are renamed with root ane w_nlp. When this method is called during building data_model step, then dataframe handling new NLP featu...
def data_transform_nlp(self): df_invoice_line = None is_build_step = False if self._vectorizer_nlp is None: is_build_step = True list_no_words=['SET','PACK'] df_invoice_line, csr_matrix_weights, self._vectorizer_nlp \ = p5_util.nlp_process(self.df_invoice_...
[ "def feature_description_nlp(self):\n \n #-------------------------------------------------------------------------\n # Returned dataframe is aggregated with weights from self.vectorizer\n #-------------------------------------------------------------------------\n list_no_words=['SET','PAC...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Build dataframe df_customers from transformed data. Transformed data are issued from NLP, Time and RFM features. See data_transform(). These data are stored as dataframes attributes.
def df_customers_features_build(self): df_customers_rfm = self._df_customers_rfm.copy() df_customers_timeFeature = self._df_customers_timeFeature.copy() df_customers_nlp = self._df_customers_pca_nlp.copy() #------------------------------------------------------------------------- # Dataf...
[ "def features_customers(df_customers):\n for i in PREMIER_VALS:\n k = 'premier_' + str(i)\n df_customers[k] = np.where(df_customers['premier'] == i, 1, 0)\n\n df_customers['age'] = datetime.now().date().year - df_customers['yearOfBirth']\n df_customers['male'] = np.where(df_customers['gender'...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Build dataframe df_customers from transformed data. Transformed data are loaded from dumped files issued from NLP, Time and RFM features. See data_transform()
def df_customers_fileRead(self): #------------------------------------------------------------------------- # RFM features are restored #------------------------------------------------------------------------- df_customers_rfm \ = p5_util.object_load(self.df_customers_rfm_fileNa...
[ "def df_customers_features_build(self):\n\n df_customers_rfm = self._df_customers_rfm.copy()\n df_customers_timeFeature = self._df_customers_timeFeature.copy()\n df_customers_nlp = self._df_customers_pca_nlp.copy()\n\n #-------------------------------------------------------------------------\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates a new customer identifier from existing dataset.
def createCustomerID(self): customerID = self._df_invoice_original.CustomerID.max() customerID += 1 return int(customerID)
[ "def test_companies_company_id_data_customers_customer_id_get(self):\n pass", "def create_customer(cls, api, **data):\n return api.create_customer(**data)", "def create_customer(data):\n mandatory_params = ['customer_name', 'mobile_number']\n result = api_utils.check_required_params(mandator...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Drop from df_invoice_line dataframe features in list given as parameter. All elements from list are checked to be into dataframe columns.
def list_feature_drop(self): list_to_drop = list() list_not_in_df = list() #------------------------------------------------------------------------- # Columns are checked to be into df_invoice_line dataframe #------------------------------------------------------------------...
[ "def drop_dfcol(self, drop_list):\n self.data = self.df\n for lbl in drop_list:\n self.data = self.data.drop(lbl, axis=1)\n self.n_features = np.shape(self.data)[1]", "def drop(self,df, column_list):\n df.drop(columns = column_list, inplace = True)\n return df", "de...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Process df_invoice_line.Description with NLTK package.
def feature_description_nlp(self): #------------------------------------------------------------------------- # Returned dataframe is aggregated with weights from self.vectorizer #------------------------------------------------------------------------- list_no_words=['SET','PACK'] ...
[ "def process_text(self, text, language):", "def data_transform_nlp(self):\n df_invoice_line = None\n \n is_build_step = False\n\n if self._vectorizer_nlp is None:\n is_build_step = True\n \n list_no_words=['SET','PACK']\n\n df_invoice_line, csr_matrix_weights, self._v...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Standardize quantitatives features. Standardizer is stored as object attribute. It will be copied into P5_SegmentClassifier object.
def feature_scale(self): #------------------------------------------------------------------------- # List of quantitative features to be standardized #------------------------------------------------------------------------- list_quant_feature = ['Quantity','UnitPrice'] self._list_qua...
[ "def standardiser(self):\n # Select only numeric features first\n\n #self.X = self.data.loc[:, self.data.columns != self.target].values\n numeric_columns = []\n for col in self.X.columns:\n if self.X[col].dtype!='object':\n numeric_columns.append(col)\n s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns market segment ID related to a customer thanks to customer invoices lines given as parameter. Features transformations are applied on data included into invoice lines. Once done, a machine learning algorithm is invocated in order to predict customer market segment.
def get_customer_marketSegment(self, df_invoice_line_customer): #------------------------------------------------------------------------- # Building data model #------------------------------------------------------------------------- self.data_transform(df_invoice_line_customer) #-----...
[ "def predict_segment(self, df_invoice_line=None):\n if df_invoice_line is not None:\n self.data_transform(df_invoice_line) \n self.df_customers_features_build() \n else:\n pass\n X_test = self._df_customers.values\n y_pred = self._classifier_model.predict(X_test)\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function creates an invoice compounding invoices lines from data given as parameters. Once done, this function computes market segment customer belongs to. If customerID is None, then a new customer identifier is created before order process to take place.
def order_process(self, customerID, list_stockCode, list_quantity\ , orderDate=None): segmentID = -1 #------------------------------------------------------------------------- # A new customer is created and inserted into data-set. #----------------------------------------------------------...
[ "def create_customer_df_invoice_line(self, customerID, list_stockCode\\\n , list_quantity, invoiceDate):\n \n dict_invoice = dict()\n\n dict_invoice['Quantity'] = list_quantity\n dict_invoice['StockCode'] = list_stockCode\n\n #--------------------------------------------------------------...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the segment identifier a customers is predicted to belongs to.
def predict_segment(self, df_invoice_line=None): if df_invoice_line is not None: self.data_transform(df_invoice_line) self.df_customers_features_build() else: pass X_test = self._df_customers.values y_pred = self._classifier_model.predict(X_test) return ...
[ "def get_customer_marketSegment(self, df_invoice_line_customer):\n #-------------------------------------------------------------------------\n # Building data model \n #-------------------------------------------------------------------------\n self.data_transform(df_invoice_line_customer)\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns list of stock codes from list of items descriptions.
def getStockCodeList(self, list_description=None): list_stockCode = list() df = self._df_invoice_original if list_description is None: list_stockCode = list(df.StockCode.unique()) else : for description in list_description: stockCode = df[df.Description==desc...
[ "def getDescriptionList(self, list_stockCode=None):\n df = self._df_invoice_original\n\n list_description = list()\n if list_stockCode is None :\n list_description = list(df.Description.unique())\n else:\n for stockCode in list_stockCode:\n description = df[df.StockCod...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns list of imtes unit price from list of stock codes.
def getUnitPriceList(self, list_stockCode): df = self._df_invoice_original list_unitPrice = list() for stockCode in list_stockCode: unitPrice = df[df.StockCode==stockCode].UnitPrice.unique()[0] list_unitPrice.append(unitPrice) return list_unitPrice
[ "def get_price_list(self, item_list):\n price_list = []\n for item in item_list:\n price_list.append(Inventory.stock[item].price)\n return price_list", "def getStockCodeList(self, list_description=None):\n list_stockCode = list()\n df = self._df_invoice_original\n \n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns list of items descriptions from list of stock codes.
def getDescriptionList(self, list_stockCode=None): df = self._df_invoice_original list_description = list() if list_stockCode is None : list_description = list(df.Description.unique()) else: for stockCode in list_stockCode: description = df[df.StockCode==stockCode]...
[ "def getStockCodeList(self, list_description=None):\n list_stockCode = list()\n df = self._df_invoice_original\n \n if list_description is None:\n list_stockCode = list(df.StockCode.unique())\n else :\n for description in list_description:\n stockCode = df[df.Desc...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Creates new dataframe with invoices lines issued from given parameters. Once done, the new dataframe is aggregated with original one.
def create_customer_df_invoice_line(self, customerID, list_stockCode\ , list_quantity, invoiceDate): dict_invoice = dict() dict_invoice['Quantity'] = list_quantity dict_invoice['StockCode'] = list_stockCode #------------------------------------------------------------------------ ...
[ "def merge_purchase_invoice(self):\r\n active_id = self.env['purchase.order'].browse(self.env['purchase.order']._context.get('active_ids'))\r\n journal_id = self.env['account.journal'].search([('type', '=', 'purchase')]) \r\n active_id_count = 0\r\n active_count = 0\r\n exist_vend...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a dataframe with all invoice lines from customerID given as parameter.
def get_customer_history_df_invoice_line(self, customerID): df_invoice_line \ = self._df_invoice_original[self._df_invoice_original.CustomerID \ == customerID] return df_invoice_line
[ "def create_customer_df_invoice_line(self, customerID, list_stockCode\\\n , list_quantity, invoiceDate):\n \n dict_invoice = dict()\n\n dict_invoice['Quantity'] = list_quantity\n dict_invoice['StockCode'] = list_stockCode\n\n #--------------------------------------------------------------...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a list of customers that have been excluded of data sampling used for building model. By default, 10 customers identifier is returned. If customerCount value is None, or <= 0, then list of all customers that have been excluded of data sampling is returned.
def get_listCustomer_out_sample(self, customerCount=10): if customerCount is None : listCustomer= list(self._df_invoice_line_out_sample.CustomerID.unique()) else: if customerCount <= 0 : listCustomer \ = list(self._df_invoice_line_out_sample.CustomerID.unique...
[ "def remove_exiting_customers(self):\n self.customers=[c for c in self.customers if c.is_active()]", "def get_all_customer_ids():\n table = data_manager.get_table_from_file(\"sales/sales.csv\")\n return get_all_customer_ids_from_table(table)", "def get_all_customers():\n data = user_obj.get_all_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns number of invoices from original dataset.
def get_invoice_count(self): return self._df_invoice_original.InvoiceNo.unique().shape[0]
[ "def _compute_no_of_invoices(self):\n for record in self:\n record.invoice_count = len(record.invoice_ids)", "def get_invl_count(self):\n return self._df_invoice_original.index.unique().shape[0]", "def invoices(self):\n from invoice.models.inv import Invoice\n\n return Invoi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns number of customers from original dataset.
def get_customer_count(self): return self._df_invoice_original.CustomerID.unique().shape[0]
[ "def get_total_customers(self, report_df):\n\n return len(report_df.loc[:, 'customer_id'].unique())", "def bus_total_customers(self) -> int:\n return self.dss_obj.BUSI(4, 0)", "def test_customer_count(self):\n\n # test that enpoint returns the correct count of products\n rv = self.ap...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns number of invoice lines (number of rows) from original dataset.
def get_invl_count(self): return self._df_invoice_original.index.unique().shape[0]
[ "def get_invoice_count(self):\n return self._df_invoice_original.InvoiceNo.unique().shape[0]", "def getNumRows(self) -> int:\n ...", "def _compute_no_of_invoices(self):\n for record in self:\n record.invoice_count = len(record.invoice_ids)", "def get_num_lines(new_crystal_text):\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns JSON structure issued form dataframe content given as parameter .
def json_df_builder(self, df, marketID, RFM=None): #------------------------------------------------------------------------- # Extract from dataframe content to be returned #------------------------------------------------------------------------- str_customerID = str(df.CustomerID.uniqu...
[ "def toJSON(self, df) :\n ret = json.dumps(df, indent=4)\n return ret", "def get_json(df):\n\t import json\n\t import datetime\n\t def convert_timestamp(item_date_object):\n\t if isinstance(item_date_object, (datetime.date, datetime.datetime)):\n\t return item_date_object....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function is used for validation process. It returns a list of stockCode items and a list of quantities for each item.
def get_order_lists(self, n_items, n_quantities): arr_stock_code = self._df_invoice_original.StockCode.unique() arr_stock_code = np.random.choice(arr_stock_code, n_items) list_stockCode = list(arr_stock_code) list_quantities = np.ones(arr_stock_code.shape[0]) list_quantities *=n_quantities...
[ "def get_items(self):\n \n items = []\n\n params = self.request.query_params\n\n if 'items[]' in params:\n items = params.getlist('items[]', [])\n elif 'item' in params:\n items = [params.get('item', None)]\n\n if type(items) not in [list, tuple]:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sentence generator for an entire corpus directory.
def sentences_for_dir(path='./',separate=True,gzipped=True): for filename in cowfiles(path): for metadata, data in sentence_generator(filename,separate,gzipped): yield metadata, data
[ "def gen_sentences_from_dir(path, ext=\"txt\"):\n for doc in gen_documents_from_dir(path, ext):\n for s in gen_sentences_from_string(doc):\n yield s", "def load_data_sentences(dirname):\n sentence_list = []\n for fname in os.listdir(dirname):\n with open(os.path.join(dirname, fna...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Build each tree in the 'forest' of trees. After each iteration, evaluate the tree and reweight the input sample such that incorrect events are weighted up and correct events are weighted down
def build(self): # weights to apply to training samples, updated on each # iteration of the boosting algo, normalised to 1 sigWeights = np.ones(self.nSig, dtype=float) bkgWeights = np.ones(self.nBkg, dtype=float) reweight = 1.0/(np.sum(sigWeights)+np.sum(bkgWeights)) sigW...
[ "def grow_forest(forest, X, y, seeds, labels=None):\n # Convert data\n X, = check_arrays(X, dtype=DTYPE, sparse_format=\"dense\")\n # Make a list container for grown trees\n n_trees = forest.n_estimators\n trees = []\n # For each tree in the forest\n for i in range(n_trees):\n # Make a n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
classify a given event. Iterates over each tree in the forest and then returns the weighted average of the results
def classify(self, event): results = np.zeros(self.ntrees, dtype=float) for i,dt in enumerate(self.dTrees): results[i] = self.treeWeights[i]*dt.classify(event) return np.sum(results)*(1.0/np.sum(self.treeWeights))
[ "def analyze_tree(dataset,my_tree,column_class=-1):\n #get the relevant starting variables\n labels = dataset[:,column_class]\n N, class_num = np.shape(dataset)\n datapred = np.zeros(N)\n #now loop and get the predictions\n for i in range(N):\n prediction = predict_tree(dataset[i,:], my_tre...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Node frontiers generator using breadthfirst search.
def bfs_nodes_generator(graph, source, reverse=...): ...
[ "def breadthfirst(self):\n import os\n cwd = os.getcwd()\n os.chdir('/Users/raj/Documents/algorithms_in_python/linked_lists/')\n from linked_collections import LinkedQueue\n os.chdir(cwd) # change to cwd\n if not self.is_empty():\n lq = LinkedQueue()\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Edges frontiers generator using breadthfirst search.
def bfs_edges_generator(graph, source, reverse=...): ...
[ "def bfs_nodes_generator(graph, source, reverse=...):\n ...", "def breadthfirst(self):\n import os\n cwd = os.getcwd()\n os.chdir('/Users/raj/Documents/algorithms_in_python/linked_lists/')\n from linked_collections import LinkedQueue\n os.chdir(cwd) # change to cwd\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Node frontiers generator using topological traversal.
def topological_nodes_generator(graph, reverse=...): ...
[ "def bfs_nodes_generator(graph, source, reverse=...):\n ...", "def _get_front_nodes(self):\n ret = []\n node = self.root.getprevious()\n while node is not None:\n ret.append(node)\n node = node.getprevious()\n return ret", "def breadth_first_iterate(execution...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Edge frontiers generator using depthfirstsearch (DFS). Multiple source nodes can be specified to start the DFS traversal. One needs to make sure that each source node belongs to different connected component, so the frontiers can be easily merged. Otherwise, the behavior is undefined.
def dfs_edges_generator(graph, source, reverse=...): ...
[ "def bfs_nodes_generator(graph, source, reverse=...):\n ...", "def breadth_first_search(self, source: int) -> list:\n # Time complexity: O(num_vertices + num_edges), aka O(V+E)\n \n # Note: This initialization is a must, since other methods may change defaults\n self.color = [Color....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
find the feature to use for the next node split and also find where the plit should be in that feature This loops through the split options within a feature to find the best gini score, then it loops through each feature to compare optimal gini scores
def find_split(self, X, y): choices = y.size if choices <= 1: return None, None # find the number of each option in the current node. options_parent = [np.sum(y == c) for c in range(self.num_outcomes)] # find the gini of current node. best_gini = 1.0 - sum((...
[ "def find_best_split(data, feature_names, min_samples_leaf=5, random_subset=False, column_class=-1):\n N, f_n = np.shape(data)\n n = f_n - 1\n root_n = int(np.ceil(np.sqrt(n)))\n if (column_class == -1):\n column_class = f_n - 1\n if (random_subset == True):\n list_features = np.random....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A class without the key_fields annotation should raise a RuntimeError
def testNoKeyFields(): with pytest.raises(RuntimeError): class AnnotatedNode(Node): x: str y: int def __init__(self, x: str, y: int): self.x = x self.y = y @property def _display(self) -> str: ret...
[ "def test_key_init_inconsistent_fields(self):\n # Modify the class to add a bogus field name that is not in the DB\n TestMappings.index_fields.append('bad_field')\n tm = Keys(TestMappings)\n # Remove the field name again (or get horrible stuff in rest of tests)\n TestMappings.inde...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
creates randomized colors of shape size_x by size_y
def create_world(size_x = 100, size_y=100): colors = np.random.randint(0,2,(size_x,size_y)).tolist() for row in range(len(colors)): for col in range(len(colors[row])): if (colors[row][col]== 1): colors[row][col] = 'R' else: colors[row][col] = 'G' ...
[ "def generate_random_colors(self):\n colors = [(random.randint(0, 200), random.randint(0, 200), random.randint(0, 255)) for _ in range(32)]\n grid = []\n for color in colors:\n grid.extend([color, color])\n grid[self.special_coord[0] + (self.special_coord[1] * 8)] = self.speci...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Finds a dihedral angle adjacent to the selected atoms that includes a new atom
def _find_dihedral(selected): atom_name = lambda atom: atom.fullName() atom_mass = lambda atom: atom.mass() # Loop over possible nearest neighbors for a2 in selected: # Find the new atom attached_to_a2 = sorted([a for a in a2.bondedTo() \ if a not in selected], key=at...
[ "def dihedral_calculator():\n\n\t# Prime with first 3 points\n\tp1 = Vector3((yield None))\n\tp2 = Vector3((yield None))\n\tp3 = Vector3((yield None))\n\n\t# Set up for first angle\n\tlastpoint = p3\n\tlastdisp = p3 - p2\n\tlastnormal = ((p2 - p1) @ lastdisp).normalize()\n\n\tangle = None\n\n\t# For each point star...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Conversion from (internal or extended) BondAngleTorsion to Cartesian coordinates
def Cartesian(self, BAT): # Arrange BAT coordinates in convenient arrays offset = 6 if len(BAT) == (3 * self.natoms) else 0 bonds = BAT[offset + 3::3] angles = BAT[offset + 4::3] phase_torsions = BAT[offset + 5::3] torsions = [(phase_torsions[n] + phase_torsions[self._firstTorsionTInd[n]]) \ ...
[ "def cartesian2polar(cartesian):\n cartesian = np.array(cartesian).squeeze()\n x, y = cartesian\n r = np.linalg.norm([x, y])\n azimuth = np.arctan2(y, x)\n return np.array([r, azimuth])", "def to_cartesian(self):\n w = 1.73205 # sqrt(3)\n h = 2\n dx = 0.5 * w if self.y % 2 == ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Opens the molecule in VMD
def showMolecule(self, colorBy=None, label=False, dcdFN=None): # Write PDB file # To set Occupancy, change atom.occupancy # To set Beta, change atom.temperature_factor import os.path pdbFN = os.path.join(MMTK.Database.molecule_types.directory, 'showMolecule.pdb') outF = ...
[ "def open_mdd(self):\n import webbrowser\n\n mdd, *_ = self.simulation_dir.files(\"*.mdd\")\n\n webbrowser.open(mdd.abspath())", "def viewNMDinVMD(filename):\n\n vmd = pathVMD()\n if vmd:\n os.system('{0} -e {1}'.format(vmd, abspath(filename)))", "def _vmd_script_molecule(mole,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test read and write ints.
def test_message_int(): result = True message = msg.Message() for i in range(num_it): message.appendInt(i) if message.length != msg.HEADER_SIZE + (i+1)*msg.intStruct.size: print("Size is ", message.length, " but should be ", msg.HEADER_SIZE + (i+1)*msg.intStruct.size) ...
[ "def testSimpleReadWrite(self):\n write_data = self.GetRandomIntegers(2048)\n read_data = []\n # Writer writes some data.\n asserts.assertTrue(\n self._queue1_writer.write(write_data, 2048), \"Write queue failed.\")\n # Check reader reads them back correctly.\n r...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Handles a leave game request. Deletes the user from the game.
def leave_game(players_cursor, states_cursor, user, room_id): leave_query = '''DELETE FROM players_table WHERE user = ? AND room_id = ?''' players_cursor.execute(leave_query, (user, room_id)) FRAMES.append(display_game(players_cursor, states_cursor, user, room_id))
[ "def leave(msg: telebot.types.Message):\n if utils.in_menu(msg.from_user):\n bot.reply_to(\n msg,\n 'This command outside of game is useless.'\n )\n return\n\n game, user, opponent = utils.get_game_user_opponent(msg.from_user)\n if not game or not user:\n #...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Select Relationships associated with specified fact_id.
def select_by_fact_id(cls, fact_id): return db.session.query(cls).filter_by(fact_id=fact_id).all()
[ "def read_relationships(person_id):\n try:\n conn = sqlite3.connect(settings.database_name)\n conn.row_factory = sqlite3.Row\n c = conn.cursor()\n c.execute(\"PRAGMA foreign_keys = ON\")\n c.execute(relationship_query, (person_id,)) # note a tuple is needed as a parameter valu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Select Relationship with specified subject, object and relationship type.
def select_by_foreign_keys(cls, subject_id=None, object_id=None, relationship_type_id=None): filter_clause = sa.and_( sa.and_(cls.subject_id == subject_id, cls.object_id == object_id), cls.relationship_type_id == relationship_type_id) return db.session.query(cls).filter(filter_cl...
[ "def select_by_values(cls, relationship_type_name=None, relationship_number=None,\n subject_name=None, object_name=None):\n query = db.session.query(cls).\\\n join(RelationshipType).\\\n filter(RelationshipType.relationship_type_name==relationship_type_name)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Select Relationships with specified relationship_type, count, subject, and object.
def select_by_values(cls, relationship_type_name=None, relationship_number=None, subject_name=None, object_name=None): query = db.session.query(cls).\ join(RelationshipType).\ filter(RelationshipType.relationship_type_name==relationship_type_name) if rela...
[ "def select_by_foreign_keys(cls, subject_id=None, object_id=None, relationship_type_id=None):\n filter_clause = sa.and_(\n sa.and_(cls.subject_id == subject_id, cls.object_id == object_id),\n cls.relationship_type_id == relationship_type_id)\n return db.session.query(cls).filter(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Validate requests decorator with Cerberus
def validate_request_cerberus(schema): def decorator(func): @wraps(func) def wrapper(*args, **kwargs): body_json = request.get_json() current_app.logger.info(body_json) v = Validator(schema, require_all=True) v.allow_unknown = True # TODO: allow reques...
[ "def validate_request(self, func):\n @wraps(func)\n def decorated_view(*args, **kwargs):\n if current_app.TESTING:\n return func(*args, **kwargs)\n url = request.base_url\n vars = request.values\n signature = request.header.get('X-Twilio-Signa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Plots the graph. If the nodes have a position, the nodes will be placed there. Otherwise, they will be placed in a random but elegant manner.
def plot_graph(self) -> None:
[ "def plot_graph(self):\r\n x = []\r\n y = []\r\n\r\n for n in self.graph.get_all_v().values():\r\n if(n.get_pos() != None):\r\n x.append(n.get_pos().get_x())\r\n y.append(n.get_pos().get_y())\r\n else:\r\n x_random = random.rand...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Formats comparison as a strings
def format_comparison(objs): def formatter(comp): if not isinstance(comp, tuple): return str(comp) output = [] return "\n".join([comp.type] + [" "+errmessage for errmessage in output]) results = map(formatter,objs) return "\n".join(results) #obj1,obj2...
[ "def generate_comparison_output_string(comparisons: List[Dict[str, Any]]) -> str:\n result_dict = generate_comparison_dict(comparisons)\n result_string = json.dumps(result_dict, sort_keys=True, indent=4)\n return result_string", "def format_condition(self, key, val1, val2):\n if val1 is not None a...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Catches a difference when one or both of the objects are None (since it is handled the same across methods)
def none_comparison(func): @functools.wraps(func) def inner(obj1,obj2): if obj1 is not None and obj2 is not None: return func(obj1, obj2) if obj1 is None and obj2 is None: return [] if obj1 is not None and obj2 is None: return Difference(f"Second {obj1...
[ "def ifnone(a: Any, b: Any) -> Any:\n return b if a is None else a", "def _check_none(self) -> PossibleResult[T]:\n if self.constructor == type(None):\n if not self.obj is None:\n raise DeserializeError(\n type(None), self.obj, self.new_depth, self.key\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compares Attributes between 2 objects via getattr, returning the attribute values as a tuple if they do not match
def attr_comparison(obj1,obj2,attrs): return [Difference(f"{obj1.__class__.__name__}.{attr}",(result1,result2)) for attr in attrs if (result1 := getattr(obj1,attr)) != (result2 := getattr(obj2,attr))]
[ "def attrs_to_tuple(obj):\n return tuple(getattr(obj, a) for a in attrs)", "def CheckAttribs(a, b, attrs, assertEquals):\n # For Stop objects (and maybe others in the future) Validate converts some\n # attributes from string to native type\n a.Validate()\n b.Validate()\n for k in attrs:\n assertEqu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a list of tuples comparised of (subcomparison method, attr name for comparison), returns any Difference tuple retunred by each method using the given attr of obj1 and obj2 as arguments (if that method is not None)
def sub_comparison(obj1,obj2,translate): return [Difference(f"{obj1.__class__.__name__} > {meth.__name__}",result) for (meth,attr) in translate if (result := meth(getattr(obj1,attr),getattr(obj2,attr))) is not None]
[ "def attr_comparison(obj1,obj2,attrs):\n return [Difference(f\"{obj1.__class__.__name__}.{attr}\",(result1,result2)) for attr in attrs if (result1 := getattr(obj1,attr)) != (result2 := getattr(obj2,attr))]", "def sortByMethodCall(objList, tag):\n # replaces sortByName and sortByQualName\n \n ll = [(getattr(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Postmortem, using a custom debug function if passed
def post_mortem(*args, debug_fn: Optional[Callable] = None, **kwargs) -> None: if debug_fn is None: import pdb debug_fn = pdb.post_mortem debug_fn()
[ "def debugger_step_over():", "def debug():", "def debugTestRunner(post_mortem=None):\n if post_mortem is None:\n post_mortem = pdb.post_mortem\n class DebugTestResult(unittest.TextTestResult):\n def addError(self, test, err):\n # called before tearDown()\n traceback.pri...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Simple forward step with crossentropy loss.
def _cross_entropy_forward_step(batch, model): timers = get_timers() # Get the batch. timers('batch-generator', log_level=2).start() try: batch_ = next(batch) except BaseException: batch_ = batch tokens, types, labels, attention_mask = process_batch(batch_) timers('batch-gen...
[ "def forward_train(self, *args, **kwargs):\n pass", "def forward(self, X, training=False):\n pass", "def forward_pass(self, x, targets=None):\n self.x = x\n self.targets = targets\n \n # Input layer\n out = self.layers[0].forward_pass(x)\n \n # Forward...\n for layer in sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Build a looped dataloader with infinite size.
def _build_infinite_size_dataloader(dataloader): iterator = dataloader.__iter__() while True: try: yield iterator.__next__() except StopIteration: iterator = dataloader.__iter__()
[ "def create_reader_op(self, feed_list):\n reader = fluid.io.DataLoader.from_generator(feed_list=feed_list, \n capacity=256, iterable=True, use_double_buffer=True)\n\n return reader", "def data_gen_infinite(self, batch_sz):\n g = self.data_gen_finite(batch_sz)\n whil...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Construct solver from Caffe solver prototxt file.
def from_caffe_solver_protoxt(cls, caffe_solver_prototxt_file: Path): solver_param = caffe_pb2.SolverParameter() with open(caffe_solver_prototxt_file, 'rt') as f: pb2.text_format.Merge(f.read(), solver_param) dictionary = {'lr_policy': solver_param.lr_policy, 'b...
[ "def from_file(self, file_path):\n clauses = []\n varnum = 0\n with open(file_path, 'r') as file:\n for line in file:\n if line.startswith(\"c\"):\n continue\n if line.startswith(\"p\"):\n tmp = line.split()\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Refreshes the Job's details by querying the workspace.
def refresh(self): self.details = self.workspace.get_job(self.id).details
[ "def refresh(self): # noqa\n data = self.connection.hgetall(self.key)\n if not data:\n raise NoSuchJobError('No such job: {0}'.format(self.key))\n self.restore(data)", "def _reload(self):\n pr = Project(path=self._job_project_path)\n self._job = pr.load(self._job_nam...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a unique id for a new job.
def create_job_id() -> str: return str(uuid.uuid1())
[ "def assign_job_id(self):\n num_string = str(randint(0, 10000)).zfill(5)\n job_id = self.jobname + str(num_string) + datetime.today().strftime(\"%Y%m%d\")\n return job_id", "def _generate_job_id():\n # CAIP job id can contains only numbers, letters and underscores.\n unique_tag = str(uu...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Applies post processing to all the outputs in the provided run results. This is a convenience function to avoid the need for manual iteration over the run_results dictionary.
def postprocess(run_results, postprocess_func): G_LOGGER.start(f"Applying post-processing to outputs: {postprocess_func.__name__}") for _, iteration_results in run_results: for index, iter_res in enumerate(iteration_results): iteration_results[index] = postprocess_func(iter_r...
[ "def postprocess(self, results):\n return results", "def process_results(self, results):\n\t\traise NotImplementedError()", "def postprocess_result(self):\n pass", "def process(self, results):\n raise NotImplementedError", "def postprocess_model_results(results, model_data, timings):\n l...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Turns Freshbooks tickets from the past x days into Toggl projects.
def sync(self, no_of_days=1): zd = Zendesk() tg = Toggl() try: self.print("Syncing...") self.print_divider(30) tickets = zd.get_tickets(no_of_days) for ticket in tickets: project_title = self.format_title(ticket.id, ticket.subject) ...
[ "def get_project_tickets(\n jira: Jira,\n project: str,\n insert_blank_tickets: bool = True,\n verbose: bool = True,\n) -> List[JiraTicket]:\n # Offsets for the API\n init = 0\n size = 100\n\n # Store all the API tickets to sort through later. Keys for this are\n # ticket number. Values a...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Starts interactive time tracking session. Updates Freshbooks based on Toggl entries.
def time_tracking(self): fb = FreshBooks() tg = Toggl() self.print_splash() self.print("Tip: You can always enter 'skip' when you want to skip a time entry.", format='warn') days = self.get_interactive_days() # number of days to go back self.print("OK, I'll run you throu...
[ "def setTrackStartTime() :\n s.startTrack()", "def start():\n start_tracking()", "def main():\n\n # Step 0:\n # Print lovley greetings.\n print(\"\"\"\n ------\n > Welcome to Værmelder!\n > Store your room climate into your OneDrive!\n ------\"\"\")\n\n # Step 1.\n # Get access ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Starts interactive search, allows user to make a selection. Accepts array of strings and optional (user) query. Returns string chosen by user.
def interactive_search(self, choices, query=None): if query: match = self.get_interactive_match(choices, query) if match: self.print("Matched query to '%s'." % (match)) answer = input("Is that correct? (Y/n) ") self.clear_lines(1) ...
[ "def launch_search(self):\n \n # gets the active selections from pymol\n active_selections = cmd.get_names('selections', 1)\n if len(active_selections) == 0:\n cmd.get_wizard().set_status('no selection')\n else:\n\n selection = active_selections[0]\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns string that best matches query out of a list of choices. Prompts user if unsure about best match.
def get_interactive_match(self, choices, query): if query in self.SKIP_KEYWORDS: return None results = process.extract(query, choices, limit=10) # fuzzy string matching best_match = results[0] second_best_match = results[1] if best_match[1] == second_best_match[1] or...
[ "def interactive_search(self, choices, query=None):\n if query:\n match = self.get_interactive_match(choices, query)\n if match:\n self.print(\"Matched query to '%s'.\" % (match))\n answer = input(\"Is that correct? (Y/n) \")\n self.clear_lin...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Asks an user how many days to go back. Returns int.
def get_interactive_days(self): answer = input("Press return to get entries of past day or input number of days to go back in time: ") if answer == '': days = 1 else: try: days = int(answer) except: print("You didn't enter a num...
[ "def guessDown(self):\n self.guesses = self.guesses - 1", "def days_back(i):\n yesterday = (datetime.now() - timedelta(i))\n return yesterday.strftime('%Y-%m-%d')", "def remaining_days(requested_on: datetime.datetime, slo_limit: int) -> int:\n # Positive: There are days remaining.\n # Zer...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Hacky way to check if this function already made a Toggl project based on a Zendesk ticket ID.
def already_created(self, ticket_id, toggl_projects): project_prepends = [p['name'].split()[0][1:] for p in toggl_projects] if str(ticket_id) in project_prepends: return True return False
[ "async def check_if_is_ticket(ctx):\n channel : TextChannel = ctx.channel\n return 'ticket-' in channel.name", "def has_project(cls, win_id):\r\n\r\n project = cls.get_project(win_id)\r\n return True if project is not None else False", "def project_exists(response, project):\n if ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Formats id and subject into a suitable (Freshbooks) title.
def format_title(self, ticket_id, subject): # TODO: strip block tags? title = "#%i %s" % (ticket_id, subject) return title.strip()
[ "def get_subject_name(id):\n if id < 10:\n return 'sub-00{}'.format(id)\n elif id < 100:\n return 'sub-0{}'.format(id)\n else:\n return 'sub-{}'.format(id)", "def BuildSubjectTitle(self):\n return u\"hunt %s\" % self.args.subject_urn.Basename()", "def get_title_by_id(id):\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Formats Toggl project name and description into (Freshbooks) description.
def format_description(self, project_name, description): description = description if description else '' return "%s %s" % (project_name, '- ' + description)
[ "def parse_project_file(self, project_file):\n project_name = None\n lines = []\n with open(project_file, \"rt\") as f:\n for line in f:\n # Finding the project name\n if \"Short Project Name\" in line:\n project_name = line.split(\":\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Merges toggle time entries with same project name. Sums duration if billable.
def merge_toggl_time_entries(self, time_entries): tg = Toggl() d = {} for entry in time_entries: if entry.get('billable'): if entry.get('tags') and tg.BOOKED_TAG in entry['tags']: status = 'booked' else: status =...
[ "def work_timing_merge(self):\n work = self.work_timing()\n work[-2].merge(work[-1])\n work.pop()\n self.set_work_timing(work)", "def _task_data(self):\n output = {\n 'all': [],\n 'open': [],\n 'open_hours': 0,\n 'done': [],\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }