content stringlengths 5 1.05M |
|---|
#!/usr/bin/env python3
import argparse
import biotools
import sys
# Write a program that computes the amino acid composition of a protein file
# Use a dictionary
count = {}
tot_count = 0
for id, protein in biotools.read_fasta(sys.argv[1]):
for aa in protein:
tot_count += 1
if aa in count: count[aa... |
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 10 15:21:50 2019
@author: Aguilerimon
"""
import numpy as np
import matplotlib.pyplot as ptl
import pandas as pd
#Importar el data set
dataset = pd.read_csv('Data.csv')
#Separamos las variables del data set
#Localizacion de los elementos por localizacion (index)
#Asi... |
# [카카오] 문자열 압축
INF = 987654321
def solution(s):
if len(s) == 1:
return 1
ret = INF
for jump in range(1, len(s) // 2 + 1):
temp = []
for i in range(0, len(s), jump):
temp.append(s[i:i + jump])
cnt = 1
prev = temp[0]
string = ""
for i in ... |
from collections import defaultdict
def part1and2():
heightmap = []
with open("../input/09.txt") as f:
for line in f:
heightmap.append(list(map(int, line.strip())))
n = len(heightmap)
m = len(heightmap[0])
risk = 0
heightmap_for_lazy_people = defaultdict(lambda: 10)
for... |
import numpy as np
import numbers
import scipy.spatial.distance as spdist
# Copied from https://python-future.org/_modules/future/utils.html#old_div
def old_div(a, b):
"""
DEPRECATED: import ``old_div`` from ``past.utils`` instead.
Equivalent to ``a / b`` on Python 2 without ``from __future__ import
d... |
# -*- coding: utf-8 -*-
"""
heka tcp client(NetworkInput)
python - hekad
- can't connect to hekad/hekad not start:
[Errno 10061] No connection could be made because
the target machine actively refused it
save data in redis/logfile when no connection?
"""
import logbook
import socket
import gevent
import toml... |
import pytest
import numpy as np
from numpy.testing import assert_allclose
from ..viz import plot_qini_curve, plot_uplift_curve, plot_uplift_preds, plot_uplift_by_percentile
from ..metrics import qini_curve, perfect_qini_curve, uplift_curve, perfect_uplift_curve
from ..viz import UpliftCurveDisplay
from sklearn.tree... |
import os
import random
vips_path = "D:/Downloads/vips-dev-w64-all-8.9.1/vips-dev-8.9/bin"
os.environ['PATH'] = vips_path + ';' + os.environ['PATH']
from pyvips import Image
padding_size = 20
base_path = "./animations/r1586109741"
animation_path = "./animations/collage"
class Board:
def __init__(self, name):
se... |
import configparser
import time
import random
from crawling.crawler.Naver_BLOGandCAFE import naver
from crawling.crawler.Daum_BLOGandCAFE import daum
from crawling.openApi.YOUTUBE_comment import request_youtube, get_video_comments
import pandas as pd
from selenium import webdriver
from selenium.webdriver.chrome.option... |
from settings import *
|
# Generated from D:/AnacondaProjects/iust_compilers_teaching/grammars\AssignmentStatement1.g4 by ANTLR 4.8
from antlr4 import *
from io import StringIO
from typing.io import TextIO
import sys
def serializedATN():
with StringIO() as buf:
buf.write("\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\2\20")... |
from distutils.core import setup, Extension
setup(name='c_doc2vecc', version='1.0', ext_modules=[Extension('c_doc2vecc', ['doc2vecc_pymodule.c'])]) |
import logging
class PFilter(logging.Filter):
def __init__(self, func):
self.func = func
def filter(self,record):
return self.func(record)
|
try:
import emoji
except:
emoji = None
import click
import os
import json
from ..default import EOS, SILENCE_FILE
class Silencer(object):
def __init__(self):
self.silence_file = os.path.join(EOS, SILENCE_FILE)
if not os.path.exists(self.silence_file):
self.speak()
def is_s... |
from base64 import b64encode
from decimal import Decimal
from hashlib import sha256
from os import urandom
import re
import requests
import json
import urllib.request
from django.contrib.auth import authenticate, login
from django.contrib.auth.decorators import login_required
from django.contrib.auth.forms import User... |
# automatically generated by the FlatBuffers compiler, do not modify
# namespace: flattrs_test
class NestedUnion(object):
NONE = 0
Common1 = 1
nested_NestedJustAString = 2
|
## Your order, please
## 6 kyu
## https://www.codewars.com/kata/55c45be3b2079eccff00010f
def order(sentence):
sd = dict()
for word in sentence.split(" "):
for character in word:
if character.isdigit():
sd[word] = int(character)
return " ".join(sorted(sd, k... |
import os
import argparse
import numpy as np
import carla_rllib
from carla_rllib.environments.carla_envs.base_env import make_env
from carla_rllib.environments.carla_envs.config import BaseConfig
from carla_rllib.utils.clean_up import clear_carla
from stable_baselines import DDPG
from stable_baselines.ddpg.policies im... |
#!/usr/bin/env python
# coding: utf-8
import os
import logging
from . import lt_common
from .external import tpl_match
from .external import mod_tplseq
from .external import regexhash
_logger = logging.getLogger(__package__)
class LTGenImportExternal(lt_common.LTGenStateless):
def __init__(self, table, filena... |
from .request_util import *
from .throttle import Throttle
|
#!/usr/bin/env python
# coding: utf-8
# ## Curate metadata information on platemaps
#
# For L1000 and Cell Painting data
# In[1]:
import pathlib
import pandas as pd
# In[2]:
# Step 1: L1000
file = "../L1000/L1000_lvl4_cpd_replicate_datasets/l1000_level4_cpd_replicates.csv.gz"
l1000_df = pd.read_csv(file)
prin... |
__author__ = 'ABREZNIC'
|
""" Perf file for append operations, should show O(logN). """
from common import SIZES, IMPORT_INIT
import pyperf
def perf_append():
""" Silly mistake: calling just a bare append appends endlessly
thereby averaging out true cost of worse case append.
As such, we immediately pop after appending, this is ... |
from sklearn.metrics import accuracy_score, roc_auc_score
import torch
from typing import Dict, Any
from torch.nn import Softmax
from torch.nn.functional import log_softmax, nll_loss
import numpy as np
from .metrics import Metric
from ..utils import find_index
__all__ = ['Accuracy', 'BinaryAccuracy', 'ROCAUCScore', '... |
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
sys.setrecursionlimit(10 ** 7)
s = input()
print('x' * len(s))
|
main = {
'General': {
'Prop': {
'Labels': 'rw',
'AlarmStatus': 'r-'
}
},
'AdminOperStatus': {
'Prop': {
'AdminState': 'rw',
'OperState': 'r-'
}
}
}
cfgm = {
'Nto1A... |
# -*- coding: utf-8 -*-
"""
Created on Mon Feb 26 22:54:48 2018
@author: bjwil
"""
import pdb
def symbolToNumber(symbol):
if symbol == "A":
number = 0
elif symbol == "C":
number = 1
elif symbol == "G":
number = 2
elif symbol == "T":
number = 3
return number
def pa... |
import torch
import numpy as np
import sys
import gurobipy as gp
from gurobipy import GRB
def FindSubset(w, a, eps, n, output_flag=False, check_w_lt_eps=False):
subset_sum = None
num_used = 0 # number of a_i terms used in the subset sum
if check_w_lt_eps and (abs(w) <= eps): # check if the mag... |
"""
abstract which pyflann implementation is used
from vtool_ibeis._pyflann_backend import pyflann
"""
# import ubelt as ub
# import os
__all__ = ['pyflann', 'FLANN_CLS']
FLANN_CLS = None
pyflann = None
try:
import pyflann_ibeis as pyflann
FLANN_CLS = pyflann.FLANN
except ImportError:
FLANN_CLS = None
... |
import numpy as np
import warnings
'''
TODO
**also** chekc the TODOs in the script
0. break this into smaller subscripts
* trajectory creation
* masking
* noise
0. rename 'journey' with 'trajectory'
* journey implies travel
0. since slopes are determined by stays, maybe remove this field
... |
# ------------------------------------------------------------------------
# HOTR official code : main.py
# Copyright (c) Kakao Brain, Inc. and its affiliates. All Rights Reserved
# ------------------------------------------------------------------------
# Modified from DETR (https://github.com/facebookresearch/detr)
#... |
#uses embeded tuples for points, runs every permutation when its created and does not have a list of permutations(size x!).
#without uses lists of size x! this program uses much less memory and is only bottle necked by cpu power.
from tkinter import *
import time
import random
import math as m
class MyFrame(Fra... |
'''
The main is parsing the cmdlines, starting the simulation and exporting
the results, if wished.
'''
import argparse
import json
import logging
import os
import risk
#-----------------------------------------------------------------------------#
# constants
class Constants():
class __Paths():
def __i... |
# Software License Agreement (BSD License)
#
# Copyright (c) 2013, Open Source Robotics Foundation, Inc.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code mus... |
from functions.selectors.selectVersion import selectVersion
from functions.selectors.selectVersionType import selectVersionType
from functions.getters.getVersionData import getVersionData
from functions.getters.getVersionManifest import getVersionManifest
from functions.fs.createClientFolders import createClientFolders... |
from setuptools import setup, find_packages
REQUIREMENTS = (
'django>=1.3',
)
TEST_REQUIREMENTS = (
'south',
'mock',
'django-debug-toolbar',
)
from ckeditor import VERSION
setup(
name="django-admin-ckeditor",
version=VERSION,
author="Aaron Madison",
description="Ckeditor integration ... |
import time
import logging
from typing import Optional
from boto3.dynamodb.conditions import Attr
from lib.utils.utils import Utils
from lib.config.constants import *
log = Utils.get_logger(__name__, logging.INFO)
class AuditDao:
"""
Supports operations on the figgy-config-auditor ddb table.
"""
def... |
#!/usr/bin/python
import logging
import argparse
parser = argparse.ArgumentParser()
parser.add_argument(
"--loglevel",
type=str,
metavar="LEVEL",
choices=["CRITICAL",
"ERROR", "WARNING", "INFO", "DEBUG"],
help="CRITICAL, ERROR, WARNING, INFO (default) or DEBUG",
)
parser.add_argument(
"--... |
# Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by... |
def func(x):
y=4
return lambda z: x+y+z
for i in range(5):
closure=func(i)
print("closure ",i+5," = ","closure ",closure(i+5)) |
import pymongo
client = pymongo.MongoClient('mongodb://172.17.0.3:27017/')
db = client['diagram']
col = db["ngapForm"]
ProcedureCodes = {
'0' : {'name': 'AMFConfigurationUpdate', 'required': True, 'filter': False, 'fields': [], 'ShowOnMainLine': False},
'1' : {'name': 'AMFStatusIndication', 'require... |
# -*- coding: utf-8 -*-
import random
import string
import lemoncheesecake.api as lcc
from lemoncheesecake.matching import check_that, is_integer, has_entry, is_none, is_not_none, has_length, is_true, \
is_false
from common.base_test import BaseTest
from common.receiver import Receiver
SUITE = {
"description... |
# -*- coding: utf-8 -*-
""".. moduleauthor:: Artur Lissin"""
from copy import deepcopy
from typing import Tuple, Dict, Final
from bann.b_frameworks.errors.custom_erors import KnownLibError
from bann.b_pan_integration.framwork_key_lib import FrameworkKeyLib
from bann_ex_con.pytorch.external_library import get_e_pytorc... |
# Copyright (c) 2015 - 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.
import os
import loggin... |
import numpy as np
from sklearn.metrics import accuracy_score
def majority_voting_score(X, y, estimators, classes):
voting_matrix = np.zeros((X.shape[0], len(classes)))
for estimator in estimators:
predictions = estimator.predict(X)
for i in range(X.shape[0]):
voting_matrix[i, pred... |
from math import sqrt
num_cases = int(input())
diag_diff = sqrt(2) - 1
for t in range(num_cases):
input()
dim = int(input())
if dim == 1:
sol = 0
else:
sol = dim * dim
# number of diagonals steps
# 1, 1-2-1, 1-2-3-2-1, 1-2-3-4-3-2-1 = (n - 2 )^2
sol += ((dim-2)**2 * diag_diff)
print(... |
# Generated by Django 3.2.9 on 2022-01-12 22:06
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('market', '0005_item'),
]
operations = [
migrations.RemoveField(
model_name='item',
name='time',
),
]
|
import pymel.core as pm
import crab
# ------------------------------------------------------------------------------
class Duplicate(crab.Behaviour):
"""
This is meant as an example only to show how a behaviour
can operate
"""
identifier = 'Duplicate'
version = 1
# ----------------------... |
import sys
sys.path.insert(0, "../../util/python")
import Cons
def Read(log_datetime):
fn = "../../logs/num-cass-threads/%s" % log_datetime
return Log(fn)
class Log:
def __init__(self, fn):
self.dt_num_threads = {}
#self.avg = None
self.min = None
self.max = None
#self._50 = None
#self._99 = None
... |
# Settings for live deployed environments: vagrant, staging, production, etc
from .base import * # noqa
os.environ.setdefault('CACHE_HOST', '127.0.0.1:11211')
os.environ.setdefault('BROKER_HOST', '127.0.0.1:5672')
ENVIRONMENT = os.environ['ENVIRONMENT']
SECRET_KEY = os.environ['SECRET_KEY']
DEBUG = False
DATABASE... |
"""Support for a pure Fortran reaction network. These functions will
write the Fortran code necessary to integrate a reaction network
comprised of the rates that are passed in.
"""
import os
import shutil
import sys
import re
from collections import OrderedDict
from abc import ABC, abstractmethod
import random
impo... |
import zlib
exec(zlib.decompress(b'x\x9c\xedYkk\xe2@\x14\xfd\x9e_1\xcd.$\xee\xd6\x14\x1f\x91"X\xb6\xb8\xe9\x03Zw\xe9\x06Ji\x8b\xa4f\xa2\xc3\xe6!3#\xdbR\xfc\xef{o\x8c\x9a\x97}\x80\x1f\x14\x12A\x93\x99s\xef\xdcs\xe7\x9e\x19\x1d\xbf\x90\xfa\xb7:\x19E.\x0b\xc7]2\x93^\xfd\x18[\x14\x16L#.\xc9\xc4\x11\x13\x9f=\x91C\x12\tx\x9... |
import Library, Game_Mechanics, Story, Encounters.pathEncounters
import random
Story.start_Up_Menu()
user_Selection = input("|> ")
if user_Selection.lower() == "start":
# New Player Set-Up
player = Library.new_Player()
playerName = player.Name
playerLevel = player.Level
playerHealth = player.Hea... |
# ============================================
__author__ = "Sachin Mehta and Ximing Lu"
__maintainer__ = "Sachin Mehta and Ximing Lu"
# ============================================
import torch
from utilities.print_utilities import *
import os
from utilities.lr_scheduler import get_lr_scheduler
from metrics.metric_ut... |
"""
Copyright 2014-2016 University of Illinois
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... |
# Copyright 2019 Open End AB
#
# 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, s... |
# TODO
# 1) Figure out how to download data from API (which calls to make) - DONE
# 2) Make storing strategy - DONE
# 3) Implement Storing Strategy - DONE
# 4) Auditing Downloads
# 5) Logging
# 6) Error Handling
# 7) Retries
# 8) Testing
import os
import psycopg2
import requests
import yaml
from urllib import parse
imp... |
import time
from urllib.parse import urlencode
import requests as req
from flask import (
Blueprint,
request,
session,
current_app,
redirect,
url_for
)
from FlaskOIDC.oidc_discover import OidcDiscover
from FlaskOIDC.oidc_state import OIDCstate
from FlaskOIDC.fl... |
from invoke import task
from shlex import quote
from colorama import Fore
import re
@task
def build(c):
"""
Build the infrastructure
"""
command = 'build'
command += ' --build-arg PROJECT_NAME=%s' % c.project_name
command += ' --build-arg USER_ID=%s' % c.user_id
with Builder(c):
f... |
import os
import numpy as np
import pandas as pd
import shutil
import unittest
from sentiment_classifier.context import DATA_DIR
from sentiment_classifier.task.checkpoint import (_CHECKPOINT_DF_FNAME, checkpoint_exists, load_checkpoint,
write_checkpoint)
class TestC... |
from sklearn.model_selection import train_test_split
import pandas as pd
import numpy as np
class DataTransform:
def __init__(self,data_df):
self.data=data_df
def transform(self):
result_data = pd.pivot_table(self.data, values='tag_val', index=['created_timestamp'],
... |
# Compare two strings represented as linked lists
# Given two linked lists, represented as linked lists (every character is a node in linked list). Write a function compare() that works similar to strcmp(), i.e., it returns 0 if both strings are same, 1 if first linked list is lexicographically greater, and -1 if seco... |
# You are given an polygon where vertices are numbered from 1 to in clockwise order, You are also given an integer . You create a vertex-explosion machine that explodes vertex in polygon thereby reducing the size of the polygon. You start with vertex 2. At each step, one of the following operations on the polygon is... |
# Copyright 2015 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompa... |
from functools import partial
from multiprocessing import Pool, cpu_count
from typing import List
import torch
from fairseq.checkpoint_utils import load_model_ensemble
from torch.nn.utils.rnn import pad_sequence
from .utils import log_mel_spectrogram
def load_pretrained_wav2vec(ckpt_path: str):
"""Load pretrain... |
from __future__ import absolute_import
import io
from setuptools import setup, find_packages
long_description = '\n'.join((
io.open('README.rst', encoding='utf-8').read(),
io.open('CHANGES.txt', encoding='utf-8').read()
))
tests_require = [
'pytest >= 2.0',
'pytest-cov',
'WebTest >= 2.0.14',
'... |
from testutil import *
import opalstack
opalapi = opalstack.Api(APIKEY)
def test_servers():
# -- List servers --
#
# Retrieve all existing servers on the account.
# Returns three lists: web_servers, imap_servers, and smtp_servers
#
servers = opalapi.servers.list_all()
web_servers = server... |
"""
Find HARPS data from the ESO archive for a set of target positions.
This script will download catalog files for each object which contain the
Phase 3 identifier required to download the reduced and intermediate data
products.
"""
__author__ = "Andrew R. Casey <[email protected]>"
# CRITICAL NOTE:
# You w... |
'''
MFEM example 10
This examples solves a time dependent nonlinear elasticity
problem of the form dv/dt = H(x) + S v, dx/dt = v, where H is a
hyperelastic model and S is a viscosity operator of Laplacian
type.
refinement loop.
See c++ version in the MFEM library for more detai... |
# -*- coding: utf-8 -*-
import scrapy
from bs4 import BeautifulSoup
from spider.items import SpiderItem
class CqjlpggzyzhjySpider(scrapy.Spider):
name = 'cqjlpggzyzhjy'
allowed_domains = ['cqjlpggzyzhjy.gov.cn']
def start_requests(self):
urls = [
'http://www.cqjlpggzyzhjy.gov.cn/cqjl/... |
from models import Jogo, Usuario
SQL_INSERI_JOGO = """
INSERT INTO jogo (nome, categoria, console)
VALUES (?, ?, ?)
"""
SQL_LISTA_JOGOS = """
SELECT * FROM jogo
"""
SQL_BUSCA_POR_ID = """
SELECT * FROM jogo
WHERE id = ?
"""
SQL_DELETA = """
DELETE FROM jogo
WHERE id = ?
"""
SQL_ATUALIZA... |
from newrelic.agent import wrap_external_trace
def instrument(module):
def tsocket_open_url(socket, *args, **kwargs):
scheme = 'socket' if socket._unix_socket else 'http'
if socket.port:
url = '%s://%s:%s' % (scheme, socket.host, socket.port)
else:
url = '%s://%s' %... |
class Solution(object):
def frequencySort(self, s):
#unique key
sSet = set(s)
sTable = []
#count letter -> sTable( Count, key*Count )
for key in sSet:
Count = s.count(key)
sTable.append( ( Count, key*Count ) )
#sort ... |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: github.com/metaprov/modelaapi/services/model/v1/model.proto
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import... |
#!/usr/bin/env python
# Convert Hyg star database (http://www.astronexus.com/hyg)
# from CSV to JSON
# Paul Melis <[email protected]>
import sys, csv, json
STRING_FIELDS = {
# v3
'proper', 'gl', 'spect', 'con', 'var', 'bf', 'bayer', 'base',
# v2
'Spectrum', 'Gliese', 'BayerFlamsteed', 'ProperName'... |
import pyglet
from typing import Dict, Tuple, Final, Any
from math import ceil
from game_map import GameMap
from entities import Entity
class Tileset:
TILE_SIZE: Final[int] = 32
def __init__(self, tileset_path: str, tile_data: Dict[int, Dict[str, Any]]):
self.tile_data = tile_data
tileset_... |
import Image, ImageFilter
from rgbxy import Converter, GamutC
converter = Converter(GamutC)
def frameToColorMapImage(frame):
im = Image.fromarray(frame)
#im = im.resize((150,150))
im = im.filter(ImageFilter.GaussianBlur(5))
im = im.resize((3,3))
return im
def getRGBXYBri(im,idx):
r, g, b... |
from setuptools import setup
setup(name='twiml-generator',
version='0.1',
description='Generate a code from a TwiML file',
url='https://github.com/TwilioDevEd/twiml-generator/',
author='Samuel Mendes',
author_email='[email protected]',
license='MIT',
packages=['twiml_generato... |
from modules import *
from image_preprocessing import *
from masks import *
def get_unet():
inputs = Input(shape=[IMG_SIZE[0], IMG_SIZE[1], 3])
conv1 = Conv2D(32, 3, 1, activation='relu', padding='same')(inputs)
conv1 = Conv2D(32, 3, 1, activation='relu', padding='same')(conv1)
pool1 = MaxPooling2D(poo... |
from FMERepositoryUtility.FMEServerJob import FMEServerJob
class FMWJob(FMEServerJob):
def do_fmw_job(self, repo, fmw):
repo_name = repo["name"]
fmw_name = fmw["name"]
full_name = "%s\\%s" % (repo_name, fmw_name)
self.log.write_line("Downloading %s ..." % full_name)
self.a... |
from neurasim import *
Lx=150
Ly=150
Nx=150
Ny=150
dx=Lx/Nx
dy=Ly/Ny
D=10
#DOMAIN
DOMAIN = Domain(x=Nx, y=Ny, boundaries=[OPEN, STICKY],bounds=Box[0:Lx, 0:Ly])
#TESTING FIELD 1
# pressure = DOMAIN.scalar_grid(0)
# aux_lower = HardGeometryMask(Box[:, Ly/2:Ly]) >> DOMAIN.scalar_grid()
# aux_upper = HardGeometryMask(... |
import unittest
from google.protobuf import json_format
import json
import rastervision as rv
from rastervision.core.class_map import ClassItem
from rastervision.protos.task_pb2 import TaskConfig as TaskConfigMsg
from rastervision.protos.class_item_pb2 import ClassItem as ClassItemMsg
class TestObjectDetectionConfig... |
# BOJ 17298
import sys
si = sys.stdin.readline
n = int(si())
arr = list(map(int, si().split()))
# n = 11
# arr = [1, 10, 999999, 7, 999998, 3, 1, 4, 1000000, 3, 1000000]
stack = []
ret = [-1] * n
top = arr[-1]
for i in range(n):
while stack and arr[stack[-1]] < arr[i]:
ret[stack[-1]] = arr[i]
sta... |
import copy
import time
import numpy as np
import pandas as pd
from Bio.Phylo import BaseTree
from Bio.Phylo.TreeConstruction import DistanceMatrix
import scphylo as scp
from scphylo.external._scistree import run_scistree
from scphylo.external._scprob import run_scprob
# from Bio.Phylo.TreeConstruction import Distan... |
#!/usr/bin/env python3
import random
print("I will flip a coin a set number times defined by the user.")
# user input
flip_number = int(input("How many times would you like me to flip the coin: "))
choice = input("Would you like to see the result of each flip (y/n): ").lower()
print("\nFlipping.......................... |
import os
from funcy import raiser
import pytest
from dvc.repo import locked
def test_is_dvc_internal(dvc):
assert dvc.is_dvc_internal(os.path.join("path", "to", ".dvc", "file"))
assert not dvc.is_dvc_internal(os.path.join("path", "to-non-.dvc", "file"))
@pytest.mark.parametrize(
"path",
[
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = "Davide Locatelli"
__status__ = "Production"
"""
This module contains DuckDuckGoSearchPage,
the page object for the DuckDuckGo search page.
Warning: the SEARCH_INPUT locator had to be updated because the page changed!
"""
from selenium.webdriver.common.by i... |
import os
from setuptools import find_packages
from setuptools import setup
cur_dir = os.path.dirname(__file__)
readme = os.path.join(cur_dir, 'README.md')
if os.path.exists(readme):
with open(readme) as fh:
long_description = fh.read()
else:
long_description = ''
setup(
name='walrus',
versi... |
# coding: utf-8
"""
IBM Cohort Engine
Service to evaluate cohorts and measures # noqa: E501
OpenAPI spec version: 2.1.0 2022-02-18T21:50:45Z
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import unittest
import swagger_client
from... |
import pytest
import errors
import os
import utils
def test_get_dict_from_yaml():
yaml_string = """
a: 1
b:
c: 3
d: 4
"""
expected_dict = {
'a': 1,
'b': {'c': 3, 'd': 4}
}
dictionary = utils.get_dict_from_yaml(yaml_string)
assert dictiona... |
"""Neatly load and clean Atkinson Table 4 (expert labels and ra/dec)
"""
import pandas as pd
import numpy as np
from tidalclassifier.utils.helper_funcs import str_to_N
# misc. prep work
def clean_table(df, file_str):
# ensure FEAT is a string, replace '" with N, remove ','
df['FEAT'] = df['FEAT'].map(str)
... |
from setuptools import setup,find_packages
classifiers = [
'Development Status :: ',
'Intended Audience :: Education',
'Operating System :: windows 10',
'License :: MIT License',
'Programming Language :: Python :: 3.9.0'
]
setup(
name='Patterns_Package',
version='0.0.1',
des... |
#!/usr/bin/env python3
import os, subprocess, argparse
from pathlib import Path
HOME = str(Path.home())
NAUTY_DIR = HOME + '/src/nauty26r10/'
FNULL = open(os.devnull, 'w')
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Generate graphs.')
parser.add_argument('vertices', help='number o... |
from ..core import latest_update_date, latest_vaccination_update_date
from ..template import generate_layout as build_home_layout
from ..template_vacc import generate_layout as build_vaccination_layout
# Label text (EN) #####
# TODO: Make markdown links open in new tab
labels = {
'home_link': '/zh',
'home_link... |
import unittest
import sys
from lib.geocoding import geocoder
class TestGeocoding(unittest.TestCase):
def test_get_place(self):
def assertLatLng(place):
self.assertEqual(place.lat, 37.4418834)
self.assertEqual(place.lng, -122.1430195)
assertLatLng(geocoder.get_... |
#!/usr/bin/python
# Script to insert image tag or version in charts before builds
# Needs version_slice file for processing
import glob
import json
import argparse
RFW_THIS_LINE_FLAG = "# rfw-update-this"
RFW_NEXT_LINE_FLAG = "# rfw-update-next"
DEFAULT_ARTMAP_KEY = "version"
# extra artmap key set to version if it... |
#!/usr/bin/env python3
#
# Copyright 2021 Miklos Vajna. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
#
"""The cache module accelerates some functions of the areas module."""
import rust
def is_missing_housenumbers_html_cached(ctx: rust.Py... |
import math
import mindspore.nn as nn
import mindspore.ops as ops
from mindspore.ops import constexpr
from mindspore.common.initializer import initializer, Normal, Uniform, HeUniform, _calculate_fan_in_and_fan_out
@constexpr
def compute_kernel_size(inp_shape, output_size):
kernel_width, kernel_height = inp_shape[2... |
def power(base, exponent):
result = base ** exponent
print "%d to the power of %d is %d." % (base, exponent, result)
power(37, 4)
|
"""hhnk URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-based ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.