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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
01306be31dc3a920951cc1ad | train | class | class ImageNotFound(Exception):
pass
| class ImageNotFound(Exception):
| pass
| cfg.BoolOpt('floating', default=True,
help="Don't test using floating networks."),
cfg.IntOpt('build-timeout', default=60,
help="Maximum time to wait for a server to become ACTIVE."),
]
CONF.register_opts(opts)
CONF.register_cli_opts(opts)
class ImageNotFound(Exception):
| 64 | 64 | 9 | 6 | 58 | CiscoCloud/sdu-test-sanity | sanity/controller.py | Python | ImageNotFound | ImageNotFound | 97 | 98 | 97 | 97 | d7588673edc7995f179b10370b5b2455590c1d66 | bigcode/the-stack | train |
60a417d920d9757c3142d87a | train | function | def list_servers(client, all_tenants=False, limit=None, **kwargs):
servers = []
marker = None
opts = {}
if limit:
opts['limit'] = limit
if all_tenants:
opts["all_tenants"] = True
opts.update(kwargs)
while True:
if marker:
opts["marker"] = marker
... | def list_servers(client, all_tenants=False, limit=None, **kwargs):
| servers = []
marker = None
opts = {}
if limit:
opts['limit'] = limit
if all_tenants:
opts["all_tenants"] = True
opts.update(kwargs)
while True:
if marker:
opts["marker"] = marker
result = client.servers.list(search_opts=opts)
if not resu... | .register_opts(opts)
CONF.register_cli_opts(opts)
class ImageNotFound(Exception):
pass
def random_string(length):
return ''.join([random.choice(string.ascii_letters + string.digits)
for _ in range(length)])
def list_servers(client, all_tenants=False, limit=None, **kwargs):
| 63 | 64 | 129 | 16 | 47 | CiscoCloud/sdu-test-sanity | sanity/controller.py | Python | list_servers | list_servers | 106 | 131 | 106 | 106 | 246d09f73703960a1923828bee37e815a6414f6b | bigcode/the-stack | train |
337cd1ab24f798667e6eb77a | train | function | def random_string(length):
return ''.join([random.choice(string.ascii_letters + string.digits)
for _ in range(length)])
| def random_string(length):
| return ''.join([random.choice(string.ascii_letters + string.digits)
for _ in range(length)])
| =True,
help="Don't test using floating networks."),
cfg.IntOpt('build-timeout', default=60,
help="Maximum time to wait for a server to become ACTIVE."),
]
CONF.register_opts(opts)
CONF.register_cli_opts(opts)
class ImageNotFound(Exception):
pass
def random_string(length):
| 64 | 64 | 28 | 5 | 58 | CiscoCloud/sdu-test-sanity | sanity/controller.py | Python | random_string | random_string | 101 | 103 | 101 | 101 | ae549ae1b04668447fd6c72d05cbf62ac624bd93 | bigcode/the-stack | train |
6d3ccc5ac3c442e81d0d9a42 | train | class | class SanityController(object):
_services = None
_test_results = {}
def __init__(self, state):
self.state = state
def setUp(self):
self.state.setUp()
def tearDown(self):
self.state.tearDown()
def add_test_result(self, test_name, host, server, result):
if test_... | class SanityController(object):
| _services = None
_test_results = {}
def __init__(self, state):
self.state = state
def setUp(self):
self.state.setUp()
def tearDown(self):
self.state.tearDown()
def add_test_result(self, test_name, host, server, result):
if test_name not in self._test_results:
... | =self.keystone.session.get_project_id(),
network_id=subnet['network_id']):
LOG.info("Delete port %s", port['id'])
self.neutron.delete_port(port['id'])
self.neutron.delete_subnet(subnet['id'])
#
# Floating IP
#
def clean_flo... | 256 | 256 | 1,985 | 6 | 249 | CiscoCloud/sdu-test-sanity | sanity/controller.py | Python | SanityController | SanityController | 642 | 896 | 642 | 642 | 892a28dffe2312412929e5a4c85fab82738968e0 | bigcode/the-stack | train |
6d82d30507d1bc9e400d23bb | train | function | @app.route("/")
def index():
return "Hello from Flask + Docker" | @app.route("/")
def index():
| return "Hello from Flask + Docker" | from app import app
@app.route("/")
def index():
| 11 | 64 | 15 | 6 | 4 | DD4F/dockerFlaskApp | flask/app/views.py | Python | index | index | 3 | 5 | 3 | 4 | 5273fbc8e6fa7300b1156c8c0f434640eb76cdf3 | bigcode/the-stack | train |
2f264982b0936936abf30a17 | train | class | class IParallel(Base):
'''Parallel machine interface. Available only in OpenDSS v8+'''
__slots__ = []
def CreateActor(self):
self.CheckForError(self._lib.Parallel_CreateActor())
def Wait(self):
self.CheckForError(self._lib.Parallel_Wait())
@property
def ActiveActor(self):
... | class IParallel(Base):
| '''Parallel machine interface. Available only in OpenDSS v8+'''
__slots__ = []
def CreateActor(self):
self.CheckForError(self._lib.Parallel_CreateActor())
def Wait(self):
self.CheckForError(self._lib.Parallel_Wait())
@property
def ActiveActor(self):
'''Gets/sets the I... | '''
A compatibility layer for DSS C-API that mimics the official OpenDSS COM interface.
Copyright (c) 2016-2020 Paulo Meira
'''
from __future__ import absolute_import
from .._cffi_api_util import Base
class IParallel(Base):
| 58 | 190 | 636 | 5 | 52 | dss-extensions/dss_python | dss/dss_capi_ir/IParallel.py | Python | IParallel | IParallel | 9 | 85 | 9 | 9 | fbda53651eb7d182d36686c15c1522f6a1aef324 | bigcode/the-stack | train |
64ce623747a4f94749447aa4 | train | class | class Test_MetricThreshold(TestCase):
def testMetricThreshold_Normal_Warning_Warning(self):
notifyMethod1 = ThresholdNotificationMethodLookup(notification_method='Email')
notifyMethod1.save()
category1 = ThresholdCategoryLookup(category_name='Cpu')
category1.save()
thresholdMetric1 = ThresholdMe... | class Test_MetricThreshold(TestCase):
| def testMetricThreshold_Normal_Warning_Warning(self):
notifyMethod1 = ThresholdNotificationMethodLookup(notification_method='Email')
notifyMethod1.save()
category1 = ThresholdCategoryLookup(category_name='Cpu')
category1.save()
thresholdMetric1 = ThresholdMetricLookup(category=category1, metric_... | from django.test import TestCase
from django.utils import timezone
from dbaas.models import Server, DbmsTypeChoices
from metrics.models import Metrics_Cpu
from monitor.models import ThresholdTest, Incident, ThresholdNotificationMethodLookup, ThresholdCategoryLookup, ThresholdMetricLookup, PredicateTypeChoices, \
Inc... | 84 | 256 | 4,313 | 8 | 75 | BrianWaganerSTL/RocketDBaaS_api | monitor/tests/test_incident.py | Python | Test_MetricThreshold | Test_MetricThreshold | 11 | 397 | 11 | 11 | e67cc3d2ce118298833437287f357f0eca396284 | bigcode/the-stack | train |
8fbf8d51e41155044dcc9d9f | train | class | @router.websocket("/guest/{slug}")
class GuestWebSocket(APIWebSocketEndpoint):
async def on_connect(self, ws: WebSocket) -> None:
# TODO Pass both feature id and guest id in route path and handle adding
# guest to feature guest list here, and use another endpoint for non-guest
# visitors.
... | @router.websocket("/guest/{slug}")
class GuestWebSocket(APIWebSocketEndpoint):
| async def on_connect(self, ws: WebSocket) -> None:
# TODO Pass both feature id and guest id in route path and handle adding
# guest to feature guest list here, and use another endpoint for non-guest
# visitors.
feature_slug = ws.scope["path_params"].get("slug")
if not (featur... | import asyncio
import logging
from typing import Any
from fastapi import APIRouter, WebSocket, status
from app.api.dependencies.publish import publish_feature
from app.core.redis import ChannelReader, redis
from app.models.features import Feature
from app.utils.endpoints import APIWebSocketEndpoint
logger = logging.... | 92 | 94 | 315 | 17 | 75 | garytyler/uvp-web | backend/app/api/ws/endpoints/guest.py | Python | GuestWebSocket | GuestWebSocket | 16 | 47 | 16 | 17 | 3c510c9e46f35f76eddbe07a4368415eb2d0c09c | bigcode/the-stack | train |
d199248b3049dbad0eb04a30 | train | function | def evaluate(backend_str: str, prog: QuantumCircuit, shots: int, b: str) -> Any:
# Q: which backend should we use?
# get state vector
quantum_state = get_statevector(prog)
# get simulate results
# provider = IBMQ.load_account()
# backend = provider.get_backend(backend_str)
# qobj = compil... | def evaluate(backend_str: str, prog: QuantumCircuit, shots: int, b: str) -> Any:
# Q: which backend should we use?
# get state vector
| quantum_state = get_statevector(prog)
# get simulate results
# provider = IBMQ.load_account()
# backend = provider.get_backend(backend_str)
# qobj = compile(prog, backend, shots)
# job = backend.run(qobj)
# job.result()
backend = Aer.get_backend(backend_str)
# transpile/schedule ->... | ">": quantum_state[i]
for i in range(2 ** qubits)
}
return quantum_state
def evaluate(backend_str: str, prog: QuantumCircuit, shots: int, b: str) -> Any:
# Q: which backend should we use?
# get state vector
| 64 | 64 | 207 | 40 | 23 | UCLA-SEAL/QDiff | data/p3BR/R2/benchmark/startQiskit_Class105.py | Python | evaluate | evaluate | 119 | 144 | 119 | 122 | b10c9ca940b970d4d19b6f07945612b8b52297e9 | bigcode/the-stack | train |
d20c60613a69c951e40711ff | train | function | def bernstein_test_3(rep: str):
"""111 . x + 1"""
a = "111"
b = "1"
return bitwise_xor(bitwise_dot(a, rep), b)
| def bernstein_test_3(rep: str):
| """111 . x + 1"""
a = "111"
b = "1"
return bitwise_xor(bitwise_dot(a, rep), b)
| wise_dot(a, rep), b)
def bernstein_test_2(rep: str):
"""000 . x + 0"""
a = "000"
b = "0"
return bitwise_xor(bitwise_dot(a, rep), b)
def bernstein_test_3(rep: str):
| 64 | 64 | 46 | 10 | 54 | UCLA-SEAL/QDiff | data/p3BR/R2/benchmark/startQiskit_Class105.py | Python | bernstein_test_3 | bernstein_test_3 | 161 | 165 | 161 | 161 | 0742d48a46c02f51d3f8e159385ce0c81d77f66b | bigcode/the-stack | train |
634390c4665e09bd94ae3a83 | train | function | def bitwise_dot(s: str, t: str) -> str:
length = len(s)
res = 0
for i in range(length):
res += int(s[i]) * int(t[i])
return str(res % 2)
| def bitwise_dot(s: str, t: str) -> str:
| length = len(s)
res = 0
for i in range(length):
res += int(s[i]) * int(t[i])
return str(res % 2)
| (s: str, t: str) -> str:
length = len(s)
res = []
for i in range(length):
res.append(str(int(s[i]) ^ int(t[i])))
return ''.join(res[::-1])
def bitwise_dot(s: str, t: str) -> str:
| 64 | 64 | 54 | 15 | 49 | UCLA-SEAL/QDiff | data/p3BR/R2/benchmark/startQiskit_Class105.py | Python | bitwise_dot | bitwise_dot | 25 | 30 | 25 | 25 | 078fbe078cfdf1766c9b9ac20f7a3207be47445c | bigcode/the-stack | train |
8b733b8e2f87f5adacfc687a | train | function | def get_statevector(prog: QuantumCircuit) -> Any:
state_backend = Aer.get_backend('statevector_simulator')
statevec = execute(prog, state_backend).result()
quantum_state = statevec.get_statevector()
qubits = round(log2(len(quantum_state)))
quantum_state = {
"|" + np.binary_repr(i, qubits) + ... | def get_statevector(prog: QuantumCircuit) -> Any:
| state_backend = Aer.get_backend('statevector_simulator')
statevec = execute(prog, state_backend).result()
quantum_state = statevec.get_statevector()
qubits = round(log2(len(quantum_state)))
quantum_state = {
"|" + np.binary_repr(i, qubits) + ">": quantum_state[i]
for i in range(2 ** ... | )] + [input_qubit[n]])
# apply H back (QFT on Z_2^n)
for i in range(n):
prog.h(input_qubit[i])
prog.barrier()
# measure
return prog
def get_statevector(prog: QuantumCircuit) -> Any:
| 64 | 64 | 103 | 13 | 50 | UCLA-SEAL/QDiff | data/p3BR/R2/benchmark/startQiskit_Class105.py | Python | get_statevector | get_statevector | 107 | 116 | 107 | 107 | e5032f490d6496bbb41a69d831ae5ffe92923f47 | bigcode/the-stack | train |
c67f68d7e44a97ef4c9ae94c | train | function | def build_oracle(n: int, f: Callable[[str], str]) -> QuantumCircuit:
# implement the oracle O_f
# NOTE: use multi_control_toffoli_gate ('noancilla' mode)
# https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html
# https://quantumcomputing.stackexchange.com/qu... | def build_oracle(n: int, f: Callable[[str], str]) -> QuantumCircuit:
# implement the oracle O_f
# NOTE: use multi_control_toffoli_gate ('noancilla' mode)
# https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html
# https://quantumcomputing.stackexchange.com/qu... | controls = QuantumRegister(n, "ofc")
target = QuantumRegister(1, "oft")
oracle = QuantumCircuit(controls, target, name="Of")
for i in range(2 ** n):
rep = np.binary_repr(i, n)
if f(rep) == "1":
for j in range(n):
if rep[j] == "0":
oracle.x(... | def build_oracle(n: int, f: Callable[[str], str]) -> QuantumCircuit:
# implement the oracle O_f
# NOTE: use multi_control_toffoli_gate ('noancilla' mode)
# https://qiskit.org/documentation/_modules/qiskit/aqua/circuits/gates/multi_control_toffoli_gate.html
# https://quantumcomputing.stackexchange.com/qu... | 144 | 89 | 299 | 144 | 0 | UCLA-SEAL/QDiff | data/p3BR/R2/benchmark/startQiskit_Class105.py | Python | build_oracle | build_oracle | 33 | 54 | 33 | 38 | 0071147babef29fa85b08f7f54c866bc2df8a77d | bigcode/the-stack | train |
f2b1fca4f841fc158a96bf98 | train | function | def build_circuit(n: int, f: Callable[[str], str]) -> QuantumCircuit:
# implement the Bernstein-Vazirani circuit
zero = np.binary_repr(0, n)
b = f(zero)
# initial n + 1 bits
input_qubit = QuantumRegister(n+1, "qc")
classicals = ClassicalRegister(n, "qm")
prog = QuantumCircuit(input_qubit, c... | def build_circuit(n: int, f: Callable[[str], str]) -> QuantumCircuit:
# implement the Bernstein-Vazirani circuit
| zero = np.binary_repr(0, n)
b = f(zero)
# initial n + 1 bits
input_qubit = QuantumRegister(n+1, "qc")
classicals = ClassicalRegister(n, "qm")
prog = QuantumCircuit(input_qubit, classicals)
# inverse last one (can be omitted if using O_f^\pm)
prog.x(input_qubit[n])
# circuit begin
... | in range(2 ** n):
rep = np.binary_repr(i, n)
if f(rep) == "1":
for j in range(n):
if rep[j] == "0":
oracle.x(controls[j])
oracle.mct(controls, target[0], None, mode='noancilla')
for j in range(n):
if rep[j] == "0":
... | 146 | 146 | 488 | 30 | 115 | UCLA-SEAL/QDiff | data/p3BR/R2/benchmark/startQiskit_Class105.py | Python | build_circuit | build_circuit | 57 | 104 | 57 | 58 | 56f9767e9a4499835f054d1208ce02276a3d3995 | bigcode/the-stack | train |
1fb96269fc382a4f7a2d6874 | train | function | def bitwise_xor(s: str, t: str) -> str:
length = len(s)
res = []
for i in range(length):
res.append(str(int(s[i]) ^ int(t[i])))
return ''.join(res[::-1])
| def bitwise_xor(s: str, t: str) -> str:
| length = len(s)
res = []
for i in range(length):
res.append(str(int(s[i]) ^ int(t[i])))
return ''.join(res[::-1])
| plot_histogram
from typing import *
from pprint import pprint
from math import log2
from collections import Counter
from qiskit.test.mock import FakeVigo, FakeYorktown
kernel = 'circuit/bernstein'
def bitwise_xor(s: str, t: str) -> str:
| 64 | 64 | 54 | 16 | 48 | UCLA-SEAL/QDiff | data/p3BR/R2/benchmark/startQiskit_Class105.py | Python | bitwise_xor | bitwise_xor | 17 | 22 | 17 | 17 | 643dca80c9054c8a7c10bfe226d5dd994f1f8215 | bigcode/the-stack | train |
8d80085eb22d76fcb783945c | train | function | def bernstein_test_2(rep: str):
"""000 . x + 0"""
a = "000"
b = "0"
return bitwise_xor(bitwise_dot(a, rep), b)
| def bernstein_test_2(rep: str):
| """000 . x + 0"""
a = "000"
b = "0"
return bitwise_xor(bitwise_dot(a, rep), b)
| "b": b
}
def bernstein_test_1(rep: str):
"""011 . x + 1"""
a = "011"
b = "1"
return bitwise_xor(bitwise_dot(a, rep), b)
def bernstein_test_2(rep: str):
| 64 | 64 | 46 | 10 | 54 | UCLA-SEAL/QDiff | data/p3BR/R2/benchmark/startQiskit_Class105.py | Python | bernstein_test_2 | bernstein_test_2 | 154 | 158 | 154 | 154 | ecac49988b56cfed1a0454174a25979f5eb6025f | bigcode/the-stack | train |
174c530e7032045d3702c091 | train | function | def bernstein_test_1(rep: str):
"""011 . x + 1"""
a = "011"
b = "1"
return bitwise_xor(bitwise_dot(a, rep), b)
| def bernstein_test_1(rep: str):
| """011 . x + 1"""
a = "011"
b = "1"
return bitwise_xor(bitwise_dot(a, rep), b)
| ).most_common(1)[0][0][::-1]
return {
"measurements": counts,
# "state": statevec,
"quantum_state": quantum_state,
"a": a,
"b": b
}
def bernstein_test_1(rep: str):
| 64 | 64 | 46 | 10 | 54 | UCLA-SEAL/QDiff | data/p3BR/R2/benchmark/startQiskit_Class105.py | Python | bernstein_test_1 | bernstein_test_1 | 147 | 151 | 147 | 147 | 35198fb96ad89ce990168d489b08f6b40106a884 | bigcode/the-stack | train |
84fd5924203c39eed41bff72 | train | function | def get_VGG_16_model(input_shape, model_path):
model = tf.keras.applications.vgg16.VGG16(
input_shape = input_shape,
weights = "imagenet",
include_top = False
)
model.save(model_path)
logging.info(f"VGG16 base model saved at: {model_path} ")
return model
| def get_VGG_16_model(input_shape, model_path):
| model = tf.keras.applications.vgg16.VGG16(
input_shape = input_shape,
weights = "imagenet",
include_top = False
)
model.save(model_path)
logging.info(f"VGG16 base model saved at: {model_path} ")
return model
| import tensorflow as tf
import os
import logging
def get_VGG_16_model(input_shape, model_path):
| 24 | 64 | 77 | 13 | 10 | sushantsur23/dvc_tensorflow | src/utils/models.py | Python | get_VGG_16_model | get_VGG_16_model | 7 | 16 | 7 | 7 | 26d0c5c5b753e43944ad842a19eed510b2076bb1 | bigcode/the-stack | train |
cdec92e06977983ffc845e0a | train | function | def prepare_model(model, CLASSES, freeze_all, freeze_till,learning_rate):
if freeze_all:
for layer in model.layers:
layer.trainable = False
elif (freeze_till is not None) and (freeze_till>1):
for layer in model.layers[:-freeze_till]:
layer.trainable = False
##add our... | def prepare_model(model, CLASSES, freeze_all, freeze_till,learning_rate):
| if freeze_all:
for layer in model.layers:
layer.trainable = False
elif (freeze_till is not None) and (freeze_till>1):
for layer in model.layers[:-freeze_till]:
layer.trainable = False
##add our full connected layers
flatten_in =tf.keras.layers.Flatten()(model.ou... | input_shape,
weights = "imagenet",
include_top = False
)
model.save(model_path)
logging.info(f"VGG16 base model saved at: {model_path} ")
return model
def prepare_model(model, CLASSES, freeze_all, freeze_till,learning_rate):
| 64 | 64 | 202 | 18 | 45 | sushantsur23/dvc_tensorflow | src/utils/models.py | Python | prepare_model | prepare_model | 18 | 46 | 18 | 18 | 4ce887d02bd1ed650845f9fcd6eec8990bd46095 | bigcode/the-stack | train |
abf15d3808caeb9918ddb0e0 | train | function | @click.command()
def main(args=None):
"""Console script for data_science."""
click.echo("Replace this message by putting your code into "
"data_science.cli.main")
click.echo("See click documentation at https://click.palletsprojects.com/")
return 0
| @click.command()
def main(args=None):
| """Console script for data_science."""
click.echo("Replace this message by putting your code into "
"data_science.cli.main")
click.echo("See click documentation at https://click.palletsprojects.com/")
return 0
| """Console script for data_science."""
import sys
import click
@click.command()
def main(args=None):
| 22 | 64 | 60 | 8 | 13 | Yue-Du/data_science | data_science/cli.py | Python | main | main | 6 | 12 | 6 | 7 | 6da53fc6572aa3ee0023c6e7cddbb2ec886a82f4 | bigcode/the-stack | train |
d0a64516e29187383007ac38 | train | function | def finalizer() -> None:
"""Logs all the closure information and opens the spreadsheet."""
console_logger.info(f'Total Stocks instantiated: {overall}')
console_logger.info(f'Total Stocks analyzed: {analyzed}')
console_logger.info(f'Total Stocks failed to analyze: {overall - analyzed}')
time_taken =... | def finalizer() -> None:
| """Logs all the closure information and opens the spreadsheet."""
console_logger.info(f'Total Stocks instantiated: {overall}')
console_logger.info(f'Total Stocks analyzed: {analyzed}')
console_logger.info(f'Total Stocks failed to analyze: {overall - analyzed}')
time_taken = time_converter(round(per... | _web_index(), find_free_port()
console_logger.info(f'Hosting the analyzer results at: http://{host}:{port}')
server = HTTPServer(server_address=(host, port), RequestHandlerClass=SimpleHTTPRequestHandler)
while True:
server.serve_forever()
def finalizer() -> None:
| 64 | 64 | 126 | 7 | 57 | thevickypedia/stock_analyzer | thor_api.py | Python | finalizer | finalizer | 358 | 369 | 358 | 358 | 431455c65c45538fb299d3075d680974deeb864a | bigcode/the-stack | train |
2c4342c3047c8abe8502ac11 | train | function | def get_web_index() -> str:
"""Fetches the IP address of the host machine.
Returns:
str:
Host IP address.
"""
ip_socket = socket(AF_INET, SOCK_DGRAM)
ip_socket.connect(("8.8.8.8", 80))
if not (host := ip_socket.getsockname()[0]):
host = gethostbyname('localhost')
ip_... | def get_web_index() -> str:
| """Fetches the IP address of the host machine.
Returns:
str:
Host IP address.
"""
ip_socket = socket(AF_INET, SOCK_DGRAM)
ip_socket.connect(("8.8.8.8", 80))
if not (host := ip_socket.getsockname()[0]):
host = gethostbyname('localhost')
ip_socket.close()
return ho... | random port number that is free.
"""
with closing(socket(AF_INET, SOCK_STREAM)) as sock:
sock.bind(('', 0))
sock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
return sock.getsockname()[1]
def get_web_index() -> str:
| 64 | 64 | 94 | 8 | 56 | thevickypedia/stock_analyzer | thor_api.py | Python | get_web_index | get_web_index | 331 | 343 | 331 | 331 | 4c045381873f0b891a79262c8e62c19072e64d78 | bigcode/the-stack | train |
fda03ed9b9123e78a278535b | train | function | def host_as_webpage():
"""Converts the generated spreadsheet as an HTML file and hosts it on localserver."""
console_logger.info(f'Converting {filename} to an HTML file.')
wb_to_html = read_excel(filename)
wb_to_html.to_html('index.html')
host, port = get_web_index(), find_free_port()
console_lo... | def host_as_webpage():
| """Converts the generated spreadsheet as an HTML file and hosts it on localserver."""
console_logger.info(f'Converting {filename} to an HTML file.')
wb_to_html = read_excel(filename)
wb_to_html.to_html('index.html')
host, port = get_web_index(), find_free_port()
console_logger.info(f'Hosting the... | = socket(AF_INET, SOCK_DGRAM)
ip_socket.connect(("8.8.8.8", 80))
if not (host := ip_socket.getsockname()[0]):
host = gethostbyname('localhost')
ip_socket.close()
return host
def host_as_webpage():
| 64 | 64 | 122 | 6 | 57 | thevickypedia/stock_analyzer | thor_api.py | Python | host_as_webpage | host_as_webpage | 346 | 355 | 346 | 346 | 1df6bf230d0a0669a1326a162e8203cde9413b50 | bigcode/the-stack | train |
9a08973005020c3ca2737ec3 | train | function | def sort_by_value(data: dict, sort: int) -> dict:
"""Sorts the dictionary.
Args:
data: Dictionary which has to be sorted.
sort: Index value of the list in the ``value`` of the dictionary.
Returns:
dict:
Returns the dictionary which is sorted by a particular element in the l... | def sort_by_value(data: dict, sort: int) -> dict:
| """Sorts the dictionary.
Args:
data: Dictionary which has to be sorted.
sort: Index value of the list in the ``value`` of the dictionary.
Returns:
dict:
Returns the dictionary which is sorted by a particular element in the list of values.
"""
column_name = headers[1... | import tqdm
from urllib3.exceptions import ProtocolError
from xlsxwriter import Workbook
from yfinance import Ticker
if not path.isdir('logs'):
mkdir('logs')
if not path.isdir('data'):
mkdir('data')
def sort_by_value(data: dict, sort: int) -> dict:
| 64 | 64 | 175 | 15 | 49 | thevickypedia/stock_analyzer | thor_api.py | Python | sort_by_value | sort_by_value | 29 | 47 | 29 | 29 | 57da47e78b14a43915ffe60f1aaf1989e1ccad04 | bigcode/the-stack | train |
8115781d9242d7bc5a0a65e4 | train | function | def writer(mapping_dict: dict) -> int:
"""Writes the global variable value ``{stock_map}`` to a spreadsheet.
Args:
mapping_dict: Takes a dictionary as argument.
Returns:
int:
Returns the number of elements in the dictionary.
"""
n = 0
for ticker in mapping_dict:
... | def writer(mapping_dict: dict) -> int:
| """Writes the global variable value ``{stock_map}`` to a spreadsheet.
Args:
mapping_dict: Takes a dictionary as argument.
Returns:
int:
Returns the number of elements in the dictionary.
"""
n = 0
for ticker in mapping_dict:
n = n + 1
worksheet.write(n, 0... | # increases count_404 for future handling
file_logger.error(f'Failed to analyze {stock}. Faced error code {err.code} while requesting {err.url}. '
f'Reason: {err.reason}.')
except (ConnectionError, ProtocolError, ConnectionResetError, ChunkedEncodingError) as conn_err:
... | 96 | 97 | 324 | 10 | 86 | thevickypedia/stock_analyzer | thor_api.py | Python | writer | writer | 212 | 242 | 212 | 212 | 2c8957c2048aa530ed0be112ae545bfcf415f4fa | bigcode/the-stack | train |
c68f83a2096d4d7bf3fe7115 | train | function | def analyzer(stock: str) -> None:
"""Gathers all the necessary details from each stock ticker. Calls ``extract_data()`` to get specifics.
Args:
stock: Takes stock ticker value as argument.
See Also:
- Captures the number of ``404`` responses in a global variable.
- Exits if a ``503... | def analyzer(stock: str) -> None:
| """Gathers all the necessary details from each stock ticker. Calls ``extract_data()`` to get specifics.
Args:
stock: Takes stock ticker value as argument.
See Also:
- Captures the number of ``404`` responses in a global variable.
- Exits if a ``503`` is received or if 50% requests ... | TimeEmployees')
employees = numerize(fte) if fte else None
recommendation = data.get('recommendationMean')
rating = float(recommendation) if recommendation else None
stock_data = [stock_name, capital, dividend_yield, pe_ratio, pb_ratio, price, today_high, today_low, high_52_weeks,
lo... | 143 | 144 | 482 | 9 | 134 | thevickypedia/stock_analyzer | thor_api.py | Python | analyzer | analyzer | 174 | 209 | 174 | 174 | ea537429d950564b06b2bdb03f22ef4199addefe | bigcode/the-stack | train |
50506a5357d0ea78eb08c026 | train | function | def columns() -> list:
"""Names of the columns that needs to be on the header in the spreadsheet.
Returns:
list:
List of headers for the spreadsheet.
"""
return [
"Stock Ticker",
"Stock Name",
"Market Capital",
"Dividend Yield",
"PE Ratio",
... | def columns() -> list:
| """Names of the columns that needs to be on the header in the spreadsheet.
Returns:
list:
List of headers for the spreadsheet.
"""
return [
"Stock Ticker",
"Stock Name",
"Market Capital",
"Dividend Yield",
"PE Ratio",
"PB Ratio",
"... | [sort]:
value[sort] = 999_999
data[key] = value
reverse_flag = False if column_name == 'Rating' else True
return dict(sorted(data.items(), key=lambda element: element[1][sort], reverse=reverse_flag))
def columns() -> list:
| 64 | 64 | 126 | 6 | 58 | thevickypedia/stock_analyzer | thor_api.py | Python | columns | columns | 50 | 74 | 50 | 50 | aeb60e2adf09482c9832d14e6e7e758d113f551e | bigcode/the-stack | train |
26f113329977993df94e2a88 | train | function | def get_sort_key() -> int:
"""Displays a menu to the user, and prompts to choose how the user likes to sort the spreadsheet.
Returns:
int:
Returns the index value using which the sorting has to be done.
"""
title = "Please pick a value using which you'd like to sort the spreadsheet (Hit... | def get_sort_key() -> int:
| """Displays a menu to the user, and prompts to choose how the user likes to sort the spreadsheet.
Returns:
int:
Returns the index value using which the sorting has to be done.
"""
title = "Please pick a value using which you'd like to sort the spreadsheet (Hit Ctrl+C to sort by stock ti... | 60
seconds %= 60
if hour:
return f'{hour} hours {minutes} minutes {seconds} seconds'
elif minutes:
return f'{minutes} minutes {seconds} seconds'
elif seconds:
return f'{seconds} seconds'
def get_sort_key() -> int:
| 64 | 64 | 216 | 8 | 56 | thevickypedia/stock_analyzer | thor_api.py | Python | get_sort_key | get_sort_key | 268 | 287 | 268 | 268 | 30913985b500aa0d0b3c116c057660e3896cd57c | bigcode/the-stack | train |
2ce3967c63ef657ce1cb9992 | train | function | def find_free_port() -> int:
"""Instead of binding to a specific port, ``sock.bind(('', 0))`` is used to bind to 0.
See Also:
- The OS will then pick an available port.
- The port number chosen can be found using ``sock.getsockname()[1]``
- Passing it on to the slaves so that they can c... | def find_free_port() -> int:
| """Instead of binding to a specific port, ``sock.bind(('', 0))`` is used to bind to 0.
See Also:
- The OS will then pick an available port.
- The port number chosen can be found using ``sock.getsockname()[1]``
- Passing it on to the slaves so that they can connect back.
- ``sock... | zing Stocks', unit='stock', leave=True))
except ConnectionRefusedError:
root_logger.error('Connection has been refused.')
except KeyboardInterrupt:
root_logger.error('Manual interrupt was received.')
ThreadPoolExecutor().shutdown(wait=False, cancel_futures=True)
def find_free_port() -> int:
| 64 | 64 | 166 | 8 | 56 | thevickypedia/stock_analyzer | thor_api.py | Python | find_free_port | find_free_port | 312 | 328 | 312 | 312 | 269df56792b782a57f69a8add7452d09d400fd27 | bigcode/the-stack | train |
166f1ad0c032f454fd6732e7 | train | function | def time_converter(seconds: int) -> str:
"""Converts seconds to appropriate hours/minutes.
Args:
seconds: Takes the number of seconds as argument.
Returns:
str:
Converted seconds to human readable values.
"""
seconds = seconds % (24 * 3600)
hour = seconds // 3600
se... | def time_converter(seconds: int) -> str:
| """Converts seconds to appropriate hours/minutes.
Args:
seconds: Takes the number of seconds as argument.
Returns:
str:
Converted seconds to human readable values.
"""
seconds = seconds % (24 * 3600)
hour = seconds // 3600
seconds %= 3600
minutes = seconds // 60... | worksheet.write(n, 13, mapping_dict[ticker][12])
worksheet.write(n, 14, mapping_dict[ticker][13])
worksheet.write(n, 15, mapping_dict[ticker][14])
workbook.close()
return len(mapping_dict)
def time_converter(seconds: int) -> str:
| 64 | 64 | 141 | 10 | 54 | thevickypedia/stock_analyzer | thor_api.py | Python | time_converter | time_converter | 245 | 265 | 245 | 245 | 2c50fc69eac89200218fafb97f03e0e7f7229361 | bigcode/the-stack | train |
0cb7c517d93df86863bdb61c | train | function | def thread_executor() -> None:
"""Executes ``ThreadPool`` on all stock tickers with a max workers limit of 10.
Warnings:
- ``max_workers`` for ThreadPool is set to 10.
- Increasing the number of workers will decrease the run time but may elevate the chances of a ``503`` response.
- Shut... | def thread_executor() -> None:
| """Executes ``ThreadPool`` on all stock tickers with a max workers limit of 10.
Warnings:
- ``max_workers`` for ThreadPool is set to 10.
- Increasing the number of workers will decrease the run time but may elevate the chances of a ``503`` response.
- Shuts down the ThreadPool during ei... | .")
root_logger.error("Either use a terminal or enable 'Emulate terminal in output console' under "
f"Edit Configurations.. -> Execution in your {run_env}.")
root_logger.error("Using default index to sort the spreadsheet.")
else:
root_logger.erro... | 72 | 72 | 240 | 7 | 65 | thevickypedia/stock_analyzer | thor_api.py | Python | thread_executor | thread_executor | 290 | 309 | 290 | 290 | 446695e2183bfa34b032ae3c008c9991ad4950ea | bigcode/the-stack | train |
567c4245f62071b866d03ac5 | train | function | def worksheet_initializer() -> None:
"""Creates header in each column."""
worksheet.write(0, 0, headers[0])
worksheet.write(0, 1, headers[1])
worksheet.write(0, 2, headers[2])
worksheet.write(0, 3, headers[3])
worksheet.write(0, 4, headers[4])
worksheet.write(0, 5, headers[5])
worksheet.... | def worksheet_initializer() -> None:
| """Creates header in each column."""
worksheet.write(0, 0, headers[0])
worksheet.write(0, 1, headers[1])
worksheet.write(0, 2, headers[2])
worksheet.write(0, 3, headers[3])
worksheet.write(0, 4, headers[4])
worksheet.write(0, 5, headers[5])
worksheet.write(0, 6, headers[6])
worksheet... | "PB Ratio",
"Current Price",
"Today's High",
"Today's Low",
"52W High",
"52W Low",
"5Y Dividend Yield",
"Profit Margin",
"Industry",
"Employees",
"Rating"
]
def worksheet_initializer() -> None:
| 65 | 66 | 223 | 7 | 58 | thevickypedia/stock_analyzer | thor_api.py | Python | worksheet_initializer | worksheet_initializer | 77 | 94 | 77 | 77 | c8d62450145f21cfb1374e311174e78e967a8670 | bigcode/the-stack | train |
6450446521c65fa037630204 | train | function | def make_float(val: int or float) -> float:
"""Return float value for each value received.
Args:
val: Takes integer or float as an argument and converts it to a proper decimal valued float number.
Returns:
float:
Rounded float value to 2 decimal points.
"""
return round(flo... | def make_float(val: int or float) -> float:
| """Return float value for each value received.
Args:
val: Takes integer or float as an argument and converts it to a proper decimal valued float number.
Returns:
float:
Rounded float value to 2 decimal points.
"""
return round(float(val), 2)
| worksheet.write(0, 12, headers[12])
worksheet.write(0, 13, headers[13])
worksheet.write(0, 14, headers[14])
worksheet.write(0, 15, headers[15])
def make_float(val: int or float) -> float:
| 64 | 64 | 73 | 12 | 52 | thevickypedia/stock_analyzer | thor_api.py | Python | make_float | make_float | 97 | 107 | 97 | 97 | 62aed8052ce9c480880a5bed33d39d36783b98c6 | bigcode/the-stack | train |
a4bd133e18c36a231692cc20 | train | function | def extract_data(data: dict) -> Union[list, None]:
"""Extracts the necessary information of each stock from the data received.
Args:
data: Takes the information of each ticker value as an argument.
Returns:
list:
A list of ``Stock Name``, ``Market Capital``, ``Dividend Yield``, ``P... | def extract_data(data: dict) -> Union[list, None]:
| """Extracts the necessary information of each stock from the data received.
Args:
data: Takes the information of each ticker value as an argument.
Returns:
list:
A list of ``Stock Name``, ``Market Capital``, ``Dividend Yield``, ``PE Ratio``, ``PB Ratio``,
``Current Price``,... | 8])
worksheet.write(0, 9, headers[9])
worksheet.write(0, 10, headers[10])
worksheet.write(0, 11, headers[11])
worksheet.write(0, 12, headers[12])
worksheet.write(0, 13, headers[13])
worksheet.write(0, 14, headers[14])
worksheet.write(0, 15, headers[15])
def make_float(val: int or float) ->... | 179 | 179 | 598 | 13 | 166 | thevickypedia/stock_analyzer | thor_api.py | Python | extract_data | extract_data | 110 | 171 | 110 | 110 | 8e0ad5190caebf3788b249b7c5330bc4949b54ff | bigcode/the-stack | train |
7fbf2ad1102161452dd09c97 | train | function | def requester(domain, proxy, timeout, user_agent, output, ok, v):
code, html = request(domain, proxy, timeout, user_agent)
service, error = find(code, html, ok)
if service and error:
if output:
_output.append((domain, service, error))
if v and not k_.get("d_list"):
... | def requester(domain, proxy, timeout, user_agent, output, ok, v):
| code, html = request(domain, proxy, timeout, user_agent)
service, error = find(code, html, ok)
if service and error:
if output:
_output.append((domain, service, error))
if v and not k_.get("d_list"):
plus(
"%s service found! Potential domai... | b=PERCENT(int(i), int(k.get("dict_len"))),
d=k.get("domains")[i],
)
print_(str_)
# else:
# info("Domain: {}".format(k.get("domains")[i]))
pass
def requester(domain, proxy, timeout, user_agent, output, ok, v):
| 69 | 69 | 232 | 17 | 51 | edoardottt/takeover | takeover.py | Python | requester | requester | 314 | 344 | 314 | 314 | 12082f6a7a0f54d925308de519ec48806f907f63 | bigcode/the-stack | train |
044eda1abc7067e93c785a78 | train | function | def warn(string, exit=not 1):
print("{0}[ ! ]{1} {2}".format(r, e, string))
if exit:
sys.exit()
| def warn(string, exit=not 1):
| print("{0}[ ! ]{1} {2}".format(r, e, string))
if exit:
sys.exit()
| error": r"The requested URL was not found on this server"},
"Uptimerobot": {"error": r"page not found"},
}
def plus(string):
print("{0}[ + ]{1} {2}".format(g, e, string))
def warn(string, exit=not 1):
| 64 | 64 | 38 | 10 | 54 | edoardottt/takeover | takeover.py | Python | warn | warn | 160 | 163 | 160 | 160 | 67a71c717af2be04a4782a76e00d187feaf17915 | bigcode/the-stack | train |
f691d8221ff41639e56bd489 | train | function | def checkurl(url):
o = urllib.parse.urlsplit(url)
if o.scheme not in ["http", "https", ""]:
warn('Scheme "%s" not supported!' % o.scheme, 1)
if o.netloc == "":
return "http://" + o.path
elif o.netloc:
return o.scheme + "://" + o.netloc
else:
return "http://" + o.netlo... | def checkurl(url):
| o = urllib.parse.urlsplit(url)
if o.scheme not in ["http", "https", ""]:
warn('Scheme "%s" not supported!' % o.scheme, 1)
if o.netloc == "":
return "http://" + o.path
elif o.netloc:
return o.scheme + "://" + o.netloc
else:
return "http://" + o.netloc
| path, 1)
else:
warn('Error in: "%s"' % path, 1)
def readfile(path):
info('Read wordlist... "%s"' % path)
return [x.strip() for x in open(checkpath(path), "r")]
def checkurl(url):
| 63 | 64 | 92 | 5 | 58 | edoardottt/takeover | takeover.py | Python | checkurl | checkurl | 265 | 274 | 265 | 265 | 62120c4f0dd0795e2ad167ab194a56c1e55a6dd7 | bigcode/the-stack | train |
20aa107f5b5d9738cdf67a41 | train | function | def request(domain, proxy, timeout, user_agent):
url = checkurl(domain)
timeout = timeout
proxies = {"http": proxy, "https": proxy}
redirect = True
headers = {"User-Agent": user_agent}
try:
req = requests.packages.urllib3.disable_warnings(
urllib3.exceptions.InsecureRequestWa... | def request(domain, proxy, timeout, user_agent):
| url = checkurl(domain)
timeout = timeout
proxies = {"http": proxy, "https": proxy}
redirect = True
headers = {"User-Agent": user_agent}
try:
req = requests.packages.urllib3.disable_warnings(
urllib3.exceptions.InsecureRequestWarning
)
req = requests.get(
... | , e, string))
def _info():
return "{0}[ i ]{1} ".format(y, e)
def err(string):
print(r" |= [REGEX]: {0}{1}{2}".format(y_, string, e))
def request(domain, proxy, timeout, user_agent):
| 64 | 64 | 140 | 11 | 53 | edoardottt/takeover | takeover.py | Python | request | request | 178 | 198 | 178 | 178 | e60ea0015779fd47e935cf9848ee18ddcd6606f4 | bigcode/the-stack | train |
7b5d8c48d3a1393bdd30eeef | train | function | def plus(string):
print("{0}[ + ]{1} {2}".format(g, e, string))
| def plus(string):
| print("{0}[ + ]{1} {2}".format(g, e, string))
| {
"error": r"hub domain\, The URL you\'ve accessed does not provide a hub"
},
"Unbounce": {"error": r"The requested URL was not found on this server"},
"Uptimerobot": {"error": r"page not found"},
}
def plus(string):
| 64 | 64 | 24 | 4 | 60 | edoardottt/takeover | takeover.py | Python | plus | plus | 156 | 157 | 156 | 156 | a450d662ee731ee9f772d7bce950952627c0adbc | bigcode/the-stack | train |
a8cba4231b3b7e59a43e56f1 | train | function | def PERCENT(x, y):
return lambda x, y: float(x) / float(y) * 100
| def PERCENT(x, y):
| return lambda x, y: float(x) / float(y) * 100
| _5) AppleWebKit/537.36 \
(KHTML, like Gecko) Chrome/76.0.3809.36 Safari/537.36",
"verbose": False,
"dict_len": 0,
}
# index/lenght * 100
def PERCENT(x, y):
| 64 | 64 | 25 | 7 | 56 | edoardottt/takeover | takeover.py | Python | PERCENT | PERCENT | 46 | 47 | 46 | 46 | 206e14bd239bccabdc9c277154cd811590628a5b | bigcode/the-stack | train |
b2d1881a856ffedf573fef79 | train | function | def banner():
print("\n /~\\")
print(" C oo ---------------")
print(" _( ^) |T|A|K|E|O|V|E|R|")
print("/ ~\\ ----------------")
print("#> by M'hamed (@m4ll0k) Outaadi")
print("#> http://github.com/m4ll0k")
print("#> fork http://github.com/edoardottt")
print("-" * 40)
print()... | def banner():
| print("\n /~\\")
print(" C oo ---------------")
print(" _( ^) |T|A|K|E|O|V|E|R|")
print("/ ~\\ ----------------")
print("#> by M'hamed (@m4ll0k) Outaadi")
print("#> http://github.com/m4ll0k")
print("#> fork http://github.com/edoardottt")
print("-" * 40)
print()
warn("CHE... | ) in range(201 if ok is False else 200, 599)
and "nginx" not in str(content)
and "openresty"
not in str(content) # avoid false positives (Cargo mainly)
):
return str(service), str(values[1])
def banner():
| 64 | 64 | 144 | 3 | 61 | edoardottt/takeover | takeover.py | Python | banner | banner | 219 | 230 | 219 | 219 | eff741ef3696f31dc87ceda4f2c04de20df3f181 | bigcode/the-stack | train |
576fff6ead5217c443cd3322 | train | function | def savetxt(path, content, v):
if v and not k_.get("d_list"):
info("Writing file..")
elif v and k_.get("d_list"):
print("")
info("Writing file..")
br = "-" * 40
bf = "=" * 40
out = "" + br + "\n"
for i in content:
out += "Domain\t: %s\n" % i[0]
out += "Ser... | def savetxt(path, content, v):
| if v and not k_.get("d_list"):
info("Writing file..")
elif v and k_.get("d_list"):
print("")
info("Writing file..")
br = "-" * 40
bf = "=" * 40
out = "" + br + "\n"
for i in content:
out += "Domain\t: %s\n" % i[0]
out += "Service\t: %s\n" % i[1]
ou... | [2]}})
b["domains"] = a
with open(path, "w+") as outjsonfile:
json.dump(b, outjsonfile, indent=4)
outjsonfile.close()
info("Saved at " + path + "..")
def savetxt(path, content, v):
| 64 | 64 | 186 | 9 | 55 | edoardottt/takeover | takeover.py | Python | savetxt | savetxt | 364 | 382 | 364 | 364 | 39b29b1a56218efcc279b938e1e3f1f241d3cf5a | bigcode/the-stack | train |
3c71e1d0ba54688781e49dd2 | train | function | def main():
# --
if len(sys.argv) < 2:
help(1)
try:
opts, _ = getopt.getopt(
sys.argv[1:],
"d:l:p:o:t:T::u:kv",
["d=", "l=", "p=", "v", "o=", "t=", "T=", "u=", "k"],
)
except Exception as e:
warn(e, 1)
for o, a in opts:
if o... | def main():
# --
| if len(sys.argv) < 2:
help(1)
try:
opts, _ = getopt.getopt(
sys.argv[1:],
"d:l:p:o:t:T::u:kv",
["d=", "l=", "p=", "v", "o=", "t=", "T=", "u=", "k"],
)
except Exception as e:
warn(e, 1)
for o, a in opts:
if o == "-d":
... | ..")
br = "-" * 40
bf = "=" * 40
out = "" + br + "\n"
for i in content:
out += "Domain\t: %s\n" % i[0]
out += "Service\t: %s\n" % i[1]
out += "Error\t: %s\n" % i[2]
out += "" + bf + "\n"
out += "" + br + "\n"
with open(path, "w+") as outtxtfile:
outtxtfile... | 145 | 145 | 484 | 6 | 139 | edoardottt/takeover | takeover.py | Python | main | main | 385 | 442 | 385 | 386 | 1c3a24d074b6ffe1d0776063c37a56da39909fe3 | bigcode/the-stack | train |
73a824abe603beef5f00d1b2 | train | function | def print_(string):
sys.stdout.write("\033[1K")
sys.stdout.write("\033[0G")
sys.stdout.write(string)
sys.stdout.flush()
| def print_(string):
| sys.stdout.write("\033[1K")
sys.stdout.write("\033[0G")
sys.stdout.write(string)
sys.stdout.flush()
| s" not supported!' % o.scheme, 1)
if o.netloc == "":
return "http://" + o.path
elif o.netloc:
return o.scheme + "://" + o.netloc
else:
return "http://" + o.netloc
def print_(string):
| 64 | 64 | 36 | 5 | 58 | edoardottt/takeover | takeover.py | Python | print_ | print_ | 277 | 281 | 277 | 277 | 5e4b63f57eccaf746e054ab8cac8e468a7c31b78 | bigcode/the-stack | train |
c21153779b3642258c9c31d8 | train | function | def find(status, content, ok):
for service in services:
for values in services[service].items():
if (
re.findall(str(values[1]), str(content), re.I)
and int(status) in range(201 if ok is False else 200, 599)
and "nginx" not in str(content)
... | def find(status, content, ok):
| for service in services:
for values in services[service].items():
if (
re.findall(str(values[1]), str(content), re.I)
and int(status) in range(201 if ok is False else 200, 599)
and "nginx" not in str(content)
and "openresty"
... | ("d_list"):
# print("")
# warn("Failed to establish a new connection for: %s" % (domain), 1)
# else:
# warn("Failed to establish a new connection for: %s" % (domain), 1)
def find(status, content, ok):
| 64 | 64 | 106 | 8 | 56 | edoardottt/takeover | takeover.py | Python | find | find | 206 | 216 | 206 | 206 | 3ca684eb99fc7d45c972a29af5ec6f562b7c6eac | bigcode/the-stack | train |
b750bbf46e8f88673ede9488 | train | function | def checkpath(path):
if os.path.exists(path):
return path
elif os.path.isdir(path):
warn('"%s" is directory!', 1)
elif os.path.exists(path) is False:
warn('"%s" not exists!' % path, 1)
else:
warn('Error in: "%s"' % path, 1)
| def checkpath(path):
| if os.path.exists(path):
return path
elif os.path.isdir(path):
warn('"%s" is directory!', 1)
elif os.path.exists(path) is False:
warn('"%s" not exists!' % path, 1)
else:
warn('Error in: "%s"' % path, 1)
| ")
print("\t-k\tProcess 200 http code, cause more false positive")
print("\t-u\tSet custom user agent (e.g: takeover-bot)")
print("\t-v\tVerbose, print more info\n")
if _exit_:
sys.exit()
def checkpath(path):
| 64 | 64 | 78 | 5 | 59 | edoardottt/takeover | takeover.py | Python | checkpath | checkpath | 249 | 257 | 249 | 249 | 793508e7546dc5e4e4b549213b881e5a839d5e1a | bigcode/the-stack | train |
eda514485993885d223a87b7 | train | function | def runner(k):
threadpool = thread.ThreadPoolExecutor(max_workers=k.get("threads"))
if k.get("verbose"):
info("Set %s threads.." % k.get("threads"))
futures = (
threadpool.submit(
requester,
domain,
k.get("proxy"),
k.get("timeout"),
... | def runner(k):
| threadpool = thread.ThreadPoolExecutor(max_workers=k.get("threads"))
if k.get("verbose"):
info("Set %s threads.." % k.get("threads"))
futures = (
threadpool.submit(
requester,
domain,
k.get("proxy"),
k.get("timeout"),
k.get("user_ag... | return o.scheme + "://" + o.netloc
else:
return "http://" + o.netloc
def print_(string):
sys.stdout.write("\033[1K")
sys.stdout.write("\033[0G")
sys.stdout.write(string)
sys.stdout.flush()
def runner(k):
| 64 | 64 | 209 | 4 | 60 | edoardottt/takeover | takeover.py | Python | runner | runner | 284 | 311 | 284 | 284 | 26750d32adefc5844911f11e03c0e031c91d4362 | bigcode/the-stack | train |
da4a895b60e84d3228a5295b | train | function | def info(string):
print("{0}[ i ]{1} {2}".format(y, e, string))
| def info(string):
| print("{0}[ i ]{1} {2}".format(y, e, string))
| (string):
print("{0}[ + ]{1} {2}".format(g, e, string))
def warn(string, exit=not 1):
print("{0}[ ! ]{1} {2}".format(r, e, string))
if exit:
sys.exit()
def info(string):
| 64 | 64 | 24 | 4 | 60 | edoardottt/takeover | takeover.py | Python | info | info | 166 | 167 | 166 | 166 | 5d4db8b4a60aa1589f7b09a4c2f0f00078f8cfda | bigcode/the-stack | train |
8f833bd13d0802d32482c750 | train | function | def readfile(path):
info('Read wordlist... "%s"' % path)
return [x.strip() for x in open(checkpath(path), "r")]
| def readfile(path):
| info('Read wordlist... "%s"' % path)
return [x.strip() for x in open(checkpath(path), "r")]
| .path.isdir(path):
warn('"%s" is directory!', 1)
elif os.path.exists(path) is False:
warn('"%s" not exists!' % path, 1)
else:
warn('Error in: "%s"' % path, 1)
def readfile(path):
| 64 | 64 | 35 | 5 | 59 | edoardottt/takeover | takeover.py | Python | readfile | readfile | 260 | 262 | 260 | 260 | 3adb41bf70d6b619c88c075115d3c60228d69074 | bigcode/the-stack | train |
e60584b5787c4ba0abc829e4 | train | function | def _info():
return "{0}[ i ]{1} ".format(y, e)
| def _info():
| return "{0}[ i ]{1} ".format(y, e)
| (string, exit=not 1):
print("{0}[ ! ]{1} {2}".format(r, e, string))
if exit:
sys.exit()
def info(string):
print("{0}[ i ]{1} {2}".format(y, e, string))
def _info():
| 64 | 64 | 20 | 4 | 60 | edoardottt/takeover | takeover.py | Python | _info | _info | 170 | 171 | 170 | 170 | 3035bf7f636dd5d639d34b12f224b07698a63b5f | bigcode/the-stack | train |
fab4a5c31692f9bdcbb6b282 | train | function | def err(string):
print(r" |= [REGEX]: {0}{1}{2}".format(y_, string, e))
| def err(string):
| print(r" |= [REGEX]: {0}{1}{2}".format(y_, string, e))
| }".format(r, e, string))
if exit:
sys.exit()
def info(string):
print("{0}[ i ]{1} {2}".format(y, e, string))
def _info():
return "{0}[ i ]{1} ".format(y, e)
def err(string):
| 64 | 64 | 28 | 4 | 60 | edoardottt/takeover | takeover.py | Python | err | err | 174 | 175 | 174 | 174 | c7e96042d82ae6aa56af04eea203c4b577b7de62 | bigcode/the-stack | train |
30b5591b0f6cfbf828d36eaa | train | function | def help(_exit_=False):
banner()
print("Usage: %s [OPTION]\n" % sys.argv[0])
print("\t-d\tSet domain URL (e.g: www.test.com)")
print("\t-t\tSet threads, default 1")
print("\t-l\tScan multiple targets in a text file")
print("\t-p\tUse a proxy to connect the target URL")
print("\t-o\tUse this ... | def help(_exit_=False):
| banner()
print("Usage: %s [OPTION]\n" % sys.argv[0])
print("\t-d\tSet domain URL (e.g: www.test.com)")
print("\t-t\tSet threads, default 1")
print("\t-l\tScan multiple targets in a text file")
print("\t-p\tUse a proxy to connect the target URL")
print("\t-o\tUse this settings for save a file... | k")
print("#> fork http://github.com/edoardottt")
print("-" * 40)
print()
warn("CHECK AT https://github.com/m4ll0k/takeover IF THE BANNERS WERE UPDATED !")
print()
def help(_exit_=False):
| 64 | 64 | 182 | 7 | 57 | edoardottt/takeover | takeover.py | Python | help | help | 233 | 246 | 233 | 233 | e584fd95a1914ed9f035ac09537250f14d6bc497 | bigcode/the-stack | train |
401212ac08323d8db8b086ec | train | function | def savejson(path, content, v):
if v and not k_.get("d_list"):
info("Writing file..")
elif v and k_.get("d_list"):
print("")
info("Writing file..")
a = {}
b = {"domains": {}}
for i in content:
a.update({i[0]: {"service": i[1], "error": i[2]}})
b["domains"] = a
... | def savejson(path, content, v):
| if v and not k_.get("d_list"):
info("Writing file..")
elif v and k_.get("d_list"):
print("")
info("Writing file..")
a = {}
b = {"domains": {}}
for i in content:
a.update({i[0]: {"service": i[1], "error": i[2]}})
b["domains"] = a
with open(path, "w+") as outjso... | "
% (service, domain)
)
elif not k_.get("d_list"):
plus(
"%s service found! Potential domain takeover found! - %s"
% (service, domain)
)
if v:
err(error)
def savejson(path,... | 64 | 64 | 141 | 9 | 55 | edoardottt/takeover | takeover.py | Python | savejson | savejson | 347 | 361 | 347 | 347 | 6197d80cb89a15edd842411eac6f11f717ad7ad8 | bigcode/the-stack | train |
7e873e14646ae14e08edb8f6 | train | class | class BasicContext(Context):
def __init__(self, fxtrade: bool, stream: bool, token: str):
api = "stream" if stream else "api"
env = "fxtrade" if fxtrade else "fxpractice"
super().__init__(
hostname=f"{api}-{env}.oanda.com",
token=token
)
| class BasicContext(Context):
| def __init__(self, fxtrade: bool, stream: bool, token: str):
api = "stream" if stream else "api"
env = "fxtrade" if fxtrade else "fxpractice"
super().__init__(
hostname=f"{api}-{env}.oanda.com",
token=token
)
| .headers
)
if request.stream:
response.set_line_parser(
request.line_parser
)
response.set_lines(
http_response.iter_lines(
self.stream_chunk_size
)
)
else:
response.... | 64 | 64 | 76 | 5 | 58 | alekna/v20-python | src/v20/__init__.py | Python | BasicContext | BasicContext | 343 | 350 | 343 | 343 | 2cc29ee8ac93b2873ace1ab4b0b1a865eeecd415 | bigcode/the-stack | train |
3fe87f184a7a91b5d4543dd9 | train | class | class Context(object):
"""
A v20.Context encapuslates a connection to OANDA's v20 REST API
"""
def __init__(
self,
hostname,
port=443,
ssl=True,
application="",
token=None,
decimal_number_as_float=True,
stream_chunk_size=512,
stream... | class Context(object):
| """
A v20.Context encapuslates a connection to OANDA's v20 REST API
"""
def __init__(
self,
hostname,
port=443,
ssl=True,
application="",
token=None,
decimal_number_as_float=True,
stream_chunk_size=512,
stream_timeout=10,
da... | import requests
from v20 import account
from v20 import user
from v20 import position
from v20 import pricing
from v20 import transaction
from v20 import primitives
from v20 import trade
from v20 import site
from v20 import pricing_common
from v20 import order
from v20 import instrument
from v20.response import Respons... | 95 | 256 | 1,733 | 4 | 90 | alekna/v20-python | src/v20/__init__.py | Python | Context | Context | 17 | 340 | 17 | 17 | 57d7a15466212c84f047a420a6feb2f260d593c7 | bigcode/the-stack | train |
1b246deaa4689f7d2a2b3ef6 | train | class | class AbstractFilterWheel(PanBase, metaclass=ABCMeta):
"""
Base class for all filter wheels
Args:
name (str, optional): name of the filter wheel
model (str, optional): model of the filter wheel
camera (pocs.camera.*.Camera, optional): camera that this filter wheel is associated with... | class AbstractFilterWheel(PanBase, metaclass=ABCMeta):
| """
Base class for all filter wheels
Args:
name (str, optional): name of the filter wheel
model (str, optional): model of the filter wheel
camera (pocs.camera.*.Camera, optional): camera that this filter wheel is associated with.
filter_names (list of str): names of the filt... | import threading
from abc import ABCMeta, abstractmethod
from astropy import units as u
from pocs.base import PanBase
from pocs.utils import listify
from pocs.utils import error
class AbstractFilterWheel(PanBase, metaclass=ABCMeta):
| 57 | 256 | 1,819 | 14 | 42 | zacharyt20/POCS | pocs/filterwheel/filterwheel.py | Python | AbstractFilterWheel | AbstractFilterWheel | 11 | 257 | 11 | 11 | b3f4d5446f0a2a3b5b4d7b5973402132acbe5e2d | bigcode/the-stack | train |
0e8a95fdb52fa6c759fa8489 | train | class | class MatchBase: # pylint: disable=too-many-instance-attributes
"""Base class with common high-level Match fields."""
def __init__(self, in_port=None, dl_src=None, dl_dst=None, dl_vlan=None,
dl_vlan_pcp=None, dl_type=None, nw_proto=None, nw_src=None,
nw_dst=None, tp_src=None,... | class MatchBase: # pylint: disable=too-many-instance-attributes
| """Base class with common high-level Match fields."""
def __init__(self, in_port=None, dl_src=None, dl_dst=None, dl_vlan=None,
dl_vlan_pcp=None, dl_type=None, nw_proto=None, nw_src=None,
nw_dst=None, tp_src=None, tp_dst=None, in_phy_port=None,
ip_dscp=None, ip... | 'set_vlan': None,
# pyof class: ActionBase child
}
@classmethod
def from_dict(cls, action_dict):
"""Build the proper Action from a dictionary.
Args:
action_dict (dict): Action attributes.
"""
action_type = action_dict.get('action_type')
a... | 190 | 190 | 636 | 16 | 173 | 2020SUM-Amlight/of_core | flow.py | Python | MatchBase | MatchBase | 272 | 334 | 272 | 272 | d214776046087a0d95a3d62f28663e52f9c746d5 | bigcode/the-stack | train |
33f2624b4df2eaac2473287f | train | class | class FlowFactory(ABC): # pylint: disable=too-few-public-methods
"""Choose the correct Flow according to OpenFlow version."""
@classmethod
def from_of_flow_stats(cls, of_flow_stats, switch):
"""Return a Flow for the switch OpenFlow version."""
flow_class = cls.get_class(switch)
ret... | class FlowFactory(ABC): # pylint: disable=too-few-public-methods
| """Choose the correct Flow according to OpenFlow version."""
@classmethod
def from_of_flow_stats(cls, of_flow_stats, switch):
"""Return a Flow for the switch OpenFlow version."""
flow_class = cls.get_class(switch)
return flow_class.from_of_flow_stats(of_flow_stats, switch)
@sta... | 0x01 and v0x04
from pyof.v0x04.controller2switch.flow_mod import FlowModCommand
from napps.kytos.of_core import v0x01, v0x04
class FlowFactory(ABC): # pylint: disable=too-few-public-methods
| 64 | 64 | 170 | 19 | 44 | 2020SUM-Amlight/of_core | flow.py | Python | FlowFactory | FlowFactory | 17 | 34 | 17 | 17 | dd00a4bf85e7d3d108d7973c9e5c63ba406b5147 | bigcode/the-stack | train |
5ee6a6c2d5753f73039bb07a | train | class | class FlowStats(Stats):
"""Common fields for 1.0 and 1.3 FlowStats."""
def __init__(self):
"""Initialize all statistics as ``None``."""
self.byte_count = None
self.duration_sec = None
self.duration_nsec = None
self.packet_count = None
| class FlowStats(Stats):
| """Common fields for 1.0 and 1.3 FlowStats."""
def __init__(self):
"""Initialize all statistics as ``None``."""
self.byte_count = None
self.duration_sec = None
self.duration_nsec = None
self.packet_count = None
| (self, attr_name_value)
@staticmethod
def _update(obj, iterable):
"""From attribute name and value pairs, update ``obj``."""
for attr_name, value in iterable:
if hasattr(obj, attr_name):
setattr(obj, attr_name, value)
class FlowStats(Stats):
| 64 | 64 | 68 | 6 | 58 | 2020SUM-Amlight/of_core | flow.py | Python | FlowStats | FlowStats | 380 | 388 | 380 | 380 | d9849beaa860e5b86c46ead86154ddbce0bc740b | bigcode/the-stack | train |
3dfd542cc051e28b16f905c3 | train | class | class ActionBase(ABC):
"""Base class for a flow action."""
def as_dict(self):
"""Return a dict that can be dumped as JSON."""
return vars(self)
@classmethod
def from_dict(cls, action_dict):
"""Return an action instance from attributes in a dictionary."""
action = cls(No... | class ActionBase(ABC):
| """Base class for a flow action."""
def as_dict(self):
"""Return a dict that can be dumped as JSON."""
return vars(self)
@classmethod
def from_dict(cls, action_dict):
"""Return an action instance from attributes in a dictionary."""
action = cls(None)
for attr_na... | _flow_stats.priority.value,
idle_timeout=of_flow_stats.idle_timeout.value,
hard_timeout=of_flow_stats.hard_timeout.value,
cookie=of_flow_stats.cookie.value,
actions=non_none_actions,
stats=FlowStats.from_of_flow_stats(of_flow... | 64 | 64 | 158 | 6 | 58 | 2020SUM-Amlight/of_core | flow.py | Python | ActionBase | ActionBase | 213 | 236 | 213 | 213 | 73bb4f7017a3e720ceee4868a55853fdaf485292 | bigcode/the-stack | train |
de1a09d14cdb6e930a182cfe | train | class | class FlowBase(ABC): # pylint: disable=too-many-instance-attributes
"""Class to abstract a Flow to switches.
This class represents a Flow installed or to be installed inside the
switch. A flow, in this case is represented by a Match object and a set of
actions that should occur in case any match happe... | class FlowBase(ABC): # pylint: disable=too-many-instance-attributes
| """Class to abstract a Flow to switches.
This class represents a Flow installed or to be installed inside the
switch. A flow, in this case is represented by a Match object and a set of
actions that should occur in case any match happen.
"""
# of_version number: 0x01, 0x04
of_version = None... | , abstractmethod
from hashlib import md5
# Note: FlowModCommand is the same in both v0x01 and v0x04
from pyof.v0x04.controller2switch.flow_mod import FlowModCommand
from napps.kytos.of_core import v0x01, v0x04
class FlowFactory(ABC): # pylint: disable=too-few-public-methods
"""Choose the correct Flow according... | 255 | 256 | 1,465 | 18 | 237 | 2020SUM-Amlight/of_core | flow.py | Python | FlowBase | FlowBase | 37 | 210 | 37 | 37 | bac8c52169ace4a9e05eb7c299ddd838dd3c570f | bigcode/the-stack | train |
462a042f912da31d90efc19c | train | class | class Stats:
"""Simple class to store statistics as attributes and values."""
def as_dict(self):
"""Return a dict excluding attributes with ``None`` value."""
return {attribute: value
for attribute, value in vars(self).items()
if value is not None}
@classmet... | class Stats:
| """Simple class to store statistics as attributes and values."""
def as_dict(self):
"""Return a dict excluding attributes with ``None`` value."""
return {attribute: value
for attribute, value in vars(self).items()
if value is not None}
@classmethod
def f... | cls()
for key, value in match_dict.items():
if key in match.__dict__:
setattr(match, key, value)
return match
@classmethod
@abstractmethod
def from_of_match(cls, of_match):
"""Return a Match instance from a pyof Match."""
@abstractmethod
def as_... | 88 | 89 | 299 | 3 | 85 | 2020SUM-Amlight/of_core | flow.py | Python | Stats | Stats | 337 | 377 | 337 | 337 | 7ef87058037b76c4c29a8f1b8fc658750d88876e | bigcode/the-stack | train |
b340ac9a5402098704f3d0c1 | train | class | class PortStats(Stats): # pylint: disable=too-many-instance-attributes
"""Common fields for 1.0 and 1.3 PortStats."""
def __init__(self):
"""Initialize all statistics as ``None``."""
self.rx_packets = None
self.tx_packets = None
self.rx_bytes = None
self.tx_bytes = None... | class PortStats(Stats): # pylint: disable=too-many-instance-attributes
| """Common fields for 1.0 and 1.3 PortStats."""
def __init__(self):
"""Initialize all statistics as ``None``."""
self.rx_packets = None
self.tx_packets = None
self.rx_bytes = None
self.tx_bytes = None
self.rx_dropped = None
self.tx_dropped = None
s... | ."""
def __init__(self):
"""Initialize all statistics as ``None``."""
self.byte_count = None
self.duration_sec = None
self.duration_nsec = None
self.packet_count = None
class PortStats(Stats): # pylint: disable=too-many-instance-attributes
| 64 | 64 | 141 | 18 | 45 | 2020SUM-Amlight/of_core | flow.py | Python | PortStats | PortStats | 391 | 407 | 391 | 391 | a314658e3aa9b53daf1a923083c5c8a2300ee4a8 | bigcode/the-stack | train |
9b9bda3e10ec42011f4cad9f | train | class | class ActionFactoryBase(ABC):
"""Deal with different implementations of ActionBase."""
# key: action_type or pyof class, value: ActionBase child
_action_class = {
'output': None,
'set_vlan': None,
# pyof class: ActionBase child
}
@classmethod
def from_dict(cls, action_d... | class ActionFactoryBase(ABC):
| """Deal with different implementations of ActionBase."""
# key: action_type or pyof class, value: ActionBase child
_action_class = {
'output': None,
'set_vlan': None,
# pyof class: ActionBase child
}
@classmethod
def from_dict(cls, action_dict):
"""Build the pro... |
@abstractmethod
def as_of_action(self):
"""Return a pyof action to be used by a FlowMod."""
@classmethod
@abstractmethod
def from_of_action(cls, of_action):
"""Return an action from a pyof action."""
class ActionFactoryBase(ABC):
| 65 | 66 | 220 | 7 | 58 | 2020SUM-Amlight/of_core | flow.py | Python | ActionFactoryBase | ActionFactoryBase | 239 | 269 | 239 | 239 | 95bc55db7cb89a3304d7da8e00ac9cc2e2aa846a | bigcode/the-stack | train |
cd607cb8057520cba44f5ebd | train | function | def _create_dict(options, info, pairkernings):
d = dict()
d['name'] = os.path.basename(options.input)
d['size'] = info.size
d['texturesize'] = info.texturesize
d['texturename'] = os.path.basename(options.output)
d['ascender'] = int(info.ascender)
d['descender'] = int(info.descender)
... | def _create_dict(options, info, pairkernings):
| d = dict()
d['name'] = os.path.basename(options.input)
d['size'] = info.size
d['texturesize'] = info.texturesize
d['texturename'] = os.path.basename(options.output)
d['ascender'] = int(info.ascender)
d['descender'] = int(info.descender)
glyphdicts = []
for glyph in info.glyphs:
... | """
Copyright @ 2013 Mathias Westerdahl
Generates a .json file given a set of glyphs
"""
import os, json
def _create_dict(options, info, pairkernings):
| 43 | 90 | 302 | 12 | 30 | JCash/fontcreator | fontout_json.py | Python | _create_dict | _create_dict | 9 | 42 | 9 | 9 | 558362ff6e6a4e9519e7089e9f4a40b434f32cd9 | bigcode/the-stack | train |
72f168c824b7624dca43b69d | train | function | def write(options, info, pairkernings):
d = _create_dict(options, info, pairkernings)
s = json.dumps(d, sort_keys=True, indent=4)
with open( os.path.splitext(options.output)[0] + '.json', 'wb') as f:
f.write(s)
return 0
| def write(options, info, pairkernings):
| d = _create_dict(options, info, pairkernings)
s = json.dumps(d, sort_keys=True, indent=4)
with open( os.path.splitext(options.output)[0] + '.json', 'wb') as f:
f.write(s)
return 0
| = ((key >> 32) & 0xFFFFFFFF, key & 0xFFFFFFFF)
pd.append( (unichr(prevchar), unichr(char), value) )
d['pairkernings'] = pd
return d
def write(options, info, pairkernings):
| 64 | 64 | 71 | 10 | 53 | JCash/fontcreator | fontout_json.py | Python | write | write | 45 | 50 | 45 | 45 | f1e393ff3e528b14f56fd662293d7ca08e07cbd3 | bigcode/the-stack | train |
6deea76bd68cb9f11661004c | train | function | def beat_times(time, loc, dif):
"""Find all of the corresponding times when a heartbeat
occurred for a given ECG signal
Args:
time: list of time values for an ECG signal
loc: tuple with the locations where the ECG
signal slope is above a threshold
... | def beat_times(time, loc, dif):
| """Find all of the corresponding times when a heartbeat
occurred for a given ECG signal
Args:
time: list of time values for an ECG signal
loc: tuple with the locations where the ECG
signal slope is above a threshold
dif: tuple with the differences... | import numpy as np
from numpy import diff
def beat_times(time, loc, dif):
| 19 | 96 | 323 | 9 | 9 | clairenied15/bme590hrm | beat_times_bme590hrm.py | Python | beat_times | beat_times | 5 | 49 | 5 | 5 | 539510969080de45e82ae883a3c5bc7aa7bd0606 | bigcode/the-stack | train |
a216396629c46902e848e5b2 | train | function | def test_add_positive():
assert add_numbers(1, 2) == 3
| def test_add_positive():
| assert add_numbers(1, 2) == 3
| import pytest
from mymath import add_numbers
def test_add_positive():
| 15 | 64 | 19 | 5 | 9 | leeltib/conduit | selenium-tests/test_mymath.py | Python | test_add_positive | test_add_positive | 5 | 6 | 5 | 5 | 69403da0b33706f9ad8fb6a301df3ac8b7b91b79 | bigcode/the-stack | train |
6916b73d21565208f5948599 | train | function | def test_add_negative():
assert add_numbers(4, -100) == -96
| def test_add_negative():
| assert add_numbers(4, -100) == -96
| import pytest
from mymath import add_numbers
def test_add_positive():
assert add_numbers(1, 2) == 3
def test_add_zero():
assert add_numbers(1, 0) == 1
def test_add_negative():
| 53 | 64 | 19 | 5 | 47 | leeltib/conduit | selenium-tests/test_mymath.py | Python | test_add_negative | test_add_negative | 11 | 12 | 11 | 11 | 762d676c1527a5832d5ccbedd717d19194a4564d | bigcode/the-stack | train |
d5c4493f45aaa5e103e3a7c7 | train | function | def test_add_zero():
assert add_numbers(1, 0) == 1
| def test_add_zero():
| assert add_numbers(1, 0) == 1
| import pytest
from mymath import add_numbers
def test_add_positive():
assert add_numbers(1, 2) == 3
def test_add_zero():
| 34 | 64 | 19 | 5 | 28 | leeltib/conduit | selenium-tests/test_mymath.py | Python | test_add_zero | test_add_zero | 8 | 9 | 8 | 8 | 6940a65de72927f793361bc9233de09c85d0bd2f | bigcode/the-stack | train |
fa3f6dd844c80dc793ea847c | train | function | def test_add_string__expect_exception():
with pytest.raises(TypeError):
add_numbers(4, 'I DO NOT BELONG HERE')
| def test_add_string__expect_exception():
| with pytest.raises(TypeError):
add_numbers(4, 'I DO NOT BELONG HERE')
| test_add_positive():
assert add_numbers(1, 2) == 3
def test_add_zero():
assert add_numbers(1, 0) == 1
def test_add_negative():
assert add_numbers(4, -100) == -96
def test_add_string__expect_exception():
| 64 | 64 | 29 | 8 | 55 | leeltib/conduit | selenium-tests/test_mymath.py | Python | test_add_string__expect_exception | test_add_string__expect_exception | 14 | 16 | 14 | 14 | 90191e07a7a77824b62f63e6725c889c0122f349 | bigcode/the-stack | train |
36a2ce97732afec443df2f5d | train | class | class LogitNormal(BoundedInterval):
"""
This class contains methods concerning Logit Normal Distirbution [#]_.
.. math::
\\text{LogitNormal}(x;\\mu,\\sigma) = \\frac{1}{\\sigma \\sqrt(2\\pi) \\cdot x(1-x)} \\exp{\\Big(-\\frac{(logit(x)-\\mu)^2}{2\\sigma^2} \\Big)}
Args:
sq_sc... | class LogitNormal(BoundedInterval):
| """
This class contains methods concerning Logit Normal Distirbution [#]_.
.. math::
\\text{LogitNormal}(x;\\mu,\\sigma) = \\frac{1}{\\sigma \\sqrt(2\\pi) \\cdot x(1-x)} \\exp{\\Big(-\\frac{(logit(x)-\\mu)^2}{2\\sigma^2} \\Big)}
Args:
sq_scale (float): squared scale parameter
... | try:
from scipy.special import logit as _logit, erf as _erf
import numpy as _np
from math import sqrt as _sqrt, pi as _pi, exp as _exp
from typing import Union, Tuple, Dict, List
from univariate._base import BoundedInterval
except Exception as e:
print(f"some modules are missing {e}")
cla... | 93 | 256 | 1,017 | 8 | 85 | adeeconometrics/s_distributions | source/univariate/test/LogitNormal.py | Python | LogitNormal | LogitNormal | 11 | 121 | 11 | 11 | 8f4c2b305d1bf8e03153e9367fc864445ffdb635 | bigcode/the-stack | train |
810240d2cf602cf3a740f37c | train | function | def numTiffs(tiffDirectory, key):
numTiffs = 0
path = os.path.join(tiffDirectory, key)
print("Checking for tiffs for key " + key + "path = " + path)
if os.path.isdir(path):
numTiffs = len([name for name in os.listdir(path) if (os.path.isfile(os.path.join(path, name)) and name.endswith(".tif"))])... | def numTiffs(tiffDirectory, key):
| numTiffs = 0
path = os.path.join(tiffDirectory, key)
print("Checking for tiffs for key " + key + "path = " + path)
if os.path.isdir(path):
numTiffs = len([name for name in os.listdir(path) if (os.path.isfile(os.path.join(path, name)) and name.endswith(".tif"))])
print(numTiffs)
return nu... | writer.writerow(["Name", "Title","Pages", "has tiffs", "TIFFS", "Count Match", "Date", "Path"])
writer.writerows(rows)
# ########################################
# determine if this pdf has diffs
# ########################################
def numTiffs(tiffDirectory, key):
| 64 | 64 | 104 | 10 | 53 | rochester-rcl/islandora-import-scripts | ur/campus_times_report.py | Python | numTiffs | numTiffs | 244 | 251 | 244 | 244 | 03d7c40094462361d45eb57d24735fff01a1ea8c | bigcode/the-stack | train |
93fd55763518dc5ccb97c049 | train | function | def getPdfPages(path):
with open(path, 'rb') as f:
pdf = PdfFileReader(f)
info = pdf.getDocumentInfo()
number_of_pages = pdf.getNumPages()
return number_of_pages
| def getPdfPages(path):
| with open(path, 'rb') as f:
pdf = PdfFileReader(f)
info = pdf.getDocumentInfo()
number_of_pages = pdf.getNumPages()
return number_of_pages
| self.month = matchInfo.group(2)
self.year = matchInfo.group(1)
else:
print("match not found for " + self.date)
# ########################################
# Get a count of pages in each pdf file
# ########################################
def getPdfPages(path):
| 64 | 64 | 50 | 6 | 57 | rochester-rcl/islandora-import-scripts | ur/campus_times_report.py | Python | getPdfPages | getPdfPages | 167 | 173 | 167 | 167 | 176cd85cdd8811fe9ffe8fcd976edd6b6149347e | bigcode/the-stack | train |
55ea16b89571a725fa80ed51 | train | function | def processFiles(tiffDirectory):
print("T_U_R_ = " + str(len(tur_file_dict)))
print("T_T_F_N_ = " + str(len(ttff_file_dict)))
print("T_T_N_C_ = " + str(len(ttnc_file_dict)))
print("T_T_ = " + str(len(tt_file_dict)))
print("T_R_C_ = " + str(len(trc_file_dict)))
print("T_C_W_ = " + str(len(tcw_fi... | def processFiles(tiffDirectory):
| print("T_U_R_ = " + str(len(tur_file_dict)))
print("T_T_F_N_ = " + str(len(ttff_file_dict)))
print("T_T_N_C_ = " + str(len(ttnc_file_dict)))
print("T_T_ = " + str(len(tt_file_dict)))
print("T_R_C_ = " + str(len(trc_file_dict)))
print("T_C_W_ = " + str(len(tcw_file_dict)))
print("T_C_S_M_ = "... | = matchInfo.group(1)
to_file_dict[key] = pdfInfo
#print(matchInfo.group(1))
#print(" found key " + key + " and value " + str(value))
elif(re.match(cc_file_match, key)):
matchInfo = re.match(cc_file_match, key)
pdfInfo = PdfFileInfo()
pdfIn... | 197 | 197 | 659 | 7 | 189 | rochester-rcl/islandora-import-scripts | ur/campus_times_report.py | Python | processFiles | processFiles | 426 | 465 | 426 | 427 | 6485d0822a766eb397bc2b3462924f84638de3fe | bigcode/the-stack | train |
3cacecfc20d72e6a56d1799d | train | function | def getFileList(itemDirectory, extension):
fileList = {}
for root, sub, files in os.walk(itemDirectory):
for item in files:
if (item.endswith(".pdf")):
#print("adding item " + item)
path = os.path.join(root,item)
fileList[i... | def getFileList(itemDirectory, extension):
| fileList = {}
for root, sub, files in os.walk(itemDirectory):
for item in files:
if (item.endswith(".pdf")):
#print("adding item " + item)
path = os.path.join(root,item)
fileList[item] = path
else:
... | _pages = pdf.getNumPages()
return number_of_pages
# ##################################
# pull list of SORTED item IDs from folder where XML files are stored
# (assumes Jeff will create one XML file / item and place them in a directory)
# ##################################
def getFileList(itemDirectory, extension... | 64 | 64 | 188 | 9 | 55 | rochester-rcl/islandora-import-scripts | ur/campus_times_report.py | Python | getFileList | getFileList | 179 | 196 | 179 | 179 | cd86b911cafe43ae7331526518fc29356c474882 | bigcode/the-stack | train |
1ca53270ead5cbea84dc168b | train | function | def printDict(dict):
for key, info in dict.items():
print(" key = " + key + "title = " + info.getTitle() + " value = " + info.value + " date = " + info.date + " parsed = " + info.getIsoDate() )
| def printDict(dict):
| for key, info in dict.items():
print(" key = " + key + "title = " + info.getTitle() + " value = " + info.value + " date = " + info.date + " parsed = " + info.getIsoDate() )
| fileSize #get the id only no extension
# sorted based on keys - use file name
sortedDict = OrderedDict(sorted(itemIdList.items(), key=itemgetter(0)))
return sortedDict
# ########################################
# print out dictionary info
# ########################################
def printDict(dict):
| 64 | 64 | 61 | 5 | 58 | rochester-rcl/islandora-import-scripts | ur/campus_times_report.py | Python | printDict | printDict | 201 | 203 | 201 | 201 | 0ef261a8bff1e9fc1687b6d5c0b601b5bbd184db | bigcode/the-stack | train |
fbf93661cac972510e987115 | train | function | def main():
process_directory = input("Please enter PDF directory with tiffs to process: ")
if not os.path.isdir(process_directory):
print("Directory " + process_directory + " does not exist or is not a directory")
sys.exit()
print("Process directory found " + process_directory)
t... | def main():
| process_directory = input("Please enter PDF directory with tiffs to process: ")
if not os.path.isdir(process_directory):
print("Directory " + process_directory + " does not exist or is not a directory")
sys.exit()
print("Process directory found " + process_directory)
tiff_director... | createCsv(tc_file_dict, "tc.csv", tiffDirectory)
createCsv(cw_file_dict, "cw.csv", tiffDirectory)
createCsv(tr_file_dict, "tr.csv", tiffDirectory)
createCsv(ts_file_dict, "ts.csv", tiffDirectory)
createCsv(to_file_dict, "to.csv", tiffDirectory)
createCsv(cc_file_dict, "cc.csv", tiffDirectory)
#... | 106 | 106 | 356 | 3 | 102 | rochester-rcl/islandora-import-scripts | ur/campus_times_report.py | Python | main | main | 470 | 510 | 470 | 470 | b0df2ee6dc4bbef40cd0cf613c119f2cb496c6f1 | bigcode/the-stack | train |
5de435ef3b064b3cc0687b1e | train | function | def createCsv(dict, csv_file, tiffDirectory):
print("Creating csv " + csv_file)
rows = []
for key, info in dict.items():
#print(" found key " + key + " and value " + value)
numPages = getPdfPages(info.value)
tiffCount = 0
if(info.hasTiffs):
tiffCount = numTiffs(t... | def createCsv(dict, csv_file, tiffDirectory):
| print("Creating csv " + csv_file)
rows = []
for key, info in dict.items():
#print(" found key " + key + " and value " + value)
numPages = getPdfPages(info.value)
tiffCount = 0
if(info.hasTiffs):
tiffCount = numTiffs(tiffDirectory, key)
#number of page... | print out dictionary info
# ########################################
def printDict(dict):
for key, info in dict.items():
print(" key = " + key + "title = " + info.getTitle() + " value = " + info.value + " date = " + info.date + " parsed = " + info.getIsoDate() )
# ################################... | 97 | 97 | 326 | 12 | 84 | rochester-rcl/islandora-import-scripts | ur/campus_times_report.py | Python | createCsv | createCsv | 209 | 239 | 209 | 209 | 130e4860331fd841b0db25a42d1be9f5274c3e98 | bigcode/the-stack | train |
7c717db28124a141d7971eb3 | train | class | class PdfFileInfo:
"""Holds pdf file information"""
def __init__(self):
self.hasTiffs = True
self.publication = ''
self.value = ''
self.month = ''
self.year = ''
self.day = ''
self.date = ''
def getTitle(self):
self.parseDate()
# Camp... | class PdfFileInfo:
| """Holds pdf file information"""
def __init__(self):
self.hasTiffs = True
self.publication = ''
self.value = ''
self.month = ''
self.year = ''
self.day = ''
self.date = ''
def getTitle(self):
self.parseDate()
# Campus Times, January 1... | d+)_(\d+)_(\d+)"
year_month_match = "(\d+)_(\d+)"
monthDict = {'00': 'Unknown',
'01': 'January',
'02': 'February',
'03': 'March',
'04': 'April',
'05': 'May',
'06': 'June',
'07': 'July',
'08': 'August',
... | 142 | 142 | 475 | 5 | 136 | rochester-rcl/islandora-import-scripts | ur/campus_times_report.py | Python | PdfFileInfo | PdfFileInfo | 98 | 162 | 98 | 98 | 4840ca701713d84395db85cd28ff5d4edb93c574 | bigcode/the-stack | train |
1639899e953aa904e5743972 | train | function | def getPdfs(processDirectory, hasTiffs):
sortedDict = getFileList(processDirectory, 'pdf')
for key, value in sortedDict.items():
if (re.match(tur_file_match, key)):
matchInfo = re.match(tur_file_match, key)
pdfInfo = PdfFileInfo()
pdfInfo.publication = tur_pub_nam... | def getPdfs(processDirectory, hasTiffs):
| sortedDict = getFileList(processDirectory, 'pdf')
for key, value in sortedDict.items():
if (re.match(tur_file_match, key)):
matchInfo = re.match(tur_file_match, key)
pdfInfo = PdfFileInfo()
pdfInfo.publication = tur_pub_name
pdfInfo.hasTiffs = hasTiffs... | row[2] = numPages
row[3] = info.hasTiffs
row[4] = tiffCount
row[5] = countMatch
row[6] = info.getIsoDate()
row[7] = info.value
rows.append(row)
with open(csv_file, 'w', newline='') as csvfile:
writer = csv.writer(csvfile)
writer.writerow(["Name", "Tit... | 256 | 256 | 1,816 | 11 | 244 | rochester-rcl/islandora-import-scripts | ur/campus_times_report.py | Python | getPdfs | getPdfs | 253 | 420 | 253 | 253 | 88f545baf5b0c06047344fda4facf08737986ee8 | bigcode/the-stack | train |
b2bad11de843bf7a7dc8c25c | train | function | def compute_optimal_points(segments):
points = []
sortedsegs = sorted(segments, key=lambda t: t[1])
point = sortedsegs[0].end
points.append(point)
for s in sortedsegs:
if s.start > point:
points.append(s.end)
point = s.end
return points
| def compute_optimal_points(segments):
| points = []
sortedsegs = sorted(segments, key=lambda t: t[1])
point = sortedsegs[0].end
points.append(point)
for s in sortedsegs:
if s.start > point:
points.append(s.end)
point = s.end
return points
| # python3
from collections import namedtuple
from sys import stdin
Segment = namedtuple('Segment', 'start end')
def compute_optimal_points(segments):
| 34 | 64 | 76 | 8 | 26 | josjosephine/dsa | AlgorithmicToolbox/GreedyAlgorithm/collecting_signatures.py | Python | compute_optimal_points | compute_optimal_points | 9 | 19 | 9 | 9 | 0ae98abc03d0ff2da338c59bdd6da0fd5c0f3d2a | bigcode/the-stack | train |
b0da28b6e14d89ea081d225f | train | class | class TestUsuarioForm:
@pytest.fixture
def init(self, db):
self.faker = Faker("pt_BR")
def test_usuario_create(self, init):
form_data = {
"nome": self.faker.name(),
"email": self.faker.company_email(),
"latitude": 0.0,
"longitude": 0.0,
... | class TestUsuarioForm:
@pytest.fixture
| def init(self, db):
self.faker = Faker("pt_BR")
def test_usuario_create(self, init):
form_data = {
"nome": self.faker.name(),
"email": self.faker.company_email(),
"latitude": 0.0,
"longitude": 0.0,
}
form = UsuarioForm(data=form_da... | import pytest
import pytest_django
from faker import Faker
from validate_docbr import CPF
from model_bakery import baker
from usuario.forms import UsuarioForm
from usuario.models import Profissional
from django.contrib.auth.models import Group
class TestUsuarioForm:
@pytest.fixture
| 60 | 64 | 98 | 10 | 49 | claysllanxavier/django-cookiecutter | {{cookiecutter.project_slug}}/usuario/tests/tests_forms.py | Python | TestUsuarioForm | TestUsuarioForm | 11 | 24 | 11 | 12 | fb98a72a3f37a9e41d0289b6a36629f96d8cfd0d | bigcode/the-stack | train |
f7ae95b2a33598d0801dbe5c | train | function | def check_dist_requires_python(dist, version_info):
"""
:param version_info: A 3-tuple of ints representing the Python
major-minor-micro version to check (e.g. `sys.version_info[:3]`).
"""
pkg_info_dict = get_metadata(dist)
requires_python = pkg_info_dict.get('Requires-Python')
try:
... | def check_dist_requires_python(dist, version_info):
| """
:param version_info: A 3-tuple of ints representing the Python
major-minor-micro version to check (e.g. `sys.version_info[:3]`).
"""
pkg_info_dict = get_metadata(dist)
requires_python = pkg_info_dict.get('Requires-Python')
try:
if not check_requires_python(
requir... | metadata = dist.get_metadata('PKG-INFO')
else:
logger.warning("No metadata found in %s", display_path(dist.location))
metadata = ''
feed_parser = FeedParser()
feed_parser.feed(metadata)
return feed_parser.close()
def check_dist_requires_python(dist, version_info):
| 64 | 64 | 190 | 10 | 54 | blurstudio/pip | src/pip/_internal/utils/packaging.py | Python | check_dist_requires_python | check_dist_requires_python | 61 | 83 | 61 | 61 | 2cdc2e73a329f3e3763a08545e1a95a1504ce03d | bigcode/the-stack | train |
4aa0991dbad55e8e722dff9a | train | function | def check_requires_python(requires_python, version_info):
# type: (Optional[str], Tuple[int, ...]) -> bool
"""
Check if the given Python version matches a `requires_python` specifier.
:param version_info: A 3-tuple of ints representing the Python
major-minor-micro version to check (e.g. `sys.ve... | def check_requires_python(requires_python, version_info):
# type: (Optional[str], Tuple[int, ...]) -> bool
| """
Check if the given Python version matches a `requires_python` specifier.
:param version_info: A 3-tuple of ints representing the Python
major-minor-micro version to check (e.g. `sys.version_info[:3]`).
Returns `True` if the version of python in use matches the requirement.
Returns `Fal... | Y_CHECK_RUNNING:
from typing import Optional, Tuple
from email.message import Message
from pip._vendor.pkg_resources import Distribution
logger = logging.getLogger(__name__)
def check_requires_python(requires_python, version_info):
# type: (Optional[str], Tuple[int, ...]) -> bool
| 64 | 64 | 196 | 27 | 37 | blurstudio/pip | src/pip/_internal/utils/packaging.py | Python | check_requires_python | check_requires_python | 22 | 42 | 22 | 23 | c02aaa919e7adfb72be9b3fb6aafe47ad1410f0f | bigcode/the-stack | train |
2a942b37bb5367e159beec2c | train | function | def get_installer(dist):
# type: (Distribution) -> str
if dist.has_metadata('INSTALLER'):
for line in dist.get_metadata_lines('INSTALLER'):
if line.strip():
return line.strip()
return ''
| def get_installer(dist):
# type: (Distribution) -> str
| if dist.has_metadata('INSTALLER'):
for line in dist.get_metadata_lines('INSTALLER'):
if line.strip():
return line.strip()
return ''
| )
except specifiers.InvalidSpecifier as e:
logger.warning(
"Package %s has an invalid Requires-Python entry %s - %s",
dist.project_name, requires_python, e,
)
return
def get_installer(dist):
# type: (Distribution) -> str
| 64 | 64 | 50 | 16 | 47 | blurstudio/pip | src/pip/_internal/utils/packaging.py | Python | get_installer | get_installer | 86 | 92 | 86 | 87 | 07aa374de224605ecf376e49ef54bde6da7be12b | bigcode/the-stack | train |
c96290b7e824e540252bf53f | train | function | def get_metadata(dist):
# type: (Distribution) -> Message
if (isinstance(dist, pkg_resources.DistInfoDistribution) and
dist.has_metadata('METADATA')):
metadata = dist.get_metadata('METADATA')
elif dist.has_metadata('PKG-INFO'):
metadata = dist.get_metadata('PKG-INFO')
else:
... | def get_metadata(dist):
# type: (Distribution) -> Message
| if (isinstance(dist, pkg_resources.DistInfoDistribution) and
dist.has_metadata('METADATA')):
metadata = dist.get_metadata('METADATA')
elif dist.has_metadata('PKG-INFO'):
metadata = dist.get_metadata('PKG-INFO')
else:
logger.warning("No metadata found in %s", display_path(... | package provides no information
return True
requires_python_specifier = specifiers.SpecifierSet(requires_python)
python_version = version.parse('.'.join(map(str, version_info)))
return python_version in requires_python_specifier
def get_metadata(dist):
# type: (Distribution) -> Message
| 64 | 64 | 114 | 15 | 48 | blurstudio/pip | src/pip/_internal/utils/packaging.py | Python | get_metadata | get_metadata | 45 | 58 | 45 | 46 | d8c0b9eb74254fe901ac81c54f22e6860f56469d | bigcode/the-stack | train |
f7e16c67119a9fbebd18de57 | train | function | def main():
"""Main method"""
window = MyGame()
window.setup()
arcade.run()
| def main():
| """Main method"""
window = MyGame()
window.setup()
arcade.run()
| )
wall.position = coordinate
self.wall_list.append(wall)
def on_draw(self):
"""Render the screen."""
# Clear the screen to the background color
arcade.start_render()
# Draw our sprites
self.wall_list.draw()
self.player_list.draw(... | 64 | 64 | 22 | 3 | 61 | KommentatorForAll/arcade | arcade/examples/platform_tutorial/02_draw_sprites.py | Python | main | main | 80 | 84 | 80 | 80 | 666a11fd283f5d844f66a839b6ba1115af736670 | bigcode/the-stack | train |
ed91fbc8268ed2e4de34348a | train | class | class MyGame(arcade.Window):
"""
Main application class.
"""
def __init__(self):
# Call the parent class and set up the window
super().__init__(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE)
# These are 'lists' that keep track of our sprites. Each sprite should
# go into a... | class MyGame(arcade.Window):
| """
Main application class.
"""
def __init__(self):
# Call the parent class and set up the window
super().__init__(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_TITLE)
# These are 'lists' that keep track of our sprites. Each sprite should
# go into a list.
self.wall_list... | """
Platformer Game
"""
import arcade
# Constants
SCREEN_WIDTH = 1000
SCREEN_HEIGHT = 650
SCREEN_TITLE = "Platformer"
# Constants used to scale our sprites from their original size
CHARACTER_SCALING = 1
TILE_SCALING = 0.5
class MyGame(arcade.Window):
| 72 | 144 | 480 | 8 | 63 | KommentatorForAll/arcade | arcade/examples/platform_tutorial/02_draw_sprites.py | Python | MyGame | MyGame | 16 | 77 | 16 | 16 | 4911409be03d8b7da15159c06e7950f5c0a6e4fa | bigcode/the-stack | train |
7652f6f45d107a6f14415368 | train | function | def centre_point3d(points):
return sum( Vector3(p) for p in points ) / len(points)
| def centre_point3d(points):
| return sum( Vector3(p) for p in points ) / len(points)
| ):
x, y, z = p1
xx, yy, zz = p2
dx = x - xx
dy = y - yy
dz = z - zz
return sqrt(dx*dx + dy*dy +dz*dz)
def centre_point3d(points):
| 64 | 64 | 24 | 7 | 57 | lzhang1/BeginningPygame | Chapter 9/gameobjects/vector3.py | Python | centre_point3d | centre_point3d | 656 | 658 | 656 | 657 | 96d0f4bf41a4e7ec1d352017d1943adc38c57909 | bigcode/the-stack | train |
d00efe175d54af1700e69fbe | train | function | def distance3d(p1, p2):
x, y, z = p1
xx, yy, zz = p2
dx = x - xx
dy = y - yy
dz = z - zz
return sqrt(dx*dx + dy*dy +dz*dz)
| def distance3d(p1, p2):
| x, y, z = p1
xx, yy, zz = p2
dx = x - xx
dy = y - yy
dz = z - zz
return sqrt(dx*dx + dy*dy +dz*dz)
| x, y, z = p1
xx, yy, zz = p2
dx = x - xx
dy = y - yy
dz = z - zz
return dx*dx + dy*dy +dz*dz
def distance3d(p1, p2):
| 64 | 64 | 66 | 10 | 53 | lzhang1/BeginningPygame | Chapter 9/gameobjects/vector3.py | Python | distance3d | distance3d | 646 | 654 | 646 | 647 | 33d928fa5b70a0231ca93409b7258d143ea7905a | bigcode/the-stack | train |
26ca75f485369bc373096154 | train | class | class Vector3(object):
__slots__ = ('_v',)
_gameobjects_vector = 3
def __init__(self, *args):
"""Creates a Vector3 from 3 numeric values or a list-like object
containing at least 3 values. No arguments result in a null vector.
"""
if len(args) == 3:
self._v =... | class Vector3(object):
| __slots__ = ('_v',)
_gameobjects_vector = 3
def __init__(self, *args):
"""Creates a Vector3 from 3 numeric values or a list-like object
containing at least 3 values. No arguments result in a null vector.
"""
if len(args) == 3:
self._v = list(map(float, args[:3... | from math import *
from gameobjects.util import format_number
class Vector3(object):
| 17 | 256 | 4,144 | 5 | 11 | lzhang1/BeginningPygame | Chapter 9/gameobjects/vector3.py | Python | Vector3 | Vector3 | 4 | 632 | 4 | 5 | 8765b8a4b9dea5de64dc787f599cb9eb500f59fb | bigcode/the-stack | train |
0a5d476da8a5989572f3c44a | train | function | def distance3d_squared(p1, p2):
x, y, z = p1
xx, yy, zz = p2
dx = x - xx
dy = y - yy
dz = z - zz
return dx*dx + dy*dy +dz*dz
| def distance3d_squared(p1, p2):
| x, y, z = p1
xx, yy, zz = p2
dx = x - xx
dy = y - yy
dz = z - zz
return dx*dx + dy*dy +dz*dz
| A vector or tuple
"""
x, y, z = self._v
bx, by, bz = other
return ( y*bz - by*z,
z*bx - bz*x,
x*by - bx*y )
def distance3d_squared(p1, p2):
| 64 | 64 | 66 | 11 | 53 | lzhang1/BeginningPygame | Chapter 9/gameobjects/vector3.py | Python | distance3d_squared | distance3d_squared | 635 | 643 | 635 | 636 | 120adbeb9a3df6791c8eaddf97589c421f788ff5 | bigcode/the-stack | train |
5cd75caa43e45e84a435c151 | train | function | def main():
sum_to_form = int(input())
denominations = list(map(int, input().split(',')))
result = calculate_change_number_dyn(sum_to_form, denominations)
print(result)
| def main():
| sum_to_form = int(input())
denominations = list(map(int, input().split(',')))
result = calculate_change_number_dyn(sum_to_form, denominations)
print(result)
| #!/usr/bin/env python3
def main():
| 10 | 64 | 40 | 3 | 6 | leskin-in/mipt-bioalgo | hw5/change.py | Python | main | main | 4 | 8 | 4 | 4 | 31ec9a94223fed55bed7f54d5d14fc0e20c8905d | bigcode/the-stack | train |
6b51757e6a7121bd2444d5b2 | train | function | def calculate_change_number_dyn(sum_to_form: int, denominations: list) -> int:
"""
Calculate the minimum number of 'denominations' required to make 'sum'
:param sum_to_form: a sum to form
:param denominations: possible denominations ("steps")
:return: a total amount of denominations to use to reach ... | def calculate_change_number_dyn(sum_to_form: int, denominations: list) -> int:
| """
Calculate the minimum number of 'denominations' required to make 'sum'
:param sum_to_form: a sum to form
:param denominations: possible denominations ("steps")
:return: a total amount of denominations to use to reach 'sum'
"""
results = [-1 for _ in range(sum_to_form + 1)]
results[0]... | usr/bin/env python3
def main():
sum_to_form = int(input())
denominations = list(map(int, input().split(',')))
result = calculate_change_number_dyn(sum_to_form, denominations)
print(result)
def calculate_change_number_dyn(sum_to_form: int, denominations: list) -> int:
| 64 | 64 | 194 | 18 | 46 | leskin-in/mipt-bioalgo | hw5/change.py | Python | calculate_change_number_dyn | calculate_change_number_dyn | 11 | 30 | 11 | 11 | 14d3ee0bceb928c2116603850f532eb3acfbfa9a | bigcode/the-stack | train |
42ce646896a93286540c4db8 | train | class | @declare(guid=guid("a0e3d8ea-c34f-4419-a1db-90435b8b21d0"), event_id=1007, version=0)
class Microsoft_Windows_Biometrics_1007_0(Etw):
pattern = Struct(
"BiometricSensor" / WString,
"SensorAdapter" / WString,
"EngineAdapter" / WString,
"StorageAdapter" / WString,
"DatabaseID" ... | @declare(guid=guid("a0e3d8ea-c34f-4419-a1db-90435b8b21d0"), event_id=1007, version=0)
class Microsoft_Windows_Biometrics_1007_0(Etw):
| pattern = Struct(
"BiometricSensor" / WString,
"SensorAdapter" / WString,
"EngineAdapter" / WString,
"StorageAdapter" / WString,
"DatabaseID" / Guid,
"SensorMode" / Int32ul,
"SensorPool" / Int32ul,
"IsolationLevel" / Int32ul,
"IsolationSensorAd... | WString
)
@declare(guid=guid("a0e3d8ea-c34f-4419-a1db-90435b8b21d0"), event_id=1007, version=0)
class Microsoft_Windows_Biometrics_1007_0(Etw):
| 64 | 64 | 181 | 59 | 5 | IMULMUL/etl-parser | etl/parsers/etw/Microsoft_Windows_Biometrics.py | Python | Microsoft_Windows_Biometrics_1007_0 | Microsoft_Windows_Biometrics_1007_0 | 141 | 156 | 141 | 142 | 64bd825dac9e81a1591fe1d4494666faa3aaa307 | bigcode/the-stack | train |
f237c0dac13911a01e33d6bd | train | class | @declare(guid=guid("a0e3d8ea-c34f-4419-a1db-90435b8b21d0"), event_id=1014, version=0)
class Microsoft_Windows_Biometrics_1014_0(Etw):
pattern = Struct(
"BiometricSensor" / WString,
"SensorAdapter" / WString,
"EngineAdapter" / WString,
"StorageAdapter" / WString,
"DatabaseID" ... | @declare(guid=guid("a0e3d8ea-c34f-4419-a1db-90435b8b21d0"), event_id=1014, version=0)
class Microsoft_Windows_Biometrics_1014_0(Etw):
| pattern = Struct(
"BiometricSensor" / WString,
"SensorAdapter" / WString,
"EngineAdapter" / WString,
"StorageAdapter" / WString,
"DatabaseID" / Guid,
"SensorMode" / Int32ul,
"SensorPool" / Int32ul,
"IsolationLevel" / Int32ul,
"IsolationSensorAd... | 32ul
)
@declare(guid=guid("a0e3d8ea-c34f-4419-a1db-90435b8b21d0"), event_id=1014, version=0)
class Microsoft_Windows_Biometrics_1014_0(Etw):
| 64 | 64 | 197 | 59 | 5 | IMULMUL/etl-parser | etl/parsers/etw/Microsoft_Windows_Biometrics.py | Python | Microsoft_Windows_Biometrics_1014_0 | Microsoft_Windows_Biometrics_1014_0 | 270 | 287 | 270 | 271 | 063ea91ffd5a957ea4057d06efe25233c90f8fa5 | bigcode/the-stack | train |
bc77e8a380bec2bb6480f04d | train | class | @declare(guid=guid("a0e3d8ea-c34f-4419-a1db-90435b8b21d0"), event_id=1010, version=0)
class Microsoft_Windows_Biometrics_1010_0(Etw):
pattern = Struct(
"BiometricSensor" / WString,
"SensorAdapter" / WString,
"EngineAdapter" / WString,
"StorageAdapter" / WString,
"DatabaseID" ... | @declare(guid=guid("a0e3d8ea-c34f-4419-a1db-90435b8b21d0"), event_id=1010, version=0)
class Microsoft_Windows_Biometrics_1010_0(Etw):
| pattern = Struct(
"BiometricSensor" / WString,
"SensorAdapter" / WString,
"EngineAdapter" / WString,
"StorageAdapter" / WString,
"DatabaseID" / Guid,
"SensorMode" / Int32ul,
"SensorPool" / Int32ul,
"IsolationLevel" / Int32ul,
"IsolationSensorAd... | 32ul
)
@declare(guid=guid("a0e3d8ea-c34f-4419-a1db-90435b8b21d0"), event_id=1010, version=0)
class Microsoft_Windows_Biometrics_1010_0(Etw):
| 64 | 64 | 187 | 59 | 5 | IMULMUL/etl-parser | etl/parsers/etw/Microsoft_Windows_Biometrics.py | Python | Microsoft_Windows_Biometrics_1010_0 | Microsoft_Windows_Biometrics_1010_0 | 196 | 212 | 196 | 197 | 66e5d3ad6e3c932a24e122b20651a5fdb0b0a2c1 | bigcode/the-stack | train |
428e3e6e94205b47685ebe3d | train | class | @declare(guid=guid("a0e3d8ea-c34f-4419-a1db-90435b8b21d0"), event_id=1508, version=0)
class Microsoft_Windows_Biometrics_1508_0(Etw):
pattern = Struct(
"SID" / WString,
"Username" / WString
)
| @declare(guid=guid("a0e3d8ea-c34f-4419-a1db-90435b8b21d0"), event_id=1508, version=0)
class Microsoft_Windows_Biometrics_1508_0(Etw):
| pattern = Struct(
"SID" / WString,
"Username" / WString
)
| 32ul
)
@declare(guid=guid("a0e3d8ea-c34f-4419-a1db-90435b8b21d0"), event_id=1508, version=0)
class Microsoft_Windows_Biometrics_1508_0(Etw):
| 64 | 64 | 82 | 59 | 5 | IMULMUL/etl-parser | etl/parsers/etw/Microsoft_Windows_Biometrics.py | Python | Microsoft_Windows_Biometrics_1508_0 | Microsoft_Windows_Biometrics_1508_0 | 667 | 672 | 667 | 668 | ec6e6689a40e83c558845ea5af46d332a1ad9ef6 | bigcode/the-stack | train |
f4b6317baf883fcc963c53a9 | train | class | @declare(guid=guid("a0e3d8ea-c34f-4419-a1db-90435b8b21d0"), event_id=1006, version=0)
class Microsoft_Windows_Biometrics_1006_0(Etw):
pattern = Struct(
"BiometricSensor" / WString,
"SensorAdapter" / WString,
"EngineAdapter" / WString,
"StorageAdapter" / WString,
"DatabaseID" ... | @declare(guid=guid("a0e3d8ea-c34f-4419-a1db-90435b8b21d0"), event_id=1006, version=0)
class Microsoft_Windows_Biometrics_1006_0(Etw):
| pattern = Struct(
"BiometricSensor" / WString,
"SensorAdapter" / WString,
"EngineAdapter" / WString,
"StorageAdapter" / WString,
"DatabaseID" / Guid,
"SensorMode" / Int32ul,
"SensorPool" / Int32ul,
"IsolationLevel" / Int32ul,
"IsolationSensorAd... | WString
)
@declare(guid=guid("a0e3d8ea-c34f-4419-a1db-90435b8b21d0"), event_id=1006, version=0)
class Microsoft_Windows_Biometrics_1006_0(Etw):
| 64 | 64 | 171 | 59 | 5 | IMULMUL/etl-parser | etl/parsers/etw/Microsoft_Windows_Biometrics.py | Python | Microsoft_Windows_Biometrics_1006_0 | Microsoft_Windows_Biometrics_1006_0 | 124 | 138 | 124 | 125 | b652da4a372a54f1a129d959bc2c35e93fa37e72 | bigcode/the-stack | train |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.