text stringlengths 1 927k |
|---|
"""Skopes rules """
import uuid
import os
import datatable as dt
import numpy as np
from h2oaicore.models import CustomModel
from sklearn.preprocessing import LabelEncoder
from h2oaicore.systemutils import physical_cores_count
from h2oaicore.systemutils import user_dir, remove, config
from h2oaicore.systemutils import... |
#!/usr/bin/env python
from cumulogenesis.interfaces import cli
cli.run() |
import sys
sys.path.append(".")
from train_net_dynamic import *
cfg=Config('volleyball')
cfg.inference_module_name = 'dynamic_volleyball'
cfg.device_list = "0,1"
cfg.use_gpu = True
cfg.use_multi_gpu = True
cfg.training_stage = 2
cfg.train_backbone = True
cfg.test_before_train = False
cfg.test_interval_epoch = 1
# vg... |
import glob
import os
import subprocess
import tempfile
import time
import cStringIO
from wand.color import Color
from wand.image import Image
PATH = './test_assets/*.pdf'
def temp_name():
""" returns a temporary file-name """
tmpfile = tempfile.NamedTemporaryFile(prefix="tess_")
return tmpfile.name
d... |
"""Main file tests"""
from typing import Final
from unittest.mock import patch, MagicMock, call
class TestHello:
"""hello function Tests"""
class TestNominalCase:
@patch('hellopymsdl.service.MessageService.MessageService')
@patch('builtins.print')
def test_call_hello__should__print_m... |
import numpy as np
import pytest
import pandas as pd
from pandas.core.arrays.integer import (
Int8Dtype,
Int16Dtype,
Int32Dtype,
Int64Dtype,
UInt8Dtype,
UInt16Dtype,
UInt32Dtype,
UInt64Dtype,
)
@pytest.fixture(
params=[
Int8Dtype,
Int16Dtype,
Int32Dtype,
... |
# Copyright 2017 The Sonnet 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 l... |
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "strike_me_happy.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv) |
import json
import uuid
import mock
import pytest
import os
import kiwi
from kiwi.entities import ViewType
from kiwi.entities.model_registry import RegisteredModel, ModelVersion, \
RegisteredModelTag, ModelVersionTag
from kiwi.exceptions import MlflowException
from kiwi.protos.databricks_pb2 import INTERNAL_ERROR... |
#
# MIT License
#
# Copyright (c) 2022 GT4SD team
#
# 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, modify, merge,... |
import unittest
from server.services.mapping_service import MappingService, Task, MappingServiceError, TaskStatus, \
ProjectService, NotFound, StatsService, MappingNotAllowed, UserLicenseError
from server.models.dtos.mapping_dto import MappedTaskDTO, LockTaskDTO
from server.models.postgis.task import TaskHistory, ... |
import logging
from .observer import Observer
import config
class Logger(Observer):
def opportunity(self, profit, volume, buyprice, kask, sellprice, kbid, perc,
weighted_buyprice, weighted_sellprice):
logging.info("profit: %f %s with volume: %f %s - buy at %i (%s) sell at %i (%s) ~%.2f... |
#!/usr/bin/env python
############################################################################
# Copyright (C) by GFZ Potsdam #
# #
# You can redistribute and/or modify this program under the ... |
# 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 under t... |
# Copyright 2018 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... |
#!/usr/bin/env python3
# Copyright (c) 2013-2021 The Fastcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
# Test AuxPOW RPC interface and constraints
#
from test_framework.test_framework import BitcoinTestFr... |
# Copyright 2014 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Removes WidgetHostMsg_Close and alike from testcases. These messages are an
annoyance for corpus distillation. They cause the browser to exit, so no
furthe... |
import csv
# import matplotlib.pyplot as plt
import pylab as plt
import numpy as np
def show_plot(times, epochs, data):
# line chart Or Scatter chart
plt.figure(figsize=(8, 5))
"""
args:
marker='o' ,'x',
color=
"""
plt.plot(epochs, data, color='red', label='0')
# plt.plot(epochs, d... |
import requests
import config
import datetime
import os
import json
import copy
from constants import *
class RequestManager:
"""A class that handles submitting TiIndicators to MS Graph API
to use the class:
with RequestManager() as request_manager:
request_manager.handle_indicator(tiindi... |
# Generated by Django 2.2.3 on 2019-07-26 07:00
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('rosters', '0019_leavedescription'),
]
operations = [
migrations.AlterField(
model_name='staffrule',
name='staff_rule... |
"""
Copyright 2020 The OneFlow 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 law or agr... |
# -*- coding: utf-8 -*-
"""
------------------------------------
@Project : uiTest
@Time : 2021/3/9 14:17
@Auth : wrc
@Email : wrcyyy@126.com
@File : base.py
@IDE : PyCharm
------------------------------------
"""
import logging
import os
from selenium.webdriver.support.wait import WebDriverWait
from se... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_job_queue.py
Test suite for zcomx/modules/job_queue.py
"""
import datetime
import os
import subprocess
import time
import unittest
from gluon import *
from applications.zcomx.modules.job_queue import \
CLIOption, \
Daemon, \
DaemonSignalError, \
... |
"""Stub method for providing current device actuator status."""
# Copyright 2019 WolkAbout Technology s.r.o.
#
# 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.apach... |
import torch
import torch.nn.functional as F
from copy import deepcopy
import numpy as np
from scipy.special import expit as sigmoid
from .cd_propagate import *
from .cd_architecture_specific import *
def cd(im_torch: torch.Tensor, model, mask=None, model_type=None, device='cuda', transform=None):
'''Get contextua... |
from setuptools import setup
from setuptools import find_packages
classifiers = [
'Development Status :: 4 - Beta',
'Intended Audience :: Developers',
'License :: OSI Approved :: MIT License',
'Programming Language :: Python',
'Programming Language :: Python :: 2.7',
]
setup(
name="interne... |
# Copyright 2019 Google LLC
#
# 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, ... |
import numpy as np
import torch
from torch.utils import data
import sys
from utils.generate_dataset import *
from HypHC.datasets.triples import samples_triples
class HyperLoader(data.Dataset):
def __init__(self, data_dir, split_indices, restrict_labels=[0,1,2,3,4,5,6], chromosome="all"):
'''
Takes ... |
"""
This file is part of flatlib - (C) FlatAngle
Author: João Ventura (flatangleweb@gmail.com)
This subpackage implements a few traditional
astrology predictive techniques.
""" |
import torch
from torch import nn
import torch.nn.functional as F
from torch.autograd import Variable
import numpy as np
import math
from sequicity.config import global_config as cfg
import copy, random, time, logging
from torch.distributions import Categorical
from sequicity.reader import pad_sequences
import pdb
i... |
'''
import re
import random
class ContextFreeGrammar:
def __init__(self, start_symbol, production_rules):
self.start_symbol = start_symbol
self.production_rules = production_rules
def expand(self):
return self.expand_rec(self.start_symbol)
def expand_rec(self, symbol_to_expand):... |
# 2019-11-12 01:01:32(JST)
import sys
# import collections
# import math
# from string import ascii_lowercase, ascii_uppercase, digits
# from bisect import bisect_left as bi_l, bisect_right as bi_r
# import itertools
# from functools import reduce
# import operator as op
# from scipy.misc import comb # float
# import ... |
"""empty message
Revision ID: 2f182d32410d
Revises:
Create Date: 2020-04-29 01:27:52.576633
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '2f182d32410d'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto gene... |
from django.dispatch import receiver
from django.db.models.signals import pre_save,post_save
from django.contrib.auth.models import User
from django.contrib.auth.signals import user_logged_out,user_logged_in
from .models import Profile
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created... |
# !/usr/bin/python3
from sudoku.cells import *
from sudoku.regions import *
class ReduceError(BaseException):
pass
# Remove all used values from a cell
def reduceCellByValues(cell, used):
reduced = []
for value in cell:
if not used[value]: reduced.append(value)
if not len(reduced): raise R... |
import cv2
from deepvision import TFlite
# open webcam
webcam = cv2.VideoCapture(0)
tflite = TFlite()
# loop through frames
while webcam.isOpened():
# read frame from webcam
status, frame = webcam.read()
frame = tflite.detect_objects(frame)
# display output
cv2.imshow("Real-time object detection"... |
import py
from rpython.rlib.parsing.ebnfparse import parse_ebnf
from rpython.rlib.parsing.regexparse import parse_regex
from rpython.rlib.parsing.lexer import Lexer, DummyLexer
from rpython.rlib.parsing.deterministic import DFA, LexerError
from rpython.rlib.parsing.tree import Nonterminal, Symbol, RPythonVisitor
from r... |
from dataclasses import dataclass
from typing import List
from beer.consensus.cost_calculator import NPCResult
from beer.types.blockchain_format.coin import Coin
from beer.types.blockchain_format.program import SerializedProgram
from beer.types.blockchain_format.sized_bytes import bytes32
from beer.types.spend_bundle ... |
from bai_kafka_utils.events import (
BenchmarkDoc,
VisitedService,
FetcherBenchmarkEvent,
DownloadableContent,
FetcherPayload,
FileSystemObject,
)
BIG_FETCHER_JSON = """{
"date": "Thu May 02 16:15:42 UTC 2019",
"authenticated": false,
"payload": {
... |
from osbot_aws.apis.Lambda import Lambda
from osbot_aws.helpers.Lambda_Helpers import slack_message
def run(event, context):
channel = event.get('channel')
try:
dot_to_svg = Lambda('gw_bot.lambdas.dot_to_svg').invoke
svg_to_png = Lambda('gw_bot.lambdas.svg_to_png').invoke
svg = ... |
import vb2py.vbparser
import unittest
class TestImports(unittest.TestCase):
# << Imports tests >>
def testImportClassToModule(self):
"""Import from class to module"""
self.proj = vb2py.vbparser.VBProject()
self.utils = vb2py.vbparser.VBCodeModule(modulename="utils")
self.cls = v... |
# Functions for the curation app
import csv
from dateutil.parser import parse
from functools import reduce
import json
import glob
import os
from os import listdir
import pandas as pd
from pathlib import Path
import re
import requests
import time
from tkinter import Tk, ttk, Frame, Label, IntVar, Checkbutton, filedialo... |
# -*- coding: utf-8 -*-
#
# Copyright (c) 2015, Alcatel-Lucent Inc, 2017 Nokia
# 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 copyrigh... |
#!/bin/zsh
import re
xmasregex = re.compile(r'\d\s\w+')
mtob1 = xmasregex.findall(
"12 drummers, 11 pipers, 10 lords, 9 ladies, 8 maids, 7 swans, 6 geese, 5 rings, 4 birds, 3 hens, 2 doves, 1 partidge"
)
print(mtob1) |
"""
A view that handles synchronization of changes from the frontend
and deals with processing all the changes to make appropriate
bulk creates, updates, and deletes.
"""
from collections import OrderedDict
from itertools import groupby
from django.conf import settings
from rest_framework.authentication import Session... |
from netdumplings import DumplingChef
class ChefOneFromFile(DumplingChef):
pass
class ChefTwoFromFile(DumplingChef):
pass |
# Copyright (c) 2012-2014 Andy Davidoff http://www.disruptek.com/
#
# 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... |
# CREATED:2013-08-13 12:02:42 by Brian McFee <brm2132@columbia.edu>
'''
Evaluation criteria for structural segmentation fall into two categories:
boundary annotation and structural annotation. Boundary annotation is the task
of predicting the times at which structural changes occur, such as when a verse
transitions to... |
# -*- coding: utf-8 -*-
from elasticapm.instrumentation.packages.mysql import extract_signature
def test_insert():
sql = """INSERT INTO `mytable` (id, name) VALUE ('2323', 'Ron')"""
actual = extract_signature(sql)
assert "INSERT INTO mytable" == actual
def test_update():
sql = """UPDATE `mytable` s... |
# -*- coding: utf-8 -*-
"""
@author: BSW
"""
import numpy as np
import os
def slicing(filename,data):
wc=1
n1c=1
n2c=1
n3c=1
n4c=1
t=0
npz = np.load(data)
x = npz['x']
y = npz['y']
os.makedirs("./data/"+filename[:-3], exist_ok=True)
os.makedirs("./data/"+filename[... |
# 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 under t... |
"""Special handling for exceptions, for the UI.
"""
def alarm(e):
"""
Write traceback into PBFALCON_ERRFILE (until we stop using pbfalcon).
Write a special JSON object expected by pbcommand.models.common.
"""
import datetime
import os
import traceback
import uuid
from ..io import se... |
"""
Given three towers and n sorted disks placed on it, we
have to move all the disks from one tower to the other
while using the third one as buffer.
There are three rules that each move should follow.
"""
def move(start, buffr, end, n):
"""
By using the recursion from base case to move upwards
we can cha... |
from django.urls import reverse
from ietf.group.factories import GroupFactory, GroupEventFactory
from ietf.group.models import Group, GroupEvent
from ietf.person.models import Person
from ietf.utils.test_utils import TestCase
SECR_USER='secretary'
def augment_data():
system = Person.objects.get(name="(System)")... |
from django.core.urlresolvers import reverse
from social_auth.backends.exceptions import AuthAlreadyAssociated
from social_auth.middleware import SocialAuthExceptionMiddleware
class ExampleSocialAuthExceptionMiddleware(SocialAuthExceptionMiddleware):
def get_message(self, request, exception):
if isinstan... |
from db.serializers.reset_serializer import SetNewPasswordSerializer |
import cProfile, pstats, io
import re
import VM
def Stats(pr):
s = io.StringIO()
sortby = 'tottime'
ps = pstats.Stats(pr, stream=s).sort_stats(sortby)
ps.print_stats()
print(s.getvalue())
def parse_code(code: str) -> bytes:
binary = ''
regex = re.compile(r"[0-9a-f]+:\s+([^;]+)\s*;.*", re... |
# Copyright (c) 2006-2007 The Regents of The University of Michigan
# Copyright (c) 2009 Advanced Micro Devices, Inc.
# 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 co... |
import glob
import os
from typing import Optional, Callable, Tuple, Dict, Any, List
from torch import Tensor
from .folder import find_classes, make_dataset
from .video_utils import VideoClips
from .vision import VisionDataset
class HMDB51(VisionDataset):
"""
`HMDB51 <https://serre-lab.clps.brown.edu/resourc... |
# Let the wookie pass. |
#!/usr/bin/env python
import os
import sys
import tempfile
assert sys.version_info[:2] >= (2.4)
def stop_err( msg ):
sys.stderr.write( "%s\n" % msg )
sys.exit()
def check_nib_file( dbkey, GALAXY_DATA_INDEX_DIR ):
nib_file = "%s/alignseq.loc" % GALAXY_DATA_INDEX_DIR
nib_path = ''
nibs = {}
... |
'''
Take the existing Kc_house_data.csv from MongoDb Atlas, parsing for latitude and longitude
It then pipes this data through the WalkScore Api, generating 3 accessibility scores
These 3 scores are then inserted into their associated rows within MongoDb
WalkScore Api: https://www.walkscore.com/professional/walk-score-... |
#!/usr/bin/env python
# coding: utf-8
# # MadMiner particle physics tutorial
#
# # Part 3b: Training a score estimator
#
# Johann Brehmer, Felix Kling, Irina Espejo, and Kyle Cranmer 2018-2019
# In part 3a of this tutorial we will finally train a neural network to estimate likelihood ratios. We assume that you have... |
import discord
from discord.ext import commands
class Help(commands.Cog):
def __init__(self, bot):
self.bot = bot
# Comands
@commands.command(pass_context=True, aliases=("commands", "cmd"))
async def help(self, ctx):
embed = discord.Embed(title="There are all commands I know", descrip... |
from rq_scheduler.scheduler import Scheduler
import rq
from redis import Redis
import os
import sys
import init_log
import logging
def _run_scheduler():
with rq.Connection(Redis.from_url(os.environ.get("REDIS_URL") or "redis://")):
q = rq.Queue()
scheduler = Scheduler(queue=q)
scheduler.... |
# Copyright (c) 2020 Graphcore Ltd. 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 l... |
"""muller_method URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class... |
"""
Generate the penalty XML file used by the antivirus file reputation analyzer.
"""
import argparse
import xml.etree.ElementTree as ET
import xml.dom.minidom
import os
import sys
PENALTIES_ELEMENT = 'penalties'
PENALTY_ELEMENT = 'penalty'
REASON_ELEMENT = 'reason'
REMEDIATION_ELEMENT = 'remediation'
ID_ATTRIBUTE =... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('accounts', '0016_auto_20150814_1727'),
]
operations = [
migrations.RemoveField(
model_name='userextended',
... |
from recommonmark.parser import CommonMarkParser
source_parsers = {
'.md': CommonMarkParser,
}
# -*- coding: utf-8 -*-
#
# Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# http://www.sphinx-d... |
# coding: utf-8
import json
from requests.auth import HTTPBasicAuth
from tapioca import (
TapiocaAdapter, generate_wrapper_from_adapter, JSONAdapterMixin)
from .resource_mapping import RESOURCE_MAPPING
class NessusClientAdapter(JSONAdapterMixin, TapiocaAdapter):
api_root = None
resource_mapping = RESOUR... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
xl_methods
Métodos ligeramente modificados a partir de abenassi/xlseries para manipular
archivos en formato XLSX (https://github.com/abenassi/xlseries).
"""
from six import string_types, text_type
def compare_cells(wb1, wb2):
"""Compare two excels based on row it... |
from keras import models, layers
class CNNModel:
@staticmethod
def generateModel(input):
model = models.Sequential()
model.add(layers.Conv2D(filters=32, kernel_size=(5,5), activation='relu', input_shape=input.shape[1:]))
model.add(layers.MaxPool2D(pool_size=(2, 2)))
model.add(la... |
from weldarray import *
from weldnumpy import *
# FIXME: Should this be in weldnump? pytest gives errors when trying to import
# weldarray in weldnumpy...so keeping it here for now.
def array(arr, *args, **kwargs):
'''
Wrapper around weldarray - first create np.array and then convert to
weldarray.
'''... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('main', '0014_auto_20150917_1211'),
]
operations = [
migrations.AlterField(
model_name='role',
name='... |
# -*- coding: utf-8 -*-
"""
Flask-Waf
---------
Adds server Waf support to your application.
:copyright: (c) 2018 by Virink
:license: BSD, see LICENSE for more details.
"""
from setuptools import setup
setup(
name='Flask-Waf',
version='1.0',
url='https://github.com/virink/flask_waf',... |
_base_ = [
'../_base_/models/pspnet_r50-d8.py',
'../_base_/datasets/cityscapes_769x769.py', '../_base_/default_runtime.py',
'../_base_/schedules/schedule_40k.py'
]
model = dict(
decode_head=dict(align_corners=True),
auxiliary_head=dict(align_corners=True),
test_cfg=dict(mode='slide', crop_size=(... |
#
# Copyright (c) 2009-2016, Jack Poulson
# All rights reserved.
#
# This file is part of Elemental and is under the BSD 2-Clause License,
# which can be found in the LICENSE file in the root directory, or at
# http://opensource.org/licenses/BSD-2-Clause
#
import El
m = 500
n = 1000
k = 750
testMehrotra = True
... |
# -*- coding: utf-8 -*-
"""
tools
=====
Functions that USERS will possibly want access to.
"""
from __future__ import absolute_import
from collections import OrderedDict
import warnings
import six
import math
import decimal
from plotly import utils
from plotly import exceptions
from plotly import graph_reference
... |
"""Common configure functions for lldp"""
# Python
import logging
log = logging.getLogger(__name__)
def configure_lldp(device):
""" Enables lldp on target device
Args:
device ('obj'): Device object
Returns:
None
"""
device.configure(['lldp'])
def unconfigure_lldp(... |
import pendulum
import requests
from github_poster.loader.base_loader import BaseLoader
from github_poster.loader.config import DUOLINGO_CALENDAR_API
class DuolingoLoader(BaseLoader):
unit = "XP"
def __init__(self, from_year, to_year, **kwargs):
super().__init__(from_year, to_year)
self.user... |
# coding: utf-8
"""
vserver
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
from ncloud_vserver.model.common_code import CommonCode # noqa: F401,E501
class ServerInstance(object):
"""NOTE: This class is auto generated by the... |
# coding=utf-8
# Copyright 2020 TF.Text 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
#
# Unless required by applicable law or ag... |
# projectile.py
# -----------------------------------------------------------------------------
# Calculate how long an object is in the air when thrown from a specified height
# with a range of initial speeds assuming constant acceleration due to gravity:
# 0.5 * g * t**2 - v0 * t - y0 = 0
# -------------------------... |
import torch
import torch.nn.functional as F
import numpy as np
# Original author: Francisco Massa:
# https://github.com/fmassa/object-detection.torch
# Ported to PyTorch by Max deGroot (02/01/2017)
def nms(boxes, scores, overlap=0.7):
"""Apply non-maximum suppression at test time to avoid detecting too many
... |
import re
import os
import time
import logging
import json
from collections import namedtuple
import ptf.mask as mask
import ptf.packet as packet
import ptf.testutils as testutils
from tests.common.errors import RunAnsibleModuleFail
from tests.common.helpers.assertions import pytest_assert
from jinja2 import Environme... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.10 on 2016-12-20 17:51
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('company', '0023_auto_20161219_1730'),
]
operations = [
migrations.AddField(... |
"""
WSGI config for seedstars_contacts project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("D... |
#!/usr/bin/env python3
# pyre-strict
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the "hack" directory of this source tree.
import tempfile
import unittest
from hphp.hack.src.hh_codesynthesis import hh_codesynthesis, hackGenera... |
# coding: utf-8
"""
PKS
PKS API # noqa: E501
OpenAPI spec version: 1.1.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
# python 2 and python 3 compatibility library
import six
from container_service_extension.lib.pksclient.api_cl... |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: POGOProtos/Inventory/InventoryDelta.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf... |
# This isn't intended as an example, it's just here to simplify all the
# output formating the examples do.
from accelerator import colour
class Printer:
def __init__(self, indent=0):
self._indent = indent
self._last_indent = 0
self._unindent = []
def _prefix(self, txt):
for c in txt:
if not c.isspace()... |
# -*- coding: utf-8 -*-
"""Chemical Engineering Design Library (ChEDL). Utilities for process modeling.
Copyright (C) 2016, 2017, 2018, 2019, 2020 Caleb Bell <Caleb.Andrew.Bell@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (t... |
import numpy as np
import cv2
from PIL import Image
from io import BytesIO, StringIO
import base64
import time
# Define a function to convert telemetry strings to float independent of decimal convention
def convert_to_float(string_to_convert):
if ',' in string_to_convert:
float_value = np.float(strin... |
# -*- coding: utf-8 -*-
'''
Author: TJUZQC
Date: 2020-10-26 10:26:51
LastEditors: TJUZQC
LastEditTime: 2020-11-20 19:23:55
Description: None
'''
import argparse
import logging
import os
import sys
import numpy as np
import torch
import torch.nn as nn
import yaml
from torch import optim
from torch.utils.data import Dat... |
import sqlite3 as sqlite
class ConType:
query = 0
mutation = 1
batch = 2
class DatabaseConnection:
is_batching = False
def __init__(self, database_object: 'MrDatabase', con_type: int=ConType.mutation):
self.database_object = database_object
self.con_type: int = con_type
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import time
import wiringpi
# 定数宣言
LED_PIN = 4 # LEDのGPIO番号
BUTTON_PIN = 13 # スイッチのGPIO番号
BUTTON_DELAY = 0.5 # チャタリング防止用の遅延時間
INTERVAL = 0.1 # スイッチチェック間隔
def get_button_value(pin):
"""指定したpinのスイッチ入力状態を取得"""
v = wiringpi.digitalRead(pin)
if v == wiringpi.H... |
import queue
import threading
import time
import concurrent.futures
q = queue.Queue(maxsize=10)
def Producer(name):
count = 1
while True:
q.put("包子 %s" % count)
print("做了包子", count)
count += 1
time.sleep(0.5)
def Consumer(name):
while True:
print("[%s] 取到[%s] 并且吃... |
from hotorcold.main import app
if __name__ == "__main__":
app.run() |
# -*- coding: utf-8 -*-
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""Miscellaneous utility functions
"""
from __future__ import (print_function, unicode_literals, division,
absolute_import)
from builtins import next, str
im... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.