content stringlengths 5 1.05M |
|---|
import argparse
import pandas as pd
import os
import sys
import numpy as np
import torch
from utils import computeMetricsAlt, evalThresholdAlt
from ModelShokri import DataHandler, TrainWBAttacker
from torch.utils.data import DataLoader
parser = argparse.ArgumentParser(description='Analyse criteria obtained from differ... |
from InstagramAPI import InstagramAPI as IG
from pprint import PrettyPrinter
from getpass import getpass
from random import randint
from datetime import datetime
import time
import yaml
import os
# Auto like user IG post by given list
pp = PrettyPrinter(indent=2)
count = 0
d1 = int(time.time())
print("============... |
"""
This file is part of the TheLMA (THe Laboratory Management Application) project.
See LICENSE.txt for licensing, CONTRIBUTORS.txt for contributor information.
Organization mapper.
"""
from sqlalchemy.orm import column_property
from everest.repositories.rdb.utils import as_slug_expression
from everest.repositories.... |
# Copyright (C) 2020 by Univeristy of Edinburgh
from numbers import Number
from typing import Any, List, Tuple
import numpy as np # type: ignore
import numpy.lib.mixins # type: ignore
import delayrepay.backend as be
_backend = be.backend
def cast(func):
"""cast to Delay array decorator"""
def wrapper(*a... |
from flask import Blueprint, render_template, abort, request, redirect, url_for, flash
from jinja2 import TemplateNotFound
from flask_login import current_user, logout_user, login_user, login_required
from .auth_forms import RegisterForm, LoginForm, ResetPasswordForm
from ..models import db, User, Post, Category
aut... |
import time
from kazoo.client import KazooClient
from kazoo.client import KazooState
import logging
logging.basicConfig()
def my_listener(state):
if state == KazooState.LOST:
# Register somewhere that the session was lost
print 'The session is lost: %s' % str(state)
elif state == KazooState.SUSPE... |
"""
Background:
===========
CTDpNUT_ncgen.py
Purpose:
========
Creates EPIC flavored, merged .nc files downcast ctd and nutrient data.
Data assumes a sparse grid for nutrient data, scales it up to the full 1m grid of
ctd data and then matches on depth. Finally, it writes a new file (mirrored to the... |
from .lib.sql_util import *
from .lib.mysql_lib import *
from .lib.pg_lib import *
from .lib.global_lib import *
from .gpss.data_pb2_grpc import *
from .gpss.data_pb2 import *
from .gpss.gpss_pb2_grpc import *
from .gpss.gpss_pb2 import *
|
from ..environment import Environment
import gym
#import roboschool
import torch
import numpy as np
class Gym_base(Environment):
def __init__(self, env_params):
super(Gym_base, self).__init__(env_params)
env_params = self.ingest_params_lvl1(env_params)
self.env = None
self.action_sp... |
import struct
from shared.lmdb_support import serialize_tuple_of_integers
def test_able_to_serialize():
data = (2506, 723526)
expected_output = b'\xca\t\x00\x00\x00\x00\x00\x00F\n\x0b\x00\x00\x00\x00\x00'
assert serialize_tuple_of_integers(data) == expected_output
def test_serialization_is_correct():
... |
import pyexcel as p
from common import get_fixtures
RANGE_COLOR = ['#313695', '#4575b4', '#74add1', '#abd9e9',
'#e0f3f8', '#ffffbf',
'#fee090', '#fdae61', '#f46d43', '#d73027', '#a50026']
def test_pie_chart():
s = p.get_sheet(file_name=get_fixtures('pie.csv'))
s.save_as('pie.ech... |
from call_views import *
from views import *
|
'''
models.py contains the persistence logic for Snakr.
'''
from django.db import models
from django.core.validators import URLValidator
from django.utils.translation import ugettext_lazy as _
from ipaddress import IPv6Interface, IPv4Interface, IPv6Address, IPv4Address, ip_interface
from snakraws import settings
fro... |
from django.conf.urls import include
from django.contrib import admin
from django.urls import re_path
from wagtail.admin import urls as wagtailadmin_urls
from wagtail.core import urls as wagtail_urls
from wagtail.documents import urls as wagtaildocs_urls
urlpatterns = [
re_path(r"^django-admin/", admin.site.urls),... |
import sys
import argparse
import pathlib
import os
import ast
from typing import *
from lib.lightning_train import generate_trainer
import torch
sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..'))
from models.lib.data import GeneExpressionData
from models.lib.neural import GeneClassifier
... |
# -*- coding: UTF-8 -*-
import os
# mongodb 连接配置
# MONGO_URI = 'mongodb://%s:%s@%s:%s/admin' % ('username', 'password', 'ip', 'port')
MONGODB_URI = 'mongodb://%s:%s@%s:%s/admin' % ('root', '123456', '127.0.0.1', '27017')
# 重要,不要修改
CLIENT_ID = '8d5227e0aaaa4797a763ac64e0c3b8'
CLIENT_SECRET = 'ecbefbf6b17e47ecb90351078... |
class RegionTopology:
@classmethod
def num_edges(cls):
return 4
@classmethod
def num_corners(cls):
return 4
@classmethod
def _edge_name_to_index_dict_(cls):
return {'U': 0, 'D': 1, 'L': 2, 'R': 3}
@classmethod
def _edge_name_to_index_(cls, _edge_name_):
... |
from typing import List
import spacy
import string
from src.lm_core import GPTLM
from .utils import plot_topk, draw_wordcloud, scatter_plot
import streamlit as st
nlp = spacy.load("en_core_web_sm")
gpt = GPTLM()
def analyse_text(articles: List, filters=None, probs_plot=False, starting_idx=0 ,
path... |
class PayGateway(object):
'''
@summary: the base class for pay gateway
'''
def create_order(self, orderItemObj, clientIp, **kwargs):
pass
def query_order(self, orderNo):
'''
@summary: query pay result of order
@return: PayResult
'''
pass... |
from django.urls import path
from .views import Providers, SetVariables
urlpatterns = [
path('set_variables/<slug:dns>/', SetVariables.as_view(), name="set-vars"),
path('all', Providers.as_view(), name="dns-providers"),
]
|
import socket
class BaseBackend(object):
"""
Base class for backend reporting storage.
settings_namespace is a class attribute that will be used to get the needed
parameters to create new backend instance from a settings file.
"""
settings_namespace = None
def report(self, name, metric, ... |
# Time: O(n^2)
# Space: O(n)
# 1301 biweekly contest 16 12/28/2019
# Given a square board of chars. You move on the board from the bottom right square marked with the char 'S'.
#
# You need to reach the top left square marked with the char 'E'. The rest of the squares are labeled
# either with a numeric char 1, 2, .... |
# Python GDB formatters for parallel-hashmap
# tested with GCC 10.2 / GDB 9.2
# to install it, ensure the script location is in the Python path
# and type the following command (or put it in $HOME/.gdbinit):
# python
# import phmap_gdb
# end
import gdb.printing
def counter():
i = 0
while(True):
yie... |
import glob
import os
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf
from matplotlib.image import imread
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import OneHotEncoder
# For image from url
from PIL import Image
import requests
from io import BytesIO
# %% Dat... |
# fizzbuzz.py
# Write a short program that prints each number from 1 to 100 on a new line.
# For each multiple of 3, print "Fizz" instead of the number.
# For each multiple of 5, print "Buzz" instead of the number.
# For numbers which are multiples of both 3 and 5, print "FizzBuzz" instead of the number.
for i in ran... |
from dataclasses import dataclass
from sqlalchemy.ext.declarative import as_declarative, declared_attr
@dataclass
@as_declarative()
class Base(object):
@declared_attr
def __tablename__(cls) -> str:
return cls.__name__.lower()
def json(self) -> dict:
dict_base = self.__dict__.copy()
... |
import xarray as xr
import numpy as np
from xhistogram.xarray import histogram
# Watermass transformation calculation
def _calc_shortwave_penetration(ds,xgrid):
R = 0.58
h1 = 0.35
h2 = 23
# Calculate in 1D
Fps77 = R*np.exp(-ds['depth_i']/h1)+(1-R)*np.exp(-ds['depth_i']/h2)
# Now get a 4D shor... |
import requests
import time
def bombus(number):
r=requests.session()
url="https://www.<redacted>.com/Personalization/SendOTP?mobile={}&phoneCode=91&OTPSource=SIGNIN".format(number)
proxy={'http':'45.7.231.86','http':'66.42.107.87:8080','http':'68.183.99.96:8080'}
headers={"Host":"www.redbus.in",
... |
# -*- coding: utf-8 -*-
import unittest
from cwr.parser.encoder.dictionary import InstrumentValueDictionaryEncoder
from cwr.table_value import InstrumentValue
"""
Acknowledgement to dictionary encoding tests.
The following cases are tested:
"""
__author__ = 'Bernardo Martínez Garrido'
__license__ = 'MIT'
__status_... |
# Copyright 2019 The Cirq Developers
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... |
from django.db import models
from django.core.urlresolvers import reverse
# Add admin Url to every content object
def get_admin_url(self):
return reverse('admin:%s_%s_change' % (self._meta.app_label, self._meta.module_name), args=[self.pk])
@classmethod
def get_class_admin_url(cls):
return reverse('admin:%s... |
import time
from zone_api import platform_encapsulator as pe
from zone_api.core.actions.play_music_at_dinner_time import PlayMusicAtDinnerTime
from zone_api.core.devices.activity_times import ActivityTimes, ActivityType
from zone_api.core.devices.motion_sensor import MotionSensor
from zone_api_test.core.device_test i... |
import glob
import os
import sys
try:
sys.path.append(glob.glob('../carla/dist/carla-*%d.%d-%s.egg' % (
sys.version_info.major,
sys.version_info.minor,
'win-amd64' if os.name == 'nt' else 'linux-x86_64'))[0])
except IndexError:
pass
try:
sys.path.append(glob.glob("/home/icv/.local/lib/python3.6/site-packages/"... |
#!/usr/bin/env python3
import os, sys
import traceback
from pymongo import MongoClient
import random
from bson.objectid import ObjectId
from solr import SOLR
from solr import SOLR_CORE_NAME
class SearchSolr():
def __init__(self, ip='127.0.0.1', solr_core=SOLR_CORE_NAME):
self.solr_url = 'http://'+ ip +':... |
from .rates import RateManager
from .vrws import Rate, Rates, VRWSException, VRWSSOAPException,\
VRWSHTTPException, VRWSErrorException
from .tic import TICException, TICHTTPException
__all__ = ['RateManager', 'Rates', 'Rate',
'VRWSException', 'VRWSSOAPException', 'VRWSHTTPException',
'VRWSErr... |
my_string = "abcba"
if my_string == my_string[::-1]:
print("palindrome")
else:
print("not palindrome")
# Output
# palindrome
|
data = (
'Ze ', # 0x00
'Xi ', # 0x01
'Guo ', # 0x02
'Yi ', # 0x03
'Hu ', # 0x04
'Chan ', # 0x05
'Kou ', # 0x06
'Cu ', # 0x07
'Ping ', # 0x08
'Chou ', # 0x09
'Ji ', # 0x0a
'Gui ', # 0x0b
'Su ', # 0x0c
'Lou ', # 0x0d
'Zha ', # 0x0e
'Lu ', # 0x0f
'Nian ', ... |
from .column_append import column_append
|
#!/usr/bin/env python
import cv2
import sys
import numpy as np
import logging
from pathlib import Path
import matplotlib.pyplot as plt
import squarify
import subprocess
import argparse
from sklearn.cluster import KMeans, MiniBatchKMeans
import av
# Pixel ordering for different backends
colorformats = {
'pyav': [0... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright 2020-2022 F4PGA Authors
#
# 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
#
# Unl... |
from argparse import ArgumentParser
from src.dummy_manager import (
DummyGameOverManager, DummyMenuManager, DummyOverWorldManager,
DummyQuestionManager
)
from src.game import Game
from src.manager import GameManager
def main() -> None:
"""Run the game"""
parser = ArgumentParser()
parser.set_defau... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
USE_CUDA = True if torch.cuda.is_available() else False
class ConvLayer(nn.Module):
def __init__(self, in_channels=1, out_channels=256, kernel_size=9):
super(ConvLayer, self).__init__()
... |
import sys
from eosfactory.eosf import *
verbosity([Verbosity.INFO, Verbosity.OUT, Verbosity.DEBUG])
CONTRACT_WORKSPACE = sys.path[0] + "/../"
# Actors of the test:
MASTER = MasterAccount()
HOST = Account()
ALICE = Account()
BOB = Account()
CAROL = Account()
def test():
SCENARIO('''
Initialize the token and... |
from .hashtag import Hashtag
from .hashtagstats_manager import HashtagStatsManager |
import sys
from socket import *
from protocol import *
name=sys.argv[1]
lang=sys.argv[2]
email=sys.argv[3]
phone=sys.argv[4]
academic=sys.argv[5]
other=sys.argv[6]
auth=sys.argv[7]
d={'name':name,'lang':lang,'email':email,'phone':phone,'academic':academic,'other':other,'auth':auth}
for key in ['email','phone','... |
##
##
# File auto-generated against equivalent DynamicSerialize Java class
class CommitGridsRequest(object):
def __init__(self):
self.commits = None
self.workstationID = None
self.siteID = None
def getCommits(self):
return self.commits
def setCommits(self, commits):
... |
import torch
from torchvision import transforms as T
from torchvision.transforms import functional as F
from PIL import Image
import numpy as np
import unittest
class Tester(unittest.TestCase):
def _create_data(self, height=3, width=3, channels=3):
tensor = torch.randint(0, 255, (channels, height, width... |
"""
Given a binary tree, check whether it is a mirror of itself (ie, symmetric
around its center).
For example, this binary tree is symmetric:
1
/ \
2 2
/ \ / \
3 4 4 3
But the following is not:
1
/ \
2 2
\ \
3 3
Note:
Bonus points if you ... |
#!/usr/bin/env python
import os
import click
import torch
import numpy as np
def load_models(model_dir):
models = []
for path in os.listdir(model_dir):
if path.endswith(".pt"):
models.append(torch.jit.load(os.path.join(model_dir, path)))
return models
def parse_feature(aln_path):
... |
import numpy as np
from mcdm_method import MCDM_method
class SPOTIS(MCDM_method):
def __init__(self):
"""
Create SPOTIS method object.
"""
pass
def __call__(self, matrix, weights, types, bounds):
"""
Score alternatives provided in decision matrix `matrix` using ... |
import numpy as np
COCO_PERSON_SKELETON = [
(16, 14), (14, 12), (17, 15), (15, 13), (12, 13), (6, 12), (7, 13),
(6, 7), (6, 8), (7, 9), (8, 10), (9, 11), (2, 3), (1, 2), (1, 3),
(2, 4), (3, 5), (4, 6), (5, 7),
]
KINEMATIC_TREE_SKELETON = [
(1, 2), (2, 4), # left head
(1, 3), (3, 5),
(1, 6),... |
buf = """const LOGIN_PACKET = 0x8f;
const PLAY_STATUS_PACKET = 0x90;
const DISCONNECT_PACKET = 0x91;
const BATCH_PACKET = 0x92;
const TEXT_PACKET = 0x93;
const SET_TIME_PACKET = 0x94;
const START_GAME_PACKET = 0x95;
const ADD_PLAYER_PACKET = 0x96;
const REMOVE_PLAYER_PACKET = 0x97;
c... |
pass
#testing 11/12/19
#testing 7/19/20 |
#!/usr/bin/env python3
# Automate the following for floating point values:
# Checking that the values are within the specified range (ValueError)
# Track the minimum, maximum, and average values found
# Usage as a tracker, store value elsewhere:
# my_stats_tracker_variable_x = StatsTrackerBase.create_instance(mi... |
# Imported required libraries
from tweepy import StreamingClient, StreamRule
from kafka import KafkaProducer
from jsons import dumps
#streamlit
# Creating reading class
class CustomInStream(StreamingClient):
def __init__(self, bearer_token, kafka_topic):
super(CustomInStream, self).__init... |
# file: tests/file_access_wrappers.py
# author: Andrew Jarcho
# date: 2017-01-22
# python: 3.5 pytest: 3.0.7
import io
class FileReadAccessWrapper:
def __init__(self, filename):
self.filename = filename
def open(self):
return open(self.filename, 'r')
class FakeFileReadWrapper:
def _... |
"""
Xtract Blueprint
"""
from calm.dsl.builtins import ref, basic_cred
from calm.dsl.builtins import Service, Package, Substrate
from calm.dsl.builtins import Deployment, Profile, Blueprint
from calm.dsl.builtins import read_provider_spec, read_local_file
ADMIN_PASSWD = read_local_file("admin_passwd")
DefaultCred ... |
# -*- coding: utf-8 -*-
from __future__ import with_statement
import os,sys
import re
import shutil
import pypsutils
import subprocess
import pyps
simd_h = "SIMD_types.h"
def gen_simd_zeros(code):
""" This function will match the pattern SIMD_ZERO*_* + SIMD_LOAD_*
and replaces it by the real corresponding SI... |
from tornado.web import url
from . import views
patterns = [
url(r'^/$', views.IndexView, name='index')
]
|
import json
import logging
from http.server import BaseHTTPRequestHandler, HTTPServer
from eth_utils import to_bytes, to_hex
from raiden.utils import sha3
# The code below simulates XUD resolver functionality.
# It should only be used for testing and should not be used in
# run time or production.
def resolve(requ... |
from collections import defaultdict
import json
'''
Convert ensembl ids to entrez ids. Delete duplicated and invalid (NA) ones.
'''
with open('./data/entrez_ids_original_HI-II-14.txt') as f:
ids = defaultdict(list)
for line in f.readlines():
num, ensembl, entrez = line[:-1].split()
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from distutils.core import setup, Extension
# define the extension module
cos_module = Extension('cos_module', sources=['cos_module.c'])
# run the setup
setup(ext_modules=[cos_module])
|
"""
Wrapper interface for dispatching calculations of auxiliary variables to the
correct functions depending on the data source a given dataset originated from.
"""
import xarray as xr
class MissingDomainData(Exception):
pass
from .era5.interpolation import interpolate_to_height_levels as era5_hl_interp
from .e... |
#!/usr/bin/env python
#
# Copyright (c) 2019, The OpenThread Authors.
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright
# ... |
from jupyter_client.managerabc import *
|
from .ipfs import *
|
from contextlib import suppress
from typing import Union, List
from requests.models import Response
from pysoundcloud.soundclouddata import SoundCloudData
from pysoundcloud.soundclouduser import SoundCloudUser
from pysoundcloud.soundcloudtrack import SoundCloudTrack
from pysoundcloud.soundcloudplaylist import... |
s = input()
print("x"*len(s))
|
from typing import TYPE_CHECKING, Any, get_args
import numpy
from openff.units import unit
class _FloatQuantityMeta(type):
def __getitem__(self, t):
return type("FloatQuantity", (FloatQuantity,), {"__unit__": t})
class FloatQuantity(float, metaclass=_FloatQuantityMeta):
@classmethod
def __get_v... |
import unittest
from firetower import redis_util
from firetower.category import Category, TimeSeries
def create_mock_category(id, sig, thresh, name):
"""Create a mock category object for testing purposes.
Args:
id: str, system referenc (hash when not a test obj).
sig: str, the signature we'r... |
print('welcome') |
#! /usr/bin/env python
import clg
import os
import yaml
import yamlordereddictloader
CMD_FILE = os.path.abspath(os.path.join(os.path.dirname(__file__),'subparsers.yml'))
def main():
cmd = clg.CommandLine(yaml.load(open(CMD_FILE),
Loader=yamlordereddictloader.Loader))
print(... |
#!/usr/bin/env python
#!coding=utf-8
import rospy
import numpy as np
import PIL.Image as pilimage
from sensor_msgs.msg import CompressedImage
from sensor_msgs.msg import Image
from cv_bridge import CvBridge, CvBridgeError
import cv2
import time
from yolo import YOLO
yolo = YOLO()
class image_converter:
def __init... |
#!/usr/bin/python
# -*-coding: utf-8 -*-
# Copyright 2010 Google Inc.
# Licensed under the Apache License, Version 2.0
# http://www.apache.org/licenses/LICENSE-2.0
# Google's Python Class
# http://code.google.com/edu/languages/google-python-class/
import os
import re
import sys
import urllib
"""Logpuzzle exercise
Gi... |
from mmocr.datasets import build_dataset
from mmcv import Config
from mmocr.apis import init_detector, model_inference
import os
from opencc import OpenCC
import cv2
import numpy as np
cc = OpenCC('s2t') # convert from Simplified Chinese to Traditional Chinese
path = os.path.join("work_dir", "order_imgs")
print(len(o... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jul 11 15:10:16 2020
@author: yujiang
"""
import datetime
def hello_world(param=2):
"""
this is to test how to use sphinx.ext.autodoc
:param var: (int) just a test a param (default is 2)
:param datetime: (int) just a test param (de... |
from django.db import models
from eworkshop.utils.models import TimeModel
class Profile(TimeModel):
"""Profile Model.
A profile holds user statistics and profile picture
"""
staff = models.OneToOneField('staff.Staff', on_delete=models.CASCADE)
picture = models.ImageField(
'profile pictur... |
# Mine content from url_kb.sqlite3
################################################################################
# Import statements
################################################################################
import hashlib
import json
import logging
import pdb
import os
import sqlite3
# import random
# impor... |
#!/usr/bin/env python3
#########################################################################################################
#
# MECCA - KPP Fortran to CUDA parser
#
# Copyright 2016-2020 The Cyprus Institute
#
# Developers: Michail Alvanos - m.alvanos@cyi.ac.cy
# Theodoros Christoudias - christoudias@c... |
#!/usr/bin/env python
#
# Copyright (c) 2013 Paolo Antonelli, Tiziana Cherubini, Graziano Giuliani
#
# 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 lim... |
from Shared.dtos.GameDto import GameDto;
from Shared.dtos.GameListDto import GameListDto;
from Shared.enums.PlayerTypeEnum import PlayerTypeEnum;
from Werewolf.game.Game import Game;
def GameToDto(game, lastUpdatedUtc, player):
if not game:
return None;
# don't give any messages if there is no last up... |
def _matcher(pattern, str):
for word in pattern.split(" "):
if word not in str:
return False
return True
def name(secret, names):
for n in names:
if _matcher(n, secret["name"]):
return True
return False
def description(secret, descriptions):
for d in descr... |
#!/usr/bin/env python
import bootstrap
import unittest
import time
import nark
class Tests(unittest.TestCase):
def setup(self):
return nark.Assert(), nark.Assets(), nark.Factory()
def test_can_create_instance(self):
t, _, i = self.setup()
t.not_null(i, "Failed to create Factory instance")
d... |
"""Test permissions of the site to ensure we haven't given write access."""
import pytest
import urllib.request
import urllib.error
@pytest.mark.parametrize("method", ["PUT", "POST"])
def test_write_is_not_allowed(url, method):
"""Test that WRITE methods are not allowed."""
req = urllib.request.Request(url, ... |
from nosem import project, executable, test
project('basic', 'cpp')
demo = executable('basic-demo', 'main.cpp')
test(demo.name(), demo)
|
from click.testing import CliRunner
from src.cli import cli
def test_cli():
"""Test CLI to import all commands without any error and exception
"""
runner = CliRunner()
result = runner.invoke(cli)
assert result.exit_code == 0
assert not result.exception
|
# This is purely the result of trial and error.
import os
import sys
import codecs
import subprocess
from setuptools import setup
from setuptools import find_packages
import aiowrpr
INSTALL_REQUIRES = [
'aiodns==2.0.0',
'aiohttp[speedups]>=3.7.4',
'aiohttp-apispec==2.1.0',
'apispec==3.2.0',
'asyn... |
"""
Python Script used for plotting common timeseries charts
"""
# Data Manipulation
import pandas as pd
import numpy as np
from scipy.ndimage.interpolation import shift
# Data Visualization
from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
import plotly.express as px
from plotly... |
from urllib.request import urlopen
from datetime import datetime
from random import choice
from json import dumps, load, loads
from contextlib import suppress
from pathlib import Path
from uuid import uuid4
from threading import Thread
from .local_amino import Client, SubClient, ACM
from .commands import *
... |
from .cls import TextClassifier, main as predict_cls
from .det import TextDetector, main as predict_det
from .rec import TextRecognizer, main as predict_rec
from .system import TextSystem, main as predict_system
|
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.viewsets import ViewSet
from rest_framework.permissions import IsAuthenticated
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.admin.models import LogEntry
from django.urls import reve... |
import keras
import keras.backend as K
import os
import cv2
import numpy as np
import scipy
def makedir_if_nexist(dir_list):
"""Create empty directory if it does not already exist
Parameters
----------
dir_list : list of str
List of directories to create
"""
for cur_dir in dir_list:
... |
# © 2019 KidsCanCode LLC / All rights reserved.
#honestly not a lot I can put in here, but I'll add more when we add more.
import pygame
# game options/settings
TITLE = "Jumpy!"
WIDTH = 480
HEIGHT = 600
FPS = 60
# Environment options
GRAVITY = 9.8
# Player properties
PLAYER_ACC = 0.5
PLAYER_FRICTION = -0.01
# defi... |
"""To identify the geo and stats"""
import json
import os
import sys
import time
import urllib
import urllib.error
import urllib.parse
import urllib.request
import requests
base_url = "https://freegeoip.app/json/"
class Identify:
# for checking geo and ip
def raw_data(self):
res_1 = urllib.request.u... |
class Constants:
APP_NAME = "EVOLUTION_CHAMBER"
COMPARISONS_PER_GENERATION = 100
POPULATION_SIZE = 20
KILL_SIZE = 10
|
# coding: utf-8
# pylint: disable=W0611
"""Compatibility layer"""
from __future__ import absolute_import as _abs
import sys
PY3 = (sys.version_info[0] == 3)
def assert_python_min_ver(py2_ver, py3_ver, info_str):
"""Enforce minimum Python version for Python 2.x and 3.x"""
py2_ver_ = py2_ver.split('.')
py3_ver_ ... |
#!/usr/bin/env python
""" Example 8
- read cisco config
- print crypto sections will all children
"""
from ciscoconfparse import CiscoConfParse
cfg_parser = CiscoConfParse('cisco_ipsec.txt')
crypto_lines = cfg_parser.find_objects(r'^crypto map CRYPTO')
for cline in crypto_lines:
print cline.text
... |
from .vosk import KaldiRecognizer, Model
|
# -*- coding: utf-8 -*-
# Author: XuMing <shibing624@126.com>
# Data: 17/10/16
# Brief: cnn网络结构
import csv
import os
import numpy as np
import tensorflow as tf
from tensorflow.contrib import learn
import config
import data_helpers
from util import to_categorical
if config.eval_all_train_data:
x_raw, y = data_he... |
"""adding more reasons for clustering
Revision ID: 256acb048a32
Revises: e2d7db861709
Create Date: 2017-07-31 11:49:16.345244
"""
from alembic import op
import sqlalchemy as sa
revision = '256acb048a32'
down_revision = 'e2d7db861709'
branch_labels = None
depends_on = None
enum_fields = ['status_code_304', 'etag', 'e... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.