content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
# 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 abc
import numpy as np
from PIL import Image
import torch
import torchvision
from platforms.platform import get_platform
class Datase... | python |
import os
import time
from NMLearn.classifiers.tree.desicion_tree import classification_tree
from NMLearn.utilities.dataset_utils.mnist import load_mnist_data
from NMLearn.utilities.metrics import accuracy
##########
# config #
##########
# data parameters
DATA_PATH = "<Path to Dataset>"
# model parameters
MAX_FEATU... | python |
## ! DO NOT MANUALLY INVOKE THIS setup.py, USE CATKIN INSTEAD
from distutils.core import setup
from catkin_pkg.python_setup import generate_distutils_setup
from io import open
# Launch command
from os import path
import re
here = path.abspath(path.dirname(__file__))
project_homepage = "https://github.com/rbonghi/ros... | python |
# misc.py --- Miscellaneous utility functions
# -*- coding: utf-8 -*-
#
# Copyright (c) 2015, 2016 Florent Rougon
#
# This file is distributed under the terms of the DO WHAT THE FUCK YOU WANT TO
# PUBLIC LICENSE version 2, dated December 2004, by Sam Hocevar. You should
# have received a copy of this license along wit... | python |
import os
import operator
import unittest
from ..utils.py3compat import execfile
from .testing import assert_point_in_collection
def mapcall(name, iterative):
return list(map(operator.methodcaller(name), iterative))
class TestExamples(unittest.TestCase):
from os.path import abspath, dirname, join
root... | python |
import re
import json
import urllib.error
import urllib.parse
import urllib.request
from lib.l2p_tools import handle_url_except, clean_exit
class DMAFinder():
location = {
"latitude": None,
"longitude": None,
"DMA": None,
"city": None,
... | python |
from PyQt5 import QtCore as qtc
import cv2
import numpy as np
class DetectionsDrawer(qtc.QObject):
detections_drawn = qtc.pyqtSignal(np.ndarray)
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.dst_h = None
self.dst_w = None
@qtc.pyqtSlot(t... | python |
from __future__ import print_function
import sys
import numpy as np
from yggdrasil.interface.YggInterface import YggRpcServer
from yggdrasil.tools import sleep
def fibServer(args):
sleeptime = float(args[0])
print('Hello from Python rpcFibSrv: sleeptime = %f' % sleeptime)
# Create server-side rpc connec... | python |
from bs4 import BeautifulSoup, SoupStrainer
import requests
import time
def extrai_html(url_pronta):
# PASSAR TAG PRINCIPAL
custom = SoupStrainer('div', {'class': 'item'})
header = {
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.75 Safari/53... | python |
import pprint
from uuid import uuid4
from twisted.internet.defer import Deferred, DeferredList, maybeDeferred
from twisted.web.resource import Resource
from twisted.internet import reactor
from twisted.web import server
from .base import BaseServer, LOGGER
from ..resources import InterfaceResource, ExposedResource
from... | python |
# Generated by Django 3.0.6 on 2020-05-25 10:41
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('sim', '0007_game_cost'),
]
operations = [
migrations.AddField(
model_name='game',
name='budget',
field=m... | python |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-09-27 18:23
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('magic_cards', '0001_initial'),
]
operations = [
migrations.AddField(
... | python |
from ursinanetworking import *
from easyursinanetworking import *
Server = UrsinaNetworkingServer("localhost", 25565)
Easy = EasyUrsinaNetworkingServer(Server)
Easy.create_replicated_variable("MyVariable", {"name" : "kevin"})
Easy.update_replicated_variable_by_name("MyVariablee", "name", "jean")
Easy.remove_replicate... | python |
from PIL import Image, ImageDraw, ImageFont
from pkg_resources import resource_exists, resource_filename, cleanup_resources
def watermark_image(image, wtrmrk_path, corner=2):
'''Adds a watermark image to an instance of a PIL Image.
If the provided watermark image (wtrmrk_path) is
larger than the provided... | python |
# -*- coding: utf-8 -*-
from __future__ import print_function
import argparse
import json
import pprint
import requests
import sys
import urllib
import sqlalchemy
from sqlalchemy import *
import pymysql
from coffeeshop import CoffeeShop
from configparser import SafeConfigParser
pymysql.install_as_MySQLdb()
# This cli... | python |
import deeplift
import numpy as np
def deeplift_zero_ref(X,score_func,batch_size=200,task_idx=0):
# use a 40% GC reference
input_references = [np.array([0.0, 0.0, 0.0, 0.0])[None, None, None, :]]
# get deeplift scores
deeplift_scores = score_func(
task_idx=task_idx,
input_d... | python |
from utils import utils
from enums.enums import MediusEnum, RtIdEnum, MediusChatMessageType
from medius.mediuspackets.chatfwdmessage import ChatFwdMessageSerializer
import logging
logger = logging.getLogger('robo.chat')
class ChatCommands:
def __init__(self):
pass
def process_chat(self, player, text)... | python |
# -*- coding: utf-8 -*-
# Python import
import sys
# Local import
import settings
BLACK, RED, GREEN, YELLOW, BLUE, MAGENTA, CYAN, WHITE = range(8)
#following from Python cookbook, #475186
def has_colors(stream):
if not hasattr(stream, "isatty") or not stream.isatty():
return False
try:
import curses
... | python |
# Copyright 2021 Beijing DP Technology Co., Ltd.
#
# 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 ... | python |
def disemvowel(string):
return "".join(i for i in string if not (i.lower() in "aeiou")) | python |
"""Tests for Broadlink devices."""
from unittest.mock import patch
import broadlink.exceptions as blke
from openpeerpower.components.broadlink.const import DOMAIN
from openpeerpower.components.broadlink.device import get_domains
from openpeerpower.config_entries import ConfigEntryState
from openpeerpower.helpers.enti... | python |
import time
import numpy as np
import sys
sys.path.append('..//Drivers')
sys.path.append('..//PlotModules')
import math
import csv
import matplotlib.pyplot as plt
from waferscreen.inst_control.Keysight_USB_VNA import USBVNA
#####
# Code which will take an S21 measurement with a Keysight USB VNA (P937XA) and plot it LM... | python |
from .Algorithm import PoblationalAlgorithm
from ..Agents.RealAgent import RealAgent
class EvolutionStrategie(PoblationalAlgorithm):
def __init__(self, function, ind_size, p_size, generations, selection_op,
mutation_op, recombination_op, marriage_size=2, agent_args={}, **kwargs):
self.ind_siz... | python |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# # MIT License
#
# Copyright (c) 2020 Mike Simms
#
# 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... | python |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
from gym.spaces import Discrete
from compiler_gym.spaces import Tuple
from tests.test_main import main
def test_equal():
assert Tuple([... | python |
import os
import sys
from configobj import ConfigObj
import click
import requests
from kaos_cli.utils.helpers import run_cmd
from ..constants import KAOS_STATE_DIR, CONFIG_PATH, ENV_DICT
def pass_obj(obj_id):
def decorator(f):
def new_func(*args, **kwargs):
ctx = click.get_current_context()
... | python |
from ModelCreator import get_proportions_model
from ModelEvaluator import plot, show_images
from CustomDataProcessor import get_processed_data
import keras.models as models
import tensorflow as tf
import argparse
import os
import numpy as np
tf.config.experimental.list_physical_devices('GPU')
def train(directory, ima... | python |
from pyalgotrade.barfeed import ibfeed
import datetime
class Parser(object):
def parse(self, filename):
slashIndex = filename.rfind('/')
if (slashIndex > -1):
filename = filename[slashIndex + 1:]
underscoreIndex = filename.rfind('_')
hyphenIndex = filename.rfind('-')
... | python |
# !/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Filename: __init__.py
# Project: helpers
# Author: Brian Cherinka
# Created: Monday, 19th October 2020 5:49:35 pm
# License: BSD 3-clause "New" or "Revised" License
# Copyright (c) 2020 Brian Cherinka
# Last Modified: Monday, 19th October 2020 5:49:35 pm
# Modified By:... | python |
from flask_bcrypt import generate_password_hash, check_password_hash
from sqlalchemy import Column, ForeignKey, Integer, String, Time, UniqueConstraint, text, Float, Index, Boolean, \
DateTime, CHAR
from sqlalchemy.dialects.postgresql import BIT
from sqlalchemy.ext.declarative import declarative_base
from sqlalchem... | python |
"""Typical Queueing Theory Processes"""
from math import erf, exp, log, pi, sqrt
from nc_arrivals.arrival_distribution import ArrivalDistribution
from utils.exceptions import ParameterOutOfBounds
class DM1(ArrivalDistribution):
"""Corresponds to D/M/1 queue."""
def __init__(self, lamb: float, n=1) -> None:
... | python |
from .swear_handler import swear
from .error_handler import VKErrorHandler, DefaultErrorHandler
| python |
def prime2(a):
if a == 2: return True
if a < 2 or a % 2 == 0: return False
return not any(a % x == 0 for x in range(3, int(a**0.5) + 1, 2))
| python |
# -*- coding: utf-8 -*-
from datetime import datetime
import threading
import time
from logger import logger
LOCK_POOL_WORKERS = threading.RLock()
POOL_WORKERS = {}
def _register_new_worker(worker_id, host, port, datetime_now, ttl=600):
""" Нельзя использовать без блокировки LOCK_POOL_WORKERS """
worker = {... | python |
import re
import sys
fileName = sys.argv[1]
with open('./'+fileName+'.g', 'r') as rf:
with open('./'+fileName+'-format.g', 'w') as wf:
line = rf.readline()
while line:
infos = re.split(r'[\s]', line)
if infos[0] == 'v':
wf.write('v {} {}\n'.format(int(infos[... | python |
import numpy as np
import scipy.sparse as sp
## sc-pml and the nonuniform grid are both examples of diagonal scaling operators...we can symmetrize them both
def create_symmetrizer(Sxf, Syf, Szf, Sxb, Syb, Szb):
'''
input Sxf, Syf, etc. are the 3D arrays generated by create_sc_pml in pml.py
#usage ... | python |
# -*- coding:UTF-8 -*-
# Author:Tiny Snow
# Date: Wed, 24 Feb 2021, 00:50
# Project Euler # 055 Lychrel numbers
#=================================================Solution
lychrel_numbers = 0
for n in range(1, 10000):
flag = True
str_n = str(n)
reverse_n = ''.join(reversed(str_n))
for _ in range(50):
... | python |
"""Apps for cms"""
from django.apps import AppConfig
class CMSConfig(AppConfig):
"""AppConfig for cms"""
name = "cms"
def ready(self):
"""Application is ready"""
import cms.signals # pylint:disable=unused-import, unused-variable
| python |
import abc
import logging
from typing import Optional
from ..defaults import Defaults, Key
from ..errors import MenuConfigError
from ..helpers import Utils
logger = logging.getLogger(__name__)
class AbstractMenu(abc.ABC):
def __init__(self, **config):
self._config = config
self.validate__conf... | python |
import os
import sys
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
probes = (
('pEN1', 100423573, 100433412, 'Linx'),
('pEN2', 100622909, 100632521, 'Xite'),
('pLG1', 100456274, 100465704, 'Linx'),
('pLG10', 100641750, 100646253, 'Dxpas34'),
('pLG11', 10... | python |
features_dict = {
"Name":{
"Description":"String",
"Pre_Action":'''
''',
"Post_Action":'''
''',
"Equip":'''
''',
"Unequip":'''
'''
},
"Dual Wielding":{
"Description":"You can use this weapon in your Off Hand (if availab... | python |
import os
import subprocess
import pytest
from app.synspec import wrapper
def test_synspecwrapper_remove_spectrum(mocker):
syn = wrapper.SynspecWrapper(teff=20000, logg=4, wstart=4400, wend=4600)
mocker.patch("os.remove")
syn._remove_spectrum()
os.remove.assert_called_once()
def test_synspecwra... | python |
# curl -i -X GET 'http://192.168.0.146:8000/v2/projects'
import requests
SERVER_IP = '192.168.0.146'
SERVER_PORT = '8000'
r = requests.get('http://'+SERVER_IP+':'+SERVER_PORT+'/v2/projects')
#print(r.status_code)
#print(r.headers['content-type'])
#print(r.encoding)
#print(r.text)
#print(type(r.json()))
ALL_PROJECT... | python |
import cx_Oracle
import log
import define_data_type as DTF
class Cache:
def __init__(self):
self._results = {}
def execute(self, conn, table, param, value):
sql_request = f"SELECT * FROM {table} WHERE {param}='{value}'"
try:
return self._results[sql_request]
except... | python |
import requests
no = input("enter your no")
r = requests.get('https://get.geojs.io/')
ip_request = requests.get('https://get.geojs.io/v1/ip.json')
ipadd = ip_request.json()['ip']
url = 'https://get.geojs.io/v1/ip/geo/' + ipadd + '.json'
geo_request = requests.get(url)
geo_data = geo_request.json()
msg = f"latitude: {ge... | python |
# encoding: utf-8
from .usstock_interface import * | python |
from SimPEG import Survey, Utils, Problem, np, sp, mkvc
from simpegMT.Utils import rec2ndarr
import simpegMT
from scipy.constants import mu_0
import sys
from numpy.lib import recfunctions as recFunc
############
### Data ###
############
class DataMT(Survey.Data):
'''
Data class for MTdata
:param SimPEG ... | python |
import itertools
from aoc_cqkh42 import BaseSolution
class Solution(BaseSolution):
def part_a(self):
return self.data.count('(') - self.data.count(')')
def part_b(self):
instructions = (1 if item == '(' else -1 for item in self.data)
return list(itertools.accumulate(instructions)).in... | python |
from .core import core
from .task_parser import TaskParser, UnexpectedDayName
from .wrapper import GoogleTasksWrapper, NoSuchTaskList | python |
class PulldownButtonData(ButtonData):
"""
This class contains information necessary to construct a pulldown button in the Ribbon.
PulldownButtonData(name: str,text: str)
"""
@staticmethod
def __new__(self,name,text):
""" __new__(cls: type,name: str,text: str) """
pass
| python |
import numpy as np
import os
from pyspark.sql import SparkSession
import cluster_pack
from cluster_pack.spark import spark_config_builder
if __name__ == "__main__":
package_path, _ = cluster_pack.upload_env()
ssb = SparkSession.builder \
.appName("spark_app") \
.master("yarn") \... | python |
from django.db import models
from django.db import migrations
import django.db.models.deletion
import swapper
class Migration(migrations.Migration):
dependencies = [
('imagestore_cms', '0001_initial'),
]
operations = [
migrations.AlterField(
'imagestorealbumptr',
... | python |
# pylint: disable=duplicate-code
"""
Authentication example
======================
.. Copyright:
Copyright Wirepas Ltd 2019 licensed under Apache License, Version 2.0
See file LICENSE for full license details.
"""
from utils import get_settings, setup_log
from connections import Connections... | python |
#
# PySNMP MIB module FR-MFR-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/FR-MFR-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:15:59 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:... | python |
import torch
import numpy as np
from utils import vocab, pos_vocab, ner_vocab, rel_vocab
class Example:
def __init__(self, input_dict):
self.id = input_dict['id']
self.passage = input_dict['d_words']
self.question = input_dict['q_words']
self.choice = input_dict['c_words']
... | python |
import pygame
pygame.init()
SCREEN_WIDTH = 800
SCREEN_HEIGHT = int(SCREEN_WIDTH * 0.8)
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption('Shooter')
#set framerate
clock = pygame.time.Clock()
FPS = 60
#define player action variables
moving_left = False
moving_right = False
... | python |
# -*- coding: utf8 -*-
from django.contrib.auth import get_user_model
from django.core import mail
from django.test import TestCase
from rest_framework.authtoken.models import Token
from nopassword.models import LoginCode
class TestRestViews(TestCase):
def setUp(self):
self.user = get_user_model().objec... | python |
# see https://www.codewars.com/kata/559a28007caad2ac4e000083/solutions/python
fibonacci_cache = {}
def fib(n):
if n in fibonacci_cache:
return fibonacci_cache[n]
if n == 1: return 0
if n == 2: return 1
else:
value = fib(n-1) + fib(n-2)
fibonacci_cache[n] = value
return value
def perimeter(n... | python |
import warnings
import numpy as np
import scipy.sparse as sp
class Graph:
"""
A container to represent a graph. The data associated with the Graph is
stored in its attributes:
- `x`, for the node features;
- `a`, for the adjacency matrix;
- `e`, for the edge attributes;
-... | python |
from __future__ import annotations
from typing import List, Tuple
def check_conflicts(path1: Path, path2: Path) -> bool:
"""
Checks if two paths have either an edge conflict or a vertex conflict
:param path1: The first path
:param path2: The second path
:return: True if paths are confl... | python |
from collections import defaultdict
from itertools import cycle, count
# Python 3 got rid of itertools.izip because zip now does it (but not in Python 2)
try: from itertools import izip
except: izip = zip
def spiral_directions():
dirs = cycle([(1,0), (0,-1), (-1,0), (0,1)]) # R, U, L, D, ...
dists = (n >> 1 f... | python |
import requests
from .progressbar import SimpleProgressBar
def download(url, dst):
r = requests.get(
url,
stream=True,
)
bar = SimpleProgressBar(int(r.headers['Content-Length']))
with open(dst, 'wb') as f:
CHUNK_SIZE = 256 * 1024
for chunk in r.iter_content(chunk_size=C... | python |
from barcode import EAN13
from barcode.writer import ImageWriter
from io import BytesIO
# print to a file-like object:
rv = BytesIO()
EAN13(str(100000902922), writer=ImageWriter()).write(rv)
# or sure, to an actual file:
with open('somefile.jpeg', 'wb') as f:
EAN13('100000011111', writer=ImageWriter()).write(f) | python |
# -*- coding: utf-8 -*-
# @Author: YangZhou
# @Date: 2017-06-03 20:02:55
# @Last Modified by: YangZhou
# @Last Modified time: 2017-06-03 20:07:13
from ase import io
atoms=io.read('POSCAR')
filter=atoms.positions[:,0]<atoms.positions[:,0].max()-5.17286
del atoms[filter]
atoms.cell[0,0]=5.17286
atoms.cente... | python |
# Copyright 2019 The ROBEL 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 agreed to in wr... | python |
a = {
'x' : 1,
'y' : 2,
'z' : 3
}
b = {
'w' : 10,
'x' : 11,
'y' : 2
}
#find keys in common
print( a.keys() & b.keys() )
#find keys in a not in b, no + operator
print(a.keys() - b.keys() )
#find (key,value) pairs in common !!not values
print(a.items() & b.items() )
c = {key:a[key] for key in a.keys() & b.keys() }
pr... | python |
"""
Простое приложение, которое показывает импорт функций.
"""
from library.services import delay_function
if __name__ == "__main__":
delay_function(10)
| python |
tup1 = ("aws",'azur',1988,2050,50,57)
tup2 = (1,2,3,4,5,6,7)
print(tuple(enumerate(tup1)),type(tup1),id(tup1),len(tup1))
print(tuple(enumerate(tup2)),type(tup2),id(tup2),len(tup2))
print(tup1[3:])
print(tup1[-3])
print(tup2[:4])
print(tup2[0:])
#del(tup1[0]) #tuple object doesnot support item deletion
tup = (1,2,[1... | python |
from .database import *
from acq4.util import DataManager
from acq4.pyqtgraph.widgets.ProgressDialog import ProgressDialog
import acq4.util.debug as debug
from acq4.Manager import logExc, logMsg
class AnalysisDatabase(SqliteDatabase):
"""Defines the structure for DBs used for analysis. Essential features are:
... | python |
# -*- coding: utf-8 -*-
"""
Created Aug 11, 2020
author: Mark Panas
"""
def OpenAirBeam2(filename):
import numpy as np
import pandas as pd
with open(filename) as fp:
out = fp.readlines()
#print(out[0].rstrip().split(','))
if out[0].rstrip().split(',')[0] != "":
#pr... | python |
import requests
import os
import json
import logging
from logging.handlers import TimedRotatingFileHandler
import time
from kafka import KafkaProducer
import psycopg2
from datetime import datetime, timezone
import datetime
import pytz
from psycopg2.extras import Json
from psycopg2.sql import SQL, Literal, Identifier
f... | python |
"""
Copyright (C) 2004-2015 Pivotal Software, Inc. All rights reserved.
This program and the accompanying materials are made available under
the terms of the under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
... | python |
from PIL import Image
import math
import sys
import eleksdrawpy as xy
def create_paths(im):
f = (255 * 255 * 3) ** 0.5
paths = []
w, h = im.size
for m in [-2, -1, 0, 1, 2]:
for radius in range(0, w, 8):
path = []
for a in range(1800):
a = math.radians(a /... | python |
"""
Satellite6Version - file ``/usr/share/foreman/lib/satellite/version.rb``
========================================================================
Module for parsing the content of file ``version.rb`` or ``satellite_version``,
which is a simple file in foreman-debug or sosreport archives of Satellite 6.x.
Typical ... | python |
def main():
# input
N = int(input())
# compute
l_0, l_1 = 2, 1
if N == 1:
print(l_1)
else:
for _ in range(N-1):
l_i = l_0 + l_1
l_0, l_1 = l_1, l_i
print(l_i)
# output
if __name__ == '__main__':
main()
| python |
"""
Qxf2 Services: Utility script to compare images
* Compare two images(actual and expected) smartly and generate a resultant image
* Get the sum of colors in an image
"""
from PIL import Image, ImageChops
import math, os
def rmsdiff(im1,im2):
"Calculate the root-mean-square difference between two images"
h ... | python |
from requests import get
def myip():
return get('http://checkip.amazonaws.com/').text.strip()
| python |
#Tres personas deciden invertir su dinero para fundar una empresa. Cada una de ellas invierte una cantidad distinta.
#Obtener el porcentaje que cada quien invierte con respecto a la cantidad total invertida.
primera_inversion = float(input("Ingrese la primera inversion \n"))
segunda_inversion = float(input("Ingrese l... | python |
import os
with open('locationsCOMSAT.csv') as f:
header = f.readline()
g = [l.rstrip().split(',') for l in f.readlines()]
## all information in string, not numerics
cmda = 'python createjobscriptsnora10a.py'
cmd = 'python createjobscriptsnora10.py'
ncdir = '/work/users/kojito/nora10/nc'
start = '2011'
end... | python |
import speech_recognition as sr
import pyttsx3
from datetime import datetime
import webbrowser
from subprocess import Popen, CREATE_NEW_CONSOLE
import random
import sys
speech = 0
commands = {}
scripts = {}
responses = {}
active = True
def audio_to_text(recognizer, mic):
if not isinstance(recognizer, sr.Recogniz... | python |
'''1. 编写 Demo 类,使得下边代码可以正常执行:
>>> demo = Demo()
>>> demo.x
'FishC'
>>> demo.x = "X-man"
>>> demo.x
'X-man'
'''
class Demo:
def __getattr__(self , name):
return 'FishC'
| python |
import os
import torch
import torch.nn as nn
import unittest
from fusion.architecture.projection_head import LatentHead
os.environ['KMP_DUPLICATE_LIB_OK']='True'
class TestLatentHead(unittest.TestCase):
def test_forward(self):
dim_in = 32
dim_l = 64
latent_head = LatentHead(dim_in, dim_... | python |
import balanced
balanced.configure('ak-test-2eKlj1ZDfAcZSARMf3NMhBHywDej0avSY')
debit = balanced.Debit.fetch('/debits/WD5SwXr9jcCfCmmjTH5MCMFD')
dispute = debit.dispute | python |
import mcprot
import asyncio
import logging
logging.basicConfig(level = logging.INFO)
stream = mcprot.PacketStream('localhost', 25565)
loop = asyncio.get_event_loop()
result = loop.run_until_complete(stream.get_status())
print(result)
| python |
from typing import Any, Dict, List
from electionguard.types import BALLOT_ID
from .base import BaseResponse, BaseRequest, Base
from .election import CiphertextElectionContext
from .tally import CiphertextTally
__all__ = [
"CiphertextTallyDecryptionShare",
"DecryptTallyShareRequest",
"DecryptionShareReque... | python |
import pandas as pd
import streamlit as st
import numpy as np
df = pd.read_csv('data/raw/ames_housing_data.csv')
max_price = df['SalePrice'].max()+50
min_price = df['SalePrice'].min()
bins = np.linspace(min_price, max_price, 60)
inds = np.digitize(df['SalePrice'], bins)
price_groups = [bins[inds[i]] for i in ... | python |
import os
from typing import Dict
from allennlp.interpret.attackers import Attacker, Hotflip
from allennlp_demo.common import config, http
class MaskedLmModelEndpoint(http.ModelEndpoint):
def __init__(self):
c = config.Model.from_file(os.path.join(os.path.dirname(__file__), "model.json"))
super(... | python |
import os
import unittest
import warnings
from flask import json
import webapp
from config import TestingConfig, Config
class HomeViewTest(unittest.TestCase):
#@unittest.skip
def setUp(self):
self.app = webapp.app.test_client()
self.app.testing = True
#@unittest.skip
def test_home_pa... | python |
import pydub
import pytube
output_path = "C:/Users/epics/Music"
segments = []
playlist = pytube.Playlist("https://youtube.com/playlist?list=PL3PHwew8KnCl2ImlXd9TQ6UnYveqK_5MC")
for i in range(0,16):
segments.append(pydub.AudioSegment.from_file(f"{output_path}/.ytmp3_cache/{i}.mp3",format="mp4"))
sum(segments).ex... | python |
import mapping
import struct
import types
#import logging
#log = logging.getLogger('util.primitives.structures')
class enum(list):
'''
>>> suits = enum(*'spades hearts diamonds clubs'.split())
>>> print suits.clubs
3
>>> print suits['hearts']
1
'''
def __init__(self, *... | python |
from __future__ import absolute_import
from __future__ import print_function
import os
import yaml
import argparse
import sys
import numpy as np
from flask import Flask, request, jsonify
import json
import os
import io
from werkzeug.utils import secure_filename
import subprocess
AUDIO_STORAGE = os.path.join("/content"... | python |
import tensorflow as tf
import numpy as np
x_data = np.random.rand(100).astype(np.float32)
y_data = 0.1*x_data + 0.3
W = tf.Variable(tf.random_uniform([1],-1.0,1.0))#产生均匀分布的随机张量
b = tf.Variable(tf.zeros([1]))
y = W*x_data + b
loss = tf.reduce_mean(tf.square(y-y_data))
optimizer = tf.train.GradientDescen... | python |
output = input['fields']
| python |
from functools import reduce
from typing import List
import numpy as np
__all__ = [
"ABCDElement", "Media", "FreeSpace", "ThinLens",
"FlatInterface", "CurvedInterface", "ABCDCompositeElement",
"ThickLens", "PlanoConvexLens"]
class ABCDElement:
@property
def length(self) -> float:
ret... | python |
class StatusHost:
hostname: str
device_id: str
uptime: int
power_time: int
time: str
timestamp: int
fwversion: str
devmodel: str
netrole: str
loadavg: float
totalram: int
freeram: int
temperature: int
cpuload: float
height: int
def __init__(self, data):
... | python |
from __future__ import division
import numpy as np
import os
import pandas as pd
import itertools
import matplotlib.pyplot as plt
## required in 3D plot
from mpl_toolkits.mplot3d import Axes3D
import xml.etree.ElementTree as ET
import time
import pylab as pl
from IPython import display
import sys
import time
import c... | python |
import flask
import requests
import sqlalchemy
from sqlalchemy import orm
_HAS_PSYCOPG2 = False
try:
import psycopg2
_HAS_PSYCOPG2 = True
except ImportError:
pass
from .base import ExceptionConverter
class ArgumentErrorConverter(ExceptionConverter):
@classmethod
def convert(cls, exc):
i... | python |
from troposphere import Template
from troposphere.iot import (
Certificate,
Policy,
PolicyPrincipalAttachment,
Thing,
ThingPrincipalAttachment,
TopicRule,
TopicRulePayload,
Action,
LambdaAction,
)
t = Template()
certificate = Certificate(
'MyCertificate',
CertificateSignin... | python |
import sys, math
code = {
"TTT": "F","TTC": "F", "TTA":"L", "TTG":"L",
"CTT":"L", "CTC":"L", "CTA":"L", "CTG":"L",
"ATT":"I", "ATC":"I", "ATA":"I", "ATG":"M",
"GTT":"V", "GTC":"V", "GTA":"V", "GTG":"V",
"TCT":"S", "TCC":"S", "TCA":"S", "TCG": "S",
"CCT":"P", "CCC":"P", "CCA":"P", "CCG":"P",
"ACT":"T", "ACC":"T", ... | python |
"""Class to infer with the model."""
from pathlib import Path
import torch
from PIL import Image
from torch.cuda.amp import autocast
from torch.nn import DataParallel
from torch.utils.data import DataLoader
from tqdm import tqdm
from .config import Config
from .data import INPUT_CHANNELS, OUTPUT_CHANNELS, TestDataset... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.