id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
172540 | <reponame>mlazowik/django-cockroachdb<filename>django_cockroachdb/creation.py
from django.db.backends.postgresql.creation import (
DatabaseCreation as PostgresDatabaseCreation,
)
class DatabaseCreation(PostgresDatabaseCreation):
def _clone_test_db(self, suffix, verbosity, keepdb=False):
raise NotImpl... | StarcoderdataPython |
8059130 | """
Copyright 2018 Google LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distr... | StarcoderdataPython |
1748456 | #!/usr/bin/env python
import sys
from overdub.main import main
sys.exit(main())
| StarcoderdataPython |
1729105 | <reponame>69495/Zooarchaeologist
from mastodon import Mastodon
import json
from login import login
from out_json import jsoner
'''
return_typeはjson or list
defaultはlistで返す
'''
def mining(id, return_type="list", switch=None):
print(return_type + " is selected!")
Mastodon = login(switch)
#timelineからlastes... | StarcoderdataPython |
1845982 | <reponame>tliang1/Academic-Projects<filename>Classes/CS 332L/Latest/src/tebg/entities/enemies/dual_wielding_gunner.py<gh_stars>0
"""
Created on May 11, 2015
@author: <NAME>
Source:
Event Timer by furas: https://stackoverflow.com/questions/40205000/pygame-datet
ime-troubles
... | StarcoderdataPython |
9623755 | <gh_stars>0
import os
import ConfigParser
class Ini(object):
def __init__(self, ini_path):
if os.path.isfile(ini_path):
self.cp = ConfigParser.ConfigParser()
self.cp.read(ini_path)
else:
raise "Invalid INI file specified: %s" % ini_path
def has_option(self,... | StarcoderdataPython |
5156989 | <reponame>sudo-rajarshi/covid19indialive.com<filename>track.py
import pandas as pd
import numpy as np
import requests
from datetime import datetime
import ftplib
import time as ts
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
# # State Data
api_url_data = 'https://api.covid19india.org/data.json'
r... | StarcoderdataPython |
1804761 | # Generated by Django 3.2.6 on 2021-10-24 11:59
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('auth... | StarcoderdataPython |
5089987 | <filename>to_python/core/types.py<gh_stars>1-10
import abc
from copy import copy
from dataclasses import dataclass, field
from typing import List, Dict, Optional, Any
from crawler.core.types import ListType
@dataclass(repr=False)
class FunctionType:
"""
Type description
"""
names: List[str] # Type u... | StarcoderdataPython |
11339594 | <gh_stars>1-10
#!/usr/bin/env python3
import os
from os import listdir
from os.path import isfile
baseRes = 16
reses = [baseRes, baseRes * 2, baseRes * 3]
for f in listdir():
if isfile(f) and f.endswith("png"):
name = f[:-4]
names = list(map(lambda x: name + "@{}x.png".format(x), [1, 2, 3]))
... | StarcoderdataPython |
8187785 | from flask import Flask, request
import contentful
import os
from rich_text_renderer import RichTextRenderer
renderer = RichTextRenderer()
SPACE_ID = os.environ.get("SPACE_ID")
DELIVERY_API_KEY = os.environ.get("DELIVERY_API_KEY")
client = contentful.Client(SPACE_ID, DELIVERY_API_KEY)
app = Flask(__name__)
@app.e... | StarcoderdataPython |
1762318 | <reponame>mrob95/natlink
#
# Python Macro Language for Dragon NaturallySpeaking
# (c) Copyright 1999 by <NAME>
# Portions (c) Copyright 1999 by Dragon Systems, Inc.
#
# testnatlink.py
# This script performs some basic tests of the NatLink system.
# Restart NatSpeak before rerunning this script. This is because... | StarcoderdataPython |
11313156 | import datetime
from django.forms.widgets import Widget
from django.template import loader
from django.utils.safestring import mark_safe
class TimespanWidget(Widget):
"""
Produces 4 text boxes for days/hours/minutes/seconds. Converts data into
- an empty string (net time is zero),
- a string of the... | StarcoderdataPython |
9749981 |
import random
import datetime
import numpy as np
from collections import deque
import tensorflow as tf
from tensorflow.keras.models import Model
from tensorflow.keras.layers import Input, Dense, Lambda, Concatenate
from tensorflow.keras.optimizers import Adam
import tensorflow_probability as tfp
from FQ.FQ_Env import... | StarcoderdataPython |
6434076 | <filename>setup.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
config = {
'name': 'simtools',
'author': 'zachglassman',
'author_email': '<EMAIL>',
'url': '',
'description': '',
'long_description': open('README.rst', 'r').read(),
'license': 'MIT'... | StarcoderdataPython |
4703 | <gh_stars>0
# -*- coding: utf-8 -*-
"""
将耗时间的任务放到线程中以获得更好的用户体验。
"""
import time
import tkinter
import tkinter.messagebox
def download():
# 模拟下载任务需要花费10秒时间
time.sleep(10)
tkinter.messagebox.showinfo('提示', '下载完成')
def show_about():
tkinter.messagebox.showinfo('关于', '作者:罗浩')
def ma... | StarcoderdataPython |
318748 | <filename>utils/drf_utils/custom_exception.py
# -*- coding: utf-8 -*-
# @Time : 2021/3/14 下午9:45
# @Author : anonymous
# @File : custom_exception.py
# @Software: PyCharm
# @Description:
from rest_framework.views import exception_handler
def custom_exception_handler(exc, context):
"""
自定义异常,需要在settings.... | StarcoderdataPython |
8079515 | import json
from abc import ABC, abstractmethod
from functools import lru_cache
from typing import Any, Dict, Iterator, List, Optional, Union
import xmltodict
import yaml
from easytxt.text import replace_chars_by_keys
from pyquery import PyQuery
from easydata.data import DataBag
from easydata.parsers.base import Base... | StarcoderdataPython |
5134967 | <filename>fudgeit/recommendation/migrations/0003_alter_restaurant_user_rating.py
# Generated by Django 3.2.8 on 2021-10-24 06:33
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('recommendation', '0002_fooditem_restaurant'),
]
operations = [
... | StarcoderdataPython |
11235898 | <gh_stars>1-10
import tensorflow as tf
import csv
import json
import numpy as np
import os
import argparse
import torch
parser = argparse.ArgumentParser()
parser.add_argument("--data_dir", default=None, help="The input data dir.")
parser.add_argument("--test_file", default=None, help="Test data file")
parser.add_argum... | StarcoderdataPython |
5090435 | import sublime, sublime_plugin
import re
ERB_BLOCKS = [['<%=', '%>'], ['<%', '%>'], ['<%#', '%>']]
ERB_REGEX = '<%(=?|-?|#?)\s{2}(-?)%>'
# matches opening bracket that is not followed by the closing one
ERB_OPENER_REGEX = '<%[\=\-\#]?(?!.*%>)'
# matches the closing bracket. I couldn't figure out a way to exclude prec... | StarcoderdataPython |
1839427 | <gh_stars>0
import hashlib
import tkinter as tk
from tkinter.filedialog import askopenfilename
filepath = ""
hash_choice = ""
class HashGenerator:
description = "Takes a file and generates the chosen encryption hash for it"
def __init__(self, hashname, filename):
self.hashname = hashname... | StarcoderdataPython |
1925680 | import numpy as np
from typing import List
class DetectedSign:
"""
Class to control detected sign operations.
We define one point of signs retectino contract for communication
"""
def __init__(self, bbox: List[float]) -> None:
self._bbox = np.array(bbox, dtype=np.float32)
def as_dic... | StarcoderdataPython |
8012075 | <filename>app/app.py
from flask import Flask
from flask_restful import Api
from app.resources.commentResource import CommentResource
from app.resources.allTicketsResource import AllTicketsResource
from app.resources.ticketResource import TicketResource
def create_app():
app = Flask(__name__)
api = Api(app)
api.ad... | StarcoderdataPython |
241274 | <reponame>francoisserra/BentoML<gh_stars>1-10
import os
import re
import time
import logging
import functools
import click
from click import ClickException
from ...exceptions import BentoMLException
# from bentoml import configure_logging
from ..configuration import CONFIG_ENV_VAR
from ..configuration import set_deb... | StarcoderdataPython |
3565297 | <filename>LeetcodeAlgorithms/562. Longest Line of Consecutive One in Matrix/longest-line-of-consecutive-one-in-matrix.py
class Solution(object):
def longestLine(self, M):
"""
:type M: List[List[int]]
:rtype: int
"""
if not M:
return 0
hor = [[0] * ... | StarcoderdataPython |
5131638 | <reponame>Hacky-DH/learn
#!/bin/env python
def get_gpu_status(dev_id):
r'''
return res.gpu res.memory
'''
try:
import py3nvml.py3nvml as nv
nv.nvmlInit()
assert dev_id >= 0 and dev_id < nv.nvmlDeviceGetCount()
handle = nv.nvmlDeviceGetHandleByIndex(dev_id)
... | StarcoderdataPython |
9688359 | import torch
def viterbi_decode(nodes, trans):
"""
维特比算法 解码
nodes: (seq_len, target_size)
trans: (target_size, target_size)
"""
with torch.no_grad():
scores = nodes[0]
scores[1:] -= 100000 # 刚开始标签肯定是"O"
target_size = nodes.shape[1]
seq_len = nodes.shape[0]
... | StarcoderdataPython |
187992 | <filename>project3/solutions/problem7_request_routing_web_srv_tries.py
# A RouteTrie will store our routes and their associated handlers
class RouteTrie:
def __init__(self):
# Initialize the trie with an root node and a handler, this is the root path or home page node
self.root = RouteTrieNode()
... | StarcoderdataPython |
4839187 | """
Given an array nums and a value val, remove all instances of that value in-place and return the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
The order of elements can be changed. It doesn't matter what you leave beyond the ... | StarcoderdataPython |
4943856 | # coding: utf-8
# Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c... | StarcoderdataPython |
3452420 | <reponame>theXYZT/codejam-2021
# Codejam 2021, Qualification Round: Cheating Detection
import numpy as np
def find_cheater(x):
Pq = x.mean(0)
correct = np.array([Pq[x[i]].mean() for i in range(100)])
wrong = np.array([Pq[~x[i]].mean() for i in range(100)])
return np.argmin(correct - wrong) + 1
# I/... | StarcoderdataPython |
6614272 | <gh_stars>0
import requests
import logging
import json
import jsonpath
def test_get_database():
# url = 'http://0.0.0.0:8080/cloudmesh/v3/ui/#/Database%20Registry/cloudmesh.database.get'
url = 'http://0.0.0.0:8080/cloudmesh/v3/database'
response = requests.get(url)
assert response.status_code == 200
... | StarcoderdataPython |
3484386 | test = {
'name' : '1.3',
'suites' : [{
'cases' : [{
'code' : r"""
>>> weight = variables.where('variable name', 'weight')
>>> weight.column('classification')[0]
'quantitative'
"""
}, {
'code' ... | StarcoderdataPython |
3516959 | <gh_stars>0
"""Perform fixed length XOR operations."""
from encode_decode import decode_hex, encode_hex
def xor_hex(hex_1, hex_2):
"""XOR two fixed length hex strings."""
return encode_hex(xor(decode_hex(hex_1), decode_hex(hex_2)))
def xor(bytes_1, bytes_2):
"""XOR two bytearrays of the same length."""... | StarcoderdataPython |
11381033 | """
Globally available fixtures.
https://docs.pytest.org/en/stable/fixture.html#scope-sharing-fixtures-across-classes-modules-packages-or-session
"""
import pytest
from starlette.testclient import TestClient
from app.dependencies import RedisBackend
from app.main import app
@pytest.fixture(scope='session')
def clie... | StarcoderdataPython |
1755728 | # 16. Take integer inputs from user until he/she presses q
# ( Ask to press q to quit after every integer input ).
# Print average and product of all numbers.
allnumbers = list()
while True:
user = input("Enter a number (q to Quit):")
if "q" in user.lower():
break
else:
allnumbers.append(in... | StarcoderdataPython |
11211885 | import time
import logging
try:
import stripe
except ImportError:
raise Exception('Stripe library not found, please install requirements.txt')
logger = logging.getLogger(__name__)
class Stripe(object):
"""TODO needs docstring"""
VERSION = 'v1'
RESPONSE_KEYS = {
'id':'trans_id',
'... | StarcoderdataPython |
296490 | <reponame>wangkangcheng/ccc<filename>qap/cloud_utils.py<gh_stars>0
# cloud_utils.py
#
# Contributing authors: <NAME>, <NAME>, 2015
'''
'''
def pull_S3_sublist(yaml_outpath, img_type, cfg_file):
# function example use:
#
# yamlpath = os.path.join(os.getcwd(), "s3dict.yml")
#
# # Build entire filep... | StarcoderdataPython |
8079018 | <filename>app_spider/api/poem/searcher.py
import json
from time import sleep
from django.core.exceptions import ObjectDoesNotExist
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from app_poem.models import Poem, Author, Dynasty, Tag
from libs.spider.poem_spider import gushiw... | StarcoderdataPython |
1925572 | from typing import Any
from .abstract_io_context import AbstractIoContext
class NullIoContext(AbstractIoContext):
"""An input/output context for not actually printing anything."""
def info(
self,
*args: Any,
**kwargs: Any
) -> None:
pass
def warn(
self,
... | StarcoderdataPython |
74443 | <reponame>fiam/blangoblog<filename>blango/views.py
from datetime import date
from xml.etree import cElementTree
from django.shortcuts import get_object_or_404
from django.http import HttpResponse, HttpResponseRedirect
from django.views.generic.simple import direct_to_template
from django.utils.translation import ugett... | StarcoderdataPython |
8093045 | from cobiv.modules.core.session.cursor import CursorInterface
from cobiv.modules.database.sqlitedb.sqlitedb import SqliteCursor
print(issubclass(SqliteCursor, CursorInterface))
| StarcoderdataPython |
1670994 | #!/usr/bin/env python3
"""A simple example of a linear regression
"""
from __future__ import absolute_import, division, print_function, unicode_literals
import argparse
import matplotlib.pyplot as plt
import tensorflow as tf
class Model(tf.keras.Model):
"""A simple fully connected layer
Attributes:
... | StarcoderdataPython |
8172649 | # -*- coding: utf-8 -*-
from pineboolib.utils import aqtt
from pineboolib.fllegacy.FLRelationMetaData import FLRelationMetaData
class FLFieldMetaData(object):
"""
@param n Nombre del campo
@param a Alias del campo, utilizado en etiquetas de los formularios
@param aN TRUE si permite nulos (NULL), FALSE si lo... | StarcoderdataPython |
6673741 | import asyncio
import logging
from unittest.mock import MagicMock
import aiohttp
import pytest
import HABApp
from HABApp.core.wrapper import ExceptionToHABApp, ignore_exception
log = logging.getLogger('WrapperTest')
@pytest.fixture
def p_mock():
post_event = HABApp.core.EventBus.post_event
HABApp.core.Even... | StarcoderdataPython |
6569339 | <reponame>rafaelurben/python-nonogram
class NonogramException(Exception):
pass
class UnsolvableState(NonogramException):
pass
class UnsolvableLine(UnsolvableState):
pass
| StarcoderdataPython |
8177735 | import sqlite3, config
import alpaca_trade_api as tradeapi
connection = sqlite3.connect(config.DB_FILE) # connect to db
connection.row_factory = sqlite3.Row # I want sqlite3 objects to return from a query
cursor = connection.cursor() # cursor obj
cursor.execute("""
SELECT id, symbol, name FROM stock
""")
rows ... | StarcoderdataPython |
6438114 | <gh_stars>1-10
import os
from fnmatch import fnmatch
from wok.core.plugin import Plugin
from wok.logger import get_logger
class StorageError(Exception):
pass
class ObjectAlreadyExistsError(Exception):
pass
class NotEmptyContainerDeletedError(Exception):
def __init__(self, name):
Exception.__init__(self, "Can n... | StarcoderdataPython |
12851944 | <reponame>7h3rAm/rudra
from lib.external.PluginManager import PluginInterface, Manager
from prettytable import PrettyTable
from aayudh import utils, fileutils
import sys
import os
current_dir = os.path.abspath(os.path.dirname(__file__))
root_dir = os.path.normpath(os.path.join(current_dir, ".."))
sys.path.insert(0, ... | StarcoderdataPython |
1933795 | <reponame>tdscheper/UMich-Course-Guide-Retriever
"""Define class for Keyword argument."""
from args import _ArgType, _QueryValues, _QueryKVPairs, _ARG_TYPE_TO_QUERY_KEY
from args.meta_arg import MetaArg
from args.arg import Arg
class Keyword(Arg, metaclass=MetaArg, argtype=_ArgType._KEYWORD):
"""Keyword argument.... | StarcoderdataPython |
9711977 | <gh_stars>0
print(' \033[36;40mExercício Python #072 - Número por Extenso\033[m')
nomesNumero = ('zero', 'um', 'dois', 'três', 'quatro', 'cinco', 'seis', 'sete', 'oito', 'nove', 'dez', 'onze', 'doze', 'treze', 'quatorze', 'quinze', 'dezesseis', 'dezessete', 'dezoito', 'dezenove', 'vinte')
escolha = 0
print('=-=' * 20... | StarcoderdataPython |
12845166 | <gh_stars>1-10
"""Routines for handling patient lists."""
# TODO: Some functions from dwi.compat should be replaced with something better
# here, they're still used by tools/{roc_auc,correlation}.py.
from .types import GleasonScore
def label_lesions(patients, thresholds=None):
"""Label lesions according to scor... | StarcoderdataPython |
3395351 | from tamproxy import Sketch, SyncedSketch, Timer
from tamproxy.devices import Motor
# Cycles a motor back and forth between -255 and 255 PWM every ~5 seconds
class MotorWrite(Sketch):
def setup(self):
self.motor = Motor(self.tamp, 2, 3)
self.motor.write(1,0)
self.delta = 1
self.mo... | StarcoderdataPython |
6407088 | from statsmodels.tools.eval_measures import rmse
from copy import deepcopy
import numpy as np
import shlex
import os
from config import SPEC_DIR
import respy
def get_est_log_info():
""" Get the choice probabilities.
"""
with open('est.respy.info') as in_file:
for line in in_file.readlines():
... | StarcoderdataPython |
6590458 | #!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Interactive python script for testing cgroups. It will try to use system
resources such as cpu, memory and device IO. The other cgroups test
instrumentation will inspect whether the linux box behaved as it should.
@copyright: 2011 Red Hat Inc.
@author: <NAME> <<EMAIL>>
"""... | StarcoderdataPython |
17093 | class Solution:
def runningSum(self, nums: List[int]) -> List[int]:
for index in range(1, len(nums)):
nums[index] = nums[index - 1] + nums[index]
return nums
| StarcoderdataPython |
6407663 | #
# Wrappers for model evaluation
#
import torch
import torch.nn.functional as F
from torch.utils.data import Dataset, DataLoader
from modules import Classifier
from typing import Generator, NamedTuple, Optional, Union
from utils import expand_generator
class Evaluator(object):
class Result(NamedTuple):
... | StarcoderdataPython |
6639765 | <filename>tests/tracer/test_propagation.py
from unittest import TestCase
from ddtrace.context import Context
from ddtrace.propagation.http import HTTPPropagator
from ddtrace.propagation.http import HTTP_HEADER_ORIGIN
from ddtrace.propagation.http import HTTP_HEADER_PARENT_ID
from ddtrace.propagation.http import HTTP_H... | StarcoderdataPython |
3522021 | <reponame>SAMY-ER/Protein-Folding-Problem<gh_stars>1-10
from psp.agents import QAgent, DQNAgent, DDQNAgent
from psp.env import ProteinStructureEnv
from psp.utils import SEQUENCE_1, SEQUENCE_2, SEQUENCE_3, SEQUENCE_4, SEQUENCE_5, SEQUENCE_6 | StarcoderdataPython |
1895834 | <reponame>RevansChen/online-judge
# Python - 3.6.0
Test.describe('Basic tests')
Test.assert_equals(basic_op('+', 4, 7), 11)
Test.assert_equals(basic_op('-', 15, 18), -3)
Test.assert_equals(basic_op('*', 5, 5), 25)
Test.assert_equals(basic_op('/', 49, 7), 7)
| StarcoderdataPython |
4895629 | import boto3
import botocore
import Settings
class SQSConnection:
session = boto3.Session(
aws_access_key_id=Settings.AWS_ACCESS_KEY_ID_SQS,
aws_secret_access_key=Settings.AWS_SECRET_ACCESS_KEY_SQS,
)
sqs = session.client('sqs', region_name=Settings.AWS_REGION_SQS)
... | StarcoderdataPython |
6685561 | """
This file contains methods allowing for interaction with the MetaNet website
(https://metaphor.icsi.berkeley.edu/pub/en/). They are needed since it appears that there
is no API available to access MetaNet programmatically.
"""
import re
import json
import logging
from time import time
from bs4 import BeautifulSoup
... | StarcoderdataPython |
369692 | <filename>head_segmentation/__init__.py
from ._version import __version__
from .constants import *
from .image_processing import *
from .model import *
from .segmentation_pipeline import *
from .visualization import *
| StarcoderdataPython |
135319 | <filename>tools/libclang_version.py
from ctypes import CDLL, c_char_p
from platform import system
from re import compile
clang_version = None
def get_libclang_version():
global clang_version
if clang_version:
return clang_version
if system() == 'Darwin':
lib_file = 'libclang.dylib'
el... | StarcoderdataPython |
5083987 | import functools
import torch
def castargs_pytorch_to_numpy(func):
@functools.wraps(func)
def wrapper_func(*args, **kwargs):
new_args = []
for arg in args:
if isinstance(arg, torch.Tensor):
new_args.append(arg.detach().numpy())
else:
new_... | StarcoderdataPython |
4860471 | <reponame>shoresh57/AzureMLWorkshop
import os
import numpy as np
import pandas as pd
import lightgbm
from sklearn.model_selection import StratifiedKFold
from azureml.core import Run
import joblib
import argparse
import statistics
# Get the experiment run context
run = Run.get_context()
# Get parameters
parser = argpa... | StarcoderdataPython |
3387714 | # -*- coding: utf-8 -*-
"""Middleware tests."""
from __future__ import unicode_literals
from django.test import TestCase
from django.http import HttpRequest, HttpResponse
from dnt.middleware import DoNotTrackMiddleware
class DoNotTrackMiddlewareTest(TestCase):
"""Unit tests for the DoNotTrackMiddleware."""
... | StarcoderdataPython |
5093297 | <reponame>JCoMcL/DCU_Discord_Bot<gh_stars>1-10
import discord
from discord.ext import commands
class Whisper(commands.Cog):
"""Whispers, for DCU Bot.
PM the bot with the !whisper prefix,
along with your message."""
def __init__(self, bot):
self.bot = bot
@commands.dm_only()
@commands.... | StarcoderdataPython |
8080537 | """
# GitHub examples repository path: Powersupplies/Python/RsInstrument
Created on 2022/03
Author: Jahns_P
Version Number: 1
Date of last change: 2022/03/18
Requires: R&S NGP series PSU, FW 2.015 or newer
- Installed RsInstrument Python module (see https://rsinstrument.readthedocs.io/en/latest/)
- Installed VISA e.g... | StarcoderdataPython |
5057112 | #!/usr/bin/python
"""
Summary:
Two functions to evaluate the number of trees using AUC-ROC/PR as score.
One Function to evalute the training sample size.
Inputs for plot_Ntree_..._curve:
classifier - The classifier you want to train. See GBC_Maker file.
train, test - (X_train,y_train), (X_test... | StarcoderdataPython |
11379495 | import numpy as np
import cv2
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
def undistort(img, mtx, dist):
undist = cv2.undistort(img, mtx, dist, None, mtx)
return undist
# Define a function that takes an image, number of x and y points,
# camera matrix and distortion coefficients
def co... | StarcoderdataPython |
9794433 | # -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-07-12 08:20
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('app_name', '0003_environmentvariable_ftp_war_name'),
]
operations = [
migra... | StarcoderdataPython |
6701999 |
import os
import pdb
import time
import sys
from optparse import OptionParser
import numpy as np
import keras
import tensorflow as tf
import tensorlayer as tl
from tensorlayer.layers import *
from data.twitter import data
from data.twitter import data_retrieval
from seq2seq_word import build_seq2seq_word, load_data,... | StarcoderdataPython |
4972752 | <filename>tests/contrib/sanic/sanic_tests.py<gh_stars>0
# BSD 3-Clause License
#
# Copyright (c) 2019, Elasticsearch BV
# 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 ... | StarcoderdataPython |
9778165 | <filename>keras/dtensor/layout_map_test.py<gh_stars>0
# Copyright 2022 The TensorFlow 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.o... | StarcoderdataPython |
4862851 | <reponame>towns-man/osm-gimmisn<gh_stars>0
#!/usr/bin/env python3
#
# Copyright 2020 <NAME>. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
#
"""Compares OSM streets with reference ones and shows the diff."""
import sys
import areas
import c... | StarcoderdataPython |
99543 | <reponame>IbHansen/modelflow2
# -*- coding: utf-8 -*-
"""
This script runs a model with numba
@author: hanseni
"""
import sys
from modelclass import model
mmodel, basedf = model.modelload(sys.argv[1],run=1,ljit=1,stringjit=False)
| StarcoderdataPython |
6616186 | <reponame>abhijeetbhagat/mp4box
from mp4box.utils.sample import VideoSample
from mp4box.utils.stream_reader import StreamReader
# SampleGenerator should work with both stbls and truns
# It should work with one mdat at a time.
class SampleGenerator:
def __init__(self, stbl):
self.stbl = stbl
def get_sa... | StarcoderdataPython |
3513751 | from distutils.core import Extension
from os.path import join
import numpy as np
include_dirs = [np.get_include()]
macros = [('NPY_NO_DEPRECATED_API', 0)]
# https://numpy.org/devdocs/reference/random/examples/cython/setup.py.html
extensions = [
Extension(
"occuspytial.distributions",
["occuspyti... | StarcoderdataPython |
4832184 | <reponame>dadalab/cloudcase-clone<filename>UserApp/models.py<gh_stars>0
from __future__ import unicode_literals
import datetime
from django.db import models
from django.contrib.auth.models import User
from django.forms.models import model_to_dict
class CaseOfficer(models.Model):
user = models.OneToOneField(User,... | StarcoderdataPython |
9750572 | import pandas as pd
from bokeh.plotting import figure
from bokeh.models import ColumnDataSource
from bokeh.transform import jitter
from .base import PlotView
DAYS = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
class PulsePlot(PlotView):
def data(self):
pdf = pd.DataFrame()
pdf["day"] = self... | StarcoderdataPython |
1702287 | <reponame>QianLiGui/tfsnippet
import numpy as np
from tfsnippet.utils import DocInherit
from .base import DataFlow
__all__ = [
'DataMapper', 'SlidingWindow'
]
@DocInherit
class DataMapper(object):
"""
Base class for all data mappers.
A :class:`DataMapper` is a callable object, which maps input arra... | StarcoderdataPython |
4940756 | """
Module: early_stopping.py
Authors: <NAME>
Institution: Friedrich-Alexander-University Erlangen-Nuremberg, Department of Computer Science, Pattern Recognition Lab
Last Access: 06.02.2021
"""
"""
Early stopping criterion as a regularization in order to stop the training after no changes with respect to a chosen
vali... | StarcoderdataPython |
5041232 | import re
import html
from math import log
from collections import Counter,defaultdict
import logging
logging.basicConfig(format='%(asctime)s %(levelname)-8s %(message)s', \
level=logging.INFO, \
datefmt='%Y-%m-%d %H:%M:%S')
from pdb import set_trace as bp
class NaiveBayes:
... | StarcoderdataPython |
4956011 | <filename>chapter7/exercises/EG7-06 Default parameters.py
# EG7-05 Keyword Arguments
def print_times_table(times_value, limit):
count = 1
while count < limit+1:
result = times_value * count
print(count,'times', times_value,'equals',result)
count = count + 1
print_times_table(tim... | StarcoderdataPython |
9734099 | <filename>src/masonite/commands/PresetCommand.py
"""New Preset Command."""
from .Command import Command
from ..presets import Remove
class PresetCommand(Command):
"""
Scaffold frontend preset in your project
preset
{name? : Name of the preset}
{--r|remove=? : Remove all scaffolded presets... | StarcoderdataPython |
4811018 | #!/usr/bin/python3.6
# created by cicek on 30.07.2018 23:12
try:
num1 = 5
num2 = 0
print(num1 / num2)
print("Done!!!")
except ZeroDivisionError:
print("\nAn error occurred")
print("due to zero division\n")
# Exception Handling, kural dışı durum izleme
try:
num1 = "aa"
num2 = 0
pr... | StarcoderdataPython |
9711772 | import _thread
import json
import os
import time
from django.http import HttpResponse, StreamingHttpResponse
from . import bencoding
import MainDB.models as DB
from django.shortcuts import render
from pyaria2 import Aria2RPC
from .Authorization import AuthorizationCheck
from .EventReg import ExcuteEvent
from .Functio... | StarcoderdataPython |
4823317 | <filename>answers/Utkarsh Srivastava/Day 2/Question 1.py
n = int(input())
e = 0
s = 0
for i in range(2,n):
if(n%i == 0):
e = 1
if(e==0):
while (n != 0):
n = int(n/10)
s = s*10+b
for i in range(2,s):
if(s%i == 0):
e = 1
if(e!=1):
print("It is a Emirp number")
else:
pri... | StarcoderdataPython |
3419473 | # -*- coding: utf-8 -*-
# Eclipse SUMO, Simulation of Urban MObility; see https://eclipse.org/sumo
# Copyright (C) 2011-2019 German Aerospace Center (DLR) and others.
# This program and the accompanying materials
# are made available under the terms of the Eclipse Public License v2.0
# which accompanies this distributi... | StarcoderdataPython |
3245957 | '''
Stripped down transformer network inspired architecture for MSAIC 2018
Built by <NAME> for team msaic_yash_sara_kuma_6223
This file contains the class for the network architecture, with built in functions for training
and operations. Any crucial step will be commented there.
Cheers!
'''
# importng the dependenci... | StarcoderdataPython |
253108 | <reponame>baovien/dota-oracle<filename>doracle/model.py
import random
class HeroStats:
def __init__(self):
pass
def get_winrate(self, hero_id):
return random.random()
def get_pickrate(self, hero_id):
return random.random()
def get_best_paired_with_hero(self, hero_id):
... | StarcoderdataPython |
271804 | # Generated by Django 3.0.5 on 2020-05-22 05:30
from django.conf import settings
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
... | StarcoderdataPython |
1790927 | <filename>alipay/aop/api/domain/NewsEntityAggregation.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
from alipay.aop.api.domain.NewsAggregationValue import NewsAggregationValue
from alipay.aop.api.domain.NewsAggregationValue import NewsAggregationValue... | StarcoderdataPython |
1740857 | <gh_stars>0
from PyQt4 import QtGui
class BaseDialogMixIn(QtGui.QDialog, object):
'''
Base dialog mixin
'''
def showDialog(self):
'''
Show the dialog.
:return:
'''
self.setupUi(self)
self.retranslateUi(self)
self.show()
self.exec_()
| StarcoderdataPython |
3555498 | from pydantic import BaseModel, EmailStr, constr, validator
class RegisterSchema(BaseModel):
email: EmailStr
username: constr(min_length=3)
confirm_password: constr(min_length=6)
password: constr(min_length=6)
@validator('password')
def validate_password(cls, v, values, **kwargs):
if '... | StarcoderdataPython |
6544735 | <reponame>cristilianojr/LoginSystem
from models import database
def check_username_exitence(database: database.DataBase, username: str) -> bool:
# Just update to verify
database._do_update_data()
for line in database.data:
if username in line:
return True
return False
def register... | StarcoderdataPython |
9700426 | <reponame>alexvonduar/gtec-demo-framework
#!/usr/bin/env python3
#****************************************************************************************************************************************************
# Copyright (c) 2014 Freescale Semiconductor, Inc.
# All rights reserved.
#
# Redistribution and use in ... | StarcoderdataPython |
367352 | import biotk.libs.BurstMetrics as bm
import os
class _test_burst_metrics:
def __init__(self, sset_path, subsampleto=None):
self.burst_metrics = bm.PpaBurstMetrics(sset_path,
subsampleto=subsampleto)
def test_burst_metrics_initialization():
"""
Given ... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.