content stringlengths 5 1.05M |
|---|
from handwrite.sheettopng import SHEETtoPNG
from handwrite.pngtosvg import PNGtoSVG
from handwrite.svgtottf import SVGtoTTF
from handwrite.cli import converters
|
# $Id$
#
# @rocks@
# Copyright (c) 2000 - 2010 The Regents of the University of California
# All rights reserved. Rocks(r) v5.4 www.rocksclusters.org
# https://github.com/Teradata/stacki/blob/master/LICENSE-ROCKS.txt
# @rocks@
#
# $Log$
# Revision 1.2 2010/09/07 23:53:03 bruno
# star power for gb
#
# Revision 1.1 20... |
import os
import argparse
from utils.transaction import Crawl
from utils.aws import Resource
from utils.mysql import MySQL
from utils.catch_exception import *
from selenium.common.exceptions import NoSuchElementException
def selenium_test():
# sleep 3초(delay=3), no headless(gui=True)
crawl = Crawl(delay=3, ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Configuration file for sphinxmark documentation."""
import os
import sys
from datetime import datetime
try:
import sphinx_rtd_theme
except ImportError:
sphinx_rtd_theme = None
try:
from sphinxcontrib import spelling
except ImportError as e:
print(e)
... |
# Copyright (c) 2020 Daniel Pietz
# 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, distrib... |
from flask_jwt_extended import JWTManager
from dawdle.utils.errors import (build_400_error_response,
build_401_error_response)
jwt = JWTManager()
@jwt.expired_token_loader
def expired_token_loader(_):
return build_400_error_response(messages={
"token": [
"Tok... |
from model.contact import Contact
from random import randrange
def test_contact_firstname(app, db, check_ui):
if app.contact.count() == 0:
app.contact.contact_create(
Contact(firstname="Сергей", middlename="Сергеевич", lastname="Сергеев", nickname="Серега",
address="г. Каза... |
from django.urls import path
from . import views
urlpatterns = [
# 127.0.0.1:8000/bookstore/all_book
path('all_book',views.all_book),
# 127.0.0.1:8000/bookstore/add_book
path('add_book',views.add_book),
# 127.0.0.1:8000/bookstore/update_book/1
path('update_book/<int:bid>',views.update_book),
... |
from generate_gerrit_jenkins_project.generate_gerrit_jenkins_project import generate_gerrit_jenkins_project
def main():
generate_gerrit_jenkins_project() |
import numpy as np
from .simulator_model_datagen import ModelAnimDataGenerator
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle, FancyBboxPatch
import matplotlib.animation as animation
class ModelSimulator():
def __init__(self, datapacket, modelname="S_I_R"):
# Initia... |
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 16 15:49:54 2020
@author: sdesnoo
"""
import logging
from pulse_lib.schedule.hardware_schedule import HardwareSchedule
from .hvi2_schedule_extensions import add_extensions
from hvi2_script.system import HviSystem
from hvi2_script.sequencer import HviSequencer
import key... |
import os
import sys
import numpy as np
# Root directory of the project
from PIL import Image
ROOT_DIR = os.path.abspath(".")
# Import Mask RCNN
sys.path.append(ROOT_DIR) # To find local version of the library
sys.path.append("/content/backlash") # To find local version of the library on Google Colab
from mrcnn i... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jun 12 02:57:59 2020
@author: eduardo
"""
import warnings
from .country import *
from .dataset import *
from .functions import *
from .region import *
from .models import *
from .stat import *
# neglecting warnings
warnings.filterw... |
import os
import pytest
from dvc.compat import fspath, fspath_py35
from dvc.dvcfile import Dvcfile
@pytest.mark.parametrize("cached", [True, False])
def test_update_import(tmp_dir, dvc, erepo_dir, cached):
gen = erepo_dir.dvc_gen if cached else erepo_dir.scm_gen
with erepo_dir.branch("branch", new=True), e... |
class Solution(object):
def search(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: int
"""
# Runtime: 188 ms
# Memory: 14.5 MB
# Binary search
start = 0
end = len(nums) - 1
while start <= end:
... |
"""Support for a ScreenLogic 'circuit' switch."""
import logging
from screenlogicpy.const import ON_OFF
from homeassistant.components.switch import SwitchEntity
from . import ScreenlogicEntity
from .const import DOMAIN
_LOGGER = logging.getLogger(__name__)
async def async_setup_entry(hass, config_entry, async_add... |
import django_filters
from .models import Organization, Application
class ApplicationFilter(django_filters.FilterSet):
name = django_filters.CharFilter(lookup_expr='icontains')
organization = django_filters.ModelMultipleChoiceFilter(queryset=Organization.objects.all())
business_criticality = django_filte... |
"""Define abstract base classes of how the local chemical stock database should
behave. This interface will be implemented in one of two ways: using sqlalchemy,
and using puchdb.
"""
import typing
import hashlib
import json
import datetime
import serverlib.timelib as timelib
import serverlib.qai_helper as qai_helper... |
#
# Copyright (c) 2009-2012 Joshua Hughes <kivhift@gmail.com>
#
import urllib
import webbrowser
import qmk
class BeolingusCommand(qmk.Command):
'''Look up a German word using Beolingus. A new tab will be opened
in the default web browser with the search results.'''
def __init__(self):
self._name ... |
def much(x):
return x+1 |
#!/usr/bin/env python
from __future__ import print_function
import setuptools
import os, sys, os.path, glob, \
tempfile, subprocess, shutil
def check_for_openmp():
# Create a temporary directory
tmpdir = tempfile.mkdtemp()
curdir = os.getcwd()
exit_code = 1
if os.name == 'nt': return False
... |
#!/usr/bin/env python
import numpy as np
# ------ HELPER FUNCTIONS ------ #
def sq(x):
return np.sqrt(x)
def calc_l0(A,Nv):
return sq(A*4./(2*Nv-4)/sq(3))
def calc_kp(l0,lm,ks,m):
return (6*ks*pow(l0,(m+1))*pow(lm,2) - 9*ks*pow(l0,(m+2))*lm + 4*ks*pow(l0,(m+3))) / (4*pow(lm,3)-8*l0*pow(lm,2)+4*pow(l0,... |
from hackerrank.HackerRankAPI import HackerRankAPI
key = ""
compiler = HackerRankAPI(api_key = key)
source = """
for i in range(5):
print i
"""
sample_msg = """:compile cpp
```
#include <iostream>
int main() {
std::cout << "hello world" << std::endl;
return 0;
}
```
"""
# if sample_msg.startswith(":... |
import numpy as np
x = np.c_[np.random.normal(size=1e4),
np.random.normal(scale=4, size=1e4)]
from nipy.neurospin.utils.emp_null import ENN
enn = ENN(x)
enn.threshold(verbose=True)
|
import cv2
import os
import numpy as np
import tensorflow as tf
from tensorflow.keras.layers import Conv2D,Conv2DTranspose,MaxPool2D
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from tensorflow.keras.utils import to_categorical
from tensorflow.keras.layers import Concat... |
from bs4 import BeautifulSoup
from scrapper.article_scrapper import ArticleScrapper
class VoxArticleScrapper(ArticleScrapper):
def scrap_header(self, dom: BeautifulSoup) -> str:
return self.find_child_h1(dom, attrs={'class': 'c-page-title'}).text
def scrap_content(self, dom: BeautifulSoup) -> str:
... |
from typing import Dict
from botocore.paginate import Paginator
class ListDetectors(Paginator):
def paginate(self, PaginationConfig: Dict = None) -> Dict:
"""
Creates an iterator that will paginate through responses from :py:meth:`GuardDuty.Client.list_detectors`.
See also: `AWS API Docume... |
# Copyright (c) by it's authors.
# Some rights reserved. See LICENSE, AUTHORS.
from wallaby.pf.room import *
from wallaby.pf.peer.viewer import *
from wallaby.pf.peer.editor import *
class Invoice(Room):
def __init__(self, name):
Room.__init__(self, name)
self._count = None
self._price... |
import math
from typing import NoReturn, Tuple
from .general import Distribution
class Binomial(Distribution):
def __init__(self, prob=.5, size=20):
"""Binomial distribution class for calculating and
visualizing a Binomial distribution.
Attributes:
mean (float): Representing ... |
adressbuch = {"JONAS": 123456,
"PETER": 8765435}
gesuchter_kontakt = input("Bitte geben Sie den Kontakt ein, den Sie suchen: ").upper() # JONAS
if gesuchter_kontakt in adressbuch:
print("Die Telefonnummer von", gesuchter_kontakt ,"ist:", adressbuch[gesuchter_kontakt])
else:
print("Dieser Eintra... |
"""
File name: plot_results.py
Author: Esra Zihni
Date created: 27.07.2018
This script creates plots for performance assessment and feature importance
assessment. It reads the implementation and path options from the config.yml script.
It saves the created plots as .png files.
"""
import itertools
import os
import p... |
import pkgutil
from collections import defaultdict
from importlib import import_module
from types import ModuleType
from typing import Any, Dict, Iterable, List, Optional, Tuple, Union
import click
from click.core import Command, Context
from click.formatting import HelpFormatter
from valohai_cli.utils import match_p... |
from helpers.common_imports import *
import clean.matrix_builder as mb
import clean.schuster as sch
class Restorer(object):
"""restores clean spectrum, algorithm steps 18 to 21 ref 2"""
def __init__(self, iterations, super_resultion_vector, number_of_freq_estimations, time_grid, max_freq):
self.__itera... |
#!/usr/bin/env python3
import argparse
import sys
from pathlib import Path
from lib.reddit import Redditor
from lib.db_helper import sqliteHelper
from lib.youtube_helper import YoutubeDL
def main():
arg_parser = argparse.ArgumentParser()
arg_parser.add_argument('-s', '--subreddit', required=True, help='Th... |
import random
def GetChar(st):
s = []
i = 0
while i < len(st):
s.append(st[i])
i = i + 1
# print(s)
return s
def CountR(st):
sout = []
cnt1 = 0
for x in st:
sout = GetChar(x)
i, j, start, cnt = 0, 0, 0, 0
for z in range(len(sout)):
... |
idade = int(input('Qual sua idade? '))
preço = float(input('Informe o valor: '))
desconto = 7.0
if preço >= 23 and preço <= idade:
print('Você terá um desconto de: R${:.2f}'.format(desconto))
else:
print('sem desconto')
#https://pt.stackoverflow.com/q/446362/101
|
import datetime
import logging
# LOGGING ----------------------------------------------------------------
filename = "logs/logfile {}.log".format(datetime.date.today())
handler = logging.FileHandler(filename, "a")
frm = logging.Formatter("%(asctime)s [%(levelname)-8s] [%(funcName)-20s] [%(lineno)-4s] %(message)s",
... |
"""Looks after the data set, trimming it when necessary etc"""
import logging
from google.appengine.ext import ndb
import models
from flask import Flask
import flask
app = Flask(__name__)
MAX_RECORDS = 5000
@app.route('/_maintain')
def datastore_maintenance():
"""Performs necessary checks on the datastore"""
... |
import re
import csv
import urllib
import datetime
from django.utils.encoding import smart_unicode, force_unicode
from django.db.models import Avg, Sum, Min, Max, Count
from time import strptime, strftime
import time
from urlparse import urljoin
from BeautifulSoup import BeautifulSoup
from fumblerooski.college.models i... |
import pandas as pd
import matplotlib.pyplot as plt
from pathlib import Path
import numpy as np
import os
def calc_top_percent(betweenness_list, percent):
height = int(len(betweenness_list) * percent)
sum_top_betweenness = 0
sum_total_betweenness = sum(betweenness_list)
for i in range(height):
... |
#!/usr/bin/env python
# Copyright 2019 Banco Santander S.A.
#
# 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 applicab... |
# Copyright (c) 2020 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... |
# https://www.acmicpc.net/problem/2468
import copy
import sys
sys.setrecursionlimit(100000)
def DFS(x, y, tempMap):
tempMap[x][y] = 0
for i in range(4):
nx = x + dx[i]
ny = y + dy[i]
if (0 <= nx < N) and (0 <= ny < N):
if tempMap[nx][ny]!=0:
DFS(nx, ny, tem... |
'''Escreva um progrma que leia um n inteiro qualquer e mostra na tela os n primeiros elementos de uma sequencia de Fibonacci.
Ex: 0 1 1 2 3 5 8'''
n = int(input('Informe um número: '))
t1 = 0
t2 = 1
print('{} > {}'.format(t1, t2), end=' ')
cont = 3
while cont <= n:
t3 = t1 + t2
print(' > {}'.format(t3), end='... |
import os
from tests.config import redis_cache_server
EXTENSIONS = (
'lux.ext.base',
'lux.ext.rest',
'lux.ext.content',
'lux.ext.admin',
'lux.ext.auth',
'lux.ext.odm'
)
APP_NAME = COPYRIGHT = HTML_TITLE = 'website.com'
SECRET_KEY = '01W0o2gOG6S1Ldz0ig8qtmdkEick04QlN84fS6OrAqsMMs64Wh'
SESSION... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Project : tql-Python.
# @File : weather
# @Time : 2020/8/24 9:01 下午
# @Author : yuanjie
# @Email : yuanjie@xiaomi.com
# @Software : PyCharm
# @Description :
import time
import json
import requests
def get_data(year='2020', mon... |
# coding=utf-8
from OTLMOW.OTLModel.BaseClasses.OTLAttribuut import OTLAttribuut
from abc import abstractmethod
from OTLMOW.OTLModel.Classes.BijlageVoertuigkering import BijlageVoertuigkering
from OTLMOW.OTLModel.Classes.LijnvormigElement import LijnvormigElement
from OTLMOW.OTLModel.Datatypes.BooleanField import Boole... |
import os
from solartf.core.generator import KerasGeneratorBase
from solartf.data.image.processor import ImageInput
class ImageDirectoryGenerator(KerasGeneratorBase):
def __init__(self,
image_dir,
image_type,
image_shape,
image_format=None):
... |
"""
This program generates a gene/cell counts table for the mutations
found in a given set of vcf files
"""
import numpy as np
import vcf
import os
import csv
import pandas as pd
import sys
import multiprocessing as mp
import warnings
import click
warnings.simplefilter(action='ignore', category=FutureWarning)
def g... |
import unittest.mock
import freezegun
import pandas as pd
import pytest
import functions
import src.getraenkeKasse.getraenkeapp
columns_purchases = ['timestamp', 'user', 'code', 'paid']
columns_products = ['nr', 'code', 'desc', 'price', 'stock']
TEST_PRODUCTS_FILE = 'test_file_1'
TEST_PURCHASES_FILE = 'test_file_2... |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import itertools
import json
import logging
import os
from argparse import Namespace
import torch
from torch.utils.tensorboard import Summary... |
# Copyright 2019 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 applica... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Test with MuJoCo.
"""
import os
import time
import numpy as np
from itertools import count
# from pyrobolearn.simulators.bullet import Bullet
from pyrobolearn.simulators.mujoco import Mujoco
import mujoco_py as mujoco
# sim = Bullet(render=True)
sim = Mujoco(render=Tr... |
import sqlite3
class PipelineDatabase:
def __init__(self, name):
self.connection = sqlite3.connect(name)
self.cursor = self.connection.cursor()
def create_if_not_exists(self):
self.cursor.execute('''create table if not exists files
(file int, name text, suff text, format text... |
#!/usr/bin/env python3
from django.core.management.base import BaseCommand
from seqauto.models import JobScript, JobScriptStatus
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument('--job_script_id', type=int, required=True)
parser.add_argument('--job_id')
def h... |
import tkinter as tk
from tkinter import messagebox
import random
import numpy as np
window = tk.Tk()
window.title('sudoku')
window.geometry('600x600')
sudoku = np.array([[1, 9, 6, 4, 3, 8, 7, 5, 2],
[3, 8, 4, 5, 7, 2, 1, 6, 9],
[7, 2, 5, 6, 1, 9, 3, 4, 8],
[... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
TODO
"""
import mir_eval
import bss_eval_base
class BSSEvalImages(bss_eval_base.BSSEvalBase):
"""
"""
def __init__(self, true_sources_list, estimated_sources_list, source_labels=None, algorithm_name=None,
do_mono=False, compute_permuta... |
#! /usr/bin/env python
"""Post-install / configuration script for Iromlab"""
import os
import sys
import imp
import site
import sysconfig
from shutil import copyfile
import threading
import logging
import pythoncom
from win32com.client import Dispatch
try:
import tkinter as tk # Python 3.x
import tkinter.scro... |
import h5py
import numpy as np
import pandas as pd
import os
from argparse import ArgumentParser
def dataframe_to_deepsurv_ds(df, event_col='Event', time_col='Time'):
# Extract the event and time columns as numpy arrays
e = df[event_col].values.astype(np.int32)
t = df[time_col].values.astype(np.float32)
... |
from icevision.models.ultralytics.yolov5.dataloaders import *
from icevision.models.ultralytics.yolov5.model import *
from icevision.models.ultralytics.yolov5.prediction import *
from icevision.models.ultralytics.yolov5.show_results import *
from icevision.models.ultralytics.yolov5.utils import *
from icevision.models.... |
from dbs.apis.dbsClient import *
url="https://cmsweb.cern.ch/dbs/prod/global/DBSReader/"
#url="https://dbs3-test2.cern.ch/dbs/dev/global/DBSReader/"
dbs3api = DbsApi(url=url)
dataset = '/JetHT/Run2018A-v1/RAW'
print(dbs3api.listFileSummaries(dataset=dataset, validFileOnly=1))
print("\n")
print(dbs3api.listFileSummar... |
import unittest
from chalmers.event_dispatcher import EventDispatcher
from chalmers import config, errors
from os.path import join
import tempfile
import os
class TestEventDispatcher(EventDispatcher):
@property
def name(self):
return 'test'
def dispatch_foo(self, value):
self.foo = value... |
from __future__ import absolute_import, division, print_function
from libtbx.test_utils import approx_equal
from cctbx import dmtbx
from cctbx import maptbx
from cctbx import miller
from scitbx import fftpack
from libtbx import complex_math
import scitbx.math
from cctbx.array_family import flex
from cctbx.development i... |
#!/usr/bin/env ipython
import numpy as np
import re
import datetime as dt
from GDSII import GDSII
from GDSII_ARef import GDSII_ARef
from GDSII_SRef import GDSII_SRef
from GDSII_Boundary import GDSII_Boundary
from GDSII_Text import GDSII_Text
from GDSII_Path import GDSII_Path
from GDSII_Box import GDSII_Box
from GDSII_... |
X = int(input())
Y = int(input())
sum = 0
if X < Y:
for i in range(X, Y + 1):
if i % 13 != 0:
sum += i
print(sum)
elif Y < X:
for i in range(Y, X + 1):
if i % 13 != 0:
sum += i
print(sum) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import requests
import gspread
import config
from oauth2client.service_account import ServiceAccountCredentials as Account
api_url = 'https://api.leaseweb.com/invoices/v1/invoices'
def api_request(url, headers, params=None):
try:
conn = requests.get(url=url... |
from pymongo import MongoClient
import os, sys
from loguru import logger
try:
conn = MongoClient(os.environ["DATABASE_ADDRESS"], int(os.environ["DATABASE_PORT"])) #host.docker.internal, 27017
logger.info("Successfully connected to Holder MongoDB")
except Exception as error:
logger.error(error)
sys.exit()
# da... |
# -*- coding: utf-8 -*-
import sys
import numpy as np
from gensim.models import Word2Vec
model_file = sys.argv[1]
(pos1, pos2, neg) = sys.argv[2:]
# 学習したモデルのロード
model = Word2Vec.load(model_file)
# 意味ベクトルのノルムを調整
model.init_sims(replace=True)
# クエリベクトルを計算
vec = model[pos1] + model[pos2] - model[neg]
# 全単語の意味ベクトルを含ん... |
#!/usr/bin/env python
# -*- coding: iso-8859-15 -*-
import time,os,pygame,json,httplib,datetime,urllib,random
from keys import PARSE_API_KEY,PARSE_APP_ID
class Panpin:
# panpin guztien ahoen gpio pinak gordetzen ditu
gpio_pinak = []
def __init__(self,izena,parse_api_class,textu_fitxategia,audio_fitxategia... |
"""This module stores all the REST API of ImageButler."""
from .apis import api
from .ping import Ping
from .image import Image
from .images import Images
api.add_resource(Ping, '/ping')
api.add_resource(Image, '/image')
api.add_resource(Images, '/images')
|
# Program: marker_a4.py
# Proyect: encuadro - Facultad de Ingenier - UDELAR
# Author: Martin Etchart - mrtn.etchart@gmail.com.
#
# Description:
# Python script to render blender model providing pose (rotation, translation), fov
# and image dimensions.
#
# Hosted on:
# http://code.google.com/p/encuadro/
#
# Usage:
# ble... |
import threadcount as tc
from threadcount.procedures import fit_line, open_cube_and_deredshift, set_rcParams
def update_settings(s):
# "de-redshift" instrument dispersion:
s.instrument_dispersion_rest = s.instrument_dispersion / (1 + s.z_set)
if s.always_manually_choose is None:
s.always_manually_... |
# -*- coding: utf-8 -*-
# @Time : 2019/10/9 20:36
# @Author : Ziqi Wang
# @FileName: read_video.py
# @Email: zw280@scarletmail.rutgers.edu
import cv2
base_path = "D:\Pyproject\image_process\ets_dataset_concordia1_v1"
file_name = "period1-1-1-gray.avi"
data_path = "D:\Pyproject\image_process\data"
def video_to_i... |
import json
import os
import pathlib
import time
from typing import Optional, List, Set, Dict, Union
import git
from lab import logger, monit
from lab.internal.configs import Configs, ConfigProcessor
from lab.internal.experiment.experiment_run import Run
from lab.internal.lab import lab_singleton
from lab.internal.lo... |
#################################################################################
# Copyright (C) 2009-2011 Vladimir "Farcaller" Pouzanov <farcaller@gmail.com> #
# #
# Permission is hereby granted, free of charge, to any person obtaining a ... |
# 比较直接,首先想到的是 从后往前递归 做
# 但其实每次计算 * 的可能性的时候,重复计算了前面的某些结果
# 可以用一个全局二维数组保存下 某个子串s 和 某个子匹配p 是否匹配
class Solution:
def isMatch(self, s: str, p: str) -> bool:
if len(s)==0 and len(p)==0:return True
if len(s)!=0 and len(p)==0:return False
if len(s)==0 and len(p)!=0:
return len(p)>=2 an... |
# Copyright 2017 FUJITSU LIMITED
#
# 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... |
from django import forms
from .models import Restaurante, Review
class BusquedaPorNombre(forms.Form):
nombre = forms.CharField(label="Nombre del Restaurante")
class BuscaTituloCuerpo(forms.Form):
contenido = forms.CharField(label="Contenido en cuerpo o titulo")
|
import os
import re
def _create_path(base: str, tail: str) -> str:
"""
Creates a safe path according to which OS the program is running on
:param base: The current path
:param tail: The last part of the path that is to be added
:return: A new OS safe path
"""
return base + ('\\' if os.name... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
import pytest
import numpy as np
from astropy import wcs
from . helper import SimModelTAB
def test_2d_spatial_tab_roundtrip(tab_wcs_2di):
nx, ny = tab_wcs_2di.pixel_shape
# generate "random" test coordinates:
np.random.seed(1)
xy = 0.... |
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import fcl
class World:
def __init__(self, x_min, x_max, v_min, v_max, Pset):
self.x_min = x_min
self.x_max = x_max
self.v_min = v_min
self.v_max = v_max
self.Pset = Pset
self.fcl_manager = ... |
from app.db.error.non_existent_error import NonExistentError
from fastapi.responses import JSONResponse
from fastapi import status
from starlette.exceptions import HTTPException
async def custom_http_exception_handler(request, exc: HTTPException):
return JSONResponse(status_code=exc.status_code, content=exc.detail... |
N = int(input())
A = list(map(int, input().split()))
v = 0
for i in range(N):
v += 1 / A[i]
print(1 / v)
|
class Solution:
def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:
m = len(obstacleGrid)
n = len(obstacleGrid[0])
dp = [[0 for i in range(n)] for j in range(m)]
if obstacleGrid[0][0] == 1:
return 0
dp[0][0] = 1
for col in r... |
"""Defines Falcon hooks
Copyright 2013 by Rackspace Hosting, 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 o... |
import curses
import py2048
def incurses(screen, game):
curses.noecho()
curses.cbreak()
screen.keypad(True)
try:
while not game.isover:
screen.addstr(0, 0, repr(game))
ch = screen.getch()
if ch == curses.KEY_RIGHT:
game.moveright()
... |
import functools
import time
import logging
logger = logging.getLogger("wrapper")
#------------------------------------------------------------------------------#
# TIME
def time_measurement(func):
"""Timestamp decorator for dedicated functions"""
@functools.wraps(func)
def wrapper(*args, **kwargs):
... |
# (C) Copyright IBM Corp. 2016
#
# 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 i... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from .UrlShortener import UrlShorter
from .lib.BitLinkUrlShortener import BitLinkUrlShorter
from .lib.GoogleUrlShortener import GoogleUrlShorter
__all__ = ['UrlShorter', 'GoogleUrlShorter', 'BitLinkUrlShorter']
|
# Copyright 2017-2018 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" fil... |
from __future__ import annotations
import os
from typing import Tuple, List, Dict, Set, Callable, Any, TYPE_CHECKING
from qtpy import QtGui
from qtpy.QtWidgets import QAction, QToolBar, QMenu
if TYPE_CHECKING:
from cpylog import SimpleLogger
from qtpy.QtWidgets import QMainWindow
def build_actions(self: QMai... |
# pip install streamlit streamlit_folium
# run with: streamlit run playground/st_view.py
import streamlit as st
from streamlit_folium import folium_static
import matplotlib.pyplot as plt
from slither.core.visualization import make_map, plot_speed_heartrate, plot_velocity_histogram
from slither.service import Service
fr... |
# -*- coding: UTF-8 -*-
import win32api
import win32gui
import win32con
import os
def setwallpaper(pic):
# open register
regkey = win32api.RegOpenKeyEx(win32con.HKEY_CURRENT_USER, "Control Panel\\Desktop", 0, win32con.KEY_SET_VALUE)
win32api.RegSetValueEx(regkey, "WallpaperStyle", 0, win32con.REG_SZ, "0"... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import functools
from hermes_python.hermes import Hermes
#from hermes_python.ontology import *
import datetime, time
from threading import Timer
THRESHOLD_INTENT_CONFSCORE_DROP = 0.3
THRESHOLD_INTENT_CONFSCORE_TAKE = 0.6
CREATOR = "maremoto:"
INTENT_HELP_ME = CRE... |
import logging # DEBUG INFO WARNING ERROR
import tkinter.ttk as TTK # use for Combobox
import win_main2
from function import *
from logging.handlers import QueueHandler
import queue
import configparser
from matplotlib.backends.backend_tkagg import (
FigureCanvasTkAgg, NavigationToolbar2Tk)
import matplotlib.pyplo... |
"""Run in command line mode."""
import fire
import morfeus.buried_volume
import morfeus.cone_angle
import morfeus.conformer
import morfeus.dispersion
import morfeus.local_force
import morfeus.pyramidalization
import morfeus.sasa
import morfeus.sterimol
import morfeus.visible_volume
import morfeus.xtb
def main() -> N... |
'''
Plane defined by vectors and point.
'''
# - Imports
from ..exceptions import VectorsNotSameSize
from typing import TypeVar
# - Globals
# Typing for Vectors and Points
Point = TypeVar("Point")
Vector = TypeVar("Vector")
class Plane:
"""
Defines a plane
Parameters
----------
... |
import pytest
from aioworkers.core.config import Config, MergeDict
from aioworkers.core.context import (
Context,
EntityContextProcessor,
GroupResolver,
Octopus,
Signal,
)
def test_octopus():
f = Octopus()
f.r = 1
assert f['r'] == 1
f['g'] = 2
assert f.g == 2
f['y.t'] = 3
... |
# 21/11/02 = Tue
# 54. Spiral Matrix [Medium]
# Given an m x n matrix, return all elements of the matrix in spiral order.
# Example 1:
# Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
# Output: [1,2,3,6,9,8,7,4,5]
# Example 2:
# Input: matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
# Output: [1,2,3,4,8,12,11,10,9,5,6,7]
#... |
# Copyright (c) 2010-2012 OpenStack Foundation
#
# 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 agree... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.