content stringlengths 5 1.05M |
|---|
from __future__ import print_function
import numpy as np
import os
import sys
import cv2
import random
import pickle
import torch
import torch.backends.cudnn as cudnn
from torch.autograd import Variable
import torch.optim as optim
from torch.optim import lr_scheduler
import torch.utils.data as data
import torch.nn.ini... |
import numpy as np
import matplotlib.pyplot as plt
import firebase_admin
from firebase_admin import credentials, db
# Get from Realtime Database
cred = credentials.Certificate('../secrets/clean-sylph-151200-ac19c9e9e196.json')
#default_app = firebase_admin.initialize_app(cred)
firebase_admin.initialize_app(cred, {
... |
import re
class Preprocessor():
"""Preprocess some generalised formats."""
def __init__(self):
pass
def preprocess(self, line):
# IP Adresses
line = re.sub('[0-9]*\.[0-9]*\.[0-9]*\.[0-9]*' , '<ip>', line)
# Time
line = re.sub('(\d{1,2}):(\d{1,2}):(\d{2}) ?([AaPp][Mm... |
from rest_framework import serializers
from rest_framework import viewsets
from allianceutils.api.permissions import GenericDjangoViewsetPermissions
from allianceutils.api.permissions import SimpleDjangoObjectPermissions
from test_allianceutils.tests.viewset_permissions.models import NinjaTurtleModel
from test_allianc... |
from setuptools import setup
setup(
use_scm_version={"write_to": "src/apipkg/version.py"},
)
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
from pygments import style
from pygments import token
KEYWORD = "bold #179CDE"
STRING = "#00af00"
NAMES = "#000"
NUMBERS = "#8700ff"
COMMENTS = "#888"
OPERATORS = "#444"
class BotogramStyle(style.Style):
"""Pygments style for the botogram documentation"""
background_color = "#fff"
highlight_color = "#f3... |
from datetime import datetime, timedelta
from random import randint
from zeeguu_core_test.rules.base_rule import BaseRule
from zeeguu_core_test.rules.cohort_rule import CohortRule
from zeeguu_core_test.rules.user_rule import UserRule
from zeeguu_core.model.user_exercise_session import UserExerciseSession
class Exercis... |
#!/usr/bin/env python3
#
# input.py
"""
Input functions (prompt, choice etc.).
"""
#
# Copyright © 2020-2021 Dominic Davis-Foster <dominic@davis-foster.co.uk>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to d... |
#!/usr/bin/env python
import os
import africastalking
def main():
africastalking.initialize(os.getenv('USERNAME', 'sandbox'), os.getenv('API_KEY', 'fake'))
sms = africastalking.SMS
def on_finish(error, data):
if error is not None:
raise error
print('\nAsync Done with -> ' + s... |
import pygame, sys
import time
def image_from_url(url):
try:
from urllib2 import urlopen
from cStringIO import StringIO as inout
except ImportError:
from urllib.request import urlopen
from io import BytesIO as inout
myurl = urlopen(url)
return inout(myurl.read())
pygam... |
# -*- coding: utf-8 -*-
import os, os.path
from amplee.indexer import *
from amplee.atompub.collection import FeedHandler
from amplee.loader import AtomPubLoader
from amplee.error import ResourceOperationException
from amplee.utils.mediatype import get_best_mimetype
from amplee.atompub.workspace import *
from amplee.a... |
from pgdrive.component.blocks.create_block_utils import ExtendStraightLane, CreateRoadFrom, CreateAdverseRoad
from pgdrive.component.blocks.pg_block import PGBlock, PGBlockSocket
from pgdrive.component.lane.straight_lane import StraightLane
from pgdrive.component.road.road import Road
from pgdrive.constants import Line... |
import time
import sys
import os
import tempfile
import tornado
import random
from circus.util import papa
from circus.client import make_message
from circus.tests.support import TestCircus, async_poll_for, truncate_file
from circus.tests.support import EasyTestSuite, skipIf, IS_WINDOWS
from circus.stream import FileS... |
import copy
import time
import psutil
import numpy as np
import torch
import torch.optim as optim
from torch.autograd import Variable, grad
from HyperSphere.BO.acquisition.acquisition_functions import expected_improvement
from HyperSphere.BO.utils.sobol import sobol_generate
N_SPREAD = 20000 # Number of sobol sequen... |
from django.db import models, connection
class Area(models.Model):
id = models.IntegerField(primary_key=True)
name = models.CharField(max_length=200)
longitude = models.FloatField()
latitude = models.FloatField()
def number_of_locations(self):
"""
Returns the number of locations f... |
# -*- coding: utf-8 -*-
"""
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Mobius Transformations of the Hyperbolic 3-Space
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Code exported and adapted from Roice Nelson's code at
"https://www.shadertoy.com/view/MstcWr"
Reference:
"Visual complex analysis" by... |
# -*- coding: utf-8 -*-
#
# Copyright 2020 Chris Myers
#
# 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 ... |
import math
# PARI GP CODE: x=5;y=13;for(i=0,2000,t=(-x)%factor(y-x)[1,1];x+=t;y+=t;y+=gcd(x,y);x+=1;print(t))
# MORE POLITE (?): x=5;y=13;for(i=0,2000,t=vecmin(apply(m->(-x)%m, factor(y-x)[,1]));x+=t;y+=t;y+=gcd(x,y);x+=1;print(t))
"""
(x, y) = (172, 513). find least natural number k s.t. (x+k, y+k) is not coprime.... |
from __future__ import absolute_import
from __future__ import print_function
from .._abstract.abstract import BaseAGSServer
import json
########################################################################
class GeoDataService(BaseAGSServer):
"""
Represents a single mobile service layer
"""
_url = No... |
from pythonosc import osc_server
from DMXEnttecPro import Controller
from masochisticlighting.scenes.bedroom import Bedroom
# Configuration
controller_address = '/dev/ttyUSB0'
osc_server_ip = "192.168.0.33"
osc_server_port = 5005
# Build the scene
scene = Bedroom(Controller(controller_address))
# Start the Server
os... |
from django.contrib import admin
from django.utils.html import format_html
from .models import BPost
@admin.register(BPost)
class BPostAdmin(admin.ModelAdmin):
def has_add_permission(self, request, obj=None) -> bool:
return False
def has_change_permission(self, request, obj=None) -> bool:
r... |
# coding: utf-8
import operate_file.operate_file as operate_file
import configuration.configuration as configuration
import shutil
import error_check
def get_distance_of_two_CAs(axes_0, axes_1):
distance = 0.0
for i in range(3):
distance += (axes_0[i] - axes_1[i]) * (axes_0[i] - axes_1[i])
retur... |
import os
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
def test_groups(host):
assert host.group('test_basic').exists
assert host.group('test_one').exists
assert host.group('test_two').e... |
from django.db import models
class GroupQuerySet(models.QuerySet):
def of_user(self, user):
return self.filter(
users__exact=user
).order_by('groupuser__order')
|
import sys
import os
import pickle
import math
import numpy as np
import matplotlib.pyplot as plt
VED_min = 155
VED_max = 180
os.chdir('C:/Users/Sarah Hanna/Documents/Data/WHI long term record/coatings/')
file = open('coating thicknesses by air mass for 69.76nm to 220.11nm-spikes_fixed.binpickl', 'r')
coating_data = ... |
#!/usr/bin/env python
import argparse
import json
import logging
import re
import sys
from datetime import datetime
from pathlib import Path
from tqdm import tqdm
LOGGER = None
NOW = datetime.now()
def get_logger() -> logging.Logger:
"""
Get a logger
"""
global LOGGER
if LOGGER is None:
... |
# TODO: Fix this after finishing ffn.py
# Abstract API class
import os
from dataclasses import dataclass
HEADERS = { # TODO: Figure out which of these are unneeded
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; "
"x64) AppleWebKit/537.36 (KHTML, "
"like Gecko) Chrome/77.0.... |
import requests
import csv
import os
from datetime import datetime
from elasticsearch import Elasticsearch
import zipfile
months = ['JAN','FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC']
fnoStocks = []
dayInt = datetime.now().day
dayStr = str(dayInt)
if dayInt < 10:
dayStr = '0' + daySt... |
#%%
import numpy as np
import pandas as pd
import altair as alt
# Load the production data.
data = pd.read_csv('./processed/whale_catches.csv')
data['Year'] = pd.to_datetime(data['Year'], format='%Y')
# Generate JSON vis for subcategories
# for g, d in data.groupby('subcategory'):
chart= alt.Chart(data).encode(
... |
# Copyright 2021 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
# Generated by Django 2.2.6 on 2020-12-15 15:58
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Comment',
fields=[
('id', models.AutoField(... |
"""
classes and methods related to repition counting in text
"""
from itertools import tee, izip, islice, groupby
import yaml
from collections import defaultdict
from cluster import HierarchicalClustering # , KMeansClustering
from fuzzywuzzy import fuzz
from functools import partial
# pylint: disable=R0913
FUZZY_ME... |
"""
constants.py
Parameters for splitting into train and test and training parameters.
"""
# Splitting parameters
TEST_RATIO = 0.2
RANDOM_SEED = 1234
# Training parameters
BATCH_SIZE = 16
LEARNING_RATE = 0.001
NB_EPOCHS = 250
|
import numpy as np
def decode_yolo_bbox(img: np.ndarray, bbox: np.ndarray):
'''
Transformar x, y, w, h normalizados em x_min, y_min, x_max, y_max
'''
height = img.shape[0]
width = img.shape[1]
c_x = bbox[0] * width
c_y = bbox[1] * height
half_w = (bbox[2] / 2) * width
... |
from abc import ABCMeta, abstractmethod
from typing import Any
class MyBaseException(Exception, metaclass=ABCMeta):
@abstractmethod
def error_description(self) -> str:
pass
class ResourceException(MyBaseException):
def __init__(self, id: Any) -> None:
super().__init__()
self._id ... |
from importlib.resources import read_text
import re
def get_decomp():
d = dict()
exclusion = (set('⿰⿱⿸⿺⿳⿻⿵⿲⿹⿴⿷⿶')
| set(chr(i) for i in range(ord('①'), ord('⑳')+1)))
for row in read_text('cjkradlib.data.cjkvi_ids', 'ids.txt').strip().split('\n'):
if row[0] != '#':
cont... |
"""This file implements a very basic console version of the rock, paper
scissors game."""
from random import randint
def valid_user_input(ui: str) -> bool:
"""Determines if the passed string is a valid RPS choice."""
if ui == "rock" or ui == "paper" or ui == "scissors":
return True
return False
def left_beats_... |
__all__ = ["config", "config_hosts_blocklists", "config_hosts_various", "merge"]
|
import pandas as pd
import numpy as np
import kMeans
import Preprocesser
import Normalizer
pd.set_option('display.width', 245)
def load():
path = './data/survey2014.csv'
return pd.read_csv(path, delimiter=';')
df = load()
#Remove student 19,45,49, because of fake answers.
df = df.drop([19])
df = df.drop([45])
d... |
"""
MVDR with torchaudio
====================
**Author** `Zhaoheng Ni <zni@fb.com>`__
"""
######################################################################
# Overview
# --------
#
# This is a tutorial on how to apply MVDR beamforming by using `torchaudio <https://github.com/pytorch/audio>`__.
#
# Steps
#
# - Id... |
# -*- coding: utf-8 -*-
"""Chatbot.ipynb is also given here"""
# Libraries needed for NLP
import nltk
nltk.download('punkt')
from nltk.stem.lancaster import LancasterStemmer
stemmer = LancasterStemmer()
# Libraries needed for Tensorflow processing
import tensorflow as tf
import numpy as np
import tflearn
import rando... |
n, k = map(int, input().split())
print(sum(sorted(list(map(int, input().split())), reverse=True)[:k]))
|
from __future__ import print_function
from __future__ import division
import os
import codecs
import collections
import numpy as np
import json
import gensim
class Vocab:
def __init__(self, token2index=None, index2token=None):
self._token2index = token2index or {}
self._index2token = index2token ... |
# RemoveV
# 2021 Yong-Jun Shin
# Ctrl-Shift-P --> Terminal: Create New Integrated Terminal
# .venv\scripts\activate --> activate the virtual environment in the current folder
# gremlinpython==3.5.0 --> requirments.txt
# gremelinpython supports python 3.4 or higher
# python -m pip install -r requirements.txt
import l... |
import os
import pytest
from hailtop.batch_client.aioclient import BatchClient
DOCKER_ROOT_IMAGE = os.environ.get('DOCKER_ROOT_IMAGE', 'gcr.io/hail-vdc/ubuntu:18.04')
pytestmark = pytest.mark.asyncio
@pytest.fixture
async def client():
bc = BatchClient('test')
yield bc
await bc.close()
async def test_... |
import tensorflow as tf
from tensorflow import keras
class CTCLoss(keras.losses.Loss):
def __init__(self, logits_time_major=False, blank_index=-1,
reduction=keras.losses.Reduction.AUTO, name='ctc_loss'):
super().__init__(reduction=reduction, name=name)
self.logits_time_major = log... |
# -*- coding: utf-8 -*-
import re
from z3 import *
class VerifyZ3:
def __init__(self, network_struct, logic='QF_LRA'):
self.network_struct = network_struct
self.parser = _generate_parser()
self.z3_obj = SolverFor(logic)
def parse_property(self, property_path):
in_expr_list... |
from typing import Optional
import uuid
from pydantic import BaseModel, Field
class UserModel(BaseModel):
id: str = Field(default_factory=uuid.uuid4, alias="_id")
fname: str = Field(...)
lname: str = Field(...)
email: str = Field(...)
class Config:
allow_population_by_field_name =... |
from hash_map.map_base import MapBase
class UnsortedTableMap(MapBase):
"""Map implementation using an unordered list."""
def __init__(self):
self._table = []
def __getitem__(self, k):
"""Return value assosiated with key k (raise KeyError if not found)."""
for item in self._table... |
import shutil
from pyrefinebio import computational_result as prb_computational_result, sample as prb_sample
from pyrefinebio.api_interface import download_file, get_by_endpoint
from pyrefinebio.base import Base
from pyrefinebio.exceptions import DownloadError, MissingFile
from pyrefinebio.util import create_paginated... |
# -*- coding: utf-8 -*-
"""
Create Time: 2020/6/2 15:56
Author: 作者
"""
# -*- coding: utf-8 -*-
"""
Create Time: 2020/5/27 12:43
Author: 作者
"""
import os
import time
from datetime import datetime
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.remo... |
from vgg import VGG
from uresnet import UResNet
# Available base networks
basenets = {
"vgg": VGG,
"uresnet": UResNet,
}
|
from decimal import Decimal
class Catalan(object):
def __init__(self):
"""
Returns catalan numbers: 1 1 2 5 14 42 132...
Memoized. Should run in amortized O(1) time.
"""
self.sofar = 0
self.cache = [1]
def catalan_it(self, start=0, end=0, c=1):
for n ... |
"""Configuration parsing module.
"""
import os, argparse, yaml, logging
log_levels = {'critical': logging.CRITICAL, 'error': logging.ERROR,
'warning': logging.WARNING, 'info': logging.INFO,
'debug': logging.DEBUG, 'notset': logging.NOTSET}
def parse_cli():
"""Parse the command line ar... |
from pypy.interpreter.error import OperationError
from pypy.rlib.rstruct.error import StructError
from pypy.rlib.rstruct.standardfmttable import PACK_ACCEPTS_BROKEN_INPUT
from pypy.rlib.rstruct.formatiterator import FormatIterator, \
CalcSizeFormatIterator
class PackFormatIterator(FormatIterator):
def __in... |
# -*- coding: utf-8 -*-
"""
Created on Mon Dec 7 14:33:12 2015
@author: tobias
"""
import analysis as analysis
import ui as ui
import main as main
import management as management
import methods as methods
import function as function
import handler as handler
|
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
from pathlib import Path
import os
import json
import click
from click_project.decorators import (
argument,
group,
use_settings,
table_format,
table_fields,
flag,
option,
)
from click_project.config import config, merge_settings
from click_p... |
#!/usr/bin/python
# Start script for the pgpool service.
from __future__ import print_function
import sys
import os
import time
import subprocess
NODE = sys.argv[1]
# Time script needs to wait before executing the repair command
WAIT_TIME=15
time.sleep(WAIT_TIME)
os.environ["PCPPASSFILE"] = '/etc/pgpool-II/.pcppass... |
#-*- coding: utf-8 -*-
#
# This file belongs to Gyrid Server.
#
# Copyright (C) 2011-2012 Roel Huybrechts
# All rights reserved.
"""
Plugin to print debug and information to the terminal.
"""
from threading import Lock
from twisted.internet import task
import olof.core
ENABLED = False
class Plugin(olof.core.Plugi... |
#!/usr/bin/env python
'''
Select values of dict of a numpy arrays, shape (1,) only based on a range
(python tuple), range is inclusive (excluding is open).
Usage:
dictrestrict.py [options] <input> <var> <range>
Options:
--output=OUTPUT -o OUTPUT Output to OUTPUT instead of stdout.
--exclude -x ... |
from django.urls import path
from .views import createSubscription,stripe_customer
urlpatterns=[
path(r'createSubscription',createSubscription.as_view()),
path(r'stripe/customer',stripe_customer.as_view())
] |
import json
class ConfigParser(object):
def __init__(self, config_file):
with open(config_file, 'r') as f:
self.values = json.load(f)
|
# Copyright 2015-2017 Cisco Systems, Inc.
# 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 ... |
/home/runner/.cache/pip/pool/f2/69/cc/e650e74f8cd742905396225b4467deb07ee28a81f0a336c3c402cf4bd6 |
import typing
import nltk
import numpy as np
def tokenize_document(document: str) -> typing.List[str]:
"""
Helper method to tokenize the document.
:param document: The input document represented as a string.
:return: A list of tokens.
"""
try:
return nltk.tokenize.word_tokenize(documen... |
''' Generic Common Utility functions to perform Common Notification Operation '''
import sys
import smtplib
import email
import email.utils
import os
import time
import psycopg2
import csv
import datetime
import logging
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
f... |
"""
Methods to facilitate the formulation and solution to a specific flavor of the
Hospital/Resident matching problem used for matching
`Hidden Genius Project (HGP) <https://www.hiddengeniusproject.org/>`_ mentors
to mentees.
The conventional hopsital/resident matching problem requires a secondary
procedure for handli... |
from typing import List
from discordmenu.embed.components import EmbedMain
from discordmenu.embed.view import EmbedView
from tsutils.menu.footers import embed_footer_with_state
from padinfo.common.config import UserConfig
from padinfo.view.components.view_state_base import ViewStateBase
class SimpleTextViewState(Vi... |
'''
################################################
# 103. Binary Tree Zigzag Level Order Traversal
################################################
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
... |
#!/usr/bin/env python3
#
# Araboly 2000 Advanced Server SP4 -- everyone's favourite board game... with IRC support and fancy colours!
# Copyright (c) 2018 Lucio Andrés Illanes Albornoz <lucio@lucioillanes.de>
# This project is licensed under the terms of the MIT licence.
#
from ArabolyGenerals import ArabolyGenerals
f... |
# The return statement "hands back" a value
# to where the function itself was called
def average(numbers):
# returns the average of a given list
return sum(numbers) / len(numbers)
numbers = [1, 2, 3]
# assigns average of "numbers" to "avg" and prints it
avg = average(numbers)
print(avg)
|
#!/usr/bin/python
import subprocess as sp
import os
try:
os.makedirs('out/debuggee')
except Exception:
pass
try:
sp.check_call(['c++', '-c', 'debuggee/cpp/no_line_info.cpp', '-std=c++11', '-o', 'out/debuggee/no_line_info.o'])
# Intentionally use unnormalized path to source, so we can test breakpoint l... |
30 mtime=1527291425.549873342
30 atime=1527291425.741874025
30 ctime=1527291454.865973311
|
"""
The Sims 4 Community Library is licensed under the Creative Commons Attribution 4.0 International public license (CC BY 4.0).
https://creativecommons.org/licenses/by/4.0/
https://creativecommons.org/licenses/by/4.0/legalcode
Copyright (c) COLONOLNUTTY
"""
from typing import Iterator, Union, Dict, Callable
from si... |
from nextnanopy.utils.mycollections import DictList
from nextnanopy.inputs import InputFileTemplate
from nextnanopy.nnp.defaults import parse_nnp_variable, is_nnp_input_text, is_nnp_variable, InputVariable_nnp
class InputFile(InputFileTemplate):
def load_variables(self):
variables = DictList()
for... |
import os
import sys
try:
from setuptools import find_packages
from setuptools import setup
packages = find_packages(exclude='tests')
except ImportError:
from distutils.core import setup
packages = ['txnats']
from pip.req import parse_requirements
try:
from pip.download import PipSession
e... |
POSITIONAL_ENCODING_MAX_LENGTH_SS3 = 513
POSITIONAL_ENCODING_MAX_LENGTH_BUR = 3800
POSITIONAL_ENCODING_MAX_LENGTH_ASA = 3800
POSITIONAL_ENCODING_MAX_LENGTH_PPI = 800
POSITIONAL_ENCODING_MAX_LENGTH_EPI = 1200
POSITIONAL_ENCODING_MAX_LENGTH_PNI = 800
POSITIONAL_ENCODING_MAX_LENGTH_PSMI = 900
POSITIONAL_ENCODING_MAX_LENGT... |
import pandas
import matplotlib.pyplot as plt
datasets = ['auto.mtx', 'delaunay_n22.mtx', 'great-britain_osm.mtx']
paths = ['cuda', 'serial_cilk']
stats = {}
stats['cuda'] = []
stats['serial'] = []
stats['cilk'] = []
stats['matlab'] = [3.3, 4.43 ,1.6]
stats['cuda960'] = [0.07 + 0.08, 0.1 + 0.39 ,0.1 + 0.47]
# rea... |
# DRUNKWATER TEMPLATE(add description and prototypes)
# Question Title and Description on leetcode.com
# Function Declaration and Function Prototypes on leetcode.com
#669. Trim a Binary Search Tree
#Given a binary search tree and the lowest and highest boundaries as L and R, trim the tree so that all its elements lies ... |
import os
import numpy as np
import json
from PIL import Image, ImageDraw
from matplotlib import cm
import seaborn as sb
import matplotlib.pyplot as plt
def compute_convolution(I, T, stride=None):
'''
This function takes an image <I> and a template <T> (both numpy arrays)
and returns a heatmap where each... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('forum', '0060_auto_20150611_1026'),
]
operations = [
migrations.RenameField(
model_name='poll',
old_... |
import history_src
from history_src import History
import Request_analyser_src
from Request_analyser_src import Request_analyser
import Service_broker
import dummy
obj=Request_analyser()
#check gets()
task=obj.get_task()
full_history=obj.get_full_data()
ip_data=obj.get_ip_data()
rms_output=obj.get... |
import contextlib
import unittest
import mock
import mandrel
from mandrel import exception
from mandrel.test import utils
def scenario(func):
def wrapper(*a, **kw):
with mock.patch('mandrel.bootstrap') as bootstrap:
if hasattr(mandrel, 'config'):
reload(mandrel.config.core)
... |
from BagOfWords import BagOfWords
from NGram import NGram
from KNN import KNN
from TFID import TFID
from Centroid import Centroid
from Statistics import Statistics
import time
import importlib
import sys
import os.path
class Main:
def __init__(self):
self.version = "1.0.0"
pass
def print_usa... |
# meta classes in python
# part 1
# in this module we will cover meta classes.
# meta classes is a fairly complicated but interesting topic in python.
# we are going to start from how classes are created, instantiated, the way they work in the lower level of python.
# and then we will learn what metaclasses are, how ... |
# Copyright 2021 The Kubernetes 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 ... |
import numpy as np
import graphlearning as gl
import matplotlib.pyplot as plt
import sklearn.datasets as datasets
X,labels = datasets.make_moons(n_samples=500,noise=0.1)
W = gl.weightmatrix.knn(X,10)
model = gl.clustering.spectral(W, num_clusters=2)
pred_labels = model.fit_predict()
accuracy = gl.clustering.clusteri... |
"""Copyright (c) 2018 Great Ormond Street Hospital for Children NHS Foundation
Trust & Birmingham Women's and Children's NHS Foundation Trust
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 withou... |
from __future__ import with_statement
import os
import re
import setuptools
try:
from setuptools import setup
except ImportError:
from distutils.core import setup
NAME = "nightcappackages"
def read_file(path):
with open(os.path.join(os.path.dirname(__file__), path)) as fp:
return fp.read()
... |
#!/usr/bin/env python
from __future__ import unicode_literals
from datetime import timedelta
import functools
import string
from hypothesis import given
import hypothesis.strategies as st
from nose.tools import (eq_ as eq, assert_not_equal as neq, assert_raises,
assert_false, assert_true, asse... |
#!/usr/bin/python3
from sqlalchemy.engine.url import URL
from sqlalchemy import MetaData, create_engine
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import sessionmaker
from sqlalchemy.sql import func
from sqlalchemy import desc
from envparse import env
from datetime import datetime
TRANSACTION... |
import numpy as np
import random
from pygments import highlight
import yaml
import aiida
from aiida import orm
from aiida.engine import WorkChain, while_
from aiida.engine.persistence import ObjectLoader
from functools import singledispatch
import math
from plumpy.utils import AttributesFrozendict
from aiida.orm.nod... |
# Copyright 2020 ETH Zurich
#
# 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, sof... |
# -*- coding: UTF-8 -*-
import functools
import threading
import logging
from enum import Enum
from typing import Optional, Callable, List, Any
from dataclasses import dataclass
from sqlalchemy.orm import Query
from sqlalchemy import desc, asc
from template_exception import (
HandlerUnCallableException, InvalidQ... |
import FWCore.ParameterSet.Config as cms
from RecoParticleFlow.PFProducer.photonPFIsolationDeposits_cff import *
from RecoParticleFlow.PFProducer.photonPFIsolationValues_cff import *
pfPhotonIsolationSequence = cms.Sequence(
photonPFIsolationDepositsSequence +
photonPFIsolationValuesSequence
)
|
# -*- coding: utf-8 -*-
import sys
REQUIRED_CONFIG = []
def notify(head, body, **cfg):
if sys.platform == 'darwin':
import objc
NSUserNotification = objc.lookUpClass('NSUserNotification')
NSUserNotificationCenter = objc.lookUpClass('NSUserNotificationCenter')
notification = NSUs... |
# Copyright 2014 Facebook, Inc.
# You are hereby granted a non-exclusive, worldwide, royalty-free license to
# use, copy, modify, and distribute this software in source code or binary
# form for use in connection with the web services and APIs provided by
# Facebook.
# As with any software that integrates with the Fa... |
#!/usr/bin/env python3
'''
File name: init.py
Author: Shamal Roy <shamal.roy@gmail.com>
Version: 1.0
'''
import time
import http.client
import shutil
import os
import subprocess
def checkAEM():
try:
conn = http.client.HTTPConnection("localhost", 4502)
conn.request("GET", "/")
r... |
# Number Guessing Game, by Jackson Urquhart - 2022, 2, 28 12:11
import random as rand, tkinter as tk
def create_initial_entries():
def min_collect_func(args = None): # Func to place curser in min_num
min_num = int(min_number_entry.get()); min_number_entry.grid_remove() # Get and remove min num entry
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.