code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
# type: (str) -> List[str]
if PYLINT_CONFIG_NAME in os.listdir(config_dir):
pylint_config_path = PYLINT_CONFIG_NAME
else:
pylint_config_path = DEFAULT_PYLINT_CONFIG_PATH
return ['--rcfile={}'.format(pylint_config_path)] | def get_pylint_options(config_dir='.') | Checks for local config overrides for `pylint`
and add them in the correct `pylint` `options` format.
:param config_dir:
:return: List [str] | 2.60825 | 3.172981 | 0.822019 |
timeout = kwargs.get("timeout")
composite_event = threading.Event()
if any([event.is_set() for event in events]):
return
def on_change():
if any([event.is_set() for event in events]):
composite_event.set()
else:
composite_event.clear()
def patc... | def wait_on_any(*events, **kwargs) | Helper method for waiting for any of the given threading events to be
set.
The standard threading lib doesn't include any mechanism for waiting on
more than one event at a time so we have to monkey patch the events
so that their `set()` and `clear()` methods fire a callback we can use
to determine ... | 2.851454 | 2.518962 | 1.131995 |
if timeout is not None:
event.wait(timeout)
return
if six.PY2:
# Thanks to a bug in python 2's threading lib, we can't simply call
# .wait() with no timeout since it would wind up ignoring signals.
while not event.is_set():
event.wait(sys.maxint)
els... | def wait_on_event(event, timeout=None) | Waits on a single threading Event, with an optional timeout.
This is here for compatibility reasons as python 2 can't reliably wait
on an event without a timeout and python 3 doesn't define a `maxint`. | 6.134295 | 5.391921 | 1.137683 |
if "config_file" not in config:
raise ValueError("No config file path given")
if "socket_file" not in config:
raise ValueError("No control socket path given")
if "pid_file" not in config:
raise ValueError("No PID file path given")
if "stats" i... | def validate_config(cls, config) | Validates that a config file path and a control socket file path
and pid file path are all present in the HAProxy config. | 3.311948 | 2.671765 | 1.239611 |
for name, proxy in six.iteritems(proxies):
if "port" not in proxy:
raise ValueError("No port defined for proxy %s" % name)
if "upstreams" not in proxy:
raise ValueError(
"No upstreams defined for proxy %s" % name
... | def validate_proxies_config(cls, proxies) | Specific config validation method for the "proxies" portion of a
config.
Checks that each proxy defines a port and a list of `upstreams`,
and that each upstream entry has a host and port defined. | 2.006575 | 1.667539 | 1.203315 |
self.haproxy_config_path = config["config_file"]
global_stanza = Stanza("global")
global_stanza.add_lines(config.get("global", []))
global_stanza.add_lines([
"stats socket %s mode 600 level admin" % config["socket_file"],
"stats timeout 2m"
])
... | def apply_config(self, config) | Constructs HAProxyConfig and HAProxyControl instances based on the
contents of the config.
This is mostly a matter of constructing the configuration stanzas. | 3.030472 | 2.87039 | 1.05577 |
logger.info("Updating HAProxy config file.")
if not self.restart_required:
self.sync_nodes(clusters)
version = self.control.get_version()
with open(self.haproxy_config_path, "w") as f:
f.write(self.config_file.generate(clusters, version=version))
... | def sync_file(self, clusters) | Generates new HAProxy config file content and writes it to the
file at `haproxy_config_path`.
If a restart is not necessary the nodes configured in HAProxy will
be synced on the fly. If a restart *is* necessary, one will be
triggered. | 4.549635 | 3.640066 | 1.249877 |
delay = (self.last_restart - time.time()) + self.restart_interval
if delay > 0:
time.sleep(delay)
self.control.restart()
self.last_restart = time.time()
self.restart_required = False | def restart(self) | Tells the HAProxy control object to restart the process.
If it's been fewer than `restart_interval` seconds since the previous
restart, it will wait until the interval has passed. This staves off
situations where the process is constantly restarting, as it is
possible to drop packets f... | 3.651832 | 3.062809 | 1.192315 |
logger.info("Syncing HAProxy backends.")
current_nodes, enabled_nodes = self.get_current_nodes(clusters)
for cluster_name, nodes in six.iteritems(current_nodes):
for node in nodes:
if node["svname"] in enabled_nodes[cluster_name]:
comman... | def sync_nodes(self, clusters) | Syncs the enabled/disabled status of nodes existing in HAProxy based
on the given clusters.
This is used to inform HAProxy of up/down nodes without necessarily
doing a restart of the process. | 3.828582 | 3.550799 | 1.078231 |
current_nodes = self.control.get_active_nodes()
enabled_nodes = collections.defaultdict(list)
for cluster in clusters:
if not cluster.nodes:
continue
if cluster.name not in current_nodes:
logger.debug(
"New cl... | def get_current_nodes(self, clusters) | Returns two dictionaries, the current nodes and the enabled nodes.
The current_nodes dictionary is keyed off of the cluster name and
values are a list of nodes known to HAProxy.
The enabled_nodes dictionary is also keyed off of the cluster name
and values are list of *enabled* nodes, i... | 2.813548 | 2.613198 | 1.076669 |
if "discovery" not in config:
raise ValueError("No discovery method defined.")
if not any([item in config for item in ["port", "ports"]]):
raise ValueError("No port(s) defined.")
cls.validate_check_configs(config) | def validate_config(cls, config) | Runs a check on the given config to make sure that `port`/`ports` and
`discovery` is defined. | 6.634019 | 4.332029 | 1.531388 |
if "checks" not in config:
raise ValueError("No checks defined.")
if "interval" not in config["checks"]:
raise ValueError("No check interval defined.")
for check_name, check_config in six.iteritems(config["checks"]):
if check_name == "interval":
... | def validate_check_configs(cls, config) | Config validation specific to the health check options.
Verifies that checks are defined along with an interval, and calls
out to the `Check` class to make sure each individual check's config
is valid. | 2.902316 | 2.690001 | 1.078927 |
self.host = config.get("host", "127.0.0.1")
self.configured_ports = config.get("ports", [config.get("port")])
self.discovery = config["discovery"]
self.metadata = config.get("metadata", {})
self.update_ports()
self.check_interval = config["checks"]["interval... | def apply_config(self, config) | Takes a given validated config dictionary and sets an instance
attribute for each one.
For check definitions, a Check instance is is created and a `checks`
attribute set to a dictionary keyed off of the checks' names. If
the Check instance has some sort of error while being created an ... | 4.280499 | 4.152641 | 1.03079 |
ports = set()
for port in self.configured_ports:
try:
ports.add(int(port))
except ValueError:
logger.error("Invalid port value: %s", port)
continue
self.ports = ports | def update_ports(self) | Sets the `ports` attribute to the set of valid port values set in
the configuration. | 3.75252 | 2.945843 | 1.273836 |
for check_name, check_config in six.iteritems(check_configs):
if check_name == "interval":
continue
for port in self.ports:
try:
check = Check.from_config(check_name, check_config)
check.host = self.host
... | def update_checks(self, check_configs) | Maintains the values in the `checks` attribute's dictionary. Each
key in the dictionary is a port, and each value is a nested dictionary
mapping each check's name to the Check instance.
This method makes sure the attribute reflects all of the properly
configured checks and ports. Remo... | 2.867685 | 2.846747 | 1.007355 |
came_up = set()
went_down = set()
for port in self.ports:
checks = self.checks[port].values()
if not checks:
logger.warn("No checks defined for self: %s", self.name)
for check in checks:
check.run()
chec... | def run_checks(self) | Iterates over the configured ports and runs the checks on each one.
Returns a two-element tuple: the first is the set of ports that
transitioned from down to up, the second is the set of ports that
transitioned from up to down.
Also handles the case where a check for a since-removed po... | 2.770136 | 2.640265 | 1.049189 |
from aiida.orm.data.singlefile import SinglefileData
success = False
node_list = []
# Check that the retrieved folder is there
try:
out_folder = retrieved['retrieved']
except KeyError:
self.logger.error("No retrieved folder found")
... | def parse_with_retrieved(self, retrieved) | Parse output data folder, store results in database.
:param retrieved: a dictionary of retrieved nodes, where
the key is the link name
:returns: a tuple with two values ``(bool, node_list)``,
where:
* ``bool``: variable to tell if the parsing succeeded
* ``node_... | 2.834302 | 2.787465 | 1.016803 |
rows_updated = queryset.update(Alive=False, Death=datetime.date.today(), Cause_of_Death='Sacrificed')
if rows_updated == 1:
message_bit = "1 animal was"
else:
message_bit = "%s animals were" % rows_updated
self.message_user(request, "%s successfully marke... | def mark_sacrificed(self,request,queryset) | An admin action for marking several animals as sacrificed.
This action sets the selected animals as Alive=False, Death=today and Cause_of_Death as sacrificed. To use other paramters, mice muse be individually marked as sacrificed.
This admin action also shows as the output the number of mice sacrifi... | 2.25884 | 1.573574 | 1.435484 |
rows_updated = queryset.update(Active=False, End=datetime.date.today() )
if rows_updated == 1:
message_bit = "1 cage was"
else:
message_bit = "%s cages were" % rows_updated
self.message_user(request, "%s successfully marked as deactivated." % message_bit) | def mark_deactivated(self,request,queryset) | An admin action for marking several cages as inactive.
This action sets the selected cages as Active=False and Death=today.
This admin action also shows as the output the number of mice sacrificed. | 2.423448 | 1.867162 | 1.297931 |
flags_obj = flags.FLAGS
absl_flags_obj = absl_flags.FLAGS
# Extract the args from the optional `argv` list.
args = argv[1:] if argv else None
# Parse the known flags from that list, or from the command
# line otherwise.
# pylint: disable=protected-access
flags_passthrough = flags_... | def run(main=None, argv=None) | Runs the program with an optional 'main' function and 'argv' list. | 5.307054 | 5.001081 | 1.061181 |
if not isinstance(s, unicode):
if not isinstance(s, basestring):
return unicode(str(s), encoding, encoding_errors)
return unicode(s, encoding, encoding_errors)
return s | def make_unicode(s, encoding='utf-8', encoding_errors='strict') | Return the unicode version of an input. | 1.984068 | 1.916595 | 1.035205 |
return escape(make_unicode(s, encoding, encoding_errors), quote=True) | def html_escape(s, encoding='utf-8', encoding_errors='strict') | Return the HTML-escaped version of an input. | 6.875757 | 6.296047 | 1.092075 |
duration = float(duration)
constraints = [
rt_constraints.TimbrePitchConstraint(
context=0, timbre_weight=1.0, chroma_weight=1.0),
rt_constraints.EnergyConstraint(penalty=.5),
rt_constraints.MinimumLoopConstraint(8),
]
if beats_per_measure is not None:
... | def retarget_to_length(song, duration, start=True, end=True, slack=5,
beats_per_measure=None) | Create a composition of a song that changes its length
to a given duration.
:param song: Song to retarget
:type song: :py:class:`radiotool.composer.Song`
:param duration: Duration of retargeted song (in seconds)
:type duration: float
:param start: Start the retargeted song at the
... | 4.113117 | 4.192254 | 0.981123 |
analysis = song.analysis
beat_length = analysis[BEAT_DUR_KEY]
beats = np.array(analysis["beats"])
# find change points
cps = np.array(novelty(song, nchangepoints=4))
cp_times = np.array(cp_times)
# mark change points in original music
def music_labels(t):
# find beat clos... | def retarget_with_change_points(song, cp_times, duration) | Create a composition of a song of a given duration that reaches
music change points at specified times. This is still under
construction. It might not work as well with more than
2 ``cp_times`` at the moment.
Here's an example of retargeting music to be 40 seconds long and
hit a change point at the... | 4.142644 | 4.132892 | 1.00236 |
if scrapyd_url[-1:] != '/':
scrapyd_url = scrapyd_url + '/'
self['daemonstatus'] = [scrapyd_url + 'daemonstatus.json', http_utils.METHOD_GET]
self['addversion'] = [scrapyd_url + 'addversion.json', http_utils.METHOD_POST]
self['schedule'] = [scrapyd_url + 'schedule.j... | def init_command_set(self, scrapyd_url) | Initialize command set by scrapyd_url,each element is a list such as ['command','supported http method type'] | 1.668137 | 1.629538 | 1.023687 |
url, method = self.command_set['daemonstatus'][0], self.command_set['daemonstatus'][1]
response = http_utils.request(url, method_type=method, return_type=http_utils.RETURN_JSON)
if response is None:
logging.warning('%s failure: not found or connection fail' % sys._getframe()... | def get_load_status(self) | To check the load status of a service.
:return: a dictionary that include json data.
example: { "status": "ok", "running": "0", "pending": "0", "finished": "0", "node_name": "node-name" } | 6.479589 | 6.440181 | 1.006119 |
url, method = self.command_set['schedule'][0], self.command_set['schedule'][1]
data = {}
data['project'] = project_name
data['spider'] = spider_name
data['priority'] = priority
if setting is not None:
data['setting'] = setting
if job_id is not... | def schedule(self,
project_name,
spider_name,
priority=0,
setting=None,
job_id=None,
version=None,
args={}) | Schedule a spider run (also known as a job), returning the job id.
:param project_name: the project name
:param spider_name: the spider name
:param priority: the run priority
:param setting: a Scrapy setting to use when running the spider
:param job_id: a job id used to identify ... | 2.969504 | 3.04553 | 0.975037 |
url, method = self.command_set['cancel'][0], self.command_set['cancel'][1]
data = {}
data['project'] = project_name
data['job'] = job_id
response = http_utils.request(url, method_type=method, data=data, return_type=http_utils.RETURN_JSON)
if response is None:
... | def cancel(self, project_name, job_id) | Cancel a spider run (aka. job). If the job is pending, it will be removed. If the job is running, it will be terminated.
:param project_name: the project name
:param job_id: the job id
:return: a dictionary that status message
example: {"status": "ok", "prevstate": "running"} | 4.836404 | 4.952516 | 0.976555 |
url, method = self.command_set['listspiders'][0], self.command_set['listspiders'][1]
data = {}
data['project'] = project_name
if version is not None:
data['_version'] = version
response = http_utils.request(url, method_type=method, data=data, return_type=http... | def get_spider_list(self, project_name, version=None) | Get the list of spiders available in the last (unless overridden) version of some project.
:param project_name: the project name
:param version: the version of the project to examine
:return: a dictionary that spider name list
example: {"status": "ok", "spiders": ["spider1", "sp... | 4.35883 | 4.572634 | 0.953243 |
url, method = self.command_set['listjobs'][0], self.command_set['listjobs'][1]
data = {'project': project_name}
response = http_utils.request(url, method_type=method, data=data, return_type=http_utils.RETURN_JSON)
if response is None:
logging.warning('%s failure: not... | def get_job_list(self, project_name) | Get the list of pending, running and finished jobs of some project.
:param project_name: the project name
:return: a dictionary that list inculde job name and status
example:
{"status": "ok",
"pending": [{"id": "78391cc0fcaf11e1b0090800272a6d06", "sp... | 5.075368 | 4.989375 | 1.017235 |
url, method = self.command_set['logs'][0] + project_name + '/' + spider_name + '/', self.command_set['logs'][1]
response = http_utils.request(url, method_type=method)
html_parser = ScrapydLogsPageHTMLParser()
html_parser.feed(response)
html_parser.clean_enter_sign()
... | def get_logs(self, project_name, spider_name) | Get urls that scrapyd logs file by project name and spider name
:param project_name: the project name
:param spider_name: the spider name
:return: two list of the logs file name and logs file url | 5.866033 | 5.584663 | 1.050383 |
lspci_cmd = ['lspci', '-xxxx', '-v']
lspci_results = subprocess.run(lspci_cmd, stdout=subprocess.PIPE)
lspci_stdout = lspci_results.stdout.decode('utf-8')
config = [parse_lspci_output(stdout) for stdout
in lspci_stdout.split('\n\n') if stdout != '']
if vendor is not None:
... | def lspci(vendor=None, device=None) | Collect PCI information and return its list.
Parameters
----------
vendor : int
Return only devices with specified vendor ID.
device : int
Return only devices with specified device ID.
Returns
-------
list
List of PCI device information.
Informa... | 2.499969 | 2.748504 | 0.909575 |
verify_access_range(bar, offset, size)
if bar.type == 'io': return io_read(bar, offset, size)
if bar.type == 'mem': return mem_read(bar, offset, size)
return b'' | def read(bar, offset, size) | Read PCI data register.
Parameters
----------
bar : BaseAddressRegister
BAR to read.
offset : int
Address offset in BAR to read.
size : int
Data size to read.
Returns
-------
bytes
Data read from BAR
Examples
------... | 4.103658 | 5.131879 | 0.79964 |
if type(data) not in [bytes, bytearray]:
msg = 'data should be bytes or bytearray type'
raise TypeError(msg)
size = len(data)
verify_access_range(bar, offset, size)
if bar.type == 'io': return io_write(bar, offset, data)
if bar.type == 'mem': return mem_write(bar, offset, d... | def write(bar, offset, data) | Write data to PCI board.
Parameters
----------
bar : BaseAddressRegister
BAR to write.
offset : int
Address offset in BAR to write.
data : bytes
Data to write.
Returns
-------
None
Examples
--------
>>> b = pypci.lspci(vend... | 3.730509 | 4.648629 | 0.802497 |
import os
path = os.path.dirname(__file__)
path = os.path.join(path, 'data')
r = dict(
Alpha_inf_hyrec_file = os.path.join(path, 'hyrec', 'Alpha_inf.dat'),
R_inf_hyrec_file = os.path.join(path, 'hyrec', 'R_inf.dat'),
two_photon_tables_hyrec_file = os.path.join(path, 'hyrec'... | def get_data_files() | Returns the path of data files, which are installed to the package directory. | 3.312381 | 3.257811 | 1.016751 |
import os
if os.path.exists(filename):
path = filename
else:
path = os.path.dirname(__file__)
path = os.path.join(path, 'data', filename)
if not os.path.exists(path):
raise ValueError("cannot locate file '%s'" %filename)
return path | def _find_file(filename) | Find the file path, first checking if it exists and then looking in the
data directory | 2.659358 | 2.441926 | 1.089041 |
# also look in data dir
path = _find_file(filename)
r = dict()
with open(path, 'r') as f:
exec(f.read(), {}, r)
return r | def load_precision(filename) | Load a CLASS precision file into a dictionary.
Parameters
----------
filename : str
the name of an existing file to load, or one in the files included
as part of the CLASS source
Returns
-------
dict :
the precision parameters loaded from file | 6.205884 | 9.318092 | 0.666004 |
# also look in data dir
path = _find_file(filename)
pars = {}
with open(path, 'r') as ff:
# loop over lines
for lineno, line in enumerate(ff):
if not line: continue
# skip any commented lines with #
if '#' in line: line = line[line.index('#')+1... | def load_ini(filename) | Read a CLASS ``.ini`` file, returning a dictionary of parameters
Parameters
----------
filename : str
the name of an existing parameter file to load, or one included as
part of the CLASS source
Returns
-------
dict :
the input parameters loaded from file | 3.839418 | 4.312007 | 0.890402 |
tags = _normalize_tags(tagged_doc)
merge = True
while merge:
merge = False
for x in range(0, len(tags) - 1):
t1 = tags[x]
t2 = tags[x + 1]
key = t1[1], t2[1]
value = CFG.get(key, '')
if value:
merge = True
... | def extract_noun_phrases(tagged_doc) | (From textblob) | 2.876878 | 2.82479 | 1.01844 |
ret = []
for word, tag in chunk:
if tag == 'NP-TL' or tag == 'NP':
ret.append((word, 'NNP'))
continue
if tag.endswith('-TL'):
ret.append((word, tag[:-3]))
continue
if tag.endswith('S'):
ret.append((word, tag[:-1]))
... | def _normalize_tags(chunk) | (From textblob)
Normalize the corpus tags.
("NN", "NN-PL", "NNS") -> "NN" | 2.370052 | 2.254148 | 1.051418 |
nrows = patt.nrows
ncols = patt.ncols
frmstr = "{0},{1},{2:.16e},{3:.16e}\n"
ar = patt.array
with open(filename, 'w') as f:
f.write("{0},{1}\n".format(nrows, ncols))
for nr in xrange(0, nrows):
for nc in xrange(0, ncols):
f.write(frmstr.format(nr,... | def save_patt(patt, filename) | Saves ScalarPatternUniform object 'patt' to file. The first line of the
file has the number of rows and the number of columns in the pattern
separated by a comma (single sphere data). The remaining lines have the
form:
0, 1, 3.14, 2.718
The first two numbers are index for the row and in... | 2.911288 | 2.435776 | 1.19522 |
nmax = scoef.nmax
mmax = scoef.mmax
frmstr = "{0:.16e},{1:.16e}\n"
L = (nmax + 1) + mmax * (2 * nmax - mmax + 1);
with open(filename, 'w') as f:
f.write("{0},{1}\n".format(nmax, mmax))
for n in xrange(0, L):
f.write(frmstr.format(scoef._vec[n].real,
... | def save_coef(scoef, filename) | Saves ScalarCoeffs object 'scoef' to file. The first line of the
file has the max number N and the max number M of the scoef structure
separated by a comma. The remaining lines have the form
3.14, 2.718
The first number is the real part of the mode and the second is the
imaginary. | 3.711313 | 2.954305 | 1.256239 |
with open(filename) as f:
lines = f.readlines()
lst = lines[0].split(',')
patt = np.zeros([int(lst[0]), int(lst[1])],
dtype=np.complex128)
lines.pop(0)
for line in lines:
lst = line.split(',')
n = int(lst[0])
... | def load_patt(filename) | Loads a file that was saved with the save_patt routine. | 3.288549 | 3.326939 | 0.988461 |
with open(filename1) as f:
lines = f.readlines()
lst = lines[0].split(',')
patt1 = np.zeros([int(lst[0]), int(lst[1])],
dtype=np.complex128)
lines.pop(0)
for line in lines:
lst = line.split(',')
n = int(lst[0])
... | def load_vpatt(filename1, filename2) | Loads a VectorPatternUniform pattern that is saved between two files. | 1.806073 | 1.634136 | 1.105216 |
with open(filename) as f:
lines = f.readlines()
lst = lines[0].split(',')
nmax = int(lst[0])
mmax = int(lst[1])
L = (nmax + 1) + mmax * (2 * nmax - mmax + 1);
vec = np.zeros(L, dtype=np.complex128)
lines.pop(0)
for n, line in enumer... | def load_coef(filename) | Loads a file that was saved with save_coef. | 3.546266 | 3.619304 | 0.97982 |
with open(filename) as f:
lines = f.readlines()
lst = lines[0].split(',')
nmax = int(lst[0])
mmax = int(lst[1])
directivity = float(lst[2])
L = (nmax + 1) + mmax * (2 * nmax - mmax + 1);
vec1 = np.zeros(L, dtype=np.complex128)
vec2 = np.zero... | def load_vcoef(filename) | Loads a set of vector coefficients that were saved in MATLAB. The third
number on the first line is the directivity calculated within the MATLAB
code. | 2.837324 | 2.770719 | 1.024039 |
data = np.genfromtxt(filename)
#data = np.genfromtxt(filename, dtype= (int, int, float, float))
if max_life is not None:
data[np.isinf(data)] = max_life
return data | def parse(cls, filename, max_life=None) | Parse barcode from gudhi output. | 3.608573 | 3.464018 | 1.04173 |
import matplotlib.pyplot as plt
life_lines = self.get_life_lines(dimension)
x, y = zip(*life_lines)
plt.scatter(x, y)
plt.xlabel("Birth")
plt.ylabel("Death")
if self.max_life is not None:
plt.xlim([0, self.max_life])
plt.title("Pers... | def plot(self, dimension) | Plot barcode using matplotlib. | 4.068365 | 4.047061 | 1.005264 |
cls.validate_config(config)
instance = cls()
if not instance.name:
instance.name = config.get("name", name)
instance.apply_config(config)
return instance | def from_config(cls, name, config) | Returns a Configurable instance with the given name and config.
By default this is a simple matter of calling the constructor, but
subclasses that are also `Pluggable` instances override this in order
to check that the plugin is installed correctly first. | 4.120111 | 3.733495 | 1.103553 |
parser = argparse.ArgumentParser(
description="Provision multiple VM's through mist.io. You can get "
"information returned with the name of the virtual machine created "
"and its main mac and ip address in IPv4 format. A post-script can be "
"specified for post-processing.")
... | def get_args() | Supports the command-line arguments listed below. | 2.471254 | 2.454892 | 1.006665 |
rules = query.files.get_priority_rules(state.db)
print(tabulate(rules, headers=['ID', 'Regexp', 'Priority'])) | def command(state, args) | List file priority rules. | 12.555437 | 6.892431 | 1.821627 |
counts = defaultdict(lambda: 0)
for transaction in transactions:
for c in (c for c in candidates if set(c).issubset(transaction)):
counts[c] += 1
return {i for i in candidates if counts[i]/len(transactions) >= min_sup} | def filter_support(candidates, transactions, min_sup) | Filter candidates to a frequent set by some minimum support. | 3.017672 | 2.832193 | 1.06549 |
single_set = {(i,) for i in set(flatten(freq_set))}
# TO DO generating all combinations gets very slow for large documents.
# Is there a way of doing this without exhaustively searching all combinations?
cands = [flatten(f) for f in combinations(single_set, k)]
return [cand for cand in cands i... | def generate_candidates(freq_set, k) | Generate candidates for an iteration.
Use this only for k >= 2. | 7.848113 | 7.652634 | 1.025544 |
for subcand in combinations(candidate, k-1):
if subcand not in freq_set:
return False
return True | def validate_candidate(candidate, freq_set, k) | Checks if we should keep a candidate.
We keep a candidate if all its k-1-sized subsets
are present in the frequent sets. | 4.306559 | 3.767469 | 1.143091 |
if self.min_sup < 1/len(docs):
raise Exception('`min_sup` must be greater than or equal to `1/len(docs)`.')
# First pass
candidates = set()
transactions = []
# Use nouns and noun phrases.
for doc in POSTokenizer().tokenize(docs):
transac... | def tokenize(self, docs) | The first pass consists of converting documents
into "transactions" (sets of their tokens)
and the initial frequency/support filtering.
Then iterate until we close in on a final set.
`docs` can be any iterator or generator so long as it yields lists.
Each list represents a docu... | 4.67739 | 4.000582 | 1.169177 |
return re.compile(self.raw_tag_re % tags, self.re_flags) | def compile_tag_re(self, tags) | Return the regex used to look for Mustache tags compiled to work with
specific opening tags, close tags, and tag types. | 6.565265 | 7.036523 | 0.933027 |
"Write your forwards methods here."
# Note: Remember to use orm['appname.ModelName'] rather than "from appname.models..."
User = orm[user_orm_label]
try:
user = User.objects.all()[0]
for article in orm.Article.objects.all():
article.author = use... | def forwards(self, orm) | Write your forwards methods here. | 5.432275 | 4.547037 | 1.194685 |
# This uses a deque to collect output fragments in reverse order,
# then joins them together at the end. It's measurably faster
# than creating all the intermediate strings.
# If you're reading this to get a handle on the tnetstring format,
# consider the _gdumps() function instead; it's ... | def dumps(value,encoding=None) | dumps(object,encoding=None) -> string
This function dumps a python object as a tnetstring. | 12.350511 | 11.636155 | 1.061391 |
write = q.appendleft
if value is None:
write("0:~")
return size + 3
if value is True:
write("4:true!")
return size + 7
if value is False:
write("5:false!")
return size + 8
if isinstance(value,(int,long)):
data = str(value)
ldata =... | def _rdumpq(q,size,value,encoding=None) | Dump value as a tnetstring, to a deque instance, last chunks first.
This function generates the tnetstring representation of the given value,
pushing chunks of the output onto the given deque instance. It pushes
the last chunk first, then recursively generates more chunks.
When passed in the current ... | 2.369281 | 2.363423 | 1.002479 |
if value is None:
yield "0:~"
elif value is True:
yield "4:true!"
elif value is False:
yield "5:false!"
elif isinstance(value,(int,long)):
data = str(value)
yield str(len(data))
yield ":"
yield data
yield "#"
elif isinstance(value... | def _gdumps(value,encoding) | Generate fragments of value dumped as a tnetstring.
This is the naive dumping algorithm, implemented as a generator so that
it's easy to pass to "".join() without building a new list.
This is mainly here for comparison purposes; the _rdumpq version is
measurably faster as it doesn't have to build inte... | 2.100966 | 2.060457 | 1.01966 |
# Read the length prefix one char at a time.
# Note that the netstring spec explicitly forbids padding zeros.
c = file.read(1)
if not c.isdigit():
raise ValueError("not a tnetstring: missing or invalid length prefix")
datalen = ord(c) - ord("0")
c = file.read(1)
if datalen != ... | def load(file,encoding=None) | load(file,encoding=None) -> object
This function reads a tnetstring from a file and parses it into a
python object. The file must support the read() method, and this
function promises not to read more data than necessary. | 2.69367 | 2.583921 | 1.042474 |
# Parse out data length, type and remaining string.
try:
(dlen,rest) = string.split(":",1)
dlen = int(dlen)
except ValueError:
raise ValueError("not a tnetstring: missing or invalid length prefix")
try:
(data,type,remain) = (rest[:dlen],rest[dlen],rest[dlen+1:])
... | def pop(string,encoding=None) | pop(string,encoding=None) -> (object, remain)
This function parses a tnetstring into a python object.
It returns a tuple giving the parsed object and a string
containing any unparsed data from the end of the string. | 2.34382 | 2.253257 | 1.040192 |
return N.log(N.abs(N.fft.rfft(frames)).clip(1e-5, N.inf)) | def log_magnitude_spectrum(frames) | Compute the log of the magnitude spectrum of frames | 5.481852 | 5.075068 | 1.080153 |
f = frames.flatten()
return N.sqrt(N.mean(f * f)) | def RMS_energy(frames) | Computes the RMS energy of frames | 7.16542 | 6.347385 | 1.128878 |
return (features - N.min(features)) / (N.max(features) - N.min(features)) | def normalize_features(features) | Standardizes features array to fall between 0 and 1 | 3.233534 | 2.706424 | 1.194763 |
frames = N.array(frames)
crossings = N.where(N.diff(N.sign(frames)))
# crossings = N.where(frames[:n] * frames[1:n + 1] < 0)
if len(crossings[0]) == 0:
print "No zero crossing"
return len(frames) - 1
return crossings[0][-1] | def zero_crossing_last(frames) | Finds the last zero crossing in frames | 3.312481 | 3.062999 | 1.08145 |
dyn_range = 32767.0 / 32767.0
lim_thresh = 30000.0 / 32767.0
lim_range = dyn_range - lim_thresh
new_arr = arr.copy()
inds = N.where(arr > lim_thresh)[0]
new_arr[inds] = (new_arr[inds] - lim_thresh) / lim_range
new_arr[inds] = (N.arctan(new_arr[inds]) * 2.0 / N.pi) *\
lim_rang... | def limiter(arr) | Restrict the maximum and minimum values of arr | 2.277544 | 2.224786 | 1.023714 |
n = N.shape(arr1)[0]
try:
channels = N.shape(arr1)[1]
except:
channels = 1
f_in = N.linspace(0, 1, num=n)
f_out = N.linspace(1, 0, num=n)
# f_in = N.arange(n) / float(n - 1)
# f_out = N.arange(n - 1, -1, -1) / float(n)
if channels > 1:
f_in = N.tile(f_in, ... | def linear(arr1, arr2) | Create a linear blend of arr1 (fading out) and arr2 (fading in) | 2.232804 | 2.067202 | 1.080109 |
n = N.shape(arr1)[0]
try:
channels = N.shape(arr1)[1]
except:
channels = 1
f_in = N.arange(n) / float(n - 1)
f_out = N.arange(n - 1, -1, -1) / float(n)
if channels > 1:
f_in = N.tile(f_in, (channels, 1)).T
f_out = N.tile(f_out, (channels, 1)).T
vals = ... | def equal_power(arr1, arr2) | Create an equal power blend of arr1 (fading out) and arr2 (fading in) | 2.875337 | 2.646351 | 1.086529 |
arr = N.array(arr)
offset = float(overlap) * length
total_segments = int((N.shape(arr)[0] - length) / offset) + 1
# print "total segments", total_segments
other_shape = N.shape(arr)[1:]
out_shape = [total_segments, length]
out_shape.extend(other_shape)
out = N.empty(out_shape)
... | def segment_array(arr, length, overlap=.5) | Segment array into chunks of a specified length, with a specified
proportion overlap.
Operates on axis 0.
:param integer length: Length of each segment
:param float overlap: Proportion overlap of each frame | 2.799702 | 3.23714 | 0.864869 |
'''
d = {'scheme': 'http', 'path': '/index.php', 'params': 'params', 'query': 'username=query', 'fragment': 'frag', 'username': '', 'password': '', 'hostname': 'www.baidu.com', 'port': ''}
pobj(d)
nkl = ['scheme', 'username', 'password', 'hostname', 'port', 'path', 'params', 'query', 'fragme... | def _reorder_via_klist(d,nkl,**kwargs) | d = {'scheme': 'http', 'path': '/index.php', 'params': 'params', 'query': 'username=query', 'fragment': 'frag', 'username': '', 'password': '', 'hostname': 'www.baidu.com', 'port': ''}
pobj(d)
nkl = ['scheme', 'username', 'password', 'hostname', 'port', 'path', 'params', 'query', 'fragment']
pob... | 3.527103 | 1.74426 | 2.02212 |
'''
#non-recursive
d = {1:'a',2:'b',3:'a'}
_keys_via_value_nonrecur(d,'a')
'''
rslt = []
for key in d:
if(d[key] == v):
rslt.append(key)
return(rslt) | def _keys_via_value_nonrecur(d,v) | #non-recursive
d = {1:'a',2:'b',3:'a'}
_keys_via_value_nonrecur(d,'a') | 3.201972 | 2.258271 | 1.417886 |
'''
d = {
'x':
{
'x2': 'x22',
'x1': 'x11'
},
'y':
{
'y1': 'v1',
'y2':
{
'y4': 'v4',
'y3': 'v3',
},
... | def _keys_via_value(d,value,**kwargs) | d = {
'x':
{
'x2': 'x22',
'x1': 'x11'
},
'y':
{
'y1': 'v1',
'y2':
{
'y4': 'v4',
'y3': 'v3',
},
'xx'... | 2.764452 | 2.038687 | 1.355996 |
'''
d = {'GPSImgDirectionRef': 'M', 'GPSVersionID': b'\x02\x03\x00\x00', 'GPSImgDirection': (21900, 100)}
pobj(d)
kl,vl = d2kvlist(d)
pobj(kl)
pobj(vl)
'''
kl = list(d.keys())
vl = list(d.values())
return((kl,vl)) | def d2kvlist(d) | d = {'GPSImgDirectionRef': 'M', 'GPSVersionID': b'\x02\x03\x00\x00', 'GPSImgDirection': (21900, 100)}
pobj(d)
kl,vl = d2kvlist(d)
pobj(kl)
pobj(vl) | 6.248737 | 1.623053 | 3.84999 |
'''
must be 1:1 map
'''
dkl,dvl = d2kvlist(d)
kl = []
for i in range(vl.__len__()):
v = vl[i]
index = dvl.index(v)
kl.append(dkl[index])
return(kl) | def klviavl(d,vl) | must be 1:1 map | 5.588719 | 4.581582 | 1.219823 |
'''
arr = ["color1","r1","g1","b1","a1","color2","r2","g2","b2","a2"]
>>> brkl2d(arr,5)
[{'color1': ['r1', 'g1', 'b1', 'a1']}, {'color2': ['r2', 'g2', 'b2', 'a2']}]
'''
lngth = arr.__len__()
brkseqs = elel.init_range(0,lngth,interval)
l = elel.broken_seqs(arr,brkseqs)
d =... | def brkl2d(arr,interval) | arr = ["color1","r1","g1","b1","a1","color2","r2","g2","b2","a2"]
>>> brkl2d(arr,5)
[{'color1': ['r1', 'g1', 'b1', 'a1']}, {'color2': ['r2', 'g2', 'b2', 'a2']}] | 3.580118 | 2.566605 | 1.394885 |
'''
d = {'a':1,'b':2,'c':2,'d':4}
desc = _vksdesc(d)
pobj(desc)
'''
pt = copy.deepcopy(d)
seqs_for_del =[]
vset = set({})
for k in pt:
vset.add(pt[k])
desc = {}
for v in vset:
desc[v] = []
for k in pt:
desc[pt[k]].append(k)
return(d... | def _vksdesc(d) | d = {'a':1,'b':2,'c':2,'d':4}
desc = _vksdesc(d)
pobj(desc) | 4.326756 | 3.040983 | 1.422815 |
'''
#duplicate keys will lost
tl = [(1,2),(3,4),(1,5)]
tlist2dict(tl)
'''
if('deepcopy' in kwargs):
deepcopy = kwargs['deepcopy']
else:
deepcopy = 1
if('check' in kwargs):
check = kwargs['check']
else:
check = 1
if(check):
if(tl... | def tlist2dict(tuple_list,**kwargs) | #duplicate keys will lost
tl = [(1,2),(3,4),(1,5)]
tlist2dict(tl) | 3.052674 | 2.336746 | 1.306378 |
'''
#sequence will be losted
d = {'a':'b','c':'d'}
dict2tlist(d)
'''
if('check' in kwargs):
check = kwargs['check']
else:
check = 1
if(check):
if(isinstance(this_dict,dict)):
pass
else:
return(None)
else:
pas... | def dict2tlist(this_dict,**kwargs) | #sequence will be losted
d = {'a':'b','c':'d'}
dict2tlist(d) | 2.91112 | 2.22467 | 1.308563 |
'''
d = {1:'a',2:'a',3:'b'}
'''
vl = list(d.values())
lngth1 = vl.__len__()
uvl = elel.uniqualize(vl)
lngth2 = uvl.__len__()
cond = (lngth1 == lngth2)
return(cond) | def is_mirrable(d) | d = {1:'a',2:'a',3:'b'} | 6.17149 | 4.620468 | 1.335685 |
'''
d = {1:'a',2:'a',3:'b'}
'''
md = {}
if('sort_func' in kwargs):
sort_func = kwargs['sort_func']
else:
sort_func = sorted
vl = list(d.values())
uvl = elel.uniqualize(vl)
for v in uvl:
kl = _keys_via_value_nonrecur(d,v)
k = sorted(kl)[0]
m... | def dict_mirror(d,**kwargs) | d = {1:'a',2:'a',3:'b'} | 5.706228 | 4.983712 | 1.144975 |
'''
d = {
"ActiveArea":"50829",
"Artist":"315",
"AsShotPreProfileMatrix":"50832",
"AnalogBalance":"50727",
"AsShotICCProfile":"50831",
"AsShotProfileName":"50934",
"AntiAliasStrength":"5073... | def _cond_select_key_nonrecur(d,cond_match=None,**kwargs) | d = {
"ActiveArea":"50829",
"Artist":"315",
"AsShotPreProfileMatrix":"50832",
"AnalogBalance":"50727",
"AsShotICCProfile":"50831",
"AsShotProfileName":"50934",
"AntiAliasStrength":"50738",
... | 4.407355 | 1.446947 | 3.045968 |
'''
d = {
"ActiveArea":"50829",
"Artist":"315",
"AsShotPreProfileMatrix":"50832",
"AnalogBalance":"50727",
"AsShotICCProfile":"50831",
"AsShotProfileName":"50934",
"AntiAliasStrength":"5073... | def _cond_select_value_nonrecur(d,cond_match=None,**kwargs) | d = {
"ActiveArea":"50829",
"Artist":"315",
"AsShotPreProfileMatrix":"50832",
"AnalogBalance":"50727",
"AsShotICCProfile":"50831",
"AsShotProfileName":"50934",
"AntiAliasStrength":"50738",
... | 4.373374 | 1.466005 | 2.983193 |
'''
d1 = {'a':'x','b':'y','c':'z'}
d2 = {'a':'x','b':'u','d':'v'}
_diff_internal(d1,d2)
_diff_internald2,d1)
'''
same =[]
kdiff =[]
vdiff = []
for key in d1:
value = d1[key]
if(key in d2):
if(value == d2[key]):
same.appe... | def _diff_internal(d1,d2) | d1 = {'a':'x','b':'y','c':'z'}
d2 = {'a':'x','b':'u','d':'v'}
_diff_internal(d1,d2)
_diff_internald2,d1) | 3.121749 | 1.986164 | 1.571748 |
'''
d1 = {'a':'x','b':'y','c':'z'}
d2 = {'a':'x','b':'u','d':'v'}
_union(d1,d2)
_union(d2,d1)
'''
u = {}
ds = _diff_internal(d1,d2)
for key in ds['same']:
u[key] = d1[key]
for key in ds['vdiff']:
u[key] = d1[key]
for key in ds['kdiff']:
... | def _union(d1,d2) | d1 = {'a':'x','b':'y','c':'z'}
d2 = {'a':'x','b':'u','d':'v'}
_union(d1,d2)
_union(d2,d1) | 2.511885 | 1.981849 | 1.267445 |
'''
d1 = {'a':'x','b':'y','c':'z'}
d2 = {'a':'x','b':'u','d':'v'}
_diff(d1,d2)
_diff(d2,d1)
'''
d = {}
ds = _diff_internal(d1,d2)
for key in ds['vdiff']:
d[key] = d1[key]
for key in ds['kdiff']:
d[key] = d1[key]
return(d) | def _diff(d1,d2) | d1 = {'a':'x','b':'y','c':'z'}
d2 = {'a':'x','b':'u','d':'v'}
_diff(d1,d2)
_diff(d2,d1) | 3.221983 | 2.339635 | 1.37713 |
'''
d1 = {'a':'x','b':'y','c':'z'}
d2 = {'a':'x','b':'u','d':'v'}
_intersection(d1,d2)
_intersection(d2,d1)
'''
i = {}
ds = _diff_internal(d1,d2)
for key in ds['same']:
i[key] = d1[key]
return(i) | def _intersection(d1,d2) | d1 = {'a':'x','b':'y','c':'z'}
d2 = {'a':'x','b':'u','d':'v'}
_intersection(d1,d2)
_intersection(d2,d1) | 3.806614 | 2.539187 | 1.499147 |
'''
d1 = {'a':'x','b':'y','c':'z'}
d2 = {'a':'x','b':'u','d':'v'}
complement(d1,d2)
complement(d2,d1)
'''
u = _union(d1,d2)
c = _diff(u,d1)
return(c) | def _complement(d1,d2) | d1 = {'a':'x','b':'y','c':'z'}
d2 = {'a':'x','b':'u','d':'v'}
complement(d1,d2)
complement(d2,d1) | 3.533742 | 2.09312 | 1.688266 |
'''
d = {1:'a',2:'b',3:'c',4:'b'}
_uniqualize(d)
'''
pt = copy.deepcopy(d)
seqs_for_del =[]
vset = set({})
for k in pt:
vset.add(pt[k])
tslen = vset.__len__()
freq = {}
for k in pt:
v = pt[k]
if(v in freq):
freq[v] = freq[v] + 1
... | def _uniqualize(d) | d = {1:'a',2:'b',3:'c',4:'b'}
_uniqualize(d) | 3.294704 | 2.878475 | 1.144601 |
'''
dict1 = {1:'a',2:'b',3:'c',4:'d'}
dict2 = {5:'u',2:'v',3:'w',6:'x',7:'y'}
d = _extend(dict1,dict2)
pobj(d)
dict1 = {1:'a',2:'b',3:'c',4:'d'}
dict2 = {5:'u',2:'v',3:'w',6:'x',7:'y'}
d = _extend(dict1,dict2,overwrite=1)
pobj(d)
'''
if('deepco... | def _extend(dict1,dict2,**kwargs) | dict1 = {1:'a',2:'b',3:'c',4:'d'}
dict2 = {5:'u',2:'v',3:'w',6:'x',7:'y'}
d = _extend(dict1,dict2)
pobj(d)
dict1 = {1:'a',2:'b',3:'c',4:'d'}
dict2 = {5:'u',2:'v',3:'w',6:'x',7:'y'}
d = _extend(dict1,dict2,overwrite=1)
pobj(d) | 1.856768 | 1.395214 | 1.330812 |
'''
dict1 = {'a':1,'b':2,'c':3,'d':4}
dict2 = {'b':2,'c':3}
_comprise(dict1,dict2)
'''
len_1 = dict1.__len__()
len_2 = dict2.__len__()
if(len_2>len_1):
return(False)
else:
for k2 in dict2:
v2 = dict2[k2]
if(k2 in dict1):
... | def _comprise(dict1,dict2) | dict1 = {'a':1,'b':2,'c':3,'d':4}
dict2 = {'b':2,'c':3}
_comprise(dict1,dict2) | 2.113247 | 1.823579 | 1.158846 |
'''
dict1 = {1:'a',2:'b',3:'c',4:'d'}
dict2 = {5:'u',2:'v',3:'w',6:'x',7:'y'}
_update_intersection(dict1,dict2)
pobj(dict1)
pobj(dict2)
'''
if('deepcopy' in kwargs):
deepcopy = kwargs['deepcopy']
else:
deepcopy = 1
if(deepcopy == 1):
di... | def _update_intersection(dict1,dict2,**kwargs) | dict1 = {1:'a',2:'b',3:'c',4:'d'}
dict2 = {5:'u',2:'v',3:'w',6:'x',7:'y'}
_update_intersection(dict1,dict2)
pobj(dict1)
pobj(dict2) | 2.465368 | 1.667438 | 1.478536 |
'''
dict1 = {1:'a',2:'b',3:'c',4:'d'}
dict2 = {5:'u',2:'v',3:'w',6:'x',7:'y'}
_update(dict1,dict2)
pobj(dict1)
pobj(dict2)
'''
if('deepcopy' in kwargs):
deepcopy = kwargs['deepcopy']
else:
deepcopy = 1
if(deepcopy == 1):
dict1 = copy.de... | def _update(dict1,dict2,**kwargs) | dict1 = {1:'a',2:'b',3:'c',4:'d'}
dict2 = {5:'u',2:'v',3:'w',6:'x',7:'y'}
_update(dict1,dict2)
pobj(dict1)
pobj(dict2) | 2.87294 | 1.960073 | 1.465731 |
'''
#if path_list already in external_dict, will do nothing
y = {}
path_list = ['c','b']
_setdefault_via_pathlist(y,path_list)
y
_setdefault_via_pathlist(y,path_list)
y = {}
_setdefault_via_pathlist(y,path_list)
y
'''
if('s2n' in kwargs... | def _setdefault_via_pathlist(external_dict,path_list,**kwargs) | #if path_list already in external_dict, will do nothing
y = {}
path_list = ['c','b']
_setdefault_via_pathlist(y,path_list)
y
_setdefault_via_pathlist(y,path_list)
y = {}
_setdefault_via_pathlist(y,path_list)
y | 2.778031 | 2.178733 | 1.275067 |
'''
y = {'c': {'b': {}}}
_setitem_via_pathlist(y,['c','b'],200)
'''
if('s2n' in kwargs):
s2n = kwargs['s2n']
else:
s2n = 0
if('n2s' in kwargs):
n2s = kwargs['n2s']
else:
n2s = 0
this = external_dict
for i in range(0,path_list.__len__()-1):
... | def _setitem_via_pathlist(external_dict,path_list,value,**kwargs) | y = {'c': {'b': {}}}
_setitem_via_pathlist(y,['c','b'],200) | 2.538756 | 2.097965 | 1.210104 |
'''
y = {'c': {'b': 200}}
_getitem_via_pathlist(y,['c','b'])
'''
if('s2n' in kwargs):
s2n = kwargs['s2n']
else:
s2n = 0
if('n2s' in kwargs):
n2s = kwargs['n2s']
else:
n2s = 0
this = external_dict
for i in range(0,path_list.__len__()):
... | def _getitem_via_pathlist(external_dict,path_list,**kwargs) | y = {'c': {'b': 200}}
_getitem_via_pathlist(y,['c','b']) | 2.625088 | 2.195693 | 1.195563 |
'''
y = {
'a':
{'x':88},
'b':
{
'x':
{'c':66}
}
}
_include_pathlist(y,['a'])
_include_pathlist(y,['a','x'])
_include_pathlist(y,['b','x','c'])
'''
if('s... | def _include_pathlist(external_dict,path_list,**kwargs) | y = {
'a':
{'x':88},
'b':
{
'x':
{'c':66}
}
}
_include_pathlist(y,['a'])
_include_pathlist(y,['a','x'])
_include_pathlist(y,['b','x','c']) | 2.597478 | 1.926315 | 1.348418 |
'''
currd = {0:'AutoPauseSpeed', 125:'HRLimitLow', 6:'Activity'}
max_wordwidth(currd)
'''
maxValueWidth = 0
for each in myDict:
eachValueWidth = myDict[each].__len__()
if(eachValueWidth > maxValueWidth):
maxValueWidth = eachValueWidth
return(maxValueWidth) | def max_word_width(myDict) | currd = {0:'AutoPauseSpeed', 125:'HRLimitLow', 6:'Activity'}
max_wordwidth(currd) | 11.154671 | 2.3479 | 4.750914 |
'''
currd = {0:'你们大家好', 125:'ABCDE', 6:'1234567'}
dict_get_max_word_displaywidth(currd)
'''
maxValueWidth = 0
for each in myDict:
eachValueWidth = str_display_width(myDict[each])
if(eachValueWidth > maxValueWidth):
maxValueWidth = eachValueWidth
return(max... | def max_display_width(myDict) | currd = {0:'你们大家好', 125:'ABCDE', 6:'1234567'}
dict_get_max_word_displaywidth(currd) | 6.936285 | 2.164945 | 3.203909 |
'''
the below is for nested-dict
any type is not dict will be treated as a leaf
empty dict will be treated as a leaf
from edict.edict import *
is_leaf(1)
is_leaf({1:2})
is_leaf({})
'''
if(is_dict(obj)):
length = obj.__len__()
if(length ... | def is_leaf(obj) | the below is for nested-dict
any type is not dict will be treated as a leaf
empty dict will be treated as a leaf
from edict.edict import *
is_leaf(1)
is_leaf({1:2})
is_leaf({}) | 5.51438 | 1.936127 | 2.84815 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.