id stringlengths 1 7 | text stringlengths 6 1.03M | dataset_id stringclasses 1
value |
|---|---|---|
3306757 | <gh_stars>0
# ##### 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 progra... | StarcoderdataPython |
3267410 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
import subprocess
import tempfile
#TODO: Cahge scrot backend to ImageMagic
# Edit the image
# https://wiki.archlinux.org/index.php/Taking_a_Screenshot
SCREENSHOT_SOUND = '/usr/share/sounds/scru_shot.wav'
class ScrotNotFound(Exception):
"""scrot must be installe... | StarcoderdataPython |
165875 | <filename>sql_queries.py
# DROP TABLES
songplay_table_drop = "DROP TABLE IF EXISTS f_songplays;"
user_table_drop = "DROP TABLE IF EXISTS d_users;"
song_table_drop = "DROP TABLE IF EXISTS d_songs;"
artist_table_drop = "DROP TABLE IF EXISTS d_artists;"
time_table_drop = "DROP TABLE IF EXISTS d_times;"
# CREATE TABLES
... | StarcoderdataPython |
104574 | <filename>neurokit2/complexity/entropy_differential.py
import numpy as np
import pandas as pd
import scipy.stats
def entropy_differential(signal, base=2, **kwargs):
"""**Differential entropy (DiffEn)**
Differential entropy (DiffEn; also referred to as continuous entropy) started as an
attempt by Shannon ... | StarcoderdataPython |
47237 | import sqlite3
import datetime
import time
import logging
import os
from bot_constant import CQ_ROOT
CQ_IMAGE_ROOT = os.path.join(CQ_ROOT, r'data/image')
logger = logging.getLogger("CTB." + __name__)
class FileDB:
def __init__(self, db_name: str):
self.conn = sqlite3.connect(db_name, check_same_thread=F... | StarcoderdataPython |
3366727 | #!/usr/bin/python
from datetime import datetime
from datetime import timedelta
#every = 4.9578 # ms
every = 120
# returns the elapsed milliseconds since the start of the program
def millis():
dt = datetime.now() - start_time
ms = (dt.days * 24 * 60 * 60 + dt.seconds) * 1000 + dt.microseconds / 1000.0
re... | StarcoderdataPython |
1763179 | <filename>pycuda/sparse/inner.py
from __future__ import division
from __future__ import absolute_import
import pycuda.driver as drv
import pycuda.gpuarray as gpuarray
import atexit
STREAM_POOL = []
def get_stream():
if STREAM_POOL:
return STREAM_POOL.pop()
else:
return drv.Stream()
class ... | StarcoderdataPython |
1743658 | # Copyright 2020 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | StarcoderdataPython |
1677310 | from django.urls import path
from django.contrib.auth.decorators import login_required
from .views import HomePageView, ProfileView, ProfileEditView
urlpatterns = [
path('', HomePageView.as_view(), name='home'),
path('profile', login_required(ProfileView.as_view()), name='profile'),
path('profile/edit', l... | StarcoderdataPython |
1669822 | <gh_stars>0
# coding=utf-8
# Distributed under the MIT software license, see the accompanying
# file LICENSE or http://www.opensource.org/licenses/mit-license.php.
from dft.core.dftnode import dftNode
from dft.generated.dft_pb2_grpc import AdminAPIServicer
class AdminAPIService(AdminAPIServicer):
# TODO: Separat... | StarcoderdataPython |
3399751 | <filename>main/gui/Frames/HomeFrame.py
from tkinter import Button, Frame
import os
from main.gui.Utilities.Settings import Settings
import subprocess
def launchVisualizationTool(path):
os.system("python " + path)
'''
The welcoming frame of the app
Inherits from Frame
Shows three buttons: create mod... | StarcoderdataPython |
3272712 | # -*- coding: utf-8 -*-
from requests import Response
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.response import HTTPResponse
from requests.packages.urllib3.poolmanager import PoolManager
class MiddlewareHTTPAdapter(HTTPAdapter):
"""An HTTPAdapter onto which :class:`BaseMiddleware <... | StarcoderdataPython |
3265110 | from .path_manager import PathManager
from .path_handler import PathHandler, NativePathHandler
from .http_path_handler import HTTPURLHandler
from .redirect_path_handler import RedirectPathHandler
from .utils import file_lock
__all__ = ["PathManager", "PathHandler", "NativePathHandler", "HTTPURLHandler", "RedirectPathH... | StarcoderdataPython |
3205916 | """Setup for the texoopy package."""
import setuptools
with open('README.md') as f:
README = f.read()
setuptools.setup(
author="",
author_email="",
name='texoopy',
license='',
description='TeXooPy (texoopy) is a Python module that tackles the handling of TeXoo style JSON data.',
version=... | StarcoderdataPython |
1693316 | <reponame>mome0320/EZ-Bot
import discord
from discord.ext import commands
class Userinfo(commands.Cog):
def __init__(self, client):
self.client = client
# Commands
@commands.command()
async def 유저정보(self, ctx):
if (ctx.message.mentions.__len__() > 0):
for user in ctx.messa... | StarcoderdataPython |
1644953 | <filename>brFinance/scraper/cvm/search.py
import re
import time
from abc import ABC, abstractmethod
from datetime import datetime
from typing import Tuple, Any
import lxml.html as LH
import pandas as pd
from selenium import webdriver
from brFinance.utils.browser import Browser
class Search(ABC):
"""
Perform... | StarcoderdataPython |
1713253 | """
Copyright 2013 <NAME>
This file is part of CVXPY.
CVXPY is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
CVXPY is distributed in the ho... | StarcoderdataPython |
3334401 | # -*- coding: utf-8 -*-
import wx
class MyFrame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, -1, "Menu01 Demo")
wx.Panel(self)
menu_bar = wx.MenuBar() # 创建菜单栏,不需要任何参数
self.menu1 = wx.Menu() # 创建菜单
self.str1 = self.menu1.Append(-1, "aaa") # 在... | StarcoderdataPython |
50358 | """Random Forest classification and computation of assessment metrics."""
import numpy as np
from imblearn.over_sampling import RandomOverSampler
from imblearn.under_sampling import RandomUnderSampler
from sklearn import metrics
from sklearn.ensemble import RandomForestClassifier
from raster import is_raster
def tr... | StarcoderdataPython |
1788026 | <gh_stars>0
#-*-coding: utf-8-*-
from pyautogui import screenshot
from os import chdir, mkdir
from datetime import date
from time import sleep
if __name__ == '__main__':
while True:
try:
chdir("C:\\{}".format(date.today()))
except:
mkdir("C:\\{}".format(date.today()))
else:
break
count = 1
while Tru... | StarcoderdataPython |
3215578 | <reponame>srihari-nagaraj/anuvaad
from anuvaad_auditor.loghandler import log_info
from anuvaad_auditor.loghandler import log_exception
from anuvaad_auditor.loghandler import log_debug
from collections import namedtuple
from src.utilities.region_operations import collate_regions, get_polygon,sort_regions, remvoe_regions... | StarcoderdataPython |
3236514 | '''
Created on Mar 1, 2017
@author: PJ
'''
from Scouting2017.model.reusable_models import Competition, Team, Match
from Scouting2017.model.models2017 import ScoreResult
from django.core.urlresolvers import reverse
from django.http.response import HttpResponseRedirect
from django.views.generic.base import TemplateView
... | StarcoderdataPython |
197913 | <filename>favicons/_constants.py<gh_stars>1-10
"""Static values for one way import."""
SUPPORTED_FORMATS = (".svg", ".jpeg", ".jpg", ".png", ".tiff", ".tif")
HTML_LINK = '<link rel="{rel}" type="{type}" href="{href}" />'
ICON_TYPES = (
{"image_fmt": "ico", "rel": None, "dimensions": (64, 64), "prefix": "favicon"... | StarcoderdataPython |
1735709 | <gh_stars>1000+
import os
import sys
from datetime import datetime
from unittest import TestCase
import pytest
from six.moves import cStringIO as StringIO
from pyinfra.operations import server
from pyinfra_cli.exceptions import CliError
from pyinfra_cli.util import get_operation_and_args, json_encode
class TestCliU... | StarcoderdataPython |
66352 | <reponame>Muntasir-Mahmud/Django-GraphQL-Test
# Generated by Django 3.1.3 on 2021-01-09 03:58
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('quiz', '0002_auto_20210109_0939'),
]
operations = [
migration... | StarcoderdataPython |
13800 | <reponame>JihoChoi/BOJ
"""
TAG: 0-1 Knapsack Problem, Dynamic Programming (DP), O(nW)
References:
- https://www.geeksforgeeks.org/0-1-knapsack-problem-dp-10/
weights and values of n items, capacity -> max value
"""
N, W = map(int, input().split()) # number of items, capacity
weights = []
values = []
for i in... | StarcoderdataPython |
194450 | <gh_stars>0
import json
import logging
from pathlib import Path
from random import shuffle
import discord
from discord.ext import commands
log = logging.getLogger(__name__)
game_recs = []
# Populate the list `game_recs` with resource files
for rec_path in Path("bot/resources/evergreen/game_recs").glob("*.json"):
... | StarcoderdataPython |
151891 | <filename>memae-anomaly-detection/models/loss.py
import torch
def get_memory_loss(memory_att):
"""The memory attribute should be with size [batch_size, memory_dim, reduced_time_dim, f_h, f_w]
loss = \sum_{t=1}^{reduced_time_dim} (-mem) * (mem + 1e-12).log()
averaged on each pixel and each batch
2. ave... | StarcoderdataPython |
4833497 | import datetime
import json
import logging
import stripe
from braces.views import LoginRequiredMixin
from channels import Channel
from django.conf import settings
from django.contrib import messages
from django.core.urlresolvers import reverse
from django.http import (
HttpResponse,
HttpResponseRedirect,
)
fro... | StarcoderdataPython |
1757511 | <filename>funcionalidades/consulta.py<gh_stars>0
import requests
class Consulta:
def consultar(self):
self.resultado = ''
cep = self.tela_buscador.input_cep.text()
url = requests.get(f'https://viacep.com.br/ws/{cep}/json/')
try:
endereco = url.json()
if "er... | StarcoderdataPython |
4839216 | <filename>examples/groups.py
from roonapi import RoonApi
appinfo = {
"extension_id": "python_roon_test",
"display_name": "Python library for Roon",
"display_version": "1.0.0",
"publisher": "gregd",
"email": "<EMAIL>",
}
# Can be None if you don't yet have a token
token = open("mytokenfile").read()... | StarcoderdataPython |
82752 | """Folder structure of the platform."""
class Folders:
"""Class containing the relevant folders of the platforms.
The members without underscore at the beginning are the exported (useful)
ones. The tests folders are omitted.
"""
_ROOT = "/opt/dike/"
_CODEBASE = _ROOT + "codebase/"
_DATA ... | StarcoderdataPython |
1795792 | #!/usr/bin/python
# -*- coding: utf-8 -*-
from pytunegen.constants import *
import random
import time
class TuneGen:
"""Tune generator"""
def __init__(self, seed = None, music_length = 50,
scale = None, bpm = None, time_sig = None,
note_jump_limit = 2.2, silence_percent = 1,... | StarcoderdataPython |
1735936 | ##########################################################################
# MediPy - Copyright (C) Universite de Strasbourg, 2011
# Distributed under the terms of the CeCILL-B license, as published by
# the CEA-CNRS-INRIA. Refer to the LICENSE file or to
# http://www.cecill.info/licences/Lice... | StarcoderdataPython |
1761393 | from django import forms
from .models import FormModel
class Forms(forms.ModelForm):
class Meta:
# in hindsight should have copied this App... then made...now server busted | StarcoderdataPython |
3280049 | <filename>convert.py
from absl import app, flags, logging
from absl.flags import FLAGS
import numpy as np
from yolov3_tf2.models import YoloV3, YoloV3Tiny
from yolov3_tf2.utils import load_darknet_weights
import tensorflow as tf
flags.DEFINE_string('weights', './data/yolov3.weights', 'path to weights file')
flags.DEFI... | StarcoderdataPython |
3249510 | from Node import Node
import random as r
def accept(currentIteration, iterations):
return r.random() < (currentIteration / iterations)
class Operation(object):
BACK_MUTATION = 0
DELETE_MUTATION = 1
SWITCH_NODES = 2
PRUNE_REGRAFT = 3
NUMBER = 4
def __init__(self, type, node_name_1 = None... | StarcoderdataPython |
70532 | """Message types."""
from functools import lru_cache
from typing import Union, Optional, Type
from typing_extensions import get_args
from . import message_definitions as defs
from ..constants import MessageId
MessageDefinition = Union[
defs.HeartbeatRequest,
defs.HeartbeatResponse,
defs.DeviceInfoRequest... | StarcoderdataPython |
1745545 | <reponame>tvuong123/espnet<filename>espnet/__init__.py
import pkg_resources
try:
__version__ = pkg_resources.get_distribution('espnet').version
except Exception:
__version__ = '(Not installed from setup.py)'
del pkg_resources
| StarcoderdataPython |
11924 | <filename>tardis/model/tests/test_csvy_model.py
import numpy as np
import numpy.testing as npt
import tardis
import os
from astropy import units as u
from tardis.io.config_reader import Configuration
from tardis.model import Radial1DModel
import pytest
DATA_PATH = os.path.join(tardis.__path__[0],'model','tests','data'... | StarcoderdataPython |
3221549 | import os
import time
import boto3
from botocore.exceptions import ClientError
from botocore.client import Config
from django.utils.crypto import get_random_string
from storages.utils import setting, lookup_env
def get_bucket_name():
return setting("AWS_STORAGE_BUCKET_NAME") or lookup_env(
["DJANGO_AWS_S... | StarcoderdataPython |
114182 | import string
class strprocess:
"""add all extra processing method """
def __init__(self):
self.data=""
self.tags=["</p>","</br>","<br/>","<br>","<p>","</P>"]
self.marks=["/","?","-","!","@","#","$","%","^","*","(",")",";","{","}","~"]
def makehtml(self,data):
self.data="<"+"... | StarcoderdataPython |
3304473 | <reponame>NaulaN/PyNoSoucisGame_Prototype
from time import time
from pygame.time import Clock
class Fps( object ):
""" Fps( ) -> Frames rate dependency. """
fps_foreground = 60
fps_background = 30
fps_limit = 60
__target_fps = 60
__s = 0
enable_fps_on_screen = False
benchmark = False
... | StarcoderdataPython |
1782895 | # Copyright (C) 2015 Nippon Telegraph and Telephone Corporation.
#
# 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 appli... | StarcoderdataPython |
32775 | <filename>code/HHV2020_07/Adafruit_Trinket_Neopixel_Strip_Cycle/main.py
import board, time
import neopixel
# Define Neopixels
LED7_PIN = board.D0 # pin that the NeoPixel is connected to
# Most Neopixels have a color order of GRB or GRBW some use RGB
LED7_ORDER = neopixel.GRB # pixel color channel order
# Create NeoP... | StarcoderdataPython |
157601 | import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
import numpy as np
from ahfhalotools.objects import Cluster
import ahfhalotools.filetools as ft
import ahfhalotools.analysis as analysis
## -----------Load Cluster Instances--------------##
#define base file name (these are for full files)
fileNameBa... | StarcoderdataPython |
1705119 | from yarl import URL
class Urls:
def __init__(self):
self.protocol = "http://"
self.base_url = "ethosdistro.com/"
self.panel_id = "{panel_id}."
self.no_pool_base_url = self.protocol + self.base_url
self.json_query_param = {"json": "yes"}
# Panel only URLs
... | StarcoderdataPython |
1634475 | <gh_stars>0
# -*- coding: utf-8 -*-
from sklearn.base import BaseEstimator, TransformerMixin # the TransformerMixin to ensure fit_transform()
import pandas as pd
import numpy as np
#we collect the data
Dataset = pd.read_csv('https://raw.githubusercontent.com/M-MSilva/Predict-NBA-player-Points-End-to-end-Project/master... | StarcoderdataPython |
3383625 | """
This is the basic training script for the baseline MRI or CT Model
It is used to train the source segmenter
"""
import os
import sys
import logging
import datetime
import argparse
import tensorflow as tf
from tensorflow.python import debug as tf_debug
import source_segmenter as drn
import numpy as np
from lib impo... | StarcoderdataPython |
3275704 | <filename>codeforces/santaclaus-748c.py<gh_stars>1-10
n = int(input())
moves = input()
rev = { 'R':'L', 'U':'D', 'L':'R', 'D':'U' }
seen = set()
min_pts = 1
for move in moves:
if rev[move] in seen:
min_pts += 1
seen = set()
seen.add(move)
print (min_pts)
| StarcoderdataPython |
3314169 | <gh_stars>0
# Image Swipe 2
__all__ = [
"renderer",
"imguiImage"
] | StarcoderdataPython |
3283412 | from rest_framework import serializers
from .models import Role
class RoleSerializer(serializers.ModelSerializer):
class Meta:
model = Role
fields = '__all__'
| StarcoderdataPython |
196565 | <filename>neutron_tempest_plugin/scenario/test_dhcp.py
# 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
#... | StarcoderdataPython |
1796280 | <gh_stars>1-10
import aioredis
from .settings import get_broker_settings
async def connect_redis() -> aioredis.Redis:
broker_settings = get_broker_settings()
return await aioredis.create_redis(f"redis://{broker_settings.host}:{broker_settings.port}/{broker_settings.db}")
| StarcoderdataPython |
3286386 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
import sys
import copy
import time
import json
from functools import wraps
from django.contrib import admin
from django.conf import settings
from django.core.cache import cache
from django.core.exceptions import PermissionDenied
from django.db.models im... | StarcoderdataPython |
1677254 | import tensorflow as tf
import numpy as np
from tensorflow.keras import datasets
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tinyimagenet import *
def get_data(dataset,path_to_data=None):
aug_config={}
if dataset.lower()=='mnist':
(train_X,train_y),(test_X,test_y)=datasets.mnist.lo... | StarcoderdataPython |
1715862 | dataset_type = 'WheatDataset'
data_root = 'global-wheat-challenge/gwhd_2021/'
img_norm_cfg = dict(
mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True)
albu_train_transforms = [
dict(
type='ShiftScaleRotate',
shift_limit=0.0625,
scale_limit=0.0,
rota... | StarcoderdataPython |
1638856 | from .command import Command
from .scenario_data import ScenarioData
class Scenario(Command):
def __init__(self, result_collector):
super(Scenario, self).__init__(result_collector)
def parse(self, path, repetition_name=None):
self.result_collector.visit_by_scenario(ScenarioData(path[0], path[... | StarcoderdataPython |
27496 | <filename>S2.Surface_Normal/regNormalNet/regNormalNet.py<gh_stars>100-1000
# coding: utf8
"""
@Author : <NAME>
"""
import os
import torch.nn as nn
import torch.utils.model_zoo as model_zoo
from torch.autograd import Variable
import torch
from basic.common import rdict
import numpy as np
from easydict import Ea... | StarcoderdataPython |
71128 | import pytest
from redis.exceptions import RedisError
from rq.exceptions import NoSuchJobError
from busy_beaver.models import Task, PostGitHubSummaryTask, PostTweetTask
MODULE_TO_TEST = "busy_beaver.models.task"
###########
# Base Task
###########
def test_create_task(session):
# Arrange
task = Task(
... | StarcoderdataPython |
97492 | <gh_stars>0
import pathlib
from enum import Enum, auto
from typing import Any, Dict, List, Union
from data_to_model.type_detectors.types import SimpleType
CsvDataType = List[Dict[str, SimpleType]]
JsonDataType = Dict[str, Any]
Collection = Union[CsvDataType, Dict]
class SupportedDataTypes(Enum):
CSV = auto()
... | StarcoderdataPython |
1668688 | <reponame>lumosan/deeplearning2018<gh_stars>0
# -*- coding: utf-8 -*-
################ Generic class ################
class Optimizer(object):
"""
Class for optimizers
"""
def __init__(self):
self.model = None
def step(self, *input):
raise NotImplementedError
def adaptive_lr(k... | StarcoderdataPython |
3373471 | <gh_stars>1-10
#!/usr/bin/python
# coding: utf-8
"""Test the functionality of SASParser and GuinierParser"""
__authors__ = ["<NAME>"]
__license__ = "MIT"
__date__ = "25/03/2021"
import unittest
import logging
import io
import contextlib
from pathlib import Path
from .. import dated_version as freesas_version
from .... | StarcoderdataPython |
30698 | <reponame>christi-john/codechef-practice
# REMISS
for i in range(int(input())):
A,B = map(int,input().split())
if A>B: print(str(A) + " " + str(A+B))
else: print(str(B) + " " + str(A+B)) | StarcoderdataPython |
1604161 | <reponame>ttx/storyboard
# Copyright 2013 <NAME> <<EMAIL>>
# 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... | StarcoderdataPython |
3268593 | """Setup script."""
import glob
import os
from setuptools import setup
with open("README.md", "r") as fh:
long_description = fh.read()
def del_prefix(path):
"""Delete prefix path."""
return os.path.relpath(path, "src")
packages = list(map(
del_prefix,
glob.glob("CardGames/resources/**/*", re... | StarcoderdataPython |
3358093 | <gh_stars>0
import time
import datetime
import json
import redis
import threading
import sys
import RPi.GPIO as GPIO
from .worker import Worker
sys.path.append('..')
from logger.Logger import Logger, LOG_LEVEL
class RelayWorker(Worker):
def __init__(self, config, main_thread_running, system_ready, relay_available, r... | StarcoderdataPython |
1747011 | <filename>src/python/pants/backend/graph_info/tasks/cloc.py
# coding=utf-8
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
... | StarcoderdataPython |
3301383 | from unittest import TestCase
from musicscore.musicxml.types.complextypes.attributes import Divisions
class TestDivisions(TestCase):
def setUp(self):
self.divisions = Divisions(1)
def test_divisions(self):
result = '''<divisions>1</divisions>
'''
self.assertEqual(self.divisions.to_s... | StarcoderdataPython |
9264 | import cv2
import ezdxf
import numpy as np
def draw_hatch(img, entity, color, mask):
for poly_path in entity.paths.paths:
# print(poly_path.path_type_flags)
polygon = np.array([vertex[:-1] for vertex in poly_path.vertices]).astype(int)
if poly_path.path_type_flags & 1 == 1:
cv2... | StarcoderdataPython |
3343723 | from PIL import Image, ImageDraw, ImageFont
from math import ceil
# pip install yapf, to install yapf
# to run format, go to root folder
# yapf -ir ./ --style ./yapf.conf
# specify how large the canvas needs to be
# size in pixels.
# horizontal size is fixed at 430,
# vertical size can vary based on how long the whole ... | StarcoderdataPython |
1769537 | <reponame>Nikolas010101/Projects<filename>APIs/APIs 8 - Hashing/app/database.py
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
#SQLALCHEMY_DATABASE_URL = 'postgresql://<username>:<password>@<ip-address/hostname>/<database_name>'
SQL... | StarcoderdataPython |
1630430 | import sc2
from sc2 import run_game, maps, Race, Difficulty, position, Result
from sc2.player import Bot, Computer
from sc2.constants import *
import sc2
from sc2 import Race, Difficulty
from sc2.player import Bot, Computer
from sc2.player import Human
from sc2.ids.unit_typeid import UnitTypeId
from sc2.ids.ability_id ... | StarcoderdataPython |
34627 | <filename>rastervision/new_version/learner/classification_learner.py
import warnings
warnings.filterwarnings('ignore') # noqa
from os.path import join, isfile, isdir
import zipfile
import torch
from torchvision import models
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader... | StarcoderdataPython |
188030 | COLORS = dict([
('CLEANUP', '\033[94m'),
('CREATE', '\033[92m'),
('INSTALL', '\033[92m'),
('SKIP', '\033[93m'),
('FAIL', '\033[31m'),
('DEFAULT', '\033[39m'),
('UNDEFINED', '\033[37m'),
('STATUS', '\033[36m')
])
def typed_message(message, message_type=None):
color = COLORS.setdefaul... | StarcoderdataPython |
1637749 | # Generated by Django 3.0.4 on 2020-06-02 01:51
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('profiles', '0003_app_label'),
]
operations = [
migrations.AlterField(
model_name='action',
name='name',
... | StarcoderdataPython |
49161 | #!/usr/bin/env python
from argparse import ArgumentParser
import os
import sys
if __name__ == '__main__':
arg_parser = ArgumentParser(description='list all files with given '
'extension in directory')
arg_parser.add_argument('--dir', default='.',
... | StarcoderdataPython |
3229912 | """
validataclass
Copyright (c) 2021, binary butterfly GmbH and contributors
Use of this source code is governed by an MIT-style license that can be found in the LICENSE file.
"""
from validataclass.exceptions import ValidationError
__all__ = [
'RegexMatchError',
]
class RegexMatchError(ValidationError):
""... | StarcoderdataPython |
79192 | <reponame>fury-gl/helios
"""VTK/FURY Tools
This module implements a set o tools to enhance VTK given new functionalities.
"""
class Uniform:
"""This creates a uniform shader variable
It's responsible to store the value of a given uniform
variable and call the related vtk_program
"""
def __init... | StarcoderdataPython |
1767143 | <filename>blog/__init__.py<gh_stars>0
from .blog import app
| StarcoderdataPython |
3228788 | <gh_stars>0
from galleries.igallery import IGallery
from mnd_qtutils.qtutils import setup_widget_from_ui
import os
from pathlib import Path
from pyrulo_qt.ui_configurable_selector import ConfigurableSelector
from PySide2 import QtWidgets, QtGui, QtCore
import galleries_qt
class GalleryWizard(QtWidgets.QWidget):
... | StarcoderdataPython |
3299920 | import screening as m
import random
import pymysql
import csv
import toml
from collections import Counter, defaultdict
from pyomo.environ import *
from pyomo.opt import SolverFactory
year = 2020
interview_number = 4
max_faculty_interview = 7
interview_low_score = 10 # Prints interviews with scores that low
weights ... | StarcoderdataPython |
60540 | <reponame>TeamMacLean/stomatadetector<gh_stars>1-10
"""
Module for dealing with Multi-TIFF metadata in Perkin ELmer .flex files.
"""
import xmltodict
import tifffile as tf
#flex_file = '/Users/macleand/Desktop/stomata_detector/Test images and output/Ok/002002002/002002002.flex'
def count_planes_in_stack(flxml_arr):... | StarcoderdataPython |
126415 | #!/usr/bin/python
#
# Compute MMANA geometry for vertical delta antenna.
# Copyright (C) 2005 <NAME> <<EMAIL>>
#
import math
# Parameters of antenna
MHz = 21.050 # Resonant frequency
R = 0.001 # Wire radius
# Wave length with experimental correction
wave = 300/MHz * 1.0707
H = wave/3 * math.sin (math.pi / 3)
print... | StarcoderdataPython |
3210828 | <filename>tests/Unit/Evolution/Systems/NewtonianEuler/BoundaryConditions/DirichletAnalytic.py
# Distributed under the MIT License.
# See LICENSE.txt for details.
import numpy as np
import PointwiseFunctions.AnalyticSolutions.Hydro.SmoothFlow as hydro
import Evolution.Systems.NewtonianEuler.TimeDerivative as flux
de... | StarcoderdataPython |
1650568 | import time
import torch
import random
import itertools
import numpy as np
from argparse import ArgumentParser
from torch.utils.data import DataLoader
from .learning_approach import Learning_Appr
class Appr(Learning_Appr):
""" Class implementing the Riemannian Walk approach described in
http://openaccess.... | StarcoderdataPython |
3239938 | #-*- coding:utf-8 -*-
import requests
import json
import time
import sys
import imp
imp.reload(sys)
if __name__ == "__main__":
def TencentReader():
url = "https://kdy.unisyou.net/yunpan/activity/doSign"
head = {}
head['User-Agent'] = 'Mozilla/5.0 (iPad; CPU OS 11_0 like Mac OS X) AppleWebKit... | StarcoderdataPython |
3325101 | <filename>test/test_scrambling.py
#
# SPDX-FileCopyrightText: Copyright (c) 2021-2022 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0
#
try:
import sionna
except ImportError as e:
import sys
sys.path.append("../")
import unittest
import numpy as np
import tensorf... | StarcoderdataPython |
1610373 | <filename>barcodes/dxfwrite/tests/test_drawing.py
#!/usr/bin/env python
#coding:utf-8
# Created: 27.04.2010
# Copyright (C) 2010, <NAME>
# License: MIT License
__author__ = "mozman <<EMAIL>>"
import os
import re
import unittest
from dxfwrite import DXFEngine as dxf
from dxfwrite.util import is_string
class TestDraw... | StarcoderdataPython |
1682764 | <gh_stars>1-10
#!/usr/bin/env python3
#
# TW_fix_Strongs.py
#
# Copyright (c) 2021 unfoldingWord
# http://creativecommons.org/licenses/MIT/
# See LICENSE file for details.
#
# Contributors:
# <NAME> <<EMAIL>>
#
# Written Aug 2021 by RJH
# Last modified: 2021-08-10 by RJH
#
"""
Quick script to fix Strongs numbers in... | StarcoderdataPython |
191087 | # https://projecteuler.net/problem=20
def reverse_str(s):
return s[::-1]
def sum_str(a, b):
if len(b) > len(a):
return sum_str(b, a)
reverseA = reverse_str(a)
reverseB = reverse_str(b)
i = 0
add = 0
result = []
while i < len(a):
o1 = int(reverseA[i])
o2 = 0
... | StarcoderdataPython |
3336071 | __all__ = ['bin', 'login']
| StarcoderdataPython |
68980 | journey_cost = float(input())
months = int(input())
saved_money = 0
for i in range(1, months+1):
if i % 2 != 0 and i != 1:
saved_money = saved_money * 0.84
if i % 4 == 0:
saved_money = saved_money * 1.25
saved_money += journey_cost / 4
diff = abs(journey_cost - saved_money)
if saved_mo... | StarcoderdataPython |
3392516 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Generated from FHIR 4.0.1-9346c8cc45 (http://hl7.org/fhir/StructureDefinition/ExampleScenario) on 2020-02-03.
# 2020, SMART Health IT.
import sys
from dataclasses import dataclass, field
from typing import ClassVar, Optional, List
from .backboneelement import Backbon... | StarcoderdataPython |
183273 | import numpy as np
def load_glove(gloveFile):
'''
Requires packages: numpy
gloveFile: string
file path to txt file containing words and glove vectors
returns a dictionary of words as keys and their corresponding vectors as values
'''
f = open(gloveFile,'r', encoding='utf8')
... | StarcoderdataPython |
3228245 | from tkinter import *
from tkinter import ttk
master = Tk()
def on_write(*args):
num = var.get()
if len(num) > 0:
if not num[-1].isdigit():
var.set(num[:-1])
else:
var.set(num[:max_len])
max_len = 5
var = StringVar()
var.trace('w', on_write)
entrada = Entry(master,... | StarcoderdataPython |
83340 | def calculated_quadratic_equation(a = 0, b = 0, c = 0):
r = a ** 2 + b + c
return r
print(calculated_quadratic_equation())
| StarcoderdataPython |
199055 | def solve(input, days):
# Lanternfish with internal timer t are the number of lanternfish with timer t+1 after a day
for day in range(days):
aux = input[0]
input[0] = input[1]
input[1] = input[2]
input[2] = input[3]
input[3] = input[4]
input[4] = input[5]
... | StarcoderdataPython |
3304355 | <filename>scripts/input-demand-analysis.py
import pandas as pd
#from datetime import datetime
import numpy as np
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
import matplotlib.pyplot as plt
from scipy import interpolate
# some processing stuff
df = pd.read_excel(
"data/cruise-arrivals.xlsx",
dt... | StarcoderdataPython |
3255822 | #
# Copyright (c) 2020, Massachusetts Institute of Technology All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# Redistributions of source code must retain the above copyright notice, this
# list o... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.