id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
3416043 | from typing import List, Union
from discord.ext.commands import Cog as _Cog
class Cog(_Cog):
name: str = None
hidden: bool = False
description: str = None
emoji: Union[str, int] = '❓'
private_guild_id: List[int] = None
| StarcoderdataPython |
5142484 | <filename>weather_forecast/device/tests.py
"""Tests for device application."""
from django.test import TestCase
# Create your tests here.
| StarcoderdataPython |
325330 | # -*- coding: utf-8 -*-
name = u'enum'
version = '2.10'
description = \
"""
enum libraries
"""
requires = []
variants = []
def commands():
import os
enum_libs_path = os.path.join(getenv("PYTHON_LIBS_PATH"), "enum", "%s"%version)
# env.PATH.append(os.path.join(enum_libs_path, 'lib'))
... | StarcoderdataPython |
1793653 | import pytest
from tempdb.utils import Version
@pytest.mark.parametrize("args", [
(),
(None,),
(1, "2"),
(1, 2, "3"),
])
def test_invalid_type(args):
with pytest.raises(TypeError):
Version(*args)
def test_invalid_order():
with pytest.raises(ValueError):
Version(1, None, 3)
| StarcoderdataPython |
3282252 | <reponame>invenio-toaster/invenio-jsonschemas<gh_stars>0
# -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2015-2018 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Module tests."""
from _... | StarcoderdataPython |
390801 | <reponame>rfrye-github/ixnetwork_restpy
# MIT LICENSE
#
# Copyright 1997 - 2020 by IXIA Keysight
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, including without... | StarcoderdataPython |
251063 | <gh_stars>1-10
# -*- coding: utf-8 -*-
"""
Created on Wed Nov 1 11:19:13 2017
@author: Thomas
"""
import numpy as np
import scipy.io
import keras
from keras.models import Sequential
from keras.layers import Dense, Activation
from keras.utils import np_utils
#%% Load dataset
from sklearn.datasets import fetch_mlda... | StarcoderdataPython |
9786632 | <reponame>ConnectionMaster/qgis-earthengine-plugin<gh_stars>100-1000
# Migrating some useful EE utils from https://code.earthengine.google.com/?accept_repo=users/gena/packages
| StarcoderdataPython |
23274 | <reponame>PacktPublishing/-Learn-MongoDB-4.0<filename>chapters/10/src/biglittle/entity/user.py
# biglittle.entity.user
# tell python where to find module source code
import os,sys
sys.path.append(os.path.realpath('../../../src'))
from biglittle.entity.base import Base
class Name(Base) :
formFieldPrefix = 'name_'
... | StarcoderdataPython |
3425120 | <reponame>bowang-lab/gcn-drug-repurposing
from .node_to_node import NodeToNode
class ProteinToProtein(NodeToNode):
def __init__(self, file_path, sep = "\t"):
super().__init__(file_path, sep) | StarcoderdataPython |
11273677 | # Copyright (C) 2020 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
import random
from sqlalchemy.orm import validates
import ggrc
import ggrc.builder
import ggrc.services
from ggrc import db
from ggrc.models import all_models
from ggrc.models.mixins import base
from ggrc.... | StarcoderdataPython |
48720 |
"""
Library to fetch and parse the public Princeton COS courses history as a
Python dictionary or JSON data source.
"""
__version__ = '1.0.0'
__author__ = "<NAME> <<EMAIL>>"
__all__ = [
"CosCourseInstance",
"CosCourseTerm",
"fetch_cos_courses",
]
from princeton_scraper_cos_courses.parsing import CosCo... | StarcoderdataPython |
1899973 | <gh_stars>0
import pandas as pd
def load(data):
data.to_csv('foo.csv')
| StarcoderdataPython |
5117864 | <reponame>noahzhy/qumaishou<gh_stars>0
from pymatting import cutout
cutout(
# input image path
r"img_fusion\image_matting\data\input\20000759811_1.png",
# input trimap path
r"img_fusion\image_matting\data\trimap\20000759811_1.png",
# output cutout path
"cutout.png"
) | StarcoderdataPython |
4942680 | <filename>src/Zbrac.py
#! /bin/env python3
# -*- coding: utf-8 -*-
################################################################################
#
# This file is part of PYJUNK.
#
# Copyright © 2021 <NAME>
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software an... | StarcoderdataPython |
3558993 | <gh_stars>1-10
#!/usr/local/bin/python
"""
dumper.py - Create Database dumps from docker containers
Running multiple services on a docker host with databases, this script
will create dumps from it.
This script did not connect to the Databases over network. It will do a
'docker exec ...' to the remote container and r... | StarcoderdataPython |
4899235 | <filename>cracking_the_coding_interview_qs/16.7/get_max_test.py
import unittest
from get_max import get_max
class Test_Get_Max(unittest.TestCase):
def test_get_max(self):
self.assertEqual(get_max(5, 10), 10)
self.assertEqual(get_max(5, 1), 5)
self.assertEqual(get_max(-5, 1), 1)
self... | StarcoderdataPython |
11223775 | from aws_cdk import (
aws_codecommit as codecommit,
aws_codepipeline as codepipeline,
aws_codebuild as codebuild,
aws_codepipeline_actions as codepipeline_actions,
aws_ecr as ecr,
aws_iam as iam,
core
)
class DockerPipelineConstruct(core.Construct):
def __init__(
self,
... | StarcoderdataPython |
19552 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from typing import Optional
from epicteller.core import redis
from epicteller.core.model.credential import Credential
class CredentialDAO:
r = redis.pool
@classmethod
async def set_access_credential(cls, credential: Credential):
await cls.r.pool.set(... | StarcoderdataPython |
1846370 | <gh_stars>0
import os
import requests
import concurrent.futures
import io
from datetime import datetime,timedelta
import pandas as pd
from pandas import ExcelWriter
from requests.exceptions import HTTPError
from bs4 import BeautifulSoup
from stolgo.nse_urls import NseUrls
from stolgo.helper import get_for... | StarcoderdataPython |
8021405 | <filename>azure-mgmt-consumption/azure/mgmt/consumption/models/consumption_management_client_enums.py
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project r... | StarcoderdataPython |
9655064 | <reponame>brno32/django-serverless-oauth-session<filename>django_serverless_oauth_session/oauth.py
from django.conf import settings
from authlib.integrations.requests_client import OAuth2Session
from django_serverless_oauth_session.models import OAuthToken
from django_serverless_oauth_session.utils import get_optiona... | StarcoderdataPython |
3246688 | """
Gets Materialflowlist UUID and adds it to mapping file(s).
Mapping file must already conform to mapping format.
"""
import pandas as pd
import materialflowlist
from materialflowlist.globals import flowmappingpath
from materialflowlist.mapping import add_uuid_to_mapping
#Add source name here. The .csv mapping fil... | StarcoderdataPython |
1650532 | #!/usr/bin/env python
####################
# Required Modules #
####################
# Generic/Built-in
# Libs
# Custom
from conftest import (
check_key_equivalence,
check_relation_equivalence,
check_detail_equivalence
)
##################
# Configurations #
##################
####################... | StarcoderdataPython |
6550590 | <reponame>noFloat/CNNexample
from Point import *
import datetime,time,math
import numpy as np
import os,re,sys
import goal_address
import shutil
area_users_name='./area_users/'
Distance=0.1#0.1,0.15,0.05,0.01
Time=86400*0.5#0.5,1,1.5,2
similiarity=0.3#0.3-0.6
startTime1=0
startTime2=0
feature2=0.6
feature3=1-feature2
p... | StarcoderdataPython |
9663860 | # !/usr/bin/env python
# -*- coding: UTF-8 -*-
#
#
# ==================
# VIZ D3 Tree - a d3 dendogram
# ==================
import json
import os
import sys
from ..builder import * # loads and sets up Django
from ..utils import *
from ..viz_factory import VizFactory
class Dataviz(VizFactory):
"""
D3 viz ... | StarcoderdataPython |
376538 | from PIL import Image
import os, sys
path = input("Give me a directory: ")
dirs = os.listdir(path)
os.chdir(path)
width = 0
height = 0
for item in dirs:
if os.path.isfile(path+item):
im = Image.open(path+item)
f, e = os.path.splitext(path+item)
imResize = im.resize((f"{width}", f"{height}"... | StarcoderdataPython |
1935256 | <reponame>Peilonrayz/skeleton_py
from skeleton_py.__main__ import main
def test_main():
# type: () -> None
assert main() == "Hello World!"
| StarcoderdataPython |
6578188 | <reponame>zhuchen03/influence
import matplotlib
matplotlib.use('agg')
from matplotlib import pyplot as plt
import numpy as np
import os
import pickle
# from matplotlib import rc
# rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})
# ## for Palatino and other serif fonts use:
# #rc('font',**{'family':'serif... | StarcoderdataPython |
6512772 | <filename>jsk_arc2017_common/node_scripts/image_buffer.py
#!/usr/bin/env python
import rospy
from std_srvs.srv import Trigger
from std_srvs.srv import TriggerResponse
from sensor_msgs.msg import Image
import message_filters
class ImageBuffer(object):
def __init__(self):
self.stamp = None
self.pu... | StarcoderdataPython |
27613 | <filename>Functions_in_Python.py
# File: Functions_in_Python.py
# Description: Creating functions in Python
# Environment: Spyder IDE in Anaconda environment
#
# MIT License
# Copyright (c) 2018 <NAME>
# github.com/sichkar-valentyn
#
# Reference to:
# [1] <NAME>. Creating functions in Python // GitHub platform [Electro... | StarcoderdataPython |
9700974 | <reponame>yoelcortes/thermotree<filename>thermosteam/utils/decorators/forward.py
# -*- coding: utf-8 -*-
# BioSTEAM: The Biorefinery Simulation and Techno-Economic Analysis Modules
# Copyright (C) 2020-2021, <NAME> <<EMAIL>>
#
# This module is under the UIUC open-source license. See
# github.com/BioSTEAMDevelopmentGr... | StarcoderdataPython |
9771679 | <filename>detectionmodels/yolov3/yolov3.py<gh_stars>0
from tensorflow.keras.layers import Input, Lambda
from tensorflow.keras.optimizers import Adam
from tensorflow.keras import Model
from detectionmodels.utils.model_utils import add_metrics
from .loss import yolo3_loss
from .utils import yolo3_body, custom_tiny_yolo3_... | StarcoderdataPython |
9674241 | from multiprocessing import Queue, Process, cpu_count
from context import laminar
from context import laminar_examples as le
def test_converter():
queue = Queue()
def sum_func(sum_list):
return sum(sum_list)
laminar.__converter("test12", sum_func, [2, 4, 6, 8], queue, [], {})
q = queue.get... | StarcoderdataPython |
1778473 | #!/usr/bin/python
import math
def recipe_batches(recipe, ingredients):
comparison = []
if (recipe.keys() == ingredients.keys()):
for key in sorted(ingredients.keys()):
comparison.append((ingredients[key]//recipe[key]))
print(comparison)
if min(comparison) <= 0:
... | StarcoderdataPython |
11260605 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 27 08:49:25 2017
Multiprocessing execution
@author: laci
"""
import multiprocessing as mp
import time
import sparse_methods as m
import sparse_move as sm
import sparse_contract as sc
import graph
startTime = time.time()
lo = 0
up = 15000
g = gr... | StarcoderdataPython |
12837131 | """Exceptions raised by TinyMongo."""
class TinyMongoError(Exception):
"""Base class for all TinyMongo exceptions."""
class ConnectionFailure(TinyMongoError):
"""Raised when a connection to the database file cannot be made or is lost.
"""
class ConfigurationError(TinyMongoError):
"""Raised when so... | StarcoderdataPython |
11387810 | # Generated by Django 3.2.5 on 2021-07-02 15:12
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('comments', '0007_alter_page_id'),
]
operations = [
migrations.AlterField(
model_name='page',
name='slug',
... | StarcoderdataPython |
3336782 | <reponame>Maik93/NURBS-Python
"""
.. module:: sweeping
:platform: Unix, Windows
:synopsis: Provides functions for generating swept geometries
.. moduleauthor:: <NAME> <<EMAIL>>
"""
from copy import deepcopy
from . import linalg
from . import construct
from .exceptions import GeomdlException
from ._utilities ... | StarcoderdataPython |
6554472 | from computations.compute_ppo import benchmark_ppo, train_ppo, evaluate_ppo
from computations.mbo_initial_design import compute_initial_design
from env.create_vec_env import create_vec_env
from computations.mbo_multi_objective_iterations import compute_iterations
from computations.plot_teacher_action import plot_teache... | StarcoderdataPython |
373782 | import json
from science_api_examples.io import ExampleIO
from science_api_examples.utils import get_data_path
if __name__ == '__main__':
with open(get_data_path("example.json"), encoding='utf-8') as f:
input_data = json.load(f)
io_instance = ExampleIO(input_data)
out_data = io_instance.get_out... | StarcoderdataPython |
349170 | <filename>tests/test_Show.py
import pathlib
import unittest.mock
import pytest
import abjad
import abjadext.ipython
def test_success():
"""
Show can process illustrable objects.
"""
staff = abjad.Staff("c'4 d'4 e'4 f'4")
show = abjadext.ipython.Show()
with unittest.mock.patch("IPython.core.d... | StarcoderdataPython |
5085556 | # [기초-1차원배열] 이상한 출석 번호 부르기2(설명)
# <EMAIL>
'''
문제링크 : https://www.codeup.kr/problem.php?id=1094
'''
n = int(input())
m = list(map(int, input().split()))
for i in range(n-1, -1, -1): print(m[i], end=' ') | StarcoderdataPython |
4999819 | <filename>software/examples/tcp_conn.py
import sys
from PIL import Image
sys.path.insert(0,"/home/pi/Capstone-GC/hardware")
from controller import Controller
sys.path.insert(0,"/home/pi/Capstone-GC/software")
from client import Client
from objectdata import ObjectData
controller = Controller()
c = Client()
print("C... | StarcoderdataPython |
11353038 | <filename>pylocator/dialogs.py<gh_stars>1-10
import gtk
import re
from resources import edit_label_dialog, edit_coordinates_dialog, edit_settings_dialog, about_dialog
from gtkutils import str2num_or_err
from colors import gdkColor2tuple, tuple2gdkColor
from events import EventHandler
from shared import shared
def edi... | StarcoderdataPython |
3275901 | from lenstronomy.SimulationAPI.observation_api import SingleBand
__all__ = ['get_noise_sigma2_lenstronomy']
def get_noise_sigma2_lenstronomy(img, pixel_scale, exposure_time, magnitude_zero_point, read_noise=None, ccd_gain=None, sky_brightness=None, seeing=None, num_exposures=1, psf_type='GAUSSIAN', kernel_point_source... | StarcoderdataPython |
8192069 | <reponame>jskolnicki/100-Days-of-Python
import pandas
import os
import csv
os.chdir(os.path.dirname(__file__))
# DON'T ACTUALLY DO IT THIS WAY. PANDAS IS WAY BETTER (obviously)
# with open("weather_data.csv") as file:
# data = csv.reader(file)
# temperature = []
# for line in data:
# if line[1] ... | StarcoderdataPython |
8165437 | <filename>ex018.py
from math import radians, sin, cos, tan
angulo = int(input('insira o angulo a ser analisado: '))
anguloRadiano = radians(angulo)
seno = sin(anguloRadiano)
cosseno = cos(anguloRadiano)
tangente = tan(anguloRadiano)
print(f"""O ângulo de {angulo:.2f} tem:\nSeno de: {seno:.2f}\nCosseno de: {cosseno:.2f}... | StarcoderdataPython |
3343348 | # Taken from the Lasagne project: http://lasagne.readthedocs.io/en/latest/
# License:
# The MIT License (MIT)
# Copyright (c) 2014-2015 Lasagne contributors
# Lasagne uses a shared copyright model: each contributor holds copyright over
# their contributions to Lasagne. The project versioning records all such
# contri... | StarcoderdataPython |
222301 | import utils
import pyspark
import os
import shutil
from pyspark.sql.functions import *
from pyspark.sql.types import *
from pyspark.sql import SparkSession
from azure.storage.blob import BlobClient
from pathlib import Path
from cloudpathlib import CloudPath, AzureBlobClient
# Initialize Spark
spark = SparkSession.bui... | StarcoderdataPython |
11285164 | <filename>python/testing/covariance_test.py
# Copyright(c) 2014, The LIMIX developers (<NAME>, <NAME>, <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/licens... | StarcoderdataPython |
8161947 | <gh_stars>10-100
import os
import sys
# Add path to python source to path.
sys.path.append(os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "python"))
import SmoothParticleNets as spn
import itertools
import numpy as np
import torch
import torch.autograd
from gradcheck import gradcheck
from t... | StarcoderdataPython |
1652655 | import os
import unittest
from aoc.day05.day05 import count_overlapping_coords, get_example_data, get_input_data
class TestDay05(unittest.TestCase):
def test_05a_example(self):
self.assertEqual(5, count_overlapping_coords(get_example_data()))
def test_05a(self):
self.assertEqual(7380, count_... | StarcoderdataPython |
11324593 | <reponame>tooxie/shiva-server
# -*- coding: utf-8 -*-
"""
This module contains the default file upload handler. When a file is uploaded
it is given to this class, which is responsible for storing it and returning
the path to it. If you need to change how or where uploaded files are stored,
extend this class and overloa... | StarcoderdataPython |
9688855 | <filename>components/ehmtx/select/__init__.py
import esphome.codegen as cg
import esphome.config_validation as cv
from esphome.components import select
from esphome.const import (
CONF_ID,
)
CONF_EHMTX = "ehmtx"
select_ns = cg.esphome_ns.namespace("esphome")
EHMTXSelect = select_ns.class_(
"EhmtxSelect", sele... | StarcoderdataPython |
1999695 | <gh_stars>1-10
from collections import OrderedDict
from itertools import chain
def buildquery(operation, *args, **kw):
"""
Return a query string and argument list pair such as:
(
'SELECT * FROM "sometable" WHERE "id" IN (?, ?)',
(2, 3)
)
"""
builder = {
... | StarcoderdataPython |
14105 | <reponame>oserikov/dream
import unittest
import eliza
class ElizaTest(unittest.TestCase):
def test_decomp_1(self):
el = eliza.Eliza()
self.assertEqual([], el._match_decomp(["a"], ["a"]))
self.assertEqual([], el._match_decomp(["a", "b"], ["a", "b"]))
def test_decomp_2(self):
el... | StarcoderdataPython |
11268936 | from unittest import TestCase
from snips_nlu.common.registrable import Registrable
from snips_nlu.exceptions import NotRegisteredError, AlreadyRegisteredError
class TestRegistrable(TestCase):
def test_should_register_subclass(self):
# Given
class MyBaseClass(Registrable):
pass
... | StarcoderdataPython |
4933110 | <gh_stars>0
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Furushchev <<EMAIL>>
from __future__ import print_function
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from cv_bridge import CvBridge
from jsk_topic_tools import ConnectionBasedTransport
import numpy as np
import rospy
im... | StarcoderdataPython |
11333338 | <reponame>caos21/ndust<gh_stars>1-10
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 22 21:10:56 EST 2016
@author: ben
"""
# Using encoding
# -*- coding: utf-8 -*-
__author__ = "<NAME>"
__copyright__ = "Copyright 2017, <NAME>"
__license__ = "Apache v2.0"
__version__ = "0.1.0"
__email__ = "<EMAIL>"
__status__ = "Develop... | StarcoderdataPython |
3314371 | import pytest
@pytest.fixture
def list_of_dicts_json():
return """[
{
"name": "Tom",
"age": 30,
"address": {
"street": ["124 Lincoln St", "West Village"],
"city": "New York",
"state": "NYC"
}
},
... | StarcoderdataPython |
1825319 | """Top-level package for sigR."""
__author__ = """<NAME>"""
__email__ = '<EMAIL>'
__version__ = '0.1.0'
| StarcoderdataPython |
9652510 | # Agent Installation on Client
#!/usr/bin/env python
import os
import sys
from subprocess import check_call
import xml.etree.ElementTree as ET
import base64
try:
import requests
except:
check_call([sys.executable, '-m', 'pip', 'install', '--upgrade', 'pip'])
s = check_call([sys.executable, '-m', 'pip', 'i... | StarcoderdataPython |
3311906 | from .. import db_result
import pymysql
from . import baseSelect
def delById(id, table='projects'):
sql1 = "DELETE FROM " + table + " WHERE id = " + id
sql2 = "SELECT id FROM " + table + " WHERE id = " + id
baseSelect(sql1, (id,))
record_name = ("id")
DR = db_result.DbResult(
re... | StarcoderdataPython |
9687165 | <reponame>enjoy-the-science/brain-texts
from torch.utils.data import Dataset
import numpy as np
class ARDataset(Dataset):
def __init__(self, files_path):
self.files_path = files_path
def __getitem__(self, index):
filepath = self.files_path[index]
data = np.load(filepath)
retu... | StarcoderdataPython |
315321 | <gh_stars>1-10
import inspect
from typing import Collection, _GenericAlias, _SpecialForm, get_type_hints
from di.utils.inspection.module_variables.base import (
Variable,
VariableFilter,
VariableFilterCascade,
)
class ModuleVariablesInspector:
def __init__(self, filters: Collection[VariableFilter]):
... | StarcoderdataPython |
3415936 | <gh_stars>1-10
default_app_config = 'wagtailcommerce.shipping_methods.flat_rate.apps.FlatRateShippingAppConfig'
| StarcoderdataPython |
9756612 | <gh_stars>0
import pandas as pd
from sqlalchemy import create_engine
import psycopg2
operation = input (" press 1 to import or 2 to export ")
df=pd.read_csv('sample.csv',encoding='iso-8859-1')
def import(df):
try:
df.columns=[c.lower() for c in df.columns]
print("create tables\n...")
... | StarcoderdataPython |
1963949 | <filename>decompy/RL/Model/Decision.py
class Decision:
"""
A Decision to hold information for the model to use.
"""
def __init__(self, summary, reward, action):
"""
Decision object to hold information for the model to use.
:param summary: the llvm summary
:type: LLVMSum... | StarcoderdataPython |
328396 | import os
import sys
import glob
import gzip
import multiprocessing
import re
import uuid
from core.log import log
from core.config import HotSOSConfig
class FileSearchException(Exception):
def __init__(self, msg):
self.msg = msg
class FilterDef(object):
def __init__(self, pattern, invert_match=F... | StarcoderdataPython |
3537042 | #!/usr/bin/python
import sys
import urllib
import urllib2
import json
if len(sys.argv) < 4:
print """arguments: host path file [httpauthuser:password]
For example:
./inject.py listeners.localweb /smashpig/globalcollect/listener Tests/Data/PSC/PaymentNoCCDetails.json
"""
exit(-1)
headers = {}
if len(sys.argv) > 4... | StarcoderdataPython |
1720268 | <reponame>ekupura/character-level-cnn
from keras.models import Model, load_model
from keras.optimizers import SGD, Adam, RMSprop
from keras.callbacks import EarlyStopping, TensorBoard, ModelCheckpoint
from sklearn.model_selection import train_test_split
import numpy as np
import pickle
from architecture import simple
f... | StarcoderdataPython |
11397006 | <gh_stars>0
#!/usr/bin/env python
class Node:
def __init__(self, p, v):
self.v = v
self.p = p
if self.p is not None:
self.p.branches.append(self)
self.branches = []
self.prevsuffix = None
self.nextsuffix = None
self.issuffix = self.p is not None
... | StarcoderdataPython |
6690871 | from kombu.serialization import registry as k_registry
from kombu.exceptions import (EncodeError, DecodeError)
def dumps(data):
"""Serializes data using Kombu serializer.
"""
try:
# dumps will convert any strings into json-compatible strings.
content_type, encoding, data = k_registry.dumps... | StarcoderdataPython |
6626226 | # Copyright (c) 2010-2012 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agree... | StarcoderdataPython |
5145937 | from typing import Dict, List
import pandas as pd
from fastapi_crud_orm_connector.utils.database_session import DatabaseSession
class PandasSession(DatabaseSession):
def __init__(self, database: pd.DataFrame):
self.database = database
def get_db(self):
yield self.database
class DictSessio... | StarcoderdataPython |
3509460 | <gh_stars>1000+
from plugin.preferences.main import OPTIONS, OPTIONS_BY_PREFERENCE, OPTIONS_BY_KEY, Preferences
| StarcoderdataPython |
362179 | #!/usr/bin/env python
import sys, os, os.path, shutil, time
import commands, traceback, glob
SCRIPT_PATH = os.path.realpath(__file__)
ConstPath = os.path.dirname(SCRIPT_PATH)
ARCH = "x86"
def genPackage():
try:
global result, ARCH
fp = open(ConstPath + "/arch.txt")
if fp.read().strip("\n\t... | StarcoderdataPython |
3381322 | <gh_stars>0
import pandas as pd
from bs4 import BeautifulSoup as bs
import time
from splinter import Browser
import html5lib
def open_browser():
executable_path = {'executable_path': '/usr/local/bin/chromedriver'}
return Browser('chrome', **executable_path, headless=False)
def scrape():
browser = open_b... | StarcoderdataPython |
1746174 | # GENERATED BY KOMAND SDK - DO NOT EDIT
import komand
import json
class Component:
DESCRIPTION = "Decodes an encoded URL"
class Input:
ENCODED_URL = "encoded_url"
class Output:
DECODED_URL = "decoded_url"
class UrlDecodeInput(komand.Input):
schema = json.loads("""
{
"type": "object"... | StarcoderdataPython |
8123521 | """
Python code to rewrite string IDs from each application CSV file to integers in new
CSVs. In addition to the str2int conversion, the string fields are cleaned up of
unwanted characters and formatted so that they can be ingested into a Neo4j graph
"""
import os
import pandas as pd
from typing import Dict, Union
de... | StarcoderdataPython |
13025 | #!/usr/bin/env python
import vtk
from vtk.util.misc import vtkGetDataRoot
VTK_DATA_ROOT = vtkGetDataRoot()
# this script tests vtkImageReslice with various axes permutations,
# in order to cover a nasty set of "if" statements that check
# the intersections of the raster lines with the input bounding box.
# Image pipel... | StarcoderdataPython |
1970075 | <gh_stars>1-10
# https://circuitdigest.com/tutorial/image-segmentation-using-opencv
import cv2
import numpy as np
# Load the image and keep a copy
image = cv2.imread("approx_contours_and_convex_hull.png")
orig_img = image.copy()
# cv2.namedWindow("Input Image", cv2.WINDOW_NORMAL)
cv2.imshow("Input Image", image)
cv2... | StarcoderdataPython |
4980840 | <filename>sdk/cognitiveservices/azure-cognitiveservices-language-textanalytics/azure/cognitiveservices/language/textanalytics/models/language_input.py<gh_stars>1000+
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# ... | StarcoderdataPython |
9709256 | #!/usr/bin/env python
#------------------------------------------------------------------------------
#
# Suggest splitting of the geometry to smaller rectangular blocks
#
#
# Author: <NAME> <<EMAIL>>
#
#-------------------------------------------------------------------------------
# Copyright (C) 2014 EOX IT Service... | StarcoderdataPython |
4871054 | """Tests for building"""
# Get methods references before compilertools.build
from distutils.command.build_ext import build_ext
BUILD_EXTENSION = build_ext.build_extension
GET_EXT_FILENAME = build_ext.get_ext_filename
GET_EXT_FULLNAME = build_ext.get_ext_fullname
GET_OUTPUTS = build_ext.get_outputs
BUILD_EXT_NEW = bui... | StarcoderdataPython |
11284310 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import socket
host = ''
port = 8888
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind((host, port))
while True:
data, (peer_host, peer_port) = sock.recvfrom(5)
print data
if not data:
break
| StarcoderdataPython |
3599236 | <reponame>Fanteria/discord-text-bot<gh_stars>1-10
EMOTES = {
"ok_hand": "👌",
"thumbsdown": "👎",
"confused": "😕",
"thinking": "🤔",
"rolling_eyes": "🙄",
"middle_finger": "🖕",
}
NUMBER_EMOTES = ["0️⃣", "1️⃣", "2️⃣", "3️⃣", "4️⃣", "5️⃣", "6️⃣", "7️⃣", "8️⃣", "9️⃣"] | StarcoderdataPython |
44438 | from twilio.rest import Client
from twilio.twiml.voice_response import Gather, VoiceResponse
import os
class TwilioNotification:
def __init__(self, sid, auth_token):
self.client = Client(sid, auth_token)
def send_call(self, action_url, contacts):
response = VoiceResponse()
gather = ... | StarcoderdataPython |
6471973 | import pytest
import os
import numpy as np
import h5py
import resqpy.grid as grr
import resqpy.model as rq
import resqpy.property as rqp
import resqpy.olio.write_hdf5 as rqwh
def test_dtype_size(tmp_path):
filenames = ['dtype_16', 'dtype_32', 'dtype_64']
byte_sizes = [2, 4, 8]
dtypes = [np.float16, np.f... | StarcoderdataPython |
8058577 | <filename>packages/jet_bridge_base/jet_bridge_base/filters/model_relation.py
import sqlalchemy
from jet_bridge_base.filters.filter import EMPTY_VALUES
from sqlalchemy import inspect
from jet_bridge_base.db import MappedBase
from jet_bridge_base.filters.char_filter import CharFilter
def filter_search_field(field):
... | StarcoderdataPython |
3266902 | <gh_stars>0
from fastapi import WebSocket
from app.topics.agent import Agent
from app.topics.producer_agent import ProducerAgent
from app.topics.consumer_agent import ConsumerAgent
class Topic():
"""
Defines a topic and setup connection managers for producers and consumers.
"""
def _... | StarcoderdataPython |
1872681 | <filename>neutron/services/logapi/common/db_api.py
# Copyright (c) 2017 Fujitsu Limited
# 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.... | StarcoderdataPython |
4861993 | # def solution(p):
# answer = ""
# return answer
def solution(w):
if w == "":
return ""
else:
left_braket = 0
right_braket = 0
idx = -1
for i in range(len(w)):
if w[i] == "(":
left_braket += 1
elif w[i] == ")":
... | StarcoderdataPython |
1891327 | <filename>python/test.py
from qsdn import Locale as IQLocale
from qsdn import NumericValidator as NumberValidator
from qsdn import LimitingNumericValidator as CryptoCurrencyValidator
import unittest
from decimal import Decimal as D
import decimal
from PyQt5.QtCore import *
from PyQt5.QtGui import *
class NumberOptio... | StarcoderdataPython |
6445885 | # from datetime import datetime
class ZodiacSigns:
def __init__(self, name, first_month, second_month, first_range, sencond_range):
self.name = name
self.first_month = first_month
self.second_month = second_month
self.first = range(first_range[0],first_range[1])
self.seco... | StarcoderdataPython |
4976479 | <filename>terragen/rivers.py<gh_stars>10-100
import numpy as np
from random import randint
from terragen.utils import log, find_neighbors, cell_north, cell_east, cell_west, cell_south
class RiverPart(object):
def __init__(self, river):
self.prev_segments = []
self.next_segments = []
self.r... | StarcoderdataPython |
4835580 | #!/usr/bin/env python
# encoding: utf-8
"""
Tests that stresses are calculated correctly by Asap
Name: testStress.py
Description: Part of the Asap test suite. Tests that stresses are
calculated correctly by calculating various elastic constants from
strain and stress and comparing them with the same constan... | StarcoderdataPython |
107503 | <filename>guests/management/commands/import_guests.py<gh_stars>0
from django.core.management import BaseCommand
from guests import csv_import
from sys import stderr
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument('--file', type=str, help='File to import from.')
pa... | StarcoderdataPython |
243322 | import json
import contextlib
import urllib2
from urllib2 import urlopen
from urllib import urlencode
import sys
if __name__ == '__main__':
fileName = sys.argv[1]
diagnoses = {}
with open(fileName) as f:
content = f.read()
content = json.loads(content)
nodes = content.get('nodes... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.