content stringlengths 5 1.05M |
|---|
# -*- UTF-8 -*-
import sqlite3,os,sys
import re
import pprint
from time import time
from hashlib import md5
from metadata import *
""" This module is intended for working with SQLite database.
runsql decorator is used to perform queries in a simple and
consistent manner. Instead of opening database each and ev... |
from collections import deque
from typing import List
class Solution:
def accountsMerge(self, accounts: List[List[str]]) -> List[List[str]]:
# Build email to name mapping
email_map = dict()
for account in accounts:
for email in account[1:]:
if email not i... |
import decimal
import logging
class InvalidConfigurationException(Exception):
pass
class Configuration(object):
def __init__(self, config):
if config.key != 'Module':
raise InvalidConfigurationException("config.key %s != Module\n" % config.key)
if config.values[0] != 'oci_write_p... |
from django.conf.urls import url, patterns
from ginger.conf.urls import scan
from . import views
urlpatterns = scan(views) |
import logging
from pygerrit.rest import GerritRestAPI
from rh_nexttask.client import Client
from rh_nexttask.constants import Constants
from rh_nexttask.date import Date
from rh_nexttask.review import Review
logger = logging.getLogger('rh-nexttask')
class Bz(object):
"""Hold a reference to one bugzilla.
""... |
import cProfile as profiler
import pstats
def start_profiler():
profile = profiler.Profile(timeunit=100)
profile.enable()
return profile
def stop_profiler(profiler, filename=None):
filename = filename or "./profile.pf"
profiler.disable()
sortby = 'cumulative'
ps = pstats.Stats(profile... |
import platform
import os
import sys
import vlc
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtGui import QPalette, QColor
class Ui_MainWindow(object):
def __init__(self):
super().__init__()
#self.setWindowTitle("PyMediaPlayer")
self.instance = vlc.Instance()
self.media =... |
#!/usr/bin/env python
# -*- coding: utf8 -*-
# python setup.py build_ext --inplace
"""
setup.py file
"""
import multiprocessing
import os
import pathlib
import platform
import re
import shutil
import subprocess
import sys
import sysconfig
import time
import unittest
import warnings
from abc import ABC
import distut... |
# Mine domain-specific paraphrases from SNIPs datasets
import os
import logging
import csv
import spacy
import codecs
import argparse
from generate_word_alignment import make_alignment_matrix
from preprocessing import create_valid_groups, normalize_sent, divide_sent_by_prep
from fsa import create_fsa, process_sents, fi... |
import datetime
import pandas as pd
import numpy as np
from dateutil.relativedelta import relativedelta
def print_schedule(data):
if len(data[0]) == 5:
fmt = "{:5,d} {:11,.2f} {:11,.2f} {:11,.2f} {:11,.2f}"
elif len(data[0]) == 6:
fmt = "{:12} {:5,d} {:11,.2f} {:11,.2f} {:11,.2f} {:11,.2f}"
... |
"""
asynchronous bot
fetches reservation events from
if-algerie
login to portal
go to /exams
fetch events
crawl events
event_crawler_callback
return
fetch payment days
crawl payments
payment_Crawler_callback
return
on error
login and r... |
# Core Pkgs
import streamlit as st
import streamlit.components.v1 as stc
import requests
base_url = "https://jobs.indeed.com/positions.json?description={}&location={}"
# Fxn to Retrieve Data
def get_data(url):
resp = requests.get(url)
return resp.json()
JOB_HTML_TEMPLATE = """
<div style="width:... |
from django.contrib import admin
from django.urls import path,include
from Admin import views
urlpatterns = [
path(r'approveEvent/', views.approveEvents, name='approveEvents'),
path(r'operate/', views.operate, name='operate'),
path(r'createEvent/', views.createEvent, name='createEvent'),
path(r'createCo... |
# -*- coding: utf-8 -*-
"""
apis.wordpress_xml_rpc
~~~~~~~~~~~~~~~~~~~~~~
Wordpress-compatible XML-RPC API
http://flask.pocoo.org/snippets/96/
"""
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.abspath(os.path.dirname(__file__))))
from flask import request, Response
from app import ... |
from unittest import TestCase
import matplotlib.pyplot as plt
import numpy as np
#from smithers.dataset import Dataset
class TestDataset(TestCase):
def test_init(self):
print('boh')
pass
|
# coding=utf-8
# Copyright 2019 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... |
import numpy
import six
from chainer import cuda
from chainer import utils
def assert_allclose(x, y, atol=1e-5, rtol=1e-4, verbose=True):
"""Asserts if some corresponding element of x and y differs too much.
This function can handle both CPU and GPU arrays simultaneously.
Args:
x: Left-hand-sid... |
#This is a percentage calculator
import time
import colorama
from colorama import Fore, Back, Style
colorama.init()
print(Fore.LIGHTGREEN_EX)
print(''' ██▓███ ▄████▄ ▄▄▄ ██▓ ██▓███ ▓██ ██▓
▓██░ ██▒▒██▀ ▀█ ▒████▄ ▓██▒ ▓██░ ██▒▒██ ██▒
▓██░ ██▓▒▒▓█ ▄ ▒██ ▀█▄ ▒██░ ▓██░ ██▓▒ ▒██ █... |
from h2o.estimators.xgboost import *
from tests import pyunit_utils, os
import sys
sys.path.insert(1,"../../../")
from h2o.two_dim_table import H2OTwoDimTable
def xgboost_feature_interactions():
prostate_frame = h2o.import_file(pyunit_utils.locate('smalldata/prostate/prostate.csv'))
y = "RACE"
ignored_col... |
# weird mypy bug with imports
from typing import Any, Dict, Generator # pylint: disable=unused-import
import attr
from ...models import TestResultSet
from ...utils import get_requests_auth
from .. import events
from .core import BaseRunner, get_session, network_test, wsgi_test
@attr.s(slots=True) # pragma: no mut... |
#
# General-purpose Photovoltaic Device Model - a drift diffusion base/Shockley-Read-Hall
# model for 1st, 2nd and 3rd generation solar cells.
# Copyright (C) 2008-2022 Roderick C. I. MacKenzie r.c.i.mackenzie at googlemail.com
#
# https://www.gpvdm.com
#
# This program is free software; you can redist... |
#!/usr/bin/python
#
# Copyright 2021 Jigsaw Operations 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 applicabl... |
class PackObject:
type: int
hash: str
ref: bytes
data: bytes
object_size: int
def __init__(self, hash: str):
self.type = 0
self.ref = None
self.hash = hash |
# Generated by Django 3.2.6 on 2021-08-16 13:04
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('emailmanager', '0002_rename_emails_email'),
]
operations = [
migrations.AlterField(
model_name='email',
name='sender... |
#!/usr/bin/python
# A simple data loader that imports the train and test mat files
# from the `filename` and converts them to torch.tesnors()
# to be loaded for training and testing DLoc network
# `features_wo_offset`: targets for the consistency decoder
# `features_w_offset` : inputs for the network/encoder
# `labels_... |
#!/usr/bin/env python3
from experiment import Experiment
if __name__ == '__main__':
Experiment.run()
|
""" Given a characters array tasks, representing the tasks a CPU needs to do,
where each letter represents a different task. Tasks could be done in any
order. Each task is done in one unit of time. For each unit of time, the CPU
could complete either one task or just be idle.
However, there is a non-n... |
#
# This file is part of the PyMeasure package.
#
# Copyright (c) 2013-2020 PyMeasure Developers
#
# 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 limit... |
def miniMaxSum(arr):
sumValue = maxV = minV = arr[0]
for item in range(1, len(arr)):
print(item)
if maxV < arr[item]:
maxV = arr[item]
if minV > arr[item]:
minV = arr[item]
sumValue += arr[item]
print(sumValue - maxV, sumValue - minV)
miniMaxSum([7,... |
from django.shortcuts import redirect
from django.contrib.auth import authenticate, login, logout
from celery_tasks.tasks import celery_send_mail
from apps.user.models import User
import re
from django.shortcuts import render
from django.views import View
from utils.security import get_user_token, get_activation_link, ... |
import sys
import logging
import inspect
import numpy as np
import sympy as sp
import ANNarchy_future.api as api
import ANNarchy_future.parser as parser
class SynapseParser(object):
"""Synapse parser.
Attributes:
synapse (api.Synapse): Synapse class.
pre (api.Neuron): pre-synaptic Neuron cl... |
from rasa.core.channels.channel import InputChannel,UserMessage,RestInput,CollectingOutputChannel
from sanic import Sanic, Blueprint, response
import asyncio
import inspect
import json
import logging
import uuid
from asyncio import Queue, CancelledError
from sanic import Sanic, Blueprint, response
from sanic.request im... |
from enum import Enum
class VibrationType(Enum):
NONE = 0
SHORT = 1
MEDIUM = 2
LONG = 3 |
"""
Created on Mon Oct 15 17:11:01 2018
@author: zhengyi
"""
|
from rest_framework import viewsets
from api.componentgroup import serializers
from core.models import ComponentGroup
class ComponentViewSet(viewsets.ModelViewSet):
def get_queryset(self):
return ComponentGroup.objects.all()
def get_serializer_class(self):
if self.action == "list":
... |
# -*- coding: utf-8 -*-
"""
test_build_gettext
~~~~~~~~~~~~~~~~~~
Test the build process with gettext builder with the test root.
:copyright: Copyright 2010 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import gettext
import os
from subprocess import Popen, PIPE
fr... |
from .baseactions import BaseActions
from models.state import State
import re
class StateActions(BaseActions):
@classmethod
def _regular_attribute_actions(cls, diff: dict, obj, old_obj=None):
actions = []
for root_attr in diff:
attr = root_attr.split('.')[1]
if attr == ... |
# Generated by Django 2.1.7 on 2019-07-07 21:39
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [("app", "0023_auto_20190706_2208")]
operations = [
migrations.AlterField(
model_name="move",
name="action_type",
field=... |
import operator
from functools import partial
from typing import Callable, Tuple, Optional, Dict
from pypika import functions
from pypika.enums import SqlTypes
from tortoise.fields import BackwardFKField, Field, ManyToManyField, RelationField
#
# Encoders
#
def identity_encoder(value, *args):
return value
d... |
from cloud_vision_samples.args import parse_request_vision_args
from cloud_vision_samples.vision_api import create_single_post, request_post
def main():
# parse arguments
input_loc, api_key, detection_types, = parse_request_vision_args()
# print(input_loc)
# print(detection_types)
# print(vision_... |
# test the PredictZero method class
import tigerforecast
import jax.numpy as np
import matplotlib.pyplot as plt
def test_predict_zero(steps=1000, show_plot=True):
T = steps
p, q = 3, 3
problem = tigerforecast.problem("ARMA-v0")
cur_x = problem.initialize(p, q)
method = tigerforecast.method("Predi... |
from django.apps import AppConfig
class DismissalConfig(AppConfig):
name = 'dismissal'
|
"""
Выполнить собственную программную реализацию любой хеш функции.
"""
import hashlib
from mymd5 import MD5
def main():
input_string = input("Введите строку для хеширования -> ")
md5_hash = MD5.hash(input_string)
print("Хеш MD5 собственной реализации\n{}".format(md5_hash))
result = hashlib.md5(inpu... |
import requests
import json
def find_needle():
r = requests.post('http://challenge.code2040.org/api/haystack', data={'token': '7628d19dc804169849b04c989c364a4e'})
d = json.loads(r.text)
for idx, val in enumerate(d['haystack']):
if val == d['needle']:
return idx
if __name__ == '__main__':
target = fi... |
# Copyright 2021 The WAX-ML 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in w... |
from django import forms
from ..models import Athlete
class AthleteForm(forms.ModelForm):
class Meta:
model = Athlete
fields = '__all__'
|
# coding: utf-8
"""
Traitement des VUES
"""
import re
import collections
from django.contrib.auth.decorators import login_required
from django.shortcuts import render, redirect, get_object_or_404
from django.core.exceptions import PermissionDenied
from django.urls import resolve
from django.http import JsonResponse... |
__version__ = '0.1'
__all__ = ["hamilton",
"objects",
"hamutilities",
"structure",
"utilities",
"gui",
"masterjobs",
"workbench.py",
"workbench_gui.py",
"setup.py",
"update.py"]
|
import cv2
import os
import gco
import argparse
import numpy as np
import pickle as pkl
from tqdm import tqdm, trange
from glob import glob
from scipy import signal
from opendr.camera import ProjectPoints
from sklearn.mixture import GaussianMixture
from util.visibility import VisibilityChecker
from util.labels import... |
from .client import HandlerClient
|
from PyQt5.QtWidgets import QGridLayout
def add_grid_to_layout(grid: list, layout: QGridLayout, start_index: int = 0):
"""Automatically adds a specified grid of QWidgets to
a given Layout
:param grid: The Grid to add to the Layout
:param layout: The Layout to use
:param start_index: What index to... |
import numpy as np
class LinearRegression:
def __init__(self, lr=0.01, n_iters=1000):
self.lr = lr
self.n_iters = n_iters
self.weights = None
self.bias = None
def fit(self, X,y):
#init parameters
n_samples, n_features = X.shape
self.weights = np.zeros(n_features)
self.bias = 0
#... |
#!/usr/bin/env python
# pylint: disable=invalid-name,bare-except
# Script to output table with the count of triage related tickets, grouped by week for the past 3 weeks
import json
import tabulate
import jira_cmd
class TriageStats:
def __init__(self):
parser = jira_cmd.build_parser()
def my_exi... |
#!/usr/bin/python
# -*- encoding: utf-8 -*-
import time
import logging
import os
import sys
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
import numpy as np
from backbone import Embeddor
from loss import BottleneckLoss
from market1501 import Market1501
from balanced_sampler import Balance... |
"""This module provides the Pins contrib class"""
import json
import time
import datetime
from ..handlers import CommandHandler, ReactionHandler
from ..dataclasses import Message, Reaction, MessageReaction
from .._i18n import _
class Pins(object):
"""
This class provides a system for pinning messages.
T... |
# coding:utf-8
import json
from urllib import request
from urllib.parse import quote
import math
import xlwt
# 作者:wangzhipan,Email:1044625113@qq.com
# 特别注意,高德地图下载的POI点为火星坐标系统,我们需要后续处理,转成WGS84坐标系统下才能用
# 根据城市名称和分类关键字获取poi数据
def getpois(cityname, keywords):
i = 1
poilist = []
while True: # 使用while循环不断分页获... |
from mxnet.gluon.nn import HybridSequential
# from d2l import mxnet as d2l
class RFN(HybridSequential):
def __init__(self,
output_mode: {'node', 'edge', 'between_edge'}=None,
**kwargs):
super().__init__(**kwargs)
self.output_mode = output_mode
def _output(sel... |
#!/usr/bin/env python3
# Copyright 2021, Collabora, Ltd.
# SPDX-License-Identifier: BSL-1.0
"""Handle the process of recording data from the "log" firmware."""
import asyncio
import logging
import dataclasses
import datetime
from typing import Optional
import aioconsole
import aioserial
from serial.tools import list_... |
# 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
# distributed under t... |
import pytest
from investmentstk.data_feeds import AvanzaFeed
from investmentstk.data_feeds.data_feed import TimeResolution
from investmentstk.models.asset import Asset
from investmentstk.models.source import Source
@pytest.fixture
def subject() -> AvanzaFeed:
return AvanzaFeed()
@pytest.fixture
def volvo() ->... |
from .merge_transformers import ConcatMerger, AverageMerger
__all__ = ["ConcatMerger", "AverageMerger"]
|
# Copyright 2010-2019 Dan Elliott, Russell Valentine
#
# 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 appl... |
#program for Toffolli gate.
#expected file name is 'in.qc'
program = """version 1.0
qubits 3
Toffoli q[0], q[1], q[2]
"""
f = open('in.qc','w')
print >>f, program
f.close() |
#! /usr/bin/env python
# -*- coding: utf-8 -*-
from flask.views import MethodView
from flask import request, g, current_app
# dracarys import
from flask_restapi.views import APIMethodView
from .models import Author
from .forms import AuthorForm
class AuthorView(APIMethodView):
model = Author
paginate_by = 1... |
# Copyright 2021 The MT3 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 applicable law or agreed to in writ... |
# i=1
# while i<=100:
# if i % 5 == 0 and i % 7 == 0: #ja i dalās ar 5 bez atlikuma
# print("FizzBuzz", end=",")
# elif i % 5 == 0:
# print("Fizz", end=",")
# elif i % 7 == 0:
# print("Buzz", end=",")
# else:
# print(i, end=",")
# i = i+1
# result = ""
# fo... |
import requests
from tenacity import retry, stop_after_attempt, wait_fixed
from utils import config, json, log
headers = {"token": config.app["apiToken"], "Content-Type": "application/json"}
def retry_failed(retry_state):
log.error(0, f"请求重试失败: {retry_state.args[0]}, {retry_state.args[1]}, {retry_state.outcome.... |
class Memento:
def restore(self):
pass
class Originator:
def save(self):
pass
class ConcreteOriginator:
def __init__(self, state):
self.__state = state
def set_state(self, state):
self.__state = state
def get_state(self):
return self.__state
def sav... |
import torch
from torch._C import INSERT_FOLD_PREPACK_OPS, Node
import torch.nn as nn
import torch.nn.functional as F
import random
import numpy as np
class HGCN(nn.Module):
def __init__(self, n_edges, in_feature, out_feature, n_agents):
super(HGCN, self).__init__()
print(n_edges)
self.W_li... |
#!/usr/bin/env python3.5
# driver.py
#
# William N. Sexton and Simson L. Garfinkel
#
# Major Modification log:
# 2018-06-12 bam - refactored DAS to modularize code found in the run function
# 2017-12-10 slg - refactored the creation of objects for the DAS() object.
# 2017-11-19 slg - rewrite for abstract modular ... |
"""
MIT License
Copyright (c) 2020 Christoph Kreisl
Copyright (c) 2021 Lukas Ruppert
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... |
import unittest
import numpy as np
from pyfpt.numerics import histogram_normalisation
class TestHistogramNormalisation(unittest.TestCase):
def test_histogram_normalisation(self):
num_data_points = 100000
# Testing uneven bins
bins = np.array([-4., -3.3, -3.2, -3., -2.9, -2.4, -1.9, -1.5, ... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.test import TestCase
from .models import Profile
# Create your tests here.
class ProfileClass(TestCase):
def setUp(self):
'''
Set up method to run before each test cases.
'''
self.new_profile=Profile(name =... |
# -*- coding: utf8 -*-
"""
Decodes FLAC files into the WAV format.
Author: Eduardo Ferreira
License: MIT (see LICENSE for details)
"""
from anarky.audio.decode import decode_flac_wav
from anarky.enum.description import Description
from anarky.enum.script import Script
from anarky.interface import get_options
def ru... |
for path in ("drift", "accel", "boost", "brake"):
speedTables = []
lastSpeed = -999999
lastAngle = 0
with open("turn." + path + ".txt", "r+") as f:
for line in f:
inSpeed, angle, totalTicks, driftTicks, outSpeed, outX, outY = map(float, line.split("\t"))
if inSpeed != lastSpeed:
speedTables.append(... |
from __future__ import print_function, division, absolute_import
class EmptyList(object):
"""
Utility that can be numerically indexed, but
always returns None.
If a no length or a negative length are passed at construction,
the list will ALWAYS return None.
If a non-negative length is passse... |
"""
A simple set of functions to compute LJ energies and gradients.
"""
import numpy as np
def calc_energy_and_gradient(positions, sigma, epsilon, do_gradient=True):
"""
Computes the energy and gradient of a expression in the form
V_{ij} = 4 \epsilon [ (sigma / r) ^ 12 - (sigma / r)^6]
"""
# Hol... |
import sys
import os
sys.path.append(os.path.abspath("../")) |
import FWCore.ParameterSet.Config as cms
process = cms.Process("CTPPS")
from FWCore.MessageLogger.MessageLogger_cfi import *
process.load("Configuration.StandardSequences.GeometryExtended_cff")
process.load("Configuration.StandardSequences.MagneticField_38T_cff")
from Geometry.VeryForwardGeometry.geometryRPFromDD_2... |
import pathlib
import os
import logging
from datetime import datetime
from typing import Tuple
import numpy as np
import dicom2nifti
from tqdm import tqdm
from glob import glob
from natsort import natsorted
from ballir_dicom_manager.directory_manager import DirManager
from ballir_dicom_manager.file_readers.read_dicom... |
from django.shortcuts import render, redirect
from .models import Category, Photo
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from .forms import CustomUserCreationForm
# Create your views here.
def loginUser(request):
page = 'login'
if ... |
import os
import numpy as np
import imageio
from torch import multiprocessing
from torch.utils.data import DataLoader
import voc12.dataloader
from misc import torchutils, imutils
def _work(process_id, infer_dataset, args):
databin = infer_dataset[process_id]
infer_data_loader = DataLoader(databin, shuffle=... |
# coding=utf-8
from __future__ import absolute_import
from wecubek8s.apps.openapi import route
|
# -*- coding: utf-8 -*-
"""
Created on Fri Mar 29 14:02:59 2019
@author: darfyma
"""
import vrep
import sys
import numpy as np
import skfuzzy as fuzz
from skfuzzy import control as ctrl
#-------------------------Fuzzy Setup------------------------------------------
lf = np.arange(0,1, 0.001)
left = ctrl.Antecedent... |
#
# PySNMP MIB module STN-ATM-VPN-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/STN-ATM-VPN-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:03:27 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from decimal import Decimal
from collections import defaultdict
import sys
sys.stdin = open('input.txt')
class KnapsackItem:
"""Один предмет в рюкзаке"""
def __init__(self, name, size, price):
# Наименование предмета
self.name = name
# Дл... |
from .routers import NoMatchFound, NoRouteFound, Prefix, Router, Routes
from .routes import BaseRoute, HttpRoute, SocketRoute
__all__ = [
"Router",
"Routes",
"BaseRoute",
"HttpRoute",
"SocketRoute",
"Prefix",
"NoMatchFound",
"NoRouteFound",
]
|
from typing import Optional
from dataclasses import dataclass
from .Crypto import Crypto
from .ManageInvoiceOperation import ManageInvoiceOperation
@dataclass
class InvoiceOperation:
"""Invoice operation of the request
:param index: Sequence number of the invoice within the request
:param invoice_operati... |
from time import sleep
import random
print(f'{30*"-"}\n{"JOGO NA MEGA SENA":^30}\n{30*"-"}')
nj = int(input('Quantos jogos você quer que eu sorteie? '))
print(f'{" SORTEANDO ":=>15}{nj}{" JOGOS ":=<15}')
lista = []
for n in range(0, nj):
num = list(range(1, 61))
# noinspection PyRedeclaration
n = list()
... |
# -*- coding: utf-8 -*-
class EmotivOutputTask(object):
def __init__(self, received=False, decrypted=False, data=None):
self.packet_received = received
self.packet_decrypted = decrypted
self.packet_data = data
class EmotivReaderTask(object):
def __init__(self, data, timestamp):
... |
"""根据 PRS 协议组合 block data, 并且使用 privateKey 进行签名"""
import prs_utility
with open(__file__) as fp:
content = fp.read()
data = {
'file_hash': prs_utility.keccak256(text=content),
}
key_pair = prs_utility.create_key_pair()
private_key = key_pair['privateKey']
sig = prs_utility.sign_block_data(data, private_key)
p... |
from datetime import timedelta
from django.db.models import Max
from django.utils.timezone import now
from preferences import preferences
from rest_framework import serializers
from bikesharing.models import Bike, Station
class GbfsFreeBikeStatusSerializer(serializers.HyperlinkedModelSerializer):
bike_id = seri... |
import frappe
def execute():
frappe.reload_doc('core', 'doctype', 'system_settings')
frappe.db.sql("update `tabSystem Settings` set allow_error_traceback=1")
|
"""
Test the Frog lemmatizer functions and task.
"""
import logging
import socket
from unittest import SkipTest
from nose.tools import assert_equal, assert_not_equal
from xtas.tasks._frog import (FROG_HOST, FROG_PORT, call_frog, frog_to_saf,
parse_frog)
def _check_frog():
s = sock... |
""" core mixin for temporal Models """
import sqlalchemy.ext.declarative as declarative
import sqlalchemy.orm as orm
from temporal_sqlalchemy import bases, clock
class TemporalModel(bases.Clocked):
""" Mixin Class the enable temporal history for a sqlalchemy model """
@declarative.declared_attr
def __ma... |
def GenCPPProperty(type, name):
assert(name.startswith('m_'))
# if name.startswith('m_'):
# name = name[2:]
pretty_name = name[2:]
# print '+++++++++++++'
# print('')
if type in ('int', 'float', 'bool', 'uint32_t', 'bool') or type.endswith('*'):
# print '==== v1'
print('{0} ... |
#!/usr/bin/env python
from distutils.core import setup
setup(name='pystatplottools',
version='0.1',
description='Python modules for performing simple statistics and plotting routines.',
author='Lukas Kades',
author_email='lukaskades@googlemail.com',
url='https://github.com/statphysandml/... |
import random
import sys
import cryptomath_module as cryptomath
SYMBOLS = (
r""" !"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\]^_`"""
r"""abcdefghijklmnopqrstuvwxyz{|}~"""
)
def main():
"""
>>> key = get_random_key()
>>> msg = "This is a test!"
>>> decrypt_message(key, encrypt... |
#!/usr/bin/env python
# coding: utf-8
from PyQt5.QtWidgets import *
import sys
from window import MainWindow, TurtleWindow
import rospy
if __name__ == '__main__':
rospy.init_node('turtle_ctrl_node')
# Qt ui 部分
app = QApplication(sys.argv)
# 窗体展示
window = TurtleWindow()
window.show()
sy... |
#!/usr/bin/env python3
import abc
import argparse
import collections
import numbers
import os.path
import re
import sys
import token
import tokenize
import fett
from typing import Any, Dict, List, Set, Union, Optional
def stderr(*args) -> None:
sys.stderr.write('{}\n'.format(' '.join(str(element) for element in... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.