id
stringlengths
1
7
text
stringlengths
6
1.03M
dataset_id
stringclasses
1 value
1605689
import numpy as np from torchvision.datasets import mnist import torchvision.transforms as transforms from torch.utils.data import DataLoader batch_size_train = 64 batch_size_test = 128 learnrate = 0.01 transform = transforms.Compose([transforms.ToTensor(), transforms.Normalize([0.5], [0.5])]) #download download =...
StarcoderdataPython
3315950
<filename>diplomova_praca_lib/diplomova_praca_lib/position_similarity/evaluation_mechanisms.py from typing import List import PIL import numpy as np from diplomova_praca_lib.image_processing import split_image_to_square_regions, crop_image from diplomova_praca_lib.models import EvaluationMechanism from diplomo...
StarcoderdataPython
1688096
from setuptools import setup, find_packages import os version = '4.0.1' install_requires = [ 'setuptools', 'requests', 'APScheduler', 'iso8601', 'python-dateutil', 'Flask', 'Flask-Redis', 'WSGIProxy2', 'gevent', 'sse', 'flask_oauthlib', 'PyYAML', 'request_id_middlewa...
StarcoderdataPython
3375621
<gh_stars>10-100 from .errors import ( BadRequestError, ErrorCode, ErrorMessage, GatewayError, HTTPErrorCode, NotAllowedError, ServerError, ) from .status_codes import HTTPStatusCode from .urls import URL def capitalize_camel_case(string): return "".join([item.capitalize() for item in ...
StarcoderdataPython
3439
<gh_stars>0 # -*- coding: utf-8 -*- """ @Project : RNN_Prediction @Author : <NAME> @Filename: stockPrediction202005201318.py @IDE : PyCharm @Time1 : 2020-05-20 13:18:46 @Time2 : 2020/5/20 13:18 @Month1 : 5月 @Month2 : 五月 """ import tushare as ts import tensorflow as tf import pandas as pd from sklearn.model_...
StarcoderdataPython
27532
from builtins import isinstance from typing import Any, Dict, Tuple from fugue import ( DataFrame, FugueWorkflow, WorkflowDataFrame, WorkflowDataFrames, Yielded, ) from fugue.constants import FUGUE_CONF_SQL_IGNORE_CASE from fugue.workflow import is_acceptable_raw_df from fugue_sql._parse import Fug...
StarcoderdataPython
1684343
<reponame>mefatshabani/Crypto-One-Time-Pad #!/usr/bin/env python3 import os, sys def file_read_data(filename): file_handle = open(filename, 'rb') data = file_handle.read() file_handle.close() return data def file_write_data(filename, data): file_handle = open(filename, 'wb+') file_handle....
StarcoderdataPython
1636862
<filename>engine.py from labpack.storage.google.drive import driveClient import RPi.GPIO as GPIO # Import Raspberry Pi GPIO library from time import sleep # Import the sleep function from the time module import os import time import datetime import urllib2 def generate(): GPIO.setwarnings(False) # Ignore warni...
StarcoderdataPython
127796
# Internal import os import subprocess from sys import exit from tkinter import * from tkinter import filedialog from tkinter import messagebox import tkinter.ttk as ttk import webbrowser # User lib from osu_extractor.GetData import getSubFolder, getAllItemsInFolder, getFolderName, extractFiles, createPathIfNotExist, ...
StarcoderdataPython
3200580
""" All different pairs in cpmpy. Assumption: a is a k by 2 matrix. n is the number of nodes. This model implements these decompositions: - pairs(x,n): function which returns the pairs of matrix x in 'integer representation': a[k,1]*(n-1) + a[k,2] - all_different_pairs(sol, x,n): all the pairs in x must be diff...
StarcoderdataPython
1724998
from Actors import Teacher, Opening import random class Matcher: # TODO this shouldn't take teachers and openings, but preferences def __init__(self, teachers, openings): # TODO comment self.teachers = teachers self.openings = openings self.actors = teachers + openings ...
StarcoderdataPython
3244255
"""Module with tests tasks""" import invoke @invoke.task def unit_tests(context): """Run unit tests :param context: invoke.Context instance """ context.run("pytest ./tests", pty=True, echo=True) @invoke.task def static_code_analysis(context): """Run static code analysis :param context: i...
StarcoderdataPython
1781223
/// Queen Abby Commands /// <play - command where you look for the song and play it <spplay - Play music from Spotify & Soundcloud (Experimental) <np - shows the song that is playing <queue - you can see the playlist <skip - change the song <stop- stop the song <volume - raise or lower the volume of you...
StarcoderdataPython
1671523
# coding=utf-8 import os import pytest import shake from shake import (Shake, redirect, Response, Rule, json, NotAllowed, BadRequest, Unauthorized, Forbidden, NotFound, MethodNotAllowed, NotAcceptable, RequestTimeout, Gone, LengthRequired, PreconditionFailed, RequestEntityTooLarge, RequestURITooLar...
StarcoderdataPython
3242010
from django.db import models from django.db.models import CharField, TextField from django.urls import reverse from django_quill.fields import QuillField __all__ = ( "QuillPost", "NonQuillPost", ) class QuillPost(models.Model): content = QuillField() class Meta: ordering = ["-pk"] def ...
StarcoderdataPython
3319235
<reponame>whitmans-max/python-examples import pandas as pd df = pd.read_csv('test.zip') print(df)
StarcoderdataPython
1740642
<gh_stars>0 # coding: utf-8 # # Copyright 2014 The Oppia Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # ...
StarcoderdataPython
41978
<filename>HLIMDS_1/servo.py from RPi import GPIO as io from time import sleep io.setmode(io.BOARD) some_freq = 440 dc = 50 servo = 12 buzzer_pin = 32 led = 10 io.setup(servo, io.OUT) io.setup(buzzer_pin, io.OUT) io.setup(led, io.OUT) sg90 = io.PWM(servo, 50) sg90.start(7.5) buzzer =io.PWM(buzzer_pin, some_freq) buzze...
StarcoderdataPython
1796522
<gh_stars>1-10 # -*- coding: utf-8 -*- """ utils/test/test_utils """ import unittest import numpy as np from sklearn.preprocessing import normalize, StandardScaler, MinMaxScaler from ilcksvd.utils.utils import Normalizer class Test_Normalizer(unittest.TestCase): def setUp(self): samples = 3 fe...
StarcoderdataPython
1667866
import math import unittest import sycomore from sycomore.units import * class TestModel(unittest.TestCase): def test_pulse(self): model = sycomore.como.Model( sycomore.Species(1*s, 0.1*s), sycomore.Magnetization(0, 0, 1), [["dummy", sycomore.TimeInterval(0*s)]]) ...
StarcoderdataPython
1647691
import argparse from datetime import datetime import time import os from tqdm import trange, tqdm from timeit import default_timer as timer import numpy as np import matplotlib.pyplot as plt from collections import deque from perlin import TileableNoise from math import sin, pi from random import random, seed, unifor...
StarcoderdataPython
80494
# -*- coding: utf-8 -*- # this file is released under public domain and you can use without limitations ######################################################################### ## This is a sample controller ## - index is the default action of any application ## - user is required for authentication and authorization...
StarcoderdataPython
1615509
<reponame>amitabhadey/texteditor # ============================================================================= # Using Tkinter to develop the interface of the text editor and textstat to analyze and grade the composition # ============================================================================= from tkinter...
StarcoderdataPython
1795320
#!/usr/bin/python3 from datetime import date, datetime, timedelta as td import pytz import numpy as np import pandas as pd import glob import matplotlib.pyplot as plt def main(): print("Running main") if __name__ == "__main__": main()
StarcoderdataPython
3293918
from flask import render_template, Blueprint, jsonify home = Blueprint('home', __name__) @home.route('/') def index(): return render_template('index.html') def bad_request(message): response = jsonify({'message': message}) response.status_code = 400 return response class BadRequestError(ValueErro...
StarcoderdataPython
174451
class ShortPath: def __init__(self): self.paths = [] self.distance = 0
StarcoderdataPython
1734056
class Memory(object): """ 自扩展的虚拟内存,字节寻址 """ def __init__(self): self._memory = [] def _prepare_item(self, index): if len(self._memory) <= index: for i in range(index - len(self._memory) + 1): self._memory.append('00') def __getitem__(self, item): ...
StarcoderdataPython
184614
<reponame>Metalprobe/small-scale-expenditures # -*- coding: utf-8 -*- """ Created on Sun Jun 28 13:33:15 2020 @author: tomvi """ import pandas as pd loc="D:\\dir\\Python\\data\\" mayors=pd.read_excel(loc+"municip\\mayor2.xlsx",dtype={"m_code":"str"}) links=pd.read_csv(loc+"pap\\PAPlinks") munic=pd.read...
StarcoderdataPython
1645191
import numpy as np import pandas as pd def mtr(val, brackets, rates): """Calculates the marginal tax rate applied to a value depending on a tax schedule. :param val: Value to assess tax on, e.g. wealth or income (list or Series). :param brackets: Left side of each bracket (list or Series). :param...
StarcoderdataPython
3296176
""" Test routing functions of StaticConnection. """ import asyncio import pytest from aries_staticagent import ( StaticConnection, Message, Module, route ) from aries_staticagent.dispatcher import ( Dispatcher, NoRegisteredHandlerException ) from aries_staticagent.type import Type # pylint: disabl...
StarcoderdataPython
1786331
<gh_stars>10-100 import os from pathlib import Path from pytest import mark, raises, warns from staticjinja import Site, Reloader import staticjinja def test_template_names(site): site.staticpaths = ["static_css", "static_js", "favicon.ico"] expected_templates = set( ["template1.html", "template2.ht...
StarcoderdataPython
1652943
<filename>client/parser.py import argparse import run from python import params parser = argparse.ArgumentParser(description="") parser.add_argument('--model', type=str, default='node_classification') parser.add_argument('--data', type=str, default='cora') parser.add_argument('--num_hops', type=int, default=3) pa...
StarcoderdataPython
1758960
<gh_stars>0 # Time: O(n) # Source https://www.geeksforgeeks.org/rearrange-array-arri/ """ Visit all the elements in the array and store them in a map Then iterate again to create the result, if it is in the map then add the number otherwise -1 """ def rearrange(arr, n): result = list() seen = {} for i in range(...
StarcoderdataPython
3373396
<reponame>emge1/tracardi import os class TracardiConfig: def __init__(self, env): self.user = env['USER_NAME'] if 'USER_NAME' in env else 'admin' self.password = env['PASSWORD'] if 'PASSWORD' in env else '<PASSWORD>' self.track_debug = env['TRACK_DEBUG'] if 'TRACK_DEBUG' in env else False ...
StarcoderdataPython
1709410
def grad_nll(X, y, coefs): y_pred = np.dot(X, coefs) y_pred = 1 / (1 + np.exp(-y_pred)) grad = (y_pred - y) return np.dot(X.T, grad)
StarcoderdataPython
64484
# train-project/train_schedule/views/formatters.py """Helper functions to format data for display.""" def format_station(station, show_id=False): """Format station data for display""" if station is None: return "Unknown" else: fmt_str = "{city}, {country} ({code})" if show_id: ...
StarcoderdataPython
57161
import boto3 from botocore.config import Config def s3_client(): s3 = boto3.client('s3', aws_access_key_id="secretless", region_name="us-east-1", aws_secret_access_key="secretless", endpoint_url="http://secretless.empty", ...
StarcoderdataPython
4816881
<reponame>johanels/micropython-wemos-esp32 from machine import Pin led1=Pin(0,Pin.OUT) led2=Pin(2,Pin.OUT) led3=Pin(12,Pin.OUT) led4=Pin(13,Pin.OUT) led5=Pin(14,Pin.OUT) led6=Pin(15,Pin.OUT) led7=Pin(16,Pin.OUT) led1.value(1) led2.value(1) led3.value(1) led4.value(1) led5.value(1) led6.value(1) led7.value(1) led1.va...
StarcoderdataPython
128425
import math import random from typing import Optional from lib.sc2.position import Point2 from lib.sc2.units import Units import lib.sc2.constants as const from lambdanaut.builds import Builds from lambdanaut.expiringlist import ExpiringList from lambdanaut.const2 import Messages, ResourceManagerCommands from lambdan...
StarcoderdataPython
3292773
<filename>ocean_lib/common/ddo/constants.py # # Copyright 2021 Ocean Protocol Foundation # SPDX-License-Identifier: Apache-2.0 # """ Contains constant values for - `DID_DDO_CONTEXT_URL` - `PROOF_TYPE` """ DID_DDO_CONTEXT_URL = "https://w3id.org/did/v1" PROOF_TYPE = "DDOIntegritySignature"
StarcoderdataPython
39744
<reponame>archoversight/u2fval<gh_stars>10-100 from u2fval import app, exc from u2fval.model import db, Client from .soft_u2f_v2 import SoftU2FDevice, CERT from six.moves.urllib.parse import quote from cryptography import x509 from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives....
StarcoderdataPython
3316277
# -*- coding: utf-8 -*- from __future__ import unicode_literals from flask import Flask app = Flask(__name__) @app.route("/") def index(): return "It’s working!!!" @app.route("/hola/<string:elephants>/<int:a>/<int:b>") def hello(elephants, a, b): user = { "first_name": elephants, "last_name...
StarcoderdataPython
3279089
from __future__ import absolute_import, print_function, unicode_literals from gripql.aggregations import term, histogram, percentile from gripql.connection import Connection from gripql.graph import Graph, BulkAdd from gripql.operators import (and_, or_, not_, eq, neq, gt, gte, lt, lte, in_, ...
StarcoderdataPython
43863
<reponame>iero/BeatCrunch import sys, os import traceback import gensim import pickle import utils import Statistics import Article # Grep articles from services and extract informations # Used to debug services if __name__ == "__main__": if len(sys.argv) < 4 : print("Please use # python beattest.py services.xml...
StarcoderdataPython
31486
<filename>wdae/wdae/common_reports_api/tests/test_common_reports_api.py import pytest from rest_framework import status pytestmark = pytest.mark.usefixtures( "wdae_gpf_instance", "dae_calc_gene_sets", "use_common_reports" ) def test_variant_reports(admin_client): url = "/api/v3/common_reports/studies/study4...
StarcoderdataPython
4826417
<filename>jwt/decode-jwt/app.py import os from flask import Flask, request import jwt VONAGE_API_KEY = os.getenv("VONAGE_API_KEY") VONAGE_SIGNATURE_SECRET = os.getenv("VONAGE_SIGNATURE_SECRET") VONAGE_SIGNATURE_SECRET_METHOD = os.getenv("VONAGE_SIGNATURE_SECRET_METHOD") app = Flask(__name__) @app.route("/", methods=...
StarcoderdataPython
50849
from .conftest import TestTimeouts from ftplib import FTP from socket import timeout class TestFtplib(TestTimeouts): def test_connect(self): with self.raises(timeout): with FTP(self.connect_host(), timeout=1) as ftp: ftp.login() def test_read(self): with self.raise...
StarcoderdataPython
3270270
# 108. Convert Sorted Array to BST # # # # class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def BTPreINTraversal(self,root): if root in None: return
StarcoderdataPython
3358688
import sys from adafruit_mcp3xxx.analog_in import AnalogIn from logger.Logger import Logger, LOG_LEVEL from sensors.mcp3xxx.sensor import Sensor # Tested using Sun3Drucker Model SX239 # Wet Water = 287 # Dry Air = 584 AirBounds = 43700 WaterBounds = 13000 intervals = int((AirBounds - WaterBounds) / 3) class Soi...
StarcoderdataPython
1717035
<reponame>daudprobst/master_thesis<filename>src/ts_analysis/autocorrelation.py from pandas.plotting import autocorrelation_plot import matplotlib.pyplot as plt import os import csv from ts_analysis.timeseries import Timeseries def plot_autocorrelation(file_name: str, output_folder: str, normalize=True, **kwargs): ...
StarcoderdataPython
1769163
''' Created on Dec 16, 2018 @author: gsnyder Add tags to a project ''' from blackduck.HubRestApi import HubInstance import argparse parser = argparse.ArgumentParser("Add tags to a project") parser.add_argument("project_name") parser.add_argument("tag") args = parser.parse_args() hub = HubInstance() project_list ...
StarcoderdataPython
1769746
import os.path as osp import re from glob import glob import pysubs2 from PyPDF2 import PdfFileReader def naruto_order_episodes(x): return float(re.findall("(\d+)", x)[0]) def extract_naruto(): subtitles_dir = './naruto_subtitles' lines = [] for i, file in enumerate(sorted(glob(osp.join(subtitles_d...
StarcoderdataPython
164133
<reponame>old-school-vienna/predict-future-sales-py<gh_stars>0 import os import typing from dataclasses import dataclass from datetime import datetime from pathlib import Path from typing import List, Dict import numpy as np import pandas as pd import tensorflow.python.keras as keras import tensorflow.python.keras.lay...
StarcoderdataPython
3296405
''' Model for fetching chart ''' import io from html.parser import HTMLParser from bokeh.plotting import figure from bokeh.embed import components from bokeh.io.export import get_screenshot_as_png from selenium import webdriver from selenium.webdriver.firefox.options import Options from selenium.webdriver.commo...
StarcoderdataPython
143863
from __future__ import division import fa import sys import os from fa import chunker if __name__ == "__main__": from sys import stderr import argparse parser = argparse.ArgumentParser(description=( "Create a set of synthetic genomes consisting " "of subgroups per tax level. Some kmers are ...
StarcoderdataPython
3375656
import time import torch def time_synchronized(): torch.cuda.synchronize() if torch.cuda.is_available() else None return time.time()
StarcoderdataPython
3289479
<reponame>raroes/one-sense-per-citation-network #!/usr/bin/python3 # this script reads the BioCreative 2 Gene Normalization task annotations # this input file is a combination of the train and testing files input_file = "./data/bc2_gene_annotations.txt" output_file = "pmid_annotations.txt" results_file = "annotation_...
StarcoderdataPython
1689064
<reponame>jsdelivrbot/pyhackeriet<gh_stars>1-10 #!/usr/bin/env python from hackeriet.mqtt import MQTT from hackeriet.door import Doors import threading, os, logging logging.basicConfig(level=logging.DEBUG) piface = False # Determine if piface is used on the Pi if "PIFACE" in os.environ: piface = True logging.inf...
StarcoderdataPython
1657377
"""Represents MAC addresses in the application """ class Mac(): def __init__(self, mac_addr): self.mac_addr = mac_addr if not ':' in self.mac_addr: self.mac_addr = self._normalize() def __str__(self): return self.mac_addr def minify(self): return self.mac_addr....
StarcoderdataPython
3275890
import pytest import pypsutil from .util import get_dead_process def test_priority() -> None: proc = pypsutil.Process() assert proc.getpriority() == proc.getpriority() # Should succeed proc.setpriority(proc.getpriority()) def test_priority_no_proc() -> None: proc = get_dead_process() wi...
StarcoderdataPython
19193
class Token: def __init__(self, type=None, value=None): self.type = type self.value = value def __str__(self): return "Token({0}, {1})".format(self.type, self.value)
StarcoderdataPython
140826
from pymtl3 import * class RegisterFile( Component ): def construct( s, Type, nregs=32, rd_ports=1, wr_ports=1, const_zero=False ): addr_type = mk_bits( max( 1, clog2( nregs ) ) ) s.raddr = [ InPort( addr_type ) for i in range( rd_ports ) ] s.rdata = [ OutPort( Type ) for i in range( ...
StarcoderdataPython
182434
# Copyright © 2020 <NAME> # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following di...
StarcoderdataPython
1764507
#!/usr/bin/env python3 # Copyright (C) The Arvados Authors. All rights reserved. # # SPDX-License-Identifier: AGPL-3.0 """arvados_docker.cleaner - Remove unused Docker images from compute nodes Usage: python3 -m arvados_docker.cleaner --quota 50G """ import argparse import collections import copy import functools ...
StarcoderdataPython
135761
<gh_stars>0 import sys sys.path.insert(0, '../..') import pyrosim import math sim = pyrosim.Simulator(play_paused=True,debug=True,eval_time=5000) #for i in range(10): # segment = sim.send_cylinder(x=0,y=(-0.5-i),z=0.5, r=0,g=1,b=0,length=0.5,r1=0,r2=1,r3=0,radius=0.1,) segment = [sim.send_cylinder(x=0,y=(0.5+i)...
StarcoderdataPython
138834
# coding=utf-8 from OTLMOW.OTLModel.Datatypes.KeuzelijstField import KeuzelijstField from OTLMOW.OTLModel.Datatypes.KeuzelijstWaarde import KeuzelijstWaarde # Generated with OTLEnumerationCreator. To modify: extend, do not edit class KlOntvangerToepassing(KeuzelijstField): """Keuzelijst met modelnamen voor Ontvan...
StarcoderdataPython
1744711
import codecs import os import math import operator from functools import reduce def fetch_data(cand, ref): """ Store each reference and candidate sentences as a list """ references = [] if '.txt' in ref: reference_file = codecs.open(ref, 'r', 'utf-8') references.append(reference_file.rea...
StarcoderdataPython
1790486
<reponame>Magni77/django-event-store from collections import defaultdict from dataclasses import dataclass from math import inf from typing import Dict, List, Union from event_store.batch_enumerator import BatchIterator from event_store.exceptions import EventDuplicatedInStream, EventNotFound from event_store.expected...
StarcoderdataPython
1698221
#!/usr/bin/env python from __future__ import print_function import time import torch import torch.nn as nn import torch.nn.parallel import torch.optim as optim import torch.utils.data import torchvision.datasets as dset import torchvision.transforms as transforms import torchvision.utils as vutils from torch.autograd...
StarcoderdataPython
3278654
import numpy files = [ "data/hsbl1.csv", "data/bl2.csv", "data/hs2.csv", "data/ss2.csv", "data/bl3.csv", "data/hs3.csv", "data/ss3.csv", ] for filename in files: stats = [] data = {} with open(filename, "r") as fin: stats ...
StarcoderdataPython
3269242
<reponame>sjn-network-automation/prsw """Test validations used in API endpoints.""" import datetime import ipaddress from . import UnitTest from prsw.validators import Validators class TestValidators(UnitTest): def test__validate_asn(self): assert Validators._validate_asn(1234) is True assert Va...
StarcoderdataPython
3282982
<reponame>determined-ai/OReilly """Train a single layer neural network on MNIST with two classification outputs. The first output and loss function is the 10-class classification that is normally used to train MNIST. The second output and loss function is a binary classification target that predicts if the input digit ...
StarcoderdataPython
3320288
from optparse import OptionValueError from twitter.common.lang import Compatibility from twitter.common.quantity import Data, Time, Amount class InvalidTime(ValueError): def __init__(self, timestring): ValueError.__init__(self, "Invalid time span: %s" % timestring) def parse_time(timestring): """ Parse...
StarcoderdataPython
1650835
<filename>toqito/matrix_ops/tensor.py<gh_stars>10-100 """Tensor product operation.""" import numpy as np def tensor(*args) -> np.ndarray: r""" Compute the Kronecker tensor product [WikTensor]_. Tensor two matrices or vectors together using the standard Kronecker operation provided from numpy. Gi...
StarcoderdataPython
1773493
<reponame>SunnyxBd/feature_engine<gh_stars>1-10 import pandas as pd import pytest from sklearn.exceptions import NotFittedError from feature_engine.selection import DropConstantFeatures def test_drop_constant_features(df_constant_features): transformer = DropConstantFeatures(tol=1, variables=None) X = transfo...
StarcoderdataPython
3266094
import logging, yaml, os, sys, argparse, math import torch from Modules import GE2E from Arg_Parser import Recursive_Parse class Tracer(torch.nn.Module): def __init__(self, hp_path: str, checkpoint_path: str): super().__init__() self.hp = Recursive_Parse(yaml.load( open(hp_path, encodi...
StarcoderdataPython
1616180
<filename>d2go/runner/__init__.py #!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import importlib from typing import Optional, Type, Union from .default_runner import BaseRunner, Detectron2GoRunner, GeneralizedRCNNRunner from .lightning_task import DefaultTask from .tra...
StarcoderdataPython
1741126
# Copyright (C) 2021, Pyronear contributors. # This program is licensed under the GNU Affero General Public License version 3. # See LICENSE or go to <https://www.gnu.org/licenses/agpl-3.0.txt> for full license details. import unittest import tempfile from pathlib import Path import requests from pyrodataset import ...
StarcoderdataPython
4817743
<filename>microsockets/socket.py import json class Socket(object): def __init__(self, scope, send, room_manager): self.scope = scope self.connected = False self.payload = None self.event = None self.code = None self.__send = send self.__room_manager = room_m...
StarcoderdataPython
3270580
<filename>src/procedural_city_generation/additional_stuff/Singleton.py class Singleton: """ Singleton Object which can only have one instance. Is instanciated with a modulename, e.g. "roadmap", and reads the corresponding "roadmap.conf" in procedural_city_generation/inputs. All attributes are mutabl...
StarcoderdataPython
18234
<gh_stars>10-100 """ Creating training file from own custom dataset >> python annotation_csv.py \ --path_dataset ~/Data/PeopleDetections \ --path_output ../model_data """ import os import sys import glob import argparse import logging import pandas as pd import tqdm sys.path += [os.path.abspath('.'), os.pat...
StarcoderdataPython
3244963
<reponame>amschaal/bioshare<filename>bioshareX/contexts.py<gh_stars>1-10 from models import Share from guardian.shortcuts import get_objects_for_user from django.conf import settings def user_contexts(request): if request.user.is_authenticated() and not request.is_ajax(): recent_shares = Share.objec...
StarcoderdataPython
129823
# -*- coding: utf-8 -*- """ Created on Sun Apr 4 18:48:31 2021 @author: ktopo """ import requests from PIL import Image import matplotlib.pyplot as plt import base64 import json import io # %% SETUP BUCKET_NAME = 'ktopolovbucket' stage_url = 'https://dy0duracgd.execute-api.us-east-1.amazonaws.com/dev' # Local files...
StarcoderdataPython
3331799
<gh_stars>0 import os import textwrap import unittest from conans import __version__ as conan_version from conans import tools from tests.utils.test_cases.conan_client import ConanClientTestCase @unittest.skipUnless(conan_version >= "1.16.0", "Conan > 1.16.0 needed") class ConanCMakeBadFiles(ConanClientTestCase): ...
StarcoderdataPython
4834035
<gh_stars>1-10 import os import sys import StringIO import unittest import warnings warnings.simplefilter("error") from support import html5lib_test_files, TestData, convertExpected from html5lib import html5parser, treewalkers, treebuilders, constants from html5lib.filters.lint import Filter as LintFilter, LintErro...
StarcoderdataPython
4822875
from django.shortcuts import render, redirect from django.views.generic import TemplateView from django.contrib.auth.mixins import LoginRequiredMixin from django.contrib.auth import login from django.contrib.auth.models import User from .otp import send_otp import json from django.http import HttpResponse from django.c...
StarcoderdataPython
3227858
#!/usr/bin/env python3 # # --- Day 19: Beacon Scanner / Part Two --- # # Sometimes, it's a good idea to appreciate just how big the ocean is. # Using the Manhattan distance, how far apart do the scanners get? # # In the above example, scanners 2 (1105,-1205,1229) and 3 (-92,-2380,-20) # are the largest Manhattan distan...
StarcoderdataPython
3219804
<gh_stars>10-100 from inspect import isclass from enum import Enum from sqlalchemy import types from pulsar.api import ImproperlyConfigured class ScalarCoercible(object): def _coerce(self, value): raise NotImplementedError def coercion_listener(self, target, value, oldvalue, initiator): ret...
StarcoderdataPython
1746999
<reponame>grey-cat-1908/boticordpy from discord.ext import commands from disnake.ext import commands as commandsnake import aiohttp from typing import Union import asyncio from .modules import Bots, Servers, Users class BoticordClient: """ This class is used to make it much easier to use the Boticord API. ...
StarcoderdataPython
1741590
# -*- coding: utf-8 -*- """Gtk.TreeView() filter.""" import gi gi.require_version(namespace='Gtk', version='3.0') from gi.repository import Gtk, Gio, Pango, GObject class MainWindow(Gtk.ApplicationWindow): software_list = [ ('Firefox', 2002, 'C++'), ('Eclipse', 2004, 'Java'), ('Pitivi', 2004, 'Python')...
StarcoderdataPython
1659635
from .param import Parameter from .exceptions import ParamRedefineException import re from typing import List, Dict, Callable, Any, Union, Tuple DYNAMIC_ROUTE_PATTERN = re.compile(r"(:(?P<name>[a-zA-Z_]+)(<(?P<regex>.+)>)?)+") class Route: def __init__(self, method, url, controller): self.method: str ...
StarcoderdataPython
1610189
import socket import tkinter as tk from datetime import datetime from time import sleep import time import json from selenium import webdriver from selenium.webdriver.common.by import By from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.support.ui import WebDriverWait now = datet...
StarcoderdataPython
4825124
""" IApiCursor module. """ from typing import List, Any, Generator class IApiCursor: """Database internal cursor. Follows Python DBAPI for cursors. Do not confuse with FLSqlCuror.""" description: List closed: bool connection: Any arraysize: int itersize: int rowcount: int rownumber: i...
StarcoderdataPython
104152
<reponame>PAX-ULaval/pax-libraries<filename>paxLibUL/convolution/datasets.py import pickle as pk import numpy as np import pandas as pd import torch from paxutils.path import Path from torch.utils.data import Dataset class FaceDataset(Dataset): def __init__(self, csv_file, transform=None, columns=None): ...
StarcoderdataPython
3347159
from .. import lists def create_reader(note_type): def read_notes_xml_element(element): note_elements = lists.filter( _is_note_element, element.find_children("w:" + note_type), ) return lists.map(_read_note_element, note_elements) def _is_note_element(element)...
StarcoderdataPython
3311705
<reponame>ruth-ann/snap-python<gh_stars>100-1000 """Defines private classes for vairous iterators """ from snap import TIntV, TFltV, TStrV from collections.abc import Generator class _BaseIterator: def __init__(self, it): if not isinstance(it, Generator): raise TypeError('Expected Generator, bu...
StarcoderdataPython
3283085
from __future__ import unicode_literals __version__ = '0.14.0'
StarcoderdataPython
3271025
import numpy as np from astropy.io import fits from scipy import linalg from scipy.sparse import csr_matrix from vega.utils import find_file class Data: """Class for handling lya forest correlation function data. An instance of this is required for each cf component """ _data_vec = None _masked_...
StarcoderdataPython
33110
<reponame>krispingal/improved-happiness """Preprocessing for tag generation""" from tag_generation.util import utils import jsonlines import csv # For test FILE_LOC = '/home/krispin/data/improved-happiness/' # For dev #FILE_LOC = '/home/krispin/data/improved-happiness/proto/' skipped, wrote = 0, 0 def get_recipe_ta...
StarcoderdataPython
1665399
import numpy as np def binary_classification_metrics(prediction, ground_truth): ''' Computes metrics for binary classification Arguments: prediction, np array of bool (num_samples) - model predictions ground_truth, np array of bool (num_samples) - true labels Returns: precision, recall, f...
StarcoderdataPython