content stringlengths 5 1.05M |
|---|
#Napisz kod generujący 2 liczby i spytaj użytkownika o ich różnicę
# W przypadku powodzenia wyświetl komunikat
import random
from zipfile import *
def losowe():
a = random.randint(1,100)
print("1 Wysolowana liczba:", a)
b= random.randint(1,100)
print("2 Wylosowana liczba:", b)
liczba =int (input("P... |
#!/usr/bin/python3
"""
Required: Python 3.6 +
This program validates any given United States phone number.
"""
# print(__doc__)
import re
def validate_phone_number(phone_number):
"""
Validates a US phone number based on a complex regular expression.
"""
# print(validate_phone_number.__doc__)
phone_number... |
#!/usr/bin/env python
from __future__ import division
from argparse import ArgumentParser
import sys
from re import sub
from multiprocessing import Pool
try:
from itertools import izip as zip
except ImportError:
pass
def argypargy():
parser = ArgumentParser(description='TransloCapture -1 in... |
"""
Test to confirm that the sum wel and wel-reduced observations is equal
to the specified well pumping rate when the AUTO_FLOW_REDUCE option is
specified.
"""
import os
import pytest
import numpy as np
try:
import pymake
except:
msg = "Error. Pymake package is not available.\n"
msg += "Try installing usi... |
import json
def load():
with open('color.json', 'r') as f:
color = json.load(f)
return color
def yellow():
return load['yellow']
def brown():
return load()['brown']
def green():
return load()['green'] |
# -*- coding: utf-8 -*-
"""
Simple Smoke Tests for Connected Proxy Minion
"""
from __future__ import absolute_import, print_function, unicode_literals
from tests.support.case import ModuleCase
from tests.support.helpers import slowTest
class ProxyMinionSimpleTestCase(ModuleCase):
"""
Test proxy minion functi... |
# I wanted to try making some classes as practice.
RUNNING = True
RESTING = False
class Reindeer:
def __init__(self, line):
"""
:param line: Parses line into the class.
:return: nothing
"""
line = line.split()
self.speed = int(line[3])
self.running_time = ... |
#!/usr/bin/env python3
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from models import Shelf, Book
import sqlite3
def construct_shelves(url):
driver = webdriver.Firefox()
driver.get(url)
shelfContainer = driver.find_elements_by_class_name("userShowPageShelfListIte... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: valengo
"""
from typing import Union
class Disk(object):
"""
This class holds information related to 'cat /sys/block/sda/stat'
"""
def __init__(self):
self.start = None
self.end = None
self.attr = ['read_ios', 'read_... |
#
# All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
# its licensors.
#
# For complete copyright and license terms please see the LICENSE at the root of this
# distribution (the "License"). All use of this software is governed by the License,
# or, if provided, by the license below or th... |
from typing import List
# O(mlogn)
class Solution:
def search(self, arr, target):
l, r = 0, len(arr)
while l <= r:
m = (l + r) // 2
if arr[m] == target:
return True
elif arr[m] <= target:
l = m + 1
else:
... |
import cv2
from PIL import Image
import time
char = [' ', '.', ':', '-', '=', '+', '#', '%', '@']
def ascii(img, width=-1):
img = img.resize((int(img.size[0]), int(img.size[1] * (7/11))))
if width != -1:
ratio = width / img.size[0]
img = img.resize((int(img.size[0]*ratio), int(img.size[1]*rati... |
"""Tests for disco_config."""
import unittest
import logging
import mock
import netsnmp
from mlab.disco import discovery
from mlab.disco import models
import disco_config
@mock.patch.object(netsnmp, 'Session')
@mock.patch.object(discovery, 'DiscoverySession')
class UpdateSNMPCommunityTest(unittest.TestCase):
... |
__________________________________________________________________________________________________
sample 24 ms submission
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def levelOrder... |
class SinglyLinkedListNode: #class SinglyLinkedListNode has a data variable and a pointer to the next node
def __init__(self, data):
self.data = data
self.next = None
def print_with_head(head) : #helper functioin to print the elements of the list
temp = head
while temp is not None :
... |
# -*- coding: utf-8 -*-
############################################################################
#
# Copyright © 2013, 2015 OnlineGroups.net and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany th... |
from distutils.core import setup
setup(name = "config",
description="A hierarchical, easy-to-use, powerful configuration module for Python",
long_description = """This module allows a hierarchical configuration scheme with support for mappings
and sequences, cross-references between one part of the configuration... |
def compare_peer_dids(did_a, did_b):
prefix_a = did_a[:12]
prefix_b = did_b[:12]
# Compare the prefix case-sensitively.
n = -1 if prefix_a < prefix_b else (1 if prefix_a > prefix_b else 0)
if n == 0:
# Don't use .localeCompare() or .toLocaleLowerCase();
# we want raw ASCII comparison... |
# Copyright (c) 2011 BSD, Roger Lew [see LICENSE.txt]
# This software is funded in part by NIH Grant P20 RR016454.
"""generates q-values using qsturng, and tests to make psturng finds
the right p-value"""
import math
import time
import numpy as np
import pylab
from qsturng import qsturng, psturng, v_keys
... |
# ----------------------------------------------------------------------------
# Copyright (c) 2021, QIIME 2 development team.
#
# Distributed under the terms of the Modified BSD License.
#
# The full license is in the file LICENSE, distributed with this software.
# -----------------------------------------------------... |
import itertools
import json
import os
import re
import time
from collections import namedtuple
from functools import reduce
from json import JSONDecodeError
from typing import *
from .utils.extra_typings import *
from .utils.freeze import *
from .utils.delazify import disable_lazy_feature
try:
profile
except Nam... |
"""
==========================
Experiment GUI: Master GUI
==========================
"""
import sys
import os
from hyperion import logging
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import traceback
import yaml
from hyperion.tools.loading import get_class
import pyqtgraph as p... |
"""Test convbot."""
# import asyncio
import pytest
from convbot import __version__
from convbot import convbot, aconvbot
pytestmark = pytest.mark.asyncio
def test_version():
"""Test version."""
assert __version__[:3] == "0.1"
def test_sanity():
"""Sanity check."""
try:
assert not convbot("... |
import logging
logging.basicConfig(filename="secret.log",level=logging.DEBUG, format="%(asctime)s:%(levelname)s:%(message)s")
def add(x,y):
return x+y
def sub(x,y):
return x-y
def mul(x,y):
return x*y
def div(x,y):
return x/y
a=20
b=2
add_result=add(a,b)
logging.debug("add")
sub_result=sub(a,b)
... |
from django.contrib import admin
from .models import TextFilter, TextFormat
class FilterInline(admin.TabularInline):
model = TextFilter
ordering = ('sort',)
extra = 1
class FormatAdmin(admin.ModelAdmin):
inlines = [FilterInline]
prepopulated_fields = {
'slug': ('name',),
}
admin.si... |
import torch as tr
from torch.autograd import Variable
import torch.nn as nn
from torch import autograd
from utils import *
import os
import numpy as np
class Prior(object):
def __init__(self, dtype,device, name = 'prior'):
self.name = name
self.type = 'euclidian'
self.dtype = dtype
self.device = device
d... |
def p_a():
d = int(input())
print("Christmas" + " Eve" * (25 - d))
def p_b():
n = int(input())
ans = []
for _ in range(n):
ans.append(int(input()))
print(sum(ans) - max(ans) + max(ans) // 2)
def p_c():
n, k = map(int, input().split())
H = [int(input()) for _ in range(n)]
... |
import json
from json import JSONEncoder
import datetime as dt
import time
from pubsubClient import PubSubClient
STATS_TIME_FRAME = 1 # seconds
STATS_TOPIC = "SYSTEM_STATS"
class ThroughputStat():
def __init__(self, start, end, msg_count, topic) -> None:
self.topic = topic
self.start_time = start... |
import os
import sys
import platform
print("Detecting OS type...")
pf=platform.system()
if pf == 'Windows':
print("OS : Windows")
print("Now installing...")
os.system("install/install.bat")
print("Please use Windows Subsystem Linux(WSL) ")
print("Successfully Installed!!")
elif pf == "Darwin":
... |
"""File containing tests of pyrex antenna module"""
import pytest
from pyrex.antenna import Antenna, DipoleAntenna
from pyrex.signals import Signal
from pyrex.ice_model import IceModel
import numpy as np
@pytest.fixture
def antenna():
"""Fixture for forming basic Antenna object"""
return Antenna(position=... |
# UI Style Lang Copyright (c) 2020 Noah Rahm, Correct Syntax.
# Redistribution and use in source and binary forms, with or without modification,
# are permitted provided that the following conditions are met:
# 1. Redistributions of source code must retain the above copyright notice,
# this list of condit... |
# Sample script for use by test_gdb.py
def foo(a, b, c):
bar(a, b, c)
def bar(a, b, c):
baz(a, b, c)
def baz(*args):
id(42)
foo(1, 2, 3)
|
import pymnet as net
import numpy as np
import warnings
from utilities import debug
class GraphBuilder:
"""
This class is used to create the multilayer graph. pymnet used as module
"""
def __init__(self, objects, baseLayerName):
"""
Construct new `GraphBuilder` object. The attribute of an object... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
import os
import torch
from data.queues import UserEpisodicDatasetQueue, ObjectEpisodicDatasetQueue
class DataLoader():
def __init__(self, dataset_info):
self.train_queue = None
self.validation_queue = None
self.test_... |
#!/usr/bin/env python3
from pandas.core.frame import DataFrame
import requests
from bs4 import BeautifulSoup, element
import json
from pprint import pprint
import pandas as pd
from colorama import Fore, Back, Style
import requests_cache
requests_cache.install_cache('cache')
url = "https://web.archive.org/web/202110... |
def insert_sort(elements):
"""
Use the simple insertion sort algorithm to sort the :param elements.
:param elements: a sequence in which the function __get_item__ and __len__ were implemented
:return: the sorted elements in increasing order
"""
if not len(elements) or len(elements) == 1:
... |
from os import path
from dbt_airflow_factory.airflow_dag_factory import AirflowDagFactory
from dbt_airflow_factory.operator import EphemeralOperator
from tests.utils import task_group_prefix_builder, test_dag
def _get_ephemeral_name(model_name: str) -> str:
return f"{model_name}__ephemeral"
def test_ephemeral_... |
#!/usr/bin/env python
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-x", type=float, default=0.0)
args = parser.parse_args()
def main():
# Read parameters
x = args.x
# Compute or learning
y = x * x - 2 * x + 1
print("Formula: {}, input: {}, output: {}".format("y = x * x - 2 * x ... |
# Only waits. For plotting purposes
import numpy as np
from numpy.random.mtrand import RandomState
from ..envs.configuration import Configuration
from ..envs.env_garden import env_args as garden_env_1_args
from .abstract import Agent
class WaitAgent(Agent):
def __init__(self, config):
# Set number of p... |
# Python Imports
import uuid
from django.core.mail import send_mail
from django.conf import settings
from django.contrib.auth.models import AbstractBaseUser
from django.contrib.auth.models import PermissionsMixin
# Django Imports
from django.db import models
from django.db.models.signals import post_save
from django.di... |
__author__ = 'Steven Ogdahl'
from django.db.models import signals
from django.utils.functional import curry
from django.utils.decorators import decorator_from_middleware
from registration import FieldRegistry
class CurrentUserMiddleware(object):
def process_request(self, request):
if request.method in [... |
# -*- coding: utf-8 -*-
from __future__ import division, print_function, unicode_literals
from .helpers import ReaderError, SUPPRESS
from .py23compat import py23_str, py23_basestring
class _KeyLevel(object):
"""An abstract base class that provides functionality essential
for a key"""
def __init__(self,... |
# !/usr/local/python/bin/python
# -*- coding: utf-8 -*-
# (C) Wu Dong, 2019
# All rights reserved
# @Author: 'Wu Dong <wudong@eastwu.cn>'
# @Time: '2020-03-17 15:34'
from pre_request.exception import ParamsValueError
from pre_request.filters.base import BaseFilter
class EmptyFilter(BaseFilter):
"""
判断参数是否为空的过... |
import os
import numpy as np
import pytest
import tempfile
import fitsio
from meds.bounds import Bounds
from .._se_image import SEImageSlice
from .._constants import MAGZP_REF
from ...memmappednoise import MemMappedNoiseImage
@pytest.mark.skipif(
os.environ.get('TEST_DESDATA', None) is None,
reason=(
... |
import sys
def find_segments(starts, ends, points):
l={}
for i,j in zip(starts,ends):
for p in points:
if p >= i and p <= j:
# print(i,j,p)
l[p] = 1
points.remove(p)
# l.append(1)
else:
l[p] = 0
... |
# coding=utf-8
# Copyright 2022 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... |
#!/usr/bin/python3
# Main.py - Entrypoint for app
# Author: ItsOiK
# Date: 14/07-2021
import multiprocessing
import requests
import os
import sys
import time
import datetime as dt
from typing import Iterable
from sanic import Sanic
from sanic.response import json, text
from loguru import logger
from threading impor... |
def callmigrate():
import os
os.system("python manage.py migrate")
|
import os
import os.path
import numpy as np
import subprocess
from subprocess import call
from multiprocessing import Pool
### read_metadata
def read_metadata(filename,dtype_used):
import numpy as np
data=open(filename,'r')
data0=[]
for records in data:
tmp = [x.strip() for x in records.split('\t')]
if len(tmp... |
import xml.etree.ElementTree as ET
import numpy as np
import pandas as pd
import scipy.io as sio
import sys
import warnings
from pathlib import Path
debug_print = False
class pyMCDS:
"""
This class contains a dictionary of dictionaries that contains all of the
output from a single time step of a PhysiCel... |
from __future__ import unicode_literals
from datetime import date, datetime, timedelta
from django.db import models
from django.core.mail import send_mail
from django.contrib.auth.base_user import BaseUserManager
from django.contrib.auth.models import PermissionsMixin
from django.contrib.auth.base_user import AbstractB... |
import glob, json, collections, re, zipfile
import os, configparser, tarfile
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QStandardItemModel, QStandardItem, QFont
import Config
import ConfigViewerUi
from PyQt5.QtWidgets import QWidget, QStyle
class Widget(QWidget):
def __init__(self, config:str):
... |
#
# This is the Robotics Language compiler
#
# test_ros_message.py: Unit testing file
#
# Created on: 08 February, 2019
# Author: Gabriel Lopes
# Licence: license
# Copyright: copyright
#
import unittest
from RoboticsLanguage.Inputs.ROSMessage import Parse
class TestROSMessage(unittest.TestCase):
... |
def add(x, y):
return x + y
def test_add__when_1_and_2__expect_3():
# arrange
expected = 3
# act
actual = add(1, 2)
# assert
if actual == expected:
print('Ok')
else:
print('Wrong')
def test_add__when_2_and_1__expect_3():
expected = 3
actual = add(2, 1)
i... |
# -*- coding: utf-8 -*-
#
# This file is part of Invenio.
# Copyright (C) 2018 CERN.
#
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
import pytest
from mock import patch
from invenio_search.utils import schema_to_index
@... |
"""Reexport used modules, main code will be in `jupyter_black.py`."""
__version__ = "v0.3.0"
__author__ = "Nathan Henrie"
__email__ = "nate@n8henrie.com"
from .jupyter_black import (
load,
load_ipython_extension,
unload_ipython_extension,
)
__all__ = [
"load",
"load_ipython_extension",
"unload... |
from device import DeviceViewSet
from order import OrderViewSet, OrderTypeViewSet
from user import UserViewSet |
"""
Module for interacting with XDMoD
"""
import os
import sys
import pwd
import errno
import logging
from datetime import datetime, timedelta
from dateutil import parser
import MySQLdb
log = logging.getLogger("gracc_xdmod")
xdmod_conn = None
xdmod_curs = None
def _add_if_exists(cp, attribute, info):
"""
... |
import sys
import threading
import datetime
import logging
import time
_log = logging.getLogger(__name__)
_log.setLevel(logging.DEBUG)
# Uninterruptable code
def _no_interrupt(fun):
"""
Executes the given function in a context where it can't be interrupted by keyboard interupts.
:type fun: ``() -> Any``
:param ... |
from CNNectome.networks import unet
from CNNectome.networks import ops3d
import tensorflow as tf
import json
def train_net():
input_shape = (196, 196, 196)
raw = tf.placeholder(tf.float32, shape=input_shape)
raw_bc = tf.reshape(raw, (1, 1) + input_shape)
last_fmap, fov, anisotropy = unet.unet(
... |
from time import sleep
from operator import itemgetter
from random import randint
jogadores = {}
print('Valores sorteados:')
jogadores['jogador1'] = randint(1, 6)
jogadores['jogador2'] = randint(1, 6)
jogadores['jogador3'] = randint(1, 6)
jogadores['jogador4'] = randint(1, 6)
for k, v in jogadores.items():
print(f'... |
from som.primitives.primitives import Primitives
from som.vmobjects.primitive import Primitive
class StringPrimitives(Primitives):
def install_primitives(self):
def _concat(ivkbl, frame, interpreter):
argument = frame.pop()
rcvr = frame.pop()
frame.push... |
# Intermediate Strings
# https://www.freecodecamp.org/learn/scientific-computing-with-python/python-for-everybody/intermediate-strings
# Slicing Strings
s = 'Monty Python'
print(s[0:4]) # Outputs 'Mont', 0 -> pos 4 but not including
print(s[6:7]) # Outputs 'P', character 6 up to but not including character 7
prin... |
import pytest
def test_introduction_4():
import pandas as pd
from tcrdist.repertoire import TCRrep
df = pd.read_csv("dash.csv")
tr = TCRrep(cell_df = df,
organism = 'mouse',
chains = ['beta'],
db_file = 'alphabeta_gammadelta_db.tsv')
"""
tr.... |
from typing import Any, Dict, List, Type, TypeVar, Union
import attr
from ..models.indy_proof_requested_proof_revealed_attr_group_values import (
IndyProofRequestedProofRevealedAttrGroupValues,
)
from ..types import UNSET, Unset
T = TypeVar("T", bound="IndyProofRequestedProofRevealedAttrGroup")
@attr.s(auto_at... |
#!/usr/bin/env python3
# Copyright (c) 2014-2016 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import *
import f... |
from django.test import TestCase
from django.contrib.auth import get_user_model
from rest_framework.test import APIClient
from rest_framework.status import HTTP_200_OK, HTTP_201_CREATED, HTTP_400_BAD_REQUEST
from core.utils import UtilityFunctions
from core.utils import CREATE_USER_URL, LOGIN_USER_URL, CHECK_USER_URL... |
import uuid
from django.db import models
from cinp.orm_django import DjangoCInP as CInP
from User.models import User
cinp = CInP( 'Car', '0.1' )
@cinp.model()
class PartType( models.Model ):
name = models.CharField( max_length=40, primary_key=True )
description = models.CharField( max_length=255 )
updated = ... |
import cv2 as cv
gpu_frame = cv.cuda_GpuMat()
screenshot = cv.imread('../../media/drip.png')
gpu_frame.upload(screenshot)
screenshot = cv.cuda.cvtColor(gpu_frame, cv.COLOR_RGB2BGR)
screenshot = cv.cuda.resize(screenshot, (400, 400))
screenshot = screenshot.download()
# display image
from PIL import Image
Image.fro... |
"""Aries#0037 v1.0 Presentation request handler."""
from ....base_handler import (
BaseHandler,
BaseResponder,
HandlerException,
RequestContext
)
from .....holder.base import BaseHolder
from .....storage.error import StorageNotFoundError
from ..manager import PresentationManager
from ..messages.pres... |
# import common module
import os
import sys
path = "%s/translator"%os.getenv('PYSPARK_SRC')
if path not in sys.path:
sys.path.append(path)
from common_in_translator import *
from general.divide_line.divide_line import divide_line
#####################################################################
imp... |
def uM_to_mgml(species_mws, species_concs, scale=1000000):
"""
Args:
species_mws: (dict) For example {'enzyme_1' : 33000, 'substrate_1' : 150}
species_concs: (dict) For example {'enzyme_1' : 10, 'substrate_1' : 10000}
scale: (int) The scale we are working on. 1=M, 1000=mM, 1000,000=uM... |
"""
GPflow and TensorFlow specific code
"""
from geometric_kernels.backends.tensorflow.gpflow import GPflowGeometricKernel
|
from eve import ID_FIELD
from eve.methods.post import post_internal
from .repository import Repository
class ViewRepo(Repository):
def __init__(self, app):
self.table = app.data.driver.db['views']
def get_view_by_id(self, id):
return self.table.find({
ID_FIELD: self.normalize_id(... |
from django_evolution.tests.utils import test_sql_mapping
tests = r"""
>>> from django.db import models
>>> from django_evolution.mutations import DeleteModel
>>> from django_evolution.tests.utils import test_proj_sig, execute_test_sql, register_models, deregister_models
>>> from django_evolution.diff import Diff
>>... |
from io import BytesIO
from typing import *
import motor.motor_asyncio
from discord import Color, Embed, PartialEmoji, Emoji, Webhook
from discord.utils import get as discord_get
from discord.ext.commands import (
Context,
BadArgument,
PartialEmojiConverter,
Cog,
command,
has_permissions,
C... |
import io
from datetime import datetime
import pytz
from django.contrib.auth.models import User
from django.core.files import File
from PIL import Image
from drf_file_upload import models
USERNAME = "test_upload"
PASSWORD = "test_upload!"
def create_simple_uploaded_file(filename="best_file_eva.pdf", size=(100, 100... |
from jce import *
import argparse
parser = argparse.ArgumentParser(description='Combine multiple JSON/CSV/Excel file into a signle file')
parser.add_argument('-t', '--type', type=str, metavar='', required=True, help='Type of the file to convert [json/csv/excel]')
parser.add_argument('-o', '--output', type=str, metavar... |
import copy
import inspect
from typing import Any, Callable, Dict, Optional, Tuple, no_type_check
from fugue._utils.interfaceless import (
FunctionWrapper,
_FuncParam,
_OtherParam,
is_class_method,
)
from triad import assert_or_throw
from triad.utils.convert import get_caller_global_local_vars, to_func... |
"""IO module for reading and writing data."""
from .meas_info import ChInfo
from .reader import read_cluster
__all__ = ("ChInfo", "read_cluster")
|
from collections import defaultdict
import numpy as np
import seaborn as sns
from matplotlib import pyplot as plt
import arba
class Performance:
""" throwaway: tracks sensitivity and specificty per method """
def __init__(self, stat_label):
self.stat_label = stat_label
self.method_stat_ss_l... |
def definition():
"""Verbose view of component object."""
sql = """
SELECT c.component_id, c.description, c.module_code, c.calendar_type, c.coordination_eligible,
c.hecos, h.code_name, c.staffing_band, c.curriculum_id, c.credits, c.is_active, c.mandatory_constraints,
c.indicative_content, c.issues, c.... |
"""General purpose frequency analysis tools."""
import importlib
import statistics
from collections import Counter
from lantern.structures import DynamicDict
from lantern.util import iterate_ngrams
def frequency_analyze(text, n=1):
"""Analyze the frequency of ngrams for a piece of text.
Examples:
>... |
import hashlib
import logging
import requests
import json
class VTiger:
def __init__(self):
self.sessionId = ''
self.userId = ''
r = requests.get("http://knowledge.aiesec.org.mx/crm_test/webservice.php?operation=getchallenge&username=admin")
d = json.loads(r.text)
self.challenge = d['result']['token']
... |
import os
import os.path
class BuildTool(object):
def __init__(self, package_path, ws_path):
self._package_path = package_path
self._package_name = os.path.split(package_path)[1]
self._ws_path = ws_path
@property
def ws_path(self):
return self._ws_path
class CatkinBuild(... |
from amf_check_writer.cvs.base import BaseCV
class ProductsCV(BaseCV):
def parse_tsv(self, reader):
ns = self.namespace
cv = {ns: []}
for row in reader:
cv[ns].append(row["Data Product"])
return cv
|
import fqe
import numpy
import openfermion
import cProfile
if __name__ == "__main__":
norbs = 12
nel = 12
sz = 0
fqe_wfn = fqe.Wavefunction(param=[[nel, sz, norbs]])
fqe_wfn.set_wfn(strategy='random')
# binarycode = None
binarycode = openfermion.transforms.bravyi_kitaev_code(norbs * 2)
... |
import logging
import requests
from lxml import etree
from normality import collapse_spaces
from libsanctions import Source, Entity, BirthDate
log = logging.getLogger(__name__)
XML_URL = 'http://www.international.gc.ca/sanctions/assets/office_docs/sema-lmes.xml' # noqa
def parse():
res = requests.get(XML_URL)... |
import logging
import re
from src.lh.service_directives import Exclude, Probe, Match, SoftMatch, Ports, SslPorts, Rarity, ProbeConfig
class ProbeFileParser(object):
cur_probe = None
FLAG_FORMAT = re.compile(r'(?:[pvihod]|cpe:)/([^/]+)/[a-z]?')
MATCH_FORMAT = re.compile(r'^m(.)(.*?)(?:\1)([a-z]+)?')
... |
# The MIT License (MIT)
# Subject to the terms and conditions contained in LICENSE
import datetime
import fnmatch
import json
import logging
import os
import re
import numpy as np
import pandas as pd
from nltk.tokenize import sent_tokenize
logger = logging.getLogger(__name__)
here = os.path.dirname(os.path.realpath(_... |
# Copyright 2018 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, ... |
import numpy as np
import ipdb
import torch
import torch.nn as nn
import numpy as np
import random
from model import Policy, StateGen
from baselines.common.segment_tree import SumSegmentTree, MinSegmentTree
from utils_bw import select_mj, evaluate_mj, zero_mean_unit_std
class ReplayBuffer:
"""
Replay buffer...... |
'''
Кубики
'''
ani = set()
bor = set()
with open('input.txt', 'r') as file:
flag = True
for line in file:
if (flag):
splitted = line.split()
n, m = int(splitted[0]), int(splitted[1])
flag = False
isF = True
elif (n > 0):
ani.add(int(lin... |
import sys
sys.path.append("..")
from util.utilities import *
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
datefmt='%B-%d-%Y %H:%M:%S',
filename=f"../logs/{Path(__file__).stem}.log",
filemode='w'
)
next_month = datetime.datetime.today().month + 1
st... |
# coding=utf-8
"""
Michael duPont - michael@mdupont.com
Original source: https://github.com/flyinactor91/AVWX-Engine
Modified by etcher@daribouca.net
"""
# pylint: disable=too-many-lines
import logging
import typing
from copy import copy
from datetime import datetime, timedelta
from itertools import permutations
from... |
print('=-'*10)
print('URNA ELETRÔNICA')
print('=-'*10)
votoslula = 0
votosbolsonaro = 0
votosnulo = 0
while True:
voto = int(input('DIGITE O NÚMERO DO SEU CANDIDATO: '))
if voto == 13:
votoslula += 1
if voto == 17:
votosbolsonaro += 1
if votosbolsonaro % 5 == 0:
votosbolsonaro -=... |
# Copyright 2018 PerfKitBenchmarker 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 appli... |
import numpy as np
from robosuite.models.arenas import Arena
from robosuite.utils.mjcf_utils import xml_path_completion
from robosuite.utils.mjcf_utils import array_to_string
class ShelfArena(Arena):
"""
Workspace that contains two bins placed side by side.
Args:
shelf_pos (3-tuple): (x,y,z) posi... |
# !/bin/python3
def count_modifications(string_1, string_2):
# Initial check
if len(string_1) != len(string_2):
return -1
# Initialization of mod count and alphabetical character count
count = 0
character_count = [0] * 26
for i in range(26):
character_count[i] = 0
# Going... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
mslib.msui.mss_pyui
~~~~~~~~~~~~~~~~~~~
Mission Support System Python/Qt User Interface
Main window of the user interface application. Manages view and tool windows
(the user can open multiple windows) and provides functionality to open, save,
a... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.