content
stringlengths
5
1.05M
# -*- coding: utf-8 -*- """ Copyright [2020] [Sinisa Seslak (seslaks@gmail.com) 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/lice...
import numpy as np class Kalman(object): DIMENSIONS = 3 MEASUREMENT = 1 def __init__(self, q, r): #initialise self.Q = np.matrix(np.eye(Kalman.DIMENSIONS)*q) self.R = np.matrix(np.eye(Kalman.MEASUREMENT)*r) self.H = np.matrix(np.zeros((Kalman.MEASUREMENT, Kalman.DIMENSIO...
# Databricks notebook source # MAGIC %run ./_databricks-academy-helper $lesson="dlt_demo" # COMMAND ---------- try: dbutils.fs.unmount("/mnt/training") except: pass # %run ./mount-datasets # COMMAND ---------- class DataFactory: def __init__(self): self.source = f"{DA.paths.data_source}/tracker/streamin...
r""" bilibili_api.live 直播相关 """ import time from enum import Enum import logging import json import struct import base64 import asyncio from typing import List import aiohttp import brotli from aiohttp.client_ws import ClientWebSocketResponse from .utils.Credential import Credential from .utils.ne...
import sys import os import torch import librosa import soundfile as sf import numpy as np import tkinter as tk from tkinter import filedialog import openunmix from PySide6 import QtCore class Main(QtCore.QThread): def __init__(self): super(Main, self).__init__() self.global_objects = {} de...
#!/usr/bin/env python # -*- coding: utf-8 -*- # File: train-atari.py # Author: Yuxin Wu import numpy as np import sys import os import uuid import argparse import cv2 import tensorflow as tf import six from six.moves import queue from tensorpack import * from tensorpack.tfutils import optimizer from tensorpack.util...
#!/usr/bin/env python import os import sys import socket import rospy from robotiq_control.cmodel_urscript import RobotiqCModelURScript from robotiq_msgs.msg import CModelCommand, CModelStatus def mainLoop(urscript_topic): # Gripper is a C-Model that is connected to a UR controller. # Commands should be published...
import torch import torch.nn.functional as F class DynamicsModel(torch.nn.Module): # transitioin function def __init__(self, D_in, D_out, hidden_unit_num): print("[DynamicsModel] H =",hidden_unit_num) super(DynamicsModel, self).__init__() # zero hidden layer #self.l1 = torch.nn.Li...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Script to plot storage IO timing usage from profiling data. This script requires the matplotlib and numpy Python modules. """ from __future__ import print_function from __future__ import unicode_literals import argparse import glob import os import sys import numpy ...
# -*- coding: utf-8 -*- import datetime from django.db import models from django.core.validators import MaxValueValidator, MinValueValidator from taxi_online_example.utils import date_now_or_future_validator, UTC from django.forms.models import model_to_dict class TaxiLocation(models.Model): taxi_id = models.Cha...
from get_data import *
import os import gzip import shutil import struct import urllib import numpy as np import matplotlib.pyplot as plt import tensorflow as tf os.environ['TF_CPP_MIN_LOG_LEVEL']='2' def read_data(filename): """ :param filename :return: array """ text = open(filename, 'r').readlines()...
#!/usr/bin/env python """ DBSCAN Project - M2 SSI - Istic, Univ. Rennes 1. Andriamilanto Tompoariniaina <tompo.andri@gmail.com> This module is an implementation of K-mean algorithm to confront it with our implementation of the DBSCAN one. """ # -- Imports import sys import random import operator from pandas import D...
import csv from stations import Station, Stations csvfile="./source/stations_aod.csv" def readCSV(csv_file): stations_aod=dict(); with open(csv_file,'rb') as csvfile: spamreader=csv.reader(csvfile,delimiter=",",quotechar='|') for row in spamreader: stations_aod[row[0]]=(row) ...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None from math import log class Solution: # @param {TreeNode} root # @return {integer[]} def rightSideView(self, root): def df...
#Ejercicio 2 - Cuaderno 2 """ Implementa un programa modularizado que, leyendo de teclado los valores necesarios, muestre en pantalla el área de un círculo, un cuadrado y un triángulo. Utiliza el valor 3.1416 como aproximación de П (pi) o importa el valor del módulo “math”. """ import math print ('Círculo') radio= f...
import sys def main(): infile=open(sys.argv[1],"r") counter=0 tf="" for l in infile: if (">" in l): s=l.split() if (tf!=""): print(tf+'\t'+str(counter)) counter=0 tf=s[1].upper() elif ("#" not in l): counter+=1 print(tf+'\t'+str(counter)) infile.close() main()
# -*- coding: utf-8 -*- """ @author: Hiromasa Kaneko """ import pandas as pd from sklearn.neighbors import NearestNeighbors # k-NN k_in_knn = 5 # k-NN における k rate_of_training_samples_inside_ad = 0.96 # AD 内となるトレーニングデータの割合。AD のしきい値を決めるときに使用 dataset = pd.read_csv('resin.csv', index_col=0, header=0) x_pr...
from BogoBogoSort import bogoBogoSort from BogoSort import bogoSort from BozoSort import bozoSort from CommunismSort import communismSort from MiracleSort import miracleSort from StalinSort import stalinSort from SlowSort import slowSort import numpy as np import time import matplotlib import matplotlib.pyplot a...
# # Copyright 2021 Red Hat Inc. # SPDX-License-Identifier: Apache-2.0 # """Django model mixins and utilities.""" class RunTextFieldValidators: """ Mixin to run all field validators on a save method call This mixin should appear BEFORE Model. """ def save(self, *args, **kwargs): """ ...
#! python3 # voicechannelcontrol.py """ ============================================================================== MIT License Copyright (c) 2020 Jacob Lee 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...
""" Copyright MIT and Harvey Mudd College MIT License Summer 2020 Lab 3B - Depth Camera Cone Parking """ ######################################################################################## # Imports ######################################################################################## import sys import cv2 as...
import pytest class RespIs: @staticmethod async def no_content(resp): assert resp.status == 204 @staticmethod async def bad_gateway(resp, message="Bad gateway"): """ Check whether a response object is a valid Virtool ``bad gateway``. """ assert resp.status == 5...
""" Some examples playing around with yahoo finance data """ from datetime import datetime from pandas.compat import zip import matplotlib.finance as fin import numpy as np from pylab import show from pandas import Index, DataFrame from pandas.core.datetools import BMonthEnd from pandas import ols startDate = date...
#!/usr/bin/env python # -*- coding: utf-8 -*- import math import torch import torch.nn as nn import torch.utils.model_zoo as model_zoo import torch.autograd as autograd from torch.autograd.variable import Variable from threading import Lock from torch.distributions import Categorical global_lock = Lock() model_urls...
from sqlalchemy import Table, Column, Integer, String, ForeignKey from utils import metadata category = Table( "category", metadata, Column("id", Integer, primary_key=True), Column("parent_fk", Integer, ForeignKey("category.id"), nullable=True), Column("label", String(length=60), unique=True, n...
import lark from foyer.exceptions import FoyerError GRAMMAR = r""" start: _string // Rules _string: _chain _nonlastbranch* _lastbranch? _chain: atom _chain | atom _nonlastbranch: "(" branch ")" _lastbranch: branch branch: _string atom: ("[" weak_and_expression "]" | atom_symbol) atom_...
""" Created on 13-Apr-2018 @author: jdrumgoole """ import unittest import pymongo from dateutil.parser import parse from pymongoimport.audit import Audit class Test_Audit(unittest.TestCase): def setUp(self): self._client = pymongo.MongoClient(host="mongodb://localhost/TEST_AUDIT") self._databa...
# search target number in the list. class LinearSearch : def __init__(self,target, data): self.data = data self.target = target print(self.doSearch()) def doSearch(self): for current in self.data : if current == self.target : return "Target Number...
import numpy as np from flask import Flask, render_template, request import jinja2 from MBScalc import * #Init Flask App app = Flask(__name__) @app.route('/', methods = ['GET','POST']) def main(): number = int(request.form['number']) if request.method == 'POST': result = number else: result = 0 # mass = float...
# -*- coding: utf-8 -*- import logging from random import randint import re import six import os from datetime import datetime __author__ = "Arun KR (kra3) <the1.arun@gmail.com>" __license__ = "Simplified BSD" RE_IP = re.compile(r'^[\d+]{1,3}\.[\d+]{1,3}\.[\d+]{1,3}\.[\d+]{1,3}$', re.I) RE_PRIV_IP = re.compile(r'^(?...
from Cimpl import load_image, create_color, set_color, show, Image, save_as, copy from typing import NewType image = load_image('p2-original.jpg') # loads the original colourless picture def createBlue( image ): """ the function createBlue displays the original image, once closed it displays the image with a bl...
import os import sys from random import Random import numpy as np from os.path import join import re from gpsr_command_understanding.generator.grammar import tree_printer from gpsr_command_understanding.generator.loading_helpers import load, GRAMMAR_YEAR_TO_MODULE, load_paired from gpsr_command_understanding.generato...
#!/usr/bin/env python3 from sys import argv,stderr,exit import json, os, yaml, pynetbox, re, ipaddress from collections import defaultdict from pprint import pprint doc = """ Get config context from netbox for specified device. ## Usage %s "FQDN" """ % (argv[0]) def assume_ip_gateway(network): return str(ipadd...
from scipy.optimize import shgo import numpy as np from numpy.linalg import norm class VectorCubicSpline: """ a0, a1, a2, a3 are numpy vectors, they form the spline a0 + a1*s + a2*s^2 + a3*s^3 """ def __init__(self, a0, a1, a2, a3): self.a0 = np.array(a0) self.a1 = np.array(a1) self.a2...
class Fonction: def calcul(self, x): pass class Carre(Fonction): def calcul(self, x): return x*x class Cube(Fonction): def calcul(self, x): return x*x*x def calcul_n_valeur (l,f): res = [ f(i) for i in l ] return res l = [0,1,2,3] l1 = calcul_n_valeur(l, Carre().cal...
import findspark findspark.init() from pyspark import SparkConf,SparkContext from pyspark.streaming import StreamingContext from pyspark.sql import Row,SQLContext import sys import requests def aggregate_tags_count(new_values, total_sum): return sum(new_values) + (total_sum or 0) def get_sql_context_instance(spark_...
""" API serializers """ from rest_framework import serializers from groups.models import CustomUser, Group, Link class CustomUserBaseSerializer(serializers.ModelSerializer): """ CustomUser base serializer """ class Meta: model = CustomUser fields = ('id', 'username', 'email', 'date_jo...
import argparse import json from pathlib import Path from typing import Iterable, Set import pandas as pd from hyperstyle.src.python.review.inspectors.inspector_type import InspectorType from hyperstyle.src.python.review.inspectors.issue import BaseIssue, IssueType from hyperstyle.src.python.review.reviewers.utils.pri...
""" The STDIO interface for interactive CIS. Authors: Hamed Zamani (hazamani@microsoft.com) """ import time import traceback from macaw import util from macaw.interface.interface import Interface from macaw.core.interaction_handler.msg import Message class StdioInterface(Interface): def __init__(self, params):...
from rest_framework import status from webfront.tests.InterproRESTTestCase import InterproRESTTestCase from webfront.models.interpro_new import Release_Note class UtilsAccessionTest(InterproRESTTestCase): def test_can_read_structure_overview(self): response = self.client.get("/api/utils") self.ass...
import os os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2" os.environ["CUDA_VISIBLE_DEVICES"] = "3" import warnings warnings.filterwarnings('ignore') import pickle as pickle import numpy as np import datetime from keras import Model import keras import queue from keras.layers import Dense, Activation, Dropout, Layer...
boot_list = [ "anklet", "boots", "clogs", "feet", "footguards", "footpads", "footsteps", "footwraps", "greatboots", "greaves", "heels", "sabatons", "sandals", "slippers", "sneakers", "socks", "sprinters", "spurs", "stompers", "treads", "walkers", "warboots", "wraps", "zoomers"] body_list = [ "bande...
# -*- coding: utf-8 -*- import cv2 import numpy as np from typing import Tuple, List, Union from image_registration.keypoint_matching.kaze import KAZE from image_registration.exceptions import (CreateExtractorError, NoModuleError, NoEnoughPointsError) class ORB(KAZE): METHOD_NAME = "ORB" def __init__(self, t...
""" functions for deterministically preprocessing 2D images (or 3D with color channels) mostly for the consumption of computer vision algorithms """ import math import numpy as np import skimage.transform from .. import utils def _center_coords_for_shape(shape): """ returns the center of an ndimage with a gi...
# This file is a part of Arjuna # Copyright 2015-2020 Rahul Verma # Website: www.RahulVerma.net # 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...
# Copyright (c) 2019, Ahmed M. Alaa # Licensed under the BSD 3-clause license (see LICENSE.txt) import pandas as pd import numpy as np def draw_ihdp_data(fn_data): # Read the covariates and treatment assignments from the original study # -----------------------------------------------------------------...
import numpy as np from numba import njit, prange from SZR_contact_tracing import nb_seed, update_cell, szr_sample, mszr_sample @njit def cluster_size(L: int, seed: int, alpha: float = 0.25, occupancy: float = 1, mszr: bool = True): # Initialize a lattice, run it, and return the cluster size. nb_seed(L) l...
"""Constants for the Kostal Plenticore Solar Inverter integration.""" from typing import NamedTuple from homeassistant.components.sensor import ( ATTR_STATE_CLASS, SensorDeviceClass, SensorStateClass, ) from homeassistant.const import ( ATTR_DEVICE_CLASS, ATTR_ICON, ATTR_UNIT_OF_MEASUREMENT, ...
import pdb import uuid from decimal import Decimal from django.apps import apps from ahj_app.models import User, Edit, Comment, AHJInspection, Contact, Address, Location, AHJ, AHJUserMaintains from django.urls import reverse from django.utils import timezone import pytest import datetime from fixtures import create_u...
from flask import Blueprint, g, request, current_app import json import logging from ..utils import datetime_to_json, get_time_string, get_default_runtime, match_movie import datetime from ..pick_algo import pick_movies_by_num, pick_movies_by_time from .auth import login_required import pandas import pathlib from .. i...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # from "SuperShape2D" (Daniel Shiffman) # Video: https://youtu.be/ksRoh-10lak # supershapes: http://paulbourke.net/geometry/supershape/ import sys, os from PyQt5.QtWidgets import * from PyQt5.QtGui import * from PyQt5.QtCore import * import math import numpy as np def...
"""Convert all the old posts. Author: Alex Alemi Date: 2019-01-23 """ import os import logging CURRENT_DIR = os.path.dirname(__file__) POSTS_DIR = os.path.normpath(os.path.join(CURRENT_DIR, '../posts/old')) def fix_front(line): """Redo the front of the metadata lines for the nikola format.""" return '.. ' +...
# Generated by Django 2.2.24 on 2021-07-26 14:50 import django.core.validators from django.db import migrations, models def split_dates(apps, schema_editor): CompanyObjective = apps.get_model('exportplan', 'CompanyObjectives') for objective in CompanyObjective.objects.all(): if objective.start_date: ...
"""https://gist.github.com/alopes/5358189""" stopwords = [ "de", "a", "o", "que", "e", "do", "da", "em", "um", "para", "é", "com", "não", "uma", "os", "no", "se", "na", "por", "mais", "as", "dos", "como", "mas", "foi", ...
import pygame from . import GameEnv, GameEnv_Simple, Ball, Robot, Goal from typing import Tuple, List, Dict import random class AbstractPlayer: def __init__(self, env: GameEnv, robot: Robot): self.env = env self.robot = robot def get_action(self) -> Tuple[float, float]: raise Exception...
class Solution: def XXX(self, head: ListNode) -> ListNode: try: new_head = new_tail = ListNode(head.val) p = head.next while p: if new_tail.val != p.val: node = ListNode(p.val) new_tail.next = node ...
from PIL import Image # Charger l'image img = Image.open('/home/popschool/Documents/GitHub/projet_recoplante/Images_test/bruyere_des_marais_NB.jpg') # Afficher l'image chargée img.show() # Récupérer et afficher la taille de l'image (en pixels) w, h = img.size print("Largeur : {} px, hauteur : {} px".format(w, h)...
import unittest from Config import Config from MossResultsRetriever import MossResultsRetriever from Result import Result class MossURLsTests(unittest.TestCase): def setUp(self): self.config = Config() self.validUrl = self.config.getMagicsquare() self.retriever = MossResultsRetriever() ...
import io import os.path import shutil import sys import tempfile import re import unittest from types import ModuleType from typing import Any, List, Tuple, Optional from mypy.test.helpers import ( assert_equal, assert_string_arrays_equal, local_sys_path_set ) from mypy.test.data import DataSuite, DataDrivenTest...
# Generated by Django 3.2.12 on 2022-02-16 23:46 import django.core.validators from django.db import migrations, models import re class Migration(migrations.Migration): dependencies = [ ('customer', '0001_initial'), ] operations = [ migrations.RemoveField( model_name='custom...
###################################################################### # # File: b2/download_dest.py # # Copyright 2019 Backblaze Inc. All Rights Reserved. # # License https://www.backblaze.com/using_b2_code.html # ###################################################################### from b2sdk.download_dest import *...
# AUTOGENERATED BY NBDEV! DO NOT EDIT! __all__ = ["index", "modules", "custom_doc_links", "git_url"] index = {"index_flow": "00_core.ipynb", "query_flow": "00_core.ipynb", "slugify": "01_loader.ipynb", "get_image_files": "01_loader.ipynb", "verify_image": "01_loader.ipynb", ...
from checkov.common.models.enums import CheckCategories from checkov.terraform.checks.resource.base_resource_negative_value_check import BaseResourceNegativeValueCheck class VMDisablePasswordAuthentication(BaseResourceNegativeValueCheck): def __init__(self): name = "Ensure that Virtual machine does not en...
"""Tests for encoder routines to tf.train.Exammple.""" from absl.testing import parameterized import tensorflow as tf from tensorflow_gnn.graph import graph_constants as gc from tensorflow_gnn.graph import graph_tensor as gt from tensorflow_gnn.graph import graph_tensor_encode as ge from tensorflow_gnn.graph import gr...
from django import forms from fir_nuggets.models import NuggetForm from incidents import models as incident_models class LandingForm(NuggetForm): new = forms.BooleanField(initial=True, required=False) event = forms.ModelChoiceField(queryset=incident_models.Incident.objects.exclude(status='C'), required=False) st...
#!/usr/bin/env python #==================================================== import copy import uuid import numpy as np import threading from Utilities.decorators import thread #==================================================== class CircuitCritic(object): def __init__(self, circuit_params): self.circuit_p...
# -*- coding: utf-8 -*- """ easybimehlanding This file was automatically generated by APIMATIC v2.0 ( https://apimatic.io ). """ import easybimehlanding.models.travel_insurance_policy_extend class TravelInsurancePolicyExtendView(object): """Implementation of the 'TravelInsurancePolicyExtend...
# Copyright (c) 2016-2020, The Bifrost Authors. 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 conditi...
from .clock import Clock from .identity import Identity from .license import License from .note import Note from .resource import Resource __all__ = ["Clock", "Identity", "License", "Note", "Resource"]
from behave import * from src.hamming import distance from assertpy import assert_that use_step_matcher("re") @given("two strands") def step_impl(context): context.distance = distance @when("(?P<strand1>.+) and (?P<strand2>.+) are same length") def step_impl(context, strand1, strand2): context.result = conte...
# # This file is an example to set the environment. # The configs will be used in dmrgci.py and chemps2.py # import os from pyscf import lib # To install Block as the FCI solver for CASSCF, see # http://sunqm.github.io/Block/build.html # https://github.com/sanshar/Block BLOCKEXE = '/path/to/Block/block.sp...
from nipype.interfaces.base import BaseInterface, \ BaseInterfaceInputSpec, traits, File, TraitedSpec, InputMultiPath, Directory from nipype.utils.filemanip import split_filename import nibabel as nb import numpy as np import os class ConsensusInputSpec(BaseInterfaceInputSpec): in_Files = traits.Either(InputMu...
#!/usr/bin/env python ## Program: VMTK ## Module: $RCSfile: vmtksurfacedistance.py,v $ ## Language: Python ## Date: $Date: 2005/09/14 09:49:59 $ ## Version: $Revision: 1.6 $ ## Copyright (c) Luca Antiga, David Steinman. All rights reserved. ## See LICENSE file for details. ## This software is d...
# -*- coding: utf-8 -*- #______________________________________________________________________________ #______________________________________________________________________________ # # Coded by Daniel González Duque #______________________________________________________________________________...
from app import db import os import requests class Movies(db.Model): """ Models the data of movies related to a given location. """ id = db.Column(db.Integer, primary_key=True) movies = db.Column(db.Text) @staticmethod def create_entry(query): """ Takes in a search query...
# # Copyright (c) 2015-2021 Thierry Florac <tflorac AT ulthar.net> # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRAN...
from pydocstyle.checker import check from pydocstyle.checker import violations import testing registry = violations.ErrorRegistry _disabled_checks = [ 'D202', # No blank lines allowed after function docstring 'D205', # 1 blank line required between summary line and description ] def check_all_files(): ...
# Copyright 2015 Google Inc. 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 applicable law or a...
# Generated by Django 3.0.2 on 2020-10-13 07:23 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('accounts', '0005_thirdpartycreds'), ] operations = [ migrations.AlterModelOptions( name='thirdpartycreds', options={'verbose...
from skynet.common.base_daos import BaseDao class BaseModel(object): DEFAULT_DAO = BaseDao def __init__(self, dao=None): if dao is None: dao = self.DEFAULT_DAO() self.dao = dao def populate(self, data): for k, v in data.iteritems(): k_transl...
import os import json import html from datetime import datetime, timedelta from fastapi import FastAPI, HTTPException from fastapi.middleware.cors import CORSMiddleware from starlette.requests import Request from starlette.responses import JSONResponse from auth import LEADERBOARD_API_TOKEN app = FastAPI(redoc_url=...
# -*- encoding: utf-8 -*- """Handle root-services sessions endpoints.""" from .base import RootService from ..decorators import dyndoc_insert, endpoint from .responses.sessions import responses @endpoint("openapi/root/v1/sessions/capabilities/") class GetSessionCapabilities(RootService): """Get the sessions cap...
from __future__ import unicode_literals from . import model from . import collection from . import fields from . import related
from collection.property_dictionary import PropertyDict from collection.xml_interface import XMLError from collection.xml_interface import XMLInterface from metadata.metadata_api import MetadataError from metadata.metadata_api import Metadata from image.envi import ENVIHeader
import json import logging import re from datetime import datetime from decimal import Decimal from enum import Enum from functools import singledispatch from sys import version_info from typing import Any, Optional, Tuple, Union from urllib.parse import urlsplit PY37 = version_info >= (3, 7) class JSONEncoder(json....
""" Adapted from https://github.com/kirubarajan/roft/blob/master/generation/interactive_test.py to process a batch of inputs. """ import argparse import json import numpy as np import os import torch from transformers import AutoModelForCausalLM, AutoTokenizer def main(args): np.random.seed(args.random_seed) ...
#!/bin/python3 import math count = 0 def count_inversions(a): length = len(a) if (length <= 1): return a else: midP = int(math.floor(length / 2)) left = a[:midP] right = a[midP:] return merge(count_inversions(left), count_inversions(right)) def merge(left, right)...
import sklearn from sklearn.linear_model import Perceptron from sklearn.datasets import load_iris import pandas as pd import numpy as np import matplotlib.pyplot as plt # load data iris = load_iris() df = pd.DataFrame(iris.data, columns=iris.feature_names) df['label'] = iris.target df.columns = [ 'sepal length', ...
# 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. """A basic unit test for the Python interface of the BMG C++ Graph.infer method""" import unittest import beanmachine.ppl as bm from beanma...
# this brainfuck source code from https://github.com/kgabis/brainfuck-go/blob/master/bf.go # and karminski port it to PHP # and is ported to Python 3.x again # Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php import sys class Brainfuck: # operators op_inc_dp = 1 op_dec_...
import os import platform import getpass if(platform.system() == "Windows"): os.system("cls") print(" _") print("__ _____| | ___ ___ _ __ ___ ___ ") print("\ \ /\ / / _ \ |/ __/ _ \| '_ ` _ \ / _ \ ") print(" \ V V / __/ | (_| (_) | | | | | | __/ ") print(" \_...
""" Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: MIT-0 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 limitat...
"""Utility code for argparse""" import argparse import yaml #class StoreDictKeyPair(argparse.Action): # """An action for reading key-value pairs from command line""" # def __call__(self, parser, namespace, values, option_string=None): # my_dict = {} # for kv in values.split(","): # k,v ...
# datastore transations and methods from sqlalchemy.orm import load_only from sqlalchemy.sql import text def count_records(session, model, **kwargs): row_count = session.query(model).filter_by(**kwargs).count() return row_count def delete_record(session, model, **kwargs): instance = session.query(model...
import rclpy from rclpy.node import Node from rclpy.qos import qos_profile_sensor_data from sensor_msgs.msg import Image # Image is the message type import cv2 # OpenCV library from cv_bridge import CvBridge # Package to convert between ROS and OpenCV Images import numpy as np # Naming the Output window windowname = ...
from random import randint import pygame as pg from scripts import constants as const class Bird(pg.sprite.Sprite): SIZE = const.SPRITE_SIZE[0] MIN_SPEED = 1 MAX_SPEED = 10 def __init__(self, bird_image): pg.sprite.Sprite.__init__(self) self.image = bird_image self.rect = sel...
""" Example showing for tkinter and ttk how to do: -- Simple animation -- on a tkinter Canvas. References: -- https://effbot.org/tkinterbook/canvas.htm This is the simplest explanation, but very old and possibly somewhat out of date. Everywhere that it says "pack" use "grid" instead. -- Th...
class LinkedList: def __init__(self, head): self.head = head self.current_element = self.head # Node navigation def next(self): if self.current_element.next is None: return self.current_element = self.current_element.next def go_back_to_head(self): ...
import pandas as pd import os import subprocess as sub import re import sys from Bio import SeqUtils import matplotlib.pyplot as plt import numpy as np from scipy import stats # path = os.path.join(os.path.expanduser('~'),'GENOMES_BACTER_RELEASE69/genbank') path = "." # ['DbxRefs','Description','FeaturesNum','assemb...