id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
6485120 | """http://ginstrom.com/scribbles/2007/10/08/design-patterns-python-style/
An example of the Template pattern in Python"""
ingredients = "spam eggs apple"
line = '-' * 10
# Skeletons
def iter_elements(getter, action):
"""Template skeleton that iterates items"""
for element in getter():
action(element... | StarcoderdataPython |
1676946 | def extract_full_names(people):
"""Return list of names, extracting from first+last keys in people dicts.
- people: list of dictionaries, each with 'first' and 'last' keys for
first and last names
Returns list of space-separated first and last names.
>>> names = [
... {'... | StarcoderdataPython |
6623922 | class Rat(object):
n : int = 0
d : int = 0
def __init__(self : Rat):
pass
def new(self : Rat, n : int, d : int) -> Rat:
self.n = n
self.d = d
return self
def mul(self : Rat, other : Rat) -> Rat:
return Rat().new(self.n * other.n, self.d * other.d)
r1 : Rat = N... | StarcoderdataPython |
6434020 | <gh_stars>1-10
from sklearn.datasets import load_breast_cancer
from sklearn.metrics import accuracy_score, classification_report, confusion_matrix
from sklearn.model_selection import train_test_split
from sklearn.svm import SVC
X, y = load_breast_cancer(return_X_y=True)
classes = ['Malignant', 'Benign']
X_train, X_t... | StarcoderdataPython |
12622 | <reponame>florianm/biosys
from django.shortcuts import reverse
from django.test import TestCase
from rest_framework import status
from rest_framework.test import APIClient
from main.models import Project
from main.tests import factories
from main.tests.api import helpers
class TestWhoAmI(helpers.BaseUserTestCase):
... | StarcoderdataPython |
6591731 | from django.contrib import admin
from teacher.models import Teacher
from django.contrib.auth.admin import UserAdmin
class TeacherAdmin(UserAdmin):
list_display = ('email','username','date_joined','is_admin','is_staff')
search_fields = ('email','username')
readonly_fields = ('date_joined','last_login')
filter_hori... | StarcoderdataPython |
1675221 | import collections
import re
Progress = collections.namedtuple('Progress', [
'frame', 'fps', 'size', 'time', 'bitrate', 'speed'
])
Progress_psnr = collections.namedtuple('Progress_psnr',['PSNR'])
Progress_vmaf = collections.namedtuple('Progress_vmaf',['VMAF'])
Progress_ssim = collections.namedtuple('Progress_ssim... | StarcoderdataPython |
9786107 | <filename>evaluatewindow.py
import sqlite3
from PyQt5 import QtCore, QtGui, QtWidgets
myteam= sqlite3.connect("TEAM.db")
class Ui_EvaluateWindow(object):
def setupUi(self, EvaluateWindow):
EvaluateWindow.setObjectName("EvaluateWindow")
EvaluateWindow.resize(699, 509)
self.centralw... | StarcoderdataPython |
3246782 | """Fun(c) with dates"""
# %% Imports
from datetime import datetime, timedelta
from typing import List
# %% Mondays
def mondays_between_two_dates(start: datetime, end: datetime) -> List[str]:
"""Returns the dates of each Monday between two dates, inclusive.
:param start (str) : ISO-formatted start date.
:... | StarcoderdataPython |
12859639 | """
WSGI config for pycess project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/dev/howto/deployment/wsgi/
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "pycess.settings")
from django.core.wsg... | StarcoderdataPython |
3354966 | from dataclasses import dataclass
from dataclasses_json import dataclass_json
from typing import Optional
from .texture_info import TextureInfo
@dataclass_json
@dataclass
class NormalTextureInfo(TextureInfo):
"""
Material Normal Texture Info
Properties:
index (integer) The index of the texture. (Requ... | StarcoderdataPython |
11320179 | import os
import sys
from datetime import datetime
class Logger(object):
"""class that logs output to a log file and stdout"""
def __init__(self, name, save_dir=None, attr=None, ovrw=False):
"""Constructor
name: the name for the log file
attr: an optional additional name for the... | StarcoderdataPython |
6429627 | from fidimag.common import CuboidMesh, constant
from fidimag.micro import UniformExchange, Sim, Zeeman
import numpy as np
def test_add_remove_interaction_simple():
mesh = CuboidMesh(nx=10, ny=10, nz=10, unit_length=1e-9)
name = 'test_add_remove_intn_simple'
sim = Sim(mesh, name=name)
sim.set_m(lambda p... | StarcoderdataPython |
6445138 | import sys
src = sys.argv[1]
tgt = sys.argv[2]
fw = open(tgt, 'w', encoding="utf8")
with open(src, 'r', encoding='utf8') as f:
for line in f:
items = line.strip().split()
utt = items[0]
txt = " ".join(list("".join(items[1:])))
fw.write(utt + " " + txt + '\n')
fw.close()
| StarcoderdataPython |
6509274 | <reponame>nikitagoel7/Client-Server-Chatting-Application<gh_stars>0
# Python TCP Client A
import socket
host = socket.gethostname()
port = 64000
BUFFER_SIZE = 2048
MESSAGE = input("tcpClientA: Enter message/ Enter exit:")
tcpClientA = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcpClientA.connect((host, p... | StarcoderdataPython |
1910062 | """
This file provides some simple tools to simulate and work with a tic tac toe board.
The functions provided assume the board is represented by
- np array of shape 3,3
- player 1 is 1, player 2 is -1 and empty is 0
"""
import logging
import itertools
import numpy as np
import gym
from gym import spaces, err... | StarcoderdataPython |
6628473 | <gh_stars>1-10
from makepy.shell import run, rm
import logging
log = logging.getLogger(__name__)
def tox(envlist=None):
log.info('starting tox tests for envlist: %s', envlist)
if envlist is None: run(['tox'])
else: run(['tox', '-e', envlist])
def clean(): rm('.tox')
| StarcoderdataPython |
101970 | <gh_stars>1-10
import json
from datetime import datetime
from bson import ObjectId
from dateutil import parser
class Project:
def __init__(
self,
name,
city,
description,
start_time,
end_time,
):
self.name = name
self.city = city
self.de... | StarcoderdataPython |
4952864 | <reponame>jeokrohn/wxc_sdk
from .base import TestCaseWithLog
class TestLocation(TestCaseWithLog):
def test_001_list_all(self):
"""
list all locations
"""
location_list = list(self.api.locations.list())
print(f'Got {len(location_list)} locations')
| StarcoderdataPython |
3345085 | #!/usr/bin/env python
##
## See COPYING file distributed along with the ncanda-data-integration package
## for the copyright and license terms
##
#
# List of fields to copy straight into REDCap
#
fields_to_copy = [ "AL1AgeOns", "AL1a",
'ASa_ao2DK', 'ASb_ao2DK', 'ASc1_ao6DK', 'ASc2_ao6DK', 'AS_ao... | StarcoderdataPython |
3307267 | """The Page database model."""
from __future__ import annotations
import uuid
from datetime import datetime
from typing import Any, Dict, List, Optional
from sqlalchemy import JSON, Column, DateTime, Integer, Unicode, UnicodeText
from .base import Base
__all__ = ["SqlPage"]
class SqlPage(Base):
"""The SQLAlc... | StarcoderdataPython |
148054 | from OpenGL import GL
import glm
import importlib
import Helpers
importlib.reload(Helpers)
from Helpers import compile_shader, link_program, create_program_attribute_layout, create_vertex_array_and_draw_call,\
flatten_vertex_data, validate_vertex_data, validate_attribute_bindings
def create_cube(s):
... | StarcoderdataPython |
1820975 | #!/usr/bin/env python3
help =\
'''
Plot trajectory, or frames if solution has two spatial dimensions, generated by
running a PETSc TS program. Reads output from
-ts_monitor binary:TDATA -ts_monitor_solution binary:UDATA
Requires copies or sym-links to $PETSC_DIR/lib/petsc/bin/PetscBinaryIO.py and
$PETSC_DIR/lib/pe... | StarcoderdataPython |
5030368 | from datetime import date
from typing import Any
from typing import TypeVar
from typing import Union
from hw.alexander_sidorov.common import Errors
from hw.alexander_sidorov.common import api
from hw.alexander_sidorov.common import typecheck
T1 = TypeVar("T1")
@api
@typecheck
def task_04(birthdays: dict[T1, date]) ... | StarcoderdataPython |
12864215 | # Copyright 2020 <NAME> (Falcons)
# SPDX-License-Identifier: Apache-2.0
#!/usr/bin/env python3
# <NAME>, March 2020
# Robot will continuously intercept around current position.
#
# For description and usage hints, execute with '-h'
import sys, os
import time
import logging, signal
logging.basicConfig(level=logging.... | StarcoderdataPython |
11363161 | <reponame>szypkiwonsz/Physiotherapy-Management-System
import calendar
import datetime
import pandas as pd
from applications.users.models import OfficeDay, UserOffice
from utils.add_zero import add_zero
def get_number_of_days_in_month(year, month):
"""
A function that returns a list of the number of days in ... | StarcoderdataPython |
1894615 | from appium import webdriver
import time
# from load_xls import read_excel
from pykeyboard import PyKeyboard
import xlrd
import xlwt
# 启动appium
def android_driver():
# 初始化配置,设置Desired Capabilities参数
desired_caps = {
"platformName": "Android",
"platformVersion": "7.1.2",
"deviceName": "... | StarcoderdataPython |
1848308 | # -*- coding: utf-8 -*-
import os
from peewee import *
from playhouse.pool import PooledPostgresqlDatabase
from src.config import DB_CONNECTION_DB_NAME, DB_CONNECTION_HOST, DB_CONNECTION_USERNAME, DB_CONNECTION_PORT, \
DB_CONNECTION_PASSWORD
__author__ = "zebraxxl"
DB_CONNECTION = PooledPostgresqlDatabase(datab... | StarcoderdataPython |
4870712 | <reponame>ProEgitim/Python-Dersleri-BEM<gh_stars>1-10
"""in operatoru içinde olup olmadıgına bakar"""
liste = [1,2,3,4,5,6,7,8,9]
for eleman in liste:
print("Eleman: ",eleman)
toplam=0
for e in liste:
toplam += e
print("toplam: ",toplam)
for sayi in liste:
if(sayi % 2 == 0):
print(sayi," sayimiz ... | StarcoderdataPython |
254286 | <reponame>ikekilinc/Columbus
# Columbus - A Smart Navigation System for the Visually-Impaired
# This is the main file that controls the functionalities of Columbus. This file
# calls others in the main project folder to import and export data as needed to
# operate Columbus and create a cogent user-experience. This fi... | StarcoderdataPython |
4972446 | """This module manages the automatic generation of new context files based on
a list of new rmaps and a baseline context.
"""
import os.path
import sys
import shutil
import re
import glob
import crds
from crds.core import (rmap, utils, log, cmdline, config)
from . import refactor
# ===================================... | StarcoderdataPython |
1658268 | #verkefni2_12
import re
from fractions import Fraction
def scale(s, ratio):
get_numerals = re.findall(r"([0-9]?[r\/]*[0-9])", s)
calculated = []
for val in get_numerals:
val = val + '*' + ratio
val = eval(val)
calculated.append(str(Fraction(val).limit_denominator()))
#split_stri... | StarcoderdataPython |
1881639 | <gh_stars>0
import unittest
from app.models import Comment
def setUp(self):
self.new_comment = Comment(id=2, pitch_id=100, pitch_comment='Test Comment', user_id=11)
def tearDown(self):
Comment.query.delete()
def test_check_instance_variables(self):
self.assertEquals(self.new_comment.id, 2)
self.a... | StarcoderdataPython |
6580373 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright © 2019 <NAME>
""" Interactive layout figure with paraxial editing
.. Created on Thu Mar 14 10:20:33 2019
.. codeauthor: <NAME>
"""
import numpy as np
from rayoptics.gui.util import bbox_from_poly
from rayoptics.mpl.interactivefigure import InteractiveFigur... | StarcoderdataPython |
3412500 | <reponame>CREATE-CHENG/skatelife
from django.contrib import admin
from .models import User
from imagekit.admin import AdminThumbnail
class AvatarAdmin(admin.ModelAdmin):
list_display = ('__str__', 'admin_thumbnail')
admin_thumbnail = AdminThumbnail(image_field='avatar_thumbnail')
admin.site.register(User, A... | StarcoderdataPython |
11226719 | <filename>tests/test_api.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
import numpy as np
from funcat import *
def test_000001():
from funcat.data.tushare_backend import TushareDataBackend
set_data_backend(TushareDataBackend())
T("20161216")
S("000001.XSHG")
assert np.equal(round(CLOSE.va... | StarcoderdataPython |
1676265 | # Status: ported
# Base revision: 64488
#
# Copyright (c) 2005, 2010 <NAME>.
# Copyright 2006 <NAME>.
#
# Use, modification and distribution is subject to the Boost Software
# License Version 1.0. (See accompanying file LICENSE.txt or
# https://www.bfgroup.xyz/b2/LICENSE.txt)
# Provides mechanism for installing whole ... | StarcoderdataPython |
5040601 | <filename>conanfile.py
from conans import ConanFile, CMake
from os import getcwd
class Domains(ConanFile):
name = "domains"
version = "0.0.1"
url = "https://github.com/skizzay/domains.git"
settings = "os", "compiler", "build_type", "arch"
generators = "cmake", "txt", "env", "ycm"
exports = "CMa... | StarcoderdataPython |
6596720 | from aws_cdk import cdk
class %name.PascalCased%Stack(cdk.Stack):
def __init__(self, app: cdk.App, id: str, **kwargs) -> None:
super().__init__(app, id)
# The code that defines your stack goes here
| StarcoderdataPython |
1770464 | <gh_stars>10-100
from pyzbar import pyzbar
from PIL import Image
def decode_qr_code(img):
txt = pyzbar.decode(img, symbols=[pyzbar.ZBarSymbol.QRCODE])
if len(txt):
return txt[0].data.decode("utf-8")
else:
return "decode fail"
qrcode = Image.new('RGB', (27, 27),color=(255,255,255))
f = ope... | StarcoderdataPython |
5025801 | <reponame>ttumiel/interpret
"Basic attribution that uses the gradient as the attribution map"
from .attribute import Attribute
class Gradient(Attribute):
"""Uses the gradient of the network with respect to a target class to
create an attribution map.
"""
def __init__(self, model, input_img, target_cla... | StarcoderdataPython |
1983276 | <reponame>timcera/tsgettoolbox<filename>src/tsgettoolbox/ulmo/usgs/nwis/__init__.py
# -*- coding: utf-8 -*-
"""
`USGS National Water Information System`_ web services
.. _USGS National Water Information System: http://waterdata.usgs.gov/nwis
"""
from __future__ import absolute_import
from tsgettoolbox.ulmo i... | StarcoderdataPython |
3425620 | """
Base class for Infinite Gaussian mixture model (IGMM)
Date: 2017
"""
from numpy.linalg import cholesky, det, inv, slogdet
from scipy.misc import logsumexp
from scipy.special import gammaln
import logging
import math
import numpy as np
import time
from scipy import stats
import copy
import matplotlib.pyplot as plt... | StarcoderdataPython |
6638170 | import dwavebinarycsp
from dwave.system.samplers import DWaveSampler
from dwave.system.composites import EmbeddingComposite
sampler = EmbeddingComposite(DWaveSampler())
def scheduling(time, location, length, mandatory):
if time:
return (location and mandatory)
else:
return ((not location) and ... | StarcoderdataPython |
11296446 | <filename>djangocms_blog/fields.py
# -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
from django.utils.text import slugify as django_slugify
__all__ = ['slugify']
def slugify(base):
return django_slugify(base, allow_unicode=True)
| StarcoderdataPython |
8107092 | from newt import (
Queue
)
def test_basic():
queue = Queue(2)
async_queue = queue.async_queue
sync_queue = queue.sync_queue
assert async_queue.maxsize == 2
assert async_queue.empty()
assert sync_queue.maxsize == 2
assert sync_queue.empty()
# @pytest.mark.asyncio
# async def test_c... | StarcoderdataPython |
1759242 | <gh_stars>1-10
##################################################
# Import Own Assets
##################################################
from hyperparameter_hunter.library_helpers.keras_optimization_helper import (
clean_parenthesized_string,
consolidate_layers,
find_space_fragments,
merge_compile_param... | StarcoderdataPython |
3497263 | <reponame>Tanc009/jdcloud-sdk-python
# coding=utf8
# Copyright 2018 JDCLOUD.COM
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless ... | StarcoderdataPython |
6581851 | <reponame>tomhodgins/xpath-helpers
## LISP-style XPath Helpers
## Nodes
def rootNode(continuation=''):
return '/' + continuation
def anyNode(continuation=''):
return '//' + continuation
def currentNode(continuation=''):
return '/.' + continuation
def parentNode(continuation=''):
return '/..' + continuation
... | StarcoderdataPython |
11235168 | <reponame>Diffeomorphic/import-daz
import cv2
import os
import argparse
def main():
parser = argparse.ArgumentParser(description="")
parser.add_argument("file", type=str, help="Name of input file.")
parser.add_argument("steps", type=int, help="Number of steps")
parser.add_argument("--overwrite"... | StarcoderdataPython |
1989055 | <reponame>sweetpalma/clrs
#!/usr/bin/env python3
# Part of CLRS solutions by SweetPalma, 2019. See LICENSE for details.
import unittest
import math
# Solution:
def modified_merge_sort(arr, p, r):
inversions = 0
if p < r:
q = math.floor((p + r) / 2)
inversions = inversions + modified_merge_sort... | StarcoderdataPython |
5034765 | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
from typing import Sequence, Union
import torch
import torch.nn as nn
from .grad_sample_module import GradSampleModule
def register_grad_sampler(target_class_or_classes: Union[type, Sequence[type]]):
"""
Registers... | StarcoderdataPython |
6694459 | <gh_stars>10-100
from typing import Dict
import numpy as np
from actor.correspondence_actor import CorrespondenceActor
from shape.point_2d import Point2D
from shape.polyline_2d import Polyline2D
from shape.shape import Shape
class Correspondence(object):
def __init__(self, shape: Shape = None,
... | StarcoderdataPython |
3538181 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# This import is for general library
import os
import threading
# This import is for ROS integration
import rospy
from sensor_msgs.msg import Image,CameraInfo
from std_msgs.msg import String
from cv_bridge import CvBridge, CvBridgeError
import numpy as np
from darknet_ros... | StarcoderdataPython |
12858971 | '''**********************************************
CODE TO IMPLEMENT FISHER'S LDA -
Given two dimensional dataset with two classes 0 and 1,
Perform Fisher's LDA on the dataset,
Perform dimensionality reduction and find the suitable vector to project it onto,
Find the threshold value for separation of the two classes
**... | StarcoderdataPython |
3567049 | import copy
import time
from time import sleep
import math3d as m3d
import urx
from math import pi
import numpy as np
# from GTac_Data import gtac_data
import GTac_Data
def safty_check(robot, goal_tool, x_lim, y_lim, z_lim):
# units: meter
goal_tool_transform = m3d.Transform(goal_tool)
# print('To execute ... | StarcoderdataPython |
5088938 | <reponame>alvesmatheus/reconhecimento-temas-comissoes
import pandas as pd
PATH_TRANSCRICOES = './data/2009-2018/00-transcricoes.csv'
PATH_METADADOS = './data/2009-2018/01-metadados.csv'
transcricoes = pd.read_csv(PATH_TRANSCRICOES)
metadados = transcricoes.filter(items=['id_evento', 'comissao', 'ano', 'data',
... | StarcoderdataPython |
9760798 | MAX_ITERATIONS = 15
TOLERANCE = 0.001
# https://en.wikipedia.org/wiki/B%C3%A9zier_curve
# P0(0, 0), P1(x1, y1), P2(x2, y2), P3(1, 1)
# B(t) = ((1-t)^3)*P0 + (3t(1-t)^2)*P1 + (3t^2(1-t))*P2 + t^3*P3
# = (3t(1-t)^2)*P1 + (3t^2(1-t))*P2 + t^3
# Returns f(t) or z(t) by given value x1, x2 or y1, ... | StarcoderdataPython |
3329547 | # -*- coding: utf-8 -*-
from openerp import models,fields,api,tools,SUPERUSER_ID
from openerp.tools.translate import _
import time
from datetime import datetime
from openerp.osv import osv
import xmlrpclib
class is_type_equipement(models.Model):
_name='is.type.equipement'
_order='name'
name = fields.Char... | StarcoderdataPython |
3557654 | <reponame>williambrode/google-resumable-media-python
# Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless... | StarcoderdataPython |
1933867 | <reponame>LaudateCorpus1/python-logging
# Copyright 2021 Google LLC All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
#... | StarcoderdataPython |
5079368 | <filename>python/Itertools/compress-the-string.py<gh_stars>0
# https://www.hackerrank.com/challenges/compress-the-string/problem
from itertools import groupby
for k, g in groupby(input()):
print(f"({len(list(g))}, {k})", end=" ")
| StarcoderdataPython |
9620594 | from collections import defaultdict
from biicode.common.find.finder_request import FinderRequest
from biicode.common.model.resource import Resource
from biicode.common.edition.block_holder import BlockHolder
from biicode.common.model.symbolic.reference import ReferencedDependencies
from biicode.common.model.symbolic.bl... | StarcoderdataPython |
75084 | <gh_stars>10-100
# iterating_over_cells_in_rows.py
from openpyxl import load_workbook
def iterating_over_values(path, sheet_name):
workbook = load_workbook(filename=path)
if sheet_name not in workbook.sheetnames:
print(f"'{sheet_name}' not found. Quitting.")
return
sheet = workbook[sheet... | StarcoderdataPython |
9748050 | <reponame>ramnes/sftpgo-client
from typing import Any, Dict, List, Type, TypeVar, Union
import attr
from ..types import UNSET, Unset
T = TypeVar("T", bound="FTPPassivePortRange")
@attr.s(auto_attribs=True)
class FTPPassivePortRange:
""" """
start: Union[Unset, int] = UNSET
end: Union[Unset, int] = UNS... | StarcoderdataPython |
3501305 | <reponame>songanz/RL_for_AV
import importlib
import matplotlib as mpl
import matplotlib.cm as cm
import numpy as np
class ValueIterationGraphics(object):
"""
Graphical visualization of the Value Iteration value function.
"""
BLACK = (0, 0, 0)
RED = (255, 0, 0)
highway_module = None
@... | StarcoderdataPython |
4813166 | #!/usr/bin/env python 3
# -*- coding: utf-8 -*-
#
# Copyright (c) 2021 PanXu, Inc. All Rights Reserved
#
"""
测试 gaz vocabulary collate
Authors: PanXu
Date: 2021/02/02 10:11:00
"""
import os
import logging
from easytext.data.pretrained_word_embedding_loader import GeneralPretrainedWordEmbeddingLoader
from easytex... | StarcoderdataPython |
3202310 | """
@brief PyTorch training code.
@author <NAME> (<EMAIL>)
@date July 2021
"""
import argparse
from decimal import Decimal
import json
from tqdm import tqdm
import numpy as np
import torch
from torch.optim import Adam
import torchnet as tnt
from src.network_architectures.custom_3dunet.unet import UNet3D
from src.e... | StarcoderdataPython |
1891574 | # MIT License
# Copyright (c) 2020 <NAME>, <NAME>, <NAME>, <NAME>, <NAME>
"""
Utility functions for training one epoch
and evaluating one epoch
"""
import torch
import random as rd
import torch.nn as nn
import math
from .metrics import accuracy_MNIST_CIFAR as accuracy
def train_epoch(model, optimizer, devi... | StarcoderdataPython |
3328577 | import calendar
import datetime
import os
import shutil
import subprocess
import time
import webbrowser
import csv
from functools import wraps
from string import digits
import arcpy
from sqlalchemy import exc, func, distinct, extract
import amaptor
import geodatabase_tempfile
import launchR
from arcproject.scripts i... | StarcoderdataPython |
29716 | <reponame>ruslanlvivsky/python-algorithm<filename>swexpert/d3/sw_2817_1.py<gh_stars>1-10
test_cases = int(input().strip())
def sum_sub_nums(idx, value):
global result
if value == K:
result += 1
return
if value > K or idx >= N:
return
sum_sub_nums(idx + 1, value)
sum_sub_nu... | StarcoderdataPython |
6410749 | <reponame>mozjay0619/scikit-optimize-adapter<filename>setup.py
from setuptools import setup, find_packages
import adapter
VERSION = adapter.__version__
with open("README.rst", "r") as fh:
long_description = fh.read()
setup(
name="scikit-optimize-adapter",
version=VERSION,
author="<NAME>",
description="Das... | StarcoderdataPython |
1727000 | <reponame>hologerry/mmflow
# optimizer
optimizer = dict(type='Adam', lr=5e-5, weight_decay=0.0004, betas=(0.9, 0.999))
optimizer_config = dict(grad_clip=None)
# learning policy
lr_config = dict(
policy='MultiStage',
by_epoch=False,
gammas=[0.5, 0.5, 0.5, 0.5, 0.5],
milestone_lrs=[5e-5, 3e-5, 2e-5, 1e-5,... | StarcoderdataPython |
1796976 | """
TLE
dp[i][k] := min of the largest sum among k subarrays from nums[:i]
"""
class Solution(object):
def splitArray(self, nums, K):
N = len(nums)
dp = [[float('inf') for _ in xrange(K+1)] for _ in xrange(N+1)]
dp[0][0] = 0
for i in xrange(1, N+1):
for ... | StarcoderdataPython |
3508969 | import unittest
from bandwidth.voice.bxml import Response
from lxml.builder import E
class ResponseTests(unittest.TestCase):
def test_to_xml(self):
"""
to_xml() should build XML
"""
estimated_xml = b'<xml><Response><Hangup/></Response></xml>'
xml = Response(E.Hangup())
... | StarcoderdataPython |
298399 | """Techniques for inference.
Description
-----------
Inference is same as asking conditional probability questions to the models.
"""
# ------------------------------------
# Name : inference.py
# Author : E.Taskesen
# Contact : <EMAIL>
# Licence : See licences
# -----------------------------------... | StarcoderdataPython |
386213 | <filename>saltlint/rules/SLSFileNameRule.py
# -*- coding: utf-8 -*-
# opyright (c) 2020 Warpnet B.V.
import os
from saltlint.linter.rule import Rule
from saltlint.utils import LANGUAGE_SLS
class SLSFileNameRule(Rule):
id = '214'
shortdesc = ('SLS file with a period in the name (besides the suffix period) can... | StarcoderdataPython |
152044 | <reponame>SebaDro/st-deep-hydro
import logging
import os
import xarray as xr
from typing import Union
from libs import processing
logger = logging.getLogger(__name__)
def nse_metric(observations: xr.DataArray, predictions: xr.DataArray, as_dataset: bool = False, basin: str = None)\
-> Union[float, xr.Datas... | StarcoderdataPython |
4916044 | from typing import List, Optional, Tuple
import pandas as pd # type: ignore
from pydantic import BaseModel
def drop_na_inputs(*, input_data: pd.DataFrame) -> pd.DataFrame:
"""Check model inputs for na values and filter."""
validated_data = input_data.copy()
validated_data.dropna(inplace=True)
retur... | StarcoderdataPython |
6606153 | import os
from collections import OrderedDict
import igibson
from igibson.utils.constants import MAX_CLASS_COUNT, SemanticClass
# To maintain backward compatibility, the starting class id should be SemanticClass.SCENE_OBJS + 1
def get_class_name_to_class_id(starting_class_id=SemanticClass.SCENE_OBJS + 1):
"""
... | StarcoderdataPython |
9619308 | class Token:
def __init__(self, question, multiline, start, end):
self.multiline = multiline
self.question = question
self.start = start
self.end = end
super().__init__()
def __str__(self):
return '(Q:{0:} ,M:{1:} ,Start: {2:} ,End: {3:} )'.format(self.question, ... | StarcoderdataPython |
232246 | <gh_stars>1-10
"""
Convert an OpenAI gym environment into a Spikey game.
Examples
--------
.. code-block:: python
from gym.envs.classic_control import cartpole
cartpole_env = gym_wrapper(cartpole.CartPoleEnv)
kwargs = {
"param1": 0,
}
game = cartpole_env(**kwargs)
game.seed(0)
s... | StarcoderdataPython |
3403383 | import click
from FC2 import utils
from FC2 import aircraft
from FC2 import airport
from FC2 import country
from FC2 import currency
from FC2 import itenerary
from FC2 import price
from FC2 import routing
import time
import networkx as nx
import pandas as pd
import os,FC2
@click.command()
@click.argument("file", type=c... | StarcoderdataPython |
9720851 | import torch
import numpy as np
import argparse
import pandas as pd
import sys
import os
from torch import nn
from torch.nn import functional as F
import tqdm
import pprint
from src import utils as ut
import torchvision
from haven import haven_utils as hu
from haven import haven_chk as hc
from src import datasets, mode... | StarcoderdataPython |
6547470 | import pandas as pd
from pandas import DataFrame
from sklearn import linear_model
import statsmodels.api as sm
data = pd.read_csv('train_data/simple.csv')
df = DataFrame(data, columns=['p', 'prev_price', 't', 'x1', 'x2'])
X = df[['x1', 'x2']]
Y = df['']
print(df) | StarcoderdataPython |
3357055 | <gh_stars>1-10
"""Miscellaneous IO related functions.."""
def dag_to_str(dag):
return "|".join(
[
str(f[0])
if len(f) == 1
else " ".join([str(f[0]), *[str(v) for v in sorted(f[1])]])
for f in dag
]
)
def str_to_dag(dag_str):
def parse_famil... | StarcoderdataPython |
3339504 | import sqlalchemy
import sqlalchemy.orm
from LanguageDeck.models import associations as assoc
from LanguageDeck.models import Base, decks
import datetime
# LanguageB_Example: sentences featuring language B.
# Contains the following relationships
# * many-to-many: LanguageB_Vocab
# * many-to-many: LanguageA_Ex... | StarcoderdataPython |
351284 | <gh_stars>0
# coding=utf-8
import os
import shutil
import sys
import time
import math
import cv2
import numpy as np
import tensorflow as tf
import pyarabic.araby as araby
import string
from keras.callbacks import ModelCheckpoint
from keras.utils import to_categorical
import keras.backend as K
from keras.models import l... | StarcoderdataPython |
1773119 | <gh_stars>0
import logging
from pathvalidate import sanitize_filename
from pathlib import Path
from .utils import validate_url, write_details
from .utils import download as download_file
from .errors import InvalidURL
from .fetcher import *
from .manga import Manga
from .chapter import Chapter
from .downloader import C... | StarcoderdataPython |
3566013 | <gh_stars>0
print('\033[31m=-=\033[m' * 19)
print('\033[31mTABUADA DE QUALQUER VALOR [Valores negativos finalizam]\033[m')
print('\033[31m=-=\033[m' * 19)
c = 0
n = int(input('Deseja a tabuada de qual valor? '))
print('===' * 10)
while True:
if n < 0:
break
c = c + 1
operacao = n * c
print(f'{n}... | StarcoderdataPython |
3407567 | # Copyright 2017-present Open Networking Foundation
#
# 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 agr... | StarcoderdataPython |
4878955 | #!/usr/bin/env python3
################################################################################
# Copyright (c) 2020, Arm Limited
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of sourc... | StarcoderdataPython |
6606076 | <reponame>tolsac/gae-rest-framework
"""
Custom responses
"""
import six
import collections
import webob
import json
from restae.conf import settings
class CorsResponse(webob.Response):
def __init__(self, *args, **kwargs):
super(CorsResponse, self).__init__(*args, **kwargs)
self.headers['Access-C... | StarcoderdataPython |
5153416 | <filename>GearBot/Util/DashConfig.py
import asyncio
from pytz import UnknownTimeZoneError, timezone
from Util import GearbotLogging, Utils, Translator, Configuration, Permissioncheckers
from database.DatabaseConnector import Infraction
BOT = None
def initialize(bot_in):
global BOT
BOT = bot_in
class Vali... | StarcoderdataPython |
9638964 | <reponame>IronVenom/encdecpy
tabula_recta = []
alphabets = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
for i in range(26):
temp = ['']*26
shiftedalphabets = alphabets[i:] + alphabets[:i]
for j in range(26):
temp[j] = shiftedalphabets[j]
tabula_recta.append(temp)
def strip(string):
string = ''.join(string... | StarcoderdataPython |
4986394 | <reponame>OSpoon/flask-server
#!/usr/bin/env python
# encoding: utf-8
'''
@author: Spoon
@contact: <EMAIL>
@file: __init__.py.py
@time: 2019/11/25 15:57
@desc:
'''
from flask import Flask
from app.resource import ShortUrl, Working
from app.security import security
from app.config import config
from app.utils import er... | StarcoderdataPython |
188614 | """
Cyborg SPDK driver modules implementation.
"""
import socket
from cyborg.accelerator.common import exception
from cyborg.accelerator.drivers.modules import generic
from oslo_log import log as logging
from oslo_config import cfg
from oslo_concurrency import processutils as putils
from cyborg.common.i18n i... | StarcoderdataPython |
5103955 | #!/usr/bin/python
# -*- coding: utf-8 -*-
import socket, sys
# BlockingIOError: [Errno 11] Resource temporarily unavailable
# python3 tcpConnection_test03.py 10000000 100
# 如果第一次write没有能够发送完数据,第二次调用write几乎肯定返回EAGAIN
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('172.16.31.10', 8888)) # 最好连接... | StarcoderdataPython |
4800150 | <gh_stars>0
import os
import json
import numpy as np
from naming_conventions import languages, languages_readable
from uriel import Similarities
import uriel
import copy
import pickle
from collections import defaultdict
import matplotlib.pyplot as plt
from scipy import stats
from matplotlib import colors
import seab... | StarcoderdataPython |
1617226 | <reponame>aceofwings/Cantactular<gh_stars>1-10
from lib import pelt
from changepy.costs import normal_mean, normal_var, normal_meanvar
import numpy as np
size = 100
mean_a = 5.0
mean_b = 10.0
var = 0.1
data_a = np.random.normal(mean_a, var, size)
data_b = np.random.normal(mean_b, var, size)
data = np.append(data_a, d... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.