id
stringlengths
1
8
text
stringlengths
6
1.05M
dataset_id
stringclasses
1 value
11392807
# -*- coding: utf-8 -*- """ Created on Wed Oct 9 18:20:41 2019 @author: <EMAIL> """ from .sunrise import * from .terminator import *
StarcoderdataPython
3412660
<gh_stars>10-100 import sys import tqdm import json import rdflib from rdflib import Namespace from rdflib.namespace import RDF, RDFS, OWL oboInOwl = Namespace('http://www.geneontology.org/formats/oboInOwl#') def owl_to_json(owl_file, json_file): ent_dict = dict() g = rdflib.Graph() g.parse(owl_file) ...
StarcoderdataPython
9787451
from flask import Flask, render_template, request, jsonify from ruamel import yaml import mysql.connector as my import os import shutil # 設定読み込み(config.ymlが存在しなければconfig.yml.sampleをコピーする) sampleConfigPath = "config.yml.sample" configPath = "config.yml" if not os.path.exists(configPath): shutil.copyfile(sampleConfi...
StarcoderdataPython
1934584
#!/usr/bin/env python3 from pgmpy.base import UndirectedGraph from pgmpy.tests import help_functions as hf import unittest class TestUndirectedGraphCreation(unittest.TestCase): def setUp(self): self.graph = UndirectedGraph() def test_class_init_without_data(self): self.assertIsInstance(self....
StarcoderdataPython
3392164
"""Fix whitespace issues.""" import os import re import argparse def find_files(top, exts): """Return a list of file paths with one of the given extensions. Args: top (str): The top level directory to search in. exts (tuple): a tuple of extensions to search for. Returns: a list o...
StarcoderdataPython
3456705
# -*- coding:utf-8 -*- """ @author: Alden @email: <EMAIL> @date: 2018/4/3 @version: 1.0.0.0 """ class Solution(object): def myAtoi(self, str): """ :type str: str :rtype: int """ res = 0 is_positive = None for i, v in enumerate(str): if res == 0: ...
StarcoderdataPython
1606448
# -*- coding: UTF-8 -* ''' @author: sintrb ''' """ PrintOnline Server. This module refer to SimpleHTTPServer """ __version__ = "0.0.3" import BaseHTTPServer import SocketServer import json import os import shutil import socket import sys import urlparse import cgi import re import inspect import tempfile try: ...
StarcoderdataPython
6617769
import luigi import os import pandas as pd from db import extract from db import sql from forecast import util import shutil import luigi.contrib.hadoop from sqlalchemy import create_engine from pysandag.database import get_connection_string from pysandag import database from db import log class IncPopulation(luigi.T...
StarcoderdataPython
249988
<filename>scripts/get_raw_sun_data.py ############ # Compute raw sun data using pvlib # # 2021-09-01 # <NAME> # # The data is about # - 1MB for a 2 of days, for ~2000 sites and takes about ~1 minutes # - 6MB for a 10 of days, for ~2000 sites and takes about ~1 minutes # - 252MB for a 365 of days, for ~2000 sites and ta...
StarcoderdataPython
123445
<reponame>imranq2/SparkAutoMapper.FHIR from __future__ import annotations from typing import Optional, TYPE_CHECKING, Union from spark_auto_mapper_fhir.fhir_types.date_time import FhirDateTime from spark_auto_mapper_fhir.fhir_types.list import FhirList from spark_auto_mapper_fhir.fhir_types.string import FhirString fr...
StarcoderdataPython
1792173
''' meetings_member - handling for meetings member ==================================================================================== ''' # standard from datetime import date, datetime from traceback import format_exc, format_exception_only from urllib.parse import urlencode # pypi from flask import request, flash,...
StarcoderdataPython
82473
import maya from .get_posts import get_posts def get_posts_for_dates(site_url, start_date, end_date): # get the posts posts_all = [] posts_selected = [] pages_tried_max = 100 done = False for i in list(range(1, pages_tried_max + 1)): if done is True: continue try: ...
StarcoderdataPython
5081543
<gh_stars>0 import os import pandas as pd from get_traces import load_traces, get_traces from highlights_state_selection import compute_states_importance, highlights from get_trajectories import get_trajectory_images, create_video, trajectories_by_importance, states_to_trajectories def create_highlights(args): ""...
StarcoderdataPython
6664265
#!/usr/bin/python # # Sigma Control API DUT (sniffer_get_field_value) # Copyright (c) 2014, Qualcomm Atheros, Inc. # All Rights Reserved. # Licensed under the Clear BSD license. See README for more details. import sys import subprocess import tshark for arg in sys.argv: if arg.startswith("FileName="): fil...
StarcoderdataPython
5081081
<gh_stars>1-10 """ Report Utility Generates and saves a CT machine's report based off of audit data. """ import logging from ctqa import logutil # Explicitly disabling matplotlib to prevent log spam logging.getLogger('matplotlib').setLevel(logging.WARNING) import matplotlib # Using simplified mpl backend due to exclus...
StarcoderdataPython
5041019
<reponame>navikt/dakan-api-graph from typing import Dict from typing import List from pydantic import BaseModel class Node(BaseModel): id: str label: str properties: dict class NodeResponse(Dict): id: str label: str type: str properties: dict class PagedNodes(Dict): page: int t...
StarcoderdataPython
8146205
import glob import os import gin import MinkowskiEngine as ME import open3d as o3d from src.data.base_loader import * from src.data.transforms import * from src.utils.file import read_trajectory @gin.configurable() class ThreeDMatchPairDatasetBase(PairDataset): OVERLAP_RATIO = None DATA_FILES = None def...
StarcoderdataPython
3503982
<reponame>twisted/quotient from nevow.livetrial.testcase import TestCase from nevow.athena import expose from nevow.tags import div, directive from nevow.loaders import stan from axiom.store import Store from xquotient.spam import Filter, HamFilterFragment class PostiniConfigurationTestCase(TestCase): """ T...
StarcoderdataPython
6547964
<gh_stars>10-100 from hana_ml.algorithms.pal.naive_bayes import NaiveBayes from hana_automl.algorithms.base_algo import BaseAlgorithm class NBayesCls(BaseAlgorithm): def __init__(self): super(NBayesCls, self).__init__() self.title = "NaiveBayesClassifier" self.params_range = { ...
StarcoderdataPython
3592584
<gh_stars>0 import os class Config(object): API_ID = int(os.environ.get("API_ID")) API_HASH = os.environ.get("API_HASH") BOT_TOKEN = os.environ.get("BOT_TOKEN") DATABASE_URL = os.environ.get("DATABASE_URL") UPDATES_CHANNEL = os.environ.get("UPDATES_CHANNEL", None) BIN_CHANNEL = int(os.environ.get("BIN_CHANNEL")...
StarcoderdataPython
1959948
# SPDX-License-Identifier: MIT # Copyright (c) 2019 Akumatic # # https://adventofcode.com/2019/day/8 def readFile() -> str: with open(f"{__file__.rstrip('code.py')}input.txt", "r") as f: return f.read()[:-1] def getLayers(input: str, width: int, height: int) -> list: layers = [] for i in range(0,...
StarcoderdataPython
1778472
import os import sys import imp import numpy as np import warnings warnings.filterwarnings("ignore") # Test for Torch def torch(test_models, model_path, img_path): results_o, results_d, op_sets = dict(), dict(), dict() from PIL import Image import torch import torchvision.models as models from tor...
StarcoderdataPython
9643583
""" Experimental code for reading Cozmo animations in .bin format. Cozmo animations are stored in files/cozmo/cozmo_resources/assets/animations inside the Cozmo mobile application. Animation data structures are declared in FlatBuffers format in files/cozmo/cozmo_resources/config/cozmo_anim.fbs . """ from typing im...
StarcoderdataPython
6412395
Ambiente = { '1': '1 - Produccion', '2': '2 - Pruebas', } TipoDocumento = { '11': '11 - Registro civil', '12': '12 - Tarjeta de identidad', '13': '13 - Cédula de ciudadanía', '21': '21 - Tarjeta de extranjería', '22': '22 - Cédula de extranjería', '31': '31 - NIT', '41': '41 - Pasa...
StarcoderdataPython
5148087
import os from ..discretization.modeltime import ModelTime from ..discretization.structuredgrid import StructuredGrid from ..mbase import BaseModel from ..modflow import Modflow from ..mt3d import Mt3dms from ..pakbase import Package from .swtvdf import SeawatVdf from .swtvsc import SeawatVsc class SeawatList(Packag...
StarcoderdataPython
8125198
<filename>Toby/network.py import keras import tensorflow as tf from keras import Input, Model from keras.layers import ( Dense, Reshape, Flatten, LeakyReLU, LayerNormalization, Dropout, BatchNormalization ) def build_generator(latent_space, n_var, n_features=2,use_bias=False): model = tf.keras.Sequent...
StarcoderdataPython
1604048
print(100 - (int(input())%100))
StarcoderdataPython
6646865
<filename>pyimgsaliency/saliency_mbd.py<gh_stars>0 import math import copy # import sys # import operator # import networkx as nx # import matplotlib.pyplot as plt import numpy as np import bottleneck as bn from scipy.spatial.distance import cdist from skimage.io import imread as skimage_imread from skimage.util import...
StarcoderdataPython
8013500
print("ece"<"csam")
StarcoderdataPython
8071490
#!/usr/bin/env python # USAGE # python real_time_object_detection.py import sys import configparser import time import numpy as np import imutils import cv2 import paho.mqtt.client as mqttClient ### Gather configuration parameters def gather_arg(): conf_par = configparser.ConfigParser() try: conf_pa...
StarcoderdataPython
6588842
# -*- coding: utf-8 -*-: from django.test import TestCase from django_dynamic_fixture import G from django.contrib.auth.models import User from resrc.tests.factories import UserFactory from resrc.userprofile.models import Profile from resrc.utils.templatetags.profile import profile from resrc.utils.templatetags.grav...
StarcoderdataPython
12853098
from django import forms from crispy_forms.helper import FormHelper from crispy_forms.layout import Submit from django.utils.translation import ugettext_lazy as _ from .models import Ride class RideForm(forms.ModelForm): date = forms.DateField( label=_('Date'), widget=forms.DateInput(format=('%Y...
StarcoderdataPython
1689682
import os, copy, cProfile, pstats, io import numpy as np import gdspy as gp import gds_tools as gdst def profile(fnc): """A decorator that uses cProfile to profile a function""" def inner(*args, **kwargs): pr = cProfile.Profile() pr.enable() retval = ...
StarcoderdataPython
1970573
<reponame>nik-panekin/olx_scraper<filename>utils/tor_proxy.py import subprocess import time import requests TOR_EXECUTABLE_PATH = 'C:/Tor/Tor/tor.exe' TOR_SOCKS_PROXIES = { 'http': 'socks5://127.0.0.1:9050', 'https': 'socks5://127.0.0.1:9050' } TOR_STARTUP_TIME = 15 HTTP_BIN_HOST = 'https://httpbin.org/' ...
StarcoderdataPython
1639645
<reponame>KVSlab/vascularManipulationToolkit<filename>morphman/common/vmtk_wrapper.py ## Copyright (c) <NAME>, <NAME>. All rights reserved. ## See LICENSE file for details. ## This software is distributed WITHOUT ANY WARRANTY; without even ## the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTI...
StarcoderdataPython
6498146
# This file is part of the pyMOR project (http://www.pymor.org). # Copyright 2013-2017 pyMOR developers and contributors. All rights reserved. # License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause) from pymor.core.interfaces import ImmutableInterface from pymor.discretizations.basic import Discr...
StarcoderdataPython
143037
'''Define the user model''' from sqlalchemy import Column, Integer, String from .base import Base class User(Base): '''User Table''' __tablename__ = 'user' id = Column(Integer, primary_key=True) display_name = Column(String(100), nullable=True) username = Column(String(300), nullable=False, index=...
StarcoderdataPython
3428917
<reponame>cuis15/FCFL import numpy as np import argparse from utils import concave_fun_eval, create_pf, circle_points from hco_search import hco_search import matplotlib.pyplot as plt from latex_utils import latexify parser = argparse.ArgumentParser() parser.add_argument('--n', type = int, default=20, help="the batc...
StarcoderdataPython
1697337
<reponame>Weiqi97/LilyPadz from flask import Flask, request, render_template from lilypadz.model.clustering import get_all_clustering_result, \ get_one_clustering_result from lilypadz.model.small_series import get_ss_for_one_toad, \ get_ss_for_multiple_toads, get_ss_for_one_toad_sight, \ get_ss_for_m...
StarcoderdataPython
3432349
from utils.db.mongo_orm import * class Role(Model): class Meta: database = db collection = 'role' # Fields _id = ObjectIdField() name = StringField(unique=True) description = StringField() def __str__(self): return "name:{} - description:{}".format(self.name, self.de...
StarcoderdataPython
11390852
# -*- coding: utf-8 -*- """Implementation of the ``AbstractRepositoryBackend`` using the ``disk-objectstore`` as the backend.""" import contextlib import shutil from typing import BinaryIO, Iterable, Iterator, List, Optional, Tuple from disk_objectstore import Container from aiida.common.lang import type_check from ...
StarcoderdataPython
6639036
<reponame>Hopson97/AppleFall import graphics as gfx import common import vector import tiles import apple as appleF import math import drawer def createAndroid(window): '''Creates the Android sprite (based on Dr. <NAME>'s code)''' coords = drawer.loadSpriteVerticies("android") body = gfx.Polygon(coords) ...
StarcoderdataPython
6415220
########## 6.8.7. Kernel Qui-quadrado ########## # O kernel qui-quadrado é uma escolha muito popular para treinar SVMs não lineares em aplicações de visão computacional. Ele pode ser calculado usando chi2_kernel e depois passado para um SVC com kernel="precomputed": from sklearn.svm import SVC from sklearn.me...
StarcoderdataPython
351837
import os import tempfile import unittest import shutil from typing import Dict from atcodertools.client.atcoder import AtCoderClient from atcodertools.client.models.contest import Contest from atcodertools.client.models.problem import Problem from atcodertools.common.language import CPP from atcodertools.tools import...
StarcoderdataPython
1931444
def findDecision(obj): #obj[0]: Driving_to, obj[1]: Passanger, obj[2]: Weather, obj[3]: Temperature, obj[4]: Time, obj[5]: Coupon, obj[6]: Coupon_validity, obj[7]: Gender, obj[8]: Age, obj[9]: Maritalstatus, obj[10]: Children, obj[11]: Education, obj[12]: Occupation, obj[13]: Income, obj[14]: Bar, obj[15]: Coffeehouse,...
StarcoderdataPython
3436053
from django.urls import path from . import views app_name = "upload" urlpatterns = [path("", views.image_upload, name="image_upload")]
StarcoderdataPython
11279288
<gh_stars>1-10 from django.core.management.base import BaseCommand, CommandError from cablegate.cable.models import Cable, CableMetadata class Command(BaseCommand): #args = '<poll_id poll_id ...>' #help = 'Closes the specified poll for voting' def handle(self, *args, **options): for cable in Cable...
StarcoderdataPython
224808
<reponame>dwxrycb123/Akina3 import nonebot from database.mysql import * from database.tables import * from models.model import * from config import * @nonebot.scheduler.scheduled_job('cron', day='*') async def clear_command_times(): record = await table_user_command_times.select_record('TRUE') for item in r...
StarcoderdataPython
8067142
#!/usr/bin/env python Copyright = """ Copyright 2020 © <NAME> 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/LI...
StarcoderdataPython
9657815
from collections import defaultdict, deque, Counter from itertools import combinations, combinations_with_replacement, permutations from functools import reduce import math # import numpy as np from operator import add, delitem, mul, itemgetter, attrgetter import re DS = [[-1, 0], [1, 0], [0, 1], [0, -1]] DS8 = DS + [...
StarcoderdataPython
4821784
from flask import current_app from app.default.default_values import types_sales from sqlalchemy.orm import Session from app.models.types_sales.type_sale import TypeSaleModel def default_types_sales(): try: session: Session = current_app.db.session types_sales_found = TypeSaleModel.query.all() ...
StarcoderdataPython
11353757
# checking for already existing files import os # downloading/extracting mnist data import gzip from tqdm import tqdm # visualising progress import numpy as np # loading data from buffer from fetch.ml import Layer, Variable, Session from fetch.ml import CrossEntropyLoss import matplotlib.pyplot as plt impo...
StarcoderdataPython
5043008
<reponame>yuzhounaut/SpaceM from . import FIJIcalls, manipulations __all__ = [FIJIcalls, manipulations]
StarcoderdataPython
1916351
<gh_stars>1-10 import nltk.chat.eliza as el import nltk.chat.iesha as ie import nltk.chat.suntsu as sun import nltk.chat.zen as zen import nltk.chat.rude as rude from chatterbot import ChatBot from chatterbot.training.trainers import ChatterBotCorpusTrainer from chatterbot.utils import clean from nltk.chat import util ...
StarcoderdataPython
12864054
import json import os import subprocess import sys TEST_FILENAME = "tmp_py_file" TEST_FOLDER = "clone_tests" TESTS = [ ("clone!( => move || {})", "If you have nothing to clone, no need to use this macro!"), ("clone!(|| {})", "If you have nothing to clone, no need to use this macro!"), ("cl...
StarcoderdataPython
5031005
<gh_stars>0 # Copyright 2018 Google LLC # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to ...
StarcoderdataPython
5007902
# Copyright 2013 Google Inc. 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 # # Unless required by applicable law or ag...
StarcoderdataPython
4947908
<reponame>wgslr/agh-compilation-theory #!/usr/bin/python from collections import defaultdict from copy import copy import AST allowed_operations = defaultdict(lambda: defaultdict(lambda: defaultdict(lambda: ""))) allowed_operations["+"]["int"]["int"] = "int" allowed_operations["+"]["float"]["int"] = "float" allowed_...
StarcoderdataPython
11213330
# # linter.py # Linter for SublimeLinter3, a code checking framework for Sublime Text 3 # # Written by <NAME> # Copyright (c) 2015 <NAME> # # License: MIT # """This module exports the Scalastyle plugin class.""" from os import path from SublimeLinter.lint import Linter, util class Scalastyle(Linter): """Provid...
StarcoderdataPython
1770944
<filename>shim/shim.py from helper import log, status, settings, sequence from abc import abstractmethod, ABCMeta from ctypes import * import os EXTENSION_NAME = "some extension" class Shim(metaclass=ABCMeta): def __init__(self): lib = cdll.LoadLibrary(os.path.dirname(__file__) + "/main.so") self....
StarcoderdataPython
37480
<gh_stars>0 import numpy as np import matplotlib.pyplot as plt import random if __name__ == '__main__': ones = np.ones(30, dtype=np.uint8) print(ones) doubled = [x * 2 for x in ones] doubled = ones * 2 print(doubled) negatives = ones - doubled print(negatives) y = np.random.rand(...
StarcoderdataPython
9708562
<reponame>JPGarzonE/curso-de-python<gh_stars>0 def main(): print("C A L C U L A D O R A D E F A C T O R I A L") numero = int( input("¿Cuál es tu numero? ") ) resultado = factorial(numero) print("El factorial de {} es {}".format(numero, resultado)) def factorial(numero): if numero == 1 : ...
StarcoderdataPython
1778509
<filename>openprocurement/search/update_orgs.py # -*- coding: utf-8 -*- import os import sys import fcntl import signal import logging.config from datetime import datetime, timedelta from ConfigParser import ConfigParser from openprocurement.search.version import __version__ from openprocurement.search.engine import...
StarcoderdataPython
11389262
<reponame>kamoljan/amazon-personalize-samples import json import boto3 import base64 def lambda_handler(event, context): # TODO implement #### Attach Policy to S3 Bucket s3 = boto3.client("s3") policy = { "Version": "2012-10-17", "Id": "PersonalizeS3BucketAccessPolicy", ...
StarcoderdataPython
3271988
from skmultiflow.evaluation.metrics import metrics import numpy as np from skmultiflow.core.base_object import BaseObject from skmultiflow.core.utils.data_structures import FastBuffer, FastComplexBuffer, ConfusionMatrix, MOLConfusionMatrix from skmultiflow.core.utils.validation import check_weights class Classificati...
StarcoderdataPython
4997416
<gh_stars>0 ''' Date: 2021-07-17 11:50:52 LastEditors: Liuliang LastEditTime: 2021-07-17 14:30:11 Description: ''' from collections import Iterable,Iterator,Generator # #1实现了__iter__方法就是iterable # # class IterObj: # # def __iter__(self): # # # 这里简单地返回自身 # # # 但实际情况可能不会这么写 # # # 而是通过内...
StarcoderdataPython
5003949
# -*- coding: utf-8 -*- """ Dropbox file system and targets. """ __all__ = ["DropboxFileSystem", "DropboxTarget", "DropboxFileTarget", "DropboxDirectoryTarget"] import logging import six from law.config import Config from law.target.remote import ( RemoteFileSystem, RemoteTarget, RemoteFileTarget, RemoteDire...
StarcoderdataPython
5147874
<reponame>li-phone/DetectionCompetition from tqdm import tqdm import glob import xml.etree.ElementTree as ET import os import json import numpy as np import random import pandas as pd try: from pandas import json_normalize except: from pandas.io.json import json_normalize def convert(size, box): dw = 1. ...
StarcoderdataPython
9631589
import os from flask import Flask,jsonify,request,render_template,redirect from heart_sound import predict from werkzeug.utils import secure_filename app = Flask(__name__) ## __name__= current file name (main) @app.route("/", methods = ["GET", "POST"]) ## page name def index(): prediction = "" if request.me...
StarcoderdataPython
1924537
<filename>Ayoubsprogramm1.py print("Mooooooin Meister!") topf = "Lego set" print(topf) print("Hallo ich programmiere gerade. Wer kann das auch?°,,,,°") print("-------------------------------------------------------")
StarcoderdataPython
9798412
<reponame>brandongk-ubco/wrinkler import torchvision from .AugmentedDataset import AugmentedDataset dataset_path = "/mnt/e/datasets/voc/" train_data = torchvision.datasets.VOCSegmentation(dataset_path, image_set='train') val_data = torchvision.datasets.VOCSegmentatio...
StarcoderdataPython
11307727
<gh_stars>1-10 import torch import numpy as np from collections import deque import time # if you have pre loaded weights in place. Set eps_start=0 def dqn(env, agent, WEIGHTS_PATH, brain_name, n_episodes=2000, eps_start=1, eps_end=0.01, eps_decay=0.993): """Deep Q-Learning. Params ====== n_episo...
StarcoderdataPython
3385211
<reponame>ThomasThoren/geographic-data """ topo2geojson.py Convert topojson to geojson Example Usage: python topo2geojson.py data.topojson data.geojson The topojson tested here was created using the mbostock topojson CLI created with --spherical coords and --properties turned on Author: <NAME> (http://github.com/...
StarcoderdataPython
4894775
<gh_stars>100-1000 import numpy as np import time from collections import defaultdict, OrderedDict from future.utils import viewitems from .base import Base from .to_float import to_float __all__ = [ "Simple", "TNT", "Timer", "Maximum", "Minimum", "Average", "Sum" ] class Simple(Base): def __init__(self, ...
StarcoderdataPython
40150
<filename>tests/test_utils.py import argparse import distutils.spawn import os import subprocess import pytest from pytest import mark from pytest_benchmark.utils import clonefunc from pytest_benchmark.utils import get_commit_info from pytest_benchmark.utils import get_project_name from pytest_benchmark.utils import ...
StarcoderdataPython
217955
<gh_stars>0 import os from PyQt5.QtGui import * from PyQt5.QtCore import * from PyQt5.QtWidgets import * from libs.threading import * import time import pickle from libs.ustr import ustr from libs.utils import * from libs.namedImage import * class FolderImagesSource(): def __init__(self, foldername): s...
StarcoderdataPython
12862481
<reponame>parag-hub/arrayfire-python #!/usr/bin/env python ####################################################### # Copyright (c) 2018, ArrayFire # All rights reserved. # # This file is distributed under 3-clause BSD license. # The complete license agreement can be obtained at: # http://arrayfire.com/licenses/BSD-3-C...
StarcoderdataPython
6554046
import command_system import db import commands.st3ch1 as st3ch1 import commands.st4_1ch0 as st4_1ch0 def next(vk_id, body): candidates = db.get_candidates(vk_id) cand_keys = [] for num, keys in enumerate(candidates): if keys[8]: fullname = keys[0].lower() + ' ' + keys[1].lower() + ' '...
StarcoderdataPython
357759
<reponame>konnase/DI-engine<gh_stars>1-10 import pytest import numpy as np import gym from easydict import EasyDict from dizoo.atari.envs import AtariMultiDiscreteEnv @pytest.mark.unittest class TestAtariMultiDiscreteEnv: def test_pong(self): env_num = 3 cfg = {'env_id': 'PongNoFrameskip-v4', 'fr...
StarcoderdataPython
9793707
""" This module is only responsible for the type of GUI. """ # -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'usbadc10gui/design.ui' # # Created by: PyQt5 UI code generator 5.15.2 # # WARNING: Any manual changes made to this file will be lost when pyuic5 is # run again. Do not edit this f...
StarcoderdataPython
3458196
<reponame>brunocvs7/dstools import pandas as pd import numpy as np from sklearn.metrics import recall_score, precision_score, f1_score import matplotlib.pyplot as plt def eval_thresh(y_real, y_proba): ''' Check the metrics varying the classification threshold Parameters: y_real (np.array): An a...
StarcoderdataPython
4819458
<gh_stars>0 # This file was automatically generated by SWIG (http://www.swig.org). # Version 2.0.12 # # Do not make changes to this file unless you know what you are doing--modify # the SWIG interface file instead. """ IDA Plugin SDK API wrapper: entry """ from sys import version_info if version_info >= (2,6,0): ...
StarcoderdataPython
4808343
from tools.general import load_input_list def resolve_bsp(bsp_code, low_char, high_char): lower = 0 upper = 2 ** len(bsp_code) - 1 for c in bsp_code: mid = (lower + upper) // 2 if c == high_char: lower = mid + 1 elif c == low_char: upper = mid else:...
StarcoderdataPython
3243121
<filename>twitter/util.py """ Internal utility functions. `htmlentitydecode` came from here: http://wiki.python.org/moin/EscapingHtml """ import re from htmlentitydefs import name2codepoint def htmlentitydecode(s): return re.sub( '&(%s);' % '|'.join(name2codepoint), lambda m: unichr(name2co...
StarcoderdataPython
9642459
<gh_stars>10-100 import math from src.objs import * # src -> https://stackoverflow.com/a/14822210 #: Convert bytes into human-readable size def convertSize(byte): if byte == 0: return "0B" size_name = ("B", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB") i = int(math.floor(math.log(byte, 1024))) p...
StarcoderdataPython
11311893
# problem 16 # Power digit sum """ 2**15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26. What is the sum of the digits of the number 2**1000? """ val = 2 ** 1000 summation = sum(int(i) for i in str(val)) print(summation)
StarcoderdataPython
4853580
<gh_stars>1-10 """ 给定两个单词 word1 和 word2,找到使得 word1 和 word2 相同所需的最小步数,每步可以删除任意一个字符串中的一个字符。 示例 1: 输入: "sea", "eat" 输出: 2 解释: 第一步将"sea"变为"ea",第二步将"eat"变为"ea" 说明: 给定单词的长度不超过500。 给定单词中的字符只含有小写字母。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/delete-operation-for-two-strings 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 """ ...
StarcoderdataPython
4989791
<gh_stars>0 """Builder Design Pattern (Made in Python 3.4.3) http://en.wikipedia.org/wiki/Builder_pattern This is my interpretation of the builder pattern for Python 3. Very simple. But also kinda cool! I use the lambda expression. This way you can design a builder to only be able to change certain properties later on...
StarcoderdataPython
9622311
<reponame>vishalbelsare/GraphFlow-1 import enum import numpy as np def L1norm(r1, r2): return np.sum(abs(r1 - r2)) class PageRankLanguage(enum.Enum): PYTHON = 0 CYTHON = 1 FORTRAN = 2 from . import hits from . import pagerank from . import simvoltage
StarcoderdataPython
3539441
<reponame>mroll/manticore<gh_stars>0 ''' Symbolic EVM implementation based on the yellow paper: http://gavwood.com/paper.pdf ''' import random import copy import inspect from functools import wraps from ..utils.helpers import issymbolic, memoized from ..platforms.platform import * from ..core.smtlib import solver, TooM...
StarcoderdataPython
8140694
<reponame>filwaitman/rest-api-lib-creator import requests from .datastructures import Meta, NoContent, UnhandledResponse from .utils import add_querystring_to_url class ListMixin(object): list_expected_status_code = 200 list_url = None @classmethod def get_list_url(cls): if cls.list_url: ...
StarcoderdataPython
187820
<filename>main.py # -*- coding: utf-8 -*- from flask import Flask import yagmail import logging import sys from flask import request reload(sys) sys.setdefaultencoding('utf-8') # change here mail_user = "yourmail" mail_pass = "<PASSWORD>" smtp_host = "smtp.163.com" smtp_port = '994' # end change app = Flask(__name_...
StarcoderdataPython
3294158
<gh_stars>10-100 ''' Authors: <NAME>, <NAME> ''' from ReLERNN.imports import * class SequenceBatchGenerator(tf.keras.utils.Sequence): ''' This class, SequenceBatchGenerator, extends tf.keras.utils.Sequence. So as to multithread the batch preparation in tandum with network training for maximum effecie...
StarcoderdataPython
5051840
# -*- coding: utf-8 -*- """Tests for Coastal Blue Carbon Functions.""" import unittest import os import shutil import csv import logging import tempfile import functools import copy import pprint import numpy from osgeo import gdal import pygeoprocessing.testing as pygeotest from natcap.invest import utils REGRESSION...
StarcoderdataPython
9663202
# # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the ...
StarcoderdataPython
1788243
<reponame>Dephilia/poaurk<filename>tests/api_test.py # -*- coding: utf-8 -*- import os import json import unittest # compatible python3 import sys from urllib.parse import parse_qsl from poaurk import PlurkAPI, PlurkOAuth class Test0ConsumerTokenSecret(unittest.TestCase): def setUp(self): pass def t...
StarcoderdataPython
8084655
import unittest import json from unittest.mock import Mock from tests import SAMPLE_BASE_URL, SAMPLE_CLIENT_ID, SAMPLE_CLIENT_SECRET def mock_response(headers, status_code, content='CONTENT', mock_json=None): # initialize mock response response = Mock() ...
StarcoderdataPython
3299747
<gh_stars>0 from collections import defaultdict from copy import copy from onegov.core.crypto import random_password from onegov.core.directives import query_form_class from onegov.core.security import Secret from onegov.core.templates import render_template from onegov.form import merge_forms from onegov.org import _,...
StarcoderdataPython
11396897
#!/usr/bin/env python # vim: expandtab:tabstop=4:shiftwidth=4 """ This is a script that snapshots all volumes in a given account. The volumes must be tagged like so: snapshot: daily snapshot: weekly Usage: ops-gcp-trim-pd-snapshots.py --keep-hourly 10 --gcp-creds-file /root/.gce/creds.json """ # Ignoring mod...
StarcoderdataPython
9788320
<filename>esmond/cassandra.py #!/usr/bin/env python # encoding: utf-8 """ Cassandra DB interface calls and data encapsulation objects. esmond schema in json-like notation: // regular col family "raw_data" : { "snmp:router_a:FastPollHC:ifHCInOctets:xe-0_2_0:30000:2012" : { "1343955624" : // long column n...
StarcoderdataPython