content stringlengths 5 1.05M |
|---|
#
# @lc app=leetcode id=657 lang=python3
#
# [657] Robot Return to Origin
#
# https://leetcode.com/problems/robot-return-to-origin/description/
#
# algorithms
# Easy (73.67%)
# Likes: 1228
# Dislikes: 692
# Total Accepted: 274.1K
# Total Submissions: 371K
# Testcase Example: '"UD"'
#
# There is a robot starting ... |
import base64
import codecs
import json
import os
from Crypto.Cipher import AES
class Cracker():
modulus = '00e0b509f6259df8642dbc35662901477df22677ec152b5ff68ace615bb7b725152b3ab17a876aea8a5aa76d2e417629ec4ee341f56135fccf695280104e0312ecbda92557c93870114af6c9d05c4f7f0c3685b7a46bee255932575cce10b424d813cfe4875d3... |
from setuptools import setup
dependencies = [
'aiohttp',
'pyjwt'
]
version = '1.0.0'
setup(name='aioupbit',
version=version,
packages=['aioupbit'],
description='Asynchronous wrapper for the Upbit API',
url='https://github.com/chaos314/aio-upbit',
author='Seokhwan Cheon',
a... |
# -*- coding: utf-8 -*-
from .autogen import *
from .custom import *
# modules = glob.glob(join(dirname(__file__), "*.py"))
# __all__ = [basename(f)[:-3] for f in modules if isfile(f) and f.endswith('_block.py')]
|
import csv
import math
import random
import time
import brainex.database.genexengine as gxdb
from pyspark import SparkContext, SparkConf
from brainex.parse import generate_query
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import findspark
import os
# spark_location = '/Users/Leo/spark-2.... |
from .helper import PillowTestCase, hopper
from .test_imageqt import PillowQtTestCase
from PIL import ImageQt, Image
if ImageQt.qt_is_installed:
from PIL.ImageQt import QImage
try:
from PyQt5 import QtGui
from PyQt5.QtWidgets import QWidget, QHBoxLayout, QLabel, QApplication
QT_VERSI... |
# -*- coding: utf-8 -*-
import unittest
import os
import re
from iktomi.utils import html
from lxml.html import Element
from lxml import etree
import lxml.html as h
class TestSanitizer(unittest.TestCase):
'''Tests for sanitizer based on lxml'''
def setUp(self):
self.attrs = {
'allow_tags':... |
# Generated by Django 4.0.1 on 2022-02-21 11:24
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('auth', '0012_alter_user_first_name_max_length'),
('member', '0002_remove_token_vali... |
import cv2
import os
import argparse
import shutil
import glob
from vidstab import VidStab
def image_to_video(image_path,out_video_path):
for image_folder in image_path:
head, tail = os.path.split(image_folder)
print(head + " and " + tail)
images = [img for img in os.listdir(image_folder) \... |
'''
Created on Aug 9, 2017
@author: Hao Wu
'''
from ScopeFoundry import HardwareComponent
from .arduino_sol_dev import ArduinoSolDev
from PyDAQmx import *
import numpy as np
import time
from math import exp
import h5py
class ArduinoSolHW(HardwareComponent):
'''
Hardware Component Class for receiving AI input... |
#!/usr/bin/env python3
import json
import os
import sys
import tempfile
import requests
from tidetech_methods import print_json, save_file
# Configuration of server and API Key
SERVER = 'https://api.tidetech.org'
# Change this to your API key
API_KEY = os.environ.get('TIDETECH_API_KEY')
if not API_KEY:
print(... |
"""
Parsers for the experimental data files
"""
# import datetime
from pathlib import Path
from html.parser import HTMLParser
from typing import Tuple
# 3rd party
# import datefinder
# import pandas as pd
#%%
class ParserError(ValueError):
"""unable to parse this file"""
def read_PAR_file(filepath: Path, brea... |
from peewee import *
import os
db = MySQLDatabase(
"metrics",
host=os.environ['MYSQL_HOST'],
port=int(os.environ['MYSQL_PORT']),
user=os.environ['MYSQL_USER'],
password=os.environ['MYSQL_PASS']
)
class Exercicios(Model):
id = PrimaryKeyField()
banca = CharField()
data_registro = DateFi... |
# -*- coding: utf-8 -*-
"""Tests: Algorithms for topological sorting"""
import unittest
from assertpy import assert_that
from algolib.graphs import DirectedSimpleGraph
from algolib.graphs.algorithms import DirectedCyclicGraphError, sort_topological_using_dfs, \
sort_topological_using_inputs
class TopologicalSor... |
class Resource:
def __init__(self, service):
self.service = service |
# coding: utf-8
# # Function dct
#
# ## Synopse
#
# Discrete Cossine Transform.
#
# - **F = dct(f)**
#
# - **F**:output: image dct transform.
# - **f**:input: input image.
# In[6]:
import numpy as np
def dct(f):
import ea979.src as ia
f = f.astype(np.float64)
if len(f.shape) == 1: f = f[:,np.... |
import json
import os
import sys
here = os.path.dirname(os.path.realpath(__file__))
sys.path.append(os.path.join(here, "./vendored"))
import requests
TOKEN = os.environ['TELEGRAM_TOKEN']
BASE_URL = f"https://api.telegram.org/bot{TOKEN}"
def manualLoad(headersfilename='headers.txt'):
unorderedlist = []
with o... |
# -*- test-case-name: Cowrie Proxy Test Cases -*-
# Copyright (c) 2019 Guilherme Borges
# See LICENSE for details.
import os
from twisted.cred import portal
from twisted.internet import reactor
from twisted.trial import unittest
from cowrie.core.checkers import HoneypotPasswordChecker, HoneypotPublicKeyChecker
fro... |
import numpy as np
from visualization import Visualization
from agent import PPOAgent
# from agent_with_throttle import PPOAgent
def expand_image_dimension(image):
return np.expand_dims(image, axis=2)
def preprocess_image(image):
return image / 255
def action_to_motion(action):
clipped_steering = np.cl... |
from typing import Sequence, Dict, Optional
import pandas as pd
import pyexlatex as pl
from datacode.models.variables import Variable
from datacode.summarize.coverage.counts import variables_drop_count_df_and_plt_figs
from datacode.summarize.coverage.to_tex import variables_drop_panel, variables_latex_figures
def v... |
# Ameryn Media metadata processor
# Alex Ball, 2015
import discogs_client
from mutagen.flac import FLAC
import csv, os, time, math, logging
import webbrowser
import time
# Initial variables
input_filename_series = False
input_whole_folder = True
use_boxes_csv = True
input_filename = '00228'
input_filename_list = []
i... |
print("hello docker world!!!")
|
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
ransomFreqMap, magazineFreqMap = Counter(ransomNote), Counter(magazine)
for char, freq in ransomFreqMap.items():
if char not in magazineFreqMap or freq > magazineFreqMap[char]:
return False
... |
'''
grad_descent.py
Use gradient descent to find the minimum value of a
single variable function. This also checks for the existence
of a solution for the equation, f'(x)=0 and plots the intermediate
points traversed.
'''
from sympy import Derivative, Symbol, sympify, solve
import matplotlib.pyplot as plt
def grad_d... |
#!/usr/bin/env python
from distutils.core import setup
import gitstats
def readme():
try:
with open('README.rst') as f:
return f.read()
except:
return '(Could not read from README.rst)'
with open('requirements.txt') as fin:
install_reqs = fin.readlines()
setup(
name='... |
import python_path
from utils.decorator import ReferenceUsingTest
from ml_workflow.viz_utils import VizUtils, plot_model, \
plot_model_full_detail, get_default_dirname
import utils
from ml_workflow.workflow_node import WorkflowNode
import ml_workflow
from ml_workflow import Rule, DataSource
import ml_workflow.trac... |
import csv
import re
def parse_peptide(peptide, peptide_regex, ptm_removal_regex):
match = peptide_regex.match(peptide)
if match and match.group('peptide'):
matched_peptide = match.group('peptide')
return ptm_removal_regex.sub('', matched_peptide)
else:
return None
class PINFile:
... |
# -*- coding: utf-8-*-
import sys, os, time, random
import re
import json
import argparse
import logging
import psutil
from multiprocessing import Process, Queue, Pipe
from lib.graphic.baiduGraphic import BaiduGraphic
from lib.voice.baiduVoice import BaiduVoice
from lib.voice.baseVoice import AbstractVoiceEngine
from ... |
#!/bin/python3
import os
# Complete the minimumSwaps function below.
def minimum_swaps(array) -> int:
swap_count = 0
correct_order = sorted(array)
indexes = {v: i for i, v in enumerate(array)}
for index, value in enumerate(array):
correct_value = correct_order[index]
if value != corr... |
from sklearn.naive_bayes import GaussianNB
import numpy as np
from sklearn import datasets
import scipy.stats
def get_data():
iris = datasets.load_iris()
features, target = iris.data, iris.target
train_features, train_targets = features[:120, :], target[:120]
test_features, test_targets = features[12... |
# Generated by Django 3.2.5 on 2021-09-12 23:26
import django.contrib.gis.db.models.fields
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
n... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''wgetdb
Usage:
wgetdb <database_path> <url> <label>
wgetdb -h | --help
wgetdb --version
Options:
-h --help Show this screen.
--version Show version.
'''
from __future__ import unicode_literals, print_function
import datetime
import urllib2
import sqli... |
class TestTypeConversionError:
pass
class TestCondition:
def test___str__(self): # synced
assert True
def test___call__(self): # synced
assert True
def test_extract_name_from_condition(self): # synced
assert True
class TestValidatorMeta:
pass
class TestValidator:
... |
def test_Druva_FindDevice_Command(requests_mock):
from Druva import Client, Druva_FindDevice_Command
mock_response = {'resources': [{
'orgID': '-1',
'resourceID': '12345',
'resourceName': 'test',
'resourceParent': 'testUser',
'resourceStatus': 'enabled',
... |
import pytest
from typing import (
Dict,
Optional,
List
)
@pytest.fixture(scope='module')
def matlab_folder_path(p: Optional[str] = None) -> str:
return r"..\sources\matlab_saved_workspaces"
@pytest.fixture(scope='module')
def matlab_ws_keys(keys: Optional[Dict] = None) -> List:
return ['data', ... |
import discord
from discord.ext import commands
import sys
import asyncio
import traceback
from contextlib import suppress
class Periodic:
def __init__(self, time, func):
self.func = func
self.time = time
self.is_started = False
self._task = None
async def start(self):
... |
import re
from aniparser.constants import audio_terms, video_terms, source_terms
__all__ = (
"EPISODE_SEASON_REGEX",
"EPISODE_REGEX",
"SEASON_REGEX",
"RESOLUTION_REGEX",
"CHECKSUM_REGEX",
"BRACKET_TERMS_REGEX",
"YEAR_REGEX",
"EXTENSION_REGEX",
"RELEASE_VERSION_REGEX",
"RELEASE_... |
from libAnt.core import lazyproperty
from libAnt.profiles.profile import ProfileMessage
class HeartRateProfileMessage(ProfileMessage):
""" Message from Heart Rate Monitor """
def __init__(self, msg, previous):
super().__init__(msg, previous)
def __str__(self):
return f'{self.heartrate}'
... |
from typing import Any, Dict, Generator, Optional
import pytest
from xpresso import App, Path, Security
from xpresso.security import OAuth2PasswordBearer
from xpresso.testclient import TestClient
from xpresso.typing import Annotated
oauth2_scheme = OAuth2PasswordBearer(
tokenUrl="/token",
description="OAuth2... |
"""
Date: 08/22/2021
Name: Rio Weil
Title: ui.py
Description: Frontend code for minesweeper game, responsible for the UI through the console.
"""
import model
import errors
class Game:
"""
Initializes the Game.
"""
def __init__(self):
try:
width, height, numbombs = self.initialpara... |
import re
from itertools import zip_longest
def text2sentences(txt, equal_to_space = ["\n"]):
"""
Разбивает текст на предложения, учитывая, что фразы типа "мат. алгоритмы", "и т. д.", ".NET" --- это всё одно предложение
"""
inds = []
for i in range(len(txt)):
if txt[i] == '.':
... |
import unittest
from request_parsers import keystroke
class KeystrokeTest(unittest.TestCase):
# Intentionally violating style conventions sot hat we can parallel the
# self.assertEqual method.
# pylint: disable=no-self-use
# pylint: disable=invalid-name
def assertKeystrokesEqual(self, expected, ... |
import multiprocessing
import concurrent.futures
import time
from typing import Callable
S_T = [4, 2, 7, 4, 3, 10, 11, 3, 2, 1]
def task(args: tuple = ('', 1)) -> str:
name = args[0]
sec = args[1]
print('Task', name, 'sleeps for', sec)
time.sleep(sec)
return 'Task', name, sec, 'finished.'
def ... |
#!/usr/bin/env python
#
import cgi
import wsgiref.handlers
import logging
import json
from actingweb import actor
from actingweb import auth
from actingweb import config
from on_aw import on_aw_bot
import webapp2
class MainPage(webapp2.RequestHandler):
def post(self, path):
"""Handles POST callbacks for ... |
"""
Copyright (c) 2019, Pyxidr and/or its affiliates. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditio... |
"""ADd cascades
Revision ID: def46e09c9ef
Revises: 3efdb537f933
Create Date: 2017-12-28 11:44:14.263012
"""
# revision identifiers, used by Alembic.
revision = 'def46e09c9ef'
down_revision = '3efdb537f933'
from alembic import op
import sqlalchemy as sa
def upgrade():
# ### commands auto generated by Alembic -... |
from __future__ import absolute_import
from pychron.core.ui import set_toolkit
set_toolkit('qt4')
from pychron.paths import paths
paths.build('_unittest')
#build_directories(paths)
from pychron.core.helpers.logger_setup import logging_setup
logging_setup('arar')
from test.database import isotope_manager_factory
... |
import numpy as np
from lib.sampling import Sampler
from shapely.geometry import Polygon, Point, LineString
from sklearn.neighbors import KDTree
import networkx as nx
def can_connect(n1, n2, polygons):
line = LineString([n1, n2])
for p in polygons:
if p.crosses(line) and p.height >= min(n1[2], n2[2]):
... |
# Copyright 2018-present, Facebook, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to ... |
import tensorflow as tf
import tensorflow_datasets as tfds
import numpy as np
builder = tfds.builder('imdb_reviews')
builder.download_and_prepare()
datasets, info = tfds.load('imdb_reviews', with_info=True, as_supervised=True)
train_dataset = datasets['train']
train_dataset = train_dataset.batch(5).shuffle(50).take... |
from abc import ABC, abstractmethod
import torch
class AbstractReward(ABC):
# language=rst
"""
Abstract base class for reward computation.
"""
@abstractmethod
def compute(self, **kwargs) -> None:
# language=rst
"""
Computes/modifies reward.
"""
pass
... |
from pathlib import Path
import torch
from PIL import ImageFont
FILE = Path(__file__).absolute()
ROOT = FILE.parents[1] # yolov5/ dir
# Check YOLOv5 Annotator font
font = 'Arial.ttf'
# try:
# ImageFont.truetype(font)
# except Exception as e: # download if missing
# url = "https://ultralytics.com/assets/" +... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright 2019 SAP SE or an SAP affiliate company. All rights reserved
# ============================================================================
""" Evaluation Content """
from __future__ import absolute_import
from __future__ import division
from __future__ import pri... |
from sqlalchemy import Column, Integer, String, DateTime, TIMESTAMP, UniqueConstraint, Time, Text, Boolean, BigInteger, Date, DateTime, ForeignKey, JSON, Float, func
from sqlalchemy.orm import relationship
|
from django.shortcuts import render
from anuncios.models import Anuncio
# Create your views here.
def anuncios(request):
anuncios = Anuncio.objects.filter(status='publicado')
return render(request,'anuncios/index.html',{'anuncios':anuncios})
def home(request):
return render(request,"web/index.html") |
import os
__author__ = ['Andrew Liew <liew@arch.ethz.ch>']
__copyright__ = 'Copyright 2017, Andrew Liew'
__license__ = 'MIT License'
__email__ = 'liew@arch.ethz.ch'
__all__ = [
'get_document_name',
'get_document_filename',
'get_document_path',
'get_document_dirname'
]
... |
from typing import List
from guet.commands.command import Command
from guet.commands.command_factory import CommandFactoryMethod
from guet.settings.settings import Settings
class CommandFactoryDecorator(CommandFactoryMethod):
def __init__(self, decorated: CommandFactoryMethod):
super().__init__()
... |
"""DjangoChina URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.11/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Clas... |
import os
import csv
import argparse
import numpy as np
from scipy import integrate
from matplotlib import pyplot as plt
from sklearn.metrics import r2_score
from exp_variant_class import exp_variant
from sklearn.decomposition import TruncatedSVD,PCA
from examples.plotting.commons import *
from copy import deepcopy
cm... |
# Copyright (c), Google Inc, 2017
# Simplified BSD License (see licenses/simplified_bsd.txt or https://opensource.org/licenses/BSD-2-Clause)
try:
import requests
HAS_REQUESTS = True
except ImportError:
HAS_REQUESTS = False
try:
import google.auth
import google.auth.compute_engine
from google.o... |
import os
import shelve
import scrape
import download
import wx.dataview as dv
from wx.lib.delayedresult import startWorker
# Ignore wxWidgets/wxWidgets version mismatch warnings.
import warnings
with warnings.catch_warnings():
warnings.simplefilter("ignore")
import wx
class AliasConfigWindow(wx.Frame):
... |
import calendar
import warnings
import ipywidgets as widgets
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from scipy import stats
from scipy.interpolate import interp1d
from scipy.optimize import curve_fit
from sklearn import linear_model
from sklearn.preprocessing import St... |
import json
import urllib.request, urllib.parse
import subprocess
from bs4 import BeautifulSoup
from inky import InkyPHAT
from PIL import Image, ImageFont, ImageDraw
from font_fredoka_one import FredokaOne
req = urllib.request.Request('http://www.instagram.com/sj___156')
req.add_header('User-Agent','Mozilla/5.0 (... |
#!/usr/bin/env python3.8
# Copyright 2020 The Fuchsia Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""Use scrutiny to verify a build."""
import argparse
import difflib
import json
import os
import re
import shlex
import subprocess
i... |
#To plot los signal for 4 given los for a given offset, polystr and tau
import numpy as np
import matplotlib.pyplot as plt
import argparse
import sys
######################################################
#### Choose (x,y) for plotting los signal
los_array=[[34,54], [12,183], [234,145], [218,87]]
##########... |
import RPi.GPIO as GPIO
import time
# Pin Definitons:
enablePin = 2
directionPin = 3
pulsePin = 4
# setup gpio
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(enablePin, GPIO.OUT)
GPIO.setup(directionPin, GPIO.OUT)
GPIO.setup(pulsePin, GPIO.OUT)
# disable stepper
GPIO.output(enablePin, GPIO.LOW)
# set dir... |
print(f"imported mw_url_shortener.api.redirects as {__name__}")
"""
Manages the redirects portion of the API
"""
from fastapi import APIRouter, Body
from ..database.entities import RedirectEntity
from ..database.interface import add_redirect
from ..database.models import Redirect
router_v1 = APIRouter()
@router_v1.... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def findBottomLeftValue(self, root: TreeNode) -> int:
leaves_list = []
def dfs(node... |
# Generated by Django 3.2.12 on 2022-04-04 15:23
import api.models
import authlib.oauth2.rfc6749.models
from django.conf import settings
import django.contrib.postgres.fields
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
import uuid
class Migration(migrations.... |
CMDPrefix = {
'502781179368439808':'i!',
}
|
# Copyright (c) 2021 Jonas Thorsell
import sys
tl = [0] * 9
for t in [int(x) for x in sys.stdin.readline().split(',')]:
tl[t] += 1
for d in range(256):
ntl = [0] * 9
for i in range(9):
if i == 0:
ntl[8] = tl[0]
ntl[6] = tl[0]
else:
ntl[i-1]... |
from django.contrib.auth import get_user_model
from django.urls import reverse
import pytest
from pytest_django.asserts import assertContains
@pytest.fixture
def user(admin_client):
user = get_user_model().objects.create_user(
email='test@fake.com',
password='password123',
name='Test user... |
from .quickperms import quickperms
|
#####################################################
# generate simulated data of sequence reads
#####################################################
import numpy as np
import pymc
import scipy.special as ss
def modelCNV(pos, filename=False):
profile = np.empty(pos)
truestate = np.empty(pos)
current = 0... |
# -*- coding: utf-8 -*-
"""
Created on Fri Apr 23 22:18:35 2021
@author: 1636740
"""
import pandas as pd
from flask import Flask, request, render_template
import pickle
app = Flask('__name__')
q = ""
@app.route("/")
def loadPage():
return render_template('home_heroku.html', query="")
@app.route(... |
# %%
from gym_minigrid.minigrid import *
from gym_minigrid.window import Window
import numpy as np
class Maze(MiniGridEnv):
"""
Maze environment.
This environment is full observation.
The state is (x, y, dir) where x,y indicate
the agent's location in the environment and
di... |
from __future__ import division # import this module if you do ANY mathematics
import sys # this module does this ...
import csv # saving RAC_samples as csv file not sure how to determine where it saves yet
# the csv module might not be necessary
username = 'lisalocey'
mydir = '/Users/'+ username + '... |
import cv2
import argparse
import time
import os
import Update_Model
import glob
import random
import eel
#import winsound
frequency=2500
duration=1000
eel.init('WD_INNOVATIVE')
emotions=["angry", "happy", "sad", "neutral"]
fishface = cv2.face.FisherFaceRecognizer_create()
font = cv2.FONT_HERSHEY_SIMPLEX
'''try:
... |
# Copyright 2015 Novo Nordisk Foundation Center for Biosustainability, DTU.
# 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 ... |
# -*- coding: utf-8 -*-
from mock import Mock
import socket
import pytest
from huskar_sdk_v2.http.components.config import Config
@pytest.fixture
def config_component(requests_mock, no_cache_client):
return Config('arch.test', 'overall')
def test_config_should_success_for_app_id_clueter(
config_compon... |
# Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by app... |
"""
test_reddit.py: Application unit tests for the Reddit Category.
__author__ = "Fernando P. Lopes"
__email__ = "fpedrosa@gmail.com"
"""
import unittest
import news_source_reddit as nsr
class RedditTests(unittest.TestCase):
def test_ask(self):
news, title = nsr.get_most_read('re_ask')
self.asse... |
from typing import List
from utils import get_characters
from beans.comment_bridge import CommentBridge
from beans.comment import Comment
from collections import Counter
import anim
def render_comment_list(comment_list: List[Comment], output_filename = 'hello.mp4', music_code = 'PWR'):
counter = Counter()
thre... |
""" Python GTH16 hash - part of pyGT https://github.com/sybip/pyGT """
def gtAlgoH16(str):
""" Proprietary hash based on the Park-Miller LCG """
seed = 0xaa
mult = 48271
incr = 1
modulus = (1 << 31) - 1 # 0x7FFFFFFF
h = 0
x = seed
for c in bytearray(str):
x = (((x + c) * mult... |
import time
import DFL168A
SuccessFresh=False
def refresh():
global SuccessFresh
if not DFL168A.DigitalCommand('FEE5'):
SuccessFresh=False
return False
Temp=DFL168A.HandleResponse(DFL168A.ReturnStr)
DFL168A.ReturnStr=Temp
SuccessFresh=True
return True
def getTotalEn... |
import requests
import json
import pandas
def create_project(url, super_token):
record = [{
'project_title': 'ham10000',
'purpose': '0',
'purpose_other': '',
'project_notes': ''}]
data = json.dumps(record)
fields = {
'token': super_token,
'content': 'p... |
############## Reverse linked List in place ###############
""" Iterate on the linked list keeping track of the latest value """
import dataclasses
from typing import Optional, Any
@dataclasses.dataclass
class Node:
value: Any
next: Optional['Node']
def revert(root: Node) -> Optional[Node]:
curr: Option... |
# Copyright 2020 Canonical, 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 applicable law or agreed to in writing,... |
# Copyright 2017 SAS Project 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 requ... |
import frappe
from frappe import _, throw, msgprint
from frappe.utils import cint
from frappe.utils import now_datetime
from frappe.model.naming import getseries
from erpnext.setup.doctype.naming_series.naming_series import NamingSeries
class ENCINamingSeries(NamingSeries):
def validate_series_name(self, n):
impo... |
from __future__ import absolute_import
from .client import * # noqa: F401,F403
from .const import * # noqa: F401,F403
from .conversions import * # noqa: F401,F403
from .exceptions import * # noqa: F401,F403
from .planner import * ... |
from .unshorten import unshorten
|
from django.apps import AppConfig
class PikaConfig(AppConfig):
name = 'pika'
|
import serial
import string
import time
import numpy as np
from file_handling import format_filename, export_recorded
from plot import plot_data
windows = 'COM6'
linux = '/dev/ttyACM0'
ser = serial.Serial(windows, 230400, timeout=1)
def read() -> list:
line = str(ser.readline()).replace(' ', '').replace('\\r\... |
import re
import packet
import json
import qbert
import cluster_manager as cm
from flask import Flask
from flask import jsonify
from flask import request
from flask import Response
app = Flask(__name__)
with open('secrets.json') as f:
SECRETS = json.load(f)
def packet_auth(auth_token, project_id):
pattern ... |
"""
Django settings for FPIDjango project.
----
Unfortunately, the modified import statement of
..
from FPIDjango.private.settings_private import *
is required for the PyCharm Python Console and the PyCharm manage.py to
work properly. It obviously knows better than I do. It cannot pay
attention to some silly... |
# Generated by Django 2.2.6 on 2019-11-05 13:51
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('myuser', '0003_auto_20191021_1610'),
]
operations = [
migrations.AddField(
model_name='templateuser',
name='photo',
... |
import requests
resto = requests.get("http://www.pythonhow.com/data/universe.txt")
text = re.text
print(text) |
from bokeh.io import show
from bokeh.layouts import column
from bokeh.models.util import generate_structure_plot
from bokeh.plotting import figure
# draw the structure graph of a basic figure model
f = figure(width=400,height=400)
f.line(x=[1,2,3],y=[1,2,3])
K = generate_structure_plot(f)
show(column(f,K))
|
# -*- coding: utf-8 -*-
try:
# python2
import urlparse
except ImportError:
# python3
from urllib.parse import urlparse
import scrapy
from scrapy.shell import inspect_response
class BrandenburgSpider(scrapy.Spider):
name = "brandenburg"
# allowed_domains = ["https://www.bildung-brandenburg.de/... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.