content stringlengths 5 1.05M |
|---|
# Given an array of unsorted numbers and a target number,
# find all unique quadruplets in it, whose sum is equal to the target number.
# Example 1:
# Input: [4, 1, 2, -1, 1, -3], target=1
# Output: [-3, -1, 1, 4], [-3, 1, 1, 2]
# Explanation: Both the quadruplets add up to the target.
# Example 2:
# Input: [2, 0, ... |
"""Jena/Fuseki API client exceptions."""
class FusekiClientError(Exception):
"""Fuseki API client default error."""
class FusekiClientResponseError(FusekiClientError):
"""A response error from Fuseki server."""
class DatasetAlreadyExistsError(FusekiClientError):
"""Dataset already exists error."""
c... |
def search_schedule():
query = """
query ($page: Int) {
Page(page: $page, perPage: 50) {
pageInfo {
hasNextPage
}
media(status: RELEASING, type: ANIME, format: TV) {
nextAiringEpisode {
airingAt
}
... |
import os
from jinja2 import Environment, FileSystemLoader, StrictUndefined
templates_path = os.path.dirname(os.path.realpath(__file__))
header_path = os.path.join(os.path.dirname(templates_path),
'include', 'dataframe')
src_path = os.path.join(os.path.dirname(templates_path), 'src')
dotnet... |
# -*- coding: utf-8 -*-
'''
Author: Hannibal
Data:
Desc: local data config
NOTE: Don't modify this file, it's build by xml-to-python!!!
'''
partnerskill2_map = {};
partnerskill2_map[1] = {"lv":1,"reqlv":1,"gold":20,"goldrate":1,};
partnerskill2_map[2] = {"lv":2,"reqlv":2,"gold":100,"goldrate":4,};
partnerskill2_map... |
import json
import requests
from flask import current_app
from app.core import lexer,token_exprs
def parse(text):
result =[]
token_table= 'Sequence' + '(Token , token type)\n'
result.append(token_table)
tokens = lexer(text, token_exprs)
if not isinstance(tokens, list):
error = 'The {} lin... |
'''Author: Brandon Trabucco, Copyright 2019
Helper functions to display and run a simple game'''
#####################################
# An interface representing actions #
#####################################
class Walkable(object):
pass
class Breakable(object):
pass
class Pickable(object):
... |
"""
Splitting image containing two samples
.. note:: Using these scripts for 1+GB images take several tens of GB RAM
Sample usage::
python split_images_two_tissues.py \
-i "/datagrid/Medical/dataset_ANHIR/images/COAD_*/scale-100pc/*_*.png" \
--nb_workers 3
Copyright (C) 2016-2019 Jiri Borovec <j... |
import functools
import glob
import gzip
import os
import sys
import warnings
import zipfile
from itertools import product
from django.apps import apps
from django.conf import settings
from django.core import serializers
from django.core.exceptions import ImproperlyConfigured
from django.core.management.b... |
from pathlib import Path
from typing import Optional
import typer
from reprexlite.formatting import Venue
from reprexlite.reprex import reprex
from reprexlite.version import __version__
app = typer.Typer()
def version_callback(version: bool):
"""Print reprexlite version to console."""
if version:
t... |
#
# wtfdmdg.py
#
# Where The Fuck Did My Day Go, dot pie
#
# A tool to help answer that question.
#
from PyQt5 import Qt, QtGui, QtWidgets, QtCore
import pyqtgraph as pg
pg.setConfigOption('background', 'w')
pg.setConfigOption('foreground', 'k')
import sys
import re
import collections
import datetime
import time
imp... |
import pathlib
import shutil
import pytest
import salt.exceptions
import salt.modules.aptpkg as aptpkg
import salt.modules.cmdmod as cmd
import salt.modules.file as file
import salt.utils.files
import salt.utils.stringutils
from tests.support.mock import Mock, patch
pytestmark = [
pytest.mark.skip_if_binaries_mis... |
import logging
from . import EncoderSelfAttentionSimultaneousNMT
logger = logging.getLogger('pysimt')
"""This is the training-time wait-k model from:
Ma et al. (2018), STACL: Simultaneous Translation with Implicit Anticipation
and Controllable Latency using Prefix-to-Prefix Framework, arXiv:1810.08398
The o... |
from datetime import datetime
from datetime import timezone
from decimal import Decimal
from typing import List
from typing import Optional
from django.db import transaction
from django.db.models import Q
from base_site.mainapp.models import FamilyMember
from base_site.mainapp.models import Records
from base_site.nub... |
pkgname = "python-charset-normalizer"
pkgver = "2.0.7"
pkgrel = 0
build_style = "python_module"
hostmakedepends = ["python-setuptools"]
checkdepends = ["python-pytest"]
depends = ["python"]
pkgdesc = "Encoding and language detection"
maintainer = "q66 <[email protected]>"
license = "MIT"
url = "https://charset-norm... |
#
# Author : Marcos Teixeira
# SkyNet is watching you
#
# common imports
import numpy as np
import pandas as pd
import os
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score,precision_score,recall_score,f1_score
import matplotlib.pyplot as plt
import lightgbm as lgb
d... |
# %% Packages
import os
from typing import Dict
import mlflow
from keras.engine.functional import Functional
from mlflow.models.signature import ModelSignature
from src.utils.logging import get_logger
# %% Logger
logger = get_logger()
# %% Class
class MLFlowGateway:
def __init__(self, name: str) -> None:
... |
#!/usr/bin/env python3
macaddress = "00:15:82:92:BF:50"
width = 384
|
#
# Collective Knowledge (generate AE table)
#
# See CK LICENSE.txt for licensing details
# See CK COPYRIGHT.txt for copyright details
#
# Developer: Grigori Fursin, [email protected], http://fursin.net
#
cfg={} # Will be updated by CK (meta description of this module)
work={} # Will be updated by CK (tempor... |
from __future__ import print_function
import torch
import codecs
import re
import datetime
import matplotlib
import numpy as np
import torch.functional as F
import torch.nn.functional as F
import os
import pickle
from torch.autograd import Variable
from annoy import AnnoyIndex
from torch.utils.data import Dataset, Data... |
def funcao1(funcao, *args, **kwargs):
return funcao(*args, **kwargs)
def funcao2(nome):
return f'Oi {nome}'
def funcao3(nome, saudacao):
return f'{saudacao} {nome}'
executando = funcao1(funcao2, 'Luiz')
print(executando)
executando = funcao1(funcao3, 'Luiz', saudacao='Bom dia')
print(executando)
|
#! /usr/bin/python3
import select
import subprocess
import sys
import threading
import time
# Own libraries from immediate directory
from paxlib import *
import read_kbd_direct
LAN_IFACE = "wlan0"
io_terminal = False # use terminal
io_pax = True # use keypad, pax display
try:
import readchar
# Usag... |
import tinput
def test_main():
assert tinput # use your library here
|
from autoconf import conf
import autofit as af
from autogalaxy.galaxy import galaxy as g
from autofit.tools.phase import Dataset
from autogalaxy.pipeline.phase import abstract
import numpy as np
class HyperPhase:
def __init__(
self,
phase: abstract.AbstractPhase,
hyper_search,
... |
import random
import copy
from Card import *
class Deck:
"""
Cards' Number in the initial deck
111 22 33 44 5 for each color
"""
def __init__(self, initial: list=None, _seed:int = None):
colors: tuple = (0, 1, 2, 3, 4)
numbers: tuple = (1, 1, 1, 2, 2, 3, 3, 4, 4, 5)
starter... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Created: 07-2020 - Carmelo Mordini <carmelo> <[email protected]>
"""Module docstring
"""
import numpy as np
from scipy.special import binom
def smooth_gradient_n(y, N, dx=1, pad_mode='edge', axis=-1):
# http://www.holoborodko.com/pavel/numerical-methods/... |
#!/usr/bin/env python
#
# ----------------------------------------------------------------------
#
# Brad T. Aagaard, U.S. Geological Survey
# Charles A. Williams, GNS Science
# Matthew G. Knepley, University of Chicago
#
# This code was developed as part of the Computational Infrastructure
# for Geodynamics (http://ge... |
import os
import sys
from GenomicsQueries import Queries
from BigQueryClient import BigQuery
from config import Config
from GoogleGenomicsClient import GoogleGenomicsClient
import logging
import time
import json
from pyflow import WorkflowRunner
class GenomicsQC(object):
def __init__(self, verbose=False, client_se... |
# SensorFusion API
# Import packages
import os
import argparse
import cv2
import numpy as np
import sys
import time
from threading import Thread
import importlib.util
from flask import Flask, jsonify, request, render_template
app = Flask(__name__)
app.config("DEBUG") = True
#############################
# Additional... |
"""
This plugin adds several convenient aliases, to shorten
roles/affiliation management.
Aliases defined
---------------
All those commands take a nick or a JID as a parameter.
For roles
~~~~~~~~~
.. glossary::
:sorted:
/visitor
/mute
Set the role to ``visitor``
/participant
Set t... |
import argparse
import pandas as pd
import matplotlib.pyplot as plt
from dialog_eval import DialogEval
from domain import Domain
parser = argparse.ArgumentParser("Test dialogue evaluation against Elasticsearch index.")
parser.add_argument("--elasticsearch-uri", default="http://localhost:9200", required=False,
... |
from reliapy.distributions.discrete._discrete import _Discrete
from reliapy.distributions.discrete._bernoulli import _Bernoulli
from reliapy.distributions.discrete._binomial import _Binomial
from reliapy.distributions.discrete._poisson import _Poisson
|
# -*- coding: utf-8 -*-
# ----------------------------------------------------------------------------
# Copyright © 2016, Continuum Analytics, Inc. All rights reserved.
#
# The full license is in the file LICENSE.txt, distributed with this software.
# -------------------------------------------------------------------... |
from tkinter import Tk, ttk, LEFT, RIGHT, BOTTOM, TOP, BOTH, Grid, \
N, S, E, W, NW, NE, Button, Radiobutton, Label, Entry, IntVar, BooleanVar, StringVar, NORMAL, DISABLED
import os
import Game
import tkinter.messagebox as msgbox
WHITE = True
BLACK = False
class GUI:
def __init__(self, physInput... |
from numba import cuda
import numpy as np
from math import tan, sqrt
KB = None
PX_KB = None
SECTOR_LEN = None
NUM_SECTOR = None
FLT_EPSILON = 0.000001
# ppx, ppy, fx, fy, coeffs[0...3]
PPX = 0.0
PPY = 0.0
FX = 0.0
FY = 0.0
#COEFFS = [0.0, 0.0, 0.0, 0.0]
def configure(kb, num_sector, intrinsics=None):
global KB, PX... |
import numpy as np
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import Aer, execute
from qiskit.tools.visualization import plot_state_city
from qiskit import compile
from qiskit.tools.visualization import plot_histogram
import qiskit.extensions.simulator
from qiskit.providers.aer ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright 2015 RAPP
# 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 app... |
#
# 行数据拆分
#
# 输入:
# ID,日期,名称,创建者,参与者列表
# 1,2015-09-01,"设计师面试",HR,"小李,小王,小严"
#
# 输出:
# ID,日期,名称,创建者,参与者
# 1,2015-09-01,设计师面试,HR,小李
# 1,2015-09-01,设计师面试,HR,小王
# 1,2015-09-01,设计师面试,HR,小严
import csv
source = 'event.csv'
dest = 'event_detail.csv'
def get_detail():
content = []
with open(source, 'r', encoding='... |
import random
import numpy as np
import pandas
binary = [ 0.0, 1.0 ]
output_values1 = [ -1.0, 1.0 ]
output_values2 = [ -1.0, -0.33333333333333337, 0.33333333333333326, 1.0 ]
output_values4 = [-1.0, -0.8666666666666667, -0.7333333333333334, -0.6,
-0.4666666666666667, -0.33333333333333337, -0.19999999999999996,
... |
"""This module contains the ``SeleniumRequest`` class"""
from scrapy import Request
from scrapy.http import HtmlResponse
from parsel.csstranslator import HTMLTranslator
from cssselect.parser import SelectorSyntaxError
from selenium.webdriver.support.ui import WebDriverWait
class SeleniumRequest(Request):
"""Scra... |
import os
import time
import carla
import gym
import numpy as np
import gym_carla_feature
from gym_carla_feature.start_env.misc import set_carla_transform
os.environ["SDL_VIDEODRIVER"] = "dummy"
# os.environ["DISPLAY"] = "localhost:12.0"
RENDER = False
def rule_demo(args):
from gym_carla_feature.start_env.config... |
from django.apps import AppConfig
class ArticlesConfig(AppConfig):
default_auto_field = 'django.db.models.AutoField'
name = 'comp.articles'
verbose_name = 'Articles'
|
"""Utility code for constructing importers, etc."""
from ._bootstrap import module_for_loader
from ._bootstrap import set_loader
from ._bootstrap import set_package
|
"""traits/parser.py - Parses trait-based arguments."""
from . import traitcommon
def parse_traits(*args) -> dict:
"""Parses arguments and puts them into a dictionary."""
ratings = {}
for arg in args:
split = arg.split("=")
trait = split[0].strip()
rating = None
traitcommo... |
import logging
import sys
from pathlib import Path
LOG_PATH = Path(__file__).parent.resolve().joinpath("logs")
if not LOG_PATH.exists():
LOG_PATH.mkdir(parents=True, exist_ok=True)
LOG_LEVEL = logging.INFO
LOG_FORMAT = logging.Formatter("%(asctime)s %(name)s %(levelname)-8s %(message)s",
... |
#!/usr/bin/env python
# coding=utf-8
"""
给定 amount 金额和coins数组的硬币,
求凑成amount金额的钱,最少需要多少枚硬币
eg.
amount = 11
coins = [1,2,5]
输出 3 (5元 *2 + 1元 *1)
"""
# 保存中间结果
map_ = {}
def exchange(amount,coins):
if map_.get(amount):
return map_.get(amount)
if amount ==0 :
return 0
if amount < 0:
ret... |
import unittest
from collections import OrderedDict
from hamlpy.compiler import Compiler
from hamlpy.parser.attributes import read_attribute_dict
from hamlpy.parser.core import Stream, ParseException
class AttributeDictParserTest(unittest.TestCase):
@staticmethod
def _parse(text):
return read_attri... |
# This file is part of the MapProxy project.
# Copyright (C) 2010 Omniscale <http://omniscale.de>
#
# 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... |
"""Configuration information about NCBI's databases"""
# Used to figure out if efetch supports the start, stop, strand, and
# complexity fields
PUBLICATION_TYPE = 0
SEQUENCE_TYPE = 1
# Map from database name to database type
class DatabaseInfo:
"""stores NCBI's name for the database and its type"""
def __init... |
import os
from curve.curve import Curve
from typing import List
class EllCurveRefBuilder:
curves: List[Curve]
uRes: int
vRes: int
def __init__(self, curves: List[Curve], uRes: int, vRes: int):
self.curves = curves
self.uRes = uRes
self.vRes = vRes
def build(self, output_p... |
from everett.manager import ConfigManager, ListOf
CONFIG = ConfigManager.basic_config()
CONFIG_SHORTCUTS = CONFIG("shortcuts", parser=ListOf(str, delimiter=", "))
def _is_shortcut(pstr: str, raise_on_missing: bool = False) -> bool:
# https://github.com/pgierz/dots
if pstr == "https" or pstr == "http":
... |
import os, sys
from distutils.core import setup, Extension
from distutils.command import build_ext
py_ver = sys.version_info[:2]
include_dirs = ["/usr/local/include"]
library_dirs = ["/usr/local/lib"]
libraries = ["boost_python-py{}{}".format(*py_ver), "stdc++"]
sources = ["src/boost_lagrange.cpp"]
lagrange = Exte... |
from pyplater.utils import Props, classing
def test_classing():
data = ['fff', 'sss ee', ['aa', 'ww', ('az', 's', 'at'), 'un']]
result = classing(data)
assert result == 'fff sss ee aa ww az s at un'
result = classing(*data)
assert result == 'fff sss ee aa ww az s at un'
def test_props():
p... |
from sqlalchemy import Column, Integer, String, Text
from sqlalchemy.orm import relationship
from src.database.session import Base
class User(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=True, index=True)
username = Column(String, unique=True, index=True)
hashed_password = Column(... |
"""Build images only when paths specified are changed"""
import json
import re
import subprocess
with open("images.json") as f:
contents = json.loads(f.read())
def grep(string, search):
return bool(re.search(search, string))
def is_changed(files):
return grep(
subprocess.run(
"git ... |
import argparse
from distutils.util import strtobool
import json
import os
import pickle
import tensorflow as tf
from softlearning.environments.utils import get_environment_from_params
from softlearning.policies.utils import get_policy_from_variant
from softlearning.samplers import rollouts
from softlearning.misc.uti... |
# encoding: utf-8
# module Revit.Filter calls itself Filter
# from RevitNodes,Version=1.2.1.3083,Culture=neutral,PublicKeyToken=null
# by generator 1.145
# no doc
# no imports
# no functions
# classes
class FilterRule(object):
""" Revit Filter Rule """
@staticmethod
def ByRuleType(type, v... |
#!/usr/bin/env python3
"""
@author: Katherine Eaton
Convert treetime mugration output to auspice json.
./treetime_mugration_json.py
"""
# -----------------------------------------------------------------------#
# Modules and Packages #
# ------------------------------... |
import unittest
from selenium import webdriver
from time import sleep
class NavigationTest(unittest.TestCase):
def setUp(self):
self.driver = webdriver.Chrome(executable_path='/usr/bin/chromedriver')
driver = self.driver
driver.implicitly_wait(30)
driver.maximize_window()
... |
def conv2DOutsize(size, kernel_size = 5, stride = 2):
return (size - (kernel_size - 1) - 1) // stride + 1 |
class Solution:
"""
@param arr: an array of non-negative integers
@return: minimum number of elements
"""
def minElements(self, arr):
# write your code here
arr.sort()
res = 0
total_old, total_new = sum(arr), 0
while total_old > total_new:
... |
import pygame
from lge.LittleGameEngine import LittleGameEngine
from lge.Sprite import Sprite
from lge.Rectangle import Rectangle
class Platform(Sprite):
def __init__(self, x, y, dir, distance, speed):
super().__init__("platform", (x, y))
# acceso a LGE
self.lge = LittleGameEngine.getIn... |
#!/usr/bin/env python
#
# This file is part of the Fun SDK (fsdk) project. The complete source code is
# available at https://github.com/luigivieira/fsdk.
#
# Copyright (c) 2016-2017, Luiz Carlos Vieira (http://www.luiz.vieira.nom.br)
#
# MIT License
#
# Permission is hereby granted, free of charge, to any person obtai... |
#!/usr/bin/python
import pandas as pd
import sys
sys.path.append('../')
from Binance import Binance
import logging.config
import logging.handlers
import logging
import os
# this logging configuration is sketchy
binance = logging.getLogger(__name__)
logging.config.fileConfig('logging.ini')
# create Binance object
bn... |
from lib import action
class KeycloakGroupCreateAction(action.KeycloakBaseAction):
def run(self, name, path, clientRoles={}, realmRoles=[], subGroups={},
parent=None, skip_exists=True):
payload = {}
payload['name'] = name
payload['path'] = path
payload['clientRoles'] = ... |
from setuptools import setup, find_packages
setup(
name='synthpop',
version='0.1.1',
description='Population Synthesis',
author='UrbanSim Inc.',
author_email='[email protected]',
license='BSD',
url='https://github.com/udst/synthpop',
classifiers=[
'Development Status ... |
from back.mongo.data.collect.metas.model import *
from back.mongo.data.collect.metas.mongo import *
|
# Generated by Django 2.2.13 on 2020-08-02 10:36
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('stats', '0012_auto_20190427_0202'),
]
operations = [
migrations.AlterField(
model_name='gamesession',
name='server'... |
#!/usr/bin/python3
import sys
def main():
# usage: ./html_gen.py
# input: a list of names (in any format) and then an email address
# (separated by a ' - ')
# output: some html containing contact information for a given list of names
# html is dependent on an existing file with '{}'... |
from chat.views import handle_chat, index_greet
def setup_routes(app):
app.router.add_get('/ws/hi/', index_greet)
app.router.add_get('/ws/chats/{chat_id}', handle_chat)
|
#!/usr/bin/env python3
from __future__ import (absolute_import, division, print_function)
from datetime import datetime, timedelta
import json
import os
import requests # python-requests
import smtplib
import sys
import time
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
# Some li... |
# coding=utf-8
# Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
# Copyright 2020 Ronald Seoh
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the Li... |
import torch.nn as nn
class LeNet(nn.Module):
def __init__(self, num_classes=10, num_channels=3):
super(LeNet, self).__init__()
act = nn.Sigmoid
self.body = nn.Sequential(
nn.Conv2d(num_channels, 12, kernel_size=5, padding=5//2, stride=2),
act(),
nn.Conv2... |
# Note: After all the names add the word STOP on the next row in the first column
import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore
import pandas as pd
# Initialize firebase admin sdk
cred = credentials.Certificate('path-to-acm-core-json')
firebase_admin.initialize_app(... |
def lengthOfLastWord_(s):
words = s.split()
return 0 if len(words) == 0 else len(words[-1])
|
from setuptools import setup
from os import path
import re
def packagefile(*relpath):
return path.join(path.dirname(__file__), *relpath)
def read(*relpath):
with open(packagefile(*relpath)) as f:
return f.read()
def get_version(*relpath):
match = re.search(
r'''^__version__ = ['"]([^'"... |
#!/usr/bin/python
#
# Copyright 2015 Hewlett-Packard Development Company, L.P.
#
# 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 req... |
# :coding: utf-8
# :copyright: Copyright (c) 2013 Martin Pengelly-Phillips
# :license: See LICENSE.txt.
import mock
from sawmill.log import Log
from sawmill.formatter.email import Email as EmailFormatter
from sawmill.handler.email import Email
def test_output():
'''Test outputting to email.'''
with mock.pat... |
import time
import sys
import multiprocessing
from socket import gethostname
import pickle
import os
import picamera
import numpy as np
import cv2
import markerDetection as md
class FrameBuffer(object):
def __init__(self, resolution):
self.buffer = []
self.resolution = resolution
def __ite... |
# Add (two numbers)
# 2021 Yong-Jun Shin
# Ctrl-Shift-P --> Terminal: Create New Integrated Terminal
# gremlinpython==3.5.0 --> requirments.txt
# gremelinpython supports python 3.4 or higher
# pip install --target ".\.venv\Lib\site-packages" -r requirements.txt --upgrade
import logging
import azure.functions as func... |
import os
import re
from setuptools import setup
def get_version(verbose=0):
""" Extract version information from source code """
try:
if os.path.exists('spirack/version.py'):
with open('spirack/version.py') as f:
ln = f.readline()
v = ln.split('=')
... |
import numpy as np
from smac.epm.base_epm import AbstractEPM
from smac.epm.gaussian_process.gradient_gpr import GaussianProcessRegressor
from smac.epm.gaussian_process.kernels import KernelBase, Cubic, Gaussian
__author__ = "jajajag"
__copyright__ = "Copyright 2018"
__license__ = "3-clause BSD"
__maintainer__ = "jaja... |
try:
from zcrmsdk.src.com.zoho.crm.api.exception import SDKException
from zcrmsdk.src.com.zoho.crm.api.util import Constants
except Exception:
from ..exception import SDKException
from ..util import Constants
class Note(object):
def __init__(self):
"""Creates an instance of Note"""
self.__owner = None
sel... |
#
# Transmission Line Simulator
#
# Author(s): Jiacong Xu
# Created: May-28-2017
#
from util.constants import *
from collections import deque
from circuit import Circuit
import numpy as np
class AppState(object):
"""
Describes the valid states in this app.
"""
Editing = 'editing'
Simulating = 'si... |
"""empty message
Revision ID: 9d8fc446eec1
Revises: cb34c1d864fc
Create Date: 2019-09-18 00:45:49.930785
"""
import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.
revision = "9d8fc446eec1"
down_revision = "cb34c1d864fc"
branch_labels = None... |
"""
This file is part of the TheLMA (THe Laboratory Management Application) project.
See LICENSE.txt for licensing, CONTRIBUTORS.txt for contributor information.
ISO plate mapper
"""
from sqlalchemy.orm import relationship
from everest.repositories.rdb.utils import mapper
from thelma.entities.iso import ISO_PLATE_TYP... |
from flask import (Blueprint, g, render_template, url_for)
bp = Blueprint('klimatologi', __name__, url_prefix='/klimatologi')
@bp.route('/')
def index():
return render_template('klimatologi/index.html')
|
"""Feedback URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-base... |
class Solution:
def findMedianSortedArrays(self, A, B):
total_len = len(A) + len(B)
len_half = total_len // 2
if total_len % 2 == 1:
return self.kth(A, B, len_half)
else:
return (self.kth(A, B, len_half) + self.kth(A, B, len_half - 1)) / 2.
def kth(self,... |
"""
.. _ref_custom_visualization:
Custom Scalar Visualization
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Display custom scalars using an existing mesh.
"""
import pyvista
import numpy as np
from ansys.mapdl import reader as pymapdl_reader
from ansys.mapdl.reader import examples
# Download an example shaft modal analysis result fi... |
from swimport.pools.pools import pools, syspools
from swimport.pools.types import TypeSwimportingPool
from swimport.typeswim import TypeSwimporting, FunctionBody
@syspools.add(TypeSwimportingPool)
def slice_no_step(start_type, end_type, cpp_name, *, swim, **type_args):
start_type, start_porting = swim.get_porting... |
import fnmatch
import itertools
import pathlib
import subprocess
from obsgit.exporter import Exporter
class StorageLFS:
"""File storage in git LFS"""
def __init__(self, git):
self.git = git
# When using the OBS storage we can avoid some downloads, but
# is not the case for LFS. In th... |
# Generated by Django 2.2 on 2019-04-26 00:57
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('anteproyecto', '0028_auto_20190424_2318'),
]
operations = [
migrations.AddField(
model_name='anteproyecto',
name='esta... |
from gym_minigrid.minigrid import *
from gym_minigrid.register import register
import numpy as np
from gym import spaces
def manhattan_dist(a, b):
return np.abs(a[0] - b[0]) + np.abs(a[1] - b[1])
class StickyFloorEnv(MiniGridEnv):
"""
Empty grid environment, no obstacles, sparse reward
"""
def ... |
"""Bancho exceptions"""
# TODO: Prints in exceptions
class loginFailedException(Exception):
pass
class loginBannedException(Exception):
pass
class tokenNotFoundException(Exception):
pass
class channelNoPermissionsException(Exception):
pass
class channelUnknownException(Exception):
pass
class channelModeratedE... |
def greet_developers(lst: list) -> list:
for i in lst:
i.update({'greeting': f'Hi {i["firstName"]}, what do you like the most about {i["language"]}?'})
return lst
|
""" rasterio environment management tools
"""
import threading
import rasterio
from rasterio.session import AWSSession
import rasterio.env
_local = threading.local()
SECRET_KEYS = ('AWS_ACCESS_KEY_ID',
'AWS_SECRET_ACCESS_KEY',
'AWS_SESSION_TOKEN')
def _sanitize(opts, keys):
return ... |
from pydgeot.commands import register
@register(name='commands', help_msg='List available commands', allow_appless=True)
def list_commands(app):
"""
Print available commands information.
:param app: App instance to get commands for.
:type app: pydgeot.app.App | None
"""
from pydgeot import co... |
N = int(input())
for i in range(1,10):
print("{N} * {i} = {Ni}".format(N=N,i=i,Ni=N*i))
|
# -*- coding: utf-8 -*-
# Copyright 2022 <Huawei Technologies Co., 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
#
# Unle... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.