content stringlengths 5 1.05M |
|---|
# RUN: llvmPy -c 'print("Test!")' | FileCheck %s
# RUN: llvmPy %s | FileCheck %s
print("Test!")
# CHECK: Test!
|
import datetime
import decimal
import json
import traceback
class MoreTypesJSONEncoder(json.JSONEncoder):
"""
A JSON encoder that allows for more common Python data types.
In addition to the defaults handled by ``json``, this also supports:
* ``datetime.datetime``
* ``datetime.date``
... |
from django.conf import settings
from django.contrib import messages
from django.contrib.auth import authenticate
from django.contrib.auth import login as force_login
from django.contrib.auth import logout as force_logout
from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_... |
import sys
import time
from client import DroidClient
import courses
from a_star import A_star
import maneuver
# connect to Sphero
droid = DroidClient()
droid.connect_to_R2D2()
# get course, find path
G = courses.grid_1
start = (0,0)
goal = (3,0)
path = A_star(G, start, goal)
# ☑ =start node, ☒ =goal node
# ☐ ══☐ ... |
# -*- coding: utf-8 -*-
import os
import cgi
import time
import hashlib
from cStringIO import StringIO
import httplib as http
import logging
from flask import request, send_file
from modularodm import Q
from framework.flask import redirect
from framework.exceptions import HTTPError
from framework.analytics import ge... |
#!/usr/bin/env python
import logging
import pdb
import time
from datetime import datetime
import paho.mqtt.client as mqtt
import json
import bme680
from mpio import ADC
import os
import gc
import subprocess
RED_PATH = """/sys/class/gpio/pioA25/value"""
GREEN_PATH = """/sys/class/gpio/pioA26/value"""
BLUE_PATH = """/s... |
# -*- coding: utf8 -*-
'''
========================================================================
CygnusCloud
========================================================================
File: networkEventsReactor.py
Version: 5.0
Description: network events... |
# encoding:utf-8
import json
import os
import time
import requests
from pyquery import PyQuery as pq
def parse_few_proxy(url, add_pattern=9):
response = requests.get(url, timeout=5)
html = pq(response.text)("tbody")
table = html.children()
i = 1
list = []
while i < len(table):
ip = st... |
import tensorflow as tf
import numpy as np
import nibabel as nib
import glob
import matplotlib.pyplot as plt
import nibabel as nib
from BSUnet import *
import BSUnetModified
global_path = "../data/Test"
global_weight_path = './weights/BottleNeckBSUnet/final_weights.hdf5'
global_autoencoder_path = './weights/Autoencod... |
from typing import NamedTuple, Optional
Language = NamedTuple('Language', [('name', str), ('iso639_1', Optional[str]),
('iso639_2', Optional[str])])
|
#!/usr/bin/env python3
# Copyright 2019
# Author: Fabio Gutmann <https://github.com/fabio-gut>
import os
import sys
import subprocess
from shutil import rmtree, move
if __name__ == '__main__':
build_dir = os.path.abspath(os.path.join(__file__, os.pardir))
main = os.path.abspath(os.path.join(__file__, os.par... |
#!/usr/bin/python3
####################
# Preliminary steps
####################
### Import necessary packages
import pandas as pd
import logging
logger = logging.getLogger(__name__)
logger.setLevel(level=logging.INFO)
### Set working directory
def run(NGRAM_FILES, K_NGRAMS, TARGETS_FILES, VERBOSE):
FREQ_1G_P... |
from dagster import check
from dagster.utils.indenting_printer import IndentingPrinter
from .config_type import ConfigType, ConfigTypeKind
from .field import resolve_to_config_type
from .iterate_types import config_schema_snapshot_from_config_type
from .snap import ConfigSchemaSnapshot
def _print_type_from_config_ty... |
#coding: utf-8
import subprocess
import re
from slackbot.bot import respond_to
from slackbot.bot import listen_to
from slackbot.bot import default_reply
from slackbot_settings import OJICHAT_PATH, E_LEVEL, P_LEVEL
@default_reply()
def default_func(message):
if message.user["profile"]["display_name"] != '':
... |
#!/usr/bin/env python
"""The setup script."""
from setuptools import setup, find_packages
from os import path
here = path.abspath(path.dirname(__file__))
with open('README.md') as readme_file:
readme = readme_file.read()
with open(path.join(here, 'requirements.txt')) as f:
requirements = f.read().split()
... |
# Faça um algoritmo que leia o preço de um produto e mostre seu novo preço, com 5% de desconto.
print('-' * 100)
print('{: ^100}'.format('EXERCÍCIO 012 - CALCULANDO DESCONTOS'))
print('-' * 100)
produto = float(input('Quanto custa o produto? R$ '))
desconto = produto * 5 / 100
novo_preco = produto - desconto
print(
... |
from model.entry import Entry
from model.normal_file import NormalFile
from model.virus_file import VirusFile
from model.save_file import SaveFile
from model.directory import Directory
|
"""
scrapy middlerwares for both downloader and spider
"""
import logging
import time
from scrapy.downloadermiddlewares.retry import RetryMiddleware
from scrapy.utils.response import response_status_message
from sentry_sdk import capture_message
from ..exceptions import (HttpError, DownloadException)
from .user_agent... |
#! /usr/bin/env python
from setuptools import setup
setup(
name='tmcmarkdown',
packages=['tmcmarkdown', 'tmcmarkdown.extensions', 'tmcmarkdown.tests'],
version='1.0.3',
maintainer="Doug Miller",
maintainer_email="dougmiller@themetacity.com",
url="themetacity.com",
license='LICENCE.md',
... |
'''
This script exemplifies usage of Seaborn Library lmplot.
For more details, see: https://seaborn.pydata.org/
'''
import seaborn as sb
import matplotlib.pyplot as plt
# Seaborn library has some example built-in data sets. You can use sb.get_dataset_names() to list the available data sets.
# Lets use one of them:
# ... |
#
# Copyright (c) 2020 Couchbase, 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... |
"""
__Author__ : Kumar Shubham
__desc__ : file for training an NCC model based on the data which has been genereated
"""
import tensorflow as tf
import json
import os
from collections import Counter
import random
import numpy as np
import pickle
class NCCTrain(object):
def __init__(self,fileName,trai... |
import abc
import click
import six
from cli.config import Config
from cli.internal.commands.command import Command
from cli.internal.utils.io import wait_for_futures
from cli.internal.utils.ui import section
from cli.internal.utils.validation import validate_credentials
@six.add_metaclass(abc.ABCMeta)
class DeployC... |
from readerwriterlock import rwlock
from hipster.min_heap import MinHeap
from hipster.max_heap import MaxHeap
from contradict.hashmap import Hashmap
class SortedDict(Hashmap):
def __init__(self):
super().__init__()
self.min_heap = MinHeap()
self.max_heap = MaxHeap()
lock = rwlock.R... |
from __future__ import with_statement
from __future__ import print_function
from __future__ import absolute_import
import motmot.ufmf.ufmf as ufmf_mod
import sys, os, tempfile, re, contextlib, warnings
from optparse import OptionParser
import flydra_analysis.a2.auto_discover_ufmfs as auto_discover_ufmfs
import flydra_a... |
import cv2
import os
import io
from numpy import vectorize
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics.pairwise import cosine_similarity
from PIL import Image
import pytesseract
pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract.exe"
num... |
import cv2
import skimage.io
import os
import mrcnn.ImgPreprocess as IP
# IMG_DIR = "/home/user/NAS/mingha88/PMJeju/1_kau_1010/191011/Working/"
# OUTPUT_DIR = "/home/user/NAS/mingha88/PMJeju/1_kau_1010/191011/crop_cv2/"
IMG_DIR = "/home/user/Dataset/Jeju/1_kau_1010/annotated/"
# OUTPUT_DIR = "/home/user/Dataset/Jeju/2... |
from django.shortcuts import render
from django.views.generic.base import TemplateView
#from django.shortcuts import HttpResponseRedirect, redirect
#from django.views.decorators.cache import never_cache
#from django.urls import reverse
from django.conf import settings
class IndexTemplateView(TemplateView):
def ge... |
import logging
import secrets
from datetime import datetime
from enum import Enum
from urllib.parse import urlparse
import sqlalchemy as sa
from Cryptodome import Random
from Cryptodome.Cipher import AES
from sqlalchemy.dialects.postgresql import JSONB
from lms.db import BASE
from lms.models.application_settings impo... |
import os
os.system("streamlit run app.py --server.enableCORS false")
|
# importing files
from .PBX_Constants import *
from .PBXResolver import *
from .PBX_Base import *
from .PBXProject import *
from .PBXBuildFile import *
from .PBXBuildRule import *
from .PBX_Base_Reference import *
from .PBXFileReference import *
from .PBXFrameworkReference import *
from .PBXApplicationReference imp... |
import os,sys,inspect
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.insert(0,parentdir)
import pmpy.des as des
import pmpy.dist as dist
import matplotlib as plt
def create_pallets(factory:des.environment,res,damage_pallets_fact... |
"""
For plotting PET forecast data!
"""
import datetime
import matplotlib.dates as mdates
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from pandas.plotting import table
from pathlib import Path
from PIL import Image
from Stations import Stations
import config
import generic_lib
def foreca... |
SESSION_NAME = 'metals'
|
import sys
from dagster_graphql.implementation.context import DagsterGraphQLContext
from dagster_graphql.schema.pipelines import DauphinPipeline, DauphinPipelineSnapshot
from graphql.execution.base import ResolveInfo
from dagster import check
from dagster.core.definitions.pipeline import ExecutionSelector
from dagste... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import csv
import numpy as np
import os
import sys
from observations.util import maybe_download_and_extract
def joint_sports(path):
"""Opinions About Joint Sports
Data from a Dan... |
# A module for windowing and windowed functions useful for convolution, pooling, and other such operations including
# indexing C-style row major arrays in their ravelled flat forms.
# Gary Bhumbra
import numpy as np
from numpy.fft import (rfftn, irfftn)
from scipy.fftpack import (fftn, ifftn)
from numpy.lib.stride_t... |
NEW_LINE = '\n\n\r'
STATUS_RBF = {'PASS': 'Passed', 'FAIL': 'Failed'}
STATUS_AZURE = {'Passed': 2, 'Failed': 11}
URL_PROJECT = 'URL_PROJECT'
PREFIXE_TAG_TEST_ID = 'ID-'
PREFIXE_TAG_TESTPLAN_ID = 'TESTPLAN-'
PREFIXE_TAG_SUITE_ID = 'SUITE-'
PREFIXE_SCREEN_ERROR = 'ID-'
SUFIXE_SCREEN_ERROR = 'FAILURE'
|
from Betsy.bie3 import *
CONTENTS2NUMCLASSES = {
"unspecified" : None, # can be any number of classes
# For 2 class problems.
"class0" : 1,
"class1" : 1,
"class0,class1" : 2,
"class0,class1,test" : 3,
# Not sure that this is needed.
"train0" : 1,
"train1" : 1,
"test" : 1... |
# -*- coding: utf-8 -*-
from sklearn import neighbors
from sklearn import datasets
knn = neighbors.KNeighborsClassifier()
iris = datasets.load_iris()
print iris
knn.fit(iris.data, iris.target)
predictedLabel = knn.predict([[0.1, 0.2, 0.3, 0.4]])
print predictedLabel
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Inspired by https://python-guide-pt-br.readthedocs.io/fr/latest/writing/logging.html#logging-in-a-library
# Set default logging handler to avoid "No handler found" warnings.
import logging
try: # Python 2.7+
from logging import NullHandler
except ImportError:
... |
# Generated by Django 2.0.4 on 2018-04-05 08:59
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('events', '0006_event_joindin_url'),
('blog', '0003_post_is_sponsored'),
]
operations = [
migrations... |
# -*- coding: utf-8 -*-
# vim: sw=4:ts=4:expandtab
"""
riko.modules.itembuilder
~~~~~~~~~~~~~~~~~~~~~~~~
Provides functions for creating a single-item data source
With the Item Builder module, you can create a single-item data source by
assigning values to one or more item attributes. The module lets you assign
a valu... |
#price = float(input('Enter The Price: ')) # int() to convert the inputs into float so we can compare it with tax
#if price >= 2.0:
#tax = 0.07
#else:
# tax = 0.00
#print(f'The Tax for this price is: ', {tax}, '\n \n') # note that the print statements without indentations so it will wait the if and else ... |
l = float(input('Largura (m) '))
alt = float(input('Altura (m) '))
a = l * alt
t = a / 2
print(f'Área é {a}m²')
print(f'São necessários {t}L de tinta') |
import requests
url = ""
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:72.0) Gecko/20100101 Firefox/72.0',
}
login_form_data = {
"username": "",
"password": "",
},
# 代码登录,带着有效的 cookie 来访问
# session类 ,可以用于保存cookie,相当于urllib->cookiejar
session = requests.session()
login_response =... |
from django.shortcuts import render
from django.http import HttpResponse, response
from . import ctrack
def user(request):
rp = ctrack.Track('carloosxdd','BQCBYd9IA9b-YUsJeDtIKL9igyywjMZHgcAID_RXfoTJCuI3BfgAQPDEKz1mx9GmwjfQ_UOWZsz1_c8BIobpjX-PSY37oj_6Dmlq7tBt7C1iCubTVrgAeCMCMkd5qdr5UNOikSvKB1cTbG7Jjxm0XLkczYtIF8u... |
import discord
from discord.ext import commands
class EGBotB(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.command()
async def lista(self, ctx):
await ctx.send("Implementeremo questa funzione nel futuro™")
def setup(bot):
bot.add_cog(EGBotB(bot))
|
import sys
import mlflow
# load model
model = mlflow.pyfunc.load_model(sys.argv[1])
# read file
file_bytes = open(sys.argv[2],'rb').read()
# single input prediction
print("Single input prediction:\n")
print(model.predict(file_bytes))
# to facilitate backwards compatibility
if hasattr(model._model_impl.python_mode... |
# -*- coding: utf-8 -*-
# Copyright 2022 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... |
class SingletonMeta(type):
_instances = {}
def __call__(cls, *args, **kargs):
if cls not in cls._instances:
instance = super().__call__(*args, **kargs)
cls._instances[cls] = instance
return cls._instances[cls]
class GerenciadorConfiguracao(metaclass=SingletonMeta):
... |
from django.db import models
from django.contrib.auth.models import User
from cloudinary.models import CloudinaryField
from django.conf import settings
from django.db.models.deletion import CASCADE
from django.db.models.fields.related import ForeignKey
from django.db.models.signals import post_save
# Create your mode... |
from __future__ import annotations
from typing import TYPE_CHECKING
import effect
from items import Item
import actions.common
if TYPE_CHECKING:
from actions import ActionWithItem
class Potion(Item):
name = "Potion"
char = ord("!")
color = (255, 255, 255)
def __init__(self, my_effect: effect.E... |
import os
IMAGE_DIR = 'faces'
for i in range(2,25):
for root, subdirs, files in os.walk(IMAGE_DIR):
for file in files:
path = root + "/" + file
if path.endswith('.'+ str(i) + '.jpg'):
os.system('rm ' + path)
print('Removed: ' + path)
|
from rest_framework import serializers
from .models import Posts
class PostsSerializer(serializers.ModelSerializer):
photo_id=serializers.CharField(max_length=11)
photo_url=serializers.CharField(max_length=255)
post_caption=serializers.CharField(max_length=5000, allow_blank=True, allow_null=True)
is... |
""" Integration tests for normalize command.
"""
import os
from .test_utils import CliTestCase
from .test_utils import TEST_TOOLS_DIR
class NormalizeTestCase(CliTestCase):
def test_shed_diff(self):
with self._isolate() as f:
fail_order = os.path.join(TEST_TOOLS_DIR, "fail_order.xml")
... |
class Solution:
def maxSubarrayXOR(self, arr, N):
# Initialize Maximum number of bits
bits = 32
front = 0
for i in range(bits-1, -1, -1) :
# Initialize temp variables for storing the position and value of maximum number with the i'th bit set
max_ele = 0
... |
import os
import tempfile
# Deactivate GPUs as pytest seems very error-prone in combination with Tensorflow
os.environ['CUDA_VISIBLE_DEVICES'] = '-1'
import tfne
def sanity_check_algorithm_state(ne_algorithm):
"""
Very basic sanity check as the purpose of the pytest checks is the run of the evolutionary loo... |
import numpy as np
from bmtk.builder.networks import NetworkBuilder
from bmtk.builder.aux.edge_connectors import connect_random
#print np.random.geometric(p=0.5)
#print np.sqrt(1-0.005)/0.005
"""
def connect_random(source, target, nsyn_min=0, nsyn_max=10, distribution=None):
return np.random.randint(nsyn_min, ns... |
# MIT License
#
# Copyright (c) 2019 DARPA
#
# 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, publis... |
"""Processes UserDetailList"""
import json
from cloudsplaining.scan.inline_policy import InlinePolicy
from cloudsplaining.shared.utils import (
is_aws_managed,
get_full_policy_path,
get_policy_name,
get_non_provider_id,
)
from cloudsplaining.shared.exclusions import DEFAULT_EXCLUSIONS, Exclusions
clas... |
# import codecademylib3
import codecademylib3
import numpy as np
from matplotlib import pyplot as plt
# load in data
in_bloom = np.loadtxt(open("in-bloom.csv"), delimiter=",")
flights = np.loadtxt(open("flights.csv"), delimiter=",")
#plt hist()
plt.figure(1)
plt.subplot(211)
plt.hist(flights, range = (0,365),bins = 3... |
'''
Excited States software: qFit 3.0
Contributors: Saulo H. P. de Oliveira, Gydo van Zundert, and Henry van den Bedem.
Contact: vdbedem@stanford.edu
Copyright (C) 2009-2019 Stanford University
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation f... |
from itertools import chain
import numpy as np
import torch
import torch.nn as nn
from torch.distributions import Normal
def init(m, gain=1.0):
if isinstance(m, nn.Conv2d) or isinstance(m, nn.Linear):
nn.init.orthogonal_(m.weight.data, gain)
nn.init.zeros_(m.bias.data)
class DDPGMLP(nn.Module):... |
from django.urls import path
from .views import company_list, company_details, company_licences
urlpatterns = [
path('', company_list),
path('/details/<int:pk>', company_details),
path('/details/<str:company_name>/licences', company_licences),
] |
#
# Copyright (c) 2017-2018 Joy Diamond. All rights reserved.
#
@gem('Pearl.ClassOrder')
def gem():
export(
'CLASS_ORDER__NORMAL_TOKEN', 1, # Normal token
'CLASS_ORDER__PYTHON_START', 10,
'CLASS_ORDER__PYTHON_END', 50,
... |
def import_csv(csv):
import re
csv = csv.replace("\\", "/") # Ensure no errors due to wrong slash
# Opens the CSV for reading
csv = (open(csv, 'r', encoding="utf-8")).readlines()
headers = csv[0].split(",") # Seperates headers by comma into a list
csv.remove(csv[0]) # Deletes headers row fr... |
# 每个节点中next存放后续节点,prev存放前驱节点
class Node(object):
def __init__(self, data, prevp=None, nextp=None):
self.__data = data
self.__prev = prevp
self.__next = nextp
def setData(self, data):
self.__data = data
def setPrev(self, prevp):
self.__prev = prevp
def setNext(... |
# flake8: noqa
from .distributions import *
from .load_scm import load_scm_equations
|
from .correlograms import *
from .genplot_autocorrelogram import * |
import mbuild as mb
from mbuild_ONA.mbuild_ONA import ONA_box
import py3Dmol
import mbuild_ONA
test_box = ONA_box(['AAC','GTAC'],[1,1,2])
test_box.write_lammps('test.lammps')
test_box.create_lammps_input_script(sim_name='test.lammps')
|
import os
import folium
import pickle
import json
import pandas as pd
import branca.colormap as cm
from collections import defaultdict
print(folium.__version__)
#us_states = os.path.join('..\\example\\data', 'us-states.json')
#US_Unemployment_Oct2012 = os.path.join('..\\example\\data', 'US_Unemployment... |
from django.core.management.base import BaseCommand
from ...importers import PermitAreaImporter
class Command(BaseCommand):
help = 'Uses the PermitAreaImporter to create permit areas'
def handle(self, *args, **options):
PermitAreaImporter().import_permit_areas()
|
#!/usr/bin/env python3
import argparse
import os.path
import subprocess
from dsbox.datapreprocessing.profiler import config as profiler_config
parser = argparse.ArgumentParser(description='Generate primitive.json descriptions')
parser.add_argument(
'dirname', action='store', help='Top-level directory to store the... |
from flask import Flask, render_template
# create a flask application name app
app = Flask(__name__)
@app.route("/")
def index():
return render_template('index.html')
if __name__=="__main__":
app.run(debug=True) |
# This file is more like a configuration to setup the websocket urls insted of regular urls.
from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
import public_chat.routing
application = ProtocolTypeRouter({
# Wrapping websocket with authentication.
... |
from django.contrib.postgres.fields import JSONField
from django.db import IntegrityError, models
from lego.apps.feeds.activity import Activity
from lego.apps.feeds.marker import MarkerModelMixin
class FeedBase(models.Model):
"""
FeedBase contains all the base components of a feed
"""
ordering_key =... |
import os
from glob import glob
import cv2
from sklearn.utils import shuffle
from utils.human_parse.handler import Handler as ParseHandler
from utils.general import find_class, append_path
def load_data(train_base, val_base):
cls = find_class(train_base)
train_paths = _find_files(train_base, cls)
val_p... |
import bisect
import sys
import typing
sys.setrecursionlimit(1 << 20)
def main() -> typing.NoReturn:
n = int(input())
a = list(map(int, input().split()))
g = [[] for _ in range(n)]
for _ in range(n - 1):
u, v = map(int, input().split())
u -= 1
v -= 1
g[u... |
from typing import IO, Dict, Type, OrderedDict
from lft.app.data import DefaultDataFactory
from lft.app.epoch import RotateEpoch
from lft.app.vote import DefaultVoteFactory
from lft.app.network import Network
from lft.app.logger import Logger
from lft.consensus.messages.data import Data
from lft.event import EventSyste... |
# Python会用一个叫做PyEval_EvalFramEx(C函数)去执行py函数
# 首先会创建一个栈帧
# Python里面一切都是对象,栈帧对象,上下文中运行字节码对象
def test():
pass
def main():
pass
if __name__ == "__main__":
main()
print("将Python字节代码反汇编:")
import dis
dis.dis(main) |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import sys
import re
import urllib
import urllib2
import requests
import pymongo
import datetime
import multiprocessing as mp
class MongoDBIO:
# 申明相关的属性
def __init__(self, host, port, name, password, database, collection):
self.host = host
self.p... |
from __future__ import absolute_import
import argparse
import collections
import logging
import os
import sys
from .. import io
from .. import bash
LOG = logging.getLogger()
def read_gathered_las(path):
"""Return dict of block->[las_paths].
For now, these are ws separated on each line of input.
"""
r... |
from datastructure import Queue
import sys
class Color:
White = 0
Grey = 1
Black = 2
def bfs(graph, s):
color = [Color] * len(graph.vertices)
d = [int] * len(graph.vertices)
p = [int] * len(graph.vertices)
Q = Queue()
for v in graph.vertices:
color[v.index] = Color.White
d[v.index] = sys.maxint
p[v.ind... |
# Generated by Django 3.1.5 on 2021-02-21 04:04
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('questionnaire', '0006_auto_20210218_1532'),
]
operations = [
migrations.CreateModel(
name='Ques... |
# This code will provide serial communication between a RPi and a Bluefruit Sense without the Arduino IDE
# This code is loaded on the RPi while Bluefruit_USB_RPi.ino is loaded on the Bluefruit
# Software and materials list
# Programming the RPi, 2nd Ed, by Simon Monk http://simonmonk.org/programming-raspberry-pi-... |
import urllib.request
import json
from Cosmos.Storage import Cache
from Cosmos.Security import Encryption
from Cosmos.Exceptions import NotFoundInApiException
class Content:
def __init__(self, cosmos, apiName):
self._cosmos = cosmos
self._apiName = apiName
def __str__(self):
return s... |
from aws_cdk import aws_ec2 as ec2, core
from typing import List
class VpcStack(core.Stack):
def __init__(self, scope: core.Construct, id: str, **kwargs) -> None:
super().__init__(scope, id, **kwargs)
self._instance = ec2.Vpc(
self,
"dataops-vpc",
max_azs=2,
... |
"""
This file calls module command function in src.maggport file
Example:
python -m maggport --host <host> --port <port> --db <db> --collection <collection>
--pipeline_path <pipeline_path> --out <out>
"""
from maggport.maggport import maggport
if __name__ == '__main__':
maggport() # pylint: disable=n... |
from __future__ import division
from __future__ import print_function
import re
import numpy as np
_CODON2LETTER = {
'TAA': '.',
'GCA': 'A', 'GCC': 'A', 'GCG': 'A', 'GCT': 'A',
'RAC': 'B', 'RAT': 'B',
'TGT': 'C', 'TGC': 'C',
'GAT': 'D', 'GAC': 'D',
'GAG': 'E', 'GAA': 'E',
'TTT': 'F', 'TTC'... |
from django.conf.urls import url
from . import views
app_name = "product"
urlpatterns = [
url(r'^create/$', views.create_product, name='create_product'),
url(r'^update/(?P<product_pk>\d+)/$', views.update_product, name='update_product'),
url(r'^details/(?P<pk>\d+)/$', views.product_details, na... |
def zamien(s):
lista = []
for item in slownik.items():
lista.append(item)
return lista
slownik = {"imie": "Magda", "imie": "Andrzej"}
print(zamien(slownik))
|
import itertools
import math
import time
import numpy as np
from .Circuit import Circuit
from .Data_Driven import Data_Driven
def spread_resistor_list(lrs, hrs, nb_states, number):
"""
This function help the create_res_states() function
Parameters
----------
number : int
The number of dis... |
"""This module define two classes: MovableListWidget which subclasses must be used together."""
from aqt.qt import (Qt, QAbstractItemView, QAbstractListModel, QListView, QAction,
QModelIndex)
from .htmldelegate import HtmlDelegate
class MovableListWidget(QListView):
"""View for subclass Movabl... |
from ..route_query_request import RouteQueryRequest
from ...message_types import ROUTE_QUERY_REQUEST
from ...models.paginate import Paginate, PaginateSchema
from unittest import mock, TestCase
class TestRouteQueryRequest(TestCase):
test_limit = 100
test_offset = 10
test_verkey = "3Dn1SJNPaCXcvvJvSbsFWP2x... |
import asyncio
import logging
import logging.handlers
from os.path import join as path_join
from queue import SimpleQueue as Queue
from typing import List
from rogerthat.config.config import Config
from rogerthat.logging.colours import ColouredFormatter
class AsyncioLoggingHandler(logging.handlers.QueueHandler):
... |
'''
Code for Rapid Treatment Planning for Low-dose-rate Prostate Brachytherapy with TP-GAN
Tajwar Abrar Aleef - tajwaraleef@ece.ubc.ca
Robotics and Control Laboratory, University of British Columbia, Vancouver, Canada
'''
import os
from sklearn.metrics import roc_curve, auc
import numpy as np
import matplotlib as mpl
... |
#!/usr/bin/python
"""Script to automatically produce the test_examples.py script which
dynamically updates to test new examples
Do not manually run in a shell where $PWD is not the directory this file is
located in. Ideally just run as part of testall.sh
The tests
"""
import os.path
from os.path import join
test_ex... |
import unittest
import copy
import pickle
from across import Options
class OptionsTest(unittest.TestCase):
def test_construct(self):
options = Options(timeout=77)
self.assertEqual(options.timeout, 77)
def test_copy(self):
options1 = Options(timeout=1)
options2 = options1.copy... |
dba__author__ = 'fabio'
#Função Que Verifica de qual País é o Código
def verifica_pais(codigo):
#Variável Para Retornar Nome Do País
pais = ""
if codigo >= 2 and codigo <= 139:
pais = "EUA"
elif 300 <= codigo <= 379:
pais = "França"
elif codigo == 380:
pais = "Bulgaria"
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.