content stringlengths 5 1.05M |
|---|
import os
from config.settings import *
# Points to the mock-sso docker container
AUTHBROKER_URL = "http://localhost:8080"
TEST_SSO_PROVIDER_SET_RETURNED_ACCESS_TOKEN = "token"
os.environ["FEEDBACK_GROUP_EMAIL"] = "feedback@email"
|
"""
Production build
"""
import os
from pathlib import Path
import dotenv
from django.core.wsgi import get_wsgi_application
dotenv.read_dotenv(Path(__file__).resolve(
).parent.parent.parent.joinpath('.env'))
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'app.core.settings')
application = get_wsgi_application()
|
from .compat import settings
def get_url(path: str):
return settings.IPAYMU_URL + path
def get_data(json_format=True):
data = {"key": settings.IPAYMU_API_KEY}
if json_format:
data["format"] = "json"
return data
|
# -*- coding:utf-8 -*-
# !/usr/bin/env python
"""
filename: zjj_xa_gov.py
usename: nico
date: 2022/1/15 23:44
MIT License
Copyright (c) 2022 nico
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 ... |
matriz = None
def mochila(numElementos, capacidad, valoresElementos, costosElementos):
for x in range(numElementos):
matriz.append([])
for y in range(capacidad + 1):
matriz[x].append(0)
for i in range(numElementos):
for j in range(capacidad + 1):
if costosElementos[i] <= j:
... |
from typing import Any
class NetworkLocation:
"""
An object used to specify parameters for a Connection.send and Connection.receive functions
This is used to create a specific address / port for a connection and allows automated specification
for a place to send / receive.
A common use is for Mu... |
# SPDX-FileCopyrightText: 2020 Efabless Corporation
#
# 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 o... |
#! ./venv/bin/python
from GitHubAnalysis import GitHubAnalysis
if __name__ == '__main__':
log_flag = True
git_hub_user_name = 'M3N'
git_hub_password = 'GitHub1'
git_hub_analysis = GitHubAnalysis(git_hub_user_name=git_hub_user_name, git_hub_password=git_hub_password,
... |
# Date: September 2017
# Author: Kutay B. Sezginel
"""
Functions to help initialize Lammps simulations
"""
import os
def read_lines(file_name):
""" Read lines from given file and return as list """
with open(file_name, 'r') as fobj:
lines = fobj.readlines()
return lines
def write_lines(file_name... |
__________________________________________________________________________________________________
sample 1424 ms submission
class Solution:
def getMaximumGold(self, grid: List[List[int]]) -> int:
def dfs(x, y, pre, visited):
nonlocal ans
for x2, y2 in [[x - 1, y], [x + 1, y], [x, y ... |
# -*- coding: utf-8 -*-
# Copyright (C) 2004-2020 Mag. Christian Tanzer. All rights reserved
# Glasauergasse 32, A--1130 Wien, Austria. tanzer@swing.co.at
# ****************************************************************************
#
# This module is licensed under the terms of the BSD 3-Clause License
# <http://www.... |
# test_mail.py - Test mail class
#
# This file is part of debexpo
# https://salsa.debian.org/mentors.debian.net-team/debexpo
#
# Copyright © 2019 Baptiste Beauplat <lyknode@cilg.org>
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentat... |
from __future__ import absolute_import
from .myglobals import *
from .pypi_simple_download import *
import re
import tkinter as tk
from collections import deque
from pip._internal.operations.check import (
check_package_set,
create_package_set_from_installed,
)
def package_set_load():
g.package_set, g.... |
# -*- coding: utf-8 -*-
"""
Created on Fri May 18 08:53:30 2018
@author: Johannes Gerstmayr
goal: automatically generate interfaces for structures
currently: automatic generate structures with ostream and initialization
"""
from autoGenerateHelper import RemoveSpacesTabs, CountLines, TypeConversion, GenerateHeader, ... |
#encoding=utf-8
"""
Created on 9:52 2018/11/14
@author: Jindong Wang
"""
# encoding=utf-8
"""
Created on 15:09 2018/11/13
@author: Jindong Wang
"""
import numpy as np
import scipy.io
import scipy.linalg
import sklearn.neighbors
import sklearn.metrics
def kernel(ker, X, X2, gamma):
if not ker o... |
# any and all function
# all as and
# any as or
# True & False = False ---> all()
# True & False = True ---> any()
#example
all([False,False,True])
#False
#example
any([False,False,True])
#True
|
#!/usr/bin/python
import random
import time
import statsd
ctr_name = 'attach.host'
while True:
client = statsd.StatsClient('localhost', 8125)
rand = random.randrange(1, 250)
print('count: (%d)' % rand)
if rand > 0:
client.incr(ctr_name, rand)
time.sleep(1)
|
#! /usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import print_function, unicode_literals, division
import numpy as np
try:
from clint.textui import colored
except ImportError:
def colored(string):
return string
import ctypes
import fluidlab.daq.daqmx as daqmx
from fluidlab.daq.daqmx ... |
import requests
from bs4 import BeautifulSoup
import csv
import os
from dotenv import load_dotenv
load_dotenv()
class Player:
def __init__(self, name, age, birthday, salary, value, weapon, aim, teamplay, handling, playing_iq, quickness, determination, awareness, creativity, patience, calmness, total, leadership, exp... |
import argparse
import time
import gym
import torch
from algorithms.utils.penv import ParallelEnv
import utils
from gym.envs.registration import register
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
register(
id='FourRooms-Dynamic-Obstacles-21x21-v0',
entry_point='custom_env.env.env... |
import magicbot
import wpilib
from magicbot import tunable
from rev import CANSparkMax, MotorType
import navx
from components.drive import Drive
class Robot(magicbot.MagicRobot):
drive: Drive
time = tunable(0)
voltage = tunable(0)
rotation = tunable(0)
def createObjects(self):
# Joysticks... |
types = {
'donor': {'display_name': 'Donors', 'in_header': True},
'sample': {'display_name': 'Samples', 'in_header': True},
'dataset': {'display_name': 'Datasets', 'in_header': True}
}
|
import random, pdb
import numpy as np
from PIL import Image
import torch
from torch import nn
from torch.autograd import Variable
import torchvision.transforms.functional as TF
from cirtorch.datasets.datahelpers import imresize
def center_crop(query_img, carrier_img):
q_i, q_c, q_w, q_h = query_img.size()
c... |
import copy
from Passes import lpla
from Passes import dfg
def alg2lpla( operation, pme, linv, alg, variant ):
# function
inop = [op for op in operation.operands if op.isInput()]
outop = [op for op in operation.operands if op.isOutput()]
f = lpla.function( operation.name, variant, inop, outop )
#... |
import math
class Solution:
"""
@param x: the given number x
@param y: the given number y
@param z: the given number z
@return: whether it is possible to measure exactly z litres using these two jugs
"""
def canMeasureWater(self, x, y, z):
# Write your code here
if x + y < z:... |
"""Simple utility to parse program arguments
"""
import sys
import logging
def parse(argv: sys.argv) -> dict:
"""Parses program options. Read options and associated values, if required. E.g.,
'-s particle-specs.dat', where the option is '-s' and the associated value is
'particle-specs.dat'
"""
#... |
from data_input import RdfParser
from match import ontology_matching
import json
import os
def main():
src_file = '../datasets/101/onto.rdf'
target_dict = {'301':'http://oaei.ontologymatching.org/2007/benchmarks/301/onto.rdf#',
'302':'http://ebiquity.umbc.edu/v2.1/ontology/publication.owl#'... |
import re
from pandas import DataFrame
def _extract_additional_columns(df: DataFrame, hovertool_string: str):
additional_columns = []
if hovertool_string is not None:
if not isinstance(hovertool_string, str):
raise ValueError("<hovertool_string> can only be None or a string.")
# S... |
from dophon.annotation import *
from .BaseController import BaseController
@DefBean
class DefBean(BaseController):
def call_method(self):
return 'this is DefBean'
|
from src.models.predict_model import Predict_label
### Argumentos com o caminho do datasets para predição
SUBMISSION_DATA_PATH = './data/raw/test_data.csv'
SAMPLE_SUBMISSION_PATH = './data/raw/sample_submission.csv'
OUTPUT_PATH = './Submissions/submission.csv'
### Iniciando a Predição
prediction = Predict_label(SUB... |
import numpy as np
from nipy.testing import funcfile, assert_true, assert_equal, assert_raises
from nipy.core.image.image_list import ImageList
from nipy.core.image.image import Image
from nipy.io.api import load_image
def test_image_list():
img = load_image(funcfile)
func_shape = img.shape
imglst = Ima... |
"""
The module to handle bet errors.
"""
class BetException(ValueError):
"""The exception to handle bet errors."""
def __init__(self, previous):
self.previous = previous
ValueError.__init__(self, previous)
|
"""
Setup script.
"""
import setuptools
# package version
VERSION = None
with open('segwrap/__init__.py', encoding='utf-8') as f:
for row in f:
if row.startswith('__version__'):
VERSION = row.strip().split()[-1][1:-1]
break
# package dependencies
with open("requirements.txt", enco... |
#!/usr/bin/env python
#
# Data Generator service
#
__VERSION__ = '0.0.1'
DEFAULT_ROWS_PER_REQUEST=10
MAX_ROWS_PER_REQUEST=10000
import yaml
import json
from flask import Flask
from flask import request
from faker import Factory
class DataRequest(object):
def __init__(self):
self._data = list()
... |
import os
import random
os.environ["KERAS_BACKEND"] = "plaidml.keras.backend"
import numpy as np
from keras.layers import Dense, Flatten, LeakyReLU
from keras.models import Sequential, load_model
from keras.optimizers import Adam
from keras.utils import to_categorical
import logger
from board import Board, ROWS, COL... |
# https://en.wikipedia.org/wiki/De_Bruijn_sequence
# https://en.wikipedia.org/wiki/De_Bruijn_graph
# https://en.wikipedia.org/wiki/Eulerian_path
import random
import numpy as np
import string
import itertools
def generate_subsequences(k, n):
"""List of all possible subsequences of length n with alphabet of size k... |
from absl import logging
import random_utils as prng
import spec
class Mnist(spec.Workload):
def has_reached_goal(self, eval_result: float) -> bool:
return eval_result['accuracy'] > self.target_value
@property
def target_value(self):
return 0.9
@property
def loss_type(self):
return spec.LossT... |
# -*- encoding: utf-8 -*-
from openerp.osv import osv, fields
import base64
import xlwt
import StringIO
import logging
class asistente_ventas_reporte_excel(osv.osv_memory):
_name = 'l10n_gt_extra.asistente_ventas_reporte_excel'
_columns = {
'empresa_id': fields.many2one('res.company', 'Empresa', requi... |
# Core Imports
import os
import re
import sys
from importlib import import_module
# 3rd Party Imports
import click
from click import echo, progressbar
#exposing echo and progressbar as utilities for migrations
echo = echo
progressbar = progressbar
# Local Imports
from .models import Migration, QuerySet
from .local ... |
0b01 <= 255
|
from crispy_forms.helper import FormHelper
from crispy_forms.layout import (
Layout, Fieldset, Div, Submit, HTML
)
from django import forms
from django.utils.translation import ugettext_lazy as _
from mptt.forms import TreeNodeChoiceField
from rakmai import settings as rakmai_settings
from . import settings as boo... |
# Generated by Django 3.0.10 on 2021-03-09 13:54
from django.db import migrations
import wagtail.core.fields
class Migration(migrations.Migration):
dependencies = [
('cms', '0073_bibliography_richtextfield'),
]
operations = [
migrations.AlterField(
model_name='bibliographyen... |
import base64
import pickle
from datetime import timedelta
import datetime
import hmac
from hashlib import sha1
import os
import hashlib
from wtforms import Form
from wtforms.widgets import HiddenInput
from wtforms.csrf.core import CSRF
from wtforms import ValidationError
from multidict import CIMultiDict
from kaira... |
import numpy as np
import pytest
from mlagents.trainers.trajectory import AgentExperience, Trajectory, SplitObservations
VEC_OBS_SIZE = 6
ACTION_SIZE = 4
def make_fake_trajectory(
length: int,
max_step_complete: bool = False,
vec_obs_size: int = VEC_OBS_SIZE,
num_vis_obs: int = 1,
action_space: ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
""" Gotify """
import logging
from urllib.parse import urljoin
import requests
from .core import Notifier
from . import constants
log = logging.getLogger(__package__)
def start(**kwargs):
""" Returns an instance of the GotifyNotifier """
return GotifyNotifier(*... |
import pathlib
import string
from collections import OrderedDict
from dataclasses import dataclass
from typing import Tuple, List, Dict, Union
import strictyaml as sy
from string import Template
# from collections import defaultdict
TOP_LEVEL_NAME = "container"
def anvil_yaml_schema() -> sy.MapPattern:
"""
... |
"""
This file realizes the linear AC state estimation in paper:
'Linear State Estimation and Bad Data Detection for Power Systems with RTU and PMU Measurements'
"""
import numpy as np
from pypower.api import case14, ppoption, runopf
from run_AC_SE import SE
from mea_idx import define_mea_idx_noise
from se_config impor... |
'''
TITULO: Lectura de documentos GFF como csv y escritura csv
FECHA: 050721
AUTOR: Everest
DESCRIPCION: Lee un documento GFF (WIKIPEDIA: En bioinformática, el
formato de características generales es un formato de archivo que
se utiliza para describir genes y otras características de secuencias
... |
from .prediction_api import TeachableHubPredictAPI
from .management_api import TeachableHubAPI
__all__ = (
'TeachableHubPredictAPI',
'TeachableHubAPI',
)
__autodoc_excludes__ = __all__
|
class DataStructureError(ValueError):
"""
Exception signalling that there is something wrong in the data saved to the database
- might be missing data, conflict with existing data, etc.
"""
class SourceFileMissingError(Exception):
"""
Used in re-importing code if is finds that the file to read... |
from datetime import datetime, timedelta
from spidermon import Monitor, MonitorSuite, monitors
from spidermon.contrib.actions.telegram import SendTelegramMessage
from spidermon.contrib.scrapy.monitors import (
ErrorCountMonitor,
FinishReasonMonitor,
ItemValidationMonitor,
)
from sqlalchemy import create_en... |
from math import sqrt
from typing import List
import pytest
from guacamol.common_scoring_functions import IsomerScoringFunction, SMARTSScoringFunction
from guacamol.score_modifier import GaussianModifier
from guacamol.scoring_function import BatchScoringFunction, ArithmeticMeanScoringFunction, GeometricMeanScoringFun... |
#/usr/bin/env python
# -*- coding: Utf8 -*-
import event
class Plugin:
def __init__(self, client):
self.client = client
@event.numeric()
def connect_success(self, e):
if e.values['num'] == '001':
self.client.connected = 1
@event.error()
def reconnect(self, e):
... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import math
class NormedLinear(nn.Module):
def __init__(self, feat_dim, num_classes):
super().__init__()
self.weight = nn.Parameter(torch.Tensor(feat_dim, num_classes))
self.weight.data.uniform_(-1, 1).renorm_(2, 1, 1e-5).m... |
import copy
# @manual=//deeplearning/trt/python:py_tensorrt
import tensorrt as trt
import torch.fx
import torch_tensorrt.fx.tracer.acc_tracer.acc_tracer as acc_tracer
import torchvision.models as models
from torch.ao.quantization.quantize_fx import convert_fx, prepare_fx
from torch.fx.experimental.normalize import No... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# (c) University of St Andrews 2020-2021
# (c) University of Strathclyde 2020-2021
# (c) James Hutton Institute 2020-2021
#
# Author:
# Emma E. M. Hobbs
#
# Contact
# eemh1@st-andrews.ac.uk
#
# Emma E. M. Hobbs,
# Biomolecular Sciences Building,
# University of St Andrews,... |
import contextlib
import os
from testtools import TestCase
from mock import Mock
from troveclient import base
from troveclient import exceptions
"""
Unit tests for base.py
"""
def obj_class(self, res, loaded=True):
return res
class BaseTest(TestCase):
def test_getid(self):
obj = "test"
r... |
import argparse
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
import re, sys
import os, glob
#from plot_from_exps import read_true_pos
inputFile=sys.argv[1]
outName=sys.argv[2]
inputMatrix = np.load(inputFile)
fig, ax = plt.subplots()
im=ax.pcolor(inputMatrix, cmap='RdB... |
from datetime import date
from json import JSONEncoder
from json import dumps as JSONDumps
from django.core import serializers
from django.db.models import Count
from django.http import HttpRequest, HttpResponse, HttpResponseRedirect
from django.http import HttpResponseForbidden, HttpResponseNotFound
from django.urls ... |
"""
WSGI config for keeper project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/howto/deployment/wsgi/
"""
import os
import sys
import site
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(__file_... |
# Fingerprint matching
# Max Granat - mg46424
# Requires OpenCV 3.3.1
import numpy as np
import cv2
import imageProcessing
import minutiae
import os
import time
import sys
import random
import pickle
from sklearn.cluster import KMeans
def match(first, second):
img = cv2.imread(first, 0)
img2 = cv2.imread(second, ... |
import sys
import os
import config
sys.path.insert(0, os.getcwd())
from typing import Any
from pyudemy import Udemy
udemy = Udemy(config.CLIENT_ID, config.CLIENT_SECRET)
def get_courses(content, bot_handler: Any) -> str:
courses = udemy.courses()
print(courses)
res = ""
i = 1
for course in cour... |
import codecs
import os
from PIL import Image
import game
from hacktools import common
def run():
xmlfile = "data/fontdump.xml"
imgfile = "data/fontdump.png"
fontfile = "font.png"
fontconfigfile = "fontconfig.txt"
outfile = "data/fontout.png"
infont = "data/extract_NFP/ETC.NFP/GL_12FNT.NFT"
... |
import gurobipy
import pytest
import gurobi_mock
import os
import glob
import logging
import datetime
from time import sleep
import alib.util as util
@pytest.fixture
def mock_gurobi(monkeypatch):
monkeypatch.setattr(gurobipy, "LinExpr", gurobi_mock.MockLinExpr)
monkeypatch.setattr(gurobipy, "Model", gurobi_... |
import pygame
from game_env.hidenseek_gym.supportive import Point, Collision
from game_env.hidenseek_gym.fixed import Wall
import copy
import random
import json
import math
import numpy as np
import os
class Player(pygame.sprite.Sprite):
"""
Parent Player Class for Hide'n'Seek Game, inherits from pygame.sprit... |
###################################################################################
# THE KALMAN MACHINE LIBRARY #
# Code supported by Marc Lambert #
####################################################################... |
from setuptools import setup
setup(
name='burgeon',
packages=['burgeon'],
include_package_data=True,
install_requires=[
'flask',
'sqlalchemy',
'flask-sqlalchemy',
'bcrypt',
'flask-bcrypt',
'flask-login'
],
) |
# (c) 2017 Gregor Mitscha-Baude
from itertools import product
import numpy as np
import dolfin
from nanopores.tools import fields
def Dt_plane(h, r):
x = r/h
return 1. - 9./16.*x + 1./8.*x**3 - 45./256.*x**4 - 1/16.*x**5
sinh = np.sinh
acosh = np.arccosh
def Dn_plane(l, r, N=100):
alpha = acosh(l/r)
s... |
#!/usr/bin/env python3
import numpy as np
import isce3
def setupOrbit(lat0, lon0, omega, Nvec, ellipsoid):
#Satellite height
hsat = 700000.0
# Setup orbit
orb = isce3.core.orbit()
t0 = isce3.core.dateTime(dt="2017-02-12T01:12:30.0")
orb.refEpoch = t0
clat = np.cos(lat0)
slat = np.sin... |
# Copyright 2013 Dean Gardiner <gardiner91@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 required by applicable law or a... |
from tdw.controller import Controller
from tdw.tdw_utils import TDWUtils
"""
Move the avatar and rotate the camera.
Note that in this example, the `avatar_id` parameters are missing. That's because they all default to "a".
"""
c = Controller()
y = 5.7
c.communicate([TDWUtils.create_empty_room(12, 12),
... |
import json
import os
import uuid
from click.testing import CliRunner
from apigee.apis.commands import delete_revision
test_api_proxy = "hello-world" # change once command to create api proxy has been added
runner = CliRunner()
#def test_delete_api_revision():
# res = runner.invoke(delete_revision, ["-n", test_api... |
#!/usr/bin/env python
from pcss import css, pct, px
css('div.header',
width=pct(10),
height=px(2),
margin=0,
_=[
css('ul > li',
display='inline-block',
padding_left=px(10),
padding_right=px(10))
])
css('div.header a',
color='blue')
OUTPUT = """div... |
from pheasant.core.base import get_render_name, rename_pattern
def test_render_name_function():
def function():
pass
assert get_render_name(function) == "function"
def render_function():
pass
assert get_render_name(function) == "function"
def test_render_name_method():
class R... |
from __future__ import annotations
import asyncio
import os
import typing as tp
from pathlib import Path
from loguru import logger
from .Camera import Camera
from .Employee import Employee
from .Singleton import SingletonMeta
from .Types import AdditionalInfo
from .Unit import Unit
from ._image_generation import cre... |
# coding: utf-8
import subprocess
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from email.mime.text import MIMEText
from email.header import Header
from email.utils import COMMASPACE, formatdate
from backup.utils import LF, SPACER
from enum import IntEnum
class... |
# Copyright 2014 Modelling, Simulation and Design Lab (MSDL) at
# McGill University and the University of Antwerp (http://msdl.cs.mcgill.ca/)
#
# 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... |
import os
from collections import namedtuple
from gitlabci_lint import lint_it, run_check
CUR_DIR = os.path.dirname(os.path.abspath(__file__))
VALID_SAMPLE_GITLABCI = os.path.join(CUR_DIR, "sample_valid_gitlabci.yml")
INVALID_SAMPLE_GITLABCI = os.path.join(CUR_DIR, "sample_invalid_gitlabci.yml")
args_tuple = namedt... |
import os.path
import math
from os import path
import numpy as np
import scipy
import scipy.optimize
allNames =[
"lizard",
"shiftHappens",
"erato",
"cubes",
"sponza",
"daviaRock",
"rungholt",
"breakfast",
"sanMiguel",
"amazonLumberyardInterior",
"amazonLumberyardExterior",
"amazonLumberyardCombinedExteri... |
"""Dataloaders and data processing utilities"""
|
from lib2to3.pytree import convert
from mimetypes import init
import os
from colorama import Fore
from colorama import init
init()
print(Fore.RED + """
$$$$$$ /$$ /$$ /$$ /$$ /$$
| $$_____/|__/| $$ | $$$ /$$$ |__/ ... |
import logging
import sys
from functools import lru_cache
from unittest import TestCase
from foxylib.tools.function.decorator_tool import DecoratorTool
from foxylib.tools.function.function_tool import FunctionTool
from foxylib.tools.log.foxylib_logger import FoxylibLogger
class TestDecoratorTool(TestCase):
@class... |
from ixnetwork_restpy.base import Base
from ixnetwork_restpy.files import Files
class RTCP(Base):
__slots__ = ()
_SDM_NAME = 'realTimeTransportControlProtocol'
_SDM_ATT_MAP = {
'RTCP header': 'realTimeTransportControlProtocol.header.rtcpHeader',
'Sender Report header': 'realTimeTransportCo... |
# Since we're not using twistd, we need to set up logging.
import sys
from twisted.python import log
log.startLogging(sys.stdout)
from twisted.web import resource, server
from twisted.internet import reactor
from minerva.mserver import WebPort, StreamTracker
try:
import simplejson as json
except ImportError:
impor... |
# Copyright © 2019 Province of British Columbia
#
# 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 agr... |
import simplekml
from time import time
from math import floor
kml = simplekml.Kml()
coordList = []
def addPoint(lat, lon):
coordList.append((lat, lon))
def saveKML():
if len(coordList) > 1:
lin = kml.newlinestring(name="RoverTests", description="This test was done on: " + str(time()), coords=coordLis... |
import yaml
from make_session import make, make2
import wandb
def main():
# with open('./config_sweep.yaml') as file:
# config = yaml.safe_load(file)
# with wandb.init(
# project="DrugNet",
# name='test',
# config=config,
# reinit=True
# ):
# session =... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
#!/usr/bin/python
import time
import paho.mqtt.client as mqtt
import json
import time
import sys
import ssl
import RPi.GPIO as GPIO
feeder = 11
GPIO.setmode(GPIO.BOARD)
GPIO.setup(feeder, GPIO.OUT)
cert_path = "/home/pi/Desktop/certs/"
host = "xxxxxxxxxxxxxx-ats.iot.us-east-1.amazonaws.com"
topic = "$aws/things/a... |
import pytest
from lkmltools.linter.rules.fieldrules.description_rule import DescriptionRule
from conftest import get_1st_dimension, get_1st_measure
from lkmltools.lookml_field import LookMLField
def test_run():
raw_lookml = """
view: aview {
dimension: memberID {
type: string
desc... |
'''
MIT License
Copyright (c) 2020 Tauhid Khan
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, merge, publish, d... |
from .c_attack_evasion import CAttackEvasion
from .c_attack_evasion_pgd_ls import CAttackEvasionPGDLS
from .c_attack_evasion_pgd import CAttackEvasionPGD
try:
import cleverhans
except ImportError:
pass # cleverhans is an extra component
else:
from .cleverhans.c_attack_evasion_cleverhans import CAttackEvas... |
'''
Desarrollar un programa que encuentre todos los números primos del 1 a n.
'''
import sys
def is_prime_loop(x):
for i in range(2, x):
if x % i == 0:
return False
return True
def get_primes_filter(n):
return filter(is_prime_loop, range(2, n))
def get_primes_gen_loop(n):
for i i... |
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 26 18:35:28 2021
@author: Dr. Birko-Katarina Ruzicka
"""
import json
with open('StarTrekDialogue.json', 'r') as read_file:
all_series = json.load(read_file)
del(read_file)
tos = all_series['TOS']
tos['tos_000']['BOYCE'].extend(tos['tos_000'].pop... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from gym_minigrid.minigrid import *
from gym_minigrid.register import register
class ThreeRoomsEnvFixed_Vert(MiniGridEnv):
"""
Classic 2 rooms gridworld environment.
Can specify agent and goal position, if not it set at random.
"""
def __init__(self,... |
import c3py # import the python interface to the c3 library
import numpy as np
## Define two functions
def func1(x,param=None):
return np.sum(x,axis=1)
def func2(x,param=None):
return np.sum(x**2,axis=1)
DIM = 2 # number of features
NDATA = 100 # numb... |
""" Random Selection
"""
# Importing the libraries
import matplotlib.pyplot as plt
import pandas as pd
import random
def main():
# Importing the dataset
dataset = pd.read_csv('Ads_CTR_Optimisation.csv')
# Implementing Random Selection
N = 10000
d = 10
ads_selected = []
total_reward = 0
... |
# -*- coding: utf-8 -*-
from django.shortcuts import render
from popbill import PopbillException, ContactInfo, CorpInfo, JoinForm, KakaoService, KakaoReceiver, \
KakaoButton
from config import settings
# config/settings.py 작성한 LinkID, SecretKey를 이용해 KakaoService 객체 생성
kakaoService = KakaoService(settings.LinkID, ... |
# -*- coding: utf-8 -*-
# Copyright 2015 moco_beta
#
# 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 agr... |
# Copyright (C) 2019 Google 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 writi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.