content stringlengths 5 1.05M |
|---|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ----------------------------------------------------------------------
# Name: csv_plot_scatter_matrix.py
# Description:
#
# Author: m.akei
# Copyright: (c) 2020 by m.na.akei
# Time-stamp: <2020-08-30 15:06:06>
# Licence:
# Copyright (c) 2021 Masaharu... |
def disable_irq():
pass
def enable_irq():
pass
def freq():
pass
mem16 = None
mem32 = None
mem8 = None
def reset():
pass
def time_pulse_us():
pass
def unique_id():
pass
|
from django.conf.urls import url
from django.views import generic
from django.test.utils import override_settings
from django_webtest import WebTest
from .. import forms
@override_settings(ROOT_URLCONF=__name__)
class Test(WebTest):
def test_default_usecase(self):
page = self.app.get('/demo/registration/'... |
# Copyright 2018 The Cornac 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 applicable ... |
import asyncio
import pytest
@pytest.mark.asyncio
@asyncio.coroutine
def test_dependent_fixture(dependent_fixture):
"""Test a dependent fixture."""
yield from asyncio.sleep(0.1)
|
#!/usr/bin/env python3
import sys
import gitlab
import yaml
gl = gitlab.Gitlab.from_config('haskell')
proj = gl.projects.get(1)
existing = proj.labels.list(all=True)
existing = { label.name: label for label in existing }
for label in yaml.load(open('labels.yaml')):
print(label)
if label['name'] in existing:
... |
import os
import sys
import socket
import struct
import SocketServer
import threadpool
# fake ip list
FAKE_IPLIST = {}
# dns server config
TIMEOUT = 2 # set timeout 2 second
TRY_TIMES = 5 # try to recv msg times
DNS_SERVER = '8.8.8.8' # remote dns server
# currently not used
def bytetodomain(... |
import numpy as np
import torch
import cv2
from .deep.feature_extractor import Extractor
from .sort.nn_matching import NearestNeighborDistanceMetric
from .sort.preprocessing import non_max_suppression
from .sort.detection import Detection
from .sort.tracker import Tracker
__all__ = ['DeepSort']
class DeepSort(obje... |
import wx
import cv2 as cv
from app.WebCam import WebCam
class OwlFrame(wx.Frame):
def __init__(self):
style = wx.STAY_ON_TOP | wx.RESIZE_BORDER | wx.CLOSE_BOX | wx.CAPTION
super(OwlFrame, self).__init__(None, title="OwlFrame", style=style)
self.pnl = wx.Panel(self)
# Set 30 fps ... |
from typing import Dict, List, Iterable, Tuple
import transition
Transition = Dict[str, str]
MachineParams = Dict[str, str]
def is_machine_param(pairs: MachineParams) -> bool:
"""Checks if a list of pairs is a machine parameter."""
compiler_params = ['start', 'empty_symbol']
return any([key in compiler... |
import json, sys
nounwind_attributor = 0
nounwind_functionattrs = 0
with open(sys.argv[1]) as f:
data = json.load(f)
for key1, value1 in data.items():
if key1 != 'tests':
continue
for test in value1:
for key, value in test.items():
if key != 'metrics':
... |
import cProfile
import contextlib
import enum
import errno
import io
import json
import os
import pstats
import subprocess
import time
import ws.cworker
import ws.logs
import ws.sockets
import ws.signals
import ws.worker
from ws.config import config
from ws.err import *
from ws.logs import error_log, profile_log
SERV... |
import numpy as np
from numpy.testing import assert_array_equal
from cloudbusting.tools import *
def test_rle_to_mask():
#test1: null case
rle = []
shape = (5,6)
out = rle_to_mask(rle, shape)
expected = np.zeros([5,6], dtype=bool)
assert_array_equal(out, expected)
#test2
rle = [1, ... |
#-- THIS LINE SHOULD BE THE FIRST LINE OF YOUR SUBMISSION! --#
def all_truthy(values):
return all(values)
#-- THIS LINE SHOULD BE THE LAST LINE OF YOUR SUBMISSION! ---#
### DO NOT SUBMIT THE FOLLOWING LINES!!! THESE ARE FOR LOCAL TESTING ONLY!
assert(all_truthy([True, "yes", "no", 1, [{}]]))
assert(all_truthy([]... |
import logging
log_name = 'runtime.log'
LOGGER = logging.getLogger(__name__)
fh = logging.FileHandler(encoding='utf-8', mode='a', filename=log_name)
logging.basicConfig(handlers=[fh], format='[%(asctime)s %(levelname)s]<%(process)d> %(message)s',
datefmt='%Y-%m-%d %H:%M:%S', level=logging.INFO) |
from plugins import BasePlugin
from plugins import PluginsData
class ScreenDumpPlugin(BasePlugin):
def run(self, rule, data=None, rows_display_limit = 100):
if data and isinstance(data, PluginsData):
print 'Fields:'
for field in data.fields:
print ' {0}'.format(fiel... |
import os
import numpy
class BaseContainer(object):
filename = os.path.join(os.path.dirname(__file__), '../test_data.csv')
data = numpy.genfromtxt(filename, delimiter=',', skip_header=1)
X = numpy.array(data[:, 0:5])
y = numpy.array(data[:, 5])
|
import abc
import textwrap
class GitHook(metaclass=abc.ABCMeta):
"""
Base class to define a Git hook usable by `hooks` task.
"""
@abc.abstractmethod
def name(self):
"""
:rtype: unicode
:return: Name of hook.
"""
@abc.abstractmethod
def script(self):
... |
from common.permissions.action_based_permissions import Action
from common.permissions.http_based_permissions import HTTP
from common.permissions.permissions import *
|
from keras.layers import concatenate, add, multiply
from numpy import average
from tensorflow.keras import backend as K
from tensorflow.keras.layers import Layer
from tensorflow.keras import initializers as initializations
from tensorflow.keras import regularizers, constraints
from tensorflow.keras.layers import Add, ... |
"""This module implements the Luhn algorithm.
It is used to check validity of various identification numbers.
For example: credit card number, Canadian Social Insurance Numbers,
survey codes on MacDonald and Taco Bell, etc.
Note: It is not intended to be a cryptographically secure hash
function; it was designed to pr... |
__author__ = "Manuel Escriche <mev@tid.es>"
import os
import base64
import requests
import xlsxwriter
import re
from datetime import date, datetime
from xlsxwriter.utility import xl_range
from operator import attrgetter
from collections import namedtuple
from kernel.Settings import settings
from kernel.SheetFormats im... |
"""Tests of the learning curve regression workflow.
Scientific Machine Learning Benchmark:
A benchmark of regression models in chem- and materials informatics.
2020, Citrine Informatics.
"""
import pytest
pytest.importorskip("sklearn")
import smlb
def test_learning_curve_regression():
"""Simple examples"""
... |
from itertools import zip_longest
class Solution:
def compareVersion(self, version1: str, version2: str) -> int:
v1s, v2s = (
list(map(int, version1.split("."))),
list(map(int, version2.split("."))),
)
for v1, v2 in zip_longest(v1s, v2s, fillvalue=0):
if... |
import os
import tuned.logs
from . import base
from tuned.utils.commands import commands
log = tuned.logs.get()
class cpulist_invert(base.Function):
"""
Inverts list of CPUs (makes its complement). For the complement it
gets number of online CPUs from the /sys/devices/system/cpu/online,
e.g. system with 4 CPUs (0... |
#!/usr/bin/python3
import os
import pathlib
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.transforms as transforms
plt.style.use('../stylesheet.mplstyle')
from nmrespy.core import Estimator
# ------------------------------------------------------------------------
# ... |
"""
util_array module. Contains the util_2d, util_3d and transient_2d classes.
These classes encapsulate modflow-style array inputs away
from the individual packages. The end-user should not need to
instantiate these classes directly.
"""
from __future__ import division, print_function
# from future.utils... |
# Copyright 2016 Google Inc. 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 applicable law or agree... |
import socket
from urlparse import urlparse
import re
import sys
class HttpResponse:
def __init__(self, headerString):
self.init()
self.parse(headerString)
def init(self):
#Contain the header parameters
self.mHeaders = dict()
self.mResponseCode = -1
... |
import configparser,os,copy
from pathlib import Path
SERVER_SECTION= 'server'
CLIENT_SECTION= 'client'
def write_back(func):
def inner_func(*args,**kwargs):
GuiConfigs.need_write_back=True
func(*args,**kwargs)
return inner_func
class GuiConfigs():
need_write_back=False
DICT_HOST = "d... |
"""
Tests for the ``releases.util`` module.
These are in the integration suite because they deal with on-disk files.
"""
import os
from docutils.nodes import document
from spec import Spec, ok_, eq_
from sphinx.application import Sphinx
from releases.models import Release, Issue
from releases.util import get_doctre... |
from ..api import issue, worklog
import inject
class FindIssues(object):
def __init__(self, subparsers):
super().__init__()
sub = subparsers.add_parser('find',
help='find issues')
sub.add_argument('filters', metavar='filter', nargs='*')
sub.set_d... |
import importlib
import sys
""" Rudimentary test runner for plugins
Pass in the plugin name as an argument, and make sure that there is a test.py file with a run() function in the plugin
directory.
"""
plugin = sys.argv[1]
test = importlib.import_module('plugins.' + plugin + '.test')
test.run()
|
class Key:
def __init__(self):
self.api_key = '1VTP01G4K4XHMPAB' |
from math import *
import numba
import numpy as np
import sympy
from scipy.special import gamma
from sympy.utilities.lambdify import lambdastr
import golf_course.estimate.numba as nestimate
class Target(object):
"""
Target
A class that describes regions around important points in the energy function.
... |
from unittest.mock import AsyncMock, MagicMock, PropertyMock
import pytest
import gidgethub
import abstracts
from aio.api import github
from aio.api import github as base_github
@abstracts.implementer(github.AGithubIssue)
class DummyGithubIssue:
pass
@abstracts.implementer(github.AGithubIssues)
class Dummy... |
"""
A watchdog timer
"""
import machine
class WatchDogTimer(object):
def __init__(self, period, timer_id=-1):
self.period = period
self.timer = machine.Timer(timer_id)
self._start()
def _start(self):
self.timer.init(
period=self.period,
mode=mac... |
import inspect
import pickle
import cv2
import numpy as np
from ColorComponents import ColorComponents
from HOGExtractor import HOGExtractor
from HistExtractor import HistExtractor
from SpacialExtractor import SpacialExtractor
class FeatureCombiner:
def __init__(self, extractors, pickle_path=None):
fram... |
from django.views.generic import TemplateView, FormView
from .readopensecrets import read_contributions, read_contibutors
from .readpolitifact import read_recent_statements
from .fivethirtyeight import getPollNum
from django.http.response import HttpResponseRedirect
from django.shortcuts import reverse
from .forms impo... |
# coding=utf-8
"""
サーバー
"""
import datetime
import json
import logging
import os
import pathlib
import Mykytea
import flask
import flask_api.status
import flask_classy
import configs
# 作者
__author__ = 'Masaya Suzuki'
# バージョン
__version__ = '0.1.6'
# 設定
conf = configs.Config(pathlib.Path.cwd().parent / 'configs')
... |
from tkinter import*
import random
import time
root = Tk()
root.geometry("1100x700+150+5")
root.title("Restaurant Billing System")
Tops = Frame(root,width = 900,height=50)
Tops.pack(side=TOP)
f1 = Frame(root,width=1600,height=700)
f1.pack(side=LEFT)
#------------------TIME--------------
localtime=time.... |
# ------------------------------------------------------------------------------
# pose.pytorch
# Copyright (c) 2018-present Microsoft
# Licensed under The Apache-2.0 License [see LICENSE for details]
# Written by Bin Xiao (Bin.Xiao@microsoft.com)
# ----------------------------------------------------------------------... |
#!/usr/bin/env python
import argparse
from pprint import pprint
def get_args():
'''This function parses and return arguments passed in'''
parser = argparse.ArgumentParser(
prog='Alignment to specie',
description='From a sam file, returns specie names')
parser.add_argument('mapsam', help="... |
"""
Minmal czi file example
"""
import czifile as zis
import numpy as np
import napari
file_name = 'data-njs/zeiss/CellDivision_T=10_Z=15_CH=2_DCV_small.czi'
czi = zis.CziFile(file_name)
cziarray = czi.asarray()
#cziarray = np.squeeze(cziarray)
print('czi file shape', cziarray.shape)
with napari.gui_qt():
napari.... |
"""
Rushing Statistics Model
"""
from django.db.models import \
BooleanField, DecimalField, ForeignKey, Model, PROTECT
class RushingStats(Model):
"""
Contains the rushing statistics for a player
"""
player = ForeignKey(
'Player',
on_delete=PROTECT,
null=False
)
att_... |
import baza1 as baza
import sqlite3
conn = sqlite3.connect('letalski_prevozi.db')
baza.ustvari_bazo_ce_ne_obstaja(conn)
conn.execute('PRAGMA foreign_keys = ON')
def commit(fun):
"""
Dekorator, ki ustvari kurzor, ga poda dekorirani funkciji,
in nato zapiše spremembe v bazo.
Originalna funkcija je na vo... |
#Copyright [2017] [Mauro Riva <lemariva@mail.com> <lemariva.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.apache.org/licenses/LICENSE-2.0
#
#Unless required by applicable l... |
# ---
# jupyter:
# jupytext:
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.5.0
# kernelspec:
# display_name: Python 3
# language: python
# name: python3
# ---
# + run_control={"frozen": false, "read_only": false}
f... |
"""
This script auto-generates the
"""
import yaml
import os
import re
final_md = (
"""\
# Per rule explanation
This is an automatically generated list of all supported rules, their docstrings, and command. At the start of each \
workflow run a list is printed of which rules will be run. And while the workflow is run... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Interpreter version: python 2.7
#
"""
This module contains functions to convert `DOM` relations to `path-like` lists
of elements defined by tag names and parameters.
"""
# Imports =====================================================================
# Functions & obj... |
from __future__ import unicode_literals
from .common import InfoExtractor
from ..utils import (
ExtractorError,
traverse_obj,
)
class MixchIE(InfoExtractor):
IE_NAME = 'mixch'
# allow omitting last /live in the URL, though it's likely uncommon
_VALID_URL = r'https?://(?:www\.)?mixch\.tv/u/(?P<id>... |
# coding: utf8
from aenum import Enum
__author__ = "Timothy Heys"
__email__ = "theys@kayak.com"
class Arithmetic(Enum):
add = '+'
sub = '-'
mul = '*'
div = '/'
class Comparator(Enum):
pass
class Equality(Comparator):
eq = '='
ne = '<>'
gt = '>'
gte = '>='
lt = '<'
lte ... |
import subprocess
import tempfile
import SimpleITK as sitk
import numpy as np
from disptools import *
def jacobian_to_atrophy_map(image: sitk.Image) -> sitk.Image:
r""" Convert a Jacobian map to a atrophy map.
The atrophy rate :math:`a` is defined as the pointwise percentage of
volume loss, so :math:`a ... |
# -*- coding: utf-8 -*-
import datetime
import matplotlib.pyplot as plt
import pandas as pd
class EPEsoMonthlyVariable():
"""A class for a monthly variable recorded in an `EPEsoSimulationEnvironment` instance.
.. note::
An EPEsoMonthlyVariable instance is returned as the result of
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 11 12:02:21 2018
@author: Niccolo' Dal Santo
@email : niccolo.dalsanto@epfl.ch
"""
import pyorb_core.error_manager as em
import numpy as np
import pyorb_core.algebraic_utils as alg_ut
def default_theta_function( _param, _q ):
em.error_raiser(... |
#!/usr/bin/python
"""
add
"""
from containernet.net import Containernet
from containernet.node import DockerSta, Docker
from containernet.cli import CLI
from containernet.term import makeTerm
from mininet.log import info, setLogLevel
from mn_wifi.link import wmediumd
from mn_wifi.wmediumdConnector import interference
i... |
# _*_ coding: utf-8 _*_
# !/usr/bin/env python3
"""
Mictlantecuhtli: A Multi-Cloud Global Probe Mesh Creator.
@author: Collisio-Adolebitque
"""
from .__main__ import *
__version__ = '0.0.1'
__all__ = ["CommandParser", "Terraform", "AWS", "GCP", "Azure", "Alibaba"]
|
'''
==========================
Hyperparameter Selection 2
==========================
This example demonstrates how to do model selection in a pipeline where segments are learned directly by a neural network
'''
# Author: David Burns
# License: BSD
import matplotlib.pyplot as plt
from keras.layers import Dense, LSTM,... |
def double_pole_fitness_func(target_len, cart, net):
def fitness_func(genes):
net.init_weight(genes)
return net.evaluate(cart, target_len)
return fitness_func
|
import pyperclip
def GetTime(text_header):
print(text_header)
hours = raw_input("Hours: ")
minutes = raw_input("Minutes: ")
seconds = raw_input("Seconds: ")
total_seconds = (int(hours) * 3600) + (int(minutes) * 60) + int(seconds)
print(total_seconds)
return total_seconds
url = raw_input("... |
def predict(x,u,A,B,P,Q):
"""
Prediction step of the Kalman filter
Input:
x - state vector
u - input vector
A - process matrix
B - input-to-state matrix
P - state covariance matrix
Q - evolution noise
Returns:
x - predicted state
P - predicted covariance
"""... |
x=int(input())
for i in range(x):
print(x-i)
|
import os
import sys
import unittest
try:
from collections import OrderedDict
except ImportError:
from ordereddict import OrderedDict
try:
import numpy
has_numpy = True
except ImportError:
has_numpy = False
sys.path.insert(1, '../')
import f90nml
from f90nml.fpy import pybool
from f90nml.namelist ... |
import gym
from rlkit.data_management.obs_dict_replay_buffer import ObsDictRelabelingBuffer
from rlkit.torch.data_management.normalizer import CompositeNormalizer
from rlkit.torch.optim.mpi_adam import MpiAdam
from rlkit.launchers.launcher_util import run_experiment
from rlkit.torch.relational.networks import *
from rl... |
import swgpy
from swgpy.object import *
from swgpy.sui import RadialMenu, RadialOptions, RadialOptionsList, RadialIdentifier
from swgpy.utility import vector3, quat
class PyRadialMenu(RadialMenu):
def buildRadial(self, owner, target, radials):
radial_list = RadialOptionsList()
radial_list.append(RadialOptions(... |
from django.contrib.auth import authenticate
from django.core.exceptions import ObjectDoesNotExist
from rest_framework import permissions
from . import app_settings
def is_authenticated(user):
return user is not None and user.is_authenticated
def is_django_staff(user):
return user and (user.is_staff or us... |
# Generated by Django 3.1.13 on 2021-09-17 07:17
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('pokemon_entities', '0004_pokemonentity_pokemon'),
]
operations = [
migrations.AddField(
model_name='pokemonentity',
... |
import numpy as np
def split_train_test_indices(num_docs, prop_to_split=0.5, seed=42):
np.random.seed(seed)
indices = np.arange(num_docs)
np.random.shuffle(indices)
num_sample = int(num_docs * prop_to_split)
train_indices = indices[:num_sample]
test_indices = indices[num_sample:]
return train_indices, test_indi... |
import sys
import glob
KATAKANA = ('。「」、・ヲァィゥェォャョラッー'
'アイウエオカキクケコサシスセソタチツテトナニヌネノ'
'ハヒフヘホマミムメモヤユヨラリルレロワヲン')
args = sys.argv # text2imageを実行した先の一時フォルダ名を第1変数として渡す
# 半角カナ→全角カナ, 全角英数記号→半角
# 日本語的におかしい濁点・半濁点などが含まれる場合は厳密には考慮してない(前の文字によって変な結果になる)
# new_linesの項目削除で文字単位のbox座標が崩れるが、LSTM学習用に行ごとに座標をまとめるので結... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
import json
import os
import requests
from .request_params import request_column, request_settings
from .utils import get_data_in_format, get_input_range
def get_new_port_number(experiment_name: str) -> json:
"""Get the latest episode num... |
"""
列表基础操作list
遍历
"""
list_name = ["郭世鑫", "涛涛", "罗耀泽"]
# 1. 从头到尾读取
for item in list_name:
print(item)
# 2. 非从头到尾读取
# 需求:将姓名是2个字的人名改为空字符串
# -- 修改
for i in range(len(list_name)):
if len(list_name[i]) == 2:
list_name[i] = ""
# 需求:非从尾到头读取(一行一个)
# 因为切片会创建新(拷贝)列表,浪费内存
# for item in list_name[::-... |
# The MIT License (MIT)
#
# Copyright (c) 2018 Carter Nelson
#
# 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, mod... |
class Solution:
def countLargestGroup(self, n: int) -> int:
ans, d = 0, collections.defaultdict(list)
for i in range(1, n + 1):
# get sum of digs
s = sum([int(n) for n in str(i)])
d[s].append(i)
# get max group
mx = max([len(v) for k, v in d.items()])
return sum([1 for k, v in... |
from . import export_d3po
from . import export_plotly
|
import time
import pygatt # type: ignore
from .constants import CHAR_TX, CHAR_FEEDBACK, PyHatchBabyRestSound
class PyHatchBabyRest(object):
""" A synchronous interface to a Hatch Baby Rest device using pygatt. """
def __init__(self, addr: str = None, adapter: pygatt.GATTToolBackend = None):
""" Ins... |
# flake8: noqa
from tune_hyperopt.optimizer import HyperoptLocalOptimizer
|
# 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 u... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.9 on 2016-08-31 06:32
from __future__ import unicode_literals
import cloudinary.models
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependenc... |
from xml_collation.core_functions import collate_xml
from xml_collation.core_functions import collate_xml_example
from xml_collation.core_functions import collate_xml_svg
__all__ = ["collate_xml", "collate_xml_example", "collate_xml_svg"]
|
# -*- coding: utf-8 -*-
"""
This file is part of pyCMBS.
(c) 2012- Alexander Loew
For COPYING and LICENSE details, please refer to the LICENSE file
"""
from pycmbs.data import Data
from pycmbs.diagnostic import PatternCorrelation
import matplotlib.pyplot as plt
import numpy as np
file_name = '../../../pycmbs/examples/... |
#!usr/bin/python
# # -*- coding:utf8 -*-
import os
import tornado.ioloop
import tornado.web
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.render("base.html")
class ErrorHandler(tornado.web.RequestHandler):
def get(self):
self.render("500.html", msg="We're sorry, but somet... |
#!/usr/bin/env python
import cvtestutils
import unittest
from cv import *
class moments_test(unittest.TestCase):
def setUp(self):
# create an image
img = cvCreateMat(100,100,CV_8U);
cvZero( img )
# draw a rectangle in the middle
cvRectangle( img, cvPoint( 25, 25 ), cvPoint(... |
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestRegressor
from sklearn.model_selection import KFold
import statistics
from tqdm.notebook import tqdm
def uncertainty_rfr_qfr(df, X, Y, o, d_start=12, label_start=0, label_end=5,
... |
from scipy.spatial import cKDTree
from collections import defaultdict
import numpy as np
import argparse
from pickle import load, dump
import pandas as pd
def sumCells(vor, heatmap):
# Generate all points to loop through
x = np.linspace(vor.min_bound[0], vor.max_bound[0], heatmap.shape[0])
y = np.linspac... |
from django.urls import path,include,re_path
from . import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns=[
path(r'',views.index,name = 'index'),
#path(r'^signup/$', views.signup, name='signup'),
path(r'^create/profile/$',views.create_profile, name='create-p... |
#!/usr/bin/python -u
import time
import os
import glob
import board
import busio
from adafruit_ht16k33 import segments
os.system('modprobe w1-gpio')
os.system('modprobe w1-therm')
base_dir = '/sys/bus/w1/devices/'
# Grabs the first probe out of the directory
device_folder = glob.glob(base_dir + '28*')[0]
device_file... |
# Copyright The Linux Foundation and each contributor to CommunityBridge.
# SPDX-License-Identifier: MIT
import csv
import logging
import os
import sys
import boto3
import botocore.session
import click
from botocore.exceptions import ClientError
from audit import ProjectAudit
@click.command()
@click.option("--aws-... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import socket
target_host = '127.0.0.1'
target_port = 8787
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
client.sendto("message here", (target_host, target_port))
data, addr = client.recvfrom(4096)
print(data)
|
from data_collection.management.commands import BaseXpressDemocracyClubCsvImporter
class Command(BaseXpressDemocracyClubCsvImporter):
council_id = "E09000025"
addresses_name = "local.2018-05-03/Version 2/LBNewham Democracy_Club__03May2018.TSV"
stations_name = "local.2018-05-03/Version 2/LBNewham Democracy... |
import requests
from config import GRAPHQL_API, HEADERS
def run_query(query): # A simple function to use requests.post to make the API call. Note the json= section.
request = requests.post(GRAPHQL_API, json={'query': query}, headers=HEADERS)
if request.status_code == 200:
return request.json()
el... |
from georef_ar_etl.models import Province
from georef_ar_etl.exceptions import ProcessException
from georef_ar_etl.provinces import ProvincesExtractionStep
from . import ETLTestCase
class TestEntitiesExtractionStep(ETLTestCase):
def setUp(self):
super().setUp()
self._tmp_provinces = self.create_te... |
from django.apps import AppConfig
class ExpeConfig(AppConfig):
name = 'experiments'
|
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# Copyright 2017 Timothy Dozat
#
# 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 ... |
import torch
import torch.nn as nn
import torch.utils.data as Data
import torchvision # this is the database of torch
from torchvision import datasets, transforms
class Discriminator(torch.nn.Module):
def __init__(self):
super(Discriminator, self).__init__()
self.feature = nn.Sequential(
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# File : Ampel-core/ampel/core/ContextUnit.py
# License : BSD-3-Clause
# Author : vb <vbrinnel@physik.hu-berlin.de>
# Date : 07.10.2019
# Last Modified Date: 19.09.2021
# Last Modified By : vb <vbrinnel@physik.hu-berlin.de>
f... |
from __future__ import absolute_import, division, print_function
import os
import sys
import argparse
from math import log
from tqdm import tqdm
from copy import deepcopy
import numpy as np
import gzip
import pickle
import random
from datetime import datetime
import matplotlib.pyplot as plt
import torch
from easydict ... |
import configparser
import os
import ast
from zaailabcorelib.zconfig.constant import *
class ZConfig():
__instance = None
@staticmethod
def getInstance():
""" Static access method. """
if ZConfig.__instance == None:
ZConfig.__instance = ZConfig()
return ZConfig.__instan... |
#!/usr/bin/env python3
import csv
import os
import sys
import gpsd
import argparse
from scapy.all import *
from multiprocessing import Process, current_process, Value
### Global Declaration ###
BANNER ="""
_, _, ___, ,_ ,_ , _, ___,___,_,,_
(_,(_,' | | \, |_)| / \,' | ' | /_,|_)
_) _) _|_,_|_/... |
# BSD 3-Clause License
# Copyright (c) 2017, Federico T.
# 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
# list o... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-02-20 20:07
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('lookup_tables', '0009_infrastructure_elevation'),
]
operations = [
migratio... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.