text stringlengths 3.07k 22.1k |
|---|
# -*- coding: utf-8 -*-
# ToDo: Add support of multi-gpu training
import os
import re
import json
import random
import argparse
import torch
import pandas as pd
import torchaudio
import librosa
import numpy as np
from shutil import copyfile
from utils.dataset import Dataset, DataColletor
from utils.generic_utils impo... |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import pdb
import fnmatch
from astropy.convolution import convolve, Gaussian1DKernel, Box1DKernel
from astropy.stats import LombScargle
from scipy.signal import savgol_filter as savgol
from astropy.io import fits
import glob, re
import time as TIME
... |
''' Module to perform decimation and smoothing on a dynamic spectrum.
Assumed raw data is in a numpy array, ready for processing.
'''
# General Imports
import numpy as np
import scipy.signal as sig
import matplotlib.pyplot as plt
def block_avg(data, tsamp, vsamp):
''' Compute a block average of the dynamic sp... |
""" Methods for PhotosDB to add Photos face info
"""
import logging
from .._constants import _DB_TABLE_NAMES, _PHOTOS_4_VERSION
from ..utils import _open_sql_file
from .photosdb_utils import get_db_version
"""
This module should be imported in the class defintion of PhotosDB in photosdb.py
Do not import th... |
# -*- coding: utf-8 -*-
# Copyright 2019-2020 CERN
#
# 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 a... |
import os,sys,time,math
import numpy as np
import matplotlib.pyplot as plt
from copy import deepcopy
import matplotlib
from matplotlib import cm
class MplColorHelper:
def __init__(self, cmap_name, start_val, stop_val):
self.cmap_name = cmap_name
self.cmap = plt.get_cmap(cmap_name)
self.nor... |
# Copyright (C) 2021 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... |
r"""@package motsfinder.metric.discrete.fdderivs
Wrapper class to compute derivatives using finite differences.
"""
import itertools
from abc import ABCMeta, abstractmethod
from six import add_metaclass
import numpy as np
from ...utils import lrange, lmap
from ..base import _ThreeMetric
from .numerical import fd_xz... |
from __future__ import print_function, absolute_import, division #makes KratosMultiphysics backward compatible with python 2.6 and 2.7
# Importing the Kratos Library
import KratosMultiphysics as KM
import KratosMultiphysics.StructuralMechanicsApplication as SMA
import KratosMultiphysics.ContactStructuralMechanicsAppli... |
#!/usr/bin/env python
# cardinal_pythonlib/ui.py
"""
===============================================================================
Original code copyright (C) 2009-2020 <NAME> (<EMAIL>).
This file is part of cardinal_pythonlib.
Licensed under the Apache License, Version 2.0 (the "License");
you ma... |
"""Config flow to configure Philips Hue."""
from __future__ import annotations
import asyncio
from typing import Any
from urllib.parse import urlparse
import aiohue
from aiohue.discovery import discover_nupnp, normalize_bridge_id
import async_timeout
import voluptuous as vol
from homeassistant import config_entries,... |
import gym
import numpy as np
from typing import Tuple, List
from mae_envs.wrappers.util import update_obs_space
from mujoco_worldgen.util.types import store_args
def get_all_integer_partitions(n, min_team_size=1, max_team_size=np.inf):
'''
Return a list of all integer partitions of n.
Args:
... |
# Copyright (C) <NAME> <<EMAIL>>
# See LICENSE for details.
from struct import pack
from twisted.internet import protocol, reactor
from twisted.internet.defer import Deferred
from smartanthill.exception import NetworkSATPMessageLost
from smartanthill.network.cdc import CHANNEL_URGENT
from smartanthill.util import ca... |
"""
DETR model and criterion classes.
"""
import sys
import torch
import torch.nn.functional as F
from torch import nn
from misc import (accuracy, is_dist_avail_and_initialized, get_world_size)
sys.path.append('./util')
import seg_ops
from backbone import build_backbone
class DETR(nn.Module):
""" This is the D... |
# Copyright 2020 QuantStack
# Distributed under the terms of the Modified BSD License.
from typing import List
from fastapi import Depends, FastAPI, HTTPException, status, Request, File, UploadFile
from starlette.staticfiles import StaticFiles
from starlette.middleware.sessions import SessionMiddleware
from starlette... |
EIDEvent = {
'name': 'eid',
'fields': [
{'name':'event_name','type': 'text', 'required': True},
{'name':'pathogens', 'type':'collection', 'model': Pathogen},
{'name':'location'},
{'name':'host'},
{'name':'disease'},
{'name':'start_date', 'type': 'date'},
{... |
#!/pxrpythonsubst
#
# Copyright 2016 Pixar
#
# Licensed under the Apache License, Version 2.0 (the "Apache License")
# with the following modification; you may not use this file except in
# compliance with the Apache License and the following modification to it:
# Section 6. Trademarks. is deleted and replaced with:
#
... |
import asyncio
import logging
from pathlib import Path
import socket
import subprocess
import time
import pytest
import rlp
from eth_utils import (
decode_hex,
encode_hex,
to_text,
)
from eth_hash.auto import keccak
from eth.chains.ropsten import (
ROPSTEN_GENESIS_HEADER,
ROPSTEN_VM_CONFIGURATION... |
#-*- coding: utf-8 -*-
import tensorflow as tf
def batchnormalize(X, eps=1e-8, g=None, b=None):
if X.get_shape().ndims == 4:
mean = tf.reduce_mean(X, [0,1,2])
std = tf.reduce_mean( tf.square(X-mean), [0,1,2] )
X = (X-mean) / tf.sqrt(std+eps)
if g is not None and b is not None:
... |
# coding: utf-8
from __future__ import unicode_literals
import datetime
import re
import time
from .common import InfoExtractor
from ..compat import (
compat_urllib_parse,
compat_ord,
)
from ..utils import (
determine_ext,
ExtractorError,
parse_iso8601,
sanitized_Request,
int_or_none,
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Tests for :mod:`orion.benchmark.benchmark_client`."""
import copy
import logging
import pytest
import orion.benchmark.benchmark_client as benchmark_client
import orion.core
from orion.benchmark.assessment import AverageResult
from orion.benchmark.benchmark_client impor... |
import csv
import copy
import math
from os import WIFCONTINUED, error
import re
import numpy as np
'''
input: Training Examples; Iteration number T; Attributes
Output: Final hypothesis: [[vote, split_attr, [value lst that the output is yes]]]
'''
class Boosting:
examples = ''
test_examples = ''
attrs = ''
... |
# -*- coding: utf-8 -*-
import glob
import json
from collections import defaultdict
from pprint import pprint
import re
import requests
from juriscraper.AbstractSite import AbstractSite
from datetime import date
from lxml import etree
from requests.exceptions import MissingSchema
def get_tree(url):
try:
... |
from __future__ import print_function
import datetime
import json
import logging
import pytz
import requests
import treq
import urllib3
from astral import Astral
from requests.exceptions import RequestException
from treq.client import HTTPClient
from twisted.internet import ssl
from twisted.web.client import Agent
fr... |
############################
__author__="Guru"
#
#Parameters_required = XCC capacity
#
#############################
import requests
import sys, json
from paepy.ChannelDefinition import CustomSensorResult
try:
data = json.loads(sys.argv[1])
except:
data = {'host':"172.25.28.102", "params":"6... |
#!usr/bin/python3
import xml.etree.ElementTree as ET
import json
import spacy
import numpy as np
from nltk.tokenize import TreebankWordTokenizer
from keras.preprocessing.sequence import pad_sequences
from keras.preprocessing.text import Tokenizer
from spacy.pipeline import EntityRuler
from spacy.lang.en import English... |
#!/usr/bin/env python3
version = "GTD.1.0.0 BETA"
#region IMPORT
import os
import time
import json
import logging
import discord
import traceback
from discord.ext import tasks
from main import GetTime # type: ignore
from main import SetLogging # type: ignore
from main import CurrentTime # type: ignore
from main import ... |
##############################################################################
#
# Copyright (c) 2001 Zope Foundation and Contributors.
#
# 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.
# THIS SOFTWARE IS PROVIDED "AS I... |
import numpy as np
import matplotlib.pyplot as plt
from typing import List, Tuple
_EPS = 1e-8
_MEAN_MAX = 1e32
_SIGMA_MAX = 1e32
class CMAES:
def __init__(self, objective_function: str, dimensions: int, mode: str, modification_every: int,
lambda_arg: int = 100):
self._fitness = objecti... |
# copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# 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... |
"""Helpers that help with state related things."""
import asyncio
import datetime as dt
import json
import logging
from collections import defaultdict
from types import TracebackType
from typing import ( # noqa: F401 pylint: disable=unused-import
Awaitable,
Dict,
Iterable,
List,
Optional,
Tuple... |
""" cbvcorrector.py module unit tests
"""
import pytest
from numpy.testing import (assert_almost_equal, assert_array_equal,
assert_allclose, assert_raises)
import warnings
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import astropy.units as u
import pandas as pd
from... |
from collections import Iterable
import json
import os
from six import with_metaclass
from django.db.models.fields.related import ForeignKey
from django.conf import settings as django_settings
from django.utils.module_loading import import_string
from inflector import Inflector
from .factories import serializer_fact... |
""" Isentropic properties. """
from __future__ import absolute_import, division
import numpy as np
import scipy as sp
from scipy.optimize import bisect, newton
from skaero.util.decorators import implicit
def mach_angle(M):
r"""Returns Mach angle given supersonic Mach number.
.. math::
\mu = \arcs... |
"""
/irahorecka/api/craigslisthousing/update/score.py
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Module to provide scores to posts in the Craigslist housing database table.
"""
import numpy as np
from sqlalchemy.sql import func, and_
from irahorecka.models import db, CraigslistHousing
def write_craigslist_h... |
import os
import logging
import time
import signal
import threading
import socket
import atexit
try:
from ConfigParser import RawConfigParser, NoOptionError
except ImportError:
from configparser import RawConfigParser, NoOptionError
from . import version as agent_version
from .common.object_names import call... |
#!/usr/bin/env python
"""Classes to aid the parsing process"""
# Python library imports
import collections
import copy
# CCPP framework imports
###############################################################################
def context_string(context=None, with_comma=True):
##########################################... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Utilities for generating the version string for Astropy (or an affiliated
package) and the version.py module, which contains version info for the
package.
Within the generated astropy.version module, the `major`, `minor`, and `bugfix`
variables hold ... |
from copy import deepcopy
from typing import overload
from torch import nn, optim
import torch
import torchvision
import torchvision.transforms as tvtf
from torch.utils.data.dataset import Dataset
from torch.utils.data import DataLoader, dataloader
from utils.models import CIFARResNet
class ExpConfig:
TEST_TY... |
"""Verilog simulator modules."""
from __future__ import absolute_import
import subprocess
import sys
import os
import ctypes
from .. import _api_internal
from .._ffi.base import string_types
from .._ffi.node import NodeBase, register_node
from .._ffi.function import register_func
from . import util
@register_node
cl... |
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 4 11:21:39 2019
@author: borre001
"""
import csv
from hyperopt import STATUS_OK
from timeit import default_timer as timer
import numpy as np
from hyperopt import hp
from hyperopt import tpe, Trials, fmin
import lightgbm as lgb
from utils_train import load_data, load_res... |
import os
from optimus_manager.bash import exec_bash, BashError
from optimus_manager.var import read_requested_mode, VarError
import optimus_manager.envs as envs
from optimus_manager.pci import get_gpus_bus_ids
from optimus_manager.config import load_extra_xorg_options
from optimus_manager import manjaro_hacks
class ... |
#!/usr/bin/python
#
# Copyright (c) 2012 <NAME> <<EMAIL>>
#
# 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... |
# -*- coding: utf-8 -*-
# pylint: disable=C0303
"""
This module contains a HTMLExportWord Model
"""
from __future__ import annotations
import fnmatch
from dataclasses import dataclass
from itertools import groupby
from typing import Union, Optional, List
from loglan_db import db
from loglan_db.model_db.addons.addon_w... |
import nyokaBase.PMML43Ext as pml
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor
from sklearn.ensemble import GradientBoostingClassifier,GradientBoostingRegressor,RandomForestClassifier,RandomForestRegres... |
import numpy as np
def softmax(predictions):
'''
Computes probabilities from scores
Arguments:
predictions, np array, shape is either (N) or (batch_size, N) -
classifier output
Returns:
probs, np array of the same shape as predictions -
probability for every class, 0..1
... |
"""Testing measurement"""
# Copyright 2019 HQS Quantum Simulations GmbH
#
# 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 python3
"""Script to create Github releases & generate release notes."""
import hashlib
import json
import logging
import os
import subprocess
import sys
import zipfile
from third_party.python import colorlog, requests
from third_party.python.absl import app, flags
logging.root.handlers[0].setFormatte... |
import zipfile
import numpy as np
from stride import *
from skempi_lib import *
from torch_utils import *
np.seterr("raise")
EPS = 1e-6
REPO_PATH = osp.join('..', '3DCNN_data', 'pdbs.zip')
TRAINING_SET_PATH = osp.join('..', '3DCNN_data', "train_pdbs")
VALIDATION_SET_PATH = osp.join('..', '3DCNN_data', "valid_pdbs")... |
# coding: utf-8
"""
Tasks that provide common and often used functionality.
"""
__all__ = ["RunOnceTask", "TransferLocalFile", "ForestMerge"]
import os
from abc import abstractmethod
import logging
import luigi
import six
from law.task.base import Task
from law.workflow.base import cached_workflow_property
from l... |
# coding=utf-8
# Copyright 2021 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... |
#!/usr/bin/python
# Copyright (c) 2020, 2022 Oracle and/or its affiliates.
# This software is made available to you under the terms of the GPL 3.0 license or the Apache 2.0 license.
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# Apache License v2.0
# See LICENSE.TXT for d... |
# -*- coding: utf-8 -*-
#-------------------------------------------------------------------------------
# Name: wwnortonMGTA.py
# Purpose: interface for using theoryAnalyzer on W.W.Norton exercises
#
# Authors: <NAME> and <NAME>
#
# Copyright: (c) 2009-2012 The music21 Project
# License: LGPL... |
# Copyright 2019 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
#
# Unless required by applicable law or agreed to in writing, ... |
import sys
import traceback
import av
import cv2.cv2 as cv2 # for avoidance of pylint error
import numpy as np
import time
import argparse
import logging
from estimator import TfPoseEstimator
from networks import get_graph_path, model_wh
from djitellopy import tello
from pose_moves_final import PoseMover
from simple_p... |
# encoding: utf-8
import datetime
from ..testing import (
DatabaseTest,
DummyMetadataClient,
)
from ..model import (
DataSource,
Edition,
Identifier,
Subject,
)
from ..external_list import (
CustomListFromCSV,
MembershipManager,
ClassificationBasedMembershipManager,
)
class TestCu... |
#!/usr/bin/python
# Copyright 2016 The ANGLE Project Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
#
# angle_format.py:
# Utils for ANGLE formats.
import json
import os
import re
def reject_duplicate_keys(pairs):
found_keys = {... |
"""isort/settings.py.
Defines how the default settings for isort should be loaded
(First from the default setting dictionary at the top of the file, then overridden by any settings
in ~/.isort.cfg if there are any)
Copyright (C) 2013 <NAME>
Permission is hereby granted, free of charge, to any person obtaining a c... |
from __future__ import print_function
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import torch.optim as optim
import numpy as np
import random
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
class Generator(nn.Module):
def __init__(... |
"""
KNXIPInterface manages KNX/IP Tunneling or Routing connections.
* It searches for available devices and connects with the corresponding connect method.
* It passes KNX telegrams from the network and
* provides callbacks after having received a telegram from the network.
"""
import ipaddress
from enum import Enum
... |
"""Allow VisiData to work directly with Amazon S3 paths.
Functionality is more limited than local paths, but supports:
* Navigating among directories (S3 prefixes)
* Opening supported filetypes, including compressed files
* Versioned buckets
"""
from visidata import ENTER, Column, Path, Sheet, asyncthread, date, vd
... |
import os
import shutil
import logging
import zipfile
import copy
import mock
from django.urls import reverse
from django.test import override_settings
from rest_framework import status
from rest_framework.test import APITestCase
from substrapp.serializers import LedgerObjectiveSerializer
from substrapp.ledger_uti... |
import hashlib
import os
from contextlib import suppress
from smtplib import SMTPException
from django.conf import settings as django_settings
from django.contrib import messages as notifications
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.views import LoginView, LogoutView, Pas... |
# The CLIF Framework has been programmed by Taguar258 and is published under the MIT License.
import importlib
class console_read_only(type):
def __setattr__(self, name, value):
if name == "objects":
raise Exception("Variable cannot be called objects.")
class console:
__metaclass__ = console_read_only
def... |
# -*- coding: utf-8 -*-
import codecs as cs
import numpy as np
import h5py
from constants import l2i_dic
def GetFiles(path):
fp = cs.open(path,'r','utf-8')
text = fp.read()
fp.close()
text = text.split('\n')[:-1]
return text
def ypre2label(ypredict):
'''
将预测出的ypredict(50维list)取最大值索引,得到每个tok... |
import os
import time
import torch
from torch import nn
import torch.nn.functional as F
from torch.utils.data import DataLoader, random_split
from torchvision import transforms
import pytorch_lightning as pl
import pandas as pd
import numpy as np
from pytorch_lightning.metrics.functional import accuracy
class HandsDat... |
import os
import pytest
import numpy as np
from thoraxe import transcript_info
@pytest.fixture(scope='module')
def datadir(request):
filename = request.module.__file__
test_dir = os.path.dirname(filename)
return os.path.join(test_dir, 'data')
@pytest.fixture(scope='module')
def mapk8(datadir):
mapk... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Sep 21 20:24:16 2020
@author: <NAME> & <NAME>
"""
import matplotlib.pyplot as plt
from matplotlib import animation, rc
rc('animation', html='jshtml')
from IPython.display import HTML
#from IPython.display import display, clear_output
import PIL
import z... |
import inspect
import itertools
import logging
import uuid
from functools import wraps
from django.conf import settings
from django.contrib.auth.decorators import user_passes_test
from django.db import models
from django.http import HttpResponse
from django.urls import path as djangopath
from django.urls import revers... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Custom Ansible module to manage the ceph.conf file
from ConfigParser import RawConfigParser
import copy
ANSIBLE_METADATA = {'status': ['preview'],
'supported_by': 'community',
'version': '1.0'}
DOCUMENTATION = '''
---
module: cephco... |
# CMSC 495 Current Trends and Projects
# Fall 2020
# Contributors: <NAME>, <NAME>, <NAME>, <NAME>
# Our Capstone project was to research different Computer Vision algorithms and techniques to produce an image
# detection program that would find a target image in a larger 'puzzle' image. We used Where's Waldo puzzles as... |
"""InfluxDB component which allows you to get data from an Influx database."""
import logging
from typing import Dict
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA as SENSOR_PLATFORM_SCHEMA
from homeassistant.const import (
CONF_API_VERSION,
CONF_NAME,
CONF_UNIT_OF_M... |
# -*- coding: utf-8 -*-
# @author: <NAME>, <EMAIL>
# @date: 2020-01
import numpy as np
import tensorflow as tf
from tensorflow.keras.layers import Conv1D, Dropout, Dense, LayerNormalization
class Attention(tf.keras.layers.Layer):
""" Multi-head attention layer
"""
def __init__(self, hidden_size, num_hea... |
from itertools import groupby
from django.http import Http404
from django.shortcuts import get_list_or_404, get_object_or_404, render
from isoweek import Week
from datacenter.models import (Chastisement, Commendation, Lesson, Mark,
Schoolkid, Subject)
def get_iso_week_from_params(get_... |
import os
import uuid
from django.apps import apps
from django.conf import settings
from django.contrib.gis.db import models
from django.utils import timezone
from geocontrib import logger
from geocontrib.choices import RELATED_MODELS
from geocontrib.choices import EXTENDED_RELATED_MODELS
from geocontrib.choices impo... |
import torch as th
from torch.autograd import Variable
import numpy as np
from dgl.frame import Frame, FrameRef
from dgl.utils import Index, toindex
import utils as U
N = 10
D = 5
def check_fail(fn):
try:
fn()
return False
except:
return True
def create_test_data(grad=False):
c1 =... |
# Copyright 2012 Citrix Systems, Inc. Licensed under the
# Apache License, Version 2.0 (the "License"); you may not use this
# file except in compliance with the License. Citrix Systems, Inc.
# reserves all rights not expressly granted by the License.
# You may obtain a copy of the License at http://www.apache.org/lic... |
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 3 15:07:16 2017
@author: <NAME>
"""
from __future__ import division, print_function, unicode_literals, absolute_import
import unittest
import sys
import numpy as np
from multiprocessing import cpu_count
sys.path.append("../../sidpy/")
from sidpy.proc import comp_utils
f... |
import sys
from pprint import pprint
# read apk
#import androguard.core.bytecodes.apk as apk
#a = apk.APK(sys.argv[1])
import androguard.core.bytecodes.dvm as dvm
from androguard.core.analysis.analysis import *
import inflection
import executor
import descriptors
# XXX must be library for this
def has_field_name(s... |
"""
A collection of methods employed in the H2+ dynamics project.
The following methods are provided by this module:
* load_data: A simple helper function to load the different data files used in this project.
* hamiltonian: Computes the Hamiltonian for a given potential as a matrix.
* TimeEvolution: The time evoluti... |
# Copyright (c) 2020 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... |
'''
CTCI Chapter 2: Linked Lists
'''
from collections import deque
class node:
def __init__(self, data=None):
self.data = data
self.next = None
class link_list:
def __init__(self):
self.head = node() # initialize the head node
def append_node(self, data):
new_node = n... |
from ctypes import c_void_p
from operator import attrgetter
import numpy as np
from parcels.field import Field
from parcels.tools.error import ErrorCode
from parcels.tools.loggers import logger
__all__ = ['ScipyParticle', 'JITParticle', 'Variable']
indicators_64bit = [np.float64, np.int64, c_void_p]
class Variabl... |
import os
import platform
import sys
import logging
import sentry_sdk
import unidecode
import tzlocal
import locale
import git
from ruamel import yaml
from threading import Timer, RLock
from datetime import datetime, timedelta
from functools import total_ordering, update_wrapper
logging_level_str_to_int = {
'disa... |
""" Minimum working example of an SME script
"""
import os.path
import pickle
import time
import keras
import matplotlib.pyplot as plt
import numpy as np
from keras.constraints import max_norm, unit_norm
from keras.layers import (
BatchNormalization,
Conv1D,
Dense,
Dropout,
Flatten,
MaxPooling1... |
from __future__ import print_function
import sys
import re
try:
# Python 3
from .__version__ import __version__
except (ValueError):
# Python 2
from __version__ import __version__
#
# The MIT License (MIT)
# Copyright (c) 2013 <NAME> and contributors.
# Permission is hereby granted, free of charge, to any pers... |
#-*- coding: UTF-8 -*-
"""
Besides the ``element`` and the ``filter`` submodules,
this submodule is one of the most elementary submodules of the **Revitron** package.
It contains all classes related to parameters, built-in parameters and value providers.
"""
import re
import numbers
class Parameter:
"""
A wrapper... |
"""Train GAIL or AIRL and plot its output.
Can be used as a CLI script, or the `train_and_plot` function can be called
directly.
"""
from collections import defaultdict
import os
import os.path as osp
import pickle
from typing import Optional
from matplotlib import pyplot as plt
from sacred.observers import FileStor... |
#!/usr/bin/env python3
# Copyright (c) 2015-2016 The Bitcoin Core developers
# Copyright (c) 2017 The Bitcoin developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""
This test checks simple acceptance of bigger blocks via p2... |
"""
Digital Filter Coefficient Conversion to C Header Files
Copyright (c) March 2017, <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:
1. Redistributions of source code must retain the a... |
from __future__ import division, print_function
import os, sys
import numpy as np
# from argparse import ArgumentParser
from sklearn.metrics import f1_score, matthews_corrcoef
import codecs
import plac
import pdb
"""
Scoring programme for WMT'20 Task 2 HTER **word-level**
"""
# -------------PREPROCESSING------------... |
import json
import os
import shutil
import stat
import threading
import uuid
from copy import copy
from unittest.case import TestCase
from unittest.mock import MagicMock
import utils.file_utils as file_utils
import utils.os_utils as os_utils
from execution.process_base import ProcessWrapper
from model.script_config im... |
import pygame
pygame.init()
screen_width = 987
screen_height = 598
# setting window size.
win = pygame.display.set_mode((screen_width, screen_height))
# game window title
pygame.display.set_caption("<NAME>")
# loading character movements
bg = pygame.image.load('img/bg.jpg')
idle = pygame.image.load('img/standing.png'... |
# Copyright 2020 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,... |
# This file is borrowed from NeuS project
import torch
import torch.nn.functional as F
import cv2 as cv
import numpy as np
import os
from glob import glob
from scipy.spatial.transform import Rotation as Rot
from scipy.spatial.transform import Slerp
# This function is borrowed from IDR: https://github.com/lioryariv/id... |
__author__ = 'jvial'
import pandas as pd
import numpy as np
lith = pd.read_csv('corrected_lithology.csv')
geo = pd.read_csv('Complete_Geophysics.csv')
# Read in all ATV data once.
atv_dictionary = {}
print('Read in lith and geo')
def get_label(bore_id, depth, rtype=False):
"""
Function to get the label, wil... |
import asyncio
import json
import os
import requests
from web3 import Web3, WebsocketProvider, Account
from web3.gas_strategies.time_based import slow_gas_price_strategy,medium_gas_price_strategy, fast_gas_price_strategy
from xchainpy_ethereum.models.asset import Asset
from xchainpy_client import interface
from xchainp... |
from bs4 import BeautifulSoup as bs
import requests
from tabulate import tabulate
import csv
from datetime import datetime
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
from email.mime.mu... |
# -*- coding: utf-8 -*-
"""
Copyright (C) 2017 <NAME> (plugin.video.netflix)
Copyright (C) 2020 <NAME> (original implementation module)
Navigation for search menu
SPDX-License-Identifier: MIT
See LICENSES/MIT.md for more information.
"""
from copy import deepcopy
import xbmcgui
import xbmcplugin
... |
#!/usr/bin/env python3
#coding: utf8
import os
import sys
import argparse
import subprocess
def get_cflags():
cflags = []
cmds = [
"pkg-config --cflags glib-2.0",
"pkg-config --cflags gio-2.0",
"ksba-config --cflags",
"pcap-config --cflags",
"gpgme-config --cflags",
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.