code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
with closing(self.open()) as f: data = f.read() return data.decode("utf-8") or None
def read(self)
Reads the contents of the GPFile and returns the contents as a string (assumes UTF-8)
5.694924
5.188911
1.097518
request = urllib.request.Request(self.server_data.url + "/rest/v1/jobs/" + self.uri) if self.server_data.authorization_header() is not None: request.add_header('Authorization', self.server_data.authorization_header()) request.add_header('User-Agent', 'GenePatternRest') ...
def get_info(self)
Query the GenePattern server for metadata regarding this job and assign that metadata to the properties on this GPJob object. Including: * Task Name * LSID * User ID * Job Number * Status * Date Submitted * URL of Log Files ...
3.210183
2.830736
1.134045
self.task_name = self.info['taskName'] self.task_lsid = self.info['taskLsid'] self.user_id = self.info['userId'] self.job_number = int(self.info['jobId']) self.status = self.get_status_message() self.date_submitted = self.info['dateSubmitted'] self.log_fi...
def load_info(self)
Parses the JSON object stored at GPJob.info and assigns its metadata to properties of this GPJob object. Primarily intended to be called from GPJob.get_info().
3.183248
2.859779
1.11311
# Lazily load info if self.info is None: self.get_info() # Lazily load children if self.children is not None: return self.children else: if 'children' in self.info: child_list = [] for child in self.inf...
def get_child_jobs(self)
Queries the GenePattern server for child jobs of this job, creates GPJob objects representing each of them and assigns the list of them to the GPJob.children property. Then return this list.
3.391035
2.990865
1.133797
self.get_info() if 'status' not in self.info: return False if 'isFinished' not in self.info['status']: return False return self.info['status']['isFinished']
def is_finished(self)
Queries the server to check if the job has been completed. Returns True or False.
3.177477
2.995097
1.060893
self.get_info() if 'status' not in self.info: return False if 'hasError' not in self.info['status']: return False return self.info['status']['hasError']
def has_error(self)
Queries the server to check if the job has an error. Returns True or False.
3.228404
3.048331
1.059072
self.get_info() if 'status' not in self.info: return False if 'isPending' not in self.info['status']: return False return self.info['status']['isPending']
def is_pending(self)
Queries the server to check if the job is pending. Returns True or False.
3.165085
3.090846
1.024019
# Lazily load info if self.info is None: self.get_info() if 'tags' in self.info: return [structure['tag']['tag'] for structure in self.info['tags']] else: return []
def get_tags(self)
Returns the tags for the job, querying the server if necessary.
4.892064
4.828952
1.01307
# Lazily load info if self.info is None: self.get_info() if 'comments' in self.info: return [structure['text'] for structure in self.info['comments']['comments']] else: return []
def get_comments(self)
Returns the comments for the job, querying the server if necessary.
4.625203
4.667088
0.991025
# Lazily load info if self.info is None: self.get_info() if 'outputFiles' in self.info: return [GPFile(self.server_data, f['link']['href']) for f in self.info['outputFiles']] else: return []
def get_output_files(self)
Returns a list of the files output by the job, querying the server if necessary. If the job has output no files, an empty list will be returned.
5.302347
4.728126
1.121448
files = self.get_output_files() for f in files: if f.get_name() == name: return f return None
def get_file(self, name)
Returns the output file with the specified name, if no output files match, returns None.
3.286765
2.393858
1.372999
wait = 1 while True: time.sleep(wait) self.get_info() if self.info['status']['isFinished']: break # implements a crude exponential back off wait = min(wait * 2, 60)
def wait_until_done(self)
This method will not return until the job is either complete or has reached an error state. This queries the server periodically to check for an update in status.
5.957776
5.600222
1.063846
if not isinstance(values, list): values = [values] if group_id is None: self.params.append({'name': name, 'values': values}) else: self.params.append({'name': name, 'groupId': group_id, 'values': values})
def set_parameter(self, name, values, group_id=None)
Sets the value of a parameter for the GPJobSpec :param name: name of the parameter :param values: list of values for the parameter :param group_id: optional parameter group ID :return:
2.094636
2.308336
0.907423
escaped_uri = urllib.parse.quote(self.uri) request = urllib.request.Request(self.server_data.url + '/rest/v1/tasks/' + escaped_uri) if self.server_data.authorization_header() is not None: request.add_header('Authorization', self.server_data.authorization_header()) re...
def param_load(self)
Queries the server for the parameter information and other metadata associated with this task
2.408006
2.290223
1.051429
# If the parameters haven't been loaded yet, do so if not self._params_loaded and self.server_data is not None: self.param_load() return GPJobSpec(self.server_data, self.lsid)
def make_job_spec(self)
:return: Returns a GPJobSpec used to launch a job of this task type
8.883573
6.921768
1.283425
if (('optional' in self.attributes and bool(self.attributes['optional'].strip())) and ('minValue' in self.attributes and self.attributes['minValue'] == 0)): return True else: return False
def is_optional(self)
Returns whether the parameter is optional or required :return: Return True if optional, False if required
4.657155
4.535584
1.026804
if 'TYPE' in self.attributes and 'MODE' in self.attributes: dto_type = self.attributes['TYPE'] dto_mode = self.attributes['MODE'] if dto_type == 'FILE' and dto_mode == 'IN': return 'File' return 'String'
def get_type(self)
Returns either 'File' or 'String'. The type attribute (e.g., java.io.File, java.lang.Integer, java.lang.Float), which might give a hint as to what string should represent, is not enforced and not employed consistently across all tasks, so we ignore.
4.27501
3.103343
1.37755
if ('default_value' in self.attributes and bool(self.attributes['default_value'].strip())): return self.attributes['default_value'] else: return None
def get_default_value(self)
Return the default value for the parameter. If here is no default value, return None
3.547638
3.400215
1.043357
if 'choiceInfo' not in self.dto[self.name]: raise GPException('not a choice parameter') status = self.dto[self.name]['choiceInfo']['status'] return status['message'], status['flag']
def get_choice_status(self)
Returns a message field, which indicates whether choices statically or dynamically defined, and flag indicating whether a dynamic file selection loading error occurred. Throws an error if this is not a choice parameter.
10.435691
6.568764
1.588684
if 'choiceInfo' not in self.dto[self.name]: raise GPException('not a choice parameter') return self.dto[self.name]['choiceInfo']['href']
def get_choice_href(self)
Returns the HREF of a dynamic choice parameter. Throws an error if this is not a choice parameter.
10.518231
6.186273
1.700253
if 'choiceInfo' not in self.dto[self.name]: raise GPException('not a choice parameter') choice_info_dto = self.dto[self.name]['choiceInfo'] if 'selectedValue' in choice_info_dto: return self.dto[self.name]['choiceInfo']['selectedValue'] else: ...
def get_choice_selected_value(self)
Returns the default selection from a choice menu Throws an error if this is not a choice parameter.
4.167753
3.293218
1.265556
if 'choiceInfo' not in self.dto[self.name]: raise GPException('not a choice parameter') return self._is_string_true(self.dto[self.name]['choiceInfo']['choiceAllowCustom'])
def allow_choice_custom_value(self)
Returns boolean indicating whether choice parameter supports custom value. If choice parameter supports custom value, user can provide parameter value other than those provided in choice list.
11.338779
10.210141
1.110541
if 'choiceInfo' not in self.dto[self.name]: raise GPException('not a choice parameter') if self.get_choice_status()[1] == "NOT_INITIALIZED": print(self.get_choice_status()) print("choice status not initialized") request = urllib.request.Request(...
def get_choices(self)
Returns a list of dictionary objects, one dictionary object per choice. Each object has two keys defined: 'value', 'label'. The 'label' entry is what should be displayed on the UI, the 'value' entry is what is written into GPJobSpec.
4.197618
3.98775
1.052628
if ('altName' in self.attributes and bool(self.attributes['altName'].strip())): return self.attributes['altName'] else: return None
def get_alt_name(self)
Returns the alternate name of a parameter. Only pipeline prompt-when-run parameters can have alternate names and alternate descriptions
4.071532
4.059886
1.002869
if 'altDescription' in self.attributes and bool(self.attributes['altDescription'].strip()): return self.attributes['altDescription'] else: return None
def get_alt_description(self)
Returns the alternate description of a parameter. Only pipeline prompt-when-run parameters can have alternate names and alternate descriptions
3.770477
3.816299
0.987993
''' Sends a UDP command to the wio device. \b DOES: Support "VERSION", "SCAN", "Blank?", "DEBUG", "ENDEBUG: 1", "ENDEBUG: 0" "APCFG: AP\\tPWDs\\tTOKENs\\tSNs\\tSERVER_Domains\\tXSERVER_Domain\\t\\r\\n", Note: 1. Ensure your device is Configure Mode. 2. Change you...
def cli(wio, send)
Sends a UDP command to the wio device. \b DOES: Support "VERSION", "SCAN", "Blank?", "DEBUG", "ENDEBUG: 1", "ENDEBUG: 0" "APCFG: AP\\tPWDs\\tTOKENs\\tSNs\\tSERVER_Domains\\tXSERVER_Domain\\t\\r\\n", Note: 1. Ensure your device is Configure Mode. 2. Change your computer n...
18.107441
2.017024
8.977305
if registers: out.write("IP: %d\n" % vm.instruction_pointer) out.write("DS: %s\n" % str(vm.stack)) out.write("RS: %s\n" % str(vm.return_stack)) def to_str(op): if is_embedded_push(op): op = get_embedded_push_value(op) if isstring(op): return...
def print_code(vm, out=sys.stdout, ops_per_line=8, registers=True)
Prints code and state for VM.
2.765955
2.788812
0.991804
print("Extra commands for the REPL:") print(".code - print code") print(".raw - print raw code") print(".quit - exit immediately") print(".reset - reset machine (IP and stacks)") print(".restart - create a clean, new machine") print(".clear - same as .restart") print("...
def repl(optimize=True, persist=True)
Starts a simple REPL for this machine. Args: optimize: Controls whether to run inputted code through the optimizer. persist: If True, the machine is not deleted after each line.
3.04998
3.049634
1.000113
try: self.db = dataset.connect(url, row_type=stuf) except Exception as e: self.err(e, "Can not connect to database") return if self.db is None: self.err("Database " + url + " not found") return self.ok("Db", self.db.url...
def connect(self, url: str)
Connect to the database and set it as main database :param url: path to the database, uses the Sqlalchemy format :type url: str :example: ``ds.connect("sqlite:///mydb.slqite")``
5.33433
5.39415
0.98891
if self._check_db() is False: return if table not in self.db.tables: self.warning("The table " + table + " does not exists") return try: self.start("Loading data from table " + table) res = self.db[table].all() self...
def load(self, table: str)
Set the main dataframe from a table's data :param table: table name :type table: str :example: ``ds.load("mytable")``
3.481149
3.488459
0.997905
try: self.df = self._load_django(query) except Exception as e: self.err(e, "Can not load data from query")
def load_django(self, query: "django query")
Load the main dataframe from a django orm query :param query: django query from a model :type query: django query :example: ``ds.load_django(Mymodel.objects.all())``
6.459784
5.895959
1.095629
try: df = self._load_django(query) return self.clone_(df) except Exception as e: self.err(e, "Can not load data from query")
def load_django_(self, query: "django query") -> "Ds"
Returns a DataSwim instance from a django orm query :param query: django query from a model :type query: django query :return: a dataswim instance with data from a django query :rtype: Ds :example: ``ds2 = ds.load_django_(Mymodel.objects.all())``
6.16367
8.074237
0.763375
dom = xml.dom.minidom.parse(filename) getText = lambda node, tag: node.getElementsByTagName(tag)[0].childNodes[0].data getNode = lambda tag: dom.getElementsByTagName(tag) content = getNode('channel')[0] # Only one channel node feedTitle = getText(content, 'title') feedLink = getText(cont...
def parseFeed(filename, yesterday)
Parse an RSS feed and filter only entries that are newer than yesterday.
2.41618
2.376769
1.016582
elem = self.rss.createElement(tag) node = self.rss.createTextNode(value) return parent.appendChild(elem).appendChild(node)
def addElement(self, parent, tag, value)
Add an RSS item.
4.338099
3.169982
1.368493
item = self.rss.createElement('item') self.addElement(item, 'title', title) self.addElement(item, 'link', link) self.addElement(item, 'description', description) self.addElement(item, 'guid', link) self.addElement(item, 'pubDate', date) if append: ...
def addItem(self, title, link, description, date, append=True)
Insert an item.
1.916163
1.892445
1.012533
with open(path, 'wb') as f: f.write(self.getXML())
def write(self, path)
Write RSS content to file.
4.533894
3.691688
1.228136
try: if dataframe is not None: df = dataframe else: df = self.df if df is None: self.warning("Dataframe is empty: nothing to show") return num = len(df.columns.values) except Exceptio...
def show(self, rows: int=5, dataframe: pd.DataFrame=None) -> pd.DataFrame
Display info about the dataframe :param rows: number of rows to show, defaults to 5 :param rows: int, optional :param dataframe: a pandas dataframe, defaults to None :param dataframe: pd.DataFrame, optional :return: a pandas dataframe :rtype: pd.DataFrame :examp...
3.888315
3.909705
0.994529
try: return self.show(1) except Exception as e: self.err(e, self.one, "Can not display dataframe")
def one(self)
Shows one row of the dataframe and the field names wiht count :return: a pandas dataframe :rtype: pd.DataFrame :example: ``ds.one()``
10.598045
9.179461
1.154539
if self.df is None: self.warning("Dataframe is empty: no tail available") return self.df.tail(rows)
def tail(self, rows: int=5)
Returns the main dataframe's tail :param rows: number of rows to print, defaults to 5 :param rows: int, optional :return: a pandas dataframe :rtype: pd.DataFrame :example: ``ds.tail()``
7.479132
6.968467
1.073282
try: s = self.df.iloc[0] df = pd.DataFrame(s) df = df.rename(columns={0: "value"}) def run(row): t = row[0] return type(t).__name__ s = df.apply(run, axis=1) df = df.rename(columns={0: "value"}) ...
def cols_(self) -> pd.DataFrame
Returns a dataframe with columns info :return: a pandas dataframe :rtype: pd.DataFrame :example: ``ds.cols_()``
3.653354
3.871312
0.943699
cols = self.df.columns.values all_types = {} for col in cols: local_types = [] for i, val in self.df[col].iteritems(): #print(i, val, type(val)) t = type(val).__name__ if t not in local_types: lo...
def types_(self, col: str) -> pd.DataFrame
Display types of values in a column :param col: column name :type col: str :return: a pandas dataframe :rtype: pd.DataFrame :example: ``ds.types_("Col 1")``
2.837435
2.860932
0.991787
# Get current CMS Page as article tree tree = request.current_page.get_public_object() # Check whether it really is a tree. # It could also be one of its sub-pages. if tree.application_urls != 'CMSArticlesApp': # In such case show regular CMS Page return page(request, slug) ...
def article(request, slug)
The main view of the Django-CMS Articles! Takes a request and a slug, renders the article.
3.38624
3.346877
1.011761
pageUrl = self.fetchUrl(url, data, self.indirectImageSearch) pageData = self.getPage(pageUrl) return super(TheThinHLine, self).getComicStrip(pageUrl, pageData)
def getComicStrip(self, url, data)
The comic strip image is in a separate page.
9.933944
9.534255
1.041921
num = pageUrl.split('/')[-1] ext = imageUrl.rsplit('.', 1)[1] return "thethinhline-%s.%s" % (num, ext)
def namer(cls, imageUrl, pageUrl)
Use page URL sequence which is apparently increasing.
7.154052
6.698876
1.067948
try: return Response('application/json', request(url=url)).read() except HTTPError as err: raise ResponseException('application/json', err)
def download_as_json(url)
Download the data at the URL and load it as JSON
11.80985
12.650414
0.933554
timeout = kwargs.pop('timeout', 5) req = PythonRequest(*args, **kwargs) return REQUEST_OPENER.open(req, timeout=timeout)
def request(*args, **kwargs)
Make a request with the received arguments and return an HTTPResponse object
6.280346
7.082938
0.886687
if path: if isinstance(obj, list) or isinstance(obj, tuple): #If the current state of the object received is a #list, return a list of each of its children elements, #traversed with the current state of the string return [traverse(x, *path) for x in obj] ...
def traverse(obj, *path, **kwargs)
Traverse the object we receive with the given path. Path items can be either strings or lists of strings (or any nested combination thereof). Behavior in given cases is laid out line by line below.
3.625704
3.553957
1.020188
return_full_object = kwargs.get('return_full_object', False) _verbose = kwargs.get('_verbose', False) traversal = kwargs.get('traversal', None) timeout = kwargs.get('_timeout', 5) self.output['url'] = self.render_url() with VerboseContextManager(verbose=_verbose)...
def send(self, **kwargs)
Send the request defined by the data stored in the object.
3.92301
3.703602
1.059242
url = self.url.format(**self.replacements) if self.params: return url + '?' + urlencode(self.params) return url
def render_url(self)
Render the final URL based on available variables
3.666201
3.256456
1.125825
if ';' in self.headers.get('Content-Type', ''): return self.headers['Content-Type'].split(';')[0] return self.headers.get('Content-Type', self.static_format)
def mimetype(self)
Get the Content-Type header from the response. Strip the ";charset=xxxxx" portion if necessary. If we can't find it, use the predefined format.
3.619557
2.622932
1.379966
if not raw: response_body = decode(self.data, self.mimetype(), encoding=self.encoding()) if perform_traversal and self.traversal is not None: return traverse(response_body, *self.traversal) return response_body else: return self.da...
def read(self, raw=False, perform_traversal=True)
Parse the body of the response using the Content-Type header we pulled from the response, or the hive-defined format, if such couldn't be pulled automatically.
3.948815
3.60328
1.095895
assert self.model is not None, ( "'{}' should include a `model` attribute, or override the `get_query()` method." .format(self.__class__.__name__) ) return self.request.dbsession.query(self.model)
def get_query(self)
Get the list of items for this view. You may want to override this if you need to provide different query depending on the incoming request. (Eg. return a list of items that is specific to the user) :return: ``sqlalchemy.orm.query.Query``
4.595842
3.871267
1.187168
query = self.filter_query(self.get_query()) # If query joins more than one table and you need to base the lookup on something besides # an id field on the self.model, you can provide an alternative lookup as tuple of the model class # and a string of the column name. i...
def get_object(self)
Returns the object the view is displaying. You may want to override this if you need to provide non-standard queryset lookups. Eg if objects are referenced using multiple keyword arguments in the url conf. :return: An instance of the view's model.
3.463607
3.545543
0.97689
klass = self.get_schema_class() # kwargs context value take precedence. kwargs['context'] = dict( self.get_schema_context(), **kwargs.get('context', {}) ) return klass(*args, strict=True, **kwargs)
def get_schema(self, *args, **kwargs)
Return the schema instance that should be used for validating and deserializing input, and for serializing output.
5.807552
5.420269
1.071451
for filter_class in list(self.filter_classes): query = filter_class().filter_query(self.request, query, self) return query
def filter_query(self, query)
Filter the given query using the filter classes specified on the view if any are specified.
4.267047
3.106879
1.373419
if self.paginator is None: return None return self.paginator.paginate_query(query, self.request)
def paginate_query(self, query)
Return single page of results or `None` if pagination is disabled.
4.516025
3.463753
1.303795
try: if col is None: self.df = self.df.dropna(how=method, **kwargs) else: self.df = self.df[self.df[col].notnull()] except Exception as e: self.err(e, "Error dropping nan values")
def drop_nan(self, col: str=None, method: str="all", **kwargs)
Drop rows with NaN values from the main dataframe :param col: name of the column, defaults to None. Drops in a...
2.501727
2.737432
0.913895
try: self.df[col] = self.df[col].replace('', nan) self.ok("Filled empty values with nan in column " + col) except Exception as e: self.err(e, "Can not fill empty values with nan")
def nan_empty(self, col: str)
Fill empty values with NaN values :param col: name of the colum :type col: str :example: ``ds.nan_empty("mycol")``
4.868146
5.006055
0.972452
if len(cols) == 0: self.warning("Can not nan zero values if a column name " "is not provided") df = self._zero_nan(*cols) if df is None: self.err("Can not fill zero values with nan") return self.df = df
def zero_nan(self, *cols)
Converts zero values to nan values in selected columns :param \*cols: names of the colums :type \*cols: str, at least one :example: ``ds.zero_nan("mycol1", "mycol2")``
6.143098
7.613492
0.80687
df = self._fill_nan(val, *cols) if df is not None: self.df = df else: self.err("Can not fill nan values")
def fill_nan(self, val: str, *cols)
Fill NaN values with new values in the main dataframe :param val: new value :type val: str :param \*cols: names of the colums :type \*cols: str, at least one :example: ``ds.fill_nan("new value", "mycol1", "mycol2")``
4.870095
6.930186
0.702737
n = [None, ""] try: self.df[col] = self.df[col].replace(n, nan) except Exception as e: self.err(e)
def fill_nulls(self, col: str)
Fill all null values with NaN values in a column. Null values are ``None`` or en empty string :param col: column name :type col: str :example: ``ds.fill_nulls("mycol")``
5.540731
6.253353
0.886042
try: for col in cols: self.df[col] = pd.to_numeric(self.df[col], **kwargs) except Exception as e: self.err(e, "Can not convert column values to integer") return self.ok("Converted column values to integers")
def to_int(self, *cols, **kwargs)
Convert some column values to integers :param \*cols: names of the colums :type \*cols: str, at least one :param \*\*kwargs: keyword arguments for ``pd.to_numeric`` :type \*\*kwargs: optional :example: ``ds.to_int("mycol1", "mycol2", errors="coerce")``
3.337578
3.635507
0.91805
try: self.df[col] = self.df[col].astype(np.float64, **kwargs) self.ok("Converted column values to float") except Exception as e: self.err(e, "Error converting to float")
def to_float(self, col: str, **kwargs)
Convert colums values to float :param col: name of the colum :type col: str, at least one :param \*\*kwargs: keyword arguments for ``df.astype`` :type \*\*kwargs: optional :example: ``ds.to_float("mycol1")``
3.995181
3.734084
1.069923
try: allcols = self.df.columns.values for col in cols: if col not in allcols: self.err("Column " + col + " not found") return self.df[col] = self.df[col].astype(dtype, **kwargs) except Exception as e...
def to_type(self, dtype: type, *cols, **kwargs)
Convert colums values to a given type in the main dataframe :param dtype: a type to convert to: ex: ``str`` :type dtype: type :param \*cols: names of the colums :type \*cols: str, at least one :param \*\*kwargs: keyword arguments for ``df.astype`` :type \*\*kwar...
3.124964
3.036191
1.029238
def formatdate(row): return row.strftime(format) def convert(row): encoded = '%Y-%m-%d %H:%M:%S' if precision == "Min": encoded = '%Y-%m-%d %H:%M' elif precision == "H": encoded = '%Y-%m-%d %H' elif pr...
def fdate(self, *cols, precision: str="S", format: str=None)
Convert column values to formated date string :param \*cols: names of the colums :type \*cols: str, at least one :param precision: time precision: Y, M, D, H, Min S, defaults to "S" :type precision: str, optional :param format: python date format, defaults to None :type ...
2.419761
2.311834
1.046685
try: name = "Timestamps" if "name" in kwargs: name = kwargs["name"] if "errors" not in kwargs: kwargs["errors"] = "coerce" if "unit" in kwargs: kwargs["unit"] = "ms" try: self.df[...
def timestamps(self, col: str, **kwargs)
Add a timestamps column from a date column :param col: name of the timestamps column to add :type col: str :param \*\*kwargs: keyword arguments for ``pd.to_datetime`` ...
3.006649
2.958384
1.016315
try: self.df[col] = pd.to_datetime(self.df[col], **kwargs) except Exception as e: self.err(e, "Can not convert to date")
def date(self, col: str, **kwargs)
Convert a column to date type :param col: column name :type col: str :param \*\*kwargs: keyword arguments for ``pd.to_datetime`` :type \*\*kwargs: optional :example: ``ds.date("mycol")``
3.599411
3.500109
1.028371
df = self._dateindex(col) if df is None: self.err("Can not create date index") return self.df = df self.ok("Added a datetime index from column", col)
def dateindex(self, col: str)
Set a datetime index from a column :param col: column name where to index the date from :type col: str :example: ``ds.dateindex("mycol")``
8.4137
9.311395
0.903592
df = self._index(col) if df is None: self.err("Can not create index") return self.df = df
def index(self, col: str)
Set an index to the main dataframe :param col: column name where to index from :type col: str :example: ``ds.index("mycol")``
7.707795
10.879455
0.708473
def remove_ws(row): val = str(row[col]) if " " in val.startswith(" "): row[col] = val.strip() return row try: self.df.apply(remove_ws) except Exception as e: self.err(e, "Can not remove white space in column") ...
def strip(self, col: str)
Remove leading and trailing white spaces in a column's values :param col: name of the column :type col: str :example: ``ds.strip("mycol")``
6.177351
5.805655
1.064023
cols = {} skipped = [] for col in self.df.columns.values: try: cols[col] = col.strip() except Exception: skipped.append(str(col)) self.df = self.df.rename(columns=cols) self.ok("White spaces removed in columns names...
def strip_cols(self)
Remove leading and trailing white spaces in columns names :example: ``ds.strip_cols()``
4.074095
3.878954
1.050308
try: self.df[col] = self.df[col].astype("float64") self.df[col] = self.df[col].apply(lambda x: round(x, precision)) except Exception as e: self.err(e, "Can not round column values") return self.ok("Rounded values in column " + col)
def roundvals(self, col: str, precision: int=2)
Round floats in a column. Numbers are going to be converted to floats if they are not already :param col: column name :type col: str :param precision: float precision, defaults to 2 :param precision: int, optional :example: ``ds.roundvals("mycol")``
3.183192
3.467954
0.917888
try: self.df[col] = self.df[col].replace(searchval, replaceval) except Exception as e: self.err(e, "Can not replace value in column")
def replace(self, col: str, searchval: str, replaceval: str)
Replace a value in a column in the main dataframe :param col: column name :type col: str :param searchval: value to replace :type searchval: str :param replaceval: new value :type replaceval: str :example: ``ds.replace("mycol", "value", "new_value")``
3.723791
3.792794
0.981807
clone = self._clone() clone._default_language = language_code return clone
def for_language(self, language_code)
Set the default language for all objects returned with this query.
6.08252
5.748047
1.058189
default_language = getattr(self, '_default_language', None) for obj in super(MultilingualModelQuerySet, self).iterator(): obj._default_language = default_language yield obj
def iterator(self)
Add the default language information to all returned objects.
4.45022
2.855473
1.558488
clone = super(MultilingualModelQuerySet, self)._clone(klass, **kwargs) clone._default_language = getattr(self, '_default_language', None) return clone
def _clone(self, klass=None, **kwargs)
Override _clone to preserve additional information needed by MultilingualModelQuerySet.
4.140708
2.447399
1.691881
''' Change setting of device. \b DOES: The config command lets you change setting of device through upd. 1. Ensure your device is Configure Mode. 2. Change your computer network to Wio's AP. \b EXAMPLE: wio config --debug [on|off], enable/disable wio debug ...
def cli(wio, get_debug, debug)
Change setting of device. \b DOES: The config command lets you change setting of device through upd. 1. Ensure your device is Configure Mode. 2. Change your computer network to Wio's AP. \b EXAMPLE: wio config --debug [on|off], enable/disable wio debug wio confi...
4.316139
2.357384
1.830902
try: val = self.df.iloc[0] return val except Exception as e: self.err(e, "Can not select first row")
def first_(self)
Select the first row
6.412609
5.34178
1.200463
try: self.df = self.df[:r] except Exception as e: self.err(e, "Can not limit data")
def limit(self, r=5)
Limit selection to a range in the main dataframe
6.422817
5.678339
1.131108
try: return self._duplicate_(self.df[:r]) except Exception as e: self.err(e, "Can not limit data")
def limit_(self, r=5)
Returns a DataSwim instance with limited selection
10.364155
9.299859
1.114442
try: df = self.df.drop_duplicates(subset=[col], inplace=False) return list(df[col]) except Exception as e: self.err(e, "Can not select unique data")
def unique_(self, col)
Returns unique values in a column
4.941169
4.947461
0.998728
try: s = pd.value_counts(self.df[col].values) df = pd.DataFrame(s, columns=["Number"]) return df except Exception as e: self.err(e, "Can not weight unique data")
def wunique_(self, col)
Weight unique values: returns a dataframe with a count of unique values
6.549153
5.77686
1.133687
df = self._nowrange(col, timeframe) if df is None: self.err("Can not select range data from now") return self.df = df
def nowrange(self, col, timeframe)
Set the main dataframe with rows within a date range from now ex: ds.nowrange("Date", "3D") for a 3 days range. Units are: S, H, D, W, M, Y
6.621043
5.782892
1.144936
df = self._nowrange(col, timeframe) if df is None: self.err("Can not select range data from now") return return self._duplicate_(df)
def nowrange_(self, col, timeframe)
Returns a Dataswim instance with rows within a date range from now ex: ds.nowrange("Date", "3D") for a 3 days range. Units are: S, H, D, W, M, Y
8.575621
8.810615
0.973328
df = self._daterange(datecol, date_start, op, **args) if df is None: self.err("Can not select date range data") self.df = df
def daterange(self, datecol, date_start, op, **args)
Returns rows in a date range
4.711834
4.727895
0.996603
df = self._daterange(datecol, date_start, op, **args) if df is None: self.err("Can not select date range data") return self._duplicate_(df)
def daterange_(self, datecol, date_start, op, **args)
Returns a DataSwim instance with rows in a date range
5.984749
5.892772
1.015608
df = self._subset(*args) if df is None: self.err("Can get subset of data") return self.df = df
def subset(self, *args)
Set the main dataframe to a subset based in positions Select a subset of the main dataframe based on position: ex: ds.subset(0,10) or ds.subset(10) is equivalent: it starts at the first row if only one argument is provided
8.033113
9.171943
0.875836
df = self._subset(*args) if df is None: self.err("Can not get subset of data") return return self._duplicate_(df)
def subset_(self, *args)
Returns a Dataswim instance with a subset data based in positions Select a subset of the main dataframe based on position: ex: ds.subset(0,10) or ds.subset(10) is equivalent: it starts at the first row if only one argument is provided
8.818485
11.157726
0.790348
try: data = getPageContent(url, session) except IOError as msg: print("ERROR:", msg, file=sys.stderr) return for match in url_matcher.finditer(data): comicurl = unquote(unescape(match.group(1))) path = comicurl[:-1].rsplit('/')[-1] name = capfirst(asciify...
def handle_url(url, session, url_matcher, num_matcher, res)
Parse one search result page.
4.063489
4.017886
1.01135
base = "http://www.theduckwebcomics.com/search/?page=%d&search=&type=0&type=1&last_update=" href = re.compile(tagre("a", "href", r'(/[^"]+/)', before="size24 yanone blue")) num = re.compile(r'(\d+) pages?</span>') # store info in a dictionary {name -> number of comics} res = {} # a search f...
def get_results()
Parse all search result pages.
8.238032
7.517585
1.095835
min_comics, filename = args min_comics = int(min_comics) with codecs.open(filename, 'a', 'utf-8') as fp: for name, entry in sorted(load_result(json_file).items()): if name in exclude_comics: continue path, num = entry if num >= min_comics: ...
def print_results(args)
Print all comics that have at least the given number of minimum comic strips.
5.511401
4.777824
1.153538
if admin: s = '{0}|1|name|{1}|{2}'.format(account_name, expires, timestamp) else: s = '{0}|name|{1}|{2}'.format(account_name, expires, timestamp) return hmac.new(preauth_key.encode('utf-8'), s.encode('utf-8'), hashlib.sha1).hexdigest()
def build_preauth_str(preauth_key, account_name, timestamp, expires, admin=False)
Builds the preauth string and hmac it, following the zimbra spec. Spec and examples are here http://wiki.zimbra.com/wiki/Preauth
2.515007
2.589313
0.971303
if isinstance(s, bool): return s elif s is None: return '' elif s == 'TRUE': return True elif s == 'FALSE': return False else: try: try: # telephone numbers may be wrongly interpretted as ints if s.startswith('+...
def auto_type(s)
Get a XML response and tries to convert it to Python base object
3.323879
3.324731
0.999744
xml = minidom.parseString(s) return pythonzimbra.tools.xmlserializer.dom_to_dict(xml.firstChild)
def xml_str_to_dict(s)
Transforms an XML string it to python-zimbra dict format For format, see: https://github.com/Zimbra-Community/python-zimbra/blob/master/README.md :param: a string, containing XML :returns: a dict, with python-zimbra format
9.137213
10.259264
0.89063
log_dict = None try: log_dict = json.loads( log_rec) except Exception as e: log.error(( 'Failed logging record={} with ex={}').format( log_rec, e)) return # end of try/ex if not log_dict: log.error(( ...
def show_search_results( log_rec, code_view=True, json_view=False, show_message_details=False)
show_search_results Show search results like rsyslog or as pretty-printed JSON dictionaries per log for debugging drill-down fields :param log_rec: log record from splunk :param code_view: show as a normal tail -f <log file> view :param json_view: pretty print each log's dictionary :param show...
1.808256
1.848758
0.978092
log_dict = None try: log_dict = json.loads( log_rec) except Exception as e: log_dict = None # end of try/ex if not log_dict: log.info(( '{}').format( ppj(log_rec))) else: log.info(( '{}').format( ...
def show_non_search_results( log_rec, code_view=True, json_view=False, show_message_details=False)
show_non_search_results Show non-search results for search jobs like: ``index="antinex" | stats count`` :param log_rec: log record from splunk :param code_view: show as a normal tail -f <log file> view :param json_view: pretty print each log's dictionary :param show_message_details
3.345172
4.044105
0.827172
if IS_PY2: sock.send(msg) else: sock.send(msg.encode())
def socket_send( sock, msg, debug=False)
socket_send Send the ``msg`` over the connected socket ``sock``. This will throw for any errors. :param sock: connected socket :param msg: message as a string :param debug: debug bool
3.55129
5.102784
0.695951
r = session.post( url=url, data=data, headers=headers, verify=verify, timeout=timeout ) r.raise_for_status() # Throws exception for 4xx/5xx status return r
def send_to_splunk( session=None, url=None, data=None, headers=None, verify=False, ssl_options=None, timeout=10.0)
send_to_splunk Send formatted msgs to Splunk. This will throw exceptions for any errors. It is decoupled from the publishers to make testing easier with mocks. :param session: requests.Session :param url: url for splunk logs :param data: data to send :param headers: headers for splunk ...
2.559144
3.119601
0.820343
print("Parsing", url, file=sys.stderr) try: data = getPageContent(url, session) except IOError as msg: print("ERROR:", msg, file=sys.stderr) return for match in page_matcher.finditer(data): page_url = match.group(1) page_url = urlparse.urljoin(url, page_url) ...
def handle_url(url, session, res)
Parse one search result page.
3.302745
3.27229
1.009307
base = "http://www.smackjeeves.com/search.php?submit=Search+for+Webcomics&search_mode=webcomics&comic_title=&special=all&last_update=3&style_all=on&genre_all=on&format_all=on&sort_by=2&start=%d" session = requests.Session() # store info in a dictionary {name -> url, number of comics, adult flag, bounce...
def get_results()
Parse all search result pages.
7.563298
7.159511
1.056399