id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
198844 | '''
sc_studio.main
Author: <NAME>
Copyright (c) 2014-2015 HKUST SmartCar Team
Refer to LICENSE for details
'''
import getopt
import logging
import sys
from sc_studio import config
def _print_usage():
print("Usage: main.py -d <device> [commands...]")
def _start_master(view_args : dict):
module = __import__("master... | StarcoderdataPython |
3413266 | def dummy_func(a, b, c, d=None, e=None):
return a
| StarcoderdataPython |
6446839 |
'''
IP Address Location & Geolocation API
(c) ipapi by Kloudend, Inc. | https://ipapi.co/
API Docs : https://ipapi.co/api/
'''
from requests import get
try:
from .exceptions import RateLimited, PageNotFound, AuthorizationFailed
except (SystemError, ImportError):
from exceptions import RateLimited, Pa... | StarcoderdataPython |
35573 | import numpy as np
class BoundBox:
"""
Adopted from https://github.com/thtrieu/darkflow/blob/master/darkflow/utils/box.py
"""
def __init__(self, obj_prob, probs=None, box_coord=[float() for i in range(4)]):
self.x, self.y = float(box_coord[0]), float(box_coord[1])
self.w, self.h =... | StarcoderdataPython |
311778 | from __future__ import annotations
import operator
from io import BytesIO
from itertools import chain
from pathlib import Path
from typing import Dict, Any, Final, Iterable, Tuple, AbstractSet, IO, Optional, TYPE_CHECKING, Mapping, Union, ClassVar
from uuid import uuid4
import attr
import toolz
from immutables import... | StarcoderdataPython |
1671642 | <reponame>VargaIonut23/companie-aeriana
from Domain.rezervare import getcheckin, getpret, getclasa, getnume, getId, creeazarezervare
def testRezervare():
rezervare = creeazarezervare('213#' , 'Ionut' , 'economy' , 317.78 , 'da')
assert getId(rezervare) == '213#'
assert getnume(rezervare) == 'Ionut'
as... | StarcoderdataPython |
12833851 | from typing import List
from apistar import http
from models import PostModel
from types_ import PostType # because types is part of the standard library
def create_post(post: PostType) -> http.JSONResponse:
instance = PostModel(**post)
instance.save()
return http.JSONResponse(PostType(instance), stat... | StarcoderdataPython |
8033613 | # ------------------------------------------------------------------ #
# ╦═╗╔═╗╔╦╗╔═╗╔═╗╔═╗
# ╠╦╝║ ║║║║╚═╗║ ║║
# ╩╚═╚═╝╩ ╩╚═╝╚═╝╚═╝
# Reduced Order Modelling, Simulation, Optimization of Coupled Systems
# 2017-2021
#... | StarcoderdataPython |
6471582 |
# Найдите максимум трех чисел с помощью функции
def max_of_four(number1,number2,number3,number4):
max1 = max(number1,number2)
max2 = max(number3,number4,number3)
max3 = (max1,max2)
print(max3)
max_of_four(10,20,40,50)
| StarcoderdataPython |
8123090 | <gh_stars>0
"""A module for testing Protein Substitution tokenization."""
import unittest
from variation.tokenizers.caches import AminoAcidCache
from variation.tokenizers import ProteinSubstitution
from .tokenizer_base import TokenizerBase
class TestProteinSubstitutionTokenizer(TokenizerBase, unittest.TestCase):
... | StarcoderdataPython |
8018954 | import argparse
import matplotlib
matplotlib.use("TkAgg")
from botocore.exceptions import ClientError
from graph_canvas import MaskGraphCanvas
from scenario_model import *
from description_dialog import *
from group_filter import groupOpLoader, GroupFilterLoader
from software_loader import getProjectProperties,getSem... | StarcoderdataPython |
5096560 | <filename>script-src/show-emulator-info.py
#!/usr/bin/env python3
# Configuration Summary
# TODO 1.Show that this core is rocket
import json
import math
import sys
def convert_size(size_bytes, types='B', base=1024):
if size_bytes == 0:
return '0' + types
size_name = ['', 'K', 'M', 'G', 'T', 'P', 'E... | StarcoderdataPython |
1876200 | <filename>application/core/generators/wordsearch_easy.py
import string
import random
from core.utils import Generator
class WordSearch:
HORIZONTAL = 0
VERTICAL = 1
DIAGONAL = 2
REVHORIZONTAL = 3
REVVERTICAL = 4
REVDIAGONAL = 5
REVFLIPDIAGONA = 6
FLIPDIAGONAL = 7
DONTCARE = -100
... | StarcoderdataPython |
5091161 | <filename>scripts/api/library_upload_from_import_dir.py
#!/usr/bin/env python
"""
Example usage:
./library_upload_from_import_dir.py <key> http://127.0.0.1:8080/api/libraries/dda47097d9189f15/contents Fdda47097d9189f15 auto /Users/EnisAfgan/projects/pprojects/galaxy/lib_upload_dir ?
"""
from __future__ import print_fun... | StarcoderdataPython |
9764096 | from typing import List
class Solution:
def makePattern(self, word):
mapping = {}
pattern = []
for char in word:
pattern.append(mapping.setdefault(char, len(mapping)))
return pattern
def findAndReplacePatternSmart(self, words: List[str], pattern: str) -> List[str]... | StarcoderdataPython |
6492585 | <gh_stars>0
import os
from vcsrepository import VcsRepository
class Local:
storage_path = ''
def __init__(self, storage_path):
"""Creates Local service instance.
:param str tmp_path: Path to store local repositories
"""
self.storage_path = storage_path.rstrip('/') + '/'
... | StarcoderdataPython |
9630934 | import sys
import os
import numpy as np
import copy as cp
import matplotlib.pyplot as plt
sys.path.insert(0, os.path.abspath(".."))
from analysis import bundlelib
# patteRNA_process_motif_bundle_average_short.py
"""The following script produces useful plots when assessing the scores of multiple motifs (bundles)
agai... | StarcoderdataPython |
5176006 | # -*- coding: utf-8 -*-
"""
@file areal.py
@author <NAME>
@date 2011-03-16
@version $Id: areal.py 15370 2014-01-10 08:50:57Z bieker $
Python implementation of the TraCI interface.
SUMO, Simulation of Urban MObility; see http://sumo-sim.org/
Copyright (C) 2011-2013 DLR (http://www.dlr.de/) and contributors
Thi... | StarcoderdataPython |
257896 | <gh_stars>10-100
# -*- coding: utf-8 -*-
"""
Test XForm XML syntax.
"""
import re
from unittest import TestCase
from xml.dom.minidom import getDOMImplementation
from pyxform import create_survey_from_xls
from pyxform.utils import node
from tests.utils import path_to_text_fixture
from tests.xform_test_case.base import ... | StarcoderdataPython |
3263396 | <reponame>Taffer/skelly
''' Skelly settings object
By <NAME> (https://github.com/Taffer)
MIT license, see LICENSE.md for details.
'''
import json
import os
class GameSettings:
def __init__(self, filename: str, defaults: dict) -> None:
''' Create a GameSettings from the given .ini file.
Defaults... | StarcoderdataPython |
3434369 | from django.test import TestCase
from django.contrib.auth import get_user_model
from core import models
def sample_user(email='<EMAIL>', password='<PASSWORD>'):
''' Cria um usuário e o retorna '''
return get_user_model().objects.create_user(email=email, password=password)
class ModelTests(TestCase):
de... | StarcoderdataPython |
1911186 | # coding: utf-8
from __future__ import absolute_import
# import models into model package
from .body1 import Body1
from .body2 import Body2
from .body3 import Body3
from .body4 import Body4
from .body5 import Body5
from .body6 import Body6
from .body7 import Body7
| StarcoderdataPython |
6419874 | from unittest.mock import patch
from flask.testing import FlaskClient
from flask import json, request
import pytest
from app.test.fixtures import client, app # noqa
from app.api_response import ApiResponse
from .controller import EntityResource
from .service import EntityService
from .model import Entity
from . impor... | StarcoderdataPython |
1673597 | # -*- coding: utf-8 -*-
"""
These utilities are designed for incorporation into tests
"""
# stdlib
import os
import codecs
import json
import operator
# package
import ashes
# ==============================================================================
# we'll store a global value in here
ChertDefaults = None
S... | StarcoderdataPython |
6611898 | from output.models.nist_data.atomic.id.schema_instance.nistschema_sv_iv_atomic_id_max_length_5_xsd.nistschema_sv_iv_atomic_id_max_length_5 import (
NistschemaSvIvAtomicIdMaxLength5,
Out,
)
__all__ = [
"NistschemaSvIvAtomicIdMaxLength5",
"Out",
]
| StarcoderdataPython |
112067 | #----------------------------------------------------------------------
# Name: wx.lib.dialogs
# Purpose: ScrolledMessageDialog, MultipleChoiceDialog and
# function wrappers for the common dialogs by <NAME>.
#
# Author: Various
#
# Created: 3-January-2002
# RCS-ID: $Id: dialogs.py ... | StarcoderdataPython |
3495961 | import os
from yacs.config import CfgNode as CN
# -----------------------------------------------------------------------------
# Config definition
# -----------------------------------------------------------------------------
_C = CN()
_C.MODEL = CN()
_C.MODEL.SMOKE_ON = True
_C.MODEL.DEVICE = "cuda"
_C.MODEL.WEIGH... | StarcoderdataPython |
4838109 |
import pandas as pd
#
from .. import global_var
def compute_maturity(dt = None,
frequency = None,
delivery_begin_date = None,
commodity = None,
):
"""
Computes the maturity for a... | StarcoderdataPython |
357984 | <filename>code/abc061_b_01.py
n,m=map(int,input().split())
l=" ".join([input() for _ in [0]*m])
for i in range(1,n+1):print(l.split().count(str(i))) | StarcoderdataPython |
6413942 | """
Plot results of one or multiple scenario runner evaluations
"""
import argparse
import os
import re
import statistics
import sys
import xml.etree.cElementTree as ET
import matplotlib.pyplot as plt
import numpy as np
class ScenarioResult:
"""
Collection of multiple results for the same scenario
"""
... | StarcoderdataPython |
11249680 | from collections import MutableMapping
class RedisDict(MutableMapping):
def __init__(self, redis_conn, key_prefix = '', exp_time = 0, sliding_expiry = False):
'''
Provides a dictionary interface to a Redis k-v store.
>>> from shitty_tools.key_value.redis import RedisDict
>>> from ... | StarcoderdataPython |
1791212 | <reponame>sgheb/kaiko-api
"""
Kaiko API Wrapper
"""
import logging
from os import environ
import pandas as pd
import kaiko.utils as ut
try:
from cStringIO import StringIO # Python 2
except ImportError:
from io import StringIO
# Base URLs
_BASE_URL_KAIKO_US = 'https://us.market-api.kaiko.io/'
_BASE_URL_... | StarcoderdataPython |
6435949 | from datetime import datetime
import os
import time
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.tensorboard import SummaryWriter
import numpy as np
from rslgym.algorithm.storage.rollout import RolloutStorage
class TRPO:
def __init__(self,
actor,
... | StarcoderdataPython |
1837913 | from directory_api_client.client import api_client
from directory_components.mixins import CountryDisplayMixin, GA360Mixin
from django.template.response import TemplateResponse
from django.views.generic.edit import FormView
from notifications import forms
class AnonymousUnsubscribeView(CountryDisplayMixin, GA360Mix... | StarcoderdataPython |
4800679 | from builtins import object
import numpy as np
import sporco.cnvrep as cr
from sporco.admm import ccmod
from sporco.linalg import rrs
from sporco.fft import fftconv
class TestSet01(object):
def setup_method(self, method):
np.random.seed(12345)
N = 32
M = 4
Nd = 5
self.D... | StarcoderdataPython |
4973132 | # -*- coding: utf-8 -*-
"""
Created on Wed Feb 22 14:19:43 2017
@author: Chris
"""
from simsearch import SimSearch
from keysearch import KeySearch
from gensim.models import TfidfModel, LsiModel
from gensim.corpora import Dictionary, MmCorpus
from gensim.similarities import MatrixSimilarity
from gensim import utils
... | StarcoderdataPython |
9745705 | #!/usr/bin/env python3
import isce
import isceobj
import argparse
import os
import shelve
import logging
def createParser():
parser = argparse.ArgumentParser( description='Duplicating the master SLC')
parser.add_argument('-i', '--input_slc', dest='input_slc', type=str, required=True,
help = 'Dire... | StarcoderdataPython |
4834262 | <gh_stars>0
#palindrome integer
def isPalindrome(n):
y = n
if n <= 0 :
return False
elif n > 0 :
rev = 0
while n != 0 :
x = rev + n % 10
n = n//10
if n > 0:
rev = x *10
... | StarcoderdataPython |
3267953 | <reponame>jcsantamaria/skid_robot
#!/usr/bin/env python
from drivetrain import DriveTrain
#import board as _
#print(_.__file__)
train = DriveTrain(4, 6, 5, 10, 12, 11, 9, 7, 8, 15, 14, 13)
train.FrontLeft.stop()
train.FrontRight.stop()
train.RearLeft.stop()
train.RearRight.stop()
| StarcoderdataPython |
12855739 | <gh_stars>0
import sys,os
import argparse
from util.MongoUtil import MongoUtil
from util.Generator import Generator
#Custom help messages
def help_msg(name=None):
return '''main.py [-h] [--length LENGTH] [--search SEARCHFIELD SEARCHTEXT]
'''
def search_usage():
return'''python main.py --search webs... | StarcoderdataPython |
360793 | <filename>register/models.py
from django.db import models
# Create your models here.
class UserModel(models.Model):
email = models.EmailField('邮箱')
password = models.CharField('密码', max_length=256)
name = models.CharField('姓名', max_length=25)
age = models.IntegerField('年龄')
birthday = models.DateField('生日')
| StarcoderdataPython |
3522213 | from __future__ import absolute_import
from django.db import models
from django.utils.translation import ugettext_lazy as _
from documents.models import Document, DocumentType
from .managers import MetadataSetManager, MetadataTypeManager
class MetadataType(models.Model):
"""
Define a type of metadata
"... | StarcoderdataPython |
1663778 | from bxutils.logging.log_level import LogLevel
from bxcommon import constants
from bxcommon.messages.bloxroute.abstract_bloxroute_message import AbstractBloxrouteMessage
from bxgateway.messages.gateway.gateway_message_type import GatewayMessageType
class BlockPropagationRequestMessage(AbstractBloxrouteMessage):
... | StarcoderdataPython |
120109 | import sys
from webob import Request
from pydap.responses.error import ErrorResponse
from pydap.lib import __version__
import unittest
class TestErrorResponse(unittest.TestCase):
def setUp(self):
# create an exception that would happen in runtime
try:
1/0
except Exception:
... | StarcoderdataPython |
5132848 | """Routes for user authentication."""
from flask import redirect, render_template, flash, Blueprint, request, url_for, session, jsonify
from flask_login import current_user, login_user
from ..forms import LoginForm, SignupForm, ReSentEmailConfirmationForm, PasswordResetFirstStepForm, PasswordResetSecondStepForm
from ..... | StarcoderdataPython |
1774700 | <gh_stars>1-10
import numpy
import matplotlib.pyplot as plt
from sklearn.metrics import r2_score
x = [1, 2, 3, 5, 6, 7, 8, 9, 10, 12, 13, 14, 15, 16, 18, 19, 21, 22]
y = [100, 90, 80, 60, 60, 55, 60, 65, 70, 70, 75, 76, 78, 79, 90, 99, 99, 100]
mymodel = numpy.poly1d(numpy.polyfit(x, y, 3))
myline = numpy.linspace(... | StarcoderdataPython |
5142401 | # CONFIG FILE #
SECRET_KEY = '<KEY>'
SQLALCHEMY_DATABASE_URI = 'sqlite:///site.db'
INT_USER = "INT_ADMIN"
INT_PASS = "<PASSWORD>"
SELF_REF = "http://127.0.0.1:5000"
DEBUG = False
| StarcoderdataPython |
225248 | import multiprocessing
import os
bind = "0.0.0.0:8000"
workers = os.environ.get('GUNICORN_WORKER_COUNT', multiprocessing.cpu_count() + 1)
threads = workers
user = 'django'
group = 'django'
worker_class = 'sync'
max_requests = 1000
max_requests_jitter = 100
| StarcoderdataPython |
11351981 | order_total = 247 #GBP
if order_total > 100:
discount = 25
else:
discount = 0
print(order_total, discount)
discount = 25 if order_total > 100 else 0
print(order_total, discount)
| StarcoderdataPython |
1906394 | # Copyright 2021 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at http://aws.amazon.com/apache2.0/
# or in the "LICENSE.txt" file accompanyin... | StarcoderdataPython |
4996662 | <gh_stars>100-1000
import time
class Reader:
wait = 0.2
timeout = 2.0
bufsize = (8 << 10)
def __init__(self, fd, data_type=None, eof=False):
self.fd = fd
self.data_type = data_type if (data_type is not None) else lambda x: x
self.eof = eof
self.total = 0
def __it... | StarcoderdataPython |
9779618 | <filename>carberretta/db/db.py
import os
from aiofiles import open
from aiosqlite import connect
from apscheduler.triggers.cron import CronTrigger
class Database:
def __init__(self, bot):
self.bot = bot
self.path = f"{bot._dynamic}/database.db3"
self.build_path = f"{bot._static}/build.sql... | StarcoderdataPython |
1824363 | #
# Copyright (c) 2021 Wind River Systems, Inc.
#
# SPDX-License-Identifier: Apache-2.0
#
from eventlet import greenthread
import eventlet
import greenlet
from oslo_config import cfg
from oslo_log import log
from oslo_service import periodic_task
from sysinv.cert_alarm import fm as fm_mgr
from sysinv.cert_alarm impor... | StarcoderdataPython |
5029593 | <reponame>DonAurelio/TweetAnalyzer
import os
from nltk.tree import Tree
from nltk.draw.tree import TreeView
from tkmorfo.settings import STATICFILES_DIRS
# References
# http://stackoverflow.com/questions/23429117/saving-nltk-drawn-parse-tree-to-image-file
# http://www.nltk.org/_modules/nltk/tree.html
# http://www.nlt... | StarcoderdataPython |
1973129 | import random
import os
import sys
import pdb
import numpy as np
import pandas as pd
from collections import Counter, defaultdict
from pprint import pprint
# acetate scaling constant
spectrum_peak_unit_quantification = 4.886210426653892e-06 / (69.6/0.0029)
# calculate distribution of class labels in a ... | StarcoderdataPython |
6471235 | # -*- coding: utf-8 -*-
"""
The nlp_model_explorer package contains the functions that are used to retreive neighbours from NLP models.
The language model needs to be in .vec or .bin format.
Works with FastText and word2vec.
Like the other packages, it outputs a :obj:`Graph` containing the results.
.. note::
No... | StarcoderdataPython |
6480745 | <reponame>yger/neuropixels-data-sep-2020
from .cortexlab_utils import cortexlab_create_recording_object
from .create_subrecording_object import create_subrecording_object
from .prepare_cortexlab_datasets import prepare_cortexlab_datasets
from .prepare_cortexlab_drift_datasets import prepare_cortexlab_drift_datasets
fro... | StarcoderdataPython |
1645640 | import json
import pytest
from botocore.exceptions import ClientError
from app.callback.sqs_client import SQSClient
from botocore.stub import Stubber
@pytest.fixture(scope='function')
def sqs_client(notify_api, mocker):
with notify_api.app_context():
sqs_client = SQSClient()
statsd_client = moc... | StarcoderdataPython |
166925 | #!/usr/bin/env python3
from setuptools import setup, find_packages
setup(
name='armagetron.py',
version='0.0.1',
description='a scripting library for Armagetron Advanced',
license='MIT',
url='https://github.com/fkmclane/armagetron.py',
author='<NAME>',
author_email='<EMAIL>',
packages=... | StarcoderdataPython |
59955 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('bugs', '0013_auto_20151123_1415'),
]
operations = [
migrations.RenameField(
model_name='bug',
old_na... | StarcoderdataPython |
1825354 | <reponame>nossas/bonde-zendesk
#!/usr/bin/env python
# coding: utf-8
from logger import log
from decorators import decode_jwt
from runners import (
Organization, MSRRunner, PsicologaRunner, AdvogadaRunner
)
from serializers import FormEntrySchema
@decode_jwt(serializer_class=FormEntrySchema)
def send_form_entry_t... | StarcoderdataPython |
8031723 | import logging
class LogGen:
@staticmethod
def loggen():
# filemode a or w a = son kalınan yerden tutmaya başlar, w = baştan yazmaya başlar
logging.basicConfig(filename=".\\Logs\\automation.log",
format="%(asctime)s:%(levelname)s:%(message)s",
... | StarcoderdataPython |
3358619 | """Adding parent duns number and name to (Published)AwardFinancialAssistance
Revision ID: 1fabe0bdd48c
Revises: 6973101b6853
Create Date: 2018-03-27 15:07:45.721751
"""
# revision identifiers, used by Alembic.
revision = '1fabe0bdd48c'
down_revision = '6973101b6853'
branch_labels = None
depends_on = None
from alemb... | StarcoderdataPython |
3350909 | <gh_stars>0
# -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2018-04-13 02:18
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('opportunities', '0001_initial'),
]
operations = [
migrations.RenameMode... | StarcoderdataPython |
1704866 | <reponame>lllucius/pysmapi<filename>pysmapi/interfaces/System_Spool_Utilization_Query.py
# Copyright 2018-2019 <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... | StarcoderdataPython |
6448405 | <gh_stars>1-10
"""
module for testing functionality of serializable list field
"""
# lib
import pytest
import marshmallow
# src
import objectfactory
from objectfactory import Serializable, List, String, Integer, register
class TestPrimitiveList( object ):
"""
test case for serialization of basic lists of pr... | StarcoderdataPython |
4891822 | <gh_stars>1-10
import re
import sys
try:
from itertools import tee, filterfalse
except ImportError:
# Accommodate prior name for filterfalse in Python 2
from itertools import tee, ifilterfalse as filterfalse
_PY2 = sys.version_info[0] == 2
if not _PY2:
basestring = str
# regex to find Python commen... | StarcoderdataPython |
9693426 | <filename>encoding/utils/misc.py
import warnings
__all__ = ['AverageMeter', 'EncodingDeprecationWarning']
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
self.reset()
def reset(self):
#self.val = 0
self.sum = 0
self.... | StarcoderdataPython |
4954080 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.6 on 2016-05-12 08:41
from __future__ import unicode_literals
import autoslug.fields
from django.db import migrations, models
import django.utils.timezone
import model_utils.fields
class Migration(migrations.Migration):
initial = True
dependencies = [
]... | StarcoderdataPython |
1679344 | import re
CLEAN_RE = re.compile(r'[^a-z0-9äöüßø]')
WHITESPACE_RE = re.compile(r'\s+')
ESCAPE_TABLE = [
('ä', 'ae'),
('ö', 'oe'),
('ü', 'ue'),
('ø', 'oe'),
('ß', 'ss'),
]
def slugify(string):
string = string.lower()
string = CLEAN_RE.sub(' ', string)
string = string.strip()
string... | StarcoderdataPython |
385182 | <reponame>Aevox121/KSbot
from nonebot import on_command,on_message,on_keyword
from nonebot.rule import to_me
from nonebot.typing import T_State
from nonebot.adapters import Bot, Event, Message
import random
weather = on_command("天气",rule=to_me(), priority=5)
@weather.handle()
async def handle_first_receive(bot: Bot,... | StarcoderdataPython |
1862015 | from __future__ import absolute_import
#
# This is an extension to the Nautilus file manager to allow better
# integration with the Subversion source control system.
#
# Copyright (C) 2006-2008 by <NAME> <<EMAIL>>
# Copyright (C) 2007-2008 by <NAME> <<EMAIL>>
# Copyright (C) 2008-2010 by <NAME> <<EMAIL>>
#
# RabbitV... | StarcoderdataPython |
1789659 | <gh_stars>1-10
from django.contrib.auth import get_user_model
from django.conf import settings
import cv2
import os
from config import celery_app
from gallery.users.models import Gallery
User = get_user_model()
@celery_app.task()
def get_users_count():
"""A pointless Celery task to demonstrate usage."""
ret... | StarcoderdataPython |
3544060 | # Copyright (c) Meta Platforms, Inc. and affiliates.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import logging
import os
from typing import Dict, Optional, Any, Union
import torch
import torch.distributed as dist
from pytorch_li... | StarcoderdataPython |
6462317 | <reponame>Waino/refpapers
from refpapers.view import print_list
def test_print_list_empty():
# neither should raise an exception
print_list([])
print_list([], grouped='tags')
| StarcoderdataPython |
5065638 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# WebCam Setting
#
# created by <NAME>
import cv2
class Camera:
"""WEBカメラの設定
"""
def __init__(self, use_last=True, camera_num=0,
image_width=1280, image_height=720, fps=30):
self.img_path = "./images/"
self.camera_num = cam... | StarcoderdataPython |
8047919 | <reponame>k01ek/netbox-devicetype-importer
# Generated by Django 3.2.9 on 2021-11-23 12:32
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='MetaDeviceType',
... | StarcoderdataPython |
179574 | #!/usr/bin/env python
# -*- encoding: utf-8 -*-
from unittest import TestCase
from pygithub3.resources.issues import Label
class TestLabel(TestCase):
def test_is_valid_color(self):
valid_colors = ['BADa55', 'FF42FF', '45DFCA']
for color in valid_colors:
self.assertTrue(Label.is_valid... | StarcoderdataPython |
1845410 | <filename>test/test_compressor.py
import os
import compressor as c
import unittest
import Utils
BASE_PATH = os.getcwd()
folder_to_zip = ".eu/"
destination_path = BASE_PATH + "/kulwant.zip"
class Internal_Methods(unittest.TestCase):
# def testing_compression_of_files_in_folder(self):
# files = Utils.get_a... | StarcoderdataPython |
58356 | from django.contrib import messages
from django.contrib.auth.models import Group
from django.core.urlresolvers import reverse, reverse_lazy
from django.http.response import HttpResponseRedirect, Http404
from django.shortcuts import get_object_or_404
from django.utils.translation import ugettext as _
from django.views.g... | StarcoderdataPython |
1879472 | import pandas as pd
from wh_parser.util import convert_freq_to_pd
methods_map = {}
def add_methods(name=''):
"""
注册函数
:param name:
:return:
"""
def wrapper(func):
methods_map[name] = func
return func
return wrapper
@add_methods('default')
def default_process(df, freq):... | StarcoderdataPython |
11221497 | <reponame>napoler/deepke
import torch.nn as nn
from deepke.model import BasicModule
from pytorch_transformers import BertModel
class LM(BasicModule):
def __init__(self, vocab_size, config):
super(LM, self).__init__()
self.model_name = 'LM'
self.lm_name = config.lm.lm_file
self.out_... | StarcoderdataPython |
3323122 | <filename>src/auto-posture-evaluator/testers/codebuild_tester.py
import time
import boto3
import interfaces
class Tester(interfaces.TesterInterface):
def __init__(self) -> None:
self.user_id = boto3.client('sts').get_caller_identity().get('UserId')
self.account_arn = boto3.client('sts').get_caller... | StarcoderdataPython |
4906815 | <reponame>GowthamChowdary/scrapy<filename>tests/CrawlerProcess/twisted_reactor_custom_settings_conflict.py<gh_stars>1-10
import scrapy
from scrapy.crawler import CrawlerProcess
class SelectReactorSpider(scrapy.Spider):
name = 'select_reactor'
custom_settings = {
"TWISTED_REACTOR": "twisted.internet.se... | StarcoderdataPython |
9662652 | <gh_stars>1-10
import discord, datetime, time
import asyncio
import os
import sys
from discord.ext import commands
from discord.ext import tasks
from discord.ext.tasks import loop
from datetime import datetime, timezone
from discord.utils import get
from config import token, CommandPrefix, activitytype, botstatusmessag... | StarcoderdataPython |
6609970 | <gh_stars>0
#!/usr/bin/env python
import os
import sys
sys.path.insert(0, os.pardir)
from testing_harness import TestHarness, PyAPITestHarness
import openmc
class MGTalliesTestHarness(PyAPITestHarness):
def _build_inputs(self):
# Instantiate a tally mesh
mesh = openmc.Mesh(mesh_id=1)
mesh... | StarcoderdataPython |
1954001 | <filename>tools/check_cf_migration.py<gh_stars>10-100
#! /usr/bin/env python
import argparse
import bz2
import json
import os.path
import urllib.request
URL_TEMPLATE = ('https://conda.anaconda.org/{channel}/label/main/'
'{subdir}/repodata.json.bz2')
def repodata_filename(channel, subdir):
fname ... | StarcoderdataPython |
8067739 | <filename>python/cinn/pe.py
from .core_api.pe import *
| StarcoderdataPython |
8182258 | # -*- coding: utf-8 -*-
# FOGLAMP_BEGIN
# See: http://foglamp.readthedocs.io/
# FOGLAMP_END
import pathlib
from pathlib import PosixPath
from unittest.mock import patch, mock_open, Mock, MagicMock
from aiohttp import web
import pytest
from foglamp.services.core import routes
from foglamp.services.core.api import s... | StarcoderdataPython |
143746 | # from hparams import hparams
# from text import text_to_sequence
#
#
# def Sy(text):
# cleaner_names = [x.strip() for x in hparams.cleaners.split(',')]
# seq = text_to_sequence(text, cleaner_names)
# return text
# print(Sy('danh mục đầu tư (so với các mn)'))
| StarcoderdataPython |
6570363 | <reponame>jorgessanchez7/Global_Forecast_Validation
import pandas as pd
df = pd.read_csv('/Users/student/Dropbox/PhD/2020 Winter/Dissertation_v9/South_America/Colombia/Stations_Selected_Colombia.csv')
IDs = df['Codigo'].tolist()
COMIDs = df['COMID'].tolist()
Names = df['Nombre'].tolist()
Rivers = df['Corriente'].toli... | StarcoderdataPython |
9667260 | """
Helper module for Data-Science-Keras repository
"""
import os, warnings
warnings.simplefilter(action="ignore", category=FutureWarning)
from time import time
import random as rn
import math
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
sns.set() # set seaborn style... | StarcoderdataPython |
5041091 | r"""Mean Deviation Similarity Index (MDSI)
This module implements the MDSI in PyTorch.
Credits:
Inspired by the [official implementation](https://www.mathworks.com/matlabcentral/fileexchange/59809-mdsi-ref-dist-combmethod)
References:
[1] Mean Deviation Similarity Index:
Efficient and Reliable Full-Refer... | StarcoderdataPython |
1971417 | <gh_stars>1-10
# -*- coding=utf-8 -*-
from __future__ import absolute_import
from __future__ import print_function
from keras.layers import *
from keras.layers import Reshape, Embedding
from keras.models import Model
from layers.Bias import *
from layers.DynamicMaxPooling1D import *
from layers.Match import *
from lay... | StarcoderdataPython |
4877861 | <reponame>andela/troupon<filename>troupon/tickets/models.py
from django.db import models
from django.contrib.auth.models import User
from deals.models import Advertiser, Deal
class Ticket(models.Model):
"""
Stores all unique codes generated for tickets
"""
user = models.ForeignKey(User)
item = mod... | StarcoderdataPython |
1844464 | <reponame>kneeraazon01/FoodandBeverage<filename>contact/views.py
from django.shortcuts import render, redirect
from .models import Contact
import requests as req
from django.contrib import messages
from django.core.mail import send_mail
from team.models import Team
from django.contrib.auth.decorators import login_requi... | StarcoderdataPython |
1927029 | <filename>infinisdk/infinibox/vm.py
from ..core.system_object import SystemObject
from ..core import Field
class Vm(SystemObject):
FIELDS = [
Field("id", type=int, cached=True, is_identity=True, is_sortable=True, is_filterable=True),
Field("uuid", type=str, cached=True, is_filterable=True, is_sor... | StarcoderdataPython |
3424952 | #
# This script is the property of Appcelerator, Inc. and
# is Confidential and Proprietary. All Rights Reserved.
# Redistribution without expression written permission
# is not allowed.
#
# Titanium application post builder class
#
# Original author: <NAME> 04/02/09
#
#
class PostBuilder(object):
def __init__(self,b... | StarcoderdataPython |
1659407 | <filename>prom/interface/sqlite.py
# -*- coding: utf-8 -*-
"""
Bindings for SQLite
https://docs.python.org/2/library/sqlite3.html
Notes, certain SQLite versions might have a problem with long integers
http://jakegoulding.com/blog/2011/02/06/sqlite-64-bit-integers/
Looking at the docs, it says it will set an integer ... | StarcoderdataPython |
4837740 | <filename>tests/unit/publication/gitlab/test_gitlab_manager.py
from typing import List, Mapping, Sequence
import pytest
from faker import Faker
from overhave.entities import FeatureTypeName
from overhave.publication.gitlab import GitlabVersionPublisher
from overhave.transport import GitlabRepository
from tests.object... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.