content stringlengths 5 1.05M |
|---|
# -*- coding: utf-8 -*-
"""
Classifiers
Created on Fri Mar 2 05:18:46 2018
@author: Oliver
"""
import sys
import os
from sklearn import svm, metrics
#from sklearn.decomposition import PCA
#from sklearn.pipeline import Pipeline
#from sklearn.model_selection import GridSearchCV
#from sklearn.linear_model import Log... |
import PyV8
ctxt = PyV8.JSContext()
ctxt.enter()
func = ctxt.eval("""
(function(){
function hello(){
return "Hello world.";
}
return hello();
})
""")
print func()
|
from django.apps import AppConfig
class PriceAnalysisConfig(AppConfig):
name = 'price_analysis'
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.8 on 2019-07-10 15:28
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('trend', '0005_auto_20190710_1810'),
]
operations = [
migrations.AlterField(... |
# Copyright 2021 Pants project contributors.
# Licensed under the Apache License, Version 2.0 (see LICENSE).
DEV_PORTS = {
"helloworld.service.frontend": 8000,
"helloworld.service.admin": 8001,
"helloworld.service.user": 8010,
"helloworld.service.welcome": 8020,
}
def get_dev_port(service: str) -> i... |
from random import randint, seed
import cv2 as cv
import sys
import os
import math
import numpy as np
import heapq
from timeit import default_timer as timer
# from numba import jit
# from numba.typed import List
seed(42069)
# functions for converting images to grids
def getListOfFiles(dirName, allFiles):
# crea... |
from datetime import datetime
from pysnmp.smi import rfc1902
from piat.utils.logger import get_logger
LOGGER = get_logger(__name__)
class TrapMsg:
""" Trap msg Object """
def __init__(self, var_binds, viewer):
"""
Trap Msg Object.
:param var_binds: pysnmp var_binds.
:param vi... |
K = int(input())
h = K // 2
print((K - h) * h)
|
# Copyright (c) 2013, Lin To and contributors
# For license information, please see license.txt
# PLEASE NOTE : THIS CODE IS TERRIBLE, I GENERALLY DO BETTER THAN THIS
from __future__ import unicode_literals
import frappe
from frappe import _
def execute(filters=None, filter_by_date=True):
records = get_sql_reco... |
#!/usr/bin/python
import os
import sys
import argparse
import numpy as np
import pylab as pl
import scipy.io
from copy import deepcopy
from scai_mne.viz import circular_layout, plot_connectivity_circle
from scai_utils import *
from aparc12 import get_aparc12_cort_rois
lobes = ["Prefrontal", "Premotor", "Insular", "... |
import os.path
from validator.contextgenerator import ContextGenerator
class ChromeManifest(object):
"""This class enables convenient parsing and iteration of
chrome.manifest files."""
def __init__(self, data, path):
self.context = ContextGenerator(data)
self.lines = data.split('\n')
... |
import torch
from torch.autograd import Variable
import torch.utils.data as Data
import torch.nn as nn
import matplotlib.pyplot as plt
import torch.optim as optim
from matplotlib import cm
import numpy as np
import copy
torch.manual_seed(1) # reproducible
def franke(X, Y):
term1 = .75*torch.exp(-((9*X - 2).pow... |
from struct import unpack
from LnkParse3.text_processor import TextProcessor
"""
An ItemID is an element in an IDList structure (section 2.2.1). The data stored
in a given ItemID is defined by the source that corresponds to the location in
the target namespace of the preceding ItemIDs. This data uniquely identifies
th... |
import sys
from pathlib import Path
from tools import human_readable, progress_bar, get_func_exec_time
from datetime import datetime
class FileCrawler:
_directories: int = 0
_files: int = 0
_hidden_files: int = 0
_total_size: int = 0
_stats_link = "\x1b]8;;file://./crawls-stats.txt/\acrawls-stats.... |
from understat.constants import BASE_URL, LEAGUE_URL, PLAYER_URL, TEAM_URL
from understat.utils import (filter_by_positions, filter_data, get_data,
to_league_name)
class Understat():
def __init__(self, session):
self.session = session
async def get_stats(self, options=Non... |
from django.urls import path
from .views import SharedImageListView,FriendsListView
urlpatterns = [
path('get-shared-img/', SharedImageListView.as_view(), name="get-share"),
path('get-friends/', FriendsListView.as_view(), name="get-friends"),
]
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pytest
from smorest_sfs.utils.text import camel_to_snake
@pytest.mark.parametrize(
"camel, snake",
[
("AdminAvator", "admin_avator"),
("getHTTPResponseCode", "get_http_response_code"),
("HTTPResponseCodeXYZ", "http_response_code_xyz... |
from Views import stok_View as stokView
from Controllers import stok_Controller as stokController
stokView(stokController())
|
from selenium import webdriver
import os
result=os.system("ls -l ")
print(result)
driver=webdriver.Firefox()
driver.get("http:/www.126.com")
driver.implicitly_wait(10)
driver.find_element_by_id("lbNormal").click()
try:
driver.find_element_by_css_selector(".j-inputtext dlemail").send_keys("jslzsy")
driver.find... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import argparse
import sys
import torch
import numpy as np
from torch.utils.data import DataLoader
from torchvision.datasets import MNIST
import torchvision.transforms as transforms
parser = argparse.ArgumentParser(description='PyTorch GMVAE')
# TRAINING PARAMS
parser.a... |
__author__ = 'stephen'
import os,sys
import numpy as np
HK_DataMiner_Path = os.path.relpath(os.pardir)
#HK_DataMiner_Path = os.path.abspath("/home/stephen/Dropbox/projects/work-2015.5/HK_DataMiner/")
sys.path.append(HK_DataMiner_Path)
from utils import plot_cluster, plot_each_cluster, XTCReader, plot_landscape
import a... |
from selenium.webdriver.remote.webelement import WebElement
import conftest
from locators.course_page_locators import CoursePageLocators
from locators.course_page_locators import ManageCoursePageLocators
from locators.login_page_locators import LoginPageLocators
from models.course import CourseData
from pages.base_pag... |
# imports
import argparse
import numpy as np
from scipy.special import gammainc
########################################################################################################################
# Game value as a function of m,n,k
#################################################################################... |
# django imports
from django.conf import settings
from django.contrib.contenttypes.models import ContentType
from django.contrib.sites.models import Site
from django.core.mail import EmailMultiAlternatives
from django.template import RequestContext
from django.template.base import TemplateDoesNotExist
from django.templ... |
#!/usr/bin/env python3
class Example:
"""Ez egy példa osztály"""
bela = 'alma'
def gizi(self):
print('I love you.')
jozsi = gizi
def __init__(self):
self.vali = 24
ex = Example()
ey = Example()
print('Kakukk')
ex.bruno = ['répa']
print(ex.bruno[0])
del(Examp... |
import requests
'''
launch simulation [POST]
curl -X POST -H "Content-Type: application/json" -d "@input_data.json" http://localhost:5000/launch_simulation
'''
response = requests.post('http://127.0.0.1:5000/launch_simulation', json={'key': 'value'})
print(response.headers)
print(response.json())
'''
as_vulnerabilit... |
from flyingpigeon import eodata
from datetime import datetime as dt
from os import listdir
from os.path import join, basename
from flyingpigeon.utils import archiveextract
# DIR = '/home/nils/birdhouse/var/lib/pywps/cache/flyingpigeon/EO_data/PSScene4Band/analytic'
# # DIR = '/home/nils/data/planet/PSScene3Band/'
# til... |
# Import necessary libraries
import streamlit as st
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from my_utils import getKmers, get_metrics, predict_sequence_class
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.model_selection import train_test_split
from sklearn.me... |
import os
from multiprocessing import Pool
from torch.cuda import is_available
os.environ["CUDA_VISIBLE_DEVICES"] = "1"
import logging
import anomalytransfer as at
from glob import glob
from utils import run_time
from typing import Sequence, Tuple, Dict, Optional
import pandas as pd
import numpy as np
import torch
f... |
class ConfigException(Exception):
pass
class ConfigLoadException(ConfigException):
pass
class NoConfigOptionError(ConfigException):
pass
|
from flask import Flask
import sys
sys.path.append('../chordpro2html')
from chordpro2html import Parser
from songs import TWINKLE, LEAVES, TENSHI
p = Parser()
song = TWINKLE
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello():
return p.to_html(LEAVES) + p.to_html(TWINKLE) + p.to_html(TEN... |
"""
A set of classes that let you create interactive menus in the console
"""
from dataclasses import dataclass, field
from console.inputs import SelectionInput, SelectionInputOptions, InputResult
@dataclass
class MenuOptions(SelectionInputOptions):
recurring: bool = True
cancel_codes: tuple = field(defau... |
from enum import Enum
from typing import Optional
from semantic_version import SimpleSpec, Version
class ContractFeature(Enum):
SERVICES = "services"
MAX_TOKEN_NETWORKS = "max_token_networks"
INITIAL_SERVICE_DEPOSIT = "initial_service_deposit"
MS_NEEDS_TOKENNETWORK_REGISTRY = "ms_needs_tokennetwork_r... |
import io
import re
import sys
from numba import njit
_INPUT_ = """\
hellospaceRhellospace
"""
#sys.stdin = io.StringIO(_INPUT_)
@njit
def solve(S):
T = ""
for i in range(len(S)):
s = S[i]
if s == 'R':
T = T[::-1]
else:
if len(T) > 0 and T[-1] == s:
... |
from .._pixsfm._residuals import * # noqa F403
|
import pandas as pd
def field_variety(data):
"""
Computes the number of different fields that each paper is about by taking the number of fields in 'fields_of_study'
Input:
- df['fields_of_study']: dataframe (dataset); 'fields_of_study' column [pandas dataframe]
Output:
... |
import gzip
import io
import lz4.frame
import struct
import sys
from .event import Event
import proio.proto as proto
from .writer import magic_bytes
class Reader(object):
"""
Reader for proio files
This class can be used with the `with` statement, and it also may be used
as an iterator that seque... |
version = "3.38"
|
from fairseq.models.transformer_lm import TransformerLanguageModel
from fairseq.models.transformer_autoencoders import TransformerAutoencoders
import torch
import numpy as np
import torch.nn.functional as F
from random import randint
from midi_preprocess import encode_midi, decode_midi
import utils
def temperature_sa... |
import sys
from xhtml2pdf import pisa
def convert_html_to_pdf(source_html, output_filename):
with open(output_filename, "w+b") as result_file:
pisa_status = pisa.CreatePDF(source_html, dest=result_file)
return pisa_status.err
if __name__ == "__main__":
if len(sys.argv) != 3:
print("re-... |
# coding: utf-8
"""
Qc API
Qc API # noqa: E501
The version of the OpenAPI document: 3.0.0
Contact: cloudsupport@telestream.net
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import six
from telestream_cloud_qc.configuration import Configuration
class... |
import logging
import time
from collections import deque
from itertools import count
import numpy as np
from qulab import BaseDriver
from .AlazarTechWrapper import (AlazarTechDigitizer, AutoDMA, DMABufferArray,
configure, initialize)
from .exception import AlazarTechError
log = loggi... |
#Faça um programa que leia o sexo de uma pessoas, mas só aceite valores 'M' e 'F'.
#Caso esteja errado, peça a digitação novamente até terum valor correto.
sexo = str(input('Informe o sexo: [M/F]')).strip().upper()[0]
while sexo not in 'FfMm':
sexo = str(input('Dados invalidos, Por favor infome seu sexo: ')).strip(... |
"""satellite-3d setup."""
from setuptools import setup, find_packages
with open("satellite_3d/__init__.py") as f:
for line in f:
if line.find("__version__") >= 0:
version = line.split("=")[1].strip()
version = version.strip('"')
version = version.strip("'")
... |
from setuptools import setup, find_packages
setup(
name='PYLin',
version='0.1',
packages=find_packages(exclude=['tests*']),
license='MIT',
description='YLin-Python-Package,
long_description=open('README.txt').read(),
install_requires=['numpy'],
url='https://github.com/BillMills/python-... |
def Boxing(box_number, box_size, object_volume_array, base_index):
a_index = base_index
object_counter = 0
for b_n in range(box_number): # filling each box
total_objects_volume = 0
while total_objects_volume <= box_size and a_index < len(object_volume_array):
# until box i... |
from pathlib import Path
import pathlib
import cv2
import numpy as np
import math
from util import _get_furniture_info
def place_multi_furniture(furniture_obj_dir="./data/basic_furniture/", wall_objs_dir="./data/mid/panel_384478_洋室/", room_scale_factor=1):
"""compute each wall's smoothness"""
if not isinstan... |
"""
WSGI config for django_practice project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/2.0/howto/deployment/wsgi/
"""
import os
import sys
import logging
from django.core.wsgi import get_ws... |
#!/usr/bin/env python3
from __future__ import annotations
import queue
import time
import pandas as pd
import mecademicpy.mx_robot_def as mx_def
from .robot_trajectory_files import RobotTrajectories
from pathlib import PurePath
# 2nd values of this dict are taken from controller.cpp HandleSetRealTimeMonitoring() ->... |
# For reference, see <https://github.com/quinlan-lab/hts-python/blob/master/hts/htsffi.py>, even though it uses deprecated .verify()
import cffi
import os.path
cxx_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'x.cpp')
with open(cxx_path) as f:
src = f.read()
ffibuilder = cffi.FFI()
ffibuilder... |
import textakel
from flask import Flask
from flask import jsonify
from flask import render_template
app = Flask(__name__)
@app.route("/")
def index():
return render_template("index.html")
@app.route("/api/v1/<string:function_name>/<path:s>")
def get_text(function_name, s):
s = textakel.takel(function_name,... |
import math
from server.federation import alignment
from server.eAd import paillier
import pandas as pd
import numpy as np
import time
# import rsa
global theta_a,ra,alpha
# 设置权重参数的初始值
theta_a = None
rsa_len = 1112
ppk_a, psk_a = paillier.gen_key()
scal = 1000
alpha = 0.1
def cal_ua(x,theta):
temp1 = np.dot(th... |
from wrangle.wrangle import wrangle_function
t_test, p_value, df = wrangle_function('sleepdata')
print(f'T-test: {t_test} \nP-value: {p_value} \nDF-head: {df.head(3)}')
|
# =============================================================================
# PROJECT CHRONO - http://projectchrono.org
#
# Copyright (c) 2014 projectchrono.org
# All rights reserved.
#
# Use of this source code is governed by a BSD-style license that can be found
# in the LICENSE file at the top level of the distr... |
import requests
import pandas as pd
import numpy as np
def fetch_url(url):
res = requests.get(url)
return res.json()
def fetch_comments(comment_url):
d = fetch_url(comment_url)
try:
nextPageToken = d["nextPageToken"]
except:
nextPageToken = None
comments = [d["items"][index][... |
from literal_distribution_thing import LiteralDistribution, exclude_subsets, PID_sets
from cana.boolean_node import BooleanNode
from binarize import to_binary
# set up variables
n_inputs = 2**3
rule = 131
output = to_binary(rule, n_inputs)
bn = BooleanNode.from_output_list(outputs=output)
# print(bn.input_symmetry())
... |
import numpy as np, tensorflow as tf, aolib.util as ut, aolib.img as ig, os
import tensorflow.contrib.slim as slim
import tensorflow.contrib.slim.nets as nets
import vgg, h5py
import sklearn.metrics
pj = ut.pjoin
full_dim = 256
crop_dim = 224
train_iters = 10000
batch_size = 32
#batch_size = 32
#base_lr = 1e-4
base_l... |
import logging
from typing import Dict
from typing import List
import neo4j
from cartography.intel.jamf.util import call_jamf_api
from cartography.util import run_cleanup_job
from cartography.util import timeit
logger = logging.getLogger(__name__)
@timeit
def get_computer_groups(jamf_base_uri: str, jamf_user: str... |
from __future__ import absolute_import
from . import train_set
# Globally-importable utils.
from .train_set import train_A_x
from .train_set import train_B_x |
#!/usr/bin/env python
from yaml import load, dump
try:
from yaml import CLoader as Loader
except ImportError:
from yaml import Loader
from connection import Connection
from logging import Logging
import importlib
import datetime
import argparse
parser = argparse.ArgumentParser(description='Start workload.')
pa... |
from unittest import TestCase
from src.utils import order_diagnosis
from src.consequents import COMMON_CONSEQUENT_NAME
class ReferenceDiagnosisTest(TestCase):
FOR_SURE_LEVEL = 60
common_consequent_name = COMMON_CONSEQUENT_NAME
output = None
def _get_diagnosis(self):
if not self.medical_recor... |
import matplotlib
from matplotlib import pyplot as plt
import pandas as pd
import numpy as np
from numpy import random
# define initial population and coolperation
def Init_pop_one():
POP_ONE = []
# define chromosome -- random.shuffle(ChromosomeX)[K]
for i in range(POP_SIZE):
POP_ONE.append(random.... |
"""
Copyright 2012 Ali Ok (aliokATapacheDOTorg)
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... |
# Copyright (c) 2015 Red Hat Inc.
# 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... |
#!/usr/bin/env python
# license removed for brevity
import sys
import os
current_folder = os.path.dirname(os.path.realpath(__file__))
sys.path.append(current_folder)
modules_folder = os.path.join(current_folder, "..")
sys.path.append(modules_folder)
main_folder = os.path.join(modules_folder, "..")
sys.path.app... |
from rest_framework.serializers import ModelSerializer
from garments.models import BaseGarment
from garments.models import Garment
from garments.models import GarmentType
from garments.models import GarmentFabric
from garments.models import Colorway
from garments.models import GarmentSize
from garments.models import G... |
warning2 = "Your email has not been verified, so if you forget your password, you will not be able to reset it."
warning = "Your email has not been linked, so if you forget your password, you will not be able to reset it."
|
import warnings
from collections.abc import MutableMapping
MSG_ERROR_OPER = "Unsupported operand type(s) for {} and 'Polynomial'"
MSG_ERROR_ARG = "Polynomial() takes least one argument (0 given)"
MSG_ERROR_VAL = "{} must be 'int' or 'float' not '{}'"
MSG_ERROR_KW = "Unexpedted keyword argument: '{}'"
MSG_WARNING = "Re... |
# Copyright 2018 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from telemetry.page import legacy_page_test
from telemetry.page import shared_page_state
from page_sets.rendering import rendering_story
from page_sets.rende... |
# -*- coding: UTF-8 -*-
from resources.lib.modules import control
from resources.lib.api import colorChoice
AddonID = control.AddonID
AddonTitle = control.AddonTitle
SelectDialog = control.SelectDialog
Execute = control.execute
Notify = control.Notify
CustomColor = control.setting('my_ColorChoice')
if CustomColor =... |
class Solution:
def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]:
ans = []; i = 0
for row in mat:
ans.append((i, row.count(1))); i+= 1
ans = sorted(ans, key = lambda element: (element[1], element[0]))
ans = [x[0] for x in ans]
... |
from abc import ABCMeta
from typing import Dict, List, Union
from urllib.parse import urlparse
ArgumentsType = Dict[str, Union[int, float, str]]
class BaseObject(metaclass=ABCMeta):
__slots__ = []
def __eq__(self, other):
if type(self) != type(other): # pylint: disable=unidiomatic-typecheck
... |
import momaf_dataset
import transformers
import bert_regressor
import sys
import re
import torch
if __name__=="__main__":
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--load-from",default=None,help="Path to a model")
parser.add_argument("--field",default="content-noyearnopers... |
class BaseBuilding(object):
"""
boilder-plate class used to initiale the various building in
municipality
"""
def __init__(self, location=None, land_rate=500):
if not isinstance(location, str) and location is not None:
raise TypeError("Location should be of type str")
... |
import gzip
import json
MAX_LUNATION = 102657
MIN_LUNATION = -21014
def generate(args, model):
print(
f'> Exporting {MAX_LUNATION - MIN_LUNATION + 1:d} lunations '
f'to {args.path_to_json_output:s}'
)
with gzip.open(args.path_to_json_output, 'wt') as f:
f.write(json.dumps(list(map... |
import torch
from torch import nn as nn
from transformers import BertConfig
from transformers import BertModel
from transformers import BertPreTrainedModel
from spert import sampling
from spert import util
def get_token(h: torch.tensor, x: torch.tensor, token: int):
"""
获得特定的token嵌入(例如[CLS])。
:param h: 句... |
"""
config_utils.py
---------------
Utility functions for parsing manim config files.
"""
__all__ = [
"_run_config",
"_paths_config_file",
"_from_command_line",
"finalized_configs_dict",
]
import argparse
import configparser
import os
import sys
import colour
from .. import constants
from ..util... |
import tornado.web
import traceback
import logging
logger = logging.getLogger("tornado.application")
class BaseHandler(tornado.web.RequestHandler):
def write_error(self, status_code, **kwargs):
exc_type, exc_value, exc_traceback = kwargs["exc_info"]
logger.error("status_code %s: %s" % (status_code... |
"""Test ndpoly baseclass functionality."""
import numpy
from pytest import raises
import numpoly
XY = numpoly.variable(2)
X, Y = numpoly.symbols("q0"), numpoly.symbols("q1")
EMPTY = numpoly.polynomial([])
def test_scalars():
"""Test scalar objects to catch edgecases."""
assert XY.shape == (2,)
assert XY.... |
# Generated by Django 3.1.4 on 2021-04-22 11:27
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('booking', '0008_auto_20210320_1615'),
]
operations = [
migrations.AlterField(
model_name='cart',
name='status',
... |
"""
"""
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from sympy import *
from sympy.matrices import Matrix,eye
from moro.abc import *
from moro.util import *
__all__ = [
"axa2rot",
"compose_rotations",
"dh",
"eul2htm",
"htm2eul",
"htmrot",
"htmtra",
"rot... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.7 on 2017-07-09 02:03
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('projects', '0003_build_error'),
]
operations = [
migrations.AlterField(
... |
# -*- coding: utf-8 -*-
#
# This file is part of AceQL Python Client SDK.
# AceQL Python Client SDK: Remote SQL access over HTTP with AceQL HTTP.
# Copyright (C) 2021, KawanSoft SAS
# (http://www.kawansoft.com). All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use ... |
i=1
s=0
dec=int(input("Enter the value of number\n"))
while(dec>0):
rem=int(dec%10)
s=s+(i*rem)
dec=int(dec/10)
i=i*2
print("\n")
print(s)
input()
|
'''
Kattis - pervasiveheartmonitor
Simple input parsing, just try to write as little code as possible.
'''
import statistics
from sys import stdin
for line in stdin:
line = line.strip()
line = line.split()
name = []
while line[0][0].isalpha():
name.append(line.pop(0))
while line[-1][0].isalp... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2019-08-02 13:59
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
replaces = [('analytics', '0001_initial'), ('analytics', '0002_node'), ('analytics', '... |
from torch import nn
from video.ConvLstmCell import ConvLstmCell
import torch
class LSTM_PixelSnail(nn.Module):
def _to_one_hot(self, y, num_classes):
scatter_dim = len(y.size())
y_tensor = y.view(*y.size(), -1)
zeros = torch.zeros(*y.size(), num_classes, dtype=y.dtype).to('cuda')
... |
# :coding: utf-8
# :copyright: Copyright (c) 2021 strack
"""Describe the distribution to distutils."""
# Import third-party modules
import os
from setuptools import find_packages
from setuptools import setup
ROOT_PATH = os.path.dirname(os.path.realpath(__file__))
README_PATH = os.path.join(ROOT_PATH, 'README.md')
r... |
import unittest
import subprocess
import sys
import socket
import os
import time
import signal
import argparse
import across
from across.__main__ import _parse_tcp
from .utils import par, mktemp, localhost, localhost_ipv6, anyaddr, skip_if_no_unix_sockets, skip_if_no_ipv6
def spawn_main(args, **popen_extras):
r... |
# python stdlib dependencies
import binascii
import os
import sys
import yaml
# local imports
from .command import Command
from .command import commandlet
from .db import Db
from .utils import TemporaryDirectory
from .utils import hash_pass
from .utils import check_pin
from .utils import rand_str
from .utils import ge... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
import glob
import time
from collections import deque
import os
# os.environ['CUDA_VISIBLE_DEVICES']='-1'
from tracker import tracker,detector,helpers
import cv2
import tqdm
import argparse
import config
from data_mana... |
# -*- coding: utf-8 -*-
"""
This is a standalone script that writes a csv with columns Time in UTCG, Lat,
Lon, and Alt to a great arc propagator file (.pg). Inputs of vehicle ID and
full csv path are prompted from the user. Output is a .pg file in the same
directory that can be imported into any STK object with a great... |
import os
import torch
from tqdm.std import tqdm
from SRDataset import SRDataset
from SR_parser import parameter_parser
from tqdm import tqdm
from utils import save_result_pic
from models.HidingRes import HidingRes
opt = parameter_parser()
stage = "IniStage"
dataset_dir = "/home/ay3/houls/watermark_dataset/derain/"
... |
#!/usr/bin/env python
import os
import shutil
import sys
# Check if directory to be cleanup provided in command line arguments
# Else take current command line path as a default root directory path
if len(sys.argv) > 1:
rootDir = sys.argv[1]
else:
rootDir = os.getcwd()
# Defined directory to be removed
rmDir... |
import sys
import argparse
import RPi.GPIO as GPIO
import txaio
txaio.use_twisted()
from twisted.internet import reactor
from twisted.internet.defer import inlineCallbacks
from twisted.internet.task import LoopingCall
from twisted.internet.error import ReactorNotRunning
from autobahn import wamp
from autobahn.wamp.... |
'''
3.8.3 Common Permutation
PC/UVa IDs: 110303/10252, Popularity: A, Success rate: average
'''
import collections
def commonPermutation(s1, s2):
c1 = collections.Counter(s1)
c2 = collections.Counter(s2)
p = {}
for i in c1:
if i in c2:
if c1[i] < c2[i]:
p[i] = c1[i... |
import os
import plistlib
import sqlite3
from scripts.artifact_report import ArtifactHtmlReport
from scripts.ilapfuncs import logfunc, logdevinfo, tsv, is_platform_windows
def get_dataArk(files_found, report_folder, seeker):
data_list = []
file_found = str(files_found[0])
with open(file_found, "rb") as f... |
import requests
import json
import time
import sys
import os
def Salad_Earnings():
sys.stdout.write("\x1b]2;Downloading History\x07")
headers = {
"User-Agent": 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko)'
' Salad/0.4.0 Chrome/78.... |
import json
import sys
import os
import contextlib
from subprocess import Popen
from subprocess import check_output
from subprocess import PIPE
from toolz import first, filter, last
from .container import Container
from .utils import indent
from .utils import TemporaryDirectory
@contextlib.contextmanager
def cd(path)... |
# This module is automatically generated by autogen.sh. DO NOT EDIT.
from . import _Programming
class _Framework(_Programming):
_type = "framework"
_icon_dir = "resources/programming/framework"
class Angular(_Framework):
_icon = "angular.png"
class Backbone(_Framework):
_icon = "backbone.png"
c... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.