text stringlengths 1 927k |
|---|
# coding=utf-8
from time import sleep
import readchar
import math
import numpy
import json
import pigpio
from turtle_draw import BrachioGraphTurtle
try:
pigpio.exceptions = False
rpi = pigpio.pi()
rpi.set_PWM_frequency(18, 50)
pigpio.exceptions = True
force_virtual = False
except:
print("pig... |
import os
import unittest
import uuid
import papermill
from tests import datasets, server
EXPERIMENT_ID = str(uuid.uuid4())
OPERATOR_ID = str(uuid.uuid4())
RUN_ID = str(uuid.uuid4())
class TestImputer(unittest.TestCase):
def setUp(self):
# Set environment variables needed to run notebooks
os.e... |
# -*- coding: utf-8 -*-
import pathlib
import os
from datetime import datetime
from dotenv import load_dotenv
load_dotenv()
WORKSPACE_PATH = pathlib.Path(__file__).parent.parent
DATA_FOLDER = os.environ.get("DATA_FOLDER") or "target/data/test_data"
REPORT_FOLDER = os.environ.get("REPORT_FOLDER") or "nginx/data"
NEB... |
"""
Very minimal unittests for parts of the readline module.
"""
from contextlib import ExitStack
from errno import EIO
import locale
import os
import selectors
import subprocess
import sys
import tempfile
import unittest
from test.support import import_module, unlink, temp_dir, TESTFN, verbose
from test.support.script... |
import django.dispatch
#自定义信号(有两个参数arg1, arg2)
mysignal = django.dispatch.Signal(providing_args=["arg1", "arg2"])
#内置的信号是可以自动触发的
#自定义信号不能自动触发 |
from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter
from datetime import datetime
from pathlib import Path
from time import sleep
from urllib.parse import urlencode
from urllib.request import urlopen
# noinspection PyPackageRequirements
from bs4 import BeautifulSoup
from four_letter_blocks.puzzle impor... |
from autoPyTorch.pipeline.base.pipeline import Pipeline
from autoPyTorch.utils.benchmarking.benchmark_pipeline import (BenchmarkSettings,
CreateAutoNet,
FitAutoNet,
... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
# Required library
import matplotlib.pyplot as plt
import networkx as nx
"""
# openfile read input from textfile
# In fact, I test the data on different jupiter notebook and come up with the shortest version
"""
def openfile(filename):
with open(filename, "r") as file_reader:
all_lines = file_reader.read... |
# Copyright (c) 2021, Framras AS-Izmir and contributors
# For license information, please see license.txt
# import frappe
from frappe.model.document import Document
class UBLTRPackages(Document):
pass |
import uuid
import datetime
from typing import Optional
import pydantic
from stopcovid.dialog.models import SCHEMA_VERSION
from stopcovid.dialog.registration import AccountInfo
from stopcovid.drills import drills
class UserProfile(pydantic.BaseModel):
validated: bool
opted_out: bool = False
is_demo: boo... |
from ._gibbs_data import GibbsData
from ._mixture_data import (
create_mixture_component,
MixtureData,
MixtureDataGenerator,
)
from ._timeseries_data import (
TimeSeriesData,
TimeSeriesDataGenerator,
) |
from meerk40t.gui.scene.sceneconst import (
HITCHAIN_DELEGATE_AND_HIT,
RESPONSE_CHAIN,
RESPONSE_CONSUME,
)
from meerk40t.gui.scene.widget import Widget
from meerk40t.svgelements import Matrix, Viewbox
class SceneSpaceWidget(Widget):
"""
SceneSpaceWidget contains two sections:
Interface: Drawn ... |
from flask import Flask
from flask_migrate import Migrate
import psycopg2
import pytest
import pytest_docker
import tenacity
from app.model import db
from app.controller import api
def ensure_schema(dsn: str) -> None:
with open("tests/data/schema.sql") as f:
with psycopg2.connect(dsn=dsn) as conn:
... |
#!/usr/bin/python3
from models.base_model import BaseModel
my_model = BaseModel()
my_model.name = "My_First_Model"
my_model.my_number = 89
print(my_model.id)
print(my_model)
print(type(my_model.created_at))
print("--")
my_model_json = my_model.to_dict()
print(my_model_json)
print("JSON of my_model:")
for key in my_mod... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.6 on 2018-03-18 13:33
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [("api", "0038_auto_20180318_1306")]
operations = [migrations.RemoveField(model_name="check", name="last_pi... |
import os
import re
from flask import json, safe_join
class RuntimeConfig:
'''Runtime configuration helper class
'''
@staticmethod
def config_file_path(service, tenant):
"""Return path to permissions JSON file for a tenant.
:param str servcie: Service name
:param str tenant: ... |
# Copyright 2020 The Cirq Developers
#
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... |
"""
Write a program that request five names separated by commas and create a
list containing those names. Print your answer.
For example: Samir, James, Alison, Tom, Sally
should return ['Samir','James','Alison','Tom','Sally']
"""
names = str(input('Names separated by commas: ')).strip().title()
list_names = names.split... |
import sys
import time
import signal
import serial
ser = serial.Serial()
ser.baudrate = 9600
ser.port = input('Enter the Port\n')
ser.open()
file = open('Arduino_Serial_Data.csv', 'w')
def prog_exit(signal, frame):
print('CONNECTION CLOSED')
file.close()
sys.exit(0)
counter = 0
while True:
inpt = ... |
""" Contains definitions for creation of external C/C++ build rules (for building external libraries
with CMake, configure/make, autotools)
"""
load("@bazel_skylib//lib:collections.bzl", "collections")
load("@rules_foreign_cc//tools/build_defs:version.bzl", "VERSION")
load(
":cc_toolchain_util.bzl",
"Librarie... |
import os
os.environ['CUDA_VISIBLE_DEVICES'] = '2,3'
import tensorflow as tf
import malaya_speech
import malaya_speech.augmentation.waveform as augmentation
import malaya_speech.augmentation.spectrogram as mask_augmentation
import malaya_speech.train.model.medium_jasper as jasper
import malaya_speech.train.model.ctc ... |
import sys
class Super(object):
"""
>>> class A(object):
... def a(self):
... print "A.a()"
>>> class B(A):
... def a(self):
... print "B.a()"
... super.a()
>>> b = B()
>>> b.a()
B.a()
A.a()
>>> class C(B):
... def a(self):... |
import logging
import os
from pathlib import Path
import time
from typing import List, cast
from pixivapi import Client, errors
import yaml
from artist import Artist
from telegrambot import TelegramBot
try:
from yaml import CLoader as Loader
except ImportError:
from yaml import Loader
# Enable logging
loggi... |
"""Factory that loads PCDCP Files."""
from __future__ import absolute_import
import obspy.core
from .. import ChannelConverter
from ..TimeseriesFactory import TimeseriesFactory
from .PCDCPParser import PCDCPParser
from .PCDCPWriter import PCDCPWriter
# pattern for pcdcp file names
PCDCP_FILE_PATTERN = "%(OBS)s%(year... |
from typing import List
class Solution:
def numWays(self, n: int, relation: List[List[int]], k: int) -> int:
self.res = 0
graph = [[[None] for x in range(n)] for x in range(n)]
for i in range(len(relation)):
graph[relation[i][0]][relation[i][1]] = 1
def dfs(start, step... |
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
"""
Common... |
from tuprolog import logger
from tuprolog.solve.flags import DEFAULT_FLAG_STORE, FlagStore
from tuprolog.solve.library import libraries, Libraries
from tuprolog.solve.channel import InputChannel, OutputChannel, std_out, std_in, std_err, warn
from tuprolog.theory import theory, mutable_theory, Theory
from tuprolog.solve... |
'''
DISCLAIMER OF WARRANTIES:
Permission is granted to copy this Tools or Sample code for internal use only, provided that this
permission notice and warranty disclaimer appears in all copies.
THIS TOOLS OR SAMPLE CODE IS LICENSED TO YOU AS-IS.
IBM AND ITS SUPPLIERS AND LICENSORS DISCLAIM ALL WARRANTIES, EITHER EXPRES... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... |
from peewee import *
from .config import mysql
db = MySQLDatabase(mysql['name'], host=mysql['host'], port=int(
mysql['port']), user=mysql['user'], passwd=mysql['passwd'])
class BaseModel(Model):
"""A base model that will use our MySQL database"""
class Meta:
database = db
class PProvider(BaseM... |
"""
Manages and updates the game state every frame and sets up new games
"""
from random import randint
import config
from . import collisionDetector, gameData
import dataModels
from serverLogic import serverData
from serverLogic.logging import logPrint
def startGame():
"""
Starts a new game
"""
game... |
#!/usr/bin/env python
# coding: utf-8
# In[8]:
import pandas as pd
import numpy as np
import os
import sqlite3
pt = os.getcwd()
alarm = pt + "\\C.csv"
def conv_2_list(ls1, ls2, ls3):
ToDf = pd.DataFrame(zip(ls1, ls2, l3))
print(Todf)
l0 = ["0", "1", "2", "3", "4"]
l1 = ["Amar", "Barsha", "Carlos", "... |
"""API Client module for handling requests and responses."""
import requests
import datetime
from .exceptions import (
PygitaException,
ServerConnectionError,
BadRequestError,
UnauthorisedError,
RequestFailedError,
ServerError,
AuthorizationError,
)
from .constants import (
TOKEN_VALIDIT... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... |
import os
from voluptuous import Required
from dvc.exceptions import OutputNotFoundError
from dvc.path_info import PathInfo
from .local import LocalDependency
class RepoDependency(LocalDependency):
PARAM_REPO = "repo"
PARAM_URL = "url"
PARAM_REV = "rev"
PARAM_REV_LOCK = "rev_lock"
REPO_SCHEMA ... |
import argparse
def get_arguments():
parser = argparse.ArgumentParser()
# data args
parser.add_argument(
"--dataset_name", default="SonyAIBORobotSurface1", help="dataset name"
)
parser.add_argument("--path_data", default="data/{}", help="dataset name")
# model args
parser.add_argu... |
from flask_restful import Resource, request
import random
import time
import os
import requests
import json
oil_tank = {
'nome': "oleo",
'volume': random.randint(100, 200)
}
BASE_URL = os.environ['BASE_URL']
class OilTank(Resource):
def __init__(self):
self.oil_url = BASE_URL + '/oleo'
... |
"""
Tests for the server configuration. Run via configtest_dev.py
Tests are standard python unittest tests.
"""
import unittest
import flask
import os
class TestConfig(unittest.TestCase):
"""
This class implements configuration checks for the GA4GH server. It is
structured as a set of unit tests, and re... |
#!c:\users\alexa\myvirtualenv2\foodtasker\scripts\python.exe
from django.core import management
if __name__ == "__main__":
management.execute_from_command_line() |
# 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... |
__all__ = ["PQ", "OPQ", "DistanceTable", "nanopq_to_faiss", "faiss_to_nanopq"]
__version__ = "0.1.9"
from .convert_faiss import faiss_to_nanopq, nanopq_to_faiss
from .opq import OPQ
from .pq import PQ, DistanceTable |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Author: thepoy
# @Email: thepoy@163.com
# @File Name: utils.py
# @Created: 2021-02-09 15:17:32
# @Modified: 2021-06-04 13:25:58
import os
from PIL import Image, ImageDraw, ImageFont, ImageEnhance
from PIL.ImageDraw import ImageDraw as Draw
from typing import List, Tup... |
#
import numpy as np
import pandas as pd
import os
from moviepy.editor import VideoFileClip
#from IPython.display import HTML
from moviepy.video.io.ffmpeg_tools import ffmpeg_extract_subclip
from Parameter import ParametersClass
from LaneDetector import LaneDetector
def main():
paramCls = ParametersClass()... |
from django.db import models
from tinymce.models import HTMLField
from config.settings.base import STATIC_URL
class Componente(models.Model):
nombre = models.CharField(max_length=50)
codigo = models.CharField(max_length=5, verbose_name='Código')
descripcion = HTMLField(blank=True, null=True, verbose_name... |
import io
import re
from setuptools import setup
from setuptools import find_packages
with io.open("README.md", "rt", encoding="utf8") as f:
readme = f.read()
with io.open("src/pyneutralino/__init__.py", "rt", encoding="utf8") as f:
version = re.search(r'__version__ = "(.*?)"', f.read()).group(1)
setup(
... |
import re
from collections import defaultdict
from multiprocessing import Process, Queue, cpu_count
from typing import Any, Dict, Iterable, List, NamedTuple, Set, Iterator
import tensorflow as tf
import numpy as np
from dpu_utils.utils import RichPath
from dpu_utils.codeutils import split_identifier_into_parts, get_la... |
import numbers
from typing import Optional, Sequence
import torch
from torch.nn import functional as F
from torch.nn import init
from torch.nn.parameter import Parameter
from oslo.pytorch.kernel_fusion.cuda import CUDA
def _get_autocast_dtypes() -> Sequence[torch.dtype]:
if torch.cuda.is_bf16_supported():
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Fypp documentation build configuration file, created by
# sphinx-quickstart on Tue Sep 12 17:02:09 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# autog... |
"""Information accessors (a layer on top of data accessors)."""
__author__ = 'thor' |
import argparse
from taskqueue import TaskQueue
import synaptor.cloud.kube.parser as parser
import synaptor.cloud.kube.task_creation as tc
from synaptor import io
def main(configfilename, tagfilename=None):
config = parser.parse(configfilename)
if tagfilename is not None:
bboxes = io.utils.read_bb... |
from arm.logicnode.arm_nodes import *
class ArrayRemoveValueNode(ArmLogicTreeNode):
"""Removes the element from the given array by its value.
@seeNode Array Remove by Index"""
bl_idname = 'LNArrayRemoveValueNode'
bl_label = 'Array Remove by Value'
arm_version = 1
# def __init__(self):
... |
# MIT License
#
# (C) Copyright [2022] Hewlett Packard Enterprise Development LP
#
# 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 righ... |
"""Costs map used by query complexity validator.
It's three levels deep dict of dicts:
- Type
- Fields
- Complexity
To set complexity cost for querying a field "likes" on type "User":
{
"User": {
"likes": {"complexity": 2}
}
}
Querying above field will not increase query complexity by 1.
If field'... |
"""tests the "bind" attribute/argument across schema and SQL,
including the deprecated versions of these arguments"""
from __future__ import with_statement
from sqlalchemy.testing import eq_, assert_raises
from sqlalchemy import engine, exc
from sqlalchemy import MetaData, ThreadLocalMetaData
from sqlalchemy import Int... |
from itertools import product
import pytest
from sklearn import clone
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.linear_model import LinearRegression
from ylearn.estimator_model.meta_learner import SLearner, TLearner, XLearner
from . import _dgp
from ._common import validate_leaner
_test_set... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
CS224N 2019-20: Homework 4
run.py: Run Script for Simple NMT Model
Pencheng Yin <pcyin@cs.cmu.edu>
Sahil Chopra <schopra8@stanford.edu>
Vera Lin <veralin@stanford.edu>
Usage:
run.py train --train-src=<file> --train-tgt=<file> --dev-src=<file> --dev-tgt=<file> --v... |
"""Test functions etc, for Byterun."""
from __future__ import print_function
import vmtest
import six
PY3 = six.PY3
class TestFunctions(vmtest.VmTestCase):
def test_functions(self):
self.assert_ok("""\
def fn(a, b=17, c="Hello", d=[]):
d.append(99)
print(a, b,... |
from setuptools import setup, find_namespace_packages
setup(
name="wot-adapter",
version="0.0.1",
package_dir={"":"src"},
packages=find_namespace_packages(where="src"),
install_requires=[
'Flask>=1.1.1',
'Flask-Cors>=3.0.9',
'pyHS100>=0.3.5',
'PyYAML>=5.3.1',
... |
# coding: utf-8
"""
LUSID API
FINBOURNE Technology # noqa: E501
The version of the OpenAPI document: 0.11.4425
Contact: info@finbourne.com
Generated by: https://openapi-generator.tech
"""
try:
from inspect import getfullargspec
except ImportError:
from inspect import getargspec as getf... |
# Copyright 2015 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... |
#
# CanvasRenderQt.py -- for rendering into a ImageViewQt widget
#
# This is open-source software licensed under a BSD license.
# Please see the file LICENSE.txt for details.
#
import numpy as np
from ginga.qtw.QtHelp import (QtCore, QPen, QPolygon, QColor,
QPainterPath, QImage, QPixmap, ... |
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
from django.shorcurts import render
from django.http import Http404
from models import contato
def index(request):
contatos = Contato.objects.all()
return render(request, 'contatos/index.html', {
'contatos': contatos
})
def ver_contato(request, co... |
#!/usr/bin/env python3
# Tokenizing text and creating sequences for sentences
# courses/udacity_intro_to_tensorflow_for_deep_learning/l09c01_nlp_turn_words_into_tokens.ipynb
# This colab shows you how to tokenize text and create sequences for sentences as
# the first stage of preparing text for use with TensorFlow mo... |
# Copyright 2021 Universität Tübingen, DKFZ and EMBL for the German Human Genome-Phenome Archive (GHGA)
#
# 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
#
# https://www.apache.org/licenses... |
#python3
import scrapy
class BrickSetSpider(scrapy.Spider):
name = "brickset_spider"
start_urls = ['http://brickset.com/sets/year-2016']
def parse(self, response):
SET_SELECTOR = '.set'
for brickset in response.css(SET_SELECTOR):
NAME_SELECTOR = 'h1 a ::text'
PIEC... |
#!/usr/bin/env python3
from __future__ import print_function
import argparse
import datetime
import hashlib
import json
import mmap
import os
import shutil
import subprocess
from struct import Struct
import sys
sys.path.append(
os.path.abspath(os.path.dirname(os.path.abspath(__file__)) + "/../.."))
from zipfile im... |
# Copyright 2014-present PlatformIO <contact@platformio.org>
#
# 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... |
#!/bin/python3
import math
import os
import random
import re
import sys
HOUR = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten',
'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen',
'eighteen', 'nineteen', 'twenty']
NUM = [i for i in range(1, 21)... |
#
# This software is licensed under the Apache 2 license, quoted below.
#
# Copyright 2019 Astraea, 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/LI... |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2019 CESNET.
#
# Invenio OpenID Connect is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Simple test of version import."""
from __future__ import absolute_import, print_function
def test_v... |
import pytest
from tyfbaf import constants
@pytest.fixture
def ugly_hack():
"""Ugly hack to disable autouse fixture in conftest.py..."""
constants.SERVER_NAME = ""
def test_server_name_default(ugly_hack):
assert constants.SERVER_NAME == ""
def test_port_default():
assert constants.PORT == 6405
... |
time = "2021/11/22, 11:09" |
# This code is part of Qiskit.
#
# (C) Copyright IBM 2019, 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivat... |
START_CONV = """
#include <cnpy.h>
#include <vector>
#include <cuda.h>
#include <iostream>
#include <fstream>
#include <stdio.h>
#include <stdlib.h>
#include <cmath>
#include <cublas_v2.h>
#include <time.h>
#include <cuda_profiler_api.h>
#include <cooperative_groups.h>
#include <cudnn.h>
#include <cassert>
#include <... |
from rest_framework import viewsets
from drf_nested_resource.mixins import NestedResourceMixin
from .models import (
TargetModel,
ForeignKeySourceModel,
ManyToManyTargetModel,
ManyToManySourceModel,
GenericForeignKeySourceModel,
)
class NestedForeignKeySourceModelViewSet(NestedResourceMixin, vie... |
import torch
import torch.nn as nn
import numpy as np
__all__ = ['FixupResNet', 'fixup_resnet18', 'fixup_resnet34', 'fixup_resnet50', 'fixup_resnet101', 'fixup_resnet152']
def conv3x3(in_planes, out_planes, stride=1):
"""3x3 convolution with padding"""
return nn.Conv2d(in_planes, out_planes, kernel_size=3, ... |
#!/usr/bin/env python
import setuptools
import novaagent
import sys
requirements = ['netifaces', 'pyxs', 'pycrypto', 'PyYaml', 'distro']
if sys.version_info[:2] < (2, 7):
requirements.append('argparse')
test_requirements = ['mock', 'nose']
if sys.version_info[:2] < (2, 7):
test_requirements.extend(['flake8... |
# Copyright 2019 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
import itertools
import logging
from dataclasses import dataclass
from typing import Iterable
from pants.backend.python.goals import lockfile
from pant... |
# This file was automatically generated by SWIG (http://www.swig.org).
# Version 4.0.2
#
# Do not make changes to this file unless you know what you are doing--modify
# the SWIG interface file instead.
from sys import version_info as _swig_python_version_info
if _swig_python_version_info < (2, 7, 0):
raise Runtime... |
# -*- coding: utf-8 -*-
"""
wsproto/extensions
~~~~~~~~~~~~~~~~~~
WebSocket extensions.
"""
import zlib
from typing import Optional, Tuple, Union
from .frame_protocol import CloseReason, FrameDecoder, FrameProtocol, Opcode, RsvBits
class Extension:
name: str
def enabled(self) -> bool:
return False... |
# LP SOLVER USING LINEAR PROGRAMMING
# the tsp solver function is based on gurobi.github.io/modeling-examples/traveling_salesman/tsp.html
# By Kirill Sechkar
# v0.1.10, 30.5.21
from itertools import combinations,product
# IMPORT GUROBI SOLVER (comment out if not using)
import gurobipy as gp
from gurobipy import GRB
... |
from jsonrpc import ServiceProxy
import sys
import string
# ===== BEGIN USER SETTINGS =====
# if you do not set these you will be prompted for a password for every command
rpcuser = ""
rpcpass = ""
# ====== END USER SETTINGS ======
if rpcpass == "":
access = ServiceProxy("http://127.0.0.1:8732")
else:
access = Ser... |
#!/usr/bin/env python
import os
import glob
import subprocess
passed = []
failed = []
def execTest(testfile):
cmd = "./glslc %s" % testfile
ret = subprocess.call(cmd, shell=True)
if ret:
return False
return True
def stat():
global passed
global failed
n = len(passed) + le... |
import pandas as pd
from tqdm import tqdm
from model.QACGBERT import *
from util.tokenization import *
from torch.utils.data import DataLoader, TensorDataset
import random
import warnings
warnings.filterwarnings('ignore')
context_id_map_fiqa = {'stock': 0,
'corporate': 1,
... |
#
# PySNMP MIB module TRIP-TC-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TRIP-TC-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:20:14 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 0... |
# Copyright 2019 IBM 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 or agreed to in writing, ... |
# Copyright 2013 Google 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 required by applicable law or ... |
# !/usr/bin/env python
# -*- coding: UTF-8 -*-
#
#
# ==================
# VIZ D3 Tree - a d3 dendogram
# ==================
import json
import os
import sys
from ..builder import * # loads and sets up Django
from ..utils import *
from ..viz_factory import VizFactory
class Dataviz(VizFactory):
"""
D3 viz ... |
print('Would you like to play a game?')
answer = input("Enter yes or no: ")
if answer == "yes":
print('wonderful!')
elif answer == "no":
print('too bad!')
else:
print("Please enter yes or no.")
print("I'm thinking of a number between 1 and 100.")
print("Do you think you can guess what it is?")
print("I will... |
import setuptools
with open('README.md', 'r', encoding='utf-8') as fh:
long_description = fh.read()
setuptools.setup(
name='pyxios',
version="1.0.2",
author="Bruno Santos",
author_email="b.g.santos@outlook.com",
long_description=long_description,
long_description_content_type="text/markdow... |
# Required to use
from discord.ext import commands
import discord
class DevOnly(commands.Cog):
def __init__(self, client):
self.client = client
# Commands
@commands.command()
async def shutdown(self, ctx):
if ctx.author.id == 322708417540259841:
myembed = discord.Embed(ti... |
import json
import logging
import requests
from urllib3.exceptions import InsecureRequestWarning
from collections import Counter
def check_links(url):
"""
Check links in a given url.
"""
requests.packages.urllib3.disable_warnings(category=InsecureRequestWarning)
try:
response = requests.g... |
# -*- coding: utf-8 -*-
"""DNA Center Update HTTP write credentials data model.
Copyright (c) 2019 Cisco and/or its affiliates.
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... |
# Copyright 2017 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... |
# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT
from .....testing import assert_equal
from ..brains import BRAINSClipInferior
def test_BRAINSClipInferior_inputs():
input_map = dict(BackgroundFillValue=dict(argstr='--BackgroundFillValue %s',
),
acLowerBound=dict(argstr='--acLowerBound %f',
),
... |
'''
Created on Apr 14, 2013
@author: Vlad
'''
import sys,os
def importFunc(funcName,moduleName,fileName):
'''Imports the function specified and returns it'''
dirName = fileName[0:fileName.rindex(moduleName)].rstrip('/').rstrip('\\')
moduleAbsolutePath = "%s/%s"%(os.getcwd(),dirName)
sys.path.append(mo... |
"""
This module contains a high-level API to SNMP functions.
The arguments and return values of these functions have types which are
internal to ``puresnmp`` (subclasses of :py:class:`x690.Type`).
Alternatively, there is :py:mod:`puresnmp.aio.api.pythonic` which converts
these values into pure Python types. This make... |
r'''
FX is a toolkit for developers to use to transform ``nn.Module``
instances. FX consists of three main components: a **symbolic tracer,**
an **intermediate representation**, and **Python code generation**. A
demonstration of these components in action:
::
import torch
# Simple module for demonstration
... |
import torch
import sys
CONSTANT = 1e-10
class ClusterLoss(torch.nn.Module):
def __init__(self):
super().__init__()
self.mse_fn = torch.nn.MSELoss(reduction='sum')
self.softmax_func = torch.nn.Softmax(dim=0)
# def forward(self, X, H, C, M, T, nM):
# sim_loss = torch.tensor(0.0... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.