content
stringlengths
5
1.05M
import os from configparser import ConfigParser import logging log = logging.getLogger(__name__) def parsing(): # default values cfg = { 'imgext': '.png, .jpg, .jpeg, .tiff, .bmp, .gif', 'audext': '.wav, .mp3, .flac, .m4a', 'separator': '-, .', 'ssr': '6', 'show_sear...
from app import main from typing import Optional from fastapi import APIRouter, Body, Depends from starlette import status from app.api.dependencies.database import get_repository from app.db.repositories.project1_words import Project1WordsRepository from app.models.domain.words import Word from app.services.image_he...
from time import sleep, time from datetime import datetime as dt from shutil import copy as copyfile from socket import socket, AF_INET, SOCK_STREAM import keyboard from keyboard import KeyboardEvent try: from conf import SPECIAL_KEYS, SERVER_ACTIVE, SERVER_ADDR, SERVER_PORT except ImportError: print("Could no...
''' 提莫攻击 在《英雄联盟》的世界中,有一个叫 “提莫” 的英雄,他的攻击可以让敌方英雄艾希(编者注:寒冰射手)进入中毒状态。现在,给出提莫对艾希的攻击时间序列和提莫攻击的中毒持续时间,你需要输出艾希的中毒状态总时长。 你可以认为提莫在给定的时间点进行攻击,并立即使艾希处于中毒状态。   示例1: 输入: [1,4], 2 输出: 4 原因: 第 1 秒初,提莫开始对艾希进行攻击并使其立即中毒。中毒状态会维持 2 秒钟,直到第 2 秒末结束。 第 4 秒初,提莫再次攻击艾希,使得艾希获得另外 2 秒中毒时间。 所以最终输出 4 秒。 示例2: 输入: [1,2], 2 输出: 3 原因: 第 1 秒初,提莫开始对艾希进...
from re import match import requests from .exception import SetSession, SetServiceId, SetKey, ParamSetException, GetException class BaseUCaller: __REGEX_PHONE = r'^(\+7|7|8)?[\s\-]?\(?[489][0-9]{2}\)?[\s\-]?[0-9]{3}[\s\-]?[0-9]{2}[\s\-]?[0-9]{2}$' __ORG_URL = "https://ucaller.ru/" __DOC_URL = "https://uc...
#!/usr/bin/env python3 """ Author : saminamomtaz <saminamomtaz@localhost> Date : 2021-11-16 Purpose: Run-length encoding/data compression """ import argparse import os # -------------------------------------------------- def get_args(): """Get command-line arguments""" parser = argparse.ArgumentParser( ...
class Solution: def fourSumCount(self, A: List[int], B: List[int], C: List[int], D: List[int]) -> int: dicA = {} dicB = {} dicC = {} dicD = {} for i in A: if i in dicA.keys(): dicA[i] += 1 else: dicA[i] = 1; for...
import unittest from QuattroComponents.Player import Anonymous_player from QuattroComponents.Card import Card from TestModule.GetMethodName import get_method_name_decorator from collections import deque def reset_player_attributes(anonymous: Anonymous_player): anonymous.player1_changed = False anonymous.playe...
import gzip import re import os import time from sys import argv import concurrent.futures import math # Keep track of when the script began startTime = time.time() char = '\n' + ('*' * 70) + '\n' # Argv information inputFile = argv[1] pathToFiles = argv[2] numCores = int(argv[3]) if pathToFiles.endswith("/"): p...
# -*- coding: utf-8 -*- from keras import models from keras import layers from keras.datasets import mnist from keras.utils import to_categorical # ニューラルネットワークの構築とコンパイル network = models.Sequential() network.add(layers.Dense(512, activation='relu', input_shape=(28 * 28,))) network.add(layers.Dense(10, activation='soft...
#!/usr/bin/env python import os ELASTICSEARCH_LOGSTASH_INDEX = "suricata-" ELASTICSEARCH_LOGSTASH_ALERT_INDEX = "suricata-" ELASTICSEARCH_VERSION = os.environ["ELASTICSEARCH_VERSION"] if "ELASTICSEARCH_VERSION" in os.environ else 7 ELASTICSEARCH_KEYWORD = "keyword" ELASTICSEARCH_LOGSTASH_TIMESTAMPING = os.environ['ELA...
# encoding: UTF-8 from __future__ import print_function import json from datetime import datetime, timedelta, time from pymongo import MongoClient from vnpy.trader.app.ctaStrategy.ctaBase import MINUTE_DB_NAME, TICK_DB_NAME from vnpy.trader.vtUtility import get_trade_time #-----------------------------------------...
# -*- coding: utf-8 -*- from django.conf import settings from django.contrib.contenttypes.fields import GenericRelation from django.db import models from django.urls import reverse from django.utils.functional import cached_property from django_autoslugfield.fields import AutoSlugField from common_utils.models import ...
# coding=utf-8 """ UserKNN based on Collaborative Filtering Recommender [Rating Prediction] Literature: KAggarwal, Charu C.: Chapter 2: Neighborhood-Based Collaborative Filtering Recommender Systems: The Textbook. 2016 file:///home/fortesarthur/Documentos/9783319296579-c1.pd...
# -*- coding: utf-8 -*- """ Regular expression serving object. Author: ------- Sri Ram Sagar K Created on Sat Jan 13 20:41:11 2018 """ import re class ReObjects(object): ''' Regex precompiled objects based on pattern''' emails = (r".*@\s*gmu\s*.\s*edu", r".*AT\s*(gmu|GMU)\s*DOT\s*(edu|EDU)") phones = (r...
import logging import voluptuous as vol from homeassistant.components.websocket_api import ( websocket_command, result_message, event_message, async_register_command ) from .const import WS_CONNECT, WS_UPDATE from .helpers import get_devices, create_entity, get_config, is_setup_complete _LOGGER = log...
import json import os from werkzeug.contrib.fixers import ProxyFix from flask import Flask, request, redirect, url_for, abort, jsonify from flask_cors import CORS, cross_origin from biosimulations_dispatch.config import Config from biosimulations_dispatch.hpc_manager import HPCManager class PrefixMiddleware: def _...
#!/usr/bin/env python3 import csv import io import json import time import argparse import requests import yaml from libgather import Gather def parse_arguments(): parser = argparse.ArgumentParser(description="MiniConf Portal Command Line") parser.add_argument("email", help="email address of user") retu...
from __future__ import absolute_import, print_function from django.core.urlresolvers import reverse from sentry.auth.view import AuthView, ConfigureView from sentry.utils.http import absolute_uri from sentry_auth_saml2.forms import ( AttributeMappingForm, SAMLForm, URLMetadataForm, XMLMetadataForm, process_m...
# -*- coding: utf-8 -*- import unittest """ ******************************************************************************* Tests of the quantarhei.qm.hilbertspace.statevector package ******************************************************************************* """ from quantarhei import StateVector cl...
#!/usr/bin/env python # -*- coding: utf-8 -*- import os import sys import time import re from glob import glob import json my_dir = os.path.abspath(os.path.dirname('__file__')) # subdir = 'api_programRatings' # subdir = 'api_commercialRatings' subdir = sys.argv[1] print("Searching directory: ", subdir) outdir = subd...
# -*- coding: utf-8 -*- # Generated by Django 1.9.4 on 2018-05-02 14:57 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('d4s2_api', '0024_auto_20180423_2026'), ] operations...
import pushjet import subprocess from ConfigParser import SafeConfigParser import sys secret_key = str('6e7ae26ce1758cd28edb5251b7cd4142') service = pushjet.Service(secret_key) line = str(sys.argv[1]) service.send(line)
import discord import asyncio import logging import json logging.basicConfig(level=logging.DEBUG) client = discord.Client() @client.event async def on_ready(): print('Connected!') print('Username: ' + client.user.name) print('ID: ' + client.user.id) for i in range(130): await client.ws.send(...
from django.urls import path from . import views app_name='reviews' urlpatterns = [ path('<int:movie_pk>/', views.ReviewListCreate.as_view()), path('<int:movie_pk>/detail/<int:review_pk>/', views.ReviewDetail.as_view()), path('<int:review_pk>/like/', views.Like.as_view()), path('<int:review_pk>/dislik...
import time import random import threading import socket import re from TCAction import PerformanceTCBase from NativeLog import NativeLog from Utility import Encoding class SendThread(threading.Thread): def __init__(self, sock, send_len, target_addr, delay): threading.Thread.__init__(self) self.s...
from haxballgym.game.common_values import COLLISION_FLAG_ALL from haxballgym.game.objects.base import PhysicsObject import numpy as np import copy class Disc(PhysicsObject): """ A class to represent the state of a disc from the game. """ def __init__(self, data_object=None, data_stadium=None): ...
from six import PY2 import collections from syn.five import xrange from syn.types.a import Type, Mapping, Dict, \ hashable, serialize, deserialize, estr, rstr, visit, find_ne, \ DiffersAtKey, KeyDifferences, deep_feq, safe_sorted, primitive_form, \ collect from syn.types.a import enumerate as enumerate_ fro...
# Lint as: python3 """Tests for google3.third_party.py.language.google.qed.qed_eval.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import json import qed_eval from absl.testing import absltest example_1 = """ { "example_id": -6560319052930436991, ...
import bs4 import requests from bs4 import BeautifulSoup from datetime import datetime def go(): a = str(datetime.now().month) b = str(datetime.now().day -1) c = str(datetime.now().year -1) d = str(datetime.now().year) yesterday = a + '/' + b + '/' + d last_year = a + '/' + b + '/' + c retu...
#!/usr/bin/env python import sys, os import itertools, shutil path = os.path.abspath(__file__) path = os.path.split(path)[0] os.chdir(path) print path device_ssh_ip = "" ssh_device = device_ssh_ip.split(",") path_tcs = path + "/tcs" path_result= path + "/result" path_allpairs = path + "/allpairs" path_resource = path ...
import json import torch device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') # sets device for model and PyTorch tensors meta_file = 'data/BZNSYP/ProsodyLabeling/000001-010000.txt' wave_folder = 'data/BZNSYP/Wave' vacab_file = 'data/vacab.json' with open(vacab_file, 'r', encoding='utf-8') as file...
# Write a function that accepts two positive integers which are the height # and width of a rectangle and returns a list that contains the area and perimeter # of that rectangle. def area_perimeter_rectangle(height, width): result = [] result_area = height * width result_perim = 2*(height + width) resu...
# Coding=UTF8 # !python # !/usr/bin/env python3 import discord from discord.ext import commands import asyncio, random from lib import db from discord_components import Button, ButtonStyle, DiscordComponents class AdminCmds(commands.Cog): def __init__(self, client): self.client = client @commands.has...
from dataclasses import dataclass from mitmproxy import connection from . import commands @dataclass class ClientConnectedHook(commands.StartHook): """ A client has connected to mitmproxy. Note that a connection can correspond to multiple HTTP requests. Setting client.error kills the connection. ...
import shelve # Pattern Singleton class MetaSingleton(type): _instances = {} def __call__(cls, *args, **kwargs): if cls not in cls._instances: cls._instances[cls] = super(MetaSingleton, cls).__call__(*args, **kwargs) return cls._instances[cls] class DataBaseController(metaclass=...
# coding=utf-8 # Copyright 2020 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 rest_framework import serializers #from orchestra.api.serializers import MultiSelectField from orchestra.contrib.accounts.serializers import AccountSerializerMixin from .models import Contact class ContactSerializer(AccountSerializerMixin, serializers.HyperlinkedModelSerializer): email_usage = serializers....
import unittest from exabel_data_sdk.client.api.data_classes.entity import Entity from exabel_data_sdk.client.api.entity_api import EntityApi from exabel_data_sdk.tests.client.api.mock_entity_api import MockEntityApi class TestEntityApi(unittest.TestCase): def test_upsert(self): entity_api: EntityApi = M...
def main(): n = int(input()) a = 'I hate it' b = 'I hate that' c = 'I love it' d = 'I love that' for i in range(1,n): if i % 2 == 1: print(b,end=" ") else: print(d,end=" ") if n % 2 == 1: print(a,end=" ") if n % 2 == 0: print(c,end=...
from request import Request class Streams(object): def get_activity_streams(): return def get_route_streams(): return def get_segment_effort_streams(): return def get_segment_streams(): return
import unyt as u import numpy as np import pandas as pd from mosdef_cassandra.analysis import ThermoProps def main(): # Systems simulated pore_area = 2 * 22.104 * 21.270 * u.angstrom**2 # From .inp file pore_sizes = [1.0, 1.5, 2.0] * u.nm n_ion_pairs = [0, 4, 8] # Output nmols_list = [] ...
from os import path from django.utils.translation import gettext_lazy as _ from docutils import nodes from docutils.transforms import Transform from docutils.utils import relative_path from django_docutils.lib.transforms.font_awesome import fa_classes_from_url from django_docutils.references.models import get_referen...
""" sentry_46elks.models ~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2012 by Matt Robenolt. :license: BSD, see LICENSE for more details. """ from __future__ import unicode_literals import re import requests import sentry_46elks from django import forms from django.utils.translation import ugettext_lazy as _ from sentry.conf ...
from nanome._internal._util._serializers import _TypeSerializer from nanome._internal._shapes._mesh import _Mesh class _MeshSerializer(_TypeSerializer): def __init__(self): pass def version(self): return 0 def name(self): return "MeshShape" def serialize(self, version, value...
# Copyright 2008-2018 pydicom authors. See LICENSE file for details. """Unit tests for the pydicom.tag module.""" import pytest from pydicom.tag import BaseTag, Tag, TupleTag, tag_in_exception class TestBaseTag: """Test the BaseTag class.""" def test_le_same_class(self): """Test __le__ of two classe...
# coding: utf-8 # $Id: __init__.py 8295 2019-07-24 09:22:01Z grubert $ # Author: David Goodger <goodger@python.org> # Copyright: This module has been placed in the public domain. """ Miscellaneous utilities for the documentation utilities. """ __docformat__ = 'reStructuredText' import sys import os import os.path im...
import argparse import time import math import torch import torch.nn as nn import torch.optim as optim import numpy as np from torch.autograd import Variable from sklearn.preprocessing import StandardScaler from sklearn.metrics import accuracy_score from sklearn.metrics import f1_score from sklearn.metrics import preci...
# coding: utf-8 import re from constants import ROOM_DOOR_FLAGS from constants import ROOM_FLAGS from constants import ROOM_SECTOR_TYPES from utils import bitvector_to_flags from utils import clean_bitvector from utils import lookup_value_to_dict EXIT_RE = r"""D(\d+) (.*?)~ (.*?)~ (.*?) """ EXIT_PATTERN = re.compile(...
# Generated by Django 2.2.7 on 2021-12-02 14:02 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('ugc', '0014_new'), ] operations = [ migrations.AddField( model_name='new', name='heading_en', field=mode...
import re from wagtail import __version__ as WAGTAIL_VERSION def is_wagtail_version_more_than_equal_to_2_5(): expression = '^((2.([5-9]{1,}|([1-9]{1,}[0-9]{1,}))(.\d+)*)|(([3-9]{1,})(.\d+)*))$' return re.search(expression, WAGTAIL_VERSION) def is_wagtail_version_more_than_equal_to_2_0(): expression = '^((2.([0-...
"""trigger.py""" import gtm_manager.base import gtm_manager.parameter from gtm_manager.utils import param_dict class GTMTrigger(gtm_manager.base.GTMBase): """Open a specific GTM Trigger. Args: trigger (dict): An API representation of the GTM Trigger. If provided, the resource will be not ...
#!/usr/bin/env python3 # Copyright (C) 2017-2020 The btclib developers # # This file is part of btclib. It is subject to the license terms in the # LICENSE file found in the top-level directory of this distribution. # # No part of btclib including this file, may be copied, modified, propagated, # or distributed except...
""" CCX API v0 Paginators. """ from edx_rest_framework_extensions.paginators import DefaultPagination class CCXAPIPagination(DefaultPagination): """ Pagination format used by the CCX API. """ page_size_query_param = "page_size" def get_paginated_response(self, data): """ Annotat...
def compare(v1, operator, v2): if operator == ">": return v1 > v2 elif operator == "<": return v1 < v2 elif operator == ">=": return v1 >= v2 elif operator == "<=": return v1 <= v2 elif operator == "=" or "==": return v1 == v2 elif operator == "!=": ...
from django.http import HttpResponse from django.shortcuts import render from django.views import View from .models import Grid from apps.subjects.models import Subject # Create your views here. ''' class GridView(View): template_name = 'grids/grids.html' def get(self, request): grids = Grid.object...
from fastapi import FastAPI, HTTPException import io import numpy as np from enum import Enum from fastapi import FastAPI, UploadFile, File, HTTPException from fastapi.responses import StreamingResponse import cv2 import cvlib as cv from cvlib.object_detection import draw_bbox # Asignamos una instancia de la clase Fas...
# -*- coding: utf-8 -*- """ MIT License Copyright (c) 2020 Matteo Ingrosso Basic loop to get baseline value for performance comparison between simulated images and objective ones. It just takes the two optical images as source and gets the indices for them. """ from config import * from metrics import PS...
import torch class Lambda(torch.nn.Module): def __init__(self, f): super().__init__() self.f = f def forward(self, X): return self.f(X) class ResBlock(torch.nn.Module): def __init__(self, shortcut, act, layers): super().__init__() self.sht = shortcut se...
#!/usr/bin/env python3 import os import json from textwrap import indent import sys #PRINT OUT ALL ENV VARIABLES AS PLAIN TEXT # print("Content-Type: text/plain") #let browser know to expect plain text # print() # print(os.environ) #PRINT ENV VARIABLES AS JSON print("Content-Type: application/json") print() print(js...
""" Example showing post-processing effects by modifying the flusher object. This example is a placeholder for how post-processing *could* work if we'd provide an API for it. Note: this example makes heavy use of private variables and makes assumptions about how the RenderFlusher works that may not hold in the future...
#coding=utf-8 from mirai import Mirai import datetime import time localtime = time.localtime(time.time()) day_set=localtime.tm_mday dragonId=[] #龙王id(可能有多个) dragon={} #各群今日是否已宣布龙王 n_time = datetime.datetime.now() #目前时间 start_time = 0 #程序启动时间 d_time = datetime.datetime.strptime(st...
from asyncio import QueueEmpty from pyrogram import Client, filters from Yukki import app from Yukki.YukkiUtilities.helpers.decorators import errors from Yukki.YukkiUtilities.helpers.filters import command, other_filters from Yukki.YukkiUtilities.tgcallsrun import (yukki, clear, get, is_empty, put, task_done) from Yukk...
def Print(*args): 'print helper' print(*args, sep='\n\n') # decorators: result = lambda f: f() def func(): return "[ I'm a function ]" def data(): return "[ I'm a string ]" data = result(data) @result def text(): return "[ I'm a string ]" Print( func(), text, data, )
from django.shortcuts import render, get_object_or_404, redirect from django.urls import reverse, reverse_lazy from django.views.generic.list import ListView from django.views.generic.detail import DetailView from django.views.generic.edit import ( CreateView, UpdateView, DeleteView) from django.contrib.aut...
""" Fortpy EPC server. Adapted from jedi EPC server by Takafumi Arakaki. """ import os import sys import re import itertools import logging import site fortpy = None # I will load it later def fortpy_script(source, line, column, source_path): return fortpy.isense.Script(source, line, column, source_path) def c...
class Unittest(): def __init__(self, code, language, is_input=True, is_output=True): self.language = language self.code = code self.is_input = is_input self.is_output = is_output def get_lang(self): return self.language def get_code(self): return self.code ...
import FWCore.ParameterSet.Config as cms # TrackerTrajectoryBuilders from RecoTracker.CkfPattern.CkfTrajectoryBuilder_cff import * # TrajectoryCleaning from TrackingTools.TrajectoryCleaning.TrajectoryCleanerBySharedHits_cfi import * # navigation school from RecoTracker.TkNavigation.NavigationSchoolESProducer_cff impor...
from django.db import models from django.utils.translation import ugettext_lazy as _ from django.contrib.auth.models import User class ResetPassword(models.Model): create_date = models.DateField(verbose_name=_('Create date'), auto_now=True) pwd_hash = models.TextField(verbose_name=_('Hash')) user = models...
from django.conf.urls import url from .views import SearchView app_name = "builds" urlpatterns = [ url(r"^search/", SearchView.as_view(), name="search"), ]
import subprocess from glob import glob from os.path import join, dirname, abspath __all__ = ['mpy_cross', 'run'] mpy_cross = abspath(glob(join(dirname(__file__), 'mpy-cross*'))[0]) def run(*args, **kwargs): return subprocess.Popen([mpy_cross] + list(args), **kwargs)
import datetime from .models import Item, Measurement def benchmark(func): fully_qualified_name = func.__module__ + '.' + func.__name__ def timing_function(*args, **kwargs): start = datetime.datetime.now() result = func(*args, **kwargs) end = datetime.datetime.now() duration = ...
import socket while True: N = input("Who do you want to call? ") msg = "(UrMum)" + input("What do you want to say? ") data = msg.encode("UTF-8") addr = ("Vampy-CS-"+N,8080) phone = socket.socket() try: phone.connect(addr) phone.send(data) resp = bytes.decode(phone.recv(1024)) if resp !="r": print("Whoo...
from ask_sdk_model.ui import SimpleCard from bs4 import BeautifulSoup from django.template.loader import get_template from ask_sdk_model.dialog import DelegateDirective from alexa.request_handler.buildin.cancel_and_stop import cancel_and_stop_request from alexa.request_handler.buildin.fallback import fallback_request ...
#%% class Kot: # def __init__(self, Imie, Kolor_oczu, Kolor_siersci, Dlugosc, Wysokosc, Wiek, Waga): # class constuctor - konstruktor uruchamia się przy starcie def __init__(self): # class constuctor - konstruktor uruchamia się przy starcie self.Imie = '' self.Kolor_oczu = '' self.Ko...
import pytest from brownie import * @pytest.fixture def stable_flash(): yield a[0].deploy(StableFlash, 1000) @pytest.fixture def stablecoin(): yield a[0].deploy(StableFlash, 1000) @pytest.fixture def another_stablecoin(): yield a[0].deploy(StableFlash, 1000) @pytest.fixture def flash_minter(): yiel...
# This mock-up is called by ../tests/test_plugin.py # to verify the behaviour of the plugin infrastructure def imread(fname, dtype=None): assert fname == 'test.png' assert dtype == 'i4' def imsave(fname, arr): assert fname == 'test.png' assert arr == [1, 2, 3] def imshow(arr, plugin_arg=None): as...
from pyspark.ml import Pipeline from pyspark.ml.evaluation import RegressionEvaluator from pyspark.ml.feature import VectorAssembler, StringIndexer from pyspark.ml.tuning import * from pyspark.sql import DataFrame, SparkSession from pyspark.sql.functions import udf, col, avg from pyspark.sql.types import IntegerT...
import logging from qcodes.instrument.parameter import Parameter, ManualParameter from qcodes.utils.validators import Enum from .FEMTO_OE300_base import (OE300State, OE300Error, LOW_NOISE_GAINS, HIGH_SPEED_GAINS, LP_SETTINGS, COUPLING_MODES, GAIN_SETTINGS, ERROR_TABLE, ...
# 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, software # d...
#!/usr/bin/env python3 """ Make a Windows batch file for building ca65 Pently. Usage: make clean && make -n COMSPEC=cmd pently.nes | tools/makewinbuild.py """ import sys prolog = """@echo off echo Building from batch file @echo on """ linesuffix = " || goto :error\n" epilog = """goto EOF :error echo Failed with error ...
# coding: utf-8 # Copyright (c) 2016, 2021, Oracle and/or its affiliates. All rights reserved. # This software is dual-licensed to you under the Universal Permissive License (UPL) 1.0 as shown at https://oss.oracle.com/licenses/upl or Apache License 2.0 as shown at http://www.apache.org/licenses/LICENSE-2.0. You may c...
import numpy as np import re def main(): grid = np.zeros((1000,1000)) countCollision = 0 filename = 'day3_1_input.txt' claims = [] userInput = open(filename, 'r') for line in userInput: #print(line) m = re.search("\\#(\d+) \\@ (\d+),(\d+): (\d+)x(\d+)", line) idx = int(m...
import json import torch import numpy as np from . import utils from PIL import Image from torch.utils.data.dataset import Dataset from pathlib import Path class DataLoaderRBV(Dataset): def __init__(self, folder_path, use_gt): super(DataLoaderRBV, self).__init__() self.info_files = list(Path(folder...
import torch import torch.nn as nn from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence from allennlp.modules.elmo import Elmo, batch_to_ids options_file = "https://s3-us-west-2.amazonaws.com/allennlp/models/elmo/2x4096_512_2048cnn_2xhighway/elmo_2x4096_512_2048cnn_2xhighway_options.json" weight_fi...
import arrow import json import logging import os import praw import time from praw.models import Comment, Submission from prawcore.exceptions import ResponseException, OAuthException, BadRequest, Forbidden from essential_generators import DocumentGenerator from re import sub from shreddit.util import ShredditError fro...
import logging, os, re, sys from code.utils.basic_utils import check_output_and_run import pprint as pp def run_fanngo(config): workdir=config["input"]["gomap_dir"]+"/" fanngo_sw_conf = config["data"]["mixed-method"]["fanngo"] fanngo_conf = config["software"]["fanngo"] fanngo_template = fanngo_conf["p...
#!/usr/bin/env python3 # command line args import argparse parser = argparse.ArgumentParser() parser.add_argument('--date',required=True) args = parser.parse_args() # imports import os import zipfile import datetime import json import pandas as pd from textblob import TextBlob # load keywords keywords = ['world ser...
from flask_restful import fields from server.models.custom_fields import StudentItemField, StatusItemField, UnixTimeStamp # Fields for classrom.py classrooms_list_fields = { # Fields list of classrooms 'name': fields.String, 'id': fields.Integer } classroom_resource_fields = { # Fields for a single classroom 'name...
""" calculates amount of time required to deliver list of containers over graph of destination points according to given transport, destinations and distances """ class Transport: """abstract transport class""" def __init__(self, location, distances): self.distances = distances self.location =...
from optparse import OptionParser import os import numpy as np import pandas as pd import get_site_features import utils np.set_printoptions(threshold=np.inf, linewidth=200) pd.options.mode.chained_assignment = None if __name__ == '__main__': parser = OptionParser() parser.add_option("--transcripts", dest...
import os import numpy as np import numpy.testing as npt import pytest from unittest import mock from imp import reload # Import the whole module so we can reload it: from pulse2percept.io import video from pulse2percept.io import image from pulse2percept import stimuli from pulse2percept import implants @pytest.mar...
from typing import List, Any from dataclasses import dataclass import pyjq GPU_MODELS = ['Quadro RTX 6000/8000', 'Tesla T4'] @dataclass(frozen=True) class GPU: """ Note that because GPUs aren't properly part of Ralph catalog structure, they appear as special fields inside the node and as such are not ...
import argparse import configparser import os import subprocess import sys import yaml from openlabcmd import exceptions from openlabcmd.plugins import base from openlabcmd import utils from openlabcmd.utils import _color from openlabcmd import zk from openlabcmd import repo from openlabcmd import hint class OpenLab...
from __future__ import print_function import numpy as np import keras from keras.preprocessing import sequence import keras.preprocessing.text from keras.models import Sequential from keras.layers import Dense from keras.layers import Embedding from keras.layers import GlobalAveragePooling1D from keras.datasets impor...
import numpy as np from evaluation.eval_process import * from libs.utils import * class Test_Process_DRM(object): def __init__(self, cfg, dict_DB): self.cfg = cfg self.dataloader = dict_DB['testloader'] self.DNet = dict_DB['DNet'] self.RNet = dict_DB['RNet'] self.MNet = d...
import os import redis _tls_store_certfile_key = "traefik/tls/stores/default/defaultCertificate/certFile" _tls_store_certfile_value = "{cert_file}" _tls_store_keyfile_key = "traefik/tls/stores/default/defaultCertificate/keyFile" _tls_store_keyfile_value = "{key_file}" _service_key = "traefik/tcp/services/{name}/loadB...
#!/usr/bin/env python import argparse import sys import pyspark.sql from pyspark.sql.types import DoubleType, StringType, IntegerType from pyspark.sql.functions import col, lit, udf, when, expr, explode, substring, array, regexp_extract, concat_ws import logging def load_eco_dict(inf): ''' Loads the csq to e...
from xml.dom.minidom import parse import json struct_format = ''' public struct {0}: Currency {{ public static var code = "{0}" public static var name = "{1}" public static var numericCode = "{2}" public static var minorUnits: Int? = {3} public static var entities: [String] = [{4}] public ...
""" 210CT - Programming, Algorithms and Data Structures. Question9.py Purpose: A function to search a value between a given interval in sequence using binary search algorithm. Author : Rithin Chalumuri Version: 1.0 Date : 02/12/16 """ def rangeBinary...