text stringlengths 3.07k 22.1k |
|---|
from django.db import models
from django.contrib.auth.models import User
from django.core.validators import MaxValueValidator, MinValueValidator
import django.contrib.postgres.fields as pgfields
def assignment_directory_path(instance, filename):
"""Used in FileField option upload_to, to upload the file to
MED... |
from typing import Dict, Any, List
from cobot_core import SelectingStrategy
from cobot_core.offensive_speech_classifier import OffensiveSpeechClassifier
import example.sensitive_response_generator.utils as sensitive_response_utils
from example.dialogues.StateTransitionPrompts import StateTransitionPrompts
from exampl... |
#
# This file is part of LiteDRAM.
#
# Copyright (c) 2021 Antmicro <www.antmicro.com>
# SPDX-License-Identifier: BSD-2-Clause
from migen import *
from litex.build.sim import SimPlatform
from litex.build.sim.config import SimConfig
from litex.build.generic_platform import Pins, Subsignal
from litex.soc.interconnect.cs... |
from src.utils.bbox import BBox
import numpy as np
"""
Pose configuration
"""
class PoseConfig:
# The joint order defined by the system
NAMES = ["head", "leftShoulder", "rightShoulder", "leftElbow", "rightElbow", "leftWrist", "rightWrist", "leftHip",
"rightHip", "leftKnee", "rightKnee", "leftAn... |
"""Módulo para metrificação de ativos e retornos."""
import numpy as np
import pandas as pd
from scipy import stats
def sharpe_ratio(returns, risk_free=0, time_scale=252):
"""
Essa função, a partir da definição do parâmetro de retorno, fornece o sharpe ratio do ativo, com base na média histórica e desvio padr... |
# This script calculates RPKM, when paired end reads are mapped to a contig
# catalogue with BWA MEM. It will not be accurate with single end reads or
# any other mapper than BWA MEM.
# Theory:
# We want a simple way to estimate abundance of redundant contig catalogues.
# Earlier we used to run analysis on deduplicate... |
# %%
from __future__ import print_function, division
import copy
import time
import datetime
import random
import os
from tqdm import tqdm
import pandas as pd
import numpy as np
import argparse
import warnings
import logging
from sklearn.model_selection import KFold
from sklearn.model_selection import train_test_split... |
from qualisys import load_qtm_data
import matplotlib.gridspec as gridspec
from tqdm import tqdm
from data.data_loader import C3DData, Marker
from vis.utils import *
class QTMData():
def __init__(self, src, ax, label="", dims="xyz", bones=None):
"""
:param src:
:param label:
:param dims: xyz if 3D, xy if 2... |
import argparse
from collections import OrderedDict
import copy
import flair
import logging
import numpy as np
import os, sys, time
import pandas as pd
import tempfile
from tqdm import tqdm
import torch
import torch.nn as nn
import transformers
from dataloader import DataLoader
from constants import spacy_pos_dict
... |
import logging
from django.core.management import call_command
from math import ceil
from multiprocessing import Pool, Event, Value
from time import perf_counter
from typing import Generator, List, Tuple
from usaspending_api.broker.helpers.last_load_date import get_earliest_load_date, update_last_load_date
from usasp... |
"""
This module is responsible for defining the RTTI types defined in rttidata.h header:
//
// _RTTIBaseClassDescriptor
//
typedef const struct _s_RTTIBaseClassDescriptor {
#if _RTTI_RELATIVE_TYPEINFO
int pTypeDescriptor; // Image relative offset of TypeDescriptor
#else
T... |
from mmdet.datasets.builder import PIPELINES
import os
import cv2
import random
import numpy as np
def visual_table_resized_bbox(results):
bboxes = results['img_info']['bbox']
img = results['img']
for bbox in bboxes:
img = cv2.rectangle(img, (int(bbox[0]), int(bbox[1])), (int(bbox[2]), int(bbox[3]... |
import os
from typing import Optional, Union, List
import numpy as np
from persia.prelude import _PersiaBatch
from persia.logger import get_default_logger
_logger = get_default_logger()
# Maximum batch_size supported.
MAX_BATCH_SIZE = 65535
# Skip all PERSIA data checks except batch size.
# Raise RuntimeError w... |
import meshio
import numpy
from . import avsucd, flac3d, pickle, tecplot, tough
from ._mesh import Mesh, from_meshio
__all__ = [
"read",
"write",
"write_points_cells",
"read_time_series",
"write_time_series",
]
_extension_to_filetype = {
".dat": "tecplot",
".f3grid": "flac3d",
".pick... |
import matplotlib.pyplot as plt
import numpy as np
from brian2 import *
def visualise_connectivity(S):
Ns = len(S.source)
Nt = len(S.target)
figure(figsize=(10, 4))
subplot(121)
plot(zeros(Ns), arange(Ns), 'ok', ms=1)
plot(ones(Nt), arange(Nt), 'ok', ms=1)
for i, j in zip(S.i, S.j):
... |
"""Constructs for managing negotiations between Peers."""
import logging
# from .dataconnection import DataConnection
from aiortc import RTCIceCandidate, RTCPeerConnection, RTCSessionDescription
from aiortc.sdp import candidate_from_sdp, candidate_to_sdp
from pyee import AsyncIOEventEmitter
# import { MediaConnection ... |
import re
FILENAME = "HPatPS.txt"
def main():
passphrase = "<PASSWORD>."
phrase = ""
escape = "escape"
while (phrase != passphrase):
print(passphrase)
print("Type the passphrase above to continue...")
phrase = input(">>> ")
if (phrase == escape):
return... |
from tkinter import Tk, Text, Menu, filedialog, Label, Button, END, W, E, FALSE
from tkinter.scrolledtext import ScrolledText
from prologpy.solver import Solver
def is_file_path_selected(file_path):
return file_path is not None and file_path != ""
def get_file_contents(file_path):
"""Return a string contain... |
import pandas as pd
import numpy as np
from sklearn import preprocessing, svm, ensemble, neighbors, metrics, model_selection, naive_bayes
import time
import sys, os
import pickle
#on assure le compatibilité pour Python 2 et 3
called_version = sys.version_info
if called_version[0] == 2:
from Tkinter import Tk
f... |
"""Summarise network-hazard intersections
Purpose
-------
Collect network-hazard intersection attributes
- Combine with boundary Polygons to collect network-hazard-boundary intersection attributes
- Write final results to an Excel sheet
Input data requirements
-----------------------
1. Correct paths to all... |
# author - <EMAIL>
# script version - 1.1
# python verison - 2.7
import os
import sys
import types
import logging
import argparse
cmdparser = argparse.ArgumentParser(description = 'generate initial HTK V3.5 DNN model')
egroup = cmdparser.add_mutually_exclusive_group()
egroup.add_argument('-v', '--verbose', he... |
import taichi as ti
import taichi_glsl as ts
from mgpcg import MGPCGPoissonSolver
import time
import utils
from utils import *
@ti.data_oriented
class SurfaceTensionStrategy:
def __init__(self, simulator, surface_tension):
self.dim = simulator.dim
self.res = simulator.res
self.dt = simula... |
""" Tests for the `multiformats.multicodec` module. """
from typing import Dict, List, Union
import pytest
from multiformats import multicodec
from multiformats.multicodec import Multicodec
exists_cases = [
"identity",
0x00
]
@pytest.mark.parametrize("name_or_code", exists_cases)
def test_exists(name_or_c... |
# Optimizing Rastrigin's function, using a combination of EA and BO
from typing import Counter
import numpy as np
import pandas as pd
import math
import matplotlib.pyplot as plt
import GPy
import GPyOpt
from GPyOpt.methods import BayesianOptimization
import matplotlib.pyplot as plt
import time
import pickle
import rand... |
from flask import Blueprint, render_template, request, redirect, url_for, flash
import logging
import utils
log = logging.getLogger("Nurevam.site")
limit = 25 #original was 10.
blueprint = Blueprint('customcmd', __name__, template_folder='../templates/custom commands')
name = "custom commands"
description = "Allow... |
"""
Connection pooling and host management.
"""
import logging
import time
from threading import Lock, RLock, Condition
import weakref
try:
from weakref import WeakSet
except ImportError:
from cassandra.util import WeakSet # NOQA
from cassandra import AuthenticationFailed
from cassandra.connection import MAX... |
from django.db import models
# So that we can set the user as a foreign key
from django.conf import settings
# So that we can set date = today
from datetime import datetime
from django.contrib.auth.models import User
from django.contrib.auth import get_user_model
User = get_user_model()
from core.models import Colo... |
# -*- coding: utf-8 -*-
"""
Analogy analyzer units
----------------------
This module provides analyzer units that analyzes unknown words by looking
at how similar known words are analyzed.
"""
from __future__ import absolute_import, unicode_literals, division
import operator
from pymorphy2.units.base import Analo... |
"""Demand probabilistic forecasting"""
import os
import pickle
import MySQLdb
import MySQLdb.cursors
import numpy as np
import pandas as pd
from dotenv import load_dotenv
import statsmodels.api as sm
import matplotlib.pyplot as plt
load_dotenv()
def get_data(sql, filename, output_dir, use_cache):
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 21 11:17:51 2017
@author: dhingratul
"""
# These are all the modules we'll be using later. Make sure you can import them
# before proceeding further.
# %matplotlib inline
from __future__ import print_function
import collections
import math
import n... |
import csv
import sys
import codecs
import psycopg2
import re
from PIL import Image
import configparser
import subprocess
import io
import requests
import urllib
from requests.auth import HTTPBasicAuth
from xml.etree.ElementTree import tostring, fromstring, Element
import time
from os import listdir, environ
from o... |
import numpy
from numba import jit
from . import best_split
from . import misc_functions as m
#from importlib import reload
#reload(m)
#reload(best_split)
cache = False
class _tree:
"""
This is the recursive binary tree implementation.
"""
def __init__(self, feature_index=-1, feature_threshold=None,... |
from days import AOCDay, day
import math
from collections import defaultdict
def borders(data):
top = data[0]
right = ''.join(line[-1] for line in data)
bottom = data[-1]
left = ''.join(line[0] for line in data)
return (top, right, bottom, left)
def mirrors(data):
mirrors = [data]
mirro... |
# Copyright 2018, The TensorFlow Federated 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 applicable law o... |
# -*- coding: utf-8 -*-
# Python 2.7 support.
from __future__ import division
from enum import Enum
from collections import namedtuple
from .techtree import Node as ResearchNode
# Source: http://wiki.kerbalspaceprogram.com/wiki/Parts, as well as in-game info
kspversion = '1.3 / 1.2'
class RadialSize(Enum):
Tin... |
import objects
import datetime
import helpers
import sys
import function
def import_chart_of_account(filename='./data/chartofaccount/ChartofAccounts.csv'):
objects.Account.import_accounts_from_file(filename=filename)
def process_statement(id_, force=False):
# Force means that all lines will be forcefully re... |
import argparse
import pafy
import os
import time
import sys
import threading
import random
from vlcyt.command_handler import CommandHandler
from colorama import Fore, Back, Style
class VLCYT:
"""
Stream YouTube playlist audio in VLC behind the scenes from the command line.
"""
command_string = f"{Fo... |
# -*- coding: utf-8 -*-
#
# Pydro documentation build configuration file, created by
# sphinx-quickstart on Tue Nov 28 16:43:03 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All... |
# Tools for working with GLM data. Mostly adapted from glmtools
import xarray as xr
import numpy as np
import pyproj as proj4
from datetime import timedelta
import warnings
from glmtools.io.lightning_ellipse import lightning_ellipse_rev
from lmatools.coordinateSystems import CoordinateSystem
from lmatools.grid.fixed i... |
from typing import Hashable
import dask.array as da
import numpy as np
from xarray import Dataset
from sgkit import variables
from sgkit.stats.aggregation import call_allele_frequencies
from sgkit.utils import (
conditional_merge_datasets,
create_dataset,
define_variable_if_absent,
)
def identity_by_sta... |
"""
Contains Osiris common IO functions
"""
from datetime import datetime
from typing import Any, Optional, Union, AnyStr, Iterable, IO, Dict
from azure.storage.blob import ContentSettings, StorageStreamDownloader
from azure.storage.blob.aio import StorageStreamDownloader as StorageStreamDownloaderAsync
from azure.sto... |
#!/usr/bin/env python3
"""
Expose a _drawing api similar to the pyx api.
The api uses the first quadrant coordinate system:
y
^
|
|
| positive x and y
|
|
--+-------------------> x
|
"""
from math import pi, sqrt, sin, cos, sqrt, floor
... |
from django import forms
from .models import (InputResult,
RowToColumn,
ColumnToRow,
DeleteDuplicates,
NumbersInWords,
ListSorting,
ChangeCase,
Autofill,
... |
# code by https://github.com/deniskamazur
from lasagne.layers import *
import theano.tensor as T
import theano
from agentnet.memory import LSTMCell, GRUCell, AttentionLayer
from agentnet import Recurrence
from agentnet.learning.generic import get_mask_by_eos
from agentnet.resolver import ProbabilisticResolver
from ag... |
import argparse
import librosa
import librosa.display
import matplotlib.pyplot as plt
import numpy as np
import os
from pathlib import Path
from shutil import copyfile
import pandas as pd
import tensorflow as tf
from tensorflow.data import Dataset
import json
import glob
import functools
import datetime
from pat... |
from typing import Sequence, Union, Tuple
import math
import numpy as np
from numpy import ndarray
from numpy.lib.stride_tricks import as_strided, broadcast_to
__all__ = [
'isscalar',
'isvector',
'ismatrix',
'repeat',
'dilate_map_2d',
'compute_window_slide_size_2d',
'window_slide_2d',
... |
import sqlite3
import os
import time
from flask import g
from app.myfunctions import get_dblp_url
from app.databases.create_sqlitedb import get_mysql_db
curpath = os.path.dirname(os.path.realpath(__file__))
DATABASE = os.path.join(curpath, 'static', 'pycsrankings.sqlite3')
def mysql_get_db():
db = getattr(g, '_... |
#!/usr/bin/env python3 -u
# Copyright (c) 2017-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the LICENSE file in
# the root directory of this source tree. An additional grant of patent rights
# can be found in the PATENTS file in the same directory.
"""
Trans... |
import matplotlib
import matplotlib.pyplot as plt
from PIL import Image
types = ['paper', ' food', 'yard trimmings', 'wood', 'steel', 'rubber and leather', 'textiles', 'aluminum', 'plastic',
'glass']
years = [1960, 1970, 1980, 1990, 2000, 2005, 2010, 2015, 2016, 2017]
years1 = list(range(1960, 2020, 5)) + ... |
import sys
from datetime import datetime, timedelta
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import time
from... |
import logging
import functools
import werkzeug
from odoo import _
from odoo import http
from odoo.http import request
from odoo.tools import ustr
from odoo.osv import expression
from odoo.exceptions import UserError, AccessError, ValidationError
from odoo.addons.website.controllers.main import QueryURL
from .contro... |
# -*- mode: python; coding: utf-8 -*-
# Copyright 2019 the HERA Collaboration
# Licensed under the 2-clause BSD License
"""Test code in hera_librarian/store.py
"""
from __future__ import print_function, division, absolute_import
import pytest
import os
import tempfile
import json
import shutil
from hera_librarian im... |
#!/usr/bin/env python3
# Copyright (c) 2020 SiFive Inc.
# SPDX-License-Identifier: Apache-2.0
import argparse
import configparser
import glob
import os
import pprint
import sys
import jinja2
import pydevicetree
DEFAULT_SOURCE_PATHS = [
".",
"sifive-blocks",
]
def parse_arguments(argv):
arg_parser = arg... |
import logging
from itertools import product
import pandas as pd
from sklearn.model_selection import train_test_split
from greenguard.demo import load_demo
from greenguard.metrics import METRICS
from greenguard.pipeline import GreenGuardPipeline, generate_init_params, generate_preprocessing
LOGGER = logging.getLogge... |
import sys
import os
from train_test_functions import custom_transforms
import torch
import models
from tensorboardX import SummaryWriter
from train_test_functions.sequence_folders_list import SequenceFolder, SequenceFolder_Validation_Full
from train_test_functions.utils import save_path_formatter
from path import Pat... |
import asyncio
import logging
from contextlib import suppress
from functools import partial
from typing import Callable, Type
import aiomisc
import aiormq.exceptions
import pytest
import shortuuid
from aiomisc_pytest.pytest_plugin import TCPProxy
from pamqp.exceptions import AMQPFrameError
from yarl import URL
import... |
#!/usr/bin/env python
"""
Python port of SolarCalc 1.0
This port only the internal calculation routines, thus making
the tool applicable for batch data processing without GUI.
Please contact me, in case I'm violating anything with this...
Not doing it on purpose.. I'm just tired of clicking through the GUI :/
For re... |
'''
@summary: Bootstrapper file to run gui_server, and UI associated with it.
Ensures all routing for pages, error routing, and user sessions are handled.
@author devopsec and mackhendricks
'''
from flask import Flask, render_template, request, jsonify, make_response, url_for, redirect, abort, Markup
import requests #... |
#!/usr/bin/env python
import os
import sys
import re
import getopt
import subprocess
opt_name_resolution = False
data_dir = False
max_results = 50
ip_to_hostname_cache = {}
# global regex to compile
re_tcp = re.compile(r"^tcp")
re_ip_port = re.compile(r"^(.*)[\.:](.*?)$")
re_trim_ip = re.compile(r"^.*:")
def get_... |
import torch
import torch.nn as nn
import numpy as np
from torch import optim
import math
from torch.autograd import Variable
import torch.nn.functional as F
import matplotlib.pyplot as plt
gamma = 0.99
class Environment():
def __init__(self):
self.a = 1.232
self.b = 1.545
self.prev = np.... |
import six
import random as rnd
from bpe import BpePair, PAR_CHILD_PAIR, ORD_PAIR, UNORD_PAIR
TOK_WORD = '<?>'
SKP_WORD = '<sk>'
RIG_WORD = '<]>'
SKIP_OP_LIST = ['lambda', 'exists', 'argmin', 'argmax',
'min', 'max', 'count', 'sum', 'the']
class STree(object):
def __init__(self, in... |
import sys
import os
import argparse
import logging
import json
import time
import numpy as np
import openslide
import PIL
import cv2
import matplotlib.pyplot as plt
from scipy import ndimage
from torch.utils.data import DataLoader
import math
import json
import logging
import time
import tensorflow as tf
from tensorfl... |
###########################################################################
#
# 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/l... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Licensed under a 3-clause BSD style license - see LICENSE.rst
# Original file comes from sncosmo
"""Functions for reading GRB light curves.
Adapted from Python module 'sncosmo'"""
from __future__ import print_function
from collections import OrderedDict as odict
im... |
# -*- coding: utf-8 -*-
"""
This module is used for importing study specific .mat files.
Since all trials will be joined to a single dataset we cannot easily handle
single electrodes/channels from certain trials.
Thus, data loaded with this module is expected to be artifact free already.
"""
from os import path, mkdir... |
#
# Copyright (c) 2021 Airbyte, Inc., all rights reserved.
#
import base64
import hashlib
import os
import re
from abc import ABC
from binascii import hexlify
from datetime import datetime
from typing import Any, Iterable, List, Mapping, MutableMapping, Optional, Tuple
from urllib.parse import parse_qs, urljoin, urlpa... |
"""Tests for the structure objects."""
import io
import pytest
import binobj
from binobj import errors
from binobj import fields
from binobj.pep526 import dataclass
class BasicStruct(binobj.Struct):
"""A basic structure."""
string = fields.String(size=7)
int64 = fields.Int64(endian="big")
uint24 =... |
import decimal
import json
from datetime import date
from accounts.models import Transaction, Wallet
from django.contrib.auth.decorators import login_required
from django.db.models import F
from django.http import (HttpResponse, HttpResponseForbidden,
HttpResponseNotFound)
from django.shortcut... |
import numpy as np
import scipy.sparse.linalg
import scipy.sparse as sparse
from time import time as tm
from einsum_tools import *
# a class to store the operators with the bottom and left indices,
# and bottom and right indices moved to the right for contraction
# while sparse
class SparseOperator():
... |
from colorama import init
import glob
import importlib
import threading
import sys
from datetime import datetime
from logging import DEBUG
import supertrend_ta as ta
import pandas as pd
import time
import ccxt
import requests
import warnings
import schedule
from binance.client import Client
import config
# use for envi... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 17 16:41:11 2020
@author: ssli
Post process of covariance calculation
re-arrange the results to desired forms
"""
import numpy as np
import pandas as pd
import os
# cut matrix into three different parts:
# bb, rr, rb (=br)
# ++++++++++... |
__author__ = "<NAME>"
__version__ = "0.1"
import os, sys
from dataclasses import dataclass
from typing import List
import functools
import operator
import numpy as np
from astropy import units as u
from astropy import constants as const
from astropy.table import QTable, Column
from colorama import Fore
from colorama... |
import io
import os
import random
import sys
from configparser import ConfigParser
from datetime import datetime
from itertools import islice
from pathlib import Path
from statistics import mean, stdev
from time import strftime
from typing import Union, Any, Dict, List
import torch
from torch.utils.data import Dataset... |
# Copyright 2018 Google Inc.
#
# 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 above copyright notice,
# this list of conditions and the following disclaimer.
#
#... |
from manim import *
import numpy as np
import random
class Tute1(Scene):
def construct(self):
plane = NumberPlane(x_range=[-7,7,1], y_range=[-4,4,1]).add_coordinates()
box = Rectangle(stroke_color = GREEN_C, stroke_opacity=0.7, fill_color = RED_B, fill_opacity = 0.5, height=1, width=1)
... |
import numpy as np
import cv2
import matplotlib.pyplot as plt
import matplotlib.image as im
from moviepy.editor import VideoFileClip
#lists to hold prev frames detected lines
prev_leftlines = []
prev_rightlines = []
#Perform color thresholding in HLS color space
def laneColors_mask(img,thresh=[(0,255),(0,255),(0,25... |
# -*- coding: utf-8 -*-
#
# "Tic Tac Toe" Game
#
# Created by LulzLoL231 on 2/24/20.
#
from random import choice
from os import system
from platform import system as OperationSystem
from time import sleep
class Vars(object):
'''Variables class for Tic Tac Toe game\n'''
game_rules = '-= RULES =-\n1. The game... |
#!/usr/bin/env python3
import os
import sys
import struct
import hashlib
import filecmp
import logging
import argparse
import time
CHUNK_SIZE = 4096
SMART_LIMIT = 2**10
def get_info(path):
return { 'path': path, 'stat': os.stat(path) }
def relpath(info):
return info['relpath']
def fileid(info):
return ... |
r"""
--- Day 7: The Sum of Its Parts ---
You find yourself standing on a snow-covered coastline; apparently, you landed a little off course. The region is too
hilly to see the North Pole from here, but you do spot some Elves that seem to be trying to unpack something that washed
ashore. It's quite cold out, so you dec... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 07 14:42:32 2021
@author: silviapagliarini
"""
import os
import numpy as np
import pandas as pd
import csv
from pydub import AudioSegment
import scipy.io.wavfile as wav
def opensmile_executable(data, baby_id, classes, args):
"""
Generate a ... |
"""
@author: <NAME>
"""
import yfinance as yf
import datetime as dt
import pandas as pd
import numpy as np
from pandas.plotting import table
import matplotlib.pyplot as plt
from scipy.stats import levene
# Download historical data for S&P 500
ticker = "^GSPC"
SnP = yf.download(ticker, start="1991-02-01", end="2018-... |
# Copyright (c) 1996-2015 PSERC. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE_MATPOWER file.
# Copyright 1996-2015 PSERC. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
#... |
"""
The features extractor decomposes each URL in the set of selected features and
saves the records in a CSV file. Selected features are: URL size, protocol used
(HTTP/HTTPS), domain and subdomain digit count, symbols count ('@', '~'),
presence
"""
import csv
import re
import subprocess
import urllib.parse as urllib
... |
from PIL import Image, ImageDraw, ImageFont # pip install pillow
import numpy
import cv2
import sys, os
FONT_MARGIN = 2
COLOR_MAP = {
'1': (255, 35, 11),
'0': (16, 194, 20),
'C': (136, 0, 21),
'D': (7, 92, 10)}
OUTPATH = 'output'
def get_attr(info, default=None, isBoolean=False):
value = in... |
import sys
sys.path.append('../utils')
from ops import dense_sum_list, get_shape
from np_op import convert2list
import tensorflow as tf
import numpy as np
import os
def test1(id_=0):
''' dense_sum_list test
Results :
=================Round1===================
const : [4, 2]
[[ 1. ... |
import tilemapbase as tmb
import matplotlib.pyplot as plt
import matplotlib.lines as lines
import folium
from .maputil import copyright_osm
import numpy as np
import re
tmb.init(create=True)
def _extend(m, M, p):
w = M - m
return m - p*w, M + p*w
def _expand(ex, p):
xmin, xmax = _extend(ex.xmin, ex.xma... |
from typing import Optional
from switchmng.schema import *
def query_switch_model(session, resource_id: str) -> Optional[SwitchModel]:
"""
Retrieve :class:`SwitchModel` object from database.
Query the database for a :class:`SwitchModel` object with given resource
identifier and return it.
:param... |
# encoding: utf-8
#
# Copyright © 2020 California Institute of Technology ("Caltech").
# ALL RIGHTS RESERVED. U.S. Government sponsorship acknowledged.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# • Redistributio... |
#!/usr/bin/env python
# Copyright 2019 <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 ... |
"""
This module handles the orders.
Orders are described in the xml files, and are the actions to be executed
for example when keyboard keys are hitted, or in reaction to other orders.
Every order is thus initialized after the parsing fo the xml files
and the created in this file.
Each order is applied to a target cal... |
#!/usr/bin/env python3
"""
A little app that calculates sun rise/set and twilight times.
Copyright (c) 2017 <NAME>. See LICENSE file.
"""
import argparse
import math
import datetime
import sys
import ephem
import ephem.cities
def fatal(text):
print(sys.argv[0] + ": " + text)
sys.exit(1)
def query(city, *... |
#!/usr/bin/env python
# coding: utf-8
version = '0.0.4'
author = """
Emanuele '<NAME>'
Email:<lele [at] quasinormale [dot] it>
Github/Twitter: eldios
"""
from pycodicefiscale import codicefiscale as cf
import datetime
from random import choice as randchoice
from random import randint
import argparse
# script descri... |
"""Iteration unus: a first attempt at a CNN, that uses lower-level API than
iteration-duo.
In the repo solely for journaling purposes.
Does not work due to dimension-related errors that are too stubborn to fix
elegantly, but has been used as the basis for the architecture of
iteration-duo. Has also been used to get a... |
import time
import json
from brownie import *
from rich.console import Console
from assistant.rewards.rewards_utils import calculate_sett_balances
from assistant.subgraph.client import fetch_wallet_balances
from config.badger_config import badger_config
from rich.console import Console
from scripts.systems.badger_syste... |
import re
from datetime import datetime
import six
if six.PY2:
from fieldtypes import SingleNumericType, GenericTextType, \
LocalizedTextType, MultiStringType, MultiNumericType, GenericDictType, \
GenericListDictType, GenericDateTimeType, VersionType
else:
from .fieldtypes import SingleNumeric... |
import torch
import qelos_core as q
import os
def load_data(p="../../datasets/wikitext2/",
batsize=100, eval_batsize=10, seqlen=35):
class Dictionary(object):
def __init__(self):
self.word2idx = {}
self.idx2word = []
def add_word(self, word):
if ... |
import pygame
from pygame.locals import *
pygame.init()
import random
import os
import math
class Mouse(pygame.sprite.Sprite):
def __init__(self):
'''
M.__init__()
Initializes Mouse
'''
pygame.sprite.Sprite.__init__(self)
self.x=0
self.y=0
... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
import csv
import numpy as np
import h5py
import statsmodels.api as sm
#from scipy.stats import wilcoxon
from keras import backend as K
from mnist_mutate import mutate_M2, mutate_M4, mutate_M5
from patsy import dmatrices
import pandas as pd
def cohen_d(orig_accuracy_lis... |
"""
==========================================
Earth Coordinate Conversion with a network
==========================================
In this tutorial, we will show how to place actors on specific locations
on the surface of the Earth using a new function.
"""
from fury import window, actor, utils, io
import matplotl... |
#!/bin/env python
from __future__ import print_function, unicode_literals
import argparse
import json
import logging
import os
import re
import shutil
import sys
import tempfile
from functools import partial
from hashlib import sha256
from io import BytesIO
try:
from urllib.parse import urljoin, urlsplit
except I... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.