query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
begin drawing a rectangle when mousebutton is pressed | def __begin_rectangle(self, event):
self.start_point_rect = Point2D(self.canvas.canvasx(event.x), self.canvas.canvasy(event.y))
global choose_rectangle
if choose_rectangle:
self.rectangles.append(self.canvas.create_rectangle(self.start_point_rect.x,
... | [
"def draw_on_clicked(tool, pos):\n x, y = pos\n\n pygame.draw.rect(WIN, tool.color, (x, y, tool.thickness, tool.thickness))",
"def draw_button(self, screen):\n\t\tmouse = pg.mouse.get_pos()\n\t\tfont = pg.font.Font('freesansbold.ttf', 20)\n\t\ttext = font.render(self.text, True, (120,130,135))\n\t\ttextRect... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
expand the begun rectangle | def __expand_rectangle(self, event):
global choose_rectangle
curX = self.canvas.canvasx(event.x)
curY = self.canvas.canvasy(event.y)
w, h = self.canvas.winfo_width(), self.canvas.winfo_height()
if event.x > 0.9 * w:
self.canvas.xview_scroll(1, 'units')
elif ev... | [
"def updateRect(self):\n newRect = self.rectExp()\n if newRect != self.rect:\n self.rect = newRect\n if self.parent:\n self.rect = (self.rect[0] + self.parent.rect[0],\n self.rect[1] + self.parent.rect[1],\n s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
add some points to a polygon stored as line until finish polygon is called | def __draw_polygon(self, event, klick):
global creating_polygon
curX = self.canvas.canvasx(event.x)
curY = self.canvas.canvasy(event.y)
if not klick and len(self.polygon_points) >= 2:
c_r_x, c_r_y = self.get_canvas_relative_coords((self.polygon_points[-2], self.polygon_points... | [
"def appendLine(self):\n # if line has only one point, than dismiss\n if len(self.__line) > 1:\n self.__polylines.append(list(self.__line))\n # new line\n self.clearLine()",
"def update_polygon(self, polygon_points: List[Tuple[float, float]]):\n self.polygon_points = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks if the point (x,y) is outside the image area | def outside(self, x, y):
bbox = self.canvas.coords(self.container) # get image area
if bbox[0] < x < bbox[2] and bbox[1] < y < bbox[3]:
return False # point (x,y) is inside the image area
else:
return True # point (x,y) is outside the image area | [
"def outside(self, x, y):\n bbox = self.canvas_image.coords(self.container) # get image area\n if bbox[0] < x < bbox[2] and bbox[1] < y < bbox[3]:\n return False # point (x,y) is inside the image area\n else:\n return True # point (x,y) is outside the image area",
"de... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Start a docker container and read out its Python version. | def ping_docker():
with Docker('unittest-36', image='python:3.6') as tun:
return tun.call(python_version)[:2] | [
"async def _get_python_version(user_image, python_binary) -> packaging.version.Version:\n\n proc = await asyncio.create_subprocess_exec(\n \"docker\",\n \"run\",\n \"--rm\",\n user_image,\n python_binary,\n \"--version\",\n stdout=subprocess.PIPE,\n stderr=... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Infinite recursion, requiring depth limit to stop. | def recursive():
with Local() as tun:
tun.call(recursive) | [
"def test_max_depth(self):\n sys.setrecursionlimit(200)\n code = 'endlessly_recursive_func(0)'\n suggs = [\"increase the limit with `sys.setrecursionlimit(limit)`\"\n \" (current value is 200)\", AVOID_REC_MSG]\n self.throws(code, MAXRECURDEPTH, suggs)\n sys.setrec... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Recursive tunneling is limited by a depth limit. | def test_depth_limit(self):
with self.assertRaisesRegexp(
RemoteException,
r'.*DepthLimitExceeded: Depth limit of 2 ' +
'exceeded at localhost -> localhost -> localhost'):
recursive() | [
"def test_max_depth(self):\n sys.setrecursionlimit(200)\n code = 'endlessly_recursive_func(0)'\n suggs = [\"increase the limit with `sys.setrecursionlimit(limit)`\"\n \" (current value is 200)\", AVOID_REC_MSG]\n self.throws(code, MAXRECURDEPTH, suggs)\n sys.setrec... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
r""" Return the busses' efficiency. | def calc_bus_efficiency(self, bus):
return bus.comps.loc[self, 'char'].evaluate(self.calc_bus_expr(bus)) | [
"def cost(self) -> float:",
"def efficiency(self):\n return self.propeller_selector[1]",
"def boatSpeedMeasure(self) -> MeasureCompact:\r\n return self.boatSpeedMeasure",
"def determine_cost(self):\n pass",
"def calculate_cost(self):\n booking_days, booking_hours = self.calculate... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
r""" Return the busses' value of the component's energy transfer. | def calc_bus_value(self, bus):
b = bus.comps.loc[self]
comp_val = self.bus_func(b)
expr = self.calc_bus_expr(bus)
if b['base'] == 'component':
return comp_val * b['char'].evaluate(expr)
else:
return comp_val / b['char'].evaluate(expr) | [
"def energy(self):\n return self.mc.energy(self.chain)",
"def energy(self):\n return self.elstate.energy(self.vsig)",
"def E(self):\n return self.generic_getter(get_energy, \"E\", \"convert_energy\")",
"def get_energy(self):\n return self.bot_client.send_command(_Command.GetEnergy)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
r""" Propagate the fluids towards connection's target in recursion. | def propagate_fluid_to_target(self, inconn, start, entry_point=False):
if not entry_point and inconn == start:
return
conn_idx = self.inl.index(inconn)
outconn = self.outl[conn_idx]
for fluid, x in inconn.fluid.val.items():
if (not outconn.fluid.val_set[fluid] a... | [
"def propagate_fluid_to_target(self, inconn, start, entry_point=False):\n return",
"def slew_to_target(self):\n raise NotImplementedError",
"def propagate_fluid_to_target(self, inconn, start, entry_point=False):\n if not entry_point and inconn == start:\n return\n if incon... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
r"""Check parameter value limits. | def check_parameter_bounds(self):
for p in self.variables.keys():
data = self.get_attr(p)
if isinstance(data, dc_cp):
if data.val > data.max_val + err:
msg = (
'Invalid value for ' + p + ': ' + p + ' = ' +
... | [
"def test_param_accessor_value_above_max(self, test_param_accessor):\n bad_value = 100000\n with pytest.raises(ParameterTreeError) as excinfo:\n test_param_accessor.md_minmax_accessor.set(bad_value)\n\n assert \"{} is above the maximum value {} for {}\".format(\n bad_v... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
r"""Entropy balance calculation method. | def entropy_balance(self):
return | [
"def entropy_balance(self):\n T_ref = 298.15\n p_ref = 1e5\n o = self.outl[0]\n self.S_comb = o.m.val_SI * (\n o.s.val_SI -\n s_mix_pT([0, p_ref, 0, o.fluid.val], T_ref, force_gas=True))\n for c in self.inl:\n self.S_comb -= c.m.val_SI * (\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
r""" Exergy balance calculation method. | def exergy_balance(self, T0):
self.E_P = np.nan
self.E_F = np.nan
self.E_bus = {
"chemical": np.nan, "physical": np.nan, "massless": np.nan
}
self.E_D = np.nan
self.epsilon = np.nan | [
"def exergy_balance(self, T0):\n if self.inl[0].T.val_SI >= T0 and self.outl[0].T.val_SI >= T0:\n self.E_P = self.outl[0].Ex_physical - self.inl[0].Ex_physical\n self.E_F = self.P.val\n elif self.inl[0].T.val_SI <= T0 and self.outl[0].T.val_SI > T0:\n self.E_P = self.o... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
r""" Calculate the vector of residual values for fluid balance equations. Returns | def fluid_func(self):
residual = []
for i in range(self.num_i):
for fluid, x in self.inl[0].fluid.val.items():
residual += [x - self.outl[0].fluid.val[fluid]]
return residual | [
"def fluid_func(self):\n residual = []\n for fluid, x in self.outl[0].fluid.val.items():\n res = -x * self.outl[0].m.val_SI\n for i in self.inl:\n res += i.fluid.val[fluid] * i.m.val_SI\n residual += [res]\n return residual",
"def residual(self,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
r""" Calculate partial derivatives for all fluid balance equations. Returns | def fluid_deriv(self):
deriv = np.zeros((self.fluid_constraints['num_eq'],
2 * self.num_i + self.num_vars,
self.num_nw_vars))
for i in range(self.num_i):
for j in range(self.num_nw_fluids):
deriv[i * self.num_nw_fluids + j, ... | [
"def fluid_deriv(self):\n # derivatives for cooling liquid composition\n deriv = np.zeros((\n self.num_nw_fluids * 4,\n 5 + self.num_vars,\n self.num_nw_vars))\n\n k = 0\n for fluid, x in self.inl[0].fluid.val.items():\n deriv[k, 0, 3 + k] = 1\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the list of logged messages. If the bitvector function includes `log_msg` calls in its ``eval``, this method return the list of messages logged in the last evaluation with the format field objects applied. Otherwise, an exception is raised. See also `log_msg`. | def get_formatted_logged_msgs(cls):
if cls._logger is None:
raise ValueError("eval must be called before get_formatted_logged_msgs")
list_msgs = []
for format_string, format_field_objects in cls._logger:
list_msgs.append(format_string.format(*format_field_objects))
... | [
"def get_formatted_logged_msgs(self):\n if self.ch_model._logger is None:\n return []\n list_msgs = []\n replacements = {vp.val: cp.val for vp, cp in self.var_prop2ct_prop.items()}\n for format_string, format_field_objects in self.ch_model._logger:\n for i in range(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the class name and the current number of rounds. | def get_name(cls):
return f"{super().get_name()}_{cls.num_rounds}R" | [
"def report_rounds(self):\n return print(f\"Total Rounds played: {sum([self.wins, self.draws, self.losses])}\")",
"def get_current_round(self) -> int:\n return self.get_game_history().current_turn",
"def getRound(self):\n\n status = self.getStatus()\n return status['round']",
"def ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the `SSA` object of the roundbased bitvector function. This method calls `BvFunction.to_ssa` with the same argument list, and stores the round outputs in the `SSA` object if `add_round_outputs` calls were added in ``eval``. | def to_ssa(cls, input_names, id_prefix, decompose_sec_ops=False, **ssa_options):
my_ssa = super().to_ssa(input_names, id_prefix, decompose_sec_ops=decompose_sec_ops, **ssa_options)
if cls._rounds_outputs is not None:
my_ssa._rounds_outputs = cls._rounds_outputs[:]
return my_ssa | [
"def to_bvfunction(self):\n _input_widths = [v.width for v in self.input_vars]\n _output_widths = [v.width for v in self.output_vars]\n\n class MyBvFunction(BvFunction):\n input_widths = _input_widths\n output_widths = _output_widths\n _ssa = self\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set `RoundBasedFunction.num_rounds` and update `input_widths` and ``output_widths`` if necessary. | def set_num_rounds(cls, new_num_rounds):
raise NotImplementedError("subclasses need to override this method") | [
"def num_rounds(self, num_rounds):\n self._num_rounds = num_rounds",
"def setrounds(self, number):\n self._rounds = number",
"def set_alg_rounds(self, t):\n self.alg_rounds = t",
"def set_num_rounds_and_return(cls, new_num_rounds):\n cls.set_num_rounds(new_num_rounds)\n retu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Call `set_num_rounds` and return ``cls``. | def set_num_rounds_and_return(cls, new_num_rounds):
cls.set_num_rounds(new_num_rounds)
return cls | [
"def set_num_rounds(cls, new_num_rounds):\n raise NotImplementedError(\"subclasses need to override this method\")",
"def make_rounds(self):\n if self.options['auto_rounds'] is None:\n self.make('rounds')\n else:\n if os.path.exists(self._csv_file_path('rounds')):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the list of round outputs obtained in the last evaluation. See also `add_round_outputs`. | def get_rounds_outputs(cls):
if cls._rounds_outputs is None:
raise ValueError("eval must be called before get_rounds_outputs")
return cls._rounds_outputs | [
"def get_round_separators(self):\n if getattr(self, \"_rounds_outputs\", None) is None:\n return None\n if len(self._rounds_outputs) == 0:\n return None\n return self._rounds_outputs[:-1]",
"def get_round_separators(self):\n if getattr(self.ch_model, \"_rounds_out... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check whether the last assignments are SSAReturn of the output variables. | def _are_last_assignments_valid(assignments, output_vars, ignore_exception=True):
assert isinstance(assignments, collections.OrderedDict)
if len(assignments) == 0:
return False
last_assignments = []
for assign_outvar in reversed(assignments):
last_assignments.appe... | [
"def is_ret(ea):\r\n return sark.Line(ea).insn.is_ret",
"def _check_return_at_the_end(self, node):\n if len(self._return_nodes[node.name]) > 1:\n return\n if len(node.body) <= 1:\n return\n\n last = node.body[-1]\n if isinstance(last, astroid.Return):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return an executable string representation. This method returns a string so that ``eval(self.vrepr())`` returns a new `SSA` object with the same content. >>> from cascada.bitvector.core import Variable >>> from cascada.bitvector.operation import BvXor, BvIdentity >>> from cascada.bitvector.ssa import BvFunction >>> z =... | def vrepr(self):
return "{}(input_vars={}, output_vars={}, assignments={}{})".format(
type(self).__name__,
f"[{', '.join([v.vrepr() for v in self.input_vars])}]",
f"[{', '.join([v.vrepr() for v in self.output_vars])}]",
f"[{', '.join([f'({v.vrepr()}, {e.vrepr()})'... | [
"def srepr(self):\n from cascada.bitvector import printing\n return (printing.BvShortPrinter()).doprint(self)",
"def to_str(self):\n\n func_str = q_consts.scalar_func_str.format(fn_name=\"to_str\")\n func = executor.eval_lua(func_str)\n result = func(self.base_scalar)\n r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return two strings (header and body) of a C function evalauting the SSA. This method returns two strings (the function header and the function body) of a function in the C programming language that computes the SSA. The C function is of ``void`` type and its list of arguments consists of the input variables, the extern... | def get_C_code(self, C_function_name):
from cascada.bitvector.printing import BvCCodePrinter
width2type = BvCCodePrinter._width2C_type
# in C, * binds to the declarator, not the type specifier
input_vars_c = ', '.join(["{} {}".format(width2type(v.width), v.name) for v in self.input_var... | [
"def to_bvfunction(self):\n _input_widths = [v.width for v in self.input_vars]\n _output_widths = [v.width for v in self.output_vars]\n\n class MyBvFunction(BvFunction):\n input_widths = _input_widths\n output_widths = _output_widths\n _ssa = self\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a `BvFunction` that evaluates ``self``. The returned `BvFunction` stores ``self`` in the ``_ssa`` attribute. Moreover, the method `BvFunction.to_ssa` of the returned `BvFunction` raises an exception unless it is called with the same arguments that were used to create ``_ssa`` (in this case ``_ssa`` is returned).... | def to_bvfunction(self):
_input_widths = [v.width for v in self.input_vars]
_output_widths = [v.width for v in self.output_vars]
class MyBvFunction(BvFunction):
input_widths = _input_widths
output_widths = _output_widths
_ssa = self
@classmethod
... | [
"def get_function(self):\n return SSAFunction(self.get_graph())",
"def Avv_func(f):\n\n def Avv(x, v):\n def F(s):\n return f(x + v * s)\n\n return jacfwd(jacfwd(F))(0.0)\n\n return Avv",
"def as_vector(self):\n if self.is_vector():\n return self\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Split into multiple `SSA` objects given the list of variable separators. | def split(self, var_separators):
assert len(var_separators) >= 1
_listify = lambda s: list(s) if isinstance(s, collections.abc.Sequence) else [s]
input_vars_set = set(self.input_vars)
external_vars_set = set(self.external_vars)
# remove input and external vars from var_separat... | [
"def SplitMany(ss: List[HeritageAwareString],\n separator: str) -> List[HeritageAwareString]:\n result = []\n for s in ss:\n result.extend(Split(s, separator))\n return result",
"def multi_split(text, seps):\n if not seps: # split by whitespaces\n return text.split()\n else: # spli... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the round separators if the SSA was obtained from a `RoundBasedFunction`. If the `SSA` object was obtained from `RoundBasedFunction.to_ssa` of a `RoundBasedFunction` including `add_round_outputs` calls in its ``eval``, this method returns a list with the round outputs delimiting the rounds. Otherwise, ``None`` i... | def get_round_separators(self):
if getattr(self, "_rounds_outputs", None) is None:
return None
if len(self._rounds_outputs) == 0:
return None
return self._rounds_outputs[:-1] | [
"def get_round_separators(self):\n if getattr(self.ch_model, \"_rounds_outputs\", None) is None:\n return None\n if len(self.ch_model._rounds_outputs) == 0:\n return None\n return tuple(tuple(self.ch_model.prop_type(v) for v in lv)\n for lv in self.ch_m... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compile a C function given its C code as two strings (function header and body). | def _compile_C_code(header, body, return_unloaded=False, verbose=False):
import importlib
import tempfile
import uuid
import cffi
module_name = "module_" + uuid.uuid4().hex
if "__uint128" in header:
raise ValueError("_compile_C_code does not support bit-vector widths "
... | [
"def compile_func(source, name, argspec='', filename='<string>', lineoffset=0,\n env=None):\n # Adjust for 'def' line\n lineoffset -= 1\n\n code = source.rstrip().replace('\\t', ' ')\n lines = (' ' + line for line in code.split('\\n'))\n code = '\\n'.join(lines)\n defined = '... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
returns progress as a number between 0 and 100 | def progress(self):
return self.progressValue | [
"def get_progress(self):\n\n data = self.make_request(REQUEST_PROGRESS_MESSAGE)\n regex_res = PROGRESS_REGEX.search(data)\n current = int(regex_res.group(1))\n max_val = int(regex_res.group(2))\n percentage = current / max_val * 100\n return round(percentage, PERCENTAGE_DIG... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parse a file from Dunbrack's PICSE server. This will iterate all lines in the file and extract the list of proteins that match the resolution criteria. | def parse_file(self, path, max_resolution, threshold, proteins={}):
"""
create regex pattern here so it is not done repeatedly while parsing file
groups:
0 - Protein ID
1 - Chain ID
2 - Length of protein chain
3 - Exptl.
... | [
"def _parse(self, file):\n self.psl = {}\n for line in file.readlines():\n line = line.decode(\"utf-8\")\n line = re.sub(r\"//.*\", \"\", line)\n line = re.sub(r\"\\s.*\", \"\", line)\n if len(line) > 0:\n exc = False\n if line[0] == \"!\":\n exc = True\n li... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create an instance by evaluating all constraints in the problem. The ``problem`` is a DnaChisel DnaOptimizationProblem. | def from_problem(problem, autopass_constraints=True):
def evaluate(constraint):
if (
autopass_constraints
and constraint.enforced_by_nucleotide_restrictions
):
return SpecEvaluation(
constraint,
prob... | [
"def phase_I_problem_from(cls, problem: LinearConstraintsProblem) -> LinearProblem:\n n = problem.n\n m = len(problem.constraints)\n\n e_x = np.zeros(shape=n)\n e_z = np.ones(shape=m)\n e = np.concatenate((e_x, e_z))\n\n x0 = np.zeros(n)\n # we dont need to look at s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return color 60f979 if evaluation.passes else f96c60. | def success_failure_color(self, evaluation):
return "#60f979" if evaluation.passes else "#f96c60" | [
"def PASOS_COLOR():\n return 128",
"def consultar_color_actual(self):\r\n\t\treturn self.color_actual",
"def TrueColor(self) -> int:",
"def get_colour(red, green, blue):\n if int(red * 5) == int(green * 5) == int(blue * 5):\n # If colour is shade of grey\n ansi_code = 232 + (int(red * 2... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a global SUCCESS or FAILURE message for all evaluations. | def text_summary_message(self):
failed = [e for e in self.evaluations if not e.passes]
if failed == []:
return "SUCCESS - all constraints evaluations pass"
else:
return "FAILURE: %d constraints evaluations failed" % len(failed) | [
"def error_all(message: str, points_total: int = 0, expected: bool = False) -> str:\n status = Test.Status.ERROR if expected else Test.Status.ERROR_ALL\n return Test.format_result(\n test_name=\"All tests\",\n status=status,\n output=message,\n points_earned... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Renvoie la première lettre de chacun des mots de chaîne_mots >>> construire_initiales(11, ["Hello","World"]) 'HW' >>> construire_initiales(21, ["rentre", "avec", "tes", "pieds"]) 'RATP' | def construire_initiales(nb_lettres: int, chaîne_mots: list) -> str:
initiales = ""
for mot in chaîne_mots:
initiales += mot[0].upper()
return initiales | [
"def _distribueMainsInitiales(self):\n self._set_taille_main()\n logger.info(\"Distribution des mains de départ\")\n logger.debug(f\"liste des joueurs : {self.list_joueur}\")\n for joueur in self.list_joueur:\n joueur.complete_main()",
"def construit_arete (l,part = 0.15):\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Synchronously sends a button one time. | def send_one(self, button):
self.client.send_one(self.name, button) | [
"def wait_for_button(self, button, message=True):\n if message:\n rospy.loginfo(\"Waiting for xbox button: \" + button)\n \n wait_for(lambda: not self.get_button(button) == 0)",
"def wait_for_buttons(self, threaded=True):\n\t\tRPIO.wait_for_interrupts(threaded)",
"def press(s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
initializes id and title | def __init__(self,
id = 'abbrev',
title = "Abbreviation Bibliography ID Cooker"):
self.id = id
self.title = title | [
"def __init__(self, title):\n self._title = title",
"def __init__(self, cd_id, cd_title, cd_artist):\r\n self.id = cd_id\r\n self.title = cd_title\r\n self.artist = cd_artist",
"def _init_titles(self):\r\n super(ModelRestApi, self)._init_titles()\r\n class_name = self.d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
cooks a bibref id for one reference entry dict | def _cookIdCore(self, ref, **kwargs):
# AUTHORS
namepart='nobody'
if self._refHasAuthorNames(ref):
lastnames = []
for each in ref['authors']:
if each.get('lastname', None):
lastnames.append(each['lastname'])
if len(lastnam... | [
"def lookup(id_reference):\n\n data = summary(id_reference)\n pmid = data.get(\"pmid\", None)\n if pmid:\n pmid = int(pmid)\n\n return Reference(\n authors=str(data.get(\"authorString\", \"\")),\n location=str(pretty_location(data)),\n title=str(clean_title(data.get(\"title\"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test for when clone lun is not passed a block count. | def test_clone_lun_zero_block_count(self):
lun = netapp_api.NaElement.create_node_with_children(
'lun-info',
**{'alignment': 'indeterminate',
'block-size': '512',
'comment': '',
'creation-timestamp': '1354536362',
'is-space-all... | [
"def test_clone_lun_zero_block_count(self):\n\n self.library._get_lun_attr = mock.Mock(return_value={'Volume':\n 'fakeLUN'})\n self.library.zapi_client = mock.Mock()\n self.library.zapi_client.get_lun_by_args.return_value = [\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks if symbol is a valid device | def _check_validdevice(self, symbol):
if symbol.type == self.scanner.KEYWORD and \
symbol.id in self.validdeviceids:
return True
else:
return False | [
"def _is_device_available():\n result = get_serial_no()\n if result[1].strip() == \"unknown\":\n return False\n else:\n return True",
"def valid_device(pattern):\n return re.compile(r\"^[cdp][0-9]{1}$\").match(pattern) is not None",
"def _check_devicelist(self):\n self.symbol = ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks if symbol is a valid parameter | def _check_validparam(self, symbol):
if symbol.type == self.scanner.KEYWORD and \
symbol.id in self.validparamids:
return True
else:
return False | [
"def valid_symbol(self, symbol):\r\n if symbol not in self.alphabet: return False\r\n return True",
"def _check_function_param_name(self, function_param_name):",
"def _is_valid_input(self, parameter_name):\n raise NotImplementedError()",
"def IsParameter(self,name):\n if not self.IsSym... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check correctness of the symbol START | def _check_fixed_start(self):
self.symbol = self.scanner.get_symbol()
if self.symbol.type == self.scanner.KEYWORD and \
self.symbol.id == self.scanner.START_ID:
pass
elif self._is_eof(self.symbol):
# In case file ends prematurely
pass
e... | [
"def valid_start(start, lines):\r\n if start.isalpha(): # start word must be alphabetic\r\n if len(start) > 1: # start word must be larger than 1 character\r\n if start in lines: # start word must be in the list of words\r\n return \"0\"\r\n else:\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if symbol is a valid DType input | def _check_validdtypeinput(self, symbol):
if symbol.type == self.scanner.KEYWORD and \
symbol.id in self.validdtypeinputs:
return True
else:
return False | [
"def _check_validdtypeoutput(self, symbol):\n if symbol.type == self.scanner.KEYWORD and \\\n symbol.id in self.validdtypeoutputs:\n return True\n else:\n return False",
"def is_symbol(obj):\n return isinstance(obj, Symbol)",
"def isSymbol(form):\n return... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if symbol is a valid DType output | def _check_validdtypeoutput(self, symbol):
if symbol.type == self.scanner.KEYWORD and \
symbol.id in self.validdtypeoutputs:
return True
else:
return False | [
"def _check_validdtypeinput(self, symbol):\n if symbol.type == self.scanner.KEYWORD and \\\n symbol.id in self.validdtypeinputs:\n return True\n else:\n return False",
"def is_symbol(obj):\n return isinstance(obj, Symbol)",
"def test_get_symbol_type(type_sca... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks for a semicolon | def _is_semicolon(self, symbol):
if symbol.type == self.scanner.SEMICOLON:
return True
else:
return False | [
"def _check_semicolon_else_skip(self, symbol):\n if symbol.type == self.scanner.SEMICOLON:\n pass\n else:\n self._display_syntax_error(\"semicolon\")\n # Skip to semicolon at end of line\n self._semicolon_skipper()",
"def _check_semicolon(line_index, input... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check for a semicolon, otherwise skip to end of line | def _check_semicolon_else_skip(self, symbol):
if symbol.type == self.scanner.SEMICOLON:
pass
else:
self._display_syntax_error("semicolon")
# Skip to semicolon at end of line
self._semicolon_skipper() | [
"def _check_semicolon(line_index, input_line):\n global _total_lines_of_code\n if input_line.endswith(';'):\n _code_lines.append(line_index)\n _total_lines_of_code += 1",
"def is_skippable(line: str) -> bool:\n return len(line) == 0 or line[0] == ';'",
"def _has_trailing_semicolon(src: st... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks for a comma | def _is_comma(self, symbol):
if symbol.type == self.scanner.COMMA:
return True
else:
return False | [
"def contains_comma(self, *args):\n return _ida_hexrays.cexpr_t_contains_comma(self, *args)",
"def comma_detector(self) -> bool:\n curr_pos = self.fileobject.tell()\n line = self.nextline()\n comma = False\n # A bold presumption, perhaps\n if ',' in line:\n com... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks if symbol is = | def _is_equal(self, symbol):
if symbol.type == self.scanner.EQUALS:
return True
else:
return False | [
"def check_equal(operator):\n\tif operator == \"=\":\n\t\treturn True",
"def have_equal_symbol(l):\r\n if \"=\" in str(l):\r\n return 1\r\n else:\r\n return 0",
"def check_for_equalchar(targst, labelst):\n if '=' not in targst:\n raise Exception('','No \"' + labelst + '=\" was foun... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks if symbol is a number | def _is_number(self, symbol):
if symbol.type == self.scanner.NUMBER:
return True
else:
return False | [
"def is_numeral(self, symbol: str) -> bool:\n return symbol in self.numerals",
"def is_number(symbol):\n return isa(symbol, complex) or is_rational(symbol)",
"def is_int(symbol):\n return isa(symbol, int)",
"def _is_num(self, s):\n try:\n float(s)\n return True\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks if symbol is END | def _is_end(self, symbol):
if symbol.id == self.scanner.END_ID:
return True
else:
return False | [
"def _is_eof(self, symbol):\n if symbol.type == self.scanner.EOF:\n return True\n else:\n return False",
"def is_eof(eof):\n return eof == Symbol('#!eof')",
"def end_marker(data):\n if ord(data[-1]) == 10 and data[-2] == '}':\n return True",
"def does_end_token... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks if symbol is period | def _is_period(self, symbol):
if symbol.type == self.scanner.PERIOD:
return True
else:
return False | [
"def _has_dot(self, tokens):\n return '.' in tokens",
"def contains_only_digit_period(cell):\n # Check if empty\n if check_empty(cell):\n return True\n return not bool(re.match(\"^[\\d\\.]+$\", str(cell)))",
"def validPeriod(period):\r\n try:\r\n i = float(period)\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks if symbol is arrow | def _is_arrow(self, symbol):
if symbol.type == self.scanner.ARROW:
return True
else:
return False | [
"def is_arrow(self, index, line):\n if index >= len(line) - 1:\n return False\n else:\n return line[index] == '-' and line[index+1] == '>'",
"def render_arrow(arrow):\r\n if arrow == '->':\r\n return u'\\u2192'\r\n if arrow == '<->':\r\n retu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks if symbol is EOF | def _is_eof(self, symbol):
if symbol.type == self.scanner.EOF:
return True
else:
return False | [
"def is_eof(eof):\n return eof == Symbol('#!eof')",
"def _is_end(self, symbol):\n if symbol.id == self.scanner.END_ID:\n return True\n else:\n return False",
"def isEOF(self):\n return _libsbml.XMLToken_isEOF(self)",
"def is_eof(self) -> bool:\n ...",
"de... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks the entire devices list until END DEVICE is reached | def _check_devicelist(self):
self.symbol = self.scanner.get_symbol()
# Repeatedly call _check_deviceline() until END DEVICE
while (
not self._is_end(
self.symbol)) and (
not self._is_eof(
self.symbol)):
self._check_deviceline()
... | [
"def waitForDevices(self):\n for devclass in XendDevices.valid_devices():\n self.getDeviceController(devclass).waitForDevices()",
"def scan_devices(self):\n _LOGGER.debug(\"Scan_devices invoked.\")\n if self._update_info() == False:\n # self.hass.data[DOMAIN]['devices'] ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks the entire connections list until END CONNECTIONS is reached | def _check_connectionlist(self):
self.symbol = self.scanner.get_symbol()
# Repeatedly call _check_connectionline() until END CONNECTIONS
while (
not self._is_end(
self.symbol)) and (
not self._is_eof(
self.symbol)):
self._check_... | [
"def __connect(self):\n while 1:\n for address in self.addrList:\n self.log.info(\"try connecting to\", address)\n if self.__connectTo(address):\n self.log.info(\"connection open to \" + address)\n return\n self.log.info(\"failed connecting to {}, waiting 15 seconds\".fo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks validity of each line in the connections list | def _check_connectionline(self):
self.connection_first_device, \
self.connection_first_port \
= self._check_validconnectionoutput()
if self._is_arrow(self.symbol):
# Get next symbol
self.symbol = self.scanner.get_symbol()
self.connection_second... | [
"def _check_connectionlist(self):\n self.symbol = self.scanner.get_symbol()\n # Repeatedly call _check_connectionline() until END CONNECTIONS\n while (\n not self._is_end(\n self.symbol)) and (\n not self._is_eof(\n self.symbol)):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create own make_connection to handle the fact that first device may sometimes not have a port specified. | def _connection_maker(
self,
first_device,
first_port,
second_device,
second_port):
if first_port is None:
return self.network.make_connection(
first_device.id, None,
second_device.id, second_port.id)
... | [
"def test_make_connection_with_preset_host_port(self, mock_get_port,\n mock_start_subprocess,\n mock_socket_create_conn):\n del mock_get_port\n socket_resp = [b'{\"status\": true, \"uid\": 1}']\n self._make_clie... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Use network's check_network() to test all connections. | def _check_whole_network(self):
if not self.network.check_network():
# check_network has failed, issue error
self._display_semantic_error("network") | [
"def test_monitorNetworkStatus(self):\n self.setup_monitorNodeUpdates()\n self.setup_checkNodeLinks()\n \n self.checkNodeUpdates()\n self.checkNodeLinks()",
"def test_connections(self) -> None:\n for server in self.servers:\n server.verify_connected()",
"def test_ge... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks the entire monitors list until END MONITORS is reached | def _check_monitorlist(self):
self.symbol = self.scanner.get_symbol()
# Repeatedly call _check_monitorline() until END MONITORS
while (
not self._is_end(
self.symbol)) and (
not self._is_eof(
self.symbol)):
self._check_monitorli... | [
"def _sync_monitors(self):\n existing = {}\n params = self.params.copy()\n params.update({\"alert_contacts\": 1})\n fetched = self._api_post_paginated(\n \"getMonitors\", params, lambda x: x[\"monitors\"])\n for monitor_dict in fetched:\n m = Monitor(**monito... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function that gets run once every watchdog_period_seconds. | def watchdog(self):
pass | [
"def enable_watchdogs():\n enableWatchdogs()",
"def AutonomousPeriodic(self):\n Scheduler.GetInstance().Run()",
"def watchdog_period(self):\n return self.__get_integer(\"watchdog\", \"period\")",
"def watchdog(self, loop):\n while True:\n if (self.reconnect_time > 0 and \n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Computes the L2 error of the adapted solution compared to the solution on the finest grid. The tree_adapted must have been projected to the finest grid first. | def global_error_to_finest_grid(tree_adapted, tree_finest):
error = 0
for index in tree_finest.tree_leaves:
error += (tree_finest.nvalue[index] - tree_adapted.nvalue[index])**2
error = math.sqrt(error)
if tree_finest.dimension == 1:
dx = mesh.space_step(tree_finest, tree_fine... | [
"def getL2Error(self,exactSolution):\n value = 0\n error = np.array(self.solution)-np.array([exactSolution(x) for x in self.triangulation.points])\n for ele,triPoints in enumerate(self.triangulation.simplices):\n transformMatrix,translateVector = self.calculateTransform(ele)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieves an updated list of tickers for companies included in the S&P 500. Saves to a pickle file. | def retrieve_sp500():
source = 'https://en.wikipedia.org/wiki/List_of_S%26P_500_companies'
resp = requests.get(source)
soup = bs.BeautifulSoup(resp.text, 'lxml')
table = soup.find('table', {'class': 'wikitable sortable'})
tickers = []
for row in table.findAll('tr')[1:]:
ticker = r... | [
"def save_sp500tickers():\n tickers = []\n\n #changed from http to https\n resp = requests.get('https://en.wikipedia.org/wiki/List_of_S%26P_500_companies')\n soup = BeautifulSoup(resp.text, 'lxml')\n table = soup.find('table', {'class': 'wikitable sortable'})\n\n for row in table.findAll('tr')[1:]... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given the RNN outputs (presoftmax) at each time step and a target labeling, compute the negative of the CTC loss for one example, where the loss itself can be defined as the negative of the probability p(target | logits) as defined in equations 3 & 8 | def compute_ctc_loss(self, logits, target):
num_time_steps = logits.shape[0]
num_labels = logits.shape[1] - 1
num_labels_with_blank = num_labels + 1
# sanity check to ensure targets are all right
assert (target < num_labels).all()
######################
### YOUR CODE HERE ###
##############... | [
"def ctc_loss(inputs, padding_mask=-1, **kwargs):\n args = ArgHelper.parse(locals())\n inputs[0] = activation_ops.softmax(inputs[0], axis=2)\n op_lib = loss_ops_lib.Operator\n if context.executing_eagerly():\n raise NotImplementedError\n else:\n return op_lib.blend('CTCLoss', **args)",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given the normalized RNN outputs (postsoftmax) at each time step and a target labeling, compute the forward variables alpha_t(s) as defined in equation 5 in the paper | def compute_forward_variables(self, normalized_logits, target):
target_length = target.shape[0]
num_time_steps = normalized_logits.shape[0]
######################
### YOUR CODE HERE ###
######################
blank_label = normalized_logits.shape[1] - 1
l = add_blanks(target, blank_label)
... | [
"def _calculate_alpha(self, feats):\n \n init_alphas = torch.Tensor(1, self.tagset_size).fill_(-10000.)\n init_alphas[0][self.tag_to_ix[START_TAG]] = 0.\n\n forward_var = autograd.Variable(init_alphas)\n\n for feat in feats:\n alphas_t = [] # The forward variables at t... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given the normalized RNN outputs (postsoftmax) at each time step and a target labeling, compute the backward variables beta_t(s) as defined in equation 9 in the paper | def compute_backward_variables(self, normalized_logits, target):
target_length = target.shape[0]
num_time_steps = normalized_logits.shape[0]
######################
### YOUR CODE HERE ###
######################
blank_label = normalized_logits.shape[1] - 1
l = add_blanks(target, blank_label)
... | [
"def backwardVariableGeneration(self):\n self.beta = zeros((self.noOfEmmittingStates+2, self.T + 1))\n\n # initialisation\n for j in range(self.noOfEmmittingStates+1):\n self.beta[j,-1] = self.transitionMatrix[j,-1]\n self.beta[-1,-1] = 1.0\n\n # main recursion\n for t in range(self.T, 1, -1)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Given the RNN outputs (presoftmax) at each time step and a target labeling, compute the gradients of the CTC loss w.r.t. the unnormalized logits | def compute_gradients(self, logits, target):
target_length = target.shape[0]
num_time_steps = logits.shape[0]
######################
### YOUR CODE HERE ###
######################
# expand labels by inserting a blank between each pair
normalized_logits = softmax(logits)
blank_label = normali... | [
"def compute_ctc_loss(self, logits, target):\n\n num_time_steps = logits.shape[0]\n num_labels = logits.shape[1] - 1\n num_labels_with_blank = num_labels + 1\n\n # sanity check to ensure targets are all right\n assert (target < num_labels).all()\n\n\t\t######################\n\t\t### YOUR CODE HERE #... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Deletes text object file, database records and any keywords in the graph. | def TextDelete(texttitle):
path = app.config['UPLOAD_FOLDER'] + \
'/objects/' + texttitle + '.txt'
with Database() as database:
database.deleteText(texttitle, session['id'])
# Loads in the file to be deleted and the keyword graph
with open(path, "rb") as objectfile:
current_fil... | [
"def clear_db():\n humans = Human4j.nodes.all()\n for h in humans:\n h.delete()\n binomes = Binome4j.nodes.all()\n for b in binomes:\n b.delete()\n projects = Project4j.nodes.all()\n for p in projects:\n p.delete()\n sherpas = Sherpa4j.nodes.all()\n for sh in sherpas:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Performs dijsktras algorithm from a certain node | def dijsktra(graph, initial):
# Sets initial node score to 10
visited = {initial: 10}
nodes = set(graph.nodes)
max_weight = graph.distances[max(graph.distances, key=graph.distances.get)]
min_weight = graph.distances[min(graph.distances, key=graph.distances.get)]
# Defines the number of nodes t... | [
"def headpass2( igen, node, result ):",
"def headpass1( igen, node ):",
"def __dikjstra(self, start_node):\n visited = []\n unvisited = [x for x in self.__node]\n shortest_dist_from_start_node = 0\n current_node = start_node\n\n current_node.setShortestDist(shortest_dist_from_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Upload path for raw text, creates a text file with the text in Creates analyser object | def raw_text_upload():
try:
global current_file
if request.method == "POST":
raw_text = request.form['raw_text']
# Checks text is not empty
raw_text = raw_text.strip('<>')
if raw_text != '':
if app.config['UPLOAD_FOLDER'] == UPLOAD_FOLD... | [
"def upload_gazette_raw_text(\n gazette: Dict, storage\n):\n file_raw_txt = Path(gazette['file_path']).with_suffix(\".txt\").as_posix()\n storage.upload_content(file_raw_txt, gazette[\"source_text\"])\n logging.debug(f\"file_raw_txt uploaded {file_raw_txt}\")\n file_endpoint = get_file_endpoint()\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Shares the text with the user, by creating link in databse | def share_text(texttitle, username):
message = session['username'] + \
" shared the text " + texttitle + " with you."
with Database() as database:
database.share_text(texttitle, username, session["username"])
database.sendNotif(username, message)
flash("Text Shared")
return redir... | [
"def share_link(cls, user, link):",
"def link_text(self, link_text):\n self._link_text = link_text",
"def insert_link(self, text, href):\n self.insert_text('\\n<a href=\"%s\">%s</a>' % (href, text))",
"def create_link(self):\n self.filename = App.get_running_app().root.ids.camera_screen.c... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Displays the text on upload and allows the analysis to be selected | def textdisplay(textTitle, analysis):
try:
global current_file
with Database() as database:
text_owner = database.getTextOwner(textTitle, session['username'])
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER + text_owner
path = app.config['UPLOAD_FOLDER'] + '/objects/' + textT... | [
"def raw_text_upload():\n try:\n global current_file\n if request.method == \"POST\":\n raw_text = request.form['raw_text']\n # Checks text is not empty\n raw_text = raw_text.strip('<>')\n if raw_text != '':\n if app.config['UPLOAD_FOLDER']... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Saves the text object in a text file and saves it in db | def save_text():
try:
global current_file
if request.method == "POST":
current_file.title = request.form['title'].replace(' ', '')
with Database() as database:
category = database.getCategory(request.form['Category'])
current_file.category = ca... | [
"def save_text(self):\n if self.tab_control.index(\"current\") == 0:\n text = self.textbox.get(\"1.0\", tk.END)\n if text is not None:\n files = [('Text Document', '*.txt')]\n text_file = asksaveasfile(title=\"Save your text as .txt\", filetypes=files,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Deletes the users account, their files and texts from the database | def deleteaccount():
try:
if app.config['UPLOAD_FOLDER'] == UPLOAD_FOLDER:
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER + \
session['username']
with Database() as db:
texts = db.getOwnedTexts(session['id'])
for text in texts:
TextDel... | [
"def delete_user():",
"def db_delete_user_data(self):\n util.log(\"Clearing all user data\", util.LogLevel.Info)\n self.db.db_clear_data_user()\n util.log(\"Done\", util.LogLevel.Info)",
"def delete_user(self) -> None:\n table_dictionary = {\n 'Apple': {\n '... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
204 responses must not return some entity headers | def get204(self):
bad = ('content-length', 'content-type')
for h in bad:
bottle.response.set_header(h, 'foo')
bottle.status = 204
for h, v in bottle.response.headerlist:
self.assertFalse(h.lower() in bad, "Header %s not deleted" % h) | [
"def _no_content_response():\n response = make_response()\n response.status_code = 204\n return response",
"def create_204_response() -> bytes:\n date = datetime.datetime.now(datetime.timezone.utc).strftime(\"%a, %d %b %Y %H:%M:%S GMT\")\n\n header = \"HTTP/1.1 204 No Content\" ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
304 responses must not return entity headers | def get304(self):
bad = ('allow', 'content-encoding', 'content-language',
'content-length', 'content-md5', 'content-range',
'content-type', 'last-modified') # + c-location, expires?
for h in bad:
bottle.response.set_header(h, 'foo')
bottle.status = 304
... | [
"def create_304_response() -> bytes:\n content_data = HttpServer.get_content_data(\"/not_modified.html\")\n date = datetime.datetime.now(datetime.timezone.utc).strftime(\"%a, %d %b %Y %H:%M:%S GMT\")\n\n header = \"HTTP/1.1 304 Not Modified\" + \"\\r\\nDate: \" + date + \"\\r\\n\" + content_dat... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns an amended copy of the proxies dictionary used by `requests`, it will disable the proxy if the uri provided is to be reached directly. | def config_proxy_skip(proxies, uri, skip_proxy=False):
parsed_uri = urlparse(uri)
# disable proxy if necessary
if skip_proxy:
if 'http' in proxies:
proxies.pop('http')
if 'https' in proxies:
proxies.pop('https')
elif proxies.get('no'):
urls = []
i... | [
"def get_proxies(self):\n proxies = {\"http\": None, \"https\": None}\n if self.proxy:\n # TODO need test to enter here\n proxies = {\n \"http\": f\"http://{self.proxy}\",\n \"https\": f\"https://{self.proxy}\",\n }\n return proxies... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a new Thoth release instance | def make_release(self, **kwargs) -> ThothRelease:
snapshot_date = make_snapshot_date(**kwargs)
release = ThothRelease(dag_id=self.dag_id, run_id=kwargs["run_id"], snapshot_date=snapshot_date)
return release | [
"def create(self, *args, **kwargs):\n config = Config.objects.create(owner=self.owner, app=self)\n Release.objects.create(version=1, owner=self.owner, app=self, config=config, build=None)",
"def create_release(config, args):\n yield config.repo.create_release(args.tag_name, name=args.name,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Task to download the ONIX release from Thoth. | def download(self, release: ThothRelease, **kwargs) -> None:
thoth_download_onix(
publisher_id=self.publisher_id,
format_spec=self.format_specification,
download_path=release.download_path,
) | [
"def _download(self):\n self._system.download(\"http://geant4.web.cern.ch/geant4/support/source/\" + self._tar_name)",
"def thoth_download_onix(\n publisher_id: str,\n download_path: str,\n format_spec: str,\n host_name: str = DEFAULT_HOST_NAME,\n num_retries: int = 3,\n) -> None:\n url =... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Hits the Thoth API and requests the ONIX feed for a particular publisher. Creates a file called onix.xml at the specified location | def thoth_download_onix(
publisher_id: str,
download_path: str,
format_spec: str,
host_name: str = DEFAULT_HOST_NAME,
num_retries: int = 3,
) -> None:
url = THOTH_URL.format(host_name=host_name, format_specification=format_spec, publisher_id=publisher_id)
logging.info(f"Downloading ONIX XML ... | [
"def get_xml(query_key, web_env, count, output_file, offset=0):\n with open(output_file, \"ab\") as text_file:\n for retstart in range(0, count, MAX_POST_LIMIT):\n print(\"Downloading from ID {:,}...\".format(retstart + offset))\n time.sleep(SLEEP_TIME)\n payload = {\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This function will produce a batch of features and labels for each epoch step to reduce the memory usage. | def generator(features, labels, batch_size):
# Create empty arrays to contain batch of features and labels#
batch_features = np.zeros((batch_size, 160, 320, 3))
batch_labels = np.zeros((batch_size, 1))
while True:
for i in range(batch_size):
# choose random index in features
... | [
"def batch_features_labels(features, labels, batch_size):\n for start in range(0, len(features), batch_size):\n end = min(start + batch_size, len(features))\n #print(labels[start:end])\n yield features[start:end], labels[start:end]",
"def batch_features_labels(features, labels, batch_size)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Validate and update field value against validator. Raise NoValidatorError if no validator was set. | def validate(self):
if self.validator is None:
raise NoValidatorError('Field %s has no validator assigned.' %
self.id)
self.value = self.validator(self.value) | [
"def _update_related_validator(self):\n\n validator = Validator.objects.filter(ip_address=self.ip_address)\n field_names = common_field_names(self, Validator)\n data = {f: getattr(self, f) for f in field_names}\n\n if validator:\n validator.update(**data)\n else:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Shortcut for field.renderer.render(). Raise NoRendererError if no renderer is set. | def render(self):
if not self.renderer:
raise NoRendererError('Field %s has no renderer assigned.' %
self.id)
return self.renderer.render(self) | [
"def custom_field_rendering(context, field, *args, **kwargs):\n if CUSTOM_FIELD_RENDERER:\n mod, cls = CUSTOM_FIELD_RENDERER.rsplit(\".\", 1)\n field_renderer = getattr(import_module(mod), cls)\n if field_renderer:\n return field_renderer(field, **kwargs).render()\n return fiel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Transform each geometry to a different coordinate reference system. The ``crs`` attribute on the current GeoSeries must be set. | def to_crs(self, crs):
if crs is None:
raise ValueError("Can not transform with invalid crs")
if self.crs is None:
raise ValueError("Can not transform geometries without crs. Set crs for this GeoSeries first.")
if self.crs == crs:
return self
return _u... | [
"def SetGeoTransform(self, *args):\n for dataset in self._sub_datasets:\n dataset.SetGeoTransform(*args)",
"def _change_crs(self, gdf, crs):\n gdf.to_crs(\n {\n 'init': \"epsg:{}\".format(crs)\n }, \n inplace=True... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a geometry that represents the union of all geometries in the GeoSeries. | def unary_union(self):
return GeoSeries(arctern.ST_Union_Aggr(self)) | [
"def mergeGeometries(self):\n self.geometry = reduce(lambda p1,p2 : p1.union(p2) ,map(lambda tax : tax.biomeGeometry,self.taxonomies))\n return self.geometry",
"def union(self, other):\n return self._geomgen(capi.geom_union, other)",
"def unary_union(self) -> ir.GeoSpatialScalar:\n r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the Hausdorff distance between each geometry and other. This is a measure of how similar or dissimilar 2 geometries are. | def hausdorff_distance(self, other):
return _binary_op(arctern.ST_HausdorffDistance, self, other) | [
"def Hausdorff_distance(l1, l2):\n d1max = 0\n d2max = 0\n for x in l1:\n t1 = min([abs(x - y) for y in l2])\n if t1 > d1max:\n d1max = t1\n for x in l2:\n t2 = min([abs(x - y) for y in l1])\n if t2 > d2max:\n d2max = t2\n return max(d1max, d2max)",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Transform each arctern GeoSeries to GeoPandas GeoSeries. | def to_geopandas(self):
import geopandas
import shapely
return geopandas.GeoSeries(self.apply(lambda x: shapely.wkb.loads(x) if x is not None else None), crs=self.crs) | [
"def conversion_function(self):\n conversion = gpd.GeoDataFrame(gpd.GeoSeries(self)) # convert the geoseries into a geodataframe\n # rename the geometry column from '0' to 'geometry'\n conversion = conversion.rename(columns={0: 'geometry'}).set_geometry('geometry')\n return conversion",
"def to_geose... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Construct polygon(rectangle) geometries from arr_min_x, arr_min_y, arr_max_x, arr_max_y and special coordinate system. The edges of polygon are parallel to coordinate axis. | def polygon_from_envelope(cls, min_x, min_y, max_x, max_y, crs=None):
crs = _validate_crs(crs)
return cls(arctern.ST_PolygonFromEnvelope(min_x, min_y, max_x, max_y), crs=crs) | [
"def create_from_bounds( min, max ):\n # stack our bounds together and add them as points\n bounds = numpy.vstack( min, max )\n return create_from_points( bounds )",
"def generatePolygons():",
"def _to_polygon(polys):\n def to_polygon(x):\n assert len(x) in [4, 8]\n if len(x) == 4:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Construct geometry from the GeoJSON representation string. | def geom_from_geojson(cls, json, crs=None):
crs = _validate_crs(crs)
return cls(arctern.ST_GeomFromGeoJSON(json), crs=crs) | [
"def geometry(self, geometry):\n self.geom = func.ST_GeomFromGeoJSON(geometry)",
"def _get_geometry(self, val):\n g = OGRGeometry(val)\n return json.loads(g.json)",
"def json2polygon(geojson_str):\n geojson_object = geojson.loads(geojson_str)\n return geometry.shape(geojson_object)",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Função para converter temperatura de celsius para kelvin | def celsius_para_kelvin(temperatura_celsius):
temperatura_kelvin = temperatura_celsius + 273.15
return temperatura_kelvin | [
"def kelvin_to_celsius(temp_kelvin):\r\n return temp_kelvin - 275.15",
"def convertCelsiustoKelvin(celsius):\n return celsius + 273.15",
"def kelvin_to_celsius(temp):\n return temp - 273.15",
"def kelvin2celsius(T):\n return T - 273.15",
"def c_to_k(c_temp):\n k_temp = c_temp + 273.15\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Decorator to load common data used by all views | def base_data_manager(wrapped):
@check_session
def wrapper(request, *arg, **kwargs):
@cache_region.cache_on_arguments()
def get_data_manager(collection, journal, document, range_start, range_end):
code = document or journal or collection
data = {}
xylose_do... | [
"def configure_views(self):",
"def a_shared_view(request):\n return view(a_shared_view)",
"def request_data_decorator(fun):\n def wrap(request, *args, **kwargs):\n if kwargs.get('data', None) is None: # data parameter must exist in view function\n if request.method == 'GET':... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Constructor. Unless otherwise specified it has a perfect quantum efficiency, samples at a rate of once per second and has a 0.1s integration time | def __init__(self, quantum_efficiency=1.0,
sample_rate_times_per_second=1.0,
integration_time_seconds=0.1):
self.quantum_efficiency = quantum_efficiency
self.sample_rate_times_per_second = sample_rate_times_per_second
self.integration_time_seconds = integration_... | [
"def __init__(self, sample_rate):",
"def __init__(self, time_constant: float, sampling_time: float):\n self.alpha = sampling_time / (time_constant + sampling_time)\n self.state = None",
"def __init__(self, timer=120, rate=1, percent=0):\n self.timer = timer\n self.rate = rate\n self.p... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates new task window | def new_task(self, widget):
my_task_window = taskwindow.TaskWindow(self) | [
"def create_task(event):\n manager = event.workbench.get_plugin('exopy.tasks')\n dialog = BuilderView(manager=manager,\n parent=event.parameters.get('parent_ui'),\n future_parent=event.parameters.get('future_parent'))\n result = dialog.exec_()\n if result:... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Shows a window with all the tasks and alarms | def see_tasks(self, widget):
my_task_list = tasklistwindow.TaskListWindow(self.task_list) | [
"def __show_all_tasks():\n os.system('clear')\n os.system('cls')\n tasks = [task for task in Application.diary.get_notes() if task.is_event is True]\n print('Tasks in {} are:\\n'.format(Application.diary.name))\n for task in tasks:\n print(task.id)\n print(ta... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
aic(timeSeries, ssc=0) > data, max_weight, max_weight_params | def aic(timeSeries, ssc=0):
if np.min(timeSeries) <= 0:
timeSeries = timeSeries + -np.min(timeSeries) + .01
# create histogram to determine plot values
# note that the original uses hist centers, this uses edges. It may matter
counts, plotvals_edges = np.histogram(timeSeries, 50)
plot... | [
"def alpha74(df):\n temp1 = u.rank(u.corr(df.close, u.ts_sum(u.adv(df, 30), 37), 15))\n temp2 = u.rank(u.corr(u.rank(((df.high * 0.0261661) + (df.vwap * (1 - 0.0261661)))), u.rank(df.volume), 11)) \n return ((temp1 < temp2) * -1)",
"def alpha88(df):\n temp1 = u.rank(u.decay_linear(((u.rank(df.open) + ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Show line of asterisks to demarcate bounds of heap | def demarcate_heap(hgt=self.level, cell_wid=minimum_cell):
# Number of nodes on bottom is 2^hgt
max_nodes = int(np.power(2, hgt))
print (''.center(cell_wid * max_nodes, '*')) | [
"def min_heap(self): \n \n for pos in range(self.size//2, 0, -1): \n self.min_heapify(pos)",
"def __repr__(self):\n return \"heap:[\" + ','.join(map(str, self.ar[:self.n])) + \"]\"",
"def _heapify(self):\n #1. 找到最后一个非叶子节点\n last_node = self.parent(len(self.l) -1)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Swap values at index_0 and index_1 | def swap(self, index_0, index_1):
value_0 = self.get_value_at(index_0)
value_1 = self.get_value_at(index_1)
self.set_value_at(index_0, value_1)
self.set_value_at(index_1, value_0) | [
"def swap_index_values(self, index_1, index_2):\n self.data[index_1], self.data[index_2] = self.data[index_2], self.data[index_1]",
"def __swap(index_i, index_j, arr):\n arr[index_i], arr[index_j] = arr[index_j].copy(), arr[index_i].copy()",
"def swap(numbers, index1, index2):\n temp = numbers[inde... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
use dictionary to store the difference (target nums[i]). | def twoSum(self, nums: List[int], target: int) -> List[int]:
diffRec = {}
for i, v in enumerate(nums):
if v in diffRec:
return [diffRec[v], i]
else:
diffRec[target - v] = i
return -1 | [
"def twoSum(nums,target):\n #Initialize count and hash table\n count=0\n hash_table={}\n \n #Build hashtable\n for i in range(len(nums)): \n hash_table[nums[i]] = i\n \n #Iterate through targets and nums to see if corresponding numbers exist in hashtable\n for i in range(len(tar... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
checks if user can afford item and deducts item cost from self.resources and adds the item (or the purchases effects) to the user. returns true if purchased, returns false if not. Default usage is to use an item name from purchase.py. If a Balance object "balance" is given INSTEAD of "item", then it is used directly. | def purchase(self, item=None, balance=None):
if item!= None:
cost = purchases.getCost(item)
if self.affords(cost):
self.payFor(cost)
# TODO: actually do whatever was purchased
# self.applyItem(item)
return True
e... | [
"def userCanAffordItemObj(self, user : bbUser.bbUser, item : bbItem.bbItem) -> bool:\n return user.credits >= item.getValue()",
"def userBuyWeaponObj(self, user : bbUser.bbUser, requestedWeapon : bbWeapon.bbWeapon):\n if self.userCanAffordItemObj(user, requestedWeapon):\n self.weaponsStoc... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the date reformated into python datetime format. | def get_python_date(self):
return dateutil.parser.parse(self.iso_date) | [
"def modis_to_from_pydatetime(date):\n \n if isinstance(date, (str, unicode)): \n return dt.datetime.strptime(date[1:], '%Y%j').date()\n return dt.datetime.strftime(date, 'A%Y%j')",
"def to_pydate(self):\n return date(*self.tuple())",
"def _to_date(self, x):\n if isinstance(x, date... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Renders a page for a particular compound. | def CompoundPage(request):
form = compound_form.CompoundForm(request.GET)
if not form.is_valid():
logging.error(form.errors)
raise Http404
# Compute the delta G estimate.
kegg_id = form.cleaned_compoundId
compound = models.Compound.objects.get(kegg_id=kegg_id)
compound.Stash... | [
"def main_page():\n pages=get_accounts()\n return render_template('disp.html',pages=pages)",
"def main_page():\n return render_template(\"main_page.html\")",
"def generatePage(self, entry, path, doc, config, pygments_style):\n\n common_kwargs = {'doc': doc,\n 'config': co... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Run SugarPy on a given .mzML file based on identified peptides from an evidences.csv Translated Ursgal parameters are passed to the SugarPy main function. | def _execute(self):
self.time_point(tag="execution")
main = self.import_engine_as_python_function()
output_file = os.path.join(
self.params["output_dir_path"], self.params["output_file"]
)
input_file = os.path.join(
self.params["input_dir_path"], self.... | [
"def main(mzML_file=None, profile=None, database=None):\n uc = ursgal.UController(\n profile=profile,\n params={\n \"database\": database,\n \"modifications\": [\n \"M,opt,any,Oxidation\", # Met oxidation\n \"C,fix,any,Carbamidomethyl\", # Carba... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |