filename stringlengths 13 19 | text stringlengths 134 1.04M |
|---|---|
the-stack_106_26230 | """
yxf: Convert from XLSForm to YAML and back.
To convert an XLSForm to a YAML file: `python -m yxf form.xlsx`.
By default, the result will be called `form.yaml`, in other words, the same name
as the input file with the extension changed to `.yaml`. You can specify a
different output file name using the `--output ot... |
the-stack_106_26232 | import sys, os
sys.path.append(os.pardir)
from Common.math_functions import *
from Common.gradient import numerical_gradient
class TwoLayerNet:
def __init__(self, input_size, hidden_size, output_size,
weight_init_std=0.01):
# 初始化权重
self.params = {}
self.params['W1'] = weig... |
the-stack_106_26233 | # 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.
# --------------------------------------------------------------------... |
the-stack_106_26234 | # Copyright 2013-2019 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... |
the-stack_106_26235 | r"""
This module contains classes for working with sparse matrices.
"""
from __future__ import division
from copy import deepcopy
from collections.abc import Mapping, MutableMapping
from numbers import Number, Integral
import numpy as np
import sympy as sp
from scipy.sparse import bmat, dia_matrix, kron, diags as sp_d... |
the-stack_106_26237 | import queue
import consts
import logging
import requests
import threading
from domain.Table import Table
from domain.Waiters import Waiters
logger = logging.getLogger(__name__)
lock = threading.Lock()
class DinningHall:
def __init__(self, config):
self.config = config
self.id_ = config["restaura... |
the-stack_106_26238 | import logging
from gaphor import UML
from gaphor.core.format import format
from gaphor.core.modeling.properties import attribute
from gaphor.core.styling import (
FontStyle,
FontWeight,
TextAlign,
TextDecoration,
VerticalAlign,
)
from gaphor.diagram.presentation import (
Classified,
Elemen... |
the-stack_106_26240 | # Copyright 2020 EraO Prosopagnosia Helper Dev Team, Liren Pan, Yixiao Hong, Hongzheng Xu, Stephen Huang, Tiancong Wang
#
# Supervised by Prof. Steve Mann (http://www.eecg.toronto.edu/~mann/)
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with th... |
the-stack_106_26242 | """
The main module containing functions for parsing text strings into crs objects.
"""
# possible use module: https://github.com/rockdoc/grabbag/wiki/CRS-WKT-Parser
# also note some paramter descriptions: http://www.geoapi.org/3.0/javadoc/org/opengis/referencing/doc-files/WKT.html
# and see gdal source code: http://g... |
the-stack_106_26244 | """
Test module for . . .
"""
# Standard library imports
from __future__ import (absolute_import, division,
print_function, unicode_literals)
import logging
from os.path import abspath, dirname, join, realpath
from sys import path
# Third party imports
import pytest
# Local imports
logger = l... |
the-stack_106_26246 | """
Transaction support for Gaphor
"""
import logging
from typing import List
from gaphor import application
from gaphor.event import TransactionBegin, TransactionCommit, TransactionRollback
log = logging.getLogger(__name__)
def transactional(func):
"""The transactional decorator makes a function transactional... |
the-stack_106_26247 | # -*- encoding: utf-8 -*-
import os
from datetime import datetime
from boto3.session import Session
from django.conf import settings
from django.core.management.base import BaseCommand
class Command(BaseCommand):
help = 'Backs up PostgreSQL database to AWS S3'
def handle(self, *args, **options):
AWS... |
the-stack_106_26248 | import gzip
import itertools
import re
import zlib
from typing import Tuple, List
from .structs.edge import Edge
from .structs.graph import Graph
from .structs.node import Node
from .utils import smiles2mol
verbose = False
def trace(msg):
if (verbose):
print("[parse.py] " + msg)
# Type ALIASES
Atom = ... |
the-stack_106_26249 | import plotly.graph_objects as go
import pandas as pd
import numpy as np
from dataset_utils import get_datasets
GRID_COLOR = "#595959"
JOB_TITLES = [
'Business Analyst',
'Data Analyst',
'Data Scientist',
'Data Engineer/DBA',
'Software Engineer',
'Statistician/Research Scientist'
]
PROGRAMMING_L... |
the-stack_106_26252 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import csv
import xlwt
def csv_to_xlsx():
with open('1.csv', 'r', encoding='utf-8') as f:
read = csv.reader(f)
workbook = xlwt.Workbook()
sheet = workbook.add_sheet('data') # 创建一个sheet表格
l = 0
for line in read:
print... |
the-stack_106_26256 | from django import forms
from django.urls import reverse
from django.utils.translation import gettext_lazy as _, gettext_noop # NoQA
from pretix.base.forms import SettingsForm
from pretix.base.models import Event
from pretix.control.views.event import (
EventSettingsFormView, EventSettingsViewMixin,
)
class Vacc... |
the-stack_106_26257 | # -*- coding: utf-8 -*-
# Define here the models for your scraped items
#
# See documentation in:
# https://doc.scrapy.org/en/latest/topics/items.html
import scrapy
from scrapy.selector import Selector
from scrapy.loader.processors import TakeFirst, MapCompose, Join
from w3lib.html import remove_tags
def clean_html_... |
the-stack_106_26259 | from urllib.parse import urlencode
from requests import Session
from db_redis import RedisQueue
from request import WeixinRequest
from config import *
import requests
from requests.exceptions import ConnectionError, ReadTimeout
from pyquery import PyQuery as pq
class Spider():
base_url = 'https://weixin.sogou.co... |
the-stack_106_26260 | #!/usr/bin/python
import wiringpi2 as gpio
import time
#init the GPIO
#prepare PWM pins
gpio.wiringPiSetupGpio()
gpio.pinMode(12, gpio.GPIO.PWM_OUTPUT)
gpio.pinMode(13, gpio.GPIO.PWM_OUTPUT)
#prepare PWM channels
gpio.pwmSetMode(gpio.GPIO.PWM_MODE_MS)
gpio.pwmSetRange(480)
gpio.pwmSetClock(2)
#prepare direction pins
g... |
the-stack_106_26261 | """
adbts.tcp.asynchronous
~~~~~~~~~~~~~~~~~~~~~~
Contains functionality for asynchronous Transmission Control Protocol (TCP) transport using `asyncio`.
"""
import asyncio
from .. import exceptions, hints, transport
from . import timeouts
__all__ = ['Transport']
# Disable incorrect warning on asyncio.w... |
the-stack_106_26262 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2018, JK & AGB
# Full license can be found in License.md
# -----------------------------------------------------------------------------
""" Tools for loading solar indices.
Classes
---------------------------------------------------------------------------... |
the-stack_106_26263 | from pypy.rpython.memory.gctransform.transform import GCTransformer
from pypy.rpython.memory.gctransform.support import find_gc_ptrs_in_type, \
get_rtti, ll_call_destructor, type_contains_pyobjs, var_ispyobj
from pypy.rpython.lltypesystem import lltype, llmemory
from pypy.rpython import rmodel
from pypy.rpython.me... |
the-stack_106_26265 | """
Platform support for Programs.
This package is a thin wrapper around interactions with the Programs service,
supporting learner- and author-facing features involving that service
if and only if the service is deployed in the Open edX installation.
To ensure maximum separation of concerns, and a minimum of interde... |
the-stack_106_26266 | import torch
import torch.nn as nn
from . import odeint
from . import odeint_err
from .misc import _flatten, _flatten_convert_none_to_zeros
class OdeintAdjointMethod(torch.autograd.Function):
total_err=[]
@staticmethod
def forward(ctx, *args):
assert len(args) >= 8, 'Internal error: all arguments ... |
the-stack_106_26267 | from common.numpy_fast import clip
from selfdrive.car.ford.values import MAX_ANGLE
def create_steer_command(packer, angle_cmd, enabled, angle_steers, action, angleReq, sappConfig, sappChime):
"""Creates a CAN message for the Ford Steer Command."""
#if enabled and lkas available:
#if enabled: # and (frame % 500)... |
the-stack_106_26269 | #!/usr/bin/env python2
# -*- coding: utf-8 -*-
import cv2
import os
import sys
cv2v = cv2.__version__
if(cv2v[0] >= '3'):
flagCapturePosFrame = cv2.CAP_PROP_POS_FRAMES
elif(cv2v[0] == '2'):
flagCapturePosFrame = cv2.cv.CV_CAP_PROP_POS_FRAMES
if len(sys.argv) == 2:
videoName = sys.argv[1]
else:
print (... |
the-stack_106_26270 | # Imports
import logging
import socket
import logging
from functools import wraps
from flask_login import current_user, LoginManager
from flask import Flask, render_template, request
from flask_sqlalchemy import SQLAlchemy
from functools import wraps
# Config
app = Flask(__name__)
app.config['SECRET_KEY'] = 'LongAndRa... |
the-stack_106_26271 | #!/usr/bin/env python3
# https://adventofcode.com/2021/day/1
INPUT_FILE ='../input/1.txt'
def file_to_ints(input_file):
"""
Input: A file containing one number per line
Output: An int iterable
Blank lines and lines starting with '#' are ignored
"""
with open(input_file) as f:
for line ... |
the-stack_106_26272 | #!/usr/bin/env python
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# ---------------------------------------------... |
the-stack_106_26276 | #!/usr/bin/env python3
import math
import torch
from .. import settings
from .variational_strategy import VariationalStrategy
from ..utils.memoize import cached
from ..lazy import RootLazyTensor, MatmulLazyTensor, CholLazyTensor, \
CachedCGLazyTensor, DiagLazyTensor, BatchRepeatLazyTensor, PsdSumLazyTensor
from ..... |
the-stack_106_26277 | # qubit number=3
# total number=6
import numpy as np
from qiskit import QuantumCircuit, execute, Aer, QuantumRegister, ClassicalRegister, transpile, BasicAer, IBMQ
from qiskit.visualization import plot_histogram
from typing import *
from pprint import pprint
from math import log2
from collections import Counter
from ... |
the-stack_106_26278 | #
# Copyright 2014 Quantopian, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in wr... |
the-stack_106_26279 | def search(value, my_list):
"""Returns the index of a requested value"""
index = 0
# print(my_list)
for i in my_list:
if i == value:
return index
else:
index += 1
return None
def count(value, my_list):
"""Returns the number of times a reques... |
the-stack_106_26281 | import numpy as np
from sklearn.base import BaseEstimator, ClassifierMixin
from sklearn.utils.validation import check_X_y, check_array, check_is_fitted
from sklearn.metrics import euclidean_distances
from sklearn.utils.multiclass import unique_labels
import math
class Node:
def __init__(self,
dept... |
the-stack_106_26282 | import numpy as np
import PILasOPENCV
# getmask in PILasOPENCV does not work with certain characters / fonts / sizes
# this is a quick fix
# XXX: fix properly and make PR to PILasOPENCV
def getmaskFix(text, ttf_font):
slot = ttf_font.glyph
width, height, baseline = PILasOPENCV.getsize(text, ttf_font)
Z =... |
the-stack_106_26284 | # -*- coding: utf-8 -*-
"""
Created on Tue Apr 26 13:44:58 2022
@author: Jens Eriksson
"""
from window_functions import hann_window, corner_hann_window, top_hann_window, bartley_hann_window, triangular_window
from window_functions import build_weighted_mask_array
from matplotlib import pyplot as plt
import numpy as n... |
the-stack_106_26286 | import datetime
import oauthlib.oauth2
import oauthlib.oauth2.rfc6749.tokens
import oauth2_provider.models
import oauth2_provider.oauth2_validators
from oauth2_provider.scopes import BaseScopes
from oauth2_provider.settings import oauth2_settings
from . import generators
def signed_token_generator(request):
to... |
the-stack_106_26287 | # coding=utf-8
import random
from pyecharts.option import get_all_options
from pyecharts.base import Base
import pyecharts.constants as constants
class Chart(Base):
"""
`Chart`类是所有非自定义类的基类,继承自 `Base` 类
"""
def __init__(self, title, subtitle,
width=800,
height=400,
... |
the-stack_106_26290 | import json
from pyramid import testing
from pyramid.response import Response
from unittest import TestCase, mock
from sqlalchemy import create_engine, Column, String, Integer
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from marshmallow import Schema, fields
from... |
the-stack_106_26291 | from multiprocessing import Lock
from contextlib import contextmanager
from typing import NewType
from dbt.adapters.postgres import PostgresConnectionManager
from dbt.adapters.postgres import PostgresCredentials
from dbt.logger import GLOBAL_LOGGER as logger # noqa
import dbt.exceptions
import dbt.flags
import boto3... |
the-stack_106_26292 | #!/usr/bin/env python3
"""Creating a dataframe from a csv or json."""
import pandas as pd
# df.csv
# a,b,c,d
# 1,2,3,4
# 5,6,7,8
# 9,8,7,6
# df.json
# {"a":{"0":1,"1":5,"2":9},"b":{"0":2,"1":6,"2":8},
# "c":{"0":3,"1":7,"2":7},"d":{"0":4,"1":8,"2":6}}
df = pd.read_csv('df.csv', header=0, sep=',', index_col=None,
... |
the-stack_106_26293 | # Licensed under a 3-clause BSD style license - see LICENSE.rst
"""
Analysis defaults options for DM pipelien analysis
"""
from __future__ import absolute_import, division, print_function
generic = {
'outfile': (None, 'Path to output file.', str),
'infile': (None, 'Path to input file.', str),
'summaryfile'... |
the-stack_106_26295 | # ******************************************************************************
# Copyright 2017-2020 Intel 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.apa... |
the-stack_106_26298 | import traceback
import Configuration
from Classes.Logic.LogicLaserMessageFactory import LogicLaserMessageFactory
from Classes.Messaging import Messaging
class MessageManager:
def receiveMessage(self, messageType, messagePayload):
message = LogicLaserMessageFactory.createMessageByType(messageType, messag... |
the-stack_106_26299 | import sys
import os
if len(sys.argv) != 4:
print(len(sys.argv))
sys.exit('Usage: python ' + sys.argv[0] + ' <input pmf.f filename> <mechID from PP> <out pmf.dat filename>')
print('reading pmf fortran file ' + sys.argv[1])
try:
f = open(sys.argv[1])
except Exception as ex:
sys.exit(ex)
lines = f... |
the-stack_106_26300 | # Copyright (c) Facebook, Inc. and its affiliates.
import argparse
import os
import yaml
import ray
from ray import tune
from ray.tune.registry import register_env
def arg_parser():
parser = argparse.ArgumentParser()
''' Specification file of the expriment '''
parser.add_argument("--spec", required=True... |
the-stack_106_26302 | import typing
if typing.TYPE_CHECKING: # pragma: no cover
from .applications import App
class SettingsError(Exception):
"""Raised when a setting is missing, ill-declared or invalid."""
class Settings:
def __init__(self, obj: typing.Optional[typing.Any]):
for setting in dir(obj):
if... |
the-stack_106_26305 | import config
import numpy as np
import os
import tarfile
import torch
import datasets
import datasets.transforms as transforms
from torch.utils.data import DataLoader
from torch.utils.data.dataloader import default_collate
from torch.utils.data.sampler import SubsetRandomSampler
from torch.utils.data.distributed impor... |
the-stack_106_26312 | import asyncio
import collections
import copy
import time
from aiokafka.errors import (KafkaTimeoutError,
NotLeaderForPartitionError,
LeaderNotAvailableError,
ProducerClosed)
from aiokafka.record.legacy_records import LegacyRecordBa... |
the-stack_106_26313 | log_level = 'INFO'
load_from = None
resume_from = None
dist_params = dict(backend='nccl')
workflow = [('train', 1)]
checkpoint_config = dict(interval=5, create_symlink=False)
evaluation = dict(interval=10, metric='mAP', key_indicator='AP')
optimizer = dict(
type='Adam',
lr=5e-4,
)
optimizer_config = dict(grad_... |
the-stack_106_26315 | # coding=utf-8
# Copyright 2021 The Google Flax Team Authors and The HuggingFace Inc. 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
... |
the-stack_106_26318 | # Copyright 2019 The Blueqat Developers
#
# 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 i... |
the-stack_106_26319 | #!/usr/bin/python
#
# Request for historical data (RDM type 12) published by provider.history.tcl
# This domain is not officially supported by Thomson Reuters
# Sample:
# {'MTYPE':'REFRESH','RIC':'tANZ.AX','SERVICE':'NIP'}
# {'SERVICE':'NIP','SALTIM':'08:05:22:612:000:000','MTYPE':'IMAGE','TRADE_ID':'123456789',
# ... |
the-stack_106_26320 | #!/usr/bin/env python3 -u
# Copyright (c) 2017-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the license found in the LICENSE file in
# the root directory of this source tree. An additional grant of patent rights
# can be found in the PATENTS file in the same directory.
import o... |
the-stack_106_26321 | # 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 may ... |
the-stack_106_26323 | from allauth.account.forms import SignupForm
from django import forms
from bims.models import Profile
class CustomSignupForm(SignupForm):
first_name = forms.CharField(
max_length=150,
label='First Name',
required=True)
last_name = forms.CharField(
max_length=150,
label=... |
the-stack_106_26324 | #!/usr/bin/env python
from random import randint
from time import sleep
import unicornhathd as unicorn
print("""Snow
Draws random white pixels to look like a snowstorm.
If you're using a Unicorn HAT and only half the screen lights up,
edit this example and change 'unicorn.AUTO' to 'unicorn.HAT' below.
""")
unicor... |
the-stack_106_26325 | import math
# Fixed parameters
N = 200 # Number of participants
Tmax = 120 # total duration of the simulaion
# Tunable parameters
Tinf = 30 # infectious time
I0 = 1 # number of initial cases
Itot = 150 # total number of cases
cr = 0.005 # per capita contact rate c,
# cr x N is the number ... |
the-stack_106_26326 | from common import Action
import copy
import gym
from gym import spaces
import numpy as np
from random import choice
from copy import deepcopy
from parse_utils import vectorize_obs
class KarelEnv(gym.Env):
N_ACTIONS = 6
# Direction encoding
dir_to_dxy = {"north": (-1, 0), "east": (0, 1),
... |
the-stack_106_26327 | import os
from unittest.mock import patch, PropertyMock
import requests
from memsource import api, constants, models
import api as api_test
class TestApiAnalysis(api_test.ApiTestCase):
def setUp(self):
self.url_base = 'https://cloud.memsource.com/web/api/v2/analyse'
self.analysis = api.Analysis(... |
the-stack_106_26328 | """
#Trains a ResNet on the CIFAR10 dataset.
"""
from __future__ import print_function
import keras
from keras.layers import Dense, Conv2D, BatchNormalization, Activation
from keras.layers import AveragePooling2D, Input, Flatten
from keras.optimizers import Adam
from keras.callbacks import ModelCheckpoint, LearningRa... |
the-stack_106_26332 | """
Tutorial 3: Null models for gradient significance
==================================================
In this tutorial we assess the significance of correlations between the first
canonical gradient and data from other modalities (curvature, cortical
thickness and T1w/T2w image intensity). A normal test of the signi... |
the-stack_106_26333 | # Copyright 2013-2019 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class Trimgalore(Package):
"""Trim Galore! is a wrapper around Cutadapt and FastQC to consistent... |
the-stack_106_26334 | """authentik expression policy evaluator"""
from ipaddress import ip_address, ip_network
from typing import TYPE_CHECKING, Optional
from django.http import HttpRequest
from django_otp import devices_for_user
from structlog.stdlib import get_logger
from authentik.core.models import User
from authentik.flows.planner im... |
the-stack_106_26335 | from Node import error
SYNTAX_NODE_SERIALIZATION_CODES = {
# 0 is 'Token'. Needs to be defined manually
# 1 is 'Unknown'. Needs to be defined manually
'UnknownDecl': 2,
'TypealiasDecl': 3,
'AssociatedtypeDecl': 4,
'IfConfigDecl': 5,
'PoundErrorDecl': 6,
'PoundWarningDecl': 7,
'Poun... |
the-stack_106_26336 | import graphene
import graphene_django
from typing import Dict, Any
from django.db.models.query import QuerySet
from meetup.models import Meetup
from meetup.models import Event
from meetup.models import Attendee
from meetup.models import Attendance
class MeetupType(graphene_django.DjangoObjectType):
"""GraphQL type... |
the-stack_106_26338 | # 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_26339 | #
# -*- coding: utf-8 -*-
# Copyright 2019 Cisco and/or its affiliates.
# GNU General Public License v3.0+
# (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
"""
The nxos hsrp_interfaces class
This class creates a command set to bring the current device configuration
to a desired end-state. The command set is ... |
the-stack_106_26340 | """
Low-level BLAS functions (:mod:`scipy.linalg.blas`)
===================================================
This module contains low-level functions from the BLAS library.
.. versionadded:: 0.12.0
.. warning::
These functions do little to no error checking.
It is possible to cause crashes by mis-using them,
... |
the-stack_106_26341 | from django.shortcuts import render, redirect
from django.conf import settings
from App.models import User
from App.models.song import Song, SpotifyTrackInput
from App.forms import SpotifyTrackInputForm, SpotifySearchForm
import os
import sys
import spotipy
from spotipy.oauth2 import SpotifyOAuth
import spotify_cred ... |
the-stack_106_26342 | """This file and its contents are licensed under the Apache License 2.0. Please see the included NOTICE for copyright information and LICENSE for a copy of the license.
"""
import drf_yasg.openapi as openapi
import logging
import numpy as np
import pathlib
import os
from collections import Counter
from django.db impor... |
the-stack_106_26343 | # coding=utf-8
import numpy as np
from snntoolbox.datasets.utils import get_dataset
class TestGetDataset:
"""Test obtaining the dataset from disk in correct format."""
def test_get_dataset_from_npz(self, _datapath, _config):
data = np.random.random_sample((1, 1, 1, 1))
np.savez_compressed(s... |
the-stack_106_26344 | from __future__ import annotations
import asyncio
import collections.abc
import re
import time
from typing import (
Any,
AsyncGenerator,
Awaitable,
Callable,
Dict,
Optional,
Sequence,
Type,
TypeVar,
)
from bluesky.protocols import Descriptor, Dtype, Reading
from ophyd.v2.core impo... |
the-stack_106_26345 | #!/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.
"""\
Serialize a btrfs subvolume built by an `image_layer` target into a
portable format (either a file, or a directory... |
the-stack_106_26346 | #
# Module providing the `SyncManager` class for dealing
# with shared objects
#
# multiprocessing/managers.py
#
# Copyright (c) 2006-2008, R Oudkerk
# Licensed to PSF under a Contributor Agreement.
#
__all__ = [ 'BaseManager', 'SyncManager', 'BaseProxy', 'Token' ]
#
# Imports
#
import sys
import threading
import ar... |
the-stack_106_26348 | #!/usr/bin/python
# coding: UTF-8
#
# Author: Dawid Laszuk
# Contact: laszukdawid@gmail.com
#
# Feel free to contact for any information.
"""
.. currentmodule:: CEEMDAN
"""
from __future__ import print_function
import logging
import numpy as np
from multiprocessing import Pool
# Python3 handles mutliprocessing ... |
the-stack_106_26352 | '''OpenGL extension APPLE.element_array
Overview (from the spec)
This extension provides facilities to improve DrawElements style vertex
indices submission performance by allowing index arrays. Using this
extension these arrays can be contained inside a vertex array range and
thus pulled directly by the graphic... |
the-stack_106_26354 | import torch
import torch.nn as nn
import torch.nn.functional as func
class DistanceDiscriminator(nn.Module):
def __init__(self, batch_size, out_size):
super().__init__()
self.batch_size = batch_size
self.batch_combine = nn.Linear(batch_size, out_size)
def forward(self, data):
data = data.view(dat... |
the-stack_106_26355 | import json
import logging
import os
import ssl
import webbrowser
from http.server import HTTPServer, BaseHTTPRequestHandler
from queue import Queue
from threading import Thread
from typing import Any, Optional
from peek.connection import EsClient, RefreshingEsClient
_logger = logging.getLogger(__name__)
class _Oid... |
the-stack_106_26357 | #!/Library/Frameworks/Python.framework/Versions/3.5/bin/python3.5
from .basics import *
import pickle
import os
import codecs
from .analysis import Analysis_net
from .analysis_prior import Analysis_prior_net
from .synthesis import Synthesis_net
class Synthesis_prior_net(nn.Module):
'''
Decode synthesis prio... |
the-stack_106_26359 | # -*- coding: utf-8 -*-
"""
Estimate the PSF FWHM for each of the reduced science images, and append the
'reducedFileIndex.csv' with a column containing that information. The PSF FWHM
values will be used to cull data to only include good seeing conditions.
"""
#Import whatever modules will be used
import os
import sys... |
the-stack_106_26361 | #
# 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... |
the-stack_106_26362 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.test import TestCase
from django.contrib.auth.models import User
from django.db import IntegrityError, DataError
from django.db import transaction
from signbank.dictionary.models import (Gloss, Dataset, SignLanguage, Language, Keyword... |
the-stack_106_26363 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Script to test homemade neural network
Args:
- (OPTIONAL) -e number of epochs (default is 200)
- (OPTIONAL) -b mini-batch size (default is 10)
- (OPTIONAL) -s hidden size, number of neurons per layers (default is 50)
- (OPTIONAL) -l learning rate (def... |
the-stack_106_26370 | #!/usr/bin/env python
# Copyright (c) 2012 The Chromium Authors. All rights reserved.
# Copyright (c) 2013 Intel Corporation. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
''' This script provides utils for python scripts in crosswalk.
'''
... |
the-stack_106_26372 | '''patching scipy to fit distributions and expect method
This adds new methods to estimate continuous distribution parameters with some
fixed/frozen parameters. It also contains functions that calculate the expected
value of a function for any continuous or discrete distribution
It temporarily also contains Bootstrap... |
the-stack_106_26373 | #!/usr/bin/python
from smfishHmrf.HMRFInstance import HMRFInstance
from smfishHmrf.DatasetMatrix import DatasetMatrix, DatasetMatrixSingleField, DatasetMatrixMultiField
from smfishHmrf.spatial import rank_transform_matrix, calc_silhouette_per_gene
import sys
import os
import math
import subprocess
import numpy as np
im... |
the-stack_106_26374 | from Population import Population
import matplotlib.pyplot as plt
import copy
def text2array_unicode(string: str) -> list:
"""
Return an array of char ascii codes for each character in string
"""
array_unicode = []
for letter in string:
array_unicode.append(ord(letter))
return array_uni... |
the-stack_106_26375 | import unittest
import codecs
from os import path
from . import xml_response_parsers
testdata_dir = path.join(path.dirname(__file__), 'testdata')
def load_data(filename):
full_path = path.join(testdata_dir, filename)
f = codecs.open(full_path, encoding="utf8")
return f.read()
class TestQuestionResponse... |
the-stack_106_26378 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import io
import os
import sys
from shutil import rmtree
from setuptools import find_packages, setup, Command
from dictquery import __version__
# Package meta-data.
NAME = 'dictquery'
DESCRIPTION = 'Library to query python dicts'
URL = 'https://github.com/cyberlis/dictque... |
the-stack_106_26379 | import torch
import torch.nn as nn
from torch.autograd import Variable
class PoetryNet(nn.Module):
def __init__(self, vocab_size, embedding_dim, hidden_dim, num_layers=2):
super(PoetryNet, self).__init__()
self.hidden_dim = hidden_dim
self.num_layers = num_layers
self.embeddings =... |
the-stack_106_26380 | import unittest
from fds.analyticsapi.engines.api.benchmarks_api import BenchmarksApi
from fds.analyticsapi.engines.model.spar_benchmark_root import SPARBenchmarkRoot
import common_parameters
from common_functions import CommonFunctions
class TestSparBenchmarkApi(unittest.TestCase):
def setUp(self):
se... |
the-stack_106_26382 | # coding:utf8
"""
# pylint: disable=line-too-long
url = "http://web.ifzq.gtimg.cn/appstock/app/hkfqkline/get?_var=kline_dayqfq¶m=hk00001,day,,,660,qfq&r=0.7773272375526847"
url 参数改动
股票代码 :hk00001
日k线天数:660
更改为需要获取的股票代码和天数例如:
# pylint: disable=line-too-long
url = "http://web.ifzq.gtimg.cn/appstock/app/hkfqkline/g... |
the-stack_106_26384 | import pickle
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
import matplotlib.pyplot as plt
import layers as ly
training_file = "train.p"
with open(training_file, mode="rb") as f:
train = pickle.load(f)
X_train, y_train = train["features"], train["labels"]
x = tf.placeholder(tf.float32, (None, 32,... |
the-stack_106_26387 | from collections.abc import Sequence
from itertools import chain
import numpy as np
import tensorflow as tf
from tensorflow.keras.layers import Dense
from tensorflow.python.framework.smart_cond import smart_cond
from .set_utils import (
build_dense_dropout_model, PaddedToSegments, SegmentAggregation,
cumulati... |
the-stack_106_26389 | #!/usr/bin/env python3
'''
Пример для первой лекции про TkInter
Закрытие окошка в постинтерактивном режиме
'''
from tkinter import *
def dump(*args):
print("DUMP:",args)
TKroot = Tk()
TKroot.title("Hello")
root = Frame(TKroot)
root.place(relx=0, rely=0, relheight=1, relwidth=1)
root.columnconfigure(0, weight=... |
the-stack_106_26390 | import re
import tweepy
import pandas as pd
from datetime import date
from textblob import TextBlob
def clean_text(text):
text = re.sub(r'@[A-Za-z0-9]+', '', text) #Remove mentions
text = re.sub(r'#', '', text) #Remove #
text = re.sub(r'RT[\s]:+', '', text) #Remove RT
text = re.sub(r'https:\/\/\S+', '... |
the-stack_106_26391 | import pandas as pd
import pytest
from powersimdata.data_access.context import Context
from powersimdata.input.change_table import ChangeTable
from powersimdata.input.grid import Grid
from powersimdata.tests.mock_context import MockContext
grid = Grid(["USA"])
@pytest.fixture
def ct():
return ChangeTable(grid)
... |
the-stack_106_26393 | import numpy as np
def calc_life(trajs, ub=5, lb=-5):
"""
Identifies transition paths and returns lifetimes of states.
Parameters
----------
trajs : list of lists
Set of trajectories.
ub, lb : float
Cutoff value for upper and lower states.
"""
try:
... |
the-stack_106_26394 | # -------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
# ----------------------------------------------------------------------... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.