content stringlengths 5 1.05M |
|---|
#!/usr/bin/env python2.5
#
# Copyright 2009 the Melange authors.
#
# 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 applic... |
import argparse as ag
import ast
import csv
import datetime
from ebooklib import epub
import feedparser
import json
import logging
from termcolor import colored
logging.basicConfig(filename='logs.log', level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - '
'%(me... |
# ----------------------------------------------------------------------------
# meh
# Copyright (c) 2021 TreeCaptcha
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the "Software"),
# to deal in the Software without restriction, in... |
# -*- coding: utf-8 -*-
# Copyright 2011 Fanficdownloader team
#
# 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 require... |
from collections import namedtuple
import csv
import gzip
from os.path import abspath, join
import subprocess
from growser.app import db, log
from growser.db import from_sqlalchemy_table
from growser.models import Recommendation
from growser.cmdr import DomainEvent, Handles
from growser.commands.recommendations impor... |
# 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, software
# distributed under t... |
from json import decoder, loads
from os import getenv
from re import findall, search
from nfu.expand_bus.network import http_get
from nfu.expand_bus.ticket import get_alipay_url
from nfu.nfu_error import NFUError
def get_bus_schedule(route_id: int, date: list) -> dict:
"""
若日期在车票预售期内,获取班车时刻表。
- 字段说明
... |
import os
import sys
import argparse
import requests
import flask
import json
import re
import yaml
import shutil
import mmh3
from munch import Munch, munchify
from flask import render_template, redirect, url_for, send_from_directory
from markupsafe import escape
def log(*args, **kwargs):
print(*args, **kwargs, ... |
from .models import Electricity
from django.http import HttpResponse
from django.utils import timezone
from django.views.generic import View
import datetime
import json
class get_json(View):
""" Returns list of timestamp-consumption pairs. """
def get(self, request, *args, **kwargs):
time_start = tim... |
# utility packages
import os
from tqdm import tqdm
import csv
# math and support packages
from scipy import ndimage
import numpy as np
import pandas as pd
# image processing packages
import cv2
import matplotlib.pyplot as plt
import sklearn
from sklearn.model_selection import train_test_split
from random import shuff... |
# Copyright 2012-2013 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Modifications made by Cloudera are:
# Copyright (c) 2016 Cloudera, 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. A cop... |
import CollectionsManager
from UserController.UserCommand import UserCommandClass
# ==================================== UserCommandAddNewDuck Class =================================#
class UserCommandAddNewDuck(UserCommandClass):
component = None
component_index = 0
component_selected = None
... |
import numpy as np
import ctypes as C
import cv2
libmog = C.cdll.LoadLibrary('libmog2.so')
def getfg(img):
(rows, cols) = (img.shape[0], img.shape[1])
res = np.zeros(dtype=np.uint8, shape=(rows, cols))
libmog.getfg(img.shape[0], img.shape[1],
img.ctypes.data_as(C.POINTER(C.c_ubyte))... |
# coding: utf-8
"""
Camunda BPM REST API
OpenApi Spec for Camunda BPM REST API. # noqa: E501
The version of the OpenAPI document: 7.13.0
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import six
from openapi_client.configuration import Configuration
clas... |
import multiprocessing
import time
from functools import wraps
def logging_decorator(f):
@wraps(f)
def wrapper(*args, **kwds):
print('Entering decorator')
result=f(*args, **kwds)
print('Exiting decorator')
return result
return wrapper
@logging_decorator
def compute_squares(number):... |
from setuptools import setup
setup(
name='nlzss',
author='magical',
license='MIT',
packages=['nlzss']
)
|
# coding: utf-8
#!/usr/bin/python
import sys, getopt, time
import operator
import pickle
import numpy as np #for euclidean distance
import pandas as pd # to read the actual dataset
from numpy import zeros, sum as np_sum, add as np_add, concatenate, repeat as np_repeat, array, float32 as REAL, empty, ones, memmap ... |
#
# PySNMP MIB module ELTEX-MES-eltMacNotification-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ELTEX-MES-eltMacNotification-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:47:57 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Pyt... |
from abc import ABC
class AbstractDiscriminantStrategy(ABC):
def calculate_discriminant(self, a, b, c):
pass
|
# Copyright (C) 2013 eNovance SAS <licensing@enovance.com>
#
# 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 applicabl... |
import pandas as pd
import numpy as np
UTIL_SCORING = {'player':
{
'assists': 2,
'kills': 3,
'deaths': -1,
'total cs': 0.02,
# 'games_not_played': 20
},
... |
"""
Business logic for the orchestration operations.
"""
from http import HTTPStatus
import bson
import requests
from shipyard_cli.errors import StatusError
class CraneService():
"""Service for orchestration operations."""
def __init__(self, url: str, port: str):
self.base_url = url + ':' + port
... |
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 21 16:20:46 2018
@author: Arvinder Shinh
"""
import tensorflow as tf
from tensorflow import saved_model as sm
import DevnagriLipiDataGenerator
import DevnagriLipiDataVerifier
SerializedImgContainer, Labels = DevnagriLipiDataGenerator.DevnagriData()
Classfy_Inputs=tf.p... |
from . import settings
from django.conf import settings
from django.core.exceptions import ObjectDoesNotExist
if hasattr(settings, 'SALES_MODEL_FROM') and hasattr(settings, 'SALES_MODEL_IMPORT'):
User = getattr(__import__(settings.SALES_MODEL_FROM, fromlist=[settings.SALES_MODEL_IMPORT]), settings.SALES_MODEL_IMPO... |
from datetime import datetime
from unittest import TestCase
import jsons
from jsons import DeserializationError
class TestPrimitive(TestCase):
def test_dump_str(self):
self.assertEqual('some string', jsons.dump('some string'))
def test_dump_int(self):
self.assertEqual(123, jsons.dump(123))
... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2021 Tong LI <tongli.bioinfo@protonmail.com>
#
# Distributed under terms of the BSD-3 license.
"""
"""
import fire
from zarr import consolidate_metadata
from pathlib import Path
import zarr
def main(file_in):
stem = Path(file_in).st... |
# coding=utf-8
# Copyright 2018 The TensorFlow Datasets Authors.
#
# 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 appl... |
# coding: utf-8
##########################################################################
# NSAp - Copyright (C) CEA, 2019
# Distributed under the terms of the CeCILL-B license, as published by
# the CEA-CNRS-INRIA. Refer to the LICENSE file or to
# http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html
# for det... |
import codecs
import numpy as np
import copy
import time
import random
import json
import multiprocessing
import torch
import torch.nn as nn
import torch.optim as optim
from torch.autograd import Variable
import os
import joblib
entities2id = {}
relations2id = {}
relation_tph = {}
relation_hpt = {}
... |
# -*- coding: utf-8 -*-
# encoding: utf-8
# /run.py
"""
Tic-Toc-Tpe API
------------------------------------------------------------------------
App for production
------------------------------------------------------------------------
"""
import os
... |
from Tkinter import *
root = Tk()
root.title("kaki")
root.resizable(0,0)
points = []
tag = "line"
c = Canvas(root, bg="white", width=1280, height= 720)
def make_dot(x, y, xmax, ymax):
dot = c.create_oval(x, y, xmax, ymax, fill="black")
def point(event):
x = event.x - 2
y = event.y - 2
o = 4
do... |
#
# Catalog creation history:
#
# catalog creation requires one to set the RESULTS_VERS environment variable to the correct reduction
#
# DR11 catalog created using 'python make_rcsample.py -o /work/bovy/data/bovy/apogee/apogee-rc-DR11.fits --addl-logg-cut --rmdups'
# rmdups was added after the fact because this option... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.2 on 2016-09-15 09:15
from django.db import migrations, models
import django.db.models.deletion
import wagtail.core.models
class Migration(migrations.Migration):
dependencies = [
("wagtailcore", "0028_merge"),
("torchbox", "0067_auto_20160906_16... |
n=int(input('no of primes to be generated : '))
counter=0
n1=2
while True:
is_prime=True
for i in range(2,n1//2+1):
if n1%i==0:
is_prime=False
break
if is_prime==True:
print(n1)
counter=counter+1
if counter==n:
break
n1=n1+1 |
# -*- encoding: utf-8 -*-
"""Main application window
Contains :
- menubar with File, Edit
- statusbar displaying cursor position on the scene
- NodeEditorWidget instance containing a graphics view and the scene
"""
import os
import json
from PyQt5.QtWidgets import QMainWindow, QAction, QFileDialog, QLabel,... |
import dgl
import networkx as nx
# create a graph
g_nx = nx.petersen_graph()
g_dgl = dgl.DGLGraph(g_nx)
import matplotlib.pyplot as plt
plt.subplot(121)
nx.draw(g_nx, with_labels=True)
plt.subplot(122)
nx.draw(g_dgl.to_networkx(), with_labels=True)
plt.show()
# add edges and nodes into graph
import dgl
import torc... |
#!/usr/bin/env python3
import base64
import sys
from pprint import pformat
from nullroute.irc import Frame
class SaslMechanism(object):
def __init__(self):
self.step = 0
self.inbuf = b""
def do_step(self, inbuf):
return None
def feed_input(self, inbuf):
self.inbuf += inbuf... |
"""Config flow for nVent RAYCHEM SENZ."""
import logging
from homeassistant.helpers import config_entry_oauth2_flow
from .const import DOMAIN
class OAuth2FlowHandler(
config_entry_oauth2_flow.AbstractOAuth2FlowHandler, domain=DOMAIN
):
"""Config flow to handle SENZ OAuth2 authentication."""
DOMAIN = DO... |
# -*- encoding: utf-8 -*-
#
# Copyright 2012 Martin Zimmermann <info@posativ.org>. All rights reserved.
# License: BSD Style, 2 clauses -- see LICENSE.
#
# Provide a homogenous interface to Templating Engines like Jinja2
import abc
class AbstractEnvironment(object):
"""Generic interface for python templating eng... |
import pandas as pd
import torch
def get_covariates(cov_name, split):
"""
get a list of strutured covariates as a pytorch tensor
split by train/val/test
input:
- cov_name = 'Male'
- split = 'train', 'val' or 'test'
Here we're mostly interested in gender so our covaraite is male... |
# -*- coding: utf-8 -*-
"""
Defines the unit tests for the :mod:`colour.plotting.section` module.
"""
import unittest
from matplotlib.pyplot import Axes, Figure
from colour.geometry import primitive_cube
from colour.models import RGB_COLOURSPACE_sRGB, RGB_to_XYZ
from colour.plotting import (plot_visible_spectrum_sect... |
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.index, name="index"),
url(r'^dashboard$', views.dashboard, name="dashboard"),
url(r'^properties$', views.properties, name="properties"),
url(r'^add_property$', views.add_property, name="add_property"),
... |
import sys
import os
import cv2
images_path = sys.argv[1]
thumbnail_size = 300
thumbnails_path = os.path.join(images_path, "thumbnails")
event_name = os.path.basename(images_path)
if not os.path.isdir(thumbnails_path):
os.mkdir(thumbnails_path)
images = os.listdir(images_path)
yml_line = "gallery:\n"
for ind,... |
class Solution:
def bstFromPreorder(self, preorder: List[int]) -> TreeNode:
if len(preorder)==0:
return None
tn=TreeNode(preorder[0])
l=[]
r=[]
for i in preorder:
if i<preorder[0]:
l.append(i)
elif i>preorder[0]:
... |
from onboarding_project.celery import app
from squad_pantry_app.models import PerformanceMetrics
@app.task
def calc_performance_metrics():
PerformanceMetrics.create_avg_performance_metrics()
|
""" Creates components from JSON files. This provides an easy
way for adding custom components without mucking around with blenders
API. Of course, for more advanced tools it is necessary to create
more complex UI's, but if you just want a component with a couple twiddleable
numbers, bools and vecs, a JSON component ca... |
#!/usr/bin/env python3
import os
import re
import sys
import errno
import subprocess
import json
import glob
IMPORTPREFIX="github.com/kentik/"
REPOROOT=os.path.basename(os.getcwd())
SRCDIR="staging"
TGTDIR="proto_go"
PACKAGE="^(package .*);"
#
# Attributes pertinent to building the go code to serve proto types
# f... |
#!/usr/bin/env python3
import sys
import time
import automationhat
time.sleep(0.1) # Short pause after ads1015 class creation recommended
try:
from PIL import Image, ImageFont, ImageDraw
except ImportError:
print("""This example requires PIL.
Install with: sudo apt install python{v}-pil
""".format(v="" if sy... |
"""Application credentials platform for the Honeywell Lyric integration."""
from homeassistant.components.application_credentials import (
AuthorizationServer,
ClientCredential,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers import config_entry_oauth2_flow
from .api import LyricLoca... |
import tensorflow as tf
from tensorflow import keras
from tensorflow.compat.v1 import ConfigProto
from tensorflow.compat.v1 import InteractiveSession
from tensorflow.keras.layers import Input, Lambda, Dense, Flatten
from tensorflow.keras.models import Model
from tensorflow.keras.applications.inception_resnet_v2 import ... |
from django.test import TestCase
from ..models import Tag, Medium
from ..management.commands.add_tag_to_media import AssignTag
class RenameTagTest(TestCase):
fixtures = ['test_basic_data.yaml']
def setUp(self):
pass
def tearDown(self):
pass
def test_assign_tag_to_one_file(self):
... |
r"""
``$ mwtext preprocess_text -h``
::
Converts MediaWiki XML dumps to plaintext. One line per text chunk with
wiki markup and punctuation cleaned up. This utility is designed with word
embeddings in mind. Generally, you can expect one line per paragraph.
Usage:
preprocess_text (-h|--help)... |
# -*- coding: utf-8 -*-
# Transformers installation
import numpy as np
from transformers import GPT2LMHeadModel, GPT2TokenizerFast
from qtorch.quant import posit_quantize, float_quantize, configurable_table_quantize
device = 'cuda'
model_id = 'gpt2-large'
tokenizer = GPT2TokenizerFast.from_pretrained(model_id)
fro... |
# coding=utf-8
import tensorflow as tf
from tensorflow.python.ops import variable_scope
import numpy as np
import sys
import os
sys.path.append('..')
from tensor2tensor.models import transformer
from tensor2tensor.layers import common_layers
from tensor2tensor.utils import trainer_lib
from tensor2tensor.utils import r... |
#!/bin/python
import listify_circuits
listify_circuits.optimize_circuits(48, 'forward') |
"""
Register Me Silly
Repeatedly checks Drexel's Term Master Schedule for availability of class sections
Author: Anshul Kharbanda
Created: 9 - 21 - 2018
"""
from . import LabeledInput
from tkinter import *
class LabeledSpinbox(LabeledInput):
"""
Docstring for LabeledSpinbox
"""
def __init__(self, ma... |
#Detector Functions
# ------------------ Importing Libraries ------------------ #
import cv2
import os
import time
# ------------------ Importing Functions ------------------ #
from utils import open_thresholds, get_audio_list, reshape_image, input_output_details, make_prediction, get_dist_values, play_audio_record... |
"""
Xero Accounts API
"""
from .api_base import ApiBase
class Accounts(ApiBase):
"""
Class for Accounts API
"""
GET_ACCOUNTS = '/api.xro/2.0/accounts'
def get_all(self):
"""
Get all accounts
Returns:
List of all accounts
"""
return self._get... |
"""Defines a Tornado Server that consumes Kafka Event data for display"""
import logging
import logging.config
from pathlib import Path
import tornado.ioloop
import tornado.template
import tornado.web
# Import logging before models to ensure configuration is picked up
logging.config.fileConfig(f"{Path(__file__).paren... |
link_template="""\
<ul>
<li><a href="{langfam_code:}/overview/introduction.html">Introduction</a></li>
<li><a href="{langfam_code:}/overview/tokenization.html">Tokenization</a></li>
<li>Morphology
<ul>
<li><a href="{langfam_code:}/overview/morphology.html">General principles</a></... |
import tensorflow as tf
hello =tf.constant('hello')
sess=tf.Session()
print(sess.run(hello)) |
import os, numpy, sys
from numpy.linalg import norm
import isambard_dev
def get_SHparams(protein):
sequence = protein[0].sequence
residue_ids = [protein[0][i].id for i in range(len(protein[0].sequence))]
reference_axis = isambard_dev.analyse_protein.reference_axis_from_chains(protein)
residue_code = [sequence[n... |
# coding=utf-8
import toml
class Config(object):
def __init__(self, config_file_name):
dictionary = toml.load(config_file_name)
mqtt = Config.get_value_or_default(dictionary, "mqtt")
self.broker_address = Config.get_value_or_default(mqtt, "broker_address")
csv = Config.get_value_... |
#! /usr/bin/env python
import argparse
import itertools
import cv2
import numpy as np
if __name__=='__main__':
parser = argparse.ArgumentParser(
description='Arrange a number of images as a matrix.')
parser.add_argument('f', help='Output filename.')
parser.add_argument('w', type=int,
... |
#!/usr/bin/env python
import rospy
import numpy as np
from sensor_msgs.msg import Image, CompressedImage
import cv2
from cv_bridge import CvBridge, CvBridgeError
bridge = CvBridge()
image_pub = rospy.Publisher("output",Image,queue_size=1)
def callback(original_image):
np_arr = np.fromstring(original_image.data, ... |
import sys
filename=sys.argv[1]
def tableHTMLtoMatrix(filename):
file=open(filename,"r")
for i in range (2):
file.readline()
all_lines=file.readline().split("</td></tr></tbody></table></td></tr></thead>")
entries=all_lines[1].split('<tr align="center">')
dict,Enodes={},[]
for entry in entries[1:]:
entry=entry... |
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import matplotlib.colors as col
import math
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
#import string
INTP_METHODS = ["bilinear", "bicubic"]
COLOR_SPECTRUMS = ["rainbow", "gray", "BuGn"]
FILE_NAMES = [ "aug_6_temp","Aug-2016... |
from brownie import accounts, web3, Wei, reverts, chain
from brownie.network.transaction import TransactionReceipt
from brownie.convert import to_address
import pytest
from brownie import Contract
from settings import *
# reset the chain after every test case
@pytest.fixture(autouse=True)
def isolation(fn_isolation):
... |
from __future__ import annotations
import re
from librespot.common import Utils
from librespot.metadata import SpotifyId
from librespot.metadata.PlayableId import PlayableId
class TrackId(PlayableId, SpotifyId):
_PATTERN = re.compile("spotify:track:(.{22})")
_hexId: str
def __init__(self, hex_id: str):... |
import torch
import numpy as np
from models_repo.massive_resnets import *
from models_repo.tiny_resnets import *
from models_repo.Middle_Logit_Generator import *
import argparse
from train_funcs import train_regular_ce,\
train_regular_middle_logits,\
train_kd_or_fitnets_2,\
stage_1_fitnet_train,\
dml_tr... |
from nlgen.cfg import read_cfg
EXAMPLE_NO_FEATURE = """
# example.nlcfg
SENTENCE -> PRONOUN VI NOUN;
VI -> VERB;
PRONOUN -> "I";
VERB -> "play";
NOUN -> "blackjack" | "poker";
""".strip()
def test_no_feature_example():
cfg = read_cfg(EXAMPLE_NO_FEATURE)
# permutations returns a generator.
# we use sets f... |
from typing import Optional
from pydantic import BaseModel, Field
class UserModel(BaseModel):
name: str = Field(...)
user_id: str = Field(...)
password: str = Field(...)
email: str = Field(...)
is_admin: bool = Field(...)
en_date: str = Field(...)
de_date: str = Field(...)
birth_date:... |
"""
Misc lr helper
"""
from torch.optim import Adam, Adamax
from .adamw import AdamW
def build_optimizer(model, opts):
param_optimizer = list(model.named_parameters())
no_decay = ['bias', 'LayerNorm.bias', 'LayerNorm.weight']
optimizer_grouped_parameters = [
{'params': [p for n, p in param_optimi... |
# Generated by Django 3.0.5 on 2020-04-07 16:08
import django.core.validators
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('django_products', '0001_initial'),
]
operations = [
migra... |
import aiodocker
async def get_docker_images():
docker = aiodocker.Docker()
print("== Images ==")
for image in await docker.images.list():
tags = image["RepoTags"][0] if image["RepoTags"] else ""
print(image["Id"], tags)
async def pull(name: str):
docker = aiodocker.Docker()
awai... |
from train import d_conv_dim, g_conv_dim, z_size, model_name, img_size
import torch
import pickle as pkl
import matplotlib.pyplot as plt
import numpy as np
from train_class.load_model import Discriminator, Generator
from train_class.load_model import build_network
import torch.nn.functional as F
# load pretrained mod... |
import numpy as np
from core import Cache
from core import scipy_diffev
from core import notification
from core import preset
from core import track_and_update_metric
from visualization import display_iterations
def diffev_function_test(w, *args):
cache = args[0]
cache.w = w
residual = 0
for x, y in ... |
from stockpyle._base import BaseDictionaryStore
class ShoveStore(BaseDictionaryStore):
"""Represents a store that places all objects in a Shove (see http://pypi.python.org/pypi/shove)"""
def __init__(self, shove=None, shoveuri=None, polymorphic=False, lifetime_cb=None):
# TODO: deprecate 'sho... |
# 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 (the
# "License"); you may not u... |
##########################################################
### Import Necessary Modules
import argparse #provides options at the command line
import sys #take command line arguments and uses it in the script
import gzip #allows gzipped files to be read
... |
# from .__S3File import s3_set_profile as set_profile
from .__S3File import s3_xlist as xlist
from .__S3File import s3_download as download
from .__S3File import s3_upload as upload
from .__S3File import s3_load as load
from .__S3File import s3_save as save
from .__S3File import s3_open as open
from .__S3File import s3... |
# Copyright 2017, 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 required by applicable l... |
import numpy as np
from scipy.integrate import solve_ivp
import matplotlib.pyplot as plt
class SEIRModelAge:
"""
This class implements a SEIR-like compartmental epidemic model
consisting of SEIR states plus death, and hospitalizations and age
structure.
In the diff eq modeling, these parameters a... |
#!/usr/bin/env python
from dissect.cstruct import cstruct, dumpstruct
import socket
import struct
protocol = cstruct()
protocol.load("""
enum AttackType : uint8 {
ATK_OPT_DPORT = 7,
ATK_OPT_DOMAIN = 8,
ATK_OPT_NUM_SOCKETS = 24,
};
struct AttackTarget {
DWORD ipv4;
BYTE netmask;
};
stru... |
from celery import task
import re
from django.utils import timezone
from backups.models import Backup, BackupRun, BackupSetOfRun, BackupNotification
import os
from django.conf import settings
from app.utils import DjangoLock
@task(ignore_result=True, queue="backups")
def run_backup(id, mode='hourly', backupsetpk=... |
import logging
from dicewars.client.ai_driver import BattleCommand, EndTurnCommand
class AI:
def __init__(self, player_name, board, players_order):
self.player_name = player_name
self.logger = logging.getLogger('AI')
def ai_turn(self, board, nb_moves_this_turn, nb_turns_this_game, time_left)... |
import random
from typing import List
from project.conf import get_configuration
from project.utils import ITEMS_SECTION
from project.effect import SideEffect, instantiate_side_effects
from project.interface import IItem, IHealingItem, IRecoveryItem, IEquipmentItem, ISideEffect
class Item(IItem):
def __init__(se... |
import RPi.GPIO as GPIO
import time
from libdw import pyrebase
#Database Set-Up
projectid = "cleanbean-9e2f5"
dburl = "https://" + projectid + ".firebaseio.com"
authdomain = projectid + ".firebaseapp.com"
apikey = "AIzaSyA6H-rDpfGJZcTqFhf69t3VYbbOzfUW0EM"
email = "kenzho_lim@mymail.sutd.edu.sg"
password = "123456"
c... |
"""Metaclass that overrides creating a new pipeline by wrapping methods with validators and setters."""
from functools import wraps
from rayml.exceptions import PipelineNotYetFittedError
from rayml.utils.base_meta import BaseMeta
class PipelineBaseMeta(BaseMeta):
"""Metaclass that overrides creating a new pipeli... |
from setuptools import setup
import glob
import os
import sys
import json
def package_files(package_dir, subdirectory):
# walk the input package_dir/subdirectory
# return a package_data list
paths = []
directory = os.path.join(package_dir, subdirectory)
for (path, directories, filenames) in os.walk... |
""" Advent of Code Day 2 - Bathroom Security"""
def get_code(start_pos, keypad, valid_pos):
"""Returns the code generated from instructions on specified keypad."""
pos = start_pos
code = ''
for line in lines:
for move in line:
if move == 'R':
next_pos = [pos[0], pos... |
import chanutils.reddit
from chanutils import get_json
from playitem import PlayItem, PlayItemList
_SEARCH_URL = "https://www.googleapis.com/youtube/v3/search"
_FEEDLIST = [
{'title':'Trending', 'url':'http://www.reddit.com/domain/youtube.com/top/.json'},
{'title':'Popular', 'url':'https://www.googleapis.com/yout... |
"""
Demo for chunk extraction in pyClarion.
Prerequisite: Understanding of the basics of pyClarion as discussed in the demo
`free_association.py`.
"""
from pyClarion import (
Structure, Construct,
agent, subsystem, buffer, flow_bt, flow_tb, features, chunks, terminus,
feature, updater,
Chunks, Asset... |
import numpy
from pylab import *
from scipy.interpolate import interp1d
d1,e1,ee1,f1,ef1=numpy.loadtxt("full.txt",unpack=True)
f1=-f1*31.6e-15
inds=argsort(d1)
d1=d1[inds]
f1=f1[inds]
d2,e2,ee2,f2,ef2=numpy.loadtxt("PEC.txt",unpack=True)
f2=-f2*31.6e-15
inds=argsort(d2)
d2=d2[inds]
f2=f2[inds]
d3,e3,ee3,f3,ef3=numpy... |
# _*_ coding:utf-8 _*_
# 练习函数调用。
def hello(name):
print "hello",name
pass
def manyHello():
for i in ["a","bobo","green"]:
hello(i)
pass
manyHello() |
from comex_stat.assets.models import (CGCE, CUCI, NCM, SH, AssetExportFacts,
AssetImportFacts, Country,
FederativeUnit, TradeBlocs,
Transportation, Urf)
from graphene_django.filter.fields import DjangoFilte... |
import numpy as np
import pandas as pd
np.random.seed(101)
df = pd.DataFrame(np.random.randn(5, 4), index='A B C D E'.split(), columns='W X Y Z'. split())
print(df)
print(df[['W', 'Z']])
df['new'] = df['W'] + df['X']
print(df)
print(df.loc['A', 'X'])
print(df.loc['A'])
|
# coding: utf-8
"""
Prisma Cloud Compute API
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
The version of the OpenAPI document: 21.04.439
Generated by: https://openapi-generator.tech
"""
from __future__ import absolute_impor... |
import boto3
def post_handler(event, context):
sns= boto3.client('sns')
response = sns.publish(
TopicArn='arn:aws:sns:eu-west-1:538353771716:mytopic',
Message='testinglambda'
)
return{
"message" : "successful"
}
|
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
# Copyright © Spyder Project Contributors
#
# Licensed under the terms of the MIT License
# (see spyder/__init__.py for details)
# -----------------------------------------------------------------------------
"""Test... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.