id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
11355706 | import re
from fractions import Fraction
import sys
''' Calculations for converting between metric and imperial units '''
def second_level_keys(d):
o = []
for v in d.values():
o = o + list(v.keys())
return o
def string_to_number(s):
try:
return float(s)
except:
try:
... | StarcoderdataPython |
1950889 | <filename>fileIO.py
import os
class Files :
def __init__(self):
pass
def openQuestion(self):
file= open("questions_words.txt", "r")
self.question = file.read()
self.question = self.question.split('\n')
self.questionWord = []
for questionIdx in range (1, len(self... | StarcoderdataPython |
186602 | <filename>papers/resources/original.py
import math
def _original(temp, prob):
if prob == 0 or prob == 0.5 or temp == 0:
return prob
if prob < 0.5:
return 1.0 - _original(temp, 1.0 - prob)
coldness = 100.0 - temp
a = math.sqrt(coldness)
c = (10 - a) / 100
f = (c + 1) * prob
r... | StarcoderdataPython |
4992595 | from chainer import cuda
from chainer import optimizer
class SGD(optimizer.Optimizer):
"""Vanilla Stochastic Gradient Descent."""
def __init__(self, lr=0.01):
self.lr = lr
def update_one_cpu(self, param, grad, _):
param -= self.lr * grad
def update_one_gpu(self, param, grad, _):
... | StarcoderdataPython |
8096423 | <gh_stars>0
import io
from itertools import tee
from zipfile import ZipFile, ZipInfo, _ZipWriteFile
from _io import _IOBase
from .exceptions import (InvalidUseOfStream, NotFileObject,
NotStreamingBytesTypeError, WrongFileLengthException)
class _ReadFromStreamingBytes:
"""
Class to t... | StarcoderdataPython |
11237461 | <reponame>PhantomPayne/jinjitsu
__author__ = 'thomas'
from jinja2 import nodes
from jinja2.ext import Extension
import inspect
class Property(object):
def __init__(self, type=None, template=None, css_classes="", label=None):
self.type = type
self.template = template
self.css_classes = css... | StarcoderdataPython |
88676 | <reponame>MarcusAndreasSvensson/sfepy
#!/usr/bin/env python
"""SfePy: Simple finite elements in Python
SfePy (simple finite elements in Python) is a software, distributed
under the BSD license, for solving systems of coupled partial
differential equations by the finite element method. The code is based
on NumPy and Sc... | StarcoderdataPython |
8180234 | <reponame>NicolasNin/purepython_flagser<filename>tests/__init__.py<gh_stars>0
"""Unit test package for purepython_flagser."""
| StarcoderdataPython |
8060831 | <gh_stars>1-10
# Copyright 2014 The Chromium OS Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Provide interfaces to initialize and read Whale color sensor."""
import ast
import logging
from cros.factory.test.fixture import bft_f... | StarcoderdataPython |
9747271 | <filename>app/tab_misclassification_v2.py
import dash
from dash import html
import base64
import os
from pprintpp import pprint
# from inference_clip import clip_inference
import pandas as pd
import random
import dash_html_components as html
import dash_bootstrap_components as dbc
import dash_table
import dash_core_com... | StarcoderdataPython |
3445815 | # Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
if head is None:
return head
dummy = ListNode(0)
dummy.next = head
... | StarcoderdataPython |
4827127 | # -*- coding: utf-8 -*-
"""vae.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/18pWjhMG_j2o1kj6gUFN4-WzU0SfvtGj_
# Stardard VAE
100 次训练生成图片,ELBO 约 -118
* reparameterize
计算 z=$\mu + \sigma \odot \varepsilon$
* log_normal_pdf
计算 log p(x|... | StarcoderdataPython |
5074365 | """Data generators for the WNGT19 Efficiency Shared Task"""
# https://github.com/tensorflow/tensor2tensor/blob/master/tensor2tensor/data_generators/translate_ende.py
# https://github.com/tensorflow/tensor2tensor/blob/4d96546af045b869e3a3f826a21b634e9631e43d/tensor2tensor/models/transformer.py#L1729
from __future__ im... | StarcoderdataPython |
6464196 | <filename>problems/score-after-flipping-matrix/solution.py
class Solution(object):
def matrixScore(self, matrix):
"""O(n^2) time and space | for nxn matrix"""
ln = len(matrix)
for r in range(ln):
if matrix[r][0] == 0:
reverse_rows(matrix, r)
col_matrix = ... | StarcoderdataPython |
8079568 | <reponame>Letty-Liang/buildroot<filename>build/android/pylib/utils/logging_utils.py
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import contextlib
import logging
@contextlib.contextmanager
def Suppress... | StarcoderdataPython |
1807495 | <reponame>maurendeviia/pythoncharmers
def checksum(cheknum, clen, odd_even):
for i in range(odd_even, clen, 2):
#test1=int(cheknum[i] * 2 /10)
cheknum[i] = int(cheknum[i] * 2 / 10) + (cheknum[i]*2 % 10)
return cheknum
while True:
cardnum = input("What is your card number?: ")
if(0 < l... | StarcoderdataPython |
4909961 | <filename>src/main/python/bayou/experiments/predictMethods/SearchDB/jaccard.py
from parallelReadJSON import parallelReadJSON
from searchFromDB import searchFromDB
from Embedding import Embedding_iterator_WBatch
from utils import rank_statistic, ListToFormattedString
import time
import numpy as np
import re
import json... | StarcoderdataPython |
8122306 | from ..abstract import ErdReadWriteConverter, ErdReadOnlyConverter
def erd_decode_string(value: str) -> str:
"""
Decode an string value sent as a hex encoded string.
"""
raw_bytes = bytes.fromhex(value)
raw_bytes = raw_bytes.rstrip(b'\x00')
return raw_bytes.decode('ascii')
def erd_encode_strin... | StarcoderdataPython |
5104660 | import numpy as np
import pytest
from scipy.stats import bootstrap, BootstrapDegenerateDistributionWarning
from numpy.testing import assert_allclose, assert_equal
from scipy import stats
from .. import _bootstrap as _bootstrap
from scipy._lib._util import rng_integers
def test_bootstrap_iv():
message = "`data` m... | StarcoderdataPython |
11390551 | <filename>tagging/apps.py
from django.apps import AppConfig
class TaggingConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'tagging'
| StarcoderdataPython |
3257457 | <filename>pygtfs/feed.py<gh_stars>10-100
from __future__ import (division, absolute_import, print_function,
unicode_literals)
import os
import io
import csv
from collections import namedtuple
from zipfile import ZipFile
import six
def _row_stripper(row):
return (cell.strip() for cell in... | StarcoderdataPython |
8179523 | from algebreb.ejercicios.operaciones_polinomio import TermPolinomio
from algebreb.expresiones.polinomios import polinomio_coeficientes_aleatorios
from sympy.abc import x, y, z
# Ejemplo 1
# Suma de polinomios
# Polinomios completos de grado 2 y 3,con coeficientes enteros aleatorios en un rango de -10 a 10
# con variab... | StarcoderdataPython |
4850498 | import re
def get_name(data):
name = []
x = data[0]
#x = 'Atul K.Singh '
for c in x:
if c.isalnum() or c==' ' or c=='.':
name.append(c)
name = ''.join(name)
name = re.sub('\s{2,}', ' ', name)
if name.endswith(' '):
name=name.rstrip()
return(nam... | StarcoderdataPython |
123516 | from sqlalchemy import func
from app import db
class Category(db.Model):
__tablename__ = 'category'
id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.String)
parent_id = db.Column(db.Integer, db.ForeignKey('category.id'), nullable=True)
last_updated = db.Column(db.DateTime(timezone... | StarcoderdataPython |
1743819 | # %%
import sys
sys.path.append("../../..")
from scipy.linalg import null_space
import copy
import numpy as np
from numpy.linalg import matrix_rank, matrix_power, cholesky, inv
import torch
from torch.optim import Adam
from torch.utils.tensorboard import SummaryWriter
from tqdm import tqdm
import util.geometry_util ... | StarcoderdataPython |
199868 | <reponame>sorja/opetus
def adder(n):
if n == 0:
return 0
# n = n - 1
return n + adder(n - 1)
if __name__ == '__main__':
print('''
Give a number between 1 and 1000. We will count the sum
1 + 2 + ... + N
''')
number = int(input('> Input a number: '))
total = adder(number)
... | StarcoderdataPython |
8074243 | <reponame>matchms/old-iomega-spec2vec
#
# Spec2Vec
#
# Copyright 2019 Netherlands eScience Center
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENS... | StarcoderdataPython |
6623307 | """additional indexing
Revision ID: 4cdcf068ef59
Revises: 54373a7de<PASSWORD>
Create Date: 2015-10-22 19:58:41.145656
"""
# revision identifiers, used by Alembic.
revision = '<KEY>'
down_revision = '54373a<PASSWORD>'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by ... | StarcoderdataPython |
106872 | import pandas as pd
import houghtest
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import accuracy_score
from sklearn.metrics import confusion_matrix
import cv2
import numpy as np
import pickle
from multiprocessing import Process
import tim... | StarcoderdataPython |
3589469 | #
# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license. See LICENSE file in the project.
#
import numpy as np
import pandas as pd
from dataclasses import dataclass
from pandas.core.groupby import DataFrameGroupBy
from data_wrangling_components.table_store import TableContainer,... | StarcoderdataPython |
6415374 | from typing import List
def solve(stocks: List[int]) -> int:
profit = 0
min_price = stocks[0]
for price in stocks:
sold_today = price - min_price
profit = max(profit, sold_today)
min_price = min(price, min_price)
return profit
result = solve([310, 315, 275, 295, 260, 270,... | StarcoderdataPython |
1856928 | from django.conf.urls import url
from . import views
app_name= 'contest'
urlpatterns = [
url(r'^$', views.contest, name='contest'),
url(r'^(?P<question_id>[0-9]+)/$', views.question, name='question'),
url(r'^(?P<question_id>[0-9]+)/results/$', views.ResultsView.as_view(), name='results'),
url(r'^(?P<qu... | StarcoderdataPython |
11251542 | <filename>test.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Jul 25 15:46:04 2021
@author: SSP
"""
import yfinance as yf
from utils_ssp_extended import get_sharecounts
def fundamental_data(ticker_str):
ticker_obj = yf.Ticker(ticker_str)
_bs = ticker_obj.balancesheet # balance s... | StarcoderdataPython |
323119 | # Runtime report tests
import json
import os
import unittest
import calipertest as cat
class CaliperRuntimeReportTest(unittest.TestCase):
""" Runtime report controller """
def test_runtime_report_default(self):
target_cmd = [ './ci_test_macros', '10', 'runtime-report,output=stdout' ]
caliper... | StarcoderdataPython |
3440800 | from sacramathengine import *
from State import State, StateError
class Movement: #Will add fixed values for specific keys, a,d,w,s.
def __init__(self, Vector, MeshObject = None):
if not isinstance(Vector, (vec3d, vec4d)):
raise TypeError("[System]: Vector has to be of type vec3d, or vec4d.")... | StarcoderdataPython |
5170569 | import os
import Client as sp
try:
from config import KEY, PID
except:
KEY = os.environ['SPURWING_KEY']
PID = os.environ['SPURWING_PID']
assert len(KEY) and len(PID)
def runner(func):
def wrapper():
try:
print(func.__name__, 'STARTED')
func()
print('\n' + func.__name__, 'PASSED')
excep... | StarcoderdataPython |
9791443 | <filename>ElevatorBot_old/static/globals.py
# bot dev channel id and clan id are in static.config.py
discord_server_id = 669293365900214293
""" Role IDs """
admin_role_id = 670383817147809814
dev_role_id = 670397357120159776
mod_role_id = 671261823584043040
socialist_role_id = 670579222468755458
member_role_id = 7696... | StarcoderdataPython |
8193351 | <filename>line/messaging/events/beacon.py
from .event import ReplyEvent
class Beacon(object):
json = None
type = None
hwid = None
def __init__(self, json):
self.json = json
self.type = self.json['type']
self.hwid = self.json['hwid']
class BeaconEvent(ReplyEvent... | StarcoderdataPython |
3389366 | import json
import os
import unittest
from app.parser.v0_0_1.schema_parser import SchemaParser
from app.schema.answer import Answer
from app.schema.block import Block
from app.schema.group import Group
from app.schema.introduction import Introduction
from app.schema.question import Question
from app.schema.questionnai... | StarcoderdataPython |
6500279 | #
# Copyright 2019 The FATE 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.org/licenses/LICENSE-2.0
#
# Unless required by appli... | StarcoderdataPython |
6630231 | <gh_stars>1-10
"""Tests for spiketools.utils.trials"""
import numpy as np
from spiketools.utils.trials import *
###################################################################################################
###################################################################################################
def ... | StarcoderdataPython |
8085638 | from collections import namedtuple
class ObviousFailure(Exception): pass
class _the(object):
def __init__(self):
self.__wrappers = set()
def __call__(self, target):
new_wrapper = WrapsObject(target)
self.__wrappers.add(new_wrapper)
return new_wrapper
def clear(self):
... | StarcoderdataPython |
98545 | <reponame>spil3141/Reseach-2-Malware-Detection-using-1D-CNN-and-RNN
# 텐서플로와 텐서플로 데이터셋 패키지 가져오기
#!pip install tensorflow-gpu==2.0.0-rc1
import tensorflow_datasets as tfds
import tensorflow as tf
#tfds.disable_progress_bar()
import os
#print(tf.config.list_physical_devices('GPU'))
print(tf.test.is_gpu_available())
#
#... | StarcoderdataPython |
1949970 | <reponame>the-4l4n/beautycave<gh_stars>0
# pylint: disable=no-member, unresolved-import
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
class Inventory(db.Model):
id = db.Column(db.Integer, primary_key=True)
category = db.Column(db.String(80), unique=False, nullable=True)
name = db.Column(db.String(80... | StarcoderdataPython |
316131 | <reponame>DirksCGM/turbo-stream
"""
Test turbo_stream.onesignal.reader
"""
import unittest
import pytest
from turbo_stream.onesignal.reader import OnesignalReader
class TestOnesignalReader(unittest.TestCase):
def test_generate_url_csv_export(self):
"""Test endpoint creation of csv_export."""
rea... | StarcoderdataPython |
3403415 | import math
from .path import Path
from .svgpathtools import parse_path
def Rectangle(x, y, width, height, rx=0, ry=0):
return Path(rectangle(x, y, width, height, rx, ry))
def Circle(cx, cy, r):
return Path(circle(cx, cy, r))
def Arc(cx, cy, radius, start_angle, end_angle):
return Path(arc(cx, cy, ra... | StarcoderdataPython |
175609 | <reponame>fsaulo/radio-retro
import sinais as sn
import numpy as np
import matplotlib.pyplot as plt
def binary_signal(bit_stream, fs, Bd):
k = len(bit_stream)
n = round(fs/Bd) * k
samples = round(n/k)
X = np.zeros(n)
for i in range(0, k):
X[i*samples:(i+1)*samples] = np.ones(samples) * int(... | StarcoderdataPython |
1997396 | import argparse
parser = argparse.ArgumentParser(
description='Generate semi-empirical glycopeptide assays.'
)
parser.add_argument(
'--in', nargs='+',
help='input assay files'
)
parser.add_argument(
'--out',
help='output assay file'
)
parser.add_argument(
'--action', choices=['interchange', 'ex... | StarcoderdataPython |
8021781 | <filename>Utils/Visualization/visualize.py
#!/usr/bin/env python3
import yaml
import matplotlib
# matplotlib.use("Agg")
from matplotlib.patches import Circle, Rectangle, Arrow, RegularPolygon
from matplotlib.collections import PatchCollection
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import ani... | StarcoderdataPython |
6501264 | <reponame>ablot/Pinceau
# -*- coding: utf-8 -*-
from neuropype import node
from neuropype.datatypes import Sweep
from neuropype.ressources._common import boxfilter
from scipy.signal import order_filter, medfilt
from numpy import ones, vstack, array
from math import ceil
##debuging tool!
#from IPython.Shell import IPS... | StarcoderdataPython |
5142526 | <filename>Python3/Offer/08/NextNodeInorder.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2018/11/21 9:32 AM
# @Author : Insomnia
# @Desc : 给定一个二叉树和其中的一个结点,请找出中序遍历顺序的下一个结点并且返回。注意,树中的结点不仅包含左右子结点,同时包含指向父结点的指针。
# @File : NextNodeInorder.py
# @Software: PyCharm
import utils.BinaryTree.BinaryTree
cla... | StarcoderdataPython |
3575931 | <reponame>amiraliakbari/sharif-mabani-python
def f(a, b, *args, **kwargs):
pass
f(4, 1, 2, 3, x=2, h=4)
| StarcoderdataPython |
9644311 | <filename>scripts/evaluation.py<gh_stars>1-10
#!/usr/bin/env python3
import csv, sys, os
def computeMRR(mpr) :
'''
Compute mean reciprocal rank for
list-of-rank-lists mpr.
'''
mrr = 0
for q in mpr :
if q[0] != None :
mrr += 1./q[0]
mrr /= len(mpr)
return mrr
def computeAP(rl) :
'''
Comp... | StarcoderdataPython |
5049110 | from datetime import datetime
from flask import make_response, abort
from config import db
from models import Response, ResponseSchema
def read_sql(workshop_id=False, length=False, offset=False):
"""
This function responds to a request for api/reviews/
with matching review given a list of optional paramet... | StarcoderdataPython |
1894058 | import torch
import torch.nn as nn
import torch.nn.functional as F
import math
class VariationalAutoEncoder(nn.Module):
"""
A VariationalAutoEncoder object contains a VAE network comprised of an encoder and decoder. The encoder compresses and reparameterizes input to a constrained multivariate latent distribution. T... | StarcoderdataPython |
6641009 | import os
import base64
import logging
import requests
import datetime
import argparse
import subprocess
import multiprocessing.dummy
CMD_ID = '1'
CHUNK_ID = '2'
UPLOAD_ID = '3'
CHUNK_SIZE = 50000 # 50 KB
LOG_FORMAT = '[%(asctime)s][%(levelname)s] %(message)s'
BANNER = """
*********************************************... | StarcoderdataPython |
9716459 | # Author: xyb, Diving_Fish
import asyncio
import os
import math
from typing import Optional, Dict, List, Tuple
import aiohttp
from PIL import Image, ImageDraw, ImageFont, ImageFilter
from src.libraries.maimaidx_music import total_list
scoreRank = 'D C B BB BBB A AA AAA S S+ SS SS+ SSS SSS+'.split(' ')
combo = ' FC F... | StarcoderdataPython |
1851322 | from . import devicearray, devices, driver, drvapi, nvvm
| StarcoderdataPython |
3520015 | <filename>polrev/offices/widgets/__init__.py
from .office_widgets import *
from .state_widgets import *
from .us_senate_widgets import *
from .us_house_widgets import *
from .state_senate_widgets import *
from .state_house_widgets import *
from .school_district_widgets import *
from .county_widgets import *
from .loca... | StarcoderdataPython |
262369 | <filename>src/fvm/test/COUPLING/Struct_Elec_3D_unsteady_uq.py
#!/usr/bin/env python
### Structure and Electrostatics coupling --- 2D beam ###
### import modules ###
import pdb
import sys
import os
from math import *
sys.setdlopenflags(0x100|0x2)
#import tecplotExporter
import fvm.fvmbaseExt as fvmbaseExt
import fvm... | StarcoderdataPython |
8032852 | <filename>output/models/nist_data/atomic/base64_binary/schema_instance/nistschema_sv_iv_atomic_base64_binary_enumeration_1_xsd/__init__.py
from output.models.nist_data.atomic.base64_binary.schema_instance.nistschema_sv_iv_atomic_base64_binary_enumeration_1_xsd.nistschema_sv_iv_atomic_base64_binary_enumeration_1 import ... | StarcoderdataPython |
9635153 | <reponame>the4t4/SyntaClean<gh_stars>1-10
import os, sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))
from clean_parser.parser import CleanParser
import unittest
from unittest import TestCase
resourceDir = "resources"
parser = CleanParser()
class TestParser(TestCase... | StarcoderdataPython |
1691081 | """Debug events handler: test [un-]load modules notification"""
import unittest
import target
import pykd
import fnmatch
import testutils
class ModuleLoadHandler(pykd.eventHandler):
"""Track load/unload module implementation"""
def __init__(self, moduleMask):
pykd.eventHandler.__init__(self)
... | StarcoderdataPython |
5022629 | <filename>components/gcp/automl/import_data_from_gcs/component.py<gh_stars>0
# Copyright 2019 The Kubeflow 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.o... | StarcoderdataPython |
8068009 | #!/usr/bin/env python
# coding: utf-8
import pandas as pd
import numpy as np
import pickle
import matplotlib.pyplot as plt
from sklearn import pipeline, preprocessing, compose, linear_model, impute, model_selection
# Load data
print("Loading the training observations")
df = pd.read_csv("https://raw.githubuserconten... | StarcoderdataPython |
4896180 | #!/usr/bin/env python
from setuptools import setup, find_packages
from admin_tools import VERSION
repo_url = 'https://github.com/django-admin-tools/django-admin-tools'
long_desc = '''
%s
%s
''' % (open('README.rst').read(), open('CHANGELOG').read())
setup(
name='django-admin-tools',
version=VERSION.replace(... | StarcoderdataPython |
4867649 | <filename>exercicios/ex078.py
# Desafio 078 -> C. um programa que leia 5 valores numericos e guarde numa lista
# No final, mostre qual foi o menor e maior valor digitado e as suas respectivas posições na lista
lista = []
max = min = 0
#listamm = lista[:]
for v in range(0, 5):
lista.append(int(inp... | StarcoderdataPython |
269900 | <reponame>ajrichards/bayesian-examples
from surprise import SVD
from surprise import Dataset, accuracy
from surprise.model_selection import cross_validate,train_test_split
# Load the movielens-100k dataset (download it if needed).
data = Dataset.load_builtin('ml-100k')
# sample random trainset and testset
# test set ... | StarcoderdataPython |
1813169 | import FWCore.ParameterSet.Config as cms
# process declaration
process = cms.Process("SiStripCommissioningOfflineDbClient")
#############################################
# General setup
#############################################
# message logger
process.load('DQM.SiStripCommissioningSources.OfflineMessageLogger_... | StarcoderdataPython |
11324339 | import json
from django.contrib.auth.models import User
from funfactory.urlresolvers import reverse
from nose.tools import eq_
import common.tests
from ..cron import assign_autocomplete_to_groups
from ..models import AUTO_COMPLETE_COUNT, Skill
class SkillsTest(common.tests.ESTestCase):
def test_autocomplete_... | StarcoderdataPython |
81365 | from get_data.dataset_util import download_raw_dataset, convert_to_faces
from get_data.get_faces import detect_face, crop_image
__all__ = ('download_raw_dataset', 'convert_to_faces', 'convert_to_faces', 'detect_face', 'crop_image')
| StarcoderdataPython |
1943861 | <reponame>rajshrivastava/LeetCode<filename>src/835. Image Overlap.py
class Solution:
def largestOverlap(self, A: List[List[int]], B: List[List[int]]) -> int:
def match(beg_i, beg_j):
count = 0
low_i = low_j = 0
high_i = high_j = n
if beg_i<=0:
... | StarcoderdataPython |
9782547 | <filename>cfgov/data_research/tests/test_blocks.py
from django.core.exceptions import ValidationError
from django.test import TestCase
from data_research.blocks import ConferenceRegistrationForm
from v1.models import BrowsePage
class ConferenceRegistrationFormTests(TestCase):
fixtures = ["conference_registration... | StarcoderdataPython |
3364396 | # -*- coding: utf-8 -*-
"""
flask_principal
~~~~~~~~~~~~~~~
Identity management for Flask.
:copyright: (c) 2012 by <NAME>.
:license: MIT, see LICENSE for more details.
"""
from __future__ import with_statement
__version__ = '0.3.5'
import sys
from functools import partial, wraps
from collecti... | StarcoderdataPython |
5071996 | ''' test NIAGADS Ontology Validator Script against Data Dictionary '''
from sys import path
path.append('../src/') # bring src directory into path so can do the import
from ontology_validator import OntologyValidator
import json
validator = OntologyValidator('https://beta.niagads.org/genomics', 'DD')
response = vali... | StarcoderdataPython |
8189344 | <reponame>jonigirl/Badb<filename>cogs/scambanner.py
import re
import discord
from discord.ext import vbu
SCAM_REGEX = re.compile(
r"""
(gift|nitro|airdrop|@everyone|:\))
.+?
(
(https?://)(\S*?)
(
((?:d|cl)s?[li](?:sc|cs|zc|cz|s|c|sck)r?oc?r?c?(?:d|c... | StarcoderdataPython |
4824200 | #!/usr/bin/env python
import web
urls = (
'/(.*)', 'hello'
)
class hello:
def GET(self, name):
i = web.input(times=1)
if not name: name = 'world'
for c in range(int(i.times)):
print 'Hello,', name+'!'
if __name__ == "__main__":
app = web.application(urls, globals... | StarcoderdataPython |
6462549 | <reponame>lauhaide/clads
import os, argparse, sys
from tqdm import tqdm
def run(args):
TARGET_LANG = args.smallestSetLang
TO_SHORTEN_LANGS = args.toShortenLangs
HOME_SUBSETS = os.path.join(args.home, args.subsetsDir)
pivotFile = open(os.path.join(args.home, args.langPivotFile), 'r')
pivotLang = a... | StarcoderdataPython |
11304618 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 26 11:38:14 2021
@author: christian
"""
from astropy import constants as const
from astropy.io import fits
from astropy.convolution import Gaussian1DKernel, convolve
import datetime as dt
import math
import matplotlib.backends.backend_pdf
import mat... | StarcoderdataPython |
9776746 | <gh_stars>0
import handyTools.stats as stats
import handyTools.bayesianBlocks as bayesianBlocks
import handyTools.denoise as denoise
import handyTools.periodogram as periodogram
import handyTools.utils as utils
name = 'handyTools'
| StarcoderdataPython |
4935699 | # -*- coding: utf-8 -*-
import scrapy
from scrapy import Selector
from scrapy_selenium import SeleniumRequest
import time
class CatlinkextractSpider(scrapy.Spider):
name = 'catLinkExtract'
def start_requests(self):
yield SeleniumRequest(
url="https://www.familydollar.com/cleaning/laundry-... | StarcoderdataPython |
260422 | """Test the API with the EMMO ontology."""
import itertools
import unittest2 as unittest
import rdflib
from osp.core.ontology import OntologyEntity
from osp.core.ontology.relationship import OntologyRelationship
from osp.core.ontology.attribute import OntologyAttribute
from osp.core.ontology.oclass_restriction import ... | StarcoderdataPython |
3433041 | # Copyright (c) 2015 Rackspace, 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 required by applicable law or agreed to in wr... | StarcoderdataPython |
1743413 | <filename>pyplusplus/code_repository/indexing_suite/suite_utils_header.py
# Copyright 2004-2008 <NAME>.
# Distributed under the Boost Software License, Version 1.0. (See
# accompanying file LICENSE_1_0.txt or copy at
# http://www.boost.org/LICENSE_1_0.txt)
"""
This file contains indexing suite v2 code
"""
file_name =... | StarcoderdataPython |
11363371 | import io
import sys
import unittest
from pyalink.alink import *
from pyalink.alink.common.utils.printing import print_with_title
class TestLazyModelTrainInfo(unittest.TestCase):
def setUp(self) -> None:
self.saved_stdout = sys.stdout
self.str_out = io.StringIO()
sys.stdout = self.str_ou... | StarcoderdataPython |
3235149 | <gh_stars>0
'''
@author: <NAME>
'''
class Numar(object):
def __init__(self, valoare, baza):
'''
Functie de tip constructor care construieste un obiect de tip Numar
Input: valoare - un string
baza - un numar intreg, pozitiv, ce apartine multimii {2, 3, ..., 10, 16}
... | StarcoderdataPython |
6461059 | <gh_stars>1-10
TEMPLATE = """
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>{{ title }}</title>
<link
rel="stylesheet"
href="../style.css">
</head>
<body>
<div class="card" style="width:100%;float:left;">
<div class="card-header text-center bg-light-cust... | StarcoderdataPython |
3563441 | #var
#a, resto4, resto100, resto400: int
a=int(input("Digite um ano: "))
resto4 = a%4
resto100 = a%100
resto400 = a%400
if resto4==0:
if resto100==0:
if resto400==0:
print("Bissexto")
else:
print("Não é bissexto")
else:
print("Bissexto")
else:
print("Nã... | StarcoderdataPython |
8099734 | <filename>FileManager/serializers.py
# from importlib.metadata import files
# from typing import Type
from rest_framework import serializers
from .models import *
class TypesSerializers(serializers.ModelSerializer):
class Meta:
model=Topics
fields = '__all__'
class FileSerializers(serializers.Mode... | StarcoderdataPython |
11333024 | <filename>chrome/browser/resources/test_presubmit.py<gh_stars>100-1000
#!/usr/bin/env python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Unit tests for Web Development Style Guide checker."""
i... | StarcoderdataPython |
234083 | <filename>tests/test_filters.py
from .context import druidry
import unittest
class FilterTest(unittest.TestCase):
def test_create_invalid(self):
with self.assertRaises(druidry.errors.DruidQueryError):
druidry.filters.Filter('INVALID')
def test_create(self):
filter_ = druidry.filt... | StarcoderdataPython |
1928543 | from .wav2letter import Wav2Letter
from .wavernn import WaveRNN
from .conv_tasnet import ConvTasNet
__all__ = ['Wav2Letter', 'WaveRNN', 'ConvTasNet']
| StarcoderdataPython |
3309719 | #!/usr/bin/env python3
'''
Homework on 04_PublishingAndGeometry
'''
from tkinter import *
from rgb import Colors
import random
def randomcolor(bright=True):
b, d = "ABCDEF", "0123456"
return "#"+"".join(random.choice(c)+random.choice(b+d) for c in random.sample(((b,b,b,d,d) if bright else (d,d,d)), 3))
def ... | StarcoderdataPython |
4949060 | <gh_stars>1-10
from airflow.operators.python_operator import PythonOperator as AirflowPythonOperator
from airflow.operators.bash_operator import BashOperator as AirflowBashOperator
from airflow.operators.slack_operator import (
SlackAPIPostOperator as AirflowSlackAPIPostOperator
)
from airflow.operators import SubD... | StarcoderdataPython |
5000637 | <filename>examples/python/dashi_comparison.py
import numpy as np
import ndhist
import dashi
import resource
import pylab
N = 1e7
axis = np.linspace(-100, 100, num=201, endpoint=True).astype(np.dtype(np.float64))
axis_min = axis.min()
axis_max = axis.max()
print("------------------------------------------------------... | StarcoderdataPython |
11295443 | <filename>fiaas_deploy_daemon/deployer/deploy.py
#!/usr/bin/env python
# -*- coding: utf-8
# Copyright 2017-2019 The FIAAS 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
#
# ht... | StarcoderdataPython |
3368954 | <reponame>shagun30/djambala-2
# -*- coding: utf-8 -*-
"""
/dms/image/views_edit.py
.. enthaelt den View zum Aendern der Eigenschaften eines Bildes
Django content Management System
<NAME>
<EMAIL>
Die Programme des dms-Systems koennen frei genutzt und den spezifischen
Beduerfnissen entsprechend angepasst werd... | StarcoderdataPython |
4861174 | <reponame>amirrpp/clearly<filename>tests/unit/test_client.py
import re
from unittest import mock
import pytest
from celery import states
from clearly.client import ClearlyClient
from clearly.protos import clearly_pb2
from clearly.utils import worker_states
from clearly.utils.colors import strip_colors
@pytest.fixtu... | StarcoderdataPython |
1907462 | from bd import models
import datetime
import Fron_end.settings as settings
def get_client_ip(request):
x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
if x_forwarded_for:
ip = x_forwarded_for.split(',')[0]
else:
ip = request.META.get('REMOTE_ADDR')
... | StarcoderdataPython |
9693580 | <filename>submit.py
import requests
import json
import uuid
import os
from fill import fillForm
from login import login
from encrypt import desEncrypt
def queryCollectorProcessingList(headers, cookies):
payload = {"pageNumber": 1, "pageSize": 20}
url = "https://ahnu.campusphere.net/wec-counselor-co... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.