text stringlengths 1 927k |
|---|
EXTERNAL_DEPS = [
"@jackson-core//jar:neverlink",
"@jackson-databind//jar",
"@jackson-annotations//jar",
"@jackson-dataformat-yaml//jar",
"@snakeyaml//jar",
] |
import subprocess
import sys
from distutils.version import LooseVersion
reqs = subprocess.check_output([sys.executable, '-m', 'pip', 'freeze'])
installed_packages = [r.decode().split('==')[0] for r in reqs.split()]
if 'torch' in installed_packages:
from rlcard.agents.dqn_agent import DQNAgent as DQNAgent
from... |
#!/usr/bin/env python
"""
Script name: getAQMeshData.py
Author: JO'N/ CEMAC (University of Leeds)
Date: March 2018
Purpose: Download data from an AQMesh pod using the API tool
Usage: ./getAQMeshData.py <stationID> <startDate> <endDate> <variables> <outFreq>
<stationID> - Unique ID of the AQMesh station from whi... |
import tensorflow as tf
import utils.model_utils as mu
from model.basic_model import BasicModel
from raw_input import Input
class SetupModel(BasicModel):
def __init__(self, attn, checkpoint):
super(SetupModel, self).__init__()
self.data = Input()
self.output = None
self.saver = No... |
class Solution:
def pivotArray(self, nums: List[int], pivot: int) -> List[int]:
great = []
small = []
equal = []
for num in nums:
if num > pivot:
great.append(num)
elif num < pivot:
small.append(num)
else:
... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import with_statement
import anyjson
import os
import sys
import time
from datetime import datetime, timedelta
from kombu.transport.base import Message
from kombu.utils.encoding import from_utf8, default_encode
from mock import Mock, patc... |
#!/usr/bin/env python
# coding: utf-8
# ---
# In[1]: Setting GPU w/ Tensorflow running
import tensorflow as tf
print(tf.__version__)
import keras
print(keras.__version__)
gpus = tf.config.experimental.list_physical_devices('GPU')
if gpus:
try:
# Currently, memory growth needs to be the same across GPUs
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
##
# utils.py : some auxiliary functions
##
# © 2017, Chris Ferrie (csferrie@gmail.com) and
# Christopher Granade (cgranade@cgranade.com).
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following co... |
workers = 3
accesslog = "gunicorn_access.log"
logfile = "gunicorn.log"
loglevel = "info" |
import pandas as pd
import sys
import os
import re
import shutil
import subprocess
inputs=sys.argv[1]
output=sys.argv[2]
#names=["Username", "IP", "Terminal 1", "Terminal 2", "RStudio", "Jupyter", "Download Files"]
df = pd.read_csv(inputs, sep=",", header=None, names=["Username", "IP"])
df['Terminal 1'] = df["IP"].map... |
import logging
_logger = logging.getLogger('theano.sandbox.cuda.opt')
import copy
import sys
import warnings
import numpy
import theano
from theano.scan_module import scan_utils, scan_op, scan_opt
from theano import scalar as scal
from theano import tensor, compile, gof
import theano.ifelse
from theano.compile impo... |
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under t... |
#!/usr/bin/env python
from oekaki.oekaki import Oekaki |
# Nothing in it here |
from django.shortcuts import render
from django.http import HttpResponseRedirect, HttpResponse
from django.contrib.auth.models import User
from django.shortcuts import get_object_or_404, render, redirect
from .models import CarModel, CarMake, CarDealer, DealerReview, ReviewPost
from .restapis import get_dealers_from_cf... |
"""
Copyright (c) 2018 Intel Corporation
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 wri... |
import time
import pytz
import urllib2
import urlparse
import datetime
from jenkinsapi.artifact import Artifact
from jenkinsapi import config
from jenkinsapi.jenkinsbase import JenkinsBase
from jenkinsapi.exceptions import NoResults
from jenkinsapi.constants import STATUS_SUCCESS
from jenkinsapi.result_set import Resul... |
import os
from pathlib import Path
def is_legal_path(path):
for p in path:
if p in [".", ".."] or "/" in p:
return False
return True
def map_existing_files(torrent, path, add_name_to_folder=True):
name = torrent[b"info"][b"name"].decode()
files = []
if b"files" in torrent[b"... |
from rllab.misc import ext
from rllab.misc import krylov
from rllab.misc import logger
from rllab.core.serializable import Serializable
import theano.tensor as TT
import theano
import itertools
import numpy as np
from rllab.misc.ext import sliced_fun
from ast import Num
class PerlmutterHvp(Serializable):
def __i... |
"""ACME protocol messages."""
import collections
from acme import challenges
from acme import errors
from acme import fields
from acme import jose
from acme import util
OLD_ERROR_PREFIX = "urn:acme:error:"
ERROR_PREFIX = "urn:ietf:params:acme:error:"
ERROR_CODES = {
'badCSR': 'The CSR is unacceptable (e.g., due ... |
from typing import FrozenSet
from collections import Iterable
from math import log, ceil
from mathsat import msat_term, msat_env
from mathsat import msat_make_constant, msat_declare_function
from mathsat import msat_get_integer_type, msat_get_rational_type, msat_get_bool_type
from mathsat import msat_make_and, msa... |
from __future__ import absolute_import
from functools import partial
from copy import deepcopy
from rest_framework.response import Response
from sentry.api.bases.organization import OrganizationPermission
from sentry.api.bases import OrganizationEndpoint
from sentry.api.paginator import GenericOffsetPaginator
from s... |
import numpy as np
from pycocotools.coco import COCO
from .custom import CustomDataset
from .registry import DATASETS
@DATASETS.register_module
class DensePose(CustomDataset):
CLASSES = ('person', 'bicycle', 'car', 'motorcycle', 'airplane', 'bus',
'train', 'truck', 'boat', 'traffic_light', 'fire_... |
import os
import codecs
import re
from setuptools import setup
def read(*parts):
return codecs.open(os.path.join(os.path.dirname(__file__), *parts)).read()
def find_version(*file_paths):
version_file = read(*file_paths)
version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]",
... |
"""
This example is largely based on the GLUE text-classification example in the huggingface
transformers library. The license for the transformer's library is reproduced below.
==================================================================================================
Copyright 2020 The HuggingFace Team. All ... |
# -*- coding: UTF-8 -*-
from math import e, inf
import os
from numpy.lib.type_check import _imag_dispatcher
import pandas as pd
import shutil
import numpy as np
import cv2
import random
from tqdm import tqdm
import pyfastcopy
import json,sklearn
from sklearn.model_selection import train_test_split
def main():
... |
# SPDX-FileCopyrightText: 2018 Michael Schroeder for Adafruit Industries
#
# SPDX-License-Identifier: MIT
"""
`adafruit_fram`
====================================================
CircuitPython/Python library to support the I2C and SPI FRAM Breakouts.
* Author(s): Michael Schroeder
Implementation Notes
-------------... |
from .parse import Markup |
"""
A Custom Runtime Interface for running Python code with Pypy on AWS Lambda
"""
import os
import json
import requests
import importlib
__author__ = "Ulrich Scheller"
__email__ = "mail@ulrich-scheller.de"
__website__ = "www.ulrich-scheller.de"
__status__ = "Prototype"
class RuntimeInterface(object):
def __init... |
#!/usr/bin/env python3
from __future__ import print_function
from typing import Tuple, Union
import torch
from captum._utils.typing import TensorOrTupleOfTensorsGeneric
from captum.attr._core.neuron.neuron_deep_lift import NeuronDeepLift, NeuronDeepLiftShap
from tests.attr.layer.test_layer_deeplift import (
_cre... |
"""meta.py - Describing describe. All metadata about the Describe package is here.
This also loaded by setup.py
"""
__author__ = "Jeff Hui"
__credits__ = [
"Kai Groner", "Jeff Hui"
]
__license__ = "MIT"
__version__ = "1.0.0beta1"
__maintainer__ = "Jeff Hui"
__email__ = "jeff@jeffhui.net"
__status__ = "Development... |
import matplotlib.pyplot as plt
import numpy as np
grid2D = np.load(r"C:\temp\10km_grids\20180808-23.npy")
fig, ax = plt.subplots(figsize=(16.2, 16))
im = ax.imshow(grid2D)
ax.set_xlabel("Cols")
ax.set_ylabel("Rows")
plt.colorbar(im)
plt.savefig('grid2D.png') |
import time
import pytest
from ably import AblyException
from test.ably.restsetup import RestSetup
from test.ably.utils import VaryByProtocolTestsMetaclass, dont_vary_protocol, BaseAsyncTestCase
class TestRestTime(BaseAsyncTestCase, metaclass=VaryByProtocolTestsMetaclass):
def per_protocol_setup(self, use_bin... |
# -*- coding: utf-8 -*-
#
# sampler.py
#
# Copyright 2020 Amazon.com, Inc. or its affiliates. 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.or... |
import os
import time
import subprocess
from argparse import ArgumentParser
import yaml
import tkinter as tk
from tkinter import filedialog
from unsup_spatial_pred import run_experiment
def check_directory(directory):
if not os.path.exists(directory):
root = tk.Tk()
root.withdraw()
directo... |
# The decimal number, 585 = 1001001001_2 (binary), is palindromic
# in both bases.
# Find the sum of all numbers, less than one million, which are
# palindromic in base 10 and base 2.
# (Please note that the palindromic number, in either base, may
# not include leading zeros.)
def is_palindrome(num):
return num[::-... |
from collections import namedtuple
from typing import Any, Dict, Optional, Set
from dagster import check
from dagster.core.definitions.pipeline import PipelineDefinition
from dagster.core.definitions.resource import ResourceDefinition, ScopedResourcesBuilder
from dagster.core.instance import DagsterInstance
from dagst... |
"""Tiles, number swapping game.
Exercises
1. Track a score by the number of tile moves.
2. Permit diagonal squares as neighbors.
3. Respond to arrow keys instead of mouse clicks.
4. Make the grid bigger.
"""
from random import *
from turtle import *
from freegames import floor, vector
tiles = {}
neighbors = [
... |
class TickPlacement(Enum,IComparable,IFormattable,IConvertible):
"""
Specifies the position of tick marks in a System.Windows.Controls.Slider control with respect to the System.Windows.Controls.Primitives.Track that the control implements.
enum TickPlacement,values: Both (3),BottomRight (2),None (0),TopLeft (1)
... |
# We will go through our S&P 500 JSON Data and merge it into CouchDB
import sys, argparse, os
import urllib.request
import requests
import json
numerrors = 0
def main(args):
global numerrors
chunklen=0
symbols=[]
sp500_json=args.infile.read()
sp500_symbols=json.loads(sp500_json)
args.infile.close()
for ... |
import time
#from django.shortcuts import render
from django.views.generic import TemplateView, FormView
from django.shortcuts import redirect, render
from django.db import transaction
from agda.views import package_template_dict
from jobs.models import (JOB_STATUS_LEVEL_ACCEPTED,
JOB_STATUS_... |
from django.core import validators
from django.db import models
class ExtraField(models.Model):
class FieldTypeChoices(models.IntegerChoices):
STRING = 1
INTEGER = 2
field_name = models.CharField(max_length=255, null=True, blank=True)
value_type = models.IntegerField(choices=FieldTypeChoi... |
""" Currency """
import json
import os
from datetime import datetime
import config
from util import date_time
from update import old_currency, currency_update
_CURR_CONV_FILE_PREFIX = "currency_conv"
_CURR_CONV_FILE_EXTENSION = "json"
_CURR_CONV_FILE = "currency_conv.json"
def save_currency_conv(conv_as_dict: {}):
... |
from collections import OrderedDict
from django.conf import settings
from django.contrib.auth.decorators import login_required, user_passes_test
from django.core.exceptions import PermissionDenied
from django.core.mail import send_mail, EmailMessage
from django.db import transaction
from django.http import HttpRespons... |
from __future__ import division
'''
Created on Dec 3, 2012
@author: jason
'''
from util.mlExceptions import *
import os
from inspect import stack
from scipy.io import loadmat
import pickle as pkl
from scipy.cluster.vq import *
from collections import Counter
from numpy.linalg import norm
import numpy as np
from evalu... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# Copyright (C) 2019-2021 Megvii Inc. All rights reserved.
import torch
import torch.nn as nn
import torch.nn.functional as F
from .tree_filter_core import MinimumSpanningTree, RandomSpanningTree, TreeFilter2D
class TreeFilterV2(nn.Module):
def __init__(self, guide_cha... |
#!usr/bin/env/python
import sys
from enum import Enum
from datetime import timedelta, date
import psycopg2
from basketball_reference_web_scraper import client
from basketball_reference_web_scraper.data import Team
import auth
import log
from scraper_lib import daterange, benchmark
@benchmark
def parse_and_input(score,... |
import numpy as np
import pandas as pd
import trading_env
from datetime import datetime
st = datetime.now()
## need to refactor the testcase
# df = pd.read_csv('trading_env/test/data/SGXTWsample.csv', index_col=0, parse_dates=['datetime'])
df = pd.read_hdf('D:\[AIA]\TradingGym\dataset\SGXTWsample.h5', 'STW')
env = t... |
#!/usr/bin/env python
# coding: utf-8
# Author: Vladimir M. Zaytsev <zaytsev@usc.edu>
import os
import numpy
import shutil
import logging
import argparse
from sear.index import InvertedIndex # The index itself.
from sear.utils import IndexingPipeline # Utility which will control indexing p... |
'''
Camera Example
==============
This example demonstrates a simple use of the camera. It shows a window with
a buttoned labelled 'play' to turn the camera on and off. Note that
not finding a camera, perhaps because gstreamer is not installed, will
throw an exception during the kv language processing.
'''
# Uncomme... |
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'cryptotracker.settings')
try:
from django.core.management import execute_from_command_line
excep... |
# Copyright The IETF Trust 2014-2021, All Rights Reserved
# -*- coding: utf-8 -*-
from django.urls import reverse as urlreverse
from unittest import skipIf
skip_selenium = False
skip_message = ""
try:
from selenium import webdriver
from selenium.webdriver.chrome.service import Service
from selenium.webdr... |
"""Module providing common functions used for analytics."""
import os.path
from dbispipeline.analytics import extract_gridsearch_parameters
from dbispipeline.db import DB
import matplotlib.pyplot as plt
import pandas as pd
def get_results(project_name, filter_git_dirty=True):
"""Returns the results stored in the... |
"""Base implementation for all modbus platforms."""
from __future__ import annotations
from abc import abstractmethod
from datetime import timedelta
import logging
import struct
from typing import Any
from homeassistant.const import (
CONF_ADDRESS,
CONF_COMMAND_OFF,
CONF_COMMAND_ON,
CONF_COUNT,
CO... |
#!/usr/bin/env python
import rospy
import numpy as np
from cv_bridge import CvBridge, CvBridgeError
from sensor_msgs.msg import Image
from std_msgs.msg import Float32
from duckietown_msgs.msg import SegmentList, Segment, Pixel, LanePose, BoolStamped, Twist2DStamped
from scipy.stats import multivariate_normal, entropy
f... |
#Import sessions for session handling
import webapp2
from webapp2_extras import sessions
#This is needed to configure the session secret key
#Runs first in the whole application
session_config = {}
session_config['webapp2_extras.sessions'] = {
'secret_key': 'my-super-secret-key-somemorearbitarythingstosay',
}
#Se... |
from celery import task
from .models import Bid
from django.conf import settings
import requests
@task
def check_for_bid_confirmation(bid_id):
bid = Bid.objects.get(id=bid_id)
item = bid.item
item.buyer = bid.current_bidder
item.cost_sold = bid.current_highest
item.save()
bid.delete()
prin... |
def reverseList(head, tail):
prev = None
while prev != tail:
prev, prev.next, head = head, prev, head.next
return prev
def reverseNodesInKGroups(l, k):
if k < 2:
return l
p = ListNode(-1)
p.next = l
ret = p
while True:
flag = True
tmp = p
for i ... |
# -*- coding: utf-8 -*-
"""tick module
"""
# License: BSD 3 clause
import tick.base |
import argparse
import os
import random
import torch
from torch import distributed as dist
from torch.utils.data import DataLoader
from torch.nn.parallel import DistributedDataParallel as DDP
from torch.utils.data.distributed import DistributedSampler
import torch.nn as nn
import torch.nn.functional as F
import numpy ... |
#!/usr/bin/env python3
# Copyright (c) 2017-2018 The BitsCoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test wallet replace-by-fee capabilities in conjunction with the fallbackfee."""
from test_framework.te... |
from conans import ConanFile, CMake
class AbcConan(ConanFile):
generators = "cmake", "cmake_find_package"
requires = "boost/1.76.0"
def build(self):
cmake = self.cmake
cmake.configure()
cmake.build()
@property
def cmake(self):
return CMake(self) |
from matplotlib import pyplot as plt
from .utils import make_img_grid
def plot_dataset(x, y, h_axis="char", v_axis="font", n_row=20, n_col=40, hide_axis=False):
img_grid, h_values, v_values = make_img_grid(x, y, h_axis, v_axis, n_row, n_col)
plt.tight_layout()
plt.imshow(img_grid)
plt.xlabel(h_axi... |
#MIT License
#Copyright (c) 2021 Sangram Ghangale
#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, pub... |
# requires: selenium, geckodriver
# Somewhat deprecated. Only use if desparate.
import json
__all__ = ["interactive_school_login"]
def interactive_school_login(school="berkeley"):
"""
Uses Selenium to interactively grab tokens from an interactive saml login.
Returns the cookies obtained.
You can sa... |
# Copyright 2016 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
"""Add slate information dynamically."""
# Import built-in modules
from datetime import datetime
import os
from tempfile import mkdtemp
# Import third-party modules
import examples._psd_files as psd # Import from examples.
# Import local modules
from photoshop import Session
PSD_FILE = psd.get_psd_files()
file_pa... |
# Generated by Django 3.0.7 on 2020-07-01 18:26
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUT... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
import uuid
from typing import Sequence
from visions.types.string import String
from visions.types.uuid import UUID
@UUID.contains_op.register
def uuid_contains(sequence: Sequence, state: dict) -> bool:
return all(isinstance(value, uuid.UUID) for value in sequence)
@UUID.register_transformer(String, Sequence)
... |
from fastapi import FastAPI
from raddar.api.api_v1.api import api_router
from raddar.db.database import engine
from raddar.models import models
from raddar.core.settings import settings
models.Base.metadata.create_all(bind=engine)
app = FastAPI()
# app = FastAPI(
# title=settings.PROJECT_NAME, openapi_url=f"{se... |
import torch
import numpy as np
class CategoriesSamplerBak():
def __init__(self, label, n_batch, n_cls, n_per): #n_batch 为 一个epoch的episode数亩
self.n_batch = n_batch
self.n_cls = n_cls
self.n_per = n_per
self.n_step = 0
self.mark = {}
self.r_clses = None
... |
valores = input().split()
A = int(valores[0])
B = int(valores[1])
C = int(valores[2])
maior = max(A, B, C)
print(str(maior)+' eh o maior') |
# -*- coding: utf-8 -*-
#
# EDguess.py - combines multiple automated approaches to identifying EDs into one shapefile
#
from histcensusgis.points.geocode import check_matt_dependencies, initial_geocode
from histcensusgis.microdata.misc import create_addresses
from histcensusgis.s4utils.AmoryUtils import *
from histce... |
import os
import re
import sys
import json
import time
import math
import errno
import random
import select
import signal
import socket
import logging
from six import reraise
from six.moves import _thread as thread
from six.moves.http_client import OK, TEMPORARY_REDIRECT, SERVICE_UNAVAILABLE
from six.moves.urllib.parse... |
"""
Generates a 3-D stomach mesh along the central line, with variable
numbers of elements around esophagus and duodenum, along and through
wall, with variable radius and thickness along.
"""
from __future__ import division
import math
import copy
from scaffoldmaker.annotation.annotationgroup import AnnotationGroup, m... |
import textwrap
import unittest
from databutler.datana.generic.corpus.code import DatanaFunction
from databutler.datana.viz.corpus.code_processors import VizMplAxesCounter
from databutler.utils import multiprocess
from databutler.utils.libversioning import modified_lib_env
def _runner(func: DatanaFunction):
# N... |
# @file Rotate Function
# @brief Calculate the maximum value of F(0), F(1), ..., F(n-1).
# https://leetcode.com/problems/rotate-function/
'''
Given an array of integers A and let n to be its length.
Assume Bk to be an array obtained by rotating the array A k positions clock-wise, we define a "rotation function" F o... |
from __future__ import division
from __future__ import print_function
from __future__ import absolute_import
import unittest
from unittest import skip
import sys
import os
import numpy as np
np.random.seed(1234)
from deeplift.conversion import kerasapi_conversion as kc
import deeplift.layers as layers
from deeplift.lay... |
# AdamP
# Copyright (c) 2020-present NAVER Corp.
# MIT license
import torch
from torch.optim.optimizer import Optimizer
import math
class AdamP(Optimizer):
"""
Paper: "AdamP: Slowing Down the Slowdown for Momentum Optimizers on Scale-invariant Weights"
Copied from https://github.com/clovaai/AdamP/
C... |
# This Python module is part of the PyRate software package.
#
# Copyright 2017 Geoscience Australia
#
# 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/... |
"""
Configuration for docs
"""
# source_link = "https://github.com/[org_name]/rh"
# docs_base_url = "https://[org_name].github.io/rh"
# headline = "App that does everything"
# sub_heading = "Yes, you got that right the first time, everything"
def get_context(context):
context.brand_html = "RH" |
"""
Copyright (c) 2018, salesforce.com, inc.
All rights reserved.
SPDX-License-Identifier: BSD-3-Clause
For full license text, see the LICENSE file in the repo root or https://opensource.org/licenses/BSD-3-Clause
This module has methods that return information about the monorepo structure.
Whenever possible, the cod... |
"""AICloudAlbum URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-... |
'''
immutable
'''
letters = ("a", "b", "c", "d", "c")
print(letters.count("c"))
print(letters.index("d"))
coordinates = (94, 6, 7)
x, y, z = coordinates
print(x, y, z) |
import os
import subprocess
from nmigen.build import *
from nmigen.vendor.lattice_ice40 import *
from .resources import *
__all__ = ["TinyFPGABXPlatform"]
class TinyFPGABXPlatform(LatticeICE40Platform):
device = "iCE40LP8K"
package = "CM81"
default_clk = "clk16"
resources = [
Res... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
import http_helper as http
_kPaths = {
# get
'getTransaction': '/api/transactions/get',
# get
'getTransactions': '/api/transactions',
# get
'getUnconfirmedTransaction': '/api/transactions/unconfirmed/get',
# get
'getUnconfirmedTransaction... |
from .lookup_provider import LookupProvider
class MerriamProvider(LookupProvider):
'''Concrete provider which provides web results from Merriam-Webster
dictionary.
'''
def lookup(self, word, limit=0):
'''Yield str results for `word` up to `limit`. When `limit == 0`,
return all results.... |
from queue_with_stacks.stack_and_queue import Stack
class PseudoQueue:
def __init__(self):
self.front=Stack()
self.rear=Stack()
def enqueue(self,value):
if value!= None:
self.front.push(value)
return self.front.top.value
else:
return Fals... |
# orm/util.py
# Copyright (C) 2005-2020 the SQLAlchemy authors and contributors
# <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
import re
import types
import weakref
from . import attributes # noqa
from .base impo... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
"""
en locale file.
It has been generated automatically and must not be modified directly.
"""
from .custom import translations as custom_translations
locale = {
"plural": lambda n: "one"
if ((n == n and ((n == 1))) and (0 == 0 and ((0 == 0)))... |
# Generated by Django 3.2.5 on 2021-07-02 16:38
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0012_alter_user_first_name_max_length'),
]
operations = [
migrations.CreateModel(
name='User',
... |
from textwrap import dedent
from pandas.compat.numpy import function as nv
from pandas.util._decorators import Appender, Substitution
from pandas.core.window.common import WindowGroupByMixin, _doc_template, _shared_docs
from pandas.core.window.rolling import _Rolling_and_Expanding
class Expanding(_Rolling_and_Expan... |
"""
TencentBlueKing is pleased to support the open source community by making
蓝鲸智云PaaS平台社区版 (BlueKing PaaSCommunity Edition) available.
Copyright (C) 2017-2018 THL A29 Limited,
a Tencent company. All rights reserved.
Licensed under the MIT License (the "License");
you may not use this file except in compliance with the... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# File: load-cpm.py
# Author: Yuxin Wu <ppwwyyxxc@gmail.com>
import cv2
import tensorflow as tf
import numpy as np
import argparse
from tensorpack import *
from tensorpack.utils import viz
from tensorpack.utils.argtools import memoized
"""
15 channels:
0-1 head, neck
2-4... |
import os
import sys
import logging
from .misc import makedirs
from .disassembler import disassembler
#------------------------------------------------------------------------------
# Log / Print helpers
#------------------------------------------------------------------------------
def lmsg(message):
"""
Pr... |
"""Custom authentication backends for the booking app."""
from django.contrib.auth.backends import ModelBackend
from .models import Booking
class BookingIDBackend(ModelBackend):
"""
Custom authentication backend that allows login via email and booking ID.
"""
def authenticate(self, username=None, pa... |
from game2048.game import Game
from game2048.displays import Display
def single_run(size, score_to_win, AgentClass, **kwargs):
game = Game(size, score_to_win)
agent = AgentClass(game, display=Display(), **kwargs)
agent.play(verbose=True)
return game.score
if __name__ == '__main__':
GAME_SIZE = 4... |
from unicodedata import name
import jmespath
from util.logger import get_logger
from util.decoder import decode
class TransactionTransformer:
def __init__(self) -> None:
self.logger = get_logger(__name__)
@staticmethod
def transform(raw_transactions):
payloads = jmespath.search('[*].payl... |
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# Copyright 2011 Justin Santa Barbara
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance wi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.