content stringlengths 5 1.05M |
|---|
'''
Author : @amitrajitbose
Problem : Codechef IPCTRAIN
Approach : Greedy
'''
t=int(input())
for _ in range(t):
finalAnswer=0
n,day=[int(x) for x in input().strip().split()]
valf=[int(i) for i in range(day+1)]
dt=[]
si=[]
for i in range(n):
d,t,s=[int(x) for x in input().strip().split()]
... |
import numpy as np
from numpy.core.defchararray import isupper
def printMatrix(mat):
out = ""
for idxi, i in enumerate(mat):
for idxj, j in enumerate(i):
out += f"{mat[idxi][idxj]} "
out += "\n"
print(out)
def printCoordMatrix(mat):
mat = np.flip(mat, 1)
out = ""
fo... |
"""This module will contain class Sort and its related methods."""
class Sort(object):
"""
"""
def __init__(self, iterable=None):
if iterable is None:
iterable = []
if type(iterable) is not list:
raise TypeError('Input is not a list.')
self.len = len(itera... |
while True:
try:
age = int(input("Enter your age: "))
except ValueError:
print("Invalid value, enter an integer")
continue
except:
print("Something went wrong")
continue
if age < 0 or age > 499:
print("Age not within valid range")
continue
else... |
from itertools import product
import epimargin.plots as plt
import numpy as np
import pandas as pd
import seaborn as sns
from epimargin.estimators import analytical_MPVS
from epimargin.models import SIR
from epimargin.policy import PrioritizedAssignment, RandomVaccineAssignment, VaccinationPolicy
from studies.age_stru... |
# coding=utf-8
import camera_app
import logging
logger = logging.getLogger(__name__)
logging.getLogger().setLevel(logging.INFO)
if __name__ == '__main__':
camera_app.start()
|
from flask import Blueprint, session, render_template, request, jsonify, Response, abort, current_app, flash, Flask, send_from_directory
from jinja2 import TemplateNotFound
from functools import wraps
from sqlalchemy import or_, and_
from sqlalchemy.orm.exc import NoResultFound
from psiturk.psiturk_config import Psit... |
import pandas as pd
import torch
class DataManager:
def __init__(self, data, labels, folds):
self.raw_data = data
self.data = self.chunks(data, folds)
self.labels = self.chunks(labels, folds)
self.folds = folds
self.index = 0
def chunks(self, seq, n):
av... |
from datetime import datetime, timedelta
import requests
import collectd
class BorgBaseService:
def __init__(self):
self.endpoint = "https://api.borgbase.com/graphql"
self.api_key = None
self.next_request_time = None
self.cached_response = None
def dispatch(self, repo, value... |
import logging
import os
from telegram.ext import Updater
from db_wrapper import DBWrapper
from handlers.admins import AdminsHandler
from handlers.all import AllHandler
TOKEN = os.environ.get("TOKEN")
LOG_LEVEL = os.environ.get("LOG_LEVEL")
DB_FILE = os.environ.get("DB_FILE")
logging.basicConfig(format='%(asctime)s... |
from flask_wtf import FlaskForm
from wtforms import StringField,TextAreaField,FileField,SubmitField
from wtforms.validators import Required
class CommentForm(FlaskForm):
title = StringField('Comment title',validators= [Required()])
comment = TextAreaField('Comment review')
submit = SubmitField('submit')
... |
# Implement the Linear Reciprocal Maximization problem
import gurobipy as gp
import numpy as np
from gurobipy import *
id = 903515184
# Invoke Gurobi to solve the SOCP
def solve_socp(id, m=400, n=50):
gm = gp.Model("reciprocal")
A, b = get_data(id, m, n)
# print(A.shape, b.shape) # (400, 50... |
from ..api_base import ApiBase
class CorporateCreditCardExpenses(ApiBase):
"""Class for BankTransactions APIs."""
GET_CORPORATE_CREDIT_CARD_EXPENSES = '/api/tpa/v1/corporate_credit_card_expenses'
GET_CORPORATE_CREDIT_CARD_EXPENSES_COUNT = '/api/tpa/v1/corporate_credit_card_expenses/count'
def get(se... |
import prata
import time
import timeit
import numpy as np
import sys
import random
import string
B = 1
KB = 1000
MB = 1000000
END = []
def getString(s):
#''.join(random.choice(string.ascii_letters) for x in range(int(real)))
real = 1 if (s-49) < 1 else s-49
return "1"*real
TIMES = 5
SLEEP = 2
NUMBER = ... |
# -*- coding: utf-8 -*-
"""
This file is used for indexing FedWeb2013.
@author: Shuo Zhang
"""
import os
import tarfile
from bs4 import BeautifulSoup
from Elastic import Elastic
def fedweb13_index(index_name,output_file):
elastic = Elastic(index_name)
mappings = {
# "id": Elastic.notanalyzed_field()... |
import ast
import re
import shutil
import sys
import urllib.parse
import urllib.request
from pathlib import Path
def download_build(branch_url: str, build: str, reg_exr: re, directory: Path):
build_url = branch_url + build + "/"
build_api_url = build_url + "api/python"
artifacts = ast.literal_eval(urllib.... |
from tests.test_helper import *
from braintree.test.credit_card_numbers import CreditCardNumbers
from datetime import datetime
from datetime import date
from braintree.authorization_adjustment import AuthorizationAdjustment
from unittest.mock import MagicMock
class TestTransaction(unittest.TestCase):
@raises_with_... |
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from .models import Promise
from .models import Family
from .models import User
admin.site.register(Promise)
admin.site.register(Family)
admin.site.register(User, UserAdmin)
|
"""
Pylot
model.py
You may place your models here.
"""
from active_sqlalchemy import SQLAlchemy
import pylot.component.model
from . import get_config
config = get_config()
db = SQLAlchemy(config.DATABASE_URI)
# User Struct.
UserStruct = pylot.component.model.user_struct(db)
# Post Struct
PostStruct = pylot.compo... |
from typing import List, Tuple
import logging
from .track import Track
from vcap import DetectionNode
from vcap_utils import iou_cost_matrix, linear_assignment
MATCH_FUNC_OUTPUT = Tuple[
List[Tuple[DetectionNode, Track]],
List[Track],
List[DetectionNode]]
class Tracker:
def __init__(self, min_iou, ... |
def reverseArray(arr, start, end):
while start < end:
if arr[start] != arr[end]:
arr[start], arr[end] = arr[end], arr[start]
start += 1
end -= 1
return arr
def reverseArrayInRecursive(arr, start, end):
if start >= end:
return arr
arr[start], arr[end] = arr[e... |
# Copyright 1999-2020 Alibaba Group Holding 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 a... |
import pytest
from mock import patch
from uds.can.consecutive_frame import CanConsecutiveFrameHandler, \
InconsistentArgumentsError, CanDlcHandler, DEFAULT_FILLER_BYTE
from uds.can import CanAddressingFormat
class TestCanConsecutiveFrameHandler:
"""Unit tests for `CanConsecutiveFrameHandler` class."""
S... |
foo = input("Treat? ")
if foo == "Pastry":
print("Buttery flaky goodness")
elif foo == "Cake":
print("A light and fluffy classic")
elif foo == "Cookie":
print("Warm and crispy on the edges")
else:
print("We do not sell that. It sounds yum!")
foo = int(input("Wind speed? "))
if foo < ... |
from .sender import *
from .receiver import *
|
import pytest
from pre_commit.main import main as pre_commit
from versort import get_sorter
def test_style():
"""Just run pre-commit and see what happens."""
pre_commit(("run", "--all-files", "--show-diff-on-failure", "--color=always"))
def test_unknown_sorter():
"""See there's a valid error when a sor... |
# -*- coding: utf-8 -*-
# (Deprecated) The old version of similarity calculation. Will be removed in upcoming update.
from func.utils import Database
from func.model import Model
from pyspark.sql.functions import column
import pickle
import time
def prefilter(db, test):
app_query = 'SELECT * FROM app WHERE... |
from django.conf import settings
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import AllowAny
from rest_framework.exceptions import NotFound
from allauth.account.models import EmailAddress
from users.models import User
from organizations_ext.model... |
from doodledashboard.component import NotificationCreator
from doodledashboard.notifications.notification import Notification
from doodledashboard.notifications.outputs import TextNotificationOutput
class TextInMessage(Notification):
"""Creates a notification containing the text of the last message"""
def cr... |
from .util import generate_evenly_spaced_data_set
def pagie_func1(x, y):
return 1.0 / x ** (-4) + 1.0 / y ** (-4)
def generate_pagie1():
train = generate_evenly_spaced_data_set(pagie_func1, 0.4, (-5, 5))
test = generate_evenly_spaced_data_set(pagie_func1, 0.4, (-5, 5))
return train, test
all_probl... |
# mc_bot.py
# Source: https://github.com/DrGFreeman/mc-to-discord
#
# MIT License
#
# Copyright (c) 2018 Julien de la Bruere-Terreault <drgfreeman@tuta.io>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# i... |
"""Setup module for NI Veristand."""
from os.path import dirname
from os.path import join
from setuptools import find_packages
from setuptools import setup
pypi_name = 'niveristand'
def get_version(name):
"""Calculate a version number."""
import os
version = None
script_dir = os.path.dirname(os.path... |
# -*- coding: utf-8 -*-
from brewtils.models import Operation
from beer_garden.api.http.base_handler import BaseHandler
class NamespaceListAPI(BaseHandler):
async def get(self):
"""
---
summary: Get a list of all namespaces known to this garden
responses:
200:
... |
from PIL import Image
import numpy
from .base import Base
from .loss_func import psnr_np, mse_np
from utils import Loader, Keeper
class BaseInterpolation(Base):
_scale_type = None
_scale_factor = 4
def model(self):
return None
def serialize(self):
pass
def unserialize(self):
... |
#Archivo para rutas USER
#Este modulo permite definir subrutas o rutas por separado, response es para respuestas HTTP
from fastapi import APIRouter, Response, status
#Esto solo me dice a donde conectarme, no hay un schema
from config.db import conn
#Aquí traemos el schema
from models.order_details import order_de... |
"""
Definitions of various hard coded constants.
Pyro - Python Remote Objects. Copyright by Irmen de Jong (irmen@razorvine.net).
"""
# Pyro version
VERSION = "4.30"
# standard object name for the Daemon object
DAEMON_NAME = "Pyro.Daemon"
# standard name for the Name server itself
NAMESERVER_NAME = "Py... |
import logging
import bson
import hashlib
import base58
def doc2CID (inp):
try:
# JSON OBJ to BSON encode
bson_ = bson.dumps(inp)
# SHA-256 Double Hashing
hash_ = hashlib.sha256(bson_)
hash_ = hashlib.sha256(hash_.digest())
# Convert to Base-58 string
b58c_ ... |
# Supported clients
from .supported_search_clients import SupportedSearchClients
# Utility function
from .download_images import download_image, download_all_images
# Search API Clients
from .search_api_client import SearchAPIClient
from .google_cse_client import GoogleCustomSearchEngineClient
from .bing_image_search... |
from quantumdl.models.quantummodel import *
from quantumdl.core.engine import * |
import datetime
from django.utils.timezone import utc
from rest_framework.authentication import TokenAuthentication
from rest_framework import exceptions
from django.utils.six import text_type
import base64
import binascii
from django.contrib.auth import get_user_model
from django.middleware.csrf import CsrfViewMiddlew... |
from __future__ import annotations
from unittest import TestCase
from tests.classes.simple_order import SimpleOrder
from tests.classes.simple_project import SimpleProject
from tests.classes.simple_chart import SimpleChart
from tests.classes.simple_setting import SimpleSetting
from tests.classes.author import Author
fro... |
# -*- coding: utf-8 -*-
from flask import render_template, request, redirect, url_for, abort
from fcsite import check_forced_registration_blueprint
from fcsite.models import bbs
from fcsite.auth import requires_login
from fcsite.utils import pagination, logi
mod = check_forced_registration_blueprint('bbs', __name__, ... |
# Copyright 2014: Mirantis 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 b... |
# This file was automatically generated by SWIG (http://www.swig.org).
# Version 3.0.10
#
# Do not make changes to this file unless you know what you are doing--modify
# the SWIG interface file instead.
from sys import version_info as _swig_python_version_info
if _swig_python_version_info >= (2, 7, 0):
... |
# Author: Calebe Elias Ribeiro Brim
# Last Update: 03/06/2018
import numpy as np
def bitsToBytes(values):
'''
Generate relative bits integers
Usage:
bitsToBytes(array.shape(1,10)) => array.shape(1,1)
bitsToBytes(array.shape(2,10)) => array.shape(2,1)
'''
ln = val... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'KeyWizard.ui'
#
# Created by: PyQt5 UI code generator 5.14.0
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_KeyWizard(object):
def setupUi(self, KeyWizard):
KeyWiz... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from pygame import *
import os
PLATFORM_WIDTH = 32
PLATFORM_HEIGHT = 32
PLATFORM_COLOR = "#FF6262"
ICON_DIR = os.path.dirname(__file__) # Полный путь к каталогу с файлами
class Platform(sprite.Sprite):
def __init__(self, x, y):
sprite.Sprite.__init__(self)
... |
import sys
import os
from setuptools import setup
"""
Use pandoc to convert README.md to README.rst before uploading
$ pandoc README.md -o README.rst
"""
if "publish" in sys.argv:
os.system("python setup.py sdist upload")
os.system("python setup.py bdist_wheel upload")
sys.exit()
setup(
name="pipr... |
"""Module for working with transcripts, creating transcript DBs and reading from transcript DB"""
from __future__ import division
import gzip
from operator import itemgetter
import pysam
import datetime
import os
class Transcript(object):
"""Class for a single transcript"""
def __init__(self, id=None, vers... |
import os
import sys
import time
import subprocess
ITERATIONS = 10
COUNT = 20000000
VERBOSE = False
NL = '\n'
INCLUDE = "../../../src"
CC = 'gcc'
CCPP = 'g++' # LoL
OPT = '-O3'
print(f'Using {CC} compiler')
def execute_command(commands):
print(' '.join(commands))
subprocess.run(commands, shell=True)
# C... |
# Copyright 2011-2013 Colin Scott
# Copyright 2011-2013 Andreas Wundsam
# Copyright 2012-2013 Sam Whitlock
# Copyright 2012-2012 Kyriakos Zarifis
#
# 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 ... |
# Songsheng YING
# coding=utf-8
# python3.6.7 Anaconda
import os, sys
import numpy as np
from progressbar import ProgressBar, Percentage, Bar
import xml.etree.ElementTree as ET
def data_file_reader_fr(file_name, lang):
print(" Working on " + file_name)
if lang == "French":
path = os.getcwd() + '/da... |
workflow_xml_start = """<workflow-app name="etk-april-2017" xmlns="uri:oozie:workflow:0.5">
<global>
<configuration>
<property>
<name>oozie.launcher.mapreduce.map.memory.mb</name>
<value>10000</value>
</property>
</configu... |
from matplotlib import pyplot as plt
from matplotlib_venn import venn3
def plot_confusion_matrix(cm, cmap=plt.cm.Blues):
"""
Args:
cm (np.ndarray): Confusion matrix to plot
cmap: Color map to be used in matplotlib's imshow
Returns:
Figure and axis on which the confusion matrix is ... |
from src import network
import numpy as np
from src.study.utils import downloader
from src.study.mnist_common import mnist_reader
items = ["T-shirt/top","Trouser","Pullover","Dress","Coat","Sandal","Shirt","Sneaker","Bag","Ankle","boot"]
def download_mnist_fashion_data():
downloader.download_data("http://fashio... |
import re
def modify_en_text(text, modify_mode='BASIC', keep_emoji=True):
""" Make your text easy to read and to translate.
Args:
text(str):
target dirty text.
modify_mode(str):
mode selection
keep_emoji(bool):
call back ... |
from functools import reduce
testcases = int(input())
for t in range(testcases):
n = int(input())
vals = list(map(int, input().split()))
missed = 0
for i in range(1, len(vals)):
x = abs(vals[i] - vals[i - 1])
if x > 0:
x -= 1
missed += x
prin... |
# Import Required Libraries
from flask import Flask, render_template, request
import pickle
# Initialise the object to run the flask app
app = Flask(__name__, static_folder='static', template_folder='templates')
# Load the pickled model file
model = pickle.load(open('model.pkl', 'rb+'))
@app.route('/', methods=['... |
# Copyright 2017 Cisco Systems, 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 functools
import operator
import unittest
from migen import *
def cols(rows):
"""
>>> a = [
... [1, 2],
... ['a', 'b'],
... [4, 5],
... ]
>>> for c in cols(a):
... print(c)
[1, 'a', 4]
[2, 'b', 5]
>>> a = [
... [1, 2, 3],
... ['a', 'b', 'c'],
... ]... |
# -*- coding: utf-8 -*-
"""
DTSA-II Script - J. R. Minter - 2016-10-12
massFractionsTheEasyWay.py
Date Who Comment
---------- --- -----------------------------------------------
2016-10-12 JRM Mass fractions the easy way...
Elapse: 0:00:00.0 ROCPW7ZC5C42
"""
import sys
sys.packageManager.makeJavaPackag... |
# Import Dependencies
import numpy as np
import pandas as pd
import datetime as dt
import sqlalchemy
from sqlalchemy import desc
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine, func, inspect... |
# Normals are for all puzzles where all 3 sides are the same
# 37 is Skewb
# 38 is Pyraminx main
# 39 is Pyraminx primary corners
# 40 is Pyraminx secondary corners
# 41 is Megaminx main
# 42 is Megaminx secondary
normals = {
2: {'moves': (('U', 'D'), ('F', 'B'), ('R', 'L')), 'directions': ('', "'", '2')},
3: {... |
from setuptools import setup
setup(
name="scripture-burrito",
version="0.0.2",
description="Python library for the Scripture Burrito data interchange format",
url="http://github.com/bible-technology/scripture-burrito-python",
author="BT Tech Consortium",
author_email="jtauber@jtauber.com",
... |
import pytest
import numpy as np
import pennylane as qml
from pennylane_qiskit import AerDevice, BasicAerDevice
from conftest import U, U2, A
np.random.seed(42)
THETA = np.linspace(0.11, 1, 3)
PHI = np.linspace(0.32, 1, 3)
VARPHI = np.linspace(0.02, 1, 3)
@pytest.mark.parametrize("theta, phi", list(zip(THETA, P... |
import argparse
import logging
import os
import sys
sys.path.insert(0, os.path.join(sys.path[0], ".."))
import development.configuration # pylint: disable = wrong-import-position
import development.environment # pylint: disable = wrong-import-position
logger = logging.getLogger("Main")
def main():
current_direct... |
import sys
import os
import json
import hashlib
import EVMfunction as EVMf
import EVMcompiler as EVMc
import EVMparse as EVMp
print('Kam1n0 script for EVM is now running...')
print('start persisting...')
args = sys.argv
sol_file_name = args[1].split('\\')[-1]
abs_file_name = os.path.abspath(args[1])
j... |
#!/usr/bin/env python3
"""Bank account without synchronization cause race condition """
class UnsyncedBankAccount:
"""Bank account without synchronization"""
balance: float
def __init__(self, balance: float = 0):
self.balance: float = balance
def deposit(self, amount: float) -> None:
... |
# import setuptools
# with open("README.md", "r") as fh:
# long_description = fh.read()
# setuptools.setup(
# #Here is the module name.
# name="TOPSIS-Shivansh-101803103",
# #version of the module
# version="0.0.1",
# #Name of Author
# author="Shivansh Kumar",
# #your Email add... |
from collections import defaultdict
from contextlib import contextmanager
from enum import Enum
import redis_lock
from passari_workflow.redis.connection import get_redis_connection
from rq import Queue
from rq.exceptions import NoSuchJobError
from rq.job import Job
from rq.registry import FailedJobRegistry, StartedJob... |
#!/usr/bin/env python
# coding: utf-8
# # 2. Τιμές, τύποι και μεταβλητές. Συμβολοσειρές
# ## Σταθερές (Constants)
#
# H Python δεν διαθέτει προκαθορισμένες *σταθερές* όπως άλλες γλώσσες προγραμματισμού.
# Όμως κατά σύμβαση και όχι κατά κανόνα έχει συμφωνηθεί οι *σταθερές* να ονοματίζονται με κεφαλαίους χαρακτήρες.
... |
import os,sys
import numpy as np
import torch
import torch.nn.functional as F
import h5py, time, itertools, datetime
from scipy.ndimage import label
from scipy.ndimage.morphology import binary_erosion
from torch_connectomics.utils.net import *
from torch_connectomics.utils.vis import visualize_aff
def test(args, test... |
import ML
import function.saveNewsList
import hook.hooks
import job
import json
from nose.tools import with_setup
from ML import Server
def setup_func():
ML.init(
"57f9edc887d4a7e337b8c231",
master_key="elhmazJfd29ZTFBhR0M3SmJ0R2N6UQ",
)
@with_setup(setup_func)
def test_saveNewsDetail():
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2016-08-11 15:42
from django.db import migrations
import utilities.fields
class Migration(migrations.Migration):
dependencies = [
('dcim', '0017_rack_add_role'),
]
operations = [
migrations.AddField(
model_name='device',
... |
import numpy as np
import sqlalchemy
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine, func
from flask import Flask, jsonify
import datetime
from dateutil.relativedelta import relativedelta
from datetime import datetime
from sqlalchemy import desc... |
#!/usr/bin/env python
import networkx as nx
import sys
with open('soc-sign-bitcoinotc.csv', 'r') as fin:
with open('bitcoinotc.in', 'a') as fout:
G = nx.DiGraph()
fout.write("Relation Edges" + '\n')
fout.write("From To" + '\n')
for line in fin:
n1, n2, rating, time = line.split(',')
fout.write(str(n1) ... |
from __future__ import division
import copy
from Game.deck import *
from Game.column import *
from Game.heap import *
NB_CARDS_SUBDECK = 24
NB_HEAPS = 4
NB_COLUMNS = 7
IN_HEAP = 'heap'
IN_DECK = 'deck'
IN_COL = 'col'
UNDRAWN = 'undraw'
ACTIONS = ['draw', 'deck-heap', 'deck-col', 'col-heap', 'heap-col', 'col-col']
c... |
from .transformer_factory import function_transformer # noqa
|
import sys
import requests
import mysql.connector
import datetime
from mysql.connector import errorcode
from bs4 import BeautifulSoup
def get_link(argv):
hari = str(datetime.datetime.now().day)
bulan = str(datetime.datetime.now().month)
tahun = str(datetime.datetime.now().year)
url = "http://www.viva.... |
from ..registry_tools import iso_register
from .core import UnitedStates
@iso_register('US-NY')
class NewYork(UnitedStates):
"""New York"""
include_lincoln_birthday = True
include_election_day_every_year = True
|
"""jc - JSON CLI output utility `sfdisk` command output parser
Supports the following `sfdisk` options:
- `-l`
- `-F`
- `-d` (deprecated - only for older versions of util-linux)
- `-uM` (deprecated - only for older versions of util-linux)
- `-uC` (deprecated - only for older versions of util-linux)
- `-uS` (depre... |
from __future__ import print_function
# vim: set fileencoding= UTF-8
#!usr/bin/python
"""Word Spot
ENG: Enter string. Output. All world in order they came in, if any word have appired more then once, print index in (paranthesise)
input: qwe sdf tyu qwe sdf try sdf qwe sdf rty sdf wer sdf wer
output:qwe(7) sdf(12) ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
from typing import Dict, Tuple, Any, Set
from tabun_stat import utils
from tabun_stat.processors.base import BaseProcessor
class BirthdaysProcessor(BaseProcessor):
def __init__(self) -> None:
super().__init__()
# {(день, месяц): айдишники... |
#!/usr/bin/python
"""
This script provides a set of tools to parse the vector and scalar files dumped
out of omnet simulation and indexed data and stats for use of other modules.
"""
from numpy import *
from glob import glob
from optparse import OptionParser
from pprint import pprint
from functools import partial
fro... |
from Proxy import ProxyFactory, Proxy
from LRUCache import LRUCache
from utils import distance, stress, MAX_DISTANCE, LOWEST_STRESS
from typing import Hashable, List, Tuple, Dict, Any
class Origin:
def __init__(self, database, max_size_of_LRUCache : int, max_age_of_LRUCache: int, load_balancing_interval : int):
... |
from __future__ import print_function
from .client import Client
__title__ = 'Steamfront'
__author__ = 'Callum Bartlett'
__license__ = 'MIT'
__copyright__ = 'Copyright 2017 Callum Bartlett'
__version__ = '0.1.0'
if __name__ == '__main__':
from sys import argv
if len(argv) < 2:
print('Please give the name of a ga... |
import sys
from ctypes import *
sys.path.append('../')
#import vscp.udp as udp
#from vscp.vscp_class import *
#from vscp.vscp_type import *
from vscp import *
def makeClass2StrMeasurement( vscpclass, vscptype, strval ):
ex = vscp.vscpEventEx()
return ex
e = vscp.vscpEvent()
ex = vscp.vscpEventEx()
print(ty... |
"""
Test cases for linear programming based on CVXOPT
This case is an economic dispatch code
"""
from cvxopt import matrix
from cvxopt import solvers
class LinearProgramming():
def run(self, PG_MAX, PG_MIN, CG, PD):
"""
:param PG_MAX: maximal generator output
:param PG_MIN: minimal gene... |
import secrets
import redis
from app.core.config import settings
ok_status = {'detail': 'Ok'}
def generate_id():
return secrets.token_urlsafe(8)
class SingletonMeta(type):
_instances = {}
def __call__(cls, *args, **kwargs):
if cls not in cls._instances:
instance = super().__call_... |
import json
import logging
import os
import pytest
from fhir2dataset.query import Query
from tests.tools import create_resource_test
log_format = "[%(asctime)s] [%(levelname)s] - %(message)s"
logging.basicConfig(level=logging.INFO, format=log_format)
@pytest.mark.parametrize(
"dirname, fhir_api_url",
[
... |
''' Tst cases fro get_names method '''
import unittest
from spydrnet import ir
from spydrnet_physical.util import get_names
from spydrnet_physical.util import get_attr
class TestGetNames(unittest.TestCase):
''' Test case class '''
def setUp(self):
''' Basic element setup '''
self.definitio... |
import random
from hashlib import sha256
def gen_password(user_password):
'''产生一个安全的密码'''
bin_password = user_password.encode('utf8') # 将密码转成 bytes 类型
hash_value = sha256(bin_password).hexdigest() # 计算用户密码的哈希值
salt = '%x' % random.randint(0x10000000, 0xffffffff) # 产生随机盐
safe_password = salt + h... |
__author__ = 'Eric Weast'
__copyright__ = "Copyright 2014, Eric Weast"
__license__ = "GPL v2"
from .exceptions import EncodingError
from .exceptions import DecodingError
from .decoder import decode
from .decoder import decode_from_file
from .encode import encode |
from copy import copy
from meerk40t.core.cutcode import RasterCut
from meerk40t.core.element_types import *
from meerk40t.core.node.node import Node
from meerk40t.core.parameters import Parameters
from meerk40t.core.units import Length
from meerk40t.image.actualize import actualize
from meerk40t.svgelements import Col... |
"""
training script
date: 10/4
author: arabian9ts
"""
# escape matplotlib error
import matplotlib
matplotlib.use('Agg')
# escape tensorflow warning
import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
import datetime
import tensorflow as tf
import numpy as np
import pickle
import threading
import matplotlib.pyplot as p... |
import unittest
from contiguous.structures import DataSection, Group
from contiguous.types import String
class TestContiguous(unittest.TestCase):
""" Test basic functionality with native Python types in schemas."""
def test_lengths(self):
data = DataSection(
String("name", 25),
... |
from typing import List
class ListNode:
def __init__(self, val=0):
self.val = val
self.next = None
def insert_at_tail(nodes: List[int]) -> ListNode:
head = ListNode(nodes[0])
for node in nodes[1:]:
insert_helper(head, node)
return head
def insert_helper(head: ListNode, node... |
import ast
import rest_framework.serializers as module_to_patch
from drf_jsonpatch.patcher import Patcher
from drf_jsonpatch.nodes.serialiazers import (
import_jsonpatch,
import_apply_json_patch,
if_apply_jsonpatch,
)
patch = Patcher(module_to_patch)
# ---- import jsonpatch ----
# added between django... |
begin_unit
comment|'# Copyright 2012 Red Hat, Inc.'
nl|'\n'
comment|'# All Rights Reserved.'
nl|'\n'
comment|'#'
nl|'\n'
comment|'# Licensed under the Apache License, Version 2.0 (the "License"); you may'
nl|'\n'
comment|'# not use this file except in compliance with the License. You may obtain'
nl|'\n'
comment|'... |
#!/usr/bin/env python
import argparse
import os
import sys
from lib.config import enable_verbose_mode, get_target_arch
from lib.util import execute_stdout
SOURCE_ROOT = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
def main():
os.chdir(SOURCE_ROOT)
args = parse_args()
if args.verbose:
ena... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.