content stringlengths 5 1.05M |
|---|
from core.emitter import Emitter
# The WebSocketEmitter for tornado websockets
# Emit all events to all connected sockets
class WebSocketEmitter(Emitter):
def __init__(self):
self._sockets = []
def add_websocket(self, socket):
self._sockets.append(socket)
def remove_websocket(self, socke... |
import json
from src import colors
class htotw:
data = None
def load():
with open("htotw.json", 'r') as f:
htotw.data = json.load(f)
def description():
return ("%s%s%s" % (
colors.get("blue", 3),
htotw.data["description"],
colors.get("reset", 0)))
def display():
prin... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2005-2009 University of Deusto
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
#
# This software consists of contributions made by many individuals, ... |
"""
The merge source provides a mechanism for merging and filtering the data
resulting from two or more other "sub-reports". This can be useful if you need
to combine results from two different databases or with two different key
ranges into one report.
When building a merged report, you must specify the reports to me... |
# coding: utf-8
"""
DiskPoolData.py
The Clear BSD License
Copyright (c) – 2016, NetApp, Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted (subject to the limitations in the disclaimer below) provided that the following conditions are met:
*... |
# This file started out in graphing, but migrated to pyray.
import numpy as np
import queue
from collections import defaultdict
from itertools import combinations
from PIL import Image, ImageDraw, ImageFont, ImageMath
def tst():
survive = {3, 10, 11, 8, 5}
gr = Graph_cube(survive)
gr.dfs('00+')
im = ... |
from ..database import DB
'''
User Recommendation Data
Example:
{
'product_ids': [1,2,3,87],
'added_on': 234234234,
'last_updated': 23523234,
'recommendation_index': 1-10
}
'''
class UserRecommendationRepository(object):
COLLECTION = "user_recommendation"
''... |
"""Test functionality of the default datastore."""
import os
import shutil
import unittest
from vizier.datastore.base import METADATA_FILE
from vizier.datastore.dataset import DatasetColumn, DatasetRow
from vizier.datastore.fs.base import FileSystemDatastore
from vizier.datastore.fs.base import DATA_FILE, DESCRIPTOR_... |
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 8 13:50:47 2018
@author: lenovo
"""
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def reverseLinkList(self, head):
'''
input: Node
return: Node
'''
dummy = ListNode(-1)... |
import csv
import warnings
import numpy as np
import pandas as pd
import torch
from genetic_algorithm import GeneticAlgorithm as ga
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import LabelEncoder
from torch.autograd import Variable
warnings.filterwarnings('ignore')
device = torch.d... |
class Solution:
"""
@param s: a string
@return bool: whether you can make s a palindrome by deleting at most one character
"""
def validPalindrome(self, s):
# Write your code here
l, r = self.findDifference(s, 0, len(s) - 1)
if l >= r:
return True
return s... |
"""Unittests for the authentication middlware"""
import os
import time
from datetime import datetime
from typing import Any, Generator
import pytest
import requests
from fastapi.testclient import TestClient
from requests.models import Response
from nlp_land_prediction_endpoint import __version__
from nlp_land_predict... |
import pathlib
import os
import sys
import unittest
import numpy as np
from .tools import debug_on
from numpy.polynomial.legendre import Legendre
import matplotlib.pyplot as plt
import time
try:
from gsplines.optimization import minimum_jerk_path
except ImportError:
MOD_PATH = pathlib.Path(__file__).parent.abso... |
RED = (255, 0, 0)
YELLOW = (255, 150, 0)
ORANGE = (255, 40, 0)
GREEN = (0, 255, 0)
TEAL = (0, 255, 120)
CYAN = (0, 255, 255)
BLUE = (0, 0, 255)
PURPLE = (180, 0, 255)
MAGENTA = (255, 0, 20)
WHITE = (255, 255, 255)
# Sparkle colors:
GOLD = (255, 222, 30)
PINK = (242, 90, 255)
AQUA = (50, 255, 255)
JADE =... |
import os
import sys
import time
import inspect
from loguru import logger
from seldom.running.config import BrowserConfig
from seldom.running.config import Seldom
stack_t = inspect.stack()
ins = inspect.getframeinfo(stack_t[1][0])
exec_dir = os.path.dirname(os.path.abspath(ins.filename))
report_dir = os.path.join(exec... |
import os
import sys
from multiprocessing import Pool
import time
import argparse
parser = argparse.ArgumentParser(description='specify test data size or percent')
parser.add_argument("--lr_grid", type=float,
help="list of learning rates to try out", nargs='+', default = [.001])
parser.add_argument... |
##############################################################################
#
# Copyright (c) 2010 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOF... |
# -*- coding: utf-8 -*-
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software... |
import torch
from torch.autograd import Function
from se3.se3_utils import create_rotx, create_roty, create_rotz
from se3.se3_utils import create_skew_symmetric_matrix
class Se3euler(Function):
@staticmethod
def forward(ctx, input):
batch_size, num_se3, num_params = input.size()
rot_params = ... |
import numpy as np
from layers import FullyConnectedLayer, ReLULayer, softmax_with_cross_entropy, l2_regularization, softmax
class TwoLayerNet:
""" Neural network with two fully connected layers """
def __init__(self, n_input, n_output, hidden_layer_size, reg):
"""
Initializes the neural net... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.10 on 2018-02-06 05:45
from django.db import migrations, models
import django.db.models.deletion
import django_enumfield.db.fields
import events.models
class Migration(migrations.Migration):
dependencies = [
('events', '0023_auto_20180206_0346'),
]... |
n = int(input())
a = n
for x in range(1,n):
a *= (n-x)
print(a)
|
# coding: utf-8
from .composite import ActivationRuleGroup, CompositeRule, ConditionalRuleGroup, UnitRuleGroup
from .reader import YamlRuleDefinitionReader, YamlRuleFactory |
import os
class CheckpointPattern(object):
@staticmethod
def pattern(dir_path: str) -> str:
return os.path.join(dir_path, '{epoch}')
@staticmethod
def path(dir_path: str, epoch: int) -> str:
return os.path.join(dir_path, f'epoch={epoch}.ckpt')
|
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... |
print("Break Statement in looping structures");
i = 1;
# infinite loop with break
while(True):
i = i+1;
print("Nishkarsh Raj Khare");
if(i==5):
break;
|
from aiocloudflare.commons.unused import Unused
from .masters.masters import Masters
from .primaries.primaries import Primaries
from .tsigs.tsigs import Tsigs
class SecondaryDns(Unused):
_endpoint1 = "accounts"
_endpoint2 = "secondary_dns"
_endpoint3 = None
@property
def tsigs(self) -> Tsigs:
... |
from networks.Keras.small_AlexNet import *
from keras.models import Model
from helper.functions import getFilesInPath
from PIL import Image as im
import os, numpy as np, argparse, random, shutil, re
def loadFolderImages(pathFiles,regularExpression=None):
filesPath = getFilesInPath(pathFiles)
newFilePath = []
... |
"""
Copyright 2015 Rackspace
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
dist... |
from requests import get
class GitHub:
supportedResources = [
'projects',
'pulls',
'branches',
'collaborators',
'comments',
'forks',
'issues',
'commits',
]
def __init__(self, owner, repos, resources):
self.owner = owner
self.r... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Apr 1 21:13:39 2020
@author: parsotak
"""
#Data retrieved from: European Centre for Medium-Range Weather Forecasts, 2009:
#ERA-Interim Project. Research Data Archive at the National Center for Atmospheric Research,
#Computational and Information Sys... |
from absl.testing import absltest
import datetime
from icubam import authenticator
from icubam import config
from icubam.db import store
class AuthenticatorTest(absltest.TestCase):
def setUp(self):
super().setUp()
self.config = config.Config('resources/test.toml')
factory = store.create_store_factory_fo... |
# from rdkit import Chem
# from rdkit.Chem import Draw, AllChem
# from rdkit.Chem.Draw import IPythonConsole #Needed to show molecules
# from rdkit.Chem.Draw.MolDrawing import MolDrawing, DrawingOptions #Only needed if modifying defaults
# for i in range(1,2):
# opts = DrawingOptions()
# opts.includeAtomNumb... |
# Copyright 2020 The StackStorm Authors.
# Copyright 2019 Extreme Networks, 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 ... |
"""Generated client library for orgpolicy version v2alpha1."""
# NOTE: This file is autogenerated and should not be edited by hand.
from __future__ import absolute_import
from apitools.base.py import base_api
from googlecloudsdk.third_party.apis.orgpolicy.v2alpha1 import orgpolicy_v2alpha1_messages as messages
clas... |
"""Nokia FlexiNS/DX200 MML support."""
from __future__ import print_function
from __future__ import unicode_literals
import re
import time
from netmiko.cisco_base_connection import CiscoSSHConnection
from netmiko.linux.linux_ssh import LinuxSSH
class NokiaFlexinsSSH(CiscoSSHConnection):
"""Nokia FlexiNS/DX200 MML ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# +
# import(s)
# -
import threading
import time
import signal
from ocs_sal import *
from OcsLogger import *
# +
# __doc__ string
# -
__doc__ = """Event logger for events in the OCS sequencer (using a thread class)"""
# +
# dunder string(s)
# -
__author__ = "Philip N.... |
"""
------------ Meta - Doom ------------
This is a meta map that combines all 9 Doom levels.
Levels:
0 - Doom Basic
1 - Doom Corridor
2 - Doom DefendCenter
3 - Doom DefendLine
4 - Doom HealthGathering
5 - Doom MyWayHome
... |
# Clairmeta - (C) YMAGIS S.A.
# See LICENSE for more information
import os
from clairmeta.utils.probe import probe_folder, probe_mediainfo
from clairmeta.check_sequence import check_sequence
from clairmeta.settings import DCDM_SETTINGS
class DCDM(object):
""" Digital Cinema Distribution Master abstraction. """
... |
from __future__ import absolute_import, division, print_function
"""
Implementation of extended argument specifications used by test_scope.
"""
from .annotations import type_from_runtime
from .config import Config
from .error_code import ErrorCode
from .format_strings import parse_format_string
from .stacked_scopes... |
import logging
import sendgrid
import azure.functions as func
import simplejson as json
from os import environ
from sendgrid.helpers.mail import *
def main(req: func.QueueMessage) -> func.HttpResponse:
try:
logging.info("SendGrid email triggered.")
logging.debug("Parsing message data from reque... |
""" this file provides common functionality and constants to the others
DO NOT import anything lazy in it other than utils/baseutils otherwise
there is a strong chance for circular import issues.
"""
import pdb
import sys
verbose = "-v" in sys.argv
undefined = NotImplemented
OPT_DIRECTIVE_SKIP = "sk... |
# Copyright 2018 Jiří Janoušek <janousek.jiri@gmail.com>
# Licensed under BSD-2-Clause license - see file LICENSE for details.
import os
import sys
from argparse import ArgumentParser
from multiprocessing import Process
from typing import List
from fxwebgen.utils import SmartFormatter
from fxwebgen.postprocessor impo... |
# cmdline: -v -v
# test verbose output
print(1)
|
expected_output = {
"active": {
"boot_variable": "bootflash:12351822-iedge-asr-uut,12;",
"configuration_register": "0x2102",
},
"next_reload_boot_variable": "bootflash:12351822-iedge-asr-uut,12;",
}
|
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
class Transformer(nn.Module):
def __init__(self,
ntoken: int,
ninp: int,
nhead: int,
nhid: int,
nlayers: int,
dropout: float):
... |
from collections import Counter
import matplotlib.pyplot as plt
import numpy as np
import os
import sys
import cv2
import torch
from torch.utils.data import Dataset
from tqdm import tqdm
ROAD_CLASSES = ('road', 'lane markings', 'undrivable', 'movable', 'my car')
CLASS_VALUES = {(64, 32, 32) : 0,
(255,... |
import logging
from shapely.geometry import Polygon
from cops_and_robots.fusion.softmax import (binary_range_model,
binary_intrinsic_space_model,
range_model,
intrinsic_space_model)
from ... |
import os
import threading
import traceback
from asyncio import set_event_loop_policy
from unittest import TestCase
from unittest.mock import patch, MagicMock
import requests
from parameterized import parameterized
from tornado.ioloop import IOLoop
from auth.authorization import Authorizer, ANY_USER, EmptyGroupProvid... |
from sse_starlette.sse import ServerSentEvent
__version__ = "0.6.2"
__all__ = ["ServerSentEvent"]
|
from support import gurllib2
def test_urlopen():
# not a great test, but something
resp = gurllib2.urlopen('https://www.paypal.com')
assert resp.getcode() == 200
lines = resp.readlines()
assert lines
def test_build_opener():
opener = gurllib2.build_opener()
assert any(isinstance(h, gurlli... |
"""
OIDC specification of authentication request parameter ``acr_values``:
OPTIONAL. Requested Authentication Context Class Reference values.
Space-separated string that specifies the ``acr`` values that the
Authorization Server is being requested to use for processing this
Authentication Request, with... |
#!/usr/bin/env python3
import os
from siterank import __version__, __description__, __author__, __email__, __license__
from setuptools import setup, find_packages
pkg_name = 'siterank'
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
s = setup(
name=pkg_name,
version=__versio... |
# Divide raw data into partitions; maintain backwards compatibility with prior training
# test data will be saved separately, validation partition 0 will be original validation data
import sys
import os
import pandas
import numpy as np
import ConfigParser
import random
from sklearn.cross_validation import train_test_s... |
# Some processing functionscopied from: tiny-face-pytorch and adopted for repo needs
import logging
import numpy as np
from PIL import Image
from torch.utils.data import dataset
from torchvision import transforms
import json
from os.path import join
import torch
from datasets.wider import augment_utils
from util import... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Update the clementine ratings between two different DBs.
Often switch between OSes and want to keep ratings up to date.
If you only want a subset of the songs, modify the QUERY_RATING variable.
Pass in db locations to the program as SRC and DST, ratings from SRC will ... |
__version__ = '0.2.1' # http://semver.org/
|
import json
from fastapi.testclient import TestClient
from sqlalchemy.orm import Session
headers = {"Content-Type": "application/json"}
def test_basic_graphql_query(client: TestClient, db_session: Session, simple_case) -> None:
'''It should return a case with only the requested fields'''
query = {
"q... |
from dataclasses import asdict, dataclass
import tornado.web
@dataclass
class Message:
author: str
text: str
timestamp: float
relative_timestamp: float
@property
def _type(self):
return "message"
def json(self) -> dict:
"""Return a JSON representation of this message"""
... |
from django.apps import AppConfig
class QaServerConfig(AppConfig):
name = "qa_server"
|
# coding: utf-8
from __future__ import absolute_import
from datetime import date, datetime # noqa: F401
from typing import List, Dict # noqa: F401
from spider.models.base_model_ import Model
from spider import util
class Dependenceitem(Model):
"""NOTE: This class is auto generated by the swagger code generat... |
"""Module for configuration"""
class Config:
"""Base Config class"""
DEBUG = False
TESTING = False
class DevelopmentConfig(Config):
"""Development DevelopmentConfig class"""
DEBUG = True
class TestingConfig(Config):
"""Development DevelopmentConfig class"""
DEBUG = True
TESTING = True... |
from dataclasses import dataclass
from productsimporter.parser.attribute import Attribute
@dataclass
class LanguageInfo:
id: str
short_cut: str
short_name: str
short_name_lowercase: str
name: str
@dataclass
class PathInfo:
picture_path: str
picto_path: str
@dataclass
class LookupTable:
... |
import spacy
from spacy import displacy
from subprocess import call
try:
NER = spacy.load("it_core_news_md")
except OSError:
print("SpaCy model not found. Downloading...")
call(["python", "-m", "spacy", "download", "it_core_news_md"])
NER = spacy.load("it_core_news_md")
input_file = "../output/Antipa... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'plantillas_interfaces/interfaz_frame_ver_registros.ui'
#
# Created by: PyQt4 UI code generator 4.11.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
exc... |
import verbose.embeds
import modules.games.counting
async def start_game(guild_id, message):
try:
game = message.content.split(" ")[2]
except IndexError:
await message.channel.send(embed=verbose.embeds.embed_error_message("Must specify a game."))
return
if game == "counting":
... |
# -*- coding: utf-8 -*-
import logging
import requests
import time
import struct
from .basemonitor import BaseMonitor
from ..keys import PublicKey
from ..serialize import Serialize
from ..transaction import TransactionPrevOut, TransactionInput
from ..wallet import Spend
from ..script import Script
from ..script impo... |
import os
import unittest
import vtk, qt, ctk, slicer
from slicer.ScriptedLoadableModule import *
import logging
#
# SlicerOrientationSelectorTest
#
class SlicerOrientationSelectorTest(ScriptedLoadableModule):
"""Uses ScriptedLoadableModule base class, available at:
https://github.com/Slicer/Slicer/blob/master/Ba... |
# Copyright (c) 2013 OpenStack Foundation.
# 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... |
# Copyright 2012 Anton Beloglazov
#
# 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... |
from allennlp.data.fields.field import DataArray, Field
class SequenceField(Field[DataArray]):
"""
A `SequenceField` represents a sequence of things. This class just adds a method onto
`Field`: :func:`sequence_length`. It exists so that `SequenceLabelField`, `IndexField` and other
similar `Fields` c... |
# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
import requests
import os
import os.path
class Tryon1Pipeline(object):
def process_item(self, item, spider):
deta... |
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision.transforms import Resize
from update import BasicUpdateBlock, SmallUpdateBlock, FlowHead
from extractor import BasicEncoder, SmallEncoder
from corr import CorrBlock, AlternateCorrBlock
from utils.utils import bilinea... |
import logging
import sys
class Logger():
"""
A custom class to handle all the logging needs.
Params:
name (str): name for the logger,you should pass __name__ generally.
std_out (bool): Logs the message to the stdout (console) also if set True.
log_file (str): custom log file to log all the me... |
#
# 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 "License"); you may not us... |
import os, shutil, time, datetime
from datetime import datetime
from shutil import copytree
savePath = "/Applications/autoBackup/"
path_to_watch = '/Volumes/'
before = dict ([(f, None) for f in os.listdir (path_to_watch)])
while True:
if os.path.exists("/applications/autoBackup/") == False:
os.makedirs(sa... |
#!/usr/bin/python
import os
import numpy as np
import sys
import argparse
from CarCNN import NeuralNet
from CarDetector import CarDetector
from PictureHeader import PictureHeader
from Utility import Utility
#from CarMxNet import NeuralNet as MXCNN
from ImagePreprocess import ImageDetector
from CarKNN import NearestNei... |
# ----------------------------------------------------------------------------
# Title: Scientific Visualisation - Python & Matplotlib
# Author: Nicolas P. Rougier
# License: BSD
# ----------------------------------------------------------------------------
# Illustrate alpha compositing (simulated)
# --------------... |
#
# PySNMP MIB module BW-BroadworksResourceAccess (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/BW-BroadworksResourceAccess
# Produced by pysmi-0.3.4 at Mon Apr 29 17:24:59 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python versio... |
"""Tests for `flowx/poisson/direct.py`."""
import numpy
import random
import unittest
import flowx
class TestPoissonDirect(unittest.TestCase):
"""Unit-tests for the Poisson Direct solver."""
def setUp(self):
"""Set up the grid and the variables of the Poisson system."""
center_vars = ["ivar... |
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, Activation, MaxPooling2D, Flatten, Dense
import matplotlib.pyplot as plt
import numpy as np
class Learner:
EPOCHS = 10 # Number of times to see the dataset
LEARNING_RATE = 0.01
def __init__... |
import torch
import torch.nn as nn
class MeshUnpool(nn.Module):
def __init__(self, unroll_target):
super(MeshUnpool, self).__init__()
self.unroll_target = unroll_target
def __call__(self, features, meshes):
return self.forward(features, meshes)
def pad_groups(self, group, unroll_... |
import uitl
import time
import torch
import numpy as np
from model import Net
from tensorboardX import SummaryWriter
if __name__ == '__main__':
opt = uitl.parser()
lr = opt.lr
view = opt.view
alpha = opt.alpha
epochs = opt.epochs
network = opt.network
gpu_ids = opt.gpu_ids
... |
from pwn import *
sh = process("./3x17")
#sh = remote("chall.pwnable.tw", 10105)
fini_addr = 0x00000000004b40f0
main = p64(0x0000000000401b6d)
call_fini = p64(0x0000000000402960)
pop_rdi = 0x0000000000401696 # pop rdi; ret;
pop_rdx_rsi = 0x000000000044a309 # pop rdx; pop rsi; ret;
pop_rax = 0x000000000041e4a... |
import docker
import traceback
import os
import logging
import argparse
from helpers import get_auth_session, retry_with_backoff
from generate import Generate
from time import sleep
parser = argparse.ArgumentParser(description='PyLogger Generator')
def add_args():
parser.add_argument(
'version', type=s... |
import base64
from io import BytesIO
from pathlib import Path
from PIL import Image, ImageDraw, UnidentifiedImageError
from nonebot.log import logger
from typing import Tuple, Union, Optional, Literal
from .util import load_font
import asyncio
class BuildImage:
def __init__(
self,
w: int,
... |
from typing import Optional, Dict, Any
from pyoembed import oEmbed, PyOembedException
import json
def get_oembed_data(url: str,
maxwidth: Optional[int]=640,
maxheight: Optional[int]=480) -> Optional[Dict[str, Any]]:
try:
data = oEmbed(url, maxwidth=maxwidth, maxheigh... |
import pytest
from monopoly_deal.cards import deck, Color
from monopoly_deal.game import Board
def test_find_cash_to_pay_bill_up_to_amount():
board = Board(cash_cards=(deck[99], deck[100]), property_sets=tuple()) # $3 and $2
cash_cards = board.find_cash_to_pay_bill_up_to_amount(bill_amount=3)
assert len... |
# coding:utf-8
import numpy as np
from numpy.testing import assert_almost_equal
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_boston
from sklearn.ensemble import RandomForestRegressor
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_err... |
# cython: language_level=3
# -*- coding: utf-8 -*-
# *****************************************************************************
# Copyright (c) 2016-2020, Intel Corporation
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the fo... |
# -*- coding: utf-8 -*-
import scrapy
from scrapy.selector import Selector
from scrapy_selenium import SeleniumRequest
from selenium.webdriver.common.keys import Keys
import csv
class GsearchSpider(scrapy.Spider):
name = 'gsearch'
# allowed_domains = ['www.google.com']
# start_urls = ['https://www.goo... |
# Generated by Django 3.1.2 on 2020-11-16 16:06
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('order', '0005_orders_productimage'),
]
operations = [
migrations.RemoveField(
model_name='orders',
name='produ... |
# -*- coding: utf-8 -*-
"""
Created on Thu Jul 11 12:12:38 2019
After an example of Jason Brownlee:
https://machinelearningmastery.com/handwritten-digit-recognition-using-convolutional-neural-networks-python-keras/
@author: timvmou
"""
# Larger CNN for the MNIST Dataset
import numpy
import git
from keras.datasets i... |
import warnings
from webob import exc
from .secure import handle_security, cross_boundary
from .util import iscontroller, getargspec, _cfg
__all__ = ['lookup_controller', 'find_object']
class PecanNotFound(Exception):
pass
class NonCanonicalPath(Exception):
'''
Exception Raised when a non-canonical p... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from collections import Counter
def dict_to_md(mydict):
for key, value in sorted(mydict.items(), key=lambda x: x[0]):
print '#', key
print
s = [', '.join(v) for v in sorted(value, key=lambda x: x[0])]
counted = Counter(s)
for e... |
c='p'
print(ord(c)) |
def keyword_in_mylibdir_subpackage2_package():
pass
|
from IGParameter import *
from PIL import Image
import copy
class IGParameterInteger(IGParameter):
def __init__(self):
super().__init__("Integer")
self._value["value"] = 0
@property
def value(self):
return self._value["value"]
@value.setter
def value(self, value):
... |
#
# Copyright (C) 2021 Pedro Garcia Freitas <pdr.grc.frts@gmail.com>
#
# This is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3, or (at your option)
# any later version.
#
# This software is dis... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""从汉典网按 unicode 编码获取汉字及发音"""
import io
import re
import sys
from time import sleep
from bs4 import BeautifulSoup
import requests
class Message(object):
def __init__(self, file_name):
self.f = io.open(file_name, 'w', encoding='utf8')
def write(self, ms... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.