text stringlengths 1 927k |
|---|
#!/usr/bin/python
euler1 = dict()
euler1[range] = 1000
solver = lambda x: sum(i for i in xrange(x) if i%3==0 or i%5==0)
euler1[solver] = solver
result = euler1[solver] (euler1[range])
euler1[result] = result
print euler1[result] |
import glob
import os
from conans import ConanFile, tools, AutoToolsBuildEnvironment, VisualStudioBuildEnvironment
class LibxsltConan(ConanFile):
name = "libxslt"
url = "https://github.com/conan-io/conan-center-index"
description = "libxslt is a software library implementing XSLT processor, based on libxm... |
"""
Readme.txt:
Required modules: random, sys, hashlib, sha3
Please read the comments below for further explanation.
"""
from random import *
import sys
import hashlib
if sys.version_info < (3, 6):
import sha3
def serialnoncegenerator(): # To generate uniformly randomly 128-bit integer
serial = str(randint(... |
# Copyright The PyTorch Lightning team.
#
# 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 i... |
"""
Profile ../profile-datasets-py/div83/028.py
file automaticaly created by prof_gen.py script
"""
self["ID"] = "../profile-datasets-py/div83/028.py"
self["Q"] = numpy.array([ 2.70658300e+00, 2.88421200e+00, 3.36234900e+00,
4.31645100e+00, 5.09368400e+00, 5.28904200e+00,
5.1902... |
import datetime
from django.conf import settings
from nose.tools import eq_
from pyquery import PyQuery as pq
from amo.tests import app_factory, mock_es
from amo.urlresolvers import reverse
import mkt
from mkt.browse.tests.test_views import BrowseBase
from mkt.webapps.models import Webapp
from mkt.zadmin.models imp... |
# for localized messages
from . import _
# Config
from Components.config import config, ConfigYesNo, ConfigNumber, ConfigSelection, \
ConfigSubsection, ConfigSelectionNumber, ConfigDirectory, NoSave
from Screens.MessageBox import MessageBox
from Screens.Standby import TryQuitMainloop
from Tools.BoundFunction import b... |
import numpy as np
import pandas as pd
from openmodelica_microgrid_gym.util import RandProcess
class RandomLoad:
def __init__(self, train_episode_length: int, ts: float, rand_process: RandProcess, loadstep_time: int = None,
load_curve: pd.DataFrame = None, bounds=None, bounds_std=None):
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('api', '0021_card_video_story'),
]
... |
import numpy
import numpy as np
import datetime
import pytest
from numpy.testing import (
assert_, assert_equal, assert_raises, assert_warns, suppress_warnings,
assert_raises_regex,
)
from numpy.compat import pickle
# Use pytz to test out various time zones if available
try:
from pytz import timezone a... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... |
# GTP for Trojan-go
# Helper file
import re
def pre_engine(s):
s = re.sub("[^\t\n -~]", "", s)
s = s.split("#")[0]
s = s.replace("\t", " ")
return s
def pre_controller(s):
s = re.sub("[^\t\n -~]", "", s)
s = s.replace("\t", " ")
return s
def gtp_boolean(b):
return "true" if b else "... |
"""
Copyright (C) 2018-2020 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to i... |
#!/usr/bin/env python2.7
# Copyright (C) 2014-2015 Job Snijders <job@instituut.net>
#
# This file is part of ACLHound
#
# 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... |
from ._constants import DEFAULT_ENDPOINT
from ._types import Options
from ._version import __version__
from typing import Any, Union, Optional, IO, Mapping, Tuple, List
import aiohttp, urllib.parse, json, re, platform
import websockets, websockets.client
Payload = Optional[Union[dict, str, bytes, IO]]
def _prepare_he... |
import collections
import itertools
import os
import random
import time
import typing
from qtpy import QtCore as QC
from qtpy import QtWidgets as QW
from qtpy import QtGui as QG
from hydrus.core import HydrusConstants as HC
from hydrus.core import HydrusData
from hydrus.core import HydrusExceptions
from hydrus.core i... |
from pydantic import BaseModel
from .ip_address import IpAddressModel
class NetworkHostModel(BaseModel):
ip_address: IpAddressModel |
from django.conf.urls import url
from . import views
urlpatterns=[
#index path
url('^$', views.index,name='index'),
url('location/', views.category, name='location'),
url('category', views.category, name='category'),
url('search/', views.search_results, name='search_results'),
] |
'''copyright Xiaosheng Wu Python game 12/31/2015'''
import pygame, sys
from classes import *
from process import *
pygame.init()
SCREENWIDTH,SCREENHEIGHT = 767,1257
screen = pygame.display.set_mode((SCREENWIDTH,SCREENHEIGHT)) #zero for the flag 32 for color
BackGround = pygame.image.load("images/bg.png")
Header = p... |
# Generated by Django 3.0.3 on 2020-02-21 19:56
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('letters', '0003_auto_202... |
from mpi4py import MPI
import matplotlib.pyplot as plt
import numpy as np
import time
def sim_rand_walks_parallel(n_runs):
# Get rank of process and overall size of communicator:
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
size = comm.Get_size()
# Start time:
t0 = time.time()
# Evenly di... |
# Copyright 2017 Stefan Richthofer
#
# 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 ... |
class LinkClickedEventHandler(MulticastDelegate,ICloneable,ISerializable):
"""
Represents the method that will handle the System.Windows.Forms.RichTextBox.LinkClicked event of a System.Windows.Forms.RichTextBox.
LinkClickedEventHandler(object: object,method: IntPtr)
"""
def BeginInvoke(self,sender,e,callback,o... |
from __future__ import division
from cctbx.eltbx import wavelengths
from libtbx.test_utils import approx_equal
def exercise():
from cctbx import factor_kev_angstrom
w = wavelengths.characteristic("CU")
assert w.label() == "Cu"
assert approx_equal(w.as_angstrom(), 1.5418)
assert approx_equal(w.as_kev(), facto... |
plus = lambda x, y: x + y
current_list = [0, 1]
next_list = []
n = int(input())
if n > 0: print(1)
for i in range(n-1):
current_list.append(0)
next_list = list(map(plus, current_list[1:], current_list))
print(*next_list,sep=' ')
current_list = next_list
current_list.insert(0, 0)
next_list = [] |
from typing import Optional
from celery import app
from celery.utils.log import get_task_logger
from gnosis.eth import EthereumClientProvider
from gnosis.eth.ethereum_client import EthereumNetwork
from safe_transaction_service.history.utils import close_gevent_db_connection
from .models import Token
logger = get_t... |
from amqpstorm.management import ApiError
from amqpstorm.management import ManagementApi
from amqpstorm.tests import HTTP_URL
from amqpstorm.tests import PASSWORD
from amqpstorm.tests import USERNAME
from amqpstorm.tests.functional.utility import TestFunctionalFramework
from amqpstorm.tests.functional.utility import se... |
fileObj = open('answer.txt',"r")
ch = ""
vCount = 0
cCount = 0
while ch:
ch = fileObj.read(1) #one character read from file
if ch in ['A','a','E','e','I','i','O','o','U','u']:
vCount+=1
else:
cCount+=1
print("Vowels in the file: ", vCount)
print("Consonants in the file: ",cCount)
#cl... |
"""A TaskRecord backend using mongodb
Authors:
* Min RK
"""
#-----------------------------------------------------------------------------
# Copyright (C) 2010-2011 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distributed as part of t... |
#!/usr/bin/env python3
# Copyright © 2021 Pavel Tisnovsky
#
# 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... |
'''
Train
Train your nerual network
Author: Tawn Kramer
'''
from __future__ import print_function
import os
import sys
import glob
import time
import fnmatch
import argparse
import numpy as np
from PIL import Image
import keras
import conf
import random
import augment
import models
'''
matplotlib can be a pain to set... |
# Copyright (c) 2013, Web Notes Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals
import frappe
from frappe.website.doctype.website_settings.website_settings import get_website_settings
from frappe.website.template import render_blocks
from frappe.website.r... |
import ujson
import uuid
import time
import zlib
import base64
from typing import Any, Dict, Tuple, Union
PROTOCOL_VERSION = 'tomodachi-json-base--1.0.0'
class JsonBase(object):
@classmethod
async def build_message(cls, service: Any, topic: str, data: Any, **kwargs: Any) -> str:
data_encoding = 'raw'... |
import sys
import numpy as np
from planning.path_generator.astar import *
def plot_global_map(path, obstacles):
fig, ax = plt.subplots()
for o in obstacles:
patch = o.get_plot_patch()
ax.add_patch(patch)
ax.plot(path[:, 0], path[:, 1])
plt.xlim([-1 * 0.15, 11 * 0.15])
plt.ylim([0... |
"""
Common routines for models in PyTorch.
"""
__all__ = ['HSwish', 'get_activation_layer', 'conv1x1', 'conv3x3', 'depthwise_conv3x3', 'ConvBlock', 'conv1x1_block',
'conv3x3_block', 'conv7x7_block', 'dwconv3x3_block', 'dwconv5x5_block', 'PreConvBlock', 'pre_conv1x1_block',
'pre_conv3x3_block'... |
# parameters_t.py
#-*- coding: utf-8 -*-
from decimal import Decimal
from loris import img_info
from loris.loris_exception import RequestException
from loris.loris_exception import SyntaxException
from loris.parameters import DECIMAL_ONE
from loris.parameters import FULL_MODE
from loris.parameters import PCT_MODE
from... |
# import apex - !!!! INCLUDE THIS IMPORT IF YOU WANT TO USE MIXED PRECISION TRAINING !!!!
import torch
import os
import sys
import torch.optim as optim
import torch.nn as nn
from datetime import datetime
from tqdm import tqdm
from pathlib import Path
# Make sure that the project root is in your PATH (i.e., the parent ... |
from django.urls import path
from . import views
app_name = "main_app"
urlpatterns = [
path('', views.home, name="home"),
path('home/', views.home, name="home"),
path('register/', views.register, name="register"),
path('logout/', views.logout_request, name="logout"),
path('login/', views.login_req... |
from chain.core.api import Resource, ResourceField, CollectionField, \
MetadataCollectionField
from chain.core.api import full_reverse, render_error
from chain.core.api import CHAIN_CURIES
from chain.core.api import BadRequestException, HTTP_STATUS_BAD_REQUEST
from chain.core.api import register_resource
from chain... |
######################################
#######ORIGINAL IMPLEMENTATION########
######################################
# FROM https://github.com/kunhe/FastAP-metric-learning/blob/master/pytorch/FastAP_loss.py
# This code is copied directly from the official implementation
# so that we can make sure our implementation ret... |
import os
from setuptools import setup
PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
with open(os.path.join(PROJECT_ROOT, 'flake8_flask.py')) as file_:
version_line = [line for line in file_ if line.startswith('__version__')][0]
__version__ = version_line.split('=')[1].strip().strip("'").strip('"')
... |
from reportlab.lib import colors
from reportlab.lib.units import inch
from reportlab.platypus import Image
from testplan.common.exporters.pdf import RowStyle, create_table
from testplan.common.exporters.pdf import format_table_style
from testplan.common.utils.registry import Registry
from testplan.testing.multitest.en... |
'''
The provided code stub will read in a dictionary containing key/value pairs of
name:[marks] for a list of students. Print the average of the marks array for
the student name provided, showing 2 places after the decimal.
'''
if __name__ == '__main__':
n = int(input())
student_marks = {}
for _ in rang... |
import h5py
filename = './sem_seg/indoor3d_sem_seg_hdf5_data/ply_data_all_0.h5'
#filename = './sem_seg/converted_KITTI/frame_10.h5'
f = h5py.File(filename, 'r')
data_file = f['data'][:]
label_file = f['label'][:]
print (data_file.shape, label_file.shape)
print (type(label_file[0])) |
import re
from itertools import combinations
from utils.solution_base import SolutionBase
class Solution(SolutionBase):
def solve(self, part_num: int):
self.test_runner(part_num)
func = getattr(self, f"part{part_num}")
result = func(self.data)
return result
def test_runner(s... |
# coding: utf-8
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# ---------------------------------------------------------------------... |
fieldID = sm.getFieldID()
if fieldID == 811000500:
sm.warpInstanceOut(811000008)
elif not sm.hasMobsInField():
sm.warp(fieldID + 100)
else:
sm.chat("The portal is not opened yet.")
sm.dispose() |
import asyncio
from telethon import events
from telethon.tl.functions.channels import EditBannedRequest
from telethon.tl.types import ChatBannedRights
from userbot.utils import admin_cmd
import userbot.plugins.sql_helper.antiflood_sql as sql
import userbot.utils
from userbot.utils import humanbytes, progress, time_form... |
import MySQLdb
import json
from datetime import timedelta, datetime
from unittest.mock import patch, Mock, ANY
import sqlparse
from django.contrib.auth import get_user_model
from django.test import TestCase
from common.config import SysConfig
from sql.engines import EngineBase
from sql.engines.goinception import GoIn... |
"""
作者:邓经纬
功能:BMR 计算器
版本:1.0
日期:26/10/2018
"""
def main():
"""
主函数
"""
# 性别
gender = '男'
# 体重
weight = 70
# 身高(cm)
height = 175
# 年龄
age = 25
if gender == '男':
# 男性
bmr = (13.7 * weight) + (5.0 * height) - (6.8 * age) + 66
elif... |
from unittest import TestCase
from justmltools.config.bucket_data_path_config import BucketDataPathConfig
PREFIX = "my_bucket_key_prefix"
class TestBucketDataPathConfig(TestCase):
def setUp(self) -> None:
self.sut: BucketDataPathConfig = BucketDataPathConfig(prefix=PREFIX)
def test_get_prefix(self... |
from hook.base import BaseHook
from task.gspread.tasks import send2ws
class MovieformHook(BaseHook):
def main(self) -> int:
channel = self.item.get("channel")
if channel != "movieform":
return 0
data = self.item.get("data")
dt = self.item.get("dt")
count = 1
... |
# -*- coding: utf-8 -*-
"""
Created on Tue Jan 28 19:58:07 2020
@author: kb1p
"""
import sys
import PyQt5.QtCore as Core
import PyQt5.QtWidgets as Gui
import PyQt5.QtGui as GuiMisc
import data_models
import dialogs
import json
class MainWindow(Gui.QMainWindow):
__slots__ = "tvStructure", "tblProps", "mdlStructur... |
"""
"Rel objects" for related fields.
"Rel objects" (for lack of a better name) carry information about the relation
modeled by a related field and provide some utility functions. They're stored
in the ``remote_field`` attribute of the field.
They also act as reverse fields for the purposes of the Meta API because
th... |
from torch.nn.modules.module import Module
from torch.autograd import Function, Variable
import resample2d_cuda
class Resample2dFunction(Function):
@staticmethod
def forward(ctx, input1, input2, kernel_size=1, bilinear= True):
assert input1.is_contiguous()
assert input2.is_contiguous()
... |
from datetime import datetime
from typing import Optional, Union
from discord.embeds import Embed
from discord.ext.commands import Cog, Context, group, has_permissions
from discord.member import Member
from discord.role import Role
from colors import Colors
from log import log
from permission import update_user_permi... |
import json
import stat
import pathlib
import platform
import globus_sdk
import requests
from dkist.net.globus.auth import (ensure_globus_authorized, get_cache_contents,
get_cache_file_path, get_refresh_token_authorizer,
save_auth_cache, start_loca... |
from pytuya.devices.base import TuyaDevice
class TuyaHeater(TuyaDevice):
"""
Represents a Tuya Heater.
"""
def __init__(self, id, password, local_key, region):
super(TuyaHeater, self).__init__(id, password, local_key, region)
def state(self):
return self._last_reading.get('1', Fal... |
import readfiles
import learnAlgorithms as learn
from plot import Plot as Plot
class Adapter(object):
def __init__(self, kernel, turnPlot, interactions):
self.log("Lendo Dados")
rf = readfiles.ReadFiles()
self.data = rf.getData()
self.labels = rf.getLabels()
self.la = learn... |
#
# PySNMP MIB module Wellfleet-FRSW-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Wellfleet-FRSW-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:40:14 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, ... |
from django.core.exceptions import PermissionDenied
from django.http import Http404
from django.utils.encoding import force_str
from rest_framework import exceptions, serializers
from rest_framework.relations import PrimaryKeyRelatedField
from rest_framework.request import clone_request
from collections import Ordered... |
"""
DataTable display.
"""
from .subframe import SubFrame
from .plugin import plugins
class DataTable(SubFrame):
"""Display a DataFrame as a DataTable."""
_plugins = [plugins.datatables]
def _js(self, data):
"""Javascript callback body."""
data = data.to_records()
data = self._... |
from setuptools import setup
setup(
name="blogen_neo",
version="0.0.1",
description="Simple static site generator for blog",
author="Kjuman Enobikto",
author_email="qmanenobikto@gmail.com",
install_requires=["jinja2", "fire"],
entry_points={
"console_scripts": [
"blogen ... |
from envs import REGISTRY as env_REGISTRY
from functools import partial
from components.episode_buffer import EpisodeBatch
import numpy as np
class EpisodeRunner:
def __init__(self, args, logger):
self.args = args
self.logger = logger
self.batch_size = self.args.batch_size_run
ass... |
# -*- coding: utf-8 -*-
"""
Specialized serializers for NSoT API client.
This is an example of how you would use this with the Client object, to make it
return objects instead of dicts::
>>> serializer = ModelSerializer()
>>> api = Client(url, serializer=serializer)
>>> obj = api.sites(1).get()
>>> o... |
import cv2
from app.Model.Model_cascades import Cascades
class FaceDetection:
def __init__(self):
self.type_cascade = Cascades.FACECASCADE
def get_type_cascade(self):
return self.type_cascade
def detection_rectangle_dimensions(self):
scaleFactor = 1.3
minNeighbors = 5
... |
from setuptools import setup
setup(
name='macresources',
version='1.2',
author='Elliot Nunn',
author_email='elliotnunn@me.com',
description='Library for working with legacy Macintosh resource forks',
long_description=open('README.md').read(),
long_description_content_type='text/markdown',
... |
import argparse
import datetime
import glob
import logging
import os
import time
import torch
from logging_helper import init_logger
from models import Discriminator, BartSystem
from train import train
from transformer_base import add_generic_args, generic_train
class Config():
# data_path = './data/chatbot/'
... |
"""Configure number in a device through MQTT topic."""
import functools
import logging
import voluptuous as vol
from homeassistant.components import number
from homeassistant.components.number import (
DEFAULT_MAX_VALUE,
DEFAULT_MIN_VALUE,
DEFAULT_STEP,
NumberEntity,
)
from homeassistant.const import ... |
# coding: utf-8
"""
DiscoveryStartRequest.py
The Clear BSD License
Copyright (c) – 2016, NetApp, Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted (subject to the limitations in the disclaimer below) provided that the following conditions are... |
from time import time
from requests import get
from qaviton_io.async_manager import AsyncManager
from tests.utils import server
def test_simple_requests():
def execute_tasks(number_of_tasks: int):
errors = {}
rs = []
def task():
try:
with server() as (host, por... |
"""Miscellaneous statistical functions."""
import numpy as np
import scipy.stats as ss
from scipy.optimize import Bounds, minimize
def weighted_least_squares(y, v, X, tau2=0.0, return_cov=False):
"""2-D weighted least squares.
Args:
y (NDArray): 2-d array of estimates (studies x parallel datasets)
... |
class Solution:
def __init__(self):
self.combs = []
def _backtrack(self, candidates, cur, target, k):
if len(cur) == k and sum(cur) == target:
self.combs.append(cur[:])
return
if sum(cur) > target:
return
elif len(cur) < k:
... |
#CADASTRO DE PESSOAS em dicionário - AULA 19 EXERCÍCIO 94
#dados das pessos: nome, sexo e idade
#todos os dicionários numa lista
#Informar quantos cadastrados, média de idade, lista de mulheres e nomes de pessoas de idade acima da média
#
pessoa = dict()
grupo = list()
somaidades = media = 0
while True:
pessoa.clea... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import requests
import json
from ndreg import *
import ndio.ramon as ndramon
import ndio.remote.neurodata as neurodata
"""
Here we show how to RAMONify Allen Reference Atlas data.
First we download annotation ontology from Allen Brain Atlas API.
It returns a JSON tree in wh... |
from flask import Flask, render_template, redirect
from jinja2 import Template
from splinter import browser
from flask_pymongo import PyMongo
import scrape_mars
# Create an instance of our Flask app.
app = Flask(__name__)
# Use flask_pymongo to set up mongo connection
app.config["MONGO_URI"] = "mongodb://localhost:2... |
# -*- coding: utf-8 -*-
# -----------------------------------------------------------------------------
__version__ = '1.40.88'
# -----------------------------------------------------------------------------
import asyncio
import concurrent.futures
import socket
import certifi
import aiohttp
import ssl
import sys
i... |
from casbin import log
class Assertion:
key = ""
value = ""
tokens = []
policy = []
rm = None
def build_role_links(self, rm):
self.rm = rm
count = self.value.count("_")
for rule in self.policy:
if count < 2:
raise RuntimeError('the number o... |
# This file is just meant to include functions that can be called from the command line to interact with the service.
# or in other words, these functions will basically make up the service. Perhaps these will actually just end up in the controller.py file.
# Created this file for planning. |
# -*- coding: utf-8 -*-
import subprocess
import sys
import json
import hashlib
import time
import base64
from binascii import hexlify
from collections import namedtuple
HEADER = """//!
//! This library is automatically generated from Google's list of known CT
//! logs. Don't edit it.
//!
//! The generation is done d... |
from model.formfiller import Contact
import re
class ContactHelper:
def __init__(self, app):
self.app = app
def add_new_contact(self, contact):
wd = self.app.wd
if not len(wd.find_elements_by_name("searchstring")) > 0:
self.app.open_home_page()
# add mew contact
... |
#!/usr/bin/python
from mininet.net import Mininet
from mininet.topo import Topo
from mininet.cli import CLI
from mininet.node import UserSwitch,RemoteController
from mininet.term import makeTerm
import os, time
class MyTopo( Topo ):
"Simple topology example."
def __init__( self):
"Create custom topo."
... |
import numpy as np
import sys
import os
import math
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' # Suppress TF info
import tensorflow as tf
#import matplotlib.pyplot as plt
# Define constants
stride = 15 #1 second @ 15 Hz sampling
window = 30*15 #30 seconds window considered
folder = sys.argv[1]
if not os.path.exists(f... |
from dataclasses import dataclass, field
from decimal import Decimal
from typing import Dict, List, Optional, Union
from bindings.csw.anim_mode_attrs_calc_mode import AnimModeAttrsCalcMode
from bindings.csw.animate_color_prototype import AnimateColorPrototype
from bindings.csw.fill_default_type import FillDefaultType
f... |
#!/usr/bin/env python
# Copyright (c) 2012-2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
'''
Generate valid and invalid base58 address and private key test vectors.
Usage:
gen_base58_test_ve... |
#!/usr/bin/env python
# coding: utf-8
from __future__ import absolute_import, unicode_literals
import collections
import contextlib
import copy
import datetime
import errno
import fileinput
import io
import itertools
import json
import locale
import operator
import os
import platform
import re
import shutil
import su... |
# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Shapelib(CMakePackage):
"""The Shapefile C Library provides the ability to write simple C ... |
from __future__ import absolute_import
from __future__ import print_function
import sys
import os
# the next line can be removed after installation
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(
os.path.dirname(os.path.dirname(os.path.abspath(__file__)))))))
from veriloggen import *
import ve... |
"""aiohttp based Socket Mode client
* https://api.slack.com/apis/connections/socket
* https://slack.dev/python-slack-sdk/socket-mode/
* https://pypi.org/project/aiohttp/
"""
import asyncio
import logging
import time
from asyncio import Future, Lock
from asyncio import Queue
from logging import Logger
from typing impo... |
#!/usr/bin/env python
from distutils.core import setup
long_desc = 'Licensed under the generic MIT License.\"sit-rep\" can either be downloaded from the ' \
'Releases page on GitHub and manually added to PATH or installed via \"pip\".'
version = ''
with open("Setup/version.txt", "r", encoding="utf-8") as... |
import numpy as np
import cv2
import os
import glob
import sys
from collections import defaultdict
from pathlib import Path
import pycocotools.mask as rletools
from PIL import Image, ImageDraw
import matplotlib.pyplot as plt
DATA_PATH = '../../data/KITTIMOTS/'
IMG_PATH = DATA_PATH + 'train/'
SAVE_VIDEO = False
IS_GT =... |
#!/usr/bin/env python
"""
Copyright (c) 2004-Present Pivotal Software, Inc.
This program and the accompanying materials are made available under
the terms of the 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... |
#!/usr/bin/python
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import lldb
import fblldbbase as fb
import fblldbviewhelpers as viewHelpers
def lldbcommands():
ret... |
import abc
from abc import abstractmethod
class Dataset(abc.ABC):
def __init__(
self,
input_params,
with_labels=False,
):
self.batch_size = input_params.batch_size
self.buffer_size = input_params.buffer_size
if with_labels:
self.train_da... |
#!/usr/bin/env python3
"""
Simple HTTP server in Python for logging events to CSV file
Motivation: Use this CSV file later for data agregation and plotting
Inspired by: Very simple HTTP server in Python for logging requests
https://gist.github.com/mdonkers/63e115cc0c79b4f6b8b3a6b797e485c7
Usage::
./SimpleLoggingS... |
try:
from _json_keys import *
from _util import *
from defs_L3 import dissectors_L3
except:
from ._json_keys import *
from ._util import *
from .defs_L3 import dissectors_L3
def decoder(x):
'''
return (dissectors_L3)
or
return { JK_EMSG:(error-message) }
'''
this = None
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for `mvport` package."""
import unittest
import numpy as np
from mvport.stock import Stock
class TestStock(unittest.TestCase):
"""Tests for `mvport` package."""
def setUp(self):
"""SetUp."""
self.ticker = 'AAPL'
self.returns =... |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from absl import flags
flags.DEFINE_string(
"output_dir",
None,
"The directory to read and write files to.",
) |
from auditlog.registry import auditlog
from django.db import models
from django.utils.translation import ugettext_lazy as _
from enumfields import EnumField
from leasing.enums import PeriodType
from .mixins import NameModel, TimeStampedSafeDeleteModel
class BasisOfRentPlotType(NameModel):
"""
In Finnish: To... |
from console import update_irc_search |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.