text stringlengths 2 999k |
|---|
# -*- coding: utf-8 -*-
# this file is released under public domain and you can use without limitations
#########################################################################
## Customize your APP title, subtitle and menus here
#########################################################################
response.logo... |
# -*- coding: utf-8 -*-
import email
import json
import logging
import smtplib
from email.header import Header
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from zvt import zvt_config
from zvt.networking.request import get_http_session, sync_get, sync_post
class Informer(object)... |
import numpy as np
from scipy import optimize
def f(x, a): return x**3 - a
def fder(x, a): return 3 * x**2
rng = np.random.default_rng()
x = rng.standard_normal(100)
a = np.arange(-50, 50)
vec_res = optimize.newton(f, x, fprime=fder, args=(a, ), maxiter=200)
print(vec_res) |
#!/usr/bin/env python2.7
# Copyright 2015 gRPC 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 l... |
# imports - compatibility packages
from __future__ import absolute_import
# module imports
from bulbea.entity import Share, Stock
from bulbea.config import AppConfig
from bulbea.app import app
from bulbea.learn import sentiment
__version__ = AppConfig.VERSION
|
"""Immutable sets that support efficient merging, traversal, and membership
check.
"""
def _empty():
"""Create an empty set.
Returns:
set, new empty set.
"""
return struct(_set_items = dict())
def _is_member(s, e):
"""Return true if `e` is in the set `s`.
Args:
s: The set to inspect.
e: The ... |
import re
from . import csv
SDC_SOURCE_FILE_COLUMN = "_sdc_source_file"
SDC_SOURCE_LINENO_COLUMN = "_sdc_source_lineno"
# TODO: Add additional logging
# TODO: conn needs get_files and get_file_handle functions
def get_schema_for_table(conn, table_spec):
files = conn.get_files(table_spec['search_prefix'], table_... |
import warnings
from inspect import isfunction, signature
import pkg_resources
import pytest
from appdaemon.plugins.hass.hassapi import Hass
from appdaemontestframework.common import AppdaemonTestFrameworkError
class AutomationFixtureError(AppdaemonTestFrameworkError):
pass
def _instantiate_and_initialize_aut... |
# Show TNDD Views for Paratext
# Written by Ian McQuay, SIL International, 2022-01-05+10:00
# Import OS to be able to output correctly to Windows
import os
# Define batch files
actionbatchfile = "C:\Users\Public\PT-Views\user-views-action.cmd"
batchfile = "C:\Users\Public\PT-Views\user-views-manager.cmd"
# setup vari... |
""" Cisco_IOS_XE_ospf_oper
This module contains a collection of YANG definitions for
monitoring the operation of ospf protocol in a Network Element.
Copyright (c) 2016\-2018 by Cisco Systems, Inc.
All rights reserved.
"""
from collections import OrderedDict
from ydk.types import Entity, EntityPath, Identity, Enum, ... |
# Copyright (c) 2012-2013, 2015-2016 ARM Limited
# All rights reserved
#
# The license below extends only to copyright in the software and shall
# not be construed as granting a license to any other intellectual
# property including but not limited to intellectual property relating
# to a hardware implementation of the... |
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm as BaseUserCreationForm
# from crispy_forms.helper import FormHelper
# from crispy_forms.layout import Submit
import sys
import os
from .models import User_Profile
sys.path.append(os.path.dirname... |
from flask import render_template, request
from flask_script import Manager, Server
from app import app
from model import Content, Summary, Article
import app.static.summ as summarizationModel
import os, json, logging
@app.route('/', endpoint='ACCESS')
@app.route('/index.html', endpoint='ACCESSFILE')
def index():
... |
# -*- 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... |
"""
# Sample code to perform I/O:
name = input() # Reading input from STDIN
print('Hi, %s.' % name) # Writing output to STDOUT
# Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail
"""
# Write your code here
from collections import deque, defaultdict
... |
"""
Django settings for apply project.
For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
impo... |
"""
WSGI config for Boats & Joy project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_S... |
#!/usr/bin/env python
#
# Public Domain 2014-2016 MongoDB, Inc.
# Public Domain 2008-2014 WiredTiger, Inc.
#
# This is free and unencumbered software released into the public domain.
#
# Anyone is free to copy, modify, publish, use, compile, sell, or
# distribute this software, either in source code form or as a compil... |
# pylint: skip-file
HARDWARE_ITEMS = [
{'attributes': [],
'capacity': '999',
'description': 'Unknown',
'itemCategory': {'categoryCode': 'unknown', 'id': 325},
'keyName': 'UNKNOWN',
'prices': [{'accountRestrictions': [],
'currentPriceFlag': '',
'hourlyRecurr... |
f = lambda x: x + 1
map(f, [1, 2, 3, 4]) |
import os
import time
from slackclient import SlackClient
import bot_id
# Instructor and student imports
import wray.slacklib
import joe.slacklib
import chris.slacklib
# constants
try:
AT_BOT = "<@" + bot_id.get_id() + ">"
except TypeError:
pass
# instantiate client
slack_client = SlackClient(os.environ.get... |
"""Auto-generated file, do not edit by hand. PH metadata"""
from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata
PHONE_METADATA_PH = PhoneMetadata(id='PH', country_code=63, international_prefix='00',
general_desc=PhoneNumberDesc(national_number_pattern='1800\\d{7,9}|(?:2|[89]\\d{4})\\d{5}|[2-8]... |
# -*- coding: UTF-8 -*-
from __future__ import unicode_literals
from datetime import timedelta
from django.conf import settings
from django.contrib.auth.decorators import login_required
from django.shortcuts import render
from django.utils.timezone import now as tz_now
@login_required
def start_page(request):
# ... |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT license.
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import collections
import inspect
from athena.onnx import constants
... |
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any... |
import math
from typing import Dict, Union, List
import torch
from torch import nn, Tensor
from .. import properties as p
def fix_msk(mol: Dict[str, Tensor], idx: Tensor):
_, atm, dim = mol[p.pos].size()
msk = torch.zeros([atm, dim], dtype=torch.bool, device=idx.device)
msk[idx, :] = True
return msk
... |
import numpy as np
import sys
sys.dont_write_bytecode = True
def ExtractCameraPose(E, K):
U, S, V_T = np.linalg.svd(E)
W = np.array([[0, -1, 0], [1, 0, 0], [0, 0, 1]])
# print("E svd U", U)
# print("E svd S", S)
# print("E svd U[:, 2]", U[:, 2])
R = []
C = []
R.append(np.dot(U, np.do... |
from rest_framework import generics, authentication, permissions
from rest_framework.authtoken.views import ObtainAuthToken
from rest_framework.settings import api_settings
from user.serializers import UserSerializer, AuthTokenSerializer
class CreateUserView(generics.CreateAPIView):
"""Create a new user in the s... |
<!DOCTYPE html>
<html lang="en" data-color-mode="auto" data-light-theme="light" data-dark-theme="dark">
<head>
<meta charset="utf-8">
<link rel="dns-prefetch" href="https://github.githubassets.com">
<link rel="dns-prefetch" href="https://avatars.githubusercontent.com">
<link rel="dns-prefetch" href="h... |
"""myblog URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.1/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based ... |
a = [0, 1, 2]
b = [0, 1]
for a, b in zip(a, b):
print(a, b) |
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 7 09:36:45 2019
@author: MyPC
"""
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib
import math
import pymssql
import numpy as np
import copy
import re
from sklearn import preprocessing
from sklearn.linear_model import LinearRegression... |
"""
This file contains the implementation of the main class object: anaRDPacct --- an analytical moment accountant
that keeps track the effects of a hetereogeneous sequence of randomized algorithms using the RDP technique.
In particular it supports amplification of RDP by subsampling without replacement and the ampli... |
import logging
import unittest
import numpy as np
from cave.utils.statistical_tests import paired_permutation, paired_t_student
class TestStatisticalTests(unittest.TestCase):
def setUp(self):
self.logger = logging.getLogger("TestStatisticalTests")
def test_paired_permutation(self):
""" Tes... |
import ibmsecurity.utilities.tools
import logging
logger = logging.getLogger(__name__)
module_uri = "/isam/felb/configuration/services/"
requires_modulers = None
requires_version = None
def add(isamAppliance, service_name, address, active, port, weight, secure, ssllabel, check_mode=False, force=False):
"""
... |
# Copyright 2018 The TensorFlow Probability 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 o... |
# Copyright 2020 The ElasticDL 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 applicable law... |
import requests
# Vuln Base Info
def info():
return {
"author": "cckuailong",
"name": '''Geddy before v13.0.8 LFI''',
"description": '''Directory traversal vulnerability in lib/app/index.js in Geddy before 13.0.8 for Node.js allows remote attackers to read arbitrary files via a ..%2f (dot ... |
import math
n = 100
print(sum(map(int, str(math.factorial(n))))) |
import os
import sys
import numpy as np
import cv2
import statistics
import datetime
def getMedian(arr, x, y):
values = []
for a in arr:
values.append(a[x][y])
return statistics.median_grouped(values)
def getMean(arr, x, y):
values = []
for a in arr:
values.append(a[x][y])
retu... |
#9TH PROGRAM
# THIS PROGRAM WILL HELP IN ACCESSING DICTIONARY ITEMS AND PERFROM CERTAIN OPERATIONS WITH DICTIONARY
ages = {} #EMPTY DICTIONARY
ages["Micky"] = 24
ages["Lucky"] = 25
print(ages)
keys = ages.keys # .keys prints all the keys avaialble in Dictionary
print(keys)
values = ages.values # .values prints a... |
from __future__ import print_function
import itertools
from PhysicsTools.Heppy.analyzers.core.Analyzer import Analyzer
from PhysicsTools.Heppy.analyzers.core.AutoHandle import AutoHandle
from PhysicsTools.HeppyCore.framework.event import Event
from PhysicsTools.HeppyCore.statistics.counter import Counter, Counters
fr... |
from django.contrib import admin
from .models import blog
# Register your models here.
admin.site.register(blog) |
#!/usr/local/sal/Python.framework/Versions/Current/bin/python3
import datetime
import pathlib
import plistlib
import sys
import sal
sys.path.insert(0, "/usr/local/munki")
from munkilib import munkicommon
__version__ = "1.2.0"
def main():
# If we haven't successfully submitted to Sal, pull the existing
#... |
__all__ = ["PY2", "PY3"]
import sys
if sys.version_info[0] == 2:
PY2 = True
PY3 = False
elif sys.version_info[0] == 3:
PY2 = False
PY3 = True
else:
PY2 = False
PY3 = False
|
## @ StitchLoader.py
# This is a python stitching script for Slim Bootloader APL build
#
# Copyright (c) 2018 - 2022, Intel Corporation. All rights reserved. <BR>
# SPDX-License-Identifier: BSD-2-Clause-Patent
#
##
import os
import re
import sys
import struct
import argparse
import zipfile
import shutil
from ctypes i... |
'''
This is a sample class that you can use to control the mouse pointer.
It uses the pyautogui library. You can set the precision for mouse movement
(how much the mouse moves) and the speed (how fast it moves) by changing
precision_dict and speed_dict.
Calling the move function with the x and y output of the gaze est... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class AntOcrVehicleplateIdentifyModel(object):
def __init__(self):
self._image = None
self._type = None
@property
def image(self):
return self._image
@image.setter... |
import json
import web
import calendar
import datetime
import cloudserver
urls = (
"/BuildingFootprint/", "BuildingFootprint",
"/BuildingFootprintDisaggregated/", "BuildingFootprintDisaggregated",
"/PersonalConsumption/", "PersonalConsumption",
"/HistoricalConsumption/", "HistoricalConsumption")
class BuildingFoo... |
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
"""
Implements the Generalized R-CNN framework
"""
import torch
from torch import nn
from openpose.structures.image_list import to_image_list
from ..backbone import build_backbone
from ..rpn.rpn import build_rpn
from ..roi_heads.roi_heads import... |
"""Test DeltaPySimulator functionality pre-execution."""
import unittest
import deltalanguage as dl
from deltalanguage.test._graph_lib import (getg_const_chain,
getg_optional_queues)
class DeltaQueueCreationTest(unittest.TestCase):
"""Test that the simulator creates q... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Program to preprocess training and test data using word2vec, dep2vec
and fact2vec embeddings and prepare corresponding weight vectors to
be used in CNN
Copyright (C) 2016
Ubiquitous Knowledge Processing (UKP) Lab
Technische Universität Darmstadt
Licensed under the Ap... |
import logging
import base64
import sys
import random
import string
import os
import ssl
import time
import copy
import json
import sys
from pydispatch import dispatcher
from flask import Flask, request, make_response, send_from_directory
# Empire imports
from lib.common import helpers
from lib.common import agents
fro... |
from website import create_app
app = create_app()
if __name__== '__main__':
app.run(debug=True)
|
from typing import List
from blogs.api.interface import IBlogApiExecutor
from domain.blog.blog_entry import BlogEntry, BlogEntries
from domain.doc.doc_entry import DocEntries, DocEntry
from dump.blog_to_doc_mapping import BlogDocEntryMapping
from dump.interface import IDumpEntriesAccessor
from files.conf.category_grou... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.2 on 2016-12-19 08:46
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('cms', '0014_auto_20161216_1359'),
('cms', '0014_auto_20161216_1424'),
]
operations ... |
"""A high-level interface to local Galaxy instances using bioblend."""
from six import StringIO
from planemo.bioblend import ensure_module
from planemo.bioblend import galaxy
DEFAULT_MASTER_API_KEY = "test_key"
def gi(port=None, url=None, key=None):
"""Return a bioblend ``GalaxyInstance`` for Galaxy on this por... |
#!/usr/bin/env python
#
# Python installation script
# Author - @chowmean
from __future__ import print_function
import os.path
import sys
import setuptools
# Project variables
VER_PROP_FILE = os.path.join(os.path.dirname(__file__), 'version.properties')
REQUIREMENTS_FILE = os.path.join(os.path.dirname(__file__), 'req... |
from django.db.models import Manager
from django.db.models.query import QuerySet
from django.contrib.contenttypes.models import ContentType
import itertools
class VoteQuerySet(QuerySet):
def delete(self, *args, **kwargs):
"""Handles updating the related `votes` and `score` fields attached to the model."""... |
"""
Django settings for django_tdd project.
Generated by 'django-admin startproject' using Django 1.9.12.
For more information on this file, see
https://docs.djangoproject.com/en/1.9/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.9/ref/settings/
"""
import o... |
from System import IntPtr
from System.Runtime.InteropServices import Marshal
import Ironclad
from Ironclad import CPyMarshal
from Ironclad.Structs import METH, Py_TPFLAGS, PyGetSetDef, PyMemberDef, PyMethodDef, PyTypeObject
from tests.utils.memory import OffsetPtr
def _new_struct(type_, fields, *v... |
from __future__ import division
import os
import time
from glob import glob
import tensorflow as tf
import numpy as np
from six.moves import xrange
from ops import *
from utils import *
class pix2pix(object):
def __init__(self, sess, image_size=256,
batch_size=1, sample_size=1, output_size=256,
... |
# -*- coding: utf-8 -*-
# Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "Lic... |
# Copyright The PyTorch Lightning team.
#
# 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 i... |
# -*- coding: utf-8 -*-
# Copyright (c) 2017, Frappe Technologies and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
class RoleProfile(Document):
def autoname(self):
"""set name as Role Profile name""... |
from output.models.ms_data.complex_type.ct_f013_xsd.ct_f013 import (
FooType,
MyType,
Root,
)
__all__ = [
"FooType",
"MyType",
"Root",
]
|
import datetime
class Filter:
def __init__(self, name):
self._name = name
def _as_params(self):
return {}
class SingleFilter(Filter):
def __call__(self, value):
self._value = value
return self
def _as_params(self):
return {"filter[{}]".format(self._name): se... |
import datetime
import hashlib
import json
import logging
import os.path
import sys
from typing import TYPE_CHECKING
from pip._vendor.packaging.version import parse as parse_version
from pip._internal.index.collector import LinkCollector
from pip._internal.index.package_finder import PackageFinder
from pip._internal.... |
from treehopper.libraries.displays import LedDriver
from treehopper.libraries.io.expander.shift_register import ChainableShiftRegisterOutput
class LedShiftRegister(ChainableShiftRegisterOutput, LedDriver):
def __init__(self):
super().__init__()
|
from userbot import bot
from telethon import events
import asyncio
from datetime import datetime
from telethon.tl.types import User, Chat, Channel
from uniborg.util import admin_cmd
@bot.on(admin_cmd(pattern=r"stats"))
async def _(event):
if event.fwd_from:
return
start = datetime.now()
u = 0
g... |
# This file will track detections
import tqdm
import cv2
import matplotlib.pyplot as plt
import matplotlib.patches as patches
from matplotlib.ticker import NullLocator
from cs231aApproachingOdt import utils as myutils
from PIL import Image
import os
import torch
import torchvision.ops.boxes as bops
def match_detectio... |
# Tot's reward lv 40
sm.completeQuest(5521)
# Lv. 40 Equipment box
sm.giveItem(2431877, 1)
sm.dispose()
|
import csv
from django.contrib.auth import get_user_model
from django.db.models.aggregates import Sum
from django.http.response import HttpResponse
from django.utils.decorators import method_decorator
from djoser.serializers import SetPasswordSerializer
from djoser.views import TokenCreateView
from drf_yasg.utils impo... |
#!/usr/bin/env python
# Copyright (c) 2015 OpenStack 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 applic... |
from typing import Dict
from twitchio.dataclasses import Message
class TeamData:
def __init__(self, num_teams: int = 2):
self.num_teams = num_teams
self.teams: Dict[int, int] = {}
async def handle_join(self, msg: Message) -> None:
if msg.author.id in self.teams:
# User al... |
from typing import FrozenSet, Tuple
import pysmt.typing as types
from pysmt.environment import Environment as PysmtEnv
from pysmt.fnode import FNode
from utils import symb_to_next
from hint import Hint, Location
def transition_system(env: PysmtEnv) -> Tuple[FrozenSet[FNode], FNode, FNode,
... |
from __future__ import print_function
from __future__ import absolute_import
from __future__ import division
from compas.utilities import geometric_key
__all__ = [
'mesh_delete_duplicate_vertices'
]
def mesh_delete_duplicate_vertices(mesh, precision=None):
"""Cull all duplicate vertices of a mesh and sanit... |
#!/usr/bin/env python3
# Copyright (c) 2014-2016 The Ruxcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
# Test RPC calls related to blockchain state. Tests correspond to code in
# rpc/blockchain.cpp.
#
from... |
##########################################################################
# If not stated otherwise in this file or this component's Licenses.txt
# file the following copyright and licenses apply:
#
# Copyright 2019 RDK Management
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use th... |
###############################################################################
#
# Tests for XlsxWriter.
#
# Copyright (c), 2013-2020, John McNamara, jmcnamara@cpan.org
#
from ..excel_comparison_test import ExcelComparisonTest
from ...workbook import Workbook
class TestCompareXLSXFiles(ExcelComparisonTest):
"""... |
class Fan():
"""Default Device with ON / OFF Functions"""
deviceID = None
def __init__(self, deviceID):
if deviceID is None:
print("Provide a Device ID")
return
self.deviceID = deviceID
def setSpeed(self):
pass
def getSpeed(self):
pass
|
# Generated by Django 2.2 on 2020-10-29 04:23
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='ConstructionSystem',
fields=... |
from typing import Optional
from cryptoxlib.exceptions import CryptoXLibException
class AAXException(CryptoXLibException):
pass
class AAXRestException(AAXException):
def __init__(self, status_code: int, body: Optional[dict]):
super().__init__(f"Rest API exception: status [{status_code}], response [{body}]")
... |
import aioredis
from sanic import Sanic
class RedisWorker:
def __init__(self):
self.__host = None
self.__pool = None
async def init(self, app: Sanic):
self.__host = app.config.REDIS_HOST
self.__pool = await aioredis.create_redis(self.__host)
async def check_session(self, ... |
# -*- coding: utf-8 -*-
'''
Connection module for Amazon Security Groups
.. versionadded:: 2014.7.0
:configuration: This module accepts explicit ec2 credentials but can
also utilize IAM roles assigned to the instance trough Instance Profiles.
Dynamic credentials are then automatically obtained from AWS API an... |
import sys
sys.path.insert(0, "../") # our fake sigrokdecode lives one dir upper
from pd import Decoder
class DS1307():
def __init__(self):
self.sigrokDecoder = Decoder()
def get_capabilities(self):
settings = {}
for option in self.sigrokDecoder.options :
settingType = ''
choices = ... |
import torch
import numpy as np
import json, sys, re, string
import collections
from collections import Counter
from collections import OrderedDict
def get_sp_pred(pred_sp_idx, data):
"""get the prediction of supporting facts in original format
Arguments:
pred_sp_idx {[type]} -- [description]
... |
#!/usr/bin/python
#-*-coding=utf-8-*-
def pyramid(n):
most = 2*n - 1
for i in range(1,n+1):
star = 2*i - 1
space = n - i
print(" "*space + "*"*star)
def test():
pyramid(3)
pyramid(4)
pyramid(5)
if __name__ == "__main__":
test()
|
# Run this again after editing submodules so Colab uses the updated versions
from citylearn import CityLearn
from citylearn import GridLearn
import matplotlib.pyplot as plt
from pathlib import Path
from citylearn import RL_Agents_Coord, Cluster_Agents
import numpy as np
import csv
import time
import re
import pandas as... |
# Copyright 2013
# Author: Christopher Van Arsdale
#
# See common/third_party/google/gflags_python/gflags for info
#
# Examlpe:
# import common.base.flags
# import sys
#
# FLAGS = flags.FLAGS
# flags.d.DEFINE_bool('my_bool', false, 'My description')
#
# def main(argv):
# flags.Parse(argv)
# ... use FLAGS.my_... |
#!/usr/bin/env python3
# Copyright (c) 2010 ArtForz -- public domain half-a-node
# Copyright (c) 2012 Jeff Garzik
# Copyright (c) 2010-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.
"""Bitcoin P2P ... |
#!/usr/bin/env python3
import argparse
import os
import pickle
from getpass import getpass
from typing import Tuple
import requests
from appdirs import user_cache_dir
from mysodexo import api
from mysodexo.constants import APPLICATION_NAME, SESSION_CACHE_FILENAME
def prompt_login() -> Tuple[str, str]:
"""Prompt... |
# Реалізувати клас Герой що має мати наступні атрибути: ім‘я, здоров‘я, ранг, сила і метод вдарити.
# Метод вдарити повинен наносити шкоду противнику в розмірі сили героя. Герой має мати наступні
# обмеження: здоров‘я від 0 до 100, ранг 1,2,3. Сила не більше 10% теперішнього здоров‘я героя.
# Не можна бити героїв здоро... |
import copy
########################################### This function reads in block from file
def grid_from_file(file_name):
lst=[]
f=open(file_name)
for line in f:
lst2=[]
for i in line:
if i == "x":
lst2.append(i)
elif i.isdigit():
... |
# coding: utf-8
import pprint
import re # noqa: F401
import six
class Body19(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_types (dict): The key is attribute name
... |
"""
Winning Python script for EasyMarkit Hackathon by Team Sigma
"""
##Team Sigma - Members: Betty Zhou, Bailey Lei, Alex Pak
# Usage: python sigma_script.py data/train.csv data/test.csv
# import any necessary packages here
#loading libraries
import argparse
import os
import pandas as pd
import numpy as np
impo... |
import pathlib
import pkg_resources
from clvm_tools.clvmc import compile_clvm
from hddcoin.types.blockchain_format.program import Program, SerializedProgram
def load_serialized_clvm(clvm_filename, package_or_requirement=__name__) -> SerializedProgram:
"""
This function takes a .clvm file in the given packag... |
from django.shortcuts import render
from django.http import HttpResponse, JsonResponse, StreamingHttpResponse, FileResponse
from django.template import loader
from django.shortcuts import get_object_or_404, render, redirect
from django.views import View
from django.views.generic import DetailView, ListView
from django.... |
import logging
import urllib
import requests
import base64
"""
HASS module to read Aerogarde bounty info, later there will be an option to control the light
writen by @epotex
"""
_LOGGER = logging.getLogger(__name__)
DOMAIN = 'aerogarden'
agent = "BountyWiFi/1.1.13 (iPhone; iOS 10.3.2; Scale/2.00)"
port = "8080... |
import asyncio
from datetime import datetime, timezone
from functools import wraps
import traceback
import inspect
import logging
import ujson as json_module
import hashlib
import yaml
from aiohttp import web
import aiohttp
import mongoengine
import os
from .engine.objects import Operation, Network, Domain, Log, Obse... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.