content stringlengths 5 1.05M |
|---|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
from django.contrib.contenttypes.models import ContentType
from django.contrib.auth.models import Permission
class MyPermission(models.Model):
'''
自定义权限表
'''
parent = models.ForeignKey('self', null=True, blank=... |
import sys
from os.path import join, dirname
sys.path.append(join(dirname(__file__), '../src'))
|
# -*- coding: utf-8 -*-
# Generated by Django 1.10.2 on 2017-07-07 21:00
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('nominations', '0028_auto_20170707_2054'),
]
operations = [
migrations.AddFi... |
import torch.nn as nn
from ..abs import BridgeBase
class Bridge(BridgeBase):
r"""
Bridge the connection between encoder and decoder.
"""
def __init__(self, args):
super().__init__(args)
self.num_layers = args.num_layers
self.dec_init = nn.Sequential(nn.Linear(args.hidden_size... |
# Copyright © 2021, United States Government, as represented by the Administrator of the
# National Aeronautics and Space Administration. All rights reserved.
#
# The “ISAAC - Integrated System for Autonomous and Adaptive Caretaking platform” software is
# licensed under the Apache License, Version 2.0 (the "License"... |
# 鸡尾酒排序算法的python实现
def cocktail_shaker_sort(a):
for i in range(len(a)-1, 0, -1):
swapped = False
for j in range(i, 0, -1):
if a[j] < a[j-1]:
a[j], a[j-1] = a[j-1], a[j]
swapped = True
for j in range(i):
if a[j] > a[j+1]:
... |
from django.shortcuts import render
from django.http import Http404
from .models import Sponser
from .serializers import SponserSerializer
# rest dependencies import
from rest_framework import status
from rest_framework.views import APIView
from rest_framework.response import Response
class AllSponsers(APIView):
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import re
from separador_silabico import *
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Marca a silaba tonica da palavra, com base nos dados de separacao silabica '
' Chamada: marcaSilTonica(palavr... |
from console import Console
from action import Action
from userLoginAction import UserLoginAction
from userRegisterAction import UserRegisterAction
class MainAction(Action):
def FollowInstructions(self, info = None):
Console.Clear()
print("""********************************\n
Acciones disponible... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# This software and supporting documentation are distributed by
# Institut Federatif de Recherche 49
# CEA/NeuroSpin, Batiment 145,
# 91191 Gif-sur-Yvette cedex
# France
#
# This software is governed by the CeCILL license version 2 under
# French law ... |
import FWCore.ParameterSet.Config as cms
class RandomRunSource (cms.Source):
"""The class is a Source whose run is chosen randomly. This initializes identically to a cms.Source
and after being initialized the run number distribution is set by calling 'setRunDistribution'.
"""
def setRunDistribution(se... |
#!/usr/bin/env python3
import fileinput
def parse_rest(rest):
if "no other bags" in rest:
return []
bagses = rest.split(", ")
ret = []
for one_bag in bagses:
tokens = one_bag.split(" ")
ret.append((" ".join(tokens[1:-1]), int(tokens[0])))
return ret
def parse():
... |
from django.conf.urls import patterns, url
from .views import CurrentLocation, PastLocations
urlpatterns = patterns('',
url(r'^current_location/$', CurrentLocation.as_view(), name="current_location"),
url(r'^past_locations/$', PastLocations.as_view(), name="past_locations... |
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
@File : 396.py
@Contact : huanghoward@foxmail.com
@Modify Time : 2022/4/22 10:42
------------
"""
from functools import reduce
from typing import List
class Solution:
def maxRotateFunction(self, nums: List[int]) -> int:
current = su... |
from django.template import Library
register = Library()
@register.filter
def noop(variable, param=None):
return variable
|
from setuptools import setup
setup(
name='cached-collections',
version='0.1.0',
description=('Synchronized between processes in-memory cache for storing '
'frequently used data'),
author='Vladimir Magamedov',
author_email='vladimir@magamedov.com',
url='https://github.com/vmagam... |
def look_up_word_value(words):
"""
---------------------------------------------------------------------
DESCRIPTION
Translates the word (string) array into a floating-point value array.
---------------------------------------------------------------------
PARAMETERS
words (string array): Th... |
#!/usr/bin/env python
# This script can be run on the core server to upgrade the riak cluster to support workflows
import riak
client = riak.RiakClient(protocol='pbc', nodes=[{'host': 'localhost'}])
client.resolver = riak.resolver.last_written_resolver
with open('/opt/al/pkg/assemblyline/al/install/etc/riak/schema/w... |
import RPi.GPIO as IO
import time
import serial
import CodeReader from QrTest
#--------------UART init-------------------------------------
ser = serial.Serial(
port='/dev/ttyAMA0',
baudrate = 9600,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBI... |
# ----------------------------------------------------------------------
# DNSZone.type field
# ----------------------------------------------------------------------
# Copyright (C) 2007-2019 The NOC Project
# See LICENSE for details
# ----------------------------------------------------------------------
# Third-par... |
from flask import Flask, jsonify, render_template, request
from main import predict
import pickle
HOST = '127.0.0.1'
PORT = 5000
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/predict-digit', methods=['POST'])
def digit():
# Take the image and preproc... |
# master morfless libraries from libraries import
from libraries import constants
from libraries import globals
from libraries import schematics
from libraries import header
from libraries import footer
from libraries import main
from libraries import before_after
from libraries import html_elements
from libraries impo... |
from hiword.extractor import KeywordsExtractor
from hiword.extractor import extract_keywords
__version__ = '0.3.1'
__all__ = [
'KeywordsExtractor',
'extract_keywords',
]
|
# 返回强度限制,即图片dtype的(最小,最大)元组。 |
"""
test score_mgr
"""
import datetime
from django.test import TransactionTestCase
from django.contrib.auth.models import User
from apps.managers.score_mgr import score_mgr
from apps.managers.team_mgr.models import Group, Team
from apps.managers.score_mgr.models import ScoreboardEntry, PointsTransaction
from apps.util... |
# Multiples of 3 and 5
# Problem 1
# If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these
# multiples is 23.
# Find the sum of all the multiples of 3 or 5 below 1000.
import math
import itertools
def is_divisible_by_one(x, factors):
for factor in facto... |
import os
from fontTools.misc.py23 import basestring
from fontParts.base.errors import FontPartsError
from fontParts.base.base import dynamicProperty, InterpolationMixin
from fontParts.base.layer import _BaseGlyphVendor
from fontParts.base import normalizers
from fontParts.base.compatibility import FontCompatibilityRep... |
import re
from mimetypes import guess_type
from django.urls import reverse
from markupsafe import Markup
from maps.model.type import Type
def link(entity):
""" Returning an HTML link for an entity."""
url = reverse(entity._meta.db_table.replace('_', ':') + '-detail', kwargs={'pk': entity.id})
return Mar... |
#!/usr/bin/env python3
import itertools
def increment(_):
return 1
def strange_jump(offset):
return -1 if offset > 2 else 1
def cpu_states(initial_state, increase_func, at=0):
pos = at
# Give this man a medal -- make a COPY of input data.
# <https://www.reddit.com/r/adventofcode/comments/7hr... |
import datetime as dt
from functools import reduce
from itertools import groupby
from django import forms
from django.db.models import Q
from django.shortcuts import render
from django.utils.html import format_html, format_html_join
from django.utils.text import capfirst
from django.utils.translation import gettext_la... |
import ca_certs_locater
import mock
import unittest
class TestLocator(unittest.TestCase):
@ mock.patch('os.path.exists')
def test_linux_exists(self, exists):
# If the file exists, return it
exists.return_value = True
fn = ca_certs_locater.get()
self.assertEqual(fn, ca_certs... |
# This is the file that implements a flask server to do inferences. It's the file that you will modify
# to implement the prediction for your own algorithm.
from __future__ import print_function
import os
import sys
import stat
import json
import shutil
import flask
from flask import Flask, jsonify, request, make_res... |
from django.apps import AppConfig
class FCMDevicesConfig(AppConfig):
name = "fcm_devices"
verbose_name = "FCM Devices"
|
import os
from textwrap import dedent
import os.path
import shutil
try:
import unittest2 as unittest
except ImportError:
import unittest
from rope.base.exceptions import RopeError, ResourceNotFoundError
from rope.base.fscommands import FileSystemCommands
from rope.base.libutils import path_to_resource
from rop... |
import re
YT_PATTERN = r'((youtu\.be/|(www\.)?youtube\.com/watch\?v=)(\w{11}))'
def parse_links(text: str) -> list:
matches = re.findall(YT_PATTERN, text)
return list(map(lambda match: match[0], matches))
|
"""
Aggregation model
:author: Angelo Cutaia
:copyright: Copyright 2021, LINKS Foundation
:version: 1.0.0
..
Copyright 2021 LINKS 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 L... |
from kombu import Queue
QUEUES = { # RabbitMQ Queue definitions, they'll be declared at gunicorn start time
"bot_events": Queue("bot_events", durable=True)
}
|
"""
Load configuration data from environment variables.
"""
import os
import functools
from urllib.parse import urljoin
@functools.lru_cache(maxsize=1)
def get_config():
"""Load environment configuration data."""
spec_path = os.environ.get('SPEC_PATH', '/spec') # /spec
spec_url = 'https://api.github.com... |
from TTS.text2speech import tts_class
from multiprocessing import Process
import faiss
import time
import sqlite3
import csv
import random
import copy
import tensorflow_hub as hub
import tensorflow_text
import math
import numpy as np
import pickle
from Retriever.Retrieve import retrieve
import Utils.functions as utils
... |
#
# (C) Copyright 2003-2010 Jacek Konieczny <jajcus@jajcus.net>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License Version
# 2.1 as published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be u... |
from colormath.color_objects import sRGBColor, LabColor
import colormath.color_conversions as color_conversions
import colormath.color_diff as color_diff
import random
class Color(object):
'''
A wrapper of LabColor. Originally designed as a subclass of LabColor, but implemented as a wrapper
because conver... |
def prima(parola):
return parola[0]
def ultima(parola):
return parola[-1]
def mezzo(parola):
return parola[1:-1]
def palindromo(parola):
if len(parola) <= 1:
return True
if prima(parola) != ultima(parola):
return False
return palidromo(mezzo(parola))
# ho aggiunto una stringa ... |
#!/usr/bin/env python
'''
hackflight_companion.py : Companion-board Python code. Runs in
Python2 instead of Python3, so we can install OpenCV without
major hassles.
This file is part of Hackflight.
Hackflight is free software: you can redistribute it and/or modify
it under the terms of the GNU Ge... |
import ast
import json
p = "{\'voter1': \"{\'a\':1, \'b\':2}\", \'voter2\': \"{\'a\':0, \'b\':1}\"}"
p1 = ast.literal_eval(p)
p2 = {}
for k, v in p1.items():
p2[k] = ast.literal_eval(v)
print(p2)
print('json: ', json.dumps(p2))
print(p)
print(str(p2)) |
"""
Copyright Matt DeMartino (Stravajiaxen)
Licensed under MIT License -- do whatever you want with this, just don't sue me!
This code attempts to solve Project Euler (projecteuler.net) Problem #18 Maximum path sum I
By starting at the top of the triangle below and moving to adjacent numbers on the row below, the max... |
"""
AUTHOR - Atharva Deshpande
GITHUB - https://github.com/AtharvaD11
QUESTION LINK - https://www.codechef.com/LRNDSA01/problems/MULTHREE
"""
HINT - Please learn Modulo Arithmetic first.
***********************************************
for _ in range(int(input())):
k,d0,d1 = map(int,input().spl... |
from secml.optim.optimizers.tests import COptimizerTestCases
from secml.optim.optimizers import COptimizerPGD
class TestCOptimizerPGD(COptimizerTestCases):
"""Unittests for COptimizerPGDLS."""
def test_minimize_3h_camel(self):
"""Test for COptimizer.minimize() method on 3h-camel fun."""
opt_... |
# -*- coding: utf-8 -*-
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""
RegSeg2
"""
from datetime import date
from ._version import get_versions
__version__ = get_versions()['version']
del get_versions
PACKAGE_NAME = 'regseg'
__author__ = 'Oscar E... |
# Copyright 2020 Toyota Research Institute. All rights reserved.
import MinkowskiEngine as ME
import torch.nn as nn
from packnet_sfm.networks.layers.minkowski import \
sparsify_depth, densify_features, densify_add_features_unc, map_add_features
class MinkConv2D(nn.Module):
"""
Minkowski Convolutional B... |
from PyQt5.QtCore import pyqtSignal, QThread
__all__ = ['LoadingThread']
class LoadingThread(QThread):
"""This is base class of thread for using with LoadingWrapper
The idea is to move some heavy operations to a special thread and show
progress on the LoadingDialog.
This actually decreases perfomanc... |
# coding=utf-8
"""
DBWriter.py
Describes the class that runs as a separate process and writes data to the database as it is pushed into a global queue.
"""
import multiprocessing
import configparser
import psycopg2
from typing import List, Tuple
from websites import ExtractedArticle
from psycopg2 import sql
class D... |
#!/usr/bin/env python3
'''
Polychora: Python animation of uniform polychora in 4 and higher dimensions
Author: M. Patrick Kelly
Email: patrickyunen@gmail.com
Last Updated: 12-9-2020
'''
from itertools import product, permutations
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import L... |
# Generated by Django 3.0.4 on 2020-03-26 03:57
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('homechef', '0003_vendor_food_items'),
]
operations = [
migrations.CreateModel(
name='Ingredients',
fields=[
... |
# @Author: Jacob A Rose
# @Date: Tue, March 31st 2020, 1:24 am
# @Email: jacobrose@brown.edu
# @Filename: __init__.py
'''
pyleaves/pyleaves/base/__init__.py
base submodule of the pyleaves package
contains base classes for use throughout other submodules in pyleaves
'''
# import pdb;pdb.set_trace();print(__file... |
#!/usr/bin/env python3
w, a, b = map(int,input().split())
s = abs(a-b)
print([0, s-w][s>w]) |
from apps.workflow.models import CustomField
from service.base_service import BaseService
from service.common.log_service import auto_log
class WorkflowCustomFieldService(BaseService):
def __init__(self):
pass
@classmethod
@auto_log
def get_workflow_custom_field(cls, workflow_id):
"""... |
import ctypes as C
import os
from typing import Final, Sequence, TypeVar
from astruct import typed_struct
from astruct.type_hints import *
from utils import CountedTable, ro_cached_property
from .classoritem import ClassOrItemTable
from .dungeoncategory import DungeonCategoryTable
from .fusioncompat import FusionComp... |
# Generated by Django 3.0.3 on 2020-04-12 04:34
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('customers', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='customer',
name='tel',
... |
import filecmp
import pytest
from sequana.freebayes_vcf_filter import VCF_freebayes
from . import test_dir
sharedir = f"{test_dir}/data/vcf/"
def test_vcf_filter(tmpdir):
path = tmpdir.mkdir("temp")
vcf_output_expected = f"{sharedir}/JB409847.expected.vcf"
v = VCF_freebayes(f"{sharedir}/JB409847.vcf")
... |
#!/usr/bin/env python
from distutils.core import setup
setup(name='estool',
version='1.0',
description='Implementation of various Evolution Strategies',
py_modules=['config', 'es', 'env', 'model', 'train'],
)
|
import streamlit as st
import altair as alt
import pandas as pd
import json
import numpy as np
from pathlib import Path
from autobrat.classifier import Model
from autobrat.data import load_training_data
from scripts.score import subtaskA, subtaskB, compute_metrics
from scripts.utils import Collection
def get_corpora... |
import resources
from dodge.game.state import GameState, GameStatus
from dodge.game.runner import GameRunner
from dodge.config import Config
from dodge.level import SillyLevelBuilder
import dodge.ui as ui
class Game(object):
def __init__(self):
self.config = Config(resources.config)
self.window = ... |
#!/usr/bin/env python3
""" Script for addressing CARRY4 output congestion in elaborated netlists.
Usage:
python3 fix_carry.py < input-netlist-json > output-netlist-json
Description:
In the 7-series SLICEL (and SLICEM) sites, there can be output congestion
if both the CO and O of the CARRY4 are used. Thi... |
# Why does this file exist, and why not put this in `__main__`?
#
# You might be tempted to import things from `__main__` later,
# but that will cause problems: the code will get executed twice:
#
# - When you run `python -m pawabot` python will execute
# `__main__.py` as a script. That means there won't be any
# `... |
import torch
import torch.nn as nn
from torch.autograd import Function
import padding._C as _C
class PaddingFunction(Function):
@staticmethod
def forward(ctx, x, pad_h=1, pad_w=0, flag=False):
ctx.constant = pad_h, pad_w, flag
if not x.is_contiguous():
x = x.contiguous()
if... |
import tensorflow as tf # tensorflow import
import numpy as np # python에서 벡터, 행렬 등 수치 연산을 수행하는 선형대수 라이브러리
import skimage.data # skimage는 이미지 처리하기 위한 파이썬 라이브러리
from PIL import Image, ImageDraw, ImageFont # PIL은 파이썬 인터프리터에 다양한 이미지 처리와 그래픽 기능을 제공하는 라이브러리
import math # 수학 관련 함수들이 들어있는 라이브러리
from tensorflow.python.platform ... |
"""
==================================
Input and output (:mod:`pyrad.io`)
==================================
.. currentmodule:: pyrad.io
Functions to read and write data and configuration files.
Reading configuration files
===========================
.. autosummary::
:toctree: generated/
read_config
Readi... |
import numpy as np
import os
from PySide import QtGui, QtCore
import sharppy.sharptab as tab
import sharppy.databases.inset_data as inset_data
from sharppy.sharptab.constants import *
## routine written by Kelton Halbert and Greg Blumberg
## keltonhalbert@ou.edu and wblumberg@ou.edu
__all__ = ['backgroundSTPEF', 'plo... |
import json
import re
from random import choice
from textwrap import wrap
from typing import Dict, List, Tuple, Union
from PIL import Image, ImageDraw, ImageFont
from .type_interfaces import GraphicInfo, GraphicSettings
from .validation import __validate_text_loaded
def __load_quotes_txt(file_path: str) -> List[Tuple... |
#!user/bin/env python3
__author__ = "tooraj_jahangiri"
__email__ = "toorajjahangiri@gmail.com"
from base64 import b64encode, b64decode
from pointerdic import PointerDic
from time import perf_counter
from random import choice
def main() -> int:
"""
PointerDic Main prg: [check(class): ./pointerdi... |
from flask import abort, Blueprint, g, make_response, render_template
from portfolio.minify import render_minified
from portfolio.projects import Project
from portfolio.sitemap import Sitemap
site = Blueprint('site', __name__, static_folder='static')
projects = Project()
# home
@site.route('/')
def index():
retu... |
from app import app, command_system
from app.scheduledb import ScheduleDB
def auto_posting_off(uid, key, arg=""):
# Если пользователя нет в базе, то ему выведет предложение зарегистрироваться
try:
with ScheduleDB(app.config) as db:
user = db.find_user(uid)
if not user or user[0] ==... |
"""Filters for Kerneladmin."""
def gvariant(lst):
"""Turn list of strings to gvariant list."""
assert isinstance(lst, list), "{} is not a list".format(lst)
content = ", ".join(
"'{}'".format(l) for l in lst
)
return '[{}]'.format(content)
class FilterModule:
"""FilterModule."""
... |
#
# PySNMP MIB module DLINK-3100-MIR-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DLINK-3100-MIR-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 18:33:44 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, ... |
import re
from bs4 import BeautifulSoup
from LimeSoup.lime_soup import Soup, RuleIngredient
from LimeSoup.parser.parser_paper_wiley import ParserPaper
__author__ = 'Zach Jensen'
__maintainer__ = ''
__email__ = 'zjensen@mit.edu'
__version__ = '0.3.0'
class WileyRemoveTagsSmallSub(RuleIngredient):
@staticmethod... |
def hw1(inp, out):
f = open(inp, 'r')
l = open(out, 'w')
out_arr = [[0 for i in range(0, 123)] for i in range(len(f))]
inp_arr = []
for line in f:
inp_arr.append(line)
for i in range(0,len(f)):
for j in inp_arr[i]:
out_arr[i][ord(j)] += 1
flag = True
for j in range(97, 123):
if (out_arr[i][j] < 1):
... |
import numpy as np
import math
import trimesh
import open3d as o3d
def reconstruct_surface(input_point_pos):
point_cloud = o3d.geometry.PointCloud()
point_cloud.points = o3d.utility.Vector3dVector(input_point_pos)
point_cloud.estimate_normals()
point_cloud.orient_normals_consistent_tangent_plane(10)
... |
# coding: utf-8
from . import views
from django.conf.urls import url
urlpatterns = [
url(
r'^create/(?P<app_label>\w+)/(?P<model>\w+)/(?P<obj_id>\d+)/$',
views.ExampleCreateView.as_view(),
name='create'
),
url(
r'^update/(?P<pk>\d+)/$',
views.ExampleUpdateView.as_... |
import os
from boa_test.tests.boa_test import BoaTest
from boa.compiler import Compiler
from neo.Prompt.Commands.BuildNRun import TestBuild
from neo.VM.ExecutionEngine import ExecutionEngine
from mock import patch
from neo.Settings import settings
from logging import DEBUG, INFO
import binascii
class StringIn(str):
... |
from app.logic_gates.gates import Gates
gates = {
1: 'not',
2: 'or',
3: 'and',
4: 'nor',
5: 'nand',
6: 'xor'
}
class LogicGates:
def __init__(self) -> None:
self.get_option()
self.get_value()
self.result()
def show_gates(self) -> None:
for key in gates... |
from __future__ import print_function
import os
import sys
import math
import pickle
import boto3
import os
import numpy as np
import kg
import pandas as pd
# from tqdm import tqdm
import time
import argparse
import json
import logging
import re
import dglke
# tqdm.pandas()
# pandarallel.initialize(progress_bar=True)
... |
# -*- coding: utf-8 -*-
# pragma pylint: disable=unused-argument, no-self-use
# (c) Copyright IBM Corp. 2010, 2019. All Rights Reserved.
"""Function implementation"""
import logging
from resilient_circuits import ResilientComponent, function, handler, StatusMessage, FunctionResult, FunctionError
from fn_cb_protectio... |
import argparse
import plotly.express as px
import plotly.graph_objects as go
import pandas as pd
import numpy as np # won't need this when data on 3rd dose for 12-17 year olds becomes available
import os
from vaccine_dataprep_Swedentots import (
first_two_vacc_dose_lan,
third_vacc_dose_lan,
fourth_vacc_d... |
class DatoolsError(Exception):
pass
|
"Legacy code. To be updated or depreciated."
from pyrvea.EAs.RVEA import RVEA
from pyrvea.OtherTools.ReferenceVectors import ReferenceVectors
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from pyrvea.Population.Population import Population
class slowRVEA(RVEA):
"""RVEA variant that impliments slow refe... |
from hashlib import sha256
from http import HTTPStatus
import grequests
import pytest
from eth_utils import decode_hex, encode_hex, to_bytes, to_checksum_address, to_hex
from raiden.api.rest import APIServer
from raiden.constants import UINT64_MAX
from raiden.settings import DEFAULT_NUMBER_OF_BLOCK_CONFIRMATIONS
from... |
import numpy as np
from itertools import combinations
from collections import OrderedDict
from module.network_trainer import NetworkTrainer # Version 'pure Python"
# from module.c_network_trainer import NetworkTrainer
from module.save import BackUp, Database
from multiprocessing import Pool
from time import time
from ... |
# -*- coding: utf-8 -*-
"""
Helper functions for the tasks app: calculate_reputation_gain and
give_reputation_reward.
"""
from .models import Profile, Task
from django.db.models import F
def calculate_reputation_gain(task):
"""
Calculate the reputation gained by completing a task. Currently based on
dif... |
from flask import Flask
from ecommerce_api.ext import configuration
def create_app(*args, **config):
app = Flask(__name__)
configuration.init_app(app, **config)
configuration.load_extensions(app)
configuration.load_blueprints(app)
configuration.load_middlewares(app)
return app
|
from pathlib import Path
import json
from .Service import *
from nonebot import export, get_driver, on_command
from nonebot.rule import to_me
from nonebot.log import logger
from nonebot.typing import T_State
from nonebot.adapters.cqhttp import Bot, Event
# Initialization
driver = get_driver()
export().Service = Servi... |
from elasticsearch import Elasticsearch
def main():
index_name = 'squad2.0'
print("Creating index")
client = Elasticsearch()
client.indices.delete(index=index_name, ignore=[404])
with open("squad_questions_mapping.json") as index_file:
source = index_file.read().strip()
client.indi... |
import matplotlib.pyplot as plt
from matplotlib import patches
def modeling(node_list: list, row_list: list, net_list: list):
figure = plt.figure()
figure.suptitle("modeling")
ax = figure.add_subplot()
row_number = 1
colors = ['#caa24e', '#caa24e', '#5a3e42', '#b35031', '#5a3e42', '#6e6e64', '#8f... |
from pathlib import Path
# Absolute path
# E:\04-PROGRAMMING\Python
# path = Path("ecommerce")
# path = Path("ecommerce1")
# path = Path("emails")
# # print(path.mkdir())
# print(path.rmdir())
# print(path.exists())
path = Path()
# for file in path.glob('*.py'): # Search a file using a pattern
... |
from ast import literal_eval
import warnings
class AttrDict(dict):
def __init__(self, **kwargs):
super(AttrDict, self).__init__(**kwargs)
self.update(kwargs)
@staticmethod
def from_dict(dict):
ad = AttrDict()
ad.update(dict)
return ad
def __setitem__(self, key... |
import os
import re
from time import sleep
from bs4 import BeautifulSoup
import pandas as pd
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
# Webdriver options; set to headless
options = webdriver.ChromeOptions()
options.add_argument("--headless")
driver = webdriver.Chrome(Chr... |
from configs import EXP_CONFIGS
import xml.etree.cElementTree as ET
from xml.etree.ElementTree import dump
from lxml import etree as ET
import os
E = ET.Element
def indent(elem, level=0):
i = "\n " + level*" "
if len(elem):
if not elem.text or not elem.text.strip():
elem.text = i + ""
... |
#!/usr/bin/python3
""" 12-main """
from models.rectangle import Rectangle
if __name__ == "__main__":
r1 = Rectangle(10, 2, 1, 9)
print(r1)
r1_dictionary = r1.to_dictionary()
print(r1_dictionary)
print(type(r1_dictionary))
r2 = Rectangle(1, 1)
print(r2)
r2.update(**r1_dictionary)
p... |
# -*- coding: utf-8 -*-
name = 'jemalloc'
version = '4.5.0'
def commands():
env.LD_LIBRARY_PATH.append('{root}/lib/')
appendenv('PATH', '{root}/bin/')
|
from subprocess import call
from config import Const
class Windows(object):
"""
This script builds a windows autoinstall image in the /kubam directory.
Build the autoinstall image and return error code with a message.
"""
@staticmethod
def build_boot_image(node, template, net_template):
... |
#!/usr/bin/env python
import json
# Import the necessary methods from "twitter" library
from twitter import Twitter, OAuth, TwitterHTTPError, TwitterStream
# Variables that contains the user credentials to access Twitter API
ACCESS_TOKEN = '######################################'
ACCESS_SECRET = '###################... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.