query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Calculate exact roots of a solvable irreducible quintic with rational coefficients. Return an empty list if the quintic is reducible or not solvable. | def roots_quintic(f):
result = []
coeff_5, coeff_4, p_, q_, r_, s_ = f.all_coeffs()
if not all(coeff.is_Rational for coeff in (coeff_5, coeff_4, p_, q_, r_, s_)):
return result
if coeff_5 != 1:
f = Poly(f / coeff_5)
_, coeff_4, p_, q_, r_, s_ = f.all_coeffs()
# Cancel coe... | [
"def _realroots_quadratic(a1, a0):\n D = a1*a1 - 4*a0\n if D < 0:\n return []\n SD = math.sqrt(D)\n return [0.5 * (-a1 + SD), 0.5 * (-a1 - SD)]",
"def getRoots(self):\n # This part is for exercise 11\n # return []\n \n # This part is for exercise 12\n if self.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compute coefficient basis for a polynomial over integers. Returns the integer ``div`` such that substituting ``x = divy`` ``p(x) = mq(y)`` where the coefficients of ``q`` are smaller than those of ``p``. For example ``x5 + 512x + 1024 = 0`` with ``div = 4`` becomes ``y5 + 2y + 1 = 0`` Returns the integer ``div`` or ``N... | def _integer_basis(poly):
monoms, coeffs = list(zip(*poly.terms()))
monoms, = list(zip(*monoms))
coeffs = list(map(abs, coeffs))
if coeffs[0] < coeffs[-1]:
coeffs = list(reversed(coeffs))
n = monoms[0]
monoms = [n - i for i in reversed(monoms)]
else:
return None
... | [
"def divisor_num(x):\n factor_pow = map(lambda y: y + 1, factorint(x).values())\n div_num = reduce(mul, factor_pow)\n return div_num",
"def integerpolynomialfactorization(f):\n cont = f.content()\n prim = f.primitive_part()\n F = [prim]\n G = prim\n c = 0\n one = G.getRing().one\n wh... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Try to get rid of symbolic coefficients from ``poly``. | def preprocess_roots(poly):
coeff = S.One
poly_func = poly.func
try:
_, poly = poly.clear_denoms(convert=True)
except DomainError:
return coeff, poly
poly = poly.primitive()[1]
poly = poly.retract()
# TODO: This is fragile. Figure out how to make this independent of constr... | [
"def linear_simplify_poly(poly):\n if len(poly) < 4:\n return poly\n\n q = Queue()\n for v in poly:\n q.put(v)\n\n new_poly = []\n a = q.get()\n b = q.get()\n while True:\n if q.empty():\n new_poly += [a,b]\n break\n c = q.get()\n e1 = (b... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Computes symbolic roots of a univariate polynomial. Given a univariate polynomial f with symbolic coefficients (or a list of the polynomial's coefficients), returns a dictionary with its roots and their multiplicities. Only roots expressible via radicals will be returned. To get a complete set of roots use RootOf class... | def roots(f, *gens,
auto=True,
cubics=True,
trig=False,
quartics=True,
quintics=False,
multiple=False,
filter=None,
predicate=None,
strict=False,
**flags):
from sympy.polys.polytools import to_rational_coeffs
flags = dict(flags)
... | [
"def test_roots_slow():\n a, b, c, d, x = symbols(\"a,b,c,d,x\")\n\n f1 = x ** 2 * c + (a / b) + x * c * d - a\n f2 = x ** 2 * (a + b * (c - d) * a) + x * a * b * c / (b * d - d) + (a * d - c / d)\n\n assert list(roots(f1, x).values()) == [1, 1]\n assert list(roots(f2, x).values()) == [1, 1]\n\n (... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns all factors of a univariate polynomial. Examples ======== >>> from sympy.abc import x, y >>> from sympy.polys.polyroots import root_factors >>> root_factors(x2 y, x) [x sqrt(y), x + sqrt(y)] | def root_factors(f, *gens, filter=None, **args):
args = dict(args)
F = Poly(f, *gens, **args)
if not F.is_Poly:
return [f]
if F.is_multivariate:
raise ValueError('multivariate polynomials are not supported')
x = F.gens[0]
zeros = roots(F, filter=filter)
if not zeros:
... | [
"def factors(x: int) -> list:\n try:\n return _np.factors(x)\n except (NameError, TypeError, OverflowError):\n pass\n\n f = []\n x = int(x)\n if x == 0:\n return [0]\n sqrt = x ** .5\n for i in range(1, int(sqrt) + 1): # Go through half of the factors\n if x % i == ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Modify the land cover to create rocks in the large gradient pixels (large steepness) | def set_rocks_in_grad(self, elevation, landcover):
# Compute the steepness of each pixel
grad = gaussian_gradient_magnitude(elevation, 1.0)
grad /= self.mercator.Resolution(self.__zoom)
# Get the mask of rock (with a smooth transition)
mask = (grad >= ROCK_STEEPNESS).astype(np.fl... | [
"def preprocess_land_cover(\n src_files, dst_raster, dst_crs, dst_bounds, dst_res, geom=None, overwrite=False\n):\n if os.path.isfile(dst_raster) and not overwrite:\n log.info(\"Land cover data already preprocessed. Skipping.\")\n return\n log.info(\"Starting preprocessing of land cover data.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Make the object directory and file for the adding file. | def make_directory_and_object_file(file_sha1_hash, file_content, parent_dir):
try:
# Create a path for the new directory, which is the first 2 characters
# of the hash.
new_dir_path = join(parent_dir, ".lgit/objects", file_sha1_hash[:2])
# Create the directory
try:
... | [
"def makeLibrary(self):\n #------------------------------------------ Instance for the output file\n outputFile = open(\"%s/%s\" % (self.sceneryPath,self.libTxtFileName),\"w\")\n #------------------------------------------------------ write the header\n for line in self.header:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the aux_input_type1 of this UpdateVehicleRequest. | def aux_input_type1(self, aux_input_type1):
allowed_values = ["none", "emergencyLights", "emergencyAlarm", "stopPaddle", "powerTakeOff", "plow", "sweeper", "salter", "reefer", "door", "boom", "auxiliaryEngine", "generator", "eightWayLights"] # noqa: E501
if self.local_vars_configuration.client_side_val... | [
"def aux_input_type2(self, aux_input_type2):\n allowed_values = [\"none\", \"emergencyLights\", \"emergencyAlarm\", \"stopPaddle\", \"powerTakeOff\", \"plow\", \"sweeper\", \"salter\", \"reefer\", \"door\", \"boom\", \"auxiliaryEngine\", \"generator\", \"eightWayLights\"] # noqa: E501\n if self.local... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the aux_input_type10 of this UpdateVehicleRequest. | def aux_input_type10(self, aux_input_type10):
allowed_values = ["none", "emergencyLights", "emergencyAlarm", "stopPaddle", "powerTakeOff", "plow", "sweeper", "salter", "reefer", "door", "boom", "auxiliaryEngine", "generator", "eightWayLights"] # noqa: E501
if self.local_vars_configuration.client_side_v... | [
"def aux_input_type9(self, aux_input_type9):\n allowed_values = [\"none\", \"emergencyLights\", \"emergencyAlarm\", \"stopPaddle\", \"powerTakeOff\", \"plow\", \"sweeper\", \"salter\", \"reefer\", \"door\", \"boom\", \"auxiliaryEngine\", \"generator\", \"eightWayLights\"] # noqa: E501\n if self.local... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the aux_input_type2 of this UpdateVehicleRequest. | def aux_input_type2(self, aux_input_type2):
allowed_values = ["none", "emergencyLights", "emergencyAlarm", "stopPaddle", "powerTakeOff", "plow", "sweeper", "salter", "reefer", "door", "boom", "auxiliaryEngine", "generator", "eightWayLights"] # noqa: E501
if self.local_vars_configuration.client_side_val... | [
"def aux_input_type1(self, aux_input_type1):\n allowed_values = [\"none\", \"emergencyLights\", \"emergencyAlarm\", \"stopPaddle\", \"powerTakeOff\", \"plow\", \"sweeper\", \"salter\", \"reefer\", \"door\", \"boom\", \"auxiliaryEngine\", \"generator\", \"eightWayLights\"] # noqa: E501\n if self.local... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the aux_input_type3 of this UpdateVehicleRequest. | def aux_input_type3(self, aux_input_type3):
allowed_values = ["none", "emergencyLights", "emergencyAlarm", "stopPaddle", "powerTakeOff", "plow", "sweeper", "salter", "reefer", "door", "boom", "auxiliaryEngine", "generator", "eightWayLights"] # noqa: E501
if self.local_vars_configuration.client_side_val... | [
"def aux_input_type9(self, aux_input_type9):\n allowed_values = [\"none\", \"emergencyLights\", \"emergencyAlarm\", \"stopPaddle\", \"powerTakeOff\", \"plow\", \"sweeper\", \"salter\", \"reefer\", \"door\", \"boom\", \"auxiliaryEngine\", \"generator\", \"eightWayLights\"] # noqa: E501\n if self.local... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the aux_input_type4 of this UpdateVehicleRequest. | def aux_input_type4(self, aux_input_type4):
allowed_values = ["none", "emergencyLights", "emergencyAlarm", "stopPaddle", "powerTakeOff", "plow", "sweeper", "salter", "reefer", "door", "boom", "auxiliaryEngine", "generator", "eightWayLights"] # noqa: E501
if self.local_vars_configuration.client_side_val... | [
"def aux_input_type6(self, aux_input_type6):\n allowed_values = [\"none\", \"emergencyLights\", \"emergencyAlarm\", \"stopPaddle\", \"powerTakeOff\", \"plow\", \"sweeper\", \"salter\", \"reefer\", \"door\", \"boom\", \"auxiliaryEngine\", \"generator\", \"eightWayLights\"] # noqa: E501\n if self.local... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the aux_input_type5 of this UpdateVehicleRequest. | def aux_input_type5(self, aux_input_type5):
allowed_values = ["none", "emergencyLights", "emergencyAlarm", "stopPaddle", "powerTakeOff", "plow", "sweeper", "salter", "reefer", "door", "boom", "auxiliaryEngine", "generator", "eightWayLights"] # noqa: E501
if self.local_vars_configuration.client_side_val... | [
"def aux_input_type6(self, aux_input_type6):\n allowed_values = [\"none\", \"emergencyLights\", \"emergencyAlarm\", \"stopPaddle\", \"powerTakeOff\", \"plow\", \"sweeper\", \"salter\", \"reefer\", \"door\", \"boom\", \"auxiliaryEngine\", \"generator\", \"eightWayLights\"] # noqa: E501\n if self.local... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the aux_input_type6 of this UpdateVehicleRequest. | def aux_input_type6(self, aux_input_type6):
allowed_values = ["none", "emergencyLights", "emergencyAlarm", "stopPaddle", "powerTakeOff", "plow", "sweeper", "salter", "reefer", "door", "boom", "auxiliaryEngine", "generator", "eightWayLights"] # noqa: E501
if self.local_vars_configuration.client_side_val... | [
"def aux_input_type7(self, aux_input_type7):\n allowed_values = [\"none\", \"emergencyLights\", \"emergencyAlarm\", \"stopPaddle\", \"powerTakeOff\", \"plow\", \"sweeper\", \"salter\", \"reefer\", \"door\", \"boom\", \"auxiliaryEngine\", \"generator\", \"eightWayLights\"] # noqa: E501\n if self.local... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the aux_input_type7 of this UpdateVehicleRequest. | def aux_input_type7(self, aux_input_type7):
allowed_values = ["none", "emergencyLights", "emergencyAlarm", "stopPaddle", "powerTakeOff", "plow", "sweeper", "salter", "reefer", "door", "boom", "auxiliaryEngine", "generator", "eightWayLights"] # noqa: E501
if self.local_vars_configuration.client_side_val... | [
"def aux_input_type6(self, aux_input_type6):\n allowed_values = [\"none\", \"emergencyLights\", \"emergencyAlarm\", \"stopPaddle\", \"powerTakeOff\", \"plow\", \"sweeper\", \"salter\", \"reefer\", \"door\", \"boom\", \"auxiliaryEngine\", \"generator\", \"eightWayLights\"] # noqa: E501\n if self.local... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the aux_input_type8 of this UpdateVehicleRequest. | def aux_input_type8(self, aux_input_type8):
allowed_values = ["none", "emergencyLights", "emergencyAlarm", "stopPaddle", "powerTakeOff", "plow", "sweeper", "salter", "reefer", "door", "boom", "auxiliaryEngine", "generator", "eightWayLights"] # noqa: E501
if self.local_vars_configuration.client_side_val... | [
"def aux_input_type9(self, aux_input_type9):\n allowed_values = [\"none\", \"emergencyLights\", \"emergencyAlarm\", \"stopPaddle\", \"powerTakeOff\", \"plow\", \"sweeper\", \"salter\", \"reefer\", \"door\", \"boom\", \"auxiliaryEngine\", \"generator\", \"eightWayLights\"] # noqa: E501\n if self.local... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the aux_input_type9 of this UpdateVehicleRequest. | def aux_input_type9(self, aux_input_type9):
allowed_values = ["none", "emergencyLights", "emergencyAlarm", "stopPaddle", "powerTakeOff", "plow", "sweeper", "salter", "reefer", "door", "boom", "auxiliaryEngine", "generator", "eightWayLights"] # noqa: E501
if self.local_vars_configuration.client_side_val... | [
"def aux_input_type10(self, aux_input_type10):\n allowed_values = [\"none\", \"emergencyLights\", \"emergencyAlarm\", \"stopPaddle\", \"powerTakeOff\", \"plow\", \"sweeper\", \"salter\", \"reefer\", \"door\", \"boom\", \"auxiliaryEngine\", \"generator\", \"eightWayLights\"] # noqa: E501\n if self.loc... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the engine_hours of this UpdateVehicleRequest. | def engine_hours(self, engine_hours):
self._engine_hours = engine_hours | [
"def actual_work_hours(self, actual_work_hours):\n self._actual_work_hours = actual_work_hours",
"def hours(self, new_hours):\n\n if (type(new_hours) != int and type(new_hours) != float) or new_hours < 0:\n raise ValueError(\n \"The number of working hours should be float o... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the external_ids of this UpdateVehicleRequest. | def external_ids(self, external_ids):
self._external_ids = external_ids | [
"def outer_vlan_ids(self, outer_vlan_ids: List[str]):\n\n self._outer_vlan_ids = outer_vlan_ids",
"def external_domains(self, external_domains):\n\n self._external_domains = external_domains",
"def external_ids(self, **kwargs):\n path = self._get_movie_id_path('external_ids')\n resp ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the gateway_serial of this UpdateVehicleRequest. | def gateway_serial(self, gateway_serial):
self._gateway_serial = gateway_serial | [
"def gateway_port(self, gateway_port):\n\n self._gateway_port = gateway_port",
"def gateway(self, gateway):\n\n self._gateway = gateway",
"def gateway_id(self, gateway_id):\n\n self._gateway_id = gateway_id",
"def gateway_id(self, gateway_id):\n self._gateway_id = gateway_id",
"d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the harsh_acceleration_setting_type of this UpdateVehicleRequest. | def harsh_acceleration_setting_type(self, harsh_acceleration_setting_type):
allowed_values = ["passengerCar", "lightTruck", "heavyDuty", "off", "automatic"] # noqa: E501
if self.local_vars_configuration.client_side_validation and harsh_acceleration_setting_type not in allowed_values: # noqa: E501
... | [
"def set_fleet_type(self, fleet_type):\n self.fleet_type = fleet_type",
"def setting_type(self, setting_type):\n\n self._setting_type = setting_type",
"def set_adjustment_type(self, adjustment_type):\n self.single_selection_from_kendo_dropdown(self.adjustment_type_dropdown_locator, adjustme... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the license_plate of this UpdateVehicleRequest. | def license_plate(self, license_plate):
if (self.local_vars_configuration.client_side_validation and
license_plate is not None and len(license_plate) > 12):
raise ValueError("Invalid value for `license_plate`, length must be less than or equal to `12`") # noqa: E501
self._l... | [
"def set_license_plate(self, text: str) -> None:\n return self._ge_api.set_license_plate(text)",
"def license_serial(self, license_serial):\n\n self._license_serial = license_serial",
"def license(self, license):\n self._license = license",
"def license(self, license):\n\n self._li... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the odometer_meters of this UpdateVehicleRequest. | def odometer_meters(self, odometer_meters):
self._odometer_meters = odometer_meters | [
"def obd_odometer_meters(self, obd_odometer_meters):\n\n self._obd_odometer_meters = obd_odometer_meters",
"def gps_odometer_meters(self, gps_odometer_meters):\n\n self._gps_odometer_meters = gps_odometer_meters",
"def drive_distance_meters(self, drive_distance_meters):\n\n self._drive_dist... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the static_assigned_driver_id of this UpdateVehicleRequest. | def static_assigned_driver_id(self, static_assigned_driver_id):
self._static_assigned_driver_id = static_assigned_driver_id | [
"def driver_id(self, driver_id):\n\n self._driver_id = driver_id",
"def assign_driver(self, driver) -> None:\n self.assigned_driver = driver\n self.possible_drivers.clear()",
"def driver_id(self, driver_id: int):\n if driver_id is None:\n raise ValueError(\"Invalid value f... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the tag_ids of this UpdateVehicleRequest. | def tag_ids(self, tag_ids):
self._tag_ids = tag_ids | [
"def update_tags(self, tags: List[str]) -> None:\n self.tags = tags",
"def setTags ( self, tags ):\n self._tags = tags",
"def tags(self, tags):\n\n self._tags = tags",
"def tags(self, tags):\n \n self._tags = tags",
"def tag_names(self, tag_names):\n\n self._tag_names =... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the vin of this UpdateVehicleRequest. | def vin(self, vin):
if (self.local_vars_configuration.client_side_validation and
vin is not None and len(vin) > 17):
raise ValueError("Invalid value for `vin`, length must be less than or equal to `17`") # noqa: E501
if (self.local_vars_configuration.client_side_validation a... | [
"def set_vin(self, value):\n return self.sendCMD(\"ATSET VIN={}\".format(value))",
"def vm_volume_num_in(self, vm_volume_num_in):\n\n self._vm_volume_num_in = vm_volume_num_in",
"def vehicle(self, vehicle):\n\n self._vehicle = vehicle",
"def vm_volume_num(self, vm_volume_num):\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return True if command return type is string | def is_string(self):
answer = self._call('is_string')
return answer.yes | [
"def _is_string(arg):\n return isinstance(arg, types.StringTypes)",
"def is_string(type_arg):\n tpye_arg = type_arg.strip()\n return type_arg == \"char *\" or type_arg == \"const char *\"",
"def is_of_type(cmd):\r\n raise NotImplementedError()",
"def typeIsString(obj):\n return type(obj... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return True if command return type is long | def is_long(self):
answer = self._call('is_long')
return answer.yes | [
"def isLong(self):\r\n return self._wrap(type(self.obj) is long)",
"def _validate_long(datum, **kwargs):\n return (\n isinstance(datum, (int, numbers.Integral))\n and LONG_MIN_VALUE <= datum <= LONG_MAX_VALUE\n and not isinstance(datum, bool)\n )",
"def convertToLong(boolean: b... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return True if command return type is double | def is_double(self):
answer = self._call('is_double')
return answer.yes | [
"def isDouble(self):\n return _yarp.Value_isDouble(self)",
"def expectDouble(self):\n return _yarp.ConnectionReader_expectDouble(self)",
"def is_double(self, size=None):\n return False",
"def has_double(self):\n has_double = False\n doubled = None\n for digit, count i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return True if command return type is datetime | def is_datetime(self):
answer = self._call('is_datetime')
return answer.yes | [
"def is_datetime(self) -> bool:\n return False",
"def has_datetime_type(obj: _std_typing.Any) -> bool:\n return obj.dtype == sc.DType.datetime64",
"def test_14_digit_datetime_detection(self):\n obj = awstats_reader.awstats_datetime('20091130165230')\n self.assertTrue(isinstance(obj, awst... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return True if command return type is bool | def is_bool(self):
answer = self._call('is_bool')
return answer.yes | [
"def __bool__(self):\n return self.bool",
"def __bool__(self):\n\t\t\n\t\treturn self.__getValueWithType(bool)",
"def __bool__(self):\n return True",
"def __bool__(self):\n return bool(self.get_value())",
"def expects_result(self, command):\n return isinstance(command, (self.pack... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return True if command return type is map | def is_map(self):
answer = self._call('is_map')
return answer.yes | [
"def _is_map_entry(field):\n return (\n field.type == descriptor.FieldDescriptor.TYPE_MESSAGE and field.message_type.has_options\n and field.message_type.GetOptions().map_entry\n )",
"def _msg_is_command(self, msg):\n return isinstance(msg, dict)",
"def is_mapping(self) -> bool:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return True if command return type is list | def is_list(self):
answer = self._call('is_list')
return answer.yes | [
"def is_list(self) -> bool:\n return self.type() == 'object_list' or self.type() == 'list'",
"def is_list(self) -> bool:\n return False",
"def isList(self):\r\n return self._wrap(type(self.obj) is list)",
"def _is_list(arg):\n return isinstance(arg, collections.Sequence) and not _is_string... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set command return value | def set_result(self, value):
value_rpc = utils.get_rpc_value(type(value), value)
self._call('set_result', value=value_rpc) | [
"def SetExitResult(self, result):\n callResult = self._Call(\"SetExitResult\", result)",
"def SetReturnResult(self, result):\n callResult = self._Call(\"SetReturnResult\", result)",
"def _set_returncode(self, code):\n if code >= self._return_code:\n self._return_code = code",
"... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set exception in command. Information about exception will be called for adapter's side. | def set_exception(self, reason):
self._call('set_exception', exception=reason) | [
"def set_exception(self, exception):\n raise NotImplementedError",
"def set_exception(self, exception):\r\n self._exception = exception\r\n self._set_done()",
"def set_exception(self, exception):\n self._loop.call_soon_threadsafe(self.future.set_exception, exception)",
"def send_ex... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reloads the datatype from Riak. | def reload(self, **params):
if not self.bucket:
raise ValueError('bucket property not assigned')
if not self.key:
raise ValueError('key property not assigned')
dtype, value, context = self.bucket._client._fetch_datatype(
self.bucket, self.key, **params)
... | [
"def reloadData(self):\n self.dto.readFromData()\n print(\"Record reloaded.\")",
"def reload(self):\n self.magic.reload()",
"def reload(self):\n self._dataset.reload()",
"def reload_surrogate():\n surrogate.reload()",
"def reload(self):\n self.module = importlib.reload(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Raises an exception if the context is not present | def _require_context(self):
if not self._context:
raise ContextRequired() | [
"def __call__(self, context, **args):\n args = self.validate(args)\n if self.needs_context:\n if isinstance(context, Exception):\n raise context\n args[CONTEXT_ARG_NAME] = context\n return self.call(**args)",
"def validate_context(self, context):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Scrubs sys.path and sys.modules to a raw state. | def _scrub_import_environment(sys_modules_whitelist: typing.List[str], logger: typing.Callable):
pex_root = pathlib.Path(Variables().PEX_ROOT)
# A generator that emits sys.path elements
def scrubbed_sys_path():
"""Yields a scrubbed version of sys.path."""
for p in sys.path[:]:
if not isinstance(p, ... | [
"def save_sys_module_state(self):\n self._orig_sys_module_state = {'stdin': sys.stdin,\n 'stdout': sys.stdout,\n 'stderr': sys.stderr,\n 'excepthook': sys.excepthook}\n self._orig_sys_modu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Yields a scrubbed version of sys.path. | def scrubbed_sys_path():
for p in sys.path[:]:
if not isinstance(p, str):
yield p
# Scrub any/all pex locations from sys.path.
pp = pathlib.Path(p)
if pex_root not in pp.parents:
yield p | [
"def scrub_from_sys_modules():\n for k, m in sys.modules.items():\n if k in sys_modules_whitelist:\n continue\n\n if hasattr(m, '__file__') and m.__file__ is not None:\n mp = pathlib.Path(m.__file__)\n if pex_root in mp.parents:\n yield k",
"def extend_path(directory):\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Yields keys of sys.modules as candidates for scrubbing/removal. | def scrub_from_sys_modules():
for k, m in sys.modules.items():
if k in sys_modules_whitelist:
continue
if hasattr(m, '__file__') and m.__file__ is not None:
mp = pathlib.Path(m.__file__)
if pex_root in mp.parents:
yield k | [
"def reset_sys_modules():\n # Save the set of keys before the test is called\n sys_modules = list(sys.modules.keys())\n\n yield\n\n # Remove entries for all the modules loaded during the test\n for key in list(sys.modules.keys()):\n if key not in sys_modules:\n print(f\"Deleting the... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Extracts exactly 1 binary from a dir and returns a Path. | def _extract_resulting_binary(self, build_dir: pathlib.PosixPath, extension: str) -> pathlib.PosixPath:
assert build_dir.is_dir(), f'build_dir {build_dir} was not a dir!'
# N.B. It's important we use pathlib.Path.rglob (recursive) here, since pants v2 prefixes dist dirs
# with their address namespace.
b... | [
"def _unpack_archive(self, file_bytes: bytes, path: PathStr) -> PathStr:\n path = Path(utils.extract_tarbytes(file_bytes, path))\n output = next(path.iterdir())\n return output",
"def dir_bin():\n return abspath('bin')",
"def unpack_no_full_paths(path, targetdir):\n return unpack(path... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates an Accordion widget and yields under care of its output capturer. | def _accordion_widget(self, title, height='300px', collapsed=True):
# Generate unique class for multiple invocations
unique_class = self._append_random_id('nb-console-output')
auto_scroll_script = '''
const config = { childList: true, subtree: true };
const callback = function(mutationsList, observe... | [
"def generate_accordion(summary, main):\n return \"\"\"\n <details>\n <summary>{}</summary>\n <main>{}</main>\n </details>\n \"\"\".format(summary, main)",
"def render_accordion(request, course, chapter, section, field_data_cache):\r\n # grab the table ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Bootstraps a pex with widget UI display. | def _bootstrap_pex(self, pex_path: pathlib.PosixPath):
title = f'[Bootstrap] {pex_path.name}'
with self._accordion_widget(title) as (expand, collapse, set_output_glyph):
try:
with environment_as(PEX_VERBOSE='2'):
# Scrub the environment.
_scrub_import_environment(self._ORIGINAT... | [
"def bootstrap():\n Bootstrap()",
"def __setup_widgets__(self):\n self.__setup_clock_widget__()\n self.__setup_sellings_widgets__()\n\n # window widget\n self.window = self.builder.get_object(\"window_pos\")\n self.window.connect(\"destroy\", gtk.main_quit)",
"def b... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Validates a given or stored path is a valid pants repo. | def _validate_pants_repo(self, pants_repo: pathlib.PosixPath) -> bool:
return (
pants_repo and
pants_repo.is_dir() and
pants_repo.joinpath('pants').is_file()
) | [
"def check_repo(arepo):\n if not check_dir(arepo):\n u.error(\"unable to access repo dir %s\" % arepo)\n if not check_dir(\"%s/.repo\" % arepo):\n u.error(\"repo client %s does not contain .repo dir\")",
"def check_repo_or_die(path=None):\r\n guess_repo(path)\r\n try:\r\n os.stat(repo('object... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Updates the important game information for each round of play. In this case, that means the puzzle is revealed and the jumper is cut if necessary. | def _do_updates(self):
is_right = self._puzzle.is_guess_right()
if is_right:
self._puzzle.reveal_puzzle()
else:
self._jumper.cut_line() | [
"def game_updated(self):\n # replace with your game updated logic",
"def new_game(self):\n self.game_over = False\n self.round = 0\n\n self.new_round()",
"def update_game(game, episode, buttons,run_status):\n\n game_round = game.round\n if game_round == 'newround':\n new... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Outputs the important game information for each round of play. In this case, that means the hider provides a hint. | def _do_outputs(self):
self._puzzle.display_revealed_puzzle()
hint = self._puzzle.get_hint()
self._console.write(hint)
print("")
self._jumper.draw_jumper()
print("")
# These ifs end the game
if self._puzzle.is_solved():
self._keep_playing = Fa... | [
"def Display_game(self):\n \n print self.HANGMANPICS[len(self.wrongGuess)]",
"def gameDescription(self):\n\n print(self.gameName)\n print(\n f\"{self.minPlayers} to {self.maxPlayers} players\",\n \"using a single deck of cards\", end=' ')\n if self.useJoker... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If trainable, returns variable, otherwise the original embedding | def embedding_setup(self, embedding, emb_trainable):
if emb_trainable == True:
emb_variable = tf.get_variable(
name="embedding_matrix", shape=embedding.shape,
initializer = tf.constant_initializer(embedding))
return emb_variable
else:
return embedding | [
"def embedding_trainable_variables(self) -> Sequence[tf.Variable]:\n return self._embedding_layer.trainable_variables",
"def get_embedding_output(self):\n return self.embedding_output",
"def get_embedding(self, input):\n if type(input) is str:\n input = torch.tensor(self.word2index[input... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Looks if the received block is in the waiting list. If yes we check if the address is already recorded. If no it is added to the waiting list and broadcasted. | def arrivingBlock(self,data, addr, receivedBlock):
if self.blockchain.waiting_blocks == []:
self.confirmed.clear()
self.neighboursOk.clear()
self.confirmed.append(addr)
self.blockchain.putting_block(receivedBlock)
self.message = self.setMessa... | [
"def recv_ack(self, my_boot_time, neighbor_boot_time, my_snapshot_sn, neighbor_snapshot):\n if neighbor_boot_time < self.time_of_boot:\n return False\n elif neighbor_boot_time > self.time_of_boot:\n self.time_of_boot = neighbor_boot_time\n self.neighbor_snapshot_sn = 0... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that a new DynamicCadence is created by form submission | def test_create_cadence_for_new_site(self):
new_form_data = {
'site': 'cpt',
'cadence_frequency': 10,
'target_id': self.target.id
}
original_dc_count = DynamicCadence.objects.all().count()
response = self.client.post(reverse('nres_calibrations:nres_sub... | [
"def test_create_new_form(self):\n\n survey = self._create_test_survey()\n assert survey is not None\n\n new_survey = SurveyForm.get(self.test_survey_name)\n assert new_survey is not None\n assert new_survey.form == self.test_form",
"def test_new_recipe_form(self):\n\n se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that the nres_home target list contains the NRES calibration targets | def test_nres_targets_list(self):
response = self.client.get(reverse('nres_calibrations:nres_home'))
self.assertContains(response, self.target.id) | [
"def test_which_targets():\n num_multi_targets = 0\n for which_targets_day in which_targets:\n # All inputs have a label\n assert np.all(which_targets_day.sum(axis=1) > 0)\n # No inputs have more than 3 targets\n assert np.all(which_targets_day.sum(axis=1) < 4)\n\n num_multi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that the NRES Cadence list contains the ObservationGroup name of the DynamicCadence | def test_nres_cadence_list(self):
response = self.client.get(reverse('nres_calibrations:nres_home'))
self.assertContains(response, self.observation_group_name) # should appear in History column | [
"def test_cgm_list(self):\n\n # the function to be tested:\n cgs = self.urihandler.get(self.hmc, '/api/cpcs/2/capacity-groups',\n True)\n\n exp_cgs = { # properties reduced to those returned by List\n 'capacity-groups': [\n {\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets user input such as the localhost and the similarity value for the comparision. Reads all the ringsugars in the given database and and creates a data frame with aglycons, their coconut_id and taxonomy. The biological names are delete and if there are two different taxonomies for an aglycon, the taxonomy is called '... | def complete_databank(port="localhost:27017",coconut_database="COCONUT2020-10",sweetcoconut_database="sweetcoconut"):
client = MongoClient(port)
db_complete = client[coconut_database]
collection = db_complete.uniqueNaturalProduct
db_complete_only_ring_sugars = pd.DataFrame(list(collection.find({"contain... | [
"def sweetcoconut_databank(df_tax_id_fromCompleteDatabank, taxonomy_Double,sweetcoconut_database,port):\n client2 = MongoClient(port)\n db_s = client2[sweetcoconut_database]\n collection2 = db_s.sweetNaturalProduct\n sweetnp = pd.DataFrame(list(collection2.find({\"contains_sugar\": True})))\n sweetnp... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the created data frame with the three columns aglycon, coconut id and taxonomy Merges sweetcocunt data frame with incoming data frame via their coconut id. Replaces nan with "no" if there isn't a known taxonomy in the row for the aglycon. Summarize all aglycons with the same structure into one row. Writes a .pkl f... | def sweetcoconut_databank(df_tax_id_fromCompleteDatabank, taxonomy_Double,sweetcoconut_database,port):
client2 = MongoClient(port)
db_s = client2[sweetcoconut_database]
collection2 = db_s.sweetNaturalProduct
sweetnp = pd.DataFrame(list(collection2.find({"contains_sugar": True})))
sweetnp_with_tax = ... | [
"def combine_results(voting = 'hard',clf_list = ['test_small','rt_small','test2_small']):\n \n start = time.clock()\n df = load_all_dfs(clf_list)\n\n print('combining the data and voting ', voting)\n\n if voting == 'hard':\n print('voting')\n\n label_tupel_list = list(df.groupby(level=[... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets a data frame with all the same aglycon structures in one row. Counts all taxonomies and create a barplot. 'Double' is also a taxonomy. Saves the bar plot with the numbers of different taxonomies as .png. | def bar_plot(df_NP):
cnt = Counter()
for tax_list in df_NP.taxonomy:
for tax in list(tax_list):
if tax != 'no':
cnt[tax] += 1
plt.bar(cnt.keys(),cnt.values())
plt.xlabel('taxonomic provenance')
plt.ylabel('number of molecules')
plt.title('number of aglycons wi... | [
"def createBarplot(visDict): \n\n xax=np.arange(visDict[1],visDict[2])\n width = 0.8\n countList = np.zeros(visDict[2]-visDict[1]) \n \n for manufacturer in visDict[0]:\n\n countList1=np.array(list(visDict[0][manufacturer].values()))\n countList =countList + countList1\n\n plt.b... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets a data frame with all the same aglycon structures in one row. Counts all taxonomies and creates a venn diagram with the four taxonomies plants, bacteria, animals, fungi. Reads the original taxonmies of the 'Double' entries. Saves a venndiagram of the different taxonmies as .png. | def venn_diagram(df_NP, taxonomy_Double):
taxonomy_Single = [list(tax) for tax in df_NP.taxonomy if 'double' not in tax]
taxonomy_All = taxonomy_Single + taxonomy_Double
plants = set()
bacteria = set()
animals = set()
fungi = set()
for tax_list in taxonomy_All:
if "plants" in tax_lis... | [
"def make_taxon_table(result_together, samples):\n ##get a named list\n ##result = dict(zip(taxon,SB_100)) #continue from here\n pathogens = pd.Series()\n for sample in samples:\n pathogens = pathogens.append(result_together[sample]['species']['species'])\n\n # Get the unique genera \n p... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets a data frame with all the same aglycon structures in one row. Deletes all rows with more than one entry in the taxonomy row. Passes a data frame with only one entry (superkingdom or 'no') in the taxonomy row. | def aglycon_single_tax(df_NP):
# **seperate aglycons with at least two different entries in taxonomy**
index_Unique_Tax = [ind for ind, tax_list in enumerate(df_NP.taxonomy) if len(tax_list) == 1]
df_Without_Double = df_NP.iloc[index_Unique_Tax[:]]
#df_Without_Double
# **check for 'double' or 'tripl... | [
"def drop_duplicate_taxa(taxa):\n cxn = connect()\n existing = pd.read_sql('SELECT sci_name, taxon_id FROM taxa', cxn)\n existing = existing.set_index('sci_name').taxon_id.to_dict()\n in_existing = taxa.sci_name.isin(existing)\n return taxa.loc[~in_existing, :].drop_duplicates('sci_name').copy()",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Draw a histogram given the graph. | def draw_histogram(graph: Graph) -> Optional[Graph]:
if not graph:
return None
try:
# generate and open a new figure
figure, ax = plt.subplots()
# When graph.x or y is str, the histogram is ill-defined.
ax.barh(graph.y, graph.x, color=graph.color)
ax.set_title(graph.title)
if graph.xlabe... | [
"def drawHistogram(self, data, label=\"Count\", title=\"title\"): # Adapted from simple_histo.py sample source\n bar_fun = plt.barh # NB: this assigns a function to bar_fun!\n bar_ticks = plt.yticks\n bar_label = plt.xlabel\n\n n = len(data)\n bar_fun(range(n), list(data.values()... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Converts a Matplotlib figure to a base64 string encoding. | def figure_to_base64str(fig: matplotlib.figure.Figure) -> str:
buf = io.BytesIO()
fig.savefig(buf, bbox_inches='tight', format='png')
return base64.b64encode(buf.getbuffer().tobytes()).decode('ascii') | [
"def plt_to_base64():\n buffer = io.BytesIO()\n plt.savefig(buffer, format='png')\n buffer.seek(0)\n return base64.b64encode(buffer.read()).decode()",
"def plot_to_str(plt):\n figfile = BytesIO()\n plt.savefig(figfile, format='png')\n figfile.seek(0) # rewind to beginning of file\n figdata... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get person's ID from mbank.tcredits (turnes DB) | def get_person_id(contract_num, phone):
exfin_connection = MySQLdb.connect(
host="10.10.100.27", # host of MySQL database
user="root", # user's username
passwd="Orraveza(99)", # your password
db="mbank", # nam... | [
"def get_person_id_and_tel(contract_num):\n exfin_connection = MySQLdb.connect(\n host=\"10.10.100.27\", # host of MySQL database\n user=\"root\", # user's username\n passwd=\"Orraveza(99)\", # your password\n db=\"mbank\", ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get person's ID from mbank.tcredits (turnes DB) | def get_person_id_and_tel(contract_num):
exfin_connection = MySQLdb.connect(
host="10.10.100.27", # host of MySQL database
user="root", # user's username
passwd="Orraveza(99)", # your password
db="mbank", # na... | [
"def get_person_id(contract_num, phone):\n exfin_connection = MySQLdb.connect(\n host=\"10.10.100.27\", # host of MySQL database\n user=\"root\", # user's username\n passwd=\"Orraveza(99)\", # your password\n db=\"mbank\", ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Adapting numpy.int64 type to SQLconform int type using psycopg extension, see [1]_ for more info. | def adapt_numpy_int64(numpy_int64):
return AsIs(numpy_int64) | [
"def convert_to_Int64(self, cols):\n \n for col in cols:\n self.df[col] = pd.to_numeric(self.df[col], errors='coerce')\n self.df = self.df.astype({col:'Int64'})",
"def castData(data, type='int64'):\n data = data.astype(type)\n return data",
"def cast_to_integer(array, a... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets a dict of bestfit information from the database regarding the specified form factor. Also gets some "meta" information like the associated momentum, current, and lattice size. | def get_best_fit_information(engine, form_factor_id):
Nstates = collections.namedtuple(
'NStates', ['n', 'no', 'm', 'mo'], defaults=(1, 0, 0, 0)
)
def _float_or_none(astr):
if astr is None:
return None
if (astr.lower() == 'nan') or (astr.lower() == 'none'):
r... | [
"def _best_fit_model_(self,fit_dict,get_unpacked = True,with_errors = True):\n\n flops = PF.flops\n unpack_parameters = PF.unpack_parameters\n\n f, p = fit_dict['spectrum']['freq'], fit_dict['spectrum']['power']\n\n\n\n if with_errors:\n outkeys = ['best_fit','16th','84th']\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Locates rows in which NaNs appear. | def locate_nan_rows(arr):
# Count the number of NaNs in each row
nan_counts = np.sum(~np.isfinite(arr), axis=1)
# Trigger on a NaN appearing anywhere in a line/row
nans, = np.where(nan_counts > 1)
return frozenset(nans) | [
"def _nan_cells(traces):\n # Find all cells with NaNs\n nancells = []\n ncells = -1\n for cs in traces:\n if len(traces[cs]) > 0:\n ncells = np.shape(traces[cs])[1]\n ns = np.sum(np.sum(np.invert(np.isfinite(\n traces[cs])), axis=2), axis=0)\n vals ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sanitizes the dict 'record' for writing to 'table', i.e., restricts to keys which appear as columns of table. | def sanitize_record(record, table):
try:
columns = table.columns
except AttributeError:
columns = vars(table)
return {key: value for key, value in record.items() if key in columns} | [
"def _sanitise_fields(self, record):\n sanitised = {}\n for k, v in record.items():\n new_key = k.replace('(', '_').replace(')', '_')\n sanitised[new_key] = v\n return sanitised",
"def clean_record(self):\n _dict = {\n key: value for (key, value) in sel... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parse a string representation of a dictionary, e.g., | def parse_string_dict(dict_as_string):
new_dict = ast.literal_eval(dict_as_string[1:-1])
new_dict = {key: parse_string(val) for key, val in new_dict.items()}
return new_dict | [
"def parse_str_dict(self, text):\n return eval(text)",
"def str_to_dict(s):\n if s.startswith(\"{\") and s.endswith(\"}\"):\n return ast.literal_eval(s)\n else:\n return ast.literal_eval(\"{\" + s + \"}\")",
"def parse_key_value_string(kv_str: str) -> t.Dict:\n lexer = shlex(kv_str... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parse a string representation of an array of gvars into an array of gvars. This operation arises frequently, for example, when reading from the various "glance" tables, which store preprocessed data. | def parse_string(str_arr):
def to_arr(str_arr):
""" Switch to list. """
row = str_arr.replace(']', '').\
replace('[', '').\
replace('{', '').\
replace('}', '').\
replace('\n', '').split()
if '+-' in row:
row = kludge_gvars(row)
... | [
"def numpy_array_from_string(string,delimiters):\n nested_list = split_string_with_delimiters(string.strip(),\n delimiters,retype=float)\n return np.array(nested_list)",
"def parse_string(s):\n # type: (str) -> Union[str, np.ndarray, float]\n v = re.sub(r'[\\[\\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Occasionally, gvars get rendered to strings as, e.g., 4e06 + 1 instead of 0.000006(1.0). This makes a complete mess of trying to parse the a list of gvar which has been turned into a string, e.g., '[1(2) 1 + 2 0.003(2)]', since the usual str.split() separates '1 + 2' > ['1','+','2']. This function is a kludge which wor... | def kludge_gvars(mangled):
# Loop in reverse looking for '+-', but don't run off the end
for idx in range(len(mangled) - 1)[::-1]:
if mangled[idx + 1] == '+-':
reunited = ' '.join(mangled[idx:idx + 3])
# Throw away the used elements...
for _ in... | [
"def parse_string(str_arr):\n def to_arr(str_arr):\n \"\"\" Switch to list. \"\"\"\n row = str_arr.replace(']', '').\\\n replace('[', '').\\\n replace('{', '').\\\n replace('}', '').\\\n replace('\\n', '').split()\n\n if '+-' in row:\n r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Upsert the content of a DataFrame into a db table | def upsert(engine, table_name, dataframe):
# Reflect table from db
metadata = sqla.MetaData(bind=engine)
table = sqla.Table(
table_name,
metadata,
autoload=True,
autoload_with=engine)
# Unpackage DataFrame
records = []
for _, row in dataframe.iterrows():
... | [
"def write_to_db(dataframe, db_conn, table_name):\n dataframe.to_sql(table_name, db_conn, if_exists='append')",
"def load_df(df, table_name, dbapi='sqlite:///insurance.db', \n if_exists='replace'):\n con = create_engine(dbapi, echo=False)\n print('Inserting {} rows into {}'.format(len(df.index... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Writes the dictionary 'src' to the table named 'table_name'. | def write(engine, table_name, src, return_id=True, do_update=False):
query = build_upsert_query(engine, table_name, src, do_update=do_update)
LOGGER.debug(query)
engine.execute(query)
if return_id:
return fetch_id(engine, table_name, src) | [
"def dump_table(self, copy_cmd, curs, fn):\r\n f = open(fn, \"w\", 64*1024)\r\n curs.copy_expert(copy_cmd, f)\r\n self.log.info('%s: Got %d bytes' % (self.table_name, f.tell()))\r\n f.close()",
"def copy_table(source_table, destination_table, db='default'):\n try:\n w... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the unique columns from the table's contraints. | def get_unique_columns(table):
for constraint in table.constraints:
if isinstance(constraint, sqla.UniqueConstraint):
return constraint.columns
# We should never get this far.
# All tables in my db should have unique constraints
assert False | [
"def get_unique_columns(cls):\n column_list = cls.get_columns()\n return [column for column in column_list if column.unique]",
"def get_uniques(constraints):\n uniques = {}\n if constraints:\n for name, constraint in constraints.items():\n if constraint[\"type\"] == UNIQUE an... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Builds a raw SQL query for "upserting" data into the database. | def build_upsert_query(engine, table_name, src_dict, do_update=False):
def _for_pgsql(value, dtype):
"""
Converts a python datatype to the appropriate string (including, e.g., \
the necessary single quotes and/or brackets ) for use in a raw \
postgresql query.
Args:
... | [
"def _generate_upsert_sql(mon_loc):\n mon_loc_db = [(k, _manipulate_values(v, k in TIME_COLUMNS)) for k, v in mon_loc.items()]\n all_columns = ','.join(col for (col, _) in mon_loc_db)\n all_values = ','.join(value for (_, value) in mon_loc_db)\n update_query = ','.join(f\"{k}={v}\" for (k, v) in mon_loc... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Converts a python datatype to the appropriate string (including, e.g., \ the necessary single quotes and/or brackets ) for use in a raw \ postgresql query. | def _for_pgsql(value, dtype):
if dtype.startswith(('int', 'float', 'double', 'numeric')):
if value is None:
return "Null"
elif str(value).lower() == 'nan':
return "'nan'"
elif dtype.endswith('[]'):
value = ', '.join([str(v) for ... | [
"def typecast(dtype: Any) -> str:\n if dtype is int:\n return \"Int64\"\n elif dtype is float:\n return \"Float64\"\n elif dtype is bool:\n return \"bool\"\n return \"string\"",
"def field_cast_sql(self, db_type):\n return '%s'",
"def python_ty... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets a list of "set pairs" for use in a raw SQL query, e.g., INSERT INTO table_name (column1, column2, ...) VALUES (value1, value2, ...) ON CONFLOCT (column1) DO UPDATE SET column1=value1, column2=value2 This function returns a string "column1=value1, column=value2 | def _get_set_pairs(uprow, types):
pairs = []
for key, val in uprow.items():
pairs.append("{0}={1}".format(key, _for_pgsql(val, types[key])))
return ", ".join(pairs) | [
"def generate_sql_update_set_formatted_string(keys_list: List[str]):\n\n return \", \".join([f\"{key} = :{key}\" for key in keys_list])",
"def sql_filtered_insert(table, set_columns, values):\n for index in range(len(set_columns) - 1, -1, -1):\n if values[index] is None:\n del set_columns[... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Fetches a list of correlators matching the specified form factor. | def fetch_basenames(engine, form_factor):
for key in ['current', 'm_mother', 'm_daughter', 'm_spectator', 'momentum']:
if key not in form_factor:
raise KeyError(f"Required key '{key}' is missing.")
def abspath(dirname):
return os.path.join(pathlib.Path(__file__).parent.absolute(), d... | [
"def get_form_factors():\n form_factors_file = '/'.join(path.realpath(__file__).split('/')[:-1]) \\\n + '/form_factors.csv'\n constants = list(n.loadtxt(form_factors_file,\n skiprows=1,\n delimiter=',',\n usecols={1,2,3,4,5,6,7,8,9}\n ))\n labels = list(n.loadt... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets an alias for a quark mass (e.g., '1.0 m_light') from a table. | def get_alias(a_fm, description, quark_mass):
quark = conventions.quark_masses
mask = utils.bundle_mask(quark, a_fm=a_fm, description=description, mq=quark_mass)
return utils.extract_unique(quark[mask], 'alias') | [
"def alias_column_name(self, column):\n # for now we simply prepend this prefix, a more thorough solution would look at actual\n # table columns to make sure none of the column names starts with the prefix:\n return self.ALIAS_COLUMN_PREFIX + column",
"def listMass(param, qk):\n\n q = para... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that variant libraries load and initialize. | def test_load_variant(variant):
try:
f = fvs.FVS(variant)
except ImportError:
pytest.skip('No variant library: {}'.format(variant))
return None
except:
raise
assert f.variant == variant
assert not f.fvslib is None
f = None | [
"def test_load_libs(self):\n script = 'var %s = {foo: \"foo\"};' % _global\n\n with js_file(script) as path:\n utils.load_libs([path])\n\n self.assertEqual('foo', utils.run_script('%s.foo' % _global))\n self.assertEqual('true', utils.run_script('delete %s.foo' % _global))",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set a new sudoku matrix with new matrix | def set_sudoku_matrix(self, matrix):
self.sudoku_matrix = matrix | [
"def make_sudoku(size):\r\n def mutate_list_1(lst, size):\r\n \"\"\"Helper function for removing part of a list from the beginning and add it to the end.\"\"\"\r\n count = 0\r\n while count < size:\r\n elem = lst[0]\r\n lst.remove(elem)\r\n lst.append(elem)\r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Print the sudoku matrix in the console | def print_sudoku_matrix(self):
row_list = 'ABCDEFGHI'
print " 1 2 3 4 5 6 7 8 9 "
for i in range(9):
if i % 3 == 0:
print " +-------+-------+-------+"
var = row_list[i] + " "
for j in range(9):
if j % 3 == 0:
... | [
"def print_sudoku(self):\r\n print(self._sudoku)",
"def print_sudoku_solution(solution):\n for row in range(9):\n for col in range(9):\n print solution['%d-%d' % (row, col)][0],\n if col == 2 or col == 5:\n print '|',\n print\n if row == 2 or row... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Hide cell in the Sudoku Matrix | def hide_values_in_matrix(self, difficult):
row = random.randint(0, 8)
column = random.randint(0, 8)
if (difficult != 0):
self.sudoku_matrix[row][column].set_cell_visibility(True)
self.sudoku_matrix[row][column].set_cell_value(0)
self.hide_values_in_matrix(dif... | [
"def uncover(self, row, column):\r\n cellStat = self.board[row][column].is_hidden()\r\n if cellStat:\r\n self.board[row][column].status = 'S'\r\n pass",
"def hide_mines(self):\n for line_i in range(len(self.board)):\n for char_i in range(len(self.board[line_i])):\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a sudoku matrix | def get_sudoku_matrix(self):
return self.sudoku_matrix | [
"def make_sudoku(size):\r\n def mutate_list_1(lst, size):\r\n \"\"\"Helper function for removing part of a list from the beginning and add it to the end.\"\"\"\r\n count = 0\r\n while count < size:\r\n elem = lst[0]\r\n lst.remove(elem)\r\n lst.append(elem)\r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a sudoku matrix solved | def get_sudoku_matrix_solved(self):
return self.sudoku_matrix_solved | [
"def solve_sudoku(sudoku):\n # Define the solution matrix that represents the sudoku puzzle\n solution = Matrix(9, 9, 1, 9)\n\n # Set up the model\n model = Model()\n\n # Set the constraints for the filled in cells\n for i in xrange(0, 9):\n for j in xrange(0, 9):\n if sudoku[i, ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method that compare if two SudokuMatrix object are equals | def __eq__(self, other_sudoku_matrix):
equals = False
for row in range(9):
for col in range(9):
if int(self.get_cell(row, col).get_cell_value()) == int(
other_sudoku_matrix.get_cell(row, col).get_cell_value()):
equals = True
... | [
"def __eq__(self, OtherMatrix):\n return self.matrix == OtherMatrix.show()",
"def __eq__(self,other):\n return (type(other) == Matrix and\n self.getA() == other.getA() and\n self.getB() == other.getB() and\n self.getC() == other.getA() and\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create HYPER_FILE from SCHEMA_FILE and load with metadata query results | def create_extract():
with open(SCHEMA_FILE, "r") as f:
SCHEMA = yaml.safe_load(f)
with open(TOKEN_FILE, "r") as f:
TOKEN = yaml.safe_load(f)
hc = HyperCreator(SCHEMA, HYPER_FILE)
ts = Tableau(TOKEN["server"], TOKEN["site"], TOKEN["name"], TOKEN["value"])
for table in SCHEMA["tabl... | [
"def create_sql_template(filename):\n with open(filename) as f:\n return f.read().replace(REPLACE_SCHEMA_NAME, '%(schema)s')",
"def _create_schema(self, cypher_file):\n if len(self.graph.nodes) > 0:\n msg = \"Cypher file specified but the graph is not empty. Aborting.\"\n ra... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Replace current extract in TDSX_FILE with HYPER_FILE | def update_datasource():
ds = Datasource(TDSX_FILE)
ds.replace_extract(HYPER_FILE) | [
"def hxlreplace():\n run_script(hxlreplace_main)",
"def subst_file(file_name, values):\n template = open(file_name, 'r').read()\n return subst_template(template, values);",
"def insert_H3(H3_file, outfile, template):\n '''\n tempdata=\"tigit_fab_with_H3_template.pdb\" \n \n temp=open(tempdata)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the current desired count of the specified ECS Service. | def get_desired_count(cluster_name, service_name):
response = ecs_client.describe_services(
cluster=cluster_name, services=[service_name],
)
for service in response["services"]:
return service["desiredCount"]
raise Exception(
f"desiredCount not found for cluster: {cluster_name... | [
"def service_count(self) -> str:\n return pulumi.get(self, \"service_count\")",
"def _describe_service(self):\n LOGGER.info('Getting the current task definition for %s in %s',\n self.args.service, self.args.cluster)\n response = self.client.describe_services(\n c... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
word 2 tuple by char_id | def word2tuple(word, char_id):
tup = []
for c in word:
if str(c) in char_id:
tup.append(char_id[c])
else:
tup.append(len(char_id))
return tuple(tup) | [
"def word2tuple(word):\n new_word = tuple(sorted(word))\n return new_word",
"def get_word2id(word2id,token):\r\n if(token in word2id):\r\n return word2id[token]\r\n else:\r\n return word2id['<unk>']",
"def create_word(char_list):",
"def word_to_tuple(word):\n # since strings are s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
we are going to split out the domain from the url and lookup the ip address then we get both whois ip and domain name info | def get_whois(doc):
#extract domain info
domain = tldextract.extract(doc['url']).registered_domain
hostname = doc['url'].split('/')[2]
doc['hostname'] = hostname
doc['ip'] = ''
doc['whois'] = {}
try:
#lookup ip address
doc['ip'] = socket.gethostbyname(hostname)
except:... | [
"def WhoisLocation(url):\n location=[]\n location_str_list=[]\n try: # first try this\n #trying with pythonwhois to see if the location exists\n obj=pythonwhois.get_whois(url)\n for key in obj['contacts']['registrant']:\n location.append(obj['contacts']['registrant'][key])\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
We are going to use a headless browser to hit the target homepage and enumerate all of the other urls that we hit, cookies and the page source | def interrogate_homepage(doc):
socket.setdefaulttimeout(30)
doc['browser'] = {}
#empty page
empty = u'<html><head></head><body></body></html>'
#set the path to our compiled phantomjs
phantomjs = '/phantom_bin/bin/phantomjs'
#set server args to ignore certificate errors
serv_arg = ['-... | [
"def get_all_headlines_from_chrome_2(site,URL_exclusions):\r\n headlines = []\r\n #Initial URL to pass to return search:\r\n URL = f'https://www.google.co.uk/search?as_q=&as_epq=irish+travellers&as_oq=&as_eq=&as_nlo=&as_nhi=&lr=&cr=&as_qdr=all&as_sitesearch={site}&as_occt=any&safe=active&as_filetype=&tbs='... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
this will parse the eve log and get some information from it and add it to our document. We are just going to get the signature name for now | def get_ids_logs(doc):
doc['ids'] = []
with open('/var/log/suricata/eve.json', 'r') as f:
for line in f:
#lets go ahead and deserialize the log and pull out sig field
sig = json.loads(line)['alert']['signature']
#blergh, too lazy to comment out of suricata, or chang... | [
"def log_parser(log):\n # substitute for GREP -- finds 'eventtype' field.\n # required as this file has a different number of fields per line\n logname = copy.copy(log)\n log = open(log, \"r\").readlines()\n pic = filter(lambda s: 'Picture' in s, log)\n vid = filter(lambda s: 'Video' in s, log)\n\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compute a the cocitation graph using a citation network | def cocite(G,min_citations = 2):
if not G.is_directed():
msg = "The cocitation algorithm requires a directed citation graph as an input."
raise nx.NetworkXError(msg)
#assert type(G) == nx.classes.digraph.DiGraph
edges = {}
#for each node
for n in G.nodes():
# for each out... | [
"def create_cocitation_network(citation_net, file_name):\n cocited = set()\n with open(file_name, 'w') as file:\n for node, neighbors in citation_net.adj.items():\n cites = list(citation_net.neighbors(node))\n size = len(cites)\n for i in range(size):\n f... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Find arguments suitable for forest.parse_args.parse_args e.g. bokeh serve args [ARGS] or forest [ARGS] | def parse_forest_args(argv=None):
if argv is None:
argv = sys.argv
if "bokeh" in os.path.basename(argv[0]):
i = argv.index("--args")
return argv[i + 1 :]
else:
_, argv = forest.cli.main.parse_args(argv)
return argv[1:] | [
"def parse_arguments(args):",
"def read_args():\n parser = argparse.ArgumentParser(description='Taiko data analysis toolkit')\n parser.add_argument('-f', help='Write frames', action='store_true')\n return vars(parser.parse_args())",
"def parse_args():\n parser = argparse.ArgumentParser(\n des... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Enables global stackwisevirtual on target device | def configure_global_stackwise_virtual(device, domain=None):
# build a list of commands to send
# Add stackwise-virtual as first element in the list
# Add domain only if domain argument has been provided
command_list = ['stackwise-virtual']
if domain:
command_list.append(f'domain {domain}')
... | [
"def unconfigure_global_stackwise_virtual(device):\n # Single command 'no stackwise-virtual' will remove configuration\n command = 'no stackwise-virtual'\n try:\n output = device.configure(command)\n except SubCommandFailure:\n raise SubCommandFailure('Failed to remove global stackwise-vir... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Disable global stackwisevirtual on target device | def unconfigure_global_stackwise_virtual(device):
# Single command 'no stackwise-virtual' will remove configuration
command = 'no stackwise-virtual'
try:
output = device.configure(command)
except SubCommandFailure:
raise SubCommandFailure('Failed to remove global stackwise-virtual')
... | [
"def unconfigure_global_dual_active_recovery_reload_disable(device):\n # build a list of commands to send\n # Add stackwise-virtual as first element in the list\n # Enables dual-active recovery-reload\n command_list = ['stackwise-virtual']\n command_list.append(f'no dual-active recovery-reload-disabl... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Enables interface as dualactivedetection interface on target device | def configure_stackwise_virtual_dual_active_interfaces(device, dad_links):
# build a list of commands to send
command_list = []
output = ''
for interface in dad_links:
command_list.append(f'interface {interface}')
command_list.append(f'stackwise-virtual dual-active-detection')
try:
... | [
"def enable(self):\n # Netmiko reports enable and config mode as being enabled\n if not self.native.check_enable_mode():\n self.native.enable()\n # Ensure device is not in config mode\n if self.native.check_config_mode():\n self.native.exit_config_mode()\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Disables interface as dualactivedetection interface on target device | def unconfigure_stackwise_virtual_dual_active_interfaces(device, dad_links):
# build a list of commands to send
command_list = []
output = ''
for interface in dad_links:
command_list.append(f'interface {interface}')
command_list.append(f'no stackwise-virtual dual-active-detection')
t... | [
"def network_disable(iface):\n\n core.disable(iface)\n\n return jsonify(message='disabled {}'.format(iface), code=200)",
"def disable_radio(self):\n self.acquire_response(b'AT*R0')",
"def test_multi_ap_disabled_on_ap(dev, apdev):\n run_multi_ap_association(dev, apdev, 0, wait_connect=False)\n ev ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Enables global stackwisevirtual dualactive recovery reload on target device | def configure_global_dual_active_recovery_reload_disable(device):
# build a list of commands to send
# Add stackwise-virtual as first element in the list
# Disables dual-active recovery-reload
command_list = ['stackwise-virtual']
command_list.append(f'dual-active recovery-reload-disable')
try:
... | [
"def unconfigure_global_dual_active_recovery_reload_disable(device):\n # build a list of commands to send\n # Add stackwise-virtual as first element in the list\n # Enables dual-active recovery-reload\n command_list = ['stackwise-virtual']\n command_list.append(f'no dual-active recovery-reload-disabl... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Enables global stackwisevirtual dualactive recovery reload on target device | def unconfigure_global_dual_active_recovery_reload_disable(device):
# build a list of commands to send
# Add stackwise-virtual as first element in the list
# Enables dual-active recovery-reload
command_list = ['stackwise-virtual']
command_list.append(f'no dual-active recovery-reload-disable')
tr... | [
"def configure_global_dual_active_recovery_reload_disable(device):\n # build a list of commands to send\n # Add stackwise-virtual as first element in the list\n # Disables dual-active recovery-reload\n command_list = ['stackwise-virtual']\n command_list.append(f'dual-active recovery-reload-disable')\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Enables portchannel interface as pagp dualactivedetection interface on target device | def configure_stackwise_virtual_dual_active_pagp(device, port_channel):
# build a list of commands to send
command_list = ['stackwise-virtual']
command_list.append(f'dual-active detection pagp')
if port_channel:
command_list.append(f'dual-active detection pagp trust channel-group {port_channel}'... | [
"def unconfigure_stackwise_virtual_dual_active_pagp(device, port_channel):\n # build a list of commands to send\n command_list = ['stackwise-virtual']\n if port_channel:\n command_list.append(f'no dual-active detection pagp trust channel-group {port_channel}')\n try:\n output = device.conf... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Disables portchannel interface as pagp dualactivedetection interface on target device | def unconfigure_stackwise_virtual_dual_active_pagp(device, port_channel):
# build a list of commands to send
command_list = ['stackwise-virtual']
if port_channel:
command_list.append(f'no dual-active detection pagp trust channel-group {port_channel}')
try:
output = device.configure(comma... | [
"def disable_cable_ports(cid):\n\n SQL.execute('''\n SELECT \n cpid,\n guid,\n port,\n hca\n FROM \n cable_ports \n WHERE\n cid = ?\n ''',(\n cid,\n ))\n\n for row in SQL.fetchall(): \n if row['hca']:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create the base project folder named `.wcscanner` This folder will contain projects folders | def create_base_projects_folder():
if '.wcscanner' not in os.listdir(context.__BASE_PATH__):
os.mkdir(context.__PROJECTS_PATH__, mode=0o777)
log.info("Base folder '.wcscanner' created in %s", context.__BASE_PATH__)
else:
log.info("Base folder '.wcscanner' already in %s", context.__BASE_P... | [
"def newproject(self):\n \n self.path = os.path.join(self.base, self.name)\n subpath = os.path.join(self.path, self.lowname)\n check_build_path(subpath)\n \n for filename, content in self.files.items():\n self.buildfile(filename, content, self.path)\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |