query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Add song to the storage directory and to the database. Return ID of the new song / error message.
def add_song(self): path = input("Give file path:\t") # Request file path path = path.replace('\\', '/') if self.path_song_re.match(path) and not self.path_storage_re.match( path): # Check that the path leads to a song that is not already found in Storage copy(...
[ "def add_song():\n song_to_playlist(PLAYLIST_FOLDER, request.form['Song'], request.form['PlayLID'])\n return jsonify(result=str(request.form['PlayLID']))", "def add_song(song):\n try:\n c = connection.cursor()\n c.execute(\"\"\"INSERT INTO DMC_SONG_LIST(id, title, game, category, url) value...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove song from database and from the storage directory based on ID
def delete_song(self): song_id = tuple(input("Give the melody id to be deleted:\t")) sql = "SELECT file_title, form FROM songs WHERE id = %s" # Check existence of song with given ID self.cursor.execute(sql, song_id) result = self.cursor.fetchall() if len(result) > 0: ...
[ "def delete_song(_id):\r\n Song.query.filter_by(id=_id).delete()\r\n # filter song by id and delete\r\n db.session.commit() # commiting the new change to our database\r", "def delete_song(database, song_name: str):\n delere = False\n deleted = None\n song_id = song_name_to_ID(song_n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Modifies song info in the database
def modify_data(self): song_id = tuple(input("Give the id of the song to be modified:\t")) # Request song ID sql = "SELECT song_title, artist, data, tag FROM songs WHERE id = %s" # Find song with given ID self.cursor.execute(sql, song_id) res = self.cursor.fetchall() if le...
[ "def update_db(self):\n songs = self.db.get_all_songs()\n for song in songs:\n if choose_song(song) == ERROR:\n self.db.delete_song(song)\n files = []\n for song in glob.glob(\"songs\\*.wav\"):\n to_append = song.split('\\\\')[ONE][:-4]\n f...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a Batch from an existing batch id. Notes
def from_batch_id(batch_id: int, *args, **kwargs): b = Batch(*args, **kwargs) assert isinstance(b._backend, _backend.ServiceBackend) b._batch_handle = b._backend._batch_client.get_batch(batch_id) return b
[ "def create_batch_prediction(BatchPredictionId=None, BatchPredictionName=None, MLModelId=None, BatchPredictionDataSourceId=None, OutputUri=None):\n pass", "def create_batch(self, batch_index, *args, **kwargs):\n batch = self.dataset.create_batch(batch_index, *args, **kwargs)\n batch_res = self._e...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a new input resource file object representing a single file.
def read_input(self, path: str) -> _resource.InputResourceFile: irf = self._new_input_resource_file(path) return irf
[ "def addinputfile(self, project, inputtemplate, sourcefile, **kwargs):\n if isinstance( inputtemplate, str) or (sys.version < '3' and isinstance( inputtemplate, unicode)): #pylint: disable=undefined-variable\n data = self.get(project) #causes an extra query to server\n inputtemplate = d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a new resource group representing a mapping of identifier to input resource files.
def read_input_group(self, **kwargs: str) -> _resource.ResourceGroup: root = secret_alnum_string(5) new_resources = {name: self._new_input_resource_file(file, root) for name, file in kwargs.items()} rg = _resource.ResourceGroup(None, root, **new_resources) self._resource_map.update({rg....
[ "def declare_resource_group(self, **mappings: Dict[str, Any]) -> 'BashJob':\n\n for name, d in mappings.items():\n assert name not in self._resources\n if not isinstance(d, dict):\n raise BatchException(f\"value for name '{name}' is not a dict. Found '{type(d)}' instead.\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Write resource file or resource file group to an output destination. Examples
def write_output(self, resource: _resource.Resource, dest: str): if not isinstance(resource, _resource.Resource): raise BatchException(f"'write_output' only accepts Resource inputs. Found '{type(resource)}'.") if (isinstance(resource, _resource.JobResourceFile) and isinstanc...
[ "def write_resources(self, resources):\n for filename, data in list(resources.get('outputs', {}).items()):\n # Determine where to write the file to\n dest = os.path.join(self.output_dir, filename)\n path = os.path.dirname(dest)\n if path and not os.path.isdir(path)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Select all jobs in the batch whose name matches `pattern`. Examples
def select_jobs(self, pattern: str) -> List[job.Job]: return [job for job in self._jobs if job.name is not None and re.match(pattern, job.name) is not None]
[ "def filter_by_name(self, pattern):\n return [t for t in self if pattern in t.name]", "def filter_jobs(jobs, keyword):\n for job in jobs:\n if keyword == \"all\":\n yield job\n elif job[\"name\"].find(keyword) != -1:\n yield job", "def get_build_name_by_pattern(self...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Initializes querysets for keyword and headlinekeyword
def __init__(self): self.keyword_queryset = Keyword.objects.all() self.headlinekeyword_queryset = Headlinekeyword.objects.all() self.headline_queryset = Headline.objects.all()
[ "def keyword_headlines(self):\r\n\t\td = {}\r\n\r\n\t\tfor q in self.keyword_queryset:\r\n\t\t\td[q.content] = self.headlinekeyword_queryset.filter(keywordid = q.id)\r\n\r\n\t\treturn d", "def setup_eager_loading(cls, queryset):\n queryset = queryset.prefetch_related('keywords_str')\n queryset = que...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a dictionary of the keywords and the list of corresponding headlines (ids only)
def keyword_headlines(self): d = {} for q in self.keyword_queryset: d[q.content] = self.headlinekeyword_queryset.filter(keywordid = q.id) return d
[ "def get_keywords(self):\r\n\t\treturn list(self.keyword_headlines().keys())", "def get_headlines_with_keyword(self, kw):\r\n\t\tkey_head = self.keyword_headlines()\r\n\r\n\t\theadlines = set()\r\n\r\n\t\tfor headlinekw in key_head[kw]:\r\n\t\t\tcontent = headlinekw.headlineid.content\r\n\t\t\theadlines.add(conte...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a list of keywords
def get_keywords(self): return list(self.keyword_headlines().keys())
[ "def get_keyword_list(self):\n return self.keywords", "def get_keyword_list(self):\n return self.__keyword_list", "def keywords(self):\n return self._keywords", "def extract_keywords(self):\n keywords = [] \n for keyword in self.watsonLanguageModel['keywords'][:self.entitySi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a list of headlines if given a keyword
def get_headlines(self, kw = None): if kw: return self.get_headlines_with_keyword(kw) else: return self.get_all_headlines()
[ "def get_headlines_with_keyword(self, kw):\r\n\t\tkey_head = self.keyword_headlines()\r\n\r\n\t\theadlines = set()\r\n\r\n\t\tfor headlinekw in key_head[kw]:\r\n\t\t\tcontent = headlinekw.headlineid.content\r\n\t\t\theadlines.add(content)\r\n\r\n\t\treturn list(headlines)", "def keyword_headlines(self):\r\n\t\td ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a list of the headlines with the corresponding keyword
def get_headlines_with_keyword(self, kw): key_head = self.keyword_headlines() headlines = set() for headlinekw in key_head[kw]: content = headlinekw.headlineid.content headlines.add(content) return list(headlines)
[ "def get_headlines(self, kw = None):\r\n\t\tif kw:\r\n\t\t\treturn self.get_headlines_with_keyword(kw)\r\n\t\telse:\r\n\t\t\treturn self.get_all_headlines()", "def keyword_headlines(self):\r\n\t\td = {}\r\n\r\n\t\tfor q in self.keyword_queryset:\r\n\t\t\td[q.content] = self.headlinekeyword_queryset.filter(keyword...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate the min number of refills to reach 'distance'. You start with a full tank.
def compute_min_refills(distance: int, tank: int, stops: List[int]): location: int = 0 n_stops = 0 last_stop = 0 max_drive = location + tank while max_drive < distance: counter = 0 # Handle the case that stops are depleted before we reach distance if len(stops) == 0: ...
[ "def compute_min_refills(distance: int, tank: int, stops: list):\n previous, current = 0, 0\n positions = [0] + stops + [distance]\n\n num_refills, cur_position = 0, 0\n\n while current <= len(stops):\n previous = current\n\n while current <= len(stops) and (\n positions[cur...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Place the vertex v at position, and apply transformation T. Return the grid points that are occupied by the piece.
def place( self, position, v, T): geo = (self.geo - self.geo[v]).dot( T) return position + geo
[ "def getPoint(self, u, v):\r\n P = matrix(np.ones((4, 1)))\r\n P.set(0, 0, self.__radius * cos(v) * u)\r\n P.set(1, 0, self.__radius * sin(v) * u)\r\n P.set(2, 0, 0.0)\r\n return P", "def project_vector(u, v):\n u_np = np.array([u.get_x(), u.get_y()])\n v_np = np.array([v....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Generate all nondegenerate placements, with one of the vertices placed at (0,0). Return the placements as [ (v, T) ], where v is the vertex to be placed at (0,0), and T the 2x2 transformation matrix that place the piece according to self.geo[v] + T.dot(self.geo self.geo[v])
def findNondegeneratePlacements( self): # Rotate counterclockwise by 90 degrees around the v'th vertex. r90 = np.array( [ [0,1], [-1,0] ], dtype=int) # Flip the piece along the vertical axis through the v'th vertex. fv = np.array( [ [1,0], [0,-1] ], dtype=int) self.placements = ...
[ "def generate_all_locations(grid, shape):", "def test_create_new_placements(self):\n subv = SimpleMachineVertex(None, \"\")\n pl = Placement(subv, 0, 0, 1)\n Placements([pl])", "def generate_nearby_cells(self):\n for y in range(len(self.island_map)):\n for x in range(len(s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Count unoccupied neighbors of a point.
def countFreeNeighbors( p, board, occupation): n = 0 for m in [0, 1]: for d in [-1, 1]: pn = [p[0], p[1]] pn[m] += d j = board.grids.get( tuple(pn), None) if (j is None): continue # Not a board point if (occupation.has_key( j)): continue # Occu...
[ "def count_neighbors(self, row, col):\r\n neighbors = 0\r\n for i in range(-1, 2):\r\n for j in range(-1, 2):\r\n try:\r\n val = self.grid[row + i][col + j]\r\n if val and not (i == 0 and j == 0):\r\n neighbors += 1...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find unoccupied positions on the board.
def findUnoccupied( board, occupation): return [ j for j in xrange(len(board.positions)) if not occupation.has_key(j) ]
[ "def available_positions(board):\r\n positions = []\r\n for i in range(board.board.num_cols()):\r\n for j in range(board.board.num_rows()):\r\n if board.board[i, j] is None:\r\n positions.append((i, j))\r\n return positions", "def unoccupied_square...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determines whether the model instance has already been selected in a related field (ManyToManyField, OneToOneField).
def available(self): fields = self._meta.get_fields() for field in fields: if isinstance(field, models.ManyToManyRel): attr = field.get_accessor_name() if getattr(self, attr).count() > 0: return False elif isinstance(field, m...
[ "def relation_exists(cls, model):\n return bool(cls.get_related_field(model)\n or cls.get_reverse_related_field(model))", "def _is_join_model(model):\n return all([\n (field.primary_key or field.rel)\n for field in model._meta.fields\n ]) and len(model._meta.fields) >...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
outputs the noise covariance matrix, R
def getCovarianceNoiseMatrix(self): return np.dot ( self.getB().T, self.getB() )
[ "def get_cov(noise):\n num_coils = noise.shape[0]\n X = noise.reshape([num_coils, -1])\n X -= np.mean(X, axis=-1, keepdims=True)\n cov = np.matmul(X, X.T.conjugate())\n\n return cov", "def covariance(data_matrix):\n return np.asmatrix(np.cov(data_matrix, rowvar=0))", "def covariance_matrix(sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Determine if the object has a parent with the supplied name.
def has_parent(obj, parent_name): if obj.parent is None: return False if obj.parent.name is None: return False elif obj.parent.name == parent_name: return True else: return has_parent(obj.parent, parent_name)
[ "def has_parent(self):\n return self.get_parent() is not None", "def has_parent(obj):\n return obj and hasattr(obj, 'parent') and obj.parent", "def has_parent(self):\n return self.parent != None", "def has_parent(self):\n return self.parent is not None", "def has_parent(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
will simulation PARALLEL_UNIVERSES_COUNT universes then, will return the overall multiverse survival of the player
def compute_player_score(): progress_bar = ProgressBar(label="Computing universes") survivals_count = 0 for i in range(PARALLEL_UNIVERSES_COUNT): if simulate_universe(): survivals_count += 1 progress_bar.set_progression((i + 1) / PARALLEL_UNIVERSES_COUNT) progress_bar.end(...
[ "def simulate_universe():\n\n # untreated_survival is the probability to survive if not treated\n # this is an exact law of the universe, the player will not have this information\n untreated_survival = random.uniform(MIN_DISEASE_SURVIVAL, MAX_DISEASE_SURVIVAL)\n\n trials: list[Trial] = []\n\n treate...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
simulates a universe and uses playground.choose_trial to take a decision return true in cas of survival in the simulated universe
def simulate_universe(): # untreated_survival is the probability to survive if not treated # this is an exact law of the universe, the player will not have this information untreated_survival = random.uniform(MIN_DISEASE_SURVIVAL, MAX_DISEASE_SURVIVAL) trials: list[Trial] = [] treated_survivals: ...
[ "def test_run_sim_1():\n rnd = rand.Arrivals(36, 41)\n sim.run_sim(3, 2, 5, 6, 22, rnd)", "def run(): \n learning_rate = 0.42\n discount_rate = 0.15\n initial_q_hat = 4\n \n # Set up environment and agent\n e = Environment() # create environment (also adds some dummy traffic)\n a = e....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Probability grouping of category variables
def probability_categorical(feature, label): assert feature.nunique()>2, 'feature category nums must be greater than 2.' t = pd.DataFrame({'feature':feature, 'label':label}) cat = label.unique() cat = [(cat[i], cat[i+1]) for i in range(len(cat)-1)] prob = label.value_counts(1).to_dict() slope = ...
[ "def cat_conditional_probability(self):\n # get dummies and isolate salary series\n df = self.custom_preprocess(flip_salary_index=True, drop_cont=True, pivot_cat=True)\n salary_series = df['salary']\n df.drop(columns=['salary'], inplace=True)\n\n corr_frame = pd.DataFrame(index=li...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert time_offsets to gps timestamps and nanoseconds
def get_gps_timestamp(file, time_offset): reference_date = get_reference_datetime(file) absolute_date = get_absolute_datetime(reference_date, time_offset) timestamp, nanosecond = datetime_to_gpstimestamp_nanoseconds(absolute_date) return timestamp, nanosecond
[ "def normalize_time(timestamps):\n phases = (timestamps - timestamps[0]) / (timestamps[-1] - timestamps[0])\n return phases", "def datetimes(self):\n if not self.offsets.offsets.shape:\n offsets = self.offsets.offsets.reshape((1,))\n else:\n offsets = self.offsets.offsets...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert datetime objects to GPS timestamp and nanoseconds
def datetime_to_gpstimestamp_nanoseconds(date): timestamp = gpstime.utc_to_gps(calendar.timegm(date.utctimetuple())) nanosecond = date.microsecond * 1000 return timestamp, nanosecond
[ "def convert_datetime_to_nanoseconds(datetime_obj):\n\n jan1_2001 = datetime.strptime(\"01-01-2001, 00:00:00.000000\", \"%m-%d-%Y, %H:%M:%S.%f\")\n\n difference = datetime_obj - jan1_2001\n\n UTC_time_diff = 7*60*60 # 7 hours converted into seconds\n\n seconds_difference = (difference.days*24*60*60) + d...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get the reference datetime from the KNMI LGT file as datetime
def get_reference_datetime(file): date_string = file.root.discharge1._f_getAttr('reference_datetime')[0] ref_date = datetime.datetime.strptime(date_string, '%d-%b-%Y;%H:%M:%S.%f') return ref_date
[ "def _get_harvest_datetime(self, filepath: str) -> str:\n\n filename = os.path.basename(filepath)\n file_tokens = filename.split(\"_\")\n return file_tokens[2][:-5]", "def getPLX_DateTime(fileName, oc=mc):\n\n if not oc:\n oc = matlab.engine.start_matlab()\n else:\n oc.cle...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
chang the order's status to be "cooking" which is selected by the id of order
def cook_order(request): order_id = request.GET.get('order_id', 0) cs , status = CookStatus.objects.get_or_create(cook_name=request.user) if cs.current_order is None: cs.current_order = Order.objects.get(id=order_id) cs.current_order.status = 'cooking' cs.current_order.tikchen = request.user.username cs.cur...
[ "def order_ready(request):\n\tcs , status = CookStatus.objects.get_or_create(cook_name=request.user)\n\tif cs.current_order is not None:\n\t\tcs.current_order.status = 'ready-to-serve'\n\t\tcs.current_order.save()\n\t\tcs.current_order = None\n\t\tcs.save()\n\n\treturn HttpResponseRedirect(\"/staff/cook_order_list/...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
chang the order's status to be "readytoserve" which is selected by the id of order
def order_ready(request): cs , status = CookStatus.objects.get_or_create(cook_name=request.user) if cs.current_order is not None: cs.current_order.status = 'ready-to-serve' cs.current_order.save() cs.current_order = None cs.save() return HttpResponseRedirect("/staff/cook_order_list/")
[ "def change_delivery_status(self, order_id):\n for order in orders:\n if order_id == order['order_id']:\n order['status'] = delivered\n return order\n return False", "async def update_order_status():\n symbol = App.config[\"symbol\"]\n\n # Get currently...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Format trajectory into a list of tuples before they are stored in memory. Trajectory is list of (s,a,r,s,d) tuples
def formatTrajectory(self, trajectory): return self.RLModel.formatTrajectory(trajectory)
[ "def write_trajectory2(trajectory, positions, velocities, accelerations, effort):\n\n # needed to set a single point in the right format.\n positions = [positions]\n velocities = [velocities]\n accelerations = [accelerations]\n effort = [effort]\n # needed to empty the previous portion of the mess...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Whether the environment is batched or not. If the environment supports batched observations and actions, then overwrite this property to True. A batched environment takes in a batched set of actions and returns a batched set of observations. This means for all numpy arrays in the input and output nested structures, the...
def batched(self) -> bool: return False
[ "def is_batch():\n\n pass", "def has_batch(self) -> bool:\n return self.has_any() and (\n self._batch_size is None or self._buffer_size >= self._batch_size\n )", "def get_batch_capable(self):\n return False", "def has_full_batch(self) -> bool:", "def should_handle_all_batc...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Whether the Environmet should reset given the current timestep. By default it only resets when all time_steps are `LAST`.
def should_reset(self, current_time_step: ts.TimeStep) -> bool: handle_auto_reset = getattr(self, '_handle_auto_reset', False) return handle_auto_reset and np.all(current_time_step.is_last())
[ "def should_reset(self) -> bool:\n changed_team = self._changed_training_team\n if self._changed_training_team:\n self._changed_training_team = False\n return changed_team", "def reset():\n return True", "def get_reset(self):\n return self.is_reset()", "def is_reset_t...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Defines the observations provided by the environment. May use a subclass of `ArraySpec` that specifies additional properties such as min and max bounds on the values.
def observation_spec(self) -> types.NestedArraySpec:
[ "def augment_env_spec(cls, env_spec, latent_dim):\n\n aug_obs = akro.Box(low=np.concatenate((env_spec.observation_space.low, \n np.zeros(latent_dim))),\n high=np.concatenate((env_spec.observation_space.high, \n np.ones(latent_dim))),\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns the current timestep.
def current_time_step(self) -> ts.TimeStep: return self._current_time_step
[ "def current_time_step(self) -> int:\n return self._current_time_step", "def time_step(self):\n return self._time_step", "def GetTimeStep(self):\n time_step = None\n\n time_step = self._solver_collection.GetTimeStep()\n \n if not time_step is None:\n\n self.time_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Updates the environment according to the action and returns a `TimeStep`. If the environment returned a `TimeStep` with `StepType.LAST` at the previous step the implementation of `_step` in the environment should call `reset` to start a new sequence and ignore `action`. This method will start a new sequence if called a...
def step(self, action: types.NestedArray) -> ts.TimeStep: if self._current_time_step is None or self.should_reset( self._current_time_step ): return self.reset() self._current_time_step = self._step(action) return self._current_time_step
[ "def step(self, action):\n action = self.randomization.action_randomizer.randomize(\n action, self._random_state\n )\n\n robot_exception = None\n try:\n self._act(action)\n except RobotException as re:\n logger.error(\n f\"Robot rais...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
it makes the flow of a given input through the network, all data are stored in the layers "y" and "v"
def flow(input_): global number_of_neurons_by_layer if len(input_) != number_of_neurons_by_layer[0]: raise IndexError( f"\033[91mInput length is incorrect. It must be {number_of_neurons_by_layer[0]}.\033[m") layers[0]["y"][1:] = np.array(input_).flatten().reshape(len(input_), 1) for ...
[ "def trainNet():", "def epoch(self, v, expected):\n self.V = []\n self.O_hidden = []\n self.O_output = []\n self.D_1 = []\n\n self.error = []\n\n\n self.forward(np.transpose([v]), np.transpose([expected]))\n self.backward()", "def forward(self, inputs):\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
it computes the error vector between desired and obtained output, stored at the last layer
def error(input_, output): global number_of_neurons_by_layer if len(output) != number_of_neurons_by_layer[-1]: raise IndexError( f"\033[91mDesired output length is incorrect. It must be {number_of_neurons_by_layer[-1]}.\033[m") output = np.array(output).reshape(len(output), 1) flow(i...
[ "def output_error(dblActivation,dblTarget):\n return(dblTarget - dblActivation)", "def _compute_error(self,expected_out,actual_out,error_func):\n\n error = error_func(expected_out,actual_out)\n return error", "def get_error(self, output,target):\n return [target[i]-output[i] for i in ran...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
it gets the list of weigths
def getweigths(): ls = [] for i_lay in range(1, len(layers)): ls.append(layers[i_lay]["weigths"]) return ls
[ "def _weichall():\n try:\n LAchall=LOSC('a').rchall();LBchall=LOSC('b').rchall();L2chall=LOSC('2').rchall();\n allwvfm=[*LAchall[:2],*LBchall,*L2chall];\n allenergy=[*EMeters.EG1wYFE1in(),*EMeters.EG1w2in()[0],*EMeters.EG()[0][0]]\n allweich=[]\n for ii ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
it gets the list of "Delta_w"
def get_Delta_weigths(): ls = [] for i_lay in range(1, len(layers)): ls.append(layers[i_lay]["Delta_w"]) return ls
[ "def _get_delta_units(self) -> List[str]:\n return [u for u in self._units if u.startswith(\"delta_\")]", "def calc_dDelta(self):\n self.dDelta = np.zeros((self.nphon, self.nwann, self.nwann))\n #iq, iv, iR\n iR0 = iRlist[(0, 0, 0)]\n iq0 = iqlist[(0, 0, 0)]\n\n for iv in...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets/clears a software breakpoint address > the address of the software breakpoint instruction > the instruction to be programmed (either the software breakpoint opcode or the original instruction the software breakopint was replacing). flags > One or more of the SWBPFlags listed below returns the original/old opcode a...
def set_sw_bp(address, instruction, flags): log.info("Debug:: set/remove bp at address 0x%0x, instructions 0x%0x, flags = 0x%0x" % ( address, instruction, flags)) # Accept addressing both from FLASH_START and from 0x0 addr = address & (FLASH_START-1) single_page_access = False buffer_size =...
[ "def set_sw_bp(address, instruction, flags):\n log.log(LEVEL_INFO, \"Debug:: set bp at address 0x%0x, store instructions 0x%0x, flags = 0x%0x\" % (address, instruction, flags))", "def bp(self, expr=None, handler=None, windbgcmd=None, oneshot=False,\n passcount=None, threadid=None, count=0xffffffff):\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return True if pen is down, False if it's up.
def isdown(self): return self.pen == 1
[ "def is_pen_down():\n return self.turtle.pen_down", "def isUp ( self ) :\n return not self.isDown()", "def isDown ( self ) :\n return self._ilhcbmagnet.isDown()", "def down(self):\n if (self.down_flag):\n self.down_flag = False\n return True\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Change the bearing (angle) of the turtle.
def setbearing(self, bearing): diff = self.bearing - bearing self.b_change = diff self.bearing = bearing self._add_point() self.b_change = 0
[ "def change_angle(self, value):\n if self.mode != Modes.Move:\n return\n\n #Get the current tank\n current_tank = self.cur_team\n\n #Erase it\n self.erase_tank(current_tank)\n\n #Change the angle accordingly\n if value == \"up\":\n current_tank....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
this method is called by an admin user to approve the lyrics of a song
def approve_lyrics(): pass
[ "def is_lyrics_approved():", "async def lyrics(self, ctx: commands.Context, *, song_name: str):\n try:\n client = await self.obtain_client()\n except AttributeError:\n await ctx.send(\"Not key for KSoft.Si has been set, ask owner to add a key.\")\n return\n tr...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This method is called to check if a song already has lyrics so as to avoid duplicity of lyrics
def song_has_lyrics(): pass
[ "def add_lyrics(self):\n\n conn = self.conn\n conn.text_factory = str\n c = conn.cursor()\n\n c.execute(\"SELECT songs.id, artist, title, url FROM songs LEFT JOIN lyrics ON songs.id = lyrics.song_id WHERE lyrics.song_id IS NULL\")\n all_songs_to_scrape = c.fetchall()\n for ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This is called to compare a lyrics note to the original to ensure they are not the same..if they are , such a lyrics note is rejected
def lyrics_note_is_same_as_original(): pass
[ "def test_two_mismatches(self):\n\n sam_fields = [\"test_read\", \"0\", \"chr1\", \"202892094\", \"255\", \"5M\", \"*\",\n \"0\", \"0\", \"ACCGA\", \"*\", \"NM:i:2\", \"MD:Z:1A0A2\", \"jI:B:i,-1\",\n \"jM:B:c,-1\" ]\n\n genome = Fasta(\"input_files/hg38_chr1...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks if the lyrics has been approved or not
def is_lyrics_approved():
[ "def approve_lyrics():\n pass", "def is_approved(self):\n if askbot_settings.ENABLE_CONTENT_MODERATION:\n if self.approved == False:\n return False\n return True", "def is_approved_speaker(self):\n try:\n return self.speaker.is_approved()\n exc...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
r"""Calculate the cold plasma dispersion surfaces according to equation 2.64 in Plasma Waves by Swanson (2nd ed.)
def disp_surf_calc(kc_x_max, kc_z_max, m_i, wp_e): # Make vectors of the wave numbers kc_z = np.linspace(1e-6, kc_z_max, 35) kc_x = np.linspace(1e-6, kc_x_max, 35) # Turn those vectors into matrices kc_x_mat, kc_z_mat = np.meshgrid(kc_x, kc_z) # Find some of the numbers that appear later in t...
[ "def compute_mixing_coefficients_surf(self):\n [Ly,N] = self.b.shape\n z_u_w = self.grid_dict['z_u_w']\n\n # SET UP NEW MIXING COEFFICIENT ARRAYS\n self.Kv_surf = np.zeros([Ly,N+1])\n self.Kt_surf = np.zeros([Ly,N+1])\n \n self.ghat = np.zeros([Ly,N+1])\n \n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test Restaurant.__check_conditions decorator Test must be passed if functions with this decorator raised error cause of Hall, Delivery or Kitchen was not setted.
def test_open_no_setup(restaurant_only, hall_only, kitchen_only, delivery_only): # Here checks not all variants, cause restaurant_only is not isolated # object. They were previously check and working alongside # but affects result if together. # no setups with pytest.raises(CustomWarning): ...
[ "def __preflight_check(self) -> None:\n\n if not self.can_proceed:\n if config.settings.dry_run:\n raise AssertionError(f'\"{self.name}\" cannot proceed because of dry run')\n\n raise PreconditionFailedError(f'\"{self.name}\" cannot proceed')", "def test_properties(self...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test of cooking the same product twice. Test passed if second cooking of same product raise ValueError
def test_cook_twice(cook_not_busy, product_for_cook): cook_not_busy.cook_dish(product_for_cook) with pytest.raises(ValueError): cook_not_busy.cook_dish(product_for_cook)
[ "def test_not_like_product_twice(self):\n\n # create initial product\n self.test_like_product()\n\n # Attempt to like the product again\n url = \"/products/1/like\"\n self.client.credentials(HTTP_AUTHORIZATION='Token ' + self.token)\n response = self.client.post(url, None, ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test of cooking by busy cook Test passed if busy cook raise a CustomWarning
def test_busy_cook(cook_busy, product_for_cook): with pytest.raises(CustomWarning): assert cook_busy.cook_dish(product_for_cook)
[ "def test_cook_twice(cook_not_busy, product_for_cook):\n\n cook_not_busy.cook_dish(product_for_cook)\n with pytest.raises(ValueError):\n cook_not_busy.cook_dish(product_for_cook)", "def test_cook_set_free(cook_busy, product_for_cook):\n cook_busy.set_free(True)\n # if product needs to be cooked...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Test of changing state of cook. Busy cook set to free and then tries to cook the dish. Cooking should be successful (product.get_need_cook_status should be False)
def test_cook_set_free(cook_busy, product_for_cook): cook_busy.set_free(True) # if product needs to be cooked assert product_for_cook.get_need_cook_status() is True cook_busy.cook_dish(product_for_cook) assert product_for_cook.get_need_cook_status() is False
[ "def test_change_recipe(self):\n c1_data, c2_data, pr = self.create_pr_data()\n c1_data, c2_data, pr = self.create_pr_data()\n self.set_counts()\n pr.save()\n self.compare_counts(events=1, jobs=2, ready=1, prs=1, active=2, active_repos=1)\n\n new_recipe = utils.create_recip...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Formats the output of a transaction receipt to its proper values
def output_transaction_receipt_formatter(receipt): if receipt is None: return None logs_formatter = compose(functools.partial(map, outputLogFormatter), list) formatters = { 'blockNumber': to_decimal, 'transactionIndex': to_decimal, 'cumulativeGasUsed': to_decimal, '...
[ "def print_receipt(self) -> typing.List[str]:\n lines = []\n euro_total=0\n usd_total=0\n gbp_total=0\n\n for item in self._items.items():\n euro_price = self._get_product_price(item[0]) * item[1]\n usd_price = self.get_price_in_currency(euro_price,\"USD\")\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Formats the output of a block to its proper values
def outputBlockFormatter(block): # Transform to number block["gasLimit"] = to_decimal(block["gasLimit"]) block["gasUsed"] = to_decimal(block["gasUsed"]) block["size"] = to_decimal(block["size"]) block["timestamp"] = to_decimal(block["timestamp"]) if block.get("number"): block["number"]...
[ "def pretty_data_block(data_block):\n return '\\nCoding: {0[0]}\\n' \\\n 'Function: {0[1]}\\n' \\\n 'Description: {0[2]}\\n' \\\n 'Value: {0[3]} {0[4]}\\n' \\\n 'Subunit: {0[5]}\\n' \\\n 'Tariff: {0[6]}\\n' \\\n 'Storage Number: {0[7]}\\n'.format(data_b...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Formats the output of a log
def outputLogFormatter(log): if log.get("blockNumber"): log["blockNumber"] = to_decimal(log["blockNumber"]) if log.get("transactionIndex"): log["transactionIndex"] = to_decimal(log["transactionIndex"]) if log.get("logIndex"): log["logIndex"] = to_decimal(log["logIndex"]) return ...
[ "def format(self, record, *args, **kwargs):\r\n return logging.Formatter.format(\r\n self, record, *args, **kwargs).replace('\\n', '\\n' + ' ' * 8)", "def format(self, record):\n\t\tif self.color:\n\t\t\ttry:\n\t\t\t\tcat = getattr(record, self.CATEGORY, None)\n\t\t\t\tif not cat:\n\t\t\t\t\tif ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Formats the input of a whisper post and converts all values to HEX
def inputPostFormatter(post): post["ttl"] = from_decimal(post["ttl"]) post["workToProve"] = from_decimal(post.get("workToProve", 0)) post["priority"] = from_decimal(post["priority"]) if not is_array(post.get("topics")): post["topics"] = [post["topics"]] if post.get("topics") else [] post[...
[ "def outputPostFormatter(post):\n\n post[\"expiry\"] = to_decimal(post[\"expiry\"])\n post[\"sent\"] = to_decimal(post[\"sent\"])\n post[\"ttl\"] = to_decimal(post[\"ttl\"])\n post[\"workProved\"] = to_decimal(post[\"workProved\"])\n\n if not post.get(\"topics\"):\n post[\"topics\"] = []\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Formats the output of a received post message
def outputPostFormatter(post): post["expiry"] = to_decimal(post["expiry"]) post["sent"] = to_decimal(post["sent"]) post["ttl"] = to_decimal(post["ttl"]) post["workProved"] = to_decimal(post["workProved"]) if not post.get("topics"): post["topics"] = [] post["topics"] = [decode_hex(topi...
[ "def inputPostFormatter(post):\n\n post[\"ttl\"] = from_decimal(post[\"ttl\"])\n post[\"workToProve\"] = from_decimal(post.get(\"workToProve\", 0))\n post[\"priority\"] = from_decimal(post[\"priority\"])\n\n if not is_array(post.get(\"topics\")):\n post[\"topics\"] = [post[\"topics\"]] if post.ge...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tests the import from local file for cities works fine
def test_csv_import_city(self): from django.contrib.messages import get_messages path = reverse("import-csv") user = mixer.blend(User, is_staff=True, is_superuser=True) file = open("city.csv") client = Client() client.force_login(user) r = client.post(path, {"titl...
[ "def load_cities():\n return os.listdir(DATA_DIR)", "def import_localities_fromfile(self, filePath=None, separator=';'):\n if not self.portal_type == 'UrbanTool':\n raise Unauthorized(\"This script must be called on portal_urban!\")\n if not hasattr(self, 'streets'):\n raise AttributeError(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Log control data at each step during evaluation.
def _log_control_data(self, action, global_reward): action_r = ','.join(['%d' % a for a in action]) cur_control = {'episode': self.cur_episode, 'step': self.t, 'action': action_r, 'reward': global_reward} self.control_data.appe...
[ "def log(self):\n self.simulator.log()", "def log(self, variable_name, data, t_step):\n self.variable_names[variable_name].step(data, t_step)", "def _log(self, data):\n if self.log_data is not None:\n self.log_data(data)", "def log_evaluation_details(self, data, labels, level=l...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Get actions of each agents neighbour in the graph.
def get_neighbor_action(self, action): naction = [] for i in range(self.n_agent): naction.append(action[self.neighbor_mask[i] == 1]) return naction
[ "def k(self, i):\n es = self.graph.es.select(_source=i)\n actions = []\n for edge in es:\n action = edge[\"action\"]\n if action not in actions:\n actions.append(action)\n return actions", "def actions(self, agent_state):\n raise NotImplement...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
! resources object of Resources class contain resources from config file options object of MergeOptions class contain merge options from config file str_name default value same as the class name "SynsetsSUMOMerger2"
def __init__(self, resources, options, str_name = 'SynsetsSUMOMerger2'): super(SynsetsSUMOMerger2, self).__init__(resources, options, str_name)
[ "def __init__(self, resources, options, str_name = 'SynsetsMSRMerger'):\n super(SynsetsMSRMerger, self).__init__(resources, options, str_name)", "def test_merge_file_multiple(self):\n cfg = gc3libs.config.Configuration()\n cfg.merge_file(self.f1)\n cfg.merge_file(self.f2)\n cfg.merg...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
! Create dictionary based on mapping PLWN on SUMO ontology file. Dictionary format and mapping PLWN on SUMO ontology file format are presented below.
def get_plwn2sumo_dict(self): if not os.path.exists(self.resources().mapping_sumo_file()): raise IOError( "%s file not found!" % \ self.resources().mapping_sumo_file() ) plwn2sumo_dict = defaultdict(set) with open(self.resources().mapping_sumo_file()) as sumofile: n...
[ "def populateMappingDictionary(self):\n with open(\"mapping.txt\", \"r\") as file_object:\n for line in file_object:\n splitline = line.split()\n self.mapping[' '.join(splitline[1:])] = splitline[0]", "def makeMapping(globalMap):\n \n from memops.xml.Implementatio...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
! Merge two given graphs, namely synsets graph and SUMO graph. The final graph contain one type of nodes, namely synsets nodes. Each synset node has an attribute named "synset",
def merge(self, g1, g2): logger = logging.getLogger(__name__) g = BaseGraph() g.copy_graph_from(g1) plwn2sumo_dict = defaultdict(set) plwn2sumo_dict = self.get_plwn2sumo_dict() synset_on_vertex_dict = {} for node in g.all_nodes(): synset_id = node.synset.synset_id if ...
[ "def merge(def1, def2):\n graph1 = def1['graph']\n graph2 = def2['graph']\n\n # Add graph2 nodes and edges to graph1\n for node, data in graph1.nodes_iter(data=True):\n # Add graph2 edges\n for edge1, edge2 in graph2.edges_iter():\n graph1.add_edge(edge1, edge2)\n # Add g...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Builds and returns (in the form returned by decoderawtransaction) a transaction that spends the given utxo, pays CHI to some output
def build_tx (self, utxo, chiOut, name, nameAddr, value): nameData = self.nodes[0].name_show (name) inputs = [nameData, utxo] outputs = {nameAddr: Decimal ('0.01')} outputs.update (chiOut) tx = self.nodes[0].createrawtransaction (inputs, outputs) nameOp = { "op": "name_update", "na...
[ "def sochain_utxo_to_xchain_utxo(utxo):\n hash = utxo['txid']\n index = utxo['output_no']\n \n value = round(float(utxo['value']) * 10 ** 8)\n script = bytearray.fromhex(utxo['script_hex']) #utxo['script_hex']\n witness_utxo = Witness_UTXO(value, script)\n return UTXO(hash, index, witness_utxo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Signs a transaction (in format of build_tx) with the given node, and returns the decoderawtransactiontype result again.
def sign (self, node, tx): signed = node.signrawtransactionwithwallet (tx["hex"]) res = node.decoderawtransaction (signed["hex"]) res.update (signed) return res
[ "def sign_transaction(self, transaction, prvkey):\n return self.web3.eth.account.sign_transaction(transaction, prvkey)", "def sign_transaction(transaction, priv_key):\n serialized_tx_msg = serialize_transaction(tx=transaction, signed=False)\n return sign_msg(serialized_tx_msg, priv_key)", "def sign...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Pick section of signal
def pick_section(signal, section=None): len_noise = signal.shape[-1] if section is None: len_sig = len_noise ii = 0 elif isinstance(section, int): len_sig = section ii = np.random.randint(0, len_noise - len_sig) else: len_sig = ...
[ "def selection_fn(self, trace, points, selector):\n self.segment = self.fig.layout[\"sliders\"][0].active\n seg = self.segment\n\n xrange = selector.xrange\n wave = self.wave[seg]\n mask = self.mask[seg]\n\n # Choose pixels and value depending on selected type\n if s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate the average level across all sentences. The levels are calculated according to the toolbox's reference level. Returns
def average_level(self): spl = [utils.dbspl(x) for x in self.load_files()] return np.mean(spl), np.std(spl)
[ "def rouge_l_sentence_level(eval_sentences, ref_sentences):\n\n f1_scores = []\n for eval_sentence, ref_sentence in zip(eval_sentences, ref_sentences):\n m = float(len(ref_sentence))\n n = float(len(eval_sentence))\n lcs = _len_lcs(eval_sentence, ref_sentence)\n f1_scores.append(_f_lcs(lcs, m, n))\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Instantiate a new TypeDefer
def __init__(self, raw_defer: Dict): self.kind = raw_defer.get("kind") self.name = raw_defer.get("name") self.of_type: TypeDefer = TypeDefer(raw_defer.get("ofType")) if raw_defer.get("ofType") is not None else None
[ "def instantiate():\n d = defer.Deferred()", "def Instance(self) -> TypeManager:", "def __call__(self, *args):\n return TypeCall(self, args)", "def _make_constructor(name, type_, attrs, kwargs):\n d = dict(attrs)\n d['_sumtype_attribs'] = [x for x in attrs]\n t = type(name, (type_,), d)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create a new Schema instance. Firstly the schema will be loaded synchronously from the endpoint and stored as raw json for further processing. Then the request types will be parsed. Those are "Query", "Mutation" and "Subscription". After that the schema types and directives are parsed.
def __init__(self, endpoint: str, transporter: Transporter, settings: Settings, cache: Optional[Cache]): self.endpoint = endpoint self.transport = transporter self.settings = settings self.cache = cache if self.cache is not None: schema_introspection = self.cache.ret...
[ "def schema(self) -> AitoSchema:\n return self.schema_cls.from_deserialized_object(self._json)", "def _CreateSchemas(self) -> None:\n self.schema_objs = dict() # Holds OpenAPI representations of types.\n\n # Add the OpenAPI schemas of protobuf primitive types.\n primitive_type_schemas = {\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parse the query type from the root schema. This can either return a string or None. The latter when the endpoint does not support queries.
def parse_query_type(raw_schema: Dict) -> Union[str, None]: return Schema.parse_operation_type(raw_schema, "queryType")
[ "def parse_operation_type(raw_schema: Dict, op_type: str) -> Union[str, None]:\n query_type = raw_schema.get(op_type, {})\n if not query_type:\n return None\n return query_type.get(\"name\")", "def parse_query_spec(self, query_spec):\n try:\n return self.QUERY_TYP...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parse the mutation type from the root schema. This can either return a string or None. The latter when the endpoint does not support mutations.
def parse_mutation_type(raw_schema: Dict) -> Union[str, None]: return Schema.parse_operation_type(raw_schema, "mutationType")
[ "def parse_operation_type(raw_schema: Dict, op_type: str) -> Union[str, None]:\n query_type = raw_schema.get(op_type, {})\n if not query_type:\n return None\n return query_type.get(\"name\")", "def set_mutation_type(self, mut_type=''):\n if mut_type:\n # specified...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parse the subscription type from the root schema. This can either return a string or None. The latter when the endpoint does not support subscriptions.
def parse_subscription_type(raw_schema: Dict) -> Union[str, None]: return Schema.parse_operation_type(raw_schema, "subscriptionType")
[ "def subscription_type(self) -> str:\n return pulumi.get(self, \"subscription_type\")", "def smn_subscription_type(self):\n return self._smn_subscription_type", "def _get_subtlv_type(self):\n return self.__subtlv_type", "def get_type_from_doc(doc):\n try:\n return doc.replace('...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parse an operation type from the root schema. This can either return a string or None. The latter when the endpoint does not support the passed by operation.
def parse_operation_type(raw_schema: Dict, op_type: str) -> Union[str, None]: query_type = raw_schema.get(op_type, {}) if not query_type: return None return query_type.get("name")
[ "def get_operation_type(self, operation_name):\n # type: (Optional[str]) -> Optional[str]\n operations_map = self.operations_map\n if not operation_name and len(operations_map) == 1:\n return next(iter(operations_map.values()))\n return operations_map.get(operation_name)", "...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parse all operations for a given operation type.
def parse_operations(self, operation_type: str) -> Tuple[Operation]: if operation_type is None: return tuple() query_type: SchemaType = self.types.get(operation_type) if query_type is None: return tuple() return tuple([Operation(f, self.settings) for f in query_ty...
[ "def parse_operation(self, data, ip):\n json_decoded = json.loads(data)\n op = json_decoded['OPERATION']\n if op in self._callbacks:\n self.logger.info(\"Got Operation: \" + op)\n self._callbacks[op](json_decoded, ip)\n else:\n self.logger.error(\"Unknown...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parse a list of arguments into a dictionary where the key is the name of the argument and the argument itself is the value.
def parse_arguments(args: List[Dict]) -> 'Dict[str, Argument]': if not args: return {} result = {} for a in args: if not a: continue arg = Argument(a) result[arg.name] = arg return result
[ "def split_args(args):\r\n if not args:\r\n return {}\r\n # Handle the old comma separated argument format.\r\n if len(args) == 1 and not re_new_args.search(args[0]):\r\n args = args[0].split(',')\r\n # Separate out the key and value for each argument.\r\n args_dict = {}\r\n for arg ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parse a list of directives into a dictionary where the key is the name of the directive and the value is the directive itself.o
def parse_directives(schema_directives: List[Dict]) -> Dict[str, Directive]: result = {} for schema_directive in schema_directives: new_directive = Directive(schema_directive) result[new_directive.name] = new_directive return result
[ "def directives():\n cmd = \"{} -L\".format(_detect_os())\n ret = {}\n out = __salt__[\"cmd.run\"](cmd)\n out = out.replace(\"\\n\\t\", \"\\t\")\n for line in out.splitlines():\n if not line:\n continue\n comps = line.split(\"\\t\")\n desc = \"\\n\".join(comps[1:])\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Given a Unity Environment and a QNetwork, this method will generate a buffer of Experiences obtained by running the Environment with the Policy derived from the QNetwork.
def generate_trajectories( env: BaseEnv, q_net: VisualQNetwork, buffer_size: int, epsilon: float ): # Create an empty Buffer buffer: Buffer = [] # Reset the environment env.reset() # Read and store the Behavior Name of the Environment behavior_name = list(env.behavior_specs)[0] # Read...
[ "def collect_gameplay_experiences(env, agent, buffer):\n state = env.reset()\n done = False\n while not done:\n action = agent.collect_policy(state)\n next_state, reward, done, _ = env.step(action)\n if done:\n reward = -1.0\n buffer.store_gameplay_experience(state, n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Performs an update of the QNetwork using the provided optimizer and buffer
def update_q_net( q_net: VisualQNetwork, optimizer: torch.optim, buffer: Buffer, action_size: int ): BATCH_SIZE = 1000 NUM_EPOCH = 3 GAMMA = 0.9 batch_size = min(len(buffer), BATCH_SIZE) random.shuffle(buffer) # Split the buffer into batches batches = [ buffer[batc...
[ "def update_optimizer(self, context, optimizer, host):\n pass", "def _refresh_buffers(self) -> None:", "def reload(self,offline_buffer):\n #loading online buffer from offline buffer by sampling (online_buffer.buffer_size) samples \n self.buffer = SumTree(self.buffer_size)\n names, id...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Search for lback index self._in_loop becomes true in the second state of the loop
def _get_lback_index(self, model, last) -> int: assert last > 0 # last state cannot be loop-back. assert model.get_value(self.totime(self._in_loop, last)).is_true() assert model.get_value(self.totime(self._in_loop, 0)).is_false() idx = last - 1 while model.get_value(self....
[ "def step_back():\r\n\r\n global index\r\n index -= 1", "def _is_looping(self):\n return self.loop_end > 0.0 and self.loop_end > self.loop_start", "def is_loop(self):\n return self.vertex_a == self.vertex_b", "def __should_loop(self):\n if self.loop:\n if self.num_of_loop...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Stores in a random location in the Linked list
def add(self, item): if self.count == 0: random_location = 0 else: random_location = random.randint(0, self.count - 1) self.insert(Node(item), random_location)
[ "def random_location(self):\n return random.choice(self.locations_list)", "def copyRandomList(self, head: 'Node') -> 'Node': \n map_new = collections.defaultdict(lambda: Node(None, None, None))\n map_new[None] = None # if a node's next or random is None, their value will be None but not a new...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns true if c is a printable character. We do this by checking for ord value above 32 (space), as well as CR (\r), LF (\n) and tab (\t)
def is_printable(c): return ord(c)>=32 or c in ['\r','\n', '\t']
[ "def _is_printable(char):\n category = unicodedata.category(char)\n return (not category.startswith(\"C\") and\n (not category.startswith(\"Z\") or category == \"Zs\"))", "def is_printable_char(character):\n if character >= 32 and character <= 127:\n return True\n if character == 10 ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Filter control characters out of the string buf, given a list of control codes that represent backspaces, and a regex of escape sequences. backspaces are characters emitted when the user hits backspace. This will probably vary from terminal to terminal, and this list should grow as new terminals are encountered. escape...
def sanitize(buf, backspaces=['\x08\x1b[K', '\x08 \x08'], escape_regex=re.compile(r'\x1b(\[|\]|\(|\))[;?0-9]*[0-9A-Za-z](.*\x07)?')): # Filter out control characters # First, handle the backspaces. for backspace in backspaces: try: while True: i...
[ "def escape_buffer(self, buf):\n esc_byte = bytes({cb.ESC})\n esc_escaped = bytes({cb.ESC}) + bytes({cb.ESC ^ cb.ESC_XOR})\n\n start_byte = bytes({cb.START})\n start_escaped = bytes({cb.ESC}) + bytes({cb.START ^ cb.ESC_XOR})\n\n escaped = buf.replace(esc_byte, esc_escaped) \\\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Tells the child process to resize its window
def resize_child_window(self): s = struct.pack('HHHH', 0, 0, 0, 0) x = fcntl.ioctl(0,termios.TIOCGWINSZ,s) fcntl.ioctl(self.child_fd,termios.TIOCSWINSZ,x)
[ "def resize(self):\r\n Win.resize(self)\r\n self.write(\"### console has been resized\")", "def __window_resizeTo(self, iWidth, iHeight):\n pass", "def OnWindowSetResizable(self, Resizable=sentinel):", "def triggerResize(self):\r\n self.parent.requestResize()", "def _resize_windo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Launch the appropriate shell as a login shell It will be either bash or tcsh depending on what the user is currently running. It checks the SHELL variable to figure it out.
def run_shell(): shell = get_shell() if shell not in ['bash','tcsh']: raise ValueError, "Unsupported shell (only works with bash and tcsh)" os.execvp(shell,(shell,"-l"))
[ "def get_default_shell():\n username = getpass.getuser()\n shell = pwd.getpwnam(username).pw_shell\n return shell", "def get_default_shell():\n if is_windows():\n return 'cmd.exe'\n else:\n import pwd\n import getpass\n\n if 'SHELL' in os.environ:\n return os....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Retrieve the name of the directory that will store the logfiles. If the SHELLLOGGERDIR environment variable is set, use that. Otherwise, default to ~/.shelllogger
def get_log_dir(): env_var = "SHELLLOGGERDIR" if os.environ.has_key(env_var): return os.environ[env_var] else: return os.path.expanduser('~/.shelllogger')
[ "def get_logging_dir(self):\n return self.logging_dir", "def platform_log_directory():\n\n LOG_DEFAULTS = {\n 'Darwin': os.path.expanduser('~/Library/Logs/Plex Media Server.log'),\n 'Linux': '/var/lib/plexmediaserver/Library/Application Support/Plex Media Server/Logs/Plex Media Server.log'...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Convert the .raw file, with illegal characters and escape keys, to a proper XML version. Returns the name of the XML file
def raw_to_xml(self): xmlfilename = self.logfilename.replace('.raw','.xml') fout = codecs.open(xmlfilename, encoding="utf-8", mode="w") for line in codecs.open(self.logfilename,encoding="utf-8"): fout.write(sanitize(line)) fout.close() return xmlfilename
[ "def _format_as_xml(self, txt_file_path, output_path):\n base_name = os.path.splitext(os.path.basename(txt_file_path))[0]\n xml_file_path = os.path.join(output_path, base_name + '.xml')\n if os.path.exists(xml_file_path):\n LOG.info(\"File already exist %s\", xml_file_path)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
get the report template
def _report_template(): current_dir = Path(__file__).parent with open(current_dir / "report_template.html", "r") as f: template = f.read() template = re.sub(r"\s{2,}", " ", template) template = re.sub(r"\n", "", template) template = re.sub(r"> <", "><", template) return temp...
[ "def get_template(self):\n return self.template", "def _get_template_filename(self):\n file_name = ReportMeta.reports[self._report_key]['fileName']\n return '{}.html'.format(file_name)", "def get_template(self, context, **kwargs):\r\n return self.template", "def GetTemplate(self, _...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Render exception_data as an html report
def render_exception_html(exception_data, report_template=None): report_template = report_template or _report_template() jinja_env = jinja2.Environment(loader=jinja2.BaseLoader(), extensions=["jinja2.ext.autoescape"]) exception_data["repr"] = repr return jinja_env.from_string(report_template).render(exc...
[ "def create_exception_report(exc_type, exc_value, tb, output_format, storage_backend, data_processor=None, get_full_tb=False):\n exception_data = get_exception_data(exc_type, exc_value, tb, get_full_tb=get_full_tb)\n if data_processor:\n exception_data = data_processor(exception_data)\n\n if output_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Render exception_data as a json object
def render_exception_json(exception_data): return json.dumps(exception_data, default=_json_serializer)
[ "def jsonify_http_exception(exception: HTTPException):\n return jsonify(exception.description, exception.code)", "def _log_and_jsonify_exception(e):\n app.logger.exception(e)\n if hasattr(e, \"json\") and e.json:\n return jsonify(**e.json), e.code\n else:\n return jsonify(message=e.messa...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns context_lines before and after lineno from file. Returns (pre_context_lineno, pre_context, context_line, post_context).
def get_lines_from_file(filename, lineno, context_lines, loader=None, module_name=None): source = None if loader is not None and hasattr(loader, "get_source"): with suppress(ImportError): source = loader.get_source(module_name) if source is not None: source = source.split...
[ "def _get_lines_from_file(filename, lineno, context_lines):\r\n try:\r\n source = open(filename).readlines()\r\n lower_bound = max(0, lineno - context_lines)\r\n upper_bound = lineno + context_lines\r\n\r\n pre_context = \\\r\n [line.strip('\\n') for...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create an exception report and return its location
def create_exception_report(exc_type, exc_value, tb, output_format, storage_backend, data_processor=None, get_full_tb=False): exception_data = get_exception_data(exc_type, exc_value, tb, get_full_tb=get_full_tb) if data_processor: exception_data = data_processor(exception_data) if output_format == ...
[ "def get_error_report(exception, **kwargs):\r\n\r\n if hasattr(exception, \"stored_report\"):\r\n result = exception.stored_report\r\n else:\r\n if hasattr(exception, \"exc_info\"):\r\n kwargs[\"exception_info\"] = exception.exc_info\r\n\r\n result = get_traceback(**kwargs)\r\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Publish a registration to the core, listing the API commands.
def register_to_core(self): self.channel.basic_publish(exchange='', routing_key='peripheral_register', body=json.dumps({self.name: api}))
[ "def register_routes(self, api):\n # Device Registration\n api.add_resource(controllers.UserDeviceRegistration, '/device-registration')", "def register_endpoints(api):\n api.add_resource(EventList, '/events')", "def auto_discover():\n auto_registration(\"actions\")", "def register(self):\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Subscribe to the queue matching the instance's name. Pass the command to the process_command function.
def subscribe_to_commands(self): self.basic_consume(self.process_command, queue=self.name)
[ "def queue_command(self, task_instance, command, priority=1, queue=None):\n super(MesosExecutor, self).queue_command(\n task_instance, command, priority, queue)\n\n key = task_instance.key\n if key not in self.queued_task_instances and key not in self.running:\n self.queue...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Run the chat client application loop. When this function exists, the application will stop
def run_chat_client(): while must_run: print_menu() action = select_user_action() perform_user_action(action) print("Thanks for watching. Like and subscribe! 👍")
[ "def MainLoop(self):\n self.pleaseQuit=0\n\n self.logger.info(\"Starting main eventloop\")\n try:\n self.irc.process_forever(1)\n except KeyboardInterrupt:\n self.logger.warn(\"Received interrupt, disconnecting from irc\")\n #self.irc.disconnect_all(\"^C ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Print the menu showing the available options
def print_menu(): print("==============================================") print("What do you want to do now? ") print("==============================================") print("Available options:") i = 1 for a in available_actions: if current_state in a["valid_states"]: ...
[ "def _print_menu(self):\n # Create header line.\n header = \"%s Menu:\" % (self.__name)\n header = header.title()\n print(header)\n\n # Show the iterations counter.\n iterations = self._status.get_value(\"iterations\")\n print(\"(Iteration %d)\" % (iterations))\n\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Ask the user to choose and action by entering the index of the action
def select_user_action(): number_of_actions = len(available_actions) hint = "Enter the number of your choice (1..%i):" % number_of_actions choice = input(hint) # Try to convert the input to an integer try: choice_int = int(choice) except ValueError: choice_int = -1 i...
[ "def take_action(self, action_index):\n assert action_index < len(self.ACTION_LOOKUP)\n action = self.ACTION_LOOKUP[action_index]\n # print(action)\n return", "def _take_action(self, action_index):\n assert action_index < len(self.ACTION_LOOKUP)\n self.action = action_ind...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Input `text` into the text field on the page.
def enter_text(self, text): self.q(css='#fixture input').fill(text)
[ "def set_text(self, text):\n self.text = text", "def ui_input_text() -> str:\n\ttext = input('enter your text ')\n\treturn text", "def input_text_basic(self, locator, text):\n self.element = self._element_finder(locator)\n if self.element:\n self.element.send_keys(text)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Select the car with ``car_value`` in the dropdown list.
def select_car(self, car_value): self.q(css=u'select[name="cars"] option[value="{}"]'.format(car_value)).first.click()
[ "def select_by_value(self, value):\n if value:\n self.browser.selenium.find_element_by_xpath(f\"//select/option[@value='{value}']\").click()", "def is_car_selected(self, car):\n return self.q(css=u'select[name=\"cars\"] option[value=\"{}\"]'.format(car)).selected", "def select_dropdown_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return ``True`` if the given ``car`` is selected, ``False`` otherwise.
def is_car_selected(self, car): return self.q(css=u'select[name="cars"] option[value="{}"]'.format(car)).selected
[ "def is_selected(self, term):\n found = self.frame.radio(label=term)\n if found.exists:\n return found.is_selected\n raise UnknownObjectException('Unable to locate radio matching {}'.format(term))", "def _is_selected ( self, object ):\n if hasattr(object, 'model_selection') ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Toggle the box for the pill with `pill_name` (red or blue).
def toggle_pill(self, pill_name): self.q(css=u"#fixture input#{}".format(pill_name)).first.click()
[ "def click_pill(self, pill):\n if pill < len(self.pills):\n return self.pills[pill].click()\n else:\n return f\"No pill {pill} found?\"", "def toggle_color_picker(self, wid, color_name='square_fill_ink'):\n print(\"TOGGLE COLOR PICKER\", getattr(wid, color_name), sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Click the ``Confirm`` button and confirm the dialog.
def confirm(self): with self.handle_alert(confirm=True): self.q(css='button#confirm').first.click()
[ "def confirm_dialog_box():\n alert = world.browser.switch_to.alert\n alert.accept()", "def _tap_on_confirm_button(self, yes=True, msg=\"Confirm dialog button\"):\n btn = self.UTILS.element.getElement(DOM.DownloadManager.download_confirm_yes if\n yes else DOM...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }