content stringlengths 5 1.05M |
|---|
from distutils.core import setup
setup(
name='pystream', # How you named your package folder (MyLib)
packages=['pystream'], # Chose the same as "name"
version='0.2', # Start with a small number and increase it with every change you make
license='MIT', # Chose a license from here: https://help.githu... |
from typing import TypeVar, Mapping, Any, List, Generic, Type, overload
from brigadier import Command, RedirectModifier, ImmutableStringReader
from brigadier.tree import CommandNode
S = TypeVar('S')
T = TypeVar('T')
V = TypeVar('V')
# necessary for type hint linting to understand that the class exists >:(
class Str... |
#!/usr/bin/env python
# coding: utf-8
# DO NOT EDIT
# Autogenerated from the notebook statespace_sarimax_pymc3.ipynb.
# Edit the notebook and then sync the output with this file.
#
# flake8: noqa
# DO NOT EDIT
# # Fast Bayesian estimation of SARIMAX models
# ## Introduction
#
# This notebook will show how to use fas... |
#####################################################################################
#
# Copyright (c) Microsoft Corporation. All rights reserved.
#
# This source code is subject to terms and conditions of the Apache License, Version 2.0. A
# copy of the license can be found in the License.html file at the root of t... |
import uuid
from django.conf import settings
from django.db import models
from django.db.models import signals
from django.utils import timezone
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _
from django.contrib.auth.models import User
from main_app... |
# constants.py
# Walker M. White (wmw2)
# November 12, 2014
"""Constants for Breakout
This module global constants for the game Breakout. These constants
need to be used in the model, the view, and the controller. As these
are spread across multiple modules, we separate the constants into
their own module. This allo... |
# -*- coding: utf-8 -*-
'''Chemical Engineering Design Library (ChEDL). Utilities for process modeling.
Copyright (C) 2016, 2017 Caleb Bell <Caleb.Andrew.Bell@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to... |
from rtamt.exception.stl.exception import STLException
from rtamt.exception.stl.exception import STLParseException
from rtamt.exception.stl.exception import STLOfflineException
from rtamt.exception.stl.exception import STLSpecificationException
from rtamt.exception.stl.exception import STLNotImplementedException
from r... |
from typing import Optional
from starlette.config import Config
from starlette.datastructures import Secret
config = Config(env_file=".env")
# whether the application is in development mode.
DEBUG: bool = config("DEBUG", cast=bool, default=False)
# SQLAlchemy database URL.
DATABASE_URL: str = config("DATABASE_URL"... |
import cv2
from sys import argv
from numpy import histogram, arange, linspace, concatenate
from matplotlib.pyplot import plot, show, xticks, yticks, title
art = 'Pollock No. 5.png' if len(argv) < 0b10 else argv[1]
img = cv2.cvtColor(cv2.imread(f'{art}'), cv2.COLOR_BGR2RGB)
redux = lambda x: x[0]
hR, hG, hB = [redux... |
import glob, os, shutil, random
SEED = 1
image_dir = "D:/data/fashion/image_retrieval/cafe24multi/images_mall_prd"
output_dir = "D:/data/fashion/image_retrieval/cafe24multi/images_split_train_test"
train_dir = os.path.join(output_dir, "train")
test_dir = os.path.join(output_dir, "test")
mall_id_list = os.listdir(image... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 26 11:00:38 2018
@author: ddeng
"""
import pickle
import pdb
def read_file(file):
main_dict = {}
for line in file:
line = line.strip('\n')
line = line.strip('\t')
[vid, uttr, pos_uttr, neg_uttr, pos_vid, neg_vid,words... |
from utils.views import ContactViewSet, IssueViewSet
drf_routers = (
('contact', ContactViewSet),
('issue', IssueViewSet)
)
|
# Copyright (C) 2014 Universidad Politecnica de Madrid
#
# 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 la... |
from sqlalchemy import Column, Integer, ForeignKey
from sqlalchemy.orm import relationship
from sqlalchemy.ext.associationproxy import association_proxy
from app.db.base_class import Base
class FilmActor(Base):
__tablename__ = "film_actors"
film_id = Column(Integer, ForeignKey("films.id"), primary_key=True)
... |
import json
from functools import partial
import geopandas as gpd
import pandas
import pytest
import scipy
import xarray
from numpy.testing import assert_almost_equal
from packaging import version
from rasterio.enums import MergeAlg
from shapely.geometry import mapping
from shapely.wkt import loads
from geocube.api.c... |
from AutoRegPilot import Linear_Regression, Loess_Regression, Polynomial_Regression
import numpy as np
import matplotlib.pyplot as plt
from timeit import default_timer as timer
"""
Line_Plotter.plot(plotlist="LR,PR,CF,LSS",title="Tablom")
Loess_Regression.Plotter()
"""
Signal = np.array(
[
100, 11, 101, ... |
from setuptools import setup, find_packages
setup(
name='ravop',
version='0.1-alpha',
packages=find_packages(),
install_requires=[
"numpy==1.20.1"
],
dependency_links=[
"https://github.com/ravenprotocol/ravcom.git@0.1-alpha"
]
)
|
from unittest import TestCase, mock
import aiocometd_chat_demo.__main__ as main
from aiocometd_chat_demo.chat_service import ChatService
from aiocometd_chat_demo.channels import ChannelsModel
from aiocometd_chat_demo.conversation import ConversationModel
from aiocometd_chat_demo._metadata import VERSION, AUTHOR, AUTHO... |
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Div, HTML, Layout, Submit
from dal import autocomplete
from django.utils.translation import ugettext, ugettext_lazy
from maps.forms.base import BaseForm
from maps.model.institute import Institute
from maps.model.type import Type
class Institu... |
# -*- coding: utf-8 -*-
# @Time : 2021/11/8 10:55
# @Author : yanqun.jiang
# @File : utils.py
import time
def print_run_time(func):
"""
本模块作用是打印程序运行时间
:param func: 要计算程序的时间
:return:
"""
def wrapper(*args, **kwargs):
start_time = time.time()
func(*args, **kwargs)
... |
import pandas as pd
import numpy as np
import succolib as sl
import inspect
###############################################################################
###############################################################################
def peakedDistMode(series):
if len(series.unique()) <= 1:
centre = 0
... |
from expungeservice.models.disposition import DispositionStatus
from tests.factories.crawler_factory import CrawlerFactory
from tests.fixtures.case_details import CaseDetails
from tests.fixtures.john_doe import JohnDoe
from expungeservice.models.record import Record
from expungeservice.util import DateWithFuture as dat... |
from tsdb.dictdb import *
from tsdb.tsdb_client import TSDBClient
from tsdb.tsdb_server import *
from tsdb.tsdb_serialization import *
from tsdb.tsdb_ops import *
from tsdb.tsdb_rest_client import TSDB_REST_Client |
# Copyright (c) MONAI Consortium
# 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, so... |
import os
import omlet.utils as U
from pytorch_lightning.callbacks import Callback
class SourceCodeBackup(Callback):
master_only = True
def __init__(self,
exp_dir,
source_dir,
include_pattern=('*.py', '*.sh'),
subdir='code'):
"""
... |
import json
import shutil
import tarfile
import tempfile
from multiprocessing import Pool, cpu_count
from pathlib import Path
from typing import List, Union
import click
import pandas as pd
import rouge
import torch
from models import Model
from reader import ReviewTest, OptimusTest
from tokenizer import Tokenizer
fr... |
from __future__ import annotations
from typing import TYPE_CHECKING
import random
from itertools import product
from py_rete.bind_node import BindNode
from py_rete.filter_node import FilterNode
from py_rete.ncc_node import NccPartnerNode
from py_rete.ncc_node import NccNode
from py_rete.negative_node import NegativeNo... |
import time
from enum import IntEnum
from typing import Tuple, Any
import pygame as pg
from pygame.surface import Surface
from bomber_monkey.features.board.board import Board
from bomber_monkey.features.board.board_display_system import BoardDisplaySystem
from bomber_monkey.features.board.board_system import BoardSys... |
import matplotlib.pyplot as plt
from transform_images import unscale
def view_dataset(images):
# plot emojis in order
lines = 12
f, axarr = plt.subplots(lines, lines, sharex=True, sharey=True, figsize=(12, 12))
for i in range(lines ** 2):
a = axarr[i % lines, i // lines]
img = images[... |
import os, sys
from matplotlib import pyplot as plot
import numpy as np
import matplotlib
from analysis_config import *
numFigs = 0
numTrials = 0
numTrialsInj = 0
colors = ['g','b', 'y', 'm', 'c', 'r']
TYPES = ["Arith-FP", "Pointer", "Arith-Fix", "Ctrl-Loop", "Ctrl-Branch"]
TYPES_LONG = ["Floating-Point", "Pointer", ... |
from bitcoin import *
import hashlib
import json
from time import time
import requests
from src.proof_of_work import ProofOfWork
from src.mempool import Mempool
from src.network import Network
class Blockchain:
def __init__(self):
self.chain = []
# Instantiate mempool
self.mempool = Memp... |
from django.contrib import admin
from rest_framework.authtoken.models import Token
from rangefilter.filter import DateRangeFilter
from room.models import Room, Scheduling
from room.forms import SchedulingForm
admin.site.site_header = 'Administração Agendador'
@admin.register(Room)
class RoomAdmin(admin.ModelAdmin):... |
import datetime
print(datetime.date(2000,1,2))
|
from celery import Celery
celery = Celery(__name__, autofinalize=False)
|
import json
from openpyxl import Workbook
from openpyxl.styles import Font, Border, Side, PatternFill, colors, Alignment
res_file = open('../models/lstm_crf/results_dde/score/testa.preds.txt', encoding='utf-8')
wb = Workbook()
wb.create_sheet('分类准确率,召回率,f1值')
ws = wb['Sheet']
ws1 = wb['分类准确率,召回率,f1值']
data = [[0, 0, 0... |
from sim.evaluation.metric.PacketMetric import *
from sim.utils.helper import *
class MetricEvaluation:
def __init__(self):
pass
def execute(self,
sqr_nodes,
connectivity,
randomize_boot,
sec_before_inject,
sec_after_inj... |
#store features in database
# we get dictionary to store id, word
# we get tfidf scores for reach document as (id,score) where we map id to dictionary to get word
# so each document or sentence is converted to word and its tfidf score. these are features we store in db
import pandas as pd
import numpy as np
import ma... |
#!/usr/bin/env python
'''
Parses input/output formats,
manages transformations
'''
import csv
import re
import sys
from numpy import array
import numpy as np
import pandas as pd
from pandas import *
from . import config
from . import distance
from . import store
from . import stats
from . import HSIC
def wrap_feat... |
import cProfile
import os
import gzip
import csv
import time
from collections import defaultdict
from itertools import combinations
from pybloomfilter import BloomFilter
#from pybloom import ScalableBloomFilter, BloomFilter #pybloom used cryptographic hashes in a bloom filter. This is a bad idea.
import numpy
class B... |
from .settings import *
SECRET_KEY = 'NOTREALLY'
|
def new2(n,operations):
a=[0 for i in range(n)]
for i in operations:
if "L" in i:
for i in range(len(a)):
if a[i]==0:
a[i]=1
break
else:
continue
elif "C" in i:
a[int(i[1])]=0
return a
print(new2(2... |
# Copyright 2016 Hewlett Packard Enterprise Development Company LP
#
# Author: Federico Ceratto <federico.ceratto@hpe.com>
#
# 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.... |
"""
A context processor which adds the value of the
``COMMENTS_MODERATE_AFTER`` setting to each ``RequestContext`` in
which it is applied.
"""
from template_utils.context_processors import settings_processor
comment_moderation = settings_processor('COMMENTS_MODERATE_AFTER')
|
"""Generate JSON-LD contexts
"""
import logging
import os, re
import sys
from typing import Union, TextIO, List, Optional, Dict
import click
from jsonasobj import JsonObj, as_json, as_dict
from prefixcommons import curie_util as cu
from metamodel.metamodel import SchemaDefinition, SlotDefinition, ClassDefinition, El... |
"""Write a version of a palindrome recogniser that accepts a file name
from the user, reads each line, and prints the line to the screen if it
is a palindrome."""
file_name = 'palindromes.txt'
def palindrome_recognizer(file_name):
pass
print(palindrome_recognizer(file_name)) |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = "Han"
__email__ = "liuhan132@foxmail.com"
import random
import numpy as np
import torch
from torch.utils.data.sampler import Sampler
class ValidDocBatchSampler(Sampler):
def __init__(self, valid_doc_nums, batch_size, shuffle=True, strict=True):
... |
import numpy as np, argparse, pickle
import matplotlib; matplotlib.use('agg')
import matplotlib.pyplot as plt
from sklearn.metrics import precision_recall_curve, average_precision_score
import pdb
def loadData(path):
preds = pickle.load(open(path, 'rb'))
y_hot = np.array(preds['y_hot'])
logit_list = np.a... |
""" An example to demonstrate the use of partitions.
(Working, but not up-to-date, as in not using latest functionalities.)
"""
from grom import Genome
Genome.DEBUG = False
e = Genome("examples/src/kdl.gb", "examples/test.gb")
print(e, end="\n\n\n")
e.partition([
("hello", range(0X0, 0x6543)),
(... |
import collections
import heapq
import numpy as np
import pandas as pd
import scipy.stats as ss
class EpidemicModel(object):
"""
Every of the epidemic models below inherits from this class, which defines
the infrastructure of the event by event principle. The class supplies the
exposure process depend... |
import json
import time
from collector.collector import Collector
class TransactionCollector(Collector):
def __init__(self, logger, web3, db):
super().__init__(logger, web3, db)
def __get_transaction(self, from_block, to_block):
"""
TODO:
parallel execute for performance or a... |
# Copyright 2019 Capital One Services, LLC
# Copyright The Cloud Custodian Authors.
# SPDX-License-Identifier: Apache-2.0
#
from c7n_kube.query import QueryResourceManager, TypeInfo
from c7n_kube.provider import resources
@resources.register('volume')
class PersistentVolume(QueryResourceManager):
class resource_t... |
import os.path
from . import *
class TestCommand(IntegrationTest):
def __init__(self, *args, **kwargs):
super().__init__(os.path.join(examples_dir, '08_commands'), *args,
**kwargs)
def test_hello(self):
self.assertRegex(self.build('hello'), r'(?m)^\s*hello$')
de... |
import sqlite3 as sq3
class SQLCursor():
def cleanup(self):
if self.connection is not None:
self.connection.close()
self.connection = None
self.cursor = None
def open(self):
try:
self.connection = sq3.connect(self.filename)
self.curs... |
import importlib
import itertools
from collections import defaultdict
from pathlib import Path
import click
import numpy as np
import pandas as pd
import rich_click
from loguru import logger
from sqlite_utils import Database
from .. import DATA_DIR
from ..utils import determine_file_name
from .etl import generate_etl... |
class HeroDoesNotExistError(Exception):
"""The specified hero does not exist."""
|
""" __init__.py."""
from .nbplugins_watch import nbplugins_watch, _watch_n_reload # noqa: F401
__version__ = "0.0.6"
VERSION = __version__.split(".")
|
# =============================================================================
#
# Copyright (c) Kitware, Inc.
# All rights reserved.
# See LICENSE.txt for details.
#
# This software is distributed WITHOUT ANY WARRANTY; without even
# the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
# PURPOSE.... |
# Generated by Django 3.2.6 on 2021-08-08 01:56
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='App',
fields=[
... |
# Client settings
BASE_URL = "https://api.mopinion.com"
TOKEN_PATH = "/token"
LATEST_VERSION = "2.0.0"
# Some settings for dataclasses
VERBOSITY_lEVELS = ["quiet", "normal", "full"]
ITERATE_VERBOSITY_lEVELS = ["normal", "full"]
VERSIONS = ["1.18.14", "2.0.0"]
CONTENT_NEGOTIATIONS = ["application/json", "application/x-... |
"""
:copyright: (c)Copyright 2013, Intel Corporation All Rights Reserved.
The source code contained or described here in and all documents related
to the source code ("Material") are owned by Intel Corporation or its
suppliers or licensors. Title to the Material remains with Intel Corporation
or its suppliers and lice... |
from __future__ import print_function
from .generalized import Scraper
class Baidu(Scraper):
"""Scrapper class for Baidu"""
def __init__(self):
Scraper.__init__(self)
self.url = 'https://www.baidu.com/s'
self.newsURL = 'http://news.baidu.com/ns'
self.defaultStart = 0
s... |
"""
pygments.lexers.berry
~~~~~~~~~~~~~~~~~~~~~
Lexer for Berry.
:copyright: Copyright 2006-2022 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import re
from pygments.lexer import RegexLexer, words, default, include, bygroups
from pygments.token import Text, Comme... |
__author__ = 'Nicholas C Pandolfi'
import os
import sys
from multiprocessing import Process
from .lrtools import addspace, removespace, checkdate
from itertools import islice
BUFFERSIZE = 1024 ** 2
class NotCompiledError(Exception):
'''
This error is called when the user tried to load
from a '.lrdict' fi... |
from experimaestro import param, config, option
from onir import datasets
@param('qlen', default=5)
@param('dlen', default=500)
@param('count', default=10000)
@config()
class RandomDataset(datasets.Dataset):
"""
Dataset producing random samples, used for controlled tests in scripts/perf_benchmark.py
"""
... |
from tournament_of_lulz.modules.top_images.model_top_images import ModelTopImages
from tournament_of_lulz.modules.top_images.view_top_images import ViewTopImages
def get(db_connection, data):
start = 0
limit = 10
if 'start' in data:
start = int(data['start'])
if 'limit' in data:
limit... |
class BaseItem(object):
def __init__(self):
super(BaseItem, self).__init__()
|
# encoding: utf-8
__author__ = "Dimitrios Karkalousos"
import argparse
import gc
import pathlib
import sys
import time
from collections import defaultdict
from typing import Any, Dict, Tuple, Union
import numpy as np
import torch
from torch.utils.data import DataLoader
from mridc import save_reconstructions, rss
fro... |
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
def override_formerly_core_masked_filter(*args, **kwargs):
return 'hello from overridden formerly_core_masked_filter'
class FilterModule(object):
def filters(self):
return {
'formerly_core_masked_filt... |
import numpy as np
import os
import glob
import pandas as pd
import cv2
from xml.etree import ElementTree
import random
import shutil
import glob
from PIL import Image
for dirname in os.listdir("tmp"):
print(dirname)
for fpath in glob.glob(os.path.join("fullsizeimg",dirname,"original","*")):
img=Image.... |
# coding: utf-8
import asyncio
import itchat
from .config import (LOG_TEMPLATE_START_SEND, LOG_TEMPLATE_SEND_FAILED,
LOG_TEMPLATE_UPLOAD_FAILED, LOG_TEMPLATE_DOWNLOAD_FAILED)
from .logger import logger
from .chatroom import chatroom
from .cralwer import get_sticker_urls
from .util import get_file
... |
import airflow.utils.dates
from airflow import DAG
from airflow.sensors.filesystem import FileSensor
from airflow.operators.dummy_operator import DummyOperator
from airflow.operators.bash import BashOperator
source_name = 'camera1'
source_path = 'camera'
file_pattern = '*.jpeg'
destentation_path = 'output'
dag = DAG... |
from visual import *
giant = sphere()
giant.pos = vector(-1e11,0,0)
giant.radius = 2e10
giant.color = color.red
giant.mass = 2e30
giant.p = vector(0, 0, -1e4) * giant.mass
dwarf = sphere()
dwarf.pos = vector(1.5e11,0,0)
dwarf.radius = 1e10
dwarf.color = color.yellow
dwarf.mass = 1e30
dwarf.p = -giant.p
... |
#!/usr/bin/env python3
# ------------------------------------------------------------------------
'''
This is a sample project that is added to the site. The idea here is
that nothing in this project can syntax error (down) the site, as it is
imported under a try: except clause, and it is calling only the
URL regi... |
import socket
import struct
import time
import threading
import select
class_name = 'fw'
manip_device_name = 'manipulations'
manip_attr_name = 'manipulations'
manip_inst_size = 14
ftp_manipulation_port = 210
NO_MANIPULATION_PORT = 0
MANIPULATION_CMD_INST = 0
MANIPULATION_CMD_FTP_DATA =1
# Helper method to turn an in... |
# loop through array
# add extra cokies at each array Index
# See if cookies is > than max
# Add true or false as necessary
class Solution:
def kidsWithCandies(self, candies: list[int], extraCandies: int) -> list[bool]:
mNum = max(candies)
store = []
for i in candies:
ie... |
from pettingzoo.atari import basketball_pong_v2
from pettingzoo.atari import boxing_v1
from pettingzoo.atari import combat_plane_v1
from pettingzoo.atari import combat_tank_v1
from pettingzoo.atari import double_dunk_v2
from pettingzoo.atari import entombed_competitive_v2
from pettingzoo.atari import entombed_cooperati... |
from flask import (Flask, g, Response, current_app)
from flask_cachual import Cachual, cached
from mock import mock, MagicMock
import cachual, pytest
def get_app():
return Flask(__name__)
@mock.patch('flask_cachual.Cachual.init_app')
def test_ctor_no_app(mock_init_app):
cachual = Cachual()
cachual.init... |
class Solution:
def divisorSubstrings(self, num: int, k: int) -> int:
result = 0
num = str(num)
for i in range(len(num)):
if i + k - 1 >= len(num):
break
if int(num[i: i + k]) == 0:
continue
if int(num) % int(num[i: i + k])... |
# groceries.py
#from pprint import pprint
products = [
{"id":1, "name": "Chocolate Sandwich Cookies", "department": "snacks", "aisle": "cookies cakes", "price": 3.50},
{"id":2, "name": "All-Seasons Salt", "department": "pantry", "aisle": "spices seasonings", "price": 4.99},
{"id":3, "name": "Robust Golden... |
from moonleap import u0
from moonleap.utils.inflect import plural
from moonleap.utils.magic_replace import magic_replace
from titan.api_pkg.pkg.ml_name import ml_type_spec_from_item_name
from titan.react_pkg.pkg.ts_var import ts_type, ts_type_import_path
from titan.react_state_pkg.itemview.props import get_item_view_ro... |
try:
prediction = stock["predictions"]["basic"][index]
current_action = prediction["action"]["current"]
previouse_action = prediction["action"]["previouse"]
action_flags = prediction["action_flags"]
key = int("".join(str(x) for x in action_flags), 2)
send_mail = False
map_action = {... |
import argparse
import os
import sys
sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), '..'))
import pynab.releases
from pynab.db import db_session, Pre, Release
from pynab import log
import config
def rename_pre_releases():
count = 0
with db_session() as db:
query = db.que... |
# Loss functions taken/inspired from Akensert's kaggle kernel
import numpy as np
import tensorflow as tf
from tensorflow import keras as K
def weighted_log_loss(y_true, y_pred):
"""
Can be used as the loss function in model.compile()
---------------------------------------------------
"""
#... |
#!/usr/bin/env python
from setuptools import setup
setup(name='pystran3',
version='0.3',
description='Set of diagnostic tools for model structure analysis',
url='https://github.com/stijnvanhoey/pystran',
author='Stijn Van Hoey',
author_email='stijnvanhoey@gmail.com',
packages=['pys... |
# src:
# https://www.geeksforgeeks.org/practice-questions-time-complexity-analysis/
"""
Name Big O
Constant O(c)
Linear O(n)
Quadratic O(n^2)
Cubic O(n^3)
Exponential O(2^n)
Logarithmic O(log(n))
Log Linear O(nlog(n))
"""
"""
1. What is the time, space complexity of following code:
int a = 0, b = 0;
fo... |
"""
General Resources for all API resources modules
"""
from flask_restful import Resource
class BaseResource(Resource):
def __init__(self, **kwargs):
self.repo = kwargs['data'] # repo: DataInterface
self.selector = kwargs['selector'] # selector: SelectInterface
|
_base_ = '../point_rend/point_rend_r50_caffe_fpn_mstrain_3x_coco.py'
# learning policy
runner = dict(type='EpochBasedRunner', max_epochs=200)
model = dict(
type='PointRend',
roi_head=dict(
type='PointRendRoIHead',
mask_head=dict(
_delete_=True,
type='CoarseMaskHead',
... |
# coding=utf-8
#
# Copyright © 2015 VMware, Inc. All Rights Reserved.
#
# 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, co... |
##################### README ###################################################
# This file executes the classification algorithm over input testing images.
# Winner neurons inhibit other neurons by a phenomenon called Lateral inhibition
# Spike for each output neuron at each time stamp is monitored.
#################... |
import time
def convert_to_underscore(record, timestamp_key):
""" Convert - to _ """
underscore_record = {}
for key, value in record.items():
underscore_record[key.replace("-", "_")] = value
return underscore_record
def convert_epoch_sec_to_iso8601(record, timestamp_key):
""" Convert epo... |
import pygeoip,os
def ipLocation(ip):
path,f = os.path.split(__file__)
fname = os.path.join(path, "GeoIP.dat")
gi = pygeoip.GeoIP(fname)
return gi.country_code_by_addr(ip)
|
__author__ = "ecaz.eth"
__author_email__ = "me@ecaz.xyz"
__description__ = "NFT metadata retrieval tool."
__license__ = "Apache 2.0"
__title__ = "right_click_save"
__url__ = "https://github.com/ecaz-eth/right-click-save"
__version__ = "0.1.0"
|
from thinkindicator.indicator import ThinkIndicator
ThinkIndicator().run()
|
import asyncio
import json
import beeprint
from loguru import logger
import websockets
from AsyncWebsocketStreamInterface import AsyncWebsocketStreamInterface
from HuobiAsyncWebsocket.UrlParamsBuilder import create_signature, UrlParamsBuilder
class HuobiAsyncWs(AsyncWebsocketStreamInterface):
ws_baseurl = 'wss... |
import numpy as np
import re
import json
import os
def read_obj(model_path, flags = ('v')):
fid = open(model_path, 'r', encoding="utf-8")
data = {}
for head in flags:
data[head] = []
for line in fid:
line = line.strip()
if not line:
continue
line = re.spli... |
"""Factory Boy factory classes for ``svdbs``."""
import binning
import factory
from ..models import (
DgvGoldStandardSvs,
DgvSvs,
ExacCnv,
ThousandGenomesSv,
DbVarSv,
GnomAdSv,
EXAC_POP_CHOICES,
)
class DgvGoldStandardSvsFactory(factory.django.DjangoModelFactory):
class Meta:
... |
from typing import Dict
from typing import List
class MediastackApiError(Exception):
def __init__(self, code: str, message: str, context: Dict[str, List[str]] = {}) -> None:
self.code = code
self.message = message
self.context = context
def __str__(self) -> str:
return f"code... |
import random
class Spell:
def __init__(self,name,cost,dmg,type):
self.name = name
self.cost = cost
self.dmg = dmg
self.type = type
def generate_spell_damage(self):
mgl = self.dmg - 15
mgh = self.dmg + 15
return random.randrange(mgl,mgh) |
#!/usr/bin/env python3
"""Get the Zappi history and import into InfluxDB.
This script will query the first zappi found to obtain a number of days history at the hourly level
It will then import a summary of this information into an influxdb database.
"""
import os
import argparse
import logging
import logging.handler... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.