id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
9610450 | <gh_stars>1-10
import pytest
import diay
def test_call_with_argument_defaults():
def f(v="foobar"):
return v
i = diay.Injector()
assert i.call(f) == "foobar"
def test_raises_exception_when_args_unknown():
def f(v):
return v
i = diay.Injector()
with pytest.raises(diay.DiayE... | StarcoderdataPython |
3278160 | #%%
import os
try:
os.chdir('/Volumes/GoogleDrive/My Drive/python_code/connectome_tools/')
print(os.getcwd())
except:
pass
#%%
import sys
sys.path.append("/Volumes/GoogleDrive/My Drive/python_code/connectome_tools/")
import pandas as pd
import numpy as np
import connectome_tools.process_matrix as promat... | StarcoderdataPython |
5106429 | <reponame>akineeic/docs<filename>tools/link_detection/link_detection.py
import subprocess
import re
import requests
import urllib3
from concurrent.futures import ThreadPoolExecutor
from threading import Lock
def get_all_file(check_path):
'''
get all the files in the directory.
'''
cmd = 'find %s -type ... | StarcoderdataPython |
3308586 | """ Specify version information about MrProxy
This file is meant to be kept minimal. It is loaded by both this library
and setup.py. This is to avoid having to specify the code in multiple
places. Because of this, this file should remain empty other than the
__version__ itself.
"""
__version__ = "0.4.0"
| StarcoderdataPython |
6558292 | # !/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/3/3 0003 16:56
# @Author : Gpp
# @File : protocol_template.py
class VmessProtocol:
def __init__(self, proxy):
self.v = proxy['v'] if proxy['v'] else ''
self.ps = proxy['ps'] if proxy['ps'] else ''
self.add = proxy['add']... | StarcoderdataPython |
167553 | <reponame>OpenTMI/stf-appium-python-client
from os import environ
from time import sleep
from stf_appium_client import StfClient
client = StfClient(host=environ.get('STF_HOST'))
client.connect(token=environ.get('STF_TOKEN'))
devs = client.get_devices()
client.allocate(devs[0])
sleep(2)
client.remote_connect(devs[0])... | StarcoderdataPython |
6636370 | # -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# (C) British Crown Copyright 2017-2021 Met Office.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions a... | StarcoderdataPython |
244965 | <filename>chmvh_website/gallery/tests/views/test_pet_memoriam_view.py
import pytest
from django.test import RequestFactory
from django.urls import reverse
from gallery.views import BasePatientView, PetMemoriamView
class TestPetMemoriamView(object):
"""Test cases for the pet memoriam view"""
@pytest.mark.dja... | StarcoderdataPython |
3568024 | #!/usr/bin/python3
from google.cloud import vision
from skimage.metrics import structural_similarity
import cv2
import imutils
import io
import json
import numpy
import os.path
import sys
class Charm:
# 1500, 230, (330, 330)
x=1500
y=230
w=330
h=330
x1=210
y1=85
w1=40
h1=30
fi... | StarcoderdataPython |
11275206 | from definitions.ir.dfg_node import *
class BigramGReduce(DFGNode):
def __init__(self, old_node, edge_ids):
assert(str(old_node.com_name) == "bigrams_aux")
com_name = Arg(string_to_argument("bigram_aux_reduce"))
com_category = "pure"
super().__init__(edge_ids[:6],
... | StarcoderdataPython |
3400658 | <filename>atividades/avaliacao-02/a02_02.py
# Apresentação
print('Programa para ordenar um vetor de inteiros maiores que 0')
print()
# Solicita os 15 valores
valores = list()
while (len(valores) < 15):
valor_informado = int(input('Informe um valor: '))
# Rejeita o valor 0 e inferiores à ele
if (valor_inf... | StarcoderdataPython |
223900 | from django.urls import path, include
from product import views
urlpatterns =[
path('latest-products/', views.LatestProductsList.as_view()),
path('products/', views.ProductSearch.as_view()),
path('products/<slug:category_slug>/<slug:product_slug>/', views.ProductDeatails.as_view()),
path('products/<s... | StarcoderdataPython |
201487 | <gh_stars>10-100
#
# Copyright 2011-2013 Blender 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 la... | StarcoderdataPython |
3591393 | <gh_stars>0
import gzip
import xml.etree.ElementTree as ET
def parse_type(tag):
return tag.split('}', maxsplit=1)[1]
def parse_vec(value):
x, y, z = value.split()
return {
'x': float(x),
'y': float(y),
'z': float(z),
}
def parse_rotation(value):
x, y, z, w = value.split... | StarcoderdataPython |
3365962 | # Authors: <NAME> <<EMAIL>>
#
# Custom warnings and error classes used in TracePy.
#
# License: MIT
class NormalizationError(Exception):
""" Custom exception for unnormalized input. """
class NotOnSurfaceError(Exception):
""" Error for rays that do not intersect with a surface. """
class TraceError(Exception... | StarcoderdataPython |
4977813 | #!/usr/bin/env python3
################################################################################
## Copyright 2018 "<NAME>" <thenoviceoof>
##
## 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 Lice... | StarcoderdataPython |
9779851 | from __future__ import unicode_literals
import os
from mopidy import config, ext
__version__ = '1.0.1'
SORT_FIELDS = ['%s %s' % (f, o) for o in ('asc', 'desc') for f in (
'addeddate',
'avg_rating',
'call_number',
'createdate',
'creatorSorter',
'date',
'downloads',
'foldoutcount',
... | StarcoderdataPython |
1792583 | <filename>hardware_func.py
# -*- coding: utf-8 -*-
### hardware_func.py ###
### 功能:将串口传来的ADC数据存储到txt文件中 ###
import serial
import time
import RPi.GPIO as GPIO
class Hardware():
def __init__(self, ser, channel1):
self.ser = ser
self.channel1 = channel1
self.filename = "input_sound.txt"
... | StarcoderdataPython |
1913397 | <reponame>dadasoz/dj-translate
# -*- coding: utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
import collections
import six
import urllib2
import urllib
import re
from fake_useragent import UserAgent
from autotranslate.compat import goslate, googleapiclient
from django.conf import settings
class Bas... | StarcoderdataPython |
9788285 | <reponame>adux/acrozuri<filename>acrozuri/home/migrations/0008_auto_20200211_1133.py
# Generated by Django 2.2.5 on 2020-02-11 10:33
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('home', '0007_member_payed_period'),
]
operations = [
mi... | StarcoderdataPython |
6628447 | <filename>docker/app.py
#! /usr/bin/env python
from flask import Flask
from redis import Redis, RedisError
import os
import socket
# Connect to Redis
redis = Redis(host="redis", db=0, socket_connect_timeout=2, socket_timeout=2)
app = Flask(__name__)
@app.route("/")
def hello():
try:
visits = redis.incr(... | StarcoderdataPython |
9740257 | <filename>continue.py
import torch
import torch.nn as nn
import torchaudio
import numpy as np
import pickle
import torch.nn.functional as F
import torch.optim as optim
import random
import librosa
import matplotlib.pyplot as plt
# torch.set_printoptions(threshold=1000000)
# CONSTANTS
LSTM_INPUT_SIZE = 128 # Input... | StarcoderdataPython |
1979554 | <filename>Aula33/exercicio1/aula33-4/dao/endereco_dao.py
import MySQLdb
from model.endereco import Endereco
class EnderecoDao:
conexao = MySQLdb.connect(host='localhost', database='aulabd', user='root', passwd='')
cursor = conexao.cursor()
def listar_todos(self):
comando_sql_select = "SELECT *... | StarcoderdataPython |
9645733 | <reponame>StoneHuX/buri
#!/usr/bin/env python
"""
Send files to Búri by directly poke-ing them into memory via the CLI.
Usage:
pokefile.py [--offset ADDRESS] <file>
Options:
-h, --help Show usage summary.
-o, --offset ADDRESS Write file starting at ADDRESS. [default: 0x5000]
The ADDRESS c... | StarcoderdataPython |
6657435 | from typing import List
class Solution:
def isNumber(self, s: str) -> bool:
begin, last = 0, len(s) - 1
while begin <= last and s[begin] == ' ':
begin += 1
while begin <= last and s[last] == ' ':
last -= 1
if begin < last and (s[begin] == '+' or s[begin] ==... | StarcoderdataPython |
8135034 | import os
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision
from torchvision import transforms
from torchvision.utils import save_image
from model.model import ApricotCNN2
from model.data_loader import CIFARCustomWrapper
# create sample directory if not exists
sample_dir = 'samples... | StarcoderdataPython |
3343339 | <gh_stars>0
class Destination:
def __init__(self):
self.location = 0
self.loads = []
self.unloads = []
class TradeRoute:
byte_length = 74
unknowns = [(35, 35), (43, 43), (45, 45), (53,53),
(55, 55), (63, 63), (65, 65), (73, 73)]
# The x5 bytes may be related to ... | StarcoderdataPython |
1783067 | import discord
from rx.subject import Subject
class RxBot(discord.Client):
messages = Subject()
edited_messages = Subject()
deleted_messages = Subject()
async def on_message(self, message):
self.messages.on_next(message)
async def on_message_delete(self, message):
self.deleted_me... | StarcoderdataPython |
3484467 | import os
import random
from tqdm import tqdm
import torch
from torch import nn
from torch.backends import cudnn
from torch.utils.data import DataLoader
from torchvision import transforms
from query.graph.hash import Hash as hashnet
from query.graph.loss import HashLoss as hloss
from query.graph.loss import CodeLoss ... | StarcoderdataPython |
12827175 | # Generated by Django 4.0.1 on 2022-03-12 11:05
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('shop', '0002_item_requirement_alter_item_grade'),
]
operations = [
migrations.AddField(
model_name='item',
name='ima... | StarcoderdataPython |
3247117 | <filename>getgist/__main__.py<gh_stars>0
from os import getenv
from click import argument, command, option
from getgist.github import GitHubTools
from getgist.local import LocalTools
GETGIST_DESC = """
GetGist downloads any file from a GitHub Gist, with one single command.
Usage: `getgist <GitHub username> ... | StarcoderdataPython |
6632338 | import torch
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib import rc
from app.utility.logger import Logger
from app.environment.enums import Actions
from datetime import timedelta
class Game:
def __init__(
self,
stock_exchange,
agent,
... | StarcoderdataPython |
1939538 | ##########################################################################
#
# Copyright (c) 2015, Image Engine Design Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistrib... | StarcoderdataPython |
5114656 | from django.contrib import messages
from django.contrib.messages.views import SuccessMessageMixin
from django.urls import reverse_lazy
from django.utils.translation import ugettext as _
from django.views import generic
from django.contrib.auth.mixins import LoginRequiredMixin
from ..forms import ExamForm
from ..models... | StarcoderdataPython |
8172454 | import numpy as np
from numerical_solvers.Burgers_HopfCole import BurgersHopfCole
# Discretisation
n_spatial_vec = [161, 321, 641, 1281, 2561, 5121]
n_temporal = 10**4+1
m = len(n_spatial_vec)
# Error vectors initialisation
l_2_errors = np.zeros(m)
l_max_errors = np.zeros(m)
# Compute solution for each discretisatio... | StarcoderdataPython |
3272464 | <reponame>SarFootball/backend
import datetime
from django.test import TestCase
from autofixture import AutoFixture
from teamlogic.models import Match, MatchInLeague, Tournament
class TestUtils(object):
@staticmethod
def create_match(home_goal, away_goal,
home_goal_first=None, away_goal... | StarcoderdataPython |
4885385 | MICROSERVICES = {
# Map locations to their microservices
"LOCATION_MICROSERVICES": [
{
"module": "intelligence.last_seen.location_lastseen_microservice",
"class": "LocationLastSeenMicroservice"
}
]
}
| StarcoderdataPython |
255397 | ### test examples for the rast_client.py file
def test_somefunction():
pass
| StarcoderdataPython |
9712516 | from Crypto.PublicKey import ECC
from Crypto.Hash import SHA256
from Crypto.Signature import DSS
from utils import hash_str
class Hashable:
def calculate_hash(self):
return hash_str(self.get_block_string())
def create_ecc_sig(self, private_key, passphrase, data):
key = ECC.import_key(private_k... | StarcoderdataPython |
3316917 | <gh_stars>0
from __future__ import division
import inspect
import warnings
from functools import wraps
from time import sleep, time
from threading import Event
from RPi import GPIO
from w1thermsensor import W1ThermSensor
from spidev import SpiDev
from .devices import GPIODeviceError, GPIODeviceClosed, GPIODevice, GP... | StarcoderdataPython |
3229965 | from pydantic import ValidationError
import pytest
import cv2
from labelbox.data.annotation_types.geometry import Point, Line
def test_line():
with pytest.raises(ValidationError):
line = Line()
with pytest.raises(ValidationError):
line = Line(points=[[0, 1], [2, 3]])
points = [[0, 1], [... | StarcoderdataPython |
6555821 | """Created table Tasks_Categories
Revision ID: 83ba3d7345a8
Revises: <PASSWORD>
Create Date: 2021-10-05 16:40:17.866192
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '83ba3d7345a8'
down_revision = '1c172052<PASSWORD>'
branch_labels = None
depends_on = None
... | StarcoderdataPython |
14730 | def som(a, b):
"""Bereken de som van twee getallen. Als de som groter is dan nul return je de som.
Als de som kleiner is dan nul, dan return je nul.
Args:
a (int): het eerste getal
b (int): het tweede getal
"""
pass
assert som(1, 2) == 3
assert som(-1, -2) == -3
assert som(0, ... | StarcoderdataPython |
372287 | <gh_stars>0
from simple_graphql.django.types import ModelClass
class ModelAlreadyRegistered(Exception):
def __init__(self, model_cls: ModelClass):
super().__init__(
f"Model {model_cls.__name__} "
"has already been registered to the GraphQL schema"
)
class MutationAlreadyR... | StarcoderdataPython |
9649997 | from vkwave.types.responses import *
from ._category import Category
from ._utils import get_params
class Users(Category):
async def get(
self,
return_raw_response: bool = False,
user_ids: typing.Optional[typing.List[str]] = None,
fields: typing.Optional[typing.List[UsersFields]] =... | StarcoderdataPython |
9741481 | #import all necessary modules
import logging
from datetime import datetime,timedelta
from airflow import DAG
from airflow.operators.dummy_operator import DummyOperator
from operators.create_tables import CreateTableOperator
from operators.load_tables import LoadTableOperator
from operators.data_quality import DataQua... | StarcoderdataPython |
5198438 | <gh_stars>10-100
"""
murmur-rest
__init__.py
Initialize murmur-rest project.
:copyright: (C) 2014 by github.com/alfg.
:license: MIT, see README for more details.
"""
import os
from flask import Flask
from flask_httpauth import HTTPDigestAuth
import settings
import Ice
# Create Flask app
app = Flask(__name__)
ap... | StarcoderdataPython |
1962431 | <reponame>artberryx/LSD
import copy
import pathlib
import time
import dowel_wrapper
import akro
import numpy as np
import torch
from PIL import Image
from moviepy import editor as mpy
from garage.envs import EnvSpec
from garage.misc.tensor_utils import discount_cumsum
from matplotlib import figure
from matplotlib.patc... | StarcoderdataPython |
3316267 | from mesa import Agent
from utilities import *
class Person_Agent(Agent):
def __init__(self, unique_id, name, model, movement_radius):
super().__init__(unique_id, model)
self.name = name
self.movement_radius = movement_radius
self.current_product = None
self.current_product... | StarcoderdataPython |
8085346 | <gh_stars>0
#!/usr/bin/env python3
# imports go here
import json
#
# Free Coding session for 2015-03-16
# Written by <NAME>
#
def decode(data, default={}):
# subtle bug here:
try:
return json.loads(data)
except:
return default
if __name__ == '__main__':
foo = decode('not json')
... | StarcoderdataPython |
11239040 | <filename>telemetry/telemetry/internal/platform/linux_based_platform_backend_unittest.py
# Copyright 2013 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.
import os
import unittest
from telemetry.core import util
from tele... | StarcoderdataPython |
3538190 | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import numpy
class ConvBlock(nn.Module):
def __init__(self, n_input_feature_maps, n_output_feature_maps, kernel_size_2d, batch_norm = False, pool_stride = None):
super(ConvBlock, self).__init__()
... | StarcoderdataPython |
11342465 | """
Contains base level parents that aren't to be used directly.
"""
from twisted.internet.defer import inlineCallbacks, returnValue
from fuzzywuzzy.process import QRatio
from fuzzywuzzy import utils as fuzz_utils
from src.daemons.server.ansi import ANSI_HILITE, ANSI_NORMAL
from src.daemons.server.objects.exceptions ... | StarcoderdataPython |
268875 | <gh_stars>0
#
# Copyright (c) Dell Inc., or its subsidiaries. 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
#
from _... | StarcoderdataPython |
1851355 | import unittest
from topper.utils.parser import create_parser
class ParserTest(unittest.TestCase):
def setUp(self):
self.parser = create_parser()
def test_arguments_no_mode(self):
parsed = self.parser.parse_args(['--landing_folder', 'landing_folder',
... | StarcoderdataPython |
295556 | application_title = "Inventory"
main_python_file = "index.py"
import sys
from cx_Freeze import setup, Executable
base = None
if sys.platform == "win32":
base = "Win32GUI"
includes = []
include_files = ['themes']
setup(
name = application_title,
version = "0.1",
description = "inv... | StarcoderdataPython |
1886738 | import torch
from syft.frameworks.torch.linalg import inv_sym
from test.efficiency.assertions import assert_time
@assert_time(max_time=40)
def test_inv_sym(hook, workers):
torch.manual_seed(42) # Truncation might not always work so we set the random seed
N = 100
K = 2
bob = workers["bob"]
alice =... | StarcoderdataPython |
3381288 | from django.conf import settings
from django.db import models
class TodoList(models.Model):
"Generated Model"
taskname = models.CharField(
max_length=256,
)
taskdescription = models.TextField()
duedate = models.DateTimeField()
username = models.ForeignKey(
"users.User",
... | StarcoderdataPython |
11201558 | <reponame>orlandofv/sianna
from django.urls import path
from django.contrib.auth import views as auth_views
from users import views
from django.conf.urls import url
app_name = 'users'
username_regex = r'[a-zA-Z0-9_]+'
handler404 = '{app_name}.views.handler404'.format(app_name=app_name)
handler500 = '{app_name}.views... | StarcoderdataPython |
137778 | <reponame>aclarknet/aclarknet-website
from .forms import ContactForm
from django.conf import settings
from django.contrib import messages
from django.core.mail import send_mail
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.utils... | StarcoderdataPython |
1729095 | import sys
sys.path.append('..')
from mtevi.mtevi import *
from mtevi.utils import *
import numpy as np
import torch
import argparse
import os
import math
from BayesianDTI.utils import *
from torch.utils.data import Dataset, DataLoader
from BayesianDTI.datahelper import *
from BayesianDTI.model import *
from BayesianDT... | StarcoderdataPython |
150539 | <gh_stars>0
import numpy as np
import cv2
imPath = "flamingo.jpg"
imPath2 = "target/separated.png"
flamingo = cv2.imread(imPath)
flamHSV = cv2.cvtColor(flamingo, cv2.COLOR_BGR2HSV)
lower = np.array([20,50,50])
upper = np.array([30,100,100])
# Threshold the HSV image to get only blue colors
mask = cv2.inRange(flamHS... | StarcoderdataPython |
1634836 | <gh_stars>0
import streamlit as st
import pandas as pd
import numpy as np
from wordcloud import WordCloud
import matplotlib.pyplot as plt
@st.cache
def load_keyword_data():
keyword_path = 'data/keyword_ratings.csv'
return pd.read_csv(keyword_path)
#################### keywords #####################
de... | StarcoderdataPython |
1708802 | import cv2
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
from matplotlib.figure import Figure
import glob
import os
from typing import Tuple
from scipy.stats import wasserstein_distance
from scipy.cluster.hierarchy import linkage, dendrogram
from scipy.spatial.distance import pdist, square... | StarcoderdataPython |
3339024 | # -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any... | StarcoderdataPython |
8024322 | <gh_stars>1-10
from .index import *
from .account import *
from .contact import *
| StarcoderdataPython |
9639550 | <gh_stars>1-10
import argparse
from itertools import cycle,dropwhile,islice,product
from prettytable import PrettyTable
from sys import exit
notes = ['A','A#','B','C','C#','D','D#','E','F','F#','G','G#']
cycled_notes = cycle(notes)
def generateScale(rootNote,scaleIntervals):
notesIterator = dropwhile(lambda x: x!=ro... | StarcoderdataPython |
3597390 | # Copyright 2017 <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
... | StarcoderdataPython |
9665275 | # -*- coding: utf-8 -*-
import sys, os
extensions = ['sphinx.ext.autodoc', 'sphinx.ext.viewcode']
master_doc = 'index'
autoclass_content = 'both'
project = u'Moodstocks API client'
copyright = u'2013, Moodstocks SAS'
html_theme = "default"
html_theme_options = {
"nosidebar": "true",
}
html_domain_indices = False
... | StarcoderdataPython |
11221606 | import pygame
from pyscroll import BufferedRenderer
class RogueRenderer(BufferedRenderer):
def center(self, coords):
""" center the map on a pixel
float numbers will be rounded.
:param coords: (number, number)
"""
vec = pygame.Vector2(coords[0], coords[1])
camera = ... | StarcoderdataPython |
5065490 | """Loads configuration files and fetches loaded configuration values."""
import json
import logging
from pathlib import Path
from .command import open_file
# Configuration variable names
_REMOTE_NAME = 'remote_name'
_REMOTE_URL = 'remote_url'
_BRANCH = 'branch'
_SOURCE_PATHS = 'source_paths'
_DESTINATION_PATHS = '... | StarcoderdataPython |
325871 | from datetime import datetime
import pytest
from click.testing import CliRunner
from mock.mock import patch
from ecs_deploy import cli
from ecs_deploy.cli import get_client, record_deployment
from ecs_deploy.ecs import EcsClient
from ecs_deploy.newrelic import Deployment, NewRelicDeploymentException
from tests.test_e... | StarcoderdataPython |
313381 | <gh_stars>1-10
import json
import time
from datetime import datetime, timedelta
from mqtt_shared import mqtt_manager as mqtt, \
mqtt_topics as topics
class _Oven():
_TEMP_INCR_MULTIPLYER = 20
_BASE_TEMPERATURE = 22
def __init__(self):
self.device_id = mqtt.get_client_id()
self.state... | StarcoderdataPython |
9674973 | # ActivitySim
# See full license in LICENSE.txt.
import logging
import numpy as np
import pandas as pd
from activitysim.core import simulate
from activitysim.core import tracing
from activitysim.core import pipeline
from activitysim.core import config
from activitysim.core import inject
from activitysim.core import e... | StarcoderdataPython |
11263934 | from detection import Detection
import numpy as np
from scipy.spatial import distance
from skimage.feature import hog
def get_distance(v1,v2):
if(len(v1)==len(v2)):
dist = distance.euclidean(np.array(v1),np.array(v2))
else:
dist = -1
if(dist>1000):
dist=30
return dist
def ge... | StarcoderdataPython |
3211405 | import sys
import filesReading
class Operators:
def __init__(self, name, language, field, end_time, minutes_done):
self.name = name
self.language = language
self.field = field
self.end_time = end_time
self.minutes_done = minutes_done
class Help_Requests:
def __init__... | StarcoderdataPython |
1987988 | import DES
def Test1():
# plain text message. 64-bit.
Msg = '0123456789ABCDEF'
M = DES.hexToBinary(Msg)
# Key. 64-bit.
Key = 'FEDCBA9876543210'
K = DES.hexToBinary(Key)
print('Text Message: ', Msg)
cipher = DES.DES_Encryption_Decryption(K, M, DES.ENCRYPT)
print('E... | StarcoderdataPython |
1960431 | <reponame>veracode-research/python-veralint<gh_stars>0
from veralint.checkers.django.SQLi import CWE89_Django_SQLi_Checker
def register(linter):
linter.register_checker(CWE89_Django_SQLi_Checker(linter))
| StarcoderdataPython |
8016777 | <filename>text_extract.py
# from readability import Readability
# import requests
# import chardet
import re
from extractor import weixin_extractor
from newspaper import Article
def main():
url = "http://mp.weixin.qq.com/s?__biz=MjM5MjIxMTc4OA==&mid=2650763642&idx=1&sn=066a574daec5e9a61bfc221ea9edd2df&scene=0#w... | StarcoderdataPython |
3485455 | import abjad
from .QSchema import QSchema
from .SearchTree import SearchTree
from .UnweightedSearchTree import UnweightedSearchTree
class BeatwiseQSchema(QSchema):
r"""
Beatwise q-schema.
Treats beats as timestep unit.
>>> q_schema = abjadext.nauert.BeatwiseQSchema()
.. container:: exampl... | StarcoderdataPython |
3332397 | #!/usr/bin/env python3
# ########################################################################
# Copyright (c) 2021 Advanced Micro Devices, Inc.
#
# 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 S... | StarcoderdataPython |
1617474 | from urlparse import urlparse
def main(request, response):
try:
code = int(request.GET.first("code", 302))
location = request.GET.first("location", request.url_parts.path +"?followed")
allowed_links = ["http://example.not", "mailto:<EMAIL>", "http://example.not", "foobar:<EMAIL>"]
... | StarcoderdataPython |
1746059 | #!/usr/bin/env python
# Copyright 2016-2020 Biomedical Imaging Group Rotterdam, Departments of
# Medical Informatics and Radiology, Erasmus MC, Rotterdam, The Netherlands
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obt... | StarcoderdataPython |
8028619 | <reponame>kiranhs/ITKv4FEM-Kiran<gh_stars>1-10
from itkalgorithms import *
from itkio import *
| StarcoderdataPython |
1896738 | <gh_stars>0
from flask_wtf import FlaskForm
from wtforms import StringField,TextAreaField,SubmitField,ValidationError
from wtforms.validators import Required,Email
class UpdateProfile(FlaskForm):
bio = TextAreaField('Tell us about you.',validators = [Required()])
submit = SubmitField('Submit')
class Cat... | StarcoderdataPython |
1832380 | <reponame>hwoarang/releng<gh_stars>0
#!/usr/bin/python
#
# This program and the accompanying materials
# are made available under the terms of the Apache License, Version 2.0
# which accompanies this distribution, and is available at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
import datetime
import jinja2
import ... | StarcoderdataPython |
3471241 |
import ipywidgets as ipw
import traitlets as tra
import pandas as pd
import numpy as np
import re
import time
from IPython import get_ipython, display
from threading import Thread
from collections.abc import Iterable
def usename(obj: 'Any') -> str:
'''
usename(obj: Any) -> str
Returns obj.__name__ if... | StarcoderdataPython |
9760075 | import time
import itertools
import contextlib
import PyOpenColorIO as OCIO
import rv
from rv.commands import setStringProperty, setIntProperty, setFloatProperty
@contextlib.contextmanager
def timer(msg):
start = time.time()
yield
end = time.time()
print "%s: %.02fms" % (msg, (end-start)*1000)
def... | StarcoderdataPython |
1886872 | """For packaging and installation."""
import os
from setuptools import setup
import versioneer
filename = os.path.join(os.path.dirname(__file__), 'requirements.txt')
requirements = open(filename).read().splitlines()
setup(
name='wembedder',
packages=['wembedder'],
author='<NAME>',
author_email='<... | StarcoderdataPython |
6665488 | """Test import-as."""
def f(a, b, c):
pass
| StarcoderdataPython |
3327188 | import os
from collections import defaultdict
from datetime import datetime
import random
import requests
import json
import logging, logging.config
import signal
from multiprocessing.dummy import Pool as ThreadPool
from bs4 import BeautifulSoup
from Levenshtein import ratio
from constants import PLS_HEADERS, USER_AGE... | StarcoderdataPython |
9731929 | """Run qt compile for multiple managers."""
import check_lib.check_sub
from qtpy import QtWidgets, QtCore
import resource_man.qt as rsc
RMAN2 = rsc.ResourceManager(prefix='rman2')
rsc.add_manager(RMAN2)
# Register on import outside of main
rsc.register('check_lib.check_sub', 'edit-cut.png', None) # None uses name no... | StarcoderdataPython |
5184537 | from flask import render_template
from . import main
@main.app_errorhandler(404)
def four(errors):
return render_template('four.html'),404
| StarcoderdataPython |
8198752 | <gh_stars>0
import os
import array
import pickle
import urllib
import random
import requests
import numpy as np
import pandas as pd
from PIL import Image
from tqdm import tqdm
import matplotlib.pyplot as plt
from sklearn.manifold import TSNE
from sklearn.decomposition import PCA
from matplotlib.offsetbox import Offse... | StarcoderdataPython |
3314496 | <filename>python/gilded_rose/__init__.py<gh_stars>0
from .gilded_rose import GildedRose, Item
| StarcoderdataPython |
3415742 | #! /usr/bin/env python
"""Draw shapes and patterns from primative forms.
CLASSES
DrawingBase() Base class to define drawable shapes and pattern.
AngledGrid(DrawingBase) Grid of parallel lines angled to the vertical.
Rectangle(DrawingBase) Filled Rectangle
"""
import math
from typing import Tuple, List, Optional
... | StarcoderdataPython |
9602304 | import multiprocessing
import traceback
from .parse import parse_csv, clean_line, spread
def spread_caller_function(**kw):
return spread(store_lines, **kw)
def writer_function(*a, **kw):
print(a, kw)
def store_lines(kw):
process_name = multiprocessing.current_process().name
db_index = k... | StarcoderdataPython |
328938 | <reponame>abinashstack/Flaskapp
from flask_wtf import FlaskForm
from wtforms import StringField,SubmitField,TextAreaField
from wtforms.validators import DataRequired
class SubmitForm(FlaskForm):
title=StringField('Title',validators=[DataRequired()])
submit=SubmitField("Submit")
| StarcoderdataPython |
9638524 | <filename>corpus_file_gen.py<gh_stars>1-10
# Copyright 2017, Mycroft AI 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 requi... | StarcoderdataPython |
1715001 | from .noise_generator import NoiseGenerator, NoiseGeneratorLog, UniformNoiseGenerator
from .prediction import Prediction
from .preprocessing import InputPreprocessor, OutputPreprocessor
from .training import Trainer
__all__ = ['NoiseGenerator', 'NoiseGeneratorLog', 'UniformNoiseGenerator', 'Prediction', 'InputPreproce... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.