text stringlengths 2 999k |
|---|
import MenuMaker
from MenuMaker import indent, writeFullMenu
menuFile = "~/.config/openbox/menu.xml"
def _map(x) :
for d, s in (("&", "&"), ("\'", "\"")) :
x = x.replace(s, d)
return x
class Sep(object) :
def emit(self, level) :
return ['%s<separator/>' % indent(level)]
class App(object) ... |
from logging import getLogger
from aiohttp import ClientSession
class PostmarkClient(object):
"""
Example:
curl "https://api.postmarkapp.com/email" \
-X POST \
-H "Accept: application/json" \
-H "Content-Type: application/json" \
-H "X-Postmark-Server-Token: server token... |
# coding=utf-8
# @File : Using_API.py
# @Author: PuJi
# @Date : 2018/4/3 0003
import sys
from fileHelper.ipfs_module import ulord_transmitter
from dbHelper import dbhelper
from fileHelper import util
import json
import requests
# metadata = {"license": "ULORD Inc", "description": "", # 1
# "languag... |
from datetime import datetime
from app import db
from app.models import Vote
from app.services.event_service import check_vote_event
def vote_exists(user_id, idea_id):
return get_vote(user_id, idea_id) is not None
def get_vote(user_id, idea_id):
return db.session.query(Vote).filter_by(user_id=user_id, idea... |
# -*- coding: utf-8 -*-
import logging
import sys
import click
import click_config_file
from coloredlogs import ColoredFormatter
from . import __version__
from .engine import USBQEngine
from .opts import add_options
from .opts import network_options
from .opts import pcap_options
from .opts import standard_plugin_opt... |
# Copyright (c) Microsoft Corporation.
#
# 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 wri... |
import logging
# General Settings
CONTROL_PHONES = ['4912312312312',]
LOG_DIR = '/var/log/smsgateway/'
LOG_STD_LEVEL = logging.DEBUG
SMS_DIR = '/var/spool/sms/outgoing/'
SYSTEMCTL_PATH = '/bin/systemctl' # Use 'which systemctl' to find out
REBOOT_PATH = '/sbin/reboot'
# When using a ramdisk you can use the script i... |
# -*- coding: utf-8 -*-
"""
Module for formatting output data in HTML.
"""
from collections import OrderedDict
from textwrap import dedent
from pandas._config import get_option
from pandas.compat import lzip
from pandas.core.dtypes.generic import ABCMultiIndex
from pandas import option_context
from pandas.io.comm... |
import numpy as np
import pandas as pd
import tensorflow as tf
from tensorflow.keras.preprocessing.text import Tokenizer
from tensorflow.keras import Input
from keras.layers.core import Activation, Dropout, Dense
from keras.layers import Flatten, LSTM, Bidirectional, Concatenate
from keras.layers.embeddings import E... |
from datetime import datetime, date
from typing import List, Optional
from cumulusci.tasks.bulkdata.step import DataOperationType
def adjust_relative_dates(
mapping,
context,
record: List[Optional[str]],
operation: DataOperationType,
):
"""Convert specified date and time fields (in ISO format) rel... |
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import absolute_import
from builtins import * # NOQA
from future import standard_library
standard_library.install_aliases() # NOQA
import collections
import itertools
from logging import getL... |
# To use this code, make sure you
#
# import json
#
# and then, to convert JSON from a string, do
#
# result = stars_add_response_from_dict(json.loads(json_string))
from dataclasses import dataclass
from typing import Optional, Any, TypeVar, Type, cast
T = TypeVar("T")
def from_bool(x: Any) -> bool:
as... |
import tensorflow as tf
from functools import partial
import os
from shutil import copyfile
from datetime import datetime
import skimage as sk
import numpy as np
from time import time
from fasterflow import train
from fasterflow import dataset
from fasterflow import utils
from fasterflow import evaluate
import config... |
"""
A* algorithm
Author: Weicent
randomly generate obstacles, start and goal point
searching path from start and end simultaneously
"""
import numpy as np
import matplotlib.pyplot as plt
import math
show_animation = True
class Node:
"""node with properties of g, h, coordinate and parent node"""
def __init_... |
import sys
import os
from io import StringIO
import textwrap
from distutils.core import Distribution
from distutils.command.build_ext import build_ext
from distutils import sysconfig
from distutils.tests.support import (TempdirManager, LoggingSilencer,
copy_xxmodule_c, fixup_build_... |
#!/usr/bin/env python3
# Copyright (c) 2016 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.
"""Tests for json_values_converter.py.
It tests json_values_converter.py.
"""
import argparse
import os
import sys
def Compare... |
"""
GARS Field is a toolkit for generating Global Area Reference grids
"""
from .edgarsgrid import EDGARSGrid # noqa: F401
from .field import GARSField # noqa: F401
from .garsgrid import GARSGrid # noqa: F401
from .gedgarsgrid import GEDGARSGrid # noqa: F401
|
"""
player
"""
from __future__ import absolute_import, division, print_function, unicode_literals
import logging
from mcedit2.rendering.chunkmeshes.entity.biped import ModelBiped
from mcedit2.rendering.chunkmeshes.entity.modelrenderer import ModelRenderer
log = logging.getLogger(__name__)
class ModelPlayer(Mode... |
# Copyright 2017 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... |
from abc import ABC
import time
import timeit
class Tracker(ABC):
def __init__(self, tracker_type, timed=False):
self.type = tracker_type
self.tracker = self.type()
self.timed = timed
if timed:
self.time = 0.
self.ptime = 0.
self.f... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.5 on 2016-04-30 16:57
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('main', ... |
from dicom_parser.utils.sequence_detector.sequences.mr.func.bold import (
BOLD_RULES,
)
from dicom_parser.utils.sequence_detector.sequences.mr.func.fieldmap import (
FUNCTIONAL_FIELDMAP_RULES,
)
from dicom_parser.utils.sequence_detector.sequences.mr.func.sbref import (
FUNCTIONAL_SBREF_RULES,
)
MR_FUNCTION... |
#!/usr/bin/env python
import argparse
import sys
import os
from datetime import datetime, timedelta
import pandas as pd
import yfinance as yf
from alpha_vantage.timeseries import TimeSeries
from prompt_toolkit.completion import NestedCompleter
from gamestonk_terminal import config_terminal as cfg
from gamestonk_term... |
import ujson
import sys
import argparse
import re
import spacy
spacy_nlp = spacy.load('en_core_web_sm')
# extra split referred to allenai docqa
extra_split_chars = ("-", "£", "€", "¥", "¢", "₹", "\u2212", "\u2014", "\u2013", "/", "~", "(", ")", "+", "^", "=", "\[", "\]", "'",
'"', "'", "\ud01C", "\u2019", "\u201D", ... |
# Generated by Django 3.2 on 2021-04-15 19:07
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('api', '0001_initial'),
]
operations = [
migrations.AlterModelOptions(
name='lesson',
options={'ordering': ['day', 'timetable']... |
import numpy as np
import pickle
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
selectors = pickle.load( open( 'l2_l1_reg/020', 'rb' ) )
#we throw out the biases because they're not important for pruning
weights = [s for s in selectors if len(s.shape)==4]
weights = [w.reshape((w.shape[0],w.shape[... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
import random
import numpy as np
from activators import SigmoidActivator, IdentityActivator
# 全连接层实现类
class FullConnectedLayer(object):
def __init__(self, input_size, output_size,
activator):
'''
构造函数
input_size: 本层输入向量的维度
... |
"""
Implementations for `Provisioning` classes
Copyright 2015 BlazeMeter 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 appl... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import re
import sys
import time
import pytest
import requests
import ray
@pytest.mark.skipif(
sys.version_info < (3, 5, 3), reason="requires python3.5.3 or higher")
def test_get_webui(shutdown_only):
... |
from django.contrib import admin
# Register your models here.
from .models import Users
class UserAdmin(admin.ModelAdmin):
list_display = ['id', 'username', 'age', 'phone', 'email']
admin.site.register(Users, UserAdmin)
|
"""
AMPAREX Rest API Documentation
This is the description of the AMPAREX Rest API. All REST calls plus the corresponding data model are described in this documentation. Direct calls to the server are possible over this page.<br/>Following steps are needed to use the API:<br/><br/>1. Get the ... |
# Copyright 2021 Dynatrace LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed t... |
#!/usr/bin/env python3
# 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 argparse
import os
from bs4 import BeautifulSoup
js_scripts = """
<script type="text/javascript" id="document... |
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from __future__ import absolute_import
from builtins import * # NOQA
from future import standard_library
standard_library.install_aliases() # NOQA
import copy
from logging import getLogger
import chainer
fr... |
# encoding=utf8
"""Flower pollination algorithm module."""
import numpy as np
from scipy.special import gamma as Gamma
from WeOptPy.algorithms.interfaces import Algorithm
from WeOptPy.util import reflect_repair
__all__ = ['FlowerPollinationAlgorithm']
class FlowerPollinationAlgorithm(Algorithm):
r"""Implementati... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
"""Support VO Simple Cone Search capabilities."""
from __future__ import absolute_import, division, print_function, unicode_literals
# STDLIB
import warnings
# THIRD-PARTY
import numpy as np
# LOCAL
from . import vos_catalog
from .async import AsyncBase... |
# Copyright (c) 2020 ING Bank N.V.
#
# 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, distr... |
from __future__ import print_function, unicode_literals, absolute_import
import codecs
import contextlib
import itertools
import os
import re
import sys
try:
from StringIO import StringIO
except ImportError:
from io import StringIO
# Check if a generator has at least one element.
#
# Since we don't want to ... |
# -*- coding: utf-8 -*-
# PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
# https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
from ccxt.async_support.base.exchange import Exchange
import math
from ccxt.base.errors import ExchangeError
from ccxt.base.errors import A... |
import json
import datetime
import os
from google.cloud import tasks_v2
from google.cloud.bigquery.reservation_v1 import ReservationServiceClient
from google.cloud.bigquery.reservation_v1 import CapacityCommitment
from google.protobuf import timestamp_pb2
"""
env:
delete_url="https://us-central1-my-test-project.clou... |
# Copyright 2017 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 2010 United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration.
# 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 ... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from sklearn import metrics
import tensorflow as tf
from tensorflow.contrib import learn
# from SKFLOW
### Download and load MNIST data.
mnist = learn.datasets.load_dataset('mnist')
### Convolutional networ... |
import numpy as np
from traffic_simulator import TrafficSim
if __name__ == "__main__":
env = TrafficSim(["./ngsim"])
obs = env.reset()
act = np.random.normal(0, 1, size=(2,))
obs, rew, done, info = env.step(act)
print("finished")
env.close()
|
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not u... |
from os import path
from ga4stpg.condition import BestKnownReached, Stagnation
from ga4stpg.customevol import GeneticEvolution as Evolution
from ga4stpg.customevol import GeneticPopulation as GPopulation
from ga4stpg.graph import ReaderORLibrary
from ga4stpg.graph.util import is_steiner_tree
from ga4stpg.no... |
import socket
import sys
import struct
# Erreursc
UDP_TIMEOUT = "UDP timeout"
TCP_TIMEOUT = "TCP timeout"
PING_TIMEOUT = "PING Timeout"
ICMP_TIMEOUT = "ICMP Timeout"
PORT_ERROR = "Port unreachable"
UDP_ERROR = "UDP packet failed"
HOP_ERROR = "No answer"
DEST_UNREACHABLE_MSG = "Dest unreach"
# Trace constantes
PORT ... |
import importlib
from collections import OrderedDict
from django.conf import settings
class ProviderRegistry(object):
def __init__(self):
self.provider_map = OrderedDict()
self.loaded = False
def get_list(self, request=None):
self.load()
return [provider_cls(request) for prov... |
import simpy
from components.base.bus.abst_bus_can import AbstractCANBus
import config.timing_registration as time
from tools.general import General as G, RefList, General
from config import project_registration as proj, can_registration
from tools.ecu_logging import ECULogger as L, ECULogger
from io_processing.survei... |
from treq.client import HTTPClient
from _utils import print_response
from twisted.internet.task import react
from twisted.web.client import Agent
def make_custom_agent(reactor):
return Agent(reactor, connectTimeout=42)
def main(reactor, *args):
agent = make_custom_agent(reactor)
http_client = HTTPClient(a... |
from eth_utils import to_set
from eth import constants
from eth.utils.address import (
force_bytes_to_address,
)
THREE = force_bytes_to_address(b'\x03')
@to_set
def collect_touched_accounts(computation):
"""
Collect all of the accounts that *may* need to be deleted based on EIP161:
https://github... |
# This code starts recording audio, registers to the 'SourceTrackDataMessage' event to get the sound localization data back from Misty
from mistyPy.Robot import Robot
from mistyPy.Events import Events
from mistyPy.EventFilters import EventFilters
import requests
import json
import time
# The callback function must on... |
"""
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
The version of the OpenAPI document: 20220523
Generated by: https://openapi-generator.tech
"""
import re # noqa: F401
import sys # noqa: F401
from pokeapiclient.api_client impo... |
"""Conversions between various entites."""
from vortexasdk.conversions.corporations import convert_to_corporation_ids
from vortexasdk.conversions.geographies import convert_to_geography_ids
from vortexasdk.conversions.products import convert_to_product_ids
from vortexasdk.conversions.vessels import convert_to_vessel_id... |
"""
Functions for manipulating wiki-text.
Unless otherwise noted, all functions take a unicode string as the argument
and return a unicode string.
"""
#
# (C) Pywikibot team, 2008-2022
#
# Distributed under the terms of the MIT license.
#
import datetime
import re
from collections import OrderedDict, namedtuple
from ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import simplejson as json
from alipay.aop.api.FileItem import FileItem
from alipay.aop.api.constant.ParamConstants import *
from alipay.aop.api.domain.AlipayPassTemplateAddModel import AlipayPassTemplateAddModel
class AlipayPassTemplateAddRequest(object):
def __in... |
import logging
import pytest
from ocs_ci.framework.pytest_customization.marks import tier1, skipif_no_kms
from ocs_ci.framework.testlib import MCGTest
from ocs_ci.ocs import constants, defaults
from ocs_ci.ocs.resources import pod
logger = logging.getLogger(__name__)
@skipif_no_kms
class TestNoobaaKMS(MCGTest):
... |
# mysql/mysqldb.py
# Copyright (C) 2005-2021 the SQLAlchemy authors and contributors
# <see AUTHORS file>
#
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""
.. dialect:: mysql+mysqldb
:name: mysqlclient (maintained fork of MySQL-Py... |
from abc import ABC, abstractmethod
from project.baked_food.baked_food import BakedFood
from project.core.validator import Validator
from project.drink.drink import Drink
class Table(ABC):
def __init__(self, table_number: int, capacity: int):
self.table_number = table_number
self.capacity = capac... |
import serial
# Note for version one - using USB connection
# device = '/dev/ttyUSB0'
baud = 9600
device = '/dev/ttyS0'
ser = serial.Serial(device,9600)
while True:
line=ser.readline()
line = line.strip()
if line:
print(line)
|
import broker
import re
from stix2 import Indicator, Sighting
from threatbus.data import (
Operation,
Subscription,
ThreatBusSTIX2Constants,
Unsubscription,
)
from threatbus.stix2_helpers import is_point_equality_ioc, split_object_path_and_value
from typing import Union
from urllib.parse import urlparse... |
import os
import re
import json
import typing
import argparse
def check_special_char(string: str) -> bool:
"""
Check if a string contains special characters.
:param string: The input string.
:return: True if there are special characters.
"""
# regex = re.compile('[@_!#$%^&*()<>?/\\|}{~:]')
... |
# input_lines = '''\
# (3x3)XYZ
# X(8x2)(3x3)ABCY
# (27x12)(20x12)(13x14)(7x10)(1x12)A
# (25x3)(3x3)ABC(2x3)XY(5x2)PQRSTX(18x9)(3x2)TWO(5x7)SEVEN'''.splitlines()
input_lines = open('input.txt')
NORMAL, MARKER, REPEAT = list(range(3))
def count_decompress(line):
result = 0
chars = iter(line)
state = NORMA... |
from spira.core.typed_list import TypedList
from spira.core.transformable import Transformable
from spira.core.parameters.variables import FloatParameter
from spira.core.parameters.descriptor import ParameterDescriptor
from spira.core.parameters.restrictions import RestrictType
from spira.yevon.geometry.ports.base impo... |
# AUTO-GENERATED by tools/checkspecs.py - DO NOT EDIT
from ....testing import assert_equal
from ..model import SegStats
def test_SegStats_inputs():
input_map = dict(annot=dict(argstr='--annot %s %s %s',
mandatory=True,
xor=(u'segmentation_file', u'annot', u'surf_label'),
),
args=dict(argstr='%s',
... |
import os
import subprocess
import sys
from datetime import datetime, timedelta
import pandas as pd
import numpy as np
def get_main_head_rev(repo_path):
cdr = os.getcwd()
os.chdir(repo_path)
command = "git show-ref --heads -s"
process = subprocess.Popen(
command, shell=True,
stdout=su... |
"""django_books 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-... |
import pytest
import torch
import torch_optimizer as optim
def assert_sparse_not_supported(optimizer_class, err_msg=None):
param = torch.randn(1, 1).to_sparse().requires_grad_(True)
grad = torch.randn(1, 1).to_sparse()
param.grad = grad
optimizer = optimizer_class([param])
optimizer.zero_grad()
... |
# Scientific Library
from pandas import HDFStore
# Standard Library
import json
from pathlib import Path
import warnings
# Third Party
import pyarrow as pa
import pyarrow.dataset as ds
import pyarrow.parquet as pq
from tqdm.auto import tqdm
# First Party
from metadamage import utils
class Parquet:
def __init__... |
from _struct import *
from _struct import _clearcache
|
# coding: utf-8
from __future__ import absolute_import
from datetime import date, datetime # noqa: F401
from typing import List, Dict # noqa: F401
from swagger_server.models.base_model_ import Model
from swagger_server import util
class InventoryItem(Model):
"""NOTE: This class is auto generated by the swagg... |
from workalendar.core import WesternCalendar, ChristianMixin
from workalendar.core import MON, TUE, FRI
from datetime import date, timedelta
class Australia(WesternCalendar, ChristianMixin):
"Australia"
include_good_friday = True
include_easter_monday = True
include_queens_birthday = False
include... |
'''
Title : Print Function
Subdomain : Introduction
Domain : Python
Author : codeperfectplus
Created : 17 January 2020
'''
|
import random
import threading
from threading import Thread, Event
import unittest
import uuid
import logger
import time
import string
from basetestcase import BaseTestCase
from couchbase_helper.document import DesignDocument, View
from membase.api.rest_client import RestConnection
from membase.helper.spatial_helper i... |
"""
Given a string, determine if it is a palindrome,
considering only alphanumeric characters and ignoring cases.
For example,
"A man, a plan, a canal: Panama" is a palindrome.
"race a car" is not a palindrome.
Note:
Have you consider that the string might be empty?
This is a good question to ask during an interview.
F... |
# -*- coding: utf-8 -*-
"""
Training a Classifier
=====================
This is it. You have seen how to define neural networks, compute loss and make
updates to the weights of the network.
Now you might be thinking,
What about data?
----------------
Generally, when you have to deal with image, text, audio or video... |
from collections.abc import MutableSequence
import re
from textwrap import dedent
from ._grouping import grouping_len, map_grouping
from .development.base_component import Component
from . import exceptions
from ._utils import patch_collections_abc, stringify_id, to_json
def validate_callback(outputs, inputs, state,... |
# Module def
|
# Extended Euclid's Algorithm for Modular Multiplicative Inverse
def euclidean_mod_inverse(a, b):
temp = b
# Initialize variables
t1, t2 = 0, 1
if b == 1:
return 0
# Perform extended Euclid's algorithm until a > 1
while a > 1:
quotient, remainder = divmod(a, b)
a, b = ... |
from application import db
#
#Create your own models here and they will be imported automaticaly. or
#use a model per blueprint.
class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True)
email = db.Column(db.String(80), unique=True)
password =... |
from __future__ import print_function
import tensorflow as tf
import numpy as np
from scipy import ndimage
from scipy.spatial.distance import euclidean
from sklearn import metrics
import TensorflowUtils as utils
import read_Data_list as scene_parsing
import BatchDatsetReader as dataset
from six.moves import xrange
I... |
from awscrt import io, mqtt, auth, http
from awsiot import mqtt_connection_builder
import json
class MQTTManager:
"""Keeps the connections to MQTT, used for sending and receiving messages."""
mqtt_connection = None
def __init__(self, cert_path: str, key_path: str, root_path: str, port: int, client_id: st... |
import os
import logging
import json
import re
DOC_PACKAGE_FILENAME = "C:/github/azure-docs-sdk-java/package.json"
def main():
logging.basicConfig(level=logging.INFO)
with open(DOC_PACKAGE_FILENAME, 'r', encoding='utf-8') as f:
lines = f.readlines()
exclude_package_defined = False
implemen... |
import base64
import json
import traceback
from typing import Any, List, Dict
from opus import Asset
from util.event_emitter import EventEmitter
import websockets
from websockets.server import WebSocketServerProtocol
class ComponentPeer(EventEmitter):
"""
Base class for peers which accepts actions.
Para... |
#!/usr/bin/env python
"""
Copyright (c) 2016 Pimoroni
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, pub... |
from django.test import TestCase
from django.contrib.auth import get_user_model
class CustomUserTests(TestCase):
def test_create_user(self):
User= get_user_model()
user= User.objects.create_user(
username='Nelg',
email='nelg@liamg.com',
password='testpass123',
... |
def helperFunction(self, root, result):
if root:
self.helperFunction(root.left, result)
result.append(root.val)
self.helperFunction(root.right, result)
def inorderTraversal(self, root):
"""
:type root: TreeNode
:rtype: List[int]
"""
result = []
self.helperFunction(ro... |
#!/usr/bin/env python3
from test_framework.test_framework import earn_save_invest_repeatTestFramework
from test_framework.util import *
"""
Simple test checking chain movement after v5 enforcement.
"""
class MiningV5UpgradeTest(earn_save_invest_repeatTestFramework):
def set_test_params(self):
self.num_n... |
N, *A = map(int, open(0).read().split())
A.sort()
s = sum(A)
result = 0
for i in range(N):
a = A[i]
s -= a
result += s - a * (N - i - 1)
print(result)
|
# Generated by Django 2.1.7 on 2019-04-30 13:39
import diventi.accounts.models
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('accounts', '0112_auto_20190430_1539'),
]
operations = [
migrations.AlterModelManagers(
name='diventiuser'... |
#!/usr/bin/env python
# encoding: utf-8
'''
@author: caroline
@license: (C) Copyright 2019-2022, Node Supply Chain Manager Corporation Limited.
@contact: caroline.fang.cc@gmail.com
@software: pycharm
@file: zjk2_transfer.py
@time: 2020/1/1 4:59 下午
@desc:
'''
import json
import logging
import threading
from datetime imp... |
# coding: utf-8
# Copyright (c) 2016, 2022, 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... |
# -*- coding: utf-8 -*-
# Copyright (c) 2019, Ben Glazier and contributors
# For license information, please see license.txt
from frappe.model.document import Document
class OnlineSellingItem(Document):
pass
|
# This file was automatically generated by SWIG (http://www.swig.org).
# Version 1.3.31
#
# Don't modify this file, modify the SWIG interface instead.
# This file is compatible with both classic and new-style classes.
import _cchardet
import new
new_instancemethod = new.instancemethod
try:
_swig_property = propert... |
# Aula 13 (Estrutura de Repetição for)
for c in range(1, 50):
if c % 2 == 0:
print(c, end=' ')
print('Acabou.')
|
# -*- coding: utf-8 -*-
#
# 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
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import os
impo... |
# Generated by Django 2.0.9 on 2018-12-28 12:39
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('bucket', '0002_auto_20181228_2135'),
]
operations = [
migrations.AlterFiel... |
import base64
def get_data_from_file(file_path: str):
"""
Get data from file and base64 encode it
"""
if file_path:
with open(file_path, "rb") as stream:
file_data = stream.read()
data = base64.b64encode(file_data).decode("utf-8")
return data
|
"""
inflateorg.py
Inflate or shrink the membrane to resolve clash between membrane and protein.
Handles the primary functions
"""
import os
import shutil
from subprocess import call
from pkg_resources import resource_filename
import MDAnalysis as mda
import numpy as np
os.environ["GMX_MAXBACKUP"] = "-1"
gromacs = '... |
n = int(input())
for i in range(1, n + 1):
tsum = sum(map(int, input().split()))
print("Case #{}: {}".format(i, tsum))
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.