text stringlengths 2 999k |
|---|
import codecs
import json
import os
import re
import yaml
class SourceConfig(object):
def __init__(self, path = None, index_filename = None):
self.path = path or 'src'
self.index_filename = index_filename or 'index'
class OutputConfig(object):
def __init__(self, path = N... |
"""
Convert BureauStructure block data from this schema:
{
'last_updated_date': datetime.date,
'download_image': <primary key to Wagtail document>
'director': string,
'divisions': [
{
'division': string,
'division_lead': string,
'title': {
'li... |
# *-- coding: utf-8 --*
import logging
import asyncio
import time
from feeluown.app import App
from fuocore.player import MpvPlayer as Player, State
from fuocore.models import SongModel
from PyQt5.QtCore import QObject
from .rpc import DiscordIpcClient, DiscordIpcError
logger = logging.getLogger(__name__)
CLIENT_ID ... |
import numpy as np
import pytest
from shapely import GeometryCollection, LineString, Point, wkt
from shapely.geometry import shape
@pytest.fixture()
def geometrycollection_geojson():
return {
"type": "GeometryCollection",
"geometries": [
{"type": "Point", "coordinates": (0, 3, 0)},
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Copyright 2014-2019 OpenEEmeter contributors
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/LIC... |
from django.db import models
from django.utils import timezone
# Create your models here.
class BaseModel(models.Model):
class Meta:
abstract = True
create_time = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
update_time = models.DateTimeField(auto_now=True, verbose_name="修改时间")
... |
import pandas as pd
import plotly.graph_objects as go
import streamlit as st
from pandas.api.types import is_numeric_dtype
#ダッシュボードの生成
def main():
st.set_page_config(layout="wide")
#タイトルの表示
st.title("DashBoard using Streamlit")
#制作者の表示
st.text("Created by Tatsuya NISHIZAWA")
#ダッシュボードの説明の表示
... |
"""I remember this being asked at my Farmwise interview. I nailed this question using the hash method. But they still needed more with the binary search and sorting method. Sigh."""
def three_sum(number_list, required_sum):
"""Three sum question using hashing method.
Parameters
----------
number... |
#!/usr/bin/env python3
# Copyright (c) 2017 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test debug logging."""
import os
from test_framework.test_framework import UnitETestFramework
class Loggi... |
# -*- coding: utf-8 -*-
# File: __init__.py
# https://github.com/celery/kombu/blob/7d13f9b95d0b50c94393b962e6def928511bfda6/kombu/__init__.py#L34-L36
STATICA_HACK = True
globals()['kcah_acitats'[::-1].upper()] = False
if STATICA_HACK:
from .base import *
from .common import *
from .format import *
fr... |
# RUN: %PYTHON %s
import absl.testing
import numpy
import test_util
model_path = "https://tfhub.dev/google/lite-model/movenet/singlepose/lightning/3?lite-format=tflite"
# Currently failing further in the linalg stack:
# Fusion appears to produce an invalid IR.
class LightningTest(test_util.TFLiteModelTest):
def ... |
"""
REST API Documentation for the NRS TFRS Credit Trading Application
The Transportation Fuels Reporting System is being designed to streamline
compliance reporting for transportation fuel suppliers in accordance with
the Renewable & Low Carbon Fuel Requirements Regulation.
OpenAPI spec version: ... |
from tqdm import tqdm
from typing import Union, Tuple
from sudoku.base_solver import BaseSolver
from sudoku.sudoku_wrapper import Sudoku
class Backtracking(BaseSolver):
def __init__(self, flatline=None, sudoku=None):
super().__init__(flatline, sudoku)
self.constraints = []
self.progressba... |
norm_cfg = dict(type='SyncBN', requires_grad=True)
model = dict(
type='EncoderDecoder',
pretrained='open-mmlab://resnet101_v1c',
backbone=dict(
type='ResNetV1c',
depth=101,
num_stages=4,
out_indices=(0, 1, 2, 3),
dilations=(1, 1, 2, 4),
strides=(1, 2, 1, 1),
... |
"""
Django settings for server project.
Generated by 'django-admin startproject' using Django 1.8.1.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Build paths... |
# This file is a part of Arjuna
# Copyright 2015-2020 Rahul Verma
# Website: www.RahulVerma.net
# 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... |
#!/usr/bin/env python3
import argparse
import cv2
def parse_node(node):
if node.isMap():
keys = node.keys()
#print('map keys ', keys)
dot = '{\n'
for k in keys:
dot += '%s: '%(k)
dot += parse_node(node.getNode(k))
dot += ',\n'
dot += ' }\... |
import io
import logging
import shlex
import subprocess
import aiohttp
from mgylabs.utils.config import CONFIG
import discord
from discord.ext import commands
from discord.opus import Encoder
from .utils.exceptions import UsageError
from .utils.MGCert import Level, MGCertificate
from .utils.MsgFormat import MsgForma... |
# -*- coding: utf-8 -*-
"""DELHI junee 2006-09 anjtry.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/15nV65qT81YVIeQ77CfXm_RGstKKJ2Lrr
"""
from IPython.display import display
import pandas as pd
# Displaying data in sumarized way
def display_da... |
#!/usr/bin/env python
import os
from fabric import Connection
conn = Connection(
host='192.168.1.83',
user='user',
port=22,
connect_kwargs={'password': 'hhserver'}
)
# TODO: create sudo config
conn_root = Connection(
host='192.168.1.83',
user='root',
port=22,
connect_kwargs={'passwor... |
#!/usr/bin/env python
# Copyright (c) 2012 Joyent, Inc. All rights reserved.
"""Shared code for test case files."""
__all__ = ["stor", "MantaTestCase"]
import sys
import os
from posixpath import join as ujoin
import unittest
import subprocess
from subprocess import PIPE
import manta
#---- exports
def stor(*sub... |
# -*- coding: utf-8 -*-
#
# MNE documentation build configuration file, created by
# sphinx-quickstart on Fri Jun 11 10:45:48 2010.
#
# This file is execfile()d with the current directory set to its containing
# dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All c... |
from django.conf.urls import patterns
__author__ = 'jay'
urlpatterns = patterns(
'',
)
|
# encoding: utf-8
import copy
import uuid
from typing import Any
import simplejson as json
from sqlalchemy import types
__all__ = ['make_uuid', 'UuidType',
'JsonType', 'JsonDictType']
def make_uuid() -> str:
return str(uuid.uuid4())
class UuidType(types.TypeDecorator): # type: ignore
impl =... |
"""TODO(cmrc2018): Add a description here."""
import json
import datasets
# TODO(cmrc2018): BibTeX citation
_CITATION = """\
@inproceedings{cui-emnlp2019-cmrc2018,
title = {A Span-Extraction Dataset for {C}hinese Machine Reading Comprehension},
author = {Cui, Yiming and
Liu, Ting and
Che, Wan... |
from random import shuffle
from wrangle import Wrangler
from sklearn import metrics
from sklearn.externals import joblib
from sklearn.cross_validation import train_test_split
from sklearn.linear_model import LogisticRegression as LR
from sklearn.svm import LinearSVC as SVC
from sklearn.feature_extraction.text import... |
description = 'nGI XinGI setup at ICON'
includes = ['ngi_xingi_gratings', 'ngi_xingi_stage', 'ngi_g0']
excludes = ['ngi_backpack']
|
import logging
import sys
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
from phase_edit import phase_edit_process
from level import level_process
from bias import fetch_sideshow_ionex, bias_process
from rinex import fname2date
from ..util.path import SmartTempDir, replace_path
logger = logging.ge... |
import unittest
from conans.test.utils.tools import TestClient
class BasicTest(unittest.TestCase):
def help_test(self):
conan = TestClient()
conan.run("")
self.assertIn('Conan commands. Type $conan "command" -h', conan.user_io.out)
|
from rest_framework import permissions
from rest_framework.exceptions import PermissionDenied
import rest_framework
class IsOwnerOrReadOnly(permissions.BasePermission):
"""
Custom permission to only allow creator of an object to edit it.
"""
def has_object_permission(self, request, view, obj):
... |
from typing import List
class Solution:
def partition(self, s: str) -> List[List[str]]:
n = len(s)
dp = [[False for _ in range(n)] for _ in range(n)]
res = []
self.backtrack(s, 0, dp, [], res)
return res
def backtrack(self, s, start, dp, current, res):
if start... |
# Copyright 2021 QuantumBlack Visual Analytics Limited
#
# 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
#
# THE SOFTWARE IS PROVIDED "AS IS",... |
# Copyright (c) 2022, DjaoDjin inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and t... |
# coding: utf-8
import re
import six
from huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization
class BatchQueryProgressReq:
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The ... |
# coding=utf-8
# *** WARNING: this file was generated by the Kulado Kubernetes codegen tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
# Export this package's modules as members:
from .Lease import *
from .LeaseList import *
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri May 14 10:55:57 2021
@author: liang
"""
'''
use redis for online mode
'''
import pandas as pd
def get_user_data_redshift(curse, user_id):
sql = '''
select user_id,max(create_time)
from 表
group by user_id
... |
import pyeccodes.accessors as _
def load(h):
def wrapped(h):
table2Version = h.get_l('table2Version')
indicatorOfParameter = h.get_l('indicatorOfParameter')
indicatorOfTypeOfLevel = h.get_l('indicatorOfTypeOfLevel')
level = h.get_l('level')
if table2Version == 207 and in... |
# print forward and reverse rate coefficients for all reactions
from Cantera import *
def show_rate_coefficients(mech, doIrrev = 0):
""" Print the rate coefficients for a reaction mechanism. The
rate coefficients include all factors that multiply the reactant
concentrations in the law of mass ... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from . import ... |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import math
from dateutil.relativedelta import relativedelta
from odoo import fields
from odoo.addons.website_slides.tests import common
from odoo.exceptions import UserError
from odoo.tests import tagged
from odoo.tes... |
from setuptools import setup
setup(name='D3MUnsupervised',
version='1.0.1',
description='Three wrappers for unsupervised clustering algorithms, one wrapper for t-SNE',
packages=['D3MUnsupervised'],
install_requires=["typing",
"numpy==1.17.3",
'scikit-learn ==... |
morningcall_msg = '''
[CQ:face,id=74] 早上好,
今天是 {date} 日,星期{weekday}
{weather},{tmp_min}~{tmp_max}℃
{comf}{drsg}
{class}
{one}
'''
morningcall_class_msg = '''
第 {class_num} 节:{class_name}'''
morningcall_love_msg = '''
[CQ:face,id=74] 早安[CQ:at,qq=1299903489],早安[CQ:at,qq=937734121]
今天是 {date} 日,星期{weekday}
我们在一起已经 {lo... |
#!E:\PycharmProjects\Custom_Mask_RCNN4\venv\Scripts\python.exe
# $Id: rst2xml.py 4564 2006-05-21 20:44:42Z wiemann $
# Author: David Goodger <goodger@python.org>
# Copyright: This module has been placed in the public domain.
"""
A minimal front end to the Docutils Publisher, producing Docutils XML.
"""
try:
impo... |
# modified by syshin
# the original code is 'minibatch.py'
"""Compute minibatch blobs for training a Fast R-CNN network."""
import numpy as np
import numpy.random as npr
#import cv2
#import PIL
import skimage.io
from fast_rcnn.config import cfg
from utils.blob import prep_im_for_blob, im_list_to_blob
def get_miniba... |
import sys, getopt, os
sys.path.append(os.path.dirname(__file__) + '\\..')
from ECG import console
os.environ['MP_CPUJOBS']='1'
os.environ["CUDA_VISIBLE_DEVICES"]="-1"
if __name__ == "__main__":
numclasses = 5
balanced = False
expsnum = 1
batchsize = 1
timesteps = 1
svmkernel = 'rbf'
#p... |
my_list = [
'My first line',
'My second line',
'My last line'
]
with open('new file.txt', 'w') as f:
f.writelines(my_list)
|
"""Core Rhasspy commands."""
import asyncio
import gzip
import logging
import os
import platform
import shutil
import tempfile
from collections import defaultdict
from pathlib import Path
from typing import Any, Dict, List, Optional, Set, Tuple, Union
import aiohttp
# Internal imports
from rhasspy.actor import ActorS... |
from model import Actor, Critic
from replay_memory import ReplayMemory
import paddle
import paddle.nn.functional as F
import numpy as np
import gym
batch_size = 256
num_episodes = 100000
memory_size = 1000000
policy_delay = 2
learning_rate = 0.1
gamma = 0.99
ratio = 0.005
exploration_noise = 0.1
epoch = 0
env = gym.m... |
XXXXXX XXXXXXX XXXXXXXBB BBBBBBBBBBBB BB BBBB XXXXXXXXBBBBBBBBBBBB BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBX
|
from setuptools import find_packages, setup
setup(
name="prereise",
version="0.4",
description="Create and run an energy scenario",
url="https://github.com/Breakthrough-Energy/PreREISE",
author="Kaspar Mueller",
author_email="kaspar@breakthroughenergy.org",
packages=find_packages(),
pac... |
###############################################################################
#
# Tests for XlsxWriter.
#
# Copyright (c), 2013-2020, John McNamara, jmcnamara@cpan.org
#
from ..excel_comparison_test import ExcelComparisonTest
from ...workbook import Workbook
class TestCompareXLSXFiles(ExcelComparisonTest):
"""... |
# QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
# Lean CLI v1.0. Copyright 2021 QuantConnect 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... |
# From https://github.com/LiyuanLucasLiu/RAdam/blob/master/radam/radam.py
import math
import torch
from torch.optim.optimizer import Optimizer
class RAdam(Optimizer):
def __init__(self, params, lr=1e-3, betas=(0.9, 0.999), eps=1e-8, weight_decay=0, degenerated_to_sgd=True):
if not 0.0 <= lr:
... |
from sanic.response import json
# from .models import Individuals
# UsersCL(app).
class Android:
def __init__(self, app):
self.config = app.config
async def route_signup(self, request=None):
pass
# async with self.config['database']:
# user = await Individuals.query.all()
... |
from django.contrib.auth import get_user_model
from rest_framework import serializers
from rest_framework_jwt.settings import api_settings
from core.models import LogRecord
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = get_user_model()
fields = ('username',)
class UserS... |
import abc
import curses
from matomat.models.point import Point
class FormBase(object):
__metaclass__ = abc.ABCMeta
HEADER_POSITION = Point(3, 3)
MENU_POSITION = Point(10, 5)
INPUT_POSITION = Point(10, 5)
menuitems = None
currentItem = 0
def __init__(self, figlet, colors):
self.... |
from base import BasePart
class Test(BasePart):
"""GET /companies/:id - 20%"""
tests = [
('verify_fetch_company_by_id', 10),
('verify_company_fields', 10),
]
def __init__(self, base_url, admin_token):
super(self.__class__, self).__init__(base_url, admin_token)
self.url... |
"""This is init file for user_profile."""
|
from enum import Enum, auto
from typing import Dict, Optional
from aws_lambda_powertools.utilities.data_classes.common import DictWrapper
class ConnectContactFlowChannel(Enum):
VOICE = auto()
CHAT = auto()
class ConnectContactFlowEndpointType(Enum):
TELEPHONE_NUMBER = auto()
class ConnectContactFlowI... |
from django.apps import AppConfig
class RestFhirConfig(AppConfig):
name = 'rest_fhir'
|
# coding: utf-8
"""
Copyright 2016 SmartBear Software
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 l... |
class LibFromPythonPath(object):
'''Class that sums two digits
'''
def MyLib(self):
print "executed LibFromPath" |
# MIT License
#
# Copyright (c) 2016-2018 Matthias Rost, Elias Doehne, Alexander Elvers
#
# 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... |
"""Per-prefix data, mapping each prefix to a dict of locale:name.
Auto-generated file, do not edit by hand.
"""
from ..util import u
# Copyright (C) 2011-2021 The Libphonenumber Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the Licens... |
# -*- coding: utf-8 -*-
"""
inheritance
-----------
:copyright: Copyright 2011-2012 by NaN Projectes de Programari Lliure, S.L.
:license: BSD, see LICENSE for details.
"""
import pprint
import re
import sys
import unicodedata
from path import Path
import docutils.nodes
import sphinx
from sphinx impor... |
'''
Copyright (c) 2011-2015, Agora Games, LLC All rights reserved.
https://github.com/agoragames/haigha/blob/master/LICENSE.txt
'''
from chai import Chai
from datetime import datetime
from io import BytesIO
from decimal import Decimal
from haigha.reader import Reader
import struct
import operator
class ReaderTest(... |
from .. import db
class Channel(db.Model):
""" Channel Model for storing channel state"""
__tablename__ = "channel_state"
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
name = db.Column(db.String(255), unique=False, nullable=False)
last_change = db.Column(db.DateTime, nullable=F... |
print("Hai")
print("Hai")
print("Hai")
print("Hai")
print("Hai")
print("Hai")
print("Hai")
|
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
fro... |
"""
Contains an Op for convolving input images with a set of filters. This was
developed especially for Convolutional Neural Networks.
For related ops, including downsampling and subsampling, see
tensor.signal and tensor.signal.pool.
See especially conv2d().
"""
import logging
import warnings
import numpy as np
fr... |
"""
* Copyright 2008 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http:#www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, s... |
import re
import time
import gevent
import humanize
import operator
from peewee import fn
from holster.emitter import Priority
from fuzzywuzzy import fuzz
from datetime import datetime, timedelta
from disco.bot import CommandLevels
from disco.types.user import User as DiscoUser
from disco.types.message import Messag... |
# -*- coding: utf-8 -*-
#
# 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
#... |
from telisar.languages import undercommon
from telisar.npc.base import BaseNPC
class NPC(BaseNPC):
ancestry = 'Drow'
language = undercommon.DrowPerson()
@property
def full_name(self):
return ' '.join([
str(self.names[0]).capitalize(),
str(self.names[1]).capitalize()
... |
# -*- coding: utf-8 -*-
#
# (C) Rob W.W. Hooft, 2003
#
# Distributed under the terms of the MIT license.
#
__version__ = '$Id: config.py 7059 2009-07-14 07:37:25Z alexsh $'
import os, re
import sys as __sys
# IMPORTANT:
# Do not change any of the variables in this file. Instead, make
# a file user-config.py, and overw... |
import pytest
from briefcase.commands.base import UnsupportedPlatform
from briefcase.config import AppConfig
def test_create_app(tracking_create_command):
"""If the app doesn't already exist, it will be created."""
tracking_create_command.create_app(tracking_create_command.apps["first"])
# Input wasn't ... |
# Copyright 2021 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... |
import sqlite3
import re
import pandas as pd
import numpy as np
import datetime
from configparser import ConfigParser
def deleteHistory(cur,conn,tableName,whereCond):
try:
deleteQuery="delete from "+tableName+whereCond
# print(deleteQuery)
cur.execute(deleteQuery)
result... |
from django.conf import settings
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.http import (HttpResponseBadRequest, HttpResponseForbidden,
JsonResponse)
from django.shortcuts import redirect, render
from django.views.decorators.http im... |
# Copyright 2014 Facebook, Inc.
# You are hereby granted a non-exclusive, worldwide, royalty-free license to
# use, copy, modify, and distribute this software in source code or binary
# form for use in connection with the web services and APIs provided by
# Facebook.
# As with any software that integrates with the Fa... |
import datetime
import pytest
from coincurve import PrivateKey, PublicKey
from nekoyume.exc import InvalidMoveError
from nekoyume.models import (Block,
CreateNovice,
HackAndSlash,
LevelUp,
Move,
... |
"""
RenderPipeline
Copyright (c) 2014-2016 tobspr <tobias.springer1@gmail.com>
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 right... |
# -*- coding: utf-8 -*-
from ocp_resources.resource import Resource
class PersistentVolume(Resource):
"""
PersistentVolume object
"""
api_version = Resource.ApiVersion.V1
class Status(Resource.Status):
RELEASED = "Released"
@property
def max_available_pvs(self):
"""
... |
def deptLevelString(classObject):
string = ""
for i in range(len(classObject['deptList'])):
thisDept = str(classObject['deptList'][i])
thisLevel = str(classObject['levelList'][i])
string += thisDept + " " + thisLevel + ", "
return string[:-2]
def dictTitleCmp(dict1, dict2):
if dict1['title'].upper() < dict2... |
# Required Packages
from sklearn import datasets # To Get iris dataset
from sklearn import svm # To fit the svm classifier
import numpy as np
import matplotlib.pyplot as plt
# import iris data to model Svm classifier
iris_dataset = datasets.load_iris()
print ("Iris data set Description :: ", iris_dataset['DES... |
# coding=utf-8
"""This module contains tools for working with Sphinx charset table files. These files
are useful for doing case and accent folding.
See :class:`whoosh.analysis.CharsetTokenizer` and :class:`whoosh.analysis.CharsetFilter`.
"""
from collections import defaultdict
from itertools import izip
impo... |
# Written by John Hoffman
# see LICENSE.txt for license information
from random import shuffle
from traceback import print_exc
try:
True
except:
True = 1
False = 0
class FileSelector:
def __init__(self, files, piece_length, bufferdir,
storage, storagewrapper, sched, fai... |
# -*- encoding: utf-8 -*-
"""
Copyright (c) 2019 - present AppSeed.us
"""
from flask_wtf import FlaskForm
from wtforms import TextField, PasswordField
from wtforms.validators import InputRequired, Email, DataRequired
## login and registration
class LoginForm(FlaskForm):
username = TextField ('Username', id='u... |
# -*- coding: utf-8 -*-
# Copyright 2016 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law ... |
from sys import stdin
def main():
for T in range(int(stdin.readline())):
score_y = 0
score_k = 0
for i in range(9):
Y, K = map(int, stdin.readline().split())
score_y += Y
score_k += K
if score_y < score_k:
print('Korea')
elif score_k < score_y:
print('Yonsei')
e... |
from unittest.mock import patch, mock_open
from pyinotify import NotifierError
import pytest
from dropboxignore import main, RETURN_CODES, ParsingException
@patch('sys.argv', ['path'])
@patch('dropboxignore.main')
def test_main_with_wrong_number_of_arguments(main_mock):
# GIVEN
# WHEN
with pytest.raise... |
from quantworks import strategy
from quantworks.barfeed import quandlfeed
from quantworks.technical import ma
from quantworks.technical import rsi
def safe_round(value, digits):
if value is not None:
value = round(value, digits)
return value
class MyStrategy(strategy.BacktestingStrategy):
def __... |
from tensorflow.python.platform import gfile
import os
import tensorflow as tf
pb_file_path = os.getcwd()
sess = tf.Session()
with gfile.FastGFile(pb_file_path+'model.pb', 'rb') as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
sess.graph.as_default()
tf.import_graph_def(graph_def, n... |
"""dummy_app URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-... |
import pytest
from bioconda_utils import bioconductor_skeleton
from bioconda_utils import cran_skeleton
from bioconda_utils import utils
config = {
'channels': ['conda-forge', 'bioconda', 'defaults']
}
def test_cran_write_recipe(tmpdir):
cran_skeleton.write_recipe('locfit', recipe_dir=str(tmpdir), recursiv... |
from . import *
from talon import utils
def test_get_delimiter():
eq_('\r\n', utils.get_delimiter('abc\r\n123'))
eq_('\n', utils.get_delimiter('abc\n123'))
eq_('\n', utils.get_delimiter('abc'))
|
import os
import sys
_THIS_DIR = os.path.dirname(os.path.realpath(__file__))
_PROJECT_DIR = os.path.normpath(os.path.join(_THIS_DIR, '..'))
# ensure "fitdecode" python package is importable
sys.path.insert(0, _PROJECT_DIR)
# import project's info (name, version, ...)
_ABOUT = {}
with open(os.path.join(_PROJECT_DIR, ... |
import os
import pygame
import random
trigger = False
pList = [(random.randrange(-100,50),random.randrange(-100,56)) for i in range(0,100)]
def setup(sscreen, etc):
global pList
print "FFFFFFFF"
pList = [(random.randrange(-100,etc.xres+100),random.randrange(-100,etc.yres+100)) for i in range(0,100)]
def ... |
from __future__ import annotations
from pathlib import Path
from typing import TYPE_CHECKING
import pytest
from poetry.factory import Factory
if TYPE_CHECKING:
from cleo.testers.command_tester import CommandTester
from poetry.poetry import Poetry
from tests.types import CommandTesterFactory
@pytest.... |
import os
import ujson
import asyncpg
from random import randint
from multiprocessing import cpu_count
from blacksheep.server import Application
from blacksheep import Response, Header, Content
from jinja2 import Template
json_dumps = ujson.dumps
async def configure_db(app):
global db_pool
db_pool = await asy... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.