text stringlengths 1 927k |
|---|
import os
import subprocess
from huntsman.pocs.utils import DummyLogger
from huntsman.pocs.utils.config import query_config_server, load_device_config
def mount(mountpoint, remote, server_alive_interval=20, logger=None,
server_alive_count_max=3, strict_host_key_checking=False):
'''
Mount remote on l... |
import json
import logging
import os
import time
import yaml
from .socketio import socketio
from .models import db, NFCTagModel
from flask import current_app
from musicfig import colors
from sqlalchemy import func
logger = logging.getLogger(__name__)
# all uses of current_app in here are for config; try just passin... |
import pytest
from trydjango.users.models import User
from trydjango.users.tests.factories import UserFactory
@pytest.fixture(autouse=True)
def media_storage(settings, tmpdir):
settings.MEDIA_ROOT = tmpdir.strpath
@pytest.fixture
def user() -> User:
return UserFactory() |
#!/usr/bin/env python
# Copyright (c) 2012 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.
"""Support for formatting a data pack file used for platform agnostic resource
files.
"""
from __future__ import print_function
i... |
# Databricks notebook source
# MAGIC %md
# MAGIC ### Ingest results.json file
# COMMAND ----------
dbutils.widgets.text("p_data_source", "")
v_data_source = dbutils.widgets.get("p_data_source")
# COMMAND ----------
dbutils.widgets.text("p_file_date", "2021-03-28")
v_file_date = dbutils.widgets.get("p_file_date")
#... |
import logging
from pyvisdk.exceptions import InvalidArgumentError
########################################
# Automatically generated, do not edit.
########################################
log = logging.getLogger(__name__)
def SnapshotFault(vim, *args, **kwargs):
'''Base type for Snapshot-related errors.'''
... |
# -*- coding: utf-8 -*-
'''
Tests for the rabbitmq state
'''
# Import python libs
from __future__ import absolute_import
# Import Salt Testing libs
from tests.support.case import ModuleCase
from tests.support.helpers import skip_if_not_root
from tests.support.mixins import SaltReturnAssertsMixin
@skip_if_not_root
c... |
from setuptools import setup
setup(name='barman_exporter',
version='1.0.7',
description='Barman exporter for Prometheus',
long_description='Barman exporter for Prometheus. Full description at https://github.com/ahes/prometheus-barman-exporter',
url='https://github.com/ahes/prometheus-barman-exp... |
import os
import pickle
# from matplotlib import pyplot as plt
import numpy as np
from . import AGD_decomposer
from . import gradient_descent
from . import ioHDF5
class GaussianDecomposer(object):
def __init__(self, filename=None, phase="one"):
if filename:
temp = pickle.load(open(filename, ... |
# 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 ... |
#!/usr/bin/env python
"""
dos2unix Batch Utility Script
=============================
First, use this for most things:
find . -name *.txt | xargs dos2unix
Second, this is a little smarter (might be faster), and I can control the
globbing a little better.
TODO
----
- implement some accounting (scanned, detect... |
from . import textakel
FUNCTIONS = {
"alphabetical": textakel.alphabetical,
"capitalize": textakel.capitalize,
"casefold": textakel.casefold,
"count_multiples": textakel.count_multiples,
"lower": textakel.lower,
"remove-consonant": textakel.remove_consonant,
"remove-digit": textakel.remove_... |
"""Unit tests for the Switcher WebAPI.
.. codeauthor:: Tomer Figenblat <tomer.figenblat@gmail.com>
"""
from aiohttp import ClientSession
from aioswitcher.api.messages import ResponseMessageType
from aioswitcher.consts import STATE_ON, WEEKDAY_TUP
from asynctest import MagicMock, patch
from bs4 import BeautifulSoup
... |
#!/usr/bin/env python
"""Django's command-line utility for administrative tasks."""
import os
import sys
#!/usr/bin/env python
def main():
"""Run administrative tasks."""
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core_app.settings')
try:
from django.core.management import execute_from_comman... |
###############################################################################
#
# Tests for XlsxWriter.
#
# Copyright (c), 2013-2020, John McNamara, jmcnamara@cpan.org
#
from ..excel_comparison_test import ExcelComparisonTest
from ...workbook import Workbook
class TestCompareXLSXFiles(ExcelComparisonTest):
"""... |
from lusidtools.lpt import lpt
from lusidtools.lpt import lse
from lusidtools.lpt import stdargs
from lusidtools.lpt import txn_config_yaml as tcy
TOOLNAME = "txn_cfg"
TOOLTIP = "Get/Set the transaction configuration"
def parse(extend=None, args=None):
return (
stdargs.Parser(
"Get/Set transa... |
# -*- coding: utf-8 -*-
# In this script we find all the history behind an evicted task that has not been finished/killed/failed/lost.
# We find how many times it has been submitted and what were the events related to this task.
# The violatedtasks dictionary is the one that is we are looking for. It has only one ent... |
import pandas as pd
from pathlib import Path
from time import perf_counter
from utils import get_document_store, get_retriever, index_to_doc_store, load_config
from haystack.preprocessor.utils import eval_data_from_json
from haystack.document_store.faiss import FAISSDocumentStore
from haystack import Document
import p... |
# -*- coding: utf-8 -*-
#
# Copyright © Spyder Project Contributors
# Licensed under the terms of the MIT License
# (see spyder/__init__.py for details)
"""
Base plugin class
"""
# Standard library imports
import inspect
import os
import sys
# Third party imports
import qdarkstyle
from qtpy.QtCore import Qt, Slot
fr... |
# -*- mode: python; encoding: utf-8 -*-
#
# Copyright 2014 the Critic contributors, Opera Software ASA
#
# 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/LI... |
"""
plotStats() method to collect statistics for the track data.
Author: Kunal Singh
Email: pykunalsingh@gmail.com
"""
def plotStats(fileName):
# read in a playlist
with open(fileName, 'rb') as fp:
plist = plistlib.load(fp)
# get the tracks from the playlist
tracks = plist['Tracks']
... |
from django.core.management import call_command
from django.db import connection, connections, models
from tenant_schemas.postgresql_backend.base import _check_schema_name
from tenant_schemas.signals import post_schema_sync
from tenant_schemas.utils import (get_public_schema_name, schema_exists,
... |
# 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... |
import sanitize_sheet
import pytest
def test_check_info():
info = ['abcdef']
assert(sanitize_sheet.check_sampleNames(info))
info = ['abcdefghijklmnopqrstuvwxy1234']
with pytest.raises(Exception):
sanitize_sheet.check_info(info)
def test_check_for_sequence():
assert(sanitize_sheet.check_for_... |
"""
Copyright (c) Facebook, Inc. and its affiliates.
"""
import unittest
import droidlet.base_util
import droidlet.lowlevel.minecraft.shape_helpers
import droidlet.lowlevel.minecraft.shapes
import droidlet.lowlevel.minecraft.shapes as shapes
from agents.craftassist.tests.base_craftassist_test_case import BaseCraftassi... |
from .ble_attribute_abstract import BleAttributeAbstract
class BleRemoteAttributeAbstract(BleAttributeAbstract):
def __init__(self, params):
super().__init__(params)
self.isRemote = False
self.discoverdOnRemote = False
@property
def ws_child_uuid_name(self):
children_name... |
# -*- coding: utf-8 -*-
# PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
# https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
from ccxt.base.exchange import Exchange
from ccxt.base.errors import ExchangeError
from ccxt.base.errors import AuthenticationError
from cc... |
# python 3
# requires reverse_https-tor2web_listener.py running as a tor hidden service on connect back host
# encoding is not quite right - multi-line returns (e.g., that of `dir`) format poorly
from urllib.request import urlopen,Request
from urllib.parse import urlencode
from urllib.error import URLError
from subpr... |
# coding=utf-8
import math
import torch
import numpy as np
from torch.nn import init
from itertools import repeat
from torch.nn import functional as F
import collections.abc as container_abcs
from typing import Optional
from torch.nn.parameter import Parameter
from torch.nn.modules.module import Module
class DOConv2... |
from django.urls import path
from . import views
from .apps import app_name
app_name = app_name
urlpatterns = [
path('', views.FblogListView.as_view(), name='list'),
path('create/', views.FblogCreateView.as_view(),
name='create'),
] |
from .cgnet import CGNet
from .fast_scnn import FastSCNN
from .hrnet import HRNet
from .mobilenet_v2 import MobileNetV2
from .mobilenet_v3 import MobileNetV3
from .resnest import ResNeSt
from .resnet import ResNet, ResNetV1c, ResNetV1d
from .resnet import ResNet_sp, ResNetV1c_sp, ResNetV1d_sp
from .resnext import ResNe... |
import pytest
from django.urls import resolve, reverse
from django_machinelearning.users.models import User
pytestmark = pytest.mark.django_db
def test_detail(user: User):
assert (
reverse("users:detail", kwargs={"username": user.username})
== f"/users/{user.username}/"
)
assert resolve(... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Submission file for the python difference_of_squares exercise.
#
# v2: Using "x*x" instead of the slower "x**2" and remove left over
# "pass" statement in difference()
# v1: Using sum(), abs(), range() and "**2"
def difference(length):
"""
Return the (abso... |
"""
Test settings for merlin project.
- Used to run tests fast on the continuous integration server and locally
"""
from .base import * # noqa
# DEBUG
# ------------------------------------------------------------------------------
# Turn debug off so tests run faster
DEBUG = False
TEMPLATES[0]['OPTIONS']['debug']... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# dagger documentation build configuration file, created by
# sphinx-quickstart on Fri Jun 9 13:47:02 2017.
#
# This file is execfile()d with the current directory set to its
# containing dir.
#
# Note that not all possible configuration values are present in this
# auto... |
# -*- coding: utf-8 -*-
"""
Convert README file from Markdown to text
"""
from markdown import markdown
import html2text # from `aaronsw` :(
MARKER = 'MARKER()()MARKER'
def fix_quotes(mdcontent):
count = 0
quote_state = False
quote_char = '`'
quote_string = ''
new_string = ''
quotes = []
... |
def split_caps(key):
""" splits a string using capital letters as separator
eg split_caps('ExampleString') returns ['Example', 'String']
"""
b = False
lst = []
x = 0
for i, ch in enumerate(key):
if i > 0 and ch.isupper():
temp = key[x:i]
if b and not temp... |
# coding=utf-8
# Copyright 2022 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicab... |
from uuid import UUID
import dao.user_dao as dao
from api import db
from utils.common import PlutoException
class InvalidUserException(PlutoException):
pass
def create_user(username: str, user_attributes):
uuid = UUID(user_attributes.get('sub', None))
existing_user = dao.find_user(uuid)
if existing... |
"""Creates New Test Command."""
from ..commands import BaseScaffoldCommand
class TestCommand(BaseScaffoldCommand):
"""
Creates a new test case.
test
{name : Name of the test you would like to create}
"""
scaffold_name = "Test"
postfix = ""
prefix = "Test"
template = "/masonit... |
import sqlite3
from .db import DB
class CounsellingInfoTable(DB):
def __init__(self):
self.table_name = 'WB_counselling'
self.table_desc = 'West Bengal ambulance and tele-counselling information'
self.cols = self.getcolumns()
def getcolumns(self):
cols = {
'date':... |
# Data Preprocessing Tools for Data Cleaning
# Import libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_ ('')
X = dataset.iloc[:, :-1].values
y = dataset.iloc[:, -1].values
print(X)
print(y)
# Taking care of missing data
from sklearn.impute imp... |
from distutils.core import setup
from catkin_pkg.python_setup import generate_distutils_setup
d = generate_distutils_setup()
d['packages'] = ['resource_retriever']
d['scripts'] = []
d['package_dir'] = {'': 'src'}
setup(**d) |
# coding: utf-8
from __future__ import absolute_import
import warnings
import textwrap
from ruamel.yaml.compat import utf8
if False: # MYPY
from typing import Any, Dict, Optional, List, Text # NOQA
__all__ = [
'FileMark', 'StringMark', 'CommentMark', 'YAMLError', 'MarkedYAMLError',
'ReusedAnchorWarn... |
from tezos_private_node_connectivity_checker import application
if __name__ == "__main__":
application.run() |
import re
import mistune
from fluffy.app import app
from fluffy.component.highlighting import guess_lexer
from fluffy.component.highlighting import PygmentsHighlighter
class HtmlCommentsInlineLexerMixin:
"""Strip HTML comments inside lines."""
def enable_html_comments(self):
self.rules.html_comment... |
"""
Comma Separated Values - CSV (Valores separados por vírgula)
É um formato de dados muito usado em tabelas (Excel, Google Sheets), bases de
dados, clientes de e-mail, etc...
"""
import csv
with open('clientes.csv', 'r') as arquivo:
dados = [x for x in csv.DictReader(arquivo)]
with open('cliente2.csv', 'w') as ... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from .. import... |
#!/usr/bin/env python3
from .input import myinput
from .utils import loop, mywrapper
from .widgets import Border, CMDInput, Text, VList
__all__ = [
'loop',
'myinput',
'mywrapper',
# widgets
'Border',
'CMDInput',
'Text',
'VList',
]
name = 'mytui' |
'''Character counting as a fold'''
from functools import reduce
from itertools import repeat
from os.path import expanduser
# charCounts :: String -> Dict Char Int
def charCounts(s):
'''A dictionary of
(character, frequency) mappings
'''
def tally(dct, c):
dct[c] = 1 + dct[c] if c in dct e... |
#!/usr/bin/env python
"""Tests for grr.server.checks.filters."""
import collections
from grr.lib import flags
from grr.lib.rdfvalues import anomaly
from grr.lib.rdfvalues import client as rdf_client
from grr.lib.rdfvalues import paths as rdf_paths
from grr.lib.rdfvalues import protodict as rdf_protodict
from grr.server... |
from __future__ import absolute_import
from pants.base.build_environment import get_scm
from pants.base.payload import Payload
from pants.base.payload_field import PrimitiveField
from pants.build_graph.target import Target
class DockerTargetBase(Target):
def __init__(self, address=None, payload=None, image_name=Non... |
from __future__ import print_function
import os, pdb, sys, glob
# we need to set GPUno first, otherwise may out of memory
stage = int(sys.argv[1])
gpuNO = sys.argv[2]
model_dir = sys.argv[3]
test_dir = sys.argv[4]
os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"]=str(gpuNO)
import StringI... |
""""
Copyright 2010 Shahriyar Amini
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 ... |
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# Copyright (c) 2020, Sandflow Consulting LLC
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, ... |
# ===============================================================================
# Copyright 2019 ross
#
# 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... |
try:
from configparser import RawConfigParser
except ImportError:
from ConfigParser import RawConfigParser
import logging
import os
import re
import socket
import threading
from stomp.backward import *
log = logging.getLogger('testutils.py')
config = RawConfigParser()
config.read(os.path.join(os.path.dirnam... |
import os
import numpy as np
import pytest
from docarray import Document
from docarray.document.generators import from_files
from docarray.helper import __windows__
cur_dir = os.path.dirname(os.path.abspath(__file__))
def test_video_convert_pipe(pytestconfig, tmpdir):
num_d = 0
fname = str(tmpdir / f'tmp{n... |
''' GridWorldMDPClass.py: Contains the GridWorldMDP class. '''
# Python imports.
from __future__ import print_function
import random
import sys
import os
import numpy as np
# Other imports.
from simple_rl.mdp.MDPClass import MDP
from simple_rl.tasks.grid_world.GridWorldStateClass import GridWorldState
# Fix input to... |
"""
XStatic resource package
See package 'XStatic' for documentation and basic tools.
"""
# official name, upper/lowercase allowed, no spaces
DISPLAY_NAME = 'bootswatch'
# name used for PyPi
PACKAGE_NAME = 'XStatic-%s' % DISPLAY_NAME
NAME = __name__.split('.')[-1] # package name (e.g. 'foo' or 'foo_bar')
... |
# Copyright (c) 2019 Seven Bridges. See LICENSE
__version__ = "2019.11.27" |
# --------------------------------------------------------------------------
# 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 cause incor... |
import numpy as np
import cvxpy as cp
import dccp
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon
from sklearn.base import BaseEstimator, ClassifierMixin, TransformerMixin
from sklearn.utils.multiclass import unique_labels
from sklearn.metrics import pairwise_distances
from sklearn.utils.validati... |
from nevada.Common.Connector import *
from typing import List
import jsonpickle
import json
class AdFieldObject:
def __init__(self, json_def=None):
if type(json_def) is str:
json_def = json.loads(json_def)
s = json_def
self.pc_display = None if 'pc' not in s else self.pc_display... |
# Copyright (c) 2017-present, Facebook, 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... |
import torch
import torch.nn as nn
import torch.nn.functional as F
class MolDQN(nn.Module):
def __init__(self, input_length, output_length):
super(MolDQN, self).__init__()
self.linear_1 = nn.Linear(input_length, 1024)
self.linear_2 = nn.Linear(1024, 512)
self.linear_3 = nn.Linear(... |
# -*- coding: utf-8 -*-
import pandas as pd
from jqdatasdk import auth, logout, finance, query
from zvt.recorders.joinquant.common import to_jq_entity_id
from zvt import zvt_env
from zvt.api import TIME_FORMAT_DAY, get_str_schema
from zvt.contract.api import df_to_db
from zvt.contract.recorder import TimeSeriesDataRec... |
import time
import math
import bpy
import bmesh
import bgl
from typing import List, Callable
from mathutils import Vector, Matrix, Color, kdtree
from mathutils.bvhtree import BVHTree
from mathutils.geometry import intersect_point_line, intersect_line_plane
from bpy_extras import view3d_utils
from .maths import Poin... |
class MockFile:
def read(self):
return False
class RequestHandler:
def __init__(self):
self.contentType = ""
self.contents = MockFile()
def getContents(self):
return self.contents.read()
def read(self):
return self.contents
def setStatus(self, status):
... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from ... import _utilities, _tables
from... |
import glob
import numpy as numpy
import cv2
import os
import random
label_list = glob.glob("./iafoss_data/256_filter/label/*.png")
file_list = glob.glob("./iafoss_data/256_filter/train/*.png")
assert len(label_list) == len(file_list), "error"
for i in range(len(label_list)):
label = cv2.imread(label_list[i], 0)
... |
from rest_framework import generics
from rest_framework.response import Response
from .request_dispatcher import dispatch_course_create_request
from .request_dispatcher import dispatch_course_get_request
from .request_dispatcher import (dispatch_student_create_request, dispatch_student_get_request,
... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
"""
The main class to obtain the compensation parameters from the clients, aggregate them,
and share the aggregation results with the server
Copyright 2021 Reza NasiriGerdeh. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in co... |
import math
from pathlib import Path
import numba
import numpy as np
from spconv.spconv_utils import (
non_max_suppression_cpu, rotate_non_max_suppression_cpu)
from second.core import box_np_ops
from second.core.non_max_suppression.nms_gpu import rotate_iou_gpu
def nms_cc(dets, thresh):
scores = dets[:, 4]
... |
import os
win32_defines = ["#define _GLFW_WIN32 1",
"#ifdef _MSC_VER\n#define _CRT_SECURE_NO_WARNINGS\n#endif",
"#define LSH_GLFW_USE_HYBRID_HPG",
"#ifdef LSH_GLFW_USE_HYBRID_HPG\n#define _GLFW_USE_HYBRID_HPG 1\n#endif",
"#define _UNICODE",
... |
import ldap3
from allauth.socialaccount.models import SocialAccount
from django.conf import settings
from base.management import BaseCommand
def init_ldap():
server = ldap3.Server("ldap://ads.mwn.de")
connection = ldap3.Connection(
server,
"CN=%s,OU=Users,ou=TU,ou=IAM,dc=ads,dc=mwn,dc=de" % ... |
# 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
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, ... |
# -*- coding: utf-8 -*-
#
# django-codenerix
#
# Codenerix GNU
#
# Project URL : http://www.codenerix.com
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LI... |
import numpy as np
import torch
from sklearn.metrics import roc_auc_score
from tqdm import tqdm
import config as c
from model import get_cs_flow_model, save_model, FeatureExtractor, nf_forward
from utils import *
def train(train_loader, test_loader):
model = get_cs_flow_model()
optimizer = torch.optim.Adam(mo... |
import random
from thehive4pyextended import TheHiveApiExtended
from thehive4py.query import Eq
from st2common.runners.base_action import Action
__all__ = [
'RunAnalyzerOnDataTypeAction'
]
class RunAnalyzerOnDataTypeAction(Action):
def run(self, case_id, data_type, analyzer_name, linked_task_name=None):
... |
# Copyright 2012 OpenStack Foundation
# Copyright 2013 Nebula 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... |
import logging
import pickle
_logger = logging.getLogger("theano.gof.callcache")
class CallCache:
def __init__(self, filename=None):
self.filename = filename
try:
if filename is None:
raise OSError("bad filename") # just goes to except
with open(filename)... |
import socket
import gevent
import time
from tempfile import NamedTemporaryFile
from locust.user import task, TaskSet
from locust.contrib.fasthttp import FastHttpSession
from locust import FastHttpUser
from locust.exception import CatchResponseError, InterruptTaskSet, ResponseError
from locust.main import is_user_clas... |
r"""
Set of homomorphisms between two affine schemes
For schemes `X` and `Y`, this module implements the set of morphisms
`Hom(X,Y)`. This is done by :class:`SchemeHomset_generic`.
As a special case, the Hom-sets can also represent the points of a
scheme. Recall that the `K`-rational points of a scheme `X` over `k`
c... |
import os
import shutil
import subprocess
import sys
import glob
APK_NAME = "vulkanTexturearray"
SHADER_DIR = "texturearray"
ASSETS_TEXTURES = ["texturearray_bc3_unorm.ktx", "texturearray_astc_8x8_unorm.ktx", "texturearray_etc2_unorm.ktx"]
if subprocess.call("ndk-build", shell=True) == 0:
print("Build successf... |
def sign_executable(executable_filename):
print("Signing '{}'".format(executable_filename)) |
import struct
fr = open("albums.db", "rb")
fr.seek(0,2) # seek end
flen = fr.tell()
fr.seek(0) # seek set
l = struct.unpack("I", fr.read(4))
l = l[0]
print "Found %d records" % l
print "File size should be:"
print " count 512"
print " tracks %d" % (l * 512) #struct.calcsize(track_struct_format))
print " ... |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# File : program_translator.py
# Author : Jiayuan Mao
# Email : maojiayuan@gmail.com
# Date : 09/30/2018
#
# This file is part of NSCL-PyTorch.
# Distributed under terms of the MIT license.
"""
Tools for translating programs into different formats.
"""
from copy im... |
#!/usr/bin/env python
from io import BufferedWriter, FileIO
import os
from ajaxuploader.backends.base import AbstractUploadBackend
from django.conf import settings
from panda.api import DataUploadResource, RelatedUploadResource, UserResource
from panda.models import Dataset, DataUpload, RelatedUpload, UserProxy
cla... |
#!/usr/bin/env python3
# Copyright (c) 2004-present Facebook All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
from enum import Enum
class Entity(Enum):
Location = "Location"
LocationType = "LocationType"
Equipment = "Equipment"
... |
"""
Given a non-empty array of integers nums, every element appears twice except for one. Find that single one.
You must implement a solution with a linear runtime complexity and use only constant extra space.
Example 1:
Input: nums = [2,2,1]
Output: 1
Example 2:
Input: nums = [4,1,2,1,2]
Output: 4
Example 3:
Inpu... |
""" Some Modules Imported by @Nitesh_231 :) & Again @heyworld roks *_* """
import asyncio
import os
import re
import requests
from html_telegraph_poster.upload_images import upload_image
from PIL import Image, ImageDraw, ImageFont
from telegraph import exceptions, upload_file
from validators.url import url
from wget ... |
import sys
import json
from random import seed
from random import randint
import boto3
sys.path.insert(0, "../src")
import bioims
artifactClient = bioims.client('artifact')
# print(artifactClient.getLambdaArn())
# seed(1)
# mids=[]
# for i in range(10):
# artifact = {
# "contextId" : 'plate-'+str(i),
#... |
import uuid
import os
from django.db import models
from django.contrib.auth.models import (AbstractBaseUser, BaseUserManager,
PermissionsMixin)
from django.conf import settings
def recipe_image_file_path(instance, filename):
"""Generate file path for new recipe image"""
... |
# -*- coding: utf-8 -*-
"""Methods to generalize any graph for its path analysis."""
import logging
from typing import Dict, Tuple, Any, List
from networkx import DiGraph, isolates
__all__ = [
'generate_reduced_graph',
]
logger = logging.getLogger(__name__)
def remove_isolated_nodes(graph: DiGraph):
"""R... |
#Se crean los inputs
rate = input("Enter Rate:")
hrs = input("Enter Hours:")
#Se toman los valores y se convierten en float ambos por que string y float no se pueden multiplicar directamente
pay = float(rate) * float(hrs)
#Se imprime el resultado de pay
print("Pay:",pay) |
# encoding: utf-8
"""Shared DB-API test cases"""
from __future__ import absolute_import
from __future__ import unicode_literals
from builtins import object
from builtins import range
from future.utils import with_metaclass
from avanthive import exc
import abc
import contextlib
import functools
def with_cursor(fn):
... |
#!/usr/bin/env python
# coding: utf-8
"""
create at 2017/11/5 by allen
""" |
from inspect import signature
from typing import Callable, Any, List
import re
import copy
from .type import Type
class Function(Type):
def __init__(self, fn: Callable[..., Any], name: str = "anonymouse") -> None:
self.name = name
self.vars = list(signature(fn).parameters)
self.expr = "[bu... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.