text stringlengths 3.07k 22.1k |
|---|
#!/usr/bin/python
"""
FAOSTAT:
-------
Reads FAOSTAT JSON and creates datasets.
"""
import logging
from datetime import datetime, timedelta
from os import remove, rename
from os.path import basename, exists, getctime, join
from urllib.parse import urlsplit
from zipfile import ZipFile
from hdx.data.dataset import Da... |
import copy
import itertools
import wsgiref.util
from oslo_config import cfg
from oslo_log import log
from oslo_serialization import jsonutils
from oslo_utils import importutils
import routes.middleware
import six
import webob.dec
import webob.exc
from wsgi_basic import exception
from wsgi_basic.common import authori... |
#!/usr/bin/env python3
# Usage: python SESGenerator.py <target_configuration>.json <output_directory>
#
# <target_configuration>.json is a json file generated from CMake on the form:
# {
# "target": {
# "name": "light_control_client_nrf52832_xxAA_s132_5.0.0",
# "sources": "main.c;provisioner.c;..",... |
"""
This script contains the code implementing my version of the Boids artificial
life programme.
"""
# ---------------------------------- Imports ----------------------------------
# Allow imports from parent folder
import sys, os
sys.path.insert(0, os.path.abspath('..'))
# Standard library imports
impor... |
#!/usr/bin/env python3
import collections
import datetime
import glob
import html
import re
import sys
# this is a mess right now, feel free to make it less bad if you feel like it
try:
# python 3.7+
datetime.datetime.fromisoformat
except AttributeError:
# not fully correct, but good enough for this use case
adjt... |
'''Disciplina: Programação I
Trabalho prático ano lectivo 2013/2014
Realizado por <NAME> (29248) e <NAME> (31511)
'''
class Village:
# Constructor method
# Used to create a new instance of Village, taking in arguments like
# its size and population, then builds the board used throughout the
# program
... |
from django.core.exceptions import ValidationError
from django.core.validators import FileExtensionValidator
from django.core.files.uploadedfile import InMemoryUploadedFile
from django.forms import Form, ModelForm, FileInput
from django.forms.fields import *
from captcha.fields import CaptchaField
from .models import ... |
import os
import cv2
import numpy as np
import matplotlib.pyplot as plt
def Compute_Block(cell_gradient_box):
k=0
hog_vector = np.zeros((bin_size*4*(cell_gradient_box.shape[0] - 1)*(cell_gradient_box.shape[1] - 1)))
for i in range(cell_gradient_box.shape[0] - 1):
for j in range(cell_gradient... |
import urllib
import json
import requests
from bs4 import BeautifulSoup
import pandas as pd
import re
import string
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer
from nltk.stem.porter import PorterStemmer
def getpage(num):
url = "https://forums.eveonline.com/c/marketplace/... |
# Data processing imports
import scipy.io as io
import numpy as np
from pyDOE import lhs
# Plotting imports
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
from scipy.interpolate import griddata
import matplotlib.gridspec as gridspec
def load_dataset(file):
data = io.loadma... |
import argparse
import importlib
import os
import sys
import jsonschema
import pkg_resources
from multiprocessing import Pool, cpu_count
from pyneval.errors.exceptions import InvalidMetricError, PyNevalError
from pyneval.pyneval_io import json_io
from pyneval.pyneval_io import swc_io
from pyneval.metric.utils import a... |
import numpy as np
import scipy.sparse as sp
import Orange.data
from Orange.statistics import distribution, basic_stats
from Orange.util import Reprable
from .transformation import Transformation, Lookup
__all__ = [
"ReplaceUnknowns",
"Average",
"DoNotImpute",
"DropInstances",
"Model",
"AsValu... |
#!/usr/bin/env python
# -*- coding: utf-8 -*
"""
tools module
"""
__author__ = 'Dr. <NAME>, University of Bristol, UK'
__maintainer__ = 'Dr. <NAME>'
__email__ = '<EMAIL>'
__status__ = 'Development'
import sys
import os
import copy
import numpy as np
try:
import opt_einsum as oe
OE_AVAILABLE = True
except Imp... |
from unittest.mock import patch, MagicMock, call
import json
from datetime import datetime
from copy import deepcopy
import pytest
from PIL import Image
from sm.engine import DB, ESExporter, QueuePublisher
from sm.engine.dataset_manager import SMapiDatasetManager, SMDaemonDatasetManager
from sm.engine.dataset_manager ... |
"""
A module for a mixture density network layer
(_Mixture Desity Networks_ by Bishop, 1994.)
"""
import sys
import torch
import torch.tensor as ts
import torch.nn as nn
import torch.optim as optim
from torch.distributions import Categorical
import math
# Draw distributions
import numpy as np
import matplotlib.pyplot ... |
'''
Aqui o programa conterá uma função que permite
listar tanto diretórios, como arquivos na forma de
árvores, ou seja, seus ramos terão linhas, e também,
espaçamentos mostrando a profundidade de cada diretório
dado uma pasta raíz.
'''
#só pode ser importado:
__all__ = ['arvore']
# ********* bibliotecas ... |
import datetime
import os
from dataclasses import dataclass, field
from operator import attrgetter
from typing import List, Dict, Optional, cast, Set
from tarpn.ax25 import AX25Call
from tarpn.netrom import NetRomPacket, NetRomNodes, NodeDestination
from tarpn.network import L3RoutingTable, L3Address
import tarpn.net... |
#! /usr/bin/env python
# Copyright (c) 2018 - 2019 <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
#
# Unless required by appl... |
import attr
from attr import attrib, s
from typing import Tuple, List, Optional, Callable, Mapping, Union, Set
from collections import defaultdict
from ..tensor import Operator
@attr.s(auto_attribs=True)
class GOp:
cost : float
size : Tuple[int]
alias : Tuple[int]
args : Tuple['GTensor']
result ... |
import numpy as np
import random
import numexpr as ne
def gen_layer(rin, rout, nsize):
R = 1.0
phi = np.random.uniform(0, 2*np.pi, size=(nsize))
costheta = np.random.uniform(-1, 1, size=(nsize))
u = np.random.uniform(rin**3, rout**3, size=(nsize))
theta = np.arccos( costheta )... |
import obj as obj_lib
import road_artifact
import drive as drive_lib
import utilities as u
class Sensor(obj_lib.Obj):
"""
parent object class for car sensors
returns instruction
driving instruction - (heading, speed)
no driving instruction (no new process or process has completed) - None
... |
# -*- coding: utf-8 -*-
import json
import threading
import time
from abc import abstractmethod
from typing import Optional
from dmtp.mtp import tlv
from dmtp import mtp
import dmtp
import stun
from .manager import ContactManager, FieldValueEncoder, Session
def time_string(timestamp: int) -> str:
time_array = ... |
from math import pi
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from scipy.optimize import minimize_scalar
__author__ = "<NAME>"
__credits__ = ["<NAME>"]
__maintainer__ = "<NAME>"
__email__ = "<EMAIL>"
__version__ = "0.1"
__license__ = "MIT"
# gravitational acceleration
g = 9.81 # m/s²
#... |
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 17 09:36:07 2015
@author: Ben
"""
from shared_classes import Stock, StockItem, SpecifiedStock
from datamapfunctions import DataMapFunctions, Abstract
import util
import numpy as np
import config as cfg
class SupplyStock(Stock, StockItem):
def __init__(se... |
import numpy as np
import networkx as nx
import argparse
import random
from models.distance import get_dist_func
def get_fitness(solution, initial_node, node_list):
"""
Get fitness of solution encoded by permutation.
Args:
solution (numpy.ndarray): Solution encoded as a permutation
ini... |
'''
Analytic Hierarchy Process, AHP.
Base on Wasserstein distance
'''
from scipy.stats import wasserstein_distance
from sklearn.decomposition import PCA
import scipy
import numpy as np
import pandas as pd
import sys
import argparse
import os
import glob
import datasets_analysis_module as dam
class idx_analysis(obje... |
""" Copyright 2016-2022 by Bitmain Technologies 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 by applica... |
"""The implementation of U-Net and FCRN-A models."""
from typing import Tuple
import numpy as np
import torch
from torch import nn
from torchvision.models import resnet
from model_config import DROPOUT_PROB
class UOut(nn.Module):
"""Add random noise to every layer of the net."""
def forward(self, input_te... |
#Dependencies, libraries, and imports
from matplotlib import style
style.use('fivethirtyeight')
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import datetime as dt
#SQLalchemy libraries and functions
import sqlalchemy
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import S... |
"""
Tools for calculations
"""
import warnings
from aiida.tools import CalculationTools
from aiida.common import InputValidationError
from aiida.orm import CalcJobNode, Dict
from aiida.common.links import LinkType
from aiida.plugins import DataFactory
from aiida.engine import CalcJob, ProcessBuilder
from aiida_castep... |
import cv2
OPENCV_OBJECT_TRACKERS = {
"csrt": cv2.TrackerCSRT_create,
"kcf": cv2.TrackerKCF_create,
"mil": cv2.TrackerMIL_create
}
class Track:
"""
Seguimiento de una persona
"""
def __init__(self, tracker_name, first_frame, bbox, id, references):
self._tracker... |
#
# Copyright 2021 Ocean Protocol Foundation
# SPDX-License-Identifier: Apache-2.0
#
import logging
import lzma
from hashlib import sha256
from typing import Optional, Tuple
from eth_typing.encoding import HexStr
from flask import Response, request
from flask_sieve import validate
from ocean_provider.requests_session ... |
"""MongoDB instance classes and logic."""
import datetime
import json
import logging
import time
import pymongo
import requests
from concurrent import futures
from distutils.version import LooseVersion
from objectrocket import bases
from objectrocket import util
logger = logging.getLogger(__name__)
class MongodbI... |
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import NoSuchElementException, TimeoutException
from enum import Enum
import re
import os
f... |
################################################################################
#
# Provide embeddings from raw audio with the wav2vec2 model from huggingface.
#
# Author(s): <NAME>
################################################################################
from typing import Optional, List
import torch as t
im... |
# Copyright 2013 <NAME>
#
# 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 writing, software
... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
range = getattr(__builtins__, 'xrange', range)
# end of py2 compatability boilerplate
import numpy as np
from matrixprofile import core
from ma... |
# -*- coding: utf-8 -*-
"""
Make figures for MUSim paper
AUTHOR: <NAME>
VERSION DATE: 26 June 2019
"""
import os
from os.path import join
import numpy as np
import pandas as pd
from statsmodels.stats.proportion import proportion_confint
import matplotlib.pyplot as plt
def binom_ci_precision(proporti... |
# %%
import matplotlib.pyplot as plt
import numpy as np
import sklearn
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader
from model.inceptionv4 import inceptionv4
from model.mobilenetv2 import mobilenetv2
from model.resnet import resnet18
from model.shufflenetv2 imp... |
import numpy as np
import json
import re
from Utils import *
np.random.seed(4)
def output_process(example):
state = e['state'][-1]
if type(state) == str:
return state
else:
return ' '.join(state)
def polish_notation(steps):
step_mapping = {}
for ix, s in enumerate(steps):
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
wz_table/spreadsheet_make.py
Last updated: 2019-10-14
Create a new spreadsheet (.xlsx).
=+LICENCE=============================
Copyright 2017-2019 <NAME>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in comp... |
# fits better in a StyleGAN or small network implementation, but provides a good
# proof of concept (especially for things like fashion MNIST)
import tensorflow as tf
from .utils import Conv2D as SpecializedConv2D
def nslice(rank, dim):
start = tuple(slice(None) for i in range(dim))
end = tuple(slice(None) for... |
import unittest
import datetime
import genetic
import random
class Node:
Value = None
Left = None
Right = None
def __init__(self, value, left=None, right=None):
self.Value = value
self.Left = left
self.Right = right
def isFunction(self):
return self.Left is not No... |
from .peg import *
# # PRange Utilities
def bitsetRange(chars, ranges):
cs = 0
for c in chars:
cs |= 1 << ord(c)
r = ranges
while len(r) > 1:
for c in range(ord(r[0]), ord(r[1])+1):
cs |= 1 << c
r = r[2:]
return cs
def stringfyRange(bits):
c = 0
s = N... |
# Copyright 2019 Systems & Technology Research, LLC
# Use of this software is governed by the license.txt file.
import os
import numpy as np
import torch
import torch.nn as nn
import torchvision.transforms as transforms
import torch.nn.functional as F
from PIL import ImageFilter
def prepare_vggface_image(img):
... |
import logging
import os
import json
from collections import namedtuple
from opentrons.config import get_config_index
FILE_DIR = os.path.abspath(os.path.dirname(__file__))
log = logging.getLogger(__name__)
def pipette_config_path():
index = get_config_index()
return index.get('pipetteConfigFile', './setting... |
# Copyright (C) 2019 <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>,
# <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>,
# <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>,
# <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>,
# <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>,
# <NAME>, <NAME>
#
# This file is pa... |
# -*- coding: utf-8 -*-
# Copyright 2016 Yelp 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 applicable law or ag... |
# Copyright (c) Meta Platforms, Inc. and affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
import copy
import json
import os
from typing import Any, Dict, List, Optional, Sequence
from iopath.common.f... |
import os
import glob
from tqdm import tqdm
import argparse
from PIL import Image
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
import torch.utils.data as data
from torchvision import transforms, datasets
from networks.dan import DAN
def parse_args():
parser = argparse.ArgumentParse... |
# Copyright (c) 2018 The Pooch Developers.
# Distributed under the terms of the BSD 3-Clause License.
# SPDX-License-Identifier: BSD-3-Clause
#
# This code is part of the Fatiando a Terra project (https://www.fatiando.org)
#
# pylint: disable=redefined-outer-name
"""
Test the hash calculation and checking functions.
""... |
# add LDDMM shooting code into path
import sys
sys.path.append('../vectormomentum/Code/Python');
sys.path.append('../library')
from subprocess import call
import argparse
import os.path
#Add deep learning related libraries
from collections import Counter
import torch
import prediction_network
import util
import numpy... |
"""
socat - UNIX-CONNECT:repl.sock
import sys, threading, pdb, functools
def _attach(repl):
frame = sys._current_frames()[threading.enumerate()[0].ident]
debugger = pdb.Pdb(
stdin=repl.conn.makefile('r'),
stdout=repl.conn.makefile('w'),
)
debugger.reset()
while frame:
frame... |
import torch
import pickle
import argparse
import os
from tqdm import trange, tqdm
import torch
import torchtext
from torchtext import data
from torchtext import datasets
from torch import nn
import torch.nn.functional as F
import math
from models import SimpleLSTMModel, AttentionRNN
from train_args import get_arg_par... |
"""Helper functions and classes for users.
They should not be used in skorch directly.
"""
from collections import Sequence
from collections import namedtuple
from functools import partial
import numpy as np
from sklearn.base import BaseEstimator
from sklearn.base import TransformerMixin
import torch
from skorch.cl... |
"""
"""
import re
from collections import namedtuple
from functools import lru_cache
from lexref.model import Value
__all__ = ['ListItemsAndPatterns']
romans_pattern = Value.tag_2_pattern('EN')['ROM_L'].pattern.strip('b\\()')
_eur_lex_item_patterns_en = { # key: (itemization-character-pattern, ordered [bool], fi... |
#!/usr/bin/env python3
# Copyright 2018-2019 <NAME>
# Copyright 2020-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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Un... |
import re
import lxml.html
import click
import scrapelib
from common import Person
def elem_to_str(item, inside=False):
attribs = " ".join(f"{k}='{v}'" for k, v in item.attrib.items())
return f"<{item.tag} {attribs}> @ line {item.sourceline}"
class XPath:
def __init__(self, xpath, *, min_items=1, max_i... |
"""
Train a model on the Reddit dataset by Khodak.
"""
import functools
import time
import logging
import pickle
import os
import pandas as pd
from sklearn.model_selection import train_test_split
from simpletransformers.classification import ClassificationModel, ClassificationArgs
from utils import (
hour_min_se... |
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import MultipleLocator
from tqdm import tqdm
import torch
from torch.utils.data import DataLoader
import torch.nn.functional as F
from model.model import BaseNet
from model.config import arguments
from dataset.dataset import FlowerData
def ge... |
import logging
import uuid
from typing import Any
import pytest
import requests
import test_helpers
from dcos_test_utils import marathon
from dcos_test_utils.dcos_api import DcosApiSession
__maintainer__ = 'kensipe'
__contact__ = '<EMAIL>'
log = logging.getLogger(__name__)
def deploy_test_app_and_check(dcos_api_... |
#!/usr/bin/env python3.5
import sys
import os
import logging
import numpy as np
import musm
from sklearn.utils import check_random_state
from textwrap import dedent
#1Social Choice
_LOG = musm.get_logger('adt17')
PROBLEMS = {
'synthetic': musm.Synthetic,
'pc': musm.PC,
}
USERS = {
'noiseless': musm.Noi... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for delta functions."""
from unittest import TestCase
from hiispider import delta
from pprint import pprint
import os
import random
import time
from datetime import datetime
from hiiguid import HiiGUID
srt = lambda l: list(sorted(l))
DATAPATH = os.path.abspath(... |
# -*- coding: utf-8 -*-
# Copyright 2013-2014 Eucalyptus Systems, Inc.
#
# Redistribution and use of this software 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... |
""" This module contains a number of useful math related functions that are used throughout this project """
from __future__ import annotations
import math
from typing import List, Union, Tuple
from deprecated import deprecated # type: ignore
AnyNumber = Union[int, float]
FloatIterable = Union[List[float], Tuple[flo... |
# -*- coding: utf-8 -*-
# *****************************************************************************
# NICOS, the Networked Instrument Control System of the MLZ
# Copyright (c) 2009-2021 by the NICOS contributors (see AUTHORS)
#
# This program is free software; you can redistribute it and/or modify it under
# the t... |
import subprocess
from os import system, remove, chdir
from tabulate import tabulate
def edges(n):
location = 0
edges = [[0,n-1]]
for i in range(n-1):
edges.append([location, location+1])
location += 1
return edges
def cut(state, edges):
cut = 0
for edge in edges:
cut += 1 if state[edge[0]] == state[ed... |
"""
Mask R-CNN
Train on the toy Balloon dataset and implement color splash effect.
Copyright (c) 2018 Matterport, Inc.
Licensed under the MIT License (see LICENSE for details)
Written by <NAME>
------------------------------------------------------------"""
import os
import sys
import json
import numpy as... |
"""
Collection of functions to calculate lag correlations
and significance following Ebisuzaki 97 JCLIM
"""
def phaseran(recblk, nsurr,ax):
""" Phaseran by <NAME>: http://www.mathworks.nl/matlabcentral/fileexchange/32621-phase-randomization/content/phaseran.m
Args:
recblk (2D array): Row: time sample.... |
import unittest
import numpy as np
import torch
from torch import optim
from spn.structure.Base import Product, Sum
from spn.structure.Base import assign_ids, rebuild_scopes_bottom_up
from spn.structure.leaves.parametric.Parametric import Gaussian, Categorical
from spn.gpu.TensorFlow import spn_to_tf_graph, optimize_... |
"""
Validate CAL DAC settings XML files. The command line is:
valDACsettings [-V] [-r] [-R <root_file>] [-L <log_file>] FLE|FHE|LAC|ULD <MeV | margin> <dac_slopes_file> <dac_xml_file>
where:
-r = generate ROOT output with default name
-R <root_file> = output validation diagnostics in ROOT... |
import os
import re
import warnings
from uuid import uuid4, UUID
import shapely.geometry
import geopandas as gpd
import pandas as pd
import numpy as np
from geojson import LineString, Point, Polygon, Feature, FeatureCollection, MultiPolygon
try:
import simplejson as json
except ImportError:
import json
from ... |
import random
import logging
import numpy as np
import tensorflow as tf
class DeepQNetworkModel:
def __init__(self,
session,
layers_size,
memory,
default_batch_size=None,
default_learning_rate=None,
default_epsil... |
import tensorflow as tf
import numpy as np
import resnet_block
def LeakyRelu(x, leak=0.2, name="LeakyRelu"):
with tf.variable_scope(name):
leak_c = tf.constant(0.1)
leak = tf.Variable(leak_c)
f1 = 0.5 * (1 + leak)
f2 = 0.5 * (1 - leak)
return f1 * x + f2 * tf.abs(x)
def... |
from functools import partial
from keyword import iskeyword
from typing import Tuple, Final, Callable, Any, List, Generator, NoReturn, Dict
from chained.type_utils.meta import ChainedMeta
def _call_monkey_patcher(self, *args, **kwargs):
"""LambdaExpr.__call__ monkey patcher"""
return self.eval()(*args, **kwa... |
import re, os, copy
PAREMETER_PATTERN = '{{%s}}'
def convert_value_for_environment(value: object) -> str:
if str(value).lower() == 'true': value = '1'
elif str(value).lower() == 'false': value = '0'
return str(value)
def set_environment_variables(environs:dict):
if environs:
for key, value in... |
from pathlib import Path
import os
import re
from decimal import Decimal
import csv
import numpy
from Utils import TextProcessingUtils
from Utils import DefinedConstants
def readEmbeddingsFromTxtFile(inFile):
w2v = {}
with open(inFile, "r") as f:
for l in f.readlines():
if not l.strip():
... |
import six
import time
import signal
import multiprocessing
from functools import partial
import numpy as np
from astropy.utils.console import (_get_stdout, isatty, isiterable,
human_file_size, _CAN_RESIZE_TERMINAL,
terminal_size, color_print, human... |
import os
from flask import Blueprint, request, jsonify
from math import exp
bp = Blueprint('app', __name__)
MODEL_COEFFICIENTS = {
'CarrierAA': -0.0019204985425103213,
'CarrierAS': -0.84841944514035605,
'CarrierB6': 0.12241821143901417,
'CarrierDL': -0.13261989508615579,
'CarrierEV': -0.010973177444743456,
'C... |
#!/usr/bin/env python3
# vim: set fileencoding=utf-8 fileformat=unix expandtab :
"""struct.py -- Point and Rect
Copyright (C) 2010 <NAME> <<EMAIL>> All rights reserved.
This software is subject to the provisions of the Zope Public License,
Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
THI... |
# Ising Model in Python.
# 28-03-2019.
# Written by <NAME>.
# Python 3.7.
# NumPy has been installed and used in this project.
# Numba has been installed and used in this project.
# Tools used: Visual Studio Code, GitHub Desktop.
from Input_param_reader import Ising_input # Python Function in... |
import math
import re
import subprocess
# from math import *
import sys
with open('response.plot', "r") as f:
plotTemplate = f.read()
with open('response_multi.plot', "r") as f:
plotTemplateMulti = f.read()
indexhtml = '<head></head><body>'
def mathDict():
d = {
"pow": math.pow, "cos": math.cos,... |
# -*- coding: utf-8 -*-
'''Module that defines classes and functions for Brillouin zone sampling
'''
import os
import re
from copy import deepcopy
import numpy as np
from mykit.core._control import (build_tag_map_obj, extract_from_tagdict,
parse_to_tagdict, prog_mapper, tags_mapping)
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Dec 29 20:53:21 2020
@author: asherhensley
"""
import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.express as px
import pandas as pd
import yulesimon as ys
from plotly.subplots import make_subplots
import plo... |
# coding=utf-8
# Copyright 2018 The DisentanglementLib 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
#
# Un... |
# Copyright FMR LLC <<EMAIL>>
# SPDX-License-Identifier: Apache-2.0
"""
The script generates variations for the parameters using configuration file and stores them in respective named tuple
"""
import math
import random
from collections import namedtuple
import numpy as np
# configuration parameters
scene_options = [... |
#%%
from fireworks import PyTorch_Model, Message, HookedPassThroughPipe, Experiment
from fireworks.toolbox import ShufflerPipe, TensorPipe, BatchingPipe, FunctionPipe
from fireworks.toolbox.preprocessing import train_test_split
from fireworks.extensions import IgniteJunction
from fireworks.core import PyTorch_Model
im... |
class AVLNode:
def __init__(self, key):
self.key = key
self.parent = None
self.left = None
self.right = None
self.balance = 0
def has_left(self): return self.left is not None
def has_right(self): return self.right is not None
def has_no_children(self): return not... |
"""
Implements MissSVM
"""
from __future__ import print_function, division
import numpy as np
import scipy.sparse as sp
from random import uniform
import inspect
from misvm.quadprog import IterativeQP, Objective
from misvm.util import BagSplitter, spdiag, slices
from misvm.kernel import by_name as kernel_by_name
from m... |
import json
import datetime
import muffin
from bson import ObjectId
from aiohttp.web import json_response
from motor.motor_asyncio import AsyncIOMotorClient
from functools import partial
from umongo import Instance, Document, fields, ValidationError, set_gettext
from umongo.marshmallow_bonus import SchemaFromUmongo
i... |
from model import *
from dataloader import *
from utils import *
from torch.utils.tensorboard import SummaryWriter
import torch.optim as optim
import time
import gc
from tqdm import tqdm
import matplotlib.pyplot as plt
import torch.nn as nn
import numpy as np
import warnings as wn
wn.filterwarnings('ignore')
#load eit... |
# -*- coding: utf-8 -*-
import pygame
import heapq as pq
import random
def explore(u,vis,adj,q):
for v,w in adj[u]:
if not vis[v]:
pq.heappush(q,[w,u,v])
def prim(adj,return_edj=0):
tree=[[] for i in range(len(adj))]
tree_edj=[]
if not adj:
return -1
... |
#!/usr/bin/env python
# encoding: utf-8
from six import with_metaclass
from functools import wraps
from webob import Request, Response, exc
import re
from pybald.util import camel_to_underscore
from routes import redirect_to
from pybald import context
import json
import random
import uuid
import logging
console = log... |
#修改为 yolo-fastest
#修改 ResidualBlock, 从原来的 ->1x1->3x3-> 变为 ->1x1->3x3->1x1->
#修改 make_residual_block, 增加前面的卷积层
import tensorflow as tf
class DarkNetConv2D(tf.keras.layers.Layer):
def __init__(self, filters, kernel_size, strides, activation="leaky", groups=1):
super(DarkNetConv2D, self).__init__()
... |
import os
import ast
import sys
import math
import time
import string
import hashlib
import tempfile
import subprocess
from operator import itemgetter
from contextlib import contextmanager
from getpass import getpass
import random; random = random.SystemRandom()
import sdb.subprocess_compat as subprocess
from sdb.util... |
import argparse
import datetime
import sys
import threading
import time
import matplotlib.pyplot as plt
import numpy
import yaml
from .__about__ import __copyright__, __version__
from .main import (
cooldown,
measure_temp,
measure_core_frequency,
measure_ambient_temperature,
test,
)
def _get_ver... |
# Copyright 2014 Google 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 by applicable law or agre... |
#!/usr/bin/python;
import sys
import ast
import json
import math as m
import numpy as np
# from scipy.interpolate import interp1d
# from scipy.optimize import fsolve
# Version Controller
sTitle = 'DNVGL RP F103 Cathodic protection of submarine pipelines'
sVersion = 'Version 1.0.0'
# Define constants
pi = m.pi
e = m.... |
import sys
import can
import logging
import struct
import re
import paho.mqtt.client as mqtt
from binascii import unhexlify, hexlify
from flask import Flask, render_template, send_from_directory
from werkzeug.serving import run_simple
from logging.handlers import TimedRotatingFileHandler
from config import Config
htt... |
from collections import Counter, defaultdict
import matplotlib as mpl
import networkx as nx
import numba
import numpy as np
import pandas as pd
import plotly.graph_objects as go
import seaborn as sns
from fa2 import ForceAtlas2
from scipy import sparse
def to_adjacency_matrix(net):
if sparse.issparse(net):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.