content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
import sys
import os
import json
# date and time
from datetime import datetime, timedelta
from email.utils import parsedate_tz
from dateutil import tz
import time
from api_extractor_config import DATETIME_FORMAT
def load_credentials(access):
credentials = {}
if access == 'AgProCanada_TableauD... | python |
import json
BATCH_SIZE = 128
RNN_SIZE = 128
EMBED_SIZE = 128
LEARNING_RATE = 0.001
KEEP_PROB = 0.75
EPOCHS = 500
DISPLAY_STEP = 30
MODEL_DIR = 'Saved_Model_Weights'
SAVE_PATH = 'model_saver'
MIN_LEARNING_RATE = 0.01
LEARNING_RATE_DECAY = 0.9
| python |
#!/usr/bin/env python
from __future__ import print_function
import cProfile
import matplotlib.pyplot as plt
import multiprocessing as mp
import numpy as np
import swn
def stats():
grouperLabels = ['Random',
'Min Dist Stars',
'Max Dist Stars',
'1/4 M... | python |
from .abstract_conjunction import AbstractConjunction
from .condition_type import ConditionType
class OrConjunction(AbstractConjunction):
def __init__(self, conditions):
super().__init__(type_=ConditionType.OR.value, conditions=conditions)
| python |
import socket
from enum import IntEnum
import json
import argparse
# Enum of available commands
class Command(IntEnum):
Undefined = 1
SafeModeEnable = 2
SafeModeDisable = 3
ShowNumCommands = 4
ShowNumSafeModes = 5
ShowUpTime = 6
ResetCommandCounter = 7
Shutdown = 8
MAX_COMMAND_NUM = 9
... | python |
# coding: utf-8
# Copyright (c) 2016, 2022, Oracle and/or its affiliates. All rights reserved.
# This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c... | python |
from django.test import TestCase
from dfirtrack_config.filter_forms import AssignmentFilterForm
class AssignmentFilterFormTestCase(TestCase):
"""assignment filter form tests"""
def test_case_form_label(self):
"""test form label"""
# get object
form = AssignmentFilterForm()
#... | python |
from guy import Guy,http
@http(r"/item/(\d+)")
def getItem(web,number):
web.write( "item %s"%number )
def test_hook_with_classic_fetch(runner):
class T(Guy):
__doc__="""Hello
<script>
async function testHook() {
var r=await window.fetch("/item/42")
return await ... | python |
'''Google Sheets Tools'''
import os
from pathlib import Path
import subprocess
import pandas as pd
def save_csv(url: str, save_path: Path, sheet_name: str, show_summary=False):
'''Download a data sheet from Google Sheets and save to csv file'''
sheet_url = f'{url}&sheet={sheet_name}'
subprocess.run(('wge... | python |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# flake8: noqa
from __future__ import absolute_import
from __future__ import print_function
import io
from os import path
from setuptools import setup, Extension
from setuptools.command.build_ext import build_ext
import sys
import setuptools
from setuptools.command.dev... | python |
# Copyright (c) 2021 Alethea Katherine Flowers.
# Published under the standard MIT License.
# Full text available at: https://opensource.org/licenses/MIT
"""Helps create releases for Winterbloom stuff"""
import atexit
import collections
import datetime
import importlib.util
import mimetypes
import os
import os.path
i... | python |
# Generated by Django 3.1.12 on 2021-08-06 12:55
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("aidants_connect_web", "0064_merge_20210804_1156"),
]
operations = [
migrations.AlterField(
model_name="habilitationrequest",
... | python |
from django.shortcuts import render
from sch.models import search1
from sch.models import subs
# Create your views here.
def list(request):
select1=request.POST.get('select1')
select2=request.POST.get('select2')
ls = search1.objects.filter(City=select2)
print(select2)
print(select1)
return re... | python |
from gooey import options
from gooey_video import ffmpeg
def add_parser(parent):
parser = parent.add_parser('trim_crop', prog="Trim, Crop & Scale Video", help='Where does this show??')
input_group = parser.add_argument_group('Input', gooey_options=options.ArgumentGroup(
show_border=True
))
# ... | python |
import pytest
from gpiozero import Device
from gpiozero.pins.mock import MockFactory, MockPWMPin
from pytenki import PyTenki
@pytest.yield_fixture
def mock_factory(request):
save_factory = Device.pin_factory
Device.pin_factory = MockFactory()
yield Device.pin_factory
if Device.pin_factory is not Non... | python |
a=list(map(int,input().split()))
n=len(a)
l=[]
m=0
j=n-1
for i in range(n-2,0,-1):
if(a[i]>a[i-1] and a[i]>a[0]):
m=max(m,a[i]-a[0])
#print(m)
elif(a[i]<a[i-1]):
j=i
m=0
l.append(m)
print(m)
m=0
while(j<n-1):
m=max(m,a[n-1]-a[j])
j+=1
l.appen... | python |
""" Pacakge for various utilities """
| python |
# type:ignore
from django.conf.urls import include, url
from . import views
from django.urls import path
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('', views.index, name='index'),
path('newproject', views.create_project, name = "create_project"),
... | python |
"""
Arrangement of panes.
Don't confuse with the prompt_toolkit VSplit/HSplit classes. This is a higher
level abstraction of the Pymux window layout.
An arrangement consists of a list of windows. And a window has a list of panes,
arranged by ordering them in HSplit/VSplit instances.
"""
from __future__ import unicode... | python |
from microsetta_public_api.utils._utils import (
jsonify,
DataTable,
create_data_entry,
)
__all__ = [
'testing',
'jsonify',
'DataTable',
'create_data_entry',
]
| python |
from __future__ import annotations
import os
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "1"
import numpy as np
import pandas as pd
import datetime
import tensorflow as tf
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import StandardScaler, OneHotEncoder
from sklearn.pipeline import Pipeline
from s... | python |
#It is necessary to import the datetime module when handling date and time
import datetime
currentTime = datetime.datetime.now()
currentDate = datetime.date.today()
#This will print the date
#print(currentDate)
#This the year
#print(currentDate.year)
#This the month
#print(currentDate.month)
#And this the d... | python |
RAD_FILE_FOLDER = ""
path_stack = [] #wrt RAD_FILE_FOLDER
JSON_FILE_FOLDER = "" | python |
# Copyright 2019 Division of Medical Image Computing, German Cancer Research Center (DKFZ), Heidelberg, Germany
#
# 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://w... | python |
import os
ps_user = "sample"
ps_password = "sample"
| python |
# encoding: UTF-8
'''
vn.lts的gateway接入
'''
import os
import json
from vnltsmd import MdApi
from vnltstd import TdApi
from vnltsqry import QryApi
from ltsDataType import *
from vtGateway import *
# 以下为一些VT类型和LTS类型的映射字典
# 价格类型映射
priceTypeMap= {}
priceTypeMap[PRICETYPE_LIMITPRICE] = defineDict["SECURITY_FTDC_OPT_Limi... | python |
from django.apps import AppConfig
class KoperationConfig(AppConfig):
name = 'koperation'
| python |
from scraper.scraper import Scraper
from scraper.template import Template
def start_scraping():
job_name = input('Enter job name: ')
place = input('Enter place: ')
radius = int(input('Enter radius: '))
scraper = Scraper(job_name, place, radius)
print(f'URL: {scraper.page.url}, Place: {scraper.loc... | python |
class Initializer:
def __init__(self, interval):
self.interval = interval
| python |
from django.apps import AppConfig
class RatingsConfig(AppConfig):
name = 'authors.apps.ratings'
| python |
import torch
import torch.nn as nn
from torch.autograd import Variable
import onmt.modules
class Encoder(nn.Module):
def __init__(self, opt, dicts):
self.layers = opt.layers
self.num_directions = 2 if opt.brnn else 1
assert opt.rnn_size % self.num_directions == 0
self.hidden_size =... | python |
import torch.utils.data as data
from torchvision import transforms
from .cifar import CorruptionDataset, cifar_transform, imagenet_transform
from .visda import VisDaTest, visda_test_transforms
from .adversarial import ImagenetAdversarial, imageneta_transforms
from .randaugment import RandAugment
from .augmix import ... | python |
# -*- coding: utf-8 -*-
"""
Python Collection Of Functions.
Package with collection of small useful functions.
Bytes calculator
"""
def bytes2human(size, *, unit="", precision=2, base=1024):
"""
Convert number in bytes to human format.
Arguments:
size (int): bytes to be converted
Key... | python |
import numpy as np
import pandas as pd
from sklearn import preprocessing
import matplotlib.pyplot as plt
import matplotlib
PLOT_TYPE_TEXT = False # For indices
PLOT_VECTORS = True # For original features in P.C.-Space
matplotlib.style.use('ggplot') # Look Pretty
c = ['red', 'green', 'blue', 'orange', 'ye... | python |
from phenotype.Core.Auxiliary import (
__apply__,
__identity__,
)
def Lookup(key_func=__identity__,val_func=__identity__): return __apply__(key_func,val_func)
class Hasher(dict):
''' '''
__key_value_function__ = Lookup(id)
__key__ = id
@classmethod
def __key_value__(cls,... | python |
import math
import unittest
from typing import *
import mock
import pytest
import tensorkit as tk
from tensorkit import tensor as T
from tensorkit.distributions import Categorical, FlowDistribution, UnitNormal
from tensorkit.distributions.utils import copy_distribution
from tensorkit.flows import ReshapeFlow, ActNorm... | python |
import toml
import argparse
import numpy as np
from scipy.stats import entropy
from pom import POM
from sample_script import get_points_covered_by_lidar_config
def evaluate(map, pom_params, lidar_params, config):
points = get_points_covered_by_lidar_config(
pom_params, lidar_params, config, lida... | python |
from cubelang.actions import Action
from cubelang.cube import Cube
from cubelang.orientation import Orientation, Side, Color
from cubelang.cli.cube_builder import apply_side, CubeBuilder
from pytest import raises
from unittest import mock
import pytest
import string
import argparse
from typing import List
class TestA... | python |
"""
线程锁-互斥锁
为什么要使用线程锁分析:https://blog.csdn.net/JackLiu16/article/details/81267176
互斥锁运行顺序分析:https://blog.csdn.net/weixin_40481076/article/details/101594705
"""
import threading,time
#实例化一个互斥锁对象
lock = threading.Lock()
def run():
lock.acquire() #获取锁
print(threading.current_thread().getName(),time.ctime())
... | python |
import FWCore.ParameterSet.Config as cms
from RecoBTag.Skimming.btagMC_QCD_800_1000_cfi import *
btagMC_QCD_800_1000Path = cms.Path(btagMC_QCD_800_1000)
| python |
def getLocation(config):
config['serverType']="regularExperiment"
config['serverPort']=2345
config['webSocketPort']=3456
ip="localhost"
config["domain"]="http://"+ip+":"+str(config['serverPort'])
config["websocketURL"]="ws://"+ip+":"+str(config['webSocketPort'])
return config | python |
import torch.nn as nn
import torch
class Density(nn.Module):
def __init__(self, params_init={}):
super().__init__()
for p in params_init:
param = nn.Parameter(torch.tensor(params_init[p]))
setattr(self, p, param)
def forward(self, sdf, beta=None):
return self.d... | python |
#!/usr/bin/env python3
import matplotlib.pylab as plt
import numpy as np
from astropy import units as u
from ctapipe.io import event_source
from ctapipe.utils import datasets
from ctapipe.visualization import ArrayDisplay
if __name__ == "__main__":
plt.figure(figsize=(9.5, 8.5))
# load up a single event, s... | python |
lists = ['1', '2', '3']
print(lists[3])
| python |
import torch
from torch.utils.data import DataLoader
import pytorch_lightning as pl
import scipy as sp
import numpy as np
import scipy.ndimage
from cyclic_gps.models import LEGFamily
from cyclic_gps.data_utils import time_series_dataset
import matplotlib.pyplot as plt
num_datapoints = 1000
DTYPE = torch.double
RANK ... | python |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
20a.py
~~~~~~
Advent of Code 2017 - Day 20: Particle Swarm
Part One
Suddenly, the GPU contacts you, asking for help. Someone has asked it to
simulate too many particles, and it won't be able to finish them all in
time to render the next fra... | python |
expected_output = {
"cos-interface-information": {
"interface-map": {
"i-logical-map": {
"cos-objects": {
"cos-object-index": ["9", "13"],
"cos-object-name": [
"dscp-ipv6-compatibility",
"ippr... | python |
from django.conf.urls import include, url
from django.urls import path
from django.contrib import admin
from django.views.generic import TemplateView
from rest_framework.permissions import IsAuthenticated
from elvanto_sync import views_api as va
from elvanto_sync import views_buttons as vb
from elvanto_sync.mixins imp... | python |
#!/usr/bin/env python2
# -*- coding: utf-8 -*- #
#
# Builds the GitHub Wiki documentation into a static HTML site.
#
# Copyright (c) 2015 carlosperate https://github.com/carlosperate/
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
#... | python |
#---- Python VNF startup for ENCRYPT_2_to_1---
import SSL_listener
import SSL_writer
incomingIP="localhost"
incomingPort=10026
incomingPrivateKeyFile="server.key"
incomingPublicKeyFile="server.crt"
outgoingIP="localhost"
outgoingPort=10027
outgoingPublicKeyFile="server.crt"
def startENCRYPT_2_to_1():
ssl_writer=SSL_... | python |
from pymongo import MongoClient
class mongoRPSE:
mongos = ""
#insertar datos
def insert_mongo_files(self,data):
mongoc = MongoClient("localhost:27017")
mongodb = mongoc.rpse
mongodb.empresas_file_process.insert_one(data)
def insert_mongo_score(self,data):
mongoc =... | python |
from floodsystem import stationdata
from floodsystem import station
def run():
stations = stationdata.build_station_list()
List = station.inconsistent_typical_range_stations(stations)
print(List)
print(f"Number of inconsistent stations: {len(List)}")
if __name__ == '__main__':
run() | python |
# IME 2022 - LabProg II
#
# Script just testing ploting on python
# This is not working propertly :p
import seaborn as sns
df = sns.load_dataset('iris')
# Usual boxplot
ax = sns.boxplot(x='species', y='sepal_length', data=df)
# Add jitter with the swarmplot function.
ax = sns.swarmplot(x='species', y... | python |
from . import mixins # noqa
from . import generic # noqa
from . import formview # noqa
from . import detail # noqa
from . import uimock # noqa
| python |
from __future__ import print_function
import gdb
import socket
import pickle
import os
import subprocess as sp
import sys
IDA_HOST = '10.113.208.101'
PORT = 56746
TMPDIR = '/tmp/iddaa'
def connect_ida():
if not os.path.exists(TMPDIR):
os.mkdir(TMPDIR)
try:
sock = socket.create_connection((IDA_... | python |
from tqdm import tqdm
from transformers import AutoTokenizer, AutoModelForSequenceClassification
from torch.utils.data import DataLoader, RandomSampler, SequentialSampler, TensorDataset
from torch.profiler import profile, record_function, ProfilerActivity, schedule
import torch
import torch.cuda as cutorch
import numpy... | python |
from mpl_toolkits import mplot3d
import numpy as np
import matplotlib.pyplot as plt
import math
import matplotlib.animation as animation
import sys
# https://towardsdatascience.com/modelling-the-three-body-problem-in-classical-mechanics-using-python-9dc270ad7767
# https://evgenii.com/blog/two-body-problem-simulator/
an... | python |
__author__ = 'anthonymendoza'
from django.db.models import Q, QuerySet
from rest_framework.response import Response
from rest_framework import status
def dynamic_field_lookups(query_params):
Qr = None
for filter_by, filter_value in query_params.iteritems():
filter_by = "date__gte" if filter_by == "sta... | python |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
"""Tabular Q-learning agent (notebook)
This notebooks can be run directly from VSCode, to generate a
traditional Jupyter Notebook to open in your browser
you can run the VSCode command `Export Currenty Python File As Jupyter Notebook`.
"""
# p... | python |
# The init module for all CRUD in bash
import uuid
import re
from datetime import datetime
from app.model.Bash import Bash
from random import randint
from app.utils.helpers import (
md5,
dell,
get_trace,
gen_hash,
check_password,
generate_key
)
from app.utils.save_bash import save_bash
from a... | python |
import csv
from clint.textui import progress
from django.core.management.base import BaseCommand
from shapes.models import MaterialShape
from bsdfs.models import ShapeBsdfLabel_wd
class Command(BaseCommand):
args = ''
help = 'Helper to export CSV data'
def handle(self, *args, **options):
print ... | python |
import os
import shutil
import typing
from ConfigSpaceNNI import ConfigurationSpace
from smac.configspace import pcs_new as pcs
class OutputWriter(object):
"""Writing scenario to file."""
def __init__(self):
pass
def write_scenario_file(self, scenario):
"""Write scenario to a file (for... | python |
# Generated by Django 3.2.8 on 2022-01-17 16:25
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Cause',
fields=[
('id', models.BigAutoField... | python |
import os
import glob
import pandas as pd
flag = True
results = pd.DataFrame()
for counter, current_file in enumerate(glob.glob("*.CSV")):
namedf = pd.read_csv(current_file, header=None, sep=";")
# print(namedf)
results = pd.concat([results, namedf])
results.to_csv('Combined.csv', index=None, sep="... | python |
from django.conf.urls import url
from django.contrib.auth.decorators import login_required, permission_required
from . import views
urlpatterns = [
url(r'^record_history/(?P<account_id>\d+)/$', login_required(views.RecordHistoryView.as_view()), name = 'record_history'),
url(r'^account_list/(?P<trade_type>\w+)/... | python |
a = input('Digite algo: ')
print('é minusculo?', a.islower())
print('é maiuscula?', a.isupper())
print('é um número?', a.isnumeric())
print('é uma letra?', a.isalpha())
| python |
from gym_brt.envs.reinforcementlearning_extensions.rl_reward_functions import (
swing_up_reward,
balance_reward
)
from gym_brt.envs.qube_balance_env import (
QubeBalanceEnv,
)
from gym_brt.envs.qube_swingup_env import (
QubeSwingupEnv,
)
from gym_brt.envs.reinforcementlearning_extensions.rl_gym_class... | python |
#!/usr/bin/env python
# coding=UTF-8
#The first line allows this script to be executable
import os
import sys
import operator
from termcolor import colored
def boost_mode():
print colored('Warning: Some features may not be available except to Titan Series GPUs, nvidia-smi will tell you which ones you can do','red... | python |
import torch
import numpy as np
import argparse
import os
import glob
from tqdm import tqdm
from collections import namedtuple
import sys
sys.path.append('../core')
from oan import OANet
from io_util import read_keypoints, read_descriptors, write_matches
class NNMatcher(object):
"""docstring for NNMatcher"""
d... | python |
class WrongState(Exception):
def __init__(self, value, sessionState=None):
self.value = value
self.state = sessionState
def __str__(self):
return repr(self.value)
| python |
from django.shortcuts import render
from .models import Chat
from .serializers import ChatSerializer
from rest_framework import viewsets
# Create your views here.
class ChatViewSet(viewsets.ModelViewSet):
serializer_class = ChatSerializer
queryset = Chat.objects.all() | python |
import os
import shutil
import requests
import zipfile
import bz2
import tarfile
from splendor.home import get_splendor_home
from splendor.assets import install_assets
from splendor.download import download, agree_to_zip_licenses
import ltron.settings as settings
from ltron.home import get_ltron_home, make_ltron_home... | python |
# 准备U-net训练数据
from scipy import ndimage as ndi
import numpy
import cv2
MASK_MARGIN = 5
def make_mask(v_center, v_diam, width, height):
mask = numpy.zeros([height, width])
v_xmin = numpy.max([0, int(v_center[0] - v_diam) - MASK_MARGIN])
v_xmax = numpy.min([width - 1, int(v_center[0] + v_diam) + MASK_MARG... | python |
import numpy as np
import pymarketstore as pymkts
try:
from unittest.mock import patch
except ImportError:
from mock import patch
from pymarketstore.proto import marketstore_pb2_grpc
from pymarketstore.proto.marketstore_pb2 import MultiQueryRequest, QueryRequest
def test_grpc_client_init():
c = pymkts.... | python |
import unittest
import pathlib
import wellcad.com
from ._extra_asserts import ExtraAsserts
from ._sample_path import SamplePath
class TestLithoPattern(unittest.TestCase, ExtraAsserts, SamplePath):
@classmethod
def setUpClass(cls):
cls.app = wellcad.com.Application()
cls.sample_path = cls._find... | python |
import os
from flask_apispec import MethodResource
from flask_apispec import doc
from flask_jwt_extended import jwt_required
from flask_restful import Resource
from decorator.catch_exception import catch_exception
from decorator.log_request import log_request
from decorator.verify_admin_access import verify_admin_acc... | python |
"""
mbed CMSIS-DAP debugger
Copyright (c) 2006-2015 ARM 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 ... | python |
#!/usr/bin/env python
import cv2
from argparse import ArgumentParser
from time import time
from core.detectors import CornerNet_Saccade, CornerNet_Squeeze
from core.vis_utils import draw_bboxes
def main(args):
cam = cv2.VideoCapture(args.device)
if args.codec == 'YUY2':
cam.set(cv2.CAP_PROP_FOURCC,... | python |
import maya.cmds as cmds
import maya.api.OpenMaya as apiOpenMaya
import maya.OpenMayaMPx as OpenMayaMPx
import json
import os
import math
import sys
import re
import struct
from collections import OrderedDict
from copy import deepcopy
import maya.OpenMaya as OpenMaya
import maya.OpenMayaMPx as OpenMayaMPx
#########... | python |
from threading import current_thread
from threading import Thread as _Thread
class Thread(_Thread):
def __init__(self, group=None, target=None, name=None,
args=(), kwargs=None):
super().__init__(group, target, name, args, kwargs)
self.done = False
self.result = None
... | python |
"""baseline
Revision ID: bb972e06e6f7
Revises:
Create Date: 2020-01-22 23:03:09.267552
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'bb972e06e6f7'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
pass
def downgrade():
p... | python |
# coding: utf-8
import sublime, sublime_plugin
import json
import re
import locale
import calendar
import itertools
from datetime import datetime
from datetime import timedelta
NT = sublime.platform() == 'windows'
ST3 = int(sublime.version()) >= 3000
if ST3:
from .APlainTasksCommon import PlainTasksBase, PlainTask... | python |
import json
from src import util
from threading import Thread
f = open('infos/accounts.json', )
accounts = json.load(f)
f = open('infos/config.json', )
config = json.load(f)
with open('infos/usernames.txt', 'r') as f:
usernames = [line.strip() for line in f]
usernamesForAccount = config["usernamesForAccount"]
... | python |
from collections import defaultdict
from datetime import timedelta
from django.contrib.sites.models import Site
from django.core import serializers
from django.core.exceptions import ObjectDoesNotExist
from django.db.models import signals
from django.utils import timezone
from cms.models import CMSPlugin
from cms.uti... | python |
# Copyright 2017 Neural Networks and Deep Learning lab, MIPT
#
# 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... | python |
"""Show the development of one optimization's criterion and parameters over time."""
from functools import partial
from pathlib import Path
import numpy as np
import pandas as pd
from bokeh.layouts import Column
from bokeh.layouts import Row
from bokeh.models import ColumnDataSource
from bokeh.models import Panel
from... | python |
import sys
import re
def check_url(url):
patt = '^(\w+)://([0-9a-z.]+)(:\d+)?(?:/([0-9a-z_/.]+)?(\S+)?)?$'
m = re.match(patt, url, re.I)
if m:
schema = m.group(1)
port = m.group(3)
if port is None and schema == 'http':
port = 80
return {'schema': schema, 'hostname': m.group(2), 'port': port... | python |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... | python |
#! /usr/bin/python3
#-*- coding: utf-8 -*-
from __future__ import print_function
import datetime
import sys
import re
class SscSite:
def __init__(self, **kwargs):
self.domes = kwargs['domes']
self.site_name = kwargs['site_name']
self.id = kwargs['id']
self.data_start = kwargs['dat... | python |
#------------------------------------------------------------------------------
# Copyright (c) 2013-2017, Nucleic Development Team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE, distributed with this software.
#------------------------------------------------... | python |
import unittest
from selenium import webdriver
class AdminLoginPageTest(unittest.TestCase):
def setUp(self):
self.admin_username = self.admin_password = 'admin'
self.site_title = 'Global Trade Motors'
self.browser = webdriver.Firefox()
self.browser.get("http://localhost:8000/admin... | python |
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class Product(models.Model):
productname=models.CharField(max_length= 255)
productdescription=models.TextField(null=True, blank=True)
productusage=models.TextField(null=True, blank=True)
productquantity=... | python |
#==========================================================================
#
# Copyright Insight Software Consortium
#
# 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... | python |
#!/usr/bin/env python2.7
#coding:utf-8
#import bpy
import os
import math
import random
from PIL import Image
import time
import codecs
import hjson
from bslideshow.slideshow import Slideshow
from bslideshow.tools import BlenderTools
ADJUST_Y = -0.1
class Director(BlenderTools):
def __init__ (self):
self.sl... | python |
from collections import defaultdict
import codecs
import csv
import json
by_verb = defaultdict(set)
with codecs.open('data.csv', encoding='utf-8', errors='ignore') as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
verbs = [
v.strip()
for v_semi in row['verb'].low... | python |
# import numpy as np
#
# ranNUm1 = np.random.random([2,3])
# print(ranNUm1)
# print(type(ranNUm1))#<class 'numpy.ndarray'> 内部元组数据类型必须一直
#
# arrTest = np.arange(32)
# print(arrTest)
# print(arrTest.reshape([4 , 8]))
| python |
class Solution:
def solve(self, digits):
map = {
'2':'abc',
'3': 'def',
'4': 'ghi',
'5': 'jkl',
'6': 'mno',
'7': 'pqrs',
'8': 'tuv',
'9': 'wxyz'
}
output = []
def helper(combination, digit... | python |
import random
import pickle
import torch
from torch import nn
class EncDecNetwork(nn.Module):
def __init__(self, encoder, decoder):
super(EncDecNetwork, self).__init__()
self.encoder = encoder
self.decoder = decoder
self._cuda = False
def full_forward(self):
raise Not... | python |
from opentrons import protocol_api
import json
import os
import math
import threading
from time import sleep
metadata = {'apiLevel': '2.5'}
NUM_SAMPLES = 24
SAMPLE_VOLUME = 475
def run(protocol: protocol_api.ProtocolContext):
source = protocol.load_labware('starlab_96_wellplate_2000ul', 2)
dest = protocol.... | python |
#!/usr/bin/python
# -*- coding: utf-8 -*-###
# Copyright (2018) Hewlett Packard Enterprise Development LP
#
# 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/LI... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.