content
stringlengths
7
928k
language
stringclasses
1 value
from pygments.lexers import Python3Lexer from pygments.token import Comment, Keyword, Name, Number, Operator, Punctuation, String def is_comment(token): return token in Comment def is_decorator(token): return token in Name.Decorator def is_function(token): return token in Name.Function def is_builti...
Python
# vmimages.py - azurerm functions for Microsoft.Compute RP publishers and images from .restfns import do_get from .settings import azure_rm_endpoint, COMP_API # list_offers(access_token, subscription_id, location, publisher) # list available VM image offers from a publisher def list_offers(access_token, subscription...
Python
# coding=utf8 # Copyright 2018 JDCLOUD.COM # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed ...
Python
import os import random from riscv_definitions import * NONE = 0 CF_J = 1 CF_BR = 2 CF_RET = 3 MEM_R = 4 MEM_W = 5 CSR = 6 PREFIX = '_p' MAIN = '_l' SUFFIX = '_s' class Word(): def __init__(self, label: int, insts: list, tpe=NONE, xregs=[], fregs=[], imms=[], symbols=[], populated=False): se...
Python
from __future__ import print_function import os import time import random import datetime import scipy.misc import numpy as np import tensorflow as tf import tensorflow.contrib.slim as slim from datetime import datetime from util.util import * from util.BasicConvLSTMCell import * class DEBLUR(object): def __init_...
Python
from datetime import datetime import json from unittest import TestCase from celery.schedules import schedule, crontab try: # celery 3.x from celery.utils.timeutils import timezone except ImportError: # celery 4.x from celery.utils.time import timezone from redbeat.decoder import RedBeatJSONDecoder, RedBeat...
Python
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import requests import json import datetime url = 'https://endpoints.office.com/endpoints/worldwide?clientrequestid=b10c5ed1-bad1-445f-b386-b919946339a7' r = requests.get(url) service_list = r.json() lurls= [] lips = [] for service in service_list: for url in servic...
Python
# -*- coding: utf-8 -*- # Copyright (c) 2014, Vispy Development Team. # Distributed under the (new) BSD License. See LICENSE.txt for more info. import numpy as np from numpy.testing import assert_allclose from vispy.util.transforms import (translate, scale, rotate, ortho, frustum, pe...
Python
# Uses python3 import sys def get_change(money, coins): t = [j+1 for j in range(money+1)] # boundary condition t[0] = 0 for j in range(1, money+1): for c in coins: if c <= j: t[j] = min(t[j], 1+t[j-c]) return t[money] if __name__ == '__main__': coins =...
Python
import os import torch import os import random from torch.nn import( Module,Linear,LayerNorm ) import math from .AutoEncoder import Encoder class DeltaT(Module): def __init__(self): super().__init__() self.reset_seed() self.elem = math.prod(Encoder().output_size) self.input_size...
Python
import asyncio import logging import ssl import time import traceback from ipaddress import IPv6Address, ip_address, ip_network, IPv4Network, IPv6Network from pathlib import Path from secrets import token_bytes from typing import Any, Callable, Dict, List, Optional, Union, Set, Tuple from aiohttp import ClientSession,...
Python
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ('data', '0002_auto_20141114_1935'), ] operations = [ migrations.RemoveField( model_name='registryentry', ...
Python
from python_dwd.additionals.functions import check_parameters, retrieve_time_resolution_from_filename,\ retrieve_parameter_from_filename, retrieve_period_type_from_filename, determine_parameters from python_dwd.enumerations.period_type_enumeration import PeriodType from python_dwd.enumerations.time_resolution_enume...
Python
import praw c_id='34kxuaxc4yWiKw' c_secret='8bJqHqNHFdB6NKV9sHzFbo4_Dl4' ua='my user agent' un='the_ugly_bot' pwd='whatever930' def login(): r = praw.Reddit(client_id=c_id, client_secret=c_secret, user_agent=ua, username=un, passwor...
Python
# Copyright 2020 The HuggingFace Team. 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 applicabl...
Python
from .utils import make_cobertura def remove_style_tag(html): style_pattern_start = '\n <style>' style_pattern_stop = '\n </style>' style_starts = html.find(style_pattern_start) style_stops = html.find(style_pattern_stop) + len(style_pattern_stop) html_nostyle = html[:style_starts] + html[st...
Python
import pytest from exchange_calendars.exchange_calendar_xshg import XSHGExchangeCalendar from .test_exchange_calendar import ExchangeCalendarTestBase from .test_utils import T class TestXSHGCalendar(ExchangeCalendarTestBase): @pytest.fixture(scope="class") def calendar_cls(self): yield XSHGExchangeCa...
Python
#For the whatsapp statuses url given below #COOL import requests from bs4 import BeautifulSoup url_to_scrape = 'https://www.appstatustxt.com/cool-whatsapp-status/' r = requests.get(url_to_scrape) soup = BeautifulSoup(r.text,"html5lib") status_object=[] statuses=[] title=soup.title.string print(title) status_...
Python
import copy import datetime import decimal import inspect import json import logging import traceback import uuid import warnings from collections import Counter, defaultdict, namedtuple from collections.abc import Hashable from functools import wraps from typing import List from dateutil.parser import parse from gre...
Python
"""""" import os import uuid import bz2 import pickle import traceback import zlib from abc import ABC from copy import copy,deepcopy from typing import Any, Callable from logging import INFO, ERROR from datetime import datetime from vnpy.trader.constant import Interval, Direction, Offset, Status, OrderType, Color, Ex...
Python
# -*- coding: utf-8 -*- ''' A Runner module interface on top of the salt-ssh Python API. This allows for programmatic use from salt-api, the Reactor, Orchestrate, etc. ''' # Import Python Libs from __future__ import absolute_import # Import Salt Libs import salt.client.ssh.client def cmd( tgt, fun,...
Python
from infoblox_netmri.utils.utils import locate, to_snake from infoblox_netmri.api.exceptions.netmri_exceptions import NotImplementedException class Broker(object): """ Base class for broker instances, provides methods for API requests. And return responces wrapped with specific class :param client...
Python
# layout.py # --------- # Licensing Information: You are free to use or extend these projects for # educational purposes provided that (1) you do not distribute or publish # solutions, (2) you retain this notice, and (3) you provide clear # attribution to UC Berkeley, including a link to http://ai.berkeley.edu. # # A...
Python
#!/usr/bin/env python3 # Copyright (c) 2014-2017 The Bitcoinlimitededition Core developers # Distributed under the MIT software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. """Test the REST API.""" from test_framework.test_framework import BitcoinlimitededitionTes...
Python
N = int(input()) line = [] for a in range(N): line.append(int(input())) total = 0 curIter = 1 while min(line) < 999999: valleys = [] for a in range(N): if line[a] < 999999: if (a == 0 or line[a] <= line[a - 1]) and (a == N - 1 or line[a] <= line[a + 1]): valleys.append...
Python
from django.conf.urls import url from . import views urlpatterns = [ url( r"^control/event/(?P<organizer>[^/]+)/(?P<event>[^/]+)/key-file-upload/$", views.KeyFileUploadView.as_view(), name="key_file_upload", ), ]
Python
#!/usr/bin/env python # # Copyright 2013 The Rust Project Developers. See the COPYRIGHT # file at the top-level directory of this distribution and at # http://rust-lang.org/COPYRIGHT. # # Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or # http://www.apache.org/licenses/LICENSE-2.0> or the MIT license #...
Python
r""" Early Stopping ^^^^^^^^^^^^^^ Monitor a validation metric and stop training when it stops improving. """ from copy import deepcopy import numpy as np import torch import torch.distributed as dist from pytorch_lightning import _logger as log from pytorch_lightning.callbacks.base import Callback from pytorch_lig...
Python
# Copyright Pincer 2021-Present # Full MIT License can be found in `LICENSE` at the project root. from __future__ import annotations from dataclasses import dataclass from typing import TYPE_CHECKING from ...utils.api_object import APIObject if TYPE_CHECKING: from ..message.emoji import Emoji @dataclass class...
Python
""" Facebook platform for notify component. For more details about this platform, please refer to the documentation at https://home-assistant.io/components/notify.facebook/ """ import logging from aiohttp.hdrs import CONTENT_TYPE import requests import voluptuous as vol from homeassistant.components.notify import ( ...
Python
# encoding: utf-8 import pytest from osf_tests.factories import ( RegistrationFactory, RegistrationProviderFactory ) from osf.models import ( RegistrationSchema, ) from osf.management.commands.move_egap_regs_to_provider import ( main as move_egap_regs ) from django.conf import settings @pytest.mar...
Python
from django.contrib import auth from django.shortcuts import render from rest_framework import generics, authentication, permissions from rest_framework.authtoken.views import ObtainAuthToken from rest_framework.settings import api_settings from user.serializers import UserSerializer, AuthTokenSerializer class Cre...
Python
from __future__ import print_function import sys import datetime import random def main(n): start = -86400 * 365 * 20 end = 86400 * 365 filename = 'testdata-' + str(n) + '.txt' with open(filename, 'w') as fp: now = datetime.datetime.now() for i in range(n): d = datetime.tim...
Python
import os import sys filename = __file__[:-5] + '-input' with open(filename) as f: board = list(map(lambda s: list(map(int, list(s))), f.read().splitlines())) max_row = len(board) max_col = len(board[0]) def get_neighbors(row, col): n = [] if(row > 0): n.append((row-1,col)) if(row+1 < max_r...
Python
import tensorflow as tf class FrozenBatchNorm2D(tf.keras.layers.Layer): def __init__(self, eps=1e-5, **kwargs): super().__init__(**kwargs) self.eps = eps def build(self, input_shape): self.weight = self.add_weight(name='weight', shape=[input_shape[-1]], ...
Python
from __future__ import unicode_literals import unittest from torrent_parser import encode class TestEncode(unittest.TestCase): def test_encode(self): self.assertEqual(encode(12345), b'i12345e')
Python
from .protocol import * import serial import time from threading import Lock from PIL import Image, ImageDraw, ImageOps, ImageFont class Device: ser = None inbuffer = "" awaitingResponseLock = Lock() testmode = False nLeds = 0 dispW = 0 dispH = 0 rotFactor = 0 rotCircleSteps = 0 ...
Python
import logging from django.utils.decorators import method_decorator from django_filters.rest_framework import DjangoFilterBackend from drf_yasg.utils import swagger_auto_schema from rest_condition import Or from rest_framework import filters, viewsets from rest_framework.permissions import IsAdminUser, IsAuthenticated...
Python
from .customer_service import * from .transaction_service import * from .webhook_service import *
Python
""" .. module: lemur.domains.models :platform: Unix :copyright: (c) 2018 by Netflix Inc., see AUTHORS for more :license: Apache, see LICENSE for more details. .. moduleauthor:: Kevin Glisson <kglisson@netflix.com> """ from sqlalchemy import Column, Integer, String, Boolean, Index from lemur.database impo...
Python
import pytest import numpy as np from numpy.testing import (assert_array_equal, assert_array_almost_equal, assert_almost_equal, assert_equal) from nose.tools import assert_raises from pystruct.models import NodeTypeEdgeFeatureGraphCRF, EdgeFeatureGraphCRF from pystruct.inference.linear_prog...
Python
from unittest import TestCase from pyVHDLParser.Blocks.List import PortList from pyVHDLParser.Blocks.List.PortList import PortListInterfaceSignalBlock from pyVHDLParser.Token import WordToken, StartOfDocumentToken, SpaceToken, CharacterToken, EndOfDocumentToken from...
Python
""" Tests for grph.py """ import os import platform import random import re import string from subprocess import getstatusoutput PRG = './grph.py' RUN = f'python {PRG}' if platform.system() == 'Windows' else PRG SAMPLE1 = './tests/inputs/1.fa' SAMPLE2 = './tests/inputs/2.fa' SAMPLE3 = './tests/inputs/3.fa' # ------...
Python
# Copyright (C) 2019 Google Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
Python
# -*- coding: utf-8 -*- import pkg_resources import platform API_YOUTU_END_POINT = 'http://api.youtu.qq.com/' API_TENCENTYUN_END_POINT = 'https://youtu.api.qcloud.com/' API_YOUTU_VIP_END_POINT = 'https://vip-api.youtu.qq.com/' APPID = 'xxx' SECRET_ID = 'xxx' SECRET_KEY = 'xx' USER_ID = 'xx' _config = { 'end_poin...
Python
from pyspark.sql import Column, DataFrame, SparkSession, functions from pyspark.sql.functions import * from py4j.java_collections import MapConverter from delta.tables import * import shutil import threading tableName = "tbltestpython" # Enable SQL/DML commands and Metastore tables for the current spark session. # W...
Python
import os import sys as _sys import platform import re PY2 = _sys.version_info < (3,) PY3 = not PY2 RE_NUM = re.compile(r'(\d+).+') if not PY2: # these were moved around for Python 3 from urllib.parse import (quote as url_quote, unquote as url_unquote, urlencode) # Python 3...
Python
# Copyright lowRISC contributors. # Licensed under the Apache License, Version 2.0, see LICENSE for details. # SPDX-License-Identifier: Apache-2.0 r""" Class describing simulation configuration object """ import os import shutil import subprocess import sys from collections import OrderedDict import logging as log fr...
Python
from bs4 import BeautifulSoup from django.forms import ( BaseForm, BaseFormSet, BoundField, CheckboxInput, CheckboxSelectMultiple, DateInput, EmailInput, FileInput, MultiWidget, NumberInput, PasswordInput, RadioSelect, Select, SelectDateWidget, TextInput, ...
Python
#!/usr/bin/env python # encoding: utf-8 """ @author: zhanghe @software: PyCharm @file: type_bank.py @time: 2019-08-17 18:23 """ from __future__ import unicode_literals from flask_babel import lazy_gettext as _ from app_common.maps.default import DEFAULT_SEARCH_CHOICES_INT, DEFAULT_SELECT_CHOICES_INT # 银行类型(1:基本账户,...
Python
from pypy.tool.pairtype import pairtype from pypy.annotation import model as annmodel from pypy.objspace.flow.model import Constant from pypy.rpython.lltypesystem import lltype from pypy.rlib.rarithmetic import r_uint from pypy.rlib.objectmodel import hlinvoke from pypy.rpython import robject from pypy.rlib import obje...
Python
# Copyright 2010 OpenStack Foundation # 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 requ...
Python
# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries # SPDX-License-Identifier: MIT # Analog to digital converter example. # Will loop forever printing ADC channel 1 raw and mV values every second. # NOTE the ADC can only read voltages in the range of ~900mV to 1800mV! import time import board impo...
Python
import re from typing import TypeVar import questionary EnumType = TypeVar("EnumType") # 驼峰命名转蛇形命名 def camel_to_snake(text: str) -> str: return re.sub(r"(?<!^)(?=[A-Z])", "_", text).lower() # 蛇形命名转驼峰命名 def snake_to_camel(text: str) -> str: return text.split('_')[0] + "".join(x.title() for x in text.split('...
Python
import numpy as np import pytest import xarray as xr import cf_xarray as cfxr from . import requires_shapely @pytest.fixture def geometry_ds(): from shapely.geometry import MultiPoint, Point # empty/fill workaround to avoid numpy deprecation(warning) due to the array interface of shapely geometries. ge...
Python
# generated from catkin/cmake/template/pkg.context.pc.in CATKIN_PACKAGE_PREFIX = "" PROJECT_PKG_CONFIG_INCLUDE_DIRS = "".split(';') if "" != "" else [] PROJECT_CATKIN_DEPENDS = "".replace(';', ' ') PKG_CONFIG_LIBRARIES_WITH_PREFIX = "".split(';') if "" != "" else [] PROJECT_NAME = "styx" PROJECT_SPACE_DIR = "/home/zche...
Python
#!/usr/bin/python3 # Helper script for the transactions method that can read the log file # and use it to detect and recover the state to one of the transactions # at which the script had previously been restarted. import sys import os import re import json import subprocess import codecs import argparse import temp...
Python
# # 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...
Python
import numpy as np np.random.seed(0) ADOPT = 0 OVERRIDE = 1 WAIT = 2 class Environment(object): def __init__(self, mining_powers, gammas, T): # relative mining strengths. self.mining_powers = mining_powers self.gammas = gammas self.num_miners = len(mining_powers) #...
Python
import unittest import textwrap from typing import Any, List from hstest.check_result import CheckResult from hstest.stage_test import StageTest from hstest.test_case import TestCase class FeedbackOnExceptionTest4(StageTest): def generate(self) -> List[TestCase]: return [ TestCase(feedback_o...
Python
from abc import ABC, abstractmethod from typing import Tuple, Dict from kloppy.infra.utils import Readable from kloppy.domain import Dataset class TrackingDataSerializer(ABC): @abstractmethod def deserialize( self, inputs: Dict[str, Readable], options: Dict = None ) -> Dataset: raise NotI...
Python
# -*- encoding: utf-8 -*- """ @Author : zYx.Tom @Contact : 526614962@qq.com @site : https://github.com/zhuyuanxiang/tensorflow_cookbook --------------------------- @Software : PyCharm @Project : TensorFlow_Machine_Learning_Cookbook @File : C0106_operations.py @Version : v0.1...
Python
from neo4j import GraphDatabase from argparse import ArgumentParser from concurrent.futures import ThreadPoolExecutor,as_completed,thread import sys import csv from time import time PRACTICAL = 'practical' LOGICAL = 'logical' NETONLY = 'netonly' ALL = 'all' PRIVS = 'privileged' rans = None def time_to_str(total_time)...
Python
from flask_restful import Resource from tasks import add class HelloResource(Resource): def get(self): add.delay(3, 5) return {"msg": "get ok"}
Python
""" Distance and Area objects to allow for sensible and convenient calculation and conversions. Here are some tests. """ import unittest from djmodels.contrib.gis.measure import A, Area, D, Distance class DistanceTest(unittest.TestCase): "Testing the Distance object" def testInit(self): "Testing in...
Python
# This is your project's main settings file that can be committed to your # repo. If you need to override a setting locally, use settings_local.py from funfactory.settings_base import * # Bundles is a dictionary of two dictionaries, css and js, which list css files # and js files that can be bundled together by the m...
Python
# Copyright 2015, Google, Inc. # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, s...
Python
#!/usr/bin/env python # Copyright (c) 2012 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """Entry point for both build and try bots. This script is invoked from XXX, usually without arguments to package an SDK. It autom...
Python
# Copyright (C) 2008 John Paulett (john -at- paulett.org) # Copyright (C) 2009-2018 David Aguilar (davvid -at- gmail.com) # All rights reserved. # # This software is licensed as described in the file COPYING, which # you should have received as part of this distribution. from __future__ import absolute_import, division...
Python
""" WSGI config for kubeoperator project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/2.1/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_...
Python
# Copyright (C) 2010-2011 Richard Lincoln # # 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, merge, publish...
Python
import math t = int(raw_input()) for i in range(t) : n = int(raw_input()) print math.factorial(n) '''Why using math.factorial() is faster? beacuse many of the Python libraries are in C or C++ and not it Python. Hence the speed improves.'''
Python
#!/usr/bin/python # # linearize-hashes.py: List blocks in a linear, no-fork version of the chain. # # Copyright (c) 2013 The Bitcoin developers # Distributed under the MIT/X11 software license, see the accompanying # file COPYING or http://www.opensource.org/licenses/mit-license.php. # import json import struct impor...
Python
#for fixture loading
Python
""" WSGI config for share_all project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SE...
Python
import random import pdb from torchvision.transforms import functional as F from utils.box_list import BoxList def resize(img_list, box_list=None, min_size=None, max_size=None): assert type(min_size) in (int, tuple), f'The type of min_size_train shoule be int or tuple, got {type(min_size)}.' if isinstance(min...
Python
# Copyright 2021 ETH Zurich, Media Technology Center # # 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...
Python
# Generated by Django 2.1.9 on 2020-03-20 00:50 import django.core.validators from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('cmsplugin_blocks', '0003_slideitem_title'), ] operations = [ migrations.AlterField( model_name='al...
Python
import pyasdf import numpy as np import scipy.fftpack import matplotlib.pyplot as plt ''' this script takes a chunk of noise spectrum for a station pair and compare their cross-correlation functions computed using two schemes: one is averaging the frequency domain and the other is in the time domain ''' def cross...
Python
__all__ = [ 'BaseClassificationAggregator', 'BaseImageSegmentationAggregator', 'BaseEmbeddingsAggregator', 'BaseTextsAggregator', 'BasePairwiseAggregator', ] import attr from .. import annotations @attr.s @annotations.manage_docstring class BaseClassificationAggregator: """ This is a base cla...
Python
import graphene import datetime import urllib import json from django.db import models from django.conf import settings from django.contrib.contenttypes.models import ContentType from django.core.signing import TimestampSigner from django.shortcuts import render from .registry import registry from .signals import pre...
Python
from .history.pyplot_history import pyplot_history from .history.plotly_history import plotly_history def plot_history(history, engine="pyplot", **kwargs): if engine == "pyplot": return pyplot_history(history, **kwargs) elif engine == "plotly": return plotly_history(history, **kwargs) else...
Python
__author__ = 'aakilomar' import requests, json, time from timeit import default_timer as timer requests.packages.urllib3.disable_warnings() host = "https://localhost:8443" def cancel_event(eventid): post_url = host + "/api/event/cancel/" + str(eventid) return requests.post(post_url,None, verify=False).json(...
Python
# -*- coding: utf-8 -*- """ solutions_by_text.sbt_token_generator ~~~~~~~~~~~~ This module handles security token generation. """ # @Author: sijanonly # @Date: 2018-03-19 10:57:26 # @Last Modified by: sijanonly # @Last Modified time: 2018-03-19 14:51:07 import json from urllib import parse import requests from...
Python
from simplecoremidi import send_midi from time import sleep def play_a_scale(): root_note = 60 # This is middle C channel = 1 # This is MIDI channel 1 note_on_action = 0x90 major_steps = [2, 2, 1, 2, 2, 2, 1, 0] velocity = 127 note = root_note for step in major_steps: send_midi((...
Python
# -*- coding: utf-8 -*- from __future__ import unicode_literals from . import __version__ as app_version app_name = "custom_scripts" app_title = "Custom Scripts" app_publisher = "C.R.I.O" app_description = "For custom scripts" app_icon = "octicon octicon-file-directory" app_color = "grey" app_email = "criogroups@gmail...
Python
import argparse import os, sys import os.path as osp import torchvision import numpy as np import torch import torch.nn as nn import torch.optim as optim from torchvision import transforms import network, loss from torch.utils.data import DataLoader import random, pdb, math, copy from tqdm import tqdm from scipy.spatia...
Python
from kafka import KafkaConsumer KAFKA_SERVER_URL = 'localhost:9092' LOGIN = "bob" PWD = "bob-secret" TOPIC = "test-topic" GROUP_ID = 'bob-group' consumer = KafkaConsumer(TOPIC, group_id=GROUP_ID, bootstrap_servers=KAFKA_SERVER_URL, security_protocol="SASL_PLAINTEXT", ...
Python
# a simple script to rename multiple files import os import re path = 'myimages/' files = os.listdir(path) files.sort(key=lambda var:[int(x) if x.isdigit() else x for x in re.findall(r'[^0-9]|[0-9]+', var)]) for i, file in enumerate(files): os.rename(path + file, path + "rename_{}".format(i)+".jpg") print('do...
Python
# # MythBox for XBMC - http://mythbox.googlecode.com # Copyright (C) 2011 analogue@yahoo.com # # 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 2 # of the License, or (at yo...
Python
import contextlib import logging from cStringIO import StringIO from teuthology import misc from teuthology.job_status import set_status from teuthology.orchestra import run log = logging.getLogger(__name__) @contextlib.contextmanager def syslog(ctx, config): """ start syslog / stop syslog on exit. ""...
Python
import os import logging import json from typing import Union, Dict, List from documentstore_migracao.utils.isis2json import isis2json logger = logging.getLogger(__name__) class OutputContainer: """Classe que mimetiza a escrita de arquivos para a escrita em uma estrutura de lista. Cada linha em um arquivo r...
Python
from setuptools import setup, find_packages from os import path here = path.abspath(path.dirname(__file__)) setup( name='nameko-couchbase', version='0.1.5', description='Nameko dependency for Couchbase', url='https://github.com/geoffjukes/nameko-couchbase', author='Geoff Jukes', license="Apach...
Python
# -*- coding: utf-8 -*- # Copyright 2020 Google LLC # # 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...
Python
import keras from keras.datasets import mnist # input image dimensions img_rows, img_cols = 28, 28 input_shape = (img_rows, img_cols, 1) num_classes = 10 def get_mnist_data(): # the data, shuffled and split between train and test sets (x_train, y_train), (x_test, y_test) = mnist.load_data() x_train = x_...
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
# -*- coding: utf-8 -*- # This Source Code Form is subject to the terms of the Mozilla Public # License, v. 2.0. If a copy of the MPL was not distributed with this # file, You can obtain one at http://mozilla.org/MPL/2.0/. from cli_common.log import get_logger logger = get_logger(__name__) WORKER_CHECKOUT = '/builds...
Python
# stdlib import json from typing import List from typing import NoReturn from typing import Optional # third party from fastapi import APIRouter from fastapi import Depends from fastapi import File from fastapi import Form from fastapi import UploadFile from loguru import logger from starlette import status from starl...
Python
# Copyright Contributors to the Pyro project. # SPDX-License-Identifier: Apache-2.0 import contextlib import funsor from funsor.adjoint import AdjointTape from pyro.contrib.funsor import to_data, to_funsor from pyro.contrib.funsor.handlers import enum, plate, replay, trace from pyro.contrib.funsor.infer.elbo import ...
Python
import torch import torch.nn.functional as F import argparse import cv2 import numpy as np from glob import glob import matplotlib.pyplot as plt num_classes = 2 img_height, img_width = 64, 64#572, 572 out_height, out_width = 64, 64#388, 388 GPU = False torch.manual_seed(0) class Mynet(torch.nn.Module): def __ini...
Python