content
stringlengths
0
894k
type
stringclasses
2 values
# Generated by Django 2.1.1 on 2018-10-23 09:29 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('places', '0029_auto_20181017_1252'), ] operations = [ migrations.RemoveField( model_name='place'...
python
#导入 GPIO库 import RPi.GPIO as GPIO import time import ui,main import threading distmin=25 whiletime=1 distmax=1 #设置 GPIO 模式为 BCM GPIO.setmode(GPIO.BCM) #定义 GPIO 引脚 GPIO_TRIGGER = 20 GPIO_ECHO = 21 #设置 GPIO 的工作方式 (IN / OUT) GPIO.setup(GPIO_TRIGGER, GPIO.OUT) GPIO.setup(GPIO_ECHO, GPIO.IN) def distance(): # 发送高电平信...
python
from torch import nn class GeneralSequential(nn.Module): def __init__(self, *layers): super().__init__() self.layers = nn.ModuleList(layers) def forward(self, *args): for layer in self.layers: args = layer(*args) return args
python
sopa = open("sopa.txt") m = input("Introduzca numero de filas: ") n = input("Introduzca numero de columnas: ") matriz = [] y = 0 while y < m: x = 0 fila = [] while x < n: fila.append(sopa.read((y*n)+x)) x += 1 matriz.append(fila) y += 1 print matriz
python
#!/usr/bin/env python """Series example Demonstrates series. """ from sympy import Symbol, cos, sin, pprint def main(): x = Symbol('x') e = 1/cos(x) print print "Series for sec(x):" print pprint(e.series(x, 0, 10)) print "\n" e = 1/sin(x) print "Series for csc(x):" print ...
python
# ProDy: A Python Package for Protein Dynamics Analysis # # Copyright (C) 2010-2011 Ahmet Bakan # # 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 version 3 of the License, or # (at your...
python
"""Module contains functions and classes for noisy EEG data detection.""" import mne import numpy as np from mne.channels.interpolation import _make_interpolation_matrix from mne.preprocessing import find_outliers from psutil import virtual_memory from scipy.stats import iqr from statsmodels.robust.scale import mad ...
python
""" Event module """ # Import modules import numpy as np import datetime import math import time import json import sys from obspy import Stream, Trace, UTCDateTime from glob import glob import ast from warnings import warn import logging import boto3 from botocore.exceptions import ClientError __author__ = "Vaclav ...
python
import argparse import pygame import random import math import heapq import grid as Grid import sketcher as Sketcher import re def defineArgs(): parser = argparse.ArgumentParser( description='simple script to find an optimal path using A*' ) parser.add_argument( '-gw', '--gridWidth', ...
python
from typing import Any, Dict, List, Optional, Tuple, Union, cast # NB: we cannot use the standard Enum, because after "class Color(Enum): RED = 1" # the value of Color.RED is like {'_value_': 1, '_name_': 'RED', '__objclass__': etc} # and we need it to be 1, literally (that's what we'll get from the client) class En...
python
""" This is the main functionality of our package. it implements the logic necessary to fetch the next event from the server and return it as a time delta for us to use. """ from datetime import datetime, timedelta, timezone import requests def get_time_difference(from_time: datetime = None) -> timedelta: """Fe...
python
import ast import datetime as dt import os import time import cv2 import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns import tensorflow as tf from keras.models import Model, load_model from tensorflow import keras from common import * # os.environ['CUDA_VISIBLE_DEVICES'] = '-...
python
import torch import src.Python.exportsd as exportsd class BasicConv1d(torch.nn.Module): def __init__(self, in_channels, out_channels, **kwargs): super().__init__() self.stack = torch.nn.Sequential( torch.nn.Conv1d(in_channels, out_channels, kernel_size=3, bias=False, **kwargs), ...
python
# -*- coding: utf-8 -*- from __future__ import division from builtins import range def merge_dictionary(dst, src): """Recursive merge two dicts (vs .update which overwrites the hashes at the root level) Note: This updates dst. Copied from checkmate.utils """ stack = [(dst, src)] while sta...
python
import queue from chess.board import Board from chess.figure import Figure PRE = 0 SOLVING = 1 class Game: def __init__(self, board_size=(8, 8)): self.board = Board(board_size) self.state = PRE self.judge = False self.score = 0 self.pre_solve_figures_queue = queue.Queue...
python
# AUTOGENERATED! DO NOT EDIT! File to edit: source_nbs/00_1_params.ipynb (unless otherwise specified). __all__ = ['Params'] # Cell from .base_params import BaseParams from .embedding_layer.base import (DefaultMultimodalEmbedding, DuplicateAugMultimodalEmbedding) from .loss_stra...
python
from sklearn.datasets import make_blobs import matplotlib.pyplot as plt import numpy as np sample_size = 100 X, y = make_blobs(n_samples = sample_size, centers = 2, random_state = 1) y[y == 0] = -1 print(f"X Shape: {X.shape}") print(f"y Shape: {y.shape}") # THE PERCEPTRON ALGORITHM def perceptron(t, D, y): ...
python
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes ...
python
import unittest import pygal from pymongo import MongoClient import driveshare_graph.minmax as minmax class MinMax(unittest.TestCase): def test_minmax_chart(self): client = MongoClient('localhost', 27017) collection = client['GroupB']['totalStorage'] graph = minmax.minmax_chart(collection)...
python
"""Test the MCP9808 temperature sensor""" from meerkat import base, mcp9808 dev = mcp9808.MCP9808(bus_n=base.i2c_default_bus) print() print('Current MCP9808 Status:') print('-----------------------') dev.print_status() print() print('One measurement') print('---------------') print(dev.get_temp()) print() print('M...
python
# coding: utf-8 # # Function dctmatrix # # ## Synopse # # Compute the Kernel matrix for the DCT Transform. # # - **A = dctmatrix(N)** # # - **A**:output: DCT matrix NxN. # - **N**:input: matrix size (NxN). # In[1]: import numpy as np def dctmatrix(N): x = np.resize(range(N), (len(range(N)), len(range...
python
import os import yaml import jsonschema import argparse SCHEMA = os.path.join(os.path.dirname(os.path.abspath(__file__)), "yaml_schema.yaml") def validate_yaml(yaml_file: str): """ Validates the syntax of the yaml file. Arguments: yaml_file: path to yaml file to be validate...
python
# -*- coding: utf-8 -*- """ Coletor Web Realiza a coleta dos comentários associados a determinado Tweet. Utiliza o selenium - Necessário instalação de arquivo externo chromedriver """ import sys import coletor_web.coletor_comentarios as comment import core.database as db def main(banco_dados, colecao): """Cole...
python
""" Provides a set of filter classes used to inject code into actions. """ import inspect from flask import request from .exceptions import ValidationError, UnsupportedMediaType from .fields import Schema from .results import BadRequestResult, ForbiddenResult, UnauthorizedResult, UnsupportedMediaTypeResult class Fi...
python
# -*- coding: utf-8 -*- # Form implementation generated from reading ui file 'SerialPort.ui' # # Created by: PyQt5 UI code generator 5.12.1 # # WARNING! All changes made in this file will be lost! from PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindow(object): def setupUi(self, MainWindow): Main...
python
#All these functions are for dummy purposes import nltk from nltk.tokenize import sent_tokenize from numpy.random import randint,uniform # from sklearn.feature_extraction.text import TfidfVectorizer # from preprocessing import * def chunker1(paragraph): ''' Creates a "lengths" list having a distribution of l...
python
from io import StringIO from django.core.management import call_command from django.db import connection import pytest # aliased, otherwise it's picked up as a test function by pytest from ctrl_z.db_restore import test_migrations_table as check_migrations @pytest.mark.django_db(databases=["secondary"]) def test_no...
python
# Copyright (c) 2015 Ansible, Inc. # All Rights Reserved. # Python import contextlib import logging import threading import json import sys # Django from django.db import connection from django.conf import settings from django.db.models.signals import ( pre_save, post_save, pre_delete, post_delete, ...
python
# -*- encoding: utf-8 -*- """ hio.demo package Demo applications that use hio """
python
from django.utils import timezone from rest_framework import serializers from rest_framework.fields import CharField from rest_framework.relations import PrimaryKeyRelatedField from api.applications.enums import ( ApplicationExportType, ApplicationExportLicenceOfficialType, ) from api.applications.libraries.ge...
python
""" This example illustrates how to send a request for the plan database from a system. """ import logging import sys import pyimc from pyimc.actors.dynamic import DynamicActor from pyimc.decorators import Periodic, Subscribe class PlanActor(DynamicActor): def __init__(self, target_name): """ In...
python
#!/usr/bin/env python2 # Example 1, iter over some names def loop_names(): names = ["pichu", "pikachu", "raichu"] for n in names: print n def name_gener(): yield "pichu" yield "pikachu" yield "raichu" def gener_names(): for n in name_gener(): print n loop_names() gener_names(...
python
from output.models.nist_data.list_pkg.hex_binary.schema_instance.nistschema_sv_iv_list_hex_binary_max_length_4_xsd.nistschema_sv_iv_list_hex_binary_max_length_4 import NistschemaSvIvListHexBinaryMaxLength4 __all__ = [ "NistschemaSvIvListHexBinaryMaxLength4", ]
python
import urllib import os.path import os import shutil import zipfile import glob from django.conf import settings from eulexistdb import db from datetime import date thisyear = date.today().year media_root = settings.MEDIA_ROOT disa_pki_flag = settings.USE_DISA_PKI root_src_dir = '/tmp/iavms/' iavm_cve_data_dir = med...
python
import numpy as np from glob import glob from tqdm import tqdm from chemprop.features import load_features from chemprop.data.scaler import StandardScaler def get_dist(dirpath): mean = list() std = list() count = list() # Get mean and standard deviation of all the features across all the files f...
python
from datetime import datetime import json from django.conf import settings def handle(context, err): print("ERROR:", err) with open(getattr(settings, "SCRAPE_LOG"), "a+") as log: log.write(str(datetime.now()) + " Error: " + str(err) + "\n") log.write("Context: " + json.dumps(context, indent=4)...
python
from django.conf.urls import url from django.views.generic import TemplateView urlpatterns = [ url(r'^$', TemplateView.as_view(template_name='website/home.html'), name='home'), url(r'^about/$', TemplateView.as_view(template_name='website/about.html'), name='about') ]
python
import numpy as np import pickle import json from keras.utils import Sequence from collections import Counter from PIL import Image, ImageDraw import random import skimage.io as io import matplotlib.pyplot as plt import matplotlib.colors as colors import os from keras.preprocessing.image import load_img from Environme...
python
# Test name = KidProfile_2 # Script dir = R:\Stingray\Tests\KidProfile_2\functionality\functionality.py # Rev v.2.0 from time import sleep from device import handler, updateTestResult import RC import UART import DO import GRAB import MOD import os from DO import status import OPER def runTest(): status("active...
python
# coding=utf-8 import unittest from pyprobe.sensors.pegasus.sensor_phy_drive import PegasusPhysicalDriveSensor __author__ = 'Dirk Dittert' class PegasusDriveSensorTest(unittest.TestCase): def test_no_drive_should_throw(self): subject = PegasusPhysicalDriveSensor() with self.assertRaises(ValueErr...
python
class Event(list): def __call__(self, *args, **kwargs): for item in self: item(*args, **kwargs) class Game: def __init__(self): self.events = Event() def fire(self, args): self.events(args) class GoalScoredInfo: def __init__(self, who_scored, goals...
python
#!/usr/bin/env python # Copyright 2019 Richard Sanger, Wand Network Research Group # # 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 ...
python
import re from random import sample from django.db.models import Avg from django.shortcuts import render from rest_framework import status from rest_framework.decorators import api_view from rest_framework.response import Response from .models import * from .serializers import * import requests from bs4 import Beauti...
python
import os import platform import sys from datetime import datetime, timezone from pathlib import Path from unittest.mock import MagicMock, Mock import pytest import tzlocal.unix import tzlocal.utils if sys.version_info >= (3, 9): from zoneinfo import ZoneInfo, ZoneInfoNotFoundError else: from backports.zonei...
python
# -*- coding: UTF-8 -*- import pandas as pd import csv import os import argparse def get_valid_query(data_path, data_name): print('begin getting valid query') valid_path=os.path.join(os.path.join(data_path,'valid'),'valid.tsv') valid_data=pd.read_csv(valid_path, sep='\t') filename =os.path.join(os.pat...
python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Mar 5 10:15:25 2021 @author: lenakilian """ import pandas as pd data_directory = "/Users/lenakilian/Documents/Ausbildung/UoLeeds/PhD/Analysis" output_directory = "/Users/lenakilian/Documents/Ausbildung/UoLeeds/PhD/Analysis/Spatial_Emissions" lookup ...
python
import tensorflow as tf from tensorflow.keras import Model from tensorflow.keras.layers import Layer, Dense, Input, Conv1D, Flatten, Dot, RepeatVector, Concatenate, Permute, Add, Multiply from tensorflow.keras import activations, initializers, regularizers, constraints from tensorflow.keras.optimizers import Adam cla...
python
from floodsystem.plot import plot_water_levels from floodsystem.stationdata import build_station_list from floodsystem.analysis import update_water_levels from floodsystem.flood import stations_highest_rel_level from floodsystem.datafetcher import fetch_measure_levels import datetime def run2e(station, dates, levels):...
python
#!/usr/bin/env python # -*- coding: utf-8 -*- """ # CODE NAME HERE # CODE DESCRIPTION HERE Created on 2019-02-04 at 16:40 @author: cook """ import numpy as np import argparse import sys import os import copy from collections import OrderedDict from apero.core.instruments.default import pseudo_const from apero.core ...
python
import unittest,json from tqdm import tqdm from mtgcompiler.parsers.JsonParser import JsonParser from multiprocessing import Pool def loadAllSets(fname="tests/parsing/AllSets.json"): with open(fname) as f: data = json.load(f) return data totalCardsParsed = 0 totalCardsAttempted...
python
from django.urls import path from .views import UserReactionView, CommentsLikeReactionAPIView from .models import UserReaction from authors.apps.articles.models import Article from authors.apps.comments.models import Comment app_name = 'user_reactions' urlpatterns = [ path('articles/<slug>/like', UserReactionVie...
python
""" A plugin that retrieves file paths from backend server. This module implements a plugin for preview-server that allows preview-server to proxy requests to a backend server. Preview requests are received by preview-server, the path is given within the URL. In order to locate the file on disk, this plugin will make...
python
"""`main` is the top level module for your Flask application.""" # Import the Flask Framework from flask import Flask from flask import render_template,request,send_from_directory from flask_misaka import Misaka import ctftools app = Flask(__name__) Misaka(app,fenced_code=True) # Note: We don't need to call run() since...
python
import torch import torch.optim as optim from torch import autograd import numpy as np from tqdm import trange import trimesh import cv2 from im2mesh.ptf import models from im2mesh.utils import libmcubes from im2mesh.common import make_3d_grid from im2mesh.utils.libsimplify import simplify_mesh from im2mesh.utils.libmi...
python
"""This module contains the utilities for the Translations app.""" from django.db import models from django.db.models.query import prefetch_related_objects from django.db.models.constants import LOOKUP_SEP from django.core.exceptions import FieldError from django.contrib.contenttypes.models import ContentType import ...
python
""" Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: MIT-0 """ def make_rule(line): """ Object Maker Function """ rule = Rule(line) return rule class Rule(object): """ Used to organize intake from custom_rule config """ valid = False resourceType = ...
python
#!/usr/bin/env python3 import sys from pyjunix import (PyJKeys, PyJArray, PyJUnArray, PyJLs, PyJGrep, PyJPrtPrn, PyJSort, PyJLast, PyJPs, PyJJoin, PyJPaste, PyJCat, PyJSplit, PyJDiff, PyJUniq) script_dir = { "pyjkeys": PyJKeys, "pyjarray": PyJArra...
python
with open("words.txt", "r+") as f: lines = f.readlines() f.seek(0) for line in lines: # print ('line is', line) if len(line) == 6: f.write(f"'{line}',") f.truncate()
python
#!/bin/python import os, shutil import numpy as np import matplotlib.pyplot as plt import np_helper as nph # plot 3d points def plot_pts3d(pts3d, visible_status): fig_xz = plt.figure() plt.xlabel('X (m)', fontsize=14) plt.ylabel('Z (m)', fontsize=14) plt.axis('equal') plt.plot(pts3d[0,:], pts3d[2...
python
from django.conf.urls import url from . import views urlpatterns = [ # 购物车 carts url(r'^carts/$', views.CartsView.as_view(),name='info'), # 全选购物车/carts/selection/ url(r'^carts/selection/$', views.CartsSelectAllView.as_view(), name='carts_select'), # 页面简单购物车 /carts/simple/ url(r'^carts/simple/$...
python
import torch import torch.nn as nn from torchvision.models.resnet import resnet50 class Resnet50Extractor(nn.Module): def __init__(self, representation_size=128): super().__init__() original_model = resnet50(pretrained=True, progress=True) in_features = 1000 self.model = nn.Sequen...
python
# -*- coding: utf-8 -*- ''' djcorecap/core --------------- core module for the djcorecap app ''' from bokeh.embed import components from bokeh.plotting import figure from bokeh.resources import CDN def bokeh_plot(data, plots, f_config={}, p_config=[]): ''' create HTML elements for a Bokeh plot :retur...
python
from aiocqhttp import Event from datasource import get_360_boardcast from .base_bot import BaseBot class Rss(BaseBot): def __init__(self): super() super().__init__() def reset_bot(self): pass def match(self, event: Event, message: str) -> bool: if not self.has_at_bot(eve...
python
""" unit test """ import difflib import inspect import json import logging import os import sys import tempfile from io import StringIO from logging import Handler from random import random from unittest.case import TestCase from bzt.cli import CLI from bzt.engine import SelfDiagnosable from bzt.modules.aggregator imp...
python
from magicbot import StateMachine, state, timed_state from components.climb import Climber from components.cargo import CargoManipulator, Height from pyswervedrive.chassis import SwerveChassis class ClimbAutomation(StateMachine): chassis: SwerveChassis climber: Climber cargo_component: CargoManipulator ...
python
#The MIT License (MIT) # #Copyright (c) 2015 Jiakai Lian # #Permission is hereby granted, free of charge, to any person obtaining a copy #of this software and associated documentation files (the "Software"), to deal #in the Software without restriction, including without limitation the rights #to use, copy, modify, mer...
python
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for license information. # -----------------------------------------------------------------------...
python
import threading import time import RPi.GPIO as GPIO class ContactSwitchRecognizer(threading.Thread): GPIO_PIN = 21 _contact_switch_listener = None _last_state_on = False def __init__(self, contact_switch_listener): threading.Thread.__init__(self) GPIO.setmode(GPIO.BCM) GPIO...
python
# -*- coding:UTF-8 -*- import rdkit import rdkit.Chem as Chem from scipy.sparse import csr_matrix from scipy.sparse.csgraph import minimum_spanning_tree from collections import defaultdict from rdkit.Chem.EnumerateStereoisomers import EnumerateStereoisomers, StereoEnumerationOptions import logging MST_MAX_WEIGHT = 100...
python
#!/usr/bin/env python3 import rospy from std_msgs.msg import Int32 import rogata_library as rgt import numpy as np def visibility(guard,thief,wall_objects,max_seeing_distance): distance = np.linalg.norm(thief-guard) direction = (thief-guard)/distance direction = np.arctan2(direction[1],direction[0]) ...
python
# coding=utf-8 from model import Balance, Label, Transfer, Internal # 保存数据库类 class Save: def __init__(self): ... # 保存balance @staticmethod def save_balance(address, balance) -> None: balance = Balance(address, balance) balance.save() return # 保存label @staticm...
python
import numpy numpy.set_printoptions(sign=' ') arr = numpy.array([*map(float, input().split())]) print(numpy.floor(arr), numpy.ceil(arr), numpy.rint(arr), sep='\n')
python
# This file is dual licensed under the terms of the Apache License, Version # 2.0, and the BSD License. See the LICENSE file in the root of this repository # for complete details. from __future__ import absolute_import, division, print_function from _cffi_src.utils import build_ffi_for_binding ffi = build_...
python
""" Created on Aug 28, 2017 @author: ionut """ import json import logging import subprocess from tornado.web import RequestHandler from tornado.websocket import WebSocketHandler from tornado.escape import url_escape import utils class BaseHandler(RequestHandler): """ Base handler returning 400 for both G...
python
"""\ Code generator functions for wxFrame objects @copyright: 2002-2007 Alberto Griggio @copyright: 2014-2016 Carsten Grohmann @license: MIT (see LICENSE.txt) - THIS PROGRAM COMES WITH NO WARRANTY """ import common import wcodegen class LispFrameCodeGenerator(wcodegen.LispWidgetCodeWriter): def get_code(self, ...
python
import numpy as np from math import * import os import time import sys import argparse from monty.serialization import loadfn """ This module implements a core class LatticeConstant that support lammps data/imput/log files i/o for calculating equilibrium lattice constant of Re . """ __author__ = "Lu Jiang and Tingzh...
python
import unittest from kafka.tools.protocol.requests import ArgumentError from kafka.tools.protocol.requests.offset_commit_v2 import OffsetCommitV2Request class OffsetCommitV2RequestTests(unittest.TestCase): def test_process_arguments(self): val = OffsetCommitV2Request.process_arguments(['groupname', '16',...
python
from typing import Any, Dict, List, Type, TypeVar import attr from ..models.label_count import LabelCount T = TypeVar("T", bound="CategoriesFacets") @attr.s(auto_attribs=True) class CategoriesFacets: """ """ labels: List[LabelCount] def to_dict(self) -> Dict[str, Any]: labels = [] for...
python
from pin_hcsr04 import HCSR04 import time measure = HCSR04(trigger = 'X8', echo = 'X7') while True: print("%.1f cm" % (measure.distance_mm() / 10)) time.sleep(1)
python
from django.shortcuts import render, redirect from django.contrib import messages from .models import * import bcrypt # ------------------------ Unprotected pages ------------------------ # ------ Main Landing Page ------ def index(request): if 'user_id' not in request.session: return render(request, 'ind...
python
# # Copyright (c) 2015 CNRS # from math import atan2, pi, sqrt import numpy as np from . import libpinocchio_pywrap as pin def npToTTuple(M): L = M.tolist() for i in range(len(L)): L[i] = tuple(L[i]) return tuple(L) def npToTuple(M): if M.shape[0] == 1: return tuple(M.tolist()[0])...
python
from django import template import calendar from django.template import loader, Context from django.utils.dates import WEEKDAYS, WEEKDAYS_ABBR from django.template.loader import render_to_string weekday_names = [] weekday_abbrs = [] # The calendar week starts on Sunday, not Monday weekday_names.append(WEEKDAYS[6]) w...
python
# Copyright 2021 Tony Wu +https://github.com/tonywu7/ # # 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 ...
python
import pickle import nltk class Classifier: def __init__(self): with open('/home/ubuntu/backend/scraped_data_classifier', 'rb') as handle: self.classifier = pickle.load(handle) def classify(self, name): return self.classifier.classify(self.feature_extraction(name)) def featur...
python
from django.urls import reverse from rest_framework import status from .test_setup import TestApiEndpoints class TestOperator(TestApiEndpoints): fixtures = ['Operator', 'Address', 'Authorization', 'Activity'] def test_operator_list_returns_200(self): self.setUpClientCredentials([self.READ_SCOPE]) ...
python
import pandas from bart.bart import Fares, get_stations def get_fare_table(): stations_abbr = [s.abbr for s in get_stations()] station_pairs = [] for o in stations_abbr: for d in stations_abbr: if o != d: station_pairs.append((o, d)) fares = Fares() fares.get_f...
python
from tqdm import tqdm import numpy as np import os from pathlib import Path # this script is to be run in an environment with the Python bindings of elsa installed import pyelsa as elsa def generate_sparse_npy_images(src_dir, out_dir=None, num_angles=50, no_iterations=20, limit=None): """ Generate sparsely s...
python
#!/usr/bin/env python3 # # fix field names using the provide schema # import os import sys import re import csv import json input_path = sys.argv[1] output_path = sys.argv[2] schema_path = sys.argv[3] schema = json.load(open(schema_path)) fields = {field["name"]: field for field in schema["fields"]} fieldnames = [...
python
import pytest from stve.log import Log from aliez.utility import * from aliez.script.kancolle import testcase_kancolle L = Log.get(__name__) def info(string, cr=True): desc(string, L, cr) class TestCase(testcase_kancolle.TestCase): def __init__(self, *args, **kwargs): super(TestCase, self).__init__(...
python
from .mae_vit_base_patch16 import model model.patch_size = 14 model.embed_dim = 1280 model.depth = 32 model.num_heads = 16
python
""" MIT License Copyright (c) 2020 Mahdi S. Hosseini Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, mer...
python
""" ========================================================================= DORYCMeshRouteUnitRTL.py ========================================================================= A DOR-Y route unit with val/rdy interface for CMesh. Author : Yanghui Ou, Cheng Tan Date : Mar 25, 2019 """ from pymtl3 import * from pymtl3...
python
# DATA data = [] with open("Data - Day09.txt") as file: for line in file: data.append(int(line.strip())) # GOAL 1 """ Find the first number in the list (after the preamble) which is not the sum of two of the 25 numbers before it. What is the first number that does not have this property? """ def check_...
python
from typing import Dict from torch import Tensor, nn from ...general import PosEngFrc class SD(nn.Module): def __init__(self, evl: nn.Module, lmd: Tensor): super().__init__() self.lmd = lmd self.evl = evl def forward(self, pef: PosEngFrc, env: Dict[str, Tensor], flt: Tensor, ...
python
from flask import Flask import redis import json from ...service.entity.author import Author from ...exception.exception import AuthorAlreadyExistsException app = Flask(__name__) AUTHOR_COUNTER = "author_counter" AUTHOR_ID_PREFIX = "author_" class AuthorRepository: def __init__(self): self.db = redis.R...
python
# Copyright The PyTorch Lightning team. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to i...
python
def load_ctrlsum(device): from transformers import AutoModelForSeq2SeqLM, PreTrainedTokenizerFast model = AutoModelForSeq2SeqLM.from_pretrained("hyunwoongko/ctrlsum-cnndm") tokenizer = PreTrainedTokenizerFast.from_pretrained("hyunwoongko/ctrlsum-cnndm") return tokenizer, model import os, json import a...
python
# Python3 function to calculate number of possible stairs arrangements with given number of boxes/bricks def solution(n): dp=[[0 for x in range(n + 5)] for y in range(n + 5)] for i in range(n+1): for j in range (n+1): dp[i][j]=0 dp[3][2]=1 dp[4][2]=1 for i in range(5...
python
from typing import Union, Optional, Dict from .core.base import * from .core.Framebuffer2D import Framebuffer2D from .core.Texture2D import Texture2D from .ScreenQuad import ScreenQuad from .RenderGraph import RenderGraph from .RenderSettings import RenderSettings from .RenderNode import RenderNode from tests.util imp...
python
''' Given an integer array nums, return the maximum result of nums[i] XOR nums[j], where 0 ≤ i ≤ j < n. Follow up: Could you do this in O(n) runtime? Example 1: Input: nums = [3,10,5,25,2,8] Output: 28 Explanation: The maximum result is 5 XOR 25 = 28. Example 2: Input: nums = [0] Output: 0 Example 3: Input: nums =...
python