id stringlengths 1 7 | text stringlengths 6 1.03M | dataset_id stringclasses 1
value |
|---|---|---|
20004 | import os
import sys
from typing import Iterable
from jinja2 import Environment, FileSystemLoader, Template
import config as cfg
from . import app_root_dir, doc_root_dir, resource_dir, template_dir
_usage = "Usage: generate.py <onprem|aws|gcp|azure|k8s|alibabacloud|oci|programming|saas>"
def load_tmpl(tmpl: str) -... | StarcoderdataPython |
3323330 | <reponame>ZTjack/tesseract.js
'''
@Author: Jack
@Date: 2020-04-02 12:55:27
@LastEditors: Jack
@LastEditTime: 2020-04-02 13:46:23
@Description: 把一张图片从歪的变成正的,方便读取信息 http://developers.goalist.co.jp/entry/2019/02/13/150126
'''
import cv2 # opencv-python
import numpy as np
from skimage.filters import threshold_local # sciki... | StarcoderdataPython |
136983 | # This file is part of Scapy
# See http://www.secdev.org/projects/scapy for more informations
# Copyright (C) <NAME> <<EMAIL>>
# This program is published under a GPLv2 license
"""
Classes related to the EAP protocol.
"""
from __future__ import absolute_import
from __future__ import print_function
import struct
fro... | StarcoderdataPython |
133815 | <filename>firefly/distributed/reference.py<gh_stars>100-1000
#coding:utf8
'''
Created on 2013-8-14
@author: lan (www.9miao.com)
'''
from twisted.spread import pb
from firefly.utils.services import Service
class ProxyReference(pb.Referenceable):
'''代理通道'''
def __init__(self):
'''初始化'''
se... | StarcoderdataPython |
3227947 | #Faça um programa que leia um número inteiro e diga se ele é
# ou não um número primo.
tot = 0
num = int(input('Digite um numero: '))
for c in range(1,num + 1):
if num % c == 0:
print('\033[34m',end=' ') #se for divisivel
tot += 1 # tot = tot + 1
else:
print('\033[31m',end=' ') #se... | StarcoderdataPython |
1745167 | <reponame>CMiksche/huntlib
#!/usr/bin/env python
import huntlib.data
from unittest import TestCase
class TestMultiReads(TestCase):
def test_read_json(self):
df = huntlib.data.read_json("support/*.json", lines=True)
(rows, cols) = df.shape
self.assertEqual(cols, 6, "The resulting DataFr... | StarcoderdataPython |
1620074 | <reponame>costa86/pypi-scaffold
from os import name
from setuptools import setup
#with open("README.md","r") as fh:
# long_description = fh.read()
name = 'special'
setup(
name=name,
version='0.0.2',
description='A short description',
long_description="Please, refer to Project links to see the docum... | StarcoderdataPython |
3389930 | # -*- coding: utf-8 -*-
"""
Created on Thu May 10 14:36:16 2018
@author: Prodipta
"""
from logbook import Logger
from collections import defaultdict
from logbook import Logger
from zipline.finance.blotter import Blotter
from zipline.utils.input_validation import expect_types
from zipline.assets import Asset
from zipl... | StarcoderdataPython |
1797917 | #
# Copyright 2018 Analytics Zoo Authors.
#
# 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... | StarcoderdataPython |
3231468 | <gh_stars>0
from abc import ABC, abstractmethod
ALLOWED_EXTENSIONS = ['html', 'csv', 'mp3', 'mp4', 'txt']
class AbstractRenderer(ABC):
@abstractmethod
def render(self):
pass
class HTMLRenderer(AbstractRenderer):
def render(self):
print("Render using HTMLRemderer.")
class Mp4Renderer(A... | StarcoderdataPython |
4835441 | from models import Fetcher
class ArtisanAndRecipe():
def getArtisan(self, server="eu", artisanSlug='blacksmith',
locale="en_US"):
self.route = '/d3/data/artisan/{}'.format(artisanSlug)
return Fetcher.fetchData(
server=server, locale=locale, route=self.route)
de... | StarcoderdataPython |
4822366 | <gh_stars>1-10
#Only for use in Python 2.6.0a2 and later
from __future__ import print_function
import sys
import os
dirpath = os.path.dirname(os.path.abspath(__file__))
sys.path.append( '.' )
sys.path.append( dirpath + '/../' )
from linkedList.linkedList import LinkedList
class ArrayStack:
def __init__(self, data... | StarcoderdataPython |
184682 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import division, print_function
__all__ = ["setup", "update_list", "update_database", "write_tweet"]
import os
import json
import nltk
import tweepy
import string
import numpy as np
import cPickle as pickle
from collections import defaultdict
PROJECTNAME... | StarcoderdataPython |
84540 | import math
import torch
import torch.nn as nn
from torch.distributions import Normal
from torch.nn import init
FixedNormal = Normal
log_prob_normal = FixedNormal.log_prob
FixedNormal.log_probs = lambda self, actions: log_prob_normal(self, actions).sum(-1, keepdim=True)
entropy = FixedNormal.entropy
FixedNormal.entro... | StarcoderdataPython |
1774883 | #!/usr/bin/env python
#
# Copyright (C) 2013 Google Inc.
#
# This file is part of YouCompleteMe.
#
# YouCompleteMe is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at you... | StarcoderdataPython |
59162 | <gh_stars>0
from django.db import models
from django.utils.translation import pgettext_lazy
from saleor.core.permissions import MODELS_PERMISSIONS
# Add in the permissions specific to our models.
MODELS_PERMISSIONS += [
'collection_extensions.view',
'collection_extensions.edit'
]
class CollectionExtension... | StarcoderdataPython |
3251918 | import os
import pandas
import math
import ntpath
from BirdRoostLocation.ReadData import Labels
import numpy as np
from BirdRoostLocation import utils
from BirdRoostLocation.PrepareData import NexradUtils
from BirdRoostLocation import LoadSettings as settings
from BirdRoostLocation.BuildModels.CNN import model as shall... | StarcoderdataPython |
3391849 | #!/usr/bin/env python3
"""PyTest tests for the get_datatype.py module.
"""
import os
import sys
sys.path.append(os.path.join(os.path.dirname(sys.path[0]),'amoebaelib')) # Customize.
from data.datatype_test_seqs import testseq1
from get_datatype import \
get_datatype_for_sequence_string, \
get_dbtype
def test_get_da... | StarcoderdataPython |
188799 | '''
URL: https://leetcode.com/problems/minimum-distance-between-bst-nodes/description/
Time complexity: O(n)
Space complexity: O(n)
'''
class Solution(object):
def minDiffInBST(self, root):
"""
:type root: TreeNode
:rtype: int
"""
sorted_lst = []
self.sort_vals(root... | StarcoderdataPython |
186478 | <reponame>sifrovacky-cz/kachna
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
#User profile model, one to one relation to User model
#Note: User = team, participants = team members
class UserProfile (models.Model):
user = models.OneToOneField(User, on_delete = ... | StarcoderdataPython |
176354 | <filename>Crawler/filecrawler.py<gh_stars>0
from apiproxy import ApiProxy, RestApiResponse
from model import AmbarFileMeta,AmbarCrawlerSettings
from logger import AmbarLogger
from abc import *
from hashlib import sha256
import hashlib
import re
class FileCrawler:
def __init__(self, ApiProxy, CrawlerSettings):
... | StarcoderdataPython |
45320 | <filename>elationmagic.py
"""
@copyright: 2013 Single D Software - All Rights Reserved
@summary: Elation Magic 260 MIDI interface for Light Maestro.
"""
# Standard library imports
import logging
# Additional library imports
import rtmidi
import rtmidi.midiconstants
# Application imports
import console
# Named log... | StarcoderdataPython |
3389691 | #!/usr/bin/env python3
import asyncio
import logging
from random import randint
import aiohttp
from asyncpraw import Reddit
from asyncpraw.models import Comment
from asyncprawcore.exceptions import ServerError
from dynaconf import Dynaconf
from discord_logging import DiscordWebhookHandler
config = Dynaconf(settings... | StarcoderdataPython |
1617335 | import pickle
import numpy as np
from tqdm.auto import tqdm
import moses
from moses import CharVocab
class NGram:
def __init__(self, max_context_len=10, verbose=False):
self.max_context_len = max_context_len
self._dict = dict()
self.vocab = None
self.default_probs = None
se... | StarcoderdataPython |
3332552 | <filename>src/server/TCGA/TCGACaller.py
__author__ = 'guorongxu'
import os
import subprocess
import itertools
from datetime import datetime
tumor_types = ["PRAD", "STES"]
#tumor_types = ["ACC", "BLCA", "BRCA", "CESC", "CHOL", "COAD", "COADREAD", "DLBC",
# "ESCA", "GBM", "GBMLGG", "HNSC", "KICH", "KIPAN"... | StarcoderdataPython |
3354663 | """BleBox climate entities tests."""
import json
from blebox_uniapi.box_types import get_latest_api_level
from .conftest import CommonEntity, DefaultBoxTest, future_date, jmerge
# TODO: remove
SUPPORT_TARGET_TEMPERATURE = 1
HVAC_MODE_OFF = "hvac mode off"
HVAC_MODE_HEAT = "hvac mode heat"
CURRENT_HVAC_OFF = "current... | StarcoderdataPython |
3212640 | <gh_stars>0
from unittest import TestCase
from unittest.mock import patch, MagicMock, PropertyMock
from bson import ObjectId
from django_mock_queries.query import MockSet
from mlplaygrounds.datasets.tests.mocks.managers import MockDatasetManager
from ..models import User, CustomUserManager
class TestUserModel(Test... | StarcoderdataPython |
68580 | import pandas as pd
import matplotlib as mpl
import matplotlib.pyplot as plt
import datetime
import seaborn as sns
from matplotlib.colors import ListedColormap
import numpy as np
df = pd.read_excel('data/R1_5_results_only.xlsx')
rc = {'figure.figsize': (10, 5),
'axes.facecolor': 'white',
'axes.grid': True... | StarcoderdataPython |
3316949 | # -*- coding: utf-8 -*-
import localhostrunner
import os.path
from django.conf import settings
from django.test.runner import DiscoverRunner
class LocalhostTestRunner(DiscoverRunner):
def run_suite(self, suite, **kwargs):
return localhostrunner.LocalhostTestRunner(**kwargs).run(suite)
| StarcoderdataPython |
103696 | <gh_stars>1-10
df.groupby('Pclass')['Fare'].hist(alpha=0.4);
| StarcoderdataPython |
1765275 | import re
from . import Mod
def remove_comments(output):
output = re.sub(r'(\/\*[\w\'\s\n\*]*\*\/)', r'', output) # multi-line comments
output = re.sub(r'((?:[\s;]+)|^)(\/\/.*$)', r'\1', output) # single-line comments
return output
mod_remove_comments = Mod(remove_comments)
| StarcoderdataPython |
3339449 | <reponame>caosenqi/Edward1
import numpy as np
import tensorflow as tf
from edward.data import Data
from edward.util import logit, get_session
def evaluate(metrics, model, variational, data):
"""
Evaluate fitted model using a set of metrics.
Parameters
----------
metric : list or str
List ... | StarcoderdataPython |
3227742 | <filename>src/train.py
from tensorflow import keras
import tensorflow as tf
import archs
from utils import data_utils, train_utils, augment, argmanager
from utils.loss import multinomial_nll
import numpy as np
import random
import string
import math
import os
import json
def subsample_nonpeak_data(nonpeak_seqs, nonpe... | StarcoderdataPython |
3347505 | from threading import Lock
from typing import Any
DRIVER_CACHE_LOCK = Lock()
NOT_SET_MARKER = object()
def singleton_setup(obj: object,
key: str,
factory,
*args,
**kwargs) -> Any:
"""
Does:
obj.key = factory(*args, **kwargs... | StarcoderdataPython |
1629702 | <reponame>RobertCraigie/prisma-client-py
import json
from typing import Any
import httpx
from ._types import Method
from .http_abstract import AbstractResponse, AbstractHTTP
__all__ = ('HTTP', 'Response', 'client')
class HTTP(AbstractHTTP[httpx.AsyncClient, httpx.Response]):
# pylint: disable=invalid-overridd... | StarcoderdataPython |
1670585 | from server import app, db
# Import model definitions and then create the database
db.create_all()
db.session.commit()
if __name__ == "__main__":
app.run(debug=True)
| StarcoderdataPython |
3229124 | DEBUG = False
BCRYPT_LOG_ROUNDS = 12 | StarcoderdataPython |
4818752 | from datetime import datetime, timedelta
from django.conf import settings
from rest_framework import generics
from rest_framework.decorators import api_view, permission_classes
from rest_framework.permissions import AllowAny
from rest_framework.response import Response
from rest_framework_jwt.utils import jwt_encode_h... | StarcoderdataPython |
3389004 | <filename>codegen.py
from ifelse_stmt import *
from stmt import *
from while_stmt import *
from block import *
from program import *
from declare import *
from assign_stmt import *
from call_stmt import *
from read_stmt import *
from write_stmt import *
from pl0yacc import *
from op import *
def getop(ast):
return... | StarcoderdataPython |
35156 | <reponame>jykntr/rest-cli-client
import argparse
from profile import Profile
PROXY = 'proxy'
VERIFY = 'verify'
DEBUG = 'verbose'
class CliParser():
def __init__(self, requests, profiles, options):
self.requests = requests
self.profiles = profiles
self.options = options
self.args =... | StarcoderdataPython |
3312891 | # We use word2vec instead of glove embedding in this file
# This word2vec is a self-trained one
import argparse
import json
import os
import pickle
from itertools import chain
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np
import pandas
import seaborn as sns
from gensim.models... | StarcoderdataPython |
4819546 | from mmdet.models.losses import FocalLoss, SmoothL1Loss, binary_cross_entropy
from .chamfer_distance import ChamferDistance, chamfer_distance
__all__ = [
'FocalLoss', 'SmoothL1Loss', 'binary_cross_entropy', 'ChamferDistance',
'chamfer_distance'
]
| StarcoderdataPython |
1790093 | from torch.utils.data import Dataset
import pymongo
import json
from collections import OrderedDict
import logging
logger = logging.getLogger(__name__)
class MongoWrapper:
"""
Load single turn Q,A data
"""
def __init__(self, config_path, filter_func=None):
"""
1. Mong... | StarcoderdataPython |
1619897 | # -*- coding: utf-8 -*-
# @Author : LG
"""
执行用时:48 ms, 在所有 Python3 提交中击败了94.04% 的用户
内存消耗:15.3 MB, 在所有 Python3 提交中击败了26.11% 的用户
解题思路:
递归
具体实现见代码注释
"""
class Solution:
def hasPathSum(self, root: TreeNode, sum: int) -> bool:
def find(root, current):
if root:
current += ro... | StarcoderdataPython |
1658865 | <reponame>tarvitz/face-check<gh_stars>0
from django.contrib.auth.models import AbstractUser
from django.db import models
from django.utils.translation import ugettext_lazy as _
class User(AbstractUser):
"""
standard django user
"""
is_verified = models.BooleanField(
_('is verified'... | StarcoderdataPython |
1638900 | <reponame>arrdem/source
import os
import re
import sys
def main(opts, args):
"""Usage: python rollback.py date
Parse /var/log/pacman.log, enumerating package transactions since the
specified date and building a plan for restoring the state of your system to
what it was at the specified date.
Ass... | StarcoderdataPython |
1616411 | import sys
import argparse
import os
from video_classification.generator.attention_cnn_lstm_classifer import BidirectionalLSTMVideoClassifier
def check_args(args):
if not os.path.exists(args.model_path):
print('Model path {} does not exist, please check.')
exit(1)
if not os.path.exists(args.v... | StarcoderdataPython |
3349317 | import csv
class IngAutCSV(csv.Dialect):
delimiter = ";"
quotechar = '"'
quoting = csv.QUOTE_MINIMAL
lineterminator = "\r\n"
def do_import(filename, store):
ing_file = open(filename, newline="", encoding="latin1")
# Convert the actual data
for record in csv.DictReader(ing_file, dialect=... | StarcoderdataPython |
193309 | import pickle
from collections import defaultdict, namedtuple
import numpy as np
import argparse
import os
import model.config as config
import preprocessing.util as util
from termcolor import colored
import tensorflow as tf
class VocabularyCounter(object):
"""counts the frequency of each word and each character... | StarcoderdataPython |
4842635 | <filename>lib/dynamic_screening_solutions/constants/__init__.py
# HTK Imports
from htk.lib.dynamic_screening_solutions.constants.general import *
| StarcoderdataPython |
1732404 | # -*- coding:utf-8 -*-
# Author: hankcs
# Date: 2020-05-06 23:16
from edparser.utils.io_util import load_pickle, save_pickle
from iwpt2020 import cdroot
import numpy as np
import matplotlib.pyplot as plt
cdroot()
gold_file = 'data/iwpt2020/test-udpipe/en.fixed.conllu'
template = 'data/model/iwpt2020/bert/dep/en.conl... | StarcoderdataPython |
1650674 | <filename>logwrap/__init__.py
# Copyright 2016-2018 <NAME> aka penguinolog
#
# Copyright 2016 Mirantis, Inc.
#
# 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://... | StarcoderdataPython |
1727324 | from django.urls import path
from . import views
urlpatterns = [
path('login/', views.loginUser, name='login'),
path('logout/', views.logoutUser, name='logout'),
path('register/', views.registerUser, name='register'),
path('', views.index, name='list'),
path('update_task/<str:pk>', views.updateTask, name='up... | StarcoderdataPython |
190449 | import csv
import camelot
IN_PATH = 'student_attendance.pdf'
OUT_PATH = f'{IN_PATH[:-3]}csv'
class Converter:
def __init__(self, input_path, output_path):
self.in_path = input_path
self.out_path = output_path
def table_to_csv(self, tables):
with open(self.out_path, 'w', newline='') ... | StarcoderdataPython |
1690403 | <gh_stars>0
import os
import re
import numpy as np
def main():
refs = []
outs = []
for file in os.scandir('../results'):
with open(file.path, "r") as f:
results = f.read()
try:
ref = re.search(R"(?<=Creversible=yes Clevels=5 Cdecomp=\"B\(-:-:-\),B\(-:-:-\),B... | StarcoderdataPython |
1656502 | import json
from erdos.op import Op
from pylot.utils import is_obstacles_stream
class BoundingBoxLoggerOp(Op):
def __init__(self, name, flags):
super(BoundingBoxLoggerOp, self).__init__(name)
self._flags = flags
self._msg_cnt = 0
@staticmethod
def setup_streams(input_streams):
... | StarcoderdataPython |
3204070 | import serial
port = None
def init(dev, baud):
global port
if port == None:
port = serial.Serial(dev, baud)
port.readline()
def shake():
global port
port.write("1\r\n")
port.readline()
| StarcoderdataPython |
3213915 | <reponame>ArthurHowardMorris/ling_features
import re
import numpy as np
from numpy import dot
from numpy.linalg import norm
# Compute cosine similarity between two vectors
def compute_cos_sim(vector_a, vector_b):
if not np.all(vector_a == 0) and not np.all(vector_b == 0):
cos_sim = dot(vector_a, vector_b)/... | StarcoderdataPython |
1771087 | from django.db import models
from django.contrib .auth.models import User
from django.utils.translation import ugettext as _
class Employer(models.Model):
owner = models.ForeignKey(to=User, on_delete=models.CASCADE, blank=True, null=True)
name = models.CharField(max_length=50)
updated_at = models.DateTim... | StarcoderdataPython |
3322854 | <filename>fieldkit/test/test_lattice.py
""" Unit tests for lattice data structures.
"""
import unittest
import numpy as np
import fieldkit
class LatticeTest(unittest.TestCase):
""" Test cases for :py:class:`~fieldkit.lattice.Lattice` and :py:class:`~fieldkit.lattice.HOOMDLattice`.
"""
def test(self):
... | StarcoderdataPython |
1612344 | from __future__ import unicode_literals
from frappe import _
def get_data():
return {
'fieldname': 'case_level',
'transactions': [
{
'label': _('Case Log'),
'items': ['Case Log']
}
]
}
| StarcoderdataPython |
3223921 | <reponame>ConsenSys/Legions
#!/usr/bin/env python3
# Legion - <NAME>, ConsenSys Diligence
import argparse
from legions.context import LegionContext
from legions.statusbar import LegionStatusBar
from nubia import PluginInterface, CompletionDataSource
from nubia.internal.blackcmd import CommandBlacklist
class Legion... | StarcoderdataPython |
3242221 | <filename>dwcontents/utils.py
# dwcontents
# Copyright 2018 data.world, Inc.
#
# 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 requir... | StarcoderdataPython |
1692783 | import argparse
import os
import torch
import yaml
from train.train import train
os.environ['NCCL_LL_THRESHOLD'] = '0'
parser = argparse.ArgumentParser(description='Train model on multiple cards')
parser.add_argument('--config', help='path to yaml config file')
parser.add_argument('--local_rank', type=i... | StarcoderdataPython |
1632222 | <reponame>egromero/chat_app_flask
# Copyright (c) 2009-2015 <NAME> and gevent contributors. See LICENSE for details.
from __future__ import absolute_import
import os
from gevent._util import copy_globals
try:
if os.environ.get('GEVENT_CORE_CFFI_ONLY'):
raise ImportError("Not attempting corecext")
fr... | StarcoderdataPython |
1649400 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# nnutil2 - Tensorflow utilities for training neural networks
# Copyright (c) 2020, <NAME> <<EMAIL>>
#
# This file is part of 'nnutil2'.
#
# This file may be modified and distributed under the terms of the 3-clause BSD
# license. See the LICENSE file for details.
import... | StarcoderdataPython |
3232849 | <gh_stars>0
import pandas as pd
import numpy as np
import torch.nn as nn
from torchvision import transforms
from torch.utils.data import Dataset
from collections import Counter
import torch
from PIL import Image
from skimage import io
#from data_util import TrainProtsDataset, ValProtsDataset, TestProtsDataset
from torc... | StarcoderdataPython |
3356680 | <filename>src/posts/models.py
import os
from django.db import models
from django.urls import reverse
from tagging.registry import register
from tagging.fields import TagField
def rename_file_with_slug(old_filename, slug):
filename, file_extension = os.path.splitext(old_filename)
truncated_slug = slug[:25] if... | StarcoderdataPython |
3315177 | <filename>botfile/sender.py
import discord
from discord.ext import commands
import asyncio
class Sender(commands.Cog):
def __init__(self,bot):
self.bot =bot
@commands.command()
async def url(self,ctx,mid:int,cid:int=ctx.channel.id):
try:
g = ctx.guild
ch = bot.get_channel(cid)
ms... | StarcoderdataPython |
3227296 | <filename>tests/test_binary_search.py
import unittest
from random import randint
from big_o import big_o, complexities
from src.binary_search import binary_search
class TestBinarySearch(unittest.TestCase):
def test_find(self):
self.assertEqual(binary_search([1, 3, 5, 7, 9], 3), 1)
def test_not_find... | StarcoderdataPython |
129934 | <filename>test_split.py
from itertools import chain, repeat
from hypothesis import given
import hypothesis.strategies as st
import pytest
from split import chunks, groupby, partition, split
expected_keys = (1, 2, 3, 4, 5)
expected_groups = ((1, 1), (2, 2), (3, 3), (4, 4), (5, 5))
def call(*args, **kwargs):
... | StarcoderdataPython |
1707699 | def comp_L2(self, L2_ref=None):
"""Compute and set the Rotor phase inductance for the equivalent electrical circuit
Parameters
----------
self : EEC_SCIM
an EEC_SCIM object
L2_ref : float
reference inductance
"""
if L2_ref is None:
raise Exception("L2 parameter for... | StarcoderdataPython |
123062 | #!/usr/bin/env python
# encoding: utf8
#
# Grab http://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt
#
from __future__ import print_function
import os, sys
from argparse import ArgumentParser
from robofab.objects.objectsRF import OpenFont
from unicode_util import parseUnicodeDataFile, MainCategories as UniMainC... | StarcoderdataPython |
1651081 | from django.conf.urls import patterns, include, url
from django.views.generic import TemplateView
from .views import location
urlpatterns = patterns('',
url(r'^(?P<locationname>[A-Za-z]+)/$', location, name='location'),
url(r'^(?P<locationname>[A-Za-z]+)/(?P<placeofinterest>[A-Za-z]+)/$', location, name = 'placeo... | StarcoderdataPython |
4815775 | import types
def isclass(obj):
"""
Helper.
Identical to Python 2.7 's inspect.isclass.
isclass in Python 2.6 also returns True when
the passed object has a __bases__ attribute.
(like in case of an instance.)
"""
return isinstance(obj, (type, types.ClassType))
from .network import *
fr... | StarcoderdataPython |
1699406 | #!/usr/bin/env python
from eth_tester.exceptions import TransactionFailed
from utils import longTo32Bytes, longToHexString, fix, AssertLog, stringToBytes, EtherDelta, PrintGasUsed, BuyWithCash, TokenDelta, EtherDelta, nullAddress
from pytest import raises, mark, fixture as pytest_fixture
from reporting_utils import pr... | StarcoderdataPython |
3358669 | <reponame>bradmontgomery/django-redis-metrics
from __future__ import unicode_literals
from django.core.management.base import BaseCommand, CommandError
from optparse import make_option
from redis_metrics.utils import generate_test_metrics
class Command(BaseCommand):
args = '<metric-name> [<metric-name> ...]'
... | StarcoderdataPython |
1695113 | <filename>src/products/views.py
# Here we are going to render the contents of the products database in these pages.
# This is a good case of dedicating each app to specific roles.
# This views.py has it's own template folder 'products/templates/'.
# Also checkout pages/views.py to see some comments that can help you un... | StarcoderdataPython |
3270062 | """Particle filtering and smoothing."""
from ._particle_filter import (
ParticleFilter,
effective_number_of_events,
resample_categorical,
)
from ._particle_filter_posterior import ParticleFilterPosterior
| StarcoderdataPython |
3280395 | # -*- coding: utf-8 -*-
"""
Conftest.
"""
import pytest
from pathlib import Path
@pytest.fixture(scope="session", autouse=True)
def data_path() -> Path:
"""Path to test data."""
return Path(__file__).parent / "data"
@pytest.fixture(scope="session")
def cal_data(data_path: Path):
return data_path / "Re... | StarcoderdataPython |
3276865 | <reponame>Cougargriff/SK-Purple-Convert
import csv
from os import system, name
def clear():
# for windows
if name == 'nt':
_ = system('cls')
# for mac and linux(here, os.name is 'posix')
else:
_ = system('clear')
blue_f = open('blue_zero_point_foods.csv')
purple_f = open('purple... | StarcoderdataPython |
3225657 | class SimModule(object):
def initialize(self, sim):
pass
def save(self, sim, **kwargs):
pass
def finalize(self, sim):
pass | StarcoderdataPython |
1725102 | # -------- BEGIN LICENSE BLOCK --------
# Copyright 2022 FZI Forschungszentrum Informatik
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright
# n... | StarcoderdataPython |
3225938 | #!/usr/bin/env python
# run:
# python3 -mvenv ../ve3
# ../ve3/bin/pip install wheel
# ../ve3/bin/pip install --editable .
# ../ve3/bin/ag-pserver --listen tcp:8001 --controller tcp:localhost:8002
# the provisioning webpage is in html/index.html , edit it in place
from setuptools import setup
import os
setup(
... | StarcoderdataPython |
3291450 | <filename>stack.py
from linked_list import *
class Stack (object):
def __init__(self):
self.linked_list = LinkedList ()
def stack_size (self):
return self.linked_list.size_of_linked_list()
def is_empty (self):
return self.linked_list.size_of_linked_list() == 0
def push (self,... | StarcoderdataPython |
4820167 | import os
class Config(object):
DEBUG = True
TESTING = True
SECRET_KEY = "<KEY>"
DATABASE_URL = os.environ.get("TRUNKS_DATABASE_URL")
| StarcoderdataPython |
3354831 | <gh_stars>0
import pdb
def spam(eggs):
print('eggs:', eggs)
if __name__ == '__main__':
pdb.set_trace()
for i in range(5):
spam(i) | StarcoderdataPython |
3528 | <filename>pysc2/lib/actions.py
# Copyright 2017 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... | StarcoderdataPython |
1604125 | import sys
import subprocess
res = subprocess.check_output(["sf", "-json",sys.argv[1][2:]])
for line in res.splitlines():
subprocess.call(["aws","sns","publish","--topic-arn","arn:aws:sns:eu-west-2:247222723249:fileformat-check-result-dev","--message",line])
| StarcoderdataPython |
1672079 | from ....Classes.Arc1 import Arc1
from ....Classes.SurfLine import SurfLine
def get_surface_active(self, alpha=0, delta=0):
"""Return the full winding surface
Parameters
----------
self : SlotW22
A SlotW22 object
alpha : float
float number for rotation (Default value = 0) [rad]
... | StarcoderdataPython |
36300 | <gh_stars>0
#!/usr/bin/env python
# import required modules:
#
import os
import sys
import string
import random
from random import shuffle
from pathlib2 import Path
import linecache
import time
# This class shuffles songs without repeating and keeps track of where
# it left off. See '-help' option for more details.
#... | StarcoderdataPython |
1618710 | <reponame>kaiergin/Quadcopter_simulator
import numpy as np
import math
import matplotlib.pyplot as plt
import mpl_toolkits.mplot3d.axes3d as Axes3D
import sys
class GUI():
# 'quad_list' is a dictionary of format: quad_list = {'quad_1_name':{'position':quad_1_position,'orientation':quad_1_orientation,'arm_span':qua... | StarcoderdataPython |
144423 | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
from typing import List
import numpy as np
import torch
from pytext.models.representations.transformer import (
TransformerLayer,
MultiheadSelfAttention,
)
from pytext.models.roberta import RoBERTaEncoder
from torch... | StarcoderdataPython |
3315789 | <gh_stars>0
import noise
import numpy as np
from PIL import Image
import math
import io
import json
from scipy.misc import toimage
shape = (1024, 1024)
scale = 150
octaves = 4
persistence = 0.5
lacunarity = 2.0
threshold = 0.05
seed = np.random.randint(0, 500)
black = [0, 0, 0]
blue = [65,105,225]
g... | StarcoderdataPython |
3294445 | <filename>fairseq/criterions/masked_adlm.py
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import math
import torch
import torch.nn.functional as F
from fairseq import metrics, utils
from... | StarcoderdataPython |
4810114 | from opentrons import protocol_api
import pandas as pd
import decimal, math
metadata = {'apiLevel': '2.8'}
def run(protocol: protocol_api.ProtocolContext):
# number of regular plates
regular_plates = 4
# pipette name
pipette_name = 'p300_multi_gen2'
# labware name for regular plates
regular_... | StarcoderdataPython |
1616685 | <reponame>Keesiu/meta-kaggle<filename>data/external/repositories_2to3/141822/AXA_Telematics-master/Features/combine_output_files_Forest.py
import numpy as np
from sklearn.ensemble import GradientBoostingRegressor
from random import sample
import os
import sys
import time
import csv
from modules_janto.paths imp... | StarcoderdataPython |
1619534 | #!/usr/bin/env python3
"""Common functions for Flask webUI"""
import os
import sqlite3
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(__file__)), '..'))
import constants # noqa
def initial_state():
"""
Set the factory settings for the application.
The settings are stored in... | StarcoderdataPython |
175685 | <reponame>openhealthcare/python-fp17
import datetime
from fp17 import treatments, exemptions
def annotate(bcds1):
bcds1.patient.surname = "BARNES"
bcds1.patient.forename = "SUSAN"
bcds1.patient.address = ["34 HIGH STREET"]
bcds1.patient.sex = 'F'
bcds1.patient.date_of_birth = datetime.date(1969, ... | StarcoderdataPython |
3295375 | <filename>features/utils.py<gh_stars>1-10
from typing import Dict
from typing import Iterable
from typing import List
from javalang.tokenizer import JavaToken, Identifier, Keyword, Literal
from javalang.tree import Node
def identifiers(tokens: List[JavaToken]) -> List[Identifier]:
return [it for it in tokens if ... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.