text stringlengths 2 999k |
|---|
# ---
# jupyter:
# accelerator: GPU
# colab:
# collapsed_sections: []
# name: Habitat Lab
# provenance: []
# jupytext:
# cell_metadata_filter: -all
# formats: nb_python//py:percent,colabs//ipynb
# notebook_metadata_filter: all
# text_representation:
# extension: .py
# forma... |
"""
This file offers the methods to automatically retrieve the graph Acinetobacter tjernbergiae.
The graph is automatically retrieved from the STRING repository.
References
---------------------
Please cite the following if you use the data:
```bib
@article{szklarczyk2019string,
title={STRING v11: protein--pro... |
import sys
input = sys.stdin.readline
def lis(seq) :
cache = [1] * len(seq)
for i in range(1, len(seq)):
for j in range(i):
if seq[j] < seq[i]:
cache[i] = max(cache[i],cache[j]+1)
print(max(cache))
N = int(input())
seq = list(map(int,input().split()))
lis(seq)
|
import network
import utils
import os
import random
import args
import numpy as np
import time
from torch.utils import data
from metrics import StreamSegMetrics
import torch
import torch.nn as nn
from utils.visualizer import Visualizer
from torch.utils.tensorboard import SummaryWriter
from PIL import Image
import matp... |
import os
from leapp.libraries.stdlib import api, run
from leapp.models import SCTPConfig
def enable_sctp(_modprobe_d_path="/etc/modprobe.d"):
"""
Enables the SCTP module by removing it from being black listed.
:type _modprobe_d_path: str
:param _modprobe_d_path: overwrite only in case of testing, by... |
import logging
import ray
from ray.rllib.agents.a3c.a3c_torch_policy import apply_grad_clipping
from ray.rllib.agents.ddpg.ddpg_tf_policy import build_ddpg_models, \
get_distribution_inputs_and_class, validate_spaces
from ray.rllib.agents.dqn.dqn_tf_policy import postprocess_nstep_and_prio, \
PRIO_WEIGHTS
from... |
from typing import List
class Solution:
def searchInsert(self, nums: List[int], target: int) -> int:
size = len(nums)
left = 0
right = size
while left < right:
mid = (left + right) >> 1
if nums[mid] < target:
left = mid + 1
else:
... |
import argparse
from argparse import ONE_OR_MORE, OPTIONAL, PARSER, REMAINDER, ZERO_OR_MORE
from typing import Type, Callable
from argparse import Action
from .logging_utils import get_logger
from .utils import (get_type_arguments, get_type_name, is_optional, is_tuple,
is_tuple_or_list, is_union)
f... |
import datetime
import logging
import json
import os
import numpy as np
import time
logging.basicConfig(format='%(asctime)s %(levelname)s %(name)s: %(message)s', level=logging.DEBUG)
logger = logging.getLogger(__file__)
from gesscon.MQTTClient import MQTTClient
from data_management.utils import Utils
class GESSCon(... |
import tkinter as tk
from src.gui.app import App
if __name__ == '__main__':
app = App()
app.geometry('{}x{}'.format(800, 600))
app.mainloop()
|
import unittest
from cloudwanderer import URN
from ..helpers import CloudWandererCalls, ExpectedCall, MultipleResourceScenario, NoMotoMock, SingleResourceScenario
class TestVPCEndpoints(NoMotoMock, unittest.TestCase):
vpc_endpoint_payload = {
"VpcEndpointId": "vpce-11111111111111111",
"VpcEndpo... |
#!/usr/bin/env python
#
# Copyright 2016 Pinterest, 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 la... |
from setuptools import setup, find_packages
setup (
name='MediaGrabber',
version='0.1',
packages=find_packages(),
description='A tool to automatically collect media files into a structure based on create date',
# Declare your packages' dependencies here, for eg:
install_requires=[],
dependency_li... |
import torch
import torch.nn as nn
import torch_scatter
from torch.nn import functional as F
class FCStack(nn.Module):
def __init__(self, in_channels, list_out_channels, batch_norm=True):
super(FCStack, self).__init__()
layers = []
for out_channels in list_out_channels:
layers.a... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'mwnt_Ch_list_item_dialog.ui'
#
# Created by: PyQt4 UI code generator 4.11.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
de... |
from fastapi.testclient import TestClient
from docs_src.advanced_middleware.tutorial002 import app
def test_middleware():
client = TestClient(app, base_url="http://example.com")
response = client.get("/")
assert response.status_code == 200, response.text
client = TestClient(app, base_url="http://subd... |
# -*- coding: utf-8 -*-
"""
Contains classes and utilities for serving a site
generated from hyde.
"""
import threading
import urlparse
import urllib
import traceback
from datetime import datetime
from SimpleHTTPServer import SimpleHTTPRequestHandler
from BaseHTTPServer import HTTPServer
from hyde.generator import Gen... |
# coding=utf-8
# Copyright Google AI and The HuggingFace Inc. 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
#
#... |
"""yoga URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/2.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based vi... |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
# -*- coding: UTF-8 -*-
import argparse
import numpy as np
import onnx
import sys
from onnx import helper, numpy_helper, shape_inference
import sympy
from packaging import version
assert version.parse(onnx.__version__) >= ve... |
#
# Copyright 2017 XEBIALABS
#
# 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, distribute, subli... |
# Copyright (c) 2012 NetApp, Inc.
# Copyright (c) 2014 Red Hat, Inc.
# 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... |
import logging
from fetchcode.vcs.pip._internal.models.direct_url import (
DIRECT_URL_METADATA_NAME,
ArchiveInfo,
DirectUrl,
DirectUrlValidationError,
DirInfo,
VcsInfo,
)
from fetchcode.vcs.pip._internal.utils.typing import MYPY_CHECK_RUNNING
from fetchcode.vcs.pip._internal.vcs import vcs
try... |
# Generated by Django 2.1.15 on 2021-07-16 13:35
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0009_alter_user_last_name_max_length'),
]
operations = [
migrations.CreateModel(
name='User',
... |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: stream_metric_states.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google... |
# -*- coding: utf-8 -*-
# File generated according to Generator/ClassesRef/Simulation/Simu1.csv
# WARNING! All changes made in this file will be lost!
"""Method code available at https://github.com/Eomys/pyleecan/tree/master/pyleecan/Methods/Simulation/Simu1
"""
from os import linesep
from sys import getsizeof
... |
# An extra day is added to the calendar almost every four years as February 29, and the day is called a leap day.
# It corrects the calendar for the fact that our planet takes approximately 365.25 days to orbit the sun. A leap year contains a leap day.
# In the Gregorian calendar, three conditions are used to identify... |
import os
import infra.basetest
GLXINFO_TIMEOUT = 120
class TestGlxinfo(infra.basetest.BRTest):
config = \
"""
BR2_x86_core2=y
BR2_TOOLCHAIN_EXTERNAL=y
BR2_TOOLCHAIN_EXTERNAL_CUSTOM=y
BR2_TOOLCHAIN_EXTERNAL_DOWNLOAD=y
BR2_TOOLCHAIN_EXTERNAL_URL="http://toolchains.... |
from tests.system.action.base import BaseActionTestCase
class MotionUpdateMetadataActionTest(BaseActionTestCase):
def test_update_correct(self) -> None:
self.create_model("meeting/2538", {"name": "name_jkPIYjFz"})
self.create_model("motion/111", {"name": "name_srtgb123", "meeting_id": 2538})
... |
# -*- coding: utf-8 -*-
'''
Support for YUM
'''
# Import python libs
from __future__ import absolute_import
import copy
import itertools
import logging
import os
import re
import string
from distutils.version import LooseVersion as _LooseVersion # pylint: disable=no-name-in-module,import-error
# Import 3rd-party lib... |
#Template of the Purkinje cell model (single compartment), Akemann et al. 2009
#Templating by Lungsi 2019 based on ~/PC2009Akemann/morphology_mechanisms.hoc
from neuron import h
#from pdb import set_trace as breakpoint
class Purkinje(object):
"""Single compartment cell
"""
def __init__(self):
h.xop... |
#!/usr/bin/env python3
import sys
if len(sys.argv) > 1 and sys.argv[1] == '--version':
print('Version 0.1.1', file=sys.stderr)
exit(0)
if len(sys.argv) != 2 + 1:
exit(1)
print(f'a+b = {sys.argv[1]} + {sys.argv[2]}')
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import matplotlib
import japanmap
import pandas as pd
def jpn_map(prefectures, values, title, cmap_name="Reds", filename=None):
"""
Show colored Japan prefecture map.
@prefectures <list/pd.Series[str]... |
#!/usr/bin/env python
# This script is intended to replace the bash wrapper script "splitseqdemultiplex_0.2.1.sh"
# It will facilitate demultiplexing with parallel processing exclusively using python
import DemultiplexUsingBarcodes_New_V2
from joblib import Parallel, delayed
import multiprocessing
import os
import Spl... |
from collections import namedtuple
from typing import List
ZERO = 0.000001 # replacement for zero in random number handling
class Ohlc(namedtuple('Ohlc', 'open high low close')):
"""Ohlc stores open, high, low, and close values as namedtuple"""
ZERO = ZERO
_prev = None # type: Ohlc
@staticmethod
... |
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, \
PermissionsMixin
class UserManager(BaseUserManager):
def create_user(self, email, password=None, **extra_fields):
"""Creates and saves a new user"""
if ... |
#
# This file is autogenerated during plugin quickstart and overwritten during
# plugin makedist. DO NOT CHANGE IT if you plan to use plugin makedist to update
# the distribution.
#
from setuptools import setup, find_packages
kwargs = {'author': '',
'author_email': '',
'classifiers': ['Intended Audience :: Science... |
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="animal-crossing-turnip-prices-chanko08",
version="0.0.5",
author="Alex Bechanko",
author_email="chanko08@gmail.com",
description="Animal Crossing New Horizons turnip price predictor",
... |
# coding: utf-8
from __future__ import unicode_literals
import codecs
import re
from collections import OrderedDict
from os import SEEK_CUR
from sys import platform
from serial import Serial, SerialBase, serial_for_url
from serial.rs485 import RS485Settings
from serial.serialutil import LF
from serial.tools.list_ports... |
#### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Static()
result.template = "object/static/item/shared_item_container_energy_radioactive.iff"
result.attribute_tem... |
from hamcrest.core.base_matcher import BaseMatcher
from calendar import monthrange
def _calculatePeselChecksum(peselPart: str):
weights = [1, 3, 7, 9, 1, 3, 7, 9, 1, 3]
checksum = 10 - sum(
weight * int(digit) for weight, digit in zip(weights, peselPart)
) % 10
return checksum
def _validatePesel(pesel: str):
... |
from direct.interval.IntervalGlobal import *
from direct.gui.DirectFrame import DirectFrame
from direct.gui.DirectLabel import DirectLabel
from toontown.toonbase import ToontownGlobals, TTLocalizer
class ScavengerHuntEffect:
images = None
def __init__(self, beanAmount):
if not ScavengerHuntEffect.imag... |
from setuptools import setup
from torch.utils.cpp_extension import BuildExtension, CUDAExtension
setup(
name='depthavgpooling_cuda',
ext_modules=[
CUDAExtension('depthavgpooling_cuda', [
'depthavgpooling_cuda.cpp',
'depthavgpooling_cuda_kernel.cu'
])
],
cmdclass=... |
import enum
from pydoc import locate # https://stackoverflow.com/a/29831586
from re import search
@enum.unique
class Status(enum.Enum):
ACTIVE = "ACTIVE"
SKIPPED = "SKIPPED"
PASSED = "PASSED"
FAILED = "FAILED"
@enum.unique
class Method(enum.Enum):
GET = "GET"
POST = "POST"
PUT = "PUT"
... |
import asyncio
class EchoServerProtocol(asyncio.DatagramProtocol):
def connection_made(self, transport):
self.transport = transport
def datagram_received(self, data, addr):
self.transport.sendto(data, addr)
class EchoServer:
async def close(self):
self.udp_server.transport.close... |
# -*- coding: utf-8 -*-
#
# Copyright (c) 2017-2019 VMware, Inc. All Rights Reserved.
# SPDX-License-Identifier: BSD-2-Clause
#
"""
Error messages
"""
unrecognized_base = '''Unable to determine the base OS of the image ''' \
'''{image_name}:{image_tag}\n'''
no_packages = '''Unable to recover packages for layer {la... |
class MessageTypeNotExist(Exception):
"""
消息类型不存在
"""
pass
class TopicMessageTypeNotExist(Exception):
"""
主题消息类型不存在
"""
pass
|
"""Running tests"""
import sys
import time
from . import result
from .signals import registerResult
__unittest = True
class _WritelnDecorator(object):
"""Used to decorate file-like objects with a handy 'writeln' method"""
def __init__(self,stream):
self.stream = stream
def __ge... |
from datetime import datetime
from pathlib import Path
import os
extensions = [
"breathe",
]
# Project
project = "Battery Management System"
author = "The Libre Solar Project"
year = datetime.now().year
copyright = f"{year} {author}"
version = os.popen("git describe --tags --abbrev=0").read()
# HTML output
ht... |
# Importing necessary libraries
import zipfile
import re
# Now the hint in the source code was zip.
# So, when we change the url to channel.zip we get a
# zip file downloaded which contains many txt files each
# linking to another file. Now the target is to open the
# first txt file and follow the numbers till we reac... |
# Copyright (c) 2014 Eric Davis
# Licensed under the MIT License
import urwid
class UserInput(urwid.Edit):
def __init__(self, config, caption, edit_text, callback_func, args):
self.config = config
self.callback_func = callback_func
self.callback_func_args = args
super(UserIn... |
import numpy as np
import argparse
import imutils
import time
import cv2
import os
from tqdm import tqdm
from collections import Counter
#Accept arguements from user
ap = argparse.ArgumentParser()
ap.add_argument("-i", "--input", required=True,
help="path to input video")
ap.add_argument("-o", "--output", required=Tr... |
from posthog.models import Event, Team, Action, ActionStep, Element, User
from rest_framework import request, serializers, viewsets, authentication # type: ignore
from rest_framework.response import Response
from rest_framework.decorators import action # type: ignore
from rest_framework.exceptions import Authentication... |
from .streaming import Streaming
from .utils import Utils
from .widgets import Widgets
from .board import Board
from .ads import Ads
from .storage import Storage
from .stats import Stats
from .auth import Auth
from .docs import Docs
from .stories import Stories
from .video import Video
from .wall import Wall
from .page... |
#!/usr/bin/env python
import pygraphviz as pgv
# strict (no parallel edges)
# digraph
# with attribute rankdir set to 'LR'
A = pgv.AGraph(directed=True, strict=True, rankdir="LR")
# add node 1 with color red
A.add_node(1, color="red")
A.add_node(5, color="blue")
# add some edges
A.add_edge(1, 2, color="green")
A.add... |
"""
Example of of simple souce RayPencil with two apertures.
"""
from poptics.ray import RayPencil, RayPath, SourcePoint
from poptics.surface import CircularAperture, IrisAperture
from poptics.vector import Vector3d
import matplotlib.pyplot as plt
def main():
# Form two apertures both 20mm wit... |
from django.shortcuts import render
# Create your views here.
from django.http import HttpResponse
from django.template import loader
def index(request):
latest_question_list = 889
template = loader.get_template('base/index.html')
context = {'latest_question_list': latest_question_list}
return HttpResp... |
from typing import List
import pytest
import requests
from background_task.tasks import tasks
from django.conf import settings
from django.contrib.auth.models import User
from django.core.mail import EmailMultiAlternatives
from pytest_mock import MockFixture
from core.tasks import (
add_user_to_mailing_list,
... |
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 29 11:36:45 2018
@author: suvod
"""
from __future__ import division
import git_access
import json
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import math
import networkx as nx
class git_api_access(object):
def __init__(self,token,repo_... |
"""Contains utility functions, including functions for loading saved results."""
import os
import numpy as np
from astropy.table import Table
BLEND_RESULT_KEYS = ("blend_images", "isolated_images", "blend_list")
def load_blend_results(path, survey):
"""Load results exported from a DrawBlendsGenerator.
Args... |
import sys
self = sys.modules[__name__]
import os
import glob
import re
import numpy
import importlib
import shutil
import cv2
from tqdm import tqdm
pointFileExtensions = ["csv", "txt", "npy", "ims"]
pointFileTypes = ["CSV", "NPY", "Imaris"]
pointFileExtensionToType = {"csv" : "CSV", "txt" : "CSV", "npy" : "NPY", "im... |
# Copyright 2008-2015 Nokia Networks
# Copyright 2016- Robot Framework Foundation
#
# 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
... |
import asyncio
import json
import logging
import time
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional, Tuple
import traceback
import aiohttp
from blspy import AugSchemeMPL, G1Element, G2Element, PrivateKey
import chia.server.ws_connection as ws # lgtm [py/import-and-import-from]
from ... |
"""
Scatterplot with categorical variables
======================================
"""
import pandas as pd
import seaborn as sns
sns.set(style="whitegrid", palette="muted")
# Load the example iris dataset
iris = sns.load_dataset("iris")
# "Melt" the dataset to "long-form" or "tidy" representation
iris = pd.melt(iris,... |
# -*- coding: utf-8 -*-
"""
oauthlib.oauth2
~~~~~~~~~~~~~~
This module is a wrapper for the most recent implementation of OAuth 2.0 Client
and Server classes.
"""
from __future__ import absolute_import, unicode_literals
from .rfc6749.clients import Client
from .rfc6749.clients import WebApplicationClient
from .rfc674... |
#!/usr/bin/env python
import multiprocessing
import click
from mypytools.server import mypy_server
@click.command()
@click.option('--compact', is_flag=True, default=False, help="Print mypy errors without surrounding code context.")
@click.option('--num-workers', default=multiprocessing.cpu_count())
def main(compact,... |
# Copyright 2016 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... |
import requests, traceback
from django.db import models
from django.utils import timezone
from django.conf import settings
def time_str(utctime):
return '{}-{}-{}T{}:{}:{}{}Z'.format(utctime.year, utctime.month, utctime.day,
utctime.hour, utctime.minute, utctime.second)
... |
'''Autogenerated by xml_generate script, do not edit!'''
from OpenGL import platform as _p, arrays
# Code generation uses this
from OpenGL.raw.GLX import _types as _cs
# End users want this...
from OpenGL.raw.GLX._types import *
from OpenGL.raw.GLX import _errors
from OpenGL.constant import Constant as _C
imp... |
'''
Manage Azure Network Security Groups (NSGs).
'''
from ... pyaz_utils import _call_az
from . import rule
def delete(name, resource_group):
'''
Delete a network security group.
Required Parameters:
- name -- Name of the network security group.
- resource_group -- Name of resource group. You can... |
import mock
from unittest import TestCase
import sewer
from . import test_utils
class TestHEDNS(TestCase):
"""
"""
def setUp(self):
self.domain_name = "example.com"
self.domain_dns_value = "mock-domain_dns_value"
self.he_uesrname = "mock-username"
self.he_password = "mock-... |
#
# License: https://creativecommons.org/licenses/by/4.0/ https://creativecommons.org/licenses/by/4.0/legalcode
# © 2020 https://github.com/Oops19
#
#
from high_heels.utilities.o19sim_v3 import O19SimV2
from high_heels.utilities.o19cache import O19Cache
import sims4
import sims4.commands
o19cache = O19Ca... |
# -*- coding: utf-8 -*-
import os
from ..utils import get_page_layout, get_text_objects
class BaseParser(object):
"""Defines a base parser."""
def _generate_layout(self, filename, layout_kwargs):
self.filename = filename
self.layout_kwargs = layout_kwargs
self.layout, self.dimension... |
#!/usr/bin/env python3
# Copyright (c) 2016-2019 The BitPal Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Encode and decode BASE58, P2PKH and P2SH addresses."""
import enum
from .script import hash256, hash16... |
# The information of database
DB_HOST="127.0.0.1"
DB_PORT=3306
DB_DATABASE="TINYHIPPOTEST"
DB_USER="root"
DB_PASSWORD="tiny-hippo"
DB_CHARSET="utf8"
# The information of database connection pool
# mincached : The number of idle connections opened at startup
DB_MIN_CACHED=3
# maxcached : The maximum number of idle co... |
# Author: Alex Ksikes
import web
from web import http
import pycurl, random, re, cStringIO, types, urllib
import urlparse as _urlparse
from lxml import etree
from md5 import md5
from datetime import datetime
def url_encode(url):
return http.urlencode(url)
def url_unquote(url):
return urlli... |
import jwt
from django.apps import apps
from drf_spectacular.extensions import OpenApiAuthenticationExtension
from rest_framework import exceptions
from rest_framework_jwt.authentication import (
JSONWebTokenAuthentication as JWTJSONWebTokenAuthentication,
)
from rest_framework_jwt.blacklist.exceptions import (
... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# Phylotree.js documentation build configuration file, created by
# sphinx-quickstart on Mon Nov 27 10:08:45 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this... |
"""Module for convolutional [conditional | latent] neural processes"""
import logging
import math
from functools import partial
import torch
import torch.nn as nn
import torch.nn.functional as F
from npf.architectures import CNN, ResConvBlock, SetConv, discard_ith_arg
from npf.utils.initialization import weights_init
... |
import torch.nn as nn
import torch.nn.functional as F
from mmcv.cnn import ConvModule, xavier_init
from mmcv.ops import DeformConv2dPack
import torch
from mmdet.core import auto_fp16
from ..builder import NECKS
@NECKS.register_module()
class FPNDcnFull(nn.Module):
r"""Feature Pyramid Network.
This is an imp... |
# Program untuk menampilkan persegi
print('\n==========Persegi==========\n')
for row in range(5):
for col in range(10):
print('#', end='')
print('') |
# Copyright 2021 DAI Foundation
#
# 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,... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import json
import warnings
import pulumi
import pulumi.runtime
from typing import Union
from .. import utilities, tables
class Functi... |
#Static Method
'''
In the below code we are invoking the getter method using a reference variable.
But the self is not used inside the method at all.
'''
class Mobile:
__discount = 50
def __init__(self, price, brand):
self.price = price
self.brand = brand
def purchase(self):
tot... |
from __future__ import print_function
import os
import re
import sys
import abc
import json
import datetime
import argparse
import requests
import yaml
from demisto_sdk.commands.common.constants import INTEGRATIONS_DIR, SCRIPTS_DIR, PLAYBOOKS_DIR, REPORTS_DIR, \
DASHBOARDS_DIR, WIDGETS_DIR, INCIDENT_FIELDS_DIR, LA... |
from datetime import datetime
from . import format, get
from .tweet import Tweet
from .user import User
from .storage import db, elasticsearch, write, panda
import logging as logme
follows_list = []
tweets_list = []
users_list = []
author_list = {''}
author_list.pop()
# used by Pandas
_follows_object = {}
def _f... |
import configparser
import datetime
import importlib
import logging
import multiprocessing
import os
import os.path
import sys
import time
import multiprocessing_logging
from .__version__ import __version__
from . import exceptions
from . import processing
def get_source_collectors(config):
source_collector_dir... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = "sepp.heid@t-online.de"
__doc__ = """ """
from pptx import Presentation
from pptx.exc import PackageNotFoundError
from poorscrum import Status, read_fields, story_points, __version__
import configparser
import argparse
import os
import sys
import loggi... |
from contextlib import contextmanager
import linecache
import os
from io import StringIO
import sys
import unittest
import subprocess
from test import support
from test.script_helper import assert_python_ok
from test import warning_tests
import warnings as original_warnings
py_warnings = support.import_fresh_module(... |
"""
WSGI config for discord_clone 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/3.2/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO... |
# 1.)
lado_1 = 20
altura = 40
area = (lado_1 * altura) / 2
print(area)
# 2.)
lado_1_rectangulo = 20
lado_2_rectangulo = 60
area_rectangulo = (lado_1_rectangulo * lado_2_rectangulo) / 2
print(area_rectangulo) |
import sys
from gensim import corpora
from topic.topicio import TopicIO
from coherence.umass import TopicCoherence
import utils.name_convention as name
from utils.corpus import arg_tfidf
#
# syntax: python tcReader.py <input directory name> <corpus type> <# of topics> <src> <word count>
# <dictionary name> the nam... |
"""
A Roll class is all the information about a roll that is made. Crits,
karma spent, or any number of other modifiers is saved to decide what
message will be sent, if any. While it could be a simulated roll made
by a GM, a character's roll will be stored in character.ndb.last_roll
attribute.
"""
from collections impo... |
import logging
from logging.config import dictConfig
from flask.logging import default_handler
# Set root logger to log to sys.stderr.
# Note: this must be set before the Flask app gets created.
dictConfig(
{
'version': 1,
'formatters':
{
'default':
... |
# !/usr/bin/python3
import os
from subprocess import getstatusoutput
from tempfile import gettempdir
from setuptools_setup_versions import install_requires
REPOSITORY_DIRECTORY = os.path.dirname(
os.path.dirname(
__file__
)
)
PACKAGE_NAME = REPOSITORY_DIRECTORY.split('/')[-1].split('\\')[-1]
def run... |
import unittest
from igf_data.utils.tools.ppqt_utils import Ppqt_tools
class Ppqt_util_test1(unittest.TestCase):
def test_parse_spp_output(self):
ppqt = Ppqt_tools(rscript_path='blah',ppqt_exe='blah')
metrics = ppqt._parse_spp_output(spp_file='data/ppqt_metrics/test.spp.out')
self.assertTrue(isinstance(m... |
import pathlib
import cv2 as cv
import numpy as np
from django.conf import settings
def get_matched_image(image, needle, threshold=0.95):
if not needle:
return image
else:
needle_path = pathlib.PurePath(
settings.STATIC_ROOT
+ f"/images/templatematching/templatematchin... |
"""
Abstract from: https://arxiv.org/abs/1409.4842
We propose a deep convolutional neural network architecture codenamed "Inception", which was responsible for setting the new state of the art for classification and detection in the ImageNet Large-Scale Visual Recognition Challenge 2014 (ILSVRC 2014). The main... |
def log(m):
print('SEND 1')
print(m)
N = int(input())
if N != 2:
log("Not the right number of players (" + str(N) + "). Should be two!")
num_rounds = 21
log("ROCK, PAPER, SCISSORS")
log("=====================")
log("Best to " + str(num_rounds) + "!")
def compare(a, b):
a = a.upper()
b = b.upper(... |
import math
import numpy as np
def correlation( x, y ):
if len( x ) != len( y ):
print( 'arrays must have same dimension' )
else:
n = len( x )
xy = x*y
xsq = x ** 2
ysq = y ** 2
m1 = n * sum( xy ) - sum( x ) * sum( y )
m2 = n * sum( xsq ) - sum( x ) ** 2
m = m1/m2
b = ( sum( y ) - m * sum( x ) ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.