content
stringlengths
5
1.05M
from typing import List import base36 # We won't need timestamps before this time # DO NOT CHANGE THIS _feature_launch_ts = 1623432061 def _encode_time(time: float): time = max(0, time - _feature_launch_ts) return base36.dumps(int(time)) def _decode_time(b36: str): return base36.loads(b36) + _feature...
# -*- coding: utf-8 -*- from PyQt5 import QtWidgets, QtGui ,QtCore # from PyQt5.QtGui import QPainter, QColor, QPen # from PyQt5.QtCore import Qt class MyQPainteWidget(QtWidgets.QWidget): def __init__(self): super(MyQPainteWidget, self).__init__() self.data = None self.paintX = 0 s...
import datetime as dt import time from typing import Any, Dict import pytest from pydantic.fields import Undefined from sqlalchemy import Column, Integer, String, Text from alchemista.field import Info, make_field def test_info_type_used_as_info() -> None: # Arrange column = Column( Integer, ...
# -*- coding:utf-8 -*- from cocutils.utils import procDataFrame from cocutils.dumpsc import dumpsc from cocutils.dumpsc2 import sc2png from cocutils.pathutils import findAllFile
from datetime import timedelta from re import search from disnake.ext.commands import Converter, converter_method from tools.exceptions import TimeConversionError class TimeConverter(Converter): @converter_method async def convert(self, _, arg: str) -> timedelta: arg = arg.lower().replace(" ", "") ...
""" solution AdventOfCode 2019 day 11 part 1. https://adventofcode.com/2019/day/11. author: pca """ from general.general import read_file from general.general import get_location_input_files from app.int_machine import IntMachine from collections import defaultdict # directions in (y, x) coords directions = [(-1, ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('jssmanifests', '0020_jsssite_jssuser'), ] operations = [ migrations.RenameField( model_name='jssuser', ...
from datetime import datetime from pathlib import Path class ImageInput: def __init__(self, input_file, output_directory): self.input_file = input_file self.input_name = Path(input_file).name self.input_stem = Path(input_file).stem self.output_directory = output_directory ...
def myFn(): print("You have called my function") def add(x, y): z = x + y print(z) myFn() add(2, 3)
import math import torch from torch import Tensor from torch.distributions import Distribution as D from torch.nn.init import _calculate_fan_in_and_fan_out # https://discuss.pytorch.org/t/implementing-truncated-normal-initializer/4778/16 def _truncated_normal(tensor, mean=0, std=1, thres=2): size = tensor.shape ...
from json import JSONEncoder import math class Point(object): def __init__(self, x, y): self.x = x self.y = y def __add__(self, other): """ You can add a Vector to a Point, but not the other way around :param other: Vector :return: Point """ if ...
from __future__ import division from __future__ import print_function import os import random import numpy as np import cv2 from SamplePreprocessor import preprocess # from models.OCRBeamSearch.src.SamplePreprocessor import preprocess chars = [' ', '!', '"', '#', "'", '(', ')', '*', ',', '-', '.', '/', '&', '+', '0'...
try: from PyQt5.QtWidgets import * from PyQt5.QtCore import * Signal = pyqtSignal except ImportError: from PySide2.QtWidgets import * from PySide2.QtCore import * from ..data_roles import InternalDataRole from ..library import Library from .model import LibraryListModel from .view import LibraryLi...
from lablog.interfaces import Interface import humongolus.field as field from lablog import messages import requests from datetime import timedelta, datetime class EnergyGateway(Interface): exchange = messages.Exchanges.energy measurement_key = "energy.smartmeter" run_delta = timedelta(seconds=30) CMD...
"""The client module defines stream and query based clients. Stream clients allow to read and write from stream based sources with ease, and in an interchangable manner. Query based clients unify how to access databases leveraging from sqlalchemy. """ from .databricks_client import * # noqa
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/vis-01-ei.ipynb (unless otherwise specified). __all__ = ['get_ei_raw_urls', 'get_ei_df', 'clean_EI_df_for_plot', 'rgb_2_plt_tuple', 'convert_fuel_colour_dict_to_plt_tuple', 'hide_spines', 'stacked_fuel_plot', 'construct_GB_decarb_progess_md_txt', 'g...
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function def train_LSN(config_file): import sys sys.path.append('./detection_model/LSN') from config.config import config, init_config from yacs.config import CfgNode as CN ...
""" Service PSQL """ import logging import psycopg2 from psycopg2.extras import RealDictCursor from quality_toolkit.services.base_sql import BaseSql class ConnectionPsql(BaseSql): """docstring for ConnectionPsql""" def __init__(self, db_config): logging.debug("db_config: %s", db_config) self...
# Copyright 2018 Cisco Systems 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 agre...
import csv from pathlib import Path from typing import Dict, List import pytest from opennem.api.stats.schema import RegionFlowEmissionsResult from opennem.api.time import human_to_interval from opennem.core.flows import net_flows_emissions def get_test_fixture(filename: str) -> List[Dict]: csv_fixture = Path(_...
from django.db import models from django.contrib.auth.models import User class Address(models.Model): address = models.CharField( "Address", max_length=255, ) zip_code = models.CharField( "ZIP / Postal code", max_length=12, ) city = models.CharField( "City...
""" Title: 0021 - Merge Two Sorted Lists Tags: Linked List Time: O(n) Space: O(1) Source: https://leetcode.com/problems/merge-two-sorted-lists/ Difficulty: Easy """ # Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solu...
from __future__ import absolute_import import os import json try: from StringIO import StringIO except ImportError: from io import BytesIO as StringIO from zipfile import ZipFile from lxml import etree import requests from .exceptions import ( NoContainerError, OperationFailedError, UnpublishedDatavers...
def mensagem(erro): cores = {'Vermelho': '\033[1;31m', 'Azul': '\033[1;34m', 'Limpa': '\033[m'} print(f'{cores["Vermelho"]}Erro "{cores["Azul"]}{erro.__class__}{cores["Limpa"]}{cores["Vermelho"]}",' f' tente novamente{cores["Limpa"]}') def leiaint(info): while True: try: num ...
#-*- coding:utf-8 -*- def upper_attr(future_class_name, future_class_parents, future_class_attr): #遍历属性字典,把不是__开头的属性名字变为大写 newAttr = {} for name,value in future_class_attr.items(): if not name.startswith("__"): newAttr[name.upper()] = value #调用type来创建一个类 return type(future_clas...
from django import forms from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, Fieldset, ButtonHolder, Submit, Div, MultiField, Field, HTML from crispy_forms.bootstrap import AppendedText, PrependedText from .models import Address class AddressForm(forms.ModelForm): """ User-relat...
from abc import ABC from enum import Enum from typing import List, Set class MessageType: INFO = 0 WARNING = 1 ERROR = 2 class ViewComponent(ABC): """ Represents a GUI component """ def __init__(self, id_: str): self.id = id_ class InputViewComponent(ViewComponent): """ ...
from functionss import * n = int(input(("Enter the value 'n' : "))) primes = primeMultipliers(n) x = primes[0] y = primes[1] print("X : {} , Y : {}".format(primes[0],primes[1])) print("{} * {} = {} ".format(x-1,y-1,multiplication(x,y))) d = modInverse(multiplication(x,y)) print("m : ",multiplication(x,y))...
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # SPDX-License-Identifier: Apache-2.0 """ Purpose Shows how to query for items from an Amazon DynamoDB table that stores movies and projects the returned items so that a particular subset of data is returned. Items are queried by a key expression th...
from abc import ABC, abstractmethod from collections import namedtuple import logging from vulk.audio import VulkAudio from vulk.context import VulkWindow, VulkContext from vulk.event import CallbackEventListener from vulk.util import millis, time_since_millis __all__ = ['BaseApp'] logger = logging.getLogger() cla...
from app.models.ingredient import Ingredient from db import session from app.models.receipt import Receipt def prepare_create_receipt() -> tuple: first_ingredient = Ingredient(name='Name', calories=200) session.add(first_ingredient) second_ingredient = Ingredient(name='Name1', calories=201) session.a...
"""Tests of parsing GTINs.""" import pytest from biip import ParseError from biip.gs1 import GS1Prefix from biip.gtin import Gtin, GtinFormat def test_parse_value_with_invalid_length() -> None: with pytest.raises(ParseError) as exc_info: Gtin.parse("123") assert ( str(exc_info.value) ...
import os SUBDIRS = ["datasets", "mapping_police_violence"] FILENAME = "fatal_encounters.xlsx" # URL = f"https://mappingpoliceviolence.org/s/{FILENAME}" PATH_ROOT = os.path.join(os.getcwd(), *SUBDIRS) FILEPATH = os.path.join(PATH_ROOT, FILENAME)
# -*- coding: utf-8 -*- """ Created on Thu Apr 20 14:54:23 2017 @author: tyler """ import pandas as pd from timeseries_analysis import timeseries_report import matplotlib.pyplot as plt import os plt.close('all') filenames = ['tibet_24_km.csv', 'Alberta-24km.csv', 'Alps-24km.csv', ...
""" Psutil homework not finished """ import psutil def performance_testing(**test_type): def inner(func): def wrapper(expected): if test_type['name'] == 'memory': actual_data = psutil.virtual_memory().percent if expected - 10 <= actual_data <= expected + 10: ...
try: from manimlib import * manimce = False except ImportError as e: from manim import * manimce = True import logging import os from rich.traceback import install from rich.logging import RichHandler import yacv.constants as constants from yacv.constants import yacv_manimce_config, yacv_manim_config...
import urllib, os i = 0 while i <= 21: os.system('wget http://paper.ijcsns.org/07_book/201407/201407%02i.pdf' % i) #untuk download file 20140701.pdf - 20140721.pdf i = i + 1
######### # Copyright (c) 2019 Cloudify Platform Ltd. 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 requi...
from django.conf.urls.defaults import patterns, include, url from tastypie.api import Api from django.contrib import admin from api import BoxResource, LeafResource, PersonResource admin.autodiscover() v1_api = Api(api_name='v1') v1_api.register(BoxResource()) v1_api.register(LeafResource()) v1_api.register(PersonRe...
# File: Hierarchy_of_classes_in_Python.py # Description: Hierarchy of classes, multiple inheritance, subclasses, super method # Environment: PyCharm and Anaconda environment # # MIT License # Copyright (c) 2018 Valentyn N Sichkar # github.com/sichkar-valentyn # # Reference to: # [1] Valentyn N Sichkar. Hierarc...
#!/usr/bin/env python import subprocess from concurrent import futures from configparser import ConfigParser from datetime import datetime from functools import wraps from google.protobuf.json_format import MessageToDict import grpc from grpc import aio import logging from logging.config import fileConfig import os imp...
import json from dataclasses import is_dataclass class DataClassEncoder(json.JSONEncoder): def default(self, obj): if is_dataclass(obj): return obj.__dict__ return json.JSONEncoder.default(self, obj)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @file ultrastar_pitch.py @brief main module to start pitch detection from command line @author paradigm """ import sys import logging import argparse import numpy as np from .version import __version__ from .project_parser import ProjectParse...
from tqdm import tqdm import torch from torch.distributions import MultivariateNormal from time import time from typing import Callable, Union, Dict from .sampler_base import SamplerBase from .. import log class Metropolis(SamplerBase): def __init__(self, nwalkers: int = 100, ns...
#!/usr/bin/env python # coding: utf-8 # In[1]: #!wget -q https://dlcdn.apache.org/spark/spark-3.0.3/spark-3.0.3-bin-hadoop2.7.tgz #!tar xzf spark-3.0.3-bin-hadoop2.7.tgz #!pip install findspark # In[1]: import os os.environ["SPARK_HOME"] ="/Users/ferhatyilmaz/Downloads/spark-3.0.3-bin-hadoop2.7" os.environ["PYSP...
# Generated by Django 3.2.4 on 2021-08-26 10:41 import coreapp.models from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ # type: ignore ] operations = [ migrations.CreateModel( name='...
# Copyright (c) 2021 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...
import io from playground.common import Version as PacketDefinitionVersion from playground.common.io import HighPerformanceStreamIO from playground.network.packet.encoders import DefaultPacketEncoder from playground.network.packet.fieldtypes import NamedPacketType, ComplexFieldType, PacketFields, Uint, \ ...
""" Tests for the gait2392geomcustomiser.py module """ import os import sys import numpy as np import copy import gait2392geomcustomiser as g23 from gias3.fieldwork.field import geometric_field from gias3.musculoskeletal.bonemodels import bonemodels from gias3.musculoskeletal.bonemodels import lowerlimbatlasfit from g...
# -*- coding: utf-8 -*- # Generated by Django 1.11.5 on 2018-01-31 19:37 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('interactive', '0002_auto_20171106_2322'), ] operations = [ migrations.AddFi...
import json import logging import math import queue import socket import sys import threading import time from multiprocessing.sharedctypes import Value from sqlite3 import Time import cv2 import numpy as np from cscore import CameraServer from networktables import NetworkTables, NetworkTablesInstance #Below link has...
import os import requests import pandas as pd class OpenData: """Contains the EU open data Covid case distribution Atributes --------- df: pandas.DataFrame Dataframe with Covid-19 case distribution Methods ------- summarize Returns summary stati...
from flask import Flask import os FLASK_NAME = os.environ.get("FLASK_NAME") FLASK_SECRET_KEY = os.environ.get("FLASK_SECRET_KEY") def create_app(): app = Flask(FLASK_NAME) app.secret_key = FLASK_SECRET_KEY return app app = create_app()
# Hacer un menú infinito para las 4 operaciones aritméticas básicas: # 1) Suma. # 2) Resta. # 3) Multiplicación. # 4) División. while True: ans = int(input("Operaciones aritméticas:\n1) Suma \n2) Resta \n3) multiplicación \n4) División \nOpción: ")) if (ans == 1): print("Suma") num1 = int(input...
# Zhihao Zhang # roadway class in python from src.curves import CurvePt from src.Vec import VecSE2, VecE2 from src.Vec.geom import geom import math import re import warnings class LaneBoundary: def __init__(self, style: str, color: str): ''' :param style: LaneBoundary style :param color: L...
#!/usr/bin/env python ''' Creates initial configuration for a system containing single branched linear chain in an unbounded domain. ''' import sys import math import numpy as np from configuration import Configuration from config_io import * #-----------------------------------------------------------------------...
import os import pyblish.api class ExtractRender(pyblish.api.InstancePlugin): label = "Extract Render" order = pyblish.api.ExtractorOrder hosts = ["filesys"] targets = [ "seqparser", ] families = [ "reveries.renderlayer", ] def process(self, instance): stagi...
""" Exception raised when the origin server requires the request to be conditional. Intended to prevent the 'lost update' problem, where a client GETs a resource's state, modifies it, and PUTs it back to the server, when meanwhile a third party has modified the state on the server, leading to a conflict """ from rinzle...
# Create an empty set s = set() # Add elements to set s.add(1) s.add(2) s.add(3) s.add(4) s.add(3) print(s) s.remove(2) print("after removed 2 :", s) print(f"after removed 2 : {s}") print(f"The set has {len(s)} elements.")
import json import pytest from django.urls import reverse from saleor.dashboard.menu.forms import AssignMenuForm from saleor.dashboard.menu.utils import update_menu_item_linked_object from saleor.menu.models import Menu, MenuItem from ..utils import get_redirect_location def test_assign_menu_form(admin_user, menu,...
import numpy as np import os import sys import seaborn as sns import matplotlib.pyplot as plt from numpy import linalg as LA import math import xlsxwriter from matplotlib import cm # Fills transpose of mat[N][N] in tr[N][N] def transpose(mat, tr, N): for i in range(N): for j in range(N): ...
# -*- coding: utf-8 -*- # Copyright (c) 2017, Frappe Technologies Pvt. Ltd. and Contributors # See license.txt from __future__ import unicode_literals import frappe import unittest from frappe.utils import today, add_days, getdate from erpnext.accounts.utils import get_fiscal_year from erpnext.accounts.report.financia...
def warn(message): print("[EZBUILD]", message) def info(*args): print("[EZBUILD]", args)
from etcd import EtcdKeyNotFound from pycalico.ipam import IPAMClient import json PREFIX = "/calico/libnetwork/v1/" class LibnetworkDatastoreClient(IPAMClient): def get_network(self, network_id): """ Get the data for a network ID. :param network_id: The network ID to read. :retur...
# -*- coding:utf-8 -*- # author:hyz import sys import threading import binascii import re import time from datetime import datetime import json from mySerial import myserial import paho.mqtt.client as mqtt import config class mqtt2sensor: def __init__(self): self.dict_num = config.doInit() self.cl...
#!/usr/bin/env python3 # coding:utf-8 import cv2 import numpy as np import rospy from sensor_msgs.msg import Image from cv_bridge import CvBridge, CvBridgeError from paddle.inference import Config from paddle.inference import PrecisionType from paddle.inference import create_predictor import yaml import time # ————...
from datetime import timedelta from typing import List, Optional from pytz import timezone from numpy import ndarray from iexfinance.stocks import Stock, get_historical_data # from iexdatac import init as iexdata_init # from iexdatac.services.basic import all_instruments as iexdata_all_instruments # from iexdatac.ser...
import os import datetime from configparser import RawConfigParser import logging from cfgexceptions import CfgUnknownCategory, CfgUnknownFile, CfgDuplicateFile, CfgUnknownAttribute EXTRUDER_KEY = "nozzle_diameter" class CfgInvalidColor(Exception): def __init__(self): pass class CfgFile: def __init__(self, att...
""" Rotten Projects Table """ import datetime import numpy as np import pandas as pd from dashboard.load import PomodorosProcessed from dashboard.typed import TypedDataFrame class RottenTable(TypedDataFrame): schema={ 'Activity': object, 'Inactive Days': np.int16 } def build_rotten_project...
import os # App settings PREFERRED_URL_SCHEME = 'https' SECRET_KEY = os.urandom( 16) # LDAP settings LDAP_URL = os.environ.get( 'LDAP_URL', 'ldap:///') BASE_DN = os.environ.get( 'BASE_DN') # Always required assert BASE_DN, "BASE_DN environment variable must be set" SCHEMA_DN = 'cn=subschema' # Attribute to check fo...
import os from subprocess import run class Gnuplot: def __init__(self, file: str, terminal: str, output: str): self._file = file self._output = output self._terminal = terminal self._vars = dict() def set_var(self, var: str, value: str): self._vars[var] = value def...
from peewee import * import sys sys.path.append(sys.path[0] + "/..") from utils.get_config import get_config_file config = get_config_file("config.json") id_super_admin = config["id_super_admin"].split(";") path_db = config["path_db"] global db db = SqliteDatabase(path_db) class BaseModel(Model): class Meta: ...
import turtle def main(): window = turtle.Screen() eliaz = turtle.Turtle() make_square(eliaz) turtle.mainloop() def make_square(eliaz): lenght = int(input('Biggest of the Square: ')) for i in range(4): make_line_and_turn(eliaz, 100) def make_line_and_turn(eliaz, le...
#! /usr/bin/env python import sys, math, os, argparse, csv csv.field_size_limit(sys.maxsize) # January 16, 2018 # Find dispersed repeated sequences in genomes. # Designed for plant mitochondrial genomes of up to a few Mbp. # May be very slow with larger genomes. # Blast can also sometimes give odd results wi...
import pytest from nlpretext.augmentation.text_augmentation import ( process_entities_and_text, get_augmenter, CouldNotAugment, UnavailableAugmenter ) @pytest.mark.parametrize( "text, text_augmented, entities, expected", [ ( "I want to buy a small black handbag.", "I wan...
from django import forms from django.contrib import admin from django.apps import apps from django.contrib.admin.sites import AlreadyRegistered from django.core.exceptions import FieldDoesNotExist from ckeditor.widgets import CKEditorWidget from django.contrib.auth.models import Permission from django.contrib.contentty...
LABELS = [ "id", "conversation_id", "datestamp", "timestamp", "timezone", "user_id", "username", "name", "place", "tweet", "mentions", "urls", "photos", "replies_count", "retweets_count", "likes_count", "hashtags", "cashtags", "link", "retw...
import time # Homogenize sensor data to contain all fields expected. # Fill in default values where value isn't available. def homogenize(sensors): out = {} for device_id, device in sensors.items(): if device_id not in out: out[device_id] = {} out[device_id]['name'] = device['name']...
import os from libs.file_utils import file_utils squad_url = 'https://rajpurkar.github.io/SQuAD-explorer/dataset/' files_ext = 'json' class dataset_squad: @staticmethod def get_dataset_squad(save_to): for dataset_fragment in ['train-v1.1', 'dev-v1.1']: dataset_fragment += "." + files_ext ...
from pymongo import MongoClient import os import json class Processor: def __init__(self): client = MongoClient('localhost', 27017) self.db = client['online_judge_2017'] def loadCollections(self, colname): self.mycol = self.db[colname] return self.mycol def printCollecti...
from EventSystem import Event import utils class ActionSystem: def __init__(self, player, rooms, tuiSystem, eventQueue): self.__player = player self.__rooms = rooms self.__tuiSystem = tuiSystem self.__eventQueue = eventQueue # a mapping for input actions to functions ...
# import smtplib # from email.mime.multipart import MIMEMultipart # # server = smtplib.SMTP('smtp.sina.com', 25) # server.login('goclare0412', 'd3f56529ea10a4f0') # server.starttls() # server.ehlo() # # message = "\ntest!" # server.sendmail(from_addr='goclare0412@sina.com', to_addrs='goclare0412@sina.com', msg...
from osbot_browser.javascript.Base_Node import Base_Node from osbot_browser.javascript.Identifier import Identifier from osbot_browser.javascript.Literal import Literal from osbot_utils.utils.Misc import list_set class VariableDeclarator(Base_Node): def __init__(self, js_ast, all_nodes): super().__init__...
# Copyright 2020 SAP SE # # 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, software ...
# Author: Kirill Leontyev (DC) class Coder: ######### ! !! !!! !!!! !!!!!! !!!! !!! !! ! ######### cp_names = ('builtin',) ######### ! !! !!! !!!! !!!!!! !!!! !!! !! ! ######### # Ref: encode: (str) -> int # decode: (int) -> str __slots__ = ('encode', 'decode') # Ref: () -> Cod...
import cv2 import face_recognition import sys if not len(sys.argv) >2: print("Please Add a Name z.B. jonas,lisa,marlon etc \n And add True if you want to make many picturs with diffrent name\n Or False if you want to take only One Image") exit(0) Video = cv2.VideoCapture(0) i = 0 while True: res,image =...
## @brief Models for the Blog app. from django.db import models from django.utils import timezone from multiselectfield import MultiSelectField from django.db.models.signals import post_save from django.dispatch import receiver ## @brief This class represents the Profile of Users enrolled in the website. class Profi...
import sys import os from Python_Scripts.data_gathering import * from Python_Scripts.data_preparation import * from Python_Scripts.model_building import * from Python_Scripts.model_validation import * from Python_Scripts.utility_functions import * function_choice = sys.argv[1] result = eval(function_choice) print(r...
# Copyright 2016 Pants project contributors (see CONTRIBUTORS.md). # Licensed under the Apache License, Version 2.0 (see LICENSE). import itertools import logging from dataclasses import dataclass from typing import Dict, Optional, Tuple, Union from pants.engine.fs import EMPTY_DIRECTORY_DIGEST, Digest from pants.eng...
# Copyright (c) 2017-2021 Cloudify Platform Ltd. 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 ...
#Задача N1. Вариант 6 #Напишите программу, которая будет сообщать род деятельности и псевдоним под которым скрывается Йоханнес Бруфельдт. #После вывода информации программа должна дожидаться пока пользователь нажмет Enter для выхода. #Будашов Андрей #03.03.2016 print("Йоханесс Бруфельд (имеет псевдоним Ахо Юхани) - фи...
# Generated by Django 2.1.5 on 2019-09-16 03:30 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('designs', '0002_auto_20190916_1119'), ] operations = [ migrations.RenameField( model_name='interfacegroup', old_name='parent...
# https://codeforces.com/contest/509/problem/A n = int(input()) range_n = range(n) range_1_n = range(1, n) m = [[0 for _ in range_n] for _ in range_n] for i in range_n: m[0][i] = m[i][0] = 1 for i in range_1_n: for j in range_1_n: m[i][j] = m[i - 1][j] + m[i][j - 1] print(m[n - 1][n - 1])
# Copyright 2015 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. from core import perf_benchmark class _TestBenchmarkFoo(perf_benchmark.PerfBenchmark): @classmethod def Name(cls): return 'test_benchmark_1' cla...
import numpy as np def rank_statistic(_rank, total, prev_hits, cutoff): cutoff = np.array(cutoff) hits = prev_hits + (_rank < cutoff) prctg = hits / total return hits, prctg def ListToFormattedString(alist, Type): # Each item is right-adjusted, width=3 if Type == 'float': formatted_lis...
from flask import Flask from flask import session, redirect, url_for, render_template, Response, request import json from urllib.parse import urlencode, quote_plus app = Flask(__name__) tokens = {} @app.route('/api/nf/balance', methods=['POST']) def balance(): content = request.json bln = { "101010"...
# -*- coding: utf-8 -*- # ***************************************************************************** # NICOS, the Networked Instrument Control System of the MLZ # Copyright (c) 2009-2022 by the NICOS contributors (see AUTHORS) # # This program is free software; you can redistribute it and/or modify it under # the t...
#!/usr/bin/env python # -*- coding: utf-8 -*- # correios-frete # https://github.com/adonescunha/correios-frete # Licensed under the MIT license: # http://www.opensource.org/licenses/mit-license # Copyright (c) 2013 Adones Cunha adonescunha@gmail.com from pyvows import Vows, expect from .utils import create_sudsobje...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Fri Jan 6 13:43:13 2017 @author: ktt """ def flatten(py_list): flat = [] for k in py_list: if k not in [None, (), [], {}]: if isinstance(k, list): flat.extend(flatten(k)) else: flat.a...
#!/usr/bin/env python3 """ Copyright (c) 2016-present, Facebook, Inc. All rights reserved. This source code is licensed under the BSD-style license found in the LICENSE file in the root directory of this source tree. An additional grant of patent rights can be found in the PATENTS file in the same directory. """ imp...