content stringlengths 5 1.05M |
|---|
#import this # delete the first hashtag to see the truth
#String methods
#isAlpha возвращает True, если строка состоит только из букв и не является пустой
print ('hello'.isalpha())
print ('hello1'.isalpha())
#isalnum возвращает True , если строка состоит из букв и цифр
print ('hello12'.isalnum())
print ('hello'.i... |
from __future__ import absolute_import, print_function
import inspect
import os
import shutil
from bs import config
from bs import objectives
class Action(object):
def __init__(self, name, description):
self.name = name
self.description = description
def add_arguments(self, parser):
... |
from .run_command import run_command
def make_volume_dict():
volume_dict = {}
for line in run_command("sudo blkid").stdout.strip("\n").split(sep="\n"):
line = line.split()
volume_name = line[0][:-1]
volume_dict[volume_name] = {}
for field_value in line[1:]:
f... |
import requests
import logging
import json
import dateutil.parser
import datetime
SOLR = "http://127.0.0.1:8983/solr/lgbt/select?"
def get_stats():
res = requests.get(SOLR + "wt=json&rows=0&q=*&stats=true&stats.field=date")
if res.status_code == 200:
return res.json()["stats"]["stats_fields"]["date"]
... |
# coding: utf-8
from workspacemanager.utils import *
import sh
def dispFreeze(theProjectDirectory=None):
# Get all dirs:
(thisLibPackageDirectory,
theProjectDirectory,
theProjectPackageDirectory,
thisLibName) = getDirs(theProjectDirectory=theProjectDirectory)
venvName = theProjectPackageDir... |
import imageio
import metaimageio
import numpy as np
import pytest
from test_io import file_with_suffix, SUFFIX
@pytest.mark.parametrize('suffix', SUFFIX)
def test_imageio(suffix):
metaimageio.imageio()
with file_with_suffix(suffix) as f:
a = (100 * np.random.random_sample((2, 3, 4)))
imageio.... |
import numpy as np
import pandas as pd
from pandas import DataFrame
from typing import Tuple
from plotnine import *
import math
def fit_linear_regression(mat_x: np.array, res_vec: np.array) -> Tuple[np.array, np.array]:
"""
Linear Regression solver
Parameters:
:param mat_x: The design matrix X (np arr... |
from urllib3 import disable_warnings
disable_warnings()
|
import os
import pickle
from jina.drivers.control import RouteDriver
from jina.executors import BaseExecutor
cur_dir = os.path.dirname(os.path.abspath(__file__))
def test_dump_driver(tmpdir):
rd = RouteDriver(raise_no_dealer=True)
rd.idle_dealer_ids = ('hello', 'there')
with open(str(tmpdir / 'a.bin'),... |
#!/usr/bin/python3
import logging
import unittest
import astropy.units as u
import simtools.io_handler as io
from simtools.simtel.simtel_events import SimtelEvents
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
class TestSimtelEvents(unittest.TestCase):
def setUp(self):
self.testFiles = l... |
from queryset_utils import annotate_mock_class, make_mock_list_from_args, get_keys_from_dict, make_mock_in_bulk_dict, make_mock_aggregate_dict, annotate_return_value
from unittest.mock import MagicMock
import unittest
class TestAnnotateMockClass(unittest.TestCase):
def test_annotate_mock_class(self):
mock... |
from ir_sim.env import env_base
from math import sqrt, pi
from gym import spaces
from gym_env.envs.rvo_inter import rvo_inter
import numpy as np
class ir_gym(env_base):
def __init__(self, world_name, neighbors_region=5, neighbors_num=10, vxmax = 1.5, vymax = 1.5, env_train=True, acceler = 0.5, **kwargs):
s... |
from functools import partial
from unittest.mock import MagicMock
import pytest
from nanopie.auth import (
Credential,
CredentialValidator,
AuthenticationHandler,
HTTPAPIKeyAuthenticationHandler,
HTTPAPIKeyModes,
HTTPBasicAuthenticationHandler,
HTTPOAuth2BearerJWTAuthenticationHandler,
... |
# pylint: disable=missing-function-docstring, missing-module-docstring/
from pyccel.stdlib.internal.blas import dgemm
from numpy import zeros
if __name__ == '__main__':
m = 4
k = 5
n = 4
a = zeros((m,k), 'double')
b = zeros((k,n), 'double')
c = zeros((m,n), 'double')
# ...
a[0,0] = 1.... |
from starlette.config import Config
MAX_QUESTIONS = 95
config = Config('.env')
MODULE_URL = config('MODULE_URL')
METABOT_URL = config('METABOT_URL')
MONGODB_URI = config('MONGODB_URI')
FEEDBACK_COLLECTION = config('FEEDBACK_COLLECTION', default='feedback')
HEARTBEAT_DELAY = config('HEARTBEAT_DELAY', cast=float, defa... |
import uuid
from datetime import datetime
from nwb_conversion_tools import NWBConverter
from .shenoyblackrockrecordingdatainterface import ShenoyBlackRockRecordingDataInterface
from .shenoymatdatainterface import ShenoyMatDataInterface
class ChurchlandNWBConverter(NWBConverter):
data_interface_classes = dict(
... |
"""Extract features from static moments of IMU data."""
from typing import Optional, Tuple, Union
import numpy as np
import pandas as pd
from scipy.stats import skew
from biopsykit.utils.array_handling import sanitize_input_nd
from biopsykit.utils.time import tz
def compute_features(
data: pd.DataFrame,
sta... |
def calibrateInertialSensorData(data, AM, SM, OV):
import numpy as np
# data: raw data to be calibrated
# AM: alignment matrix
# SM: sensitivity matrix
# OV: offset vector
# double[] tempdata = data;
# double[,] data2d = new double[3, 1];
# data2d[0, 0] = data[0];
# data2d[1, 0] = d... |
"""Test Base module of python-openflow."""
import unittest
from pyof.foundation import base, basic_types
class TestGenericStruct(unittest.TestCase):
"""Testing GenericStruct class."""
def setUp(self):
"""Basic Test Setup."""
class AttributeA(base.GenericStruct):
"""Example class.... |
# encoding: utf-8
#
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this file,
# You can obtain one at http://mozilla.org/MPL/2.0/.
#
# Author: Kyle Lahnakoski (kyle@lahnakoski.com)
#
from __future__ import absolute_import, divisio... |
#!/usr/bin/env
# -*- coding: utf-8 -*-
import csv
import requests
import random
import json
import os
from os.path import join, dirname
from dotenv import load_dotenv
# 環境変数読み込み
load_dotenv(join(dirname(__file__), '.env'))
url = os.environ.get("VUE_APP_IBM_CLIENT_URL2")
headers = {
"Accept": "application/json",
... |
# This Python file uses the following encoding: utf-8
"""autogenerated by genpy from duckietown_msgs/LEDDetection.msg. Do not edit."""
import sys
python3 = True if sys.hexversion > 0x03000000 else False
import genpy
import struct
import duckietown_msgs.msg
import genpy
class LEDDetection(genpy.Message):
_md5sum = "... |
# references
# http://tcl.tk/man/tcl8.6/TkCmd/pack.htm pack
# https://docs.python.org/3/library/tkinter.html#the-packer docs
# import tkinter
# from typing import Text
#tinkter.<class name> to import singly
#turtle
import turtle
tim = turtle.Turtle()
tim.write("shreya", font = ("Times New Roman", 80, "bold"))... |
#!/usr/bin/python3
import sys
import random
import argparse
COMMON_BG = "авгеиКкмМнопрсТтух"
COMMON_EN = "aBreuKkMMHonpcTTyx"
def voidscate(text, rev=False):
temp = ""
if rev:
this, that = COMMON_BG, COMMON_EN
else:
this, that = COMMON_EN, COMMON_BG
for letter in text:
if let... |
import xadmin
from xadmin import views
from auth_server.models import MobileData, KeyStroke, Mouse
class BaseSettings:
enable_themes = True
use_bootswatch = True
class GlobalSettings:
site_title = '西安交大数据采集系统后台管理'
site_footer = '西安交通大学'
menu_style = 'accordion'
class MobileDataAdmin:
list_... |
myl1 = [1,2,3,4]
print("Before reversing list elements are: " + str(myl1))
myl1.reverse()
print("After reversing list elements are: " + str(myl1))
|
# -*- coding: utf-8 -*-
"""
@summary: Maya cooperative python library
@run: import coop.coopLib as lib (suggested)
@license: MIT
@repository: https://github.com/artineering-io/maya-coop
"""
from __future__ import print_function
from __future__ import unicode_literals
import os, sys, subprocess,... |
# -*- coding:utf-8 -*-
import os
import time
import sys
import traceback
from selenium import webdriver
# from pyvirtualdisplay import Display
"""
wget https://github.com/mozilla/geckodriver/releases/download/v0.19.0/geckodriver-v0.19.0-linux64.tar.gz
tar -zxvf geckodriver-v0.19.0-linux64.tar.gz
mv geckod... |
# -*- coding: utf-8 -*-
"""
authorization handlers base module.
"""
from abc import abstractmethod
import pyrin.security.session.services as session_services
import pyrin.utils.misc as misc_utils
from pyrin.core.globals import _, _n
from pyrin.core.exceptions import CoreNotImplementedError
from pyrin.security.author... |
import logging
import numpy as np
import pandas as pd
import torch
from torch.nn.parameter import Parameter
from src.model.ae_modules import (
PrototypeAutoencoder,
PrototypeTransitionAutoencoder
)
from src.model.standard_autoencoder import StandardAutoencoderModel
from src.model.misc import (
diversity... |
import tensorflow as tf
from heads import WriteHead, ReadHead
class NTM:
def __init__(self, scope_, controller_, read_heads_, write_heads_, num_nodes_, size_):
self.controller = controller_
self.read_heads = read_heads_
self.write_heads = write_heads_
self.w_output = tf.get_variable... |
from dolfin import *
from xii import *
# mesh_file = 'geometry.h5'
# comm = mpi_comm_world()
# h5 = HDF5File(comm, mesh_file, 'r')
# mesh = Mesh()
# h5.read(mesh, 'mesh', False)
# volumes = MeshFunction('size_t', mesh, mesh.topology().dim())
# h5.read(volumes, 'physical')
mesh = Mesh('geometry_old.xml')
surfaces = M... |
# Generated by Django 3.1.1 on 2021-02-03 22:59
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("temperature", "0001_squashed_0007_auto_20181125_2259"),
]
operations = [
migrations.AddField(
model_name="measurementdevice",
... |
__all__ = ["Component", "Composite", "TaskComponent", "TaskComposite"]
from icevision.imports import *
from icevision.core import tasks
class Component:
order = 0.5
def __init__(self):
self.composite = None
def set_composite(self, composite):
self.composite = composite
class TaskCompo... |
#=============================
# JointFontGAN
# Modified from https://github.com/azadis/MC-GAN
# By Yankun Xi
#=============================
import numpy as np
import os
import ntpath
import time
from . import XIutil
from . import XIhtml
import shutil
from scipy import misc
from skimage import data, img_as_float
impor... |
"""Testing for Symbolic Fourier Approximation."""
# Author: Johann Faouzi <johann.faouzi@gmail.com>
# License: BSD-3-Clause
import numpy as np
import pytest
from sklearn.feature_selection import f_classif
from pyts.approximation import MultipleCoefficientBinning
from pyts.approximation import SymbolicFourierApproxima... |
import os
import pickle
import argparse
from tqdm import trange
import torch
import torch.nn as nn
import pyro
import pyro.distributions as dist
import mlflow
from neural.baselines import BatchDesignBaseline
from neural.critics import CriticBA
from neural.aggregators import ConcatImplicitDAD
from neural.modules impor... |
#Utilize sympy for creating
#the matrices used within the
#chemical equation balancer
import sympy
#
#use the string module
#in order to get a list of
#all ascii_letters for the
#chemical equation balancer
import string
#Purpose: The purpose of the balance.py file is to provide other developers functionality that wil... |
import logging
from typing import Any, Dict
logger = logging.getLogger(__name__)
logger.addHandler(logging.NullHandler())
class WorkflowState:
"""
Represents a single Comala workflow state which a page can be in.
"""
def __init__(self, json): # type: (Dict[str, Any]) -> None
self.name = json... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import csv
import pickle
import ujson, yaml
from collections import OrderedDict
from pathlib import Path
from typing import Union, Optional
def deserialize_yml(fpath: Union[Path, str]) -> dict:
# load yaml with OrderedDict to preserve order
# http://stackoverflow.com... |
# std libraries
import os
import warnings
# third parties libraries
import numpy as np
import matplotlib.pyplot as plt
# we use this function to extract certain information in the file f that stores the log of the specified mathematical model
def read(f):
lines = f.readlines()
start=dict(... |
from heapq import heappush, heappop
#import collections
n, k = map(int, input().split())
c = []
for i in range(n):#h:高さ
c.append([int(m) for m in input().split()])
c.sort(key=lambda x:(x[0], x[1]))
f = sorted(c, key=lambda x:(x[1], x[0]), reverse=True)
donyoku = 0
donset = set()
#pq = PriorityQueue()
notfirst =[]
f... |
#!/usr/bin/python3
import time
from selenium.webdriver.chrome.options import Options
from selenium import webdriver
import re
from collections import Counter
from urllib.parse import urlparse
from fake_useragent import UserAgent
import argparse
WEBURL = "https://www.eniyiuygulama.com/"
PROXY = "socks5://127.0.0.1:9050"... |
import qsm
def test_project_defines_author_and_version():
assert hasattr(qsm, '__author__')
assert hasattr(qsm, '__version__')
|
#!/usr/bin/env python2.7
import numpy as np
import math as m
import matplotlib.pyplot as plt
import radio_beam
from spectral_cube import SpectralCube
from astropy.io import fits
from astropy import units as u
import os
#from reproject import reproject_interp
from astropy.wcs import WCS
"""
using data cubes and pu... |
import discord
import asyncio
from discord.ext import commands
from bin import zb_config
from bin import zb
_var = zb_config
_query = """ SELECT g.guild_id,u.real_user_id,r.role_id,u.name,g.nick,u.int_user_id
FROM users u
LEFT JOIN guild_membership g ON u.int_user_id = g.int_user_id
... |
# https://www.codewars.com/kata/find-the-next-perfect-square/train/python
# My solution
find_next_square = lambda sq : -1 if int(sq**0.5)**2 != sq else int(sq**0.5+1)**2
# Return the next square if sq is a square, -1 otherwise
# ...
def find_next_square(sq):
root = sq ** 0.5
if root.is_integer():
... |
from django.contrib import admin
from store.models import Product
@admin.register(Product)
class ProductAdmin(admin.ModelAdmin):
list_display = ['title', 'user', 'price']
|
import random
from tests.utils import async_test
from donphan import Column, Table, SQLType
from unittest import TestCase
class _TestLikeTable(Table):
a: Column[SQLType.Text] = Column(primary_key=True)
class ViewTest(TestCase):
def test_query_fetch_null(self):
where = _TestLikeTable._build_where_cl... |
from tkinter import *
from utility import *
import os
from tkinter import messagebox
import threading
from os import listdir
from os.path import isfile, join
from pygame import mixer # Load the popular external library
import time
from mutagen.mp3 import MP3
def main(root, WIDTH, HEIGHT, wu, hu):
global songFolder... |
import os
import sys
import numpy as np
import torch
from torch import nn
from torch import optim
from torch.optim import lr_scheduler
import torchvision.transforms as transforms
from PIL.Image import CUBIC
from time import time
from opts import parse_opts
from model import generate_model
from spatial_transforms impor... |
class Solution(object):
# def minTotalDistance(self, grid):
# """
# :type grid: List[List[int]]
# :rtype: int
# """
# # sort
# rows = []
# cols = []
# for i in range(len(grid)):
# for j in range(len(grid[0])):
# if grid[i][j... |
"""Provide methodologies for creating the model from the data."""
import json
import logging
from datetime import datetime
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import scipy.stats
from hoqun... |
from __future__ import division
from openpyxl import Workbook
from array import array
#from openpyxl.utils import coordinate_from_string, column_index_from_string
from openpyxl.utils import column_index_from_string
from openpyxl.utils.cell import coordinate_from_string
from openpyxl.utils import get_column_letter
impor... |
import os
import glob
import inspect
import warnings
import datetime
import functools
import contextlib
import collections
import numpy as np
import pandas as pd
import tqdm
from . import getdata
from . import getstatic
from .. import config
def _filter_df(df: pd.DataFrame, query: str) -> pd.DataFrame:
if '@' i... |
import json
import uvicorn
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import Response
from fastapi.templating import Jinja2Templates
from climate.model.load_production_model import Load_Prod_Model
from climate.model.prediction_from_model import Predi... |
from flask import Flask, render_template, request, redirect, url_for
import json, time, serial
app = Flask(__name__)
app.secret_key = 'shumugfdsghjk'
app.config['SERVER_NAME'] = '192.168.1.33'
ser = serial.Serial('/dev/ttyACM0', 9600)
@app.route('/')
def needToLogin():
return redirect(url_for('login'))
@app.rou... |
# -*-coding:Utf-8 -*
# Copyright (c) 2010-2016 DAVY Guillaume
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# * Redistributions of source code must retain the above copyright notice, this
#... |
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:
retHead = head
if head is None: return head
while... |
from trnlp import TrnlpWord
from SimurgKelimeTemizle import kelime_temizle
text = "İnsanlar buraya geldiler."
#text = "İnsanlar buraya geldi."
#text = "Birkaç kişiler geldiler."
#text = "Bizimkilerle sizin eve geldim."
def ozneYuklem(text):
def cumle_ayirici(text):
ayrilmis_metin = []
obj = Trnl... |
"""Unit test module for Intervention API"""
from datetime import datetime, timedelta
import json
import os
from dateutil.relativedelta import relativedelta
from flask_webtest import SessionScope
import pytest
from portal.extensions import db
from portal.models.audit import Audit
from portal.models.clinical_constants... |
from __future__ import division
from builtins import object
import pytest
import numpy as np
import os
import platform
from sporco import util
def fn(prm):
x = prm[0]
return (x - 0.1)**2
def fnnan(prm):
x = prm[0]
if x < 0.0:
return np.nan
else:
return (x - 0.1)**2
def fnv(p... |
from django.shortcuts import render
import logging
# Create your views here.
def inicio(request):
# Aunque le este enviando el context al index.html. El context puede viajar anidamente los template. index.html -> base.html -> navbar.hmtl
context = {"indexNavActiveClass": "active"}
logger = logging.getLo... |
# std libs
import os
import glob
import json
import mmap
import pickle
import shutil
import tempfile
import fnmatch as fnm
import itertools as itt
from pathlib import Path
from contextlib import contextmanager
# local libs
import docsplice as doc
from recipes.bash import brace_expand_iter
from recipes.string import ... |
class Solution(object):
# 贪心
def maxProfit(self, prices):
"""
:type prices: List[int]
:rtype: int
"""
if(prices==None or len(prices)==0):
return 0
min_v = prices[0]
max_v = 0
for i in range(len(prices)):
min_v = min(min_v,prices[i])
max_v = max(max_v,prices[i]-min_v)
return max_v
... |
import socket
s = socket.socket()
port = 12348
s.connect(('localhost', port))
def math():
s.send(b'1')
data = input("Enter mathematical operation :")
s.send(str(data).encode())
r = s.recv(1024).decode()
print("Result is :", r)
s.close()
def ftp():
... |
"""Tests for `pypendency` package."""
import uuid
import pytest
import pypendency.models.graph as pmg
from pypendency.models.generics import BaseNode, Relation, Direction
def test_graph_context():
g = pmg.Graph(str(uuid.uuid4()))
with g:
node = BaseNode("TestNode",
slug="t1",... |
from .d4pg.engine import Engine as D4PGEngine
def load_engine(config):
return D4PGEngine(config)
|
from yowsup.layers import YowProtocolLayer
from .protocolentities import *
import logging
logger = logging.getLogger(__name__)
class YowContactsIqProtocolLayer(YowProtocolLayer):
def __init__(self):
handleMap = {
"iq": (self.recvIq, self.sendIq),
"notification": (self.recvNotifica... |
from easydict import EasyDict as edict
class Config:
# dataset
# dataloader
# model
MODEL = edict()
MODEL.SCALE = 4
MODEL.IN_CHANNEL = 3
MODEL.OUT_CHANNEL = 3
MODEL.N_FEATURE = 64
MODEL.N_BLOCK = 23
MODEL.GROWTH_CHANNEL= 32
MODEL.DOWN = 1
MODEL.DEVICE... |
# -*- coding: utf-8 -*-
# @Time : 2020/11/24 17:51
# @Author : islander
# @File : model.py
from pprint import pprint
from typing import Dict, List
import tensorflow as tf
from . import layers
from .utils import *
from . import utils
class NetNotBuiltError(Exception):
pass
class Din(object):
"""Deep... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2017-01-09 14:42
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('houses', '0091_auto_20170109_1536'),
]
operations = [
migrations.AddField(
... |
import numpy as np
from scipy.special import erfinv
from scipy.stats import norm
from mmu.lib._mmu_core_tests import norm_ppf
from mmu.lib._mmu_core_tests import erfinv as cpp_erfinv
from mmu.lib._mmu_core_tests import binomial_rvs
from mmu.lib._mmu_core_tests import multinomial_rvs
def test_erfinv():
"""Test C+... |
class Module(object):
__key__ = None
def start(self):
pass
|
#!/usr/bin/env python
## Program: VMTK
## Module: $RCSfile: vmtkmeshimplicitdistance.py,v $
## Language: Python
## Date: $Date: 2014/10/24 16:35:13 $
## Version: $Revision: 1.10 $
## Copyright (c) Luca Antiga, David Steinman. All rights reserved.
## See LICENCE file for details.
## This softwar... |
from datetime import datetime, timedelta
import os
import random
import names
from dateutil.relativedelta import relativedelta
from django.conf import settings
from db.models import Branch, CulturalFit, JobType, Language, LanguageLevel, Skill, SoftSkill, ProfileState, Benefit, \
JobRequirement, JobPostingState, P... |
from keras.preprocessing import image
from keras.models import Sequential,load_model
from keras.layers import Dense,Conv2D,Flatten,BatchNormalization,MaxPool2D,Dropout
import cv2
import numpy as np
from sklearn.utils import shuffle
import os
train_dir = "/data/train"
test_dir = "/data/test"
def data_loader(dir):
labe... |
# eine Liste initialisieren
prime_list = [2, 3, 5, 7, 11, 13]
# Listen können jegliche Objekte,
# auch gemischt und mehrfach enthalten
stuff = [5, 1.56363, 5, False, prime_list, None, False]
# einzelne Elemente referenzieren
first_prime = prime_list[0] #2
third_prime = prime_list[2] #5
last_prime = prime_list[-1] #13... |
from flask import Blueprint, render_template, redirect, url_for, flash
from solarvibes.models import User, Agripump, Agrimodule, Field
from flask_login import current_user
from flask_security import login_required
agripump_bp = Blueprint(
'agripump_bp',
__name__,
template_folder="templates"
)
###########... |
import tensorflow as tf
classes = 3
labels = tf.constant([1, 0, 2]) # 输入的元素值最小为0,最大为2
output = tf.one_hot(labels, depth=classes)
print("result of labels1:", output)
print("\n")
|
#!/usr/bin/env python
# coding: utf-8
import time
from operator import itemgetter
from aiocache import SimpleMemoryCache
from aiocache.serializers import JsonSerializer
from sanic import Sanic
from sanic.exceptions import NotFound
from sanic.response import json
from sanic_jinja2 import SanicJinja2
from tinydb import... |
from typing import List, Optional
from src.utils import print_util
# https://yzhong-cs.medium.com/serialize-and-deserialize-complex-json-in-python-205ecc636caa
class ShortcutParam(object):
def __init__(self, name: str, dynamic: bool = False, value: Optional[str] = ''):
self.name = name
self.dynam... |
import os
class XYZNamingScheme:
file_type = 'png'
basedir = './'
def __init__(self, file_type, basedir="./"):
self.file_type = file_type
self.basedir = basedir
def bound_name(self, lonTS, latTS):
"""Generate the name reference for the given bound"""
return "%s/%s" % (s... |
import json
import boto3
from flask import Flask, request
app = Flask(__name__)
@app.route('/devices/<device_id>', methods=['GET', 'POST'])
def manage_devices(device_id):
client = boto3.client('iot-data')
if request.method == 'GET':
response = client.get_thing_shadow(thingName=device_id)
else:
... |
from .toms import convert_toms_str
from .toms import replace_millis_str
from .toms import split_timestamp
__version__ = '0.4.5'
__all__ = ['convert_toms_str', 'split_timestamp', 'replace_millis_str']
|
#!/usr/bin/env python3
# Copyright 2021 DeepMind Technologies Limited
#
# 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 ... |
import telegram
from telegram import ParseMode
import time
class TelegramBot:
def __init__(self, token, chatId, botEnabled=True, monitor=None):
self.token = token
self.chatId = chatId
self.bot = telegram.Bot(token=self.token)
self.botEnabled = botEnabled
self.monitor = moni... |
import colored
import pandas as pd
import matplotlib.pyplot as plt
print(colored.stylize("\n---- | Plotting COVID-19 cases in specified country | ----\n", colored.fg("red")))
# dataframe
df = pd.read_csv("https://raw.githubusercontent.com/owid/covid-19-data/master/public/data/owid-covid-data.csv")
# smaller more use... |
import numpy as np
from sklearn.linear_model import LinearRegression
import math
from itertools import combinations
def print_LR(X, w, y, add_bias = True, n = 5, verbose = False):
W = np.diag(w)
if verbose:
print(W)
Z1 = np.dot(np.dot(X.T,W), X)
Z2 = np.linalg.inv(Z1)
Z3 = np.dot(Z2, np.do... |
import argparse
import sys
import hashlib
import hmac
from binascii import hexlify
try:
from scapy.all import *
except ImportError:
print "please install scapy: http://www.secdev.org/projects/scapy/ "
sys.exit()
def get_challenge_response(cfg_pcap_file):
r = rdpcap(cfg_pcap_file)
lens = map(lamb... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from datetime import datetime
from airflow import DAG
from airflow.operators.bash_operator import BashOperator
default_args = {'owner': 'afroot05'}
dag = DAG('stock_3minute_deploy_production',
default_args=default_args,
schedule_interval='0 6 * * *',
... |
# 5 seti 0 8 4 E = 0
# 6 bori 4 65536 3 D = E | 65536 (1000000000000000..)
# 7 seti 707129 0 4 E = 707129
# 8 bani 3 255 2 C = D & 255
# 9 addr 4 2 4 E = E + C
# 10 bani 4 16777215 4 E = E & 11111111111111
# 11 muli 4 65899 4 E *= 4
# 12 bani ... |
import unittest
import pytest
import spikeextractors as se
from spikesorters import KlustaSorter
from spikesorters.tests.common_tests import SorterCommonTestSuite
# This run several tests
@pytest.mark.skipif(not KlustaSorter.installed, reason='klusta not installed')
class KlustaCommonTestSuite(SorterCommonTestSuite, u... |
"""
parser.py
"""
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
def parse_args(description, defaults={}):
d = {'e': 0.1, 'f': '.3f', 'l': 0.1, 'n': 100}
for key, value in defaults.items():
d[key] = value
parser = ArgumentParser(
description=description,
fo... |
# Copyright 2017 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... |
# coding: utf-8
import sys
import grpc
import grpc_nlu_pb2
import grpc_nlu_pb2_grpc
if len(sys.argv) != 2:
print('Usage: python test_grpc.py "address:port"')
exit(1)
address = sys.argv[1]
channel = grpc.insecure_channel(address)
stub = grpc_nlu_pb2_grpc.RouteNLUStub(channel)
domains = stub.GetDomains(grp... |
import os,re, math
from xml.dom.minidom import *
from svgelements import *
iconRoot = ".."
blockList = ["dot"]
for filename in os.listdir(iconRoot):
if not filename.endswith(".svg"):
continue
filePath = os.path.join(iconRoot, filename)
source = open(filePath,'r').read()
if 'viewBox="0 0 60... |
import urllib
def get_sentence_from_source(source):
# The next two lines are absolutely the most horrible lines I've written in five years!
direct = [{**t, "direct": True} for t in [{k: sentence[k] for k in ('text', 'id', 'lang')} for sentence in source[1]]]
indirect = [{**t, "direct": False} for t in [{k... |
#!/usr/bin/python
'''
Defines a non-blocking lock context for threading.Lock objects
'''
import time
class NBLockContext(object):
'''
Creates a context for threading.Lock objects, similar to the default but which
returns the result of a non-blocking acquisition, rather than blocking till acquiring
Ex... |
from os.path import join
import json
import re
import string
from collections import OrderedDict
from markdown import Markdown
class Term(dict):
id = None
def __init__(self, *args, key="", **kwargs) -> None:
super().__init__(*args, **kwargs)
self.id = key
def set_item(self, item, data, ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.