Code
stringlengths
103
85.9k
Summary
listlengths
0
94
Please provide a description of the function:def set_chorus(self, nr=-1, level=-1.0, speed=-1.0, depth=-1.0, type=-1): set=0 if nr>=0: set+=0b00001 if level>=0: set+=0b00010 if speed>=0: set+=0b00100 if depth>=0: set+=0b010...
[ " \n nr Chorus voice count (0-99, CPU time consumption proportional to this value)\n level Chorus level (0.0-10.0)\n speed Chorus speed in Hz (0.29-5.0)\n depth_ms Chorus depth (max value depends on synth sample rate, 0.0-21.0 is safe for sample rate valu...
Please provide a description of the function:def consume_messages(self, max_next_messages): # get messages list from kafka if self.__next_messages == 0: self.set_next_messages(min(1000, max_next_messages)) self.set_next_messages(min(self.__next_messages, max_next_messages)) ...
[ " Get messages batch from Kafka (list at output) " ]
Please provide a description of the function:def decompress_messages(self, partitions_offmsgs): for pomsg in partitions_offmsgs: if pomsg['message']: pomsg['message'] = self.decompress_fun(pomsg['message']) yield pomsg
[ " Decompress pre-defined compressed fields for each message. " ]
Please provide a description of the function:def unpack_messages(self, partitions_msgs): for pmsg in partitions_msgs: key = pmsg['_key'] partition = pmsg['partition'] offset = pmsg['offset'] msg = pmsg.pop('message') if msg: t...
[ " Deserialize a message to python structures " ]
Please provide a description of the function:def append_stat_var(self, name, get_func): self._stats_getters.append(get_func) self._stats_logline += '%s: {}. ' % name self._stats_logline_totals += 'Total %s: {}. ' % name
[ "\n get_func is a function that returns a tuple (name, value)\n " ]
Please provide a description of the function:def _init_offsets(self, batchsize): upper_offsets = previous_lower_offsets = self._lower_offsets if not upper_offsets: upper_offsets = self.latest_offsets self._upper_offsets = {p: o for p, o in upper_offsets.items() if o > self._...
[ "\n Compute new initial and target offsets and do other maintenance tasks\n " ]
Please provide a description of the function:def _filter_deleted_records(self, batches): for batch in batches: for record in batch: if not self.must_delete_record(record): yield record
[ "\n Filter out deleted records\n " ]
Please provide a description of the function:def get_catalog(mid): if isinstance(mid, _uuid.UUID): mid = mid.hex return _get_catalog(mid)
[ "Return catalog entry for the specified ID.\n\n `mid` should be either a UUID or a 32 digit hex number.\n " ]
Please provide a description of the function:def stream(identifier=None, priority=LOG_INFO, level_prefix=False): r if identifier is None: if not _sys.argv or not _sys.argv[0] or _sys.argv[0] == '-c': identifier = 'python' else: identifier = _sys.argv[0] fd = stream_...
[ "Return a file object wrapping a stream to journal.\n\n Log messages written to this file as simple newline sepearted text strings\n are written to the journal.\n\n The file will be line buffered, so messages are actually sent after a\n newline character is written.\n\n >>> from systemd import journa...
Please provide a description of the function:def _convert_field(self, key, value): convert = self.converters.get(key, bytes.decode) try: return convert(value) except ValueError: # Leave in default bytes return value
[ "Convert value using self.converters[key].\n\n If `key` is not present in self.converters, a standard unicode decoding\n will be attempted. If the conversion (either key-specific or the\n default one) fails with a ValueError, the original bytes object will be\n returned.\n " ]
Please provide a description of the function:def _convert_entry(self, entry): result = {} for key, value in entry.items(): if isinstance(value, list): result[key] = [self._convert_field(key, val) for val in value] else: result[key] = self....
[ "Convert entire journal entry utilising _convert_field." ]
Please provide a description of the function:def add_match(self, *args, **kwargs): args = list(args) args.extend(_make_line(key, val) for key, val in kwargs.items()) for arg in args: super(Reader, self).add_match(arg)
[ "Add one or more matches to the filter journal log entries.\n\n All matches of different field are combined with logical AND, and\n matches of the same field are automatically combined with logical OR.\n Matches can be passed as strings of form \"FIELD=value\", or keyword\n arguments FIE...
Please provide a description of the function:def get_next(self, skip=1): r if super(Reader, self)._next(skip): entry = super(Reader, self)._get_all() if entry: entry['__REALTIME_TIMESTAMP'] = self._get_realtime() entry['__MONOTONIC_TIMESTAMP'] = se...
[ "Return the next log entry as a dictionary.\n\n Entries will be processed with converters specified during Reader\n creation.\n\n Optional `skip` value will return the `skip`-th log entry.\n\n Currently a standard dictionary of fields is returned, but in the\n future this might be...
Please provide a description of the function:def query_unique(self, field): return set(self._convert_field(field, value) for value in super(Reader, self).query_unique(field))
[ "Return a list of unique values appearing in the journal for the given\n `field`.\n\n Note this does not respect any journal matches.\n\n Entries will be processed with converters specified during\n Reader creation.\n " ]
Please provide a description of the function:def wait(self, timeout=None): us = -1 if timeout is None else int(timeout * 1000000) return super(Reader, self).wait(us)
[ "Wait for a change in the journal.\n\n `timeout` is the maximum time in seconds to wait, or None which\n means to wait forever.\n\n Returns one of NOP (no change), APPEND (new entries have been added to\n the end of the journal), or INVALIDATE (journal files have been added or\n r...
Please provide a description of the function:def seek_realtime(self, realtime): if isinstance(realtime, _datetime.datetime): realtime = int(float(realtime.strftime("%s.%f")) * 1000000) elif not isinstance(realtime, int): realtime = int(realtime * 1000000) return ...
[ "Seek to a matching journal entry nearest to `timestamp` time.\n\n Argument `realtime` must be either an integer UNIX timestamp (in\n microseconds since the beginning of the UNIX epoch), or an float UNIX\n timestamp (in seconds since the beginning of the UNIX epoch), or a\n datetime.date...
Please provide a description of the function:def seek_monotonic(self, monotonic, bootid=None): if isinstance(monotonic, _datetime.timedelta): monotonic = monotonic.total_seconds() monotonic = int(monotonic * 1000000) if isinstance(bootid, _uuid.UUID): bootid = bo...
[ "Seek to a matching journal entry nearest to `monotonic` time.\n\n Argument `monotonic` is a timestamp from boot in either seconds or a\n datetime.timedelta instance. Argument `bootid` is a string or UUID\n representing which boot the monotonic time is reference to. Defaults to\n current...
Please provide a description of the function:def log_level(self, level): if 0 <= level <= 7: for i in range(level+1): self.add_match(PRIORITY="%d" % i) else: raise ValueError("Log level must be 0 <= level <= 7")
[ "Set maximum log `level` by setting matches for PRIORITY.\n " ]
Please provide a description of the function:def messageid_match(self, messageid): if isinstance(messageid, _uuid.UUID): messageid = messageid.hex self.add_match(MESSAGE_ID=messageid)
[ "Add match for log entries with specified `messageid`.\n\n `messageid` can be string of hexadicimal digits or a UUID\n instance. Standard message IDs can be found in systemd.id128.\n\n Equivalent to add_match(MESSAGE_ID=`messageid`).\n " ]
Please provide a description of the function:def this_boot(self, bootid=None): if bootid is None: bootid = _id128.get_boot().hex else: bootid = getattr(bootid, 'hex', bootid) self.add_match(_BOOT_ID=bootid)
[ "Add match for _BOOT_ID for current boot or the specified boot ID.\n\n If specified, bootid should be either a UUID or a 32 digit hex number.\n\n Equivalent to add_match(_BOOT_ID='bootid').\n " ]
Please provide a description of the function:def this_machine(self, machineid=None): if machineid is None: machineid = _id128.get_machine().hex else: machineid = getattr(machineid, 'hex', machineid) self.add_match(_MACHINE_ID=machineid)
[ "Add match for _MACHINE_ID equal to the ID of this machine.\n\n If specified, machineid should be either a UUID or a 32 digit hex\n number.\n\n Equivalent to add_match(_MACHINE_ID='machineid').\n " ]
Please provide a description of the function:def emit(self, record): try: msg = self.format(record) pri = self.map_priority(record.levelno) # defaults extras = self._extra.copy() # higher priority if record.exc_text: ...
[ "Write `record` as a journal event.\n\n MESSAGE is taken from the message provided by the user, and PRIORITY,\n LOGGER, THREAD_NAME, CODE_{FILE,LINE,FUNC} fields are appended\n automatically. In addition, record.MESSAGE_ID will be used if present.\n " ]
Please provide a description of the function:def is_socket_sockaddr(fileobj, address, type=0, flowinfo=0, listening=-1): fd = _convert_fileobj(fileobj) return _is_socket_sockaddr(fd, address, type, flowinfo, listening)
[ "Check socket type, address and/or port, flowinfo, listening state.\n\n Wraps sd_is_socket_inet_sockaddr(3).\n\n `address` is a systemd-style numerical IPv4 or IPv6 address as used in\n ListenStream=. A port may be included after a colon (\":\").\n See systemd.socket(5) for details.\n\n Constants for...
Please provide a description of the function:def listen_fds(unset_environment=True): num = _listen_fds(unset_environment) return list(range(LISTEN_FDS_START, LISTEN_FDS_START + num))
[ "Return a list of socket activated descriptors\n\n Example::\n\n (in primary window)\n $ systemd-activate -l 2000 python3 -c \\\\\n 'from systemd.daemon import listen_fds; print(listen_fds())'\n (in another window)\n $ telnet localhost 2000\n (in primary window)\n ...\n ...
Please provide a description of the function:def connect(self): self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self._socket.settimeout(self._connect_timeout) SocketError.wrap(self._socket.connect, (self.host, self.port)) self._socket.settimeout(None) se...
[ "Connect to beanstalkd server." ]
Please provide a description of the function:def close(self): try: self._socket.sendall('quit\r\n') except socket.error: pass try: self._socket.close() except socket.error: pass
[ "Close connection to server." ]
Please provide a description of the function:def put(self, body, priority=DEFAULT_PRIORITY, delay=0, ttr=DEFAULT_TTR): assert isinstance(body, str), 'Job body must be a str instance' jid = self._interact_value('put %d %d %d %d\r\n%s\r\n' % ( priority, dela...
[ "Put a job into the current tube. Returns job id." ]
Please provide a description of the function:def reserve(self, timeout=None): if timeout is not None: command = 'reserve-with-timeout %d\r\n' % timeout else: command = 'reserve\r\n' try: return self._interact_job(command, ...
[ "Reserve a job from one of the watched tubes, with optional timeout\n in seconds. Returns a Job object, or None if the request times out." ]
Please provide a description of the function:def release(self, jid, priority=DEFAULT_PRIORITY, delay=0): self._interact('release %d %d %d\r\n' % (jid, priority, delay), ['RELEASED', 'BURIED'], ['NOT_FOUND'])
[ "Release a reserved job back into the ready queue." ]
Please provide a description of the function:def delete(self): self.conn.delete(self.jid) self.reserved = False
[ "Delete this job." ]
Please provide a description of the function:def release(self, priority=None, delay=0): if self.reserved: self.conn.release(self.jid, priority or self._priority(), delay) self.reserved = False
[ "Release this job back into the ready queue." ]
Please provide a description of the function:def bury(self, priority=None): if self.reserved: self.conn.bury(self.jid, priority or self._priority()) self.reserved = False
[ "Bury this job." ]
Please provide a description of the function:def create( path, base_url, version=None, version_dev="master", env=None, registry=None, urls=None, ): if isinstance(path, (list, tuple)): path = os.path.join(*path) if env is not None and env in os.environ and os.environ[env]...
[ "\n Create a new :class:`~pooch.Pooch` with sensible defaults to fetch data files.\n\n If a version string is given, the Pooch will be versioned, meaning that the local\n storage folder and the base URL depend on the project version. This is necessary\n if your users have multiple versions of your libra...
Please provide a description of the function:def abspath(self): "Absolute path to the local storage" return Path(os.path.abspath(os.path.expanduser(str(self.path))))
[]
Please provide a description of the function:def fetch(self, fname, processor=None): self._assert_file_in_registry(fname) # Create the local data directory if it doesn't already exist if not self.abspath.exists(): os.makedirs(str(self.abspath)) full_path = self.abs...
[ "\n Get the absolute path to a file in the local storage.\n\n If it's not in the local storage, it will be downloaded. If the hash of the file\n in local storage doesn't match the one in the registry, will download a new copy\n of the file. This is considered a sign that the file was upd...
Please provide a description of the function:def get_url(self, fname): self._assert_file_in_registry(fname) return self.urls.get(fname, "".join([self.base_url, fname]))
[ "\n Get the full URL to download a file in the registry.\n\n Parameters\n ----------\n fname : str\n The file name (relative to the *base_url* of the remote data storage) to\n fetch from the local storage.\n\n " ]
Please provide a description of the function:def _download_file(self, fname): destination = self.abspath / fname source = self.get_url(fname) # Stream the file to a temporary so that we can safely check its hash before # overwriting the original fout = tempfile.NamedTemp...
[ "\n Download a file from the remote data storage to the local storage.\n\n Used by :meth:`~pooch.Pooch.fetch` to do the actual downloading.\n\n Parameters\n ----------\n fname : str\n The file name (relative to the *base_url* of the remote data storage) to\n ...
Please provide a description of the function:def load_registry(self, fname): with open(fname) as fin: for linenum, line in enumerate(fin): elements = line.strip().split() if len(elements) > 3 or len(elements) < 2: raise IOError( ...
[ "\n Load entries from a file and add them to the registry.\n\n Use this if you are managing many files.\n\n Each line of the file should have file name and its SHA256 hash separate by a\n space. Only one file per line is allowed. Custom download URLs for individual\n files can be ...
Please provide a description of the function:def is_available(self, fname): self._assert_file_in_registry(fname) source = self.get_url(fname) response = requests.head(source, allow_redirects=True) return bool(response.status_code == 200)
[ "\n Check availability of a remote file without downloading it.\n\n Use this method when working with large files to check if they are available for\n download.\n\n Parameters\n ----------\n fname : str\n The file name (relative to the *base_url* of the remote da...
Please provide a description of the function:def file_hash(fname): # Calculate the hash in chunks to avoid overloading the memory chunksize = 65536 hasher = hashlib.sha256() with open(fname, "rb") as fin: buff = fin.read(chunksize) while buff: hasher.update(buff) ...
[ "\n Calculate the SHA256 hash of a given file.\n\n Useful for checking if a file has changed or been corrupted.\n\n Parameters\n ----------\n fname : str\n The name of the file.\n\n Returns\n -------\n hash : str\n The hash of the file.\n\n Examples\n --------\n\n >>> ...
Please provide a description of the function:def check_version(version, fallback="master"): parse = Version(version) if parse.local is not None: return fallback return version
[ "\n Check that a version string is PEP440 compliant and there are no unreleased changes.\n\n For example, ``version = \"0.1\"`` will be returned as is but\n ``version = \"0.1+10.8dl8dh9\"`` will return the fallback. This is the convention used\n by `versioneer <https://github.com/warner/python-versionee...
Please provide a description of the function:def make_registry(directory, output, recursive=True): directory = Path(directory) if recursive: pattern = "**/*" else: pattern = "*" files = sorted( [ str(path.relative_to(directory)) for path in directory...
[ "\n Make a registry of files and hashes for the given directory.\n\n This is helpful if you have many files in your test dataset as it keeps you\n from needing to manually update the registry.\n\n Parameters\n ----------\n directory : str\n Directory of the test data to put in the registry....
Please provide a description of the function:def load(fp, encoding=None, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, use_decimal=False, **kw): return loads(fp.read(), encoding=encoding, cls=cls, object_hook=object_hook, ...
[ "Deserialize ``fp`` (a ``.read()``-supporting file-like object containing\n a JSON document) to a Python object.\n\n *encoding* determines the encoding used to interpret any\n :class:`str` objects decoded by this instance (``'utf-8'`` by\n default). It has no effect when decoding :class:`unicode` objec...
Please provide a description of the function:def encode_basestring(s): if isinstance(s, str) and HAS_UTF8.search(s) is not None: s = s.decode('utf-8') def replace(match): return ESCAPE_DCT[match.group(0)] return u'"' + ESCAPE.sub(replace, s) + u'"'
[ "Return a JSON representation of a Python string\n\n " ]
Please provide a description of the function:def loads(s, **kwargs): try: return _engine[0](s) except _engine[2]: # except_clause: 'except' [test ['as' NAME]] # grammar for py3x # except_clause: 'except' [test [('as' | ',') test]] # grammar for py2x why = sys.exc_info()[1...
[ "Loads JSON object." ]
Please provide a description of the function:def dumps(o, **kwargs): try: return _engine[1](o) except: ExceptionClass, why = sys.exc_info()[:2] if any([(issubclass(ExceptionClass, e)) for e in _engine[2]]): raise JSONError(why) else: raise why
[ "Dumps JSON object." ]
Please provide a description of the function:def decode(self, s, _w=WHITESPACE.match): obj, end = self.raw_decode(s, idx=_w(s, 0).end()) end = _w(s, end).end() if end != len(s): raise JSONDecodeError("Extra data", s, end, len(s)) return obj
[ "Return the Python representation of ``s`` (a ``str`` or ``unicode``\n instance containing a JSON document)\n\n " ]
Please provide a description of the function:def from_query(query, engine=None, limit=None): if limit is not None: query = query.limit(limit) result_proxy = execute_query_return_result_proxy(query) return from_db_cursor(result_proxy.cursor)
[ "\n Execute an ORM style query, and return the result in\n :class:`prettytable.PrettyTable`.\n\n :param query: an ``sqlalchemy.orm.Query`` object.\n :param engine: an ``sqlalchemy.engine.base.Engine`` object.\n :param limit: int, limit rows to return.\n\n :return: a ``prettytable.PrettyTable`` obj...
Please provide a description of the function:def from_table(table, engine, limit=None): sql = select([table]) if limit is not None: sql = sql.limit(limit) result_proxy = engine.execute(sql) return from_db_cursor(result_proxy.cursor)
[ "\n Select data in a database table and put into prettytable.\n\n Create a :class:`prettytable.PrettyTable` from :class:`sqlalchemy.Table`.\n\n **中文文档**\n\n 将数据表中的数据放入prettytable中.\n " ]
Please provide a description of the function:def from_object(orm_class, engine, limit=None): Session = sessionmaker(bind=engine) ses = Session() query = ses.query(orm_class) if limit is not None: query = query.limit(limit) result_proxy = execute_query_return_result_proxy(query) ses....
[ "\n Select data from the table defined by a ORM class, and put into prettytable\n\n :param orm_class: an orm class inherit from\n ``sqlalchemy.ext.declarative.declarative_base()``\n :param engine: an ``sqlalchemy.engine.base.Engine`` object.\n :param limit: int, limit rows to return.\n\n **中文文...
Please provide a description of the function:def from_data(data): if len(data) == 0: # pragma: no cover return None else: ptable = PrettyTable() ptable.field_names = data[0].keys() for row in data: ptable.add_row(row) return ptable
[ "\n Construct a Prettytable from list of rows.\n " ]
Please provide a description of the function:def from_everything(everything, engine, limit=None): if isinstance(everything, Table): return from_table(everything, engine, limit=limit) if type(everything) is DeclarativeMeta: return from_object(everything, engine, limit=limit) if isinsta...
[ "\n Construct a Prettytable from any kinds of sqlalchemy query.\n " ]
Please provide a description of the function:def great_circle(point1, point2, miles=True): # unpack latitude/longitude lat1, lng1 = point1 lat2, lng2 = point2 # convert all latitudes/longitudes from decimal degrees to radians lat1, lng1, lat2, lng2 = list(map(radians, [lat1, lng1, lat2, lng2])...
[ " Calculate the great-circle distance bewteen two points on the Earth surface.\n :input: two 2-tuples, containing the latitude and longitude of each point\n in decimal degrees.\n Example: haversine((45.7597, 4.8422), (48.8567, 2.3508))\n :output: Returns the distance bewteen the two points.\n The def...
Please provide a description of the function:def generate_table(self, rows): table = PrettyTable(**self.kwargs) for row in self.rows: if len(row[0]) < self.max_row_width: appends = self.max_row_width - len(row[0]) for i in range(1, appends): ...
[ "\n Generates from a list of rows a PrettyTable object.\n " ]
Please provide a description of the function:def sql_to_csv(sql, engine, filepath, chunksize=1000, overwrite=False): if overwrite: # pragma: no cover if os.path.exists(filepath): raise Exception("'%s' already exists!" % filepath) import pandas as pd columns = [str(column.name) fo...
[ "\n Export sql result to csv file.\n\n :param sql: :class:`sqlalchemy.sql.selectable.Select` instance.\n :param engine: :class:`sqlalchemy.engine.base.Engine`.\n :param filepath: file path.\n :param chunksize: number of rows write to csv each time.\n :param overwrite: bool, if True, avoid to overi...
Please provide a description of the function:def table_to_csv(table, engine, filepath, chunksize=1000, overwrite=False): sql = select([table]) sql_to_csv(sql, engine, filepath, chunksize)
[ "\n Export entire table to a csv file.\n\n :param table: :class:`sqlalchemy.Table` instance.\n :param engine: :class:`sqlalchemy.engine.base.Engine`.\n :param filepath: file path.\n :param chunksize: number of rows write to csv each time.\n :param overwrite: bool, if True, avoid to overite existin...
Please provide a description of the function:def update_all(engine, table, data, upsert=False): data = ensure_list(data) ins = table.insert() upd = table.update() # Find all primary key columns pk_cols = OrderedDict() for column in table._columns: if column.primary_key: ...
[ "\n Update data by its primary_key column.\n " ]
Please provide a description of the function:def upsert_all(engine, table, data): update_all(engine, table, data, upsert=True)
[ "\n Update data by primary key columns. If not able to update, do insert.\n\n Example::\n\n # suppose in database we already have {\"id\": 1, \"name\": \"Alice\"}\n >>> data = [\n ... {\"id\": 1, \"name\": \"Bob\"}, # this will be updated\n ... {\"id\": 2, \"name\": \"Cathy...
Please provide a description of the function:def ensure_session(engine_or_session): if isinstance(engine_or_session, Engine): ses = sessionmaker(bind=engine_or_session)() auto_close = True elif isinstance(engine_or_session, Session): ses = engine_or_session auto_close = Fals...
[ "\n If it is an engine, then create a session from it. And indicate that\n this session should be closed after the job done.\n " ]
Please provide a description of the function:def pk_names(cls): if cls._cache_pk_names is None: cls._cache_pk_names = cls._get_primary_key_names() return cls._cache_pk_names
[ "\n Primary key column name list.\n " ]
Please provide a description of the function:def id_field_name(cls): if cls._cache_id_field_name is None: pk_names = cls.pk_names() if len(pk_names) == 1: cls._cache_id_field_name = pk_names[0] else: # pragma: no cover raise ValueErro...
[ "\n If only one primary_key, then return it. Otherwise, raise ValueError.\n " ]
Please provide a description of the function:def values(self): return [getattr(self, c.name, None) for c in self.__table__._columns]
[ "\n return list of value of all declared columns.\n " ]
Please provide a description of the function:def items(self): return [ (c.name, getattr(self, c.name, None)) for c in self.__table__._columns ]
[ "\n return list of pair of name and value of all declared columns.\n " ]
Please provide a description of the function:def to_dict(self, include_null=True): if include_null: return dict(self.items()) else: return { attr: value for attr, value in self.__dict__.items() if not attr.startswith("_sa_"...
[ "\n Convert to dict.\n " ]
Please provide a description of the function:def to_OrderedDict(self, include_null=True): if include_null: return OrderedDict(self.items()) else: items = list() for c in self.__table__._columns: try: items.append((c.name, s...
[ "\n Convert to OrderedDict.\n " ]
Please provide a description of the function:def absorb(self, other): if not isinstance(other, self.__class__): raise TypeError("`other` has to be a instance of %s!" % self.__class__) for attr, value in other.items(): if value is not None: ...
[ "\n For attributes of others that value is not None, assign it to self.\n\n **中文文档**\n\n 将另一个文档中的数据更新到本条文档。当且仅当数据值不为None时。\n " ]
Please provide a description of the function:def revise(self, data): if not isinstance(data, dict): raise TypeError("`data` has to be a dict!") for key, value in data.items(): if value is not None: setattr(self, key, deepcopy(value))
[ "\n Revise attributes value with dictionary data.\n\n **中文文档**\n\n 将一个字典中的数据更新到本条文档。当且仅当数据值不为None时。\n " ]
Please provide a description of the function:def by_id(cls, _id, engine_or_session): ses, auto_close = ensure_session(engine_or_session) obj = ses.query(cls).get(_id) if auto_close: ses.close() return obj
[ "\n Get one object by primary_key value.\n " ]
Please provide a description of the function:def by_sql(cls, sql, engine_or_session): ses, auto_close = ensure_session(engine_or_session) result = ses.query(cls).from_statement(sql).all() if auto_close: ses.close() return result
[ "\n Query with sql statement or texture sql.\n " ]
Please provide a description of the function:def smart_insert(cls, engine_or_session, data, minimal_size=5, op_counter=0): ses, auto_close = ensure_session(engine_or_session) if isinstance(data, list): # 首先进行尝试bulk insert try: ses.add_all(data) ...
[ "\n An optimized Insert strategy.\n\n :return: number of insertion operation been executed. Usually it is\n greatly smaller than ``len(data)``.\n\n **中文文档**\n\n 在Insert中, 如果已经预知不会出现IntegrityError, 那么使用Bulk Insert的速度要\n 远远快于逐条Insert。而如果无法预知, 那么我们采用如下策略:\n\n 1. 尝试B...
Please provide a description of the function:def update_all(cls, engine, obj_or_data, upsert=False): obj_or_data = ensure_list(obj_or_data) update_all( engine=engine, table=cls.__table__, data=[obj.to_dict(include_null=False) for obj in obj_or_data], ...
[ "\n The :meth:`sqlalchemy.crud.updating.update_all` function in ORM syntax.\n\n :param engine: an engine created by``sqlalchemy.create_engine``.\n :param obj_or_data: single object or list of object\n :param upsert: if True, then do insert also.\n " ]
Please provide a description of the function:def upsert_all(cls, engine, obj_or_data): cls.update_all( engine=engine, obj_or_data=obj_or_data, upsert=True, )
[ "\n The :meth:`sqlalchemy.crud.updating.upsert_all` function in ORM syntax.\n\n :param engine: an engine created by``sqlalchemy.create_engine``.\n :param obj_or_data: single object or list of object\n " ]
Please provide a description of the function:def fixcode(**kwargs): # repository direcotry repo_dir = Path(__file__).parent.absolute() # source code directory source_dir = Path(repo_dir, package.__name__) if source_dir.exists(): print("Source code locate at: '%s'." % source_dir) ...
[ "\n auto pep8 format all python file in ``source code`` and ``tests`` dir.\n " ]
Please provide a description of the function:def _get_rows(self, options): if options["oldsortslice"]: rows = copy.deepcopy(self._rows[options["start"]:options["end"]]) else: rows = copy.deepcopy(self._rows) # Sort if options["sortby"]: sort...
[ "Return only those data rows that should be printed, based on slicing and sorting.\n\n Arguments:\n\n options - dictionary of option settings." ]
Please provide a description of the function:def get_string(self, **kwargs): options = self._get_options(kwargs) lines = [] # Don't think too hard about an empty table # Is this the desired behaviour? Maybe we should still print the # header? if self.rowcount...
[ "Return string representation of table in current state.\n\n Arguments:\n\n title - optional table title\n start - index of first data row to include in output\n end - index of last data row to include in output PLUS ONE (list slice style)\n fields - names of fields (columns) to i...
Please provide a description of the function:def create_postgresql(username, password, host, port, database, **kwargs): # pragma: no cover return create_engine( _create_postgresql(username, password, host, port, database), **kwargs )
[ "\n create an engine connected to a postgresql database using psycopg2.\n " ]
Please provide a description of the function:def create_postgresql_psycopg2(username, password, host, port, database, **kwargs): # pragma: no cover return create_engine( _create_postgresql_psycopg2(username, password, host, port, database), **kwargs )
[ "\n create an engine connected to a postgresql database using psycopg2.\n " ]
Please provide a description of the function:def create_postgresql_pg8000(username, password, host, port, database, **kwargs): # pragma: no cover return create_engine( _create_postgresql_pg8000(username, password, host, port, database), **kwargs )
[ "\n create an engine connected to a postgresql database using pg8000.\n " ]
Please provide a description of the function:def create_postgresql_pygresql(username, password, host, port, database, **kwargs): # pragma: no cover return create_engine( _create_postgresql_pygresql(username, password, host, port, database), **kwargs )
[ "\n create an engine connected to a postgresql database using pygresql.\n " ]
Please provide a description of the function:def create_postgresql_psycopg2cffi(username, password, host, port, database, **kwargs): # pragma: no cover return create_engine( _create_postgresql_psycopg2cffi( username, password, host, port, database), **kwargs )
[ "\n create an engine connected to a postgresql database using psycopg2cffi.\n " ]
Please provide a description of the function:def create_postgresql_pypostgresql(username, password, host, port, database, **kwargs): # pragma: no cover return create_engine( _create_postgresql_pypostgresql( username, password, host, port, database), **kwargs )
[ "\n create an engine connected to a postgresql database using pypostgresql.\n " ]
Please provide a description of the function:def create_mysql(username, password, host, port, database, **kwargs): # pragma: no cover return create_engine( _create_mysql(username, password, host, port, database), **kwargs )
[ "\n create an engine connected to a mysql database using mysqldb.\n " ]
Please provide a description of the function:def create_mysql_mysqldb(username, password, host, port, database, **kwargs): # pragma: no cover return create_engine( _create_mysql_mysqldb(username, password, host, port, database), **kwargs )
[ "\n create an engine connected to a mysql database using mysqldb.\n " ]
Please provide a description of the function:def create_mysql_mysqlconnector(username, password, host, port, database, **kwargs): # pragma: no cover return create_engine( _create_mysql_mysqlconnector(username, password, host, port, database), **kwargs )
[ "\n create an engine connected to a mysql database using mysqlconnector.\n " ]
Please provide a description of the function:def create_mysql_oursql(username, password, host, port, database, **kwargs): # pragma: no cover return create_engine( _create_mysql_oursql(username, password, host, port, database), **kwargs )
[ "\n create an engine connected to a mysql database using oursql.\n " ]
Please provide a description of the function:def create_mysql_pymysql(username, password, host, port, database, **kwargs): # pragma: no cover return create_engine( _create_mysql_pymysql(username, password, host, port, database), **kwargs )
[ "\n create an engine connected to a mysql database using pymysql.\n " ]
Please provide a description of the function:def create_mysql_cymysql(username, password, host, port, database, **kwargs): # pragma: no cover return create_engine( _create_mysql_cymysql(username, password, host, port, database), **kwargs )
[ "\n create an engine connected to a mysql database using cymysql.\n " ]
Please provide a description of the function:def create_oracle(username, password, host, port, database, **kwargs): # pragma: no cover return create_engine( _create_oracle(username, password, host, port, database), **kwargs )
[ "\n create an engine connected to a oracle database using cx_oracle.\n " ]
Please provide a description of the function:def create_oracle_cx_oracle(username, password, host, port, database, **kwargs): # pragma: no cover return create_engine( _create_oracle_cx_oracle(username, password, host, port, database), **kwargs )
[ "\n create an engine connected to a oracle database using cx_oracle.\n " ]
Please provide a description of the function:def create_mssql_pyodbc(username, password, host, port, database, **kwargs): # pragma: no cover return create_engine( _create_mssql_pyodbc(username, password, host, port, database), **kwargs )
[ "\n create an engine connected to a mssql database using pyodbc.\n " ]
Please provide a description of the function:def create_mssql_pymssql(username, password, host, port, database, **kwargs): # pragma: no cover return create_engine( _create_mssql_pymssql(username, password, host, port, database), **kwargs )
[ "\n create an engine connected to a mssql database using pymssql.\n " ]
Please provide a description of the function:def titleize(text): if len(text) == 0: # if empty string, return it return text else: text = text.lower() # lower all char # delete redundant empty space chunks = [chunk[0].upper() + chunk[1:] for chunk in text.split(" ") if len(...
[ "Capitalizes all the words and replaces some characters in the string \n to create a nicer looking title.\n " ]
Please provide a description of the function:def grouper_list(l, n): chunk = list() counter = 0 for item in l: counter += 1 chunk.append(item) if counter == n: yield chunk chunk = list() counter = 0 if len(chunk) > 0: yield chunk
[ "Evenly divide list into fixed-length piece, no filled value if chunk\n size smaller than fixed-length.\n\n Example::\n\n >>> list(grouper(range(10), n=3)\n [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]\n\n **中文文档**\n\n 将一个列表按照尺寸n, 依次打包输出, 有多少输出多少, 并不强制填充包的大小到n。\n\n 下列实现是按照性能从高到低进行排列的:\n\n ...
Please provide a description of the function:def convert_query_to_sql_statement(query): context = query._compile_context() context.statement.use_labels = False return context.statement
[ "\n Convert a Query object created from orm query, into executable sql statement.\n\n :param query: :class:`sqlalchemy.orm.Query`\n\n :return: :class:`sqlalchemy.sql.selectable.Select`\n " ]
Please provide a description of the function:def execute_query_return_result_proxy(query): context = query._compile_context() context.statement.use_labels = False if query._autoflush and not query._populate_existing: query.session._autoflush() conn = query._get_bind_args( context, ...
[ "\n Execute a query, yield result proxy.\n\n :param query: :class:`sqlalchemy.orm.Query`,\n has to be created from ``session.query(Object)``\n\n :return: :class:`sqlalchemy.engine.result.ResultProxy`\n " ]
Please provide a description of the function:def find_state(self, state, best_match=True, min_similarity=70): result_state_short_list = list() # check if it is a abbreviate name if state.upper() in STATE_ABBR_SHORT_TO_LONG: result_state_short_list.append(state.upper()) ...
[ "\n Fuzzy search correct state.\n\n :param best_match: bool, when True, only the best matched state\n will be return. otherwise, will return all matching states.\n " ]
Please provide a description of the function:def find_city(self, city, state=None, best_match=True, min_similarity=70): # find out what is the city that user looking for if state: state_sort = self.find_state(state, best_match=True)[0] city_pool = self.state_to_city_mapp...
[ "\n Fuzzy search correct city.\n\n :param city: city name.\n :param state: search city in specified state.\n :param best_match: bool, when True, only the best matched city\n will return. otherwise, will return all matching cities.\n\n **中文文档**\n\n 如果给定了state, 则只在...
Please provide a description of the function:def _resolve_sort_by(sort_by, flag_radius_query): if sort_by is None: if flag_radius_query: sort_by = SORT_BY_DIST elif isinstance(sort_by, string_types): if sort_by.lower() == SORT_BY_DIST: if ...
[ "\n Result ``sort_by`` argument.\n\n :param sort_by: str, or sqlalchemy ORM attribute.\n :param flag_radius_query:\n :return:\n " ]
Please provide a description of the function:def query(self, zipcode=None, prefix=None, pattern=None, city=None, state=None, lat=None, lng=None, radius=None, population_lower=None, ...
[ "\n Query zipcode the simple way.\n\n :param zipcode: int or str, find the exactly matched zipcode. Will be\n automatically zero padding to 5 digits\n :param prefix: str, zipcode prefix.\n :param pattern: str, zipcode wildcard.\n :param city: str, city name.\n :p...
Please provide a description of the function:def by_zipcode(self, zipcode, zipcode_type=None, zero_padding=True): if zero_padding: zipcode = str(zipcode).zfill(5) else: # pragma: no cover zipcode = str(zipcode) ...
[ "\n Search zipcode by exact 5 digits zipcode. No zero padding is needed.\n\n :param zipcode: int or str, the zipcode will be automatically\n zero padding to 5 digits.\n :param zipcode_type: str or :class`~uszipcode.model.ZipcodeType` attribute.\n by default, it returns any...