id stringlengths 1 265 | text stringlengths 6 5.19M | dataset_id stringclasses 7
values |
|---|---|---|
127371 | <filename>secret.py
# Change these to your instagram login credentials.
username = "Username"
password = "Password"
| StarcoderdataPython |
1733504 | #!/usr/bin/env python2
import fileinput
import re
TAB_LENGTH = 4
def prependTabs(string, numTabs=1):
return numTabs * TAB_LENGTH * ' ' + string
def getVariables(string):
regex = r'\$[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*'
return re.findall(regex, string)
def createVariableDeclaration(variable):
... | StarcoderdataPython |
1755081 | from .etl_helper import ETLHelper
from .neo4j_helper import Neo4jHelper
from .assembly_sequence_helper import AssemblySequenceHelper
from .obo_helper import OBOHelper
from .resource_descriptor_helper_2 import ResourceDescriptorHelper2
from .text_processing_helper import TextProcessingHelper
| StarcoderdataPython |
3393321 | """ Example showing how to use visual search APIs via python SDK.
"""
from pprint import pprint
from props import *
from cfapivisualsearch.sdk import VisualSearch
#------------------------------------------------------------------------------
# Initialize.
#----------------------------------------------------------... | StarcoderdataPython |
3230972 | from boiler import bootstrap
from boiler.config import TestingConfig
from shiftuser.config import UserConfig
"""
Create app for testing
This is not a real application, we only use it to run tests against.
"""
class Config(TestingConfig, UserConfig):
USER_JWT_SECRET = 'typically will come from environment'
SE... | StarcoderdataPython |
1641057 | try:
from meu_grafo import MeuGrafo
except Exception as e:
print(e)
# Grafo da Paraíba
g_p = MeuGrafo(['J', 'C', 'E', 'P', 'M', 'T', 'Z'])
g_p.adicionaAresta('a1', 'J', 'C')
g_p.adicionaAresta('a2', 'C', 'E')
g_p.adicionaAresta('a3', 'C', 'E')
g_p.adicionaAresta('a4', 'P', 'C')
g_p.adicionaAresta('a5', 'P', 'C')
g... | StarcoderdataPython |
1752333 | # Write your solution for 1.2 here!
sum =0
for i in range(101):
if(i%2==0):
sum+=i
print(sum) | StarcoderdataPython |
1685952 | <reponame>enhatem/quadrotor_mpc_acados
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d
def trajectory_generator(T_final, N, traj=0, show_traj=False):
'''
Generates a circular trajectory given a final time and a sampling time
'''
r = 0.5 # radius
th = np.linspace... | StarcoderdataPython |
3385728 | #!/usr/bin/env python3
import numpy as np
import scipy.linalg
try:
import lib.metrics as metrics
except ModuleNotFoundError:
import metrics
__all__ = ["OLSRegression", "RidgeRegression", "LassoRegression"]
class __RegBackend:
"""Backend class in case we want to run with either scipy, numpy
(or somet... | StarcoderdataPython |
4816952 | <gh_stars>10-100
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# dis... | StarcoderdataPython |
22276 | ##
## Evaluation Script
##
import numpy as np
import time
from sample_model import Model
from data_loader import data_loader
from generator import Generator
def evaluate(label_indices = {'brick': 0, 'ball': 1, 'cylinder': 2},
channel_means = np.array([147.12697, 160.21092, 167.70029]),
data... | StarcoderdataPython |
3233811 | #! /usr/bin/env python3
# MIT License
#
# Copyright (c) 2018 <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, co... | StarcoderdataPython |
149678 | # Code generated by moonworm : https://github.com/bugout-dev/moonworm
# Moonworm version : 0.1.15
import argparse
import json
import os
from pathlib import Path
from typing import Any, Dict, List, Optional, Union
from brownie import Contract, network, project
from brownie.network.contract import ContractContainer
fro... | StarcoderdataPython |
1679371 | <gh_stars>1-10
# Copyright (c) 2020 PaddlePaddle 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 ... | StarcoderdataPython |
3358257 | import numpy as np
import pandas as pd
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import OneHotEncoder
import os
import pickle
raw = pd.read_csv('heloc_dataset_v1.csv', na_values = [-9])
# raw = pd.read_csv('heloc_dataset_v1.csv')
#### transform target
raw.loc[raw['RiskPerformance'] == 'Good'... | StarcoderdataPython |
96134 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 14 22:55:34 2021
@author: logan
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
import sys; sys.path.append("../../meshcnn")
from meshcnn.ops import MeshConv, DownSamp, ResBlock
import os
class DownSamp(nn.Module):
def... | StarcoderdataPython |
4806101 | <filename>molsysmt/element/molecule/__init__.py
from . import water
from . import ion
from . import cosolute
from . import small_molecule
from . import peptide
from . import protein
from . import dna
from . import rna
from . import lipid
from .get_molecule_index_from_atom import get_molecule_index_from_atom
from .get_... | StarcoderdataPython |
3380226 | <reponame>wakaflorien/cst-research-api<gh_stars>1-10
# Generated by Django 3.2.2 on 2021-09-18 09:57
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('staff', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name... | StarcoderdataPython |
162277 | from fastapi import Depends
from server.dependencies import get_db
from sqlalchemy.orm import Session
from users.schemas import Token_Schema
from .models import User, Blacklisted_Token
def register_or_login(user_data: dict, user_type: str, db: Session = Depends(get_db)):
email = user_data["email"]
name = use... | StarcoderdataPython |
3380114 | <filename>handler.py
import json
import os
import sys
here = os.path.dirname(os.path.realpath(__file__))
sys.path.append(os.path.join(here, "./vendored"))
import requests
TOKEN = os.environ['TELEGRAM_TOKEN']
BASE_URL = "https://api.telegram.org/bot{}".format(TOKEN)
def hello(event, context):
try:
data =... | StarcoderdataPython |
3391530 |
from minerl.herobraine.hero.handlers.actionable import *
from minerl.herobraine.hero.handlers.mission import *
from minerl.herobraine.hero.handlers.observables import *
from minerl.herobraine.hero.handlers.rewardables import *
| StarcoderdataPython |
45237 | DEFAULT_OCR_AUTO_OCR = True
DEFAULT_OCR_BACKEND = 'mayan.apps.ocr.backends.tesseract.Tesseract'
DEFAULT_OCR_BACKEND_ARGUMENTS = {'environment': {'OMP_THREAD_LIMIT': '1'}}
TASK_DOCUMENT_VERSION_PAGE_OCR_RETRY_DELAY = 10
TASK_DOCUMENT_VERSION_PAGE_OCR_TIMEOUT = 10 * 60 # 10 Minutes per page
| StarcoderdataPython |
3230747 | # Solution 1
# O(bns) time / O(n) space
# b length of the bigString
# n length of the smallStrings array
# s length of the largest small string
def multiStringSearch(bigString, smallStrings):
return [isInBigString(bigString, smallString) for smallString in smallStrings]
def isInBigString(bigString, smallString):
... | StarcoderdataPython |
3273186 | import re
import ipaddress
import argparse
class nmapError(Exception):
pass
class nmap(object):
IPV4_RE = r'(\d{1,3}\.){3}\d{1,3}'
CIDR_RE = r'^{}/[1-3]?[0-9]$'.format(IPV4_RE)
OPTION = 1
HOST = 2
PORT = 3
SCRIPT = 4
OPTION_LIST = ['-PR', '-PS', '-sS', '-sT', '-sU', '-sA', '-OT']
... | StarcoderdataPython |
1793541 | <reponame>codescribblr/project-manager-django3<gh_stars>0
# Generated by Django 3.0.4 on 2020-03-19 17:56
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('accounts', '0... | StarcoderdataPython |
74306 | <reponame>SykieChen/WeiboBlackList
import requests
class WeiboSession(requests.Session):
def __init__(self, username, password):
super(WeiboSession, self).__init__()
self.__username = username
self.__password = password
def __del__(self):
self.close()
def login(self):
... | StarcoderdataPython |
41016 | from datetime import timedelta
import app_config
import dateutil.parser
from googleapiclient.discovery import build
from injector import inject
from models import AllDayCalendarEntry, CalendarEntry
from google_api import GoogleAuthenication
class GoogleCalendar:
@inject
def __init__(self, auth: GoogleAuthe... | StarcoderdataPython |
1645682 | # https://www.hackerrank.com/challenges/python-lists/problem
queries = int(input())
data = []
for _ in range(queries):
command, *parameter = input().split()
parameters = list(map(int, parameter))
if command == 'insert':
data.insert(parameters[0], parameters[1])
elif command == 'print':
... | StarcoderdataPython |
3327489 | <filename>Phaedra/__main__.py
from Phaedra.Language import Mode, set_mode
from Phaedra.Secrets import get_secrets, set_secrets
set_secrets(get_secrets())
set_mode(Mode.REMOTE)
from Phaedra.API import run
run()
# from json import dump
# from Phaedra.Notebook import Notebook
# dump(
# Notebook.from_pdf(path="C:/... | StarcoderdataPython |
113395 | <reponame>snwhd/pyretrommo
#!/usr/bin/env python3
# this file is auto-generated by gen_from_wiki.py
from __future__ import annotations
from typing import (
Dict,
Tuple,
)
from ..item import EquipmentItem
from .ability import Ability
from .equipment import find_equipment
from .player_class import PlayerClass
C... | StarcoderdataPython |
3267542 | def login(username, password) :
user_data = username + ":" + password + "\n"
try:
auth_data = open("start.auth", "r")
except FileNotFoundError :
print("Wrong Username or Password \n")
return False
auth_state = False
# print auth_data.readlines()
for auth in... | StarcoderdataPython |
3250856 | <reponame>mwiens91/twitch-game-notify
"""Functions for processing and displaying notifications."""
import datetime
import logging
import time
import notify2
import requests
from twitchgamenotify.constants import HTTP_502_BAD_GATEWAY
from twitchgamenotify.twitch_api import FailedHttpRequest
from twitchgamenotify.versio... | StarcoderdataPython |
1615663 | import sys
import socket
try:
import pika
except ImportError:
print("RabbitMQ test requested, but pika not installed. "
"Try 'pip install pika' and try again.")
sys.exit(1)
def rabbit_check(config):
host = config.get("host", "localhost")
port = int(config.get("port", 5672))
params = p... | StarcoderdataPython |
3345279 | <reponame>luck97/LP2_2s2017
# -*- coding: utf-8 -*-
# Exercícios by <NAME> (CodingBat)
# F. middle_way
# sejam duas listas de inteiros a e b
# retorna uma lista de tamanho 2 contendo os elementos do
# meio de a e b, suponha que as listas tem tamanho ímpar
# middle_way([1, 2, 3], [4, 5, 6]) -> [2, 5]
# middle_way([7, 7... | StarcoderdataPython |
3324627 | <reponame>ManishSahu53/wifi-finder
import numpy as np
from src import point, vector, line, source
# Initializing Wifi source at random 3D location, which we don't know
sx, sy, sz = np.random.randint(0, 100, 1)[0], np.random.randint(0, 100, 1)[0], np.random.randint(0, 100, 1)[0]
wifi = source.Source(sx, sy, sz)
# In... | StarcoderdataPython |
3260631 | from hubcheck.pageobjects.po_generic_page import GenericPage
from hubcheck.pageobjects.basepageelement import Link
class ToolsPipelinePage(GenericPage):
"""page that lists all tool resources"""
def __init__(self,browser,catalog):
super(ToolsPipelinePage,self).__init__(browser,catalog)
self.pat... | StarcoderdataPython |
4839206 | import logging
from pathlib import Path
from typing import Any, List, Optional, Tuple
import networkx
import osmnx
from more_itertools import pairwise
from networkx_astar_path import astar_path
from . import exceptions, models, weights
from .utils.debug import timeit
from .utils.graph import load_map
logger = loggin... | StarcoderdataPython |
3360098 | """
Test ABC parsing
"""
from pyabc2.parse import INFO_FIELDS, Tune
# Norbeck version
# http://www.norbeck.nu/abc/display.asp?rhythm=jig&ref=12
abc_have_a_drink = """
X:12
T:Have a Drink with Me
R:jig
D:Patrick Street 1.
Z:id:hn-jig-12
M:6/8
K:G
BAG E2D|EGD EGA|BAB GED|EAA ABc|BAG E2D|EGD EGA|BAB GED|EGG G3:|
|:GBd e2... | StarcoderdataPython |
109268 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# thumbor imaging service
# https://github.com/thumbor/thumbor/wiki
# Licensed under the MIT license:
# http://www.opensource.org/licenses/mit-license
# Copyright (c) 2011 globo.com <EMAIL>
from json import loads, dumps
import hashlib
import pylibmc
from thumbor.storages i... | StarcoderdataPython |
1719550 | import torch
from .registry import DATASETS
from .base import BaseDataset
def rotate(img):
'''
img: Tensor(CHW)
'''
return [
img,
torch.flip(img.transpose(1, 2), [1]),
torch.flip(img, [1, 2]),
torch.flip(img, [1]).transpose(1, 2)
]
@DATASETS.register_module
class... | StarcoderdataPython |
1789817 | <reponame>amaurirg/Web2Py
# -*- coding: utf-8 -*-
#########################################################################
## This scaffolding model makes your app work on Google App Engine too
#########################################################################
if request.env.web2py_runtime_gae: # ... | StarcoderdataPython |
1757204 | #!/usr/bin/python
#-*- coding: utf-8 -*-
# >.>.>.>.>.>.>.>.>.>.>.>.>.>.>.>.
# Licensed under the Apache License, Version 2.0 (the "License")
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# --- File Name: hd_networks_stylegan2.py
# --- Creation Date: 22-04-2020
# --- Last Modif... | StarcoderdataPython |
1780078 | #unit test script to test sum module under my_sum
import sys
sys.path.append('/home/user/workarea/projects/learn-pyspark/jobs/samples/')
import unittest
from calc import basic
class TestSum(unittest.TestCase):
def test_list_int(self):
"""
Test that it can sum a list of integers
"""
... | StarcoderdataPython |
4830413 | <gh_stars>0
import random
def play():
print("Welcome to my game")
secret_number = 42
total_attempts = 3
attempts = 1
for attempts in range (1, total_attempts+1):
##.format is String interpolation
print("You have {} attemps the {}".format(attempts, total_attempts))
chute_str... | StarcoderdataPython |
3037 | import platform
import shutil
import tempfile
import warnings
from pathlib import Path
import requests
from tqdm import tqdm
DOCKER_VERSION = "20.10.5"
BUILDX_VERSION = "0.5.1"
CACHE_DIR = Path.home() / ".cache" / "python-on-whales"
TEMPLATE_CLI = (
"https://download.docker.com/{os}/static/stable/{arch}/docker-... | StarcoderdataPython |
1734688 | <reponame>koyoo-maxwel/sudoPay
from django import forms
from .models import Account , Profile
from django.contrib.auth.models import User
class UserUpdateForm (forms.ModelForm):
class Meta:
model = User
fields = ['username','email']
class ProfileUpdateForm (forms.ModelForm):
class Meta:
... | StarcoderdataPython |
1670280 | # -*- coding: utf-8 -*-
__title__ = 'latinpigsay'
__license__ = 'MIT'
__author__ = '<NAME>'
__author_email__ = '<EMAIL>'
__created_on__ = '12/3/2014'
"""
Created on Wed Dec 3 17:36:17 2014
@author: steven_c
"""
acidtest = """Can you talk piglatin to piglatin.
"""
quotes = """A Tale of Two Cities LITE(tm)
-- ... | StarcoderdataPython |
1654472 | <filename>python/custom_transformer/setup.py
# Copyright 2021 The KServe 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 ... | StarcoderdataPython |
19406 | <reponame>hanyas/pyro_examples
import torch
from torch.distributions import Gamma
import torch.nn.functional as F
import matplotlib.pyplot as plt
from tqdm import tqdm
from pyro.distributions import *
import pyro
from pyro.optim import Adam
from pyro.infer import SVI, Trace_ELBO, Predictive
assert pyro.__version__... | StarcoderdataPython |
69657 | <reponame>PKUfudawei/cmssw
import FWCore.ParameterSet.Config as cms
process = cms.Process("TrackerMapProd")
process.MessageLogger = cms.Service("MessageLogger",
cablingReader = cms.untracked.PSet(
threshold = cms.untracked.string('INFO')
),
cerr = cms.untracked.PSet(
enable = cms.untracke... | StarcoderdataPython |
3236614 | <gh_stars>0
from tkinter import *
from PIL import ImageTk, Image
root = Tk()
root.title('Image Viewer')
root.iconbitmap('im_logo.ico')
frame=LabelFrame(root, text="I am here",padx=5,pady=5).grid(row=0,column=0)
b= Button(frame,text="This will make you exit",command=root.quit).grid(row=0,column=1)
image1 = Im... | StarcoderdataPython |
1699600 | import pyparsing
from pyparsing import Word, WordStart, WordEnd, ZeroOrMore, Optional
class reference_patterns:
def __init__(self):
real_word_dashes = Word(pyparsing.alphas + "-")
punctuation = Word(".!?:,;-")
punctuation_no_dash = Word(".!?:,;")
punctuation_reference_letter = Word... | StarcoderdataPython |
183222 | <filename>src/django_clickhouse/routers.py
"""
This file defines router to find appropriate database
"""
from typing import Type
import random
import six
from infi.clickhouse_orm.migrations import Operation, DropTable, CreateTable
from .clickhouse_models import ClickHouseModel
from .configuration import config
from .... | StarcoderdataPython |
105813 | import collections.abc
from functools import partial
from urllib.parse import urlencode
from geopy.exc import ConfigurationError, GeocoderQueryError
from geopy.geocoders.base import _DEFAULT_USER_AGENT, DEFAULT_SENTINEL, Geocoder
from geopy.location import Location
from geopy.util import logger
__all__ = ("Nominatim"... | StarcoderdataPython |
1679962 | frase = str(input('Digite uma frase qualquer: ')).strip().upper()
#Faça um programa que leia uma frase pelo teclado e mostre quantas vezes aparece a letra “A”,
print(f'A letra "A" apareceu', frase.count('A'), 'vezes')
# em que posição ela aparece a primeira vez
print(f'A letra "A" apareceu na posição', frase.find('A')... | StarcoderdataPython |
36369 | <reponame>MilosRasic98/Orbweaver-Rover
#!/usr/bin/env python3
import rospy
import serial
from std_msgs.msg import Float32
tt_arduino = serial.Serial("/dev/ttyUSB0", 9600)
rospy.init_node('torque_test_stand', anonymous = False)
pub = rospy.Publisher('/test_equipment/measured_torque', Float32, queue_size=10)
r = rospy... | StarcoderdataPython |
3222070 | """
Functions to unpack Simrad EK60 .raw and save to .nc.
Pieces for unpacking power data came from:
https://github.com/oceanobservatories/mi-instrument (authors: <NAME> & <NAME>)
with modifications:
- python 3.6 compatibility
- strip off dependency on other mi-instrument functions
- unpack split-beam angle data
- unp... | StarcoderdataPython |
1689206 | <gh_stars>1-10
import mailbox
import sys
from sets import Set
from operator import itemgetter
import time
import email.utils
import re
import os
from git import Repo
import atexit
import shutil
import smtplib
from email.mime.text import MIMEText
email_message_failed = '''Patch set failed to apply to the current HEAD.
... | StarcoderdataPython |
3307356 | <reponame>trh0ly/Derivate
"""
Dieses Beispiel stammt aus dem Buch "Python for Finance - Second Edition" von Yuxing Yan: https://www.packtpub.com/big-data-and-business-intelligence/python-finance-second-edition
Sämtliche Beispiele sind in leicht abgewandeltet Form zu finden unter: https://github.com/PacktPublishing/Py... | StarcoderdataPython |
17675 | from __future__ import division, print_function, absolute_import
from .core import SeqletCoordinates
from modisco import util
import numpy as np
from collections import defaultdict, Counter, OrderedDict
import itertools
import sys
import time
from .value_provider import (
AbstractValTransformer, AbsPercentileValTra... | StarcoderdataPython |
43733 | from src.objects.Track import Track
from src.usesful_func import start_pygame_headless
start_pygame_headless()
track = Track("tracks/tiny.tra")
def test_car_human():
from src.cars.CarHuman import CarHuman
car = CarHuman(track)
assert car
def test_car_ai():
from src.cars.CarAI import CarAI
fr... | StarcoderdataPython |
3208567 | <gh_stars>0
import ab
print(ab.a) | StarcoderdataPython |
179883 | #!/usr/bin/env python
from PartsManager import PartsManager
from MachinePNP import Machine
from getchar import getchar
import time, os, pickle, sys, math
# coordinate systems
# G53 machine
# G54 camera
# G55 paste
# G56 place
# G57 part tape 0
try:
import BeautifulSoup
except:
import ... | StarcoderdataPython |
3295789 | <filename>tests/test_latentdistributiontest.py
# <NAME>
# bvarjavand [at] jhu.edu
# 02.26.2019
import unittest
import numpy as np
from graspy.inference import LatentDistributionTest
from graspy.simulations import er_np, sbm
class TestLatentDistributionTest(unittest.TestCase):
@classmethod
def setUpClass(cl... | StarcoderdataPython |
1773199 | # Generated by Django 4.0.3 on 2022-04-05 09:12
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('home', '0010_sitesettings_moderator_reply_name_and_more'),
]
operations = [
migrations.AddField(
model_name='sitesettings',
... | StarcoderdataPython |
77736 | """Реализация разделов сайта для работы с пользователями."""
import os
from flask import Blueprint, flash, redirect, render_template, request, url_for
from flask_login import current_user, login_required, login_user, logout_user
from werkzeug.urls import url_parse
from webapp.account.models import Account
from webapp... | StarcoderdataPython |
3233956 | <gh_stars>1-10
##############################################################################
# cpuspinner.py
##############################################################################
# Class used to keep the game looping. Generates a tick event each time
# the game loops.
###################################... | StarcoderdataPython |
3215765 | <reponame>ViliamVadocz/AutoLeague2
import shutil
from typing import Mapping, Tuple, Optional
from rlbot.parsing.bot_config_bundle import BotConfigBundle
from rlbot.setup_manager import setup_manager_context
from rlbot.training.training import Fail
from rlbottraining.exercise_runner import run_playlist, RenderPolicy
f... | StarcoderdataPython |
1704688 | <reponame>OP2/PyOP2<filename>pyop2/types/dataset.py
import numbers
import numpy as np
from petsc4py import PETSc
from pyop2 import (
caching,
datatypes as dtypes,
exceptions as ex,
mpi,
utils
)
from pyop2.types.set import ExtrudedSet, GlobalSet, MixedSet, Set, Subset
class DataSet(caching.Object... | StarcoderdataPython |
3390974 | import numpy
from .AssemblyFlaw import AssemblyFlaw
class Assembly:
"""Base class to represent assemblies. See GibsonAssembly, BASICAssembly,
etc. for usage classes
Parameters
----------
parts
List of part names corresponding to part records in a repository
name
Name of the a... | StarcoderdataPython |
3266870 | import sys
# look in ../ BEFORE trying to import Algorithmia. If you append to the
# you will load the version installed on the computer.
sys.path = ['../'] + sys.path
import unittest, os, uuid
import Algorithmia
from Algorithmia.datafile import DataFile, LocalDataFile
class DataFileTest(unittest.TestCase):
de... | StarcoderdataPython |
4808189 | # -*- coding: utf-8 -*-
"""
Created on Mon Jul 9 20:57:29 2012
@author: garrett
@email: <EMAIL>
original pygmail from:
https://github.com/vinod85/pygmail/blob/master/pygmail.py
"""
import imaplib, smtplib
import re
from email.mime.text import MIMEText
class pygmail(object):
IMAP_SERVER='imap.gmail.com... | StarcoderdataPython |
1706833 | <reponame>sling254/Newscatch
from flask import render_template, url_for
from . import main
from ..request import get_news_source, get_articles
@main.route('/')
def index():
"""
a function to view the home page
"""
technology = get_news_source('technology')
sports = get_news_source('sports')
... | StarcoderdataPython |
89996 | <filename>autovirt/equipment/interface/__init__.py
from .equipment import EquipmentGateway
| StarcoderdataPython |
111789 | <reponame>ploshkin/hivemind<filename>hivemind/client/optim/collaborative.py
from __future__ import annotations
import warnings
from dataclasses import dataclass
from threading import Thread, Lock, Event
from typing import Optional, Type
import logging
import torch
import numpy as np
from hivemind.dht import DHT
from ... | StarcoderdataPython |
3273070 | from sympy.abc import x
import sympy as sp
import math
def newton_iteration(x0, func, tol=1e-9, Max_iter=100):
""" Solve non-linear equation by Newton iteratin method.
Args:
x0: double, the initial value of the iteration
func: symbol object, the non-linear equation to be solved
tol: d... | StarcoderdataPython |
4808551 | <reponame>rGunti/flpy_bank
from dataclasses import asdict
from typing import List
import yaml
from flpy_bank.exporter import DataExporter
from flpy_bank.objects import Record
class YamlExporter(DataExporter):
def __init__(self,
file: str):
self.file = file
def export_data(self, dat... | StarcoderdataPython |
157059 | from torchtext import data
from torchtext import datasets
# Testing SNLI
print("Run test on SNLI...")
TEXT = datasets.nli.ParsedTextField()
LABEL = data.LabelField()
TREE = datasets.nli.ShiftReduceField()
train, val, test = datasets.SNLI.splits(TEXT, LABEL, TREE)
print("Fields:", train.fields)
print("Number of examp... | StarcoderdataPython |
1789249 | class Vehicle:
def __init__(self,regnum,make,model,color):
self.regnum=regnum
self.make=make
self.model=model
self.color=color
class PassengerVehicle(Vehicle):
def __init__(self, regnum, make, model, color,pasCap):
super().__init__(regnum, make, model, color)
... | StarcoderdataPython |
1687434 | import sys
import dask.dataframe as dd
from handling_data.handling_data import HandlingData
from automl.mltrons_automl import MltronsAutoml
ddf = dd.read_csv("titanic.csv")
target_variable = 'Survived'
problem_type = 'Classification'
h = HandlingData(ddf, target_variable, problem_type)
train_pool, test_pool, order_o... | StarcoderdataPython |
1692401 | <gh_stars>0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 3 13:45:43 2020
@author: antony
"""
import json
import time
import urllib.request
import collections
import subprocess
import re
pubs = json.load(open('publications.json', 'r'))
URL = 'https://www.ncbi.nlm.nih.gov/pubmed/?term={}&re... | StarcoderdataPython |
1782592 | <reponame>dolong2110/Algorithm-By-Problems-Python
from typing import List
def sortedSquares(nums: List[int]) -> List[int]:
answer = [0] * len(nums)
l, r = 0, len(nums) - 1
while l <= r:
left, right = abs(nums[l]), abs(nums[r])
if left > right:
answer[r - l] = left * left
... | StarcoderdataPython |
3341532 | <filename>document.py
import calendar
import click
import locale
import yaml
from datetime import date
from mailmerge import MailMerge
from os import path
locale.setlocale(locale.LC_TIME, 'es_ES.UTF-8')
CONFIG = "config.yml"
TEMPLATE_1 = "cuenta-de-cobro-v1.docx"
TEMPLATE_2 = "cuenta-de-cobro-v2.docx"
def load_conf... | StarcoderdataPython |
1731276 | def is_letter(s:str):
if len(s) == 1 and s.isalpha():
return True
return False | StarcoderdataPython |
3334517 | import logging
from xv_wb import xv_wb
from xv_kws import xv_kws
import json, asyncio
# 默认日志
logging.getLogger().setLevel(logging.INFO)
class xv:
def __init__(self):
self.is_kws = False
self.kws = xv_kws()
self.websocket_server = xv_wb(main=self.main)
async def main(self, websock... | StarcoderdataPython |
3394113 | """
integration tests on doppel-describe
commandline entrypoint (targeting a
python package)
"""
import json
import os
import pytest
# details that will always be true of doppel-describe output
EXPECTED_TOP_LEVEL_KEYS = set([
"name",
"language",
"functions",
"classes"
])
NUM_TOP_LEVEL_KEYS = len(EXPEC... | StarcoderdataPython |
4813326 | <gh_stars>1-10
"""conftest.py -- Configure pytest.
https://docs.pytest.org/en/reorganize-docs/example/simple.html#control-skipping-of-tests-according-to-command-line-option
"""
import pytest
def pytest_addoption(parser):
parser.addoption("--runslow", action="store_true",
help="run slow tests") | StarcoderdataPython |
140706 | #!/usr/bin/env python
# -*- coding: UTF-8 -*-
import cv2
import numpy as np
import constants as const
import transformations.shadow_mask as mask
def add_n_ellipses_light(image, intensity = 0.5, blur_width = 6, n = 1):
inverted_colors = const.WHITE - image
inverted_shadow = add_n_ellipses_shadow(inverted_colors, i... | StarcoderdataPython |
145052 | # -*- coding: utf-8 -*-
"""
Created on 12 April, 2019
@author: Tarpelite
"""
import requests,re,collections
from bs4 import BeautifulSoup
import json
# choose your demand
Max_page = 2
key = 'sparse+autoencoder'
start = '2000'
final = '2018'
text_title = 'GStitle.txt'
text_keyword = 'GSkw.txt'
headers = {'User-Agen... | StarcoderdataPython |
3377690 | """
This is an AWS Lambda function that watches specific files of a public GitHub
repository since a given date, if it detects new changes, it notifies the user
via Telegram (using a Telegram bot).
"""
from __future__ import annotations # https://www.python.org/dev/peps/pep-0563/
import json
import os
import urllib.e... | StarcoderdataPython |
23256 | from sklearn import tree
from matplotlib import pyplot as plt
from sklearn.model_selection import cross_val_score
from sklearn.model_selection import train_test_split
from sklearn import model_selection
from sklearn import metrics
import numpy as np
import pandas as pd
import seaborn as sns
from sklearn.neighbors impor... | StarcoderdataPython |
100973 | <reponame>mamoanwar97/Anynet_modified
import numpy as np
import skimage
import skimage.io
import torch
import torch.nn as nn
import torch.nn.parallel
import torch.optim as optim
import torch.utils.data
import torch.nn.functional as F
from torchvision.utils import save_image
import torch.backends.cudnn as cudnn
from d... | StarcoderdataPython |
3280581 | """File holding the Enums and Exceptions for the application. Constants, basically """
from enum import Enum
class Direction(Enum):
""" Enum with possible rotations for the item. Its actual value is unimportant"""
LEFT = -90
RIGHT = 90
class Facing(Enum):
""" Enum with possible facings for the item. ... | StarcoderdataPython |
125172 | <reponame>LLNL/LBANN<filename>ci_test/integration_tests/test_integration_onnx_output.py
import functools
import operator
import os
import os.path
import re
import sys
import numpy as np
import google.protobuf.text_format
import pytest
# Local files
current_file = os.path.realpath(__file__)
current_dir = os.path.dirnam... | StarcoderdataPython |
4826559 | <reponame>lokesh-lraj/30-Day-LeetCoding-Challenge-april_2020
"""
Given a binary tree where each path going from the root to any leaf form a valid sequence, check if a given string is a valid sequence in such binary tree.
We get the given string from the concatenation of an array of integers arr and the concatenation ... | StarcoderdataPython |
3241271 | from bs4 import BeautifulSoup
from urllib2 import urlopen
from pprint import pprint
import re
def fetch_html (url, process_callback):
response = urlopen(url)
return process_callback(BeautifulSoup(response.read(), 'html.parser'))
def enforce (condition, msg, *args):
if not condition:
raise Excepti... | StarcoderdataPython |
1646274 | #!/usr/bin/env python
kmh = int(raw_input("Enter km/h: "))
mph = 0.6214 * kmh
print "Speed:", kmh, "KM/H = ", mph, "MPH"
| StarcoderdataPython |
3388073 | <gh_stars>0
import numpy as np
import gym
class State:
def __init__(self, state_space):
self.past_states = []
self.current, self.previous = None, None
if isinstance(state_space, gym.spaces.box.Box):
self.low = state_space.low
self.high = state_space.high
... | StarcoderdataPython |
1634162 | <filename>cisco-ios-xr/ydk/models/cisco_ios_xr/Cisco_IOS_XR_bundlemgr_cfg.py
""" Cisco_IOS_XR_bundlemgr_cfg
This module contains a collection of YANG definitions
for Cisco IOS\-XR bundlemgr package configuration.
This module contains definitions
for the following management objects\:
lacp\: Link Aggregation Contro... | StarcoderdataPython |
1656269 | <filename>datahoarder/web.py
import os
from flask import Flask, jsonify, request, send_from_directory
from flask_cors import CORS
from datahoarder.source import *
from datahoarder.download import get_download_status
from datahoarder.run import sync
app = Flask(__name__)
CORS(app)
# Disable Flask logging... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.