query stringlengths 9 9.05k | document stringlengths 10 222k | negatives listlengths 19 20 | metadata dict |
|---|---|---|---|
Resizes img of shape (h, w, ch) or (h, w) to square of size (side, side, ch) or (side, side), respectively, while preserving aspect ratio. Image is being padded with pad_cval if needed. | def resize_image_to_square(img, side, pad_cval=0, dtype=np.float64):
if len(img.shape) == 2:
h, w = img.shape
if h == w:
padded = img.copy()
elif h > w:
padded = np.full((h, h), pad_cval, dtype=dtype)
l = int(h / 2 - w / 2) # guaranteed to be non-negativ... | [
"def format_img_size(self, img, C):\n img_min_side = float(C.im_size)\n (height,width,_) = img.shape\n\n if width <= height:\n ratio = img_min_side/width\n new_height = int(ratio * height)\n new_width =... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Initializes lists, an x list, and a y value list with corresponding indicies | def __init__(self, dataList):
xList = []
yList = []
for index in range(0, len(dataList)):
xList.append(dataList[index][0])
yList.append(dataList[index][1])
self.xList = xList
self.yList = yList
self.dataList = dataList | [
"def init_location_list(self):\r\n # The size of the canvas is 500x500. The coordinate start from (20,20)\r\n # to (495,495) with increment of 5 for each axis\r\n for x_position in range(20, 495, 5):\r\n for y_position in range(20, 495, 5):\r\n location = [x_position,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Fetch the usd layer's contents on disk. | def _GetDiskContents(self, layer):
# type: (Sdf.Layer) -> str
# with USD Issue #253 solved, we can do a cheaper check of just
# comparing time stamps and getting contents only if needed.
if not layer.realPath:
# New() or anonymous layer that cant be loaded from disk.
... | [
"def fetch(self) -> bytes:\n self.log.debug(f\"fetching package: {self.file_name}\")\n desc = self.format_desc(self.file_name)\n content = utils.stream_download(self.source_url, desc=desc)\n return content",
"def fetch_the_data():\n subprocess.run([\"wget\", \"https://storage.google... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Create the hierarchy view for the outliner. This is provided as a convenience for subclass implementations. | def _CreateView(self, stage, role):
# type: (Usd.Stage, Union[Type[OutlinerRole], OutlinerRole]) -> QtWidgets.QAbstractItemView
return OutlinerTreeView(
contextMenuActions=role.GetContextMenuActions(self),
contextProvider=self,
parent=self) | [
"def create_hierarchy(self):\n\t\tpass",
"def makeTree(self):\n return makeTree(self.events,self.outTree)",
"def plot_hierarchy(self):\r\n tree = self.hierarchy()\r\n tree.show()",
"def getHierarchies():",
"def _write_trees(self, public, private):\n # Write the header and navigat... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Reset the stage for this outliner and child dialogs. | def ResetStage(self, stage):
self._stage = stage
self._dataModel.ResetStage(stage)
self.stageChanged.emit(stage) | [
"def reset_stage_to_defaults(self):\r\n self.KCube.CC_ResetStageToDefaults(self.serial)",
"def reset_stage():\n return set_stage('')",
"def stage(self):\n self.parent_obj.stage()",
"def ResetStage(self, stage):\n # type: (Usd.Stage) -> None\n if stage == self._stage:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Convenience method to get or create a shared editor dialog instance. | def GetSharedLayerTextEditorInstance(self, layer):
# type: (Sdf.Layer, bool, Optional[QtWidgets.QWidget]) -> LayerTextEditorDialog
dialog = self._sharedLayerTextEditors.get(layer)
if dialog is None:
readOnly = not layer.permissionToEdit
dialog = LayerTextEditorDialog(laye... | [
"def GetSharedInstance(cls, layer, readOnly=False, parent=None):\n # type: (Sdf.Layer, bool, Optional[QtWidgets.QWidget]) -> LayerTextEditorDialog\n dialog = cls._sharedInstances.get(layer)\n if dialog is None:\n dialog = cls(layer, readOnly=readOnly, parent=parent)\n cls.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks if there is a source file added. | def has_source_file( self ):
return self._source_file is not None | [
"def _check_source_exists(self):\r\n if not hasattr(self, '_source_exists'):\r\n self._source_exists = (self.source and\r\n (not isinstance(self.source, basestring) or\r\n isfile(self.source)))\r\n return self._source_exis... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Make fragment data coherent. Evaluates that the columns ``neighbors``, ``neighbor`` and ``position`` are coherent with the data contained according to ``frame`` and ``size``. | def coerce( self ):
df = self.copy()
gcond = ['neighbor', 'pdb'] if 'source' not in df.columns else ['neighbor', 'pdb', 'source']
for frame_id, frame in df.groupby('frame'):
g = frame.groupby(gcond)
neighbors = len(g)
neighbor = list(g.ngroup() + 1)
... | [
"def fragment_on_bonds(self):\n\n def remove_connection(connections, atom1, atom2):\n if atom2 in connections[atom1]:\n connections[atom1].remove(atom2)\n if atom1 in connections[atom2]:\n connections[atom2].remove(atom1)\n return connections\n\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add to a given position a set of fragments more fragments. | def add_fragments( self, fragments, ini, how='replace' ):
if (self['size'].unique() != fragments['size'].unique()).any():
raise ValueError('Only same-sized fragments can be merged.')
frags = fragments.copy()
df = self.copy()
columns = ['frame', 'neighbor', 'position']
... | [
"def addfragment(self, fragment):\n self.__fragments.append(fragment)",
"def add_fragment(self, fragment, delay_sort=False):\n Segment.add_fragment(self, fragment, delay_sort)\n fragment.chain = self",
"def add_fragment(efpobj, fragments):\n if isinstance(fragments, str):\n fragme... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Limit to the top selected neighbors for each frame. | def sample_top_neighbors( self, max_count=200 ):
df = self.copy()
return df[df['neighbor'] <= max_count].coerce() | [
"def _select_best_tiles(self) -> utils.TileIndices:\n return list(set(\n coordinates for scores_dict in self.__scores\n for coordinates, _ in list(sorted(\n scores_dict.items(),\n key=itemgetter(1),\n reverse=self.__is_high_better,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add RMSD quality measure to the fragment data. The RMSD quality measurement is performed by the ``r_fraq_qual`` application | def add_quality_measure( self, filename, pdbfile=None ):
if filename is None and not self.has_source_file():
raise AttributeError("No quality file is provided and no source file can be found.")
# Make the quality fragmet eval if needed.
if filename is None:
sofi = self._... | [
"def add_quality(df):\n df = pd.concat([df, convert_quality(df['quality'])], \n axis=1)\n\n df['Q_min'] = df.filter(regex='Q_\\d+', axis=1).min(axis=1)\n df['Q_mean'] = df.filter(regex='Q_\\d+', axis=1).mean(axis=1)\n return df",
"def fset(self, quality):\r\n \r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Generate a graph representation of the perresidue frequency. | def make_per_position_frequency_network( self ):
matrix = self.make_sequence_matrix(frequency=True)
g = nx.DiGraph()
for i, row in matrix.iterrows():
if i == matrix.iloc[0].name:
nterm = ["0X", ]
invrow = (1 - row[row > 0])
cterm = [str(i) + ... | [
"def gen_graph(self, seed=None):\n block = make_residue_graph(self.molecule, attrs=('resid', 'resname'))\n resnames = nx.get_node_attributes(block, 'resname')\n graph = nx.Graph()\n graph.add_nodes_from(block.nodes)\n graph.add_edges_from(block.edges)\n nx.set_node_attribut... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Consensus sequence with the highest representative per position. | def quick_consensus_sequence( self ):
consensus = []
for i in range(1, max(self["position"].values) + 1):
values = self[self["position"] == i]["aa"].values
qseq = sorted(Counter(values).most_common(), key=lambda x: (-x[1], x[0]))[0]
consensus.append(qseq[0])
r... | [
"def majority_consensus(self):\n if self.is_empty():\n seq_constructor = Sequence\n else:\n seq_constructor = self[0].__class__\n\n # Counter.most_common returns an ordered list of the n most common\n # (sequence, count) items in Counter. Here we set n=1, and take o... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Consensus secondary structure with the highest representative per position. | def quick_consensus_secondary_structure( self ):
consensus = []
for i in range(1, max(self["position"].values) + 1):
values = self[self["position"] == i]["sse"].values
qseq = sorted(Counter(values).most_common(), key=lambda x: (-x[1], x[0]))[0]
consensus.append(qseq[0... | [
"def secondary_structure(self):\n return self._secondary_structure",
"def _calculate_secondary_structure(seq, window):\n # STRUCTS = {0: \"Helix\", 1: \"Turn\", 2: \"Sheet\"}\n window_sequence = iterutils.windowed(seq, window) # sliding windows\n residue_num = len(seq)\n struct = [0 for _ in r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Queries the blocks status for a specific proposal and returns the blocks code with the specified status. | def get_blocks_status(proposal_code, blocks_status_id):
sql = '''SELECT BlockCode AS block_code
FROM Block
JOIN BlockCode USING (BlockCode_Id)
JOIN ProposalCode USING (ProposalCode_Id)
JOIN BlockStatus USING (BlockStatus_Id)
WHERE Proposal_Code=%s
AND BlockStatus_Id=%s'''
df = pd.read_sql(sql, params=(proposal... | [
"def process_get_block_by_height(\n status: int,\n json: dict,\n network_type: models.NetworkType,\n) -> models.BlockInfo:\n\n assert status == 200\n return models.BlockInfo.create_from_dto(json, network_type)",
"def get_proposals(self, current_block_height: int, type: int = None, status: int = Non... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Cleanup old backups, keeping the number of backups specified by DBBACKUP_CLEANUP_KEEP and any backups that occur on first of the month. | def cleanup_old_backups(self):
print("Cleaning Old Backups for media files")
file_list = utils.get_backup_file_list(
self.get_databasename(),
self.get_servername(),
'media.tar.gz',
self.storage
)
for backup_date, filename in file_list[0:-... | [
"def clean_backups(BCK_BASE_PATH='/backups/sql', DAYS='30'):\n print(white(\"\\tCleaning oldest backups...\"))\n with settings(hide('warnings', 'running', 'stdout', 'stderr')):\n local('find %s -mtime +%s -exec rm -rf {} \\;' % (BCK_BASE_PATH, DAYS))",
"def delete_old_backup(self):\n print \"#... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
findSquares intend to locate rectangle in the image of minimum area, minSize, and maximum angle, maxAngle, between sides | def findSquares(img,minSize = 2000,maxAngle = 1):
squares = []
contours, hierarchy = cv2.findContours(img, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours:
cnt_len = cv2.arcLength(cnt, True)
cnt = cv2.approxPolyDP(cnt, 0.08*cnt_len, True)
if len(cnt) == 4 and cv2.conto... | [
"def find_squares(img,minArea=1000):\n\n squares = []\n\n contours, hierarchy = cv2.findContours(img, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)\n\n for cnt in contours:\n cnt_len = cv2.arcLength(cnt, True)\n cnt = cv2.approxPolyDP(cnt, 0.02*cnt_len, True)\n if len(cnt) == 4 and cv2.contourArea(cnt) > 1000... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Fetch the testing data for a fixed period but the testing start may not in the dataframe So we need to look for the next available start date | def fetch_testing(df, testing_start, curr_date_set, duration=1):
dt_testing_start = dt.datetime.strptime(testing_start, '%Y-%m-%d')
for _ in range(200):
if testing_start in curr_date_set:
dt_testing_end = dt_testing_start + dt.timedelta(days=duration)
break
else:
... | [
"def get_next_earnings(limit: int = 5, start_date: date = date.today()) -> DataFrame:\n base_url = \"https://seekingalpha.com/api/v3/earnings_calendar/tickers\"\n df_earnings = pd.DataFrame()\n\n for _ in range(0, limit):\n start_date = pd.to_datetime(start_date)\n date_str = str(start_date.s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check a proper oidc user can be added. | def test_add_oidc(self, db_session: Session) -> None:
user_service = get_user_service(db_session)
identity_provider = RandomDbAdder().random_identity_provider(db_session)
profile = RandomDbAdder().random_profile(db_session)
oidc_user_dict = InputDictGenerator().random_oidc_user(profile.n... | [
"def test_check_user_known_good(self):\n user_identifier = 'duo-atlas-hypnotism-curry-creatable-rubble'\n test_response = check_user(user_identifier = user_identifier)\n self.assertTrue(test_response)",
"def test_user_can_add(self):\n self.assertTrue(self.asset.user_can_add(self.user1)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check a proper basic user can be added. | def test_add_basic(self, db_session: Session) -> None:
user_service = get_user_service(db_session)
profile = RandomDbAdder().random_profile(db_session)
basic_user_dict = InputDictGenerator().random_basic_user(profile.name)
response = user_service.add_user(**basic_user_dict)
ass... | [
"def test_add_user(self):\n pass",
"def test_can_register_user(self) -> None:\n # Register a new user\n user_id, access_token = self.get_success(\n self.module_api.register(\n \"bob\", displayname=\"Bobberino\", emails=[\"bob@bobinator.bob\"]\n )\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check the get_entity_by rpc functions all return a correct user entity dict. | def test_user_entity_by(self, db_session: Session, get_user: Callable, attribute: str, db_column: Column,
entity_attr: str, entity_column: Column) -> None:
user_service = get_user_service(db_session)
user = get_user(db_session)
profile = db_session.query(Profiles).fil... | [
"async def test_get_entity(self):\n await test_service.get_entity(self)",
"async def get_entity(self):\n if not self.entity and await self.get_input_entity():\n try:\n self._entity =\\\n await self._client.get_entity(self._input_entity)\n excep... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks that val matches expval within tol. | def check_eq(val, expval, tol=None):
if type(val) == dict:
for k in val:
check_eq(val[k], expval[k], tol)
else:
try:
if tol and hasattr(val, '__rsub__'):
are_eq = abs(val - expval) < tol #absolute check
if not are_eq:
ar... | [
"def check_eq(self, val, expval, tol=None):\n\tif type(val) == dict:\n\t for k in val:\n\t\tcheck_eq(val[k], expval[k], tol)\n\telse:\n\t try:\n\t\tif tol and hasattr(val, '__rsub__'):\n\t\t are_eq = abs(val - expval) < tol\n\t\telse:\n\t\t are_eq = val == expval\n\t\tif hasattr(are_eq, 'all'):\n\t\t ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Makes a hash from a dictionary, list, tuple or set to any level, that contains only other hashable types (including any lists, tuples, sets, and dictionaries). | def make_hash(o):
if isinstance(o, (set, tuple, list)):
return hash(tuple([make_hash(e) for e in o]))
elif not isinstance(o, dict) and o.__class__.__module__ == 'builtins':
return hash(o)
elif not isinstance(o, dict):
return make_hash(o.__dict__)
new_o = copy.deepcopy(o)
for... | [
"def make_hash(o):\n\n if isinstance(o, (set, tuple, list)):\n\n return hash( tuple([make_hash(e) for e in o]) )\n\n elif not isinstance(o, dict):\n\n return hash(o)\n\n new_o = copy.deepcopy(o)\n for k, v in new_o.items():\n new_o[k] = make_hash(v)\n\n return hash(tuple(frozenset(sorted(new_o.items()... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Load from l2 or l3 in case of l2 cache miss | def load(self, name: str):
result = self.l2.load(name)
if result is not None:
logging.debug(f'{name} l2 hit')
return result
result = self.l3.load(name, self.l2)
if result is not None:
logging.debug(f'{name} l3 hit')
return result
l... | [
"def _load_cached_2to3(self, path, cache):\n try:\n cache_stats = os.stat(cache)\n source_stats = os.stat(path)\n except OSError as e:\n if e.errno == errno.ENOENT: # FileNotFoundError\n self.logger.debug('Cache miss: %s' % cache)\n return... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Load from l2 or download from l3 in case of l2 cache miss | def download(self, name: str):
result = self.l2.load(name)
if result is not None:
logging.debug(f'{name} l2 hit')
return result
result = self.l3.download(name, self.l2.get_path(name))
if result is not None:
logging.debug(f'{name} l3 hit')
... | [
"def load(self, name: str):\n result = self.l2.load(name)\n if result is not None:\n logging.debug(f'{name} l2 hit')\n return result\n\n result = self.l3.load(name, self.l2)\n if result is not None:\n logging.debug(f'{name} l3 hit')\n return re... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This test confirms that mg flux has many groups when loaded with the history tracker. armi.bookeeping.db.hdf.hdfDB.readBlocksHistory requires historical_values[historical_indices] to be cast as a list to read more than the first energy group. This test shows that this behavior is preserved. | def test_calcMGFluence(self):
o = self.o
b = o.r.core.childrenByLocator[o.r.core.spatialGrid[0, 0, 0]].getFirstBlock(
Flags.FUEL
)
bVolume = b.getVolume()
bName = b.name
hti = o.getInterface("history")
# duration is None in this DB
timesInYea... | [
"def test_get_n_latest_blocks(self):\n\n latest = 5\n number_of_blocks = 15\n wait_for_block(self.network, 5)\n for validator_id in range(self.network.validators_count()):\n height_counter = latest\n host, public_port, private_port = self.network.api_address(validat... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test generation of history report. | def test_historyReport(self):
history = self.o.getInterface("history")
history.interactBOL()
history.interactEOL()
testLoc = self.o.r.core.spatialGrid[0, 0, 0]
testAssem = self.o.r.core.childrenByLocator[testLoc]
fileName = history._getAssemHistoryFileName(testAssem)
... | [
"def test_add_history(self):\n pass",
"def test_get_alert_history(self):\n pass",
"def test_get_ticket_history(self):\n pass",
"def test_get_ticket_history_0(self):\n pass",
"def test_get_team_history(self):\n pass",
"def test_projects_history(self):\n pass",
"d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Roulettewheel (Proportional) solution selection. | def select_roulette(solver, pop, bias=1, minimising=False):
assert min(c.fitness for c in pop) >= 0
assert len(pop) > 0
assert minimising is False # Done to ensure consistency. Check could be moved to solver (roulette can only do maxi)
point = random.uniform(0, sum(c.fitness**bias for c in pop))
#... | [
"def roulette_wheel_selection(population):\n total_fitness = 0.0\n for genome in population:\n total_fitness += genome.fitness\n\n # Ensures random selection if no solutions are \"fit\".\n if total_fitness == 0.0:\n return random.choice(population)\n\n random_point = random.uniform(0.0,... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Select best n solutions from a population | def select_best_n(solver, pop, n, minimising=None):
assert n <= len(pop)
if minimising is None:
minimising = solver.alg_params.minimising
key_f = operator.attrgetter('fitness')
if minimising:
f = copy.deepcopy(sorted(pop, key=key_f, reverse=False))
else:
f = copy.deepcopy(so... | [
"def select_best(self, population, n_best):\n\t\t\t\tfitnesses = []\n\t\t\t\tfor idx, individual in enumerate(population):\n\t\t\t\t\t\tindividual_fitness = self.fitness_function(individual)\n\t\t\t\t\t\tfitnesses.append([idx, individual_fitness])\n\t\t\t\t\n\t\t\t\tcosts_tmp = pd.DataFrame(fitnesses).sort_values(b... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
One point crossover for the SAES | def crossover_one_point_saes(solver, par1, par2, xo_chance=None, point=None):
assert len(par1.es_params) == len(par1.trace)
assert len(par2.es_params) == len(par2.trace)
if xo_chance is None:
xo_chance = solver.alg_params.crossover_rate
r = random.random()
if r < xo_chance:
if point... | [
"def crossover(self, dad, mom):\n pass",
"def crossover(mom, dad):\n n = len(mom.decisions)\n return Point(mom.decisions[:n // 2] + dad.decisions[n // 2:])",
"def twoPointCrossover(self, cl):\n points = []\n changed = False\n points.append( int( random.random() * ( cons.env.format_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Cuts off the top line of the parachute | def cut_line(self):
self.parachute.pop(0) | [
"def mid_top(self):\r\n self.writing_position()\r\n self.half_left()",
"def add_top(self):\n line = \"HDR\"\n self.lines.insert(0, line)",
"def _show_topline(self):\n\n self.scr.erase()\n r = 3\n if self.nosep:\n return 3\n\n if self.topline is ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks to see how much parachute is left. If there is only the guy left, you are dead. Returns true or false. Also changes the guy's head to an 'x' if he is dead. | def is_dead(self):
if len(self.parachute) <= 5:
self.parachute.pop(0)
self.parachute.insert(0, " x")
return True
else:
return False | [
"def is_dead(self):\n return self.hp <= 0",
"def is_left(self):\n if self.pupils_located:\n return self.horizontal_ratio() >= 0.65",
"def player_is_dead(wrong_guesses):\n player_is_dead = False\n\n if len(wrong_guesses) >= 6:\n player_is_dead = True\n\n return player_is_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Announce the agent about your intention to modify the collection. | def assert_modification_intention(self, db_cfg_name, collection_cfg_name):
return self.__assert_collection_change(db_cfg_name,
collection_cfg_name, False) | [
"def pytest_collection_modifyitems(items):\n logger.info(\"no actions taken.\")",
"def updateCollection():\n \n cl.updColletion()",
"def Action(self) -> NotifyCollectionChangedAction:",
"def setListModified(self):\r\n\r\n currentList = self.pdef.getCurrentListObject()\r\n #also set pdef.Modifie... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Tell the agent the collection will be/has been modified. | def __assert_collection_change(self, db_cfg_name, collection_cfg_name,
is_finished):
import time
from ir_config import IRConfig
db_name = IRConfig.get_instance().get(db_cfg_name)
collection_name = IRConfig.get_instance().get(collection_cfg_name)
meta_... | [
"def updateCollection():\n \n cl.updColletion()",
"def modified(self):\n self.notify_observers(\"modified\")",
"def test_update_collection(self):\n pass",
"def assert_modification_intention(self, db_cfg_name, collection_cfg_name):\n return self.__assert_collection_change(db_cfg_name... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Find the information of the collection in meta data. | def __find_collection_in_meta(self, db_name, collection_name):
meta_collection = self.__get_meta_collection(db_name)
return meta_collection.find({self.__meta_key_name : collection_name}) | [
"def _show_metadata(collection_name=None):\n db = _open_db_connection()\n \n # View the metadata record of a given collection (by \"_id\")\n document = db['metadata'].find({'_id': collection_name})\n if document.count() > 0:\n pprint.pprint ((db['metadata'].find({'_id': collection_name}))[0])\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Get the meta collection. | def __get_meta_collection(self, db_name):
connection = self.get_connection()
return connection[db_name][self.__meta_collection_name] | [
"def metaItems(self):\n return self.__meta.items()",
"def meta(self):\n return self._meta",
"def get_collection():",
"def get_metas(self):\n return self.get_meta_classes() + self.get_meta_functions()",
"def meta(self):\n return self.spec.meta",
"def get_meta(filename):\n wit... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Close the collection. It is essential for collection in 'w'/'a' mode. | def close(self):
if self.__mode == 'w' or self.__mode == 'a':
IRMongodbHelper.get_instance().update_meta(
self.__db_name, self.__collection_name, True)
self.__is_closed = True | [
"def _close_collection(self):\n self.output.write(b'{}]') # empty {} so the final entry doesn't end with a comma",
"def __is_collection_close(self):\n if self.__is_closed:\n from ir_log import IRLog\n IRLog.get_instance().println(\n 'Error! Cannot write to closed co... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if current mode supports modifying operation. | def __is_modification_legal_in_current_mode(self):
self.__is_collection_close()
if self.__mode == 'r':
from ir_log import IRLog
IRLog.get_instance().println(
'Error! Cannot write to collection being opened in read mode.')
assert False | [
"def can_modify(self):\n return self._can_modify",
"def has_modify_permissions(self, request, obj, *args, **kwargs):\n return False",
"def can_edit(self):\n utility = self.utility\n poll = self.poll()\n return utility.allowed_to_edit(poll)",
"def can_edit(self):\n ret... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Check if the operation is conducted after the collection is closed. | def __is_collection_close(self):
if self.__is_closed:
from ir_log import IRLog
IRLog.get_instance().println(
'Error! Cannot write to closed collection.')
assert False | [
"def is_closed(self) -> bool:",
"def __is_closed(self):\n with self.__cond:\n return self.__closed",
"def is_closed(self):\n pass",
"def closed(self):\n return self.__closeEvent.is_set()",
"def _check_closed(self):\n if self.closed:\n raise Error(\"cursor is... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
set self._adding_meals to value. If value == True, it assigns False to the other two atributes | def adding_meals(self, value):
self._adding_meals = value
if value:
self._adding_ingridients = not value
self._removing_ingridients = not value | [
"def adding_ingridients(self, value):\n self._adding_ingridients = value\n if value:\n self._adding_meals = not value\n self._removing_ingridients = not value",
"def loading_meals(self, value):\n self._loading_meals = value\n if value:\n self._loading_i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
set self._adding_ingridients to value. If value == True, it assigns False to the other two atributes | def adding_ingridients(self, value):
self._adding_ingridients = value
if value:
self._adding_meals = not value
self._removing_ingridients = not value | [
"def removing_ingridients(self, value):\n self._removing_ingridients = value\n if value:\n self._adding_ingridients = not value\n self._adding_meals = not value",
"def loading_ingridients(self, value):\n self._loading_ingridients = value\n if value:\n s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
set self._removing_ingridients to value. If value == True, it assigns False to the other two atributes | def removing_ingridients(self, value):
self._removing_ingridients = value
if value:
self._adding_ingridients = not value
self._adding_meals = not value | [
"def adding_ingridients(self, value):\n self._adding_ingridients = value\n if value:\n self._adding_meals = not value\n self._removing_ingridients = not value",
"def setFalse(self):\n self.cond = CT.FALSE\n self.left = self.right = None\n self.z3 = BoolSort... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
set self._loading_meals to value. If value == True, it assigns False to the other atribute | def loading_meals(self, value):
self._loading_meals = value
if value:
self._loading_ingridients = not value | [
"def loading_ingridients(self, value):\n self._loading_ingridients = value\n if value:\n self._loading_meals = not value",
"def adding_meals(self, value):\n self._adding_meals = value\n if value:\n self._adding_ingridients = not value\n self._removing_i... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
set self._loading_ingridients to value. If value == True, it assigns False to the other atribute | def loading_ingridients(self, value):
self._loading_ingridients = value
if value:
self._loading_meals = not value | [
"def loading_meals(self, value):\n self._loading_meals = value\n if value:\n self._loading_ingridients = not value",
"def update_waiting(self):\n if self.get_value(0) is None:\n self.set_value(True, 0)\n else:\n self.set_value(not bool(self.get_value(0)... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
it assigns a telegram replay keyboard to self._keyboard | def keyboard(self, value):
if value is None:
self._keyboard = telegram.ReplyKeyboardRemove()
elif value == "add_ingridients":
keyboard = [[key] for key in self.ingridients]
self._keyboard = telegram.ReplyKeyboardMarkup(keyboard)
elif value == "remove_ingridien... | [
"def set_keyboard(self, keyboard: Keyboard) -> None:\n lib.wlr_seat_set_keyboard(self._ptr, keyboard._ptr)",
"def _restore_keyboard(self):\n if hasattr(self, \"original_kbd_settings\"):\n fd = sys.stdin.fileno()\n termios.tcsetattr(fd, termios.TCSADRAIN, self.original_kbd_setti... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
this function handles text messages without commands. Depending on the last command used it might add ingridients from a meal to the list, a particular ingridient, remove an ingridient from the list or do nothing | def text_message(self, update, context):
# check mode
if self.adding_meals:
# text from the message is retrieved
typed_meal = update.message.text
# we get the instance from the meal list. It might be None
meal = self.meal_list.get(typed_meal)
... | [
"def handle_text_messages(self, update, context):\n\n # Split user input into single words\n words = set(update.message.text.lower().split())\n logging.debug(f'Received message: {update.message.text}')\n\n # For debugging: Log users that received something from bot\n chat_user_cli... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
if the commands /load_meals or /load_ingridients were used, this will save files with the code of the chat | def file_message(self, update, context):
# asigns file_tipe according to the program status
if self.loading_meals:
file_type = "_meals"
elif self.load_ingridients:
file_type = "_ingridients"
else:
# if the script isn't loading_meals or loading_ingridie... | [
"async def trainer():\r\n #check if the path to the file exists\r\n if not os.path.exists(\"data/player\"):\r\n await bot.say(\"data/player folder does not exist!\")\r\n await bot.say(\"Creating data/player folder...\")\r\n os.makedirs(\"data/player\")\r\n else:\r\n await bot.say(\"Fol... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
gets size of table | def get_size(self):
return len(self.table) | [
"def get_table_size_from_IS(self, table_name):\n result = self.query(sql.show_table_stats(self._current_db), (self.table_name,))\n if result:\n return result[0][\"Data_length\"] + result[0][\"Index_length\"]\n return 0",
"def get_table_size(self, table_name):\n # Size of the... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
gets left child for parent if exists | def left_child(self, position):
child = 2 * position + 1
if child > len(self.table) - 1:
return None
return child | [
"def get_left_child(\n self\n ):\n return self.left_child",
"def remove_left(self):\n temp = self._leftchild\n self._leftchild.set_parent(None)\n self.set_leftchild(None)\n return temp",
"def _get_left_child(self, parent_index):\n return 2 * parent_index",... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
search for value in table, return item index if exists | def find(self, value):
for position in range(self.get_size()):
if self.table[position] == value:
return position | [
"def find(self, list, key, value):\n for i, dic in enumerate(list):\n if dic[key] == value:\n return i\n return -1",
"def find(self, value):\n if self.total == 0\n return None\n\n current_item = self.head\n current_index = 0\n while cu... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
pop specified value from heap them promote children if applicable | def heap_pop(self, value):
if value is None or self.get_size() == 0:
return
if self.find(value) is not None:
# end of list
position = self.find(value)
last = self.get_size() - 1
# pop element and percolate down
self.swap(position,... | [
"def _heapify_after_remove(self,ele):\r\n \r\n if self._chk_left(ele):\r\n left = self._left(ele)\r\n find_small_child = left\r\n # below to find which child has small integer\r\n if self._chk_right(ele):\r\n right = self._right(ele)\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Visualize cumulative rewards for all agents | def show_rewards(agents, fname=None):
fig = plt.figure()
ax = plt.subplot(111)
box = ax.get_position()
ax.set_position([box.x0, box.y0, box.width * 0.8, box.height])
ax.set_ylabel('Cumulative Reward')
for agent in agents:
agent.show_rewards()
ax.legend([a.id for a in agents], loc='ce... | [
"def visualize(self):\n print ' '.join(['agent is', str(self.timestep), 'time steps old'])\n self.reward_history.append(float(self.cumulative_reward) / \n (self.time_since_reward_log + 1))\n self.cumulative_reward = 0 \n self.time_since_reward_log = 0... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Funcion que cuenta cantidad de arrobas "@" devuelve True si cantidad de @ es 1 devuelve False si cantidad de @ es 1 | def count_ats(str):
contador_de_arrobas=0
for char in str:
if char == "@":
contador_de_arrobas+=1
if contador_de_arrobas == 1 :
return True
else:
return False | [
"def validaAnnoe(anno):\n valid = ((len(anno) == 4) and (int(anno)) > 2000)\n if (valid and((len(anno) == 4) and (int(anno)) > 2000)):\n valid=True\n if(valid == False):\n print(\"fechas invalidas.\")\n labelinformativo('fechas invalidas')\n return valid",
"def comprueba_mail(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
List of variables in the graphical model; equals model.X | def vars(self):
return [Var(i,self.dims[i]) for i in range(self.nvar)] # TODO: use stored state info (=1 sometimes) | [
"def variables(model):\r\n return model.keys()",
"def variables(model):\n return model.keys()",
"def variables(self):\n return [i.name for i in self.inputs + self.outputs]",
"def variables(model: Model) -> AbstractSet[str]:\r\n assert is_model(model)\r\n return model.keys()",
"def variabl... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a variable object (with states) for id 'i'; equals model.X[i] | def var(self,i): # TODO: change to property to access (read only?) X?
return Var(i,self.dims[i]) | [
"def vars(self):\n return [Var(i,self.dims[i]) for i in range(self.nvar)] # TODO: use stored state info (=1 sometimes)",
"def get_variable_from_model(self,modeltype,obsname):\n return get_variable_from_model(self.getmodel(modeltype),obsname)",
"def getStateIndexByIndex(self, i):\n if i >= 0:\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The number of factors in the model | def nfactors(self):
return self.L.nnz | [
"def NFactors(x: int) -> int:\n return len(factors(x))",
"def get_number_of_models():\n return 8",
"def get_number_of_classes(self):\n return self.N",
"def n_classifiers_per_level(self):\n return [len(clf) for clf in self.classifiers]",
"def nr_predictors(self):\n return self._nr_pred... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a list of factors (converted to tables) in the model that contain the variable 'v' | def factorsWith(self,v,copy=True):
Lv = self.L.getrow(v).tocoo();
factors = [Factor([Var(int(v),2)],[-th,th]).exp() for th in [self.h[v]] if self.dims[i]>1]
factors = factors + [Factor([Var(int(v),2),Var(int(j),2)],[[th,-th],[-th,th]]).exp() for j,th in zip(Lv.col,Lv.data)]
return factors | [
"def factorsWithAny(self,vs):\n factors = []\n for v in vs:\n factors += [Factor([Var(int(v),2)],[-th,th]).exp() for th in [self.h[v]] if self.dims[i]>1]\n for u in self.markovBlanket(v):\n if u not in vs or v < u:\n factors += [Factor([Var(int(v),2),Var(int(u),2)],[[th,-th],[-th,th]... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a list of factors (converted to tables) in the model that contain any of the variables in 'vs' | def factorsWithAny(self,vs):
factors = []
for v in vs:
factors += [Factor([Var(int(v),2)],[-th,th]).exp() for th in [self.h[v]] if self.dims[i]>1]
for u in self.markovBlanket(v):
if u not in vs or v < u:
factors += [Factor([Var(int(v),2),Var(int(u),2)],[[th,-th],[-th,th]]).exp() fo... | [
"def _variations(self):\n\n\t\treturn self.parameter_set!=self.parameter_set[self._fiducial]",
"def get_all_matching_models(grep='trail'):\n lst = []\n for make, model in cars.items():\n for version in model:\n if grep.upper() in version.upper():\n lst.append(version)\n r... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return the Markov Blanket (list of neighbors) of a given variable in the model | def markovBlanket(self,v):
return VarSet([Var(int(i),2) for i in self.L.getrow(int(v)).nonzero()[1]])
#return self.L.getrow(int(v)).nonzero()[1].astype(int) | [
"def markov_blanket(self,variable):\n return self._hypergraph.neighbours(variable)",
"def markov_blanket(self,beta,alpha): \n likelihood_blanket = self.m_likelihood_markov_blanket(beta,alpha)\n state_blanket = self.state_likelihood_markov_blanket(beta,alpha,0)\n for i in range(self.sta... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Find the connected components of the model's Markov graph. Returns a list of sets of variables. | def connectedComponents(self):
components = []
X = set(self.X)
while X:
Xi = X.pop()
if Xi.states <= 1: continue # don't include missing or assigned variables
group = {Xi} # start a new group with this variable
queue = [Xi] # do DFS on the... | [
"def nxMarkovGraph(self, all_vars=False):\n import networkx as nx\n return nx.from_scipy_sparse_matrix(self.L!=0)",
"def get_model_variables():\n g = tf.get_default_graph()\n return set(g.get_collection(tf.GraphKeys.MODEL_VARIABLES))",
"def connected_components(graph):\n return list(nx.connected_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Return a networkx object representing the Markov graph of the Ising model | def nxMarkovGraph(self, all_vars=False):
import networkx as nx
return nx.from_scipy_sparse_matrix(self.L!=0) | [
"def get_network_graph(mtf):\n # Build the graph with networkx:\n graph = nx.from_numpy_matrix(mtf)\n \n # Loops through the edges to get associate each of them with the\n # corresponding Markov transition probability:\n weights = [mtf[u,v] for u,v in graph.edges()]\n for index, e in enumerate(... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Compute the pseudo (log) likelihood, \sum_i \sum_j \log p(x^{(j)}_i | x^{(j)}_{\neg i}) | def pseudolikelihood(self, data):
data = toPM(data); # interface glue: convert {0,1} to {-1,+1}
r = self.L.dot(data)
r += self.h.reshape(-1,1) if len(data.shape)==2 else self.h
lnp = -np.log(1+np.exp(-2*data*r)) # ln p(x_i^(s)|x_{-i}^(s)) for all vars i, samples s
return lnp.su... | [
"def calculate_negative_log_likelihood(self):\n data = self.played_points_hist[:self.t]\n kernel_matrix = self.kernel_fn(data, data, self.best_ard_params)\n c_matrix = kernel_matrix + (self.noise_sigma ** 2) * np.eye(data.shape[0])\n c_matrix_inv = np.linalg.inv(c_matrix)\n first_... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Estimate an Ising model using Bresler's greedy edge selection approach | def fit_greedy(data, nnbr=10, threshold=0.05, refit=refit_pll):
n,m = data.shape;
L = np.zeros((n,n)) # initialize parameters
scores = np.zeros(n)
data = data.astype(int)
for i in range(n):
Ni = []
while (len(Ni)<nnbr):
Vi = (0*data[i,:] + sum(data[j,:]*(2**jj) for ... | [
"def optimise(self):\n \n #LOG.info(\"Optimising\")\n #self.network.optimise_igp_weights() ",
"def simulated_anneal(model, kmax=1500, cooling=1):\n def anneal(old, new, temp):\n a = math.e**((old - new)/temp)\n b = random.random()\n return a < b\n print(model)\n print(\"Params ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Run loopy belief propagation (specialized for Ising models) lnZ, bel = LBP(ising, maxIter, verbose) | def LBP(ising, maxIter=100, verbose=False):
# TODO: pass requested beliefs (like JT?), or "single", "factors", etc.
assert isinstance(ising,Ising), "Model must be an Ising model for this version to work"
R = ising.L.tocoo(); row = R.row; col = R.col;
mu = csr(([],([],[])),shape=ising.L.shape)
L_tanh... | [
"def bps_main(model, num_results, num_burnin_steps,\n bnn_neg_joint_log_prob, map_initial_state, X_train,\n y_train, X_test, y_test):\n print('running bps')\n kernel = BPSKernel(\n target_log_prob_fn=bnn_neg_joint_log_prob,\n store_parameters_in_results=True,\n lambda_ref=0.5)\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Returns False if the package version or newer is already installed, False otherwise. | def _checkUpdateNeeded(self):
try:
currentVersionLine = str(subprocess.run(['pacman', '-Q', '-i', self._name],
stdout=subprocess.PIPE, stderr=subprocess.STDOUT, check=True).stdout)
currentVersion = re.sub(r'.*Version\s*: ([\d|\.]*)-.*', r'\1', cur... | [
"def is_installed(self):\n return not self.dont_install",
"def is_installed(self):\n return not run('mvn dependency:get -Dartifact={}:{} --offline'.format(\n self.package,\n self.version), stdout=Capture(),\n stderr=Capture()).returnc... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
do builder; in this case, old time stamp is removed from filename and a new time stamp is append to the filename | def build_base_filename(self):
if self.stream:
self.stream.close()
self.stream = None
# remove old suffix
# if self.suffix_time != "":
# index = self.baseFilename.find("." + self.suffix_time)
# if index == -1:
# index = self.baseFi... | [
"def build_base_filename(self):\n if self.stream:\n self.stream.close()\n self.stream = None\n\n # remove old suffix\n if self.suffix_time != \"\":\n index = self.baseFilename.find(\".\" + self.suffix_time)\n if index == -1:\n index = s... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Replaces incorrect words with the closest correct one If no such word is found, commence splitting in split_word | def replace_nearest(word):
nearest = spellcheck.correction(word)
#When there is no valid word, the nearest word
#is the same as the original
if word == nearest:
#This implies we need to try splitting it
return split_word(word)
return nearest | [
"def eng_word_correction(text):\n import enchant\n d = enchant.Dict(\"en_US\") # create dictionary for US English\n# language_model = load_lm('bigrams.pkl')\n text = text.lower()\n text = \"<s> \" + text + \" </s>\"\n text = text.split()\n for n, m in enumerate(text):\n if m != \"<s>\" ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that the ``from_crawler`` method should initialize the selenium driver | def test_from_crawler_method_should_initialize_the_driver(self):
crawler = Crawler(
spidercls=self.spider_klass,
settings=self.settings
)
selenium_middleware = SeleniumMiddleware.from_crawler(crawler)
# The driver must be initialized
self.assertIsNotNone... | [
"def init_driver(request):\n driver = webdriver.Chrome(\n CHROME_PATH, options=opts)\n if BROWSER.lower() == 'firefox':\n driver = webdriver.Firefox()\n\n driver.get(URL)\n driver.maximize_window()\n request.cls.driver = driver\n yield\n print(d... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that the ``spider_closed`` method should close the driver | def test_spider_closed_should_close_the_driver(self):
crawler = Crawler(
spidercls=self.spider_klass,
settings=self.settings
)
selenium_middleware = SeleniumMiddleware.from_crawler(crawler)
with patch.object(selenium_middleware.driver, 'quit') as mocked_quit:
... | [
"def close_spider(self, spider):\n pass",
"def spider_closing(spider):\n logger.info(\"Spider closed: %s\" % spider)\n if True:\n reactor.stop()",
"def spider_closing(spider):\n print(\"Spiderclose\"*10)\n #reactor.stop()",
"def close_spider(self, spider):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that the ``process_request`` should return a request if not selenium request | def test_process_request_should_return_the_request_if_not_selenium_request(self):
scrapy_request = Request(url='http://not-an-url')
self.assertEqual(
self.selenium_middleware.process_request(
request=scrapy_request,
spider=None
),
scr... | [
"def test_process_request_should_return_a_response_if_selenium_request(self):\n\n selenium_request = SeleniumRequest(url='http://www.python.org')\n\n html_response = self.selenium_middleware.process_request(\n request=selenium_request,\n spider=None\n )\n\n # We hav... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that the ``process_request`` should return a response if selenium request | def test_process_request_should_return_a_response_if_selenium_request(self):
selenium_request = SeleniumRequest(url='http://www.python.org')
html_response = self.selenium_middleware.process_request(
request=selenium_request,
spider=None
)
# We have access to th... | [
"def test_process_request_should_return_the_request_if_not_selenium_request(self):\n\n scrapy_request = Request(url='http://not-an-url')\n\n self.assertEqual(\n self.selenium_middleware.process_request(\n request=scrapy_request,\n spider=None\n ),\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Test that the ``process_request`` should return a response with a screenshot | def test_process_request_should_return_a_screenshot_if_screenshot_option(self):
selenium_request = SeleniumRequest(
url='http://www.python.org',
screenshot=True
)
html_response = self.selenium_middleware.process_request(
request=selenium_request,
... | [
"def test_screenshot_create(self):\n pass",
"def test_screenshot_show(self):\n pass",
"def screenshot(request):\n if not settings.SCREENSHOT_FEATURE:\n raise Http404\n\n # read payload\n try:\n payload = json.loads(Signer().unsign(request.GET.get('payload', '')))\n except... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
An argument parser as an initializing function | def initialize():
parser = argparse.ArgumentParser(
description='This function takes a gene count file, a gene name, and \
an output file as parameters, and creates a file with the \
sample IDs and counts for that gene.')
parser.add_argument('-i',
... | [
"def __init__(self, *args, **kwargs):\n\t\tconfig_file = None\n\t\tif len(args) > 0:\n\t\t\tconfig_file = args[0]\n\t\t\targs = args[1:]\n\t\targparse.ArgumentParser.__init__(self, *args, **kwargs)\n\t\tinit(config_file)\n\t\tfor name in parameters:\n\t\t\ttyp = type(parameters[name][\"value\"])\n\t\t\tself.add_arg... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
check if brain has lead image | def brain_has_lead_image(self, brain=None): | [
"def is_ball(self, blob, im):\n size=self.cam.info.get_pixel_size(blob[0], im)*len(blob)\n return size>15 and size<45",
"def check_availability(img_path):\n # loading gray image\n gray_image = cv2.imread(img_path, 0)\n\n # check whether img give empty list or not\n flag = face_recognitio... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
return the issue obj | def get_issue(self, context): | [
"def get_issue(self):\n issue_id = self.kwargs['issue_id']\n try:\n issue = Issue.objects.get(pk=issue_id)\n except ObjectDoesNotExist:\n raise ObjectNotFound('Not found')\n if issue.project.pk != self.project.pk:\n raise ObjectNotFound('Not found')\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
return a list of result sets based on aggregation sources | def get_results_from_aggregation_sources(self, context): | [
"def _aggregate_results(self): \n\n processed_results = self._group_and_reduce()\n\n if self.config[\"core\"].get(\"scan_result_aggr_scheme\", \"\").upper() == \"MULTIPLE\":\n return processed_results\n\n if self.config[\"core\"].get(\"scan_result_aggr_scheme\", \"\").upper() == \"SI... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
filter given list by portal_type | def type_filter(self, items, types=None):
if not types:
return items
allowed_items = []
for item in items:
if item.portal_type not in types:
continue
allowed_items.append(item)
return allowed_items | [
"def filter_by_type(lst, acceptedtype):\n return _filter(lst, lambda x: isinstance(x, acceptedtype))",
"def search_portal_types(self):\n context = Acquisition.aq_inner(self.context)\n #local_portal_types = context.getProperty('search_portal_types', []);\n # we need to use the output of sea... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Confirm that backup reserve sensor is not added if data is unavailable from the device. | async def test_sensor_backup_reserve_unavailable(hass: HomeAssistant) -> None:
mock_powerwall = await _mock_powerwall_with_fixtures(hass)
mock_powerwall.get_backup_reserve_percentage = Mock(
side_effect=MissingAttributeError(Mock(), "backup_reserve_percent", "operation")
)
config_entry = MockC... | [
"def is_backup_available(tenant_id, auth_token, backup_id):\n content = backup_details(tenant_id, auth_token, backup_id)\n while content[\"backup\"][\"status\"] == \"creating\":\n time.sleep(5)\n content = backup_details(tenant_id, auth_token, backup_id)\n if content[\"backup\"][\"status\"] =... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The 'request' parameter is set for custom auth use by subclasses. The form data comes in via the standard 'data' kwarg. | def __init__(self, request=None, *args, **kwargs):
self.request = request
self.user_cache = None
super(AuthForm, self).__init__(*args, **kwargs) | [
"def __init__(self, request=None, *args, **kwargs):\n self.request = request\n self.user_cache = None\n super(AuthenticationFormCustom, self).__init__(*args, **kwargs)",
"def set_input_data(self, request, auth_data):\n request.auth_data = auth_data",
"def form_for_request(request, Fo... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
this converts a multiline string into a list of individual lines=entries, stripped of white spaces and \n newlines. | def parse_multiline_string(s):
result = [x.strip() for x in s.strip().split('\n')]
return result | [
"def list_of_lines(s):\n return s.split('\\n')",
"def to_lines(s: str) -> list[str]:\n lines = s.splitlines(True)\n if not lines:\n return [\"\"]\n if lines[-1].splitlines() != [lines[-1]]:\n lines.append(\"\")\n for i, ln in enumerate(lines):\n l2 = ln.splitlines()\n as... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
main method, shifts between the three modes and rules to utilize depending on context and feedback. | def main()-> None:
print("Mode One - One time rules")
conflict_check()
init_safeboard()
corner_init_check()
squeeze_rules()
progress_handler(False, True)
print("Mode Two - iterative rules")
while progress_handler():
progress_handler(False, False)
mark_check()
... | [
"def main():\r\n\r\n # Information about this program\r\n program_info = {\r\n\r\n # Program and Contact Info\r\n 'name':'IMPROV Trainer',\r\n 'version': '1.0',\r\n 'author':'Matt Weir',\r\n 'contact':'cweir@vt.edu',\r\n\r\n # Standard Options\r\n 'rule_name':'... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks for squeezed variables (4_2_4), which signify a safe mark in the middle and rule of three (4_4_4), which signifies a crossing of edge values. Updates conflict_board when done. | def squeeze_rules() -> None:
for x in range(shape):
for y in range(1, shape-1):
# Vertical check
if conflict_space[x, y+1] == conflict_space[x, y-1] and conflict_space[x, y+1] != 0:
if conflict_space[x, y] == conflict_space[x, y+1]:
example[x... | [
"def special_corner() -> None:\r\n if example[1, 1] == 0: # NW\r\n if conflict_space[0, 0] == conflict_space[0, 2] and conflict_space[2, 0] == conflict_space[0, 0] \\\r\n and conflict_space[0, 0] != 0:\r\n example[0, 0] = 0\r\n safeboard[0, 0] = 0\r\n progr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Progress value is used to determine if program need to switch ruleset or determine progress. operation defines read if true, write if false. Setstate defines what to write. Used by most function to indicate that it has done an operation | def progress_handler(operation: bool = True, setstate: bool = False) -> bool:
global progress
if operation:
return progress
else:
if setstate:
progress = True
else:
progress = False
return progress | [
"def set_progress(self, progress: float):",
"def set_Progress(self,func):\n self.__obj.set_Progress(func)",
"def setOperationState(self, state):\n self.in_oper = state\n return self.in_oper",
"def _setProgress(self):\n\n self.progress = (self.iteration, self.iterationCount)",
"def start_main... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
First level iterative checker. Iterates through whole conflict_space and checks for each cell. If the value of the cell is not marked as safe (i.e. cannot me crossed,1), and it is only in conflict with one other cell then it marks itself. Includes horizontal and vertical check. | def mark_check() -> None:
for i in range(shape):
y = i
can_mark = False
conflict_counter = 0
# Horizontal Check
for j in range(shape):
x = j
for z in range(shape):
if conflict_space[x, y] == conflict_space[z, y] and x != z an... | [
"def victory_checker() -> bool:\r\n conflict_check()\r\n for x in range(shape):\r\n for y in range(shape):\r\n if conflict_space[x, y] != 0:\r\n return False\r\n if separation_crawler(False):\r\n return False\r\n return True",
"def markEdgesAsSafe(self):\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Based on input coords, mark surrounding cells and itself as safe in the safe_board | def shade_neighbours(x: int, y: int) -> None:
if x > 0:
safeboard[x-1, y] = 0
if x < shape-1:
safeboard[x+1, y] = 0
if y > 0:
safeboard[x, y-1] = 0
if y < shape-1:
safeboard[x, y+1] = 0
safeboard[x, y] = 0 | [
"def markEdgesAsSafe(self):\n # Iterate over all rows\n for i in range(self.gridSize):\n # Iterate over all columns\n for j in range(self.gridSize):\n # Check if cell is along an edge\n if i == 0 or j == 0 or i == self.gridSize-1 or j == self.gridSiz... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Verifies if victory is reached. Requires that conflict_space is empty and separation crawler to not find any divided partitions. Returns True if victory is reached, False if not | def victory_checker() -> bool:
conflict_check()
for x in range(shape):
for y in range(shape):
if conflict_space[x, y] != 0:
return False
if separation_crawler(False):
return False
return True | [
"def check_for_collisions(self):\n \n # INSERT HERE - check for collisions with edge of window\n \n # INSERT HERE - check for collisions with obstacles ",
"def collision_check(self):\n return True",
"def _check_for_completion(self, node):\n dis=0\n for i in ran... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Writes end output. state determines if solution(T) or failure(F) output. Ends program. | def completion(state: bool) -> None:
if state:
print("Solution is reached. Zero represents marked nodes")
print_debug("checkstate")
print("Preferred output:")
for y in range(shape):
for x in range(shape):
if example[y, x] == 0:
... | [
"def end(self):\n self.end_work(\"full_analysis\")\n self.write()",
"def end_output(self):\n self._output_ended = True",
"def end(self):\n self.my_print(\"\\t[DONE]\", msg_types.INFO)\n self.in_progress = False",
"def state_print_exit(cfg, app, win):",
"def printFinalState... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Mode two rule, rarer situations. This one marks the corner if it is in conflict two direct spaces away and inner corner is marked.Avoids getting blocked in. | def special_corner() -> None:
if example[1, 1] == 0: # NW
if conflict_space[0, 0] == conflict_space[0, 2] and conflict_space[2, 0] == conflict_space[0, 0] \
and conflict_space[0, 0] != 0:
example[0, 0] = 0
safeboard[0, 0] = 0
progress_handler(False,... | [
"def squeeze_rules() -> None:\r\n for x in range(shape):\r\n for y in range(1, shape-1):\r\n # Vertical check\r\n if conflict_space[x, y+1] == conflict_space[x, y-1] and conflict_space[x, y+1] != 0:\r\n if conflict_space[x, y] == conflict_space[x, y+1]:\r\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
This is mode three. The system has now determined that it cannot solve it with the rules available and needs to start guessing. Creates a list of all cells left in conflict and does one last test. If crossing one with the most conflicts doesn't solve it, it switches mode into a depth first search function that iterates... | def occam_razor() -> None:
print("WARNING! Mode three activated. Time to complete may be several minutes")
temp = [] # x-y-conflicts
global example
backup = example.copy() # Backup so it can backtrack through solutions
for x in range(shape):
for y in range(shape):
confli... | [
"def backtrack():\n for position in positions:\n if solution[position] == -1:\n for rule_idx in candidate_rules:\n if compat[position, rule_idx] == 1:\n solution[position] = rule_idx\n candidate_rules.remove(rule_idx)\... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Number of the previous page. | def prev_num(self):
return self.page - 1 | [
"def previous_page(self) -> int:\n return max(1, self.page - 1)",
"def get_previous_page(self):\n return max((self.get_page() - 1), self.get_first_page)",
"def prev_page(self):\n if self.current_page - 1 >= 1:\n self.current_page -= 1\n return self.get_current_page()\n... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Number of the next page | def next_num(self):
return self.page + 1 | [
"def next_num(self):\n return self.page + 1 if self.has_next else None",
"def next_page(self) -> int:\n return min(self.total_pages, self.page + 1)",
"def get_num_of_pages(self):",
"def next_page(self):\n return self._next_page",
"def next_page(self):\n cur_pg = self.get_curr... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Move forward in the page history. | def forward(
self
) -> None:
if not self._forward_page_history_stack:
# Do nothing if there is no forward page history.
return
self._back_page_history_stack.append(self._current_page)
self._current_page = self._forward_page_history_stack.pop() | [
"def goForward(self):\r\n if self.currLoc + 1 < len(self.history):\r\n self.currLoc += 1\r\n return self.history[self.currLoc]",
"def navigateForward(self):\n if len(self.future) > 0:\n self.history.append(self.location)\n self.location = self.future.pop()\n self.connect... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The class used to create new directory pages. | def directory_page_cls(
self
) -> Type[DirectoryPage]:
return self._directory_page_cls | [
"def create_page(self):",
"def add_directory_page(\n self,\n path: PagePathLike\n ) -> DirectoryPage:\n dir_page = self.directory_page_cls(path)\n\n try:\n self.set_page(PagePath(path), dir_page, allow_overwrite=False)\n except BlockedPageOverwriteError as e:\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The root page within this navigator. | def root_page(
self
) -> AbstractPage:
return self._root_page | [
"def get_root_page(self):\n return Page.get_first_root_node()",
"def main_page(self):\n return self.server._my_main_page",
"def get_root_site(self):\n return self.get_site('root')",
"def root():\n return render_template('home.html')",
"def _currentPage(self):\n view = self... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
The current page within this navigator. | def current_page(
self
) -> AbstractPage:
return self._current_page | [
"def current_page(self):\n return self._current_page",
"def _currentPage(self):\n view = self._window.currentBrowser()\n if view is None:\n return None\n \n return view.page()",
"def current_page(self):\n return int(self._current_page.value)",
"def GetCurre... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Add a directory page at the specified path. This method is only used for adding pages that do not already exist. It will also create any intermediate directories within the path that do not already exist. | def add_directory_page(
self,
path: PagePathLike
) -> DirectoryPage:
dir_page = self.directory_page_cls(path)
try:
self.set_page(PagePath(path), dir_page, allow_overwrite=False)
except BlockedPageOverwriteError as e:
raise e
return dir_page | [
"def add_directory(self, path):\n self._backend.add_plugin_directories(path)\n self._cache = None",
"def add_dir(self, path):\n if self.validate(path):\n self._watch_manager.add_watch(path, EVENT_MASK, rec=True)\n self._walk_thread = WalkDirectoryThread(self, path,\n ... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Checks if this map_obstacle is capable of movement. | def can_move(self):
return self.movement | [
"def is_able_to_move(self):\n return len(self.adjacent_unoccupied_locations()) > 0",
"def check_movement(self):\n is_clear = True # default return value if no obstacles\n # !!! IR_SENSORS DISABLED\n if self.move_state == MOV_FORWARD:\n if self.l.look_for_obstacl... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Figure out the sight range of this map_obstacle. | def _get_sight_range(self):
raise NotImplementedError | [
"def sight_range(self) -> Union[int, float]:\n return self.type_data.proto.sight_range",
"def check_map_obstacle_has_sight(self):\n return self.map_obstacle.sight_range > 0",
"def getBounds(self):\n resp = self.getBoundsProxy()\n lower = resp.lower_bound\n upper = resp.upper_b... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Constructs a ``ThreatZone`` based on a graph of a map and a particular object on that map. | def __init__(self, map_obstacle, main_graph):
self.map_obstacle = map_obstacle
self.main_graph = main_graph
self.sight_range = self.calculate_sight_range()
self.top_left_y = None
self.top_left_x = None
self.bottom_right_y = None
self.bottom_right_x = None
... | [
"def new(topo):\n\t\treturn Tile(topo)",
"def timemap_object(self):\n tm = TimeMap(original=self.original, timegate=self.original, timemap=self.uri)\n for contained in self.contains:\n datetime = 'Tue, 20 Jun 9999 10:11:12 GMT' # FIXME - need datetime for Mementos\n tm.add_mem... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |
Calculate the bounds of the threat zone based on the map obstacle. Returns the top left corner (y, x) and the bottom right corner (y, x) in the form of ((y, x), (y, x), height, width). | def calculate_size(self):
top_left_y = 0
top_left_x = 0
bottom_right_y = 1
bottom_right_x = 1
# TODO: calculate the correct bounds of the threat zone.
raise NotImplementedError
# if there is a sight_range for this map_obstacle then increase the size of the zon... | [
"def get_bounds(self):\n bottom_right = np.asarray([self.coords[k][0] for k in range(self.dim)])\n upper_left = np.asarray([self.coords[k][-1] for k in range(self.dim)])\n return bottom_right, upper_left",
"def get_bounds(self):\n\n northing=self.f.variables['y']\n easting=self.... | {
"objective": {
"paired": [],
"self": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} |