query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
creates a network using the config file | def create_networks(self, force=False):
# FIXME: debugging here
logging.debug("create_networks called")
# check for an existing configuration file...
# logging.debug("networks: %s" % self.infra.get("networks"))
networks = self.infra.get("networks")
for net in networks.ke... | [
"def create_network(self):\n #Create the network\n self.network = Network(\"50.19.23.117\", 8080)",
"def _create_network(\n config_filepath, weight_filepath, conf_thresh, nms_thresh, multi=False\n):\n device = torch.device('cpu')\n if torch.cuda.is_available():\n logger.info('[lightn... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
creates ALL the machines! At the end of this function, all machines should be in either ACTIVE, BUILD, SPAWNING | def create_machines(self):
logging.debug("create_machines called")
machines = self.infra.get("servers")
for machine in machines.keys():
mconf = machines[machine]
# see if the machine is already up and running
# print mconf
uuid = mconf.get... | [
"def createMachines():\n machines = []\n for i in range(0, num_of_machines):\n cur_machine = Machine(i)\n machines.append(cur_machine)\n return machines",
"def create_virtual_machines(self):\n user_operation_commit(self.user_template, CREATE_VIRTUAL_MACHINES, START)\n storage_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
removes all the machines in this footprint. use with caution, obviously | def delete_machines(self):
logging.debug("delete_machines called")
for machine in self.machines:
logging.warn("Deleting %s" % machine)
print "Deleting %s" % machine
cs.servers.delete(self.machines[machine]) | [
"def _UpdateMachineList(self, locked_machines):\n for m in self._experiment.remote:\n if m not in locked_machines:\n self._experiment.remote.remove(m)\n\n for l in self._experiment.labels:\n for m in l.remote:\n if m not in locked_machines:\n l.remote.remove(m)",
"def purgeM... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
creates a machine using the dictionary 'mconf' | def create_machine(self, mconf):
logging.debug("create_machine called")
mconf = self.infra['servers'][machine]
logging.debug( mconf)
mnets = []
for net in mconf['networks']:
net = self.footprint_name + net
n = nets.get(net)
mnets.extend(n.get_... | [
"def create_machines(self):\n logging.debug(\"create_machines called\")\n machines = self.infra.get(\"servers\")\n \n for machine in machines.keys():\n mconf = machines[machine]\n # see if the machine is already up and running\n # print mconf\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Stops my running machines and Networks | def stop(self):
logging.debug("footprint/stop entered")
logging.info("Stopping cloud instances")
print "Stopping machines"
for machine in self.machines:
logging.debug("stopping %s" % machine)
server = self.machines[machine]
server.stop()
... | [
"def stop():\n server = current_server()\n server.stop()",
"def stop_network(self):\n self.net.stop()\n cleanup()",
"def stopServers(self):\n self.nlp.kill()\n self.semafor.kill()",
"def stop_machines(args):\n session = Session()\n finder = MachineFinder(args.finder)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
gets rid of the images that are in self.old_images | def cleanup_old_images(self):
logging.debug("%s cleanup_old_images entered" % self.footprint_name)
active_imgs = self.images.values()
old_images = self.old_images[:]
for img_id in old_images:
logging.info("Deleting image %s from footprint %s" % (img_id, self.footprin... | [
"def remove_images(self):\r\n self.canvas.delete(\"all\") # clear the canvas\r\n self.images = [] # empty all the images\r\n with self.cond_var:\r\n self.cond_var.notify()",
"def clear_images(self):\n self._images.clear()\n self.update_images_tabview()",
"def clea... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Decorator used to mark test as unstable, on failure test will be skipped | def unstable_test(reason):
def decor(f):
@functools.wraps(f)
def inner(self, *args, **kwargs):
try:
return f(self, *args, **kwargs)
except Exception as e:
msg = ("%s was marked as unstable because of %s, "
"failure was: %... | [
"def unstable(func):\n\n @functools.wraps(func)\n def new_func(*args, **kwargs):\n warnings.warn(\n \"Call to unstable API. It is expect that future API updates are possible {}.\".format(func.__name__),\n category=UserWarning, stacklevel=2)\n return func(*args, **kwargs)\n\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Moves the bat so that it's horizontal center matches the `mouse`'s x coordinate | def follow_mouse(self, mouse):
half_width = self.width() / 2
self.left = mouse.get_x() - half_width
self.right = mouse.get_x() + half_width | [
"def mouse_center():\n rect = ui.screen.main_screen().rect\n x = rect.x + rect.width / 2\n y = rect.y + rect.height / 2\n ctrl.mouse_move(x, y)",
"def center_on_mouse(w):\n root=w.get_toplevel().get_root_window()\n (screen, x, y, mod) = root.get_display().get_pointer()\n r = s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test SDPS is closed by default. | def test_open_close():
spds = SDPS(VirtualDevice(), 'MX28')
assert not spds.is_opened
spds.open()
assert spds.is_opened
spds.open()
#TODO: analyze caplog, there should be no new records
assert spds.is_opened | [
"def test_close():\n try:\n cfg = config()\n js = rs.job.Service(cfg.job_service_url, cfg.session)\n js.close()\n js.get_url()\n assert False, \"Subsequent calls should fail after close()\"\n\n except rs.NotImplemented as ni:\n assert cfg.notimpl_warn_only, \"%s \" % ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Lists the datasets of given type. | def list_datasets(self):
if self.list_type == "base":
ds = Dataset(f"{self.pool}/iocage/releases").get_dependents()
elif self.list_type == "template":
ds = Dataset(
f"{self.pool}/iocage/templates").get_dependents()
else:
ds = Dataset(f"{self.po... | [
"async def get_datasets(self) -> List[Dataset]:",
"def list_datasets(self):\n return self.parent._request('/shodan/data', {})",
"def list_datasets():\n return METADATA.keys()",
"def datasets(self):\n pass",
"def dataset_list(self):\n\n response = self.send(root_url=self.session.d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Filter out known triples. | def filter_triples(self, *triples: Optional[AnyTriples]) -> pandas.DataFrame:
df = self.df
for mapped_triples in triples:
if mapped_triples is None:
continue
df = df[
self._contains(
df=df, mapped_triples=get_mapped_triples(mapp... | [
"def filter_trips(trip):\n return list(filter(lambda x: x.building != None, trip))",
"def filter_triples(triples):\n mapped = {\"support\": \"sup\", \"attack\": \"att\"}\n for src, trg, rel in triples:\n yield src, trg, mapped[rel]",
"def prune_triples(file, worker_id):\n buf_triples_coun... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add columns indicating whether the triples are known. | def add_membership_columns(self, **filter_triples: Optional[AnyTriples]) -> pandas.DataFrame:
df = self.df.copy()
for key, mapped_triples in filter_triples.items():
if mapped_triples is None:
continue
df[f"in_{key}"] = self._contains(
df=df, mapped... | [
"def _add_necessary_columns(args, custom_columns):\n # we need to add the variant's chrom, start and gene if \n # not already there.\n if custom_columns.find(\"gene\") < 0:\n custom_columns += \", gene\"\n if custom_columns.find(\"start\") < 0:\n custom_columns += \", start\"\n \n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Finalize the result to build a score pack. | def finalize(self) -> ScorePack:
return _build_pack(result=self.result, scores=self.scores, flatten=self.flatten) | [
"def finalize_scores(self):\n if self.candidates_finalized:\n return\n self.candidates_finalized = True\n for cand in self.candidates:\n new_logp_blank = cand.logp_total()\n last_word = cand.text_state.last_word\n if self.lm is not None and last_wor... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Predict scores for triples in batches. | def _predict_triples_batched(
model: Model,
mapped_triples: MappedTriples,
batch_size: int,
*,
mode: Optional[InductiveMode],
) -> torch.FloatTensor:
return torch.cat(
[
model.predict_hrt(hrt_batch=hrt_batch, mode=mode)
for hrt_batch in mapped_triples.split(split_... | [
"def predict(self, input_batch: InputBatch) -> OutputBatch:",
"def batched_predict(model, batcher, batch_size, int_mapped_X, doc_labels):\n # Intialize batcher but dont shuffle.\n train_batcher = batcher(full_X=int_mapped_X, full_y=doc_labels,\n batch_size=batch_size, shuffle=Fals... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
read the information of the proc_card | def read_proc_card(self,proc_card,cond=''):
# Define Process
ff=open(proc_card,'r')
#read step by step
# 1) find the begin of the definition of process
# 2) read all process
# 3) find multiparticle
# 1) find the begin of the definition of process
... | [
"def read_pc(self):\n pass",
"def info(rom):\n rom = ROM(rom, detect=True)",
"def read_pc_cards(line_split, bc_class, temp_data):\n try:\n card = line_split[1]\n oc = bc_class.output_control\n if card == 'ADP':\n oc.print_adaptive_mesh = True\n elif card == 'E... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
find the pid(s) of the fist tag in text. return the text without this tag and the pid. pid is a dictonary | def first_part_pid(self,text,pid):
len_max=4
key_list=pid.keys()
while 1:
num=min(len_max,len(text))
if len_max==0:
sys.exit('error pid dico not complete or invalid input :'+str([text[:min(3,len(text))]])+'\
\n Complete proc_info... | [
"def put_pid(html):\n pid = 1\n while \"<p>\" in html:\n pttn = \"<p id=\\\"p\"+str(pid)+\"\\\">\"\n html = html.replace(\"<p>\", pttn, 1)\n pid += 1\n return html",
"def search_id(root, pid):\n for page in root.iter('page'):\n if pid == int(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Randomly sample wavelengths For the elements in the input parameters the linelist is generated by uniformly sampling n lines (from the input params) between the wavelength bounds, uniformly sampling the EP, exponentially sampling the EW. Then uses a general curveofgrowth (COG) to evaluate the loggf values for these lin... | def generate_random_linelist (teff,wv_bounds=(4500,5500),species_params=None,filepath=None):
abund_offset_range = (-1,1)
species_offset_range = (-1,1)
ew_dist_width = 30
ep_range = (0,12)
loggf_range = (-6.0,0.5)
theta = 5040.0/teff
# # TODO: remove this calculation???
# ... | [
"def gendata(params,xmin,xmax,npts=4000):\n F = lorentzian.ForwardFactory\n def gensample(F, xmin, xmax):\n from numpy import arange\n import random\n a = arange(xmin, xmax, (xmax-xmin)/200.)\n ymin = 0\n ymax = F(a).max()\n while 1:\n t1 = random.random() ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compute up to and including the numberth Fibonacci number using a tuple. | def fibonacci_tuple(number: int) -> Tuple[int]:
# TODO: Add all of the required source code for this tuple-based function
# create an empty tuple that will ultimately contain the results
result = ()
return result | [
"def fibonacci_tuple(n):\n\n (fib_n, fib_n_minus_1) = fib_tuple(n)\n\n return fib_n",
"def get_nth_fibonacci(n):\n\n if n == 0:\n return 0\n elif n == 1:\n return 1\n else:\n return get_nth_fibonacci(n - 1) + get_nth_fibonacci(n - 2)",
"def fibFN(n):\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get equivalent numpy data type. | def to_numpy(self) -> np.dtype:
return self._numpy_type | [
"def _get_numpy_datatype(self):\n\n pt = self.desc_pixelType\n\n # determine bit depth\n if \"128\" in pt:\n bits = 128\n elif \"64\" in pt:\n bits = 64\n elif \"32\" in pt:\n bits = 32\n elif \"16\" in pt... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get equivalent pandas data type. | def to_pandas(self) -> np.dtype:
return self._pandas_type | [
"def get_data_type(df, col):\n if col not in df.columns:\n raise KeyError(f'Column \"{col:s}\" not in input dataframe.')\n dt = dict(df.dtypes)[col]\n\n if hasattr(dt, \"type\"):\n # convert pandas types, such as pd.Int64, into numpy types\n dt = type(dt.type())\n\n try:\n # ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get equivalent python data type. | def to_python(self):
return self._python_type | [
"def get_data_type(self):\n return self.data_type",
"def DtypeToType(self, dtype):\n if dtype.char in np.typecodes['AllFloat']:\n return self.fs_proto.FLOAT\n elif (dtype.char in np.typecodes['AllInteger'] or dtype == np.bool or\n np.issubdtype(dtype, np.datetime64) or\n np.iss... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Deserialize from a json loaded dictionary. The dictionary is expected to contain `dtype` and `shape` keys. | def from_json_dict(cls, **kwargs):
if not {"dtype", "shape"} <= set(kwargs.keys()):
raise MlflowException(
"Missing keys in TensorSpec JSON. Expected to find keys `dtype` and `shape`"
)
tensor_type = np.dtype(kwargs["dtype"])
tensor_shape = tuple(kwargs["s... | [
"def deserialize(cls, json_):\n et_schema = cls._schema()\n dict_ = et_schema.deserialize(json_)\n d_init = {}\n\n for i_key, i_val in json_['initializers'].iteritems():\n deserial = eval(i_val['obj_type']).deserialize(i_val)\n\n if json_['json_'] == 'save':\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Deserialize from a json loaded dictionary. The dictionary is expected to contain `type` and `tensorspec` keys. | def from_json_dict(cls, **kwargs):
if not {"tensor-spec", "type"} <= set(kwargs.keys()):
raise MlflowException(
"Missing keys in TensorSpec JSON. Expected to find keys `tensor-spec` and `type`"
)
if kwargs["type"] != "tensor":
raise MlflowException("Ty... | [
"def from_json_dict(cls, **kwargs):\n if not {\"dtype\", \"shape\"} <= set(kwargs.keys()):\n raise MlflowException(\n \"Missing keys in TensorSpec JSON. Expected to find keys `dtype` and `shape`\"\n )\n tensor_type = np.dtype(kwargs[\"dtype\"])\n tensor_shap... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return true iff this schema is specified using TensorSpec | def is_tensor_spec(self) -> bool:
return self.inputs and isinstance(self.inputs[0], TensorSpec) | [
"def has_regular_shape(dataset):\n with tf.Graph().as_default():\n iterator = dataset.make_one_shot_iterator()\n example, labels = iterator.get_next()\n return all([x > 0 for x in example.shape])",
"def is_flat_spec_or_tensors_structure(spec_or_tensors):\n\n # We only have a tensor_spec_struct_or_tenso... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get list of required data names or range of indices if schema has no names. | def required_input_names(self) -> List[Union[str, int]]:
return [x.name or i for i, x in enumerate(self.inputs) if not x.optional] | [
"def _get_index_names(data, use_default=False):\n if use_default:\n try:\n single_default = 'level_0' if 'index' in data.columns else 'index'\n except AttributeError:\n single_default = 'index'\n return _fill_index_names(data.index, single_default)\n else:\n r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get list of optional data names or range of indices if schema has no names. | def optional_input_names(self) -> List[Union[str, int]]:
return [x.name or i for i, x in enumerate(self.inputs) if x.optional] | [
"def _get_index_names(data, use_default=False):\n if use_default:\n try:\n single_default = 'level_0' if 'index' in data.columns else 'index'\n except AttributeError:\n single_default = 'index'\n return _fill_index_names(data.index, single_default)\n else:\n r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return true iff this schema declares names, false otherwise. | def has_input_names(self) -> bool:
return self.inputs and self.inputs[0].name is not None | [
"def is_named(self):\n return self._name != \"\"",
"def hasname(self):\n\t\treturn self.name is not None",
"def has_schema(self, schema_name: str, **kw: Any) -> bool:\n with self._operation_context() as conn:\n return self.dialect.has_schema(\n conn, schema_name, info_cac... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convenience shortcut to get the datatypes as numpy types. | def numpy_types(self) -> List[np.dtype]:
if self.is_tensor_spec():
return [x.type for x in self.inputs]
return [x.type.to_numpy() for x in self.inputs] | [
"def _get_numpy_datatype(self):\n\n pt = self.desc_pixelType\n\n # determine bit depth\n if \"128\" in pt:\n bits = 128\n elif \"64\" in pt:\n bits = 64\n elif \"32\" in pt:\n bits = 32\n elif \"16\" in pt... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convenience shortcut to get the datatypes as pandas types. Unsupported by TensorSpec. | def pandas_types(self) -> List[np.dtype]:
if self.is_tensor_spec():
raise MlflowException("TensorSpec only supports numpy types, use numpy_types() instead")
return [x.type.to_pandas() for x in self.inputs] | [
"def dtypes(self):\n from pandas import Series\n return Series({column_name:self.data_type(column_name) for column_name in self.get_column_names()})",
"def data_all_types(df):\n \n printmd (\"**Type of every column in the data**\")\n print(\"\")\n print(df.dtypes)",
"def dtypes(self):\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert to Spark schema. If this schema is a single unnamed column, it is converted directly the corresponding spark data type, otherwise it's returned as a struct (missing column names are filled with an integer sequence). Unsupported by TensorSpec. | def as_spark_schema(self):
if self.is_tensor_spec():
raise MlflowException("TensorSpec cannot be converted to spark dataframe")
if len(self.inputs) == 1 and self.inputs[0].name is None:
return self.inputs[0].type.to_spark()
from pyspark.sql.types import StructField, Struc... | [
"def test_as_spark_schema():\n TestSchema = Unischema('TestSchema', [\n UnischemaField('int_field', np.int8, (), ScalarCodec(IntegerType()), False),\n UnischemaField('string_field', np.string_, (), ScalarCodec(StringType()), False),\n UnischemaField('string_field_implicit', np.string_, ()),\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The parameter shape. If shape is None, the parameter is a scalar. | def shape(self) -> Optional[tuple]:
return self._shape | [
"def shape(self):\n if self._shape is None:\n return None\n elif is_np_shape():\n # Parameters shouldn't be zero-size. If one of its dimension is 0,\n # it means the parameter isn't initialized. In the NumPy semantics,\n # the unknown dimension should be mar... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Deserialize from a json loaded dictionary. The dictionary is expected to contain `name`, `dtype` and `default` keys. | def from_json_dict(cls, **kwargs):
if not {"name", "dtype", "default"} <= set(kwargs.keys()):
raise MlflowException.invalid_parameter_value(
"Missing keys in ParamSpec JSON. Expected to find "
"keys `name`, `dtype` and `default`",
)
return cls(
... | [
"def deserialize(cls, json_):\n et_schema = cls._schema()\n dict_ = et_schema.deserialize(json_)\n d_init = {}\n\n for i_key, i_val in json_['initializers'].iteritems():\n deserial = eval(i_val['obj_type']).deserialize(i_val)\n\n if json_['json_'] == 'save':\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Representation of ParamSchema as a list of ParamSpec. | def params(self) -> List[ParamSpec]:
return self._params | [
"def get_params_schema(self):\n return getattr(self.signature, \"params\", None)",
"def param(self):\n parameters = []\n for layer in self.layers:\n parameters.extend(layer.param)\n return parameters",
"def get_params_as_list(self):\n\n\t\tparams = [self.shape_slope, self.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Serialize and sign a payload | def serialize_and_sign_payload(payload):
secret = workspace_config.secret
serializer = URLSafeTimedSerializer(secret)
return serializer.dumps(payload) | [
"def sign(self, payload):\n raise NotImplementedError",
"def create_payload(**kwargs):\n return signing.dumps(kwargs, salt=SALT, compress=True)",
"def sign_object(self) -> bytes:\n message = self.signed_object.econtent.signed_attrs().to_der()\n signature = self.private_key.sign(data=... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get a list of source columns needed for a list of Tranforms | def _get_cols_source(transforms: List[api.Transform]) -> List[str]:
all_names = [transform.name for transform in transforms]
all_cols = []
for transform in transforms:
for col in transform.cols_input:
all_cols.append(col)
# Dedup
all_cols = sorted(list(set(all_cols)))
cols_... | [
"def columns(self):\n return self.sources.columns",
"def static_columns(self):\n columns = [k for k,v in self._columns.items() \n if v in self.sources.columns]\n return columns",
"def _columns(cls, schema: dsl.Source.Schema) -> typing.Sequence[str]:\n return tuple(f.na... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
ap = voc_ap(rec, prec, [use_07_metric]) Compute VOC AP given precision and recall. If use_07_metric is true, uses the | def voc_ap(rec, prec, use_07_metric=False):
if use_07_metric:
# 11 point metric
ap = 0.
for t in np.arange(0., 1.1, 0.1):
if np.sum(rec >= t) == 0:
p = 0
else:
p = np.max(prec[rec >= t])
ap = ap + p / 11.
else:
# correct AP calculation
# first append... | [
"def voc_ap(rec, prec, use_07_metric=False):\n # print('voc_ap() - use_07_metric:=' + str(use_07_metric))\n if use_07_metric:\n # 11 point metric\n ap = 0.\n for t in np.arange(0., 1.1, 0.1):\n if np.sum(rec >= t) == 0:\n p = 0\n else:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns True if x is a factor of y, False otherwise. >>> is_factor(3, 6) True >>> is_factor(4, 10) False >>> is_factor(0, 5) False >>> is_factor(0, 0) False | def is_factor(x, y):
"*** YOUR CODE HERE ***"
return x != 0 and y % x == 0 | [
"def is_factor(a, b):\n q, r = divmod(b, a)\n return not r",
"def is_factor(f, n):\r\n return n%f == 0",
"def is_factor(f, n):\n\n if n//f*f == n:\n return True\n else:\n return False",
"def is_factor(num,composite):\n if insist_number([num,composite]):\n if composite % ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initialize a MultiGetBuilder class instance. | def __init__(self, get_builder: List[GetBuilder], connection: Connection):
get_names = []
super().__init__(connection)
if not isinstance(get_builder, List):
raise TypeError(f"get_builder must be of type List but was {type(get_builder)}")
for get in get_builder:
if... | [
"def __init__(self, target):\n super(MultiQuery, self).__init__()\n self.__options = {}\n self.__target = target\n self.uriBase = \"/api/mqapi2/%s\" % self.target",
"def __init__(self, gt_paths, getter):\n Loader.__init__(self)\n self.args = self._prepare_args(locals())\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
function to setup open3d Visualizer for the lidar data | def setup_visualizer(self, name = 'Lidar', width=960, height=540):
self.frame_count = 0
self.visualizer = o3d.visualization.Visualizer()
self.visualizer.create_window(
window_name=name,
width=width,
height=height,
left=int(width/2),
t... | [
"def enable3D(self):\r\n if(self.dataController.fileLoaded==True):\r\n self.dataController.toggleInteractiveMode()\r\n\r\n self.midsagittalView = False\r\n self.frontView = False\r\n self.topView = False\r\n self.bottomView = False\r\n self.threeDView = True",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
get the best trial for the specified pilot | def get_best_trial(self, pilote_indir):
directoryFiles = glob.glob(pilote_indir + '\\*\\')
current_directory = os.path.dirname(os.path.realpath(__file__))
os.chdir('{}'.format(pilote_indir))
TimeToTake = 2000
for directoryFile in directoryFiles:
fileList = glob.glob(... | [
"def _get_nearest_slot(self):\n available_slots = [pslot for pslot in self.slots.values() if pslot.available]\n if not available_slots:\n return None\n\n return sorted(available_slots, key=lambda x: x.slot_no)[0]",
"def get_best_fit(self, idx, parameter=None):\n if parameter... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a notification widget for the given Apple notification. | def create_notification_widget(
notification: Notification,
max_width: int,
max_height: int,
*,
color_count: int = 2**16
) -> PlainNotification:
# pylint: disable=unused-argument
return PlainNotification(
notification.title, notification.message, max_width, max_height
) | [
"def create_notification(self, notifying_href, notifying_action, notified_href, owner):\n if self.id == owner.id:\n return\n new_notification = Notification()\n new_notification.eid = make_uuid()\n new_notification.notifier = self\n new_notification.notifying_href = notifying_href\n new_not... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Ensure locking works with packages providing egg formats. | def test_lock_handle_eggs(PipenvInstance):
with PipenvInstance() as p:
with open(p.pipfile_path, 'w') as f:
f.write("""
[packages]
RandomWords = "*"
""")
c = p.pipenv('lock --verbose')
assert c.return_code == 0
assert 'randomwords' in p.lockfile['default']
... | [
"def test_lock():\n output = subprocess.check_output([\"poetry\", \"install\", \"--dry-run\"]).strip()\n matches = re.findall(rb\"^Warning: The lock file is not up to date .*$\", output, re.MULTILINE)\n if matches:\n logging.getLogger(__name__).warning(matches[0])\n raise RuntimeError(\"Updat... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test locking pathlib2 on python2.7 which needs `scandir`, but fails to resolve when using a fresh dependency cache. | def test_lock_missing_cache_entries_gets_all_hashes(PipenvInstance, tmpdir):
with temp_environ():
os.environ["PIPENV_CACHE_DIR"] = str(tmpdir.strpath)
with PipenvInstance(chdir=True) as p:
p._pipfile.add("pathlib2", "*")
assert "pathlib2" in p.pipfile["packages"]
... | [
"def test_multiple_file_locks(tmp_path, monkeypatch):\n monkeypatch.setenv(\"RAY_TMPDIR\", str(tmp_path))\n with TempFileLock(path=\"abc.txt\"):\n with TempFileLock(path=\"subdir/abc.txt\"):\n assert RAY_LOCKFILE_DIR in os.listdir(tmp_path)\n # We should have 2 locks, one for abc.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that locking VCS dependencies respects top level packages pinned in Pipfiles | def test_vcs_lock_respects_top_level_pins(PipenvInstance):
with PipenvInstance(chdir=True) as p:
requests_uri = p._pipfile.get_fixture_path("git/requests").as_uri()
p._pipfile.add("requests", {
"editable": True, "git": "{0}".format(requests_uri),
"ref": "v2.18.4"
})
... | [
"def test_vcs_entry_supersedes_non_vcs(pipenv_instance_pypi):\n with pipenv_instance_pypi(chdir=True) as p:\n jinja2_uri = p._pipfile.get_fixture_path(\"git/jinja2\").as_uri()\n with open(p.pipfile_path, \"w\") as f:\n f.write(\n \"\"\"\n[[source]]\nurl = \"https://pypi.or... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the ProposalDuplicatesStatus entity belonging to the given program or creates a new one. | def getOrCreateStatusForProgram(program_entity):
q = GSoCProposalDuplicatesStatus.all().filter('program', program_entity)
pds_entity = q.get()
if not pds_entity:
pds_entity = GSoCProposalDuplicatesStatus(program=program_entity)
pds_entity.put()
return pds_entity | [
"def as_proposal_duplicates(context, proposal_duplicate):\n\n context['student'] = proposal_duplicate.student\n orgs = db.get(proposal_duplicate.orgs)\n proposals = db.get(proposal_duplicate.duplicates)\n\n orgs_details = {}\n for org in orgs:\n orgs_details[org.key().id_or_name()] = {\n 'name': org... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Deletes all ProposalDuplicates for a given program. | def deleteAllForProgram(program_entity, non_dupes_only=False):
q = GSoCProposalDuplicate.all()
q.filter('program', program_entity)
if non_dupes_only:
q.filter('is_duplicate', False)
# can not delete more then 500 entities in one call
proposal_duplicates = q.fetch(500)
while proposal_duplicates:
d... | [
"def __delete_duplicates(self):\n log = logging.getLogger()\n log.debug(\"\\n---> Duplicate check <---\")\n\n chromosomes = list(set(self.chromosomes))\n diff = self.size - len(chromosomes)\n\n if diff > 0:\n log.debug(\"---> Duplicate(s) found! <---\")\n for... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Experimental general propagation command Propagate is an experimental propagation command which selects the best propagation routine automatically. The idea is to use something like the Fesnel number to select the Forvard, GForvard or the Fresnel command. Please provide us with tips to improve this command by starting ... | def Propagate(Fin,z,UseFresnel=False,UseForvard=False):
xs,ys=D4sigma(Fin)
M=10
NF=M*(((xs**4)/Fin.lam)**0.333)/z # Check with formula given by jjmelko in issue 59
#NF=xs*xs/Fin.lam/z #Check with Fresnel number
print(NF)
if Fin._IsGauss: #obvious choice ...
print('using GForvard, pure Ga... | [
"def _logp_propose(self, top_proposal, old_positions, beta, new_positions=None, direction='forward',\n validate_energy_bookkeeping=True, platform_name='CPU'):\n _logger.info(\"Conducting forward proposal...\")\n import copy\n from perses.dispersed.utils import compute_poten... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Fout = StepsLoopElim(z, nstep, refr, Fin) | def _StepsLoopElim(z, nstep, _refr, Fin):
if Fin._curvature != 0.0:
raise ValueError('Cannot operate on spherical coords.'
+ 'Use Convert() first')
if type(_refr) != _np.ndarray:
refr=_np.ones((Fin.N,Fin.N))*_refr
else:
refr = _refr
if Fin.field.sha... | [
"def step(z):\n result = np.zeros_like(z)\n result[z > 0] = 1.0\n return result",
"def factorial_loop(n):\n\n pass # @todo -fix this",
"def n_steps(self, n: int):\n z = self.__z0\n for _ in range(n):\n z = self.__call__(z, self.__c)\n return z",
"def step_back():\r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sends out currently buffered tuples into the OutStream | def send_out_tuples(self):
self._flush_remaining() | [
"def _send_output_to_buffers(self, output_msg):\n for buffer_info in self._output_buffers:\n buffer_name = buffer_info.buffer_name\n self._buffer_manager.put_force(buffer_name, output_msg)",
"def write_out_on_get_next(self, arg: Name):\n res = self.get_next(arg)\n while ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add a new data tuple to the currently buffered set of tuples | def add_data_tuple(self, stream_id, new_data_tuple, tuple_size_in_bytes):
if (self.current_data_tuple_set is None) or \
(self.current_data_tuple_set.stream.id != stream_id) or \
(len(self.current_data_tuple_set.tuples) >= self.data_tuple_set_capacity) or \
(self.current_data_tuple_size_in_by... | [
"def _append_to_write_buffer(self, data: list):\n assert isinstance(data, list)\n assert isinstance(data[0], tuple)\n assert isinstance(data[1], int)\n\n prev_name = data[0][0]\n prev_date = data[0][1]\n prev_time = data[0][2]\n prev_data1 = data[0][3]\n prev_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add a new control (Ack/Fail) tuple to the currently buffered set of tuples | def add_control_tuple(self, new_control_tuple, tuple_size_in_bytes, is_ack):
if self.current_control_tuple_set is None:
self._init_new_control_tuple()
elif is_ack and (len(self.current_control_tuple_set.fails) > 0 or
len(self.current_control_tuple_set.acks) >= self.control_tuple_set_c... | [
"def put_pending_call(self, pending_call):",
"async def ack(self, offset: int):",
"def transmitPollAck(): \n global data\n DW1000.newTransmit()\n data[0] = C.POLL_ACK\n DW1000.setDelay(REPLY_DELAY_TIME_US, C.MICROSECONDS)\n DW1000.setData(data, LEN_DATA)\n DW1000.startTransmit()",
"de... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the in_crc_errors of this EthernetInterfaceStateCounters. | def in_crc_errors(self) -> str:
return self._in_crc_errors | [
"def _get_rx_crc_error_cnt(self):\n return self.__rx_crc_error_cnt",
"def _get_error_counters(self):\n return self.__error_counters",
"def _get_rx_errors_cnt(self):\n return self.__rx_errors_cnt",
"def errorCount(self):\n return self._errors",
"def readCRCErrorCount(self):\n s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the in_crc_errors of this EthernetInterfaceStateCounters. | def in_crc_errors(self, in_crc_errors: str):
self._in_crc_errors = in_crc_errors | [
"def _set_rx_crc_error_cnt(self, v, load=False):\n if hasattr(v, \"_utype\"):\n v = v._utype(v)\n try:\n t = YANGDynClass(v,base=RestrictedClassType(base_type=long, restriction_dict={'range': ['0..18446744073709551615']}, int_size=64), is_leaf=True, yang_name=\"rx-crc-error-cnt\", rest_name=\"rx-cr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the out_mac_control_frames of this EthernetInterfaceStateCounters. | def out_mac_control_frames(self) -> str:
return self._out_mac_control_frames | [
"def out_mac_control_frames(self, out_mac_control_frames: str):\n\n self._out_mac_control_frames = out_mac_control_frames",
"def in_mac_control_frames(self) -> str:\n return self._in_mac_control_frames",
"def out_mac_pause_frames(self) -> str:\n return self._out_mac_pause_frames",
"def _g... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the out_mac_control_frames of this EthernetInterfaceStateCounters. | def out_mac_control_frames(self, out_mac_control_frames: str):
self._out_mac_control_frames = out_mac_control_frames | [
"def out_mac_control_frames(self) -> str:\n return self._out_mac_control_frames",
"def out_mac_pause_frames(self, out_mac_pause_frames: str):\n\n self._out_mac_pause_frames = out_mac_pause_frames",
"def in_mac_control_frames(self, in_mac_control_frames: str):\n\n self._in_mac_control_frames... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the in_block_errors of this EthernetInterfaceStateCounters. | def in_block_errors(self) -> str:
return self._in_block_errors | [
"def errorCount(self):\n return self._errors",
"def _get_error_counters(self):\n return self.__error_counters",
"def getNumErrors(self):\n return _libsbml.XMLErrorLog_getNumErrors(self)",
"def _get_vm_failed_states(self):\n return self.VM_FAILED_STATES",
"def read_error_count(self):\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the in_block_errors of this EthernetInterfaceStateCounters. | def in_block_errors(self, in_block_errors: str):
self._in_block_errors = in_block_errors | [
"def setInError(self):\n if self.isClosed():\n raise TransactionError(\"Cannot set a closed transaction to \"\n \"error state.\", self)\n self.state = self.STATE_INERROR",
"def error_count(self, error_count):\n\n self._error_count = error_count",
"def in_block_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the in_jabber_frames of this EthernetInterfaceStateCounters. | def in_jabber_frames(self) -> str:
return self._in_jabber_frames | [
"def in8021q_frames(self) -> str:\n return self._in8021q_frames",
"def getBitstreamFrames(self):\n \n return self.bitstream_frames",
"def event_frames(self):\n return self._event_frames",
"def frames(self) -> Optional[Tuple[int, ...]]:\n return self._frames",
"def frames(s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the in_jabber_frames of this EthernetInterfaceStateCounters. | def in_jabber_frames(self, in_jabber_frames: str):
self._in_jabber_frames = in_jabber_frames | [
"def in8021q_frames(self, in8021q_frames: str):\n\n self._in8021q_frames = in8021q_frames",
"def setBitstreamFrames(self, bitstream_frames):\n \n self.bitstream_frames = bitstream_frames",
"def in_fragment_frames(self, in_fragment_frames: str):\n\n self._in_fragment_frames = in_fragm... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the in_mac_control_frames of this EthernetInterfaceStateCounters. | def in_mac_control_frames(self) -> str:
return self._in_mac_control_frames | [
"def out_mac_control_frames(self) -> str:\n return self._out_mac_control_frames",
"def out_mac_control_frames(self, out_mac_control_frames: str):\n\n self._out_mac_control_frames = out_mac_control_frames",
"def in_mac_control_frames(self, in_mac_control_frames: str):\n\n self._in_mac_contro... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the in_mac_control_frames of this EthernetInterfaceStateCounters. | def in_mac_control_frames(self, in_mac_control_frames: str):
self._in_mac_control_frames = in_mac_control_frames | [
"def out_mac_control_frames(self, out_mac_control_frames: str):\n\n self._out_mac_control_frames = out_mac_control_frames",
"def in_mac_pause_frames(self, in_mac_pause_frames: str):\n\n self._in_mac_pause_frames = in_mac_pause_frames",
"def in_mac_control_frames(self) -> str:\n return self.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the out_mac_pause_frames of this EthernetInterfaceStateCounters. | def out_mac_pause_frames(self) -> str:
return self._out_mac_pause_frames | [
"def out_mac_pause_frames(self, out_mac_pause_frames: str):\n\n self._out_mac_pause_frames = out_mac_pause_frames",
"def in_mac_pause_frames(self) -> str:\n return self._in_mac_pause_frames",
"def out_mac_control_frames(self) -> str:\n return self._out_mac_control_frames",
"def out_mac_co... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the out_mac_pause_frames of this EthernetInterfaceStateCounters. | def out_mac_pause_frames(self, out_mac_pause_frames: str):
self._out_mac_pause_frames = out_mac_pause_frames | [
"def out_mac_pause_frames(self) -> str:\n return self._out_mac_pause_frames",
"def in_mac_pause_frames(self, in_mac_pause_frames: str):\n\n self._in_mac_pause_frames = in_mac_pause_frames",
"def out_mac_control_frames(self, out_mac_control_frames: str):\n\n self._out_mac_control_frames = ou... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the out8021q_frames of this EthernetInterfaceStateCounters. | def out8021q_frames(self) -> str:
return self._out8021q_frames | [
"def in8021q_frames(self) -> str:\n return self._in8021q_frames",
"def out8021q_frames(self, out8021q_frames: str):\n\n self._out8021q_frames = out8021q_frames",
"def _get_rx_frames(self):\n return self.__rx_frames",
"def q_states(self):\n return self._q_states",
"def _get_inactive_o... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the out8021q_frames of this EthernetInterfaceStateCounters. | def out8021q_frames(self, out8021q_frames: str):
self._out8021q_frames = out8021q_frames | [
"def out8021q_frames(self) -> str:\n return self._out8021q_frames",
"def in8021q_frames(self, in8021q_frames: str):\n\n self._in8021q_frames = in8021q_frames",
"def in8021q_frames(self) -> str:\n return self._in8021q_frames",
"def out_mac_pause_frames(self, out_mac_pause_frames: str):\n\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the in_mac_pause_frames of this EthernetInterfaceStateCounters. | def in_mac_pause_frames(self) -> str:
return self._in_mac_pause_frames | [
"def out_mac_pause_frames(self) -> str:\n return self._out_mac_pause_frames",
"def out_mac_pause_frames(self, out_mac_pause_frames: str):\n\n self._out_mac_pause_frames = out_mac_pause_frames",
"def in_mac_pause_frames(self, in_mac_pause_frames: str):\n\n self._in_mac_pause_frames = in_mac_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the in_mac_pause_frames of this EthernetInterfaceStateCounters. | def in_mac_pause_frames(self, in_mac_pause_frames: str):
self._in_mac_pause_frames = in_mac_pause_frames | [
"def out_mac_pause_frames(self, out_mac_pause_frames: str):\n\n self._out_mac_pause_frames = out_mac_pause_frames",
"def in_mac_pause_frames(self) -> str:\n return self._in_mac_pause_frames",
"def out_mac_pause_frames(self) -> str:\n return self._out_mac_pause_frames",
"def in_mac_control... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the in8021q_frames of this EthernetInterfaceStateCounters. | def in8021q_frames(self) -> str:
return self._in8021q_frames | [
"def out8021q_frames(self) -> str:\n return self._out8021q_frames",
"def in8021q_frames(self, in8021q_frames: str):\n\n self._in8021q_frames = in8021q_frames",
"def q_states(self):\n return self._q_states",
"def out8021q_frames(self, out8021q_frames: str):\n\n self._out8021q_frames... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the in8021q_frames of this EthernetInterfaceStateCounters. | def in8021q_frames(self, in8021q_frames: str):
self._in8021q_frames = in8021q_frames | [
"def out8021q_frames(self, out8021q_frames: str):\n\n self._out8021q_frames = out8021q_frames",
"def in8021q_frames(self) -> str:\n return self._in8021q_frames",
"def out8021q_frames(self) -> str:\n return self._out8021q_frames",
"def set_qinq(self, qinq):\n self.set_svlan_cvlan(qi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the in_fragment_frames of this EthernetInterfaceStateCounters. | def in_fragment_frames(self) -> str:
return self._in_fragment_frames | [
"def event_frames(self):\n return self._event_frames",
"def in8021q_frames(self) -> str:\n return self._in8021q_frames",
"def frames(self) -> Optional[Tuple[int, ...]]:\n return self._frames",
"def getBitstreamFrames(self):\n \n return self.bitstream_frames",
"def _get_tx_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the in_fragment_frames of this EthernetInterfaceStateCounters. | def in_fragment_frames(self, in_fragment_frames: str):
self._in_fragment_frames = in_fragment_frames | [
"def in8021q_frames(self, in8021q_frames: str):\n\n self._in8021q_frames = in8021q_frames",
"def in_mac_pause_frames(self, in_mac_pause_frames: str):\n\n self._in_mac_pause_frames = in_mac_pause_frames",
"def setBitstreamFrames(self, bitstream_frames):\n \n self.bitstream_frames = bi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the in_undersize_frames of this EthernetInterfaceStateCounters. | def in_undersize_frames(self) -> str:
return self._in_undersize_frames | [
"def in_undersize_frames(self, in_undersize_frames: str):\n\n self._in_undersize_frames = in_undersize_frames",
"def in_oversize_frames(self) -> str:\n return self._in_oversize_frames",
"def dropped_frames(self):\n # type: () -> int\n return self._dropped_frames",
"def in_oversize_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the in_undersize_frames of this EthernetInterfaceStateCounters. | def in_undersize_frames(self, in_undersize_frames: str):
self._in_undersize_frames = in_undersize_frames | [
"def in_oversize_frames(self, in_oversize_frames: str):\n\n self._in_oversize_frames = in_oversize_frames",
"def in_undersize_frames(self) -> str:\n return self._in_undersize_frames",
"def _set_underflow(self, v, load=False):\n if hasattr(v, \"_utype\"):\n v = v._utype(v)\n try:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the in_oversize_frames of this EthernetInterfaceStateCounters. | def in_oversize_frames(self) -> str:
return self._in_oversize_frames | [
"def in_undersize_frames(self) -> str:\n return self._in_undersize_frames",
"def in_oversize_frames(self, in_oversize_frames: str):\n\n self._in_oversize_frames = in_oversize_frames",
"def event_frames(self):\n return self._event_frames",
"def framecount(self):\n return math.ceil(l... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the in_oversize_frames of this EthernetInterfaceStateCounters. | def in_oversize_frames(self, in_oversize_frames: str):
self._in_oversize_frames = in_oversize_frames | [
"def in_undersize_frames(self, in_undersize_frames: str):\n\n self._in_undersize_frames = in_undersize_frames",
"def in_oversize_frames(self) -> str:\n return self._in_oversize_frames",
"def set_frame_size(self, frame_size_selector):\n raise NotImplementedError",
"def nb_frames(self, nb_f... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return only subset with values inside the percentile range. | def filter_percentile(df, col, up=95, down=5):
pup = np.percentile(df[col].values, up)
pdw = np.percentile(df[col].values, down)
s = (df[col]<pup) & (df[col]>pdw)
df2 = df[s]
return df2 | [
"def quietParts(data,percentile=10):\n nChunks=int(len(Y)/CHUNK_POINTS)\n chunks=np.reshape(Y[:nChunks*CHUNK_POINTS],(nChunks,CHUNK_POINTS))\n variances=np.var(chunks,axis=1)\n percentiles=np.empty(len(variances))\n for i,variance in enumerate(variances):\n percentiles[i]=sorted(variances).ind... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Computes the distance of the shortest route beween pickup and dropoff points and adds additional column for the distance and duration. | def add_shortest_route(df):
df['gmaps_dist'] = df.apply(lambda row: gmaps.getTotDist((row['pick_lon'], row['pick_lat']), (row['drop_lon'], row['drop_lat'])), axis=1)
df['gmaps_dur'] = df.apply(lambda row: gmaps.getTotDur((row['pick_lon'], row['pick_lat']), (row['drop_lon'], row['drop_lat'])), axis=1) | [
"def calc_distance_walktime(rows):\n\n route_length = 0\n walk_time = 0\n\n for row in rows:\n\n route_length += row[3]\n # calculate walk time\n if row[5] == 3 or row[5] == 4: # stairs\n walk_speed = 1.2 # meters per second m/s\n elif row[5] == 5 or row[5] == 6: #... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Filters out the entries that fall outside the given times times are defined in hours (023 h format) | def keep_daytimes(df, hours=range(0,24)):
within_hours = lambda x: x.hour in hours
df2 = df[df.pick_date.map(within_hours)]
df2 = df2[df2.drop_date.map(within_hours)]
return df2 | [
"def time_filter(target_time, format, delta_hours):\n return datetime.strptime(target_time, format) + timedelta(hours=delta_hours) >= datetime.utcnow()",
"def time_filter(time_range):\n if not time_range:\n return Q()\n times = time_range.split(\"-\")\n if len(times) != 2:\n return Q()\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retains only entries that have start and end points on keep_Manhattan | def keep_Manhattan(df):
df2 = df.apply(lambda row: gmaps.onManhattan(row['pick_lat'], row['pick_lon']), axis=1)
df2 = df2.apply(lambda row: gmaps.onManhattan(row['drop_lat'], row['drop_lon']), axis=1)
return df2 | [
"def mask_infeasible(self):\n ns = len(self)-1\n # mask entries with i+j+k > ns\n for ii in range(len(self)):\n for jj in range(len(self)):\n for kk in range(len(self)):\n if ii+jj+kk > ns:\n self.mask[ii,jj,kk] = True\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets meta information about a User. This call requires an access token. Returns a map of User Metainformation, including their name, email address and identities for scope you've initialized this client for. User's will have the ability to restrict what is being sent back, so you make no assumptions. | def get_user_info(self):
if self._access_token is None:
raise RequiresAccessTokenError()
response = self.__make_oauth_request(USER_INFO_URL, token=self._access_token, signed=True)
return simplejson.loads(response.read()) | [
"def userinfo(self, **kwargs):\n metadata = self.load_server_metadata()\n resp = self.get(metadata['userinfo_endpoint'], **kwargs)\n resp.raise_for_status()\n data = resp.json()\n return UserInfo(data)",
"def user_data(self, access_token, *args, **kwargs):\n return self.g... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieves a user's photos based on the Query passed in. This call requires an access token. | def get_photos(self,query=None):
if self._access_token is None:
raise RequiresAccessTokenError()
parameters = self.__get_default_oauth_params()
base_url = CONTENT_ROOT_URL + 'photos/'
if query is not None:
query_post = simplejson.dumps(query, cls=JSONFac... | [
"def get_user_photos(self, user_id, count = 30, page = 1):\n uri = 'users/' + user_id + '/photos'\n options = { 'per_page': count, 'page': page }\n return self.make_request(uri, options)",
"def search_photo(self, query):\n\n params = {\n 'query': query,\n 'per_page': '50'\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Pushes a list of photos for user_id specified into Trove associated to your service. This call requires an access token. Returns a map of the status of your push. | def push_photos(self, user_id, photos_list= []):
if self._access_token is None:
raise RequiresAccessTokenError()
if photos_list is None:
return
parameters = self.__get_default_oauth_params()
json_photos_list = simplejson.dumps(photos_list, cls... | [
"def get_user_photos(self, user_id, count = 30, page = 1):\n uri = 'users/' + user_id + '/photos'\n options = { 'per_page': count, 'page': page }\n return self.make_request(uri, options)",
"def _receive_photos_from_vk(self, user_id):\n vk = self._ctx['vk']\n res = vk.wall.get(owner_id=user_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets all the services Trove provides for the scope set for this client. This call requires an access token. Returns a list of service names | def get_services(self):
if self._access_token is None:
raise RequiresAccessTokenError()
response = self.__make_oauth_request(ADD_URLS_FOR_SERVICES_URL, token=self._access_token, signed=True)
return simplejson.loads(response.read()).keys() | [
"def get_services(self):\r\n return get_service_list()",
"def getServiceList(self):\n if self.verbose is True: print \"Getting list of services\"\n return self.request(\"%s/services\" % self.baseurl)",
"def get_service_token_list(self):\n run = Runrequst(self.url, self.headers)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This creates a URL that allows a user to add a service to their Trove and then immediately bounce back to your service. If a redirect_url URL is specified it uses that, otherwise it uses your application's default. This call requires an access token. Returns a onetime use URL for the user | def get_url_for_service(self, service, redirect_url=None):
if self._access_token is None:
raise RequiresAccessTokenError()
response = self.__make_oauth_request(ADD_URLS_FOR_SERVICES_URL, token=self._access_token, signed=True)
services = simplejson.loads(response.read())
... | [
"def _service_url(request, redirect_to=None):\n\n service = host_url(request, request.path)\n if redirect_to:\n if '?' in service:\n service += '&'\n else:\n service += '?'\n service += urlencode({REDIRECT_FIELD_NAME: redirect_to})\n return service",
"def get_se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A formatted string for the time | def _time_str(self):
try:
if not self._time:
raise ValueError
format_ = '%a, %d %b %Y %H:%M:%S'
return datetime.fromtimestamp(float(self._time)).strftime(format_)
except ValueError:
return plastic_date() | [
"def timestr():\n return dt.strftime(dt.now(),'%H:%M:%S')",
"def format_time(format=\"%H:%M:%S\") -> str:\n return datetime.now().strftime(format)",
"def formatted_time_now():\n now = datetime.datetime.now()\n return (now.strftime(\"%H:%M:%S\"))",
"def getTimeString():\n\tfrom time import strf... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A list of time, size and sum as strings | def strings(self):
return [str(self._time), str(self._size), str(self._sum)] | [
"def calculate_time_data(cls, time_list):\n max_val = max(time_list)\n min_val = min(time_list)\n length = len(time_list)\n sum_val = sum(time_list)\n average = sum_val / length\n data = dict(\n max_val=max_val,\n min_val=min_val,\n length=l... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Make sure all keys are in items If any key is missing add an empty signature | def pad_keys(items, keys):
for key in keys:
if key not in items:
items[key] = EmptySignature()
return items | [
"def checkInvalidKeys(self, item): \n allowedKeys = {\n 'None': [\"image\"],\n 'Empty': [\"image\"]\n }\n for key in item:\n try:\n if (item[key] == None or item[key] == \"Error\") and key not in allowedKeys['None']:\n ra... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gives a dict of default values for the default basenames | def default_values():
return pad_keys({}, default_basenames()) | [
"def get_default_paths(self):\n return {key: value.default_path for key, value in self}",
"def get_default_paths():\n DATA_ROOT = os.environ.get(\"DATA_ROOT\", \"data\")\n defaults = {\n \"TOKENIZE_DATA_DIR\": DATA_ROOT + \"/tokenize\",\n \"MWT_DATA_DIR\": DATA_ROOT + \"/mwt\",\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Write default values to the data file | def write_default_values():
values = default_values()
write_files(values, path_to_data())
return values | [
"def save_defaults(self):\n\n pass",
"def set_defaults(data: dict) -> dict:\n # Set tuning as default\n if \"tuning\" not in data:\n data.update({\"tuning\": True})\n\n # Set int8 as default requested precision\n if \"precision\" not in data:\n data.update({\"precision\": \"int8\"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Read old date, size and md5sum for those basenames If old values are not present, write defaults | def old_values(basenames):
p = path_to_data()
if not p.isfile():
if not p.parent.isdir():
p.parent.makedirs_p()
return write_default_values()
else:
return read_old_values(basenames) | [
"def _load_md5s(self) -> None:\n self._md5s = {}\n path = os.path.join(self.path, \".fairly_md5\")\n try:\n with open(path, \"r\") as file:\n reader = csv.reader(file)\n for name, date, size, md5 in reader:\n self._md5s[name] = (date, ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
takes a list mxd_lst of integers and floats | def sum_mixed_list(mxd_lst: List[Union[int, float]]) -> float:
return sum(mxd_lst) | [
"def floats(float_list):\n return [ float(number) for number in float_list ]",
"def sum_mixed_list(mxd_lst: mixed_list) -> float:\n result: float = 0\n\n for num in mxd_lst:\n result = result + num\n\n return result",
"def list2float(list):\n\n out=[]\n for i in range(0,len(list)):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Resolve a country code, either by its iso code or its real name. | def resolveCountryCode(country_code):
country_name = None
if len(country_code) > 2:
country_name = country_code
country_code = next((cc for cc, country in countries.items() if country == country_code), None)
if country_code not in countries:
logger.error("Country code %s unknown. For... | [
"def country(alpha_2_code: str) -> None:",
"def iso3166_country_code(country_name: str) -> str:\n if len(country_name) == 2 and country_name.isalpha():\n return country_name.upper()\n if (ucase_name := country_name.upper()) in country_to_iso_fixes:\n return country_to_iso_fixes[ucase_name]\n\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Execute an elasticsearch query. | def executeQuery(es_client, index_name, query):
try:
result = es_client.search(index=index_name, body=query)
except:
etype, evalue, etb = sys.exc_info()
logger.error('The query %s failed. Exception: %s, Error: %s.' % (query, etype, evalue))
sys.exit(255)
return result | [
"def query_es(base, dbid, query, headers, verbose=0):\n # see https://www.elastic.co/guide/en/elasticsearch/reference/5.5/search-multi-search.html\n headers.update(\n {\"Content-type\": \"application/x-ndjson\", \"Accept\": \"application/json\"}\n )\n uri = base + \"/api/datasources/proxy/{}/_mse... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get a list of ipaddresses via an elasticsearch query. The query needs to return the ipaddresses as first aggregated field in result['aggregations']. The easiest way to build such a query is to use the kibana facet module and copy the used query via the info button of this module. | def getIpListFromElasticsearch(query_name, min_term_count=0):
es = connect()
result = executeQuery(es, index_name, elasticsearch_queries.queries[query_name])
try:
hits = result['aggregations'].itervalues().next()['buckets']
hit_count = len(hits)
except:
logger.error("The search d... | [
"def _generate_es_query_external():\n\n internal_ips = [net[0] for service in Service.objects.all() for net in get_internal_ips(service)]\n\n query_object = {\n \"size\": 0,\n \"query\": {\n \"constant_score\": {\n \"filter\": {\n \"and\": [\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the contents of a given url and parse out all contained ip addresses. | def getIpListFromUrl(url):
ip_list = []
try:
url_content = urllib2.urlopen(url).read()
except:
etype, evalue, etb = sys.exc_info()
logger.error('Failed to retrieve ip list from %s. Exception: %s, Error: %s.' % (url, etype, evalue))
sys.exit(255)
regex_ip = re.compile('(\d... | [
"def get_and_parse_blacklist(url):\n data = urllib.request.urlopen(url).read().decode('utf-8')\n ip_addresses = re.findall(r'^[0-9]+(?:\\.[0-9]+){3}$', data, re.M)\n netblocks = re.findall(r'^[0-9]+(?:\\.[0-9]+){0,3}/[0-9]{1,2}$',\n data, re.M)\n\n return ip... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates an ipset via If the ipset already exists it will be flushed. | def createIpSetList(set_list_name):
result = subprocess.Popen("/usr/sbin/ipset list", shell=True, stdout=subprocess.PIPE).stdout.read()
if "Name: %s" % set_list_name in result:
# Flush existing set.
#result = subprocess.Popen("/usr/sbin/ipset flush %s 2>&1" % set_list_name, shell=True, stdout=su... | [
"def _create(self, name):\n command = [\n 'ipset create -exist ' + name + ' hash:net family inet maxelem 536870912',\n ]\n self.__run(command)",
"def create_ip_set(Name=None, ChangeToken=None):\n pass",
"def _add(self, name, ipset_name, ip):\n if name != 'whitelist-tota... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add a list of ip addresses to an existing ipset. | def addIpAddressesToIpSet(set_list_name, ip_addresses):
for ip_address in ip_addresses:
result = subprocess.Popen("/usr/sbin/ipset -A %s %s 2>&1" % (set_list_name, ip_address), shell=True, stdout=subprocess.PIPE).stdout.read()
if result.strip() != "":
logger.error("Could not add ip addre... | [
"def add_ips(self, ips):\n return self.bulk_create(ips)",
"def _add(self, name, ipset_name, ip):\n if name != 'whitelist-total':\n command = [\n 'ipset -exist add ' + ipset_name + ' ' + ip\n ]\n else:\n command = [\n 'ipset -exist... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Flush the iptables INPUT chain. That will effectively unblock all currently blocked ip addresses. | def unblockAll():
result = subprocess.Popen("/sbin/iptables -F INPUT 2>&1", shell=True, stdout=subprocess.PIPE).stdout.read()
if result.strip() != "":
logger.error("Could not flush INPUT chain. Error: %s." % (result))
result = subprocess.Popen("/usr/sbin/ipset destroy 2>&1", shell=True, stdout=subpr... | [
"def _flush_ip_addresses(self):\n log.debug(f\"Removing all addresses from {self.interface}\")\n ipdb = pyroute2.IPDB()\n with ipdb.interfaces[self.interface] as i:\n for addr in i.ipaddr:\n i.del_ip(*addr)",
"def flushRules(self):\n self.chain.flush()",
"def flush_arp(self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Print out a list of all configured elasticsearch queries available for selecting ip address to be blocked. | def listQueries():
for query_name in elasticsearch_queries.queries.keys():
logger.info("Query name: %s" % query_name) | [
"def getIpListFromElasticsearch(query_name, min_term_count=0):\n es = connect()\n result = executeQuery(es, index_name, elasticsearch_queries.queries[query_name])\n try:\n hits = result['aggregations'].itervalues().next()['buckets']\n hit_count = len(hits)\n except:\n logger.error(\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculates the deltas for this layer as a hidden layer. | def calcDeltaHiddenLayer(self, WeightedDelta):
return self.prevZ*(1.0-self.prevZ)*(WeightedDelta) | [
"def compute_delta_hidden_layer(self, delta_next_layer, currentLayerIndex):\n # delta_layer vector\n delta_layer = np.empty(shape=(len(self.layers[currentLayerIndex].neurons)-1))\n for h in range(len(self.layers[currentLayerIndex].neurons)-1):\n downstream = self.layers[currentLayerI... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |