content stringlengths 5 1.05M |
|---|
from server import app
if __name__ == "__main__":
print('WSGI server running at localhost:4000')
app.run(host='localhost', port=4000)
|
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
import sys
sys.path.append("src/envrd")
import audio
class AudioObject(QObject, audio.SpeechRecognizer):
detected_phrase = pyqtSignal(str)
transcribed_phrase = pyqtSignal(str)
error = pyqtSignal()
def __init... |
import numpy as np
def create_label_map(num_classes=19):
name_label_mapping = {
'unlabeled': 0, 'outlier': 1, 'car': 10, 'bicycle': 11,
'bus': 13, 'motorcycle': 15, 'on-rails': 16, 'truck': 18,
'other-vehicle': 20, 'person': 30, 'bicyclist': 31,
'motorcyclist': 32, 'road': 40, 'par... |
# Generated by Django 2.0.3 on 2018-03-17 18:54
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accounts', '0002_auto_20180314_2252'),
]
operations = [
migrations.AlterField(
model_name='user',
name='image',
... |
#!/usr/bin/env python
# !!!!!!!! density.out is wrong !!!!
# data extraction is correct, but the assignment of each
# data point to x,y,z location is wrong
# avgdens[x][y][z] is correct but x,y,z run backwards
import h5py
import numpy as np
def grabDensity(h5file):
# get density
f = h5py.File(h5file)
for ... |
import os
from netdice.input_parser import InputParser
from netdice.util import project_root_dir
def get_test_input_file(topo_name: str):
return os.path.join(project_root_dir, "tests", "inputs", topo_name)
def get_paper_problem_file():
return get_test_input_file("paper_example.json")
def get_paper_proble... |
from django.contrib import admin
from .models import *
admin.register(Project)
admin.register(ProjectList)
admin.register(ListItem)
admin.register(ItemDetail)
|
import pickle
import numpy as np
import torch
class RLModel:
def __init__(self, observation_def, action_space, train=False, training_comm=(None, None)):
# observation_def -- list (name, tuple (shape, dtype))
self.observation_def = observation_def
self.action_space = action_space
s... |
import sqlite3
#import pwd
myemp=99999
while myemp != 0:
myemp = int(input("Enter Employee Id : "))
if myemp == 0:
break
myfname = input("Enter First Name : ")
mylname = input("Enter Last Name : ")
mydept = input("Enter Department Code : ")
mysal = float(in... |
# coding:utf-8
import os
import logging
import json
import urllib2
url = "http://www.tbs.co.jp/kanran/"
try:
req = urllib2.urlopen(url)
message = ""
#req.encoding = req.apparent_encoding
r = req.read()
for line in r.splitlines():
if line.find("クリスマスの約束") >= 0:
message += line... |
import numpy as np
import torch
from mjrl.utils.tensor_utils import tensorize
from torch.autograd import Variable
class MLP(torch.nn.Module):
def __init__(self, env_spec=None,
hidden_sizes=(64,64),
min_log_std=-3.0,
init_log_std=0.0,
seed=123,
... |
print("Allow the user to enter a series of integers. Sum the integers")
print("Ignore non-numeric input. End input with'.' ")
theSum = 0
while True:
theNum = input("Number:")
if theNum == '.':
break
if not theNum.isdigit():
print("Error,only numbers please")
continue
theSum += ... |
#
# Copyright 2019 BrainPad Inc. All Rights Reserved.
#
# 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, me... |
# [129] 求根到叶子节点数字之和
# https://leetcode-cn.com/problems/sum-root-to-leaf-numbers/description/
# * algorithms
# * Medium (66.16%)
# * Total Accepted: 61.1K
# * Total Submissions: 92K
# * Testcase Example: '[1,2,3]'
# 给定一个二叉树,它的每个结点都存放一个 0-9 的数字,每条从根到叶子节点的路径都代表一个数字。
# 例如,从根到叶子节点路径 1->2->3 代表数字 123。
# 计算从根到叶子节点生成的... |
#
# This file is 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, software
# distr... |
#Faça um programa que leia um número inteiro e diga se ele é ou não um número primo.
num = int(input('Digite um número: '))
total = 0
for c in range(1, num + 1):
if num % c == 0:
total += 1
if total == 2:
print(f'O numero {num} é primo')
else:
print(f'O número {num} não é primo') |
# Import Configuration
from config import config
output_dir = config["OUTPUT"]["DIRECTORY"]
output_db = config["OUTPUT"]["DATABASE"]
crossref_email = config["API"]["CROSSREF_EMAIL"]
# Import Internal
from graph_utils import *
from db_utils import *
# Import External
from graph_tool.all import *
from halo import Halo... |
from conans import tools
import os
from conanfile_base import BaseLib
class xclockConan(BaseLib):
basename = "xclock"
name = basename.lower()
version = "1.0.9"
tags = ("conan", "xclock")
description = '{description}'
exports = ["conanfile_base.py"]
requires = [ 'libx11/1.6.8@bincrafters/sta... |
# -*- coding: utf-8 -*-
#con.execute_non_query(INSERT_EX_SQ.encode('your language encoder'))
#
__doc__='''
使い方:
'''
import os
from os import getenv
import sys
import datetime
import time
import locale
import psycopg2
import csv
from map_matching import map_matching as mm
from map_matching.utils... |
default_app_config = "request_log.apps.RequestLogConfig"
|
import atexit
from threading import Thread
from ..util.ipc import ipc_cleanup, ipc_send, start_ipc_server
from ..util.sdk import Singleton
class KeyboardButtonsListener(metaclass=Singleton):
def __init__(self):
self.buttons = {}
atexit.register(self.__clean_up)
self.listener_thread = Th... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Sep 19 08:41:14 2018
@author: gcu
"""
import networkx as nx
import pickle
import pandas as pd
import numpy as np
import glob
import os
import re
from collections import Counter
#import pylab as plt
import matplotlib.pyplot as plt
data=pd.read_csv("./l... |
# -- encoding: UTF-8 --
from django.forms import TypedChoiceField, CharField
from django.utils.text import capfirst
__all__ = ["formfield"]
# This is a copy of Django 1.8's (78d43a5e1064b63db1c486516c4263ef1c4c975c)
# `Field.formfield()`, for compatibility with Django 1.5.x, which does not
# support `choices_form_cla... |
import os
import streamlit.components.v1 as components
# Create a _RELEASE constant. We'll set this to False while we're developing
# the component, and True when we're ready to package and distribute it.
# (This is, of course, optional - there are innumerable ways to manage your
# release process.)
_RELEASE = True
#... |
import os
import logging
import sys
import shutil
import json
import pkg_resources
import pandas as pd
from Bio import SeqIO
class Controller(object):
def __init__(self, args):
self.fasta = args.input
self.out = args.output
self.threads = args.threads
self.dist = args.dis... |
"""
Plot training/validation curves for multiple models.
"""
from __future__ import division
from __future__ import print_function
import argparse
import matplotlib
import numpy as np
import os
matplotlib.use('Agg') # This must be called before importing pyplot
import matplotlib.pyplot as plt
COLORS_RGB = [
(2... |
from .testmapgen import TestMapGen
from .testwalk import TestWalk
|
"""
Module for generation of plots.
"""
# Import Python standard libraries
import statistics
# Import 3rd-party libraries
from matplotlib import pyplot as plt
import numpy as np
import math
def graph_word_distribution_entropies(entropies1, entropies2, output_path, **kwargs):
title = kwargs.get("title", "")
... |
"""
Copyright (c) 2018-2019 ARM Limited. All rights reserved.
SPDX-License-Identifier: Apache-2.0
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... |
from rest_framework import serializers
from users.models import User
from django.contrib.auth.models import Group
from django.contrib.auth.hashers import make_password
class AdminSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = [
'id',
'username',
... |
#Votemain module
"""
Votelib module by Blake Cretney
This work is distributed AS IS. It is up to you to
determine if it is useful and safe. In particular,
NO WARRANTY is expressed or implied.
I permanently give everyone the rights to use, modify,
copy, distribute, re-distribute, and perform this work,
and all ... |
from flask import json
from werkzeug.exceptions import HTTPException
def register_error_handler(flask_app):
flask_app.register_error_handler(HTTPException, __handle_exception)
def __handle_exception(e):
"""Return JSON instead of HTML for HTTP errors."""
# start with the correct headers and status code f... |
import gzip, shutil
def decompress(n):
with gzip.open(n, 'r') as f_in, open('farm_0.uc', 'wb') as f_out:
shutil.copyfileobj(f_in, f_out)
def compress(n):
with open(n, 'rb') as f_in:
with gzip.open('Events.json', 'wb') as f_out:
shutil.copyfileobj(f_in, f_out)
decompress('farm_0.d... |
__version_tuple__ = (2, 6, 0, "dev")
__version__ = '2.6.0-dev'
|
# -*- coding: utf-8 -*-
import unittest
from datetime import date
from skyscraper.utils.constants import POWER_KEY, TRUNK_KEY, MASS_KEY, PRICE_KEY, AGE_KEY, CURRENCY_KEY
from skyscraper.utils.constants import SPEEDOMETER_KEY, CAR_KEY, CONDITION_KEY
from skyscraper.utils.value_parser import ValueParser
class TestBas... |
import pytest
import requests
from schema_registry.client import SchemaRegistryClient, schema
from tests import data_gen
def test_context(client):
with client as c:
parsed = schema.AvroSchema(data_gen.BASIC_SCHEMA)
schema_id = c.register("test-basic-schema", parsed)
assert schema_id > 0
... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'vars.ui'
#
# Created by: PyQt5 UI code generator 5.10.1
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.... |
class ProgressTracker:
def __init__(self):
self.set_skipped_paths([])
def skip_file(self, file_path: str):
return not all([file_path.startswith(path) for path in self._skipped])
def set_skipped_paths(self, skipped_paths):
self._skipped = skipped_paths
|
#!/usr/bin/env python
import zmq
import sys
import time
import pickle
# Socket to talk to server
context = zmq.Context()
sub = context.socket(zmq.SUB)
sub.setsockopt(zmq.RCVHWM, 2) # This line added.
sub.setsockopt(zmq.SUBSCRIBE, b'')
# sub.setsockopt(zmq.CONFLATE, True)
USE_ICP = False
if USE_ICP:
sub.connect... |
# -*- coding: utf-8 -*-
# Copyright (c) 2016 Mirantis 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 ... |
# -*- coding: utf-8 -*-
from collections import defaultdict
import commonware.log
from amo.utils import find_language
import mkt
log = commonware.log.getLogger('z.webapps')
def get_locale_properties(manifest, property, default_locale=None):
locale_dict = {}
for locale in manifest.get('locales', {}):
... |
# Generated by Django 3.1.3 on 2020-11-28 11:20
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('api', '0016_messages_author_id'),
]
operations = [
migrations.AddField(
model_name='request',
name='likes',
... |
# -*- coding: utf-8 -*-
"""
Public API: Version 1
"""
|
# -*- coding: utf-8 -*-
from django.core.urlresolvers import reverse, resolve
from django.conf.urls import url
from test_plus.test import TestCase
from ...users.tests.factories import UserFactory
from .factories import ReviewFactory
class TestReviewURLs(TestCase):
def setUp(self):
self.user = UserFactor... |
from .landmark import landmark_mesh, get_landmark_points, LANDMARK_MASK
from .visualize import visualize_nicp_result
from .correspond import correspond_mesh, build_correspondence_matrix
from .data.basel import load_basel_template_metadata
from .data import prepare_mesh_as_template, load_template
from ._version import g... |
__copyright__ = "Copyright (C) 2013 Andreas Kloeckner"
__license__ = """
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, ... |
from django.conf.urls import url
from rest_framework_jwt.views import obtain_jwt_token, refresh_jwt_token
from accounts import views
urlpatterns = [
url(r'^auth/register/$',
views.RegistrationView.as_view(), name='user-registration'),
url(r'^auth/activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Z... |
# Copyright 2017-present Adtran, 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 writ... |
'''OpenGL extension ARB.debug_label
This module customises the behaviour of the
OpenGL.raw.GL.ARB.debug_label to provide a more
Python-friendly API
Overview (from the spec)
This extension defines a mechanism for OpenGL applications to label their
objects (textures, buffers, shaders, etc.) with a descriptive st... |
from typing import Dict, List, Tuple, Union
from web3.main import Web3
from ..utils.utils import calculate_lp_token_price, open_contract, blockchain_urls, get_token_price_from_dexs, symbol_mapping, decimals_mapping
from ..masterchef_apr_fetcher import MasterchefAPRFetcher
from pprint import pprint
class TraderjoeAPRF... |
#!/usr/bin/env python3
# =============================================================================
# Created On : MAC OSX High Sierra 10.13.6 (17G65)
# Created On : Python 3.7.0
# Created By : Jeromie Kirchoff
# Created Date: Mon May 14 21:46:03 PDT 2018
# ========================================================... |
#!/usr/bin/env python2
import socket
import threading
import time
import SocketServer
import random
HOST = "0.0.0.0"
PORT = 11071
WELCOME_MSG = "Hi, I like math and cryptography. Can you talk to me?!\n"
ERROR_MSG = "Ooops, something went wrong here. Please check your input!\n"
CORRECT_MSG = "Yay, that's right!\n"
WRO... |
"""Serveradmin
Copyright (c) 2019 InnoGames GmbH
"""
from django.conf import settings
def base(request):
return {'MENU_TEMPLATES': settings.MENU_TEMPLATES}
|
from ..utils import Object
class MessagePassportDataReceived(Object):
"""
Telegram Passport data has been received; for bots only
Attributes:
ID (:obj:`str`): ``MessagePassportDataReceived``
Args:
elements (List of :class:`telegram.api.types.encryptedPassportElement`):
... |
from collections import namedtuple
from base58 import b58decode
from sovtokenfees.serializers import txn_root_serializer
def test_utxo_batch_handler_commit_batch(utxo_batch_handler, utxo_cache):
utxo_cache.set('1', '2')
ThreePcBatch = namedtuple("ThreePcBatch", "state_root valid_digests txn_root")
three_p... |
r"""
Support for monitoring loss in Megatron
"""
import torch
from fmoe.balance import reset_balance_profile
from fmoe.balance import update_balance_profile
from fmoe.utils import get_torch_default_comm
balance_dict = {}
num_layers = 0
def reset_gate_hook(_num_layers=None):
from megatron import get_args
gl... |
from pytest import fixture
from typing import List
from moodle import Moodle
from moodle.core.course import Course
@fixture
def domain() -> str:
return "https://school.moodledemo.net"
@fixture
def moodle(domain: str) -> Moodle:
username = "manager"
password = "moodle"
return Moodle.login(domain, us... |
# import pytest
from yaost.base import Node
def test_serialization():
n = Node('x', None, int_value=1)
assert 'x(int_value=1);' == n.to_string()
n = Node('x', None, bool_value=True)
assert 'x(bool_value=true);' == n.to_string()
n = Node('x', None, str_value='abc')
assert 'x(str_value="abc")... |
x = int(input())
a = int(input())
b = int(input())
x -= a
print(x % b)
|
# Licensed under the Upwork's API Terms of Use;
# you may not use this file except in compliance with the Terms.
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or i... |
#!/usr/bin/python3
import sys
import operator
set = {}
result = {}
for a in sys.stdin:
bbw,ball = a.split(';')
batsmanbolwer,wicket = bbw.split('$')
if batsmanbolwer not in set:
set[batsmanbolwer] = [int(wicket),int(ball)]
else:
set[batsmanbolwer][0]=set[batsmanbolwer][0]+wicket
set[batsmanbolw... |
import pytest
from os.path import join
def test_confgen_tree_build(confgen_single_service):
'''
Based on:
hierarchy:
- GLOBAL
- STAGE
- CLUSTER
infra:
prod: # stage
- main # cluster
- multiapp # cluster
- staging # cluster
dev: # stage
- qa1 # clu... |
#!/usr/bin/env python3
import sys, csv, os
try:
isoforms = open(sys.argv[1])
isbed = sys.argv[1][-3:].lower() != 'psl'
alignment = open(sys.argv[2])
minsupport = int(sys.argv[3])
outfilename = sys.argv[4]
if len(sys.argv) > 5:
outfilename2 = sys.argv[5]
else:
outfilename2 = ''
calculate_all = len(sys.argv)... |
from library import keyword_map
key_map = keyword_map.Keyword_map()
non_k_map = ["{", "}", "(", ")"]
def code_parser(code):
k_map = key_map.getMaps()
for rpl in non_k_map:
code = code.replace(rpl, " " + rpl + " ")
pass
for rpl in k_map:
code = code.replace(rpl + " ", rpl + " ")
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import pytest
from eve import ISSUES, STATUS
from eve.tests.methods import post as eve_post_tests
from eve_sqlalchemy.tests import TestBase, test_sql_tables
class TestPost(eve_post_tests.TestPost, TestBase):
@pytest.mark.xfail(True, run=False, rea... |
import numpy as np
import torch
N_CLASSES = 150
def mask_to_subgrids(mask, cell_scale):
"""
break WxH annotation array into a cell_scale x cell_scale vectors
"""
num_elem_row, num_elem_col = int(mask.shape[0] / cell_scale), int(mask.shape[1] / cell_scale)
res = []
for h in range(cell_scale):
... |
from tensorflow import keras
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM, Dropout, Dense, Concatenate, GlobalAveragePooling1D
from tensorflow.keras import Input, Model
from tcn import TCN
from keras.callbacks import EarlyStopping
import tensorflow as tf
import numpy as np
imp... |
# -*- coding: utf-8; -*-
import os
import sys
import shlex
import subprocess
from operator import attrgetter
from optparse import IndentedHelpFormatter
try:
from itertools import izip_longest as zip_longest
except ImportError:
from itertools import zip_longest
class CompactHelpFormatter(IndentedHelpFormatt... |
import crypto_key_gen
import hashlib
sk = crypto_key_gen.generate_key()
pk = crypto_key_gen.get_public_key(sk)
crypto_key_gen.save_key(sk, "./wallet/secret.pem")
crypto_key_gen.save_key(pk, "./wallet/public.pem")
|
# USAGE
# python webstreaming.py --ip 0.0.0.0 --port 8000
# import the necessary packages
from imutils.video import VideoStream
from flask import Response
from flask import Flask
from flask import render_template
from tensorflow.keras.models import load_model
import resizer as re
import threading
import argparse
impor... |
import re
# input_lines = '''\
# swap position 4 with position 0
# swap letter d with letter b
# reverse positions 0 through 4
# rotate left 1 step
# move position 1 to position 4
# move position 3 to position 0
# rotate based on position of letter b
# rotate based on position of letter d
# '''.splitlines()
input_lin... |
import paddle
import numpy as np
from matplotlib import pyplot as plt
from paddle.fluid.dataloader import batch_sampler
from paddle.fluid.dataloader.batch_sampler import BatchSampler
import paddle.nn.functional as F
from paddle.nn import Linear
from paddle.io import Dataset
import math
# Define
num_sampl... |
import warnings
from .._data import conform_dataset, normalize_likelihood
from .._display import session_block
class VarDec(object):
"""
Variance decompositon through GLMMs.
Example
-------
.. doctest::
>>> from limix.vardec import VarDec
>>> from limix.stats import multivariat... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import math
import scipy.sparse as sp
from torch.nn.parameter import Parameter
from torch.nn.modules.module import Module
from modules import *
# GCN model
class GraphConvolution(Module):
"""
Simple GCN layer, similar to https://arxiv.org/abs/... |
import json
from src.services.property_service import PropertyService
class PropertyController:
property_service = PropertyService()
def properties(self, status: str, year: int, city: str) -> object:
properties = self.property_service.get_properties(status, year, city)
return json.dumps(pro... |
import numpy as np
import pytest
from compimg.similarity import MSE, RMSE, MAE, PSNR, SSIM, GSSIM
from compimg.exceptions import DifferentDTypesError, DifferentShapesError
@pytest.fixture
def reference_image():
return np.array([[1, 2, 3], [4, 5, 6]], dtype=np.uint8)
@pytest.fixture
def image():
return np.a... |
from enum import Enum
import sys
class ParseCode(Enum):
good_pair_sub = 1 # 2 partners listed in partner.txt, code exists
format_error_sub = 2 # code
good_alone = 3 # txt and submission for 1 person
none_found_sub = 4
empty = 5
no_dir = 6
format_error_no_sub = 7
good_pair_no_... |
# Generated by Django 2.2.5 on 2020-01-12 21:29
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('sites_microsoft_auth', '0006_auto_20190923_1535'),
]
operations = [
migrations.AlterField(
model_name='siteconfiguration',
... |
from app.config.base import BaseConfig
class Config(BaseConfig):
DEBUG = False
ENVIRONMENT = 'DEVELOPMENT'
|
# Copyright (c) Facebook, Inc. and its affiliates.
import unittest
from densepose.structures import normalized_coords_transform
class TestStructures(unittest.TestCase):
def test_normalized_coords_transform(self):
bbox = (32, 24, 288, 216)
x0, y0, w, h = bbox
xmin, ymin, xmax, ymax = x0, ... |
import random
lives = 9
words = ['happy', 'pizza', 'otter', 'sixty', 'truck', 'teeth', 'night', 'light', 'fight', 'hight']
secret_word = random.choice(words)
clue = list('?????')
heart_symbol =u'♥ '
guessed_word_correctly = False
def find_question_mark(clue):
has_question_mark = False
index = 0
while i... |
#!/usr/bin/python
import sys, os, inspect
from argparse import ArgumentParser
import keras
import numpy
import skimage
from keras.utils import plot_model
from scipy import ndimage
from PIL import Image
from skimage.transform import resize
print("Parsing arguments ...")
parser = ArgumentParser("Classify an RGB-imag... |
import time
from django.conf import settings
def attach_ex(code, data):
"""
New version of attach for new protocol, simplified
@param code: Unique phone code
@type code: str
@param data: Dictionary data for the phone, passed from client in the 'data' request field
@type data: dict
"""
... |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: get_source_data.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.prot... |
num = int(input('\033[30;1;7mdigite um número\033[m: '))
resultado = num % 2
if resultado == 0:
print('\033[30;7;1mo número é\033[m \033[33;1mpar\033[m')
else:
print('\033[30;7;1mo número é\033[m \033[32;1mimpar\033[m')
|
import unicodedata
import arrow
from pdl.models import Proyecto
from pdl.models import Expedientes
from pdl.utils import convert_string_to_time
def get_proyecto_from_short_url(short_url):
"""
:param short_url:
:return: item for Proyecto
"""
item = Proyecto.objects.get(short_url=short_url)
if ... |
from pysyncgateway import UserClient
def test(syncgateway_public_url):
user_client = UserClient(syncgateway_public_url)
result = user_client.get_server()
assert sorted(list(result)) == ["couchdb", "vendor", "version"] # No ADMIN key
|
import os
# Local directory of CypherCat API
CYCAT_DIR = os.path.dirname(os.path.abspath(__file__))
# Local directory containing entire repo
REPO_DIR = os.path.split(CYCAT_DIR)[0]
# Local directory for datasets
DATASETS_DIR = os.path.join(REPO_DIR, 'Datasets')
# Local directory for datasets
DATASPLITS_DIR = os.path... |
import torch
from torchtext.legacy import data, datasets
from typing import Dict
SEED = 1234
torch.manual_seed(SEED)
torch.backends.cudnn.deterministic = True
TEXT = data.Field(tokenize='spacy',
tokenizer_language='en_core_web_sm',
include_lengths=True)
LABEL = data.LabelField(dty... |
import inspect
import unittest
from tests.integrations.config.database import DATABASES
from src.masoniteorm.connections import ConnectionFactory
from src.masoniteorm.models import Model
from src.masoniteorm.query import QueryBuilder
from src.masoniteorm.query.grammars import SQLiteGrammar
from src.masoniteorm.relatio... |
import torch
import torch.nn as nn
import torch.nn.functional as F
import math
from lib.models.modules.pos_embedding import PosEmbedding1D, PosEncoding1D
from lib.models.tools.module_helper import ModuleHelper
def Upsample(x, size):
"""
Wrapper Around the Upsample Call
"""
return nn.functional.interpol... |
#!/usr/bin/python3.7
from opty import algy, funky
import numpy as np
import sys
from configparser import ConfigParser
import random
conf = ConfigParser()
conf.read(sys.argv[1])
h = conf['GENERAL'].getfloat('h')
e = conf['GENERAL'].getfloat('e')
verbose = conf['GENERAL'].getboolean('verbose')
step = conf['simplex'].g... |
import numpy as np
"""
Supporting methods for data handling
"""
def shuffle_batch(images, labels):
"""
Return a shuffled batch of data
"""
permutation = np.random.permutation(images.shape[0])
return images[permutation], labels[permutation]
def extract_data(data, augment_data):
images,... |
import argparse
import os
from datarobot_drum.drum.push import PUSH_HELP_TEXT
import sys
import subprocess
from datarobot_drum.drum.description import version
from datarobot_drum.drum.common import (
LOG_LEVELS,
ArgumentsOptions,
RunLanguage,
TargetType,
ArgumentOptionsEnvVars,
)
class CMRunnerA... |
from setuptools import setup
setup(name='latext',
version='0.0.7',
description='For converting LaTeX to spoken text.',
url='https://github.com/Alex-Tremayne/LaTeXt',
author='Alex Tremayne',
author_email='alexjtremayne@gmail.com',
license='MIT',
classifiers=['Developme... |
#!/bin/env python3
import io
import logging
import os
import os.path
import re
import tarfile
import zipfile
from collections import namedtuple
import magic
import requests
import yaml
from github import Github
from requests.exceptions import ConnectionError
from semver import VersionInfo
Asset = namedtuple('Asset', ... |
from django.shortcuts import render
from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator
from actualite.models import Actualite
# Create your views here.
def actualite_views(request):
actualite_list = Actualite.objects.all().order_by('-created')[:1]
actualite_list_laterale = Actualite.objec... |
from django.db import models
class Mappings(models.Model):
TRUE_NAME = models.CharField(max_length = 100, default = "NONAME")
FILE_NAME = models.CharField(max_length = 100, default = "NONAME")
FILE_LINK = models.TextField(default = "NOFILE")
GEXF_LINK = models.TextField(default = "NOGEXF")
|
from recognizers.program import Program
class Parser:
def __init__(self, lexical_reclassifier):
self.lexical = lexical_reclassifier
def parse(self):
reuse_token = False
stack = []
machine = Program()
while True:
if not reuse_token:
token =... |
# diagrams as code vía https://diagrams.mingrammer.com
from diagrams import Cluster, Diagram, Edge, Node
from diagrams.aws.security import IAM, IAMRole
from diagrams.aws.management import Cloudtrail
from diagrams.aws.storage import S3
from diagrams.aws.compute import ECR
with Diagram("Sysdig Secure for Cloud\n(organi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.