text stringlengths 3.07k 12.6k |
|---|
# GNU MediaGoblin -- federated, autonomous media hosting
# Copyright (C) 2011, 2012 MediaGoblin contributors. See AUTHORS.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either versio... |
import logging
import numpy as np
import torch
from detectron2.data import transforms as T
from detectron2.data.detection_utils import transform_instance_annotations as d2_transform_inst_anno
from detectron2.data.detection_utils import annotations_to_instances as d2_anno_to_inst
from detectron2.structures import BoxM... |
# coding: utf-8
## Function used to clean and pre-process dataset
## required modules
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import datetime as dt
def step_clean(dat):
""" Step1: data cleaning before further processing"""
dat = dat[pd.notnull(dat['CustomerID'])]
dat = dat[... |
#########################################################################
#
# Copyright 2011-2012 <NAME>
# Copyright 2008-2009 VMware, Inc.
# All Rights Reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to d... |
"""Unit tests for the `nc-time-axis.NetCDFTimeDateLocator` class."""
from __future__ import (absolute_import, division, print_function)
from six.moves import (filter, input, map, range, zip) # noqa
import unittest
import matplotlib.style
import matplotlib.dates as mdates
import cftime
import numpy as np
from nc_ti... |
import BeeVeeH.bvh as BVHLIB
import math
import copy
import numpy as np
from collections import Iterable
class BVHChannel(object):
ChannelTransformMatrixMap = {
'Xposition': lambda x: np.array([[1, 0, 0, x],
[0, 1, 0, 0],
... |
from zulip_bots.test_lib import BotTestCase, DefaultTests, StubBotHandler, read_bot_fixture_data
from simple_salesforce.exceptions import SalesforceAuthenticationFailed
from contextlib import contextmanager
from unittest.mock import patch
from typing import Any, Dict, Iterator
@contextmanager
def mock_salesforce_quer... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import... |
# coding: utf-8
# /*##########################################################################
#
# Copyright (c) 2020 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 deal
#... |
import os
os.environ['KMP_DUPLICATE_LIB_OK']='True'
import easyocr
import matplotlib.pyplot as plt # plt 用于显示图片
import re
from paddleocr import PaddleOCR, draw_ocr
import cv2 as cv
import numpy as np
import time
from collections import defaultdict
import json
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
keyw... |
import logging
import requests
import time
import os
import json
HEADER_CONTENT_TYPE = "Content-Type"
HEADER_VALUE_CONTENT_TYPE = "application/json"
HEADER_AUTHORIZATION = "Authorization"
#version 0.9.2.7
_LOGGER = logging.getLogger(__name__)
def _api_headers(access_token=None):
headers = {
... |
from tkinter import Button, END, Entry, Frame, Label, Menu, messagebox, Scrollbar, StringVar, Text, Tk
import sqlite3
# Función para conectar a la BBDD
def conecta_bbdd():
conexion = sqlite3.connect("usuarios")
cursor = conexion.cursor()
try:
cursor.execute('''
CREATE TABLE DATOS_USUAR... |
# Copyright 2016 The TensorFlow 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 applica... |
import json
from database import Block, engine, Session
import wallet_clustering
import pandas as pd
from flask import g
### Graph endpoints
def get_inputs_links(transactions_ids):
query = f"""
SELECT inputs.address, inputs.transaction_id
FROM inputs
WHERE inputs.t... |
# Copyright 2017-2021 Reveal Energy Services, Inc
#
# 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 applicab... |
#!/usr/bin/python3
#Create Index CADD
import json
import pandas as pd
import glob
import os,argparse
from glob import iglob
#################################################
############## Function wc -l #################
#################################################
def get_chunk_line_count(ranges):
name, s... |
"""Monitor and influence the optimization procedure via callbacks.
Callbacks are callables which are invoked after each iteration of the optimizer
and are passed the results "so far". Callbacks can monitor progress, or stop
the optimization early by returning `True`.
Monitoring callbacks
--------------------
* Verbos... |
import numpy as np
import torch
from scipy.spatial.distance import pdist
try:
from sklearn import linear_model, model_selection, preprocessing, pipeline, kernel_ridge
except ImportError as err:
print('Error importing sklearn {}. '
'You need to have sklearn installed to run qm7/9 example : '
'pi... |
#
# Copyright (c) 2020. <NAME> (<EMAIL>)
#
# 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
#
from queue import PriorityQueue
import scipy
fr... |
#!/usr/bin/python
"""
(C) Copyright 2020 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 ... |
import sys, os, subprocess, sysconfig
class CompilerError(Exception):
pass
class Compiler:
cc = None
cflags = None
ldflags = None
def __init__(self, verbose=0, env=None, forPython=True):
self.verbose, self.env = verbose, env
platform = self.setupPlatform(forPython)
self.pydext, self.oext, self.libex... |
import torch
import torch.optim as optim
from torch.optim.optimizer import Optimizer, required
class LARS(Optimizer):
"""
Layer-wise adaptive rate scaling
- Converted from Tensorflow to Pytorch from:
https://github.com/google-research/simclr/blob/master/lars_optimizer.py
- Based on:
https://git... |
#!/usr/bin/env python
###############################################################################
# Copyright 2017 The Apollo 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 ... |
import functools
import textwrap
import warnings
class MatplotlibDeprecationWarning(UserWarning):
"""
A class for issuing deprecation warnings for Matplotlib users.
In light of the fact that Python builtin DeprecationWarnings are ignored
by default as of Python 2.7 (see link below), this class was pu... |
# Copyright 2018 The Bazel 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 applicable law o... |
# -*- coding: utf-8 -*-
import logging
import os
from glob import glob
from pprint import pformat
from subprocess import check_output
import yaml
# Constants needed in scripts
CUSTOM_DIR = "/opt/odoo/custom"
AUTO_DIR = "/opt/odoo/auto"
ADDONS_DIR = os.path.join(AUTO_DIR, "addons")
SRC_DIR = os.path.join(CUSTOM_DIR, "... |
import numpy as np
from sklearn.neighbors import NearestNeighbors
from neat.config import ConfigParameter, write_pretty_params
import matplotlib.pyplot as plt
class DefaultNoveltySearchConfig(object):
"""
Sets up and holds configuration information for the DefaultNoveltySearch class.
"""
def __init__(... |
"""
A ``TokenEmbedder`` which uses one of the BERT models
(https://github.com/google-research/bert)
to produce embeddings.
At its core it uses Hugging Face's PyTorch implementation
(https://github.com/huggingface/pytorch-pretrained-BERT),
so thanks to them!
"""
import logging
import torch
from pytorch_pretrained_ber... |
import datetime
import PIL
import pytest
from jmm.crawlers import JavBooksCrawler
@pytest.mark.parametrize(
'number, metadata', [
(
'star-325',
{
'keywords': ['潮吹', '偶像艺人', '中出', '女检察官', '单体作品'],
'title': '美人潜入捜査官 羽田あい',
'release_date... |
#!/usr/bin/env python
"""Tests for `datawrangler` package (decorate module)."""
import os
import datawrangler as dw
import pandas as pd
import numpy as np
# noinspection PyTypeChecker
def test_list_generalizer():
@dw.decorate.list_generalizer
def f(x):
return x ** 2
assert f(3) == 9
assert ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import serial
import subprocess
import time
import yaml
import sys
from argparse import ArgumentParser
import logging
################################################################################
# Relay logic
################################################... |
'''
Imports from internal packages
'''
import random
'''
Imports from external packages
'''
import discord
import tenorpy
import wolframalpha
from discord.ext import commands
from discord.ext.commands import BucketType
tenor = tenorpy.Tenor()
class commands(commands.Cog):
def __init__(self, client):
self... |
#!/usr/bin/env python
# Copyright 2017 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 __future__ import print_function
import hashlib
import json
import os
import shutil
import subprocess
import sys
import tarfile
... |
import uuid
from cytoolz import (
merge,
)
from evm.db.backends.base import BaseDB
from evm.exceptions import ValidationError
class Journal(object):
"""
A Journal is an ordered list of checkpoints. A checkpoint is a dictionary
of database keys and values. The values are the "original" value of tha... |
import datetime
import math
import typing
from .. import spec
from .. import timelength_utils
from .. import timestamp_utils
def get_standard_timeperiod(
timelength_label: spec.TimelengthLabel = None,
*,
block_unit: typing.Optional[spec.DatetimeUnit] = None,
block_size: typing.Optional[int] = None,
... |
"""
Script used to create the test data in this directory.
"""
import os
import subprocess
import cdms2
class FileAndVars:
def __init__(self, remote_uri, local_uri, vars_to_keep, time_slice=()):
self.remote_uri = remote_uri
self.local_uri = local_uri
self.vars_to_keep = vars_to_keep
... |
import logging
from abc import ABC, abstractmethod
from typing import Dict, List, Optional, Set, Tuple, Type
from pycfmodel.model.cf_model import CFModel
from pycfmodel.model.resources.resource import Resource
from cfripper.config.config import Config
from cfripper.config.filter import Filter
from cfripper.config.rul... |
from __future__ import unicode_literals
from pygments.token import Token, Keyword, Name, Comment, String, Operator, Number
from pygments.style import Style
from pygments.styles import get_style_by_name, get_all_styles
from prompt_toolkit.styles import default_style_extensions, PygmentsStyle
from prompt_toolkit.utils i... |
# -*- coding: utf-8 -*-
"""
@author:XuMing(<EMAIL>)
@description:
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import CrossEntropyLoss
from ner.losses.focal_loss import FocalLoss
from ner.losses.label_smoothing import LabelSmoothingCrossEntropy
from .crf import CRF
from .linears... |
import time
#------------------------------------- Cliente -----------------------------------#
def Cliente():
#
pass
def getHoraCliente1():
#horaServidor = horaServer.split(' ') # guardo la hora del servidor en una lista
horaUTC = time.localtime() # se define horaUTC obteniendo la hora... |
from typing import Optional
import os
import collections
import logging
import threading
import shutil
import PIL.Image
import pygame
import anre
LOG = logging.getLogger(__name__)
FONT = None
RED = (255, 0, 0)
def calc_scale(src_width, src_height, dst_width, dst_height):
"""scale into max size but do not upsca... |
import bpy
import os
from math import pi,radians
import numpy as np
PATH2CMAPS = os.path.join( os.path.split(__file__)[0] , 'cmaps')
class MeshSingleColor(object):
def __init__(self, XYZ, CONN, color=(1,1,1), specular=0.2, alpha=1.0):
self.XYZ = XYZ
self.CONN = CONN
# self.mesh ... |
# -*- coding: utf-8 -*-
import json
from unittest import mock
from pyquery import PyQuery as pq
from olympia import amo
from olympia.access.models import Group, GroupUser
from olympia.amo.tests import TestCase, user_factory
from olympia.amo.urlresolvers import reverse
from olympia.files.models import File
from olymp... |
"""
Module contains all views for this extension package.
"""
import json
from django.shortcuts import render
from extensions.views import tab_extension, TabExtensionDelegate
from infrastructure.models import Server
from . import os_info_helpers
os_info_helpers.create_os_info_parameters_if_needed()
#
# All of th... |
import os
import zipfile
import calendar
from pathlib import Path
from glob import glob
import shapefile
from future.utils import lzip
from delphi.utils.shell import cd
from delphi.utils.web import download_file
from delphi.paths import data_dir
from tqdm import tqdm
import matplotlib as mpl
import pandas as pd
mpl.rc... |
"""Call this module `FuncNotify` to be able to time scripts as well as functions
To pass key word arguments, pass --kwargs followed by the arguments
Note compiling function time may be counted, which is why some timings may
appear to be innacurate
"""
import argparse
import subprocess
import ast
import re
from Fu... |
from collections import Iterator
from collections import defaultdict
from datetime import timedelta
import far_ho.examples.datasets as dts
from marthe import *
from marthe import AllPlaceholders
from tensorflow.examples.tutorials.mnist import input_data
import marthe.timit_main as tmm
class TimitCompExpConfig(Con... |
#!/usr/bin/python
# Copyright (c) 2014-2018 <NAME>
# All rights reserved.
#
# Redistribution and use in source and binary forms,
# with or without modification, are permitted provided
# that the following conditions are met:
#
# * Redistributions of source code must retain
# the above copyright notice, this list of ... |
# -*- coding: utf-8 -*-
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
__author__ = 'christoph.statz <at> tu-dresden.de'
import numpy as np
def compute_receiver_halo_location(mesh, halos, idx, sender):
halo_direction = np.asarray(idx)-np.asarray(se... |
import os
import sys
import re
import datetime
import socket
import traceback
from .WatchDogBase import WatchDogBase
from pandajedi.jedicore.MsgWrapper import MsgWrapper
from pandajedi.jedicore.ThreadUtils import ListWithLock, ThreadPool, WorkerThread
# logger
from pandacommon.pandalogger.PandaLogger import PandaLog... |
import matplotlib.pyplot as plt
import numpy as np
import torch
from torch import nn, Tensor
class SeqGenerator:
def __init__(self, model: nn.Module, record_intensity: bool = False):
self.model = model
self.process_dim = model.input_size - 1 # process dimension
print("Process model dim:\t... |
import re
import sys
ERRORS = {
'unexp_end_string': u'Unexpected end of string while parsing Lua string.',
'unexp_end_table': u'Unexpected end of table while parsing Lua string.',
'mfnumber_minus': u'Malformed number (no digits after initial minus).',
'mfnumber_dec_point': u'Malformed number (no digits... |
from gen.javaLabeled.JavaLexer import JavaLexer
try:
import understand as und
except ImportError as e:
print(e)
from antlr4 import *
from antlr4.TokenStreamRewriter import TokenStreamRewriter
from gen.javaLabeled.JavaParserLabeled import JavaParserLabeled
from gen.javaLabeled.JavaParserLabeledListener import... |
import shutil
import qdms
import numpy as np
def setup_save_load():
memristor = qdms.Data_Driven()
circuit = qdms.Circuit(memristor_model=memristor, number_of_memristor=4, is_new_architecture=True, v_in=1e-3,
gain_resistance=0, R_L=1)
pulsed_programming = qdms.PulsedProgrammi... |
#!/usr/bin/env python
import os
import sys
import json
import numpy as np
import matplotlib.pyplot as plt
from scipy.spatial import ConvexHull
import argparse
def spcgrp_props(space_group):
cst_marker = '.'
cst_color = '#000000'
cst_marker_size = 2
cst_zorder = 2
cst_fillstyle = 'full'
if spa... |
from rpython.rtyper.lltypesystem import lltype, rffi
from rpython.rlib.rarithmetic import widen
from rpython.rlib import rgc
from rpython.rlib.unroll import unrolling_iterable
#
from pypy.interpreter.error import OperationError, oefmt
from pypy.interpreter.baseobjspace import W_Root
from pypy.interpreter.gateway import... |
import numpy as np
from numpy.random import random_sample
# Simulated Binary Crossover (SBX)
def SBX(Parent_1, Parent_2, nvar, lb, ub):
n = 17
u = random_sample()
beta_1 = np.zeros(shape=[nvar])
beta_2 = np.zeros(shape=[nvar])
beta_u = np.zeros(shape=[nvar])
P_1 = np.zeros(shape=[nvar])
P... |
import paddle
import paddle.nn as nn
import paddle.nn.functional as F
from paddle import ParamAttr
from paddle.regularizer import L2Decay
from ppdet.core.workspace import register, serializable
from ppdet.modeling.ops import batch_norm
__all__ = ['DarkNet', 'ConvBNLayer']
class ConvBNLayer(nn.Layer):
def __init_... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
This Python module contains not only the class Pokemon, but also the test of
this Python class.
@contents : This module contains not only a single Python class, but also the
test cases to probe its functionality.
@project : N/A
@program : N/A
@file : ... |
from Burger import *
from plotting import *
# dns defaults
L = 2*np.pi
tEnd = 5
basis = 'hat'
def setup_dns_default(N, dt, nu , ic, forcing, seed):
print("Setting up default dns with args ({}, {}, {}, {}, {}, {})".format(N, dt, nu, ic, forcing, seed))
dns = Burger(L=L, N=N, dt=dt, nu=nu, tend=tEnd, case=i... |
from amadeus import Client as amadeus_Client
from src.backend.config import ConfigFunctions
from googlemaps import Client as gmaps_Client
from datetime import timedelta, date
from pprint import pprint
config = ConfigFunctions()
def get_driving_to_resort_data_from_api(resort):
cli = _get_gmaps_client()
resort... |
from django.shortcuts import get_object_or_404
from rest_framework.decorators import api_view, permission_classes
from rest_framework.pagination import PageNumberPagination
from rest_framework.permissions import AllowAny, IsAuthenticated
from rest_framework.response import Response
from rest_framework import viewsets
f... |
"""Support for Huawei LTE sensors."""
import logging
import re
import attr
import voluptuous as vol
from homeassistant.const import (
CONF_URL, CONF_MONITORED_CONDITIONS, STATE_UNKNOWN,
)
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.helpers.entity import Entity
import homeassista... |
from __future__ import absolute_import, division, print_function
from six.moves import range
import math
import scitbx.math
from scitbx import lbfgs
from scitbx.array_family import flex
class fit_cdf(object):
"""
=============================================================================
Class fits a distribut... |
import glob
import os
import pickle
import random
import numpy as np
import cv2
import torch
class BaseLoader(torch.utils.data.Dataset):
def __init__(self, triplets, transform=None, resz=None):
self.triplets = triplets
self.transform = transform
self.resz = resz
def __getitem__(self, ... |
#
# Copyright (c) 2021 Airbyte, Inc., all rights reserved.
#
import linecache
import os
import random
import sys
import tracemalloc
from abc import ABC, abstractmethod
from datetime import datetime, timedelta
from functools import lru_cache, wraps
from typing import Any, Callable, List, Mapping
import pytest
from air... |
#!/usr/bin/env python
# Copyright (c) 2021 CRS4
#
# 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, ... |
# 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... |
# STDLIB
import logging
import platform
import signal
import sys
import threading
from types import FrameType
from typing import Any, Callable, Dict, List, Type, Union
# EXT
import dill # type: ignore
import multiprocess # type: ignore
logger = logging.getLogger('pickle_analyzer')
class WrapHelper(o... |
# coding=utf-8
# Copyright 2022 The Google Research 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 applicab... |
import timeago
import datetime
from datetime import timezone
from doing.utils import run_command, get_repo_name, replace_user_aliases, validate_work_item_type
from rich.table import Table
from rich.live import Live
from rich.progress import track
from rich.console import Console
from typing import List, Dict
console... |
import asyncio
import aiohttp
import requests
from rest_framework import status
from presqt.targets.curate_nd.utilities import get_curate_nd_resource, extra_metadata_helper
from presqt.targets.curate_nd.classes.main import CurateND
from presqt.utilities import (PresQTInvalidTokenError, PresQTValidationError,
... |
from uuid import uuid4
from graph import Graph
__all__ = ['ap_solver', 'wtap_solver']
def ap_solver(graph):
"""
ASSIGNMENT PROBLEM
Definition:
The problem instance has a number of agents and a number of tasks.
Any agent can be assigned to perform any task, incurring some cost that may
var... |
# -*- coding: utf-8 -*-
"""Pibooth language handling.
"""
import io
import os
import os.path as osp
from pibooth.utils import LOGGER, open_text_editor
try:
from configparser import ConfigParser
except ImportError:
# Python 2.x fallback
from ConfigParser import ConfigParser
PARSER = ConfigParser()
CURRE... |
"""opcode_decoding.py - Tools for working with opcodes and opcode values
"""
# Reads and parses a text file containing a list of opcodes and their
# textual "nice names". For opcodes that have specific / discrete value
# settings, the values and textual "nice names" for each are included.
# Once the file is parsed, the... |
import urllib
import time
from facetools import json
from django.conf import settings
from facetools.common import _get_app_access_token, _create_permissions_string
from facetools.models import TestUser
import requests
class CreateTestUserError(Exception): pass
class DeleteTestUserError(Exception): pass
class NotATes... |
from enum import Enum
from typing import List, Optional, Union
from dataclasses import dataclass
from bs4 import Tag, NavigableString
from yarl import URL
import re
import libkol
from ..util import parsing
from ..Error import InvalidActionError, UnknownError, NotFightingError
from ..Skill import Skill
from ..Monster ... |
# Copyright (c) 2021 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 appli... |
import datetime
import json
from unittest.mock import MagicMock
import pytest
import yaml
from datacube.utils import geometry as geom
from odc.index._grouper import group_by_nothing, key2num, mid_longitude, solar_offset
from odc.index._index import (
month_range,
parse_doc_stream,
product_from_yaml,
s... |
"""
Every night, the virus spreads to all neighboring cells in all four
directions unless blocked by a wall. Resources are limited. Each day,
you can install walls around only one region -- the affected area
(continuous block of infected cells) that threatens the most
uninfected cells the following ... |
import torch
import torch.nn as nn
import torch.nn.utils.rnn as rnn_utils
from pytorch_pretrained_bert import BertModel
class TaggerBERT(nn.Module):
"""
BERT-based tagger
'BERT: Pre-training of Deep Bidirectional Transformers for
Language Understanding' (Devlin et al. 2019)
https://arxiv.org/abs/... |
"""
---------------------------------------------------------------------------------------------------
Author:
<NAME> 18676
---------------------------------------------------------------------------------------------------
"""
from numpy import pi
def relative(user_input, input_low, input_high, output_high, outp... |
#!/usr/bin/env python
"""Clones all the repositories from the specified GitHub organizations.
After cloning to the destination specified, an archive is created and moved
to a final destination which is backed up. Credentials needs to be given,
and private repositories can only be cloned if the user has access... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
import time
import pandas as pd
import random
import os.path
from pysc2.agents import base_agent
from pysc2.lib import actions
from pysc2.lib import features
_PLAYER_SELF = features.PlayerR... |
import math
from dataclasses import dataclass
from typing import Dict, Optional
from vyper import ast as vy_ast
from vyper.address_space import MEMORY
from vyper.codegen.ir_node import Encoding
from vyper.codegen.types import NodeType, parse_type
from vyper.exceptions import StructureException
from vyper.utils import ... |
import json
import os
import datetime
from flask import Blueprint
from flask import flash
from flask import redirect
from flask import render_template
from flask import url_for
from flask import current_app
from flask import request
from flask_login import current_user
from flask_login import login_required
from flask_... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import pathlib
import unetsl.cerberus
import unetsl.model
import unetsl.masker
import numpy
import click
def guessShaper(key):
"""
REDUNDANT see unetsl.cerberus.__main__
"""
kl = key.lower()
if "crop" in kl:
return "crop"
... |
import numpy as np
import miepy
from sympy.physics.wigner import wigner_3j, gaunt
from scipy import special
import math
from functools import lru_cache
# w = miepy.vsh.wigner_3j(1,1,1, 1,-1,0)
# print(w)
# w = wigner_3j(1,1,1,1,-1,0)
# print(w)
# from IPython import embed; embed()
@lru_cache(None)
def gaunt(m,n,u,v,p... |
#!/usr/bin/env python3
import numpy as np
import math
import torch
import torch.nn.functional as F
from torch import nn
def create_src_lengths_mask(batch_size, src_lengths):
max_srclen = src_lengths.max()
src_indices = torch.arange(
0,
max_srclen,
).unsqueeze(0).type_as(src_lengths)
... |
#
# 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... |
try:
import Crypto
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
from Crypto import Random
except:
import crypto as Crypto
from crypto.PublicKey import RSA
from crypto.Cipher import PKCS1_OAEP
from crypto import Random
import os
import base64
import hashlib
class RSA_Local:
def __init... |
#!/usr/bin/env python3
# vim: set fileencoding=utf-8 :
"""Implements a very basic version of LSTM."""
import torch
import torch.nn as nn
from torch.autograd import Variable
class LstmCell(nn.Module):
"""
A reimplementation of the LSTM cell. It takes 176s to run the time
sequence prediction example; the b... |
"""
Wrapper of the bridge-like integrator for amuse. To see how bridge works go to the file bridge.py in this folder.
This bridge makes the integration of eqs of motion in a right hand counterclockwise rotating system.
Usage:
from amuse.ext.composition_methods import *
from amuse.ext.rotating_bridge import Rotating_B... |
"""
@<NAME> (<EMAIL>)
Licensed under Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International (https://creativecommons.org/licenses/by-nc-sa/4.0/legalcode)
"""
from __future__ import print_function, division, absolute_import
import math
import numpy as np
def get_phi_theta_from_euler(euler_angles):
... |
# Copyright 2021 Google LLC
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
import argparse
import torch
from torch import nn
from torch import optim
from torch.autograd import Variable
from torchvision import datasets, transforms, models
from torchvision.datasets import ImageFolder
import torch.nn.functional as F
from PIL import Image
from collections import OrderedDict
import time
import num... |
"""Start a hyperoptimization from a single node"""
import sys
import numpy as np
import pickle as pkl
import hyperopt
from hyperopt import hp, fmin, tpe, Trials
import pysr
import time
import contextlib
@contextlib.contextmanager
def temp_seed(seed):
state = np.random.get_state()
np.random.seed(seed)
try... |
import binascii
import datetime as dt
import hashlib
import logging
import sys
from typing import Generator, Union
from contextlib import contextmanager
from io import TextIOWrapper
import attr
import pytz
from regipy.exceptions import NoRegistrySubkeysException, RegistryKeyNotFoundException, RegipyGeneralExceptio... |
"""Support for a ScreenLogic Sensor."""
from screenlogicpy.const import (
CHEM_DOSING_STATE,
DATA as SL_DATA,
DEVICE_TYPE,
EQUIPMENT,
)
from homeassistant.components.sensor import (
SensorDeviceClass,
SensorEntity,
SensorStateClass,
)
from homeassistant.config_entries import ConfigEntry
fro... |
#
# Copyright (c) <NAME>, http://hgtfshook.codeplex.com
#
# This software may be used and distributed under the
# Microsoft Public License (Ms-PL).
#
from ntlm import HTTPNtlmAuthHandler
from xml.sax.saxutils import escape
import xml.etree.ElementTree as et
from datetime import datetime
import re, httplib, uuid, urlli... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.