id stringlengths 2 8 | text stringlengths 16 264k | dataset_id stringclasses 1
value |
|---|---|---|
9775994 | import final_server as fs
import pytest
def test_circlePixelID():
circleData = [5, 5, 1]
pixelLocations = fs.circlePixelID(circleData)
exp_pixelLocations = [[4, 5],
[5, 4], [5, 5], [5, 6],
[6, 5]]
assert pixelLocations == exp_pixelLocations
circ... | StarcoderdataPython |
9607564 | <gh_stars>1-10
class TermColors:
GREEN = '\033[32m'
RED = '\033[31m'
YELLOW = '\033[33m'
ENDC = '\033[0m'
| StarcoderdataPython |
6620559 | <reponame>myutman/contracode<filename>scripts/hf_create_train_test.py
from pathlib import Path
import numpy as np
import pandas as pd
import pickle
import gzip
from tqdm.auto import tqdm
DATA_PICKLE_PATH = Path("data/codesearchnet_javascript/javascript_augmented.pickle.gz")
CACHE_PATH = Path("data/hf_data/augmented_p... | StarcoderdataPython |
5128858 | <gh_stars>0
#!/usr/bin/env python
""" Tool for gathering statistics on progress of download. """
import argparse
import datetime
import os
import pathlib
import re
import time
import utils.solo_models
import utils.team_models
def monitor(module, args):
profile_pattern = re.compile(r'matches_for_([0-9]+)\.csv$')
... | StarcoderdataPython |
4996110 | import json
import boto3
import os
# env variables
BUILDER_INSTANCE_PROFILE_ARN = os.environ['BUILDER_INSTANCE_PROFILE_ARN']
print('Loading function')
ec2 = boto3.client('ec2')
ssm = boto3.client('ssm')
COMMAND_START = 'start'
COMMAND_STOP = 'stop'
COMMAND_STATUS_EC2 = 'status_ec2'
COMMAND_STATUS_SSM = 'status_ssm'
... | StarcoderdataPython |
266323 | from abc import ABC, abstractmethod
from typing import List, Tuple, Optional, Type
from functools import partial
import pkgutil
from io import BytesIO
import numpy as np
import torch
import pytorch_lightning as pl
from spacy.language import Language
from torch.utils.data import DataLoader, Dataset
from kogito.core.he... | StarcoderdataPython |
3238174 | #!/usr/bin/env python3
"""
Copyright (c) 2019 LINKIT, The Netherlands. All Rights Reserved.
Author(s): <NAME>
This software may be modified and distributed under the terms of the
MIT license. See the LICENSE file for details.
"""
import os
import sys
import argparse
from .main.make_backend import BackendAWS
from .ma... | StarcoderdataPython |
1993377 | # import galry.plot as plt
from galry import *
import numpy as np
# fig = figure()
X = np.random.randn(2, 1000)
# fig.imshow(np.random.rand(10, 10, 4), is_static=True)
plot(X, color=['r', 'y'])
text("Hello world!", coordinates=(.0, .9), is_static=True)
def callback(figure, parameters):
print figure, parameters... | StarcoderdataPython |
5110347 | <filename>hmm2ancestral.py
'''
Created on Oct 20, 2015
@author: bardya
'''
import os
import argparse
import re
import sys
from Bio.SeqUtils import GC
def parse_args():
parser = argparse.ArgumentParser(description='Get the ancestral consensus sequence from a hmm file')
parser.add_argument('-i', dest='infi... | StarcoderdataPython |
1826463 | from typing import Union
from .base import DependencyBase, dataclass
@dataclass
class Id(DependencyBase):
""" Dependency on an id of some object
Usage:
when the cached data includes an object, use its id to declare a dependency
Example:
cache.put(
'articles-list',
... | StarcoderdataPython |
9664837 | '''#!/usr/bin/env python'''
# python imports
import requests
import datetime
# native imports
from bs4 import BeautifulSoup
# native module imports
from lib.citation import Citation
from lib.datafinder import Datafinder
"""
Scrapes a news article for its article files based on the stipulations in
Datafinder, format... | StarcoderdataPython |
3236904 | import k3d
import numpy as np
import pytest
from .plot_compare import *
from k3d.helpers import download
import vtk
from vtk.util import numpy_support
vertices = [
-10, 0, -1,
10, 0, -1,
10, 0, 1,
-10, 0, 1,
]
indices = [
0, 1, 3,
1, 2, 3
]
def test_mesh():
global vertices, indices
... | StarcoderdataPython |
8146006 | <reponame>KelvinHong/landmark-tool
from tkinter.tix import WINDOW
from urllib.parse import _NetlocResultMixinBytes
from utils import *
from PIL import Image
import io
import os
import pandas as pd
import numpy as np
import json
import screeninfo
# Detect double monitor
# monitors = screeninfo.get_monitors()
# if len(mo... | StarcoderdataPython |
8055612 | from kubernetes import client, config
from flask import Flask, request, abort
from logging.config import dictConfig
dictConfig({
'version': 1,
'formatters': {'default': {
'format': '[%(asctime)s] %(levelname)s in %(module)s: %(message)s',
}},
'handlers': {'wsgi': {
'class': 'logging.Str... | StarcoderdataPython |
3403378 | import seaborn as sns
from pudzu.charts import *
from pudzu.sandbox.bamboo import *
countries = pd.read_csv("datasets/countries.csv")[["country", "continent", "flag"]].split_columns('country', "|").explode('country').set_index('country')
df = pd.read_csv("datasets/nobels.csv")
df = df[df['category'] == "Litera... | StarcoderdataPython |
1958307 | <filename>IOPool/Output/test/PoolOutputTest_cfg.py
import FWCore.ParameterSet.Config as cms
import argparse
import sys
parser = argparse.ArgumentParser(prog=sys.argv[0], description="Test PoolOutputModule")
parser.add_argument("--firstLumi", type=int, default=None, help="Set first lumi to process ")
argv = sys.argv[:... | StarcoderdataPython |
8139064 | <reponame>European-XFEL/euxfel-python
"""AGIPD & LPD geometry handling."""
from cfelpyutils.crystfel_utils import load_crystfel_geometry
from copy import copy
import h5py
from itertools import product
import numpy as np
from scipy.ndimage import affine_transform
import warnings
from .crystfel_fmt import write_crystfel... | StarcoderdataPython |
9753884 | # pylint: disable=arguments-differ,unused-argument
from typing import Generic, List, TypeVar
from datafiles import Missing, converters, datafile
from datafiles.utils import dedent
from . import xfail_on_latest
@xfail_on_latest
def test_generic_converters(expect):
S = TypeVar("S")
T = TypeVar("T")
clas... | StarcoderdataPython |
8193908 | from __future__ import (absolute_import, division, print_function,
unicode_literals)
import argparse
import os
import random
import sys
from collections import defaultdict
from multiprocessing import Pool
import time
from threading import Timer
# import matplotlib.pyplot as plt
# import networkx... | StarcoderdataPython |
9633968 | <filename>sandbox/pages/forms.py
from django import forms
from clientaddress.models import *
from bibliothek.Widgets import *
class Widerrufform(forms.ModelForm):
class Meta:
model = Clientaddress
exclude = ["id","trash","is_deleteable","is_editable","create_date","modified_date","create_user","... | StarcoderdataPython |
385268 | <gh_stars>1000+
# Copyright 2020 Makani Technologies 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable ... | StarcoderdataPython |
8148148 | text = "X-DSPAM-Confidence: 0.8475";
num = text.find('0')
get = text[23:]
Get = print(float(get))
| StarcoderdataPython |
1617187 | from django.db import models
class Award(models.Model):
name=models.CharField(max_length=300)
description=models.TextField(max_length=5000)
developer=models.CharField(max_length=300)
created_date=models.DateField()
averangeRating=models.FloatField(default=0)
image=models.URLField(default=... | StarcoderdataPython |
12838651 | <gh_stars>1-10
from nltk.tokenize import word_tokenize
from nltk import pos_tag
from nltk.tokenize import PunktSentenceTokenizer
from nltk.corpus import state_union
from nltk import RegexpParser
train_text = state_union.raw("2005-GWBush.txt")
sample_text = state_union.raw("2006-GWBush.txt")
custom_sent_token... | StarcoderdataPython |
338837 | <gh_stars>0
import csv
from _common import create_mobile_library_file
DATA_SOURCE = '../raw/birmingham.csv'
def run():
timetable = 'https://www.birmingham.gov.uk/info/50163/library_services/1479/mobile_library_service/3'
mobiles = []
with open(DATA_SOURCE, 'r') as raw:
reader = csv.reader(raw, ... | StarcoderdataPython |
1627827 | <reponame>AndyVirginia/-<filename>generator.py
from fractions import Fraction
import random
class Ari_Expression():
'''算术表达式的生成'''
def __init__(self, max_num):
self.init_operators()
self.init_nums(max_num)
self.init_expression()
def init_num(self, max_num):
'''随机生成数'''
... | StarcoderdataPython |
9792498 | import numpy as np
import pylab as plt
from scipy.special import erf
from scipy.integrate import simps
from scipy.linalg import cho_solve
#from ChoSolver import choSolve, choBackSubstitution
def styblinsky(x):
return (x[0]**4 - 16*x[0]**2 + 5*x[0] + x[1]**4 - 16*x[1]**2 + 5*x[1])/2.
def rosenbrock(x):
... | StarcoderdataPython |
1787455 | <reponame>JohnZhang000/adaptive-jpeg-compression
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jul 3 14:51:04 2021
@author: ubuntu204
"""
import os
import numpy as np
from six.moves import cPickle as pickle
# from scipy.misc import imread
import platform
from PIL import Image
def load_pickle(f):... | StarcoderdataPython |
3446645 | <reponame>matslindh/pytest-image-diff
from typing import BinaryIO, Union, Tuple, Optional
from PIL.Image import Image
from typing_extensions import Literal, Protocol
PathOrFileType = Union[str, bytes, BinaryIO]
ImageFileType = Union[Image, PathOrFileType]
ImageSize = Tuple[int, int]
class ImageRegressionCallableTyp... | StarcoderdataPython |
1795394 | <reponame>enthought/etsproxy
# proxy module
from __future__ import absolute_import
from apptools.naming.pyfs_state_factory import *
| StarcoderdataPython |
3539138 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
filament_watch.py
Cancel the print on OctoPrint if the filament is not feeding (e.g. due to
jam, out of filament, etc.)
"""
##############################################################################
#
# The MIT License (MIT)
#
# Copyright (c) 2015 <NAME> <<EMAIL>... | StarcoderdataPython |
6625132 | '''
<table class="ee-notebook-buttons" align="left">
<td><a target="_blank" href="https://github.com/giswqs/earthengine-py-notebooks/tree/master/Algorithms/CloudMasking/modis_surface_reflectance_qa_band.ipynb"><img width=32px src="https://www.tensorflow.org/images/GitHub-Mark-32px.png" /> View source on GitHub</a>... | StarcoderdataPython |
395667 | <reponame>rabernat/scikit-downscale
import numpy as np
from scipy.spatial import cKDTree
from sklearn.base import RegressorMixin
from sklearn.linear_model import LinearRegression
from sklearn.linear_model.base import LinearModel
from sklearn.utils.validation import check_is_fitted
from .utils import ensure_samples_fea... | StarcoderdataPython |
8088785 | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.modules.loss import _Loss
from torch_geometric.utils import remove_self_loops, add_self_loops, softmax
from tqdm import tqdm, trange
from scipy import sparse
class ClassBoundaryLoss(_Loss):
__constants__ = ['reduc... | StarcoderdataPython |
11233809 | <filename>observations/r/intqrt.py
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import csv
import numpy as np
import os
import sys
from observations.util import maybe_download_and_extract
def intqrt(path):
"""intqrt
Data lo... | StarcoderdataPython |
223107 | <reponame>gluesolutions/glue-vispy-viewers
import numpy as np
from vispy.visuals.transforms import (ChainTransform, NullTransform,
MatrixTransform, STTransform)
from vispy.visuals.transforms.base_transform import InverseTransform
from vispy.visuals.transforms._util import arg_to_v... | StarcoderdataPython |
12801431 | import os
import cv2
import torch
from torch.utils.data import Dataset
class ChestHeartDataset(Dataset):
def __init__(self, img_ids, data_dir, transform=None):
self.img_ids = img_ids
self.transform = transform
self.img_dir = os.path.join(data_dir, 'images')
self.mask_dir = os.pat... | StarcoderdataPython |
6549791 | <reponame>moslog/exam-app
from datetime import datetime
def resolve_date(date: datetime) -> str:
months = [
'Januari',
'Februari',
'Maret',
'April',
'Mei',
'Juni',
'Juli',
'Agustus',
'September',
'Oktober',
'November',
... | StarcoderdataPython |
1740151 | <filename>Labs/fixbold.py
#! /usr/bin/env python3
# fix the **bold** tags in html pre sections
import sys
from tempfile import mkstemp
import os
filename = sys.argv[1]
inf = open(filename, "r")
fd, tfile = mkstemp('','tmp','.',True)
outf = open(tfile, "w")
INPRE = False
for line in inf:
if line[:5] == "<pre>":
... | StarcoderdataPython |
363369 | from agrirouter.constants.media_types import ContentTypes
class SoftwareOnboardingHeader:
def __init__(self,
reg_code,
application_id,
signature=None,
content_type=ContentTypes.APPLICATION_JSON.value
):
self._set_params(... | StarcoderdataPython |
8073496 | # SPDX-FileCopyrightText: 2021 <NAME>
# Modified by <NAME> 2021 all the keys bar the modifier key
# can now be used as layer select and input keys
# prints debug messages via debug serial port (USB)
# sudo cat /dev/ttyACM0
# SPDX-License-Identifier: MIT
# An advanced example of how to set up a HID keyboard.
# There... | StarcoderdataPython |
12846218 | #!/usr/bin/env python
import rospy
from std_msgs.msg import Header
from geometry_msgs.msg import PoseStamped
from nav_msgs.msg import Odometry
from sensor_msgs.msg import Image
from cv_bridge import CvBridge, CvBridgeError
import cv2
import sys
import numpy as np
import message_filters
import tf
class DepthImageProc... | StarcoderdataPython |
1690904 | # $Id: __init__.py 7646 2013-04-17 14:17:37Z milde $
# Author: <NAME> <<EMAIL>>
# Copyright: This module has been placed in the public domain.
"""
This package contains Docutils parser modules.
"""
__docformat__ = 'reStructuredText'
import sys
from docutils import Component
if sys.version_info < (2,5):
from docu... | StarcoderdataPython |
4820622 | """Tests for application configuration."""
import pytest
from almanac import (
ConflictingPromoterTypesError,
current_app,
InvalidCallbackTypeError
)
from .utils import get_test_app
@pytest.mark.asyncio
async def test_prompt_str_customization():
app = get_test_app()
app.bag.counter = 0
@ap... | StarcoderdataPython |
9682569 | <gh_stars>0
# coding=utf-8
# flake8: noqa
from itertools import islice
from typing import List
from hypothesis import given
from hypothesis.strategies import integers
from oeis import recaman
@given(integers(min_value=2, max_value=100))
def test_recaman_greater_than_zero(n: int) -> None:
r: List[int] = list(isl... | StarcoderdataPython |
6589088 | import RPi.GPIO as GPIO
import time
import os
import commands
GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)
GPIO.setup(11, GPIO.OUT)
GPIO.output(11, 1)
time.sleep(0.5)
GPIO.output(11, 0)
time.sleep(0.5)
GPIO.output(11, 1)
time.sleep(0.5)
GPIO.output(11, 0)
time.sleep(0.5)
GPIO.output(11, 1)
time.sleep(0.5)
GPIO.o... | StarcoderdataPython |
9779886 | <gh_stars>0
import datetime
from json import loads, JSONDecodeError
import re
from .net.http import ApiRequester
from .models.response import Response
from .exceptions.error import ParameterError, EmptyApiKeyError, \
UnparsableApiResponseError
class Client:
__default_url = "https://domains-subdomains-discove... | StarcoderdataPython |
361068 | import configargparse
import generation
import utils
__VERSION__ = '0.4.0'
def main():
parser = configargparse.ArgParser(default_config_files=['config.ini'])
parser.add('--width', required=False, type=int, help='SVG width')
parser.add('--height', required=False, type=int, help='SVG height')
parser.a... | StarcoderdataPython |
5000756 | <filename>backend/exam/admin.py
from django.contrib import admin
from exam.models import (
Question,
QuestionGroup,
Exam,
Choice,
Topic,
QuestionChoice,
SelectedChoices
)
admin.site.register(Question)
admin.site.register(Exam)
admin.site.register(Choice)
admin.site.register(Topic)
admin.... | StarcoderdataPython |
1630541 | #!/user/bin/python
import time
import os
import logging
# http://www.pythonforbeginners.com/files/reading-and-writing-files-in-python
# https://www.andreas-jung.com/contents/a-python-decorator-for-measuring-the-execution-time-of-methods
def timeit(method):
def timed(*args, **kw):
ts = time.time()
... | StarcoderdataPython |
3443763 | #! /usr/bin/env python
# This file is part of the Astrometry.net suite.
# Licensed under a 3-clause BSD style license - see LICENSE
# Used to trim down the "hpslit"-merged USNO-B files before
# building indices out of them.
from __future__ import print_function
import sys
from optparse import OptionParser
try:
i... | StarcoderdataPython |
5168690 | from .Affine2DMat import Affine2DMat, Affine2DUniMat
from .math_ import (intersect_two_line, polygon_area, segment_length,
segment_to_vector)
from .nms import nms
| StarcoderdataPython |
261714 | <gh_stars>0
# Copyright 2020 The Magenta Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | StarcoderdataPython |
8042676 | """
The MIT License (MIT)
Copyright (c) 2015-present Rapptz
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merg... | StarcoderdataPython |
8026249 |
import re
from enum import Enum
from multiprocessing import Lock
from systemtools.duration import *
from systemtools.location import *
from systemtools.printer import *
from systemtools.logger import *
from systemtools.file import *
from systemtools.basics import * # stripAccents, reduceBlank
from datatools.htmltools... | StarcoderdataPython |
8095824 | <filename>train.py
import os
import sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from glob import glob
import cv2
import numpy as np
import tensorflow as tf
import cfgs
from cfgs import logger
from model.model import generator, discriminator
from model.ops import ... | StarcoderdataPython |
308617 | <filename>stores/aliexpress.py
import json
import re
from json.decoder import JSONDecodeError
from common import get_session, message, find_str
conf = {'aep_usuc_f': 'isfm=y&site=esp&c_tp=USD&isb=y®ion=CL&b_locale=es_ES'}
pat = re.compile(r'^(https://[a-z]{2,3}\.aliexpress\.com/item/[0-9]+\.html)')
name = 'Aliexpr... | StarcoderdataPython |
6519769 |
import unittest
from parameterized import parameterized as p
from solns.bubbleSort.bubbleSort import *
class UnitTest_BubbleSort(unittest.TestCase):
@p.expand([
[[4,5,1,8,10,11,0,7,9],[0,1,4,5,7,8,9,10,11]]
])
def test_naive(self,nums,expected):
self.assertEqual(Solution.naive(nums), expec... | StarcoderdataPython |
11349471 | from picosystem import *
import math
# A simple raycaster demo, heavily inspired by https://lodev.org/cgtutor/raycasting.html
# Copy to your Pico along with "gadgetoid-raycaster.16bpp" for full textured output
textured = False
try:
# Read the 16-bits per pixel ARGB4444 texture into a buffer
# The texture ma... | StarcoderdataPython |
8149662 | <gh_stars>0
# -*- coding: utf-8 -*-
# Grupo 11:
# 83597 <NAME>
# 84715 <NAME>
from search import Problem, Node, Graph, astar_search, breadth_first_tree_search, \
depth_first_tree_search, greedy_search
import sys
import copy
class RRState:
state_id = 0
def __init__(self, board):
self.board = board
self.id = RR... | StarcoderdataPython |
6429854 | <gh_stars>0
from mycroft import MycroftSkill, intent_file_handler, util
from .data import events
class Mathformula (MycroftSkill):
def __init__(self):
MycroftSkill.__init__(self)
@intent_file_handler('formula.intent')
def handle_formula(self, message):
self.speak_dialog("formula")
self.... | StarcoderdataPython |
3560668 | <reponame>Duckie-town-isu/tulip-control
# Copyright (c) 2013-2014 by California Institute of Technology
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must... | StarcoderdataPython |
9681784 | import redis
r = redis.Redis(password='<PASSWORD>')
# 任务信息:任务类别——发送者——接受者——内容
task = '%s_%s_%s_%s'%('sendMail','<EMAIL>','<EMAIL>','hello world')
# 添加任务
r.lpush('pylk1',task)
| StarcoderdataPython |
3246959 | import matplotlib.pyplot as plt
import numpy as np
#t = [i for i in range (-10,20)]
t=np.linspace(-10, 10, 20)
plt.figure()
plt.subplot(221)
y = t*(t<=10)
plt.plot(t,y,color='red',linewidth=4)
plt.grid()
plt.title('y1=x')
plt.subplot(222)
y = (t*2)*[t<=10]
plt.plot(t,y,color='blue',linewidth=4)
plt.grid()
... | StarcoderdataPython |
1928776 | import yaku.utils
def setup(ctx):
env = ctx.env
ctx.env["CC"] = ["clang"]
ctx.env["CC_TGT_F"] = ["-c", "-o"]
ctx.env["CC_SRC_F"] = []
ctx.env["CFLAGS"] = []
ctx.env["DEFINES"] = []
ctx.env["LINK"] = ["clang"]
ctx.env["LINKFLAGS"] = []
ctx.env["LINK_TGT_F"] = ["-o"]
ctx.env["LIN... | StarcoderdataPython |
4931945 | #!/usr/bin/python
# Copyright 2013 CereProc Ltd.
# 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
#
# THIS CODE IS PROVIDED *AS IS* BASIS, WITHO... | StarcoderdataPython |
4800907 | <reponame>stvstnfrd/openedx-webhooks
"""
Get information about people, repos, orgs, pull requests, etc.
"""
import datetime
import re
from typing import Dict, Iterable, Optional, Union
import yaml
from iso8601 import parse_date
from openedx_webhooks.lib.github.models import PrId
from openedx_webhooks.oauth import ge... | StarcoderdataPython |
328501 | import math
import torch
import torch.nn as nn
import torch.nn.functional as F
from models.residual_prediction_net import ResidualPredictionNet
torch.manual_seed(42)
class VGG(nn.Module):
'''
VGG model
'''
def __init__(self, classifier_type, lr=1e-3, device="cpu", hidden=200, output=10, groups=5, dept... | StarcoderdataPython |
4825216 | import pandas as pd
import argparse
import PyFloraBook.in_out.data_coordinator as dc
# ---------------- GLOBALS ----------------
WEBSITE = 'OregonFlora'
OUTPUT_SUFFIX = 'species'
# ---------------- INPUT ----------------
# Parse arguments
parser = argparse.ArgumentParser(
description='Count the observed specie... | StarcoderdataPython |
12859514 | from dataclasses import dataclass, field
from typing import List
from itertools import chain
@dataclass
class Word:
word: str
wordtype: str
shortdef: List[str] = field(default_factory=list)
synonyms: List[str] = field(default_factory=list)
antonyms: List[str] = field(default_factory=list)
stem... | StarcoderdataPython |
1911635 | # Copyright 2021 IBM Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wri... | StarcoderdataPython |
9712573 | <reponame>vitruvianscience/OpenDeep
"""
This module defines isotropic gaussian log-likelihood loss.
"""
# standard libraries
import logging
# third party libraries
from theano.tensor import (log as Tlog, sqrt)
from numpy import pi
# internal references
from opendeep.optimization.loss import Loss
log = logging.getLogge... | StarcoderdataPython |
3444519 | import tensorflow as tf
def createFullToken(voxel_shape, TOKEN):
return tf.fill(voxel_shape, TOKEN)
| StarcoderdataPython |
3511422 | from __future__ import absolute_import
from __future__ import unicode_literals
import six
from corehq.util.translation import localize
from custom.ilsgateway.tanzania.exceptions import InvalidProductCodeException
from custom.ilsgateway.tanzania.handlers.generic_stock_report_handler import GenericStockReportHandler
fr... | StarcoderdataPython |
1774224 | """
Ce script s'occupe de tout ce qui est lié au vocalisme.
"""
class VocalismeNonTonique:
def __init__(self):
return
def vocalisme_atone(object):
changements = ''
if ("I") in object:
changements = object.replace("I", "")
elif ("AU") in object:
... | StarcoderdataPython |
5084720 | # Copyright (c) 2010 <NAME>
from __future__ import absolute_import, with_statement, division
from twisted.trial import unittest
from .. import plugin
from . import plugins
def identity(*args, **kwargs):
return args, kwargs
class PluginTest(unittest.TestCase):
def testGetCheckerFactories(self):
... | StarcoderdataPython |
5112032 | <filename>Python/sparse-matrix-multiplication.py
# Time: O(m * n * l), A is m x n matrix, B is n x l matrix
# Space: O(m * l)
class Solution(object):
def multiply(self, A, B):
"""
:type A: List[List[int]]
:type B: List[List[int]]
:rtype: List[List[int]]
"""
m, n, l ... | StarcoderdataPython |
1961878 | <reponame>MatheusMullerGit/app_empresas<gh_stars>1-10
from django.db import models
from django.urls import reverse
from apps.empresas.models import Empresa
class Departamento(models.Model):
nome = models.CharField(max_length=70)
empresa = models.ForeignKey(Empresa, on_delete=models.PROTECT)
def get_abso... | StarcoderdataPython |
4887822 | from coalib.bearlib.abstractions.Linter import linter
from dependency_management.requirements.DistributionRequirement import (
DistributionRequirement)
@linter(executable='verilator',
output_format='regex',
use_stderr=True,
output_regex=r'\%(?:(?P<severity>Error|Warning.*?).*?):'
... | StarcoderdataPython |
3330784 | import io
import os
import unittest
import chess.pgn
from puzzlemaker.puzzle_finder import find_puzzle_candidates
from puzzlemaker.analysis import AnalysisEngine
def pgn_file_path(pgn_filename) -> io.TextIOWrapper:
cur_dir = os.path.dirname(os.path.abspath(__file__))
return open(os.path.join(cur_dir, '..', ... | StarcoderdataPython |
4802030 | """
Same as my_first_test.py, but without the asserts.
"""
from seleniumbase import BaseCase
class MyTestClass(BaseCase):
def test_basic(self):
self.open("https://store.xkcd.com/search")
self.type('input[name="q"]', "xkcd book\n")
self.open("https://xkcd.com/353/")
self.click('a[... | StarcoderdataPython |
3301299 | class Solution:
def canIWin(self, max_num: int, desiredTotal: int) -> bool:
if desiredTotal<= max_num: return True
if (max_num*(max_num+1)//2)< desiredTotal: return False
mem ={}
def dp(total, seen):
if total>=desiredTotal: return False... | StarcoderdataPython |
1913537 | <filename>unittests/test_Grapher.py<gh_stars>10-100
from dnnviewer.layers.Dense import Dense
from dnnviewer.Grapher import Grapher
import numpy as np
class TestGrapher:
def test_clear_layers(self):
grapher = Grapher()
assert len(grapher.layers) == 0
assert grapher.structure_props['num_... | StarcoderdataPython |
1842436 | <reponame>osoco/better-ways-of-thinking-about-software
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('email_marketing', '0004_emailmarketingconfiguration_welcome_email_send_delay'),
]
operations = [
migrations.AddField(
mode... | StarcoderdataPython |
4979198 | #!/usr/bin/env python3
import sys
def twos():
# 16406297185095647658 - 8579294738944438520
# 7827002446151209138
cval = 16406297185095647658
sval = 8579294738944438520
dval = cval - sval
sum1 = cval + sval
val1 = 1
last1 = val1
for i1 in range(68):
print("%s %s" % (str(i1),... | StarcoderdataPython |
8050354 | <reponame>LarmIg/Algoritmos-Python
# Calcular e apresentar o valor do volume de uma lata de óleo, utilizando a fórmula VOLUME <- 3.14159 *R^2 * ALTURA.
Alt = float(input('Informe a altura da lata: '))
R = float(input('informe o raio da lata: '))
volume = 3.14159 * R**2 * Alt
print('O volume da lata corresponde a:... | StarcoderdataPython |
3333191 | <reponame>stanford-futuredata/sketchstore<filename>python/storyboard/eval.py
from typing import List, Tuple, Sequence, Mapping
import itertools
import numpy as np
from pandas import DataFrame
from storyboard.planner import WorkloadProperties, FreqGroup
from tqdm import tqdm
class StoryboardQueryExecutor:
def __i... | StarcoderdataPython |
4981085 | <filename>docs/source/examples/bar.py
plot = Plot()
bar = Bar()
bar.xValues = range(5)
bar.yValues = [2, 8, 4, 6, 5]
plot.add(bar)
plot.xLabel = "Widget ID"
plot.yLabel = "# Widgets Sold"
plot.save("bar.png")
| StarcoderdataPython |
6456055 | <filename>CytoPy/flow/gating/density.py
from .utilities import kde, check_peak, find_local_minima
from .defaults import ChildPopulationCollection
from .base import Gate, GateError
from scipy.signal import find_peaks
import pandas as pd
import numpy as np
class DensityThreshold(Gate):
"""
Threshold gating esti... | StarcoderdataPython |
9699205 | <reponame>nitish771/pygorithm
'''
Author : <NAME> (nitish771)
25-06-21
'''
from inspect import getsource
def common_word(word1, word2):
result = ''
l1 = len(word1)
l2 = len(word2)
min_len = l1 if l1 < l2 else l2
for i in range(min_len):
if word1[i] != word2[i]:
break
r... | StarcoderdataPython |
5155612 | import numpy as np
'''
Functions to specify how y_ex (exemplar -> outcome associations) are updated.
from_rtrv: Learning rates for exemplars are equal to retrieval strength
times a constant (lrate_par).
from_rtrv_indv_delta: Learning rates for exemplars are equal to retrieval strength
times a constant (lrate... | StarcoderdataPython |
51739 | <filename>components/gbf.py
import ssl
import re
import json
import zlib
from urllib import request
from datetime import datetime, timedelta
# ----------------------------------------------------------------------------------------------------------------
# GBF Component
# ------------------------------------... | StarcoderdataPython |
8130351 | <reponame>domwillcode/home-assistant
"""The etherscan component."""
| StarcoderdataPython |
1898348 | #!/usr/bin/env python
"""Tests for `statdepth` package."""
import unittest
import pandas as pd
import numpy as np
from statdepth import *
from statdepth.testing import *
from statdepth.homogeneity import *
class TestStatdepth(unittest.TestCase):
"""Tests for `statdepth` package."""
def setUp(self):
... | StarcoderdataPython |
4840878 | from gi.repository import Gtk, Gio, Gdk, GObject, Pango
from asciiplayback import *
from asciimation import *
class GtkASCIIPlayer(Gtk.Box):
def __init__(self, player):
Gtk.Box.__init__(self, orientation=Gtk.Orientation.VERTICAL)
self.player = player
labelbox = Gtk.Box()
label = G... | StarcoderdataPython |
9752258 | from chispa import assert_df_equality
from cishouseholds.derive import assign_any_symptoms_around_visit
def test_assign_any_symptoms_around_visit(spark_session):
expected_df = spark_session.createDataFrame(
data=[
(1, "No", 1, "2020-07-20", "Yes"),
(2, "No", 1, "2020-07-20", "No")... | StarcoderdataPython |
180071 | from .ddr import *
from .ndt import *
from .nnb import *
from .rnn import *
from .wnd import *
from .fcnn import *
from .linear import *
from .tree_dnn import *
from .transformer import *
from .base import ModelBase
| StarcoderdataPython |
8190806 | <gh_stars>10-100
from zipfile import ZipFile
import requests
from tcrdist import paths
__all__ = ['download_and_extract_zip_file']
"""
python -c "from tcrdist.setup_tests import *; download_and_extract_zip_file('bulk.csv.zip')"
python -c "from tcrdist.setup_tests import *; download_and_extract_zip_file('dash.zip')"
p... | StarcoderdataPython |
3469143 | #!/usr/bin/env python3
'''
$ argument_group.py --help
> usage: argument_group.py --flag1 [--flag2] [-h] pos1 [pos2] [args [args ...]]
>
> positional arguments:
> args
>
> optional arguments:
> -h, --help show this help message and exit
>
> Group #1:
> First group.
>
> pos1 First positional argument
> ... | StarcoderdataPython |
6551070 | # Define a bazel macro that creates cc_test for re2.
def re2_test(name, deps=[]):
native.cc_test(
name=name,
srcs=["re2/testing/%s.cc" % (name)],
deps=[
":re2",
":test",
] + deps
)
| StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.