id stringlengths 1 7 | text stringlengths 6 1.03M | dataset_id stringclasses 1
value |
|---|---|---|
1760285 | # -*- coding:utf-8 -*-
"""
Market module.
Author: HuangTao
Date: 2019/02/16
Email: <EMAIL>
"""
import json
from aioquant import const
from aioquant.utils import logger
class Orderbook:
"""Orderbook object.
Args:
platform: Exchange platform name, e.g. `binance` / `bitmex`.
symbol: Trade... | StarcoderdataPython |
4838415 | def getNextGenotype(genotypeLine):
# Get the location and rsid number for the next genotype
genotypeLineElements = genotypeLine.split("\t")
rsidList = []
if genotypeLineElements[2][0:2] == "rs":
# At a SNP
rsidList = genotypeLineElements[2].strip().split(";")
else:
rsidList = ["Indel"]
genotypeInfo... | StarcoderdataPython |
170817 | <gh_stars>1-10
from karp5.server.translator.parser import freetext
from karp5.tests.util import assert_es_search
def test_freetext_minimum():
text = None
mode = "karp"
result = freetext(text, mode)
expected = {
"query": {
"bool": {
"should": [
... | StarcoderdataPython |
3372444 | # jump
import pygame
from pygame.locals import *
import sys
import random
pygame.init() # Begin pygame
vec = pygame.math.Vector2
# CONSTANTS
HEIGHT = 550
WIDTH = 1000
FPS = 60
FPS_CLOCK = pygame.time.Clock()
COUNT = 0
ACC = 0.5
FRIC = -0.05
JUMP = -7
GRAVITY = 0.25
# CLASS INTERFACES
class Background(pygame.sprite.... | StarcoderdataPython |
3310613 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""segnet package file tf_record
Segmentation_base_class -> SegmentationInput -> SegmentationCompile ->
SegmentationSummaries -> Segmentation_model_utils -> Segmentation_train
TODO CHECK SIZE OF PROBABILITY, IT CAME OUT AS 1800 1800 1
"""
import numpy as np
from .segme... | StarcoderdataPython |
3295751 | <reponame>Govexec/django-formulaic<gh_stars>1-10
import json
from ckeditor.fields import RichTextField
from django.contrib.contenttypes.models import ContentType
from django.db import models, transaction
from django.db.models import Max
from django.forms import fields, widgets
from django.utils import timezone
from dj... | StarcoderdataPython |
3237696 | <gh_stars>1-10
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import struct, os
filename, count_one, count_zero = 'example.txt', 0, 0
for current_byte in list(open(filename, 'rb').read()):
count_one += bin(struct.unpack("B", current_byte)[0]).count('1')
count_zero = os.path.getsize(filename) * 8 - count_one
p... | StarcoderdataPython |
1772086 | class Solution(object):
def longestValidParentheses(self, s):
"""
:type s: str
:rtype: int
"""
l = [0] * len(s)
mx = 0
for i in range(1,len(s)):
if (s[i] == ')') and (i - l[i-1] -1 >=0) and (s[i-l[i-1]-1] == '('):
c = i - l[i-1] - 2... | StarcoderdataPython |
3316343 | <filename>src/encoder_decoder/encoder_decoder.py<gh_stars>0
from transformers import AutoModel, BertGenerationConfig, BertGenerationDecoder
from torch.nn import Module
class EncoderDecoderModel(Module):
def __init__(self, num_hidden_layers):
super(EncoderDecoderModel, self).__init__()
self.encoder... | StarcoderdataPython |
120783 | from datetime import datetime, timedelta
import pytest
from actions.user.authentication import (
UserAuthentication,
InvalidCredentialsException,
)
from database_schemas.users import UserEntry
from data_models.access_token import UserToken
@pytest.fixture(name="user_authentication")
def fixture_user_authenti... | StarcoderdataPython |
3225824 | <reponame>stackhpc/azimuth
"""
Module containing the base authenticator.
"""
class BaseAuthenticator:
"""
Base class for an authenticator, defining the expected interface.
"""
#: Indicates if the authenticator uses cross-domain POST requests in the auth completion
#: This has implications for the ... | StarcoderdataPython |
1666188 | <filename>docker/machine/cli/machine.py
import inspect
import docker.machine
from docker.machine.cli.client import Status
class Machine(object):
@classmethod
def default_client(cls):
return docker.machine.CLIENT
@classmethod
def docker_machine_version(cls):
return cls.default_client... | StarcoderdataPython |
135723 | # -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
import lo... | StarcoderdataPython |
1643204 | """empty message
Revision ID: 13796bbe4df2
Revises:
Create Date: 2021-03-22 21:48:31.734766
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '13796bbe4df2'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto gene... | StarcoderdataPython |
3395067 | <filename>test/test_config_value_integer.py
# coding=utf-8
import pathlib
import pytest
from elib_config import ConfigValueInteger, ConfigValueTypeError, MissingValueError, OutOfBoundError
@pytest.fixture(name='value')
def _dummy_string_value():
yield ConfigValueInteger(
'key',
description='des... | StarcoderdataPython |
1710742 | from django.contrib import admin
from movies.models import Movie
# Register your models here.
admin.site.register(Movie)
| StarcoderdataPython |
3240283 | <gh_stars>1-10
import pytest
import requests_mock
import rich
from openff.bespokefit.cli.executor.list import _get_columns, list_cli
from openff.bespokefit.executor.services import current_settings
from openff.bespokefit.executor.services.coordinator.models import (
CoordinatorGETPageResponse,
CoordinatorGETRe... | StarcoderdataPython |
3270938 | from classess.virustotal import *
from time import sleep
## main interface that will be introduced in the beginning
def interface():
print("""
_______ ______ _
|__ __| |___ / | |
| | ___ __ _ _ __ ___ / / ___ __| |
| |/ _ \/ _... | StarcoderdataPython |
52855 | <gh_stars>10-100
import numpy as np
#import cPickle as pickle
import pickle
class Data_Preparation:
def __init__ (self, vectors_file):
self.vectors_dc=self.load_word_embedding_pickle(vectors_file)
def load_word_embedding_pickle(self, pickle_file):
vectors_dc = pickle.load( o... | StarcoderdataPython |
52599 | <reponame>kukiamarilla/polijira<gh_stars>1-10
from django.core.exceptions import ValidationError
from backend.api.models import Miembro
from django import forms
class CreateMiembroSprintForm(forms.Form):
"""
CreateMiembroSprintForm Valida los datos del request.data al crear un miembro del sprint
Args:
... | StarcoderdataPython |
1716565 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# PROGRAMMER: <NAME>
# DATE CREATED: Feb. 23, 2019
# PURPOSE: Predict flower name from an image with predict.py along with the probability of that name.
# Can also predict the Top K classes and use category name mapping to show the real names.
imp... | StarcoderdataPython |
174980 | <reponame>AlexanderFabisch/slither<filename>slither/test/test_unit_conversions.py
from slither.core import unit_conversions
from nose.tools import assert_equal
def test_semicircles_to_radians():
assert_equal(unit_conversions.semicircles_to_radians(0), 0)
assert_equal(unit_conversions.semicircles_to_radians(1)... | StarcoderdataPython |
1735520 | <reponame>ChadKillingsworth/sentry
from __future__ import absolute_import
import logging
from django.contrib import messages
from django.core.urlresolvers import reverse
from sentry.models import OrganizationMemberType
from sentry.permissions import can_create_teams, Permissions
from sentry.web.forms.add_project imp... | StarcoderdataPython |
47970 | import sys
import re
from pprint import pprint
sample = { 'awesome-cancer-variant-databases':
{ 'Cancer':
{
'Clinically-focused':
[{'CanDL': 'https://candl.osu.edu' }],
'Catalogs':
[{ 'COSMIC':
... | StarcoderdataPython |
1636566 | <gh_stars>0
# Copyright 2019, 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/LICENSE-2.0
#
# Unless required by applicable law o... | StarcoderdataPython |
1625292 | from flatfeature import Bed
import operator
class LocalDups(object):
def __init__(self,filename,bed):
self.filename = filename
self.bed = Bed(bed)
self.bed.fill_dict()
def get_order_dups(self):
d = {}
for line in open(self.filename):
dupline = DupLine(line)
... | StarcoderdataPython |
99435 | <filename>locations/spiders/nike.py
import scrapy
import re
from locations.items import GeojsonPointItem
class NikeSpider(scrapy.Spider):
name = "nike"
allowed_domains = ["www.nike.com"]
download_delay = 1.5
start_urls = (
'https://www.nike.com/us/en_us/retail/en/directory',
)
def par... | StarcoderdataPython |
1748414 | <gh_stars>0
from configs import LearningConfigs
from modules.Snake import Snake
from modules.Food import Food
from modules.Render import Render
from modules.Observer import Observer
class Game:
def __init__(self, screen = None):
self.screen = screen
self.snake = Snake()
self.food = Food(sel... | StarcoderdataPython |
4830736 | <reponame>t-vi/candlegp<gh_stars>10-100
# Copyright 2016 <NAME>, <NAME>, alexggmatthews
# Copyright 2017 <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/licen... | StarcoderdataPython |
1618299 | <reponame>imcs-compsim/meshpy
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# MeshPy: A beam finite element input generator
#
# MIT License
#
# Copyright (c) 2021 <NAME>
# Institute for Mathematics and Computer-Based Simulation
# ... | StarcoderdataPython |
1715668 | <filename>Part 2/Week_1_3/Exer 1 - Tamanho da Matriz.py
import dimensoes
minha_matriz = [[1, 2, 3], [4, 5, 6]]
minha_matriz2 = [[1], [2], [3]]
print(dimensoes.dimensoes(minha_matriz))
print(dimensoes.dimensoes(minha_matriz2))
| StarcoderdataPython |
1620547 | from cs231n.layers import *
from cs231n.fast_layers import *
def affine_relu_forward(x, w, b):
"""
Convenience layer that perorms an affine transform followed by a ReLU
Inputs:
- x: Input to the affine layer
- w, b: Weights for the affine layer
Returns a tuple of:
- out: Output from the ReLU
- cache... | StarcoderdataPython |
150044 | import numpy as np
import cv2
from matplotlib import pyplot as plt
img = cv2.imread('b.jpg',0)
print(img.shape)
# Initiate STAR detector
star = cv2.xfeatures2d.StarDetector_create()
# Initiate BRIEF extractor
brief = cv2.xfeatures2d.BriefDescriptorExtractor_create()
# find the keypoints with STAR
kp = star.detect(i... | StarcoderdataPython |
1643493 | import requests
import urllib3
from loguru import logger
from requests_toolbelt import MultipartEncoder
from PicImageSearch.Utils.iqdb import IqdbResponse
class Iqdb:
"""
Iqdb and Iqdb 3d
-----------
Reverse image from http://www.iqdb.org\n
Params Keys
-----------
:param **requests_kwar... | StarcoderdataPython |
1695850 | <gh_stars>0
from microbit import *
import math
REFRESH = 50
def get_data():
x, y, z = accelerometer.get_x(), accelerometer.get_y(), accelerometer.get_z()
#acceleration = math.sqrt(x**2 + y**2 + z**2)
#a, b = button_a.was_pressed(), button_b.was_pressed()
#print(x, y, z, a, b)
print(x, y, z)
def... | StarcoderdataPython |
1689625 | print("Hello Vagrant")
| StarcoderdataPython |
3265443 | # -*- coding: utf-8 -*-
# Copyright 2019-2021 releng-tool
from releng_tool.util.io import interim_working_dir
from releng_tool.util.io import opt_file
from releng_tool.util.io import run_script
from releng_tool.util.log import verbose
import os
import sys
#: filename of the script to execute the post-processing opera... | StarcoderdataPython |
3377275 | <gh_stars>1-10
from sklearn.model_selection import StratifiedKFold
from sklearn.preprocessing import OneHotEncoder
from joblib import Parallel, delayed
from joblib import dump, load
from .joblib_silent_timeout import ParallelSilentTimeout
from joblib.externals.loky.process_executor import TerminatedWorkerError
from fun... | StarcoderdataPython |
1672719 | import base64
from django.contrib.auth import get_user_model
from django.contrib.sites.models import Site
from django.core import mail
from django.test import TestCase
from django.test.utils import override_settings
from six.moves import cPickle as pickle
from . import get_backend_id
from ..conf import settings
from ... | StarcoderdataPython |
99904 | <filename>utils/nbdepend.py
#!/usr/bin/env python
# Issue dependencies for given notebook(s)
"""
usage:
python nbdepend.py A.ipynb B.ipynb C.ipynb > Makefile_deps
"""
import io, os, sys, types, re
from IPython import get_ipython
from IPython.core.interactiveshell import InteractiveShell
import nbformat
RE_IMPORT =... | StarcoderdataPython |
125396 | <reponame>micmurawski/big-array
from typing import List, Tuple
import numpy as np
def chunk2list(chunk: Tuple[slice]) -> List[List[int]]:
return [[s.start, s.stop, s.step] for s in chunk]
def list2chunk(_list: List[List[int]]) -> Tuple[slice]:
return tuple([slice(*el) for el in _list])
def is_in(s, key):... | StarcoderdataPython |
3207262 | <reponame>lunika/richie
"""
Helpers that can be useful throughout the whole project
"""
import random
from django.conf import settings
from django.utils.text import slugify
import factory
from cms.api import add_plugin, create_page, create_title
def create_i18n_page(title=None, languages=None, is_homepage=False, **... | StarcoderdataPython |
60426 | #!/usr/bin/env python
# Copyright JS Foundation and other contributors, http://js.foundation
#
# 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.... | StarcoderdataPython |
126265 | <filename>main.py
""""
The main file for the fall detection task
Written by <NAME>
"""
""" Fist let import the necessary library"""
import math
import numpy as np
import cv2.cv2 as cv2
from sklearn.externals import joblib
from scipy.ndimage.interpolation import shift
from matplotlib import pyplot as plt
from sklea... | StarcoderdataPython |
83327 | <gh_stars>0
name = 'Escape'
movies = [
{'title': 'My Neighbor Totoro', 'year': '1988'},
{'title': 'Dead Poets Society', 'year': '1989'},
{'title': 'A Perfect World', 'year': '1993'},
{'title': 'Leon', 'year': '1994'},
{'title': 'Mahjong', 'year': '1996'},
{'title': 'Swallowtail Butterfly', 'yea... | StarcoderdataPython |
3251936 | <gh_stars>100-1000
# Copyright (c) 2020 Institution of Parallel and Distributed System, Shanghai Jiao Tong University
# ServerlessBench is licensed under the Mulan PSL v1.
# You can use this software according to the terms and conditions of the Mulan PSL v1.
# You may obtain a copy of Mulan PSL v1 at:
# http://lic... | StarcoderdataPython |
49 | <filename>test.py
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import torch.backends.cudnn as cudnn
import torchvision
import torchvision.transforms as transforms
import torchvision.datasets as datasets
import os
import argparse
from torch.autograd impor... | StarcoderdataPython |
4829314 | <reponame>Jspsun/LEETCodePractice<gh_stars>1-10
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def lowestCommonAncestor(self, root, p, q):
"""
:type r... | StarcoderdataPython |
167600 | <gh_stars>10-100
# Generated by Django 2.0.10 on 2019-04-30 20:23
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('userprofile', '0013_auto_20190408_1825'),
]
operations = [
migrations.RemoveField(
model_name='profile',
... | StarcoderdataPython |
1696082 | #!/usr/bin/env python3
import argparse
import concurrent.futures
import glob
import itertools
import io
import os
import subprocess
def cargo_boilerplate(binary):
return ['cargo', 'run', '--bin', binary, '--release', '--']
# binjs_generate_prediction_tables takes a dictionary output path
# whereas binjs_encode t... | StarcoderdataPython |
3322137 | <reponame>samacyc/loanBook
from django.contrib.auth import get_user_model
from django.urls import reverse
from django.test import TestCase
from rest_framework.test import APIClient
from core.models import Ingredients
from books.serializers import IngredientSerializer
INGREDIENT_URL =reverse('books:ingredients-list')
... | StarcoderdataPython |
84712 | <gh_stars>10-100
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from hwt.code import If, FsmBuilder
from hwt.math import inRange
from hwt.hdl.types.enum import HEnum
from hwtLib.abstract.busEndpoint import BusEndpoint
from hwtLib.avalon.mm import AvalonMM, RESP_OKAY, RESP_SLAVEERROR
class AvalonMmEndpoint(BusEndpoin... | StarcoderdataPython |
4800288 | # -*- test-case-name: nevow.test.test_flatstan,nevow.test.test_later -*-
# Copyright (c) 2004,2008 Divmod.
# See LICENSE for details.
from twisted.internet import defer
from nevow import flat
def _isDeferred(d):
"""
Flattener predicate for trampolining out when handling a Deferred.
"""
return isinst... | StarcoderdataPython |
1795749 | import cv2
import numpy as np
import pickle
class Calibrate:
def __init__(self, name='', image=None, device=''):
self.name = name
self.image = image
self.device = device
self.mtx = None
self.dist = None
self.obj_pts = []
self.img_pts = []
# From the OpenCV documentation
def get_obj_pts(self, show_... | StarcoderdataPython |
1762845 | <filename>setup.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
# thumbor imaging service
# https://github.com/globocom/thumbor/wiki
# Licensed under the MIT license:
# http://www.opensource.org/licenses/mit-license
# Copyright (c) 2011 globo.com <EMAIL>
from setuptools import setup, find_packages
from remotecv import ... | StarcoderdataPython |
3389161 | import pandas as pd
def count_people_field1_not_match_field2(field1, field2, data):
res_count = 0
for (f1, f2) in zip(data[field1], data[field2]):
if not find_match(f1, f2) and not find_match(f2, f1):
res_count += 1
return res_count
def top(top_size, data, f_to_search, f_to_return, s... | StarcoderdataPython |
3270140 | from tkinter import *
root = Tk()
root.title("chemist")
root.geometry('220x500')
root.resizable(False,False)
im = PhotoImage(file='flask1.gif')
elements = ['O','H','C','S','Ci','Na']
sub1 = ['OH','OC','OHS','HCi','CiNa','OHNa','HS','OS','OSNa','HC','CNa','OCi']
sub2 = ['H2O','CO2','H2SO4','HCi','NaCi','NaOH','H2S','SO2... | StarcoderdataPython |
1643105 | #!/usr/bin/env python
import stem.control
import sys
con = stem.control.Controller.from_port()
con.authenticate()
# Disable automatic circuit creation:
# http://www.thesprawl.org/research/tor-control-protocol/
con.set_conf('__DisablePredictedCircuits', '1')
con.set_conf('MaxOnionsPending', '0')
con.set_conf('newcircui... | StarcoderdataPython |
3249921 | # encoding: UTF-8
from tkinter import *
from tkinter import ttk
root = Tk()
ttk.Button(root, text="Hello World").grid()
root.mainloop() | StarcoderdataPython |
3252073 | #!/usr/bin/env python
# coding: latin-1
"""
nat_topo.py: a mininet topology for testing the NAT/Kiwi implementation
<NAME>, Cambridge University Computer Lab, August 2016
This software was developed by the University of Cambridge,
Computer Laboratory under EPSRC NaaS Project EP/K034723/1
Use of this source code is ... | StarcoderdataPython |
3373919 | <reponame>arifmudi/Hands-On-Transfer-Learning-with-Python
# coding: utf-8
# ## Import required packages
import numpy as np
import pandas as pd
from collections import Counter
# plotting
import seaborn as sns
import matplotlib.pyplot as plt
# setting params
params = {'legend.fontsize': 'x-large',
'figure.f... | StarcoderdataPython |
3326617 | <filename>src/qts/_tests/qt/test_widgets.py
from qts import QtCore
from qts import QtWidgets
def test_widget_present() -> None:
assert issubclass(QtWidgets.QWidget, QtCore.QObject)
| StarcoderdataPython |
1757081 | import os
def preproc(sheet_list, CWD):
"""
Предобработка таблицы данных
"""
# Чёткое очерчивание границ таблицы:
col_num = 0
while col_num < len( sheet_list[0] ):
if sheet_list[0][col_num].strip() == "":
for row_num in range( len( sheet_list ) ):
del sh... | StarcoderdataPython |
3277744 | # Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may... | StarcoderdataPython |
3288084 | # -*- coding: utf-8 -*-
"""
Created on Sat Nov 18 12:27:16 2017
@author: <NAME>
This script reads sgf files from a file directory, converts them into pairs of "current board - next move" and stores
them either in a dictionary or in a sqlite3 database.
"""
import os
from collections import defaultdict
from Board impo... | StarcoderdataPython |
3396409 | import os
import re
import copy
from typing import List, Dict
from collections import OrderedDict
from logging import Logger
from jinja2 import BaseLoader
from jinja2 import Environment, meta
from jinja2 import TemplatesNotFound
from mailmerge.apps.dto.source import ColHeader, RowSet
from mailmerge.domain.models.merged... | StarcoderdataPython |
57134 | """App utilites tests.
"""
import sys
import pytest
from django.apps import apps
from ..models import Camera
pytestmark = pytest.mark.django_db
@pytest.mark.parametrize(
"testargs, output",
[
[["python", "manage.py", "runserver"], 4],
[["python", "manage.py", "makemigration"], 0],
[... | StarcoderdataPython |
1696469 | <filename>custom/ilsgateway/slab/forms.py
from __future__ import absolute_import
from __future__ import unicode_literals
from django import forms
from corehq.apps.users.forms import MultipleSelectionForm
from crispy_forms.helper import FormHelper
from crispy_forms import layout as crispy
from corehq.apps.hqwebapp impo... | StarcoderdataPython |
198293 | # This code is provoded by MDS DSCI 531/532
def mds_special():
font = "Arial"
axisColor = "#000000"
gridColor = "#DEDDDD"
return {
"config": {
"title": {
"fontSize": 24,
"font": font,
"anchor": "star... | StarcoderdataPython |
189068 | <filename>curso/PY2/for/ex7.py
###exercicio 52
n = int(input('digite um numero: '))
if n == 2 or n == 3 or n == 5:
print ('{} é um numero primo'.format(n))
elif n%2 == 0 or n%3 == 0 or n%5 == 0:
print ('{} não é um numero primo'.format(n))
else:
print ('{} é um numero primo'.format(n))
print ('F... | StarcoderdataPython |
1672057 | import os
import sys
import pytest
from tests.lib.path import Path
COMPLETION_FOR_SUPPORTED_SHELLS_TESTS = (
('bash', """\
_pip_completion()
{
COMPREPLY=( $( COMP_WORDS="${COMP_WORDS[*]}" \\
COMP_CWORD=$COMP_CWORD \\
PIP_AUTO_COMPLETE=1 $1 2>/dev/null ) )
}
complete -o d... | StarcoderdataPython |
1676494 | # Chapter05-04
# 파이썬 심화
# 데코레이터
# 장점
# 1. 중복 제거, 코드 간결, 공통 함수 작성
# 2. 로깅, 프레임워크, 유효성 체크..... -> 공통 기능
# 3. 조합해서 사용 용이
# 단점
# 1. 가독성 감소?
# 2. 특정 기능에 한정된 함수는 -> 단일 함수로 작성하는 것이 유리
# 3. 디버깅 불편
# 데코레이터 실습
import time
def perf_clock(func):
def perf_clocked(*args):
# 함수 시작 시간
st =... | StarcoderdataPython |
113898 | # coding=utf-8
"""
All commands that create & use the local copies of the Google Calendar data.
"""
from __future__ import absolute_import, print_function
import requests
from icalendar import Calendar
from ..config import config, ICAL_PATH
from ..utils import nice_format
from .parser import subparsers
import six
f... | StarcoderdataPython |
71065 | # -*- coding: utf-8 -*-
"""
This script is used to validate that my implementation of DBSCAN produces
the same results as the implementation found in scikit-learn.
It's based on the scikit-learn example code, here:
http://scikit-learn.org/stable/auto_examples/cluster/plot_dbscan.html
@author: <NAME>
"""
from sk... | StarcoderdataPython |
152871 | from torchvision import datasets, transforms
import torch
from torch.utils.data.sampler import SubsetRandomSampler
import numpy as np
def load_train_data(dataset_name, batch_size, val_split=0.9, dataset_seed=0, resolution=32):
if dataset_name.lower() == "mnist":
dataset = datasets.MNIST('./data/mnist', tr... | StarcoderdataPython |
1666097 | # -*- coding: utf-8 -*-
"""
:mod:`sorting` module : sorting functions module for experience assignment
:author: `Dpt Informatique - FST - Univ. Lille <http://portail.fil.univ-lille1.fr>`
:date: 2018, january
"""
import copy
import numpy
def merge (t1,t2, cmp):
"""
Given two sorted array, creates a fresh so... | StarcoderdataPython |
6810 | """
These modules contain sub-modules related to defining various profiles in a model
""" | StarcoderdataPython |
12578 | import numpy as np
import cv2
import os
import math
os.system("fswebcam -r 507x456 --no-banner image11.jpg")
def showImage(capImg):
cv2.imshow('img', capImg)
cv2.waitKey(0)
cv2.destroyAllWindows()
img = cv2.imread('image11.jpg',-1)
height, width, channel = img.shape
topy= height
topx = width
hsv = cv2.cv... | StarcoderdataPython |
68066 | # Copyright 2019 The FastEstimator 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
#
# Unless required by appl... | StarcoderdataPython |
1601574 | #!/usr/bin/env python3
import os
import re
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec
import numpy as np
import pandas as pd
import seaborn as sns
from itertools import cycle
from scipy.cluster.hierarchy import dendrogram, linkage
# Adjust matplotlib backend for snakemake/cluster
try:
... | StarcoderdataPython |
1741150 | <reponame>kataev/flake8-rst<filename>tests/result_py2/result_13.py<gh_stars>10-100
('test_precisely',
[('F821', 5, 10, "undefined name 'LdaModel'", u'>>> lda = LdaModel(corpus=mm, id2word=id2word,\n'),
('F821', 5, 26, "undefined name 'mm'", u'>>> lda = LdaModel(corpus=mm, id2word=id2word,\n'),
('F821', 5, 38, "und... | StarcoderdataPython |
153109 | <filename>glemmazon/__init__.py
# -*- encoding: utf-8 -*-
"""Init module for glemmazon."""
__all__ = ['Analyzer', 'Inflector', 'Lemmatizer']
__version__ = '0.4'
__author__ = '<NAME>'
__date__ = '2020-06-01'
from glemmazon.pipeline import Analyzer, Inflector, Lemmatizer
| StarcoderdataPython |
3259366 | <reponame>zawad2221/online-doctor-server<filename>online_doctor/visiting_schedule/migrations/0004_auto_20210604_2027.py
# Generated by Django 3.1.6 on 2021-06-04 20:27
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('visiting_schedule', '0003_visitingsch... | StarcoderdataPython |
1701131 | <gh_stars>0
age = int(input("How old are you?"))
# if age >= 16 and age <= 65:
if 16<= age <= 65:
print("Have a good day at work")
else:
print("Enjoy your free time")
# to print a line
print("-" * 80)
if age < 16 or age > 65 :
print("Enjoy your free time")
| StarcoderdataPython |
1692880 | <filename>cfnet/data.py
import os
import random
import h5py
import numpy as np
import math
from PIL import Image
from scipy import ndimage
from scipy.stats import truncnorm
def stretch_images(images, min_values, max_values):
perc = np.percentile(images, [0.1, 99.9], axis=[0, 1])
min_values = perc[0, :]
ma... | StarcoderdataPython |
3326337 | <gh_stars>10-100
import matplotlib.pyplot as plt
import numpy as np
import sys
import time
datafile = sys.argv[1]
fftsize = int(sys.argv[2]) #
samp_rate = float(sys.argv[3]) # MSamples/s, i.e. bandwidth is half in MHz.
cfreq = float(sys.argv[4])
outfile = sys.argv[5]
def stack_FFT_file(infile):
# Load FFT segme... | StarcoderdataPython |
3290927 | <gh_stars>0
#-*- coding:utf-8
#### compile the py files to EXE (standalone EXE ,include the ordinary stdlibs ),for ironpyton 。
from __future__ import print_function
import clr
import System
import System.IO
def getFullNames(dllname):
libpaths= ".\\;"+System.Environment.GetEnvironmentVariable("path") +";"+System.Env... | StarcoderdataPython |
1700800 | # ##
# <NAME>, 11 janvier 2016
# This file is part of MLDB. Copyright 2016 mldb.ai inc. All rights reserved.
# ##
import unittest
import random
import datetime
from mldb import mldb, ResponseException
class SampledDatasetTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
# Create toy datase... | StarcoderdataPython |
3330860 | <gh_stars>0
# Load important libraries
import pandas as pd
import streamlit as st
import os
from pages import utils
def app():
"""This application is created to help the user change the metadata for the uploaded file.
They can perform merges. Change column names and so on.
"""
# Load the uploaded ... | StarcoderdataPython |
3351452 | from .BioequivalenceApp import BioequivalenceApp
from .StatisticsApp import StatisticsApp
from .StartingApp import StartingApp
from .PredictionApp import PredictionApp
| StarcoderdataPython |
3338046 | import requests
from bs4 import BeautifulSoup
def fetchurl(url):
res = requests.get(url)
if res.status_code == 200:
return res.text
else:
return False
def parsedoc(html_doc):
s=BeautifulSoup(html_doc,"html.parser")
return s.select('a[href^="http://www.mobmp4.org/Mp4-Videos"]')
... | StarcoderdataPython |
3398427 | <filename>app/utils/avscanlib.py
import os
import sys
import subprocess
import configparser
import logging
import re
import shlex
logging.getLogger(__name__).addHandler(logging.NullHandler())
try:
import pyclamd
except ImportError as ie:
logging.error(ie.message)
def popen(*args, **kwargs):
defaults = {... | StarcoderdataPython |
1794515 | <filename>online_app/gunicorn.conf.py
workers = 1
timeout = 120
bind = ":5000"
| StarcoderdataPython |
1766258 | # This file contains model for ethereum price prediction
| StarcoderdataPython |
114477 | <reponame>expressionsofchange/nerf0<gh_stars>1-10
"""
The structure described in the present file is the result of the very first phase of static analysis of an s-expression.
Staying true to the nature of this project, this analysis is done in terms of expressions of change on a given
s-expression. For simplicity's sa... | StarcoderdataPython |
67676 | # 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
# d... | StarcoderdataPython |
4808439 | ###
# File that configures everything. Set macros here
###
# Database
DATABASE_NAME = 'OrienTinder'
DATABASE_URI = 'mongodb://127.0.0.1:27017/' + DATABASE_NAME
# Flask app
CSRF_SECRET_KEY = '<KEY>'
# Views
LOGIN_VIEW = 'login'
# Models settings
MAX_NICKNAME_LENGTH = 20
MAX_FULLNAME_LENGTH = 50
MAX_LABORATORY_LENGTH... | StarcoderdataPython |
1750882 | import torch
from mmcv.runner import force_fp32
from torch import nn as nn
from typing import List
from .furthest_point_sample import (furthest_point_sample,
furthest_point_sample_with_dist)
from .utils import calc_square_dist
def get_sampler_type(sampler_type):
"""Get the typ... | StarcoderdataPython |
196801 | # emacs: -*- mode: python-mode; py-indent-offset: 4; tab-width: 4; indent-tabs-mode: nil -*-
# -*- coding: utf-8 -*-
# ex: set sts=4 ts=4 sw=4 noet:
# ## ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ### ##
#
# See COPYING file distributed along with the datalad package for the
# copyright and... | StarcoderdataPython |
3301840 | from os import path
import pandas as pd
from django.core.management import BaseCommand
from pension.models import Fund, Quarter
managing_body_dict = {
'amitim': 'AMT',
'as': 'AS',
'clal': 'CLL',
'ds': 'MTD',
'yl': 'YL',
'fnx': 'FNX',
'fenix': 'FNX',
'harel': 'HRL',
'menoramivt': '... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.