uid stringlengths 24 24 | split stringclasses 1
value | category stringclasses 2
values | content stringlengths 5 482k | signature stringlengths 1 14k | suffix stringlengths 1 482k | prefix stringlengths 9 14k | prefix_token_count int64 3 5.01k | prefix_token_budget int64 64 256 | element_token_count int64 1 292k | signature_token_count int64 1 5.01k | prefix_context_token_count int64 0 255 | repo stringlengths 7 112 | path stringlengths 4 208 | language stringclasses 1
value | name stringlengths 1 218 | qualname stringlengths 1 218 | start_line int64 1 26.7k | end_line int64 1 26.7k | signature_start_line int64 1 26.7k | signature_end_line int64 1 26.7k | source_hash stringlengths 40 40 | source_dataset stringclasses 1
value | source_split stringclasses 1
value |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
43715773d4e28db8b70a35c1 | train | function | def _search_path(path):
mapping = dict()
for file in sorted(os.listdir(path)):
# Install from PYPI.
if fnmatch.fnmatch(file, '*-info'):
top_level = os.path.join(path, file, 'top_level.txt')
pkg_name, version = file.split('-')[:2]
if version.endswith('dist'):
... | def _search_path(path):
| mapping = dict()
for file in sorted(os.listdir(path)):
# Install from PYPI.
if fnmatch.fnmatch(file, '*-info'):
top_level = os.path.join(path, file, 'top_level.txt')
pkg_name, version = file.split('-')[:2]
if version.endswith('dist'):
version ... | Parser()
try:
dt = parser.get_doctest(docstring, {}, None, None, None)
except ValueError:
# >>> 'abc'
pass
else:
examples = dt.examples
return '\n'.join([example.source for example in examples])
r... | 164 | 164 | 549 | 6 | 157 | vishalsrao/pigar | pigar/parser.py | Python | _search_path | _search_path | 270 | 338 | 270 | 270 | 3e8be9f24e5edfcd37111e0dffe0a4c2b3c11762 | bigcode/the-stack | train |
9337c0d3f3743c7c22a71025 | train | function | def _read_code(fpath):
if fpath.endswith(".ipynb"):
nb = nbformat.read(fpath, as_version=4)
code = ""
for cell in nb.cells:
if cell.cell_type == "code":
code += cell.source + "\n"
return code
elif fpath.endswith(".py"):
with open(fpath, 'rb') a... | def _read_code(fpath):
| if fpath.endswith(".ipynb"):
nb = nbformat.read(fpath, as_version=4)
code = ""
for cell in nb.cells:
if cell.cell_type == "code":
code += cell.source + "\n"
return code
elif fpath.endswith(".py"):
with open(fpath, 'rb') as f:
return... | _modules.add(fpath[:-3])
code = _read_code(fpath)
if code:
imported_modules.extend(parse_file_imports(fpath, code))
if has_py:
user_modules.add(trim_suffix(dirpath, "/"))
return imported_modules, user_modules
def _read_code(fpath):
| 64 | 64 | 93 | 7 | 56 | vishalsrao/pigar | pigar/parser.py | Python | _read_code | _read_code | 58 | 69 | 58 | 58 | 051fe4d9b9c2776d91e1b914fd6a2dc0206ab5d2 | bigcode/the-stack | train |
243e8a2dfd10a0e13a4fed4f | train | function | def parse_installed_packages():
"""Get mapping for import top level name
and install package name with version.
"""
mapping = dict()
for path in sys.path:
if pathlib.isdir(path) and trim_suffix(path, '/').endswith(
('site-packages', 'dist-packages')
):
mappin... | def parse_installed_packages():
| """Get mapping for import top level name
and install package name with version.
"""
mapping = dict()
for path in sys.path:
if pathlib.isdir(path) and trim_suffix(path, '/').endswith(
('site-packages', 'dist-packages')
):
mapping.update(_search_path(path))
... | None)
except ValueError:
# >>> 'abc'
pass
else:
examples = dt.examples
return '\n'.join([example.source for example in examples])
return None
@property
def modules(self):
return self._modules
def parse_inst... | 64 | 64 | 79 | 6 | 57 | vishalsrao/pigar | pigar/parser.py | Python | parse_installed_packages | parse_installed_packages | 255 | 267 | 255 | 255 | aa87b21d7cf688aab7f2b9738c4b9e63c3449701 | bigcode/the-stack | train |
362f7cc9c28011f5bccd6e6c | train | function | def read(fname):
basedir = os.path.dirname(sys.argv[0])
return open(os.path.join(basedir, fname)).read()
| def read(fname):
| basedir = os.path.dirname(sys.argv[0])
return open(os.path.join(basedir, fname)).read()
| from setuptools import setup, find_packages
from setuptools.command.develop import develop
from setuptools.command.install import install
from subprocess import check_call
from codecs import open
import pyaws
requires = [
'boto3',
'botocore',
'Pygments'
]
def read(fname):
| 64 | 64 | 30 | 4 | 60 | mwozniczak/pyaws | setup.py | Python | read | read | 39 | 41 | 39 | 39 | 4672e5db4a471e776bb6277c4704bca071a4cdab | bigcode/the-stack | train |
979216346e634645117fa8c3 | train | class | class PostInstallDevelop(develop):
""" post-install, development """
def run(self):
check_call("bash scripts/post-install-dev.sh".split())
develop.run(self)
| class PostInstallDevelop(develop):
| """ post-install, development """
def run(self):
check_call("bash scripts/post-install-dev.sh".split())
develop.run(self)
|
import pyaws
requires = [
'boto3',
'botocore',
'Pygments'
]
def read(fname):
basedir = os.path.dirname(sys.argv[0])
return open(os.path.join(basedir, fname)).read()
class PostInstallDevelop(develop):
| 64 | 64 | 37 | 7 | 57 | mwozniczak/pyaws | setup.py | Python | PostInstallDevelop | PostInstallDevelop | 44 | 48 | 44 | 44 | 5e5f430b2b9b279e4d27b6d33893d8be2e5e0861 | bigcode/the-stack | train |
ae44b25f5fb283f77960b273 | train | class | class PostInstall(install):
"""
Post-install, production
cmdclass={
'develop': PostInstallDevelop,
'install': PostInstall,
}
"""
def run(self):
check_call("bash post-install.sh".split())
install.run(self)
| class PostInstall(install):
| """
Post-install, production
cmdclass={
'develop': PostInstallDevelop,
'install': PostInstall,
}
"""
def run(self):
check_call("bash post-install.sh".split())
install.run(self)
| .path.dirname(sys.argv[0])
return open(os.path.join(basedir, fname)).read()
class PostInstallDevelop(develop):
""" post-install, development """
def run(self):
check_call("bash scripts/post-install-dev.sh".split())
develop.run(self)
class PostInstall(install):
| 64 | 64 | 58 | 6 | 58 | mwozniczak/pyaws | setup.py | Python | PostInstall | PostInstall | 51 | 61 | 51 | 51 | 523812a3504614eea93ebc880641af495466bf43 | bigcode/the-stack | train |
2957594e3c4ab41424c2b9d4 | train | function | def get_sentseg_tac(data_folder,sentseg_folder):
files = os.listdir(data_folder)
for i_file,f in enumerate(files):
with open(data_folder+f,'r',encoding='utf-8',errors='ignore') as of:
lines = of.readlines()
sents = []
for l in lines:
if l!='\n':
sents.extend(sent_tokenize(l))
of = open(sentseg_folde... | def get_sentseg_tac(data_folder,sentseg_folder):
| files = os.listdir(data_folder)
for i_file,f in enumerate(files):
with open(data_folder+f,'r',encoding='utf-8',errors='ignore') as of:
lines = of.readlines()
sents = []
for l in lines:
if l!='\n':
sents.extend(sent_tokenize(l))
of = open(sentseg_folder+f+'.out','w')
of.write('\n'.join(sents))
of... | .write('\n'.join(sentences))
of.close()
# torch.save(all_data,f)
print('%d/%d: %s is done!'%(i_file,len(files),f.name))
# break
print(num_data)
def get_sentseg_tac(data_folder,sentseg_folder):
| 64 | 64 | 126 | 13 | 51 | Wendy-Xiao/ext_summ_disco_tree_attn | EDU_segment.py | Python | get_sentseg_tac | get_sentseg_tac | 63 | 75 | 63 | 63 | 19cb582448aef2a4f9509d38c54e4146e5145137 | bigcode/the-stack | train |
11fb855c43bd8d83e2bcd3b6 | train | function | def preprocess_sent(text):
text=re.sub('""','',text)
text=re.sub("''"'','',text)
text=re.sub('``','',text)
text=re.sub(' ` ','',text)
text=re.sub(" ' ",'',text)
return text
| def preprocess_sent(text):
| text=re.sub('""','',text)
text=re.sub("''"'','',text)
text=re.sub('``','',text)
text=re.sub(' ` ','',text)
text=re.sub(" ' ",'',text)
return text
| ',text)
text=re.sub('``','',text)
text=re.sub(' ` ','',text)
text=re.sub(" ' ",'',text)
sents = sent_tokenize(text)
of = open(out_file,'w')
of.write('\n'.join(sents))
of.close()
def preprocess_sent(text):
| 64 | 64 | 55 | 5 | 59 | Wendy-Xiao/ext_summ_disco_tree_attn | EDU_segment.py | Python | preprocess_sent | preprocess_sent | 22 | 28 | 22 | 22 | f3fd4d892deee50dbc129a011651719a20ab15c9 | bigcode/the-stack | train |
990967561ee7ff578486b672 | train | function | def split_by_sentences(in_file,out_file):
of = open(in_file,'r')
text=of.read()
of.close()
text=re.sub('""','',text)
text=re.sub("''"'','',text)
text=re.sub('``','',text)
text=re.sub(' ` ','',text)
text=re.sub(" ' ",'',text)
sents = sent_tokenize(text)
of = open(out_file,'w')
of.write('\n'.join(sents))
of.c... | def split_by_sentences(in_file,out_file):
| of = open(in_file,'r')
text=of.read()
of.close()
text=re.sub('""','',text)
text=re.sub("''"'','',text)
text=re.sub('``','',text)
text=re.sub(' ` ','',text)
text=re.sub(" ' ",'',text)
sents = sent_tokenize(text)
of = open(out_file,'w')
of.write('\n'.join(sents))
of.close()
| import os
from nltk import sent_tokenize,word_tokenize
import re
import sys
from pathlib import Path
import torch
def split_by_sentences(in_file,out_file):
| 38 | 64 | 101 | 10 | 27 | Wendy-Xiao/ext_summ_disco_tree_attn | EDU_segment.py | Python | split_by_sentences | split_by_sentences | 8 | 20 | 8 | 8 | 92533de56802d6b85fb1b1c303f826d1d55287f5 | bigcode/the-stack | train |
81045c7b0354fd2c9325bf86 | train | function | def get_sentseg_cnndm(data_folder,sentseg_folder):
files = [f for f in Path(data_folder).glob('*.pt')]
num_data = 0
for i_file,f in enumerate(files):
all_data = torch.load(f)
new_data = []
num_data+=len(all_data)
for data in all_data:
doc_id = data['doc_id']
sentences = [' '.join(s) for s in data['sent... | def get_sentseg_cnndm(data_folder,sentseg_folder):
| files = [f for f in Path(data_folder).glob('*.pt')]
num_data = 0
for i_file,f in enumerate(files):
all_data = torch.load(f)
new_data = []
num_data+=len(all_data)
for data in all_data:
doc_id = data['doc_id']
sentences = [' '.join(s) for s in data['sent_txt']]
# sentences = [preprocess_sent(' '.join(... | (" ' ",'',text)
sents = sent_tokenize(text)
of = open(out_file,'w')
of.write('\n'.join(sents))
of.close()
def preprocess_sent(text):
text=re.sub('""','',text)
text=re.sub("''"'','',text)
text=re.sub('``','',text)
text=re.sub(' ` ','',text)
text=re.sub(" ' ",'',text)
return text
def get_sentseg_cnndm(data_fol... | 104 | 104 | 349 | 14 | 89 | Wendy-Xiao/ext_summ_disco_tree_attn | EDU_segment.py | Python | get_sentseg_cnndm | get_sentseg_cnndm | 30 | 60 | 30 | 30 | 4930d700f9729704bb1f82ea649cc530ad1be7a5 | bigcode/the-stack | train |
96370518240745c4f5c307d1 | train | class | class ExchangeEndpoint(EnumString):
BinanceSpot = 'binance_spot'
BinanceFutures = 'binance_futures'
BinanceFuturesCoin = 'binance_futures_coin'
BybitFutures = 'bybit_futures'
BybitFuturesInverse = 'bybit_futures_inverse'
BacktestLinear = 'backtest_linear'
BacktestInverse = 'backtest_invers... | class ExchangeEndpoint(EnumString):
| BinanceSpot = 'binance_spot'
BinanceFutures = 'binance_futures'
BinanceFuturesCoin = 'binance_futures_coin'
BybitFutures = 'bybit_futures'
BybitFuturesInverse = 'bybit_futures_inverse'
BacktestLinear = 'backtest_linear'
BacktestInverse = 'backtest_inverse'
DryrunLinear = "dryrun_linea... | from kektrade.exchange.backtest_inverse import BacktestInverse
from kektrade.exchange.backtest_linear import BacktestLinear
from kektrade.exchange.dryrun_inverse import DryrunInverse
from kektrade.exchange.dryrun_linear import DryrunLinear
from kektrade.misc import EnumString
class ExchangeEndpoint(EnumString):
| 64 | 64 | 106 | 6 | 57 | flamingrickpat/kektrade | kektrade/exchange/resolver.py | Python | ExchangeEndpoint | ExchangeEndpoint | 9 | 21 | 9 | 9 | 20b7d293777c37271b9a58a573e6cebffe48718e | bigcode/the-stack | train |
1b0abdad9a7dca9f6a7f3105 | train | class | class ExchangeResolver():
@classmethod
def load_exchange(cls, exchange_name: ExchangeEndpoint):
exchange = ExchangeEndpoint.from_str(exchange_name)
if exchange == ExchangeEndpoint.BacktestInverse:
return BacktestInverse()
elif exchange == ExchangeEndpoint.BacktestLinear:
... | class ExchangeResolver():
@classmethod
| def load_exchange(cls, exchange_name: ExchangeEndpoint):
exchange = ExchangeEndpoint.from_str(exchange_name)
if exchange == ExchangeEndpoint.BacktestInverse:
return BacktestInverse()
elif exchange == ExchangeEndpoint.BacktestLinear:
return BacktestLinear()
eli... | utures'
BybitFuturesInverse = 'bybit_futures_inverse'
BacktestLinear = 'backtest_linear'
BacktestInverse = 'backtest_inverse'
DryrunLinear = "dryrun_linear"
DryrunInverse = "dryrun_inverse"
class ExchangeResolver():
@classmethod
| 64 | 64 | 104 | 8 | 56 | flamingrickpat/kektrade | kektrade/exchange/resolver.py | Python | ExchangeResolver | ExchangeResolver | 25 | 38 | 25 | 26 | e6741835faca49736a751c2ba1595fb60b0d16ad | bigcode/the-stack | train |
045f7a92f8223792bdcf24a5 | train | function | @pytest.mark.supportedwindows
def test_if_all_mesos_masters_have_registered(dcos_api_session):
# Currently it is not possible to extract this information through Mesos'es
# API, let's query zookeeper directly.
zk_hostports = 'zk-1.zk:2181,zk-2.zk:2181,zk-3.zk:2181,zk-4.zk:2181,zk-5.zk:2181'
zk = kazoo.c... | @pytest.mark.supportedwindows
def test_if_all_mesos_masters_have_registered(dcos_api_session):
# Currently it is not possible to extract this information through Mesos'es
# API, let's query zookeeper directly.
| zk_hostports = 'zk-1.zk:2181,zk-2.zk:2181,zk-3.zk:2181,zk-4.zk:2181,zk-5.zk:2181'
zk = kazoo.client.KazooClient(hosts=zk_hostports, read_only=True)
master_ips = []
zk.start()
for znode in zk.get_children("/mesos"):
if not znode.startswith("json.info_"):
continue
master =... | .exception.DNSException:
assert False, "Cannot resolve leader.mesos"
@pytest.mark.supportedwindows
def test_if_all_mesos_masters_have_registered(dcos_api_session):
# Currently it is not possible to extract this information through Mesos'es
# API, let's query zookeeper directly.
| 64 | 64 | 201 | 47 | 17 | leehambley/dcos | packages/dcos-integration-test/extra/test_composition.py | Python | test_if_all_mesos_masters_have_registered | test_if_all_mesos_masters_have_registered | 48 | 64 | 48 | 51 | 5731d5bb43333753083e9269d267b59474ce1d2e | bigcode/the-stack | train |
901498beb34151ce66ccdfb5 | train | function | @pytest.mark.supportedwindows
def test_if_all_exhibitors_are_in_sync(dcos_api_session):
r = dcos_api_session.get('/exhibitor/exhibitor/v1/cluster/status')
assert r.status_code == 200
correct_data = sorted(r.json(), key=lambda k: k['hostname'])
for master_node_ip in dcos_api_session.masters:
# ... | @pytest.mark.supportedwindows
def test_if_all_exhibitors_are_in_sync(dcos_api_session):
| r = dcos_api_session.get('/exhibitor/exhibitor/v1/cluster/status')
assert r.status_code == 200
correct_data = sorted(r.json(), key=lambda k: k['hostname'])
for master_node_ip in dcos_api_session.masters:
# This relies on the fact that Admin Router always proxies the local
# Exhibitor.
... | mesos/" + znode)[0].decode('utf-8'))
master_ips.append(master['address']['ip'])
zk.stop()
assert sorted(master_ips) == dcos_api_session.masters
@pytest.mark.supportedwindows
def test_if_all_exhibitors_are_in_sync(dcos_api_session):
| 64 | 64 | 163 | 21 | 42 | leehambley/dcos | packages/dcos-integration-test/extra/test_composition.py | Python | test_if_all_exhibitors_are_in_sync | test_if_all_exhibitors_are_in_sync | 67 | 81 | 67 | 68 | 50109f4bfbbd3a07908aeb09629deeb7c857c28c | bigcode/the-stack | train |
899588ec7b2f0a718ff2f80c | train | function | @pytest.mark.first
@pytest.mark.supportedwindows
def test_dcos_cluster_is_up(dcos_api_session):
def _docker_info(component):
# sudo is required for non-coreOS installs
return subprocess.check_output(['sudo', 'docker', 'version', '-f', component]).decode('utf-8').rstrip()
cluster_environment = {... | @pytest.mark.first
@pytest.mark.supportedwindows
def test_dcos_cluster_is_up(dcos_api_session):
| def _docker_info(component):
# sudo is required for non-coreOS installs
return subprocess.check_output(['sudo', 'docker', 'version', '-f', component]).decode('utf-8').rstrip()
cluster_environment = {
"docker_client_version": _docker_info('{{.Client.Version}}'),
"docker_server_ve... | oo.client
import pytest
import requests
from test_helpers import expanded_config
__maintainer__ = 'mnaboka'
__contact__ = 'dcos-cluster-ops@mesosphere.io'
@pytest.mark.first
@pytest.mark.supportedwindows
def test_dcos_cluster_is_up(dcos_api_session):
| 64 | 64 | 155 | 22 | 42 | leehambley/dcos | packages/dcos-integration-test/extra/test_composition.py | Python | test_dcos_cluster_is_up | test_dcos_cluster_is_up | 19 | 34 | 19 | 21 | b297b14ee36c2ae45430fced8b928fe847c2f6c1 | bigcode/the-stack | train |
6f6a30876c6ef9f58b5b5092 | train | function | def test_mesos_agent_role_assignment(dcos_api_session):
state_endpoint = '/state.json'
for agent in dcos_api_session.public_slaves:
r = dcos_api_session.get(state_endpoint, host=agent, port=5051)
assert r.json()['flags']['default_role'] == 'slave_public'
for agent in dcos_api_session.slaves:... | def test_mesos_agent_role_assignment(dcos_api_session):
| state_endpoint = '/state.json'
for agent in dcos_api_session.public_slaves:
r = dcos_api_session.get(state_endpoint, host=agent, port=5051)
assert r.json()['flags']['default_role'] == 'slave_public'
for agent in dcos_api_session.slaves:
r = dcos_api_session.get(state_endpoint, host=a... | hibitor/exhibitor/v1/cluster/status'.format(master_node_ip), verify=False)
assert resp.status_code == 200
tested_data = sorted(resp.json(), key=lambda k: k['hostname'])
assert correct_data == tested_data
def test_mesos_agent_role_assignment(dcos_api_session):
| 64 | 64 | 111 | 12 | 51 | leehambley/dcos | packages/dcos-integration-test/extra/test_composition.py | Python | test_mesos_agent_role_assignment | test_mesos_agent_role_assignment | 84 | 91 | 84 | 84 | e52f52c56e0eed3e1de4d75623fc984672fac998 | bigcode/the-stack | train |
2ca668ed623b4d3d23666840 | train | function | @pytest.mark.supportedwindows
def test_leader_election(dcos_api_session):
mesos_resolver = dns.resolver.Resolver()
mesos_resolver.nameservers = dcos_api_session.masters
mesos_resolver.port = 61053
try:
mesos_resolver.query('leader.mesos', 'A')
except dns.exception.DNSException:
asser... | @pytest.mark.supportedwindows
def test_leader_election(dcos_api_session):
| mesos_resolver = dns.resolver.Resolver()
mesos_resolver.nameservers = dcos_api_session.masters
mesos_resolver.port = 61053
try:
mesos_resolver.query('leader.mesos', 'A')
except dns.exception.DNSException:
assert False, "Cannot resolve leader.mesos"
| .platform(),
"system_platform_system": platform.system(),
"system_platform_release": platform.release(),
"system_platform_version": platform.version()
}
logging.info(json.dumps(cluster_environment, sort_keys=True, indent=4))
@pytest.mark.supportedwindows
def test_leader_election(dcos_api... | 64 | 64 | 89 | 17 | 47 | leehambley/dcos | packages/dcos-integration-test/extra/test_composition.py | Python | test_leader_election | test_leader_election | 37 | 45 | 37 | 38 | a005a78f8f198a0b56e26c0654e67fbca3c54b58 | bigcode/the-stack | train |
ac1cf8b22562c8f0d4baedd0 | train | function | def test_signal_service(dcos_api_session):
"""
signal-service runs on an hourly timer, this test runs it as a one-off
and pushes the results to the test_server app for easy retrieval
When this test fails due to `dcos-checks-poststart-service-unhealthy`,
consider that the issue may be due to check t... | def test_signal_service(dcos_api_session):
| """
signal-service runs on an hourly timer, this test runs it as a one-off
and pushes the results to the test_server app for easy retrieval
When this test fails due to `dcos-checks-poststart-service-unhealthy`,
consider that the issue may be due to check timeouts which are too low.
"""
# Th... | string if healthy),
# "dcos-unit-foo.service": "journalctl output" (if unhealthy),
# }
# },
# ...
# ]
# }
# }
# }
# Test that all nodes have the correct set of dcos-* systemd units.
... | 256 | 256 | 978 | 9 | 246 | leehambley/dcos | packages/dcos-integration-test/extra/test_composition.py | Python | test_signal_service | test_signal_service | 218 | 321 | 218 | 218 | bfb8eb87b0486bfabe63aec617448f8b2e174a7a | bigcode/the-stack | train |
7946687878fa9ff5f35a61e2 | train | function | def test_systemd_units_are_healthy(dcos_api_session) -> None:
"""
Test that the system is healthy at the arbitrary point in time
that this test runs. This test has caught several issues in the past
as it serves as a very high-level assertion about the system state.
It seems very random, but it has p... | def test_systemd_units_are_healthy(dcos_api_session) -> None:
| """
Test that the system is healthy at the arbitrary point in time
that this test runs. This test has caught several issues in the past
as it serves as a very high-level assertion about the system state.
It seems very random, but it has proven very valuable.
We are explicit about the list of un... | hibitor/v1/cluster/status')
assert r.status_code == 200
correct_data = sorted(r.json(), key=lambda k: k['hostname'])
for master_node_ip in dcos_api_session.masters:
# This relies on the fact that Admin Router always proxies the local
# Exhibitor.
resp = requests.get('http://{}/exhi... | 256 | 256 | 1,177 | 16 | 239 | leehambley/dcos | packages/dcos-integration-test/extra/test_composition.py | Python | test_systemd_units_are_healthy | test_systemd_units_are_healthy | 94 | 215 | 94 | 94 | 80ad353d7031e19a07f952c6fd09721ad18ae148 | bigcode/the-stack | train |
aecbf6d2a59625dadab6aa5e | train | class | class MapData(models.Model):
lon = models.FloatField()
lat = models.FloatField()
def __str__(self):
return self.user.username
def get_absolute_url(self):
return reverse('profile-detail', kwargs={'id': self.id}) | class MapData(models.Model):
| lon = models.FloatField()
lat = models.FloatField()
def __str__(self):
return self.user.username
def get_absolute_url(self):
return reverse('profile-detail', kwargs={'id': self.id}) | from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
# Create your models here.
class MapData(models.Model):
| 36 | 64 | 55 | 6 | 30 | akbernamazi/Safer_Cities | rain/maps/models.py | Python | MapData | MapData | 6 | 13 | 6 | 6 | 542090dc00d9cb8862d6948cd401aa2b891a1336 | bigcode/the-stack | train |
0c82ea9a023ecf22b3d18ef4 | train | class | class WXAPI(object):
def __init__(self, host):
self.cookie = set_cookie(Constant.WECHAT_COOKIE_FILE)
self.wx_host = host
self.wx_filehost = ''
self.wx_conf = {}
# jsLogin时这个appid只能使用: wx782c26e4c19acffb
self.appid = Constant.API_APPID
self.uuid = ''
... | class WXAPI(object):
| def __init__(self, host):
self.cookie = set_cookie(Constant.WECHAT_COOKIE_FILE)
self.wx_host = host
self.wx_filehost = ''
self.wx_conf = {}
# jsLogin时这个appid只能使用: wx782c26e4c19acffb
self.appid = Constant.API_APPID
self.uuid = ''
self.redirect_uri = ''... | #!/usr/bin/env python
# coding: utf-8
# Modify base on from https://github.com/Urinx/WeixinBot/blob/master/wxbot_project_py2.7/wechat/wechat_apis.py
#===================================================
from utils import *
from config import Constant
from config import Log
#---------------------------------------------... | 122 | 256 | 8,778 | 5 | 117 | ymlbright/wechat_bot | wechat/wechat_apis.py | Python | WXAPI | WXAPI | 23 | 985 | 23 | 24 | 48444ae883934ae7761b28ea960d147784be541f | bigcode/the-stack | train |
eaf267f2b33ca1a226b6d934 | train | class | class Local:
__slots__ = ("_storage",)
def __init__(self) -> None:
object.__setattr__(self, "_storage", ContextVar("local_storage"))
def __iter__(self) -> t.Iterator[t.Tuple[int, t.Any]]:
return iter(self._storage.get({}).items())
def __call__(self, proxy: str) -> "LocalProxy":
... | class Local:
| __slots__ = ("_storage",)
def __init__(self) -> None:
object.__setattr__(self, "_storage", ContextVar("local_storage"))
def __iter__(self) -> t.Iterator[t.Tuple[int, t.Any]]:
return iter(self._storage.get({}).items())
def __call__(self, proxy: str) -> "LocalProxy":
"""Create a... | as well
as :class:`LocalStack` objects. However it is not possible to
release data held by proxies that way, one always has to retain
a reference to the underlying local object in order to be able
to release it.
.. versionadded:: 0.6.1
"""
local.__release_local__()
class Local:
| 78 | 79 | 265 | 3 | 76 | swt2c/werkzeug | src/werkzeug/local.py | Python | Local | Local | 42 | 76 | 42 | 42 | 76f92428f544b05e2d7c6eef6d1274b9f53b6580 | bigcode/the-stack | train |
476fb8a57eb7ce14fa465e3d | train | function | def release_local(local: t.Union["Local", "LocalStack"]) -> None:
"""Releases the contents of the local for the current context.
This makes it possible to use locals without a manager.
Example::
>>> loc = Local()
>>> loc.foo = 42
>>> release_local(loc)
>>> hasattr(loc, 'foo... | def release_local(local: t.Union["Local", "LocalStack"]) -> None:
| """Releases the contents of the local for the current context.
This makes it possible to use locals without a manager.
Example::
>>> loc = Local()
>>> loc.foo = 42
>>> release_local(loc)
>>> hasattr(loc, 'foo')
False
With this function one can release :class:`L... | import StartResponse
from _typeshed.wsgi import WSGIApplication
from _typeshed.wsgi import WSGIEnvironment
F = t.TypeVar("F", bound=t.Callable[..., t.Any])
def release_local(local: t.Union["Local", "LocalStack"]) -> None:
| 64 | 64 | 166 | 18 | 46 | swt2c/werkzeug | src/werkzeug/local.py | Python | release_local | release_local | 19 | 39 | 19 | 19 | fc71004e63ef65e1400df7dd49eeda0890ccf079 | bigcode/the-stack | train |
554bd09cbda30314b54ce175 | train | class | class LocalStack:
"""This class works similar to a :class:`Local` but keeps a stack
of objects instead. This is best explained with an example::
>>> ls = LocalStack()
>>> ls.push(42)
>>> ls.top
42
>>> ls.push(23)
>>> ls.top
23
>>> ls.pop()
... | class LocalStack:
| """This class works similar to a :class:`Local` but keeps a stack
of objects instead. This is best explained with an example::
>>> ls = LocalStack()
>>> ls.push(42)
>>> ls.top
42
>>> ls.push(23)
>>> ls.top
23
>>> ls.pop()
23
>>> l... | ({})
def __getattr__(self, name: str) -> t.Any:
values = self._storage.get({})
try:
return values[name]
except KeyError:
raise AttributeError(name) from None
def __setattr__(self, name: str, value: t.Any) -> None:
values = self._storage.get({}).copy()
... | 152 | 152 | 509 | 4 | 147 | swt2c/werkzeug | src/werkzeug/local.py | Python | LocalStack | LocalStack | 79 | 149 | 79 | 79 | 0b304b78487a185b25bb0f0bc75c1fd20992a835 | bigcode/the-stack | train |
a17582733a6699ee4afccfc1 | train | class | class LocalManager:
"""Local objects cannot manage themselves. For that you need a local
manager. You can pass a local manager multiple locals or add them
later by appending them to `manager.locals`. Every time the manager
cleans up, it will clean up all the data left in the locals for this
context.... | class LocalManager:
| """Local objects cannot manage themselves. For that you need a local
manager. You can pass a local manager multiple locals or add them
later by appending them to `manager.locals`. Every time the manager
cleans up, it will clean up all the data left in the locals for this
context.
.. versionchan... | the topmost item from the stack, will return the
old value or `None` if the stack was already empty.
"""
stack = getattr(self._local, "stack", None)
if stack is None:
return None
elif len(stack) == 1:
release_local(self._local)
return stack[-1... | 149 | 149 | 497 | 4 | 144 | swt2c/werkzeug | src/werkzeug/local.py | Python | LocalManager | LocalManager | 152 | 216 | 152 | 152 | 7aa31d16d2429357aeea1d07b4a75b290a7c06df | bigcode/the-stack | train |
e1f1bee35bceffe12329890a | train | function | def _l_to_r_op(op: F) -> F:
"""Swap the argument order to turn an l-op into an r-op."""
def r_op(obj: t.Any, other: t.Any) -> t.Any:
return op(other, obj)
return t.cast(F, r_op)
| def _l_to_r_op(op: F) -> F:
| """Swap the argument order to turn an l-op into an r-op."""
def r_op(obj: t.Any, other: t.Any) -> t.Any:
return op(other, obj)
return t.cast(F, r_op)
| : t.Any) -> "LocalProxy":
f(self, other) # type: ignore
return instance
return i_op.__get__(obj, type(obj)) # type: ignore
self.bind_f = bind_f
def _l_to_r_op(op: F) -> F:
| 64 | 64 | 63 | 13 | 50 | swt2c/werkzeug | src/werkzeug/local.py | Python | _l_to_r_op | _l_to_r_op | 319 | 325 | 319 | 319 | db1014c89cd2fddc9507f835c8b78651d97ca161 | bigcode/the-stack | train |
ce8b72b551a7d2c9dd58fac3 | train | class | class _ProxyIOp(_ProxyLookup):
"""Look up an augmented assignment method on a proxied object. The
method is wrapped to return the proxy instead of the object.
"""
__slots__ = ()
def __init__(
self, f: t.Optional[t.Callable] = None, fallback: t.Optional[t.Callable] = None
) -> None:
... | class _ProxyIOp(_ProxyLookup):
| """Look up an augmented assignment method on a proxied object. The
method is wrapped to return the proxy instead of the object.
"""
__slots__ = ()
def __init__(
self, f: t.Optional[t.Callable] = None, fallback: t.Optional[t.Callable] = None
) -> None:
super().__init__(f, fallba... | `, which does
``type(x).__copy__(x)``. ``type(x)`` can't be proxied, so it
returns the proxy type and descriptor.
"""
return self.__get__(instance, type(instance))(*args, **kwargs)
class _ProxyIOp(_ProxyLookup):
| 64 | 64 | 171 | 9 | 55 | swt2c/werkzeug | src/werkzeug/local.py | Python | _ProxyIOp | _ProxyIOp | 297 | 316 | 297 | 297 | c3be4209854b16ae4f601226b4a096e926bb16e2 | bigcode/the-stack | train |
d91659bafe306c268a22c02c | train | class | class _ProxyLookup:
"""Descriptor that handles proxied attribute lookup for
:class:`LocalProxy`.
:param f: The built-in function this attribute is accessed through.
Instead of looking up the special method, the function call
is redone on the object.
:param fallback: Call this method if ... | class _ProxyLookup:
| """Descriptor that handles proxied attribute lookup for
:class:`LocalProxy`.
:param f: The built-in function this attribute is accessed through.
Instead of looking up the special method, the function call
is redone on the object.
:param fallback: Call this method if the proxy is unbound... | after
request end.
"""
def application(
environ: "WSGIEnvironment", start_response: "StartResponse"
) -> t.Iterable[bytes]:
return ClosingIterator(app(environ, start_response), self.cleanup)
return application
def middleware(self, func: "WSGIApplic... | 190 | 191 | 638 | 5 | 185 | swt2c/werkzeug | src/werkzeug/local.py | Python | _ProxyLookup | _ProxyLookup | 219 | 294 | 219 | 219 | bd979ee6d4e2bd1a71452010248ab90ae9cfec96 | bigcode/the-stack | train |
f72e6939e01781289ef24f9e | train | class | class LocalProxy:
"""A proxy to the object bound to a :class:`Local`. All operations
on the proxy are forwarded to the bound object. If no object is
bound, a :exc:`RuntimeError` is raised.
.. code-block:: python
from werkzeug.local import Local
l = Local()
# a proxy to whateve... | class LocalProxy:
| """A proxy to the object bound to a :class:`Local`. All operations
on the proxy are forwarded to the bound object. If no object is
bound, a :exc:`RuntimeError` is raised.
.. code-block:: python
from werkzeug.local import Local
l = Local()
# a proxy to whatever l.user is set to... | """
return self.__get__(instance, type(instance))(*args, **kwargs)
class _ProxyIOp(_ProxyLookup):
"""Look up an augmented assignment method on a proxied object. The
method is wrapped to return the proxy instead of the object.
"""
__slots__ = ()
def __init__(
self, f: t.Optional[... | 256 | 256 | 2,094 | 4 | 252 | swt2c/werkzeug | src/werkzeug/local.py | Python | LocalProxy | LocalProxy | 328 | 512 | 328 | 328 | 861628a5d44a63bfe9a791c008789de29a443132 | bigcode/the-stack | train |
ea21b6db3ea84b32cdd9ac93 | train | class | class LabD65(LabBase):
"""Lab D65 class."""
SPACE = "lab-d65"
SERIALIZE = ("--lab-d65",)
DEFAULT_MATCH = re.compile(RE_DEFAULT_MATCH.format(color_space='|'.join(SERIALIZE), channels=3))
WHITE = "D65"
@classmethod
def _to_xyz(cls, parent, lab):
"""To XYZ."""
return parent.c... | class LabD65(LabBase):
| """Lab D65 class."""
SPACE = "lab-d65"
SERIALIZE = ("--lab-d65",)
DEFAULT_MATCH = re.compile(RE_DEFAULT_MATCH.format(color_space='|'.join(SERIALIZE), channels=3))
WHITE = "D65"
@classmethod
def _to_xyz(cls, parent, lab):
"""To XYZ."""
return parent.chromatic_adaptation(cls... | """Lab D65 class."""
from ..spaces import RE_DEFAULT_MATCH
from .xyz import XYZ
from .lab.base import LabBase, lab_to_xyz, xyz_to_lab
import re
class LabD65(LabBase):
| 47 | 64 | 149 | 8 | 38 | evandroforks/mdpopups | st3/mdpopups/coloraide/spaces/lab_d65.py | Python | LabD65 | LabD65 | 8 | 26 | 8 | 8 | 19439d61fbd85a788fd604ceec29995c540391b9 | bigcode/the-stack | train |
8cc9a3db3dc8ce85e274295b | train | class | class PSF(object):
"""
Point Spread Function convolution
"""
def __init__(self, psf_type='NONE', fwhm=None, truncation=5, pixel_size=None, kernel_point_source=None,
psf_error_map=None, point_source_supersampling_factor=1, kernel_point_source_init=None):
"""
:param psf_... | class PSF(object):
| """
Point Spread Function convolution
"""
def __init__(self, psf_type='NONE', fwhm=None, truncation=5, pixel_size=None, kernel_point_source=None,
psf_error_map=None, point_source_supersampling_factor=1, kernel_point_source_init=None):
"""
:param psf_type: string, type ... | import numpy as np
import lenstronomy.Util.kernel_util as kernel_util
import lenstronomy.Util.util as util
import warnings
class PSF(object):
| 33 | 256 | 1,586 | 5 | 27 | tvelagapudi/lenstronomy | lenstronomy/Data/psf.py | Python | PSF | PSF | 7 | 150 | 7 | 7 | fcb90d5142fa119fbeffd65e99882b4c6db36612 | bigcode/the-stack | train |
1cbae99752b8e7f326e9e52e | train | function | def _do_transfer(
src: "ObjectDB",
dest: "ObjectDB",
obj_ids: Iterable["HashInfo"],
missing_ids: Iterable["HashInfo"],
processor: Callable,
src_index: Optional["ObjectDBIndexBase"] = None,
dest_index: Optional["ObjectDBIndexBase"] = None,
cache_odb: Optional["ObjectDB"] = None,
**kwa... | def _do_transfer(
src: "ObjectDB",
dest: "ObjectDB",
obj_ids: Iterable["HashInfo"],
missing_ids: Iterable["HashInfo"],
processor: Callable,
src_index: Optional["ObjectDBIndexBase"] = None,
dest_index: Optional["ObjectDBIndexBase"] = None,
cache_odb: Optional["ObjectDB"] = None,
**kwa... | from dvc.exceptions import FileTransferError
dir_ids, file_ids = split(lambda hash_info: hash_info.isdir, obj_ids)
total_fails = 0
succeeded_dir_objs = []
all_file_ids = set(file_ids)
for dir_hash in dir_ids:
dir_obj = find_tree_by_obj_id([cache_odb, src], dir_hash)
assert dir_... | : Iterable[Optional["ObjectDB"]], obj_id: "HashInfo"
) -> Optional["Tree"]:
from .errors import ObjectFormatError
from .tree import Tree
for odb in odbs:
if odb is not None:
try:
return Tree.load(odb, obj_id)
except (FileNotFoundError, ObjectFormatError):
... | 174 | 174 | 581 | 90 | 83 | lucasalavapena/dvc | dvc/objects/transfer.py | Python | _do_transfer | _do_transfer | 55 | 127 | 55 | 65 | ce05ef5efe7712fe10467a56af5b289e9acfbeb0 | bigcode/the-stack | train |
62223294aad5fec9ac698eca | train | function | def transfer(
src: "ObjectDB",
dest: "ObjectDB",
obj_ids: Iterable["HashInfo"],
jobs: Optional[int] = None,
verify: bool = False,
hardlink: bool = False,
**kwargs,
) -> int:
"""Transfer (copy) the specified objects from one ODB to another.
Returns the number of successfully transfer... | def transfer(
src: "ObjectDB",
dest: "ObjectDB",
obj_ids: Iterable["HashInfo"],
jobs: Optional[int] = None,
verify: bool = False,
hardlink: bool = False,
**kwargs,
) -> int:
| """Transfer (copy) the specified objects from one ODB to another.
Returns the number of successfully transferred objects
"""
from .status import compare_status
logger.debug(
"Preparing to transfer data from '%s' to '%s'",
src.fs_path,
dest.fs_path,
)
if src == dest:... | .hash_info,
len(file_hashes),
)
assert dir_obj.hash_info and dir_obj.hash_info.value
dest_index.update([dir_obj.hash_info.value], file_hashes)
def transfer(
src: "ObjectDB",
dest: "ObjectDB",
obj_ids: Iterable["HashInfo"],
jobs: Optional[int] = None,
... | 97 | 97 | 326 | 58 | 39 | lucasalavapena/dvc | dvc/objects/transfer.py | Python | transfer | transfer | 130 | 176 | 130 | 138 | 40360665f3158110de9a5a2a865e4f55712fa4d8 | bigcode/the-stack | train |
04c172fa65f214aeb4f3961e | train | function | def find_tree_by_obj_id(
odbs: Iterable[Optional["ObjectDB"]], obj_id: "HashInfo"
) -> Optional["Tree"]:
from .errors import ObjectFormatError
from .tree import Tree
for odb in odbs:
if odb is not None:
try:
return Tree.load(odb, obj_id)
except (FileNotFo... | def find_tree_by_obj_id(
odbs: Iterable[Optional["ObjectDB"]], obj_id: "HashInfo"
) -> Optional["Tree"]:
| from .errors import ObjectFormatError
from .tree import Tree
for odb in odbs:
if odb is not None:
try:
return Tree.load(odb, obj_id)
except (FileNotFoundError, ObjectFormatError):
pass
return None
| .errno == errno.EMFILE:
raise
logger.exception("failed to transfer '%s'", fs_path)
return 1
return wrapper
def find_tree_by_obj_id(
odbs: Iterable[Optional["ObjectDB"]], obj_id: "HashInfo"
) -> Optional["Tree"]:
| 64 | 64 | 94 | 32 | 31 | lucasalavapena/dvc | dvc/objects/transfer.py | Python | find_tree_by_obj_id | find_tree_by_obj_id | 40 | 52 | 40 | 42 | 2896891d5fae33ad15d98dda852f1113f7e7ae49 | bigcode/the-stack | train |
1524eb7f236ba5ebcd45c43f | train | function | def _log_exceptions(func):
@wraps(func)
def wrapper(fs_path, *args, **kwargs):
try:
func(fs_path, *args, **kwargs)
return 0
except Exception as exc: # pylint: disable=broad-except
# NOTE: this means we ran out of file descriptors and there is no
#... | def _log_exceptions(func):
@wraps(func)
| def wrapper(fs_path, *args, **kwargs):
try:
func(fs_path, *args, **kwargs)
return 0
except Exception as exc: # pylint: disable=broad-except
# NOTE: this means we ran out of file descriptors and there is no
# reason to try to proceed, as we will hit th... |
if TYPE_CHECKING:
from dvc.hash_info import HashInfo
from .db.base import ObjectDB
from .db.index import ObjectDBIndexBase
from .tree import Tree
logger = logging.getLogger(__name__)
def _log_exceptions(func):
@wraps(func)
| 64 | 64 | 143 | 13 | 51 | lucasalavapena/dvc | dvc/objects/transfer.py | Python | _log_exceptions | _log_exceptions | 21 | 37 | 21 | 22 | dfe00e20a4a3ca86ec261a33979ea605918204a8 | bigcode/the-stack | train |
605f8a44a95abc39f3dc933c | train | class | class AwaitableGetP2sVpnGatewayResult(GetP2sVpnGatewayResult):
# pylint: disable=using-constant-test
def __await__(self):
if False:
yield self
return GetP2sVpnGatewayResult(
custom_routes=self.custom_routes,
etag=self.etag,
id=self.id,
... | class AwaitableGetP2sVpnGatewayResult(GetP2sVpnGatewayResult):
# pylint: disable=using-constant-test
| def __await__(self):
if False:
yield self
return GetP2sVpnGatewayResult(
custom_routes=self.custom_routes,
etag=self.etag,
id=self.id,
location=self.location,
name=self.name,
p2_s_vpn_server_configuration=self.p2_s_v... | (self) -> Optional[int]:
"""
The scale unit for this p2s vpn gateway.
"""
return pulumi.get(self, "vpn_gateway_scale_unit")
class AwaitableGetP2sVpnGatewayResult(GetP2sVpnGatewayResult):
# pylint: disable=using-constant-test
| 64 | 64 | 164 | 29 | 35 | pulumi-bot/pulumi-azure-native | sdk/python/pulumi_azure_native/network/v20190601/get_p2s_vpn_gateway.py | Python | AwaitableGetP2sVpnGatewayResult | AwaitableGetP2sVpnGatewayResult | 169 | 187 | 169 | 170 | 7830de717025ddfea4eb72e906cd746854a29ebd | bigcode/the-stack | train |
7531ac44493f311bdc62cc28 | train | function | def get_p2s_vpn_gateway(gateway_name: Optional[str] = None,
resource_group_name: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetP2sVpnGatewayResult:
"""
P2SVpnGateway Resource.
:param str gateway_name: The name of the gatew... | def get_p2s_vpn_gateway(gateway_name: Optional[str] = None,
resource_group_name: Optional[str] = None,
opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetP2sVpnGatewayResult:
| """
P2SVpnGateway Resource.
:param str gateway_name: The name of the gateway.
:param str resource_group_name: The resource group name of the P2SVpnGateway.
"""
__args__ = dict()
__args__['gatewayName'] = gateway_name
__args__['resourceGroupName'] = resource_group_name
if opts is No... | tags=self.tags,
type=self.type,
virtual_hub=self.virtual_hub,
vpn_client_address_pool=self.vpn_client_address_pool,
vpn_client_connection_health=self.vpn_client_connection_health,
vpn_gateway_scale_unit=self.vpn_gateway_scale_unit)
def get_p2s_vpn_... | 108 | 108 | 362 | 53 | 55 | pulumi-bot/pulumi-azure-native | sdk/python/pulumi_azure_native/network/v20190601/get_p2s_vpn_gateway.py | Python | get_p2s_vpn_gateway | get_p2s_vpn_gateway | 190 | 222 | 190 | 192 | 5e7f32130edb7649d1ffc8fd90a976816f5366b4 | bigcode/the-stack | train |
a90ae57f7eb3fd1c7245dfae | train | class | @pulumi.output_type
class GetP2sVpnGatewayResult:
"""
P2SVpnGateway Resource.
"""
def __init__(__self__, custom_routes=None, etag=None, id=None, location=None, name=None, p2_s_vpn_server_configuration=None, provisioning_state=None, tags=None, type=None, virtual_hub=None, vpn_client_address_pool=None, vp... | @pulumi.output_type
class GetP2sVpnGatewayResult:
| """
P2SVpnGateway Resource.
"""
def __init__(__self__, custom_routes=None, etag=None, id=None, location=None, name=None, p2_s_vpn_server_configuration=None, provisioning_state=None, tags=None, type=None, virtual_hub=None, vpn_client_address_pool=None, vpn_client_connection_health=None, vpn_gateway_scale... | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from ... import _utilities, _tables
from... | 133 | 256 | 1,375 | 15 | 118 | pulumi-bot/pulumi-azure-native | sdk/python/pulumi_azure_native/network/v20190601/get_p2s_vpn_gateway.py | Python | GetP2sVpnGatewayResult | GetP2sVpnGatewayResult | 18 | 166 | 18 | 19 | 9a743b27d601e26961029ae9632807976aaf3607 | bigcode/the-stack | train |
78eb7ecadb91368472ed94af | train | class | class FilterCog(commands.Cog, name = "Filter"):
"""Commands for filtering things"""
def __init__(self, client):
self.client = client
self.channel = 745390366802575391
#self.sync_filter.start()
async def filter_message(self,message):
async with aiosqlite.connect('fil... | class FilterCog(commands.Cog, name = "Filter"):
| """Commands for filtering things"""
def __init__(self, client):
self.client = client
self.channel = 745390366802575391
#self.sync_filter.start()
async def filter_message(self,message):
async with aiosqlite.connect('filter.db') as connection:
async with c... | License
Copyright (c) 2020 BobDotCom
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute... | 256 | 256 | 2,191 | 12 | 243 | BobDotCom/BobDotBot | cogs/filter.py | Python | FilterCog | FilterCog | 29 | 280 | 29 | 29 | f7502336da0356712c2f27e7f727864c2a072bb7 | bigcode/the-stack | train |
788e916825928d984aea6587 | train | function | def setup(client):
client.add_cog(FilterCog(client))
| def setup(client):
| client.add_cog(FilterCog(client))
| (self):
with open('filter.json','r') as f:
data = json.load(f)
self.filtered_words = data['words']
# CHECKS #
async def cog_check(self,ctx):
return True # ctx.author.id == 690420846774321221
def setup(client):
| 64 | 64 | 13 | 4 | 59 | BobDotCom/BobDotBot | cogs/filter.py | Python | setup | setup | 282 | 283 | 282 | 282 | 949de45ffb92089dd2058c545935ad502e172cc6 | bigcode/the-stack | train |
58489e8c3a02dc18bbea964d | train | function | def F1(t):
return 0.063 * (t ** 3) - 5.284 * t * t + 4.887 * t + 412 + np.random.normal(0, 1)
| def F1(t):
| return 0.063 * (t ** 3) - 5.284 * t * t + 4.887 * t + 412 + np.random.normal(0, 1)
| #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 15 18:41:35 2017
@author: sitibanc
"""
import math
import numpy as np
from matplotlib import pyplot as plt
# Linear Regression
def F1(t):
| 63 | 64 | 47 | 5 | 57 | SitiBanc/1061_NCTU_IOMDS | 1115/Course Material/1115.py | Python | F1 | F1 | 14 | 15 | 14 | 14 | 9e6a791383f4fe6ce445558a830f728aab2bf0af | bigcode/the-stack | train |
723d1714a76101ee5e8844c5 | train | function | def E(b2, A2, A, B, C, D):
sum = 0
for i in range(1000):
sum = sum + abs(F2(A2[i], A, B, C, D) - b2[i])
return sum
| def E(b2, A2, A, B, C, D):
| sum = 0
for i in range(1000):
sum = sum + abs(F2(A2[i], A, B, C, D) - b2[i])
return sum
| -Linear
def F2(t, A, B, C, D):
return A * (t ** B) + C * math.cos(D * t) + np.random.normal(0, 1)
# Energy Function
def E(b2, A2, A, B, C, D):
| 64 | 64 | 60 | 16 | 47 | SitiBanc/1061_NCTU_IOMDS | 1115/Course Material/1115.py | Python | E | E | 24 | 28 | 24 | 24 | 89e8246697ba26b2f0c31644ec95f8b98f196d9b | bigcode/the-stack | train |
b482e08dda82aaa110e7177e | train | function | def F2(t, A, B, C, D):
return A * (t ** B) + C * math.cos(D * t) + np.random.normal(0, 1)
| def F2(t, A, B, C, D):
| return A * (t ** B) + C * math.cos(D * t) + np.random.normal(0, 1)
| F1(t):
return 0.063 * (t ** 3) - 5.284 * t * t + 4.887 * t + 412 + np.random.normal(0, 1)
# Non-Linear
def F2(t, A, B, C, D):
| 64 | 64 | 41 | 13 | 50 | SitiBanc/1061_NCTU_IOMDS | 1115/Course Material/1115.py | Python | F2 | F2 | 19 | 20 | 19 | 19 | 0ab0151b1a2da0665a557ebbd111cae8cbc6de44 | bigcode/the-stack | train |
4e4a4f5141173017c92b4452 | train | function | def ts_to_hrs(time_val, filedate):
'''Convert utc timestamp to hours since midnight on filedate.'''
return (datetime.utcfromtimestamp(time_val).replace(tzinfo=timezone.utc) -
filedate).total_seconds()/3600.
| def ts_to_hrs(time_val, filedate):
| '''Convert utc timestamp to hours since midnight on filedate.'''
return (datetime.utcfromtimestamp(time_val).replace(tzinfo=timezone.utc) -
filedate).total_seconds()/3600.
| /m**3'],
'HmF2': ['HmF2', 'height of maximum electron number density in F2 layer',
12, 'SPH', 'sph', ['time', 'lon', 'lat'], 'km']
}
def ts_to_hrs(time_val, filedate):
| 64 | 64 | 56 | 11 | 53 | nasa/Kamodo-Analysis-Suite | kamodo_ccmc/readers/iri_4D.py | Python | ts_to_hrs | ts_to_hrs | 36 | 40 | 36 | 36 | e2f1bd87eb46a7a177d1df57fc4a64e954b0dbb2 | bigcode/the-stack | train |
a8ce911f2f7252b244a2ece0 | train | function | def MODEL():
from kamodo import Kamodo
from netCDF4 import Dataset
from os.path import basename
from numpy import array, transpose, NaN, unique, append, zeros, abs, diff, where
from time import perf_counter
from astropy.constants import R_earth
from kamodo_ccmc.readers.reader_utilit... | def MODEL():
| from kamodo import Kamodo
from netCDF4 import Dataset
from os.path import basename
from numpy import array, transpose, NaN, unique, append, zeros, abs, diff, where
from time import perf_counter
from astropy.constants import R_earth
from kamodo_ccmc.readers.reader_utilities import regde... | 'vertical total electron content (height integrated from bottom to top boundary)',
10, 'SPH', 'sph', ['time', 'lon', 'lat'], '10**16/m**2'],
'NmF2': ['NmF2', 'maximum electron number density in F2 layer',
11, 'SPH', 'sph', ['time', 'lon', 'lat']... | 256 | 256 | 3,432 | 4 | 251 | nasa/Kamodo-Analysis-Suite | kamodo_ccmc/readers/iri_4D.py | Python | MODEL | MODEL | 47 | 354 | 47 | 48 | 72d1f24280e08b308c47e24b741c5c08a6da13f1 | bigcode/the-stack | train |
3bf29ae570996fe4fb90b7f8 | train | class | class NatGateway(pulumi.CustomResource):
@overload
def __init__(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
id: Optional[pulumi.Input[str]] = None,
idle_timeout_in_minutes: Optional[pulumi.Input[int]] = None,
... | class NatGateway(pulumi.CustomResource):
@overload
| def __init__(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
id: Optional[pulumi.Input[str]] = None,
idle_timeout_in_minutes: Optional[pulumi.Input[int]] = None,
location: Optional[pulumi.Input[str]] = ... | The nat gateway SKU.
"""
return pulumi.get(self, "sku")
@sku.setter
def sku(self, value: Optional[pulumi.Input['NatGatewaySkuArgs']]):
pulumi.set(self, "sku", value)
@property
@pulumi.getter
def tags(self) -> Optional[pulumi.Input[Mapping[str, pulumi.Input[str]]]]:
... | 256 | 256 | 3,057 | 14 | 242 | polivbr/pulumi-azure-native | sdk/python/pulumi_azure_native/network/v20200701/nat_gateway.py | Python | NatGateway | NatGateway | 183 | 420 | 183 | 184 | 5989fb71967994e4d281f1dbe6811825de539d10 | bigcode/the-stack | train |
7d2c4e0d3a482fbcc6fd423a | train | class | @pulumi.input_type
class NatGatewayInitArgs:
def __init__(__self__, *,
resource_group_name: pulumi.Input[str],
id: Optional[pulumi.Input[str]] = None,
idle_timeout_in_minutes: Optional[pulumi.Input[int]] = None,
location: Optional[pulumi.Input[str]... | @pulumi.input_type
class NatGatewayInitArgs:
| def __init__(__self__, *,
resource_group_name: pulumi.Input[str],
id: Optional[pulumi.Input[str]] = None,
idle_timeout_in_minutes: Optional[pulumi.Input[int]] = None,
location: Optional[pulumi.Input[str]] = None,
nat_gateway_name: ... | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
fro... | 118 | 256 | 1,599 | 12 | 106 | polivbr/pulumi-azure-native | sdk/python/pulumi_azure_native/network/v20200701/nat_gateway.py | Python | NatGatewayInitArgs | NatGatewayInitArgs | 16 | 180 | 16 | 17 | c11afacd540e7b8f4052c7c620efa68dd8856005 | bigcode/the-stack | train |
9a3c430485b7ebcb3c688d1b | train | class | class SensorWrapperTestCase(unittest2.TestCase):
@classmethod
def setUpClass(cls):
super(SensorWrapperTestCase, cls).setUpClass()
tests_config.parse_args()
def test_sensor_instance_has_sensor_service(self):
file_path = os.path.join(RESOURCES_DIR, 'test_sensor.py')
trigger_ty... | class SensorWrapperTestCase(unittest2.TestCase):
@classmethod
| def setUpClass(cls):
super(SensorWrapperTestCase, cls).setUpClass()
tests_config.parse_args()
def test_sensor_instance_has_sensor_service(self):
file_path = os.path.join(RESOURCES_DIR, 'test_sensor.py')
trigger_types = ['trigger1', 'trigger2']
parent_args = ['--config-fi... | # you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES... | 256 | 256 | 1,314 | 14 | 242 | tirkarthi/st2 | st2reactor/tests/unit/test_sensor_wrapper.py | Python | SensorWrapperTestCase | SensorWrapperTestCase | 42 | 170 | 42 | 43 | 963f88f96fa8d6ad3c52e69535e34a4013b6929d | bigcode/the-stack | train |
1393f30bc362d5d48b14c6da | train | function | def random_gradient(canvas):
# specifying the image dimesion in pixels (1:1 ratio)
dimension = 2000
# creating a new image canvas with defined dimension
img = Image.new("RGB", (dimension, dimension), "#000000")
draw = ImageDraw.Draw(img)
# generating random integers for Red, Green & Blue
r... | def random_gradient(canvas):
# specifying the image dimesion in pixels (1:1 ratio)
| dimension = 2000
# creating a new image canvas with defined dimension
img = Image.new("RGB", (dimension, dimension), "#000000")
draw = ImageDraw.Draw(img)
# generating random integers for Red, Green & Blue
r, g, b = rint(0, 255), rint(0, 255), rint(0, 255)
dr = (rint(0, 255) - r) / dimensi... | from PIL import Image, ImageDraw
from random import randint as rint
# Definig custom function
def random_gradient(canvas):
# specifying the image dimesion in pixels (1:1 ratio)
| 43 | 73 | 246 | 21 | 21 | tre3x/awesomeScripts | gradient_generator/gradient.py | Python | random_gradient | random_gradient | 6 | 25 | 6 | 7 | 791f003d66f95572773e1c939fb0f3cc506c0688 | bigcode/the-stack | train |
137f9057348321f51fbd497f | train | class | class SignInTest(BaseTest):
# Currently these are the prepared data
# We want to quick start the API Test so we set it here
DEFAULT_PASSWORD = "12345678"
INVALID_EMAIL = "somethingiswrongwiththisusernamepleasedontsignupwithit@gmail.com"
INVALID_PASSWORD = "^&%$^%#%^$@#%$$*^$"
INVALID_INPUT... | class SignInTest(BaseTest):
# Currently these are the prepared data
# We want to quick start the API Test so we set it here
| DEFAULT_PASSWORD = "12345678"
INVALID_EMAIL = "somethingiswrongwiththisusernamepleasedontsignupwithit@gmail.com"
INVALID_PASSWORD = "^&%$^%#%^$@#%$$*^$"
INVALID_INPUT = 14
INVALID_PARAM = 13
BLANK_FIELD_CODE = 14
NO_EMAIL_CODE = 14
def __init__(self, *args, **kwargs):
s... | from API import SignIn, SignUp
from Core.Base.BaseTest import BaseTest
from Core.Assertions.Assertion import APIAssert
from Utils.JSONUtils import JSONUtils
from Utils.DataGenerateUtils import DataGenerateUtils
class SignInTest(BaseTest):
# Currently these are the prepared data
# We want to quick start th... | 77 | 256 | 1,094 | 32 | 44 | toilatester/sample-automation-frameworks-across-languages | python/TestAPI/SignInTest.py | Python | SignInTest | SignInTest | 8 | 118 | 8 | 10 | 9746fc391adf1164e76c7665dfe6c38ebb2471af | bigcode/the-stack | train |
98dd85b170099a45f85c8ed1 | train | function | def drop_empty_dict_values(already: Dict, **kwargs) -> Dict:
overlay = {k: v for k, v in kwargs.items() if v not in _empty_symbols}
return {**already, **overlay}
| def drop_empty_dict_values(already: Dict, **kwargs) -> Dict:
| overlay = {k: v for k, v in kwargs.items() if v not in _empty_symbols}
return {**already, **overlay}
| import Dict, Iterable, List, Union
_backslash = '\\'
_empty_symbols = (None, '', [], {}) # exclude 0
_filter_symbols = {"-filter_complex", "-vf", "-af", "-lavfi"}
def drop_empty_dict_values(already: Dict, **kwargs) -> Dict:
| 63 | 64 | 48 | 16 | 47 | wilson52c/ffmpeg-generator | ffmpeg/_utils.py | Python | drop_empty_dict_values | drop_empty_dict_values | 14 | 16 | 14 | 14 | fdeef98c5b27bfd25a728b41eb768e203cd7cdbd | bigcode/the-stack | train |
95235e4662ed9440da0cde0d | train | function | def drop_empty_list_values(already: list, **kwargs) -> list:
already = list(already)
for k, v in kwargs.items():
if v:
already.append(f'-{k}')
return already
| def drop_empty_list_values(already: list, **kwargs) -> list:
| already = list(already)
for k, v in kwargs.items():
if v:
already.append(f'-{k}')
return already
| def drop_empty_dict_values(already: Dict, **kwargs) -> Dict:
overlay = {k: v for k, v in kwargs.items() if v not in _empty_symbols}
return {**already, **overlay}
def drop_empty_list_values(already: list, **kwargs) -> list:
| 64 | 64 | 48 | 16 | 48 | wilson52c/ffmpeg-generator | ffmpeg/_utils.py | Python | drop_empty_list_values | drop_empty_list_values | 19 | 24 | 19 | 19 | d84c7608cfaa6ffeb862f86e718901f7ea1c7a0f | bigcode/the-stack | train |
428fa177e8db530216b5599d | train | function | def join_cmd_args_seq(args: List[str]) -> str:
cmd_args_seq = list(args)
for i in range(len(cmd_args_seq)):
if cmd_args_seq[i] in _filter_symbols:
cmd_args_seq[i + 1] = f'"{cmd_args_seq[i + 1]}"'
elif ' ' in cmd_args_seq[i]:
cmd_args_seq[i] = f'"{cmd_args_seq[i]}"'
... | def join_cmd_args_seq(args: List[str]) -> str:
| cmd_args_seq = list(args)
for i in range(len(cmd_args_seq)):
if cmd_args_seq[i] in _filter_symbols:
cmd_args_seq[i + 1] = f'"{cmd_args_seq[i + 1]}"'
elif ' ' in cmd_args_seq[i]:
cmd_args_seq[i] = f'"{cmd_args_seq[i]}"'
return " ".join(cmd_args_seq)
| '-{key}')
if value not in _empty_symbols:
args.append(f'{value}')
continue
args.append(f'-{key}')
if v not in _empty_symbols:
args.append(f'{v}')
return args
def join_cmd_args_seq(args: List[str]) -> str:
| 64 | 64 | 100 | 13 | 50 | wilson52c/ffmpeg-generator | ffmpeg/_utils.py | Python | join_cmd_args_seq | join_cmd_args_seq | 70 | 79 | 70 | 70 | f55d24ffb41d0e26258630198c35976774abc7a0 | bigcode/the-stack | train |
cced7cfec8441c57e1ffbc30 | train | function | def convert_kwargs_string(**kwargs):
return ':'.join([f'{k}={v}' for k, v in kwargs.items() if v not in _empty_symbols])
| def convert_kwargs_string(**kwargs):
| return ':'.join([f'{k}={v}' for k, v in kwargs.items() if v not in _empty_symbols])
| return {**already, **overlay}
def drop_empty_list_values(already: list, **kwargs) -> list:
already = list(already)
for k, v in kwargs.items():
if v:
already.append(f'-{k}')
return already
def convert_kwargs_string(**kwargs):
| 64 | 64 | 36 | 7 | 56 | wilson52c/ffmpeg-generator | ffmpeg/_utils.py | Python | convert_kwargs_string | convert_kwargs_string | 27 | 28 | 27 | 27 | 45e7884d4ef5a79cd964e274f540302da59379d4 | bigcode/the-stack | train |
12906445b7fa623b7c7188fc | train | function | def seconds_to_string(seconds: Union[float, int, str]) -> str:
if isinstance(seconds, str):
return seconds
hours = seconds // (60 * 60)
minutes = seconds % (60 * 60) // 60
seconds -= hours * 60 * 60 + minutes * 60
return f"{hours:02.0f}:{minutes:02.0f}:{seconds:02.03f}"
| def seconds_to_string(seconds: Union[float, int, str]) -> str:
| if isinstance(seconds, str):
return seconds
hours = seconds // (60 * 60)
minutes = seconds % (60 * 60) // 60
seconds -= hours * 60 * 60 + minutes * 60
return f"{hours:02.0f}:{minutes:02.0f}:{seconds:02.03f}"
| clock[0], clock[1]
else:
hours, minutes, seconds = clock[0], clock[1], clock[2]
return hours * 60 * 60 + minutes * 60 + seconds
def seconds_to_string(seconds: Union[float, int, str]) -> str:
| 64 | 64 | 95 | 17 | 46 | wilson52c/ffmpeg-generator | ffmpeg/_utils.py | Python | seconds_to_string | seconds_to_string | 99 | 106 | 99 | 99 | ccd037e7b9b9c2ed09c8bca6a45a62d9da6667dc | bigcode/the-stack | train |
5c99455341c2224e24037ec8 | train | function | def string_to_seconds(clock: str) -> int:
if isinstance(clock, (int, float)):
return clock
clock = [int(c) for c in clock.split(":")]
if len(clock) == 0:
hours, minutes, seconds = 0, 0, 0
elif len(clock) == 1:
hours, minutes, seconds = 0, 0, clock[0]
elif len(clock) == 2:
... | def string_to_seconds(clock: str) -> int:
| if isinstance(clock, (int, float)):
return clock
clock = [int(c) for c in clock.split(":")]
if len(clock) == 0:
hours, minutes, seconds = 0, 0, 0
elif len(clock) == 1:
hours, minutes, seconds = 0, 0, clock[0]
elif len(clock) == 2:
hours, minutes, seconds = 0, clock[0... | [i + 1] = f'"{cmd_args_seq[i + 1]}"'
elif ' ' in cmd_args_seq[i]:
cmd_args_seq[i] = f'"{cmd_args_seq[i]}"'
return " ".join(cmd_args_seq)
def string_to_seconds(clock: str) -> int:
| 64 | 64 | 156 | 11 | 53 | wilson52c/ffmpeg-generator | ffmpeg/_utils.py | Python | string_to_seconds | string_to_seconds | 82 | 96 | 82 | 82 | 96994936cab87e8cce53439229fe1f5811e7f82f | bigcode/the-stack | train |
3cc99057480ab4a6d4157bb6 | train | function | def escape(text: str, chars: str) -> str:
"""Helper function to escape uncomfortable characters."""
text = str(text)
chars = list(set(chars))
if _backslash in chars:
chars.remove(_backslash)
chars.insert(0, _backslash)
for char in chars:
text = text.replace(char, _backslash... | def escape(text: str, chars: str) -> str:
| """Helper function to escape uncomfortable characters."""
text = str(text)
chars = list(set(chars))
if _backslash in chars:
chars.remove(_backslash)
chars.insert(0, _backslash)
for char in chars:
text = text.replace(char, _backslash + char)
return text
| if v:
already.append(f'-{k}')
return already
def convert_kwargs_string(**kwargs):
return ':'.join([f'{k}={v}' for k, v in kwargs.items() if v not in _empty_symbols])
def escape(text: str, chars: str) -> str:
| 64 | 64 | 83 | 13 | 51 | wilson52c/ffmpeg-generator | ffmpeg/_utils.py | Python | escape | escape | 31 | 43 | 31 | 31 | 0adf73c26aa13d6e2908eb90c1e53d9ea53268b2 | bigcode/the-stack | train |
e90f479772e62c21f115df4c | train | function | def convert_kwargs_to_cmd_line_args(kwargs: Dict, sort=True) -> List[str]:
"""Helper function to build command line arguments out of dict."""
args = []
keys = sorted(kwargs.keys()) if sort else kwargs.keys()
for key in keys:
v = kwargs[key]
# list, tuple, map
if isinstance(v, I... | def convert_kwargs_to_cmd_line_args(kwargs: Dict, sort=True) -> List[str]:
| """Helper function to build command line arguments out of dict."""
args = []
keys = sorted(kwargs.keys()) if sort else kwargs.keys()
for key in keys:
v = kwargs[key]
# list, tuple, map
if isinstance(v, Iterable) and not isinstance(v, str):
for value in v:
... | _backslash in chars:
chars.remove(_backslash)
chars.insert(0, _backslash)
for char in chars:
text = text.replace(char, _backslash + char)
return text
def convert_kwargs_to_cmd_line_args(kwargs: Dict, sort=True) -> List[str]:
| 64 | 64 | 143 | 18 | 45 | wilson52c/ffmpeg-generator | ffmpeg/_utils.py | Python | convert_kwargs_to_cmd_line_args | convert_kwargs_to_cmd_line_args | 46 | 67 | 46 | 46 | b4a3ef5fac9b40e6e53797ad79a71823b91a35bc | bigcode/the-stack | train |
0122e13cef6e14afc1b39a66 | train | function | def traco():
print('-'*50)
| def traco():
| print('-'*50)
| '''
Faça um programa que pergunte a hora ao usuário e, baseando-se no horário descrito, exiba a saudação apropriada.
Bom dia 0 - 11, Boa tarde 12 - 17 e Boa noite 18 - 23
'''
def traco():
| 58 | 64 | 10 | 4 | 54 | jonfisik/Projects | python/projetos_dev/python_basico/exer_saudacao.py | Python | traco | traco | 5 | 6 | 5 | 5 | 9d6e234f3c31a50e80120029ff5551671aea4294 | bigcode/the-stack | train |
b478af6f818453404f971baf | train | function | def ai(grades, speed):
if(grades>=0):
points = ((grades/90)*40/2)
return "$A,"+str(speed) + "," + str(points) + "," + str(-speed) + "," + str(points)
# cant_encoders = [speed, points, -speed, points]
else:
grades = -1 *grades
points = ((grades/90)*40/2)
return "$A,... | def ai(grades, speed):
| if(grades>=0):
points = ((grades/90)*40/2)
return "$A,"+str(speed) + "," + str(points) + "," + str(-speed) + "," + str(points)
# cant_encoders = [speed, points, -speed, points]
else:
grades = -1 *grades
points = ((grades/90)*40/2)
return "$A,"+str(-speed) + "," + s... | '''Donde g = grados y v = velocidad'''
def ai(grades, speed):
| 18 | 64 | 122 | 7 | 11 | GeorgEncinas/Multi-Agents | funcion.py | Python | ai | ai | 3 | 11 | 3 | 3 | 4b556207ee45e45efe9c0e86787bf34b0204d150 | bigcode/the-stack | train |
4638e884da5c86c2011ab8b9 | train | class | class Error(Exception):
pass
| class Error(Exception):
| pass
| import os
import shutil
import zipfile
from jinja2.sandbox import SandboxedEnvironment
from inkpy_jinja.backends.external_script import ExternalRenderer
settings = {}
class Error(Exception):
| 40 | 64 | 7 | 4 | 36 | ar4s/InkPy | inkpy_jinja/converter.py | Python | Error | Error | 13 | 14 | 13 | 13 | 160058a98b17b07e9da440ff05d449add408aac2 | bigcode/the-stack | train |
80be62eb513a70541cf05ab7 | train | class | class IdDoesNotExist(Error):
"""Document id does not exist"""
| class IdDoesNotExist(Error):
| """Document id does not exist"""
| import shutil
import zipfile
from jinja2.sandbox import SandboxedEnvironment
from inkpy_jinja.backends.external_script import ExternalRenderer
settings = {}
class Error(Exception):
pass
class FileDoesNotExist(Error):
"""File to file does not exist"""
class IdDoesNotExist(Error):
| 64 | 64 | 15 | 7 | 57 | ar4s/InkPy | inkpy_jinja/converter.py | Python | IdDoesNotExist | IdDoesNotExist | 21 | 22 | 21 | 21 | 5260514071cba9066a445f167baeec017ec48f26 | bigcode/the-stack | train |
6d652f6a95e281d914c4c4cb | train | class | class FileDoesNotExist(Error):
"""File to file does not exist"""
| class FileDoesNotExist(Error):
| """File to file does not exist"""
| import os
import shutil
import zipfile
from jinja2.sandbox import SandboxedEnvironment
from inkpy_jinja.backends.external_script import ExternalRenderer
settings = {}
class Error(Exception):
pass
class FileDoesNotExist(Error):
| 51 | 64 | 16 | 7 | 43 | ar4s/InkPy | inkpy_jinja/converter.py | Python | FileDoesNotExist | FileDoesNotExist | 17 | 18 | 17 | 17 | 4721661d105147933f43394674572b92b2cc78d9 | bigcode/the-stack | train |
8c2a512fa297f9471f531678 | train | class | class Converter(object):
"""
Fill special prepareted odt file with filled django style template
tags and convert this file to pdf file.
Conversion from odt to pdf file it's made with external command
run in subprocess.call.
:param source_file: The source odt file path.
:param output_path: T... | class Converter(object):
| """
Fill special prepareted odt file with filled django style template
tags and convert this file to pdf file.
Conversion from odt to pdf file it's made with external command
run in subprocess.call.
:param source_file: The source odt file path.
:param output_path: The destination pdf file p... | import os
import shutil
import zipfile
from jinja2.sandbox import SandboxedEnvironment
from inkpy_jinja.backends.external_script import ExternalRenderer
settings = {}
class Error(Exception):
pass
class FileDoesNotExist(Error):
"""File to file does not exist"""
class IdDoesNotExist(Error):
"""Docum... | 79 | 256 | 1,332 | 4 | 75 | ar4s/InkPy | inkpy_jinja/converter.py | Python | Converter | Converter | 25 | 182 | 25 | 25 | 6a50a0bce0a7535db62c661d6ac528ad3255bed8 | bigcode/the-stack | train |
b5d3165f19fd8b2ef404f311 | train | class | class LinkedList:
def __init__(self):
self.head = None
self.size = 0
# 0(n) linear running time complexity
def get_middle_node(self):
slow_pointer = fast_pointer = self.head
while fast_pointer.next_node and fast_pointer.next_node.next_node:
fast_pointer = fast_... | class LinkedList:
| def __init__(self):
self.head = None
self.size = 0
# 0(n) linear running time complexity
def get_middle_node(self):
slow_pointer = fast_pointer = self.head
while fast_pointer.next_node and fast_pointer.next_node.next_node:
fast_pointer = fast_pointer.next_node.... | class Node:
def __init__(self, data=None):
self.data = data
self.next_node = None
class LinkedList:
| 30 | 64 | 144 | 4 | 25 | clintbugsdev/binary-tree | LinkedList_MiddleNode.py | Python | LinkedList | LinkedList | 7 | 33 | 7 | 7 | eb793f8d6efff0da4e2d03800a0e7aa19c9dc932 | bigcode/the-stack | train |
c9d735356b61fa0d2363b4b5 | train | class | class Node:
def __init__(self, data=None):
self.data = data
self.next_node = None
| class Node:
| def __init__(self, data=None):
self.data = data
self.next_node = None
| class Node:
| 3 | 64 | 26 | 3 | 0 | clintbugsdev/binary-tree | LinkedList_MiddleNode.py | Python | Node | Node | 1 | 4 | 1 | 1 | e6a7fd9f29878afbbb10a5e86ec51286ee565036 | bigcode/the-stack | train |
812fe1d449ddd36dd9024af0 | train | function | @vectorize(["f4(f4, f4, f4)", "f8(f8, f8, f8)"], nopython=True, target="cpu")
def get_pdf_of_normal_distribution(x, mu, sigma):
"""Compute the probability of ``x`` under a normal distribution.
This implementation is faster than calling ``scipy.stats.norm.pdf``.
Parameters
----------
x : float or n... | @vectorize(["f4(f4, f4, f4)", "f8(f8, f8, f8)"], nopython=True, target="cpu")
def get_pdf_of_normal_distribution(x, mu, sigma):
| """Compute the probability of ``x`` under a normal distribution.
This implementation is faster than calling ``scipy.stats.norm.pdf``.
Parameters
----------
x : float or np.ndarray
The probability is calculated for this value.
mu : float or np.ndarray
Mean of the normal distribu... | ipped
sum_smooth_values += val_clipped
prob_choice[i] = total_values[idx, i] / sum_smooth_values
@vectorize(["f4(f4, f4, f4)", "f8(f8, f8, f8)"], nopython=True, target="cpu")
def get_pdf_of_normal_distribution(x, mu, sigma):
| 79 | 79 | 265 | 49 | 29 | tobiasraabe/respy_for_ma | respy/python/evaluate/evaluate_auxiliary.py | Python | get_pdf_of_normal_distribution | get_pdf_of_normal_distribution | 116 | 151 | 116 | 117 | ccb4f64ee7e8bf7c983098345648dd8bd63515c9 | bigcode/the-stack | train |
75f38ea1f79aada731579dd9 | train | function | @vectorize("f8(f8, f8, f8)", nopython=True, target="cpu")
def clip(x, minimum=None, maximum=None):
"""Clip (limit) input value.
Parameters
----------
x : float
Value to be clipped.
minimum : float
Lower limit.
maximum : float
Upper limit.
Returns
-------
flo... | @vectorize("f8(f8, f8, f8)", nopython=True, target="cpu")
def clip(x, minimum=None, maximum=None):
| """Clip (limit) input value.
Parameters
----------
x : float
Value to be clipped.
minimum : float
Lower limit.
maximum : float
Upper limit.
Returns
-------
float
Clipped value.
"""
if minimum is not None and x < minimum:
return minim... | ize
from respy.python.shared.shared_constants import HUGE_FLOAT
from respy.python.shared.shared_constants import INADMISSIBILITY_PENALTY
@vectorize("f8(f8, f8, f8)", nopython=True, target="cpu")
def clip(x, minimum=None, maximum=None):
| 64 | 64 | 129 | 34 | 29 | tobiasraabe/respy_for_ma | respy/python/evaluate/evaluate_auxiliary.py | Python | clip | clip | 10 | 34 | 10 | 11 | 2bfab881a0a9f28b5520641ee26021164acd07c7 | bigcode/the-stack | train |
cf09acbd1e6e5885e55b0352 | train | function | @guvectorize(
["f8, f8[:], i8, f8[:, :, :], i8, f8[:, :], f8[:, :], f8[:]"],
"(), (w), (), (i, p, n), (), (m, n) -> (p, n), (p)",
nopython=True,
target="parallel",
)
def create_draws_and_prob_wages(
wage_observed,
wages_systematic,
period,
periods_draws_prob,
choice,
sc,
draw... | @guvectorize(
["f8, f8[:], i8, f8[:, :, :], i8, f8[:, :], f8[:, :], f8[:]"],
"(), (w), (), (i, p, n), (), (m, n) -> (p, n), (p)",
nopython=True,
target="parallel",
)
def create_draws_and_prob_wages(
wage_observed,
wages_systematic,
period,
periods_draws_prob,
choice,
sc,
draw... | """Create draws to simulate maximum utilities and create probabilities of wages.
Draws are taken from a general set of unique shocks for each period. The shocks are
adjusted in case the wage of an agent is available as well as the probability of the
wage.
Parameters
----------
wage_observe... | -------
probability : float
Probability of ``x`` under a normal distribution with mean ``mu`` and standard
deviation ``sigma``.
Example
-------
>>> result = get_pdf_of_normal_distribution(0)
>>> result
0.3989422804014327
>>> from scipy.stats import norm
>>> assert re... | 256 | 256 | 1,032 | 124 | 131 | tobiasraabe/respy_for_ma | respy/python/evaluate/evaluate_auxiliary.py | Python | create_draws_and_prob_wages | create_draws_and_prob_wages | 154 | 263 | 154 | 169 | 27dfb814384b7c5955d60bafdb17db6ca888fff3 | bigcode/the-stack | train |
05bf9c564952d8a841df04a9 | train | function | @guvectorize(
["f8[:], f8[:], f8[:], f8[:, :], f8, b1, i8, f8, f8[:]"],
"(m), (n), (n), (p, n), (), (), (), () -> (p)",
nopython=True,
target="parallel",
)
def simulate_probability_of_agents_observed_choice(
wages, rewards_systematic, emaxs, draws, delta, max_education, idx, tau, prob_choice
):
... | @guvectorize(
["f8[:], f8[:], f8[:], f8[:, :], f8, b1, i8, f8, f8[:]"],
"(m), (n), (n), (p, n), (), (), (), () -> (p)",
nopython=True,
target="parallel",
)
def simulate_probability_of_agents_observed_choice(
wages, rewards_systematic, emaxs, draws, delta, max_education, idx, tau, prob_choice
):
| """Simulate the probability of observing the agent's choice.
The probability is simulated by iterating over a distribution of unobservables.
First, the utility of each choice is computed. Then, the probability of observing
the choice of the agent given the maximum utility from all choices is computed.
... | clipped.
minimum : float
Lower limit.
maximum : float
Upper limit.
Returns
-------
float
Clipped value.
"""
if minimum is not None and x < minimum:
return minimum
elif maximum is not None and x > maximum:
return maximum
else:
return ... | 183 | 183 | 610 | 111 | 71 | tobiasraabe/respy_for_ma | respy/python/evaluate/evaluate_auxiliary.py | Python | simulate_probability_of_agents_observed_choice | simulate_probability_of_agents_observed_choice | 37 | 113 | 37 | 45 | 2b0fb27f27ae52f7ee6d06c91841065bbf314da2 | bigcode/the-stack | train |
a4a0c91e7b13641f84b7bf5b | train | class | class Metric(ABC):
def __init__(
self,
data_source_scan: DataSourceScan,
partition: Partition | None,
column: Column | None,
name: str,
check: Check,
# schedule name, data source name, table name, partition name, column name and name are
# already adde... | class Metric(ABC):
| def __init__(
self,
data_source_scan: DataSourceScan,
partition: Partition | None,
column: Column | None,
name: str,
check: Check,
# schedule name, data source name, table name, partition name, column name and name are
# already added to the identity. ... | from __future__ import annotations
from abc import ABC
from soda.common.undefined_instance import undefined
from soda.execution.identity import Identity
from soda.execution.query import Query
from soda.sampler.storage_ref import StorageRef
class Metric(ABC):
| 49 | 177 | 592 | 5 | 43 | duyet/soda-core | soda/core/soda/execution/metric.py | Python | Metric | Metric | 11 | 84 | 11 | 11 | a84b227157a43a6d94d654a3ea4536684f923af4 | bigcode/the-stack | train |
be21553f25a3b95d8a258d12 | train | class | class BaseGCAdapter(BaseAdapter):
"""
Base class for adapters that use a Generator and Classifier.
"""
def get_key_enforcer(self) -> KeyEnforcer:
return KeyEnforcer(
models=["G", "C"],
optimizers=["G", "C"],
)
| class BaseGCAdapter(BaseAdapter):
| """
Base class for adapters that use a Generator and Classifier.
"""
def get_key_enforcer(self) -> KeyEnforcer:
return KeyEnforcer(
models=["G", "C"],
optimizers=["G", "C"],
)
| use a Generator, Classifier, and Discriminator.
"""
def get_key_enforcer(self) -> KeyEnforcer:
return KeyEnforcer(
models=["G", "C", "D"],
optimizers=["G", "C", "D"],
)
class BaseGCAdapter(BaseAdapter):
| 64 | 64 | 62 | 7 | 57 | KevinMusgrave/pytorch-adapt | src/pytorch_adapt/adapters/base_adapter.py | Python | BaseGCAdapter | BaseGCAdapter | 183 | 192 | 183 | 183 | 9269d850b60d25bfe2418d9237fbfbfcd7ce01db | bigcode/the-stack | train |
b910e583546ca045183b8a5c | train | class | class BaseGCDAdapter(BaseAdapter):
"""
Base class for adapters that use a Generator, Classifier, and Discriminator.
"""
def get_key_enforcer(self) -> KeyEnforcer:
return KeyEnforcer(
models=["G", "C", "D"],
optimizers=["G", "C", "D"],
)
| class BaseGCDAdapter(BaseAdapter):
| """
Base class for adapters that use a Generator, Classifier, and Discriminator.
"""
def get_key_enforcer(self) -> KeyEnforcer:
return KeyEnforcer(
models=["G", "C", "D"],
optimizers=["G", "C", "D"],
)
| optimizers\n{self.optimizers}")
c_f.LOGGER.debug(f"lr_schedulers\n{self.lr_schedulers}")
c_f.LOGGER.debug(f"misc\n{self.misc}")
c_f.LOGGER.debug(f"hook\n{self.hook}")
class BaseGCDAdapter(BaseAdapter):
| 63 | 64 | 73 | 8 | 55 | KevinMusgrave/pytorch-adapt | src/pytorch_adapt/adapters/base_adapter.py | Python | BaseGCDAdapter | BaseGCDAdapter | 171 | 180 | 171 | 171 | 48353c1b719a70d9297d68244005d871be02ea01 | bigcode/the-stack | train |
a4f9ac9be76893ee1c56241d | train | class | class BaseAdapter(ABC):
"""
Parent class of all adapters.
"""
def __init__(
self,
models: Models = None,
optimizers: Optimizers = None,
lr_schedulers: LRSchedulers = None,
misc: Misc = None,
default_containers: MultipleContainers = None,
key_enfor... | class BaseAdapter(ABC):
| """
Parent class of all adapters.
"""
def __init__(
self,
models: Models = None,
optimizers: Optimizers = None,
lr_schedulers: LRSchedulers = None,
misc: Misc = None,
default_containers: MultipleContainers = None,
key_enforcer: KeyEnforcer = None,... | from abc import ABC, abstractmethod
from typing import Any, Dict, Tuple
import torch
from ..containers import (
KeyEnforcer,
LRSchedulers,
Misc,
Models,
MultipleContainers,
Optimizers,
)
from ..inference import default_fn
from ..utils import common_functions as c_f
from .utils import default_o... | 85 | 256 | 1,257 | 6 | 78 | KevinMusgrave/pytorch-adapt | src/pytorch_adapt/adapters/base_adapter.py | Python | BaseAdapter | BaseAdapter | 19 | 168 | 19 | 19 | 733ac5e9b74d4ca23fa9ecce9b72ffafb4f44b85 | bigcode/the-stack | train |
8586eae61eb6a42409b61157 | train | function | def load_Sample_Bundle(path):
path += ".sb"
with open(path, 'rb') as input:
sb = pickle.load(input)
assert isinstance(sb, sample_bundle.Sample_Bundle)
return sb
| def load_Sample_Bundle(path):
| path += ".sb"
with open(path, 'rb') as input:
sb = pickle.load(input)
assert isinstance(sb, sample_bundle.Sample_Bundle)
return sb
| def save_object(self, filename):
filename += ".sb"
with open(filename, 'wb') as output: # Overwrites any existing file.
pickle.dump(self, output, pickle.HIGHEST_PROTOCOL)
print(filename + " saved successfully")
return
def load_Sample_Bundle(path):
| 64 | 64 | 47 | 8 | 55 | thgnaedi/DeepRain | Data/sample_bundle.py | Python | load_Sample_Bundle | load_Sample_Bundle | 181 | 186 | 181 | 181 | ca6906157002a9756753c80afea7eac3e4d1fc63 | bigcode/the-stack | train |
fac2e90bff27b7353bb7f05e | train | class | class Sample_Bundle():
def __init__(self, subimg, resizeshape, all_samples, details=""):
self.subimg = subimg # Subimg selection ((Y,X), (width, height))
self.resizeshape = resizeshape # Tuple or int == outputshape
self.all_samples = all_samples # list of Tuples [(data0, label0), (data1... | class Sample_Bundle():
| def __init__(self, subimg, resizeshape, all_samples, details=""):
self.subimg = subimg # Subimg selection ((Y,X), (width, height))
self.resizeshape = resizeshape # Tuple or int == outputshape
self.all_samples = all_samples # list of Tuples [(data0, label0), (data1, label1), ...]
... | import numpy as np
import pickle
import sys
sys.path.append("../Data")
import sample_bundle
class Sample_Bundle():
| 26 | 256 | 1,529 | 5 | 20 | thgnaedi/DeepRain | Data/sample_bundle.py | Python | Sample_Bundle | Sample_Bundle | 8 | 178 | 8 | 8 | 0adb48ee5ca60536e7275bdfd0554f65128587d2 | bigcode/the-stack | train |
f400179c0454115383c44e30 | train | class | class TestBase(APITestCase):
def setUp(self):
self.client = APIClient()
self.url = reverse("authentication:login")
self.register_url = reverse("authentication:register")
self.acc_verify = AccountVerification
self.known_key = self.acc_verify().generate_confirmation_token('tes... | class TestBase(APITestCase):
| def setUp(self):
self.client = APIClient()
self.url = reverse("authentication:login")
self.register_url = reverse("authentication:register")
self.acc_verify = AccountVerification
self.known_key = self.acc_verify().generate_confirmation_token('test2@testuser.com')
self... | from rest_framework.test import APITestCase, APIClient
from django.urls import reverse
from ..models import User
import json, os
from ..backends import AccountVerification
from itsdangerous import URLSafeTimedSerializer
class TestBase(APITestCase):
| 54 | 256 | 1,526 | 7 | 46 | andela/ah-backend-realers | authors/apps/authentication/tests/test_base.py | Python | TestBase | TestBase | 9 | 213 | 9 | 10 | 7d2fc4b9a24e453e71ebb90d98855b2ad9de4b17 | bigcode/the-stack | train |
5b252aebe6a9cbf1395ea7af | train | function | def find_optimal_fontsize(img_fraction, fontpath, text, width):
breakpoint = img_fraction * width
jumpsize = 2
fontsize = 16
tw = 0
th = 0
font = ImageFont.truetype(fontpath, fontsize)
while True:
tw, th = font.getsize(text)
if tw < breakpoint:
fontsize += ju... | def find_optimal_fontsize(img_fraction, fontpath, text, width):
| breakpoint = img_fraction * width
jumpsize = 2
fontsize = 16
tw = 0
th = 0
font = ImageFont.truetype(fontpath, fontsize)
while True:
tw, th = font.getsize(text)
if tw < breakpoint:
fontsize += jumpsize
else:
jumpsize = jumpsize // 2
... | ")
exportpath= join(mainpath,"export")
exportednames = join(exportpath,"exportednames.txt")
# Algorithm https://newbedev.com/pil-how-to-scale-text-size-in-relation-to-the-size-of-the-image
def find_optimal_fontsize(img_fraction, fontpath, text, width):
| 64 | 64 | 140 | 16 | 47 | slawyn/image-tagger | pytag/pytag.py | Python | find_optimal_fontsize | find_optimal_fontsize | 21 | 40 | 21 | 21 | 24c9960763c859af908b3673cf0ea1770b0adf95 | bigcode/the-stack | train |
adf39aeb3cb99798b6091f96 | train | function | def add_text(pil_img, text, color):
width, height = pil_img.size
fontpath = "arial.ttf"
fontsize, tw, th = find_optimal_fontsize(1, fontpath, text, width)
font = ImageFont.truetype(fontpath, fontsize)
# Calculate margin
new_width = max(width,tw)
new_height = height + th
# ... | def add_text(pil_img, text, color):
| width, height = pil_img.size
fontpath = "arial.ttf"
fontsize, tw, th = find_optimal_fontsize(1, fontpath, text, width)
font = ImageFont.truetype(fontpath, fontsize)
# Calculate margin
new_width = max(width,tw)
new_height = height + th
# Create margin and paste the image to... | if tw < breakpoint:
fontsize += jumpsize
else:
jumpsize = jumpsize // 2
fontsize -= jumpsize
font = ImageFont.truetype(fontpath, fontsize)
if jumpsize <= 1:
break
return (fontsize, tw, th)
def add_text(pil_img, text, color):
| 75 | 75 | 250 | 11 | 64 | slawyn/image-tagger | pytag/pytag.py | Python | add_text | add_text | 42 | 65 | 42 | 42 | 1c081131016ab8e19b82daf1b6e906f355bb5c37 | bigcode/the-stack | train |
dffa84b367678aac57248222 | train | function | @register(outgoing=True, pattern="^.all$")
async def all(event):
if event.fwd_from:
return
await event.delete()
mentions = "@all"
chat = await event.get_input_chat()
async for x in bot.iter_participants(chat):
mentions += f"[\u2063](tg://user?id={x.id})"
await bot.send_message(ch... | @register(outgoing=True, pattern="^.all$")
async def all(event):
| if event.fwd_from:
return
await event.delete()
mentions = "@all"
chat = await event.get_input_chat()
async for x in bot.iter_participants(chat):
mentions += f"[\u2063](tg://user?id={x.id})"
await bot.send_message(chat, mentions, reply_to=event.message.reply_to_msg_id)
| at http://mozilla.org/MPL/2.0/.
"""A Plugin to tagall in the chat for @UniBorg and cmd is `.all`"""
from userbot import CMD_HELP, bot
from userbot.events import register
@register(outgoing=True, pattern="^.all$")
async def all(event):
| 64 | 64 | 95 | 16 | 47 | SECONTRE/XBot-Remix | userbot/modules/tag_all.py | Python | all | all | 11 | 20 | 11 | 12 | a127eb0c73200956f6781710d125f94147a434ff | bigcode/the-stack | train |
275a4159c70cd0b624edc47e | train | function | def on_focusin(event):
global entry_search
if entry_search.get() == 'Search':
entry_search.delete(0, "end")
entry_search.insert(0, '')
entry_search.config(fg = 'black')
| def on_focusin(event):
| global entry_search
if entry_search.get() == 'Search':
entry_search.delete(0, "end")
entry_search.insert(0, '')
entry_search.config(fg = 'black')
| 11, 'Dec':12}
month = month_cb.get()
month = months_dict[month]
def year_changed(event):
global year
year = year_cb.get()
def refresh():
for i in table.get_children():
table.delete(i)
retrieve_data()
def on_focusin(event):
| 64 | 64 | 51 | 6 | 58 | HariChandana27/Employee-Payroll-Management-System | comp_payroll.py | Python | on_focusin | on_focusin | 37 | 42 | 37 | 37 | a0e49a18ad2090d988e4f68864553576d6fa6b6e | bigcode/the-stack | train |
94fb43e75c4e1727e93c537e | train | function | def create_connection():
global conn,c
conn = oracle.connect(user="payroll", password="password",dsn="localhost/xepdb1")
c = conn.cursor()
| def create_connection():
| global conn,c
conn = oracle.connect(user="payroll", password="password",dsn="localhost/xepdb1")
c = conn.cursor()
| tk
from tkinter import ttk
import tkinter.font as tkfont
from functools import partial
import emp_payroll as ep
import cx_Oracle as oracle
import os
#oracle.init_oracle_client(lib_dir=os.environ.get("HOME")+"/Downloads/instantclient_19_8")
def create_connection():
| 64 | 64 | 37 | 4 | 60 | HariChandana27/Employee-Payroll-Management-System | comp_payroll.py | Python | create_connection | create_connection | 12 | 15 | 12 | 12 | bcf29771f2a0af5e5dd4259b91ee4d3a39f1d3af | bigcode/the-stack | train |
50b2ebbd3c9ff1962b341cca | train | function | def month_changed(event):
global month
months_dict = {'Jan':1, 'Feb':2, 'Mar':3, 'Apr':4, 'May':5, 'Jun':6, 'Jul':7, 'Aug':8, 'Sep':9, 'Oct':10, 'Nov':11, 'Dec':12}
month = month_cb.get()
month = months_dict[month]
| def month_changed(event):
| global month
months_dict = {'Jan':1, 'Feb':2, 'Mar':3, 'Apr':4, 'May':5, 'Jun':6, 'Jul':7, 'Aug':8, 'Sep':9, 'Oct':10, 'Nov':11, 'Dec':12}
month = month_cb.get()
month = months_dict[month]
| _19_8")
def create_connection():
global conn,c
conn = oracle.connect(user="payroll", password="password",dsn="localhost/xepdb1")
c = conn.cursor()
def close_connection():
global conn,c
c.close()
conn.close()
def month_changed(event):
| 64 | 64 | 88 | 5 | 59 | HariChandana27/Employee-Payroll-Management-System | comp_payroll.py | Python | month_changed | month_changed | 22 | 26 | 22 | 22 | 8c2e0bc48a9c2ed615c8324352cc4d5ad01aef05 | bigcode/the-stack | train |
b77d91fe27b7b6c067764853 | train | function | def search(event):
search_word = entry_search.get()
if search_word=='':
for record in table.get_children():
table.delete(record)
retrieve_data()
else:
dept_names = []
for i in range(len(result_data)):
if(search_word.lower() in result_data[i][1].lower(... | def search(event):
| search_word = entry_search.get()
if search_word=='':
for record in table.get_children():
table.delete(record)
retrieve_data()
else:
dept_names = []
for i in range(len(result_data)):
if(search_word.lower() in result_data[i][1].lower()):
... |
entry_search.insert(0, '')
entry_search.config(fg = 'black')
def on_focusout(event):
global entry_search
if entry_search.get() == '':
entry_search.insert(0, 'Search')
entry_search.config(fg = 'grey')
def search(event):
| 64 | 64 | 149 | 5 | 59 | HariChandana27/Employee-Payroll-Management-System | comp_payroll.py | Python | search | search | 50 | 64 | 50 | 50 | 95349b0faa4ecc4236baa6cc6270954a1fc56491 | bigcode/the-stack | train |
55049589fa2408c5332f4fac | train | function | def refresh():
for i in table.get_children():
table.delete(i)
retrieve_data()
| def refresh():
| for i in table.get_children():
table.delete(i)
retrieve_data()
| 'Jul':7, 'Aug':8, 'Sep':9, 'Oct':10, 'Nov':11, 'Dec':12}
month = month_cb.get()
month = months_dict[month]
def year_changed(event):
global year
year = year_cb.get()
def refresh():
| 64 | 64 | 20 | 3 | 61 | HariChandana27/Employee-Payroll-Management-System | comp_payroll.py | Python | refresh | refresh | 32 | 35 | 32 | 32 | 9382c7a76beb396443a50ad5e5cf051e33608430 | bigcode/the-stack | train |
c6be84b4862af623721c8db9 | train | function | def emp_payroll(event):
global table, month, year
selected_row = table.focus()
selected_row_values = table.item(selected_row,'values')
ep.employee_payroll(selected_row_values,month,year)
| def emp_payroll(event):
| global table, month, year
selected_row = table.focus()
selected_row_values = table.item(selected_row,'values')
ep.employee_payroll(selected_row_values,month,year)
| in dept_names:
table.insert(parent='', index='end', iid=i, text="Label", values=(result_data[i][0],result_data[i][1],result_data[i][2],result_data[i][3],result_data[i][4],result_data[i][5]))
def emp_payroll(event):
| 64 | 64 | 46 | 6 | 58 | HariChandana27/Employee-Payroll-Management-System | comp_payroll.py | Python | emp_payroll | emp_payroll | 66 | 70 | 66 | 66 | 6c02da4024318ee11928d07692a2f4fb9e3868de | bigcode/the-stack | train |
fb9454fef9ac848840f8d1e9 | train | function | def close_connection():
global conn,c
c.close()
conn.close()
| def close_connection():
| global conn,c
c.close()
conn.close()
| oracle.init_oracle_client(lib_dir=os.environ.get("HOME")+"/Downloads/instantclient_19_8")
def create_connection():
global conn,c
conn = oracle.connect(user="payroll", password="password",dsn="localhost/xepdb1")
c = conn.cursor()
def close_connection():
| 64 | 64 | 17 | 4 | 60 | HariChandana27/Employee-Payroll-Management-System | comp_payroll.py | Python | close_connection | close_connection | 17 | 20 | 17 | 17 | b6f784f56831c6418f504faf0fe17b54ccdcfc6c | bigcode/the-stack | train |
9658ddada568e319d1c4870c | train | function | def on_focusout(event):
global entry_search
if entry_search.get() == '':
entry_search.insert(0, 'Search')
entry_search.config(fg = 'grey')
| def on_focusout(event):
| global entry_search
if entry_search.get() == '':
entry_search.insert(0, 'Search')
entry_search.config(fg = 'grey')
| .delete(i)
retrieve_data()
def on_focusin(event):
global entry_search
if entry_search.get() == 'Search':
entry_search.delete(0, "end")
entry_search.insert(0, '')
entry_search.config(fg = 'black')
def on_focusout(event):
| 64 | 64 | 39 | 6 | 58 | HariChandana27/Employee-Payroll-Management-System | comp_payroll.py | Python | on_focusout | on_focusout | 44 | 48 | 44 | 44 | 35eb1dc351b3761a2402bf437cf76402e098a98f | bigcode/the-stack | train |
8665ecd7602147076f6ec5b9 | train | function | def retrieve_data():
global c,result_data,lbl_total
create_connection()
sql = (''' SELECT
emp_id,
name,
salary,
allowances,
deductions,
(salary + allowances - dedu... | def retrieve_data():
| global c,result_data,lbl_total
create_connection()
sql = (''' SELECT
emp_id,
name,
salary,
allowances,
deductions,
(salary + allowances - deductions) AS net_salary... | (fg = 'grey')
def search(event):
search_word = entry_search.get()
if search_word=='':
for record in table.get_children():
table.delete(record)
retrieve_data()
else:
dept_names = []
for i in range(len(result_data)):
if(search_word.lower() in result_da... | 205 | 205 | 685 | 4 | 201 | HariChandana27/Employee-Payroll-Management-System | comp_payroll.py | Python | retrieve_data | retrieve_data | 72 | 169 | 72 | 72 | 79b79745401de44d4d7532b4ca71416466c3969c | bigcode/the-stack | train |
1480d49b0197495a0c7d0b94 | train | function | def create_main_window():
global month_cb,year_cb,main,lbl_total,month,year
main = tk.Tk()
main.title("Payroll | Employee Payroll Management System")
heading = tkfont.Font(family="Times New Roman", size=25,weight='bold')
text = tkfont.Font(family="Times New Roman", size=16)
text2 = tkfont.Font(f... | def create_main_window():
| global month_cb,year_cb,main,lbl_total,month,year
main = tk.Tk()
main.title("Payroll | Employee Payroll Management System")
heading = tkfont.Font(family="Times New Roman", size=25,weight='bold')
text = tkfont.Font(family="Times New Roman", size=16)
text2 = tkfont.Font(family="Times New Roman", s... | _search.config(fg = 'grey')
entry_search.pack(anchor='ne')
global table
table = ttk.Treeview(fr_table)
table['columns'] = columns
for i in columns:
table.heading(i,text=i,anchor='center')
table.column("#0",width=0,stretch='no')
for i in range(0,len(columns)):
table.column(col... | 193 | 194 | 647 | 5 | 188 | HariChandana27/Employee-Payroll-Management-System | comp_payroll.py | Python | create_main_window | create_main_window | 199 | 238 | 199 | 199 | 4f86fd0aa4d5537d072660c20ee6498e06e54292 | bigcode/the-stack | train |
5db0dee8e3468f77ec7c324c | train | function | def create_table_GUI(fr_table,text,columns,width,double_click):
global entry_search
entry_search = tk.Entry(fr_table,relief="groove")
entry_search.insert(0, 'Search')
entry_search.bind('<FocusIn>', on_focusin)
entry_search.bind('<FocusOut>', on_focusout)
entry_search.bind('<KeyRelease>',search)
... | def create_table_GUI(fr_table,text,columns,width,double_click):
| global entry_search
entry_search = tk.Entry(fr_table,relief="groove")
entry_search.insert(0, 'Search')
entry_search.bind('<FocusIn>', on_focusin)
entry_search.bind('<FocusOut>', on_focusout)
entry_search.bind('<KeyRelease>',search)
entry_search.config(fg = 'grey')
entry_search.pack(ancho... | ],result_data[i][5]))
total = 0
for i in range(len(result_data)):
total = total+result_data[i][5]
if(result_data==[]):
lbl_total.config(text = '0')
else:
lbl_total.config(text = round(total,2))
close_connection()
def create_table_GUI(fr_table,text,columns,width,double_click):... | 80 | 80 | 267 | 13 | 67 | HariChandana27/Employee-Payroll-Management-System | comp_payroll.py | Python | create_table_GUI | create_table_GUI | 171 | 197 | 171 | 171 | 38956e1f705260e37cd8f4f79eeb7e16cea41226 | bigcode/the-stack | train |
f1d9b5da47f2c9ac8a6c4547 | train | function | def year_changed(event):
global year
year = year_cb.get()
| def year_changed(event):
| global year
year = year_cb.get()
| Apr':4, 'May':5, 'Jun':6, 'Jul':7, 'Aug':8, 'Sep':9, 'Oct':10, 'Nov':11, 'Dec':12}
month = month_cb.get()
month = months_dict[month]
def year_changed(event):
| 64 | 64 | 16 | 5 | 59 | HariChandana27/Employee-Payroll-Management-System | comp_payroll.py | Python | year_changed | year_changed | 28 | 30 | 28 | 28 | ba1f8e83b83c86431ffb3c4f478ace86a79a9599 | bigcode/the-stack | train |
36d97dd04799fd14a0f99b2e | train | function | def Rand(start, end, num):
res = []
for j in range(num):
res.append(random.randint(start, end))
return res
| def Rand(start, end, num):
| res = []
for j in range(num):
res.append(random.randint(start, end))
return res
| :
movieNameList[line[0]]=line[1]
#Generate movieGenreIdDictionary
movieGenreList = {}
for line in movieData:
movieGenreList[line[0]]=line[2]
#Function to get the list of 20 random numbers
def Rand(start, end, num):
| 64 | 64 | 36 | 9 | 54 | VishalSain773/MovieRecommendSystem | mrsMain.py | Python | Rand | Rand | 22 | 28 | 22 | 22 | b01e51d68963b0fff240ad07b6e7ec0cc343d26b | bigcode/the-stack | train |
cdf249ffd3977850f7be10a1 | train | class | class GrantPermissionToServiceAccountUI(metaclass=ABCMeta):
@abstractmethod
def grant_permission_to_service_account_failed_invalid_argument(
self, permission, argument, service, message
):
# type: (str, str, str, str) -> None
pass
@abstractmethod
def grant_permission_to_serv... | class GrantPermissionToServiceAccountUI(metaclass=ABCMeta):
@abstractmethod
| def grant_permission_to_service_account_failed_invalid_argument(
self, permission, argument, service, message
):
# type: (str, str, str, str) -> None
pass
@abstractmethod
def grant_permission_to_service_account_failed_permission_denied(
self, permission, argument, servic... | .permission_grant import GroupPermissionGrant
from grouper.usecases.interfaces import (
GroupInterface,
PermissionInterface,
ServiceAccountInterface,
TransactionInterface,
UserInterface,
)
from typing import List
class GrantPermissionToServiceAccountUI(metaclass=ABCMe... | 65 | 65 | 219 | 19 | 45 | ph0enix49/merou | grouper/usecases/grant_permission_to_service_account.py | Python | GrantPermissionToServiceAccountUI | GrantPermissionToServiceAccountUI | 19 | 47 | 19 | 20 | f5779cfead221868568e632578e4ba07fa4906b2 | bigcode/the-stack | train |
35406b4c5d2dbfd6ba8cab31 | train | class | class GrantPermissionToServiceAccount:
def __init__(
self,
actor, # type: str
ui, # type: GrantPermissionToServiceAccountUI
permission_service, # type: PermissionInterface
service_account_service, # type: ServiceAccountInterface
user_service, # type: UserInterfac... | class GrantPermissionToServiceAccount:
| def __init__(
self,
actor, # type: str
ui, # type: GrantPermissionToServiceAccountUI
permission_service, # type: PermissionInterface
service_account_service, # type: ServiceAccountInterface
user_service, # type: UserInterface
group_service, # type: Group... | (
GroupInterface,
PermissionInterface,
ServiceAccountInterface,
TransactionInterface,
UserInterface,
)
from typing import List
class GrantPermissionToServiceAccountUI(metaclass=ABCMeta):
@abstractmethod
def grant_permission_to_service_account_failed_invalid_arg... | 256 | 256 | 903 | 7 | 248 | ph0enix49/merou | grouper/usecases/grant_permission_to_service_account.py | Python | GrantPermissionToServiceAccount | GrantPermissionToServiceAccount | 50 | 155 | 50 | 50 | 1a4c2d02df76024b5fa63c6ea290787ceeb5df3b | bigcode/the-stack | train |
0ff16addf46b0dabee4b8be5 | train | function | def url_exists(text):
for url in [text, "https://" + text, "http://" + text]:
try:
code = urlopen(url).code
if code / 100 >= 4:
pass
elif code == 200:
return url.replace("https://", "").replace("http://", "")
except URLError:
... | def url_exists(text):
| for url in [text, "https://" + text, "http://" + text]:
try:
code = urlopen(url).code
if code / 100 >= 4:
pass
elif code == 200:
return url.replace("https://", "").replace("http://", "")
except URLError:
pass
return ... | |zw)\b/?(?!@)))"""
def get_links(message):
result = []
for i in re.findall(URL_REGEX, message):
if not urlparse.urlparse(i).scheme:
i = "http://"+i
result.append(i)
return result
def url_exists(text):
| 64 | 64 | 83 | 5 | 58 | K00sKlust/K00sTwitchBot | essentials/FindUrls.py | Python | url_exists | url_exists | 38 | 48 | 38 | 38 | d9a4e69ed08547f5d8b11b5db395ae55da91963e | bigcode/the-stack | train |
4206330d209d219699c51b7c | train | function | def get_links(message):
result = []
for i in re.findall(URL_REGEX, message):
if not urlparse.urlparse(i).scheme:
i = "http://"+i
result.append(i)
return result
| def get_links(message):
| result = []
for i in re.findall(URL_REGEX, message):
if not urlparse.urlparse(i).scheme:
i = "http://"+i
result.append(i)
return result
| tr|tt|tv|tw|tz|ua|ug|uk|
us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)\b/?(?!@)))"""
def get_links(message):
| 64 | 64 | 49 | 5 | 59 | K00sKlust/K00sTwitchBot | essentials/FindUrls.py | Python | get_links | get_links | 29 | 35 | 29 | 29 | 2e66b62139107109aa320e7dba30cc16657ae58b | bigcode/the-stack | train |
0fe4923ce8fa8efee5dce81f | train | function | def spikey_thumbnail(data, context):
bucket = spikey_client.get_bucket(data['bucket'])
blob = bucket.get_blob(data['name'])
spikey_imagedata = blob.download_as_string()
spikey_newimage = Image(blob=spikey_imagedata)
spikey_newimage.sample(200,200)
bucket = spikey_client.get_bucket(THUMBNAIL_BUCK... | def spikey_thumbnail(data, context):
| bucket = spikey_client.get_bucket(data['bucket'])
blob = bucket.get_blob(data['name'])
spikey_imagedata = blob.download_as_string()
spikey_newimage = Image(blob=spikey_imagedata)
spikey_newimage.sample(200,200)
bucket = spikey_client.get_bucket(THUMBNAIL_BUCKET)
newblob = bucket.blob('thumbn... | from wand.image import Image
from google.cloud import storage
spikey_client = storage.Client()
THUMBNAIL_BUCKET = 'spikey-developers'
def spikey_thumbnail(data, context):
| 40 | 64 | 111 | 8 | 32 | Katniss394/Google-Cloud-Fucntions-Samples | Background_function.py | Python | spikey_thumbnail | spikey_thumbnail | 7 | 15 | 7 | 7 | e84db06984a86d175b263f88fb3ef5cfecbd2f7b | bigcode/the-stack | train |
d270444b3f7dd96f83d4f7b5 | train | class | class VpnSitesConfigurationOperations:
"""VpnSitesConfigurationOperations async operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this opera... | class VpnSitesConfigurationOperations:
| """VpnSitesConfigurationOperations async operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.mg... | # coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... | 227 | 256 | 1,357 | 7 | 220 | LianwMS/azure-sdk-for-python | sdk/network/azure-mgmt-network/azure/mgmt/network/v2019_08_01/aio/operations_async/_vpn_sites_configuration_operations_async.py | Python | VpnSitesConfigurationOperations | VpnSitesConfigurationOperations | 23 | 154 | 23 | 23 | 42c3acb5580ef9357efdbe9519c15d817b1a8c91 | bigcode/the-stack | train |
add709ea733adc689c8969a0 | train | class | class TempFileManager():
@staticmethod
def namedFileDescriptor(
mode='w+b', buffering=-1, encoding=None,
newline=None, suffix=None, prefix=None,
dir=None, delete=True
):
return tempfile.NamedTemporaryFile(
mode=mode, buffering=buffering, encoding=encoding,
... | class TempFileManager():
@staticmethod
| def namedFileDescriptor(
mode='w+b', buffering=-1, encoding=None,
newline=None, suffix=None, prefix=None,
dir=None, delete=True
):
return tempfile.NamedTemporaryFile(
mode=mode, buffering=buffering, encoding=encoding,
newline=newline, suffix=suffix, prefix... | import tempfile
from pathlib import Path
class TempFileManager():
@staticmethod
| 17 | 64 | 128 | 9 | 7 | leoprover/tptp | tptp/utils/tempFile.py | Python | TempFileManager | TempFileManager | 5 | 23 | 5 | 7 | d5cc853f3fbfc96c8a93ca9d741395f38c76f8f6 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.