text stringlengths 1 927k |
|---|
from flask import jsonify, request, g, current_app, Response
from . import api
@api.route("/provider", methods=["GET"])
def get_provider():
return jsonify(provider=current_app.config["LIGHT_PROVIDER"])
@api.route("/lights/<int:lid>/color", methods=["POST"])
def set_color(lid):
params = request.json
red... |
from __future__ import print_function
from builtins import range, object
import inspect
import six
class _ConfigureComponent(object):
"""Denotes a class that can be used by the Processes class"""
def _isTaskComponent(self):
return False
class PrintOptions(object):
def __init__(self, indent = 0, de... |
import re
import gettext
_ = gettext.gettext
from BeautifulSoup import BeautifulSoup, Declaration, Comment, Tag
from html5lib.constants import namespaces
import _base
class TreeWalker(_base.NonRecursiveTreeWalker):
doctype_regexp = re.compile(
r'(?P<name>[^\s]*)(\s*PUBLIC\s*"(?P<publicId>.*)"\s*"(?P<syste... |
# Copyright (c) 2020 PaddlePaddle Authors. 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 by applic... |
import _plotly_utils.basevalidators
class CustomdataValidator(_plotly_utils.basevalidators.DataArrayValidator):
def __init__(
self, plotly_name="customdata", parent_name="choroplethmapbox", **kwargs
):
super(CustomdataValidator, self).__init__(
plotly_name=plotly_name,
... |
# simple plot of a larger file
from py3plex.visualization.multilayer import hairball_plot, plt
from py3plex.visualization.colors import colors_default
from py3plex.core import multinet
from py3plex.wrappers import train_node2vec_embedding
from py3plex.visualization.embedding_visualization import embedding_tools
from py... |
# exported from PySB model 'model'
from pysb import Model, Monomer, Parameter, Expression, Compartment, Rule, Observable, Initial, MatchOnce, Annotation, ANY, WILD
Model()
Monomer('Ligand', ['Receptor'])
Monomer('ParpU', ['C3A'])
Monomer('C8A', ['BidU', 'C3pro'])
Monomer('SmacM', ['BaxA'])
Monomer('BaxM', ['BidM', '... |
from hashlib import sha512
from django_filters.rest_framework import DjangoFilterBackend
from drf_yasg.utils import swagger_auto_schema
from rest_framework import status, viewsets
from rest_framework.decorators import action
from rest_framework.pagination import LimitOffsetPagination
from rest_framework.response impor... |
from a10sdk.common.A10BaseClass import A10BaseClass
class Nat46Stateless(A10BaseClass):
""" :param static_dest_mapping_list: {"minItems": 1, "items": {"type": "static-dest-mapping"}, "uniqueItems": true, "array": [{"required": ["v4-address", "v6-address"], "properties": {"count": {"platform-specific-range... |
def __bootstrap__():
global __bootstrap__, __loader__, __file__
import sys, pkg_resources, imp
__file__ = pkg_resources.resource_filename(__name__, '_imagingmorph.pyd')
__loader__ = None; del __bootstrap__, __loader__
imp.load_dynamic(__name__,__file__)
__bootstrap__() |
#! /usr/bin/env python
import tensorflow as tf
import os
import time
from text_cnn import TextCNN
from utils.feature_extraction import load_datasets, DataConfig, Flags
from utils.general_utils import print_confusion_matrix
def highlight_string(temp):
print 80 * "="
print temp
print 80 * "="
def main(fl... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-01-14 22:14
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('frontend', '0001_initial'),
]
operations = [
migrations.AlterModelOptions(
... |
import time
import os
import numpy as np
import pybullet as p
import pybullet_data
import pybullet_utils.bullet_client as bc
import pygame
os.environ['PYGAME_HIDE_SUPPORT_PROMPT'] = "hide"
import pymunk
import pymunk.pygame_util
# from pygame.color import THECOLORS
# from pymunk.vec2d import Vec2d
from spike_swarm_sim.... |
##
# Implement idea 2: multi-chromosome version
##
import argparse
parser = argparse.ArgumentParser(prog='impute_otf_multi_chr.py', description='''
Impute parental origin of haplotypes and observed phenotypes.
It takes preloaded phenotypes, covariates, and genotypes
(generated by impute_otf_preload.py)
''... |
# Copyright (c) OpenMMLab. All rights reserved.
import copy
import warnings
from abc import ABCMeta
from collections import defaultdict
from logging import FileHandler
import torch.nn as nn
from mmcv.runner.dist_utils import master_only
from mmcv.utils.logging import get_logger, logger_initialized, print_log
class ... |
ZULIP_VERSION = "1.6.0+git"
PROVISION_VERSION = '6.0' |
# This file is part of Indico.
# Copyright (C) 2002 - 2020 CERN
#
# Indico is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see the
# LICENSE file for more details.
from functools import wraps
from itertools import groupby, islice, zip_longest
def group_list(data, key=... |
from invoke import Collection, Task, task
import inspect
## Utilities
# these helper functions are for automatically listing all of the
# functions defined in the tasks module
def _is_mod_task(mod, func):
return issubclass(type(func), Task) and inspect.getmodule(func) == mod
def _get_functions(mod):
"""ge... |
# -*- coding: utf-8 -*-
"""
sphinx.builders.latex
~~~~~~~~~~~~~~~~~~~~~
LaTeX builder.
:copyright: Copyright 2007-2018 by the Sphinx team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import os
from os import path
from docutils import nodes
from docutils.frontend import OptionParser
... |
# Copyright 2013-2019 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Magma(CMakePackage):
"""The MAGMA project aims to develop a dense linear algebra library ... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Renderman Export functions
B{Project Name:} MakeHuman
B{Product Home Page:} U{http://www.makehuman.org/}
B{Code Home Page:} U{http://code.google.com/p/makehuman/}
B{Authors:} Marc Flerackers
B{Copyright(c):} MakeHuman Team 2001-2011
B{Licensing... |
import argparse
import math
import random
import sys
import os
import json
import numpy as np
import time
import torch
import arguments
import models
import models.data_utils.data_utils as data_utils
import models.model_utils as model_utils
from models.model import PlotCodeGenerator
def create_model(args, word_vocab... |
"""
This package wraps the [`os.pipe`](https://docs.python.org/3/library/os.html#os.pipe)
simplex communication pipe so it can be used as part of the non-blocking
[`asyncio`](https://docs.python.org/3/library/asyncio.html) event loop. A duplex pipe
is also provided, which allows reading and writing on both ends.
## Si... |
#
# Copyright (c) 2018 Wind River Systems, Inc.
#
# SPDX-License-Identifier: Apache-2.0
#
# -*- encoding: utf-8 -*-
#
from cgtsclient.common import base
CREATION_ATTRIBUTES = ['cert_path', 'public_path', 'tpm_path']
class Certificate(base.Resource):
def __repr__(self):
return "<certificate %s>" % self.... |
import os
from django.conf import settings
def get_image_file_path(instance, filename):
return os.path.join('photos', str(instance.id), filename) |
import pandas
def enlarge(n):
return n * 100
print("HELLO WORLD")
df = pandas.DataFrame({"state": ["CT", "CO", "CA", "TX"]})
print(df.head())
print("-----------------")
x = 5
print("NUMBER", x)
print("ENLARGED NUMBER", enlarge(x)) # invoking our function!! |
# 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... |
# coding: utf-8
"""
Kubernetes
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
The version of the OpenAPI document: v1.23.6
Generated by: https://openapi-generator.tech
"""
try:
from inspect import getfullargspec
except Im... |
import sys
from .data import REPLACEMENTS, COMBININGMARKS, SUBSUPERSCRIPTS
if __name__ == "__main__":
outname = 'ts_src/data.ts'
if len(sys.argv) == 2:
outname = sys.argv[1]
with open(outname, 'w') as f:
f.write('// autogenerated with python -m unicodeit.export_data\n\n')
f.writ... |
# Copyright (c) 2019 Graphcore Ltd. All rights reserved.
# coding=utf-8
def is_nearest_multiple(m, a, b):
"""
Replacement for m % b == 0 operator when variable is incremented by value other than one at each iteration.
m is assumed to be increased by a at each iteration. If not exactly divisible, this fun... |
import json
import sys
import csv
from enum import Enum
import requests
import os.path
import logging
import re
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from datetime import date
import ctypes as ct
logging.basicConfig(level=logging.INFO)
logging.getLogger("requests").setLevel(logging.W... |
# -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from gaebusiness.business import CommandExecutionException
from gaecookie.decorator import no_csrf
from gaepermission.decorator import login_not_required
from tekton.gae.middleware.json_middleware import JsonResponse
from chamado_app impor... |
import unittest
import mock
import numpy
import chainer
from chainer import cuda
from chainer import functions
from chainer import gradient_check
from chainer import testing
from chainer.testing import attr
@testing.parameterize(*testing.product({
'shape': [(3, 2), ()],
'dtype': [numpy.float16, numpy.float3... |
# coding: utf-8
import Tkinter as tk
from program_constants import *
from frontend.main import Main, Registro, DatosAlumnos, DatosProfesor, \
RegistroMateriaAlumno, RegistroMateriaProfesor
class Root(tk.Tk):
"""
Proporciona una ventana raiz acondicionada y reutilizable
"""
def __init__(self, ico... |
'''
Make me some salt!
'''
# Import python libs
import os
import sys
import logging
# Import salt libs
# We import log ASAP because we NEED to make sure that any logger instance salt
# instantiates is using salt.log.SaltLoggingClass
import salt.log
# the try block below bypasses an issue at build time so that modul... |
# =============================================================================
# Copyright (c) 2016, Cisco Systems
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# Redistributions of source c... |
# -*- coding: utf-8 -*-
"""vrmapiのMock
sphinx-apidocで撮る夫くんをビルドするときに,
WindowsのPythonエンジンにvrmapiがないのでModuleNotFoundErrorが出る。
エラーを回避するための最小限のコードを含むガワだけ用意しておくのが目的。
"""
import os
from unittest.mock import MagicMock
def LAYOUT():
return MagicMock()
def SYSTEM():
return VRMSystem()
def LOG(obj):
return
def C... |
import os
import platform
import pathlib
from pip._internal.network.session import PipSession
import pkg_resources
import setuptools
import sys
# from zeee_bot.common import logging
os.system("clear" if platform.system() == "Linux" else "cls")
print("Before Starting, Auto-installing Python dependencies")
if platform.... |
# BSD 3-Clause License; see https://github.com/scikit-hep/awkward-1.0/blob/main/LICENSE
from __future__ import absolute_import
import pytest # noqa: F401
import numpy as np # noqa: F401
import awkward as ak # noqa: F401
def test():
array = ak.Array(
[[{"a": 1, "b": [1, 2, 3]}], [{"a": 1, "b": [4, 5]}... |
from __future__ import unicode_literals
from frappe import _
def get_data():
return [
{
"label": _("Crm"),
"icon": "fa fa-star",
"items": [
{
"label":("Reservation"),
"type": "doctype",
"name": "Reservation",
"onboard": 1,
},
{
"type": "doctype",
"name": "Empl... |
###############################################################################
# Orkid SCONS Build System
# Copyright 2010, Michael T. Mayers
# email: michael@tweakoz.com
# The Orkid Build System is published under the GPL 2.0 license
# see http://www.gnu.org/licenses/gpl-2.0.html
#####################################... |
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.i18n import i18n_patterns
from django.conf.urls.static import static
from django.contrib.sitemaps.views import sitemap
from django.contrib.staticfiles.views import serve
from django.views.i18n import JavaScriptCatalog, set_... |
__author__ = 'rochacbruno' |
from django.shortcuts import render, redirect
from django.http import HttpResponse
from django.core.paginator import Paginator
from .models import Subject
import json
def index(request):
if request.method == "POST":
value = request.POST.get("subject_title")
subject_list = Subject.objects.filter(ti... |
"""
Pymunk 2
If Python and Arcade are installed, this example can be run from the command line with:
python -m arcade.examples.pymunk_joint_builder
"""
import arcade
import pymunk
import timeit
import math
import os
SCREEN_WIDTH = 1200
SCREEN_HEIGHT = 800
SCREEN_TITLE = "Pymunk 2 Example"
"""
Key bindings:
1 - Drag... |
# -*- coding: utf-8 -*-
u"""OAUTH support
:copyright: Copyright (c) 2016 RadiaSoft LLC. All Rights Reserved.
:license: http://www.apache.org/licenses/LICENSE-2.0.html
"""
from __future__ import absolute_import, division, print_function
from flask_sqlalchemy import SQLAlchemy
from pykern import pkconfig, pkcollection... |
# Ho many odd numbers at odd positions there are
user_input = input().split()
nums = enumerate([int(item) for item in user_input])
result = [(item_nr, item) for (item_nr, item) in nums if (item_nr % 2 != 0 and item % 2 != 0)]
for result_set in result:
print("Index %d -> %d" % (result_set[0], result_set[1])) |
"""Base classes for AT command errors.
"""
class AtException(Exception):
"""Base class for AT command exceptions."""
pass
class AtTimeout(AtException):
"""Indicates a timeout waiting for response."""
pass
class AtGnssTimeout(AtException):
"""Indicates a timeout waiting for a GNSS fix."""
pa... |
from instagrapi import Client
from instagrapi.types import StoryLink
import config
#Read user information from config
ID = config.userID
PW = config.userPW
#Login Processing
cl = Client()
cl.login(ID, PW)
#cl.login(ID, PW, verification_code="<2FA CODE HERE>") 2FA support
#cl.loginby_sessionid("token") use this for to... |
import os,sys
import pandas as pd
import numpy
from numpy import random
from numpy.random import shuffle
file = sys.argv[1]
df = pd.read_csv(file, sep=',', index_col = None, header = 0)
# rowname = df.index.tolist()
# row = shuffle(rowname)
# df.index = rowname
shuffle(df.ID)
df.to_csv(file, index=False, header=True,se... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
fro... |
# Time: O(m * n)
# Space: O(m)
import itertools
import collections
class Solution(object):
def findDiagonalOrder(self, nums):
"""
:type nums: List[List[int]]
:rtype: List[int]
"""
result, dq, col = [], collections.deque(), 0
for i in xrange(len(nums)+max(itertools... |
# -*- coding: utf-8 -*-
"""
:copyright: Copyright 2020-2022 Sphinx Confluence Builder Contributors (AUTHORS)
:license: BSD-2-Clause (LICENSE)
"""
from __future__ import unicode_literals
from tests.lib.testcase import ConfluenceTestCase
import io
import os
class TestConfluenceConfigPrevNext(ConfluenceTestCase):
@... |
import numpy as np
import pickle
import torch
from torch.utils.data import Dataset
import sys
sys.path.extend(['../'])
from feeders import tools
class Feeder(Dataset):
def __init__(self, data_path1, data_path2, label_path,
random_choose=False, random_shift=False, random_move=False,
... |
from fastapi import Depends, FastAPI
from typing import List, Any
from fastapi.middleware.cors import CORSMiddleware
from backend.db import create_db_and_tables
% if auth:
from backend.core.auth import auth_backend, fastapi_users
from backend.api.endpoints.user_endpoints import router as user_routes
% endif
app = Fas... |
"""
run ntuple where=DICE:
Runs the ntuple production in the Data Intensive Computing Environment.
See 'ntp help run ntuple' for a complete list of parameters.
"""
from __future__ import print_function
import os
import logging
from . import Command as ParentCommand
from ntp import NTPROOT
from ntp.... |
# -*-coding=utf-8-*-
'''
@Created on 2016-12-26
@author gongsc@hsfund.com
交易系统资产单元份额计算工具
'''
from util.db_util import get_engine, query_asset_data, insert_message, query_msg_queue_sqe
from util.logging_util import info, error
from config.configuration import *
import time
from apscheduler.schedulers.blocking import Bl... |
import datetime
from omega_miya.database import DBCoolDownEvent, Result
from dataclasses import dataclass, field
@dataclass
class PluginCoolDown:
"""
插件冷却工具类, 用于声明当前 matcher 权限及冷却等信息, 并负责处理具体冷却事件
- type: 冷却类型
- cool_down_time: 冷却时间, 单位秒
"""
type: str
cool_down_time: int
global_... |
"""Add 'updated' to packages
Revision ID: 2ca4511880b
Revises: 1fc38fa913a
Create Date: 2014-10-11 13:29:07.675201
"""
# revision identifiers, used by Alembic.
revision = '2ca4511880b'
down_revision = '1fc38fa913a'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated by Al... |
# MIT License
#
# Copyright (C) The Adversarial Robustness Toolbox (ART) Authors 2020
#
# 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
# r... |
# -*- coding:utf-8 -*-
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved.
# This program is free software; you can redistribute it and/or modify
# it under the terms of the MIT License.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the ... |
from django.contrib.sitemaps import Sitemap
from .models import Post
class PostSiteMap(Sitemap):
"""
Just a reminder:
We're (simply) override
the (static) attrs of the class 'Sitemap' :P
Some attrs & methods:
changefreq possible vals: 'al... |
# File: cofenseintelligence_consts.py
#
# Copyright (c) 2020-2021 Splunk 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 req... |
import time
def time_stamp_now():
time_now = int(time.time())
time_local = time.localtime(time_now)
return time.mktime(time_local)
class FileMetaData:
def __init__(self, fname, blocks=None, timestamp=None):
if blocks is None:
blocks = []
self.fname = fname
self.bl... |
# -*- coding: utf-8 -*-
# Copyright 2010 Yefe<yefe@ichuzhou.cn>
from os import path
import codecs
class Hanzi2Pinyin(object):
def __init__(self):
self.table = {}
try:
fp = codecs.open(path.join(path.dirname(
__file__), 'pinyin.txt'), 'r', 'utf-8')
except IOError... |
#!/usr/bin/env python
import os
import sys
import shlex, subprocess
import tempita
from conf import bib_dir, build_dir, template_dir, html_dir
from options import get_config
def _from_template(tmpl_basename, config):
tmpl = os.path.join(template_dir, tmpl_basename + '.tmpl')
template = tempita.HTMLTemplate(o... |
#!/usr/bin/env python
# Copyright (c) 2016 Hewlett Packard Enterprise Development Company, L.P.
#
# 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... |
from flask import Flask
# Bibliotecas publicamente acessíveis
#db = SQLAlchemy()
def init_app():
# Inicializa a aplicação
app = Flask(__name__, instance_relative_config=False)
app.config.from_object('config.Config')
# Inicializa Plugins
#db.init_app(app)
with app.app_context():
... |
import time
import re
import json
import pytest
import platform
from swsscommon import swsscommon
from distutils.version import StrictVersion
class TestVlan(object):
def setup_db(self, dvs):
self.pdb = swsscommon.DBConnector(0, dvs.redis_sock, 0)
self.adb = swsscommon.DBConnector(1, dvs.redis_soc... |
# from common.file_operations import save_to_file [X] <-- Wrong Way
# from utils.common.file_operations import save_to_file [+1] <-- Correct
# from .common.file_operations import save_to_file [+1] <-- Correct
"""
Above methods are : Relative imports : that starts from current file we're working with and it can ... |
# -*- coding: utf-8 -*-
# Copyright 2014-2016 OpenMarket Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... |
# Generated by Django 3.1.7 on 2021-03-29 13:19
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('quizapp', '0004_auto_20210329_1318'),
]
operations = [
migrations.AlterField(
model_name='student',
name='points',
... |
import uuid
import numpy
import pandas
from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import GridSearchCV
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC, SVR
from sklearn.tree imp... |
import astral
import csv
import datetime
import math
import os
import random
import re
import statistics
def load_historical_data_headers():
"""Load the headers for historical weather data."""
with open(os.path.dirname(os.path.realpath(__file__)) + '/../data/1711054.csv') as f:
reader = csv.reader(f)
... |
from rest_framework import serializers
from rest_framework.validators import UniqueValidator
from foundation.models import Instrument, Sensor, TimeSeriesDatum
class InstrumentSerializer(serializers.Serializer):
id = serializers.IntegerField(read_only=True)
location = serializers.CharField(validators=[
... |
# -*- coding: utf-8 -*-
# file: change_loading_device.py
# time: 2021/6/8 0008
# author: yangheng <yangheng@m.scnu.edu.cn>
# github: https://github.com/yangheng95
# Copyright (C) 2021. All Rights Reserved.
from pyabsa import APCConfigManager, APCCheckpointManager
sent_classifier = APCCheckpointManager.get_sentiment_... |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2016-2020 CERN.
#
# Marshmallow-Utils is free software; you can redistribute it and/or modify
# it under the terms of the MIT License; see LICENSE file for more details.
"""Localized Extended Date(/Time) Format Level 0 date string field."""
import calendar
from datetime impor... |
# -*- coding: utf-8 -*-
"""
oauthlib.oauth2.rfc6749.grant_types
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"""
from __future__ import unicode_literals, absolute_import
import json
import logging
from .base import GrantTypeBase
from .. import errors
from ..request_validator import RequestValidator
log = logging.getLogger(_... |
# BSD 2-Clause License
#
# Copyright (c) 2021, Hewlett Packard Enterprise
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright noti... |
# -*- coding: utf-8 -*-
"""Defining functions and classes for classification of dementia features.
The contents of this module define functions and classes for cleaning,
visualizing, and making predictions based on clinical datasets collected by
the Open Access Series of Imaging Studies (OASIS) project.
Explore this ... |
"""
Inflater
========
#. :class:`.Inflater`
Generator of blob guests using nonbonded interactions and growth.
"""
from __future__ import annotations
from collections import abc
import typing
import numpy as np
from copy import deepcopy
from scipy.spatial.distance import cdist
from .host import Host
from .blob imp... |
from datetime import date
from api.models.account_balance import AccountBalance
from api.models.credit_transaction import CreditTransaction
from django.db.models import Sum
def parse_summary_serializer(lst, serializer_data, category):
index = 0
found = False
model_year = serializer_data['model_year'].get(... |
#
# Script to scrape 43877 encoded Xiangqi games from wxf.ca
#
import scrapy
from scrapy.crawler import CrawlerProcess
class Xqdb(scrapy.Spider):
name = 'xqdb'
def start_requests(self):
for page in range(41, 43919):
yield scrapy.Request(
url='http://wxf.ca/xq/xqdb/jgam... |
import logging
from dataclasses import field
from functools import wraps, lru_cache
import cachetools
import dill
import six
from cachetools import Cache
from frozendict import frozendict
from future.utils import lmap
from nose.tools import assert_is_not_none, assert_equal, assert_true
from foxylib.tools.collections.... |
class ObjectFactory:
def __init__(self):
self._builders={}
def register_builder(self, key , builder):
self._builders[key] = builder
def create(self, key, **kwargs):
builder = self._builders.get(key)
if not builder:
raise ValueError(key)
return builder(**... |
class RecordNotFoundError(Exception):
def __init__(self, record_id):
super().__init__()
self.record_id = record_id |
# Copyright 2015 Red Hat, 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 writing, so... |
from insights.core.spec_factory import glob_file, simple_file, head, first_file
from functools import partial
from insights.core.context import HostArchiveContext
from insights.specs import Specs
simple_file = partial(simple_file, context=HostArchiveContext)
glob_file = partial(glob_file, context=HostArchiveContext)
f... |
import functools
from typing import (
Any,
Dict,
Iterable,
Sequence,
Tuple,
Type,
Union,
)
from eth_typing import (
Address,
Hash32,
)
from eth_utils import (
ValidationError,
)
from eth_utils.toolz import dicttoolz
from eth_utils.toolz import functoolz
from eth_utils.toolz ... |
# -*- coding: utf-8 -*-
# ------------------------------------------------------------------------------
#
# Copyright 2018-2019 Fetch.AI Limited
#
# 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 ... |
#socket_multicast_sender.py
import socket
import struct
import sys
import zlib
import pyaudio
message = b'very important data'
multicast_group = ('224.3.29.71', 10000)
# Create the datagram socket
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# Set a timeout so the socket does not block
# indefinitely when... |
from pwn import *
# context.terminal = ['tmux', 'split', '-h']
# context.log_level = 'debug'
p = process('./hack')
# p = remote('127.0.0.1', 23455)
def addi(size, content):
p.sendlineafter('choice>', '1')
p.sendlineafter('size>', str(size))
p.sendlineafter('content>', content)
def deli(index):
p.sen... |
# 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 by applicable law or a... |
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'socialNetwork.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise ... |
from .metric import *
from .help import *
from .logs import *
from .lr_scheduler import * |
"""
.. moduleauthor:: Chris Bowman <chris.bowman.physics@gmail.com>
"""
import sys
from warnings import warn
from copy import copy, deepcopy
from multiprocessing import Process, Pipe, Event, Pool
from time import time
from random import choice
import matplotlib.pyplot as plt
from numpy import array, arange, float64, ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Computed attributes based on schema fields.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
# stdlib imports
import sys
from Acquisition import aq_base
from Acquisition.interfaces import IAcquirer
from... |
#while loop
#Difference between for loop and while loop
#FOR LOOP: for item in the list_of_items:
# Do something to each item
#for number in range(a,b)
# print(number)
#WHILE LOOP: whuile something_is_true #Do someting repeatedly
#only when while loop is false the loop stops
#number_of_hurdles = 6
#while numbe... |
import requests
url = 'http://127.0.0.1:5000/covidgr/2020-11-02/2020-11-03'
headers = {
'Content-type': 'application/json',
}
response = requests.get(url, headers=headers)
print(response.json()) |
from django.db import models
from django.db.models.base import Model
from django.urls import reverse
import uuid #required for unique book instances
from django.contrib.auth.models import User
from datetime import date
# Create your models here.
class Genre(models.Model):
"""
Molde representing a book genre.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.