text stringlengths 2 999k |
|---|
from pathlib import Path
from aoc.utils import load_data, profiler
@profiler
def main():
data = list(map(int, (load_data(test=False)[0].split(","))))
timer = {i: 0 for i in range(9)}
for time in data:
timer[time] += 1
for _ in range(256):
today = {i: 0 for i in range(9)}
toda... |
from localization import L
from PyQt6.QtCore import *
from PyQt6.QtGui import *
from PyQt6.QtWidgets import *
from resources.fonts import QXFontDB
from xlib import qt as lib_qt
from ... import backend
class QBCFaceSwapViewer(lib_qt.QXCollapsibleSection):
"""
"""
def __init__(self, backed_weak_heap : bac... |
""" generic datetimelike tests """
import numpy as np
import pytest
import pandas as pd
import pandas.util.testing as tm
from .common import Base
class DatetimeLike(Base):
def test_argmax_axis_invalid(self):
# GH#23081
rng = self.create_index()
with pytest.raises(ValueError):
... |
# This file based on : https://jmetzen.github.io/notebooks/vae.ipynb
# pylint: disable = C0103, C0111, C0301, R0913, R0903, R0914, R0902
import tensorflow as tf
import utils
class Hparams(object):
def __init__(self):
self.n_hidden_recog_1 = 500 # 1st layer encoder neurons
self.n_hidden_recog_2 ... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import pickle
import torch.utils.data as data
from ACT_utils.ACT_utils import tubelet_in_out_tubes, tubelet_has_gt
class BaseDataset(data.Dataset):
def __init__(self, opt, mode, ROOT_DATASET_... |
# The MIT License (MIT)
#
# Copyright (c) 2013 Victor Chinedu
#
# 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, mo... |
"""System tests for fetching Google BigQuery credentials."""
try:
import mock
except ImportError: # pragma: NO COVER
from unittest import mock
import pytest
from pandas_gbq import auth
def _check_if_can_get_correct_default_credentials():
# Checks if "Application Default Credentials" can be fetched
... |
import enum
import logging
import typer
from playlist_organizer.client.auth.deezer import DeezerAuthenticator
from playlist_organizer.client.auth.settings import DeezerAuthSettings, SpotifyAuthSettings
from playlist_organizer.client.auth.spotify import SpotifyAuthenticator
from playlist_organizer.client.deezer.client... |
import pyaf.Bench.TS_datasets as tsds
import pyaf.tests.artificial.process_artificial_dataset as art
art.process_dataset(N = 128 , FREQ = 'D', seed = 0, trendtype = "MovingMedian", cycle_length = 30, transform = "BoxCox", sigma = 0.0, exog_count = 0, ar_order = 0); |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.29 on 2020-12-08 07:18
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('feewaiver', '0016_auto_20201208_1448'),
]
operations = [
migrations.AddFie... |
from flexlmtools import parse_query, is_valid_server_name
import pytest
APP_FEATURES = {'feat1': (2, 0), 'feat2': (5, 1),
'feat6': (3, 3), 'feat-add': (2, 0),
'feat_opt': (1, 1)}
def test_parse_query():
with open('./test/app-features.txt', 'r') as f:
lines = f.read()
... |
# Copyright 2020-2021 Huawei Technologies Co., Ltd
#
# 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 agre... |
#!/usr/bin/env python
#encoding: utf8
import unittest, rostest
import rosnode, rospy
import time
from pimouse_ros.msg import MotorFreqs
from geometry_msgs.msg import Twist
from std_srvs.srv import Trigger, TriggerResponse
from pimouse_ros.srv import TimedMotion
class MotorTest(unittest.TestCase):
def setUp... |
# 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... |
# -*- coding: utf-8 -*-
#
# escpostools/commands/cmd_version.py
#
# Copyright 2018 Base4 Sistemas Ltda ME
#
# 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/license... |
# -*- coding: utf-8 -*-
'''
:codeauthor: Lukas Raska <lukas@raska.me>
'''
# Import Python Libs
from __future__ import absolute_import, print_function, unicode_literals
# Import Salt Testing Libs
from tests.support.unit import TestCase, skipIf
from tests.support.mock import (
MagicMock,
patch,
)
# Import ... |
import pytest
from numpy.random import choice
from textwrap import dedent
from random import Random
from bionic.exception import CodeVersioningError
from bionic import interpret
import bionic as bn
from ..helpers import import_code
class SimpleFlowModel:
"""
Manages a simple Bionic flow where every entity v... |
"""Generic step implementations for reports, subjects, metrics, and sources."""
import json
from asserts import assert_equal, assert_false, assert_true
from behave import given, when, then
@given("an existing {item}")
@given('an existing {item} with {attribute} "{value}"')
@given('an existing {item} with {attribute}... |
import pandas as pd
import numpy as np
import gc
def f():
print('called f')
#Uses around 4GB of memory when looped once
df = np.ones(500000000)
#Uses around 20GB of memory when looped 5 times
for i in range(0,5):
f()
|
# -*- coding: utf-8 -*-
#
# Copyright (C) 2018 CERN.
#
# invenio-app-ils is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.
"""Circulation PID providers."""
from invenio_pidstore.models import PIDStatus
from invenio_pidstore.providers.re... |
"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.
openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:
http://license.coscl.org.cn/MulanPSL2
THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, W... |
from django.contrib import admin
from django.db import models
from django.utils.translation import gettext_lazy as _
from .generic_audited_model import GenericAuditedModel
from .information_model import Information
from .company_paint_scheme_model import CompanyPaintScheme
class CompanyPaintSchemeInformation(Generic... |
from datetime import datetime
from balsam.service.models import BalsamJob
from tests.BalsamTestCase import BalsamTestCase
from tests.BalsamTestCase import create_job
from tests import util
class TestNoOp(BalsamTestCase):
def setUp(self):
from itertools import product
self.launcherInfo = util.la... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
"""File containing NASNet-series search space.
The implementation is based on NDS.
It's called ``nasnet.py`` simply because NASNet is the first to propose such structure.
"""
from collections import OrderedDict
from functools import partial
fro... |
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
dataset = pd.read_csv('Mall_Customers.csv')
X = dataset.iloc[:,[3,4]].values
#Using Elbow method
from sklearn.cluster import KMeans
wcss = []
for i in range(1,11):
kmeans = KMeans(n_clusters = i, init = 'k-means++', max_iter = 300, n_init = 10... |
import setuptools
with open("README.md", "r") as readme:
long_description = readme.read()
with open("requirements.txt", "r") as reqs:
requirements = reqs.read()
setuptools.setup(
name="redis-sitesearch",
version="1.0",
author="Andrew Brookins",
author_email="andrew.brookins@redislabs.com",
... |
# Copyright 2014 Cisco Systems, 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/LICENSE-2.0
#
# Unless requir... |
import _plotly_utils.basevalidators
class SizesrcValidator(_plotly_utils.basevalidators.SrcValidator):
def __init__(
self, plotly_name='sizesrc', parent_name='table.header.font', **kwargs
):
super(SizesrcValidator, self).__init__(
plotly_name=plotly_name,
parent_name=p... |
"""Copyright (c) 2015 – Thomson Licensing, SAS
Redistribution and use in source and binary forms, with or without
modification, are permitted (subject to the limitations in the
disclaimer below) provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, th... |
from flask import render_template, flash, make_response, \
redirect, url_for, request, jsonify, current_app
from flask.ext.login import login_user, logout_user, login_required, \
current_user
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from sqlalchemy import desc
from datetime import... |
from typing import List, Dict
PACKAGES_DATA: Dict[str, List[str]] = {
"init": [
"071f0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
"071f0000000000000000000000000000000000000000000000000000000000000000000000000000000000... |
# -*- coding: utf-8 -*-
from keepuppy.files import FileLocal, FileSFTP
from keepuppy.exceptions import FileException
import os
import tempfile
from nose.tools import eq_, assert_true, assert_false, raises
from datetime import datetime
from sftp_server import SFTPAuth, SFTPServer
import logging
log = logging.getLogger... |
# Copyright 2013 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/LICENSE-2.0
#
# Unless required by... |
# -*- coding: utf-8 -*-
# test_watchdog_events.py: tests for the watchdog.events module.
from nose.tools import \
assert_equal, \
assert_true, \
assert_false, \
assert_not_equal
from utils import assert_readonly_public_attributes
from watchdog.utils import has_attribute
from pathtools.patterns import ... |
### This script works for separacted shapes. Made by Edwin NG
###
### 1,create onside geo (name have to be "R_"/"L_")
### 2,dup and rename to the oppesite (R>L or L>R)
### 3,select both geos set transforms to origin
### 4,run the script except last line
### 5,select on3eside is correct,run last line. Done.
### I will ... |
import csv
import json
from graphenebase import Account
with open('./data/genesis_worksheet.csv') as csvfile:
c = csv.DictReader(csvfile, delimiter=',')
accounts = {}
for row in c:
#print(row["QUANTA Addr"], row["AccountID"])
accounts[row["AccountID"]] = row["QUANTA Addr"]
for name, ke... |
nums = list(map(int, input().split()))
print(f"The minimum number is {min(nums)}")
print(f"The maximum number is {max(nums)}")
print(f"The sum number is: {sum(nums)}") |
#!/usr/bin/env python
from pdb import set_trace as bp
import json
import os
import re
import sys
import glob
import pandas as pd
import typer
from typing import Optional
from sqlalchemy import create_engine
import psycopg2
debug = False
verbose = True
use_pandas = False
if use_pandas:
print("WARNING: under deve... |
from unittest import TestCase
from compoundFeaturization import deepChemFeaturizers
from deepchem.models import TextCNNModel
from deepsweet_utils import IO
from generate_features_rnn import RNNFeatureGenerator
from hyperparameter_optimisation import SklearnKerasHyperparameterOptimiser, EndToEndHyperparameterOptimiser... |
from homeassistant.util import slugify
from .const import SLUG_FORMAT
def slugify_entry(host, port):
return slugify(SLUG_FORMAT.format(host=host, port=port))
|
import sys
from pathlib import Path
file = Path(__file__).resolve()
parent, root = file.parent, file.parents[1]
sys.path.append(str(root))
try:
sys.path.remove(str(parent))
except ValueError: # Already removed
pass
import streamlit as st
import validators
from util.release_helper import create_static_notes
V... |
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 23 18:28:16 2021
@author: Debian_Boy
"""
from nltk.chat.util import Chat, reflections
#Pairs is a list of patterns and responses.
pairs = [
[
r"(.*)my name is (.*)",
["Hello %2, How are you today ?",]
],
[
r"(.*)help(.*)... |
import os
from datetime import datetime
from dbt.config import RuntimeConfig
import dbt.adapters.factory
import dbt.perf_utils
import utils.ui
from utils.logging import logger
from dbt.task.generate import Catalog, CatalogResults
from jinja2 import Template
SCHEMA_YML_TEMPLATE = Template(
"""
version: 2
models:... |
import chess
__all__ = ['Pawn', 'Rook', 'Bishop', 'Queen', 'Knight']
class Piece(object):
def __init__(self):
self.board = None
self.team = None
self.position = None
self.type = None
self.name = None
self.repr = None
def is_valid_move(self, pos):
pass
... |
import _plotly_utils.basevalidators
class SizesrcValidator(_plotly_utils.basevalidators.SrcValidator):
def __init__(
self, plotly_name="sizesrc", parent_name="barpolar.marker.pattern", **kwargs
):
super(SizesrcValidator, self).__init__(
plotly_name=plotly_name,
parent_n... |
from typing import Type
from rest_framework import filters, mixins, permissions, serializers, status, viewsets
from posthog.api.routing import StructuredViewSetMixin
from posthog.constants import AvailableFeature
from posthog.exceptions import EnterpriseFeatureException
from posthog.filters import TermSearchFilterBac... |
# Copyright (C) 2013 Google Inc. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are
# met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the ... |
from framework import utils
from osf.utils import permissions as osf_permissions
def serialize_initiator(initiator):
return {
'fullname': initiator.fullname,
'id': initiator._id
}
def serialize_meta_schema(meta_schema):
if not meta_schema:
return None
return {
'id': me... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.2 on 2016-11-12 16:43
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('crm', '0011_auto_20161106_1320'),
]
operations = [
migrations.AddField(
... |
import sys
import time
from socket import socket
from threading import Thread
from PyQt4.QtGui import *
import start_services
import settings
import os.path
from multiprocessing import Process
class Window(QMainWindow):
def __init__(self):
super(Window, self).__init__()
self.create_main_window()
... |
# VARIABLES
# tries: The maximum number of attempts of accessing url
# delay: The delay in amount of seconds after the first failed attempt
# backoff: Multiplier for exponential growth used for the calculation of delay for subsequent failed attempts. If backoff is 2, 2nd failed attempt delay is 2*delay, 3rd failed ... |
from dataclasses import dataclass, field
from typing import List
from raiden.utils.typing import BlockNumber, ChainID
from raiden_libs.types import Address, TokenNetworkAddress
@dataclass
class BlockchainState:
chain_id: ChainID
token_network_registry_address: Address
monitor_contract_address: Address
... |
class CyclicDependencyError(ValueError):
pass
def topological_sort_as_sets(dependency_graph):
"""
Variation of Kahn's algorithm (1962) that returns sets.
Take a dependency graph as a dictionary of node => dependencies.
Yield sets of items in topological order, where the first set contains
al... |
# Copyright (c) 2019. TsumiNa. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
import torch
from torch import nn
__all__ = ['ConvLayer', 'CrystalGraphConvNet']
class ConvLayer(nn.Module):
"""
Convolutional operation on graphs
... |
__all__ = ['invariant']
from typing import Any, Optional
def invariant(condition: Any, message: Optional[str] = None):
boolean_condition = bool(condition)
if not boolean_condition:
raise Exception(message if message is not None else 'Unexpected invariant triggered.')
|
"""herethere.here.config"""
from dataclasses import dataclass
from herethere.everywhere import ConnectionConfig
@dataclass
class ServerConfig(ConnectionConfig):
"""SSH server configuration."""
key_path: str
chroot: str
|
from nexpose_rest.nexpose import _GET
def getReportInstances(config, id):
getParameters=[]
code, data = _GET('/api/3/reports/' + str(id) + '/history', config, getParameters=getParameters)
return data
def getReport(config, id):
getParameters=[]
code, data = _GET('/api/3/reports/' + str(id) + '', ... |
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If ex... |
from trecs.models.recommender import SystemStateModule
from trecs.components import PredictedUserProfiles
import numpy as np
class TestComponents:
def test_system_state(self):
profiles = PredictedUserProfiles(np.zeros((5, 5)))
sys = SystemStateModule()
sys.add_state_variable(profiles)
... |
"""
merge:
Merges ROOT files
Usage:
merge file1 [file2 file3 ...] output_file=merged.root [compression=<int>]
Parameters:
output_file: name of the output file. Default: merged.root
compression: compression factor [0-9]. Default: 7
"""
import logging
import o... |
# flake8: noqa
# Registry keyss
AUGMENTOR = 'AUGMENTOR'
NODATA_AUGMENTOR = 'NODATA_AUGMENTOR'
from rastervision.augmentor.augmentor_config import AugmentorConfig
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.4 on 2017-10-03 19:09
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import multiselectfield.db.fields
class Migration(migrations.Migration):
dependencies = [
('map', '0015_auto_20170929... |
import unittest, time, sys, random
sys.path.extend(['.','..','../..','py'])
import h2o, h2o_cmd, h2o_browse as h2b, h2o_import as h2i, h2o_jobs, h2o_gbm
DELETE_KEYS = True
# FIX need to get exec workin
DO_CLASSIFICATION = False
class Basic(unittest.TestCase):
def tearDown(self):
h2o.check_sandbox_for_erro... |
import argparse
import cv2
import glob
import os
from basicsr.archs.rrdbnet_arch import RRDBNet
from aesrgan import RealESRGANer
def main():
parser = argparse.ArgumentParser()
parser.add_argument('--input', type=str, default='.\inputs', help='Input image or folder')
parser.add_argument(
'--model_... |
"""Users views."""
# Django REST Framework
from rest_framework import mixins, status, viewsets
from rest_framework.decorators import action
from rest_framework.response import Response
# Permissions
from rest_framework.permissions import (
AllowAny,
IsAuthenticated
)
from pmanagement.users.permissions imp... |
# Example 3
import csv
# Indexes of some of the columns
# in the dentists.csv file.
COMPANY_NAME_INDEX = 0
NUM_EMPLOYEES_INDEX = 6
NUM_PATIENTS_INDEX = 7
def main():
# Open a file named dentists.csv and store a reference
# to the opened file in a variable named dentists_file.
with open("E:/GitHub/2021-c... |
# Copyright (c) 2021, Sumit and Contributors
# See license.txt
# import frappe
import unittest
class TestRegistrationDistricts(unittest.TestCase):
pass
|
from django.shortcuts import render, redirect
from django.contrib import messages
from django.contrib.auth import login, logout
from django.contrib.auth.decorators import login_required
from .forms import UserRegisterForm, UserLoginForm, UserEditForm, ProfileEditForm
from .models import Profile
def register_view(req... |
def init(context):
context.s1 = '000905.XSHG'
subscribe(context.s1)
def handle_bar(context, bar_dict):
# stocknum = 50
his = history_bars(context.s1, 10, '1d', 'close')
# print(his)
if his[9] / his[8] < 0.97:
if len(context.portfolio.positions) > 0:
for stock in context.p... |
# Bot URL bank
urls = {
'flexing_bot': (
'https://cdn.discordapp.com/attachments/'
'390337910244769792/704686351228076132/arquius_smooth.gif'
),
'latex_parser': 'https://rtex.probablyaweb.site/api/v2',
'latex_icon': (
'https://cdn.discordapp.com/attachments/'
'663453... |
# api_internal_cache/controllers.py
# Brought to you by We Vote. Be good.
# -*- coding: UTF-8 -*-
from config.base import get_environment_variable
import wevote_functions.admin
logger = wevote_functions.admin.get_logger(__name__)
WE_VOTE_SERVER_ROOT_URL = get_environment_variable("WE_VOTE_SERVER_ROOT_URL")
|
# Copyright 2015-2016 The Meson development team
# 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 agree... |
"""
Landscape omnikeeper REST API
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
The version of the OpenAPI document: v1
Generated by: https://openapi-generator.tech
"""
import sys
import unittest
import okclient
from okclien... |
import numpy as np
from lazy_ops import DatasetView, lazy_transpose
import secrets
from numpy.testing import assert_array_equal
import unittest
import tempfile
from functools import wraps
import h5py
import zarr
import pytest
# Define decorator to iterate over dset_list
def dset_iterator(f):
@wraps(f)
def wrap... |
import functools as ft
import inspect
from typing import Any, Callable, Dict, Iterable, Optional, Union
from pjrpc.server import utils
class ValidationError(Exception):
"""
Method parameters validation error. Raised when parameters validation failed.
"""
class BaseValidator:
"""
Base method par... |
# Copyright (C) 2020 GreenWaves Technologies, SAS
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
# This progr... |
# -*- coding: utf-8 -*-
from django.test import TestCase
from core.models import Parent, Child, Unrelated
class CascadeDeleteTests(TestCase):
def setUp(self):
self.parent = Parent(name="Joe")
self.parent.save()
self.child = Child(name="John-Boy", parent=self.parent)
self.child.sa... |
import unittest
from src.masonite.orm.collection import Collection
from src.masonite.orm.factories import Factory as factory
from src.masonite.orm.models import Model
class TestCollection(unittest.TestCase):
def test_take(self):
collection = Collection([1, 2, 3, 4])
self.assertEqual(collection.ta... |
# -*- coding: utf-8 -*-
from .msg import WeixinMsg
from .pay import WeixinPay
from .login import WeixinLogin
from .mp import WeixinMP
from .base import WeixinError, Map
from collections import namedtuple
__all__ = ("Weixin")
__author__ = "Weicheng Zou <zwczou@gmail.com>"
__version__ = "0.5.5"
StandaloneApplicati... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2016-09-19 07:46
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('photos', '0002_auto_20160919_0737'),
]
operations = [
migrations.CreateMode... |
import os
import random
from parser import sexp_from_string
from config import KMemoryLimit, KTimeLimit, KExampleLimit
import time
from util import verify, flush_line
esolver_path = "../recommend/esolver"
def parse_result(result_file):
if not os.path.exists(result_file): return None
with open(result_file, "r")... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# __author__ : stray_camel
# __description__ : 用户部门管理等
# __REFERENCES__ :
# __date__: 2020/09/28 09
from django.db import models
from django.conf import settings
from datetime import datetime
AUTH_USER_MODEL = getattr(settings, 'AUTH_USER_MODEL', 'auth.User')
class Department... |
# ### Problem 6
# Example Output:
# ```
# There are currently 4 club members in the list!
# Club President: Alfred
# Club Vice President: Troy
# Club Secretary: Albert
# Club Treasurer: Bob
# ```
# Create a class called ClubMember
# Each club member has a name and a role
class ClubMember:
def __init__(self, name,... |
# 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 ... |
# brute force solution
#We can solve this by using a set. We first iterate through the first linked list and put every node in the set.
#We then iterate through the second linked list and check if the node is in the set. If it is, then we return the node.
def intersection(l1, l2):
nodeSet = set()
cur = l1
... |
from collections import defaultdict
from pathlib import Path
import numpy as np
import torch.utils.data as torch_data
from ..utils import common_utils
from .augmentor.data_augmentor import DataAugmentor
from .processor.data_processor import DataProcessor
from .processor.point_feature_encoder import PointFeatureEncode... |
import glob as _glob
import hashlib
import os
import platform
import random as _random
import struct
import subprocess
import sys
import threading
from . import log
system = platform.system()
linux = system == 'Linux'
windows = system == 'Windows'
mac = system == 'darwin'
if windows:
NEW_PROCESS_GROUP = dict(cre... |
# Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If ex... |
def max_subarray(nums):
# kadane algorithm
max_so_far = max_ending = 0
begin = start = end = 0
for i in range(len(nums)):
max_ending += nums[i]
if max_ending < 0:
max_ending = 0
begin = i + 1
if max_so_far < max_ending:
max_so_far =... |
from functools import reduce
from django.core.urlresolvers import NoReverseMatch
from django.template.defaultfilters import date
from django.utils.html import (conditional_escape, escape, format_html,
format_html_join)
from django.utils.safestring import mark_safe
from django.utils.trans... |
"""
Django settings for app project.
Generated by 'django-admin startproject' using Django 2.1.15.
For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/ref/settings/
"""
import os
# Bu... |
import sys
#import dlm.utils as U
#import dlm.io.logging as L
import codecs
class NBestList():
def __init__(self, nbest_path, mode='r', reference_list=None):
assert mode == 'r' or mode == 'w', "Invalid mode: " + mode
self.mode = mode
self.nbest_file = codecs.open(nbest_path, mode=mode, enco... |
from django.db import models
import pyperclip
# Create your models here.
class Poster(models.Model):
first_name = models.CharField(max_length=255 ,primary_key = True)
last_name = models.CharField(max_length=255)
email = models.EmailField()
def __str__(self):
return self.first_name
def... |
#! /usr/bin/env python
# coding=utf-8
# Copyright (c) 2019 Uber Technologies, 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
#
# Unles... |
import logging
import attr
import IPython
from ..hookspec import hookimpl
from ..pm import pm
log = logging.getLogger(__name__)
@attr.s(cmp=False)
class IPythonUI:
'IPython UI for usbq'
ns = {}
@hookimpl
def usbq_ipython_ns(self):
res = {'pm': pm}
return res
def run(self, eng... |
"""
This file offers the methods to automatically retrieve the graph SW-1000-5-0d1-trial2.
The graph is automatically retrieved from the NetworkRepository repository.
Report
---------------------
At the time of rendering these methods (please see datetime below), the graph
had the following characteristics:
Datet... |
import binascii
import badger2040
import badger_os
# **** Put your list title here *****
list_title = "Checklist"
list_file = "checklist.txt"
# Global Constants
WIDTH = badger2040.WIDTH
HEIGHT = badger2040.HEIGHT
ARROW_THICKNESS = 3
ARROW_WIDTH = 18
ARROW_HEIGHT = 14
ARROW_PADDING = 2
MAX_ITEM_CHARS = 26
TITLE_TE... |
#!/usr/bin/python3
# ########################################################################
# Copyright (c) 2021 Advanced Micro Devices, Inc.
#
# 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 Softw... |
import json
import re
from typing import List, Optional
from bs4 import BeautifulSoup, Tag
def _format_link(url: str) -> Optional[str]:
"""
Formats links on wiki page
:param url: href attribute of <a> element
:return: if correct internal link, returns formatted link; otherwise (external or... |
from django import forms
from django.utils.translation import ugettext_lazy as _
from .models import Profile
class MemberSignupForm(forms.Form):
first_name = forms.CharField(
label=_('First name'),
max_length=30,
widget=forms.TextInput(),
)
last_name = forms.CharField(
la... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.