id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
3502376 | #!/usr/bin/env python
import sys
import os
import shutil
import subprocess
import argparse
import logging
from pprint import pprint
import fileinput
from typing import Tuple
import dryable
from distutils.dir_util import copy_tree
# the make pdf command to fire.
CMD_MAKE_PDF = 'make pdf'
def get_target_dirs(read_fr... | StarcoderdataPython |
1920131 | <gh_stars>0
"""DDD17+ create configs.
Author: <NAME>
Email : <EMAIL>
"""
from __future__ import print_function
import os
from os.path import join
import json
import spiker
# configure path
config_path = os.path.join(
spiker.HOME, "workspace", "ddd17-cvpr", "exps", "configs",
"ral-exps")
num_trails = 5
con... | StarcoderdataPython |
3238088 | import unittest
from urllib2 import HTTPError
from flotilla.scheduler.coreos import CoreOsAmiIndex
from mock import MagicMock, patch
CHANNEL = 'stable'
VERSION = '835.9.0'
REGION = 'us-east-1'
@patch('urllib2.urlopen')
class TestCoreOsAmiIndex(unittest.TestCase):
def setUp(self):
self.coreos = CoreOsAmi... | StarcoderdataPython |
1770819 | # -*- coding: utf-8 -*-
# pylint: disable=unused-argument
"""Functional tests."""
from fm_database.settings import DevConfig, ProdConfig, TestConfig, get_config
def test_retrieving_settings():
"""Test that the correct settings are retrieved."""
test_config = get_config(override_default="test")
dev_config ... | StarcoderdataPython |
6549777 | <reponame>kaushikcfd/numloopy<filename>test/test_essentials.py
import sys
import numpy
import pyopencl as cl
import numloopy as nplp
from loopy.version import LOOPY_USE_LANGUAGE_VERSION_2018_2 # noqa: F401
try:
import faulthandler
except ImportError:
pass
else:
faulthandler.enable()
from pyopencl.tools i... | StarcoderdataPython |
1938600 | from hashtable.hashtable import Hashtable
def repeat_word(long_string):
start=0
word=''
words_ht = Hashtable()
long_string = long_string.lower()
words= long_string.split(' ')
for word in words:
if words_ht.contains(word):
return word
else:
word_hash = wor... | StarcoderdataPython |
1835225 | <filename>divia_req.py
from divia_api import DiviaAPI
from datetime import date, datetime
from browser import window
api = DiviaAPI()
def bridge(ligne, sens, arret):
totem_result = api.find_stop(ligne, arret, sens).totem()
now = datetime.now()
processed_result = []
for t in totem_result:
proc... | StarcoderdataPython |
4853346 | import logging
import subprocess
import tempfile
import typing
import const
import models
import schemas
import os
import re
import util
_LOGGER = logging.getLogger(__name__)
class WGAlreadyStartedError(Exception):
pass
class WGAlreadyStoppedError(Exception):
pass
class WGPermissionsError(Exception):
... | StarcoderdataPython |
112696 | <reponame>simonwoerpel/runpandarun
import os
from ..util import get_files
from .backend import Backend
def ensure_directory(fp):
fp = os.path.abspath(fp)
if not os.path.isdir(fp):
os.makedirs(fp)
return fp
class FilesystemBackend(Backend):
def get_base_path(self):
return ensure_dire... | StarcoderdataPython |
4926947 |
import asyncio
import itertools
from aiostream import stream
async def number_generator(name, sleepytime):
numbers_returned = 0
while numbers_returned < 10:
numbers_returned += 1
await asyncio.sleep(sleepytime)
yield (name, numbers_returned)
async def main():
generator1 = number_g... | StarcoderdataPython |
5062041 | <filename>src/tom/_mailbox/imapclient.py
import sys
import socket
import select
import imapclient as _imapclient
from imapclient import *
class IMAPClient(_imapclient.IMAPClient):
"""
This class provdes some extensions to `imapclient.IMAPClient`
"""
@imapclient.require_capability('IDLE')
def idle... | StarcoderdataPython |
6643666 | """Recommend API.
"""
from copy import deepcopy
import numpy as np
from catalog import SimpleCatalog, Track
from cf.cf_hidden_feature import get_hidden_feature_matrix_GD
import itertools
from API.user import train_user_taste_model
# TODO: implement classes: UserTasteModel.
class RecommendationEngine(object):
de... | StarcoderdataPython |
3476127 | <reponame>EHakansson/nvdb2osm<filename>waydb.py
import logging
from functools import cmp_to_key
from twodimsearch import TwoDimSearch
from geometry_search import GeometrySearch
from geometry_basics import *
from merge_tags import merge_tags
from proj_xy import latlon_str
from shapely_utils import *
from nseg_tools imp... | StarcoderdataPython |
4994088 | <gh_stars>100-1000
def custom_simclr_contrastive_loss(proj_feat1, proj_feat2, temperature=0.5):
"""
custom_simclr_contrastive_loss(proj_feat1, proj_feat2)
Returns contrastive loss, given sets of projected features, with positive
pairs matched along the batch dimension.
Required args:
- proj_feat1 (2D torch... | StarcoderdataPython |
6500105 | __all__ = ['coroutine',
'iscoroutinefunction', 'iscoroutine']
import functools
import inspect
import opcode
import os
import sys
import traceback
import types
from . import compat
from . import events
from . import futures
from .log import logger
# Opcode of "yield from" instruction
_YIELD_FROM = opcode.... | StarcoderdataPython |
3406945 | import MySQLdb
import datetime
from copy import deepcopy
#current db on VM: playgroundapr8; on jas' computer: playgroundapr8; on github: playgroundapr11
def launchdb():
db = MySQLdb.connect(host="localhost", user="root", passwd="", db="playgroundapr8")
return db
def launchcursor(db):
cursor = db.cursor()
return ... | StarcoderdataPython |
9727344 | <reponame>anamaria-uofg/mass-spec-utils<gh_stars>1-10
# gnps.py
from .spectrum import SpectralRecord
from loguru import logger
def load_gnps_files(file_list):
if type(file_list) == str:
file_list = [file_list]
spectra = {}
for file_name in file_list:
spectra = load_mgf(file_name,id_field = '... | StarcoderdataPython |
6414794 | <filename>backend/api/urls.py
from .views import RegisterAPI, LoginAPI, ReactAPI, CommentAPI
from django.urls import path
from knox import views as knox_views
urlpatterns = [
path('register/', RegisterAPI.as_view(), name='register'),
path('login/', LoginAPI.as_view(), name='login'),
path('logout/', knox_vi... | StarcoderdataPython |
56270 | <filename>test-app/behave/steps/autocomplete.py
####
#### Steps centered around dealing with the various
#### autocomplete/search boxes.
####
from behave import *
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditio... | StarcoderdataPython |
9749337 | #!/usr/bin/env python
"""
synopsis:
Custom routing Router to Mama (ROUTER to REQ)
Author: <NAME> (brainsik) <spork(dash)zmq(at)theory(dot)org>
Modified for tornado/ioloop: <NAME> <dkuhlman(at)davekuhlman(dot)org>
usage:
python rtreq.py
"""
import sys
import random
import zmq
from functools import part... | StarcoderdataPython |
6514149 | # -*- coding: utf-8 -*-
from juriscraper.OpinionSite import OpinionSite
from juriscraper.WebDriven import WebDriven
class OpinionSiteWebDriven(OpinionSite, WebDriven):
def __init__(self, *args, **kwargs):
super(OpinionSiteWebDriven, self).__init__(*args, **kwargs)
WebDriven.__init__(self, args, k... | StarcoderdataPython |
4929884 | """Hidden Markov Model example.
https://github.com/pyro-ppl/numpyro/blob/master/examples/hmm.py
"""
import argparse
from typing import Callable, Dict, Tuple
import jax.numpy as jnp
import matplotlib.pyplot as plt
import numpy as np
import numpyro
import numpyro.distributions as dist
from jax import lax, random
from ... | StarcoderdataPython |
6583481 | """A ``tesliper``'s main data storage."""
import logging as lgg
from collections import Counter, OrderedDict
from collections.abc import ItemsView, KeysView, ValuesView
from contextlib import contextmanager
from inspect import Parameter
from itertools import chain
from reprlib import recursive_repr
from typing import C... | StarcoderdataPython |
11356560 | """Test the refinement routines in RBFOpt.
This module contains unit tests for the module rbfopt_refinement.
Licensed under Revised BSD license, see LICENSE.
(C) Copyright International Business Machines Corporation 2017.
"""
from __future__ import print_function
from __future__ import division
from __future__ impo... | StarcoderdataPython |
11393364 | # -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright (c) 2014, <NAME>
# Distributed under the (new) BSD License.
#
# Contributors: <NAME> (<EMAIL>)
# -----------------------------------------------------------------------------
# References:
#
# * Interacti... | StarcoderdataPython |
191104 | from pathlib import Path
import pytest
@pytest.fixture(autouse=True)
def tests_directory() -> Path:
return Path(__file__).parent
@pytest.fixture(autouse=True)
def project_root_directory() -> Path:
return Path(__file__).parent.parent
@pytest.fixture(autouse=True)
def test_root_directory(request) -> Path:
... | StarcoderdataPython |
6491049 | <filename>specs/secure/scanning/scanning_vulnerability_spec.py
import os
from expects import equal, expect, have_keys
from mamba import before, context, description, it
from sdcclient import SdScanningClient
from specs import be_successful_api_call
with description("Scanning vulnerability details", "integration") as... | StarcoderdataPython |
3226002 | <reponame>Bhaskers-Blu-Org1/SPAHM
import numpy as np
import sys
from sklearn.metrics.pairwise import euclidean_distances
from scipy.optimize import linear_sum_assignment
def gen_gaus_mixture(centers, mixing_prop=None, noise_sd=0.1, M=5000):
# noise_sd=0.1
# M=5000
# mixing_prop=None
# centers = np.random.n... | StarcoderdataPython |
11309212 | import pulp
import LPHelpers as lph
import Utils
##### Goal Interface #####
class Goal(object):
def __init__(self, required, netReward, partialReward):
self.required = required
self.netReward = netReward
self.partialReward = partialReward
def genConstraintsAndRewards(self, dataBox):
... | StarcoderdataPython |
61086 | # import RPi.GPIO as GPIO
import datetime
class Servo:
def __init__(self, on_time=datetime.time(0,0,0)): #pin_mode = GPIO.BOARD):
self.on_time = on_time
self.on_hour = on_time.hour
self.on_minute = on_time.minute
self.is_running = False
def view_config(self):
print(f'on_time: {self.on_time}')
... | StarcoderdataPython |
11200762 | from .base import *
# Parse database configuration from $DATABASE_URL
import dj_database_url
DATABASES['default'] = dj_database_url.config()
# Allow all host headers
ALLOWED_HOSTS = ['*']
DEBUG = False
| StarcoderdataPython |
3394165 | <gh_stars>0
# Generated by Django 2.1.1 on 2018-10-05 11:41
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('app', '0007_auto_20181004_1735'),
]
operations = [
migrations.AddField(
model_name='otp',
name='verified... | StarcoderdataPython |
4847819 | # -*- coding: utf8 -*-
#-----------------------------------------------------------------------------
# Copyright (c) 2010-2012 <NAME>, <NAME>
#
# This file is part of pyzmq
#
# Distributed under the terms of the New BSD License. The full license is in
# the file COPYING.BSD, distributed as part of this software.
... | StarcoderdataPython |
8072285 | from django import forms
from django_countries.tests import models
class PersonForm(forms.ModelForm):
class Meta:
model = models.Person
fields = ["country", "favourite_country"]
class AllowNullForm(forms.ModelForm):
class Meta:
model = models.AllowNull
fields = ["country"]
... | StarcoderdataPython |
1839698 | <reponame>DeWill404/Data-Structure-and-Algorithm<filename>Python/Data Structure/Stack/Stack Using Array.py
class Stack:
# Stack varaible Initialization
def __init__(self):
self.stack = []
self.MAX = 5
self.TOP = -1
# OVERFLOW check function
def UNDERFLOW(self):
if se... | StarcoderdataPython |
3327570 | import pytest
from asn1PERser.codec.per.encoder import encode as per_encoder
from asn1PERser.classes.data.builtin.BooleanType import BooleanType
@pytest.mark.parametrize("boolean, encoded", [
(BooleanType(value=True), '80'),
(BooleanType(value=False), '00')
])
def test_boolean_type_can_be_encoded(boolean, enc... | StarcoderdataPython |
280574 | import tempfile
import pytest
import numpy as np
from pandas import DataFrame
import joblib
from sklearn_pandas import DataFrameMapper
from sklearn_pandas import NumericalTransformer
@pytest.fixture
def simple_dataset():
return DataFrame({
'feat1': [1, 2, 1, 3, 1],
'feat2': [1, 2, 2, 2, 3],
... | StarcoderdataPython |
3212103 | import requests
import re
import random
import configparser
from bs4 import BeautifulSoup
from flask import Flask, request, abort
from imgurpython import ImgurClient
from linebot import (
LineBotApi, WebhookHandler
)
from linebot.exceptions import (
InvalidSignatureError
)
from linebot.models import *
app = F... | StarcoderdataPython |
11210168 | <gh_stars>1-10
# this file is for testing purposes only
# TODO remove this file later
from bython.parser import parse_file_recursively
parse_file_recursively("test-code.by") | StarcoderdataPython |
9727410 | import json
from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import reverse
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.utils.translation import ugettext as _, ugettext
from django.view... | StarcoderdataPython |
5012981 | <filename>recipes/recipe_modules/windows_adk/examples/ensure.py
# Copyright 2021 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from recipe_engine.post_process import StepCommandRE, DropExpectation
DEPS = [
'windows_... | StarcoderdataPython |
12831633 | from subscriber import podaac_data_subscriber as pds
import pytest
def test_temporal_range():
assert pds.get_temporal_range(None, '2021-01-01T00:00:00Z', "2021-08-20T13:30:38Z") == "1900-01-01T00:00:00Z,2021-01-01T00:00:00Z"
assert pds.get_temporal_range('2021-01-01T00:00:00Z', '2022-01-01T00:00:00Z', "2021-... | StarcoderdataPython |
1924829 | <reponame>fictional-tribble/integrations-extras
# (C) Datadog, Inc. 2010-2016
# All rights reserved
# Licensed under Simplified BSD License (see LICENSE)
# stdlib
from nose.plugins.attrib import attr
from collections import namedtuple
import os
# 3p
from mock import patch
# project
from tests.checks.common import Ag... | StarcoderdataPython |
305383 | import json
import os
from os import path
from .provider import Provider
SOURCE_DIR = "./source/data/"
class GCloud(Provider):
def __init__(self, options, *args, **kwargs):
data_file = path.join(os.path.dirname(os.path.abspath(__file__)), SOURCE_DIR, 'gcloud.json')
super(GCloud, self).__init__(d... | StarcoderdataPython |
1819055 | <reponame>chirain1206/Improvement-on-OTT-QA
#!/usr/bin/env python3
# Copyright 2017-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the
# LICENSE file in the root directory of this source tree.
"""A script to build the tf-idf document matrices for retrieval."""... | StarcoderdataPython |
6579567 | <filename>src/moehni/progmem_creator.py<gh_stars>0
# Writes the intensities to one header file
import math
f = open("intensities.h", "w")
size = 256
max_value = 4095
i = 0;
offset_0 = 125
for i in range(5):
name = "const PROGMEM uint16_t intensities_" + str(i) + "[] = {";
f.write(name)
offset = offset_... | StarcoderdataPython |
289599 | <gh_stars>1-10
#!/usr/bin/env python
"""
admindb helper library
Called by flask app admin
to modify budgets, etc.
Copyright 2015 zulily, 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 ... | StarcoderdataPython |
41139 | # Refaça o desafio 035, acrescentando o recurso de mostrar que
# tipo de triângulo será formado:
# - Equilátero: todos os lados iguais;
# - Isósceles: dois lados iguais;
# - Escaleno: todos os lados diferentes.
n1 = float(input('\033[34mMedida 1:\033[m '))
n2 = float(input('\033[31mMedida 2:\033[m '))
n3 = float(input(... | StarcoderdataPython |
3364989 | #!/usr/bin/env python
"""
CX input generation script.
"""
import logging
import sys
import h5py
import numpy as np
import matplotlib as mpl
import matplotlib.animation as anim
import matplotlib.image
import matplotlib.cm as cm
import matplotlib.pyplot as plt
try:
from shutil import which
except:
from shuti... | StarcoderdataPython |
3444992 | <reponame>jhonifreitas/auto-service<gh_stars>0
from model_mommy import mommy
from rest_framework.serializers import ValidationError
from django.test import TestCase
from django.contrib.auth.models import User
from gojob.api.v1.auth.serializers import LoginSerializer
class LoginSerializerValidTest(TestCase):
de... | StarcoderdataPython |
262997 | import math
import collections
import nltk
import time
from glob import glob
import os
from nltk.tokenize import RegexpTokenizer
from nltk.stem.snowball import SnowballStemmer
from nltk.util import ngrams
from nltk.corpus import stopwords
tokenizer = RegexpTokenizer(r'\w+')
stemmer = SnowballStemmer("english")
stopset... | StarcoderdataPython |
6702208 | class Solution:
def computeArea(self, A: int, B: int, C: int, D: int, E: int, F: int, G: int, H: int) -> int:
r1 = [A,B,C,D]
r2 = [E,F,G,H]
ra1 = (C-A)*(D-B)
ra2 = (G-E)*(H-F)
ra3 = 0
dx = min(r1[2], r2[2]) - max(r1[0], r2[0])
dy = min(r1[3], r2[3]) ... | StarcoderdataPython |
5092895 | <filename>pipeline/tests/core/flow/io/test_object_item_schema.py<gh_stars>10-100
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community
Edition) available.
Copyright (C) 2017-2021 THL A29 Limited, a Tencent company. All rights reserved.
Licen... | StarcoderdataPython |
4939478 | import pytest
import packerlicious.provisioner as provisioner
class TestPowerShellProvisioner(object):
def test_required_fields_missing(self):
b = provisioner.PowerShell()
with pytest.raises(ValueError) as excinfo:
b.to_dict()
assert 'PowerShell: one of the following must be... | StarcoderdataPython |
5068612 | <reponame>VerdigrisTech/data_science_tools
""" Data Science Tools
"""
# flake8: noqa: F403,F401
# pylint: disable=import-outside-toplevel,global-statement
from typing import List
def get_version() -> str:
"""Get version number"""
import os # pylint: disable=redefined-outer-name
filepath = os.path.join(... | StarcoderdataPython |
11267452 | <gh_stars>1-10
import sys; import os
from pathlib import Path
import configparser
import subprocess
def install(package):
print('Installing:', fp)
print('Install Exit Code:',
subprocess.check_call(
[sys.executable, "-m", "pip",
"install", package])
)
lib_fp = Path('li... | StarcoderdataPython |
12813856 | <reponame>jnoddell/LC
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution(object):
def isSymmetric(self, root):
"""
:type root: TreeNode
... | StarcoderdataPython |
4954831 | <reponame>SounakMandal/AlgoBook
class edge:
def __init__(self, u, w):
self.From = u
self.weight = w
def addedge(u, v, w):
edges[v].append(edge(u, w))
def shortestpath(dp):
for i in range(V + 1):
for j in range(V):
dp[i][j] = -1
for i in range(1, V + 1):
for j in range(V):
for k in ra... | StarcoderdataPython |
3542522 | from tornado import web, gen, httpclient
import socket
import json
class Repos(web.RequestHandler):
@gen.coroutine
def get(self):
return_data = []
for port in range(8010, 8040):
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
if s.connect_ex(('localhos... | StarcoderdataPython |
6473550 | <filename>scholar_crawler.py
# -*- coding: utf-8 -*-
from requests import get
from bs4 import BeautifulSoup
import numpy as np
from time import sleep
import pandas as pd
url = 'https://scholar.google.com/citations?view_op=search_authors&hl=en&mauthors=label:reinforcement_learning'
base_url = 'https://scholar.google.c... | StarcoderdataPython |
1912396 | # Generated by Django 2.2.4 on 2019-08-13 13:43
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('user', '0001_initial'),
('goo... | StarcoderdataPython |
1707787 | import os
from index import SysConst
if __name__ == '__main__':
folder = SysConst.getDownloadPath()
movieTypes = set(["avi", "mp4", "mkv", "rmvb", "wmv", "iso"])
for fpath, dirs, fs in os.walk(folder):
for filename in fs:
# fullpath = os.path.join(fpath, filename)
... | StarcoderdataPython |
5123755 | # -*- coding: utf-8 -*-
from django.db.models.fields import FieldDoesNotExist
from django.db.models.fields.related import ForeignRelatedObjectsDescriptor
class DataProvider(object):
def __init__(self, model=None, queryset=None, filters={}, fields=[],
related_fields={}, field_mappings=None, orde... | StarcoderdataPython |
1715587 |
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision
import torchaudio
from librosa.filters import mel as librosa_mel_fn
from asr.data import Audio2Mel
path = "/home/ubuntu/data/datasets/data_processed_voc/wav/voc_26_part_65.wav"
vocoder = torch.hub.load('descriptinc/melgan-neurips... | StarcoderdataPython |
8065366 | import pygame
from pygame.locals import *
import gamelib
from elements import Arrow
from elements import Text
class MainGame(gamelib.SimpleGame):
BLACK = pygame.Color('black')
WHITE = pygame.Color('white')
SECOND = 1000
def __init__(self):
super(MainGame, self).__init__('VimHero', MainGam... | StarcoderdataPython |
8000536 |
# 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.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... | StarcoderdataPython |
11223124 | import os
from setuptools import setup
from pypandoc import convert
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-rundbg',
version='0.1.3',
packages=['django_rundbg'],
include_package_data=True,
license='... | StarcoderdataPython |
4949738 | import numpy as np
class SimplePreprocessor(object):
def __init__(self, is_categorical):
numeric_transformer = Pipeline(steps=[
('imputer', SimpleImputer(strategy='median')),
('scaler', StandardScaler())])
categorical_transformer = Pipeline(steps=[
('imputer', Si... | StarcoderdataPython |
97724 | <filename>google/cloud/recommendationengine_v1beta1/types/__init__.py<gh_stars>10-100
# -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# ... | StarcoderdataPython |
11364850 | <gh_stars>1-10
def encode(plain_text):
text = decode(plain_text.lower())
return ' '.join(text[i:i + 5] for i in range(0, len(text), 5))
def decode(ciphered_text):
chars = []
for ch in ciphered_text:
if ch.isalnum():
chars.append(chr(219 - ord(ch)) if ch.islower() else ch)
re... | StarcoderdataPython |
11306349 | # Name: SpatialJoin_AddField
# Description: Join attributes
# Requirements: os module
# Import system modules
import arcpy
import os
# Set local variables
workspace = "F:\\data_test\\fahui_wang\\"
outWorkspace = "F:\\data_test\\fahui_wang\\"
targetFeatures = os.path.join(workspace, "d_04")
joinFeatures = os.path.joi... | StarcoderdataPython |
5047628 | from typing import Optional
def say_hi(name: Optional[str] = None):
if name is not None:
print(f"Hey {name}!")
else:
print("Hello World")
| StarcoderdataPython |
11258321 | import os
import shutil
import re
import argparse
import json
import socket
import time
CONFIG_TEMPLATES_ROOT_PATH = '/cfg-templates/'
CONFIG_OUTPUT_ROOT_PATH = '/config/'
def slugify(value):
"""
Normalizes string, converts to lowercase, removes non-alpha characters,
and converts spaces to hyphens.
""... | StarcoderdataPython |
3358216 | from pathmagic import Dir
import os
from miscutils import Profiler
testdir = Dir.from_home().new_dir("test")
testdir.settings.lazy = True
run = 1000
print("pathmagic")
with Profiler() as magic_create_profiler:
for num in range(run):
testdir.new_file(f"test{num + 1}", "txt").write(f"Hi, I'm file number {... | StarcoderdataPython |
82556 | def reverse(string):
return string[::-1]
print('Gimmie some word')
s = input()
print(reverse(s))
| StarcoderdataPython |
6434033 | """API Handler for hacs_repositories"""
from homeassistant.components import websocket_api
import voluptuous as vol
from custom_components.hacs.share import get_hacs
@websocket_api.async_response
@websocket_api.websocket_command({vol.Required("type"): "hacs/repositories"})
async def hacs_repositories(_hass, connecti... | StarcoderdataPython |
3251483 | import crawler
import psycopg2
from datetime import datetime
def delete():
conn=get_conn()
cur = conn.cursor()
quary = "DELETE FROM crawl_lists"
cur.execute(quary)
conn.commit()
cur = conn.cursor()
quary = "DELETE FROM posts"
cur.execute(quary)
conn.commit()
cur = conn.cursor()
... | StarcoderdataPython |
3219718 | import datetime
import time
class EarthquakeUSGS:
"""
@brief Class that holds earthquake data records.
Class that hold earthquake data, for use with USGIS retrieved quake data.
BRIDGES uses scripts to
continually monitor USGIS site (tweets) and retrieve the latest
quake data for use in stude... | StarcoderdataPython |
11361101 | # Python Standard Library Imports
import json
# Django Imports
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django.http import Http404
from django.urls import reverse
from django.utils.http import (
base36_to_int,
int_to_base36,
)
# HTK Imports
from htk.utils im... | StarcoderdataPython |
8188680 | #
# 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
# ... | StarcoderdataPython |
11324993 | #!/usr/bin/env python3
import json
import os
if not os.path.exists('json-out'):
os.makedirs('json-out')
for file in os.listdir("."):
if file[0:1] == "x":
with open(file) as f:
contents = f.read()
contents = contents[0:(len(contents) - 2)]
try:
conten... | StarcoderdataPython |
6511543 | # Enter your code here. Read input from STDIN. Print output to STDOUT
from collections import deque
d = deque()
N = int(input()) #number of element
if N > 0 and N <= 100:
for _ in range(N):
command = input().split()
if command[0] == "append":
d.append(int(command[1]))
elif comma... | StarcoderdataPython |
8006064 | from haystack.fields import NgramField
try:
from .elasticsearch import SuggestField
except ImportError:
class SuggestField(NgramField):
pass
class SearchQuerySetWrapper(object):
"""
Decorates a SearchQuerySet object using a generator for efficient iteration
"""
def __init__(self, sqs... | StarcoderdataPython |
8087101 | <reponame>shridarpatil/Flask-RestApi
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Exceptions to be raised by every other sub-package"""
__all__ = ['RestApixBaseException', 'ResourceNotFound']
class RestApixBaseException(Exception):
"""Base exception for crux utils."""
pass
class ResourceNotFound(Res... | StarcoderdataPython |
9745189 | <gh_stars>1-10
from datetime import date, datetime
from decimal import Decimal
import itertools
import time
def encode(value):
encoder = encodings.get(type(value))
if encoder is None:
raise ValueError('Can\'t encode type: %s' % type(value))
return encoder(value)
def decode(value):
decoder = d... | StarcoderdataPython |
1685315 | <gh_stars>10-100
'''
@package: pyAudioLex
@author: <NAME>
@module: polarity
Take in a text sample and output the average, standard deviation, and variance
polarity. (+) indicates happy and (-) indicates sad, 0 is neutral.
'''
import nltk
from nltk import word_tokenize
from textblob import TextBlob
import numpy as np... | StarcoderdataPython |
3589455 | # Copyright (C) 2021 Intel Corporation
#
# SPDX-License-Identifier: MIT
import os
import glob
import requests
import json
from deepdiff import DeepDiff
from .utils import config
def test_check_objects_integrity():
with requests.Session() as session:
session.auth = ('admin1', config.USER_PASS)
for... | StarcoderdataPython |
5113575 | <reponame>manoadamro/jason<filename>tests/unit/props/types/test_bool.py
import pytest
from jason import props
def test_validates():
assert props.Bool().load(True)
def test_true_from_string():
assert props.Bool().load("true") is True
def test_false_from_string():
assert props.Bool().load("false") is F... | StarcoderdataPython |
12825614 | #!/usr/bin/env python
from __future__ import print_function
import os
import subprocess
import signal
import time
import glob
import unittest
ZX_SPEC_OUTPUT_FILE = "printout.txt"
ZX_SPEC_TEST_END_MARKER = '-- ZX SPEC TEST END --'
class TestPasses(unittest.TestCase):
@classmethod
def setUpClass(self):
... | StarcoderdataPython |
4936422 | # see https://www.codewars.com/kata/55968ab32cf633c3f8000008/solutions/python
def initials(name):
names = name.split(" ")
ret = ''
for i, name in enumerate(names):
if i == len(names) - 1:
ret += name.capitalize()
break
ret += name[0].upper() + '.'
return ret
pri... | StarcoderdataPython |
1692437 |
def get_lti_value(key, tool_provider):
""" Searches for the given key in the tool_provider and its custom and external params.
If not found returns None """
lti_value = None
if "custom" in key:
lti_value = tool_provider.custom_params[key]
if "ext" in key:
lti_value ... | StarcoderdataPython |
274672 | import pytest
from django.contrib.auth import get_user_model
from pontoon.base.models import Project, Resource
from pontoon.base.utils import (
aware_datetime,
extension_in,
get_m2m_changes,
get_object_or_none,
glob_to_regex,
latest_datetime)
def test_util_glob_to_regex():
assert glob_t... | StarcoderdataPython |
11385480 | from __future__ import print_function
from helper import Helper
import pandas as pd
from mldata.lib.category_converter import CategoryConverter
from mldata.lib.normalizer import Normalizer
class Processor(object):
def __init__(self, csv_file_path, target_column, exclude_column_list=None, category_list=None, posi... | StarcoderdataPython |
11230712 | import random
import requests
from celery import shared_task
from celery.utils.log import get_task_logger
from celery.signals import task_postrun
from django.core.management import call_command
from polls.consumers import notify_channel_layer
logger = get_task_logger(__name__)
@shared_task()
def sample_task(email... | StarcoderdataPython |
6572309 | <reponame>DuJiajun1994/BinaryNetwork
import tensorflow as tf
from tensorflow.python.framework import ops
def binary_identity(inputs, name=None):
graph = tf.get_default_graph()
with ops.name_scope(name, 'BinaryIdentity', [inputs]):
with graph.gradient_override_map({"Sign": "Identity"}):
out... | StarcoderdataPython |
1640429 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2010 <NAME> <<EMAIL>>
# Licensed under the GNU LGPL v2.1 - http://www.gnu.org/licenses/lgpl.html
"""
Automated tests for checking transformation algorithms (the models package).
"""
import logging
import unittest
from gensim.summarization.bm25 import ge... | StarcoderdataPython |
6510944 | from fpdf import FPDF #PDF_In_Columns inherites from this class
"""
This class is used to create PDF files formated into two columns
In the context of Exam PDF Generator, it's only used in for the Exam sheet
"""
class PDF_In_Columns(FPDF):
def __init__(self):
super().__init__()
self.co... | StarcoderdataPython |
5122348 | #!/usr/bin/env python2
import sys
import time
from Nonin import *
finished = False
while not finished:
try:
# device = Nonin3150.get_device()
device = sys.argv[1]
nonin = Nonin3150(device)
current_time = nonin.get_current_time()
finished = True
except Exception:
... | StarcoderdataPython |
8062672 | <gh_stars>10-100
from rlscore.learner import KronRLS
from rlscore.measure import cindex
import davis_data
def main():
X1_train, X2_train, Y_train, X1_test, X2_test, Y_test = davis_data.settingC_split()
learner = KronRLS(X1 = X1_train, X2 = X2_train, Y = Y_train)
log_regparams = range(15, 35)
for log_re... | StarcoderdataPython |
3344988 | from nipype.interfaces.base import (TraitedSpec, File, traits, CommandLine, InputMultiPath,
CommandLineInputSpec)
from nipype.utils.filemanip import fname_presuffix
import os
class ImageReconInputSpec(CommandLineInputSpec):
in_file = File(
exists=True,
argstr='-... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.