text stringlengths 2 999k |
|---|
###############################################################################
# Copyright (c) 2014-2019, Lawrence Livermore National Security, LLC.
#
# Produced at the Lawrence Livermore National Laboratory
#
# LLNL-CODE-666778
#
# All rights reserved.
#
# This file is part of Conduit.
#
# For details, see: htt... |
from hachoir_core.endian import BIG_ENDIAN, LITTLE_ENDIAN, MIDDLE_ENDIAN
from hachoir_core.error import info
from hachoir_core.log import Logger
from hachoir_core.bits import str2long
from hachoir_core.i18n import getTerminalCharset
from hachoir_core.tools import lowerBound
from hachoir_core.i18n import _
from hachoir_... |
"""
hubspot deals api
"""
from hubspot3 import logging_helper
from hubspot3.base import BaseClient
from hubspot3.utils import prettify
import urllib.parse
DEALS_API_VERSION = "1"
class DealsClient(BaseClient):
"""
The hubspot3 Deals client uses the _make_request method to call the API
for data. It retu... |
import os, sys, time
from psychopy import visual, core, data, logging
from .task_base import Task
from ..shared import config
FADE_TO_GREY_DURATION = 2
class SingleVideo(Task):
DEFAULT_INSTRUCTION = """You are about to watch a video.
Please keep your eyes open."""
def __init__(self, filepath, *args,**kwar... |
# AUTO GENERATED FILE - DO NOT EDIT
from dash.development.base_component import Component, _explicitize_args
class Snackbar(Component):
"""A Snackbar component.
Material UI Snackbar component
Keyword arguments:
- action (string; default ''): The text of the action button inside the snackbar. If empty, no action... |
from abc import ABC, abstractmethod
from itertools import chain
from typing import Type
from unittest import TestCase
from open_sea_v1.endpoints.abc import BaseEndpoint
from open_sea_v1.responses.abc import BaseResponse
class QueryTestCase(TestCase, ABC):
sample_wallet = "0x5ca12f79e4d33b0bd153b40df59f6db9ee034... |
#!/usr/bin/env python3
from cereal import car
from selfdrive.config import Conversions as CV
from selfdrive.controls.lib.drive_helpers import EventTypes as ET, create_event
from selfdrive.controls.lib.vehicle_model import VehicleModel
from selfdrive.car.hyundai.carstate import CarState, get_can_parser, get_camera_parse... |
import math, functools
chars = ' abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$¢€£¥%^&*()-–—=≠[]\\;\'‘’,./_+{}|:"“”<≤≥>?`~×⋅÷±°′″'
class line:
def __init__(self, p1, p2):
if p1[0] < p2[0]:
self.left = p1
self.right = p2
else:
self.left = p2... |
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
from typing import cast
import pytest
from pants.backend.docker.goals.package_image import BuiltDockerImage, DockerFieldSet
from pants.backend.docker.... |
testinfra_hosts = ['instance-3', 'instance-4']
def test_node_is_worker(docker_info):
assert "Is Manager: false" in docker_info
|
# Copyright 2018-Present Shanghai Yitu Technology Co., Ltd.
# Licensed under the Apache License, Version 2.0
CONSTANT_VERSION = '0.1.0'
CONSTANT_REQUEST_TIMEOUT = 50
CONSTANT_AUE_PCM = 'pcm'
CONSTANT_AUE_AAC = 'aac'
CONSTANT_AUE_MP3 = 'mpeg2'
CONSTANT_LANG_MANDARIN = 1
CONSTANT_SCENE_GENERAL = 0
CONSTANT_AUE_SE... |
from ray.experimental.workflow.api import (
step,
init,
virtual_actor,
get_output,
get_actor,
get_status,
resume,
cancel,
list_all,
resume_all,
)
from ray.experimental.workflow.workflow_access import WorkflowExecutionError
from ray.experimental.workflow.common import WorkflowStat... |
import os
os.environ['CUDA_VISIBLE_DEVICES'] = ''
os.environ['MALAYA_USE_HUGGINGFACE'] = 'true'
import sys
import malaya
import logging
logging.basicConfig(level=logging.DEBUG)
chinese_text = '今天是6月18号,也是Muiriel的生日!'
english_text = 'i totally love it man'
indon_text = 'menjabat saleh perombakan menjabat periode kom... |
import typing
import numpy as np
import scipy.special
from fourier_accountant.plds import PrivacyLossDistribution, PrivacyException, DiscretePrivacyLossDistribution
__all__ = ['get_delta_upper_bound', 'get_delta_lower_bound', 'get_epsilon_upper_bound', 'get_epsilon_lower_bound']
def _get_ps_and_Lxs(
pld: Priv... |
import sys
import json
import unittest
import ctxt
class TracerKeyError(ctxt.Tracer):
throws = (IndexError, )
def __init__(self):
super(TracerKeyError, self).__init__()
tracer = ctxt.Tracer()
tracer1 = ctxt.Tracer(throws=(KeyError, ))
tracer2 = TracerKeyError()
class DoSomeStuff1(object):
@tr... |
"""
Django settings for health project.
Generated by 'django-admin startproject' using Django 1.11.8.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""
import os
i... |
"""Utilites: Functions to Help configure the BaseConfig class."""
import os
import fnmatch
def map_routes(
template_path,
template_extensions,
ignore_paths
):
"""Generate routes from a folder directory."""
routes = []
for root, dirnames, filenames in os.walk(template_path):
for extensi... |
class Element(object):
def __init__(self, value):
self.value = value
self.next = None
class LinkedList(object):
"""
Linked list class is used to hold elements but will act as a stack.
Which means it will delete and insert only from the top of the Stack
"""
def __init__(self, he... |
#!/usr/bin/env python
import hashlib
import logging
import os
import sys
import requests
from requests_toolbelt.multipart.encoder import MultipartEncoderMonitor, MultipartEncoder
from clint.textui.progress import Bar as ProgressBar
def create_callback(size):
bar = ProgressBar(expected_size=size, filled_char='=')... |
# -*- coding: UTF-8 -*-
# File: __init__.py
if False:
from .base import *
from .convert import *
from .crop import *
from .deform import *
from .geometry import *
from .imgproc import *
from .meta import *
from .misc import *
from .noise import *
from .paste import *
from .t... |
#!/usr/bin/env python
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# ---------------------------------------------... |
# -*- coding: utf-8 -*-
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Instance.shard'
db.add_column(u'physical_instance', 'shar... |
#!/usr/bin/env python
# --------------------------------------------------------
# Written by Bharat Singh
# Modified version of py-R-FCN
# --------------------------------------------------------
"""Train a Fast R-CNN network on a region of interest database."""
import _init_paths
from fast_rcnn.train_multi_gpu imp... |
# coding:utf-8
import math
import stemming.porter2 as porter
import numpy as np
import copy
from collections import Counter
def position_rank(sentence, tokenizer, alpha=0.85, window_size=6, num_keyphrase=10, lang="en"):
"""Compute position rank score.
Position rank is a method for extracting keyphrase from s... |
import logging
import os
import textwrap
from mkdocs import utils
from mkdocs.config import config_options
from mkdocs.plugins import BasePlugin
log = logging.getLogger('mkdocs.plugin.redirects')
log.addFilter(utils.warning_filter)
def write_html(site_dir, old_path, new_path):
""" Write an HTML file in the site... |
# -*- coding: utf-8 -*-
from setuptools import setup
from setuptools import find_packages
import hmmtool
with open('README.rst') as f:
readme = f.read()
setup(
name='hmm-tool',
version=hmmtool.__version__,
packages=['hmmtool'],
author='Chef_J',
author_email='hedge_jzt@hotmail.com',
maint... |
# URI Online Judge 2543
while True:
try:
entrada = input().split()
N, id = int(entrada[0]), entrada[1]
contador = 0
for n in range(N):
entrada = input().split()
if entrada[0] == id and entrada[1] == '0':
contador += 1
... |
# -*- coding: utf-8 -*-
import csv
from datetime import date, timedelta
from unittest.mock import patch
import os
import random
from django.contrib.auth.models import User, AnonymousUser
from django.core.exceptions import ValidationError, PermissionDenied
from django.core.management import call_command
from django.cor... |
import gzip
import docker
import logging
import os
import tarfile
import uuid
from collections import OrderedDict
from io import BytesIO
from textwrap import dedent
from .Cluster import Cluster
from ..flow_serialization.Minifi_flow_yaml_serializer import Minifi_flow_yaml_serializer
from ..flow_serialization.Nifi_flow... |
#!/usr/bin/python3
import os
import sys
sys.path.append('/var/www/html/castrcv')
from app import app as application
|
from tests.unit.dataactcore.factories.domain import SF133Factory
from tests.unit.dataactcore.factories.staging import AppropriationFactory
from tests.unit.dataactvalidator.utils import number_of_errors, query_columns
_FILE = 'a34_appropriations'
_TAS = 'a34_appropriations_tas'
def test_column_headers(database):
... |
# -*- coding: utf-8 -*-
# MegEngine is Licensed under the Apache License, Version 2.0 (the "License")
#
# Copyright (c) 2014-2021 Megvii Inc. All rights reserved.
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT ARRANTI... |
# -*- coding: utf8 -*-
import requests, time, datetime, re,sys, json, random
# 设置开始
# 用户名(格式为 13800138000)
# 酷推skey和server酱sckey和企业微信设置,只用填一个其它留空即可
skey = sys.argv[3]
# 推送server酱
sckey = sys.argv[4]
# 企业微信推送
# 是否开启企业微信推送false关闭true开启,默认关闭,开启后请填写设置并将上面两个都留空
position = sys.argv[5]
base_url = 'https://qyapi.weixin.qq.co... |
num = int(input('Digite um número para ver a sua tabuada: '))
print ('-'*12)
print('{} X {:2} = {}'.format(num, 1, num*1))
print('{} x {:2} = {}'.format(num, 2, num*2))
print('{} x {:2} = {}'.format(num, 3, num*3))
print('{} x {:2} = {}'.format(num, 4, num*4))
print('{} x {:2} = {}'.format(num, 5, num*5))
print('{} x {... |
# views.py
from flask import abort, jsonify, render_template, request, redirect, url_for, make_response
#from flask_cache import Cache
from app import app
from classyfire_tasks import get_entity, classify_full_structure, record_failure
from classyfire_tasks import populate_batch_task
from werkzeug.utils import secure... |
# Utilities
import torch
import shutil
import torchvision.utils as vutils
import matplotlib.pyplot as plt
import numpy as np
import os
from ipdb import set_trace as st
from torch.autograd import Variable
from tqdm import tqdm
from collections import OrderedDict
from PIL import Image
from torch import nn
save_samples_p... |
"""Copyright 2012 Phidgets Inc.
This work is licensed under the Creative Commons Attribution 2.5 Canada License.
To view a copy of this license, visit http://creativecommons.org/licenses/by/2.5/ca/
"""
__author__="Adam Stelmack"
__version__="2.1.8"
__date__ ="13-Jan-2011 12:29:34 PM"
import ctypes
from ctypes import ... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
@version: ??
@author: li
@file: __init__.py.py
@time: 2019/10/30 9:06 上午
""" |
# -*- coding: utf-8 -*-
# @Time : 2017/9/6 23:06
# @Author : Forec
# @File : post/__init__.py
# @Project : WildPointer
# @license : Copyright(C), Forec
# @Contact : forec@bupt.edu.cn
from flask import Blueprint
post = Blueprint('post', __name__)
from . import views, api
from ..models import Permission
@po... |
from astropy import units as u
from astropy import constants as const
from mirage.util import Jsonable
from .Cosmic import Cosmic
from .CalculationDependency import CalculationDependency
class Quasar(Jsonable, Cosmic, CalculationDependency):
"""A class for containing information about a quasar. By default... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# File: example_stream_management_extended.py
#
# Part of ‘UNICORN Binance WebSocket API’
# Project website: https://www.lucit.tech/unicorn-binance-websocket-api.html
# Github: https://github.com/LUCIT-Systems-and-Development/unicorn-binance-websocket-api
# Documentation... |
from ..util import (take, unique, interleave, intersection, groupsizes,
dicthash, hashable, multihash)
def test_hashable():
assert hashable(2)
assert hashable((2, 3))
assert not hashable({1: 2})
assert not hashable((1, {2: 3}))
def test_unique():
assert tuple(unique((1, 2, 3)... |
import json
#file = open(filename)
#output = open('output.txt', 'w')
#print "Here's your file %r:" % filename
with open("Hello.txt","r") as infile, open("Output.txt","w") as outfile:
d={}
for line in infile:
x = line.split(":")
y = line.split(" ", 2)
a = x[0] #splits the string in half... |
import asyncio
from httpx import AsyncClient
from starlette import status
async def main():
print("running test script")
async with AsyncClient(base_url="http://127.0.0.1:8000") as client:
await script(client)
print("test script done")
async def script(client: AsyncClient):
username, passw... |
# 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
# "License... |
"""
Copyright (c) 2020, salesforce.com, inc.
All rights reserved.
SPDX-License-Identifier: BSD-3-Clause
For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
Sequence decoder module.
"""
import torch
import torch.nn as nn
from src.common.nn_modules import L... |
import unittest
from expression_builder.exceptions import ExpressionError
from expression_builder.expression_builder import ExpressionBuilder
class StringReplaceTests(unittest.TestCase):
# noinspection PyPep8Naming
def setUp(self):
self.exp = ExpressionBuilder()
self.exp.add_to_global("fred"... |
from __future__ import print_function # Python 2/3 compatibility
import boto3
import pandas as pd
import MySQLdb
import sys
def add_item(table, user_id, product_id, product_name, aisle_name):
table.put_item(
Item={
'user_id': user_id,
'update_ver' : 1,
'product_id': product_id,
... |
import random
import re
# variables
user_selection = "R"
computer_selection = "R"
vocabulary = {"R":"ROCK", "P":"PAPER", "S":"SCISSORS"}
play_input_pattern = re.compile("^[R,P,S]{1,1}$")
user_input = "Y"
def computer_choice():
return random.choice("RPS")
# user flow
while(1):
user_input = input("Do you want... |
import copy
import re
from random import randint, shuffle
from tddspry import TestCase
from tddspry.django import TestCase as DjangoTestCase
TEST_DICT = {
'key': 'value',
'some': 'thing',
}
TEST_ITEM = randint(1, 10)
TEST_LIST = range(1, 11)
TEST_NONE = None
TEST_NOT_REGEXP = re.compile('\d+')
TEST_NOT_ITEM... |
import logging
import os
from sdtables.sdtables import SdTables
import yaml, json
import sdtables_cli.common as common
logger = logging.getLogger('main.{}'.format(__name__))
class Build:
def __init__(self, args):
# Run setup tasks
self.args = args
self.schema = {}
# Run the comma... |
import re
with open("texts/text_1.txt", "r") as source:
dest = open("texts/output-2.txt", "w")
for i, line in enumerate(source):
punc_cunt = len(re.findall(r"[\-,\.'!?]", line))
chars = len(re.findall(r"[\w]", line))
edited_line = f"Line {i + 1}: {line[0:-2]} ({chars})({punc_cunt})\n"... |
#
# Copyright 2017 Quantopian, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wr... |
from resumable import Resumable
from test.fixture import ( # noqa: F401
SAMPLE_CONTENT, TEST_CHUNK_SIZE, SAMPLE_CONTENT_CHUNKS, sample_file,
server, Request
)
def expected_body(identifier, testfile, index, content):
body = {
'resumableChunkNumber': index + 1,
'resumableCurrentChunkSize':... |
#!/usr/bin/env python
# encoding: utf-8
'''
@author: Jason Lee
@license: (C) Copyright @ Jason Lee
@contact: jiansenll@163.com
@file: jianzhi_offer_23.py
@time: 2019/5/3 15:54
@desc:
'''
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class So... |
import os
import logging
import mock
import ddtrace
from unittest import TestCase, skip, skipUnless
from ddtrace.api import API, Response
from ddtrace.ext import http
from ddtrace.filters import FilterRequestsOnUrl
from ddtrace.constants import FILTERS_KEY
from ddtrace.tracer import Tracer
from ddtrace.encoding impor... |
# Copyright 2015 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
import dataclasses
import difflib
import json
import textwrap
from typing import Dict, cast
from typing_extensions import Literal
from pants.base.build_environment import pants_version
f... |
from datetime import date, datetime, timedelta
import numpy as np
import pytest
from pandas.core.dtypes.cast import infer_dtype_from_array, infer_dtype_from_scalar
from pandas.core.dtypes.common import is_dtype_equal
from pandas import (
Categorical,
Interval,
Period,
Series,
Timedel... |
# coding: utf-8
"""
Kubernetes
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
The version of the OpenAPI document: v1.15.9
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import six
fr... |
"""Модель для регистрационной формы"""
from flask_wtf import FlaskForm
from wtforms import PasswordField, StringField, SubmitField
from wtforms.fields.html5 import EmailField
from wtforms.validators import DataRequired
class RegisterForm(FlaskForm):
surname = StringField('Фамилия:', validators=[DataRequired()])
... |
"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.
openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:
http://license.coscl.org.cn/MulanPSL2
THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, W... |
# Copyright 2018 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... |
# coding=utf-8
# Copyright 2020 The HuggingFace Team. 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 requir... |
'''
Module showing how doctests can be included with source code
Each '>>>' line is run as if in a python shell, and counts as a test.
The next line, if not '>>>' is the expected output of the previous line.
If anything doesn't match exactly (including trailing spaces), the test fails.
'''
def multiply(a, b):
... |
"""A mix of `bib.evensen2009ensemble` and `bib.sakov2008implications`.
.. note::
Since there is no noise, and the system is stable,
the rmse's from this HMM go to zero as `T` goes to infinity.
Thus, benchmarks largely depend on the initial error,
and so these absolute rmse values are not so useful
... |
"""Setup file for gruut_lang_ar"""
from pathlib import Path
import setuptools
module_name = "gruut_lang_ar"
this_dir = Path(__file__).parent
module_dir = this_dir / module_name
# -----------------------------------------------------------------------------
# Load README in as long description
long_description: str... |
# Copyright 2020 The FedLearner 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... |
from datetime import date
from fava.util.ranking import ExponentialDecayRanker
def test_ranker():
list_ = [1, 2, 3]
ranker = ExponentialDecayRanker(list_)
ranker.update(1, date(2015, 1, 1))
ranker.update(2, date(2014, 1, 1))
ranker.update(3, date(2016, 1, 1))
assert ranker.sort() == [3, 1, 2]... |
lista = [1, 10]
arquivo = open('teste.txt', 'r')
try:
divisao = 10 / 0
numero = lista[1]
x = a
except ZeroDivisionError:
print('Não é possível realizar uma divisão por 0')
except IndexError:
print('Erro ao acessar um indice inválido da lista')
except BaseException:
print('Erro desconhecido. Err... |
# Copyright 2017 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, ... |
import pytest
import os
import shutil
from datetime import datetime
from seamm_dashboard import create_app, db
from seamm_datastore.util import parse_flowchart
from seamm_datastore.database.models import (
Job,
Flowchart,
Project,
User,
Role,
UserProjectAssociation,
)
from selenium import web... |
data_dir = '/home/cn/data/sample_tick/'
import os
import shutil # higher level file operations - more choices for error handling
os.path.join('usr', 'bin', 'spam') # join path
cur_dir = os.getcwd() # current working dir
os.chdir('/tmp'); os.getcwd() # move around
os.chdir('/home/cn/program/python/sandbox');
os.ge... |
from flask import Flask, render_template
from flask_dummyimage import DummyImage
app = Flask(__name__)
dummyimage = DummyImage(app, url_prefix="/dm", endpoint="images", route="img")
@app.route("/")
def index():
return render_template("index.html")
if __name__ == "__main__":
app.run(debug=True)
|
from EXOSIMS.Prototypes.PlanetPopulation import PlanetPopulation
import numpy as np
import os
import inspect
from astropy.io import ascii
import astropy.units as u
import astropy.constants as const
import scipy.interpolate as interpolate
import sys
# Python 3 compatibility:
if sys.version_info[0] > 2:
xrange = ran... |
POINT_FOR_LIKE = 1 # очки за лайки поста
POINT_FOR_TIME_LIKE_1 = 4 # лайк поста не позже... n1 времени
TIME_LIKE_1 = 60*10
POINT_FOR_TIME_LIKE_2 = 2 # лайк поста не позже... n2 времени
TIME_LIKE_2 = 60*30
POINT_FOR_COMMENT = 5
LIKE_ON_COMMENT = True # начислять очки за лайки комментариев других юзер... |
import numpy as np
from sklearn.model_selection import GridSearchCV, StratifiedKFold
from sklearn.utils.estimator_checks import check_estimator
from pywsl.pul import pu_mr
from pywsl.utils.syndata import gen_twonorm_pu
from pywsl.utils.comcalc import bin_clf_err
def main():
prior = .5
x, y, x_t, y_t = gen_t... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#__author__ = '1c3z'
# ref:http://www.wooyun.org/bugs/wooyun-2010-093049
def assign(service, arg):
if service == "umail":
return True, arg
def getPath(arg):
import re
path = ''
url = arg + 'webmail/client/mail/module/test.php'
... |
import numpy as np
import math, time
import random
import matplotlib.pyplot as plt
from numpy import linalg as LA
import mpl_toolkits.mplot3d.axes3d as p3
from matplotlib.animation import FuncAnimation
import matplotlib.patches as mpatches
from scipy import stats
import os
import sqlite3
k_B = 1.380648e-... |
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by appli... |
# file __init__.py
# This file contains no code, but it causes the Python interpreter to
# treat this directory as a Python package.
|
from zetgo.zobrist import Zobrist
class Board(object):
def __init__(self, board_size):
self.board_size = board_size
self.dragons = {}
self.positions = [[Position(x, y, self.board_size) for y in range(self.board_size)] for x in range(self.board_size)]
self.zobrist = Zobrist(self.bo... |
import shutil
def inplace_change(filename, pairs):
# Safely read the input filename using 'with'
with open(filename) as f:
s = f.read()
# Safely write the changed content, if found in the file
with open(filename, 'w') as f:
for p in pairs:
s = s.replace(p[0], p[1])
f.write(s)
print 'Generat... |
from django.contrib import admin
from django.contrib.auth.views import LoginView
from django.urls import include
from django.urls import path
from battle_wizard.views import build_deck
from battle_wizard.views import choose_deck_for_match
from battle_wizard.views import choose_opponent
from battle_wizard.views import f... |
# -*- coding: utf-8 -*-
#
# Copyright 2019 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law... |
import logging
import argparse
from flask import Flask, render_template, jsonify, request
from datetime import datetime
from registration import Registration
from registrator import Registrator
from configuration import Configuration
from myservice import myservice
# default config file (use -c parameter on command... |
# Copyright 2017 Google Inc. 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... |
from datetime import datetime, timedelta
def get_date_range(start, end, fmt):
start = datetime.strptime(start, fmt)
end = datetime.strptime(end, fmt)
diff = (end - start).days
res = []
if diff < 0:
return res
cur = start
while cur <= end:
res.append(datetime.strftime(cur,... |
"""
PRACTICE Exam 3.
This problem provides practice at:
*** SEQUENCES. ***
Authors: David Mutchler, Vibha Alangar, Matt Boutell, Dave Fisher,
Mark Hays, Amanda Stouder, Aaron Wilkin, their colleagues,
and Cleo Barmes.
""" # DONE: 1. PUT YOUR NAME IN THE ABOVE LINE.
############################... |
import tkinter as tk
def make_root() -> tk.Tk:
root = tk.Tk()
root.title("Calculator")
root.config(padx=10, pady=10, background="white")
root.resizable(False,False)
return root
def make_label()
|
"""A PEP 517 interface to setuptools
Previously, when a user or a command line tool (let's call it a "frontend")
needed to make a request of setuptools to take a certain action, for
example, generating a list of installation requirements, the frontend would
would call "setup.py egg_info" or "setup.py bdist_wheel" on t... |
import sys
from utils import xml_differencer
from tkinter import Label, Entry, Button, Tk, filedialog, END, Text, W, E, N, S
class StdoutRedirector(object):
def __init__(self, text_widget):
self.text_space = text_widget
def write(self, string):
self.text_space.configure(state='normal')
... |
class IEXSymbolError(Exception):
"""
This error is thrown when an invalid symbol is given.
"""
def __init__(self, symbol):
self.symbol = symbol
def __str__(self):
return "Symbol " + self.symbol + " not found."
class IEXEndpointError(Exception):
"""
This erro... |
from django.urls import path
from .views import FortuneList, FortuneDetail
urlpatterns = [
path('<int:pk>/', FortuneDetail.as_view()),
path('', FortuneList.as_view()),
]
|
#!/usr/bin/python
#
# @author: Gaurav Rastogi (grastogi@avinetworks.com)
# Eric Anderson (eanderson@avinetworks.com)
# module_check: supported
# Avi Version: 17.1.1
#
# Copyright: (c) 2017 Gaurav Rastogi, <grastogi@avinetworks.com>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses... |
# This file is part of Scapy
# Copyright (C) 2007, 2008, 2009 Arnaud Ebalard
# 2015, 2016 Maxence Tury
# This program is published under a GPLv2 license
"""
TLS ciphers.
"""
class CipherError(Exception):
"""
Raised when .decrypt() or .auth_decrypt() fails.
"""
pass
# We have to keep ... |
"""Rules for generating unit-tests using hexagon delegates."""
def hexagon_op_tests(
srcs = [],
deps = []):
"""Create separate unit test targets for each test file in 'srcs'.
Args:
srcs: list of test files, separate target will be created for each item in the list.
deps: Depend... |
from dependency_injector.wiring import inject
from .base_command import BaseCommand, COMMAND_TYPES
from functools import partial
import webbrowser
class SearchGoogleMaps(BaseCommand):
@inject
def __init__(
self, command_str: str, type: COMMAND_TYPES, fct: partial = None
) -> None:
super().... |
# -*- coding: utf-8 -*-
"""
Utility functions.
"""
import functools
from typing import Callable
from flask import request
from flask_marshmallow import Schema
from .models import Post
USER_SERVICE = 'http://user_service:8000'
def paginate(collection_schema: Schema, max_per_page: int=10) -> Callable:
"""
... |
from django.db import models
from cride.utils.models import CRideModel
class Circle(CRideModel):
"""Cirle model
private group"""
name = models.CharField('circle name', max_length=140)
slug_name = models.SlugField('slug name', max_length=140, unique=True)
about = models.CharField('circle descripti... |
import numpy as np
import os
from os import makedirs
from os.path import split, join, splitext, exists, isfile
class peak(object):
def __init__(self,z,f,baseLine = None,model = None,id=''):
self.z = z
self.f = f
self.model = model
self.fit = None
self.id = id
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.