text stringlengths 957 885k |
|---|
<filename>du/android/adb/App.py
from os import system
from du.android.adb.Adb import Adb
import sys
import logging
import cmd2
import time
import argparse
from collections import namedtuple
from cmd2 import with_argparser
logger = logging.getLogger(__name__.split(".")[-1])
ProcInfo = namedtuple("ProcInfo", "cpu,memor... |
<filename>tabulate/t_print.py
#!/usr/bin/python
from model import Table
def t_print(table, \
table_name = None, \
footer_str = None, \
corner = '+', \
column_sep = '|', \
row_sep = '-', \
box_width = 0, \
col_width_adjust = 2, \
... |
from .isolationTester import Session, Step, Permutation, TestSpec, Pstep, Blocker
from .parser.specParserVisitor import specParserVisitor
# Generated from specParser.g4 by ANTLR 4.9.3
from antlr4 import *
from .parser.specParser import specParser
# This class defines a complete generic visitor for a parse tree produ... |
import os
import sys
import argparse
import roblib
__author__ = '<NAME>'
def read_blast_file(filename, query=True, evalue=10, bitscore=0):
"""
Read the blast output file and return a dict of hits that has contig, start, stop.
# crAssphage_C NODE_1_length_14386_cov_54.5706_ID_1703 94.64 1157 62 ... |
NOTE_OFF_STATUS = 128
NOTE_ON_STATUS = 144
CC_STATUS = 176
NUM_NOTES = 127
NUM_CC_NO = 127
NUM_CHANNELS = 15
NUM_PAGES = 4
PAGES_NAMES = (('P', 'o', 's', 'i', 't', 'i', 'o', 'n', ' ', '&', ' ', 'T', 'e', 'm', 'p', 'o'),
('C', 'l', 'i', 'p', ' ', '&', ' ', 'T', 'e', 'm', 'p', 'o'),
('V', 'o', 'l', 'u', 'm', 'e', ' ', ... |
import copy
import numpy as np
class Particle:
def __init__(self, x_0, v):
self.x = x_0
self.v = v
self.n_constraints = None
self.p_best = None
self.pos_p_best = None
self.n_constraints_best = None
class Swarm:
def __init__(self, function, dimen... |
<filename>asana_extensions/general/config.py<gh_stars>0
#!/usr/bin/env python3
"""
This module handles access to the configuration files. The configuration
files--including the environment files--are accessed by the other python scripts
through this file.
This is setup such that other files need only call the `get()`... |
<filename>time_measure.py<gh_stars>10-100
from umap import umap_
import numpy as np
import timeit
from gensim.models.keyedvectors import KeyedVectors
from utils import pca, run_umap, run_umap2, run_tsne, draw_plot, load_merge_cifar, load_merge_mnist
# from sklearn.datasets import load_digits
timeit.template =... |
from __future__ import annotations
import collections
import os
import shutil
import sys
import sysconfig
from contextlib import contextmanager
from pathlib import Path
from typing import TYPE_CHECKING, Any, Dict, Iterator, List, Optional, Tuple
from pip._internal.req import req_uninstall
from pip._internal.utils imp... |
<gh_stars>0
from functools import partial
from typing import Dict, List
import numpy as np
import argparse
import helper as Helper
def original(start: int, end: int, rank_map: Dict[int, int]) -> List:
""" Temporal evaluation metric as seen in the original HyTE code and paper."""
ranks = []
for time in ran... |
<gh_stars>0
import mimetypes
import pathlib
from dataclasses import dataclass
import boto3
from botocore.exceptions import ClientError
from scripts.commands import settings
from scripts.commands.auth0_handler import management_api
BASE_DIR = pathlib.Path(__file__).resolve().parent.parent.parent
@dataclass(frozen... |
<gh_stars>0
import unittest
import softwareprocess.angles.Longitude as Long
class LongitudeTest(unittest.TestCase):
def setUp(self):
self.longitudeTooLowStr = 'The longitude specified is too low! It must be greater than or equal to 0 degrees and 0.0 minutes'
self.longitudeTooHighStr = 'The longit... |
# -*- coding: utf-8 -*-
'''
Tests for the SVN state
'''
# Import python libs
from __future__ import absolute_import, unicode_literals, print_function
import os
import shutil
import socket
# Import Salt Testing libs
from tests.support.case import ModuleCase
from tests.support.paths import TMP
from tests.support.mixin... |
<reponame>Zilched/docker-weewx
#
# Copyright (c) 2009-2021 <NAME> <<EMAIL>>
#
# See the file LICENSE.txt for your full rights.
#
"""weedb driver for the MySQL database"""
import decimal
import six
try:
import MySQLdb
except ImportError:
# Some installs use 'pymysql' instead of 'MySQLdb'
import pymys... |
# bruteforce imports
from bruteforce.bruteforce import bruteforce
# configs imports
from configs import configs
# crawler imports
from crawler.crawler import Crawler
# funcs imports
from funcs.tokenizer import tokenize_html
# network imports
from network.Socket import Socket
from network.HttpRequest import HttpRequ... |
<reponame>clatterrr/NumericalComputationProjectsCollection<filename>FiniteElement/fem50/fem50.py
import numpy as np
import math
"""
D:\FluidSim\FluidSim\FEMNEW\fem50-master\src
https://github.com/cpraveen/fem50
Remarks around 50 lines of Matlab: short finite element implementation
"""
coordinates = np.array([[0,0],... |
<filename>src/booking/views.py
import datetime
from datetime import timedelta
from django.urls import reverse
from django.shortcuts import render, redirect, get_object_or_404
from django.http import Http404
from django.contrib import messages
from usermgmt.models import Profile
from .models import Activity, Ticket
from... |
#!/usr/bin/python
#analyza.py
import sys
import os
import json
import cx_Oracle
from modules import *
#------------------------------------------------------------------------------
# MAIN driver code
#------------------------------------------------------------------------------
if __name__ == "__main__":
if... |
# Copyright 2022 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
# -*- coding: utf-8 -*-
import datetime
import json
import uuid
import requests
from catalog.model.product import Product, ProductSchema
def test_get_products():
"""
Test for get_products
:return:
"""
try:
products = requests.get('http://127.0.0.1:5000/products')
assert products... |
# -*- coding: utf-8 -*-
# Copyright 2021 Cohesity Inc.
class AzureParams(object):
"""Implementation of the 'AzureParams' model.
Specifies various resources when converting and deploying a VM to Azure.
Attributes:
availability_set_id (long|int): Specifies id of the Availability set
i... |
## Animate fractals from an iterated function system
## by <NAME>
## <EMAIL>
## earlbellinger.com
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from tqdm import tqdm
from easing import easing
from PIL import ImageColor # for rgb
from numba import jit
from joblib import Para... |
# Copyright (c) 2020 The Regents of the University of Michigan
# All rights reserved.
# This software is licensed under the BSD 3-Clause License.
import unittest
import os
import io
import warnings
import tempfile
import subprocess
from itertools import chain
from ddt import ddt, data
import garnett
import numpy as np
... |
<gh_stars>0
from abc import ABC, abstractmethod
import numbers
import numexpr as ne
import numpy as np
from .. import metrics
from .. import minimizers
class Refocus(ABC):
def __init__(self, field, wavelength, pixel_size, medium_index=1.3333,
distance=0, kernel="helmholtz", padding=True):
... |
<reponame>tango4j/loss-balance
import torch
import numpy as np
import ipdb
from utils import *
from losses import ContrastiveLoss_mod as const_loss
import copy
import operator
import matplotlib
import matplotlib.pyplot as plt
matplotlib.use('Agg')
from pylab import logspace
import matplotlib as mpl
import warnings
war... |
import json
import logging
import csv
import pkg_resources
from oic.extension.token import JWTToken
from oic.utils.authn.authn_context import AuthnBroker
from oic.utils.authn.client import verify_client
from oic.utils.authz import AuthzHandling
from oic.utils.keyio import keyjar_init
from oic.utils.sdb import Session... |
# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!
"""Client and server classes corresponding to protobuf-defined services."""
import grpc
import blockchain_pb2 as blockchain__pb2
import common_pb2 as common__pb2
import controller_pb2 as controller__pb2
class RPCServiceStub(object):
"""Missing... |
#! /bin/env python
# -*- coding: utf-8 -*-
import pandas as pd
import numpy as np
from gensim.models.word2vec import Word2Vec
from keras.preprocessing import sequence
import keras.utils
from keras import utils as np_utils
from keras.models import Sequential
from keras.models import model_from_yaml
from keras.layers.e... |
<reponame>scalasm/my-notes<filename>lambda/mynotes/core/notes.py
import logging
import uuid
from abc import ABC, abstractmethod
from dataclasses import dataclass
from datetime import datetime
from enum import Enum
from typing import List
from mynotes.core.architecture import (DataPage, DataPageQuery, DomainEntity, Obj... |
import os
import argparse
import matplotlib.pyplot as plt
from numpy.core.multiarray import empty
import pandas as pd
import numpy as np
import sys
from keras.models import load_model
from keras.backend import clear_session
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM... |
<filename>hyp/base.py
"""Base classes for the ``Responders`` and ``Adapters``.
"""
import json
from .collector import Collector
from six import iteritems
from .helpers import *
from .constants import JSONAPI_VERSION_DICT
class NonCompliantException(Exception):
pass
class BaseResponder(object):
TYPE = None
... |
###
# Copyright (c) 2005,2008, <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 conditions, ... |
import FWCore.ParameterSet.Config as cms
# This is used to modify parameters for Run 2 (see bottom of file)
#Global fast calorimetry parameters
from FastSimulation.Calorimetry.HcalResponse_cfi import *
from FastSimulation.Calorimetry.HSParameters_cfi import *
#from FastSimulation.Configuration.CommonInputs_cff import... |
import os
import glob
import nska_deserialize as nd
from scripts.artifact_report import ArtifactHtmlReport
from scripts.ilapfuncs import logfunc, tsv, timeline, is_platform_windows
def get_bundle_id_and_names_from_plist(library_plist_file_path):
'''Parses Library.plist and returns a dictionary where Key=B... |
<reponame>camiloaruiz/goatools
"""Test TermCounts object used in Resnik and Lin similarity calculations."""
from __future__ import print_function
import os
import sys
from goatools.base import get_godag
from goatools.associations import dnld_assc
from goatools.semantic import TermCounts
from goatools.semantic import ... |
from django.contrib import admin
from django.contrib.admin.widgets import FilteredSelectMultiple
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import Group
from common.constants import GROUP_WORKING_TYPE_CHOICES
from accounts.forms import GroupForm, UserCreateForm, UserSetPasswordFor... |
"""
Coupling Matrix
===============================================================================
>>> from techminer2 import *
>>> directory = "/workspaces/techminer2/data/"
>>> coupling_matrix(
... top_n=15,
... column='references',
... directory=directory,
... ).head()
document ... |
<filename>src/zsl/utils/deploy/js_model_generator.py
"""
:mod:`zsl.utils.deploy.js_model_generator`
------------------------------------------
.. moduleauthor:: <NAME>
"""
from __future__ import unicode_literals
from builtins import object, range
import hashlib
import importlib
import json
import sys
from typing impo... |
<filename>tictactoe/full_ttt.py
#!/usr/bin/env python3
import argparse
import copy
import sys
# --------------------------------------------------
def get_args():
"""get command-line arguments"""
parser = argparse.ArgumentParser(
description='Two-player Tic-Tac-Toe',
formatter_class=argparse.... |
<reponame>mindspore-ai/models<gh_stars>10-100
# Copyright 2022 Huawei Technologies Co., Ltd
#
# 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
#
# ... |
#specialized version of class SegmentTree2DFast
#(+,+) update-query
class SegmentTree2DSum:
#(uo,ui,qo,qi,uor)=(+,0,+,0,*)
class Node:
def __init__(self,A,AZ):
self.A=A
self.AZ=AZ
class SegmentTree1DSum:
class Node:
def __init__(self,V,Z):
... |
<filename>nox/src/nox/netapps/monitoring/monitoring.py
'''monitoring core'''
# Written for Ripcord by
# Author: <NAME> (<EMAIL>)
# Ported to NOX to use LAVI/messenger by
# Author: <NAME> (<EMAIL>)
import time
import logging
from collections import defaultdict
from collections import deque
from twisted.python import l... |
# -*- coding: utf-8 -*-
import abc
import logging
import datetime
import functools
import httplib as http
import time
import urlparse
import uuid
from flask import request
from oauthlib.oauth2.rfc6749.errors import MissingTokenError
from requests.exceptions import HTTPError as RequestsHTTPError
from modularodm impor... |
<reponame>Meng-Xiang-Rui/qusource
import numpy as np
from scipy.linalg import expm
import matplotlib.pyplot as plt
import scipy.stats as stats
from scipy.stats import bernoulli
import random
trans_mat = np.zeros((4, 10))
trans_mat[0, 1] = trans_mat[1, 3] = trans_mat[2, 4] = trans_mat[3, 8] = 1
def int2bin(n, count=2... |
"""!
@brief Graph representation (uses format GRPR).
@authors <NAME> (<EMAIL>)
@date 2014-2020
@copyright BSD-3-Clause
"""
import matplotlib.pyplot as plt
from matplotlib import colors
from enum import IntEnum
class type_graph_descr(IntEnum):
"""!
@brief Enumeration of graph description... |
<gh_stars>1000+
"""
Unit tests for the Deis api app.
Run the tests with "./manage.py test api"
"""
from __future__ import unicode_literals
import json
import urllib
from django.contrib.auth.models import User
from django.test import TestCase
from django.test.utils import override_settings
from rest_framework.authto... |
# -*- coding: utf-8 -*-
###############################################################################
#
# Copyright (c) 2019 HERE Europe B.V.
#
# SPDX-License-Identifier: MIT
# License-Filename: LICENSE
#
###############################################################################
import math
# hth G... |
<filename>python/zyzzyva.py
import time
import json
import hashlib
msg_types = {}
class MessageType:
def __init__(self, t):
self.t = t
msg_types[t] = self
def __str__(self):
return self.t
def str(self):
return self.t
def __repr__(self):
return 'MessageType(' + repr(self.t) + ')'
REQUEST = ... |
import characterquests
from characterutil import *
def sz_01_10_Wandering_Isle(count,datatree,openfile):
characterquests.charquestheader(count,"01-10: Wandering Isle",openfile)
def z_80_90_Jade_Forest(count,datatree,openfile):
characterquests.charquestheader(count,"80-90: Jade Forest",openfile)
characterquests.cha... |
<gh_stars>0
# Version: 2020.02.21
#
# MIT License
#
# Copyright (c) 2018 <NAME> and <NAME>
#
# 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 limit... |
<gh_stars>0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Mar 25 10:37:17 2021
@author: yonnss
"""
import tt
import scipy.io
import numpy as np
from CME import CME,Gillespie,CompleteObservations,Observations_grid
import matplotlib.pyplot as plt
import scipy.integrate
import tt.amen
import datetim... |
<filename>vgg_train.py
import torch.optim as optim
import torch.nn as nn
import time
import os
import datetime
from cifar10.tnt_solver import *
from collections import OrderedDict
from collections import namedtuple
from itertools import product
from cifar10.classifiers.vgg import *
import torchnet.meter as me... |
<reponame>StuartDAdams/SYCL-CTS<gh_stars>0
#!/usr/bin/env python3
import os
import subprocess
import sys
import xml.etree.ElementTree as ET
import json
import argparse
REPORT_HEADER = """<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet xmlns="http://www.w3.org/1999/xhtml" type="text/xsl" href="#stylesheet"?>
<!... |
<reponame>OpheliaMiralles/pykelihood<filename>tests/test_stats_utils.py
import numpy as np
import pandas as pd
import pytest
from pykelihood import kernels
from pykelihood.distributions import GEV, Distribution
from pykelihood.stats_utils import Profiler
@pytest.fixture(scope="module")
def likelihood(dataset):
f... |
# This is a sample mean-reversion algorithm on Quantopian for you to test and adapt.
# Algorithm investment thesis:
# Top-performing stocks from last week will do worse this week, and vice-versa.
# Every Monday, we rank high-volume stocks based on their previous 5 day returns.
# We go long the bottom 20% of stock... |
import os
import glob
# Our numerical workhorses
import numpy as np
import pandas as pd
import scipy.special
# Import the project utils
import sys
sys.path.insert(0, '../')
import image_analysis_utils as im_utils
# Useful plotting libraries
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import matplotlib... |
import unittest
import pyrepscan
class RulesManagerTestCase(
unittest.TestCase,
):
def test_should_scan_file_ignored_extensions(
self,
):
rules_manager = pyrepscan.RulesManager()
self.assertTrue(
expr=rules_manager.should_scan_file_path('file.txt'),
)
... |
<reponame>Ornendil/logout<filename>logout2.py
#!/usr/bin/python3
# coding: utf-8
#Innstillinger
# Hvor mange sekunder med inaktivitet før brukeren får beskjed om at han snart logges ut
loggUtBeskjedTid = 1 * 60
# Hvor mange sekunder etter det igjen før brukeren logges ut
loggUtTid = 4 * 60
import cairo
import gi
gi... |
from flask import Flask, flash, redirect, render_template, request, url_for, send_file
from flask_wtf import Form, FlaskForm
from wtforms import Form, TextField, TextAreaField, validators, StringField, SubmitField, SelectField, IntegerField
from flask_wtf.file import FileField, FileAllowed, FileRequired
from werkzeug i... |
import sys, os, json, io, csv
# from django.http import Http404
# from django.shortcuts import get_object_or_404, render
# from django.http import JsonResponse, HttpResponse
# from django.core.urlresolvers import reverse
from django.views.decorators.csrf import csrf_exempt
import traceback
import pymongo
from urllib.pa... |
<reponame>textileio/pygate-gRPC
from typing import Iterable, List, Tuple
from deprecated import deprecated
from google.protobuf.json_format import Parse
from proto import ffs_rpc_pb2, ffs_rpc_pb2_grpc
from pygate_grpc.errors import ErrorHandlerMeta, future_error_handler
TOKEN_KEY = "x-ffs-token"
CHUNK_SIZE = 1024 * ... |
# -*- mode: python; coding: utf-8 -*
# Copyright (c) 2018 Radio Astronomy Software Group
# Licensed under the 2-clause BSD License
"""Tests for HDF5 object
"""
from __future__ import absolute_import, division, print_function
import os
import copy
import numpy as np
import nose.tools as nt
from astropy.time import Ti... |
<filename>celery/tests/test_worker_control.py<gh_stars>1-10
import socket
import unittest2 as unittest
from celery import conf
from celery.decorators import task
from celery.registry import tasks
from celery.task.builtins import PingTask
from celery.utils import gen_unique_id
from celery.worker import control
from cel... |
# TODO: real error handling
# TODO: fix how ports work
from curses import A_REVERSE
INT_MIN = -999
INT_MAX = 999
CODE_LINES = 15
LINE_LEN = 18
MODE_RUN = 0
MODE_READ = 1
MODE_WRITE = 2
SRC = 0
DST = 1
LABEL = 2
REG_PORTS = ["UP", "DOWN", "LEFT", "RIGHT"]
PORTS = REG_PORTS + ["ANY", "LAST"]
REGISTERS = ["ACC", "N... |
"""Config flow for Metlink departure info."""
# Copyright 2021 <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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless ... |
import unittest
from project.hero import Hero
class TestHero(unittest.TestCase):
USERNAME = "Main hero"
LEVEL = 10
HEALTH = 1000.1
DAMAGE = 100.2
def setUp(self):
self.hero = Hero(self.USERNAME, self.LEVEL, self.HEALTH, self.DAMAGE)
def test_hero__expect_valid_name_attr(self):
... |
# Copyright (c) 2020, eQualit.ie inc.
# 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.
from baskerville.features.feature_minutes_total import FeatureMinutesTotal
from baskerville.util.enums import FeatureComputeT... |
<filename>dissertation/fetch.py<gh_stars>1-10
# Fetch all elasticity, piezo and diel properties from Material Project
from pymatgen import MPRester
from pymatgen.io.cif import CifWriter
import csv
if __name__ == '__main__':
MAPI_KEY = '<KEY>' # You must change this to your Materials API key! (or set MAPI_KEY env ... |
#!/usr/bin/env python
import datetime
import json
import os
import pathlib
import re
import sys
from typing import List, Optional, Tuple
from vaccine_feed_ingest_schema import location as schema
from vaccine_feed_ingest.utils.log import getLogger
from vaccine_feed_ingest.utils.validation import BOUNDING_BOX
logger ... |
<filename>Mathstein/mathroot.py
#!/usr/bin/env python
# coding: utf-8
# In[26]:
import math, cmath
import numpy as np
def graphgen(coeff):
"""
Generates a graph for any given equation
:param coeff: list of all the coefficients of an equation
:return: Graph object plotted based on the equati... |
import torch
from torch import nn
from tvae.nn.modules import (MultiHeadAttention, PositionalEmbedding,
PositionWise)
class TransformerEncoderLayer(nn.Module):
def __init__(self, dim_m, dim_q_k, dim_v, n_heads, dim_i, dropout):
"""Transformer encoder layer.
Args:
... |
<reponame>deepset-ai/Haystack<filename>haystack/nodes/question_generator/question_generator.py
from typing import List, Union, Optional, Iterator
import itertools
from transformers import AutoModelForSeq2SeqLM
from transformers import AutoTokenizer
from haystack.errors import HaystackError
from haystack.schema import... |
# python3
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in... |
<reponame>vika-sonne/sam-ba-loader
#
# Open Source SAM-BA Programmer
# Copyright (C) <NAME>, 2016.
#
# dean [at] fourwalledcubicle [dot] com
# www.fourwalledcubicle.com
#
#
# Released under a MIT license, see LICENCE.txt.
from .import ChipIdentifier
class CHIPID(ChipIdentifier.ChipIdentifierBase):
"... |
<filename>isi_sdk/apis/storagepool_api.py
# coding: utf-8
"""
StoragepoolApi.py
Copyright 2016 SmartBear Software
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.... |
# coding=utf-8
import numpy as np
import scipy.interpolate as intpl
import scipy.sparse as sprs
def to_sparse(D, format="csc"):
"""
Transform dense matrix to sparse matrix of return_type
bsr_matrix(arg1[, shape, dtype, copy, blocksize]) Block Sparse Row matrix
coo_matrix(arg1[, shape, dtype, ... |
from bs4 import BeautifulSoup as bs
from splinter import Browser
import pandas as pd
import time
# Initialize browser
def init_browser():
executable_path = {'executable_path': '/usr/local/bin/chromedriver'}
return Browser('chrome', **executable_path, headless=False)
def scrape():
# # NASA Mars News
... |
import os
import shutil
import zipfile
import urllib.parse
import urllib.request
import torch
import torch.utils.data
from dataset import *
import pickle
from sklearn.manifold import TSNE
import matplotlib.pyplot as plt
import numpy as np
import csv
from collections import Counter, defaultdict
def maybe_download_and... |
<filename>custom_envs/spurious_predator_prey_env.py
import curses
import gym
import numpy as np
from gym import spaces
class SpuriousPredatorPreyEnv(gym.Env):
def __init__(self,):
self.__version__ = "0.0.1"
self.vision = 0
self.OBS_CLASS = 3
self.OUTSIDE_CLASS = 2
self.PR... |
<filename>python/code/training.py
# The MIT License (MIT)
# =====================
#
# Copyright © 2020 Azavea
#
# 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, includin... |
#!/usr/bin/python
import json
import numpy as np
import math
import sys
import argparse
from SetupLUT import FP2FIX, SetupTwiddlesLUT, SetupSwapTable, SetupSwapTableR4, SetupDCTTable, SetupLiftCoeff, SetupTwiddlesRFFT, MFCC_COEFF_DYN
def array_to_def_c_file(arr, name, data_type, size, elem_in_rows=2):
Out_str = ""
#... |
<filename>fractalis/data/etl.py
"""This module provides the ETL class"""
import abc
import json
import logging
import os
from Cryptodome.Cipher import AES
# noinspection PyProtectedMember
from celery import Task
from pandas import DataFrame
from fractalis import app, redis
from fractalis.data.check import IntegrityC... |
# -*- coding: utf-8 -*-
"""
Created on Thu May 4 11:33:01 2017
@author: gualandi
"""
import numpy as np
from gurobipy import Model, GRB, quicksum, tuplelist
def ComputeDistanceMatrix(n, p=2):
""" Compute the ground distance with power p of an n*n image """
C = {}
for i in range(n):
for j in rang... |
# Copyright 2014 - Mirantis, 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... |
<filename>kaspersky/src/kaspersky/master_yara/importer.py
"""Kaspersky Master YARA importer module."""
from typing import Any, Mapping, Optional
from pycti import OpenCTIConnectorHelper # type: ignore
from stix2 import Bundle, Identity, MarkingDefinition # type: ignore
from stix2.exceptions import STIXError # typ... |
<reponame>D-ICE/chrono<filename>src/demos/python/chrono-tensorflow/envs/chtrain_pendulum.py<gh_stars>1-10
import pychrono as chrono
from pychrono import irrlicht as chronoirr
#from pychrono import postprocess
import numpy as np
class Model(object):
def __init__(self, render):
self.render = render
#sel... |
from copy import deepcopy
import jsonschema
from django.contrib.postgres.fields.jsonb import JSONField
from django.core import exceptions
from django.db import DataError, connection, models
from prettytable import from_db_cursor
from rest_framework import exceptions
from .utils import DefaultValidatingDraft4Validator... |
import numpy as np
import theano
import theano.tensor as T
from theano.tensor.nnet import conv2d
from theano.tensor.signal import downsample
from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams
import sys
import glob
import matplotlib.pyplot as plt
from sklearn.cross_validation import train_test_split
... |
<reponame>mjq11302010044/TATT
import math
import torch
import torch.nn.functional as F
from torch import nn
from collections import OrderedDict
import sys
from torch.nn import init
import numpy as np
from IPython import embed
sys.path.append('./')
sys.path.append('../')
from .recognizer.tps_spatial_transformer import ... |
import pandas as pd
import random as rd
rd.seed(2020)
def read_csv(filename):
file = pd.read_csv(filename)
file.fillna(" ", inplace=True)
return file
def save_csv(filename, data):
data.to_csv(filename, mode="w", index=False)
def train_shuffle_before_after(data):
data_size =... |
#!/usr/bin/env python3
import sys
import socket
from time import sleep
import threading
import socket
from enum import Enum, auto
SYNCWORD_H = 0xBE
SYNCWORD_L = 0xEF
class ParseState(Enum):
SYNC_H = 0
SYNC_L = 1
FLAGS = 2
CMD = 3
PAYLOAD_LEN = 4
PAYLOAD = 5
CHKSUM_H = 6
CHKSUM_L = 7... |
import itertools
import random
import collections
import operator
import functools
from scipy import ndimage
import numpy as np
import matplotlib
from panoptic_parts.utils.format import decode_uids
from panoptic_parts.utils.utils import _sparse_ids_mapping_to_dense_ids_mapping
# Functions that start with underscore ... |
<filename>src/main/app-resources/node_flood_extraction/run.py
#!/opt/anaconda/bin/python
# -*- coding: utf-8 -*-
#Classe runSnap legge da una singola cartella i file in essa contenuti
#li ordina in modo decrescente per data e crea
#le coppie per lo start di SNAP
#infine crea il file name da associare all'output di SNAP... |
# Copyright (c) 2018 Midokura SARL
# 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 require... |
<reponame>YU-Zhejian/HERVfinder
import argparse
import os
import sys
from typing import List
from herv_finder import blast
from herv_finder.blast import indexer, search
PROG = "HERVfinder"
BANNER = """
=========================================================
= HERVfinder ... |
<reponame>UnnamedMoose/serialMonitor<gh_stars>1-10
# -*- coding: utf-8 -*-
###########################################################################
## Python code generated with wxFormBuilder (version Sep 19 2018)
## http://www.wxformbuilder.org/
##
## PLEASE DO *NOT* EDIT THIS FILE!
###############################... |
# Copyright (c) 2016-2018 Uber Technologies, 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 agree... |
from os import path
from typing import List, Optional
import pandas as pd
from code_base.excess_mortality.base_eurostat_bulk import (SaveFileMixin,
UN_LOC_VARS,
UN_DECODE_AGE_GROUPS,
... |
import warnings
import numpy as np
import pandas as pd
import sklearn
from sklearn import metrics
class MetricCatalog:
catalog_dict = {
'accuracy': {
'func': metrics.accuracy_score,
'params': {},
'require_score': False,
'binary': True,
'multi': ... |
<filename>src/milannotations/datasets.py<gh_stars>1-10
"""PyTorch datasets that nicely wrap exemplars for every unit in a network."""
import collections
import csv
import pathlib
from typing import Any, Iterable, NamedTuple, Optional, Sequence, Union
from src.deps.netdissect import renormalize
from src.utils.typing im... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.