id stringlengths 1 7 | text stringlengths 6 1.03M | dataset_id stringclasses 1
value |
|---|---|---|
21469 | '''
Preorder Binary Tree
For a given Binary Tree of integers, print the pre-order traversal.
Input Format:
The first and the only line of input will contain the nodes data, all separated by a single space. Since -1 is used as an indication whether the left or right node data exist for root, it will not be a part of t... | StarcoderdataPython |
1666686 | <filename>exercicios.py/ex053.py<gh_stars>1-10
frase = str(input('Digite uma frase: ')).strip()
# fc = len(frase) - frase.count(' ')
fs = frase.replace(' ','')
cont = 0
for c in range (0, len(fs)):
if fs [c] == fs [-c-1]:
cont += 1
if cont == fs:
print('O inverso de {} é {}'.format(frase, frase[::-1]))... | StarcoderdataPython |
4811262 | <reponame>t27/adversarial-detection<gh_stars>0
import torch
import torch.nn as nn
class SkipBlock2(nn.Module):
"""Skip block from resnet paper(Figure2) with additional 1x1 conv on input(to "select" and weight good channels)
Args:
nn ([type]): [description]
"""
def __init__(
self, in_c... | StarcoderdataPython |
3285190 | <gh_stars>10-100
""" Input functions """
from .read_nc_emodnet import read_nc_emodnet
from .read_nc import read_nc
from .read_nc_ooi import read_nc_ooi
from .read_nc_imos import read_nc_imos
from .read_pkl import read_pkl
from .read_json import read_json
from .read_nc_moist import read_nc_moist
from .from_emso ... | StarcoderdataPython |
1747211 | <filename>twitter_api_v2/TwitterAPI.py
import json
import logging
from logging import Logger
from typing import Dict, List, Optional
import requests
from requests.models import Response
from twitter_api_v2 import Media, Poll, Tweet, User
logger: Logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
c... | StarcoderdataPython |
1686583 | '''
#!/usr/bin/python
#Author: <NAME>
#Version: 2.0
#Date: 27th March 2014
does the ceaser decryption of the output of ceaser.py, the cipher and shift are taken
from the user and the plain text is printed on the console
'''
import string
cipher=raw_input('enter cipher')
key=raw_input('enter key')
letters = string.asc... | StarcoderdataPython |
3210984 | <filename>tests/serializers.py
from drf_toolbox.compat import django_pgfields_installed
from drf_toolbox.serializers import ModelSerializer
from tests import models as test_models
class ExplicitAPIEndpointsSerializer(ModelSerializer):
class Meta:
model = test_models.ExplicitAPIEndpointsModel
class Norma... | StarcoderdataPython |
3359412 | from __future__ import division
import os, scipy.io
from test_Sony import toimage
import tensorflow.compat.v1 as tf
from test_Sony import network
from d2s_numpy import depth_to_space
tf.disable_v2_behavior()
import numpy as np
output_filepath = "./qemu_output.data"
processed_output_filepath = "./qemu_output.png"
outpu... | StarcoderdataPython |
3334435 | # Generated by Django 3.1.2 on 2021-04-27 12:58
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('sis', '0004_auto_20210427_1546'),
]
operations = [
migrations.CreateModel(
name='ClassLevel',
... | StarcoderdataPython |
1615585 | import unittest
from pynecone import Shell, Cmd
class TestCmd(Cmd):
def __init__(self):
super().__init__('cmd')
def add_arguments(self, parser):
parser.add_argument('arg')
def get_help(self):
return 'test cmd'
def run(self, args):
return args.arg
class TestShell(S... | StarcoderdataPython |
4825144 | <reponame>007sya/Project2021<filename>src/PythonLib/lib/utils/download_data/datasets.py
# %%
import os
from typing import List
import pandas as pd
from utils.download_data import data_dtypes as dtypes
from utils.download_data import download_safegraph_data
from utils.file_utils import file_type
from utils.path_utils i... | StarcoderdataPython |
20584 | <gh_stars>1-10
#! /usr/bin/env python
from pylib import *
CopyConfigForDistribution(InstallRoot)
| StarcoderdataPython |
1732911 | """
constance file, generate all constance values from json file
"""
from NBprocessing.src._constance_dict import data
class Const(object):
def __init__(self):
# check input file
self.CHECK_DATABASE_INPUT = data["CHECK_INPUT"]["CHECK_DATABASE_INPUT"]
self.CHECK_COLUMN_NAME = data["CHECK_... | StarcoderdataPython |
196114 | <gh_stars>1-10
# Create list baseball
baseball = [180, 215, 210, 210, 188, 176, 209, 200]
# Import the numpy package as np
import numpy as np
# Create a numpy array from baseball: np_baseball
np_baseball = np.array(baseball)
# Print out type of np_baseball
print(type(np_baseball)) | StarcoderdataPython |
1615860 | <gh_stars>1-10
class Room():
def __init__(self, array_pos):
self.pos_room = array_pos | StarcoderdataPython |
1767325 | <reponame>GustavoTelles/Python_Coursera
'''
Somar todas as unidades de um número inteiro digitado usando a estrutura de repetição while
'''
n1 = int(input('Digite um número: '))
soma = 0
total = 0
while n1 != 0:
soma = int(n1 % 10)
total = soma + total
n1 = n1 / 10
print('A soma dos números é {}' .format... | StarcoderdataPython |
132679 | # -*- coding: utf-8 -*-
from __future__ import print_function
import pytest
import random
import numpy as np
import pandas as pd
from pandas.compat import lrange
from pandas.api.types import CategoricalDtype
from pandas import (DataFrame, Series, MultiIndex, Timestamp,
date_range, NaT, IntervalIn... | StarcoderdataPython |
1686733 | from flask import current_app
from fnmatch import fnmatch
class Manager(object):
def __init__(self):
self.handlers = []
def register(self, cls, matches):
self.handlers.append((cls, matches))
def process(self, artifact):
job = artifact.job
artifact_name = artifact.name
... | StarcoderdataPython |
57970 | <reponame>jazeved0/cinema-system<gh_stars>1-10
from flask import Flask, g, jsonify
from flask.json import JSONEncoder
from flask_restful import Api, inputs
from flask_cors import CORS
from sqlalchemy.exc import SQLAlchemyError
from datetime import datetime, date
from auth import authenticated, get_failed_auth_resp, ha... | StarcoderdataPython |
3230870 | <reponame>yngtodd/seeds
"""
Tests for `seeds` module.
"""
import pytest
from seeds import seeds
class TestSeeds(object):
@classmethod
def setup_class(cls):
pass
def test_something(self):
pass
@classmethod
def teardown_class(cls):
pass
| StarcoderdataPython |
3226242 | <reponame>kagemeka/atcoder-submissions<gh_stars>1-10
n = int(input())
ls = []
for i in range(n):
ls.append(int(input()))
ls.sort()
layer = 1
current = ls[0]
for i in range(n):
if current != ls[i]:
layer += 1
current = ls[i]
print(layer)
| StarcoderdataPython |
1797765 | <filename>puls/views/admin/suppliers.py
# coding=utf-8
from __future__ import absolute_import, unicode_literals, division
from puls.models import Supplier, SupplierForm
from puls.compat import unquote_plus
from puls import app, paginate
import flask
@app.route("/admin/suppliers/", methods=["GET", "POST"],
... | StarcoderdataPython |
3368648 | <filename>contrapartes/views.py
from django.shortcuts import render
from .models import *
from .forms import *
from notas.models import *
from notas.forms import *
from agendas.models import *
from agendas.forms import *
from foros.forms import *
from publicaciones.models import *
from publicaciones.forms import *
from... | StarcoderdataPython |
1631893 | import logging
from django.utils import timezone
from elasticsearch import Elasticsearch, NotFoundError, RequestError
from zentral.core.exceptions import ImproperlyConfigured
from .base import BaseExporter
logger = logging.getLogger("zentral.contrib.inventory.exporters.es_machine_snapshots")
MAX_EXPORTS_COUNT = 3
ES... | StarcoderdataPython |
1620512 | <reponame>li195111/real-estate-price
from celery import Celery
from celery.schedules import crontab
import utils
# from app import rdb
task = Celery('tasks',
broker='redis://localhost:6379/0',
backend='redis://localhost:6379/0')
task.conf.timezone = 'UTC'
'''
@task.task
def function():
... | StarcoderdataPython |
1765095 | import django_heroku
from .production import *
ALLOWED_HOSTS = ['*.herokuapp.com']
CACHES = {
'default': {
'BACKEND': 'django_bmemcached.memcached.BMemcached',
'LOCATION': os.getenv('MEMCACHIER_SERVERS').split(','),
'OPTIONS': {
'username': os.getenv('MEMCACHIER_USERNAME')... | StarcoderdataPython |
3227106 | import logging
import itertools
from data.logs_model.datatypes import AggregatedLogCount, LogEntriesPage
from data.logs_model.interface import ActionLogsDataInterface
from data.logs_model.shared import SharedModel
logger = logging.getLogger(__name__)
def _merge_aggregated_log_counts(*args):
""" Merge two lists of... | StarcoderdataPython |
1675576 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Constants related to the GCP auth method and/or secrets engine."""
DEFAULT_MOUNT_POINT = 'database'
ALLOWED_CREDS_ENDPOINT = 'creds' | StarcoderdataPython |
3333633 | <gh_stars>0
__author__ = 'Nikhil'
import scrapy
from MedIndia.items import MedindiaItem
html_headers = {
"accept" : "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
"accept-encoding" : "gzip, deflate, sdch, br",
"accept-language" : "en-US,en;q=0.8,ms;q=0.6",
"user-agent" : "... | StarcoderdataPython |
70452 | import sys
import argparse
import numpy as np
from dataclasses import dataclass
from mchap.application import baseclass
from mchap.application.baseclass import SampleAssemblyError, SAMPLE_ASSEMBLY_ERROR
from mchap.application.arguments import (
CALL_MCMC_PARSER_ARGUMENTS,
collect_call_mcmc_program_arguments,
)... | StarcoderdataPython |
136644 | import numpy as np
import cv2
import matplotlib.pyplot as plt
import numpy as np
import math
def ClassifyColor( BGR, width, height ): ##分類顏色 (BGR, width, height)
r_threshold = 20 ##r閾值 before 10
b_threshold = 20 ##b閾值 before 10
FortyFive_degree = math.pi / 4 ## 45度
grey_threshold = 10.0 * ... | StarcoderdataPython |
3381440 | for i in range(11):
for j in range(i+1):
print("# ",end=" ")
for k in range(i+1,11):
print("^ ",end=" ")
print(" ")
| StarcoderdataPython |
3338051 | import sys
import pymongo
from pymongo import MongoClient
client=MongoClient()
db=client.person_db
user=db.user
img_id=sys.argv[1]
lat=sys.argv[2]
lng=sys.argv[3]
flag=0
#ele = user.find()
#cnt=user.find().count()
for ele in user.find():
#res=cmp_img_id.py #(call a script checking for similarity of image)
res=0
if ... | StarcoderdataPython |
4836595 | <reponame>bopopescu/google-cloud-sdk<gh_stars>0
"""Small helper class to provide a small slice of a stream."""
from gslib.third_party.storage_apitools import exceptions
class StreamSlice(object):
def __init__(self, stream, max_bytes):
self.__stream = stream
self.__remaining_bytes = max_bytes
self.__max... | StarcoderdataPython |
3288435 | <reponame>duggalsu/PySyft<filename>syft/frameworks/crypten/message_handler.py
import syft
from syft.messaging.message import CryptenInitPlan
from syft.messaging.message import CryptenInitJail
from syft.messaging.message import ObjectMessage
from syft.frameworks import crypten as syft_crypten
from syft.frameworks.cryp... | StarcoderdataPython |
1608894 | # from ripe.atlas.sagan import Result
from ripe.atlas.cousteau import Probe
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
from collections import Counter
from sklearn.mixture import GaussianMixture
import urllib.request
import json
import pickle
import decimal
from Ollivie... | StarcoderdataPython |
3297600 | from setuptools import setup, find_packages
__version__ = '1.0.2'
setup(
name='amundsen-metadata',
version=__version__,
description='Metadata service package for Amundsen',
url='https://www.github.com/lyft/amundsen',
maintainer='Lyft',
maintainer_email='<EMAIL>',
packages=find_packages(exc... | StarcoderdataPython |
78765 | import abc
import copy
import re
import pandas as pd
class Feature(metaclass=abc.ABCMeta):
def __init__(self, name, path):
self.name = name
self.path = path
self._data = None
def data(self):
if self._data is None:
self.load_data()
return self._data
@... | StarcoderdataPython |
3293325 | import os
import importlib.util
from pykeops.common.gpu_utils import get_gpu_number
###############################################################
# Initialize some variables: the values may be redefined later
##########################################################
# Update config module: Search for GPU
gpu_ava... | StarcoderdataPython |
168629 | <gh_stars>1-10
# -------- BEGIN LICENSE BLOCK --------
# Copyright 2022 FZI Forschungszentrum Informatik
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above cop... | StarcoderdataPython |
4811257 | import os
device_name = os.getenv('DEVICENAME', 'Poweredge-R510')
energy_sensor_name = os.getenv('ENERGYNAME', device_name + '-energysensor')
mqtt_energy_topic = os.getenv('ENERGYSTATETOPIC', '' + energy_sensor_name + '/energyusage')
energy_config_template = {
"name": energy_sensor_name,
"unique_id": energy_s... | StarcoderdataPython |
3386171 | <gh_stars>0
from rest_framework.permissions import BasePermission
class AllowSpecificClients(BasePermission):
"""
Allows access to only specific clients.
Should be used along with `<>.auth.TokenAuthentication`.
"""
allowed_clients_name = ("web",)
def has_permission(self, request, view):
... | StarcoderdataPython |
1756135 | import webapp2
import jinja2
from google.appengine.api import users
from google.appengine.ext import ndb
import os
from user import User
from directory import Directory
import random
JINJA_ENVIRONMENT = jinja2.Environment(
loader = jinja2.FileSystemLoader(os.path.dirname(__file__)),
extensions = ['jinja2.ext.autoes... | StarcoderdataPython |
46111 | class Point:
"Classe Point géographique contenant une position"
def __init__(self,x,y):
self._x=x
self._y=y
def getx(self):
return self._x
def gety(self):
return self._y
def setx(self, x):
self._x = x
def sety(self, y):
self._y = y
... | StarcoderdataPython |
1708113 | <filename>conf/settings/test_ci.py
from .base import *
from .base import env
DEBUG = False
SECRET_KEY = env("SECRET_KEY", default="myverysecretkey")
TEST_RUNNER = "django.test.runner.DiscoverRunner"
CACHES = {
"default": {
"BACKEND": "django.core.cache.backends.locmem.LocMemCache",
"LOCATION": ""... | StarcoderdataPython |
4838564 | <filename>cloud/endagaweb/settings/test_spatialite.py
"""
Use Django prod settings from endagaweb with as few changes as necessary
to make tests run under Buck/Sandcastle.
Copyright (c) 2016-present, Facebook, Inc.
All rights reserved.
This source code is licensed under the BSD-style license found in the
LICENSE file... | StarcoderdataPython |
1624547 | <gh_stars>0
from django.core.paginator import Paginator,EmptyPage,PageNotAnInteger
from django.shortcuts import render
from pages.models import Post
def index_func(request):
posts = Post.objects.order_by('published_date')
return render(request,"home/index.html",{'posts': posts})
def about_func(request):
re... | StarcoderdataPython |
1765060 | # ------------------------------------------------------------------------------
# Copyright (c) 2010-2013, EVEthing team
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
#
# Redistributions of... | StarcoderdataPython |
1605346 | <gh_stars>0
import os
import sys
import inspect
import pytest
import json
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.insert(0, "{}/src".format(parentdir))
from Components.MarketProvider import MarketProvider
from Components.B... | StarcoderdataPython |
3316655 | """
pygments.lexers.procfile
~~~~~~~~~~~~~~~~~~~~~~~~
Lexer for Procfile file format.
:copyright: Copyright 2006-2021 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from pygments.lexer import RegexLexer
from pygments.lexer import bygroups
from pygments.token import... | StarcoderdataPython |
1783065 | <gh_stars>0
import math
import copy
class Vector3:
def __init__(self, x=0.0, y=0.0, z=0.0):
self.x = x
self.y = y
self.z = z
def __str__(self):
return '(' + str(self.x) + ' , ' + str(self.y) + ' , ' + str(self.z) + ')'
def __getitem__(self, key):
if key == 0:
... | StarcoderdataPython |
3250263 | <filename>Kerning/Remove all kerning exceptions.py
#MenuTitle: Remove Kerning Exceptions
# -*- coding: utf-8 -*-
from __future__ import division, print_function, unicode_literals
__doc__="""
Removes all kernings glyph-glyph, group-glyph, and glyph-group; only keeps group-group kerning.
"""
import vanilla
class Remove... | StarcoderdataPython |
4826793 | # Get Launcher as well as OpenGL imports
from projects.launcher import *
w, h = 500, 500
def square(size=(100, 100), pos=(0, 0)):
glColor3f(0.25, 0.5, 0.75)
glBegin(GL_QUADS)
glVertex2f(pos[0], pos[1])
glVertex2f(pos[0] + size[0], pos[1])
glVertex2f(pos[0] + size[0], pos[1] + size[1])
glVerte... | StarcoderdataPython |
1600371 | <reponame>Obarads/torch_point_cloud
import os, sys
import numpy as np
from plyfile import PlyData, PlyElement
from sklearn.decomposition import PCA
##
## Write
##
def write_pc(filename, xyz, rgb=None):
"""
write into a ply file
ref.:https://github.com/loicland/superpoint_graph/blob/ssp%2Bspg/partition/pr... | StarcoderdataPython |
4816674 | <filename>code/python-modules/debugrayleigh.py
'''
Code to debug the mixed rayleigh issues using personal_test dataset
'''
import numpy as np
import personal_test as pt
import matplotlib.pyplot as plt
from copy import deepcopy
import process
'''basic setup
txtnames,kinectDict,startsDict = pt.setup()
task_type = ... | StarcoderdataPython |
4808162 | '''Cross validation
bug tracker
-----------------------------
priority | name
-----------------------------
1 | rubi, how accuracy so high?? 64%!
2 | should use PURGED K-FOLD Cross Validation or TimeSeriesSplit instead of standart split
3 | rubi, which normalize function to use?
'''
from __futur... | StarcoderdataPython |
1787670 | <reponame>mazi76erX2/football_forecaster
"""
Django settings for Football Forecaster project.
Generated by 'django-admin startproject' using Django 3.1.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djang... | StarcoderdataPython |
146878 | <reponame>karlp/KiCost
# -*- coding: utf-8 -*-
# MIT license
#
# Copyright (C) 2018 by XESS Corporation / <NAME> / <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... | StarcoderdataPython |
40980 | <reponame>intelkevinputnam/lpot-docs
# -*- coding: utf-8 -*-
# Copyright (c) 2021 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/LICENS... | StarcoderdataPython |
3354948 | import pandas as pd
import numpy as np
import os
import glob
from common.io import file_base, parent_dir, mkdir
import re
import os
# @todo add warning if file is missing (i.e., None)
# @todo clean out files such that features are in 1 and labels (i.e., y or professor rating) is in another (samename_label.csv)
#
def ... | StarcoderdataPython |
100218 | <gh_stars>1-10
from attacker import *
from victim import *
def p_selection(p_init, it, num_iter):
""" Piece-wise constant schedule for p (the fraction of pixels changed on every iteration). """
it = int(it / num_iter * 10000)
if 10 < it <= 50: return p_init / 2
elif 50 < it <= 200: ... | StarcoderdataPython |
1644029 | import os
from django.core.wsgi import get_wsgi_application
from dj_static import Cling
settings_module = os.environ.setdefault('DJANGO_SETTINGS_MODULE', "settings.base")
application = Cling(get_wsgi_application())
| StarcoderdataPython |
1738218 | <gh_stars>1-10
# coding=utf8
import hashlib
import mimetypes
import re
import evernote.edam.type.ttypes as Types
from evernote.api.client import EvernoteClient
from evernote.edam.error.ttypes import EDAMUserException
from storage import Storage
class EvernoteController(object):
def __init__(self, token, isSpeci... | StarcoderdataPython |
4831861 | # Generated by Django 3.2.4 on 2021-06-15 19:28
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("app_forecast", "0004_auto_20210615_2035"),
]
operations = [
migrations.AlterField(
model_name="forecast",
... | StarcoderdataPython |
3353458 | # =============================================================================
# Copyright 2020 NVIDIA. All Rights Reserved.
# Copyright 2018 The Google AI Language Team Authors and
# The HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in co... | StarcoderdataPython |
4816336 | import importlib
import types
import collections
import inspect
import numpy as np
import logging
import typing
from functools import partial
import typing
class Encoder:
"""
Encode arbitrary objects. The encoded object consists of dicts,
lists, ints, floats and strings.
"""
def __call__(self, ob... | StarcoderdataPython |
3305351 | # type: ignore
# -*- coding: utf-8 -*-
#
# ramstk.analyses.milhdk217f.models.inductor.py is part of the RAMSTK Project
#
# All rights reserved.
# Copyright since 2007 Doyle "weibullguy" Rowland doyle.rowland <AT> reliaqual <DOT> com
"""Inductor MIL-HDBK-217F Constants and Calculations Module."""
# Standard Libra... | StarcoderdataPython |
1755430 | # get string input
Total_bill =int(raw_input("Enter the total amont: "))
# get integer input: int() convert string to integer
# float() convert string to floating number
tip_rate = float(raw_input("Enter tip rate (such as .15): "))
tip=(Total_bill*tip_rate)
total=int(Total_bill+tip)
# use string formatting to outpu... | StarcoderdataPython |
1668604 | <gh_stars>0
from pytz import timezone
from helpers import query, generate_uuid
from ..queries.document import construct_get_file_for_document, construct_insert_document
from ..sudo_query import update as sudo_update
from .file import download_sh_doc_to_mu_file
from .exceptions import NoQueryResultsException
TIMEZONE =... | StarcoderdataPython |
1622730 | import numpy as np
from toolkit.methods.pnpl import CvxPnPL, DLT, EPnPL, OPnPL
from toolkit.suites import parse_arguments, PnPLReal
from toolkit.datasets import Linemod, Occlusion
# reproducibility is a great thing
np.random.seed(0)
np.random.seed(42)
# parse console arguments
args = parse_arguments()
# Just a lo... | StarcoderdataPython |
3266190 | from pygame.rect import Rect
from battle_city.collections.sliced_array import SlicedArray
from battle_city.monsters import Coin
import pytest
def test_init_empty():
array = SlicedArray(grid=32)
assert array._parts == {}
assert array._grid == 32
assert len(array) == 0
def test_init_filled():
co... | StarcoderdataPython |
3232041 | import boto3
import click
def get_r_client():
return boto3.client('rekognition', region_name='eu-west-1')
def delete_collection(client,collection):
print(client.delete_collection(CollectionId=collection))
@click.command()
@click.option('--collection-id', help='Your picture file')
def main(collection_id):
... | StarcoderdataPython |
1761423 | <reponame>vtecftwy/unpackai
import streamlit as st
def make_predictions():
st.write("Hello")
st.button("useless button")
| StarcoderdataPython |
147624 | <filename>kerlescan/exceptions.py
class HTTPError(Exception):
def __init__(self, status_code, message=""):
"""
Raise this exception to return an http response indicating an error.
This is a boilerplate exception that was originally from Crane project.
:param status_code: HTTP statu... | StarcoderdataPython |
138427 | # -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: streamlit/proto/Video.proto
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_databas... | StarcoderdataPython |
1770570 | import asyncio
import dataclasses
@dataclasses.dataclass
class Command:
future: asyncio.Future = dataclasses.field(init=False, compare=False, hash=False)
def __post_init__(self):
try:
self.future = asyncio.get_running_loop().create_future()
except Exception:
self.futur... | StarcoderdataPython |
4813077 | import numpy as np
def dump_nparray(array, filename):
#array_file = open(filename, 'w')
array_file = open(filename, 'w')
np.uint32(array.ndim).tofile(array_file)
#for d in xrange(array.ndim):
for d in range(array.ndim):
np.uint32(array.shape[d]).tofile(array_file)
array.tofile(array_file)
array_file.... | StarcoderdataPython |
10985 | from django.contrib import admin
from .models import Image
@admin.register(Image)
class ImageAdmin(admin.ModelAdmin):
list_display = ('image', 'predict_covid', 'predict_no_findings', 'predict_pneumonia', 'created_at', 'updated_at', 'activated_at')
| StarcoderdataPython |
101167 | <filename>binary_mnist_pathnet.py
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import sys
import tensorflow as tf
import input_data
import pathnet
import numpy as np
import time
FLAGS = None
def train():
# Import data
mnist = inp... | StarcoderdataPython |
4816046 | name = "mpesa" | StarcoderdataPython |
3224567 | <filename>Plots/plot_timing_histo.py
#!/usr/bin/env python
from __future__ import print_function
import numpy as np
import sys
import matplotlib.pyplot as plt
import matplotlib.pylab as pylab
params = {'legend.fontsize': 'x-large',
'figure.figsize': (13, 6),
'figure.autolayout': True,
'a... | StarcoderdataPython |
1678536 | <gh_stars>1-10
# coding: utf-8
from __future__ import unicode_literals
import re
from .common import InfoExtractor
class EggheadCourseIE(InfoExtractor):
IE_DESC = 'egghead.io course'
IE_NAME = 'egghead:course'
_VALID_URL = r'https://egghead\.io/courses/(?P<id>[a-zA-Z_0-9-]+)'
_TEST = {
'url'... | StarcoderdataPython |
36256 | <gh_stars>1-10
import numpy as np
import math
from pandas import DataFrame
def min_rw_index(prices, start, end):
"""
Searches min price index inside window [start,end]
:param prices: in list format
:param start: window start index
:param end: window end index
:return:
"""
matching... | StarcoderdataPython |
1665943 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def removeNthFromEnd(self, head, n):
"""
:type head: ListNode
:type n: int
:rtype: ListNode
"""
tmp = Li... | StarcoderdataPython |
121823 | <gh_stars>1-10
import unittest
import numpy as np
from matchernet.fn import LinearFn, LinearFnXU
class TestLinearFn(unittest.TestCase):
def setUp(self):
self.x = np.array([10, 20, 30], dtype=np.float32)
self.test_A_patterns = [
np.array([[1, 2, 3], [4, 5, 6]], dtype=np.float32),
... | StarcoderdataPython |
3278029 | <gh_stars>0
from django.db import models
from django.db.models.fields.related import ForeignKey, ManyToManyField
from django_countries.fields import CountryField
from django.contrib.auth.models import User
class League(models.Model):
name = models.CharField(max_length=255)
rating = models.IntegerField(default... | StarcoderdataPython |
164692 | <filename>grid/__init__.py
from __future__ import print_function # Only Python 2.x
import sys
import subprocess
import os
import syft
from grid.client import GridClient
from grid.websocket_client import WebsocketGridClient
from grid import utils as gr_utils
from grid import deploy
from grid.grid_network import Grid... | StarcoderdataPython |
6418 | <filename>appr/commands/logout.py
from __future__ import absolute_import, division, print_function
from appr.auth import ApprAuth
from appr.commands.command_base import CommandBase, PackageSplit
class LogoutCmd(CommandBase):
name = 'logout'
help_message = "logout"
def __init__(self, options):
su... | StarcoderdataPython |
3244735 | <gh_stars>1-10
# -*- coding: utf-8 -*-
# Libaddon for Anki
#
# Copyright (C) 2018 <NAME>. <https//glutanimate.com/>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of... | StarcoderdataPython |
174456 | <filename>python/class-challenges/src/image_analysis.py
# Built-int imports
import sys
# External imports
import cv2 as cv
import numpy as np
class ImageAnalysis:
"""
This is a python class that was implemented to be able to perform
a correct analysis to an image, this class has a method to plot the
... | StarcoderdataPython |
69822 | import mysql.connector
PORT = "3306"
DATABASE = "stockDB"
SERVER_NO = 1
SERVER = {"host": ["localhost", "cadb.cc0uav02d2tx.ap-southeast-2.rds.amazonaws.com"],
"user": ["root", "admin"],
"password": ["<PASSWORD>", "<PASSWORD>"]}
def my_connector(host=SERVER["host"][SERVER_NO],
use... | StarcoderdataPython |
3313741 | from flask import Flask, render_template, request, redirect, session, url_for
from flask_socketio import SocketIO, emit, join_room, leave_room
app = Flask(__name__)
app.config['SECRET_KEY'] = '<KEY>'
socketio = SocketIO(app, manage_session=False)
socketio.init_app(app, cors_allowed_origins="*")
data = {}
users = []... | StarcoderdataPython |
3338212 | import unittest
import os
import os.path
from poly_juice.polyjuice import zip_folder
from poly_juice.lumberjack import Lumberjack
class TestZipFolder(unittest.TestCase):
"""
This test makes sure that the processed folders are successfully zipped.
"""
def setUp(self):
self.directory = os.path... | StarcoderdataPython |
3306888 | import unittest
import sys
import os
path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))
sys.path.insert(0, path)
from src.translator import Translator
from src.base import Vector2D
class TranslationTest(unittest.TestCase):
def test_starting_out(self):
translator = Translator((100, 10... | StarcoderdataPython |
101202 | <gh_stars>1-10
"""Mock OAUTH2 aiohttp.web server."""
from aiohttp import web
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.backends import default_backend
from authlib.jose import jwt, jwk
from typing import Tuple
import urll... | StarcoderdataPython |
3236674 | import copy
from enum import Enum
import sty
from .board import Board
from .location import Location
from .piece import Color, Piece
class Printer:
r"""
Dedicated printer class that caches information about the board so it does not need to be
regenerated each time.
"""
SEP = "|"
EMPTY_LOCAT... | StarcoderdataPython |
3221445 | # Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from botframework.connector.auth import AppCredentials
class OAuthPromptSettings:
def __init__(
self,
connection_name: str,
title: str,
text: str = None,
timeout: int = None,
... | StarcoderdataPython |
84276 | import torch
from scipy import io
import numpy as np
#import visdom
#vis = visdom.Visdom()
file_PATH = '/home/leejeyeol/Documents/ground_truth_demo/testing_label_mask'
num_of_files = 21
for videos in range(1, num_of_files+1):
volLabel = io.loadmat(file_PATH+'/%d_label.mat' % videos)['volLabel'].tolist()[0]
... | StarcoderdataPython |
3389587 | import matplotlib.pyplot as plot
from Chapter15_RandomWalk_class import RandomWalk
rw = RandomWalk()
rw.fill_walk()
plot.scatter(rw.x_values,rw.y_values,s = 1)
plot.show()
| StarcoderdataPython |
118625 | <reponame>LechMadeyski/PhD19MarekSosnicki
from ArticlesDataDownloader.ArticlesDataDownloader import ArticlesDataDownloader
from ArticlesServer.database.DatabaseManager import DatabaseManager
from ArticlesServer.directories import OUTPUT_DIRECTORY, FINDER_FILE
from TextSearchEngine.parse_finder import parse_finder
impor... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.