id stringlengths 1 7 | text stringlengths 6 1.03M | dataset_id stringclasses 1
value |
|---|---|---|
69804 | '''
Function:
配置文件
'''
import os
'''字体'''
FONTPATH = os.path.join(os.getcwd(), 'G2/resources/font/font.ttf')
'''图片'''
BULLET_IMAGE_PATHS = {
'up': os.path.join(os.getcwd(), 'G2/resources/images/bullet/bullet_up.png'),
'down': os.path.join(os.getcwd(), 'G2/resources/images/bullet/bullet_down.png'),
... | StarcoderdataPython |
1651253 | """ pixtosky - A module to perform coordinate transformation from pixel coordinates
in one image to pixel coordinates in another frame
:Authors: <NAME>
:License: :doc:`LICENSE`
PARAMETERS
----------
inimage : str
full filename with path of input image, an extension name ['... | StarcoderdataPython |
3250745 | <filename>meutils/request_utils/__init__.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Project : MeUtils.
# @File : http_utils
# @Time : 2020/11/12 11:49 上午
# @Author : yuanjie
# @Email : <EMAIL>
# @Software : PyCharm
# @Description :
import requests
from loguru import log... | StarcoderdataPython |
1744420 | <filename>hero/myproject/pipelines.py<gh_stars>0
# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
from pymongo import MongoClient
import json
class MyprojectPipeline(object):... | StarcoderdataPython |
1649827 | <gh_stars>100-1000
# -*- coding: utf-8 -*-
import requests
import multiprocessing
import models
from gevent.pool import Pool
from sqlalchemy.exc import IntegrityError, InvalidRequestError
from helpers import random_str
from webs.douban import parsers
from config import sqla
from . import get_main_movies_base_data
do... | StarcoderdataPython |
3293705 | <reponame>skostya64/Music_store_test
class CheckBassNamePage:
def __init__(self, driver):
self.driver = driver
def click_menu_bass_guitars(self):
self.driver.find_element_by_xpath("//a[@href='https://www.musicstore.de/ru_OT/EUR/-/cat-BASS']").click()
def click_electric_bass_guitars(self... | StarcoderdataPython |
3248873 | import logging
from time import sleep
from django.conf import settings
from django.core.management.base import BaseCommand
import arrow
from kegbot.reader import TapReader
from kegbot.tasks import record_pulses
logger = logging.getLogger(__name__)
class Command(BaseCommand):
def handle(self, *args, **opts):
... | StarcoderdataPython |
193873 | # -*- coding: utf-8 -*-
import tweepy
import os
from airpoldata import NOX, P2, highorlow, highorlowNOX, highorlowp2
#this script runs the twitterbot
auth = tweepy.OAuthHandler(os.environ['CONSUMER_KEY'], os.environ['CONSUMER_SECRET'])
auth.set_access_token(os.environ['ACCESS_TOKEN'], os.environ['ACCESS_TOKEN_SECRET'... | StarcoderdataPython |
3395850 | <reponame>sivasanarul/amfe_topopt<filename>amfe/parametric/morphing/morpher/__init__.py
#
# Copyright (c) 2018 TECHNICAL UNIVERSITY OF MUNICH, DEPARTMENT OF MECHANICAL ENGINEERING, CHAIR OF APPLIED MECHANICS,
# BOLTZMANNSTRASSE 15, 85748 GARCHING/MUNICH, GERMANY, <EMAIL>.
#
# Distributed under 3-Clause BSD license. See... | StarcoderdataPython |
189988 | from django.db import models
from .auth.custom_user_model import AbstractBaseUser
from django.utils.translation import ugettext_lazy as _
# Create your models here.
class Usermaster(AbstractBaseUser):
user_no = models.IntegerField(db_column='userno', primary_key=True) # Field name made lowercase.
user_status... | StarcoderdataPython |
59110 | <gh_stars>1-10
# Copyright (C) 2020 TU Dresden
# Licensed under the ISC license (see LICENSE.txt)
#
# Authors: <NAME>, <NAME>
from mocasin.common.platform import Platform, Processor
from mocasin.platforms.topologies import fullyConnectedTopology
from mocasin.platforms.platformDesigner import PlatformDesigner
from moca... | StarcoderdataPython |
3256375 | # from .ddaig import DDAIG
# from .daeldg import DAELDG
# from .vanilla import Vanilla
from .crossgrad import CrossGrad
from .dddcian import CIAN
from .CAN import CAN
from .mixture import mixup
from .ADV import ADV
from .EpiDG import EpiDG
from .MetaReg import MetaReg
from .FeatureCritic import FCDG
# from .MLDG_tmp im... | StarcoderdataPython |
3337705 | <reponame>97littleleaf11/mypyc-benchmarks
"""Utilities for generation markdown."""
from reporting.common import BENCHMARKS_DIR
def mypy_commit_link(commit: str) -> str:
url = 'https://github.com/python/mypy/commit/%s' % commit
return '[%s](%s)' % (commit[:12], url)
def benchmark_link(benchmark: str, link_n... | StarcoderdataPython |
26314 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2017-04-06 16:37
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migratio... | StarcoderdataPython |
1627093 | # -*- coding: utf-8 -*-
"""Input and output functions for BEL graphs.
PyBEL provides multiple lossless interchange options for BEL. Lossy output formats are also included for convenient
export to other programs. Notably, a *de facto* interchange using Resource Description Framework (RDF) to match the
ability of other... | StarcoderdataPython |
1649614 | <reponame>drschwabe/prototype
# Copyright (c) 2020 <NAME>
# Distributed under the MIT software license, see the accompanying# file LICENSE or http://www.opensource.org/licenses/mit-license.php
from moneysocket.protocol.layer import ProtocolLayer
from moneysocket.protocol.transact.consumer_nexus import ConsumerTransac... | StarcoderdataPython |
3364586 | <reponame>xxchenxx/dlrm<filename>metrics/pac.py
'''
Metrics:
PAC Bayesian flatness with respect to input and weight
'''
import os
import time
import copy
import torch
import numpy as np
import torch.nn.functional as F
from dlrm_s_pytorch import unpack_batch
__all__ = ['eval_pac_weight', 'eval_pac_in... | StarcoderdataPython |
3337914 | # !/usr/bin/env python3
# Check for missing dependencies which are: SpeechRecognition, Pandas and PyAudio
try:
import os
import speech_recognition as sr
from pandas.io.clipboard import copy as cp
except ImportError as e:
exit(f"\033[91mMissing dependency: {e.name}. Please check your installation!")
# ... | StarcoderdataPython |
3211389 | <gh_stars>1-10
import logging
# Define the name of the logger for the package
logger = logging.getLogger('swallow')
EXIT_SUCCESS = 0
EXIT_IO_ERROR = 11
EXIT_USER_INTERRUPT = 21
| StarcoderdataPython |
3355396 | from protorpc import messages
from protorpc import protojson
import bleach
import grow
import os
import requests
try:
from HTMLParser import HTMLParser
except ImportError:
from html.parser import HTMLParser
class Error(Exception):
pass
class AttributeMessage(messages.Message):
tag = messages.StringF... | StarcoderdataPython |
138824 | '''
Created by <NAME> 2020
# Read in WAV file into Python Class
sound1 = AudioProcessing('input.wav')
# Set the speed of the audio
sound1.set_audio_speed(0.5)
# Set the pitch of the audio
sound1.set_audio_pitch(2)
# Reverse the content of the audio
sound1.set_reverse()
# Add an echo to the audio
sound1.... | StarcoderdataPython |
3204560 | import warnings
import numpy as np
from .utils import *
from .exceptions import NotEvaluatedError, NotSupposedToHappenError
class TreeNode:
"""Decision tree node
We would not want to define another node in the constructor
so the API requires you to set the left and right
node attributes manually.
... | StarcoderdataPython |
1781517 | """Pre-configured commands."""
from . import ffmpeg, icecast, sox
from ._aria2 import Aria2
from .icecast import Icecast
from ._redis import Redis
SRC_SILENCE = "ffmpeg -re -f s16le -i /dev/zero -f s16le -"
SRC_FILE = "ffmpeg -ac 2 -i {filename} -f s16le -ar 44.1k -acodec pcm_s16le -"
PYP_NORMED = """fmpeg -ac 2 -... | StarcoderdataPython |
3322313 | import krakenex
import networkx as nx
import matplotlib.pyplot as plt
import numpy as np
import pandas
import seaborn
import datetime
pandas.set_option('display.width', 1000)
import pprint
pp = pprint.PrettyPrinter()
import itertools
for index in itertools.count():
now = datetime.datetime.now()
k = krakene... | StarcoderdataPython |
80268 | <filename>server_expects/matchers.py
# -*- coding: utf-8 -*-
from expects.matchers import Matcher, default_matcher
from .resources import (
package as package_resource,
host as host_resource,
path as path_resource
)
class _be_installed(Matcher):
def _match(self, package):
package = self._res... | StarcoderdataPython |
1725324 | """CLI"""
import sys
import datetime
import click
from advent_of_code import tools
today = datetime.date.today()
if today.month < 12:
MAX_YEAR = today.year - 1
else:
MAX_YEAR = today.year
@click.group()
def aoc():
"""Advent of Code CLI"""
pass
@aoc.command("solve")
@click.argument("year", type=clic... | StarcoderdataPython |
1735448 | """
# My first app
Here's our first attempt at using data to create a table:
"""
import streamlit as st
import pandas as pd
df = pd.DataFrame({
'first column': [1, 2, 3, 4],
'second column': [10, 20, 30, 40]
})
df | StarcoderdataPython |
137777 | from .packet_buffer import PacketBuffer
from zlib import compress
from minecraft.networking.types import (
VarInt, Enum
)
class Packet(object):
packet_name = "base"
id = None
definition = None
# To define the packet ID, either:
# 1. Define the attribute `id', of type int, in a subclass; or
... | StarcoderdataPython |
4816998 | # import unittest, os, subprocess, time, datetime, random, string, re
# from selenium import webdriver
# from selenium.webdriver.support.ui import WebDriverWait
# from selenium.webdriver.support import expected_conditions as EC
# from selenium.webdriver.common.by import By
# from selenium.webdriver.common.keys import ... | StarcoderdataPython |
1634662 |
import os
import time
import uuid
import threading
import xml.etree.ElementTree as ET
from XSTAF.core.logger import LOGGER
class Run(object):
#test case result
NotRun = 0b10000000
Fail = 0b00000001
Pass = 0b00000000
#pretty results
Results = { NotRun : "not run",
Fail : "... | StarcoderdataPython |
152429 | <reponame>rivamarco/alexa-apis-for-python
# coding: utf-8
#
# Copyright 2019 Amazon.com, Inc. or its affiliates. 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. A copy of the License is located at
#
# http://aws... | StarcoderdataPython |
3365721 | <reponame>marshall/gaia
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
try:
from marionette import (expected,
Wait)
from marionette... | StarcoderdataPython |
3314497 | import argparse
import logging
import traceback
from typing import List
from sys import exit
import click
from cli.echo import Echo
from common.errors import BaseError
from vm_providers.factory import get_provider_for
from vm_providers.errors import ProviderNotFound
from common import definitions
logger = logging.ge... | StarcoderdataPython |
1787837 | <reponame>kennethreitz-archive/wolfram
import os
from fabric.api import *
os.f
def scrub():
""" Death to the bytecode! """
local('rm -fr dist build')
local("find . -name \"*.pyc\" -exec rm '{}' ';'")
#def docs():
# """Build docs."""
# os.system('make html')
# os.chdir('_build/html')
# os.system('sphinxtogithub .')... | StarcoderdataPython |
4821914 | # coding=utf-8
__author__ = 'kohlmannj'
import os
import Ity
import FilePaths
from Corpus import Corpus
from CorpusText import CorpusText
__all__ = ["Corpus", "CorpusText", "FilePaths"]
def get_models(metadata_root_path=None):
if metadata_root_path is None:
metadata_root_path = Ity.metadata_root
retu... | StarcoderdataPython |
3254480 | import os
import sys
import logging
sys.path.append(os.path.abspath("."))
print(sys.path)
# import own libs
from src.models.model_manager import *
from src.models.evaluate_model import evaluate
from src.data.data_utils import get_train_and_validation_generator
from src.models.model_utils import get_callbacks
from src... | StarcoderdataPython |
3243301 | <filename>xaikit/adapters/__init__.py
import sklearn
from xaikit.adapters.sklearn_adapter import SklearnModelAdapter
def create_model_adapter(external_model):
"""
Brings an external model under the xAIkit interface.
"""
if isinstance(external_model, sklearn.base.BaseEstimator):
return Sklearn... | StarcoderdataPython |
3215387 | # Demo Python Strings - Slicing Strings
'''
Negative Indexing
Use negative indexes to start the slice from the end of the string:
'''
# Get the characters from position 5 to position 1, starting the count from the end of the string:
b = "Hello, World!"
print("string original: ", b)
print(b[-5:-2])
# Incluye el car... | StarcoderdataPython |
1788284 | """Resources for nbvewerbot functionality"""
import os
import re
import logging
import pickle
import dotenv
import praw
# Relevant directories
SRC_DIR = os.path.dirname(__file__)
RESOURCES_DIR = os.path.join(SRC_DIR, "resources.d")
PROJECT_DIR = os.path.realpath(os.path.join(SRC_DIR, ".."))
# Logging
LOGFILE_PATH =... | StarcoderdataPython |
3273386 | # Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license. See LICENSE file in the project root for
# full license information.
import getopt
class OptionError(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
def g... | StarcoderdataPython |
3371013 | '''Python file for the traversal abstract class
This is an abstract class inherited from the NodeVisitor class to allow to kwargs
'''
from ...nodes import AST
from ...nodes import NodeVisitor
class Traversal(NodeVisitor):
def visit(self, node: AST, **kwargs):
'''
Public visit method
The vi... | StarcoderdataPython |
3203682 | <filename>train_wqx/transformer_model.py<gh_stars>0
import os
# os.environ['CUDA_VISIBLE_DEVICES'] = '1'
import torch.nn as nn
import torch.nn.functional as F
import torch
import numpy as np
import time
# import matplotlib.pyplot as plt
import math
import yaml
# from fast_ctc_decode import beam_search, viterbi_search... | StarcoderdataPython |
1691938 | <gh_stars>1-10
# -*- encoding: utf-8 -*-
"""
Insertion Sort em Python
by Ed
"""
def insertion_sort(lista):
for i in range(1,len(lista)):
eleito = lista[i]
j = i-1
while j >= 0 and eleito < lista[j]:
lista[j+1] = lista[j]
j=j-1
lista[j+1] = eleito
prin... | StarcoderdataPython |
1720780 | <reponame>rtu715/NAS-Bench-360
from typing import Any, Dict, Union, Sequence
import boto3
import os
import tempfile
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision.datasets as dset
from torch.optim.lr_scheduler import CosineAnnealingLR
from collections import Cou... | StarcoderdataPython |
3247147 | <reponame>faezezps/SiMQC<gh_stars>10-100
import argparse
import json
import nltk
import numpy as np
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics import pairwise_distances
from hotpot import config
from hotpot.tfidf_retriever.utils import STOPWORDS
def build_all_dev_rankings_file(... | StarcoderdataPython |
3238078 | <reponame>Horta/limix-tool
from .nh2 import recovery_true_heritability as nh2
| StarcoderdataPython |
29879 | <gh_stars>0
# -*- coding: utf-8 -*-
from .._protos.public.uac import Organization_pb2 as _Organization
from .._protos.public.common import CommonService_pb2 as _CommonCommonService
class CollaboratorType:
def __init__(self, global_collaborator_type=None, default_repo_collaborator_type=None,
defau... | StarcoderdataPython |
3277163 | <gh_stars>1-10
# -*- coding: utf-8 -*-
"""NIM REST API Python Client -- Team component"""
from __future__ import absolute_import
import json
from netease_im import util
from netease_im.components import base
from netease_im.util import is_str_type
__author__ = "<NAME>"
__email__ = "<EMAIL>"
class TeamComponent(b... | StarcoderdataPython |
3330363 | <filename>src/main.py
# import some modules to be used in py-spark SQL
from pyspark import SparkConf
from pyspark.sql import SparkSession
from pyspark.sql import HiveContext
from tools import buildFiles
from latentsFactorsModel import generateUsersItensVectors
from mips import process
# Initialize Saprk Session
impo... | StarcoderdataPython |
4834219 | <filename>packit_service/service/api/koji_builds.py<gh_stars>0
# MIT License
#
# Copyright (c) 2019 Red Hat, 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 Software without restriction, includ... | StarcoderdataPython |
3350989 | <reponame>fabiograssiotto/rashid
import sys
import os
import shutil
import time
from pathlib import Path
class Logger(object):
MODULES_MAIN = 'Main'
MODULES_MODEL = 'Model'
MODULES_MEMORY = 'Memory'
MODEL_ID = 'ID'
MODEL_EDD = 'EDD'
MODEL_SAM = 'SAM'
MODEL_TOM = 'TOM'
def __init__... | StarcoderdataPython |
88772 | <gh_stars>0
with open('23B.in','r') as f:
insts = [s.split() for s in f]
p = 0
r = {'a':12,'b':0,'c':0,'d':0}
def get_value(v):
try: return int(v)
except: return r[v]
while p < len(insts) and p >= 0:
inst = insts[p][0]
if inst == 'tgl':
n_p = p+int(r[insts[p][1]])
if n_p < len(insts) and n_p >= 0:
... | StarcoderdataPython |
3264826 | <gh_stars>0
#!/usr/bin/env python
# -*- coding: utf-8 -*- #
from __future__ import unicode_literals
AUTHOR = '<NAME>'
SITENAME = '<NAME>'
SITESUBTITLE = 'Data Scientist'
SITEURL = ''
BIO = 'Data scientist. Iron Man fan.'
PROFILE_IMAGE = 'avatar.jpg'
PATH = 'content'
STATIC_PATHS = ['images', 'pdfs', 'extra']
EXTRA_PA... | StarcoderdataPython |
1729936 | #!/usr/bin/python -u
# -*- coding: utf-8 -*-
# v 0.0.4 Tlek
import random
import datetime
import sys
from libs import respond
from libs import sql_query as sql
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
from telegram import KeyboardButton, ReplyKeyboardMarkup
token = str(sys.argv[1])
r... | StarcoderdataPython |
78101 | # -*- coding: utf-8 -*-
# upd dist
import sys
import sqlite3
import time
from typing import List, Dict
from collections import namedtuple, defaultdict
from common import upcase_regex, pos2pos, penn2pos, is_stop_ngram
Record = namedtuple('Record', ['word', 'lemma', 'sublemma', 'tag', 'abs', 'arf'])
def create_tabl... | StarcoderdataPython |
4759 | from django.apps import AppConfig
from django.contrib.admin.apps import AdminConfig
from django.contrib.auth.apps import AuthConfig
from django.contrib.contenttypes.apps import ContentTypesConfig
from django.contrib.sessions.apps import SessionsConfig
from django.db.models.signals import post_migrate
from django_celery... | StarcoderdataPython |
4827579 | # Polyline drawing in codeskulptor
import simplegui
polyline = []
def click(pos):
global polyline
polyline.append(pos)
def clear():
global polyline
polyline = []
def draw(canvas):
if len(polyline) == 1:
canvas.draw_point(polyline[0], "White")
for i in range(1,... | StarcoderdataPython |
152852 | class Solution:
"""
@param nums: an array with positive and negative numbers
@param k: an integer
@return: the maximum average
"""
def maxAverage(self, nums, k):
if not nums:
return 0
min_num = min(nums)
max_num = max(nums)
while ... | StarcoderdataPython |
4831851 | <filename>test.py
import argparse
from matplotlib import pyplot as plt
import torch
from torchvision import datasets, transforms
from torch.utils.data import DataLoader
from torch.autograd import Variable
from PIL import Image
import cv2
import os
import json
import math
from utils import get_model, WarmUpLR, my_eval... | StarcoderdataPython |
1701929 | <filename>md5Ripper.py<gh_stars>0
'''
* Program: md5Ripper ;
* File: md5Ripper.py ;
* Author: F0r3bod1n' ;
* Version: v1.0 ;
'''
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import argparse
import os.path
import codecs
import hashlib
import colorama
parser = argparse.ArgumentPars... | StarcoderdataPython |
3368007 | from typing import *
import numpy as np
from itertools import combinations, product, permutations
from scipy.special import loggamma
def rss_objective( y_test: np.ndarray, y_predicted: np.ndarray) -> float:
"""Return the residual sum of squares"""
return np.sum((y_predicted - y_test)**2)
def rmse_objective(... | StarcoderdataPython |
94458 | <reponame>star2dust/MOSEK-MATLAB
"""
This setup.py file is a mish-mash of hacks that should make it work
under most circumstances. The core problems of the installation
process are
- Installation across different platforms
- Installation in user-defined locations
- Handling shared library dependencies
The extension m... | StarcoderdataPython |
3230636 | from django.apps import AppConfig
class PollConfig(AppConfig):
name = "polls"
| StarcoderdataPython |
3263118 | #!/usr/bin/env python3
import sys
import numpy as np
for fname in sys.argv[1:]:
with open(fname) as f:
lines = f.readlines()
ls = (l.strip() for l in lines)
ls = [int(l, 16) for l in lines]
d = np.diff(ls)
print(fname.split('.')[0], np.median(d), sep='\t')
| StarcoderdataPython |
1798232 | from osrsmath.general.skills import *
import unittest
class TestExperience(unittest.TestCase):
def test_experience_for_levels_below_1_raises(self):
self.assertRaises(ValueError, lambda:experience(0))
self.assertRaises(ValueError, lambda:experience(-3))
def test_experience_for_levels_above_level_cap_with... | StarcoderdataPython |
1790007 | ## @ingroup Components-Energy-Storages-Batteries-Constant_Mass
# Lithium_Ion_LiNiMnCoO2_18650.py
#
# Created: Feb 2020, <NAME>
# Modified: Sep 2021, <NAME>
# ----------------------------------------------------------------------
# Imports
# ----------------------------------------------------------------------
imp... | StarcoderdataPython |
3387849 | <gh_stars>1-10
#!/usr/bin/env python
#
# Protein Engineering Analysis Tool DataBase (PEATDB)
# Copyright (C) 2010 <NAME> & <NAME>
#
# 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... | StarcoderdataPython |
1612556 | import unittest
from query_tools.base_tokenizer import WikidataTokenizer, DBpediaTokenizer
from query_tools.base_query import WikidataQuery
from templates.wikidata_template import WikidataTemplate
class TestQuery(unittest.TestCase):
def testWikidataQuery(self):
query_1 = "SELECT DISTINCT ?uri WHERE { <h... | StarcoderdataPython |
1634542 | <reponame>QuickBase/QB_APIs<gh_stars>1-10
##################### SCRIPT FOR UPDATING TABLES IN QB APPS WITH DATA FROM SQL SERVER #####################
################################## written by <NAME> ##################################
## INSTRUCTIONS
# Modify the variables in the next section as specified below. Al... | StarcoderdataPython |
89546 |
def fxp(number, fractionalBits):
"""
Returns a fixed point representation of a floating point number
rounded to a given number of fractional bits.
The returned value is a string of 1's and 0's and a dot. The
substring on the left of the dot gives the binary representation
of ... | StarcoderdataPython |
3289366 | <reponame>ksshanam/sahara<gh_stars>0
# Copyright (c) 2015 OpenStack Foundation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless req... | StarcoderdataPython |
113571 | import dataclasses
from typing import Any, ClassVar, Dict, Iterable, Optional
from dbdaora.data_sources.fallback import FallbackDataSource
@dataclasses.dataclass
class DictFallbackDataSource(FallbackDataSource[str]):
db: Dict[Optional[str], Dict[str, Any]] = dataclasses.field(
default_factory=dict
)
... | StarcoderdataPython |
1673387 | <gh_stars>1-10
def super_fibonacci(n, m):
fib = [0] + [1 for i in range(m)]
for i in range(m + 1, n + 1):
val = 0
for k in fib[i - m:i]:
val += k
fib.append(val)
return fib[n]
print(super_fibonacci(2, 1))
print(super_fibonacci(3, 5))
print(super_fibonacci(8, 2))
print(super_fibonacci(9, 3)) | StarcoderdataPython |
3231996 | from __future__ import print_function
import keras
from keras.datasets import mnist
from keras.layers import *
from keras.models import Sequential, load_model
from keras.layers import Dense, Dropout, Activation, Flatten
from keras.layers import Conv2D, MaxPooling2D
from keras.callbacks import ModelCheckpoint
import n... | StarcoderdataPython |
1634404 |
import datetime
import os
import re
from typing import List, Optional, Sequence
from stramp.docstruct import DocFile, DocSection
# https://orgmode.org/worg/dev/org-syntax.html
re_heading = re.compile(br'(?m)^(\*+)[^\S\r\n](\S.*)$')
re_greater_block_delimiter = re.compile(br'(?mi)^[^\S\r\n]*#\+(begin|end)_(\S+)(?:[^\... | StarcoderdataPython |
107272 | from model.network import LeNet5
from saliency.vanilla_gradient import save_vanilla_gradient
from model.data import mnist_train_test_sets
import numpy as np
# Get MNIST dataset, preprocessed
train_images, train_labels, test_images, test_labels = mnist_train_test_sets()
# Load net and 98% acc weights
net = LeNet5(weig... | StarcoderdataPython |
1628042 | <gh_stars>1-10
# COUNTING VALLEYS HACKERRANK SOLUTION:
# creating a function to calculate the number of valleys.
def countingValleys(steps, path):
# creating variables to store the values for the valleys crossed and the current level.
current_level = 0
valley_count = 0
# creating a for-loop ... | StarcoderdataPython |
26597 | <reponame>Fairy-Phy/Relium
import random
from Relium import calcurate, classes, parser, constant
"""
1ラインづつランダムな位置に表示していきます
"""
source_file = r""
target_start_offset = 31999
target_end_offset = 34666
avgbpm = 180
# ノーツの高さの最大値(上げすぎると見えなくなります)
max_laneheight = 370
beat = 4
sample_set = 1
sample_index = 0
volume = 6... | StarcoderdataPython |
3327441 | # -*- coding: utf-8 -*-
"""
Created on Sat Aug 21 14:36:08 2021
@author: Administrator
"""
#%%
# =============================================================================
# =============================================================================
# # 문제 11 유형(DataSet_11.csv 이용)
# 구분자 : comma(“,... | StarcoderdataPython |
53110 | """empty message
Revision ID: 2d70b2b7f421
Revises: <PASSWORD>
Create Date: 2017-01-07 15:40:46.326596
"""
# revision identifiers, used by Alembic.
revision = '2d70b2b7f421'
down_revision = '<PASSWORD>'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Alembic - plea... | StarcoderdataPython |
1773355 | """Test prepare run module."""
from math import isnan
import pytest
from haddock.gear.prepare_run import (
get_expandable_parameters,
populate_mol_parameters,
populate_topology_molecule_params,
)
from haddock.gear.yaml2cfg import read_from_yaml_config
from haddock.modules.topology.topoaa import DEFAUL... | StarcoderdataPython |
120135 | import argparse
import itertools
import logging
import os
import time
from types import SimpleNamespace
import falcon
import pandas
import torch
from falcon_cors import CORS
import waitress
import numpy as np
import json
import re
from torch.utils.data import DataLoader
from tqdm import tqdm
from data import Data
fro... | StarcoderdataPython |
2930 | <reponame>youngmg1995/NES-Music-Maker
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 1 17:14:19 2020
@author: Mitchell
nesm_generator.py
~~~~~~~~~~~~~~~~~
This file serves as a script for using our pre-trained VAE model to generate
brand new NES music soundtracks. NOTE - using the reduced model we only
generate the ... | StarcoderdataPython |
3394943 | import numpy as np
from copy import copy
from typing import Union, Tuple, Iterable, Sequence
from ._constants import DimsMode
from ...util.event import EmitterGroup
class Dims:
"""Dimensions object modeling multi-dimensional slicing, cropping, and
displaying in Napari
Parameters
----------
init_... | StarcoderdataPython |
131208 | # encoder.py
# <NAME>
# Encoder Class Adapted from py-gaugette rotary encoder library
import RPi.GPIO as GPIO
import time
import math
import threading
class Encoder:
def __init__(self, pin_a, pin_b):
self.pin_a = pin_b; # Our Encoders are inverted,
self.pin_b = pin_a; # Which is why this looks we... | StarcoderdataPython |
1674228 | <gh_stars>0
from django.shortcuts import render_to_response
from django.shortcuts import render
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from .forms import NewUserForm
def index (request):
return render_to_response('laravel_course/index.html')
def logout_request(request):
l... | StarcoderdataPython |
1628958 | <gh_stars>1-10
def init_actions_(service, args):
"""
this needs to returns an array of actions representing the depencies between actions.
Looks at ACTION_DEPS in this module for an example of what is expected
"""
# some default logic for simple actions
return {
'test': ['install']
... | StarcoderdataPython |
185807 | from django.contrib import admin
from .models import JobListing
class JobListingAdmin(admin.ModelAdmin):
list_display = ("title", "employer_name", "status", "created")
list_filter = ("status",)
ordering = ("-created",)
admin.site.register(JobListing, JobListingAdmin)
| StarcoderdataPython |
63126 | sexo = str(input('Informe seu sexo [M/F]: ')).upper().strip()[0]
while sexo not in 'MmFf':
sexo = str(input('Informação incorreta, digite novamente [M/F]: ')).upper().strip()[0]
print(f'Obrigado! Seu sexo foi computado como {sexo}!')
| StarcoderdataPython |
96434 | <reponame>ApproxEng/approxeng.holochassis
from abc import ABCMeta, abstractmethod
from math import asin, pi, sqrt
from time import sleep
from approxeng.chassis import rotate_vector, Motion, DeadReckoning, rotate_point
from approxeng.chassis.dynamics import MotionLimit
from euclid import Vector2, Point2
class Waypoin... | StarcoderdataPython |
18302 | # Copyright 2014 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 mojo_lexer
import unittest
# Try to load the ply module, if not, then assume it is in the third_party
# directory.
try:
# Disable lint check which ... | StarcoderdataPython |
1765456 | <gh_stars>100-1000
'''
Register modules here. Module-specific parameters in the config .ini file
can be added under a section with the same name as the module.
2019-2020 <NAME>
'''
# set up Celery configuration
import celery_worker
from .LabelUI.app import LabelUI
from .Database.app import Database
from ... | StarcoderdataPython |
4833451 | from ..web import Links
from . import WebEntity
__all__ = ['Image']
class Image (WebEntity):
"""
Represents an image.
"""
def __init__ (self, board, tim, ext, filename, md5, fsize, w, h):
self.board = board
self.tim = tim
self.ext = ext
self.filename = filename
... | StarcoderdataPython |
118870 | from pyradioconfig.parts.jumbo.calculators.calc_synth import CALC_Synth_jumbo
class CALC_Synth_nixi(CALC_Synth_jumbo):
pass | StarcoderdataPython |
197693 | <filename>build/cpp/verify_runtime_deps.py
#!/usr/bin/env python2.7
# Copyright 2018 The Fuchsia 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 argparse
import json
import os
import sys
def has_packaged_file(needed_file, deps... | StarcoderdataPython |
149740 | __author__ = "<NAME>"
__copyright__ = "Copyright 2022, <NAME>"
__credits__ = ["<NAME>"]
__license__ = "mit"
__maintainer__ = "<NAME>"
__email__ = "<EMAIL>"
from ..item.PDFObject import PDFObject
from ..item.PDFDictionary import PDFDictionary
from ..item.PDFList import PDFList
from ..item.PDFStream import PDFStream
fro... | StarcoderdataPython |
183211 | <reponame>bmjhit/tf-estimator-tutorials
#!/usr/bin/python
#
# Copyright 2018 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
#
... | StarcoderdataPython |
172919 | <reponame>SanUni2020/ProjetoIntegrador-I
from flask import Flask, render_template, request, url_for, redirect
from flask_sqlalchemy import SQLAlchemy
app = Flask(__name__, template_folder='templates')
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///comentarios.sqlite3'
db = SQLAlchemy(app)
class Com... | StarcoderdataPython |
3201918 | import pandas as pd
import numpy as np
from .extractors import TfIdfExtractor
from .encoders import GenericLabelBinarizer
from typing import List, Tuple
from .extractors import BaseExtractor
from .encoders import BaseEncoder
def check_data_alignment(labeled_df, unlabeled_df):
if labeled_df is None and unlabeled_d... | StarcoderdataPython |
3317622 | # MIT License
# Copyright 2020 <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 limitation the rights to
# use, copy, modify, merge, publish, di... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.