id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
3260584 | __author__ = 'saeedamen'
from findatapy.market.datavendor import DataVendor
# don't include DataVendorBBG, in case users haven't installed blpapi
# from findatapy.market.datavendorbbg import DataVendorBBG
from findatapy.market.ioengine import IOEngine, SpeedCache
from findatapy.market.market import Market, FXV... | StarcoderdataPython |
3385450 | <reponame>Storvild/wheellog_graph<filename>wheellog_graph.py
import tkinter as tk
from tkinter import ttk
from tkinter import filedialog
import os
import matplotlib
import matplotlib.pyplot
from tk_zoom import ZoomPan
from settings import Settings
from tkinter import messagebox #messagebox.showinfo("Title", "a Tk Messa... | StarcoderdataPython |
5090606 | <filename>scripts/exp8-phases-experiment-grace-join.py<gh_stars>1-10
#!/usr/bin/python3
import matplotlib.gridspec as gridspec
import matplotlib.pyplot as plt
import numpy as np
import csv
import commons
fname_phases = "data/phases-runtime-output-grace-join.csv"
def plot_phases_per_cycle():
plot_fname = "img/p... | StarcoderdataPython |
1717116 | <filename>conflowgen/tests/domain_models/factories/test_container_factory__create_for_large_scheduled_vehicle.py
"""
Check if containers can be stored in the database, i.e. the ORM model is working.
"""
import datetime
import unittest
from conflowgen.domain_models.container import Container
from conflowgen.domain_mod... | StarcoderdataPython |
11267519 | import time
import numpy as np
import sys
debugLevel = "debug"
global_filter = None
def average_completion(exp):
completion_time = 0
number_task = 0
for job in exp.simulation.cluster.jobs:
for task in job.tasks:
number_task += 1
# completion_time += (task.finished_timestamp... | StarcoderdataPython |
8107140 | """
Monkey patch rekey into the list, dict, and set built-in types.
Warning, this depends on the forbiddenfruit library, which
is self proclaimed to be hacky and not production ready.
Use at your own discretion.
usage: just import this package and you're good to go,
eg. `import rekey.native`
"""
from .rekey import ... | StarcoderdataPython |
5053389 | <filename>mysite/ViralScreener/views/views.py<gh_stars>1-10
from .imports import *
#Put all views that don't belong elsewere here
@login_required
def homepage(request):
return render(request, 'ViralScreener/home.html',
context = {"AlertMessage":AlertMessage.objects.all})
@login_required
def employeeScreening(r... | StarcoderdataPython |
11249923 | <reponame>tip308/sysomos
#!/usr/bin/python
"""
Sysomos API wrapper
This is a simple wrapper for the Sysomos MAP REST API v1.0
Author - <NAME>
"""
import requests
__author__ = "<NAME>"
__version__ = "0.1"
class twitter:
def __init__(self,api_key):
self.base_url = "http://ap... | StarcoderdataPython |
3288080 | <filename>all/environments/gym_test.py
import unittest
import gym
from all.environments import GymEnvironment
class GymEnvironmentTest(unittest.TestCase):
def test_env_name(self):
env = GymEnvironment('CartPole-v0')
self.assertEqual(env.name, 'CartPole-v0')
def test_preconstructed_env_name(se... | StarcoderdataPython |
1689434 | <reponame>ThomasTusche/docker-launcher
from tkinter import *
from tkinter import filedialog
from functools import partial
# import dockerfile_generator methods
from dockerfile_generator import *
# import info pop up methods
from info_popup import *
#import os to get the absolut path of the py files and list the temp... | StarcoderdataPython |
3470925 | # -*- coding: utf-8 -*-
"""
Created on Sat Oct 23 14:57:38 2021
@author: kenhu
"""
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn import metrics
from sklearn.ensemble import RandomForestClassif... | StarcoderdataPython |
155454 | """
Console script used to start Labtronyx in Server mode
"""
import os
import argparse
import appdirs
import labtronyx
import labtronyx.gui
labtronyx.logConsole()
def main(search_dirs=None):
parse = argparse.ArgumentParser(description="Labtronyx Automation Framework")
parse.add_argument('-g', dest='gui', ac... | StarcoderdataPython |
8134366 | # -*- coding: utf-8 -*-
import numpy as np
from PIL import Image
import torch
import torch.nn as nn
try:
from net.matting_networks.transforms import trimap_transform, groupnorm_normalise_image
from net.matting_networks.models import build_model
except ModuleNotFoundError:
from matting_networks.transforms i... | StarcoderdataPython |
71581 | <reponame>cosanlab/facesync
# from nltools.version import __version__
from setuptools import setup, find_packages
__version__ = '0.0.9'
# try:
# from setuptools.core import setup
# except ImportError:
# from distutils.core import setup
extra_setuptools_args = dict(
tests_require=['pytest']
)
setup(
n... | StarcoderdataPython |
3440794 | <reponame>wangonya/auto-repair-saas<gh_stars>1-10
from datetime import timedelta
from dateutil import rrule
from django.contrib.auth.mixins import LoginRequiredMixin
from django.db.models import Sum
from django.http import JsonResponse
from django.shortcuts import render
from django.utils import timezone
from django.v... | StarcoderdataPython |
5091938 | <filename>app/tests/test_broadcaster.py
from json import dumps
import pytest
from app.main import app
from app.settings import settings
from httpx import AsyncClient
from tests.conftest import RequestCache
registration_object = {
"connection_type": "ws",
"endpoint": "wss://test",
"transaction_events": [
... | StarcoderdataPython |
6483062 | <filename>app/project/forms.py
from flask_wtf import FlaskForm
from flask_wtf.file import FileAllowed
from wtforms import StringField, SubmitField, FileField, TextAreaField
from wtforms.validators import DataRequired, Length
class PublishProjectForm(FlaskForm):
team_name = StringField('Team name', validators=[Dat... | StarcoderdataPython |
8093460 | <reponame>Tomvictor/ciid-machine-learning<filename>keras/classification/train.py
import pandas as pd
from keras.callbacks import EarlyStopping
from keras.models import Sequential
from keras.layers import Dense
from keras.utils import to_categorical
from numpy import argmax
print("loading datasets..")
train_df_2 = pd.r... | StarcoderdataPython |
1917601 | <gh_stars>1-10
#!/usr/bin/env python3
import argparse
import logging
import os
import sys
import traceback
import Constants
import Mailer
import PumpReport
import PumpStatsWriter
import TuyaLogParser
if __name__ == "__main__":
parser = argparse.ArgumentParser(description = "Compute waterpump stats and email alert")
... | StarcoderdataPython |
1762610 | import re
from w3af.plugins.attack.payloads.base_payload import Payload
from w3af.core.ui.console.tables import table
class ssh_version(Payload):
"""
This payload shows the current SSH Server Version
"""
def api_read(self):
result = {}
result['ssh_version'] = ''
def parse_bina... | StarcoderdataPython |
11381012 | <reponame>LaetitiaBracco/bso-publications<gh_stars>1-10
import logging
import sys
FORMATTER = '%(asctime)s | %(name)s | %(levelname)s | %(message)s'
def get_formatter() -> logging.Formatter:
formatter = logging.Formatter(FORMATTER)
return formatter
def get_console_handler() -> logging.StreamHandler:
co... | StarcoderdataPython |
3421865 | from home.constants import *
from paw.methods import Url
from . import views
app_name = 'home'
urlpatterns = []
url_manager = Url(urlpatterns, views)
url_manager.add_url(EXPRESSION_INDEX, INDEX)
url_manager.add_url(EXPRESSION_INDEX_BASE, INDEX)
url_manager.add_url(EXPRESSION_DASHBOARD, INDEX)
url_manager.a... | StarcoderdataPython |
5145993 | from django.utils.decorators import method_decorator
from drf_yasg.utils import swagger_auto_schema
from rest_framework.decorators import action, api_view, permission_classes
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.response import Response
from rest_framework.viewsets import... | StarcoderdataPython |
6705098 | <gh_stars>1-10
import pygame
from pygame.locals import *
import pymunk
from pymunk import Vec2d
class Bird():
def __init__(self, distance, angle, x, y, space):
self.life = 20
mass = 5
radius = 12
inertia = pymunk.moment_for_circle(mass, 0, radius, (0, 0))
body = pymunk.Body(... | StarcoderdataPython |
1600274 | from django.db import models
# Create your models here.
class Category(models.Model):
name = models.CharField(max_length=255)
parent = models.ForeignKey('self', on_delete=models.SET_NULL, null=True, blank=True)
last_modified = models.DateTimeField(auto_now=True)
def __str__(self):
if self.par... | StarcoderdataPython |
166875 | import os
import os.path
import yaml
class Configuration:
def __init__(self):
self.path = os.path.dirname(__file__)
def get_liq_bands(self):
return self.__load_config(os.path.join(self.path,'liq_bands.yml'))
def get_trades_bands(self):
return self.__load_config(os.path.join(self.p... | StarcoderdataPython |
11334905 | from calendar import timegm
from datetime import datetime
from django.contrib.auth import get_user_model
from django.utils.translation import ugettext_lazy as _
import graphene
from graphene.types.generic import GenericScalar
from . import exceptions
from .settings import jwt_settings
from .shortcuts import get_toke... | StarcoderdataPython |
9707769 | # ##### BEGIN GPL LICENSE BLOCK #####
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distrib... | StarcoderdataPython |
106750 | <gh_stars>1-10
# Written by <NAME> / Freywa
# Original code from https://gitlab.com/parclytaxel/Shinjuku/-/blob/master/shinjuku/nakano.py
import re
from math import gcd, isqrt
from collections import Counter
import lifelib
rule_re = re.compile(r"rule\s*=\s*([A-Za-z0-9/_-]+)\s*$", re.M)
def factors(n):
"""Yield t... | StarcoderdataPython |
9704656 | # SPDX-License-Identifier: MIT
# Copyright (C) 2019 <NAME>
from dosagelib.helpers import joinPathPartsNamer, queryNamer
class TestNamer(object):
"""
Tests for comic namer.
"""
def test_queryNamer(self):
testurl = 'http://FOO?page=result&page2=result2'
assert queryNamer('page')(self, t... | StarcoderdataPython |
1822452 | import sys
import os
import shutil
import glob
import numpy as np
import fortesfit
# Update the python path temporarily to allow the load of the test_model.py module
fortesfitpath = os.path.dirname(fortesfit.__file__)
sys.path.insert(0,fortesfitpath)
from fortesfit import FortesFit_Settings
from fortesfit import For... | StarcoderdataPython |
3501891 | import os
import sys
from setuptools import setup
from setuptools import find_packages
from distutils.util import convert_path
version_properties = dict()
version_filename = convert_path(os.path.join('PyKomoran', '__version__.py'))
with open(version_filename) as version_file:
exec(version_file.read(), version_prop... | StarcoderdataPython |
5058183 | <gh_stars>0
from io import BytesIO
import struct
import numpy as np
def test_uint32_vector_differential():
from eventio.tools import read_vector_of_uint32_scount_differential
from eventio.tools import read_vector_of_uint32_scount_differential_optimized
num = 5
num <<= 1
b = BytesIO(num.to_bytes(1,... | StarcoderdataPython |
8121432 | import pandas as pd
import plotly.graph_objects as ply
analyze = pd.read_pickle('data.pickle')
data = stream[(stream.svewidth == 512) & (stream.version == 'arm19.2')]
labels = [
"total", #0
"loads", #1
"stores", #2
# Loads
"non-sve", #3
"sve", #4
"conti... | StarcoderdataPython |
4891525 | <filename>app/src/tools/AESBlockFeeder.py
# The MIT License (MIT)
#
# Copyright (c) 2014 <NAME>
#
# 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 limita... | StarcoderdataPython |
6689509 | <reponame>DavidKatz-il/pdpipe
"""Testing compatability with scikit-learn's Pipelinel objets."""
import pandas as pd
from pdutil.transform import x_y_by_col_lbl
from sklearn.pipeline import make_pipeline
from sklearn.linear_model import LogisticRegression
import pdpipe as pdp
def _train_df():
return pd.DataFrame... | StarcoderdataPython |
6540231 | <filename>flocker/volume/filesystems/memory.py
# Copyright Hybrid Logic Ltd. See LICENSE file for details.
"""In-memory fake filesystem APIs, for use with unit tests."""
from __future__ import absolute_import
from contextlib import contextmanager
from tarfile import TarFile
from io import BytesIO
from zope.interfa... | StarcoderdataPython |
11358038 | import sys
import os
import seaborn as sns
sns.set_style("whitegrid", {'axes.grid' : False})
import pandas as pd
import numpy as np
import conf
import oncotree
tree = oncotree.Oncotree()
def get_mutations():
obs_mut = pd.read_csv(os.path.join(conf.output_boostdm, 'discovery', 'mutations.tsv'), sep='\t')
... | StarcoderdataPython |
8197933 | <reponame>pierg/crome-logic
from __future__ import annotations
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from crome_logic.specification.temporal import LTL
def find_inconsistencies(specifications: set[LTL]):
# TODO
pass
| StarcoderdataPython |
4918031 | <reponame>SHENOISZ/mk
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('formularios', '0003_auto_20150925_1032'),
]
operations = [
migrations.AddField(
model_name... | StarcoderdataPython |
37136 | <reponame>0--key/lib<gh_stars>0
from csv import DictReader
from petsafeconfig import CSV_FILENAME
from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector
from scrapy.http import Request
from product_spiders.items import Product, ProductLoader
import logging
class PetstreetmallComSpider(B... | StarcoderdataPython |
11314574 | #!/usr/bin/env python3
# ------------------------------------------------------------------
#
# Copyright (C) 2014 Canonical Ltd.
# Author: <NAME> <<EMAIL>>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of version 2 of the GNU General Public
# License published ... | StarcoderdataPython |
1978302 | import time
import warnings
from copy import deepcopy
from abc import ABC, abstractmethod
import SimpleITK as sitk
from ..utils import is_image_dict, nib_to_sitk, sitk_to_nib
from .. import TypeData, TYPE
class Transform(ABC):
"""Abstract class for all TorchIO transforms.
All classes used to transform a samp... | StarcoderdataPython |
1970609 | import unittest
from Evaluator import MatchWordsFromLetters, CalculateWholeScore
class EvaluatorTestCase(unittest.TestCase):
def test_basic_count(self):
letterList = ['c', 'a','t', 'h']
wordList = ['cat', 'mat', 'hat', 'sat']
self.assertListEqual(MatchWordsFromLetters(letterList, wordList),... | StarcoderdataPython |
1795019 | <reponame>1byte2bytes/cpython<filename>Mac/Modules/ctl/ctlsupport.py
# This script generates a Python interface for an Apple Macintosh Manager.
# It uses the "bgen" package to generate C code.
# The function specifications are generated by scanning the mamager's header file,
# using the "scantools" package (customized ... | StarcoderdataPython |
3264983 | <reponame>moonieann/welib<filename>welib/vortilib/elements/VortexLine.py
"""
Reference:
[1] <NAME> - Wind Turbine Aerodynamics and Vorticity Based Method, Springer, 2017
"""
#--- Legacy python 2.7
from __future__ import division
from __future__ import print_function
# --- General
import unittest
import numpy as np
... | StarcoderdataPython |
26210 | # Generated by Django 2.1.7 on 2019-02-14 13:07
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
ope... | StarcoderdataPython |
1676592 | <reponame>amiltonwong/mil-segment-pytorch
# camera-ready
# this file contains code snippets which I have found (more or less) useful at
# some point during the project. Probably nothing interesting to see here.
import pickle
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import numpy as np
... | StarcoderdataPython |
9716355 | __author__ = "<NAME>"
__copyright__ = "Copyright 2015-2019, <NAME>"
__email__ = "<EMAIL>"
__license__ = "MIT"
import os
import re
import sys
import inspect
import sre_constants
import collections
from urllib.parse import urljoin
from pathlib import Path
from itertools import chain
from snakemake.io import (
IOFil... | StarcoderdataPython |
263648 | <filename>sidekick-experimental/sidekick/experimental/magics/base_magics.py
from ..functions import fn
# ------------------------------------------------------------------------------
# DATA MAGICS
# ------------------------------------------------------------------------------
class DataMagicMeta(type):
def __... | StarcoderdataPython |
5018800 | <gh_stars>0
from cleo import Command
from starling_server.main import db
from starling_server.mappers.category_mapper import CategoryMapper
category_mapper = CategoryMapper(db=db)
class CategoryRename(Command):
"""
Rename a category
rename
{group : A category group}
{category : A catego... | StarcoderdataPython |
9746983 | from django import forms
from .models import elgamaluni
class elgamaluniform(forms.ModelForm):
pr = forms.IntegerField(label='Private Key x, x ',widget=forms.TextInput(attrs={
'placeholder':'Enter first private key',
'class': 'form-control',
}))
m = forms.IntegerField(label='... | StarcoderdataPython |
12852293 | import urllib.request
import cv2
import numpy as np
import time
URL = "http://192.168.1.3:8080/shot.jpg"
while True:
img_arr = np.array(bytearray(urllib.request.urlopen(URL).read()),dtype=np.uint8)
img = cv2.imdecode(img_arr,-1)
cv2.imshow('IPWebcam',img)
q = cv2.waitKey(1)
if q == ord("q"... | StarcoderdataPython |
1646120 | <reponame>HanseulJo/COMBO_NKmodel
import os
import pickle
import numpy as np
import progressbar
import torch
from COMBO.experiments.test_functions import generate_random_seed_pestcontrol, generate_random_seed_pair_centroid
from COMBO.experiments.test_functions import PESTCONTROL_N_STAGES, CENTROID_N_EDGES, CENTROID_N... | StarcoderdataPython |
8108946 | #coding=utf-8
# Copyright 2017 - 2018 Baidu 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 required by applicable law or a... | StarcoderdataPython |
52385 | def consume_rec(xs, fn, n=0):
if n <= 0:
fn(xs)
else:
for x in xs:
consume_rec(x, fn, n=n - 1)
| StarcoderdataPython |
1652672 | <reponame>yaricom/Plastic-UNet<gh_stars>1-10
# The script to visualize data collected during training session
from optparse import OptionParser
import h5py
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
plt.style.use('seaborn-white')
import seaborn as sns
sns.set_style("white")
def plot_best_... | StarcoderdataPython |
1946778 | <reponame>erick-otenyo/trends.earth-API
"""SCRIPT SERVICE"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import logging
from gefapi.errors import EmailError
from sparkpost import SparkPost
class EmailService(object):
"""MailService Class"""
... | StarcoderdataPython |
9728330 | # --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# -----------------------------------------------------------------... | StarcoderdataPython |
1791888 | <reponame>dev-11/aws-sandbox
import requests
import bs4
class BooksOfTheMonthService:
def __init__(self, url):
self._url = url
@staticmethod
def get_book_details(divs):
section = divs[0].find('h2').find('em').text.strip()
title = divs[1].find(class_='title').find('a').text.strip()... | StarcoderdataPython |
9704458 | import threading
from django.conf import settings
from django.contrib.sites.shortcuts import get_current_site
from django.core.mail import EmailMessage
from django.template.loader import render_to_string
class EmailThread(threading.Thread):
''' Thread to send email in background. '''
def __init__... | StarcoderdataPython |
11237354 | """
Name: Vaidya
References: Stephani (13.20) p158
Coordinates: Eddington-Finkelstein
Notes: Outgoing Coordinates
"""
from sympy import Function, diag, sin, symbols
coords = symbols("r v theta phi", real=True)
variables = ()
functions = symbols("M", cls=Function)
r, v, th, ph = coords
M = functions
metric = diag(0, -(... | StarcoderdataPython |
11277329 | <reponame>gitter-badger/mlmodels
import re
import sys
from collections import defaultdict
import matplotlib.pyplot as plt
import numpy as np
# f = open(sys.argv[1], "r")
f = open("groundtruth_random_level_1", "r")
folds = defaultdict(lambda: defaultdict(lambda: list()))
for line in f.readlines():
folds[line.spli... | StarcoderdataPython |
11271273 | <filename>languagelab/wsgi.py
"""
WSGI config for languagelab project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/2.2/howto/deployment/wsgi/
"""
import os
# import sys
from django.core.wsgi import get_wsgi_a... | StarcoderdataPython |
11200630 | from typing import Optional
class Registrable(object):
"""
A class that collects all registered components,
adapted from `common.registrable.Registrable` from AllenNLP
"""
registered_components = dict()
default_implementation: Optional[str] = None
@staticmethod
def register(name):
... | StarcoderdataPython |
11265479 | import time
import os
points = 100
clear = lambda: os.system('clear')
print('Правила:')
print('1. Отвечайте односложно и конкретно.')
print('2. Получайте удовольствие от игрового процесса.')
print('Удачи!')
time.sleep(2)
while True:
ans = str(input('Хотите начать со вступления?(да/нет): '))
if (ans == 'Да') or ... | StarcoderdataPython |
3288726 | import pytest
import os
from utils import lambda_decorators
from unittest.mock import MagicMock, patch
from asyncio import get_running_loop
from lambda_templates.lazy_initialising_lambda import LazyInitLambda
from test_utils.test_utils import coroutine_of
@pytest.mark.unit
def test_ssm_params():
called = False
... | StarcoderdataPython |
1966190 | '''Faça um programa que leia o nome completo de uma pessoa, mostrando em seguida o primeiro e o último nome separadamente.
Ex: <NAME>
Primeiro= Ana Último= Souza'''
nome = str(input('Informe o seu nome completo: ')).strip()
primeiro = segundo = nome.split()
print(f'O primeiro nome é {primeiro[0]}.')
print(f'O último ... | StarcoderdataPython |
1966055 | import scrapy
from scrapy.loader import ItemLoader
import pymongo
import sys
import importlib
importlib.reload(sys)
# sys.setdefaultencoding('utf8')
# sys.path.append('../')
from wiki_crawler.items import WikiCrawlerItem
import zhconv
import re
class UrlsSpider(scrapy.Spider):
name = 'urls'
allowed_domains =... | StarcoderdataPython |
5195851 | from setuptools import setup, find_packages
setup(name='opposite',
version='1.0',
description='False',
author=['<NAME>', '<NAME>'],
url='https://github.com/momirza/opposite',
packages=find_packages(exclude=['test']),
)
| StarcoderdataPython |
6463243 | # Time complexity: O(ls*lt)
# Approach: Take frequency list for both the strings and keep checking for the same frequency whenever the number of chars matches.
class Solution:
def minWindow(self, s: str, t: str) -> str:
ls, lt = len(s), len(t)
if ls<lt:
return ""
fs, ft = [0]*25... | StarcoderdataPython |
4907632 | from .base import _SaveBase
from application.src.forms.form import Form
class SaveSingle(_SaveBase):
@classmethod
def parse_request(cls, raw: "flask.request.form",
files: "flask.request.files") -> list:
save_data = {}
save_data["sample"] = Form.parse_simple(raw, "sample... | StarcoderdataPython |
6515900 | from . import secp256k1
from . import bn128
from . import optimized_bn128
| StarcoderdataPython |
115346 | from Child import Child
from Node import Node # noqa: I201
# These nodes are used only in code completion.
COMPLETIONONLY_NODES = [
# type
Node('CodeCompletionType', kind='Type',
children=[
Child('Base', kind='Type', is_optional=True),
Child('Period', kind='Token',
... | StarcoderdataPython |
338304 | # -*- 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or... | StarcoderdataPython |
12808482 | <reponame>pootle/bluepystepper
#!/usr/bin/env python3
from bluedot import BlueDot
from signal import pause
import unipolarDirect
class bluemotor():
def __init__(self):
self.motor=unipolarDirect.StartMotor( name='unitest')
self.speed = 0
self.speedlimit=self.motor['settings/maxrpm'].getCurre... | StarcoderdataPython |
1927914 | <filename>tests/test_variable.py
"""Test: variable."""
import pytest
from gibica.types import Int, Float, Bool
from gibica.exceptions import LexicalError, SementicError
@pytest.mark.parametrize(
'input, expected',
[
('let a=4;', {'a': Int(4)}),
('let a=10;', {'a': Int(10)}),
('let a ... | StarcoderdataPython |
9700931 | <gh_stars>0
"""Database."""
from logging import getLogger
from typing import cast
from sqlalchemy import inspect
from sqlalchemy.engine.reflection import Inspector
from radikopodcast import Session
from radikopodcast.database.models import Base
class Database:
"""Database."""
def __init__(self) -> None:
... | StarcoderdataPython |
1812811 | import json
import os
#from os import makedirs, rename
from os.path import exists, basename, splitext
import copy
import random
import matplotlib
from glob import glob
import time
from shutil import copyfile, rmtree
matplotlib.use('TkAgg')
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from properties im... | StarcoderdataPython |
12848602 | from typing import Type
from elliptic.Kernel.Context import ContextDelegate
from elliptic_meshql.Selector import SelectorImplementationBase
class LoopDelegate(ContextDelegate):
loop_name = ''
def __init__(self, context, unique_id):
super().__init__(context, unique_id)
self.loop_var_prefix ... | StarcoderdataPython |
4937795 | """TRPO-compatible feedforward policy."""
import tensorflow as tf
import numpy as np
from hbaselines.base_policies import Policy
from hbaselines.utils.tf_util import create_fcnet
from hbaselines.utils.tf_util import create_conv
from hbaselines.utils.tf_util import print_params_shape
from hbaselines.utils.tf_util impor... | StarcoderdataPython |
3577499 | <reponame>yamaken1343/gyoseki-archive
from django import template
register = template.Library()
@register.filter("replace_comma_and")
def replace_comma_and(value):
return value.replace(",", " and")
| StarcoderdataPython |
386511 | from typing import Dict
from fastapi.testclient import TestClient
from sqlalchemy.orm import Session
from app.database import crud
from app.core.config import settings
from app.database.models.user import User
from app.database.schemas.user import UserCreate, UserUpdate
from app.tests.utils.utils import random_email,... | StarcoderdataPython |
4904352 | ####################################################
#
# This Work is written by <NAME> <nikolai>
#
# Contact: <EMAIL>
#
# Copyright (C) 2018-Present <NAME>
#
####################################################
####################################################
# IMPORT STATEMENTS
#################################... | StarcoderdataPython |
3357796 | # Copyright (c) The InferLO authors. All rights reserved.
# Licensed under the Apache License, Version 2.0 - see LICENSE.
import numpy as np
from inferlo import PairWiseFiniteModel
from inferlo.pairwise.optimization.map_lp import map_lp
from inferlo.testing import grid_potts_model, tree_potts_model, \
line_potts_m... | StarcoderdataPython |
6609217 | <filename>collections/collections.bzl<gh_stars>1-10
# Copyright (c) 2017 <NAME>
# Licensed under Apache License v2.0
load(
":internal.bzl",
"DEFAULT_TARGET_STRUCT_KEYS",
"default_none",
)
# An important note about functions in this file. Bazel does not support recursion, so this file
# uses a loop with a ... | StarcoderdataPython |
1629340 | import serial
import threading
import time
from messages import ProtoBuffableMessage, DripRecordedMessage, SetCurrentHeightMessage
class Communicator(object):
def send(self, message):
raise NotImplementedError()
def register_handler(self, message_type, handler):
raise NotImplementedError()
... | StarcoderdataPython |
8073984 | import numpy as np
import os
import sys
import cv2
import time
import queue
import argparse
from tqdm import tqdm
import threading
from constants import *
parser = argparse.ArgumentParser(description='Preprocess SegNet Data')
parser.add_argument('--data_root', required=True)
parser.add_argument('--mask_dir', required... | StarcoderdataPython |
3550139 | <filename>codes/runs.py
import os
import json
import logging
import argparse
import numpy as np
import torch
from torch.utils.data import DataLoader
from models import KGEModel, ModE, HAKE
from data import TrainDataset, BatchType, ModeType, DataReader
from data import BidirectionalOneShotIterator
def parse_args(a... | StarcoderdataPython |
3231237 | <gh_stars>0
# -*- coding: utf-8 -*-
"""
@created on: 2/23/20,
@author: <NAME>,
@version: v0.0.1
@system name: badgod
Description:
..todo::
"""
import pandas as pd
import random
import h5py
import numpy as np
import pickle
from sklearn.model_selection import StratifiedShuffleSplit
def subject_level_splitting(file):... | StarcoderdataPython |
362819 | <filename>pychron/experiment/automated_run/automated_run.py
# ===============================================================================
# Copyright 2011 <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 ... | StarcoderdataPython |
142361 | import os
import yaml
settings = False
cwd = os.getcwd()
path = "%s/%s" % (os.getcwd(), '/.gitconsensus.yaml')
def getSettings():
global settings
return settings
def reloadSettings():
global settings
if os.path.isfile(path):
with open(path, 'r') as f:
settings =... | StarcoderdataPython |
5196103 | <filename>pyqt_viewer_widget/__init__.py
from .viewerWidget import * | StarcoderdataPython |
3212523 | import json
import os
config_path = os.path.join(os.path.dirname(__file__), "..", "..", "config.json")
config = None
def __load_config():
global config
try:
with open(config_path, "r") as jsonfile:
config = json.load(jsonfile)
except FileNotFoundError:
print("Configuration fi... | StarcoderdataPython |
44812 | """SQLAlchemy models and utility functions for Sprint."""
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class Record(db.Model):
id = db.Column(db.Integer, primary_key=True)
datetime = db.Column(db.String(25))
value = db.Column(db.Float, nullable=False)
def __repr__(self):
return... | StarcoderdataPython |
6416857 | import subprocess
sp = subprocess.Popen(['cargo', 'run', '--example', 'hello'], stdout=subprocess.PIPE)
stdout = sp.communicate()[0].decode("utf-8")
lines = stdout.splitlines()
assert lines == ["life before main", "main"], "got %s" % lines
print("Test Passed")
| StarcoderdataPython |
1974482 | from typing import Optional, Union
from pydantic import BaseModel, Field, validator
from app.airtable.base_school_db import guides_schools as airtable_guides_schools_models
from app.airtable.response import AirtableResponse
class AirtablePartnerFields(BaseModel):
synced_record_id: Optional[str] = Field(alias="S... | StarcoderdataPython |
9669499 | <filename>geoq/accounts/urls.py
from django.conf.urls import patterns, include, url
from django.views.generic import RedirectView
from django.conf import settings
from accounts.views import OnlineUserView
from forms import SignupFormExtra
from django.contrib.auth.decorators import login_required
from userena import v... | StarcoderdataPython |
342013 | <filename>jactorch/models/vision/vgg.py<gh_stars>100-1000
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# File : vgg.py
# Author : <NAME>
# Email : <EMAIL>
# Date : 03/31/2018
#
# This file is part of Jacinle.
# Distributed under terms of the MIT license.
import math
import functools
import torch.nn as nn
impo... | StarcoderdataPython |
6612247 | # for04.py
'''
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100
'''
for i in ran... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.