content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
# coding: utf-8
# import models into model package
from .error_enveloped import ErrorEnveloped
from .health_check_enveloped import HealthCheckEnveloped
from .inline_response200 import InlineResponse200
from .inline_response200_data import InlineResponse200Data
from .inline_response201 import InlineResponse201
from .in... | python |
__author__ = 'Bohdan Mushkevych'
from odm.document import BaseDocument
from odm.fields import StringField, ObjectIdField, DateTimeField
TIMEPERIOD = 'timeperiod'
START_TIMEPERIOD = 'start_timeperiod'
END_TIMEPERIOD = 'end_timeperiod'
FLOW_NAME = 'flow_name'
STATE = 'state'
CREATED_AT = 'created_at'
STARTED_AT = 'sta... | python |
''' This module generates charts from cohort.pickle rather than from the cumulative csvs.
'''
import os
import pandas as pd
import matplotlib.pyplot as plt
from plot_practice_charts import *
from ethnicities import high_level_ethnicities
wave_column_headings = {
"total": "All",
"all_priority": "Priority grou... | python |
# nxpy_svn --------------------------------------------------------------------
# Copyright Nicola Musatti 2010 - 2018
# Use, modification, and distribution are subject to the Boost Software
# License, Version 1.0. (See accompanying file LICENSE.txt or copy at
# http://www.boost.org/LICENSE_1_0.txt)
# See https://git... | python |
# -*- Python -*-
# license
# license.
"""
Files opening and reading/writing functions.
"""
import sys, os, bz2, lzma, json
import logging; module_logger = logging.getLogger(__name__)
# ======================================================================
def open_for_reading_binary(filename):
"""Opens binary fi... | python |
# get largest continues sum
def pair_sum(arr, target):
seen = set()
output = set()
for num in arr:
diff = target - num
if diff not in seen:
print('adding diff',diff)
seen.add(num)
else:
print('adding output',diff, seen)
outpu... | python |
#!/usr/bin/env python
"""Archive Now for python"""
# import pyhesity wrapper module
from pyhesity import *
from datetime import datetime
# command line arguments
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-v', '--vip', type=str, required=True) # cluster to connect to
parser.add_argu... | python |
# https://www.hackerrank.com/challenges/sherlock-and-anagrams/problem
def anagramPairs(s):
# Write your code here
dic = {}
res = 0
for k in range(1, len(s)):
for i in range(len(s)-k+1):
j = i+k
strr = "".join(sorted(s[i:j]))
dic[strr] = dic.get(strr,0)+1
f... | python |
"""
/******************************************************************************
* *
* Name: mylogger.py *
* ... | python |
#!/usr/bin/env python
"""Celery worker to be run as follows:
(venv) $ celery worker -A pili.entrypoints.celery.celery --loglevel=info
Environment variables (such as MAIL_SERVER, MAIL_USERNAME, etc.)
should be set using export:
(venv) $ export MAIL_SERVER=smtp.youserver.com
'export' keyword in bash sets a variable t... | python |
import asyncio
import http
import aiohttp.client
import urllib.robotparser
import datetime
import collections
import logging
import abc
logger = logging.getLogger(__name__)
import site_graph
class RequestQueue:
"""A queue of pending HTTP requests, that maintains a minimum interval between outgoing requests
I... | python |
import numpy as np
from scratch_ml.utils import covariance_matrix
class PCA():
"""A method for doing dimensionality reduction by transforming the feature
space to a lower dimensionality, removing correlation between features and
maximizing the variance along each feature axis."""
def transform(self, ... | python |
import logging
import argparse
from s3push.connector import resource
from s3push.uploader import upload
from s3push.eraser import erase
parser = argparse.ArgumentParser(
description='Upload directories and files to AWS S3')
parser.add_argument(
'path',
type=str,
help='Path to a directory of file tha... | python |
# parses vcontrold serial data
import struct
from scapy.packet import Packet, bind_layers
from scapy.fields import *
START_BYTE = 0x41
TYPES = {
0x00: "request",
0x01: "response",
0x03: "error"
}
COMMANDS = {
0x01: "readdata",
0x02: "writedata",
0x07: "functioncall"
}
class VS2Header(Packet... | python |
import os
def exists_or_create_directory(temp_path: str) -> None:
directory = os.path.dirname(temp_path)
try:
os.stat(directory)
except Exception as exp:
os.mkdir(directory)
print(str(exp) + f" -> {directory} created...") | python |
from collections import defaultdict
raw_template = []
rules = []
with open("input") as file:
raw_template = list(next(file).strip())
for line in file:
line = line.strip()
if not line:
continue
left, right = line.split("->")
left = left.strip()
right = right.... | python |
# 쿼드압축 후 개수 세기
def quadtree(arr):
l = len(arr)
if l == 1: return [1,0] if arr[0][0] == 0 else [0,1]
lu = quadtree([a[:l//2] for a in arr[:l//2]])
ru = quadtree([a[l//2:] for a in arr[:l//2]])
ld = quadtree([a[:l//2] for a in arr[l//2:]])
rd = quadtree([a[l//2:] for a in arr[l//2:]])
if l... | python |
# -*- coding: utf-8 -*-
"""
Created on Thu Nov 11 16:31:58 2021
@author: snoone
"""
import os
import glob
import pandas as pd
pd.options.mode.chained_assignment = None # default='warn'
OUTDIR3= "D:/Python_CDM_conversion/monthly/cdm_out/cdm_head"
OUTDIR2= "D:/Python_CDM_conversion/monthly/cdm_out/cdm_ob... | python |
#EsmeeEllson
#Help
#Class Attributes
#You can instantiate with AsciiTable(table_data) or AsciiTable(table_data, 'Table Title').
#These are available after instantiating AsciiTable.
Name Description/Notes
table_data = List of list of strings. Same object passed to __init__().
title = Table title string.... | python |
# -*- coding: utf-8 -*-
"""
Created on Thu Oct 21 18:32:33 2021
@author: User
"""
# Expresiones generadoras
# El módulo itertools
itertools.chain(s1,s2)
itertools.count(n)
itertools.cycle(s)
itertools.dropwhile(predicate, s)
itertools.groupby(s)
itertools.ifilter(predicate, s)
itertools.imap(function, s1, ... sN)
ite... | python |
"""Implementation of the Unet in torch.
Author: zhangfan
Email: zf2016@mail.ustc.edu.cn
data: 2020/09/09
"""
import torch
import torch.nn as nn
from network.blocks.residual_blocks import ResFourLayerConvBlock
class UNet(nn.Module):
"""UNet network"""
def __init__(self, net_args={"num_class": 1,
... | python |
import re
from textwrap import dedent
import black
import autopep8
from pkg_resources import resource_string
def get_snippet(name, decorator=True):
'Get a Python snippet function (as a string) from the snippets directory.'
out = resource_string('matflow_defdap', f'snippets/{name}').decode()
if not decor... | python |
# -*- coding:utf-8 -*-
from timeit import default_timer
import numpy as np
import matplotlib.pyplot as plt
from scipy.misc import face
# Importing global thresholding algorithms
from .global_th import otsu_threshold, p_tile_threshold,\
two_peaks_threshold, min_err_threshold
# Importing global entropy threshold... | python |
#!/usr/bin/python
import paho.mqtt.publish as publish
import paho.mqtt.client as mqtt
import ssl
auth = {
'username':"ciscohackhub.azure-devices.net/lora1",
'password':"SharedAccessSignature sr=ciscohackhub.azure-devices.net%2Fdevices%2Flora1&sig=xxxx&se=1463048772"
}
tls = {
'ca_certs':"/etc/ssl/certs/ca-cert... | python |
def input1(type = int):
return type(input())
def input2(type = int):
[a, b] = list(map(type, input().split()))
return a, b
def input3(type = int):
[a, b, c] = list(map(type, input().split()))
return a, b, c
def input_array(type = int):
return list(map(type, input().split()))
def input_string():
s = in... | python |
from sklearn.base import BaseEstimator, TransformerMixin
import re
class TextCleaner(BaseEstimator, TransformerMixin):
''' text cleaning :
input can be str, list of sring, or pandas Series
a minimal version, repacing only '\n' with ' '
'''
def __init__(self):
print('')
def f... | python |
import torch
import torch.optim as optim
from torch.optim.lr_scheduler import LambdaLR
from allenact.algorithms.onpolicy_sync.losses import PPO
from allenact.algorithms.onpolicy_sync.losses.ppo import PPOConfig
from allenact.utils.experiment_utils import (
Builder,
PipelineStage,
TrainingPipeline,
Line... | python |
import py.path
import pytest
from .conftest import TEST_PLAYBOOKS
MODULES_PATH = py.path.local(__file__).realpath() / '..' / '..' / 'plugins' / 'modules'
def find_all_modules():
for module in MODULES_PATH.listdir(sort=True):
module = module.basename
if module.endswith('.py') and not module.start... | python |
#!/usr/bin/env python
# Copyright 2014-2018 The PySCF Developers. 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
#
# U... | python |
import os
import sys
import time
import glob
import numpy as np
import pandas as pd
import torch
import utils
import logging
import argparse
import torch.nn as nn
import torch.utils
import torch.nn.functional as F
import torchvision.datasets as dset
import torch.backends.cudnn as cudnn
from copy import deepcopy
from nu... | python |
"""
hhpy
~~~~~~
The hhpy package - a Python package developed by Henrik Hanssen centered around the idea of providing
unified and convenient tools for Data Science
"""
from hhpy.main import *
from hhpy.ds import *
from hhpy.ipython import *
from hhpy.modelling import *
from hhpy.plotting import *
from hhpy.regression... | python |
"""
Copyright 2017 Nikolay Stanchev
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, softwa... | python |
import importlib
from pathlib import Path
from airflow.hooks.base import BaseHook
from astro.databases.base import BaseDatabase
from astro.utils.path import get_class_name, get_dict_with_module_names_to_dot_notations
DEFAULT_CONN_TYPE_TO_MODULE_PATH = get_dict_with_module_names_to_dot_notations(
Path(__file__)
)... | python |
from PySide2 import QtWidgets
import maya.cmds as cmds
class MyWindow(QtWidgets.QDialog):
def __init__(self, parent=None):
super(MyWindow, self).__init__(parent)
lay = QtWidgets.QHBoxLayout(self)
self._line = QtWidgets.QLineEdit('', self)
self._line.setPlaceholde... | python |
# Copyright 2021 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... | python |
"""AVMATH
Avmath is a Python module for mathematical purposes.
It contains functionalities for simple mathematical
usage as sine or logarithm functions and submodules
for more advanced applied math in the topics of ana-
lysis and linear algebra.
The module uses a mathematical syntax. The classes
and functions are nam... | python |
"""
This script deploys all the AWS instances required for a single distributed experiment and runs the docker container
on the instances.
The experiment is one of inner_product / quadratic / kld / dnn.
The user could choose whether to run the coordinator on a strong EC2 instance, or on an ECS Fargate instance.
"""
imp... | python |
from .models import Answer, Landscape
def landscape_boundary(landscape_name):
"""
Return landscape boundary as GeoJSON
:param landscape_name:
:return:
"""
landscape_boundaries = Landscape.objects.raw("""SELECT
id,
... | python |
import random, string
from datetime import datetime
import pytz
import json
import types
from unittest import TestCase
from unittest.mock import patch
from plaw.wrapper import Plaw, InvalidGrant, InvalidToken
class TestPlaw(TestCase):
# helper
def generate_random_token(self, length=16):
return ''.jo... | python |
# encoding: utf-8
# Duke the dog
# Este código va destinado al reconocimiento de un perro por su color de pelaje,
# eliminando todo ruido causado por el ambiente.
# Todo mediante la librería open cv en Python..subl
# Programador Sergio Luis Beleño Díaz
# Enero.2019
'''
Para empezar se importan las librerías de Open... | python |
from chemlib.chemistry import Combustion, Compound, Reaction
from chemlib.utils import reduce_list
# TODO: TEMP IMPLEMENTATIONS, NEED TO CONSIDER ADDITIONAL METHODS/CALCULATIONS
# INTERFACE?
def combustion_analysis(CO2, H2O) -> str:
molesC = Compound("CO2").get_amounts(grams = CO2)["moles"]
molesH = (Compou... | python |
__all__ = [ 'assign','smart_assign','LCA','linkable',
'Assign','SmartAssign','Linkable',
'join_name',
'Component',
'Input','Output','UInt','SInt','IOGroup','Parameter','Wire','Reg',
'And','Or','Greater','Less','GreaterEqual','LessEqual','NotEqual','Equal',
... | python |
import numpy as np
import torch
import torch.nn as nn
from .anchor_head_template import AnchorHeadTemplate
class GradReverse(torch.autograd.Function):
def __init__(self, lambd):
self.lambd = lambd
def forward(self, x):
return x.view_as(x)
def backward(self, grad_output):
return (... | python |
# coding= utf-8
# author= Administrator
# date= 2021/3/15 17:38
from bs4 import BeautifulSoup
# 创建html字符串
html_doc = """
<!DOCTYPE html><!--STATUS OK-->
<html><head><meta http-equiv="Content-Type" content="text/html;charset=utf-8"><meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"><meta content="always... | python |
# Generated by Django 3.0.7 on 2020-06-30 17:03
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('portfolio', '0005_auto_20200630_1658'),
]
operations = [
migrations.AddField(
model_name='collection',
name='spotlig... | python |
from tool.runners.python import SubmissionPy
class DivSubmission(SubmissionPy):
def match(self, x):
s = str(x)
n = len(s)
if n != 6:
return False
# always increasing (or equal)
for i in range(n-1):
if s[i] > s[i+1]:
return False
... | python |
#take file called numbers.txt to start
fileName = "numbers.txt"
def main():
global fileName
fileInput = open(fileName, 'r')
numAry = []
for line in fileInput.readlines():
numAry.append(eval(line))
maxInt = findMax(numAry, 0, len(numAry)-1)
print("The Max Value Is " + str... | python |
#!/usr/bin/python2.7
# coding:utf-8
import logging
from time import sleep
from RPi import GPIO
from cmdtree import INT
from cmdtree import command
from cmdtree import entry
from cmdtree import group
from cmdtree import option
GPIO_CONTROL_PORT = 12
FAN_ON_TEMPERATURE = 55
def get_cpu_temp():
... | python |
from copy import deepcopy
from torch import nn
import numpy as np
import math
import torch
from torch.utils.data import dataset
from torch.utils.data.dataset import Subset
from torch.utils.data import DataLoader
# def compare_models(model: nn.Module, clients: 'list[Client]', num: int):
# def print_params(model... | python |
#!/usr/bin/env python3
# Copyright 2018 Brocade Communications Systems LLC. 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 also obtain a copy of the License at
# http://www.apache.org/licenses/LICENS... | python |
import json
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.core.paginator import Paginator
from django.db import IntegrityError
from django.http import HttpResponse, HttpResponseRedirect, JsonResponse
from django.shortcuts import render... | python |
nome = str(input('Digite seu nome completo: ')).strip()
print('Silva' in nome.title())
| python |
from __future__ import print_function
from optparse import make_option
from datetime import datetime, timedelta
import sys
from textwrap import dedent
from django.core.mail import mail_admins
from django.contrib.auth.models import User
from reversion.models import Revision
from cobl.utilities import LexDBManagementComm... | python |
def load_STNTable(fobj, kwArgCheck = None, debug = False, errors = "strict", indent = 0):
# NOTE: see https://github.com/lw/BluRay/wiki/STNTable
# Import standard modules ...
import struct
# Import sub-functions ...
from .load_StreamAttributes import load_StreamAttributes
from .load_StreamEntr... | python |
import unicodedata
def parse(dict_file):
with open(dict_file, 'r', encoding='utf-8') as r:
for line in r:
for word in line.split("#")[1].split(","):
word = unicodedata.normalize('NFKC', word.strip())
yield word
def parse_lexemes(dict_file):
with open(dict_... | python |
#!/usr/bin/env python
# Copyright (c) 2014, Stanford University
# All rights reserved.
#
# 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, this list ... | python |
import pyperclip
class User:
'''
class for passing all instances of the user
'''
user_list = []
def __init__(self,user_name,account_name,email,password):
'''
initiates properties of my objects
Args:
user_name:New username of the account
'''... | python |
from ecco.attribution import gradient_x_inputs_attribution
import torch
import pytest
@pytest.fixture
def simpleNNModel():
class simpleNNModel(torch.nn.Module):
def __init__(self):
super(simpleNNModel, self).__init__()
self.w = torch.tensor([[10., 10.]])
def forward(self, ... | python |
from sklearn import ensemble
from model_man import get_models
def create():
models = get_models()
v_models = [(key, models[key].create()) for key in models.keys()]
return ensemble.VotingClassifier(
estimators=v_models,
voting="hard"
)
| python |
# -*- coding: utf-8 -*-
"""
A nested dict with both attribute and item access.
NA stands for Nested and Attribute.
"""
import collections
import copy
class NADict:
"""A nested dict with both attribute and item access.
It is intended to be used with keys that are valid Python
identifiers. However, excep... | python |
# -*- coding: utf-8 -*-
# FreeCAD macro for woodworking
# Author: Darek L (aka dprojects)
# Version: 5.0
# Latest version: https://github.com/dprojects/getDimensions
import FreeCAD
# #######################################################
# SETTINGS ( SET HERE )
# ####################################################... | python |
def get_length_of_missing_array(arr):
if len(arr) == 0:
return 0
else:
lens = []
for i in arr:
if i == None or len(i) == 0:
return 0
lens.append(len(i))
lens.sort()
prevInt = 0
for i in lens:
... | python |
"""
Given an array of positive integers nums and a positive integer target, return the minimal length of a contiguous
subarray [numsl, numsl+1, ..., numsr-1, numsr] of which the sum is greater than or equal to target. If there is no
such subarray, return 0 instead.
Example 1:
Input: target = 7, nums = [2,3,1,2,4,3]
Ou... | python |
# -*- coding: utf-8 -*-
# Copyright 2021 Jacob M. Graving <jgraving@gmail.com>
#
# 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 requi... | python |
from typing import Sequence, Hashable
def find_field(d, candidates):
"""
Given a dict and a list of possible keys, find the first key
which is included into this dict. Throws ValueError if not found.
"""
for c in candidates:
if c in d:
return c
raise ValueError(f"Can't find any of: {candidates}")
def find... | python |
from zmodulo.plot.properties.color.color import Color
class LineColor:
""" A Z-Tree plot line color """
def __init__(self, color=None):
"""
Initializes the LineColor object
:param color: line color
:type color: Color
"""
if color is None:
self.color... | python |
from lin import db
from lin.core import File
from lin.exception import NotFound
from pydash import uniq_by
from sqlalchemy import Column, Integer, String
from sqlalchemy.orm import aliased
from app.models.base import Base
class Category(Base):
id = Column(Integer, primary_key=True)
name = Column(String(50), ... | python |
swaps=[]
def heapify(data,n,vert):
min=vert
l=2*vert+1
r=2*vert+2
if l<n and data[l]<data[min]:
min=l
if r<n and data[r]<data[min]:
min=r
if min!=vert:
data[vert],data[min]=data[min],data[vert]
swaps.append([vert,min])
heapify(data,n,min)
def main():
... | python |
from django.contrib import admin
from .models import Report, ReportFiles, ReportIndex
admin.site.register(Report)
admin.site.register(ReportFiles)
admin.site.register(ReportIndex)
| python |
#!/usr/bin/env python
# encoding: utf-8
"""
@author: anly_jun
@file: github_trending
@time: 16/10/17 下午2:23
"""
import requests
from bs4 import BeautifulSoup
GITHUB = 'https://github.com'
TRENDING_URL = GITHUB + "/trending"
TRENDING_DEV_URL = TRENDING_URL + "/developers"
USER_AGENT_BY_MOBILE = 'Mozilla/5.0 (Linux; A... | python |
import requests
from bs4 import BeautifulSoup as bs
import time
import random
import os
import pandas as pd
from pathlib import Path
pwd = os.getcwd()
# Creating /details_page folder
Path(pwd + '/details_pages').mkdir(parents=True, exist_ok=True)
df = pd.read_csv(pwd + '\\dataframes\\Data - IT_Companies_Algiers.csv')... | python |
def make_local_image( embedded_cid , filename, payload):
"""helper func that creates an image object. others may replace this with a specific solution.
the important point is that it returns a link
"""
import models #my models module. you will probably replace this entire function with your own code
... | python |
import json
from mock import patch
import jenkins
from tests.base import JenkinsTestBase
class JenkinsCancelQueueTest(JenkinsTestBase):
@patch.object(jenkins.Jenkins, 'jenkins_open')
def test_simple(self, jenkins_mock):
job_name_to_return = {u'name': 'TestJob'}
jenkins_mock.return_value = js... | python |
from itertools import permutations
l=list(map(int,input().split()))
r=list(permutations(l))
print(r)
| python |
import typing
import datetime
import pandas as pd
from .make_df import ComicDataFrame
from lib.aws_util.s3.upload import upload_to_s3
from lib.aws_util.s3.download import download_from_s3
def store(df: ComicDataFrame) -> typing.NoReturn:
dt = datetime.datetime.now()
bucket = 'av-adam-store'
save_dir = '/tmp/'
... | python |
from .charge import Charge | python |
from telegram.ext import Updater, CommandHandler, ConversationHandler, MessageHandler, Filters, CallbackQueryHandler
from telegram import InlineKeyboardMarkup, InlineKeyboardButton, ChatAction
#Google
import gspread
from oauth2client.service_account import ServiceAccountCredentials
import os
import pandas as pd
INPUT_... | python |
"""
Manages creation of POVMs and geneartion of outcomes from measuring these POVM given a state
Author: Akshay Seshadri
"""
import numpy as np
import scipy as sp
from scipy import stats
import project_root # noqa
from src.utilities.qi_utilities import generate_random_state, generate_POVM, generate_Pauli_ope... | python |
#!/usr/bin/env python3
import logging
import resource
import sys
logging.basicConfig(level=logging.INFO)
import teether.project
if __name__ == '__main__':
if len(sys.argv) < 2:
print('Usage: %s [flags] <code>' % sys.argv[0])
exit(-1)
mem_limit = 4 * 1024 * 1024 * 1024 # 4GB
resource.set... | python |
#!/usr/bin/python3
from PyQt5.QtWidgets import *
class ModulPU(QWidget):
def __init__(self):
super().__init__()
self.layout = QGridLayout()
self.setLayout(self.layout)
#################################################################################################################
############################... | python |
# encoding: utf-8
# Copyright 2011 California Institute of Technology. ALL RIGHTS
# RESERVED. U.S. Government Sponsorship acknowledged.
'''Service Binding: implementation'''
from Acquisition import aq_inner, aq_parent
from ipdasite.services import ProjectMessageFactory as _
from ipdasite.services.config import PROJEC... | python |
from pathlib import Path
from conanRunner import conanRunner
def conanInstall(conanfile, installFolder):
print("\n")
conanfile = str(conanfile)
installFolder = str(installFolder)
args = ["install", conanfile, "--install-folder", installFolder]
for s in conanRunner(args):
print(s)
| python |
# coding: utf-8
"""
Telstra Event Detection API
# Introduction Telstra's Event Detection API provides the ability to subscribe to and receive mobile network events for registered mobile numbers associated with Telstra's mobile network, such as; SIM swap, port-in, port-out, new MSIDN, new mobile service and c... | python |
import unittest
import mock
from factor_graph import FactorGraph, FactorGraphService, Node, Edge
class TestFactorGraph(unittest.TestCase):
pass
class TestFactorGraphService(unittest.TestCase):
## mock FG for failure tests
def test_create_success(self):
factor_graph_service = FactorGraphService()
... | python |
import configparser
import inspect
import logging
import os
import typing
import numpy as np
from ConfigSpace.configuration_space import Configuration
from smac.runhistory.runhistory import RunHistory, RunKey
from cave.utils.exceptions import NotApplicable
def get_timeout(rh, conf, cutoff):
"""Check for timeout... | python |
# encoding: utf-8
from .default import Config
class DevelopmentConfig(Config):
# App config
DEBUG = True
SQLALCHEMY_DATABASE_URI = "sqlite:///../db/dictionary.sqlite3"
| python |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2017 KuraLabs S.R.L
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicabl... | python |
############################################################
# -*- coding: utf-8 -*-
#
# # # # # # #
# ## ## # ## # #
# # # # # # # # # # #
# # ## # ## ## ######
# # # # # # #
#
# Python-based Tool for interaction with the 10micron mounts
# GUI with PyQT5 fo... | python |
import sysconfig
import sys
CFLAGS = "{} -I{} -I{} -fno-omit-frame-pointer".format(
sysconfig.get_config_var("CFLAGS"),
sysconfig.get_path("include"),
sysconfig.get_path("platinclude"),
)
if __name__ == "__main__":
print(f'export CFLAGS="{CFLAGS}"')
| python |
#!/usr/bin/env python3
# This example demonstrates the interaction between different execution modes
import mavlinkinterface # Needed to use the library
from time import sleep # For waiting between commands
# Create interface object, All calls will be made through this
# execMode="queue" means that the "que... | python |
from uuid import uuid4
import pytest
from protean import BaseCommand, BaseEventSourcedAggregate
from protean.exceptions import IncorrectUsageError
from protean.fields import String
from protean.fields.basic import Identifier
class User(BaseEventSourcedAggregate):
id = Identifier(identifier=True)
email = Str... | python |
#!/usr/bin/env python3
# MIT License
#
# Copyright (c) 2020 FABRIC Testbed
#
# 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 ... | python |
import dataclasses
import logging
from dataclasses import dataclass
import tempfile
import os
from typing import Optional
import loaders
import synth
from synth import ( # noqa: F401
grid_dataset,
grid_dataset_path,
dataset_fixtures_dir,
)
import fv3fit
from fv3net.diagnostics.offline import compute
from ... | python |
import gym
from agents.random_agent import RandomAgent
def main(episode_count):
env = gym.make('CartPole-v0')
agent = RandomAgent(env.action_space.n)
for i in range(episode_count):
observation = env.reset() # initialize the environment
done = False
step = 0
while not done:... | python |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... | python |
XXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXX XX XXX XXXXXX XXXX XXXXXX
XXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XX XXXXXXXXXXX XXXX
XXXXXXX XX X XXXXXXXXXXX XXXX XXXXXX XXX XXXXX XXXXXXXXXX XX XXXXXXX XX XXX
XXXXXX XXXXXXXX XX XXXX XX XXX XXXXXXXXX XXXXXX XXX XXXXX
XX XXXXXXXX XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
XXXXXXXXXX XXXXXX
XXXXXXXXX... | python |
"""
zoom.mail
email services
"""
import os
import json
import logging
from smtplib import SMTP
from mimetypes import guess_type
from email import encoders
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email.mime.image import MIMEImage
from email.mime.audio import MIMEAudio
fro... | python |
# SPDX-License-Identifier: MIT
# Copyright (c) 2022 MBition GmbH
from ..globals import logger
from .compumethodbase import CompuMethod
class TabIntpCompuMethod(CompuMethod):
def __init__(self,
internal_type,
physical_type):
super().__init__(internal_type, physical_type... | python |
# -*- coding: utf-8 -*-
from datetime import datetime, timedelta
from hashlib import md5
from flask import Flask, request, redirect, current_app
from time import gmtime
from xmltodict import parse
import requests
import urllib
app = Flask(__name__)
app.config.from_pyfile('config.py', silent=True)
app.config.from_pyf... | python |
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from catboost import Pool
from sklearn.model_selection import StratifiedKFold
from tqdm import tqdm
class CatBoostCustomModel:
def __init__(self, model, model_params={}):
self.result = {}
try:
self.model = model
self.model.set_params(**m... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.