content stringlengths 5 1.05M |
|---|
from django.core.handlers.wsgi import WSGIHandler
import pinax.env
# setup the environment for Django and Pinax
pinax.env.setup_environ(__file__)
# set application for WSGI processing
application = WSGIHandler() |
from interfaces import DataInterface
class Data(DataInterface):
def __init__(self) -> None:
self.weight: float = 0
def setTotalWeight(self, weight: float) -> None:
self.weight = weight
def getTotalWeight(self) -> float:
return self.weight
|
import os
from setuptools import setup, find_packages
setup(name='gelato.admin',
version='0.0.1',
description='Gelato admin',
namespace_packages=['gelato'],
long_description='',
author='',
author_email='',
license='',
url='',
include_package_data=True,
pack... |
#!/usr/bin/python
import unittest
from lib.brainwallet import private_key, public_key
from lib.secp256k1 import secp256k1
class AddressTest(unittest.TestCase):
phrase = "passphrase"
private_key = "1e089e3c5323ad80a90767bdd5907297b4138163f027097fd3bdbeab528d2d68"
public_key = "13YXiHAXcR7Ho53aExeHMwWEgHcB... |
from flexx import flx
#The Widget class is the base class of all other ui classes. On itself it does not do or show much. What you’ll typically do, is subclass it to create a new widget that contains ui elements
class WebPage(flx.Widget):
def init(self):
flx.Button(text='hello')
flx.Button(text='w... |
# -*- coding: utf-8 -*- #
# Copyright 2018 Google 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 IndexerMod
import ThreadingMod
import threading
import time
##MyCraweler.Crawel()
##MyIndexer = IndexerMod.Indexer()
##MyIndexer.StartIndexing()
#MyThreads=[]
#MyCraweler.Crawel("https://moz.com/top500")
#MyCraweler.Crawel("https://www.facebook.com/")
#MyCraweler.Crawel("https://www.crummy.com/software/Beaut... |
import discord
# Defining the client that the bot will log in
client = discord.Client()
@client.event
async def on_ready():
# Basic definitions to the entrance of the robot to the network
print("BOT ON **")
print("Name= {}".format(client.user.name))
print("------------")
@client.event
async def on_... |
import pandas as pd
import numpy as np
from scipy import stats
from scipy.stats import norm
import matplotlib.pyplot as plt
import seaborn as sns
from IPython.display import Markdown, display
def printmd(string):
display(Markdown(string))
def normality_diagnostic (s, var):
fig, ax = plt.subplots(figsize=... |
from torch import nn
from torchvision.models.resnet import ResNet
from torchvision.models.resnet import BasicBlock
from torchvision.models.resnet import Bottleneck
from pretrainedmodels.models.torchvision_models import pretrained_settings
from .attention_modules.cbam import CBAM
from .attention_modules.bam import BAM
... |
# Master version for Pillow
__version__ = '5.2.0'
|
from thesis_util.thesis_util import eval_experiment
from thesis_util.thesis_util import create_eval_recon_imgs,create_eval_random_sample_imgs
# load results for spatial VAE with latent space 3x3x9
# Pathes and names
pathes_2_experiments = [r'C:\Users\ga45tis\GIT\mastherthesiseval\experiments\VQVAEadapt_06_25AM on Novem... |
def f(<caret>x):
pass
|
# Question 2
# Count number 4 in a list
list1 = [1, 2, 10, 4, 3, 4, 4, 4, 1, 3, 5]
x = 0
for i in range(len(list1)):
if list1[i] == 4:
x += 1
print("Number of 4 in the list:", x)
|
# -*- coding: utf-8 -*-
import os
import numpy as np
import numpy.testing as npt
import pytest
from numpy import genfromtxt
import roomacoustics.dsp as dsp
test_data_path = os.path.join(os.path.dirname(__file__), 'test_data')
def test_start_ir_insufficient_snr():
n_samples = 2**9
ir = np.zeros(n_samples, ... |
import datetime
from dataclasses import dataclass
import sqlalchemy as sa
import sqlalchemy.orm as orm
from data.models.modelbase import SqlAlchemyBase, UniqueMixin
@dataclass
class User(UniqueMixin, SqlAlchemyBase):
__tablename__ = 'users'
id: int = sa.Column(sa.Integer, primary_key=True, autoincrement=Tr... |
"""Built-in weight initializers.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import six
from . import backend as K
from .utils.generic_utils import serialize_keras_object
from .utils.generic_utils import deserialize_keras_object
... |
from openbiolink.graph_creation.file_processor.fileProcessor import FileProcessor
from openbiolink.graph_creation.metadata_infile.mapping.inMetaMapDisGeNet import InMetaMapDisGeNet
from openbiolink.graph_creation.types.infileType import InfileType
from openbiolink.graph_creation.types.readerType import ReaderType
cla... |
import re
from pygmalion._model import Model
from typing import List, Iterable, Optional
class Tokenizer(Model):
"""
A text tokenizer is an object with an 'encode' and a 'decode' method
"""
def encode(self, sentence: str, regularize: bool = False) -> List[int]:
"""encode a sentence"""
... |
# Copyright 2013-2021 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class NcepPost(CMakePackage):
"""The NCEP Post Processor is a software package designed
to g... |
# coding: utf-8
"""
Part of this code is based on a similar implementation present in FireWorks (https://pypi.python.org/pypi/FireWorks).
Work done by D. Waroquiers, A. Jain, and M. Kocher.
The main difference wrt the Fireworks implementation is that the QueueAdapter
objects provide a programmatic interface for settin... |
from .agent import Agent
from .random_agent import RandomAgent
from .human_agent import HumanAgent
from .student_agent import StudentAgent
|
import numpy as np
import pandas as pd
from feature_importance.feature_importance import FeatureImportance
from evaluators.evaluator import Evaluator
from models.model import Model
class Permutation(FeatureImportance):
def __init__(self, model_type):
super().__init__(model_type)
def calc_feature_impo... |
from esper.prelude import *
from matplotlib.patches import Patch
from matplotlib.lines import Line2D
from scipy.stats import linregress
import statsmodels.api as sm
MALE_COLOR = 'tab:blue'
FEMALE_COLOR = 'tab:red'
MARKER_SIZE = 50
def align(col, all_dfs):
all_cols = reduce(lambda x, y: x & y, [set(list(df[col]))... |
import torch
import torchvision
import numpy as np
import matplotlib.pyplot as plt
import torch.nn as nn
import torch.nn.functional as F
from torchvision.transforms import ToTensor
from torchvision.utils import make_grid
from torch.utils.data import random_split
from torch.utils.data import TensorDataset, DataLoader
im... |
import pandas as pd
import numpy as np
from difflib import SequenceMatcher
from nltk.translate.bleu_score import SmoothingFunction, sentence_bleu
from nltk.translate.gleu_score import sentence_gleu
from sklearn import metrics
def _tag(x, strict):
return x or "" if strict else ""
def _spanrange(span, str_spans=Tru... |
#!/usr/bin/python
# Populates a local mongo db with currency minute data using the ForexiteConnection class.
from nowtrade import data_connection
import datetime
start = datetime.datetime(2014, 05, 17)
end = datetime.datetime(2015, 02, 20)
data_connection.populate_currency_minute(start, end, sleep=60)
|
import pandas as pd
import requests
import es_cal.gcal.config as cfg
import time
from datetime import datetime
from es_cal.gcal import make_event_in_gcal
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
f... |
from datetime import datetime
from hearthstone import enums
def test_zodiac_dates():
assert enums.ZodiacYear.as_of_date(datetime(2014, 1, 1)) == enums.ZodiacYear.PRE_STANDARD
assert enums.ZodiacYear.as_of_date(datetime(2016, 1, 1)) == enums.ZodiacYear.PRE_STANDARD
assert enums.ZodiacYear.as_of_date(datetime(2016,... |
"""
Contains:
Colors:
- Colors Class
- Create & Convert colors to RGB, HEX, HSV and CMYK
Colors tuples in RGB
"""
from math import floor
from typing import Tuple
class Color:
"""
Color values in RGB
"""
Red = (255, 0, 0)
Green = (0, 255, 0)
Blue = (0, 0, 255)
Whit... |
#pythran export _integ(uint8[:,:], int, int, int, int)
import numpy as np
def _clip(x, low, high):
assert 0 <= low <= high
if x > high:
return high
if x < low:
return low
return x
def _integ(img, r, c, rl, cl):
r = _clip(r, 0, img.shape[0] - 1)
c = _clip(c, 0, img.shape[1] - 1)... |
# -*- coding: utf-8 -*-
import ipaddress
import numpy
import Crypto.Cipher.AES
import array
import struct
import socket
class IPAddrAnonymizer:
def __init__(self):
self.init()
def setRandomSeed(self,seed):
numpy.random.seed(seed)
self.init()
def init(self):
self.blockA = n... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import sys
def add_path(paths):
if not isinstance(paths, (list, tuple)):
paths = [paths]
for path in paths:
if path not in sys.path:
sys.path.insert(0, path)
de... |
def happyNumber(n):
# 1 <= n <= 2^31 - 1 == 2,147,483,647 Mersenne prime.
# the maximum positive value for a 32-bit signed binary integer
if n <= 0:
return False
for count in range (0, 6):
# Split number
suma = 0;
while n > 0:
# Add square number
... |
"""EOF (End of file) - special token, query and resolver for this specific token
Use of this token is optional, but it helps parser to identify the end to trigger productions.
EOF is a special object to distinguish from any text / None or other tokens that could be valid.
"""
from .grammar import TerminalQuery
from .... |
from lightCore import *
class Item:
def __init__(self, name, nameish, description, weight, cost, image):
self.weight = weight
self.cost = cost
self.name = name
self.nameish = nameish
self.description = description
self.image = image
self.cat = "Item"
class... |
import io, os.path, re
from setuptools import setup, find_packages
def read(*names, **kwargs):
with io.open(
os.path.join(os.path.dirname(__file__), *names),
encoding=kwargs.get("encoding", "utf8")
) as fp:
return fp.read()
def find_version(*file_paths):
version_file = read(*file... |
import json
class Move():
def __init__(self, move_type, count, value):
#valid MOVE_TYPE's
# attack
# block
self.type = move_type
self.count = count
self.value = value
class MoveEncoder(json.JSONEncoder):
def default(self, obj):
try:
return {... |
# -*- coding: utf-8 -*-
import sys
import os
from loguru import logger
from datetime import datetime
_author_ = 'luwt'
_date_ = '2021/8/27 11:11'
# 移除原本的控制台输出样式
logger.remove()
log_format = (
'<g>{time:YYYY-MM-DD HH:mm:ss}</g> '
'| <level>{level: <8}</level> '
'| <e>{thread.name: <12}</e> '
'| <cyan>{... |
from cumulusci.tasks.github.merge import MergeBranch
from cumulusci.tasks.github.pull_request import PullRequests
from cumulusci.tasks.github.release import CreateRelease
from cumulusci.tasks.github.release_report import ReleaseReport
from cumulusci.tasks.github.tag import CloneTag
__all__ = ("MergeBranch", "PullRequ... |
# import libraries
import pyttsx3
import PyPDF2
# load PDF to be read
content = open('TheRaven.pdf', 'rb')
#print(type(content))
Reader = PyPDF2.PdfFileReader(content)
# get number of pages in document
pages = Reader.numPages
print(pages)
read_out = pyttsx3.init()
# set Japanese voice
voices = read_out.getProperty... |
import pytest
from typing_extensions import get_args
from typing_extensions import get_origin
from phantom.negated import SequenceNotStr
parametrize_instances = pytest.mark.parametrize(
"value",
(
("foo", "bar", "baz"),
(1, 2, object()),
(b"hello", b"there"),
[],
["foo"... |
from django.urls import path
from . import views
app_name = 'workshop'
urlpatterns=[
path('',views.workshop,name='workshop_page'),
path('form/',views.workshop_form,name='workshop_form'),
path('delete/<int:pk>/',views.deleteWorkshop,name='workshop_delete'),
path('update/<int:pk>/',views.updateWorkshop,... |
"""
CGNS <https://cgns.github.io/>
TODO link to specification?
"""
import numpy
from .._exceptions import ReadError
from .._helpers import register
from .._mesh import Mesh
def read(filename):
f = h5py.File(filename, "r")
x = f["Base"]["Zone1"]["GridCoordinates"]["CoordinateX"][" data"]
y = f["Base"]["... |
# pythonpath modification to make hytra and empryonic available
# for import without requiring it to be installed
import os
import sys
sys.path.insert(0, os.path.abspath('..'))
import skimage.external.tifffile as tiffile
import argparse
import numpy as np
import h5py
import hytra.util.axesconversion
if __name__ == "... |
# Copyright (c) 2013 OpenStack Foundation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to... |
VARIABLE_TYPES = [
'<string',
'<boolean',
'<map',
'<integer',
'<float',
'<double',
'<COMPONENT',
'<[]string',
'<[]boolean',
'<[]map',
'<[]integer',
'<[]float',
'<[]double',
'<[]COMPONENT',
]
def get_json(obj):
if type(obj) == dict:
return obj
else... |
# Clase 19. Curso Píldoras Informáticas.
# Control de Flujo. Generadores 1.
# Más eficientes que las funciones tradicionales. Ahorra memoria y trabajo.
# Útiles para trabajar con listas de valores infinitos como una lista que devuelva IPs random.
# Además de yield puede llevar el método return.
# Funció... |
# -*- coding: utf-8 -*-
from icalendar.tests import unittest
import datetime
import icalendar
import os
class TestTime(unittest.TestCase):
def setUp(self):
icalendar.cal.types_factory.types_map['X-SOMETIME'] = 'time'
def tearDown(self):
icalendar.cal.types_factory.types_map.pop('X-SOMETIME'... |
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from scipy import stats
import csv
def get_rand_data(nrow, file_name):
s = np.random.uniform( 0 , 1 , nrow * 10)
for i in range(nrow * 10):
s[i] = (int(s[i] * 10 + 0.5))/10
rd = np.reshape( s , (nrow , 1... |
from django.contrib.auth import get_user_model
from django.urls import reverse
from django.test import TestCase
from rest_framework import status
from rest_framework.test import APIClient
from core.models import Ingredient
from recipe.serializers import IngredientSerializer
INGREDIENTS_URL = reverse('recipe:ingredien... |
from PIL import Image, ImageDraw, ImageOps
import turtle
import util
import os
import gcode as gc
import argparse
# Printer parameters (Change these values to match your 3D printer/CNC machine)
painting_size = 150 # Max x/y dimension of paining in mm
origin_offset = (75, 75) # x/y origin of painting on printer in mm... |
from .category import Category
# from .code_edition import CodeEdition
from .user import User
|
from django.db import models
from django.utils.text import slugify
from django.contrib.auth.models import BaseUserManager, AbstractUser
from localflavor.br.validators import BRCPFValidator
class UserManager(BaseUserManager):
def create_user(self, email, password=None):
if not email:
raise Val... |
from google.appengine.api import urlfetch
from BeautifulSoup import BeautifulSoup
from google.appengine.api import memcache
import re
import cPickle as pickle
import logging
from sys import setrecursionlimit
setrecursionlimit(4000)
agencyURL = "http://www.nextbus.com/wireless/miniAgency.shtml?re=%s"
routeURL = "http:/... |
# https://www.facebook.com/rohit.jha.94043/posts/1638189713017643
#subscribe by code house
import random
import turtle
# function to check whether turtle
# is in Screen or not
def isInScreen(win, turt):
# getting the end points of turtle screen
leftBound = -win.window_width() / 2
rightBound = win.window_wi... |
"""
Functions for pretty-printing tables.
author: dangeles at caltech edu
"""
def table_print(l, space=20):
"""
A function to pretty-print tables.
Params:
l - a list of strings, each entry is in a different column
space - the space between the separators.
Must be > than the longest en... |
import numpy as np
from nptyping import NDArray
from typing import Union, Tuple
from ..objective import Objective
from .. import utils
def soma_II(f: Objective, r: int, eps: float) -> Tuple[NDArray[int], float]:
"""
Implement Soma'18 algorithm for maximizing a submodular monotone function
over the integer... |
# Generated by Django 2.2.12 on 2020-05-04 13:22
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('permissions', '0002_auto_20200221_2126'),
('environments', '0011_auto_20200220_0044'),
]
operations = [
migrations.DeleteModel(
... |
"""Rattr error/logging functions."""
import ast
import sys
from enum import Enum
from os.path import expanduser
from typing import List, Optional, Tuple
from rattr import config
__ERROR = "{prefix}: {optional_file_info}{optional_line_info}{message}"
__FILE_INFO = "\033[1m{}: \033[0m"
__LINE_INFO = "\033[1mline {}:{}... |
from unittest import TestCase
from bin.retrieve import Retriever
class TestRetrieve(TestCase):
def test_failure(self):
self.fail()
def test_fail_to_load_database_config(self):
with self.assertRaises(SystemExit):
Retriever({})
|
#!/usr/bin/env python
# This files contains functions to construct matrices
import numpy as np
from utils import calculate_matrix_A, find_neighbors, calc_D_size, calculate_N_from_level
# Load normal matrix from file
def load_matrix(aFile):
with open(aFile, "r") as f:
A = np.loadtxt(f, delimiter=",")
... |
from configredis.setconf import defaultconfig, devconfig, proconfig, configs, ConfigArgs, ConfigUpdate, lookup_proj_config
from configredis.setredis import SetRedis
con = ConfigArgs()
defaultconfig(
disk_name='TenD'
)
devconfig(
sentry=False,
celery_broker="amqp://user:password@172.0.0.1:5672//",
)
pro... |
import requests
# API_URL = "https://rel.cs.ru.nl/api"
API_URL = "http://localhost:5555"
# text_doc = "If you're going to try, go all the way - Charles Bukowski"
# text_doc = "David and Victoria named their children Brooklyn, Romeo, Cruz, and Harper Seven."
text_doc = "Victoria and David added spices on their marriag... |
"""Plot intensity profile of sidelobes."""
import matplotlib.pyplot as plt
import numpy as np
from frbpoppy.survey import Survey
from tests.convenience import plot_aa_style, rel_path
SIDELOBES = [0, 1, 2, 8]
SURVEY = 'wsrt-apertif'
MIN_Y = 1e-7
n = 50000
plot_aa_style()
for sidelobe in reversed(SIDELOBES):
ar... |
# Copyright 2015 Mirantis, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or ... |
import sys
import pickle
from rdkit import Chem
from rdkit.Chem import AllChem
# Reaction formats
# __rxn1__ = AllChem.ReactionFromSmarts('[C;H1:1]=[C,N;H1:2]>>[CH2:1][*H+:2]')
# __rxn2__ = AllChem.ReactionFromSmarts('[C;H1:1]=[C,N;H0:2]>>[CH2:1][*+;H0:2]')
__rxn1__ = AllChem.ReactionFromSmarts('[C;R;H1:1]=[C,N;R;H1:... |
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
import os
import copy
import scipy
def make_gif(images, fname, duration=2, true_image=False):
import moviepy.editor as mpy
def make_frame(t):
try:
x = images[int(len(images)/duration*t)]
except:
x = images[-1]
if t... |
import sys
import os
import time
import tqdm
import shelve
import argparse
import skimage.io
from torchvision import transforms
from collections import defaultdict
from pathlib import Path
import torch
import matplotlib
import numpy as np
from PIL import Image
import model.model as module_arch
from data_loader import ... |
""" The Upload ServiceProvider for Backblaze B2 """
from masonite.provider import ServiceProvider
from .driver import UploadBackblazeDriver
class UploadBackblazeProvider(ServiceProvider):
wsgi = False
def register(self):
self.app.bind('UploadBackblazeDriver', UploadBackblazeDriver)
def boot(se... |
# Standard settings except we use SQLite, this is useful for speeding
# up tests that depend on the test database, try for instance:
#
# ./manage.py test --settings=settings_sqlitetest doc.ChangeStateTestCase
#
from settings import * # pyflakes:ignore
# Workaround to avoid spending minutes stepping... |
class Credentials:
# Class that generates new instances of credentials.
def __init__(self,account,password):
self.account = account
self.password = password
credentials_list = [] # Empty credentials list
def save_credential(self):
# save_user method saves credent... |
import sys
import trimesh
import pandas as pd
import numpy as np
import subprocess, glob, os, json
from autolab_core import YamlConfig
from pose_rv import GaussianPoseRV
masses = {
'bar_clamp': 18.5, 'book': 34.8, 'bowl': 15.7, 'cat': 9.9, 'cube_3cm': 3.0, 'endstop_holder': 16.3,
'engine_part': 28.6, 'fan_extr... |
import string
import contractions
import io
from gutenberg.acquire import load_etext
from gutenberg.cleanup import strip_headers
#book = strip_headers(load_etext(2701)).strip()
#print(book)
# load text
filename = 'songs-input.txt'
file = open(filename, encoding="utf8")
text = file.read()
file.close()
# expand contact... |
#!/usr/bin/env python3
"""
check the security and functionability of uploaded code
- forbid from importing os
- random chessboard check
- some special case check
"""
import imp
import traceback
import sys
import os
import numpy as np
from timeout_decorator import timeout
FORBIDDEN_LIST = ['import os', 'exec']
class ... |
# Copyright (c) 2020 KU Leuven
import os
os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID"
import sparsechem as sc
import scipy.io
import scipy.sparse
import numpy as np
import pandas as pd
import torch
import argparse
import os
import sys
import os.path
import time
import json
import functools
import csv
#from apex import ... |
import unittest
import mock
from cloudshell.devices.snmp_handler import SnmpContextManager
from cloudshell.devices.snmp_handler import SnmpHandler
class TestSnmpContextManager(unittest.TestCase):
def setUp(self):
self.enable_flow = mock.MagicMock()
self.disable_flow = mock.MagicMock()
se... |
''''Write a function called repeatStr which repeats the given string string exactly n times.'''
def repeat_str(repeat, string):
return string*repeat
|
import threading
from date_time_event.utils import (convert_datetime_secs,
complete_datetime)
class Untiltime(threading.Thread):
def __init__(self, function=None, dateOrtime=None, name=None,
join=False, group=None, daemon=False, *args, **kwargs):
super... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from netests import log
from netests.constants import COMPARE_OPTION_KEY, PRINT_OPTION_KEY, NOT_SET
ERROR_HEADER = "Error import [ospf.py]"
class OSPFSession:
peer_rid: str
local_interface: str
peer_ip: str
session_state: str
peer_hostname: str
... |
# Note: this file was automatically converted to Python from the
# original steve-language source code. Please see the original
# file for more detailed comments and documentation.
import breve
class Camera( breve.Abstract ):
'''Summary: creates a new rendering perspective in the simulated world. <P> The Camera c... |
# Copyright (c) 2019-2020 Cloudify Platform Ltd. 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 b... |
"""This is the front end fof the command line utility. Features can
be accessed according to the available commands"""
import sys, argparse, pkgutil
from importlib import import_module
import os.path
import fcsio.cli.utilities
def main():
"""save the full command"""
cache_argv = sys.argv
front_end_args = sy... |
'''
New Integration Test for hybrid.
@author: Legion
'''
import zstackwoodpecker.test_util as test_util
import zstackwoodpecker.test_lib as test_lib
import zstackwoodpecker.test_state as test_state
import zstackwoodpecker.operations.hybrid_operations as hyb_ops
import zstackwoodpecker.operations.resource_operations ... |
import requests
from . import embed
from . import extra
class DMChannel:
"""
Nertivia DM Channel
Same as Text Channel but is used to send messages to a user.
Attributes:
- id (int): The ID of the channel.
"""
def __init__(self, id) -> None:
self.id = id
def send(self, cont... |
import json
#Usage
#Auxiliary set of files of manage_responses.py function
#Mainly functions that manage dictionairies
def get_final_json(server_response_text, query_result, audio_encode):
json_trial = json.loads(server_response_text)
json_trial.update({"user_response" : query_result.query_text})
json_trial... |
#coding=utf-8
"""
@From book Fluent Python
cannot run on Python 2.7
"""
import collections
class DoubleDict(collections.UserDict):
kk = {}
def __setitem__(self, key, value):
## In Python 2.7
super(DoubleDict, self).__setitem__( key, [value] * 2)
def main():
dd = DoubleDict(one = 1)
prin... |
__pragma__('noalias', 'update')
class Scene:
def __init__(self, config=None):
if config is None:
self.scene = __new__(Phaser.Scene())
else:
self.scene = __new__(Phaser.Scene(config))
self.scene.init = self.init
self.scene.preload = self.preload
self.... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2021-01-16 10:28:33
# @Author : Zhi Liu (zhiliu.mind@gmail.com)
# @Link : http://iridescent.ink
# @Version : $1.0$
from __future__ import division, print_function, absolute_import
import torch as th
from torchsar.utils.const import *
from torchsar.dsp.norma... |
import os
import errno
import json
import gdal
from googleapiclient.http import MediaFileUpload
from google.cloud import storage
# Create the service client
from googleapiclient.discovery import build
from apiclient.http import MediaIoBaseDownload
GOOGLE_APPLICATION_CREDENTIALS = os.getenv('APPLICATION_CREDENTIALS... |
# -*- coding: utf-8 -*-
# DISTRIBUTION STATEMENT A. Approved for public release. Distribution is unlimited.
# This material is based upon work supported under Air Force Contract No. FA8702-15-D-0001.
# Any opinions,findings, conclusions or recommendations expressed in this material are those
# of the author(s) and do ... |
# import os
# import re
#
# # DEFAULT SETTING
#
# WORKER_PATH = re.sub(r'([\\/]items$)|([\\/]spiders$)|([\\/]utils$)', '', os.getcwd())
#
# SCHEDULER = 'ReSpider.core.scheduler.Scheduler' # python <Queue> 队列
# DUPEFILTER = 'ReSpider.dupefilter.RFPDupeFilters' # 去重组件
#
# # SCHEDULER = 'ReSpider.extend.redis.scheduler.... |
#codes to for analyse the model.
import re
import os
from astropy import units as u
from tardis import constants
import numpy as np
import pandas as pd
class LastLineInteraction(object):
@classmethod
def from_model(cls, model):
return cls(model.runner.last_line_interaction_in_id,
... |
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 21 11:14:53 2016
@author: Administrator
"""
#数据库中读取数据
import pymongo_class as mongdb_class
import pandas as pd
dataunion = mongdb_class.MongoClass('10.82.0.1',27017,'bigdata','dataunions');
artlist = dataunion.find_mongo({});
datayuan = mongdb_class.MongoClass... |
import cv2
import numpy as np
import dlib
from imutils import face_utils
import face_recognition
from keras.models import load_model
from statistics import mode
from utils.datasets import get_labels
from utils.inference import detect_faces
from utils.inference import draw_text
from utils.inference import draw_bounding_... |
import requests
from ast import literal_eval
import json
import re
def get_unfollowed_followers():
headers = {
'cookie': 'mid=XRvsVwAEAAFhekNSfuB2niWmAW9v; csrftoken=ppIenJiCBh20h06wjwBUAC2Q1E3e4FnQ; shbid=8575; ds_user_id=38135600; sessionid=38135600%3AVCSshmWATt5OoG%3A26; rur=VLL; shbts=1562906659.046413... |
# -*- coding:utf-8 -*-
from django.template import Library
register = Library() # 必须叫register
# @register.tag
# @register.tag_function
@register.filter
def mod(param):
"""判断单双"""
# if param % 2 == 0:
# return True
# else:
# return False
return param % 2
@register.filter
def mod1(pa... |
#
# ESnet Network Operating System (ENOS) Copyright (c) 2015, The Regents
# of the University of California, through Lawrence Berkeley National
# Laboratory (subject to receipt of any required approvals from the
# U.S. Dept. of Energy). All rights reserved.
#
# If you have questions about your rights to use or distrib... |
# Generated by Django 2.1.5 on 2019-02-18 11:27
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('todo', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='todo',
... |
from hyperopt.hp import choice
from hyperopt.hp import randint
from hyperopt.hp import pchoice
from hyperopt.hp import uniform
from hyperopt.hp import quniform
from hyperopt.hp import loguniform
from hyperopt.hp import qloguniform
from hyperopt.hp import normal
from hyperopt.hp import qnormal
from hyperopt.hp import lo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.