id stringlengths 1 7 | text stringlengths 6 1.03M | dataset_id stringclasses 1
value |
|---|---|---|
3266262 | <reponame>niyiwei/python-study
def countWords(fileName):
try:
with open(fileName,"r") as fObj:
contents = fObj.read()
except FileNotFoundError:
#pass语句,可以在代码快中使用它来让Python什么都不做
pass
# msg = "Sorry, the file "+ fileName + " does not exist.";
# print(msg);
else:
# 计算文件大致包含多少个单词
words = contents.split()... | StarcoderdataPython |
11821 | <reponame>Lisa-pa/SAMAE
"""Standard test images.
"""
import os
from skimage.io import imread
data_dir = os.path.abspath(os.path.dirname(__file__))
__all__ = ['data_dir', 'circle', 'skmuscimg']
def _load(f, as_gray=False):
"""Load an image file located in the data directory.
Parameters
----------
... | StarcoderdataPython |
146019 | # Write your frequency_dictionary function here:
def frequency_dictionary(words):
freqs = {}
for word in words:
if word not in freqs:
freqs[word] = 0
freqs[word] += 1
return freqs
# Uncomment these function calls to test your function:
print(frequency_dictionary(["apple", "apple", "cat", 1]))
# sho... | StarcoderdataPython |
1785538 | <reponame>alitariqbsc06/mmclassification
# model settings
model = dict(
type='ImageClassifier',
backbone=dict(
type='ResNet',
depth=50,
num_stages=4,
out_indices=(3, ),
style='pytorch'),
neck=dict(type='GlobalAveragePooling'),
head=dict(
type='MultiLabelLi... | StarcoderdataPython |
3314628 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# ---
# Flask app factory from:
# https://github.com/mattupstate/overholt/blob/master/overholt/factory.py
# ---
#
# MIT License
#
# Copyright (C) 2013 by <NAME>
# Copyright (C) 2014 by <NAME>
#
# Permission is hereby granted, free of charge, to any person
# obtaining a co... | StarcoderdataPython |
114925 | <gh_stars>0
import pandas as pd
import os
from scipy.sparse import csr_matrix
from scipy.sparse import save_npz
from sklearn.neighbors import NearestNeighbors
import numpy as np
from sklearn.externals import joblib
class initalizer:
def __init__(self, items_csv_path="../data/new_movies.csv", ratings_csv_path="../... | StarcoderdataPython |
3335537 | <gh_stars>0
# Bot written to play the game using what seems to be the best strategy according to the authors.
import MLModifiedSpaceShooter as game
import numpy as np
def playGame():
game_state = game.GameState()
todo = 0
counter = 0
while True:
if counter > 12:
counter = 0
... | StarcoderdataPython |
1796046 | # Protocol Buffers - Google's data interchange format
# Copyright 2008 Google Inc.
# http://code.google.com/p/protobuf/
#
# 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.apa... | StarcoderdataPython |
3350939 | import torch.nn.functional as F
from collections import OrderedDict
import numpy as np
class InputPadder:
"""Pads images such that dimensions are divisible by 8 , from RAFT."""
def __init__(self, dims, mode='sintel'):
self.ht, self.wd = dims[-2:]
pad_ht = (((self.ht // 8) + 1) * 8 - self.ht) ... | StarcoderdataPython |
1642264 | <reponame>philippjfr/idom-bokeh
from .panel import IDOM
__author__ = "idom-team"
__version__ = "0.0.1" # DO NOT MODIFY
__all__ = ["IDOM"]
| StarcoderdataPython |
1689153 | import requests
data = {
"chat_id": chat_id,
"chat_keypad_type": "Removed",
}
url = f'https://messengerg2b1.iranlms.ir/v3/{token}/editChatKeypad'
response = requests.post(url, data=data)
print(response.text)
| StarcoderdataPython |
115375 | <filename>gotime/maps.py
import requests
import time
class BaseMapsApi(object):
def __init__(self):
pass
def format_data(self, key, origin, destination, model=None, now_secs=None):
data = {'key': key,
'origin': origin.replace(' ', '+'),
'destination': destinati... | StarcoderdataPython |
1655217 | <gh_stars>1-10
import gitbigfile
try:
from setuptools import setup
kw = {
'install_requires': 'docopt == 0.5.0',
}
except ImportError:
from distutils.core import setup
kw = {}
setup(
name='git-bigfile',
version=gitbigfile.__version__,
author='<NAME>',
author_email='<EMAIL>'... | StarcoderdataPython |
3368152 | <reponame>techthiyanes/textacy
import pytest
import textacy
import textacy.text_stats
@pytest.fixture(scope="module")
def doc(lang_en):
text = "I write code. They wrote books."
return textacy.make_spacy_doc(text, lang=lang_en)
def test_morph(doc):
exp = {
"Case": {"Nom": 2},
"Number": {... | StarcoderdataPython |
11952 | # Copyright 2020 Google LLC. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... | StarcoderdataPython |
3363769 | <reponame>MauroCL75/Gerald<gh_stars>0
"""
Introduction
============
Capture, document and manage database schemas.
This is the Schema module, it contains one useful class, Schema. This is a
super class which is then sub-classed for specific databases (eg.
OracleSchema, MySQLSchema, etc).
A schema is compr... | StarcoderdataPython |
1763971 | <reponame>huachao2017/goodsdl
# -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2019-05-06 13:54
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('goods', '0065_shelfimage_image_name'),
]
operations =... | StarcoderdataPython |
74180 | """
Data access functions
---------------------
"""
from __future__ import absolute_import
from os.path import join as pjoin, basename, dirname
import subprocess
import tempfile
import logging
import numpy as np
import h5py
import rasterio
from rasterio.crs import CRS
from rasterio.warp import reproject
from rasterio... | StarcoderdataPython |
1615004 | <filename>dnd.py
#!/usr/bin/env python3
import argparse
import json
from helpers.spells import *
from helpers.classes import *
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument('-c', '--dndclass', help="Get all spells for a certain class")
parser.add_argument('-l', '--level', help="Sp... | StarcoderdataPython |
1707374 | import logging
import os
import requests
import json
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, CallbackContext
from texts import get_manual_do_membro
TOKEN = os.environ['TELEGRAM_TOKEN']
PORT = int(os.environ.get("PORT", "8443"))
HEROKU_APP_NAME = os.environ.get("bot-telegram-turing"... | StarcoderdataPython |
3343104 | from docsie_universal_importer.providers.base import StorageTreeView, ImporterView
from .import_provider import BitbucketProvider
storage_view = StorageTreeView.provider_view(BitbucketProvider)
importer_view = ImporterView.provider_view(BitbucketProvider)
| StarcoderdataPython |
1688471 | from gna.ui import basecmd
from gna.env import env
import ROOT
import numpy as np
import scipy.misc
from scipy.stats import poisson
import gna.constructors as C
class cmd(basecmd):
@classmethod
def initparser(cls, parser, env):
parser.add_argument('--name', required=True)
parser.add_argument('-... | StarcoderdataPython |
3256085 | <reponame>ZRHonor/pytorch_resnet_cifar10<gh_stars>0
from torch.nn import CrossEntropyLoss
from torch import nn
import numpy as np
import torch
class CBCELoss(nn.Module):
def __init__(self, lt_factor, num_classes) -> None:
super(CBCELoss).__init__()
weight = np.linspace(1/lt_factor, 1, num=num_class... | StarcoderdataPython |
1684176 | <filename>lib/galaxy/model/migrate/versions/0080_quota_tables.py
"""
Migration script to create tables for disk quotas.
"""
from __future__ import print_function
import datetime
import logging
from sqlalchemy import BigInteger, Boolean, Column, DateTime, ForeignKey, Integer, MetaData, String, Table, TEXT
now = datet... | StarcoderdataPython |
3394199 | from .evaluator import MultiScaleEvaluator | StarcoderdataPython |
72016 | """Arithmetic Coding
Functions for doing compression using arithmetic coding.
http://en.wikipedia.org/wiki/Arithmetic_coding
The functions and classes all need predictive models; see model.py
"""
import math
import itertools
from seq_predict import CTW
def grouper(n, iterable, fillvalue=None):
args = [iter(ite... | StarcoderdataPython |
3334109 | import re
from textwrap import dedent, indent
import click as cl
def run_file(text):
"""Evaluate a Bayes file."""
global file_vars, env
file_vars = {}
env = {"__builtins__": {}}
# extract code chunks from text, combine, and sort by position
chunks = extract_chunks(text)
hypotheses = {}
... | StarcoderdataPython |
10950 | # Copyright 2013 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 DEPS
CONFIG_CTX = DEPS['gclient'].CONFIG_CTX
ChromiumGitURL = DEPS['gclient'].config.ChromiumGitURL
@CONFIG_CTX()
def v8(c):
soln = c.solutions.ad... | StarcoderdataPython |
128401 | <gh_stars>1-10
import os
import subprocess
from nmigen.build import *
from nmigen.vendor.lattice_ecp5 import *
from nmigen_boards.resources import *
from ..gateware.ft600 import FT600Resource
__all__ = ["KilsythPlatform"]
class KilsythPlatform(LatticeECP5Platform):
device = "LFE5U-45F"
package = "... | StarcoderdataPython |
4803505 | <filename>src/api/filters/FilterScopes.py
class FilterScopes:
filter_scopes = {
'user:read': ['name', 'email'],
'manager': ['name', 'email', 'password']
}
def filter(self, response):
if 'error' in response:
return response
token = self.get_token()
sco... | StarcoderdataPython |
3276066 | <reponame>RoastVeg/cports
pkgname = "xbitmaps"
pkgver = "1.1.2"
pkgrel = 0
build_style = "gnu_configure"
hostmakedepends = ["pkgconf"]
pkgdesc = "Common X11 bitmaps"
maintainer = "q66 <<EMAIL>>"
license = "MIT"
url = "https://xorg.freedesktop.org"
source = f"$(XORG_SITE)/data/{pkgname}-{pkgver}.tar.bz2"
sha256 = "b9f0c... | StarcoderdataPython |
3314917 | <filename>multiband_melgan/utils.py
def repeat(iterable):
while True:
for x in iterable:
yield x
| StarcoderdataPython |
114019 | <reponame>damnit/pymite
# -*- coding: utf-8 -*-
# File: test_daily_adapter.py
""" daily adapter test module. """
import urllib.request
from .conftest import mock_urlopen, _get_url
from pymite.adapters import Daily
def test_daily_setup(libfactory):
""" Test tracker setup. """
factory = libfactory.daily_adapte... | StarcoderdataPython |
1681566 | <filename>nahamconctf/2021/ngrocket/client.py
#!/usr/bin/env python3
import time
from pwn import *
target = b'HOST:PORT'
while True:
conn = remote('challenge.nahamcon.com', 0)
conn.recv()
conn.recv()
conn.send(target)
data = conn.recvuntil(b'ngrocket')
print(data)
conn.close()
time... | StarcoderdataPython |
3253558 | # -*- coding: utf-8 -*-
# Generated by Django 1.9.1 on 2017-08-30 13:35
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('frontend', '0024_measure_tags'),
('frontend', '0028_prescription_net_cost'),
]
opera... | StarcoderdataPython |
3245653 | <gh_stars>1-10
from enum import Enum
from json import loads
from typing import List, Dict
import numpy as np
from tdw.tdw_utils import TDWUtils
from tdw.output_data import OutputData, Bounds, Raycast, SegmentationColors, Magnebot
from magnebot.arm import Arm
from magnebot.util import get_data
from magnebot.ik.orientati... | StarcoderdataPython |
38183 | <gh_stars>0
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import binned_statistic
def var_correct(qso, rest_ranges=None, zq_range=[1.6, 4.], fit_model=True,
savefile=False):
""" Corrections to the vriance assigned to the pixels by the pipeline
Notes:
1. Scaling s... | StarcoderdataPython |
1714904 | <filename>scripts/dataex_list_user_preferences.py
#!/usr/bin/env python3
import json
import click
import requests
from yaspin import yaspin
from dataexclient.auth import auth
from dataexclient import auth_helper
from dataexclient.utils import check_error, check_output_format
from dataexclient.config import GET_REGI... | StarcoderdataPython |
1656898 | # Generated by Django 2.2.6 on 2021-04-13 11:04
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('control', '0039_auto_20201203_0057'),
]
operations = [
migrations.AlterUniqueTogether(
name='agentadmin',
unique_together={(... | StarcoderdataPython |
1687703 | #!/usr/bin/python3
import unittest
from pypcep.pcep_parser import parse_pcep, PCEPMessageType
PCEP_OPEN_MSG = [
'0x20', '0x01', '0x00', '0x50', '0x01', '0x10', '0x00', '0x4c',
'0x20', '0x1e', '0x78', '0x01', '0x00', '0x10', '0x00', '0x04',
'0x00', '0x00', '0x01', '0xc5', '0x00', '0x18', '0x00', '0x10',
... | StarcoderdataPython |
1762081 | <gh_stars>1-10
from django.contrib.auth.models import User
from django.db import models
from django_extensions.db.fields import AutoSlugField
from apps.government.models import Government
from apps.core.models import BaseData
from apps.contacts.models import Contact
from datetime import datetime
from django.utils impor... | StarcoderdataPython |
3234805 | <filename>ldndc2nc/extra.py
# -*- coding: utf-8 -*-
"""ldndc2nc.extra: extra module within the ldndc2nc package."""
import logging
import os
from pkg_resources import Requirement, resource_filename
import shutil
import string
import numpy as np
import param
import yaml
log = logging.getLogger(__name__)
def enum(*s... | StarcoderdataPython |
3224778 | #!/usr/bin/env python
# encoding: utf-8
"""
@version: v1.0
@author: xag
@license: Apache Licence
@contact: <EMAIL>
@site: http://www.xingag.top
@software: PyCharm
@file: views.py
@time: 2018/7/23 21:20
@description:TODO
"""
import qiniu
from flask import (
Blueprint,
jsonify
)
bp = Blueprint('common',... | StarcoderdataPython |
3380831 | import pytest
from metrics_layer.core.model.project import AccessDeniedOrDoesNotExistException
@pytest.mark.query
def test_query_no_join_with_limit(connection):
query = connection.get_sql_query(metrics=["total_item_revenue"], dimensions=["channel"], limit=499)
correct = (
"SELECT order_lines.sales_... | StarcoderdataPython |
4820307 | <reponame>sanger-tol/weskit-api
# Copyright (c) 2021. Berlin Institute of Health (BIH) and Deutsches Krebsforschungszentrum (DKFZ).
#
# Distributed under the MIT License. Full text at
#
# https://gitlab.com/one-touch-pipeline/weskit/api/-/blob/master/LICENSE
#
# Authors: The WESkit Team
import uuid
import pyte... | StarcoderdataPython |
1757992 | <reponame>Julio-Yanes/NiMARE
import os
import pathlib
import click
from nilearn.image import resample_to_img
from nilearn.masking import apply_mask
from ..base import MetaResult
from ..meta.ibma import rfx_glm
from ..meta.cbma import Peaks2MapsKernel
from ..io import convert_sleuth_to_dataset
n_iters_default = 10000
... | StarcoderdataPython |
1707155 | from .modeconvo import ModeConvo
class ModeTalkWin3(ModeConvo):
pass
| StarcoderdataPython |
38054 | <reponame>kevin-ci/advent-of-code-2020<gh_stars>0
import re
input = """iyr:2010 ecl:gry hgt:181cm
pid:591597745 byr:1920 hcl:#6b5442 eyr:2029 cid:123
cid:223 byr:1927
hgt:177cm hcl:#602927 iyr:2016 pid:404183620
ecl:amb
eyr:2020
byr:1998
ecl:hzl
cid:178 hcl:#a97842 iyr:2014 hgt:166cm pid:594143498 eyr:2030
ecl:hzl
... | StarcoderdataPython |
173479 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.4'
# jupytext_version: 1.1.4
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# # s_co... | StarcoderdataPython |
3269976 | """ do book related things with other users """
from django.apps import apps
from django.db import models, IntegrityError, transaction
from django.db.models import Q
from bookwyrm.settings import DOMAIN
from .base_model import BookWyrmModel
from . import fields
from .relationship import UserBlocks
class Group(BookWyr... | StarcoderdataPython |
197024 | import numpy as np
from numpy import linalg
from gym import utils
import os
from gym.envs.mujoco import mujoco_env
import math
#from gym_reinmav.envs.mujoco import MujocoQuadEnv
# For testing whether a number is close to zero
_FLOAT_EPS = np.finfo(np.float64).eps
_EPS4 = _FLOAT_EPS * 4.0
class BallBouncingQuadEnv(mu... | StarcoderdataPython |
1689866 | <reponame>PENGUINLIONG/tinyspv
from re import match
HEADERS = []
op_names = []
with open("./include/tinyspv/spirv/unified1/spirv.hpp") as f:
lines = [x.strip() for x in f.readlines()]
for line in lines:
if not line.startswith("//"):
break
HEADERS += [line]
for line in lines:
... | StarcoderdataPython |
62290 | # -*- coding: utf-8 -*-
import re
from mattermost_bot.bot import respond_to
@respond_to('(.*) added to the channel by (.*)', re.IGNORECASE)
def added_to_channel(message, myname, channel_admin):
message.reply('Hi, %s. I am %s. Glad to join this channel :) ' % (channel_admin, myname))
added_to_channel.__doc__ = ... | StarcoderdataPython |
3318739 | from securitytxt.parsers.textparsers.comment_line_parser import CommentLineParser
from securitytxt.parsers.textparsers.field_line_parser import FieldLineParser
from securitytxt.parsers.textparsers.signed_text_parser import SignedTextParser
from securitytxt.securitytxt import SecurityTXT
class FileParser:
"""Takes... | StarcoderdataPython |
3212393 | from .BidirectionalLSTM import BidirectionalLSTM
| StarcoderdataPython |
3222810 | """Functions for evaluating the cifar10 CNN model."""
import tensorflow as tf
from cifar10_input import Cifar10Data
def evaluation(logits, labels):
"""
Evaluates image inference model.
:param logits: A tensor of shape [BATCH_SIZE, NUM_CLASS], float32, each row represents an image inference
:param lab... | StarcoderdataPython |
4835369 | <reponame>sethmlarson/selectors2<filename>tests/support.py
import os
import signal
import socket
import threading
import time
__all__ = [
"get_time",
"resource",
"socketpair",
"AlarmMixin",
"TimerMixin"
]
# Tolerance values for timer/speed fluctuations.
TOLERANCE = 0.5
# Detect whether we're runn... | StarcoderdataPython |
3290430 | from c2d_clang2c_ast import *
from typing import List, Dict, Set
import copy
class UnaryExtractorNodeLister(NodeVisitor):
def __init__(self):
self.nodes: List[UnOp] = []
def visit_UnOp(self, node: UnOp):
if node.op in ["++", "--"]:
self.nodes.append(node)
return self.gener... | StarcoderdataPython |
164605 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
from frappe.utils import cstr, getdate
from frappe import _
from erpnext.stock.utils import get_valid_serial_nos
from erpnext.utilities... | StarcoderdataPython |
86370 | <filename>setup.py
from setuptools import setup, find_packages
REQUIRED_PYTHON = (3, 6, 4)
EXCLUDE_FROM_PACKAGES = []
try:
with open('LICENSE.txt', 'r') as f:
_license = f.read()
except:
_license = ''
try:
with open('README.md', 'r') as f:
_readme = f.read()
except:
_readme = ''
setup... | StarcoderdataPython |
1610820 | class ConsumeException(Exception):
def __init__(self, message):
self.__message = message
def __str__(self):
return repr(self.__message)
def get_message(self):
return self.__message
| StarcoderdataPython |
1721731 | <filename>projects/democv/calibrate.py
import numpy as np
import cv2
# termination criteria
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 30, 0.001)
# prepare object points, like (0,0,0), (1,0,0), (2,0,0) ....,(6,5,0)
objp = np.zeros((8*6,3), np.float32)
objp[:,:2] = np.mgrid[0:6,0:8].T.reshape(-1,2... | StarcoderdataPython |
1791262 | <reponame>lunduniversity/schoolprog-satellite
temps = []
with open("data_april_2017_lund.txt", "r") as f:
# print(f.read().split("\n")[:-1])
temps = list(map(lambda x: float(x.split()[3]), f.read().split("\n")[:-1]))
print(temps)
with open("temps_april_2017_lund.txt", "w") as f:
for i in range(len(temps))... | StarcoderdataPython |
1739010 | <reponame>hujingguang/Archery
# -*- coding: UTF-8 -*-
"""
@author: hhyo、yyukai
@license: Apache Licence
@file: redis.py
@time: 2019/03/26
"""
import re
import redis
import logging
import traceback
from common.utils.timer import FuncTimer
from . import EngineBase
from .models import ResultSet, ReviewSet, ReviewResult... | StarcoderdataPython |
1685110 | <filename>yuntu/models.py
from django.db import models
class Index(models.Model):
master_title = models.CharField(max_length=50)
slave_title = models.CharField(max_length=200)
about_us_string = models.TextField()
contact_us_address = models.CharField(max_length=500)
contact_us_email = models.CharF... | StarcoderdataPython |
4838401 | import factory
from factory import Faker
from factory.django import DjangoModelFactory
from ..models import Agency, Correspondence, RecordRequest, RecordRequestFile
class AgencyFactory(DjangoModelFactory):
class Meta:
model = Agency
name = Faker("company")
class RecordRequestFactory(DjangoModelFac... | StarcoderdataPython |
3276967 | <reponame>jim/documenters-aggregator<filename>tests/test_chi_school_community_action_council.py<gh_stars>0
from datetime import datetime
import pytest
from freezegun import freeze_time
from tests.utils import file_response
from city_scrapers.spiders.chi_school_community_action_council import Chi_school_community_actio... | StarcoderdataPython |
3205906 | import copy
import torch.nn as nn
from models.glt_models import LinearClassifier
from models.resnet_blocks import BasicBlock, Bottleneck, DownsampleConv2d
from models.svdo_layers import LinearSVDO, Conv2dSVDO
class SequentialSparsifier(nn.Module):
def __init__(self, pretrained_model):
super(SequentialSp... | StarcoderdataPython |
1742266 | # Copyright 2018 Intel 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 writi... | StarcoderdataPython |
3253645 | from django.apps import AppConfig
from cmsplugin_text_ng.type_registry import register_type
class CmsPluginTextNgConfig(AppConfig):
name = 'cmsplugin_text_ng'
verbose_name = "Django Cms Plugin Text-NG"
def ready(self):
from cmsplugin_text_ng.models import TextNGVariableText
register_type... | StarcoderdataPython |
1688740 | from mrjob.job import MRJob
class MRCcounter(MRJob):
def mapper(self, key, value):
for phrase in value.split('.')[:-1]:
yield 'phrase', 1
for word in phrase.split(' '):
yield 'word', 1
yield 'characters', len(word)
def reducer(self, key, valu... | StarcoderdataPython |
1667408 | # !/usr/bin/env python
# -*-coding:utf8 -*-
"""
Front controller
"""
class Dispatcher(object):
frontcontroller = None
module = "default"
controller = "default"
action = "index"
isDispatched = False
def __init__(self, frontcontroller):
"""
"""
self.frontcontroller = fro... | StarcoderdataPython |
3332295 | from __future__ import print_function
import itertools
import os
import sys
from functools import wraps
from ruskit import cli
NO_RETRY = -1
COLOR_MAP = {
"red": 31,
"green": 32,
"yellow": 33,
"blue": 34,
"purple": 35
}
def echo(*values, **kwargs):
end = kwargs.get("end", '\n')
color... | StarcoderdataPython |
3225098 | <filename>python_tests/test_input.py
from __future__ import print_function
import dynet as dy
import numpy as np
input_vals = np.arange(81)
squared_norm = (input_vals**2).sum()
shapes = [(81,), (3, 27), (3, 3, 9), (3, 3, 3, 3)]
for i in range(4):
# Not batched
dy.renew_cg()
input_tensor = input_vals.reshap... | StarcoderdataPython |
3297995 | <reponame>davidbarkhuizen/pytxt2html<gh_stars>1-10
source_file_path = '/home/mage/Downloads/c0.txt'
template = '''<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>{{title}}</title>
</head>
<body class='bodyStyle'>{{body}}</body>
<style>{{style}}</style>
</html>'''
br = '<br>'
title = 'c0'
style =... | StarcoderdataPython |
34468 | <reponame>verycourt/Elections
#!/usr/bin/python
# encoding=utf8
import sys
reload(sys)
sys.setdefaultencoding('utf8')
import requests
from bs4 import BeautifulSoup
import numpy as np
import pandas as pd
import warnings
import dateparser
import datetime
import time
import json
from json import encoder
encoder.FLOAT_RE... | StarcoderdataPython |
50039 | <reponame>Chicone/SSM-VPR<filename>ssmbase.py
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'ssm.ui'
#
# Created by: PyQt5 UI code generator 5.9.2
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def se... | StarcoderdataPython |
1696677 | from plenum.test.node_request.helper import sdk_ensure_pool_functional
from plenum.test.helper import sdk_send_random_and_check, sdk_send_random_requests, \
sdk_eval_timeout, sdk_get_and_check_replies
from plenum.test.node_catchup.helper import ensure_all_nodes_have_same_data
from plenum.test.pool_transactions.hel... | StarcoderdataPython |
3207127 | <reponame>ngi-nix/liberaforms
"""
This file is part of LiberaForms.
# SPDX-FileCopyrightText: 2021 LiberaForms.org
# SPDX-License-Identifier: AGPL-3.0-or-later
"""
import os
import pytest
from liberaforms.models.user import User
from liberaforms.models.formuser import FormUser
from .utils import login, logout
class ... | StarcoderdataPython |
1733603 | <filename>styn/tests/build_scripts/annotation_misuse_2.py
from styn import chore
@chore()
def clean():
pass
# Should be marked as chore.
def html():
pass
# References a non chore.
@chore(clean, html)
def android():
pass
| StarcoderdataPython |
141425 | import dash
import dash as html
import dash as dcc
from dash import dash_table
from dash.dependencies import Input, Output
import plotly.graph_objs as go
import pandas as pd
import datetime
import mysql.connector
import os,io
#============================================================================================... | StarcoderdataPython |
119322 | <reponame>amirmallaei/recipe-app-api
from django.test import TestCase
from django.contrib.auth import get_user_model
from django.urls import reverse
from rest_framework.test import APIClient
from rest_framework import status
CREATE_USER_URL = reverse('user:create')
TOKEN_URL = reverse('user:token')
ME_URL = reverse(... | StarcoderdataPython |
1743316 | <reponame>pyccel/psydac
# coding: utf-8
import sys
import os
import importlib
import inspect
import numpy as np
from functools import lru_cache
from mpi4py import MPI
from sympy import Mul, Tuple
from sympy import Mod as sy_Mod, Abs, Range, Symbol, Max
from sympy import Function, Integer
from psydac.pyccel.ast.... | StarcoderdataPython |
3357257 | """
Genetic Programming for Quant
Author: UePG
Reference:
[1] https://gplearn.readthedocs.io/en/stable/
[2] <NAME>, "Genetic Programming", 1992.
"""
__version__ = "0.1.4"
__all__ = ["Function", "Fitness", "Backtester", "SymbolicRegressor"]
| StarcoderdataPython |
1719276 | <reponame>mingkaic/tenncor
import re
import logging
from tools.gen.plugin_base import PluginBase
from tools.gen.file_rep import FileRep
from plugins.template import build_template
from plugins.apis import api_header
from plugins.common import order_classes, reference_classes
from plugins.cformat.funcs import render_d... | StarcoderdataPython |
1790251 | import numpy as np
import pandas as pd
def compute_sprns_array(cells_file, spk_f_names, f_out_r, t_start, t_stop, bin_size):
cells_db = pd.read_csv(cells_file, sep=' ')
t_bins = np.arange(t_start, t_stop, bin_size)
r_data = np.zeros( (len(cells_db.index), t_bins[:-1].size) )
t = np.array([])
gid... | StarcoderdataPython |
157670 | <filename>queues/queues_two_stacks.py
class Stack:
def __init__(self):
self.data = []
def pop(self):
if self.is_empty():
return None
val = self.data[len(self.data)-1]
self.data = self.data[:len(self.data)-1]
return val
def peek(self):
if self.is_... | StarcoderdataPython |
1697370 | <reponame>jgurtowski/pbcore_python
from nose.tools import assert_equal, assert_true, assert_false
from pbcore import data
from pbcore.io import FastaReader, FastaWriter, FastaRecord
from StringIO import StringIO
class TestFastaRecord:
def setup(self):
self.name = "chr1|blah|blah"
self.sequence = "... | StarcoderdataPython |
1607674 | #IMPORTING REQUIRED MODULES
import mysql.connector
import datetime
import pyautogui
#CONNECTING TO DB AND CREATING CURSOR OBJECT
mycon = mysql.connector.connect(user='root',passwd='',host='localhost',database='hotel_management')
cursor = mycon.cursor()
#DEFINING GLOBAL VARIABLES NEEDED
global action
global... | StarcoderdataPython |
1690555 | <reponame>dpleshkov/programming-class
class Furniture:
def __init__(self, name, width, height, material, quantity):
self.name = name
self.width = width
self.height = height
self.material = material
self.quantity = quantity | StarcoderdataPython |
1670610 | # IMPORTS
from flask import Flask, jsonify, request
import logging.handlers
import datetime
from mongoSetup import Patient
from pymodm import errors
from pymodm import connect
# FLASK SERVER SETUP
app = Flask(__name__)
formatter = logging.Formatter(
"[%(asctime)s] {%(pathname)s:%(lineno)d} %(levelname)s - %(messag... | StarcoderdataPython |
1795837 | <gh_stars>1-10
import hashlib, json
from collections import OrderedDict
class MerkleTree:
def __init__(self, listoftransaction=None):
self.listoftransaction = listoftransaction
self.ordered_transaction = OrderedDict()
def create(self):
listoftransaction = self.listoftransaction
... | StarcoderdataPython |
4840926 | <filename>test/test_admin_host.py<gh_stars>1-10
#!/usr/bin/env python
#
# ___INFO__MARK_BEGIN__
#######################################################################################
# Copyright 2016-2021 Univa Corporation (acquired and owned by Altair Engineering Inc.)
# Licensed under the Apache License, Version 2... | StarcoderdataPython |
1709680 | <filename>services/evaluation/ocr_evaluation_service.py<gh_stars>1-10
import os
from typing import List, Dict
import csv
import torch
from scipy import spatial
import numpy as np
from entities.batch_representation import BatchRepresentation
from enums.evaluation_type import EvaluationType
from enums.metric_type impo... | StarcoderdataPython |
1783206 | /home/runner/.cache/pip/pool/5b/9f/71/72b1957fed5e77d1644200b1816d1df5ada510d6b11d4a58540676c34d | StarcoderdataPython |
186501 | import unittest
from osm_export_tool.sources import Overpass
from osm_export_tool.mapping import Mapping
class TestMappingToOverpass(unittest.TestCase):
def test_mapping(self):
y = '''
buildings:
types:
- points
select:
- column1
... | StarcoderdataPython |
1692044 | <filename>Algorithm1B.py
'''
Copyright (c) 2020 <NAME> (<NAME>
@file Algorithm1B.py
@date 2020/03/08
@brief Lane detection application
@license This project is released under the BSD-3-Clause license.
'''
import numpy as np
import cv2
'''
@brief Application which detects and overlays road lan... | StarcoderdataPython |
3213806 | <gh_stars>1-10
import unittest
from translate.factory import get_translator
youdao = get_translator('youdao')
class YoudaoTest(unittest.TestCase):
def test_query(self):
youdao.query('hello')
self.assertTrue('发音' in youdao.format())
self.assertTrue('helˈō' in youdao.format())
self... | StarcoderdataPython |
192448 | n#!/usr/bin/env python
# Copyright (c) 2014-2016 <NAME>
# 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, m... | StarcoderdataPython |
3269562 | <reponame>chechir/doors
import datetime
import re
import numpy as np
import pandas as pd
import pytz
def get_day_of_year(dates):
return _get_timestamp_attribute(dates, "dayofyear")
def get_day_of_week(dates):
return pd.Series(dates).apply(lambda x: x.weekday()).values
def get_hour(dates):
return _get... | StarcoderdataPython |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.