text stringlengths 1 927k |
|---|
def votoElecciones():
print("Como saber si puedes votar por tu edad")
mensaje =""
edadP=int(input("ingrese la edad que tiene:"))
if edadP>=18:
mensaje ="Usted esta apto para votar"
else:
mensaje ="Usted no cumple con la edadad minima y no esta apto para votar"
print(mensaje)
votoElecciones() |
# Copyright 2012 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
#
# Copyright 2012 Nebula, Inc.
# Copyright (c) 2012 X.commerce, a business unit of eBay Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License")... |
'''
Function Name : main()
Description : How To Open File & Read The Data Using Open, Read
Function Date : 15 Mar 2021
Function Author : Prasad Dangare
Input : Int
Output : Int
'''
def main():
name = input("Enter the file name that you want to Read : ")
fobj = open... |
from pathlib import Path
from typing import Optional
from recording_script_generator.app.helper import (
raise_error_if_directory_exists_and_not_overwrite,
raise_error_if_directory_not_exists)
from recording_script_generator.app.io import (load_reading_passages,
l... |
import datetime
from django.test import TestCase
from django.utils import timezone
from .models import Question
from django.urls import reverse
class QuestionModelTests(TestCase):
def test_was_published_recently_with_future_question(self):
"""
was_published_recently() returns False for question... |
#!/usr/bin/env python3
from enum import Enum
class Type(Enum):
NORMAL = 0
FIGHTING = 1
FLYING = 2
POISON = 3
GROUND = 4
ROCK = 5
BIRD = 6
BUG = 7
GHOST = 8
FIRE = 20
WATER = 21
GRASS = 22
ELECTRIC = 23
PSYCHIC = 24
ICE = 25
DRAGON = 26
def __str__(s... |
"""This module defines all the ORS(https://openrouteservice.org/services/) commands."""
import os
import click
import openrouteservice as opnrs
import simplejson as json
from geojsonio import display as geo_display
from maps.exceptions import ApiKeyNotFoundError
from maps.utils import yield_subcommands
@click.group... |
# flake8: noqa
from .fields import ProcessedImageField |
from copy import deepcopy
from sklearn.metrics import f1_score
from sklearn.preprocessing import LabelBinarizer, MultiLabelBinarizer
from sklearn.preprocessing import LabelEncoder
import numpy as np
import pdb
def binarize_labels(true_labels, pred_labels):
srcids = list(pred_labels.keys())
tot_labels = [list(l... |
import codecs
import contextlib
import io
import locale
import sys
import unittest
import encodings
from unittest import mock
from test import support
from test.support import os_helper
from test.support import warnings_helper
try:
import _testcapi
except ImportError:
_testcapi = None
try:
import ctypes
... |
from __future__ import division, absolute_import
__copyright__ = "Copyright (C) 2012 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, incl... |
from django.shortcuts import render
from django.http import Http404
from Inventory.models import Item
def index(request):
items=Item.objects.exclude(amount=0)
return render(request,'Inventory/index.html',{
'items':items,})
def item_detail(request, id):
try:
item=Item.objects.get(id=id)
except Item.DoesNotExis... |
# encoding: utf-8
import datetime
import pytz
from babel import numbers
import ckan.lib.i18n as i18n
from ckan.common import _, ungettext
##################################################
# #
# Month translations #
# ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class AlipayOpenMiniAmpeTracerSyncModel(object):
def __init__(self):
self._device_id = None
self._product_id = None
self._spm_a = None
self._spm_b = None
self._s... |
"""
read picture
"""
import cv2
def read_picture(path):
"""
读取图片
:return:
"""
img = cv2.imread(path)
cv2.namedWindow("OPEN_CV_READ_IMG")
cv2.imshow("OPEN_CV_READ_IMG", img)
cv2.waitKey(0)
cv2.destroyAllWindows()
if __name__ == '__main__':
path = "../media/lena/lena.jpg"
r... |
from __future__ import annotations
import typing as t
from abc import ABC, abstractmethod
from pymenu.listener import GroupListener, Listener, ListenerInterface
from pymenu.triggers import Trigger
from rich import print
class ElementInterface(ListenerInterface, ABC):
@abstractmethod
def render(self) -> None:
... |
import pytest
import mymath.calculator
from mymath.calculator import add, div, filesum, fileconcat, approx_eq
# Simple tests
# ----------------------------------------------------
def test_add():
assert add(1, 2) == 3
def test_div():
assert div(4, 2) == 2
assert div(0, 2) == 0
# Catching excep... |
"""
@author: magician
@file: redis_action_ch05.py
@date: 2021/11/22
"""
import bisect
import contextlib
import csv
import functools
import json
import logging
import random
import threading
import time
import unittest
import uuid
import redis
from datetime import datetime
QUIT = False
SAMPLE_COUNT = 100
config_... |
# qubit number=5
# total number=50
import cirq
import qiskit
from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister
from qiskit import BasicAer, execute, transpile
from pprint import pprint
from qiskit.test.mock import FakeVigo
from math import log2,floor, sqrt, pi
import numpy as np
import networkx as ... |
import pdf_to_json as p2j
import json
url = "file:data/multilingual/Latn.VMW/Serif_12/udhr_Latn.VMW_Serif_12.pdf"
lConverter = p2j.pdf_to_json.pdf_to_json_converter()
lConverter.mImageHashOnly = True
lDict = lConverter.convert(url)
print(json.dumps(lDict, indent=4, ensure_ascii=False, sort_keys=True)) |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.11 on 2018-03-21 13:36
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('articles', '0007_auto_20180113_2139'),
]
operations = [
migrations.AlterFi... |
from XLMMacroDeobfuscator.excel_wrapper import ExcelWrapper
from XLMMacroDeobfuscator.boundsheet import Boundsheet
from XLMMacroDeobfuscator.boundsheet import Cell
from win32com.client import Dispatch
import pywintypes
from enum import Enum
import os
import re
class XlCellType(Enum):
xlCellTypeFormulas = -4123
... |
# -*- coding: utf-8 -*-
# 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, softw... |
# Protocol Buffers - Google's data interchange format
# Copyright 2008 Google Inc. All rights reserved.
# https://developers.google.com/protocol-buffers/
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redi... |
# coding: utf-8
from __future__ import unicode_literals
import json
import re
from .common import InfoExtractor
from ..utils import (
parse_duration,
unified_strdate,
)
class LibsynIE(InfoExtractor):
_VALID_URL = r'(?P<mainurl>https?://html5-player\.libsyn\.com/embed/episode/id/(?P<id>[0-9]+))'
_TE... |
# GNU MediaGoblin -- federated, autonomous media hosting
# Copyright (C) 2011, 2012 MediaGoblin contributors. See AUTHORS.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the Free Software Foundation, either versio... |
import sys
import six
import os
import json
import logging
import lib_kbase
import lib_patterns
import lib_naming
import lib_util
from lib_properties import pc
import lib_exports
_node_json_number = 0
class NodeJson:
"""This models a node as it will be saved to Json."""
# TODO: This creates a useless layer... |
# Copyright The IETF Trust 2021, All Rights Reserved
# -*- coding: utf-8 -*-
import datetime
import debug # pyflakes:ignore
from ietf.doc.factories import WgDraftFactory
from ietf.group.factories import GroupFactory, RoleFactory, DatedGroupMilestoneFactory
from ietf.utils.jstest import Ietf... |
# PyGetWindow
# A cross-platform module to find information about the windows on the screen.
"""
# Work in progress
# Useful info:
#https://stackoverflow.com/questions/373020/finding-the-current-active-window-in-mac-os-x-using-python
#https://stackoverflow.com/questions/7142342/get-window-position-size-with-python
... |
# encoding: utf-8
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding field 'Title.num_volumes'
db.add_column('manuscript_title', 'num_volumes', self.gf('django.db.mod... |
"""Main library."""
from typing import Optional
# Import module
import jpype
# Enable Java imports
import jpype.imports
# Pull in types
from jpype.types import *
import importlib
class JavaLib:
ROBOT_LIBRARY_SCOPE = "GLOBAL"
"""General library documentation."""
def __init__(
self,
lib... |
from discord.ext.commands import Cog, command
from discord import Embed, File
from discord.ext import commands
import os, discord
class Pin(Cog):
def __init__(self, bot):
self.bot = bot
self.emoji = "📌"
@Cog.listener()
async def on_raw_reaction_add(self, payload):
if payload.emoji... |
# -*- coding: utf-8 -*-
from mollusc.dist import Twine
class TestTwine(object):
def test_register_command(self):
twine = Twine(username='registrar', password='reg1strar')
assert twine.get_command('register', 'package.whl', {'-c': 'test register'}) == [
'twine',
'register',
... |
from django import forms
class SlackInviteForm(forms.Form):
email = forms.EmailField(label="Email") |
# OpenCMISS Python package initialisation file.
from pkgutil import extend_path
__path__ = extend_path(__path__, __name__) |
from .bhtreelib import *
__MGLTOOLSVersion__ = '1-4alpha3'
CRITICAL_DEPENDENCIES = ['mglutil']
NONCRITICAL_DEPENDENCIES = [] |
import time
import datetime
import numpy as np
__start_time = time.time()
__end_time = time.time()
def calc_accuracy(predicted_labels, real_labels):
correct_qty = 0
for i in range(len(predicted_labels)):
if predicted_labels[i] == real_labels[i]:
correct_qty += 1
return correct_qty * 1... |
from datetime import date
from decimal import Decimal
from functools import partial
from django.conf import settings
from django.db import models
from django.db.models import F, Q
from django.utils.translation import pgettext, pgettext_lazy
from django_countries.fields import CountryField
from django_prices.models imp... |
"""Added notifications
Revision ID: f0793141fd6b
Revises: 9ecc68fdc92d
Create Date: 2020-05-02 17:17:31.252794
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = "f0793141fd6b"
down_revision = "9ecc68fdc92d"
branch_labels = None
depends_on = None
def upgrade():
... |
data = b""
data += b"\x7F\x45\x4C\x46\x01\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00"
data += b"\x02\x00\x28\x00\x01\x00\x00\x00\x60\x00\x00\x00\x40\x00\x00\x00"
data += b"\xB0\x00\x00\x00\x00\x00\x00\x00\x34\x00\x20\x00\x01\x00\x28\x00"
data += b"\x04\x00\x03\x00"
data += b"\x00" * (0x40 - len(data))
data += b"\x0... |
#!/usr/bin/env python3
# Copyright (c) 2014-2017 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Base class for RPC testing."""
from enum import Enum
import logging
import optparse
import os
import p... |
import halftones
from scipy.misc import *
gray = imread('lena1.jpg', True)
# halftones
jarvis = halftones.halftone.error_diffusion_jarvis(gray)
floyd_steinberg = halftones.halftone.error_diffusion_floyd_steinberg(gray)
stucki = halftones.halftone.error_diffusion_stucki(gray)
burkes = halftones.halftone.error_diffusio... |
#!/usr/bin/env python
"""Apply the DESITrIP CNN classifier to observed spectra,
chosen by tile ID and date.
"""
from desispec.io import read_spectra, write_spectra
from desispec.spectra import Spectra
from desitarget.cmx.cmx_targetmask import cmx_mask
from desitrip.preproc import rebin_flux, rescale_flux
from astrop... |
# Copyright 2021 DAI Foundation
#
# 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,... |
class RET:
OK = '0'
DBERR = '4001'
NODATA = '4002'
DATAEXIST = '4003'
DATAERR = '4004'
SESSIONERR = '4101'
LOGINERR = '4102'
PARAMERR = '4103'
USERERR = '4104'
ROLEERR = '4105'
PWDERR = '4106'
REQERR = '4201'
IPERR = '4202'
THIRDERR = '4301'
IOERR = '4302'
... |
from functools import wraps
from urllib.error import URLError
from django.db import models
from django.urls import reverse
#from amazonproduct import API as AmazonAPI
from manabi.apps.utils.slugs import slugify
from django.conf import settings
#TODO-OLD find different way.
#amazon_api = AmazonAPI(settings.AWS_KEY, ... |
import _plotly_utils.basevalidators
class SurfaceValidator(_plotly_utils.basevalidators.CompoundValidator):
def __init__(self, plotly_name="surface", parent_name="", **kwargs):
super(SurfaceValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
dat... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 4 15:57:47 2017
@author: wangronin
"""
import pdb
import os
import pandas as pd
from mpi4py import MPI
import numpy as np
from deap import benchmarks
from mipego import mipego
from mipego.surrogate import RrandomForest, RandomForest
from mipego.S... |
"""Package tool."""
VERSION = 0.1 |
'''
Basic LinUCB implementation.
'''
# Python imports.
import numpy as np
from collections import defaultdict
# Other imports.
from tensor_rl.agents.AgentClass import Agent
class LinUCBAgent(Agent):
'''
From:
Lihong Li, et al. "A Contextual-Bandit Approach to Personalized
News Article Recomme... |
# pylint: disable=missing-docstring
import unittest
from unittest.mock import MagicMock
import handsdown.ast_parser.smart_ast as ast
from handsdown.ast_parser.analyzers.module_analyzer import ModuleAnalyzer
class TestModuleAnalyzer(unittest.TestCase):
def test_init(self):
analyzer = ModuleAnalyzer()
... |
import torch
import torch as th
import syft
from syft.frameworks.torch.tensors.interpreters.additive_shared import AdditiveSharingTensor
from syft.frameworks.torch.tensors.interpreters.precision import FixedPrecisionTensor
from syft.generic.pointers.pointer_tensor import PointerTensor
import pytest
def test_init(wor... |
from setuptools import setup, find_packages
setup(
name='jogger',
version='0.1.1',
description='Navigate log files.',
long_description=(
open('README.md').read()
),
url='http://github.com/jomido/jogger/',
license='MIT',
author='Jonathan Dobson',
author_email='jon.m.dobson@gm... |
# 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 may ... |
#!/usr/bin/env python
from __future__ import print_function
import datetime
try:
from urllib.request import urlopen, Request #py3
except ImportError:
from urllib2 import urlopen, Request #py2
import requests
from netCDF4 import Dataset
import os, glob
'''
Methods for generating ordered filelist for... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# This is very different to AboutModules in Ruby Koans
# Our AboutMultipleInheritance class is a little more comparable
#
from runner.koan import *
from another_local_module import *
from local_module_with_all_defined import *
class AboutModules(Koan):
def test_i... |
import torch
from torch._six import int_classes as _int_classes
class Sampler(object):
r"""Base class for all Samplers.
Every Sampler subclass has to provide an :meth:`__iter__` method, providing a
way to iterate over indices of dataset elements, and a :meth:`__len__` method
that returns the length o... |
"""
此模块做停车管理系统的客户端
Author:Recall
Date: 2018-10-19
module: socket、multiprocessing、sys、os、time、signal
Email:
"""
from socket import *
from setting import *
from messageAff import user_message
from multiprocessing import Process
import sys,os,time,signal
class carClient(object):
def __init__(self):
self.so... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.8 on 2018-04-26 21:19
from __future__ import unicode_literals
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('ubicacion', '0003_auto_20180417_1603'),
]
operations =... |
# 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 ... |
# -*- coding: utf-8 -*-
"""
This module provides an extension to write all features, scenarios and steps to the syslog.
"""
from __future__ import unicode_literals
from radish.terrain import world
from radish.feature import Feature
from radish.hookregistry import before, after
from radish.extensionregistry impor... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.11 on 2018-03-27 13:41
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('setup_guide', '0004_auto_20180322_1443'),
]
operations = [
migrations.RenameField(... |
from __future__ import annotations
import math
import warnings
from collections.abc import Iterable
from functools import partial, reduce, wraps
from numbers import Integral, Real
import numpy as np
from tlz import concat, interleave, sliding_window
from dask.array import chunk
from dask.array.core import (
Arra... |
import copy
from datetime import datetime
class LifeGame:
def __init__(self, width, height):
self.__width = width
self.__height = height
self.__cells = [[False for x in range(0, width)] for y in range(0, height)]
self.__fps = 2
self._next_ts = datetime.now().timestamp()
... |
#!/usr/bin/env python
"""docker monitor using docker /events HTTP streaming API"""
from contextlib import closing
from functools import partial
from socket import socket, AF_UNIX
from subprocess import Popen, PIPE
from sys import stdout, version_info
import json
import shlex
if version_info[:2] < (3, 0):
from htt... |
import numpy as np
import pytest
from pandas.core.dtypes.common import ensure_platform_int
import pandas as pd
from pandas import (
Float64Index,
Index,
Int64Index,
RangeIndex,
)
import pandas._testing as tm
from pandas.tests.indexes.test_numeric import Numeric
# aliases to make some tests easier to ... |
from rpython.translator.backendopt.merge_if_blocks import merge_if_blocks_once
from rpython.translator.backendopt.merge_if_blocks import merge_if_blocks
from rpython.translator.backendopt.all import backend_optimizations
from rpython.translator.translator import TranslationContext, graphof as tgraphof
from rpython.flow... |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def levelOrderBottom(self, root):
"""
:type root: TreeNode
:rtype: List[List[int]]
"""
... |
import json
from json.decoder import JSONDecodeError
import xml.etree.ElementTree as ET
import isodate
import re
from .common import (
Chat,
BaseChatDownloader,
Remapper as r
)
from requests.exceptions import RequestException
from ..utils import (
remove_prefixes,
multi_get,
try_get_first_val... |
import re
from .exceptions import InvalidPostcode
class PostcodeRule:
attr_applied = None
applied_areas_regex = None
rule_regex = None
def __init__(self, postcode):
self.postcode = postcode
def validate(self):
postcode_attr_value = getattr(self.postcode, self.attr_applied, None)... |
#!/usr/bin/env python3
"""Classes and functions related to dataset generation for learning Q
functions. Datasets in this sense are mappings from board positions
(represented as flattened arrays of tile numbers) to score values.
"""
import argparse
import sys
import numpy as np
from game.common import *
from game.b... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import sys, os, stat, commands
from distutils.core import setup
from distutils.extension import Extension
from Cython.Build import cythonize
try:
from Cython.Distutils import build_ext
except:
print "You don't seem to have Cython installed. Please get a"
print... |
# -*- coding: utf-8 -*-
import logging
LOG = logging.getLogger(__name__)
def institute(store, institute_id):
""" Process institute data.
Args:
store(adapter.MongoAdapter)
institute_id(str)
Returns
data(dict): includes institute obj and specific settings
"""
institute_ob... |
# -*- coding=utf-8 -*-
from __future__ import print_function, absolute_import
import attr
import operator
from collections import defaultdict
from . import BaseFinder
from .path import PathEntry
from .python import PythonVersion, VersionMap
from ..exceptions import InvalidPythonVersion
from ..utils import ensure_path
... |
# coding: utf-8
"""
Seldon Deploy API
API to interact and manage the lifecycle of your machine learning models deployed through Seldon Deploy. # noqa: E501
OpenAPI spec version: v1alpha1
Contact: hello@seldon.io
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future... |
#!/usr/bin/env python
# Copyright 2016 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... |
'''
Determined model def example:
https://github.com/determined-ai/determined/tree/master/examples/computer_vision/cifar10_pytorch
'''
import tempfile
from typing import Any, Dict, Sequence, Tuple, Union, cast
from functools import partial
import os
import boto3
import numpy as np
from sklearn.metrics import average_p... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
JSON-RPC (remote procedure call).
It consists of 3 (independent) parts:
- proxy/dispatcher
- data structure / serializer
- transport
It's intended for JSON-RPC, but since the above 3 parts are independent,
it could be used for other RPCs as well.
Current... |
import csv
import eyed3
import librosa
import numpy as np
import sys
def load_editorial_metadata(audiofile):
'''Loads an audio file and extract its editorial metadata
Args:
audiofile (string): audio file to be extracted.
Returns:
title (string): title of the mp3 file
artist (strin... |
import keras.backend as K
import numpy as np
from PIL import Image, ImageDraw
def get_activations(model, model_inputs, print_shape_only=False, layer_name=None):
print('----- activations -----')
activations = []
inp = model.input
model_multi_inputs_cond = True
if not isinstance(inp, list):
# only one input! let... |
import graphene
from ..core.fields import PrefetchingConnectionField
from ..descriptions import DESCRIPTIONS
from ..translations.mutations import PageTranslate
from .bulk_mutations import PageBulkDelete
from .mutations import PageCreate, PageDelete, PageUpdate
from .resolvers import resolve_page, resolve_pages
from .t... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
###############################################################################
# Copyright Kitware 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 ... |
#!/usr/bin/python
import sys
from w1thermsensor import W1ThermSensor
if len(sys.argv) == 2:
sensor_id = sys.argv[1]
else:
print('usage: sudo ' + sys.argv[0] + ' <sensor id>')
print('example: sudo ' + sys.argv[0] + ' 00000588806a - Read from an DS18B20 wiht id 00000588806a')
sys.exit(1)
sensor = W1The... |
from jsonrpc import ServiceProxy
import sys
import string
import getpass
# ===== 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:6666")
e... |
# -*- coding: utf-8 -*-
import numpy as np
import torch
"""
The complete formulas and explanations are available in our doc:
https://dwi-ml.readthedocs.io/en/latest/formulas.html
"""
def fisher_von_mises_log_prob_vector(mus, kappa, targets):
log_c = np.log(kappa) - np.log(2 * np.pi) - np.log(np.exp(kappa) -
... |
from fastapi import FastAPI
from pydantic import BaseModel
from starlette.responses import FileResponse
class Item(BaseModel):
id: str
value: str
responses = {
404: {"description": "Item not found"},
302: {"description": "The item was moved"},
403: {"description": "Not enough privileges"},
}
a... |
from __future__ import unicode_literals
from django.apps import AppConfig
class AccountsConfig(AppConfig):
name = 'Fango.accounts' |
# Copyright Contributors to the Pyro project.
# SPDX-License-Identifier: Apache-2.0
"""
Example: Bayesian Models of Annotation
======================================
In this example, we run MCMC for various crowdsourced annotation models in [1].
All models have discrete latent variables. Under the hood, we enumerate... |
"""Tests for the dbt templater."""
import glob
import os
import pytest
import logging
from pathlib import Path
from sqlfluff.core import FluffConfig, Lexer, Linter
from sqlfluff.core.errors import SQLTemplaterSkipFile
from test.fixtures.dbt.templater import ( # noqa: F401
DBT_FLUFF_CONFIG,
dbt_templater,
... |
from typing import Any, MutableMapping, Optional
def merge_dicts(a: MutableMapping[str, Any], b: MutableMapping[str, Any], path: Optional[list] = None) -> MutableMapping[str, Any]:
"""
Merge the keys and values of the two dicts.
:param a:
:param b:
:param path:
:return:
:raises ValueError... |
#! /usr/bin/env python
# -*- encoding: UTF-8 -*-
"""Example: Get an image. Display it and save it using PIL."""
import qi
import argparse
import sys
import time
import Image
def main(session):
"""
First get an image, then show it on the screen with PIL.
"""
# Get the service ALVideoDevice.
vide... |
# Copyright 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# All Rights Reserved.
# Copyright 2012 Red Hat, Inc.
# Copyright 2013 NTT corp.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file exc... |
# Copyright (c) 2013 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 law... |
"""
Check if container weights can be properly seeded.
"""
import unittest
from conflowgen.domain_models.distribution_models.container_weight_distribution import ContainerWeightDistribution
from conflowgen.domain_models.distribution_seeders import container_weight_distribution_seeder
from conflowgen.tests.substitute_... |
import httplib2
from bs4 import BeautifulSoup, SoupStrainer
import urllib.request, urllib.error
import os
import re
import sys
def get(url):
http = httplib2.Http(".cache", disable_ssl_certificate_validation=True)
status, response = http.request(url)
return response
def getlinks(url):
return Beautiful... |
# This exploit script is my first. I have to manually change the paddings before and after the input to get the desired chosen plaintext. I created it to understand how desired chosen plaintext attack works. See automatic_soln_for_spyfi.py for the automatic solution.
from pwn import *
padding_before = "A" * 11
paddin... |
"""
Author: CAI JINGYONG @ BeatCraft, Inc & Tokyo University of Agriculture and Technology
placeholder
input: numpy array
output: numpy array
"""
import numpy
class LogQuant:
def __init__(self,layer,bitwidth):
self.layer_data = layer
self.width = bitwidth
self.maxima = numpy.amax(layer)
... |
from abc import ABCMeta, abstractmethod
from hashlib import sha256
from typing import Any, Dict, List, Tuple
from chives.types.blockchain_format.sized_bytes import bytes32
"""
A simple, confidence-inspiring Merkle Set standard
Advantages of this standard:
Low CPU requirements
Small proofs of inclusion/exclusion
Reas... |
"""
Sensitivities of *DSLR* Cameras
===============================
Defines the sensitivities of *DSLR* cameras.
Each *DSLR* camera data is in the form of a *dict* of
:class:`colour.characterisation.RGB_CameraSensitivities` classes as follows::
{
'name': RGB_CameraSensitivities,
...,
'nam... |
from __future__ import absolute_import
from gevent import monkey
monkey.patch_all(thread=False, select=False)
import json
import arrow
from apiclient.discovery import build
from gevent.pool import Pool
from httplib2 import Http
from logbook import Logger
from oauth2client import client
from . import config
logger ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.