query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Return the two ends of an iterable | def ends(iter):
li = list(iter)
return li[0], li[-1] | [
"def _tails(iterable: Iterable[T], *, num_from_each_tail=Union[int, Tuple[int, int]]) -> Tuple[List[T], List[T], int]:\n num_start, num_end = (num_from_each_tail, num_from_each_tail) if isinstance(num_from_each_tail, int) else num_from_each_tail\n iterator = iter(iterable)\n start = list(it.islice(iterat... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a Course object parsed from a file | def from_file(cls, fn):
fp = os.path.join('courses', fn)
with open(fp, 'r') as f:
lines = f.readlines()
name = os.path.splitext(fn)[0]
start, stop = map(date.fromisoformat, lines[0].split())
nbr_of_exams = int(lines[1].rstrip())
exerci... | [
"def load_courses(self, file):\n with open(file) as csv_file:\n csv_reader = csv.reader(csv_file, delimiter=',')\n for row in csv_reader:\n self.courses.append(Course(row[0], row[1], row[2],row[3],row[4],row[5],row[6],row[7]))\n\n # removing the first row because i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Parse each course file in the courses directory into a Course object and yield it. | def courses(cls):
for fn in os.listdir('courses'):
yield cls.from_file(fn) | [
"def read(cls, filename):\n for item in cls().parse(filename):\n yield item",
"def load_courses(self, file):\n with open(file) as csv_file:\n csv_reader = csv.reader(csv_file, delimiter=',')\n for row in csv_reader:\n self.courses.append(Course(row[0],... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Chunk the exercises over a stretch of days | def chunk_over_days(self):
# - 1 for full-day repetition
# - nbr_of_exams for studying exams
return self._chunk_over_days(self.duration - self.nbr_of_exams - 1) | [
"def _chunk_over_days(self, days):\n x = len(self.exercises) # see docs\n d = x % days # see docs\n n = x // days # see docs\n\n sliced_at = (days - d) * n\n pt1 = self.exercises[:sliced_at]\n pt2 = self.exercises[sliced_at:]\n\n return list(g... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Chunk the exercises over a stretch of days Imagine the list of exercises [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] to be chunked over 3 days. That is, after doing a certain amount of exercises each day (the day's chunk size), after 3 days, all exercises will be completed. | def _chunk_over_days(self, days):
x = len(self.exercises) # see docs
d = x % days # see docs
n = x // days # see docs
sliced_at = (days - d) * n
pt1 = self.exercises[:sliced_at]
pt2 = self.exercises[sliced_at:]
return list(grouped(pt1, n)... | [
"def chunk_over_days(self):\n \n # - 1 for full-day repetition\n # - nbr_of_exams for studying exams\n\n return self._chunk_over_days(self.duration - self.nbr_of_exams - 1)",
"def chunk(elist, size):\n for i in range(0, len(elist), size):\n yield elist[i:i + size]",
"def ch... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the condition_type of this ConditionRequireBookingData. | def condition_type(self) -> str:
return self._condition_type | [
"def _GetConditionForType(obj, condition_type):\n conditions = _GetPathValue(obj, ['status', 'conditions'])\n if not conditions:\n return False\n for condition in conditions:\n if condition['type'] == condition_type:\n return condition\n return None",
"def getCondition(self):\r\n return self... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the condition_type of this ConditionRequireBookingData. | def condition_type(self, condition_type: str):
if condition_type is None:
raise ValueError("Invalid value for `condition_type`, must not be `None`") # noqa: E501
self._condition_type = condition_type | [
"def relaxation_type(self, relaxation_type):\n\n self._relaxation_type = relaxation_type",
"def set_conditional(self, func_type):\n _validate_func_type(func_type)\n self.conditionals[func_type] = True",
"def set_type(self, the_type: [bool, int, float, str]):\n if self._value:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the required_fields of this ConditionRequireBookingData. | def required_fields(self) -> List[str]:
return self._required_fields | [
"def check_required_fields(self):\n required_fields = set()\n for field_id in self.REQUIRED_FIELDS:\n if not getattr(self, field_id):\n required_fields.add(field_id)\n return required_fields",
"def get_required_keys(self):\n return self.REQUIRED_KEYS",
"def ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the required_fields of this ConditionRequireBookingData. | def required_fields(self, required_fields: List[str]):
allowed_values = ["FROM_ADDRESS", "TO_ADDRESS", "BIRTHDATE", "EMAIL", "PERSONAL_ADDRESS", "PHONE_NUMBERS", "LICENSES", "BANK_CARDS", "DISCOUNT_CARDS", "TRAVEL_CARDS", "ID_CARDS", "CREDIT_CARDS", "NAME", "AGE", "BLOCKCHAIN_CLAIMS"] # noqa: E501
if n... | [
"def required(self):\n self.is_required = True\n return self",
"def check_required_fields(self):\n required_fields = set()\n for field_id in self.REQUIRED_FIELDS:\n if not getattr(self, field_id):\n required_fields.add(field_id)\n return required_fields... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the claims of this ConditionRequireBookingData. | def claims(self) -> List[str]:
return self._claims | [
"def getClaims(self, property):\r\n if not hasattr(self, 'claims'):\r\n self.get()\r\n if self.claims:\r\n if property in self.claims:\r\n return self.claims[property]\r\n return []",
"def getClaim():",
"def value(self):\n return getattr(self, 'cl... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sets the claims of this ConditionRequireBookingData. | def claims(self, claims: List[str]):
self._claims = claims | [
"def claim(self, claim: str):\n\n self._claim = claim",
"def edit_claim(self, claim):\n token = self.get_csrf_token()\n params = {\n \"action\": \"wbsetclaim\",\n \"claim\": json.dumps(claim),\n \"token\": token,\n }\n r1 = self.session.post(self... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Little helper routine that will return a UTCDateTime object with the beginning of the next month of the given UTCDateTime object. | def _getNextMonth(self, datetime):
year = datetime.year
month = datetime.month
next_month = month + 1
if next_month != 12:
next_month = next_month % 12
if next_month == 1:
year += 1
return UTCDateTime(year, next_month, 1) | [
"def _getBeginningOfMonth(self, datetime):\n return UTCDateTime(datetime.year, datetime.month, 1)",
"def get_next_month(date):\n if date.month == 12:\n return date.replace(year=date.year + 1, month=1, day=1)\n else:\n return date.replace(month=date.month + 1, day=1)",
"def _get_end_of... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Same as _getNextMonth but this one will return the beginning of the month as a UTCDateTime object. | def _getBeginningOfMonth(self, datetime):
return UTCDateTime(datetime.year, datetime.month, 1) | [
"def _getNextMonth(self, datetime):\n year = datetime.year\n month = datetime.month\n next_month = month + 1\n if next_month != 12:\n next_month = next_month % 12\n if next_month == 1:\n year += 1\n return UTCDateTime(year, next_month, 1)",
"def get_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns the relative position of datetime within the graph in respect to self.starttime and self.time_range. | def _getRelativePosition(self, datetime):
return (datetime - self.starttime) / self.time_range *\
parent.graph_width | [
"def position_timed(self):\r\n actual_time = time.time()\r\n self.position[0] = self.speed[0] * self.time_speed + self.position[0]\r\n self.position[1] = self.speed[1] * self.time_speed + self.position[1]\r\n self.last_time_position = actual_time\r\n return self.position",
"def ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculates the tick positions for the months in relative units, e.g. 0 is at the left border of the graph and 1 at the right border. | def _calculateMonthlyTicks(self):
first_tick = self._getNextMonth(self.starttime)
last_tick = self._getBeginningOfMonth(self.endtime)
self.ticks = [self._getRelativePosition(first_tick)]
# Loop and get the relative positions.
while first_tick < last_tick:
first_tick =... | [
"def setup_ticks(self):\r\n ndana = self.zavrsnoVrijeme - self.pocetnoVrijeme\r\n #major ticks\r\n majorLocator = HourLocator(interval=ndana.days+1)\r\n majorFormat = DateFormatter('%H:%M')\r\n #minor ticks\r\n minorLocator = AutoMinorLocator(n=4)\r\n minorFormat = N... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
sets in __objects the obj with key .id | def new(self, obj):
key = str((type(obj).__name__) + '.' + (obj.id))
return self.__objects.update({key: obj}) | [
"def update(self, obj, id):",
"def register_object( self, obj ):\n obj_id = id( obj )\n self.objects[ obj_id ] = obj\n return obj_id",
"def test_patch_obj_id_put(self):\n pass",
"def id_dict(self):\n return {obj.id: obj for obj in self}",
"def test_patch_obj_id_get(self):\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get starting hash for given device | def get_hash_for_device(uuid: int, location: str) -> ElementModQ:
return hash_elems(uuid, location) | [
"def __get_current_hash__(self):\n hasher = hashlib.sha256()\n hasher.update(self.previous_hash.encode() + self.data.encode())\n return hasher.hexdigest()",
"def hash(self):\n return self.wh",
"def get_hash(self):\r\n path = self.files[self.idx_image]\r\n filename = path.split(\"/\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the rotated tracker hash for a particular ballot. | def get_rotating_tracker_hash(
prev_hash: ElementModQ, timestamp: int, ballot_hash: ElementModQ
) -> ElementModQ:
return hash_elems(prev_hash, timestamp, ballot_hash) | [
"def get_hash(self, label):\n labelhash = self._hasher.copy()\n labelhash.update(pickle.dumps(label))\n return labelhash.digest()",
"def hash(polygon):\n crc = zlib.adler32(polygon.wkb)\n return crc",
"def zobrist_hash(self) -> int:\n return chess.polyglot.zobrist_hash(self)",
... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
shows board with PyGame functions | def show_board(self) -> None:
pygame.display.set_caption("Qwixx Board")
if self.is_turn_invalid:
self.screen.fill(PyGameUi.red_vibrant)
else:
self.screen.fill(PyGameUi.white)
font = pygame.font.SysFont('Comic Sans MS', PyGameUi.font_numbers_size, True, False)
... | [
"def drawBoard(self):\n\n # \"board\" is a list of 10 strings representing the board (ignore index 0)\n print(' | |')\n print(' ' + self.board[7] + ' | ' + self.board[8] + ' | ' + self.board[9])\n print(' | |')\n print('-----------')\n print(' | |')\n pri... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
draws a skip button | def _render_skip_button(self, font) -> None:
pygame.draw.rect(self.screen, PyGameUi.light_grey,
[PyGameUi.skip_button_x, PyGameUi.penalty_box_y, PyGameUi.skip_button_x_length,
PyGameUi.penalty_box_y_length], 0)
self.button(0, PyGameUi.skip_button_x_leng... | [
"def btn_func_skip(self):\n self.new_point(QtCore.QPoint(-1, -1))",
"def story_skip(self):\r\n #if self.skip.displayed(max_wait=5):\r\n self.skip.click()\r\n # return not self.skip.displayed(max_wait=5)\r",
"def skip():\n Playlist.skip_song()\n current_song_text.setText(\"{}\".... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
renders the dice onto the board | def _render_dice(self, font) -> None:
for dice in range(len(self.lst_eyes)):
text = font.render(f"{self.lst_eyes[dice]}", True, self.convert_number_to_color(dice, True))
self.screen.blit(text,
[PyGameUi.button_length + PyGameUi.button_x_distance * dice,
... | [
"def roll_two_dice(self, graphical=True):\n\n die_1 = self.get_random_die() # Set random value between 1 - 6\n die_2 = self.get_random_die() # Set random value between 1 - 6\n\n # -------------------\n # DIE MAP DESCRIPTION\n # -------------------\n # The die map holds th... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
shows whether the player is active or passive | def _show_player_mode(self, font) -> None:
if self.is_active_player:
player_mode = "active player"
else:
player_mode = "passive player"
text = font.render(f"{player_mode}", True, PyGameUi.dark_grey)
self.screen.blit(text, [PyGameUi.box_x + PyGameUi.player_mode_x_o... | [
"def external_player(self, player_obj):\n return plugin_addon.getSetting('external_player').lower() == 'true'",
"def is_paused(self) -> bool:",
"def is_playing(self, user):\r\n\t\treturn user is self.player1 or user is self.player2",
"def test_toggle_active(self):\n the_game = game.Game()\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
converts the color of a button to a row number | def convert_color_to_row(color) -> int:
if color == PyGameUi.red_vibrant:
return 0
if color == PyGameUi.yellow_vibrant:
return 1
if color == PyGameUi.green_vibrant:
return 2
if color == PyGameUi.blue_vibrant:
return 3
if color == Py... | [
"def __get_row_ids(self, r) -> Tuple[int, int, int]:\n return r*self.col, r*self.col+self.col, 1",
"def pressed(self):\n\n for i, col in enumerate(self.cols):\n col.value(1)\n for j, row in enumerate(self.rows):\n if row.value() == 1:\n col.val... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
converts numbers of dice or rows to one or a tuple of colors | def convert_number_to_color(number, is_dice=False) -> tuple:
if is_dice:
if number in (0, 1):
return PyGameUi.dark_grey
if number == 2:
return PyGameUi.red
if number == 3:
return PyGameUi.yellow_vibrant
if number == ... | [
"def get_colours(self, number):\n if number <= 0:\n number = 1\n ix = int(log2(number))\n return self.colours[ix]",
"def compute_colors(number):\n return COLORS[number % len(COLORS)]",
"def _next_colour():\n return tuple(numpy.concatenate(\n (numpy.random.choice(rang... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Computes the values of the hidden layer | def get_hidden_values(self, input):
# print T.dot(input, self.W).eval()
return T.nnet.sigmoid(T.dot(input, self.W) + self.b) | [
"def get_hidden(self, layer):",
"def compute_visible(self, h): \n hidden = tf.placeholder(tf.float32, [None, self.n_hidden], name=\"hidden\")\n compute = sample(tf.sigmoid(tf.matmul(hidden, tf.transpose(self.W)) + self.vb))\n \n x = self.sess.run(compute, feed_dict={hidden:h})\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Computes the reconstructed input given the values of the hidden layer | def get_reconstructed_input(self, hidden):
return T.nnet.sigmoid(T.dot(hidden, self.W_prime) + self.b_prime) | [
"def get_hidden_values(self, input):\n# print T.dot(input, self.W).eval()\n return T.nnet.sigmoid(T.dot(input, self.W) + self.b)",
"def get_output(self, input_, mask_, hidden_init):\n # input_ are (n_batch, n_timesteps, n_features)\n # change to (n_timesteps, n_batch, n_features)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
configuration interaction for hydrogen molecule | def configuration_interaction(R,Z):
# Hartree Fock computations yield a set of MOs
C, Hcore, nuclear_energy, two_electron = hartree_fock(R, Z, CI=True)
# number of configurations considered in the calculation
ND = 2
P = np.zeros(Hcore.shape)
K = Hcore.shape[0]
print('number of MOs = ', K... | [
"def PlotConfig(self) -> _n_1_t_3:",
"def hxconfig(self, cmd):\n \n if self.backend is not 'hxhal' or self.controller is None:\n cmd.fail('text=\"No hxhal controller\"')\n return\n\n cmdKeys = cmd.cmd.keywords\n configName = cmdKeys['configName'].values[0]\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the string to print with the recipe info | def __str__(self):
text = "Recipe for: " + self.name + "\nIt's a level "+str(self.cooking_lvl)+" recipe that takes "+str(self.cooking_time)+"min to prepare.\n"
text = text + "The ingredient list is :" + str(self.ingredients) + "\nRecipe Description:\n" + self.description + "\nIt's a " + self.type
... | [
"def __str__(self):\n return \"\"\"Recipe class containing info about name, cooking_lvl,\n ingredients, recipe_type and description\"\"\"\n return txt",
"def test_print_recipe():\n recipe = Recipe(\"Tuna pasta\", ingreds)\n assert str(recipe) == 'Recipe \"Tuna pasta\"\\n - tuna\\n - swe... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes in the initial position (X_o) of the system along with an optional set of parameters (params), and runs DDP to meet some desired state. params | def __init__(self,X_o,**params):
#------------------------------------------------>
#----------> Possible Parameter Values ---------->
#------------------------------------------------>
# Horizon - Number of timesteps into the future we wish to program
self.Horizon = params.get(... | [
"def qp_controller(current_state, desired_state, dt, dim=2):\n\n # torque PD controller values\n wheel_kp = 50.0\n wheel_kd = 10.0\n max_torque = 20.0\n\n # cost on obtaining next state and velocity\n kp = 0.0\n kd = 1.0\n\n # half state length\n hl = len(current_state) / 2\n\n mp = Ma... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
NumberOfIterations Number of times to iterate the DDP. Must be an integer. Default is 100. | def set_NumberOfIterations(self,NumberOfIterations):
self.NumberOfIterations = NumberOfIterations | [
"def getNIterations(self):\n return self.n_iterations",
"def num_passed_iterations(self) -> int:\n\n return self._num_passed_iterations",
"def getNrTimesteps():\n\n timesteps = 25\n return timesteps",
"def iterations_count(loop_node: Node):\n assert loop_node.soft_get('type') == 'Loop'\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
U_o Initial input to the system. Must be either None (meaning zero initial input to the system) or an array with shape (Horizon1,). Default is None. | def set_U_o(self,U_o):
self.U_o = U_o
if self.U_o is None:
self.U = np.zeros((self.Horizon-1,))
else:
self.U = self.U_o | [
"def populate_model(self, **kwargs):\n T = self._opts['T']\n nu = self._dims['u']\n if self._changed['T']: # first time def or change of horizon\n # make sure to delete old optimization variables if they exist\n self._removeOld()\n # define optimization variabl... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
p_target Target state for the system to reach. Must be a (2,1) numpy matrix. Default is numpy.matrix([[np.pi/2,0]]).T. | def test_p_target(self):
assert hasattr(self,'p_target'), "p_target is undefined."
assert (str(type(self.p_target))=="<class 'numpy.matrixlib.defmatrix.matrix'>"
and np.shape(self.p_target)==(2,1)), \
"p_target must be a (2,1) numpy matrix." | [
"def find_target(self):\n\n # Logic if the path was not provided\n if self.tracking == -1:\n\n #check if current target the robot has just arrived at is the goal\n if self.astar.check_for_goal(self.robot_target_node) == 1:\n arrived = 1\n\n else:\n\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Q_f Terminal cost matrix. Must be a (2,2) numpy matrix. Default is 50numpy.matrix(numpy.eye(2)). Each element should be positive. | def test_Q_f(self):
assert hasattr(self,'Q_f'), "Q_f is undefined."
assert (str(type(self.Q_f))=="<class 'numpy.matrixlib.defmatrix.matrix'>"
and np.shape(self.Q_f)==(2,2)), \
"Q_f must be a (2,2) numpy matrix. Default is 50*numpy.matrix(numpy.eye(2))." | [
"def init_Q(self):\n self.Q = np.matrix(np.tril(self.A))",
"def init_Q(self):\n self.Q = np.matrix(np.diagflat(np.diag(self.A)))",
"def constructRateMatrix(self):\n # initialize the rate matrix with proper dimension\n self.K = np.zeros((self.num_state, self.num_state), dtype=float) ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes in the state vector (x), the input vector (u) and returns the discretized and linearized state matrix, Phi. | def return_Phi(self,x,u):
# assert (str(type(x)) in ["<class 'numpy.ndarray'>"]
# and np.shape(x)==(2,)), "Error with the type and shape of x ["+ return_Phi.__name__+"()]."
# assert str(type(u)) in ["<class 'int'>",
# "<class 'float'>",
# "<class 'numpy.fl... | [
"def gate_decomposition(u_):\n assert (u_.shape == (2, 2))\n assert(is_unitary(u_))\n\n det = np.linalg.det(u_)\n delta = 0.5 * cmath.phase(det)\n p = phase(delta)\n\n u = np.linalg.inv(p) @ u_\n\n if u[0][0] == 0:\n theta = math.pi\n alpha = 2 / 1j * cmath.log(u[0][1])\n b... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Takes in the input U and the the corresponding output X, as well as dt and returns lists that contain the coefficient matrices for the quadratic expansion of the cost function (l(x,u)) for each timestep for range(len(Time)1). | def return_quadratic_cost_function_expansion_variables(self):
# returns a list of length len(Time)-1, each element with shape (1,1), where n is the number of states.
l = list(
map(
lambda x,u: u.T * self.R * u * self.dt,
self.X[:,1:].T,
... | [
"def test_quadratic_cost_function_expansion_variables(\n self,l,\n lx,lu,\n lux,lxu,\n luu,lxx):\n\n Time = self.return_time_array()\n\n # l should be a list of length len(Time)-1, with each element with shape (1,1), where n is the number of states.\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
tests the lists made by self.return_quadratic_cost_function_expansion_variables(). | def test_quadratic_cost_function_expansion_variables(
self,l,
lx,lu,
lux,lxu,
luu,lxx):
Time = self.return_time_array()
# l should be a list of length len(Time)-1, with each element with shape (1,1), where n is the number of states.
assert len(l)... | [
"def return_quadratic_cost_function_expansion_variables(self):\n # returns a list of length len(Time)-1, each element with shape (1,1), where n is the number of states.\n l = list(\n map(\n lambda x,u: u.T * self.R * u * self.dt,\n self.X[:,1:].T,\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Load initial data from Cloud Commerce Product Range data. | def create_from_range(cls, data, product_range):
data["BasePrice"] = None
data["VatRateID"] = None
data["WeightGM"] = None
data["LengthMM"] = None
data["WidthMM"] = None
data["HeightMM"] = None
data["LargeLetterCompatible"] = None
data["ExternalProductId"]... | [
"def product_range(self):\n if self._product_range is None:\n from .functions import get_range\n\n self._product_range = get_range(self.range_id)\n return self._product_range",
"def load_product(self, data_path, data, lote):\n\n bulonfer_id = self.env['res.partner'].sear... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a list of IDs for Bays in which this product is located. | def bays(self):
if self._bays is None:
self._bays = [b.id for b in CCAPI.get_bays_for_product(self.id)]
return self._bays | [
"def get_ids():",
"def get_bids(self):\n return Bid_API.Bid().get()",
"def id_list(self):\n return numpy.array(self.spiketrains.keys(), int)",
"def getAllBinIds( self, minBinId = None, maxBinId = None ):\n keys = list(self.bin2count.keys())\n if not keys: keys = ( 0, )\n ret... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the product's country of origin ID. | def country_of_origin(self):
if self._country_of_origin_id is None:
self._reload()
return self._country_of_origin_id | [
"def country(self):\n return Country(alpha_2=self.country_code)",
"def idToCountry(self, countryId):\n if 'code3' == self.cf_country_print_mode:\n return GeoIP.id_to_country_code3(countryId)\n elif 'name' == self.cf_country_print_mode:\n return GeoIP.id_to_country_name(countryId)\n else:... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the barcode of the product. | def barcode(self):
return self._barcode | [
"def barcode(self, barcode):\n CCAPI.set_product_barcode(product_id=self.id, barcode=barcode)",
"def _get_products_db_barcode(self):\n\n products = Product.objects.all() # Gets all products from database\n products_barcode = []\n\n for product in products:\n # Gets product ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set the barcode for the product. | def barcode(self, barcode):
CCAPI.set_product_barcode(product_id=self.id, barcode=barcode) | [
"def set_barcode(self, barcode):\n\n self.barcode = barcode\n self.format_barcode()",
"def barcode(self, barcode):\n if barcode is None:\n raise ValueError(\"Invalid value for `barcode`, must not be `None`\") # noqa: E501\n\n self._barcode = barcode",
"def __init__(self, ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the description of the product. | def description(self):
if self._description is None:
self._description = CCAPI.get_product(self.id).description
return self._description | [
"def getDescription(self):\n\n prod = self.productClass()\n\n if prod: result = prod.description\n else : result = None\n\n return result",
"def v_product_item_description(self) -> str:\n return self._v_product_item_description",
"def description(self, value):\n if va... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set the description of the product. | def description(self, value):
if value is None or value == "":
value = self.name
CCAPI.set_product_description(product_ids=[self.id], description=value)
self._description = value | [
"def setDescription(self, description):\n\n prod = self.productClass()\n\n if prod:\n prod.description = description",
"def set_description(description):",
"async def set_description(self, description: str):\n self.preview_embed.description = description",
"def set_description(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the handling time for the product. | def handling_time(self):
return self._handling_time | [
"def handling_time(self, handling_time):\n CCAPI.set_product_handling_time(product_id=self.id, handling_time=handling_time)\n self._handling_time = handling_time",
"def get_time(self):\n return self.event_time",
"def get_physical_time():\n return datetime.now().timestamp()",
"def _... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set the handling time for the product. | def handling_time(self, handling_time):
CCAPI.set_product_handling_time(product_id=self.id, handling_time=handling_time)
self._handling_time = handling_time | [
"def set_alarm(self, target_time: datetime.time):\n self.time = target_time.replace(second=0, microsecond=0)\n # print the time\n print(\"Alarm set for {}:{}\".format(self.time.hour, self.time.minute))",
"def handling_time(self):\n return self._handling_time",
"def set_pick_up_time(s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set the product's name. | def name(self, name):
CCAPI.set_product_name(name=name, product_ids=[self.id])
self._name = name
self.full_name = None | [
"def set_name(self, new_name):\n self.name = new_name",
"def update_prod_name(self, prod_id):\n if self.cursor:\n self.cursor.execute(\"\"\"UPDATE products SET \n prod_name = %s where prod_id = %s\"\"\",\n (self.data[\"prod_name\"], prod_id), )",
"d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the Product Options of the product. | def options(self):
if self._options is None:
self._options = productoptions.VariationOptions(self, self.product_range)
return self._options | [
"def options(self):\n pclass_options = self.get_product_class().options.all()\n return set(pclass_options) or set(self.product_options.all())",
"def getOptions(self,productTypeId):\r\n\r\n\t\turl = MozuUrl(\"/api/commerce/catalog/admin/attributedefinition/producttypes/{productTypeId}/Options\", \"GE... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set the base price for the product. | def price(self, price):
CCAPI.set_product_base_price(product_id=self.id, price=price)
self._price = price | [
"def _set_base_price(self, price=None, region=\"us\"):\n\n if price is None or price == \"\" or price == self.R_NOT_RELATIVE:\n self._base_price = None\n\n elif price == self.R_RETAIL_PRICE:\n if region == \"uk\":\n self._base_price = self._si.original_price_uk\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the Product Range to whicth this product belongs. | def product_range(self):
if self._product_range is None:
from .functions import get_range
self._product_range = get_range(self.range_id)
return self._product_range | [
"def __get_range(self):\n return self.high - self.low",
"def get_gridrange(self, start, end):\n return self._get_range(start, end, \"gridrange\")",
"def price_range(self) -> Optional[pulumi.Input['GoogleCloudRecommendationengineV1beta1ProductCatalogItemPriceRangeArgs']]:\n return pulumi.get... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the current stock level for the product. | def stock_level(self):
return self._stock_level | [
"def in_stock(self):\n return self.product.in_stock",
"def get_inventory(self):\n return self.inventory_level",
"def get_level(self):\r\n return self.__level",
"def stock_level(self, new_stock_level):\n CCAPI.update_product_stock_level(\n product_id=self.id,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Update the stock level of the product. | def stock_level(self, new_stock_level):
CCAPI.update_product_stock_level(
product_id=self.id,
new_stock_level=new_stock_level,
old_stock_level=self._stock_level,
)
self._stock_level = new_stock_level | [
"def _update_stock(self, stock):\n from MercadoLibre.services.MeradoLibreService import MercadoLibreService\n MercadoLibreService().update_stock(stock)",
"def update_stockcounter(self, stock):\n\n bg = stock.get_mw_price()\n self.update_portfolio()\n stock.counter = int(float(se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the pending stock level of the product. | def get_pending_stock(self):
return CCAPI.get_pending_stock(self.id) | [
"def in_stock(self):\n return self.product.in_stock",
"def available_stock(self):\n return self.total_stock - self.unreturned_stock",
"def excess_stock(self, product):\n return max(int(self.inventory[product][0] - self.goal[product]), 0)",
"def stock_state(self) -> Optional[pulumi.Input['... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set the supplier of the product. Remove all Factory Links and create a new Factory Link to the Factory named factory_name. Set Product Option Supplier to factory name. | def supplier(self, factory_name):
if not isinstance(factory_name, Factory):
factories = CCAPI.get_factories()
if factory_name in factories.names:
factory = factories.names[factory_name]
else:
raise exceptions.FactoryDoesNotExist(factory_name)
... | [
"def test_update_supplier_with_no_name(self):\n test_supplier = self._create_suppliers(1)[0]\n test_supplier.name = None\n resp = self.app.put('/suppliers/{}'.format(test_supplier.id),\n json=test_supplier.serialize(), content_type='application/json')\n self.as... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Block for upsampling, concat and conv in UNet | def __init__(self, in_ch, out_ch, dropout_rate=0, learnable_upsample=True):
super(UpBlock, self).__init__()
# TODO: would be a nice idea if the upsampling could be learned too,
if learnable_upsample:
self.up = nn.ConvTranspose2d(in_ch // 2, in_ch // 2, 2, stride=2)
else:
... | [
"def upconv_block(\n inputs: tf.keras.layers.Layer, skip: tf.keras.layers.Layer\n) -> tf.keras.layers.Layer:\n x = inputs\n x = tf.keras.layers.UpSampling2D()(x)\n x = tf.keras.layers.Concatenate()([skip, x])\n\n return x",
"def upsample(self, img, result=...) -> result:\n ...",
"def initi... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Searches the src directory for all 'slugs' that should be translated by looking for matches of the pattern t("string") | def find_translation_slugs():
slugs = {}
for (dirpath, _, filenames) in walk(SRC_DIR):
for filename in filenames:
if not filename.endswith(".py"):
continue
with open(join(dirpath, filename), "r") as src_file:
contents = src_file.read()
... | [
"def _get_all_source_strings(resources, *args, **kwargs):\r\n return Translation.objects.source_strings(resources)",
"def find_strings(self) -> List[LocalizedString]:\n raise NotImplementedError()",
"def test_translate_locations(self):\n # Check that translatables can be loaded from the dialog ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Validates all translation files, checking for missing and unnecessary translations | def validate_translation_files():
passed = True
slugs = find_translation_slugs()
translation_filenames = [
f
for f in listdir(TRANSLATION_FILES_DIR)
if isfile(join(TRANSLATION_FILES_DIR, f))
]
for translation_filename in translation_filenames:
print("Validating %s..."... | [
"def check_properties_files():\n for lang_code in LANG_CODES:\n print \"======================\"\n print lang_code\n print \"======================\"\n translationPropertiesFile = get_properties_file_path(lang_code)\n englishPropertiesFile = get_properties_file_path(None)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Bakes all translations into a translations.py file inside the krux namespace | def bake_translations():
translation_table = {}
translation_filenames = [
f
for f in listdir(TRANSLATION_FILES_DIR)
if isfile(join(TRANSLATION_FILES_DIR, f))
]
for translation_filename in translation_filenames:
with open(
join(TRANSLATION_FILES_DIR, translatio... | [
"def test_translate_locations(self):\n # Check that translatables can be loaded from the dialog directory\n s = SimpleSkill1()\n s.root_dir = abspath(join(dirname(__file__),\n 'translate', 'in-dialog/'))\n lst = s.translate_list('good_things')\n se... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Creates a new translation file for the given locale with stubbedout translations | def create_translation_file(locale):
translations = {}
slugs = find_translation_slugs()
for slug in slugs:
translations[slug.replace("\\n", "\n")] = ""
with open(join(TRANSLATION_FILES_DIR, "%s.json" % locale), "w") as translation_file:
translation_file.write(
json.dumps(tran... | [
"def bake_translations():\n translation_table = {}\n translation_filenames = [\n f\n for f in listdir(TRANSLATION_FILES_DIR)\n if isfile(join(TRANSLATION_FILES_DIR, f))\n ]\n for translation_filename in translation_filenames:\n with open(\n join(TRANSLATION_FILES_D... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Sorts and prettyprints all translation files | def prettify_translation_files():
translation_filenames = [
f
for f in listdir(TRANSLATION_FILES_DIR)
if isfile(join(TRANSLATION_FILES_DIR, f))
]
for translation_filename in translation_filenames:
translations = {}
with open(
join(TRANSLATION_FILES_DIR, tr... | [
"def main():\n file = open_file()\n word_list = format_file(file)\n new_list = add_to_list(word_list)\n sorted_list = msort(new_list)\n print_words(sorted_list)",
"def sort(self):\n self.treeview.delete(*self.treeview.get_children())\n output_root = self.output_path.get() + '/'\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initialize the class using parameters e.g. which data from SNLI should be stored. SNLI also needs buckets These are initialized by default if not specified. | def __init__(self,label_dict, data_params=None, bucket_params=None, embeddings=None):
super(SNLIData, self).__init__('SNLI', embeddings)
# Default parameters to be called from SNLI
if data_params is None or len(data_params) == 0:
self.data_params = {
"annotator_lab... | [
"def __init__(self):\n # Empty subsystem data\n self._subsystems = [] # Remember order\n self._subsysdict = {} # Convenient access (want a sorteddict)\n\n # Initialise own parameters, variables with no kwargs\n super(SODENetwork, self).__init__()",
"def __init__(self, init_size=... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
stores the data points in the designated buckets and stores meta data a bucket is defined by the maximum length of sentence1 and sentence2 respectively | def bucketize_data(self, data_set, initialize):
PAD_position = self.embeddings.get_pad_pos(initialize=True)
bucket_name = data_set + "_buckets"
if bucket_name in self.data_sets:
return None
# dictionary in which the data of the different buckets will be stored
bu... | [
"def perform_bucketing(opt, labeled_pair_list):\n # Obtain sentence lengths\n sentence_pair_lens = [(len(pair[0].split()), len(pair[1].split())) for pair in labeled_pair_list[0]]\n\n # Calculate bucket size\n buckets = [[0, 0] for _ in range(opt.num_buckets)]\n avg_bucket = len(labeled_pair_list[0]) ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Modify user input. Make sure the user's email is all lowercase. Create a slug for the user. | def save(self, *args, **kwargs):
self.email = self.email.lower()
self.slug = slugify(self.username, allow_unicode=True)
super().save(*args, **kwargs) | [
"def test_new_user_email_normalize(self):\n email = 'test1@gmail.com'\n user = get_user_model().objects.create_user(email, 'test123')\n\n self.assertEqual(user.email, email.lower())",
"def test_create_user_email_normalized(self):\n email = 'test1@ASDSS.com'\n user = sample_user(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Transmit a single temperature to heatseeknyc.com. | def transmit_temperature(temperature):
common.add_temperature(temperature)
reading = dict(sensor_name=temperature['cell_id'],
temp=temperature['temperature'],
humidity=temperature['humidity'],
time=temperature['hub_time'].timestamp(),
v... | [
"def sendMQTTData(temperature, humidity):\n timestamp = time.strftime(\"%Y-%m-%dT%H:%M:%SZ\", time.gmtime(time.time()))\n payload = (\"\"\"\n {\n \"deviceID\" : \"WeatherMap\",\n \"Data\" :{\n \"Temperature\" : {\n \"data\": \"%s\",\n \... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Continually transmit temperatures from database to heatseeknyc.com. | def transmit():
database = common.get_db()
while True:
with database:
fetch_after = datetime.datetime.now() - datetime.timedelta(days=365)
cursor = database.cursor()
cursor.execute('select temperatures.id, cell_id, adc, temperature, hub_time, version, humidity'
... | [
"def transmit_temperature(temperature):\n common.add_temperature(temperature)\n reading = dict(sensor_name=temperature['cell_id'],\n temp=temperature['temperature'],\n humidity=temperature['humidity'],\n time=temperature['hub_time'].timestamp(),\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Asynchronous coroutine to fetch the HostedNumberOrderInstance | async def fetch_async(self) -> "HostedNumberOrderInstance":
return await self._proxy.fetch_async() | [
"async def fetch_async(self) -> \"BuildInstance\":\n return await self._proxy.fetch_async()",
"async def fetch_async(self) -> \"FactorInstance\":\n return await self._proxy.fetch_async()",
"async def fetch_async(self) -> \"AccountInstance\":\n return await self._proxy.fetch_async()",
"asy... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Asynchronous coroutine to fetch the HostedNumberOrderInstance | async def fetch_async(self) -> HostedNumberOrderInstance:
payload = await self._version.fetch_async(
method="GET",
uri=self._uri,
)
return HostedNumberOrderInstance(
self._version,
payload,
sid=self._solution["sid"],
) | [
"async def fetch_async(self) -> \"BuildInstance\":\n return await self._proxy.fetch_async()",
"async def fetch_async(self) -> \"FactorInstance\":\n return await self._proxy.fetch_async()",
"async def fetch_async(self) -> \"AccountInstance\":\n return await self._proxy.fetch_async()",
"asy... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Build an instance of HostedNumberOrderInstance | def get_instance(self, payload: Dict[str, Any]) -> HostedNumberOrderInstance:
return HostedNumberOrderInstance(self._version, payload) | [
"def __new__(cls, *args, **kwargs):\n return BuiltInClass.get_instance(cls, 'FIXNUM', *args)",
"def __new__(cls, *args, **kwargs):\n return BuiltInClass.get_instance(cls, 'NUMBER', True)",
"def shopify_create_order_queue(self, instance, created_by=\"import\"):\n order_queue_vals = {\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Streams HostedNumberOrderInstance records from the API as a generator stream. This operation lazily loads records as efficiently as possible until the limit is reached. The results are returned as a generator, so this operation is memory efficient. | def stream(
self,
status: Union["HostedNumberOrderInstance.Status", object] = values.unset,
phone_number: Union[str, object] = values.unset,
incoming_phone_number_sid: Union[str, object] = values.unset,
friendly_name: Union[str, object] = values.unset,
unique_name: Union[... | [
"async def stream_async(\n self,\n status: Union[\"HostedNumberOrderInstance.Status\", object] = values.unset,\n phone_number: Union[str, object] = values.unset,\n incoming_phone_number_sid: Union[str, object] = values.unset,\n friendly_name: Union[str, object] = values.unset,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Asynchronously streams HostedNumberOrderInstance records from the API as a generator stream. This operation lazily loads records as efficiently as possible until the limit is reached. The results are returned as a generator, so this operation is memory efficient. | async def stream_async(
self,
status: Union["HostedNumberOrderInstance.Status", object] = values.unset,
phone_number: Union[str, object] = values.unset,
incoming_phone_number_sid: Union[str, object] = values.unset,
friendly_name: Union[str, object] = values.unset,
unique_... | [
"async def list_async(\n self,\n status: Union[\"HostedNumberOrderInstance.Status\", object] = values.unset,\n phone_number: Union[str, object] = values.unset,\n incoming_phone_number_sid: Union[str, object] = values.unset,\n friendly_name: Union[str, object] = values.unset,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Asynchronously lists HostedNumberOrderInstance records from the API as a list. Unlike stream(), this operation is eager and will load `limit` records into memory before returning. | async def list_async(
self,
status: Union["HostedNumberOrderInstance.Status", object] = values.unset,
phone_number: Union[str, object] = values.unset,
incoming_phone_number_sid: Union[str, object] = values.unset,
friendly_name: Union[str, object] = values.unset,
unique_na... | [
"async def list_async(\n self,\n limit: Optional[int] = None,\n page_size: Optional[int] = None,\n ) -> List[FactorInstance]:\n return [\n record\n async for record in await self.stream_async(\n limit=limit,\n page_size=page_size,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieve a specific page of HostedNumberOrderInstance records from the API. Request is executed immediately | def get_page(self, target_url: str) -> HostedNumberOrderPage:
response = self._version.domain.twilio.request("GET", target_url)
return HostedNumberOrderPage(self._version, response) | [
"def get_object(self):\n return get_object_or_404(Order, number=self.kwargs['order_number'])",
"def stream(\n self,\n status: Union[\"HostedNumberOrderInstance.Status\", object] = values.unset,\n phone_number: Union[str, object] = values.unset,\n incoming_phone_number_sid: Union... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
r"""Forces a Failover for a regional cluster. Failover promotes the HA standby instance in the regional cluster. | def Failover(self, request, global_params=None):
config = self.GetMethodConfig('Failover')
return self._RunMethod(
config, request, global_params=global_params) | [
"def FailoverInstance(opts, args):\n cl = GetClient()\n instance_name = args[0]\n ignore_consistency = opts.ignore_consistency\n force = opts.force\n iallocator = opts.iallocator\n target_node = opts.dst_node\n\n if iallocator and target_node:\n raise errors.OpPrereqError(\"Specify either an iallocator (-... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
View which gets the link for the given shortcut value and redirects to it. | def follow(request, shortcut, params=None):
try:
link = Link.objects.get(shortcut=shortcut)
link.usage_count += 1
link.save()
user = request.user
if user.is_anonymous():
user = None
Click.objects.create(
link=link,
user=user,
... | [
"def info(request, shortcut):\n link = get_object_or_404(Link, shortcut=shortcut)\n values = default_values(request)\n values['link'] = link\n return render_to_response(\n 'shortener/link_info.html',\n values,\n context_instance=RequestContext(request))",
"def redirect_to_url(requ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
View which shows information on a particular link | def info(request, shortcut):
link = get_object_or_404(Link, shortcut=shortcut)
values = default_values(request)
values['link'] = link
return render_to_response(
'shortener/link_info.html',
values,
context_instance=RequestContext(request)) | [
"def get_show_url(self, name):",
"def Info(request):\n return render_to_response('radabo/info.html', {})",
"def get_link_info(link_id: int, db: Session = Depends(get_db)):\n link = db.query(Link).where(Link.id == link_id).first()\n if not link:\n raise HTTPException(404, detail='Link not found.'... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return true if user is allowed to submit URLs | def is_allowed_to_submit(request):
return not settings.REQUIRE_LOGIN or request.user.is_authenticated() | [
"def url_allowed(self, url):\n return get_netloc(url) in self.root_hosts",
"def can_create_url(self):\n return (self.allowed_postfixes is not None)",
"def legal_url(self, url_name):\n if users.is_current_user_admin():\n return True\n if (self.active_permissions_vault == No... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Decides the computation shape based on the split_size. | def ComputationShape(split_size):
assert (split_size in SUPPORTED_SPLIT_SIZE), ('Model parallelism with %d',
'devices is currently not'
' supported.' % split_size)
return SUPPORTED_SPLIT_SIZE[split_size] | [
"def split_shape(self):\n return self.__split_shape",
"def calculate_split_by_split_size(self):\n self.set_split_extents_by_split_size()\n return self.calculate_split_from_extents()",
"def compute_splits(var_shape, block_size):\n splits = []\n split_sizes = []\n for i, d in enumerate(var... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Computes the overall step rate and adds a summary. | def _RecordStepRate(self, current_steps, total_examples):
self._time_steps.append((time.time(), current_steps, total_examples))
# Keeps a relative long history to compute a smooth steps/second.
# Removes duplicate stats for step = 0 to get rid of the warm-up period.
while (self._time_steps[-1][1] - self... | [
"def get_total(self, time_step: int) -> Decimal:\n return self.rate * self.get_rounded_hours(time_step)",
"def _report_step(self, learning_rate, step, train_stats=None,\n valid_stats=None, attns=None):\n if self.report_manager is not None:\n return self.report_manager.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Process all perexample tensor outfeed data for a TPU sess.run. | def _OutfeedDequeueLoop(self, per_example_tensors, num_loops, num_devices):
if not per_example_tensors:
return tf.no_op()
tensor_shapes = [
py_utils.GetShape(per_example_tensors[key])
for key in sorted(per_example_tensors)
]
tensor_types = [
tf.as_dtype(per_example_tensors... | [
"def produce(self, dataset, batch, output_tensors):\n\n # Fill feed dict\n feed_dict = self.fill_feed_dict(batch)\n\n # Run one step of the model\n output_values = self.sess.run(output_tensors, feed_dict=feed_dict)\n\n return output_values",
"def run(\n self,\n fet... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Retrieve the checkpoint id for the decoder out file. Finds the checkpoint id in the checkpoint file name and compares to global step. If they diverge, uses the retrieved id and prints a warning. | def _GetCheckpointIdForDecodeOut(checkpoint_path, global_step):
ckpt_id_from_file = int(re.sub(r'.*ckpt-', '', checkpoint_path))
tf.logging.info('Loaded checkpoint is at global step: %d', global_step)
tf.logging.info('Checkpoint path: %s', checkpoint_path)
tf.logging.info('Checkpoint id according to checkpoint ... | [
"def get_checkpoint():\n if FLAGS.checkpoint:\n checkpoint = os.path.join(FLAGS.model_dir, FLAGS.checkpoint)\n else:\n checkpoint = tf.train.latest_checkpoint(FLAGS.model_dir)\n # TODO(petershaw): Consider less hacky way to get current step.\n step = None\n if checkpoint is not None:\n step = int(chec... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Gets the path to decode out file. | def GetDecodeOutPath(cls, decoder_dir, checkpoint_id):
out_dir = cls._GetTtlDir(decoder_dir, duration='7d')
return os.path.join(out_dir, 'decoder_out_%09d' % checkpoint_id) | [
"def file_path(self) -> str:\n return self.files[self.__main['location']['file']]",
"def GetCodegenFile(self):\n\t\tif os.path.isabs(self.FilePath):\n\t\t\tRelativePath = self.FilePath[3:]\n\t\t\treturn \"%s\\\\%s.codegen.inl\" % (ExportPath, RelativePath)\n\t\telse:\n\t\t\treturn \"%s\\\\%s.codegen.inl\" ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Decodes `samples_per_summary` examples using `checkpoint_path`. | def DecodeCheckpoint(self, sess, checkpoint_path):
p = self._model_task.params
samples_per_summary = p.eval.decoder_samples_per_summary
if not samples_per_summary:
samples_per_summary = p.eval.samples_per_summary
self._LoadCheckpointForEval(sess, checkpoint_path)
global_step = sess.run(py_uti... | [
"def load_example_data():\n from pkg_resources import resource_stream\n data = np.load(resource_stream(__name__, 'example_data/CCF1.npy'))\n return data",
"def read_make_examples_run_info(path):\n with tf.gfile.GFile(path) as f:\n return text_format.Parse(f.read(), deepvariant_pb2.MakeExamplesRunInfo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Runs decoder on the latest checkpoint. | def DecodeLatestCheckpoint(self, last_path=None):
with tf.container(self._container_id), self._GetSession() as sess:
# This initializes local tables
sess.run(self.initialize_tables)
# This initializes local variables.
sess.run(self._initialize_local_vars)
path = tf.train.latest_checkpo... | [
"def DecodeCheckpoint(self, sess, checkpoint_path):\n p = self._model_task.params\n samples_per_summary = p.eval.decoder_samples_per_summary\n if not samples_per_summary:\n samples_per_summary = p.eval.samples_per_summary\n self._LoadCheckpointForEval(sess, checkpoint_path)\n\n global_step = ses... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns params for job `job_name` on the dataset `dataset_name`. | def GetParamsForDataset(self, job_name, dataset_name):
# Get the current cluster and update its params from flags.
cluster = cluster_factory.Current()
self.UpdateClusterParamsFromFlags(cluster.params, job_name)
with cluster_factory.Cluster(cluster.params):
try:
cfg = self.model_registry.Ge... | [
"def job_attributes(self) -> Dict[str, str]:\n params: Dict[str, str] = {\n \"esi_job_name\": self.name,\n \"esi_job_id_\": self.id_,\n \"esi_job_op_id\": self.op_id,\n \"esi_job_max_attempts\": str(self.max_attempts),\n \"esi_job_uid\": str(self.uid),\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
If given a `FLAGS.cluster_spec`, update flags for running distributed. | def MaybeConfigRunDistributed(self):
if not FLAGS.cluster_spec:
return
job_specs = FLAGS.cluster_spec.split('@')
cluster_spec_dict = {}
for job_spec in job_specs:
# ps_host=worker1:1231,worker2:1234
job_machines = job_spec.split('=')
if len(job_machines) != 2:
raise Value... | [
"def UpdateClusterParamsFromFlags(self, cluster, job_name):\n cluster.mode = FLAGS.mode\n cluster.job = job_name\n cluster.task = FLAGS.task\n\n cluster.controller.name = FLAGS.controller_job\n cluster.controller.gpus_per_replica = FLAGS.controller_gpus\n\n cluster.worker.name = FLAGS.worker_job\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Update `cluster` with a training cluster configuration from flags. | def UpdateClusterParamsFromFlags(self, cluster, job_name):
cluster.mode = FLAGS.mode
cluster.job = job_name
cluster.task = FLAGS.task
cluster.controller.name = FLAGS.controller_job
cluster.controller.gpus_per_replica = FLAGS.controller_gpus
cluster.worker.name = FLAGS.worker_job
cluster.wo... | [
"def cmd_node_update_cluster(self, args):\n node_id = args[0]\n cluster_id = args[1]\n data = {'cluster_id': cluster_id}\n self._update_obj(node_id, 'node', data)",
"def cluster_updated(configuration, cluster_state):",
"def update_cluster(self, cluster_id, values):",
"def modify_cl... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Runs `runners` in parallel threads. Returns when all of them finish. | def StartRunners(self, runners):
threads = []
tf.logging.info('Starting runners')
for runner in runners:
t = threading.Thread(target=runner.Start)
t.daemon = True
t.start()
threads.append(t)
tf.logging.info('Total num runner.enqueue_ops: %d',
len(runner.en... | [
"def do_parallel(runs, func, use_threads):\n if use_threads:\n executor = concurrent.futures.ThreadPoolExecutor(max_workers=MAX_TH_DEG)\n else:\n executor = concurrent.futures.ProcessPoolExecutor(max_workers=MAX_PR_DEG)\n\n done = []\n\n first = runs[0]\n is_iterable = isinstance(first,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generates the inference graphs for a given model. | def WriteInferenceGraph(self):
inference_graph_dir = os.path.join(FLAGS.logdir, 'inference_graphs')
tf.gfile.MakeDirs(inference_graph_dir)
tf.logging.info('Writing inference graphs to dir: %s', inference_graph_dir)
cfg = self.model_registry.GetParams(self._model_name, 'Test')
if (issubclass(cfg.cls... | [
"def infer_model():\n # Setup training/testing environment\n setup_env()\n # Construct the model\n model = setup_model()\n # Load model weights\n cp.load_checkpoint(cfg.TEST.WEIGHTS, model)\n logger.info(\"Loaded model weights from: {}\".format(cfg.TEST.WEIGHTS))\n # Create data loaders and ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns a list starting with the given context's parent followed by each of its parents till we reach the object. | def getParentsFromContextToObject(context, obj):
if sameProxiedObjects(context, obj):
return []
parents = []
w = context
while 1:
w = w.__parent__
if sameProxiedObjects(w, obj):
parents.append(w)
break
if w is None:
break
par... | [
"def walk_parents(self):\n active = self.parent_datasets[:]\n while active:\n d = active.pop()\n yield d\n active += d.parent_datasets",
"def get_parents(self):\n return []",
"def iter_parents(content: IResource) -> typing.Iterator[IResource]:\n content =... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Function to perform ondevice parallel ROT13 encrypt/decrypt by explicitly allocating device memory for host variables using gpuarray. Returns | def devCipher(self, sentence):
# create Event
start = cuda.Event()
end = cuda.Event()
# Get kernel function
func = self.mod.get_function("rot13")
# Device memory allocation for input and output array(s)
mem_size=len(sentence)*4
decrypted=np... | [
"def random_cipher():\n return np.random.permutation(26)",
"def _aes_encrypt_permutation(p):\n key_length = 24 # 192 Bit key size\n IV_LENGTH = 16\n BLOCK_SIZE = 16\n key = Random.get_random_bytes(key_length)\n iv = Random.get_random_bytes(IV_LENGTH)\n aes_obj = AES.n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Set or update the parent of this node. Set parent to `None` to remove this node's parent. | def setParent(self, parent):
# Don't allow a node to set its parent as one of its children!
if (parent in self.unorderedChildren):
logging.error("Node.setParent: cannot set a node's child to be its own parent! node = {}; parent = {}"
.format(self.name, pare... | [
"def set_parent(self, parent: 'Node'):\n if parent == self.parent:\n return\n self.parent = parent\n if parent is not None:\n self.parent.add_child(self)",
"def set_parent(self, parent_node):\n self.parent = parent_node",
"def setParent(self, parent):\n a... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Print the names of the children this node has | def printChildren(self):
print("Printing {}'s children:".format(self.name))
if (len(self.orderedChildren) != 0):
for child in self.orderedChildren:
print(child.name)
else:
# no children
print("NONE") | [
"def printChildren(self):\n for node in self.allNodes:\n node.printChildren()",
"def child_names(self) -> List[str]:\n return [t.name for t in self.children]",
"def _pprint_children(self):\n return self.children",
"def get_children_names(self):\n children_names = self._s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Print the names of all of the children of each node in this tree | def printChildren(self):
for node in self.allNodes:
node.printChildren() | [
"def printChildren(self):\n\n print(\"Printing {}'s children:\".format(self.name))\n if (len(self.orderedChildren) != 0):\n for child in self.orderedChildren:\n print(child.name)\n else:\n # no children\n print(\"NONE\")",
"def child_names(self)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Graphically print the tree | def printTree(self):
pass | [
"def print_tree(self, tabwidth=0):\n\n # if teststr == \"silent\":\n print(tabwidth * \" \", self.ele, '*' if self.mark else '', sep=\"\")\n\n \"\"\" Debugging purposes\n elif teststr == \"loud\":\n print(tabwidth*\" \", end = \" \")\n show((self.ele, id(self)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method to emit a timing message to the log(s) | def timing(message):
# get the appropriate logger
logger = AdmitLogging.findLogger()
if logger is None:
return
logger.log(AdmitLogging.TIMING, message) | [
"def time_block(self, message):\n tic = time.time()\n yield\n dt = time.time() - tic\n log = app_log.info if dt > 1 else app_log.debug\n log(\"%s in %.2f ms\", message, 1e3 * dt)",
"def use_time_writer(time_writer, msg):\n if not time_writer:\n print(msg)\n else:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method to emit a regression message to the log(s) It is suggested to start the message with a magic word followed by a colon, so top level scripts can reliably parse them. It is typically not needed to add verbosely what these numbers are, just the numbers are fine, the associated label defines them | def regression(message):
# get the appropriate logger
logger = AdmitLogging.findLogger()
if logger is None:
return
logger.log(AdmitLogging.REGRESSION, message) | [
"def print_logregress(ds, logys, yname=\"y\"):\n m, b, r, p, se = linregress(ds, logys)\n print(\"\\nlog({_coconut_format_0}) = {_coconut_format_1} d + {_coconut_format_2}\\t(r**2 = {_coconut_format_3})\".format(_coconut_format_0=(yname), _coconut_format_1=(m), _coconut_format_2=(b), _coconut_format_3=(r**2))... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method to get the appropriate logger. This is done by inspecting the stack, looking for either Admit.py or AT.py, both of which have the name of their loggers. | def findLogger():
aclass = None
for i in stack():
# look for either AT.py or Admit.py in the stack
if "Admit.py" in i[1] or "AT.py" in i[1]:
# when found, get the class instance
for k in getargvalues(i[0]).locals.keys():
if 'sel... | [
"def logger(self) -> logging.Logger:\n if self._logger is None:\n name = '.'.join([\n self._callerType.__module__,\n self._callerType.__name__\n ])\n logger = logging.getLogger(name)\n logger = self.configureLogger(logger)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Method to emit a subheader message to the log(s). Subheader messages are encapsulated in an empty line for emphasis | def subheading(message):
# get the appropriate logger
logger = AdmitLogging.findLogger()
if logger is None:
return
logger.info("")
logger.info(" " + message)
logger.info("") | [
"def draw_header(self, stream, header):\n stream.writeln(header)\n stream.writeln('~' * len(header))\n stream.writeln()",
"def print_header(message: str, level: int = 2) -> None:\n prefix = \"#\" * level\n display(Markdown(f\"{prefix} {message}\"))",
"def generate_header():\n trace... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculate weights for a low pass Lanczos filter. | def low_pass_weights(window, cutoff):
order = ((window - 1) // 2 ) + 1
nwts = 2 * order + 1
w = np.zeros([nwts])
n = nwts // 2
w[n] = 2 * cutoff
k = np.arange(1., n)
sigma = np.sin(np.pi * k / n) * n / (np.pi * k)
firstfactor = np.sin(2. * np.pi * cutoff * k) / (np.pi * k)
w[n-1:0:-1... | [
"def weights(self) :\n\t\treturn sign(self.L) #1/(self.L + 0.00001) ",
"def wwl(X, node_features=None, num_iterations=3, sinkhorn=False, gamma=None):\n D_W = pairwise_wasserstein_distance(X, node_features = node_features, \n num_iterations=num_iterations, sinkhorn=sinkhorn)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
gets the model file name | def _get_model_filename(self) -> str:
model_filename = f'{self.model_dir}/{self.description}.{self._get_model_file_extension()}'
return model_filename | [
"def _get_model_name_from_file(path: str):\n return os.path.basename(path).split(\".\")[0]",
"def _get_model_name(self):\n sysinfo = SystemInfo()\n model_name = sysinfo.get_model_name()\n return model_name",
"def get_model_filename(model_dir: str) -> str:\n return os.path.join(mod... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
run fit on model | def _fit_model(self):
pass | [
"def test_fit(self):\n self._fit()",
"def fit_model(self, data, batch_size, epochs, **kwargs):\n return None",
"def fit(self, X):",
"def fit_model(self):\n yy, xx = np.indices(self.data.shape)\n xdata_tuple = (xx, yy)\n # return model\n return self.model(xdata_tuple, ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |