content stringlengths 5 1.05M |
|---|
"""381. Insert Delete GetRandom O(1) - Duplicates allowed
https://leetcode.com/problems/insert-delete-getrandom-o1-duplicates-allowed/
Design a data structure that supports all following operations in average O(1) time.
Note: Duplicate elements are allowed.
insert(val): Inserts an item val to the collection.
... |
import numpy as np
from math import sin,cos,pi
class Pose(object):
"""The pose class allows for a posing of objects in 2D space. The pose uses a right-hand coordinate system with counter-clockwise measurement of theta from the x-axis
There are several ways to create a pose:
========... |
import operator
from typing import Sequence, Callable, Any, TYPE_CHECKING
import flowsaber
from flowsaber.core.engine.scheduler import Job, TaskManager
if TYPE_CHECKING:
from flowsaber.core.task import Task
from flowsaber.core.flow import Flow
class Solver(object):
"""Multiple knapsack problem solver.
... |
#!/usr/bin/python
# Copyright (c) 2018 PythonAnywhere LLP.
# All Rights Reserved
#
## FIXME: this file is a pre-release copy of a built-in PythonAnywhere script.
## remove once the updated version is deployed to live.
import os
import sys
HOME = os.path.expanduser('~')
TMP = '/tmp'
def write_temporary_bashrc(virtu... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import six
import numpy as np
from gensim.models import Word2Vec
class Word2vecVocabulary(object):
def __init__(self, unknown_token="<UNK>", support_reverse=True):
self._freeze = Fals... |
# Generated by Django 3.0.12 on 2021-02-22 13:43
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('users', '0005_auto_20210221_1538'),
]
operations = [
migrations.AddField(... |
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community
Edition) available.
Copyright (C) 2017-2020 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in co... |
#!/usr/bin/env python
from __future__ import absolute_import, print_function
import sys
from collections import Counter, defaultdict
from . import GeminiQuery
from . import sql_utils
try:
from compiler import compile
except ImportError:
basestring = str
from .gemini_constants import *
from .gemini_bcolz impor... |
#
# PySNMP MIB module DISMAN-EVENT-MIB (http://pysnmp.sf.net)
# ASN.1 source http://mibs.snmplabs.com:80/asn1/DISMAN-EVENT-MIB
# Produced by pysmi-0.0.7 at Sun Feb 14 00:07:55 2016
# On host bldfarm platform Linux version 4.1.13-100.fc21.x86_64 by user goose
# Using Python version 3.5.0 (default, Jan 5 2016, 17:11:52)... |
"""
Outline Tab Serializers.
"""
from django.utils.translation import ngettext
from rest_framework import serializers
from lms.djangoapps.course_home_api.dates.serializers import DateSummarySerializer
from lms.djangoapps.course_home_api.progress.serializers import CertificateDataSerializer
from lms.djangoapps.course_... |
from numpy.distutils.fcompiler import get_default_fcompiler
import sys
import os
fcompile = get_default_fcompiler(os.name, sys.platform, True)
install_dir = sys.argv[1]
os.system("python setup.py " +
"config_fc --fcompiler=" + str(fcompile) +
" build_clib --fcompiler=" + str(fcompile) +
... |
from dataclasses import dataclass
from sqlalchemy import String
import sqlalchemy_utils as su
import uuid
from ..utils import BaseModel, Column, TimeRecordableCRUD
@dataclass
class Usuario(TimeRecordableCRUD, BaseModel):
__tablename__ = 'usuario'
id: str = Column(su.UUIDType, primary_key=True, default=uuid.... |
from .base import *
DEBUG = True
# look into django debug_toolbar app to install for local
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Author : Xiaobo Yang
@Contact : hal_42@zju.edu.cn
@Time : 2021/4/26 21:58
@File : check_img_exits.py
@Software: PyCharm
@Desc :
"""
from imghdr import what
import os.path as osp
__all__ = ["check_img_exits"]
def check_img_exits(img_path: str) -> bool:
... |
# Generated by Django 2.0.6 on 2018-06-20 09:20
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('films', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='film',
n... |
URL = "https://www.prullenbakvaccin.nl"
FORM = "#location-selector"
|
#!/usr/bin/env python
# coding: utf-8
# # Clear Data
# <div style="position: absolute; right:0;top:0"><a href="./tools.ipynb" style="text-decoration: none"> <font size="5">←</font></a>
# <a href="../evaluation.ipynb" style="text-decoration: none"> <font size="5">↑</font></a></div>
#
# This script deletes all files in... |
# Duration Collection Generator
# Jacques Mathieu - 11/19/18
MAX_DUR = 5000.0
MIN_DUR = 5.0
def gen_dur_coll(method, params):
if method == "asc":
return gen_asc_dur_coll(params)
def gen_asc_dur_coll(params):
base_dur = params['base_dur']
max_dur = params['max_dur']
if base_dur < MIN_DUR:
... |
import asyncio
import websockets
import json
from uuid import uuid4
# On Minecraft, when you type "/connect localhost:3000" it creates a connection
async def mineproxy(websocket, path):
print('Connected')
# Tell Minecraft to send all chat messages. Required once after Minecraft starts
await websocket.sen... |
import numpy as np
class BayesBlocks (object):
"""Creates Bayesian blocks from input data.
Based on Scargle et al, 2013
:param data: dict containing one or more of the following keys:
- 't': iterable (1D) containing the times of events or bins.
- 'x': iterable (1D) containing t... |
# Generated from /Users/pdodds/src/kodexa/kodexa/resources/selector.g4 by ANTLR 4.9.1
# encoding: utf-8
from antlr4 import *
from io import StringIO
import sys
if sys.version_info[1] > 5:
from typing import TextIO
else:
from typing.io import TextIO
def serializedATN():
with StringIO() as buf:
buf.write(... |
from celery import task
from tenant_schemas.utils import tenant_context
@task
def send_all_notification_task(tenant, **kwargs):
with tenant_context(tenant):
pk = kwargs.pop('instance_id')
model = kwargs.pop('model')
created = kwargs.pop('created', False)
send_email = kwargs.pop('se... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Mar 20 14:09:11 2019
@author: charlie
"""
from grass.pygrass.modules.shortcuts import vector as v
from grass.script import run_command
#create new column in points map to hold lithology
ksn_points_map = 'chan_segs_points_trimmed'
new_col_name = 'lith_... |
import numpy as np
import matplotlib.pyplot as plt
# Create some training samples
# To demonstrate L2 regularisations ability to minimize the impact
# of outliers, we fabricate training data where X and Y are roughly
# linearly related and then insert a few outliers into Y.
# Construct X
X = np.linspace(0, 10, 50)
... |
from typing import List
from json import dumps
from pathlib import Path
from tdw.controller import Controller
from tdw.tdw_utils import TDWUtils
from tdw.add_ons.object_manager import ObjectManager
from tdw.add_ons.oculus_touch import OculusTouch
from tdw.vr_data.oculus_touch_button import OculusTouchButton
from tdw.ad... |
class InputStreamError(Exception):
""" An error occurred while reading source input """
class InputStream(object):
def __init__(self, data):
self.data = data
self.pos = 0
self.line = 1
self.col = 0
def next(self):
self.pos += 1
ch = self.data[self.pos]
... |
#!usr/bin/env python3
# -*- coding: utf-8 -*-
import pkgutil
from bwtougu.__main__ import cli
from bwtougu.api.api_base import export_as_api
__all__ = [
'__version__',
'version_info'
]
__version__ = pkgutil.get_data(__package__, 'VERSION.txt').decode('ascii').strip()
version_info = tuple(int(v) if v.isdigit... |
# 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 ... |
import logging
import os
import secrets
import ssl
import pyotp
import pymongo
from .common import AUTH_DEV_MODE
def get_env_param(name, def_val=None, try_file=False):
val = os.getenv(name, def_val)
if try_file and val and os.path.isfile(val):
with open(val) as fp:
return fp.read().strip(... |
# Copyright 2017 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.
DEPS = [
'properties',
'step',
'url',
]
def RunSteps(api):
api.url.validate_url(api.properties['url_to_validate'])
def GenTests(api):
... |
import requests
from slugify import slugify
from mycroft.util import LOG
API_URL = 'http://localhost:5005/'
MAX_VOLUME = 32
DELTA_VOLUME = 5
def _get(url):
LOG.info(url)
return requests.get(url)
def get(url):
response = _get(url)
return response.ok
def play(speaker):
return get(API_URL + spea... |
from django import forms
from django.core.validators import MaxValueValidator
from crispy_forms.helper import FormHelper
from captcha.fields import ReCaptchaField
class ContactForm(forms.Form):
helper = FormHelper()
email = forms.EmailField(
label="Podaj swój email kontaktowy",
widget=forms.Em... |
#!/usr/bin/env python3
""" AI Model Data Class.
Provides the AI Model with the required required data
processing functionality.
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,... |
import unittest
import package_1.arithmetic
class Test(unittest.TestCase):
def test_add(self) -> None:
self.assertEqual(package_1.arithmetic.add(1, 2), 3)
if __name__ == "__main__":
unittest.main()
|
"""Template tags for docs italia app."""
from __future__ import absolute_import
from django import template
from readthedocs.core.resolver import resolve
from ..models import PublisherProject
register = template.Library()
@register.filter
def get_publisher_project(slug):
"""get a publisher project from the slu... |
from poetry.core.exceptions.base import PoetryCoreException
__all__ = [clazz.__name__ for clazz in {PoetryCoreException}]
|
#PyTorch implementation of Recurrent Batch Normalization
# proposed by Cooijmans et al. (2017). https://arxiv.org/abs/1603.09025
# Source code from: https://github.com/jihunchoi/recurrent-batch-normalization-pytorch
import torch
from torch import nn
from torch.autograd import Variable
from torch.nn import functional, ... |
# Collect weather data for predetermined cities
# these are the corresponding cities with:
# - wind
# - solar
# - weather data exists on openweather api
import json
import requests
import pandas as pd
from time import time, sleep
from datetime import datetime
def writeData(title,timetext,data):
histfile = f'{t... |
from bs4 import BeautifulSoup
class HtmlParser(object):
def __init__(self, html):
self.soup = BeautifulSoup(html, 'html5lib')
@property
def hrefs(self):
# find all a tag which contains href attribute
a_tags = self.soup.find_all("a", {"href": True})
for tag in a_tags:
... |
#!/usr/bin/env python
"""
Main script
Contains: main function
Author: Yasim Ahmad(yaaximus)
Email: yasim.ahmed63@yahoo.com
"""
from Robot import Robot
from Object import Object
import matplotlib.pyplot as plt
from utils.positional import Position
def main():
"""
This is the function for instantiating obj... |
from stockfish import Stockfish
import re
# Download link: https://stockfishchess.org/download/
def play_on_console():
stockfish = Stockfish(r"stockfish/stockfish_13_win_x64_bmi2.exe")
usr_move = ""
print(stockfish.get_board_visual())
while(1):
usr_move = str(input("Enter move: "))
... |
from .logger import logger
from .ecc import convert_pubkey_to_addr,VerifyingKey,sha256d
class Stack(list):
push = list.append
def peek(self):
return self[-1]
class LittleMachine(object):
def __init__(self):
self.stack = Stack()
self._map = {
"OP_ADD": ... |
from django.db import models
class Customer(models.Model):
email = models.EmailField(unique=True)
name = models.CharField(max_length=255)
class Invoice(models.Model):
email = models.EmailField()
amount = models.IntegerField()
class Note(models.Model):
email = models.EmailField()
content = ... |
from django.apps import AppConfig
class CrapConfig(AppConfig):
name = 'crap'
|
import io
import csv
import requests
import datetime
from config import settings
class Cap(object):
"""
Used for accessing the API from the Harvard Law Caselaw Access Project.
"""
def __init__(self):
"""
Used for authentication.
"""
self.API_KEY = settings.API_KEY
... |
#Problem Link: https://www.codechef.com/MARCH21C/problems/NOTIME
n, h, x = map(int, input().split())
li = list(map(int, input().split()))
if max(li)+x>=h:
print("YES")
else:
print("NO")
|
# -*- coding: utf-8 -*-
# ---
# jupyter:
# jupytext:
# formats: ipynb,py:light
# text_representation:
# extension: .py
# format_name: light
# format_version: '1.5'
# jupytext_version: 1.10.3
# kernelspec:
# display_name: wikirecs
# language: python
# name: wikirecs
# ---
... |
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras.preprocessing.text import Tokenizer
import numpy as np
sentences=[
'I love my dog',
'I love my cat',
'You love my dog!',
'I love cat-dog!'
]
#set the number of the words as 100
#OOV is out of v... |
from app.resources.commentary import Commentary
from app.resources.scorecard import Scorecard
from app.resources.game_play import GamePlay
|
from django.contrib.auth import authenticate, login, logout
from django.db import IntegrityError
from django.http import HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from .models import Carbs, Drinks, Fats, Meals, Proteins, User, Weekly
def index(request):
if request.u... |
# This file is part of the Reproducible and Reusable Data Analysis Workflow
# Server (flowServ).
#
# Copyright (C) 2019-2021 NYU.
#
# flowServ is free software; you can redistribute it and/or modify it under the
# terms of the MIT License; see LICENSE file for more details.
"""Unit tests for helper methods of the stor... |
# -*- coding: utf-8 -*-
# (c) Copyright IBM Corp. 2010, 2020. All Rights Reserved.
# pragma pylint: disable=unused-argument, no-self-use
"""Tests using pytest_resilient_circuits"""
from __future__ import print_function
import pytest
from mock import patch
from resilient_circuits.util import get_function_definition
fro... |
# -*- coding: utf-8 -*-
from helper import *
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
ROOT_DIR = g.ROOT_DIR
raw_data_dir = g.raw_data_dir
processed_data_dir = g.processed_data_dir
print(f"ROOT DIR = {ROOT_DIR}")
data_directory = ROOT_DIR+"/data/raw/"
@click.command()
@click.option('--data_dir', default=ROOT_DIR+"/d... |
# read from HDF5 generated by ../bgen2hdf5/geno_hdf5.py
import h5py
import numpy as np
import pandas as pd
def get_individual_list(hdf5):
with h5py.File(hdf5, 'r') as f:
indiv = f['samples'][:].astype(str)
return indiv
def get_position_list(hdf5):
with h5py.File(hdf5, 'r') as f:
pos = f['... |
#
# File comparison - Compare contents of two files
#
# Copyright (c) 2018, Nobutaka Mantani
# All rights reserved.
#
# 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 ret... |
#!/usr/bin/python
from __future__ import division
# example virtual base jump
import math
from lxml import etree
from pykml.parser import Schema
from pykml.factory import KML_ElementMaker as kml
from pykml.factory import ATOM_ElementMaker as atom
from pykml.factory import GX_ElementMaker as gx
GX_ns = "{http://www.go... |
# vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright 2011 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Copyright 2011 Nebula, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# no... |
import pandas as pd
import torch
from sentence_transformers import SentenceTransformer
df = pd.read_json('data/Movies_and_TV_5.json', lines=True)
df = df[['reviewText']]
df = df.rename(columns={'reviewText': 'review'})
index = pd.read_json('data/amt_train.json').index
df = df.loc[index]
df.to_json('data/review.json')... |
#!/usr/bin/env python
count = 1
count2 = 16
for i in range(1,10):
for j in range(count,10):
if i == 1:
print("%d * %d = %d" % (i,j,i*j),end="\t")
else:
if i == j:
print(" "*count2*(i-1),end="")
print("{} * {} = {}".format(i,j,i*j),end="\t")
... |
# Crie um programa que gere uma página html com links para todos os arquivos jpg e png encontrados a partir de um
# diretório informado na linha de comando
import sys
import os.path
import urllib.request
if len(sys.argv) < 2:
print('\n\nDigite o nome do diretório para coletar os arquivos jpg e png!')
print('U... |
import pytorch_lightning as pl
import torch
from torch import nn
import torch.nn.functional as F
from torchvision import transforms, models
IMAGENET_CLASS_COUNT = 1001
class SimpleCNN(pl.LightningModule):
def __init__(self):
super().__init__()
# TODO: torchserve does this processing, but maybe ... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# ProDy: A Python Package for Protein Dynamics Analysis
#
# Copyright (C) 2010-2012 Ahmet Bakan
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, eith... |
import os
import configparser
QUICKIE_CONFIG_FILE = '.quickieconfig'
def find_quickieconfig():
current_dir = os.getcwd()
while not os.path.isfile(os.path.join(current_dir, QUICKIE_CONFIG_FILE)):
parent_dir = os.path.dirname(current_dir)
if current_dir == parent_dir:
raise... |
import pandas as pd
from sklearn.tree import DecisionTreeClassifier # Import Decision Tree Classifier
from sklearn.model_selection import train_test_split # Import train_test_split function
from sklearn import metrics #Import scikit-learn metrics module for accuracy calculation
from sklearn.tree import export_graphviz
... |
from django.conf.urls import url
from . import views
from . import api_v1
app_name = 'users'
urlpatterns = [
url(
regex=r'^$',
view=views.UserListView.as_view(),
name='list'
),
url(
regex=r'^~redirect/$',
view=views.UserRedirectView.as_view(),
name='redir... |
import os
import sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))
import re
import time
import json
import pprint
import logging
import base64
import pykd
import util.common
import log
import breakpoints
class PyKdDebugger(pykd.eventHandler):
def __init__(self, executable_path = ... |
'''
@jacksontenorio8
Crie um programa que leia vários números inteiros pelo teclado.
O programa só vai parar quando o usuário digitar o valor 999, que
é a condição de parada. No final, mostre quantos números foram
digitados e qual foi a soma entre eles (desconsiderando o flag)
'''
num = i = s = 0
num = int(input('Digit... |
"""
EXERCÍCIO 059: Criando um Menu de Opções
Crie um programa que leia dois valores e mostre um menu como o abaixo na tela:
[ 1 ] Somar
[ 2 ] Multiplicar
[ 3 ] Maior
[ 4 ] Novos Números
[ 5 ] Sair do Programa
Seu programa deverá realizar a operação solicitada em cada caso.
"""
from time import sleep
n1 = int(input('... |
from models.user import UserModel
from conftest import is_valid, log
from freezegun import freeze_time
from models.user import RoleEnum
def test_user_auth(client, test_database, admin_user):
login_response = client.post("/api/login", json={
"email": admin_user.email,
"password": admin_user.password... |
import setuptools
with open("README.md", "r", encoding="utf-8") as fh:
long_description = fh.read()
setuptools.setup(
name="datadock",
version="0.0.1",
author="Andrew Hannigan",
author_email="andrew.s.hannigan@gmail.com",
description="Data blending utility",
long_description=long_descripti... |
__project__ = "SteamGuard"
__author__ = "Tygon"
__version__ = "1.0.0"
__license__ = "MIT" |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'gupiao3.ui'
#
# Created by: PyQt5 UI code generator 5.5.1
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
import sys
import db_mysql
class Ui_Stock(object):
def setupUi(self, Stock):
... |
import requests
from lxml import html
import time
import praw
def sort(inputList):
isSorted=False;
while(isSorted==False):
isSorted=True
for i in range(len(inputList)-1):
if(inputList[i].score > inputList[i+1].score):
inputList[i], inputList[i+1] = inputList[i+1], inputList[i]
isSorted=False
return... |
# Not sure these functions are needed now
def createFileStructure(file_id, fileList=[], folderList=[], filePath=LOCAL_TARGET_DIR):
contents = searchChildrenByParent(file_id)
# Can probably refactor this loop to handle .DS_Store files more elegantly
for item in contents:
newPath = filePath+SLASH+item['name']
... |
"""
The MerossIot library is a low-level python library which interacts with the Meross Cloud
backend systems in order to control Meross devices. You can consider it as a library
upon which you can build automation scripts.
"""
name = "meross_iot"
|
# -*- coding: utf-8 -*-
from ctypes import (
Structure, byref, create_unicode_buffer, c_ubyte, c_ulong,
c_ulonglong, c_ushort, sizeof, windll
)
from enum import IntEnum
class GUID(Structure):
_fields_ = [
('Data1', c_ulong),
('Data2', c_ushort),
('Data3', c_ushort),
('Dat... |
import torch
import matplotlib.pyplot as plt
#################
# Fashion-MNist #
#################
def get_fashion_mnist_labels(labels):
"""Return text labels for the Fashion-MNIST dataset."""
text_labels = [
't-shirt', 'trouser', 'pullover', 'dress', 'coat', 'sandal', 'shirt',
'sneaker', 'bag... |
with open("output.csv", "w") as output:
clusters = []
for i in range(0, 50):
clusters.append( [] )
with open("centroids2.csv", "r") as fd:
for line in fd:
elements = line.split(",")
for x in range(0, 50):
clusters[x].append( elements[x].rstrip() )
output.write("clusterID\t")
for i in r... |
from .web_gui import * |
import torch
a = torch.Tensor([[1, 2], [3, 4]])
print(a)
print(a.type())
a = torch.Tensor(2, 3)
print(a)
print(a.type())
a = torch.ones(2, 2)
print(a)
print(a.type())
# 对角线
a = torch.eye(2, 2)
print(a)
print(a.type())
a = torch.zeros(2, 2)
print(a)
print(a.type())
b = torch.Tensor(2, 3)
b = torch.zeros_like(b)
pr... |
def solve(arr: list) -> int:
""" This function returns the difference between the count of even numbers and the count of odd numbers. """
even = []
odd = []
for item in arr:
if str(item).isdigit():
if item % 2 == 0:
even.append(item)
else:
... |
from setuptools import setup, find_packages
setup(
name='ubuntunews',
version='1.0',
author='Isaac Atia',
author_email='atiaisaac007@gmail.com',
description='Ubuntu News from omgubuntu site',
long_description='Web scraping omgubuntu.co.uk to get latest news about my favourite \
linux distr... |
r=10**9
p=r
c=0
s=0
for i in range(2,int(p/3)+1):
k=0
for j in [i-1,i+1]:
p=2*i+j
if p>10**9:
k=1
if ((p**.5)%10)%2==0:
if ((4*i*i-j*j)**.5)%4==0 and p<r:
print(i,i,j,p)
s+=p
c+=1
if k==1:
... |
#!/usr/bin/env python
# encoding: utf-8
"""
comment.py
Created by Benjamin Fields on 2014-02-11.
Copyright (c) 2014 . All rights reserved.
"""
import sys
import os
import unittest
import requests
import re
from bs4 import BeautifulSoup
class comment(object):
def __init__(self, rg_id=None, text=None, links=[], ... |
import glob
import io
import re
import subprocess
import sys
from enum import Enum
from typing import Tuple
__version__ = '0.2.0'
def get_output(*args):
return subprocess.check_output(args, universal_newlines=True).strip()
def sh(*args):
return subprocess.check_call(args)
def compile_string_decl_regex(va... |
#!/usr/bin/env python
# encoding=utf-8
"""
Copyright (c) 2021 Huawei Technologies Co.,Ltd.
openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:
http://license.coscl.org.cn/MulanPSL2
THIS SOFT... |
"""
create_yaml module
This module provide a create_yaml function to interface the efficientdet-configuration file
"""
import yaml
def create_yaml(list_classes, path_output, autoaugment_policy, sample_image_path=None):
"""create_yaml function
This function has the efficientdet hyper-parameters
Args:
lis... |
from datetime import datetime
import logging
import urllib2
from django.conf import settings
from django.http import HttpResponse
import jsonpickle
from datawinners.common.authorization import httpbasic, is_not_datasender
from datawinners.main.database import get_database_manager
from datawinners.dataextraction.helpe... |
from restart_datasets.core import DataLoader, LocalDataLoader
data = DataLoader()
local_data = LocalDataLoader()
__version__ = "0.6"
|
from CoinInfo import CoinInfo
scrapper = CoinInfo()
num = 1
for i in scrapper.get_paragraphs('bitcoin'):
print(str(num) + ") Title : " + i['title'] + ".\n Link: "+ i['link'])
print("Briefly: " + i['body'])
print("##############################################################################... |
import argparse
from .molecularflow import runSimulation
parser = argparse.ArgumentParser(
prog='python -m molecularflow',
description='Compute molecular flow particle densities in an elbow tube',
formatter_class=argparse.ArgumentDefaultsHelpFormatter
)
parser.add_argument('A', type=float, help='Tube dimen... |
#!/usr/bin/env python3
def welcome():
print("Welcome")
def hi(name):
print("Hi " + name + "!")
welcome()
username = input("Who are there? ")
hi(name=username)
hi(username)
|
from hashlib import md5
from django.core.cache import cache
from django.core.exceptions import ImproperlyConfigured
from django.utils.encoding import smart_str
from django.utils.importlib import import_module
from static_precompiler.settings import MTIME_DELAY, POSIX_COMPATIBLE, STATIC_URL, \
COMPILERS
import os
im... |
from setuptools import setup, find_packages
setup(
name="pyti",
version='0.2.2',
description='Technical Indicator Library',
long_description="This library contains various financial technical "
"indicators that can be used to analyze financial data.",
url='https://github.co... |
# -*- coding: utf-8 -*-
#
# Copyright 2017-2022 - Swiss Data Science Center (SDSC)
# A partnership between École Polytechnique Fédérale de Lausanne (EPFL) and
# Eidgenössische Technische Hochschule Zürich (ETHZ).
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in c... |
"""Submodule providing tensorflow layers."""
from embiggen.layers.tensorflow.graph_convolution_layer import GraphConvolution
from embiggen.layers.tensorflow.noise_contrastive_estimation import NoiseContrastiveEstimation
from embiggen.layers.tensorflow.sampled_softmax import SampledSoftmax
from embiggen.layers.tensorflo... |
from unittest import TestCase
from unittest.mock import Mock, patch
from guet.settings.settings import Settings
from guet.commands.decorators.local_decorator import LocalDecorator
class LocalDecoratorTest(TestCase):
def test_calls_build_on_decorated_when_local_flag_not_in_args(self):
mock_factory = Moc... |
import math
import os
import random
import numpy as np
from gym_duckietown.envs import DuckietownEnv
from gym_duckietown.simulator import AGENT_SAFETY_RAD
POSITION_THRESHOLD = 0.04
REF_VELOCITY = 0.7
FOLLOWING_DISTANCE = 0.24
AGENT_SAFETY_GAIN = 1.15
class PurePursuitPolicy:
"""
A Pure Pusuit controller cl... |
# -*- coding: utf-8 -*-
# file: train_atepc_based_on_checkpoint.py
# time: 2021/7/27
# author: yangheng <yangheng@m.scnu.edu.cn>
# github: https://github.com/yangheng95
# Copyright (C) 2021. All Rights Reserved.
from pyabsa import ATEPCCheckpointManager
from pyabsa.functional import ATEPCModelList
from pyabsa.functiona... |
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D # noqa: F401 unused import
import numpy as np
# Create Map
cm = plt.get_cmap("RdYlGn")
x = np.random.rand(30)
y = np.random.rand(30)
z = np.random.rand(30)
col = np.arange(30)
# # 2D Plot
# fig = plt.figure()
# ax = fig.add_subplot(111)
# ax.sca... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.