text
stringlengths
957
885k
<reponame>lavon321/Kunlun-M #!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2018/7/26 16:38 # @Author : LoRexxar # @File : views.py # @Contact : <EMAIL> import os import codecs import json from django.core import serializers from django.shortcuts import render, redirect, HttpResponse from django.http i...
<filename>tasks/bert/__init__.py import os import types import contextlib import itertools import re from typing import Iterable, List, Tuple import torch from torch.random import fork_rng import torchvision import numpy as np from torch.utils.data import DataLoader from torch.utils.data.dataset import Subset, random_...
import sys import os import numpy as np import glob import matplotlib # Force matplotlib to not use any Xwindows backend. matplotlib.use('Agg') from matplotlib import pylab as plt from matplotlib.backends.backend_pdf import PdfPages from geoNet.utils import read_statsll, get_processed_stats_list from geoNet.gmpe impor...
from typing import List import math import sys from functools import partial from random import shuffle import getpass from .constants import ALL_DIRECTIONS, print, log, STRATEGY_HYPERPARAMETERS, ResourceTypes, Directions, LogicGlobals, StrategyTypes, INFINITE_DISTANCE, GAME_CONSTANTS, ValidActions, is_turn_during_nig...
#!/usr/bin/env python # # Copyright (c) 2006 <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 ...
from __future__ import division from ..lab1.Solver import Solver from ..lab2.SimplexMethod import get_basis_matrix, get_cannonical_form, get_basis_cost_vector from sympy import zeros, Matrix from sympy.functions import transpose import bisect class DualSimplexMethod(object): """ :type matrix_c:Matrix :ty...
<reponame>OmriNach/WizardHat """Plotting of data in `buffers.Buffer` objects. Rough implementation of a standalone bokeh server. Currently just grabs the most recent sample from Buffers.buffer every time the periodic callback executes. This is probably not the best way to do it, because the sampling rate is arbitrari...
<gh_stars>1-10 """ 给定两个单词 word1 和 word2,找到使得 word1 和 word2 相同所需的最小步数,每步可以删除任意一个字符串中的一个字符。 示例 1: 输入: "sea", "eat" 输出: 2 解释: 第一步将"sea"变为"ea",第二步将"eat"变为"ea" 说明: 给定单词的长度不超过500。 给定单词中的字符只含有小写字母。 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/delete-operation-for-two-strings 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 """ ...
<reponame>Microsoft/CameraTraps # # Merge high-confidence detections from one results file into another file, # when the target file does not detect anything on an image. # # Does not currently attempt to merge every detection based on whether individual # detections are missing; only merges detections into images tha...
<filename>src/fastjet/_utils.py import awkward as ak import fastjet._swig # light wrapping for the functions to raise an error if the user inputs awkward arrays into functions meant for swig def sorted_by_E(data): if isinstance(data, ak.Array): try: tempE = data.E except AttributeErr...
<reponame>tristanengst/apex-utils<filename>conditional_imle/ConditionalIMLE.py """File with conditional IMLE implementation. To use this utility, you need to do the following: 1. Your network needs to return a list of outputs, where the ith element is the network's output (to the loss function) at the ith level. ...
<filename>item.py #!/usr/bin/env python import sys from os.path import isfile, basename, join as pjoin from subprocess import Popen from xml.etree import ElementTree as ET lorem="Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua." slots="Head Ne...
<reponame>Ecrypty/florijncoinmnb import sys import os sys.path.append(os.path.join(os.path.dirname(__file__), '.')) import time def clear_screen(): os.system('clear') def check_version(): from mnb_explorer import get_version_txt cur_version = get_florijncoinmnbversion() git_version = get_version_tx...
<reponame>short-greg/takonet from abc import ABC, abstractmethod from functools import partial, reduce import typing from ._networks import Node, NodeSet, Network from abc import ABC, abstractmethod import typing class Q(ABC): @abstractmethod def __call__(self, nodes: typing.Iterable[Node]) -> NodeSet: ...
<reponame>albgar/legacy_aiida_plugin<filename>aiida_siesta/workflows/exchange_barrier.py from aiida import orm from aiida.engine import WorkChain, ToContext from aiida_siesta.workflows.neb_base import SiestaBaseNEBWorkChain from aiida_siesta.workflows.base import SiestaBaseWorkChain from aiida_siesta.utils.structures i...
<filename>roster/crawlers.py # -*- coding:utf-8 -*- import os import re from steem.comment import SteemComment from steem.collector import get_posts, get_comments from utils.logging.logger import logger TEAMCN_SHOP_ACCOUNT = "teamcn-shop" TEAMCN_SHOP_POST_NAME_NICKNAME_PATTERN = r"\|(\@[A-Za-z0-9._-]+) ([^|]+)\|" ...
import hmac import json import re import time from hashlib import sha256 import requests from django.conf import settings from django.core.exceptions import ImproperlyConfigured, ValidationError from django.core.files.base import ContentFile from django.core.validators import URLValidator from django.http import HttpR...
<filename>tests/sandbox/.venv_ccf_sandbox/lib/python3.8/site-packages/joblib/test/test_dask.py from __future__ import print_function, division, absolute_import import os import pytest from random import random from uuid import uuid4 from time import sleep from .. import Parallel, delayed, parallel_backend from ..para...
<gh_stars>10-100 #!/usr/bin/env python import os import json import torch import torch.nn.functional as F import pickle import random import urllib import urllib.request import cherrypy from transformers import DistilBertTokenizer from model.multimodal_transformer import MMT_VideoQA from util import compute...
<filename>checks.d/burrow_v3.py # stdlib from urlparse import urljoin # 3rd Party import requests import json # project from checks import AgentCheck SERVICE_CHECK_NAME = 'burrow.can_connect' DEFAULT_BURROW_URI = 'http://localhost:8000' CLUSTER_ENDPOINT = '/v3/kafka' CHECK_TIMEOUT = 10 class BurrowCheck(AgentChe...
<filename>hardware/controller.py from multiprocessing.connection import Listener from nanpy import (ArduinoApi, SerialManager, Ultrasonic) from picamera import PiCamera from time import sleep import sys import camera_config import numpy as np LEFT = 0 RIGHT = 1 FORWARD = 2 BACKWARD = 3 MAX_SPEED = 255 M...
<filename>upload.py #!/usr/bin/env python3 import configargparse import shutil import tempfile import urllib.request from urllib.parse import urlparse import requests import logging from http import HTTPStatus from pymarc import parse_xml_to_array DEFAULT_CONFIG_FILE = 'config.yaml' # TAGS according to https://www.l...
<gh_stars>0 import os import re import numpy as np import matplotlib.pyplot as plt from sklearn.metrics import confusion_matrix from PIL import Image import cv2 def next_greater_power_of_2(x): return 2 ** (int(x) - 1).bit_length() def next_lower_power_of_2(x): return 2 ** ((int(x) - 1).bit_length() - 1) d...
#!/usr/bin/env python """ # Problem Description: Given a tile index of (x,y,z) of size 256x256, 1. Find out (lat_deg, lng_deg) and the extent covered by the maptile (ie. the radius in meters) 2. Grab the road network (and other entities, like building boundaries or types) from OSM -- use OSMnx -- in the area ...
import os from jacowvalidator.docutils.styles import get_style_summary from jacowvalidator.docutils.margins import get_margin_summary from jacowvalidator.docutils.languages import get_language_summary from jacowvalidator.docutils.title import get_title_summary, get_title_summary_latex from jacowvalidator.docutils.autho...
<filename>tests/test_auth.py import unittest from datetime import datetime from unittest import mock from openhim_mediator_utils.auth import Auth API_URL = 'https://localhost:8080' USERNAME = 'user' class Authenticate(unittest.TestCase): def setUp(self): self.auth = Auth({'verify_cert': False, 'apiURL'...
# Licensed under a 3-clause BSD style license - see LICENSE.rst # -*- coding: utf-8 -*- from __future__ import absolute_import, division, unicode_literals, print_function from astropy.extern import six from astropy.utils.compat.odict import OrderedDict import numpy as np import yaml from . constants import YAML_TA...
# File: ds_search_entities_connector.py # # Licensed under Apache 2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt) # import phantom.app as phantom from phantom.action_result import ActionResult from digital_shadows_consts import * from dsapi.service.search_entities_service import SearchEntitiesService from exc...
# -*- coding: utf-8 -*- import os import sys import psycopg2 as pg import elasticsearch as es script_path = os.path.abspath(os.path.join(os.path.dirname(__file__),os.pardir)) sys.path.append(script_path) from weatherLib.weatherDoc import WeatherData from weatherLib.weatherUtil import WLogger __INSERT_OBS = "insert...
<gh_stars>0 from urllib import parse import datetime import requests import urllib import os from os import path from pathlib import Path import sys import time import math from concurrent.futures import ThreadPoolExecutor, wait, FIRST_EXCEPTION, ALL_COMPLETED, as_completed import threading import socket class downloa...
from pyspark.sql import SparkSession, DataFrame from pyspark.sql.types import StructType, StructField, MapType, StringType from pyspark.sql.functions import explode, map_keys, map_values """ MapType Column PySpark MapType is used to represent map key-value pair similar to python Dictionary (Dict), it extends DataType ...
<gh_stars>1-10 # coding=utf-8 # Copyright 2019 The Edward2 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 a...
import sys, os import numpy as np from scipy import stats from collections import defaultdict import nanoraw_helper as nh VERBOSE = False def correct_multiple_testing(pvals): """ Use FDR Benjamini-Hochberg multiple testing correction """ pvals = np.asarray(pvals) pvals_sortind = np.argsort(pvals) ...
# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other # Spack Project Developers. See the top-level COPYRIGHT file for details. # # SPDX-License-Identifier: (Apache-2.0 OR MIT) class Geant4(CMakePackage): """Geant4 is a toolkit for the simulation of the passage of particles through matter....
<reponame>lamypark/ingredient2vec<filename>src/utils/DataLoader.py import os import collections import smart_open import random import numpy as np import Config """ Load basic ingredients and compounds data from Nature Scientific Report(Ahn, 2011) """ class DataLoader: # {ingredient_id: [ingredien...
<reponame>techman83/maestral-dropbox # -*- coding: utf-8 -*- """ @author: <NAME> (<EMAIL>) (c) <NAME>; This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivs 2.0 UK: England & Wales License. This module is the heart of Maestral, it contains the classes for sync functionality. """ # system...
<gh_stars>1-10 # Copyright 2014: Mirantis 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 # # Un...
<gh_stars>0 # -*- coding: utf-8 -*- # # Copyright 2015-2020 BigML # # 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...
import numpy as np import tensorflow as tf import copy import scipy.stats import time def TicTocGenerator(): # Generator that returns time differences ti = 0 # initial time tf = time.time() # final time while True: ti = tf tf = time.time() yield tf-ti # returns the t...
<reponame>fcco/SkySol<filename>skysol/lib/visualization.py # Import MatplotLib for visualization import matplotlib.pyplot as plt import time from datetime import datetime import cv2 import os import numpy as np from skysol.lib import optical_flow, misc, drawings from numpy import degrees, radians, arctan2, pi from matp...
"""Module unittests.test_sequence_algorithms.py This module contains methods to test the sequence_algorithms module via pytest. It uses good_mock_server to validate the positive test cases and bad_mock_server for the negative test cases. """ import pytest import json import click from click.testing import CliRunner fr...
<reponame>haygcao/UnicomDailyTask<filename>activity/womail/mailxt5.py # -*- coding: utf8 -*- import re import requests from utils.common import Common from utils.bol import rsa_encrypt_password from lxml import etree from random import randint class XT5CoreMail(Common): def __init__(self, mobile, password): ...
# Copyright 2016 - Nokia # # 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, sof...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # finpie - a simple library to download some financial data # https://github.com/peterlacour/finpie # # Copyright (c) 2020 <NAME> # # Licensed under the MIT License # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and assoc...
<gh_stars>1-10 #!/usr/bin/env python import os import re import argparse from yarp import Registry class UsrClassHandler(object): def __init__(self, usrclass_location): self.hive = Registry.RegistryHive( open(usrclass_location, 'rb') ) log_mapping = { "log": None, ...
""" Work with files: copy, move, check file exist """ import os import sys import shutil from .makedir import makedir # http://stackoverflow.com/questions/123198/how-do-i-copy-a-file-in-python def copyfile(src, dst, override=False, verbosity=False): """Copy file Keyword Arguments: src -- source fil...
IMAGE_SIZE = (299,299) # The dimensions to which all images found will be resized. BATCH_SIZE = 16 NUMBER_EPOCHS = 5 TENSORBOARD_DIRECTORY = "../logs/simple_model/tensorboard" TRAIN_DIRECTORY = "../data/train/" VALID_DIRECTORY = "../data/valid/" NUMBER_TRAIN_SAMPLES = 17500 NUMBER_VALIDATION_SAMPLES = 5000 WEIGHTS_D...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Oct 6 13:55:32 2021 @author: ccamargo """ import numpy as np import xarray as xr import sys sys.path.append("/Users/ccamargo/Documents/py_scripts/") import utils_SL as sl import utils_SLE_v2 as sle # import utils_hec as hec # import os # import cmo...
from zencad import * from api import Size, SimpleZenObj, CompoundZenObj from config import EPS, EPS2, LEVER_ANGLE # Fix the incorrectly named color color.cyan = color.cian class Pcb(SimpleZenObj): colour = color.yellow size = Size(72.5, 60.1, 1.3) hole_r = 3.5 / 2.0 hole_vector_nw = vector3(hole_r...
# -*- coding: utf-8 -*- ########################################################################## # NSAp - Copyright (C) CEA, 2019 # Distributed under the terms of the CeCILL-B license, as published by # the CEA-CNRS-INRIA. Refer to the LICENSE file or to # http://www.cecill.info/licences/Licence_CeCILL-B_V1-en.html #...
<reponame>heatherwan/Automatic-Validation-of-Simulation-Results import importlib import os import socket import sys import time from datetime import datetime import numpy as np import tensorflow as tf from sklearn.metrics import classification_report from sklearn.metrics import confusion_matrix from utils.Dataset_hdf...
<filename>jupyter_home/sources/gloaders/dancer_loader.py import re from logging import warning from typing import List, Dict, Tuple, Set from os import listdir from os.path import isfile, join, exists import igraph from sources.gloaders.loader_interface import LoaderInterface class DancerLoader(LoaderInterface): ...
#!/usr/bin/env python # coding: utf-8 # In[ ]: #Importing Necessary Libraries from bs4 import BeautifulSoup as soup import requests import lxml import re import pandas as pd from threading import Thread from elasticsearch import Elasticsearch if __name__== "__main__": main_url='https://en.wikipedia.org/wiki/Lis...
<reponame>sahandv/science_science #!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Oct 21 16:10:03 2020 @author: github.com/sahandv """ import sys import time import gc import os import numpy as np import pandas as pd from tqdm import tqdm import matplotlib.pyplot as plt from random import randint fr...
from django.contrib.sites.models import Site from django.core.urlresolvers import reverse from omb import OMB_VERSION_01, OAUTH_REQUEST, OAUTH_ACCESS, OMB_POST_NOTICE, OMB_UPDATE_PROFILE from oauth.oauth import OAuthConsumer, OAuthRequest, OAuthSignatureMethod_HMAC_SHA1, OAuthToken import urlparse, urllib def requestT...
import pytest import pandas as pd import pandas._testing as tm from pandas.tests.extension.base.base import BaseExtensionTests class BaseGroupbyTests(BaseExtensionTests): """Groupby-specific tests.""" def test_grouping_grouper(self, data_for_grouping): df = pd.DataFrame( {"A"...
from enum import Enum from typing import Optional, Callable, Iterable, Iterator, Union JOIN_TYPES = ('left', 'right', 'full', 'inner', 'outer') # deprecated class JoinType(Enum): Left = 'left' Right = 'right' Full = 'full' Inner = 'inner' Outer = 'outer' def topologically_sorted( # Kahn's al...
<filename>tests/golog.py<gh_stars>1-10 #!/usr/bin/env python3 from collections import defaultdict from strips import * from golog_program import * from domains.bag import S as S from domains.math1 import S as S1 def assert_pn(s, incl, excl): assert set(incl) <= s.exists assert not s.exists.intersection(set(ex...
'''SMART API Verifier main controller''' # Developed by: <NAME> # # CONFIG: Change the consumer_secret in _ENDPOINT! # # Revision history: # 2012-02-24 Initial release # 2013-03-27 Upgraded to SMART v0.6 OAuth - <NAME> import os import sys abspath = os.path.dirname(__file__) sys.path.append(abspath) import l...
<gh_stars>1-10 #!/usr/bin/env python from HTMLParser import HTMLParser import re import os import sys import string class Html2MarkdownParser(HTMLParser): def __init__(self): self._markdown = '' self._tag_stack = [] self._tag_attr_data = {} self._handled_tag_body_data = '' ...
import math import os import unittest import torch import torchaudio import torchaudio.functional as F import torchaudio.transforms as T import pytest import common_utils from common_utils import AudioBackendScope, BACKENDS class TestFunctional(unittest.TestCase): data_sizes = [(2, 20), (3, 15), (4, 10)] nu...
<filename>loopchain/peer/candidate_blocks.py # Copyright 2017 theloop, 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 requi...
<filename>actor_services/src/random_create.py<gh_stars>10-100 #!/usr/bin/env python # coding=utf-8 ''' Author:<NAME> Date: Info: ''' import random import numpy as np import rospkg from lxml import etree from lxml.etree import Element from copy import deepcopy import yaml rospack = rospkg.RosPack() with open(rospack....
import cdms2,cdutil,sys,MV2,numpy,os,cdat_info f=cdms2.open(os.path.join(cdat_info.get_sampledata_path(),'clt.nc')) s=f("clt") cdutil.setTimeBoundsMonthly(s) print 'Getting JJA, which should be inexistant in data' try: cdutil.JJA(s[:5]) raise RuntimeError( "data w/o season did not fail") except: pass ## Create...
import hashlib import os import requests import time import warnings import six warnings.filterwarnings("ignore", message=".*InsecurePlatformWarning.*") """ OneSky's simple python wrapper Known WTF?: - If you manualy create project file (e.g. django.po) inside SkyOne app, API will return 400 er...
<reponame>Xchkoo/student_system_web from flask import g import sqlite3 from app_mask import config, app def get_db(): db = getattr(g, '_database', None) if db is None: db = g._database = sqlite3.connect(config.DATABASE) return db @app.teardown_appcontext def close_connection(exception): db =...
# Online Bayesian linear regression using Kalman Filter # Based on: https://github.com/probml/pmtk3/blob/master/demos/linregOnlineDemoKalman.m # Author: <NAME> (@gerdm), <NAME>(@karalleyna) import superimport import matplotlib.pyplot as plt import pyprobml_utils as pml from numpy.linalg import inv from lds_lib import...
import requests; from bs4 import BeautifulSoup; import jieba; import os; import re; import time; from gensim import corpora,models,similarities; import random; import sys; def get_review_tag(src): review_response=requests.get(src); review_soup=BeautifulSoup(review_response.text); review_tag=review_soup.fi...
<reponame>stactools-packages/soilgrids # flake8: noqa from datetime import datetime from pystac import Link, Provider, ProviderRole COLLECTION_ID = "soilgrids250m" EPSG = 152160 CRS_WKT = """PROJCS["Homolosine", GEOGCS["WGS 84", DATUM["WGS_1984", SPHEROID["WGS 84",6378137,298.257223563, ...
from unittest.mock import patch from bs4 import BeautifulSoup from django.urls import reverse from web.grant_applications.forms import CompanyDetailsForm from web.grant_applications.services import BackofficeService from web.grant_applications.views import CompanyDetailsView from web.tests.factories.grant_application...
<reponame>draftable/compare-api-python-client<filename>draftable/commands/dr_compare.py #!/usr/bin/env python import argparse import configparser import datetime import os import sys from draftable import Client as DraftableClient from draftable.endpoints.comparisons.sides import make_side from draftable.endpoints.ex...
""" Copyright 2017 <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...
<reponame>dankilman/pysource<filename>pysource/transport.py # Copyright 2014 <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 r...
<gh_stars>1-10 from django.db import models from django.contrib.auth.models import User import uuid class Company(models.Model): name = models.CharField(max_length=128) telephone = models.CharField(max_length=128) mail = models.CharField(max_length=128) def __str__(self): return self.name ...
<reponame>tliakos/default-toolchain-1490724000329 from __future__ import with_statement import doctest import socket import unittest2 try: import urllib.error as urllib_error except ImportError: import urllib2 as urllib_error from klout import * class TestKlout(unittest2.TestCase): def test_klout(self):...
import os import numbers import base64 from django.contrib.auth.models import User from django.db import transaction import io import pandas as pd import numpy as np from openfacstrack.apps.track.models import ( PanelMetadata, Parameter, ProcessedSample, Result, DataProcessing, Patient, Pa...
#!/usr/bin/env python # ALTA data transfer: Uses the iROD client to transfer data from ALTA # Example usage: >> python getdata_alta.py 180316 004-010 00-36 # <NAME> (<EMAIL>) ################################################################################################### from __future__ import print_function impo...
import glob import os import sys import copy from joblib import Parallel, delayed import matplotlib.pyplot as plt import numpy as np import pandas as pd import pyabf from ipfx import feature_extractor from ipfx import subthresh_features as subt print("feature extractor loaded") from .abf_ipfx_dataframes import _build...
import pandas as pd import matplotlib.pyplot as plt import numpy as np #-------------read csv--------------------- df_2010_2011 = pd.read_csv("/mnt/nadavrap-students/STS/data/data_Shapira_20200911_2010_2011.csv") df_2012_2013 = pd.read_csv("/mnt/nadavrap-students/STS/data/data_Shapira_20200911_2012_2013.csv") df_2014...
import numpy as np import os, argparse, pickle, sys from os.path import exists, join, isfile, dirname, abspath, split import logging from sklearn.neighbors import KDTree import yaml from .base_dataset import BaseDataset, BaseDatasetSplit from .utils import DataProcessing from ..utils import make_dir, DATASET logging...
#!/usr/bin/python3 import argparse import base64 import time import logging _logger = logging.getLogger(__name__ if __name__ != '__main__' else __file__) class Stream(): def __init__(self, stream, host=None, debug=False): ''' TODO: support streams other than filenames ''' self.stream = stream ...
import random def gen_test(): n = 1000 k = 100 max_end = 1000 A = [] R = random.Random(0) for _ in range(n): a = R.randint(0, max_end) b = R.randint(0, max_end) if a == b: A.append((a, a + 1)) else: a, b = min(a, b), max(a, b) ...
<reponame>lutzkuen/statarb #!/usr/bin/env python import numpy as np import pandas as pd import gc from scipy import stats from pandas.stats.api import ols from pandas.stats import moments from lmfit import minimize, Parameters, Parameter, report_errors from collections import defaultdict from util import * INDUSTR...
<reponame>kmeister/ML_Benchmark from multiprocessing import Pool from multiprocessing import Manager import subprocess class AsyncTask: def __init__(self, name, command, queue): self.command = command self.queue = queue self.name = name def execute(self): print(f"Starting Task...
<gh_stars>1-10 # -*- coding: utf-8 -*- from tm import TuringMachine from tmbuilder import TuringMachineBuilder import re import sys import logging class TuringMachineParser: """ Proportionate methods to parse a Turing Machine. The allowed expresions are: - empty line - comme...
<reponame>Wentaobi/OpenCDA<gh_stars>0 # -*- coding: utf-8 -*- """ Use Extended Kalman Filter on GPS + IMU for better localization. """ # Author: <NAME> <<EMAIL>>, credit to <NAME> <<EMAIL>> # License: MIT import math import numpy as np class ExtentedKalmanFilter(object): """ Kalman Filter implementation for ...
import numpy as np from vis.fields import DomainType, VisualizationField, ScalarField, VectorField from vis.pythreejs_viewer import * try: from vis.offscreen_viewer import * HAS_OFFSCREEN = True except Exception as e: print("WARNING: failed to load offscreen viewer:", e) HAS_OFFSCREEN = False import...
<filename>matting/alpha_matting.py from .util import make_system, solve_cg from .closed_form_laplacian import closed_form_laplacian from .knn_laplacian import knn_laplacian from .ichol import ichol, ichol_solve from .lkm import make_lkm_operators from .ifm_matting import ifm_system from .vcycle import vcycle import num...
import pdb import time import copy import math import numpy as np import torch import torch.nn as nn import torch.optim as optim import torch.utils.model_zoo as model_zoo from torch.optim import lr_scheduler from torchvision.models.resnet import Bottleneck, BasicBlock class DeepLearningModel(nn.Module): def __i...
# This file was automatically generated by SWIG (http://www.swig.org). # Version 2.0.11 # # Do not make changes to this file unless you know what you are doing--modify # the SWIG interface file instead. from sys import version_info if version_info >= (2,6,0): def swig_import_helper(): from os.path impo...
import time from uuid import uuid4 import hypothesis.strategies as hst from hypothesis import HealthCheck, assume, given, settings import numpy as np import pytest import qcodes as qc from qcodes.dataset.guids import (filter_guids_by_parts, generate_guid, parse_guid, set_guid_locat...
#!/usr/bin/env python3 """Crawl DB for started bcl2fastq runs and resp. output folders for flag files indicating completion, upon which DB needs update """ #--- standard library imports # import sys import os import argparse import logging import subprocess from datetime import datetime #--- third-party imports # i...
<reponame>seangeggie/tourney import os import json from .constants import DATA_PATH class State: __instance = None def __init__(self): if not State.__instance: self.reset() try: self.load() except Exception as ex: print("State file could not load: {}".format(self.file_path()...
# import os # import sys import shelve import random import textwrap from time import sleep, time from collections import namedtuple from bearlibterminal import terminal as term # sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)) + '/../') import spaceship.strings as strings from .screen_functions import * ...
from __future__ import print_function from future.utils import iteritems from builtins import range, str, object import os import sys import time import inspect import itertools import numpy as np from contextlib import contextmanager from peri import initializers from peri.logger import log log = log.getChild('util'...
<filename>src/peltak/extra/gitflow/logic/task.py<gh_stars>1-10 # Copyright 2017-2020 <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 # # ...
<filename>backend/app.py<gh_stars>0 from flask import Flask, redirect, sessions, request, jsonify, session, abort from flask_sqlalchemy import SQLAlchemy from sqlalchemy.sql import func import requests import os from models import db, User, Points, Event from dotenv import load_dotenv from flask_jwt_extended import ( ...
<reponame>socialmediaie/EDNIL2020<filename>utils.py import xml.etree.ElementTree as ET from pathlib import Path from collections import Counter from collections import defaultdict import json import pandas as pd CLASS_MAP={ "MAN_MADE_EVENT": "MANMADE_DISASTER", "NATURAL_EVENT": "NATURAL_DISASTER" } def t...
#!/usr/bin/env python # coding: utf-8 # In[5]: import pandas as pd import os import numpy import MySQLdb import omdtfn as odt #conn= MySQLdb.connect("localhost","root","admin","omdb") #df_mysql = pd.read_sql("select * from sitedb",conn) omdb = os.getcwd() + "\\" + "OMDB.csv" pntxt = os.getcwd() + "\\" + "Periodic_N...
# Copyright The IETF Trust 2016-2019, All Rights Reserved # -*- coding: utf-8 -*- from __future__ import absolute_import, print_function, unicode_literals # various utilities for working with the mailarch mail archive at # mailarchive.ietf.org import contextlib import datetime import tarfile import mailbox import ...