content stringlengths 5 1.05M |
|---|
from datetime import datetime
import os
import subprocess
from pathlib import Path
FILE_SUFFIX = datetime.today().strftime('%Y%m%d')
home = str(Path.home())
root = os.path.join(home, "Desktop")
for subdir in [x[0] for x in os.walk(root)]:
# master = os.path.join(subdir, "macro-output", "master.mp3")
master = o... |
import Quandl
import pandas as pd
import pickle
import matplotlib.pyplot as plt
from matplotlib import style
style.use('fivethirtyeight')
# Not necessary, I just do this so I do not show my API key.
api_key = open('quandlapikey.txt','r').read()
def state_list():
fiddy_states = pd.read_html('https://simple.wikip... |
# For installation: "python setup.py install"
from distutils.core import setup, Extension
# Nombre del módulo y archivos que contienen el código fuente.
module1 = Extension("optimcore",
define_macros=[('MAJOR_VERSION', '0'),
('MINOR_VERSION', '1')],
... |
# Time: O(n)
# Space: O(1)
class Solution(object):
def twoSum(self, nums, target):
start, end = 0, len(nums) - 1
while start != end:
sum = nums[start] + nums[end]
if sum > target:
end -= 1
elif sum < target:
start += 1
... |
import os
import sys
import re
from time import sleep
import time
import random
from microMolder import LambdaMolder
from microFront import CloudFrontMolder
from microGateway import ApiGatewayMolder
from microDynamo import DynamoMolder
from microUtils import loadConfig, roleCleaner, serviceID
from MMAnsibleDeployAll i... |
from model import common
import torch
import torch.nn as nn
class ClipL1(nn.Module):
def __init__(self, clip_min=0.0, clip_max=10.0):
super(ClipL1, self).__init__()
self.clip_max = clip_max
self.clip_min = clip_min
def forward(self, sr, hr):
loss = torch.mean(torch.clamp(torch.... |
from util.credentials.credentials_provider import CredentialsProviderFactory
from util.app_util import AppUtil
from util.grant_util import GrantUtil
from util.credential_test_util import CredentialsTestUtil
from util.role_util import RoleUtil
from util.keyvault_util import KeyVaultUtil
from util.validator_util import V... |
"""
Make a movie out of a shotgun VAE projection and an audio file.
"""
__date__ = "Novemeber 2019"
import matplotlib.pyplot as plt
plt.switch_backend('agg')
import numpy as np
import os
from scipy.io import wavfile
from scipy.spatial.distance import euclidean
import torch
from torch.utils.data import Dataset, DataL... |
from django.contrib import admin
from .models import School, Department, Course
admin.site.register(School)
admin.site.register(Department)
admin.site.register(Course)
|
from .. import Provider as AutomotiveProvider
class Provider(AutomotiveProvider):
"""Implement automotive provider for ``pt_BR`` locale."""
license_formats = ("???-####",)
|
def train_model(model, X_train, Y_train, callback_list, **params):
train_epochs = params.get("train_epochs")
batch_size = params.get("batch_size")
val_split = params.get("val_split")
model_verbose = params.get("model_verbose")
embedding_type = params.get("embedding_type")
print("training neural network...")
m... |
import numpy as np
import torch
from torch import nn
# DATASET and DATALOADER
class myDataset(torch.utils.data.Dataset):
def __init__(self, data, lat_samples, transform=None):
self.data = data
self.lat_samples = lat_samples
self.transform = transform
def __len__(self):
return ... |
# pylint: disable=missing-docstring
"""Test the plt fixture."""
import numpy as np
def test_rectification(plt):
"""The test shown in the documentation.
Included here to be extra sure that the example works when copy-pasted
into a user's tests, and to easily generate the plot that we display
in docu... |
from uuid import uuid4
from django.core.exceptions import ObjectDoesNotExist
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
from rest_framework_simplejwt.state import token_backe... |
# -*- coding: utf-8 -*-
# Copyright (c) 2022 Ricardo Bartels. All rights reserved.
#
# wordpress-hash-event-api
#
# This work is licensed under the terms of the MIT license.
# For a copy, see file LICENSE.txt included in this
# repository or visit: <https://opensource.org/licenses/MIT>.
from typing import Tuple
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Author: illuz <iilluzen[at]gmail.com>
# File: AC_recursive_n.py
# Create Date: 2015-04-05 09:22:43
# Usage: AC_recursive_n.py
# Descripton:
# Definition for a binary tree node
class TreeNode:
def __init__(self, x):
self.val = x
self.l... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import paho.mqtt.client as mqtt
import json
import time
class mqttpublisher():
def __init__(self):
self.client = mqtt.Client()
self.client.connect("mqtt.realraum.at", 1883, 60)
def send(self, structname, datadict):
self.client.publish(st... |
import concurrent.futures
from auto_surprise.constants import (EVALS_MULTIPLIER, MAX_WORKERS)
from auto_surprise.trainer import Trainer
from auto_surprise.strategies.base import StrategyBase
class BasicReduction(StrategyBase):
"""
A basic strategy for comparison of algorithms
"""
def evaluate(self):
... |
"""The schema for the condensation application data layer.
There are several attributes and several miscelaneous constraints.
There is a brief synopsis for each entity in the documentation, however
for up to date a specific details about constraints read the code """
from datetime import datetime
from dateutil i... |
from torch.autograd import Variable
import torch
from torch.nn.modules.module import Module
from torch.nn.modules.container import Sequential
from torch.nn.modules.activation import LogSoftmax
from torch.nn import functional as F
def _assert_no_grad(variable):
assert not variable.requires_grad, \
"nn crit... |
import sys
sum = 0
def get_stats(values, sum):
if len(values) == 0:
print ("All zeros")
return
values.sort()
mean = sum / len(values)
median = values[len(values)//2]
mode_d = {}
for x in values:
mode_d[x] = mode_d.get(x, 0) + 1
mode = max(mode_d.values())
print (values)
print (f"Mean is ... |
import pandas
# create a list of 100000 pairs with values (i,i) then output pairs as 'rising_limbo.csv'
pairs = [(i, i) for i in range(100_000)]
pandas.DataFrame(pairs).to_csv('rising_limbo.csv', header=False, index=False)
|
from .rpc.request import (
rpc_request
)
_default_endpoint = 'http://localhost:9500'
_default_timeout = 30
#########################
# Transaction Pool RPCs #
#########################
def get_pending_transactions(endpoint=_default_endpoint, timeout=_default_timeout) -> list:
"""
Get list of pending tra... |
# Copyright 2020 The TensorFlow Probability 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 applicable law o... |
import functools
from .abi import ( # noqa: F401
abi_middleware,
)
from .attrdict import ( # noqa: F401
attrdict_middleware,
)
from .cache import ( # noqa: F401
_latest_block_based_cache_middleware as latest_block_based_cache_middleware,
_simple_cache_middleware as simple_cache_middleware,
_time... |
import string
import nltk
import textblob as textblob
from nltk import word_tokenize, pos_tag, ne_chunk, tree2conlltags
from nltk.corpus import stopwords
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
from sklearn.preprocessing import MinMaxScaler
from constants import emoticons
from feat... |
from ..helpers.dom_type import DomType
from ..errors.invalid_dom_type import InvalidDomTypeError
class TestCaseStep:
def __init__(self, dom_type, selector, validate_type, validation_value, action, action_input):
self.dom_type = dom_type
self.selector = selector
self.validate_type = validat... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import re, time
import logging
import base64, hashlib
import binascii, textwrap, json, copy
from subprocess import Popen, PIPE
try: from urllib.request import urlopen # Python 3
except ImportError: from urllib2 import urlopen # Python 2
LOGGER = logging.getLogger(_... |
import datetime
import time
import math
from collections import defaultdict, Counter
from operator import itemgetter
from xml.etree import ElementTree
from sqlalchemy import desc
from config import CONFIG
from db import db
from models import Player, Record, Listing, Alliance
from pixelstarshipsapi import PixelStarshi... |
# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
setup(
name = "yolo4keras",
version = "0.1.0",
url = "https://github.com/Kajiyu/yolo4keras",
description = "Yolo implementation for Keras",
author = "Kaji",
license = 'MIT',
classifiers = [
'Intended Audience :: Inf... |
# -*- coding: utf-8 -*-
# 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, softw... |
bl_info = {
"name": "Unitize Mesh",
"author": "Dennis",
"description": "Scales a mesh's geometry such that it fits in a unit cube around the origin.",
"blender": (2, 81, 0),
"category": "Object",
}
import bpy
import math
class Unitize(bpy.types.Operator):
"""Scales a mesh's geometry such that... |
# -*- encoding: utf-8 -*-
#
# Copyright © 2014-2015 eNovance
#
# 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 applica... |
"""
===================================================
Analysis Tools (:mod:`pchangetools.analysis_tools`)
===================================================
.. currentmodule:: pchangetools.analysis_tools
Tools for generating graphics for teaching computational thinking from
ECMWF reanalysis data. Initial work by S... |
"""BOM additional fields on station and observation
Revision ID: 28a206c84987
Revises: 659f03439631
Create Date: 2020-10-09 05:12:59.186661
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = "28a206c84987"
down_revision = "659f03439631"
branch_labels = None
depends... |
"""Configuration Module provides a dictionary-like with configuration settings.
It also sets up the logging.
* The ``LEGA_LOG`` environment variable is used to configure where the logs go.
Without it, there is no logging capabilities.
Its content can be a path to an ``INI`` or ``YAML`` format, or a string
repre... |
#ruamel may create environment conflicts, proceed with caution:
# pip install --user 'ruamel.yaml<0.16,>0.15.95' --no-deps
import ruamel.yaml as yaml
def load_yaml_cards(sample_cards):
SampleList = None
SampleDict = dict()
try:
import ruamel.yaml
ruamel.yaml.preserve_quotes = True
except... |
import vtk
from vtk import *
import string
import sys
f = open(sys.argv[1],'r')
outfile = sys.argv[2]
l = f.readline()
tokens = string.split(string.strip(l),' ')
Nnodes = int(tokens[0])
Nelts = int(tokens[1])
Points = vtk.vtkPoints()
print 'Reading',Nnodes,'nodes...',
for i in range(Nnodes):
d = string.split(s... |
# -*- coding: utf-8 -*-
def cypher(message):
cyphered = []
for letter in message:
binary = bin(ord(letter))
cyphered.append(binary)
return''.join(cyphered)
def decypher(message):
chars = message.split('0b')
chars.pop(0)
decyphered = []
for char in chars:
... |
# type: ignore
import pytest
import datetime
from sqlalchemy import create_engine
from sqlalchemy.types import Integer, String, DateTime
from sqlalchemy.schema import Column, ForeignKey
from sqlalchemy.orm import relationship, sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy_oso i... |
from db import db, User
def get_user_by_email(email):
return User.query.filter(User.email == email).first()
def get_user_by_session_token(session_token):
return User.query.filter(User.session_token == session_token).first()
def get_user_by_update_token(update_token):
return User.query.filter(User.update_... |
import pandas as pd
fp = 'hospital_100.csv'
df = pd.read_csv(fp, index_col=False)
df_clean = df.drop(columns=['Address2','Address3', 'State','HospitalType','HospitalOwner',
'EmergencyService','Condition','MeasureCode','MeasureName',
'Score','Sample','Stateavg'])
m... |
# models.py
import datetime
import traceback
from flask import current_app
from invenio_accounts.models import User
from invenio_db import db
from sqlalchemy import ARRAY
from sqlalchemy.dialects.postgresql import JSONB
from base32_lib import base32
from sqlalchemy.orm import relationship
from sqlalchemy_utils import ... |
# This file is part of Happypanda.
# Happypanda is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 2 of the License, or
# any later version.
# Happypanda is distributed in the hope that it will be... |
from django.conf import settings
from django.conf.urls.static import static
from django.urls import path, re_path,include
from django.contrib.auth import views
from rest_framework.routers import DefaultRouter, SimpleRouter
from mpesa.api.views import MakeC2BPayment, MakeLNMPayment
router = SimpleRouter()
router.regist... |
import numpy as np
from functools import partial
from bokeh.layouts import column, row, layout
from bokeh.models import ColumnDataSource, Slider, Button
from bokeh.themes import Theme
from bokeh.io import show
from bokeh.plotting import figure, output_file, Column
from bokeh.models import DataTable, TableColumn, Poin... |
def str2bool(s):
if s.lower() == "true":
return True
elif s.lower() == "false":
return False
else:
raise BooleanConversionException("can not convert %s to boolean" % s)
class BooleanConversionException(Exception):
pass
|
from matplotlib import pyplot as plt
source_data = 'day7/input.txt'
with open(source_data, 'r') as f:
initial_state = [x.replace('\n', '').split(',') for x in f.readlines()]
initial_list = [int(item) for sublist in initial_state for item in sublist]
initial_state = {x:0 for x in range(max(initial_list) + 1)}
... |
#
# The Python Imaging Library.
# $Id$
#
# GD file handling
#
# History:
# 1996-04-12 fl Created
#
# Copyright (c) 1997 by Secret Labs AB.
# Copyright (c) 1996 by Fredrik Lundh.
#
# See the README file for information on usage and redistribution.
#
# NOTE: This format cannot be automatically recogni... |
import logging
from rest_framework import status
from rest_framework import permissions
from rest_framework import renderers as rf_renderers
from rest_framework.decorators import api_view
from rest_framework.decorators import permission_classes
from rest_framework.decorators import renderer_classes
from rest_framework... |
#!/usr/bin/env pnpython4
#
# Rename nodal fcnt file names to RL_S.0.x.rg16 filename format.
#
# Input: List of files to rename in a file (one per line),
# output directory for links
#
# Usage: unsimpleton list_of_files_to_link out_directory
#
# Steve Azevedo, August 2016
#
import argparse
import sys
import os
import lo... |
# This sample tests the type analyzer's handling of a variant
# of the TypedDict "alternate syntax" defined in the Python docs.
from typing import TypedDict
Movie = TypedDict("Movie", name=str, year=int)
def get_movie_name(movie: Movie):
return movie["name"]
name2 = get_movie_name({"name": "ET", "... |
#!/usr/bin/env python
#
# Public Domain 2014-2016 MongoDB, Inc.
# Public Domain 2008-2014 WiredTiger, Inc.
#
# This is free and unencumbered software released into the public domain.
#
# Anyone is free to copy, modify, publish, use, compile, sell, or
# distribute this software, either in source code form or as a compil... |
from src.server.server import Server
from src.constant import Constant
def compute_inter_sever_cost(servers): # servers is a list of server
cost = 0
for server in servers:
for node in server.graph:
if server.graph.nodes[node]['node_type'] == Constant.NON_PRIMARY_COPY or se... |
banner = """
██╗ ██╗██╗███████╗██████╗
██║ ██║██║██╔════╝██╔══██╗
██║ █╗ ██║██║███████╗██████╔╝
██║███╗██║██║╚════██║██╔═══╝
╚███╔███╔╝██║███████║██║
╚══╝╚══╝ ╚═╝╚══════╝╚═╝ 0.0.1-beta
JIMUT(TM)
"""
print(banner) |
#!/usr/bin/env python
import argparse
import configparser
import datetime
from decimal import Decimal
import json
import sys
import time
import os
import cbpro
import requests
# TODO implement allowlist to only allow requests to coinbase and pushover domains
try:
import http.client as http_client
except ImportEr... |
#!/usr/bin/python
# -*- coding: cp1252 -*-
import easygui
"""
__version__ = "$Revision: 1.3 $"
__date__ = "$Date: 2004/04/14 02:38:47 $"
"""
from PythonCard import model
class MyBackground(model.Background):
def on_initialize(self, event):
# if you have any initialization
# including sizer setup,... |
"""
Downloading the original DES images (10000 * 10000 pixels).
These images are the into 100*100 pixels are cut, using random x, y coordinates, these images are
known as background sky/noise. The original images are clipped using the World Coordinate System,
and are 100*100 pixels in size around stellar/astronomical... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
__title__ = 'semi_simple'
__author__ = 'JieYuan'
__mtime__ = '19-1-11'
"""
import numpy as np
import pandas as pd
from tql.pipe import tqdm, cprint
class SimpleSemi(object):
def __init__(self, clf, subsample=0.05, n_iter=1, scale_pos=1, mode=None, opt_seed=None):... |
from ._version import __version__
from .layer import register_carto_layer
from .credentials import load_carto_credentials
__all__ = ["__version__", "load_carto_credentials", "register_carto_layer"]
|
# This module can load passwords from external sources, such as files or
# environment variables or KWallet (and no, *not* libsecret -- as much as I
# want to use the nifty gi-based libsecret API...).
#
# It deals with strings (the lowest common denominator), but it's really meant
# to be used for storing Base64-encode... |
# reference: Liu, Y. and Durlofsky, L.J., 2020. 3D CNN-PCA: A Deep-Learning-Based. Parameterization for Complex Geomodels. arXiv preprint arXiv:2007.08478
import numpy as np
import matplotlib.pyplot as plt
class PCA(object):
def __init__(self, nc=1, nr=1, l=1):
self.l = l
self.nc = nc
self... |
from chainercv.evaluations.eval_detection_voc import calc_detection_voc_ap # NOQA
from chainercv.evaluations.eval_detection_voc import calc_detection_voc_prec_rec # NOQA
from chainercv.evaluations.eval_detection_voc import eval_detection_voc # NOQA
from chainercv.evaluations.eval_instance_segmentation_voc import cal... |
class ListNode:
def __init__(self, val = 0, next = None):
self.val = val
self.next = next
class Solution:
def removeElements(self, head, val):
dummy = ListNode(0)
dummy.next = head
prev, curr = dummy, dummy.next
while curr:
if curr.val == val:
... |
from .entfunc import *
import pytest
ADMIN_PASSWORD = os.environ.get('ADMIN_PASSWORD', "None")
TEST_RANCHER_GKE_SERVER_IP = os.environ.get('RANCHER_GKE_SERVER_IP', "None")
RKE_K8S_VERSION = os.environ.get('RANCHER_RKE_K8S_VERSION', "v1.15.5-rancher1-1")
RANCHER_SERVER_URL = "https://" + TEST_RANCHER_GKE_SERVER_IP + ":... |
#!/usr/bin/env python
import argparse
import rospy
from std_msgs.msg import Int32
from geometry_msgs.msg import PoseStamped, Pose, TwistStamped
from styx_msgs.msg import TrafficLightArray, TrafficLight, Lane, Waypoint
from dbw_mkz_msgs.msg import ThrottleCmd, SteeringCmd, BrakeCmd, SteeringReport
from sensor_msgs.msg ... |
import pytest # noqa: F401
from common import login
import sys
sys.path.insert(0, './app/')
from app.models import db, Users # noqa E402
from app.tools import hash_str_with_pepper # noqa E402
def test_account_settings_password(client):
login(client)
# First test the default username (note the username hash... |
# -*- coding: utf-8 -*-
__all__ = ["TrivialSolver", "BasicSolver", "HODLRSolver"]
from .trivial import TrivialSolver
from .basic import BasicSolver
from .hodlr import HODLRSolver
|
import urllib.parse
import requests
import time
import json
import os
from bs4 import BeautifulSoup
STORE = 'momo'
MOMO_MOBILE_URL = 'http://m.momoshop.com.tw/'
MOMO_QUERY_URL = MOMO_MOBILE_URL + 'mosearch/%s.html'
USER_AGENT_VALUE = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_5) AppleWebKit/537.36 (KHTML, like Gec... |
import unittest
import solution
class TestQ(unittest.TestCase):
def test_case_0(self):
dist = solution.calculate_distances(5,
[1, 1, 1, 1, 2, 3, 4],
[2, 3, 4, 5, 3, 4, 5],
[... |
from collections import defaultdict
from redash.handlers.base import BaseResource, get_object_or_404
from redash.models import AccessPermission, Query, Dashboard, User, db
from redash.permissions import require_admin_or_owner, ACCESS_TYPES
from flask import request
from flask_restful import abort
from sqlalchemy.orm.e... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import logging
import threading
import os
import sys
import traceback
try:
from multiprocessing import current_process
from multiprocessing import util as mputil
except ImportError:
current_process = mputil = None # noqa
from . import curren... |
from charrnn import CharacterRNN
|
import asyncio
from typing import Union
import discord
async def add_choices_message(message: discord.Message, num: int, cancellable: bool = False) -> list:
"""React with choice emotes to message, return them as list"""
# Only supports 10 max. stock "keycap digit" emojis
assert 0 <= num <= 10
# Ind... |
"""
Used to execute code before running tests, in this case we want to use test database.
We don't want to mess up dev database.
Put here any Pytest related code (it will be executed before `app/tests/...`)
"""
import os
os.environ["ENVIRONMENT"] = "PYTEST"
|
from django.contrib import admin
from guardian.admin import GuardedModelAdmin
from models import SearchEngine, Project, Subject
class ProjectAdmin(GuardedModelAdmin):
model = Project
class SubjectAdmin(GuardedModelAdmin):
model = Subject
class SearchEngineAdmin(admin.ModelAdmin):
model = SearchEngin... |
# In OnData(self, data)
bar = data["EURUSD"]
# Anywhere in the code
equity = self.Securities["EURUSD"] |
# save python objects as pickle object in ROOT file
from rootpyPickler import Pickler
from ShipGeoConfig import AttrDict
import ROOT,os,subprocess
def execute(f,o):
# record some basic information about version of software:
tmp = os.environ['FAIRSHIP']+'/.git/refs/remotes/origin/master'
if os.path.isfile(tm... |
def main():
# input
N = int(input())
Hs = list(map(int, input().split()))
# compute
flag = True
for i in reversed(range(N-1)):
if Hs[i]-Hs[i+1] == 1:
Hs[i] -= 1
for i in range(N-1):
if Hs[i] > Hs[i+1]:
flag = False
# output
if flag:
p... |
TCP_IP = '0.0.0.0'
TCP_PORT = 5005
BUFFER_SIZE = 1024
|
from os import environ as env
aws_access_key_id = env.get("aws_access_key_id")
aws_secret_key = env.get("aws_secret_access_key")
region_name = env.get("region_name")
|
"""We intend to make our reproduction as close as possible to the original paper.
The configuration in the file is mostly from the description in the original paper
and will be loaded when setting up."""
def dataset_based_configure(opts):
if opts['dataset'] == 'cycles':
ds_configure = cycles_configure
... |
from flask import (Blueprint, flash, jsonify, redirect, render_template,
request, url_for)
from flask_login import current_user, login_required, login_user, logout_user
from lisapi import db
from lisapi.helpers import helpers
from lisapi.models.forms import EditPin, NewPin
from lisapi.models.tables i... |
import ctypes
class Region(ctypes.Structure):
''' @class Region
@brief Class containing lattice bounds and ticks.
@details Replicates C Region class.
'''
_fields_ = [('imin', ctypes.c_uint32),
('jmin', ctypes.c_uint32),
('kmin', ctypes.c_uint32),
... |
import torch
import numpy as np
class SequenceAccuracy(object):
"""Computes accuracy between two sequences.
Inputs:
pred (N, L, C)
tgt (N, L)
ignore_index (int): index of token to mask out
"""
def __init__(self, ignore_index=-100):
self.ignore_index = ignore_index
... |
from common_fixtures import * # NOQA
from test_docker import docker_client, TEST_IMAGE_UUID, if_docker
import requests
import jwt
# work around flake8 issue
docker_client
@if_docker
def test_stats_host(docker_client, context):
host = docker_client.list_host()[0]
sim_host = context.host
assert 'stats' ... |
from PLC.Faults import *
from PLC.Method import Method
from PLC.Parameter import Parameter, Mixed
from PLC.ConfFiles import ConfFile, ConfFiles
from PLC.Nodes import Node, Nodes
from PLC.Auth import Auth
class AddConfFileToNode(Method):
"""
Adds a configuration file to the specified node. If the node is
al... |
from keras.models import Sequential
from keras.layers.core import Dense, Activation, Dropout
from keras.layers.embeddings import Embedding
from keras.layers.normalization import BatchNormalization
from keras.layers import Input, Convolution1D, GlobalMaxPooling1D, GlobalAveragePooling1D, \
Lambda, TimeDistributed, S... |
# -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/items.html
import scrapy
class LianjiaspiderItem(scrapy.Item):
# define the fields for your item here like:
# 定义爬取的信息
# 爬取房屋的所在城市
city = scrapy.Field()
# 街道... |
from datetime import datetime, timedelta
from itertools import accumulate
from typing import Iterator, NamedTuple, Tuple
from fastapi import APIRouter, Depends, Request
from fastapi.templating import Jinja2Templates
from sqlalchemy.orm.session import Session
from app.database.models import Event, User
from app.depend... |
"""
MIT License
Copyright (c) 2021 Tim Schneider
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, including without limitation the rights
to use, copy, modify, merge, publish,... |
import os
from setuptools import setup
import codenerix_storages
with open(os.path.join(os.path.dirname(__file__), 'README.rst')) as readme:
README = readme.read()
# allow setup.py to be run from any path
os.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))
setup(
name='django-code... |
#!/usr/bin/python3
import prpg
prpg.main()
|
# -*- coding: utf-8 -*-
from flask import Flask
from redis import StrictRedis
import arrow
redis_client = StrictRedis(host="192.168.0.111",
port=6380,
db=0,
decode_responses=True)
def create_app():
app = Flask(__name__)
@app.ro... |
from property.zoopla import Zoopla
from utils import db
def get_listings():
db.insert_or_replace(table_name='Listings', items=Zoopla().get_listings())
|
import torch
from tqdm import tqdm
from sklearn.metrics import roc_auc_score as auc
def train_desc(epoch, **kw):
_ = ' | '.join([f'{k.title()} = {v:.5f}' for k, v in kw.items()])
return f'Epoch {epoch+1: >2}: ' + _
def fit(model, X, y, epochs=5, batch_size=128, loss_func=torch.nn.CrossEntropyLoss()):
asse... |
"""Template methods for API."""
# Standard Python Libraries
import os
# cisagov Libraries
from dmcli.utils import api
def get_templates():
"""Get templates."""
return api.get("/api/templates/")
def template_attributes():
"""Get generated template attributes."""
return api.get("/api/templates/attrib... |
"""Data resource."""
from __future__ import absolute_import, division, print_function, unicode_literals
import json
import logging
import requests
from six.moves.urllib.parse import urljoin # pylint: disable=wrong-import-order
from resdk.constants import CHUNK_SIZE
from .base import BaseResolweResource
from .descr... |
from django.contrib import admin
class GroundtruthRecordAdminMixin(admin.ModelAdmin):
fields = ('groundtruth_target', 'actual_use', 'contact_name',
'contact_email', 'contact_phone', 'added',)
list_display = ('pk', 'groundtruth_target', 'actual_use', 'contact_name',
'contact_e... |
"""
shaa2tn.py - convert a Shaarli HTML export to a Trilium Notes
markdown.tar import.
Terry N. Brown terrynbrown@gmail.com Tue Aug 27 19:21:47 CDT 2019
"""
import argparse
import os
import random
import xml.etree.ElementTree as ET
from trilium_io import attr_template, node_template, write_tar
# used to generate Tr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.