content stringlengths 5 1.05M |
|---|
# Generated by Django 3.2 on 2021-07-25 11:04
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('cart', '0004_comment_image'),
]
operations = [
migrations.AddField(
model_name='colourvariation',... |
from typing import Callable
from tsdemux.es import Es
from tsdemux.psi import PsiTableReader
class PmtTableReader(PsiTableReader):
def __init__(self, pid, program_id,
on_pcr_pid_changed: Callable[[int, int], None],
on_stream_added: Callable[[int, int, Es], None],
... |
#!/usr/bin/env python3
from datainterface import DataInterface
from glob import glob
import os
from IPython import embed
# Input folder
# mosaics_folder = ("/media/seba/WD_500GB/tellnet/datasets/mueller/anglikon/"
# "20200425/mosaics")
mosaics_folder = ("/media/seba/WD_500GB/tellnet/datasets/mueller/anglikon/"
... |
import inspect
import sys
from sqlalchemy.dialects.mssql import BIT
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import DECIMAL, Column
from sqlalchemy.sql.expression import table
from planning_system.api.functions import periods
# This Base used by all submodules
Base = declarative_base()
... |
from openslides_backend.permissions.management_levels import OrganizationManagementLevel
from .base import BasePresenterTestCase
class TestGetUSerScope(BasePresenterTestCase):
def test_good(self) -> None:
self.set_models(
{
"meeting/1": {
"name": "meeting1"... |
from Kaspa.modules.abstract_modules.abstractSubmodule import AbstractSubmodule
import random
class ExampleCommandModuleDe(AbstractSubmodule):
module_name = "Example Commands"
language = "de"
EXAMPLE_COMMAND_PATH = \
"Kaspa/modules/core_modules/resources/example_command_module/" + language + "/ex... |
import matplotlib.pyplot as plt
import numpy as np
def plotdata(X, y, wf, wg, desc):
'''
PLOTDATA Plot data set.
INPUT: X: sample features, P-by-N matrix.
y: sample labels, 1-by-N row vector.
wf: true target function parameters, (P+1)-by-1 column vector.
wg: learnt tar... |
from dataclasses import dataclass
from khbr.randutils import create_new_entity
from khbr.KH2.schemas.random_config import RandomConfig
class EnemySeed:
def __init__(self, config: RandomConfig):
self.spawns = {}
self.subtract_map = {}
self.spawn_limiters = {}
self.msn_mapping = {}
... |
import argparse
def get_default_parser():
parser = argparse.ArgumentParser(conflict_handler='resolve')
parser.add_argument('--train_file', default=None, type=str, required=True, help='The input train corpus.')
parser.add_argument('--valid_file', default=None, type=str, required=False, help='The input val... |
from .database import *
from .conf import *
from .data_record import *
from .experiment import *
from .result import *
from .sample import *
from .project import *
|
# -*- coding: utf-8 -*-
"""
Fallback to given artist name when no title/artist detected
"""
def fallback_artist(artist):
"""
Fallback method
"""
def fallback_a(title):
return [artist, title]
return fallback_a
|
import os
from logconf import logconf
LOGFILE = '{}.log'.format(__name__)
# By default, the debug file add a suffix '.dbg' to the logfile. It captures
# everything that prints on the console.
DBGFILE = '{}.dbg'.format(LOGFILE)
def test_show_debug(capsys):
log = logconf(LOGFILE)
msg = 'should see this messag... |
from biosppy import storage
from biosppy.signals import ecg
from ecg_record import EcgRecord
import joblib
if __name__ == '__main__':
rec = EcgRecord.example()
strt, end = 0, 10000
y = rec.get_ecg_samples(0, strt, end)
out = ecg.ecg(signal=y, sampling_rate=1000., show=True)
|
""" TFRecords contain serialized examples. Parsers read in these parsed
examples and return a decoded tf.Tensor.
"""
from typing import Tuple
import tensorflow as tf
def parse_image(serialized: tf.Tensor, channels: int = 3) -> tf.Tensor:
"""Parse an image contained in 'serialized' under the key 'image/enc... |
#!/usr/bin/env python2
from pwn import *
payload = "AAAA%23$x"
p = process('./pwn1')
def enc(payload):
output = ''
for i in range(len(payload)):
if i%2==0:
output+=str(chr(ord(payload[i])-10))
else:
output+=str(chr(ord(payload[i])+10))
return output
payloadFile = o... |
import pytest
import numpy as np
from ..irr import (compute_ts,
simulate_ts_dist,
simulate_npc_dist)
from ..data import nsgk
R = 10
Ns = 35
from numpy.random import RandomState
RNG = RandomState(42)
res = RNG.binomial(1, .5, (R, Ns))
def test_irr():
rho_s = compute_ts(re... |
# coding=utf-8
from __future__ import unicode_literals
from ipaddress import IPV4LENGTH, IPV6LENGTH, ip_address, ip_network
from text_unidecode import unidecode
# from faker.generator import random
# from faker.providers.lorem.la import Provider as Lorem
from faker.utils.decorators import lowercase, slugify, slugify... |
#! /usr/bin/env python
import pathlib
from datetime import datetime, timedelta, timezone
import logging
from pyschism.mesh import Hgrid, Vgrid, Fgrid
from pyschism import ModelDomain, ModelDriver, Stations
from pyschism.forcing import Tides
from pyschism.forcing.atmosphere.nws.nws2 import NWS2
from pyschism.forcing.at... |
class CustomException(Exception):
def __init__(self, *args):
if args:
self.message = args[0]
else:
self.message = None
def get_str(self, class_name):
if self.message:
return '{0}, {1} '.format(self.message, class_name)
else:
return... |
# 2.6 : Transformar un script en una función
# 2.8 : Administración de errores
# 2.9 : Funciones de la biblioteca
# Modificado : 3.8: Un ejemplo práctico de enumerate()
# Modificado : 3.9: La función zip()
import csv
def costo_camion(archivo):
costo = 0.0
with open (archivo, 'rt') as archivo:
#... |
# Copyright 2019, OpenTelemetry 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 or agreed to i... |
from datetime import datetime
from sqlalchemy import ForeignKey, Column, Integer, String, Boolean, JSON, TIMESTAMP, Enum, FLOAT, Text
from sqlalchemy.orm import relationship
from sqlalchemy import event
from nephele2.rds.orm_base import Model
# NOTE if we want JSON representation of these objects for some reason see:
... |
from django.contrib.auth import get_user_model
from django.urls import reverse
from django.test import TestCase
from rest_framework import status
from rest_framework.test import APIClient
from core.models import Nuwroversion
from manager.serializers import NuwroversionSerializer
NUWROVERIONS_URL = reverse('manager:... |
#!/usr/bin/env python
from __future__ import print_function
import rospy
from tf.transformations import quaternion_from_euler
from std_msgs.msg import String
from nav_msgs.msg import Odometry, Path
from geometry_msgs.msg import PoseWithCovarianceStamped, PoseStamped
from sensor_msgs.msg import Joy
import sys
import js... |
#!/usr/bin/env python3
from __future__ import annotations
from typing import List, Protocol, Sequence, Set, Type, runtime_checkable, Dict, Any
import asyncio
import enum
import dataclasses
class ComponentKind(str, enum.Enum):
BEHAVIOUR = "Behaviour"
TRIGGER = "Trigger"
CONDITION = "Condition"
ACTIO... |
import numpy as np
import pandas as pd
from scipy.optimize import curve_fit
import time
def powerlaw(x, A, s):
return A * np.power(x, s)
def fit_powerlaw(row):
X = np.arange(row.shape[0]) + 1.0
params, cov = curve_fit(f=powerlaw, xdata=X, ydata=row, p0=[100, -1], bounds=(-np.inf, np.inf))
time.sleep(0... |
import torch
from tsl.nn.metrics.metric_base import MaskedMetric
import torch.nn as nn
class MaskedMultiLoss(MaskedMetric):
r"""
Adapted from: https://github.com/jdb78/pytorch-forecasting/blob/master/pytorch_forecasting/metrics.py
Metric that can be used to combine multiple metrics.
Args:
metr... |
from flask_table import Table, Col, DatetimeCol, BoolCol
class BlockchainTable(Table):
# Class to format the table
classes = ['table', 'table-striped']
from_user = Col('From')
to_user = Col('To')
amount = Col('Amount')
timestamp = DatetimeCol('Timestamp', datetime_format='full')
nonce = C... |
from push_message import Push_message
|
#!/usr/bin/env python3
# coding: utf-8
import os
import sys
import subprocess
cflags = "-O3 -g -std=gnu99 -I. -Iapps -pipe -mmmx -msse -msse2 -fplan9-extensions -Wall -Wextra -Wno-unused-parameter"
class Classifier(object):
dependency_hints = {
# Toaru Standard Library
'<toaru/kbd.h>': ... |
'''
Created on Sep 6, 2021
@author: mhindle
'''
import numpy as np
import numbers
from typing import Tuple, List, Dict, Union, Set
import itertools
from collections import defaultdict
import pandas as pd
class JointAllellicDistribution(object):
def __init__(self, snp_ordered, chromosome2snp=None, pseudocount = 1... |
import pytest
from opennem.utils.numbers import sigfig_compact, trim_nulls
@pytest.mark.parametrize(
"number,number_expected",
[
(0, 0),
(0.0, 0),
(1, 1),
(1.0, 1),
(-1.0, -1),
(0.012, 0.012),
(-0.012, -0.012),
(123.01, 123),
(1234.9, 12... |
#/usr/bin/python
#Author: Raj Bindra
import sys
from lxml import etree
from getpass import getpass
from jnpr.junos import Device
from jnpr.junos.utils.start_shell import StartShell
from pprint import pprint
import re
devices = open('device_list1')
devlist = devices.readlines()
user = raw_input('username: ')
passwd = ge... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 10 21:46:41 2021
@author: abda
"""
import numpy as np
import scipy.ndimage
import cv2
def get_gauss_feat_im(im, sigma=1, normalize=True, norm_fac = None):
"""Gauss derivative feaures for every image pixel.
Arguments:
image: a 2D im... |
#Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
#Licensed under the Apache License, Version 2.0 (the "License");
#you may not use this file except in compliance with the License.
#You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
#Unless required by applicable l... |
from django.apps import AppConfig
from django.utils.translation import gettext_lazy as _
class ShopConfig(AppConfig):
name = 'ddd_shop.store'
verbose_name = _("store")
def ready(self):
try:
import ddd_shop.store.signals # noqa F401
except ImportError:
pass
|
"""
File: errors.py
Author: David Smerkous
Date: Tue Nov 21 2017
The neural network error definitions
"""
class AbstractionError(Exception):
""" Common abstraction errors
Raised when the programmer decides to use an unknown type
"""
def __init__(self, *args, **kwargs):
Exception.__init__(sel... |
from twitch_info.twitch_info import get_stream
from twitch_info.twitch_info import get_user_id
from twitch_info.twitch_info import get_access_token
from twitch_info.twitch_info import InvalidClient
from twitch_info.twitch_info import InvalidOAuthToken
from twitch_info.twitch_info import InvalidUser
from twitch_info.tw... |
from channels.db import database_sync_to_async
from semesters.models import Semester
from students.models import Student
@database_sync_to_async
def create_or_update_student(data):
student = Student.objects.filter(roll_number=data["roll_number"])
created = False
if student.exists():
student = stu... |
"""
Script to verify all examples in the readme.
Simply execute
python test_readme_examples.py
The tests in this file are currently not unittests!
They do plot images.
TODO move this to checks/ ?
"""
from __future__ import print_function, division
import functools
def main():
example_simple_training_setti... |
#
# PySNMP MIB module A3COM-HUAWEI-E1T1VI-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/A3COM-HUAWEI-E1T1VI-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 16:49:57 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 ... |
# Copyright (c) 2020, Xilinx
# 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 and the follow... |
from memoized import memoized
from custom.inddex.ucr.data_providers.mixins import SummaryStatisticsDataMixin
class SummaryStatsNutrientDataProvider(SummaryStatisticsDataMixin):
total_row = None
title = 'Group-level Summary Statistics by Nutrient Intake'
slug = 'group_level_summary_statistics_by_nutrient_... |
def singleton(cls):
"""Change class behavior to singleton.
Singleton can have only one instance.
"""
def singleton_constructor(cls):
if not hasattr(cls, 'instance'):
cls.instance = old_constructor(cls)
return cls.instance
old_constructor = cls.__new__
cls.__new__ = si... |
from __future__ import absolute_import
from django.core.urlresolvers import reverse
from sentry.models import AuditLogEntry, AuditLogEntryEvent
from sentry.testutils import TestCase, PermissionTestCase
class OrganizationAuditLogPermissionTest(PermissionTestCase):
def setUp(self):
super(OrganizationAudit... |
# Copyright 2020 EraO Prosopagnosia Helper Dev Team, Liren Pan, Yixiao Hong, Hongzheng Xu, Stephen Huang, Tiancong Wang
#
# Supervised by Prof. Steve Mann (http://www.eecg.toronto.edu/~mann/)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with th... |
# Copyright (c) 2017 Sony Corporation. 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 applicabl... |
# ===========================================
# generate JVM dumps, heap, system, threads
# for one or more servers
# ===========================================
script_name = "server_inside_none.py"
# ================================================
# show server inside hierarchy
# need to show transportChannels
# ... |
import requests
response = requests.patch(
'http://address:22/path',
params=[('query', 'param')],
headers={'header': 'qvalue'},
data=b'content'
)
print(response.text) |
"""Pages, Domain and Review indexes for getting by uuid
Revision ID: 4ab7a2e91f2d
Revises: 5edcaddd6c9
Create Date: 2013-11-27 15:36:05.865518
"""
# revision identifiers, used by Alembic.
revision = '4ab7a2e91f2d'
down_revision = '5edcaddd6c9'
from alembic import op
def upgrade():
op.create_index('idx_pages_u... |
import sys
import os
import numpy as np
from astropy.io import fits
sys.path.append("/Users/will/Dropbox/multibin-maps")
from rebin_utils import downsample, oversample, pad_array
nlist = [1, 2, 4, 8, 16, 32]
mingoods = [2]*len(nlist)
try:
infile = sys.argv[1]
except IndexError:
sys.exit(f"Usage: {sys.argv[0]}... |
# Generated by Django 3.0.3 on 2020-03-26 13:50
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Resource',
fields=[
... |
from pytpp.attributes._helper import IterableMeta, Attribute
from pytpp.attributes.application_base import ApplicationBaseAttributes
class F5Attributes(ApplicationBaseAttributes, metaclass=IterableMeta):
__config_class__ = "F5"
bundle_certificate = Attribute('Bundle Certificate')
certificate_chain_name = Attribute... |
from services.service import Service
import pygame
import os
import re
import random
from time import sleep
class MediaPlayer(Service):
"""docstring for MediaPlayer"""
def __init__(self):
super(MediaPlayer, self).__init__()
self.option = "stop"
def run(self):
self.logger.info("Me... |
import scipy as sp
import scipy.stats
import scipy.optimize
import numpy as np
import math
import mango
import mango.image
import mango.mpi as mpi
import copy
from mango.math import *
logger, rootLogger = mpi.getLoggers(__name__)
class SphHistPearsonrMetric:
def __init__(self, fixdSphHist, trnsSphHist, loPercenti... |
import argparse
import json
import uuid
import os
def lat_lon_from_geojson_or_json(entry):
lat = entry.get('latitude', None)
lon = entry.get('longitude', None)
if lat is None and lon is None:
try:
coordinates = entry['geometry']['coordinates']
lat = coordinates[1]
... |
import os
mod_list = []
for module in os.listdir(os.path.dirname(__file__)):
if module != '__init__.py' and module[-3:] == '.py':
mod_list.append(module[:-3])
__all__ = mod_list
|
import numpy as np
import hpat
import time
@hpat.jit
def logistic_regression(iterations):
t1 = time.time()
N = 10**8
D = 10
g = 2 * np.random.ranf(D) - 1
X = 2 * np.random.ranf((N, D)) - 1
Y = ((np.dot(X, g) > 0.0) == (np.random.ranf(N) > .90)) + .0
w = np.random.ranf(D) - .5
for i in... |
from django_markup.filter import MarkupFilter
class SmartyPantsMarkupFilter(MarkupFilter):
title = 'SmartyPants'
def render(self, text, **kwargs):
from smartypants import smartypants
return smartypants(text, **kwargs)
|
from enum import Enum
class SCPAllocFreeType(Enum):
""" The SCP Allocation and Free codes
"""
ALLOC_SDRAM = (0, "Allocate SDRAM")
FREE_SDRAM_BY_POINTER = (1, "Free SDRAM using a Pointer")
FREE_SDRAM_BY_TAG = (2, "Free SDRAM using a Tag")
ALLOC_ROUTING = (3, "Allocate Routing Entries")
FRE... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
class implementations for real-time 3D feature extraction
"""
import pandas as pd
import os
import glob
import numpy as np
# from skimage.feature import match_template
# from tomopy import normalize, minus_log, angles, recon, circ_mask
# from scipy.ndimage.filters... |
import logging
import os
from contextlib import ExitStack, contextmanager
from typing import List
from click.testing import CliRunner, Result
from idact import show_cluster, save_environment, set_log_level, AuthMethod
from idact.detail.auth.set_password import set_password
from idact.detail.config.client.client_clust... |
from nicegui.elements.scene_object3d import Object3D
from nicegui.elements.scene_objects import Curve
from ..world import PathSegment
class PathObject(Object3D):
def __init__(self):
super().__init__('group')
def update(self, path: list[PathSegment]) -> bool:
[obj.delete() for obj in list(sel... |
"""
Tests for LivingAPI.
This tests the Python and Java implementations of the LivingAPI as well as
direct access via the gateway.
To run the tests, :mod:`pytest` is required. For rerunning flaky tests the
package ``pytest-rerunfailures`` is used.
"""
import textwrap, re, json
from conftest import *
###
### Tests... |
import numpy as np
import os
import six.moves.urllib as urllib
import sys
import tarfile
import tensorflow as tf
import zipfile
from collections import defaultdict
from io import StringIO
from matplotlib import pyplot as plt
from PIL import Image
from IPython.display import display
def run_interference_for_single_imag... |
from .models import LeafData
import csv
from datetime import datetime
import re
import os
from geoposition import Geoposition
from decimal import Decimal
from django.core.files import File
import matplotlib.pyplot as plt
def _get_data_from_filename(filename):
datepat = re.compile(r'.+\_(?P<day>\d\d)\_(?P<month... |
import numpy as np
import pytest
from process_improve.bivariate.methods import find_elbow_point
@pytest.fixture
def straight_line():
slope = 2.5
intercept = -13
delta = 0.1
x = np.arange(0, 5, delta)
y0 = np.zeros_like(x)
y1 = slope * x + intercept
y2 = np.ones_like(x)
return x, y0, y... |
#!/usr/bin/python
"""
pre commit mercurial script
to strip IPython Notebooks in the InputFiles dir
requires 'nbstripout.py' to be located repoRoot/.hg/
"""
import os, subprocess
script_path="./libUnderworld/script/nbstripout.py"
# parse dir structure under InputFiles
for path, dis, files in os.walk("./InputF... |
#!/usr/bin/python
#
# Copyright 2018 Amazon.com, Inc. or its affiliates. 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. A copy of the License
# is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "L... |
from __future__ import absolute_import
import numpy as np
from scipy import sparse
from catboost import CatBoostClassifier
from sklearn.linear_model import LogisticRegression
from sklearn.feature_extraction.text import TfidfVectorizer
from keras import regularizers
from keras.regularizers import l1, l2, l1_l2
from ke... |
'''
Create an unified test_stub to share test operations
@author: SyZhao
'''
import os
import subprocess
import time
import uuid
import zstacklib.utils.ssh as ssh
import zstacklib.utils.shell as shell
import zstackwoodpecker.test_lib as test_lib
import zstackwoodpecker.test_util as test_util
import zsta... |
"""
Summary
-------
To methodically pull study files to a version controlled study From a
Non-Version Controlled Study (FNVCS), this Python file moves the following file
types from directory to another:
- *.wresl
- *.table
- *.project
- *.launch
"""
# %% Import libraries.
# Import standard libraries.
i... |
import pytest
def pytest_addoption(parser):
parser.addoption("--ip", action="store", default="localhost", help="service's ip")
parser.addoption("--host", action="store", default="localhost", help="service's ip")
parser.addoption("--service", action="store", default="", help="service address")
parser.a... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import random
from torch.distributions import Normal
from torch.optim import lr_scheduler
import pandas as pd
import os
'''
Counterfactual Multi-Agent Policy Gradients
https://ojs.aaai.org/index.php/AAAI/article/view/11794
'''
class ... |
"""unique workflow name
Revision: 83ac97de615
Revises: 270148ec7ba7
Created: 2013-03-21 14:27:28.659710
"""
revision = '83ac97de615'
down_revision = '270148ec7ba7'
from alembic import op
from spire.schema.fields import *
from sqlalchemy import Column, ForeignKey, ForeignKeyConstraint, PrimaryKeyConstraint, CheckCons... |
import os
import math
import torch
import shutil
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
self.reset()
def reset(self):
self.val = 0
self.avg = 0
self.sum = 0
self.count = 0
def update(self, val, n... |
# Copyright (C) 2001-2006 Python Software Foundation
# Author: Barry Warsaw
# Contact: email-sig@python.org
"""Class representing message/* MIME documents."""
__all__ = ['MIMEMessage']
z email zaimportuj message
z email.mime.nonmultipart zaimportuj MIMENonMultipart
klasa MIMEMessage(MIMENonMultipart):
"""Cla... |
import sys
import pygame
from random import shuffle
from bullet import Bullet
from enemy import EnemyShip
from enemy_bullet import EnemyBullet
def enemies_collision(enemies, bullets, game_setting):
collisions = pygame.sprite.groupcollide(bullets, enemies, True, True)
game_setting.enemy_bullet_allowed = max(ga... |
# https://www.geeksforgeeks.org/largest-number-less-than-or-equal-to-z-that-leaves-a-remainder-x-when-divided-by-y/
# https://www.quora.com/How-do-you-write-a-Python-program-if-you-are-given-three-numbers-a-b-and-c-Write-a-program-to-determine-the-largest-number-that-is-less-than-or-equal-to-c-and-leaves-a-remainder-b... |
# Task is to train various classifiers on MNIST dataset
# (sklearn's load_digits() [1797 instances] was used instead of full MNIST dataset [10000 instances])
import yaml
import os
from sklearn.datasets import load_digits
import random
import matplotlib.pyplot as plt
from sklearn.neighbors import KNeighborsClas... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# academic_german.py
"""Collection of German academic degrees combining wiki and drtitel."""
import os
import sys
import re
PACKAGE_PARENT = '..'
SCRIPT_DIR = os.path.dirname(
os.path.realpath(os.path.join(os.getcwd(),
os.path.expanduser(__file__))),
) # isort:ski... |
import unittest
from .updated import Updated
import datetime
class UpdatedTest(unittest.TestCase):
def setUp(self):
self.now = datetime.datetime.strptime('2021-01-07 22:45:13', '%Y-%m-%d %H:%M:%S')
def test_is_writeable(self):
updated = Updated(self.now)
self.assertFalse(updated.is_wr... |
from math import cos, pi
import numpy
from chainer.training import extension
class CosineAnnealing(extension.Extension):
'''
https://gist.github.com/hrsma2i/9c6514e94cd5e802d9e216aef2bcfe59
'''
def __init__(self, lr_max, lr_min=0, T_0=1, T_mult=2,
optimizer=None):
... |
# coding: utf-8
import codecs
import copy
import importlib
import inspect
import os
import re
import sys
import jsonschema
import yaml
from six import string_types, text_type
from copy import deepcopy
from functools import wraps
from importlib import import_module
from collections import OrderedDict
from flask import ... |
# Faça um programa que tenha uma função chamada contador(), que receba três parâmetros: início, fim e passo e realize
# a contagem.
# Seu programa tem que realizar três contagens através da função criada:
# a) De 1 até 10, de 1 em 1
# b) De 10 até 0, de 2 em 2
# c) Uma contagem personalizada.
from time import sleep ... |
"""
substitute every letter with it's number from the alphabet and the other way around
"""
# assign each char a letter
def substitute(string, substitutes=None, joint=''):
# replace substitutes with default
if substitutes is None:
substitutes = {
"1": 'A',
"2": 'B',
... |
# -*- coding: utf-8 -*-
'''This module provides functions for connecting and downloading
from Alaska satellite Faciltity's Vertex server
'''
import os
from os.path import join as opj
import glob
import requests
import tqdm
import multiprocessing
from ost.helpers import helpers as h
from ost import Sentinel1_Scene as ... |
# -*- coding: utf-8 -*-
'''
Basic functions for accessing the SDB interface
For configuration options, see the docs for specific sdb
modules.
'''
from __future__ import absolute_import
import salt.loader
from salt.ext.six import string_types
def sdb_get(uri, opts, utils=None):
'''
Get a value from a db, usin... |
__author__ = 'max'
from state import State
class Protein(State):
def __init__(self, init_dict):
super(Protein, self).__init__(init_dict["ID"], init_dict["name"])
|
import os
import re
import sys
import urllib
from pathlib import Path
import pickle
import librosa
import librosa.display
import matplotlib.pyplot as plt
from sklearn.metrics import accuracy_score
import numpy as np
from python_speech_features import mfcc
def report_hook(count, block_size, total_size):
percent =... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import random
import os
print('Welcome to the game!')
input('Press enter to continue: ')
print('')
print('- This is a population simulator for a fictional town.')
print('- The town starts with 20 people. With each year that passes, babies will be ... |
# uncompyle6 version 2.9.10
# Python bytecode 2.7 (62211)
# Decompiled from: Python 3.6.0b2 (default, Oct 11 2016, 05:27:10)
# [GCC 6.2.0 20161005]
# Embedded file name: __init__.py
VIRTUAL_DIR_ENV_NAME = '_VIRTUAL_DIRECTORY'
def GetFullPath(relativePath):
fullPath = _GetFullPathBase(relativePath)
if len(full... |
from .mcp23x17 import MCP23x17
class MCP23017(MCP23x17):
"""Class representing mcp23017 chip"""
def __init__(self, port, device):
"""Constructor."""
self._port = port
self._device = device
#self._address = address
self.start()
def start(self):
"""Init har... |
# Code Listing #3
"""
Maximum subarray problem - version #3
"""
def max_subarray(sequence):
""" Find sub-sequence in sequence having maximum sum """
# Trackers for max sum and max sub-array
max_sum, max_sub = 0, []
for i in range(len(sequence)):
for j in range(i + 1, len(sequence)):
... |
# -*- coding: utf-8 -*-
from __future__ import with_statement, unicode_literals
from ziggurat_foundations.models.services.group import GroupService
from ziggurat_foundations.models.services import BaseService
from ziggurat_foundations.tests import add_user, add_group, BaseTestCase
from ziggurat_foundations.tests.conft... |
# Copyright (c) 2021 The Trustees of the University of Pennsylvania
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, co... |
#!/usr/bin/env pypy
from random import choice, randint, shuffle
N = 1000000
Q = 20000
print("0 %s" % N)
for i in range(0, Q):
x1 = randint(1, N)
x2 = randint(x1, N)
y1 = randint(1, N)
y2 = randint(y1, N)
t = randint(1, 2)
if t == 1: # ADD
print("1 %s %s %s %s %s" % (x1, y1, x2, y2,... |
"""
Reads in single-cell Hi-C data from Stevens et al. (2017)
Download data from
https://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc=GSE80280
then "Samples (42)" -> "GSM2219{497-504}" -> GSM2219xxx_Cell_x_contact_pairs.txt.gz
"""
import numpy as np
from pyliftover import LiftOver
import matplotlib.pyplot as plt
import ... |
from contentagregator import db
from contentagregator.modules.auth.models import User
from marshmallow_sqlalchemy import SQLAlchemySchema
from datetime import datetime
class User_article(db.Model):
__tablename__ = 'user_article'
article_id = db.Column(db.Integer, primary_key = True)
title = db.Column(db.... |
from api import app
from flask import Flask, session, g
from api.models import User, Group, App, Log, Invite, Reset, Component, ComponentUser
from api.database import db
from flask_login import LoginManager, login_user, login_required, logout_user, current_user
from api.mail import send_email, send_email_register, send... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.