content stringlengths 5 1.05M |
|---|
import imp
import module1 # 使用import导入外部定义的函数
module1.make_pizze(16, "pepperoni") # 外部导入的函数调用 必须以导入的模块开头
module1.make_pizze(12, "mushrooms", "green penper", "extra cheese")
from module1 import make_pizze as pizz # 使用as为make_pizza函数定义一个别名
pizz(12, "mushrooms", "green penper", "extra cheese")
import module1 as p # ... |
import asyncio
import enum
import random
import logging
from collections import namedtuple, deque, defaultdict
from .utils import id_generator, prefix_for_id
def get_default_logger():
log = logging.getLogger(__name__)
log.setLevel(logging.INFO)
log.propagate = False
if log.hasHandlers():
ret... |
# -*- coding: utf-8 -*-
import ctypes
import ctypes.util
import os
import sys
def get_libc_function(fn):
if sys.platform == 'win32':
if sys.version_info.minor >= 5:
libc = ctypes.windll.msvcrt
else:
libc = ctypes.CDLL(ctypes.util.find_msvcrt())
else:
libc = cty... |
from isce3.ext.isce3.io import *
# Note that the local 'gdal' package import shadows the gdal package that was
# imported from 'isce3.ext.isce3.io' above
from . import gdal
|
from evalml.pipelines.components.transformers import Transformer
from evalml.utils import (
_convert_woodwork_types_wrapper,
_retain_custom_types_and_initalize_woodwork,
infer_feature_types
)
def _extract_year(col, encode_as_categories=False):
return col.dt.year, None
_month_to_int_mapping = {"Janua... |
import math
import collections
def solution():
while True:
n = int(input())
if n==0:
break
v = collections.Counter(str(math.factorial(n)))
print('%d! --' %(n))
for it in range(5):
print(' (%d)%5d' %(it, v[str(it)]), end = '')
print('')
... |
"""
REST calls to Hopsworks Feature Store Service
"""
import json
import sys
from hops import constants, util
from hops.exceptions import RestAPIError
def _get_featurestores():
"""
Sends a REST request to get all featurestores for the project
Returns:
a list of Featurestore JSON DTOs
Raise... |
from django.contrib import admin
from django.urls import path, include
from mysite_old.cities.views import index
urlpatterns = [
path('admin/', admin.site.urls),
path("", index),
path('cities/', include('mysite_old.cities.urls')),
path('people/', include('mysite_old.people.urls')),
]
|
import math
import os
import paddle.fluid as fluid
import numpy as np
from reader import custom_img_reader
from config import read_params,logger
from network import resnet50
learning_params = {
'learning_rate': 0.0001,
'batch_size': 64,
'step_per_epoch':-1,
'num_epoch': 80,
'epochs':[10,30], # Appl... |
#!/usr/bin/python
# This script prints the predicted body part for a given image
import os
import numpy as np
from keras import optimizers
from keras.models import load_model
from keras.preprocessing import image
import argparse
import tensorflow as tf
parser = argparse.ArgumentParser(description='Predict on single ... |
##############################################################################
#
# Copyright (c) 2005 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOF... |
from textwrap import dedent
from hamcrest import assert_that, equal_to, is_
from pluscal.ast import Skip
from pluscal.builders.procedure import ProcedureBuilder, ProceduresBuilder, PVariableBuilder
def test_procedure() -> None:
builder = ProcedureBuilder("foo").args(
"bar",
).vars(
PVariable... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
import logging
import math
import os
import sys
from io import open
import torch
from torch import nn
from transformerquant.models.base import PreTrainedModel
from transformerquant.modules.residual_bert import ResidualBERT
from transformerquant.modules.activa... |
import MySQLdb
import logging
class Results():
def __init__(self, year=None):
self.year = year
self.logger = logging.getLogger(__name__)
self.db = MySQLdb.connect(host='localhost',
user='vagrant',
passwd='',
... |
import cv2
import numpy as np
cap = cv2.VideoCapture(0)
def nothing(x):
pass
# Creating a window for later use
cv2.namedWindow('result')
# Starting with 100's to prevent error while masking
h,s,v = 100,100,100
# Creating track bar
cv2.createTrackbar('h_min', 'result',0,179,nothing)
cv2.createTrackbar('s_min', ... |
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 6 10:29:21 2018
@author: dedekinds
"""
import os
from PIL import Image
import numpy as np
PATH = os.getcwd()
def png2jpg_background_white(PNG,SEG):
os.chdir(PATH+'/READY')
INPUT=np.array(Image.open(PNG))
os.chdir(PATH+'/examples/segmentation')
seg = np.... |
squares = []
for x in range(6):
squares.append(x ** 2)
squares |
import os
from openpyxl import load_workbook, Workbook
from openpyxl.styles import Font
# mapping from index to letter
letters = [
"A", "B", "C", "D", "E", "F", "G", "H", "I",
"J", "K", "L", "M", "N", "O", "P", "Q", "R",
"S", "T", "U", "V", "W", "X", "Y", "Z"
]
# needed information about excel workbook... |
#!/usr/bin/env python3
import unittest
import ctypes
import re
lib = ctypes.CDLL('../c-bindings/libgojsonnet.so')
lib.jsonnet_evaluate_snippet.argtypes = [
ctypes.c_void_p,
ctypes.c_char_p,
ctypes.c_char_p,
ctypes.POINTER(ctypes.c_int),
]
lib.jsonnet_evaluate_snippet.restype = ctypes.POINTER(ctypes.c... |
from django.test import SimpleTestCase
from ads.forms import AdvertisementForm
from .models import Category
from django.test import TestCase
class TestForms(TestCase):
"""This class tests the input fields in the form that is used when creating or editing a new ad."""
def setUp(self):
"""Making a cate... |
# -*- encoding: utf-8 -*-
'''
@Time : 2020-08-06
@Author : EvilRecluse
@Contact : https://github.com/RecluseXU
@Desc : 为每一个响应的请求头 添加一个 统计数量的响应项
'''
# here put the import lib
import mitmproxy.http
from mitmproxy import ctx
class AddHeader:
def __init__(self):
self.num = 0
def request(s... |
from flask import Flask, request
from flask_restful import Api, Resource, reqparse
import time, json
from API_executor.Authentication import invalidToken
#importing Database
import os, sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import Database as db
class Audit(Resource):
def... |
from abc import ABCMeta, abstractmethod
import os
class TraversalAlgorithm(object, metaclass=ABCMeta):
@abstractmethod
def __init__(self, gridClass, draw):
self.gridClass = gridClass
self.grid = gridClass.get_grid()
self.draw = draw
self.lowestCost = 0
@abstractmethod
... |
import numpy as np
import os
from os import path
import shutil
def material_properties():
'''
Cross-sections from Capilla. Applications of the multidimensional
PL equations to complex fuel assembly problems. 2009.
Returns:
--------
constants: [dictionary]
dictionary that contains the ... |
from time import sleep_ms, ticks_ms, ticks_diff
from machine import Pin, ADC, reset
from micropython import const
from hcsr04 import HCSR04
from umqtt.simple import MQTTClient
_led_light_on_milliseconds = const(30000)
_led_light_current_to_voltage_resistor_value = const(47)
# Wiring:
# D7 UV light switch. High == o... |
# -*- coding: utf-8 -*-
"""
TencentBlueKing is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS
Community Edition) available.
Copyright (C) 2017-2018 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file exce... |
import unittest
from python3_gearman.admin_client import GearmanAdminClient, ECHO_STRING
from python3_gearman.admin_client_handler import GearmanAdminClientCommandHandler
from python3_gearman.errors import InvalidAdminClientState, ProtocolError
from python3_gearman.protocol import GEARMAN_COMMAND_ECHO_RES, GEARMAN_CO... |
import copy
import random
import numpy as np
from typing import Any, Dict, Optional, Union, List
from ding.envs import BaseEnv, BaseEnvInfo, BaseEnvTimestep
from ding.envs.common.env_element import EnvElement, EnvElementInfo
from ding.utils import ENV_REGISTRY
@ENV_REGISTRY.register('bitflip')
class BitFlipEnv(Base... |
#!/usr/bin/python
import operator, copy, os, sys, threading, cStringIO, traceback
import gc
from PySide.QtCore import *
from PySide.QtGui import *
import preferences
pref = preferences.pref
prefDir = preferences.prefDir
from log import *
from tools import unicode_cleanup
import jsitwindow
import TorrentTable
im... |
def pretvori_v_sekunde(niz):
"""
Pretvori niz, ki predstavlja dolžino skladbe v formatu hh:mm:ss v število sekund.
"""
h, m, s = map(int, niz.split(":"))
return s + m*60 + h*3600
def sekunde_v_format(sek):
"""
Pretvori sekunde `sek` v format hh:mm:ss.
"""
if isinstance(sek, str):
... |
import numpy as np
from numba import jit
from ..utils import Const
@jit(nopython=True)
def JB2008(AMJD,YRDAY,SUN,SAT,F10,F10B,S10,S10B,M10,M10B,Y10,Y10B,DSTDTC):
'''
Jacchia-Bowman 2008 Model Atmosphere
This is the CIRA "Integration Form" of a Jacchia Model.
There are no tabular values of density. In... |
"""
Revision ID: 0280_invited_user_folder_perms
Revises: 0279_remove_fk_to_users
Create Date: 2019-03-11 14:38:28.010082
"""
import sqlalchemy as sa
from alembic import op
from sqlalchemy.dialects import postgresql
revision = "0280_invited_user_folder_perms"
down_revision = "0279_remove_fk_to_users"
def upgrade():... |
from rest_framework import serializers
from .models import Role, User, Document
class RoleSerializer(serializers.ModelSerializer):
"""Role Serializer"""
class Meta:
model = Role
fields = ('id', 'name',)
class UserSerializer(serializers.ModelSerializer):
"""User Serializer"""
class Me... |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
from google.cloud import storage
from google.protobuf import json_format
from google.cloud import vision as vision
from google.cloud.vision import enums
from google.cloud.vision import types
import pathlib
# サンプルコードのディレクトリから画像のあるディレクトリへのパスを解決する
image_dir = pathlib.Pat... |
version https://git-lfs.github.com/spec/v1
oid sha256:05673db1cb1df666b8bf0197af1c6e98f55c2f7592d1d52ad135ffd846aa913c
size 1917
|
from ctapipe.visualization import CameraDisplay
__all__ = ['plot_muon_event',
]
def plot_muon_event(ax, geom, image, centroid, ringrad_camcoord,
ringrad_inner, ringrad_outer, event_id):
"""
Paramenters
---------
ax: `matplotlib.pyplot.axis`
geom:... |
# Generated by Django 3.0.10 on 2021-05-17 16:21
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('cms', '0078_auto_20210506_1329'),
]
operations = [
migrations.AlterModelOptions(
name='glossaryterm',
options={'ord... |
import re
from .get_string_similarity import get_string_similarity
class Word:
def __init__(self, string):
if string is None: string = ''
if isinstance(string, self.__class__):
string = string._string
else:
string = str(string)
self._string = re.sub(r'\W+', '', string)
@property
def string(self):
... |
# Split Array Largest Sum: https://leetcode.com/problems/split-array-largest-sum/
# Given an array nums which consists of non-negative integers and an integer m, you can split the array into m non-empty continuous subarrays.
# Write an algorithm to minimize the largest sum among these m subarrays.
# So this solution ... |
from my_lambdata.ds_ulitities import enlarge
print(enlarge(5)) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__author__ = 'ipetrash'
from subprocess import Popen, PIPE, STDOUT
p = Popen(['python', 'google_search.py'], stdout=PIPE, stdin=PIPE, stderr=STDOUT)
p_stdout, p_stderr = p.communicate(input='Котики в чашке'.encode())
print(p_stdout.decode())
|
from functools import partial
class Base:
async def get_data(self):
raise NotImplementedError("Please fill this out")
async def __anext__(self):
return await self.get_data()
def __aiter__(self):
return self
def __or__(self, other):
return other(self)
@classmetho... |
import csv
import math
import os
import random
import re
import time
from pathlib import Path
import pygame
from PIL import Image, ImageOps
from gamescript import commonscript, readstat, menu, battleui
from gamescript.arcade import longscript
rotationxy = commonscript.rotationxy
load_image = commonscript.load_image
l... |
#if-else in python
number = int(input("Enter a number: "))
if number in range(80, 101):
print("A+")
elif number in range(50, 80):
print("50 to 79 range")
elif number in range(33, 50):
print("33 to 49 range")
elif number in range(101, 1000):
print("Over 100")
else:
print("Fail")
|
# Copyright (c) 2018 PaddlePaddle 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 app... |
import numpy as np
from pyscf.lib.linalg_helper import eig
#from pyscf.lib.numpy_helper import einsum
from numpy import einsum
from scipy import linalg as la
import matplotlib.pyplot as plt
############################################################################
# General Simple Exclusion Process:
# ... |
#!/usr/bin/env python
# ____________________________________________________
# :) My Button Netmaxiot interfacing
# Button Example By NetmaxIOT & Rohitkhosla
# OpenSource MIT licence by Netmax IOT Shield And Rohitkhosla
# :)
#------------------------------------------------------------
import time
import Netmaxiot
... |
# coding: utf-8
# /*##########################################################################
# Copyright (C) 2016-2017 European Synchrotron Radiation Facility
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to dea... |
"""
Copyright 2010 Jason Chu, Dusty Phillips, and Phil Schalm
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 agre... |
from celery.result import AsyncResult
from django.shortcuts import render
from django.contrib import messages
from django.http import JsonResponse
from .forms import SendEmailForm
from .tasks import send_email_task, loop
def index(request):
if request.method == 'POST':
form = SendEmailForm(request.POST)... |
from .darknet import Darknet
from .detectors_resnet import DetectoRS_ResNet
from .detectors_resnext import DetectoRS_ResNeXt
from .hourglass import HourglassNet
from .hrnet import HRNet
from .regnet import RegNet
from .res2net import Res2Net
from .resnet import ResNet, ResNetV1d
from .resnext import ResNeXt
from .ssd_v... |
__author__ = 'markcial'
from libs import Slide, Tutor
slides = [
Slide(
"""Types in python
===============
Everything in python has a type, the philosophy behind python is that everything
in the python codebase is a "first class citizen", everything is able to be
overriden, metaprogrammed, extended or patched."""... |
"""Module pointing to different implementations of Model class
The implementations contain methods to access the output or gradients of ML models trained based on different frameworks such as Tensorflow or PyTorch.
"""
class Model:
"""An interface class to different ML Model implementations."""
def __i... |
from enum import Enum
class MethodType(Enum):
COMPUTATION = 'COMPUTATION'
INSTRUMENTATION = 'INSTRUMENTATION'
EXTRACTION = 'EXTRACTION'
PROVENANCE = 'PROVENANCE' |
# metar.py
import logging
import re
# Metadata
NAME = 'metar'
ENABLE = True
USAGE = '''Usage: ![metar|taf] <id> <date>
Given a station ID, produce the METeorological Aerodrome Report or the terminal
aerodrome forecast.
Date is in format yyyymmddhhnn
Examples:
> !metar # Default location... |
import cv2
import numpy as np
import torch
def mmdet_normalize(img, mean, std, to_rgb=True):
"""
Args:
img (ndarray): Image to be normalized.
mean (ndarray): The mean to be used for normalize.
std (ndarray): The std to be used for normalize.
to_rgb (bool): Whether to convert to... |
from django.contrib.auth.models import User
from rest_framework import serializers
from activities.models import Activity
from activities_links.serializer import LinkSerializer
from activities_files.serializer import ActivityFileSerializer
from users.serializer import UserBriefSerializer
from utils.validators i... |
from unittest import TestCase
import pyepgdb
from .testutil import get_resource_path
class SingleResult (TestCase):
def setUp (self):
with open(get_resource_path('single-result.epgdb'), 'rb') as f:
self.results = list(pyepgdb.parse(f))
def test_count (self):
self.assertEqual(len... |
#
# PySNMP MIB module CISCO-VISM-CODEC-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-VISM-CODEC-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:02:03 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (defau... |
""" auto patch things. """
# manual test for monkey patching
import logging
import sys
# project
import ddtrace
# allow logging
logging.basicConfig(stream=sys.stdout, level=logging.DEBUG)
ddtrace.tracer.debug_logging = True
# Patch nothing
ddtrace.patch()
# Patch all except Redis
ddtrace.patch_all(redis=False)
#... |
from hyperpython import div, a
from boogie import router
urlpatterns = router.Router(
template='testapp/{name}.jinja2',
)
@urlpatterns.route('hello/')
def hello_world(request):
return '<Hello World>'
@urlpatterns.route('hello-simple/')
def hello_world_simple():
return 'Hello World!'
@urlpatterns.rou... |
#!/usr/bin/env python3
import pybind_isce3.core as m
def test_constants():
for method in "SINC BILINEAR BICUBIC NEAREST BIQUINTIC".split():
assert hasattr(m.DataInterpMethod, method)
|
# *************************
# |docname| - Core routines
# *************************
#
# Imports
# =======
# These are listed in the order prescribed by `PEP 8
# <http://www.python.org/dev/peps/pep-0008/#imports>`_.
#
# Standard library
# ----------------
# None.
#
# Third-party imports
# -------------------
from sqlalc... |
from django.contrib import admin
# Register your models here.
from .models import Libro, Autor, Prestamo
admin.site.register(Libro)
admin.site.register(Autor)
admin.site.register(Prestamo)
|
import os, sys, subprocess, uproot
from glob import glob
import multiprocessing as mp
from tqdm import tqdm
import numpy as np
from scipy.io import savemat
ntuplePath = "/afs/cern.ch/user/i/ideadr/cernbox/TB2021_H8/rawNtupleSiPM"
def getFiles():
files = glob(ntuplePath + "/*list.root")
files = list(map(os.p... |
# File: 10_game.py
# Author: Raphael Holzer
# Date: 07.01.2019
# from <module> import <object>
from sense_hat import SenseHat
from time import sleep
# create a new SenseHat object
sense = SenseHat()
sense.
blue = (0, 0, 255)
red = (255, 0, 0)
white = (255, 255, 255)
bat_y = 4
ball_position = [3, 3]
ball_velocity =... |
#################################### IMPORTS ###################################
if __name__ == '__main__':
import sys
import os
pkg_dir = os.path.split(os.path.abspath(__file__))[0]
parent_dir, pkg_name = os.path.split(pkg_dir)
is_pygame_pkg = (pkg_name == 'tests' and
os.path.... |
class Demo(object):
A = 1
def get_a(self):
return self.A
demo = Demo()
print(demo.get_a())
|
"""Pytorch recursive layers definition in trident"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import math
import numbers
import random
import warnings
from typing import Optional, Tuple, overload,Union
import torch
import torch.nn as nn
from torch im... |
from model import RepositoryBase
from github import Github
import os
import git
from pydriller import GitRepository
from configuration import REPOSITORY
from model import RepositorySnapshot
from .progress import GitCloneProgress
from typing import List
import itertools
import math
class GithubRepository(RepositoryBas... |
# -*- coding: utf-8 -*-
# Copyright 2017 Carlos Dauden <carlos.dauden@tecnativa.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from odoo import fields, models
class ResPartner(models.Model):
_inherit = 'res.partner'
contract_count = fields.Integer(
string='Contracts',
c... |
from bs4 import BeautifulSoup
from urllib.request import urlopen
class Worldometers():
url = 'https://countrymeters.info/en/World'
# html = requests.get(url).text
html = urlopen(url)
soup = BeautifulSoup(html, 'html.parser')
# World Population
def current_world_population(self, option='total'... |
"""The package metadata."""
__version__ = '0.1.5'
__url__ = 'https://github.com/sublee/teebee'
__license__ = 'MIT'
__author__ = 'Heungsub Lee'
__author_email__ = 'sub@subl.ee'
__description__ = '1k steps for 1 epoch in TensorBoard'
|
import pandas as pd
from pandas import Series,DataFrame
iris_df=pd.read_csv('iris.csv')
print('---DataFrame---')
print(iris_df)
print('---info---')
iris_df.info()
print('---Functions---')
print(iris_df[['Species','Sepal.Length']].groupby(['Species'],as_index=True).mean())
print("Max sepal length: ",iris_df['Sepal.Lengt... |
'''
This module is about domain features.
Author:www.muzixing.com
Date Work
2015/7/29 new this file
'''
from ryu.openexchange.domain.setting import features
from ryu.openexchange.utils import controller_id
from ryu import cfg
CONF = cfg.CONF
class features(object):
def __init__(self,
... |
#!/usr/bin/env python3
import unittest
import os
import numpy as np
from scipy.io import netcdf
from booz_xform import Booz_xform
TEST_DIR = os.path.join(os.path.dirname(__file__), 'test_files')
class RegressionTest(unittest.TestCase):
def test_regression(self):
configurations = ['circular_tokamak',
... |
# coding: utf-8
"""json读写插件
"""
import re
import types
import ujson
import requests
from girlfriend.util.lang import args2fields
from girlfriend.util.resource import HTTP_SCHEMA
from girlfriend.plugin.data import (
AbstractDataReader,
AbstractDataWriter
)
from girlfriend.exception import InvalidArgumentExcept... |
from gingerit.gingerit import GingerIt
text = 'The smelt of fliwers bring back memories.'
parser = GingerIt()
print(parser.parse(text)) |
import random
def Header():
print("-=-"*13)
print("Bem vindo ao jogo de forca")
print("-=-"*13)
def forca():
Header()
#manipulação de arquivos
#Abertura do arquivo
with open("/home/felipe/Desktop/python 3 parte 1/palavras.txt", "r") as arq:
palavras = []
#preenchimento d... |
from __future__ import print_function
import re
import requests
from orionsdk import SwisClient
def main():
# Connect to SWIS
server = 'localhost'
username = 'admin'
password = ''
swis = SwisClient(server, username, password)
engine_id = 1
node_caption = 'example.com'
node_props = {
... |
__all__ = ["VERSION"]
_MAJOR = "0"
_MINOR = "2"
_PATCH = "0.post1"
VERSION = f"{_MAJOR}.{_MINOR}.{_PATCH}"
|
# https://technovechno.com/creating-graphs-in-python-using-matplotlib-flask-framework-pythonanywhere/
# https://stackoverflow.com/questions/50728328/python-how-to-show-matplotlib-in-flask
from flask import Flask, render_template
from graph import build_graph
app = Flask(__name__)
@app.route('/') # Change U... |
#!/usr/bin/env python3.6
# -*- encoding: utf-8; py-indent-offset: 2 -*-
from tkinter import *
def create_textfield():
# constants
background_color = 'grey'
font = "none 14 bold"
window = Tk()
text_input = StringVar()
window.geometry("215x250+100+100")
window.title('A Tkinter Text Field'... |
"""
A robot on an infinite grid starts at point (0, 0) and faces north. The robot can receive one of three possible types of commands:
-2: turn left 90 degrees
-1: turn right 90 degrees
1 <= x <= 9: move forward x units
Some of the grid squares are obstacles.
The i-th obstacle is at grid point (obstacles[i][0], obst... |
import boto3
import os
cw = boto3.client('cloudwatch')
s3 = boto3.client('s3')
def save(filename):
print('Saving ' + filename + ' to s3://'+ os.environ['s3bucket'] + '/' + os.environ['s3key'])
response = s3.upload_file(filename, os.environ['s3bucket'], os.environ['s3key']+'/output/' + filename.split('/')... |
import numpy as np
import pandas as pd
from pandas_profiling import ProfileReport
df = pd.read_excel('teste.xlsx')
profile = ProfileReport(df, title="Pandas Profiling Report")
print(profile) |
import core.models
methods = {
'Actor': {
'model': core.models.view_tables.Actor,
'detail_fields': ['Actor Description', 'Status', 'Organization', 'Person', 'Person Organization',
'Systemtool', 'Systemtool description', 'Systemtool type', 'Systemtool vendor',
... |
"""
Utility file to select GraphNN model as
selected by the user
"""
from nets.molecules_graph_regression.gated_gcn_net import GatedGCNNet
from nets.molecules_graph_regression.gcn_net import GCNNet
from nets.molecules_graph_regression.gat_net import GATNet
from nets.molecules_graph_regression.graphsage_net imp... |
import tensorflow as tf
from .gated_conv import conv2d
def ConvLSTM(inputs, prev_state, hidden_size=128, k_size=3, trainable=True, namescope='convlstm'):
# prev_state:([N, H, W, hidden_size], [N, H, W, hidden_size])
# prev_state = (tf.zeros([N, H, W, hidden_size], tf.float32), tf.zeros([N, H, W, hidden_... |
#!/usr/bin/env python
'''
wbutil/func.py
Functional-programming-oriented utilities.
Will Badart <wbadart@live.com>
created: JAN 2018
'''
import re
from functools import partial, reduce, wraps
from inspect import signature
from itertools import chain
from typing import Any, Callable, Generic, Iterable, TypeVar, Unio... |
#! /usr/bin/python3
'''
This file is part of Lightning Network Probing Simulator.
Copyright © 2020-2021 University of Luxembourg
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 restri... |
#!/usr/bin/env python
import asyncio
import logging
from aiowsio.server import WSIOServer
logger = logging.getLogger("websockets")
logger.setLevel(logging.DEBUG)
logger.addHandler(logging.StreamHandler())
server = WSIOServer("127.0.0.5", 8001)
@server.on("chat message")
async def on_chat_message(client, data):
... |
from flask_sketch.templates.api import resources
__all__ = ["resources"]
|
"""
Contains functions for post-processing of covariance matrices/blocks.
"""
import glob
import os.path
import time
import healpy as hp
import numpy as np
import pymaster as nmt
def get_mixmat(mask_path, nside, lmax_mix, lmax_out, save_path):
"""
Produce the EE->EE mixing matrix for a given mask.
Args... |
from __future__ import division, print_function
import os
import time
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.nn.init as init
import torch.optim as optim
from torch.autograd import Variable
from torch.utils.data import DataLoader
from tqdm import tqdm
import... |
class Remote:
def isClickRight():
pass
class Move:
def moveRight():
pass
remote1 = Remote()
move1 = Move()
if (remote1.isClickRight()):
move1.moveRight()
|
#!/usr/bin/env python
# coding: utf-8
# In[5]:
import pandas as pd
from datetime import datetime
import requests
import numpy as np
import re
from alphacast import Alphacast
from dotenv import dotenv_values
API_KEY = dotenv_values(".env").get("API_KEY")
alphacast = Alphacast(API_KEY)
loop = {
1:{"sheet":'3'},... |
"""
Model objects for the Glance mimic.
"""
from __future__ import absolute_import, division, unicode_literals
from json import dumps
from uuid import uuid4
import attr
from mimic.util.helper import json_from_request
from six import text_type
random_image_list = [
{"id": text_type(uuid4()), "name": "OnMetal - C... |
"""
The count-and-say sequence is the sequence of integers with the first five
terms as following:
1. 1
2. 11
3. 21
4. 1211
5. 111221
1 is read off as "one 1" or 11.
11 is read off as "two 1s" or 21.
21 is read off as "one 2, then one 1" or 1211.
Given an integer n where 1 ≤ n ≤ 30, generate the n... |
import reshade as rs
import pytest
class Test_ConnectionLayer:
def test_ConnectionLayer(self):
layer = rs.ConnectionLayer(height=3, width=4, depth=2)
assert layer.values == [
[[0, 0, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 0]],
[[0, 0, 0, 0],
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.