query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
field Field returns optimal move
def _find_optimal_impl(self, field, depth, is_r, alpha, beta): # Try to evaluate the field right now if field.is_terminal(): final_value = self.eval_field(field, depth, is_r) return Move(final_value, 0, 0) self.unrolled += 1 # copy = field.copy() value =...
[ "def potential_field_path_planning(self):\r\n x = 0\r\n y = 1\r\n z = 2\r\n self.potential_field_sweep_steps = 0\r\n if np.linalg.norm(self.goal-self.position) < self.min_goal_distance: # objective has been found (inside the same cell of the drone)\r\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Decorator for a custom writer, but a default reader
def _writer(func): name = func.__name__ return property(fget=lambda self: getattr(self, '_%s' % name), fset=func)
[ "def get_writer(fn, samples):\n if is_bed(fn):\n return BedWriter(fn, samples)\n elif is_vcf(fn):\n return VcfWriter(fn, samples)\n else:\n raise ValueError(\"Could not get reader for %s\" % fn)", "async def reader_writer():\n return (mock.Mock(readline=readline), None)", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Encodes a certificate into PEM format
def pem_armor_certificate(certificate): return asymmetric.dump_certificate(certificate)
[ "def encode_certificate(self, cert):\n return cert.public_bytes(\n serialization.Encoding.PEM,\n ).decode(encoding='UTF-8')", "def _serialize_cert(cert: x509.Certificate) -> bytes:\n return cert.public_bytes(serialization.Encoding.PEM)", "def cert_to_pem(cert):\n return cert.publi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
An asn1crypto.x509.Certificate object of the issuer. Used to populate both the issuer field, but also the authority key identifier extension.
def issuer(self, value): is_oscrypto = isinstance(value, asymmetric.Certificate) if not isinstance(value, x509.Certificate) and not is_oscrypto: raise TypeError(_pretty_message( ''' issuer must be an instance of asn1crypto.x509.Certificate or ...
[ "def issuer_cert(self, value):\n\n is_oscrypto = isinstance(value, asymmetric.Certificate)\n if not is_oscrypto and not isinstance(value, x509.Certificate):\n raise TypeError(_pretty_message(\n '''\n issuer must be an instance of asn1crypto.x509.Certificate or\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
An asn1crypto.keys.PublicKeyInfo or oscrypto.asymmetric.PublicKey object of the subject's public key.
def subject_public_key(self, value): is_oscrypto = isinstance(value, asymmetric.PublicKey) if not isinstance(value, keys.PublicKeyInfo) and not is_oscrypto: raise TypeError(_pretty_message( ''' subject_public_key must be an instance of asn1cry...
[ "def get_pubkey(self):\n return self._csr['certificationRequestInfo']['subjectPublicKeyInfo']", "def get_public_key_in_pem(self):\n serialized_public = self.public_key_obj.public_bytes(\n encoding=serialization.Encoding.PEM,\n format=serialization.PublicFormat.SubjectPublicKeyI...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A list of unicode strings the domains in the subject alt name extension.
def subject_alt_domains(self): return self._get_subject_alt('dns_name')
[ "def subject_alt_names(self):\n try:\n return self.asn1.subject_alt_name_value.native\n except Exception:\n return []", "def list_domain_names():\n pass", "def subject_alt_emails(self):\n\n return self._get_subject_alt('rfc822_name')", "def _get_subject_alt(self, ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A list of unicode strings the email addresses in the subject alt name extension.
def subject_alt_emails(self): return self._get_subject_alt('rfc822_name')
[ "def subject_alt_names(self):\n try:\n return self.asn1.subject_alt_name_value.native\n except Exception:\n return []", "def subject_alt_names_str(self):\n return \", \".join(self.subject_alt_names)", "def _get_subject_alt(self, name):\n\n if self._subject_alt_n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A list of unicode strings the IPs in the subject alt name extension.
def subject_alt_ips(self): return self._get_subject_alt('ip_address')
[ "def subject_alt_names(self):\n try:\n return self.asn1.subject_alt_name_value.native\n except Exception:\n return []", "def subject_alt_domains(self):\n\n return self._get_subject_alt('dns_name')", "def subject_alt_emails(self):\n\n return self._get_subject_alt...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A list of unicode strings the URIs in the subject alt name extension.
def subject_alt_uris(self): return self._get_subject_alt('uniform_resource_identifier')
[ "def subject_alt_names(self):\n try:\n return self.asn1.subject_alt_name_value.native\n except Exception:\n return []", "def subject_alt_emails(self):\n\n return self._get_subject_alt('rfc822_name')", "def subject_alt_names_str(self):\n return \", \".join(self.s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the native value for each value in the subject alt name extension that is an asn1crypto.x509.GeneralName of the type specified by the name param.
def _get_subject_alt(self, name): if self._subject_alt_name is None: return [] output = [] for general_name in self._subject_alt_name: if general_name.name == name: output.append(general_name.native) return output
[ "def subject_alt_names(self):\n try:\n return self.asn1.subject_alt_name_value.native\n except Exception:\n return []", "def _set_subject_alt(self, name, values):\n\n if self._subject_alt_name is not None:\n filtered_general_names = []\n for general...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Replaces all existing asn1crypto.x509.GeneralName objects of the choice represented by the name param with the values.
def _set_subject_alt(self, name, values): if self._subject_alt_name is not None: filtered_general_names = [] for general_name in self._subject_alt_name: if general_name.name != name: filtered_general_names.append(general_name) self._subjec...
[ "def convert_x509_name(name):\n types = {\n 'country_name': 'C',\n 'state_or_province_name': 'ST',\n 'locality_name': 'L',\n 'organization_name': 'O',\n 'organizational_unit_name': 'OU',\n 'common_name': 'CN',\n 'email_address': 'emailAddress'\n }\n\n return...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
A set of unicode strings the allowed usage of the key from the extended key usage extension.
def extended_key_usage(self): if self._extended_key_usage is None: return set() return set(self._extended_key_usage.native)
[ "def extract_key_usage(self, ext):\n res = []\n fields = KU_FIELDS[:]\n\n # \"error-on-access\", real funny\n if not ext.key_agreement:\n fields.remove('encipher_only')\n fields.remove('decipher_only')\n\n for k in fields:\n val = getattr(ext, k, F...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Location of the delta CRL for the certificate. Will be one of the
def delta_crl_url(self): if self._freshest_crl is None: return None return self._get_crl_url(self._freshest_crl)
[ "def delta_crl_distribution_points(self):\n\n if self._delta_crl_distribution_points is None:\n self._delta_crl_distribution_points = []\n\n if self.freshest_crl_value is not None:\n for distribution_point in self.freshest_crl_value:\n distribution_poin...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Grabs the first URL out of a asn1crypto.x509.CRLDistributionPoints object
def _get_crl_url(self, distribution_points): if distribution_points is None: return None for distribution_point in distribution_points: name = distribution_point['distribution_point'] if name.name == 'full_name' and name.chosen[0].name == 'uniform_resource_identifie...
[ "def _make_crl_distribution_points(self, name, value):\n\n if value is None:\n return None\n\n is_tuple = isinstance(value, tuple)\n if not is_tuple and not isinstance(value, str_cls):\n raise TypeError(_pretty_message(\n '''\n %s must be a un...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Constructs an asn1crypto.x509.CRLDistributionPoints object
def _make_crl_distribution_points(self, name, value): if value is None: return None is_tuple = isinstance(value, tuple) if not is_tuple and not isinstance(value, str_cls): raise TypeError(_pretty_message( ''' %s must be a unicode string o...
[ "def delta_crl_distribution_points(self):\n\n if self._delta_crl_distribution_points is None:\n self._delta_crl_distribution_points = []\n\n if self.freshest_crl_value is not None:\n for distribution_point in self.freshest_crl_value:\n distribution_poin...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Location of the OCSP responder for this certificate. Will be one of the
def ocsp_url(self): if self._authority_information_access is None: return None for ad in self._authority_information_access: if ad['access_method'].native == 'ocsp' and ad['access_location'].name == 'uniform_resource_identifier': return ad['access_location'].cho...
[ "def ocsp_responder_uri(self):\n return self._ocsp_responder_uri", "def determine_ocsp_server(self, cert_path):\n try:\n url, _err = util.run_script(\n [\"openssl\", \"x509\", \"-in\", cert_path, \"-noout\", \"-ocsp_uri\"],\n log=logger.debug)\n except...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the value for an extension using a fully constructed asn1crypto.core.Asn1Value object. Normally this should not be needed, and the convenience attributes should be sufficient. See the definition of asn1crypto.x509.Extension to determine the appropriate object type for a given extension. Extensions are marked as cr...
def set_extension(self, name, value, allow_deprecated=False): extension = x509.Extension({ 'extn_id': name }) # We use native here to convert OIDs to meaningful names name = extension['extn_id'].native if name in self._deprecated_extensions and not allow_deprecated:...
[ "def __init__(self, value=None):\n super(ExtensionType, self).__init__(value, Tags.EXTENSION_TYPE)", "def new_extension(name, value, critical=0, _pyfree=1):\n if name == 'subjectKeyIdentifier' and \\\n value.strip('0123456789abcdefABCDEF:') is not '':\n raise ValueError('value must be prec...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Preemphasis or Deemphasis of higher frequencies given a batch of signal. 对一批信号进行高频预加重或去加重
def emphasis(signal_batch, emph_coeff=0.95, pre=True): result = np.zeros(signal_batch.shape) for sample_idx, sample in enumerate(signal_batch): for ch, channel_data in enumerate(sample): if pre: result[sample_idx][ch] = np.append(channel_data[0], channel_data[1:] - emph_coeff...
[ "def amplifyhighfreq(lpyramid, l0_factor=1.2, l1_factor=1.1):\n\n #\n # You code here\n lpyramid_amp = deepcopy(lpyramid)\n lpyramid_amp[0] = lpyramid_amp[0] * l0_factor\n lpyramid_amp[1] = lpyramid_amp[1] * l1_factor\n\n return lpyramid_amp\n #", "def increaseFreq(self, desHz):\n from...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Helper function for slicing the audio file by window size and sample rate with [1stride] percent overlap (default 50%).
def slice_signal(file, window_size, stride, sample_rate): wav, sr = librosa.load(file, sr=sample_rate) hop = int(window_size * stride) slices = [] for end_idx in range(window_size, len(wav), hop): start_idx = end_idx - window_size slice_sig = wav[start_idx:end_idx] #print(type(sl...
[ "def read_and_slice1d(wavfilename, window_size, minlength, stride=0.5):\n fs, signal = wavfile.read(wavfilename)\n if fs != 16000:\n raise ValueError('Sampling rate is expected to be 16kHz!')\n sliced = slice_1dsignal(signal, window_size, minlength, stride=stride)\n return sliced", "def slice_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Helper function to make calls to Airtable REST API.
def airtable_api(base, table, token, action = '', parameters = {}, method = 'get', data = {}): headers = { 'Content-type': 'application/json', 'Accept-Encoding': 'gzip', 'Authorization': 'Bearer %s' % token } url = "https://api.airtable.com/v0/%s/%s/%s" % (base, table, action) i...
[ "def call_api(airport,startTime,endTime):\n time.sleep(10)\n URL = f\"https://opensky-network.org/api/flights/departure?airport={airport}&begin={startTime}&end={endTime}\"\n logging.info(f\"URL is now: {URL}\")\n r = requests.get(URL, auth=(username, password))\n if r.status_code == 404:\n log...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tokenize data file and turn into tokenids using given vocabulary file. This function loads data linebyline from data_path, calls the above sentence_to_token_ids, and saves the result to target_path. See comment for sentence_to_token_ids on the details of tokenids format.
def data_to_token_ids(data_path, target_path, vocabulary_path, tokenizer=None, normalize_digits=True): if not gfile.Exists(target_path): print("Tokenizing data in %s" % data_path) vocab, _ = data_utils.initialize_vocabulary(vocabulary_path) with gfile.GFile(data_path, m...
[ "def data_to_token_ids(data_path, target_path, vocabulary_path):\n if not gfile.Exists(target_path):\n print(\"Tokenizing data in %s\" % data_path)\n vocab, _ = initialize_vocabulary(vocabulary_path)\n with gfile.GFile(data_path, mode=\"rb\") as data_file:\n with gfile.GFile(targe...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Finds and retrieves sbfdInitiator resources from the server. All named parameters are evaluated on the server using regex. The named parameters can be used to selectively retrieve sbfdInitiator resources from the server. To retrieve an exact match ensure the parameter value starts with ^ and ends with $ By default the ...
def find( self, Count=None, DescriptiveName=None, MplsLabelCount=None, Name=None, SessionInfo=None, ): # type: (int, str, int, str, List[str]) -> SbfdInitiator return self._select(self._map_locals(self._SDM_ATT_MAP, locals()))
[ "def find(resource_name, paths=...):\n ...", "def find_registration_by_params(\n self, iss: str, client_id: str, *args, **kwargs\n ) -> Registration:\n raise NotImplementedError", "def _generic_find(controller, heading, patterns):\n msg.info(heading)\n msg.info(\"----------------------...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add L1feature selection (LASSO) to a classifier
def with_l1_feature_selection(class_T, **kwargs): class FeatureSelect(class_T): def fit(self, X, y): # The smaller C, the stronger the regularization. # The more regularization, the more sparsity. self.transformer_ = class_T(penalty="l1", **kwargs) logger.inf...
[ "def get_lasso_features(df, convergence='complete'):\n df, __ = data_prep_columns(df, 'neither')\n lasso_columns = df.iloc[:, 84:-4].columns\n X_train, X_test, y_train, y_test, holdout, X = model_prep_loc(df, lasso_columns)\n \n log_model = LogisticRegression(penalty='l1', solver='saga', max_iter=100...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Inserts or updates a row in the agdds table.
def add_agdd_row(station_id, source_id, gdd, agdd, year, doy, date, base, missing, tmin, tmax): cursor = mysql_conn.cursor(buffered=True) cursor.execute(search_for_agdd_row, (station_id, source_id, date, base)) if cursor.rowcount < 1: cursor.execute(insert_agdd_row, (station_id, source_id, gdd, ...
[ "def insert_db_row(self, param):\n c = self._conn.cursor()\n c.execute(self.sqladdrow, param)\n self._conn.commit()", "def _upsert(cursor, table, data, pk):\n stamped = table in ('game', 'drive', 'play')\n update_set = ['%s = %s' % (k, '%s') for k, _ in data]\n if stamped:\n u...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieves tmin and tmax data from climate source and computes agdds to be inserted into the agdd table.
def populate_agdds(start_date, end_date, source, source_id, stations): # possibly grab ACIS station data (for entire date range) if source == 'ACIS': station_ids = [] for station in stations: station_ids.append(station['char_network_id']) acis_data = get_acis_climate_da...
[ "def calc_temps(start_date, end_date):\r\n\r\n print(\"two dates\\n\")\r\n return session.query(func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)).\\\r\n filter(Measurement.date >= start_date).filter(Measurement.date <= end_date).all()", "def calc_temps(start_date, en...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Populates the agdds table with urma, acis, and prism temps and agdds for qc purposes.
def populate_agdd_qc(urma_start, urma_end, acis_start, acis_end, prism_start, prism_end): logging.info(' ') logging.info('-----------------beginning climate quality check population-----------------') stations = get_stations() sources = get_sources() acis_source_id = None urma_source_i...
[ "def populate_agdds(start_date, end_date, source, source_id, stations):\r\n # possibly grab ACIS station data (for entire date range)\r\n if source == 'ACIS':\r\n station_ids = []\r\n for station in stations:\r\n station_ids.append(station['char_network_id'])\r\n acis_data = ge...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute the reciprocal rank of a ranked list against some ground truth.
def reciprocal_rank(ranking, references, atk=None): for k, prediction in enumerate(ranking[:atk], 1): if prediction in references: return 1.0 / k return 0.0
[ "def calculate_reciprocal_rank(rank_df, expected_rank_df):\n counter = 0\n for relevant_doc in expected_rank_df['doc_number']:\n if relevant_doc in list(rank_df['doc_number']):\n mask = rank_df['doc_number'] == relevant_doc\n rank = int(rank_df.loc[mask]['rank'])\n if c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute the average precision of a ranked list against some ground truth
def average_precision(ranking, references, atk=None): total, num_correct = 0.0, 0.0 for k, prediction in enumerate(ranking[:atk], 1): if prediction in references: num_correct += 1 total += num_correct / k return total / num_correct if total > 0 else 0.0
[ "def avg_precision(actual=None, predicted=None):\n for (i, p) in enumerate(predicted):\n if actual == p:\n return 1.0 / (i + 1.0)\n return 0.0", "def compute_average_precision(real_gains, predicted_gains):\n precs = [compute_r_precision(real_gains, predicted_gains, k=x+1) for x in range(len(real_gains)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute the mean average precision. Input should be a list of prediction rankings and a list of ground truth rankings.
def mean_average_precision(rankings, references, atk=None): return _mean_score(rankings, references, partial(average_precision, atk=atk))
[ "def compute_average_precision(real_gains, predicted_gains):\n precs = [compute_r_precision(real_gains, predicted_gains, k=x+1) for x in range(len(real_gains))]\n if not precs:\n return 0.\n return np.mean(precs)", "def avg_precision(actual=None, predicted=None):\n for (i, p) in enumerate(predicted):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return the margin, or absolute difference between the highest irrelevant item and the lowest relevant one.
def margin(ranking, references): lowest_relevant, highest_irrelevant = 0, 0 for k, prediction in enumerate(ranking, 1): if prediction not in references and highest_irrelevant is 0: highest_irrelevant = k if prediction in references and k > lowest_relevant: lowest_relevant...
[ "def get_margin(self):\r\n return self.target - sum(self.cards)", "def available_margin(self) -> float:\n return self.position.exchange.available_margin", "def score_margin(self):\n if self.previous_event is None:\n score = self.score\n else:\n score = self.prev...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Completes the bird's active ride.
def CompleteRide(self,endTime,endX,endY): ride = self.currRide ride.EndRide(endX,endY,endTime) self.totalDistance+=ride.GetDistance() self.totalDuration+=ride.GetDuration() self.rides.append(ride) self.currRide = None self.idleTime = endTime self.Calculat...
[ "def complete(self):\n self.completed = 1", "def complete(self):\n self._state = \"COMPLETE\"", "def end_ride(self):\n # TODO\n self.location = self.destination\n self.is_idle = True\n self.destination = None", "def endCompetition(self):\n self.robot_exit = Tru...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Getter for distance from drop point Return
def GetDistanceFromDropPoint(self): return self.distanceFromDropPoint
[ "def get_distance(self): \n return self.from_station.distance_to(self.to_station)", "def getDistance(self):\r\n return self.currentCalib['distance']", "def get_distance(self):\n return _TOF_LIBRARY.getDistance(self._dev)", "def get(cls, approach):\n return approach.dista...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Getter for maximum wait time Return
def GetMaxWaitTime(self): return max(self.waitTimes)
[ "def MaxWaitTime(self):\r\n\t\treturn self._get_attribute('maxWaitTime')", "def max_timeout(self):\n return self._max_timeout", "def max_waiting(self):\n return self._max_waiting", "def max_wait_count(self) -> int:\n return self._config['max_wait_count']", "def max_queue_wait(self) -> O...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Getter for total Duration Return
def GetTotalDuration(self): return self.totalDuration
[ "def duration(self):\n return self._duration", "def get_duration(self):\n duration = 0\n\n for entry in self.entries:\n duration += entry.get_duration()\n return duration", "def get_duration(self, obj):\n return obj.duration.total_seconds()", "def getDuration(self...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns all options of the strip characters in required length
def bruteforce(strip, min_length, max_length): return (''.join(char) for char in chain.from_iterable(product(strip, repeat=x) for x in range(min_length, max_length+1)))
[ "def lstrip(self, chars=None):\n return asarray(lstrip(self, chars))", "def lstrip(self, chars=None): # real signature unknown; restored from __doc__\n return \"\"", "def length(self):\n # because combining characters may return -1, \"clip\" their length to 0.\n clip = functools.part...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function updates knownfaces dynamo table with the data derived from Slack and AWS Rekognition
def update_dynamo(username, userid, match_percentage, image_id, url, \ age, gender, smile, beard, happy, sad, angry): put_into_dynamo = RekognitionKnown( user_name = username, slack_user_id = userid, match_percentage = match_percentage, image_id = image_id, image_url = ur...
[ "def update_fruit(email):\n result = {}\n machine = get_machine_on_email(email)\n table = dynamodb.Table('fruit-img')\n response = table.scan(FilterExpression=Attr('machine').eq(machine))\n for i in response['Items']:\n fruit_name = i['fruit_name']\n if fruit_name != 'NOT':\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function updates unknownfaces dynamo table with the data derived AWS Rekognition
def update_unknown_dynamo(url, age, gender, \ smile, beard, happy, sad, angry): put_into_unknown_dynamo = RekognitionUnknown( image_url = url, age_range = age, gender = gender, is_smiling = smile, has_beard = beard, is_happy = happy, is_sad = sad, ...
[ "def _update_table(self, table_name, RCU, WCU):\n print(\"Updating table with name {}\".format(table_name))\n try:\n dynamodb.update_table(\n TableName = table_name,\n ProvidionedThroughput = {\n 'ReadCapacityUnits': RCU,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a default LabelStoreConfig to fill in any missing ones.
def get_default_label_store(self, scene: SceneConfig) -> LabelStoreConfig: raise NotImplementedError()
[ "def register_default_store(self, type_, **config):\n self.register_store(\"default\", type_, **config)", "def _default_config(cls):\n return dict()", "def get_default_config(self, ext_name):\n real_name, alias_config = self.resolve_alias(ext_name)\n base_default_config = self.get_ex...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a default EvaluatorConfig to use if one isn't set.
def get_default_evaluator(self) -> EvaluatorConfig: raise NotImplementedError()
[ "def get_default_config(self):\n return self._invoke('get_default_config')", "def get_default_config():\n # pylint: disable=cyclic-import\n from raylab.agents.sac import DEFAULT_CONFIG\n\n return DEFAULT_CONFIG", "def get_default(cls):\n if cls._default is None:\n c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Visualization routine for generating a calendar visualization with Bokeh.
def _bokeh_visualization( calendar: "Calendar", n_years: int, relative_dates: bool, add_yticklabels: bool = True, **kwargs, ) -> plotting.figure: if add_yticklabels: tooltips = [ ("Interval", "@desc"), ("Size", "@width_days days"), ("Type", "@type"), ...
[ "def calendar_plot(data, field=\"ret\"):\n from math import pi\n from bokeh.models import (\n LinearColorMapper,\n BasicTicker,\n PrintfTickFormatter,\n ColorBar,\n )\n from bokeh.plotting import figure\n from bokeh.palettes import Spectral\n\n df = data.copy()\n # T...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Registers a global stack transformation that merges a set of tags with whatever was also explicitly added to the resource definition.
def register_auto_tags(auto_tags: Mapping[str, str]) -> None: pulumi.runtime.register_stack_transformation(lambda args: auto_tag(args, auto_tags))
[ "def add_tags(event):\n\n add_tags_from_presets()", "def _build_stack_tags(self, stack):\n return [\n {'Key': t[0], 'Value': t[1]} for t in self.context.tags.items()]", "def add_ptransform(self, ptransform_class, tags):\n # Many tags can refer to the same ptransform_class, but each\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns true if the given resource type is an AWS resource that supports tags.
def is_taggable(t: str) -> bool: return t in taggable_resource_types
[ "def supports(self, resource, resourceType = None):\n pass;", "def is_tag_and_type(xml_obj, tag, type):\n\treturn xml_obj.tag == tag and xml_utils.get_attrib_if_exists(xml_obj,\"Type\") == type", "def has_tags(self):\n return bool(self.tags)", "def is_tag_available(self, tag):\n return ta...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
add a file full of user agents to use The loading of more than one user agent implies the use of random user agents.
def add_user_agent(self, useragent_path): with open(useragent_path) as wordlist_f: for useragent in wordlist_f.read().split("\n"): useragent = useragent.strip() if useragent: self.user_agents.append(useragent)
[ "def get_user_agents(self, file_name):\n with open(file_name) as f:\n self.user_agents = json.load(f)\n self.headers[\"User-Agent\"] = random.choice(self.user_agents)", "def add_user_agent(self, value):\n # type: (str) -> None\n self.user_agent_policy.add_user_agent(value)",...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Run a full attack on the domain with which we have been configured. Brute force a directory and file structure based on the wordlists with which we have been configured.
def brute(self, follow_redirects, max_depth, method="GET"): """TODO option to make max_depth be obeyed relative to the last successful dir? ie: with max_depth 3, example.com/fail/fail/fail fails out but once we hit example.com/fail/success/, keep going until we hit exam...
[ "def runAttacks(self,\n policy: Policy,\n outputDir: str=None):\n outputDir = policy.getOutputDir(parent=outputDir) if \\\n policy else outputDir\n\n acCache = AccessListCache.get()\n acListInst = acCache.getAccessListFromPolicy(policy)\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
String for representing the Organization object (in Admin site etc.).
def __str__(self): if self.name != None and self.name != '': return self.name else: return "Organization object owned by %s."%(self.owner)
[ "def obj2org(self, obj):\n return obj.organization", "def organization_name(self) -> str:\n return pulumi.get(self, \"organization_name\")", "def organization_name(self):\n if self.organization is not None:\n return self.organization.name\n\n return ''", "def org_urn(sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Yields counts of character ngrams from string s of order n.
def extract_char_ngrams(self, s: str, n: int) -> Counter: return Counter([s[i:i + n] for i in range(len(s) - n + 1)])
[ "def count_ngrams(seq, n):\n if seq == '':\n seq = ' '\n if isinstance(n, int):\n n = [n]\n ngrams = list()\n for i in n:\n ngrams.extend([seq[j:j+i] for j in range(len(seq) - (i-1))])\n counts = {g: (seq.count(g)) for g in set(ngrams)}\n counts = collections.OrderedDict(sorte...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Yields counts of character ngrams from string s of order n.
def extract_char_ngrams(self, s: str, n: int) -> Counter: return Counter([s[i:i + n] for i in range(len(s) - n + 1)])
[ "def count_ngrams(seq, n):\n if seq == '':\n seq = ' '\n if isinstance(n, int):\n n = [n]\n ngrams = list()\n for i in n:\n ngrams.extend([seq[j:j+i] for j in range(len(seq) - (i-1))])\n counts = {g: (seq.count(g)) for g in set(ngrams)}\n counts = collections.OrderedDict(sorte...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Apply Gaussian noise to an input tensor.
def gaussian_noise(tensor, mean, stddev): noise = Variable(tensor.data.new(tensor.size()).normal_(mean, std)) return tensor + noise
[ "def task_gaussian_noise(input_array, noise_factor):\n return(np.random.normal(0, noise_factor, input_array.shape))", "def add_gaussian_noise(X, mu=0, sigma=0.1):\n noise = np.random.normal(0.0, sigma, size=X.size)\n return X + noise.reshape(X.shape)", "def gaussian_noise(X, std=1.0):\n return tf.ad...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a `canon` option to `f` which toggles canonicalizes the return value of `f`.
def canon(f): @wraps(f) def wrapped(G, H, canon=True): game = f(G, H) if canon: game = canonicalize(game) return game return wrapped
[ "def canonical_form(G, specify=True):\n cG = canonical(G)\n\n return make_specific(cG) if specify else cG", "def test_canonify_value_when_attribute_exists():\n assert 'True' == issue.canonify_value(canonify(), 'value')", "def main():\n parser = argparse.ArgumentParser(description=(\n 'Canonic...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fast calculation of the last digit for nth fibonacci number
def get_fibonacci_last_digit_fast(n): fibonacci = [0 for i in range(n + 1)] fibonacci[1] = 1 for i in range(2, n + 1): fibonacci[i] = (fibonacci[i - 1] + fibonacci[i - 2]) % 10 return fibonacci[n]
[ "def last_digit_fib(n):\n\tif n == 0: \n\t\treturn 0\n\tif n == 1: \n\t\treturn 1\n\telse: \n\t\tF = (n+1)*[0]\n\t\tF[0] = 0\n\t\tF[1] = 1\n\t\tfor i in range(2,n+1): \n\t\t\tF[i] = (F[i-1] + F[i-2]) % 10 \n\t\t\tF.append(F[i])\n\t\treturn F[-1]", "def fibonacci(n):\n seq = fib_sequence(n)\n number = seq[-1...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
find any sub dict contains pattern to list
def find_dict_to_list(target, pattern): result = [] if isinstance(target, dict): for k, v in target.items(): if k == pattern: result.append(v) if isinstance(v, dict) or isinstance(v, list): result.extend(find_dict_to_list(v, pattern)) if isinst...
[ "def find_all(list_of_dict, match_function):\n\treturn [entry for entry in list_of_dict if match_function(entry)]", "def multifilter(names, patterns):\n for name in names:\n if isinstance(name, collections.Mapping):\n for key in name.iterkeys():\n for pattern in patterns:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Perform random search on hyper parameters list, saves models and validation accuracies.
def run_random_search(X, y, params, no_of_searches=1): val_accs_list = [] for i in range(no_of_searches): # Creating a tuple for each iteration of random search with selected parameters params_dict = {"iteration": i + 1, "no_of_filters": rd.choice(params["no_of_filters"]...
[ "def random_search(model, random_hyperparams, model_fname, **score_kwds):\n experiments = []\n N = len(random_hyperparams.values()[0])\n best_score = -1.0\n best_params = {}\n for i in range(N):\n random_hyperparam = {k:v[i] for k,v in random_hyperparams.items()}\n model.set_params(**ra...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Open the given filepath as new document
def open_document(filepath, show=True): k = krita.Krita.instance() print('Debug: opening %s' % filepath) doc = k.openDocument(filepath) if show: Application.activeWindow().addView(doc) return doc
[ "def OpenFile(self,path):\n\t\tself.acad.Documents.Open(path)", "def open( self, filename ):\r\n #http://www.oooforum.org/forum/viewtopic.phtml?t=35344\r\n properties = []\r\n properties.append( OpenOfficeDocument._makeProperty( 'Hidden', True ) ) \r\n properties = tuple( properties )\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return layers for given document
def get_layers(doc): nodes = [] root = doc.rootNode() for node in root.childNodes(): print('Debug: found node of type %s: %s' % (node.type(), node.name())) if node.type() == "paintlayer": nodes.append(node) return nodes
[ "def layers(self):\n return self['layers']", "def layers(self):\r\n return self._flc.layers", "def get_layers(self):\n layers = set()\n for element in self.elements:\n if isinstance(element, PolygonSet):\n layers.update(element.layers)\n elif isin...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
r"""Linear Buckling Analysis It can also be used for more general eigenvalue analyzes if `K` is the tangent stiffness matrix of a given load state.
def lb(K, KG, tol=0, sparse_solver=True, silent=False, num_eigvalues=25, num_eigvalues_print=5): msg('Running linear buckling analysis...', silent=silent) msg('Eigenvalue solver... ', level=2, silent=silent) k = min(num_eigvalues, KG.shape[0]-2) if sparse_solver: mode = 'cayley' ...
[ "def elbo(\n self,\n llk: Optional[Dict[str, tf.Tensor]] = {},\n kl: Optional[Dict[str, tf.Tensor]] = {},\n ) -> tf.Tensor:\n # sum all the components log-likelihood and KL-divergence\n llk_sum = tf.constant(0., dtype=self.dtype)\n kl_sum = tf.constant(0., dtype=self.dtype)\n for x in ll...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests that the shape exceptions are not raised.
def test_blend_exception_not_raised(self, *shapes): self.assert_exception_is_not_raised(linear_blend_skinning.blend, shapes)
[ "def test_loss_not_raised(self, *shapes):\n self.assert_exception_is_not_raised(matting.loss, shapes)", "def test_face_normals_exception_not_raised(self, shapes, dtypes):\n self.assert_exception_is_not_raised(normals.face_normals, shapes, dtypes)", "def test_assert_exception_is_not_raised_raises_exception...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test the Jacobian of the blend function.
def test_blend_jacobian_random(self): (x_points_init, x_weights_init, x_rotations_init, x_translations_init) = test_helpers.generate_random_test_lbs_blend() self.assert_jacobian_is_correct_fn( linear_blend_skinning.blend, [x_points_init, x_weights_init, x_rotations_init, x_translations_ini...
[ "def test_gradable_funcs(self):\n self.jit_grad_wrap(self.basic_lindblad.evaluate_rhs)(\n 1.0, Array(np.array([[0.2, 0.4], [0.6, 0.8]]))\n )\n\n self.basic_lindblad.rotating_frame = Array(np.array([[3j, 2j], [2j, 0]]))\n\n self.jit_grad_wrap(self.basic_lindblad.evaluate_rhs)(\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Module fixture for the IrisDataset class
def iris(): return IrisDataset()
[ "def test_get_iris_setosa_data(self):\n iris = get_iris_setosa_data()\n self.assertEqual(len(iris.data), 150)\n self.assertEqual(len(iris.labels), 150)", "def __init__(self, dataset):\n self._dataset = dataset", "def test_datasets(ds_cls: type[VisionDataset]) -> None:\n transform ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that the dataset exposes features correctly
def test_features(iris): assert iris.num_features == 4 assert iris.feature_names == [ "sepal length (cm)", "sepal width (cm)", "petal length (cm)", "petal width (cm)", ]
[ "def test_all_features_with_data(self):\n feature1 = Feature('looktest1')\n feature1.set_percentage(5)\n\n feature2 = Feature('looktest2')\n feature2.activate()\n feature2.add_to_whitelist(3)\n\n feature3 = Feature('looktest3')\n feature3.activate()\n feature3...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that the dataset exposes targets correctly
def test_targets(iris): assert iris.num_targets == 3 np.testing.assert_array_equal( iris.target_names, ["setosa", "versicolor", "virginica"] )
[ "def test_which_targets():\n num_multi_targets = 0\n for which_targets_day in which_targets:\n # All inputs have a label\n assert np.all(which_targets_day.sum(axis=1) > 0)\n # No inputs have more than 3 targets\n assert np.all(which_targets_day.sum(axis=1) < 4)\n\n num_multi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test that the setting of feature values works as expected
def test_feature_values(iris, name, x_feature, y_feature, x_vals, y_vals): iris.x_feature = x_feature iris.y_feature = y_feature assert iris.title == "{} x {}".format(x_feature, y_feature) data = iris.sources[name].data np.testing.assert_array_almost_equal(data["x"][:2], x_vals) np.testing.asser...
[ "def test_feature_values(boston, x_feature, y_feature, x_vals, y_vals):\n boston.x_feature = x_feature\n boston.y_feature = y_feature\n assert boston.title == \"{} x {}\".format(x_feature, y_feature)\n data = boston.source.data\n np.testing.assert_array_almost_equal(data[\"x\"][:2], x_vals)\n np.t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find the user with the given foreign_id and return their id, or None if no such user exists.
def find_user_by_foreign_id(db, foreign_id): users = db.tables.users return db.load_scalar( table=users, value={'foreign_id': foreign_id}, column='id')
[ "def _get_user_by_id(self, _id):\n user_resp = self._db.Users(database_pb2.UsersRequest(\n request_type=database_pb2.UsersRequest.FIND,\n match=database_pb2.UsersEntry(global_id=_id)))\n if user_resp.result_type != database_pb2.UsersResponse.OK:\n self._logger.warning(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test for graph thresholding based on the mean degree.
def test_graphs_threshold_mean_degree(): # Groundtruth expected = np.load("groundtruth/graphs_threshold/mean_degree.npy") # Data graph = np.load("sample_data/graphs_threshold/graph.npy") # Run mean_degree_threshold = 5 binary_mask = threshold_mean_degree(graph, mean_degree_threshold) ...
[ "def test_graphs_threshold_mst_mean_degree():\n\n # Groundtruth\n expected = np.load(\"groundtruth/graphs_threshold/mst_mean_degree.npy\")\n\n # Data\n graph = np.load(\"sample_data/graphs_threshold/graph.npy\")\n\n # Run\n tree = threshold_mst_mean_degree(graph, 3.6)\n\n # Test\n np.testing...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test for graph thresholding based in the MST's mean degree.
def test_graphs_threshold_mst_mean_degree(): # Groundtruth expected = np.load("groundtruth/graphs_threshold/mst_mean_degree.npy") # Data graph = np.load("sample_data/graphs_threshold/graph.npy") # Run tree = threshold_mst_mean_degree(graph, 3.6) # Test np.testing.assert_array_equal(e...
[ "def test_graphs_threshold_mean_degree():\n\n # Groundtruth\n expected = np.load(\"groundtruth/graphs_threshold/mean_degree.npy\")\n\n # Data\n graph = np.load(\"sample_data/graphs_threshold/graph.npy\")\n\n # Run\n mean_degree_threshold = 5\n binary_mask = threshold_mean_degree(graph, mean_deg...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test the kcore decomposition algorithm.
def test_graphs_k_core_decomposition(): # Groundtruth expected = np.load("groundtruth/graphs_threshold/k_cores.npy") # Data graph = np.load("sample_data/graphs_threshold/graph_binary.npy") # Run kcores = k_core_decomposition(graph, 10) # Test np.testing.assert_array_equal(expected, k...
[ "def test_determine_k(self):\n test_dir_name = os.path.dirname(__file__)\n feat_array_fn = os.path.join(\n test_dir_name, \"data\", \"four_clusters.csv\")\n df = pd.read_csv(feat_array_fn)\n feat_array = df[[\"x\", \"y\"]].values\n\n clusterer = Clusterer(feat_array_fn,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test for graph thresholding base on shortest paths.
def test_graphs_threshold_shortest_paths(): # Groundtruth expected = np.load("groundtruth/graphs_threshold/shortest_paths.npy") # Data graph = np.load("sample_data/graphs_threshold/graph.npy") # Run binary_mask = threshold_shortest_paths(graph, treatment=False) # Test np.testing.asse...
[ "def _importance_based_graph_cut(self, graph, threshold):\n for node, data in graph.nodes_iter(data=True):\n if float(data['importance']) < threshold:\n graph.remove_node(node)\n return", "def thresh_f(i):\r\n s = len(graph[i])\r\n t = 0\r\n for j in graph[i]:\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test for graph threshlding using global cost efficiency (GCE).
def test_graphs_threshold_global_cost_efficiency(): # Groundtruth expected = np.load("groundtruth/graphs_threshold/gce.npy") # Data graph = np.load("sample_data/graphs_threshold/graph.npy") # Run iterations = 50 binary_mask, _, _, _, _ = threshold_global_cost_efficiency(graph, iterations)...
[ "def test_graphs_threshold_omst_global_cost_efficiency2():\n # the function is optmized at the 3rd OMST, so it is going to yeild the same results\n # as the exhaustive search\n\n # Groundtruth\n expected = np.load(\"groundtruth/graphs_threshold/omst_gce.npy\")\n\n # Data\n graph = np.load(\"sample...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test for graph threshlding using global cost efficiency (GCE) on OMSTs (extract all MSTs).
def test_graphs_threshold_omst_global_cost_efficiency(): # the function is optmized at the 3rd OMST. # Groundtruth expected = np.load("groundtruth/graphs_threshold/omst_gce.npy") # Data graph = np.load("sample_data/graphs_threshold/graph.npy") # Run _, CIJtree, _, _, _, _, _, _ = threshol...
[ "def test_graphs_threshold_omst_global_cost_efficiency2():\n # the function is optmized at the 3rd OMST, so it is going to yeild the same results\n # as the exhaustive search\n\n # Groundtruth\n expected = np.load(\"groundtruth/graphs_threshold/omst_gce.npy\")\n\n # Data\n graph = np.load(\"sample...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test for graph threshlding using global cost efficiency (GCE) on OMSTs (extract the first five MSTs).
def test_graphs_threshold_omst_global_cost_efficiency2(): # the function is optmized at the 3rd OMST, so it is going to yeild the same results # as the exhaustive search # Groundtruth expected = np.load("groundtruth/graphs_threshold/omst_gce.npy") # Data graph = np.load("sample_data/graphs_thr...
[ "def test_graphs_threshold_omst_global_cost_efficiency():\n # the function is optmized at the 3rd OMST.\n\n # Groundtruth\n expected = np.load(\"groundtruth/graphs_threshold/omst_gce.npy\")\n\n # Data\n graph = np.load(\"sample_data/graphs_threshold/graph.npy\")\n\n # Run\n _, CIJtree, _, _, _,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test for graph thresholding based on the economical method.
def test_graphs_threshold_eco(): # Groundtruth expected_filt = np.load("groundtruth/graphs_threshold/eco_filtered.npy") expected_bin = np.load("groundtruth/graphs_threshold/eco_binary.npy") # Data graph = np.load("sample_data/graphs_threshold/graph2.npy") # Run filterted, binary, _ = thre...
[ "def apply_thresholding(x):\n return x > threshold_otsu(x)", "def test_graphs_threshold_global_cost_efficiency():\n\n # Groundtruth\n expected = np.load(\"groundtruth/graphs_threshold/gce.npy\")\n\n # Data\n graph = np.load(\"sample_data/graphs_threshold/graph.npy\")\n\n # Run\n iterations = ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns True if and only if `expr` contains only correctly matched delimiters, else returns False.
def check_delimiters(expr): delim_openers = '{([<' delim_closers = '})]>' ### BEGIN SOLUTION s = Stack() for c in expr: if c in delim_openers: s.push(c) elif c in delim_closers: try: t = s.pop() if delim_openers.fin...
[ "def check_delimiters(expr):\n s = Stack()\n newExpr = expr.replace(\" \", \"\")\n if len(newExpr) ==1:\n return False\n else:\n for c in newExpr:\n if c in delim_openers:\n s.push(c)\n elif c in delim_closers:\n toCheck = delim_openers[d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the postfix form of the infix expression found in `expr`
def infix_to_postfix(expr): # you may find the following precedence dictionary useful prec = {'*': 2, '/': 2, '+': 1, '-': 1} ops = Stack() postfix = [] toks = expr.split() ### BEGIN SOLUTION opp = {'*', '/','+', '-'} for x in toks: if str.isdigit(x): post...
[ "def infix_to_postfix(expr):\n ops = Stack()\n postfix = []\n toks = expr.split()\n def tests(chr):\n if chr.isdigit():\n postfix.append(chr)\n\n elif chr == '(':\n ops.push('(')\n\n elif ops.peek() == '(' or ops.empty():\n ops.push(chr)\n\n e...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determines whether or not a project exists at the specified path
def project_exists(response: 'environ.Response', path: str) -> bool: if os.path.exists(path): return True response.fail( code='PROJECT_NOT_FOUND', message='The project path does not exist', path=path ).console( """ [ERROR]: Unable to open project. The specif...
[ "def does_project_exist(team, project):\n\n project_path = get_project_path(team, project)\n return os.path.isdir(project_path)", "def isproject(path):\r\n\r\n try:\r\n if os.path.basename(path)[0] in (\".\", \"_\"):\r\n return False\r\n if not os.path.isdir(path):\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert phrase to a vector by aggregating it's word embeddings. Just take an average of vectors for all tokens in the phrase with some weights.
def get_phrase_embedding(phrase): vector = np.zeros([model.vector_size], dtype='float32') # 1. lowercase phrase phrase = phrase.lower() # 2. tokenize phrase phrase_tokens = tokenizer.tokenize(phrase) # 3. average word vectors for all words in tokenized phrase, skip ...
[ "def avg_sentence_vector(words, model, num_features, index2word_set):\n featureVec = np.zeros((num_features,), dtype=\"float32\")\n nwords = 0\n\n for word in words:\n if word in index2word_set:\n nwords = nwords+1\n featureVec = np.add(featureVec, model.wv[word])\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Print last `n` lines of file
def file_tail(filename, n): result = '' with open(filename, 'r') as f: for line in (f.readlines()[-n:]): result += line return result
[ "def tail(filepath, n):\n with open(filepath, encoding=\"utf-8\") as f:\n return f.read().splitlines(keepends=False)[-n:]", "def tail(filepath, n):\n with open(filepath) as file_fd:\n lines = ''.join(file_fd.readlines())\n lines = lines.splitlines()[-n:]\n return lines", "def t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the disks file names from the domain XML description.
def GetFilesToBackup(domainXml): disks = root.findall("./devices/disk/source") files = [] for disk in disks: files.append(disk.get("file")) return files
[ "def get_disks(self):\n # root node\n root = ElementTree.fromstring(self.libvirt_domain.XMLDesc())\n\n # search <disk type='file' device='disk'> entries\n disks = root.findall(\"./devices/disk[@device='disk']\")\n\n # for every disk get drivers, sources and targets\n driver...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reads a CSV file for a catalog into a long format Python dictionary. The first line is assumed to be the header line, and must contain the field 'item_name'.
def _read_csv_to_dictionary_list(file_name): catalog_list = [] with open(file_name) as csvfile: reader = csv.DictReader(csvfile) for item in reader: catalog_list.append(item) return catalog_list
[ "def read_file(file):\n \n dictionary = {}\n csv_fp = csv.reader(file)\n #L[46] = manufacturer, L[63] = year\n #L[4]= city mileage, L[34]=highway mileage\n for line in csv_fp:\n #Skip the headings and the year 2017\n if (not (line[46] == 'make')) and (not (line[63] == '2017')):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function will return Grid size of UI based on difficulty level.
def get_grid_size(game_level): grid_length = 0 grid_width = 0 minecount = 0 if game_level == DifficultyLevel.BeginnerLevel: grid_length = GridSize.BeginnerLength grid_width = GridSize.BeginnerWidth minecount = 10 elif game_level == DifficultyLevel.IntermediateLevel: ...
[ "def _grid_hint_size(self) -> int:", "def get_size_of_grid(self):\n row = 0\n column = 0\n if int(self.var1.get()) == 1:\n row, column = 6, 6\n\n if int(self.var2.get()) == 1:\n row, column = 7, 6\n\n if int(self.var3.get()) == 1:\n row, column =...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function updates the timer lcd
def timer_change(self): if self.time < 999: self.time += 1 self.time_lcd.display(self.time) else: self.timer.stop()
[ "def update_timer(self):\r\n frmt_time = \"%d:%02d\" % (self.time_minutes, self.time_seconds)\r\n self.time_seconds += 1\r\n if self.time_seconds == 60:\r\n self.time_seconds = 0\r\n self.time_minutes += 1\r\n\r\n self.mainWidget.statusLabel.setText(\"{} {} --- {} {...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function handles the left click action on each of the grid cell. It will also handle the actions required
def handle_left_click(self): if not self.game_in_progress: return if self.first_click: self.first_click = False self.timer.start(1000) sender = self.sender() row = 0 col = 0 for row in range(self.rows): for col in range(self...
[ "def on_click_grid_cell(self):\n if not self.is_mouse_playing:\n for grid_item in self.mouse_grid.selectedItems():\n cell_widget = self.mouse_grid.cellWidget(grid_item.row(), grid_item.column())\n \n if self.button_selected == ButtonKey.MOUSE:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function handles the right click action on grid cell.
def handle_right_click(self): if not self.game_in_progress: return if self.first_click: self.first_click = False self.timer.start(1000) sender = self.sender() row = 0 col = 0 for row in range(self.rows): for col in range(sel...
[ "def OnLabelRightClick(self, evt):\n \n self.actRow = evt.Row\n self.actCol = evt.Col\n \n if evt.Row<0 and evt.Col>=0: #right click on column label\n\n menu = wx.Menu()\n \n miX = menu.Append(self.ID_popup_Column_SetX,\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function displays help about game This function will pop up message box to user
def game_help(self): QtGui.QMessageBox.about(self, "How to Play game", "<b>How to Play</b><br>" "The rules in Minesweeper are simple:<br><br>" "<b>1.</b> Uncover a mine and that's end of game <br>" ...
[ "def helpHelp(self):\r\n QtGui.QMessageBox.about(self, \"Help me!\",\"\"\"\r\n <p> Program sucks and you need help?\r\n <p>Email: \r\n <p><b>andrew.kolb@marquette.edu</b>\r\n <p>Or visit him in Room 230U!\r\n \"\"\")", "def displayHelpMessage(self):\n if self.dialo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function helps in changing game level When user clicks on change game level from File menu this function will change height and width of grid.
def change_game_level(self, change_level): global CURRENT_GAME_LEVEL file_object = open("Level.txt", "w") file_object.write(str(change_level)) file_object.close() CURRENT_GAME_LEVEL = change_level if change_level == DifficultyLevel.BeginnerLevel: grid_length ...
[ "def change_level(self):\n new_level = GameLevel[self.scoreboard.current_level]\n self.greeterboard.reset(level=new_level, msg='')\n self.end_game(i18n.OUT_MSG_NEW_GAME)\n self.init_game_metrics()", "def grid_level(self, grid_level):\n\n self._grid_level = grid_level", "def di...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parse ``define``'s of constants and of types.
def parse_defines(self): for line in self.header.splitlines(): if line.lower().startswith("#define"): _, line = line.strip().split(None, 1) # remove #define if " " in line: symbol, value = line.split(None, 1) if value.isdigit():...
[ "def test_define_variable(self):\n self.assertEqual(['define', 'test', '\"test\"'],\n grammar._DEFINE_VAR.parseString(\"#define test \\\"test\\\"\").asList())\n\n self.assertEqual(['define', 'test', \"f(w,x)\"],\n grammar._DEFINE_VAR.parseString(\"#defin...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Cast a ctypes object or byref into a Python object.
def deref(obj): try: return obj._obj.value # byref except AttributeError: try: return obj.value # plain ctypes except AttributeError: return obj # plain python
[ "def _ptr2obj(ptr):\n if isinstance(ptr, _Pointer):\n return ptr.contents\n return ptr", "def as_pyobj(space, w_obj, w_userdata=None, immortal=False):\n assert not is_pyobj(w_obj)\n if w_obj is not None:\n py_obj = w_obj._cpyext_as_pyobj(space)\n if not py_obj:\n py_obj...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Add a method with specific success codes.
def _set_success_codes(self, fname, success_codes): func = getattr(self._dll, fname) argtypes, func.argtuple_t, restype = self._fundecls[fname] argtypes = [argtype if not (isinstance(argtype, type(ctypes.POINTER(ctypes.c_int))) and argtype._type_.__module__ != "ct...
[ "def add_success(self, group=None, type_='', field='', description=''):\n group = group or '(200)'\n group = int(group.lower()[1:-1])\n self.retcode = self.retcode or group\n if group != self.retcode:\n raise ValueError('Two or more retcodes!')\n type_ = type_ or '{Stri...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return nth value of the modified Tribonnaci sequence Expand the sequence if necessary
def get_tribonnaci(self, n): if n not in self.numbers: current_n = max(self.numbers) while current_n < n: current_n += 1 self.numbers[current_n] = self.numbers[current_n - 1] + \ self.numbers[current_n - 2] + \ ...
[ "def colatz_seq(n):\n x = n / 2 if n % 2 == 0 else 3 * n + 1\n return x", "def _get_nth(self, n):\n return self.start + ((n - 1) * self.delta)", "def solve(n, seq):\n\n return sum(seq) - (n-1) * (n-2) / 2", "def triangular_number(n):\n defined_values = [1, 3, 5, 10, 15, 21]\n if 1 <= n <...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This is a hook for providing more complex voting once logical reasoning has been performed.
def _vote(self, team): return True
[ "def opinion_vote(mode, verbose, revision):\n judge = VotingJudge(mode, revision)\n flags = judge.vote()\n if verbose is True:\n click.echo(\"Vote resulted in %i flags:\" % len(flags))\n for f in flags:\n format_flag(f)", "def _process_vote(user, post, timestamp=None, cancel=Fals...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the argument parser for passing times.
def get_parser_times(): parser = argparse.ArgumentParser( description=__doc__, formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument( "start_time", action="store", type=pandas.Timestamp) parser.add_argument( "end_time", action="store", ...
[ "def parse_args():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--date\", \"-d\", help=\"Date of this lab session\")\n parser.add_argument(\"--time-in\", \"-ti\", help=\"Time string representing the time lab began\")\n parser.add_argument(\"--time-out\", \"-to\", help=\"Time string repre...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks if Python version is supported by Cuckoo.
def check_python_version(): version = sys.version.split()[0] if version < "2.6" or version >= "3": raise CuckooStartupError("You are running an incompatible version of Python, please use 2.6 or 2.7")
[ "def check_python():\n if (sys.version_info[:2] > (2, 6) or sys.version_info[:2] > (3, 1)):\n return True\n\n return False", "def check_python3():\n\tpythonVersion = sys.version_info[:3]\n\treturn (pythonVersion[0] == 3)", "def check_python_version():\n # Required due to multiple with statements...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks if dependencies are installed.
def check_dependencies(): check_python_version() dependencies = ["sqlite3"] for dependency in dependencies: try: __import__(dependency) except ImportError as e: raise CuckooStartupError("Unable to import \"%s\"" % dependency) return True
[ "def dependencies_installed(self):\n return True", "def check_dependencies():\n missing=False\n for program in ['mashtree', 'mash']:\n try:\n output = subprocess.run([program, '--version'],\n check=True,\n stdout=...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks if config files exist.
def check_configs(): configs = [os.path.join(CUCKOO_ROOT, "conf", "cuckoo.conf"), os.path.join(CUCKOO_ROOT, "conf", "reporting.conf")] for config in configs: if not os.path.exists(config): raise CuckooStartupError("Config file does not exist at path: %s" % config) return...
[ "def check_conf_files(self):\n pass", "def config_exists():\n return CONFIG_PATH.exists()", "def __check_config(self):\n if not os.path.exists(self.__config_path):\n return False\n else:\n return True", "def is_config_exist(self) -> bool:\n return True", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Randomly transform image data. Given an input image list (possibly multimodal) and an optional corresponding segmentation image list, this function will perform data augmentation with
def data_augmentation(input_image_list, segmentation_image_list=None, number_of_simulations=10, reference_image=None, transform_type='affineAndDeformation', noise_model='additivegaussian', ...
[ "def data_augmentation(image_data, mask_data, rotate=False, vertical_flip=False, horizontal_flip=False):\n aug_images = []\n aug_masks = []\n\n for _ in range(len(image_data)):\n if rotate:\n rotation = A.RandomRotate90(p=1)\n rotated_data = rotation(image=image_data[_], mask=m...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns an ``Iterable`` containing all the instances in the specified dataset. If ``self.lazy`` is False, this calls ``self._read()``, ensures that the result is a list, then returns the resulting list. If ``self.lazy`` is True, this returns an object whose ``__iter__`` method calls ``self._read()`` each iteration. In ...
def read(self, *args, **kwargs) -> Iterable[Instance]: lazy = getattr(self, 'lazy', None) if lazy is None: logger.warning("DatasetReader.lazy is not set, " "did you forget to call the superclass constructor?") if lazy: return _LazyInstances(lam...
[ "def read(self, file_path: str) -> Iterable[Instance]:\n lazy = getattr(self, 'lazy', None)\n if lazy is None:\n logger.warning(\"DatasetReader.lazy is not set, \"\n \"did you forget to call the superclass constructor?\")\n if lazy:\n return _Lazy...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test the login page elements like button, username field and password field is loded properly or not.
def test_login_page_elements(self): response = self.client.get(reverse('users:login')) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'users/login.html') self.assertContains(response, ' <input type="text" name="username"') self.assertContains(respon...
[ "def test_login(self):\n url_extend = 'user_auth/login/'\n self.browser.get(self.url + url_extend)\n\n # enter the username and password.\n username_field = self.browser.find_element_by_name('user_name')\n username_field.send_keys('user4')\n password_field = self.browser.fi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check for valid username and invalid password should not be able to login
def test_valid_username_invalid_password(self): response = self.client.post(reverse('users:login'), {'username': self.user['username'], 'password': '1sfsdf'}) self.assertEqual(response.status_code, 200) self.assertFormError(response, 'form', None, ERROR_MSG)
[ "def test_incorrect_login(self):\n # test incorrect username\n self.incorrect_login(\"\", \"password\")\n # test incorrect password\n self.incorrect_login(\"admin\", \"\")", "def validate_authentication(self, username, password):\n return self.user_table[username]['pwd'] == pass...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Check for blank username and blank password should not be able to login
def test_blank_username_blank_password(self): response = self.client.post(reverse('users:login'), {'username': '', 'password': ''}) self.assertEqual(response.status_code, 200) self.assertFormError(response, 'form', 'username', 'This field is required.') self.assertFormError(response, 'fo...
[ "def test_login_emptypassword(self):\n emptypassword = self.new_user.user_login(\"kaguna@gmail.com\", \" \")\n self.assertEqual(\"check_null_empty_fields\", emptypassword, \"Password field should not be empty.\")", "def test_incorrect_login(self):\n # test incorrect username\n self.in...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieves all info needed for worker and puts it into a dictionary
def get_task_worker(self): start, end = self.get_block() return { 'task_id':self.id, 'finished':self.finished, 'free_block':(start != end), 'keyword':self.keyword, 'chars':self.chars, 'algorithm':self.algorithm, ...
[ "def _get_worker_resources_dict(self):\n return {\n 'number_of_threads': self._resources_per_worker.number_of_threads,\n 'number_of_gpus': self._resources_per_worker.number_of_gpus,\n }", "async def read_worker_metadata(self) -> Dict[str, Any]:\n response = await self._c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Gets the Updated job template right now changes from active to inactive.
def get_updated_jobtemplate(self): return self.response_json
[ "def last_status_update(self):\n try:\n return StatusUpdate.objects.filter(section=self).latest(\"created_at\")\n except StatusUpdate.DoesNotExist:\n return None", "def getModified(self):\n return self.modified", "def changes(self) -> dict:\n return self.config[...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Display all videos in a playlist with a given name.
def show_playlist(self, playlist_name): if self.playlists[playlist_name.lower()]!=[]: print(f"Showing playlist: {playlist_name}") for i in self.playlists[playlist_name.lower()]: videos = self._video_library.get_all_videos() templist = [] d...
[ "def show_playlist(self, playlist_name):\n if playlist_name.upper() not in self.playlists:\n print(f\"Cannot show playlist {playlist_name}: Playlist does not exist\") \n return\n if not self.playlists[playlist_name.upper()].videos:\n print(f\"Showing playlist: {playlis...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }