content
stringlengths
0
894k
type
stringclasses
2 values
# Import the modules import sys import MinVel as mv import numpy as np # NOTES: May want to update temperature dependence of thermal expansivity using Holland and Powell's (2011) # new revised equations (see figure 1 in that article). This will necessitate recalculating the first # Gruneisen parameters...
python
import os import sys import cv2 import numpy as np from PyQt5.QtCore import pyqtSlot, QThreadPool, QTimer from PyQt5.QtWidgets import * from PyQt5 import QtCore from PyQt5.QtGui import * from src.transformers.Transformer import Transformer, getTransformer from src.util.UserInterface.ControlBox import ControlBox from ...
python
# 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...
python
"""Metrics to assess performance on sequence labeling task given prediction Functions named as ``*_score`` return a scalar value to maximize: the higher the better Reference: seqeval==0.0.19 """ from __future__ import absolute_import, division, print_function import warnings from collections import defaultdict impor...
python
from det3d.core.utils.scatter import scatter_mean from torch.nn import functional as F from ..registry import READERS from torch import nn import numpy as np import torch def voxelization(points, pc_range, voxel_size): keep = (points[:, 0] >= pc_range[0]) & (points[:, 0] <= pc_range[3]) & \ (points[:,...
python
from fjord.base.tests import eq_, TestCase from fjord.feedback.utils import clean_url, compute_grams class Testclean_url(TestCase): def test_basic(self): data = [ (None, None), ('', ''), ('http://example.com/', 'http://example.com/'), ('http://example.com/#f...
python
from typing import Optional from cdm.enums import CdmObjectType from cdm.objectmodel import CdmAttributeReference, CdmCorpusContext from .cdm_object_ref_persistence import CdmObjectRefPersistence class AttributeReferencePersistence(CdmObjectRefPersistence): @staticmethod def from_data(ctx: CdmCorpusContext,...
python
import pandas as pd IN_FILE = 'aus-domain-urls.txt' START_IDX = 0 BLOCK_SIZE = [10, 20, 50, 100, 1000, 100000, 1000000] OUT_FILE_PREFIX = 'aus-domain-urls' data = pd.read_csv(IN_FILE) data_length = len(data) for i in range(len(BLOCK_SIZE)): if i == 0: lower_bound = 0 else: lower_bound = upper_...
python
# Generated by Django 3.2.6 on 2021-10-19 10:58 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('dashboard', '0002_auto_20211019_1613'), ] operations = [ migrations.RemoveField( model_name='bookingrooms', name='ro...
python
from typing import Protocol class SupportsStr(Protocol): def __str__(self) -> str: ...
python
import os import tensorflow as tf from PIL import Image cwd = os.getcwd()+'/train/' for root, dirs, files in os.walk(cwd): print(dirs) # 当前路径下所有子目录 classes = dirs break print(cwd) writer = tf.python_io.TFRecordWriter("train.tfrecords") for index, name in enumerate(classes): class_path = cwd + name + ...
python
# -*- coding: utf-8 -*- # (c) Copyright IBM Corp. 2010, 2021. All Rights Reserved. # pragma pylint: disable=unused-argument, no-self-use """ Incident poller for a ProofPoint TRAP server """ import logging from resilient_circuits import ResilientComponent, handler from fn_scheduler.components import SECTION_SCHEDULER f...
python
import os import pandas as pd from bento.common import datautil, logger, util logging = logger.fancy_logger(__name__) def load_covid_raw_data(data_path, base, cases, deaths, nrows=None): read_args = {} if nrows: read_args["nrows"] = nrows idf = pd.read_csv(f"{data_path}/{base}/{cases}").drop(["La...
python
from tests.unit.dataactcore.factories.staging import DetachedAwardFinancialAssistanceFactory from tests.unit.dataactvalidator.utils import number_of_errors, query_columns _FILE = 'fabs18_detached_award_financial_assistance' def test_column_headers(database): expected_subset = {'row_number', 'business_types', 'un...
python
from rtm.api import validate def test_validate(rtm_path): validate(rtm_path)
python
from sqlalchemy import create_engine from td.client import TDClient from datetime import datetime from td import exceptions from requests.exceptions import ConnectionError import datetime import pandas as pd import sqlite3 import time import credentials print("- Modules imported -") def make_sqlite_table(table_name)...
python
import sys, os, subprocess, shutil, time BUILDDIR = os.path.abspath("build") NINJA_EXE = "ninja.exe" NINJA_BUILD_FILE = "build/build.ninja" CALL_PATH = os.getcwd() TOOL_PATH = sys.path[0] + "/" TOOLCHAIN_PATH = os.path.dirname(sys.path[0]) NO_EMOJI = False NO_COLOR = False SELECTION = None SECONDARY = None CMAKE_EX...
python
#!/usr/bin/python """ This plugin implements identifying the modbusRTU protocol for serial2pcap. Modbus RTU Frame Format: Name Length (bits) Function Start 28 At least 3.5 (28 bits) character times of silence Address 8 Function 8 Data n*8 CRC 16 End 28 At Least 3.5 (28 bits) charact...
python
import sys import DiveConstants as dc from rpy2.rinterface import NA from rpy2.robjects.vectors import IntVector, FloatVector, StrVector import rpy2.robjects.packages as rpackages import rpy2.robjects as robjects import numpy as np np.set_printoptions(suppress=True) utils = rpackages.importr('utils') scuba = rpackages....
python
from collections import Counter from random import randint from django.http import JsonResponse from django.shortcuts import render from django.views.generic import View, TemplateView from .models import Article, portals, languages from utils.utils import parse_a_website BENCHMARK_URL = 'https://www.benchmark.pl/' B...
python
'''utils and constants functions used by the selector and selectors class''' import re RE_ALPHA = re.compile(r'\w') SELECTOR_TYPE = {'XML': 'xml', 'TRXML': 'trxml'} TRXML_SELECTOR_TYPE = {'SINGLETON': 'singleton', 'MULTIPLE': 'multiple'} def valid_field_name(tag_name: str = '') -> bool: ''' simple validatio...
python
import matplotlib.pyplot as plt import random import numpy as np import cv2 def visualize(img, det_boxes=None, gt_boxes=None, keypoints=None, is_show_label=True, show_cls_label = True, show_skeleton_labels=False, classes=None, thresh=0.5, name='detection', return_img=False): if is_show_label: if classes ==...
python
import webbrowser class RomanNumeralCipher: def __init__(self): ''' This is a python implementation of Roman Numeral Cipher''' self.val = [ 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1 ] self.syb = [ "M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"...
python
import json import disnake as discord from disnake.ext import commands class Active_Check(commands.Cog): def __init__(self, bot): self.bot = bot @commands.command() async def activate(self, ctx, cog=None): with open('utils/json/active_check.json', 'r') as f: data = json.load(f...
python
import sys sys.path.append("../common/tests") from test_utils import * import test_common sys.path.insert(0, '../../../../build/production/config/schema-transformer/') from vnc_api.vnc_api import * import uuid class STTestCase(test_common.TestCase): def setUp(self): super(STTestCase, self).setUp() ...
python
from django.contrib import admin from unecorn.models import * admin.site.register(Discount) admin.site.register(Category) admin.site.register(Company)
python
from keras.models import Sequential, model_from_json from keras.layers.core import Dense, Activation, Flatten, Dropout, Lambda from keras.layers import Cropping2D from keras.layers.convolutional import Conv2D from keras.layers.pooling import MaxPooling2D from keras.layers.advanced_activations import ELU from keras.opti...
python
#!/usr/bin/env python import logging from p4p.client.thread import Context _log = logging.getLogger(__name__) def getargs(): from argparse import ArgumentParser P = ArgumentParser() P.add_argument('pvname', help='SIGS pvname (eg. RX:SIG') P.add_argument('filename', help='list of BSA/signal PV names....
python
#!/usr/bin/env python # coding: utf-8 import rospy import tf from geometry_msgs.msg import PoseStamped from sensor_msgs.msg import JointState from std_msgs.msg import Float64 import numpy as np class Pose_pub: def __init__(self): self._sub_pos = rospy.Subscriber("/head", PoseStamped, self.pose_callback) ...
python
""" 语言概念与机制 http://coolpython.net/python_interview/basic/py_concept_mechanism.html """ # 01 谈下GIL 全局解释器锁 # 02 遍历文件夹,输出文件夹下所有文件的路径 import os def print_directory_contents(path): test02_dirList = os.listdir(path) for childfile in test02_dirList: childPath = os.path.join(path, childfile) # 判断为文件夹...
python
import gzip import jsonpickle from mdrsl.rule_models.eids.st_to_mt_model_merging import MergedSTMIDSClassifier def store_merged_st_mids_model(merged_model_abs_file_name: str, merged_st_mids_classifier: MergedSTMIDSClassifier) -> None: frozen = jsonpickle.encode(merged_st_mids_classifier) with gzip.open(merg...
python
#https://www.youtube.com/watch?v=2egPL5KFCC8&list=PLGKQkV4guDKEKZXAyeLQZjE6fulXHW11y&index=2 #java scrip cannot be pull by beautifulsoap, java scrip use sileniun #resultdo 0 para atributo existentem, vem exemplo imagem como pegar import requests from bs4 import BeautifulSoup url = "https://www.marketwatch.com/" respons...
python
# coding: utf-8 """ jatdb JSON API to DB: Fetch JSON from APIs and send to a TinyDB database. # noqa: E501 OpenAPI spec version: 0.0.2 Contact: Nathan@Genetzky.us Generated by: https://github.com/swagger-api/swagger-codegen.git """ from __future__ import absolute_import import unittest impor...
python
import json import os import sys import re import pickle import logging import gzip import shutil import urllib.request from tqdm import tqdm from collections import defaultdict from utils.data_utils import load_jsonl_file, create_pkl_file, load_pkl_file module_path = os.path.dirname(os.path.abspath(__file__)) # ---...
python
KEYWORDS = ["dev", "backup", "develop", "int", "internal", "staging", "test"] with open("../../roots.txt") as roots: with open("targets.txt", "w+") as targets: for domain in roots: for keyword in KEYWORDS: target = domain.strip("\n") + "-" + keyword.strip("\n") + ".oss.eu-west-1....
python
# -*- coding: utf-8 -*- """ Module docstring TODO: * Write module docstring """ from .player.dealer import Dealer from .player.player import Player from .carddeck.deck import Deck class Game(): """Class to represent the blackjack Game""" def __init__(self): self.dealer = Dealer() self.pl...
python
from flask_pymongo import PyMongo from flask_compress import Compress from flask_cors import CORS from flask_bcrypt import Bcrypt from itsdangerous import URLSafeTimedSerializer mongo = PyMongo() flask_bcrypt = Bcrypt() flask_compress = Compress() flask_cors = CORS(resources={"/api/*": {"origins": "*"}}) RECAPTCHA_SI...
python
# # Jasy - Web Tooling Framework # Copyright 2013-2014 Sebastian Werner # import json import copy class AbstractNode(list): __slots__ = [ # core data "line", "type", "tokenizer", "start", "end", "rel", "parent", # dynamic added data by other modules "comments", "scope", "values"...
python
from useless import base from useless.base import * class Resolver(CMakePackage): def __init__(self): super().__init__() self.name = 'openvdb' self.depends(require('openexr')) self.depends(require('tbb')) self.depends(require('boost')) self.set('USE_BLOSC','OFF') ...
python
# -*- coding: utf-8 -*- """ Diffraction image analysis """ from .alignment import ( align, ialign, shift_image, itrack_peak, masked_register_translation, ) from .calibration import powder_calq from .correlation import mnxc, xcorr from .metrics import ( snr_from_collection, isnr, mask_fr...
python
class AbstractObject(object): def __init__(self): pass def get_class(self, universe): raise NotImplementedError("Subclasses need to implement get_class(universe).") def get_object_layout(self, universe): raise NotImplementedError( "Subclasses need to implement get_objec...
python
""" Tests for Galaxy Queue Worker """
python
from io import BytesIO import json import cgi from pathlib import Path from abeja.common.docker_image_name import DockerImageName, ALL_GPU_19_04, ALL_CPU_19_10 from abeja.training import JobDefinition, JobDefinitionVersion # noqa: F401 def test_job_definition_version( requests_mock, api_base_url, ...
python
""" Import as: import dataflow.core.dag_adapter as dtfcodaada """ import logging from typing import Any, Dict, List import core.config as cconfig import dataflow.core.builders as dtfcorbuil import dataflow.core.dag as dtfcordag import dataflow.core.node as dtfcornode import helpers.hdbg as hdbg import helpers.hprint...
python
from distutils.core import setup setup(name='DefenseLab', version='1.0', author='Andrew Meserole', packages=['DefenseLab', ])
python
#!/usr/bin/python #_*_coding:utf-8_*_ import sys # Point类 class Point: lng = '' lat = '' def __init__(self,lng,lat): self.lng = lng self.lat = lat def show(self): print self.lng,"\t",self.lat #采用射线法判断点是否在多边形集内 def isPointsInPolygons(point,xyset): ...
python
from . import utils from discord.utils import get async def update_admins(guild, bot_log): role_admin = get(guild.roles, name='Админ') role_past_admin = get(guild.roles, name='Бивш Админ') for admin in utils.get_members_with_role(guild, role_admin): await bot_log.send(f'{admin.mention}') ...
python
from statistics import multimode def migratoryBirds(arr): mode = multimode(arr) mode.sort() return mode[0] if __name__ == "__main__": arr = [1 ,2 ,3 ,4 ,5 ,4 ,3 ,2 ,1 ,3 ,4] print(migratoryBirds(arr))
python
'''Test configuration constants, functions ... ''' import subprocess import os import unittest TVM_ROOT_PART='may not need' TVM_SWAP_PART='may not need' TVM_HOSTNAME='cworld.local' TVM_GITREPO_URL = 'git@cworld.local' def product_topdir(): '''return the project's top level directory (according to git) ''' ...
python
import pytest from core import helpers @pytest.mark.parametrize('path,expected_prefix', ( ('/', 'en-gb'), ('/ar/', 'ar'), ('/es/industries/', 'es'), ('/zh-hans/industries/', 'zh-hans'), ('/de/industries/aerospace/', 'de'), ('/fr/industries/free-foods/', 'fr'), )) def test_get_language_from_pr...
python
from os import path, environ from imgaug import augmenters as iaa from keras import backend as K from keras import optimizers from keras.callbacks import ModelCheckpoint, ReduceLROnPlateau from keras.layers import BatchNormalization, Activation from keras.layers import Input, Conv2D, MaxPooling2D, GlobalAveragePooling...
python
# mb, 2012-05-26, 2013-02-28 import os import sys import subprocess import shutil from datetime import datetime ospj = os.path.join dest_path_to_extensions = '/home/mbless/public_html/TYPO3/extensions' tempdir = '/home/mbless/HTDOCS/render-ter-extensions/temp' proceeding = True stats = {} def walk_ter_extensions_...
python
def test(i): print("test", i) def add_test(mf): def add_test_print(i): print("added to test", i) mf.register_event("test", add_test_print, unique=False) def main(event): event.test(0) event.add_test() event.test(1) def register(mf): mf.register_event("test", test, unique=False...
python
""" Entendendo Interadores e Iteraveis #Interador - Um objeto que poder ser iterado - Um objeto que retorna um dado, sendo um elemento por vez quando uma função next() é chamada; #Interaveis - Um objeto que irá retorna um interator quando inter() for chamada. """
python
from infosystem.common.subsystem import router class Router(router.Router): def __init__(self, collection, routes=[]): super().__init__(collection, routes) @property def routes(self): # TODO(samueldmq): is this the best way to re-write the defaults to # only change bypass=true fo...
python
from ubikagent import Project from ubikagent.introspection import get_methods class DummyAgent: """Test class needed by `InstantiableProject` and `TestProject`.""" pass class NonInstantiableProject(Project): """Test class needed by `TestProject`.""" pass class InstantiableProject(Project): """...
python
# coding:utf-8 import threading import redlock class Locker(object): def __init__(self,resource,ttl=0,servers=[{"host": "localhost", "port": 6379, "db": 0}, ]): self.servers = servers self.resource = resource self.ttl = ttl self.dlm = None self.r = None def lock(self...
python
#!/usr/bin/env python # Copyright 2020 MaaT Pharma # # 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 a...
python
import logging from io import BytesIO from datetime import datetime, timezone from kermes_infra.mail import MailService from kermes_infra.repositories import FileRepository, UserRepository, EBookRepository from kermes_infra.queues import SQSConsumer from kermes_infra.messages import DeliverEBookMessage, CleanUpMessag...
python
# values_from_literature.py (flowsa) # !/usr/bin/env python3 # coding=utf-8 """ Values from the literature used for data allocation are specified here and can be called on using functions. """ import pandas as pd import numpy as np from flowsa.common import datapath def get_US_urban_green_space_and_public_parks_rati...
python
""" sentry.plugins.base.v2 ~~~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2010-2013 by the Sentry Team, see AUTHORS for more details. :license: BSD, see LICENSE for more details. """ from __future__ import absolute_import, print_function __all__ = ('Plugin2',) import logging from django.http import HttpResponseRedirect fro...
python
# Copyright (C) 2019 Analog Devices, Inc. # # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # - Redistributions of source code must retain the above copyright # notice, this list of cond...
python
# Dindo Bot # Copyright (c) 2018 - 2019 AXeL from lib.shared import LogType, DebugLevel from lib import tools, parser from .job import JobThread class BotThread(JobThread): def __init__(self, parent, game_location, start_from_step, repeat_path, account_id, disconnect_after): JobThread.__init__(self, parent, game_...
python
class ForeignCountry: def __init__(self, code): self.code = code self.name = "Paese Estero"
python
import json import pytest from tests.unit.resources import searched_observable from trustar2.models.searched_observable import SearchedObservable from trustar2.trustar_enums import ObservableTypes VALUE = "2.2.2.2" TYPE = ObservableTypes.IP4.value FIRST_SEEN = 1623273177255 LAST_SEEN = 1623701072520 ENCLAVE_GUIDS = ...
python
#!/usr/bin/env python # BSD 3-Clause License; see https://github.com/scikit-hep/uproot3/blob/master/LICENSE
python
import ipywidgets as widgets a = widgets.IntText(description='Value A') b = widgets.IntSlider(description='Value B') vbox = widgets.VBox(children=[a, b]) vbox
python
""" Char. number range | UTF-8 octet sequence (hexadecimal) | (binary) --------------------+--------------------------------------------- 0000 0000-0000 007F | 0xxxxxxx 0000 0080-0000 07FF | 110xxxxx 10xxxxxx 0000 0800-0000 FFFF | 1110xxxx 10xxxxxx 10xxxxxx 0001 0000-0010...
python
from fastapi import FastAPI, status from pydantic import BaseModel, ValidationError from requests_html import HTMLSession from starlette.middleware.cors import CORSMiddleware from starlette.responses import JSONResponse session = HTMLSession() app = FastAPI( title="corona virus real time data", description=""...
python
#! /usr/bin/env python3 from typing import Dict, List, Tuple import graphics import day24 from utils import get_file_lines class Hexagon(graphics.Polygon): def __init__(self, x, y, length): delta_x = (1, 0.5, -0.5, -1, -0.5, 0.5) delta_y = (0, -0.86602540378443864676372317075294, -0.8660254037...
python
# TODO # class MeanAbsoluteError(): # def __init__(self): pass # TODO # class MeanBiasError(): # def __init__(self): pass # TODO # class ClassificationLosses(): # def __init__(self): pass # TODO # class Elbow(): # def __init__(self): pass # TODO # class EuclideanDistance(): # def __init__(self)...
python
## @packege zeus_security_py # Helper package for data security that will implement zeus microservices # # from Cryptodome.Cipher import AES from Cryptodome import Random from hashlib import sha256 import base64 import os import json __author__ = "Noé Cruz | contactozurckz@gmail.com" __copyright__ = "Copyright 2007...
python
# Copyright 2022 MosaicML Composer authors # SPDX-License-Identifier: Apache-2.0 """Helper function to generate the README table.""" import json import os from pathlib import Path import utils import composer from composer import functional as CF EXCLUDE_METHODS = ['no_op_model', 'utils'] HEADER = ['Name', 'Functi...
python
# -*- coding: utf-8 -*- """IdentityServicesEngineAPI network_access_time_date_conditions API fixtures and tests. Copyright (c) 2021 Cisco and/or its affiliates. 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...
python
"""Run calcsfh or hybridMC in Parallel (using subprocess)""" import argparse import logging import os import subprocess import sys from glob import glob1 import numpy as np logging.basicConfig(level=logging.DEBUG) logger = logging.getLogger(__name__) # Could be in a config or environ calcsfh = '$HOME/research/match2...
python
import os import pickle import sys import time import logging from watchdog.observers import Observer from watchdog.events import LoggingEventHandler, FileCreatedEvent, FileDeletedEvent, FileModifiedEvent, FileMovedEvent, \ DirCreatedEvent, DirDeletedEvent, DirModifiedEvent, DirMovedEvent from watchdog.utils.dirsna...
python
# -*- coding: utf-8 -*- # ----------------------------------------------------------------------------- # Copyright © Spyder Project Contributors # # Licensed under the terms of the MIT License # (see spyder/__init__.py for details) # ----------------------------------------------------------------------------- """ Te...
python
from discord.ext.alternatives import silent_delete from bot import Bot Bot().run()
python
import distutils.command.build import setuptools.command.egg_info from setuptools import setup, Extension, find_packages from Cython.Build import cythonize import os def get_build_dir(default): return os.environ.get('STFPY_BUILD_DIR', default) # Override egg command class EggCommand(setuptools.command.egg_info.eg...
python
from geolocalizador import * endereco = u'Universidade de Sao Paulo, Instituto de Matematica e Estatastica, Departamento de Ciencia da Computacao. Rua do Matao 1010 Cidade Universitaria 05508090 - Sao Paulo, SP - Brasil Telefone: (11) 30916135 Ramal: 6235 Fax: (11) 30916134 URL da Homepage: http://www.ime.usp.br/~cesa...
python
# Copyright (c) 2013 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. import sys from telemetry import test from measurements import image_decoding class ImageDecodingToughImageCases(test.Test): test = image_decoding....
python
from .hook_group import HookGroup class Event(HookGroup): def __init__(self, event=None, hooks=None, config=None): self.type = event super().__init__(hooks=hooks, config=config)
python
# ------------------------------------------------- # Data Types for Data Science in Python - Handling Dates and Times # 24 set 2020 # VNTBJR # ------------------------------------------------ # # Load packages reticulate::repl_python() # Load data import csv csvfile2 = open("Datasets/cta_summary.csv", mode = 'r') da...
python
import requests import folium import geocoder import string import os import json from functools import wraps, update_wrapper from datetime import datetime from pathlib import Path from flask_bootstrap import Bootstrap from flask_nav import Nav from flask_nav.elements import * from dominate.tags import img from edibl...
python
from django.db.models.signals import pre_save, post_save from django.dispatch import receiver from asset_events.models import StatusChangingEvent @receiver(post_save) def update_asset_status(sender, instance, **kwargs): if not issubclass(sender, StatusChangingEvent): return sender.post_save(instance...
python
# -*- coding: utf-8 -*- # Generated by Django 1.10 on 2018-06-05 08:38 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('yaksh', '0015_auto_20180601_1215'), ] operations = [ migrations.AlterField( ...
python
# Generated by Django 3.0.5 on 2020-12-11 07:03 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('content_api', '0002_auto_20201002_1228'), ] operations = [ migrations.AlterModelOptions( name='...
python
# 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 # distributed u...
python
# Copyright (C) 2013 Claudio "nex" Guarnieri (@botherder) # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This pro...
python
# -*- coding: utf-8 -*- from calendar import timegm from collections import defaultdict from datetime import datetime from importlib import import_module from os import path as op import re from pkg_resources import DistributionNotFound, iter_entry_points, load_entry_point from pygments import highlight from pygments...
python
import asyncio from xwing.socket.server import Server BACKEND_ADDRESS = '/var/tmp/xwing.socket' async def start_server(loop): server = Server(loop, BACKEND_ADDRESS, 'server0') await server.listen() conn = await server.accept() while True: data = await conn.recv() if not data: ...
python
import sys import json if len(sys.argv) < 2: print('uso: python tag_input.py <arquivo>') exit(-1) arquivo_entrada = open(sys.argv[1], 'r', encoding='utf8') fluxo = json.load(arquivo_entrada) arquivo_entrada.close() for bloco in fluxo: for action_moment in ['$enteringCustomActions', '$leavingCustomAction...
python
# coding=utf-8 from setuptools import setup, find_packages setup( name="wsgi-listenme", description="WSGI middleware for capture and browse requests and responses", version='1.0', author='Mario César Señoranis Ayala', author_email='mariocesar.c50@gmail.com', url='https://github.com/humanzilla...
python
name=("Rayne","Coder","Progammer","Enginner","VScode") (man,*item,software)=name print(man) #*item container for all value that not contain by man and software print(item) print(software)
python
import unittest from unittest import mock from .. import surface class TestEllipsoidDem(unittest.TestCase): def test_height(self): test_dem = surface.EllipsoidDem(3396190, 3376200) self.assertEqual(test_dem.get_height(0, 0), 0) self.assertEqual(test_dem.get_height(0, 180), 0) sel...
python
# ==正規表現によるスクレイピング== import re from html import unescape # プロジェクト配下にダウンロードしたhtmlファイルを開き、レスポンスボディを変数に格納。 with open('../sample.scraping-book.com/dp.html') as f: html = f.read() # findallを使って書籍一冊分のhtml情報を取得する # re.DOTALL => 改行も含むすべての文字にマッチ for partial_html in re.findall(r'<a itemprop="url".*?</ul>\s*</a></li>', htm...
python
""" 735. Asteroid Collision Medium We are given an array asteroids of integers representing asteroids in a row. For each asteroid, the absolute value represents its size, and the sign represents its direction (positive meaning right, negative meaning left). Each asteroid moves at the same speed. Find out the state ...
python
import torch import time class AverageMeter(object): """Computes and stores the average and current value""" def __init__(self, name, fmt=':f'): self.name = name self.fmt = fmt self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 sel...
python
from time import time from json import dumps, loads from redis import StrictRedis, ConnectionPool, WatchError from PyYADL.distributed_lock import AbstractDistributedLock class RedisLock(AbstractDistributedLock): def __init__(self, name, prefix=None, ttl=-1, existing_connection_pool=None, redis_host='localhost', ...
python
from .elbo import ELBO __all__ = [ 'ELBO' ]
python