content
stringlengths
5
1.05M
import numpy as np import pandas as pd from parallelm.components import ConnectableComponent class RandomDataframe(ConnectableComponent): """ Generating a random dataframe. The number of rows and columns is provided as input parameters to the component """ def __init__(self, engine): super(se...
from functools import lru_cache from operator import mul def parse_decks(filename): with open(filename) as file: player1_raw, player2_raw = file.read().split("\n\n") p1 = list(map(int, player1_raw.split("\n")[1:])) p2 = list(map(int, player2_raw.split("\n")[1:])) return p1, p2 def play_combat...
from tkinter import * import sqlite3 root=Tk() root.title(" DataBase Record ") root.geometry("400x600") root.iconbitmap('edit.ico') ''' # Create a Database or connect to one conn=sqlite3.connect('address_book.db') # Create cursor c = conn.cursor() # Create a Table c.execute("""CREATE TABLE addresses( fi...
def print_matrix(m): idx = 1 for r in m: if idx < 10: print(" ", idx, r) else: print(idx, r) idx += 1 print("-------------------") def nz_min(line): if len(line) == 0: return 0 line = [i for i in line if i != 0] if len(line) == 0: ...
#!/usr/bin/env python3 # Copyright (c) 2018 The Zcash developers # Copyright (c) 2020 The PIVX Developers # Copyright (c) 2020 The Deviant Developers # Distributed under the MIT software license, see the accompanying # file COPYING or https://www.opensource.org/licenses/mit-license.php . from test_framework.test_fram...
from collections import * from functools import lru_cache import heapq import itertools import math import random import sys # https://raw.githubusercontent.com/arknave/advent-of-code-2020/main/day18/day18.py def parse(eqn, is_part_2=False): eqn = eqn.replace("(", "( ") eqn = eqn.replace(")", " )") # acc...
import sys sys.path.append('..') import time import pygame from pygame import Rect, Color from pathfinder import PathFinder from gridmap import GridMap class Visualizer(object): def __init__(self, screen, field, message_func): self.screen = screen self.field = field self.message_func = m...
from datetime import timedelta from celery import Celery app = Celery('twitch', backend='db+sqlite:///celeryresdb.sqlite', broker='sqla+sqlite:///celerydb.sqlite', include=['tasks']) app.conf.CELERYBEAT_SCHEDULE = { 'clear-db': { 'task': 'twitch.clear_dbs', '...
from bokeh.io import export_png, output_file, show def _get_return(function, x, y, return_var): return_var.append(function(x, elapsed_time=y)) from tnetwork.DCD.analytics.dynamic_partition import * from nf1 import NF1 from sklearn.metrics import adjusted_rand_score,normalized_mutual_info_score import pandas as p...
from django.contrib import admin from submissions.models import Submission class SubmissionAdmin(admin.ModelAdmin): list_display = ("submitted_by", "status", "is_valid", "file_upload", "submitted_file_name", "group_submitted", "trigger", "entry_point", "datetime_submitted") ...
""" Stats 101 Based on the 10 Days of Statistics Tutorial see: https://www.hackerrank.com/domains/tutorials/10-days-of-statistics """ import random from collections import Counter from collections.abc import Sequence from fractions import Fraction from functools import reduce from operator import mul, itemgetter from ...
#!/usr/bin/env python # # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ # # Jiao Lin # California Institute of Technology # (C) 2007 All Rights Reserved # # {LicenseText} # # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~...
from django.urls import reverse from django.shortcuts import render from urllib.parse import urljoin LEGACY_PYTHON_DOMAIN = 'http://legacy.python.org' PYPI_URL = 'https://pypi.org/' def legacy_path(path): """Build a path to the same path under the legacy.python.org domain.""" return urljoin(LEGACY_PYTHON_DOM...
# check_cpu.py - An example Opsview plugin written with plugnpy from __future__ import print_function import plugnpy import psutil def get_cpu_usage(): """Returns CPU Usage %""" return psutil.cpu_percent(interval=2.0) def get_args(): """Gets passed arguments using plugnpy.Parser. This will exit 3 (...
from django.contrib import admin from apps.configuration.models import Project @admin.register(Project) class ProjectAdmin(admin.ModelAdmin): """ The representation of :class:`configuration.models.Project` in the administration interface. """ list_display = ('id', 'name', 'abbreviation', 'active'...
""" Contains the HappyGeneration class """ from dataclasses import dataclass from typing import List from transformers import AutoModelForCausalLM, TextGenerationPipeline from happytransformer.happy_transformer import HappyTransformer from happytransformer.gen.trainer import GENTrainer, GENTrainArgs, GENEvalArgs from h...
# # This file is part of PCAP BGP Parser (pbgpp) # # Copyright 2016-2017 DE-CIX Management GmbH # Author: Christopher Moeller <[email protected]> # # 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...
import os import sqlite3 as sql from flask import Flask, render_template, request, g, url_for, redirect from gerrymander_app.db import get_db from wtforms import form import pdb app = Flask(__name__) def district_info(): db = get_db() """query to get random district id""" random_district_id = db.execute("SELECT ...
import onmt import torch import torch.nn as nn if __name__ == "__main__": from onmt.models.multilingual_translator.reversible_transformers import reversible_encoder, \ ReversibleTransformerEncoderLayer from onmt.models.multilingual_translator.reversible_transformers import reversible_decoder, \ ...
import os import sys import time import cv2 import matplotlib.pyplot as plt import numpy as np from pathlib import Path sys.path.append(os.path.join(Path().resolve(), '../../../python')) import jellypy # Video Write-DMA REG_VIDEO_WDMA_CORE_ID = 0x00 REG_VIDEO_WDMA_VERSION = 0x01 REG_V...
from collections import namedtuple SrcTile = namedtuple('SrcTile', 'bbox f img scale') class BBOX(namedtuple('BBOX_base', 'x y w h')): """ Represents a bounding box as something more specific than a shapely polygon Units are usually northing and easting. """ @classmethod def with_xyxy(_cls, x1, ...
from smbus import SMBus bus = SMBus(1) address = 0x48 def get_temp(): data = bus.read_i2c_block_data(0x48, 0x00, 2) data[0] = data[0] * 256 temperature = data[0] + data[1] temperature = (temperature >> 4) * 0.0625 return(temperature)
# -*- encoding:utf-8 -*- """ company:IT author:pengjinfu project:migu time:2020.5.7 """
import sqlite3 import db_tools as db db_file = 'db/pyolo.db' db.create_connection(db_file) db.initialize_tables(db_file)
import requests import json import logging import traceback import datetime import time import pandas as pd log_fmt = '%(asctime)s- %(name)s - %(levelname)s - %(message)s' logging.basicConfig(format=log_fmt, level=logging.DEBUG) class Db2dataTool: userid = None passwd = None dbname = None crn = None ...
import unittest from impbot.connections import twitch_webhook class TestTwitchWebhookConnection(unittest.TestCase): def test_topic(self): link = ( '<https://api.twitch.tv/helix/webhooks/hub>; rel="hub", ' '<https://api.twitch.tv/helix/streams?user_id=1234>; rel="self"') se...
import tempfile import os from PIL import Image from django.contrib.auth import get_user_model from django.test import TestCase from django.urls import reverse from rest_framework import status from rest_framework.test import APIClient from core.models import Post, Tag from post.serializers import PostSerializer, P...
"""Quantum Inspire library Copyright 2019 QuTech Delft qilib is available under the [MIT open-source license](https://opensource.org/licenses/MIT): 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 Softwar...
#!/usr/bin/python # -*- coding: UTF-8 -*- # licensed under CC-Zero: https://creativecommons.org/publicdomain/zero/1.0 import requests import json import pywikibot from pywikibot.data import api site = pywikibot.Site('wikidata', 'wikidata') site.login() repo = site.data_repository() site.get_tokens('edit') ERROR_THR...
# Copyright (c) Meta Platforms, Inc. and affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. from typing import Set, Tuple from . import DictEntries, ParseIssueTuple, PipelineStep, Summary class WarningCodeFilter(PipelineStep[Dict...
from aacharts.aachartcreator.AAChartModel import AAChartModel from aacharts.aachartcreator.AASeriesElement import AASeriesElement from aacharts.aaenum.AAEnum import AAChartType, AAChartAnimationType, AAChartSymbolType, AAChartSymbolStyleType from aacharts.aatool.AAGradientColor import AAGradientColor, AALinearGradientD...
from adafruit_circuitplayground.express import cpx while True: if cpx.button_a: cpx.play_tone(262, 1) if cpx.button_b: cpx.play_tone(294, 1)
import os import re import matplotlib.pyplot as plt def get_root_dir(): return input("Enter root_dir: ") def get_user_input(): return input("Enter keyword: ") def find_files(): root_dir = get_root_dir() keyword = re.compile(get_user_input()) files_found = {} for (dirpath, dirnames, filenames...
from socketclient.SocketClient import SocketClient from socketclient.SocketPool import SocketPool from socketclient.Connector import Connector, TcpConnector
# -*- coding: utf-8 -*- from scrapy_redis.spiders import RedisCrawlSpider from crawler.items import ArticleItem class Game17373Spider(RedisCrawlSpider): name = 'game_17373' allowed_domains = ['news.17173.com'] redis_key = '17373_game:start_urls' custom_settings = { 'ITEM_PIPELINES' : { ...
"""Sensor from an SQL Query.""" import datetime import decimal import logging import sqlalchemy from sqlalchemy.orm import scoped_session, sessionmaker import voluptuous as vol from homeassistant.components.recorder import CONF_DB_URL, DEFAULT_DB_FILE, DEFAULT_URL from homeassistant.components.sensor import PLATFORM_...
import os from multiprocessing import Process, Pool, Value, Lock from ctypes import c_int import subprocess from datetime import datetime import time from io import StringIO from vncdotool import api import argparse parser = argparse.ArgumentParser(description="Open/Unsafe VNC Scraper") parser.add_argument("-input", ...
from django.contrib import admin from .models import Assignments # Register your models here. admin.site.register(Assignments)
import ldap3, json def makeOrganogram(staff): connection = make_connection() organogram = {} for uid in staff.nList: employees = query_cdr(connection, staff.person[uid]["Email"], "eMail") emList = [] for employee in employees: ee = employee.decode() fID = ee....
def generate_project_params(runlevel): """Returns the project-specific params.""" params = {} return params def generate_project_users(runlevel): origin = 'nest' users = [ { 'username': 'demouser', 'password': 'GARBAGESECRET', 'given_name': 'ARI', ...
import enum import logging import numpy as np import sympy as sp class TrajectoryType(enum.Enum): VELOCITY = 2 ACCELERATION = 4 JERK = 6 SNAP = 8 class MininumTrajectory: def __init__(self, trajtype: TrajectoryType): numcoeffs = trajtype.value logging.info(f'Creating minimum {tr...
#!/usr/bin/env python3 # Copyright 2019 Google LLC # # Licensed under the the Apache License v2.0 with LLVM Exceptions (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://llvm.org/LICENSE.txt # # Unless required by applicable law ...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.contrib import admin from blog.models import Post, Author class PostAdmin(admin.ModelAdmin): pass class AuthorAdmin(admin.ModelAdmin): pass admin.site.register(Post, PostAdmin) admin.site.register(Author, AuthorAdmin)
''' Description: Note: This is a companion problem to the System Design problem: Design TinyURL. TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problems/design-tinyurl and it returns a short URL such as http://tinyurl.com/4e9iAk. Design the encode and decode methods for the Ti...
# -*- coding: utf-8 -*- # # Test Django Rest framework related changes # # :copyright: 2020 Sonu Kumar # :license: BSD-3-Clause # import unittest from django.test import LiveServerTestCase from util import TestBase class BasicTestCase(LiveServerTestCase, TestBase): def test_no_exception(self): ...
from django import forms from .models import Wish class WishForm(forms.Form): author = forms.CharField(max_length=40, widget=forms.TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Your name' ...
import numbers import ipywidgets import numpy as np import pandas as pd import ubermagutil.units as uu import matplotlib.pyplot as plt import ubermagutil.typesystem as ts import discretisedfield.util as dfu @ts.typesystem(dim=ts.Scalar(expected_type=int, positive=True, const=True), n=ts.Scalar(expected...
from django.db import models from django.db.models import DO_NOTHING from bpp.fields import YearField from bpp.models import BazaModeluOdpowiedzialnosciAutorow, TupleField class RozbieznosciViewBase(models.Model): id = TupleField(models.IntegerField(), size=3, primary_key=True) rekord = models.ForeignKey("bp...
from abc import ABC, abstractmethod from typing import List, Tuple, Dict from utils.data_structures import UFDS from utils.search import strict_binary_search class TrainingInstancesGenerator(ABC): @abstractmethod def generate(self, training_ids: List[int], ufds: UFDS) -> List[Tuple[int, int, int]]: p...
import datetime import enum from typing import List, Any, Dict from flask import current_app from itsdangerous import (JSONWebSignatureSerializer as Serializer, BadSignature, SignatureExpired) from sqlalchemy import ForeignKey from sqlalchemy.dialects.postgresql import ARRAY from sqlalchemy.orm import relationship fro...
import numpy as np def center(data: np.ndarray, axis: int = 0) -> np.ndarray: ''' centers data by subtracting the mean ''' means = np.mean(data, axis=axis) return data - means def minmax_scale(data: np.ndarray, axis: int = 0) -> np.ndarray: ''' Scales data by dividing by the range ''...
# Copyright (c) 2013 Ian C. Good # # 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, distrib...
#! coding: utf-8 import itertools import time from unittest import TestCase from dogpile.cache import util from dogpile.cache.api import NO_VALUE from dogpile.util import compat from . import eq_ from . import winsleep from ._fixtures import _GenericBackendFixture class DecoratorTest(_GenericBackendFixture, TestCas...
from django.test import TestCase, Client from django.contrib.auth.models import User # Setup functions def add_test_user(): user_to_test = User.objects.create_user( username="user_test", password="teste", is_staff=True ) return user_to_test # Tests class TestAddClient(TestCase): ...
from django.test import TestCase from django.conf import settings from django.core.management import call_command from cla_common.constants import DIAGNOSIS_SCOPE, MATTER_TYPE_LEVELS from legalaid.models import Category, MatterType from diagnosis.graph import get_graph from diagnosis.utils import get_node_scope_value ...
# -*- coding: utf-8 -*- # Licensed under a 3-clause BSD style license - see LICENSE.rst from __future__ import (absolute_import, division, print_function, unicode_literals) import fnmatch import time import re import datetime from collections import OrderedDict import numpy as np from .. impo...
# Celery配置文件 # 指定中间人、消息队列、任务队列、容器,使用redis broker_url = "redis://192.168.103.168/10"
APPLICATION_JS = 'application/javascript' JSONP_TEMPLATE = u'{callback}({payload})' JSONP = 'jsonp' CALLBACK = 'callback' def get_callback(request): return request.GET.get(CALLBACK, request.GET.get(JSONP, None))
from flask import Blueprint blog_blueprint = Blueprint('blog', __name__, static_folder='static', template_folder='templates') from . import routes
from py_sexpr.terms import * from py_sexpr.stack_vm.emit import module_code res = block( " | The functions in this module are highly unsafe as they treat records like | stringly-keyed maps and can coerce the row of labels that a record has. | | These function are intended for situations where there is some other way of...
import tweepy from config import create_api # auth = tweepy.OAuthHandler("CONSUMER_KEY", "CONSUMER_SECRET") # auth.set_access_token("ACCESS_TOKEN", "ACCESS_TOKEN_SECRET") def authentication(): auth = tweepy.OAuthHandler("eLz5PW2HhVvfeJ2hmKjlZmP6g", "BDGnsOitwOcZJWdvvSwTr...
from rest_framework import serializers from battleships.models.game import Game from battleships.models.game_player import GamePlayer from battleships.models.ship import Ship from battleships.models.coordinate import Coordinate class CoordinateSerializer(serializers.Serializer): x = serializers.PrimaryKeyRelatedF...
#!/usr/bin/env python2 # # @file # @author # @version 0.1 # @date # # @short: # from __future__ import print_function import itertools from threading import Lock from Queue import Queue from collections import namedtuple import rospy # Necessary to create a ros node from geometry_msgs.msg import PoseWithCovariance...
import codecs import numpy as np from word_beam_search import WordBeamSearch def apply_word_beam_search(mat, corpus, chars, word_chars): """Decode using word beam search. Result is tuple, first entry is label string, second entry is char string.""" T, B, C = mat.shape # decode using the "Words" mode of ...
import random import string class User: ''' Class that generates new instances ofCredentials user i.e: username and password ''' User_List = [] def save_user(self): User.User_List.append(self) def __init__(self,username,password): """ intro of...
"""Constants for the autelis integration.""" import logging _LOGGER = logging.getLogger(__package__) DOMAIN = "autelis_pool" AUTELIS_HOST = "host" AUTELIS_PASSWORD = "password" AUTELIS_USERNAME = "admin" AUTELIS_PLATFORMS = ["sensor", "switch", "climate"] # ["binary_sensor", "climate", "sensor", "weather"] TEMP_S...
#!/usr/bin/env python import torch import argparse from src.loadopts import * from src.utils import timemeter from src.config import SAVED_FILENAME METHOD = "WhiteBox" FMT = "{description}={attack}-{epsilon_min:.4f}-{epsilon_max}-{epsilon_times}-{stepsize:.5f}-{steps}" parser = argparse.ArgumentParser() parser.ad...
import os import copy import argparse import time from qdmr2sparql.datasets import DatasetBreak, DatasetSpider from qdmr2sparql.structures import GroundingKey, GroundingIndex from qdmr2sparql.structures import save_grounding_to_file, load_grounding_from_file, load_grounding_list_from_file, assert_check_grounding_save_...
# Copyright 2020 Jigsaw Operations LLC # # 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...
import sqlite3 conn = sqlite3.connect('degiro_new.db') c = conn.cursor() import json from datetime import datetime import pandas as pd import degiroapi from degiroapi.product import Product from degiroapi.order import Order from degiroapi.utils import pretty_json # c.execute('''UPDATE portfolio SET category = (?)'''...
# -*- coding: utf-8 -*- """ Last updated Apr 2019 by @ivanwilliammd """ import glob import os import subprocess import SimpleITK as sitk import numpy as np import lidcXmlHelper as xmlHelper # Path to the command lines tools of MITK Phenotyping path_to_executables=r"C:\Users\Ivan William Harsono\Documents\MITK 2016.11...
# -*- coding: utf-8 -*- from django.db import models from django.utils.translation import ugettext_lazy as _ from django.utils.timezone import now # 自定义基类型: class BaseModel(models.Model): created_at = models.DateTimeField(verbose_name=_("Created At"), auto_now_add=True) updated_at = models.DateTimeField(verbo...
import asyncio from aiohttp import ClientSession from aiochclient import ChClient async def some_query(client: ChClient, offset, limit): await client.execute( "INSERT INTO t VALUES", *((i, i / 2) for i in range(offset, offset + limit)) ) async def main(): async with ClientSession() as s: ...
import numpy as np import pytest from rolldecayestimators import tests import rolldecayestimators import pandas as pd import os from rolldecayestimators import ikeda_speed as ikeda from numpy import pi, sqrt from numpy.testing import assert_almost_equal from matplotlib import pyplot as plt @pytest.fixture def lewis_co...
from scipy.special import logsumexp from scipy.stats import norm from .data_base import np, gaussian_kde, RegressManager, check_reg_limits class PointManager(RegressManager): def get_percentiles(self, mean, var, p): return np.array([norm.ppf(i, mean, np.sqrt(var)) for i in p]).T @check_reg_limits ...
#App config #webx #central config CENTRAL_CONFIG = 'c:/mtp/avl_dc/bli_monitor/conf/maboss_config.py' #windows service SERVICE_NAME = '_MaboTech_Monitor_HotTest' SERVICE_DESC = 'HotTest Data Collection'
from sklearn.ensemble import RandomForestRegressor import goal_metrics from mle import engine from mle.problem_type import ProblemType def main(): model_config = { 'problem_type': ProblemType.REGRESSION, 'model_class': RandomForestRegressor, 'train_data_path': 'example_data/train.csv', ...
from six import add_metaclass from abc import ABCMeta from abc import abstractmethod @add_metaclass(ABCMeta) class AbstractAdditionalInput(object): """ Represents a possible additional independent input for a model """ @abstractmethod def get_n_parameters(self): """ Get the number of paramete...
from django.conf import settings from model_utils import Choices from assopy.models import Vat, VatFare from conference.models import FARE_TICKET_TYPES, Conference, Fare # due to historical reasons this one is basically hardcoded in various places. SOCIAL_EVENT_FARE_CODE = "VOUPE03" SIM_CARD_FARE_CODE = "SIM1" FAR...
"""The entrypoint into the CLI for tfimgsort""" from .tfimgsort import main main()
""" The regex blocking method is from jieba. https://github.com/fxsjy/jieba/blob/master/jieba/__init__.py Algorithm wise, use dp with uni-gram probability. """ from collections import defaultdict, deque import math import time import re re_dict = re.compile('^(.+?)( [0-9]+)?( [a-z]+)?$', re.U) re_han = re.compile("(...
import numpy as np import ini import diagn import h5py from os.path import join as pjoin params = ini.parse(open('input.ini').read()) ####### Parameters ####### # box size, mm lx = float(params['grid']['lx']) ly = float(params['grid']['ly']) # intervals in x-, y- directions, mm dx = float(params['grid']['dx']) dy = fl...
from getratings.models.ratings import Ratings class NA_Jhin_Top_Aatrox(Ratings): pass class NA_Jhin_Top_Ahri(Ratings): pass class NA_Jhin_Top_Akali(Ratings): pass class NA_Jhin_Top_Alistar(Ratings): pass class NA_Jhin_Top_Amumu(Ratings): pass class NA_Jhin_Top_Anivia(Ratings): pass clas...
import os import sys import cv2 import numpy as np # Download and install the Python COCO tools from https://github.com/waleedka/coco # That's a fork from the original https://github.com/pdollar/coco with a bug # fix for Python 3. # If the PR is merged then use the original repo. # Note: Edit PythonAPI/Makefile and re...
import os # key of locking gpu GPU_LOCKING_SET = "gpu_locking_set" # gpu usage for dispach GPU_USAGE_THRESHOLD = float(os.environ.get("GPU_USAGE_THRESHOLD", 0.8)) # gpu lock time GPU_LOCK_MINUTES = int(os.environ.get("GPU_LOCK_MINUTES", 3))
from uqcsbot import bot, Command from uqcsbot.utils.command_utils import loading_status from typing import Tuple, Dict, List import feedparser ARTICLES_TO_POST = 5 RSS_URL = "http://feeds.feedburner.com/TechCrunch/" TECHCRUNCH_URL = "https://techcrunch.com" def get_tech_crunch_data() -> List[Dict[str, str]]: """...
#!/usr/bin/env python3 import sys import os from importlib.machinery import SourceFileLoader from scapy.all import * from scapy.contrib.geneve import GENEVE def hexstring(p): s = bytes(p.__class__(p)) return ",".join("0x{:02x}".format(c) for c in s) def output_test(filename, tests): (name, ext) = os.path...
import rtree import pandas as pd from scipy.optimize import linear_sum_assignment import numpy as np def create_rtree_from_polygon(coords_list): """ Args: coords_list: tuple with coordinates of a polygon Returns: index: indexed bounding boxes """ index = rtree.index.Index(interleav...
# -*- coding: utf-8 -*- from django.conf.urls import url, include from djanban.apps.visitors.views.main import view_list, new, edit, delete urlpatterns = [ url(r'^$', view_list, name="view_list"), url(r'^new$', new, name="new"), url(r'^(?P<visitor_id>\d+)/edit$', edit, name="edit"), url(r'^(?P<visito...
# -------------------------------------------------------- # (c) Copyright 2014, 2020 by Jason DeLaat. # Licensed under BSD 3-clause licence. # -------------------------------------------------------- import unittest import common_tests import pymonad from pymonad.state import _State class EqState(pymonad.monad.Monad...
#!/usr/bin/env python3 # Copyright (c) 2015-2019 Daniel Kraft # Distributed under the MIT/X11 software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # RPC test for name_pending call. from test_framework.names import NameTestFramework, val from test_framework.util ...
EUQ_PATTERN = '(.*) = (.*)' IN_PATTERN = '(.*) in (.*)' NOT_NULL_PATTERN = "(.*) is not null" import re class FilterParser(): def parse(filterExpression): if re.match(EUQ_PATTERN, filterExpression): return FilterParser._parseEuq(filterExpression) elif re.match(IN_PATTERN, filterExpres...
import os import re import requests from PIL import Image, ImageEnhance from pytesseract import pytesseract from bs4 import BeautifulSoup headers = { 'User-Agent': "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:58.0) Gecko/20100101 Firefox/58.0" } login_url = "http://202.194.119.110/login.php" verify_code_url = "h...
"""Defines classes for representing note details, queries, and update requests. The most important classes are :class:`FileInfo` , :class:`FileEditCmd` , and :class:`FileQuery` """ from __future__ import annotations from dataclasses import dataclass, field, replace from datetime import datetime, timezone from enum im...
# django imports from django import forms from django.db import models from django.template import RequestContext from django.template.loader import render_to_string from django.utils.translation import ugettext_lazy as _ # portlets imports from portlets.models import Portlet class TextPortlet(Portlet): """Portl...
#!/usr/bin/env python from pprint import pprint from typing import List from problema import Problema class BuscaEmProfundidade(object): # TODO: verificar objeto None sendo retornado def busca_profundidade(self, problema: Problema, estado=None, visitados=[]): if estado is None: estado =...
# =============================================================================== # Copyright 2015 Jake Ross # # 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...
#!/usr/bin/env python """ A polar decoder class. Currently only Successive Cancellation Decoder (SCD) is supported. """ import numpy as np from polarcodes.utils import * from polarcodes.SCD import SCD class Decode: def __init__(self, myPC, decoder_name = 'scd'): """ Parameters ...
from importers import CSVImportCommand import requests import click class SchoolsImportCommand(CSVImportCommand): def process_row(self, row): # Only import schools with easting and northing information if row[70] and row[71]: if 'Primary' in row[11]: school_type = 'PRI...
import numpy as np import tensorflow as tf class FastZeroTagModel(object): """ Create a tensorflow graph that finds the principal direction of the target word embeddings (with negative sampling), using the loss function from "Fast Zero-Shot Image Tagging". """ def __init__(self, input_size, ...