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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
8165330df44b617c21a5acdc | train | function | @app.route("/delete_thread", methods=["POST"])
def delete_thread():
if not session["csrf_token"] == request.form["csrf_token"]:
abort(403)
thread_id = request.form["thread_id"]
category_id = request.form["cat_id"]
if users.is_admin():
messages.delete_thread(thread_id)
r... | @app.route("/delete_thread", methods=["POST"])
def delete_thread():
| if not session["csrf_token"] == request.form["csrf_token"]:
abort(403)
thread_id = request.form["thread_id"]
category_id = request.form["cat_id"]
if users.is_admin():
messages.delete_thread(thread_id)
return redirect("/category/"+str(category_id))
| if not msg_deleted:
return render_template("error.html",
message="Lol yritit nokkelasti poistaa ketjun ensimmäisen viestin mutta etpä voi :P")
return redirect("/thread/"+str(thread_id))
@app.route("/delete_thread", methods=["POST"])
def delete_thread():
| 64 | 64 | 80 | 15 | 49 | Ronttikasa/foorumisovellus | routes.py | Python | delete_thread | delete_thread | 126 | 137 | 126 | 127 | 8a38ddc8540863c9d96b7af4d0579552358847e5 | bigcode/the-stack | train |
5974cda18722da69dcd6a929 | train | function | @app.route("/new_category", methods=["POST"])
def new_category():
if not session["csrf_token"] == request.form["csrf_token"]:
abort(403)
if not users.is_admin():
return render_template("error.html", message="Ei oikeutta luoda uutta aluetta")
name = request.form["category_name"]
gr... | @app.route("/new_category", methods=["POST"])
def new_category():
| if not session["csrf_token"] == request.form["csrf_token"]:
abort(403)
if not users.is_admin():
return render_template("error.html", message="Ei oikeutta luoda uutta aluetta")
name = request.form["category_name"]
group = request.form["group"]
category_added = messages.new_cat... | aluetta")
name = messages.get_category_name(id)
threads = messages.get_threads(id)
else:
return redirect("/")
return render_template("category.html", threads=threads, cat_id=id, cat_name=name)
@app.route("/new_category", methods=["POST"])
def new_category():
| 64 | 64 | 126 | 15 | 49 | Ronttikasa/foorumisovellus | routes.py | Python | new_category | new_category | 37 | 51 | 37 | 38 | 7667ff5a7b092def8921c725cc8837eadae51635 | bigcode/the-stack | train |
57c507708a5781145956337c | train | function | @app.route("/login", methods=["POST"])
def login():
username = request.form["username"]
password = request.form["password"]
if not users.login(username, password):
return render_template("error.html", message="Väärä käyttäjätunnus tai salasana.")
return redirect("/")
| @app.route("/login", methods=["POST"])
def login():
| username = request.form["username"]
password = request.form["password"]
if not users.login(username, password):
return render_template("error.html", message="Väärä käyttäjätunnus tai salasana.")
return redirect("/")
| ", message=error_message)
if not users.register(username, password):
return render_template("error.html", message="Käyttäjätunnus on jo käytössä.")
users.login(username, password)
return redirect("/")
@app.route("/login", methods=["POST"])
def login():
| 63 | 64 | 67 | 13 | 50 | Ronttikasa/foorumisovellus | routes.py | Python | login | login | 160 | 168 | 160 | 161 | 76009a180e38568313c2a34209d1ef4cdadabea1 | bigcode/the-stack | train |
494d4ede8767734a5fc05819 | train | function | @app.route("/thread/<int:id>")
def thread(id):
if session.get("username"):
header_data = messages.get_header_data(id)
if not header_data:
return render_template("error.html", message="Ketjua ei löytynyt")
category_id = header_data.id
user_id = session.get("user... | @app.route("/thread/<int:id>")
def thread(id):
| if session.get("username"):
header_data = messages.get_header_data(id)
if not header_data:
return render_template("error.html", message="Ketjua ei löytynyt")
category_id = header_data.id
user_id = session.get("user_id")
if not users.category_access(use... | request.form["group"]
category_added = messages.new_category(name, group)
if not category_added:
render_template("error.html", message="Nimi tai käyttäjäryhmän valinta puuttuu")
return index()
@app.route("/thread/<int:id>")
def thread(id):
| 64 | 64 | 154 | 13 | 51 | Ronttikasa/foorumisovellus | routes.py | Python | thread | thread | 53 | 72 | 53 | 54 | 9b00d9e1c2b190ee3d1ed4151330e1d8589163fe | bigcode/the-stack | train |
9385eac80ae57ea307c9c79a | train | function | @app.route("/logout")
def logout():
users.logout()
return redirect("/")
| @app.route("/logout")
def logout():
| users.logout()
return redirect("/")
| login():
username = request.form["username"]
password = request.form["password"]
if not users.login(username, password):
return render_template("error.html", message="Väärä käyttäjätunnus tai salasana.")
return redirect("/")
@app.route("/logout")
def logout():
| 63 | 64 | 17 | 8 | 55 | Ronttikasa/foorumisovellus | routes.py | Python | logout | logout | 170 | 173 | 170 | 171 | 1cb79feff65ee2e7f05fdfdfe803ae468fceda9e | bigcode/the-stack | train |
5e35db9245d40c7e896aafb0 | train | function | @app.route("/register", methods=["POST", "GET"])
def register():
if request.method == "GET":
return render_template("register.html")
if request.method == "POST":
username = request.form["username"].strip()
password = request.form["password"]
password_again = request.form... | @app.route("/register", methods=["POST", "GET"])
def register():
| if request.method == "GET":
return render_template("register.html")
if request.method == "POST":
username = request.form["username"].strip()
password = request.form["password"]
password_again = request.form["password_again"]
credentials_ok, error_message = users... | abort(403)
thread_id = request.form["thread_id"]
category_id = request.form["cat_id"]
if users.is_admin():
messages.delete_thread(thread_id)
return redirect("/category/"+str(category_id))
@app.route("/register", methods=["POST", "GET"])
def register():
| 64 | 64 | 150 | 16 | 48 | Ronttikasa/foorumisovellus | routes.py | Python | register | register | 139 | 158 | 139 | 140 | 891ed11f1661438c91be5f4db1fb2bdb8468996d | bigcode/the-stack | train |
efa8cd807496ab99e78a2c5f | train | function | @app.route("/delete", methods=["POST"])
def delete_message():
if not session["csrf_token"] == request.form["csrf_token"]:
abort(403)
message_id = request.form["msg_id"]
user_id = int(request.form["user_id"])
thread_id = request.form["thread_id"]
if session["user_id"] == user_i... | @app.route("/delete", methods=["POST"])
def delete_message():
| if not session["csrf_token"] == request.form["csrf_token"]:
abort(403)
message_id = request.form["msg_id"]
user_id = int(request.form["user_id"])
thread_id = request.form["thread_id"]
if session["user_id"] == user_id or users.is_admin():
msg_deleted = messages.delete_me... | _template("error.html", message="Ketjun luominen ei onnistunut. Otsikon tulee olla 1-100 merkkiä ja viestin 1-5000 merkkiä pitkä.")
return redirect("/thread/"+str(thread_id))
@app.route("/delete", methods=["POST"])
def delete_message():
| 64 | 64 | 143 | 14 | 50 | Ronttikasa/foorumisovellus | routes.py | Python | delete_message | delete_message | 108 | 124 | 108 | 109 | d36f3e05c67c470ddf1731dfdbec841f2bbeecee | bigcode/the-stack | train |
d1a4ebb7b2899f3f5911a657 | train | function | @app.route("/category/<int:id>")
def category(id):
if session.get("username"):
if not users.category_access(session.get("user_id"), id):
return render_template("error.html", message="Ei oikeutta katsella aluetta")
name = messages.get_category_name(id)
threads = me... | @app.route("/category/<int:id>")
def category(id):
| if session.get("username"):
if not users.category_access(session.get("user_id"), id):
return render_template("error.html", message="Ei oikeutta katsella aluetta")
name = messages.get_category_name(id)
threads = messages.get_threads(id)
else:
return red... | _by_group(group_id)
for category in allowed:
if category not in categories:
categories.append(category)
else:
return render_template("index.html")
return render_template("index.html", categories=categories, groups=group_permissions)
@app.route("/ca... | 64 | 64 | 98 | 13 | 51 | Ronttikasa/foorumisovellus | routes.py | Python | category | category | 24 | 35 | 24 | 25 | 8299ea84826c3815314cca8323a3a3ca674dce0a | bigcode/the-stack | train |
643fda7dc715695089f683df | train | function | @app.route("/new_message", methods=["POST"])
def new_message():
if not session["csrf_token"] == request.form["csrf_token"]:
abort(403)
if not users.category_access(session.get("user_id"), request.form["cat_id"]):
return render_template("error.html", message="Ei oikeutta kirjoittaa tähän ket... | @app.route("/new_message", methods=["POST"])
def new_message():
| if not session["csrf_token"] == request.form["csrf_token"]:
abort(403)
if not users.category_access(session.get("user_id"), request.form["cat_id"]):
return render_template("error.html", message="Ei oikeutta kirjoittaa tähän ketjuun")
content = request.form["content"]
thread_id = req... | msgs = messages.get_messages(id)
is_admin = users.is_admin()
else:
return redirect("/")
return render_template("thread.html", messages=msgs, thread_id=id, header_data=header_data, admin=is_admin)
@app.route("/new_message", methods=["POST"])
def new_message():
| 64 | 64 | 156 | 15 | 49 | Ronttikasa/foorumisovellus | routes.py | Python | new_message | new_message | 74 | 88 | 74 | 75 | 8a4cd11640854d47463f15920880fb021e90822f | bigcode/the-stack | train |
0011796b13c1be38dc21ed3f | train | function | @app.route("/")
def index():
if session.get("username"):
categories = []
group_permissions = users.user_in_groups(session.get("user_id"))
for group_id in group_permissions:
allowed = messages.get_categories_by_group(group_id)
for category in allowed... | @app.route("/")
def index():
| if session.get("username"):
categories = []
group_permissions = users.user_in_groups(session.get("user_id"))
for group_id in group_permissions:
allowed = messages.get_categories_by_group(group_id)
for category in allowed:
if category ... | from app import app
from flask import render_template, request, redirect, session, abort
import users
import messages
@app.route("/")
def index():
| 32 | 64 | 99 | 7 | 24 | Ronttikasa/foorumisovellus | routes.py | Python | index | index | 7 | 22 | 7 | 8 | ea9eef6aace35cc2cedd6cb16b8c8ff14cc491a2 | bigcode/the-stack | train |
acb5fb4204c75b03d9fcf682 | train | function | def lazy_import():
from infobip_api_client.model.sms_language import SmsLanguage
globals()["SmsLanguage"] = SmsLanguage
| def lazy_import():
| from infobip_api_client.model.sms_language import SmsLanguage
globals()["SmsLanguage"] = SmsLanguage
|
ApiTypeError,
ModelComposed,
ModelNormal,
ModelSimple,
cached_property,
change_keys_js_to_python,
convert_js_args_to_python_args,
date,
datetime,
file_type,
none_type,
validate_get_composed_info,
)
def lazy_import():
| 64 | 64 | 28 | 4 | 60 | DavadDi/infobip-api-python-client | infobip_api_client/model/sms_language_configuration.py | Python | lazy_import | lazy_import | 31 | 34 | 31 | 31 | 218ff8639347bd8557668daa96c48a0b88c697c0 | bigcode/the-stack | train |
72db0f1e2c7310c18f7b05df | train | class | class SmsLanguageConfiguration(ModelNormal):
"""
Attributes:
allowed_values (dict): The key is the tuple path to the attribute
and the for var_name this is (var_name,). The value is a dict
with a capitalized key describing the allowed value and an allowed
value. These dicts s... | class SmsLanguageConfiguration(ModelNormal):
| """
Attributes:
allowed_values (dict): The key is the tuple path to the attribute
and the for var_name this is (var_name,). The value is a dict
with a capitalized key describing the allowed value and an allowed
value. These dicts store the allowed enum values.
attribute... | """
Infobip Client API Libraries OpenAPI Specification
OpenAPI specification containing public endpoints supported in client API libraries. # noqa: E501
The version of the OpenAPI document: 1.0.172
Contact: support@infobip.com
Generated by: https://openapi-generator.tech
"""
import re # noqa: ... | 199 | 256 | 1,198 | 7 | 191 | DavadDi/infobip-api-python-client | infobip_api_client/model/sms_language_configuration.py | Python | SmsLanguageConfiguration | SmsLanguageConfiguration | 37 | 175 | 37 | 37 | 3725d859480a887f758e4bc8c72d42d23ee6f262 | bigcode/the-stack | train |
61c99ae9a24416492e3a9828 | train | function | def Serve(queue=None, port=0):
server = FakeAurServer(('localhost', port), FakeAurHandler)
endpoint = 'http://{}:{}'.format(*server.socket.getsockname())
if queue:
queue.put(endpoint)
else:
print('serving on', endpoint)
signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit(0... | def Serve(queue=None, port=0):
| server = FakeAurServer(('localhost', port), FakeAurHandler)
endpoint = 'http://{}:{}'.format(*server.socket.getsockname())
if queue:
queue.put(endpoint)
else:
print('serving on', endpoint)
signal.signal(signal.SIGTERM, lambda signum, frame: sys.exit(0))
try:
server.ser... | for k, v in headers:
self.send_header(k, v)
self.end_headers()
if response:
self.wfile.write(response)
class FakeAurServer(http.server.HTTPServer):
def handle_error(self, request, client_address):
raise
def Serve(queue=None, port=0):
| 64 | 64 | 104 | 9 | 54 | eli-schwartz/auracle | tests/fakeaur/server.py | Python | Serve | Serve | 171 | 186 | 171 | 171 | 156e18ad0fddbbde091b414598698e06d2b41b52 | bigcode/the-stack | train |
faf145ee1a5b6a5b4b0b9a9e | train | class | class FakeAurServer(http.server.HTTPServer):
def handle_error(self, request, client_address):
raise
| class FakeAurServer(http.server.HTTPServer):
| def handle_error(self, request, client_address):
raise
| )
def respond(self, status_code=200, headers=[], response=None):
self.send_response(status_code)
for k, v in headers:
self.send_header(k, v)
self.end_headers()
if response:
self.wfile.write(response)
class FakeAurServer(http.server.HTTPServer):
| 64 | 64 | 23 | 9 | 55 | eli-schwartz/auracle | tests/fakeaur/server.py | Python | FakeAurServer | FakeAurServer | 166 | 168 | 166 | 166 | 67075d1a70e983fde3aa03e18460dfb8cee1ec8c | bigcode/the-stack | train |
46fbe03115b975c800693a42 | train | class | class FakeAurHandler(http.server.BaseHTTPRequestHandler):
def do_GET(self):
handlers = {
'/rpc': self.handle_rpc,
'/cgit/aur.git/snapshot': self.handle_download,
'/cgit/aur.git/plain/': self.handle_source_file,
}
url = urllib.parse.urlparse(self.path)
... | class FakeAurHandler(http.server.BaseHTTPRequestHandler):
| def do_GET(self):
handlers = {
'/rpc': self.handle_rpc,
'/cgit/aur.git/snapshot': self.handle_download,
'/cgit/aur.git/plain/': self.handle_source_file,
}
url = urllib.parse.urlparse(self.path)
for path, handler in handlers.items():
i... | #!/usr/bin/env python
import gzip
import http.server
import io
import json
import os.path
import signal
import sys
import tarfile
import tempfile
import urllib.parse
DBROOT = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'db')
AUR_SERVER_VERSION = 5
class FakeAurHandler(http.server.BaseHTTPRequestHandler... | 78 | 256 | 935 | 10 | 67 | eli-schwartz/auracle | tests/fakeaur/server.py | Python | FakeAurHandler | FakeAurHandler | 19 | 163 | 19 | 20 | 4fe0caecb3da408fd62b110df2dddc3955f10f9b | bigcode/the-stack | train |
c3f71f429048594d473105fb | train | class | class Agent:
def __init__(self, building_ids, buildings_states_actions, building_info):
with open(buildings_states_actions) as json_file:
self.buildings_states_actions = json.load(json_file)
'''Initialize the class and define any hyperparameters of the controller'''
... | class Agent:
| def __init__(self, building_ids, buildings_states_actions, building_info):
with open(buildings_states_actions) as json_file:
self.buildings_states_actions = json.load(json_file)
'''Initialize the class and define any hyperparameters of the controller'''
... | ### Feel free to edit this file at will, but make sure it runs properly when we execute the main.py or main.ipynb file that is provided. You can't change the main file, only to the submission files.
'''Import any packages here'''
import json
import torch
class Agent:
| 60 | 64 | 203 | 3 | 56 | QasimWani/CityLearn | agent.py | Python | Agent | Agent | 7 | 26 | 7 | 7 | 92a3cb7ba277625762767c3f45888b748d354741 | bigcode/the-stack | train |
8b99eae5e22e03c1b9b780b6 | train | function | def searchBST(root, val):
if root is None: return None
if root.val == val:
return root
if val < root.val:
return searchBST(root.left, val)
elif val > root.val:
return searchBST(root.right,val)
| def searchBST(root, val):
| if root is None: return None
if root.val == val:
return root
if val < root.val:
return searchBST(root.left, val)
elif val > root.val:
return searchBST(root.right,val)
| the root node of a binary search tree (BST) and a value. You need to find the
# node in the BST that the node's value equals the given value. Return the subtree
# rooted with that node. If such node doesn't exist, you should return NULL.
def searchBST(root, val):
| 64 | 64 | 58 | 7 | 57 | shoaibur/SWE | Leetcoding-Actions/Explore-Monthly-Challenges/2020-06/15-search-in-binary-search-tree.py | Python | searchBST | searchBST | 5 | 12 | 5 | 5 | 0cc217e6ecfea6f4c296e88b6d14f7773784ec69 | bigcode/the-stack | train |
644b5d430ae1761adf37570c | train | class | class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKCYAN = '\033[96m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
| class bcolors:
| HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKCYAN = '\033[96m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
| class bcolors:
| 4 | 64 | 92 | 4 | 0 | Gambl3r08/ejercicios-Python | colores.py | Python | bcolors | bcolors | 1 | 10 | 1 | 1 | 8a7c48079ab77878fd50a7612aad00cc5255a15a | bigcode/the-stack | train |
188227e27997629685e12940 | train | function | def fix_whitespace(fname):
""" Fix whitespace in a file """
with open(fname, "rb") as fo:
original_contents = fo.read()
# "rU" Universal line endings to Unix
with open(fname, "rU") as fo:
contents = fo.read()
lines = contents.split("\n")
fixed = 0
for k, line in enumerate(lin... | def fix_whitespace(fname):
| """ Fix whitespace in a file """
with open(fname, "rb") as fo:
original_contents = fo.read()
# "rU" Universal line endings to Unix
with open(fname, "rU") as fo:
contents = fo.read()
lines = contents.split("\n")
fixed = 0
for k, line in enumerate(lines):
new_line = lin... | os.path.exists(fname):
print("Python file not found: %s" % sys.argv[1])
sys.exit(1)
else:
print("Invalid arguments. Usage: python fix_whitespace.py foo.py")
sys.exit(1)
fix_whitespace(fname)
def fix_whitespace(fname):
| 65 | 65 | 218 | 6 | 59 | ciena-blueplanet/git-fat | win32/fix_whitespace.py | Python | fix_whitespace | fix_whitespace | 24 | 47 | 24 | 24 | d906cf6dc5f74990b7f1e05cdadd00d1bcbc7489 | bigcode/the-stack | train |
6b686a991a81518b141acffa | train | function | def main():
""" Parse arguments, then fix whitespace in the given file """
if len(sys.argv) == 2:
fname = sys.argv[1]
if not os.path.exists(fname):
print("Python file not found: %s" % sys.argv[1])
sys.exit(1)
else:
print("Invalid arguments. Usage: python fix_w... | def main():
| """ Parse arguments, then fix whitespace in the given file """
if len(sys.argv) == 2:
fname = sys.argv[1]
if not os.path.exists(fname):
print("Python file not found: %s" % sys.argv[1])
sys.exit(1)
else:
print("Invalid arguments. Usage: python fix_whitespace.py... | #!/usr/bin/env python
"""
Fix trailing whitespace and line endings (to Unix) in a file.
Usage: python fix_whitespace.py foo.py
"""
import os
import sys
def main():
| 41 | 64 | 96 | 3 | 37 | ciena-blueplanet/git-fat | win32/fix_whitespace.py | Python | main | main | 11 | 21 | 11 | 11 | 20466900869ba00889283267966d90a94ac21987 | bigcode/the-stack | train |
7bf8be66d52b96e5f466e9f6 | train | function | def training(sess, neuralnet, saver,
dataset, batch_size, sequence_length,
iteration):
start_time = time.time()
loss_tr = 0
list_loss = []
print("\n** Training of the LSTM model to %d iterations | Batch size: %d" %(iteration, batch_size))
make_dir(path=os.path.join(PACK_P... | def training(sess, neuralnet, saver,
dataset, batch_size, sequence_length,
iteration):
| start_time = time.time()
loss_tr = 0
list_loss = []
print("\n** Training of the LSTM model to %d iterations | Batch size: %d" %(iteration, batch_size))
make_dir(path=os.path.join(PACK_PATH, 'results'))
train_writer = tf.summary.FileWriter(PACK_PATH+'/logs')
for it in range(iteration):
... | )
except: print("%s is already exists." %(path))
def data2canvas(data, dy, dx):
nx, ny = 10, 10
i, j = 0, 0
canvas = np.zeros((dy*ny+10*(ny-1), dx*nx+10*(nx-1)))
for da in data:
if(np.min(da) < 0):
da += abs(np.min(da))
canvas[(nx-i-1)*dy+(nx-i-1)*10:(nx-i)*dy+(nx-i-1)*1... | 212 | 212 | 709 | 21 | 190 | YeongHyeon/Arrhythmia_Detection_RNN_and_Lyapunov | source/tf_process.py | Python | training | training | 29 | 92 | 29 | 32 | f45cab346bc898f43514388b72130b084a118d35 | bigcode/the-stack | train |
d8aa3944f85c7a90579f8c76 | train | function | def make_dir(path):
try: os.mkdir(path)
except: print("%s is already exists." %(path))
| def make_dir(path):
| try: os.mkdir(path)
except: print("%s is already exists." %(path))
| import os, inspect, time, scipy.misc, pickle
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
PACK_PATH = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))+"/.."
def make_dir(path):
| 54 | 64 | 25 | 5 | 48 | YeongHyeon/Arrhythmia_Detection_RNN_and_Lyapunov | source/tf_process.py | Python | make_dir | make_dir | 9 | 11 | 9 | 9 | 5134d4cfaa3189774a4684e76587f2cafc69990b | bigcode/the-stack | train |
e7b8d6785cd0d447beff3ea5 | train | function | def validation(sess, neuralnet, saver,
dataset, sequence_length):
if(os.path.exists(PACK_PATH+"/Checkpoint/model_checker.index")):
saver.restore(sess, PACK_PATH+"/Checkpoint/model_checker")
make_dir(path=os.path.join(PACK_PATH, 'valids'))
print("\n** Validation of the LSTM model wi... | def validation(sess, neuralnet, saver,
dataset, sequence_length):
| if(os.path.exists(PACK_PATH+"/Checkpoint/model_checker.index")):
saver.restore(sess, PACK_PATH+"/Checkpoint/model_checker")
make_dir(path=os.path.join(PACK_PATH, 'valids'))
print("\n** Validation of the LSTM model with %d sets." %(dataset.am_tot))
for key in dataset.key_tot:
list_dist... | , color='blue', linestyle="-", label="loss")
# plt.plot(sparse_loss_x, np.log(sparse_loss), color='tomato', linestyle="--", label="log scale loss")
plt.ylabel("loss")
plt.xlabel("iteration")
# plt.legend(loc='best')
plt.tight_layout(pad=1, w_pad=1, h_pad=1)
plt.savefig("l... | 105 | 105 | 353 | 15 | 90 | YeongHyeon/Arrhythmia_Detection_RNN_and_Lyapunov | source/tf_process.py | Python | validation | validation | 94 | 129 | 94 | 96 | 1d77181f264fa37ca52a21d5f4883b343a8a2068 | bigcode/the-stack | train |
b3f27fdd229bdce8e59fea70 | train | function | def data2canvas(data, dy, dx):
nx, ny = 10, 10
i, j = 0, 0
canvas = np.zeros((dy*ny+10*(ny-1), dx*nx+10*(nx-1)))
for da in data:
if(np.min(da) < 0):
da += abs(np.min(da))
canvas[(nx-i-1)*dy+(nx-i-1)*10:(nx-i)*dy+(nx-i-1)*10, j*dx+j*10:(j+1)*dx+(j)*10] = da.reshape((dy, dx))
... | def data2canvas(data, dy, dx):
| nx, ny = 10, 10
i, j = 0, 0
canvas = np.zeros((dy*ny+10*(ny-1), dx*nx+10*(nx-1)))
for da in data:
if(np.min(da) < 0):
da += abs(np.min(da))
canvas[(nx-i-1)*dy+(nx-i-1)*10:(nx-i)*dy+(nx-i-1)*10, j*dx+j*10:(j+1)*dx+(j)*10] = da.reshape((dy, dx))
j += 1
if(j >= 1... | np
import matplotlib.pyplot as plt
PACK_PATH = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))+"/.."
def make_dir(path):
try: os.mkdir(path)
except: print("%s is already exists." %(path))
def data2canvas(data, dy, dx):
| 64 | 64 | 177 | 10 | 54 | YeongHyeon/Arrhythmia_Detection_RNN_and_Lyapunov | source/tf_process.py | Python | data2canvas | data2canvas | 13 | 27 | 13 | 13 | 32f34eb432e0eec24c1d073c8ff24b3a9f6ddfc2 | bigcode/the-stack | train |
034cf97e34edcb8f21d12020 | train | function | def generate_overlays(n): # Don't use!
sol = Solver()
x = {}
for i in range(n):
for j in range(n):
x[(i,j)] = makeIntVar(sol,"x[%i,%i]" % (i,j),0,1)
for i in range(n):
sol.add(Sum([x[(i,j)] for j in range(n)]) == 1)
sol.add(Sum([x[(j,i)] for j in range(n)]) == 1)
num... | def generate_overlays(n): # Don't use!
| sol = Solver()
x = {}
for i in range(n):
for j in range(n):
x[(i,j)] = makeIntVar(sol,"x[%i,%i]" % (i,j),0,1)
for i in range(n):
sol.add(Sum([x[(i,j)] for j in range(n)]) == 1)
sol.add(Sum([x[(j,i)] for j in range(n)]) == 1)
num_solutions = 0
overlays = []
while s... | _solvable, " (%2f%%)" % (num_solvable / num_problems))
#
# generate the n! overlays
# Note: This the unoptimized version.
#
# Better use generate_overlays2(n,problem) instead.
#
def generate_overlays(n): # Don't use!
| 64 | 64 | 187 | 11 | 53 | Wikunia/hakank | z3/ormat_game.py | Python | generate_overlays | generate_overlays | 122 | 142 | 122 | 123 | 72ac4bb720e6c005f0524205d97b9c54f0866a2c | bigcode/the-stack | train |
f1f34317f0db04f2e0f459b2 | train | function | def prod(n):
return reduce(lambda x, y: x * y, range(1,n+1))
| def prod(n):
| return reduce(lambda x, y: x * y, range(1,n+1))
| # num_overlays: 4
#
#
# This Z3 model was written by Hakan Kjellerstrand (hakank@gmail.com)
# See also my Z3 page: http://hakank.org/z3/
#
from z3_utils_hakank import *
import random
def prod(n):
| 64 | 64 | 23 | 4 | 59 | Wikunia/hakank | z3/ormat_game.py | Python | prod | prod | 69 | 70 | 69 | 69 | 1db7835225d4d3c4e8c7be7f837632611979fe2b | bigcode/the-stack | train |
12e9ca3b629627913221850d | train | function | def test_all_problems(n):
sol = Solver()
x = {}
for i in range(n):
for j in range(n):
x[(i,j)] = makeIntVar(sol,"x[%i,%i]" % (i,j),0,1)
num_solutions = 0
overlays = []
num_problems = 0
num_solvable = 0
while sol.check() == sat:
num_problems += 1
mod = sol.mode... | def test_all_problems(n):
| sol = Solver()
x = {}
for i in range(n):
for j in range(n):
x[(i,j)] = makeIntVar(sol,"x[%i,%i]" % (i,j),0,1)
num_solutions = 0
overlays = []
num_problems = 0
num_solvable = 0
while sol.check() == sat:
num_problems += 1
mod = sol.model()
xx = [[mod.eval(... | #
# Number of solvable problems for som (small) n
# n possible problems solvable problems
# -----------------------------------------
# 3 512 49
# 4 65536 7443
# 5 33554432
#
# (Number of possible problems is 2**(n*n)
#
#
def test_all_problems(n):
| 82 | 82 | 275 | 7 | 75 | Wikunia/hakank | z3/ormat_game.py | Python | test_all_problems | test_all_problems | 87 | 112 | 87 | 87 | e531ab4e2cfc9a4cab6ecc806b0005b1ae9187cd | bigcode/the-stack | train |
92fb06c1907fdb3d967a374f | train | function | def generate_overlays2(n,problem):
sol = Solver()
x = {}
for i in range(n):
for j in range(n):
x[(i,j)] = makeIntVar(sol,"x[%i,%i]" % (i,j),0,1)
for i in range(n):
for j in range(n):
sol.add(If(problem[i][j] == 0, x[(i,j)] == 0, True))
sol.add(Sum([x[(i,j)] for j ... | def generate_overlays2(n,problem):
| sol = Solver()
x = {}
for i in range(n):
for j in range(n):
x[(i,j)] = makeIntVar(sol,"x[%i,%i]" % (i,j),0,1)
for i in range(n):
for j in range(n):
sol.add(If(problem[i][j] == 0, x[(i,j)] == 0, True))
sol.add(Sum([x[(i,j)] for j in range(n)]) == 1)
sol.add(Sum([x... | then problem has an 0 in a cell
# then the overlay also must have an 0 in the same cell.
# This reduces the number of overlays and the complexity
# of the problem.
# Note: The reduction percetage is thus problem specific.
#
def generate_overlays2(n,problem):
| 65 | 65 | 218 | 10 | 55 | Wikunia/hakank | z3/ormat_game.py | Python | generate_overlays2 | generate_overlays2 | 155 | 177 | 155 | 156 | 430bf0c36aa9fd7d4c1fddc1d85cd0be1acf389f | bigcode/the-stack | train |
a8db8e87df33a6a76e80d2e8 | train | function | def ormat_game(game,printit=1):
# data
name = game[0]
n = game[1]
problem = game[2]
overlays = generate_overlays2(n,problem)
# f = prod(n)
f = len(overlays)
if printit == 1:
print(name, "\n")
print(f, "overlays generated")
print("problem:\n",end=" ")
for i... | def ormat_game(game,printit=1):
# data
| name = game[0]
n = game[1]
problem = game[2]
overlays = generate_overlays2(n,problem)
# f = prod(n)
f = len(overlays)
if printit == 1:
print(name, "\n")
print(f, "overlays generated")
print("problem:\n",end=" ")
for i in range(n):
for j in range(n):
... | i,j)] == 0, True))
sol.add(Sum([x[(i,j)] for j in range(n)]) == 1)
sol.add(Sum([x[(j,i)] for j in range(n)]) == 1)
num_solutions = 0
overlays = []
while sol.check() == sat:
num_solutions += 1
mod = sol.model()
overlays.append([[mod.eval(x[(i,j)]).as_long() for j in range... | 153 | 153 | 512 | 15 | 138 | Wikunia/hakank | z3/ormat_game.py | Python | ormat_game | ormat_game | 184 | 246 | 184 | 187 | 571ddb2f7a706b58bf6a5136883769d409992526 | bigcode/the-stack | train |
3ab43d0b60151e937bf313cc | train | function | @pytest.mark.parametrize("sep", [",", "\t"])
@pytest.mark.parametrize("encoding", ["utf-16", "utf-16le", "utf-16be"])
def test_utf16_bom_skiprows(all_parsers, sep, encoding):
# see gh-2298
parser = all_parsers
data = """skip this
skip this too
A,B,C
1,2,3
4,5,6""".replace(
",", sep
)
path = ... | @pytest.mark.parametrize("sep", [",", "\t"])
@pytest.mark.parametrize("encoding", ["utf-16", "utf-16le", "utf-16be"])
def test_utf16_bom_skiprows(all_parsers, sep, encoding):
# see gh-2298
| parser = all_parsers
data = """skip this
skip this too
A,B,C
1,2,3
4,5,6""".replace(
",", sep
)
path = f"__{tm.rands(10)}__.csv"
kwargs = dict(sep=sep, skiprows=2)
utf8 = "utf-8"
with tm.ensure_clean(path) as path:
from io import TextIOWrapper
bytes_data = data.enco... | 0141aski, Jan", 1]])
tm.assert_frame_equal(result, expected)
@pytest.mark.parametrize("sep", [",", "\t"])
@pytest.mark.parametrize("encoding", ["utf-16", "utf-16le", "utf-16be"])
def test_utf16_bom_skiprows(all_parsers, sep, encoding):
# see gh-2298
| 77 | 77 | 257 | 59 | 18 | acrucetta/Chicago_COVI_WebApp | .venv/lib/python3.8/site-packages/pandas/tests/io/parser/test_encoding.py | Python | test_utf16_bom_skiprows | test_utf16_bom_skiprows | 37 | 68 | 37 | 40 | 545bdf407dede1f88af06b42e8d36a2b58536f6e | bigcode/the-stack | train |
f25290dc558ffd82f48ebdfe | train | function | def test_read_csv_unicode(all_parsers):
parser = all_parsers
data = BytesIO("\u0141aski, Jan;1".encode("utf-8"))
result = parser.read_csv(data, sep=";", encoding="utf-8", header=None)
expected = DataFrame([["\u0141aski, Jan", 1]])
tm.assert_frame_equal(result, expected)
| def test_read_csv_unicode(all_parsers):
| parser = all_parsers
data = BytesIO("\u0141aski, Jan;1".encode("utf-8"))
result = parser.read_csv(data, sep=";", encoding="utf-8", header=None)
expected = DataFrame([["\u0141aski, Jan", 1]])
tm.assert_frame_equal(result, expected)
| :1234\n562:123".encode(encoding))
result = parser.read_csv(data, sep=":", encoding=encoding)
expected = DataFrame([[562, 123]], columns=["שלום", "1234"])
tm.assert_frame_equal(result, expected)
def test_read_csv_unicode(all_parsers):
| 64 | 64 | 84 | 9 | 55 | acrucetta/Chicago_COVI_WebApp | .venv/lib/python3.8/site-packages/pandas/tests/io/parser/test_encoding.py | Python | test_read_csv_unicode | test_read_csv_unicode | 28 | 34 | 28 | 28 | c427779811cd34b67d105c262ff2b8dfde017df0 | bigcode/the-stack | train |
4860c2acbe6e43765a786bc4 | train | function | @pytest.mark.parametrize(
"file_path,encoding",
[
(("io", "data", "csv", "test1.csv"), "utf-8"),
(("io", "parser", "data", "unicode_series.csv"), "latin-1"),
(("io", "parser", "data", "sauron.SHIFT_JIS.csv"), "shiftjis"),
],
)
def test_binary_mode_file_buffers(
all_parsers, csv_d... | @pytest.mark.parametrize(
"file_path,encoding",
[
(("io", "data", "csv", "test1.csv"), "utf-8"),
(("io", "parser", "data", "unicode_series.csv"), "latin-1"),
(("io", "parser", "data", "sauron.SHIFT_JIS.csv"), "shiftjis"),
],
)
def test_binary_mode_file_buffers(
all_parsers, csv_d... | parser = all_parsers
fpath = datapath(*file_path)
expected = parser.read_csv(fpath, encoding=encoding)
with open(fpath, mode="r", encoding=encoding) as fa:
result = parser.read_csv(fa)
tm.assert_frame_equal(expected, result)
with open(fpath, mode="rb") as fb:
result = parser.r... | @pytest.mark.parametrize(
"file_path,encoding",
[
(("io", "data", "csv", "test1.csv"), "utf-8"),
(("io", "parser", "data", "unicode_series.csv"), "latin-1"),
(("io", "parser", "data", "sauron.SHIFT_JIS.csv"), "shiftjis"),
],
)
def test_binary_mode_file_buffers(
all_parsers, csv_d... | 145 | 85 | 284 | 145 | 0 | acrucetta/Chicago_COVI_WebApp | .venv/lib/python3.8/site-packages/pandas/tests/io/parser/test_encoding.py | Python | test_binary_mode_file_buffers | test_binary_mode_file_buffers | 135 | 163 | 135 | 147 | 8870cccc56c1eedc293081b9d513912ba92191e9 | bigcode/the-stack | train |
07012623fc60ee30bf3e300d | train | function | def test_unicode_encoding(all_parsers, csv_dir_path):
path = os.path.join(csv_dir_path, "unicode_series.csv")
parser = all_parsers
result = parser.read_csv(path, header=None, encoding="latin-1")
result = result.set_index(0)
got = result[1][1632]
expected = "\xc1 k\xf6ldum klaka (Cold Fever) (1... | def test_unicode_encoding(all_parsers, csv_dir_path):
| path = os.path.join(csv_dir_path, "unicode_series.csv")
parser = all_parsers
result = parser.read_csv(path, header=None, encoding="latin-1")
result = result.set_index(0)
got = result[1][1632]
expected = "\xc1 k\xf6ldum klaka (Cold Fever) (1994)"
assert got == expected
| _path):
path = os.path.join(csv_dir_path, "utf16_ex.txt")
parser = all_parsers
result = parser.read_csv(path, encoding="utf-16", sep="\t")
assert len(result) == 50
def test_unicode_encoding(all_parsers, csv_dir_path):
| 64 | 64 | 97 | 12 | 51 | acrucetta/Chicago_COVI_WebApp | .venv/lib/python3.8/site-packages/pandas/tests/io/parser/test_encoding.py | Python | test_unicode_encoding | test_unicode_encoding | 78 | 87 | 78 | 78 | bc609d69f795e020ec0a7e31ff36ba1560d34226 | bigcode/the-stack | train |
f73aa8d212575c13f234d84c | train | function | def test_utf16_example(all_parsers, csv_dir_path):
path = os.path.join(csv_dir_path, "utf16_ex.txt")
parser = all_parsers
result = parser.read_csv(path, encoding="utf-16", sep="\t")
assert len(result) == 50
| def test_utf16_example(all_parsers, csv_dir_path):
| path = os.path.join(csv_dir_path, "utf16_ex.txt")
parser = all_parsers
result = parser.read_csv(path, encoding="utf-16", sep="\t")
assert len(result) == 50
| _buffer, encoding=utf8)
result = parser.read_csv(path, encoding=encoding, **kwargs)
expected = parser.read_csv(bytes_buffer, encoding=utf8, **kwargs)
bytes_buffer.close()
tm.assert_frame_equal(result, expected)
def test_utf16_example(all_parsers, csv_dir_path):
| 64 | 64 | 63 | 13 | 51 | acrucetta/Chicago_COVI_WebApp | .venv/lib/python3.8/site-packages/pandas/tests/io/parser/test_encoding.py | Python | test_utf16_example | test_utf16_example | 71 | 75 | 71 | 71 | 700c51eb59734e1a4775a3a54e66d3b6cf642177 | bigcode/the-stack | train |
0e062fd4fd9c464f54f57d44 | train | function | def test_encoding_named_temp_file(all_parsers):
# see gh-31819
parser = all_parsers
encoding = "shift-jis"
if parser.engine == "python":
pytest.skip("NamedTemporaryFile does not work with Python engine")
title = "てすと"
data = "こむ"
expected = DataFrame({title: [data]})
with tem... | def test_encoding_named_temp_file(all_parsers):
# see gh-31819
| parser = all_parsers
encoding = "shift-jis"
if parser.engine == "python":
pytest.skip("NamedTemporaryFile does not work with Python engine")
title = "てすと"
data = "こむ"
expected = DataFrame({title: [data]})
with tempfile.NamedTemporaryFile() as f:
f.write(f"{title}\n{data}"... | like=True) as f:
f.write("foo\nbar")
f.seek(0)
result = parser.read_csv(f, encoding=encoding if pass_encoding else None)
tm.assert_frame_equal(result, expected)
def test_encoding_named_temp_file(all_parsers):
# see gh-31819
| 64 | 64 | 134 | 18 | 46 | acrucetta/Chicago_COVI_WebApp | .venv/lib/python3.8/site-packages/pandas/tests/io/parser/test_encoding.py | Python | test_encoding_named_temp_file | test_encoding_named_temp_file | 182 | 201 | 182 | 183 | 6a281247191e6da7e79092e61d928cf6db561eb6 | bigcode/the-stack | train |
42de968cc59babc2fe620e69 | train | function | def test_read_csv_utf_aliases(all_parsers, utf_value, encoding_fmt):
# see gh-13549
expected = DataFrame({"mb_num": [4.8], "multibyte": ["test"]})
parser = all_parsers
encoding = encoding_fmt.format(utf_value)
data = "mb_num,multibyte\n4.8,test".encode(encoding)
result = parser.read_csv(BytesI... | def test_read_csv_utf_aliases(all_parsers, utf_value, encoding_fmt):
# see gh-13549
| expected = DataFrame({"mb_num": [4.8], "multibyte": ["test"]})
parser = all_parsers
encoding = encoding_fmt.format(utf_value)
data = "mb_num,multibyte\n4.8,test".encode(encoding)
result = parser.read_csv(BytesIO(data), encoding=encoding)
tm.assert_frame_equal(result, expected)
| )
return BytesIO(bom_data)
result = parser.read_csv(_encode_data_with_bom(data), encoding=utf8, **kwargs)
tm.assert_frame_equal(result, expected)
def test_read_csv_utf_aliases(all_parsers, utf_value, encoding_fmt):
# see gh-13549
| 64 | 64 | 108 | 25 | 39 | acrucetta/Chicago_COVI_WebApp | .venv/lib/python3.8/site-packages/pandas/tests/io/parser/test_encoding.py | Python | test_read_csv_utf_aliases | test_read_csv_utf_aliases | 123 | 132 | 123 | 124 | 80c405c2c188b32f5d44ff728918923be05ad8a1 | bigcode/the-stack | train |
ee19c2ab517307d49758c798 | train | function | def test_bytes_io_input(all_parsers):
encoding = "cp1255"
parser = all_parsers
data = BytesIO("שלום:1234\n562:123".encode(encoding))
result = parser.read_csv(data, sep=":", encoding=encoding)
expected = DataFrame([[562, 123]], columns=["שלום", "1234"])
tm.assert_frame_equal(result, expected)
| def test_bytes_io_input(all_parsers):
| encoding = "cp1255"
parser = all_parsers
data = BytesIO("שלום:1234\n562:123".encode(encoding))
result = parser.read_csv(data, sep=":", encoding=encoding)
expected = DataFrame([[562, 123]], columns=["שלום", "1234"])
tm.assert_frame_equal(result, expected)
| """
Tests encoding functionality during parsing
for all of the parsers defined in parsers.py
"""
from io import BytesIO
import os
import tempfile
import numpy as np
import pytest
from pandas import DataFrame
import pandas._testing as tm
def test_bytes_io_input(all_parsers):
| 62 | 64 | 86 | 9 | 52 | acrucetta/Chicago_COVI_WebApp | .venv/lib/python3.8/site-packages/pandas/tests/io/parser/test_encoding.py | Python | test_bytes_io_input | test_bytes_io_input | 17 | 25 | 17 | 17 | 4057a10a63717e530956d9a3a8d950f0e1708378 | bigcode/the-stack | train |
9229fcaf3872db9e2c6ad9ce | train | function | @pytest.mark.parametrize(
"data,kwargs,expected",
[
# Basic test
("a\n1", dict(), DataFrame({"a": [1]})),
# "Regular" quoting
('"a"\n1', dict(quotechar='"'), DataFrame({"a": [1]})),
# Test in a data row instead of header
("b\n1", dict(names=["a"]), DataFrame({"a":... | @pytest.mark.parametrize(
"data,kwargs,expected",
[
# Basic test
("a\n1", dict(), DataFrame({"a": [1]})),
# "Regular" quoting
('"a"\n1', dict(quotechar='"'), DataFrame({"a": [1]})),
# Test in a data row instead of header
("b\n1", dict(names=["a"]), DataFrame({"a":... | parser = all_parsers
bom = "\ufeff"
utf8 = "utf-8"
def _encode_data_with_bom(_data):
bom_data = (bom + _data).encode(utf8)
return BytesIO(bom_data)
result = parser.read_csv(_encode_data_with_bom(data), encoding=utf8, **kwargs)
tm.assert_frame_equal(result, expected)
| @pytest.mark.parametrize(
"data,kwargs,expected",
[
# Basic test
("a\n1", dict(), DataFrame({"a": [1]})),
# "Regular" quoting
('"a"\n1', dict(quotechar='"'), DataFrame({"a": [1]})),
# Test in a data row instead of header
("b\n1", dict(names=["a"]), DataFrame({"a":... | 206 | 87 | 293 | 206 | 0 | acrucetta/Chicago_COVI_WebApp | .venv/lib/python3.8/site-packages/pandas/tests/io/parser/test_encoding.py | Python | test_utf8_bom | test_utf8_bom | 90 | 120 | 90 | 110 | 8edfb9703a458d7323b7b2963bcdcfe216a4dfa7 | bigcode/the-stack | train |
744da3e859ebe1bdac3b07d3 | train | function | @pytest.mark.parametrize("pass_encoding", [True, False])
def test_encoding_temp_file(all_parsers, utf_value, encoding_fmt, pass_encoding):
# see gh-24130
parser = all_parsers
encoding = encoding_fmt.format(utf_value)
expected = DataFrame({"foo": ["bar"]})
with tm.ensure_clean(mode="w+", encoding=e... | @pytest.mark.parametrize("pass_encoding", [True, False])
def test_encoding_temp_file(all_parsers, utf_value, encoding_fmt, pass_encoding):
# see gh-24130
| parser = all_parsers
encoding = encoding_fmt.format(utf_value)
expected = DataFrame({"foo": ["bar"]})
with tm.ensure_clean(mode="w+", encoding=encoding, return_filelike=True) as f:
f.write("foo\nbar")
f.seek(0)
result = parser.read_csv(f, encoding=encoding if pass_encoding els... | ) as fb:
result = parser.read_csv(fb, encoding=encoding)
tm.assert_frame_equal(expected, result)
@pytest.mark.parametrize("pass_encoding", [True, False])
def test_encoding_temp_file(all_parsers, utf_value, encoding_fmt, pass_encoding):
# see gh-24130
| 64 | 64 | 128 | 38 | 26 | acrucetta/Chicago_COVI_WebApp | .venv/lib/python3.8/site-packages/pandas/tests/io/parser/test_encoding.py | Python | test_encoding_temp_file | test_encoding_temp_file | 166 | 179 | 166 | 168 | 2c97e4009dff0d4ec0f32b7ec5d87db7d5ead2a1 | bigcode/the-stack | train |
8a091dce2abb988757411be5 | train | function | def theoretical_fixed_r(min_r, max_r, min_domain, max_domain, domain_skip=5):
r = min_r
if not isdir(config.theo_fixed_r):
mkdir(config.theo_fixed_r)
savepath = config.theo_fixed_r + str(datetime.now()) + '/'
if not isdir(savepath):
mkdir(savepath)
for r in range(min_r, max_r + 1):
... | def theoretical_fixed_r(min_r, max_r, min_domain, max_domain, domain_skip=5):
| r = min_r
if not isdir(config.theo_fixed_r):
mkdir(config.theo_fixed_r)
savepath = config.theo_fixed_r + str(datetime.now()) + '/'
if not isdir(savepath):
mkdir(savepath)
for r in range(min_r, max_r + 1):
per_dat_points = []
dom_dat_points = []
for domain in ... | .xlabel("Domain Size")
plt.ylabel("% Actual Injective")
plt.savefig(savepath + "r" + str(r) + "tests" + str(num_tests) + ".png")
plt.clf()
def theoretical_fixed_r(min_r, max_r, min_domain, max_domain, domain_skip=5):
| 65 | 65 | 219 | 21 | 44 | ClaytonMcCray/injectionAnalysis | analysis_driver.py | Python | theoretical_fixed_r | theoretical_fixed_r | 89 | 110 | 89 | 89 | 3ed555ce51cc7001eeb779a078cd97b1e0fd420c | bigcode/the-stack | train |
adfe3abc1cff83b48ca764f7 | train | function | def fixed_domain_plots(domain, min_codomain, max_codomain, num_tests, codomain_skip=5):
per_dat_points = []
co_dat_points = []
codomain = min_codomain
for codomain in range(min_codomain, max_codomain + 1, codomain_skip):
actual_per, _ = test(domain, codomain, num_tests)
per_dat_points.ap... | def fixed_domain_plots(domain, min_codomain, max_codomain, num_tests, codomain_skip=5):
| per_dat_points = []
co_dat_points = []
codomain = min_codomain
for codomain in range(min_codomain, max_codomain + 1, codomain_skip):
actual_per, _ = test(domain, codomain, num_tests)
per_dat_points.append(actual_per)
co_dat_points.append(codomain)
plt.ylim(0, 105)
plt.sc... | from os import mkdir
from datetime import datetime
import config
# TODO #####################
# * Need to make a test config. Will be config.py
# to replace the garbage below cluttering up the driver.
def fixed_domain_plots(domain, min_codomain, max_codomain, num_tests, codomain_skip=5):
| 70 | 70 | 234 | 24 | 46 | ClaytonMcCray/injectionAnalysis | analysis_driver.py | Python | fixed_domain_plots | fixed_domain_plots | 16 | 38 | 16 | 16 | 62ef6225e31077f68fe38e451136512218fe6e2e | bigcode/the-stack | train |
82f1dbd08d6265abb4a324ae | train | function | def theoretical_fixed_domain(domain, min_codomain, max_codomain, codomain_skip=5):
per_dat_points = []
co_dat_points = []
for codomain in range(min_codomain, max_codomain + 1, codomain_skip):
per_dat_points.append(theoretical_prob_injective(domain, codomain))
co_dat_points.append(codomain)
... | def theoretical_fixed_domain(domain, min_codomain, max_codomain, codomain_skip=5):
| per_dat_points = []
co_dat_points = []
for codomain in range(min_codomain, max_codomain + 1, codomain_skip):
per_dat_points.append(theoretical_prob_injective(domain, codomain))
co_dat_points.append(codomain)
if not isdir(config.theo_fixed_domain):
mkdir(config.theo_fixed_dom... | if not isdir(savepath):
mkdir(savepath)
plt.savefig(savepath + "d" + str(domain) + "tests" + str(num_tests) + ".png")
plt.clf()
def theoretical_fixed_domain(domain, min_codomain, max_codomain, codomain_skip=5):
| 64 | 64 | 203 | 20 | 44 | ClaytonMcCray/injectionAnalysis | analysis_driver.py | Python | theoretical_fixed_domain | theoretical_fixed_domain | 41 | 60 | 41 | 41 | 09bb4169b878dc027bb043fca78a7dd160cd4829 | bigcode/the-stack | train |
afda9bb0ec222f04fb2a1d0e | train | function | def fixed_r_plots(min_r, max_r, min_domain, max_domain, num_tests, domain_skip=5):
savepath = config.fixed_r + str(datetime.now()) + '/'
if not isdir(config.fixed_r):
mkdir(config.fixed_r)
if not isdir(savepath):
mkdir(savepath)
for r in range(min_r, max_r + 1): # the ratio codomain/do... | def fixed_r_plots(min_r, max_r, min_domain, max_domain, num_tests, domain_skip=5):
| savepath = config.fixed_r + str(datetime.now()) + '/'
if not isdir(config.fixed_r):
mkdir(config.fixed_r)
if not isdir(savepath):
mkdir(savepath)
for r in range(min_r, max_r + 1): # the ratio codomain/domain
per_dat_points = []
dom_dat_points = []
for domain in ... | Domain Plot, k = ' + str(domain))
plt.xlabel('Codomain Size')
plt.ylabel('Probability of Injectiveness')
plt.savefig(savepath + 'd' + str(domain) + '.png')
plt.clf()
def fixed_r_plots(min_r, max_r, min_domain, max_domain, num_tests, domain_skip=5):
| 74 | 74 | 249 | 25 | 49 | ClaytonMcCray/injectionAnalysis | analysis_driver.py | Python | fixed_r_plots | fixed_r_plots | 63 | 86 | 63 | 63 | 74fe3b310bd40ea86960d59aee7edfe57ed73778 | bigcode/the-stack | train |
4afdf39bf0c50d622ebdfdec | train | function | def HaloferacalesArchaeonDl31(
directed: bool = False,
preprocess: bool = True,
load_nodes: bool = True,
verbose: int = 2,
cache: bool = True,
cache_path: str = "graphs/string",
version: str = "links.v11.0",
**additional_graph_kwargs: Dict
) -> Graph:
"""Return new instance of the Ha... | def HaloferacalesArchaeonDl31(
directed: bool = False,
preprocess: bool = True,
load_nodes: bool = True,
verbose: int = 2,
cache: bool = True,
cache_path: str = "graphs/string",
version: str = "links.v11.0",
**additional_graph_kwargs: Dict
) -> Graph:
| """Return new instance of the Haloferacales archaeon DL31 graph.
The graph is automatically retrieved from the STRING repository.
Parameters
-------------------
directed: bool = False
Wether to load the graph as directed or undirected.
By default false.
preprocess: bool = True... | va, Nadezhda T and Morris, John H and Bork, Peer and others},
journal={Nucleic acids research},
volume={47},
number={D1},
pages={D607--D613},
year={2019},
publisher={Oxford University Press}
}
```
"""
from typing import Dict
from ..automatic_graph_retrieval import AutomaticallyRetrievedGraph
fr... | 181 | 181 | 604 | 82 | 98 | AnacletoLAB/ensmallen_graph | bindings/python/ensmallen/datasets/string/haloferacalesarchaeondl31.py | Python | HaloferacalesArchaeonDl31 | HaloferacalesArchaeonDl31 | 30 | 104 | 30 | 39 | eb6154fc33fdd1df4786fe23f04345cb6f24cb31 | bigcode/the-stack | train |
7f1a417aee5001bd047f6d8d | train | class | class LitnetCrawler(Crawler):
base_url = 'https://litnet.com/'
def search_novel(self, query):
query = query.lower().replace(' ', '+')
soup = self.get_soup(search_url % query)
results = []
for a in soup.select('div.l-container ul a'):
results.append({
... | class LitnetCrawler(Crawler):
| base_url = 'https://litnet.com/'
def search_novel(self, query):
query = query.lower().replace(' ', '+')
soup = self.get_soup(search_url % query)
results = []
for a in soup.select('div.l-container ul a'):
results.append({
'title': a.text.strip(),
... | # -*- coding: utf-8 -*-
import logging
from ..utils.crawler import Crawler
logger = logging.getLogger('LITNET')
search_url = 'https://litnet.com/en/search?q=%s'
class LitnetCrawler(Crawler):
| 52 | 204 | 680 | 7 | 45 | Epicpkmn11/lightnovel-crawler | src/sources/litnet.py | Python | LitnetCrawler | LitnetCrawler | 9 | 93 | 9 | 9 | 769c6229d1fd237d56c3cc04d686975f46edf6de | bigcode/the-stack | train |
8849ab272bbbaf5542e9ab89 | train | class | class NestableBlueprint(Blueprint):
def __init__(self, name=None, import_name=None, static_folder=None,
static_url_path=None, template_folder=None,
url_prefix=None, subdomain=None, url_defaults=None,
root_path=None, cur_name=None, cur_file=None):
if name is... | class NestableBlueprint(Blueprint):
| def __init__(self, name=None, import_name=None, static_folder=None,
static_url_path=None, template_folder=None,
url_prefix=None, subdomain=None, url_defaults=None,
root_path=None, cur_name=None, cur_file=None):
if name is None and cur_name:
name... | from flask import Blueprint
from apps.libs.func import cur_abs_path
class NestableBlueprint(Blueprint):
| 20 | 64 | 173 | 6 | 13 | lucylqe/flaskStudy | apps/libs/register_blueprint.py | Python | NestableBlueprint | NestableBlueprint | 6 | 23 | 6 | 6 | f45d48ed187a898d49f6d47e77f2cae47da26bb2 | bigcode/the-stack | train |
63eb352aec42d5153d30682e | train | function | def convert_bytes(value):
"""
Reduces bytes to more convenient units (i.e. KiB, GiB, TiB, etc.).
Args:
values (int): Value in Bytes
Returns:
tup (tuple): Tuple of value, unit (e.g. (10, 'MiB'))
"""
n = np.rint(len(str(value))/4).astype(int)
return value/(1024**n), sizes[n]
| def convert_bytes(value):
| """
Reduces bytes to more convenient units (i.e. KiB, GiB, TiB, etc.).
Args:
values (int): Value in Bytes
Returns:
tup (tuple): Tuple of value, unit (e.g. (10, 'MiB'))
"""
n = np.rint(len(str(value))/4).astype(int)
return value/(1024**n), sizes[n]
| .pop('mk', False)
path = os.sep.join(list(args))
if mk:
while sep2 in path:
path = path.replace(sep2, os.sep)
try:
os.makedirs(path)
except FileExistsError:
pass
return path
def convert_bytes(value):
| 64 | 64 | 95 | 5 | 58 | rdmontgomery/exa | exa/util/utility.py | Python | convert_bytes | convert_bytes | 55 | 66 | 55 | 55 | deccc152e2bbb67a0efb2ecd44023a07b7d01225 | bigcode/the-stack | train |
39c99da418a4e7e2e874b737 | train | function | def datetime_header(title=''):
"""
Creates a simple header string containing the current date/time stamp
delimited using "=".
"""
return '\n'.join(('=' * 80, title + ': ' + str(datetime.now()), '=' * 80))
| def datetime_header(title=''):
| """
Creates a simple header string containing the current date/time stamp
delimited using "=".
"""
return '\n'.join(('=' * 80, title + ': ' + str(datetime.now()), '=' * 80))
| repetition reduction).
"""
import os
import sys
import numpy as np
from datetime import datetime
sep2 = os.sep + os.sep
sizes = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB']
def datetime_header(title=''):
| 64 | 64 | 55 | 6 | 58 | rdmontgomery/exa | exa/util/utility.py | Python | datetime_header | datetime_header | 19 | 24 | 19 | 19 | 3f66602eef8355d7e1d47f0d901f3eb3b4a8f115 | bigcode/the-stack | train |
d54e91998cf91c70af767f1e | train | function | def get_internal_modules(key='exa'):
"""
Get a list of modules belonging to the given package.
Args:
key (str): Package or library name (e.g. "exa")
"""
key += '.'
return [v for k, v in sys.modules.items() if k.startswith(key)]
| def get_internal_modules(key='exa'):
| """
Get a list of modules belonging to the given package.
Args:
key (str): Package or library name (e.g. "exa")
"""
key += '.'
return [v for k, v in sys.modules.items() if k.startswith(key)]
| in Bytes
Returns:
tup (tuple): Tuple of value, unit (e.g. (10, 'MiB'))
"""
n = np.rint(len(str(value))/4).astype(int)
return value/(1024**n), sizes[n]
def get_internal_modules(key='exa'):
| 64 | 64 | 66 | 8 | 56 | rdmontgomery/exa | exa/util/utility.py | Python | get_internal_modules | get_internal_modules | 69 | 77 | 69 | 69 | 2e6b4d59e9a909914a7f0979e576429c246be421 | bigcode/the-stack | train |
104f42385ae685af049f10a4 | train | function | def mkp(*args, **kwargs):
"""
Generate a directory path, and create it if requested.
.. code-block:: Python
filepath = mkp('base', 'folder', 'file')
dirpath = mkp('root', 'path', 'folder', mk=True)
Args:
\*args: File or directory path segments to be concatenated
mk (bo... | def mkp(*args, **kwargs):
| """
Generate a directory path, and create it if requested.
.. code-block:: Python
filepath = mkp('base', 'folder', 'file')
dirpath = mkp('root', 'path', 'folder', mk=True)
Args:
\*args: File or directory path segments to be concatenated
mk (bool): Make the directory (i... | ']
def datetime_header(title=''):
"""
Creates a simple header string containing the current date/time stamp
delimited using "=".
"""
return '\n'.join(('=' * 80, title + ': ' + str(datetime.now()), '=' * 80))
def mkp(*args, **kwargs):
| 64 | 64 | 169 | 8 | 56 | rdmontgomery/exa | exa/util/utility.py | Python | mkp | mkp | 27 | 52 | 27 | 27 | 56cb69ec8faea45b9e6bad4a89fe4cdd3dcec70b | bigcode/the-stack | train |
a2def5ce5d3dba5fcbbdac56 | train | function | def main():
n, *a = map(int, sys.stdin.read().split())
a.sort()
b = list(itertools.accumulate(a))
count = 1
for i in range(n-1, 0, -1):
if a[i] <= b[i-1] * 2:
count += 1
else:
break
print(count)
| def main():
| n, *a = map(int, sys.stdin.read().split())
a.sort()
b = list(itertools.accumulate(a))
count = 1
for i in range(n-1, 0, -1):
if a[i] <= b[i-1] * 2:
count += 1
else:
break
print(count)
| # 2019-11-23 01:09:31(JST)
import itertools
import sys
def main():
| 26 | 64 | 84 | 3 | 22 | kagemeka/atcoder-submissions | jp.atcoder/agc011/agc011_b/8562284.py | Python | main | main | 6 | 19 | 6 | 6 | 30fd23d8c82f29ed27a7f18d95b3584ab42638e8 | bigcode/the-stack | train |
70c06863d424c26815534088 | train | class | class PyreTest(unittest.TestCase):
def assert_imports(self, error_json, expected_imports) -> None:
error = Error(**error_json)
stub = None
if FunctionStub.is_instance(error.inference):
stub = FunctionStub(error.inference)
elif FieldStub.is_instance(error.inference):
... | class PyreTest(unittest.TestCase):
| def assert_imports(self, error_json, expected_imports) -> None:
error = Error(**error_json)
stub = None
if FunctionStub.is_instance(error.inference):
stub = FunctionStub(error.inference)
elif FieldStub.is_instance(error.inference):
stub = FieldStub(error.infer... | ("typing.List"), "List")
self.assertEqual(
dequalify("typing.Union[typing.List[int]]"), "Union[List[int]]"
)
def test__relativize_access(self) -> None:
self.assertEqual(
_relativize_access(
"tools.pyre.client.infer.Stub", "tools/pyre/client/infer.py"
... | 256 | 256 | 2,436 | 8 | 248 | ishaanthakur/pyre-check | client/commands/tests/infer_test.py | Python | PyreTest | PyreTest | 77 | 497 | 77 | 77 | 7d4fcb874e8b5b72a720f90d4e2ac076ce31b967 | bigcode/the-stack | train |
0ce8d9fdd00870a9b5cae1ac | train | class | class InferTest(unittest.TestCase):
@patch("json.loads", return_value=[])
@patch(_typeshed_search_path, Mock(return_value=["path3"]))
@patch.object(commands.Reporting, "_get_directories_to_analyze", return_value=set())
def test_infer(self, directories_to_analyze, json_loads) -> None:
arguments =... | class InferTest(unittest.TestCase):
@patch("json.loads", return_value=[])
@patch(_typeshed_search_path, Mock(return_value=["path3"]))
@patch.object(commands.Reporting, "_get_directories_to_analyze", return_value=set())
| def test_infer(self, directories_to_analyze, json_loads) -> None:
arguments = mock_arguments()
arguments.recursive = False
arguments.strict = False
configuration = mock_configuration()
configuration.get_typeshed.return_value = "stub"
with patch.object(commands.Comma... | "
configuration.search_path = ["path1", "path2"]
configuration.get_typeshed = MagicMock()
configuration.logger = None
configuration.strict = False
return configuration
class InferTest(unittest.TestCase):
@patch("json.loads", return_value=[])
@patch(_typeshed_search_path, Mock(return_value=["... | 92 | 92 | 307 | 53 | 38 | ishaanthakur/pyre-check | client/commands/tests/infer_test.py | Python | InferTest | InferTest | 529 | 574 | 529 | 532 | 56f7a888d099628dc2977a8ae70f51a0c1e095e1 | bigcode/the-stack | train |
80deaaa4a12c94cec78cd581 | train | function | def mock_arguments() -> MagicMock:
arguments = MagicMock()
arguments.debug = False
arguments.additional_check = []
arguments.sequential = False
arguments.show_error_traces = False
arguments.verbose = False
arguments.hide_parse_errors = True
arguments.local_configuration = None
argum... | def mock_arguments() -> MagicMock:
| arguments = MagicMock()
arguments.debug = False
arguments.additional_check = []
arguments.sequential = False
arguments.show_error_traces = False
arguments.verbose = False
arguments.hide_parse_errors = True
arguments.local_configuration = None
arguments.logging_sections = None
ar... | typing.List[int], typing.Any]",
"field_name": "global",
"parent": None,
}
)
],
"""\
from typing import Any, List, Union
global: Union[List[int], Any] = ...
""",
)
def ... | 64 | 64 | 103 | 8 | 56 | ishaanthakur/pyre-check | client/commands/tests/infer_test.py | Python | mock_arguments | mock_arguments | 500 | 516 | 500 | 500 | ea37f32a5388d691015c9aebe2125552a4bcb9e6 | bigcode/the-stack | train |
59e121bf6347d046eac3f511 | train | class | class HelperTest(unittest.TestCase):
def test_dequalify(self) -> None:
self.assertEqual(dequalify("typing.List"), "List")
self.assertEqual(
dequalify("typing.Union[typing.List[int]]"), "Union[List[int]]"
)
def test__relativize_access(self) -> None:
self.assertEqual(
... | class HelperTest(unittest.TestCase):
| def test_dequalify(self) -> None:
self.assertEqual(dequalify("typing.List"), "List")
self.assertEqual(
dequalify("typing.Union[typing.List[int]]"), "Union[List[int]]"
)
def test__relativize_access(self) -> None:
self.assertEqual(
_relativize_access(
... | = "{}.typeshed_search_path".format(commands.infer.__name__)
def build_json(inference):
return {
"line": 0,
"column": 0,
"code": 0,
"name": "name",
"path": "test.py",
"description": "",
"inference": inference,
}
class HelperTest(unittest.TestCase):
| 81 | 81 | 273 | 7 | 74 | ishaanthakur/pyre-check | client/commands/tests/infer_test.py | Python | HelperTest | HelperTest | 38 | 74 | 38 | 38 | 8c9e5ac69d805da861c53f836b82e0da574684b4 | bigcode/the-stack | train |
b7bdf01aee59f586e2444974 | train | function | def build_json(inference):
return {
"line": 0,
"column": 0,
"code": 0,
"name": "name",
"path": "test.py",
"description": "",
"inference": inference,
}
| def build_json(inference):
| return {
"line": 0,
"column": 0,
"code": 0,
"name": "name",
"path": "test.py",
"description": "",
"inference": inference,
}
| Stub,
FunctionStub,
Infer,
StubFile,
_relativize_access,
dequalify,
)
from ...error import Error
from ...filesystem import AnalysisDirectory
_typeshed_search_path = "{}.typeshed_search_path".format(commands.infer.__name__)
def build_json(inference):
| 64 | 64 | 59 | 6 | 58 | ishaanthakur/pyre-check | client/commands/tests/infer_test.py | Python | build_json | build_json | 26 | 35 | 26 | 26 | fa85f68225dd8251b392653d2db0b8d7e87f0180 | bigcode/the-stack | train |
d47d4e2a720eb47ef0815b70 | train | function | def mock_configuration() -> MagicMock:
configuration = MagicMock()
configuration.typeshed = "stub"
configuration.search_path = ["path1", "path2"]
configuration.get_typeshed = MagicMock()
configuration.logger = None
configuration.strict = False
return configuration
| def mock_configuration() -> MagicMock:
| configuration = MagicMock()
configuration.typeshed = "stub"
configuration.search_path = ["path1", "path2"]
configuration.get_typeshed = MagicMock()
configuration.logger = None
configuration.strict = False
return configuration
|
arguments.hide_parse_errors = True
arguments.local_configuration = None
arguments.logging_sections = None
arguments.logger = None
arguments.log_identifier = None
arguments.enable_profiling = None
arguments.current_directory = "."
return arguments
def mock_configuration() -> MagicMock:
| 64 | 64 | 60 | 8 | 55 | ishaanthakur/pyre-check | client/commands/tests/infer_test.py | Python | mock_configuration | mock_configuration | 519 | 526 | 519 | 519 | 50c59fe84e2b00e7e498ba3fa45378467c56eed6 | bigcode/the-stack | train |
83af13c42cda0eded96c1fef | train | function | def run_stderr(name,
cmd,
exec_driver=None,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
ignore_retcode=False,
keep_env=None):
'''
Run :py:func:`cmd.run_stderr <salt.m... | def run_stderr(name,
cmd,
exec_driver=None,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
ignore_retcode=False,
keep_env=None):
| '''
Run :py:func:`cmd.run_stderr <salt.modules.cmdmod.run_stderr>` within a
container
name
Container name or ID in which to run the command
cmd
Command to run
exec_driver : None
If not passed, the execution driver will be detected as described
:ref:`above <dock... | cmd,
exec_driver=exec_driver,
output='all',
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
keep_env=keep... | 111 | 111 | 373 | 48 | 63 | tinyclues/salt | salt/modules/dockerng.py | Python | run_stderr | run_stderr | 4,790 | 4,845 | 4,790 | 4,798 | 9812b12139801deb570a10b6bb4241a30a8e56f5 | bigcode/the-stack | train |
df4d82726b6b6abb749aebe1 | train | function | def tag_(name, image, force=False):
'''
Tag an image into a repository and return ``True``. If the tag was
unsuccessful, an error will be raised.
name
ID of image
image
Tag to apply to the image, in ``repo:tag`` notation. If just the
repository name is passed, a tag name of... | def tag_(name, image, force=False):
| '''
Tag an image into a repository and return ``True``. If the tag was
unsuccessful, an error will be raised.
name
ID of image
image
Tag to apply to the image, in ``repo:tag`` notation. If just the
repository name is passed, a tag name of ``latest`` will be assumed.
fo... | Size'] = os.stat(path).st_size
ret['Size_Human'] = _size_fmt(ret['Size'])
# Process push
if kwargs.get(push, False):
ret['Push'] = __salt__['cp.push'](path)
return ret
def tag_(name, image, force=False):
| 68 | 68 | 229 | 10 | 57 | tinyclues/salt | salt/modules/dockerng.py | Python | tag_ | tag_ | 3,993 | 4,024 | 3,993 | 3,993 | d2817ae10b6c3568c63d0108377365d454b912c6 | bigcode/the-stack | train |
df19d52976fb60e0326ccfab | train | function | def dangling(prune=False, force=False):
'''
Return top-level images (those on which no other images depend) which do
not have a tag assigned to them. These include:
- Images which were once tagged but were later untagged, such as those
which were superseded by committing a new copy of an existing... | def dangling(prune=False, force=False):
| '''
Return top-level images (those on which no other images depend) which do
not have a tag assigned to them. These include:
- Images which were once tagged but were later untagged, such as those
which were superseded by committing a new copy of an existing tagged
image.
- Images which ... | repo_name,
tag=repo_tag,
message=message,
author=author)
ret = {'Time_Elapsed': time.time() - time_started}
_clear_context()
image_id = None
for id_ in ('Id', 'id', 'ID'):
if id_ in response:
image_id = response[id_]
break
if image_id is None... | 129 | 129 | 433 | 9 | 119 | tinyclues/salt | salt/modules/dockerng.py | Python | dangling | dangling | 3,280 | 3,334 | 3,280 | 3,280 | f11b102a45debea347b7cbcc3c230e204375c3ba | bigcode/the-stack | train |
fe852b74e0040de742545bbf | train | function | @_docker_client
def info():
'''
Returns a dictionary of system-wide information. Equivalent to running
the ``docker info`` Docker CLI command.
CLI Example:
.. code-block:: bash
salt myminion dockerng.info
'''
return _client_wrapper('info')
| @_docker_client
def info():
| '''
Returns a dictionary of system-wide information. Equivalent to running
the ``docker info`` Docker CLI command.
CLI Example:
.. code-block:: bash
salt myminion dockerng.info
'''
return _client_wrapper('info')
| ret.update(copy.deepcopy(context_data.get('untagged', {})))
# If verbose info was requested, go get it
if verbose:
for img_id in ret:
ret[img_id]['Info'] = inspect_image(img_id)
return ret
@_docker_client
def info():
| 64 | 64 | 63 | 8 | 55 | tinyclues/salt | salt/modules/dockerng.py | Python | info | info | 2,006 | 2,018 | 2,006 | 2,007 | 21ce81d85ce9f486b7f49f9dc819213367c0b0db | bigcode/the-stack | train |
7f82562ced22add33ac563d6 | train | function | def retcode(name,
cmd,
exec_driver=None,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
ignore_retcode=False,
keep_env=None):
'''
Run :py:func:`cmd.retcode <salt.modules.cmdmod.retcode>` within... | def retcode(name,
cmd,
exec_driver=None,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
ignore_retcode=False,
keep_env=None):
| '''
Run :py:func:`cmd.retcode <salt.modules.cmdmod.retcode>` within a container
name
Container name or ID in which to run the command
cmd
Command to run
exec_driver : None
If not passed, the execution driver will be detected as described
:ref:`above <docker-executi... | python_shell=python_shell,
output_loglevel=output_loglevel,
ignore_retcode=ignore_retcode,
use_vt=use_vt,
keep_env=keep_env)
_cleanup_tempfile(path)
run(name, 'rm ' + path)
return ret
def retcode(name,
cmd,
exec_driver=None,
stdin=None,
... | 110 | 110 | 368 | 47 | 62 | tinyclues/salt | salt/modules/dockerng.py | Python | retcode | retcode | 4,613 | 4,667 | 4,613 | 4,621 | 633ab643a56f300a896c6ba95a2048c663b7e059 | bigcode/the-stack | train |
15d558eba39d51031464fedf | train | function | def inspect_image(name):
'''
Retrieves image information. Equivalent to running the ``docker inspect``
Docker CLI command, but will only look for image information.
name
Image name or ID
**RETURN DATA**
A dictionary of image information
CLI Examples:
.. code-block:: bash
... | def inspect_image(name):
| '''
Retrieves image information. Equivalent to running the ``docker inspect``
Docker CLI command, but will only look for image information.
name
Image name or ID
**RETURN DATA**
A dictionary of image information
CLI Examples:
.. code-block:: bash
salt myminion doc... | A dictionary of container information
CLI Example:
.. code-block:: bash
salt myminion dockerng.inspect_container mycontainer
salt myminion dockerng.inspect_container 0123456789ab
'''
return _client_wrapper('inspect_container', name)
def inspect_image(name):
| 64 | 64 | 161 | 5 | 59 | tinyclues/salt | salt/modules/dockerng.py | Python | inspect_image | inspect_image | 2,088 | 2,114 | 2,088 | 2,088 | 0929f2d566e98885ba2a47e120309ec09317dc09 | bigcode/the-stack | train |
2a12bfb10d89cbe5c2009697 | train | function | def load(path, image=None):
'''
Load a tar archive that was created using :py:func:`dockerng.save
<salt.modules.dockerng.save>` (or via the Docker CLI using ``docker
save``).
path
Path to docker tar archive. Path can be a file on the Minion, or the
URL of a file on the Salt fileserv... | def load(path, image=None):
| '''
Load a tar archive that was created using :py:func:`dockerng.save
<salt.modules.dockerng.save>` (or via the Docker CLI using ``docker
save``).
path
Path to docker tar archive. Path can be a file on the Minion, or the
URL of a file on the Salt fileserver (i.e.
``salt://pa... | )
time_started = time.time()
response = _image_wrapper('import_image',
path,
repository=repo_name,
tag=repo_tag)
ret = {'Time_Elapsed': time.time() - time_started}
_clear_context()
if not response:
ra... | 256 | 256 | 855 | 7 | 248 | tinyclues/salt | salt/modules/dockerng.py | Python | load | load | 3,418 | 3,505 | 3,418 | 3,418 | b433021ee2aadd35e6bd409d64d3e6d4da95c412 | bigcode/the-stack | train |
32d79362b0c9ae9505e89401 | train | function | def list_tags():
'''
Returns a list of tagged images
CLI Example:
.. code-block:: bash
salt myminion dockerng.list_tags
'''
ret = set()
for item in six.itervalues(images()):
for repo_tag in item['RepoTags']:
ret.add(repo_tag)
return sorted(ret)
| def list_tags():
| '''
Returns a list of tagged images
CLI Example:
.. code-block:: bash
salt myminion dockerng.list_tags
'''
ret = set()
for item in six.itervalues(images()):
for repo_tag in item['RepoTags']:
ret.add(repo_tag)
return sorted(ret)
| image>
'''
ret = set()
for item in six.itervalues(ps_(all=kwargs.get('all', False))):
for c_name in [x.lstrip('/') for x in item.get('Names', [])]:
ret.add(c_name)
return sorted(ret)
def list_tags():
| 64 | 64 | 73 | 4 | 60 | tinyclues/salt | salt/modules/dockerng.py | Python | list_tags | list_tags | 2,140 | 2,154 | 2,140 | 2,140 | 9a8ec8967728846da0e7b917cee0e41cd704b7c0 | bigcode/the-stack | train |
f1c0b81853612419b0bb4ebf | train | class | class _api_version(object):
'''
Enforce a specific Docker Remote API version
'''
def __init__(self, api_version):
self.api_version = api_version
def __call__(self, func):
def wrapper(*args, **kwargs):
'''
Get the current client version and check it against th... | class _api_version(object):
| '''
Enforce a specific Docker Remote API version
'''
def __init__(self, api_version):
self.api_version = api_version
def __call__(self, func):
def wrapper(*args, **kwargs):
'''
Get the current client version and check it against the one passed
'''... | = tuple(
[int(x) for x in match.group(1).split('.')]
)
else:
log.warning('Unable to determine docker-py version')
__context__[contextkey] = None
return __context__[contextkey]
# Decorators
class _api_version(object):
| 64 | 64 | 176 | 6 | 57 | tinyclues/salt | salt/modules/dockerng.py | Python | _api_version | _api_version | 530 | 551 | 530 | 530 | 03e2025cfa423c28953c1c9b3d5450bd262df939 | bigcode/the-stack | train |
f91ccc5b1f64283532aa5395 | train | function | def run(name,
cmd,
exec_driver=None,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
ignore_retcode=False,
keep_env=None):
'''
Run :py:func:`cmd.run <salt.modules.cmdmod.run>` within a container
name
Container nam... | def run(name,
cmd,
exec_driver=None,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
ignore_retcode=False,
keep_env=None):
| '''
Run :py:func:`cmd.run <salt.modules.cmdmod.run>` within a container
name
Container name or ID in which to run the command
cmd
Command to run
exec_driver : None
If not passed, the execution driver will be detected as described
:ref:`above <docker-execution-drive... | ,
exec_driver=exec_driver,
output='retcode',
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=ignore_retcode,
keep_env=keep_env)
def run(n... | 108 | 108 | 362 | 46 | 62 | tinyclues/salt | salt/modules/dockerng.py | Python | run | run | 4,670 | 4,724 | 4,670 | 4,678 | d30beb95d788e170743e49bb34e3f5e2edb84fba | bigcode/the-stack | train |
26983f1398e747e611878795 | train | function | @_refresh_mine_cache
@_api_version(1.12)
@_ensure_exists
def unpause(name):
'''
Unpauses a container
name
Container name or ID
**RETURN DATA**
A dictionary will be returned, containing the following keys:
- ``status`` - A dictionary showing the prior state of the container as
... | @_refresh_mine_cache
@_api_version(1.12)
@_ensure_exists
def unpause(name):
| '''
Unpauses a container
name
Container name or ID
**RETURN DATA**
A dictionary will be returned, containing the following keys:
- ``status`` - A dictionary showing the prior state of the container as
well as the new state
- ``result`` - A boolean noting whether or not the... | .format(name))}
ret = _change_state(name, 'stop', 'stopped', timeout=timeout)
ret['state']['old'] = orig_state
return ret
@_refresh_mine_cache
@_api_version(1.12)
@_ensure_exists
def unpause(name):
| 65 | 65 | 219 | 26 | 38 | tinyclues/salt | salt/modules/dockerng.py | Python | unpause | unpause | 4,432 | 4,465 | 4,432 | 4,435 | b0d03f29fc0b9e04037596d30ae777c7f68c2950 | bigcode/the-stack | train |
c1b7fce2351e774ebbae7056 | train | function | @_refresh_mine_cache
def _script(name,
source,
saltenv='base',
args=None,
template=None,
exec_driver=None,
stdin=None,
python_shell=True,
output_loglevel='debug',
ignore_retcode=False,
use_vt=False,
... | @_refresh_mine_cache
def _script(name,
source,
saltenv='base',
args=None,
template=None,
exec_driver=None,
stdin=None,
python_shell=True,
output_loglevel='debug',
ignore_retcode=False,
use_vt=False,
... | '''
Common logic to run a script on a container
'''
def _cleanup_tempfile(path):
'''
Remove the tempfile allocated for the script
'''
try:
os.remove(path)
except (IOError, OSError) as exc:
log.error(
'cmd.script: Unable to c... | output,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
ignore_retcode=ignore_retcode,
use_vt=use_vt,
keep_env=keep_env)
if output in (None, 'all'):
return ret
else:
return ret[output]
@_refresh_mine_cache
def _script(name... | 142 | 142 | 475 | 69 | 73 | tinyclues/salt | salt/modules/dockerng.py | Python | _script | _script | 4,539 | 4,610 | 4,539 | 4,551 | f735acc2319ecf4fbdd8d786ab3fcf44049cf80f | bigcode/the-stack | train |
f2eecce86ccb604111d7b551 | train | function | def _build_status(data, item):
'''
Process a status update from a docker build, updating the data structure
'''
stream = item['stream']
if 'Running in' in stream:
data.setdefault('Intermediate_Containers', []).append(
stream.rstrip().split()[-1])
if 'Successfully built' in st... | def _build_status(data, item):
| '''
Process a status update from a docker build, updating the data structure
'''
stream = item['stream']
if 'Running in' in stream:
data.setdefault('Intermediate_Containers', []).append(
stream.rstrip().split()[-1])
if 'Successfully built' in stream:
data['Id'] = stre... | )
else:
# Allow API errors to be caught further up the stack
raise
except Exception as exc:
raise CommandExecutionError(
'Error occurred performing docker {0}: {1}'.format(attr, exc)
)
return ret
def _build_status(data, item):
| 64 | 64 | 86 | 8 | 55 | tinyclues/salt | salt/modules/dockerng.py | Python | _build_status | _build_status | 911 | 920 | 911 | 911 | a198da7e06122d920753cccf2be3079a12ed68a5 | bigcode/the-stack | train |
8a60221837c48a894721996d | train | function | def exists(name):
'''
Check if a given container exists
name
Container name or ID
**RETURN DATA**
A boolean (``True`` if the container exists, otherwise ``False``)
CLI Example:
.. code-block:: bash
salt myminion dockerng.exists mycontainer
'''
contextkey = 'do... | def exists(name):
| '''
Check if a given container exists
name
Container name or ID
**RETURN DATA**
A boolean (``True`` if the container exists, otherwise ``False``)
CLI Example:
.. code-block:: bash
salt myminion dockerng.exists mycontainer
'''
contextkey = 'docker.exists.{0}'.f... | if 'Unknown' in ret:
log.error(
'Unknown changes detected in docker.diff of container {0}. '
'This is probably due to a change in the Docker API. Please '
'report this to the SaltStack developers'.format(name)
)
return ret
def exists(name):
| 64 | 64 | 155 | 4 | 59 | tinyclues/salt | salt/modules/dockerng.py | Python | exists | exists | 1,819 | 1,847 | 1,819 | 1,819 | 32096773af4b8e32cd55177130a2addfef3301b3 | bigcode/the-stack | train |
0e5fbe35ed9982bd75ab7c8f | train | function | @_docker_client
def _image_wrapper(attr, *args, **kwargs):
'''
Wrapper to run a docker-py function and return a list of dictionaries
'''
catch_api_errors = kwargs.pop('catch_api_errors', True)
if kwargs.pop('client_auth', False):
# Set credentials
registry_auth_config = __pillar__.g... | @_docker_client
def _image_wrapper(attr, *args, **kwargs):
| '''
Wrapper to run a docker-py function and return a list of dictionaries
'''
catch_api_errors = kwargs.pop('catch_api_errors', True)
if kwargs.pop('client_auth', False):
# Set credentials
registry_auth_config = __pillar__.get('docker-registries', {})
for key, data in six.it... | , **kwargs)
except docker.errors.APIError as exc:
if catch_api_errors:
# Generic handling of Docker API errors
raise CommandExecutionError(
'Error {0}: {1}'.format(exc.response.status_code,
exc.explanation)
)
... | 141 | 141 | 472 | 17 | 124 | tinyclues/salt | salt/modules/dockerng.py | Python | _image_wrapper | _image_wrapper | 847 | 908 | 847 | 848 | fa13340d892c97fe5b87d20f22ac8a8fa3ac1d01 | bigcode/the-stack | train |
e44c77d0a47f52cc3cedb403 | train | function | def _import_status(data, item, repo_name, repo_tag):
'''
Process a status update from docker import, updating the data structure
'''
status = item['status']
try:
if 'Downloading from' in status:
return
elif all(x in string.hexdigits for x in status):
# Status ... | def _import_status(data, item, repo_name, repo_tag):
| '''
Process a status update from docker import, updating the data structure
'''
status = item['status']
try:
if 'Downloading from' in status:
return
elif all(x in string.hexdigits for x in status):
# Status is an image ID
data['Image'] = '{0}:{1}'.... | 'Running in' in stream:
data.setdefault('Intermediate_Containers', []).append(
stream.rstrip().split()[-1])
if 'Successfully built' in stream:
data['Id'] = stream.rstrip().split()[-1]
def _import_status(data, item, repo_name, repo_tag):
| 64 | 64 | 114 | 14 | 50 | tinyclues/salt | salt/modules/dockerng.py | Python | _import_status | _import_status | 923 | 936 | 923 | 923 | 93081b3f7866e4eda1632ee52e9901e5be8dc09b | bigcode/the-stack | train |
09306812b72a78c2700f7824 | train | function | @_ensure_exists
def export(name,
path,
overwrite=False,
makedirs=False,
compression=None,
**kwargs):
'''
Exports a container to a tar archive. It can also optionally compress that
tar archive, and push it up to the Master.
name
Container na... | @_ensure_exists
def export(name,
path,
overwrite=False,
makedirs=False,
compression=None,
**kwargs):
| '''
Exports a container to a tar archive. It can also optionally compress that
tar archive, and push it up to the Master.
name
Container name or ID
path
Absolute path on the Minion where the container will be exported
overwrite : False
Unless this option is set to ``Tr... | the
destination is a directory, the file will be copied into that
directory.
exec_driver : None
If not passed, the execution driver will be detected as described
:ref:`above <docker-execution-driver>`.
overwrite : False
Unless this option is set to ``True``, then if a ... | 256 | 256 | 1,367 | 30 | 226 | tinyclues/salt | salt/modules/dockerng.py | Python | export | export | 2,867 | 3,045 | 2,867 | 2,873 | 720c5610e4651f1293633f90a4210ab03b7632f5 | bigcode/the-stack | train |
75a610dbca6a9e977fc0d4d6 | train | function | def images(verbose=False, **kwargs):
'''
Returns information about the Docker images on the Minion. Equivalent to
running the ``docker images`` Docker CLI command.
all : False
If ``True``, untagged images will also be returned
verbose : False
If ``True``, a ``docker inspect`` will ... | def images(verbose=False, **kwargs):
| '''
Returns information about the Docker images on the Minion. Equivalent to
running the ``docker images`` Docker CLI command.
all : False
If ``True``, untagged images will also be returned
verbose : False
If ``True``, a ``docker inspect`` will be run on each image returned.
... | is 'FROM scratch'
val = 'FROM scratch'
else:
val = command_prefix.sub('', val)
step[step_key] = val
if 'Time_Created_Epoch' in step:
step['Time_Created_Local'] = \
time.strftime(
'%Y-%m-%d %H:%M:... | 157 | 157 | 526 | 8 | 148 | tinyclues/salt | salt/modules/dockerng.py | Python | images | images | 1,939 | 2,003 | 1,939 | 1,939 | e0753ac2af97b06022ef63ea99c3f29f6684024e | bigcode/the-stack | train |
c481dffb07189df6cb3454b1 | train | function | def _change_state(name, action, expected, *args, **kwargs):
'''
Change the state of a container
'''
pre = state(name)
if action != 'restart' and pre == expected:
return {'result': False,
'state': {'old': expected, 'new': expected},
'comment': ('Container \'{0}... | def _change_state(name, action, expected, *args, **kwargs):
| '''
Change the state of a container
'''
pre = state(name)
if action != 'restart' and pre == expected:
return {'result': False,
'state': {'old': expected, 'new': expected},
'comment': ('Container \'{0}\' already {1}'
.format(name, ex... | returned = wrapped(*args, **salt.utils.clean_kwargs(**kwargs))
__salt__['mine.send']('dockerng.ps', verbose=True, all=True, host=True)
return returned
return wrapper
# Helper functions
def _change_state(name, action, expected, *args, **kwargs):
| 64 | 64 | 181 | 16 | 47 | tinyclues/salt | salt/modules/dockerng.py | Python | _change_state | _change_state | 603 | 624 | 603 | 603 | 9624de048e0fec869f100804b4870b854ac17ba4 | bigcode/the-stack | train |
737bd7db416333795f2e4764 | train | function | def depends(name):
'''
Returns the containers and images, if any, which depend on the given image
name
Name or ID of image
**RETURN DATA**
A dictionary containing the following keys:
- ``Containers`` - A list of containers which depend on the specified image
- ``Images`` - A lis... | def depends(name):
| '''
Returns the containers and images, if any, which depend on the given image
name
Name or ID of image
**RETURN DATA**
A dictionary containing the following keys:
- ``Containers`` - A list of containers which depend on the specified image
- ``Images`` - A list of IDs of images ... | # Run validation function
_locals[key](*validation_arg)
# Clear any context variables created during validation process
for key in list(__context__):
try:
if key.startswith('validation.docker.'):
__context__.pop(key)
except AttributeError:
... | 73 | 73 | 244 | 4 | 68 | tinyclues/salt | salt/modules/dockerng.py | Python | depends | depends | 1,736 | 1,773 | 1,736 | 1,736 | 02a4887d91da23c5d913251ea3117d4024cd477b | bigcode/the-stack | train |
d1021c27b5493375f4b4c63e | train | function | def ps_(**kwargs):
'''
Returns information about the Docker containers on the Minion. Equivalent
to running the ``docker ps`` Docker CLI command.
all : False
If ``True``, stopped containers will also be returned
host: False
If ``True``, local host's network topology will be include... | def ps_(**kwargs):
| '''
Returns information about the Docker containers on the Minion. Equivalent
to running the ``docker ps`` Docker CLI command.
all : False
If ``True``, stopped containers will also be returned
host: False
If ``True``, local host's network topology will be included
verbose : Fa... | '{0}/*'.format(private_port)
else:
err = (
'Invalid private_port \'{0}\'. Must either be a port number, '
'or be in port/protocol notation (e.g. 5000/tcp)'
.format(private_port)
)
try:
port_num, _, protocol = pr... | 154 | 154 | 514 | 6 | 148 | tinyclues/salt | salt/modules/dockerng.py | Python | ps_ | ps_ | 2,255 | 2,322 | 2,255 | 2,255 | 5ca0c5cba20be92ee52b53b73a8b798efbaed202 | bigcode/the-stack | train |
b41763519cf46925235f33e3 | train | function | @_ensure_exists
def restart(name, timeout=10):
'''
Restarts a container
name
Container name or ID
timeout : 10
Timeout in seconds after which the container will be killed (if it has
not yet gracefully shut down)
**RETURN DATA**
A dictionary will be returned, containi... | @_ensure_exists
def restart(name, timeout=10):
| '''
Restarts a container
name
Container name or ID
timeout : 10
Timeout in seconds after which the container will be killed (if it has
not yet gracefully shut down)
**RETURN DATA**
A dictionary will be returned, containing the following keys:
- ``status`` - A di... | state': {'old': orig_state, 'new': orig_state},
'comment': ('Container \'{0}\' is stopped, cannot pause'
.format(name))}
return _change_state(name, 'pause', 'paused')
freeze = pause
@_ensure_exists
def restart(name, timeout=10):
| 66 | 66 | 220 | 13 | 52 | tinyclues/salt | salt/modules/dockerng.py | Python | restart | restart | 4,095 | 4,129 | 4,095 | 4,096 | c77fb828282cadc9d24dcd669d73d958431f2cff | bigcode/the-stack | train |
5901d13ce8c2ddcf17bd285b | train | function | def run_all(name,
cmd,
exec_driver=None,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
ignore_retcode=False,
keep_env=None):
'''
Run :py:func:`cmd.run_all <salt.modules.cmdmod.run_all>` within... | def run_all(name,
cmd,
exec_driver=None,
stdin=None,
python_shell=True,
output_loglevel='debug',
use_vt=False,
ignore_retcode=False,
keep_env=None):
| '''
Run :py:func:`cmd.run_all <salt.modules.cmdmod.run_all>` within a container
.. note::
While the command is run within the container, it is initiated from the
host. Therefore, the PID in the return dict is from the host, not from
the container.
name
Container name o... | ls -l /etc'
'''
return _run(name,
cmd,
exec_driver=exec_driver,
output=None,
stdin=stdin,
python_shell=python_shell,
output_loglevel=output_loglevel,
use_vt=use_vt,
ignore_retcode=igno... | 123 | 123 | 410 | 47 | 76 | tinyclues/salt | salt/modules/dockerng.py | Python | run_all | run_all | 4,727 | 4,787 | 4,727 | 4,735 | 0c392263bb655f89c9fed0dde7554882672ed460 | bigcode/the-stack | train |
3760662f1d22925fb94922ed | train | function | @_refresh_mine_cache
def create(image,
name=None,
client_timeout=CLIENT_TIMEOUT,
**kwargs):
'''
Create a new container
name
Name for the new container. If not provided, Docker will randomly
generate one for you.
image
Image from which to create ... | @_refresh_mine_cache
def create(image,
name=None,
client_timeout=CLIENT_TIMEOUT,
**kwargs):
| '''
Create a new container
name
Name for the new container. If not provided, Docker will randomly
generate one for you.
image
Image from which to create the container
command
Command to run in the container
Example: ``command=bash``
hostname
H... | ret = []
for process in response['Processes']:
cur_proc = {}
for idx, val in enumerate(process):
cur_proc[columns[idx]] = val
ret.append(cur_proc)
return ret
def version():
'''
Returns a dictionary of Docker version information. Equivlent to running
the ``do... | 256 | 256 | 1,547 | 26 | 229 | tinyclues/salt | salt/modules/dockerng.py | Python | create | create | 2,499 | 2,700 | 2,499 | 2,503 | 550a4159ad6d17235ee1fbb6dbe15d0df1e41a49 | bigcode/the-stack | train |
11d2bbf162b22bbbf1efecf8 | train | function | def import_(source,
image,
api_response=False):
'''
Imports content from a local tarball or a URL as a new docker image
source
Content to import (URL or absolute path to a tarball). URL can be a
file on the Salt fileserver (i.e.
``salt://path/to/rootfs/tarba... | def import_(source,
image,
api_response=False):
| '''
Imports content from a local tarball or a URL as a new docker image
source
Content to import (URL or absolute path to a tarball). URL can be a
file on the Salt fileserver (i.e.
``salt://path/to/rootfs/tarball.tar.xz``. To import a file from a
saltenv other than ``base``... | successful, ``False`` if
not)
CLI Example:
.. code-block:: bash
salt myminion dockerng.dangling
salt myminion dockerng.dangling prune=True
'''
all_images = images(all=True)
dangling_images = [x[:12] for x in _get_top_level_images(all_images)
if '<non... | 192 | 192 | 641 | 13 | 178 | tinyclues/salt | salt/modules/dockerng.py | Python | import_ | import_ | 3,337 | 3,415 | 3,337 | 3,339 | 9765249b373ba167ad49795b29c3474815776299 | bigcode/the-stack | train |
ed57dd3b83e20037eea11469 | train | function | def _pull_status(data, item):
'''
Process a status update from a docker pull, updating the data structure.
For containers created with older versions of Docker, there is no
distinction in the status updates between layers that were already present
(and thus not necessary to download), and those whi... | def _pull_status(data, item):
| '''
Process a status update from a docker pull, updating the data structure.
For containers created with older versions of Docker, there is no
distinction in the status updates between layers that were already present
(and thus not necessary to download), and those which were actually
downloade... | stream.rstrip().split()[-1])
if 'Successfully built' in stream:
data['Id'] = stream.rstrip().split()[-1]
def _import_status(data, item, repo_name, repo_tag):
'''
Process a status update from docker import, updating the data structure
'''
status = item['status']
try:
if 'Downlo... | 153 | 153 | 513 | 8 | 144 | tinyclues/salt | salt/modules/dockerng.py | Python | _pull_status | _pull_status | 939 | 996 | 939 | 939 | 1fcfac7b3aa2e4f36f7bfb6230b1764c02591bc4 | bigcode/the-stack | train |
c497841fc0bee66b91c66515 | train | function | def list_containers(**kwargs):
'''
Returns a list of containers by name. This is different from
:py:func:`dockerng.ps <salt.modules.dockerng.ps_>` in that
:py:func:`dockerng.ps <salt.modules.dockerng.ps_>` returns its results
organized by container ID.
all : False
If ``True``, stopped c... | def list_containers(**kwargs):
| '''
Returns a list of containers by name. This is different from
:py:func:`dockerng.ps <salt.modules.dockerng.ps_>` in that
:py:func:`dockerng.ps <salt.modules.dockerng.ps_>` returns its results
organized by container ID.
all : False
If ``True``, stopped containers will be included in r... | 6789ab
'''
ret = _client_wrapper('inspect_image', name)
for param in ('Size', 'VirtualSize'):
if param in ret:
ret['{0}_Human'.format(param)] = _size_fmt(ret[param])
return ret
def list_containers(**kwargs):
| 64 | 64 | 173 | 7 | 56 | tinyclues/salt | salt/modules/dockerng.py | Python | list_containers | list_containers | 2,117 | 2,137 | 2,117 | 2,117 | 02351a7e5f411352a277e13e244110465f3c23ad | bigcode/the-stack | train |
a036a65b5171b3e1f98f70d6 | train | function | @_ensure_exists
def inspect_container(name):
'''
Retrieves container information. Equivalent to running the ``docker
inspect`` Docker CLI command, but will only look for container information.
name
Container name or ID
**RETURN DATA**
A dictionary of container information
CLI E... | @_ensure_exists
def inspect_container(name):
| '''
Retrieves container information. Equivalent to running the ``docker
inspect`` Docker CLI command, but will only look for container information.
name
Container name or ID
**RETURN DATA**
A dictionary of container information
CLI Example:
.. code-block:: bash
sa... | return inspect_image(name)
except CommandExecutionError as exc:
if not exc.strerror.startswith('Error 404'):
raise
raise CommandExecutionError(
'Error 404: No such image/container: {0}'.format(name)
)
@_ensure_exists
def inspect_container(name):
| 64 | 64 | 112 | 10 | 54 | tinyclues/salt | salt/modules/dockerng.py | Python | inspect_container | inspect_container | 2,063 | 2,085 | 2,063 | 2,064 | fed223e86924d98cae3edcac7d8d8561ef2de31a | bigcode/the-stack | train |
936458db479bb842ded62fe5 | train | function | def _ensure_exists(wrapped):
'''
Decorator to ensure that the named container exists.
'''
@functools.wraps(wrapped)
def wrapper(name, *args, **kwargs):
'''
Check for container existence and raise an error if it does not exist
'''
if not exists(name):
raise... | def _ensure_exists(wrapped):
| '''
Decorator to ensure that the named container exists.
'''
@functools.wraps(wrapped)
def wrapper(name, *args, **kwargs):
'''
Check for container existence and raise an error if it does not exist
'''
if not exists(name):
raise CommandExecutionError(
... | **kwargs):
'''
Ensure that the client is present
'''
client_timeout = __context__.get('docker.timeout', CLIENT_TIMEOUT)
_get_client(timeout=client_timeout)
return wrapped(*args, **salt.utils.clean_kwargs(**kwargs))
return wrapper
def _ensure_exists(wrapped):
| 64 | 64 | 111 | 7 | 56 | tinyclues/salt | salt/modules/dockerng.py | Python | _ensure_exists | _ensure_exists | 570 | 584 | 570 | 570 | c796d1aa7cd8f731584ce9cda216825fe0a4d1f5 | bigcode/the-stack | train |
db3652dde2c2712ff587860b | train | function | @_ensure_exists
def top(name):
'''
Runs the `docker top` command on a specific container
name
Container name or ID
CLI Example:
**RETURN DATA**
A list of dictionaries containing information about each process
.. code-block:: bash
salt myminion dockerng.top mycontainer... | @_ensure_exists
def top(name):
| '''
Runs the `docker top` command on a specific container
name
Container name or ID
CLI Example:
**RETURN DATA**
A list of dictionaries containing information about each process
.. code-block:: bash
salt myminion dockerng.top mycontainer
salt myminion dockerng... | = item[key]
if not limit:
return results
ret = {}
for key, val in six.iteritems(results):
for item in limit:
if val.get(item, False):
ret[key] = val
break
return ret
@_ensure_exists
def top(name):
| 64 | 64 | 182 | 9 | 54 | tinyclues/salt | salt/modules/dockerng.py | Python | top | top | 2,432 | 2,467 | 2,432 | 2,433 | 4e0108a26df24ec28b2c21f88506f8d19b56eba1 | bigcode/the-stack | train |
7b44169682ca46c39f03f6d8 | train | function | def _size_fmt(num):
'''
Format bytes as human-readable file sizes
'''
try:
num = int(num)
if num < 1024:
return '{0} bytes'.format(num)
num /= 1024.0
for unit in ('KiB', 'MiB', 'GiB', 'TiB', 'PiB'):
if num < 1024.0:
return '{0:3.1f}... | def _size_fmt(num):
| '''
Format bytes as human-readable file sizes
'''
try:
num = int(num)
if num < 1024:
return '{0} bytes'.format(num)
num /= 1024.0
for unit in ('KiB', 'MiB', 'GiB', 'TiB', 'PiB'):
if num < 1024.0:
return '{0:3.1f} {1}'.format(num, un... | Populate __context__ with the current (pre-pull) image IDs (see the
docstring for _pull_status for more information).
'''
__context__['dockerng._pull_status'] = \
[x[:12] for x in images(all=True)]
def _size_fmt(num):
| 63 | 64 | 143 | 6 | 57 | tinyclues/salt | salt/modules/dockerng.py | Python | _size_fmt | _size_fmt | 799 | 814 | 799 | 799 | 9281a61e925ac8e291df66ba84720c7ac632f103 | bigcode/the-stack | train |
98072488f32bcee2c0c000d1 | train | function | def _docker_client(wrapped):
'''
Decorator to run a function that requires the use of a docker.Client()
instance.
'''
@functools.wraps(wrapped)
def wrapper(*args, **kwargs):
'''
Ensure that the client is present
'''
client_timeout = __context__.get('docker.timeout... | def _docker_client(wrapped):
| '''
Decorator to run a function that requires the use of a docker.Client()
instance.
'''
@functools.wraps(wrapped)
def wrapper(*args, **kwargs):
'''
Ensure that the client is present
'''
client_timeout = __context__.get('docker.timeout', CLIENT_TIMEOUT)
_g... | API version of at least '
'{0}. API version in use is {1}.'
.format(self.api_version, current_api_version)
)
return func(*args, **salt.utils.clean_kwargs(**kwargs))
return _mimic_signature(func, wrapper)
def _docker_client(wrapped):
| 64 | 64 | 103 | 7 | 57 | tinyclues/salt | salt/modules/dockerng.py | Python | _docker_client | _docker_client | 554 | 567 | 554 | 554 | dca47097365f3454a3cd29fc73af6b9b02603b9e | bigcode/the-stack | train |
63b95cce4f09371504be8693 | train | function | def version():
'''
Returns a dictionary of Docker version information. Equivlent to running
the ``docker version`` Docker CLI command.
CLI Example:
.. code-block:: bash
salt myminion dockerng.version
'''
ret = _client_wrapper('version')
version_re = re.compile(VERSION_RE)
... | def version():
| '''
Returns a dictionary of Docker version information. Equivlent to running
the ``docker version`` Docker CLI command.
CLI Example:
.. code-block:: bash
salt myminion dockerng.version
'''
ret = _client_wrapper('version')
version_re = re.compile(VERSION_RE)
if 'Version' in... | ']):
columns[idx] = col_name
# Build return dict
ret = []
for process in response['Processes']:
cur_proc = {}
for idx, val in enumerate(process):
cur_proc[columns[idx]] = val
ret.append(cur_proc)
return ret
def version():
| 64 | 64 | 178 | 3 | 60 | tinyclues/salt | salt/modules/dockerng.py | Python | version | version | 2,470 | 2,495 | 2,470 | 2,470 | b321d3af87eecf1b33d1f0d920a2c0a2202662ac | bigcode/the-stack | train |
a2f9f25f569d03b7bf2dde16 | train | function | def inspect(name):
'''
This is a generic container/image inspecton function. It will first attempt
to get container information for the passed name/ID using
:py:func:`docker.inspect_container
<salt.modules.dockerng.inspect_container>`, and then will try to get image
information for the passed na... | def inspect(name):
| '''
This is a generic container/image inspecton function. It will first attempt
to get container information for the passed name/ID using
:py:func:`docker.inspect_container
<salt.modules.dockerng.inspect_container>`, and then will try to get image
information for the passed name/ID using :py:fun... | ret[img_id]['Info'] = inspect_image(img_id)
return ret
@_docker_client
def info():
'''
Returns a dictionary of system-wide information. Equivalent to running
the ``docker info`` Docker CLI command.
CLI Example:
.. code-block:: bash
salt myminion dockerng.info
'''
... | 85 | 85 | 284 | 4 | 81 | tinyclues/salt | salt/modules/dockerng.py | Python | inspect | inspect | 2,021 | 2,060 | 2,021 | 2,021 | 03b6d9beb80dd248412b3ecb8b2ee89f828170df | bigcode/the-stack | train |
073c0bea87c9ea4e40b53727 | train | function | def _get_repo_tag(image, default_tag='latest'):
'''
Resolves the docker repo:tag notation and returns repo name and tag
'''
if ':' in image:
r_name, r_tag = image.rsplit(':', 1)
if not r_tag:
# Would happen if some wiseguy requests a tag ending in a colon
# (e.g. ... | def _get_repo_tag(image, default_tag='latest'):
| '''
Resolves the docker repo:tag notation and returns repo name and tag
'''
if ':' in image:
r_name, r_tag = image.rsplit(':', 1)
if not r_tag:
# Would happen if some wiseguy requests a tag ending in a colon
# (e.g. 'somerepo:')
log.warning(
... | 'nsenter'
else:
raise NotImplementedError(
'Unknown docker ExecutionDriver \'{0}\', or didn\'t find '
'command to attach to the container'.format(driver)
)
return __context__[contextkey]
def _get_repo_tag(image, default_tag='latest'):
| 64 | 64 | 150 | 12 | 52 | tinyclues/salt | salt/modules/dockerng.py | Python | _get_repo_tag | _get_repo_tag | 753 | 770 | 753 | 753 | ff2430197ea7c439870bd563773843472eb6a1d6 | bigcode/the-stack | train |
737aa79f9446220e389ca66a | train | function | @_refresh_mine_cache
@_api_version(1.12)
@_ensure_exists
def pause(name):
'''
Pauses a container
name
Container name or ID
**RETURN DATA**
A dictionary will be returned, containing the following keys:
- ``status`` - A dictionary showing the prior state of the container as
well... | @_refresh_mine_cache
@_api_version(1.12)
@_ensure_exists
def pause(name):
| '''
Pauses a container
name
Container name or ID
**RETURN DATA**
A dictionary will be returned, containing the following keys:
- ``status`` - A dictionary showing the prior state of the container as
well as the new state
- ``result`` - A boolean noting whether or not the a... |
CLI Example:
.. code-block:: bash
salt myminion dockerng.kill mycontainer
'''
return _change_state(name, 'kill', 'stopped')
@_refresh_mine_cache
@_api_version(1.12)
@_ensure_exists
def pause(name):
| 64 | 64 | 213 | 25 | 39 | tinyclues/salt | salt/modules/dockerng.py | Python | pause | pause | 4,057 | 4,090 | 4,057 | 4,060 | 3f4ca4db542747d97b72418b107f38da1535ee75 | bigcode/the-stack | train |
d2e90c2313d2ee8a5389b33e | train | function | def history(name, quiet=False):
'''
Return the history for an image. Equivalent to running the ``docker
history`` Docker CLI command.
name
Container name or ID
quiet : False
If ``True``, the return data will simply be a list of the commands run
to build the container.
... | def history(name, quiet=False):
| '''
Return the history for an image. Equivalent to running the ``docker
history`` Docker CLI command.
name
Container name or ID
quiet : False
If ``True``, the return data will simply be a list of the commands run
to build the container.
.. code-block:: bash
... | ret = {}
for change in changes:
key = kind_map.get(change['Kind'], 'Unknown')
ret.setdefault(key, []).append(change['Path'])
if 'Unknown' in ret:
log.error(
'Unknown changes detected in docker.diff of container {0}. '
'This is probably due to a change in the Dock... | 256 | 256 | 860 | 7 | 249 | tinyclues/salt | salt/modules/dockerng.py | Python | history | history | 1,850 | 1,936 | 1,850 | 1,850 | d10b1e838f52b1f6d124b3871c1d6eda621b9458 | bigcode/the-stack | train |
1167fd9a18231bc2f5c81005 | train | function | def _prep_pull():
'''
Populate __context__ with the current (pre-pull) image IDs (see the
docstring for _pull_status for more information).
'''
__context__['dockerng._pull_status'] = \
[x[:12] for x in images(all=True)]
| def _prep_pull():
| '''
Populate __context__ with the current (pre-pull) image IDs (see the
docstring for _pull_status for more information).
'''
__context__['dockerng._pull_status'] = \
[x[:12] for x in images(all=True)]
| in filter_ if x not in parents]
except (KeyError, TypeError):
raise CommandExecutionError(
'Invalid image data passed to _get_top_level_images(). Please '
'report this issue. Full image data: {0}'.format(imagedata)
)
def _prep_pull():
| 64 | 64 | 65 | 5 | 59 | tinyclues/salt | salt/modules/dockerng.py | Python | _prep_pull | _prep_pull | 790 | 796 | 790 | 790 | e71bb502b3c2265c2a0991d3d1d859c0ce407f4a | bigcode/the-stack | train |
049d38d930adce6ba670bee6 | train | function | def _get_client(timeout=None):
'''
Obtains a connection to a docker API (socket or URL) based on config.get
mechanism (pillar -> grains)
By default it will use the base docker-py defaults which
at the time of writing are using the local socket and
the 1.4 API
Set those keys in your configu... | def _get_client(timeout=None):
| '''
Obtains a connection to a docker API (socket or URL) based on config.get
mechanism (pillar -> grains)
By default it will use the base docker-py defaults which
at the time of writing are using the local socket and
the 1.4 API
Set those keys in your configuration tree somehow:
-... | the dict is modified during
# iteration.
keep_context = (
'docker.client', 'docker.exec_driver', 'dockerng._pull_status',
'docker.docker_version', 'docker.docker_py_version'
)
for key in list(__context__):
try:
if key.startswith('docker.') and key not in keep_context... | 96 | 96 | 322 | 7 | 88 | tinyclues/salt | salt/modules/dockerng.py | Python | _get_client | _get_client | 646 | 681 | 646 | 646 | 07ffdcff6bb30d24b3125290f4dbf706b40ce62d | bigcode/the-stack | train |
4f1ad39d62d890cc5f52979f | train | function | @_docker_client
def _client_wrapper(attr, *args, **kwargs):
'''
Common functionality for getting information from a container
'''
catch_api_errors = kwargs.pop('catch_api_errors', True)
func = getattr(__context__['docker.client'], attr)
if func is None:
raise SaltInvocationError('Invalid... | @_docker_client
def _client_wrapper(attr, *args, **kwargs):
| '''
Common functionality for getting information from a container
'''
catch_api_errors = kwargs.pop('catch_api_errors', True)
func = getattr(__context__['docker.client'], attr)
if func is None:
raise SaltInvocationError('Invalid client action \'{0}\''.format(attr))
err = ''
try:
... | .1f} {1}'.format(num, unit)
num /= 1024.0
except Exception:
log.error('Unable to format file size for \'{0}\''.format(num))
return 'unknown'
@_docker_client
def _client_wrapper(attr, *args, **kwargs):
| 65 | 65 | 217 | 17 | 48 | tinyclues/salt | salt/modules/dockerng.py | Python | _client_wrapper | _client_wrapper | 817 | 844 | 817 | 818 | 978f39dedf46549e578237b06bad6d3fb5e99d5c | bigcode/the-stack | train |
f3683a5d65eb5e07adf32049 | train | function | @_refresh_mine_cache
@_ensure_exists
def stop(name, timeout=STOP_TIMEOUT, **kwargs):
'''
Stops a running container
name
Container name or ID
unpause : False
If ``True`` and the container is paused, it will be unpaused before
attempting to stop the container.
timeout : 10
... | @_refresh_mine_cache
@_ensure_exists
def stop(name, timeout=STOP_TIMEOUT, **kwargs):
| '''
Stops a running container
name
Container name or ID
unpause : False
If ``True`` and the container is paused, it will be unpaused before
attempting to stop the container.
timeout : 10
Timeout in seconds after which the container will be killed (if it has
... | (VALID_RUNTIME_OPTS)):
if key in runtime_kwargs:
val = VALID_RUNTIME_OPTS[key]
if 'api_name' in val:
runtime_kwargs[val['api_name']] = runtime_kwargs.pop(key)
log.debug(
'dockerng.start is using the following kwargs to start container '
'\'{0}\': {1}'... | 121 | 121 | 405 | 24 | 97 | tinyclues/salt | salt/modules/dockerng.py | Python | stop | stop | 4,376 | 4,429 | 4,376 | 4,378 | 347893707f0ca36664f7c93599c38dc071c78228 | bigcode/the-stack | train |
ca4e4b432ce68c6ed3c98577 | train | function | def build(path=None,
image=None,
cache=True,
rm=True,
api_response=False,
fileobj=None):
'''
Builds a docker image from a Dockerfile or a URL
path
Path to directory on the Minion containing a Dockerfile
image
Image to be built, in ``rep... | def build(path=None,
image=None,
cache=True,
rm=True,
api_response=False,
fileobj=None):
| '''
Builds a docker image from a Dockerfile or a URL
path
Path to directory on the Minion containing a Dockerfile
image
Image to be built, in ``repo:tag`` notation. If just the repository
name is passed, a tag name of ``latest`` will be assumed. If building
from a URL, ... | force : False
If ``True``, the container will be killed first before removal, as the
Docker API will not permit a running container to be removed. This
option is set to ``False`` by default to prevent accidental removal of
a running container.
volumes : False
Also remove... | 256 | 256 | 925 | 27 | 228 | tinyclues/salt | salt/modules/dockerng.py | Python | build | build | 3,091 | 3,213 | 3,091 | 3,096 | 43ad1d0633935bbba82d2e00d8e8be954211ce04 | bigcode/the-stack | train |
02559f6b0c3de7fa46c6a685 | train | function | @_refresh_mine_cache
@_ensure_exists
def _run(name,
cmd,
exec_driver=None,
output=None,
stdin=None,
python_shell=True,
output_loglevel='debug',
ignore_retcode=False,
use_vt=False,
keep_env=None):
'''
Common logic for docker.run fun... | @_refresh_mine_cache
@_ensure_exists
def _run(name,
cmd,
exec_driver=None,
output=None,
stdin=None,
python_shell=True,
output_loglevel='debug',
ignore_retcode=False,
use_vt=False,
keep_env=None):
| '''
Common logic for docker.run functions
'''
if exec_driver is None:
exec_driver = _get_exec_driver()
ret = __salt__['container_resource.run'](
name,
cmd,
container_type=__virtualname__,
exec_driver=exec_driver,
output=output,
stdin=stdin,
... | @_refresh_mine_cache
@_ensure_exists
def _run(name,
cmd,
exec_driver=None,
output=None,
stdin=None,
python_shell=True,
output_loglevel='debug',
ignore_retcode=False,
use_vt=False,
keep_env=None):
| 63 | 64 | 200 | 63 | 0 | tinyclues/salt | salt/modules/dockerng.py | Python | _run | _run | 4,503 | 4,536 | 4,503 | 4,514 | 898f7c0cde7dcc00467b26393d564219bde2a6f8 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.