query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Create a new graphpoint of the given class and id | def manage_addCustomGraphPoint(self, new_id, flavor, REQUEST=None):
exec 'import %s' % flavor
cls = eval('%s.%s' % (flavor, flavor))
gp = self.createGraphPoint(cls, new_id)
if REQUEST:
audit('UI.GraphDefinition.AddGraphPoint', self.id, graphPointType=flavor, graphPoint=gp.id)... | [
"def createGraphPoint(self, cls, newId):\n def getUniqueId(container, base):\n ids = set(container.objectIds())\n new = base\n i = 2\n while new in ids:\n new = '%s%s' % (base, i)\n i += 1\n retur... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create new graph points The migrate script graphDefinitions and friends depends on the first element in newGps being the DataPointGraphPoint when only one name is passed in dpNames. | def manage_addDataPointGraphPoints(self, dpNames=None,
includeThresholds=False,
REQUEST=None):
if not dpNames:
if REQUEST:
messaging.IMessageSender(self).sendToBrowser(
'Error',
... | [
"def manage_addDataPointsToGraphs(self, ids=(), graphIds=(), REQUEST=None):\n newGps = []\n for graphDefId in graphIds:\n graphDef = self.rrdTemplate.graphDefs._getOb(graphDefId, None)\n if graphDef:\n for dpId in ids:\n dp = self.datapoints._get... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Make sure that Threshold graph points exist for all thresholds that use the given dpName. Return a list of all graphpoints created by this call. | def addThresholdsForDataPoint(self, dpName):
from ThresholdGraphPoint import ThresholdGraphPoint
newGps = []
for thresh in self.rrdTemplate().thresholds():
if thresh.canGraph(self) \
and dpName in thresh.dsnames \
and not self.isThresholdGraphe... | [
"def getDataPointGraphPoints(self, dpName):\n from DataPointGraphPoint import DataPointGraphPoint\n return [gp for gp in self.graphPoints()\n if isinstance(gp, DataPointGraphPoint)\n and gp.dpName == dpName]",
"def isDataPointGraphed(self, dpName):\n from DataPoi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return list of rrd variable names that are defined by DEF, CDEF or VDEF statements in the rrd commands. If upToPoint is not None then only consider statements generated by graphoints where sequence < upToPoint | def getRRDVariables(self, upToPoint=None):
cmds = self.getFakeGraphCmds(upToPoint=upToPoint)
names = [line[line.find(':')+1:line.find('=')]
for line in cmds.split('\n')
if line[:line.find(':')] in ('DEF', 'CDEF', 'VDEF')]
nameSet = set(names)
resul... | [
"def get_defined_names(self):\r\n n = []\r\n for stmt in self.statements:\r\n try:\r\n n += stmt.get_defined_names(True)\r\n except TypeError:\r\n n += stmt.get_defined_names()\r\n\r\n # function and class names\r\n n += [s.name for s i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a list of DataPointGraphPoints that use the given dpName | def getDataPointGraphPoints(self, dpName):
from DataPointGraphPoint import DataPointGraphPoint
return [gp for gp in self.graphPoints()
if isinstance(gp, DataPointGraphPoint)
and gp.dpName == dpName] | [
"def isDataPointGraphed(self, dpName):\n from DataPointGraphPoint import DataPointGraphPoint\n return any(isinstance(gp, DataPointGraphPoint) and gp.dpName == dpName\n for gp in self.getGraphPoints(includeThresholds=False))",
"def addThresholdsForDataPoint(self, dpName):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get a list of all unique datapoint names | def getUniqueDpNames(self, limit=None):
dpNames = set()
limitReached = False
for t in self.dmd.Devices.getAllRRDTemplates():
for ds in t.datasources():
# If we have a broken datasource (likely from a missing zenpack)
# then don't try to parse datapoint... | [
"def get_sample_names(self):\r\n return list(self.records.sampleId.unique())",
"def getGraphPointsNames(self):\n return [gp.id for gp in self.getGraphPoints()]",
"def get_probe_names(self): \r\n return list(self.records.assayId.unique())",
"def list_unique_names(self):\n ret... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get a list of all unique threshold names | def getUniqueThresholdNames(self, limit=100):
names = set()
limitReached = False
for t in self.dmd.Devices.getAllRRDTemplates():
for thresh in t.thresholds():
names.add(thresh.id)
if len(names) >= limit:
limitReached = True
... | [
"def unique_names(self):\n return list(self._nmtensor_uniname_dict.keys()) + [\"loss\"]",
"def get_all_analysis_unique_names(self) -> List[Text]:\n return list(self._analysis_tracker.keys())",
"def metrics_names(self):\n return []",
"def get_probe_names(self): \r\n return list(s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reads in the unbinned data cube, slices it, and writes the subsampled result to a file. | def subsample():
nwav = 872
nrow = 1600
ncol = 1560
fpath = os.path.join(HYSS_ENVIRON['HYSS_WRITE'],'raw_binned/nrow1600')
fnames = ['full_frame_20ms_faster_VNIR_1600.raw',
'full_frame_20ms_faster_VNIR_1600_flat.raw']
for fname in fnames:
print("SUBSAMPLE: reading data ... | [
"def make_subcube(slice_params, path_to_file=None, hdu=None, dtype='float32',\n save=False, overwrite=True, path_to_output_file=None,\n get_hdu=False, get_data=True, get_header=True):\n print('\\nmaking subcube with the slice parameters {}...'.format(\n slice_params))\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Read in the dark file, generate a smoothed spectrum of the instrument response, and write to a file. | def get_dark():
# -- utilities
nwav = 872
nrow = 1600
ncol = 20
dpath = "../../data/middleton/night time vnir full frame"
dname = "full frame 20ms dark_VNIR.raw"
fname = os.path.join(dpath,dname)
# -- read the file
raw = 1.0*np.fromfile(open(fname,'rb'),np.uint16 \
... | [
"def __write_file(self, filename, spectrum):\n\n Freq = np.array(spectrum[\"Frequencies\"].tolist())\n Intens = np.array(spectrum[\"Intensities\"].tolist())\n file = open(filename, \"w\")\n file.write(\"Frequency (cm-1) Oscillator Strengths \\n\")\n for i in range(len(Freq)):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Script to grab the NOAA templates from the web. By default the (.xls) files are put into the HYSS_ENVIRON path NOAA_DPATH. | def get_noaa(dpath=HYSS_ENVIRON['NOAA_DPATH']):
# -- define the file list
flist = ["Oil_Lanterns_20100311.xls",
"Pressurized_Gas_Lanterns_20100311.xls",
"Incandescent_Lamps_20100311.xls",
"Quart_Halogen_Lamps_20100311.xls",
"Mercury_Vapor_Lamp_20100311.xls",
... | [
"def DownloadTemplate(template):\n\n\tpdbl = PDBList()\n\tpdbl.retrieve_pdb_file(template, obsolete=False, pdir=\"./\", file_format=\"pdb\")",
"def create_NAEI_data_template(headers,Global_Atts):\n\n (lat4,lon4,east4,north4) = calculate_lat_lon_grids(headers)\n\n #%% start creation of the dataset which will... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Estimate the noise in a spectrum by computing the noise in the derivative spectrum. This function takes the derivative of an input spectrum and estimates the noise over a specified index range. | def estimate_noise(spec, ind_range=None):
# -- set the index range (nb, ends at len(spec)-1 since the derivative has
# one fewer points than the spectrum).
ind_range = ind_range if ind_range else [0,spec.shape[0]-1]
# -- compute the derivative and estimate the noise over the range
noise = (spec... | [
"def generate_overf_noise(amp, index, f0, dt, n):\n\n white_noise = rand.normal(size=n)\n power_spectrum = overf_power_spectrum(amp, index, f0, dt, n)\n # Power spectrum is in physical units of T**2/Hz. Put in discrete units by\n # multiplying by twice the bandwidth.\n power_spectrum *= 1.0/dt\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Decode int from bytes. | def IntDecode(int_bytes: bytes) -> int:
return ed25519_lib.int_decode(int_bytes) | [
"def decode_int(bytes: bytearray) -> int:\n return int.from_bytes(bytes, INT_ENCODING)",
"def _decode_int(data: BencodedString) -> int:\n data.del_prefix(1)\n end_marker_index = data.bytes.find(END_MARKER)\n\n if end_marker_index > 0:\n result_bytes = data.get_prefix(end_marker_index)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Encode int to bytes. | def IntEncode(int_val: int) -> bytes:
return ed25519_lib.int_encode(int_val) | [
"def encode_int(i: int, nbytes: int, encoding: str = 'little') -> bytes:\n return i.to_bytes(nbytes, encoding)",
"def _encode_int(source: int) -> bytes:\n return b\"i\" + str(source).encode(\"ascii\") + b\"e\"",
"def encode_int(n):\n return struct.pack(\">I\", n)",
"def int_to_bytes(i: int) -> bytes:... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convert rststyle sections into custom directives that ONLY insert the HTML header tags. | def convertSections(tabContent):
return PAT_RST_SECTION.sub(
lambda match: HEADING_TEMPLATE_RST.format(template.Options.HEADING_LEVELS.index(match.group(2)[0]) + 1, match.group(1)),
tabContent) | [
"def convert_headers(mkd):\n\t\n\tfor md_code in re.findall(r\"^#####[^#].*\", mkd, re.M):\n\t\ttex_code = \"\\subparagraph{\" + re.findall(r\"#####(.*)\", md_code, re.M)[0] + \"}\"\n\t\tmkd = mkd.replace(md_code, tex_code)\n\n\tfor md_code in re.findall(r\"^####[^#].*\", mkd, re.M):\n\t\ttex_code = \"\\paragraph{\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Produce all possible outcomes of n dsided dice, which obey the statistics of a particle of a given type. | def throw_table(n, d=6, type='classical'):
table = None
roll = range(1, d+1)
if type == 'classical':
table = list(itertools.product(roll, repeat=n))
else:
table = list(itertools.combinations(roll, n))
if type == 'bosonic':
# TODO: This only works for 2 dice!!!!
... | [
"def get_outcomes(num_die_sides):\n outcomes = []\n\n for value in range(1, num_die_sides + 1):\n outcomes.append(value)\n\n return outcomes",
"def get_outcomes(num_die_sides):\n outcomes = []\n\n for value in range(1, num_die_sides + 1):\n outcomes.append(value)\n\n return outcome... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculate the probability of a given throw. | def prob(throw, n, d=6, type='classical'):
count = 0
table = throw_table(n, d, type)
for t in table:
if sum(t) == throw:
count += 1
return float(count)/len(table) | [
"def calculate_probability(self):\n return 0",
"def probability_of(self, conditions):\n return self.distribution.probability_of(conditions)",
"def calcProbability(self, look, hit, nohit, hit_count, denominator):\n\n try:\n combination = calcCombination(look, hit_count)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Run test on data using MDCAS classifier | def test(ctx, input_file, model, output_file):
# parse extra input args
kwargs = {ctx.args[i][2:]: ctx.args[i+1].strip('"') for i in range(0, len(ctx.args), 2)}
if 'use_groups' in kwargs:
if kwargs['use_groups']:
no_groups = 0
else:
no_groups = 1
else:
no_... | [
"def test_svm_classifier_manual_test_set(self):\n\n classname = 'Soluble'\n dataframe = sdf_to_csv(\n self.sdf_file_path, self.fingerprints, class_name_list=classname)\n manual_test_dataframe = sdf_to_csv(\n self.manual_test_file_path, self.fingerprints,\n class... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sorts list Calls basic_list_exception.make_list(). The return is assigned variable name fun_list. Fun_list is sorted and returned. | def sort_list():
fun_list = basic_list_exception.make_list()
fun_list.sort()
return fun_list | [
"def sort_list(self,list_):\r\n list_.sort()",
"def sort_list(self, list_):\n self._validate_list(list_)\n list_.sort()",
"def sorted_list(original_function):\n def sl_function(*args, **kwargs):\n struct = original_function(*args, **kwargs)\n\n if struct is None:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the index of the desired list item Calls basic_list_exception.make_list(). This return is assigned variable name fun_list. Parameter 'search' is searched for in fun_list and the index returned. An invalid search will return 1. This function will only return the first occurrence of the desired item. Multiple occ... | def search_list(search):
fun_list = basic_list_exception.make_list()
for x in range(len(fun_list)):
try:
location = fun_list.index(search)
return location
except ValueError:
return -1 | [
"def find(l,func):\n for i,item in enumerate(l):\n if func(item):\n return i\n return -1",
"def _search_for_first_match(self, search_list):\n for item in search_list:\n ind = self._search_for_label(item, print_msg=False)\n if ind is not None:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Render a template asynchronously. Can only be used within async functions. | async def render(
self, filename: str, *args: dict, **kwargs: typing.Any
) -> str:
with self._enable_async():
return await self._get_template(filename).render_async(
*args, **kwargs
) | [
"async def render(tpl, **kwargs) -> object:\n template = env.get_template(tpl)\n content = await template.render_async(kwargs)\n return html(content)",
"def render_sync(\n self, filename: str, *args: dict, **kwargs: typing.Any\n ) -> str:\n return self._get_template(filename).render(*arg... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Render a template synchronously. See Also [Templates.render](render) for the accepted arguments. | def render_sync(
self, filename: str, *args: dict, **kwargs: typing.Any
) -> str:
return self._get_template(filename).render(*args, **kwargs) | [
"async def render(tpl, **kwargs) -> object:\n template = env.get_template(tpl)\n content = await template.render_async(kwargs)\n return html(content)",
"async def render(\n self, filename: str, *args: dict, **kwargs: typing.Any\n ) -> str:\n with self._enable_async():\n return... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Open a file and its directory. The file is opened in binary mode and created if it does not exist. Both file descriptors must be closed after use to prevent them from leaking. | def open_file_in_dir(path: str) -> Tuple[io.FileIO, int]:
directory = os.path.dirname(path)
if not os.path.isdir(directory):
raise ValueError('No directory {}'.format(directory))
if not os.path.exists(path):
file_fd = open(path, mode='x+b', buffering=0)
else:
file_fd = open(path... | [
"def _open(self, path, mode='r'):\n # auto-create directory in write modes\n if ('w' in mode) or ('a' in mode):\n dirname = os.path.dirname(path)\n if not os.path.exists(dirname):\n os.makedirs(dirname)\n # support compression\n if path.endswith('.gz'... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check that the interaction accepts a 'name' argument and has a 'name' attribute. | def test_interaction_accepts_name():
demag = ThinFilmDemag()
assert hasattr(demag, 'name') | [
"def test_interaction_accepts_name():\n dmi = DMI(1)\n assert hasattr(dmi, 'name')",
"def test_args_valid_name(self):\n output = addr.args_valid(name='someBox', addr=None, component=None)\n\n self.assertTrue(output)",
"def checkName(self, event=None):\r\n self.Validate()",
"def test... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reset the error for integral sum so it doesn't run away | def reset_sum(self):
self._error_sum = 0 | [
"def reset(self):\n self.integral = 0.0\n self.previous_error = 0.0",
"def update_error_integral(self):\n\t\tself.integral_error += self.error * self.Ts",
"def reset(self):\n self.integrated_error = 0.0\n self.last_error = 0.0\n self.last_var_desired = 0.0",
"def reset_sum(s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Remove the columns from dataset DataFrame that are specified in drop_list and convert to numpy array loaded in data | def drop_dfcol(self, drop_list):
self.data = self.df
for lbl in drop_list:
self.data = self.data.drop(lbl, axis=1)
self.n_features = np.shape(self.data)[1] | [
"def preprocessData(df, removeCols):\n\tdf1=df.drop(removeCols, axis=1)\n\t\t\n\treturn df1",
"def features_dataset(self):\n df = self.get_prepared_df()\n features= df.drop('price', axis = 1)\n features = np.array(features) \n \n return features",
"def load_data(csv,drop_colum... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function returning the next batch When dataset has been fully fetched, a permutation is done By default, the labels will be onehot encoded | def get_next_batch(self, onehot=True):
if self.current_batch_idx == 0:
self.permutation()
next_beg = self.current_batch_idx * self.batch_size
next_end = (self.current_batch_idx + 1) * self.batch_size
if next_end > self.n_samples:
next_end = self.n_samples
... | [
"def _next(self):\n batch_start, batch_end = self.batch_start, self.batch_start + self.batch_size\n if batch_end > self.X.shape[0]:\n self.shuffle()\n return self._next()\n else:\n batch_indices = self.indices[batch_start:batch_end]\n X_batch, y_batch... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Run permutations in the dataset to ensure that the different extracted sets will contain all type of labels | def permutation(self):
perm = np.random.permutation(self.n_samples)
self.data = self.data.iloc[perm]
self.labels = self.labels.iloc[perm]
self.labels_onehot = self.labels_onehot.iloc[perm]
self.df_perm = self.df_perm.iloc[perm] | [
"def label_permutation_test(model_dir):\n\n with open(os.path.join(model_dir, 'config.yaml')) as file:\n cfg = yaml.full_load(file)\n\n graph_name = cfg['graph_name']['value']\n conv_type = cfg['model']['value']\n\n n_conv_layers = cfg['n_conv_layers']['value']\n layer_sizes = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Split dataset in n_subset parts and create as many dataset objects containing samples of original dataset chosen randomly with replacement | def random_sampling(self, n_subset):
t = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
print("[INFO] {} - Random sampling with replacement ...".format(t))
subset_list = []
training_set = self
subset_size = math.ceil(training_set.n_samples / n_subset)
# create subsets
... | [
"def subsample_data(dataset, n_data, subset_idx):\n\n if n_data is None:\n return dataset\n\n else:\n if subset_idx == -1:\n import numpy as np\n np.random.seed(0)\n subset = list(np.random.permutation(len(dataset))[:n_data])\n else:\n subset = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Clip values a DataFrame | def clip(df, clip_val_low, clip_val_high):
clipped_df = df.clip(lower=clip_val_low, upper=clip_val_high)
return clipped_df | [
"def clip(df, lower, upper):\n\n # Pandas' clip-function doesn't allow dicts with bounds for only some\n # columns, so we convert them to Pandas Series which is allowed.\n if isinstance(lower, dict):\n lower = pd.Series(lower)\n if isinstance(upper, dict):\n upper = pd.Series(upper)\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Quantize in 8bit integer the input DataFrame | def quantize(self, df):
if len(self.dict_scalers) == 0:
raise Exception("[ERROR] quantize method called prior to"
"normalization transform method ")
quant_df = pd.DataFrame()
if 'OneForAll' in self.dict_scalers:
# quantization is applied on al... | [
"def quint8(scale, zero_point):\n return create_quantized_dtype(_builtin_quant_dtypes[\"quint8\"], scale, zero_point)",
"def qint8(scale):\n return create_quantized_dtype(_builtin_quant_dtypes[\"qint8\"], scale, None)",
"def quantize_row_q8_K(x: ffi.CData, y: ffi.CData, k: int) -> None:\n ...",
"def ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set parameters specific to the optimizer and configure accordingly the optimizer | def set_optimizer_params(self):
n_params = len(self.optim_params)
if self.optimizer_name == 'GradientDescent' and n_params == 1:
self.optimizer = tf.keras.optimizers.SGD(
learning_rate=self.optim_params[0],
momentum=0)
elif self.optimizer_name == 'Mome... | [
"def set_optimizer(self, optimizer):\n\n pass",
"def setOptimizerParams(self,lr,momentum,decay):\n self.optimizer = SGD(lr=lr,momentum=momentum,decay=decay)",
"def define_optimizer(self):\n raise NotImplementedError",
"def _set_optimizer(self):\n\n if self.optimizer_name == 'Adam':... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a tensorflow layer Returns | def create(self):
output = None
if self.output_bias is not None:
output_bias = tf.keras.initializers.Constant(self.output_bias)
else:
output_bias = None
kernel_init = None
if self.activation_name == 'relu' or self.activation_name == 'elu':
# K... | [
"def fc_layer(scope, input_layer, n_outs):\n with tf.variable_scope(scope):\n n_ins = input_layer.shape.as_list()[-1]\n W = tf.Variable(tf.random_normal([n_ins, n_outs]), name='weights')\n b = tf.Variable(tf.zeros([n_outs]), name='bias')\n output = tf.nn.xw_plus_b(input_layer, W, b, n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add a layer in the topology description | def add_layer(self, layer):
idx = len(self.dict_topo)
idx += 1
self.dict_topo[idx] = layer | [
"def AddLayer(self, layer):\n pass",
"def add(self, layer):\n self._top = layer(self._top)\n layer_name_ = layer.__class__.__name__\n layer_params_ = layer.params\n self._info.append((layer_name_, layer_params_))",
"def add_layer(self, layer):\n self.__layers.append(layer)",
"def add(s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Patch method on the CTC loss function. | def replacement_ctc(self, model, target, output):
if model.get_backend().get_name() == 'pytorch':
pytest.xfail('Backend "pytorch" does not use a CTC loss function.')
return replacement_ctc.original(self, model, target, output) | [
"def loss(self):\n pass",
"def ctc_loss_lambda_func(args):\n\n y_pred, labels, input_length, label_length = args\n return K.ctc_batch_cost(labels, y_pred, input_length, label_length)#, ignore_longer_outputs_than_inputs=True)",
"def compute_ctc_loss(criterion, ip, tgt, tgt_lens):\n ip_len... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Prepares the distribution to be used later in KS and CvM, merges equal data, computes (summed) weights and cumulative distribution. All output arrays are of same length and correspond to each other. | def prepare_distibution(data, weights):
weights = weights / numpy.sum(weights)
prepared_data, indices = numpy.unique(data, return_inverse=True)
prepared_weights = numpy.bincount(indices, weights=weights)
prepared_cdf = compute_cdf(prepared_weights)
return prepared_data, prepared_weights, prepared_cd... | [
"def _build_precomputed_data(self):\n if self.num_sampled == 0:\n self._K_chol = numpy.array([])\n self._K_inv_y = numpy.array([])\n else:\n covariance_matrix = python_utils.build_covariance_matrix(\n self._covariance,\n self._points_sampl... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
For arbitrary number of variables computes the indices of data, the indices are unique numbers of bin from zero to \prod_j (len(bin_limits[j])+1) | def compute_bin_indices(X_part, bin_limits=None, n_bins=20):
if bin_limits is None:
bin_limits = []
for variable_data in range(X_part.shape[1]):
bin_limits.append(numpy.linspace(numpy.min(variable_data), numpy.max(variable_data), n_bins + 1)[1: -1])
bin_indices = numpy.zeros(len(X_p... | [
"def bin_index(x, n_bins):\n assert(torch.min(x) >= 0 and torch.max(x) <= 1)\n cdf = torch.arange(n_bins, dtype=torch.float32, device=x.device)\n cdf.add_(1).div_(n_bins)\n mask = (x.view(-1,1).repeat((1, n_bins)) > cdf)\n return torch.sum(mask, dim=1)",
"def bin_index(xbins,ns,p,value):\n\n\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Transforms bin_indices into group indices, skips empty bins | def bin_to_group_indices(bin_indices, mask):
assert len(bin_indices) == len(mask), "Different length"
bins_id = numpy.unique(bin_indices)
result = list()
for bin_id in bins_id:
result.append(numpy.where(mask & (bin_indices == bin_id))[0])
return result | [
"def groupDigitized(arr, bins, edges='right'):\n edges = edges.lower()\n if edges.startswith('r'): right = True\n elif edges.startswith('l'): right = False\n else: RuntimeError(\"``edges`` must be 'right' or 'left'!\")\n\n # `numpy.digitize` always assumes `bins` are right-edges (in effect)\n shif... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Computes cumulative distribution function (CDF) by ordered weights, be sure that sum(ordered_weights) == 1 | def compute_cdf(ordered_weights):
return numpy.cumsum(ordered_weights) - 0.5 * ordered_weights | [
"def cdf(weights):\r\n\treturn np.cumsum(weights) / sum(weights)",
"def get_ecdf(\n sample: np.ndarray,\n weights: Optional[np.ndarray] = None\n ) -> Tuple[np.ndarray, np.ndarray]:\n\n assert len(sample.shape) == 1, \"Only 1D CDF is implemented\"\n\n if weights is None:\n weights = n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Group weight = sum of divided weights of indices inside that group. | def compute_group_weights(group_indices, sample_weight):
divided_weight = compute_divided_weight(group_indices, sample_weight=sample_weight)
result = numpy.zeros(len(group_indices))
for i, group in enumerate(group_indices):
result[i] = numpy.sum(divided_weight[group])
return result / numpy.sum(r... | [
"def group_weight(group):\n weight_sum = 0\n for comp in weight_store:\n if determine_group(group, comp['group']):\n weight_sum = weight_sum + comp['weight']\n return weight_sum",
"def group_weight(self):\r\n return self._group_weight",
"def group_weights(self):\n return... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Efficiency of bin = total weight of (signal) events that passed the cut in the bin / total weight of signal events in the bin. Returns small negative number for empty bins | def compute_bin_efficiencies(y_score, bin_indices, cut, sample_weight, minlength=None):
y_score = column_or_1d(y_score)
assert len(y_score) == len(sample_weight) == len(bin_indices), "different size"
if minlength is None:
minlength = numpy.max(bin_indices) + 1
bin_total = numpy.bincount(bin_ind... | [
"def computeBinWidth(self):\n self.binWidth = (self.data[-1] - self.data[0]) / self.numBins\n # Fill the frequencies array with zero\n for i in range(self.numBins):\n self.frequencies.append(0)",
"def bin_width(self):\n return self.bins[2] - self.bins[1]",
"def n_bins(self... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
KolmogorovSmirnov flatness on groups | def groups_based_ks(y_pred, mask, sample_weight, groups_indices):
assert len(y_pred) == len(sample_weight) == len(mask)
group_weights = compute_group_weights(groups_indices, sample_weight=sample_weight)
prepared_data, prepared_weight, prep_F = prepare_distibution(y_pred[mask], weights=sample_weight[mask])
... | [
"def test_ks_test(mode):\n indices = np.random.randint(0, 1000, 1000)\n out = compute_indices_ks_test(indices, 1000, mode=mode)\n assert all([o > 0.0 for o in out])",
"def test_kolmogorov_smirnov_fails():\n strat = FloatStrategy(0, 10, 8)\n data = [strat.do_draw(None) for x in range(10000)]\n ar... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create new customer until the sim time reaches 120. with poisson process | def customer_arrivals(env,n_customer,res_counter,kitchen,parameters,result_fifo):
for i in range(n_customer):
yield env.timeout(random.poisson(1/parameters['lamb']))
env.process(customer(env, i+1, res_counter, kitchen,parameters, result_fifo)) | [
"def customer_generator(env, run_time, order_station_1, order_station_2, pickup_window, number_of_customers, order_station_number):\n number_of_customers += 1\n c = customer(env, 'Customer%02d' % number_of_customers, order_station_1, order_station_2, pickup_window, order_station_number)\n env.process(c)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parses a textual table that the console commands generate. Each row is converted into a dictionary. | def _parse_table(value):
lines = value.split('\n')
header = None
rows = []
for l in lines:
if l.startswith('+-'):
pass
elif l.startswith('|'):
columns = [c.strip() for c in l.split('|')[1:-1]]
if header is None:
header = columns
... | [
"def _parse_table(text):\n\n text = str(text)\n try:\n text = text.split(\"<pre>\")[1]\n text = text.split(\"</pre>\")[0]\n text = text.split(\"To save this output\")[0]\n lines = text.split(\"\\n\")\n except Exception as exc:\n raise NNDCRequestError(f\"Unable to parse t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Hull has a chance of being breached if less than the dangerzone. Chance of survival is determined by how much % hull remains. Returns input hull amount if RNG thinks it should, otherwise 0. | def hull_breach(hull, max_hull, damage,
hull_danger_zone=HULL_DANGER_ZONE):
damaged_hull = hull - damage
chance_of_survival = damaged_hull / max_hull
return not (chance_of_survival < hull_danger_zone and
chance_of_survival < random.random()) and damaged_hull or 0 | [
"def solidity(cnt,hull):\n return area(hull) / area(cnt)",
"def convexity(cnt,hull):\n return perimeter(hull) / perimeter(cnt)",
"def attack_success(self) -> float:\n return (0.5 * (1 + self.health / 100) *\n random.randint(50 + self.experience, 100) / 100)",
"def starve_checker(hu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check whether the damage has enough power to damage the shield or just harmlessly bounce off it, only if there is a shield available. Shield will be returned if the above conditions are not met, otherwise the current shield less damage taken will be returned. Returns the new shield value. | def shield_bounce(shield, max_shield, damage,
shield_bounce_zone=SHIELD_BOUNCE_ZONE):
# really, shield can't become negative unless some external factors
# hacked it into one.
return ((damage < shield * shield_bounce_zone) and shield > 0 and
shield or shield - damage) | [
"def shield(self) -> Union[int, float]:\n return self.proto.shield",
"def shield_percentage(self) -> Union[int, float]:\n if not self.proto.shield_max:\n return 0\n return self.proto.shield / self.proto.shield_max",
"def can_take_damage(self):\n result = True\n if s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculates damage factor on size. If weapon size is greater than the target size, then only the area that falls within the target will the damage be applied. | def size_damage_factor(weapon_size, target_size):
if weapon_size <= target_size:
return damage
return (target_size ** 2) / (weapon_size ** 2) | [
"def dmg_mult(self, target=None):\n mast_mult = Damage(self.masterypage.perc_dmg_out,\n self.masterypage.perc_dmg_out)\n if target is not None:\n mast_mult += Damage(target.masterypage.perc_dmg_in,\n target.masterypage.perc_dmg_in)\n\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Simple check to see if ship is alive. | def is_ship_alive(ship):
# If and when flag systems become advanced enough **FUN** things can
# be applied to make this check more hilarious.
return ship.attributes.hull > 0 # though it can't be < 0 | [
"def is_alive(self):\r\n if self.health > 0 and self.life_span > 0:\r\n return True\r\n else:\r\n return False",
"def has_active_ship(self):\n if self.mark in (constants.ACTIVE_SHIP_MARK, constants.HIT_SHIP_MARK):\n return True\n return False",
"def i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retuns a dict of applied debufs calculated from ship schema as well as ship attributes. Source is ShipSchema target_in is a Ship | def grab_debuffs(source, target_in):
inactive = {}
sensor_str = target_in.schema.sensor_strength
target = target_in
# I'm sure there's a list comprehension thing that could be used
# to clean this up but I have no idea what
if source.target_painter:
if target.debuffs.get('inactive', {}).... | [
"def get_updated_decl(\n config: Dict,\n inbound_external_streams: List[str],\n outbound_external_streams: List[str],\n):\n io_decl = {}\n external_wire_decl = {}\n internal_wire_decl = {}\n\n def _update_decl(stream, port):\n wire_name = config['edges'][stream]['port_wire_map'][port]\n width = config[... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Do a ship attack. Apply the attacker's schema onto the victim_ship as an attack and return a new Ship object as the result. | def ship_attack(attacker_ship, victim_ship):
if not is_ship_alive(victim_ship):
# save us some time, it should be the same dead ship.
return victim_ship
if attacker_ship.debuffs.get('active', {}).get('ECM', 0) != 0:
# attacker is jammed can't attack or apply debuffs
return vict... | [
"def attack(self, ship_id, target_id):\n\n # Perfom attack\n attack_string = \"SELECT ATTACK(\" + str(ship_id) + \",\" + str(target_id) + \");\"\n self.conn_cur.execute(attack_string)\n print(\"[>] Attack ordered\")",
"def attack(self,otherObject):\n\t\t\n\t\tif self is otherObject:\n\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Prune an AttackResult of dead ships and restore shields/armor. Returns the pruned fleet and a count of ships. | def prune_fleet(attack_result):
fleet = []
count = {}
damage_taken = 0
for ship in attack_result.damaged_fleet:
if not ship.attributes.hull > 0:
continue
updated_debuffs = {}
if ship.debuffs.get('inactive'):
updated_debuffs['active'] = ship.debuffs.get(... | [
"def shotResult(self, shot, hit, sunk):\r\n logging.debug(\"shot result: %s, hit: %d, sunk: %d\" % (shot, hit, sunk))\r\n coordinates = self.mapToCoordinates(shot)\r\n # If a ship was sunk, remove it from the fleet.\r\n if sunk:\r\n sunk = str(sunk)\r\n assert(self.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
returns two sub_fleets of logi ships that can rep | def logi_subfleet(input_fleet):
logi_shield = []
logi_armor = []
for ship in input_fleet:
if ship.debuffs.get('active', {}).get('ECM', 0) != 0:
# can't target to apply repairs
continue
if ship.schema.remote_shield:
logi_shield.append(ship)
if ship.sche... | [
"def identify_lipid_leaflets_legacy(pts,vec,monolayer_cutoff,\n\tmonolayer_cutoff_retry=True,max_count_asymmetry=0.05,pbc_rewrap=True,\n\ttopologize_tolerance=None,topologize_time_limit=30):\n\t#---previous default was somewhat high, but typically came in from specs, and we reduced it incrementally\n\tif monolayer_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Have logistics ships do their job and repair other ships in the fleet | def repair_fleet(input_fleet):
logistics = logi_subfleet(input_fleet)
logi_shield = logistics[0]
logi_armor = logistics[1]
if (logi_shield == []) and (logi_armor == []):
return input_fleet
damaged_shield = []
# I have a bad feeling that this function won't last longer
# than a sing... | [
"def repair(self):\n\t\tfor ship in self.states['shiplist']:\n\t\t\tship.repair\n\t\t\t\n\t\texisting_Fleets.extend([self])\n\t\treturn 'Whee'",
"def setRepairCost(self):\n # first take into account the ship hull which is based on internal structure points\n ratio = 1.0 - (self.currentISP/self.myShi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Do a round of fleet attack calculation. Send an attack from fleet_a to fleet_b. Appends the hit_by attribute on the victim ship in fleet_b for each ship in fleet_a. | def fleet_attack(fleet_a, fleet_b):
# if fleet b is empty
if not fleet_b.ships:
return AttackResult(fleet_a, fleet_b.ships, 0, 0)
result = []
result.extend(fleet_b.ships)
shots = 0
damage = 0
for ship in fleet_a.ships:
firing = True
# I kind of wanted to do apply a... | [
"def attack(self, from_id, to_id, count):\r\n\r\n\t\tret = {}\r\n\r\n\t\t# Chances to destroy one fleet\r\n\t\tatk_chance = Constants.DESTROY_CHANCE['attacker']\r\n\t\tdef_chance = Constants.DESTROY_CHANCE['defender']\r\n\r\n\t\tfrom_planet = self.planets[from_id]\r\n\t\tto_planet = self.planets[to_id]\r\n\r\n\t\ta... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add to parent sizer | def addToParent(self):
self.parent.GetSizer().Add(self.fieldLabel, 0,
wx.ALIGN_CENTER_VERTICAL)
self.parent.GetSizer().Add(self.textInput, 0,
wx.ALIGN_CENTER_VERTICAL)
self.parent.GetSizer().Add(self.browseButton, 0,
... | [
"def initialize_sizer(self):\n self.sizer = wx.BoxSizer(wx.VERTICAL)\n self.sizer.Add(self.toolbar, 0, wx.LEFT | wx.EXPAND)\n self.sizer.Add(self.figure_canvas, 1, wx.LEFT | wx.TOP | wx.GROW)\n self.SetSizer(self.sizer)\n self.Fit()\n self.toolbar.Show()",
"def __init__(s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Switch editability and appearance of FASTQ File 2 field when single vs. pariedend is toggled; retain field value | def switchPairedEnd(self, event):
fastq2Input = self.fieldPanel.fieldDict["FASTQ File 2"].textInput
if not self.isPairedEnd.GetValue():
fastq2Input.SetEditable(False)
fastq2Input.SetBackgroundColour("Gray")
else:
fastq2Input.SetEditable(True)
fastq... | [
"def dummy():\n\t\t\tself.edit = True",
"def _onchange_type2(self):\n if self.no_direct_fp and self.type2:\n self.type = 'internal'",
"def mode(self, value):\r\n if value != self._mode:\r\n if str(value).lower() == 'edit':\r\n if self._mode == 'read':\r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes two joints, calculates their twist in the given axis and applies half of that to a third joint created and situated halfway between the two. Returns the halfway joint. | def jointWithHalfwayTwist(
joint1,
joint2,
twistAxisJoint1,
twistAxisJoint2,
twistAxisHalfwayJoint,
staticParent,
side,
name,
):
DEBUG_MODE = mc.getAttr("C_top_CTL.debugMode")
joint1Twist = extractTwist(joint1, staticParent, alignXwith=twistAxisJoint1)
joint2Twist = extractT... | [
"def get_middle_joint(joint_a: Joint2D, joint_b: Joint2D) -> Joint2D:\n if not joint_a.is_set or not joint_b.is_set:\n return None\n visibility: JointVisibility\n if joint_a.visibility == JointVisibility.VISIBLE and joint_b.visibility == JointVisibility.VISIBLE:\n visibility = JointVisibility... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function reads data from data_dir, computes unigram and bigram counts, and writes the result to fn_LM | def lm_train(data_dir, language, fn_LM):
# TODO: Implement Function
language_model, unigram, bigram = {}, {}, {}
CKP = "WEAREDELETINGEND"
pre_w = CKP
for root, dirs, files in os.walk(data_dir, topdown=False):
for name in files:
if name.endswith(language):
... | [
"def lm_train(data_dir, language, fn_LM):\r\n\t\r\n\t# TODO: Implement Function\r\n\r\n LM = {}\r\n LM['uni'] = {}\r\n LM['bi'] = {}\r\n\r\n for (dirpath, dirnames, filenames) in os.walk(data_dir):\r\n for filename in filenames:\r\n if(filename.endswith(language)):\r\n w... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
given a suit level, return a randomlychosen suit type | def getRandomSuitType(level, rng=random):
return random.randint(max(level-4, 1 ), min(level, 8)) | [
"def getType(level):\n randomId = random.randint(1, WEIGHT[level])\n return getByWeight(POSSIBLE_TYPES[level], randomId)[0]",
"def random_suit():\n return random.choice(list(Suit))",
"def newSuitRandom(self, level=None, dept=None):\n self.type = \"s\"\n \n if (level==None):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
given a suit dept, return a randomlychosen suit | def getRandomSuitByDept(dept):
deptNumber = suitDepts.index(dept)
return suitHeadTypes[(suitsPerDept*deptNumber) + random.randint(0,7)] | [
"def random_suit():\n return random.choice(list(Suit))",
"def select_suit(self):\n\n # Are there any fives?\n fives = [card for card in self.player.hand if card.rank == '5']\n if fives:\n return fives[0].suit\n\n return random.choice(self.player.hand.cards).suit",
"def ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
__init__(self, string=None, string=None, string()=None, float=None, float=None, float=None) SuitDNA contructor see class comment for usage | def __init__(self, str=None, type=None, dna=None, r=None, b=None, g=None):
# have they passed in a stringified DNA object?
if (str != None):
self.makeFromNetString(str)
# have they specified what type of DNA?
elif (type != None):
if (type == 's'): # Suit
... | [
"def __init__(self, sequence=\"\"):\n assert Sequence.is_valid(sequence), \\\n \"Sequence should only contain A, C, G and T\"\n self._nucleotides = sequence.upper() # 处理对象.方法",
"def __init__(self, string1, string2):\r\n self.s1 = string1\r\n self.s2 = string2\r\n retu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
__defaultSuit(self) Make a default suit dna | def __defaultSuit(self):
self.type = 's'
self.name = 'ds'
self.dept = getSuitDept(self.name)
self.body = getSuitBodyType(self.name) | [
"def generateSuit(self):\n\n dna = self.style\n self.headParts = []\n \n # most heads do not need different poly color or texture\n self.headColor = None\n self.headTexture = None\n\n # For suit death animation\n self.loseActor = None\n\n # Have we beco... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
newSuit(self, string=None) If no suit name specified, set the dna for the default suit else set the dna for suit specified by the given string. | def newSuit(self, name=None):
if (name == None):
self.__defaultSuit()
else:
self.type = "s"
self.name = name
self.dept = getSuitDept(self.name)
self.body = getSuitBodyType(self.name) | [
"def setSuit(self, arg):\n self.suit = arg",
"def set_suit(self, suit: str):\n if suit not in ['diamond', 'spade', 'club', 'heart']:\n raise ValueError('invalid suit')\n self.suit = suit",
"def set_suit(self, suit):\n assert suit in set(['S', 'H', 'C', 'D'])\n self.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
newSuitRandom(self, int=None, string=None) Generate dna for a random suit of random level (unless level is specified) and random dept (again, unless specified) | def newSuitRandom(self, level=None, dept=None):
self.type = "s"
if (level==None):
# pick a random level
level = random.choice(range(1, len(suitsPerLevel)))
else:
# make sure supplied one is valid
if (level < 0 or level > len(suitsPerLevel)... | [
"def getRandomSuitByDept(dept):\n deptNumber = suitDepts.index(dept)\n return suitHeadTypes[(suitsPerDept*deptNumber) + random.randint(0,7)]",
"def random_suit():\n return random.choice(list(Suit))",
"def getRandomSuitType(level, rng=random):\n return random.randint(max(level-4, 1 ), min(level, 8))"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
newGoon(self, type) Return the dna for the goon of this name. If no name is given return the default goon. | def newGoon(self, name = None):
if type == None:
self.__defaultGoon()
else:
self.type = 'g'
if (name in goonTypes):
self.name = name
else:
notify.error("unknown goon type: ", name) | [
"def _newcreature(self, level):\n class_ = type = None\n if self.creatures:\n class_ = self.creatures[0].subtype\n if class_ is None: type = self.creatures[0].name\n return TrainableAnimal(type, class_)",
"def create_goat(name):\n weight = random.randint(50, 100)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
getType(self) Return which type of actor this dna represents. | def getType(self):
if (self.type == 's'):
#suit type
type = "suit"
elif (self.type == 'b'):
#boss type
type = "boss"
else:
notify.error("Invalid DNA type: ", self.type)
return type | [
"def get_type(self):\n return self.__animal_type",
"def get_agent_type(self):\n\n return self._agent_type;",
"def getType(self):\n return self.get('SOR.type')",
"def get_type(self, ):\n return self.attrs.get(self.AttributeNames.TYPE, None)",
"def an_type(self):\n return se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create the NN architecture for the model. | def make_architecture(self):
self.arch = simple_mlp(num_inputs=self.p.model.num_inputs,
num_outputs=self.p.model.num_outputs,
params=self.p.model.arch) | [
"def _create_network(self):\n layer_dim = np.append(\n np.array(self.net_arch[\"n_input\"]), self.net_arch[\"hidden_dim\"]\n )\n\n self.z, self.y, self.p_X_chain = self._autoencoder(self.x, layer_dim)",
"def define_model_architecture(\n net_params: dict,\n in_channels... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get a list of the trainable variables of the model. | def get_trainable_vars(self):
return self.arch.variables | [
"def _get_trainable_variables(self, model):\n if isinstance(model, list):\n return self._get_trainable_variables_list(model)\n\n return model.trainable_variables",
"def _get_trainable_variables_list(self, model_list):\n model_vars = []\n\n for m in model_list:\n m... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create the NN inputs and outputs from the raw data batch. All preprocessing should go here. | def create_nn_inputs_and_outputs(self, raw_data, is_training=None):
raise NotImplementedError | [
"def load_data_and_labels(self):\n gen = image.ImageDataGenerator()\n target_size = (224,224)\n if self.preprocess:\n print('Preprocessing data...')\n if not os.path.isdir(self.pproc_dir()):\n os.mkdir(self.pproc_dir())\n \n batch_a... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Predict the NN output to a given input with an optional post processing function applied. By default there is no post processing function applied. | def predict_nn_output_with_postprocessing(self, data, is_training=None):
return self.predict_nn_output(data, is_training=is_training) | [
"def predict(self, input):\n self._check_predict_ready()\n with torch.no_grad():\n self.eval()\n input = deep_to(input, self.device)\n prediction = self.nn_module(input)\n prediction = self.prediction_transform(prediction)\n return prediction",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initialize the processing functions if required. | def make_processing_functions(self):
return | [
"def pre_process(self):\n pass",
"def initialize(self, runInfo, inputs, initDict) :\n PostProcessor.initialize(self, runInfo, inputs, initDict)",
"def setup(self):\n self.kernel = RunningKernel()\n self.setup_sanitize_files()",
"def _build_preprocessing(self):\n\n # For now, do ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This is for formatting the mocked XML db so it doesn't have whitespace between elements | def format_db(self) -> None:
with open(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'basedb.xml'), 'r') as f:
base = f.read()
parser = etree.XMLParser(remove_blank_text=True)
elem = etree.XML(base, parser=parser)
print(etree.tostring(elem))
with open(os.... | [
"def format_xml(self,query_results):\n results=query_results.data\n factory=factory_xml()\n dump=factory.dumps({'data':results})\n print(dump)\n # TODO return output for this\n return \"\"",
"def pretty(self, ugly):\n document_root = html.fromstring(ugly.replace(\"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parses the passed CQL to its AST interpretation. | def parse(cql, geometry_factory=values.Geometry, bbox_factory=values.BBox,
time_factory=values.Time, duration_factory=values.Duration):
parser = CQLParser(
geometry_factory,
bbox_factory,
time_factory,
duration_factory
)
return parser.parse(cql) | [
"def parse(query):\n\n if type(query) == str:\n try:\n query = query.decode(\"utf-8\")\n except Exception, e:\n raise\n\n q = StringIO(query)\n lexer = CQLshlex(q)\n parser = CQLParser(lexer)\n object = parser.query()\n if parser.currentToken != '':\n dia... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
For example if rhs = NP PP VP PP and i = 1 Y = NP|PP.VP.PP | def cnf_create_variable(cls, rhs, i):
Y = rhs[0]
for j in range(1, len(rhs)):
Y += "|" if j == i else "."
Y += rhs[j]
return Y | [
"def perplexity(py, y):\n perplexity = 1.\n for i, p in enumerate(py):\n perplexity *= p[y[i]]**(-1./len(y))\n return perplexity",
"def PViLearningRule(p, word=None):\n PVi = word.GetGroupByName(\"PVi\")\n PVe = word.GetGroupByName(\"PVe\")\n d = PVe.activations - PVi.activations\n X... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generates a derivation tree from a given symbol | def gentree(self, symbol):
### YOUR CODE HERE
tree = "(" + symbol + " "
expansion = self.random_expansion(symbol)
for s in expansion:
if self.is_terminal(s):
tree += " " + s
else:
tree += " " + self.gentree(s)
tree +... | [
"def deriv2tree(self,derivation):\n StackElt = namedtuple('StackElt',['symbol','predicted','has_to_move'])\n\n stack = [] \n inc_index = 0\n prev_action = None\n for action in derivation:\n if prev_action == DiscoRNNGparser.SHIFT:\n stack.append( Sta... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generates a random RHS for symbol, in proportion to the weights. | def random_expansion(self, symbol):
p = random.random() * self._sums[symbol]
for r,w in self._rules[symbol]:
p = p - w
if p < 0: return r
return r | [
"def random_expansion(self, symbol):\r\n p = random.random() * self._sums[symbol]\r\n for r,w in self._rules[symbol]:\r\n p = p - w\r\n if p < 0: return r\r\n return r",
"def gen_random(self, symbol):\n sentence = ''\n\n # select one production of this symb... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This method actually calculates the distance between two dataObjects x and y @ In, x, dict, dictionary containing data of x @ In, y, dict, dictionary containing data of y @ In, kwargs, dictionary of parameters characteristic of each metric (e.g., weights) @ Out, value, float, distance between x and y | def distance(self,x,y,**kwargs):
pass | [
"def distance(obj_1, obj_2):\n # return heuristic(obj_1, obj_2)\n return euclidean(obj_1, obj_2)",
"def distance(cls,config_1, config_2):\n\t\tsorted_data_1 = (config_1.data).sort_values('item')\n\t\tsorted_data_2 = (config_2.data).sort_values('item')\n\t\tdr = sorted_data_1 - sorted_data_2\n\t\tret... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Module to support character map dictitonary creation through method call/cli | def create_charmap_dictionary(input_data='nltk', file_path=None, logger=None):
data_list = fetch_word_list(input_data, file_path, logger)
# Fetch the dictionary
dict_file_path = fetch_dictionary_information()
# Creating and Persisting the dictionary
create_dictionary(data_list, dict_file_path, Cha... | [
"def _init_charmap(self):\n charmap = \"\"\"\n _U,_D,UU,DD:VLINE\n _L,_R,LL,RR:HLINE\n UL,RD:URCORNER\n UR,LD:ULCORNER\n DL,RU:LRCORNER\n DR,LU:LLCORNER\n U_,D_,L_,R_,__:DIAMOND\n \"\"\"\n self.charmap = {}\n fo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates and returns a new experiment | def create_experiment(self):
experiment = wandb.init(
name=self._name, dir=self._dir, project=self._project,
anonymous=self._anonymous, reinit=True, id=self._id,
resume='allow', tags=self._tags, entity=self._entity
)
wandb.run.save()
return experiment | [
"def newExperiment(self):\n experiment = Experiment()\n newtitle = 'Untitled ' + self.getNextUntitled()\n experimentFrame = SequenceFrame(self, experiment, True, newtitle)\n experiment.setInteractionParameters(parentFrame=experimentFrame,\n graphManagerC... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the experiment (creates a new if it doesn't exist). | def experiment(self) -> Run:
if self._experiment is None:
self._experiment = self.create_experiment()
return self._experiment | [
"def create_experiment_if_needed(tr):\n exp = tr.getExperiment(EXPERIMENT_ID)\n if None == exp:\n create_project_if_needed(tr)\n exp = tr.createNewExperiment(EXPERIMENT_ID, 'DEFAULT_EXPERIMENT')\n \n return exp",
"def _create_or_get_experiment(self) -> tensorboard_experiment.TensorboardExperiment:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Helper function used to log images relevant for depth estimation | def log_depth(self, *args, **kwargs):
def log(prefix_idx, batch, output):
self._metrics.update(log_rgb('rgb', prefix_idx, batch))
self._metrics.update(log_inv_depth('inv_depth', prefix_idx, output))
if 'depth' in batch:
self._metrics.update(log_depth('depth', ... | [
"def log_depth(key, prefix, batch, i=0):\n depth = batch[key] if is_dict(batch) else batch\n inv_depth = 1. / depth[i]\n inv_depth[depth[i] == 0] = 0\n return prep_image(prefix, key,\n viz_inv_depth(inv_depth, filter_zeros=True))",
"def log_scale_depth(depth_image):\n\n\t# Log sca... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Converts an RGB image from a batch for logging | def log_rgb(key, prefix, batch, i=0):
rgb = batch[key] if is_dict(batch) else batch
return prep_image(prefix, key,
rgb[i]) | [
"def convert_color(self, img, conv):",
"def bgr2rgb(image):\n return image[..., [2, 1, 0]]",
"def _decode_image(self, row_image):\n length = int(self.image_size ** 2)\n red = row_image[:length].reshape(32, 32)\n green = row_image[length:length * 2].reshape(32, 32)\n blue = row_ima... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Converts a depth map from a batch for logging | def log_depth(key, prefix, batch, i=0):
depth = batch[key] if is_dict(batch) else batch
inv_depth = 1. / depth[i]
inv_depth[depth[i] == 0] = 0
return prep_image(prefix, key,
viz_inv_depth(inv_depth, filter_zeros=True)) | [
"def log_inv_depth(key, prefix, batch, i=0):\n inv_depth = batch[key] if is_dict(batch) else batch\n return prep_image(prefix, key,\n viz_inv_depth(inv_depth[i]))",
"def depth_from_coords(depth_map, data, width, height):\r\n assert depth_map.ndim == 3\r\n assert data.ndim == 3 and... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Converts an inverse depth map from a batch for logging | def log_inv_depth(key, prefix, batch, i=0):
inv_depth = batch[key] if is_dict(batch) else batch
return prep_image(prefix, key,
viz_inv_depth(inv_depth[i])) | [
"def log_depth(key, prefix, batch, i=0):\n depth = batch[key] if is_dict(batch) else batch\n inv_depth = 1. / depth[i]\n inv_depth[depth[i] == 0] = 0\n return prep_image(prefix, key,\n viz_inv_depth(inv_depth, filter_zeros=True))",
"def write_inverse_depth_map(image, file_path, ex... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Finds the best answer with the maximum start_prob end_prob from a single passage | def find_best_answer_for_passage(start_probs, end_probs, passage_len=None, max_a_len=None):
if passage_len is None:
passage_len = len(start_probs)
else:
passage_len = min(len(start_probs), passage_len)
best_start, best_end, max_prob = -1, -1, 0
# 从头扫描passage
for start_idx in range(pa... | [
"def find_best_answer_for_passage(self, start_probs, end_probs, passage_len=None):\n if passage_len is None:\n passage_len = len(start_probs)\n else:\n passage_len = min(len(start_probs), passage_len)\n best_start, best_end, max_prob = -1, -1, 0\n for start_idx in r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initialize and configure HTTP requests client for selected service. | def _init_http_client(service_id=None, opts=None):
if service_id:
opts = _get_trs_opts(service_id)
http_client = RequestsClient()
http_client.set_api_key(host=opts['host'],
api_key=opts['auth'],
param_in='header')
return http_client | [
"async def init_http_client(app: Application):\n logger.info('Initializing HTTP client')\n tcp_connector = aiohttp.TCPConnector(limit=TCP_CONNECTIONS_LIMIT, ttl_dns_cache=TTL_DNS_CACHE)\n app['http_client'] = ClientSession(connector=tcp_connector)",
"def service_client_initialization(self) -> global___Sn... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initializes an Auction object. | def __init__(self, bidders, item, starting_price):
self._bidders = bidders
self._item = item
self._starting_price = starting_price
self._auctioneer = Auctioneer(self._bidders, self._starting_price) | [
"def __init__(self, bidders):\n self._bidders = bidders\n self._auctioneer = Auctioneer()\n for bidder in bidders:\n self._auctioneer.register_bidder(bidder)",
"def __init__(self, bidders):\n # self._observers = bidders\n self._core = Auctioneer()\n self._ob... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Update the highest current bid price and highest bidder, and start a new bid in turn. | def update_bid(self, bid_price, bidder):
bidder_info = "Starting Bid"
if self.current_bidder is not None:
bidder_info = self.current_bidder.name
print(f"{bidder.name} bidded {bid_price} in response to "
f"{bidder_info}'s bid of {self.current_bid}!")
self._highes... | [
"def start_new_bids(self):\n for bidder in self._bidders:\n if bidder != self._highest_current_bidder:\n bid_price = bidder(self)\n if bid_price > self.current_bid:\n self.update_bid(bid_price, bidder)",
"def __call__(self, auctioneer):\n c... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Start a new bid by notifying all bidders except for the current highest bidder. | def start_new_bids(self):
for bidder in self._bidders:
if bidder != self._highest_current_bidder:
bid_price = bidder(self)
if bid_price > self.current_bid:
self.update_bid(bid_price, bidder) | [
"def _notify_bidders(self):\n for bidder in self.bidders:\n if self._highest_bidder is not bidder:\n bidder(self)",
"def update_bid(self, bid_price, bidder):\n bidder_info = \"Starting Bid\"\n if self.current_bidder is not None:\n bidder_info = self.curren... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Places a new bid with the auctioneer, after checking the budget and probability, and updates the its highest bid price. | def __call__(self, auctioneer):
curr_bid = auctioneer.current_bid
bid_price = curr_bid * self._bid_increase_perc
if bid_price <= self._budget and self.get_bid_probability() > 0.3:
self._highest_bid = bid_price
return bid_price
return 0 | [
"def update_bid(self, bid_price, bidder):\n bidder_info = \"Starting Bid\"\n if self.current_bidder is not None:\n bidder_info = self.current_bidder.name\n print(f\"{bidder.name} bidded {bid_price} in response to \"\n f\"{bidder_info}'s bid of {self.current_bid}!\")\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Map a point to bitvector corresponding to the bin that contains it. | def pt2bv(self, point: float, tol=0.0):
index = self.pt2index(point, tol)
return int2bv(index, self.num_bits) | [
"def mapping(bits):\r\n return np.array([mappingTable[tuple(b)] for b in bits])",
"def coordinate_to_address(self, points):\n points = self._check_in_bounds(points)\n voxel_coordinates = np.floor((points-self.minimum_corner)/self.edge_length).astype(np.int64)\n\n # now do the bit shifts\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Filters data source by attackpattern which extracts all ATT&CK Techniques | def get_all_techniques(src, source_name, tactic=None):
filters = [
Filter("type", "=", "attack-pattern"),
Filter("external_references.source_name", "=", source_name),
]
if tactic:
filters.append(Filter('kill_chain_phases.phase_name', '=', tactic))
results = src.query(filters)
... | [
"def apply_attack(self, data):",
"def get_attacks(self):\n if self.character_data is None: raise Exception('You must call get_character() first.')\n attacks = AttackList()\n for rownum in range(32, 37): # sht1, R32:R36\n a = self.parse_attack(f\"R{rownum}\", f\"Y{rownum}\", f\"AC{... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Filters data source by id and type | def filter_by_type_and_id(src, object_type, object_id, source_name):
filters = [
Filter("type", "=", object_type),
Filter("id", "=", object_id),
Filter("external_references.source_name", "=", source_name),
]
results = src.query(filters)
return remove_deprecated(results) | [
"def filter_by_types(self, types: List[Hashable]) -> \"ModinDataframe\":\n pass",
"def filter(self, data):\n pass",
"def getFilter(self, type: int) -> int:\n ...",
"def _data_filtering(self):\n self._filter_nan_user_or_item()\n self._remove_duplication()\n self._filte... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Grab external id from STIX2 object | def grab_external_id(stix_object, source_name):
for external_reference in stix_object.get("external_references", []):
if external_reference.get("source_name") == source_name:
return external_reference["external_id"] | [
"def getId():",
"def external_id(self):\n return self._external_id",
"def getId(self):\n return _libsbml.SBase_getId(self)",
"def get_identifier(self):",
"def get_primary_id(self):",
"def internal_id_from_model_and_external_id(model, external_id):\n try:\n content_type_id, instance... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Will remove any revoked or deprecated objects from queries made to the data source | def remove_deprecated(stix_objects):
# Note we use .get() because the property may not be present in the JSON data. The default is False
# if the property is not set.
return list(
filter(
lambda x: x.get("x_mitre_deprecated", False) is False and x.get("revoked", False) is False,
... | [
"def garbage_collect(cls):\n extra_filter_kwargs = (\n {\n \"editors_picks__isnull\": True,\n }\n if hasattr(cls, \"editors_picks\")\n else {}\n )\n cls.objects.filter(daily_hits__isnull=True, **extra_filter_kwargs).delete()",
"def da... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Grab all the scripts in the bin directory. | def get_scripts():
scripts = []
if os.path.isdir('bin'):
scripts = [fname for fname in glob.glob(os.path.join('bin', '*'))
if not os.path.basename(fname).endswith('.rst')]
return scripts | [
"def get_scripts():\n paths = ['bin/addartobj',\n 'bin/convgauss',\n 'bin/ds9reg2fits',\n 'bin/fitshead',\n 'bin/mcmcangcorr',\n 'bin/radprof',\n 'bin/sexcat2fits',\n 'bin/simbgim',\n 'bin/stackmasks',\n '... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Delete an existing permission prototype. | def delete(self, orgname, prototypeid):
permission = AdministerOrganizationPermission(orgname)
if permission.can() or allow_if_superuser():
try:
org = model.organization.get_organization(orgname)
except model.InvalidOrganizationException:
raise Not... | [
"def delete_permission(connection, project_id, group_id, permisison_type, permission_list, existing_mode):\n \n if permission_type == 'project':\n url = connection['server'] + \"/api/{0}/sites/{1}/projects/{2}/permissions/groups/{3}/{4}/{5}\".format(connection['api_version'],\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Main handler for E1.33 RDMnet Broker PDUs. Switches the handler based on the broker vector as defined in RDMNet.vectors. | def handle(self, data):
#Check broker vector
if data[26:28] == vectors.vector_broker_connect:
#Ignore - we won't receive this
pass
elif data[26:28] == vectors.vector_broker_connect_reply:
broker_connect_reply(self, data)
elif data[26:28] == vectors.vector_broker_client_entry_upd... | [
"def main():\n verbose = '-v' in sys.argv\n broker = MajordomoBroker(verbose)\n broker.bind('tcp://*:5555')\n broker.mediate()",
"def main():\n\n logger.info(\"Starting Message Broker Service\")\n\n broker = Broker()\n\n s1 = Subscriber(\"subscriber1\", broker)\n s2 = Subscriber(\"subscrib... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Handles the broker_connect_reply vector. | def broker_connect_reply(self, data):
print("Broker Connected")
#IDEA: Does this need a handler? | [
"def handle_connect(self):\n pass",
"def process_reply(self, message):\n logger.debug(\"Reply for connect received: %s\", message)\n with self.app.peers_lock:\n try:\n peer = self.app.peers[message.source]\n except KeyError:\n logger.error(\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Handles the broker_null (heartbeat) vector. | def broker_null(self, data):
print("Heartbeat")
#TODO: Reset heartbeat timer or something like that | [
"def test_heartbeatDisabled(self):\n self.assertIdentical(self.client._heartbeat, None)\n self.client.heartbeatInterval = None\n self.client.irc_RPL_WELCOME(\"foo\", [])\n self.assertIdentical(self.client._heartbeat, None)",
"async def test_no_hb(self):\n await self.async_setup(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Loads an image file located in the textures directory and specified by the given filename, adds it to the texture atlas and returns the resulting texture. | def atlas_load(filename):
t = pyglet.image.load(os.path.join('textures','ground.png'))
tex = atlas.add(t)
return tex | [
"def _load_texture(self, filename):\n if not os.path.exists(filename):\n raise ValueError(\"Texture file not found: \" + filename)\n sys.exit()\n # Load the image\n image = Image.open(filename)\n ix = image.size[0]\n iy = image.size[1]\n image = image.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |