content stringlengths 5 1.05M |
|---|
import pytorch_lightning as pl
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision.utils as vutils
from torchvision import models, transforms
from torch.optim import Adam
from torchsummary import summary
import numpy as np
from byol_pytorch import BYOL
class ContrastiveLearner(pl.Lig... |
##
# File: DictionaryApiTests.py
# Author: jdw
# Date: 8-Mar-2018
# Version: 0.001
##
"""
Tests cases for Dictionary API.
"""
from __future__ import absolute_import, print_function
import json
import logging
import os
import pprint
import sys
import time
import unittest
from mmcif.api.DictionaryApi import Dic... |
# Generated by Django 2.2.9 on 2020-02-19 21:39
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
("course_flow", "0001_init... |
#!/usr/bin/env python
# Copyright 2021 Marcelo Sanches
#
# 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 la... |
class Solution:
"""
Time Complexity: O(N)
Space Complexity: O(1)
"""
def balanced_string_split(self, s: str) -> int:
# initialize variables
L_count, R_count = 0, 0
balanced_substring_count = 0
# parse the string
for char in s:
# update the numbe... |
import mysql.connector
from Repositories.BaseRepository import Repository
from mysql.connector import errorcode
class SqlRepo(Repository):
'''
A generic class for a repository for a given class
'''
def __init__(self, config, objFromSql, objToSql, db, db_params):
'''
... |
"""DjAI Pre-Trained Torch Vision Model classes."""
|
#!/usr/bin/python
import argparse
import json
import logging
import signal
import sys
import time
import websocket
logger = logging.getLogger(__name__)
def signal_handler(sig, frame):
logger.debug('Received signal to stop, exiting')
sys.stdout.write('\n')
sys.stdout.flush()
sys.exit(0)
# Global pla... |
from django.conf.urls import url
from djoser import views
urlpatterns = [
url(r"^token/login/?$", views.TokenCreateView.as_view(), name="login"),
url(r"^token/logout/?$", views.TokenDestroyView.as_view(), name="logout"),
]
|
from ._dummy_data import make_fruit_sold_dummy_association_rules
from ._dummy_data import make_dummy_data_classification
from ._covid_id import make_covid_id
from ._covid_id import get_example_covid_id
__all__ = [
"make_fruit_sold_dummy_association_rules",
"make_dummy_data_classification",
"make_covid_id",... |
import pytest
def test_classic_notebook_templates(jp_serverapp):
classic_notebook_templates = [
"notebook.html",
"tree.html"
]
# Get the server's template environment.
template_env = jp_serverapp.web_app.settings.get("notebook_jinja2_env")
for name in classic_notebook_templates:
... |
from flask import Blueprint, request, jsonify, url_for, redirect
from flask_login import current_user, login_user, logout_user
from project import app, db, google_blueprint
from project.api.forms.forms import LoginForm
from project.models import User, OAuth
from sqlalchemy.orm.exc import NoResultFound
from flask_danc... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.7 on 2018-02-23 20:24
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('booking', '0004_booked_service_staff'),
]
operations = [
migrations.AlterFi... |
#!/usr/bin/env python
# Copyright (c) 2016, wradlib developers.
# Distributed under the MIT License. See LICENSE.txt for more info.
"""
Composition
^^^^^^^^^^^
Combine data from different radar locations on one common set of locations
.. autosummary::
:nosignatures:
:toctree: generated/
extra... |
#!/usr/bin/env python3
"""
Python 3
Try to get all questions from an instrument
"""
import colectica
from colectica import ColecticaObject
import api
import pandas as pd
import os
import numpy as np
import json
def from_instrument_get_question_response(C, Agency, ID):
"""
From an instrument get all quest... |
import random
import gym
import numpy as np
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Flatten, BatchNormalization,Activation
from tensorflow.keras.optimizers import Adam
from scores.score_logger import ScoreLogger
ENV_NAME = "TimePilot-ram-v0"
GAMMA = 0.95
LEARNING_RATE... |
"""
Added public field to the report table
Revision ID: 1fb575f848af
Revises: 492fe78451c6
Create Date: 2014-02-28 02:14:43.655893
"""
# revision identifiers, used by Alembic.
revision = '1fb575f848af'
down_revision = '492fe78451c6'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands au... |
# coding: utf-8
from .projection import *
import math
__all__ = ["create_zone", "create_zone_by_code", "meter2hex", "hex2deg", "hex2meter", "deg2hex", "encode", "decode", "create_zones_by_extent"]
HEX_KEY = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
WKB_TMPL = "POLYGON(({0} {1}, {2} {3}, {4} {5}, {6} {7... |
import warnings
from collections import namedtuple
from typing import Optional, Tuple, List, Callable, Any
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch import Tensor
class BasicConv2d(nn.Module):
def __init__(self, in_channels: int, out_channels: int, kernel_size, stride=1, **kwa... |
"""Python 2/3 compat layer."""
from __future__ import print_function, division, absolute_import
try:
basestring
except NameError:
basestring = str
try:
unicode
except NameError:
unicode = str
try:
unichr
bytechr = chr
byteord = ord
except:
unichr = chr
def bytechr(n):
return bytes([n])
def byteord(c):
... |
# Copyright 2021 Alibaba Group Holding Limited. 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 ... |
from ctypes import *
from numba.cuda.cudadrv import _extras
cu_device = c_int
cu_device_attribute = c_int # enum
cu_context = c_void_p # an opaque handle
cu_module = c_void_p # an opaque handle
cu_jit_option = c_int # enum
cu_jit_input_type = c_int # enum
cu_function = c_void_... |
#coding:utf-8
#
# id: functional.arno.indices.upper_bound_asc_01_segments_02
# title: ASC single index upper bound
# decription: Check if all 32 values are fetched with "lower than" operator.
# tracker_id:
# min_versions: []
# versions: 1.5
# qmid: functional.arno.indexes.upper_bound_a... |
#!/usr/bin/env python
""" Here we draw the 2-D phase portrait of the equations """
import numpy as np
import matplotlib.pyplot as plt
from runge_kutta4 import rk4
def x_dot(t, x):
return x[1]
def u_dot(t, x):
gamma1 = 0.1
a1 = 3
b1 = 2.2
epsilon1 = 17.09
omega1 = 2 * np.pi
c1 = 2.2
... |
'''
P11 and P12 must be connected together for this test to pass.
'''
from machine import UART
from machine import Pin
import os
import time
# do not execute this test on the GPy and FiPy
if os.uname().sysname == 'GPy' or os.uname().sysname == 'FiPy':
print("SKIP")
import sys
sys.exit()
uart = UART(2, 11... |
# Copyright (C) 2019 "Daniel Bramblett" <daniel.r.bramblett@gmail.com>
import numpy as np
import random
from board_state import BoardState
# The instance that is the genetic algorithm which manages the population each generation and performs the crossover
# and mutation operation.
class GeneticAlgorithm:
# The s... |
# Copyright (c) 2017 The WebRTC project authors. All Rights Reserved.
#
# Use of this source code is governed by a BSD-style license
# that can be found in the LICENSE file in the root of the source
# tree. An additional intellectual property rights grant can be found
# in the file PATENTS. All contributing project au... |
"""Test the magic commands used to update variables and trace properties.
We expect the correct updates to be performed when a valid input is given, and the
correct warnings to be shown when an invalid one is.
"""
import pytest
from tests.unit.autoplot.mocks import COL, DF, DF_COL, DF_COL_ALT, VAR
@pytest.mark.par... |
a=[1,34,45,23,47,56,32,24,13,67,98,90,77,76,3,2]
o=[]
e=[]
for i in range(0,len(a)):
if (a[i]%2==0):
e.append(a[i])
else:
o.append(a[i])
print("The odd values are",o)
print("The even values are",e)
print("ascending order of numbers: ")
e.sort()
o.sort()
print("EVEN NUMBERS",e)
pr... |
import os
import numpy as np
import numpy
import sys
import tensorflow as tf
import dirt
import skimage.io
canvas_width, canvas_height = 960, 640
def get_dirt_pixels_render(render_op, par_dims=8):
square_vertices = tf.constant([[-1, -1, 0, 1], [-1, 1, 0, 1], [1, 1, 0, 1], [1, -1, 0, 1]], dtype=tf.float32)
... |
from subprocess import call
import sys
action = ['Greeting','Sitting','SittingDown','WalkTogether','Phoning','Posing','WalkDog','Walking','Purchases','Waiting','Directions','Smoking','Photo','Eating','Discussion']
group = [1, 2, 3, 5]
for i in action:
cmd = """nohup python -u run.py --model srnet -arc 1,1,1 --use... |
import numpy
def solve_tridiagonal_system(N, a, b, c, r):
"""Efficiently solve a tridiagonal system.
For example if,
x + y = 3
y + z = 5
y + 2z = 8
then,
A = 3x3
[ 1 1 0
0 1 1
0 1 2 ]
and r = [ 3, 5, 8 ]' for which the expected
result is x... |
'''
@author Tian Shi
Please contact tshi@vt.edu
'''
import json
import torch
from torch.autograd import Variable
from transformers import BertTokenizer
from .model_base import modelClassificationBase
tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
class modelClassificationBaseBert(modelClassificatio... |
def pairs(k, arr):
"""Hackerrank Problem: https://www.hackerrank.com/challenges/pairs/problem
You will be given an array of integers and a target value. Determine the number of pairs of array elements that
have a difference equal to a target value.
Args:
k (int): The target difference
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Feb 27 18:32:12 2022
Autor: Carlos Armando De Castro (cadecastro.com)
"""
def interpolacion_lagrange(x,y,xi):
yi=0
N=len(x)
for i in range(0,N):
L=1
for j in range(0,N):
if j!=i:
L=L*(xi-x[j])/(x[i... |
# Copyright 2015 Rackspace
# 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, sof... |
import oneflow
from oneflow.utils.data import Dataset
import cv2
import os
import glob
import random
class SelfDataSet(Dataset):
def __init__(self, data_path):
self.data_path = data_path
self.imgs_path = glob.glob(os.path.join(data_path, "*.png"))
def augment(self, image, flipcod... |
v = int(input()) # pool`s litters
p1 = int(input()) # litters per hour
p2 = int(input())
n = float(input()) # hours
litters_p1 = p1 * n
litters_p2 = p2 * n
all_litters_from_p1_p2 = litters_p1 + litters_p2
percent_pool = all_litters_from_p1_p2 / v * 100
percent_p1 = litters_p1 / all_litters_from_p1_p2 * 100
perc... |
# This is an example of adding a custom plugin to Projeny
# If you uncomment this then initialize a new project (for eg. "prj -p MyProject -bf")
# Then after that completes there should be a new file at UnityProjects/MyProject/MyP-win/MyExampleFile.txt
#import mtm.ioc.Container as Container
#from mtm.ioc.Inject impor... |
#!/USSR/bin/env python
import argparse
import biom
from biom.util import biom_open
import numpy as np
import pandas as pd
from scipy.sparse import coo_matrix
import scipy as sp
def main(args):
table = biom.load_table(args.table)
aligns = pd.read_table(args.align, header=None)
seq_to_genome = aligns[[0, 2,... |
import random
import string
class Helper:
""" Helper function just to do some stuff. """
def get_random_string(self, length):
""" Function to generate random string. """
letters = string.ascii_lowercase
return ''.join(random.choice(letters) for i in range(length))
|
import requests
import json
import csv
import sys
# Stream List
resp = requests.get('http://listen.di.fm/[streamlist]')
resplist = resp.json()
respsort = sorted(resplist, key=lambda k: k['name'])
respfinal = []
for i in respsort:
print(i['id'],"\t",i['name'])
respfinal.append({'id': i['id'], 'name'... |
from __future__ import unicode_literals
from django.contrib import admin
from django.contrib.contenttypes.admin import GenericTabularInline
from django.utils.safestring import mark_safe
from .models import Car, SubType, Transmission, Fuel
from src.medias.models import Photo, Video
class PhotoInline(GenericTabularI... |
# library
from click.decorators import command
from pyngrok import ngrok
import requests
import json
import click
from click import echo, style
from pyfiglet import Figlet, main
import colorama
import os.path
import subprocess
import shutil
import os
from time import sleep
import sys
# start
banner = Figlet(font="slant... |
from flask import Flask, request, jsonify
from flask_sqlalchemy import SQLAlchemy
import redis
from flask_cors import *
import time
import json
from pyecharts import options as opts
from pyecharts.charts import Graph
# /*----------------Flask and DB----------------*/
app = Flask(__name__)
app.config['SQLALCHEMY_DATAB... |
import sys, os
sys.path.append(os.pardir) # 親ディレクトリのファイルをインポートするための設定
import numpy as np
from dataset.mnist import load_mnist
from controllers.controller import Controller
from modules.pklController import PKL
# データの読み込み
(x_train, t_train), (x_test, t_test) = load_mnist(normalize=True, one_hot_label=True)
... |
from django.db import models
from improved_user.model_mixins import AbstractUser
# Create your models here.
class User(AbstractUser):
"""A User model that extends the Improved User"""
is_rowo = models.BooleanField(
default=False, help_text="Is the User a Robin Wood member?"
)
|
import pandas as pd
import numpy as np
import pvlib
import logging
log = logging.getLogger(__name__)
class IrradianceDataset(pd.DataFrame):
"""pandas.DataFrame extension class for location-aware irradiance data
This class is intended to make life a bit easier when working with irradiance
datasets. I... |
# Exercício Python 65: Crie um programa que leia vários números inteiros pelo teclado.
# No final da execução, mostre a média entre todos os valores e qual foi o maior e o menor valores lidos.
# O programa deve perguntar ao usuário se ele quer ou não continuar a digitar valores.
print('\033[1;33m====== EX 065 ======\03... |
"""Ensure extra credentials can be supplied for inclusion in tokens.
"""
from __future__ import absolute_import, unicode_literals
import mock
from ....unittest import TestCase
from oauthlib.oauth2 import RequestValidator
from oauthlib.oauth2 import WebApplicationServer, MobileApplicationServer
from oauthlib.oauth2 im... |
#!/usr/bin/env python
from nipype.interfaces.utility import Split
from nipype.interfaces.base import Bunch
from nipype.algorithms.modelgen import SpecifyModel
import nipype.interfaces.fsl as fsl
import nipype.pipeline.engine as pe
import nipype.interfaces.io as nio
import nipype.interfaces.utility as util
from nipype.... |
from django.core.management.base import BaseCommand, CommandError
from static_models.view_generator import ViewStaticManager
from static_models.settings import settings
class Command(BaseCommand):
help = 'Create/update static files'
def add_arguments(self, parser):
parser.add_argument(
... |
z = int(input())
vetor = list(map(int, input().split()))
m2 = m3 = m4 = m5 = 0
for y in range(0, z):
if vetor[y] % 2 == 0:
m2 +=1
if vetor[y] % 3 == 0:
m3 += 1
if vetor[y] % 4 == 0:
m4 += 1
if vetor[y] % 5 == 0:
m5 += 1
print('{} Multiplo(s) de 2'.format(m2))
print('{} Mu... |
"""
Generic utilities used by the metacells code.
Arguably all(most) of these belong in more general package(s).
All the functions included here are exported under ``metacells.ut``.
"""
from .annotation import * # pylint: disable=redefined-builtin
from .computation import *
from .documentation import *
from .loggin... |
import numpy as np
from translate import Translator
from sklearn.feature_extraction.text import TfidfVectorizer
translator = Translator(from_lang="Catalan", to_lang="English")
def getStops():
with open("stopwords.txt") as f:
words = [x.replace("\n", "") for x in f.readlines()]
return words
def remo... |
__author__ = 'Meng'
|
import os
import sys
import time
import argparse
import signal
from typing import List, Optional
from enum import Enum
import subprocess
from multiprocessing import Queue, Process
from bottle import request, response, post, run, get, delete
class Status(Enum):
PENDING = 'PENDING'
RUNNING = 'RUNNING'
FAILE... |
from backend.common_tile import CommonTile
class Plains(CommonTile):
def __init__(self):
super().__init__()
self.food = self.food + 1
self.production = self.production + 1
|
__all__ = [
'FourState']
from direct.directnotify import DirectNotifyGlobal
from direct.fsm import ClassicFSM
from direct.fsm import State
class FourState:
notify = DirectNotifyGlobal.directNotify.newCategory('FourState')
def __init__(self, names, durations=[
0, 1, None, 1, 1]):
self.stateIndex = 0
... |
import sys
sys.path.insert(0,'./class')
from flask import render_template, request, render_template_string, send_file
from Cache import Cache
from Utils import Utils
import flask, json
class Api():
def __init__(self, port, config):
self.Cache = Cache('./Data/Account.json', './Data/Zombies.j... |
# split is the proporitionality of the training set that first CRF uses
from SentenceGetter import SentenceGetter
import pandas as pd
import configparser
from Sents2Features import sent2labels
from Sents2Features import sent2features
from sklearn_crfsuite import CRF
from sklearn.model_selection import cross_va... |
# -*- coding: utf-8 -*-
"""
Set up benchmarker package.
To use the 'upload' functionality of this file, you must do:
pip install twine
"""
import io
import os
import sys
import warnings
from pathlib import Path
from shutil import rmtree
from typing import Union
from setuptools import Command, find_packages, set... |
#coding=utf-8
import os
# Basic settings
# requests settings
TIMEOUT = 5
VERIFY = False
# directories might be used
LOCATIONS = {
'log': 'log',
'data': 'data',
}
# stderr is redirected to this file
ERR_LOG_FILE = os.path.join(LOCATIONS['log'], 'err.log')
# log in this file
LOGGING_FILE = os.path.join(LOCAT... |
from hellbox.chutes.chute import Chute
class CompositeChute(Chute):
def __init__(self, *chutes):
chutes = [self.__clone(c) for c in chutes]
self.head = self.tail = chutes[0]
for chute in chutes[1:]:
self.tail = self.tail >> chute
def __call__(self, *args):
self.hea... |
import sqlite3
from os import system
a= system("rm dbz")
conn = sqlite3.connect('dbz')
conn.execute("""
CREATE TABLE targets (hash TEXT NOT NULL PRIMARY KEY, name TEXT)
""")
conn.execute("""
CREATE TABLE phished (hash TEXT, timings DATETIME)
""")
conn.execute("""
CREATE TABLE data (hash TEXT NOT NULL PRIMARY KEY, det... |
#!/usr/bin/env python
# -*- coding: utf-8 -*
# Copyright: [CUP] - See LICENSE for details.
# Authors: Guannan Ma (@mythmgn),
"""
:description:
**Async Module is a tcp framework for asynchrous network msg tranfering**
"""
# TODO:
# 1. If the socket has been in a state in which it does not send or
# recv any... |
# tools for dealing with files, mostly images
"""
Copyright 2016 Fabric S.P.A, Emmanuel Benazera, Alexandre Girard
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership... |
#
# Copyright The NOMAD Authors.
#
# This file is part of NOMAD.
# See https://nomad-lab.eu for further info.
#
# 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/lic... |
class DoubleLinkedListNode(object):
def __init__(self, value):
self.value = value
self.next = None
self.previous = None
def __repr__(self):
return str(self.value)
class LRU_Cache(object):
def __init__(self, capacity: int):
self._cache = dict()
self.capacity... |
#!/usr/bin/python3
"""Filter and/or process subtitles' content that match a particular pattern."""
import importlib
import logging
from . import _cli
log = logging.getLogger(__name__)
def _true(param):
"""Always returns true for matching functionality."""
return True
def _pass(param):
"""Always retur... |
import sys
import click
from ..alias import AliasedGroup
from .. import core, display, exceptions
@click.group(cls=AliasedGroup, short_help='Create or update resources.', invoke_without_command=True)
@click.option('-f', '--file', 'file_path', type=click.Path(exists=True),
help="Select file or folder t... |
import pyaudio
import wave
import audioop
from collections import deque
import os
import urllib
import time
import math
import subprocess as sub
FLAC_CONV = 'flac -f' # We need a WAV to FLAC converter. flac is available
# on Linux
# Microphone stream config.
CHUNK = 1024 # CHUNK... |
import math
def tokenizePassports(inputList):
tempPassport = {}
passports = []
for row in inputList:
if len(row) > 0:
items = row.split(" ")
for item in items:
item = item.split(":")
tempPassport[item[0]] = item[1]
else:
passports.append(tempPassport)
tempPassport = {}
if len(tempPassport) ... |
import asyncio
import logging
import os
import websockets
from fenix_pipeline import ConnectionClosed
from fenix_pipeline import RawDataSocket
from fenix_pipeline import SubscriptionTypes
from fenix_pipeline import Trade
log = logging.getLogger(__name__)
LOCAL_ONLY = os.environ.get('LOCAL_ONLY', 'true').lower() i... |
# Generated by Django 3.0.7 on 2020-06-18 05:56
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('problem', '0008_auto_20200618_1347'),
]
operations = [
migrations.AlterModelOptions(
name='problem',
options={'permissions':... |
# Copyright 2017 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from datetime import datetime
import json
import mock
from google.appengine.ext import ndb
import webapp2
from gae_libs.testcase import TestCase
from hand... |
from time import time
b = 5
c = 3
d = 2
initime = time()
for x in range(100000):
b = (c + d)%100
c= (b + d)%1000
d= (c + b + d)%500
b= (d - c)%150
fintime = time()
print("TIME: " + str(fintime - initime)) |
from typing import List
from sqlalchemy.exc import InvalidRequestError, OperationalError
from sqlalchemy.orm import sessionmaker, Session
from DTO.run_type_dto import RunTypeDto, create_run_type
from config.base import getSession
from utils.checkers import Checkers
try:
from entities.lst_run_type import LstRunTy... |
print("""
######### ######## # # ######## ############
# # # # # # # # #
# # # # # # # # #
######### ######## # # ######## ############
# # # # # ... |
"""Collection of code generation utils."""
import os
import shutil
from pathlib import Path
from typing import Union
from black import WriteBack, format_file_in_place
from black.mode import Mode
from git import RemoteProgress, Repo
from mypy.stubgen import generate_stubs, parse_options
PROJECT_DIRECTORY = Path(__fil... |
"""
メッシュコード処理モジュール
"""
from math import floor
from typing import Tuple
def get_meshcode(lat: float, lon: float) -> str:
"""経度・緯度からメッシュコード(1 次、2 次、3 次)を取得
Args:
lat(float): 緯度(10 進数)
lon(float): 経度(10 進数)
Returns:
str: 1 次メッシュコード(4 桁), 2 次メッシュコード(2 桁), 3 次メッシュコード(2 桁) 計8桁
"""
... |
from matrix_bot.mbot.plugins import Plugin, civility
import random
class GuessNumberPlugin(Plugin):
"""Play a guess the number game.
You have to guess what the number is in a certain number of attempts. You
will be told information such as higher/lower than the guessed number.
guessnumber new : Starts... |
import datetime
import glob
import json
import logging
import os
import re
from ruxit.api.base_plugin import RemoteBasePlugin
from googleapiclient.discovery import build
from google.oauth2 import service_account
COMPUTE_METRICS = [
'compute.googleapis.com/instance/cpu/utilization',
'compute.googleapis.com/in... |
"""Produce new haiku from training corpus of existing haiku."""
import sys
import logging
import random
import json
from collections import defaultdict
from generate_corpus_missing_words.count_syllables import count_syllables
from string import punctuation
logging.disable(logging.CRITICAL) # comment-out to enable deb... |
"""A pub/sub Bus for managing states and transitions.
The 'process' subpackage defines a ProcessBus object, which is used to
connect applications, servers, and frameworks with site-wide services
such as daemonization, process reload, signal handling, drop privileges,
PID file management, logging for all of these, and ... |
#
# Copyright (C) 2021 Vaticle
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0... |
#!/usr/bin/env python3
# coding: utf8
# Author: Lenz Furrer, 2017
'''
Loaders and formatters for the BeCalm TIPS formats.
'''
import json
import codecs
import logging
from urllib import request as url_request
from .document import Article, Section
from .load import DocIterator
from .export import StreamFormatter
... |
#!/usr/bin/env python
#-*- coding: utf-8 -*-
"""
把一些人去操作的时候不会关心的配置参数定义在这里。
而如IP、用户名、密码等属性,人工操作也需要的,则通过函数接口传入
"""
#NIM
NIM_prompt='#'
NIM_port=23
#VIO
#each VIOServer config should be the same
VIOServer_prompt='$'
VIOServer_port=23
#HMC
HMC_prompt='hscroot@localhost:~>'
HMC_port=22
#AIX Common
AIX... |
# Generated by Django 3.1.11 on 2021-07-20 08:22
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('schools', '0006_auto_20210713_1029'),
]
operations = [
migrations.AlterField(
model_name='school',
name='zip_city',... |
import time
import os
# from lucent.optvis.objectives import channel
from lucent.optvis.render import render_vis, tensor_to_img_array
import numpy as np
from PIL import Image
import streamlit as st
import torch
from lucent.interface.utils import join_layer_channel, update_image_db, display_image, init, create_model_l... |
from __future__ import division
from __future__ import print_function
from scipy.stats import norm
import numpy as np
from . import common_args
from ..util import read_param_file
def analyze(problem, X, Y, num_resamples=1000,
conf_level=0.95, print_to_console=False):
"""Calculates Derivative-based ... |
'''
144. Binary Tree Preorder Traversal Easy
Given the root of a binary tree, return the preorder traversal of its nodes' values.
Example 1:
Input: root = [1,null,2,3]
Output: [1,2,3]
Example 2:
Input: root = []
Output: []
Example 3:
Input: root = [1]
Output: [1]
Example 4:
Input: root = [1,2]
Output: [1,2]
E... |
# -*- coding: utf-8 -*-
import aiohttp
from aiohttp import web
import argparse
import asyncio
import concurrent.futures
import io
import os
from .data import Data
# Local resources
HERE = os.path.dirname(os.path.realpath(__file__))
INDEX_HTML = os.path.join(HERE, 'index.html')
D3_JS = os.path.join(HERE, 'd3.v4.min... |
from __future__ import absolute_import
from __future__ import print_function
import veriloggen.core.vtypes as vtypes
import veriloggen.core.module as module
def mkMultiplierCore(index, lwidth=32, rwidth=32, lsigned=True, rsigned=True, depth=6):
if lwidth <= 0:
raise ValueError("data width must be greater... |
#!/usr/bin/python
import wgdata
from wvtest import wvtest
@wvtest.wvtest
def EaterTest():
e = wgdata.Eater('abcdefg')
wvtest.WVPASSEQ(e.Eat(2), 'ab')
wvtest.WVEXCEPT(wgdata.DecodeError, e.Eat, 10)
wvtest.WVPASSEQ(e.Unpack('!3s'), ('cde',))
wvtest.WVPASSEQ(e.Remainder(), 'fg')
wvtest.WVPASSEQ(e.Remainder()... |
import hashlib
import os
import logging
import sys
import xmlrpclib
import ssl
class StarfaceConfig():
def __init__(self, file):
self.file = file
self.__items = ['url', 'user', 'password', 'preferred_device']
self.url = None
self.user = None
self.password = None
se... |
"""Support for Freedompro cover."""
import json
from pyfreedompro import put_state
from homeassistant.components.cover import (
ATTR_POSITION,
CoverDeviceClass,
CoverEntity,
CoverEntityFeature,
)
from homeassistant.config_entries import ConfigEntry
from homeassistant.const import CONF_API_KEY
from hom... |
from flask_wtf import FlaskForm
from wtforms import StringField
from wtforms import validators
class UserSignupForm(FlaskForm):
username = StringField('username', default="username *", validators=[validators.DataRequired()])
email = StringField("email", default="your@email.com *", validators=[validators.Email(... |
#!/usr/bin/env python3
import argparse
import os
import sys
import re
import json
import base64
import urllib3
from github import Github
from github.PullRequest import PullRequest
from github.Repository import Repository
from github.ContentFile import ContentFile
from github.Branch import Branch
from utils import loa... |
# Copyright (c) 2009 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
{
'variables': {
'chromium_code': 1,
'wixdir': 'third_party\\wix_2_0_4221\\files',
'dx_redist_path': '../../../o3d-internal/third_party/dx_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.