content stringlengths 5 1.05M |
|---|
#
# PySNMP MIB module TOASTER-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TOASTER-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:23:54 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 0... |
import sys
import configparser
import RPi.GPIO as GPIO
import time
config_file = sys.argv[1]
config = configparser.ConfigParser()
config.read(config_file)
led_pin = int(config['SETTINGS']['led_pin'])
delay = float(config['SETTINGS']['delay'])
exception_sleep_time = float(config['SETTINGS']['exception_sleep_time'])
G... |
# This informs python that this is a package |
class Solution:
def leftMostColumnWithOne(self, binaryMatrix: 'BinaryMatrix') -> int:
rows, cols = binaryMatrix.dimensions()
currRow, currCol = 0, cols - 1
while currRow < rows and currCol >= 0:
if binaryMatrix.get(currRow, currCol):
currCol -= 1
... |
#-*- coding: utf-8 -*-
from django.core.exceptions import ValidationError
def validate_file_extension(value):
''' used by models.FileField '''
supported_extension = ('txt', 'doc', 'docx')
for extension in supported_extension:
if value.name.endswith(extension):
return
raise Validati... |
import unittest
import numpy
from chainer import backend
from chainer.backends import cuda
from chainer import initializers
from chainer import testing
from chainer.testing import attr
from chainer.testing import condition
@testing.parameterize(*testing.product_dict(
[
{'shape': (), 'dim_in': 1, 'dim_ou... |
class Solution:
"""
@param nums: An integer array
@return: nothing
"""
def recoverRotatedSortedArray(self, nums):
# write your code here
# nums.sort()
for i in range(len(nums)-1):
if nums[i] > nums[i+1]:
for i in range(i+1, len(nums)):
... |
# -*- coding: utf-8 -*-
# Copyright (c) 2010-2017 Tuukka Turto
#
# 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,... |
"""Module responsible for managing the trace ID sent as X-Trace-Id header and logged under the `trace_id` variable
"""
import logging
import random
import string
from contextvars import ContextVar
TRACE_ID_LENGTH = 6
X_TRACE_ID = "X-Trace-Id"
HEADER_ARG_INDEX = 4
def setup_trace_id_log_record_factory():
"""Add... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'SpacersLayout.ui'
#
# Created by: PyQt5 UI code generator 5.13.0
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
... |
import os
import re
from typing import List, Optional
import _io # type: ignore
import pretty_tables
import woodchips
from homebrew_releaser.constants import FORMULA_FOLDER, LOGGER_NAME
from homebrew_releaser.git import Git
class ReadmeUpdater:
@staticmethod
def update_readme(homebrew_tap: str):
""... |
import json
import random
import discord
from discord.ext import commands
# SEE: https://www.reddit.com/r/copypasta/comments/jai7dh/penis_synonyms/
penis_aliases = json.load(open('bot/assets/text/penis_aliases.json'))
class Fun(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.comman... |
from z3 import *
from typing import List
import pandas as pd # pip install pandas
from statistics import mean, stdev
from math import sqrt
from scipy import stats
o = Optimize() #z3 solver in optimize mode because we are using soft constraints
# Each statistical test (eg Pearson's corr) is defined by this class, w... |
# Generated by Django 2.1 on 2018-08-11 23:02
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('user_profile', '0004_auto_20180811_1901'),
]
operations = [
migrations.AddField(
model_name='socialdisplaysettings',
n... |
from csv import DictReader
from collections import defaultdict, Counter
from statistics import fmean, stdev
from os import path, makedirs, chdir
from shutil import copyfile
scriptPath = path.dirname(path.abspath(__file__))
chdir(scriptPath)
def indexOrDefault(arr, val, default):
if val in arr:
return arr.index... |
## Check the given string is scrambled or not..!!!
def solve(a: str,b : str):
## base case...!!!
if (len(a) != len(b)):
return False
if (len(a)<=1):
return False
if (len(a)==0 and len(b) == 0):
return True
## loop and extract ans from temp_ans..!!1
n = len(... |
# class Animal:
# fur_color = "Orange"
# def speak(self):
# raise NotImplementedError
# def eat(self):
# print("I am eating yum yum")
# def chase(self):
# pass
# class HouseCat(Animal):
# def speak(self):
# print("Meow")
# cat = HouseCat()
# cat.eat() # I a... |
import boto3
import os
import botocore.exceptions as botoexceptions
from hokusai import CWD
from hokusai.lib.command import command
from hokusai.lib.config import HOKUSAI_CONFIG_DIR, BUILD_YAML_FILE, TEST_YML_FILE, DEVELOPMENT_YML_FILE, config
from hokusai.services.ecr import ECR
from hokusai.services.kubectl import ... |
#%%
from datetime import datetime
import matplotlib.pyplot as plt
import neurokit2 as nk
import numpy as np
import pandas as pd
from scipy import stats
import seaborn as sns
from texttable import Texttable
import wfdb
import sys
sys.path.append("..")
from fda import *
#%%
M = pd.read_csv(data_processed + "male_ages... |
import unittest
from time import time
from unittest.mock import Mock, patch
from cache_gs.cache_classes.redis_cache import RedisCache
from cache_gs.interfaces.serialization import serialize
from tests.test_tools import raise_test_exception
class TestRedisCache(unittest.TestCase):
STRING_CONNECTION = 'redis://lo... |
default_app_config='channelaudit.apps.ChannelauditConfig' |
# stdlib
from configparser import ConfigParser
# 3rd party
import pytest
import toml
from coincidence import AdvancedDataRegressionFixture
from domdf_python_tools.paths import PathPlus
# this package
from dep_checker import AllowedUnused, ConfigReader, NameMapping, NamespacePackages
class TestIni:
@pytest.mark.pa... |
from django.template import TemplateSyntaxError
from django.test import SimpleTestCase
from ..utils import setup
class NamedEndblockTests(SimpleTestCase):
@setup({'namedendblocks01': '1{% block first %}_{% block second %}'
'2{% endblock second %}_{% endblock first %}3'})
def ... |
#!/usr/bin/env python
"""
Alexa skill that queries the 511.org service for incoming bus times in SF
"""
import logging
import os
from aws_xray_sdk.ext.flask.middleware import XRayMiddleware
from aws_xray_sdk.core import patcher, xray_recorder
import boto3
from boto3.dynamodb.conditions import Key
from fiveoneone.st... |
import numpy as np
import functools
from .debug import dprint
####################################################################################################
####################################################################################################
class ValidationException(Exception): pass
########... |
# -*- coding: utf-8 -*-
# Copyright 2019 Cohesity Inc.
import logging
from cohesity_management_sdk.api_helper import APIHelper
from cohesity_management_sdk.configuration import Configuration
from cohesity_management_sdk.controllers.base_controller import BaseController
from cohesity_management_sdk.http.auth.auth_manag... |
# Copyright 2021 Open Source Robotics Foundation, 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... |
import numpy as np
def assert_filters_equal(m1, m2):
assert np.allclose(m1.filtered_state, m2.filtered_state)
assert np.allclose(m1.filtered_state_cov, m2.filtered_state_cov)
assert np.allclose(m1.predicted_state, m2.predicted_state)
assert np.allclose(m1.predicted_state_cov, m2.predicted_state_cov)
... |
"""baseline
Revision ID: 5bbb66a12c24
Revises:
Create Date: 2021-02-10 18:39:35.000498
"""
import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import postgresql
# revision identifiers, used by Alembic.
revision = "5bbb66a12c24"
down_revision = None
branch_labels = None
depends_on = None
def upg... |
# -*- coding: utf-8 -*-
"""
cherry.analysis
~~~~~~~~~~~~
This module implements the cherry Analysis.
:copyright: (c) 2018 by Windson Yang
:license: MIT License, see LICENSE for more details.
"""
import matplotlib.pyplot as plt
from terminaltables import AsciiTable
from .trainer import Trainer
from .classify import Re... |
from_address = ""
email_password = ""
destination = "" |
#! /usr/bin/env python3
# Table Printer Chap. 6
# Function for taking lists of strings and displays in an organized table
tableData = [['apples','oranges','cherries','bananas'],
['Alice','Bob','Carol','David'],
['dogs','cats','moose','goose']]
def printTable(dataLists):
colWidths = [0] ... |
SESSION_STORAGE = {
"asked_to_consent": [],
"initial_analysis_ran": [],
}
def user_asked_to_consent_for_project(project_path):
return project_path in SESSION_STORAGE["asked_to_consent"]
def add_project_to_asked_to_consent(project_path):
if user_asked_to_consent_for_project(project_path):
ret... |
# capture only luminescence
import time
import picamera
import picamera.array
import numpy as np
with picamera.PiCamera() as camera:
camera.resolution = (100, 100)
time.sleep(2)
y_data = np.empty((112, 128), dtype=np.uint8)
try:
camera.capture(y_data, 'yuv')
except IOError:
pass
... |
import unittest
from alfred_client.message import MetaMessage, Message, MessageTypeId
expected_bytes = b'\x00\x00\x00\x17\x00\x00\x00\x00r\x00\x01\x93\x9c`\x00\x00\x00\x03foo' # noqa
@MessageTypeId(99)
class MockMessage(Message):
def __init__(self):
super().__init__()
class TestMetaMessage(unittest.T... |
from JumpScale import j
import struct
import os
import time
class GridAgent:
def __init__(self, path="", key="", name="", nsid=0, epoch=0, stat="", bindata=None, changelog=[]):
if bindata <> None:
self.unserialize(bindata, changelog)
else:
self.path = path
self... |
from .serializer import StackSearchapi
from django.http import JsonResponse
import requests
import requests_cache
import json
from ratelimit.decorators import ratelimit
from django.core.paginator import Paginator
import datetime
requests_cache.install_cache('stackapi_cache', backend='sqlite', expire_after=180)
@ratel... |
# The using GPU ID
gpu = '0' # '0,1,2,3'
finetune = False # False True
resume = False # False True
resume_path = './ckpt/saved_models/20.pth'
### TRAINING PARAMETERS ###
max_epoch = 30
batch_size = 10
val_batch = 4
data_shape = [128, 128*5]
### LOSS PARAMETERS ###
dice_coef = 10.0
valid_coef = 1.0
hole_coef = 6.0
... |
import numpy as np
import torch
from torch.utils.data import Dataset
class BookDataset(Dataset):
def __init__(self, datafile, embeddings, win_size, device='cpu'):
"""Loads features and labels from '.npz' file"""
super(Dataset, self).__init__()
self.win_size = win_size
self.device =... |
"""Test `demo.py` files in model dirs."""
from importlib import import_module
import matplotlib as mpl
import pytest
from matplotlib import pyplot as plt
import dapper as dpr
mpl.use("Qt5Agg")
plt.ion()
@pytest.mark.parametrize(("path"), dpr._find_demos())
def test_imp(path):
import_module(path)
assert Tr... |
import pandas as pd
import numpy as np
from sklearn.impute import SimpleImputer
from sklearn.preprocessing import StandardScaler
# import the data
hec_data = pd.read_csv("../phl_exoplanet_catalog.csv")
exos=pd.read_csv('../exoplanets.csv')
# remove unconfirmed planets
hec_data = hec_data[hec_data.P_STATUS == 3].drop(... |
__doc__ = "a module housing posterior functions used in our inference of anisotropies"
__author__ = "reed.essick@ligo.org"
#-------------------------------------------------
import healpy as hp
import numpy as np
### non-standard libraries
from gpr_isotropy import likelihood
from gpr_isotropy.utils import DEFAULT_NU... |
"""
"""
import attr
import codecs
from pathlib import Path
import pysrt
@attr.s
class SubReader:
path = attr.ib(type=Path)
file = attr.ib(init=False, type=codecs.StreamReaderWriter)
encoding = attr.ib(type=str, default='utf-8')
stream = attr.ib(init=False, type=pysrt.SubRipFile)
def __attrs_po... |
#!/usr/local/bin/python3.7
# -*- coding: utf-8 -*-
from datatype.list_node import ListNode, MyListNode
def deleteNode(head: ListNode, val: int) -> ListNode:
dummy = ListNode(0)
dummy.next = head
pre = dummy
cur = head
while cur:
if cur.val == val:
pre.next = cur.next
... |
"""
Test the nuances of the npc.commands.util.create_path_from_character method
"""
import npc
from npc.commands import util
from npc.character import Character
import pytest
class TestPathLiteral:
"""Test that character literals are added"""
def test_literal_component(self, tmp_path):
char = Charac... |
import argparse
import sys
import logging
from deepsegment import DeepSegment as sbd
import deepspeech
from tqdm import tqdm
from . import preprocess_audio
from . import utils
logger = logging.getLogger(__name__)
segmenter = sbd("en")
def transcribe(audiosegment, model):
stream = model.createStream()
chun... |
from datetime import timedelta
from flask import url_for
from .extensions import db
from .models import Notification, Room
def push_new_order_notification(order, receiver):
"""推送新订单消息"""
message = '您有新的外卖订单 <a href="%s">%s</a> ! \n %s' % \
(url_for('user.show_order', order_id=order.id), order.... |
"""
Files views.
"""
import os
import codecs
from flask import request
from framework.render.tasks import ensure_path, old_build_rendered_html
from website.util import rubeus
from website.project.decorators import must_be_contributor_or_public
from website import settings
from website.project.views.node import _view... |
from collections import defaultdict
import datetime
import logging
import webapp2
from google.appengine.api import memcache
from google.appengine.ext import ndb
import tba_config
from base_controller import CacheableHandler
from consts.award_type import AwardType
from consts.event_type import EventType
from consts.la... |
from .pyARSS import Encode, Decode |
import json
from configparser import ConfigParser
from http.server import BaseHTTPRequestHandler, HTTPServer
from utils import return_vector
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response_only(200)
def do_POST(self):
self.send_response(200)
self.send_hea... |
# -*- coding: UTF-8 -*-
import pymysql
import time
import os
from apscheduler.schedulers.blocking import BlockingScheduler
from datetime import datetime
def get_info(db, sql):
try:
cursor = db.cursor()
cursor.execute(sql)
if sql[0:6].lower() == "select":
results = cursor.fetch... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'pysdb3/ui/importsitescsv.ui'
#
# Created by: PyQt5 UI code generator 5.14.1
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_DialogImportSitesCSV(object):
def setupUi(self, ... |
#!/usr/bin/env python
import sys
from cafysis.file_io.dcd import DcdFile
if len(sys.argv) != 6:
print ('Usage: SCRIPT [Nrep] [nmp] [step] [path/prefix] [output restart file]')
sys.exit(2)
Nrep = int(sys.argv[1])
nmp = int(sys.argv[2])
step = int(sys.argv[3])
file_path = sys.argv[4]
f_rst = open(sys.argv[5]... |
# -*- coding: utf-8 -*-
from ansi_colours import AnsiColours as Colour
from rummy.constants.constants import UNICODE_SUPPORT
from rummy.deck.suits import Suits
class Card:
value = ""
suit = ""
def __init__(self, value, suit):
self.value = value
self.suit = Suits.alpha_to_unicode_suit_gl... |
# Generated by Django 3.0.6 on 2020-05-30 16:42
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('posts', '0007_auto_20200530_1813'),
]
operations... |
# Copyright (C) 2019 The Raphielscape Company LLC.
#
# Licensed under the Raphielscape Public License, Version 1.c (the "License");
# you may not use this file except in compliance with the License.
"""
Userbot module to help you manage a group
"""
from asyncio import sleep
from os import remove
from teletho... |
# Generated by Django 3.2.13 on 2022-05-11 14:29
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('programmes', '0043_programme_effet_relatif'),
]
operations = [
migrations.RemoveField(
model_name='logementedd',
na... |
# -*- coding: utf-8 -*-
# Copyright 2011 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 require... |
dictt = {"Ads": 123, "Red": 424, "frt": 9129}
print(dictt) |
from UQpy.surrogates.polynomial_chaos import *
from UQpy.surrogates.stochastic_reduced_order_models import *
from UQpy.surrogates.kriging import *
from UQpy.surrogates.gaussian_process import *
from UQpy.surrogates.baseclass import *
from . import polynomial_chaos, stochastic_reduced_order_models, gaussian_process, ba... |
#!/usr/bin/python
# coding=utf-8
# @Date : 2015-06-28
# @Author : xyw55 (xyw5255@163.com)
'''
phpwind 9.0 /res/js/dev/util_libs/swfupload/Flash/swfupload.swf xss漏洞 POC
refer : http://wooyun.org/bugs/wooyun-2013-017731
'''
import md5
def assign(service, arg):
if service == "phpwind":
r... |
import click
from Crypto.PublicKey import RSA
from pathlib import Path
@click.command()
@click.option('--dec_digits', default=2048, help='Length of RSA private key')
@click.option('--save_dir', default='.', help='Directory to save both keys')
def gen_pair(dec_digits: int=2048, save_dir: str='.'):
"""Generate pub... |
import asyncio
def session(function):
tasks = {}
async def closure(dialog, message):
call_id = message.headers["Call-ID"]
expires = int(message.headers["Expires"])
await dialog.reply(message, status_code=200)
if expires > 0:
future = asyncio.ensure_future(functio... |
from LightController import *
lc = lightcontroller()
print "Welcome to Light Tester"
print ""
raw_input("Press Enter to begin...")
for i in range(12):
print "{} - ON" .format(i)
lc.lightOn(i, 1)
#raw_input()
#lc.lightOff(i)
for i in range(13, 24):
print "{} - ON" .format(i)
lc.lightOn(i, 1)
... |
"""Transformers for MICOM types."""
from micom.workflows.core import GrowthResults
import pandas as pd
from q2_micom.plugin_setup import plugin
import q2_micom._formats_and_types as ft
@plugin.register_transformer
def _1(data: pd.DataFrame) -> ft.MicomMediumFile:
mm = ft.MicomMediumFile()
data.to_csv(str(mm)... |
from graffan.library.models.targets import TorsionTarget
from graffan.utilities.forcebalance import (
extract_target_parameters,
extract_targets,
load_fb_force_field,
)
def test_mvals_to_pvals_jacobian():
# Not 100% clear what a good test for this will be.
pass
def test_load_fb_force_field(force... |
"""Other user's solutions can be found below."""
def find_even_index_using_built_in(arr):
"""."""
# this solution does not return 0 for empty array
# But it is a good reference for using list slicing
for i in range(len(arr)):
if sum(arr[i:]) == sum(arr[:i+1]):
return i
return -... |
from abstract_deque import AbstractDeque
class ArrayDeque(AbstractDeque):
def __init__(self, data=None):
super().__init__()
if data is None:
self._array = []
else:
self._array = list(data)
self._size = len(self._array)
def __iter__(self):
return... |
a = [5, 6, 8, 2, 3]
print(max(a))
|
# -*- coding: utf-8 -*-
from flask.ext.script import Manager
from fbone import create_app
from fbone.extensions import db
from fbone.utils import MALE
from fbone.modules.user import User, UserDetail, ADMIN, ACTIVE
app = create_app()
manager = Manager(app)
@manager.command
def run():
"""Run in local machine.""... |
class Ability(object):
def __init__(this, name, value, cond=None):
this.name = name
this.value = value
this.cond = cond
this.mod = []
if name == 'a' or name == 'att':
this.mod = [('att','passive',value, cond)]
elif name == 's' or name == 'sd':
... |
from penty.types import Cst, Module, astype
from penty.types import Type, TypeOf, FilteringBool
from penty.types import ConstFunctionType, ConstFunctionTypeMeta
import operator
import re
class UnaryOperatorMeta(ConstFunctionTypeMeta):
cache = {}
def __getitem__(self, args):
if args not in UnaryOperat... |
"""Created by sgoswami on 9/13/17."""
"""You're given an array as an input, form a binary tree with the following characteristics,
1. Should satisfy binary heap property at every node, thus the value if the node should be less than both its children.
2. An inorder traversal should return the array."""
import sys
clas... |
# (C) Copyright Artificial Brain 2021.
#
# 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 ... |
from copy import deepcopy
from typing import List, Tuple, Dict, Union, Optional
EncodeDecodeMappings = List[Tuple[int, str, str]]
Predictions = List[Dict[str, Union[str, Dict]]]
class TextEncoder:
def __init__(
self,
encoding: Dict[str, str],
model_special_tokens: Optional[List[str]] = No... |
from django.db import models
from django.urls import reverse_lazy
from tweets.models import Tweet
class HashTag(models.Model):
tag = models.CharField(max_length=120)
timestamp = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.tag
def get_absolute_url(self):
ret... |
#!/usr/bin/env python
import sys
from EPPs.common import StepEPP
class CheckStepUDFs(StepEPP):
"""
Checks Step UDFs have been completed and causes a sys exit if not. Can be prefixed before other python scripts with
'&&' in EPP.
"""
def __init__(self, argv=None):
super().__init__(argv)
... |
import logging
import shutil
from datetime import (
datetime,
timedelta,
)
from decimal import Decimal
from sqlalchemy import (
and_,
desc,
false,
null,
true,
)
from sqlalchemy.orm import eagerload
from galaxy import (
model,
util,
)
from galaxy.webapps.base.controller import (
... |
#!/usr/bin/env python
'''
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");... |
# -*- coding: utf-8 -*-
# Copyright (c) 2021, Alcazas and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe import _
from frappe.model.document import Document
class JobTier(Document):
def validate(self):
if len(self.tier_code) != 2:
... |
class Solution(object):
def countAndSay(self, n):
"""
:type n: int
:rtype: str
"""
if n <= 1:
return '1'
ret = ""
last_str = self.countAndSay(n - 1)
print n - 1, last_str
i, end, count, last_word = ... |
import torch
import copy
import random
import numpy as np
class BirdBrain:
def __init__(self, input_size=6, hidden_size=8, output_size=2):
layers = list()
layers.append(torch.nn.Linear(input_size, hidden_size))
layers.append(torch.nn.Sigmoid())
layers.append(torch.nn.Linear(hidden_... |
from gym.envs.registration import register
register(
id='slotcar-v0',
entry_point='gym_slotcar.envs:SlotcarEnv',
)
|
from GNetLMM.pycore.mtSet.utils.utils import smartSum
from GNetLMM.pycore.mtSet.mean import mean
import pdb
import numpy as NP
import scipy as SP
import scipy.linalg as LA
import time as TIME
from gp_base import GP
class gp2kronSum(GP):
def __init__(self,mean,Cg,Cn,XX=None,S_XX=None,U_XX=None,offset=1e-4):
... |
import sys
import urllib.request
def check_donate():
if len(sys.argv) > 1 and sys.argv[1] == "--donate":
amount = 50000
memo = ""
if len(sys.argv) > 2:
amount = int(sys.argv[2])
if len(sys.argv) > 3:
memo = sys.argv[3]
with request.urlopen("h... |
from ray.rllib.agents.ppo import PPOAgent
from ray import tune
import ray
if __name__ == "__main__":
ray.init()
# Test legacy *Agent classes work (renamed to Trainer)
tune.run(
PPOAgent,
config={"env": "CartPole-v0"},
stop={"training_iteration": 2})
|
from re import I
import re
import conda
from conda.models.match_spec import MatchSpec
from conda.cli.python_api import Commands, run_command as conda_run
import os, stat
import subprocess
from numpy import isin
DOCKER_SOCKET = "/var/run/docker.sock"
DOCKER_IMAGE = os.environ.get("DOCKER_IMAGE", "rpbs/seamless")
def ... |
# coding: utf-8
"""
TF-IDF 模型:
主要思想是,如果某个词或短语在一篇文章中出现的频率TF(Term Frequency,词频),词频高,
并且在其他文章中很少出现,则认为此词或者短语具有很好的类别区分能力,适合用来分类。
公式:
* TF-IDF = TF * IDF
* TF(t) = (词t在文档中出现的总次数) / (文档的词总数)
* IDF = log_e(总文档数/词t出现的文档数)
"""
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.tex... |
#!/usr/bin/python3
# rotary volume knob
# these files belong all together:
# RPi-Jukebox-RFID/scripts/rotary-encoder.py
# RPi-Jukebox-RFID/scripts/ky040.py
# RPi-Jukebox-RFID/misc/sampleconfigs/phoniebox-rotary-encoder.service.stretch-default.sample
# See wiki for more info: https://github.com/MiczFlor/RPi-Jukebox-RFID... |
import fire
import os
import os.path as osp
import numpy as np
import pandas as pd
from cytokit import config as cytokit_config
from cytokit.ops import cytometry
from cytokit.ops import tile_generator
from cytokit.ops import tile_crop
from cytokit.utils import ij_utils
from cytokit import io as cytokit_io
from cytokit ... |
# Generated by Django 3.1.6 on 2021-02-08 17:31
import app.forms.enums
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import enumchoicefield.fields
import uuid
class Migration(migrations.Migration):
initial = True
dependencies = [
('conten... |
#
# Copyright (c) 2022 Airbyte, Inc., all rights reserved.
#
from abc import ABC
from typing import Any, Iterable, Mapping, Optional
import requests
from airbyte_cdk.sources.streams.http import HttpStream
class MetabaseStream(HttpStream, ABC):
def __init__(self, instance_api_url: str, **kwargs):
super()... |
from django.db import models
from django.db.models.fields import NullBooleanField
from .user import User
class Product(models.Model):
id_product=models.AutoField(primary_key=True)
name_product=models.CharField(max_length=30,null=False)
description_product=models.CharField(max_length=80, null=True)
... |
# coding=utf8
#
# conftest.py
# Part of SublimeLinter3, a code checking framework for Sublime Text 3
#
# Written by Joshua Hagins
#
# Project: https://github.com/SublimeLinter/SublimeLinter3
# License: MIT
#
"""This module exports session-scoped fixtures for tests."""
from pytest import fixture
from mock import patch... |
from scipy.io import loadmat
from os.path import isfile
import pandas as pd
import numpy as np
import re
def read_table(swan_file):
'''
Reads in SWAN table format output
Parameters
----------
swan_file: str
filename to import
Returns
-------
swan_data: DataFram... |
from __future__ import absolute_import, division, print_function, unicode_literals
import os, sys, json
from datetime import datetime, timedelta
import requests
from . import register_parser
from .util import paginate
from .util.printing import format_table, page_output, tabulate, format_datetime
from .util.aws impo... |
import unittest
from team import *
class TestPlayer(unittest.TestCase):
def setUp(self):
self.test_player = Player("Test")
def test_eq_false(self):
self.assertFalse(self.test_player == Player("test"))
def test_eq_true(self):
self.assertTrue(self.test_player == Player("Test"))
... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.15 on 2019-11-12 21:37
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('tenx', '0013_auto_20191021_0959'),
]
operations = [
migrations.AlterField(... |
'''Refaça o DESAFIO 51,
lendo o primeiro termo e a razão de uma PA,
mostrando os 10 primeiros termos da progressão usando a estrutura while.'''
primeiro = int(input('Qual o termo? '))
progressao = int(input('Pular de quanto em quanto? '))
contador = 1
termo = primeiro
while contador <= 10:
print('{}'.format(... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.