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
6230ae8a396bf0056a6864ff
train
class
class SingleDiscreteDomain(SingleDomain): pass
class SingleDiscreteDomain(SingleDomain):
pass
, self.set.inf, self.set.sup), **kwargs) else: return Sum(expr * self.pdf(var), (var, self.set.inf, self.set.sup), **kwargs) def __call__(self, *args): return self.pdf(*args) class SingleDiscreteDomain(SingleDomain):
64
64
11
8
56
atul107/sympy
sympy/stats/drv.py
Python
SingleDiscreteDomain
SingleDiscreteDomain
106
107
106
106
1f1243488fa7c74a5373b999d96a15ba3edeeca8
bigcode/the-stack
train
508835c58b42dbcbf492a199
train
function
@shared_task def report_submitted_qualifier(qualifier_id): from .models import Qualifier qualifier = Qualifier.objects.get(id=qualifier_id) event = qualifier.event discord_user = qualifier.user.discord_user # Send message to channel channel_id = env("DISCORD_QUALIFIER_REPORTING_CHANNEL_ID") ...
@shared_task def report_submitted_qualifier(qualifier_id):
from .models import Qualifier qualifier = Qualifier.objects.get(id=qualifier_id) event = qualifier.event discord_user = qualifier.user.discord_user # Send message to channel channel_id = env("DISCORD_QUALIFIER_REPORTING_CHANNEL_ID") if channel_id: channel_embed = MessageEmbed() ...
Go watch live on {twitch_url}".format( discord_user=discord_user.user_tag, event=event.name, twitch_url=twitch_user.twitch_url, ) discord.send_channel_message(channel_id, message) @shared_task def report_submitted_qualifier(qualifier_id):
64
64
165
16
48
Madv0x/classic-tetris-project
classic_tetris_project/tasks.py
Python
report_submitted_qualifier
report_submitted_qualifier
33
50
33
34
072eab9f45e1b05d29cb5f647e14cec341590181
bigcode/the-stack
train
eeda3e043dd3e26635e3870d
train
function
@shared_task def report_reviewed_qualifier(qualifier_id): from .models import Qualifier qualifier = Qualifier.objects.get(id=qualifier_id) event = qualifier.event discord_user = qualifier.user.discord_user # Send message to user user_embed = MessageEmbed() user_embed.description = render_to...
@shared_task def report_reviewed_qualifier(qualifier_id):
from .models import Qualifier qualifier = Qualifier.objects.get(id=qualifier_id) event = qualifier.event discord_user = qualifier.user.discord_user # Send message to user user_embed = MessageEmbed() user_embed.description = render_to_string("discord/qualifier_reviewed.txt", { "event...
": event.get_absolute_url(True), "qualifier": qualifier, }).replace("\\\n", "").strip() channel_embed.color = QUALIFIER_COLOR_APPROVED discord.send_channel_message(channel_id, embed=channel_embed) @shared_task def report_reviewed_qualifier(qualifier_id):
64
64
210
16
48
Madv0x/classic-tetris-project
classic_tetris_project/tasks.py
Python
report_reviewed_qualifier
report_reviewed_qualifier
53
72
53
54
86299b0659f3f667a158c6660ad08c3c21a517aa
bigcode/the-stack
train
45cad84ee6509b07a1ff5705
train
function
@shared_task def announce_qualifier(qualifier_id): from .models import Qualifier qualifier = Qualifier.objects.get(id=qualifier_id) event = qualifier.event discord_user = qualifier.user.discord_user twitch_user = qualifier.user.twitch_user # Send message to channel channel_id = env("DISCORD...
@shared_task def announce_qualifier(qualifier_id):
from .models import Qualifier qualifier = Qualifier.objects.get(id=qualifier_id) event = qualifier.event discord_user = qualifier.user.discord_user twitch_user = qualifier.user.twitch_user # Send message to channel channel_id = env("DISCORD_QUALIFIER_REPORTING_CHANNEL_ID") if channel_id...
.template.loader import render_to_string from . import discord_disco as discord from .env import env QUALIFIER_COLOR_APPROVED = 0x07D12F QUALIFIER_COLOR_REJECTED = 0xE60000 @shared_task def announce_qualifier(qualifier_id):
64
64
151
14
49
Madv0x/classic-tetris-project
classic_tetris_project/tasks.py
Python
announce_qualifier
announce_qualifier
14
30
14
15
8974c694d7d2f5d4c3077d786e49460b5f351755
bigcode/the-stack
train
c691ceb4c9c69c0c63e25e0f
train
function
@app.route('/', methods=['GET', 'POST']) def upload_file(): if request.method == 'POST': # check if the post request has the file part if 'file' not in request.files: flash('No file part') return redirect(request.url) file = request.files['file'] # if user doe...
@app.route('/', methods=['GET', 'POST']) def upload_file():
if request.method == 'POST': # check if the post request has the file part if 'file' not in request.files: flash('No file part') return redirect(request.url) file = request.files['file'] # if user does not select file, browser also # submit an empty pa...
UPLOAD_FOLDER app.secret_key = 'Dese.Decent.Pups.BOOYO0OST' def allowed_file(filename): return '.' in filename and \ filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS @app.route('/', methods=['GET', 'POST']) def upload_file():
64
64
211
14
49
LabVirtual/emotions
test_utils/handler_file.py
Python
upload_file
upload_file
16
43
16
17
b28b0f4f45c5c666a16543b475c4e0bdb2f83ebe
bigcode/the-stack
train
4747fd9909a0ff91febd2827
train
function
def allowed_file(filename): return '.' in filename and \ filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
def allowed_file(filename):
return '.' in filename and \ filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
temp/' ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif']) app = Flask(__name__) app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER app.secret_key = 'Dese.Decent.Pups.BOOYO0OST' def allowed_file(filename):
64
64
30
5
59
LabVirtual/emotions
test_utils/handler_file.py
Python
allowed_file
allowed_file
12
14
12
12
7552f90a5007c73b7ce33c82292eb4557aa1d298
bigcode/the-stack
train
36d4abb234f334ebc895b5c0
train
function
def post_is_expired(args): """Checks if Craigslist housing post is expired.""" id_, url, session, strainer = args soup = BeautifulSoup(session.get(url).text, "lxml", parse_only=strainer) return { "id": id_, "is_expired": bool( soup.find_all("h2") # Searches for ke...
def post_is_expired(args):
"""Checks if Craigslist housing post is expired.""" id_, url, session, strainer = args soup = BeautifulSoup(session.get(url).text, "lxml", parse_only=strainer) return { "id": id_, "is_expired": bool( soup.find_all("h2") # Searches for keywords 'deleted', 'expired'...
)) # Dispatch tasks to multiple threads. for post in map_threads(post_is_expired, args): if post["is_expired"]: CraigslistHousing.query.filter(CraigslistHousing.id == post["id"]).delete(synchronize_session="fetch") db.session.commit() def post_is_expired(args):
64
64
123
7
57
irahorecka/pweb2-dev
irahorecka/api/craigslisthousing/update/clean.py
Python
post_is_expired
post_is_expired
96
107
96
96
171ac17efb19ea4872b0ec0ec070a274068d128c
bigcode/the-stack
train
640deb3a42da3a23de8c47c3
train
function
def get_cl_strainer(): """Gets bs4.SoupStrainer object, targeting relevant elements and attributes of a Craigslist post's HTML document.""" def target_elem_attrs(elem, attrs): """Gets desired element and attributes.""" return elem == "h2" return SoupStrainer(target_elem_attrs)
def get_cl_strainer():
"""Gets bs4.SoupStrainer object, targeting relevant elements and attributes of a Craigslist post's HTML document.""" def target_elem_attrs(elem, attrs): """Gets desired element and attributes.""" return elem == "h2" return SoupStrainer(target_elem_attrs)
( soup.find_all("h2") # Searches for keywords 'deleted', 'expired', and 'flagged'. and any(keyword in str(soup.find_all("h2")[0]) for keyword in ("deleted", "expired", "flagged")) ), } def get_cl_strainer():
64
64
66
6
58
irahorecka/pweb2-dev
irahorecka/api/craigslisthousing/update/clean.py
Python
get_cl_strainer
get_cl_strainer
110
118
110
110
42a93cef70e22b03bdb1d2f01042501342c110ad
bigcode/the-stack
train
0f30bc23303e87c56c0021c9
train
function
def rm_old_posts(days=7): """Removes posts where `CraigslistHousing.last_updated` is over `days` days old.""" lower_dttm_threshold = datetime.datetime.now() - datetime.timedelta(days=days) CraigslistHousing.query.filter(CraigslistHousing.last_updated < lower_dttm_threshold).delete( synchronize_sessi...
def rm_old_posts(days=7):
"""Removes posts where `CraigslistHousing.last_updated` is over `days` days old.""" lower_dttm_threshold = datetime.datetime.now() - datetime.timedelta(days=days) CraigslistHousing.query.filter(CraigslistHousing.last_updated < lower_dttm_threshold).delete( synchronize_session="fetch" ) db.se...
housing posts.""" # Tack on more functions as you see fit. The order of function calls should not be order-dependent. rm_old_posts() rm_duplicate_posts() rm_scam_warning_posts() rm_private_bedrooms_posts() rm_low_price_posts() def rm_old_posts(days=7):
64
64
80
8
56
irahorecka/pweb2-dev
irahorecka/api/craigslisthousing/update/clean.py
Python
rm_old_posts
rm_old_posts
32
38
32
32
1ea77378c9e3b89c2218fc97777cb996f78b5471
bigcode/the-stack
train
d22e79d9449d1e9df49742d2
train
function
def rm_duplicate_posts(): """Filters IDs where `CraigslistHousing._title_neighborhood` is unique. This prevents reposts by users via a different posting ID.""" unique_posts = CraigslistHousing.query.with_entities(CraigslistHousing.id).distinct( CraigslistHousing._title_neighborhood ) duplica...
def rm_duplicate_posts():
"""Filters IDs where `CraigslistHousing._title_neighborhood` is unique. This prevents reposts by users via a different posting ID.""" unique_posts = CraigslistHousing.query.with_entities(CraigslistHousing.id).distinct( CraigslistHousing._title_neighborhood ) duplicate_posts = CraigslistHousi...
is over `days` days old.""" lower_dttm_threshold = datetime.datetime.now() - datetime.timedelta(days=days) CraigslistHousing.query.filter(CraigslistHousing.last_updated < lower_dttm_threshold).delete( synchronize_session="fetch" ) db.session.commit() def rm_duplicate_posts():
64
64
104
5
59
irahorecka/pweb2-dev
irahorecka/api/craigslisthousing/update/clean.py
Python
rm_duplicate_posts
rm_duplicate_posts
41
50
41
41
ceea8a48c4fe71a2386f7efc13f98b75c3755003
bigcode/the-stack
train
c1503167f6a3e0c9a6c066ac
train
function
def map_threads(func, _iterable): """Maps function with iterable object in using thread pools.""" with concurrent.futures.ThreadPoolExecutor() as executor: result = executor.map(func, _iterable) return result
def map_threads(func, _iterable):
"""Maps function with iterable object in using thread pools.""" with concurrent.futures.ThreadPoolExecutor() as executor: result = executor.map(func, _iterable) return result
.SoupStrainer object, targeting relevant elements and attributes of a Craigslist post's HTML document.""" def target_elem_attrs(elem, attrs): """Gets desired element and attributes.""" return elem == "h2" return SoupStrainer(target_elem_attrs) def map_threads(func, _iterable):
64
64
48
9
55
irahorecka/pweb2-dev
irahorecka/api/craigslisthousing/update/clean.py
Python
map_threads
map_threads
121
125
121
121
ac509a3ea1528ca3c054adc2acf21fd361161443
bigcode/the-stack
train
5702cc5db78a8d71c904ca91
train
function
def rm_expired_craigslist_housing(): """ENTRY POINT: Removes expired Craigslist housing posts from database. To be ran less frequently than `clean_craigslist_housing` as it is time consuming. Advised to run nightly.""" ids = [post.id for post in CraigslistHousing.query.all()] urls = [post.url for post i...
def rm_expired_craigslist_housing():
"""ENTRY POINT: Removes expired Craigslist housing posts from database. To be ran less frequently than `clean_craigslist_housing` as it is time consuming. Advised to run nightly.""" ids = [post.id for post in CraigslistHousing.query.all()] urls = [post.url for post in CraigslistHousing.query.all()] ...
") db.session.commit() def rm_low_price_posts(): """Removes posts where `price` is less than 700 USD.""" CraigslistHousing.query.filter(CraigslistHousing.price < 700).delete(synchronize_session="fetch") db.session.commit() def rm_expired_craigslist_housing():
64
64
212
10
54
irahorecka/pweb2-dev
irahorecka/api/craigslisthousing/update/clean.py
Python
rm_expired_craigslist_housing
rm_expired_craigslist_housing
76
93
76
76
1cd9b26b61807b2a0ee56350a53d119102ae6758
bigcode/the-stack
train
b6af62f2e09bb2a33fb45042
train
function
def clean_craigslist_housing(): """ENTRY POINT: Cleans Craigslist housing database table. To be ran after every write to database with new Craigslist housing posts.""" # Tack on more functions as you see fit. The order of function calls should not be order-dependent. rm_old_posts() rm_duplicate_post...
def clean_craigslist_housing():
"""ENTRY POINT: Cleans Craigslist housing database table. To be ran after every write to database with new Craigslist housing posts.""" # Tack on more functions as you see fit. The order of function calls should not be order-dependent. rm_old_posts() rm_duplicate_posts() rm_scam_warning_posts() ...
`lxml` imported - used under the hood import cchardet import lxml import httpx from bs4 import BeautifulSoup, SoupStrainer from sqlalchemy.sql import func, and_ from irahorecka.models import db, CraigslistHousing def clean_craigslist_housing():
64
64
89
8
55
irahorecka/pweb2-dev
irahorecka/api/craigslisthousing/update/clean.py
Python
clean_craigslist_housing
clean_craigslist_housing
21
29
21
21
d974016d06b0ab55b8b547c049d9f8f41bf2ae33
bigcode/the-stack
train
501d48aa782b43f62e3cd228
train
function
def rm_scam_warning_posts(): """Removes posts where 'scam' is in the post title (case-insensitive). These posts usually warn buyers of scammy Craigslist posts.""" CraigslistHousing.query.filter(func.lower(CraigslistHousing.title).contains("scam")).delete( synchronize_session="fetch" ) db.ses...
def rm_scam_warning_posts():
"""Removes posts where 'scam' is in the post title (case-insensitive). These posts usually warn buyers of scammy Craigslist posts.""" CraigslistHousing.query.filter(func.lower(CraigslistHousing.title).contains("scam")).delete( synchronize_session="fetch" ) db.session.commit()
igslistHousing.id).distinct( CraigslistHousing._title_neighborhood ) duplicate_posts = CraigslistHousing.__table__.delete().where(CraigslistHousing.id.not_in(unique_posts)) # Remove duplicate posts db.session.execute(duplicate_posts) db.session.commit() def rm_scam_warning_posts():
64
64
73
7
57
irahorecka/pweb2-dev
irahorecka/api/craigslisthousing/update/clean.py
Python
rm_scam_warning_posts
rm_scam_warning_posts
53
59
53
53
4f56e15c94948c41c480778dddfc69ac171927a6
bigcode/the-stack
train
a3ce336d6bb1166df43966fe
train
function
def rm_low_price_posts(): """Removes posts where `price` is less than 700 USD.""" CraigslistHousing.query.filter(CraigslistHousing.price < 700).delete(synchronize_session="fetch") db.session.commit()
def rm_low_price_posts():
"""Removes posts where `price` is less than 700 USD.""" CraigslistHousing.query.filter(CraigslistHousing.price < 700).delete(synchronize_session="fetch") db.session.commit()
ignored.""" posts = CraigslistHousing.query.filter(and_(CraigslistHousing.price > 0, CraigslistHousing.bedrooms > 0)) posts.filter(CraigslistHousing.price / CraigslistHousing.bedrooms <= 600).delete(synchronize_session="fetch") db.session.commit() def rm_low_price_posts():
64
64
48
6
58
irahorecka/pweb2-dev
irahorecka/api/craigslisthousing/update/clean.py
Python
rm_low_price_posts
rm_low_price_posts
70
73
70
70
21d03d2c5920bea9e41f6bf7a493951209473378
bigcode/the-stack
train
19d91087aed8726177861526
train
function
def rm_private_bedrooms_posts(): """Removes housing posts where price / bedrooms <= 600 USD. Studio posts (i.e. bedrooms == 0) are ignored.""" posts = CraigslistHousing.query.filter(and_(CraigslistHousing.price > 0, CraigslistHousing.bedrooms > 0)) posts.filter(CraigslistHousing.price / CraigslistHousin...
def rm_private_bedrooms_posts():
"""Removes housing posts where price / bedrooms <= 600 USD. Studio posts (i.e. bedrooms == 0) are ignored.""" posts = CraigslistHousing.query.filter(and_(CraigslistHousing.price > 0, CraigslistHousing.bedrooms > 0)) posts.filter(CraigslistHousing.price / CraigslistHousing.bedrooms <= 600).delete(synchro...
is in the post title (case-insensitive). These posts usually warn buyers of scammy Craigslist posts.""" CraigslistHousing.query.filter(func.lower(CraigslistHousing.title).contains("scam")).delete( synchronize_session="fetch" ) db.session.commit() def rm_private_bedrooms_posts():
64
64
94
8
56
irahorecka/pweb2-dev
irahorecka/api/craigslisthousing/update/clean.py
Python
rm_private_bedrooms_posts
rm_private_bedrooms_posts
62
67
62
62
17d41b841ad8b2a5e1c20da4ace99ef3aa0f48b8
bigcode/the-stack
train
158a4f645f815e84d907907e
train
function
def subscribe(client): def on_message(client, userdata, msg): print(f"Received `{msg.payload.decode()}` from `{msg.topic}` topic") with open('iot.json', 'a+') as f: m_decode = str(msg.payload.decode()) r = json.dumps(m_decode,indent=7) f.write(r) client....
def subscribe(client):
def on_message(client, userdata, msg): print(f"Received `{msg.payload.decode()}` from `{msg.topic}` topic") with open('iot.json', 'a+') as f: m_decode = str(msg.payload.decode()) r = json.dumps(m_decode,indent=7) f.write(r) client.subscribe(topic) cl...
to MQTT Broker!") else: print("Failed to connect, return code %d\n", rc) client = mqtt_client.Client(client_id) client.username_pw_set(username, password) client.on_connect = on_connect client.connect(broker, port) return client def subscribe(client):
64
64
85
4
59
RodrigoLima82/Maratona_IBM_2021
Desafio_02/functions/getdata.py
Python
subscribe
subscribe
27
37
27
27
a70c533f186398251ff0c981e4f720017b3b54bd
bigcode/the-stack
train
214486a9f21b52d2ee299d18
train
function
def run(): client = connect_mqtt() client.loop_start() subscribe(client)
def run():
client = connect_mqtt() client.loop_start() subscribe(client)
}" result = client.publish(topic, msg) status = result[0] if status == 0: print(f"Send `{msg}` to topic `{topic}`") else: print(f"Failed to send message to topic {topic}") msg_count += 1 def run():
64
64
19
3
60
RodrigoLima82/Maratona_IBM_2021
Desafio_02/functions/getdata.py
Python
run
run
52
55
52
52
a5d4e43db0ecbf84f0c0461aee67093bdd64014d
bigcode/the-stack
train
d2cb090603cd51e2a0c91085
train
function
def publish(client): msg_count = 0 while True: time.sleep(1) msg = f"messages: {msg_count}" result = client.publish(topic, msg) status = result[0] if status == 0: print(f"Send `{msg}` to topic `{topic}`") else: print(f"Failed to send messag...
def publish(client):
msg_count = 0 while True: time.sleep(1) msg = f"messages: {msg_count}" result = client.publish(topic, msg) status = result[0] if status == 0: print(f"Send `{msg}` to topic `{topic}`") else: print(f"Failed to send message to topic {topic}") ...
from `{msg.topic}` topic") with open('iot.json', 'a+') as f: m_decode = str(msg.payload.decode()) r = json.dumps(m_decode,indent=7) f.write(r) client.subscribe(topic) client.on_message = on_message def publish(client):
64
64
92
4
59
RodrigoLima82/Maratona_IBM_2021
Desafio_02/functions/getdata.py
Python
publish
publish
39
50
39
39
da5897a500f7e21eefdd23a085dfaf10ed1d67ab
bigcode/the-stack
train
b508f7e60fe9dc13e876a9e9
train
function
def connect_mqtt(): def on_connect(client, userdata, flags, rc): if rc == 0: print("Connected to MQTT Broker!") else: print("Failed to connect, return code %d\n", rc) client = mqtt_client.Client(client_id) client.username_pw_set(username, password) client.on_conn...
def connect_mqtt():
def on_connect(client, userdata, flags, rc): if rc == 0: print("Connected to MQTT Broker!") else: print("Failed to connect, return code %d\n", rc) client = mqtt_client.Client(client_id) client.username_pw_set(username, password) client.on_connect = on_connect ...
json broker = 'iot.maratona.dev' port = 31666 topic = "quanam" client_id = 'quanam-mqtt-desafio-02-ibm' username = 'maratoners' password = 'btc-2021' def connect_mqtt():
64
64
88
5
59
RodrigoLima82/Maratona_IBM_2021
Desafio_02/functions/getdata.py
Python
connect_mqtt
connect_mqtt
14
25
14
14
48c3541b0c96fccabda785f56ce77dc32dece4ab
bigcode/the-stack
train
c8745f32634716e6a8621310
train
class
class BLEConnector(Connector, Thread): process_data = Queue(-1) def __init__(self, gateway, config, connector_type): self.statistics = {'MessagesReceived': 0, 'MessagesSent': 0} super().__init__() self._connector_type = connector_type self.__gateway = ...
class BLEConnector(Connector, Thread):
process_data = Queue(-1) def __init__(self, gateway, config, connector_type): self.statistics = {'MessagesReceived': 0, 'MessagesSent': 0} super().__init__() self._connector_type = connector_type self.__gateway = gateway self.__config = config ...
# Licensed under the Apache License, Version 2.0 (the "License"); # 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 # ...
256
256
1,000
8
247
longxiuzhai/thingsboard-gateway
thingsboard_gateway/connectors/ble/ble_connector.py
Python
BLEConnector
BLEConnector
35
166
35
35
832cbbfe2e0b601b16a425abe033e82faad3a8d3
bigcode/the-stack
train
d0818e564af3fd9b024ca34a
train
class
class ReporterModel(MetaModel): """ Reporter base class """ def on_start(self): """ Called when testing starts """ raise NotImplementedError() def on_finish(self): """ Called when testing ends """ raise NotImplementedError() def on_scanner_start(self, scanner): ...
class ReporterModel(MetaModel):
""" Reporter base class """ def on_start(self): """ Called when testing starts """ raise NotImplementedError() def on_finish(self): """ Called when testing ends """ raise NotImplementedError() def on_scanner_start(self, scanner): """ Called when scanner starts ...
on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Reporter model """ from dusty.models.meta import MetaModel class ReporterModel(MetaModel):
64
64
129
7
56
LifeDJIK/dusty-ng
dusty/models/reporter.py
Python
ReporterModel
ReporterModel
25
50
25
25
c67680f92421f818fda85a09f697101cb37ef351
bigcode/the-stack
train
16f1365c27b94aec7e01f948
train
function
def make_pillars_from_existing(): _client = _get_client() _pillar_path = _get_pillar_path() ntp_peers = _client.cmd('*', 'ntp.peers', [], expr_form='glob', timeout=60) ntp_servers = _client.cmd('*', 'ntp.servers', [], expr_form='glob', timeout=60) for device, device_ntp_peers in six.iteritems(ntp...
def make_pillars_from_existing():
_client = _get_client() _pillar_path = _get_pillar_path() ntp_peers = _client.cmd('*', 'ntp.peers', [], expr_form='glob', timeout=60) ntp_servers = _client.cmd('*', 'ntp.servers', [], expr_form='glob', timeout=60) for device, device_ntp_peers in six.iteritems(ntp_peers): if not device_ntp_...
_synced_devices.append(device) continue under_stratum = [synced_peer.keys()[0] for synced_peer in synced_peers if synced_peer.values()[0] <= stratum] if not under_stratum: _over_stratum_devices.append(device) continue return (_not_synced_devices, _over_stratum_de...
81
81
273
8
73
napalm-automation/napalm-salt
carbon/_runners/ntp.py
Python
make_pillars_from_existing
make_pillars_from_existing
150
175
150
151
ed3ac1b3ad9fdebabf20655efa9d34ccd1828a8a
bigcode/the-stack
train
cc3755530db5dfe5100b4f63
train
function
def unsynchronized(): _client = _get_client() _rclient = _get_rclient() ntp_stats = _client.cmd('*', 'ntp.stats', [], expr_form='glob', timeout=120) _not_synced_devices = list() _over_stratum_devices = list() for device, device_ntp_stats in six.iteritems(ntp_stats): if not device_ntp_...
def unsynchronized():
_client = _get_client() _rclient = _get_rclient() ntp_stats = _client.cmd('*', 'ntp.stats', [], expr_form='glob', timeout=120) _not_synced_devices = list() _over_stratum_devices = list() for device, device_ntp_stats in six.iteritems(ntp_stats): if not device_ntp_stats.get('result', Fal...
if add_servers: if 'servers' not in _ntp_diff['add'].keys(): _ntp_diff['add']['servers'] = {} _ntp_diff['add']['servers'][device] = add_servers if remove_servers: if 'servers' not in _ntp_diff['remove'].keys(): ...
109
109
365
4
104
napalm-automation/napalm-salt
carbon/_runners/ntp.py
Python
unsynchronized
unsynchronized
112
147
112
113
8003fe896ee8d1004d4a70b90ca53e0b60d85035
bigcode/the-stack
train
53595eac92d87e60f019f73c
train
function
def _get_pillar_path(): return __opts__['pillar_roots'].get('base')[0]
def _get_pillar_path():
return __opts__['pillar_roots'].get('base')[0]
time.apple.com '40.118.103.7' # time.windows.com ] # ---------------------------------------------------------------------------------------------------------------------- # module properties # ---------------------------------------------------------------------------------------------------------------------- ...
63
64
23
7
56
napalm-automation/napalm-salt
carbon/_runners/ntp.py
Python
_get_pillar_path
_get_pillar_path
38
40
38
39
4074c33f9c41c0be38bc4916ca894bfb9865a0fe
bigcode/the-stack
train
cf4309e11701f0de0af5dabc
train
function
def _get_rclient(): quiet_opts = deepcopy(__opts__) quiet_opts.update({'quiet': True}) _rclient = salt.runner.RunnerClient(quiet_opts) return _rclient
def _get_rclient():
quiet_opts = deepcopy(__opts__) quiet_opts.update({'quiet': True}) _rclient = salt.runner.RunnerClient(quiet_opts) return _rclient
# ---------------------------------------------------------------------------------------------------------------------- # helper functions -- will not be exported # ---------------------------------------------------------------------------------------------------------------------- def _get_pillar_path(): retu...
63
64
43
6
57
napalm-automation/napalm-salt
carbon/_runners/ntp.py
Python
_get_rclient
_get_rclient
48
53
48
49
94925658754857df755c435d6620fe3638d1f207
bigcode/the-stack
train
1b414d9aa21940396c0b1640
train
function
def _get_client(): return salt.client.LocalClient(__opts__['conf_file'])
def _get_client():
return salt.client.LocalClient(__opts__['conf_file'])
# ---------------------------------------------------------------------------------------------------------------------- # module properties # ---------------------------------------------------------------------------------------------------------------------- # -------------------------------------------------------...
64
64
18
5
59
napalm-automation/napalm-salt
carbon/_runners/ntp.py
Python
_get_client
_get_client
43
45
43
44
d5074a20d87e52a15668b2a80471e59f3ca49354
bigcode/the-stack
train
e985331701260a05789c0667
train
function
def rebuild_pillars(): _pillar_path = _get_pillar_path() ntp_files = [f for f in os.listdir(_pillar_path) if os.path.isfile(os.path.join(_pillar_path, f)) and f.startswith('ntp_')] ntp_file_content = { 'ntp.peers': _PEERS, 'ntp.servers': _SERVERS } for ntp_filename in ntp_files: ...
def rebuild_pillars():
_pillar_path = _get_pillar_path() ntp_files = [f for f in os.listdir(_pillar_path) if os.path.isfile(os.path.join(_pillar_path, f)) and f.startswith('ntp_')] ntp_file_content = { 'ntp.peers': _PEERS, 'ntp.servers': _SERVERS } for ntp_filename in ntp_files: with open(ntp_fi...
) ntp_peers_filepath = os.path.join(_pillar_path, ntp_filename) with open(ntp_peers_filepath, 'w') as ntp_file: ntp_file.write( yaml.dump(ntp_filecontent, default_flow_style=False) ) def rebuild_pillars():
64
64
132
6
58
napalm-automation/napalm-salt
carbon/_runners/ntp.py
Python
rebuild_pillars
rebuild_pillars
178
193
178
179
3f9716959c46d8a7d5993a3a46e3c941665dfdcd
bigcode/the-stack
train
980d5c2f77e259bb83db4aa3
train
function
def diff(): """Returns the differences between the expected device config and the actual config.""" _client = _get_client() ntp_state_result = _client.cmd('*', 'state.sls', ['router.ntp', 'test=True'], expr_form='glob', timeout=60) _ntp_diff = { 'add': {}, 'remove': {} } for...
def diff():
"""Returns the differences between the expected device config and the actual config.""" _client = _get_client() ntp_state_result = _client.cmd('*', 'state.sls', ['router.ntp', 'test=True'], expr_form='glob', timeout=60) _ntp_diff = { 'add': {}, 'remove': {} } for device, devi...
---------------------------------------------------------------------------------------------------------------------- # property functions # ---------------------------------------------------------------------------------------------------------------------- # -------------------------------------------------------...
123
124
416
3
120
napalm-automation/napalm-salt
carbon/_runners/ntp.py
Python
diff
diff
61
109
61
62
228db8086ef03e2fb9c37c21a51465c44e9f054f
bigcode/the-stack
train
5b26dae06f68b0ff96874630
train
class
class TemplatePlugin: def __init__(self, config): self.self_contained = not config.getoption("--split-report") self._css = None self._assets = [] self._dirs = [] def pytest_reporter_loader(self, dirs, config): self._dirs = dirs + [str(TEMPLATE_PATH)] conv = Ansi...
class TemplatePlugin:
def __init__(self, config): self.self_contained = not config.getoption("--split-report") self._css = None self._assets = [] self._dirs = [] def pytest_reporter_loader(self, dirs, config): self._dirs = dirs + [str(TEMPLATE_PATH)] conv = Ansi2HTMLConverter(escaped=...
71C1C", "#FFFFFF"), "xfailed": ("#EF9A9A", "#222222"), "xpassed": ("#A5D6A7", "#222222"), "skipped": ("#9E9E9E", "#FFFFFF"), "notrun": ("#9E9E9E", "#FFFFFF"), "rerun": ("#FBC02D", "#222222"), "warning": ("#FBC02D", "#222222"), "green": ("#43A047", "#FFFFFF"), "red": ("#E53935", "#FFFFFF"...
256
256
1,033
4
251
christiansandberg/pytest-reporter-html1
pytest_reporter_html1/plugin.py
Python
TemplatePlugin
TemplatePlugin
64
191
64
65
6d86df6d4a266a895a766699abc02f567bfc536e
bigcode/the-stack
train
a441995d8a0657c4d9327208
train
function
def css_minify(s): s = re.sub(r"\s+", " ", s) s = re.sub(r"/\*.*?\*/", "", s) return s
def css_minify(s):
s = re.sub(r"\s+", " ", s) s = re.sub(r"/\*.*?\*/", "", s) return s
): group = parser.getgroup("report generation") group.addoption( "--split-report", action="store_true", help="store CSS and image files separately from the HTML.", ) def pytest_configure(config): config.pluginmanager.register(TemplatePlugin(config)) def css_minify(s):
64
64
39
6
58
christiansandberg/pytest-reporter-html1
pytest_reporter_html1/plugin.py
Python
css_minify
css_minify
58
61
58
58
4bffe2756b8be2539307430d9e11e5de72bffe0c
bigcode/the-stack
train
b8a0e06eeb1191235ccfc8b0
train
function
def pytest_configure(config): config.pluginmanager.register(TemplatePlugin(config))
def pytest_configure(config):
config.pluginmanager.register(TemplatePlugin(config))
#FBC02D", "#222222"), } def pytest_addoption(parser): group = parser.getgroup("report generation") group.addoption( "--split-report", action="store_true", help="store CSS and image files separately from the HTML.", ) def pytest_configure(config):
64
64
16
6
58
christiansandberg/pytest-reporter-html1
pytest_reporter_html1/plugin.py
Python
pytest_configure
pytest_configure
54
55
54
54
b97a04197ede9ad80b0e1424736883ae4299a2fc
bigcode/the-stack
train
3dfacdfc8e3bd299469e80c1
train
function
def pytest_addoption(parser): group = parser.getgroup("report generation") group.addoption( "--split-report", action="store_true", help="store CSS and image files separately from the HTML.", )
def pytest_addoption(parser):
group = parser.getgroup("report generation") group.addoption( "--split-report", action="store_true", help="store CSS and image files separately from the HTML.", )
"), "warning": ("#FBC02D", "#222222"), "green": ("#43A047", "#FFFFFF"), "red": ("#E53935", "#FFFFFF"), "yellow": ("#FBC02D", "#222222"), } def pytest_addoption(parser):
64
64
47
6
58
christiansandberg/pytest-reporter-html1
pytest_reporter_html1/plugin.py
Python
pytest_addoption
pytest_addoption
45
51
45
45
c592d49181430ddeecc2f8bcb784d6730926257a
bigcode/the-stack
train
02d097462b53c93b52d37b7f
train
function
def test(identifier=""): """ test exection """ bendo_base_url = "http://bendo-pprd-vm.library.nd.edu:14000" bendo_base_url = "http://bendo-prod-vm.library.nd.edu:14000" bendo_item = "0g354f1907g" filename = 'October197613thissue.pdf' results = get_bendo_info(bendo_base_url, bendo_item, filename)...
def test(identifier=""):
""" test exection """ bendo_base_url = "http://bendo-pprd-vm.library.nd.edu:14000" bendo_base_url = "http://bendo-prod-vm.library.nd.edu:14000" bendo_item = "0g354f1907g" filename = 'October197613thissue.pdf' results = get_bendo_info(bendo_base_url, bendo_item, filename) print("results = ", ...
return results # export SSM_KEY_BASE=/all/new-csv # aws-vault exec testlibnd-superAdmin --session-ttl=1h --assume-role-ttl=1h -- # python -c 'from get_bendo_info import *; test()' def test(identifier=""):
64
64
106
5
59
ndlib/mellon-manifest-pipeline
curate_export/get_bendo_info.py
Python
test
test
29
36
29
29
347b918ab1c8983ddcf67e9b5d4578321a372660
bigcode/the-stack
train
8247fdc7e5f7317e3815a18b
train
function
def get_bendo_info(bendo_base_url, bendo_item, filename): results = {} url = bendo_base_url + "/item/" + bendo_item + "/" + filename try: response = dependencies.requests.head(url) # , headers=self.curate_header) if response: results = response.headers except dependencies.re...
def get_bendo_info(bendo_base_url, bendo_item, filename):
results = {} url = bendo_base_url + "/item/" + bendo_item + "/" + filename try: response = dependencies.requests.head(url) # , headers=self.curate_header) if response: results = response.headers except dependencies.requests.exceptions.InvalidURL as e: print("invalid ...
# get_bendo_info.py # import _set_path # noqa: F401 import dependencies.requests from dependencies.sentry_sdk import capture_exception def get_bendo_info(bendo_base_url, bendo_item, filename):
48
64
174
16
31
ndlib/mellon-manifest-pipeline
curate_export/get_bendo_info.py
Python
get_bendo_info
get_bendo_info
7
23
7
7
806f7e3aa3c247547a27e160519cd4a326d09c3b
bigcode/the-stack
train
2646853859a5271f6ed1fb0e
train
class
class SinkFillerBarnes(LakeMapperBarnes): """Uses the Barnes et al (2014) algorithms to replace pits in a topography with flats, or optionally with very shallow gradient surfaces to allow continued draining. This component is NOT intended for use iteratively as a model runs; rather, it is to fill i...
class SinkFillerBarnes(LakeMapperBarnes):
"""Uses the Barnes et al (2014) algorithms to replace pits in a topography with flats, or optionally with very shallow gradient surfaces to allow continued draining. This component is NOT intended for use iteratively as a model runs; rather, it is to fill in an initial topography. If you want to re...
#!/usr/env/python """fill_sinks_barnes.py. Fill sinks in a landscape to the brim, following the Barnes et al. (2014) algorithms. """ import numpy as np from landlab.components import LakeMapperBarnes from landlab.utils.return_array import return_array_at_node class SinkFillerBarnes(LakeMapperBarnes):
75
256
3,067
12
62
speleophysics/landlab
landlab/components/sink_fill/sink_fill_barnes.py
Python
SinkFillerBarnes
SinkFillerBarnes
16
298
16
16
441fae0dc082d5931b1e3c9641995cd2d2d66e7a
bigcode/the-stack
train
3b8255b85b6eda7b51ec26fc
train
class
class EmailService(str, Enum): MAILJET = "mailjet" SENDGRID = "sendgrid"
class EmailService(str, Enum):
MAILJET = "mailjet" SENDGRID = "sendgrid"
from enum import Enum class EmailService(str, Enum):
12
64
23
7
4
umluizlima/email-sender
app/settings/email_service.py
Python
EmailService
EmailService
4
6
4
4
d8792cdfb862ca92f120c41d7c02f126d29c1078
bigcode/the-stack
train
cef78deab466083f4a46cf16
train
function
def test(clf, X_test, y_test): accuracy = clf.score(X_test, y_test) return accuracy
def test(clf, X_test, y_test):
accuracy = clf.score(X_test, y_test) return accuracy
.makedirs(SAVE_DIR) def train(clf, X_train, y_train): start = time.time() clf.fit(X_train, y_train) print('Training took {:.04f}secs'.format(time.time() - start)) return clf def test(clf, X_test, y_test):
64
64
26
11
52
victor-iyi/epl-prediction
models/epl_engine.py
Python
test
test
17
19
17
17
81e36dc772a87e33e88c298006cc5c15592b6049
bigcode/the-stack
train
1e428a783b61a6c76c0be5ae
train
function
def train(clf, X_train, y_train): start = time.time() clf.fit(X_train, y_train) print('Training took {:.04f}secs'.format(time.time() - start)) return clf
def train(clf, X_train, y_train):
start = time.time() clf.fit(X_train, y_train) print('Training took {:.04f}secs'.format(time.time() - start)) return clf
import os.path import pickle import time SAVE_DIR = 'trained' if not os.path.isdir(SAVE_DIR): os.makedirs(SAVE_DIR) def train(clf, X_train, y_train):
43
64
48
11
32
victor-iyi/epl-prediction
models/epl_engine.py
Python
train
train
10
14
10
10
6ade37a6570ac68534730de0ba46c825b4a4fdb1
bigcode/the-stack
train
36a6a202cb6a1f68c8d45e00
train
function
def predict(clf, X): return clf.predict(X)
def predict(clf, X):
return clf.predict(X)
clf.fit(X_train, y_train) print('Training took {:.04f}secs'.format(time.time() - start)) return clf def test(clf, X_test, y_test): accuracy = clf.score(X_test, y_test) return accuracy def predict(clf, X):
64
64
13
7
56
victor-iyi/epl-prediction
models/epl_engine.py
Python
predict
predict
22
23
22
22
4f356bb51cc493899233ed2c17d0872c2020017f
bigcode/the-stack
train
11f8471c074f732213b051f1
train
function
def main(): from sklearn.ensemble import AdaBoostClassifier from .preprocess import process, process_to_features # Load all the datasets home_team = 'arsenal' away_team = 'stoke' X_train, X_test, y_train, y_test = process(filename=None, test_size=0.1, save_csv=True) pred_features = process...
def main():
from sklearn.ensemble import AdaBoostClassifier from .preprocess import process, process_to_features # Load all the datasets home_team = 'arsenal' away_team = 'stoke' X_train, X_test, y_train, y_test = process(filename=None, test_size=0.1, save_csv=True) pred_features = process_to_features...
('(')] filename = os.path.join(SAVE_DIR, '{}.pkl'.format(filename)) if force or not os.path.exists(filename): f = open(filename, 'wb') pickle.dump(clf, f) f.close() print('Successfully saved!') else: raise (Exception('File already exist!')) def main():
74
75
252
3
71
victor-iyi/epl-prediction
models/epl_engine.py
Python
main
main
45
74
45
45
24723e93852483eb9a669864d775ae8ba8fb35b4
bigcode/the-stack
train
9c54265b78edcbf2554d0b76
train
function
def train_predict(clf, X_train, y_train, X): train(clf, X_train, y_train) return predict(clf, X)
def train_predict(clf, X_train, y_train, X):
train(clf, X_train, y_train) return predict(clf, X)
format(time.time() - start)) return clf def test(clf, X_test, y_test): accuracy = clf.score(X_test, y_test) return accuracy def predict(clf, X): return clf.predict(X) def train_predict(clf, X_train, y_train, X):
64
64
33
14
50
victor-iyi/epl-prediction
models/epl_engine.py
Python
train_predict
train_predict
26
28
26
26
5e0492073d8b422699e080d9baa4037ba370ab8e
bigcode/the-stack
train
ffea2c8ae733a54f98226b3d
train
function
def save_classifier(clf, filename=None, force=False): if not filename: model_name = str(clf) filename = model_name[:model_name.index('(')] filename = os.path.join(SAVE_DIR, '{}.pkl'.format(filename)) if force or not os.path.exists(filename): f = open(filename, 'wb') pickle.du...
def save_classifier(clf, filename=None, force=False):
if not filename: model_name = str(clf) filename = model_name[:model_name.index('(')] filename = os.path.join(SAVE_DIR, '{}.pkl'.format(filename)) if force or not os.path.exists(filename): f = open(filename, 'wb') pickle.dump(clf, f) f.close() print('Successful...
_test) return accuracy def predict(clf, X): return clf.predict(X) def train_predict(clf, X_train, y_train, X): train(clf, X_train, y_train) return predict(clf, X) def save_classifier(clf, filename=None, force=False):
64
64
105
12
52
victor-iyi/epl-prediction
models/epl_engine.py
Python
save_classifier
save_classifier
31
42
31
31
e692808be16edae8e250e5af7f70106c01ed5236
bigcode/the-stack
train
120983f21d1f823a7fecd8d8
train
class
class DocumentProcessorServiceAsyncClient: """Service to call Cloud DocumentAI to process documents according to the processor's definition. Processors are built using state-of-the-art Google AI such as natural language, computer vision, and translation to extract structured information from unstruc...
class DocumentProcessorServiceAsyncClient:
"""Service to call Cloud DocumentAI to process documents according to the processor's definition. Processors are built using state-of-the-art Google AI such as natural language, computer vision, and translation to extract structured information from unstructured or semi-structured documents. """...
the License for the specific language governing permissions and # limitations under the License. # from collections import OrderedDict import functools import re from typing import Dict, Mapping, Optional, Sequence, Tuple, Type, Union from google.api_core import exceptions as core_exceptions from google.api_core impo...
256
256
4,055
7
248
galz10/python-documentai
google/cloud/documentai_v1/services/document_processor_service/async_client.py
Python
DocumentProcessorServiceAsyncClient
DocumentProcessorServiceAsyncClient
44
588
44
44
42085aef1ef0ece7575bed33bcf1c36a6747f8e1
bigcode/the-stack
train
a6ad55a64857a330e1de05c8
train
class
class CardApi(ListAPIView): queryset = Card.objects.all() serializer_class = CardSerializer
class CardApi(ListAPIView):
queryset = Card.objects.all() serializer_class = CardSerializer
from rest_framework.generics import ListAPIView from .serializers import ListSerializer, CardSerializer from .models import List, Card class ListApi(ListAPIView): queryset = List.objects.all() serializer_class = ListSerializer class CardApi(ListAPIView):
54
64
20
6
47
abumukhlis/djangular
djangular/scrumboard/api.py
Python
CardApi
CardApi
11
13
11
11
1f044e49fda6e2dc28f5609aad0fb319f3988d11
bigcode/the-stack
train
a7ecb44827df5718ef54a631
train
class
class ListApi(ListAPIView): queryset = List.objects.all() serializer_class = ListSerializer
class ListApi(ListAPIView):
queryset = List.objects.all() serializer_class = ListSerializer
from rest_framework.generics import ListAPIView from .serializers import ListSerializer, CardSerializer from .models import List, Card class ListApi(ListAPIView):
34
64
20
6
27
abumukhlis/djangular
djangular/scrumboard/api.py
Python
ListApi
ListApi
6
8
6
6
1f3021f892d8c3b88d772727d30d134f5ef749bd
bigcode/the-stack
train
d3c230312f9b96cf26c7d473
train
class
class NodeTests(unittest.TestCase): #단위테스트 def test_initialization(self): node = Node(0.5, to_play=1) #Node(확률, 내가 게임시작) #이렇게 test initialization 검사 - 초기화 self.assertEqual(node.visit_count, 0) self.assertEqual(node.prior, 0.5) self.assertEqual(len(node.children)...
class NodeTests(unittest.TestCase): #단위테스트
def test_initialization(self): node = Node(0.5, to_play=1) #Node(확률, 내가 게임시작) #이렇게 test initialization 검사 - 초기화 self.assertEqual(node.visit_count, 0) self.assertEqual(node.prior, 0.5) self.assertEqual(len(node.children), 0) self.assertFalse(node.expanded()) ...
index 1 self.assertLess(root.children[0].visit_count, root.children[1].visit_count) def test_mcts_finds_best_move_with_really_really_bad_priors(self): class MockModel: def predict(self, board): #starting board is : #[-1, 0, 0, 0] ...
256
256
1,892
13
243
Youngseo-Jeon0313/AlphaZeroSimple
tests.py
Python
NodeTests
NodeTests
66
222
66
67
956c39b504a901c2064a18e6b002d9a9118f2a5f
bigcode/the-stack
train
675feb4af3461121028a7c18
train
class
class MCTSTests(unittest.TestCase): def test_mcts_from_root_with_equal_priors(self): #동등한 사전확률의 root로부터의 test class MockModel: #모의 모델 def predict(self, board): #예측 #starting board is : # [0, 0, 1, -1] return np.array([0.26, 0.24, 0.24, 0.26]),...
class MCTSTests(unittest.TestCase):
def test_mcts_from_root_with_equal_priors(self): #동등한 사전확률의 root로부터의 test class MockModel: #모의 모델 def predict(self, board): #예측 #starting board is : # [0, 0, 1, -1] return np.array([0.26, 0.24, 0.24, 0.26]), 0.001 game = Connect2Ga...
#어떻게 할당해주고 test를 하는거지? #test set 만들어주기 import numpy as np import unittest from monte_carlo_tree_search import Node, MCTS, ucb_score from game import Connect2Game class MCTSTests(unittest.TestCase):
63
183
611
10
52
Youngseo-Jeon0313/AlphaZeroSimple
tests.py
Python
MCTSTests
MCTSTests
8
64
8
9
9c978e4c1c4bb472fb9b027a63ceb91ba61925ea
bigcode/the-stack
train
c4663f5fb19d767d3f09b48c
train
function
def _swig_repr(self): try: strthis = "proxy of " + self.this.__repr__() except __builtin__.Exception: strthis = "" return "<%s.%s; %s >" % (self.__class__.__module__, self.__class__.__name__, strthis,)
def _swig_repr(self):
try: strthis = "proxy of " + self.this.__repr__() except __builtin__.Exception: strthis = "" return "<%s.%s; %s >" % (self.__class__.__module__, self.__class__.__name__, strthis,)
try: import builtins as __builtin__ except ImportError: import __builtin__ _swig_new_instance_method = _fe_h1.SWIG_PyInstanceMethod_New _swig_new_static_method = _fe_h1.SWIG_PyStaticMethod_New def _swig_repr(self):
64
64
65
7
56
GabrielJie/PyMFEM
mfem/_par/fe_h1.py
Python
_swig_repr
_swig_repr
25
30
25
25
74bf9358625d922abb67ce987d3810bb3c81f49e
bigcode/the-stack
train
e5fc40767acadb4192283dbe
train
class
class H1_SegmentElement(mfem._par.fe_base.NodalTensorFiniteElement): r"""Proxy of C++ mfem::H1_SegmentElement class.""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self, *args, **kwargs): r"""__init__(H1_S...
class H1_SegmentElement(mfem._par.fe_base.NodalTensorFiniteElement):
r"""Proxy of C++ mfem::H1_SegmentElement class.""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self, *args, **kwargs): r"""__init__(H1_SegmentElement self, int const p, int const btype=GaussLobatto) -> H1_...
""" __setattr__ = _swig_setattr_nondynamic_class_variable(type.__setattr__) import weakref import mfem._par.fe_base import mfem._par.intrules import mfem._par.array import mfem._par.mem_manager import mfem._par.geom import mfem._par.densemat import mfem._par.vector import mfem._par.operators import mfem._par.mat...
144
144
483
19
124
GabrielJie/PyMFEM
mfem/_par/fe_h1.py
Python
H1_SegmentElement
H1_SegmentElement
82
111
82
82
7d1a544f7344844756b3c82ba72b65c4aba70ae9
bigcode/the-stack
train
7e71b6361b0ff72458b1a4c5
train
class
class H1_QuadrilateralElement(mfem._par.fe_base.NodalTensorFiniteElement): r"""Proxy of C++ mfem::H1_QuadrilateralElement class.""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self, *args, **kwargs): r"""_...
class H1_QuadrilateralElement(mfem._par.fe_base.NodalTensorFiniteElement):
r"""Proxy of C++ mfem::H1_QuadrilateralElement class.""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self, *args, **kwargs): r"""__init__(H1_QuadrilateralElement self, int const p, int const btype=GaussLob...
1_SegmentElement_CalcHessian) def ProjectDelta(self, vertex, dofs): r"""ProjectDelta(H1_SegmentElement self, int vertex, Vector dofs)""" return _fe_h1.H1_SegmentElement_ProjectDelta(self, vertex, dofs) ProjectDelta = _swig_new_instance_method(_fe_h1.H1_SegmentElement_ProjectDelta) __swig_de...
150
150
502
20
130
GabrielJie/PyMFEM
mfem/_par/fe_h1.py
Python
H1_QuadrilateralElement
H1_QuadrilateralElement
116
145
116
116
ce9b4abbd578b45ced32511e95a24dbc04e361de
bigcode/the-stack
train
cd999ef213d5e8390a2b6d06
train
class
class H1_WedgeElement(mfem._par.fe_base.NodalFiniteElement): r"""Proxy of C++ mfem::H1_WedgeElement class.""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self, *args, **kwargs): r"""__init__(H1_WedgeElemen...
class H1_WedgeElement(mfem._par.fe_base.NodalFiniteElement):
r"""Proxy of C++ mfem::H1_WedgeElement class.""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self, *args, **kwargs): r"""__init__(H1_WedgeElement self, int const p, int const btype=GaussLobatto) -> H1_Wedg...
shape) CalcHessian = _swig_new_instance_method(_fe_h1.H1_TetrahedronElement_CalcHessian) __swig_destroy__ = _fe_h1.delete_H1_TetrahedronElement # Register H1_TetrahedronElement in _fe_h1: _fe_h1.H1_TetrahedronElement_swigregister(H1_TetrahedronElement) class H1_WedgeElement(mfem._par.fe_base.NodalFiniteElement...
98
98
327
18
80
GabrielJie/PyMFEM
mfem/_par/fe_h1.py
Python
H1_WedgeElement
H1_WedgeElement
242
261
242
242
b9c4bfb1502e68a88ada3a220b1cb22f84bf07fa
bigcode/the-stack
train
8a46e1cb39fbc19eeb51613c
train
class
class H1_TetrahedronElement(mfem._par.fe_base.NodalFiniteElement): r"""Proxy of C++ mfem::H1_TetrahedronElement class.""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self, *args, **kwargs): r"""__init__(H1...
class H1_TetrahedronElement(mfem._par.fe_base.NodalFiniteElement):
r"""Proxy of C++ mfem::H1_TetrahedronElement class.""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self, *args, **kwargs): r"""__init__(H1_TetrahedronElement self, int const p, int const btype=GaussLobatto...
Element self, IntegrationPoint ip, DenseMatrix ddshape)""" return _fe_h1.H1_TriangleElement_CalcHessian(self, ip, ddshape) CalcHessian = _swig_new_instance_method(_fe_h1.H1_TriangleElement_CalcHessian) __swig_destroy__ = _fe_h1.delete_H1_TriangleElement # Register H1_TriangleElement in _fe_h1: _fe_h1.H...
127
127
425
19
108
GabrielJie/PyMFEM
mfem/_par/fe_h1.py
Python
H1_TetrahedronElement
H1_TetrahedronElement
213
237
213
213
1ba526877a338d89153f5571b76b0f1f1792a0dd
bigcode/the-stack
train
67a3333f89d1c7df8384bccc
train
function
def _swig_setattr_nondynamic_instance_variable(set): def set_instance_attr(self, name, value): if name == "thisown": self.this.own(value) elif name == "this": set(self, name, value) elif hasattr(self, name) and isinstance(getattr(type(self), name), property): ...
def _swig_setattr_nondynamic_instance_variable(set):
def set_instance_attr(self, name, value): if name == "thisown": self.this.own(value) elif name == "this": set(self, name, value) elif hasattr(self, name) and isinstance(getattr(type(self), name), property): set(self, name, value) else: ...
proxy of " + self.this.__repr__() except __builtin__.Exception: strthis = "" return "<%s.%s; %s >" % (self.__class__.__module__, self.__class__.__name__, strthis,) def _swig_setattr_nondynamic_instance_variable(set):
63
64
106
13
50
GabrielJie/PyMFEM
mfem/_par/fe_h1.py
Python
_swig_setattr_nondynamic_instance_variable
_swig_setattr_nondynamic_instance_variable
33
43
33
33
03e56b4f3d0ee41ebbe74ae516f5d9abaec225fe
bigcode/the-stack
train
f7ec12014f9e92ce8282afed
train
class
class _SwigNonDynamicMeta(type): """Meta class to enforce nondynamic attributes (no new attributes) for a class""" __setattr__ = _swig_setattr_nondynamic_class_variable(type.__setattr__)
class _SwigNonDynamicMeta(type):
"""Meta class to enforce nondynamic attributes (no new attributes) for a class""" __setattr__ = _swig_setattr_nondynamic_class_variable(type.__setattr__)
): """Class decorator for adding a metaclass to a SWIG wrapped class - a slimmed down version of six.add_metaclass""" def wrapper(cls): return metaclass(cls.__name__, cls.__bases__, cls.__dict__.copy()) return wrapper class _SwigNonDynamicMeta(type):
64
64
48
9
54
GabrielJie/PyMFEM
mfem/_par/fe_h1.py
Python
_SwigNonDynamicMeta
_SwigNonDynamicMeta
62
64
62
62
c86e0990c06bcd081781abf4416833e9a149f7cc
bigcode/the-stack
train
a20ef312195948362fee8bf2
train
class
class H1_TriangleElement(mfem._par.fe_base.NodalFiniteElement): r"""Proxy of C++ mfem::H1_TriangleElement class.""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self, *args, **kwargs): r"""__init__(H1_Trian...
class H1_TriangleElement(mfem._par.fe_base.NodalFiniteElement):
r"""Proxy of C++ mfem::H1_TriangleElement class.""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self, *args, **kwargs): r"""__init__(H1_TriangleElement self, int const p, int const btype=GaussLobatto) -> H...
int vertex, Vector dofs)""" return _fe_h1.H1_HexahedronElement_ProjectDelta(self, vertex, dofs) ProjectDelta = _swig_new_instance_method(_fe_h1.H1_HexahedronElement_ProjectDelta) __swig_destroy__ = _fe_h1.delete_H1_HexahedronElement # Register H1_HexahedronElement in _fe_h1: _fe_h1.H1_HexahedronElemen...
122
122
409
18
104
GabrielJie/PyMFEM
mfem/_par/fe_h1.py
Python
H1_TriangleElement
H1_TriangleElement
184
208
184
184
c619cfd353d78d04701fdf6fb37747a69a47b32b
bigcode/the-stack
train
87e5532fb1c16fd3eb555f4f
train
function
def _swig_setattr_nondynamic_class_variable(set): def set_class_attr(cls, name, value): if hasattr(cls, name) and not isinstance(getattr(cls, name), property): set(cls, name, value) else: raise AttributeError("You cannot add class attributes to %s" % cls) return set_class...
def _swig_setattr_nondynamic_class_variable(set):
def set_class_attr(cls, name, value): if hasattr(cls, name) and not isinstance(getattr(cls, name), property): set(cls, name, value) else: raise AttributeError("You cannot add class attributes to %s" % cls) return set_class_attr
elif hasattr(self, name) and isinstance(getattr(type(self), name), property): set(self, name, value) else: raise AttributeError("You cannot add instance attributes to %s" % self) return set_instance_attr def _swig_setattr_nondynamic_class_variable(set):
64
64
76
13
50
GabrielJie/PyMFEM
mfem/_par/fe_h1.py
Python
_swig_setattr_nondynamic_class_variable
_swig_setattr_nondynamic_class_variable
46
52
46
46
33b34280e77841c0c10b90b3d57e90eff7202a84
bigcode/the-stack
train
15620bc9687d6844e3f33589
train
function
def _swig_add_metaclass(metaclass): """Class decorator for adding a metaclass to a SWIG wrapped class - a slimmed down version of six.add_metaclass""" def wrapper(cls): return metaclass(cls.__name__, cls.__bases__, cls.__dict__.copy()) return wrapper
def _swig_add_metaclass(metaclass):
"""Class decorator for adding a metaclass to a SWIG wrapped class - a slimmed down version of six.add_metaclass""" def wrapper(cls): return metaclass(cls.__name__, cls.__bases__, cls.__dict__.copy()) return wrapper
): if hasattr(cls, name) and not isinstance(getattr(cls, name), property): set(cls, name, value) else: raise AttributeError("You cannot add class attributes to %s" % cls) return set_class_attr def _swig_add_metaclass(metaclass):
64
64
65
11
52
GabrielJie/PyMFEM
mfem/_par/fe_h1.py
Python
_swig_add_metaclass
_swig_add_metaclass
55
59
55
55
cbddae4380252f98610304463a78350d60714e43
bigcode/the-stack
train
eeac39f8480339591b2c357d
train
class
class H1_HexahedronElement(mfem._par.fe_base.NodalTensorFiniteElement): r"""Proxy of C++ mfem::H1_HexahedronElement class.""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self, *args, **kwargs): r"""__init_...
class H1_HexahedronElement(mfem._par.fe_base.NodalTensorFiniteElement):
r"""Proxy of C++ mfem::H1_HexahedronElement class.""" thisown = property(lambda x: x.this.own(), lambda x, v: x.this.own(v), doc="The membership flag") __repr__ = _swig_repr def __init__(self, *args, **kwargs): r"""__init__(H1_HexahedronElement self, int const p, int const btype=GaussLobatto) ...
essian) def ProjectDelta(self, vertex, dofs): r"""ProjectDelta(H1_QuadrilateralElement self, int vertex, Vector dofs)""" return _fe_h1.H1_QuadrilateralElement_ProjectDelta(self, vertex, dofs) ProjectDelta = _swig_new_instance_method(_fe_h1.H1_QuadrilateralElement_ProjectDelta) __swig_destro...
150
150
502
20
130
GabrielJie/PyMFEM
mfem/_par/fe_h1.py
Python
H1_HexahedronElement
H1_HexahedronElement
150
179
150
150
ffe493abff17250602605c1b33588620679a008e
bigcode/the-stack
train
cd5f88360b1c76dc519ec3fc
train
class
class condGANTrainer(object): def __init__(self, output_dir, data_loader, n_words, ixtoword): if cfg.TRAIN.FLAG: self.model_dir = os.path.join(output_dir, 'Model') self.image_dir = os.path.join(output_dir, 'Image') mkdir_p(self.model_dir) mkdir_p(self.image_di...
class condGANTrainer(object):
def __init__(self, output_dir, data_loader, n_words, ixtoword): if cfg.TRAIN.FLAG: self.model_dir = os.path.join(output_dir, 'Model') self.image_dir = os.path.join(output_dir, 'Image') mkdir_p(self.model_dir) mkdir_p(self.image_dir) torch.cuda.set_dev...
from __future__ import print_function from six.moves import range import torch import torch.nn as nn import torch.optim as optim from torch.autograd import Variable import torch.backends.cudnn as cudnn from PIL import Image from torch.utils.tensorboard import SummaryWriter from config import cfg from utils import mk...
173
256
4,649
6
167
LonglifeHyun/GANda_text-to-image
trainer.py
Python
condGANTrainer
condGANTrainer
29
511
29
29
0e1668be715acccc80dd383bf4d20ac7358d4f3b
bigcode/the-stack
train
10bdb2f43b25b2a175e650e0
train
function
def get_dispatch_handler(smartapp): """Get a handler to mock in the dispatcher.""" async def handler(req, resp, app): handler.fired = True assert app == smartapp handler.fired = False return handler
def get_dispatch_handler(smartapp):
"""Get a handler to mock in the dispatcher.""" async def handler(req, resp, app): handler.fired = True assert app == smartapp handler.fired = False return handler
"""Load a fixtures file.""" file_name = F"tests/fixtures/{file}.{ext}" with open(file_name, encoding="utf-8") as open_file: if ext == 'json': return json.load(open_file) return open_file.read() def get_dispatch_handler(smartapp):
64
64
54
8
56
andrewsayre/pysmartapp
tests/utilities.py
Python
get_dispatch_handler
get_dispatch_handler
14
20
14
14
53f9b983c41eff9095099706b416b6648ac3b267
bigcode/the-stack
train
8726cace500c313209d48c32
train
function
def get_fixture(file: str, ext: str = 'json'): """Load a fixtures file.""" file_name = F"tests/fixtures/{file}.{ext}" with open(file_name, encoding="utf-8") as open_file: if ext == 'json': return json.load(open_file) return open_file.read()
def get_fixture(file: str, ext: str = 'json'):
"""Load a fixtures file.""" file_name = F"tests/fixtures/{file}.{ext}" with open(file_name, encoding="utf-8") as open_file: if ext == 'json': return json.load(open_file) return open_file.read()
"""Testing utilities.""" import json def get_fixture(file: str, ext: str = 'json'):
21
64
71
14
6
andrewsayre/pysmartapp
tests/utilities.py
Python
get_fixture
get_fixture
5
11
5
5
727f511fe262664c1bfa1f6fab962b8db3820a32
bigcode/the-stack
train
dd17a718482e9af7bc807f03
train
class
class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('recipients', '0008_mealrequest_major_intersection'), ] operations = [ migrations.RemoveField( model_name='mealrequest', name='major_intersect...
class Migration(migrations.Migration):
dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('recipients', '0008_mealrequest_major_intersection'), ] operations = [ migrations.RemoveField( model_name='mealrequest', name='major_intersection', ), migrations.AddF...
# Generated by Django 3.1.2 on 2020-11-16 03:01 import core.models from django.conf import settings from django.db import migrations, models import django.db.models.deletion import uuid class Migration(migrations.Migration):
58
151
505
7
50
tibet5/website
website/recipients/migrations/0009_auto_20201116_0301.py
Python
Migration
Migration
10
53
10
11
cc694e5a79d6a172d0b1f0d4c80e22ccd0cfc6b5
bigcode/the-stack
train
164e24e7998657c5dc904724
train
class
@torch.jit.script # noqa: B903 class FooSameName(object): def __init__(self, x): self.x = x self.nested = bar.FooSameName(x)
@torch.jit.script # noqa: B903 class FooSameName(object):
def __init__(self, x): self.x = x self.nested = bar.FooSameName(x)
import torch from . import bar # This file contains definitions of script classes. # They are used by test_jit.py to test ScriptClass imports @torch.jit.script # noqa: B903 class FooSameName(object):
50
64
45
18
31
Hacky-DH/pytorch
test/jit/_imported_class_test/foo.py
Python
FooSameName
FooSameName
7
11
7
8
362967660613efc643bf5e8b1f17c422db903597
bigcode/the-stack
train
d667437a4c9472139d7502f7
train
function
def read_lexicon(lex_path): lexicon = {} with open(lex_path) as f: for line in f: temp = re.split(r"\s+", line.strip("\n")) word = temp[0] phones = temp[1:] if word.lower() not in lexicon: lexicon[word.lower()] = phones return lexicon
def read_lexicon(lex_path):
lexicon = {} with open(lex_path) as f: for line in f: temp = re.split(r"\s+", line.strip("\n")) word = temp[0] phones = temp[1:] if word.lower() not in lexicon: lexicon[word.lower()] = phones return lexicon
Parameters from ctc_segmentation import prepare_token_list import tgt, re from pypinyin import pinyin, Style from data.text import TextToTokens from data.text.tokenizer import Phonemizer, Tokenizer from data.audio import Audio def read_lexicon(lex_path):
64
64
82
9
54
taylorlu/dulcet
fa_test.py
Python
read_lexicon
read_lexicon
16
25
16
16
f36b0d30dad726a7faa194bb99cb5b81bb5b1c3c
bigcode/the-stack
train
6d58d0b3a7d1f757b48740bd
train
class
class Champion: def __init__(self, name, chest): self.name = name self.chest = chest self.image = Image.open("C:\\Riot Games\\League of Legends\\RADS\\projects\\lol_air_client\\releases\\" + imagesVersion + "\\deploy\\assets\\images\\champions\\" + name + "_Square_0.png") self.f...
class Champion:
def __init__(self, name, chest): self.name = name self.chest = chest self.image = Image.open("C:\\Riot Games\\League of Legends\\RADS\\projects\\lol_air_client\\releases\\" + imagesVersion + "\\deploy\\assets\\images\\champions\\" + name + "_Square_0.png") self.frameImg = Image.o...
col].show(self.frame, row, col) return buttons def onFrameConfigure(self, event): '''Reset the scroll region to encompass the inner frame''' self.canvas.configure(scrollregion=self.canvas.bbox("all")) def bound_to_mousewheel(self, event): self.canvas.bind_all("<MouseWh...
128
129
431
3
125
Aliamondo/ChampionChests
main.pyw
Python
Champion
Champion
109
145
109
109
95c1fe6f185d96f5ccc3b264532ac0912f50c7de
bigcode/the-stack
train
4782a8043b78a9f5d886b5d4
train
class
class View(tk.Frame): def __init__(self, root): tk.Frame.__init__(self, root) self.canvas = tk.Canvas(root, borderwidth=0, background="#ffffff") self.frame = tk.Frame(self.canvas, background="#ffffff") self.vsb = tk.Scrollbar(root, orient="vertical", command=self.canvas.yview)...
class View(tk.Frame):
def __init__(self, root): tk.Frame.__init__(self, root) self.canvas = tk.Canvas(root, borderwidth=0, background="#ffffff") self.frame = tk.Frame(self.canvas, background="#ffffff") self.vsb = tk.Scrollbar(root, orient="vertical", command=self.canvas.yview) self.canvas.c...
import tkinter as tk from tkinter import simpledialog import math from PIL import Image, ImageTk import pickle import os class View(tk.Frame):
34
231
773
6
27
Aliamondo/ChampionChests
main.pyw
Python
View
View
8
106
8
8
2064c85a2bcbfa3600c2fd4df01e843209b4372c
bigcode/the-stack
train
68823404200eafc874239226
train
function
def center(win): win.update_idletasks() width = win.winfo_width() height = win.winfo_height() x = (win.winfo_screenwidth() // 2) - (width // 2) y = (win.winfo_screenheight() // 2) - (height // 2) win.geometry('{}x{}+{}+{}'.format(width, height, x, y))
def center(win):
win.update_idletasks() width = win.winfo_width() height = win.winfo_height() x = (win.winfo_screenwidth() // 2) - (width // 2) y = (win.winfo_screenheight() // 2) - (height // 2) win.geometry('{}x{}+{}+{}'.format(width, height, x, y))
.delete(tk.ANCHOR) def newUser(): new = simpledialog.askstring("Input name", "New user name") #print(new) open("users/" + new + ".txt", 'a').close() listbox.insert(tk.END, new) def center(win):
63
64
88
4
59
Aliamondo/ChampionChests
main.pyw
Python
center
center
164
170
164
164
660b105ff83b8a5aceecbcfc04287886a9b6cb95
bigcode/the-stack
train
04dcabd65957423a69592ba1
train
function
def newUser(): new = simpledialog.askstring("Input name", "New user name") #print(new) open("users/" + new + ".txt", 'a').close() listbox.insert(tk.END, new)
def newUser():
new = simpledialog.askstring("Input name", "New user name") #print(new) open("users/" + new + ".txt", 'a').close() listbox.insert(tk.END, new)
.curselection()[0]) #print(currentUser) rootSelect.destroy() def deleteUser(): currentUser = listbox.get(listbox.curselection()[0]) os.remove("users/" + currentUser + ".txt") listbox.delete(tk.ANCHOR) def newUser():
64
64
51
4
60
Aliamondo/ChampionChests
main.pyw
Python
newUser
newUser
158
162
158
158
7c8b39a605e0a75e90b2c197b2b7a19b83351c0b
bigcode/the-stack
train
dcd1cef8e2c265aded081aa0
train
function
def selectUser(self): global currentUser, listbox currentUser = listbox.get(listbox.curselection()[0]) #print(currentUser) rootSelect.destroy()
def selectUser(self):
global currentUser, listbox currentUser = listbox.get(listbox.curselection()[0]) #print(currentUser) rootSelect.destroy()
: if pair[0] == self.name: pair[1] = self.chest #print(self.name + " chest status: " + str(self.chest)) pickle.dump(chests, open("users/" + currentUser + ".txt", "wb")) def selectUser(self):
63
64
39
5
58
Aliamondo/ChampionChests
main.pyw
Python
selectUser
selectUser
147
151
147
147
72241b8b835df450ada954348b0f5e3d587e58fb
bigcode/the-stack
train
927fb437165201854d2f03c0
train
function
def deleteUser(): currentUser = listbox.get(listbox.curselection()[0]) os.remove("users/" + currentUser + ".txt") listbox.delete(tk.ANCHOR)
def deleteUser():
currentUser = listbox.get(listbox.curselection()[0]) os.remove("users/" + currentUser + ".txt") listbox.delete(tk.ANCHOR)
pickle.dump(chests, open("users/" + currentUser + ".txt", "wb")) def selectUser(self): global currentUser, listbox currentUser = listbox.get(listbox.curselection()[0]) #print(currentUser) rootSelect.destroy() def deleteUser():
64
64
43
4
60
Aliamondo/ChampionChests
main.pyw
Python
deleteUser
deleteUser
153
156
153
153
3dffa342b6856e2a7e5103ffec6093d913c0efb7
bigcode/the-stack
train
b4dbe9ce172b2693e9877b92
train
class
class TestREParse(unittest.TestCase): def test_parseRegex(self): """ Parsing substitution regex syntax should result in something that correctly performs substitution and obeys the flags passed in. """ s = reparse.parseRegex('s/foo/bar/g') self.assertEqual(s.sub('quux...
class TestREParse(unittest.TestCase):
def test_parseRegex(self): """ Parsing substitution regex syntax should result in something that correctly performs substitution and obeys the flags passed in. """ s = reparse.parseRegex('s/foo/bar/g') self.assertEqual(s.sub('quuxfooquux'), 'quuxbarquux') self...
from twisted.trial import unittest from eridanus import errors, reparse class TestREParse(unittest.TestCase):
25
67
224
8
16
mithrandi/eridanus
eridanus/test/test_reparse.py
Python
TestREParse
TestREParse
6
25
6
6
788c935ec0bafd953d030e82694383938b60bbac
bigcode/the-stack
train
7a19fc140d3e43cd83a16f05
train
class
class policy_node(graph_node): __policy_document = {} __policy_summary = None def is_principal(self): return False def get_services_allowed(self): response = {} services = self.__policy_summary.action_summary().keys() for service in services: response[servic...
class policy_node(graph_node):
__policy_document = {} __policy_summary = None def is_principal(self): return False def get_services_allowed(self): response = {} services = self.__policy_summary.action_summary().keys() for service in services: response[service] = [self.name()] retu...
_graph[policy["PolicyArn"]] self.add_child(policy_node) policy_node.add_parent(self) for policy in auth.get("GroupPolicyList", []): policy_node = inline_policy_node(self, policy) auth_graph[policy_node.key()] = policy_node class policy_node(graph_node):
64
64
99
6
57
LeeJCherry/cloudmapper
commands/iam_report.py
Python
policy_node
policy_node
276
292
276
276
86ab2ca2dcbdb40b502f0ecc4d7a9980ea164188
bigcode/the-stack
train
5f28dddbb09b555ed54a7363
train
class
class user_node(graph_node): __auth = None def is_principal(self): return True def get_type(self): return "user" def __init__(self, auth, auth_graph): super().__init__() self.set_key(auth["Arn"]) self.set_name(auth["UserName"]) self.__auth = auth ...
class user_node(graph_node):
__auth = None def is_principal(self): return True def get_type(self): return "user" def __init__(self, auth, auth_graph): super().__init__() self.set_key(auth["Arn"]) self.set_name(auth["UserName"]) self.__auth = auth for policy in auth["Attach...
for s in source: source_path.append("{}.{}".format(self.name(), s)) source_list.extend(source_path) services[service] = source_list return services def __init__(self): self.__children = [] self.__parents = [] class user_node(graph_nod...
63
64
203
6
57
LeeJCherry/cloudmapper
commands/iam_report.py
Python
user_node
user_node
201
229
201
201
5af2f25dc598ee5d217d06d99a84b5e5966c5113
bigcode/the-stack
train
1f61e6498acd8ff4d5280f0e
train
function
def get_service_count_and_used(service_last_accessed): service_count = 0 service_used_count = 0 for service_last_access in service_last_accessed: service_count += 1 if service_last_access["TotalAuthenticatedEntities"] > 0: service_used_count += 1 return {"service_count": serv...
def get_service_count_and_used(service_last_accessed):
service_count = 0 service_used_count = 0 for service_last_access in service_last_accessed: service_count += 1 if service_last_access["TotalAuthenticatedEntities"] > 0: service_used_count += 1 return {"service_count": service_count, "service_used_count": service_used_count}
( job_completion_date - last_access_date ).days if service["days_since_last_use"] < args.max_age: stats["is_inactive"] = False break principal_stats[principal_auth["Arn"]] = stats def get_service_count_and_used(service...
64
64
84
11
52
LeeJCherry/cloudmapper
commands/iam_report.py
Python
get_service_count_and_used
get_service_count_and_used
117
124
117
117
046101a9277e8230c96c8da3f52c24f07cf69a9c
bigcode/the-stack
train
be7e556173ab42ac07cf5219
train
function
def get_access_advisor(region, principal_stats, json_account_auth_details, args): for principal_auth in [ *json_account_auth_details["UserDetailList"], *json_account_auth_details["RoleDetailList"], ]: stats = {} stats["auth"] = principal_auth job_id = get_parameter_file( ...
def get_access_advisor(region, principal_stats, json_account_auth_details, args):
for principal_auth in [ *json_account_auth_details["UserDetailList"], *json_account_auth_details["RoleDetailList"], ]: stats = {} stats["auth"] = principal_auth job_id = get_parameter_file( region, "iam", "generate-service-last-accessed...
_key_2_last_used_service": parts[17], "cert_1_active": parts[18], "cert_1_last_rotated": parts[19], "cert_2_active": parts[20], "cert_2_last_rotated": parts[21], } users.append[user] return users def get_access_advisor(region, principal_stats, json_acc...
87
87
293
17
69
LeeJCherry/cloudmapper
commands/iam_report.py
Python
get_access_advisor
get_access_advisor
78
114
78
78
9c4a402052ec299d1d8b00d17639c220b1dee8f4
bigcode/the-stack
train
8351963d1ab82297b671160f
train
function
def build_cytoscape_graph(iam_graph): cytoscape_json = [] for k in iam_graph: node = iam_graph[k] if len(node.children()) > 0 or len(node.parents()) > 0: cytoscape_json.append(iam_graph[k].cytoscape_data()) for k in iam_graph: node = iam_graph[k] for child in nod...
def build_cytoscape_graph(iam_graph):
cytoscape_json = [] for k in iam_graph: node = iam_graph[k] if len(node.children()) > 0 or len(node.parents()) > 0: cytoscape_json.append(iam_graph[k].cytoscape_data()) for k in iam_graph: node = iam_graph[k] for child in node.children(): edge = { ...
in auth["UserDetailList"]: iam_graph[user["Arn"]] = user_node(user, iam_graph) for role in auth["RoleDetailList"]: iam_graph[role["Arn"]] = role_node(role, iam_graph) return iam_graph def build_cytoscape_graph(iam_graph):
64
64
131
11
52
LeeJCherry/cloudmapper
commands/iam_report.py
Python
build_cytoscape_graph
build_cytoscape_graph
342
357
342
342
ac11e8bf23bcb26c81e0609f1e12eba40fba4e86
bigcode/the-stack
train
7a2f14c218373c8d5aa21b7c
train
class
class OutputFormat(Enum): json = "json" html = "html"
class OutputFormat(Enum):
json = "json" html = "html"
from jinja2 import Template from enum import Enum from policyuniverse.policy import Policy from shared.common import parse_arguments, get_regions from shared.query import query_aws, get_parameter_file from shared.nodes import Account, Region __description__ = "Create IAM report" class OutputFormat(Enum):
64
64
17
5
59
LeeJCherry/cloudmapper
commands/iam_report.py
Python
OutputFormat
OutputFormat
19
21
19
19
4af85272e65b7a46adfe6322c32308216c3ef381
bigcode/the-stack
train
98d5a4f5a4ca44d6491111ee
train
function
def html_service_chart(principal, services_used, services_granted): chartid = "serviceChart" + principal return ( '<div style="width:30%"><canvas id="{}" width="100" height="15"></canvas></div>' + '<script>makeServiceUnusedChart("{}", {}, {});</script>' ).format(chartid, chartid, services_us...
def html_service_chart(principal, services_used, services_granted):
chartid = "serviceChart" + principal return ( '<div style="width:30%"><canvas id="{}" width="100" height="15"></canvas></div>' + '<script>makeServiceUnusedChart("{}", {}, {});</script>' ).format(chartid, chartid, services_used, services_granted - services_used)
_accessed: service_count += 1 if service_last_access["TotalAuthenticatedEntities"] > 0: service_used_count += 1 return {"service_count": service_count, "service_used_count": service_used_count} def html_service_chart(principal, services_used, services_granted):
64
64
91
14
50
LeeJCherry/cloudmapper
commands/iam_report.py
Python
html_service_chart
html_service_chart
127
132
127
127
bdbc3350805fbec152dfc9fb85bd2148b86b1b10
bigcode/the-stack
train
c3193716b46038df450837e2
train
class
class role_node(graph_node): def is_principal(self): return True def get_type(self): return "role" def __init__(self, auth, auth_graph): super().__init__() self.set_key(auth["Arn"]) self.set_name(auth["RoleName"]) for policy in auth["AttachedManagedPolicies...
class role_node(graph_node):
def is_principal(self): return True def get_type(self): return "role" def __init__(self, auth, auth_graph): super().__init__() self.set_key(auth["Arn"]) self.set_name(auth["RoleName"]) for policy in auth["AttachedManagedPolicies"]: policy_node =...
policy_node for group_name in auth.get("GroupList", []): group_key = self.key()[0:26] + "group/" + group_name group_node = auth_graph[group_key] group_node.add_parent(self) self.add_child(group_node) class role_node(graph_node):
64
64
135
6
58
LeeJCherry/cloudmapper
commands/iam_report.py
Python
role_node
role_node
232
251
232
232
d7530067784b6c255ad4009a58a09618c93d89b3
bigcode/the-stack
train
43555ff5045d766e321b697b
train
class
@add_metaclass(ABCMeta) class graph_node(object): __key = "" __children = None __parents = None __name = "" def cytoscape_data(self): response = { "data": {"id": self.key(), "name": self.name(), "type": self.get_type()} } return response def key(self): ...
@add_metaclass(ABCMeta) class graph_node(object):
__key = "" __children = None __parents = None __name = "" def cytoscape_data(self): response = { "data": {"id": self.key(), "name": self.name(), "type": self.get_type()} } return response def key(self): return self.__key def set_key(self, key):...
incipal, services_used, services_granted): chartid = "serviceChart" + principal return ( '<div style="width:30%"><canvas id="{}" width="100" height="15"></canvas></div>' + '<script>makeServiceUnusedChart("{}", {}, {});</script>' ).format(chartid, chartid, services_used, services_granted - se...
99
99
330
13
86
LeeJCherry/cloudmapper
commands/iam_report.py
Python
graph_node
graph_node
135
198
135
136
72f18444af8f97868b16fcc8548a1b41dcd9fa79
bigcode/the-stack
train
6e79eb647a729929b8cd1131
train
function
def iam_report(accounts, config, args): """Create IAM report""" principal_stats = {} json_account_auth_details = None # Ensure only one account is given if len(accounts) > 1: raise Exception("This command only works with one account at a time") account = accounts.pop() # Create dir...
def iam_report(accounts, config, args):
"""Create IAM report""" principal_stats = {} json_account_auth_details = None # Ensure only one account is given if len(accounts) > 1: raise Exception("This command only works with one account at a time") account = accounts.pop() # Create directory for output file if it doesn't alr...
policy_version in policy["PolicyVersionList"]: if policy_version["IsDefaultVersion"]: iam_graph[policy["Arn"]].set_policy_document(policy_version["Document"]) for group in auth["GroupDetailList"]: iam_graph[group["Arn"]] = group_node(group, iam_graph) for user in auth["Use...
256
256
2,064
9
246
LeeJCherry/cloudmapper
commands/iam_report.py
Python
iam_report
iam_report
360
632
360
360
0f81f3a8fd7893751e6a475347d10f53319a9f65
bigcode/the-stack
train
548d0a87ff633640127c092b
train
function
def tolink(s): # TODO sanitize return s
def tolink(s): # TODO sanitize
return s
_file from shared.nodes import Account, Region __description__ = "Create IAM report" class OutputFormat(Enum): json = "json" html = "html" REPORT_OUTPUT_FILE = os.path.join("web", "account-data", "iam_report") def tolink(s): # TODO sanitize
64
64
14
10
54
LeeJCherry/cloudmapper
commands/iam_report.py
Python
tolink
tolink
27
29
27
28
1394551c47d5bf8b370b62b78d56c6158f52e34a
bigcode/the-stack
train
17259f42cd479d7702dafd31
train
function
def load_credential_report(): users = [] json_blob = query_aws(region.account, "iam-get-credential-report", region) csv_lines = json_blob["Content"].split("\n") # Skip header csv_lines.pop(0) # Header: # user,arn,user_creation_time,password_enabled,password_last_used,password_last_changed...
def load_credential_report():
users = [] json_blob = query_aws(region.account, "iam-get-credential-report", region) csv_lines = json_blob["Content"].split("\n") # Skip header csv_lines.pop(0) # Header: # user,arn,user_creation_time,password_enabled,password_last_used,password_last_changed, # password_next_rotation...
import print_function import argparse import json import datetime import os.path from abc import ABCMeta from six import add_metaclass from jinja2 import Template from enum import Enum from policyuniverse.policy import Policy from shared.common import parse_arguments, get_regions from shared.query import query_aws, g...
144
144
480
6
137
LeeJCherry/cloudmapper
commands/iam_report.py
Python
load_credential_report
load_credential_report
32
75
32
32
079dac7b80ed363c2c1a2871a764c979462e932a
bigcode/the-stack
train
d284a1c9f6f1d41f87374671
train
function
def get_iam_graph(auth): iam_graph = {} for policy in auth["Policies"]: iam_graph[policy["Arn"]] = managed_policy_node(policy) for policy_version in policy["PolicyVersionList"]: if policy_version["IsDefaultVersion"]: iam_graph[policy["Arn"]].set_policy_document(polic...
def get_iam_graph(auth):
iam_graph = {} for policy in auth["Policies"]: iam_graph[policy["Arn"]] = managed_policy_node(policy) for policy_version in policy["PolicyVersionList"]: if policy_version["IsDefaultVersion"]: iam_graph[policy["Arn"]].set_policy_document(policy_version["Document"]) ...
, auth): super().__init__() self.set_key(parent.key() + "/policy/" + auth["PolicyName"]) self.set_key(auth["PolicyName"]) parent.add_child(self) self.add_parent(parent) self.set_policy_document(auth["PolicyDocument"]) def get_iam_graph(auth):
63
64
152
7
56
LeeJCherry/cloudmapper
commands/iam_report.py
Python
get_iam_graph
get_iam_graph
321
339
321
321
ba8f7da407bf13e80d1bc601ac412dc81846211f
bigcode/the-stack
train
1f68c1f241afa1b8e3bfa833
train
function
def run(arguments): parser = argparse.ArgumentParser() parser.add_argument( "--max-age", help="Number of days a user or role hasn't been used before it's marked dead", default=90, type=int, ) parser.add_argument( "--graph", help="Do not create and display ...
def run(arguments):
parser = argparse.ArgumentParser() parser.add_argument( "--max-age", help="Number of days a user or role hasn't been used before it's marked dead", default=90, type=int, ) parser.add_argument( "--graph", help="Do not create and display a graph", de...
=t)) elif args.requested_output == OutputFormat.json: with open("{}.json".format(REPORT_OUTPUT_FILE), "w") as f: json.dump(t, f) print("Report written to {}.{}".format(REPORT_OUTPUT_FILE, args.requested_output.value)) def run(arguments):
64
64
155
4
60
LeeJCherry/cloudmapper
commands/iam_report.py
Python
run
run
635
659
635
635
a902e4241e36775bc2899d6bed1ac9a08be452a2
bigcode/the-stack
train
a525092930c71540a3058fa0
train
class
class inline_policy_node(policy_node): def get_type(self): return "inline policy" def __init__(self, parent, auth): super().__init__() self.set_key(parent.key() + "/policy/" + auth["PolicyName"]) self.set_key(auth["PolicyName"]) parent.add_child(self) self.add_pa...
class inline_policy_node(policy_node):
def get_type(self): return "inline policy" def __init__(self, parent, auth): super().__init__() self.set_key(parent.key() + "/policy/" + auth["PolicyName"]) self.set_key(auth["PolicyName"]) parent.add_child(self) self.add_parent(parent) self.set_policy_do...
self, auth): super().__init__() self.set_key(auth["Arn"]) self.set_name(auth["PolicyName"]) for policy_doc in auth["PolicyVersionList"]: if policy_doc["IsDefaultVersion"]: self.set_policy_document(policy_doc["Document"]) class inline_policy_node(policy_node):
63
64
83
7
56
LeeJCherry/cloudmapper
commands/iam_report.py
Python
inline_policy_node
inline_policy_node
308
318
308
308
bd636bb10e7bfb5f112bee4b5dbcd3a4702c989c
bigcode/the-stack
train
d1898024c3cd77722d53b928
train
class
class managed_policy_node(policy_node): def get_type(self): return "managed policy" def __init__(self, auth): super().__init__() self.set_key(auth["Arn"]) self.set_name(auth["PolicyName"]) for policy_doc in auth["PolicyVersionList"]: if policy_doc["IsDefaultV...
class managed_policy_node(policy_node):
def get_type(self): return "managed policy" def __init__(self, auth): super().__init__() self.set_key(auth["Arn"]) self.set_name(auth["PolicyName"]) for policy_doc in auth["PolicyVersionList"]: if policy_doc["IsDefaultVersion"]: self.set_polic...
services = self.__policy_summary.action_summary().keys() for service in services: response[service] = [self.name()] return response def set_policy_document(self, doc): self.__policy_document = doc self.__policy_summary = Policy(doc) class managed_policy_node(policy_node...
64
64
80
7
57
LeeJCherry/cloudmapper
commands/iam_report.py
Python
managed_policy_node
managed_policy_node
295
305
295
295
42886f60606f45dbd125db665c56e3f142a36bd1
bigcode/the-stack
train
0d970df82c948576a6544307
train
class
class group_node(graph_node): def is_principal(self): return False def get_type(self): return "group" def __init__(self, auth, auth_graph): super().__init__() self.set_key(auth["Arn"]) self.set_name(auth["GroupName"]) for policy in auth["AttachedManagedPoli...
class group_node(graph_node):
def is_principal(self): return False def get_type(self): return "group" def __init__(self, auth, auth_graph): super().__init__() self.set_key(auth["Arn"]) self.set_name(auth["GroupName"]) for policy in auth["AttachedManagedPolicies"]: policy_nod...
_graph[policy["PolicyArn"]] self.add_child(policy_node) policy_node.add_parent(self) for policy in auth.get("RolePolicyList", []): policy_node = inline_policy_node(self, policy) auth_graph[policy_node.key()] = policy_node class group_node(graph_node):
64
64
135
6
57
LeeJCherry/cloudmapper
commands/iam_report.py
Python
group_node
group_node
254
273
254
254
8aa460f3255af111f26553d5c94ab89d578829a2
bigcode/the-stack
train
6644b8b2baad885243743ec0
train
class
class SqliteUsers(SqliteTable): def __init__(self, conn): self._name = 'users' self._fields = [{'name': 'user_id', 'type': 'str', 'default': ''}, {'name': 'email', 'type': 'str', 'default': ''}, {'name': 'name', 'type': 'str', 'default': ''}, ...
class SqliteUsers(SqliteTable):
def __init__(self, conn): self._name = 'users' self._fields = [{'name': 'user_id', 'type': 'str', 'default': ''}, {'name': 'email', 'type': 'str', 'default': ''}, {'name': 'name', 'type': 'str', 'default': ''}, {'name': 'al...
from .sqlitetable import SqliteTable from datetime import datetime import pytz class SqliteUsers(SqliteTable):
27
256
1,343
8
18
fjacob21/mididecweb
backend/src/stores/sqlite/sqliteusers.py
Python
SqliteUsers
SqliteUsers
6
127
6
7
29fdb46305705c31c2033abff4d16f948ef8d5f6
bigcode/the-stack
train
b09686e2e9dc4d5a2fc554a4
train
function
def _resolve_paths_recursively(config_dict: dict, parent: str) -> None: """Resolve relative paths in values of config dict. Only strings starting with ./, ../, ~/ are handled, since general strings might otherwise be falsely handled as paths. """ for key, value in config_dict.items(): if is...
def _resolve_paths_recursively(config_dict: dict, parent: str) -> None:
"""Resolve relative paths in values of config dict. Only strings starting with ./, ../, ~/ are handled, since general strings might otherwise be falsely handled as paths. """ for key, value in config_dict.items(): if isinstance(config_dict[key], dict): _resolve_paths_recursively...
added_dict[key], dict) ): merged_dictionary[key] = _merge_dictionaries( start_dict[key], added_dict[key] ) else: merged_dictionary[key] = value return merged_dictionary def _resolve_paths_recursively(config_dict: dict, parent: str) -> None:
64
64
153
18
45
roym899/yoco
yoco.py
Python
_resolve_paths_recursively
_resolve_paths_recursively
341
355
341
341
ecd511498c51f4896466ddaba28554e6fe94fa2c
bigcode/the-stack
train
b3b22f2663f4249cd85fa9b8
train
function
def _merge_dictionaries(start_dict: dict, added_dict: dict) -> dict: """Create a dictionary by merging one into another. Keys present in start_dict will be overwritten by added_dict. Args: start_dict: The starting dictionary. added_dict: The dictionary to merge into current_dictionary. ...
def _merge_dictionaries(start_dict: dict, added_dict: dict) -> dict:
"""Create a dictionary by merging one into another. Keys present in start_dict will be overwritten by added_dict. Args: start_dict: The starting dictionary. added_dict: The dictionary to merge into current_dictionary. Returns: The merged dictionary. """ merged_dictiona...
element, current_dict, parent, search_paths ) elif isinstance(element, dict): current_dict = _resolve_config_dict( element, current_dict, parent, search_paths ) return current_dict def _merge_dictionaries(start_dict: dict, added_dict: dict) -> dict:
64
64
162
18
45
roym899/yoco
yoco.py
Python
_merge_dictionaries
_merge_dictionaries
314
338
314
314
74e9498d85eb1261a8c4e90e55eb9f77b7444575
bigcode/the-stack
train
ddbc8f9063a6285650ebde0a
train
function
def _resolve_config_dict( config_dict: list, current_dict: dict, parent: str, search_paths: List[str] ) -> None: for ns, element in config_dict.items(): if ns not in current_dict: current_dict[ns] = {} if isinstance(element, str): current_dict[ns] = load_config_from_file(...
def _resolve_config_dict( config_dict: list, current_dict: dict, parent: str, search_paths: List[str] ) -> None:
for ns, element in config_dict.items(): if ns not in current_dict: current_dict[ns] = {} if isinstance(element, str): current_dict[ns] = load_config_from_file( element, current_dict[ns], parent, search_paths ) elif isinstance(element, list)...
"], current_dict, parent, search_paths ) else: raise TypeError("Can't parse element of type {type(config_dict['config'])}") def _resolve_config_dict( config_dict: list, current_dict: dict, parent: str, search_paths: List[str] ) -> None:
63
64
164
31
32
roym899/yoco
yoco.py
Python
_resolve_config_dict
_resolve_config_dict
274
292
274
276
6e481dc09bb9190daab0955fd4cf48e3f5fff485
bigcode/the-stack
train
8895fa1e242fa0310defb6b0
train
function
def _resolve_config_key( config_dict: dict, current_dict: dict, parent: str, search_paths: List[str] ) -> dict: # config can be string, list of strings, dict, or list of string / dict if isinstance(config_dict["config"], str): return load_config_from_file( config_dict["config"], current_...
def _resolve_config_key( config_dict: dict, current_dict: dict, parent: str, search_paths: List[str] ) -> dict: # config can be string, list of strings, dict, or list of string / dict
if isinstance(config_dict["config"], str): return load_config_from_file( config_dict["config"], current_dict, parent, search_paths ) elif isinstance(config_dict["config"], list): return _resolve_config_list( config_dict["config"], current_dict, parent, search_path...
") as f: _yaml.dump(config_dict, f) def _resolve_config_key( config_dict: dict, current_dict: dict, parent: str, search_paths: List[str] ) -> dict: # config can be string, list of strings, dict, or list of string / dict
64
64
171
51
13
roym899/yoco
yoco.py
Python
_resolve_config_key
_resolve_config_key
254
271
254
257
488b00efee1ab38635ff7a48ffb5d2de71bde30e
bigcode/the-stack
train
3bc316205bd92fbed66fd3e0
train
function
def _resolve_config_list( config_list: list, current_dict: dict, parent: str, search_paths: List[str] ) -> None: for element in config_list: if isinstance(element, str): current_dict = load_config_from_file( element, current_dict, parent, search_paths ) el...
def _resolve_config_list( config_list: list, current_dict: dict, parent: str, search_paths: List[str] ) -> None:
for element in config_list: if isinstance(element, str): current_dict = load_config_from_file( element, current_dict, parent, search_paths ) elif isinstance(element, list): current_dict = _resolve_config_list( element, current_dict,...
): current_dict[ns] = _resolve_config_dict( element, current_dict[ns], parent, search_paths ) return current_dict def _resolve_config_list( config_list: list, current_dict: dict, parent: str, search_paths: List[str] ) -> None:
64
64
130
31
32
roym899/yoco
yoco.py
Python
_resolve_config_list
_resolve_config_list
295
311
295
297
ae2b206e2b08ffda7c44462f70aa15b0a015153b
bigcode/the-stack
train
1a50a70d442ce63e35491b39
train
function
def load_config_from_args( parser: _argparse.ArgumentParser, args: Optional[list] = None, search_paths: Optional[List[str]] = None, ) -> dict: """Parse arguments and load configs into a config dictionary. Strings following -- will be used as key. Dots in that string are used to access nested di...
def load_config_from_args( parser: _argparse.ArgumentParser, args: Optional[list] = None, search_paths: Optional[List[str]] = None, ) -> dict:
"""Parse arguments and load configs into a config dictionary. Strings following -- will be used as key. Dots in that string are used to access nested dictionaries. YAML will be used for type conversion of the value. Args: parser: Parser used to parse known and unknown arguments. ...
"""This module contains all YOCO functions to load and save configurations. YOCO is based on Python dictionaries and YAML files to provide a simple, yet powerful way of configuring Python projects. YOCO supports specifying parameters through the command line, YAML-files or directly from a Python dictionary. """ import...
138
252
843
39
99
roym899/yoco
yoco.py
Python
load_config_from_args
load_config_from_args
17
105
17
21
7494bb60f19bfe2a417053f1daf5bbffeff0efe8
bigcode/the-stack
train
dce6c8d5ed1f44bbf8a38247
train
function
def save_config_to_file(path: str, config_dict: dict) -> None: """Save config dictionary as a yaml file.""" with open(path, "w") as f: _yaml.dump(config_dict, f)
def save_config_to_file(path: str, config_dict: dict) -> None:
"""Save config dictionary as a yaml file.""" with open(path, "w") as f: _yaml.dump(config_dict, f)
in search_paths: resolved_path = resolve_path(_os.path.join(search_path, path), parent, []) if _os.path.exists(resolved_path): return _os.path.normpath(resolved_path) return path def save_config_to_file(path: str, config_dict: dict) -> None:
64
64
47
17
46
roym899/yoco
yoco.py
Python
save_config_to_file
save_config_to_file
248
251
248
248
e7dd29a8af1dc3ae0b0c2e36c834ea8deb0df439
bigcode/the-stack
train
3f2fc380ede847bd87f62e3a
train
function
def load_config( config_dict: dict, current_dict: Optional[dict] = None, parent: Optional[str] = None, search_paths: Optional[List[str]] = None, ) -> dict: """Load a config dictionary. If a key is already in current_dict, config_dict will overwrite it. Args: config_dict: Configurat...
def load_config( config_dict: dict, current_dict: Optional[dict] = None, parent: Optional[str] = None, search_paths: Optional[List[str]] = None, ) -> dict:
"""Load a config dictionary. If a key is already in current_dict, config_dict will overwrite it. Args: config_dict: Configuration dictionary to be parsed. current_dict: Current configuration dictionary to be updated, will not be changed. parent: Path of parent config. U...
config_dict = _yaml.load(f) current_dict = load_config(config_dict, current_dict, parent, search_paths) return current_dict def load_config( config_dict: dict, current_dict: Optional[dict] = None, parent: Optional[str] = None, search_paths: Optional[List[str]] = None, ) -> dict:
76
76
256
45
30
roym899/yoco
yoco.py
Python
load_config
load_config
145
185
145
150
3e6d5d4815edecd0bc5eae3e2778f7655bb87de3
bigcode/the-stack
train
34a0676f5640fd85c591b753
train
function
def resolve_path( path: str, parent: Optional[str] = None, search_paths: Optional[List[str]] = None ) -> str: """Resolves a path to a full absolute path based on parent and search_paths. This function considers paths of 5 different cases: - `/...` Absolute path, nothing todo. - `~/...` Home dir, e...
def resolve_path( path: str, parent: Optional[str] = None, search_paths: Optional[List[str]] = None ) -> str:
"""Resolves a path to a full absolute path based on parent and search_paths. This function considers paths of 5 different cases: - `/...` Absolute path, nothing todo. - `~/...` Home dir, expand user. - `./...` Relative to parent (current directory if parent is None). - `../...` Relative to par...
more information. Returns: Loaded / updated configuration dictionary. """ config_dict = copy.deepcopy(config_dict) if current_dict is None: current_dict = {} else: current_dict = copy.deepcopy(current_dict) if "config" in config_dict: current_dict = _resolve_co...
157
157
524
31
125
roym899/yoco
yoco.py
Python
resolve_path
resolve_path
188
245
188
190
89d569d11fab2740b9fe92014dc901411988621b
bigcode/the-stack
train
357799f6a8a7e8fa0a8089a9
train
function
def load_config_from_file( path: str, current_dict: Optional[dict] = None, parent: Optional[str] = None, search_paths: Optional[List[str]] = None, ) -> dict: """Load configuration from a file. Args: path: Path of YAML file to load. current_dict: Current configuration...
def load_config_from_file( path: str, current_dict: Optional[dict] = None, parent: Optional[str] = None, search_paths: Optional[List[str]] = None, ) -> dict:
"""Load configuration from a file. Args: path: Path of YAML file to load. current_dict: Current configuration dictionary. Will not be modified. If None, an empty dictionary will be created. parent: Parent directory. If not None, path will ...
config_dict = _merge_dictionaries(with_default_config_dict, config_dict) return config_dict def load_config_from_file( path: str, current_dict: Optional[dict] = None, parent: Optional[str] = None, search_paths: Optional[List[str]] = None, ) -> dict:
66
66
220
46
19
roym899/yoco
yoco.py
Python
load_config_from_file
load_config_from_file
108
142
108
113
2a8a47aa4a0ecff652031661f7ce067b58c76b42
bigcode/the-stack
train