content stringlengths 5 1.05M |
|---|
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: chunk.proto
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_dat... |
import os
import sys
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import json
import collections
from deprecated import deprecated
decoder = json.JSONDecoder(object_pairs_hook=collections.OrderedDict)
# global vars
out_dir = './graph'
figure_dir = './figures'
mem_f = '... |
from marshmallow import ValidationError, Schema, fields
# Custom validator
def must_not_be_blank(data):
if not data:
raise ValidationError('Data not provided.')
class GroupSchema(Schema):
id = fields.Int(dump_only=True, dump_to='_id')
name = fields.String(required=True, validate=must_not_be_blan... |
# -*- coding: utf-8 -*-
import os
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2"
import numpy as np
import tensorflow as tf
class DecoderSoftmax(tf.keras.Model):
def __init__(self, tag_size):
super(DecoderSoftmax, self).__init__(self)
self.tag_size = tag_size
def call(self, inputs, lengths):
... |
import random
from random import randint
c = 6
l = list(range( 1 , 50 ))
def main():
i = len(l)
print(i)
print(l)
r = int(input("Which index do you want removed?\n"))
l.pop(r)
print(l)
main() |
"""Sixi webframework"""
__version__ = "0.1.4"
from .api import API
from .middleware import Middleware
from .orm import Column, Database, ForeignKey, Table # noqa
__all__ = ["API", "Middleware", "Database" "Table", "Column", "ForeignKey"]
|
import logging
import numpy as np
from datatypes.projection import Projection as ProjectionData
from datatypes.projection import SubtreeLevelOrder, PerLevelOrders
from projections.qualitymetrics import wrapper_for_d_matrix_calculation, \
points_ordering_to_wildfire_structure, calculate_M1_M2_score, calculate_metri... |
from cacp.dataset import \
ClassificationDatasetBase, \
ClassificationDataset, \
LocalClassificationDataset, \
ClassificationFoldData, \
all_datasets
from cacp.run import run_experiment
__all__ = [
'ClassificationDatasetBase',
'ClassificationDataset',
'LocalClassificationDataset',
... |
# Generated by Django 3.1.2 on 2020-11-11 07:21
from django.db import migrations
import django.db.models.functions.text
class Migration(migrations.Migration):
dependencies = [
('housekeeping_book', '0003_auto_20201014_1830'),
]
operations = [
migrations.AlterModelOptions(
na... |
# -*- coding: utf-8 -*-
"""
Created on Wed Dec 30 15:28:52 2020
@author: TNIKOLIC
"""
import streamlit as st
import nltk
from nltk.tokenize import word_tokenize
import seaborn as sns
from collections import Counter
def plot_parts_of_speach_barchart(text):
nltk.download('averaged_perceptron_tagger')
def _get_... |
#!/usr/bin/env python
'''
primes-cgi.py
@author: Lorenzo Cipriani <lorenzo1974@gmail.com>
@contact: https://www.linkedin.com/in/lorenzocipriani
@since: 2017-10-23
@see:
'''
primesToFind = 1000000
num = 0
found = 0
def isPrime(num):
if num > 1:
for i in range(2, num):
if (num % i) == 0: retu... |
import db.backends.base.operations
import db.backends.base.schema
__all__ = ['operations', 'schema']
|
"""An empty sound package
This is the sound package, providing hardly anything!"""
print("sound package is getting imported!")
|
import asyncio
from pyrogram import Client, idle
from config import API_HASH, API_ID, TOKEN
from utils import http_pool, letras, musixmatch, webdrv
async def main():
await client.start()
await idle()
await client.stop()
await http_pool.aclose()
await letras.http.aclose()
await musixmatch.h... |
def euler1():
count = 0
for i in range(0, 1000):
if i % 3 == 0 or i % 5 == 0:
count += i
print(count)
euler1()
|
import sys
import unittest
sys.path.insert(0, "../src")
from komparse import *
class TestVisitor(object):
def __init__(self):
self._offset = 0
self._tabsize = 2
def enter_node(self, ast):
print(self._offset * " " + ast.name)
self._offset += self._tabsize
def exit_... |
import sentencepiece as spm
# spm.SentencePieceTrainer.train(input='sents.txt', model_prefix='abs-sent-piece', vocab_size=10000)
sp = spm.SentencePieceProcessor(model_file = 'abs-sent-piece.model')
print(sp.encode('Master Servicers'))
print(sp.encode('Special Servicers'))
print(sp.decode([44, 1105]))
print(sp.decode(... |
# Activity
@classmethod
def speed(cls, unit, *args):
speed = 0
speed = reduce(lambda x, y: x/y, args)
return "%s %s" %(speed, unit)
|
#how to make simple your life in tg hehe
from asyncio import sleep
from collections import deque
from random import choice, getrandbits, randint
from re import sub
import requests
from userbot import CMD_HELP
from userbot.events import register
from userbot.modules.admin import get_user_from_event
SALAM = [
"Wa\'... |
from __future__ import division
from cyvlfeat.hog import hog
import numpy as np
from numpy.testing import assert_allclose
from cyvlfeat.test_util import lena
img = lena().astype(np.float32) / 255.
half_img = img[:, :256]
def test_hog_cell_size_32_uoctti():
i = img.copy()
output = hog(i, 32)
asse... |
directions = open('input', 'r').read().strip().split(', ')
x = 0
y = 0
facing = 0 #North
for direction in directions:
if direction[0] == 'R':
facing += 1
else:
facing -= 1
if facing < 0:
facing = 3
elif facing > 3:
facing = 0
count = int(direction[1:])
if facin... |
from pyb import Pin, SPI
import time
class SX1239():
def __init__(self):
super().__init__()
self.SPI = SPI(1, SPI.MASTER, baudrate=600000, polarity=0, phase=0, crc=None)
self.NRST = Pin('Y6', Pin.OUT_PP)
self.NSS = Pin('X5', Pin.OUT_PP)
self.DIO0 = Pin('Y5', Pin.IN, Pin.PUL... |
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
from django.test import TestCase
from django.test.client import Client
from reviewclone.models import Review, Item, Relation, Similar
from reviewclone.utils import find_similar
class TestModels(TestCase):
fixtures = ['item.j... |
#!/usr/bin/env python
import rospy
from flexbe_msgs.msg import BehaviorLog
class Logger(object):
'''
Realizes behavior-specific logging.
'''
REPORT_INFO = BehaviorLog.INFO
REPORT_WARN = BehaviorLog.WARN
REPORT_HINT = BehaviorLog.HINT
REPORT_ERROR = BehaviorLog.ERROR
REPORT_DEBUG = Beh... |
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.my_machine, name='dbindex'),
url(r'^my_machine$', views.my_machine, name='my_machine'),
url(r'^run_model$', views.run_model, name='run_model'),
url(r'^ram_status$', views.ram_status, name='ram_status'),
url(r'^cp... |
"""
UCS FI Claim Handler for Cisco Intersight, v2.2
Author: Ugo Emekauwa
Contact: uemekauw@cisco.com, uemekauwa@gmail.com
Summary: The UCS FI Claim Handler for Cisco Intersight automates the
claiming of UCS Fabric Interconnect clusters in Intersight Managed
Mode.
Credits: Brian Morrissey and Da... |
import pytest
# import constants
from profane.base import (
ModuleBase,
PipelineConstructionError,
ConfigOption,
InvalidConfigError,
Dependency,
module_registry,
constants,
_DEFAULT_RANDOM_SEED,
)
@pytest.fixture
def rank_modules():
module_registry.reset()
constants.reset()
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Module for xml parsing"""
# Libraries
from lxml import etree
# Modules
import datamodel
from jarvis.shared_orchestrator import (function_inheritance, fun_elem_inheritance,
fun_inter_inheritance, phy_elem_inheritance,
... |
# BVH, May 2020
# Common code for VRNN / CVAE-RNN
import sys
import math
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
def sample_latent(mu, logvar):
assert(mu.shape == logvar.shape)
eps = torch.empty_like(logvar).normal_() # standardnormal Gaussian distribution
ep... |
# -*- coding:utf-8 -*-
# author: lyl
from django import forms
from apps.users.models import UserProfile
class WorkOrderApplyForm(forms.Form):
assign_sa = UserProfile.objects.filter(groups__name='sa').values_list('id', 'name_cn')
title = forms.CharField(required=True,
max_length=10, ... |
import json
import codecs
import os
from datetime import datetime
from collections import Counter
def fma():
#userInput = input('Directory of only messages_.json files': ')
searchInput = str(input('Search for word: ').lower())
directory = 'fma/messages/noura'
dir_list = os.listdir(directo... |
# -----------------------------------------------------------------------------
# Copyright (c) 2009-2016 Nicolas P. Rougier. All rights reserved.
# Distributed under the (new) BSD License.
# -----------------------------------------------------------------------------
import numpy as np
from glumpy import app, gloo, g... |
# Generated by Django 3.0 on 2020-03-19 10:33
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='AnalogsModel',
fields=[
('id', models.AutoFie... |
import numpy as np
'''
With Mathematica
FindInstance[
Mod[1504170715041707*n, 4503599627370517] == 0, n, PositiveIntegers]
{{n -> 9007199254741034}}
'''
def fastlinearcongruence(powx, divmodx, N, withstats=False):
x, y, z = egcditer(powx, N, withstats)
answer = (y * divmodx) % N
if x > 1:
powx ... |
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
from setuptools import setup
setup(
name = 'pgdumper',
description = 'Simple PostgreSQL dumper',
author = 'Roman Dolgushin',
author_email = 'rd@roman-dolgushin.ru',
url = 'https://github.com/rdolgushin/pgdumper',
license = 'MIT',
version = '0.1',
packages = ['pgdumper'],
install_requires = ['mydumper... |
import torch.nn as nn
import torch
from transformers import BertModel, BertTokenizer, RobertaModel, RobertaTokenizer
from transformers import AutoTokenizer, AutoModel
import pdb
class BertEncoder(nn.Module):
def __init__(self, bert_model = 'beomi/KcELECTRA-base',device = 'cuda:0 ', freeze_bert = False):
super(BertE... |
# Copyright 2016 Intel Corporation
#
# 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 wri... |
import logging
def basic_logger(name, level):
"""
Returns a basic logger, with no special string formatting.
Parameters
----------
name : str
The name of the logger.
level : int
An integer, such as `logging.INFO`, indicating the desired severity
level. As in the `loggi... |
# Generated by Django 2.2.9 on 2020-07-30 17:20
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('proponentes', '0009_auto_20200729_1628'),
]
operations = [
migrations.AlterField(
model_name='proponente',
name='kit... |
#!/usr/bin/env python
import os
import sys
import warnings
import dotenv
if __name__ == '__main__':
# Filter out missing .env warning, it's fine if we don't have one.
warnings.filterwarnings('ignore', module='dotenv')
# Read .env file and inject it's values into the environment
dotenv.read_dotenv()
... |
import os
with open('neg.txt', 'w') as f:
for filename in os.listdir('./neg'):
f.write('neg/'+filename+'\n')
|
from pulpo_forms.fieldtypes import Field
from pulpo_forms.fieldtypes import FieldFactory
class FileField(Field.Field):
"""
Text field validator, render and analize methods
"""
template_name = "file/template.html"
edit_template_name = "file/template_edit.html"
prp_template_name = "file/properti... |
from pathlib import Path
with (Path(__file__).parent / "input.txt").open() as puzzle_input_file:
puzzle_input_raw = puzzle_input_file.read()
import re
import itertools
import math
INGREDIENT_PATTERN = re.compile(r"capacity (?P<capacity>-?\d+), durability (?P<durability>-?\d+), flavor (?P<flavor>-?\d+), texture (... |
from itertools import product
import random
SHIP_ALIVE = 0x2588 # закрашенный квадрат █ - живой блок корабля
SHIP_HITTED = 0x2591 # полупрозрачный квадрат ░ - подбитый блок корабля
SPACE = 0x0020 # пробел " " - пустая клетка
MISS = 0x002E # точка . - промах
class Dot:
"""класс описание точки"""
# границ... |
import itertools
import torch
class AntecedentLayer(torch.nn.Module):
"""
Form the 'rules' by taking all possible combinations of the MFs
for each variable. Forward pass then calculates the fire-strengths.
"""
def __init__(self, varlist):
super(AntecedentLayer, self).__init__()
... |
#-*- coding: utf-8 -*-
# DO NOT EDIT THIS FILE
# YOU MAY EXTEND/OVERWRITE THE DEFAULT VALUES IN YOUR settings.py FILE
import os
ST_COMMENTS_PER_PAGE = 20
ST_COMMENTS_PAGE_VAR = 'page'
ST_TOPIC_PRIVATE_CATEGORY_PK = 1
ST_UNCATEGORIZED_CATEGORY_PK = 2
ST_RATELIMIT_ENABLE = True
ST_RATELIMIT_CACHE_PREFIX = 'srl'
ST_R... |
import os
import lucene
import time
from java.io import File
from java.nio.file import Paths
from org.apache.pylucene.analysis import PythonAnalyzer
from org.apache.lucene.analysis import LowerCaseFilter, StopFilter
from org.apache.lucene.analysis.standard import StandardAnalyzer, StandardTokenizer
from org.apache.luc... |
# Recipe creation tool - create command plugin
#
# Copyright (C) 2014-2017 Intel Corporation
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
#
# This program is distributed in the ho... |
from nltk.corpus import stopwords
from . import util, scoring_algorithm
from string import punctuation
def remove_stopwords(sentences):
"""
Removes stopwords from the sentence
:param sentences: (list) sentences
:returns: cleaned sentences without any stopwords
"""
sw = set(stopwords.words('nep... |
import math
from maya import cmds, mel
from pymel import core as pm
import pymel.core.datatypes as dt
def find_ikfk_node(node):
for conn in node.attr('message').connections(d=True, s=False):
if pm.hasAttr(conn, 'nodeType') and conn.attr('nodeType').get() == 'FKIKReferences':
return conn
rai... |
import pytest
import os
from turf.distance import distance
from turf.midpoint import midpoint
from turf.utils.error_codes import error_code_messages
from turf.utils.exceptions import InvalidInput
from turf.utils.helpers import truncate
from turf.utils.test_setup import get_fixtures
current_path = os.path.dirname(os.... |
from .checkpoint import checkpoint
from .makeModel import make_model
from .run import fit
from . import constants
from .tools import show_info
from torch.utils.data import DataLoader, distributed
import torch.distributed as dist
import torch
from Transformer.Module import WarmUpOpt, Label... |
# (FIFO) configuration
# author: Christophe VG <contact@christophe.vg>
# class implementation of (FIFO) configuration
from d7a.support.schema import Validatable, Types
from d7a.types.ct import CT
from d7a.sp.qos import QoS
from d7a.sp.session import States
from d7a.d7anp.addressee import ... |
# last edit date: 2016/11/2
# author: Forec
# LICENSE
# Copyright (c) 2015-2017, Forec <forec@bupt.edu.cn>
# Permission to use, copy, modify, and/or distribute this code for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
... |
import json
from transformers import pipeline
model_name = "distilbert-base-uncased-distilled-squad"
nlp = pipeline('question-answering', model=model_name, tokenizer=model_name)
with open("../data/intents-store_inventory.json") as file:
data = json.load(file)
disable_helper = True
input = "available computer"
cu... |
from math import sqrt
def get_z_value(percent):
if percent == int(95):
return 1.96
return None
def get_standard_error(samplevariance=False, standard_deviation=False, samplesize=False):
'''
If you have the sample variance, return it's square root.
Otherwise return the standard deviation divided by the square ro... |
import unittest
from .processor import *
class TestProcessorMethods(unittest.TestCase):
def test_build_matrix01(self):
p = Processor()
p.build_matrix(3, 3)
self.assertEqual(p.encoded_matrix, [[0,0,0],[0,0,0],[0,0,0]])
def test_build_matrix02(self):
p = Processor()
p.bu... |
import torch
import os.path
import math
import pickle
import numpy
print(torch.cuda.is_available())
dataset = []
with open('dataset.pickle', 'rb') as f:
dataset = pickle.load(f)
device = torch.device('cpu')
if torch.cuda.is_available():
device = torch.device('cuda:0')
inputs = []
outputs = []
if torch.cuda... |
from behave import *
use_step_matcher("parse")
@given('Exists a user "{username}" with password "{password}"')
def step_impl(context, username, password):
from django.contrib.auth.models import User
User.objects.create_user(username=username, email='user@example.com', password=password)
@given('I login as u... |
import os
from conans import ConanFile
required_conan_version = ">=1.33.0"
class RenderContextConan(ConanFile):
python_requires = "base_conanfile/v0.2.0@jgsogo/stable"
python_requires_extend = "base_conanfile.BaseCMakeConanfile"
name = "render_context"
homepage = "https://github.com/jgsogo/render_con... |
from django.forms import (
ModelChoiceField,
Form,
RadioSelect,
)
from gbe.models import Class
class PickClassField(ModelChoiceField):
def label_from_instance(self, obj):
return "%s - %s" % (obj.b_title, obj.teacher)
class PickClassForm(Form):
'''
Form for selecting the type of event... |
# -*- coding: utf-8 -*-
import json
from django.test import TestCase
from blueking.component import collections
from blueking.component.client import BaseComponentClient, ComponentClientWithSignature
from blueking.tests.utils.utils import tests_settings as TS # noqa
class TestBaseComponentClient(TestCase):
@cl... |
from microbit import display
display.scroll("Hello, World!")
# Images
from microbit import display, Image
display.show(Image.HAPPY)
boat = Image("00710:00755:00700:99999:09990")
display.show(boat)
# Animation
display.show(reversed([str(x) for x in range(10)]), loop=False, delay=500)
display.show(Image.ALL_CLOCKS,... |
"""Math and other util functions"""
from __future__ import annotations
from typing import TYPE_CHECKING
from ctypes import c_float
from typing import Any, Optional
if TYPE_CHECKING:
from entity import Entity
def cfloat_mult(a: float, b: float) -> int:
c_float_value = c_float(c_float(a).value * c_float(b).val... |
"""
An ``asyncio.Protocol`` subclass for lower level IO handling.
"""
import asyncio
import re
import ssl
from typing import Callable, Optional, cast
from .compat import start_tls
from .errors import (
SMTPDataError,
SMTPReadTimeoutError,
SMTPResponseException,
SMTPServerDisconnected,
SMTPTimeoutEr... |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Copyright(C) 2017-2020 T.WKVER | </MATRIX>. All rights reserved.
# code by </MATRIX>@Neod Anderjon(LeaderN)
#
# modeoption.py
# Original Author: Neod Anderjon(1054465075@qq.com/EnatsuManabu@gmail.com), 2018-3-10
#
# PixivCrawlerIII component
# T.WKVER crawler function... |
#!/usr/bin/env python
"""
File: reporthost.py
Author: Me
Description:
"""
from libnessus.objects.dictdiffer import DictDiffer
from libnessus.objects import reportlogger
from libnessus import exceptions as NessusExceptions
log = reportlogger.ReportLogger('HOST PARSER')
class NessusReportHost(object):
"""
Desc... |
import datetime
import glob
import io
import json
import locale
import logging
import os
import platform
import re
import shutil
import stat
import subprocess
import sys
import threading
import time
import timeit
import urllib.error
import urllib.parse
import urllib.request
import xml.etree.ElementTree as et
import zip... |
import torch
import torchvision
import torchvision.transforms as transforms
import matplotlib.pyplot as plt
import numpy as np
import utils
import seaborn as sns
# Load the training sets
# The data is shuffled by the trainloader
transformCutout = transforms.Compose([
transforms.RandomCrop(32, padding=4),
tran... |
import os
from . import dark_palette
from xappt_qt import constants
def apply_style(app):
xappt_qt_stylesheet = os.getenv(constants.APP_STYLESHEET_ENV)
if xappt_qt_stylesheet is not None and os.path.isfile(xappt_qt_stylesheet):
with open(xappt_qt_stylesheet, 'r') as fp:
custom_stylesheet ... |
from torch_geometric.utils import dense_to_sparse
import torch
import networkx as nx
class Adjacency:
def __init__(self, adj):
self.adj_matrix = adj
self.num_nodes = adj.shape[0]
self.num_edges = int(adj.sum())
self.edge_index, _ = dense_to_sparse(torch.tensor(self.adj_matrix))
... |
import requests
import json
class SummaryService:
""" Base service for calling summary search daemon """
def __init__(self, url):
""" Initialize service parameters
Arguments:
url -- url of daemon, something like http://localhost:5000
"""
self.url_... |
import datetime
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import finance
from matplotlib.collections import LineCollection
from sklearn import cluster, covariance, manifold
def load_dictionary(path):
f = open(path)
names = dict()
for line in f:
if(line[0] != '#'):
l = line.split()
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import numpy as np
import sys
DIR_LIST = ['gradual_ufs', 'burst_ufs', 'gradual_max', 'burst_max']
NUM_RPT = 5
def print_usage_and_exit():
print(f"Usage: {sys.argv[0]} <calloc_dir>")
exit(1)
if len(sys.argv) != 2:
print_usage_and_exit()
calloc_dir = sys.a... |
pre,ans=0,-1
for i in range(int(input())):
n=int(input())
ans+=abs(n-pre)
ans+=2
pre=n
print(ans) |
import pathlib
import urllib.request
import io
from PIL import Image
def get_image_with_url(image_url, save_image=False, title='Unknown', score=0, binary=False, size=()):
try:
if len(title.split(" ")) > 1:
title = title.replace(" ", "-")
if len(title.split(",")) > 1:
titl... |
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 7)
n = int(input())
ans = 0
for i in range(1, n+1):
if i % 3 == 0 or i % 5 == 0:
continue
ans += i
print(ans)
|
"""
Paper: 'BERT: Pre-training of Deep Bidirectional Transformers for Language Understanding'
- https://arxiv.org/pdf/1810.04805.pdf
From original at https://github.com/huggingface/transformers
Original copyright of Hugging Face team code below, modifications by Yehao Li, Copyright 2021.
"""
# Copyrigh... |
#!/usr/bin/env python3
import rasterio
import numpy as np
import argparse
from utils.shared_functions import mem_profile
@mem_profile
def burn_in_levees(dem_filename,nld_filename,out_dem_filename):
#TODO Document this code
dem = rasterio.open(dem_filename)
nld = rasterio.open(nld_filename)
dem_data... |
from typing import TYPE_CHECKING
from typing import Any
from typing import Dict
from typing import Optional
from typing import Union
from poetry.core.semver import VersionRange
from poetry.core.semver import parse_constraint
from poetry.core.version.markers import parse_marker
if TYPE_CHECKING:
from . import (
... |
from typing import Tuple
from group import UnixGroup
class UnixUser:
def __init__(self, name: str, uid: int = None, group: UnixGroup = None, gecos = None, home_dir: str = None, shell: str = None, group_membership: Tuple[str] = ()):
self._name = name
self._uid = uid
self._group = group
... |
import tensorflow as tf
from .vgg16 import vgg16
from tensorflow.python.layers.layers import max_pooling2d
from xview.models.cGAN_ops import residual_block, deconv2d, instance_norm
import os
from glob import glob
class batch_norm(object):
def __init__(self, epsilon=1e-5, momentum = 0.9, name="batch_norm"):
... |
#!/usr/bin/env python
import sys
from deiis.rabbit import Message, MessageBus
""" kaichenc 0307 """
import os
print 'save.py: called'
destination = '/tmp/submission.json'
if len(sys.argv) > 1:
destination = sys.argv[1]
message = Message.Command('SAVE ' + destination, [])
""" kaichenc 0307 """
host = os.environ... |
'''
MIT License
Copyright (c) 2022 Wentao Yuan
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, d... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
# build_test.py
# Copyright (c) 2013 Ahmed M. Hussein (amhussein4@gmail.com)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# ... |
# -*- coding : utf-8-*-
#初始化
week=0
#自定义文本句子获取(sen.txt)
#取自issue #1(By AdminWhaleFall)
def txt():
import random
with open('sen.txt', 'r' , encoding='utf8') as f:
datas = f.readlines()
data = random.choice(datas)
if data.strip() == '':
txt()
else:
return... |
# coding: utf-8
import itertools
import json
import logging
import pandas as pd
import numpy as np
import dataiku
from dataiku.core.sql import SQLExecutor2, HiveExecutor
from dataiku.sql import toSQL
from dataiku.sql import Expression, Column, List, Constant, Interval, SelectQuery, Window, TimeUnit, ColumnType
from ... |
"""
Hangout API for OnAir Broadcast
"""
# pylint: disable=R0801
from hangout_api.utils import tries_n_time_until_true, TIMEOUTS
from retrying import retry
class Broadcast(object):
"""
Broadcast plugin for OnAir
.. testsetup:: Broadcast
from hangout_api.settings.broadcast import Broadcast
... |
__version__ = '0.1.1'
from has_flag import has_flag
from os import environ as env
from dict import dict as edict
import re
import sys
if has_flag('no-color') or \
has_flag('no-colors') or \
has_flag('color=false') or \
has_flag('color=never'):
flagForceColor = 0
elif has_flag('color') or \... |
import json, pyperclip, random
quotefile = './quotes.json'
with open(quotefile) as json_file:
data = json.load(json_file)
quote = random.choice(data['quotes'])
pyperclip.copy(quote)
print(f'The following quote has been copied to your clipboard:\n\033[94m{quote}\033[0m')
|
import itertools
import re, os
import sys
import json
import numpy
class TreeBuilder:
def __init__(self, input_dict, output_file, keys):
"""Class takes a list of dictionaries and creates a tree data structure through dictionaries.
Calls tree builder function.
Args:
input_dict ... |
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from django import forms
from models import TRAFFIC_SOURCE, Wall
import re
class UserCreation(UserCreationForm):
about_textwall = forms.ChoiceField(TRAFFIC_SOURCE)
class LoginForm(AuthenticationForm):
username = forms.CharField(max_l... |
from typing import Union
def plural(n: Union[int,float]) -> bool:
"""Returns True if the plural version is needed for number n."""
return not n == 1 |
from zone_api.core.devices.switch import Switch
from zone_api.core.event_info import EventInfo
from zone_api.core.zone_event import ZoneEvent
from zone_api.core.action import action
@action(events=[ZoneEvent.STARTUP], devices=[], zone_name_pattern='.*Virtual.*')
class SetSwitchTimerAfterStartup:
"""
After the... |
#!/bin/python
from app import app
from flask import g
if __name__ == "__main__":
from os import environ
if 'WINGDB_ACTIVE' in environ:
app.debug = False
app.run(use_reloader=True) |
# -*- coding: utf-8 -*-
import re
import string
import click
import requests
from click import Abort
from colorama import Fore, Back
from requests import RequestException
from ._compat import urlparse
SCHEMES = ['http', 'https']
DEFAULT_SCHEME = 'http'
ARGUMENT_MULT = re.compile('(.+)\*(\d+)$')
def lrange(start, ... |
import copy
import time
import torch
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import roc_auc_score, average_precision_score, f1_score
import sys
sys.path.append("..")
from Graph_embedding import DeepWalk
import random
from utils import *
import dgl
from dataset import *
from sklearn.prepr... |
COMPILER_PATH = "bin/ProtoCompiler.exe"
COMPILER_OPTIONS = [ "--usings", "OxidePack", "--exclude-protoparser" ]
INPUT_FILES = [
"OxidePack.Server.proto"
]
OUTPUT_FILE = "OxidePack.Data.cs"
COPY_PATHS = [
"../../src/OxidePack.Server/Data"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.