query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Using the string returned from get_sra_xml(), finds the file size of the sra run (it is in bytes), convert it to gigabytes and returns it as a float. | def get_filesize(string):
string = get_sra_xml('SRR3403834')
pattern = re.compile(r'size.*?([0-9.-]+)')
size = re.search(pattern,string)
return float(size.group(1))/(10**9) | [
"def str2gib_size(s):\n size_in_bytes = str2size(s)\n return size_in_bytes // units.Gi",
"def get_gsize(self):\n gsize_file = Genome(self.genome).get_fasize()\n gsize = 0\n with open(gsize_file, 'rt') as fi:\n for a in fi:\n c, n = a.strip().split('\\t')\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Uniprot is a database of protein sequence data. Given the uniprot_id of a protein, and using urllib, return only the sequence (not the header) from the fasta entry. Be sure to remove new line characters from the protein sequence. | def get_protein_fasta(uniprot_id):
url = "http://www.uniprot.org/uniprot/{}.fasta".format(uniprot_id)
string = re.split("\n",ur.urlopen(url).read().decode(),1)[1]
return re.sub("\n","",string) | [
"def fetch_uniprot_fasta(accession_id):\n base_url = \"http://www.uniprot.org/uniprot/\"\n \n fasta_url = base_url + accession_id + \".fasta\"\n \n sequence = \"\"\n \n for line in urllib.request.urlopen(fasta_url):\n text = line.decode(\"utf-8\").strip()\n \n if text.star... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Handle /admin BOTNAME groups. | def admin(frame):
ctx, msg, modconf = frame.ctx, frame.msg, frame.value
text = frame.text
if text.startswith('remove '):
text = text[len('remove '):]
group = modconf['groups'].pop(text)
if group:
msg.add('Removed <b>%s</b>.', group['name'])
else:
msg.... | [
"def admin_group_name(self):\n return self.short_name+\"_admins\"",
"async def _group(self, ctx):\r\n\t\tif ctx.invoked_subcommand is None:\r\n\t\t\tprint (\"Ryhmä komento annettiin ilman alakomentoa\")",
"def _get_admin_group_lists(self):\n return self.__admin_group_lists",
"def set_admin(self, adm... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Try to convert an invite link to a normalized group info dict. | def get_private_group(invite_link):
info = fetch_opengraph(invite_link)
if not info.get('title'):
return
return {
'desc': info['description'],
'id': '',
'invite_link': invite_link,
'location': '',
'name': info['title'],
'type': '',
'username'... | [
"def parse_invite(invite_url: str) -> Message:\n matches = re.match('(.+)?c_i=(.+)', invite_url)\n assert matches, 'Improperly formatted invite url!'\n\n invite_msg = Message.deserialize(\n base64.urlsafe_b64decode(matches.group(2)).decode('ascii')\n )\n\n INVITE_SCHEMA(invite_msg)\n\n retu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
.dispose() method has to be overwritten | def dispose(self) -> None: | [
"def _close(self):\n pass",
"def __del__(self):\n self.close()",
"def __del__(self):\n self.window.close()",
"def __del__(self):\n self.releaseResource()",
"def __del__(self):\n # Here we'd like to call panel.close() if window is opened and then set\n # all objects ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets a list of tweets text from new tweets | def get_all_new_tweets_text(all_new_tweets):
all_tweets_text = []
for tweet in all_new_tweets:
all_tweets_text.append(tweet["text"])
return all_tweets_text | [
"def get_text_of_tweets(tweets_list):\n tweets_text = []\n for status in tweets_list['statuses']:\n tweets_text.append(status['text'])\n return tweets_text",
"def get_tweets(user, num = 200):\n tweets = []\n \n for tweet in user.home_timeline(count = num):\n edited_tweet = tweet.te... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This uses kmeans clustering from sklearn to cluster the text | def cluster_text(list_of_text):
print("Clustering text info saved the clustering.txt")
vectorizer = TfidfVectorizer(stop_words="english")
transform = vectorizer.fit_transform(list_of_text)
true_k = 70
model = MiniBatchKMeans(n_clusters=true_k, init="k-means++", max_iter=100, n_init=1)
model.fi... | [
"def cluster_texts(texts, clusters):\n vectorizer = TfidfVectorizer(lowercase=True,max_df=0.4,min_df=1)\n \n tfidf_model = vectorizer.fit_transform(texts)\n km_model = KMeans(n_clusters=clusters,init='k-means++', max_iter=100, n_init=1)\n km_model.fit(tfidf_model)\n \n clustering = collections.defaul... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a tuple of setting overrides and filter setting overrides. | def overrides(self) -> tuple[dict[str, Any], dict[str, Any]]:
settings = {}
if self.actions:
settings = self.actions.overrides
if self.validations:
settings |= self.validations.overrides
filter_settings = {}
if self.extra_fields:
filter_settin... | [
"def filter_overrides_for_ui(filter_: Filter) -> tuple[dict, dict]:\n overrides_values, extra_fields_overrides = filter_.overrides\n return to_serializable(overrides_values, ui_repr=True), to_serializable(extra_fields_overrides, ui_repr=True)",
"def overrides(self):\n return self._overrides",
"def ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that all notebooks have a README file and exist in the Notebooks README | def test_readme():
notebooks_readme = Path("notebooks/README.md").read_text()
for item in Path("notebooks").iterdir():
if item.is_dir():
# item is a notebook directory
notebook_dir = item.relative_to("notebooks")
if str(notebook_dir)[0].isdigit():
assert "... | [
"def test_readme():\n notebooks_readme = Path(\"notebooks/README.md\").read_text()\n for item in Path(\"notebooks\").iterdir():\n if item.is_dir():\n # item is a notebook directory\n notebook_dir = item.relative_to(\"notebooks\")\n if str(notebook_dir)[0].isdigit():\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Start NAT/forwarding between Mininet and external network | def startNAT( root, inetIntf='eth0', subnet='10.0/8' ):
# Identify the interface connecting to the mininet network
localIntf = root.defaultIntf()
# Flush any currently active rules
root.cmd( 'iptables -F' )
root.cmd( 'iptables -t nat -F' )
# Create default entries for unmatched traffic
... | [
"def startNAT( root, inetIntf='eth0', subnet='10.0/8' ):\n\n # Identify the interface connecting to the mininet network\n localIntf = root.defaultIntf()\n\n # Flush any currently active rules\n root.cmd( 'iptables -F' )\n root.cmd( 'iptables -t nat -F' )\n\n # Create default entries for unmatched... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Stop NAT/forwarding between Mininet and external network | def stopNAT( root ):
# Flush any currently active rules
root.cmd( 'iptables -F' )
root.cmd( 'iptables -t nat -F' )
# Instruct the kernel to stop forwarding
root.cmd( 'sysctl net.ipv4.ip_forward=0' )
# Restart network-manager
root.cmd( 'service network-manager start' ) | [
"def stopNAT( root ):\n # Flush any currently active rules\n root.cmd( 'iptables -F' )\n root.cmd( 'iptables -t nat -F' )\n\n # Instruct the kernel to stop forwarding\n root.cmd( 'sysctl net.ipv4.ip_forward=0' )",
"def stop_network_nat(self):\n\t\tcmd = [\"/sbin/iptables\",\"-t\",\"nat\",\"-F\"]\n\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Information of a particular city | def get_city_info(g, city_name):
flag = 0
for key in g.city_dict:
if(g.city_dict[key].get_name() == city_name):
print g.city_dict[key].get_info()
flag = 1
if(flag == 0):
print ("Invalid Input") | [
"def GetCity():\n IPinfoRequest = requests.get('https://ipinfo.io/')\n IPinfo = IPinfoRequest.json()\n City = IPinfo['city']\n return(City)",
"def city_info(self, args):\n self.requiere_param(args, '$city')\n city_name = args['$city']\n city = self.__get_city(city_name)\n a... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Distance and endpoints of the shortest flight | def shortest_flight(g):
min_distance = sys.maxsize
min_destination = None
min_key = None
for key in g.city_dict:
for flight in g.city_dict[key].get_flights_out():
if(flight[1] < min_distance):
min_key = key
min_... | [
"def get_shortest_route_floyd(network, start,destination, excludings=[]):\n\n # On récupère la liste des villes\n list_city = network[1].keys()\n \n # Si la ville de départ ou de fin n'existe pas\n if start not in list_city or destination not in list_city:\n return None\n\n # On retire les villes à exclure... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculates city with the most population | def biggest_city(g):
max_size = None
max_city = None
for key in g.city_dict:
if(g.city_dict[key].get_population() > max_size):
max_size = g.city_dict[key].get_population()
max_city = g.city_dict[key].get_name()
... | [
"def biggest_city(self):\r\n biggest = 0\r\n for code, node in self.vertices.items():\r\n if node.population > biggest:\r\n biggest = node.population\r\n city_code = node.code\r\n name = node.name\r\n return city_code, name, biggest",
"d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculates city with the least population | def smallest_city(g):
min_size = sys.maxsize
min_city = None
for key in g.city_dict:
if(g.city_dict[key].get_population() < min_size):
min_size = g.city_dict[key].get_population()
min_city = g.city_dict[key].get_name()
... | [
"def smallest_city(self):\r\n smallest = sys.maxsize\r\n for code, node in self.vertices.items():\r\n if node.population < smallest:\r\n smallest = node.population\r\n city_code = node.code\r\n name = node.name\r\n return city_code, name, ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculates the average population across all cities | def average_city(g):
average = 0
ctr = 0
for key in g.city_dict:
average = average + g.city_dict[key].get_population()
ctr = ctr + 1
return (average / ctr) | [
"def average_city_size(self):\r\n average = 0\r\n total = 0\r\n for code, node in self.vertices.items():\r\n average += node.population\r\n total += 1\r\n return average // total",
"def average_population(self,population):\n add = 0\n average = 0\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
List of continents and sub cities | def continents(g):
continents = []
for key in g.city_dict:
if(g.city_dict[key].get_continent() not in continents):
continents.append(g.city_dict[key].get_continent())
for continent in continents:
print("{}: ").format(continent)
... | [
"def continents_and_cities(self):\r\n list_all = col.defaultdict(list)\r\n for code, node in self.vertices.items():\r\n list_all[node.continent].append(node.name)\r\n return list_all",
"def cities(self):\n return {team.city for team in self.teams}",
"def GetCities(self):\r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculates the hub cities | def hub_city(g):
max_flights = None
hub_cities = []
for key in g.city_dict:
if(len(g.city_dict[key].get_flights_in()) > max_flights):
max_flights = len((g.city_dict[key]).flights_in)
for key in g.city_dict:
if(len(... | [
"def cal_city_cat_values(self, df):\n _dict = {}\n\n col_enum = list(enumerate(df.groupby(['city', 'max_partial_category']).size().unstack().columns.tolist()))\n\n # 建用各縣市各類消費量前幾名 dict\n for idx in df.groupby(['city', 'max_partial_category']).size().unstack().fillna(0).astype('int32').in... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Removes routes in either one or both directions depending on choice | def remove_route(g, origin, destination, choice_dir):
origin_code = g.convert[origin]
destination_code = g.convert[destination]
# Removes both directions and returns
if(choice_dir == "y"):
for key in g.city_dict:
if(key == origin_code):
... | [
"def _ri_maybe_remove_route(sip_message, proxy_params):\n if proxy_params.check_rroute_function is not None:\n route_hdr = sip_message.find(ROUTE_HEADER)\n if not isinstance(route_hdr, NotFound):\n first_route = route_hdr.first\n if proxy_params.check_rrout... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Edits a particular city's information | def edit_city(g, city_name, option, value):
city_code = g.convert[city_name]
if(option == "country"):
g.city_dict[city_code].set_country(value)
if(option == "continent"):
g.city_dict[city_code].set_continent(value)
if(option == "timezone"):
g.city_dict[... | [
"def city_update(self):\n self.city = self.city_finder(self.location.__str__())",
"def city(self, city):\n self._city = city",
"def update_city(city_id):\n update_city_json = request.get_json(silent=True)\n if update_city_json is None:\n return jsonify(\"Not a JSON\"), 400\n city =... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Helper function for route info. Calculates Time | def route_info_helper(g, origin, destination, distance):
time = 0
acceleration = 1406.25
if(distance > 400):
time = time + 0.53 + 0.53
distance = distance - 400
time = time + distance / 750
else:
half = distance / 2.0
time = time + 2 (math.sqrt((2 * half) / ... | [
"def get_time(network, road_id):\n return network[0][road_id][4]",
"def route_time(self, route, truck_speed):\n\n distance_miles = self.get_route_distance(route)\n distance_time = (distance_miles / truck_speed) * 60 * 60\n\n return distance_time",
"def GetArrivalTimeOfTour(PathInfo):\r\n\t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Validates a large collection of webaccessible VOTable files. Generates a report as a directory tree of HTML files. | def make_validation_report(
urls=None,
destdir="astropy.io.votable.validator.results",
multiprocess=True,
stilts=None,
):
from astropy.utils.console import ProgressBar, Spinner, color_print
if stilts is not None:
if not os.path.exists(stilts):
raise ValueError(f"{stilts} doe... | [
"def checkAll(dirName):\n\n global failures\n\n # Find/parse all HTML files first\n print()\n print('Crawl/parse...')\n allFiles = {}\n\n if os.path.isfile(dirName):\n root, fileName = os.path.split(dirName)\n iter = ((root, [], [fileName]),)\n else:\n iter = os.walk(dirName)\n\n for root, dirs, fi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Build a word cooccurrence list for the given corpus. This function is a tuple generator, where each element (representing a cooccurrence pair) is of the form (i_main, i_context, cooccurrence) where `i_main` is the ID of the main word in the cooccurrence and `i_context` is the ID of the context word, and `cooccurrence` ... | def _build_cooccur(self):
vocab_size = len(self._vocabulary)
# Collect cooccurrences internally as a sparse matrix for passable
# indexing speed; we'll convert into a list later
cooccurrences = sparse.lil_matrix((vocab_size, vocab_size),
dtype=... | [
"def build_cooccurrence_graph(preprocessed_context: Generator[Tuple[List[str], List[Tuple[str, str]]], None, None],\n directed: bool = False,\n weighted: bool = False,\n conn_with_original_ctx=True, window: int = 2) -> Tuple[\n U... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Run a single iteration of GloVe training using the given cooccurrence data and the previously computed weight vectors / biases and accompanying gradient histories. `data` is a prefetched data / weights list where each element is of the form (v_main, v_context, b_main, b_context, gradsq_W_main, gradsq_W_context, gradsq_... | def _run_iter(self, data):
global_cost = 0
# We want to iterate over data randomly so as not to unintentionally
# bias the word vector contents
shuffle(data)
for (v_main, v_context, b_main, b_context, gradsq_W_main, gradsq_W_context,
gradsq_b_main, gradsq_b_contex... | [
"def cost_and_updates(self, mini_batch_data, test=False):\n\n cost = correct = total = 0.0\n\n # Set gradients to zero.\n # --------------------------\n self.V, self.W, self.b, self.W_s, self.b_s = self.params\n \n self.dV.set_value(np.zeros(self.np_dV.shape).astype(floatX)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Train GloVe vectors on the given generator `cooccurrences`, where each element is of the form (word_i_id, word_j_id, x_ij) where `x_ij` is a cooccurrence value $X_{ij}$ as presented in the matrix defined by `build_cooccur` and the Pennington et al. (2014) paper itself. If `iter_callback` is not `None`, the provided fun... | def _train(self, iter_callback=None):
vocab_size = len(self._vocabulary)
# Word vector matrix. This matrix is (2V) * d, where N is the size
# of the corpus vocabulary and d is the dimensionality of the word
# vectors. All elements are initialized randomly in the range (-0.5,
# ... | [
"def train_batch_cbow(model, sentences, alpha, work=None, neu1=None, compute_loss=False):\n result = 0\n for sentence in sentences:\n word_vocabs = [\n model.wv.vocab[w] for w in sentence if w in model.wv.vocab\n and model.wv.vocab[w].sample_int > model.random.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Merge the mainword and contextword vectors for a weight matrix using the provided merge function (which accepts a mainword and contextword vector and returns a merged version). By default, `merge_fun` returns the mean of the two vectors. | def _merge_main_context(self, W, merge_fun=lambda m, c: np.mean([m, c], axis=0),
normalize=True):
vocab_size = int(len(W) / 2)
for i, row in enumerate(W[:vocab_size]):
merged = merge_fun(row, W[i + vocab_size])
if normalize:
merged /= ... | [
"def combine_word_vectors(self, embeddings):\n # the embeddings are combined according to the operation given in\n # the configuration\n combined = self.embedding_combiner(embeddings, axis=0)\n # make sure the resulting vector has the dimensions 1 x embedding_dim\n assert combined... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check that the learner model copies the parameters to the actor model. | def test_parameters_copied_to_actor_model(self):
# Reset models.
self.model.load_state_dict(self.initial_model_dict)
self.actor_model.load_state_dict(self.initial_actor_model_dict)
polybeast.learn(*self.learn_args)
np.testing.assert_equal(
_state_dict_to_numpy(self.... | [
"def check_model(self, model):\n self.check_initial_conditions(model)\n self.check_variables(model)",
"def test_gradients_update(self):\n # Reset models.\n self.model.load_state_dict(self.initial_model_dict)\n self.actor_model.load_state_dict(self.initial_actor_model_dict)\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check that gradients get updated after one iteration. | def test_gradients_update(self):
# Reset models.
self.model.load_state_dict(self.initial_model_dict)
self.actor_model.load_state_dict(self.initial_actor_model_dict)
# There should be no calculated gradient yet.
for p in self.model.parameters():
self.assertIsNone(p.gr... | [
"def gradient_check():\n X, T = twospirals(n_points=10)\n NN = NeuralNetwork()\n eps = 0.0001\n\n for key, value in NN.var.items():\n row = np.random.randint(0, NN.var[key].shape[0])\n col = np.random.randint(0, NN.var[key].shape[1])\n print(\"Checking \", key, \" at \", row, \",\",... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check that the loss is not zero after one iteration. | def test_non_zero_loss(self):
# Reset models.
self.model.load_state_dict(self.initial_model_dict)
self.actor_model.load_state_dict(self.initial_actor_model_dict)
polybeast.learn(*self.learn_args)
self.assertNotEqual(self.stats["total_loss"], 0.0)
self.assertNotEqual(sel... | [
"def _check_loss(self, loss):\n assert not np.isnan(loss), \"Model diverged with loss = NaN\"",
"def loss_initialized(self) -> bool:\n return len(self._losses) > 0",
"def check_loss(self, loss):\r\n if loss in loss_functions:\r\n return loss\r\n else:\r\n raise Inva... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create entity via REST API call to FIWARE Orion instance | def create_entity(self, data):
url = '{}/ngsi-ld/v1/entities'.format(self.url)
return self.post(url, data=data, headers=self.headers_ld) | [
"def post(self):\n data = request.json\n create_another_entity(data)\n return None, 201",
"def create_entity(self, entity: Entity) -> requests.models.Response:\r\n if not isinstance(entity, Entity):\r\n raise TypeError('entity must be of type \\'Entity\\'')\r\n else:\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get list of subscriptions | def get_subscriptions(self):
url = '{}/v2/subscriptions'.format(self.url)
r = requests.get(url, headers=self.headers_v2)
return r.json() | [
"def get_subscriptions(self):\n return self.subscriptions.all()",
"def list(self):\n return self._engine.exec(\"subscription-manager list\")",
"def subscriptions(self):\r\n return subs.AccountSubscriptions(self)",
"def get_subscriptions(self):\n \n r = self.fitbit_service.get('http:/... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return version of Orion | def get_version(self):
url = '{}/version'.format(self.url)
try:
r = requests.get(url)
if r.status_code == 200:
return r.json()['orionld version']
except Exception as e:
pass
return '' | [
"def get_otx_version() -> str:\n otx = load_module(name=\"src/otx/__init__.py\")\n return otx.__version__",
"def get_version(self):\n return \"built-in\"",
"def _onnx_ir_version(self) -> int:\n ...",
"def get_version():\n return magpy.get_version()",
"def version():\n retur... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Iteratively improve guess with update until close(guess) is true. | def improve(update, close, guess=1, max_updates=100):
k = 0
while not close(guess) and k < max_updates:
guess = update(guess)
k = k + 1
return guess | [
"def _updateGuess(self, newGuess, index, direction):\n oldGuess = self.guesses[index]\n oldElements = oldGuess.elements\n self.guesses[index] = newGuess\n\n if direction * newGuess.energy <= direction * self.lowestEnergy:\n self.lowestEnergy = newGuess.energy\n\n for el... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Whether x is within tolerance of y. | def approx_eq(x, y, tolerance=1e-15):
return abs(x - y) < tolerance | [
"def within_tolerance(x, y, tolerance): \r\n return abs(x) <= tolerance and abs(y) <= tolerance",
"def withinEpsilon(x, y, epsilon):\n return abs(x - y) <= epsilon",
"def checktol(x,y,tol):\n err = abs(x-y)/x\n if err<tol:\n return True\n if err>tol:\n return False",
"def is_clo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a zero of the function f with derivative df. | def find_zero(f, df):
def near_zero(x):
return approx_eq(f(x), 0)
return improve(newton_update(f, df), near_zero) | [
"def derivative(f): # Newton's method\n def df(x, h=0.1e-3):\n der = ( f(x+h/2) - f(x-h/2) )/h\n return der if der!=0 else 0.00001\n return df",
"def zzX_zero_of(f, d=0):\n return zzX_zero(poly_level(f)-d)",
"def find_zero(f,p1,d):\n if p1 > 10:\n p1 = 0.5\n c... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return an update function for f with derivative df. | def newton_update(f, df):
def update(x):
return x - f(x) / df(x)
return update | [
"def derivative(f): # Newton's method\n def df(x, h=0.1e-3):\n der = ( f(x+h/2) - f(x-h/2) )/h\n return der if der!=0 else 0.00001\n return df",
"def derivative(func: Callable, x: float, delta: float) -> float:\n return (func(x + delta) - func(x - delta)) / (2.0 * delta)",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the nth root of a. >>> nth_root_of_a(2, 64) 8.0 >>> nth_root_of_a(3, 64) 4.0 >>> nth_root_of_a(6, 64) 2.0 | def nth_root_of_a(n, a):
return find_zero(lambda x: pow(x, n) - a, lambda x: n * pow(x, n-1)) | [
"def nth_root(a, b):\n return a**(1/b)",
"def square_root(a):\n return nth_root(a, 2)",
"def _nth_root(value, n_root):\n return value ** (1 / n_root)",
"def nthRoot(x,n):\n return op.pow(x,1/n)",
"def cubic_root(a):\n return nth_root(a, 3)",
"def _nth_root(value, n_root) -> float:\r\n\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return where f with derivative df intersects g with derivative dg. | def intersect(f, df, g, dg):
"*** YOUR CODE HERE ***" | [
"def derivative(f): # Newton's method\n def df(x, h=0.1e-3):\n der = ( f(x+h/2) - f(x-h/2) )/h\n return der if der!=0 else 0.00001\n return df",
"def grad(f):\n h = 10**(-10)\n return lambda x,y : np.array((f(x+h,y)-f(x,y), f(x,y+h)-f(x,y)))/h",
"def set_second_derivati... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a quadratic polynomial axx + bx + c. >>> q_and_dq = quadratic(1, 6, 8) xx + 6x + 8 >>> q_and_dq(1.0, False) value at 1 15.0 >>> q_and_dq(1.0, True) derivative at 1 8.0 >>> q_and_dq(1.0, False) value at 1 3.0 >>> q_and_dq(1.0, True) derivative at 1 4.0 | def quadratic(a, b, c):
A, B, C = K(a), K(b), K(c)
AXX = mul_fns(A, mul_fns(X, X))
BX = mul_fns(B, X)
return add_fns(AXX, add_fns(BX, C)) | [
"def myQuad(x,Q,b):\n #Make sure the input is numpy compatible\n x = np.array(x)\n Q = np.array(Q)\n b = np.array(b)\n # Run f(x)\n r = 0.5 * np.matmul(x.transpose(), np.matmul(Q, x)) - np.matmul(b.transpose(), x)\n # Since we're hoping for a symmetric, positive definite Q, I'm taking\n # th... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes a FQDN, removes common hosts prepended to it in the subdomain, and returns it. | def _remove_common_hosts(fqdn):
fqdn_parts = fqdn.split(".", 1)
common_hosts = ["*", "www", "mail", "cpanel", "webmail",
"webdisk", "autodiscover"]
if len(fqdn_parts) > 1:
if fqdn_parts[0] in common_hosts:
return fqdn_parts[1]
return ... | [
"def get_subdomain(url, server_name):\n if server_name not in url:\n return None\n\n host = urlsplit(url).netloc\n\n if host == server_name:\n return None\n\n return host.replace('.%s' % server_name, '')",
"def extract_hostname_from_fqdn(fqdn: str) -> str:\n return fqdn.split(\".\")[0... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Break apart domain parts and return a dictionary representing the individual attributes like subdomain, domain, and tld. | def _fqdn_parts(fqdn):
parts = tldextract.extract(fqdn)
result = {}
result['subdomain'] = parts.subdomain
result['domain'] = parts.domain
result['tld'] = parts.suffix
return result | [
"def sub_domain(self) -> dict:\n\n #Veriables\n site_name = []\n site_value = []\n\n #Bilgiler alınıyor.\n sub_name = self.soup.find_all('table', attrs={'id': 'subdomain_table'})[0].find_all(\"span\",attrs={\"class\":\"word-wrap\"})\n sub_value = self.soup.find_all('table',... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Look for presence of keywords anywhere in the FQDN i.e. 'account' would match on 'dswaccounting.tk'. | def _fe_keyword_match(self, sample):
result = OrderedDict()
for item in self._keywords:
result[item + "_kw"] = 1 if item in sample['fqdn'] else 0
return result | [
"def _fe_keyword_match_fqdn_words(self, sample):\n result = OrderedDict()\n\n for item in self._fqdn_keywords:\n result[item + \"_kw_fqdn_words\"] = 1 if item in sample['fqdn_words'] else 0\n\n return result",
"def has_keyword(tweet, keywords):\n temp = tweet.lower()\n for ke... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compare FQDN words (previous regex on special characters) against a list of common phishing keywords, look for exact match on those words. Probably more decisive in identifying phishing domains. | def _fe_keyword_match_fqdn_words(self, sample):
result = OrderedDict()
for item in self._fqdn_keywords:
result[item + "_kw_fqdn_words"] = 1 if item in sample['fqdn_words'] else 0
return result | [
"def _fe_check_phishing_similarity_words(self, sample):\n result = OrderedDict()\n\n for key in self._similarity_words:\n result[key + \"_lev_1\"] = 0\n\n for word in sample['fqdn_words']:\n if distance(word, key) == 1:\n result[key + \"_lev_1\"]... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes domain name from FQDN and computes entropy (randomness, repeated characters, etc). | def _fe_compute_domain_entropy(sample):
# Compute entropy of domain.
result = OrderedDict()
p, lns = Counter(sample['domain']), float(len(sample['domain']))
entropy = -sum(count / lns * math.log(count / lns, 2) for count in list(p.values()))
result['entropy'] = entropy
r... | [
"def prc_entropy(domain):\n subdomain = ignoreVPS(domain)\n # get probability of chars in string\n prob = [float(subdomain.count(c)) / len(subdomain) for c in dict.fromkeys(list(subdomain))]\n\n # calculate the entropy\n entropy = - sum([p * math.log(p) / math.log(2.0) for p in prob])\n return ent... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes a list of words from the FQDN (split by special characters) and checks them for similarity against words commonly disguised as phishing words. This method only searches for a distance of 1. i.e. 'pavpal' = 1 for 'paypal', 'verifycation' = 1 for 'verification', 'app1eid' = 1 for 'appleid'. | def _fe_check_phishing_similarity_words(self, sample):
result = OrderedDict()
for key in self._similarity_words:
result[key + "_lev_1"] = 0
for word in sample['fqdn_words']:
if distance(word, key) == 1:
result[key + "_lev_1"] = 1
ret... | [
"def domainSimilarityAlgorithm(domain1, domain2):\n try:\n d1_ip = socket.gethostbyname(domain1)\n d2_ip = socket.gethostbyname(domain2)\n\n text_similar = similarByName(domain1, domain2)\n net_similar = similarByNetwork(d1_ip, d2_ip)\n # total_similar = round(mean([text_simila... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compute number of periods several subdomains could be indicative of a phishing domain. | def _fe_number_of_periods(sample):
result = OrderedDict()
result['num_periods'] = sample['fqdn'].count(".")
return result | [
"def get_subdomaincount(self):\n return len(self.domaininfo.subdomain.split(\".\"))",
"def countSubDomain(subdomain):\r\n if not subdomain:\r\n return 0\r\n else:\r\n return len(subdomain.split('.'))",
"def domain_count(self) -> int:\n return pulumi.get(self, \"domain_count\")"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
evaluate single user statistic against consensus | def evaluate_user(user_name, path_annots, path_out, path_dataset=None,
tp_consensus='mean', visual=False):
tissue_sets = list_sub_folders(path_annots)
path_visu = path_out if visual else None
stats = []
for p_set in tissue_sets:
paths = list_sub_folders(p_set, '*_scale-*pc')
... | [
"def get_trust(self, session_dat, user_dat):\n\t\ttotal = 0 #total user score\n\t\tactmax = 0 #maximum achievable total (A user with this score is PERFECT)\n\t\tfor dt in self.__comparers.keys(): #loop through all the types of data\n\t\t\tactmax += self.__maxscores[dt] #add data type's max score to the maximum\n\t\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert a string to 'ladcase' (Alternating uppercase and lowercase) | def ladcased(normal):
ladified = ''
for i, c in enumerate(normal):
ladified += c.lower() if (i % 2 == 0) else c.upper()
return ladified | [
"def case(string):\r\n if string.islower():\r\n return \"lower\"\r\n elif string.isupper():\r\n return \"upper\"\r\n else:\r\n return \"mixed\"",
"def recase(s: str, case: str) -> str:\n s = apply_case_hack(s)\n if case == \"lower\":\n s = s.lower()\n elif case == \"u... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Delete the command message sent by the user | def delete_command(update):
try:
update.message.delete()
except error.BadRequest:
pass | [
"def on_message_delete(self, room, user, message):\n pass",
"def deleteMessage(upd, ctx):\n\tupd.callback_query.message.delete()",
"async def message_delete(ctx):\n try:\n await ctx.message.delete()\n except:\n return",
"async def delete(self):\n await self.ht... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
wrapper to run noise jobs | def run_noise_jobs(jobtime=60, on_the_fly=True, delay_submit=False):
pos = 'S5'
filelist = get_list('./%s.txt' % pos)
jobdir = './job'
job_idx = 0
for line in filelist:
runno = int(line)
# phase 1
basedir = "/nfs/slac/g/exo_data6/groups/Energy/data/WIPP/selection/2017_Ph... | [
"def run_experiment(self):",
"def multi_run_wrapper(args):\n return RUN_AGNfitter_onesource(*args)",
"def multi_run_wrapper(args):\n\treturn img_preprocessing(*args)",
"def run_job(job, interrupt_if_necessary):",
"def photo_worker(cmd):\n\n subprocess.run(cmd, shell=True, timeout=20)",
"def job(ctx)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Genera los flujos del derivado para la valorización. Quedan en el atributo flujos_nosensibles y flujos_derivados | def genera_flujos(self):
pass | [
"def get_flujos_derivado(self):\n return self.flujos_derivados",
"def valoriza_flujos(self):\n\n col_tabla_aux = ['Fecha', 'Fondo', 'Tipo', 'ID', 'Hora', 'Mercado',\n 'ActivoPasivo', 'FechaFixing', 'FechaFlujo', 'FechaPago', 'Moneda', 'Flujo', 'Amortizacion',\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retorna los flujos valorizados. Si no se ha llamado al método valoriza_flujos retorna un DataFrame vacío | def get_flujos_valorizados(self):
return self.flujos_valorizados | [
"def valoriza_flujos(self):\n\n col_tabla_aux = ['Fecha', 'Fondo', 'Tipo', 'ID', 'Hora', 'Mercado',\n 'ActivoPasivo', 'FechaFixing', 'FechaFlujo', 'FechaPago', 'Moneda', 'Flujo', 'Amortizacion',\n 'Interes', 'MonedaBase', 'Sensibilidad']\n\n tabla_aux = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retorna los flujos del derivado. Si no0 se ha llamado al método genera_flujos retorna un DataFrame vacío | def get_flujos_derivado(self):
return self.flujos_derivados | [
"def valoriza_flujos(self):\n\n col_tabla_aux = ['Fecha', 'Fondo', 'Tipo', 'ID', 'Hora', 'Mercado',\n 'ActivoPasivo', 'FechaFixing', 'FechaFlujo', 'FechaPago', 'Moneda', 'Flujo', 'Amortizacion',\n 'Interes', 'MonedaBase', 'Sensibilidad']\n\n tabla_aux = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retorna los flujos DV01 del derivado. Si no se ha llamado al método valoriza_flujos_DV01 retorna un DataFrame vacío | def get_flujos_DV01(self):
return self.flujos_DV01_valorizados | [
"def valoriza_flujos(self):\n\n col_tabla_aux = ['Fecha', 'Fondo', 'Tipo', 'ID', 'Hora', 'Mercado',\n 'ActivoPasivo', 'FechaFixing', 'FechaFlujo', 'FechaPago', 'Moneda', 'Flujo', 'Amortizacion',\n 'Interes', 'MonedaBase', 'Sensibilidad']\n\n tabla_aux = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Valoriza los flujos y los guarda en el atributo flujos_valorizados Si no se ha llamado al método genera_flujos puede lanzar error | def valoriza_flujos(self):
col_tabla_aux = ['Fecha', 'Fondo', 'Tipo', 'ID', 'Hora', 'Mercado',
'ActivoPasivo', 'FechaFixing', 'FechaFlujo', 'FechaPago', 'Moneda', 'Flujo', 'Amortizacion',
'Interes', 'MonedaBase', 'Sensibilidad']
tabla_aux = pd.DataFram... | [
"def genera_flujos(self):\n pass",
"def get_flujos_valorizados(self):\n return self.flujos_valorizados",
"def get_Fluksos():\n #fetch Google credentials\n gjson = c.get('metadata','json')\n gfile = c.get('metadata','file')\n json_key = json.load(open(gjson))\n scope = ['https://spre... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
this function is depricated in evaluation part of the code , please use cross_time_index only keep values that are in both timeseries with same timestamp | def cross_timeseries(series1, series2):
ts_new1 = []
val_new1 = []
ts_new2 = []
val_new2 = []
for i in range(len(series1[1])):
# for j in range(len(series2[1])):
if series1[1][i] in series2[1]:
ts_new1.append(series1[1][i])
val_new1.append(series1[0][i])
... | [
"def cross_time_index(df1, df2):\n series = pd.core.series.Series\n crossed_index = df1.index.intersection(df2.index)\n\n if type(df1) == series and type(df2) == series:\n df1 = df1[crossed_index]\n df2 = df2[crossed_index]\n elif type(df1) == series and type(df2) != series:\n df1 =... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
cross Index of Dataframe or Series to get same timestamps in both variables | def cross_time_index(df1, df2):
series = pd.core.series.Series
crossed_index = df1.index.intersection(df2.index)
if type(df1) == series and type(df2) == series:
df1 = df1[crossed_index]
df2 = df2[crossed_index]
elif type(df1) == series and type(df2) != series:
df1 = df1[crossed_... | [
"def cross_timeseries(series1, series2):\n\n ts_new1 = []\n val_new1 = []\n\n ts_new2 = []\n val_new2 = []\n\n for i in range(len(series1[1])):\n # for j in range(len(series2[1])):\n if series1[1][i] in series2[1]:\n ts_new1.append(series1[1][i])\n val_new1.append(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
creates a numpy.array of daily timestamp between date1 and date2 | def daily_date_range(date1, date2):
num_days = (date2-date1).days
return np.array([datetime(date1.year, date1.month, date1.day, 0)+timedelta(days=i) for i in range(num_days)]) | [
"def make_timeseries(self, t1, t2):\n\n # make sure the function inputs are correct\n \n if t1 >= t2:\n print('t1 must be less than t2')\n return\n\n dates, values = zip(*self.events)\n\n series = []\n t = t1\n\n # go through time period and fil... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
calculates the latest synoptic date [00, 06, 12, 18] | def latest_synop_time()-> datetime:
utc = datetime.utcnow()
if utc.hour < 1:
utc = utc - timedelta(days=1)
utc = utc.replace(hour=18)
elif utc.hour < 7:
utc = utc.replace(hour=0)
elif utc.hour < 13:
utc = utc.replace(hour=6)
elif utc.hour < 19:
utc = utc.repl... | [
"def date_of_last_manual_test(self, version: str = 'trunk') -> DateTime:\n return datetime.datetime.min",
"def latest_site_update():\n return np.datetime64(json.loads(Path('latest_vax_stats.json').read_text())['today'])",
"def define_secdate(self):\r\n \r\n # Since 2017\r\n self.s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function performs Naive Bayes prediciton on a given set of known data split into test and training data. | def naiveBayes(x_train, x_test, y_train):
gnb = GaussianNB()
y_pred = gnb.fit(x_train, y_train).predict(x_test)
return y_pred | [
"def train_and_test_with_naive_bayes(data, class_names):\n # Train data\n class_normalized_data = normalize_data(data, class_names[0])\n class_training_table = util.get_training_table(class_normalized_data, 0, get_training_index())\n class_model = nb.train(class_training_table[0], class_training_table[1... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function performs KNN prediction on a given set of known data split into test and training data. | def KNN(x_train, x_test, y_train, k=3):
knn = KNeighborsClassifier(n_neighbors=k)
knn.fit(x_train, y_train)
y_pred = knn.predict(x_test)
return y_pred | [
"def run_knn(K, train_data, train_labels, test_data):\n\n M = train_data.shape[1]\n N = test_data.shape[1]\n prediction = np.zeros(N)\n\n dist = l2_distance(test_data, train_data)\n nearest = np.argsort(dist, axis=1)[:,:]\n\n train_labels = train_labels.reshape(-1)\n test_labels = train_labels[nearest]\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a container by name, creating it if it doesn't exist yet | def get_container_by_name(self, container_name, is_source):
if container_name not in self.containers:
self.containers[container_name] = self.create_container(container_name, is_source)
return self.containers[container_name] | [
"def get_by_name(cls, context, name):\n db_container = dbapi.get_container_by_name(context, cls.container_type,\n name)\n container = cls._from_db_object(cls(context), db_container)\n return container",
"def _create_container(self, container_n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates n pairs that are pooled, i.e. there are n analytes that are mapped to m analytes, where m < n. The wells in the source container are [A1, B2, ...] | def create_pooled_pairs(self, pool_size):
source_analytes = list()
for i in range(1, pool_size + 1):
source_container = self.get_container_by_name("source{}".format(i), True)
name = "analyte{}".format(i)
analyte = self._create_analyte(True, name, Analyte)
... | [
"def get_all_mappings(W, n):\n current_W = copy.copy(W)\n all_mappings = [] # to keep all mapping arrays\n for i in range(n):\n current_W, mapping = GraphMaxPooling.one_coarsening(current_W)\n all_mappings.append(mapping)\n return all_mappings",
"def windows_of_p... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds an input analyte to the last container added | def add_input_analyte(self, name=None, analyte_id=None, input_container_ref=-1):
last_container = self.input_containers[input_container_ref]
if analyte_id is None:
analyte_id = "analyte_{}-{}".format(last_container.id, len(last_container.occupied))
if name is None:
name =... | [
"def addInput(self,input):\n self.inputs.append(input)",
"def _add(self):\n item = self._inputVar.get()\n if item != \"\":\n self._theList.insert(END, item)\n self._theList.see(END)",
"def add_input(self, input):\n self.inputs.append(input)\n input.consumers.appe... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the values required for dilution (conc and vol) to the analyte that was added last to the scenario | def dilution_vals(self, conc, vol, analyte_ref=-1):
analyte = self.analytes[analyte_ref]
if analyte.is_input:
analyte.udf_map = UdfMapping({self.conc_source_udf: conc,
"Current sample volume (ul)": vol})
else:
analyte.udf_map = U... | [
"def set_voltages(): \n #0) set parameters\n from project_parameters import trapFile,multipoleControls,reg,driveFrequency,ax,az,phi,coefs\n import pickle\n with open(trapFile,'rb') as f:\n trap = pickle.load(f)\n V,X,Y,Z=trap.instance.DC,trap.instance.X,trap.instance.Y,trap.instance.Z\n tc=... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate new plans for robot and human, set them in the corresponding trajectories, and return the robot plan. | def plan(self):
opt_r, opt_h = self.optimizer.maximize(bounds=self.bounds) # 1-D
plan_r, plan_h = opt_r, opt_h
# Update optimal control in trajectories
self.traj_r.u = plan_r # numpy robot plan
self.traj_r.u_th = plan_r # Theano robot plan
self.traj_h.u = plan_h # numpy human plan
self.traj_h.u_th = plan_... | [
"def execute_plans(robot, plans):\n # make sure the robot is actually in the home position\n # before executing a plan\n robot.mg.set_joint_value_target(\n plans[0].joint_trajectory.points[0].positions)\n robot.mg.go(wait=True)\n print(\"Moved to home, start executing task.\")\n\n # TODO qu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if rows exist in a table satisfying the given where clauses. | def exists(self, table, **where):
# Format the list of where statements
wheres = ' AND '.join([str(attr) + '=\'' + str(val) + '\'' for attr, val in where.items()])
if where:
query = 'SELECT COUNT(*) FROM "{}" WHERE {}'.format(table, wheres)
else:
query = 'SELECT ... | [
"def row_exists(self, table_name: str, id_: str) -> bool:\n table = self.metadata.tables.get(table_name)\n if table is None:\n return False\n\n query = select([func.count()]).select_from(table).where(\n table.c.doc_id == id_\n )\n with self.engine.connect() a... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Constructs a new ``MetropolisHastings`` sampler given a machine and a transition kernel. | def __init__(
self, machine, transition_kernel, n_chains=16, sweep_size=None, batch_size=None
):
self.machine = machine
self.n_chains = n_chains
self.sweep_size = sweep_size
self._kernel = transition_kernel
self.machine_pow = 2.0
super().__init__(machine,... | [
"def graph_hmc(*args, **kwargs):\n return tfp.mcmc.sample_chain(*args, **kwargs)",
"def __init__(self, machine, sample_size=16):\n super().__init__(machine, sample_size)\n if isinstance(machine, AbstractDensityMatrix):\n self.hilbert = DoubledHilbert(machine.hilbert)\n else:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The measured acceptance probability. | def acceptance(self):
return _mean(self._accepted_samples) / _mean(self._total_samples) | [
"def acceptance_fraction(self):\n return self.naccepted / self.iterations",
"def calculate_probability(self):\n return 0",
"def get_acceptance(self):\n return self.count_accepted / self.count_proposed",
"def avg_acceptance_probability(self):\n avg_ap = np.mean([c.acceptance_probabi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Snake activation function f(x) = x + sin(x)2 The function is computed used the first terms of the Taylor series decomposition | def snakeh2(x):
return x + (2 * tf.sin(0.5 * x) * tf.sin(0.5 * x)) | [
"def snake2(x):\n return x + (0.5 * tf.sin(2 * x) * tf.sin(2 * x))",
"def S_FI(FI: float) -> float:\n return 2 * np.arctan(np.tan(FI) ** 3)",
"def f(x, u, t=None):\n L = 1 # m\n x, y, θ, s = x\n \n ϕ, a = u\n f = torch.zeros(4)\n f[0] = s * torch.cos(θ)\n f[1] = s * torch.sin(θ)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Snake activation function f(x) = x + sin(x)2 The function is computed used the first terms of the Taylor series decomposition | def snake2(x):
return x + (0.5 * tf.sin(2 * x) * tf.sin(2 * x)) | [
"def snakeh2(x):\n return x + (2 * tf.sin(0.5 * x) * tf.sin(0.5 * x))",
"def S_FI(FI: float) -> float:\n return 2 * np.arctan(np.tan(FI) ** 3)",
"def f(x, u, t=None):\n L = 1 # m\n x, y, θ, s = x\n \n ϕ, a = u\n f = torch.zeros(4)\n f[0] = s * torch.cos(θ)\n f[1] = s * torch.sin(θ)\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Swish activation function f(x) = x sigmoid(x) | def swish(x):
return x * tf.sigmoid(x) | [
"def sigmoid():",
"def sigmoid_activation(X):\n return expit(X)",
"def sigmoid(x): # sigmoid activation function\n return 1 / (1 + np.exp(-x))",
"def sigmoid(x):\r\n return 1 / (1 + exp(-x))",
"def sigmoid(X,W,b):\n preActivation = np.dot(X, W) + b\n return (1.0)/(1.0 + np.exp(-preActivation... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parses a textformat proto at the given path into the given message. | def parse_text_proto_file(proto_path: str, output: message.Message) -> None:
with gfile.open(proto_path, 'r') as f:
proto_text = f.read()
text_format.Parse(proto_text, output) | [
"def read_proto_text(path, model):\n with open(path, 'r') as fp:\n Merge(fp.read(), model)\n\n return model",
"def validate_protobuf(dataset_path, message):\n modules = message.split('.')\n assert len(modules) >= 4, '{} needs to be at least 4-tuple valued'.format(message)\n try:\n top... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Read the boot code from the assembly dump. Will return a ``list`` of "instructions", i.e., a 3tuple of ``(instruction_number, opcode, arg)``. | def load_boot_code():
boot_code = []
with open("assembly.txt") as f:
for instruction_number, line in enumerate(f.readlines()):
opcode, arg = line.strip().split()
arg = int(arg)
boot_code.append((instruction_number, opcode, arg))
return boot_code | [
"def dis_lite_all(self, code, address):\n dis_gen = self.cs.disasm_lite(code, address)\n return [asm for asm in dis_gen]",
"def load(self):\n # Error handling\n if len(sys.argv) != 2:\n print(\"usage: ls8.py filename\")\n sys.exit(1)\n\n progname = sys.argv... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Execute the program, and return the value of the accumulator. If ``allow_swap`` is ``True``, then we will test the code asis and with the next ``jump`` will be converted to a ``nop`` or the next ``nop`` will be converted to a ``jump``. If we detect a loop, we will return ``None`` to indicate that. >>> instructions = [ ... | def execute(
program, instruction_ptr=0, accumulator=0, instruction_cache=None, allow_swap=True,
):
if instruction_cache is None:
instruction_cache = set()
# I'm pretty sure we just finished the program!
if instruction_ptr == len(program):
print("Finished successfully?")
return ... | [
"def run_boot_code(instructions: list) -> tuple:\n accumulator = 0\n visited_indicies = set([0])\n current_index = 0\n while True:\n try:\n operation, argument = instructions[current_index].split()\n except IndexError:\n # Indicates program ran to completion\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This is a slightly modified version of matplotlib.colors.LightSource.hillshade, modified to remove the contrast stretching (because that uses local min/max values). Calculates the illumination intensity for a surface using the defined azimuth and elevation for the light source. Imagine an artificial sun placed at infin... | def _hillshade(elevation,
azdeg=315,
altdeg=45,
vert_exag=1,
dx=1,
dy=1,
fraction=1.):
# Azimuth is in degrees clockwise from North. Convert to radians
# counterclockwise from East (mathematical notation).
az = np.radi... | [
"def get_hillshade(self,altitude = 45, angle = 315, z_exageration = 1):\n\t\t# SImply:\n\t\treturn self.cppdem.get_hillshade(altitude,angle,z_exageration)",
"def hillshade(dem, cell_size, azimuth=330, altitude=30, numt=None):\n if len(dem.shape) > 2:\n raise ValueError(f'Raster contains more than 2 dime... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns distance in metres two points at a scale in m / pixel. | def distance(a: Point, b: Point, scale: float) -> float:
x_north = a.y - b.y
y_east = b.x - a.x
return scale * math.sqrt(x_north**2 + y_east**2) | [
"def distance_in_meters(coord1, coord2):\n return vincenty(coord1, coord2).meters",
"def get_distance_in_meters(latlon1, latlon2):\n return get_distance_in_km(latlon1, latlon2) * 1000",
"def distMiles(lat1, lon1, lat2, lon2):\n return distOnUnitSphere(lat1, lon1, lat2, lon2) * 3960",
"def metal_dist(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The mid point between two points. | def mid_point(a: Point, b: Point) -> Point:
return Point((a.x + b.x) / 2, (a.y + b.y) / 2) | [
"def midpoint(p1, p2):\n mx = (p1.x + p2.x) / 2\n my = (p1.y + p2.y) / 2\n return Point(mx, my)",
"def getMidpoint(p1, p2):\r\n return(((p1[0] + p2[0]) / 2), ((p1[1] + p2[1]) / 2))",
"def midpoint(point1, point2):\n\n x, y = (int((point1[0] + point2[0]) / 2), int((point1[1] + poin... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the error estimate of distance. At +2500m to the threshold this is assumed to be 100m decreasing linearly to 10m at the threshold and thereafter. | def distance_tolerance(distance: float) -> float:
ret = 10.0
if distance < 0:
ret += distance * (100 - ret) / -2500.0
return ret | [
"def determine_cutoff_distance(self):\n \n cutoff_distance = 10.0*math.sqrt(self.mesh_one.calculate_average_element_area())\n \n return cutoff_distance",
"def raydistance_error(motiontrajectory, ptstart, ptend):\n assert len(motiontrajectory.shape) == 2\n assert motiontrajectory.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Child Key Derivation (CDK) Key derivation is normal if the extended parent key is public or child_index is less than 0x80000000. Key derivation is hardened if the extended parent key is private and child_index is not less than 0x80000000. | def ckd(xparentkey: Octets, index: Union[Octets, int]) -> bytes:
if isinstance(index, int):
index = index.to_bytes(4, 'big')
elif isinstance(index, str): # hex string
index = bytes.fromhex(index)
if len(index) != 4:
raise ValueError(f"a 4 bytes int is required, not {len(index)}")
... | [
"def ChildKey(self,\n index: int) -> 'Bip32':\n return self.__CkdPriv(index) if not self.m_is_public else self.__CkdPub(index)",
"def __CkdPub(self,\n index: int) -> 'Bip32':\n\n # Check if index is hardened\n if Bip32Utils.IsHardenedIndex(index):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Read input file, calculate its LSH and query it in the LSH database | def check_new_lsh(filename):
filename, text = utils.tokenize_file(filename)
min_hash = MinHash(num_perm=128)
for d in ngrams(text, 3):
min_hash.update(" ".join(d).encode('utf-8'))
return lsh.query(min_hash) | [
"def analyze_ls_pair(file_ch1,file_ch2,px_size,ch_actin,sigma_actin,version):\n\n # makes directory in data_dir for saving\n save_dir = file_ch1[:-4] + '_ls_data'\n uf.make_dir(save_dir)\n\n # makes a list of parameters to extract from cortex data\n data_to_write = [['basename', 'category',\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The number of quadrature points in the fixed quadrature | def num_quadrature_points(self) -> int: | [
"def getNumQuads(self):\n return len(self._quadrilaterals)",
"def get_number_of_quad_points(order):\n return points_per_order[order - 1]",
"def numberOfPoints(self):\n return 20000",
"def get_num_quadratic_variables(self):\n return len(self._quadratic)",
"def nquads(self):\n r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Widget contenant une publication, ses commentaires ainsi qu'un TextInput permettant d'y ajouter un commentaire | def __init__(self, username, publication, **kwargs):
self.register_event_type("on_add_comment")
super(FeedWidget, self).__init__(publication, **kwargs)
self.username = username
self.publication = publication
self.publicationLabel.text = "@{:s}\n{:s}".format(
publica... | [
"def post(request, post_id, suis_auteur=1):\n\n mon_post = Post.objects.get(id=post_id)\n commentaires = Commentaire.objects.filter(post__id=post_id)\n sauvegarde = False\n form = CommentaireForm(request.POST or None)\n communaute_id = mon_post.communaute.id\n\n # Permet l'affichage de la couleur ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Getter de l'attribut publication | def getPublication(self):
return self.publication | [
"def get_publication(self):\n return self.publication",
"def public(self):\n return attrs(self)",
"def ATTRIBUTE():\n return \"author\", \"title\", \"publisher\", \"shelf\", \"category\", \"subject\"",
"def __get__(self, instance, owner):\n if instance is None:\n return self... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Verify that commas are not touched when url encoding | def test_url_encoding_allows_comma(self):
api = bandcamp.Api(api_key=None)
url = 'http://api.bandcamp.com/api/track/3/info'
parameters = {'track_id': '3257270656,3467313536'}
encoded_url = 'http://api.bandcamp.com/api/track/3/info?track_id=3257270656,3467313536'
self.assertEqua... | [
"def test_dont_percent_encode_safe_chars_query():\n assert (normalize_url(\"http://example.com/a/?face=(-.-)\") ==\n \"http://example.com/a?face=(-.-)\")",
"def test_unreserved_percentencoding():\n assert (normalize_url(\"http://www.example.com/%7Eusername/\") ==\n \"http://www.example... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Device secret_id. secret_id column, if missing then device_id | def secret_id(self):
if self._secret_id:
return self._secret_id
return self.device_id | [
"def device_id(self):\n return self._id[0]",
"def get_device_id(self) -> str:\n return Config.get('device_id')",
"def get_hue_device_id(device_entry: DeviceEntry) -> str | None:\n return next(\n (\n identifier[1]\n for identifier in device_entry.identifiers\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get a Device object given its public_id or device_id. | def get_by_id(cls, public_id):
# First check public_id column, if that is not found return
# device that has device_id beginning with public_id.
if len(public_id) < 6:
raise Http404
try:
return cls.objects.get(_public_id=public_id)
except cls.DoesNotExist:... | [
"def get_device_or_None(id):\n try:\n d = Device.objects.get(id=id)\n return d\n except Device.DoesNotExist:\n return None",
"def get_device(self, device_id):\n \n for device in self.devices:\n if device.id == device_id:\n return device\n r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the Python class corresponding to this device. | def get_class(self):
return devices.get_class(self.type) | [
"def device_class(self):\n return self._device_class",
"def device_class(self):\n return self.sensor.get('class')",
"def device_class(self):\n return self.sensor_type[\"class\"]",
"def device_class(self):\n return self._sensor_type",
"def device_class(self):\n return SENSO... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create the checkpoint store if it doesn't exist. Do nothing if it does exist. | async def create_checkpoint_store_if_not_exists_async(self): | [
"def test_create_store(self):\n self._storage_clm.initialize(self._host)\n self._loop = asyncio.get_event_loop()\n self._loop.run_until_complete(self._storage_clm.create_checkpoint_store_if_not_exists_async())",
"def create_checkpoint(self):\n checkpoint_id = uuid.uuid4()\n self... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the checkpoint data associated with the given partition. Could return null if no checkpoint has been created for that partition. | async def get_checkpoint_async(self, partition_id): | [
"def get_checkpoint_data(self) -> Dict[str, Any]:\n # get ckpt file path from config.trainer.params.resume_from_checkpoint\n path = self.config.trainer.params.get(\"resume_from_checkpoint\", None)\n if path is not None:\n is_zoo = self.is_zoo_path(path)\n ckpt_filepath = p... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create the given partition checkpoint if it doesn't exist.Do nothing if it does exist. The offset/sequenceNumber for a freshlycreated checkpoint should be set to StartOfStream/0. | async def create_checkpoint_if_not_exists_async(self, partition_id): | [
"def create_checkpoint(self):\n checkpoint_id = uuid.uuid4()\n self.checkpoints.append(checkpoint_id)\n self.journal_data[checkpoint_id] = {}\n return checkpoint_id",
"def create_checkpoint(self, name, path=''):\n\n\t\tnb_path = self._get_os_path(name, path)\n\t\tself.log.debug('creati... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Update the checkpoint in the store with the offset/sequenceNumber in the provided checkpoint. | async def update_checkpoint_async(self, lease, checkpoint): | [
"def commit(self, checkpoint):\n self._validate_checkpoint(checkpoint)\n self.journal.commit_checkpoint(checkpoint)",
"def _checkpoint(self) -> None:\n if self.position is not None and self.checkpointer:\n self.checkpointer.checkpoint(self.position)\n logger.debug(f'Set ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Delete the stored checkpoint for the given partition. If there is no stored checkpoint for the given partition, that is treated as success. | async def delete_checkpoint_async(self, partition_id): | [
"def remove_checkpoint(cls, checkpoint):\n cls.log.info('Removing checkpoint: {}'.format(checkpoint))\n # TODO: remove ckpt\n cls.log.info('Checkpoint successfully removed.')\n raise NotImplementedError",
"def delete_checkpoint(self, checkpoint_id, name, path=''):\n\n\t\tcp_path = self... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return gino db connection. | async def _get_db_connection():
return await gino.Gino(get_database_dsn()) | [
"def get_connection(self):\n\n\t\treturn dbapi.connect(credentials.SERVER,\\\n\t\t\t\t\t\t\t credentials.PORT,\\\n\t\t\t\t\t\t\t credentials.USER,\\\n\t\t\t\t\t\t\t credentials.PASSWORD)",
"def connect_to_db():\n return pg.connect(DB_CONN_STRING)",
"def connect_db():\n db.connect()\n return db",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Process the products file | def process_products_file(products_df: pd.DataFrame):
products = []
file_size = len(products_df)
logging.info(f"Processing PRODUCTS.csv file... {file_size} rows")
for index, row in products_df.iterrows():
if not pd.isnull(row["NAME"]):
product = Product(sku=row["SKU"], store="Richart... | [
"def parse_products(self, infile):\r\n self._verify_version(infile)\r\n return self._find_repeated_at_header(infile, 'products')",
"def parse_products(self, cveid, products):\n data = self.build_product_lists(products)\n productrows = list()\n affectsrows = list()\n vendorrows = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Process the stock prices file | def process_stock(prices_stock_df: pd.DataFrame, sku_id_map: dict):
file_size = len(prices_stock_df)
logging.info(f"Processing PRICES-STOCK file... {file_size} rows")
# cleaning null values, since nullable is false for all columns
if prices_stock_df.isnull().values.sum() > 0:
logging.warning(f"... | [
"def get_prices(self):\n if not self._prices_cache:\n first_line = True\n with open(self._file_name, 'r') as file:\n for line in file:\n if first_line:\n first_line = False\n continue\n el... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculate distance between to earth coordinates. Result is in miles. | def earth_distance(lat1: float, lon1: float, lat2: float, lon2: float)\
-> float:
# R = 6373.0 # earth radius in km
R = 3963.0 # earth radius in miles
lat1 = radians(lat1)
lon1 = radians(lon1)
lat2 = radians(lat2)
lon2 = radians(lon2)
dlon = lon2 - lon1
dlat = lat2 - lat1
a... | [
"def distance_on_earth(a, b):\n return distance(a, b).meters",
"def _earth_distance(time='now'):\n return get_earth(time).radius",
"def delta_lat_miles(self, delta_lat):\n\n return delta_lat.dist_from_radius(EARTH_RADIUS)",
"def earth_dist_in_meters(point1, point2):\n # Convert latitude and longit... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function creates a dictionary. the keys are the US zip codes. The data is the earth coordinates of that key. | def create_zip_dict() -> dict:
with open('zip_coordinates.json', 'r') as zip_map:
return json.loads(zip_map.read()) | [
"def get_geo_hashes_map(latitude, longitude):\n geo_hashes_map = {}\n geohash = geohash2.encode(latitude, longitude)\n for i in range(1, 12):\n geo_hashes_map['hash' + str(i)] = geohash[0:i]\n return geo_hashes_map",
"def create_row_zipcode(zipcode):\n return {'concept_cd': 'AKTIN:ZIPCODE', ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds user to users_dict where phone_number is the index. | def add_phone_user(users_dict: dict, phone_number: str, radius: int,
user_zip_code: str, state: str, carrier: str,
provider_filter: list) -> None:
if user_zip_code in ZIP_MAP_DICT:
users_dict[phone_number] = {'radius': radius,
'user_z... | [
"def _add_data_to_user(self, user, number):\n self._users_numbers[user]['sum'] += number\n self._users_numbers[user]['counter'] += 1\n self._save_users_data_to_json()",
"def add_to_user_dict(user_dict, entry):\n username = entry.username\n # Try to remove the e-mail address from the use... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adds user to users_dict where email is the index. | def add_email_user(users_dict: dict, receiver_email_id: str, radius: int,
user_zip_code: str, state: str, provider_filter: list)\
-> None:
if user_zip_code in ZIP_MAP_DICT:
users_dict[receiver_email_id] = {'radius': radius,
'user_zip_code':... | [
"def add_user(self, user):\n\t\tself.users[user.username] = user",
"def add_user(self, name):\n self.users[name] = {\n \"name\":name,\n \"owes\":{},\n \"owed_by\":{},\n \"balance\":0.0\n }\n self.names.append(name)",
"def get_users_index(self)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |