content stringlengths 5 1.05M |
|---|
import random,math
def distribution(decay,buckets):
"Return random numbers, sum noamrlzes 0..1"
tmp=[random.random()]
for _ in range(buckets-1):
old=tmp[-1];
tmp += [old*decay]
s=sum(tmp)
return sorted([x/s for x in tmp])
def run(n=1000,decay=0.99,dimensions=10, buckets = 10):
ds=[distribution... |
from datetime import datetime
import pytest
from sqlalchemy import func
from mock_alchemy.mocking import UnifiedAlchemyMagicMock
from quarry.web.models.query import Query
from quarry.web.models.star import Star
from quarry.web.models.queryrevision import QueryRevision
from quarry.web.models.queryrun import QueryRun
f... |
#!/bin/python
import datetime
class employee:
first=\"\";
last=\"\";
department=\"\";
start_date=\"\";
end_date=\"\";
def set_all(self,first,last,depart,start,end):
self.first=first;
self.last=last;
self.department=depart;
self.start_date=start;
self.end_date=end;
def date_diff(self... |
import socket
import time
from menu import *
DEBUG = 0
class Client(object):
def __init__(self,host="localhost",port=9046):
try:
self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
if DEBUG:
print "Socket Created."
except socket.error:
if DEBUG:
print "Failed to create socket"
sys.exit... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Author: Jialiang Shi
from sonarqube.utils.rest_client import RestClient
from sonarqube.utils.config import (
API_PROJECTS_BULK_DELETE_ENDPOINT,
API_PROJECTS_SEARCH_ENDPOINT,
API_PROJECTS_CREATE_ENDPOINT,
API_PROJECTS_DELETE_ENDPOINT,
API_PROJECTS_UPDAT... |
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^door/', views.changeState, name='changeState'),
] |
from ..en import Provider as PersonProvider
class Provider(PersonProvider):
pass
|
from data import *
def test_abn_lookup(py):
"""Verify search abn"""
# GIVEN ABN lookup page has loaded
# WHEN user types search query into Search field
# AND clicks search button
# THEN results contain expected results, such as ABN number, Name, Type, Location
py.visit(BASE_URL)
py.get(SE... |
from kat.harness import Query, EDGE_STACK
from abstract_tests import AmbassadorTest, ServiceType, HTTP
# STILL TO ADD:
# Host referencing a Secret in another namespace?
# Mappings without host attributes (infer via Host resource)
# Host where a TLSContext with the inferred name already exists
class HostCRDSingle(Amb... |
from django.apps import apps
from django.conf import settings
def UserCls():
return apps.get_model('cauth', settings.AUTH_USER_MODEL.split('.')[-1])
|
#!/usr/bin/env python3
import random
from typing import List
class D6s:
@staticmethod
def roll(count: int = 1) -> List[int]:
results = []
for _ in range(count):
results.append(random.randint(1, 6))
return results
|
#
# PySNMP MIB module DNOS-METRO-DOT1AG-PRIVATE-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DNOS-METRO-DOT1AG-PRIVATE-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:36:55 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python ve... |
import numpy as np
from FUNCS import FNS, RK4
from PTSS import PtssJoint as ptssjnt
from PTSS import PtssSpatial as ptssspt
# variable class for Leg Module
class LegVar:
def __init__(self, num_deg):
self.num_deg = num_deg
self.ppc = self.Parietal(num_deg)
self.mtc = self.Motor()
... |
#import spacy
#nlp = spacy.load('en')
def spacy_extract(text_string):
out = dict()
doc = nlp(text_string)
for ent in doc.ents:
if ent.label_ not in out:
out[ent.label_] = list()
out[ent.label_].append(ent.text)
return out
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2017-10-17 10:50
from __future__ import unicode_literals
from django.db import migrations, models
import wagtail.core.fields
class Migration(migrations.Migration):
dependencies = [
('events', '0013_event_parent'),
]
operations = [
... |
#!/usr/bin/env python
from setuptools import setup, find_packages
try:
import pypandoc
try:
pypandoc.convert_file("README.md", "rst", outputfile="README.rst")
except (IOError, ImportError, RuntimeError):
pass
long_description = pypandoc.convert_file("README.md", "rst")
except (IOError,... |
from django.test import TestCase
from dwitter.templatetags.insert_magic_links import insert_magic_links
class DweetTestCase(TestCase):
def test_insert_magic_links_bypasses_html(self):
self.assertEqual(
'prefix <h1>content</h1> suffix',
insert_magic_links('prefix <h1>content</h1> su... |
# Створити змінну n ( Де n - кількість елементів ) і пустий массив arr = [ ] .
# Ввести з клавіатури числа і добавити в массив число в квадраті .
# В кінці надрукувати сам массив тобто print( arr ) .
# 5 ** 2, pow(3, 2), 4 * 4
print("Enter number of elements in array")
n = int(input())
arr = [0 for x i... |
import os
import re
from distutils.core import setup
tests_require = [
'pytest',
'pytest-runner',
'python-coveralls',
'pytest-pep8'
]
install_requires = [
'pathlib'
]
def sanitize_string(str):
str = str.replace('\"', '')
str = str.replace("\'", '')
return str
def parse_version_file... |
from django.db import models
from django.contrib.auth.models import User
from django.conf import settings
from django.contrib.auth import get_user_model
from django.db.models.signals import post_save
from django.dispatch import receiver
from rest_framework.authtoken.models import Token
@receiver(post_save, sender=sett... |
import requests
from bs4 import BeautifulSoup
URL = "https://www.amazon.in/Wear-Your-Opinion-Printed-T-Shirt/dp/B09BZFM6SY/ref=sr_1_4_sspa?crid=3SRLZDG0M0VNR&dchild=1&keywords=code&qid=1635232842&s=apparel&sprefix=cod%2Cfashion%2C254&sr=1-4-spons&psc=1&spLa=ZW5jcnlwdGVkUXVhbGlmaWVyPUEyUkJSMEVXVzZUMzBKJmVuY3J5cHRlZElkP... |
import random
import discord
from jb2.bot import bot
from jb2.embed import error_embed
def przondling(text):
przondling_factor = 0.3
letter_dict = {
'q': 'qwas',
'w': 'qweasd',
'e': 'wresfd',
'r': 'rtefdg',
't': 'yrtghf',
'y': 'uythg',
'u': 'iuyjkh',
... |
import torch
import torchvision
import torchvision.transforms as T
import random
import numpy as np
from scipy.ndimage.filters import gaussian_filter1d
import matplotlib.pyplot as plt
from cs231n.image_utils import SQUEEZENET_MEAN, SQUEEZENET_STD
from PIL import Image
def preprocess(img, size=224):
transform = T.C... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Project : MeUtils.
# @File : sim_app
# @Time : 2021/9/1 下午2:45
# @Author : yuanjie
# @WeChat : 313303303
# @Software : PyCharm
# @Description : https://blog.csdn.net/Datawhale/article/details/107053926
# http://cw.hubwiz.com/card/c/s... |
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Silo(AutotoolsPackage):
"""Silo is a library for reading and writing a wide variety of sci... |
from plugin.core.database.manager import DatabaseManager
from stash import Stash, ApswArchive
from threading import Lock, Thread
import logging
import time
DEFAULT_SERIALIZER = 'msgpack:///'
log = logging.getLogger(__name__)
class CacheManager(object):
active = {}
_lock = Lock()
_process_interval = 1... |
import numpy as np
from torch.utils.data import Dataset, DataLoader
import torchvision.transforms as transforms
import torch
from samplers import TripletSampler
from utils import args
class BaseData(Dataset):
def __init__(self, data, neg_samples, sampling_method="triplet"):
self.data = data
self.... |
from jina import Executor, requests
import rocketqa
class RocketQADualEncoder(Executor):
"""
Calculate the `embedding` of the passages and questions with RocketQA Dual-Encoder models.
"""
def __init__(self, model, use_cuda=False, device_id=0, batch_size=1, *args, **kwargs):
"""
:para... |
import os
import json
import statistics
import pandas as pd
import numpy as np
class DataSet:
def __init__(self, D, name="default"):
self.D = D
self.n, self.d = self.D.shape
self.name = name
def getResource(self, index):
return self.D.iloc[index, :]
def saveMetaData(self... |
"""
This package contains the JIRA implementations of the interfaces in
server.git.Interfaces.
"""
from urllib.parse import urljoin
import logging
import os
from oauthlib.oauth1 import SIGNATURE_RSA
from requests_oauthlib import OAuth1
from IGitt.Interfaces import get
from IGitt.Interfaces import Token
from IGitt.Uti... |
#!/usr/bin/env python3
"""Rewrap lines without breaking words"""
import sys
import argparse
import textwrap
def main():
parser = argparse.ArgumentParser(description=sys.modules[__name__].__doc__)
parser.add_argument('infile', type=argparse.FileType('r', encoding='UTF-8'), help='Input file')
parser.add_ar... |
import logging
import tmllc
logging.basicConfig(format='%(asctime)s %(levelname)s: %(name)s(%(funcName)s): %(message)s', level=logging.INFO)
# Transforming the TESS files into big tables that are saved in pickle form
# TODO allow for a function to be applied to the data first!
tmllc.utils.fits2pickle(["planet", "non... |
##Write code that uses the string stored in org and creates an acronym which is assigned to the variable acro. Only the first letter of each word should be used, each letter in the acronym should be a capital letter, and there should be nothing to separate the letters of the acronym. Words that should not be included i... |
import pandas as pd
import numpy as np
import numerical as mynum
def test_filter_constant():
"""Test if function correctly deletes columns"""
testDf = pd.DataFrame(
{"time": np.arange(5), "one": np.ones(5), "zero": np.zeros(5)}
)
resultDf = pd.DataFrame({"time": np.arange(5), "zero": np.zeros... |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: jar.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 _re... |
"""
--- Day 22: Slam Shuffle ---
https://adventofcode.com/2019/day/22
"""
import re
import aocd
DATA = aocd.data.splitlines()
nCards = 10007
techniques = {
re.compile(r"deal into new stack"): lambda p: nCards - 1 - p,
re.compile(r"cut (-?\d+)"): lambda p, n: (p - int(n)) % nCards,
re.compile(r"deal with ... |
# Importing libraries
import pandas as pd
import numpy as np
import math
import operator
import matplotlib.pyplot as plt
from sklearn import datasets, neighbors
from mlxtend.plotting import plot_decision_regions
#### Start of STEP 1
# Importing data
data = pd.read_csv('artists1.csv')
#Normalization
#co... |
"""
HTTP utilities. Contains no business logic.
This mainly exists because we didn't want to depend on werkzeug.
"""
import re
from typing import Dict
from typing import Iterable
from typing import List
from typing import Tuple
# copied from werkzeug.http
_accept_re = re.compile(
r"""
( ... |
# -*- coding: utf-8 -*-
#
# This file is part of the ska-tmc-common project
#
#
#
# Distributed under the terms of the BSD-3-Clause license.
# See LICENSE.txt for more info.
""" Tango Group Client Code
"""
# Tango imports
import tango
from tango import DevFailed
import logging
class TangoGroupClient:
"""
Cla... |
#Glenn Gasmen's struggle with recursive modes
from Xml.Xslt import test_harness
sheet_1 = """<xsl:stylesheet
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:ft="http://xmlns.4suite.org/ext"
xmlns:ot='http://namespaces.opentechnology.org/talk'
xmlns:dc='http://purl.org/metadata/dublin_core'
extension-... |
from ylang.el import *
from contextlib import contextmanager
def y_eq(a, b):
return a is b
def y_is(a, b):
return a == b
def y_next(h):
if keywordp(car(h)):
return cddr(h)
else:
return cdr(h)
def y_key(x):
if keywordp(x):
return intern(symbol_name(x)[1:])
else:
return x
def y_for(h):
... |
"""Main application and routing logic for TwitOff."""
from decouple import config
from flask import Flask, render_template, request
from .models import DB, User
from .predict import predict_user
from .twitter import add_or_update_user
def create_app():
"""Create and configure and instance of the Flask application... |
# Generated by Django 3.2.5 on 2021-07-30 15:48
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('mweb', '0012_certificate'),
]
operations = [
migrations.AlterField(
model_name='certificate',
name='cd... |
# Created By: Hector Rodriguez
from selenium.webdriver.common.by import By
from selenium import webdriver
import os, time, sys
import bot_functions as bf
class InstagramBot:
def __init__(self, username = None, password = None):
"""Initialize parameters for Instagram login."""
self.username = usern... |
import csv
from tqdm import tqdm
import sys
from transformers import BertWordPieceTokenizer
tokenizer = BertWordPieceTokenizer(
"/scratch/gpfs/altosaar/dat/longform-data/BERT/bert-base-uncased.txt",
lowercase=True,
)
csv.field_size_limit(sys.maxsize)
ifile = open("fake-news.csv", "r")
reader = csv.reader(ifile... |
"""
Copyright Zapata Computing, Inc. All rights reserved.
"""
import os
import setuptools
readme_path = os.path.join("..", "README.md")
with open(readme_path, "r") as f:
long_description = f.read()
setuptools.setup(
name = "z-lstm",
version = "0.1.0",
... |
import tempfile
import contextlib
import os
import pytest
from gitorg import git
from gitorg.cli import run
@contextlib.contextmanager
def temp_cd():
with tempfile.TemporaryDirectory() as tmpdirname:
with cd(tmpdirname):
yield tmpdirname
@contextlib.contextmanager
def cd(dirname):
curd... |
import requests,re,time,math,random,os
from bs4 import BeautifulSoup
def Get_PostData(LoginUrl):
'''
获取登录参数
'''
Req_Class = requests.get(LoginUrl)#获取Get对象,准备那曲第一次Cookie
Req_Cookies = Req_Class.cookies["JSESSIONID"]#获取请求Cookie
Html_Text = Req_Class.text#获取源码
Soup_Class = BeautifulSoup(Html... |
import log2
print "f1 0 4096 10 1"
log2.accelerando(0.5, 3.7, 0.4, 0.01)
print "f1 5.2 4096 10 0 1.3"
log2.accelerando(5.2, 11.7, 1.2, 0.5)
|
from collections import Counter
from contextlib import contextmanager
from datetime import date
from time import time
OPERATION_THRESHOLD_IN_SECONDS = 2.2
ALERT_THRESHOLD = 3
ALERT_MSG = 'ALERT: suffering performance hit today'
violations = Counter()
def get_today():
"""Making it easier to test/mock"""
retu... |
class Tuple:
pass
|
import struct
from block.Block import Block
from block.UserDirBlock import UserDirBlock
from block.DirCacheBlock import *
from ADFSFile import ADFSFile
from ADFSNode import ADFSNode
from FileName import FileName
from FSError import *
from FSString import FSString
from MetaInfo import *
class ADFSDir(ADFSNode):
def ... |
'''
Crie um programa que leia o ano de nascimento de sete pessoas.
No final, mostre quantas pessoas ainda não atingiram a maioridade e quantas já são maiores.
'''
from datetime import datetime
now = datetime.now()
now = now.year
contMen = 0
contMai = 0
for c in range (0,7):
nasc = int(input('Digite o Ano de Nascime... |
import os
import pandas as pd
import numpy as np
import matplotlib.pylab as plt
from astropy.io import fits
from astropy.io import fits
from wotan import flatten
from process_lightcurve_with_two_cadence import process_lightcurves_into_input_representation
from preprocess import lightcurve_detrending
def process_toi_... |
import pygame
import random
pygame.init()
#dimensions
screen_x = 900
screen_y = 500
#window config
game_window = pygame.display.set_mode((screen_x, screen_y))
pygame.display.set_caption("Gold Cave")
game_running = True
#tick
clock = pygame.time.Clock()
#colors
red = (252, 19, 3)
purple = (96, 50, 168)
white = (2... |
"""
Copyright (c) 2020 Kudelski Security, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writ... |
#!/bin/env python
# Automatically translated python version of
# OpenSceneGraph example program "osgtexturecompression"
# !!! This program will need manual tuning before it will work. !!!
import sys
from osgpypp import osg
from osgpypp import osgDB
from osgpypp import osgGA
from osgpypp import osgText
from osgpypp ... |
# -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2017 CERN.
#
# Invenio 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 2 of the
# License, or (at your option) any later... |
from src.controller import EventDispatcher as Ed
from src.events import ExitMaze
from src.model.entities import Entity
class Ladder(Entity):
def __init__(self):
super().__init__(walkable=True)
def interact(self):
Ed.post(ExitMaze()) |
# MIT License
#
# Copyright (c) 2018, Andrew Warrington.
#
# 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,... |
a, b = input().split()
while (a, b) != ("0", "0"):
c = b.replace(a, '')
if c == '':
print(0)
else:
print(int(c))
a, b = input().split()
|
# Created by Patrick Kao
from agents.random_agent import RandomAgent
from environments.hearts import SimpleHearts
from game import Game
def test_hearts():
game = Game(SimpleHearts, [RandomAgent]*4)
result = game.run()
print(result)
if __name__ == "__main__":
test_hearts()
|
"""
Extensions to serve static and media files
"""
from ._base import SimpleTag
from django.contrib.staticfiles.storage import staticfiles_storage
from django.conf import settings as dj_settings
class StaticExtension(SimpleTag):
"""Django-like static tag"""
tags = set(['static'])
def get_... |
import logging
def configure_logging(cfg):
"""
Initialize the root logger from a HayrackConfiguration object
"""
logger = logging.getLogger()
logger.setLevel(cfg.logging.verbosity)
if cfg.logging.logfile:
logger.addHandler(logging.FileHandler(cfg.logging.logfile))
if bool(cfg.logg... |
from appdirs import AppDirs
import unittest
import radiam
import os
import tempfile
import shutil
from radiam_api import RadiamAPI
# copied this from radiam_tray, might not all be necessary for testing
dirs = AppDirs("radiam-agent", "Compute Canada")
os.makedirs(dirs.user_data_dir, exist_ok=True)
tokenfile = os.path.j... |
#!/usr/bin/env python
from tools.load import LoadMatrix
lm=LoadMatrix()
traindat = lm.load_dna('../data/fm_train_dna.dat')
testdat = lm.load_dna('../data/fm_test_dna.dat')
label_traindat = lm.load_labels('../data/label_train_dna.dat')
parameter_list=[[traindat,testdat,label_traindat,1,1e1, 1e0],[traindat,testdat,label... |
from .LocallyConnected1d import LocallyConnected1d
from .LocallyConnected2d import LocallyConnected2d |
#
# This file is part of BRANCHPRO
# (https://github.com/SABS-R3-Epidemiology/branchpro.git) which is released
# under the BSD 3-clause license. See accompanying LICENSE.md for copyright
# notice and full license details.
#
"""Processing script for Hainan, China data from [1]_.
It rewrites the data file into the forma... |
import sys, os, glob
from glbase3 import *
sys.path.append('../../')
import shared
[os.remove(f) for f in glob.glob('*.tsv')]
[os.remove(f) for f in glob.glob('*.glb')]
def qcollide(al, ar, bl, br):
return ar >= bl and al <= br # return(self.loc["right"] >= loc.loc["left"] and self.loc["left"] <= loc.loc["right"]... |
import re
import numpy as NP
from matplotlib import pyplot as PLT
import sys, getopt
import matplotlib.lines as mlines
import matplotlib.patches as mpatches
import os
import statistics
SERVICE_NUMBERS = [0, 1, 2, 4, 8, 16]
path = ""
class FileParser:
def __init__(self):
self.cbench_filenames = []
de... |
#!/usr/bin/env python
from _winreg import *
from subprocess import check_output
regKeys = []
regKeys.append(['SOFTWARE\\Policies\\Microsoft\\Windows\\WindowsUpdate', '',REG_SZ, None])
regKeys.append(['SOFTWARE\\Policies\\Microsoft\\Windows\\WindowsUpdate\\AU', '',REG_SZ, None])
regKeys.append(['SOFTWARE\\Policies\\Mi... |
from .mongo_connector import db
def get_client():
return db
|
"""
Running example 6.9 from Ang & Tang 1984
"""
import paransys
import numpy as np
# Call ParAnsys
mc = paransys.MonteCarlo()
# Console log On
mc.Info(True)
# Create random variables
mc.CreateVar('y', 'gauss', 40, cv=0.125)
mc.CreateVar('z', 'gauss', 50, cv=0.050)
mc.CreateVar('m', 'gauss', 1000, std=0.200*1000)
... |
# -*- coding: utf-8 -*-
# @Time : 2020-10-07 13:33
# @Author : Zhiwei Yang
|
import random
class Counter:
def __init__(self):
self.reset()
def get(self):
return self.count
def increment(self):
self.count += 1
def reset(self):
self.count = 0
class ProbabilisticCounter(Counter):
def __init__(self, a = 2):
super().__init__()
... |
class Colors:
BLACK_COLOR = (0, 0, 0)
WHITE_COLOR = (255, 255, 255)
DARK_BLUE = (0, 0, 100)
DARK_GRAY = (75, 75, 75)
TROLL_GREEN = (100, 180, 150)
ORC_GREEN = (150, 250, 230)
BLOOD_RED = (255, 50, 50) |
# Copyright 2020-2021 Axis Communications AB.
#
# For a full list of individual contributors, please see the commit history.
#
# 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... |
orders = [
{
'name': 'Mario',
'flavor': 'pepperoni'
},
{
'name': 'Marcolino',
'flavor': 'barbecue'
}
]
for order in orders:
s = 'Name: {0}, Flavor: {1}'
print(s.format(order['name'], order['flavor']))
|
"""
jupylet/audio/__init__.py
Copyright (c) 2020, Nir Aides - nir@winpdb.org
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,... |
from setuptools import setup, find_packages
with open("README.md", "rt", encoding="utf8") as f:
readme = f.read()
setup(
name="eth2_api_testgen",
description="Eth2 API test gen",
version="0.0.1",
long_description=readme,
long_description_content_type="text/x-markdown",
author="protolambda"... |
# tests/test_basic.py
import unittest
from base import BaseTestCase
from app import db
from app.models import Command
from app.core.helpers import getUserId, getGroupId, objectToJson
class DashboardTests(BaseTestCase):
# ensure normal behavior
def test_normal_behavior(self):
with self.client:
self.client.post... |
from dataclasses import dataclass
from functools import lru_cache
from pathlib import Path
from typing import List, Set
@dataclass(frozen=True)
class Location:
x: int
y: int
def __add__(self, other: "Location") -> "Location":
return Location(
x=self.x + other.x,
y=self.y +... |
import setuptools
import yaml
meta = yaml.load(open('./meta.yaml'), Loader=yaml.FullLoader)
setuptools.setup(
name=meta['package']['name'],
author='aster',
author_email='galaster@foxmail.com',
url=meta['source']['url'],
version=meta['package']['version'],
description='',
packages=['sgan']... |
"""All functions in this script are scraped via the :py:mod:`inspect` module when checking the arguments given in the config under the 'constraints' object/subdict.
A single value should be returned for any constraint.
"""
import numpy as np
import hawks.objectives
def overlap(indiv):
"""Calculate the amount of ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Graph
Contains methods relating to graph image exporting
"""
import urllib3
import requests
import os
import logging
from datetime import datetime
from requests import Response
from pathlib import PurePath
from pybix.api import ZabbixAPI
logger = logging.getLogger(... |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
"""
linprog.py: Linear program to empirically find values of a, b, c.
a is how much a constraint going from the whole plain to a circle is worth.
b is how much a constraint going from a circle to two points is worth.
c is how much a constrint going from two points to ... |
''' My Application '''
import re
import yaml
from quick_scheme import KeyBasedList
from quick_scheme import ListOfReferences, ListOfNodes
from quick_scheme import SchemeNode, Field
from quick_scheme import qs_yaml
DATA = '''
version: 1
updates:
# this is our update log to demonstrate lists
- '2019-08-14: init... |
# -*- coding: utf-8 -*-
import numpy as np
import pandas as pd
import datetime
import matplotlib.pyplot as plt
from logproj.P8_performanceAssessment.utilities_movements import getCoverageStats
from logproj.P9_workloadPrediction.demand_assessment import getAdvanceInPlanning
from logproj.ml_graphs import plotGraph
#%%
... |
import io
import gzip
import kvenjoy.graph
from kvenjoy.io import *
class Variable:
"""Representa a variable.
A variable has a X/Y coordinates and a name.
"""
def __init__(self, x, y, name):
self.x = x
self.y = y
self.name = name
@classmethod
def load(cls, stm):
... |
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import scipy.stats
from finished_files.survey_data_dictionary import DATA_DICTIONARY
# Load data
# We want to take the names list from our data dictionary
names = [x.name for x in DATA_DICTIONARY]
# Generate the list of names to import
usecols =... |
#coding: utf-8
import json
from m3_ext.ui.app_ui import (
DesktopModel, DesktopLoader, BaseDesktopElement, MenuSeparator
)
from m3.actions import ControllerCache, ActionPack
class DesktopProcessor(object):
@classmethod
def filter_factory(cls, request, place):
u"""
Возвращает функцию филь... |
from .character import (
CharacterBlackSpriteMerger,
CharacterLimeSpriteMerger,
CharacterMagentaSpriteMerger,
CharacterOliveSpriteMerger,
CharacterOrangeSpriteMerger,
CharacterPinkSpriteMerger,
CharacterRedSpriteMerger,
CharacterVioletSpriteMerger,
CharacterWhiteSpriteMerger,
Cha... |
"""
Given an m x n grid of characters board and a string word, return true if word exists in the grid.
The word can be constructed from letters of sequentially adjacent cells,
where adjacent cells are horizontally or vertically neighboring.
The same letter cell may not be used more than once.
Example 1:
Input:... |
import setuptools
with open("README.md", "r", encoding="utf-8") as fh:
long_description = fh.read()
requirements = []
with open("Requirements.txt", "r", encoding="utf-8") as fh:
for line in fh.readlines():
requirements.append(line[:-1])
setuptools.setup(
name="desktop-organiser-tht",
version=... |
""" Bayes Theorem Rule """
def bayes(x,nx,y,y_x,y_nx):
return (x_y*x)/((y_nx*nx)+(y_x*x))
""" Finding P(A|B) with Bayes Theorem """
#Basic Probabilities
A = 0
notA = 1-A
B=0
notB = 1-B
#Conditional probabilities
B_A = 0
notB_A = 1 -B_A
B_notA = 0
notB_notA =1 - B_notA
#A_B = (B_A*A)/((B_notA*notA)+(B_A*A))
... |
###############################################################################
#
# uniqueMarkers.py - find a set of markers that are descriptive for a taxonomy
#
###############################################################################
# ... |
import os
# Discord Bot token here
token = os.environ.get('GLOSSY_DISCORD_TOKEN')
# Prefix for commands
prefix = '!'
# MongoDB address including any credentials
db_address = os.environ.get('GLOSSY_DB_ADDRESS')
# Name of the MongoDB database
db_name = 'ESOBot'
|
#!/usr/bin/env python
# sp800_22_serial_test.py
#
# Copyright (C) 2017 David Johnston
# This program is distributed under the terms of the GNU General Public License.
#
# This file is part of sp800_22_tests.
#
# sp800_22_tests is free software: you can redistribute it and/or modify
# it under the terms of the GNU G... |
"""Commands to interact with Yara rules stored in Yeti."""
import os
import click
from yeti_python_api.api import YetiAPI
from cli.config import config
@click.command()
@click.option('--recurse', help='Recurse in directory', is_flag=True, default=False) # pylint: disable=line-too-long
@click.option('--verbose', he... |
# Write a program to sort a stack in ascending order. You should not make any assumptions about how the stack is implemented. The following are the only functions that should be used to write this program: push | pop | peek | isEmpty.
class Stack(list):
def push(self, val):
self.append(val)
# pop == list.pop
de... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.