text stringlengths 2 999k |
|---|
class Solution:
def XXX(self, nums1: List[int], nums2: List[int]) -> float:
n1 = len(nums1)
n2 = len(nums2)
if n1 > n2:
return self.XXX(nums2,nums1)
k = (n1 + n2 + 1)//2
left = 0
right = n1
while left < right :
m1 = left +(right - left... |
def load_csv(fdir):
f = open(fdir)
data = []
for line in f.readlines():
atts = line.split(',')
if len(atts) > 1:
data.append(atts)
return data
data = load_csv("dbpedia-2016-10.csv")
commands = ""
for row in data:
print(row[0]+" of size: "+row[1])
# command = "wget... |
# -*- coding: utf8 -*-
import os
import unittest
import das # pylint: disable=import-error
class TestCase(unittest.TestCase):
TestDir = None
HomerInput = None
HomerOutput = None
SimpsonsInput = None
SimpsonsOutput = None
MultipleOutput = None
@classmethod
def setUpClass(cls):
cls.TestDi... |
# -*- coding: utf-8 -*-
"""
@author: Amin Asbai
"""
import json
import pandas as pd
import requests
def update_Weather_data(df):
url='http://api.openweathermap.org/data/2.5/weather?q=Andratx&units=metric&appid=1e47e582bff799e3514239429b76f2aa'
response = requests.get(url)
climate_data=response.json()
... |
from unittest.mock import MagicMock, patch
import sklearn.naive_bayes
import numpy as np
import pandas as pd
import re
# test csv file
TEST_CSV = 'data/test_info.csv'
class AssertTest(object):
'''Defines general test behavior.'''
def __init__(self, params):
self.assert_param_message = '\n'.join([str(k... |
# --------------------------------------------------------
# Deep Feature Flow
# Copyright (c) 2016 by Contributors
# Copyright (c) 2017 Microsoft
# Licensed under The Apache-2.0 License [see LICENSE for details]
# Modified by Xizhou Zhu, Yuwen Xiong, Bin Xiao
# --------------------------------------------------------
... |
import math
def sqr(x):
return x * x
def distance_between(one, two):
return math.sqrt(sqr(two["x"] - one["x"]) + sqr(two['y'] - one['y']))
def manhattan(one, two):
return abs(two["x"] - one["x"]) + abs(two['y'] - one['y']) |
html_file = 'obama_addresses.html'
with open(html_file, 'r') as f:
text = f.read()
search_text = 'watch?v='
video_ids = []
pos = 0
i = 0
while i != -1:
i = text.find(search_text, pos)
quote_stop = text.find('"', i+1)
and_stop = text.find('&', i+1)
if and_stop != -1:
stop_pos = min(quote_stop, and_stop)
else:... |
import logging
import msgpack
from . import rpc_serialize
import WebRequest
class PluginInterface_RemoteExecLocalProxy():
name = 'RemoteExec'
can_send_partials = True
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.log = logging.getLogger("Main.RemoteExec.Caller")
self.wg = We... |
#!/usr/bin/env python
# Copyright 2016 The Kubernetes 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 applic... |
import numpy as np
import pandas as pd
import pytest
from ..testing_utils import make_ecommerce_entityset
import featuretools as ft
from featuretools.computational_backends import PandasBackend
from featuretools.primitives import (
CumCount,
CumMax,
CumMean,
CumMin,
CumSum,
Last,
Transform... |
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import logging
import os
import sys
from pathlib import Path
import torch
import numpy as np
from scipy import spatial
from datasets.datas... |
# Author Maria carroll
# Week 2
# https://www.w3resource.com/python-exercises/python-basic-exercise-66.php
# Lecture 2 Statements
# Lecturer: Andrew Beatty
#Here we are writng a program to take information from the user to assertain a bmi result from their input
height = float(input ("Enter height in metres: "))
w... |
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community
Edition) available.
Copyright (C) 2017-2019 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in co... |
"""
Tests for the HubSpot template tags and filters.
"""
from django.http import HttpRequest
from django.template import Context
from django.test.utils import override_settings
from analytical.templatetags.hubspot import HubSpotNode
from analytical.tests.utils import TagTestCase
from analytical.utils import Analytica... |
from __future__ import unicode_literals
from django.contrib.auth.forms import AuthenticationForm
from django import forms
from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Submit, HTML, Field
from authtools import forms as authtoolsforms
from django.contrib.auth import forms as authform... |
import re
import sys
import urllib3
import click
from pyVmomi import vim, vmodl
import requests
from vctl.objects.datastore import get_http_cookie
from vctl.helpers.helpers import load_context, scrape
from vctl.helpers.vmware import get_obj
from vctl.helpers.auth import inject_token
urllib3.disable_warnings(urllib... |
"""Common classes and functions for Zoom."""
from datetime import timedelta
from logging import getLogger
from typing import Any, Dict
import async_timeout
from homeassistant.core import HomeAssistant
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
from custom_components.niceh... |
# -*- coding: utf-8 -*-
from django.utils.translation import ugettext_lazy as _
from cms.plugin_pool import plugin_pool
from cms.plugin_base import CMSPluginBase
from .models import Promo
@plugin_pool.register_plugin
class PromoPlugin(CMSPluginBase):
model = Promo
name = _('Promo')
admin_preview = False
... |
# coding: utf-8
"""
Kubernetes
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: v1.9.4
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import os
import sys
im... |
from django.shortcuts import render, get_object_or_404
from django.views import generic
from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.utils.decorators import available_attrs, method_decorator
f... |
#!/usr/bin/python
# Perform spiral holography scan on specified target(s). Mostly used for beam pattern measurement.
#
# to run on simulator:
# ssh kat@monctl.comm
# kat-start.sh (may need to call kat-stop.sh, or better kat-kill.py, and possibly kill all screen sessions on kat@monctl.comm, and possibly kat@proxy.monctl... |
# 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 ... |
"""Basic Graphical User Interface Components
"""
import os
import collections
import functools
import inspect
from PyQt4 import QtGui, QtCore
CONFIG = {'font': QtGui.QFont(),
'translator': QtCore.QTranslator(),
'locale': 'default'}
def with_app(func):
"""Intended to be used as a decorator to ... |
"""
Reference: https://github.com/mfaruqui/eval-word-vectors
"""
import math
import numpy
from operator import itemgetter
from numpy.linalg import norm
EPSILON = 1e-6
def euclidean(vec1, vec2):
diff = vec1 - vec2
return math.sqrt(diff.dot(diff))
def cosine_sim(vec1, vec2):
vec1 += EPSILON * numpy.ones(len(vec... |
asian_chars = '亙卉嘆噢嚮壇層嶺廣怵恆情懲拐拴捨換栓氯沉漢濫爵璜痊癲磺納練翎莒藍術誤請謁贈躍轂述鄹鈴難靛響領類鴒齡亶嗢枘歎沭洴潢瀞瞋秫稙笄糨芮荃蔇醛饂饗县迩傻将植浅茎莓嗔汧慨残画置殖鯽厩启碌虞訥蠁韞鯖令伶倩僧全捌卿器嚥弥径憎怜懊榔櫛涵滞澳猜缾瘟直睛矗禅称簧羚曜聆臭苓菁莽芦蜈蜻褐覃践鄙隆靜麸埴寃彍肭燠瓴筌徭蛉衲襁錆纊吆屛从匆卥屘宂岍揅揑撧氱炖筙舁䘐鎾鐠鬮黾刑澗刱帲剙隙傲塭台系仃尽当罗汇历欠只获巴签胡系脏巴胡胡冲辟只台发松胡须恶台团纤坛芘芘峄角辟阝𡋄㝡𢔛𢱍㒞祓篪靚蚋觵耙鱑祢干硎柃覈윗'
eastern_chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvw... |
# Copyright 2013-2022 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
"""
This test verifies that the Spack directory layout works properly.
"""
import os
import os.path
import pytest
import... |
import re
import html
import urllib
import w3lib.html
CHINESE_REGEX = re.compile('[\u4e00-\u9fa5]')
NUM_ENG_REGEX = re.compile('[a-zA-Z0-9]')
URL_REGEX = re.compile(
r'http[s]?://(?:[a-zA-Z]|[0-9]|[$-_@.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+',
re.IGNORECASE)
EMAIL_REGEX = re.compil... |
import chainer
from chainer.backends import cuda
from chainer import gradient_check
from chainer import testing
from chainer.testing import attr
from chainer.testing import condition
import numpy as np
import unittest
from light_head_rcnn import functions
class TestPSROIMaxPolling2D(unittest.TestCase):
def setU... |
from __future__ import annotations
from .lib import mcl
from .consts import FR_SIZE
from typing import Optional
import ctypes
class Fr(ctypes.Structure):
_fields_ = [("v", ctypes.c_ulonglong * FR_SIZE)]
def __init__(self, v: Optional[str, int]=None) -> None:
if isinstance(v, int):
self.set... |
import unittest
from cupy import testing
@testing.gpu
class TestBasic(unittest.TestCase):
_multiprocess_can_split_ = True
@testing.for_all_dtypes()
@testing.numpy_cupy_array_equal()
def test_copyto(self, xp, dtype):
a = testing.shaped_arange((2, 3, 4), xp, dtype)
b = xp.empty((2, 3,... |
# -*- coding: utf-8 -*-
"""
The following line helps to fix the Module Import issue when the Daemon tries
to call the main module under this directory from outside.
"""
from pathlib import Path
import sys
#
# Insert the current directory into the PYTHONPATH
sys.path.insert(0, Path(__file__).parent.as_posix()) |
"""
MicroPsi web server component, currently using the bottle framework for rendering content
"""
__author__ = 'joscha'
__date__ = '15.05.12'
|
# @Title: 前 K 个高频元素 (Top K Frequent Elements)
# @Author: KivenC
# @Date: 2020-09-07 22:37:32
# @Runtime: 64 ms
# @Memory: 16.5 MB
class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
return [num for num, _ in collections.Counter(nums).most_common(k)]
|
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
# SPDX-License-Identifier: MIT-0
__copyright__ = ('Copyright Amazon.com, Inc. or its affiliates. '
'All Rights Reserved.')
__version__ = '2.6.0'
__license__ = 'MIT-0'
__author__ = 'Akihiro Nakajima'
__url__ = 'https://github.com/aws-s... |
#!/usr/bin/env python3
# Copyright (c) 2013-2017 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
#
# Generate seeds.txt from Pieter's DNS seeder
#
NSEEDS=512
MAX_SEEDS_PER_ASN=2
MIN_BLOCKS = 615801
#... |
"""
- A project is a configuration (can be created, modified/updated, deleted)
- It is possible to switch between projects (every project operation needs)
the project unique id as part of the url
- Each user operation need the user id as part of the url
(for nor default value)
"""
from flask import Flask, rende... |
# terrascript/provider/PortOfPortland/activedirectory.py
# Automatically generated by tools/makecode.py (24-Sep-2021 15:10:54 UTC)
import terrascript
class activedirectory(terrascript.Provider):
"""A Terraform provider for Microsoft Active Directory"""
__description__ = "A Terraform provider for Microsoft A... |
# 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 ... |
from . import db
from flask_login import UserMixin
from sqlalchemy.sql import func
from flask_migrate import Migrate
from configparser import ConfigParser
config = ConfigParser()
config.read('Env_Settings.cfg')
token = config.get('SECRET_KEY', 'Session_Key')
#This file manages the columns defined in the dat... |
# 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! ***
from .. import _utilities
import typing
# Export this package's modules as members:
from .udpn_connection import *
|
import shutil
import tempfile
import sys
import os
import json
from decimal import Decimal
import time
from io import StringIO
from electrum_mona.storage import WalletStorage
from electrum_mona.json_db import FINAL_SEED_VERSION
from electrum_mona.wallet import (Abstract_Wallet, Standard_Wallet, create_new_w... |
"""Logging utilities for Certbot.
The best way to use this module is through `pre_arg_parse_setup` and
`post_arg_parse_setup`. `pre_arg_parse_setup` configures a minimal
terminal logger and ensures a detailed log is written to a secure
temporary file if Certbot exits before `post_arg_parse_setup` is called.
`post_arg_... |
"""
DELL EMC ECS API Data Collection Module.
"""
from influxdb import InfluxDBClient
import requests
from requests.auth import HTTPBasicAuth
class InfluxException(Exception):
pass
class InfluxUtility(object):
"""
Stores ECS Authentication Information
"""
def __init__(self, config, logger):
... |
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import absolute_import
import hashlib
import os
import sys
from pex import pex_warnings
from pex.common import atomic_directory, die, pluralize
from pex.inherit_path impo... |
# 2019-11-22 19:46:21(JST)
import sys
def main():
n, a, b, c, d = [int(x) for x in sys.stdin.readline().split()]
s = '#' + sys.stdin.readline().rstrip()
if '##' in s[a+1:c-1] or '##' in s[b+1:d-1]:
ans = 'No'
else:
if c < d:
ans = 'Yes'
else:
... |
# Cite from https://github.com/metrofun/E3D-LSTM
from functools import reduce
import copy
import operator
import torch
import torch.nn as nn
import torch.nn.functional as F
from .rnn_cell import E3DLSTMCell, ConvDeconv3d
from .utils import window
from tqdm import tqdm
import numpy as np
class E3DLSTM_Module(nn.Module... |
import random
from classes.Brief import get_my_brief
from classes.Cover import get_my_cover
from utils.misc.find_index_of_entry_with_id import find_index_of_entry_with_id
class Uploads():
def __init__(self):
self.data = self.uploads_default_values()
def uploads_default_values(self):
return {
... |
import json
import datetime
import re
from google.appengine.ext import ndb
from consts.event_type import EventType
from consts.playoff_type import PlayoffType
from helpers.tbavideo_helper import TBAVideoHelper
from helpers.youtube_video_helper import YouTubeVideoHelper
from models.event import Event
from models.team... |
# SPDX-License-Identifier: Apache-2.0
#
# The OpenSearch Contributors require contributions made to
# this file be licensed under the Apache-2.0 license or a
# compatible open source license.
import os
import unittest
from unittest.mock import MagicMock, call, patch
from git.git_repository import GitRepository
from m... |
import os
import sys
from .color import green, white, blue, start, alert, numbering
def TODO():
print(start + " ToDo List " + start)
print(alert + " This List Will Be Updated" + alert)
print("")
print(numbering(1) + white + " Add More Email Template (will always update)" + numbering(1))
print(numbering(2) + white... |
import numpy as np
import pandas as pd
import scipy.spatial
from sklearn.metrics.scorer import _BaseScorer
from autodc.components.utils.constants import CLS_TASKS
from sklearn.cluster import AgglomerativeClustering
from sklearn.metrics import accuracy_score
def choose_base_models_regression(predictions, labels, num_m... |
## Task 0.4
## Modules
class Module:
"""
Attributes:
_modules (dict of name x :class:`Module`): Storage of the child modules
_parameters (dict of name x :class:`Parameter`): Storage of the module's parameters
mode (string): Mode of operation, can be {"train", "eval"}.
"""
def... |
#!/usr/bin/env python
# coding:utf-8
__version__ = '1.1'
import sys
import os
import glob
import errno
import time
import struct
import collections
import binascii
import zlib
import itertools
import re
import fnmatch
import io
import random
import base64
import string
import hashlib
import threading
import thread
im... |
from __future__ import division, print_function, unicode_literals
from contextlib import contextmanager
from ctypes import byref, c_longlong, c_size_t, c_void_p
from .ffi import (
write_disk_new, write_disk_set_options, write_free, write_header,
read_data_block, write_data_block, write_finish_entry, ARCHIVE_E... |
from conans import ConanFile, tools, AutoToolsBuildEnvironment
import os
class GperfConan(ConanFile):
name = "gperf"
license = "GPL-3.0-or-later"
url = "https://github.com/conan-io/conan-center-index"
homepage = "https://www.gnu.org/software/gperf"
description = "GNU gperf is a perfect hash functio... |
import asyncio
import os
import asyncpg
from opentelemetry.instrumentation.asyncpg import AsyncPGInstrumentor
from opentelemetry.test.test_base import TestBase
from opentelemetry.trace import StatusCode
POSTGRES_HOST = os.getenv("POSTGRESQL_HOST", "localhost")
POSTGRES_PORT = int(os.getenv("POSTGRESQL_PORT", "5432")... |
from pytest import raises
from elasticsearch_dsl import result
def test_interactive_helpers(dummy_response):
res = result.Response(dummy_response)
hits = res.hits
h = hits[0]
rhits = "[<Result(test-index/company/elasticsearch): %s>, <Result(test-index/employee/42): %s...}>, <Result(test-index/employe... |
import json
import pytest
import unittest
from unittest import mock
from django.test import TestCase
from django.urls import reverse
from mixer.backend.django import mixer
# from services.anomalys import Anomalys
from anomaly.services.anomalys import Anomalys
from anomaly.models import AnomalyDefinition, Anomaly
@pyt... |
# Copyright 2018-present Open Networking Foundation
# SPDX-License-Identifier: Apache-2.0
# This Starlark rule imports the bmv2 shared libraries and headers since there is
# not yet any native support for Bazel in bmv2. The BMV2_INSTALL environment
# variable needs to be set, otherwise the Stratum rules which depend o... |
"""
Collection of tasks for sending notifications.
Useful for situations in which state handlers are inappropriate.
"""
from prefect.tasks.notifications.email_task import EmailTask
from prefect.tasks.notifications.slack_task import SlackTask
from prefect.tasks.notifications.pushbullet_task import PushbulletTask
__all... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
#
# Configuration file for the Sphinx documentation builder.
#
# This file does only contain a selection of the most common options. For a
# full list see the documentation:
# http://www.sphinx-doc.org/en/master/config
# -- Path setup --------------------------------------------------------------
# If extensions (or ... |
from sharpy.plans.acts import ActBase
from sc2 import AbilityId
class NoDoubleOrders(ActBase):
"""Don't use this for terrans, seriously!"""
def __init__(self):
super().__init__()
self.last_cancel = -1
async def execute(self) -> bool:
for unit in self.ai.structures:
if... |
def test1(x,y):
print("test1") |
# Generated by Django 3.2.9 on 2021-12-03 09:40
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('hotels_app', '0009_remove_review_reservation'),
]
operations = [
migrations.AlterField(
model_name='reservation'... |
#!/usr/bin/env python3
# Copyright lowRISC contributors.
# Licensed under the Apache License, Version 2.0, see LICENSE for details.
# SPDX-License-Identifier: Apache-2.0
r"""Command-line tool to autogenerate boilerplate DV testbench code extended from dv_lib / cip_lib
"""
import argparse
import gen_agent
import gen_en... |
from binascii import hexlify, unhexlify
import hashlib
import sys
import string
import logging
log = logging.getLogger(__name__)
""" Default Prefix """
PREFIX = "GPH"
known_prefixes = [
PREFIX,
"BTS",
"MUSE",
"TEST",
"STM",
"GLX",
"GLS",
"LLC",
]
class Base58(object):
"""Base58 b... |
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits import mplot3d
from mpl_toolkits.mplot3d.axes3d import get_test_data
from mpl_toolkits.mplot3d import Axes3D
import pickle
class ANFIS():
def __init__(self, no_rules=1):
self.no_rules = no_rules
self.p = np.random.randn(no_rules... |
"""A transformer for gen3 project,reads diagnosiss bcc, writes to DEFAULT_OUTPUT_DIR."""
import hashlib
import os
import json
from gen3_etl.utils.ioutils import reader
from defaults import DEFAULT_OUTPUT_DIR, DEFAULT_EXPERIMENT_CODE, DEFAULT_PROJECT_ID, default_parser, default_diagnosis, default_case, emitter, missi... |
import random
import re
import datetime
import demjson
import requests
import time
import sys
sys.path.append('..')
from configure.settings import DBSelector, send_from_aliyun
from common.BaseService import BaseService
import warnings
warnings.filterwarnings("ignore")
now = datetime.datetime.now()
TODAY = now.strfti... |
"""
MIT License
Copyright (c) 2016 - Edward Wells
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... |
import shutil
import os
# Assumes this folder structure.
# Folder Variable
# ---------------------------------------
# etl etl_dir
# arduino arduino_dir
# include include_dir
# etl-arduino etl_arduino_dir
# src etl_arduino_src_dir
print('... |
import os
import sys
import time
import shutil
import random
import numpy as np
import pandas as pd
import geopandas as gpd
from map2loop.topology import Topology
from map2loop import m2l_utils
from map2loop import m2l_geometry
from map2loop import m2l_interpolation
from map2loop import m2l_map_checker
from map2loop.m... |
# -*- coding: utf-8 -*-
"""setup script"""
import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="pyqttable",
version="0.0.2",
author="Tongyan Xu",
author_email="tyxu18@gmail.com",
description="A simple configurable table widget based on PyQt... |
# Copyright 2016 The TensorFlow Authors. All Rights Reserved.
# Modifications copyright (C) 2018 Uber Technologies, Inc.
# Modifications copyright (C) 2019 Intel Corporation
# Modifications copyright (C) 2020, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
#... |
# Lint as: python3
# Copyright 2020 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 ... |
import networkx as nx
N, Q, *l = map(int, open(0).read().split())
A = l[0:2 * (N - 1):2]
B = l[1:2 * (N - 1):2]
C = l[2 * (N - 1)::2]
D = l[2 * (N - 1) + 1::2]
G = nx.Graph()
G.add_nodes_from(range(1, N + 1))
edges = [(A[i], B[i]) for i in range(len(A))]
G.add_edges_from(edges) # 一括で追加
length = nx.single_source_sh... |
# generated by 'xml2py'
# flags '-c -d -v C:\test_h\MvCameraControl.xml -o MvCameraControl_header.py'
from ctypes import *
STRING = c_char_p
PixelType_Gvsp_BayerBG12 = 17825811
MV_TRIGGER_SOURCE_LINE1 = 1
PixelType_Gvsp_Mono8_Signed = 17301506
MV_BALANCEWHITE_AUTO_ONCE = 2
PixelType_Gvsp_BayerGB8 = 17301514
MV_BALAN... |
#!/usr/bin/env python
"""
@package mi.dataset.parser.adcpa_m_glider
@file marine-integrations/mi/dataset/parser/adcpa_m_glider.py
@author Jeff Roy
@brief Particle classes for the moas_gl_adcpa dataset driver
These particles are parsed by the common PD0 Parser and
Abstract particle class in file adcp_pd0.py
Re... |
#
# chemicalFormulas.py
#
# Copyright (c) 2003,2019 Paul McGuire
#
import pyparsing as pp
atomicWeight = {
"O": 15.9994,
"H": 1.00794,
"Na": 22.9897,
"Cl": 35.4527,
"C": 12.0107,
}
digits = "0123456789"
# Version 1
element = pp.Word(pp.alphas.upper(), pp.alphas.lower(), max=2)... |
# Generated by Django 2.0.4 on 2018-04-18 14:22
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='IncomeMail',
fields=[
... |
import time
import traceback
import sharedfunc
from dbClass import dbCalls
from dbPGClass import dbPGCalls
from tnClass import tnCalls
from otherClass import otherCalls
from verification import verifier
class controller(object):
def __init__(self, config, db = None):
self.config = config
if db == ... |
from bs4 import BeautifulSoup
import requests
import collections
def scrape(url): #input url, returns beautifulsoup object
headers = {
"user-agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5)",
"accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"accept-charset": "ISO-8859-1,utf-8... |
# Copyright 2018 The TensorFlow Authors All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... |
# --------------
import json
from collections import Counter
with open(path) as f:
data = json.load(f)
#data
# Code starts here
# # Can you find how many deliveries were faced by batsman `SC Ganguly`.
first_inning_deliveries = data['innings'][0]['1st innings']['deliveries']
def number_of_delivers(player):
... |
#! /Users/gabriel.hernandez/.virtualenvs/better/bin/python
from lifxlan import LifxLAN
import time
aqua = (180, 94.31, 100)
orag = (37, 100, 100)
pink = (308, 81.18, 100)
max_range = 65535
hue_range = 360
sat_bri_r = 100
FPS = 60
# dt is the time delta in seconds (float).
class LaserCatTheme():
def __init_... |
from typing import Any, Dict
from pandas.core.series import Series
from ..caller_base import CallerBase
from ..error.illegal_attr_checker import IllegalAttrChecker
from .graph_object import Graph
class GraphExportRunner(CallerBase, IllegalAttrChecker):
def __call__(self, G: Graph, **config: Any) -> Series:
... |
# coding=utf-8
from __future__ import absolute_import, division, print_function, unicode_literals
import wrapt
from bottle import request, response
import scout_apm.core
from scout_apm.core.config import scout_config
from scout_apm.core.tracked_request import TrackedRequest
from scout_apm.core.web_requests import (
... |
# -*- coding: utf-8 -*-
"""This module contains utilities to improve waveform plotting in python.
"""
import numpy as np
import scipy.interpolate as interp
from matplotlib.lines import Line2D
from matplotlib.figure import Figure
from matplotlib.text import Annotation
import matplotlib.pyplot as plt
from ..math impo... |
import json
def buildC(code: str) -> str:
data = {
"code": code,
"compiler": "gcc-head"
}
return json.dumps(data)
def buildBash(code: str) -> str:
data = {
"code": code,
"compiler": "bash"
}
return json.dumps(data)
def buildCSharp(code... |
"""
This is an implementation of R2D2(Soft Actor Critic ver).
See https://openreview.net/pdf?id=r1lyTjAqYX and https://arxiv.org/abs/1801.01290
"""
import torch
import torch.nn as nn
from machina import loss_functional as lf
from machina import logger
from machina.traj import traj_functional as tf
def train(traj,
... |
import pickle
from dataclasses import dataclass
import pytest
from datetime import timedelta
from temporal.api.common.v1 import Payload
from temporal.conversions import METADATA_ENCODING_KEY
from temporal.converter import DataConverter
from temporal.workflow import workflow_method, WorkflowClient, Workflow
from tempo... |
# -*- coding: utf-8 -*-
import tweepy, json, abc, pickle, time
import ConfigParser
from objectpath import Tree
from threading import Thread
from feature_process import FeatureList, FeatureMapping
from text_processing import TextUtil, TextProcessing
import feature_process
from sklearn.cross_validation import train_test_... |
import socket
import re
from selenium import webdriver
import sys
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.action_chains import ActionChains
from selenium.common.exceptions import WebDriverException
import time
import os
from QUANTAXIS.QAUtil import (DATABASE)
'''
https://www.cn... |
# Copyright 2021 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... |
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Tests for miscellaneous behaviors of the top-level L{twisted} package (ie, for
the code in C{twisted/__init__.py}.
"""
from __future__ import division, absolute_import
import re
import sys
from types import ModuleType, FunctionType
from twi... |
version = '1.6.0'
|
import numpy as np
import pytest
import aesara
from aesara import function
from aesara import tensor as aet
from aesara.assert_op import Assert
from aesara.compile.mode import Mode
from aesara.configdefaults import config
from aesara.gradient import grad
from aesara.graph.basic import applys_between
from aesara.graph.... |
import os, os.path
import random
import string
import sqlite3
import time
import cherrypy
import json
import re
from string import digits
DB_STRING = "ibc.db"
def dict_factory(cursor, row):
d = {}
for idx, col in enumerate(cursor.description):
d[col[0]] = row[idx]
return d
class IbcWebMain(object):
@cher... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.