content
stringlengths
5
1.05M
# Copyright (C) 2015 Haruhiko Matsuo <[email protected]> # # Distributed under the MIT License. # See accompanying file LICENSE or copy at # http://opensource.org/licenses/MIT """Decorators""" from functools import wraps from itertools import product import numpy as np def tag_maker(counter_method): """T...
from django.apps import AppConfig class HTMLBlockConfig(AppConfig): name = 'glitter.blocks.html' label = 'glitter_html'
"""Discover LG WebOS TV devices.""" from netdisco.util import urlparse from . import SSDPDiscoverable # pylint: disable=too-few-public-methods class Discoverable(SSDPDiscoverable): """Add support for discovering LG WebOS TV devices.""" def info_from_entry(self, entry): """Return the most important in...
from __future__ import annotations from abc import ABCMeta from collections.abc import Mapping, Set, AsyncGenerator from contextlib import closing, asynccontextmanager, AsyncExitStack from typing import Final from pymap.context import cluster_metadata, connection_exit from pymap.exceptions import InvalidAuth, Respon...
# -*- coding: utf-8 -*- """ Created on Sun Aug 12 00:01:10 2018 @author: deanecke """ import pandas as pd import numpy as np import os from sklearn import tree, ensemble from sklearn.preprocessing import MinMaxScaler from sklearn.ensemble import BaggingClassifier, AdaBoostClassifier from sklearn.utils impo...
from .Derivative import * from .Series import * from .FunctionCall import * from .UnaryFormatting import * from .Arithmatic import *
import numpy as np import tensorflow as tf import matplotlib.pyplot as plt from datetime import datetime from vggface2_datagen import genid from model import build_rec_model np.set_printoptions(threshold=np.inf, linewidth=np.inf) img_dir_path = '../datasets/vggface2/train_refined_resized/' test_anno_file_path = 'ann...
#MenuTitle: Copy Download URL for Current App Version # -*- coding: utf-8 -*- from __future__ import division, print_function, unicode_literals __doc__=""" Puts the download URL of the current Glyphs app version into your clipboard for easy pasting. """ from AppKit import NSPasteboard, NSStringPboardType def setClipb...
#!/usr/bin/env python3 # coding: utf-8 # PSMN: $Id: get_serial.py 2997 2020-09-23 13:14:12Z ltaulell $ # SPDX-License-Identifier: CECILL-B OR BSD-2-Clause """ POC: use execo to get chassis serial number from host(s) quick & dirty return a list of comma separated serial numbers """ import argparse import execo fro...
#!/usr/bin/env python # -*- coding: UTF-8 -*- import warnings import threading import numpy import scipy.optimize import pyFAI FIT_PARAMETER = ['wavelength', 'distance', 'center_x', 'center_y', 'tilt', 'rotation'] LN_2 = numpy.log(...
class Tuner: def __init__(self, desc): self.description = desc self.frequency = 0 def on(self): print(f'{self.description} on.') def off(self): print(f'{self.description} off.') def set_frequency(self, frequency): print(f'{self.description} setting frequency to...
from typing import List Vector = List[float] height_weight_age = [70, # inches, 170, # pounds, 40 ] # years grades = [95, # exam1 80, # exam2 75, # exam3 62 ] # exam4 def add(v: Vector, w: Vector) -> Vector: """Adds corresponding el...
import sys __all__ = ['__version__', 'version_info'] import pkgutil __version__ = pkgutil.get_data(__package__, 'VERSION').decode('ascii').strip() version_info = tuple(int(v) if v.isdigit() else v for v in __version__.split('.')) del pkgutil if sys.version_info < (2, 7): print("os-tornado %s ...
from datetime import timedelta from django.conf import settings from django_statsd.clients import statsd from google.cloud import bigquery from olympia.constants.applications import ANDROID, FIREFOX # This is the mapping between the AMO usage stats `sources` and the BigQuery # columns. AMO_TO_BQ_DAU_COLUMN_MAPPING =...
import codecs from typing import Optional, Tuple, Iterable from unicodedata import normalize from dedoc.data_structures.paragraph_metadata import ParagraphMetadata from dedoc.data_structures.unstructured_document import UnstructuredDocument from dedoc.readers.base_reader import BaseReader from dedoc.readers.utils.hie...
class Solution(object): def convert(self, s: str, numRows: int) -> str: """ The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility) P A H N A P L S I I ...
import requests import json import pandas as pd # URL of the authentication endpoint auth_url = "https://api.hatebase.org/4-4/authenticate" # initialize authentication payload & headers # use x-www-form-urlencoded as content-type # replace this dummy key with your own auth_payload = "api_key=[API KEY GOES HERE]" he...
import yaml import numpy as np class setup: def __init__(self, setup): with open(setup,'r') as obj: input=yaml.safe_load(obj) print('loaded calculation setups:') print(input) self.structure_file=input['structure_file'] self.dyn_file=input['dyn_file'] self....
""" 校内打卡相关函数 @create:2021/03/10 @filename:campus_check.py @author:ReaJason @email_addr:[email protected] @blog_website:https://reajason.top @last_modify:2021/03/15 """ import time import json import requests from setting import log def get_id_list_v2(token, custom_type_id): """ 通过校内模板id获取校内打卡具体的每个时间段id :...
#MIT License # #Copyright (c) 2021 Nick Hurt # #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 rights #to use, copy, modify, merge, publish,...
import pytest from app.tools.utils import get_domain_name class TestGetDomainName: @pytest.fixture def item_source_domain_pairs(self, scraped_item_source_data): return [ (itm['url'], src['domain']) for itm, src in scraped_item_source_data ] def test_domain_getter_util(self, ...
import threading from orchestrator.Task import Task class Orchestrator: def __init__(self): self._tasks = [] self._semaphore = threading.Semaphore(2) def run_task(self, task: Task) -> None: self._tasks += [task] task.append_on_finish_event(lambda: self._when_task_is_terminate...
from django.conf import settings from django.utils.six import string_types from django.utils.translation import ugettext_lazy as _ _DEFAULT_KINDS = { "other": 0, "audit": 1, "edit": 2, "deletion": 3, "note": 4, "email": 5, "warning": 6, "error": 7 } _DEFAULT_KIND_LABELS = { "other"...
# Generated by Django 3.2.13 on 2022-05-10 15:20 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('ask_cfpb', '0039_2022_squash'), ] operations = [ migrations.RemoveField( model_name='answerpage', name='user_feedback', ...
## # File: MultiProcUtilTests.py # Author: jdw # Date: 17-Nov-2018 # # Updates: # ## """ """ __docformat__ = "restructuredtext en" __author__ = "John Westbrook" __email__ = "[email protected]" __license__ = "Apache 2.0" import logging import random import re import unittest from rcsb.utils.multiproc.Mul...
"""Logic for comparing DICOM data sets and data sources""" from copy import deepcopy from hashlib import sha256 from typing import Optional, List from pydicom import Dataset, DataElement from pydicom.tag import BaseTag def _shorten_bytes(val: bytes) -> bytes: if len(val) > 16: return b"*%d bytes, hash =...
# -*- coding: utf-8 -*- # @Time : DATE:2021/10/7 # @Author : yan # @Email : [email protected] # @File : 07_supervoxel_clustering.py import pclpy from pclpy import pcl import numpy as np import sys if __name__ == '__main__': if len(sys.argv) < 2: print("Syntax is: %s <pcd-file> \n" % sys.argv[0], ...
import pybullet as p from time import sleep import pybullet_data physicsClient = p.connect(p.GUI) p.setAdditionalSearchPath(pybullet_data.getDataPath()) p.resetSimulation(p.RESET_USE_REDUCED_DEFORMABLE_WORLD) p.resetDebugVisualizerCamera(4,-40,-30,[0, 0, 0]) p.setGravity(0, 0, -10) tex = p.loadTexture("uvmap.png") ...
from nltk import word_tokenize, sent_tokenize import networkx as nx import enchant import numpy as np from scipy import stats as st import matplotlib.pyplot as plt from itertools import * from tqdm import tqdm_notebook import re import RAKE from ripser import ripser import spacy from nltk.corpus import brown nlp = spa...
""" Contains the views and routes used by the Flask-webserver. """ from flask import (render_template, send_from_directory, Response, session, redirect, request, url_for, flash) from .app import app import os import functools from playhouse.flask_utils import object_list, get_object_or_404 from ...
#!/usr/bin/env python # coding: utf-8 import os import sys import multiprocessing as mp import threading import time import pandas as pd import numpy as np import scipy.stats as st from tqdm import tqdm #sys.path.append('./../dgonza26/infinity-mirror') sys.path.append('./../..') from src.graph_comparison import Gra...
# Time: O(n) # Space: O(1) # 995 # In an array A containing only 0s and 1s, a K-bit flip consists of choosing a (contiguous) subarray # of length K and simultaneously changing every 0 in the subarray to 1, and every 1 in the subarray to 0. # # Return the minimum number of K-bit flips required so that there is no 0 in...
from PIL import Image def cat(im1: Image, im2: Image, dim: tuple, append_on: tuple): ''' Concatenates two images together im1 : PIL.Image of the first image im2 : PIL.Image of the second image dim : Dimensions of the output image append_on : Dimensions on where to past...
# -*- coding: utf-8 -*- """ Copyright 2022 Mitchell Isaac Parker 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 ...
import pytest from dask.distributed import Client from dask_kubernetes.experimental import KubeCluster @pytest.fixture def cluster(kopf_runner, docker_image): with kopf_runner: with KubeCluster(name="foo", image=docker_image) as cluster: yield cluster def test_kubecluster(cluster): wit...
# Top k (soft criteria) k = 10 # Max top (hard criteria) maxtop = 3 # Number of examples per image g = 8 # Run through the adjacency matrix softcorrect = 0 hardcorrect = 0 totalnum = 0 for j, i in enumerate(F): if ((j-1) % g) == 0: continue topk = i.argsort()[-k:] # Soft criteria if j/g in topk...
# -*- coding: utf-8 -*- import os.path import shutil from django.db.models import Q from django.urls import reverse_lazy from django.http import HttpResponseRedirect from django.views.generic import CreateView, ListView, DeleteView from django.core.paginator import Paginator from tool.forms.xray_from import XrayTaskF...
from django.conf.urls import url from django.conf import settings from django.conf.urls.static import static from . import views from django.conf.urls import include from django.contrib import admin from django.contrib.auth import views as auth_views urlpatterns = [ url(r'^$', views.recipe_list, name='recipe_list'),...
import argparse import os import sys from comet_ml import Experiment, ExistingExperiment import torch from torch.utils.data import DataLoader from data.dataloader import DatasetFactory from runner import ImprovedVideoGAN def get_parser(): global parser parser = argparse.ArgumentParser(description='VideoGAN'...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Apr 10 12:52:42 2021 @author: jasperhajonides """ from sklearn.model_selection import train_test_split from tools.sliding_window import sliding_window from custom_classifier import sample_data from custom_classifier.custom_classification import Custom...
# coding: utf-8 """A SRU client. :copyright: Copyright 2020 Andreas Lüschow """ import inspect import logging import time import requests from srupy.iterator import BaseSRUIterator, SRUResponseIterator from srupy.response import SRUResponse from .models import Explain logger = logging.getLogger(__name__) class SR...
from django.shortcuts import render from .models import * from .tables import * from .tables import Rank_awpTable, Rank_retakeTable from .filters import Rank_awpFilter, Rank_retakeFilter from django.views.generic import TemplateView from django_filters.views import FilterView from django_tables2.views import SingleTa...
BBS_V1 = { "@context": { "@version": 1.1, "id": "@id", "type": "@type", "BbsBlsSignature2020": { "@id": "https://w3id.org/security#BbsBlsSignature2020", "@context": { "@version": 1.1, "@protected": True, "id": "@...
#!/usr/bin/env python3 import gemmi import copy import numpy as np from scipy.spatial import distance import string from rdkit import Chem from rdkit.Geometry import Point3D import warnings from . import xyz2mol import argparse def parse_arguments(): """ Parse command line arguments. """ parser =...
from django.shortcuts import render from rest_framework import serializers, viewsets from .serializers import AttributeSerializer from .models import * from PIL.Image import new from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt from django.views.generic import View, FormView, Temp...
# coding: utf-8 from __future__ import absolute_import import unittest from flask import json from six import BytesIO from openapi_server.models.feedback import Feedback # noqa: E501 from openapi_server.models.feedback_response import FeedbackResponse # noqa: E501 from openapi_server.models.result import Result #...
""" ******************************************************************************** main file to execute your program ******************************************************************************** """ import time import numpy as np import tensorflow as tf from pinn import PINN from config_gpu import config_gpu fro...
from functools import partial from wai.annotations.core.component import ProcessorComponent from wai.annotations.core.stream import ThenFunction, DoneFunction from wai.annotations.core.stream.util import RequiresNoFinalisation from wai.annotations.domain.image.object_detection import ImageObjectDetectionInstance from ...
import re # Utility class with useful functions that do not belong to a specific component of the Enigma Machine. class Util: alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' alphabetPos = [] for i in range(0, len(alphabet)): alphabetPos.append(alphabet[i]) # Converts a letter of the alphabet to its nu...
import sys ifunc, g = lambda: [*map(int, sys.stdin.readline().rstrip().split())], range n = ifunc() iList = ifunc() iList = sorted(iList) ret = [-1, -1, -1] minMinDiff = 10**10 for idx in g(len(iList)-2): tar = -iList[idx] le = idx+1 ri = len(iList)-1 tarLe, tarRi = -1, -1 minDiff = 10**10 ...
# -*- coding: utf-8 -*- # Copyright (c) 2012-2015, Anima Istanbul # # This module is part of anima-tools and is released under the BSD 2 # License: http://www.opensource.org/licenses/BSD-2-Clause import sys import maya.OpenMaya as OpenMaya import maya.OpenMayaMPx as OpenMayaMPx kPluginNodeTypeName = "spClosestPointO...
import sys sys.path.append(r"C:\Program Files\Python 3.5\lib\site-packages") import matplotlib.pyplot as plt print(sys.path) plt.plot([1, 2, 3, 7, 9, 23, 32, 12], [2, 1, 3, 32, 11, 5, 65, 43]) plt.show()
# -*- coding: utf8 -*- # Copyright (C) 2013 Daniel Lombraña González # # This program 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 of the License, or # (at your option) any later version. #...
#!/usr/bin/env python3 import autopipe if __name__ == "__main__": exit(autopipe.main())
from django.contrib.sitemaps import Sitemap from django.core.urlresolvers import reverse from .models import Product, Category class HomeSitemap(Sitemap): changefreq = "weekly" priority = 0.7 def items(self): return ['product:home'] def location(self, obj): return reverse(obj) class ...
# Generated by Django 3.2.5 on 2021-08-12 07:51 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('school', '0007_alter_studentlist_child'), ] operations = [ migrations.AlterField( model_name='s...
from opendc.models.model import Model from opendc.models.user import User from opendc.util.exceptions import ClientError from opendc.util.rest import Response class Prefab(Model): """Model representing a Project.""" collection_name = 'prefabs' def check_user_access(self, google_id): """Raises an...
import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim import time import argparse import numpy as np from scipy.sparse import csr_matrix import pandas as pd import logging from sklearn.decomposition import TruncatedSVD from sklearn.linear_model import LinearRegres...
# Allow slice-creator to change their slice even after other users voted for it # Slices are un-modifiable # If user changes their slice, create new slice record # Deduplicate slice-records by content # Remove the slice-record if votes=0 and fromEditPage=false # Also allows user to vote for slice that was cha...
# -*- coding: utf-8 -*- import os from datetime import date, datetime, timedelta from django.conf import settings from django.core.files.storage import default_storage as storage from django.core.management import call_command from django.core.management.base import CommandError import mock from nose.tools import eq_...
# Copyright 2020 Maintainers of OarphPy # # 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 ...
""" The intention of this script is to provide a demonstration of how ConFlowGen is supposed to be used as a library. It is, by design, a stateful library that persists all input in an SQL database format to enable reproducibility. The intention of this demo is further explained in the logs it generated. """ import da...
import pickle import numpy as np import pandas as pd import ssms import argparse def none_or_str(value): print('none_or_str') print(value) print(type(value)) if value == 'None': return None return value def none_or_int(value): print('none_or_int') print(value) print(type(value)...
from . import base class Error(base.Event): pass class ConnectNotAvailable(Error): def __str__(self): return "connect not available." class VPNClientStateNotConnected(Error): def __str__(self): return "vpn client state is not connected" class ConnectAlreadyInProgress(Error): def ...
""" This problem was asked by Amazon. Implement a stack that has the following methods: push(val), which pushes an element onto the stack pop(), which pops off and returns the topmost element of the stack. If there are no elements in the stack, then it should throw an error or return null. max(), ...
from flask import Flask from flask_bootstrap import Bootstrap from flask_login import LoginManager from .config import Config from .auth import auth from .models import UserModel login_manager = LoginManager() login_manager.login_view = 'auth.login' # Para cuadno flask_login quiera cargar un usuario @login_manager....
""" Wrapper for `git diff` command. """ from textwrap import dedent from diff_cover.command_runner import CommandError, execute class GitDiffError(Exception): """ `git diff` command produced an error. """ class GitDiffTool: """ Thin wrapper for a subset of the `git diff` command. """ d...
from pathlib import Path import pytest @pytest.fixture(scope="session") def tests_dir(): return Path(__file__).parent.resolve()
########################################################################## # # Copyright (c) 2015, Image Engine Design Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistrib...
from typing import Optional from anyio import to_thread from github import Github from github.Label import Label from github.Repository import Repository from Shared.functions.readSettingsFile import get_setting _REPO: Optional[Repository] = None _LABELS: Optional[list[Label]] = None async def get_github_repo() ->...
import json import pandas as pd import sqlite3 conn = sqlite3.connect('hackernews.sqlite3') curs = conn.cursor() query = '''SELECT author, count(author), sentiment FROM comments GROUP BY author HAVING count(author) >= 50 ORDER BY sentiment LIMIT 10''' curs.execute(query) results = curs.fetchall() df = pd.D...
import os import numpy as np os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # for ignoring the some of tf warnings import tensorflow as tf from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint, TensorBoard from sklearn.model_selection import train_test_split from src.CNN_classification import network from ...
from setuptools import setup, find_packages setup( name = 'port_dashboard', version = '1.0', packages = find_packages(), package_data = { '': ['LICENSE', 'README.md'], }, # PyPI metadata description = 'generate a port to-do list from C preprocessor macros', author = 'Michael L...
import scipy def sparseCheck(features, labels): features = features labels = labels """ Takes features and labels as input and checks if any of those is sparse csr_matrix. """ try: print('Checking for Sparse Matrix [*]\n') if scipy.sparse.issparse(features[()]): pri...
{%- if cookiecutter.add_graphiql_route == "yes" -%} from .graphiql import handle_graphiql {% endif -%} from .graphql import handle_graphql {%- if cookiecutter.add_health_routes == "yes" %} from .health import ( handle_live as handle_health_live, handle_ready as handle_health_ready, ) {%- endif %} __all__ = ( ...
from datetime import datetime from cred.database import db class Event(db.Model): __tablename__ = 'event' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(240)) location = db.Column(db.String(240)) action = db.Column(db.String(240)) value = db.Column(db.String(240)) ...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- ################################################## # GNU Radio Python Flow Graph # Title: Top Block # Generated: Wed Feb 14 21:28:23 2018 ################################################## if __name__ == '__main__': import ctypes import sys if sys.platform.sta...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Oct 11 10:31:47 2021 @author: nd """ import sys import re from .build_struts import * # add file names here ## origin file #file_in = sys.argv[1] ## output file file_out = "_output.txt" # read in file def file_read(file_in): ...
# # Test solvers give the same output # import pybamm import numpy as np import unittest import liionpack as lp class TestSolvers(unittest.TestCase): def test_consistent_results_1_step(self): Rsmall = 1e-6 netlist = lp.setup_circuit( Np=1, Ns=1, Rb=Rsmall, Rc=Rsmall, Ri=5e-2, V=4.0, I...
#!/usr/bin/env python2.7 # -*- coding: UTF-8 -*- from sys import stdin from collections import defaultdict import re def main(): list = [] for l in stdin: # every line in the input text = l.decode('utf8') # decode from utf-8 encoded string text = text.rstrip('\n') # strip newline...
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def isBalanced(self, root: TreeNode) -> bool: return self.depth(root) != -1 def depth(self, root): if not root: return 0 left = self.depth(roo...
from datetime import ( datetime ) from pydantic import ( BaseModel ) from typing import ( Optional, List, ) __all__ = [ "Company", ] class Value(BaseModel): value: str enum_id: Optional[int] = None enum_code: Optional[str] = None class CustomFieldValue(BaseModel): field_id: int...
#!/usr/bin/env python # -*- encoding: utf-8 -*- """ Topic: 利用generator模仿tail -f www.log | grep "python" 对变化的日志文件持续查看含有python的行 Desc : """ import time __author__ = 'Xiong Neng' def tail(f): f.seek(0, 2) # 移动到EOF while True: line = f.readline() if not line: ...
from ibis.tests.expr.mocks import BaseMockConnection class MockImpalaConnection(BaseMockConnection): @property def dialect(self): from ibis.backends.impala.compiler import ImpalaDialect return ImpalaDialect def _build_ast(self, expr, context): from ibis.backends.impala.compiler i...
##Here we plot distributrions of how many individuals were correct for each states. import seaborn as sns import matplotlib.pyplot as plt import numpy as np from scipy.stats import gaussian_kde pal = sns.diverging_palette(10, 220, sep=80, n=5,l=40,center='light') pal2 = sns.diverging_palette(10, 220, sep=80, n=5,l=40,...
class Solution(object): def XXX(self, root): if not root: return 0 return max(self.XXX(root.left), self.XXX(root.right)) + 1
from bs4 import BeautifulSoup import requests import time def get_movie_budgets( page_index): r = requests.get('https://www.the-numbers.com/movie/budgets/all/%s'% (page_index,)) html_doc = r.content soup = BeautifulSoup(html_doc, 'html.parser') rows = [tr for tr in soup.find_all('tr') if len(tr) == ...
class Transformer(object): def __init__(self, pc=None): self.pc = pc def transform_jump(self, cond, true_path, false_path, **kwargs): return None def transform_ret(self, ret_value, **kwargs): return None def transform_branch(self, cond, true_path, false_path, **kwargs): ...
# Generated by Django 3.2 on 2021-05-01 08:58 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('store', '0001_initial'), ] operations = [ migrations.RenameField( model_name='category', old_name='website_category', ...
# coding=UTF-8 #------------------------------------------------------------------------------ # Copyright (c) 2007-2016, Acoular Development Team. #------------------------------------------------------------------------------ # separate file to find out about version without importing the acoular lib __author_...
# Copyright 2000 - 2013 NeuStar, Inc.All rights reserved. # NeuStar, the Neustar logo and related names and logos are registered # trademarks, service marks or tradenames of NeuStar, Inc. All other # product names, company names, marks, logos and symbols may be trademarks # of their respective owners. __author__ = 'Jon...
import visitors.visitor as visitor from pipeline import State from cl_ast import * class FormatVisitor(State): def __init__(self, sname, fname): super().__init__(sname) self.fname = fname def run(self, ast): printed_ast = self.visit(ast) f = open(self.fname, 'w') f.writ...
import requests import math import os import time import lxml.html PROXY_TXT_API = 'https://www.proxyscan.io/api/proxy?type=https&format=txt&uptime=100' PLATFORM = os.name def get_proxy(): ''' Get proxy (str) from API. ''' proxy = requests.get(PROXY_TXT_API).text return proxy.rstrip() def convert...
import time import RPi.GPIO as GPIO GPIO.setmode(GPIO.BCM) digitBitmap = {0: 0b00111111, 1: 0b00000110, 2: 0b01011011, 3: 0b01001111, 4: 0b01100110, 5: 0b01101101, 6: 0b01111101, 7: 0b00000111, 8: 0b01111111, 9: 0b01100111} masks = {'a': 0b00000001, 'b': 0b00000010, 'c': 0b00000100, 'd': 0b000...
import tkinter as tk class SimpleTableInput(tk.Frame): def __init__(self, parent, rows, columns): tk.Frame.__init__(self, parent) self._entry = {} self.rows = rows self.columns = columns # register a command to use for validation vcmd = (self.register(se...
from __future__ import absolute_import from __future__ import unicode_literals from couchexport.export import get_writer class WorkBook(object): _undefined = '---' @property def undefined(self): return self._undefined def __init__(self, file, format): self._headers = {} self....
from django_elasticsearch_dsl_drf.serializers import DocumentSerializer from rest_framework import serializers from radical_translations.core.documents import ResourceDocument class ResourceDocumentSerializer(DocumentSerializer): highlight = serializers.SerializerMethodField() class Meta: document =...
from afterpay.exceptions.afterpay_error import AfterpayError class ServerError(AfterpayError): """ A common cause of this response from PUT/POST endpoints is that the request body is missing or empty. """ pass
#!/usr/bin/env python # -*- coding: utf-8 -*- # Author: Yuki Furuta <[email protected]> import chainer import chainer.links as L import chainer.functions as F from ... import links class DeepEpisodicMemoryDecoder(chainer.Chain): """Deep Episodic Memory Decoder""" def __init__(self, num_epi...
import shutil import pytest from jupytext import read from jupytext.cli import jupytext from .utils import requires_ir_kernel, requires_nbconvert, skip_on_windows @requires_nbconvert @skip_on_windows def test_pipe_nbconvert_execute(tmpdir): tmp_ipynb = str(tmpdir.join("notebook.ipynb")) tmp_py = str(tmpdir...