content
stringlengths
5
1.05M
""" Master class for the AIRC """ import asyncio import logging from . import server from .abstracts import Messageable __all__ = ("User", "Channel", "DefaultClient") log = logging.getLogger("airc.client") async def empty_handler(event): pass def empty_handler_sync(event): pass class User(Messageable): ...
import inspect from core import reify, run_goal, variables, gen_name from goals import conj from stream import SuspendIteration def run(*args): if isinstance(args[0], int): n = args[0] args = args[1:] else: n = None var, goals = args[0], args[1:] if isinstance(var, tuple): ...
#!/usr/bin/python try: import simplejson as json except ImportError: import json import couchdb import httplib import urllib import common import unittest HOST = "localhost:5984" SET_NAME = "test_suite_set_view" # Can't use something higher than 96 on Mac OS X, start getting # system_limit errors due to too many fil...
# -*- coding: utf-8 -*- import os from unittest import TestCase import json import requests import responses from odata import ODataService from odata.entity import EntityBase path = os.path.join(os.path.dirname(__file__), 'demo_metadata.xml') with open(path, mode='rb') as f: metadata_xml = f.read() class Tes...
# -------------------------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # --------------------------------------------------------------------...
# Generated by Django 2.0.5 on 2018-06-06 04:39 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('archives_app', '0003_auto_20180606_0822'), ] operations = [ migrations.RenameField( model_name='category', old_name='subdirs...
from os import getenv class Config: def __init__(self): self.database = getenv("DB_PATH", "mangaloid.db") self.http_port = int(getenv("HTTP_PORT", "1337")) self.admin_ips = [i.strip() for i in getenv("ADMIN_IPS", "").split(",")] self.instance_name = getenv("INSTANCE_NAME") ...
import os from .model import ( Resnet50, Vgg16, ) MODEL = { "resnet50": Resnet50, "vgg16": Vgg16 } ### Export model model = MODEL[os.getenv("visual_model.model")] model = model().to(os.getenv("visual_model.device")).eval()
#! /usr/bin/env python3 import numpy as np import tkinter as tk def coords2xbm(coords, returnOffset=False, joinstr=', '): """ Draw an XBM-formatted image from coordinates. :param coords: The coordinates to be set as image foreground :type coords: (N,2)-shaped numpy array with x-values in first and y-v...
import os import subprocess import glob from .env import IS_CONDA, IS_LINUX, IS_WINDOWS, CONDA_DIR, check_env_flag, check_negative_env_flag, gather_paths from .cuda import USE_CUDA # On ROCm, RCCL development isn't complete. https://github.com/ROCmSoftwarePlatform/rccl USE_DISTRIBUTED = not check_negative_env_flag("U...
import re def text_match(text): patterns = '^[a-z]+_[a-z]+$' if re.search(patterns, text): return 'Found a match!' else: return('Not matched!') print(text_match("aab_cbbbc")) print(text_match("aab_Abbbc")) print(text_match("Aaab_abbbc"))
import dbc.ast as ast from dbc.visit import Visitor from dbc.errors import CheckError from collections import OrderedDict class TypeChecker(Visitor): """ This class extends Visitor and is responsible for checking for any type errors like for example: - wrong type of arguments for function calls. - using t...
# coding=utf-8 # Copyright 2022 The Google Research 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 applicab...
from nose.tools import istest, assert_equal from mammoth.docx.xmlparser import element as xml_element from mammoth.docx.numbering_xml import read_numbering_xml_element from mammoth.docx.styles_xml import NumberingStyle, Styles @istest def find_level_returns_none_if_num_with_id_cannot_be_found(): numbering = _rea...
#!/usr/bin/env python # coding: utf-8 # In[2]: import pandas as pd import matplotlib.pyplot as plt import numpy as np from bs4 import BeautifulSoup import requests from itertools import chain from tqdm import tqdm_notebook as tqdm import re # In[51]: def parse_bat_table(tbl): columns = tbl.find_all('th') ...
"""Unit test package for dji_asdk_to_python."""
import numpy as np import pandas as pd import logging import plotly.graph_objects as go from sklearn.preprocessing import MinMaxScaler from datetime import datetime, timedelta import scipy.io DATA_PATH = 'data/nasa-randomized/' NOMINAL_CAPACITY = 2.2 class NasaRandomizedData(): def __init__(self, base_path="./")...
import os import torch import cv2 import torch.nn as nn import torchvision.datasets as datasets import torch.utils.data as data from PIL import Image from torchvision import transforms from glob import glob from torch.utils.data import DataLoader, Dataset import glob import numpy as np from skimage import io from torch...
from django.contrib import admin # Expose the Experiment Model on the Admin Site from tp.models import Experiment #todo: register more models? security of admin pannel admin.site.register(Experiment)
# -*- coding: utf-8 -*- # @Time : 3/31/2021 3:08 PM # @Author : Rex Yu # @Mail : jiafish@outlook.com # @Github : https://github.com/Rexyyj from common.MyMQTT import * from common.RegManager import * import json import time class MotorConnector(): def __init__(self, confAddr): try: se...
'''https://leetcode.com/problems/jump-game/ 55. Jump Game Medium 8538 507 Add to List Share You are given an integer array nums. You are initially positioned at the array's first index, and each element in the array represents your maximum jump length at that position. Return true if you can reach the last index, ...
# mode: python; py-indent-offset: 4; tab-width: 8; coding:utf-8 ''' Copyright 2022 Airbus SAS 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 ...
from .admin_feedback_list_view import AdminFeedbackListView from .region_feedback_list_view import RegionFeedbackListView from .admin_feedback_actions import ( mark_admin_feedback_as_read, mark_admin_feedback_as_unread, delete_admin_feedback, ) from .region_feedback_actions import ( mark_region_feedback...
from django.conf import settings from django.contrib import admin from django.conf.urls import include, url from django.conf.urls.static import static urlpatterns = [ url('admin/', admin.site.urls), url('', include('home.urls')), url(r'^db/', include(('database.urls', 'database'), namespace='db')) ] + stat...
# File: awssystemsmanager_consts.py # # Copyright (c) 2019-2022 Splunk 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 requi...
# Normal libraries from enum import IntEnum class DefaultErrorType(IntEnum): """ An enumerable object for the default errors that occur with interaction creation. .. note:: This is a port from v3's errors, which basically delegate errors to a unique error code. This enum's purpose is to h...
############################## # author : qianqiu # email : qianqiu@tencent.com # time : 2022.1.7 ############################## import os import tvm import tvm.relay as relay from tvm.driver import tvmc from tvm.contrib import graph_executor from tvm import auto_scheduler import onnx import onnx_graphsurgeon as gs imp...
import glob import settings as settings import zipfile import arrow import os import shutil import logging """ look in unpacked_renamed_ejp_files look for all matching pdf and xml files elife_poa_e000213.xml elife_poa_e000213.pdf If there is an xml or pdf file that is not matched, log an error for the day of deli...
""" Hosts the actions and a function to create them """ from collections import namedtuple from shared.orders import Order Action = namedtuple("Action", "event orders conditions") def loadAction(event, dat, named): """ Returns an action instance from a Xml structure and name mapping """ orders = [] for o...
#/usr/bin/python3 # -*- coding:Utf-8 -*- """ Module principal, c'est le point d'entrée """ import os import shutil import datetime import sys import argparse import time import gi gi.require_version('Gtk', '3.0') gi.require_version('Notify', '0.7') from gi.repository import Gtk, Gdk, GdkPixbuf, Gio, Notify from cr...
# Generated by Django 3.0.6 on 2020-09-16 19:47 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('authentication', '0001_initial'), ] operations = [ migrations.AddField( model_name='user', name='auth_provider', ...
# -*- coding: utf-8 -*- currencymap = { "AED": "United Arab Emirates dirham" ,"AFN": "Afghan afghani" ,"ALL": "Albanian lek" ,"AMD": "Armenian dram" ,"ANG": "Netherlands Antillean guilder" ,"AOA": "Angolan kwanza" ,"ARS": "Argentine peso" ,"AUD": "Australian dollar" ,"AWG": "Aruban florin" ,"AZN": "Azerbaijani manat" ...
from django.contrib.auth import get_user_model from django.contrib.staticfiles.templatetags.staticfiles import static from django.db import models from django.utils.text import Truncator from meta.models import ModelMeta class Post(ModelMeta, models.Model): ''' Blog Post ''' title = models.CharField...
# -*- coding: UTF-8 -*- from pyxer.base import * import model @expose def index(): """ List guest book entries and a form for creating new entries. """ if GAE: # Google App Engine query = model.GuestBook.all() query.order("-date") c.messages = query.fetch(limit=20) ...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Created on Mon Oct 30 19:00:00 2017 @author: gsutanto """ import numpy as np import os import sys import copy import glob sys.path.append(os.path.join(os.path.dirname(__file__), '../../../dmp_coupling/utilities/')) sys.path.append(os.path.join(os.path.dirname(__file_...
# -*- coding: utf-8 -*- # Generated by Django 1.10.4 on 2016-12-29 21:43 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [("villages", "0008_auto_20161228_2209")] operations = [ migrations.AlterField( model_name="village", name...
#! usr/bin/python3 # -*- coding: utf-8 -*- # # Flicket - copyright Paul Bourne: evereux@gmail.com import datetime import os from flask import redirect, url_for, flash, render_template, g, request from flask_babel import gettext from flask_login import login_required from . import flicket_bp from application import a...
import pytest from bib_downloader import doi def test_acm_doi(monkeypatch): acm_doi = "10.1145/3428216" def mock_return(_doi_str): return "MOCK RETURN" monkeypatch.setitem(doi.PUBLISHER_LOOKUP, doi.ACM_PREFIX, mock_return) result = doi.process_doi(acm_doi) assert result == "MOCK RETURN...
import sys from resources.lib.timer.set_quick_epg_timer import SetQuickEpgTimer if __name__ == "__main__": SetQuickEpgTimer(sys.listitem)
import tensorflow as tf import numpy as np xin=tf.Variable(tf.constant(np.array([-1.,0.,1.]),shape=[1,3])) we=tf.Variable(tf.constant(np.array([[0.1,0],[-0.2,0.3],[0.4,-0.6]]),shape=[3,2])) bi=tf.Variable(tf.constant(np.array([0.3,0.1]),shape=[2])) yout=tf.nn.tanh(tf.matmul(xin,we)+bi) g_we = tf.gradients(yout,we) g...
# Definition for singly-linked list. class Solution: def isPalindrome(self, head: ListNode) -> bool: # Initial, naive Solution forward = [] reverse = [] curr = head while curr is not None: forward.append(curr.val) reverse.insert(0, curr.val) ...
import numpy as np import pickle import glob import os import matplotlib.pyplot as plt import seaborn as sns sns.set() from pathlib import Path from common.plotting_utils import get_scores, generate_plot, get_all_run_titles, get_all_runs_and_subruns def make_graphs(experiment_name, subdir, ...
# Generated by Django 2.0.3 on 2018-03-08 08:11 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] ope...
import os import json import cv2 import random import re from bs4 import BeautifulSoup as bs from shutil import copyfile from tqdm import tqdm from pathlib import Path from abc import ABCMeta, abstractmethod Path("../coco_df_detr/data").mkdir(parents=True, exist_ok=True) bashCommand = "mkdir ../coco_df_detr\n" \ ...
def fizzbuzz(input_number): words = '' if input_number % 3 == 0: words += 'Fizz' if input_number % 5 == 0: words += 'Buzz' return words or str(input_number)
# -*- coding: utf-8 -*- # # Copyright (c) 2019~2999 - Cologler <skyoflw@gmail.com> # ---------- # some object for parser # ---------- from typing import List import enum import dis from collections import defaultdict class ID: def __init__(self, name): self._name = name # a name use to debug def __r...
from .cacbarcode import CACBarcode, PDF417Barcode, Code39Barcode
# Extracción de una página web de información import requests def generate_hashtags(baselist): url= "http://d212rkvo8t62el.cloudfront.net/tag/" for base in baselist: one = baselist[base][1:] resp= requests.get(url=url+one) data= resp.json() baselist[base] = ['#'+hashtag...
"""Contains utilities for plotting PPI NetworkX graphs.""" # %% # Graphein # Author: Arian Jamasb <arian@jamasb.io> # License: MIT # Project Website: https://github.com/a-r-j/graphein # Code Repository: https://github.com/a-r-j/graphein from typing import List, Optional import networkx as nx import plotly.express as p...
#!/usr/bin/env python # # Utility methods for security descriptor manipulation # # Copyright Nadezhda Ivanova 2010 <nivanova@samba.org> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either v...
class AnnotationEvent: event_type = 'event' def __init__(self, time): self.time = time def to_json(self): return { **self.__dict__, 'type': self.event_type }
from armulator.armv6.opcodes.abstract_opcodes.umaal import Umaal from armulator.armv6.opcodes.opcode import Opcode class UmaalT1(Umaal, Opcode): def __init__(self, instruction, m, d_hi, d_lo, n): Opcode.__init__(self, instruction) Umaal.__init__(self, m, d_hi, d_lo, n) def is_pc_changing_opco...
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from ... import _utilities fro...
# # Brambox version: Automatically generated version file # Copyright EAVISE # __version__ = "1.1.0+b"
#!/usr/bin/python3 # coding=utf-8 # import os import threading import socketserver import select import struct import logging import logging.config import datetime import time import json import yaml import ssl import paho.mqtt.publish as publish from crc import CRC_GT02 THREAD_TIMEOUT = 120 # seconds config = {} #...
#!/usr/bin/env/python # File name : LED_test.py # Author : majki # Date : 2020/11/01 #import web_pdb; web_pdb.set_trace() import move import robotLight import ultra import os #import info import RPIservo from time import sleep def arm_park(): sc.certSpeed([12,13,14], [50,50,0], [70,70,40]) def arm_...
""" Luke """ from mmcv.utils import Registry, build_from_cfg from torch import nn TOKENIZERS = Registry('tokenizer') def build_tokenizer(cfg, default_args=None): if 'Wrapper' in cfg['type']: wrapper = build_from_cfg(cfg, TOKENIZERS, default_args) return wrapper.tokenizer else: return...
from flask import jsonify, request from flask_restful import Resource from zeep.exceptions import Fault from marshmallow import ValidationError from ..libs import VivaMyPages from ..libs import VivaAttachments from ..libs import hash_to_personal_number from ..libs import authenticate class Attachment(Resource): ...
from PIL import Image # Python Imaging Library import math # Maths functions import sys # Allows us to access function args import os # Allows us to split the text for saving the file filePath = sys.argv[1] # adjusted the layout of the cubes to match the format used by humus. # X ->...
# IPython log file from tqdm import tqdm import dask.array as da import zarr import itertools from skimage.transform import downscale_local_mean lls = da.from_zarr('data/gokul-lls/aollsm-m4-560nm.zarr') lls3 = zarr.open('data/gokul-lls/aollsm-m4-560nm-downscale.zarr', dtype=np.float32, shape=(199, 201, 192, 256), chu...
""" ExportProgressDialog :Authors: Berend Klein Haneveld 2013 """ from PySide.QtGui import QDialog from PySide.QtGui import QGridLayout from PySide.QtGui import QProgressBar from PySide.QtGui import QLabel class ExportProgressDialog(QDialog): """ ExportProgressDialog is a dialog that shows a progress bar or bus...
import matplotlib as mpl import numpy as np from matplotlib import pyplot as plt def show_sample(sample): """Shows the sample with tasks and answers""" print("Train:") for i in range(len(sample["train"])): fig = plt.figure() ax1 = fig.add_subplot(121) ax1.matshow(np.array(sample["...
#!/usr/local/bin/python __metaclass__=type class Rectangle: def __init__(self): self.width=0 self.height=0 def setSize(self,size): self.width,self.height=size def getSize(self): return self.width,self.height size=property(getSize,setSize) r=Rectangle() r.width=15 r.height=10 print r.size r.size=...
#!/usr/bin/env python # # description: Toeplitz Matrix # difficulty: Easy # leetcode_num: 766 # leetcode_url: https://leetcode.com/problems/toeplitz-matrix/ # # Given an m x n matrix, return true if the matrix is Toeplitz. Otherwise, return false. # A matrix is Toeplitz if every diagonal from top-left to bottom-right h...
from gpvolve.cluster.utils import assignment, membership, crispness, cluster_assignments from gpvolve.cluster.pcca import cluster from gpvolve.cluster.opt import optimize import gpvolve.cluster.criteria as criteria
from rest_framework import serializers from .models import Profile class RequestsSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = ( 'code', 'full_name', 'email', 'phone' ) class ProfileSerializer(serializers.Mode...
import sys input = sys.stdin.readline sizes = {"S": 1, "M": 2, "L": 3} jers = int(input()) athl = int(input()) stuff = [input().rstrip() for n in range(jers)] works = 0 for _ in range(athl): s = input().split() s[1] = int(s[1]) - 1 if (stuff[s[1]] != 0 and sizes[stuff[s[1]]] >= sizes[s[0]]): wor...
#UserName List Generator - D.Patrick Dugan #There probably is a more pythonic way to do this... import argparse import sys class UserNameGen(object): def __init__(self, username, usersfile, outfile, numappend, email): self.username = username self.usersfile = usersfile ...
# -*- coding: utf-8 -*- import os import logging import time import torch import cv2 import numpy as np class Solver(object): def __init__(self, task_name, torch_module, trainset_dataiter, net, net_initializer, op...
import time import subprocess import smbus import Adafruit_SSD1306 as ssd1306 from PIL import Image from PIL import ImageDraw from PIL import ImageFont BUS = 1 ADDR = 0x3C RST = None oled = ssd1306.SSD1306_128_32(rst=RST, i2c_address=ADDR) oled.begin() oled.clear() oled.display() width = oled.width height = oled.h...
import random def data() : return [{'signal_count': n} for n in range(random.randint(50,1000)) for l in range(0, random.randint(1,100))]
from typing import Optional, Tuple from . import BaseHandler, apply_request_schema, apply_response_schema from ..aliases import AliasStoreType, RevealFailed from ..aliases.manager import redact, reveal from ..schemas.aliases import ( AliasResponseSchema, AliasesResponseSchema, RedactRequestSchema, ) STOR...
from django.conf.urls import url from django.contrib import admin from django.views.generic.base import RedirectView from django.conf import settings from django.conf.urls.static import static from .views import ( RetweetView, TweetListView, TweetDetailView, TweetCreateView, TweetUpdateView, ...
#!/usr/bin/env python # -*- coding: utf-8 -*- __author__ = "Evangelos A. Dimopoulos, Evan K. Irving-Pease" __copyright__ = "Copyright 2020, University of Oxford" __email__ = "antonisdim41@gmail.com" __license__ = "MIT" import os import sys import numpy as np import pandas as pd from haystac.workflow.scripts.utiliti...
from isodate import parse_duration from isoduration import parse_duration as isodate_parse_duration def test_isoduration(benchmark): benchmark(parse_duration, "P18Y9M4DT11H9M8S") def test_isodate(benchmark): benchmark(isodate_parse_duration, "P18Y9M4DT11H9M8S")
from headers import Headers from url import Url class Response(object): """ The ``Response`` object encapsulates HTTP style responses. """ def __init__(self, status, headers=Headers(), content=None, message=None, request=None): """ Construct a new ``Response`` object. ...
import argparse import serial import time BAUD = 115200 * 2 SLEEP_AFTER_RESET_IN_S = 0.02 # This is modified when reading RAM and flash. SLEEP_BETWEEN_READ_AND_WRITE_IN_S = 0.02 RAM_SIZE = 0x010000 FLASH_SIZE = 0x7d000 serial_port = None def hexdump(bytearr): return ' '.join(f'{b:02x}' for b in bytearr) def...
""" Test cases David Johnston 2015 """ import unittest import numpy as np import Agents import Problems def setupESA(): """ Test problem from Hutter(2014) """ gamma = 1/2. r0 = gamma/2/(1+gamma) r1 = (1+gamma/2)/(1+gamma) transitions = np.array([[[0 ,0.5 ,0.5 ,0], ...
#!/usr/bin/env python3 # -*- coding:utf-8 -*- # author: bigfoolliu from sqlalchemy import Column, Integer, String class BaseModel(object): pass class User(BaseModel): pass
# cSpell:ignore smsl # Setup ###################################################################### def _setup(sys_module, _imp_module): """Setup importlib by importing needed built-in modules and injecting them into the global namespace. As sys is needed for sys.modules access and _imp is needed to load...
#coding: utf-8 import django from django.views.generic import TemplateView, CreateView, UpdateView, DeleteView, DetailView, RedirectView from django.views.generic.list import ListView from django.views.generic.edit import BaseFormView, FormView, ProcessFormView from django.http import HttpResponseRedirect from django.s...
import numpy as np import torch from torch.utils.data import Dataset from utils import subsequent_mask """ important: concat all data and org them to batches learned from: https://github.com/pytorch/examples/blob/master/word_language_model/main.py """ class Dataset(Dataset): def __init__(self, data, batch_siz...
# Generated by Django 2.2.1 on 2019-10-29 10:05 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('comedians', '0007_auto_20191027_1858'), ] operations = [ migrations.AlterField( model_name='registercomedian', name=...
######################################################################################################################## # Module: transport/smc.py # Description: SMC samplers for tempered sequence of distributions. # # Web: https://github.com/SamDuffield/mocat ##########################################################...
import logging from collections import OrderedDict import torch from .SRRaGAN_model import SRRaGANModel from .base_model import nullcast logger = logging.getLogger('base') from . import optimizers from . import schedulers from dataops.batchaug import BatchAug from options.options import opt_get class SRFlowModel(...
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: stt.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 google.protobuf import reflection as _reflectio...
from ctypes import * import os, sys dir = os.path.dirname(sys.modules["test"].__file__) if sys.platform == "win32": libName = "test.dll" elif sys.platform == "darwin": libName = "libtest.dylib" else: libName = "libtest.so" dll = cdll.LoadLibrary(os.path.join(dir, libName)) class testError(Exception): pass ...
#!/usr/bin/env python import rospy from rover_state_mach.msg import RoverStateMsg from std_msgs.msg import String from sensor_msgs.msg import NavSatFix from sensor_msgs.msg import Imu from nav_msgs.msg import Odometry from actionlib_msgs.msg import GoalStatusArray import rosparam class status_handler: def __init_...
from collections import OrderedDict import json from six import iteritems from neomodel import Property from neomodel.relationship_manager import RelationshipDefinition class StructuredThingSerializer(object): """Initially made to only handle StructuredNodes but found that it also worked for StructuredRels....
from draw.DrawingPatternPoint import DrawingPatternPoint RIP_PATTERN = [ DrawingPatternPoint(0, -1, True), DrawingPatternPoint(0, -1, True), DrawingPatternPoint(0, -1, True), DrawingPatternPoint(0, -1, True), DrawingPatternPoint(0, -1, True), DrawingPatternPoint(1, 0, True), DrawingPatternP...
#!/usr/bin/env python # Info module template ############################################# # WARNING # ############################################# # # This file is auto generated by # https://github.com/jgroom33/vmware_rest_code_generator # # Do not edit this file manually. # # Ch...
#!/usr/bin/env python3 from cereal import car from selfdrive.car.chrysler.values import CAR from selfdrive.car import STD_CARGO_KG, scale_rot_inertia, scale_tire_stiffness, gen_empty_fingerprint from selfdrive.car.interfaces import CarInterfaceBase ButtonType = car.CarState.ButtonEvent.Type class CarInterface(CarInte...
# (c) 2021 by William H. Grover | wgrover@engr.ucr.edu | groverlab.org import matplotlib.pyplot as plt import csv, sys, numpy, math class candy: def __init__(self): self.points = {"A":[], "R":[], "P":[], "O":[], "Y":[], "G":[], "L":[], "D":[], "W":[] } def add(self, color, x, y): sel...
import torch import torch.nn as nn from ..builder import LOSSES def binary_logistic_regression_loss(reg_score, label, threshold=0.5, ratio_range=(1.05, 21), eps=1e-5): "...
import unittest from baseclasses import BaseSolver from baseclasses.utils import Error from baseclasses.decorators import require_mpi class SOLVER(BaseSolver): def __init__(self, name, options={}, comm=None, checkDefaultOptions=True, caseSensitiveOptions=False): """Create an artificial class for testing"...
# coding: utf-8 from zeit.connector.resource import Resource from zeit.importer.article import Article from zeit.importer.highres import ImageHash from zeit.importer.interfaces import DOC_NS, PRINT_NS import datetime import io import logging import logging.config import lxml.etree import optparse import os import pkg_r...
#! cd .. && python3 -m tests.parser_test import unittest from tests.util import edit_distance, parsecmp, TOKEN from daedalus.lexer import Token, Lexer from daedalus.parser import Parser as ParserBase, ParseError class Parser(ParserBase): def __init__(self): super(Parser, self).__init__() ...
import os import yaml SLEEP = 0.5 CACHE_FILE = ".cache.json" AUTHOR_FORMAT = "%C (%N)" DATE_FORMAT = "%y-%m-%d" CONFIG_FILE = "config.yml" if os.path.exists(CONFIG_FILE): c = yaml.load(CONFIG_FILE) SLEEP = c.get("sleep") or SLEEP CACHE_FILE = c.get("cache_file") or CACHE_FILE AUTHOR_FORMAT = c.get("au...
from typing import List class Solution: def removeDuplicates(self, nums: List[int]) -> int: l, p = len(nums), 0 for i in range(l): if nums[p] == nums[i]: continue else: p = p + 1 nums[p] = nums[i] return p + 1 if __n...
# -*- coding: utf-8 -*- import numpy as np from enum import Enum, auto, unique from collections import namedtuple, OrderedDict from copy import deepcopy from .affine import change_of_basis, transform from .atom_data import ( ELEM_TO_MAGMOM, ELEM_TO_MASS, ELEM_TO_NAME, NAME_TO_ELEM, ELEM_TO_NUM, ...