content stringlengths 5 1.05M |
|---|
import django_filters
from django import forms
from .models.song import Song
class SongFilter(django_filters.FilterSet):
artist = django_filters.CharFilter(lookup_expr='icontains', widget=forms.TextInput(attrs={'size':20}))
title = django_filters.CharFilter(lookup_expr='icontains', widget=forms.TextInput(attr... |
#!/usr/bin/python
'''
This is to clean up the extracted alignment so it contains only the full length sequences.
This removes the following from alignment:
1.sequences start with '-'
2.sequences end with '-'
3.sequences with '-' account for over 20% of the full length.
Arguments:
1. alignment fasta file ('-' indicate... |
"""
T: O(NlogN + W**2*N)
S: O(N)
We operate on a sorted list of words to find the correct result.
On each iteration, we find all words which are one letter smaller
then the current one, and check if they have been seen already.
The chain length for the previous word plus one is the current
chain length. The answer is ... |
"""Methods for computing, reading, and writing saliency maps."""
import numpy
import netCDF4
from gewittergefahr.gg_utils import file_system_utils
from gewittergefahr.gg_utils import error_checking
from gewittergefahr.deep_learning import saliency_maps as saliency_utils
EXAMPLE_DIMENSION_KEY = 'example'
CYCLONE_ID_CH... |
"""Generate synthetic data for PairedDNNClassifier."""
import os
import random
import string
import numpy as np
import pandas as pd
SEED = 123
NUMBER_OF_WORDS = 300
NUMBER_OF_DIMENSIONS = 500
NUMBER_OF_PAIRS = 1000
MAXIMUM_WORD_LENGTH = 10
NUMBER_OF_TRAINING_PAIRS = int(NUMBER_OF_PAIRS*.5)
# set seed for reproducibil... |
import os
import sys
try:
from mpi4py import MPI
except:
MPI = False
def under_mpirun():
"""Return True if we're being executed under mpirun."""
# this is a bit of a hack, but there appears to be
# no consistent set of environment vars between MPI
# implementations.
for name in os.environ... |
class Config():
def __init__(self):
self.gamma = 0.99
self.entropy_beta = 0.001
self.eps_clip = 0.2
self.steps = 128
self.batch_size = 32
self.training_epochs = 4
self.acto... |
# coding=utf-8
from datapoller.settings import THRESHOLD_FOR_KP
LON_BLOCKS = 1024
LAT_BLOCKS = 512
def lat_lon_to_cell(lat, lon):
"""
Converts (lat, lon) to linear cell index, based on a 1024 x 512 grid.
Latitude ranges between -90.0 (south pole) and +90.0 (north pole), longitude is between -180.0 and +18... |
# Code from Chapter 9 of Machine Learning: An Algorithmic Perspective (2nd Edition)
# by Stephen Marsland (http://stephenmonika.net)
# You are free to use, change, or redistribute the code in any way you wish for
# non-commercial purposes, but please maintain the name of the original author.
# This code comes with no... |
import os
from dotenv import load_dotenv
load_dotenv()
def get_env(name: str, terminal_action=True) -> str:
"""
return to environment variables
"""
if name in os.environ:
return os.environ[name]
try:
if terminal_action is True:
return (input(f'Enter your {name}: '))
... |
import linktypes.default
import linktypes.steam
from linktypes.settings import LinktypeException
default = linktypes.default
all = {linktypes.default.name: linktypes.default,
linktypes.steam.name: linktypes.steam}
def get_config(linktypename):
try:
linktype = all[linktypename]
except KeyError:
... |
# -*- coding: utf-8 -*-
"""
Created on Sun Aug 6 21:36:50 2017
@author: XLP
"""
import tensorflow as tf
import tensorlayer as tl
import numpy as np
from tensorlayer.layers import list_remove_repeat
Layer = tl.layers.Layer
def image_preprocess(img,meanval):
meanval = tf.constant(meanval,tf.float32)* ... |
__project__ = "o3seespy"
__author__ = "Maxim Millen & Minjie Zhu"
__version__ = "3.1.0.18"
__license__ = "MIT with OpenSees License"
|
# -*- coding: utf-8 -*-
"""This module implements a time picker widget"""
from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
from __future__ import unicode_literals
from datetime import datetime
from builtins import range
from asciimatics.event import KeyboardE... |
from itertools import islice, izip
import math
FAR_AWAY = 256.0 # A dummy far-away distance used instead of zeros in laser scans. [m]
class VFH:
'''
VFH+ implementation. No long-term memory is used, only the obstacles in the last laser scan are taken in account.
The laser is expected to be mounted on ... |
##
from __future__ import absolute_import
from questgen.encoding import encoding
|
import pytest
import numpy as np
import reciprocalspaceship as rs
def test_merge_valueerror(hewl_merged):
"""
Confirm rs.algorithms.merge() raises ValueError when invoked with
merged DataSet
"""
with pytest.raises(ValueError):
merged = rs.algorithms.merge(hewl_merged)
@pytest.mark.param... |
import argparse
import json
import itertools
import logging
import re
import os
import uuid
import sys
from urllib.request import urlopen, Request
from bs4 import BeautifulSoup
REQUEST_HEADER = {
'User-Agent': "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.134 Safari/5... |
"""
@filename: process_tweets.py
@author: Matthew Mayo
@modified: 2014-04-25
@description: Calculates the sentiment score of tweets stored in
<tweet_file> by referencing term-value pairs in the
<sentiment_file>; also calcualtes the length of ea... |
#write import statements for Player and Die class
from player import
from die import
#Create an instance of the Main class and call/execute the roll_doubles method
class Main():
def run(self):
self.Main = main
|
import warnings
import numpy as np
import pandas as pd
def from_pyvista(poly_data, **kwargs):
"""Load a PyntCloud mesh from PyVista's PolyData instance"""
try:
import pyvista as pv
except ImportError:
raise ImportError("PyVista must be installed. Try `pip install pyvista`")
if not is... |
"""Delete group API method."""
from ibsng.handler.handler import Handler
class delGroup(Handler):
"""Delete group method class."""
def control(self):
"""Validate inputs after setup method.
:return: None
:rtype: None
"""
self.is_valid(self.group_name, str)
def set... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import functools
from .SurfaceClassifier import conv1_1, period_loss
# from .DepthNormalizer import DepthNormalizer
from ..net_util import *
# from iPERCore.models.networks.criterions import VGGLoss
from lib.model.Models import NestedUNet
import numpy a... |
"""
The roseguarden project
Copyright (C) 2018-2020 Marcus Drobisch,
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU General Public License as published by the Free Software
Foundation, either version 3 of the License, or (at your option) any later
version.
This pr... |
"""Suite Standard Suite: Common terms for most applications
Level 1, version 1
Generated from /Volumes/Sap/Applications (Mac OS 9)/Metrowerks CodeWarrior 7.0/Metrowerks CodeWarrior/CodeWarrior IDE 4.2.5
AETE/AEUT resource version 1/0, language 0, script 0
"""
import aetools
import MacOS
_code = 'CoRe'
from StdSuite... |
#!/usr/bin/env python
# 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
#
# Authors:
# - Tobias Wegner, [email protected], 2017-2018
# - Paul Nils... |
"""
Copyright (c) Contributors to the Open 3D Engine Project.
For complete copyright and license terms please see the LICENSE at the root of this distribution.
SPDX-License-Identifier: Apache-2.0 OR MIT
"""
# -------------------------------------------------------------------------
"""DCCsi Tool and Application servic... |
import unittest
from metis.Constants import Constants
class ConstantsTest(unittest.TestCase):
def test_lookup(self):
self.assertEqual(Constants[Constants.DONE], "Constants.DONE")
self.assertEqual(Constants.get_name(Constants.DONE), "Constants.DONE")
if __name__ == "__main__":
unittest.main(... |
input = """
c num blocks = 1
c num vars = 200
c minblockids[0] = 1
c maxblockids[0] = 200
p cnf 200 810
51 12 -4 0
-15 -9 7 0
-91 57 -17 0
-89 -69 197 0
4 68 113 0
-25 2 168 0
43 146 -61 0
-84 -200 88 0
-70 112 -96 0
131 18 72 0
97 161 -193 0
44 41 -80 0
194 -11 -116 0
-126 -162 65 0
-84 183 -155 0
-172 -122 135 0
-52 ... |
""" Useful numerical constants.
Attributes
----------
inf_bound : float
This parameter is intended to be used to denote a infinite bound on
a design variable or constraint. The default value of 2.0e20 is
large enough that it will trigger special treatment of the bound
as infinite by optimizers like SN... |
import numpy as np
import hiddenmm.model.markov_chain as mc
import hiddenmm.constants as constants
import hiddenmm.numeric_util as nutil
class DiscreteHiddenMM:
""" Class implementing a discrete Hidden Markov Model """
def __init__(self, markov_chain: mc.MarkovChain, projection: np.ndarray):
self.ma... |
"""
Metrics that provide data about with insight detection and reporting
"""
import datetime
import sqlalchemy as s
import pandas as pd
from augur.util import logger, annotate, add_metrics
@annotate(tag='top-insights')
def top_insights(self, repo_group_id, num_repos=6):
"""
Timeseries of pull request accepta... |
#!/usr/bin/env python
#
# entp_plots.py
#
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
# Reading data
ent = (np.loadtxt('t-fixed-2.0.DAT')).T
plt.xlabel('$t \Delta$')
plt.ylabel('$\sigma(t)$', rotation='horizontal')
plt.plot(ent[0], ent[1], 'y-')
plt.grid(True)
plt.show()
|
import numpy as np
import scipy.io as sio
np.random.seed(0)
VGG_MEAN = [103.939, 116.779, 123.68]
def read_mat(path):
return np.load(path)
def write_mat(path, m):
np.save(path, m)
def read_ids(path):
return [line.rstrip('\n') for line in open(path)]
class Batch_Feeder:
def __init__(self, datas... |
import unittest
from lib.models import *
from lib.generator import RandomFiller
class TestGameModels(unittest.TestCase):
randomFiller = RandomFiller()
def test_player_generator(self):
pl = self.randomFiller.get_player()
self.assertIsInstance(pl, Player)
self.assertIsNotNone(pl.name)
... |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import rg
class Robot:
def act(self, game):
# jeΕΌeli jesteΕ w Εrodku, broΕ siΔ
if self.location == rg.CENTER_POINT:
return ['guard']
# jeΕΌeli wokΓ³Ε sΔ
przeciwnicy, atakuj
for poz, robot in game.robots.iteritems():
... |
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.utils.safestring import mark_safe
from django.contrib.auth.decorators import login_required
import json
# Create your views here.
def index(request):
return render(request, 'index.html',{})
@login_required
def room(req... |
# MIT License
#
# Copyright (c) 2020, Bosch Rexroth AG
#
# 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, copy, modify, m... |
meuCartao = int(input("Digite o nΓΊmero do cartΓ£o de crΓ©dito: "))
cartaolido = 1
encontreiMeuCartaoNaLista = False
while cartaolido != 0 and not encontreiMeuCartaoNaLista:
cartaolido = int(input("Digite o nΓΊmero do prΓ³ximo cartΓ£o de crΓ©dito: "))
if cartaolido == meuCartao:
encontreiMeuCartaoNaLista = T... |
"""Evaluate model and calculate results for SMP-CAIL2020-Argmine.
Author: Tsinghuaboy [email protected]
"""
from typing import List
import codecs
import pandas
import torch
from tqdm import tqdm
from sklearn import metrics
# from classmerge import classy_dic, indic
LABELS = [0,1]
threshold = 0.8
def calculate_... |
#!/usr/bin/env python
import argparse
import logging
import os
import sys
import gi
gi.require_version("Gtk", "3.0")
gi.require_version("Gdk", "3.0")
from .config import load_steady, ConfigError
from .gui_handlers import SetupHandler, ConfigHandler
from .msikeyboard import MSIKeyboard, UnknownModelError
from .parsi... |
from ai import AIPlayer
import tkinter as tk # GUI
from logika import *
from minimax import *
from clovek import Clovek
from racunalnik import Racunalnik
##################################
# GRAFICNI / UPORABNISKI VMESNIK #
##################################
MIN_SIRINA = 500
MIN_VISINA = 555
ZVP = 100
class Gui:
... |
#!/usr/bin/python
config = [
# enable ldap
{
"/v1/sys/auth/ldap": {
"type": "ldap",
"description": "Login with ldap"
}
},
# configure ldap
{
"/v1/auth/ldap/config": {
"url": "ldap://[myldapserver].net",
"binddn": "cn=[myadminuser],dc=[mydomain],dc=net",
"u... |
#-*- coding: utf-8 -*-
import unittest
import os
import sys
import json
import requests
import time
import hashlib
import random
import string
cli_wallet_url = "http://127.0.0.1:8047"
headers = {"content-type": "application/json"}
chain_url = "http://127.0.0.1:8149" # ζδΊζ₯ε£cli_wallet沑ζοΌδ½Ώη¨chain api
# curl https://ap... |
"""
Copyright 2020 MPI-SWS
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distri... |
import os
import matplotlib.pyplot as plt
import numpy as np
import pickle
from ssm import HMM
from ssm.messages import forward_pass
from scipy.special import logsumexp
from sklearn.metrics import r2_score
# -------------------------------------------------------------------------------------------------
# model fitt... |
#! /usr/bin/env python
# --coding:utf-8--
# coding: utf-8
# ββββββη₯ε
½εΊζ²‘ββββββ
# γγγββγγγββ
# γγβββ»βββββ»β
# γγβγγγγγγγβ
# γγβγγγβγγγβ
# γγβγβ³βγββ³γβ
# γγβγγγγγγγβ
# γγβγγγβ»γγγβ
# γγβγγγγγγγβ
# γγβββγγγβββ
# γγγγβγγγβη₯ε
½δΏδ½, ζ°Έζ BUG!
# γγγγβγγγβCode is far away from bug with the animal protecting
# γγγγβγγγβββββ
# ... |
from math import pi, radians
import socket
import struct
import find_sun
import test_light_system as ls
VIEWER_ADDR ('172.16.164.208', 43521)
class Servo:
def __init__(self, pin=18, minval=520, maxval=2240, wincount=8):
self.pi = pigpio.pi()
self.pin = pin
self.minval = minval
self.maxval = maxval
self.wi... |
from .get_links_directly import get_links_directly
from .get_links_using_Google_search import get_links_using_Google_search
from .find_links_by_extension import find_links_by_extension
|
import logging
from datetime import date, datetime, timedelta
import redis
from integration_tests.utils import populate_mock_db
from sqlalchemy.sql.expression import or_
from src.challenges.challenge_event_bus import ChallengeEvent, ChallengeEventBus
from src.challenges.trending_challenge import (
should_trending_... |
"""
implementation of criteo dataset
"""
# pylint: disable=unused-argument,missing-docstring
import os
import sys
import re
import random
import numpy as np
from intel_pytorch_extension import core
import inspect
# pytorch
import torch
from torch.utils.data import Dataset, RandomSampler
import os
# add dlrm code pa... |
from disnake.ext import commands
class ErrorHandler(commands.Cog):
"""A cog for global error handling."""
def __init__(self, bot: commands.Bot):
self.bot = bot
@commands.Cog.listener()
async def on_command_error(
self, ctx: commands.Context, error: commands.CommandError
):
... |
import matplotlib
import subprocess
import matplotlib.pyplot as plt
import numpy as np
time_gpu = {}
time_cpu = {}
generate = './generate_dataset.py'
par = './../cpp/kmean-par'
seq = './../cpp/kmean-seq'
file_input = 'points_'
for k in range(100, 510, 100):
time_cpu[k] = {}
time_gpu[k] = {}
for n in rang... |
ο»Ώimport aspose.slides as slides
def charts_set_data_range():
#ExStart:SetDataRange
# The path to the documents directory.
outDir = "./examples/out/"
dataDir = "./examples/data/"
# Instantiate Presentation class that represents PPTX file
with slides.Presentation(dataDir + "charts_with_external_... |
#!/usr/bin/python3
""" ===================================================================================================================
|
| Name : roll_the_dice.py
| Project : diceware
| Copyright : burrwebb
| License : Apache-2.0 (https://www.apache.org/licenses/LICENSE-2.0.txt)
| ... |
"""Treadmill metrics collector.
Collects Treadmill metrics and sends them to Graphite.
"""
import glob
import logging
import os
import time
import click
from treadmill import appenv
from treadmill import exc
from treadmill import fs
from treadmill import rrdutils
from treadmill.metrics import rrd
#: Metric collect... |
import testaid
testinfra_hosts = testaid.hosts()
def test_testaid_ruby_role_curl_install_packages_installed(host, testvars):
curl_packages = testvars['curl_packages']
for debian_package in curl_packages:
deb = host.package(debian_package)
assert deb.is_installed
|
#pylint: disable=import-error
from machine import Pin, SPI
from input import DigitalInput
import display
import m5stack
#pylint: enable=import-error
#TODO: does not handle multiple initialisations
if not 'tft' in dir():
tft = m5stack.Display()
tft.image(x, y, file [,scale, type]
|
import requests
from datetime import datetime, timedelta
def get_average_prices(currency, start_date, end_date):
""" Returns the average price per day for this currency between the two dates.
start_date and end_date must be datetime objects """
# Ex : https://poloniex.com/public?command=returnChartData... |
####################################################################################
# BLACKMAMBA BY: LOSEYS (https://github.com/loseys)
#
# QT GUI INTERFACE BY: WANDERSON M.PIMENTA (https://github.com/Wanderson-Magalhaes)
# ORIGINAL QT GUI: https://github.com/Wanderson-Magalhaes/Simple_PySide_Base
####################... |
from .cCollateralBugHandler import cCollateralBugHandler; |
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 1 20:58:36 2019
@author: Sneha
"""
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 26 13:26:27 2019
@author: Sneha
"""
import tkinter as tk
from tkinter import *
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import numpy as np
import matplotlib.pyplot... |
#!/usr/bin/env python3
import pandas as pd
from xlsxwriter.utility import xl_cell_to_rowcol
template_name = 'background/Billing of Witzenmann.xlsx'
source = (
'A7:A15', 'A19:A21', 'A42:A44', 'B2:B11', 'C2:C13', 'D63:D84',
'E2:E168')
def dfg(df, ranges):
for dv_range in ranges:
cells = dv... |
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
task_config = {}
"""A short and descriptive title about the kind of task the HIT contains.
On the Amazon Mechanical Turk... |
import komand
from .schema import UpdateSiteExcludedTargetsInput, UpdateSiteExcludedTargetsOutput, Input
# Custom imports below
from komand_rapid7_insightvm.util import endpoints
from komand_rapid7_insightvm.util.resource_helper import ResourceHelper
class UpdateSiteExcludedTargets(komand.Action):
def __init__(s... |
"""Constants."""
from typing import TypeVar
from .feed_entry import FeedEntry
from .filter_definition import GeoJsonFeedFilterDefinition
DEFAULT_REQUEST_TIMEOUT = 10
UPDATE_OK = "OK"
UPDATE_OK_NO_DATA = "OK_NO_DATA"
UPDATE_ERROR = "ERROR"
T_FILTER_DEFINITION = TypeVar("T_FILTER_DEFINITION", bound=GeoJsonFeedFilterD... |
#!/usr/bin/env python
# coding: utf-8
# In[3]:
import lmdb
import sys
import numpy as np
from io import BytesIO
import numpy as np
#sys.path.append("/dvmm-filer2/projects/AIDA/alireza/tools/AIDA-Interchange-Format/python/aida_interchange")
from rdflib import URIRef
from rdflib.namespace import ClosedNamespace
from c... |
from __future__ import unicode_literals
from ..enums import IncrementalSearchDirection, InputMode
from ..keys import Keys
from ..line import ClipboardData, ClipboardDataType, SelectionType, indent, unindent
from ..selection import SelectionType
from .basic import basic_bindings
from .utils import create_handle_decorat... |
# [warning: do not run this script in the partiiton where system files are stored]
# use it with caution
import os
import shutil
path = '/home/hafeez/Downloads/'
names = os.listdir(path)
folder_name = ['Images', 'Audio', 'Videos', 'Documents', 'Softwares','System']
for x in range(0,6):
if not os.path.ex... |
# An attempt to support python 2.7.x
from __future__ import print_function
import signal
import sys
import boto3
import botocore.exceptions
from stacks import aws, cf, cli
from stacks.config import config_load, print_config, validate_properties
#Uncomment to get extensive AWS logging from Boto3
#boto3.set_stream_lo... |
import discord
import asyncio
from app.vars.client import client
from app.helpers import Notify, getUser
from discord.ext import commands
@client.command(aliases=['removeban','xunban','unbanid', 'unban_id', 'id_unban'])
@commands.guild_only()
@commands.has_permissions(ban_members=True)
async def unban(ctx, id):
no... |
# coding: utf8
from __future__ import unicode_literals, print_function, division
from collections import OrderedDict
import re
from clldutils import jsonlib
from pylexibank.util import get_reference
VALUE_MAP = {
#'not done yet',
#'n/a',
#'no?',
#'yes',
#'check',
#'24',
#'1',
#'21',
... |
import json, csv, os, argparse
def main():
parser = argparse.ArgumentParser(description='using a standard json formatted phylogeny file, finds time to most recent common ancestor for the oldest organisms in file. origin_time is used to find oldest organisms and to establish the time axis.')
parser.add_argu... |
import urllib.parse
def query_field(query, field):
field_spec = field in query
return (field_spec, query[field] if field_spec else '')
def unpack_id_list(l):
return [int(x) for x in
[_f for _f in urllib.parse.unquote_plus(l).split(',') if _f]]
|
# Generated by Django 2.2 on 2019-06-24 14:22
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("audits", "0010_auto_20190410_2241")]
operations = [
migrations.AddField(
model_name="auditresults",
name="lh_metric_first_contentfu... |
from telegram.constants import MAX_FILESIZE_DOWNLOAD
from telegram.ext import CommandHandler, ConversationHandler, Filters, MessageHandler
from pdf_bot.consts import (
BACK,
BEAUTIFY,
BY_PERCENT,
BY_SIZE,
CANCEL,
COMPRESS,
COMPRESSED,
CROP,
DECRYPT,
ENCRYPT,
EXTRACT_PHOTO,
... |
from recurrent_ics.grammar.parse import ContentLine
from recurrent_ics.serializers.serializer import Serializer
class CalendarSerializer(Serializer):
def serialize_0version(calendar, container): # 0version will be sorted first
container.append(ContentLine("VERSION", value="2.0"))
def serialize_1prod... |
import h5py, cv2, os, random, argparse
from tqdm import tqdm
import numpy as np
class Process:
def __init__(self, data_path=None, filename=None):
self.filename = filename
self.data_path = data_path
self.prefix = "landmark_aligned_face." # every image name is prefixed with this string
... |
from sqlalchemy.dialects.sybase import base, pysybase, pyodbc
from base import CHAR, VARCHAR, TIME, NCHAR, NVARCHAR,\
TEXT,DATE,DATETIME, FLOAT, NUMERIC,\
BIGINT,INT, INTEGER, SMALLINT, BINARY,\
VARBINARY,UNITEXT,UNICHAR,UNIVARCHAR,\
... |
import os
import binascii
# os.urandom()γε©η¨γγ¦γη§ε―ι΅γASCIIε½’εΌγ§δ½ζγγ¦γγ γγ
secret_key = os.urandom(32)
print(secret_key)
print(binascii.hexlify(secret_key))
# secret_key2 = os.urandom(1)
# print(secret_key2)
# print(binascii.hexlify(b'0'))
# print(int(binascii.hexlify(b'0'),16))
# print(int('bdd03cb27bfd5c61254e693f246a0a2e... |
import os
import sys
from pbstools import PythonJob
import sys
import getopt
import numpy as np
import glob
import h5py
import time
import glob
import shutil
def main(argv):
opts, args = getopt.getopt(
argv,
[],
[
"output_folder=",
"model_file=",
"start_... |
import tensorflow as tf
import numpy as np
import math
class ConvKB(object):
def __init__(self, sequence_length, num_classes, embedding_size, filter_sizes, num_filters, vocab_size,
pre_trained=[], l2_reg_lambda=0.001, is_trainable=True, useConstantInit=False):
# Placeholders for input, o... |
import secrets
import datetime
import time
from flask import Flask, render_template, redirect, url_for, request, make_response
from LoginInfo import LoginInfo
import displayManager as dm
import numpy as np
path = "C:/Users/132/Desktop/WebServer/" #Change this if not me
app = Flask(__name__,template_folder= pa... |
__copyright__ = "Copyright (c) 2020 Jina AI Limited. All rights reserved."
__license__ = "Apache-2.0"
import os
import random
import sys
from jina.drivers import BaseDriver
from jina.flow import Flow
class RandomPopRanker(BaseDriver):
max_num_docs = 100
def __call__(self, *args, **kwargs):
for d in ... |
import numpy as np
import pandas as pd
from sklearn import preprocessing, model_selection, svm, neighbors, linear_model, discriminant_analysis, naive_bayes, tree
from utils import general
df = pd.read_csv('iris.data.txt', names=['sepal-length', 'sepal-width', 'petal-length', 'petal-width', 'class'])
df = df.replace({... |
#!/usr/bin/env python3
# encoding: utf-8
import setuptools
setuptools.setup(
name='reactor_bot',
version='4.5.15',
url='https://github.com/iomintz/reactor-bot',
author='Io Mintz',
author_email='[email protected]',
description='The best dang Discord poll bot aroundβ’',
long_description=open('README.rst').read(),
p... |
# -*- coding: utf-8 -*-
"""Test the layerresponse functions defined in layers.py."""
import unittest
import numpy as np
import smuthi.layers as lay
import smuthi.fields.expansions as fldex
layer_d = [0, 300, 400, 0]
layer_n = [1, 2 + 0.1j, 3, 1 + 5j]
omega = 2 * 3.15 / 550
kpar = omega * 1.7
precision = 15
class T... |
'''
A message containing letters from A-Z can be encoded into numbers using the following mapping:
'A' -> "1"
'B' -> "2"
...
'Z' -> "26"
To decode an encoded message, all the digits must be grouped then mapped back into letters using the reverse of the mapping above (there may be multiple ways). For example, "11106" c... |
import logging
import imio
import numpy as np
from skimage.segmentation import find_boundaries
def boundaries(registered_atlas, boundaries_out_path):
"""
Generate the boundary image, which is the border between each segmentation
region. Useful for overlaying on the raw image to assess the registration
... |
import pytest
@pytest.mark.parametrize("route, expected", [
("/youtube/PLdduFHK2eLvfGM7ADIbCgWHFRvu1yBNj0/", "Now, Now - MJ")
])
def test_youtube(client, route, expected):
response = client.get(route)
assert expected.encode('ascii') in response.data
@pytest.mark.parametrize("route, expected", [
("/vi... |
import json
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
from matplotlib.patches import Rectangle as rectangle
import seaborn as sns
import string
from PIL import Image
import io
import sys
import matplotlib.font_manager as fm
def retrieve_expected_responses_and_hist(expected_... |
from datetime import timedelta
from operator import methodcaller
from testtools.content import text_content
from testtools.matchers import AfterPreprocessing as After
from testtools.matchers import (
Equals, GreaterThan, IsInstance, LessThan, MatchesAll, MatchesAny,
MatchesStructure, Mismatch)
class HasHeade... |
from django.http import JsonResponse
from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from tasks.sample_tasks import create_task
from celery.result import AsyncResult
def home(request):
return render(request, "home.html")
@csrf_exempt
def run_task(request):
if request... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import socket
import subprocess
import urllib2
import json
import time
import sys, os
import multiprocessing
sys.path.append(os.path.abspath(__file__ + '/../../library/'))
import copiedRequests
MDM_HOST = "tst-mdm.safekiddo.com"
PORT = 443
TIMEOUT = 5
DISCOVERY = "discovery"... |
import confuse as cf
def configure():
config = cf.Configuration('bud', __name__)
config.set_file('./config.yaml')
return config
def get_path():
cfg = configure()
return str(cfg["directory_path"])
|
# -*- encoding: utf-8 -*-
from habet.response import Response
class BaseServerError(Exception):
def __init__(self):
self.status = None
self.code = None
self.message = None
self.data = None
self.content_type = 'application/json'
def as_response(self):
body = {
'error': {
'cod... |
#
# AutoCuts.py -- class for calculating auto cut levels
#
# This is open-source software licensed under a BSD license.
# Please see the file LICENSE.txt for details.
#
import numpy as np
from ginga.misc import Bunch
#from ginga.misc.ParamSet import Param
from ginga.util import zscale
have_scipy = True
autocut_method... |
"""
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distri... |
from flask_login import LoginManager
from flask_sqlalchemy import SQLAlchemy
db = SQLAlchemy()
login_manager = LoginManager()
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Nekozilla is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Nekozilla is distributed... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.