filename
stringlengths
13
19
text
stringlengths
134
1.04M
the-stack_106_21160
import requests import xml.etree.ElementTree as ET URL = "http://www.perseus.tufts.edu/hopper/xmlmorph?lang=greek&lookup={0}" def doRequest(w): r = requests.get(URL.format(w)) xml = ET.fromstring(r.text) forms = {} for x in xml.iter('analysis'): lemma = x.find('lemma').text expanded = ...
the-stack_106_21161
import requests from urllib.parse import urljoin BASE_URL = 'https://hangman-api.herokuapp.com' def createGame(): try: url = urljoin(BASE_URL, '/hangman') response = requests.post(url) print(response.json()) return response.json() except Exception as err: print(err) de...
the-stack_106_21163
import datetime import logging from collections import namedtuple from decimal import Decimal import sys import re import string import argparse import beancount.loader import beancount.core import time import asyncio import tempfile try: import requests except ImportError: requests = None try: import a...
the-stack_106_21167
# This file is part of Indico. # Copyright (C) 2002 - 2022 CERN # # Indico is free software; you can redistribute it and/or # modify it under the terms of the MIT License; see the # LICENSE file for more details. from indico.modules.events.models.persons import EventPerson from indico.modules.users import User from in...
the-stack_106_21168
#!/usr/bin/env python __all__ = ['baomihua_download', 'baomihua_download_by_id'] from ..common import * import urllib def baomihua_download_by_id(id, title=None, output_dir='.', merge=True, info_only=False, **kwargs): html = get_html('http://play.baomihua.com/getvideourl.aspx?flvid=%s&devicetype=phone_app' % id...
the-stack_106_21170
# coding: utf-8 """Tasks for the ISO generation. This module handles the creation of the final ISO, which involves: - creating the ISO's root - populating the ISO's tree - creating the ISO - computing the ISO's checksum Overview: ┌───────────────┐ ┌──────>│ ...
the-stack_106_21172
""" @Author : Ailitonia @Date : 2021/06/01 22:28 @FileName : monitor.py @Project : nonebot2_miya @Description : Pixiv User Monitor @GitHub : https://github.com/Ailitonia @Software : PyCharm """ import asyncio import random from nonebot import logger, require, get_bots,...
the-stack_106_21173
# Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. import logging import os from collections import OrderedDict from fairseq import utils from fairseq.data import ( BacktranslationDataset,...
the-stack_106_21176
""" nodal_averaged_equivalent_elastic_strain ======================================== """ from ansys.dpf.core.dpf_operator import Operator from ansys.dpf.core.inputs import Input, _Inputs from ansys.dpf.core.outputs import Output, _Outputs, _modify_output_spec_with_one_type from ansys.dpf.core.operators.specification i...
the-stack_106_21178
''' URL: https://leetcode.com/problems/find-peak-element Time complexity: O(logn) Space complexity: O(1) ''' class Solution(object): def findPeakElement(self, nums): """ :type nums: List[int] :rtype: int """ start = 0 end = len(nums) - 1 while start <= end: ...
the-stack_106_21179
#!/usr/bin/env python """ Get twinpy strucuture """ import argparse import numpy as np from pymatgen.io.vasp import Poscar from twinpy.properties.hexagonal import (get_hexagonal_lattice_from_a_c, get_wyckoff_from_hcp) from twinpy.interfaces.pymatgen import get_cell_from_pymatg...
the-stack_106_21180
# Copyright 2014 Objectif Libre # Copyright 2015 DotHill Systems # # 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 # # U...
the-stack_106_21182
""" Derived from henchbot.py script: https://github.com/henchbot/mybinder.org-upgrades/blob/master/henchbot.py """ from yaml import safe_load as load import requests import subprocess import os import shutil import time import logging logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(message...
the-stack_106_21183
# Copyright (c) 2019-2020, NVIDIA CORPORATION. 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 a...
the-stack_106_21188
from numpy import arcsin, exp def _comp_point_coordinate(self): """Compute the point coordinates needed to plot the Slot. Parameters ---------- self : SlotM10 A SlotM10 object Returns ------- point_dict: dict A dict of the slot coordinates """ Rbo = self.get_Rbo(...
the-stack_106_21189
""" Sensor for Inter RAO cabinet. Retrieves indications regarding current state of accounts. """ import logging import re from datetime import date, datetime from enum import IntEnum from typing import ( Any, ClassVar, Dict, Final, Hashable, Mapping, Optional, TypeVar, Union, ) impo...
the-stack_106_21190
from selenium import webdriver from fixture.session import SessionHelper from fixture.group import GroupHelper from fixture.contact import ContactHelper class Application: def __init__(self, browser, base_url): if browser == "firefox": self.wd = webdriver.Firefox( firefox_binary...
the-stack_106_21191
# FSM Simulation edges = {(1, 'a') : 2, (2, 'a') : 2, (2, '1') : 3, (3, '1') : 3} accepting = [3] def fsmsim(string, current, edges, accepting): if string == "": return current in accepting else: letter = string[0] currentState = (current, lett...
the-stack_106_21192
from __future__ import division import logging import numpy as np from smqtk.algorithms.nn_index.lsh.functors import LshFunctor from smqtk.representation.descriptor_element import elements_to_matrix from smqtk.utils.bin_utils import report_progress class SimpleRPFunctor (LshFunctor): """ This class is meant...
the-stack_106_21194
""" Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this ...
the-stack_106_21195
# -*- coding: utf-8 -*- import json import logging import re from ..utils.crawler import Crawler logger = logging.getLogger(__name__) search_url = 'https://www.royalroad.com/fictions/search?keyword=%s' class RoyalRoadCrawler(Crawler): base_url = 'https://www.royalroad.com/' def search_novel(self, query): ...
the-stack_106_21196
# -*- coding: utf-8 -*- # -- General configuration ----------------------------------------------------- # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = [ 'sphinx.ext.todo', 'sphinx.ext.imgmath', ...
the-stack_106_21198
import os import pickle def check_file_exists(file_path): return os.path.exists(file_path) def save_to_pickle(data, save_path): with open(save_path, "wb") as handle: pickle.dump(data, handle, protocol=pickle.HIGHEST_PROTOCOL) def load_from_pickle(load_path, encoding="latin1"): if check_file_ex...
the-stack_106_21199
# This sample tests the scoping rules for assignment expressions # within a list comprehension. from typing import Tuple def foo() -> Tuple[str, int]: a = 3 y = 4 b = [(a := x) for x in ["1", "2"] for y in ["1", "2"]] # The type of "y" should be int because the "y" within # the list comprehensio...
the-stack_106_21200
from __future__ import print_function, division from sympy import Symbol, Integer, sympify class PlotInterval(object): """ """ _v, _v_min, _v_max, _v_steps = None, None, None, None def require_all_args(f): def check(self, *args, **kwargs): for g in [self._v, self._v_min, self._v_...
the-stack_106_21201
# File to ingest an equities bundle for zipline # Import libraries import pandas as pd import numpy as np import sys data_folder = r'C:\Users\\walte\\OneDrive - K Squared Capital\\K Squared Capital\\Trading Models\\Code\\Live Trading\\Live Trading' from zipline.utils.calendars import get_calendar def eu_etfs_bundle()...
the-stack_106_21202
import os from unittest import TestCase from unittest.mock import patch from selenium_youtube_crawler.utilities import read_playlist_from_file, read_playlist_from_youtube_api, \ populate_local_archive, create_required_dirs_for_archive_if_not_present class TestUtilities(TestCase): def test_read_playlist_from...
the-stack_106_21203
# -*- coding: utf-8 -*- """ Kakao Hangul Analyzer III __version__ = '0.4' __author__ = 'Kakao Corp.' __copyright__ = 'Copyright (C) 2018-, Kakao Corp. All rights reserved.' __license__ = 'Apache 2.0' __maintainer__ = 'Jamie' __email__ = 'jamie.lim@kakaocorp.com' """ ########### # imports # ########### from distuti...
the-stack_106_21204
# Copyright 2018 The TensorFlow Authors. 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 applica...
the-stack_106_21205
from .pdg_format import _round, _strip import numpy as np import re def pdg_format(value, *errors): if value is None: strings, nexp = _round((0, *errors), None, None) strings = strings[1:] else: strings, nexp = _round((value, *errors), None, None) strings = _strip(strings) if n...
the-stack_106_21206
# Configuration file for the Sphinx documentation builder. # # This file only contains a selection of the most common options. For a full # list see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Path setup -------------------------------------------------------------- # If ex...
the-stack_106_21207
""" Exceptions that are raised by sam deploy """ from samcli.commands.exceptions import UserException class ChangeEmptyError(UserException): def __init__(self, stack_name): self.stack_name = stack_name message_fmt = "No changes to deploy. Stack {stack_name} is up to date" super(ChangeEmpty...
the-stack_106_21208
# micropolisevaluationpanel.py # # Micropolis, Unix Version. This game was released for the Unix platform # in or about 1990 and has been modified for inclusion in the One Laptop # Per Child program. Copyright (C) 1989 - 2007 Electronic Arts Inc. If # you need assistance with this program, you may contact: # http:...
the-stack_106_21209
# multithread demo # https://nrsyed.com/2018/07/05/multithreading-with-opencv-python-to-improve-video-processing-performance/ # object-oriented programming + multithread # # 1 thread - acquire image from camera # 1 thread - to disply raw image # 1 thread - to calculate Laplacian of Guassian image of the ra...
the-stack_106_21211
import logging from aiogram.dispatcher import FSMContext from aiogram.types import CallbackQuery, Message from filters.filters_admin import IsAdmin from keyboards.default.cancel_menu import cancel_menu from keyboards.inline.callback_datas import message_callback from keyboards.inline.react_buttons import message_choi...
the-stack_106_21212
from __future__ import unicode_literals import pprint from django import VERSION as DJANGO_VERSION from django.conf import global_settings from django.core.checks import Warning from yacms.conf import settings def check_template_settings(app_configs, **kwargs): issues = [] if not settings.TEMPLATES: ...
the-stack_106_21213
# 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 ...
the-stack_106_21216
#!/usr/bin/python3 import os import json from pprint import pprint INSTANCE_FOLDER = './original' TO_FOLDER = './json' def convert(): files = os.listdir(INSTANCE_FOLDER) for file in files: filename = file.split('.')[0] to_folder = os.path.join(TO_FOLDER, filename) if n...
the-stack_106_21217
import unittest from petsc4py import PETSc import os from PetscBinaryIO import * class TestPetscBinaryIO(unittest.TestCase): def setUp(self): try: os.remove('test.dat') except OSError: pass try: os.remove('test.dat.info') except OSError: ...
the-stack_106_21220
import os import dmenu import pyimgur def upload(): client_id = "8e98531fa1631f6" PATH = "/tmp/screenshot.png" im = pyimgur.Imgur(client_id) uploaded_image = im.upload_image(PATH, title="Uploaded with PyImgur") print(uploaded_image.link) os.system("rm /tmp/screenshot.png") def save_local(): save_name = dmenu.s...
the-stack_106_21223
# -*- coding: utf-8 -*- # --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.4' # jupytext_version: 1.2.3 # kernelspec: # display_name: Python [conda env:cpm] # language: python # name: conda-env-cpm-py # --- import p...
the-stack_106_21224
""" @author: David Lei @since: 22/04/2017 @modified: https://www.hackerrank.com/challenges/ctci-comparator-sorting Sample input: 5 amy 100 david 100 heraldo 50 aakansha 75 aleksa 150 """ from functools import cmp_to_key class Player: def __init__(self, name, score): self.name = name self.score ...
the-stack_106_21226
# Copyright (c) 2018 PaddlePaddle Authors. 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 app...
the-stack_106_21228
""" This code is modified from Hao Luo's repository. Paper: Bag of Tricks and A Strong Baseline for Deep Person Re-identification https://github.com/michuanhaohao/reid-strong-baseline """ import copy import random import torch from collections import defaultdict import numpy as np from torch.utils.data.sampler import...
the-stack_106_21229
import networkx as nx import matplotlib.pyplot as plt import v_parser ''' in_n: input nodes; out_n: output nodes; nodes: gates; edges: wire connections ''' def grapher(in_n, out_n, nodes, edges): # in_n, out_n, nodes, edges = verilog_parser.parser(file_) G=nx.DiGraph()#graph creation G.add_nodes_from(in...
the-stack_106_21230
# coding: utf-8 """ Training module """ import argparse import time import shutil from typing import List import logging import os import sys import queue import pickle import json import numpy as np import torch from torch import Tensor from torch.utils.tensorboard import SummaryWriter from torchtext.data import ...
the-stack_106_21232
import urllib.request, json import pandas as pd import os import datetime as dt from sklearn.preprocessing import MinMaxScaler import numpy as np from alpha_vantage.timeseries import TimeSeries class DataLoader: scaler = MinMaxScaler(feature_range=(0, 1)) api_key = "<Alpha Vantage API KEY>" def get_his...
the-stack_106_21233
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not us...
the-stack_106_21234
import logging import sys import pdb import shutil from tensorboardX import SummaryWriter class TensorboardHandler(logging.Handler): def __init__(self, writer, tag): self.writer = writer self.tag = tag super().__init__() def emit(self, record): log_entry = self.format(record) ...
the-stack_106_21238
"""Tests for importing OAS by Toolbox""" import json import random import re import string from urllib.parse import urlparse import importlib_resources as resources import pytest import yaml from testsuite.config import settings from testsuite import rawobj from testsuite.rhsso.rhsso import OIDCClientAuth from tests...
the-stack_106_21239
# Copyright (c) Microsoft Corporation. # Licensed under the MIT License. import pickle import dill from pathlib import Path from typing import Union class Serializable: """ Serializable will change the behaviors of pickle. - It only saves the state whose name **does not** start with `_` It provides a...
the-stack_106_21241
import os import errno import numpy as np from torch.nn import init import torch import torch.nn as nn from PIL import Image, ImageDraw, ImageFont from copy import deepcopy import skimage.transform from miscc.config import cfg # For visualization ################################################ COLOR_DIC = {0:[128...
the-stack_106_21242
import sys import argparse import torch import marius as m def main(): parser = argparse.ArgumentParser( description='Configuration file based training', prog='train') parser.add_argument('config', metavar='config', type=str, hel...
the-stack_106_21244
from typing import List, Optional, Tuple import numpy as np import mindspore from mindspore import Tensor from mindspore.ops import operations as P import mindspore.common.dtype as mstype def generate( model=None, config=None, input_ids: Optional[Tensor] = None, input_mask: Optional[Te...
the-stack_106_21246
# -*- coding: UTF-8 -*- from flask import Blueprint, Flask, jsonify, request, make_response import pdfkit from utils.cm.utils import is_exist from utils.cm.files import delete_dir from utils.pdf.pdfkits import * app = Blueprint('pdfapi', __name__) # curl -v -H "Content-type: application/json" -X POST http://192.168.1...
the-stack_106_21247
import os, sys file_path = os.path.abspath(__file__) project_path = os.path.dirname(os.path.dirname(file_path)) sys.path.append(project_path) import glob import open3d as o3d import numpy as np from tqdm import tqdm from dataset.base import DatasetBase from geometry.pointcloud import make_o3d_pointcloud, extract_fe...
the-stack_106_21248
#!/usr/bin/env python3 """A dead simple aiohttp-based library for weeb.sh. Nothing more. Honest.""" from typing import List import urllib import asyncio import aiohttp BASE_URL_TYPES = "https://api.weeb.sh/images/types" BASE_URL_TAGS = "https://api.weeb.sh/images/tags" BASE_URL_RANDOM = "https://api.weeb.sh/images...
the-stack_106_21249
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, ...
the-stack_106_21252
import logging import os from django.conf import settings APP_DIR = settings.LOG_DIR LOG_FILE = os.path.join(APP_DIR, 'mics_odk.log') logger = logging.getLogger('audit_logger') handler = logging.FileHandler(LOG_FILE) formatter = logging.Formatter('[%(asctime)s] %(levelname)s %(message)s') handler.setFormatter(formatte...
the-stack_106_21253
import json import logging import os from collections import OrderedDict from mgl2d.graphics.texture import Texture from mgl2d.math.rect import Rect from mgl2d.math.vector2 import Vector2 logger = logging.getLogger(__name__) # NOTE: This class needs to be tested and updated class FramesStore: DEFAULT_FPS = 30 ...
the-stack_106_21254
import asyncio import discord from discord import HTTPException, InvalidArgument, Embed, Role, Emoji from discord.ext import commands from discord.ext.commands import Greedy from Cogs.BaseCog import BaseCog from Util import Permissioncheckers, MessageUtils, Translator, Pages, Utils from Util.Converters import EmojiNa...
the-stack_106_21256
from util import * import matplotlib.pyplot as plt plt.ion() def distmat(p, q): """Computes pair-wise L2-distance between columns of p and q.""" d, pn = p.shape d, qn = q.shape pmag = np.sum(p**2, axis=0).reshape(1, -1) qmag = np.sum(q**2, axis=0).reshape(1, -1) dist = qmag + pmag.T - 2 * np.dot(p.T, q) ...
the-stack_106_21257
# Copyright 2017 The TensorFlow Authors. 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 applica...
the-stack_106_21258
from pystac import Extensions from pystac.item import Item from pystac.extensions.base import (ItemExtension, ExtensionDefinition, ExtendedObject) class EOItemExt(ItemExtension): """EOItemExt is the extension of the Item in the eo extension which represents a snapshot of the earth for a single date and time. ...
the-stack_106_21259
import abc, json from .yaml_parser import SimpleRegex, NestedRegex, ParamsRegex, Dictionary, List class CodeWriter: def __init__(self, name): self.name = name @abc.abstractmethod def write(self): pass class DefaultWriter(CodeWriter): def __init__(self, name, definition...
the-stack_106_21261
# Code from Chapter 15 of Machine Learning: An Algorithmic Perspective (2nd Edition) # by Stephen Marsland (http://stephenmonika.net) # You are free to use, change, or redistribute the code in any way you wish for # non-commercial purposes, but please maintain the name of the original author. # This code comes with no...
the-stack_106_21265
from itertools import repeat, zip_longest from typing import Iterator, Iterable import tensorflow as tf K = tf.keras DISCARD_REMAINDER = 'DISCARD_REMAINDER' def next_n(it: Iterator, n: int): return list(map(next, repeat(it, n))) def longest_grouper(iterable: Iterable, group_size: int, fillvalue=None): """ Col...
the-stack_106_21268
import setuptools with open("README.md") as fp: long_description = fp.read() setuptools.setup( name="cdk_aws_cookbook_206", version="0.0.1", description="An empty CDK Python app", long_description=long_description, long_description_content_type="text/markdown", author="author", pa...
the-stack_106_21270
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Create a base docker image for building pyflann """ from __future__ import absolute_import, division, print_function import os from os.path import join import ubelt as ub def main(): # TODO: find a better place for root ROOT = join(os.getcwd()) # ROOT = '...
the-stack_106_21271
# coding: utf-8 """ Copyright 2016 SmartBear Software 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 applica...
the-stack_106_21272
""" pygame-menu https://github.com/ppizarror/pygame-menu HORIZONTAL MARGIN Horizontal box margin. License: ------------------------------------------------------------------------------- The MIT License (MIT) Copyright 2017-2021 Pablo Pizarro R. @ppizarror Permission is hereby granted, free of charge, to any person ...
the-stack_106_21273
#!/usr/bin/env python # # Cloudlet Infrastructure for Mobile Computing # - Task Assistance # # Author: Zhuo Chen <zhuoc@cs.cmu.edu> # # Copyright (C) 2011-2013 Carnegie Mellon University # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the...
the-stack_106_21275
#!/usr/bin/env python from __future__ import print_function import logging import os import pandas import SimpleITK as sitk import radiomics from radiomics import featureextractor def main(): outPath = r'' inputCSV = os.path.join(outPath, 'testCases.csv') outputFilepath = os.path.join(outPath, 'radiomics_f...
the-stack_106_21276
"""Test time schema implementation.""" import numpy as np import pandas as pd import pytest from asdf import ValidationError from weldx.asdf.util import _write_buffer, _write_read_buffer @pytest.mark.parametrize( "inputs", [ pd.Timedelta("5m3ns"), pd.Timedelta("106751 days 23:47:16.854775"), ...
the-stack_106_21277
"""Print a summary of specialization stats for all files in the default stats folders. """ import collections import os.path import opcode from datetime import date import itertools import argparse import sys if os.name == "nt": DEFAULT_DIR = "c:\\temp\\py_stats\\" else: DEFAULT_DIR = "/tmp/py_stats/" #Creat...
the-stack_106_21279
""" PRACTICE Exam 1, problem 0. These problems illustrate concepts that previous problems have not emphasized: -- determining whether a number is odd or even (Problem 0a) -- returning True or False (Problem 0a) -- is_prime (Problem 0b) -- animation (Problem 0c) Authors: David Mutchler, Vibha Alangar, Matt Bou...
the-stack_106_21280
#!/Users/harukii/PycharmProjects/InterfaceAutoTest/venv/bin/python # Copyright (c) 2005-2012 Stephen John Machin, Lingfo Pty Ltd # This script is part of the xlrd package, which is released under a # BSD-style licence. from __future__ import print_function cmd_doc = """ Commands: 2rows Print the contents o...
the-stack_106_21281
from functools import lru_cache import logging import re from lona import default_settings ABSTRACT_ROUTE_RE = re.compile(r'<(?P<name>[^:>]+)(:(?P<pattern>[^>]+))?>') ROUTE_PART_FORMAT_STRING = r'(?P<{}>{})' DEFAULT_PATTERN = r'[^/]+' OPTIONAL_TRAILING_SLASH_PATTERN = r'(/)' MATCH_ALL = 1 logger = logging.getLogger...
the-stack_106_21282
import pandas as pd from eventstudy.naivemodel import EventStudyNaiveModel from eventstudy.dpyahoo import DataProviderYahoo import datetime as dt def read_events(file_name, start_date, end_date, value_threshold=7): """Read a csv and return a list of events as a pandas DataFrame.""" event_list_df = pd.read_c...
the-stack_106_21285
#!/usr/bin/env python import os import time import RPi.GPIO as GPIO # Import Raspberry Pi GPIO library import sys if len(sys.argv) < 2: print("Usage: killswitch.py /path/to/kill_script") exit(1) full_kill_script_path = "" if os.path.isfile(sys.argv[1]): full_kill_script_path = os.path.abspath(sys.argv[1...
the-stack_106_21286
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """CIFAR10 dataset.""" import numpy as np import os import pickle import torch import torch.utils.data from sscls.co...
the-stack_106_21288
import cv2 import numpy as np from mmpose.core.post_processing import transform_preds def _calc_distances(preds, targets, mask, normalize): """Calculate the normalized distances between preds and target. Note: batch_size: N num_keypoints: K Args: preds (np.ndarray[N, K, 2]): Pre...
the-stack_106_21290
number=int(input("enter the no to check prime or not")) n=int(number/2) flag=0 for i in range(2,n+1): if number % 2 == 0: flag = 1 if flag == 1: print("not a prime number") else: print('prime number')
the-stack_106_21295
# -*- coding: utf-8 -*- from __future__ import absolute_import, annotations, division, print_function import argparse import logging import os import re import time from collections.abc import Callable from enum import Enum, unique from typing import Any, Callable, Dict, List, Optional, Tuple from rich.console impor...
the-stack_106_21299
from src.loader.LoaderInterface import LoaderInterface from src.utility.Utility import Utility class ObjectLoader(LoaderInterface): """ Just imports the objects for the given file path The import will load all materials into cycle nodes. **Configuration**: .. list-table:: :widths: 25 100 1...
the-stack_106_21302
from dask.distributed import get_client, futures_of from dask import delayed from toolz import partition_all import numpy as np def _cluster_mode(): try: get_client() return True except ValueError: return False def get_futures(lst): """ Loop through items in list to keep order of...
the-stack_106_21305
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from django.core.urlresolvers import reverse from django.test import TestCase from ralph.ui.tests.global_utils import login_as_su from ralph_as...
the-stack_106_21307
import getopt import os import sys import time import matplotlib.pyplot as plt import pandas as pd import netifaces as ni CONNECTIONS = 'Connections' REQS_PER_SEC = 'Requests/Second' DATA_FILENAME = 'benchmark_output.csv' PLOT_FILENAME = 'benchmark_plot.png' PORT = 8081 # retrieve the ip address of the swissknife0 in...
the-stack_106_21308
from typing import List, Dict from overrides import overrides import numpy from allennlp.common.util import JsonDict from allennlp.data import DatasetReader, Instance from allennlp.data.fields import FlagField, TextField, SequenceLabelField from allennlp.data.tokenizers.spacy_tokenizer import SpacyTokenizer from alle...
the-stack_106_21309
# The MIT License (MIT) # Copyright (c) 2021-present EQUENOS # 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, mod...
the-stack_106_21311
# Copyright 2020 The TensorFlow Probability Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law o...
the-stack_106_21312
#!/usr/bin/python ''' Extract _("...") strings for translation and convert to Qt stringdefs so that they can be picked up by Qt linguist. ''' from __future__ import division,print_function,unicode_literals from subprocess import Popen, PIPE import glob import operator import os import sys OUT_CPP="qt/prismstrings.cpp"...
the-stack_106_21313
from shablbot.components.chat import Chat def command(processed_chat: Chat) -> None: processed_chat.turn_off() command_settings = { "code": "bot_off", "name": "Выключить бота", "templates": ["выкл бот", "бот выкл"], "answer": "Теперь бот не читает сообщения в чате", "description": "Команда для...
the-stack_106_21314
from collections import Counter # Just stick some data there with open('email_addresses.txt', 'w') as f: f.write("joelgrus@gmail.com\n") f.write("joel@m.datasciencester.com\n") f.write("joelgrus@m.datasciencester.com\n") def get_domain(email_address: str) -> str: """Split on '@' and return the last pi...
the-stack_106_21315
# day 12 challenge 1 from collections import deque # get input data instructions = [] with open('input.txt', 'r') as file: for line in file: instructions.append((line[0], int(line[1:]))) # x and y are 0, facing is 0 = east curr = {'x' : 0, 'y' : 0, 'f' : deque(['E', 'S', 'W', 'N'])} for instruction in ins...
the-stack_106_21318
# Default configuration where the problem is regression and the agent is Kalman Filter import ml_collections # Local imports from configs.utils import PriorKnowledge def get_config(): """Get the default hyperparameter configuration.""" config = ml_collections.ConfigDict() config.problem = "classification...
the-stack_106_21319
from __future__ import absolute_import from __future__ import division from __future__ import print_function import torch.nn.functional as F import torch import torch.nn as nn import util.util as util from util.Selfpatch import Selfpatch # SE MODEL class SELayer(nn.Module): def __init__(self, channel, reduction=1...
the-stack_106_21321
from collections import OrderedDict from sqlalchemy.inspection import inspect as sqlalchemyinspect from sqlalchemy.ext.hybrid import hybrid_property from sqlalchemy.orm.exc import NoResultFound from graphene import Field # , annotate, ResolveInfo from graphene.relay import Connection, Node from graphene.types.object...
the-stack_106_21322
""" 2019-06957 Michael Benjamin C. Morco CS 150 Extra Lab 1 Wordle Clone """ from ctypes import alignment import toga from toga.style import Pack from toga.style.pack import COLUMN, ROW, CENTER import random class get_word: def __init__(self, words): self.rando = random.randint(0,2314) ...
the-stack_106_21323
import torch from mmdet.core import bbox2result, bbox2roi from ..builder import HEADS, build_head, build_roi_extractor from .standard_roi_head import StandardRoIHead @HEADS.register_module() class GridRoIHead(StandardRoIHead): """Grid roi head for Grid R-CNN. https://arxiv.org/abs/1811.12030 """ de...