content stringlengths 5 1.05M |
|---|
# Implemente um programa que possa receber do usuário a temperatura em graus Celsius ou Fahrenheit. Antes de receber a temperatura, pergunte ao usuário se ele deseja inserir em Celsius ou em Fahrenheit. Se a entrada for em graus Celsius, o programa deverá retornar a temperatura em Fahrenheit. Se a entrada for em Fahren... |
#!/usr/bin/python
import sys, os, re, string
dotExtRe = re.compile("\.[a-zA-Z]+")
includeRe = re.compile("^#[ \t]*include[ \t]*")
for file in sys.argv[1:]:
inf = open(file)
myIncludes = [ ]
for x in inf.readlines():
m = includeRe.search(x)
if m != None:
x = x[m.regs[0][1]... |
# uncompyle6 version 2.9.10
# Python bytecode 2.7 (62211)
# Decompiled from: Python 3.6.0b2 (default, Oct 11 2016, 05:27:10)
# [GCC 6.2.0 20161005]
# Embedded file name: __init__.py
import dsz
import dsz.cmd
import dsz.data
import dsz.lp
class Plugins(dsz.data.Task):
def __init__(self, cmd=None):
dsz.dat... |
#!/usr/bin/python3
# Copyright (c) 2016-2021 Wind River Systems, Inc.
#
# SPDX-License-Identifier: Apache-2.0
#
import sys
import os
import json
import datetime
import uuid as uuid_gen
import yaml
import collections
import sqlalchemy
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import decl... |
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
class CustomTokenSerializer(TokenObtainPairSerializer):
@classmethod
def get_token(cls, user):
token = super().get_token(user)
token['role'] = user.role.name
return token |
from enums import *
from board import Board
from piece import Piece
def clone_board_state(board):
return [list(x) for x in board.state]
class Move(object):
def __init__(self, board, start_coord, end_coord, attacked = None, attacked_count = 0):
self.white_plays = board.white_plays
self.state = bo... |
#!/usr/bin/env python
import time
import DalekV2DriveV2
import DalekSpi
import RPi.GPIO as GPIO # Import GPIO divers
GPIO.setwarnings(False)
DalekV2DriveV2.init()
DalekSpi.init()
# this gets the spi reading and gets rid of bad readings and
# readings that are out of range due to the motors and acceleration
def... |
import numpy as np
import os
from gensim.models import KeyedVectors
from keras.layers import add, Bidirectional, Concatenate, CuDNNGRU
from keras.layers import Dense, Embedding, Input, SpatialDropout1D
from keras.models import Model
from keras.optimizers import Adam
from keras.regularizers import l2
from src.BiGRU_ex... |
import torch
from ReplayBuffer import ReplayBuffer
from CombinedReplayBuffer import CombinedReplayBuffer
import torch.optim as optim
from ranger import Ranger
DEVICE = 'cuda' if torch.cuda.is_available() else 'cpu'
POLICY_LEARNING_RATE = 3e-4
Q_LEARNING_RATE = 3e-4
ALPHA_LEARNING_RATE = 3e-4
POLICY_OPTIM = optim.Adam... |
import numpy as np
import matplotlib.pyplot as plt
from tqdm import tqdm
from pathlib import Path
def julia_set(c: complex, iterations: int, x_limit: float, y_limit: float, ppl: int = 1000, x_origin: float = 0., y_origin: float = 0.) -> np.ndarray:
threshold = (1 + np.sqrt(1 + 4 * np.abs(c))) / 2
n_x = int(pp... |
#
# Copyright 2016 Dohop hf.
#
# 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, ... |
"""Helper script to generate a pylint badge"""
from pathlib import Path
from pylint.lint import Run
ROOT_DIR = Path(__file__).resolve().parent.parent
DIRECTORY_TO_LINT = (ROOT_DIR / "sam-application").name
# pylint: disable=too-many-return-statements
def get_color(score: float) -> str:
"""Return a colour refere... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Convert the output of CombineSnpCounts.py to gene level counts
============================================================================
AUTHOR: Michael D Dacre, mike.dacre@gmail.com
ORGANIZATION: Stanford University
LICENSE: MIT License, property ... |
# Generated by Django 3.1.7 on 2021-10-19 12:56
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('dm_page', '0086_auto_20211019_1140'),
]
operations = [
migrations.RemoveField(
model_name='organisation',
name='addi... |
# A Wavenet For Speech Denoising - Dario Rethage - 19.05.2017
# Util.py
# Utility functions for dealing with audio signals and training a Denoising Wavenet
import os
import numpy as np
import json
import warnings
import scipy.signal
import scipy.stats
import soundfile as sf
import keras
def l1_l2_loss(y_true, y_pred, ... |
from rdkit import Chem
import os
import os.path as osp
import shutil
from ogb.utils import smiles2graph
from ogb.utils.torch_util import replace_numpy_with_torchtensor
from ogb.utils.url import decide_download, download_url, extract_zip
import pandas as pd
import numpy as np
from tqdm import tqdm
import torch
from torc... |
from .base_path_processor import BasePathProcessor
from .simple_path_processor import SimplePathProcessor
|
#!/usr/bin/python
#
# Copyright (C) 2009 Google Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list ... |
import peewee as pw
from flask import Blueprint
from flask import redirect
from flask import render_template
from flask import request
from flask import url_for
from myfunds.core.models import Account
from myfunds.core.models import Category
from myfunds.core.models import Currency
from myfunds.core.models import Join... |
from tkinter import *
from password_generator import PasswordGenerator
master = Tk()
master.title("Password Generator")
master.resizable(0,0)
password = PasswordGenerator()
password.minlen = 8
password.maxlen = 9
password.minuchars = 2
password.minlchars = 2
password.minnumbers = 2
password.minschars =... |
# Desenvolva uma logica que elia o peso e a altura de uma pessoa, calcule seu IMC e mostre seu status de acordo com a tabela abaixo
# Abaixo de 18.5: Abaixo do peso; Entre 18.5 e 25: Peso ideal; 25 ate 30: Sobrepeso; 30 ate 40: Obesidade; Acima de 40: obesidade morbida
peso = float(input('Qual é o seu peso? (KG)'))
alt... |
"""
Create a multibar file from our labeled file and our tree. We will do this at different taxonomic levels
and different label levels.
For each label level we have, we'll create a single file.
"""
import os
import sys
import argparse
from ete3 import Tree
def read_labels(lf, col, verbose=False):
"""
Read ... |
#!/usr/bin/python3 -OO
# Copyright 2009-2020 The SABnzbd-Team <team@sabnzbd.org>
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any late... |
'''
瞳孔直径数据存储在csv文件当中,现在把它构造成 伪"EEG"格式的mne数据结构中,
方便进行计算,同时能够统一接口,便于后续的数据融合。
'''
import pandas as pd
import numpy as np
import mne
def create_mne_object_from_pupil_diameter(data, sample_rate=60):
data = np.array([data])
# ch_types = ['eye']
ch_types = ['eeg']
ch_names = ['pupil_diameter']
info = mn... |
import numpy as np
from dataclasses import dataclass
from typing import Any
from typing import Optional
from torch.utils import data as torch_data
from lso.data import data as lso_data
@dataclass
class NumpyData(lso_data.Data, torch_data.Dataset):
x: np.array
objective: Optional[np.array] = None
feature... |
# Create lists and import using csv.
import csv
train_sad = []
train_anger = []
train_joy = []
train_trust = []
train_fear = []
train_surprise = []
train_disgust = []
train_anticipation = []
#Open and import the training set emotions.txt
with open("TrainingSetEmotions.txt", "r") as trainingsetemotions:
next(train... |
from __future__ import absolute_import
from __future__ import print_function
import operator
import six
from six.moves import range
class HotCounter(object):
def __init__(self, vs=None, limit=20):
if vs is None:
vs = []
self.limit = limit
self.total = {}
self.updates = ... |
import json
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
with open('data.json', 'r') as jf:
data = json.load(jf)
bulk_list = []
for goal, name in data['goals'].items():
bulk_list.append({'goal': goal, 'name': name})
op.bulk_insert(goals, b... |
# Generated by Django 2.1.1 on 2018-10-05 04:25
from django.db import migrations, models
import uuid
class Migration(migrations.Migration):
dependencies = [
('api', '0022_merge_20181004_0912'),
]
operations = [
migrations.RemoveField(
model_name='accommodation',
... |
import logging
import colorlog
class CustomLogger:
FORMAT = '[%(asctime)s | PID: %(process)d | %(name)s - %(levelname)-8s] %(message)s'
dict_level = {
'debug' : logging.DEBUG,
'info' : logging.INFO,
'warning' : logging.WARNING,
'error' : logging.ERROR,
'criti... |
from jax import random, vmap
from jax.example_libraries.optimizers import adam
import jax.numpy as jnp
import numpy as np
import numpy.typing as npt
import numpyro
import numpyro.distributions as dist
from numpyro.infer import SVI, Trace_ELBO
from numpyro.infer.autoguide import AutoNormal
from scipy.stats import beta, ... |
#!/usr/bin/env python3
# This script starts a `qemu-system` to run the tests and then safely shutdown
# the VM.
#
# Inspired by https://github.com/CTSRD-CHERI/cheribuild/tree/master/test-scripts
import argparse
import os
from run_tests_common import boot_cheribsd, run_tests_main
def run_cheri_examples_tests(qemu: b... |
import os
import pandas as pd
import matplotlib.pyplot as plt
from examples.cartpole_example.cartpole_dynamics import RAD_TO_DEG, DEG_TO_RAD
if __name__ == '__main__':
#df_model = pd.read_csv(os.path.join("data", "pendulum_data_PID.csv"))
#df_nn = pd.read_csv(os.path.join("data", "pendulum_data_PID_NN_model.c... |
"""paicli: A CLI tool for PAI (Platform for AI).
Author: Sotetsu KOYAMADA
"""
from __future__ import unicode_literals
from prompt_toolkit.application import Application
from prompt_toolkit.interface import CommandLineInterface
from prompt_toolkit.key_binding.manager import KeyBindingManager
from prompt_toolkit... |
"""
Computer vision.
"""
from . import mussels
__all__ = [
"mussels",
]
|
import unittest
from intrepyd.iec611312py.parsest import parse_st
from intrepyd.iec611312py.variable import Variable
from intrepyd.iec611312py.stmtprinter import StmtPrinter
from intrepyd.iec611312py.summarizer import Summarizer
from intrepyd.iec611312py.datatype import Primitive
from intrepyd.iec611312py.expression im... |
"""HTTP Navigation Manager."""
from configparser import ConfigParser
from typing import Dict, List
import logging
import random
from OSIx.core.base_module import BaseModule
from OSIx.core.http_manager import HttpNavigationManager
logger = logging.getLogger()
class HttpNavigationManagerHandler(BaseModule):
""... |
#!/usr/bin/env python
import re
import yaml
def camel_to_snake(name):
""" Convert CamelCase names to snake_case """
s1 = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', name)
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', s1).lower()
with open('z.yaml') as yaml_file:
y = yaml.load(yaml_file, Loader=yaml.FullLoa... |
import random
guess_num = random.randint(1, 100)
playing = True
while(playing):
difficulty = input(
"What is your preference for difficulty\nhard or medium or easy\n>")
if(difficulty == "h" or difficulty == "hard" or difficulty == 1):
life = 5
elif(difficulty == "m" or difficulty == "me... |
import configparser
from pymongo import MongoClient
import os
class Properties:
def __init__(self):
pass
def load_properties():
# Read configuration properties
config = configparser.ConfigParser()
base_path = os.path.dirname(os.path.realpath(__file__))
config.read(os.path.join(base_path,... |
import time
import board
from adafruit_pyportal import PyPortal
from adafruit_bitmap_font import bitmap_font
from adafruit_display_text.label import Label
import json
from secrets import secrets
import gc
# Set up where we'll be fetching data from. Presumes a JSON structure of:
# [{"status":"At home",
# "date":"- Mo... |
""" Defines the CloudNoiseModel class and supporting functions """
#***************************************************************************************************
# Copyright 2015, 2019 National Technology & Engineering Solutions of Sandia, LLC (NTESS).
# Under the terms of Contract DE-NA0003525 with NTESS, the U.... |
from .text_detector import *
from .text_recognizer import *
|
from shutil import make_archive, copytree, rmtree, unpack_archive, move
import json
import decimal
import datetime
import uuid
import os
import rdb.models.image as Image
import rdb.models.mlModel as MLModel
import rdb.models.feature as Feature
import rdb.models.featureSet as FeatureSet
import rdb.models.environment as ... |
"""
Visualize the apparent quasar proper motions caused by the acceleration of the solar sytem barycentre
Use the results from Gaia Collaboration, Klioner, et al. (2020) to visualize the apparent proper motions of quasars
caused by the acceleration of the solar system barycentre (also known as 'Galactic aberration'). ... |
"""Provides data structures for encapsulating loss data."""
import numpy
class Loss:
"""Encapsulates training loss data.
.. py:attribute:: label
A string that will be used in graph legends for this loss data.
.. py:attribute:: loss_values
A numpy.ndarray containing the training loss dat... |
# Solution of;
# Project Euler Problem 691: Long substring with many repetitions
# https://projecteuler.net/problem=691
#
# Given a character string $s$, we define $L(k,s)$ to be the length of the
# longest substring of $s$ which appears at least $k$ times in $s$, or $0$ if
# such a substring does not exist. For exa... |
import asyncio
from unittest import mock
import pytest
from distributed.core import ConnectionPool
from distributed.utils_comm import gather_from_workers, pack_data, retry, subs_multiple
from distributed.utils_test import BrokenComm, gen_cluster
def test_pack_data():
data = {"x": 1}
assert pack_data(("x", "... |
from ... pyaz_utils import _call_az
def add(name, ip_address=None, no_wait=None, resource_group=None, subnet=None, vnet_name=None):
'''
Required Parameters:
- name -- Name of the Vault.
Optional Parameters:
- ip_address -- IPv4 address or CIDR range. Can supply a list: --ip-address ip1 [ip2]... |
import numpy as np
import keras
import logging
import sys
import pandas as pd
from data.base import DataObject
from keras.layers import Input
from keras.layers import Conv1D
from keras.layers import GRU
from keras.layers import MaxPooling1D
from keras.models import Model
from keras.layers import Flatten, Dense
from k... |
# Generated by Django 3.2.11 on 2022-01-25 03:16
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
("users", "0082_alter_userprofile_lang"),
]
operations = [
migrations.AddField(
model_name="editor",
name="wp_block_h... |
#!/usr/bin/env python
import os, sys, re
import unicodecsv as csv
index = None
def get_csv_path(repo):
# NOTE: this assumes that everything is stored using a specific naming
# convention: /usr/local/aclu/[repo]/data/data.csv (20180601/dphiffer)
return "/usr/local/aclu/%s/data/data.csv" % repo
def get_index(rep... |
import json
from py42 import settings
from py42._compat import str
from py42.sdk.queries.query_filter import create_eq_filter_group
from py42.services import BaseService
from py42.services.util import get_all_pages
class AlertService(BaseService):
_uri_prefix = u"/svc/api/v1/{0}"
_CREATED_AT = u"CreatedAt"
... |
def basis2(n,uv):
# Shape function values and their derivatives for a given point in the
# in the reference triangle with 3 or 6 nodes
#
# Inputs: n number of nodes in the triangle
# uv coordinates of the pont (size 2x1)
# Outputs: N shape function values (size n x 1)
# ... |
import os
import json
import redis
redis_connection = redis.Redis(decode_responses=True)
if not os.path.isdir('logs_json'):
os.mkdir('logs_json')
for key in redis_connection.scan_iter('*'):
file_name = 'logs_json/' + '_'.join(key.split(':')) + '.json'
print(key)
data = redis_connection.lrange(key, 0,... |
import discord
from cogs.utils.Cache import cache
class RequestView(discord.ui.View):
def __init__(self):
super().__init__(timeout=None)
@discord.ui.button(label="Received", style=discord.ButtonStyle.blurple, emoji='📩')
async def receive_button_callback(self, button, interaction):
... |
"""
Code for sidebar navigation inclusion tags for blog.
:author: Douglas Daly
:date: 1/4/2018
"""
#
# Imports
#
from django import template
from ..models import Post, Category, Tag, Author
#
# Tag Definitions
#
register = template.Library()
@register.inclusion_tag("blog/tags/sidebar_menu.html")
def sidebar_... |
import numpy as np
import matplotlib.pyplot as plt
import cos_doubles
x = np.arange(0, 2 * np.pi, 0.1)
y = np.empty_like(x)
cos_doubles.cos_doubles_func(x, y)
plt.plot(x, y)
plt.show()
|
# TODO: Use batch API instead of sending 1-by-1: https://github.com/Azure-Samples/cognitive-services-speech-sdk/tree/master/samples/batch/python
import azure.cognitiveservices.speech as speechsdk
import os
from tqdm import tqdm
from glob import glob
import time
LANGUAGE = 'en-IN'
SPEECH_CONFIG = speechsdk.SpeechConfig... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0011_element_concept'),
]
operations = [
migrations.AddField(
model_name='element',
name='act... |
from locust import TaskSet, User
from appian_locust.helper import ENV
from .mock_client import CustomLocust
from .mock_reader import read_mock_file
from appian_locust import AppianTaskSet
from appian_locust.uiform import (ComponentNotFoundException,
ChoiceNotFoundException, InvalidComp... |
"""Import-Related Tasks"""
import time
import uuid
from celery import shared_task
from django.conf import settings
from django.core.exceptions import ValidationError
import requests
import unicodecsv
import newrelic.agent
from accounts.utils_user import create_user
from mailer.mailserver import deliver
from user_impo... |
import argparse
import cv2
import numpy as np
import os
import tensorflow as tf
import time
from atom import Element
from atom.messages import LogLevel, Response
from autolab_core import YamlConfig
from keras.backend.tensorflow_backend import set_session
from mrcnn import model as modellib
from sd_maskrcnn.config impor... |
from scraper import *
# Currently just a script to run a few demo cases for anity checking purposes
# TODO: programatically compare results
# Ordinary case
print(get_card_price("tarmogoyf"))
# 'Splinter' is a card with a name that is a substring of another
# this should return the correct card
print(get_card_price(... |
# vim: tabstop=2 shiftwidth=2 softtabstop=2 expandtab autoindent smarttab
from manipulator import *
import random
# sv_swarm
def testInteger():
name = 'int1'
pmin = -10
pmax = 10
# vals = [random.randint(1, 100) for i in range(pmin, pmax+1)]
p = IntegerParameter(name, pmin, pmax)
v = -10
pos = {name:... |
import os
def check_file_exists(full_path):
if not os.path.isfile(full_path):
message = "File NOT found \n"+full_path
raise Exception(message) |
import argparse
import ast
import json
import sys
def normalize(input):
data = []
with open(input) as f:
for line in f:
data.append(json.loads(line))
return data
def in_memory_normalize(input):
# may be OOM killed
r = normalize(args.input)
jr = ast.literal_eval(json.dumps(r, sor... |
import numpy as np
a = intBuffer.data[1] + 0 # plus zero to make a copy or a&b is changed in the for loop
b = intBuffer.data[3] + 0
for i in range(0,intBuffer.data.shape[0]):
intBuffer.data[i] = i*i
|
# Copyright 2022 Shuhei Nitta. All rights reserved.
import os
from pathlib import Path
DATA_DIR = Path(os.environ.get("YA3_REPORT_DATA_DIR", "data"))
DATAFILE_SUFFIX = os.environ.get("YA3_REPORT_DATAFILE_SUFFIX", ".csv.gz")
|
class InvalidQueryException(BaseException):
pass
|
# Generated by Django 2.2.24 on 2021-12-02 09:33
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('home', '0002_customtext_homepage'),
]
operations = [
migrations.CreateModel(
name='Demo',
fields=[
... |
from django.http import HttpResponse, HttpResponseRedirect # noqa: 401
from django.shortcuts import get_object_or_404, render
from django.urls import reverse
from django.views import generic
from collections import Counter
import uuid
from .models import Choice, Question, Product
def home(request):
products = Pro... |
import re
from imbi.endpoints import base
class _RequestHandlerMixin:
ID_KEY = ['id']
FIELDS = ['id', 'project_type_ids', 'name', 'fact_type', 'data_type',
'description', 'ui_options', 'weight']
DEFAULTS = {
'data_type': 'string',
'fact_type': 'free-form',
'weight':... |
# coding=utf-8
# Copyright 2020 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... |
"""
This module provides utilities to write cross-version python code.
"""
import sys
py_version = sys.version_info
if py_version.major == 3:
BASE_STRING_TYPE = str
else:
BASE_STRING_TYPE = basestring
if py_version.major == 3 and py_version.minor >= 5:
from http import HTTPStatus as HTTPStatus
... |
"""
Contains data utils.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from rdkit import Chem
from rdkit.Chem import AllChem
from rdkit.Chem.SaltRemover import SaltRemover
from rdkit.Chem.FilterCatalog import *
import numpy as np
import pandas as... |
st = input('Input number')
try:
num = int(st)
result = num *100
print('%d, %d' % (num, result))
except:
print('Invalid Number')
print('end') |
#!/usr/bin/env python3
import os
from aws_cdk import core
from ds_dashboard.spoke import SpokeStack
app = core.App()
usecase_stack = SpokeStack(
app,
"ds-dashboard-spoke-stack",
)
app.synth()
|
# -*- coding: utf-8 -*-
import unittest
from ...util.byteutil import ByteUtil
# from ...util.hexutil import HexUtil
class ByteUtilTest(unittest.TestCase):
def test_split(self):
# okm = HexUtil.decodeHex('02a9aa6c7dbd64f9d3aa92f92a277bf54609dadf0b00'
# '828acfc61e3c724b84a... |
#-------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
#--------------------------------------------------------------------------
# It is a tool to compare the inference results of the original model and... |
import ccobra
class Matching(ccobra.CCobraModel):
"""
This model returns True if the mood of the prediction matches the mood of the conclusion
for the syllogisms AE1, AE2, EA1, EA2
"""
def __init__(self, name='Matching'):
super(Matching, self).__init__(
name, ['syllogistic'], ['... |
import itertools
from termtable.utils import RamCacheWrapper
_COLOUR_LISTS = {
'basic': [
('00', '000000'),
('01', '800000'),
('02', '008000'),
('03', '808000'),
('04', '000080'),
('05', '800080'),
('06', '008080'),
('07', 'c0c0c0'),
... |
"""
This script determines whether a 450 Hz camera can observe multiple frames
during the partial occulation of a star by the moon.
If the begin and end time of a partial occultation could be measured accurately,
it could be used to determine the radius of the star and hence the radius of
its transiting planets.
"""
i... |
import re
import unittest
from stix_shifter.stix_translation import stix_translation
from stix_shifter_utils.utils.error_response import ErrorCode
translation = stix_translation.StixTranslation()
def _remove_timestamp_from_query_ver1(queries):
pattern = r'\s*AND\s*EventTime\s*BETWEEN\s*\\"\d{4}-\d{2}-\d{2}T\d{2}... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import subprocess
def main():
result = "pass"
try:
ver = subprocess.check_output(["./version.py"])
except OSError:
result = "fail"
ver = 0
except subprocess.CalledProcessError:
result = "fail"
ver = 0
subprocess... |
# Copyright 2021 Huawei Technologies Co., Ltd
#
# 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... |
# Copyright (c) 2019, CRS4
#
# 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, distribu... |
# Generated by Django 3.2.5 on 2021-07-11 15:35
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='book_detail',
fields=[
('id', models.BigAut... |
"""p2 S3 URLs"""
from django.conf import settings
from django.urls import include, path, register_converter
from p2.s3.urls import EverythingConverter, S3BucketConverter
from p2.s3.views import buckets, get, objects
register_converter(S3BucketConverter, 's3')
register_converter(EverythingConverter, 'everything')
app... |
# Copyright (c) initOS GmbH 2019
# Distributed under the MIT License (http://opensource.org/licenses/MIT).
from ..commands import CommandError, parse_commands
from ..config import OCABOT_EXTRA_DOCUMENTATION, OCABOT_USAGE
from ..router import router
from ..tasks.add_pr_comment import add_pr_comment
@router.register("... |
# Note: The profiles/__init__.py bits are not required if you are already referring to your AppConfig in the INSTALLED_APPS settings.
# default_app_config = 'invoices.apps.InvoicesConfig' |
# Copyright (c) 2018 Phil Vachon <phil@security-embedded.com>
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
from .state import TruePositionState
from .uart import TruePositionUART
from .http import TruePositionHTTPApi
from .sat_... |
# Dialog used to select cells for assigning protocols or types
import bisect
from PyQt5.QtCore import pyqtSignal
from PyQt5.QtWidgets import QLabel, QGridLayout, QPushButton, \
QTextEdit, QDialog, QListWidget, QListWidgetItem, QVBoxLayout, \
QHBoxLayout
class SelectCellDialog(QDialog):
'''
Dialog used to select... |
# -*- coding: utf-8 -*-
"""Untitled0.ipynb
Automatically generated by Colaboratory.
Original file is located at
https://colab.research.google.com/drive/1_BEDlHOdtbAEWSvPgI5Lp00ZydRk48QX
"""
# ! git clone
import cv2
import os
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
import numpy as np
imp... |
import math
from miscellanies.torch.distributed import is_dist_available_and_initialized, is_main_process
import torch.distributed
from miscellanies.yaml_ops import load_yaml
import os
from .mixin_utils import apply_mixin_rules
def _update_sweep_config_(config: dict):
wandb_tuner_config = config['tune']
for p... |
"""
This module loads trained models to predict properties of organic molecules
"""
from __future__ import print_function
import os
import pkg_resources
import numpy as np
import pandas as pd
from tensorflow.keras import backend as K
from tensorflow.keras.models import load_model
from rdkit import Chem
from rdkit.Che... |
def crash_add(a, b):
raise RuntimeError("I can't calculate anything :(")
|
# coding=utf-8
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^conta/$', views.index, name='index'),
url(r'^alterar-dados/$', views.alterar_dados_usuario, name='alterar-dados-usuario'),
url(r'^alterar-senha/$', views.update_password, name='update_password'),
url(r'^registr... |
# Time: O(nlogn)
# Space: O(n)
class BIT(object): # 0-indexed
def __init__(self, n):
self.__bit = [0]*(n+1)
def add(self, i, val):
i += 1
while i < len(self.__bit):
self.__bit[i] += val
i += (i & -i)
def query(self, i):
i += 1
ret = 0
... |
#!/usr/bin.env/python
# -*- coding: utf-8 -*-
"""
This module contains the base class KerasCellClassifier for using deep learning methods,
trained on some labeled FileGroup (has existing Populations), to predict single cell classifications.
Copyright 2020 Ross Burton
Permission is hereby granted, free of charge, to a... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.