content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
from DB import Database
db = Database("db")
MENU = range(1)
def reminder_handler(user_id, obj):
date, type, name = obj
db.add_event(user_id, date, "birthday" if type == "Birthday" else "regular", name)
if type == "Birthday":
db.add_reminder(user_id, date - 7 * 24 * 60 * 60, "birthday" if type ==... | python |
import glob
import os
import sys
import argparse
import time
from datetime import datetime
import random
import numpy as np
import copy
from matplotlib import cm
import open3d as o3d
VIRIDIS = np.array(cm.get_cmap('plasma').colors)
VID_RANGE = np.linspace(0.0, 1.0, VIRIDIS.shape[0])
LABEL_COLORS = np.array([
(255,... | python |
from __future__ import absolute_import, division, print_function
from distutils.version import LooseVersion
import pickle
import numpy as np
import pytest
import xarray as xr
import xarray.ufuncs as xu
from . import (
assert_array_equal, assert_identical as assert_identical_, mock,
raises_regex,
)
require... | python |
from .utils import *
from .ps.dist_model import DistModel
from .ps import ps_util
def evaluate_ps(gpu_available, options):
model_path = os.path.join(options.model_path, 'alex.pth')
model = DistModel()
model.initialize(model='net-lin', net='alex', model_path=model_path, use_gpu=gpu_available)
dist_sta... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Cisco-IOS-XR-Get-Full-ClearText-Running-Config Console Script.
Copyright (c) 2021 Cisco and/or its affiliates.
This software is licensed to you under the terms of the Cisco Sample
Code License, Version 1.1 (the "License"). You may obtain a copy of the
License at
... | python |
#Uses Money Flow Index to determine when to buy and sell stock
import numpy as np
import pandas as pd
#import warnings
import matplotlib.pyplot as plt
plt.style.use('fivethirtyeight')
#warnings.filterwarnings('ignore')
df = pd.read_csv('StockTickers/JPM.csv',nrows=200)
df.set_index(pd.DatetimeIndex(df['Date'].values),... | python |
from synapse import Synapse
from timemodule import Clock
from neuron import *
import random
clock = Clock()
neurons = []
for i in range(20):
neurons.append(Neuron(clock.get_time(),7/10))
for i in range(30):
connect(neurons[random.randrange(20)],neurons[random.randrange(20)]
,random.randrange(2),1)... | python |
#!/usr/bin/env python3
import logging
import os
import yaml
from jinja2 import Environment, FileSystemLoader
logging.getLogger().setLevel(logging.DEBUG)
def main(template_name, vars_file):
logging.info("Enter main.")
with open(vars_file, 'r') as yaml_vars:
variables = yaml.load(yaml_vars)
thes... | python |
from status import Status
import errors
from unittest import TestCase
class TestStatus(TestCase):
def test_ok(self):
try:
Status.divide(Status.OK.value, None)
self.assertTrue(True)
except errors.JstageError:
self.assertTrue(False)
def test_no_results(self):... | python |
# -*- coding: utf-8 -*-
# file: train_atepc_english.py
# time: 2021/6/8 0008
# author: yangheng <yangheng@m.scnu.edu.cn>
# github: https://github.com/yangheng95
# Copyright (C) 2021. All Rights Reserved.
###################################################################################################################... | python |
#!env python3
import pyd4
import sys
file = pyd4.D4File(sys.argv[1])
chrom = sys.argv[2]
begin = int(sys.argv[3])
end = int(sys.argv[4])
for (chrom, pos, value) in pyd4.enumerate_values(file, chrom, begin, end):
print(chrom, pos, value)
| python |
XXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXXXX XXXXXXXXXX
XXXXXXXXXXXXXXXXXXXXXXXX
XX XXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXX XXXXXXXX XXXXXXX XXXXXXXXXXXX
XXX XXXXXXXXXXXX XXXXXXXXXX XXX XXXXXXXXXX XXXXXXX XXXXXXXXXXX XXXXXXXXXX
XXXXXXX XXXXXXXXXXXXXXXX XXXX XXXX XX XXXXXX XXXXXX XXXX X XXXXXXXXX XXXX
XXXXXX X... | python |
import datetime
model_date_to_read = '20200125'
model_version_to_read = '2.0'
model_date_to_write = datetime.datetime.today().strftime('%Y%m%d')
model_version_to_write = '2.0'
| python |
# -*- coding: utf-8 -*-
"""
Created on 2017-8-23
@author: cheng.li
"""
import numpy as np
import pandas as pd
from PyFin.api import *
from alphamind.api import *
from matplotlib import pyplot as plt
plt.style.use('ggplot')
import datetime as dt
start = dt.datetime.now()
universe = Universe('custom', ['zz800'])
f... | python |
# Other imports
import numpy as np
import torch
# DeepCASE Imports
from deepcase.preprocessing import Preprocessor
from deepcase import DeepCASE
if __name__ == "__main__":
########################################################################
# Loading data ... | python |
"""
[summary]
[extended_summary]
"""
# region [Imports]
# * Standard Library Imports ------------------------------------------------------------------------------------------------------------------------------------>
import os
from datetime import datetime
import re
# * Third Party Imports -----------------------... | python |
import math
import sys
import time
import numpy as np
import owl
from net import Net
import net
from net_helper import CaffeNetBuilder
from caffe import *
from PIL import Image
class NetTrainer:
''' Class for training neural network
Allows user to train using Caffe's network configure format but on multiple G... | python |
import numpy as np
import torch
import torch.nn.functional as F
import os, copy, time
#from tqdm import tqdm
import pandas as pd
from ipdb import set_trace
path = '/home/vasu/Desktop/project/'
### helper functions
def to_np(t):
return np.array(t.cpu())
### Losses
def calc_class_weight(x, fac=2):
... | python |
# Copyright Jetstack Ltd. See LICENSE for details.
# Generates kube-oidc-proxy Changelog
# Call from the branch with 3 parameters:
# 1. Date from which to start looking
# 2. Github Token
# requires python-dateutil and requests from pip
from subprocess import *
import re
from datetime import datetime
import dateutil.... | python |
from PIL import Image
import numpy as np
from matplotlib import pylab as plt
img = np.array(Image.new("RGB", (28, 28)))
img[:,:,:] = 255
img[2,2,:] = 0
img[2,5,:] = 0
img[2,6,:] = 0
img[2,10,:] = 0
img[2,11,:] = 0
img[3,10,:] = 0
img[3,11,:] = 0
plt.imshow(img)
plt.imsave("p.png", img)
np.save('p,npy', img, allo... | python |
""" Hyperparameters for MJC peg insertion trajectory optimization. """
from __future__ import division
from datetime import datetime
import os.path
import numpy as np
from gps import __file__ as gps_filepath
from gps.agent.mjc.agent_mjc import AgentMuJoCo
from gps.algorithm.algorithm_traj_opt import AlgorithmTrajOpt
... | python |
import os
import sys
PROJECT_ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.append(os.path.join(PROJECT_ROOT, 'vendor', 'pyyaml', 'lib'))
import yaml
from git import apply as git_apply
class Patch:
def __init__(self, file_path, repo_path):
self.file_path = file_pa... | python |
# vim: fileencoding=utf-8 et sw=4 ts=4 tw=80:
# See LICENSE comming with the source of python-quilt for details.
import runpy
import sys
from unittest import TestCase
from six.moves import cStringIO
from helpers import tmp_mapping
class Test(TestCase):
def test_registration(self):
with tmp_mapping(v... | python |
from django.test import TestCase
from rest_framework.test import APIRequestFactory
from rest_framework.test import APIClient
import json
from django.utils import timezone
from datetime import timedelta
# Create your tests here.
from .models import Contact
from .serializers import ContactSerializer
from agape.people.... | python |
#!/usr/bin/python
import sys
def __test1__(__host__):
import pylibmc
print 'Testing <pylibmc> ... %s' % (__host__)
mc = pylibmc.Client([__host__], binary=True, behaviors={"tcp_nodelay": True,"ketama": True})
print mc
mc["some_key"] = "Some value"
print mc["some_key"]
assert(mc["some_key"... | python |
import json
import argparse
import requests
parser = argparse.ArgumentParser()
parser.add_argument("--extension-uuid", dest="extension_uuid", type=str)
parser.add_argument("--gnome-version", dest="gnome_version", type=str)
args = parser.parse_args()
def get_extension_url(extension_uuid, gnome_version):
base_url ... | python |
# -*- coding: utf-8 -*-
import re, kim, dinle, islem, muhabbet
def __init__(giris):
pattern_kim = re.match('(.+) ((kim(dir)?)|nedir)(\?)?$', giris, re.IGNORECASE)
pattern_dinle = re.match('(.+) dinle$', giris, re.IGNORECASE)
pattern_islem = re.match('^([\d\(\)\-]+(\+|\-|\*|\/)[\d\(\)\+\-\*\/\.]+)(=)?(\?)?... | python |
from pirates.minigame import CannonDefenseGlobals
from pirates.pirate.CannonCamera import CannonCamera
from pirates.util.PythonUtilPOD import ParamObj
class CannonDefenseCamera(CannonCamera):
class ParamSet(CannonCamera.ParamSet):
Params = {
'minH': -60.0,
'maxH': 60.0,
... | python |
class Tweet:
def __repr__(self):
return self.id
def __init__(self, _id, text, created_at, hashtags, retweet_count, favorite_count, username, user_location):
self.id = _id
self.text = text
self.created_at = created_at
self.hashtags = hashtags
self.retweet_count = ... | python |
class DimensionError(Exception):
def __init__(self, message="Dimension mismatch"):
super(DimensionError, self).__init__(message)
| python |
import numpy as np
from task.Schema import Schema
# import pdb
class StimSampler():
'''
a sampler of sequences
'''
def __init__(
self,
n_param,
n_branch,
pad_len=0,
max_pad_len=None,
def_path=None,
def_prob=None,
... | python |
from mwcleric.auth_credentials import AuthCredentials
class AuthCredentials(AuthCredentials):
"""Wrapper class just to make imports nicer to work with"""
pass
| python |
import tkinter as tk
import view_calc as vc
import model_calc as mc
class CalcController:
def __init__(self):
self.root = tk.Tk()
self.calc = vc.ViewCalc(self.root, self)
self.moc = mc.ModelCalc()
def start(self):
self.root.mainloop()
def operacao(self, op, n1, n2):
... | python |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import... | python |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: robot_behavior.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as... | python |
import six
import itertools
import numpy as np
from chainer import serializers
import nutszebra_log2
# import nutszebra_slack
import nutszebra_utility
import nutszebra_log_model
import nutszebra_sampling
import nutszebra_download_cifar100
import nutszebra_preprocess_picture
import nutszebra_basic_print
import nutszebra... | python |
import torch
import wandb
import numpy as np
from mlearn import base
from tqdm import tqdm, trange
from collections import defaultdict
from mlearn.utils.metrics import Metrics
from mlearn.utils.early_stopping import EarlyStopping
from mlearn.utils.evaluate import eval_torch_model, eval_sklearn_model
from sklearn.model_... | python |
# Software License Agreement (BSD License)
#
# Copyright (c) 2012, Fraunhofer FKIE/US, Alexander Tiderko
# 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 mus... | python |
import bpy
from bpy.props import *
from .. events import propertyChanged
from .. base_types import AnimationNodeSocket, PythonListSocket
class ColorSocket(bpy.types.NodeSocket, AnimationNodeSocket):
bl_idname = "an_ColorSocket"
bl_label = "Color Socket"
dataType = "Color"
drawColor = (0.8, 0.8, 0.2, 1)... | python |
import pytest
from src.xmlToData.regexExtractors.parametersExtractor import ParametersExtractor
@pytest.mark.parametrize("xml_string", ["+ get_age(): int",
"# add_weight( ): int",
"- set_height( ): int"])
def test_extract_empty_pa... | python |
#
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not us... | python |
# coding: utf-8
"""
nlpapiv2
The powerful Natural Language Processing APIs (v2) let you perform part of speech tagging, entity identification, sentence parsing, and much more to help you understand the meaning of unstructured text. # noqa: E501
OpenAPI spec version: v1
Generated by: https://git... | python |
import torch
from nff.utils.scatter import compute_grad
from nff.utils import batch_to
from torch.nn import ModuleDict
from ase import Atoms
from ase import units
import numpy as np
from torchmd.topology import generate_nbr_list, get_offsets, generate_angle_list
def check_system(object):
import torchmd
if o... | python |
#!/usr/bin/env python3.8
from passlocker import User, user_details
def create_new_user(fisrtname, lastname ,password):
'''
Function to create a new user with a username and password
'''
new_user = User(fisrtname, lastname ,password)
return new_user
def save_user(user):
'''
Function to save... | python |
import mdk
import requests
class MockRequest(object):
def __init__(self):
self.data = None
self.get = self.repeater
self.post = self.repeater
self.put = self.repeater
self.delete = self.repeater
self.status = 200
def repeater(self, url, params=None, headers=No... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import simplejson as json
from alipay.aop.api.constant.ParamConstants import *
class PropertyAuthInfo(object):
def __init__(self):
self._area = None
self._city = None
self._community = None
self._data_id = None
self._latitude ... | python |
def queryUser(feature_names):
print "Please enter changes to features in the format:\n(feature 1 number) (+ for increase, - for decrease)\n(feature 2 number) (+/-)\n...\n(enter -1 -1 to stop)"
for i in range(len(feature_names)):
print str(i+1)+": "+feature_names[i]
print "-------------------------------------"
in... | python |
from ..profiles import models
def user_display(user):
try:
profile = user.profile
except models.Profile.DoesNotExist:
return user.email
return profile.name
| python |
"""
Contains the CNOT gate
"""
from .quantum_gate import QuantumGate
import numpy as np
class CNOT(QuantumGate):
""" Implements the CNOT gate
Parameters
------------
target : 0 or 1, optional
Specifies the target qubit, default is 0.
"""
def __init__(... | python |
import sys
from daqhats import hat_list, HatIDs, mcc152
# get hat list of MCC daqhat boards
board_list = hat_list(filter_by_id = HatIDs.ANY)
if not board_list:
print("No boards found")
sys.exit()
# Read and display every channel
for entry in board_list:
if entry.id == HatIDs.MCC_152:
print("Board... | python |
"""Calculates the new ROM checksum and writes it back to the binary
"""
from binaryninja import BackgroundTaskThread, BinaryReader, show_message_box
import struct
class GenesisChecksum(BackgroundTaskThread):
def __init__(self, bv):
BackgroundTaskThread.__init__(self, "", True)
self.progress = 'ge... | python |
# Direct CAD entry for Mitutoyo calipers via USB HID emulation.
# Assuming a Serpente board, with `req`, `clock`, `data` and `ready` connected to
# D0, D1, D2 and D3, respectively.
import time
import board
import digitalio
import mitutoyo
import usb_hid
from adafruit_hid.keyboard import Keyboard
from adafruit_hid.key... | python |
# calculate the z-score for each individual by two type isoform's junction reads
# 20170522 filter the min reads counts: 25% sample's reads counts >= 1
# added postfix
# 20170626 change the filter method
# 20170705 change the filter method to left in out
# individual sum count must > 5
# rema... | python |
'''Defines blueprints and routes for the app'''
from flask import Blueprint
from flask_restful import Api, Resource
from .views.users import Signup
BLUE = Blueprint('api', __name__, url_prefix="/api/v1")
API = Api(BLUE)
API.add_resource(Signup, '/auth/signup')
| python |
# -*- coding: utf-8 -*-
def main():
import sys
input = sys.stdin.readline
n, s, d = map(int, input().split())
for i in range(n):
xi, yi = map(int, input().split())
if xi < s and yi > d:
print("Yes")
exit()
print("No")
if __name__ == "__main__":
ma... | python |
import komand
from .schema import ListAlertsInput, ListAlertsOutput
# Custom imports below
class ListAlerts(komand.Action):
def __init__(self):
super(self.__class__, self).__init__(
name='list_alerts',
description='List Carbon BlackLi alerts with given parameters',
... | python |
#!/usr/bin/python
# coding=utf-8
################################################################################
from mock import Mock
from mock import patch
from test import CollectorTestCase
from test import get_collector_config
from test import unittest
from urllib2 import HTTPError
from diamond.collector import ... | python |
# coding: utf-8
import click
from datetime import datetime
import re
import shortuuid
from werkzeug.security import generate_password_hash
from app import db
from app import get_db_cursor
from grid_id import GridId
from institution import Institution
from package import Package
from permission import Permission
from p... | python |
import difflib
from bs4 import BeautifulSoup
from selenium import webdriver
from time import sleep
import itertools
import requests
import re
import sqlite3
import jellyfish
conn = sqlite3.connect('bazadanych.db')
c = conn.cursor()
def forbet_teams():
driver = webdriver.Firefox()
driver.get... | python |
filas = int(input("Ingrese el número de filas de la matriz: "))
columnas = int(input("Ingrese el número de columnas de la matriz: "))
matriz = []
for m in range(filas):
matriz.append([])
for n in range(columnas):
matriz[m].append(int(input(f"Ingrese el valor de la columna {n} de la fil... | python |
import glob
import os
from setuptools import setup, find_packages
here = os.path.dirname(os.path.abspath(__file__))
with open(os.path.join(here, "README.md")) as f:
long_description = f.read()
setup(
name="spire-pipeline",
version="1.2.0",
description="Run software pipelines using doit",
lon... | python |
from sensors.range_finder import UltrasonicRangeFinder
from multiprocessing import Queue, Value
import threading
import logging
import unittest
from util.definitions import GPIO_ULTRASONIC_ECHO, GPIO_ULTRASONIC_TRIGGER
# In order to execute this test, an ultrasonic range finder has to be connected to th... | python |
from django.shortcuts import render
from moviesapp.models import Movies
from moviesapp.forms import MoviesForm
def index(request):
return render(request, 'moviesapp/index.html')
def moviesList(request):
moviesList=Movies.objects.all()
movies_dict={'movies':moviesList}
return render(request, 'moviesapp... | python |
from django.apps import AppConfig
class DelayConfig(AppConfig):
name = "channels.delay"
label = "channels.delay"
verbose_name = "Channels Delay"
| python |
from .twitter import TwitterReviews
from .imdb import IMDBReviews
from .ny_times import NYTimesReviews
__all__ = ['TwitterReviews', 'IMDBReviews', 'NYTimesReviews']
| python |
# -*- coding: utf-8 -*-
"""
This tokenizer has been copied from the ``tokenize.py`` standard library
tokenizer. The reason was simple: The standard library tokenizer fails
if the indentation is not right. The fast parser of jedi however requires
"wrong" indentation.
Basically this is a stripped down version of the sta... | python |
import thredo
def func(x, y):
return x + y
def main():
t = thredo.spawn(func, 2, 3)
print("Result:", t.join())
thredo.run(main)
| python |
# -*- coding: utf-8 -*-
#
# Copyright 2020-2021 -Swiss Data Science Center (SDSC)
# A partnership between École Polytechnique Fédérale de Lausanne (EPFL) and
# Eidgenössische Technische Hochschule Zürich (ETHZ).
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in co... | python |
"""
The ``planning`` package contains the planning steps for initial and rolling
wave planning. It creates a ``PlanningCreator`` and calls the methods to set
the Gurobi variables and constraints. It runs the planner afterwards and saves
the plans.
The implementations of the ``PlanningCreator`` (initial and rolling wav... | python |
'''
/vg/station-specific fixes.
'''
from .base import Matcher,MapFix,RenameProperty,DeclareDependencies,ChangeType
from byond.basetypes import BYONDString, BYONDValue, Atom, PropertyFlags
from byond.directions import *
DeclareDependencies('vgstation',['ss13'])
ATMOSBASE = '/obj/machinery/atmospherics'
@MapFix('vgsta... | python |
import pytest
from bearboto3.iam import (
InstanceProfileExistsWaiter,
UserExistsWaiter,
RoleExistsWaiter,
PolicyExistsWaiter,
)
from beartype import beartype
from beartype.roar import (
BeartypeCallHintPepParamException,
BeartypeCallHintPepReturnException,
BeartypeDecorHintPep484585Exceptio... | python |
__author__ = 'hunter'
| python |
#
# PySNMP MIB module Nortel-Magellan-Passport-HdlcTransparentMIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Nortel-Magellan-Passport-HdlcTransparentMIB
# Produced by pysmi-0.3.4 at Mon Apr 29 20:17:57 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by use... | python |
from bs4 import BeautifulSoup, Tag
import os
from abc import ABC, abstractmethod
from typing import List, Dict, NoReturn
class Csskrt(ABC):
def __init__(self, filename: str, tag_styles: Dict):
f = open(filename) # should be able to handle dirs (for later) todo
f_data = f.read()
self.file... | python |
import tensorflow as tf
import tensorflow_hub as hub
import numpy as np
from nboost.plugins.models.rerank.base import RerankModelPlugin
from nboost import defaults
from typing import List, Tuple
class USERerankModelPlugin(RerankModelPlugin):
def __init__(self, **kwargs):
super().__init__(**kwargs)
... | python |
from yolov3.config.defaults import get_default_config
| python |
#!/usr/bin/env python
"""ztc.vm.memory tests"""
import unittest
from ztc.vm.memory import Memory
class Test(unittest.TestCase):
def test_get_active(self):
m = Memory()
assert isinstance(m.active, long)
if __name__ == "__main__":
#import sys;sys.argv = ['', 'Test.testName']
unittest.ma... | python |
import cv2
import argparse
from datetime import datetime
import sys
def do_capture(args):
print("Capturing", args.url)
capture=cv2.VideoCapture(args.url)
i = 0
while True:
if args.nframes is not None and i >= args.nframes:
print("Done")
break
i += 1
fram... | python |
#!/usr/local/bin/python
#==========================================================================
# Ingest a given scripps dataset into the corresponding databases.
# To be invoked by the overall scripps_ingest.py using subprocess,
# destination data directory and temporary working directory are defined in
# proper... | python |
################################################################################
#
# qooxdoo - the new era of web development
#
# http://qooxdoo.org
#
# Copyright:
# 2006-2009 1&1 Internet AG, Germany, http://www.1und1.de
#
# License:
# MIT: https://opensource.org/licenses/MIT
# See the LICENSE file in the... | python |
#!/usr/bin/env python3
import sys
import functools
def parse_tile(s):
lines = s.split('\n')
tile_id = int(lines[0].strip(':').split()[1])
return tile_id, list(map(list, lines[1:]))
def read_tiles():
blocks = sys.stdin.read().strip().split("\n\n")
return {tile_id: tile for tile_id, tile in map(... | python |
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import config
import time
module = 'separable_adapter' # specific module type for universal model: series_adapter, parallel_adapter, separable_adapter
trainMode = 'universal'
from sync_batchnorm import SynchronizedBatchNorm3d
'''
Inp... | python |
"""
@author: Arpit Somani
"""
#Import the required modules
import numpy
#Creating the platform, where we play the game.
board= numpy.array([['_','_','_'],['_','_','_'],['_','_','_']])
#We have 2 symbols , as its a 2 player game
p1s= 'X'
p2s= 'O'
#Checking for empty place in rows
def check_row... | python |
# segmented sieve
from __future__ import annotations
import math
def sieve(n: int) -> tuple:
"""
>>> sieve(2 **3)
(2, 3, 5, 7)
>>> sieve(3 ** 3)
(2, 3, 5, 7, 11, 13, 17, 19, 23)
>>> sieve(4)
(2, 3)
"""
in_prime = []
start = 2
end = int(math.sqrt(n))
temp = [True] * ... | python |
# Generated by Django 3.0.5 on 2020-04-23 10:34
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('payment', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='payment',
name='payment_type',
... | python |
import torch
import torch.nn as nn
import torch.functional as F
import torch.optim as optim
from random import randint
import argparse
from datetime import datetime
import os
import numpy as np
from time import time
from collections import defaultdict
from gnn_cnn_model.deepwalks import *
from gnn_cnn_model.model impo... | python |
#!/usr/bin/env python
"""
Compute the DSigma profiles for different lenses
"""
import os
import pickle
from astropy.table import Table
from jianbing import scatter
from jianbing import wlensing
TOPN_DIR = '/tigress/sh19/work/topn'
# Lensing data using medium photo-z quality cut
s16a_lensing = os.path.join(TOPN_DIR... | python |
"""
File name: __init__.py
Author: Lukas Müller
Python Version: 3.6
"""
from .lfsr import LFSR
from .fsr_function import FSRFunction
from .nlfsr import NLFSR
from .tools import logical_and, logical_xor
name = "pyfsr"
version = "1.0"
| python |
from unittest import TestCase
from hamcrest import assert_that, is_
from util.string_util import replace_not_alphanumeric, normalize, remove_multi_spaces, create_filename, replace_numeric, \
contains_numeric
class TestStringUtils(TestCase):
def test_remove_multi_spaces(self):
assert_that(remove_mul... | python |
from django.contrib import admin
from django.urls import path
from django.conf import settings
from django.conf.urls.static import static
from django.urls import include
from django.views.generic import TemplateView
import django_cas_ng.views
urlpatterns = [
path("admin/", admin.site.urls),
path(
"ope... | python |
from flask import Flask, g, render_template, flash, redirect, url_for, abort, send_file, request, jsonify
from flask_bcrypt import check_password_hash
from flask_login import LoginManager, login_user, logout_user, login_required, current_user
from flask_admin import Admin, AdminIndexView, BaseView, expose
from flask_a... | python |
'''
Recursion
We're going to take a break from our tour of data structures in order to look at the concept of recursion. Recursion is going to be a useful tool for solving some of the problems we'll be tackling later on, and this is a good place to introduce it and get some practice using it with the data structures we... | python |
"""Tests for the fixes of CNRM-CM6-1."""
import os
import iris
import numpy as np
import pytest
from netCDF4 import Dataset
from esmvalcore.cmor._fixes.cmip6.cnrm_cm6_1 import Cl, Clcalipso, Cli, Clw
from esmvalcore.cmor.fix import Fix
from esmvalcore.cmor.table import get_var_info
@pytest.fixture
def cl_file(tmp_p... | python |
#!/usr/bin/env python
# -*- coding utf-8 -*-
#
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
# Author: Markus Ritschel
# eMail: kontakt@markusritschel.de
# Date: 03/04/2019
# %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
#
from __future__ import division, print_function, absolute_import
from mpi_icelab_routines.arduino import read_ardui... | python |
from .code_actions import actions_manager
from .code_actions import CodeActionOrCommand
from .core.logging import debug
from .core.protocol import Diagnostic
from .core.protocol import Request
from .core.registry import LspTextCommand
from .core.registry import windows
from .core.sessions import SessionBufferProtocol
f... | python |
from django import forms
#from pagedown.widgets import PagedownWidget
from apps.saas.models import Offer
class OfferForm(forms.ModelForm):
#content= forms.CharField(widget=PagedownWidget(show_preview=False))
#publish= forms.DateField(widget=forms.SelectDateWidget)
class Meta:
model = Offer
fields= [
"tipo_... | python |
from pathlib import Path, PurePath
import re
import json
import copy
import logging
from sc2_tournament_analysis.defaults import standard_player_match
from sc2_tournament_analysis.handle_replay import handle_replay
def recursive_parse(
*,
sub_dir=None,
data_function,
player_match=None,
identifier_... | python |
# Interpretable cnn for big five personality traits using audio data #
# Parameters initalization #
NUM_FRAMES = 208 # No of Frames for summary spectrogram.
NUM_BANDS = 64 # No of frequency bands for mel-spectrogram.
# Model hyperparameters.
INIT_STDDEV = 0.01 # Standard deviation used to initialize weights.
LEARNI... | python |
fichier = open("/run/media/Thytu/TOSHIBA EXT/PoC/Smartshark/DS/test_ds_DDOS.csv", "r")
pos = 13 #pos to flatten
def flat_line(line, target):
index = 0
pos = 0
for l in line:
print(l, end="")
pos += 1
if (l == ','):
index += 1
if index == target:
brea... | python |
class Attachment:
def __init__(
self,
id,
filename,
size,
url,
proxy_url,
**kwargs
):
self.id = id
self.filename = filename
self.size = size
self.url = url
self.proxy_url = proxy_url
if 'height' in kwargs.... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.