id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7
values |
|---|---|---|
1762195 | <filename>Alice/Sorting/Insertion_Sort.py<gh_stars>1-10
class InsertionSort:
def __init__(self,array):
self.array = array
def result(self):
for i in range(1,len(self.array)):
for j in range(i-1,-1,-1):
if self.array[j] > self.array[j+1]:
self.array... | StarcoderdataPython |
3226610 | <gh_stars>0
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import cm
from tqdm import tqdm
class EvolutionaryParameterOptimizer:
"""
Evolutionary Algorithm Optimizer for arbitrary parameter_discretization which allows it to solve integer optimizations
"""
def __init__(self, parame... | StarcoderdataPython |
3356701 | <gh_stars>10-100
#! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
@version: ??
@author: li
@file: rnn_model_attention.py
@time: 2018/3/27 下午5:41
"""
import tensorflow as tf
from attention import attention
import os
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
class TRNNConfig(object):
embedding_dim = 64 # 词向量维度
... | StarcoderdataPython |
1730111 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Helper functions to train a model."""
| StarcoderdataPython |
2500 | # -*- coding: utf-8 -*-
__author__ = """<NAME>"""
__email__ = '<EMAIL>'
__version__ = '0.1.0'
| StarcoderdataPython |
3229433 | from .produces import *
from .dependencies import * | StarcoderdataPython |
107326 | <reponame>utsavdey/Fundamentals_Of_Deep_Learning_Assignments<filename>Assignment1/grad.py<gh_stars>0
import numpy as np
def cross_entropy_grad(y_hat, label):
# grad w.r.t out activation
temp = np.zeros_like(y_hat)
# If the initial guess is very wrong. This gradient will explode. This places a limit on tha... | StarcoderdataPython |
1696441 | import logging
from requests import request
import json
logger = logging.getLogger("ghproject")
def post_request(url: str, data: dict, headers: dict):
"""Send data to GitHub API
Parameters
----------
url : str
url to request
data : dict
data to be send to url
headers : dict
... | StarcoderdataPython |
1654194 | from app import app
from .routes import france_routes
app.register_blueprint(france_routes) | StarcoderdataPython |
4820516 | import pytest
def test_get_sample_ecommerce_dataset():
from relevanceai.datasets import get_ecommerce_1_dataset
assert len(get_ecommerce_1_dataset(number_of_documents=100)) == 100
def test_get_games_dataset_subset():
from relevanceai.datasets import get_games_dataset
assert len(get_games_dataset(n... | StarcoderdataPython |
1764786 | <filename>lowhaio.py
import asyncio
import contextlib
import ipaddress
import logging
import urllib.parse
import ssl
import socket
from aiodnsresolver import (
TYPES,
DnsError,
Resolver,
ResolverLoggerAdapter,
)
class HttpError(Exception):
pass
class HttpConnectionError(HttpError):
pass
c... | StarcoderdataPython |
1738392 | #!/usr/bin/env python2
"""
builtin_process.py - Builtins that deal with processes or modify process state.
This is sort of the opposite of builtin_pure.py.
"""
from __future__ import print_function
import signal # for calculating numbers
from _devbuild.gen import arg_types
from _devbuild.gen.runtime_asdl import (
... | StarcoderdataPython |
162937 | # Generated by Django 2.2.13 on 2020-10-09 17:57
import django.db.models.deletion
import django.utils.timezone
import model_utils.fields
from django.db import migrations, models
import waldur_core.core.fields
import waldur_core.core.models
import waldur_core.core.shims
import waldur_core.core.validators
import waldur... | StarcoderdataPython |
160587 | <gh_stars>0
from . import immix
CACHEABLE = True
methods = ("imagesforperson")
def run(args, method):
if "q" not in args:
raise Exception("No query given")
q = args.get("q")
if method == "imagesforperson":
return immix.imagesforperson(q) | StarcoderdataPython |
3367183 | # -*- coding: utf-8 -*-
#
# Copyright (c) 2019~2999 - Cologler <<EMAIL>>
# ----------
#
# ----------
from typing import Tuple
import click
from click.testing import CliRunner
from click_anno import command, click_app, attrs
def test_basic_arguments():
@command
def touch(filename):
click.echo(filenam... | StarcoderdataPython |
3264657 | <filename>modules/Eventlog/lv1_os_win_event_logs_shared_folder.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import os, sys, re
from datetime import datetime
from utility import database
class Shared_Folder_Information:
par_id = ''
case_id = ''
evd_id = ''
task = ''
time = ''... | StarcoderdataPython |
105971 | <gh_stars>0
from dataclasses import dataclass
from typing import Optional
from torch.utils.data import DataLoader
@dataclass
class DataLoaderCollection:
train_loader: DataLoader
test_loader: DataLoader
valid_loader: Optional[DataLoader] = None
| StarcoderdataPython |
4801934 | ''' corpusからwordデータを抜き出して、model作成するための前処理 '''
import re
from collections import Counter
import MeCab
from tqdm import tqdm
from modules.models.DbModel import DbModel
from modules.corpus_processing.WikiProcessing import WikiProcessing
from config.config import CONFIG
class WordProcessing():
''' 文章から単語の出現頻度を求めたり、単語... | StarcoderdataPython |
4842171 | <filename>src/graph/visu_sol.py
from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
import numpy as np
from itertools import product, combinations
fig = plt.figure()
ax = None
def create_subfig(row, col, place):
global ax
ax = fig.add_subplot(row, col, place, projection="3d")
def wires... | StarcoderdataPython |
1713660 | """Module that defines the message class."""
class Message(object):
"""Defines the message to be added in the response."""
def __init__(self, message: str) -> None:
"""
Instances the Message Class.
Args:
message: Aditional information of the response.
"""
... | StarcoderdataPython |
3312458 | from ._circuit_conversions import export_to_qiskit, import_from_qiskit
from ._openfermion_conversions import qiskitpauli_to_qubitop, qubitop_to_qiskitpauli
| StarcoderdataPython |
3359624 | <reponame>itsyaboyrocket/ttleveleditor<filename>leveleditor/ObjectMgr.py
"""
Defines ObjectMgr
"""
from ObjectMgrBase import *
class ObjectMgr(ObjectMgrBase):
""" ObjectMgr will create, manage, update objects in the scene """
def __init__(self, editor):
ObjectMgrBase.__init__(self, editor)
| StarcoderdataPython |
3235790 | <filename>tests/test_connection_spid.py
import ctds
from .base import TestExternalDatabase
from .compat import long_
class TestConnectionSpid(TestExternalDatabase):
'''Unit tests related to the Connection.spid attribute.
'''
def test___doc__(self):
self.assertEqual(
ctds.Connection.sp... | StarcoderdataPython |
1654803 | import cv2
import numpy
def merge_rectangle_contours(rectangle_contours):
merged_contours = [rectangle_contours[0]]
for rec in rectangle_contours[1:]:
for i in range(len(merged_contours)):
x_min = rec[0][0]
y_min = rec[0][1]
x_max = rec[2][0]
y_max = rec... | StarcoderdataPython |
199353 | <reponame>toyoshi/myCobotROS
#!/usr/bin/env python2
# license removed for brevity
import time, subprocess
import rospy
from sensor_msgs.msg import JointState
from std_msgs.msg import Header
from visualization_msgs.msg import Marker
from pymycobot.mycobot import MyCobot
def talker():
pub = rospy.Publisher('joint... | StarcoderdataPython |
1704987 | <reponame>raminjafary/ethical-hacking<gh_stars>0
#!/usr/bin/python2.7
#discover urls in the domain by extract the href link in the content and crawl recursively to get all urls
import requests
import re
import urlparse
target_url = "http://192.168.44.101"
target_links = []
def extract_links_from(url):
response = re... | StarcoderdataPython |
3251438 | from aiogram import types
from aiogram.dispatcher import FSMContext
from tortoise.exceptions import IntegrityError
from keyboards import inline
from keyboards.inline import back_callback, faculties, delete_callback, create_callback
from keyboards.inline.admin import cancel, cancel_or_delete, cancel_or_create
fr... | StarcoderdataPython |
3307459 | import numpy as np
from PIL import Image
def rebuild(dir):
images = np.zeros([7, 168, 168])
lvector = np.zeros([7, 3]) # the direction of light
for num in range(7):
image = Image.open(dir + '/train/' + str(num + 1) + '.bmp')
images[num] = np.asarray(image)
for line in open(dir... | StarcoderdataPython |
134965 | from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User
# from .models import Profile
#
# class ProfileInline(admin.StackedInline):
# """
#
# """
# model = Profile
# can_delete = False
# verbose_name_plural = 'Profile'
# fk_na... | StarcoderdataPython |
1652681 | # Generated by Django 2.2.2 on 2019-08-31 20:05
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('source_optics', '0020_statistic_days_before_joined'),
]
operations = [
migrations.AddField(
model_name='statistic',
... | StarcoderdataPython |
4823341 | from urllib.error import URLError, HTTPError
import logging
from time import time, sleep
from .configuration import config
from .jsonapi import JsonApi
from .util import random_secret
log = logging.getLogger(__name__)
class Vault(JsonApi):
def __init__(self, endpoint, token=None):
super().__init__(endp... | StarcoderdataPython |
1784515 | import click
def print_buckets(buckets):
click.echo(' buckets')
for bucket in buckets:
frozen = '[frozen]' if bucket['frozen'] else ''
click.echo(' + %-25s' % (bucket['name'] + frozen), nl=False)
if bucket['urls']:
urls = '(%s)' % ', '.join(bucket['urls'].keys())
... | StarcoderdataPython |
1656173 | <filename>11/aoc_11.py
import os
import numpy as np
INPUT = os.path.join(os.path.dirname(__file__), "input.txt")
with open(INPUT) as f:
lines = f.readlines()
lines = [list(l.rstrip()) for l in lines]
lines_arr = np.array(lines).astype(int)
def within_bounds(x, y, lower, upper):
full = np.transpose(np.vstac... | StarcoderdataPython |
1749100 | <gh_stars>0
from lx16a import *
"""
# This is the port that the controller board is connected to
# This will be different for different computers
# On Windows, try the ports COM1, COM2, COM3, etc...
# On Raspbian, try each port in /dev/
LX16A.initialize('/dev/ttyUSB0')
servo1 = LX16A(1)
servo2 = LX16A(2)
servo3 = LX16... | StarcoderdataPython |
1799719 | __version__ = '0.4.0.dev0+git'
| StarcoderdataPython |
3206805 | import logging
import pygame
from ._game_scene_manager import IProvideGameScenes
from ._game_session import IGameSession
logger = logging.getLogger(__name__)
class BlockingGameSession(IGameSession):
_scene_manager: IProvideGameScenes
def __init__(self, scene_manager: IProvideGameScenes) -> None:
s... | StarcoderdataPython |
1628868 | # coding=utf-8
# Copyright 2021 The Google Research Authors.
#
# 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 applicab... | StarcoderdataPython |
3244468 | # Copyright L.P.Klyne 2013
# Licenced under 3 clause BSD licence
# $Id: TestHttpAction.py 3499 2010-02-02 08:55:42Z philipp.schuster $
#
# Unit testing for WebBrick library functions (WbAccess.py)
# See http://pyunit.sourceforge.net/pyunit.html
#
# NOTE: this is not strictly a unit test, in that it requires a WebBri... | StarcoderdataPython |
1729342 | #!/usr/bin/env python3
"""
Day 8
for Advent of Code 2015
Link to problem description:
http://adventofcode.com/day/8
author:
<NAME>
(nitsas)
language:
Python 3.4.2
date:
December, 2015
usage:
$ python3 runme.py input.txt
or
$ runme.py input.txt
(where input.txt is the input file and $ the prompt)
"""
import sys
i... | StarcoderdataPython |
1711692 |
class PkgTypeEnum:
REQUIREMENT, DEPENDENCY = range(2)
| StarcoderdataPython |
166575 | import logging
from typing import Optional, Dict, List
import pysolr
import serpy
from manifest_server.helpers.fields import StaticField
from manifest_server.helpers.identifiers import get_identifier, IIIF_V3_CONTEXT
from manifest_server.helpers.metadata import v3_metadata_block, get_links
from manifest_server.helper... | StarcoderdataPython |
139325 | <gh_stars>1-10
from flask import Blueprint
project = Blueprint("project", __name__)
from app.project import routes # noqa: E402, F401
| StarcoderdataPython |
3367290 | from db import words
def test_get_id_for_word(db_conn):
cursor = db_conn.cursor()
assert words.get_id_for_word(cursor, '&c') == (1,)
# Should also test when the word *doesn't* exist in the database
assert words.get_id_for_word(cursor, 'rgnthm') is None
def test_get_word_for_id(db_conn):
cursor =... | StarcoderdataPython |
1794891 | n = int(input())
numbers = list(map(int, input().split()))
weights = list(map(int, input().split()))
result = 0
for index in range(n):
result += numbers[index] * weights[index]
result /= sum(weights)
print(round(result, 1))
| StarcoderdataPython |
19776 | <reponame>paulkramme/mit-license-adder
#!/usr/bin/python2
import tempfile
import sys
import datetime
mit_license = ("""\
/*
MIT License
Copyright (c) 2016 <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
... | StarcoderdataPython |
4843267 | <gh_stars>1-10
import os
import sys
try:
from balsam.core import models
from balsam.core.models import ApplicationDefinition, BalsamJob
from balsam.service import service
except:
pass
from deephyper.core.cli.utils import generate_other_arguments
from deephyper.core.exceptions import DeephyperRuntimeEr... | StarcoderdataPython |
1666306 | <filename>onmt/encoders/__init__.py<gh_stars>10-100
"""Module defining encoders."""
from onmt.encoders.encoder import EncoderBase
from onmt.encoders.transformer import TransformerEncoder
from onmt.encoders.rnn_encoder import RNNEncoder
from onmt.encoders.cnn_encoder import CNNEncoder
from onmt.encoders.mean_encode... | StarcoderdataPython |
88279 | def foo():
"""
Parameters:
a: foo
Returns:
None
""" | StarcoderdataPython |
3373995 | <reponame>jhoe123/Elastos.Hive.Node<gh_stars>1-10
# -*- coding: utf-8 -*-
URL_V2 = '/api/v2'
URL_SIGN_IN = '/did/signin'
URL_AUTH = '/did/auth'
URL_BACKUP_AUTH = '/did/backup_auth'
URL_SERVER_INTERNAL_BACKUP = '/vault-backup-service/backup'
URL_SERVER_INTERNAL_RESTORE = '/vault-backup-service/restore'
URL_SERVER_INTER... | StarcoderdataPython |
3384011 |
from dispy.types.User import User
import asyncio
class Guild:
# no support for threads
def __init__(self, args: dict) -> None:
self.id = int(args['id'])
self.name = args['name']
self.icon = args.get('icon', None)
self.icon_hash = args.get('icon_hash', None)
self.splash... | StarcoderdataPython |
3392101 | <gh_stars>10-100
#!/usr/bin/env python3
# This file is Copyright (c) 2016-2020 <NAME> <<EMAIL>>
# This file is Copyright (c) 2018-2019 <NAME> <<EMAIL>>
# License: BSD
import argparse
from migen import *
from migen.genlib.resetsync import AsyncResetSynchronizer
from litex.build.generic_platform import *
from litex.... | StarcoderdataPython |
55858 | <filename>program1.py
#This is my first program in python. Trying various things and capabilities of python
from datetime import datetime
import getpass
todaysDate = datetime.today().strftime('%d-%m-%Y')
welcomeMessage = "Hello " + getpass.getuser() + ' , welcome!'
userActions = 0
print('\n------------------------... | StarcoderdataPython |
1657683 | <reponame>cedadev/cloudhands-provider-iface<gh_stars>0
"""JASMIN Cloud
JASMIN Cloud Provider Interface package - command line client for Edge Gateway
interface
"""
__author__ = "<NAME>"
__date__ = "24/03/14"
__copyright__ = "(C) 2014 Science and Technology Facilities Council"
__license__ = "BSD - see LICENSE file in t... | StarcoderdataPython |
1613456 | <reponame>miiiingi/algorithmstudy
import re
p = re.compile('a[e]c')
m = p.match('adec')
print(m.group()) | StarcoderdataPython |
3212051 | <filename>Examples/study/chain_genetic_algorithm_multinode/compute_execution_time_multinode.py<gh_stars>0
import Source.io_util as io
import json
def get_n_maximum(iteration_partial_results, n_nodes):
time = [r['exec_time'] for n, r in iteration_partial_results.items() if n != 'selection']
time.sort(reverse=Tr... | StarcoderdataPython |
3285605 | <filename>broffeact/__init__.py<gh_stars>0
#!/usr/bin/python3
import datetime as dt
import os
import re
import argparse
from jinja2 import Template
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\0... | StarcoderdataPython |
3351090 | <gh_stars>10-100
from .chargen import CharGen
| StarcoderdataPython |
1731309 | from aiogram import types
from ..services.database import RedisDB
from ..utils import text
async def command_reset(message: types.Message, database: RedisDB):
await database.clear_received_urls(user_id=message.from_user.id)
await message.reply(
text=text.get_text(
language_code=message.f... | StarcoderdataPython |
1771762 | from typing import List
import numpy as np
from .mexpress import native_parse_f64, native_parse_f32
def _transform_x(x):
x = np.asarray(x)
# since we want to have both options f(*x) and f(x) we need to check the dimension
return x if x.ndim == 1 else x.squeeze()
class Mexpress:
def __init__(self, i... | StarcoderdataPython |
3287556 | #!/usr/bin/env python
# import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc
import matplotlib.patches as mpatches
import matplotlib
import os
# import random
# import time
ext = ".eps"
matplotlib.rcParams.update({'font.size': 17})
def activityDayCount():
labels = "2", "3", "4", "5", "6... | StarcoderdataPython |
125330 | import torch
import torch.nn as nn
import torch.nn.functional as F
import math
import pdb, time
from torch.autograd import Variable
torch.manual_seed(12)
SIGMA = 1
EPSILON = 1e-5
class GatedConv1d(nn.Module):
def __init__(self, input_channels, output_channels,
kernel_size, stride, pad... | StarcoderdataPython |
1688617 | import balanced
balanced.configure('<KEY>')
api_key = balanced.APIKey()
api_key.save() | StarcoderdataPython |
182570 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import logging
def TagNumDict(version_file_path):
tag_num_dict = {}
with open(version_file_path, 'r') as file:
for line in file.readlines():
line = line.strip()
tag = line.split('=')[0]
num = line.split('=')[1]
... | StarcoderdataPython |
3320569 | from django.urls import path
from petstagram.pets.views import *
urlpatterns = [
path('', AllPetsView.as_view(), name='list pets'),
path('create/', CreatePetView.as_view(), name='create pet'),
path('edit/<int:pk>', EditPetView.as_view(), name='edit pet'),
path('delete/<int:pk>', DeletePetView.as_view(... | StarcoderdataPython |
98468 | <reponame>jankokk/zoo
from setuptools import setup
with open('requirements.txt', 'r') as f:
requirements = f.read().splitlines()
setup_config = {
'name': 'pylfire',
'version': 0.1,
'packages': ['pylfire'],
'install_requires': requirements,
'author': '<NAME>',
'author_email': '<EMAIL>',
... | StarcoderdataPython |
1636646 | # -*- coding: utf-8 -*-
"""快代理自定义异常"""
import sys
class KdlException(Exception):
"""异常类"""
def __init__(self, code=None, message=None):
self.code = code
if sys.version_info[0] < 3 and isinstance(message, unicode):
message = message.encode("utf8")
self.messa... | StarcoderdataPython |
90046 | <reponame>QualiSystems/Ixia-IxChariotController-Shell<filename>src/driver.py
from cloudshell.shell.core.session.cloudshell_session import CloudShellSessionContext
from cloudshell.traffic.driver import TrafficControllerDriver
from ixc_handler import IxcHandler
class IxChariotControllerDriver(TrafficControllerDriver... | StarcoderdataPython |
3204127 | import threading
from threading import*
import time
f={}
def create(key,value,timeout=0):
if key in f:
print("key already exists")
else:
if(key.isalpha()):
if len(f)<(1024*1024*1024) and value<=(16*1024*1024):
if timeout==0:
l=[v... | StarcoderdataPython |
129979 | <reponame>neural-reckoning/decoding_sound_location
from brian import *
from brian.hears import *
from matplotlib import cm, rcParams
import sys, os, glob
sys.path = [os.path.normpath(os.path.join(os.path.split(__file__)[0], '../'))]+sys.path
from common import *
| StarcoderdataPython |
1643761 | <gh_stars>0
# -*- coding: utf-8 -*-
"""
@author: guqiuyang
@description: 封装用户类
@create time: 2018/12/18
"""
import json
import logging
import usertable
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from hashlib import sha1
class User(object):
def __init__(self, sql_json=None):... | StarcoderdataPython |
3239643 | """ Services model module. """
# Django imports
from django.db import models
from django.utils.translation import gettext_lazy as _
from django.core.validators import MaxValueValidator
# Utils Abstract model
from hisitter.utils.abstract_users import HisitterModel
class Service(HisitterModel):
""" This model hast... | StarcoderdataPython |
1631807 | # Iterate over two lists
alist = ["Red", "Blue", "Green"]
blist = [22, 33, 44]
for ii, jj in zip(alist, blist):
print(f"There are {jj} {ii} balls.")
# Update the counts
for idx, val in enumerate(alist):
if val == "Blue":
blist[idx] *= 100
for ii, jj in zip(alist, blist):
print(f"There are {jj} ... | StarcoderdataPython |
88189 | <filename>packages/gtmapi/lmsrvlabbook/api/mutations/bundledapp.py
import graphene
from gtmcore.inventory.inventory import InventoryManager
from lmsrvcore.auth.user import get_logged_in_username, get_logged_in_author
from lmsrvlabbook.api.objects.environment import Environment
from gtmcore.environment.bundledapp impor... | StarcoderdataPython |
3207975 | <filename>tests/test_sudo.py
# -*- coding: utf-8 -*-
import pytest
import plumbum
from plumbum import local
from plumbum._testtools import skip_on_windows
# This is a seperate file to make seperating (ugly) sudo command easier
# For example, you can now run test_local direcly without typing a password
class TestSu... | StarcoderdataPython |
123513 | <gh_stars>1-10
import json
import os
import sys
import time
from multiprocessing import Process
import requests
import websocket
from .objects import Key, Object
class ResponseError(Exception):
pass
class Client():
def __init__(self, callback):
self.callback = callback
self.host = os.gete... | StarcoderdataPython |
1798071 | from django.contrib.auth.decorators import login_required
from django.shortcuts import render
# Create your views here.
@login_required
def checkout(request):
context = {}
template = 'checkout.html'
return render(request,template,context) | StarcoderdataPython |
165511 | <reponame>PvrpleBlvck/Python_Learning_Journey
import tweepy
import os
TWITTER_API_KEY = os.getenv('TWITTER_API_KEY')
TWITTER_API_KEY_SECRET = os.getenv('TWITTER_API_KEY_SECRET')
TWITTER_ACCESS_TOKEN = os.getenv('TWITTER_ACCESS_TOKEN')
TWITTER_ACCESS_TOKEN_SECRET = os.getenv('TWITTER_ACCESS_TOKEN_SECRET')
# Authentica... | StarcoderdataPython |
1673935 | # python3
# Copyright 2021 InstaDeep Ltd. 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 applic... | StarcoderdataPython |
3277063 | <reponame>pirofti/SSPG
# Copyright (c) 2019-2020 <NAME> <<EMAIL>>
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS I... | StarcoderdataPython |
3221042 | #
# This file is part of pysnmp-apps software.
#
# Copyright (c) 2005-2017, <NAME> <<EMAIL>>
# License: http://snmplabs.com/pysnmp/license.html
#
from pysnmp_apps.cli import base
from pysnmp.entity import config
from pysnmp import error
authProtocols = {
'MD5': config.usmHMACMD5AuthProtocol,
'SHA': config.usm... | StarcoderdataPython |
17194 | #poly_gauss_coil model
#conversion of Poly_GaussCoil.py
#converted by <NAME>, Mar 2016
r"""
This empirical model describes the scattering from *polydisperse* polymer
chains in theta solvents or polymer melts, assuming a Schulz-Zimm type
molecular weight distribution.
To describe the scattering from *monodisperse* poly... | StarcoderdataPython |
27639 | import abc
from typing import List
from utils.datatypes import Source
class DataLoaderInterface(object):
@abc.abstractmethod
def get_name() -> str:
'''Returns an internal name for this loader'''
raise NotImplementedError("users must define a name for this loader")
@staticmethod
@abc.... | StarcoderdataPython |
3368881 | import os
import torch
import pickle
import pandas as pd
import numpy as np
from torch.utils.data import Dataset
import tqdm
def createDataCSV(dataset):
labels = []
texts = []
dataType = []
label_map = {}
name_map = {'wiki31k': 'Wiki10-31K',
'wiki500k': 'Wiki-500... | StarcoderdataPython |
3304157 | # 2021 - <NAME> - www.manualdocodigo.com.br
import sys
from PyQt5 import QtCore, QtWidgets, uic
from PyQt5.QtCore import QFile, QTextStream
class MainWindow(QtWidgets.QMainWindow):
def __init__(self, *args, **kwargs):
super(MainWindow, self).__init__(*args, **kwargs)
self.filename = ""
... | StarcoderdataPython |
130254 | <reponame>johnnoone/django-admincommand<gh_stars>10-100
def generate_instance_name(name):
out = name[0].lower()
for char in name[1:]:
if char.isupper():
out += "_%s" % char.lower()
else:
out += char
return out
def generate_human_name(name):
out = name[0]
for... | StarcoderdataPython |
3387690 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import json
import math
import string
import collections
import numpy as np
from keras import backend
from six.moves import xrange
from nets.layers import BatchNormalization
from keras import layers
... | StarcoderdataPython |
3259341 |
class Environment(object):
def __init__(self, loader, autoescape):
pass
class Template(object):
def __init__(self, source, autoescape):
pass
def select_autoescape(files=[]):
def autoescape(template_name):
pass
return autoescape
class FileSystemLoader(object):
def __ini... | StarcoderdataPython |
3376188 | <gh_stars>0
"""Start game"""
from Skier import Game
def main():
game = Game()
# if "keyboard_game=False", need to use "step(action)" to play
game.start(keyboard_game=True, increase_speed=1, low_speed=6, max_speed=15)
if __name__ == '__main__':
main()
| StarcoderdataPython |
3332411 | <reponame>bigfoolliu/liu_aistuff<gh_stars>1-10
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# author: bigfoolliu
"""
问题8: 100w个数中找出最大的100个数。时间复杂度尽可能的小
方案1:采用局部淘汰法。选取前100个元素,并排序,记为序列L。然后每次取出剩余的元素集合中的一个元素,与排好序的100个元素中最小的元素比,
如果比这个最小的要大,那么把这个最小的元素删除,并把x利用插入排序的思想,插入到序列L中。
依次循环,直到扫描了所有的元素。复杂度为O(100w*100)。
方... | StarcoderdataPython |
51117 | def is_string(thing):
try:
return isinstance(thing, basestring)
except NameError:
return isinstance(thing, str)
| StarcoderdataPython |
3318167 | from django.shortcuts import render
from .tasks import add
def calc(req):
if req.method == "POST":
add.send(float(req.POST["a"]), float(req.POST["b"]))
return render(req, "calc.html")
| StarcoderdataPython |
3217966 | <filename>input_data/mnist/mnist_input.py
# Copyright 2018 <NAME> 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
#
# U... | StarcoderdataPython |
1769181 | """
udf.py
written in Python3
author: <NAME> <<EMAIL>>
"""
import numpy as np
from refunction import Refunction
# Ensure that pandas DataFrame columns are not changed
def required_dataframe_columns(columns):
"""
Specify required columns in pandas DataFrames
Parameters
----------
columns : list o... | StarcoderdataPython |
3380454 | <gh_stars>1-10
from unittest import main
from .helpers import api, test_base
request_dynamic_parts = ["1337", "3.141592653589793", "dynamic_part_of_url"]
request_dynamic = "/".join(str(x) for x in request_dynamic_parts)
class RouteDynamicCases:
class RouteDynamicBase(test_base.TestBase):
def test_dynam... | StarcoderdataPython |
4832090 | <reponame>emcannaert/CMSSW
import FWCore.ParameterSet.Config as cms
primitiveRPCProducer = cms.EDProducer("L1TMuonRPCTriggerPrimitivesProducer",
Primitiverechitlabel = cms.InputTag("rpcdigis"),
Mapsource = cms.string('L1Trigger/L1TMuon/data/rpc/Linkboard_rpc_roll_mapping_lb_chamber2.txt'),
ApplyLi... | StarcoderdataPython |
1614772 | <reponame>Hvass-Labs/SwarmOps
########################################################################
# SwarmOps - Heuristic optimization for Python.
# Copyright (C) 2003-2016 <NAME>.
# See the file README.md for instructions.
# See the file LICENSE.txt for license details.
# SwarmOps on the internet: http://www.Hvass... | StarcoderdataPython |
4840940 | #!/usr/bin/env python3
#
# Authors: <NAME>
import sys
import json
import itertools
import logging
from hypertrace import do_hypertrace, mkabs
logging.basicConfig(stream=sys.stdout, level=logging.INFO)
logger = logging.getLogger(__name__)
clean = False
if len(sys.argv) > 1:
configfile = sys.argv[1]
if "--cle... | StarcoderdataPython |
141659 | <filename>examples/simple.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
.. codeauthor:: <NAME> <<EMAIL>>
"""
import os
from flask import Flask
from flask_tat.engine import TATClient
os.environ.setdefault('TAT_URL', 'http://1192.168.3.11')
os.environ.setdefault('TAT_USERNAME', 'test')
os.environ.setdefault('... | StarcoderdataPython |
4842565 | <gh_stars>10-100
from qtools.qtpy import QtCore, QtGui
from qtools.qtpy.QtCore import Qt
from galry import Manager, ordict
import numpy as np
__all__ = ['BindingManager', 'Bindings']
class BindingManager(Manager):
"""Manager several sets of bindings (or interaction modes) and allows
to switch between sever... | StarcoderdataPython |
4819357 | from typing import Optional
import sys
import click
from PyInquirer import prompt, Separator
from contxt.cli.clients import Clients
from contxt.utils.serializer import Serializer
from contxt.utils.config import ContextException
@click.group()
def env() -> None:
"""Contxt Environment Functions"""
@env.command()
... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.