content stringlengths 5 1.05M |
|---|
import json
from django.urls import reverse
from rest_framework import status
from rest_framework.test import APITestCase
from django.contrib.auth import get_user_model
from authors.apps.articles.models import Articles
from authors.apps.profiles.models import Profile
class TestGetEndpoint(APITestCase):
def setU... |
"""first create User Post...
Revision ID: fc3f3b3d437e
Revises:
Create Date: 2020-04-01 21:23:21.121228
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'fc3f3b3d437e'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### comman... |
from unittest import TestCase
from cloudrail.knowledge.context.aliases_dict import AliasesDict
from cloudrail.knowledge.context.azure.webapp.azure_function_app import AzureFunctionApp
from cloudrail.knowledge.rules.base_rule import RuleResultType
from cloudrail.knowledge.context.azure.azure_environment_context import A... |
import copy
import os
from typing import Dict, List, Optional, Tuple
import netsquid as ns
import numpy as np
from netqasm.logging.glob import get_netqasm_logger
from netqasm.logging.output import NetworkLogger
from netqasm.qlink_compat import RequestType
from netqasm.runtime.interface.config import (
Link,
Ne... |
from copy import copy
from collections import namedtuple
from .angles import relative_azimuth
from ..core.util import project_coords
import numpy as np
import xarray as xr
import dask
import dask.array as da
import logging
logger = logging.getLogger(__name__)
def dtor(x):
"""Converts degrees to... |
import asyncio
from japronto.app import Application
def slash(request):
return request.Response()
async def sleep(request):
await asyncio.sleep(int(request.match_dict['sleep']))
return request.Response()
app = Application()
r = app.router
r.add_route('/', slash)
r.add_route('/sleep/{sleep}', sleep)
... |
from django.contrib.staticfiles.testing import StaticLiveServerTestCase
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.common.exceptions import WebDriverException
import time
import os
MAX_WAIT = 10
class NewVisitorTest(StaticLiveServerTestCase):
def setUp(self):
... |
v = ""
while 1:
oopen = open('SSshell.py', 'w')
x = input('>>> ')
def replace1():
global x
if 's.show-' in x:
x = x.replace('s.show-', 'print')
if 's.var-' in x:
x = x.replace('s.var-', '')
if 's.if-' in x:
x = x.replace('s.if-', 'if ')
if 's.elif-' in x:
x = x.replace('s.elif-', 'elif ')
i... |
import pymysql
import string
import re
from kritzbot.configloader import BotCfg
from kritzbot.logger import Logger
log = Logger(__name__)
class DatabaseConnection:
def __init__(self, name):
self.name = name
log.info('Database connection created at {}'.format(self.name))
self.db = self.createDatabaseConnection... |
import tensorflow as tf
from feeder import VarFeeder
import os
import argparse
import pandas as pd
import numpy
import logging
import yaml
import datetime
import math
import numpy as np
from typing import Tuple
import pickle
log = logging.getLogger()
SHUFFLE_BUFFER = 100
def __data_parser(seriali... |
# Copyright 2022 Google LLC
# 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 writing, sof... |
###############################################################################
# WaterTAP Copyright (c) 2021, The Regents of the University of California,
# through Lawrence Berkeley National Laboratory, Oak Ridge National
# Laboratory, National Renewable Energy Laboratory, and National Energy
# Technology Laboratory ... |
from __future__ import absolute_import
from __future__ import print_function
from django.core.management.base import BaseCommand
from optparse import make_option
from django3scaffold.scaffold import Scaffold
from django3scaffold import settings
class Command(BaseCommand):
def add_arguments(self, parser):
... |
"""
---
title: Test performance of Adam implementations
summary: This experiment compares performance of Adam implementations.
---
# Performance testing Adam
```text
TorchAdam warmup...[DONE] 222.59ms
TorchAdam...[DONE] 1,356.01ms
MyAdam warmup...[DONE] 119.15ms
MyAdam...[DONE] 1,192.89ms
```
[:
analyze_url = vision_base_u... |
import time
import cv2
from threading import Thread
from src.camera.BaseCamera import BaseCamera
from src.camera.Frame import Frame
from src.utils.injection.decorator import inject
from src.utils.PubSub import PubSub
class Camera(BaseCamera):
FRAME_DELAY = .1 # type: float
@inject
def __init__(self, s... |
# File Size
def get_size(size):
"""Get size in readable format"""
units = ["Bytes", "KB", "MB", "GB", "TB", "PB", "EB"]
size = float(size)
i = 0
while size >= 1024.0 and i < len(units):
i += 1
size /= 1024.0
return "%.2f %s" % (size, units[i])
# Button Count
def split_list(l, ... |
"""Sensor platform for Beward devices."""
import logging
from datetime import datetime
from os import path
from typing import Optional, Union, Dict, Any
import beward
import homeassistant.util.dt as dt_util
from homeassistant.const import (
CONF_NAME,
CONF_SENSORS,
)
from homeassistant.core import callback
fr... |
from .distinct_colors import * # noqa: F401
from .layer_viewer_widget import LayerViewerWidget # noqa: F401
from .layers import * # noqa: F401
from .version import __version__ # noqa: F401
dcolors = distinct_colors
# note on the case convention all the symbols that are used by qt, for instance methods that overri... |
import copy
import json
import re
from typing import Any, Dict, List, Mapping, Optional
import markdown
from markdown.extensions import Extension
from markdown.preprocessors import Preprocessor
from zerver.openapi.openapi import get_openapi_return_values, likely_deprecated_parameter
from .api_arguments_table_generat... |
#!/usr/bin/python
#SSH BruteForcer that scans an ip range for
#open ssh ports using nmap and then brute
#forces them.
#http://www.darkc0de.com
#d3hydr8[at]gmail[dot]com
import sys, time, StringIO, commands, re
#Set the successful login file.
save_file = "SSH_Logins.txt"
#Set verbose mode: 1=on 0=off
verbose = 1
#S... |
# Advent of Code 2020 Day 4
# https://adventofcode.com/2020/day/4
import re
ECL_LIST = ["amb", "blu", "brn", "gry", "grn", "hzl", "oth"]
with open("./AdventOfCode/2020/day4-input.txt") as f:
lines = f.read() # read file to a single string
# make a list of records. Two newlines seperate records.
records = lin... |
# -*- coding: utf-8 -*-
"""
plot.py: Tools for manipulating and plotting dynamic spectra, time series, etc.
This functionality is accessed by the user through the class Dynspec.
"""
from pylab import *
from numpy import *
import matplotlib.pyplot as plt
import os
from astropy.time import Time
from copy import deepco... |
"""
## Questions : Easy
### 202. [Happy Number](https://leetcode.com/problems/happy-number/)
Write an algorithm to determine if a number is "happy".
A happy number is a number defined by the following process: Starting with any positive integer, replace the number by
the sum of the squares of its digits, and repeat ... |
"""
MIT License
Copyright (c) 2019-present Josh B
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 json
import logging
import requests
import tweepy
class Telegram:
@staticmethod
def post_tweet_link(status: tweepy.Status, bot_token: str, chat_id: str):
tweet_link = "https://twitter.com/" + status.user.screen_name + "/status/" + status.id_str
payload = {
'chat_id': chat_i... |
from flask import Flask, request, jsonify
import json, os
try:
from flask.ext.cors import CORS # The typical way to import flask-cors
except ImportError:
# Path hack allows examples to be run without installation.
parentdir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
os.sys.path.ins... |
#!/usr/bin/python
# sequence.py
#
# Mike Bonnington <mjbonnington@gmail.com>
# Benjamin Parry <ben.parry@gps-ldn.com>
# (c) 2015-2019
#
# These functions convert formatted sequences to lists and vice-versa.
import glob
import os
import re
from collections import OrderedDict
# Import custom modules
# import verbose
... |
import numpy as np
from matplotlib import pyplot as plt
plt.rc('text', usetex=True)
plt.rcParams.update({'font.size': 20})
fig = plt.figure(figsize=(8, 6))
ax = fig.gca()
Ns = (2**np.arange(3,12)).tolist()
errors = np.zeros(len(Ns))
errors2 = np.zeros(len(Ns))
for i, N in enumerate(Ns):
data = np.loadtxt('saved_... |
# --------------------------------------------------------
# Deep Iterative Matching Network
# Licensed under The Apache-2.0 License [see LICENSE for details]
# Written by Yi Li, Gu Wang
# --------------------------------------------------------
from __future__ import print_function, division
import numpy as np
from gl... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from . import ... |
FEEDS_TEMPLATE = "feeds.html"
INDEX_TEMPLATE = "index.html" |
import sys, os, json
version = (3,7)
assert sys.version_info >= version, "This script requires at least Python {0}.{1}".format(version[0],version[1])
# Game loop functions
def render(game,current):
''' Displays the current room '''
print('You are in the ' + game['rooms'][current]['name'])
print(game['... |
import uuid
from django.db import models
class TimestampedModel(models.Model):
updated_at = models.DateTimeField(auto_now=True)
created_at = models.DateTimeField(auto_now_add=True)
class Meta:
abstract = True
class KeyModel(TimestampedModel):
key = models.CharField(
max_length=255,... |
import urllib.request
import json
def get_bing_image_url():
"""Retrieve image of the day from Bing's service"""
# TODO figure out what other locales Bing accepts
locale = "en-US"
url = f"https://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1&mbl=1&mkt={locale}"
req = urllib.request.Request(u... |
from user_messages.models import Thread
def user_messages(request):
c = {}
if request.user.is_authenticated():
c["inbox_count"] = Thread.objects.inbox(request.user).count()
return c
|
from numpy import *
# 1NN算法
def _1NN(traindataMat, testdataMat, traintagMat, testtagMat):
trainSize = traindataMat.shape[0]
testSize = testdataMat.shape[0]
cnt_correct = 0
for i in range(testSize):
sample_test = mat(testdataMat[i, :])
pos = -1
for j in range(trainSize):
... |
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
import numpy
ext_modules = [Extension(
"nearest_neighbors",
sources=["knn.pyx", "knn_.cxx",], # source file(s)
include_dirs=["./", numpy.get_include()],
language="c++", ... |
import setuptools
setuptools.setup(
name="txCarbonClient",
version="0.1",
packages=["txCarbonClient"],
package_dir={'' : 'src'},
install_requires=["twisted"],
author="Chasm",
author_email="fd.chasm@gmail.com",
url="https://github.com/fdChasm/txCarbonClient",
license="MIT",
descr... |
#training script for neural nets
import numpy as np
from pooling_gru import PoolingGRU
from baseline.naive_gru import NaiveGRU
from utils import *
import pdb
import argparse
import math
_id = 0
_position = 1
_class = 2
#hyperparameters
__INPUT_DIM = 2
__OUTPUT_DIM = 2
__HIDDEN_DIM = 128
__NUM_EPOCHS = 2 # 100
__LEARN... |
"""
The roseguarden project
Copyright (C) 2018-2020 Marcus Drobisch,
This program 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 3 of the License, or (at your option) any later
version.
This pr... |
from functools import partial
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from pycpd import DeformableRegistration
from pycpd import RigidRegistration, AffineRegistration
import numpy as np
def visualize(iteration, error, X, Y, ax):
plt.cla()
ax.scatter(X[:, 0], X[:, 1], X[:, 2], ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Microservice to generate 1 model"""
# builtin
import os
import json
import secrets
import argparse
from enum import Enum
from pathlib import Path
# third party
import numpy as np
# local
import site
site.addsitedir(Path(__file__).parent)
import misc
import rosetta_ut... |
# -*- coding: utf-8 -*-
from PyQt5 import QtCore, QtGui, QtWidgets
from random import *
import sys, os
class ui(object):
def __init__(self, Form):
self.Form = Form
self.Form.setObjectName("Form")
self.Form.setFixedSize(1400, 500)
self.overall_vertical_layout = QtWidgets.QVBoxLayout... |
# pylint: disable=redefined-outer-name
import os
from datetime import datetime
from itertools import zip_longest
from pathlib import Path
from typing import List, Union
from loguru import logger
from courier.config import get_config
from courier.elements.assign_page_service import AssignPageService
from courier.eleme... |
from tkinter import *
from gamemodes.locales.localeManager import *
import platform
def langSettingMenu(ticTacPyApp):
def applyFunction():
options = open("gamemodes/options/options.tictacpy", "r")
content = options.readlines()
lang = content[0]
options.close()
op... |
class Edge:
"""
Edge ID will be represented as a tuple consisting of adjacent tiles' IDs.
By default, no edges will have roads on them.
"""
def __init__(self, tile_ids, has_road=False):
self.edge_ID = tile_ids
self.has_road = has_road
"""
Return whether or not another is e... |
from TensorFlowModels import LinearModelExample
|
import swapper
from .abstracts import AbstractOrder, AbstractPayment # noqa
class Payment(AbstractPayment):
class Meta(AbstractPayment.Meta):
swappable = swapper.swappable_setting("getpaid", "Payment")
|
import helium
import unittest
class TestXXX(unittest.TestCase):
if __name__ == '__main__':
unittest.main()
|
import requests
from bs4 import BeautifulSoup
class UsualFunctions():
def __init__(self):
self.page = requests.get('https://www.worldometers.info/coronavirus/country/brazil/')
self.soup = BeautifulSoup(self.page.content, 'html.parser')
self.main_info = self.soup.find_all(class_='maincounter... |
#!/usr/bin/env python
from __future__ import division, print_function, absolute_import
from itertools import product
from functools import reduce
import operator
import numpy as np
from numpy.testing import (assert_allclose, assert_, assert_raises,
assert_equal)
import pywt
def test_trav... |
import os
import numpy as np
def main():
"""
train_mapping.txt
date, drive_id, frame_idx
train_rand.txt
img_idx | line in train_mapping.txt (1 indexed)
"""
train_mapping_path = os.path.expanduser(
'~/Kitti/object/devkit_object/mapping/train_mapping.txt')
train_rand_path = os... |
from django import forms
from .models import SuggestedProjects
class ProjectSuggestion(forms.ModelForm):
class Meta:
model = SuggestedProjects
fields = ['title', 'submitter_name', 'ip_address', 'links', 'summary']
widgets = {'ip_address': forms.HiddenInput()} |
#A* -------------------------------------------------------------------
#B* This file contains source code for the PyMOL computer program
#C* copyright 1998-2000 by Warren Lyford Delano of DeLano Scientific.
#D* -------------------------------------------------------------------
#E* It is unlawful to modify or remove ... |
import os
from wasienv.wasicc import run
from wasienv.tools import is_exe, is_wasm
EXAMPLES_DIR = os.path.join(os.path.dirname(__file__), '../examples/')
os.chdir(EXAMPLES_DIR)
def test_wasicc():
return_code = run(["wasicc", "c/example.c", "-o", "c/example"])
assert return_code == 0
assert is_exe("c/ex... |
from __future__ import absolute_import
from .style import style as CMS_style
from .labels import CMS_label
__all__ = [
'CMS_style',
'CMS_label',
]
|
from ..lib import utils, output_pipe, keras_utils
from .. import channels
import json
import threading
from .base import BaseService
class FitWorkerService(BaseService):
# The purpose of this service is to train a model that was called using
# the "fit" method - which is a more rigid training spec inspired b... |
#!/usr/bin/env python
#coding=utf-8
""" grab mets files from UCB server """
import urllib2
def main():
with open("mets_index.html", "r") as f:
for line in f:
if line.find("xml") == 69:
filename = line[74:94]
print "filename:", filename
grabfile(fi... |
###########################################################################
#
# Copyright 2020 Google LLC
#
# 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/l... |
# Generated by Django 3.1 on 2020-10-24 15:24
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('ui', '0004_remove_feed_url'),
]
operations = [
migrations.AlterField(
model_name='feed',
name='updated',
f... |
import pandas as pd
from bs4 import BeautifulSoup
from ..common import web
import re
def get_symbol_list(cache="", update_cache=True):
"""
:param cache:
:param update_cache:
:return:
"""
url = "https://fundamentus.com.br/detalhes.php?papel="
raw_html = ""
if len(cache) > 0 and not upd... |
# Copyright (C) 2014 SignalFuse, Inc.
# Copyright (C) 2015 SignalFx, Inc.
#
# Docker container orchestration utility.
import getpass
import json
import requests
from . import exceptions
from .version import name as maestro_name
class BaseAuditor:
"""Base class for auditors that can save or notify about orchestr... |
__author__ = 'saeedamen' # Saeed Amen
#
# Copyright 2016-2020 Cuemacro
#
# 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... |
from abc import abstractmethod, ABC
from typing import Dict
class AlertData(ABC):
"""
Define an empty object which will hold the extra data needed for special
alerts.
"""
def __init__(self):
self._alert_data = {}
@property
def alert_data(self) -> Dict:
return self._alert_... |
# =
# +=
# c += a is equivalent to c = c + a
# -=
# *=
# /=
# %=
# **=
# //= |
# -*- coding: utf-8 -*-
import logging
_logger = logging.getLogger(__name__)
error_code = {
-1: u'服务器内部错误',
0: u'接口调用成功',
403: u'禁止访问',
405: u'错误的请求类型',
501: u'数据库错误',
502: u'并发异常,请重试',
600: u'缺少参数',
601: u'无权操作:缺少 token',
602: u'签名错误',
700: u'暂无数据',
701: u'该功能暂未开通',
... |
from binding import *
from ..namespace import llvm
@llvm.Class()
class StringRef:
_include_ = "llvm/ADT/StringRef.h"
|
import traceback
from flask import url_for
from dashboards import Dashboard
import itertools
import dash_bootstrap_components as dbc
import dash_html_components as html
from dash.dependencies import Output, Input, State
from dash.exceptions import PreventUpdate
from dashboards.dashboard import StyledDash
from dashb... |
import datetime
import stationary
import unittest
class TestPost(unittest.TestCase):
def test_load_from_filename(self):
post = stationary.post_from_filename('example/posts/example-post.md')
self.assertEqual(post.title, 'Example Post')
self.assertEqual(post.slug, 'example-post')
sel... |
import sys, os
sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))
import torch
from torchvision.models import resnet18
import torch_pruning as tp
model = resnet18(pretrained=True)
# pruning according to L1 Norm
strategy = tp.strategy.L1Strategy() # or tp.strategy.RandomStrategy()
# build la... |
#!/usr/bin/python
import tweepy
import time
import os
class MyStreamListener(tweepy.StreamListener):
def on_status(self, status):
with open("stalking.txt", "a") as myfile:
if "RT " not in status.text:
print status.text
myfile.write(status.text + "\n")
link = status.text.split(" ")
for l in l... |
from pycoingecko import CoinGeckoAPI
cg = CoinGeckoAPI()
class Coin:
def __init__(self, top, Name, market_cap):
self.top = top
self.name = Name
self.market_cap = market_cap
def __str__(self):
return f"{self.name}"
print("Please define N top of cryptocurrencie... |
from django.contrib import admin
class ElasticIndexAdmin(admin.ModelAdmin):
list_display = ("name", "remote_name", "remote_exists", "error_count", "language", "created_at", "modified_at",
"pushed_at")
|
#!/usr/bin/env python
import sys
import numpy as np
from optparse import OptionParser
parser = OptionParser()
parser.add_option("-m",
"--matrix",
dest="matrix",
help="Matrix file")
(options, args) = parser.parse_args()
f = []
if options.matrix:
f = open(options.matrix,'r')
else:
f = sys.stdin
... |
import logging
from src.commons.big_query.big_query import BigQuery
from src.slo.predicate.sli_table_exists_predicate import \
SLITableExistsPredicate
from src.slo.backup_quality.quality_query_specification import \
QualityQuerySpecification
from src.slo.backup_quality.predicate.sli_table_newer_modification_pr... |
__version__ = "0.0.1"
AUTHOR = "Kerem Koseoglu"
EMAIL = "kerem@keremkoseoglu.com"
DESCRIPTION = "Encryption toolkit"
PYTHON_VERSION = ">=3.6.5" |
from functools import wraps
from flask_basicauth import BasicAuth
from flask_jwt_extended import get_jwt_identity, jwt_required
basic_auth = None
def flask_admin_auth(app):
global basic_auth
if basic_auth:
return basic_auth
basic_auth = BasicAuth(app)
return basic_auth
def get_current_jwt_... |
#!/usr/bin/env python3
# date: 2019.12.18
# ???
import requests
url = "https://httpbin.org/ip"
proxy = {
#"http": '141.125.82.106:80'
"https": '141.125.82.106:80'
}
r = requests.get(url, timeout=200, proxies=proxy)
print(r.text)
|
from _fatcore import ffi, lib
from fatuv import Loop
from fatuv.internal import get_strerror
import socket
uv_get_pyobj = lib.fatuv_get_pyobj
uv_set_pyobj = lib.fatuv_set_pyobj
uv_getaddrinfo_ctx_new = lib.fatuv_getaddrinfo_ctx_new
uv_getaddrinfo_ctx_delete = lib.fatuv_getaddrinfo_ctx_delete
uv_getaddrinfo = lib.fat... |
from bars import get_tick_bars, get_volume_bars, get_dollar_bars
symbols = ['AAPL','TSLA','AMZN']
tick_threshold = {'AAPL':1000,'TSLA':1000,'AMZN':1000}
volume_threshold = {'AAPL':50000,'TSLA':5000,'AMZN':50000}
dollar_threshold = {'AAPL':2000000,'TSLA':2000000,'AMZN':2000000}
# get_tick_bars(symbols, tick_threshold... |
import json
from datetime import datetime
from urllib.parse import urlencode
import requests
from flask import current_app
from werkzeug.exceptions import InternalServerError, NotFound, RequestTimeout, TooManyRequests
class ThingAPI:
def __init__(self):
self.url = current_app.config["THING_API_URL"]
... |
from socialjusticebingo.settings.common import *
SECRET_KEY = 'oe3-zo6yeb34h*ktvana^ejbb(^du)613z+tl8@)psqkr+k7sd'
DEBUG = True
TEMPLATE_DEBUG = DEBUG
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'socialjusticebingo.db'),
'USER': '',
... |
import os
def static():
path = './train2id.txt'
head_dic = {}
tail_dic = {}
cnt = 0
with open(path, 'r') as f:
for raw in f.readlines():
raw = raw.strip().split(' ')
try:
head, tail, r = raw
if head not in head_dic.keys():
... |
import sys
import inspect
# functions
def whoami():
"""Get the name of the current function"""
return inspect.stack()[1][3]
def whosdaddy():
"""Get the name of the current function"""
return inspect.stack()[2][3]
def die(msg):
"""Writes msg to stderr and exists"""
sys.stderr.write(msg + "\... |
from django.core.exceptions import ImproperlyConfigured
class ImproperlyConfigured(ImproperlyConfigured):
pass
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
sys.path.append("./examples/proto")
from pprint import pprint
import logging
import time
from ledgerblue.comm import getDongle
import argparse
from base import parse_bip32_path
import validateSignature
import binascii
import base58
logging.basicConfig(level=l... |
# Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0
# For details: https://github.com/gaogaotiantian/pygictower/blob/master/NOTICE
import random
import time
class GameGlobal:
def __init__(self, seed=int(time.time())):
self._seed = seed
self._state = random.getstate()
... |
REPOSITORY_LOCATIONS = dict(
bazel_gazelle = dict(
sha256 = "62ca106be173579c0a167deb23358fdfe71ffa1e4cfdddf5582af26520f1c66f",
urls = ["https://github.com/bazelbuild/bazel-gazelle/releases/download/v0.23.0/bazel-gazelle-v0.23.0.tar.gz"],
),
bazel_skylib = dict(
sha256 = "1c531376ac7... |
#!/usr/bin/python
##########################
# This was a simple program built to determine all possible outcomes for a math game
# Rules of the game are:
# Using the numbers 1 through 10 once, fill an inverted pyramid
#
# _ _ _ _
# _ _ _
# _ _
# _
#
# The final solution(s) must work together m... |
from rest_framework import serializers
from .models import Plant
class PlantSerializer(serializers.ModelSerializer):
"""
Serializer for Plant model.
"""
seller = serializers.PrimaryKeyRelatedField(read_only=True)
class Meta:
model = Plant
fields = '__all__'
read_only = ('... |
list = [1,2,3,4,5,6,7,8,9,10]
print(list[:])
print(list[::])
print(list[0:])
print(list[:-1])
print(list[::-1])
print(list[0:0])
print(list[3:6])
print(list[3:20])
print(list[6:3])
print(list[6:3:-1])
print(list[3:8:2])
print(list[8:3:-2])
|
from statsmodels.regression.linear_model import OLS
import statsmodels.api as sm
import pandas as pd
import matplotlib.pyplot as plt
from collections import OrderedDict
current = pd.read_excel('p1-customers.xlsx')
new = pd.read_excel('p1-mailinglist.xlsx')
# the instructions were not clear here. Do we fit a... |
import scrapy
import urllib
import os, io
class DatasetSpider(scrapy.Spider):
name = "dataset"
def start_requests(self):
urls = ["../machine-learning-databases/abalone/", "../machine-learning-databases/breast-cancer/", "../machine-learning-databases/bridges/", "../machine-learning-databases/balloons/... |
import discord
import json
from random import choice as choose_from
import logging
from termcolor import colored, cprint
logger = logging.getLogger('discord')
logger.setLevel(logging.DEBUG)
handler = logging.FileHandler(filename='discord.log', encoding='utf-8', mode='w')
handler.setFormatter(logging.Formatter('%(ascti... |
import sys
import random
if __package__ == "":
# for kaggle-environments
from lux.game import Game
from lux.game_map import Cell, RESOURCE_TYPES
from lux.constants import Constants
from lux.game_constants import GAME_CONSTANTS
from lux import annotate
else:
# for CLI tool
from .lux.game ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from hwt.hdl.types.bits import Bits
from hwt.interfaces.hsStructIntf import HsStructIntf
from hwt.interfaces.utils import addClkRstn
from hwt.synthesizer.param import Param
from hwt.synthesizer.unit import Unit
from hwtHls.hlsStreamProc.streamProc import HlsStreamProc
c... |
import os
from glob import glob
from typing import AnyStr
from pyshrimp.exception import IllegalArgumentException
def _ls(list_supplier, dirs_only=False, files_only=False):
if dirs_only and files_only:
raise IllegalArgumentException('Illegal arguments - dirs_only and files_only cannot be true together')
... |
from .linear import Linear
from .rnn import LSTM, LSTMCell, RNNCell, GRUCell
__all__ = [
'Linear',
'LSTM',
'LSTMCell',
'RNNCell',
'GRUCell',
]
|
#!/usr/bin/env python
import json
import argparse
from ..wrapper import describe_algorithm
from ..wrapper import generate_all
from ..utils import get_true_or_false
def main():
DEFAULT_USER = 'wangyx2005'
parser = argparse.ArgumentParser(
description='A tool to wrap your containers')
parser.add_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.