id stringlengths 2 8 | text stringlengths 16 264k | dataset_id stringclasses 1
value |
|---|---|---|
1667510 | from django.test import TestCase
from .models import Comment, Profile, Post, Like
from django.urls import resolve, reverse
from .views import signup
class TestProfile(TestCase):
'''Test Class to test the Profile Class'''
def setUp(self)-> None:
'''To set up test class before running every test case'''
... | StarcoderdataPython |
11266018 | <reponame>Ian-Almeida/survey-site
from fastapi import APIRouter, Depends, HTTPException
from app.models.user import User, UserCreate
from typing import List
from app.db.config_db import getDB
from pymongo.database import Database
from app.core import dependencies
from app.crud import crud_user
router = APIRouter()
@... | StarcoderdataPython |
4832419 | <reponame>cll27/pvae<gh_stars>1-10
import math
import torch
from torch import nn
from torch.nn.parameter import Parameter
from torch.nn import init
from torch.autograd import Function
from pvae.ops.mobius_poincare import *
from pvae.utils import Arcsinh, Constants
class PoincareLayer(nn.Module):
def __init__(self... | StarcoderdataPython |
39559 | <reponame>DirkZomerdijk/status<gh_stars>0
#%%
import numpy as np
import matplotlib.pyplot as plt
import json
import copy
# chronic_threshold
# repeats
# time
# stress_max
global_settings = {
"data_file": "clean",
"save_folder": "pre-test\\",
"status_type": "linear",
"distance_measure": "euclidean",
... | StarcoderdataPython |
3522183 | from setuptools import setup
with open("README.md", "r", encoding="utf-8") as fh:
long_description = fh.read()
setup(
name='aiodiskdb',
version='0.2.4a1',
long_description=long_description,
long_description_content_type="text/markdown",
url='https://github.com/mempoolco/aiodiskdb/',
licens... | StarcoderdataPython |
1999794 | #!/usr/bin/env python
import base64, quopri
import mimetypes, email.Generator, email.Message
import cStringIO, os
# sample addresses
toAddr = "<EMAIL>"
fromAddr = "<EMAIL>"
outputFile = "dirContentsMail"
def main():
mainMsg = email.Message.Message()
mainMsg["To"] = toAddr
mainMsg["From"] = fromAddr
main... | StarcoderdataPython |
4852811 | <reponame>b3astyy/b3astyy<filename>narrate.py
#!/usr/bin/env python3
# narrate.py, a tool to create a narrative out of nothing by asking questions
# Copyright 2016 <NAME>
# MIT licensed, so do whatever you want with it :)
import hashlib
from os import getenv
from blessings import Terminal
# ===== Configuration. Fee... | StarcoderdataPython |
3244223 | <filename>tests/test_movablestand.py
import logging
import pytest
from ophyd.sim import make_fake_device
from pcdsdevices.movablestand import MovableStand
logger = logging.getLogger(__name__)
@pytest.fixture(scope='function')
def fake_stand():
FakeStand = make_fake_device(MovableStand)
stand = FakeStand('S... | StarcoderdataPython |
3367795 | <filename>pyheapdump/__main__.py
#
# -*- coding: utf-8 -*-
#
# Copyright (c) 2016 by <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.... | StarcoderdataPython |
151987 | <gh_stars>0
import typing
import numpy as np
import numba as nb
@nb.njit((nb.i8[:], ), cache=True)
def next_permutation(a: np.ndarray) -> typing.NoReturn:
n = a.size
i = -1
for j in range(n - 1, 0, -1):
if a[j - 1] >= a[j]: continue
i = j - 1
break
if i == -1:
a[:] = -1
return
a[i + 1:... | StarcoderdataPython |
3250419 | # coding: UTF-8
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
class Config(object):
"""配置参数"""
def __init__(self):
self.model_name = 'TextRCNN'
self.embedding_pretrained = None # 预训练词向量
self.dropout = 1.0 ... | StarcoderdataPython |
1614778 | <filename>isitfit/cost/base_reporter.py
# Related
# https://docs.datadoghq.com/integrations/amazon_redshift/
# https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/redshift.html#Redshift.Paginator.DescribeClusters
from termcolor import colored
import click
from isitfit.utils import logger
cla... | StarcoderdataPython |
6681586 | # @lc app=leetcode id=17 lang=python3
#
# [17] Letter Combinations of a Phone Number
#
# https://leetcode.com/problems/letter-combinations-of-a-phone-number/description/
#
# algorithms
# Medium (49.52%)
# Likes: 5831
# Dislikes: 515
# Total Accepted: 815.5K
# Total Submissions: 1.6M
# Testcase Example: '"23"'
#
... | StarcoderdataPython |
248352 | <reponame>magnusmel/Deep-Learning-Adventures-with-PyTorch<filename>Section 3/train.py
"""
Train and test a simple RNN for language detection.
Inspired by
https://pytorch.org/tutorials/intermediate/char_rnn_classification_tutorial.html
"""
import torch
torch.manual_seed(2)
import torch.nn as nn
from prep import get_d... | StarcoderdataPython |
6408518 | <reponame>stjordanis/datar
"""Chop and unchop
https://github.com/tidyverse/tidyr/blob/master/R/chop.R
"""
from collections import defaultdict
from typing import Iterable, List, Mapping, Tuple, Union
import numpy
import pandas
from pandas import DataFrame, Series
from pipda import register_verb
from pipda.utils import... | StarcoderdataPython |
8132072 | <gh_stars>1-10
#!/usr/bin/env python
import rospy
import tf
import tf.transformations as tr
from std_msgs.msg import String, Header, ColorRGBA
from nav_msgs.msg import OccupancyGrid, MapMetaData, Odometry
from geometry_msgs.msg import Twist, PoseStamped, Point
from sensor_msgs.msg import LaserScan
from visualization_ms... | StarcoderdataPython |
1603285 | from gym.envs.registration import register
register(
id='GridDrawBw-v0',
entry_point='grid_draw.envs:GridDrawBwEnv',
)
register(
id='GridDrawRgb-v0',
entry_point='grid_draw.envs:GridDrawRgbEnv',
)
| StarcoderdataPython |
1981298 | class UnionFindNode:
"""Nodo di una struttura dati union-find."""
def __init__(self, e):
self.elem = e
self.father = None
self.sons = []
class UnionFindQuickFind:
"""Rappresenta una collezione di alberi QuickFind."""
def __init__(self):
self.nodes = [] # lista contenent... | StarcoderdataPython |
8056687 | from core.exceptions.exceptions import LinTimException
class InputFileException(LinTimException):
"""Exception to throw if an input file cannot be found."""
def __init__(self, file_name: str):
"""
Initialise a new exception
:param file_name: name of the file that could not be found
... | StarcoderdataPython |
6668869 | <gh_stars>0
# uncompyle6 version 3.7.4
# Python bytecode 3.7 (3394)
# Decompiled from: Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)]
# Embedded file name: T:\InGame\Gameplay\Scripts\Server\careers\rabbithole_career_gig.py
# Compiled at: 2020-02-05 22:23:21
# Size of source mod... | StarcoderdataPython |
6525277 | <filename>find_parsimonious_assignments.py
from treelib import Node, Tree
import sys
import io
import argparse
import gzip
def create_tree(tree_filename):
tree = Tree()
# Read Newick file line
f = open(tree_filename)
line = f.readline().rstrip()
f.close()
# Get leaves names in s2
s1 = line.... | StarcoderdataPython |
11326132 | # -*- coding: utf-8 -*-
# Generated by Django 1.10.3 on 2016-11-17 15:05
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('movies', '0001_initial'),
]
operations = [
migrations.AlterField(
... | StarcoderdataPython |
3501800 | import sys
import os
import yaml
from munch import munchify
from ott.netcdf import IfcbMetadata, csdir2netcdf
# constants
CONFIG_FILE = 'config.yml'
def load_config(config_file):
with open(config_file) as fin:
return munchify(yaml.safe_load(fin))
def process_dir(in_dir, out_dir):
# load configurati... | StarcoderdataPython |
3509686 | <filename>libs/send2trash/compat.py<gh_stars>1000+
# Copyright 2017 <NAME>
# This software is licensed under the "BSD" License as described in the "LICENSE" file,
# which should be included with this package. The terms are also available at
# http://www.hardcoded.net/licenses/bsd_license
import sys
import os
PY3 = s... | StarcoderdataPython |
1767792 | <filename>AutomatedTesting/Gem/PythonTests/physics/C15096740_Material_LibraryUpdatedCorrectly.py
"""
Copyright (c) Contributors to the Open 3D Engine Project. For complete copyright and license terms please see the LICENSE at the root of this distribution.
SPDX-License-Identifier: Apache-2.0 OR MIT
Test case ID : C15... | StarcoderdataPython |
239725 | <gh_stars>0
import pygame
from desky.button import ButtonState
class Scheme:
pass
def add_default_methods(clsname):
def default_setup(self, panel, gui):
pass
setattr(Scheme, "setup_" + clsname, default_setup)
def default_layout(self, panel, w, h):
panel.layout_children(self, w, h)
... | StarcoderdataPython |
6503875 | <reponame>UniSerj/ai-research
import os
import torch
import torchvision
import numpy as np
from enum import Enum
from datasets.data_preprocessing import get_preprocessing, PreProcessing
from datasets.data_augmentation import get_augmentation, Augmentation
from torch.utils.data import DataLoader
class Dataset(Enum):
... | StarcoderdataPython |
6509848 | <gh_stars>1-10
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
import json
from api_client.ado.constants import ADOConstants
from api_client.exceptions import FailedToAttachWorkItemError, FailedToUpdateFieldsError
from core.api.caller import get, patch, post
from api_client.ado.endpoints impo... | StarcoderdataPython |
107039 | <gh_stars>0
class Block(object):
def __init__(self, name) -> None:
super().__init__()
self.__name__ = name
| StarcoderdataPython |
9759905 | DEBUG = False
PLUGINS = [
"myapp"
]
ASGI_APP = "myapp.asgi:app" | StarcoderdataPython |
11275390 | #from ._version import get_versions
#
#__version__ = get_versions()["version"]
#del get_versions
#
#global_config = None
| StarcoderdataPython |
8049584 | """
# Python Handout
Turn Python scripts into handouts with Markdown comments and inline figures. An
alternative to Jupyter notebooks without hidden state that supports any text
editor.
"""
import handout
import matplotlib.pyplot as plt
import numpy as np
"""Start your handout with an output directory."""
doc = hand... | StarcoderdataPython |
5006536 | from . import InitDB
from configs import config
from typing import Dict, List
class ChatDB(InitDB):
@staticmethod
def _get(chats: List) -> Dict[str, str]:
result = {}
for chat in chats:
(
owner_id,
chat_id,
lang,
quali... | StarcoderdataPython |
6629955 | <reponame>plocandido/docinfrati<gh_stars>100-1000
import logging
from typing import Callable, Dict
from lunr.exceptions import BaseLunrException
from lunr.token import Token
log = logging.getLogger(__name__)
class Pipeline:
"""lunr.Pipelines maintain a list of functions to be applied to all tokens
in docume... | StarcoderdataPython |
6657362 | import numpy as np
from sklearn.ensemble import RandomForestRegressor
from sklearn.linear_model import LinearRegression, LogisticRegression
from justcause.learners import (
CausalForest,
DoubleRobustEstimator,
DragonNet,
PSWEstimator,
RLearner,
SLearner,
TLearner,
XLearner,
)
from justc... | StarcoderdataPython |
6686679 | import rbnf.zero as ze
import sys, os
from rbnf.easy import build_parser
from Redy.Tools.PathLib import Path
pwd = Path(__file__).parent().__str__()
sys.path.append(pwd)
os.chdir(pwd)
def test_predicate():
ze_exp = ze.compile(
"""
[python] import predicate_helpers.[*]
lexer_helper := R'.'
a ::= (_{is_ok})... | StarcoderdataPython |
4871959 | import numpy as np
import torch
import argparse
import json
import os
import traceback
from tqdm import tqdm
import gym
import pickle
from tensorboardX import SummaryWriter
# TODO: this is ugly as hell but python sucks sometimes, should try to put everything in packages?
import os,sys,inspect
current_dir = os.path.di... | StarcoderdataPython |
1879553 | # Copyright 2018 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | StarcoderdataPython |
6439221 | <filename>test/tests/name_mangling.py
# Simple test:
class MyClass(object):
__a = 1
print sorted(locals().items()) # This should contain the mangled name
print hasattr(MyClass, "__a")
print hasattr(MyClass, "_MyClass__a")
# Names in functions get mangled:
class MyClass(object):
def __init__(self):
... | StarcoderdataPython |
4949169 | import re
from datetime import datetime
# function for parsing templates
def replace_var(text: str, variables: dict, row: dict):
text = text
for i in variables.keys():
text = re.sub(f"<{i}>", row[variables[i]], text)
return text
# string format of current time
def now():
return datetime.now(... | StarcoderdataPython |
4900422 | <reponame>hughperkins/ShapeWorld<gh_stars>0
from random import choice, random
from shapeworld.captions import Attribute
from shapeworld.captioners import WorldCaptioner
class RegularAttributeCaptioner(WorldCaptioner):
def __init__(
self,
pragmatical_redundancy_rate=1.0,
pragmatical_tautol... | StarcoderdataPython |
11291945 | '''
Lib de pilotage des gbf BK serie 4050 (4052,4053,4054,4055)
'''
import time
import sys
import telnetlib
import string
class telnet_das220_240(object):
'''
classdocs
'''
# Timeout on frame receive
TIMEOUT = 1
DEST = '192.168.0.115'
PORT = 23
tn = 0
... | StarcoderdataPython |
3314074 | <reponame>yamamon75/PmagPy<filename>programs/forc_diagram.py
#!/usr/bin/env python
# --*-- coding:utf-8 --*--
'''
#=================================================
/this is for processing and plotting forc diagrams,
/including the conventional and irregualar forc.
/author: Jiabo
/GFZ potsdam
#========================... | StarcoderdataPython |
1753232 | <filename>burog_auth/urls.py<gh_stars>0
from django.urls import path
from django.contrib.auth import views as auth_views
from .views import FormWizardView
from .forms import UserAuthForm
urlpatterns = [
path('register/', FormWizardView.as_view(), name='register'),
path(
'login/',
auth_views.Lo... | StarcoderdataPython |
26468 | from __future__ import division
import numpy as np
from sklearn.utils import shuffle
from sklearn.metrics import *
"""
Module with different fitness functions implemented to be used by the CRO algorithm.
The functions' only argument must be an individual (coral) and return its fitness, a number.
The fitness might re... | StarcoderdataPython |
1891617 | """@package plot_run_stats
Function to compare objective function and norm grad L between analyses.
"""
#import matplotlib.pyplot as plt
from .mpl_import import *
import pandas as pd
import numpy as np
def multi_plot_obj_grad_lag(fun_log_files, plot_names=None, file_names=None, legend_both=False, log_both=False):
... | StarcoderdataPython |
3269034 | from flask import Flask
from flask_bootstrap import Bootstrap
from config import Config
from flask_sqlalchemy import SQLAlchemy
from flask_login import LoginManager
from flask_moment import Moment
import os
app = Flask(__name__)
app.config.from_object(Config)
bootstrap = Bootstrap(app)
db = SQLAlchemy(app)
login = L... | StarcoderdataPython |
6410627 | <reponame>chenxuanshu/sayhello
'''
@Author: <NAME>
@Date: 2020-05-23 09:05:32
@LastEditTime: 2020-05-23 09:05:33
@LastEditors: Please set LastEditors
@Description: In User Settings Edit
@FilePath: \sayhello\errors.py
'''
| StarcoderdataPython |
5044733 | <gh_stars>1-10
# Copyright 2011 <NAME>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in... | StarcoderdataPython |
1740493 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
"""Decode the trained multi-task CTC outputs (TIMIT corpus)."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from os.path import join, abspath
import sys
import tensorflow as tf
import yaml
import argparse
... | StarcoderdataPython |
8055388 | <filename>test/xlog-py/lsn_gap.test.py<gh_stars>1-10
import os
import yaml
#
# gh-167: Replica can't find next xlog file if there is a gap in LSN
#
server.stop()
server.deploy()
# Create wal#1
server.admin("space = box.schema.space.create('test')")
server.admin("index = box.space.test:create_index('primary')")
server... | StarcoderdataPython |
6695155 | # -*- coding: utf-8 -*-
"""
Django settings for leprikonweb project.
"""
from django.utils.translation import ugettext_lazy as _
from cms_site.settings import *
ADMINS = (('<NAME>', '<EMAIL>'),)
MANAGERS = ADMINS
SERVER_EMAIL = 'Leprikón @ {} <<EMAIL>>'.format(os.uname()[1])
GANALYTICS_TRACKING_CODE = 'UA-78897621-... | StarcoderdataPython |
1702721 | #!/usr/bin/env python3
import matplotlib.pyplot as plt
from hdrh.histogram import HdrHistogram
import seaborn as sns
import pandas
from matplotlib import pyplot as plt
import os.path
from enum import Enum
import matplotlib as mpl
from typing import *
import argparse
parser = argparse.ArgumentParser(description='Genera... | StarcoderdataPython |
234914 | # -*- coding: utf-8 -*-
"""
author : <NAME> (email: <EMAIL>)
visit: (https://jfayaz.github.io)
"""
from urllib.request import urlopen
import pandas as pd
import numpy as np
import json
def url_resp_values_deag(url_final):
#deagg capture responses
# Opening url
#print(url_final)
deag_respo... | StarcoderdataPython |
366127 | import sys
import time
import numpy as np
import cv2
print(sys.executable)
print(sys.version)
print(cv2.__version__)
def evaluate_threshold(path, threshold):
cap = cv2.VideoCapture(video_file)
timeP = time.time()
diff_sum = 0
if cap.isOpened():
ret, img = cap.read()
while ret:
gray_image = cv2.cvtColor(img,... | StarcoderdataPython |
1816468 | <reponame>Insurance-Metrics-Measure-Advisory/watchman-data-connector<gh_stars>100-1000
# from japanese_address import parse
def __parse(address):
pass
# return parse(address)
def run(value):
pass
# return parse(value)
| StarcoderdataPython |
170494 | <gh_stars>0
from flask_wtf import FlaskForm
from wtforms import StringField, TextAreaField, SubmitField
from wtforms.validators import InputRequired
class CommentForm(FlaskForm):
comment = TextAreaField('Your comment here', validators=[InputRequired()])
submit = SubmitField('Post')
class BlogForm(FlaskForm):
... | StarcoderdataPython |
3274327 | <gh_stars>0
from __future__ import annotations
import typing
class Activity:
def __init__(self, start_time: float, finish_time: float, profit: float) -> None:
self.start_time = start_time
self.finish_time = finish_time
self.profit = profit
def __iter__(self) -> typing.Iterator[float]... | StarcoderdataPython |
3218055 | r"""
Points of Topological Manifolds
The class :class:`ManifoldPoint` implements points of a
topological manifold.
A :class:`ManifoldPoint` object can have coordinates in
various charts defined on the manifold. Two points are declared
equal if they have the same coordinates in the same chart.
AUTHORS:
- <NAME>, <NA... | StarcoderdataPython |
3232591 | #!/usr/bin/env python
import sys, re, csv
import pprint as pp
import pandas as pd
import argparse
from datetime import date
from go_utils import gaf, obo
import timeit
parser = argparse.ArgumentParser(description='Convert the RBH output to to gaf files')
parser.add_argument("-i","--input", help="Input file with RBH G... | StarcoderdataPython |
9767246 | '''
basic authentication (username, password)
no database systems, users defined by python scripts
'''
from flask import render_template, request, redirect, abort, flash, url_for
from flask_login import login_user, LoginManager, current_user, logout_user, login_required
from werkzeug.security import generate_password_... | StarcoderdataPython |
3543420 | <filename>evalml/data_checks/data_checks.py
import inspect
from evalml.data_checks import DataCheck
from evalml.exceptions import DataCheckInitError
from evalml.utils import infer_feature_types
def _has_defaults_for_all_args(init):
"""Tests whether the init method has defaults for all arguments."""
signature... | StarcoderdataPython |
11229192 | <filename>scripts/oov-clustering/compare-references.py
#!/usr/bin/env python
import argparse
import sys
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('ref1')
parser.add_argument('ref2')
args = parser.parse_args()
nb_00 = 0
nb_01 = 0
nb_10 = 0
nb_11 =... | StarcoderdataPython |
4906041 | <filename>datasets/hollywood2.py
import json
import csv
from pathlib import Path
import torch
import torch.utils.data as data
import numpy as np
import math
from .loader import VideoLoader
def get_class_labels(data, data_name, root_path):
class_labels_map = {}
f = open(root_path / 'list.txt', 'r')
i = ... | StarcoderdataPython |
1774495 | # -*- coding: utf-8 -*-
"""The app module, containing the app factory function."""
from flask import Flask, jsonify
from werkzeug.exceptions import HTTPException
from werkzeug.exceptions import default_exceptions
from api import commands, user
from api.extensions import bcrypt, db, migrate
from api.settings import Pro... | StarcoderdataPython |
6444196 | <reponame>cjwatson/flask-storm<filename>tests/test_utils_colored.py
import pytest
import sys
from flask_storm.utils import colored, has_color_support
from mock import Mock, patch
fg42 = "\x1b[38;5;42m"
bg69 = "\x1b[48;5;69m"
bold = "\x1b[1m"
underline = "\x1b[4m"
reset = "\x1b[0m"
def j(*args):
return "".join(... | StarcoderdataPython |
1794283 | <filename>functions_legacy/RawMigrationDb2AggrRiskDrivers.py
import numpy as np
from numpy import array, unique, zeros, sort, where, argsort, r_, ones
from numpy import sum as npsum
from datetime import datetime
def RawMigrationDb2AggrRiskDrivers(db,t_start,t_end):
# This function processes the raw database of c... | StarcoderdataPython |
5023598 | <reponame>01coders/50-Days-Of-Code<filename>python_AbhiMHolla/day 02.py<gh_stars>0
# Arithmetic operations
#basic Arithmetic operators part 1
x = 5
y = 3
z=15
print(x + y)
print(z-y)
print(x*y)
print(z/y)
print(z%x)
#comparison operators
a = 15
b = 23
print(a == b) # returns False because 15 is not equal to 23... | StarcoderdataPython |
6660099 | <reponame>spbrogan/edk2-pytool-extensions<filename>edk2toolext/capsule/pyopenssl_signer.py
# @file pyopenssl_signer.py
# This module contains the abstracted signing interface for pyopenssl. This interface
# abstraction takes in the signature_options and signer_options dictionaries that are
# used by capsule_tool and ca... | StarcoderdataPython |
12805476 | <reponame>apgupta3091/CSE389Project<filename>Pr0j3ct/server.py
# server.py
# implements HTTP Server class
from Pr0j3ct.requests import RequestProcessor
from Pr0j3ct.logging import Logger
from Pr0j3ct.scheduler import Scheduler
import os
import ssl
import socket
class Server:
def __init__(self, rootDirectory, por... | StarcoderdataPython |
4936184 | from django.apps import AppConfig
class SavConfig(AppConfig):
name = 'SAV'
| StarcoderdataPython |
370100 | import sys, os, timeit
moddir = os.path.join( os.path.dirname( __file__ ), '..' )
sys.path = [moddir] + sys.path
import pytest
from utils import Approx
from dynconfig.read import *
from dynconfig.parsers import *
def test_simple():
data = '''
var1 = $(1|int)
var2 = some string
var3 = $(3|int)
var4 = $({va... | StarcoderdataPython |
1603042 | import datetime
import io
import logging
import os
import tempfile
import uuid
import zipfile
from typing import *
import pandas as pd
import requests
from Modules.ExposureNotification.SourceRegionsProviders.base import BaseSourceRegionsProvider
from Modules.ExposureNotification import exposure_notification_exception... | StarcoderdataPython |
6647163 | <gh_stars>0
import sqlite3
# open connection to new db file
CONN = sqlite3.connect('demo_data.sqlite3')
# create table
cursor = CONN.cursor()
create_table = 'CREATE TABLE demo (s varchar(30), x int, y int);'
cursor.execute(create_table)
cursor.close()
CONN.commit()
# add data to table
cursor2 = CO... | StarcoderdataPython |
11220582 | from estimators.bandits import base
from typing import Optional
class Estimator(base.Estimator):
weighted_examples_count: float
weighted_reward: float
def __init__(self):
self.weighted_examples_count = 0
self.weighted_reward = 0
def add_example(self, p_log: float, r: float, p_pred: f... | StarcoderdataPython |
12818534 | import unittest
import numpy as np
from rlcard.agents.human_agents.wizard_human_agent import _print_state, _print_action
# from rlcard.agents.human_agents.wizard_ms_trickpred_human_agent import _print_state, _print_action as _print_state02, _print_action02
# from rlcard.agents.human_agents.wizard_s_trickpred_human_agen... | StarcoderdataPython |
4825462 | <reponame>aronwoost/sublime-expand-region
import unittest
from expand_to_word import *
class WordTest(unittest.TestCase):
@classmethod
def setUpClass(self):
with open ("test/snippets/word_01.txt", "r") as myfile:
self.string1 = myfile.read()
with open ("test/snippets/word_02.txt", "r") as myfile:
... | StarcoderdataPython |
1823264 | # encoding: utf-8
from pypi_server.handlers.pypi.simple.packages import PackagesHandler
from pypi_server.handlers.pypi.simple.files import VersionsHandler
| StarcoderdataPython |
1654260 | # -*- coding: utf-8 -*-
###############################################################################
#
# SearchByKeyword
# Searches movie reviews by keyword and various filter parameters.
#
# Python versions 2.6, 2.7, 3.x
#
# Copyright 2014, Temboo Inc.
#
# Licensed under the Apache License, Version 2.0 (the "Licen... | StarcoderdataPython |
378620 | <reponame>mpesavento/arg-mine
import os
import json
from arg_mine import PROJECT_DIR
def load_json_fixture(fixture_filename):
"""Get test fixture data from a JSON filename"""
# import pkg_resources
# json_path = pkg_resources.resource_filename("tests.fixtures", fixture_filename)
json_path = os.path.jo... | StarcoderdataPython |
3594349 | <filename>py_types/runtime/__init__.py
"""Runtime checks and decorators to ensure correctness of functions.
Includes schema tools and runtime type checks."""
from .schema import (
schema,
SchemaOr,
SchemaError
)
from .typecheck import typecheck
| StarcoderdataPython |
276253 | import rasterio
import numpy as np
import dask.array as da
from dask.base import tokenize
from rasterio.windows import Window
def read_raster(image_path, bands=None, masked=False, block_size=1):
"""
Read all or some band_ids from raster
Arguments:
image_path {string} -- image_path to raster file
... | StarcoderdataPython |
6587862 | <gh_stars>1-10
from pimsviewer import run
from pimsviewer.example_plugins import AnnotatePlugin
run('path/to/file', [AnnotatePlugin])
| StarcoderdataPython |
9797909 | <reponame>Darkshadow9799/Super-Resolution
import moviepy.editor as mp
audio_path = 'Results/audio.mp3'
video_path = 'Results/2.mp4'
clip = mp.VideoFileClip(video_path)
clip.audio.write_audiofile(audio_path)
print("SUCCESS")
| StarcoderdataPython |
4836458 | <reponame>materialsvirtuallab/nano281<gh_stars>10-100
from sklearn.ensemble import AdaBoostClassifier
x_train, x_test, y_train, y_test = train_test_split(x, y_class, test_size=0.2)
decision_tree = AdaBoostClassifier(DecisionTreeClassifier(criterion="entropy", random_state=0, max_depth=3),
... | StarcoderdataPython |
3344236 | <filename>src/road_collisions_uk/models/collision.py
import datetime
import os
import glob
import csv
from pandas import DataFrame
import pandas as pd
from road_collisions_base import logger
from road_collisions_base.models.raw_collision import RawCollision
from road_collisions_uk.utils import extract_tgz
from road_... | StarcoderdataPython |
8088314 | from rest_framework.pagination import PageNumberPagination
class DefaultPagePagination(PageNumberPagination):
max_page_size = 100
page_size_query_param = "page_size"
page_size = 25
| StarcoderdataPython |
285642 | import json
import requests
import sys
# instantiate working variables
octopus_server_uri = 'http://your.octopus.app/'
octopus_api_key = 'API-YOURAPIKEY'
params = {'API-Key': octopus_api_key}
space_name = 'Default'
project_name = 'ProjectName'
#Set disable_proect to 'True' to disable | 'False' to enable.
disable_proje... | StarcoderdataPython |
4874083 | import os
from bs4 import BeautifulSoup
import xmltodict
from collections import OrderedDict
def data_generator(dirname):
"""Transforms all summaries in directory into data objects for pipeline.
Simply iterates over the directory and calls file_to_data.
"""
for root, dirs, files in os.walk(dirname):
... | StarcoderdataPython |
9745926 | #!/usr/bin/python3
# File name: ajakipro_checkavailablespace.py
# Version: 1.0.0
# Author: <NAME>
# Email: <EMAIL>
# Date created: 5/23/2021
# Date last modified: 5/23/2021
# Checks to see amount of available space on the Ki Pro. If the percentage is >= the threshhold, the job succeeds. If it is less, it fails.
# Job... | StarcoderdataPython |
3292093 | <filename>test/test_stack.py<gh_stars>0
# -*- coding: utf-8 -*-
from src.Stack import Stack
def test_empty_stack():
s = Stack()
assert s.size() == 0
assert len(s) == 0
def test_nonempty_stack():
s = Stack()
s.push(1)
s.push(2)
assert len(s) == 2
assert s.pop() == 2
assert len(... | StarcoderdataPython |
4929983 | <reponame>Thanatoz-1/EmotionStimuli
__author__ = "<NAME>"
from emotion.utils import Data, Dataset
from emotion import HMM
from emotion.evaluation import Evaluation
# read Data from file, only gne, all labels
rem_all = Data(
filename="data/rectified-unified-with-offsets.json",
roles=[
"experiencer",
... | StarcoderdataPython |
3301472 | import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import layers
import numpy as np
| StarcoderdataPython |
4983612 | <filename>Methods/RichouxDeepNetwork/RichouxDeepNetwork.py<gh_stars>1-10
#Based on paper Comparing two deep learning sequence-based models for protein-protein interaction prediction by Richoux, Servantie, Bores, and Teletchea
import os
import sys
#add parent and grandparent to path
currentdir = os.path.dirname(os.p... | StarcoderdataPython |
6403361 | from django.apps import AppConfig
class NoteapiConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'apis.noteapi'
| StarcoderdataPython |
6483953 | import os
import abc
import swamp
import threading
import numpy as np
import pandas as pd
from statistics import mean
import swamp.utils.swamplibrary
from swamp.logger import SwampLogger
from swamp.wrappers.gesamt import Gesamt
from itertools import groupby, combinations
from sklearn.metrics import silhouette_score
fro... | StarcoderdataPython |
3279758 | """This module supplies various reindex functions.
"""
import logging
import dateutil.parser
from elasticsearch import helpers
from . import util
__all__ = ['date_reindex']
logger = logging.getLogger(__name__)
def date_reindex(url, source_index_name, target_index_name, date_field=None,
delete_do... | StarcoderdataPython |
1883275 | <gh_stars>0
# Special Pythagorean triplet
#
# A Pythagorean triplet is a set of three natural numbers, a < b < c, for which,
# a2 + b2 = c2
#
# For example, 32 + 42 = 9 + 16 = 25 = 52.
#
# There exists exactly one Pythagorean triplet for which a + b + c = 1000.
# Find the product abc.
def abc_1000():
for a in ran... | StarcoderdataPython |
11307632 | <gh_stars>1-10
HOST = 'localhost' # 10.19.179.123'
# HOST = '10.10.207.61'
PORT = 1081
BUFFSIZE = 16777215
| StarcoderdataPython |
8121087 | #!/usr/bin/python3
# ros
from scipy.ndimage.measurements import label
import rospy
import ros_numpy
import message_filters
from sensor_msgs.msg import Image, PointCloud2
from cv_bridge import CvBridge, CvBridgeError
from std_msgs.msg import Float32MultiArray, MultiArrayLayout, MultiArrayDimension
from SegmentationMa... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.