content stringlengths 5 1.05M |
|---|
# -*- coding: utf-8 -*-
def main():
n = int(input())
a = [int(input()) for _ in range(n)]
count = 0
years = 0
for ai in a:
years += ai
if years <= 2018:
count += 1
print(count)
if __name__ == '__main__':
main()
|
import time
import re
import socket
import sys
import traceback
import paho.mqtt.client as mqtt
from threading import Thread
class TemperatureLogger:
config = None
mqtt_client = None
mqtt_connected = False
worker = None
# removed as not one of my requirements
#temperatures = {}
def __ini... |
import unittest
from calibre.ebooks.metadata.sources.test import (test_identify_plugin,
title_test, authors_test,
series_test)
from source import Comicvine
class TestFileList(unittest.TestCase):
def test_list(sel... |
# -*- coding: utf-8 -*-
"""
Functions for performing statistical preprocessing and analyses
"""
import warnings
import numpy as np
from tqdm import tqdm
from itertools import combinations
from scipy import optimize, spatial, special, stats as sstats
from scipy.stats.stats import _chk2_asarray
from sklearn.utils.valid... |
import sys
import pathlib
# sys.path.append(pathlib.Path(__file__).resolve().parents[1].as_posix())
# sys.path.append((pathlib.Path(__file__).resolve().parents[1] / 'submodule/FightingICE/python').as_posix())
import numpy as np
# from nike.contest_modified.utils import Environment, Agent
from utils import Agent
cl... |
class RemovedInWagtailMenus29Warning(DeprecationWarning):
pass
removed_in_next_version_warning = RemovedInWagtailMenus29Warning
class RemovedInWagtailMenus210Warning(PendingDeprecationWarning):
pass
class RemovedInWagtailMenus211Warning(PendingDeprecationWarning):
pass
|
# settings.py #
# ============================================================================
# DEFINE THE SETTINGS CLASS FOR THE GAME TO SET UP A SPECIFIED ENVIRONMENT.
#
# !!!WARNING: THE GAME MIGHT NOT BEHAVE PROPERLY IF YOU CHANGE THE VALUES
# IN THIS FILE. BACK UP THIS FILE IF YOU WISH TO EDIT ANYTHING.
#
cla... |
from .anchor_utils import *
from .hyperparams import *
from .image_resizer import *
|
import threading
from common.pygamescreen import PyGameScreen
from webserver.server import setup_server_runner, run_http_server, run_socket_server
from webserver.video import VideoSource
from webserver.websocket import WebSocketManager
class WebControlManager:
def __init__(self, enable_http, enable_socket, pygame_s... |
from flask import Flask
from flask import jsonify
from flask_cors import CORS
from bs4 import BeautifulSoup
import threading
from queue import Queue
import requests
app = Flask(__name__)
cors = CORS(app, resources={r"/api/*": {"origins": "*"}})
request_lock = threading.Lock()
q = Queue()
data_dvds = []
@app.route('... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.10 on 2017-04-15 11:22
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('products', '0003_auto_20170321_2006'),
]
operations = [
migrations.AddField... |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2021.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative wo... |
"""
Given the array nums consisting of 2n elements in the form [x1,x2,...,xn,y1,y2,...,yn].
Return the array in the form [x1,y1,x2,y2,...,xn,yn].
Example 1:
Input: nums = [2,5,1,3,4,7], n = 3
Output: [2,3,5,4,1,7]
Explanation: Since x1=2, x2=5, x3=1, y1=3, y2=4, y3=7 then the answer is [2,3,5,4,1,7].
Example 2:
In... |
from lbry.cryptoutils import get_lbry_hash_obj
MAX_BLOB_SIZE = 2 * 2 ** 20
# digest_size is in bytes, and blob hashes are hex encoded
blobhash_length = get_lbry_hash_obj().digest_size * 2
|
import uuid
import logging
from sqlalchemy import create_engine
from dependency_injector import containers, providers
from dependency_injector.wiring import inject # noqa
from modules.catalog.module import CatalogModule
from modules.catalog.infrastructure.listing_repository import (
PostgresJsonListingRepository,... |
"""
Signal Filtering and Generation of Synthetic Time-Series.
Copyright (c) 2020 Gabriele Gilardi
"""
import numpy as np
def synthetic_wave(P, A=None, phi=None, num=1000):
"""
Generates a multi-sine wave given periods, amplitudes, and phases.
P (n, ) Periods
A (n, ... |
from typing import BinaryIO
from pycubexr.classes import MetricValues, Metric
from pycubexr.parsers.data_parser import parse_data
from pycubexr.parsers.index_parser import parse_index
def extract_metric_values(
*,
metric: Metric,
index_file: BinaryIO,
data_file: BinaryIO
) -> MetricVa... |
import csv
from functools import partial
import gzip
from pathlib import Path
from typing import Collection, Dict, Optional
from tqdm import tqdm
from molpal.objectives.base import Objective
class LookupObjective(Objective):
"""A LookupObjective calculates the objective function by looking the
value up in an... |
# Copyright 2017, Inderpreet Singh, All rights reserved.
import unittest
import json
from datetime import datetime
from pytz import timezone
from .test_serialize import parse_stream
from web.serialize import SerializeModel
from model import ModelFile
class TestSerializeModel(unittest.TestCase):
def test_event_n... |
"""
Makes a figure providing an overview of our dataset with a focus on lineages
laid out as follows:
a - Patient metadata
b - Donut plot of our lineage distributions vs the world
c - Timeline of patient sampling vs lineages identified
d - Choropleth of lineages by region
"""
import matplotlib.pyplot as plt
import n... |
"""recipient use composite primary key
Revision ID: 2693c4ff6368
Revises: 39df5dce6493
Create Date: 2022-05-06 20:39:56.757617+00:00
"""
import sqlalchemy as sa
import sqlmodel
from alembic import op
# revision identifiers, used by Alembic.
revision = "2693c4ff6368"
down_revision = "39df5dce6493"
branch_labels = Non... |
"""Instalador para el paquete pyqt_password"""
from setuptools import setup
long_description = (
open("README.org").read()
+ '\n' +
open("LICENSE").read()
+ '\n')
setup(
name="pyqt_password",
version='1.0',
description='Aplicación para gestión de contraseñas',
long_description=long... |
#!/usr/bin/env python
#
# 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, softwar... |
#!/home/toby/anaconda/bin/python
import matplotlib.pyplot as plt
import numpy as np
def log_10_product(x, pos):
if (x < 1.0):
return '%3.1f' % (x)
else:
return '%i' % (x)
cc = '0.10'
font = {'family' : 'DejaVu Serif',
'weight' : 'normal',
'size' : 20,
}
tfont = {
'family' : 'DejaVu ... |
import config
from page_objects.common import Common
from utilities.data_factory import DataRead
from utilities.locator_strategy import LocatorStrategy
class Contact(Common):
def __init__(self, driver):
super().__init__(driver)
self.driver = driver
self.data = DataRead.json_read('data.jso... |
from nnf import Var
from lib204 import Encoding
from tree import buildTree, findLeaves, findAllParents
givenBoardCondition = ["Wo_11 >> (Wh_21 || Sh_22)", "Wh_21 >> Br_31", "Wh_21 >> Wo_32", "Sh_22 >> Wo_31"]
S = ["Wh", "Wo", "Br"] #set of nodes required for a winning branch
k = 3 #maximum amount of steps required to ... |
# Generated by Django 3.1.1 on 2020-09-08 10:03
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('sciencehistory', '0008_auto_20200908_1901'),
]
operations = [
migrations.AddField(
model_name='referringflow',
name=... |
from ioUtils import getFile
from fsUtils import setDir, mkDir, isDir, moveDir
class myMusicName:
def __init__(self, debug=False):
self.debug = False
self.abrv = {}
self.abrv["AllMusic"] = "AM"
self.abrv["MusicBrainz"] = "MC"
self.abrv["Discogs"] = "DC"
... |
"""
Package for components related to video/image processing,
excluding camera/display interface related components.
"""
|
# coding=utf-8
# Copyright 2022 The Deeplab2 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 ... |
n = int(input())
mem = [[0, 0] for i in range(80)]
m1 = m2 = 0
m = 80
for i in range(n):
x = int(input())
p = x % m
y_min = mem[p][0]
y_max = mem[p][1]
if y_max and abs(x - y_max) > abs(m1 - m2):
m1 = x
m2 = y_max
if y_min and abs(x - y_min) > abs(m1 - m2):
m1 = x
m2 = y_min
if x < y_min or not y_m... |
from .catboost_ranker import CatBoostRanker
|
import numpy as np
# Answer for Part 2a)
def MLE_transition_parameters(train_dir = "data/ES/train"):
''' Calculates the transition parameters by count(y->x)/count(y)
:param train_dir: our train file path to either ES or RU
:type train_dir: str
:return: count_y_dict, Count(yi-1), keys are word '... |
import torch
import torch.nn as nn
import torch.nn.functional as F
def add_mask_transformer(self, temperature=.66, hard_sigmoid=(-.1, 1.1)):
"""
hard_sigmoid:
False: use sigmoid only
True: hard thresholding
(a, b): hard thresholding on rescaled sigmoid
"""
self.temperature =... |
import time
from typing import Any
class Cache:
''' Inner cache for registered callbacks '''
def __init__(self):
self.data = {}
def add(self, seq, webhook_url: str, pin: str, retention_sec: int, rand: str, context: Any) -> None:
'''
Saves data in a dictionary
: param seq:... |
from dataclasses import dataclass
from datetime import timedelta
from functools import lru_cache
from typing import Optional, Union, List
from bson import ObjectId
from extutils.dt import localtime
from extutils.linesticker import LineStickerUtils
from JellyBot import systemconfig
from flags import AutoReplyContentTy... |
#! ./venv/bin/python
from GitHubBatchRunner import GitHubBatchRunner
if __name__ == '__main__':
batch_file = "repo_names.json"
output_folder = r'./Output/all_issues_c_repositories'
github_user_name = 'user_name'
github_password = 'password'
log_flag = True
error_log_file_name = r'error_log.txt... |
__all__ = ['vk']
from .vk import residual_screen, residual_screen_sphere
|
from flask_restful.reqparse import RequestParser
class aggregateValidate(object):
def validate(self):
valid = RequestParser(bundle_errors=True)
valid.add_argument("pipeline", required=True)
valid.add_argument("entity", required=True)
return valid.parse_args()
|
from bindings import Cloudevent
import bindings as b
import wasmtime
from cloudevents.http import CloudEvent, to_binary
def run(cloudevent: CloudEvent) -> None:
store = wasmtime.Store()
module = wasmtime.Module.from_file(store.engine, "crates/ce/target/wasm32-wasi/release/ce.wasm")
linker = wasmtime.Link... |
import numpy as np
from dipy.tracking.distances import (bundles_distances_mam,
bundles_distances_mdf)
if __name__ == '__main__':
np.random.seed(42)
filename_idxs = [0, 1]
embeddings = ['DR', 'FLIP']
ks = [5, 20, 40, 100]
nbs_points = [20, 64]
distance_thresh... |
#flask testing
from flask import Flask, render_template, request, redirect, url_for, send_file, send_from_directory
from Tkinter import * #Needed for the GUI portion
import Tkinter as tk
import os #Needed for the GUI portion
import shlex, subprocess #Needed to call on the C program
from email.mime.multipart import MIM... |
# -*- coding: utf-8 -*-
"""
Testing class for record progress endpoints of the Castor EDC API Wrapper.
Link: https://data.castoredc.com/api#/record-progress
@author: R.C.A. van Linschoten
https://orcid.org/0000-0003-3052-596X
"""
import pytest
from castoredc_api.tests.test_api_endpoints.data_models import (
recor... |
# An implementation of Memory game
# (c) gengwg [at] gmail com
try:
import simplegui
except ImportError:
import SimpleGUICS2Pygame.simpleguics2pygame as simplegui
import random
# cards
deck = []
# exposed lists. if True, expose card. Else Green rectangle.
exposed = []
# define event handlers
def new_game():... |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2006-2007 Alec Thomas <alec@swapoff.org>
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
#
"""CLY and readline, together at last.
This module uses readline's line editing and tab completion along w... |
# -*- coding: utf-8 -*-
"""Language ISO codes
https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes
"""
from os import path
import re
__all__ = [
'CODES_FILE',
'iso_codes'
]
# default model location
CODES_FILE = path.join(path.dirname(__file__), 'data', 'lang_iso_codes.csv')
with open(CODES_FILE, 'r') as f:
... |
import torch
from torch.fx.graph import Node
from .pattern_utils import (
register_fusion_pattern,
)
from .utils import _parent_name
from .quantization_types import QuantizerCls
from ..fuser_method_mappings import get_fuser_method
from abc import ABC, abstractmethod
from typing import Any, Callable, Dict
# -------... |
# -*- coding: utf-8 -*-
"""
Created on Nov 07, 2014
@author: Tyranic-Moron
"""
from IRCMessage import IRCMessage
from IRCResponse import IRCResponse, ResponseType
from CommandInterface import CommandInterface
from string import maketrans
class Flip(CommandInterface):
triggers = ['flip']
help = 'flip <text> -... |
import sys
from django.core import serializers
from django.core.management.base import NoArgsCommand
from django.db.models import get_apps, get_models
class Command(NoArgsCommand):
help = 'Dump a common serialized version of the database to stdout.'
def handle_noargs(self, **options):
models = []
... |
# 80 ms ; faster than 85.96 %
class Solution:
def searchRange(self, nums: List[int], target: int) -> List[int]:
i = 0
j = len(nums)
left = -1
right = -1
while i<j:
mid = (i+j)//2
if nums[mid] == target:
if mid == 0 or (mid>0 and... |
"""
Use secrets in a task
----------------------
This example explains how a secret can be accessed in a Flyte Task. Flyte provides different types of Secrets, as part of
SecurityContext. But, for users writing python tasks, you can only access ``secure secrets`` either as environment variable
or injected into a file.... |
import os
from typing import Generator
import asyncpg
import pytest
from ddtrace import Pin
from ddtrace import tracer
from ddtrace.contrib.asyncpg import patch
from ddtrace.contrib.asyncpg import unpatch
from ddtrace.contrib.trace_utils import iswrapped
from tests.contrib.config import POSTGRES_CONFIG
@pytest.fixt... |
import pandas as pd
import numpy as np
import os
from MagGeoFunctions import ST_IDW_Process
from MagGeoFunctions import CHAOS_ground_values
TotalSwarmRes_A = pd.read_csv(r'./temp_data/TotalSwarmRes_A.csv',low_memory=False, index_col='epoch')
TotalSwarmRes_A['timestamp'] = pd.to_datetime(TotalSwarmRes_A['timestamp'])
T... |
## ====================================================================================================
## The packages.
import feature
import library
## The root of project.
## Initialize the cache object for save the miscellany.
root = library.os.getcwd()
table = library.cache()
table.folder = library.os.path.j... |
from .source_income_serializer import *
|
"""
Задача 11. Создайте класс ИГРУШКА с методами, позволяющими вывести на экран информацию о товаре,
а также определить соответствие игрушки критерию поиска.
Создайте дочерние классы КУБИК (цвет, цена, материал, размер ребра),
МЯЧ (цвет, цена, материал, диаметр),
МАШИНКА (цвет, цена, название, производитель) со своим... |
# -*- coding: utf-8 -*-
import traceback
from django.test import TestCase, override_settings
from des.models import DynamicEmailConfiguration
from des.backends import ConfiguredEmailBackend
try:
from django.urls import reverse
except ImportError:
from django.core.urlresolvers import reverse
class ConfiguredEm... |
import logging
import sys
LOGGER_NAME = 'jira-bot'
_logger = logging.getLogger(LOGGER_NAME)
_logger.setLevel(logging.INFO)
# create logger formatter
_formatter = logging.Formatter("%(asctime)s:%(levelname)s:%(message)s")
# log to stdout
_stdout_handler = logging.StreamHandler(sys.stdout)
_stdout_handler.setFormatte... |
times=int(input())
for i in range(times):
a,b=input().split()
if len(a)!=len(b):
print(f'{a}, {b} have different lengths')
else:
length=len(a)
pa=[]
for e in range(length):
for c in range(e+1,length):
if a[e]==a[c]:
p... |
import pprint
import os
import sys
import json
def get_all_json(path):
l=[]
for root, dirs, files in os.walk(path):
for file in files:
if file.endswith('.json') and not file.startswith('.'):
l.append(os.path.join(root, file))
return l
class Visitor:
def __init__(self... |
#!/usr/bin/python
import pandas as pd
import sys
def main():
# fle_path = '/home/alex/workspace/ReportGen/python/BigBenchTimes.csv'
file_path = sys.argv[1]
df = pd.read_csv(file_path, sep=';')
df.to_excel("BigBenchTimes.xlsx")
print df.to_string()
if __name__ == '__main__':
main()
|
from elasticsearch import Elasticsearch
from elasticsearch_dsl import Q, Search
from distant_supervision.ds_utils import CorpusGenUtils
class ElasticClient(object):
# Example document from the elasticsearch index
# {
# "_index":"enwiki",
# "_type":"sentence",
# "_id":"AXCbniQUQZzz3GiznsR... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import pytest
@pytest.hookspec(firstresult=True)
def pytest_send_upload_request(upload_url: str, files: list, config: dict):
""" send upload request """
|
import numpy as np
import pandas as pd
from sparklines import sparklines
def sparklines_str(col, bins=10):
bins = np.histogram(col[col.notnull()], bins=bins)[0]
return "".join(sparklines(bins))
def df_types_and_stats(df: pd.DataFrame) -> pd.DataFrame:
missing = df.isnull().sum().sort_index()
missing... |
import logging
from pathlib import Path
from newton import Newton
import plot
import matplotlib.pyplot as plt
import numpy as np
def obj_func(x : np.array) -> float:
# Six hump function
# http://scipy-lectures.org/intro/scipy/auto_examples/plot_2d_minimization.html
return ((4 - 2.1*x[0]**2 + x[0]**4 / 3.) ... |
#!/usr/bin/env python3
# Run OSSF Scorecard (https://github.com/ossf/scorecard) against Envoy dependencies.
#
# Usage:
#
# tools/dependency/ossf_scorecard.sh <path to repository_locations.bzl> \
# <path to scorecard binary> \
# <output CSV path>
#
# You will need to checkout and build the OSSF scorecard ... |
import time
import os
from talon.voice import Context, Key, press
from talon import ctrl, clip, applescript
from . import browser
DOWNLOAD_PATH = "~/Music"
def youtube_download_audio(m):
youtube_download(video=False)
def youtube_download_video(m):
youtube_download(video=True)
def youtube_download(video... |
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 7 14:58:47 2019
@author: bdgecyt
"""
import sys
import time
import datetime
import argparse
import cv2
import numpy as np
from PIL import Image
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from matplotlib.ticker import NullLocator
import wrapper
... |
"""pip dependencies collector."""
from base_collectors import JSONFileSourceCollector
from model import Entities, Entity, SourceResponses
class PipDependencies(JSONFileSourceCollector):
"""pip collector for dependencies."""
async def _parse_entities(self, responses: SourceResponses) -> Entities:
"""... |
# -*- coding: utf-8 -*-
"""
/***************************************************************************
WilliamWallaceDialog
A QGIS plugin
This plugin do a supervised classification
-------------------
begin : 2016-05-17
git... |
import sys
html_template = file('charts-template.html', 'r').read()
file('charts.html', 'w').write(html_template.replace('__CHART_DATA_GOES_HERE__', sys.stdin.read()))
|
# get_data.py
import requests
import json
print("REQUESTING SOME DATA FROM THE INTERNET...")
print("")
request_url = "https://raw.githubusercontent.com/prof-rossetti/intro-to-python/master/data/products.json"
response = requests.get(request_url)
print(type(response))
print("")
print(response.status_code)
print("")... |
import json
import nibabel as nib
import numpy as np
from PIL import Image
from pathlib import Path
from sklearn.model_selection import train_test_split
from typing import Tuple
def load_raw_volume(path: Path) -> Tuple[np.ndarray, np.ndarray]:
"""
Loads volume of skull's scan
:param path: path to scan o... |
# Copyright 2018 Takahiro Ishikawa. 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 l... |
from .custom_library import CustomLibrary
from .feature_library import ConcatLibrary
from .fourier_library import FourierLibrary
from .identity_library import IdentityLibrary
from .polynomial_library import PolynomialLibrary
__all__ = [
"ConcatLibrary",
"CustomLibrary",
"FourierLibrary",
"IdentityLibra... |
from fastapi import FastAPI
from fastapi import status
from dynaconf import settings
from src import db
from src import schemas
API_URL = "/api/v1"
app = FastAPI(
description="example of API based on FastAPI and SqlAlchemy frameworks",
docs_url=f"{API_URL}/docs/",
openapi_url=f"{API_URL}/openapi.json",
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Transient Scanning Technique implementation
# Sebastien Lemaire: <sebastien.lemaire@soton.ac.uk>
import numpy as np
import multiprocessing as mp
from matplotlib import pyplot
class pyTST:
"""
Class performing and processing the Transient Scanning Technique
... |
import json
carroJson = '{"marca": "honda", "modelo": "HRV", "cor": "prata"}' #isso é um json
print(carroJson)
carros = json.loads(carroJson) #e aqui converte de json para dictionary
print(carros)
print(carros['marca'])
print(carros['modelo'])
for x, y in carros.items():
print(f'... |
import turtle as t
zel = float(input("What is your Zel: "))
for i in range(4):
t.fd(zel)
t.lt(90)
t.done()
|
# Copyright (c) 2015 Presslabs SRL
#
# 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 writ... |
import os
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# from mpl_toolkits.mplot3d import Axes3D
import sklearn
from sklearn.model_selection import train_test_split
# from sklearn import svm
# from sklearn.linear_model import LinearRegression
import seaborn as sns
# TODO:Loading dataset
df... |
class AudioFile:
def __init__(self, filename):
if not filename.endswith(self._ext):
raise Exception("Invalid file format")
self._filename = filename
def play(self):
raise NotImplementedError("Not implemented")
class MP3File(AudioFile):
_ext ="m... |
# Copyright (c) 2013, 2018 National Technology and Engineering Solutions of Sandia, LLC . Under the terms of Contract
# DE-NA0003525 with National Technology and Engineering Solutions of Sandia, LLC, the U.S. Government
# retains certain rights in this software.
import RemoteComputationInterface
import subprocess
impo... |
import os
import shutil
import json
import logging
from django.conf import settings
from django.core.mail import send_mail, EmailMessage
from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
from mptt.models import MPTTModel, TreeForeignKey
from mptt.utils import t... |
"""MMT_STACK Configs."""
from enum import Enum
from typing import Optional
import pydantic
class DeploymentStrategyEnum(str, Enum):
application = 'application'
pipeline = 'pipeline'
class StackSettings(pydantic.BaseSettings):
"""Application settings"""
name: str = "maap-mmt"
stage: str = "produ... |
import argparse
import logging
from . import main
if __name__ == "__main__":
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s: %(name)s: %(levelname)s: %(message)s")
parser = argparse.ArgumentParser(
"Case study of generating a Markov chain with RNN.",
formatter_cla... |
import os
LOG_LEVEL = os.environ.get("LOG_LEVEL", "INFO")
DROPBOX_ACCESS_TOKEN = os.environ["DROPBOX_ACCESS_TOKEN"]
DROPBOX_ROOT_FOLDER = os.environ["DROPBOX_ROOT_FOLDER"]
IFQ_USERNAME = os.environ["IFQ_USERNAME"]
IFQ_PASSWORD = os.environ["IFQ_PASSWORD"]
SLACK_WEBHOOK_URL = os.environ["SLACK_WEBHOOK_URL"]
SLACK_SI... |
from binascii import hexlify
from .definitions import COMMON_PROLOGUES
class FunctionCandidate(object):
def __init__(self, binary_info, addr):
self.bitness = binary_info.bitness
self.addr = addr
rel_start_addr = addr - binary_info.base_addr
self.bytes = binary_info.binary[rel_star... |
"""
lec 8 , functions
"""
def cal_pi(m,n):
#def my_function(a,b=0):
# print('a is ',a)
# print('b is ',b)
# return a + b
#print(my_function(a=1))
#ex1
#def calculate_abs(a):
# if type (a) is str:
# return ('wrong data type')
# if a > 0:
# return a
# if a... |
#!/usr/bin/env python
from datetime import datetime, timedelta
from typing import List
from .io import load, loadkeogram, download # noqa: F401
def datetimerange(start: datetime, stop: datetime, step: timedelta) -> List[datetime]:
return [start + i * step for i in range((stop - start) // step)]
|
import time
import random
def timeit(func, *args):
t1 = time.time()
ret = func(*args)
cost_time = (time.time() - t1) * 1000
print("cost time: %sms" % cost_time)
try:
randint_wrap = random.randint
except:
# micropython
def randint_wrap(a, b):
return a + random.getrandbits(32) % (b-a... |
"""URL configuration for djoser reset password functionality"""
from django.urls import path
from mitol.authentication.views.djoser_views import CustomDjoserAPIView
urlpatterns = [
path(
"password_reset/",
CustomDjoserAPIView.as_view({"post": "reset_password"}),
name="password-reset-api",... |
# Copyright (C) 2013 David Rusk
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to
# deal in the Software without restriction, including without limitation the
# rights to use, copy, modify, merge, publish, distribu... |
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 15 02:04:24 2018
@author: Kundan
"""
import matplotlib.pyplot as plt
import csv
x = []
y = []
with open('dataset.txt','r') as csvfile:
plots = csv.reader(csvfile, delimiter=' ')
for row in plots:
x.append(float(row[0]))
y.append(float(row[1]))
... |
"""Create caches of read-prep steps for Virtool analysis workflows."""
# pylint: disable=redefined-outer-name
# pylint: disable=too-many-arguments
import shutil
from pathlib import Path
from typing import Dict, Any, Optional
import virtool_core.caches.db
from virtool_workflow import fixture
from virtool_workflow.analy... |
import os
def get_specs_dir():
return os.path.join(get_data_dir(), 'cs251tk', 'data')
def get_data_dir():
return os.getenv('XDG_DATA_HOME', os.path.join(os.path.expanduser('~'), '.local', 'share'))
|
"""This module contains the general information for ConfigSearchResult ManagedObject."""
from ...ucscentralmo import ManagedObject
from ...ucscentralcoremeta import UcsCentralVersion, MoPropertyMeta, MoMeta
from ...ucscentralmeta import VersionMeta
class ConfigSearchResultConsts():
IS_RENAMEABLE_FALSE = "false"
... |
# -*- coding: utf-8 -*-
# Copyright (c) 2010-2016, MIT Probabilistic Computing Project
#
# 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/LICENS... |
"""
MacroecoDesktop script for making standalone executable
"""
import sys as _sys
from macroeco import desktop
if len(_sys.argv) > 1:
desktop(_sys.argv[1])
else:
desktop()
|
from django.contrib import admin
from .models import OrderCampProduct
admin.site.register(OrderCampProduct)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.