filename stringlengths 13 19 | text stringlengths 134 1.04M |
|---|---|
the-stack_106_22015 | # ___________________________________________________________________________
#
# Pyomo: Python Optimization Modeling Objects
# Copyright 2017 National Technology and Engineering Solutions of Sandia, LLC
# Under the terms of Contract DE-NA0003525 with National Technology and
# Engineering Solutions of Sandia, LLC... |
the-stack_106_22016 | import time
from collections import OrderedDict, namedtuple
import numpy as np
from pandas import DataFrame
from scipy.integrate import odeint, ode
import ggplot as gg
from scipy_ode import solve_ivp
HAS_ODES = False
try:
from scikits.odes.odeint import odeint as odes_odeint
from scikits.odes import ode as odes... |
the-stack_106_22017 | """
For raspberry pi use:
import sys
sys.path.append('/home/pi/.local/lib/python3.9/site-packages')
"""
import cv2 as cv
import numpy as np
from PIL import Image, ImageEnhance
import time
import PRNTR
path1 = PRNTR.location
def ED():
#Canny edge detector
#load birds image
image = cv.imread("{}/files/new_test_resi... |
the-stack_106_22019 | import json
import re
import requests
from six.moves.urllib.parse import quote, quote_plus
from blackbelt.config import config
from blackbelt.errors import ConfigurationError
class Trello(object):
"""
I represent a authenticated connection to Trello API.
Dispatch all requests to it through my methods.
... |
the-stack_106_22020 | from __future__ import print_function
class BoundObjAndStoredGlobals(object):
def __init__(self, obj, globals_, exclusions={'In', 'Out'}):
self.obj = obj
self.globals_ = globals_
self.exclusions = exclusions
self.exclusions.update(k for k in globals_ if k.startswith('_'))
def... |
the-stack_106_22021 | import mne
import os.path as op
from autoreject import get_rejection_threshold
subject = 'CC110037'
kind = 'rest'
raw = mne.io.read_raw_fif(
'/storage/local/camcan/data/'
'{0:s}/{1:s}/{2:s}_raw.fif'.format(subject, kind, kind))
mne.channels.fix_mag_coil_types(raw.info)
raw.info['bads'] = ['MEG1031', 'M... |
the-stack_106_22023 | # scapy.contrib.description = Link Layer Discovery Protocol (LLDP)
# scapy.contrib.status = loads
"""
LLDP - Link Layer Discovery Protocol
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:author: Thomas Tannhaeuser, hecke@naberius.de
:license: GPLv2
This module is free software; you can redistribut... |
the-stack_106_22024 | class DListNode:
def __init__(self, val):
self.val = val
self.prev = self.next = Null
def reverse(self, head):
curr = None
while head:
curr = head
head = curr.next
curr.next = curr.prev
curr.prev = head
return curr
|
the-stack_106_22027 | # Copyright 2018 Google 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
the-stack_106_22030 | import numpy as np
from classy import Class
def compute_sigma8(pars, lnA0 = 3.047):
OmegaM, h= pars
omega_b = 0.02242
lnAs = lnA0
ns = 0.9665
nnu = 1
nur = 2.033
mnu = 0.06
omega_nu = 0.0106 * mnu
omega_c = (OmegaM - omega_b/h**2 - omega_nu/h**2) * h**2
p... |
the-stack_106_22031 | #!/usr/bin/env python
# -*- Mode: Python -*-
# vi:si:et:sw=4:sts=4:ts=4
#
# GStreamer python bindings
# Copyright (C) 2004 Johan Dahlin <johan at gnome dot org>
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Fre... |
the-stack_106_22032 | # Copyright (C) 2013 Lukas Lalinsky
# Distributed under the MIT license, see the LICENSE file for details.
import re
import sqlparse
from sqlparse import tokens as T
from sqlparse.sql import Token, TokenList, Parenthesis, Statement
def group_parentheses(tokens):
stack = [[]]
for token in tokens:
if t... |
the-stack_106_22036 | from django.conf import settings
from django.http import HttpResponse
from django.views.generic import DetailView
from core import tasks
from core.models import Link
from core.utils import get_client_ip
class LinkDetailView(DetailView):
model = Link
def get_queryset(self):
qs = super().get_queryset(... |
the-stack_106_22037 | # Copyright (c) 2013-2021 khal contributors
#
# 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, publi... |
the-stack_106_22038 | # Helper Functions
# Imports
import requests, json, os
# Credentials
api_key = "04b2253f2a386ad7e8fcc3104c69531e"
# Genres Function
def get_genres():
query = f"https://api.themoviedb.org/3/genre/movie/list?api_key={api_key}&language=en-US"
response = requests.get(query)
if response.status_code == 200:
... |
the-stack_106_22039 | # -*- coding: utf-8 -*-
# Copyright 2020 Google 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... |
the-stack_106_22040 | # This file is created by Minyi Liu (GitHub ID: MiniMinyi)
# The hash algorithm is copied from:
# https://github.com/hjaurum/DHash/blob/master/dHash.py
def _intersect(rect1, rect2):
"""
Check whether two rectangles intersect.
:param rect1, rect2: a rectangle represented with a turple(x,y,w,h,approxPoly_co... |
the-stack_106_22041 | from time import sleep
class Iteratable:
def __init__(self, max):
self.max = max
self.arr = []
self.i = 0
def __iter__(self):
self.n = 0
if len(self.arr) == self.max and self.i + 1 <= self.max :
return iter(self.arr)
return self
def __next__(s... |
the-stack_106_22043 | #!/usr/bin/env python
# Copyright 2019 The Fuchsia Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import argparse
from host import Host
class Args:
@classmethod
def make_parser(cls, description, name_required=True, label_prese... |
the-stack_106_22045 | import numpy as np
from pyldpc import make_ldpc, ldpc_images
from pyldpc.utils_img import gray2bin # , rgb2bin
from matplotlib import pyplot as plt
from PIL import Image
from time import time
##################################################################
# Let's see the image we are going to be working with
t... |
the-stack_106_22046 | # 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... |
the-stack_106_22047 | from model.contact import Contact
from random import randrange
#def test_modify_first_contact_firstname(app):
# if app.contact.contact_count() == 0:
# app.contact.create_contact(Contact(firstname="для модификации контакта"))
# old_contacts_list = app.contact.get_contact_list()
# contact = Contact(firs... |
the-stack_106_22051 | from mongrel2.config import *
main = Server(
uuid="f400bf85-4538-4f7a-8908-67e313d515c2",
access_log="/logs/access.log",
error_log="/logs/error.log",
chroot="./",
default_host="localhost",
name="test",
pid_file="/run/mongrel2.pid",
port=6767,
hosts = [
Host(name="localhost"... |
the-stack_106_22052 | """
This is PISACov, a program designed to infer quaternary structure
of proteins from evolutionary covariance.
"""
from pisacov import __prog__, __description__, __version__
from pisacov import __author__, __date__, __copyright__
__script__ = 'PISACov Statistical Analysis script'
from pisacov import command_line as ... |
the-stack_106_22055 | from flask import Flask
from flask import render_template
from flask import redirect
from flask import request
from flask import url_for
from flask import flash
from flask import jsonify
from flask import session as login_session
from flask import abort
from flask import make_response
from flask_wtf.csrf import CSRFPr... |
the-stack_106_22058 | #-----------------------------------------------------------------------------
# Copyright (c) 2012 - 2020, Anaconda, Inc., and Bokeh Contributors.
# All rights reserved.
#
# The full license is in the file LICENSE.txt, distributed with this software.
#-------------------------------------------------------------------... |
the-stack_106_22059 | # 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... |
the-stack_106_22061 | import numpy as np
import warnings
import cv2
import torch
def topdownhead_decode_heatmaps_without_cs(output):
"""Decode keypoints from heatmaps.
Args:
img_metas (list(dict)): Information about data augmentation
By default this includes:
- "image_file: path to the image file
... |
the-stack_106_22064 | #!/usr/bin/env python
# Copyright 2021 Roboception GmbH
#
# 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-stack_106_22068 | def load_input():
cases = open("input.txt", "r").readlines()
for i in range(len(cases)):
cases[i] = cases[i].replace('\n','')
return cases
groups = []
def parse_input():
inp = load_input()
inp_len = len(inp)
group = []
for i in range(inp_len):
line = inp[i]
if line ... |
the-stack_106_22069 | import logging
import collections
import numpy as np
logger = logging.getLogger(__name__)
LabelGrouping = collections.namedtuple('LabelGrouping',
['title', 'Y', 'Y_labels', ])
DataSplit = collections.namedtuple('DataSplit',
[ 'X_train', 'X_tes... |
the-stack_106_22070 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2021/1/23 18:48
# @Author : Charseki.Chen
# @Email : chenshengkai@vip.qq.com
# @Site : https://www.chenshengkai.com
# @File : datatype.py
# @Software: PyCharm
class TestSuite():
sub_suites = None
name = ""
details = ""
testcase_list = N... |
the-stack_106_22072 | # SPDX-License-Identifier: Apache-2.0
#
# Copyright (C) 2016, ARM Limited and contributors.
#
# 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
#
# ... |
the-stack_106_22073 | FILENAME = "path/to/lahman2016.sqlite"
# import `pandas` and `sqlite3`
import pandas as pd
import sqlite3
# Connecting to SQLite Database
conn = sqlite3.connect(FILENAME)
# Querying Database for all seasons where a team played 150 or more games and is still active today.
query = "select name from sqlite_master where... |
the-stack_106_22075 | # -*- coding: utf-8 -*-
from datetime import datetime
import functools
import random
import pytest
import falcon
from falcon import testing
from falcon import util
from falcon.util import compat, json, uri
def _arbitrary_uris(count, length):
return (
u''.join(
[random.choice(uri._ALL_ALLOWE... |
the-stack_106_22076 | import scipy.stats
import numpy as np
from numpy import sign, abs, exp, log, pi, sqrt
from numpy import nanmean as mean, nanstd as std, nanmedian as median, nanmin as min, nanmax as max
# .95 quantile of Extreme Value Distribution
_gumble_p95 = scipy.stats.gumbel_l.ppf(.95)
def _skew(vector):
return scipy.stats.s... |
the-stack_106_22077 | # Fibonacci tool
# This script only works with Python3!
import time
def getFibonacciIterative(n: int) -> int:
"""
Calculate the fibonacci number at position n iteratively
"""
a = 0
b = 1
for i in range(n):
a, b = b, a + b
return a
def getFibonacciRecursive(n: int) -> int:
... |
the-stack_106_22078 | #!/usr/bin/env python3
# Copyright (c) 2014-2018 The Bitcoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test behavior of headers messages to announce blocks.
Setup:
- Two nodes:
- node0 is the... |
the-stack_106_22080 | import torch
import torch.nn as nn
import numpy as np
from torchsummary import summary
from torchvision import datasets
import torchvision.transforms as transforms
import torch.nn.functional as F
from extract_layers import extract_layers
from visualize_net import nnVisual, NetVisual
from manim.utils.file_ops import ope... |
the-stack_106_22081 | import random
# Ok, I think what we have below is correct as pseudo-code.
# Next: test it with a simple environment and make it no-longer pseudo-code
# After that: make it into a persistent thing that I can make multiple calls to.
'''
A snag:
I need some way of figuring out whether a node has already been explored. ... |
the-stack_106_22082 | """empty message
Revision ID: ee2b22119072
Revises:
Create Date: 2018-04-16 21:19:27.273617
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'ee2b22119072'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ###... |
the-stack_106_22083 | """Implements an adapter for DeepMind Control Suite environments."""
from collections import OrderedDict
import copy
import numpy as np
from dm_control import suite
from dm_control.rl.specs import ArraySpec, BoundedArraySpec
from dm_control.suite.wrappers import pixels
from gym import spaces
from .softlearning_env i... |
the-stack_106_22084 | """Support for the Devcon UI."""
from functools import wraps
import logging
import os
import time
import voluptuous as vol
from openpeerpower.components import websocket_api
from openpeerpower.exceptions import OpenPeerPowerError
from openpeerpower.util.yaml import load_yaml
_LOGGER = logging.getLogger(__name__)
DO... |
the-stack_106_22085 | # vim: tabstop=4 shiftwidth=4 softtabstop=4
# Copyright (c) 2011 Citrix Systems, 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/LICE... |
the-stack_106_22087 | import socket
import pickle
import threading
import sys
import argparse
import os
from datetime import datetime
from message import Message, EnhancedJSONEncoder
from streaming import createMsg, streamData
import json
from Crypto.Cipher import PKCS1_OAEP # RSA based cipher using Optimal Asymmetric Encryption Padding
f... |
the-stack_106_22089 | # Copyright 2020 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 agreed to... |
the-stack_106_22090 | import csv
import numpy as np
import sys
import os
from pathlib import Path
from argparse import ArgumentParser
inputBytes = sys.argv[1]
outputBytes = sys.argv[2]
stagesOutputBytes = sys.argv[3]
replicationFactor = sys.argv[4]
outputFile = sys.argv[5]
appNameIndex = 0
nodeNameIndex = 1
executorIdIndex = 2
executorTo... |
the-stack_106_22093 | #!/usr/bin/python3
from pwn import *
binary = ELF('./hello')
context.update(arch='i386',os='linux')
#p = process(binary.path)
#libc = ELF('/lib/i386-linux-gnu/libc.so.6')
p = remote('chall.csivit.com', 30046)
libc = ELF('libc-database/db/libc6-i386_2.23-0ubuntu11.2_amd64.so')
payload = 0x88 * b'A'
payload += p32(b... |
the-stack_106_22095 | import climt
from sympl import PlotFunctionMonitor
import numpy as np
import matplotlib.pyplot as plt
from datetime import timedelta
def plot_function(fig, state):
fig.set_size_inches(10, 5)
ax = fig.add_subplot(1, 2, 1)
state['air_temperature'].mean(dim='lon').plot.contourf(
ax=ax, levels=16)
... |
the-stack_106_22096 | #
# Copyright (C) 2021 Vaticle
#
# 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, Versi... |
the-stack_106_22099 | # Copyright 2020 The IREE Authors
#
# Licensed under the Apache License v2.0 with LLVM Exceptions.
# See https://llvm.org/LICENSE.txt for license information.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
"""Macros for defining tests that run a module using iree-check-module."""
load("//iree/tools:compila... |
the-stack_106_22100 | import json
import sys
from os.path import abspath
def join_jsons(fin_path1, fin_fpath2, fout_path, with_dup = False):
final = list()
with open(fin_path1, 'r', encoding="utf8") as f:
final = json.load(f)
print(f"First JSONL contains {len(final)} rows")
tmp = list()
with open(fin_f... |
the-stack_106_22102 | """
A batch prcoessing that calls main_lc.py with the same set of parameters
but different split ids.
"""
import warnings
warnings.filterwarnings('ignore')
import os
import sys
from pathlib import Path
import argparse
from glob import glob
import numpy as np
# from joblib import Parallel, delayed
fdir = Path(__file_... |
the-stack_106_22103 | from __future__ import division, absolute_import, print_function
from .. import affinitymat
from .. import nearest_neighbors
from .. import cluster
from .. import aggregator
from .. import core
from .. import util
from .. import seqlet_embedding
from .. import pattern_filterer as pattern_filterer_module
from joblib imp... |
the-stack_106_22104 | '''!
* Copyright (c) 2020-2021 Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See LICENSE file in the
* project root for license information.
'''
from typing import Dict, Optional, List, Tuple, Callable
import numpy as np
import time
import pickle
try:
from ray.tune.sug... |
the-stack_106_22106 | import networkx as nx
import numpy as np
import scipy as sp
import matplotlib.pyplot as plt
from itertools import product
import random
import math
from functools import wraps
import pandas as pd
from .information import mutual_information
def compose(f, g):
"""
:param f: Second function to apply
:param g... |
the-stack_106_22108 | """Commonly used functions not available in the Python2 standard library."""
from __future__ import division
import math
from sys import float_info
NORM_EPSILON = math.pow(float_info.epsilon, 0.25) # half-precision works for machine learning
def mean(values):
values = list(values)
return sum(map(float, valu... |
the-stack_106_22110 | from ibm_watson import LanguageTranslatorV3
languages = {
"English": "en",
"French": "fr",
"Spanish": "es",
"German": "de"
}
API_key = 'ujft9Uu2E6jFCcaYAiUxIKfs4w6DnFnX3C_hac2IDr_N'
def initLT():
return LanguageTranslatorV3(
version = '2018-05-01',
iam_apikey = API_key)
def trans... |
the-stack_106_22111 | import logging
import json
from urllib import error
from pkg_resources import resource_filename, Requirement
import pandas as pd
from pvlib import iotools
from requests.exceptions import HTTPError
from solarforecastarbiter.datamodel import Observation, SolarPowerPlant
from solarforecastarbiter.io.reference_observat... |
the-stack_106_22113 | ################################################################################
# TLGProb: Two-Layer Gaussian Process Regression Model For
# Winning Probability Calculation of Two-Team Sports
# Github: https://github.com/MaxInGaussian/TLGProb
# Author: Max W. Y. Lam (maxingaussian@gmail.com)
#############... |
the-stack_106_22114 |
from ..client import Client
class ProductTargeting(Client):
def get_targets(self, next_token: str = None, max_results: int = 0, filters: list = None):
self.uri_path = "/sb/targets/list"
self.method = "post"
self.data = {
"nextToken": next_token,
"maxResults": ma... |
the-stack_106_22116 | import descriptors as desc
import pandas as pd
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler
from sklearn.manifold import TSNE
import umap
import seaborn as sns
from scipy import stats
import numpy as np
import math
import matplotlib.pyplot as plt
class Plotter(object):
"""... |
the-stack_106_22118 | import boto3
from boto3.dynamodb.conditions import Key
from pprint import pprint
def get_item():
"""Get item from the DynamoDB table."""
dynamo_db = boto3.resource("dynamodb")
table = dynamo_db.Table("devices")
response = table.query(KeyConditionExpression=Key("name").eq("core02-wdc01"))
for item ... |
the-stack_106_22119 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Module to create an OPC UA client. Reference code:
https://github.com/FreeOpcUa/python-opcua/tree/master/examples
"""
#import sys
#sys.path.insert(0, "..")
import logging
import logging.config
import yaml
import coloredlogs
from opcua import Client
logger = logging.getL... |
the-stack_106_22121 | # Copyright 2015 Hewlett-Packard Development Company, L.P.
#
# 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
#
# Un... |
the-stack_106_22122 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
import requests
import webbrowser
import sys
CONFIG_KEYS = ['mode']
DIRECTIONS = ['Stay', 'North', 'South', 'East', 'West']
TIMEOUT = 15
# This is the class that a program interacts with
class client:
"""A client for interacting with the vindinium server"""
def ... |
the-stack_106_22123 | import _plotly_utils.basevalidators
class ShowticksuffixValidator(_plotly_utils.basevalidators.EnumeratedValidator):
def __init__(
self, plotly_name="showticksuffix", parent_name="choropleth.colorbar", **kwargs
):
super(ShowticksuffixValidator, self).__init__(
plotly_name=plotly_na... |
the-stack_106_22126 | # -*- test-case-name: twisted.test.test_protocols -*-
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details.
"""
Basic protocols, such as line-oriented, netstring, and int prefixed strings.
Maintainer: Itamar Shtull-Trauring
"""
# System imports
import re
import struct
import warnings
import cStrin... |
the-stack_106_22129 | from __future__ import absolute_import, print_function
from wagl.acca_cloud_masking import majority_filter
from . import fmask_cloud_masking as _fmask
def fmask_cloud_mask(
mtl, null_mask=None, cloud_prob=None, wclr_max=None, sat_tag=None, aux_data=None
):
Lnum = int(sat_tag[-1:])
(_, _, _, _, _, _, _, ... |
the-stack_106_22130 | # NOTICE: As required by the Apache License v2.0, this notice is to state this file has been modified by Arachne Digital
# This file has been renamed from `tram.py`
# To see its full history, please use `git log --follow <filename>` to view previous commits and additional contributors
import aiohttp_jinja2
import asyn... |
the-stack_106_22131 | '''
CSCI 379 Programming Assignment 2
By Antonina Serdyukova
With help of this tutorial https://ruslanspivak.com/lsbaws-part3/
'''
import errno
import os
import sys
import signal
import socket
import datetime
import time
if len(sys.argv) > 1:
p = int(sys.argv[1])
else:
p = 80
SERVER_ADDRESS = (HOST, PORT) = '... |
the-stack_106_22134 | #
# Copyright (c) 2020, NVIDIA CORPORATION. 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 appl... |
the-stack_106_22135 | import sys
# add source
sys.path.insert(0, os.path.abspath('./sphinxext'))
sys.path.append('/Users/mdl-admin/Desktop/mdl')
# import package
import imhr
# create image
import matplotlib.pyplot as plt
import matplotlib.image as image
from pathlib import Path
# path
path = '%s/dist/roi/output/img/bounds/'%(Path(imhr.__fi... |
the-stack_106_22138 | """ Pytorch Inception-Resnet-V2 implementation
Sourced from https://github.com/Cadene/tensorflow-model-zoo.torch (MIT License) which is
based upon Google's Tensorflow implementation and pretrained weights (Apache 2.0 License)
"""
import torch
import torch.nn as nn
import torch.nn.functional as F
from .registry import ... |
the-stack_106_22140 | # The corresponding complete binary tree for this array of elements [4, 10, 3, 5, 1] will be:
#
# 4
# / \
# 10 3
# / \
# 5 1
#
# Note:
# Root is at index 0 in array.
# Left child of i-th node is at (2*i + 1)th index.
# Right child of i-th node is at (2*i + 2)th index.
# Parent of i-th node is... |
the-stack_106_22144 | from typing import Generator, Literal
from app.element.block import Block, ParseResult, CodeBlock, CodeChildBlock
from app.converter.block_converter import BlockConverter
class Converter:
""" 複数行におよぶBlock要素をHTMLタグと対応した形へ変換することを責務に持つ """
def __init__(self):
self._block_converter = BlockConverter()
... |
the-stack_106_22145 | """
common implementation for building namelist commands
These are used by components/<model_type>/<component>/cime_config/buildnml
"""
from CIME.XML.standard_module_setup import *
from CIME.utils import expect, parse_args_and_handle_standard_logging_options, setup_standard_logging_options
import sys, os, argparse
l... |
the-stack_106_22146 | #!/usr/bin/env python
# Copyright 2014 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.
"""Simple client for the Gerrit REST API.
Example usage:
./gerrit_client.py -j /tmp/out.json -f json \
-u https://chromium.googl... |
the-stack_106_22151 |
class Hyperparameters():
def __init__(self):
self.IMAGESIZE = [30,30]
self.MEAN_REWARD_BOUND = 19.0
self.CHANNEL_NUM = 4
self.ACTION_SPACE = 6
self.GAMMA = 0.99
self.BATCH_SIZE = 32
self.REPLAY_SIZE = 10000
self.REPLA... |
the-stack_106_22152 | import pytest
from mach9.http import HttpProtocol, BodyChannel
from tests.utils import Transport
@pytest.mark.asyncio
async def test_body_channel_send():
transport = Transport()
body_channel = BodyChannel(transport)
i = 1
await body_channel.send(i)
o = await body_channel.receive()
assert i ==... |
the-stack_106_22153 | import os
def WalkFileStructure(curDir, callback, reportFiles = True, reportFolders = True):
for name in os.listdir(curDir):
if name.startswith("."):
continue
fullPath = os.path.join(curDir, name)
if (reportFiles and os.path.isfile(fullPath)) or (reportFolders and os.path.is... |
the-stack_106_22155 | import datetime
import json
import logging
import os
import re
from copy import deepcopy
from json import dumps, loads, JSONEncoder
from pathlib import Path
from typing import Optional, Dict, Mapping, Set, Tuple, Callable, Any, List, Type
import deep_merge
import hcl2
from lark import Tree
from checkov.common.paralle... |
the-stack_106_22156 | import pandas as pd
import os
import sys
#data=pd.read_excel(sys.argv[1])
data=pd.read_excel('/Users/siaga/Desktop/processedData.xlsx')
mass=set()
basket=pd.DataFrame()
excelList=os.listdir('/Users/siaga/Desktop/NFT')
for i in excelList:
i=i.replace('.xlsx','')
i=i.replace('-','_')
locals()['data'+i]=data[... |
the-stack_106_22157 | """
Options for Streamlit widgets.
"""
style_gan_choices = [
"faces (ffhq slim 256x256)",
"lsun cats",
"wildlife",
"my little pony",
"grumpy cat",
"lsun cars",
"beetles",
"more abstract art",
"obama",
"abstract photos",
"horse",
"cakes",
"car (config-e)",
"paint... |
the-stack_106_22160 | import os
from os import path, makedirs, listdir
import sys
import numpy as np
np.random.seed(1)
import random
random.seed(1)
import torch
from torch import nn
from torch.backends import cudnn
from torch.autograd import Variable
import pandas as pd
from tqdm import tqdm
import timeit
import cv2
from sklearn.model_sel... |
the-stack_106_22161 | import csv
with open('graphs/class1.csv', newline='') as f:
reader = csv.reader(f)
file_data = list(reader)
#To remove headers from CSV
file_data.pop(0)
total_marks = 0
total_entries = len(file_data)
for marks in file_data:
total_marks += float(marks[1])
mean = total_marks / total_entrie... |
the-stack_106_22164 | # -*- coding: utf-8 -*-
from __future__ import absolute_import, unicode_literals
from contextlib import contextmanager
from logging import getLogger
import os
from tempfile import TemporaryFile
import mimetypes
from future.standard_library import install_aliases
install_aliases()
from urllib.parse import urlparse, ur... |
the-stack_106_22167 | # This code calibrates magnetometer. Please add the scale values to the other file codes when imu_algorithms are used.
from modules.mpulib import computeheading, attitudefromCompassGravity
import socket, traceback
import csv
import struct
import sys, time, string, pygame
import pygame
import pygame.draw
import pygam... |
the-stack_106_22168 | #!/usr/bin/env python3
import os
import ssl
import argparse
from socketserver import ThreadingMixIn
from http.server import BaseHTTPRequestHandler, HTTPServer
parser = argparse.ArgumentParser(prog="server", description="Python HTTPS Server")
parser.add_argument(
"-m",
"--mtls",
dest="mtls",
action="st... |
the-stack_106_22174 | from torch import nn, Tensor
class SpatialAttention(nn.Module):
def __init__(self, input_size: int):
super().__init__()
self.conv1 = nn.Sequential(
nn.Conv2d(input_size, input_size // 2, kernel_size=3, stride=1, padding=1),
nn.BatchNorm2d(input_size // 2),
nn.... |
the-stack_106_22177 | import operator
import numpy as np
from cvxpy import *
from knapsack.hyper.multiple import problem
def ksp_solve_lp_relaxed_convex(costs, weights, sizes):
x = Variable(len(sizes), len(costs))
weights_param = Parameter(rows=len(sizes), cols=len(costs))
weights_param.value = np.asarray(weights)
costs_... |
the-stack_106_22182 | # -*- coding: utf-8 -*-
# AtCoder Beginner Contest
def main():
n, t = list(map(int, input().split()))
a = [int(input()) for _ in range(n)]
duration = t
# See:
# https://beta.atcoder.jp/contests/abc024/submissions/2841120
for i in range(1, n):
duration += min(t, a[i] - a[i - 1])
p... |
the-stack_106_22183 | # Authors: Christian Lorentzen <lorentzen.ch@gmail.com>
#
# License: BSD 3 clause
import numpy as np
from numpy.testing import assert_allclose
import pytest
import warnings
from sklearn.datasets import make_regression
from sklearn.linear_model._glm import GeneralizedLinearRegressor
from sklearn.linear_model import Tw... |
the-stack_106_22184 | from abc import ABC, abstractmethod
from typing import Dict, List, Tuple
from enum import Enum
from nxs_types import DataModel
class NxsDbType(str, Enum):
MONGODB = "mongodb"
REDIS = "redis"
class NxsDbSortType(int, Enum):
DESCENDING = -1
ASCENDING = 1
class NxsDbQueryConfig(DataModel):
projec... |
the-stack_106_22186 |
from ..scripts.test_script_ver_4 import *
from ..scripts.hist_eq import hist_eq
def driver_he():
# making preprocessing_name string
preprocessing_name = "HE"
# method as function name
method = hist_eq
# making initial list
parameters_list = ['', method, []]
parameters_string = 'histogr... |
the-stack_106_22187 | # This is a simple MXNet server demo shows how to use DGL distributed kvstore.
import dgl
import argparse
import mxnet as mx
import time
ID = []
ID.append(mx.nd.array([0,1], dtype='int64'))
ID.append(mx.nd.array([2,3], dtype='int64'))
ID.append(mx.nd.array([4,5], dtype='int64'))
ID.append(mx.nd.array([6,7], dtype='int... |
the-stack_106_22188 | # Copyright (c) 2021, NVIDIA CORPORATION.
class ListMethods:
def __init__(self, d_series):
self.d_series = d_series
def len(self):
"""
Computes the length of each element in the Series/Index.
Returns
-------
Series or Index
Examples
--------
... |
the-stack_106_22189 | import csv
from typing import Dict, List, Optional
import logging
import copy
from random import randint, sample
from overrides import overrides
from allennlp.common.checks import ConfigurationError
from allennlp.common.file_utils import cached_path
from allennlp.common.util import START_SYMBOL, END_SYMBOL
from allenn... |
the-stack_106_22190 | # Author: Parashar Shah
# Chapter: Cognitive Services
# Version: 1.0
# Date: May 25, 2018
# Replace <Subscription Key> with your valid subscription's api access key.
subscription_key = "<Access Key>"
assert subscription_key
# Replace the base url with what you see as Endpoint in the portal’s Overview section u... |
the-stack_106_22191 | from nose.tools import assert_equal
from cutecharts.charts import Pie
from cutecharts.render.engine import remove_key_with_none_value
def gen_pie_base() -> Pie:
c = Pie("Pie")
c.set_options(labels=["A", "B"])
c.add_series(["1", "2"])
return c
def test_pie_opts_before():
c = gen_pie_base()
e... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.