id stringlengths 1 8 | text stringlengths 6 1.05M | dataset_id stringclasses 1
value |
|---|---|---|
148033 | import time
load_start_time = time.time()
import csv
import nltk
import re
import numpy as np
import pandas as pd
from dateutil import parser
import gensim, logging
from gensim.models import Word2Vec
from nltk.tokenize import sent_tokenize, word_tokenize
from nltk.corpus import stopwords
from nltk.stem.porter import ... | StarcoderdataPython |
3345995 | # -*- coding: utf-8 -*-
"""Helper utilities and decorators."""
from flask import flash, _request_ctx_stack
from functools import wraps
from flask_jwt import _jwt
import jwt
def jwt_optional(realm=None):
def wrapper(fn):
@wraps(fn)
def decorator(*args, **kwargs):
token = _jwt.request_ca... | StarcoderdataPython |
357507 | <reponame>wdoppenberg/ellipse-rcnn
import warnings
from pytorch_lightning.utilities.warnings import LightningDeprecationWarning
warnings.simplefilter(action='ignore', category=LightningDeprecationWarning)
import pytorch_lightning as pl
from ellipse_rcnn import get_dataloaders, EllipseRCNN
if __name__ == "__main__"... | StarcoderdataPython |
11295179 | """Simple command line interface for common use cases"""
import argparse
from nix_bisect import nix, git, git_bisect, bisect_runner, exceptions
from nix_bisect.derivation import Derivation
def _perform_bisect(attrname, nix_file, to_pick, max_rebuilds, failure_line):
for rev in to_pick:
git.try_cherry_pic... | StarcoderdataPython |
8187732 | <filename>mistraldashboard/action_executions/forms.py<gh_stars>10-100
# Copyright 2016 - Nokia.
# 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 |
3204181 | <reponame>wasp/gateway
from http import HTTPStatus
class HTTPException(Exception):
__status__ = HTTPStatus.INTERNAL_SERVER_ERROR
@property
def status(self):
return self.__status__
# ==============================
# 4xx
# ==============================
class HTTPNotFoundException(HTTPException):... | StarcoderdataPython |
6516413 | """Top-level package for inheritance_explorer."""
__author__ = """<NAME>"""
__email__ = "<EMAIL>"
__version__ = "0.1.0"
from .inheritance_explorer import ClassGraphTree
| StarcoderdataPython |
11250727 | import inputs as _inputs
import threading as _threading
import time as _time
class gamepad:
def __init__(self, pygame):
self._lasty = ''
self._lastx = ''
self.founded = False
self._buttons = {'left-joystick': False,
'right-joystick': False,
... | StarcoderdataPython |
3467422 | <filename>src/train.py
import pickle
import argparse
from tensorflow.keras import Model
from sklearn.model_selection import train_test_split
from .network import make_network
def load(x):
pass
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--data", help="path to data"... | StarcoderdataPython |
6414235 | """
<NAME>, <NAME>
Many functions are adopted from Chris's mypy
"""
from __init__ import *
import subprocess as sp
import os
from scipy import sparse
def myScatter(ax, df, x, y, l,
s=20,
sample_frac=None,
sample_n=None,
legend_size=None,
legend_k... | StarcoderdataPython |
5159030 | import cv2
import numpy as np
import math
import time
cap = cv2.VideoCapture(0)
test_img = cv2.imread('test_red.png')
kernel = np.ones((5, 5), np.uint8)
# imgray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
# BGR
# ret,thresh = cv2.threshold(imgray, 127, 255, 0)
# image, contours, hierarchy = cv2.findContours(thresh,cv2.RET... | StarcoderdataPython |
5077086 | #!/usr/bin/env python3
# encoding: UTF-8
__author__ = "mirai"
__license__ = "GPLv3"
__version__ = "1.3.2"
################################
import argparse
import sys
import time
import requests
import re
import os
import validators
from termcolor import colored
from argparse import RawTextHelpFormatter
from sys imp... | StarcoderdataPython |
3524476 | """
Cash Flow Statement
"""
from datetime import timedelta
from matilda.data_pipeline.db_crud import read_financial_statement_entry
def cash_flow_operating_activities(stock, date=None, lookback_period: timedelta = timedelta(days=0),
period: str = 'TTM'):
'''
Operating cash ... | StarcoderdataPython |
1756303 | <filename>setup.py<gh_stars>1-10
from setuptools import setup
setup(
name = "LDApackage",
version = "1.0",
author='<NAME>, <NAME>',
url='https://github.com/rebeccazjy425/663_LDA_Tang-Zhang.git',
py_modules = ['LDApackage'],
install_requires=['jieba','gensim','nltk']
)
| StarcoderdataPython |
4850062 | from flags import *
# Vertical Tricolours
def ireland():
return verticalTricolour(green, white, orange)
def france():
return verticalTricolour(navy_blue, white, red)
def italy():
return verticalTricolour(green, white, red)
def barbados():
return verticalTricolour(navy_blue, light_yellow, navy_blue)
... | StarcoderdataPython |
11376075 | #!/usr/bin/env python
import sys
import argparse
import numpy as np
import os
import matplotlib.pyplot as plt
from utils import load_data
from utils import argparse_parents
def create_colors_list():
colors_list = []
for color in plt.cm.Set1(np.linspace(0, 1, 9)):
colors_list.append(tuple(color))
... | StarcoderdataPython |
1789660 | <reponame>ryuzakyl/yapir
import cv2
import numpy as np
from encoding.fda_encoding import ComputeMfAnnular
from utils.error_utils import SUCCESS, UNKNOWN_FAIL
def encode_iris(norm_img, mask_img, order=16, eps_lb=0.25, eps_ub=1.0):
# getting image dimensions
height, width = norm_img.shape
# computing Mf ... | StarcoderdataPython |
79751 | <filename>dnanexus/filter_qc/src/filter_qc.py
#!/usr/bin/env python
# filter_qc 0.0.1
# Generated by dx-app-wizard.
#
# Basic execution pattern: Your app will run on a single machine from
# beginning to end.
#
# See https://wiki.dnanexus.com/Developer-Portal for documentation and
# tutorials on how to modify this file.... | StarcoderdataPython |
5092917 | #!/usr/bin/env python
import time
import requests
import json
from collections import OrderedDict
import os
import sys
import random
from pprint import pprint
COIN = 1000000
TX_FEE = 0.01
rpcurl = 'http://1192.168.127.12:9902'
genesis_privkey = '<KEY>'
genesis_addr = '1965p604xzdrffvg90ax9bk0q3xyqn5zz2vc9zpbe3wdswz... | StarcoderdataPython |
3201142 | import math
import os
import random
import re
import sys
def anagrams_in_string(s):
'''
Given a string, find the number of pairs of substrings of the string that are anagrams of each other.
For example 'mom', the list of all anagrammatic pairs is [m,m], [mo, om].
Anagrams = the letters of one strin... | StarcoderdataPython |
1977083 | from api_client import *
from haversine import haversine, Unit
import db_handler
import env
import aiohttp
import asyncio
import json
import sys
# TODO: PLAN OUT AND FIX THIS ENTIRE DOCUMENT, BACKEND IS COMPLETELY RESTRUCTURED
client = ApiClient("src/db.sqlite", env.KEY_WALK_SCORE, env.KEY_GOOGLE_GEO)
# test_house =... | StarcoderdataPython |
6653729 | import argparse
import logging
import os
import re
import sys
from concurrent import futures
from typing import Any
import grpc
import yaml
sys.path.append(os.path.dirname(os.path.dirname(__file__)))
from controller import server_impl as mir_controller_service
from controller import task_monitor
from proto import ba... | StarcoderdataPython |
9776986 | import os
import io
from tempfile import TemporaryFile
from OpenSSL.crypto import X509 as openssl_X509
from OpenSSL.crypto import dump_certificate, FILETYPE_PEM
from OpenSSL.SSL import TLSv1_2_METHOD
from cryptography import x509
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primit... | StarcoderdataPython |
6452534 | <reponame>goncalovalverde/seshat<gh_stars>1-10
import dash
import dash_core_components as dcc
import dash_html_components as html
import dash_table
import dash_bootstrap_components as dbc
from dash.dependencies import Input, Output
from dash_extensions import Download
from dash_extensions.snippets import send_data_fram... | StarcoderdataPython |
3594324 | <reponame>redhuntlabs/Log4JHunt<gh_stars>10-100
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#:-:--:--:--:--:--#
# Log4JHunt #
#:-:--:--:--:--:--#
# Author: <NAME> (@0xInfection)
# This file is a part of the Log4JHunt tool meant for testing of
# hosts vulnerable to the Log4Shell vulnerability.
import os, sys... | StarcoderdataPython |
8049924 | from tslearn.piecewise import calculate_circles
print()
| StarcoderdataPython |
30185 | <gh_stars>0
import os
import cv2
import mxnet as mx
import numpy as np
from . import face_preprocess
from .mtcnn_detector import MtcnnDetector
def get_model(ctx, image_size, model_str, layer):
_vec = model_str.split(',')
assert len(_vec) == 2
prefix = _vec[0]
epoch = int(_vec[1])
print('loading'... | StarcoderdataPython |
3373635 | <reponame>WatsonWangZh/CodingPractice
# Given n nodes labeled from 0 to n-1 and a list of undirected edges (each edge is a pair of nodes),
# write a function to check whether these edges make up a valid tree.
# Example 1:
# Input: n = 5, and edges = [[0,1], [0,2], [0,3], [1,4]]
# Output: true
# Example 2:
# Input: n... | StarcoderdataPython |
9789534 | """
Copyright (C) 2010-2022 Alibaba Group Holding Limited.
"""
import torch
from .builder import CAMERA
from .common import yaw_to_rot_mat, quaternion_to_rot_mat, skew
def project_a(x3d, pose, cam_mats, z_min: float):
if pose.size(-1) == 4:
x3d_rot = x3d @ (yaw_to_rot_mat(pose[..., -1])).transpose(-1, -... | StarcoderdataPython |
11227852 | <gh_stars>0
__version__ = "{{cookiecutter.package_version}}"
| StarcoderdataPython |
8187176 | import setuptools, os
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as doc:
__doc__=doc.read()
setuptools.setup(
name='teacup',
version='0.9',
url='https://github.com/benwbooth/python-teacup',
author='<NAME>',
author_email='<EMAIL>',
license='MIT',
keywords="python mo... | StarcoderdataPython |
6558681 | <filename>distiller/helpers/HttpRequestHandler.py
from http.server import BaseHTTPRequestHandler
import json
import sys
class HttpRequestHandler(BaseHTTPRequestHandler):
max_length = 1024 * 1024
def do_POST(self):
try:
con_len = int(self.headers.get("content-length", 0))
con_... | StarcoderdataPython |
4824304 | import pytest
import repo
@pytest.fixture
def mock_repo(mocker):
mocker.patch.object(repo, 'REPO')
return repo.REPO
def test_get_application(mock_repo):
app_id = 'myApp'
app = {'ApplicationId': app_id}
mock_repo.get_application.return_value = app
assert repo.get_application(app_id) == app
... | StarcoderdataPython |
3247238 | class Solution(object):
def peakIndexInMountainArray(self, A):
"""
:type A: List[int]
:rtype: int
"""
for i in range(2, len(A)):
if A[i-2] < A[i-1] > A[i]:
return i-1
| StarcoderdataPython |
3415412 | # reference: https://github.com/open-mmlab/mmselfsup/tree/master/mmselfsup/models/algorithms
# modified from mmselfsup barlowtwins.py
from openmixup.utils import print_log
from ..classifiers import BaseModel
from .. import builder
from ..registry import MODELS
@MODELS.register_module
class BarlowTwins(BaseModel):
... | StarcoderdataPython |
6555344 | <reponame>andreasvlachos/structured_imitation_demo
# This is a basic definition of the state. But it can be overriden/made more complicated to support:
# - bookkeeping on top of the actions to facilitate feature extraction, e.g. how many times a tag has been used
# - non-trivial conversion of the state to the final pre... | StarcoderdataPython |
3305281 | <gh_stars>0
#!/usr/bin/env python3
from argparse import ArgumentParser
from dataclasses import dataclass
from itertools import zip_longest
from typing import Dict
from typing import Iterable
from typing import List
from typing import NamedTuple
from typing import Tuple
from typing import TypeVar
T = TypeVar("T")
def... | StarcoderdataPython |
5054022 | <reponame>rn5l/rsc18
'''
Created on 13.04.2018
@author: malte
'''
from algorithms.Model import Model
import pandas as pd
import numpy as np
class Random(Model):
'''
classdocs
'''
def __init__(self):
'''
Constructor
'''
def init(self, train, test):
pass
... | StarcoderdataPython |
3275387 | # __init__.py
from Ronnakornschool.Ronschool import Student, SpecialStudent
| StarcoderdataPython |
3501260 | <filename>10 - python-data-science-toolbox-part-2/14 - changing the output in generator expressions.py
'''
Great! At this point, you already know how to write a basic generator expression. In this exercise, you will push this idea a little further by adding to the output expression of a generator expression. Because ge... | StarcoderdataPython |
6510251 | import fbdplc.s7xml as s7mxl
from lxml import etree
def _simple_or(networks):
assert(len(networks) == 1)
def test_simple_or_file():
'''
fdb that computes "a_or_b" := Or(ToSafety.a, ToSafety.b)
stored in testdata/blocks/simple_or.xml
cut from a larger programs
'''
networks = s7mxl.parse_f... | StarcoderdataPython |
11320289 | __version__ = "1.b"
__all__ = ["anarci", "schemes"]
from anarci import *
| StarcoderdataPython |
394427 | <gh_stars>1-10
from textwrap import dedent
import pytest
from texttree import sibling, parent, child
from texttree import Tree
@pytest.mark.parametrize(
'given, expected',
[
[(0,), (1,)],
[(1, 1), (1, 2)],
],
)
def test_sibling(given, expected):
got = sibling(given)
assert got ==... | StarcoderdataPython |
1842201 | <filename>function/index.py
import math
# def loops():
# d =4
# for i in range(d):
# print(i)
# loops()
#object-oriented programming
#procedural programming
# hello world
# def hello_world():
# print("Hello world jayson")
# hello_world()
#arguments
def hell... | StarcoderdataPython |
182738 | <reponame>LawlietJH/DigitalRain<filename>DigitalRain - v1.0.0.py<gh_stars>1-10
# By: LawlietJH
# Digital Rain
from datetime import datetime
# ~ import threading
# ~ import binascii # hexlify y unhexlify
# ~ import psutil
import pygame # python -m pip install pygame
import ctypes # windll Manipulac... | StarcoderdataPython |
3219286 | from django.urls import path
from .views import *
urlpatterns = [
path('login/', login , name="login")
]
| StarcoderdataPython |
8024587 | <gh_stars>10-100
import json
import os
from dadmatools.datasets.base import BaseDataset, DatasetInfo, BaseIterator
from dadmatools.datasets.dataset_utils import download_dataset, unzip_dataset, is_exist_dataset, DEFAULT_CACHE_DIR
URL = 'https://drive.google.com/uc?id=1jHje8Q07tQWEpt8cEpFR_TOuqjFs79Vb'
DATASET_NAME = "... | StarcoderdataPython |
9611558 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
This program is designed to migrate checksums to new versions of software,
when it is known that all the checksum changes are irrelevant to the visual
aspects of the PDF. An example of this is when the PDF version number is
incremented from 1.3 to 1.4 for no good reas... | StarcoderdataPython |
3266269 | import time
import random
from tqdm import tqdm
import numpy as np
def efficient_greedy(
measure,
dataset_size,
subset_size,
start_indices,
intermediate_target=None,
clustering_combinations=None,
celf_ratio=0,
verbose=True
):
candidates = list(set(range(dataset_size)) - set(start... | StarcoderdataPython |
1692823 | <filename>python/flask/app/controller.py
# Standard library
import logging
# 3rd party modules
import flask
from flask import jsonify, make_response, request
from app import httputil
from app.httputil import status
from app.httputil.error import BadRequestError
from app.httputil.instrumentation import trace
# Interna... | StarcoderdataPython |
137840 | """
django-json-dbindex tests
"""
import os
import json
import util
from django.test import TestCase
class SimpleTest(TestCase):
def test_sql_simple(self):
"""
Return of sql_simple
"""
idx = {'foo': 'bar'}
res = "FOOBAR bar"
self.assertEqual(util.sql_simple(idx, 'f... | StarcoderdataPython |
11299269 | <filename>actions/lib/base.py
from st2common.runners.base_action import Action
from exception import MissingProfileError
from exception import ValidationFailError
from exception import NexusClientNotInstantiatedError
from nexuscli.repository import Repository
from nexuscli.nexus_client import NexusClient
from nexuscli.... | StarcoderdataPython |
4876781 | <gh_stars>0
from django.contrib import admin
from .models import Company
@admin.register(Company)
class CompanyAdmin(admin.ModelAdmin):
autocomplete_fields = ["jurisdictions", "sic_codes"]
list_display = ["__str__"]
ordering = ["name", "pk"]
search_fields = ["name"]
fieldsets = [
[
... | StarcoderdataPython |
3563992 | import logging
from flask import Blueprint, jsonify
from investing_algorithm_framework.globals import current_app
from investing_algorithm_framework.exceptions import ApiException
logger = logging.getLogger(__name__)
blueprint = Blueprint("operational-views", __name__)
@blueprint.route("/start", methods=["GET"])
d... | StarcoderdataPython |
6413185 | """Support for file formats not specific to particular simulators.
.. raw:: html
<h2>Submodules</h2>
.. autosummary::
:toctree:
opendrive
"""
| StarcoderdataPython |
5147724 | <filename>tsutil/daemonize.py
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: <NAME>
# @Date: 2014-03-07 17:11:20
# @Last Modified by: <NAME>
# @Last Modified time: 2014-09-10 11:03:30
import os
import sys
def daemonize(stdin='/dev/null', stdout='/dev/null', stderr='/dev/null'):
try:
pid = ... | StarcoderdataPython |
180102 | # Copyright (C) 2015 ycmd contributors
#
# This file is part of ycmd.
#
# ycmd is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ycmd... | StarcoderdataPython |
6468515 | <filename>models/displayable_reviews.py
from dataclasses import dataclass
from typing import Iterator, Set, List
import settings
from models.displayable_review import DisplayableReview
@dataclass
class DisplayableReviews:
reviews: Iterator[DisplayableReview]
def __approved_reviews(self) -> List[DisplayableR... | StarcoderdataPython |
306127 | """Global fixtures for zadnego_ale integration."""
import json
from unittest.mock import patch
import pytest
from pytest_homeassistant_custom_component.common import load_fixture
from custom_components.zadnego_ale import ApiError
@pytest.fixture(name="bypass_get_data")
def bypass_get_data_fixture():
"""Skip cal... | StarcoderdataPython |
11307878 | <reponame>pkfec/regulations-parser<filename>regparser/web/management/commands/eregs.py
import logging
import os
import sys
import click
import coloredlogs
import ipdb
from django.core import management
from django.db import connections
from django.db.migrations.loader import MigrationLoader
from djclick.adapter import... | StarcoderdataPython |
1830672 | import logging as Log
import logging.config
import os
from tools.config import API_LOGS, LOG_CONFIGFILE
def Logger(where="", name=None):
dests = where.split('/')
aws_logfile = os.path.join(API_LOGS,
dests[0],
dests[1])
logging.config.fileConfig... | StarcoderdataPython |
3308999 | <gh_stars>0
# Generated by Django 2.2.17 on 2021-02-13 17:23
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('authentications', '0001_initial'),
]
operations = [
migrations.AlterField(
model_n... | StarcoderdataPython |
1651604 | import os
from time import sleep
def clearConsole():
command = 'clear'
if os.name in ('nt', 'dos'): # If Machine is running on Windows, use cls
command = 'cls'
os.system(command)
def debug(positions):
for i in positions:
print(i)
def draw_logo():
print("""BEM VINDO AO
mm ... | StarcoderdataPython |
3532003 | import json
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models
from django_delta_logger import DeltaEventType
from django_delta_logger.fields import IntEnumField
class DeltaEventManager(models.Manager):
def ge... | StarcoderdataPython |
3378074 | <reponame>slamer59/dagster-mlflow<gh_stars>1-10
import pysftp
hostname = '127.0.0.1'
username = 'mlflow_user'
password = '<PASSWORD>'
with pysftp.Connection(hostname, username=username, password=password) as sftp:
print('ok')
with sftp.cd(''): # temporarily chdir to public
sftp.put('/mlflow... | StarcoderdataPython |
1757453 | SEP = ':'
def pair_key(p1, p2):
return p1 + SEP + p2 if p1 <= p2 else p2 + SEP + p1
def highest_affinity_pair(views):
user_views = dict()
affinity = dict()
mx = float('-inf')
best = None
for page, user in views:
if page in user_views.setdefault(user, {}):
continue
... | StarcoderdataPython |
11205901 | <filename>application/tests/test_domain/test_transactions.py
# TODO: write me
| StarcoderdataPython |
11206545 | <filename>criterion/WCELoss.py
# -*- coding: utf-8 -*-
"""
@description:最基本的CrossEntropyLoss
@author: LiuXin
@contact: <EMAIL>
@Created on: 2020/11/27 上午11:19
"""
import torch
import torch.nn as nn
class WCELoss(nn.Module):
def __init__(self,weight=None,*args,**kwargs):
super(WCELoss,self).__init__()
... | StarcoderdataPython |
6431388 | <gh_stars>10-100
# -*- coding: utf-8 -*-
# pragma pylint: disable=unused-argument, no-self-use
# (c) Copyright IBM Corp. 2010, 2018. All Rights Reserved.
"""Tests using pytest_resilient_circuits"""
from __future__ import print_function
import pytest
from mock import patch
from resilient_circuits.util import get_conf... | StarcoderdataPython |
1829307 | <gh_stars>0
from ratpacdbplot.split_matching_brackets import split_matching_brackets
def test_split_curly_braces():
text = "{abc} {def} {ghi}"
actual = list(split_matching_brackets(text))
expected = ["{abc}", " {def}", " {ghi}"]
assert expected == actual
def test_split_curly_braces_nested():
tex... | StarcoderdataPython |
11271343 | <gh_stars>0
import nmrpy.data_objects
import logging, traceback
import numpy
import scipy
from matplotlib import pyplot as plt
import numbers
from datetime import datetime
from matplotlib.figure import Figure
from mpl_toolkits.mplot3d import Axes3D
from matplotlib.collections import PolyCollection
import copy
from mat... | StarcoderdataPython |
11212003 | import xmlrpc as rpc_handle
class KVS:
def __init__(self, ip, port):
self.ip = ip
self.port = port
self.connection = rpc_handle.ServerProxy("http://" + ip + ":" + port + "/", allow_none = True)
def write(self,key,value):
return self.connection.write(key, value)
def read(self,key):
return self.connection.... | StarcoderdataPython |
25414 | <gh_stars>1-10
from django.shortcuts import render
from .models import Name
from .forms import NameForm
# Create your views here.
def i_was_here(request):
form=NameForm()
if request.method=="POST":
form=NameForm(request.POST)
if form.is_valid():
form.save()
names=Name.objects.... | StarcoderdataPython |
1610066 | <reponame>beproud/django-newauth<filename>tests/test_decorator.py<gh_stars>1-10
#:coding=utf-8:
from urllib.parse import urlparse
import pytest
from django.test import TestCase as DjangoTestCase
from django.conf import settings
__all__ = (
'DecoratorTest',
)
@pytest.mark.django_db
class DecoratorTest(DjangoTest... | StarcoderdataPython |
9616653 | import time
import random
from six.moves import input
from connect4.agent import minmax
from connect4 import c4types
from connect4.gamestate import GameState
from connect4.utils import print_board, print_move
from connect4.move import Move
def main():
rows = 6
cols = 7
game = GameState.new_game((rows, co... | StarcoderdataPython |
213966 | # Copyright 2019 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | StarcoderdataPython |
218657 | import math
import matplotlib.pyplot as plt
with open('datasets/hw2dataset_100.txt', 'r') as f:
all_text = f.read()
text = all_text.split('\n')[1:]
class Data:
def __init__(self, line):
line = line.split('\t')
self.weight = int(line[1])
self.height = int(line[2])
self.missing... | StarcoderdataPython |
8004645 | def override(cls):
"""Annotation for documenting method overrides.
Args:
cls (type): The superclass that provides the overridden method. If this
cls does not actually have the method, an error is raised.
"""
def check_override(method):
if method.__name__ not in dir(cls):
... | StarcoderdataPython |
396304 | <filename>biography/serializers/ideology.py
from biography.models import Ideology
from rest_framework import serializers
class IdeologySerializer(serializers.ModelSerializer):
class Meta:
model = Ideology
exclude = ('biography',)
| StarcoderdataPython |
11244730 | import hypothesis.strategies as st
from hypothesis import given, settings, note
from qiskit.circuit.library import CCXGate, CXGate, CSwapGate, HGate, SwapGate, CPhaseGate
#####################################################################################
### Change the file to import from, in order to test a mutant ... | StarcoderdataPython |
358341 | <gh_stars>0
def f(x):
for i in reversed([20, 19, 18, 17, 16, 15, 14, 13, 12, 11]):
if x % i != 0:
return False
return True
i = 20
while f(i) == False:
i += 20
print(i)
| StarcoderdataPython |
3513252 | from datetime import datetime, timezone
from django.conf import settings
from django.contrib.auth import get_user_model
from django.db import models
from django.urls import reverse
from django.utils.translation import gettext_lazy as _
User = get_user_model()
class TaskReport(models.Model):
WORKFLOW_STATE_QUEUE... | StarcoderdataPython |
5149270 | from django.db import models as m
from django.db.models.query import QuerySet
from django.utils import timezone
from django_lifecycle import LifecycleModelMixin
class Model(LifecycleModelMixin, m.Model):
def delete(self):
setattr(self, 'updated_at', timezone.now())
self.save()
class Meta:
... | StarcoderdataPython |
5122806 | # -*- coding: utf-8 -*
import sys
import importlib
#importlib.reload(sys)
#sys.setdefaultencoding("utf-8")
import unicodedata
class Thesaurus:
def __init__(self):
self.dictionnary = {}
def add_entry(self, word, synonyms):
self.dictionnary[word] = synonyms
def add_synonym_of... | StarcoderdataPython |
1781307 | <reponame>Guillaume-Fernandez/phishfinder<filename>venv/lib/python3.6/site-packages/clint/textui/formatters.py
# -*- coding: utf-8 -*-
"""
clint.textui.formatters
~~~~~~~~~~~~~~~~~~~~~~~
Core TextUI functionality for text formatting.
"""
from __future__ import absolute_import
from .colored import ColoredString, cl... | StarcoderdataPython |
8031012 | from django.test import TestCase
from django.contrib.auth import get_user_model
from django.test.client import Client
from django.urls import reverse
from ..accounts.models import UserProfile
from django.contrib.auth.models import Permission
from .models import IdentityAssuranceLevelDocumentation
class IALUpgradeTest... | StarcoderdataPython |
338171 | #
# voice-skill-sdk
#
# (C) 2021, Deutsche Telekom AG
#
# This file is distributed under the terms of the MIT license.
# For details see the file LICENSE in the top directory.
#
#
import json
import logging
import string
import random
from logging import makeLogRecord, INFO
from unittest.mock import patch
from fastapi... | StarcoderdataPython |
11352697 | from __init__ import *
import sys
import subprocess
import numpy as np
from fractions import Fraction
sys.path.insert(0, ROOT)
from compiler import *
from constructs import *
def pyramid_blending(pipe_data):
R = Parameter(Int, "R")
C = Parameter(Int, "C")
x = Variable(Int, "x")
y = Variable(Int, "y... | StarcoderdataPython |
3567635 | def UpdateMoManI(Model, SetNames, NewSetItems, NewSetGroups, IARList, OARList):
import pymongo
from bson.objectid import ObjectId
from bson.binary import Binary
import uuid
# Connect to the Mongodb daemon
client = pymongo.MongoClient()
# Connect to the momani database
db = ... | StarcoderdataPython |
9749885 | <reponame>formlio/forml
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "... | StarcoderdataPython |
6581446 | <filename>pypytorch/tensor.py
# -*- coding: utf-8 -*-
import numpy as np
import pypytorch.tensortype as tt
from pypytorch.torchnode import GradFn
from pypytorch.torchnode import TorchNode
from pypytorch.functions import *
from pypytorch import utils
def tensor(data, dtype=tt.float32, mu=0.0, sigma=1.0):
return ... | StarcoderdataPython |
11207201 | <reponame>dchaplinsky/vulyk-ner
#!env python
import argparse
import json
import logging
import re
import time
import glob
import pathlib
from typing import Any, Generator
from collections import namedtuple
from enum import Enum
from itertools import chain
from tokenize_uk import tokenize_text # type: ignore
log = l... | StarcoderdataPython |
9741950 | from toee import *
def OnBeginSpellCast(spell):
print "Angelskin OnBeginSpellCast"
print "spell.target_list=", spell.target_list
print "spell.caster=", spell.caster, " caster.level= ", spell.caster_level
def OnSpellEffect(spell):
print "Angelskin OnSpellEffect"
spell.duration = 1 * spell.caster_l... | StarcoderdataPython |
1630480 | # encoding: utf-8
"""Unit test suite for `cr.cube.stripe.assembler` module."""
import numpy as np
import pytest
from cr.cube.cube import Cube
from cr.cube.dimension import Dimension, _Element, _OrderSpec, _Subtotal
from cr.cube.enums import COLLATION_METHOD as CM
from cr.cube.stripe.assembler import (
StripeAsse... | StarcoderdataPython |
4940141 | <reponame>excitedleigh/giki<filename>giki/web.py<gh_stars>0
from .core import PageNotFound
from .formatter import format, get_names
from jinja2 import Environment, PackageLoader
from StringIO import StringIO
from traceback import print_exc
from werkzeug.wrappers import Response
from werkzeug.utils import redirect
from... | StarcoderdataPython |
3509789 | <filename>lyricpys.py
# MIT License
#
# Copyright (c) 2021 <NAME> All Rights Reserved.
# Distributed under the terms of the MIT License.
#
# lyricpys - song lyrics engine interpreter (implementation of lyricpps)
# -----------------------------------------
# lyricpys uses tree to store datas instead of plain-text parsin... | StarcoderdataPython |
8065262 | import json
import multiprocessing
from contextlib import closing
from multiprocessing import Pool
from os.path import isdir, isfile, basename, join
from typing import List
import requests
from requests import ReadTimeout, Timeout, HTTPError, RequestException
from tenacity import retry, wait_exponential, stop_after_at... | StarcoderdataPython |
237585 | <gh_stars>10-100
import os
import logging
import pkg_resources
from deluge.plugins.pluginbase import WebPluginBase
log = logging.getLogger(__name__)
def get_resource(filename):
return pkg_resources.resource_filename('updatorr', os.path.join('data', filename))
class WebUI(WebPluginBase):
scripts = [get_reso... | StarcoderdataPython |
9623716 | #!/usr/bin/env python
import sys
import json
from pprint import pprint
import requests
from extractor import Extractor
from crawler import Crawler
def crawl_school_programs(data):
programs = []
for program in data:
pprint(program)
if program.has_key('text'):
programs.append(program)
continue... | StarcoderdataPython |
8167893 | <filename>pagination.py
from collections import OrderedDict
from rest_framework.response import Response
from rest_framework.pagination import PageNumberPagination
# 1. 配置settings
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'conf.pagination.GlobalPageNumberPagination',
'PAGE_SIZE': 10,
'MAX_PAGE_SIZE':... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.