content
stringlengths
0
894k
type
stringclasses
2 values
# python3 def fibo(n): a = 0 if n==0: return a b = 1 if n==1: return b for i in range(2,n+1): c = (a+b)%10 a = b b = c return c if __name__ == '__main__': n = int(input()) print(fibo(n))
python
access_token = "1115607808185995264-em8QLLFJ6ESWiVRM5G77euAA0rmaxU" access_token_secret = "pnfdtIsloJsg9huAUb8mVAMApYqv9fyiJRqdTaJwkYvS0" consumer_key = "wM7VnB9KDsU1ZiezePZmyRSZo" consumer_secret = "0Vd3EiWZQppmOTkd8s8lTynU1T9rBs5auMQQvJy9xNE1O49yXJ" filename = "/Users/tanujsinghal/Documents/trained_models/toxic-text-...
python
from . import db # The class that corresponds to the database table for decision reasons. class DecisionReason(db.Model): __tablename__ = 'decision_reason' id = db.Column(db.Integer, primary_key=True) name = db.Column(db.VARCHAR(1024)) reason = db.Column(db.VARCHAR(1024))
python
from mastodon import Mastodon from Zodiac import Zodiac def announce(user_id, domain, zodiac): if zodiac.bot_access_token is '' or zodiac.bot_access_token is None or zodiac.bot_base_url is '' or zodiac.bot_base_url is None: return bot = Mastodon(access_token=zodiac.bot_access_token, api_base_url=zodia...
python
import pytest from mypy_boto3_s3 import S3Client from dc_logging_client.log_client import DummyLoggingClient, DCWidePostcodeLoggingClient from dc_logging_client.log_entries import PostcodeLogEntry def test_log_client_init_errors(): with pytest.raises(ValueError) as e_info: DummyLoggingClient(fake=False) ...
python
import fileinput TAGS = {"[": "]", "(": ")", "<": ">", "{": "}"} def find_illegal(line): stack = [] for c in line: if c in TAGS: stack.append(c) else: expected = TAGS[stack.pop()] if c != expected: return c return None def find_comple...
python
#!/usr/bin/env python # -*- coding: utf8 -*- # Copyright (C) 2013-2014 Craig Phillips. All rights reserved. """Remote file synchronisation""" import os, re, datetime from libgsync.output import verbose, debug, itemize, Progress from libgsync.sync import SyncType from libgsync.sync.file import SyncFile, SyncFileInfo...
python
"""Collection of helper methods. All containing methods are legacy helpers that should not be used by new components. Instead call the service directly. """ from homeassistant.components.group import ( ATTR_ADD_ENTITIES, ATTR_CONTROL, ATTR_ENTITIES, ATTR_OBJECT_ID, ATTR_VIEW, ATTR_VISIBLE, DOMAIN, SERVICE_REMO...
python
import FWCore.ParameterSet.Config as cms patEventContentNoCleaning = [ 'keep *_selectedPatPhotons*_*_*', 'keep *_selectedPatOOTPhotons*_*_*', 'keep *_selectedPatElectrons*_*_*', 'keep *_selectedPatMuons*_*_*', 'keep *_selectedPatTaus*_*_*', 'keep *_selectedPatJets*_*_*', 'drop *_*PF_cal...
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Extract S3 OLCI SNOW processor results from S3 OLCI images Written by Maxim Lamare """ import sys from pathlib import Path from argparse import ArgumentParser, ArgumentTypeError import csv import pandas as pd from datetime import datetime import re from snappy_funcs im...
python
import tensorflow as tf import numpy as np import yaml from src.preprocessing import clean_doc # load conifig with open('config.yaml', 'r') as f: conf = yaml.load(f) MAX_NUM_WORDS = conf["EMBEDDING"]["MAX_NUM_WORDS"] MAX_SEQUENCE_LENGTH = conf["EMBEDDING"]["MAX_SEQUENCE_LENGTH"] def get_data_tensor(texts, trainin...
python
from _init_paths import * import cv2 import numpy as np import pickle import json import os.path as osp import skimage.transform import argparse import h5py import time # Preprocess image def prep_image(fname, mean_values): im = cv2.imread(fname) h, w, _ = im.shape if h < w: im = skimage.transform....
python
# # Copyright 2012-2014 John Whitlock # # 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...
python
from typing import List, Tuple from chia.types.blockchain_format.sized_bytes import bytes32 from chia.util.db_wrapper import DBWrapper2 import logging log = logging.getLogger(__name__) class HintStore: db_wrapper: DBWrapper2 @classmethod async def create(cls, db_wrapper: DBWrapper2): self = cls(...
python
# Copyright 2021 IBM Corporation # # 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 wri...
python
# Generated by Django 2.0.3 on 2018-07-25 06:07 import django.contrib.gis.db.models.fields from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('firstgis', '0004_auto_20180725_0157'), ] operations = [ migrations.CreateModel( name=...
python
from .CompoundEditor import CompoundEditor from .Icons import Icons from .TypeUtils import getListElemTypeHint import copy class EditorList(CompoundEditor): canDeleteElements = True canMoveElements = True def _getProperties(self): for i in range(len(self._targetObject)): name = str(i...
python
""" @author: @file: urls.py @time: 2018/1/31 13:20 """ from app.case.views import * from app.case import case case.add_url_rule('/add_cases', view_func=AddtestcaseView.as_view('add_cases')) case.add_url_rule('/edit_case/<int:id>', view_func=EditcaseView.as_view('edit_case')) case.add_url_rule('/import_cases', view_...
python
#!/usr/bin/env python """ Generate database file in .h5 containing master, slaves sensor, and pseudo groundtruth. The final output fps depends on the sampling rate input. """ import os, os.path import inspect currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) parentdir = os.path.dir...
python
from django.apps import AppConfig class FontExemplosConfig(AppConfig): name = 'font_exemplos'
python
import glob import os import pickle import re import gensim from gensim.models.callbacks import CallbackAny2Vec from gensim.models import Word2Vec import numpy as np from mat2vec.processing.process import MaterialsTextProcessor text_processing = MaterialsTextProcessor() COMMON_TERMS = ["-", "-", b"\xe2\x80\x93", ...
python
def main(): str = raw_input() print str[::-1] #nixuzifuchuan if __name__ == '__main__': main()
python
# -*- coding: utf-8 -*- """ Tencent is pleased to support the open source community by making BK-BASE 蓝鲸基础平台 available. Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved. BK-BASE 蓝鲸基础平台 is licensed under the MIT License. License for BK-BASE 蓝鲸基础平台: ---------------------------------------------...
python
"""Consts used by pilight.""" CONF_DIMLEVEL_MAX = "dimlevel_max" CONF_DIMLEVEL_MIN = "dimlevel_min" CONF_ECHO = "echo" CONF_OFF = "off" CONF_OFF_CODE = "off_code" CONF_OFF_CODE_RECEIVE = "off_code_receive" CONF_ON = "on" CONF_ON_CODE = "on_code" CONF_ON_CODE_RECEIVE = "on_code_receive" CONF_SYSTEMCODE = "systemcode" C...
python
"""Shared Handlers This file is used to drive the handlers for the following intents: Intent Handler ====== ======= ChangeUnitsIntent ChangeUnitsIntentHandler """ import ask_sdk_core.utils as ask_utils from ask_sdk_core.skill_builder import SkillBuilder from ask_sdk_cor...
python
from . import base reload(base) from . import xref reload(xref) from . import line reload(line) from . import function reload(function) from . import switch reload(switch) from . import instruction reload(instruction) from . import segment reload(segment) from .base import * from .line import Line, lines ...
python
import ever as er import torch.nn as nn from core.mixin import ChangeMixin from module.segmentation import Segmentation @er.registry.MODEL.register() class ChangeStar(er.ERModule): def __init__(self, config): super().__init__(config) segmentation = Segmentation(self.config.segmenation) ...
python
import json import os import sys import urllib.error from http import HTTPStatus from typing import Generator from urllib.request import Request from urllib.request import urlopen from pyro.Comparators import endswith from pyro.Remotes.RemoteBase import RemoteBase class BitbucketRemote(RemoteBase): ...
python
from functools import cached_property from typing import Union from wtforms import DecimalField, IntegerField from app.data_models.answer_store import AnswerStore from app.forms.field_handlers.field_handler import FieldHandler from app.forms.fields import DecimalFieldWithSeparator, IntegerFieldWithSeparator from app....
python
#!/usr/bin/env python3 # Copyright (c) 2017-2018 The Bitcoin Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test various command line arguments and configuration file parameters.""" import os from test_framewo...
python
# # hdg-from -- Generate HDG files for GEMSS # # Copyright (C) 2017 Di WU # All rights reserved. # # This software may be modified and distributed under the terms # of the MIT license. See the LICENSE file for details. # # Compatibility with Pyhton 2.7 from __future__ import absolute_import, division, print_function,...
python
from PyQt5.QtWidgets import QAbstractButton, QSizePolicy from PyQt5.Qt import QPainter, QSize class QIconButton(QAbstractButton): def __init__(self, image=None, imageSelected=None, parent=None): super(QIconButton, self).__init__(parent) self.image = image if imageSelected is None: ...
python
import time import os """ 一些对象 Writer Reader """ class _OO: def orun(self, ident): ll = len(self.data) wres = [] if type(self.handler) is type: flag = issubclass(self.handler, HandleUnit) else: flag = False try: for ...
python
"""Faça um programa que tenha uma função notas() que pode receber várias notas de alunos e vai retornar um dicionário com as seguintes informações: Quantidade de notas A maior nota A menor nota A média da turma Situação (opcional) Adicione também as docstrings da função.""" def notas(*n, sit=False): """ -> F...
python
# This file was originally authored by # Brandon Davidson from the University of Oregon. # The Rocks Developers thank Brandon for his contribution. # # @copyright@ # Copyright (c) 2006 - 2019 Teradata # All rights reserved. Stacki(r) v5.x stacki.com # https://github.com/Teradata/stacki/blob/master/LICENSE.txt # @copyri...
python
# Copyright (c) MONAI Consortium # 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, so...
python
from numba.core.descriptors import TargetDescriptor from numba.core.options import TargetOptions from .target import HSATargetContext, HSATypingContext class HSATargetOptions(TargetOptions): pass class HSATargetDesc(TargetDescriptor): options = HSATargetOptions typingctx = HSATypingContext() targetc...
python
from discord.ext import commands from ..services import status_service, config_service from ..helpers import game_mapping_helper from ..clients import ecs_client class Config(commands.Cog): def __init__(self, bot): self.bot = bot @commands.command(help='Get the current admins') async def admins(s...
python
from django.contrib import admin # Register your models here. from .models import Pessoa admin.site.register(Pessoa)
python
# Generated by Django 2.1.7 on 2019-03-01 02:23 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('account', '0018_auto_20190228_1807'), ] operations = [ migrations.AlterField( model_name='wxuserintegrallog', name='...
python
from quakefeeds import QuakeFeed from datetime import datetime, timezone import logging import tweepy import io import os import json from urllib.request import urlopen, Request logging.basicConfig(filename='tweet.bot.log', level=logging.INFO) logger = logging.getLogger() base_url = os.getenv("API_HTTPS").rstrip('/')...
python
import tensorflow as tf from nn_basic_layers import * from ops import * import numpy as np import os class FCNNRNN(object): def __init__(self, config, is_eog=True, is_emg=True): self.g_enc_depths = [16, 16, 32, 32, 64, 64, 128, 128, 256] self.d_num_fmaps = [16, 16, 32, 32, 64, 64, 12...
python
class Rule(): """This class defines a rule""" def __init__(self,name): self.name = name self.datasets = [] def add_dataset(self,dataset): self.datasets.append(dataset) def __str__(self): return "Rule %s"%(self.name) class DataSet(): """This is a dataset""" def __...
python
print "this is a syntax error"
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Mon Feb 4 14:03:21 2019 @author: 3535008 """ try: import Tkinter as tk import ttk except ImportError: # Python 3 import tkinter as tk from tkinter import ttk from tincan import tracing_mrpython as tracing class CloseableNotebook(ttk.Not...
python
""" BIR module status Output card to control 8 250V/8A two-pole relays. :author: Zilvinas Binisevicius <zilvinas@binis.me> """ import json import domintell from domintell.messages import GenericAOStatusMessage class DDIMStatusMessage(GenericAOStatusMessage): COMMAND_CODE = 'DIM' """ DDIM module status ...
python
# -*- coding: utf-8 -*- import logging import oss2 from django.conf import settings from django.db import transaction from django.db.models import Count from chisch.common import dependency from chisch.common.decorators import login_required, lecturer_required from chisch.common.retwrapper import RetWrapper from chi...
python
# -*- coding: utf-8 -*- test_input_folder = 'test_input/' sangam_tamil = __import__("sangam_tamil") cdeeplearn = __import__("cdeeplearn") sangam_class = sangam_tamil.SangamPoems() config = sangam_tamil.config GREEN_CHECK = u'\u2714 ' RED_CROSS = u'\u274C ' GEQ = u' \u2265 ' STATUS_CHECK = lambda rc : GREEN_CHECK if r...
python
# Problem 1 # You are learning how to make milkshakes. # First, you will be given two sequences of integers representing chocolates and cups of milk. # You have to start from the last chocolate and try to match it with the first cup of milk. If their values are equal, # you should make a milkshake and remove both ingre...
python
#----------------------------------------------------------------------------- # Copyright (c) 2012 - 2021, Anaconda, Inc., and Bokeh Contributors. # All rights reserved. # # The full license is in the file LICENSE.txt, distributed with this software. #-------------------------------------------------------------------...
python
import requests import json from device_configs.csr_1000_devnet import router print(router) session = requests.Session() session.auth = (router['username'], router['password']) session.headers = ({ 'Accept': 'application/yang-data+json', 'Content-Type': 'application/yang-data+json' }) host = router['host'] po...
python
# -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ import random import time dizi1 = [5,8,7,1,35,42,32,12,56,45,21,326,20,28,54] arananEleman = 1 ######## Linear Arama ############# for diziDeger in dizi1: if arananEleman == diziDeger: print("Aranan Eleman Dizinin...
python
import tensorflow as tf import numpy as np # demo1 # def my_image_file(input): # conv1_weights = tf.Variable(tf.random_normal([3,4]),name="conv1_weights") # return conv1_weights # # input1=tf.get_variable(name="var1", initializer=np.ones (shape=[2,3],dtype=np.float32)) # input2=tf.get_variable(name="var2", in...
python
import numpy as np import math as math from pathfinding.core.diagonal_movement import DiagonalMovement from pathfinding.core.grid import Grid from pathfinding.finder.a_star import AStarFinder UNOCCUPIED = 1 OCCUPIED = -1 FOOD = 2 HEAD = -2 TAIL = 4 HEALTHLIM = 25 FOODDIST = 3 game_state = "" direc...
python
#!/usr/bin/python # @FarPixel & @DavidMaitland # https://github.com/davidmaitland/GifPro import os import time import pytumblr import urllib import uuid from subprocess import call frequency = 10 # Loop interval frames = 20 # Fames to take delay = 0.2 # Delay between frames gifDelay = 20 # Used for timing GIF genera...
python
# Generated by Django 3.0.3 on 2020-03-26 13:50 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ('tags', '0001_initial'), ('programs', '0002_auto_20200326_2050')...
python
""" A top-level linear programming interface. Currently this interface solves linear programming problems via the Simplex and Interior-Point methods. .. versionadded:: 0.15.0 Functions --------- .. autosummary:: :toctree: generated/ linprog linprog_verbose_callback linprog_terse_callback """ from __...
python
""" constraint_aggregator.py Aggregated Constraints from Astroplan as well as our own user-defined constraints. In our architecture we define the concept of a "Static Constraint" as one that always applies no matter how far we are scheduling into the future "Dynamic Constraints" are those that only apply if our tota...
python
import os import uuid import json import mimetypes from django.conf import settings from django.contrib import messages from django.contrib.auth import authenticate, login as django_login, logout from django.core import serializers from django.core.serializers.json import DjangoJSONEncoder from cloud.decorators.userReq...
python
import logging from django import forms import requests from .base import BaseAction, BaseActionForm logger = logging.getLogger('zentral.core.actions.backends.trello') class TrelloClient(object): """Trello API Client""" API_BASE_URL = "https://api.trello.com/1" def __init__(self, app_key, token): ...
python
import os from unittest.mock import patch from unittest.mock import MagicMock import cauldron from cauldron.cli.commands import save from cauldron.environ.response import Response from cauldron.test import support from cauldron.test.support import scaffolds class TestSave(scaffolds.ResultsTest): def test_fails_...
python
import cv2 import numpy as np import torchvision.datasets as datasets class CIFAR10Noise(datasets.CIFAR10): """CIFAR10 Dataset with noise. Args: clip (bool): If True, clips a value between 0 and 1 (default: True). seed (int): Random seed (default: 0). This is a subclass of the `CIFAR10`...
python
class ReturnInInitE0101: def __init__(self, value): # Should trigger "return-in-init" return value
python
#!/usr/bin/python help_msg = 'calculate contact order from PDB structure file' import os, sys, glob import imp from Bio.PDB import NeighborSearch, PDBParser, Atom, Residue, Polypeptide from Bio import PDB import numpy as np CWD = os.getcwd() UTLTS_DIR = CWD[:CWD.index('proteomevis_scripts')]+'/proteomevis_scripts/u...
python
from matplotlib import pyplot as plt import numpy as np import argparse def prettyPrint(data): x = np.linspace(1,len(data[0]),len(data[0])) y = np.mean(data, axis=0) print(y) std = np.std(data,axis=0) plt.plot(x,y,'k-',label='Mean') plt.xlabel("Generation") plt.ylabel("Max fitness") ...
python
from typing import Tuple, List, Optional import mvc import pygame import pygame.locals as pg import time import terrain import civ import cv2 import numpy as np import image import sprite import gaia class Model(mvc.Model): def __init__(self) -> None: self.sprites: List[sprite.Sprite] = [] self.sprites.append(spr...
python
#!/usr/bin/env python import vtk from vtk.util.misc import vtkGetDataRoot VTK_DATA_ROOT = vtkGetDataRoot() def GetRGBColor(colorName): ''' Return the red, green and blue components for a color as doubles. ''' rgb = [0.0, 0.0, 0.0] # black vtk.vtkNamedColors().GetColorRGB(colorName, rgb...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- ''' Created on 2018年2月1日 @author: Irony."[讽刺] @site: https://pyqt5.com , https://github.com/892768447 @email: 892768447@qq.com @file: PushButtonLine @description: ''' from random import randint import sys from PyQt5.QtCore import QTimer, QThread, pyqtSignal from PyQt5.QtG...
python
import glob import numpy as np import pre_processing2 as pre import cv2 import matplotlib.pyplot as plt images = [] for imagePath in glob.glob('data/library/train/*'): images.append(imagePath) faceList = [] labelList = [0,0,0,0,0,0,0,0,0,0] index = 0 for path in images: temp = pre.getFaceGray(path) temp = cv2.re...
python
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: google/cloud/firestore_v1beta1/proto/admin/index.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from go...
python
''' Demo for running training or linear models. ''' import utils from kahip.kmkahip import run_kmkahip if __name__ == '__main__': opt = utils.parse_args() #adjust the number of parts and the height of the hierarchy n_cluster_l = [opt.n_clusters] height_l = [opt.height] # lo...
python
#!/usr/bin/python3 import spidev import smbus import adpi import sys from time import sleep RAW_OFFSET = (1 << 23) RAW_SCALE = ( 0.000596040, 0.000298020, 0.000149010, 0.000074500, 0.000037250, 0.000018620, 0.000009310, 0.000004650, ) TEMP_VREF = 1.17 def v2k(rate, val): for k, v...
python
#!/usr/bin/env python # -*- encoding: utf-8 -*- # Time: 2020/11/05 17:35:42 # Author: Yingying Li import yaml import os import collections import numpy as np class LoadData(object): def __init__(self, path): yaml_path = path file = open(yaml_path, 'r', encoding='utf-8') content = file.read(...
python
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.utils.decorators import method_decorator from honeypot.decorators import check_honeypot from userprofiles.views import RegistrationView from ..forms import RegistrationMemberForm, RegistrationCommunityForm class RegistrationView(Registratio...
python
#!/usr/bin/env python3 # # Updater script of CVE/CPE database # # Copyright (c) 2012-2016 Alexandre Dulaunoy - a@foo.be # Copyright (c) 2014-2016 Pieter-Jan Moreels - pieterjan.moreels@gmail.com # Imports import os import sys runPath = os.path.dirname(os.path.realpath(__file__)) sys.path.append(os.path.join(runPath,...
python
# Copyright 2017 gRPC authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing...
python
VERSION = "0.13.3"
python
import logging __all__ = ( "logger", "set_verbosity_level" ) logging.basicConfig( stream=None, level=logging.CRITICAL, format="%(asctime)s - %(name)s (%(levelname)s): %(message)s" ) logger = logging.getLogger("siliqua") def set_verbosity_level(verbosity_level=0): """ Set the logging verbosity l...
python
#!/usr/bin/python # # Filename: prependTimestamps.py # # Version: 1.0.1 # # Author: Joe Gervais (TryCatchHCF) # # Summary: Inserts datetimestamps in front of each line of a file. Used to # add noise to a cloaked file (see cloakify.py) in order to degrade frequency # analysis attacks against the cloaked payload. #...
python
"""Actions that X can take""" from enum import Enum class MegamanAction(Enum): """Enum of possible actions""" MOVE_RIGHT = 1 MOVE_LEFT = 2 STOP_MOVEMENT = 3 JUMP = 4 SHOOT = 5 CHARGE = 6 DASH = 7 CHANGE_WEAPON = 8 START = 9
python
import json filename = './project_data_files/population_data.json' with open(filename) as f: pop_data = json.load(f) for pop_dict in pop_data: if pop_dict['Year'] == '2010': country_name = pop_dict['Country Name'] population = pop_dict['Value'] print(f'{country_name}: {population}') ...
python
# File: sudokuTests.py # from chapter 11 of _Genetic Algorithms with Python_ # # Author: Clinton Sheppard <fluentcoder@gmail.com> # Copyright (c) 2016 Clinton Sheppard # # Licensed under the Apache License, Version 2.0 (the "License"). # You may not use this file except in compliance with the License. # You may obta...
python
''' Created on Dec 20, 2017 @author: William Tucker ''' class ParserError(Exception): pass
python
#!/usr/bin/env python # -*- coding: utf-8 -*- # ''' model.py Andy Freeland and Dan Levy 5 June 2010 Contains functions to handle database queries. ''' import web from config import db def add_object(name): '''Adds an object with the given name to the objects table in the database. ...
python
from ncssl_api_client.api.commands.abstract_command import AbstractCommand class GetListCommand(AbstractCommand): pass
python
import logging logger = logging.getLogger(__name__) import io import os import re from collections import defaultdict from html import unescape from urllib.parse import urljoin import chardet import lxml.html import pandas as pd from bs4 import BeautifulSoup from py_sec_edgar.settings import CONFIG from py_sec_edg...
python
#!/usr/bin/env python import copy import rospy from geometry_msgs.msg import PoseStamped from interactive_markers.interactive_marker_server import InteractiveMarkerServer from interactive_markers.menu_handler import MenuHandler from traversability_rviz_paths.msg import Path, Paths from std_msgs.msg import ColorRGBA f...
python
# Copyright 2019 Google 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
python
#!/usr/bin/python3 import pandas as pd from os.path import join as oj import os def load_mit_voting(data_dir='.'): ''' Load in 2000-2016 County Presidential Data Parameters ---------- data_dir : str; path to the data directory containing mit_voting.csv Returns ------- data frame ...
python
import bpy light = bpy.context.light physical_light = bpy.context.light.photographer light.type = 'SPOT' light.spot_blend = 0.15000000596046448 light.shadow_soft_size = 0.029999999329447746 physical_light.spot_size = 1.1344640254974365 physical_light.light_unit = 'lumen' physical_light.use_light_temperature = True phy...
python
"""This module tests the RXGate class.""" from __future__ import annotations import numpy as np from bqskit.ir.gates import RXGate from bqskit.ir.gates import XGate def test_get_unitary() -> None: g = RXGate() u = XGate().get_unitary() assert g.get_unitary([np.pi]).get_distance_from(u) < 1e-7
python
from urllib.parse import urlparse from kafka import KafkaProducer def check(url): bootstrap_urls = url.split(",") bootstrap_parsed_urls = (urlparse(u) for u in bootstrap_urls) bootstrap_nodes = list( u.hostname + ":" + str(u.port or "9092") for u in bootstrap_parsed_urls ) try: K...
python
# -*- coding: utf-8 -*- # this file is released under public domain and you can use without limitations if MULTI_USER_MODE: db = DAL('sqlite://storage.sqlite') # if not, use SQLite or other DB from gluon.tools import * auth = Auth( globals(), db) # authentication/authoriz...
python
import pandas as pd import numpy as np import time from datetime import datetime import plotly.graph_objects as go import logging def historic_reader(path, symbol): # Historic dfs data_5m = pd.read_csv(path + 'historic/'+symbol+'-5m-data.csv') data_1h = pd.read_csv(path + 'historic/'+symbol+'-1h-data.csv'...
python
from collections import OrderedDict from bs4 import BeautifulSoup HEADER = """package cpu // Generated from: http://www.pastraiser.com/cpu/gameboy/gameboy_opcodes.html""" def main(): with open('opcodes.html', 'r') as f: soup = BeautifulSoup(f, 'html.parser') tables = soup.find_all('table') st...
python
from flask import Flask from flask.helpers import send_from_directory from waitress import serve app = Flask(__name__, static_folder="build", static_url_path="/") @app.route("/") def index(): return send_from_directory(app.static_folder, "index.html") @app.route("/api") def hello_world(): return {"data": "...
python
from typing import Union from dimod import BinaryQuadraticModel, ConstrainedQuadraticModel from omniqubo.transpiler import TranspilerAbs from ..sympyopt import SympyOpt class DimodToSympyopt(TranspilerAbs): """Transpiler for transforming dimod models into SymptOpt model Transpiler can transform any Binary...
python
from rapidfuzz import fuzz from dvha.tools.roi_name_manager import clean_name class ROINamePredictor: def __init__(self, roi_map, weight_simple=1., weight_partial=0.6, threshold=0): """ :param roi_map: ROI map object :type roi_map: DatabaseROIs """ self.roi_map = roi_map ...
python
import hou import AttributeName as an def findPointAttrType(node_relative_path, attr_name): attr_type = "none" point_attrs = an.point(node_relative_path) if attr_name in point_attrs: if attr_name in an.pointFloat(node_relative_path): attr_type = "f" elif attr_name in ...
python
EPSG_List = [ # ('3819 : HD1909', '3819'), # ('3821 : TWD67', '3821'), # ('3824 : TWD97', '3824'), # ('3889 : IGRS', '3889'), # ('3906 : MGI 1901', '3906'), # ('4001 : Unknown datum based upon the Airy 1830 ellipsoid', '4001'), # ('4002 : Unknown datum based upon the Airy Modified 1849 ellip...
python