content stringlengths 5 1.05M |
|---|
from marshmallow import Schema, fields
class InternalErrorSchema(Schema):
type = fields.String()
description = fields.String()
class ErrorSchema(Schema):
success = fields.String()
error = fields.Nested(InternalErrorSchema)
class VOPException(Exception):
code = 500
name = "VOPException"
... |
'''
Methods to create various types of Decoder objects from data(files)
'''
import re
import pickle
import sys
import numpy as np
from scipy.io import loadmat
from riglib.dio import parse
import tables
from . import kfdecoder, ppfdecoder
import pdb
from . import state_space_models
import stat
import os
import subpr... |
#!/usr/bin/env python
# coding: utf-8
# In[12]:
import torch
from torch import nn
import math
import matplotlib.pyplot as plt
# In[13]:
torch.manual_seed(111)
# In[14]:
train_data_length = 1024
train_data = torch.zeros((train_data_length, 2))
train_data[:, 0] = 2 * math.pi * torch.rand(train_data_length)
tr... |
from numpy import array
from keras.layers import Input
from keras.layers import Dense
from keras.layers import LSTM
from keras.layers import TimeDistributed
from keras.applications.vgg16 import VGG16
from keras.preprocessing.image import img_to_array
from keras.applications.vgg16 import preprocess_input
from keras.mode... |
import numpy as np
import statsmodels.tsa.stattools as stattools # type: ignore
class StatTester:
"""Carry out stationarity test of time-series.
Parameters
----------
- method : {"ADF"}, default "ADF"
If "ADF":
Augmented Dickey-Fuller unit-root test.
Examples
--------
... |
#!/usr/bin/env python3
"""
Deploy script for entire MOOC's JupyterHub
Every function must be idempotent, calling multiple times should work A-OK
"""
import glob
import os
import time
import argparse
import logging
import tempfile
import subprocess
import json
import copy
import glob
from jinja2 import Environment, Fil... |
#!/usr/bin/env python
# See LICENSE for licensing information
# a simple range and bin test for privcount's random constructions
# this test can not prove that these constructs produce uniformly random
# results, it can only reveal obvious range or partition issues
# this test will exit successfully, unless the count... |
import click
from pash.cli_utils.questions import password_questions, user_site_questions, one_password_question
from pash.cli_utils.pass_generator import get_generator_by_questions, generator
from pash.cli_utils.config_mode_utils import get_password_formated
from pash.actions.store_pass import NewStorePass
import colo... |
from __future__ import absolute_import, unicode_literals
from copy import deepcopy
from .auth import flex_auth
from .consts import default_timeout
from .network import get
from .search import asset_formatters
from .util import gen_v3_url
def individual_asset(
id,
asset_type,
detailed=False,
fields=s... |
from typing import Dict, List, Optional, Protocol, Tuple
import logging
import random
from pajbot.managers.redis import RedisManager
from pajbot.managers.schedule import ScheduleManager
from pajbot.models.emote import Emote, EmoteInstance, EmoteInstanceCount
from pajbot.streamhelper import StreamHelper
from pajbot.u... |
for case in xrange(input()):
P, K, L = map(int, raw_input().split())
freqs = map(int, raw_input().split())
keys = [[] for i in xrange(K)]
index = 0
keypress = 0
for freq in reversed(sorted(freqs)):
while len(keys[index]) >= P:
index = (index + 1)%len(keys)
keys[index].append(freq)
keypre... |
import os
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.metrics import plot_confusion_matrix
# Univariate visualization
def univariate_plot(data, path, save = True):
''' Plot the data univariately. '''
for col in data.columns:
plt.figure(figsize = (10, 8))
... |
import numpy as np
from numpy.random import multivariate_normal as mvn
from itertools import izip
import math
class GeneticOptimizer(object):
def __init__(self, crossover_func, mutate_func, selection_func,
checker_func=None, prob_cx=0.6, popsize=None,
elitist=False, verbose=Fals... |
"""This is script for sending emails directly through terminal or command line from yahoo.com"""
import time
import getpass
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
browser = webdriver.Firefox()
browser.get('http://yahoo.com')
sign_in_elem = browser.find_element_by_id('uh-signin... |
import re
from decimal import Decimal, InvalidOperation
from babel.core import Locale, UnknownLocaleError, get_global
from babel.numbers import format_currency
from django import template
from django.conf import settings
from django.utils.safestring import mark_safe
from django.utils.translation import get_language, t... |
from flask import Flask, redirect, render_template, request, session
from werkzeug.security import generate_password_hash, check_password_hash
from helpers import login_required
from flask_session import Session
from tempfile import mkdtemp
import sqlite3
# Configure application
app = Flask(__name__)
### (DON'T UNDE... |
import numpy as np
import csv
from io import StringIO
def topsis(data,weights,impacts):
number_of_weights = len(weights)
for i in range(number_of_weights):
weights[i] = float(weights[i])
rows=[]
x2=[]
row_num=0
buffer = StringIO()
data.to_csv(buffer)
buffer.seek(0)
... |
import weakref
from typing import (Generic,
TypeVar)
try:
from typing import Protocol
except ImportError:
from typing_extensions import Protocol
class WeakReferencable(Protocol):
__weakref__ = ...
Domain = TypeVar('Domain',
bound=WeakReferencable)
class WrappedVal... |
#!/usr/bin/env python
# encoding: utf-8
########################################################################
# Copyright © 2020 OUC_LiuX, All rights reserved.
# File Name: mknewset.py
# Author: OUC_LiuX Mail:liuxiang@stu.ouc.edu.cn
# Version: V1.0.0
# Date: 2020-12-07 Mon 22:37
# Description:
# History:
####... |
from __future__ import division
import os
import time
from glob import glob
import tensorflow as tf
import numpy as np
from six.moves import xrange
from ops import *
from utils import *
class pix2pix(object):
def __init__(self, sess, image_size=256,
batch_size=1, sample_size=1, output_size=256,
... |
import boto3
from botocore.exceptions import ClientError
class DatabaseClient(object):
def __init__(self, config):
self._config = config
self.connect(self._config)
def create_table(self, name, key_schema, attribute_definitions):
self.dynamodb.create_table(
TableName=nam... |
# Copyright 2016 Cisco Systems, Inc. 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 requir... |
import matplotlib
import matplotlib.backend_bases
import matplotlib.backends.backend_wxagg
import wx
import wx.lib.intctrl
from ..constants.figure import NAV_MODE_ZOOM
from ..constants.figure import NAV_MODE_MEASURE
from ..constants.figure import BMP_MEASURE
from ..constants.figure import NAV_MODE_PAN
from ..constants... |
from __future__ import division, absolute_import, print_function
from .logger import *
|
#!/usr/bin/python3
from glob import glob
from os import rmdir, unlink, path, walk
from sys import argv
import src.common as cm
import src.modelPacker as mp
import src.shaderPacker as sp
import src.texturePacker as tp
import src.materialPacker as mtp
import src.fontPacker as fp
from shutil import copyfile
# 5 bytes: m... |
import time
import torch
import torch.nn as nn
from torchdiffeq import odeint
import numpy as np
from .base import AbstractSDE
from .registry import register
from ..utils.utils import fill_tail_dims
class VPSDE(AbstractSDE):
# Beta max and min values defined in eqn 34
beta_min: float
beta_max: float
... |
# Authors: Hyunwoo Lee <hyunwoo9301@naver.com>
# Released under the MIT license.
from konlpy.tag import Twitter
from sklearn.feature_extraction.text import CountVectorizer
import tensorflow as tf
import numpy as np
import math
from api.common import *
intent_data_file = 'intent.txt'
def stemming(text):
stemmed... |
#!/usr/bin/python
# coding: UTF-8
from serial import *
from sys import stdout, stdin, stderr, exit
from flask import Flask, render_template, request, redirect, url_for, jsonify
# シリアルポートはls -l /dev/tty.*
# 自身の名称を app という名前でインスタンス化する
app = Flask(__name__)
ser = None
tocostick = '/dev/tty.usbserial-AHXMLYXU'
# 前進時の推力一覧... |
from pathlib import Path
from PIL import Image
from zipfile import ZipFile
from utils import get_project_root
class PackerAPI:
def __init__(self):
self.root = get_project_root()
def pack_cbz_or_zip(self, album_hash, zip_archive):
if zip_archive:
file_path = Path(self.root, 'tem... |
import logging
import github.Issue
from .policy_registry import RegisterPolicy, GetPolicyConfig
class Policy(object):
def __init__(self):
self.id = self._id()
self.logging = logging.getLogger(self.id)
self.config = GetPolicyConfig(self.id)
RegisterPolicy(self)
def _id(self):... |
import logging
import time
import podcastindex
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger()
def _log_results(context, results):
logger.ingo("Podcast results from {}".format(context))
for feed in results["feeds"]:
logger.info(
"Podcast Id: {} \t Title: {} \t Newes... |
#!/usr/bin/env python
from distutils.core import setup
setup(
name='latex2sympy',
version='0.1.3',
description='latex2sympy parses LaTeX math expressions and converts it into the equivalent SymPy form',
author='augustt198',
author_email='aug@mit.edu',
packages=['latex2sympy', 'latex2sympy.gen'... |
from ctypes import POINTER, Structure
from math import ceil
import numpy as np
from cached_property import cached_property
from cgen import Struct, Value
from devito.parameters import configuration
from devito.tools import as_tuple, ctypes_to_cstr, dtype_to_ctype
from devito.types.basic import AbstractFunction
__all... |
lines = open('day-11.input')
import timeit
def get_map():
return [list((char for char in line.strip())) for line in lines]
map = get_map()
dy = len(map)
dx = len(map[0])
print(str(dy) + 'x' + str(dx))
def copy_from(input):
new_map = []
for y in range(0, dy):
line = []
for x in range(0, dx):
lin... |
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
MODEL = {'T': 'TabNet', 'X':'LightGBM'}
DATASET = {'i':'attrition', 'g':'german'}
DATASETNAME = {'i':'Attrition', 'g':'German'}
METHODS = {'clustering':'Clustering', 'ares':'AReS', 'cet':'CET'}
MARKER = {'clustering':'v', 'ares':'s', 'cet':'o... |
import gdown
url = 'https://drive.google.com/uc?id=1oeSnkgJpwyudtTx-f5CE84B7e-Vkv3yK'
output = 'tensorflow-2.3.1-cp36-cp36m-linux_aarch64.whl'
gdown.download(url, output, quiet=False)
|
"""
17 16 15 14 13
18 5 4 3 12
19 6 1 2 11
20 7 8 9 10
21 22 23---> ...
NOTE: the spiral is 1-indexed.
"""
import itertools
import spiral_walk as sw
def test_first_pos() -> None:
"""Data from square 1 is carried 0 steps, since it's at the access port."""
assert sw.walk_to(1) == s... |
from src import setup, teardown
@setup
def my_smoke_setup(global_object):
global_object.package3 = "package3"
@teardown
def my_smoke_teardown(global_object):
print(global_object.package3)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class InitModuleException(Exception):
pass
class ExceptionParseStandings(Exception):
pass
|
import os
import numpy as np
import pandas as pd
import mne
from mne.preprocessing import ICA, create_ecg_epochs, create_eog_epochs
from autoreject import AutoReject
from scipy.io import loadmat, savemat
#from brainpipe import feature
from src.saflow_params import BIDS_PATH, LOGS_DIR
from mne.io import read_raw_fif, re... |
name = "vfatqc"
|
#! /usr/bin/env python
# coding:utf-8
from __future__ import division, print_function
import unittest
from smt.langmodel.ngram import ngram
from smt.langmodel.ngram import NgramException
class NgramTest(unittest.TestCase):
def test_ngram_3(self):
sentence = ["I am teacher",
"I am",
... |
import tweepy
import requests
from utils import ocr, tweetsplitter
class MentionListener(tweepy.StreamListener):
def __init__(self, api, deepai):
self.api = api
self.key = deepai['key']
def on_status(self, status, firstcall=True):
# Save ID of first tweet with @mention to reply to
if firstcall:
self.id ... |
from pydantic import BaseModel, Field, validator
from decimal import Decimal
from .object_values import (
PriceFilter,
PercentPriceFilter,
LotSizeFilter,
MarketLotSizeFilter,
)
from .tools import strict_integer_validator
class Entity(BaseModel):
class Config:
allow_mutation = True
... |
"""Tests for urls."""
import unittest
from grow.pods import pods
from grow.testing import testing
from . import urls
class UrlTest(unittest.TestCase):
def setUp(self):
dir_path = testing.create_test_pod_dir()
self.pod = pods.Pod(dir_path)
def test_relative_path(self):
"""Relative pa... |
import unittest
from pyalink.alink import *
import numpy as np
import pandas as pd
class TestSwingTrainBatchOp(unittest.TestCase):
def test_swingtrainbatchop(self):
df_data = pd.DataFrame([
["a1", "11L", 2.2],
["a1", "12L", 2.0],
["a2", "11L", 2.0],
["a2", "1... |
# -*- coding: utf-8 -*-
# !/usr/bin/env python
###############################################################################
# Copyright (c) Futurewei Technologies, inc. All Rights Reserved.
#
# Author: Hongwei Jin (hongwei.jin@futurewei.com), 2020-05
#################################################################... |
from django.conf import settings
from django.core.urlresolvers import reverse
from django.db import models
from django.utils import timezone
from django.utils.text import slugify
class Article(models.Model):
""" Model to represent a help article """
body = models.TextField(
help_text="The body of an a... |
# -*- coding: utf-8 -*-
"""Copyright 2015 Ericsson 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 w... |
#!/usr/bin/env python3
from aoc2021.util import print_solutions, import_ints_line
def part_2(fishes, days):
count_cache = {}
count = sum(calc_fish(fish, days, count_cache) for fish in fishes)
print(count)
def calc_fish(fish, days, count_cache):
key = (fish, days)
if key in count_cache:
re... |
import json
import os,requests
from lib import reco_embeds as rm
from lib.helpers import boolConverter
import configs
async def addcount(ctx=None):
updateInterval=int(configs.UPDATE_NOTIFIER_INTERVAL)
#Check the File.
if not os.path.isfile("rcc.txt"):
with open("rcc.txt","w") as f:
f... |
from biokbase.narrative.common.url_config import URLS
import unittest
class UrlConfigTest(unittest.TestCase):
def test_getter(self):
url = URLS.workspace
self.assertTrue(url.endswith('/services/ws'))
def test_get_url(self):
url = URLS.get_url('workspace')
self.assertTrue(url.e... |
"""Script to integrate Config with Security Hub."""
import boto3
import hashlib
SECURITYHUB = boto3.client('securityhub')
CONFIG = boto3.client('config')
def get_description_of_rule(config_rule_name):
"""Gather description of config rule."""
description = ""
try:
response = CONFIG.describe_config... |
import random
import os
import datetime
import requests
# key pair for API authentication
API_KEY = os.environ['DOGGOS_API_KEY']
API_SECRET = os.environ['DOGGOS_API_SECRET']
def create_post(data=None, file=None):
url = 'https://api.iaebots.com/api/v1/posts'
requests.post(url, headers={'Authorization': 'Token api... |
class Solution:
def isRectangleCover(self, rectangles: List[List[int]]) -> bool:
if not any(rectangles):
return False
xmin = ymin = math.inf
xmax = ymax = -math.inf
seen = set()
area = 0
for x1, y1, x2, y2 in rectangles:
xmin = min(xmin, x1)
... |
"""
Copyright contributors to the Application Gateway project
"""
from __future__ import absolute_import
from ibm_application_gateway.config.oauth_ssl import *
from ibm_application_gateway.config.resource_server_cookies import *
from ibm_application_gateway.config.resource_server_forms_login_fields import *
from ibm... |
# Escreva um programa que converta uma temperatura digitada em °C para graus Fahrenheit
celcius = float(input('Está quantos graus °C? '))
fahrenheit = ((9 * celcius) / 5) + 32
print('{}°C equivalem a {}°F'.format(celcius, fahrenheit))
|
# import pylab
# import networkx as nx
from brian2 import *
from scipy.stats import norm as normDistribution
def plotTracesFromStatemon(statemon, *args):
N = len(getattr(statemon, args[0]))
N_lines = ceil(N/4)
plt.ion()
plt.figure()
plots=[]
for i in range(N):
plt.subplot(N_lines, 4, i+1)
for attribute in ... |
#!/usr/bin/env python2
import unittest
import numpy as np
import libpandasafety_py
MAX_RATE_UP = 7
MAX_RATE_DOWN = 17
MAX_STEER = 300
MAX_BRAKE = 350
MAX_GAS = 3072
MAX_REGEN = 1404
MAX_RT_DELTA = 128
RT_INTERVAL = 250000
DRIVER_TORQUE_ALLOWANCE = 50;
DRIVER_TORQUE_FACTOR = 4;
def twos_comp(val, bits):
if val >= ... |
# OctopusLAB (c) 2021
# by Petr Kracik
from . import Keypad
__version__ = "0.5.0"
__license__ = "MIT"
class I2CKeypad(Keypad):
def __init__(self, i2c, address=0x21, bussize = 8, keymap = None):
self._i2c = i2c
self._address = address
self._bussize = bussize
super().__init__(keym... |
"""
Union Find
Input: accounts = [ ["John", "johnsmith@mail.com", "john00@mail.com"],
["John", "johnnybravo@mail.com"], ["John", "johnsmith@mail.com",
"john_newyork@mail.com"], ["Mary", "mary@mail.com"]]
Output: [ ["John", "john00@mail.com", "john_newyork@mail.com",
"johnsmith@mail.com"... |
"""\
wxComboBox widget configuration
@copyright: 2014-2016 Carsten Grohmann
@license: MIT (see LICENSE.txt) - THIS PROGRAM COMES WITH NO WARRANTY
"""
config = {
'wxklass': 'wxComboBox',
'style_defs': {
'wxCB_SIMPLE': {
'desc': _('Creates a combobox with a permanently displayed list. Window... |
import numpy as np
import pandas as pd
def df_rescale_sqrt(data, retain_cols=None, destructive=False):
'''
data : pandas dataframe
A dataframe to be rescaled
retain_cols : str or list
The columns that should be excluded from rescaling
destructive : bool
If set to True, will ... |
import refnx
def refplot(datasets):
"""
Quickly plot a lot of datasets
Parameters
----------
datasets : iterable
{str, file, Data1D} specifying the datasets to plot
Returns
-------
fig : matplotlib.figure.Figure
The figure. Use fig.show() to display
"""
import... |
import csv
import pickle as pkl
import sys
INPUT_FILE_PATH = ""
OVERLAP_PATH = "data/overlapfiles/"
PAS_DATASET = ""
REFERENCE_PATH = ""
'''
This script is a subscript of matrixrawandisoformanalysis.py
This script is set to be run in parallel.
This script takes input in the form of a hdf5 file containing a sparse ... |
###
# Copyright 2021 New H3C 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
#
# Unless required by applicab... |
from django.conf import settings
from django.urls import path
from graphene_django.views import GraphQLView
from .base import urlpatterns
urlpatterns += [path(settings.GRAPHQL_URL, GraphQLView.as_view(graphiql=True))]
|
#!/usr/bin/env python
import argparse, subprocess, json, os, os.path, urllib2, sys, base64, binascii, time, \
hashlib, re, copy, textwrap
#CA = "https://acme-staging.api.letsencrypt.org"
CA = "https://acme-v01.api.letsencrypt.org"
def get_crt(account_key, csr, acme_dir):
# helper function base64 encode for j... |
"""Add support for Sentry notifications.
"""
from .sentry import SentryNotifier
|
import numpy as np
from matplotlib import pylab as plt
import scipy.integrate
from scipy import interpolate
from scipy.optimize import minimize
from random import uniform
class Material():
#Define de lower and upper limits and center frequencies of octave and third-octave bands
lower = {
... |
from starry_process.longitude import LongitudeIntegral
from starry_process.wigner import R
import numpy as np
from scipy.integrate import quad
from tqdm import tqdm
def test_longitude(ydeg=3, rtol=1e-12, ftol=1e-10):
# Random input moment matrices
np.random.seed(0)
N = (ydeg + 1) ** 2
s = np.random.r... |
"""
CMS module customisations for GIMS
License: MIT
"""
from gluon import current, URL, IS_EMAIL
from core import IS_ONE_OF
# -----------------------------------------------------------------------------
def lookup_newsletter_recipients(resource):
"""
Callback function to look up the recipients ... |
from tests.test_helper import *
from braintree.us_bank_account_verification import UsBankAccountVerification
class PaymentMethodWithUsBankAccountTest(unittest.TestCase):
def test_create_with_nonce(self):
customer_id = Customer.create().customer.id
result = PaymentMethod.create({
"custom... |
from rest_framework import status
from rest_framework.response import Response
from rest_framework.generics import GenericAPIView
from ..permissions import IsAuthenticated
from ..models import (
Group_Share_Right
)
from ..app_settings import (
ReadGroupRightsSerializer,
)
from ..authentication import TokenAu... |
import pickle
import numpy as np
def is_close(x):
if x%100 >= 0 and x%100 <=50:
ret_class = [x-x%100,x-x%100+50]
elif x%100 >=50 and x%100 <=99:
ret_class = [x-x%100+50,x-x%100+100]
return ret_class
def predict_dose(age,sex,level):
try:
model = pickle.load(open("models/rf_dos... |
import torchvision.models as models
from torch.nn import Parameter
import torch
import torch.nn as nn
from models.util import *
class PosVAE(nn.Module):
def __init__(self, word_dim, out_dim=256, enc_layers="256", dec_layers="256", tune_pos=False, fuse="add", bias=True):
super(PosVAE, self).__init__()
... |
#!/usr/bin/python
# 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.
"""This script helps to generate code coverage report.
It uses Clang Source-based Code Coverage -
https://clang.llvm.org/docs/SourceBas... |
#Треугольник задан координатами своих вершин. Найти периметр и площадь треугольника.
import math
x1 = (float(input('Введите x1: ')))
x2 = (float(input('Введите x2: ')))
x3 = (float(input('Введите x3: ')))
y1 = (float(input('Введите y1: ')))
y2 = (float(input('Введите y2: ')))
y3 = (float(input('Введите y3: ')))
a =... |
# !/usr/bin/python
# -*- coding: UTF-8 -*-
import random
from urllib.parse import quote
import urllib3
from bs4 import BeautifulSoup
http = urllib3.PoolManager()
header = {
"Host": "xh.5156edu.com",
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:66.0) Gecko/20100101 Firefox/66.0",
"Accept": "text/htm... |
# vim: set encoding=utf-8
from collections import defaultdict
from datetime import datetime
import jinja2
import json
import mock
import os
import shutil
import tempfile
from main import (
LineReader, ThreadLineReader, Messages,
EpiphanyBrowser, BrowserReturnPositioner, EmployeeIDScanner,
Kinto... |
from server.config import get_db_uri
from tasks.prediction import predict
from dbmodels.model import models, insert_model
from sqlalchemy import create_engine
import pickle
import pandas as pd
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.line... |
from .common import preferred_units_from_type, preferred_units_from_symbol, invert_dict
from .units import units, Quantity
import matplotlib.pyplot as plt
from IPython.display import display as mpldisplay
from IPython.display import clear_output
import numpy as np
# Set matplotlib figure size defaults
plt.rcParams["fi... |
import xlrd
datatmp = set()
count = 0
def addall(name):
data = xlrd.open_workbook(name)
table = data.sheet_by_index(0)
for i in range(2, table.nrows):
datatmp.add(str(table.cell(i, 0))[5:])
return table.nrows - 2
... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2018-2019 Pi-Yueh Chuang <pychuang@gwu.edu>
#
# Distributed under terms of the BSD 3-Clause license.
"""Compile and build GeoClaw solver binary."""
import os
import sys
import subprocess
import textwrap
def test_env_variables(var):
"... |
from gpa import Student, make_student
def read_students(filename):
infile = open(filename, 'r')
students = []
for line in infile:
students.append(make_student(line))
infile.close()
return students
def write_students(students, filename):
outfile = open(filename, 'w')
for s in stud... |
from django.urls import path
from . import views
urlpatterns = [
path('login', views.loginhere, name='login'),
path('register', views.register, name='register'),
path('logout', views.logouthere, name='logout'),
path('dashboard', views.dashboard, name='dashboard'),
]
|
while True:
senha=int(input('digite sua senha : '))
if senha==2:
print('acesso permitido')
break
else:
print('senha invalida, tente novamente') |
import os
import sys
sys.path.append(os.path.join(os.path.dirname(os.path.realpath("__file__")), os.pardir))
import os
import sys
import IPython
import numpy as np
import matplotlib.pyplot as plt
import seaborn
import settings
import inspect
import random
import math
from ac_utils.general import *
from ac_utils.evalua... |
from qip.operators import *
from qip.qip import *
from qip.qfft import *
from qip.svgwriter import make_svg
try:
from matplotlib import pyplot
except ImportError:
pyplot = False
def graph(measure):
if pyplot:
pyplot.plot(measure, label='ds')
pyplot.ylim([0, 1])
pyplot.legend()
... |
# -- coding: utf-8 --
from data_base import *
class AnnotationSefRefListItemData(BaseData):
"""
注解引用列表中的子类型结构数据
"""
@classmethod
def create(cls):
"""
创建子项
"""
return AnnotationSefRefListItemData(createBytes(0x04))
def __init__(self, bytes):
"""
初始化
bytes: 字节数组
"""
super(AnnotationSefRefL... |
#!/usr/bin/python -u
#-*- encoding: utf-8 -*-
from collections import OrderedDict
from html import unescape
import os
import random
import re
###
import sys
sys.path.append('../')
###
import utils
SEED = 42
ROOT_URL = 'https://www.rulit.me'
INIT_URL = ROOT_URL + '/tag/samizdat/all/{}/date'
if SEED:
random.seed... |
# coding=utf-8
'''
Created on 2015-9-24
@author: Devuser
'''
from doraemon.ci.pagefactory.ci_pageworker import CIPageWorker
from doraemon.ci.pagefactory.ci_template_path import CIPluginPath
from doraemon.ci.pagefactory.ci_common_pageworker import CICommonControllPageWorker
from doraemon.project.pagefactory.project_co... |
from __future__ import unicode_literals
import vmraid
def execute():
vmraid.reload_doc('custom', 'doctype', 'custom_field', force=True)
try:
vmraid.db.sql('update `tabCustom Field` set in_standard_filter = in_filter_dash')
except Exception as e:
if not vmraid.db.is_missing_column(e): raise e
for doctype in v... |
#!/usr/bin/env python
# -*- mode: python; coding: utf-8 -*-
import sys
import random
from PySide2.QtWidgets import QApplication
from PySide2.QtWidgets import QWidget, QLabel, QPushButton, QVBoxLayout
from PySide2.QtCore import Qt, Slot
def make_str(str):
return '<h1><font color="blue">' + str + '</font></h1>'
... |
from clientbase.clientbase import ClientBase
client = ClientBase()
print(client.clisock.state)
reslist = client.SearchForGoods("Chen")
print(reslist[0]) |
# Predict pKa of acids from descriptors and combination of fingerprint
# and similarity predictors
from sklearn.neural_network import MLPRegressor
from sklearn.model_selection import train_test_split
from sklearn import preprocessing
import numpy as np
from rdkit import Chem
from rdkit.Chem import rdMolDescriptors, L... |
import socket
import time
from unittest import mock
import pytest
from tamarco.resources.basic.metrics import MetersManager
from tamarco.resources.basic.metrics.meters import Counter, Gauge
from tamarco.resources.basic.metrics.reporters import CarbonHandler, FileHandler, StdoutHandler
@pytest.fixture
def meters_man... |
''' Calculate Inception Moments
Adapted from https://github.com/ajbrock/BigGAN-PyTorch/blob/master/calculate_inception_moments.py
under the MIT license.
This script iterates over the dataset and calculates the moments of the
activations of the Inception net (needed for FID), and also returns
the Inception Score o... |
# O(n) time
# create 2 pointers - one for back it would check if number is not 'target',
# and in that case swap it with 'front' pointer
# front pointer tracks 'target' numbers
# [2, 1, 2, 2, 2, 3, 4, 2]
def moveElementToEnd(array, toMove):
front = 0
back = len(array) - 1
while back > front:
if arr... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import lib.helper
def generate(posts, config, output):
data = """<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitema... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.