text stringlengths 1 927k |
|---|
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
fro... |
# -*- coding: utf-8 -*-
################################################################################
## Form generated from reading UI file 'plotConfigTemplate.ui'
##
## Created by: Qt User Interface Compiler version 6.1.0
##
## WARNING! All changes made in this file will be lost when recompiling UI file!
########... |
from bson import ObjectId
from .field import Field
class ObjectIdField(Field):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def to_mongo(self, value):
return ObjectId(value) if value else None
async def from_mongo(self, value, resolver=None):
return str... |
def init_app(app):
app.config["SECRET_KEY"] = "abacate01"
app.config["SQLALCHEMY_DATABASE_URI"] = 'sqlite:///delivery.db'
if app.debug:
app.config['DEBUG_TB_TEMPLATE_EDITOR_ENABLED'] = True
app.config['DEBUG_TB_PROFILER_ENABLED'] = True |
from typing import Union, List, Optional
from pyspark.sql.types import (
StructType,
StructField,
StringType,
ArrayType,
BooleanType,
DataType,
)
# This file is auto-generated by generate_schema so do not edit manually
# noinspection PyPep8Naming
class CodingSchema:
"""
A reference to... |
from __future__ import (
absolute_import,
unicode_literals,
)
import functools
def decorated(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
return func(*args, **kwargs)
return wrapper |
# Copyright (C) 2015-2019 SignalFx, Inc. All rights reserved.
# Copyright (C) 2020-2021 Splunk, Inc. All rights reserved.
from __future__ import print_function
import argparse
import calendar
from datetime import datetime as dt
from datetime import timedelta as delta
import os
import pytz
import re
import six
import ... |
# coding: utf-8
"""
Octopus Server API
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) # noqa: E501
OpenAPI spec version: 2019.6.7+Branch.tags-2019.6.7.Sha.aa18dc6809953218c66f57eff7d26481d9b23d6a
Generated by: https://github.com/swagger-api... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
"""
Support for TPLink HS100/HS110/HS200 smart switch.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/switch.tplink/
"""
import logging
import time
import voluptuous as vol
from homeassistant.components.switch import (SwitchDevice, PLATFORM_SCHEMA)
fr... |
import sys, os, time, atexit, socket, subprocess
from signal import SIGTERM
import logging
fqdn = 'FQDN_PLACEHOLDER'
port = 'PORT_PLACEHOLDER'
keyfile = 'KEYFILE_PLACEHOLDER'
if __name__ == '__main__':
try:
pid = os.fork()
if pid > 0:
# exit first parent
sys.exit(0)
ex... |
#!/usr/bin/env python
"""
_JobStatusMonitoring_
MySQL implementation for loading a job by scheduler status
"""
from WMCore.Database.DBFormatter import DBFormatter
class JobStatusForMonitoring(DBFormatter):
"""
_LoadForMonitoring_
Load all jobs with a certain scheduler status including
all the joine... |
#! /usr/bin/env python
# -*- coding: latin1 -*-
""" ---- inq.py -- Reptor input queue writer ----
Write messages to the Reptor input queue
via EntireX Broker ACI call interface
Usage: python inq.py [options]
Options:
-h, --help display this help
-b, --broker .. id of broker ETBxxxxx ... |
import json
from flask import Blueprint, request, current_app
from flask.ext.jsontools import jsonapi
from flask.ext.login import login_required
from dart.auth.required_roles import required_roles
from dart.message.trigger_proxy import TriggerProxy
from dart.model.action import ActionState
from dart.model.engine impo... |
"""
1344
medium
angle between hands of a clock
"""
class Solution:
def angleClock(self, hour: int, minutes: int) -> float:
min_angle = minutes * 6
hour_angle = hour * 30 + minutes / 2
hand_angles = abs(min_angle - hour_angle)
if hand_angles > 180:
hand_angles = 360 - ... |
def countConsecutive(N):
# constraint on values of L gives us the
# time Complexity as O(N^0.5)
count = 0
L = 1
while( L * (L + 1) < 2 * N):
a = (1.0 * N - (L * (L + 1) ) / 2) / (L + 1)
if (a - int(a) == 0.0):
count += 1
L += 1
return count
#... |
# Copyright (c) 2017, Apple Inc. All rights reserved.
#
# Use of this source code is governed by a BSD-3-clause license that can be
# found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause
"""
Functions related to graph visualization of mlmodels
"""
import ast as _ast
import json as _json
im... |
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
import os
import compas_rhino
from compas._os import remove_symlink
__all__ = ['uninstall_plugin']
def uninstall_plugin(plugin, version=None):
"""Uninstall a Rhino Python Command Plugin.
Paramete... |
# Copyright 2013 OpenStack Foundation
#
# 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... |
from TikTokApi import TikTokApi
# Starts TikTokApi
api = TikTokApi.get_instance()
# The Number of trending TikToks you want to be displayed
results = 10
# Returns a list of dictionaries of the trending object
userPosts = api.userPosts(
"6745191554350760966",
"MS4wLjABAAAAM3R2BtjzVT-uAtstkl2iugMzC6AtnpkojJbji... |
# Copyright (c) Microsoft. All rights reserved.
# Licensed under the MIT license. See LICENSE.md file in the project root
# for full license information.
# ==============================================================================
import numpy as np
import sys
import os
from cntk import Trainer
from cntk.io import... |
# from .provider_test import ProviderTest, TestSource
from gunpowder import (BatchProvider, ArrayKeys, ArraySpec, Roi, Batch,
Coordinate, SpecifiedLocation, build,
BatchRequest, Array, ArrayKey)
import numpy as np
import unittest
class TestSourceSpecifiedLocation(BatchPro... |
from setuptools import setup
setup(name='bhc',
version='0.1',
description='Bayesian Hierarchical Clustering',
url='https://github.com/qxxxd/bhc',
author='Xiaodi Qin, Lina Yang',
author_email='xq24@duke.edu, ly81@duke.edu',
license='MIT',
packages=['bhc'],
#install_requir... |
"""
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.
"""
import os
from collections import defaultdict
import numpy as np
import torch
import torch_geometric
from torch.utils.data import DataLoader... |
from django.conf import settings
from .. import Tags, Warning, register
SECRET_KEY_MIN_LENGTH = 50
SECRET_KEY_MIN_UNIQUE_CHARACTERS = 5
W001 = Warning(
"You do not have 'django.middleware.security.SecurityMiddleware' "
"in your MIDDLEWARE_CLASSES so the SECURE_HSTS_SECONDS, "
"SECURE_CONTENT_TYPE_NOSNIFF... |
"""
142. Linked List Cycle II
Medium
Given the head of a linked list, return the node where the cycle begins. If there is no cycle, return null.
There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally, pos is used to denote t... |
""" A program that is able to convert a number between 1 and 4999 (inclusive)
to a roman numeral with variables, arithmetic operators, and functions."""
def main():
# Input the number
number = roman_num = int(input('Enter number:'))
# The quotient gotten from 'number // 1000' is the number of 'M'
... |
"""
ASGI config for djangoapi project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SET... |
from collections import Counter
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
if len(s) == 0:
return 0
max_length = 0
window = Counter()
left = 0
right = left
while right < len(s):
window[s[right]] += 1
while wi... |
import sys
from setuptools import find_packages
from setuptools import setup
version = '1.18.0'
install_requires = [
# This dependency just exists to ensure that chardet is installed along
# with requests so it will use it instead of charset_normalizer. See
# https://github.com/certbot/certbot/issues/896... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function
import sys
import shlex
from subprocess import Popen, PIPE, \
check_call, CalledProcessError
def run_cmd(cmd, ignore_error=False, exargs=[]):
cmd = shlex.split(cmd)
cmd.extend(exargs)
p = Popen(cmd, stdout=PIPE, std... |
from abc import ABCMeta, abstractmethod
from typing import Any, List
class LLVMType(metaclass=ABCMeta):
@abstractmethod
def to_json(self) -> Any: pass
class LLVMIntType(LLVMType):
def __init__(self, width : int) -> None:
self.width = width
def to_json(self) -> Any:
return {'type': 'pr... |
#%%
import sys, os, glob
import numpy as np
sys.path.append("../") # go to parent dir
from utils.coco_manager import MaskManager
## Create Train/Val/Test/ Datasets
#Train: 80%
#Val: 18%
#Test: 2%
#%%
DATASET_VERSON = 'ds2'
DATASET_PATH = f'/mnt/zerowastepublic/02-datasets/{DATASET_VERSON}/'
DATASET_RAW_FOLD... |
# Generated by Django 3.1.2 on 2020-10-30 16:22
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('auctions', '0008_bidlisting_bidprice'),
]
operations = [
migrations.AlterField(
model_name='bidlisting',
name='bidpr... |
import unittest
from acme import Product, BoxingGlove
from acme_report import generate_products, ADJECTIVES, NOUNS
"""Tests for Acme Python modules."""
class AcmeProductTests(unittest.TestCase):
"""Making sure Acme products are the tops!"""
def test_default_product_price(self):
"""Test default prod... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 21 15:36:06 2022
@author: bobrokerson
"""
# part of code from task #1
from math import sin, exp
import numpy as np
import matplotlib.pyplot as plt
def func(x):
return sin(x / 5.) * exp(x / 10.) + 5. * exp(-x/ 2.)
xarr = np.arange(1., 31.)
p... |
#!/usr/bin/env python
# Copyright 2014 BitPay Inc.
# Copyright 2016 The Ilcoin Core developers
# All Rights Reserved. ILCoin Blockchain Project 2019©
from __future__ import division,print_function,unicode_literals
import os
import bctest
import buildenv
import argparse
import logging
help_text="""Test framework for il... |
import sqlite3
from dbconn import dbconnect
import codecs
db_conn = dbconnect('database/commandsDB.db')
# add here when adding commands
commands = ["tableflip", "gitgud", "heresy"]
commands_create_sql = []
for command in commands:
commands_create_sql.append(f""" CREATE TABLE IF NOT EXISTS {command} (
... |
from sklearn.metrics import precision_recall_fscore_support as prfs
import numpy as np
import json
import argparse
from typing import List, Tuple, Dict
import sys
# From spert.evaluator class
# https://github.com/markus-eberts/spert/blob/master/spert/evaluator.py
def _get_row(data, label):
row = [label]
for i... |
import sys
import os
import shutil
import cv2
import open3d as o3d
import open3d.core as o3c
import numpy as np
from rendering.pytorch3d_renderer import PyTorch3DRenderer
from data import StandaloneFrameDataset
import data.presets as presets
import tsdf.default_voxel_grid
import data.camera
from settings import proce... |
import numpy as np
import pandas as pd
import gzip
input_file = 'predictions/2nd-place-233-seq.csv'
nickname='kazuki2'
df = pd.read_csv('../233x_sequences_degdata_081120.csv')
df1 = pd.read_csv(input_file)
df1['ID'] = [int(x.split('_')[0]) for x in df1['id_seqpos']]
df1['seqpos'] = [int(x.split('_')[1]) for x in df1... |
from django.db import transaction
from mutagen.mp3 import MP3
from os import path
@transaction.atomic()
def fetch_feed(podcast_pk, url):
from ..validator.utils import find_validator
from .models import Podcast
import requests
import json
response = requests.get(url, stream=True)
response.rais... |
# -*- encoding: utf-8 -*-
#
# Grasso - a FAT filesystem parser
#
# Copyright 2011 Emanuele Aina <em@nerd.ocracy.org>
#
# Released under the term of a MIT-style license, see LICENSE
# for details.
import math, io, pprint
from struct import unpack
from .util import FragmentInfo, FragmentedIO
class BootSector(object):
... |
#!/usr/bin/env python3
import model
m = model.HaliteModel()
m.train_on_files('training', 'aggressive')
m.save(file_name='greedy.svc') |
from .legacy_cube import CubeClass
class Cube(CubeClass):
def __init__(self,faces):
super().__init__(faces)
self.algo = []
self.rotation_dict = {'r':lambda x:x.R(),\
'l':lambda x:x.L(),\
'u':lambda x:x.U(),\
'f':lambda x:x.F(),\
'b':lambda x:x.B(),\
'd':lambda x:x.D(... |
"""distutils.command.bdist_dumb
Implements the Distutils 'bdist_dumb' command (create a "dumb" built
distribution -- i.e., just an archive to be unpacked under $prefix or
$exec_prefix)."""
# This module should be kept compatible with Python 2.1.
__revision__ = "$Id$"
import os
from distutils.core import Command
fro... |
"""
WSGI config for myproject 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.11/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SE... |
#!/usr/bin/env python
"""Entry widget for commands, with history.
History:
2002-11-13 ROwen Added history. Bug fix: entering a command would not
scroll all the way to the bottom if data was coming in; fixed using
a carefully placed update_idletasks (we'll see if this always ... |
"""
给定一个没有重复数字的序列,返回其所有可能的全排列。
"""
from typing import List
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
if len(nums) == 1:
return [nums]
else:
ret = []
for i in range(len(nums)):
sub_permute = self.permute(nums[0:i] + n... |
"""Requires Python 3"""
# General imports
import os, sys, shutil
# Third-Party imports
from PySide2 import QtCore
import maya.cmds as cmds
from maya.app.startup import basic
import maya.utils
# Base path definitions
MODULENAME = "depthOfFieldTool"
DRAGGEDFROMPATH = os.path.dirname(__file__)
DEFAULTMODULEPATH = f"... |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from typing import List
from botbuilder.adapters.slack.slack_event import SlackEvent
from botbuilder.adapters.slack.slack_payload import SlackPayload
class SlackRequestBody:
def __init__(self, **kwargs):
self.ch... |
import cv2
import numpy as np
from VideoProcess import PreProcess
from OpticalFlow import OptFlow
import math
class VioFlow:
def __init__(self,video_name):
self.height = 0
self.width = 0
self.B_height = 0
self.B_width = 0
self.bins = np.arange(0.0,1.05,0.05,dtype=np.float64)... |
import torch
import torch.nn as nn
import torch.nn.functional as F
# from torch_scatter import scatter_add
# from num_nodes import maybe_num_nodes
import dgl
from torch_geometric.nn.conv import MessagePassing
import numpy as np
import torch.nn as nn
from torch import Tensor
# from torch_geometric.utils import degree
fr... |
#!/usr/bin/env python
import numpy as np
import cv2
import os
from common import splitfn
USAGE = '''
USAGE: calib.py [--save <filename>] [--debug <output path>] [--square_size] [<image mask>]
'''
if __name__ == '__main__':
import sys, getopt
from glob import glob
args, img_mask = getopt.getopt(sys.arg... |
# Copyright 2021, The TensorFlow Federated 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 o... |
import re
import os
from typing import Optional, Union, List, Dict
from os.path import expandvars
from itertools import chain
from pathlib import Path
from pydantic import (
BaseModel,
SecretStr,
BaseSettings,
PositiveInt,
FilePath,
Field,
validator,
root_validator,
)
from . import co... |
"""Define the DenseMatrix class."""
from __future__ import division, print_function
import numpy as np
from numpy import ndarray
from six import iteritems
from scipy.sparse import coo_matrix
from openmdao.matrices.coo_matrix import COOMatrix
# NOTE: DenseMatrix is inherited from COOMatrix so that we can easily handl... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from .layers import SeqAttnMatch, StackedBRNN, LinearSeqAttn, BilinearSeqAttn
from .layers import weighted_avg, uniform_weights, dropout
class DrQA(nn.Module):
"""Network for the Document Reader module of DrQA."""
_RNN_TYPES = {'lstm': nn.LSTM... |
from mqfactory import Message
from mqfactory.message.security import Signing, Signature
from mqfactory.tools import Policy, Rule
def test_signing_setup(mq, transport, signature):
Signing( mq, adding=signature )
mq.before_sending.append.assert_called_with(signature.sign)
mq.before_han... |
# Automatically generated file
# enum Z3_lbool
Z3_L_FALSE = -1
Z3_L_UNDEF = 0
Z3_L_TRUE = 1
# enum Z3_symbol_kind
Z3_INT_SYMBOL = 0
Z3_STRING_SYMBOL = 1
# enum Z3_parameter_kind
Z3_PARAMETER_INT = 0
Z3_PARAMETER_DOUBLE = 1
Z3_PARAMETER_RATIONAL = 2
Z3_PARAMETER_SYMBOL = 3
Z3_PARAMETER_SORT = 4
Z3_PARAMETER_AST = 5
Z... |
#!/bin/python3
# -*- coding:utf-8 -*-
# CTX Engine-874 : IP
# 1、查询ip样本 2、查看查询结�?# 2、返回正确的ioc信息
from maldium import *
import ctypes
def print_result(result, extra_res):
if result is None:
print("query failed")
return
if result.eMatchType == engine.NO_MATCH:
print("result NO_MATCH")
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
"""Contains classes and functions that a SAML2.0 Service Provider (SP) may use
to conclude its tasks.
"""
import threading
import six
from saml2.entity import Entity
from saml2.mdstore import destinations
from saml2.profile import paos, ecp
from saml2.saml import NAMEI... |
print('Digite um valor de volume em metros cúbocos, que será convertido em libras')
M = float(input('Volume: '))
L = 1000 * M
print(f'O volume em litros é: {L} e em metros cúbicos é: {M}') |
"""Support for alarm control panels that can be controlled through IFTTT."""
import logging
import re
import voluptuous as vol
import homeassistant.components.alarm_control_panel as alarm
from homeassistant.components.alarm_control_panel import DOMAIN, PLATFORM_SCHEMA
from homeassistant.components.alarm_control_panel... |
"""Thin wrapper for dict or OrderedDict providing togglable read-only.
If the Python version keeps dict entries in insertion order, dict is used,
otherwise OrderedDict.
"""
import sys
if (
sys.version_info[:3] >= (3, 6, 0) # pragma: no cover
and sys.implementation.name == "cpython"
) or sys.version_info >= ... |
# flake8: noqa: F811, F401
import asyncio
import pytest
from colorlog import logging
from scam.consensus.block_rewards import calculate_base_farmer_reward, calculate_pool_reward
from scam.protocols import full_node_protocol
from scam.simulator.simulator_protocol import FarmNewBlockProtocol
from scam.types.peer_info i... |
# -*- coding: utf-8 -*-
# Copyright 2018 by dhrone. All Rights Reserved.
#
import pytest
import json
from python_jsonschema_objects import ValidationError
from pyASH.exceptions import *
from pyASH.pyASH import pyASH
from pyASH.objects import Request
# Imports for v3 validation
import jsonschema
from jsonschema im... |
# Copyright 2018 The LUCI Authors. All rights reserved.
# Use of this source code is governed under the Apache License, Version 2.0
# that can be found in the LICENSE file.
"""Defines pRPC server interceptor that initializes auth context."""
import logging
from components import prpc
from . import api
from . import... |
#
# 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
# ... |
#execute
#py config_create.py
import configparser
config = configparser.ConfigParser()
config['mssql'] = {}
config['mssql']['server'] = 'localhost\sql2019'
config['mssql']['database'] = 'dhw_PerformanceAnalytics'
# mssql = config['mssql']
# mssql['server'] = 'localhost\sql2019'
# config['DEFAULT'] = {'ServerAliveIn... |
"""Slice a Volume with an arbitrary plane
hover the plane to get the scalar values"""
from vedo import *
vol = Volume(dataurl+'embryo.slc').alpha([0,0,0.8]).c('w').pickable(False)
sl = vol.slicePlane(origin=vol.center(), normal=(0,1,1))
sl.cmap('Purples_r').lighting('off').addScalarBar(title='Slice', c='w')
arr = sl.... |
from django.contrib import admin
from .models import Room, Message
# Register your models here.
admin.site.register(Room)
admin.site.register(Message) |
"""
This file offers the methods to automatically retrieve the graph Blastomyces dermatitidis ER-3.
The graph is automatically retrieved from the STRING repository.
References
---------------------
Please cite the following if you use the data:
```bib
@article{szklarczyk2019string,
title={STRING v11: protein--... |
import numpy as np
import haiku as hk
import jax
import jax.numpy as jnp
class Actor(hk.Module):
def __init__(self,action_size,node=256,hidden_n=2):
super(Actor, self).__init__()
self.action_size = action_size
self.node = node
self.hidden_n = hidden_n
self.layer = hk.Linear... |
# modified from https://github.com/tkipf/gae/blob/master/gae/layers.py
import torch
import torch.nn as nn
class InnerProductDecoder(nn.Module):
"""Decoder model layer for link prediction."""
def __init__(self, input_dim, act=nn.functional.sigmoid):
super(InnerProductDecoder, self).__init__()
s... |
import pytest
from riotwatcher import ValWatcher
@pytest.mark.val
@pytest.mark.usefixtures("reset_globals")
class TestValWatcher:
def test_require_api_key(self):
with pytest.raises(ValueError):
ValWatcher(None)
def test_allows_positional_api_key(self):
ValWatcher("RGAPI-this-is-a... |
from flask import Flask
from temperature import TemperatureSensor
from flask_socketio import SocketIO, send, emit
from flask import render_template
import time
import threading
import RPi.GPIO as GPIO
app = Flask(__name__)
degcel = TemperatureSensor()
socketio = SocketIO(app)
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(Fa... |
from __future__ import absolute_import, division, print_function
import os
import procrunner
import pytest
import six
from cctbx import sgtbx
from dxtbx.serialize import load
from six.moves import cPickle as pickle
def pickle_loads(data):
if six.PY3:
return pickle.loads(data, encoding="bytes")
else:... |
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making 蓝鲸智云(BlueKing) available.
Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in compliance with the License.
You may obt... |
doc+='''<script type="text/javascript" src="'''
try: doc+=str(routes.widget_base_url)
except Exception as e: doc+=str(e)
doc+='''/__javascript__/bootstrap.js"></script>''' |
import os
import numpy as np
import cv2
import csv
def find_parts(skeleton_reader):
for row in skeleton_reader:
head_color = (float(row['Head_color_X'].replace(',', '.')), float(row['Head_color_Y'].replace(',', '.')))
head_depth = (float(row['Head_depth_X'].replace(',', '.')), float(row['Head_dep... |
import re
def camel_to_snake_case(name: str) -> str:
"""
Source: https://stackoverflow.com/a/1176023
Args:
name: A CamelCase name
Returns:
A snake_case version of the input name
"""
name = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name)
name = re.sub('__([A-Z])', r'_\1', name)
... |
"""Implement a function recursivly to get the desired
Fibonacci sequence value.
Your code should have the same input/output as the
iterative code in the instructions."""
compute_mapping = {}
def get_fib(position):
if position in compute_mapping:
return compute_mapping[position]
if position <= 1:
... |
# 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... |
#
# 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
# ... |
"""
## Pump curve fitting and drawing
- Establish an equation for the pump curve from measured points on the curve in the pump's data sheet
- Get the coefficients of the 2nd order polynomial describing the pump curve and determined via curve fitting
- Draw the pump curve in a diagram
"""
from typing import List, Tupl... |
import ctypes
import os
lib_path = os.path.join(os.path.dirname(__file__), '..', 'strings.so')
lib = ctypes.CDLL(lib_path)
hello = lib.C_Hello
hello.argtype = ctypes.c_int
hello.restype = ctypes.c_char_p
print("Running from python")
print(lib.C_Hello(0))
print(lib.C_Hello(1)) |
findings = {
'a': 'AutoML and high-code model trials return almost the same output',
'b': 'AutoML makes data-cleaning and feature selection implicitly',
'c': 'Quality and relevance of the data is the main determinant',
'd': 'Consuming the model via web interface could provide a better UX',
'p': 'is ... |
import unittest
import numpy as np
from limix.core.covar.zkz import ZKZCov
from limix.utils.check_grad import mcheck_grad
import scipy as sp
class TestZKZ(unittest.TestCase):
def setUp(self):
np.random.seed()
print '\n\n\n'
print np.random.randn(1)
print '\n\n\n'
self._X = n... |
import json
DATATABLES_HTML = """
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Haziris: Datatable</title>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.min.css">
<style>
#haziris-datatables{
padding:5%;
}
#hazi... |
"""Implementation of basic controllers."""
from datetime import datetime
from typing import Any, List, Sequence
from ..utils.common import parse_variables
class RandomController(object):
def __init__(self, env: Any):
"""Random agent. It selects available actions randomly.
Args:
env ... |
# --------------------------
# General Formatting Options
# --------------------------
# How wide to allow formatted cmake files
line_width = 120
# How many spaces to tab for indent
tab_size = 2
# If an argument group contains more than this many sub-groups (parg or kwarg
# groups), then force it to a vertical layout... |
name = input('enter your name: ')
age = input('enter your age: ')
print('My name is %s and I am %s years old' % (name, age))
print('My name is {} and I am {} years old'.format(name, age))
print('My name is {name} and I am {age} years old'.format(age=99, name='Ryan'))
# This last one is more fancy than most people use... |
# Copyright (c) 2021, NVIDIA CORPORATION. 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 appli... |
from dataclasses import dataclass
from typing import Optional
from cactus.types.blockchain_format.vdf import VDFInfo, VDFProof
from cactus.util.streamable import Streamable, streamable
@dataclass(frozen=True)
@streamable
class SignagePoint(Streamable):
cc_vdf: Optional[VDFInfo]
cc_proof: Optional[VDFProof]
... |
#!/usr/bin/env python
import sys
sys.stdout.write('Hello World!\n')
print sys.platform
print sys.version |
#!/usr/bin/env python
'''
===============================================================================
QR code detect and decode pipeline.
===============================================================================
'''
import os
import numpy as np
import cv2 as cv
from tests_common import NewOpenCVTests
class ... |
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 2 20:56:50 2020
@author: junaid
"""
import cv2
import Model_Wrapper as mp
from tensorflow.keras.models import load_model
from PreProcessing_V5 import Fit_Preprocessing, GlobalNormalization, ToJson
from PreProcessing_V5 import ReadFileNames
import numpy as np
import tensor... |
from setuptools import find_packages, setup
import os
import codecs
from conveiro import __version__
with codecs.open(os.path.join(os.path.dirname(__file__), 'README.md'), 'r', encoding='utf-8') as f:
description = f.read()
setup(
author='The ShowmaxLab & Showmax teams',
author_email='oss+conveiro@showm... |
# Copyright 2019 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.
# pylint: disable=W0401,W0614
from telemetry import story
from telemetry.page import page as page_module
from telemetry.page import shared_page_state
clas... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.