query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Retry if not hosts used on client first time connection. | def get_hosts_retry(self, target, listener_type): | [
"def reconnect(self):\n self.test_cmd()\n if not self.check_network: \n self.reset()\n attempt=0\n while not self.check_network and attempt<self.retries:\n self.full_reset()\n attempt+=1",
"def _reconnect(self):\n for host, port in self.nodes:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get all hosts for fanout from nameserver by target. | def get_hosts_fanout(self, target, listener_type): | [
"def get_hosts(self, target, listener_type):",
"def get_allhosts():\n connection, tablename = HomeNetwork.get_connection_info()\n query = 'SELECT hostname from {}'.format(tablename)\n output = pandas.read_sql_query(query, connection).to_json(orient='records')\n\n for host in json.loads... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retry if not host for fanout used on client first time connection. | def get_hosts_fanout_retry(self, target, listener_type): | [
"def reconnect(self):\n self.test_cmd()\n if not self.check_network: \n self.reset()\n attempt=0\n while not self.check_network and attempt<self.retries:\n self.full_reset()\n attempt+=1",
"def decide_to_retry(error):\n return True",
"def r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Each profile model should define the __init__ method. The __init__ method must take the grid as the first input parameter. All other input parameters can be specified to define the model. The grid input parameter is automatically added as an attribute of the profile model. This method should set all three components of... | def __init__(self, grid, coef_u, coef_w=[0.01, 0.2]):
# In this example, we set the u-component to increase linearly with height:
# Note: we are making use of the automatically added 'grid' attribute
self._u[0] = coef_u * self.grid.z[:, None]
# Arbitrarily chose a factor of 0.3
... | [
"def initialize(self, grid=None, input_file=None, intensity=None, stormduration=None):\n self.grid = grid \n if self.grid==None:\n self.grid = create_and_initialize_grid(input_file) ##<- this is the same input file used for parameters. \n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Thermal Gradient Flow – nostrilregion tracking method using the thermal gradient magnitude and points tracking methods | def thermal_gradient_flow():
pass | [
"def vis_d():\n \n data_gen = generator(fixed_noise)\n# loss = d_loss(discriminator(data_gen), discriminator(grid))\n loss = g_loss(discriminator(grid))\n loss.backward()\n \n grads = - grid.grad.data.numpy()\n grid.grad.data *= 0 \n plt.quiver(X_grid, Y_grid, grads[:, 0], grads[:, ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Thermal Voxelbased Respiratory Rate Estimation – extracting the respiratory signals by integrating the unit thermal voxels inside the nostril | def thermal_voxel_respiration_estimation():
pass | [
"def Find_Res(HyperfineStr=[1.4680e+4,2.9361e3] ,B_field =400 ,tau_max=6*1e-6,tau_step = 0.005*1e-6, max_gate_time = 8000*1e-6):\n #physical constants\n gamma_c = 1.071e3 #g-factor for C13 in MHz/G\n #Model parameters\n timesteps = np.arange(tau_step,tau_max,tau_step)\n omega_larmor = 2*np.pi*gamma_c... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Take the MD5 digest of a name, convert it to hex and take the first 6 characters as an RGB value. | def dopplr(name):
return "#" + hashlib.sha224(name).hexdigest()[:6] | [
"def name_to_rgb(name, spec='css3'):\n return hex_to_rgb(name_to_hex(name, spec=spec))",
"def color(name):\n return pygame.Color(name)[:3]",
"def color_to_hex(name):\n _tuple = (int(name.red*255), int(name.green*255), int(name.blue*255))\n _string = '#%02x%02x%02x' % _tuple\n return _string.u... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Find the largestsized font that'll fit this text on this cover | def largest_font_that_fits(draw, font_file, text, cover_width):
text_w = cover_width + 1
font_size = 110
padding = 20
while(text_w + padding > cover_width):
font_size -= 10
font = ImageFont.truetype(font_file, font_size)
text_w, text_h = draw.textsize(text, font)
return font | [
"def _find_biggest_possible_font(self) -> Optional[int]:\n max_width = self.placement[2]\n max_height = self.placement[3]\n \n current_max_font = min(max_height, max_width)\n testing_label = pygame.font.SysFont(self.font, current_max_font).render(f'{self.text}', 1, (*self.font_col... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get some public domain image for text | def get_an_image(text):
# Get the second or fourth word
index = random.choice([1, 3])
text = text.split()[index]
print(text)
sort = random.choice(["relevance", "interestingness-desc"])
print(sort)
from flickr_search_downloadr import flickr_search_downloadr
filename = flickr_search_dow... | [
"def getTextImage(self):\r\n return self.textImage",
"def getTextImage(self):\n return self.textImage",
"def get_image_character(character):\n info_character = Charsearch(character)\n return info_character.image_url",
"def l10n_img(ctx, url):\n return static(l10n_img_file_name(ctx, url)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate the train and validation errors needed to plot a validation curve that we can use to select lambda. | def validation_curve(x, y, x_val, y_val):
lambda_vec = np.array([0, 0.001, 0.003, 0.01, 0.03, 0.1, 0.3, 1, 3, 10])
error_train = np.zeros(len(lambda_vec))
error_val = np.zeros(len(lambda_vec))
m = x.shape[0]
m_val = x_val.shape[0]
for i in range(len(lambda_vec)):
l = lambda_vec[i]
... | [
"def validationCurve(X, y, Xval, yval):\n\n # Selected values of lambda (you should not change this)\n lmbda_vec = [0, 0.001, 0.003, 0.01, 0.03, 0.1, 0.3, 1, 3, 10]\n\n # You need to return these variables correctly.\n error_train = np.zeros((len(lmbda_vec), 1))\n error_val = np.zeros((len(lmbda_vec)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check that we reject a WRITE that names the iounit argument but still has a positional format argument (containing an '='). TODO 267. This test needs expanding and probably moving to a file dedicated to R913 and its (many) constraints. | def test_named_unit_before_fmt_error():
tcls = Write_Stmt
# Cannot have an un-named (positional) argument after a named argument
with pytest.raises(NoMatchError):
tcls('''WRITE (UNIT=6, '("write some=""'//'text'//'""")')''') | [
"def test_write_run_output_unexpected_kwarg(self):\n self.assertRaises(\n TypeError, nestcheck.write_polychord_output.write_run_output,\n {}, unexpected=1)",
"def test_incorrect_input():\n content = 'hi'\n filename = {}\n\n with pytest.raises(TypeError):\n write_file(c... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Filter neighborhoods with max number of neighbors. Limit is set to keep XX% of the neighborhoods untouched. Limit is computed at initialization | def big_neighborhood_filter(self, neighbors, layer):
# crop neighbors matrix
return neighbors[:, :self.neighborhood_limits[layer]] | [
"def big_neighborhood_filter(self, neighbors, layer):\r\n\r\n # crop neighbors matrix\r\n if len(self.neighborhood_limits) > 0:\r\n return neighbors[:, :self.neighborhood_limits[layer]]\r\n else:\r\n return neighbors",
"def sample_top_neighbors( self, max_count=200 ):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns colour scheme for CSI (critical success index). | def _get_csi_colour_scheme():
this_colour_map_object = pyplot.cm.Blues
this_colour_norm_object = matplotlib.colors.BoundaryNorm(
LEVELS_FOR_CSI_CONTOURS, this_colour_map_object.N)
rgba_matrix = this_colour_map_object(this_colour_norm_object(
LEVELS_FOR_CSI_CONTOURS
))
colour_list ... | [
"def _get_csi_colour_scheme(use_grey_scheme):\n\n this_colour_map_object = pyplot.get_cmap(\n 'gist_yarg' if use_grey_scheme else 'Blues'\n )\n this_colour_norm_object = matplotlib.colors.BoundaryNorm(\n CSI_LEVELS, this_colour_map_object.N\n )\n\n if use_grey_scheme:\n rgba_matr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns colour scheme for Peirce score. | def _get_peirce_colour_scheme():
this_colour_map_object = pyplot.cm.Blues
this_colour_norm_object = matplotlib.colors.BoundaryNorm(
LEVELS_FOR_PEIRCE_CONTOURS, this_colour_map_object.N)
rgba_matrix = this_colour_map_object(this_colour_norm_object(
LEVELS_FOR_PEIRCE_CONTOURS
))
col... | [
"def _get_peirce_colour_scheme():\n\n this_colour_map_object = pyplot.get_cmap('Blues')\n this_colour_norm_object = matplotlib.colors.BoundaryNorm(\n PEIRCE_SCORE_LEVELS, this_colour_map_object.N\n )\n\n rgba_matrix = this_colour_map_object(this_colour_norm_object(\n PEIRCE_SCORE_LEVELS\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generates polygon for confidence interval. P = number of points in bottom curve = number of points in top curve | def _confidence_interval_to_polygon(
x_coords_bottom, y_coords_bottom, x_coords_top, y_coords_top,
for_performance_diagram=False):
nan_flags_top = numpy.logical_or(
numpy.isnan(x_coords_top), numpy.isnan(y_coords_top))
real_indices_top = numpy.where(numpy.invert(nan_flags_top))[0]
... | [
"def subdivision(P):\n # we want the bezier polygon with 2n+1 points over [0, 0.5, 1]\n n, dim = P.shape\n n = n - 1\n b = np.copy(P).astype(\"float\")\n t = 0.5\n\n P0 = np.zeros((n + 1, dim))\n P1 = np.zeros((n + 1, dim))\n P0[0] = b[0]\n P1[0] = b[n]\n\n for i in range(1, n + 1):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Plots background (references lines and polygons) of attributes diagram. For more on the attributes diagram, see Hsu and Murphy (1986). BSS = Brier skill score. For more on the BSS, see `model_evaluation.get_brier_skill_score`. | def _plot_background_of_attributes_diagram(
axes_object, climatology,
no_skill_line_colour=DEFAULT_ZERO_BSS_COLOUR,
no_skill_line_width=DEFAULT_ZERO_BSS_WIDTH,
other_line_colour=DEFAULT_CLIMATOLOGY_COLOUR,
other_line_width=DEFAULT_CLIMATOLOGY_WIDTH):
error_checking.assert_is... | [
"def _plot_attr_diagram_background(\n axes_object, mean_value_in_training, min_value_in_plot,\n max_value_in_plot):\n\n x_coords_left, y_coords_left, x_coords_right, y_coords_right = (\n _get_positive_skill_area(\n mean_value_in_training=mean_value_in_training,\n min_va... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Plots forecast histogram inset in attributes diagram. For more on the attributes diagram, see Hsu and Murphy (1986). B = number of forecast bins | def _plot_inset_histogram_for_attributes_diagram(
figure_object, num_examples_by_bin,
bar_face_colour=DEFAULT_HISTOGRAM_FACE_COLOUR,
bar_edge_colour=DEFAULT_HISTOGRAM_EDGE_COLOUR,
bar_edge_width=DEFAULT_HISTOGRAM_EDGE_WIDTH):
error_checking.assert_is_integer_numpy_array(num_examples... | [
"def IMF_B_hist():\n param_list = [\"By\", \"Bz\"]\n colors=['k'] * len(imf_bins)\n xlim=[-20, 20]\n ylim=[0, 120000]\n\n # Determines how to place the imf_bins into panels,\n # NOTE: must match with imf_bins\n ax_idxs = [1, 2, 5, 8, 7, 6, 3, 0]\n bins_txt = [\"Bz+\", \"By+/Bz+\", \"By+\", \... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Bootstrapped version of plot_roc_curve. T = number of probability thresholds in curve | def plot_bootstrapped_roc_curve(
axes_object, ci_bottom_dict, ci_mean_dict, ci_top_dict,
line_colour=DEFAULT_ROC_COLOUR,
line_width=DEFAULT_ROC_WIDTH,
random_line_colour=DEFAULT_RANDOM_ROC_COLOUR,
random_line_width=DEFAULT_RANDOM_ROC_WIDTH):
plot_roc_curve(
axes_obje... | [
"def make_roc_curve(predictions, targets): \n false_positive_rate, true_positive_rate, thresholds = metrics.roc_curve(\n targets, predictions)\n \n plt.ylabel(\"true positive rate\")\n plt.xlabel(\"false positive rate\")\n plt.plot(false_positive_rate, true_positive_rate)",
"def compute_roc_curve(clf, ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Bootstrapped version of plot_performance_diagram. | def plot_bootstrapped_performance_diagram(
axes_object, ci_bottom_dict, ci_mean_dict, ci_top_dict,
line_colour=DEFAULT_PERFORMANCE_COLOUR,
line_width=DEFAULT_PERFORMANCE_WIDTH,
bias_line_colour=DEFAULT_FREQ_BIAS_COLOUR,
bias_line_width=DEFAULT_FREQ_BIAS_WIDTH):
plot_performa... | [
"def create_dashboard(h, t, k, p):\n plt.style.use('seaborn')\n # Initialize the dashboard\n fig = plt.figure(figsize=(20, 8))\n ax1 = fig.add_subplot(2, 2, 1)\n ax2 = fig.add_subplot(2, 2, 2)\n ax3 = fig.add_subplot(2, 2, 3)\n ax4 = fig.add_subplot(2, 2, 4)\n\n # Create individual graphs\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Bootstrapped version of plot_reliability_curve. B = number of bins (separated by forecast probability) | def plot_bootstrapped_reliability_curve(
axes_object, ci_bottom_dict, ci_mean_dict, ci_top_dict,
line_colour=DEFAULT_RELIABILITY_COLOUR,
line_width=DEFAULT_RELIABILITY_WIDTH,
perfect_line_colour=DEFAULT_PERFECT_RELIABILITY_COLOUR,
perfect_line_width=DEFAULT_PERFECT_RELIABILITY_WI... | [
"def pr_curves(model_list, title_list, main_title, label_key,\n dashes=[], xlim=(0,1), ylim=(0,1), figsize=(6,4),\n xticks=None, yticks=None,\n save_fname=None, test_data=None):\n y_trues = np.array(test_data[label_key])\n is_biased = np.array(test_data['is_biased'])\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Bootstrapped version of plot_attributes_diagram. | def plot_bootstrapped_attributes_diagram(
figure_object, axes_object, ci_bottom_dict, ci_mean_dict, ci_top_dict,
num_examples_by_bin,
reliability_line_colour=DEFAULT_RELIABILITY_COLOUR,
reliability_line_width=DEFAULT_RELIABILITY_WIDTH,
perfect_relia_line_colour=DEFAULT_PERFECT_RE... | [
"def plot_attributes_diagram(\n figure_object, axes_object, mean_prediction_matrix,\n mean_observation_matrix, example_counts, mean_value_in_training,\n min_value_to_plot, max_value_to_plot, confidence_level=0.95,\n line_colour=RELIABILITY_LINE_COLOUR,\n line_style='solid', line_w... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Provides the spin from an int. +1 == Spin.up, 1 == Spin.down. | def from_int(i):
if i == 1:
return Spin.up
elif i == -1:
return Spin.down
else:
raise ValueError("Spin integers must be 1 or -1") | [
"def spin(mult):\n return mult - 1",
"def getSpinControl(*args):",
"def spin(self) -> float:\n return self._s",
"def spin(rxn_class):\n return rxn_class[1]",
"def spinWheel():\n\tt = random.randrange(8)\n\tif t == 7:\n\t\treturn \"00\"\n\treturn str(t)",
"def spin2spinor(s):\n up =np.arra... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
String indicating the type of orbital. Is always uppercase. E.g., S, P, D, F, etc. | def orbital_type(self):
return self.name[0].upper() | [
"def getType(self):\n if (self.type == 's'):\n #suit type\n type = \"suit\"\n elif (self.type == 'b'):\n #boss type\n type = \"boss\"\n else:\n notify.error(\"Invalid DNA type: \", self.type)\n\n return type",
"def unit_type(self) ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns an orbital based on the index of the orbital in VASP runs. | def from_vasp_index(i):
return Orbital.all_orbitals[i] | [
"def get_vsolar(self):\n return self.read_register(4098, 1, 3)",
"def getPlanetAt(self, index):\n return self.planeten[index]",
"def orbit_structure(self,f):\n orbit = []\n index = 1\n P = copy(self)\n P.normalize_coordinates()\n F = copy(f)\n F.normalize_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns an orbital from a string representation, e.g., "s", "px". | def from_string(orb_str):
for orb in Orbital.all_orbitals:
if str(orb) == orb_str:
return orb
raise ValueError("Illegal orbital definition!") | [
"def from_str(cls, arc):\n m = cls._str_verif_regex.match(arc)\n\n if m is None:\n raise ValueError('invalid arc string')\n\n return cls(float(m.group(1)), float(m.group(3)), float(m.group(5)))",
"def fromString(cls, string):\n # From SAM specification v1.5, slightly adapted... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
We use cli_url to set CLI URL and reflect this in cli_area to take it from JS. | def _get_cli_area(self):
for rec in self:
rec.cli_area = rec.cli_url | [
"def asset_cli():",
"def custom_cli_file() -> str:\n return f\"slipbox_cli_{uuid.uuid4().hex}.py\"",
"def boilerplate_cli():\n\twith open(os.path.join(\n\t\tos.path.dirname(__file__),'cli_example.txt')) as fp:\n\t\ttext = fp.read()\n\t\tprint(text)",
"def job_cli():",
"def cli(self):\n return self... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Asks for the user to guess numbers and turns the strings to a list | def user_guess():
return list(input("What is your guess?")) | [
"def __get_ints():\n while True:\n try:\n response = input()\n if response: return [int(i) for i in response.split(' ')]\n return None\n except ValueError:\n print(\"Not a Number - try again!\")",
"def from_input_to_list(inputted_string):\n\n created... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
It takes the code generater by the machine and the user's guess then compares the numbers in a loop and creates a list of clues according to the matching parameters | def clues_generator(code, userGuess):
if userGuess == code:
return "Code Cracked!"
clues = []
# Compare guess to code
for ind, num in enumerate(userGuess):
if num == code[ind]:
clues.append("Match")
elif num in code:
clues.append("Close")
if clues ==... | [
"def check_user_guess(user_guess, game_code):\n if user_guess == game_code:\n return \"Game Won\"\n\n results = []\n for index, number in enumerate(user_guess):\n if number == game_code[index]:\n results.append(\"Match\")\n elif number in game_code:\n results.appe... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get compute plugin disabled status | def nfvi_compute_plugin_disabled():
return (_compute_plugin is None) | [
"def get_disabled_plugins(self):\n return self._disabled_plugins",
"def getDisabledPlugin(self, *args):\n return _libsbml.SBase_getDisabledPlugin(self, *args)",
"def get_disabled():\n (enabled_services, disabled_services) = _get_service_list(\n include_enabled=False, include_disabled=Tru... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get a list of host aggregates | def nfvi_get_host_aggregates(callback):
cmd_id = _compute_plugin.invoke_plugin('get_host_aggregates',
callback=callback)
return cmd_id | [
"def compute_host_aggregates(self):\n path = '/os-aggregates'\n res = self.compute.call(path, 'GET', data='', \n token=self.manager.identity.token)\n self.logger.debug('Get openstack host aggregates: %s' % truncate(res))\n return res[0]['aggregates']",
"d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Delete an instance type | def nfvi_delete_instance_type(instance_type_uuid, callback):
cmd_id = _compute_plugin.invoke_plugin('delete_instance_type',
instance_type_uuid,
callback=callback)
return cmd_id | [
"def delete_instance(instanceName=None):\n pass",
"def delete(cls, type_obj):\n DB.session.delete(type_obj)\n DB.session.commit()",
"def help_destroy(self):\n print(\"delete an instance based on the class name and id\")",
"def delete_thing_type(thingTypeName=None):\n pass",
"def t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Cold migrate confirm an instance | def nfvi_cold_migrate_confirm_instance(instance_uuid, callback, context=None):
if context is None:
cmd_id = _compute_plugin.invoke_plugin_expediate(
'cold_migrate_confirm_instance', instance_uuid, context,
callback=callback)
else:
cmd_id = _compute_plugin.invoke_plugin(
... | [
"def migrate_instance():\n logger.debug(\"Migration not yet supported.\")",
"def migrate(self):\n\tpass",
"def post_migrations(self):",
"def model_post_migrate(*args, **kwargs):\n global IN_MIGRATIONS\n IN_MIGRATIONS = False",
"def migrate_cancel(self):\n\t\treturn Job(SDK.PrlVm_MigrateCancel(self.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Cold migrate revert an instance | def nfvi_cold_migrate_revert_instance(instance_uuid, callback, context=None):
cmd_id = _compute_plugin.invoke_plugin('cold_migrate_revert_instance',
instance_uuid, context,
callback=callback)
return cmd_id | [
"def migrate_instance():\n logger.debug(\"Migration not yet supported.\")",
"def migrate(self):\n\tpass",
"def post_revert(self):",
"def migrateDown(self):\n ss = self.avatars.open()\n def _():\n oldAccounts = ss.query(LoginAccount)\n oldMethods = ss.query(LoginMethod)\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reject an action against an instance | def nfvi_reject_instance_action(instance_uuid, message, context):
cmd_id = _compute_plugin.invoke_plugin('reject_instance_action',
instance_uuid, message, context)
return cmd_id | [
"def reject(self):\n self.rejected = True",
"def modReject(self, **kwargs):\n self.checker.modReject(self, **kwargs)\n return self",
"def on_reject(self):\n self.state = REJECTED\n self._reject()",
"def reject(self, message):\n boto_connection = connection.get_connect... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Register for instance action change notifications | def nfvi_register_instance_action_change_callback(callback):
_compute_plugin.invoke_plugin('register_instance_action_change_callback',
callback=callback) | [
"def notify_of_action(self, action):\n raise NotImplementedError()",
"def nfvi_register_instance_action_callback(callback):\n _compute_plugin.invoke_plugin('register_instance_action_callback',\n callback=callback)",
"def update_actions(self):\n pass",
"def not... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Register for instance action callback | def nfvi_register_instance_action_callback(callback):
_compute_plugin.invoke_plugin('register_instance_action_callback',
callback=callback) | [
"def nfvi_register_instance_action_change_callback(callback):\n _compute_plugin.invoke_plugin('register_instance_action_change_callback',\n callback=callback)",
"def register(self, callback):\n self.callback = callback",
"def add_callback(callback, control_instance):\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Notify compute host is enabled | def nfvi_notify_compute_host_enabled(host_uuid, host_name, host_personality,
callback):
cmd_id = _compute_plugin.invoke_plugin('notify_host_enabled',
host_uuid, host_name,
host_personality,
... | [
"def nfvi_notify_compute_host_disabled(host_uuid, host_name, host_personality,\n callback):\n cmd_id = _compute_plugin.invoke_plugin('notify_host_disabled',\n host_uuid, host_name,\n host_pers... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Notify compute host is disabled | def nfvi_notify_compute_host_disabled(host_uuid, host_name, host_personality,
callback):
cmd_id = _compute_plugin.invoke_plugin('notify_host_disabled',
host_uuid, host_name,
host_personality,
... | [
"def notify_host_disabled(self, future, host_uuid, host_name,\n host_personality, callback):\n pass",
"def nfvi_notify_host_services_disabled(host_uuid, host_name, callback):\n cmd_id = _infrastructure_plugin.invoke_plugin(\n 'notify_host_services_disabled', host_uuid,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Disable compute host services | def nfvi_disable_compute_host_services(host_uuid, host_name, host_personality,
callback):
cmd_id = _compute_plugin.invoke_plugin('disable_host_services',
host_uuid, host_name,
host_personalit... | [
"def nfvi_notify_compute_host_disabled(host_uuid, host_name, host_personality,\n callback):\n cmd_id = _compute_plugin.invoke_plugin('notify_host_disabled',\n host_uuid, host_name,\n host_pers... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Enable compute host services | def nfvi_enable_compute_host_services(host_uuid, host_name, host_personality,
callback):
cmd_id = _compute_plugin.invoke_plugin('enable_host_services',
host_uuid, host_name,
host_personality,
... | [
"def enable_host_services(self, future, host_uuid, host_name,\n host_personality, callback):\n pass",
"def nfvi_enable_container_host_services(host_uuid, host_name,\n host_personality,\n callback):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initialize the NFVI compute package | def nfvi_compute_initialize(config, pool):
global _compute_plugin
if _compute_plugin is None:
_compute_plugin = NFVIComputePlugin(config['namespace'], pool)
if _compute_plugin.ready_to_initialize(config['config_file']):
_compute_plugin.initialize(config['config_file'])
return True
... | [
"def nfvi_infrastructure_initialize(config, pool):\n global _infrastructure_plugin\n\n _infrastructure_plugin = NFVIInfrastructurePlugin(config['namespace'], pool)\n _infrastructure_plugin.initialize(config['config_file'])",
"def main():\n run_nutanix_vm_creation_module()",
"def nfvi_identity_initia... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Finalize the NFVI compute package | def nfvi_compute_finalize():
if _compute_plugin is not None:
_compute_plugin.finalize() | [
"def nfvi_infrastructure_finalize():\n if _infrastructure_plugin is not None:\n _infrastructure_plugin.finalize()",
"def finalize(self):\n print(\"Please wait while finalizing the operation.. Thank you\")\n self.save_checkpoint()\n self.summary_writer.export_scalars_to_json(\"{}all_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If we have multiple projects, will loop through the projects to find the one with the given story. returns None if not found | def find_project_for_story(story_id):
for project in Project.all():
story = project.load_story(story_id)
if story is not None:
return project
#Not found
print "No project found for story: #{}".format(story_id)
return None | [
"def find_project_for_story(story_id):\r\n\r\n for project in Project.all():\r\n story = project.load_story(story_id)\r\n if story is not None:\r\n return project\r\n\r\n #Not found\r\n print \"No project found for story: #{}\".format(story_id)\r\n return None",
"def find_proj... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
returns the first label if any from labels. Used for grouping | def first_label(self):
if self.labels:
return self.labels[0]
else:
return None | [
"def first_label(self):\r\n return self.labels.split(',')[0]",
"def first_line(self):\n\n self.label_index = {}\n for index, pair in enumerate(self.lines):\n self.label_index[pair[0]] = index\n\n if self.lines:\n label = self.lines[0][0]\n self.current_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given a filter strong, returns an list of stories matching that filter. If none will return an empty list | def get_stories(self, filter_string):
story_filter = quote(filter_string, safe='')
stories_url = "https://www.pivotaltracker.com/services/v5/projects/{}/stories?filter={}".format(self.project_id, story_filter)
response = _perform_pivotal_get(stories_url)
return [Story.from_json(story_n... | [
"def GetStories(self, filt=None):\n stories = self._ApiQueryStories(filt)\n parsed = xml.dom.minidom.parseString(stories)\n els = parsed.getElementsByTagName('story')\n lst = []\n for el in els:\n lst.append(Story.FromXml(el.toxml()))\n return lst",
"def Filter... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
parses an int from an ElementTree node, if not found returns None | def _parse_int(node, key):
element = node.get(key)
if element is not None:
return int(element)
else:
return None | [
"def _parse_int(node, key):\r\n element = node.find(key)\r\n if element is not None:\r\n return int(element.text)\r\n else:\r\n return None",
"def getint(node):\n try:\n return int(node.text)\n except ValueError:\n raise XMLError(\"Invalid int value for \" + node.tag)",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
parses an boolean from an ElementTree node, if not found returns None | def _parse_boolean(node, key):
element = node.get(key)
if element is not None:
return bool(element)
else:
return None | [
"def _parse_boolean(node, key):\r\n element = node.find(key)\r\n if element is not None:\r\n if element.text == 'true':\r\n return True\r\n else:\r\n return False\r\n else:\r\n return None",
"def parsebool(el):\n txt = text(el)\n up = txt.upper()\n if u... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks if value is a dict | def is_dict(value):
return isinstance(value, dict) | [
"def _is_dict(val):\n\n return isinstance(val, dict)",
"def _is_dict(v):\n return isinstance(v, dict)",
"def test_is_dict(input):\n return isinstance(input, dict)",
"def is_dict(o):\n return isinstance(o, dict)",
"def isDict(data):\n\ttry:\n\t\tfrom types import DictType\n\t\tif type(data) == D... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks if value is a list | def is_list(value):
return isinstance(value, list) | [
"def _is_list(val):\n\n return isinstance(val, list)",
"def isList(data):\n\ttry:\n\t\tfrom types import ListType\n\t\tif type(data) == ListType:\n\t\t\treturn True\n\texcept ImportError:\n\t\tif type(data) == type([]):\n\t\t\treturn True\n\treturn False",
"def isList(self):\n return _yarp.Value_isL... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get epoch time (seconds) from either passed in UTC datetime or current datetime | def get_epoch_time(utc_datetime=None):
if not utc_datetime:
utc_datetime = datetime.datetime.utcnow()
return math.ceil((utc_datetime - EPOCH_START).total_seconds()) | [
"def get_utc_now_as_epoch():\n return convert_dt_to_utc_epoch(get_utc_now_as_dt())",
"def timestampfromutc(utc):\n return (utc - datetime(1970, 1, 1)).total_seconds()",
"def epoch_time_now():\n return int(time.time())",
"def epoch_time_ms_now():\n ms = int(time.time() * 1000)\n return ms",
"d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get epoch time (milliseconds) from either passed in UTC datetime or current datetime | def get_epoch_time_milliseconds(utc_datetime=None):
epoch_seconds = get_epoch_time(utc_datetime)
return epoch_seconds * MILLISECONDS_IN_SECOND | [
"def get_epoch_time(utc_datetime=None):\n if not utc_datetime:\n utc_datetime = datetime.datetime.utcnow()\n return math.ceil((utc_datetime - EPOCH_START).total_seconds())",
"def epoch_time_ms_now():\n ms = int(time.time() * 1000)\n return ms",
"def get_utc_now_as_epoch():\n return convert... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns True if val is Falsy, otherwise returns False | def is_empty(val):
return not bool(val) | [
"def is_truthy(val):\n return bool(val)",
"def scheme_falsep(val):\n return val is False",
"def _val_is_null(self, val):\r\n return val is None",
"def NONE(value):\n return value is None",
"def is_false(value):\n \n return (value is False)",
"def scheme_truep(val):\n return val is n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the food "Item" string with most calories | def get_food_most_calories(df=df):
return df[df.Calories == df.Calories.max()]["Item"].values[0] | [
"def get_food_most_calories(df=df):\r\n max_calories_row = df.loc[df['Calories'].idxmax()]\r\n return max_calories_row['Item']",
"def get_food_most_calories(df: pd.DataFrame = df):\n max_caloires = df.loc[df[\"Calories\"].idxmax()]\n return max_caloires[\"Item\"]",
"def get_food_most_calories(df=df)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calulate the Protein/Calories ratio of foods and return the 5 foods with the best ratio. This function has a excl_drinks switch which, when turned on, should exclude 'Coffee & Tea' and 'Beverages' from this top 5. You will probably need to filter out foods with 0 calories to get the right results. Return a list of the ... | def get_bodybuilder_friendly_foods(df=df, excl_drinks=False):
if excl_drinks:
fltr_excl_drinks = ~df["Category"].isin(["Coffee & Tea", "Beverages"])
else:
fltr_excl_drinks = True
df_nzc = df[(df.Calories != 0) & fltr_excl_drinks] # non zero calories
fltr = (df_nzc.Protein / df_nzc.Calori... | [
"def get_bodybuilder_friendly_foods(\n df: pd.DataFrame = df, excl_drinks: bool = False\n) -> List[str]:\n filtered_df = df[df[\"Calories\"] > 0].copy()\n if excl_drinks:\n filtered_df = filtered_df[\n (filtered_df.Category != \"Coffee & Tea\")\n & (filtered_df.Category != \"Be... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Hydrodynamic added mass matrix of a vertical cylinder | def cylindervert_addedmass(R, z1, z2, rho, Ca=1, AxCa=1,
m_f=0, z_f=0, m_mg=0, z_mg=0):
if z1<z2:
raise Exception('z1 should be above z2')
if z1<0:
# Fully submerged
ztop = z1
A0=0
nAx=2
else:
# Partially submerged
ztop = 0
A0 = np.pi*... | [
"def mass_matrix(self):\n # Inertia Tensor. Principal moments of inertia, and products of inertia [kg*m*m]\n Ixx = float(self.tensor[0])\n Ixy = float(self.tensor[1])\n Ixz = float(self.tensor[2])\n Iyx = float(self.tensor[3])\n Iyy = float(self.tensor[4])\n Iyz = fl... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Does a None user return False | def test_user_is_none(self):
self.assertFalse(send_rotate_to_can(None, self.BIN_NUM)) | [
"def validate_user_is_null(user):\n if user is None:\n print \"Entered user account is not valid\"\n return True\n return False",
"def IsNone(self) -> bool:",
"def test__user_passed_as_none(self):\r\n access.has_access(None, 'staff', 'global', None)",
"def NONE(value):\n return val... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
A CanInfo where a matching user cannot be found returns False | def test_can_info_does_not_exist(self):
fake_user = User(username='Fake', password='')
self.assertFalse(send_rotate_to_can(fake_user, self.BIN_NUM)) | [
"def can_view(self, user):\r\n return True",
"def user_exists(userid):",
"def test_check_user_known_good(self):\n user_identifier = 'duo-atlas-hypnotism-curry-creatable-rubble'\n test_response = check_user(user_identifier = user_identifier)\n self.assertTrue(test_response)",
"def t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
When the channel on the CanInfo is None, return False | def test_request_channel_is_none(self):
CanInfo.objects.filter(can_id=self.UUID).update(channel_name=None)
self.assertFalse(send_rotate_to_can(self.USER, self.BIN_NUM)) | [
"def is_channel(self):\n return True",
"def ccheck(self, msg):\r\n if msg.channel == self.channel or (msg.channel.is_private and self.ispm):\r\n return True\r\n return False",
"def isInChannelBox(self):\n \n pass",
"async def channel_check(ctx):\n\tif ctx.message.chan... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If votes is not a QuerySet or contains the wrong model, TypeError is raised | def test_wrong_input_type(self):
with self.assertRaises(TypeError):
votes_to_percentages(['not', 'a', 'queryset'])
with self.assertRaises(TypeError):
votes_to_percentages(Disposable.objects.all()) | [
"def test_empty_votes(self):\n with self.assertRaises(ValueError):\n votes_to_percentages(DisposableVote.objects.none())",
"def get_votes(self, obj):\n\t\tctype = ContentType.objects.get_for_model(obj)\n\t\tvotes = self.filter(object_id=obj._get_pk_val(), content_type=ctype).count()\n\t\treturn ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If votes is empty, a ValueError is raised | def test_empty_votes(self):
with self.assertRaises(ValueError):
votes_to_percentages(DisposableVote.objects.none()) | [
"def test_missing_vote_value(self) -> None:\n self.clear_votes()\n try:\n message = \"successfully voted\"\n QuestionVote.objects.create(\n question=self.question,\n user=self.user,\n )\n except django.db.IntegrityError:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Busca un cero usando el metodo de la biseccion. func es la funcion, a y b encajonan el cero, tol=toleracia | def biseccion(func, a, b, tol=1e-4):
p = (a + b) / 2
while np.fabs(func(p)) > tol:
p = (a + b) / 2
if func(a) * func(p) < 0:
b = p
elif func(a) * func(p) > 0:
a = p
else:
return p
return p | [
"def biseccion(funcion,x0,x1,tol): \n xr=x0\n a=x0\n b=x1\n k=1\n if (evaluar(funcion,x0) * evaluar(funcion,x1) <0 ):\n while (error(a,b,k)>=tol): \n xr=(x0+x1)/2\n if (evaluar(funcion,x0)*evaluar(funcion,xr)<0):\n x1=xr\n else:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
return the child point q corresponding to p in the parent. note that q.side == p.side THINK ABOUT IT | def parent_to_child(p):
a,b = LINES[p.side]
if p.x < 0.5:
return Point(a, p.side, 2*p.x)
else:
return Point(b, p.side, 2*p.x - 1) | [
"def parent(self,p):\n node = self._validate(p)\n return self._make_position(node._parent)",
"def parent(self, p):\n node = self._validate(p)\n return self._make_position(node._parent)",
"def parent(self, p):\n node = self._validate(p)\n return self._make_position(node.parent)"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
return a random endpoint in the current child not on taken_side | def random_endpoint(child, taken_side=None):
sides = [s for s in SIDES[child] if s != taken_side]
return Point(child, random.choice(sides), 0 if random.random() < 0.5 else 1) | [
"def _get_random_point(self):\n return 2 * self.bound * np.random.rand(self.dimension) - self.bound",
"def get_random_node(self):\n if not self.goal_chosen and random.randint(0, 100) <= self.goal_sample_rate:\n # goal point sampling\n rnd = self.Node(self.end.x, self.end.y)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Loads a .py module from github (raw) Returns a module object | def get_module_from_github(url):
with urlopen(url) as response:
if response.code == 200:
text = str(response.read(), encoding="utf-8")
_, path = mkstemp(suffix=".py", text=True)
with open(path, mode='wt', encoding='utf-8') as fh:
fh.write(text)
directory, file_... | [
"def load_module(self, fullname):\n LOGGER.info('Loading module {0}'.format(fullname))\n if fullname in sys.modules:\n return sys.modules[fullname]\n\n splitted_names = fullname.split('.')\n if 'github' in splitted_names:\n if len(splitted_names) >= 3:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
retuns the quote's text with tagged part of quote chunks | def serialize_quote(self):
partofs = PartOfQuote.objects.filter(part_of=self)
quote = self.text
for x in partofs:
quote = quote.replace(x.text, create_tag(x))
return quote | [
"def process_quote_text(quote_text):\n quote_text = quote_text.replace('―', '').replace('\\n\\n', '\\n')\n quote_text = quote_text[:-1] if quote_text[-1] == '\\n' else quote_text\n for char in HTML:\n quote_text = quote_text.replace(*char)\n return quote_text",
"def _readquotes(self,html,pos):\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Increase the number of xor gateways (split + join) | def inc_xor_gateways(self):
self.num_xor_gateways += 1 | [
"def xor(a, b):",
"def xor_buffers(left, right):\n return bytes(xor_pairs(repeating_zip(left, right)))",
"def xor2(c, a, b):\n\n @always_comb\n def comb():\n c.next = a ^ b\n\n return comb",
"def learn_xor():\n net = init_net([2,2,1],0.5)\n for _ in xrange(5000):\n for inst in ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Increase the number of tau transitions | def inc_tau_trans(self):
self.num_tau_trans += 1 | [
"def incTrials(self, nNewTrials):\r\n self.nTrials += nNewTrials",
"def _kendall_tau_add(self, len_old: int, diff_pos: int, tau_old: float):\n return 2.0 / (len_old + 1) * (float(diff_pos) / len_old - tau_old)",
"def incrementTimeStep(self):\n pass",
"def _kendall_tau_add(self, len_old, d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create a task with the specified label in the BPMN | def add_task(bpmn, counts, label):
from pm4py.objects.bpmn.bpmn_graph import BPMN
task = BPMN.Task(name=label)
bpmn.add_node(task)
return bpmn, task, counts | [
"def create_task(self, name, value):\n pass",
"def tasks_create(\n self,\n name: str,\n labels: List[Dict[str, str]],\n resources: Sequence[str],\n *,\n resource_type: ResourceType = ResourceType.LOCAL,\n annotation_path: str = \"\",\n annotation_form... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parse the www/template.html and createsthe content of file lib/htmltemplate/htmlclasses.py | def parse(force=False):
from htmltemplate import WWW_DIR, TEMPLATE_FILE, TEMPLATE_PY
# pylint: disable=duplicate-string-formatting-argument
print("Parse html template")
lines = open(WWW_DIR+TEMPLATE_FILE).readlines()
pyClassFile = open(TEMPLATE_PY,"w")
pyClassFile.write("''' File automatically generated wit... | [
"def html_template_file(self):\n pass",
"def get_html_template():\n try:\n os.chdir(product_server.HTML_ROOT) # !!\n html = ET.parse(product_server.HTML_TEMPLATE).getroot()\n except IOError as err:\n html = ET.Element('html')\n body = ET.Element('bo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Computes labels and inertia using a full distance matrix. This will overwrite the 'distances' array inplace. | def _labels_inertia_precompute_dense(norm, X, sample_weight, centers, distances):
n_samples = X.shape[0]
if norm == 'L2':
labels, mindist = pairwise_distances_argmin_min(
X=X, Y=centers, metric='euclidean', metric_kwargs={'squared': True})
elif norm == 'L1':
labels, mindist = pai... | [
"def _labels_inertia(X, x_squared_norms, centers, precompute_distance= True, distances = None):\n n_clusters = centers.shape[0]\n n_samples = X.shape[0]\n\n inertia = 0.0\n D = Dcalculus(X[0].shape[0])\n labels = -np.ones(n_samples, np.int32)\n #Assign distances array for intra inertia calculating... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Interactively retrieves the crendential for a user_id client_id user identifier client_secret user's secret key persist True to immediately store the credential, False otherwise (default) | def get_client_credentials_intractive(self, client_id, client_secret, persist=False):
if type(client_id) == unicode:
client_id = client_id.encode('ascii')
if type(client_secret) == unicode:
client_secret = client_secret.encode('ascii')
flow = OAuth2WebServerFlow(... | [
"def test_retrieve_client_credentials_when_set(self):\n s = self.build_session()\n s.params = {\"client_id\": \"id\", \"client_secret\": \"secret\"}\n assert s.retrieve_client_credentials() == (\"id\", \"secret\")",
"def get_credentials():\n store = Storage(CREDENTIAL_PATH)\n credential... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Remove the locally stored credentials | def remove_client_credentials(self):
if self._dry_run:
return
os.unlink(self._store_pathname) | [
"def remove(ctx, all):\n # retrieving from parameter because host_info is already overwritten\n # with old password from credential file\n credentials.remove_credentials(ctx.obj['username'], all)",
"def delete_credentials(self):\n Credentials.credential_details.remove(self)",
"def erase_credent... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the credential store if the file exists | def _load_credential_store(self):
try:
return shelve.open(self._store_pathname)
except Exception:
raise CredentialError('Unable to open credential store: ' + self._store_pathname) | [
"def get_credentials():\n home_dir = os.path.expanduser('~')\n credential_dir = os.path.join(home_dir, '.credentials')\n if not os.path.exists(credential_dir):\n os.makedirs(credential_dir)\n credential_path = os.path.join(credential_dir,'credentials.json')\n\n store = oauth2client.file.Storag... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Flushes and closes the credential store | def _save_credential_store(self, store):
store.close() | [
"def close(self):\n self.save()\n # self.fileKey = None\n if self.openAccount:\n self.openAccount.close()\n self.openAccount = None",
"async def close(self) -> None:\n\n await asyncio.gather(*(credential.close() for credential in self.credentials))",
"async def ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Extract location from FX node stack trace. | def _location_from_fx_stack_trace(
node_stack_trace: str,
) -> Optional[diagnostics.infra.Location]:
if "File" not in node_stack_trace:
return None
lines = node_stack_trace.strip().split("\n")
idx = 0
while idx < len(lines) and "File" not in lines[idx]:
idx += 1
if idx + 1 >= le... | [
"def get_location(self):\n callerframerecord = inspect.stack()[2]\n frame = callerframerecord[0]\n info = inspect.getframeinfo(frame)\n fname = info[0]\n line = info[1]\n return fname, line",
"def getStackPosition(self):\r\n return self.callstack.getStack()",
"de... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Map FX value to TorchScript value. When creating TorchScript graph from FX graph, we need a mapping from FX variable to TorchScript variable. This function maps FX variable, fx_node_arg, to torch.jit.Value. | def _retrieve_or_adapt_input_to_graph_set(
fx_node_arg: fx_type_utils.Argument,
fx_name_to_onnxscript_value: Dict[
str,
Union[
onnxscript_graph_building.TorchScriptTensor,
Tuple[onnxscript_graph_building.TorchScriptTensor, ...],
],
],
tracer: onnxscript_gr... | [
"def call_module(\n self,\n node: torch.fx.Node,\n parent_onnxscript_graph: onnxscript_graph_building.TorchScriptGraph,\n fx_name_to_onnxscript_value: Dict[\n str,\n Union[\n onnxscript_graph_building.TorchScriptTensor,\n Tuple[onnxscri... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Fill the meta information of onnxscript_values with that from the fx FakeTensor. | def _fill_tensor_shape_type(
onnxscript_values: Union[
onnxscript_graph_building.TorchScriptTensor,
Tuple[onnxscript_graph_building.TorchScriptTensor, ...],
],
name: str,
expected_values: Union[
fx_type_utils.META_VALUE_TYPE,
List[fx_type_utils.META_VALUE_TYPE],
T... | [
"def set_values(self):\n\n if self.featureType != \"gene\":\n self.transcriptId = self.meta['transcript_id']\n self.transcriptName = self.meta['transcript_name']\n self.transcriptBioType = self.meta['transcript_biotype']\n if self.featureType == 'exon':\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Export a fx.GraphModule submodule to ONNXScript graph. The export process specifically targets `call_module` nodes that are created by the exporter's `Modularize` pass. Each `call_module` node has an associated fx.GraphModule by `node.target` underneath the root fx.GraphModule. These `call_module` nodes are exported as... | def call_module(
self,
node: torch.fx.Node,
parent_onnxscript_graph: onnxscript_graph_building.TorchScriptGraph,
fx_name_to_onnxscript_value: Dict[
str,
Union[
onnxscript_graph_building.TorchScriptTensor,
Tuple[onnxscript_graph_buil... | [
"def export_finn_onnx(module, input_shape, export_path, input_t = None,\n torch_onnx_kwargs = {}):\n if onnx is None or opt is None:\n raise ModuleNotFoundError(\"Installation of ONNX is required.\")\n\n with torch.no_grad():\n # TODO maybe consider a deepcopy of the module first?\n mo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Restore a queue from a message reader. This publishes to the queue any messages returned by the reader. Any existing messages in the queue will still be in the queue. | def restore(self, reader):
while True:
msg = reader.read()
if msg is None:
break
self.publish(msg) | [
"def reverse_queue(queue):\r\n outqueue = QueueV3()\r\n stack = Stack()\r\n while not queue.length() == 0:\r\n item = queue.dequeue()\r\n stack.push(item)\r\n print('dequeued', item)\r\n while not stack.length() == 0:\r\n item = stack.pop()\r\n outqueue.enqueue(item)\r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
pull alarm from queue if you want | def pull_alarm(self):
self.job = MATCH_QUEUE.take(timeout=settings.QUEUE_WAIT_TIMEOUT)
if not self.job:
raise lock.PassEmpty
# JSON数据格式,反序列化
try:
self.alarm_list = map(json.loads, self.job.body.strip().splitlines())
except Exception as error:
... | [
"def push_alarm(self):\n for alarm in self.alarm_list:\n serialized_alarm = json.dumps(alarm)\n self.bucket_send(serialized_alarm)\n self.bucket_send('', push_remain=True)\n logger.info(\"push alarm to match queue finished(%s)\" % len(self.alarm_list))",
"def alarm(self)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
check whether match for every alarmalarm_defmatch_key the match result will be self.matched_alarm_list | def match_alarm(self):
for alarm in self.alarm_list:
is_matched = False
self._match_alarm_by_def(alarm)
if alarm["_match_info"].get("alarm_def_id"):
self.matched_alarm_list.append(alarm)
is_matched = True
if is_matched:
... | [
"def _match_alarm_by_def(self, alarm, origin_alarm_def_id=None,\n unmatch_log=None):\n if unmatch_log is None and settings.ENV == \"TEST\":\n unmatch_log = True\n\n matched_alarm_def_id = None\n for alarm_def in self.alarm_def_list:\n for match_k... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
match alarm by alarm_def alarm["_match_info"]["alarm_def_id"] will be matched alarm_def's id | def _match_alarm_by_def(self, alarm, origin_alarm_def_id=None,
unmatch_log=None):
if unmatch_log is None and settings.ENV == "TEST":
unmatch_log = True
matched_alarm_def_id = None
for alarm_def in self.alarm_def_list:
for match_key, match_func... | [
"def match_alarm(self):\n for alarm in self.alarm_list:\n is_matched = False\n self._match_alarm_by_def(alarm)\n if alarm[\"_match_info\"].get(\"alarm_def_id\"):\n self.matched_alarm_list.append(alarm)\n is_matched = True\n\n if is_mat... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a list of durations | def get_dur(self):
return [char.get_dur() for char in self.string] | [
"def getDurations(self):\n return self.durations",
"def durations(self):\n return [x.duration() for x in self.intervals]",
"def chunkDurationCalc(self):\n output = [None] * len(self.chunks)\n index = 0\n for chunk in self.chunks:\n initialChunk = chunk[0]\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
My new constructor, which makes sure that the ``FRAME_TOOL_WINDOW`` style is not passed through to the ``AuiFloatingFrame`` constructor | def __init__(self, *args, **kwargs):
if 'style' in kwargs:
style = kwargs['style']
# This is the default style, as defined
# in the AuiFloatingFrame constructor
else:
style = (wx.FRAME_TOOL_WINDOW |
wx.FRAME_FLOAT_ON_PARENT |
... | [
"def _AuiDockingGuide_init(self, *args, **kwargs):\n\n if 'style' in kwargs:\n style = kwargs['style']\n\n # This is the default style, as defined\n # in the AuiDockingGuide constructor\n else:\n style = (wx.FRAME_TOOL_WINDOW |\n wx.FRAME_STAY_ON_TOP |\n wx.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
I am also monkeypatching the ``wx.lib.agw.aui.AuiDockingGuide.__init__`` method, because in this instance, when running over SSH/X11, the ``wx.FRAME_TOOL_WINDOW`` style seems to result in the docking guide frames being given title bars, which is quite undesirable. I cannot patch the entire class in the aui package, bec... | def _AuiDockingGuide_init(self, *args, **kwargs):
if 'style' in kwargs:
style = kwargs['style']
# This is the default style, as defined
# in the AuiDockingGuide constructor
else:
style = (wx.FRAME_TOOL_WINDOW |
wx.FRAME_STAY_ON_TOP |
wx.FRAME_NO_TASKBA... | [
"def UpdateDockingGuides(self, paneInfo):\r\n\r\n if len(self._guides) == 0:\r\n self.CreateGuideWindows()\r\n\r\n captionSize = self._art.GetMetric(AUI_DOCKART_CAPTION_SIZE)\r\n frameRect = GetInternalFrameRect(self._frame, self._docks)\r\n mousePos = wx.GetMousePosition()\r\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate adversarial via CW optimization. | def make_cw(env, X_data, epochs=50, eps=0.1, batch_size=1):
print('\nMaking adversarials via CW')
n_sample = X_data.shape[0]
n_batch = int((n_sample + batch_size - 1) / batch_size)
X_adv = np.empty_like(X_data)
for batch in range(n_batch):
with Timer('Batch {0}/{1} '.format(batch + 1, n_ba... | [
"def optimize(w, b, X, Y, num_iterations,learning_rate,print_cost = False):\n costs = []\n for i in range(num_iterations):\n\n # Cost and gradient calculation (≈ 1-4 lines of code)\n ### START CODE HERE ###\n grads,cost = propagate(w,b,X,Y)\n ### END CODE HERE ###\n\n # Retr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compute orbit positions for the general two body problem from the initial orbital elements with a deterministic mathematical model. Factory function that returns a functional model. | def make_position_model_g2b_math(traj_size = 731):
num_particles = 2
space_dims = 3
t = keras.Input(shape=(traj_size,), name='t')
q0 = keras.Input(shape=(num_particles, space_dims,), name='q0')
v0 = keras.Input(shape=(num_particles, space_dims,), name='v0')
m = keras.Input(shape=(num_particles,)... | [
"def make_physics_model_r2bc_math(position_model: keras.Model, traj_size: int):\n # Create input layers\n t = keras.Input(shape=(traj_size,), name='t')\n q0 = keras.Input(shape=(2,), name='q0')\n v0 = keras.Input(shape=(2,), name='v0')\n mu = keras.Input(shape=(1,), name='mu')\n # The combined inp... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Turns bytes into unicode, if needed. Uses UTF8. | def asunicode(s):
if isinstance(s, bytes):
return s.decode('utf-8', 'replace')
else:
return s | [
"def bytes_to_unicode(value, encoding=\"utf-8\"):\n if value is None or is_unicode(value):\n return value\n assert is_bytes(value)\n return value.decode(encoding)",
"def as_unicode(b):\n try:\n b = b.decode()\n except (AttributeError, UnicodeDecodeError):\n pass\n return b",... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
load_ticker Retrieves market data from external data source (in this case Bloomberg) | def load_ticker(self, time_series_request):
time_series_request_vendor = self.construct_vendor_time_series_request(time_series_request)
data_frame = None
self.logger.info("Request Bloomberg data")
# do we need daily or intraday data?
if (time_series_request.freq in ['daily', '... | [
"def load_ticker(self, market_data_request):\n\n self.logger.info(\"Request Reuters data\")\n\n data_frame_list = self.get_data(market_data_request)\n\n self.logger.info(\"Completed request from Reuters \")\n\n return data_frame_list",
"def remote_load_price(symbol):\n # This is... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Applies a substituition cypher done by the rotor from right to left input_letter > integer that represents the letter rotor > rotor as a list of integers | def _rotor_right2left(rotor, input_letter, offset, ring):
alpha_size = len(ALPHABET)
return (rotor[(input_letter + offset - ring) % alpha_size] - offset +\
ring) % alpha_size | [
"def rotate_word(original, shift):\r\n rotated = \"\"\r\n for c in original:\r\n rot = rotate_letter(c, shift)\r\n rotated = rotated + rot\r\n print rotated",
"def _rotor_left2right(rotor, input_letter, offset, ring):\n\t\tletter = (input_letter + offset - ring) % len(AL... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Applies a substituition cypher done by the rotor from left to right input_letter > integer that represents the letter rotor > rotor as a list of integers | def _rotor_left2right(rotor, input_letter, offset, ring):
letter = (input_letter + offset - ring) % len(ALPHABET)
return (rotor.index(letter) - offset + ring) % len(ALPHABET) | [
"def rotate_word(original, shift):\r\n rotated = \"\"\r\n for c in original:\r\n rot = rotate_letter(c, shift)\r\n rotated = rotated + rot\r\n print rotated",
"def _rotor_right2left(rotor, input_letter, offset, ring):\n\t\talpha_size = len(ALPHABET)\n\t\treturn (rotor[(i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Executes a forward pass through all the rotors from right to left Returns the encrypted letter as an integer | def _forward(self, letter):
self._turn_rotors()
l = letter
for i in range(-1, -self.n_rotors - 1, -1):
l = self._rotor_right2left(self.rotors[i], l, self.offsets[i],
self.rings[i])
return l | [
"def rotate_based(password, *args):\n letter = args[4]\n l_idx = password.index(letter)\n steps = 1 + l_idx\n if l_idx >= 4:\n steps += 1\n\n return rotate_right(password, steps, \"dummy\")",
"def rotate_letter(c, num):\n return chr(((ord(c) - 97) + num) % 26 + 97)",
"def rotated_alphab... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given the letter returned by the reflector, executes a backward pass, cyphering the input letter in all rotors from left to right Returns the output letter as an integer | def _backwards(self, letter):
l = letter
for i in range(self.n_rotors):
l = self._rotor_left2right(self.rotors[i], l, self.offsets[i],
self.rings[i])
return l | [
"def _forward(self, letter):\n\t\tself._turn_rotors()\n\t\tl = letter\n\t\tfor i in range(-1, -self.n_rotors - 1, -1):\n\t\t\tl = self._rotor_right2left(self.rotors[i], l, self.offsets[i],\n\t\t\t\t\t\t\t\t\tself.rings[i])\n\t\treturn l",
"def rotate_based(password, *args):\n letter = args[4]\n l_idx = pass... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Decrypts text. The configuration should be the same as the initial configuration used by the machine for encryption. Use the reset method to reset the offsets if necessary. | def decrypt(self, text):
if self.offsets != self.start_off:
raise Exception("Current offset != starting offset. Use the reset"+\
" method before decrypting.")
return self.encrypt(text) | [
"def decrypt_text(self, text):\n\n if self.enc_alg == CryptoAlg.SDES:\n return self.sdes.decrypt(str(text))\n elif self.enc_alg == CryptoAlg.RC4:\n return self.rc4_dec.decrypt(str(text))\n else:\n return str(text)",
"def decrypt(self, text):\n return se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
FindFile(file) Attempts to locate file in any of the mods folders. If file is a full path, it will attempt to use the GetFile() function to split the folder and file from the full path. Returns a tuple of (folder, file) in either case. If the file is not a full path and can't be found, it will raise FileNotFoundError, ... | def FindFile(seeker):
for folder in var.MOD_LOCATION:
for file in os.listdir(folder):
if file.lower() == seeker.lower():
if not folder.endswith(("/", "\\")):
folder = folder + "\\"
return folder, file
if True in [slash in seeker for slash... | [
"def findfile(file2find):\n cwd = os.getcwd()\n paths = [cwd] + sys.path\n for dirname in paths:\n possible = os.path.join(dirname, file2find)\n if os.path.isfile(possible):\n return possible\n return None",
"def checkFilePath(self, filename, search... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
ExecuteFile(file, params) Runs an executable file located in (one of) the Mods location. Returns the process' return code. | def ExecuteFile(*args): # the docstring lies about parameters
folder, file = FindFile(args[0])
params = args[1:]
log.logger("PARS_EXEC_FILE", format=[file, folder[:-1], params], display=False)
process = subprocess.Popen([folder + file] + list(params))
process.communicate()
return process.retur... | [
"def run_file(file_path, globals_, script_dir=SCRIPT_DIR):\n fix_sys_path()\n script_name = os.path.basename(file_path)\n script_name = SCRIPT_EXCEPTIONS.get(script_name, script_name)\n script_path = os.path.join(script_dir, script_name)\n execfile(script_path, globals_)",
"def do_execfile( self, args ):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
GetFile(file) Splits the folder and file from a full path. Returns a tuple of (folder, file). | def GetFile(file):
file = file.replace("/", "\\").strip("\\")
new = list(file)
new.reverse()
if "\\" not in new:
return None, file # Don't raise an error, but there isn't any folder
indx = new.index("\\")
return file[:-indx], file[-indx:] # Full path and file name | [
"def parse_file_path(file_path):\n\n file_name = os.path.basename(file_path)\n\n cutoff = len(file_path) - len(file_name)\n\n folder_path = file_path[:cutoff]\n\n return folder_path, file_name",
"def separate_folder_file_path(file_path):\n return file_path.split(\"_\", 1)",
"def split_folder_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
ExtractFile(file, dst=None, pw=None) Extracts an archive into the temp folder. Specify a file, a destination and a password. If 'file' is not an archive, it will simply copy it over. If 'dst' is not specified, it will use the file's name. Returns the location of the resulting files. | def ExtractFile(file, dst=None, pw=None):
path, file = FindFile(file)
if file.endswith(".rar"):
type = "rar"
elif file.endswith((".zip", ".7z")):
type = "zip"
else:
type = None
if dst is None:
dst = file
if not dst.endswith(("/", "\\")):
dst = dst + "\\... | [
"def extractfile(file, passwd):\n try:\n zipf = zipfile.ZipFile(file)\n zipf.extractall(path=os.path.join(file[:-4]), pwd=str.encode(passwd))\n print('Password: {}'.format(passwd))\n except:\n pass",
"def extract_zipfile(filename, extract_dir):\n util.file.maybe_rmtree(extract... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
ExtractMod(mod, dst=None, pw=None, range=None, overwrite=True) Checks for a mod's existence and installs it if it exists. 'dst' will be the final location. Defaults to the temp folder if unspecified. 'pw' will be fed as the password to the ExtractFile function. 'range' will be the range for which to check files; it's a... | def ExtractMod(mod, dst=None, pw=None, range=None, overwrite=True):
file = getattr(fl, mod)
if dst is None:
dst = var.BOOTLEG_TEMP + mod
try:
if range is None:
FindFile(file)
else: # explicit override of the range function - yay __builtins__ :D
for num in __... | [
"def ExtractFile(file, dst=None, pw=None):\n\n path, file = FindFile(file)\n\n if file.endswith(\".rar\"):\n type = \"rar\"\n elif file.endswith((\".zip\", \".7z\")):\n type = \"zip\"\n else:\n type = None\n\n if dst is None:\n dst = file\n if not dst.endswith((\"/\", \... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
ExtractFolder(path) Extracts all the archives from a folder into that same folder. Returns a tuple of all the resulting folders' names. | def ExtractFolder(path):
if not path.endswith(("/", "\\")):
path = path + "\\"
folders = []
files = []
for file in os.listdir(path):
files.append(path + file)
_file, ext = GetName(file)
folder = ExtractFile(path + file)
CopyFolder(folder, path + _file)
fo... | [
"def _extract_archive(path: str, extracted_dir_path: str) -> str:\n logging.info('extracting %s to %s', path, extracted_dir_path)\n with tarfile.open(path) as tar:\n tar.extractall(path=extracted_dir_path)\n extracted_items = os.listdir(extracted_dir_path)\n if len(extracted_items) != 1:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |