query
stringlengths
9
9.05k
document
stringlengths
10
222k
negatives
listlengths
19
20
metadata
dict
Get a new table from rows between start and end index.
def get_slice(self, start: Optional[Index] = None, end: Optional[Index] = None): index = self._slice_index(slice(start, end)) return self.get_table(index, self._columns)
[ "def copy_table(tbl, start=0, stop=None, blen=None, storage=None,\n create='table', **kwargs):\n\n # setup\n names, columns = _util.check_table_like(tbl)\n storage = _util.get_storage(storage)\n blen = _util.get_blen_table(tbl, blen)\n if stop is None:\n stop = len(columns[0])\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets multiple cell values at a time. Both `indexes` and `columns` can be scalar or listlike, which enables setting individual cells, rows/columns, or regions. If `values` is scalar, all matching cells will be set to that value. Otherwise the length should match the cell count defined by the other parameters.
def set(self, indexes=None, columns=None, values=None): indexes = to_list(if_none(indexes, self.index)) columns = to_list(if_none(columns, self._columns)) size = len(indexes) + len(columns) values = to_list(values, size=size) if not len(values) == size: raise ValueEr...
[ "def set_values(self, vals):\n for i, g in enumerate(self.genes):\n g.set_value( vals[i] )", "def set_all_values(self, values):\n return self.display_table.set_all_values(values,root=self.display_table_root,include=self.params)", "def set_col(self, col: int, values: list) -> None:\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set individual cell value. If either index or column is missing, they are created.
def set_cell(self, index, column, value): try: idx = self.index_location(index) except (IndexError, ValueError): idx = self._add_row(index) try: col = self.column_location(column) except (IndexError, ValueError): col = self._add_column(col...
[ "def setCell(self, row = None, column = None, value = None, *, cell = None):\n\n\t\t\t\tif (cell is None):\n\t\t\t\t\tcell = self.getCell(row = row, column = column)\n\n\t\t\t\tif (value is None):\n\t\t\t\t\tvalue = \"\"\n\n\t\t\t\t#Write Value\n\t\t\t\tfor _cell in self.ensure_container(cell):\n\t\t\t\t\t_cell.val...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set values in row. If index is missing, it is created.
def set_row(self, index, values): try: idx = self.index_location(index) except (IndexError, ValueError): idx = self._add_row(index) column_values = self._column_value_getter(values) row = [column_values(values, column) for column in self._columns] self._...
[ "def set_row(self, row: int, values: list) -> None:\n for i, _ in enumerate(values):\n self.values[row][i] = values[i]", "def updateRow(self, index: int) -> None:\n ...", "def set_row_values(self, row, value_list=[]):\n for col, value in enumerate(value_list):\n if col...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set values in column. If column is missing, it is created.
def set_column(self, column, values): values = to_list(values, size=self.size) if len(values) != self.size: raise ValueError( f"Values length ({len(values)}) should match data length ({self.size})" ) if column not in self._columns: self._add_...
[ "def set_column_values(self, col, value_list=[]):\n for row, value in enumerate(value_list):\n if row in self.entries.keys():\n if row in self.entries and col in self.entries[row]:\n self.entries[row][col].set_value(value)", "def set_col(self, col: int, values: ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Append multiple rows to table.
def append_rows(self, rows): for row in rows: self.append_row(row)
[ "def add_rows(self):\n for row in self.rows:\n self.table.add_row(row)", "def UpdateRows(self, table, rows):\n table.AddRows(rows)", "def addRows(self, rows):\n command = AddRowsCommand(self, rows)\n command.execute()", "def add_items(self,table,row_list):\n row_count...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove rows with matching indexes.
def delete_rows(self, indexes: Union[Index, List[Index]]): indexes = [self.index_location(idx) for idx in to_list(indexes)] unknown = set(indexes) - set(self.index) if unknown: names = ", ".join(str(name) for name in unknown) raise ValueError(f"Unable to remove unknown r...
[ "def remove_indexes(self, indexes):\n # Create a set of the rows (as int) to delete\n selected_rows = set()\n for index in indexes:\n selected_rows.add(index.row())\n\n # Delete all of them one by one (easy but maybe not the best performance-wise)\n for index, row in en...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Append data from table to current data.
def append_table(self, table): if not table: return indexes = [] for idx in table.index: index = self.size + idx indexes.append(index) self.set(indexes=indexes, columns=table.columns, values=table.data)
[ "def add_data(self, data):\n if not data:\n raise ValueError\n if not self.table_data:\n self.table_data = [data]\n else:\n if len(self.table_data[0]) == len(data):\n self.table_data.append(data)\n elif len(self.table_data[0]) < len(dat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Group rows by column value and return as list of tables.
def group_by_column(self, column): ref = self.copy() ref.sort_by_column(column) col = self.column_location(column) groups = groupby(ref.data, itemgetter(col)) result = [] ref.clear() for _, group in groups: table = ref.copy() table.append...
[ "def group_table_by_column(self, table: Table, column: Column) -> List[Table]:\n self._requires_table(table)\n groups = table.group_by_column(column)\n self.logger.info(\"Found %s groups\", len(groups))\n return groups", "def group_by(self, group_by_col_name):\n\n col = self.get...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove rows by evaluating `condition` for every row. The filtering will be done inplace and all the rows evaluating as falsy through the provided condition will be removed.
def filter_all(self, condition: RowCondition): def _check_row(index: int) -> bool: row = self.get_row(index) return condition(row) self._filter(_check_row)
[ "def delete(self, condition: conditions.Condition = None):\n if not condition:\n del self.rows[:]\n\n for i, row in enumerate(self.rows):\n if condition.evaluate(self, row):\n del self.rows[i]", "def delete(self, predicate: WhereClause = lambda row: True) -> None...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove rows by evaluating `condition` for cells in `column`. The filtering will be done inplace and all the rows where it evaluates to falsy are removed.
def filter_by_column(self, column: Column, condition: CellCondition): def _check_cell(index: int) -> bool: cell = self.get_cell(index, column) return condition(cell) self._filter(_check_cell)
[ "def delete(self, condition: conditions.Condition = None):\n if not condition:\n del self.rows[:]\n\n for i, row in enumerate(self.rows):\n if condition.evaluate(self, row):\n del self.rows[i]", "def filter_rows(col, value):\n\n def filterer(data):\n re...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Make a copy of a table object.
def copy_table(self, table: Table) -> Table: self._requires_table(table) return table.copy()
[ "def Copy(self, copy):\n return _table.Table_Copy(self, copy)", "def copy_table(document, table, cut=False):\n if cut:\n document._body._element._insert_tbl(table._tbl)\n else:\n document._body._element._insert_tbl(copy.deepcopy(table)._tbl)\n return document.tables[-1]", "def __co...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Merge tables by appending columns and rows.
def _merge_by_append(self, tables: Tuple[Table, ...]): columns = uniq(column for table in tables for column in table.columns) merged = Table(columns=columns) for table in tables: merged.append_rows(table) return merged
[ "def merge_tables(tables):\n base = tables[0]\n for table in tables[1:]:\n for row_index, row in enumerate(table):\n # Chop off duplicate leftmost column\n base[row_index] += row[1:]\n return base", "def merge_tables(self, to_merge=[\"featurizer\", \"predictor\", \"communicat...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find index for row, if key already exists.
def find_index(row): value = row[index] if value in seen: return seen[value] for row_ in merged.iter_dicts(True): if row_[index] == value: seen[value] = row_["index"] return row_["index"] return None
[ "def _get_row_index(self, row: Row) -> int:\n row_index = -1\n for index, table_row in enumerate(self.table_data):\n if table_row.values == row.values:\n row_index = index\n break\n return row_index", "def _select_index_from_item(item):\n for in...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return table dimensions, as (rows, columns).
def get_table_dimensions(self, table: Table) -> Tuple[int, int]: self._requires_table(table) notebook_print(text=table.dimensions) return table.dimensions
[ "def dimensions():", "def dims(self):\n return (self.dim(),)", "def size(self):\n cols = self.max_col + 1 - self.min_col\n rows = self.max_row + 1 - self.min_row\n return {'columns':cols, 'rows':rows}", "def size(self):\r\n rows = len(self.pixels[0])\r\n cols = len(se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Renames columns in the Table with given values. Columns with name as ``None`` will use the previous value.
def rename_table_columns( self, table: Table, names: List[Union[str, None]], strict: bool = False ): self._requires_table(table) before = table.columns if strict and len(before) != len(names): raise ValueError("Column lengths do not match") after = [] fo...
[ "def rename_columns(self):\n if self.column_names is not None:\n logger.info(\"Renaming columns as follows:\")\n logger.info(json.dumps(self.column_names, cls=TypeEncoder))\n if isinstance(self.column_names, dict):\n for old_name, new_name in self.column_names....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Assign values to a row in the table.
def set_table_row(self, table: Table, row: Index, values: Any): self._requires_table(table) table.set_row(row, values)
[ "def set_row(self, row: int, values: list) -> None:\n for i, _ in enumerate(values):\n self.values[row][i] = values[i]", "def set_row_values(self, row, value_list=[]):\n for col, value in enumerate(value_list):\n if col in self.entries[row]:\n # print('COL VALUE'...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Assign values to a column in the table.
def set_table_column(self, table: Table, column: Column, values: Any): self._requires_table(table) table.set_column(column, values)
[ "def __set_column(self, index, new_col):\n for col_val, row in zip(new_col, self.__table):\n row[index] = col_val", "def set_col(self, col: int, values: list) -> None:\n for i, _ in enumerate(values):\n self.values[i][col] = values[i]", "def set_column(self, column, values):\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set existing row as names for columns.
def set_row_as_column_names(self, table: Table, row: Index): values = self.pop_table_row(table, row, as_list=True) table.columns = values
[ "def row_rename(self):\n # TODO develop method\n pass", "def setNames(self,names):\n h2o.rapids(ExprNode(\"colnames=\", self, range(self.ncol), names)._eager())\n self._update()\n return self", "def setFieldNames(self, model, lyr): \n #get the fields\n fields = lyr.pending...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return first ``count`` rows from a table.
def table_head( self, table: Table, count: int = 5, as_list: bool = False ) -> Union[Table, List[List]]: self._requires_table(table) return table.head(count, as_list)
[ "def take_first(count):\n def _take_first(iterable):\n return islice(iterable, count)\n return pipe | set_name('take_first(%s)' % count, _take_first)", "def head(self, limit, columns=None):\n return self.table.head(limit, partition=self.partition_spec, columns=columns)", "def get_table_nfirs...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return last ``count`` rows from a table.
def table_tail( self, table: Table, count: int = 5, as_list: bool = False ) -> Union[Table, List[List]]: self._requires_table(table) return table.tail(count, as_list)
[ "def get_last(self, count):", "def fetch_last(self, tablename):\n query = 'select * from ' + tablename\n try:\n self.__cur.execute(query)\n except Exception as e:\n self.__conn.rollback()\n raise e\n fetcheddata = self.__cur.fetchall()\n if fetch...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set a cell value in a table.
def set_table_cell(self, table: Table, row: Index, column: Column, value: Any): self._requires_table(table) table.set_cell(row, column, value)
[ "def set_cell(self, point, value):\r\n self.ws.cell(point).value = value", "def set_cell(self, cell, value):\n x,y = cell\n self.grid[y][x] = value", "def setCell(self, row = None, column = None, value = None, *, cell = None):\n\n\t\t\t\tif (cell is None):\n\t\t\t\t\tcell = self.getCell(row...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Find all the rows in a table which match a condition for a given column.
def find_table_rows(self, table: Table, column: Column, operator: str, value: Any): self._requires_table(table) condition = to_condition(operator, value) matches = [] for index in table.index: cell = table.get_cell(index, column) if condition(cell): ...
[ "def get_matches(df, column, to_match):\n\n return df[df[column] == to_match]", "def get_rows(column_to_search, value_to_match, table, db_file):\n \n try:\n conn, c = connect_to_db(db_file) \n c.execute('SELECT * FROM {t} WHERE {col}=\"{value}\"'.format(t=safe(table), \n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sort a table inplace according to ``column``.
def sort_table_by_column( self, table: Table, column: Column, ascending: bool = True ): self._requires_table(table) table.sort_by_column(column, ascending=ascending)
[ "def sorted(df, column=False):\n\n if not isinstance(df, aku.DataFrame):\n raise TypeError(\"The sorted operation requires an DataFrame.\")\n result = DataFrame(df.data)\n result.sort(column)\n return result", "def sortByColumn(data_file, column_to_sort=1):\n cmp = lambda qvar: float(qvar.sp...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Group a table by ``column`` and return a list of grouped Tables.
def group_table_by_column(self, table: Table, column: Column) -> List[Table]: self._requires_table(table) groups = table.group_by_column(column) self.logger.info("Found %s groups", len(groups)) return groups
[ "def group_by_column(self, column):\n ref = self.copy()\n ref.sort_by_column(column)\n\n col = self.column_location(column)\n groups = groupby(ref.data, itemgetter(col))\n\n result = []\n ref.clear()\n for _, group in groups:\n table = ref.copy()\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Run a keyword for each row of a table, then remove all rows where the called keyword returns a falsy value. Can be used to create custom RF keyword based filters.
def filter_table_with_keyword(self, table: Table, name: str, *args): self._requires_table(table) def condition(row: Row) -> bool: return BuiltIn().run_keyword(name, row, *args) before = len(table) table.filter_all(condition) after = len(table) self.logger.i...
[ "def test_queryUnkeywordFlag(self):\n self._keywordFilteringTest(\"unkeyword\")", "def delete(self, predicate: WhereClause = lambda row: True) -> None:\n self.rows = [row for row in self.rows if not predicate(row)]", "def filterRows(function, rows):\n return [y for y in rows if function(y)]", ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Run a keyword for each cell in a given column, and replace its content with the return value. Can be used to easily convert column types or values inplace.
def map_column_values(self, table: Table, column: Column, name: str, *args): self._requires_table(table) values = [] for index in table.index: cell = table.get_cell(index, column) output = BuiltIn().run_keyword(name, cell, *args) values.append(output) ...
[ "def spellcheck(df, column):\n for i in df.index:\n df[column][i] = TextBlob(df[column][i]).correct().raw\n return df", "def replace(self, func, heading):\n #return on empty data\n if not self.cols : return\n index = self.index_from_header(heading)\n new = [func(item) for...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove all rows from a table which have only ``None`` values.
def filter_empty_rows(self, table: Table): self._requires_table(table) empty = [] for idx, row in table.iter_lists(): if all(value is None for value in row): empty.append(idx) table.delete_rows(empty)
[ "def trim_empty_rows(self, table: Table):\n self._requires_table(table)\n\n empty = []\n for idx in reversed(table.index):\n row = table[idx]\n if any(value is not None for value in row):\n break\n empty.append(idx)\n\n table.delete_rows(em...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove all rows from the end of a table which have only ``None`` as values.
def trim_empty_rows(self, table: Table): self._requires_table(table) empty = [] for idx in reversed(table.index): row = table[idx] if any(value is not None for value in row): break empty.append(idx) table.delete_rows(empty)
[ "def filter_empty_rows(self, table: Table):\n self._requires_table(table)\n\n empty = []\n for idx, row in table.iter_lists():\n if all(value is None for value in row):\n empty.append(idx)\n\n table.delete_rows(empty)", "def clean(df):\n return list(filter(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove all extraneous whitespace from column names.
def trim_column_names(self, table: Table): self._requires_table(table) table.columns = [ column.strip() if isinstance(column, str) else column for column in table.columns ]
[ "def strip_extra_spaces_and_newline_characters_in_column_names(\n self,\n df\n ):\n return df.rename(columns=lambda x: x.strip())", "def trim_space_around_column_names(self, df):\n df.columns = [x.strip() for x in df.columns.tolist()]\n return df", "def fix_col_name...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
计算AUC,必须以loan_id为维度,因为在建模的时候就是以loan_id为维度 需要:模型分+label 1、建模的时候,label的定义:坏用户label=1, 好用户label=0 2、注意计算AUC的时候,函数metrics.roc_auc_score(label_list, pvalue_list)的label与pvalue必须是这样的对应关系:pvalue越高,用户越坏(label=1),否则计算的AUC就不对 3、但是我们现在有的模型分:取值范围在[300, 700]之间,分数越高,用户越好(label=0),那怎么计算AUC呢? 4、解决办法:将label颠倒过来,好用户label=1, 坏用户label=0。将这...
def _calc_auc(self, target, df_loan_sub): print("注意,计算AUC的时候,必须以loan_id为维度。并且label与pvalue必须是正相关的!否则计算的AUC就不对") df_loan_sub_copy = df_loan_sub.copy() # 去掉空值 df_loan_sub_copy = df_loan_sub_copy[df_loan_sub_copy[self.split_col].notnull()] # 模型分可能有NULL df_loan_sub_copy = df_loan_sub...
[ "def _auc_score(self, predictions, targets):\n \treturn roc_auc_score(predictions, targets)", "def compute_AUC_score(X, y, model, label):\n logging.info(\"Computing AUC score on {} set...\".format(label))\n y_proba = model.predict_proba(X)[:, 1]\n auc_score = roc_auc_score(y, y_proba)\n logging.inf...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
计算ks的时候,必须以建模时候的最小粒度样本来进行计算 需要:模型分+label label的定义:与模型训练时候一致,坏用户label=1, 好用户label=0
def _calc_ks(self, target, df_loan_sub): # 去掉空值,NULL值可能填充成-1,-2,-3 df_loan_sub_copy = df_loan_sub.copy() df_loan_sub_copy = df_loan_sub_copy[(df_loan_sub_copy[self.split_col].notnull()) & (df_loan_sub_copy[self.split_col] >= 0)] df_loan_sub_copy["label"] = df_loan_sub_copy["max_overdue"]...
[ "def compute_ks_statistic(trainModel, statManager):\n rescaled_S = trainModel.computeRescaledSpikeTimes()\n C = trainModel.modelParams[\"proc_id_model\",\"C\"]\n K = trainModel.modelParams[\"proc_id_model\",\"K\"]\n \n for k in np.arange(K):\n statManager.setSingleSample(\"rescaled_S_%d\" % k,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns True or False depending on whether or not the key is in the cache
def __contains__(self, key): return key in self.cache
[ "def isCached(cache, key):\n if key in cache:\n return True\n return False", "def cached(self, key):\n return key in self._cache", "def __contains__(self, key):\n return key in self.cache", "def exists(self, key):\n return bool(self.cache.exists(key))", "def con...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Return current keys existing in cache
def print_keys_existing(self): for key in self.cache: print(key)
[ "def _cache_keys(self):\n return [t.cache_key for t in self]", "def get_keys(self, key):\n\t\ttry:\n\t\t\tkey = self.make_key(key + \"*\")\n\t\t\treturn self.keys(key)\n\n\t\texcept (ConnectionError, TimeoutError):\n\t\t\tregex = re.compile(cstr(key).replace(\"|\", \"\\|\").replace(\"*\", \"[\\w]*\"))\n\t\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create new untitled notebook at 'path' Server base URL is 'url' Returns name of the new notebook file.
def newnb(url, path, copy=None): # See IPython/html/services/notebooks/handlers.py for API details. # Compare directory contents before and after new notebook creation. names = [nb['name'] for nb in get_nblist(url, path) if nb['type'] == 'notebook'] arg = path if isinstance(arg, unicode): ...
[ "def addNotebook(userID, title):", "def createNotebook(self, authenticationToken, notebook):\r\n pass", "def upload_notebook(dbricks_client, notebook_folder,\n notebook_dir, notebook_name):\n\n # Read notebook file into a Base-64 encoded string\n with open(f\"{notebook_dir}/{notebook...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Calculate an MD5checksum (128 bits) of the given object. The types of the object and it's elements (in case of a container)
def checksum(*objects): hasher = hashlib.md5() _checksum(hasher, objects) return hasher.hexdigest()
[ "def calc_hash_digest(obj):\r\n # Get string representation\r\n string = repr(obj).encode()\r\n # Create hash digest\r\n hash = hashlib.md5()\r\n hash.update(string)\r\n digest = hash.hexdigest()\r\n return digest", "def md5(obj):\n import hashlib\n # print \"self.conf\", str(self.conf)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
returns the value of the nth bit of reg.
def get_bit(reg,n_bit): return reg >> n_bit & 1
[ "def get_bit(self, register: str, n_bit: int):\n byte = self.get_byte(register)\n return byte[::-1][n_bit]", "def getbit(n, i):\r\n return (n >> i) & 1", "def get_bit(number, index):\n return (number >> index) & 1", "def get_bit(number, index):\n return (int(number) & (1 << index)) >> i...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Writes the ndata (int) data bytes of data (int) into regiter reg of the device. Error is raised if data is longer than ndata. If the chip has only one register and therefore it has no register address, set data=0 and ndata=0, and give the intended register value to the "reg" argument.
def write(self, reg, data, ndata): assert 0<=reg<=0xff, f"Invalid register addres: f{hex(reg)}. Valid range is (0x00, 0xff)" if self.emulate: pass else: l_tx = [(self.addr << 1), reg ] l_data = [] if ndata > 0: l_data = self.int_to...
[ "def _write_reg(self, register, data):\n logger.debug(\"Writing to register {0}: {1}\".format(register, data))\n if isinstance(register, str):\n w_data = [self.registers[register]]\n elif isinstance(register, int):\n w_data = [register]\n else:\n raise (V...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Getter for the version string. If no version was provided upon creation (e.g. via a command line flag), we will attempt to auto generate a version string using the username and the current date.
def version(self): if self._version is None: self.version = '{user}-{date}'.format( user=getpass.getuser().strip().lower(), date=datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d')) return self._version
[ "def get_version_string():\n return (f\"{config.VERSION['repo']}:{config.VERSION['name']}@\"\n f\"{config.VERSION['sha']}, modified:{config.VERSION['modified']}\")", "def get_version(cls):\n if Config.ENV_TYPE == PRD:\n return Config.version + \"/\" + Config.build\n return C...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Setter for the version string.
def version(self, version): self._version = utils.VersionParser().parse(version)
[ "def version(self, version: str):\n\n self._version = version", "def set_version(self, version: str) -> None:\n if self.current_version == version:\n return\n self.current_version = version\n self._del_cached_property(\"version\")", "def version_name(self, version_name):\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Runs the Grab n Go manager.
def run(self): try: while True: utils.clear_screen() utils.write('Which of the following actions would you like to take?\n') for opt in self._options.values(): utils.write('Action: {!r}\nDescription: {}\n'.format( opt.name, opt.description)) action = uti...
[ "def run(self):\n self.cmdloop()", "def run():\n board = SimpleGoBoard(7)\n con = GtpConnection(Gomoku4(), board)\n con.start_connection()", "def run():\n board = SimpleGoBoard(7)\n con = GtpConnectionGo2(Go2(), board)\n con.start_connection()", "def run():\n board = GoBoard(7)\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Changes the project configuration being managed.
def _change_project(self): project_key = utils.prompt_string( 'You are currently managing Google Cloud Project {!r}.\n' 'This project is currently saved as {!r}.\n' 'All of the currently configured projects include: {}.\n' 'Which project would you like to switch to?'.format( ...
[ "def handle_project_change(self):\n self.update_default_wdir()\n self.load_config()", "def configure(self):\n projects = self.get_dep_projects()\n configure_args = {\n \"version\": self.version,\n \"hosted\": self.hosted,\n \"build_type\": self.build_ty...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Prompts the user for project wide constants.
def _configure(self): opts = sorted(self._constants.keys()) opts.append(_QUIT) try: while True: utils.clear_screen() utils.write('Here are the project wide constants for {!r}:\n'.format( self._config.project)) configured, unconfigured = [], [] for name in so...
[ "def get_project() -> str:\n readline.set_completer(completions.project_complete)\n project = input(\"project: \")\n if project == \"\":\n project = None\n return project", "def prompt_project(arguments):\r\n projects = Project.all()\r\n\r\n # Do not prompt -- and auto select the one proj...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Writes constants to the configured Google Cloud Storage Bucket.
def _save_constants(self): try: self._storage_api.insert_blob( self._config.constants_storage_path, {name: const.value for name, const in six.iteritems(self._constants)}, bucket_name=self._config.bucket, ) except storage.NotFoundError as err: logging.error('Failed...
[ "def gcs_bucket(request, gcs: storage.Client) -> storage.Bucket:\n bucket = gcs.create_bucket(f\"test_gcs_ocn_bq_ingest_{str(uuid.uuid4())}\")\n bucket.versioning_enabled = True\n bucket.patch()\n # overide default field delimiter at bucket level\n load_config_json = {\n \"fieldDelimiter\": \"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Attempts to load constants from Google Cloud Storage.
def load_constants_from_storage(self): try: constants = self._storage_api.get_blob( self._config.constants_storage_path, self._config.bucket, ) except storage.NotFoundError as err: logging.error('Constants were not found in storage: %s', err) else: for name in sel...
[ "def _gcs_load(path):\n return Command(\"gsutil cat {}\".format(path)).output", "def get_gcs():\n return discovery.build(\n 'storage',\n 'v1',\n credentials=GoogleCredentials.get_application_default()\n )", "def load_gcp_data(self):\n pass", "def _instantiate_gcs_client(...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function is called when a new robot is created. It adds it to the drop down menu.
def add_robot(self, robot): # ALTHOUGH THE DOCUMENTATION SAYS THAT MENU CHOICES CAN BE UPDATED, # THE PACKAGE DOES NOT ALLOW IT. # THUS THIS 'HACK' MUST BE DONE TO REFRESH THE UI WITH AN UPDATED LIST # Save the list of robot names new_list = [] for name in self.__ui_cont...
[ "def __del_robot(self):\n if len(self.__robots) == 0:\n # Alert the user and return\n self.scene.append_to_caption(\n '<script type=\"text/javascript\">alert'\n '(\"No robot to delete\");</script>')\n return\n\n # Clear the robot visuals\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This function is called when a new robot is to be deleted from the scene.
def delete_robot(self, robot): if len(self.__robots) == 0 or robot not in self.__robots: return robot_index = self.__robots.index(robot) # Clear the robot visuals self.__robots[robot_index].set_reference_visibility(False) self.__robots[robot_index].set_robot_visibil...
[ "def __del_robot(self):\n if len(self.__robots) == 0:\n # Alert the user and return\n self.scene.append_to_caption(\n '<script type=\"text/javascript\">alert'\n '(\"No robot to delete\");</script>')\n return\n\n # Clear the robot visuals\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Checks whether the given robot is in the canvas
def is_robot_in_canvas(self, robot): return robot in self.__robots
[ "def isOnCanvas(self, x, y):\n return 0 <= x < self.width and 0 <= y < self.height", "def _isInCamera(self, pos):\n return self._isInScreen(self._posToScreenCoords(pos))", "def check_in_screen(self):\n if self.rect.colliderect(screen_rect) and not self.moving:\n return True\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Adds a button to the UI that toggles the UI mode
def __add_mode_button(self): btn_text = self.__toggle_button_text_dict.get( self.__ui_mode, "Unknown Mode Set") btn_text = "<span style='font-size:20px;'>" + btn_text + "</span>" btn_toggle = button(bind=self.__toggle_mode, text=btn_text) self.__ui_controls.btn_toggle = btn_...
[ "def Toggle(self, UI):\n\n mode = 0 if self.text == \"NORMAL\" else 1\n UI.SetGameMode(mode)\n\n self.text += \" X\"\n self.color = ActiveColor\n self.isActive = not self.isActive\n self.UpdateToggle()\n\n self.otherToggle.text = self.otherToggle.text[:-4]\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove a robot from the scene and the UI controls
def __del_robot(self): if len(self.__robots) == 0: # Alert the user and return self.scene.append_to_caption( '<script type="text/javascript">alert' '("No robot to delete");</script>') return # Clear the robot visuals self.__rob...
[ "def remove_robots(): #py:remove_robots\n RUR._remove_robots_()", "def delete_robot(self, robot):\n if len(self.__robots) == 0 or robot not in self.__robots:\n return\n\n robot_index = self.__robots.index(robot)\n\n # Clear the robot visuals\n self.__robots[robot_index]....
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reload the UI with the new list of robot names
def __reload_caption(self, new_list): # Remove all UI elements for item in self.__ui_controls: if self.__ui_controls.get(item) is None: continue self.__ui_controls.get(item).delete() for item in self.__teachpanel_sliders: item.delete() ...
[ "def reloadPanel(self):\n\n self.name_box.delete('1.0', END)\n self.version_box.delete('1.0', END)\n self.rel_path_box.delete('1.0', END)\n self.url_box.delete('1.0', END)\n self.repository_box.delete('1.0', END)\n self.clone_check.set(False)\n self.build_check.set(F...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Load the UI menu depending on the current mode
def __load_mode_ui(self, new_list): self.__add_mode_button() if self.__ui_mode == UImode.CANVASCONTROL: self.__setup_ui_controls(new_list) elif self.__ui_mode == UImode.TEACHPANEL: self.__setup_joint_sliders() else: self.scene.append_to_caption("UNKNOW...
[ "def setMenuMode(*args, **kwargs)->AnyStr:\n pass", "def show_menu(self, **kwargs):\n\n if self.machine.game and self.machine.game.num_players > 1:\n self.machine.variables.set_machine_var(\"players_widget_text\", \"Player {} of {}\".format(\n self.mach...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Reset the camera to a default position and orientation
def __reset_camera(self): # Reset Camera self.scene.up = z_axis_vector self.scene.camera.pos = vector(10, 10, 10) self.scene.camera.axis = -self.scene.camera.pos # Update grid self.__graphics_grid.update_grid()
[ "def reset_camera(self):\n if self.can_reset_view:\n camera = self.ren.GetActiveCamera()\n camera.SetPosition(self.position)\n camera.SetFocalPoint(self.focal_point)\n camera.SetViewUp(self.view_up)\n camera.SetViewAngle(self.view_angle)\n cam...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
When a menu item is chosen, update the relevant checkboxes/options
def __menu_item_chosen(self, m): # Get selected item self.__selected_robot = m.index # Update the checkboxes/sliders for the selected robot self.__ui_controls.get('chkbox_ref').checked = \ self.__robots[self.__selected_robot].ref_shown self.__ui_controls.get('chkbox...
[ "def update_menu(self):\n aktivnoUmjeravanje = self.get_aktivno_umjeravanje()\n if aktivnoUmjeravanje:\n check = True\n else:\n check = False\n self.action_save.setEnabled(check)\n self.action_save_as.setEnabled(check)\n self.action_close_aktivno_umjer...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
When a checkbox is changed for the reference frame option, update the graphics
def __reference_frame_checkbox(self, c): if len(self.__robots) > 0: self.__robots[self.__selected_robot].set_reference_visibility( c.checked)
[ "def change(self):\r\n\r\n # If checkboxes are available, check status and set boat speed reference line visibility accordingly.\r\n if self.cb:\r\n if self.cb_bt.checkState() == QtCore.Qt.Checked:\r\n for item in self.bt:\r\n item.set_visible(True)\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
When a checkbox is changed for the robot visibility, update the graphics
def __robot_visibility_checkbox(self, c): if len(self.__robots) > 0: self.__robots[self.__selected_robot].set_robot_visibility( c.checked)
[ "def change(self):\r\n\r\n # If checkboxes are available, check status and set boat speed reference line visibility accordingly.\r\n if self.cb:\r\n if self.cb_bt.checkState() == QtCore.Qt.Checked:\r\n for item in self.bt:\r\n item.set_visible(True)\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
When a checkbox is changed for the camera lock, update the camera
def __camera_lock_checkbox(self, c): # Update parameters # True = locked self.__camera_lock = c.checked # True = enabled self.scene.userspin = not c.checked self.scene.userzoom = not c.checked
[ "def update_camera(self):\n\n logger.info('Updating parameters of the camera')\n self.experiment.camera_microscope.config.update({\n 'exposure': Q_(self.camera_exposure_line.text()),\n 'gain': float(self.camera_gain_line.text()),\n })\n self.experiment.camera_micros...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update the opacity slider depending on the slider value
def __opacity_slider(self, s): if len(self.__robots) > 0: self.__robots[self.__selected_robot].set_transparency(s.value)
[ "def ct_slider_value_changed(self):\n for (x, slider) in enumerate(self.sliders):\n # for x in range(0, len(self.sliders)):\n # slider = self.sliders[x]\n slider_value = float(slider.value()) / float(slider.maximum())\n # Use an square function for easier opacity adjus...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Clear the scene of all objects, keeping the grid visible if set on
def clear_scene(self): # Save grid visibility restore = self.__grid_visibility # Set invis if restore: self.__graphics_grid.set_visibility(False) # Set all objects invis for obj in self.scene.objects: obj.visible = False # Restore grid (...
[ "def clear(self):\r\n self.scene.clear()", "def clean_all(self):\n self.scene.clear()\n self.image.fill(Qt.color0)", "def clear_scene(self, event):\n self.shapes = []\n self.redraw()", "def clearGrid(grid):\n\n grid.xaxis.set_visible(False)\n grid.yaxis.set_visible(Fal...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update the grid visibility in the scene
def grid_visibility(self, is_visible): self.__graphics_grid.set_visibility(is_visible)
[ "def displayGrid(self, toggled):\n self.scene.setGridVisible(visible=toggled)", "def gridDisplay(self):\n\n if self.griddButton.isCheckable():\n self.photo_grid.setVisible(False)\n self.griddButton.setCheckable(False)\n self.griddButton.setDown(False)\n se...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
When a checkbox is changed for the camera lock, update the camera
def __camera_lock_checkbox(self, c): # Update parameters # True = locked self.__camera_lock = c.checked # True = enabled self.scene.userspin = not c.checked self.scene.userzoom = not c.checked
[ "def update_camera(self):\n\n logger.info('Updating parameters of the camera')\n self.experiment.camera_microscope.config.update({\n 'exposure': Q_(self.camera_exposure_line.text()),\n 'gain': float(self.camera_gain_line.text()),\n })\n self.experiment.camera_micros...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
When a checkbox is changed for the grid visibility, update the graphics
def __grid_visibility_checkbox(self, c): self.grid_visibility(c.checked) self.__grid_visibility = c.checked
[ "def change(self):\r\n\r\n # If checkboxes are available, check status and set boat speed reference line visibility accordingly.\r\n if self.cb:\r\n if self.cb_bt.checkState() == QtCore.Qt.Checked:\r\n for item in self.bt:\r\n item.set_visible(True)\r\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set Serial/Lot number in pack operations to mark the pack operation done.
def set_so_pack_operation_lot(self, picking): StockProductionLot = self.env['stock.production.lot'] sale_line_obj = self.env['sale.order.line'] has_wrong_lots = False for del_move in picking.move_lines: del_move.move_line_ids.unlink() for move in picking.move_lines: ...
[ "def set_serial(self):\n self.write('008', '0')\n time.sleep(0.05)\n self.acknowledge()", "def lot_serial_nbr(self, lot_serial_nbr):\n\n self._lot_serial_nbr = lot_serial_nbr", "def serial_num(self, serial_num):\n self._serial_num = serial_num", "def setDone(self, index):\n\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
2.收到客户端上传文件的请求,判断该文件是否在服务器端存在,直接查看文件md5值 2.1 如果md5值相同,则文件存在 2.2 如果md5值不同,则告知客户端文件大小,如果md5值为None,则文件不存在 2.3 校验服务器空间是否充足,如果不足,则在1.2中同时告知客户端文件不足的信息
def put(self, request): print(request) filename = request.split()[-1] recv_data = pickle.loads(self.conn.recv(8192)) if recv_data['status']: abs_file_path = os.path.join(settings.BaseDir, self.current_path, filename) server_file_md5 = get_md5(abs_file_path, "file"...
[ "def file_request_check(file_request):\r\n filename_len = (file_request[3] << 8) + file_request[4]\r\n if (file_request[0] << 8) + file_request[1] != MAGIC_NO:\r\n print('ERROR: Invalid Magic Number in FileRequest')\r\n return False\r\n if file_request[2] != 1:\r\n print('ERROR: Invali...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
check java script log for errors (only `severe` level)
def check_js_log(self): js_log = self.get_log("browser") clean_log = [] total_chars = 0 idx = 0 for entry in js_log: if entry['level'] in ['SEVERE']: idx += 1 clean_log.append(entry) total_chars += len(entry['message']) ...
[ "def check_log_for_errors(self):\n log = self.driver.get_log('browser')\n error_messages = []\n\n for this_log in log:\n if this_log['level'] == 'SEVERE':\n error_messages.append(this_log['message'])\n\n if error_messages:\n all_msgs = \"\\n\".join(er...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Create an exception, using the string msg as message
def create_exception(self, msg: str):
[ "def create_exception(self, msg):\n return Exception(msg)", "def make_exception(message: str, error_code: int):\n\n try:\n exc_type = exception_type_from_error_code(error_code)\n # log internal backend engine errors only.\n if error_code == INTERNAL:\n logging.log(\n logging.WARNING...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Save a contour plot to a file for pgfplots Additional arguments are passed to iter_segements Important, simplify = True will remove invisible points
def save_contour(fname, cs, fmt = 'matlab', simplify = 1e-3, **kwargs): def write_path_matlab(fout, x_vec, y_vec, z): # Now dump this data back out # Header is level followed by number of rows fout.write('%15.15e\t%15d\n' % (z, len(x_vec))) for x, y in zip(x_vec, y_vec): fout.write("%15.15e\t%15.15e\n" % (...
[ "def write_to(self, filename):\n ncontour = self.get_contours_number\n npoints = self.get_points_number\n\n with open(filename, 'w') as f:\n f.write(str(ncontour) + '\\n')\n for i in range(0, ncontour):\n\n logger.debug(\"Sub-contour no. {0} has {1} points\"...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fill NaN with zero.
def fill_zero(df): df = df.fillna(0) return df
[ "def _zero_nas(self):\n self.data_frame = self.data_frame.fillna(0.0)", "def set_nan_or_inf_to_zero( array ):\n array[ np.isinf( array ) + np.isnan( array ) ] = 0\n \n return array", "def zero_to_nan(arr):\n arr[arr == 0] = numpy.nan\n return arr", "def convert_fill_zeros_like(g, op, blo...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fill NaN with previous values.
def fill_forward(df): df = df.fillna(method='ffill') df = df.fillna(method='bfill').fillna(0) return df
[ "def _forward_fill(data: np.ndarray):\n last_values = None\n\n for row in data:\n if last_values is not None:\n # Get NaN values index\n idx = np.isnan(row)\n # Fill NaN values using last seen values\n row[idx] = last_values[idx]\n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fill NaN with mean.
def fill_mean(df): df = df.fillna(df.mean().fillna(0).to_dict()) return df
[ "def nanmean(x):", "def mean_nan(A):\n dat = np.ma.masked_array(A, np.isnan(A))\n mean = np.mean(dat, axis=0)\n return mean.filled(np.nan)", "def mean_replace_nan(dataframe, median=False):\n tmp = dataframe\n\n if median:\n tmp_med = tmp[median]\n tmp_med = tmp_med.f...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fill NaN with median.
def fill_median(df): df = df.fillna(df.median().fillna(0).to_dict()) return df
[ "def mean_replace_nan(dataframe, median=False):\n tmp = dataframe\n\n if median:\n tmp_med = tmp[median]\n tmp_med = tmp_med.fillna(tmp_med.median())\n \n tmp = tmp.fillna(tmp.mean())\n\n if median:\n tmp[tmp_med.columns] = tmp_med\n\n retur...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Fill NaN with mean of last window values.
def rolling_mean(df, window: int = 10): df = fill_forward(df.fillna(df.rolling(window=window, min_periods=1).mean())) return df
[ "def fill_mean(df):\n df = df.fillna(df.mean().fillna(0).to_dict())\n return df", "def replaces_nans_ma(series):\n series = series.replace([np.inf, -np.inf], np.nan)\n result = series.fillna(series.rolling(window=len(series), min_periods=0).mean())\n return result", "def nanmean(x):", "def movi...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
User who created feedback can delete feedback
def delete_feedback(feedback_id): feedback = Feedback.query.get_or_404(feedback_id) recipient = feedback.recipient db.session.delete(feedback) db.session.commit() return redirect(f'/users/{recipient}')
[ "def delete_feedback(feedback_id): \n if 'username' in session:\n # Get username \n username = session['username']\n\n # Remove feedback \n Feedback.query.filter_by(id=feedback_id).delete()\n db.session.commit()\n flash('Feedback Deleted!', 'success')\n return red...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
shows or hides the histogram controls depending on whether Histogram is currently selected
def showOrHideHistogramControls(graphType:int): if GRAPHTYPE_CHOICES[graphType] == 'Histogram': return {'display': 'block'} return {'display': 'none'}
[ "def hide_histogram(key_figure_value):\n if \"Typical Mistakes\" in key_figure_value:\n display_style = {\"display\": \"block\"}\n else:\n display_style = {\"display\": \"none\"}\n return display_style", "def btn_equalize_hist_callback(self):\n self.show_as_waiting(True)\n sel...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
updates the graph based on the chosen data fields, data filters, graph type, and bin size (the latter if histogram is selected)
def updateGraph(dataFields:list, filterIndex:int, graphType:int, binSize:int): # title of the graph, set to the filename for now title = CSVPATH_CACHE[:-4] if len(dataFields) == 0: return go.Figure(layout=dict(title=title)) # empty graph if filterIndex is 0: fList = ['isMale'] elif filterIndex is 1: f...
[ "def updateGraph(dataFields:list, filterIndex:int, graphType:int,\n\t\t\t\tbinSize:int):\n\n\t# title of the graph, set to the filename for now\n\ttitle = 'Without filter'\n\n\tif len(dataFields) == 0:\n\t\treturn go.Figure(layout=dict(title=title)) # empty graph\n\n\tif filterIndex is 0:\n\t\tfList = ['isMale']\n\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
updates the graph based on the chosen data fields, data filters, graph type, and bin size (the latter if histogram is selected)
def updateGraph(dataFields:list, filterIndex:int, graphType:int, binSize:int): # title of the graph, set to the filename for now title = 'Without filter' if len(dataFields) == 0: return go.Figure(layout=dict(title=title)) # empty graph if filterIndex is 0: fList = ['isMale'] elif filterIndex is 1: fLi...
[ "def updateGraph(dataFields:list, filterIndex:int, graphType:int,\n\t\t\t\tbinSize:int):\n\n\t# title of the graph, set to the filename for now\n\ttitle = CSVPATH_CACHE[:-4]\n\n\tif len(dataFields) == 0:\n\t\treturn go.Figure(layout=dict(title=title)) # empty graph\n\n\tif filterIndex is 0:\n\t\tfList = ['isMale']\...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove any type of punctuation and the words and then split on whitespace
def simple_tokenizer(text): re_tok = re.compile(punctuation_string) return re_tok.sub(' ', text).split()
[ "def split_string_on_punctuation(text):\n pattern = r'[?!.,;][\\s]*'\n return [i for i in re.sub(pattern, \"|\", text).split(\"|\") if i != \"\"]\n pass", "def splitToWords(paragraph):\n listOfWords = []\n paragraph = paragraph.lower()\n paragraph = paragraph.replace('\\n', ' ')\n for char in...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Remove any type of punctuation and the words contained in the global variable common_words and then split on whitespace
def tokenize(text): common_words_string = " | ".join(common_words) re_tok = re.compile(punctuation_string + "| " + common_words_string + " ") words = re_tok.sub(' ',re_tok.sub(' ',text)).split() tokens = [] for i in range(len(words)-1): first = words[i] second = words[i+1] #...
[ "def clean_words(text: str,\n clean_all: bool = True,\n extra_spaces: bool = False,\n stemming: bool = False,\n stopwords: bool = False,\n lowercase: bool = False,\n numbers: bool = False,\n punct: bool = False,...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Use a web service to determine whether the sentiment of text is positive
def is_positive(text) : r = requests.post("http://text-processing.com/api/sentiment/", data={'text': text}) return r.json()['probability']['pos'] > r.json()['probability']['neg']
[ "def havenSentiment(text):\n\tfrom havenondemand.hodindex import HODClient\n\timport os\n\tkey = os.environ.get('havenAPI')\n\tclient = HODClient(apikey=key, apiversiondefault=1)\n\tdata = {'text': text}\n\tr = client.post('analyzesentiment', data)\n\tsentiment = r.json()['aggregate']['sentiment']\n\tscore = r.json...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
function is used to generate random int asynchronously
async def getrandom_number() : # run an infinite loop to continue generating random numbers while True: await asyncio.sleep(2) # let this task sleep for a while yield random.randint(0, sys.maxsize) # yield a random int
[ "async def generate_random():\n return randint(0, 1024)", "def gen_random_number():\n delay = random.randint(40, 1000)\n # substract delay to simulate sleep time\n seed = int(time()) - delay\n rng = MT19937RNG(seed)\n return rng.next()", "def randomNumberGenerator(self):\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Extract random subvolume from original images.
def get_sub_volume(image, label, orig_x = 240, orig_y = 240, orig_z = 155, output_x = 160, output_y = 160, output_z = 16, num_classes = 4, max_tries = 1000, background_threshold=0.95): # Initialize features and labels with `None` X =...
[ "def get_sub_volume(image, label, \n orig_x = 240, orig_y = 240, orig_z = 155, \n output_x = 160, output_y = 160, output_z = 16,\n num_classes = 4, max_tries = 1000, \n background_threshold=0.95):\n # Initialize features and labels with 'Non...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute dice coefficient for single class.
def single_class_dice_coefficient(y_true, y_pred, axis=(0, 1, 2), epsilon=0.00001): ### START CODE HERE (REPLACE INSTANCES OF 'None' with your code) ### dice_numerator = 2. * K.sum(y_true * y_pred, axis=axis) + epsilon dice_denominator = K.sum(y_true, axis=axis) + K....
[ "def single_class_dice_coefficient(y_true, y_pred, axis=(0, 1, 2), \n epsilon=0.00001):\n \n dice_numerator = K.sum(2 * y_true * y_pred, axis= axis) + epsilon\n dice_denominator = K.sum(y_true,axis= axis) + K.sum(y_pred, axis = axis) + epsilon\n dice_coefficient = dice_n...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute mean soft dice loss over all abnormality classes.
def soft_dice_loss(y_true, y_pred, axis=(1, 2, 3), epsilon=0.00001): ### START CODE HERE (REPLACE INSTANCES OF 'None' with your code) ### dice_numerator = 2. * K.sum(y_true * y_pred, axis=axis) + epsilon dice_denominator = K.sum(y_true**2, axis=axis) + K.sum(y_pred**2, axis=axis) + eps...
[ "def softmax_dice_loss(y, t, normalize=True, class_weight=None,\n ignore_label=-1, reduce='mean', eps=1e-08):\n return 1.0 - softmax_dice(y, t, normalize, class_weight,\n ignore_label, reduce, eps)", "def compute_mean_loss(self, X, D):\n\n mean_loss = 0...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Compute sensitivity and specificity for a particular example for a given class.
def compute_class_sens_spec(pred, label, class_num): # extract sub-array for specified class class_pred = pred[class_num] class_label = label[class_num] ### START CODE HERE (REPLACE INSTANCES OF 'None' with your code) ### # compute: # true positives tp = np.sum((class_pred == 1) ...
[ "def compute_class_sens_spec(pred, label, class_num):\n\n # extract sub-array for specified class\n class_pred = pred[class_num]\n class_label = label[class_num]\n \n # compute:\n \n # true positives\n tp = np.sum((class_label == 1) & (class_pred == 1))\n\n # true negatives\n tn = np.s...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Format an exception so that it prints on a single line.
def formatException(self, exc_info): result = super(OneLineExceptionFormatter, self).formatException(exc_info) return repr(result) # or format into one line however you want to
[ "def format_exception_only(exc):\r\n exc_type = type(exc)\r\n\r\n stype = exc_type.__qualname__\r\n smod = exc_type.__module__\r\n if smod not in (\"__main__\", \"builtins\"):\r\n stype = smod + '.' + stype\r\n try:\r\n _str = str(exc)\r\n except:\r\n _str = \"<unprintable {} ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Converts firestore stream to SearchResult model.
def from_stream(stream): results = [] for doc in stream: results.append(from_dict(data_class=SearchEntity, data=doc.to_dict())) return SearchResult(results)
[ "def create_from_search_query(search_query):\n if search_query.total_results_size == 0: # A search query with no results: build minimal details.\n return SearchResult.create_from_search_query_no_results(search_query)\n\n search_result = SearchResult(search_id=search_query.id, exact_match_c...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
This method is responsible for adding a store to the database, if not already existing.
def add_store_to_db(self, connexion): # initiate a cursor cursor = connexion.cursor() # check if the store already exists in database cursor.execute("""SELECT name FROM Store WHERE name = %s""", (self.name, )) rows = cursor.fetchall() if n...
[ "def add_store(self, product, store):\n self.db.query(\"\"\"\n INSERT IGNORE INTO product_store(product_id, store_id)\n VALUES (:product_id, :store_id)\n \"\"\", product_id=product.id, store_id=store.id)", "def add_store(self, name, store):\n self.store_dict[name] = stor...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a DoorStatus instance from the last line of logs.
def __read_last_line(self) -> str: with open(LOGFILE_OPENINGS, "r", encoding="utf-8") as f: last_line = f.readlines()[-1] return repr(LogLine.from_line(last_line))
[ "def get_log_pos(self):\n coll = self.get_coll('mysqllog', self.utildb)\n try:\n last_log = coll.find_one({'_id': 'last_log_pos'})\n except Exception as e:\n raise SysException(e)\n\n return last_log", "def get_last_logs(self):\n return [log[-1] for log in ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a string of DoorStatus instances from the last 10 lines of logs.
def __read_last_lines(self) -> str: with open(LOGFILE_OPENINGS, "r", encoding="utf-8") as f: last_lines = f.readlines()[-10:] return " 🌸 " + "\n🌸 ".join( map(lambda l: repr(LogLine.from_line(l)), last_lines) )
[ "def get_last_logs(self):\n return [log[-1] for log in self.log.values()]", "def log_n(self, n):\n lines = tailer.tail(open('logs/status.log'), n)\n\n statement = \"\"\n\n for line in lines:\n statement += (line + \"<br />\")\n return statement", "def read_all_info_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Update the status of the watched door. Returns True if it was modified.
def update_status(self) -> bool: last_edit = self.__get_modification_time(LOGFILE_OPENINGS) if self._last_edit != last_edit: self._last_edit = last_edit self._last_line = self.__read_last_line() self._last_lines = self.__read_last_lines() return True ...
[ "def update_status(self, status):\n pass", "def updateStatus(self, status):\n pass", "def _update_status(self):\n self._db_update({'status': self.status})", "def update_status(status):", "def update_status(self, updated_value='done'):\n self.status = updated_value\n if upd...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Returns a formated list of last 20 videos from motion folder.
def last_videos_recorded(self) -> list: return sorted(glob.glob(VIDEOS_DIR), key=os.path.getmtime)[-20:]
[ "def list_videos() -> list:\n # get a reference to this directory\n this_dir = os.path.dirname(os.path.abspath(__file__))\n # create a glob for MP4 files in this directory\n mp4_glob = os.path.join(this_dir, '*.mp4')\n # return the output from the glob as a list\n return sorted(glob.glob(mp4_glob)...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Set the verbose flag from given context args
def __read_verbose_param(self, context): self.__verbose = False if context.args and context.args[0] in "verboseVERBOSE": self.__verbose = True
[ "def set_verbose(x):\n\tglobal verbose\n\tverbose = x", "def _do_set_verbose(self, args):\r\n verbose = int(args[1])\r\n self.server.set_verbose(verbose)\r\n return \"%d\" % verbose", "def verbose(parser, options=('-v', '--verbose'), help='increase verbosity'):\n parser.add_argument(help...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Extract the filename from a filepath
def filename_from_path(filepath: str) -> str: return filepath.split("/")[-1]
[ "def extract_filename(filepath, ext=None):\n if ext[0] != \".\":\n ext = \".\" + ext\n\n filename = filepath.split(\"/\")[-1]\n if ext is not None:\n filename = filename.split(ext)[0]\n\n return filename", "def get_filename(path):\n\n filename = path.split('/')[-1].split('.')[0]\n ...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sent the last 10 videos as an inline keyboard.
async def last_vids(self, update: Update, _: ContextTypes.DEFAULT_TYPE) -> None: keyboard = [ [ InlineKeyboardButton( f"🎬 {self.filename_from_path(video_path)}", callback_data=video_path ) ] for video_path in self.door_stat...
[ "def display_videos(self):\n for i, v in enumerate(self.videos):\n Session.display_video(i+1, v)", "def next_video(driver):\n ActionChains(driver) \\\n .key_down(Keys.SHIFT) \\\n .key_down('N') \\\n .key_up(Keys.SHIFT) \\\n .key_up('N') \\\n .perform()", "...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Parses the CallbackQuery and updates the message text. Send the selected video.
async def button(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: query = update.callback_query # CallbackQueries need to be answered, even if no notification to the user is needed # Some clients may have trouble otherwise. See https://core.telegram.org/bots/api#callbackquery ...
[ "def _receive_video_thread(self):", "def CallVideoReceiveStatusChanged(self, Call, Status):", "def CallVideoSendStatusChanged(self, Call, Status):", "def _reply_to_callback_query(update, context, text=None, keyboard=None):\n callback_query = update.callback_query\n assert callback_query is not None, \"N...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Repond with the last lines of the log.
async def last_lines(self, update: Update, _: ContextTypes.DEFAULT_TYPE) -> None: self.door_status.update_status() await update.message.reply_text(text=self.door_status.last_lines)
[ "def out_last(self):\n self.out_last_line = self.nth_line(1, self.name + \".out\")", "def slurm_last(self):\n #print (self.slurm_id)\n self.slurm_last_line = self.nth_line(1, 'slurm.out')", "def keep_last_lines(self, num_lines):\n self.data = self.data[-num_lines:]", "def __read_la...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Respond with the status (running / stopped) of the alarm
async def status(self, update: Update, _: ContextTypes.DEFAULT_TYPE) -> None: msg = "running ✅" if self._running else "stopped 🚫" await update.message.reply_text(text=f"The alarm is {msg}")
[ "def _isalarm(self):\n return self.dp.state()==PyTango.DevState.ALARM", "def is_alarm():\n return _alarm", "def get_state(self):\r\n alarm = self._alarm()\r\n return alarm.state", "def get_alarm_state(self):\n return 'ALRM?'", "def status():\n status = platform_watchdog.is_...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
Sets the alarm, verbose or not. Send confirmation. Removes all scheduled jobs. Set a scheduled job every `due` seconds. If "verbose" is present in the command, it will spam the user with debugging info every time. Else, it will only send messages when the log is changed.
async def alarm(self, update: Update, context: ContextTypes.DEFAULT_TYPE) -> None: self.__read_verbose_param(context) chat_id = update.effective_message.chat_id job_removed = remove_job_if_exists(str(chat_id), context) due = 1.0 context.job_queue.run_repeating( self._...
[ "def alarm(self):\n log.debug(\"issued command alarm\")\n self.send_cmd('a')", "def alarm(self, context):\n job = context.job\n context.bot.send_message(job.context, text=\"Nuevo valor seteado!\")", "def alarm(context):\n job = context.job\n context.bot.send_message(job.context...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
x is the x coordinate in the image where the user clicked y is the y coordinate in the image where the user clicked
def click_a(self, event, x, y, flags, params): if event == cv2.EVENT_LBUTTONDOWN: self.image_a_coordinates = (x, y) print("ImageA selected coordinates =", self.image_a_coordinates) return x, y
[ "def click_b(self, event, x, y, flags, params):\n if event == cv2.EVENT_LBUTTONDOWN:\n self.image_b_coordinates = (x, y)\n print(\"ImageB selected coordinates =\", self.image_b_coordinates)\n return x, y", "def clickCell(self, event):\n position = self.input.checkMou...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }
x is the x coordinate in the image where the user clicked y is the y coordinate in the image where the user clicked
def click_b(self, event, x, y, flags, params): if event == cv2.EVENT_LBUTTONDOWN: self.image_b_coordinates = (x, y) print("ImageB selected coordinates =", self.image_b_coordinates) return x, y
[ "def click_a(self, event, x, y, flags, params):\n if event == cv2.EVENT_LBUTTONDOWN:\n self.image_a_coordinates = (x, y)\n print(\"ImageA selected coordinates =\", self.image_a_coordinates)\n return x, y", "def clickCell(self, event):\n position = self.input.checkMou...
{ "objective": { "paired": [], "self": [], "triplet": [ [ "query", "document", "negatives" ] ] } }