input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
import sys, os
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
from tqdm import tqdm
import learningHelper as lh
import datetime
# sageconv
from typing import Union, Tuple
from torch_geometric.typing import OptPairTensor, Adj, Size
from torch import Tensor
from torch.n... | |
import struct
import sys
import timeit
import threading
import pdb
import bpy
import mathutils
import os.path
from bpy.props import *
from bpy_extras.image_utils import load_image
from ast import literal_eval as make_tuple
from math import sqrt
from math import atan2
import re
import bmesh
def openclose(file):
oc... | |
user_alert infos for particular user with alerts.
Parameters:
:param alert_infos: alert_infos list for particular user
:param user: user details format is list type: [(<userIndicator>, <userValue>)]
Returns:
:return: parsed alerts
"""
# Initialize user_alerts list
user_alerts = list()
last_run_user_alert_has... | |
+ m.x2831
+ m.x2981 == 1)
m.c3133 = Constraint(expr= m.x132 + m.x282 + m.x432 + m.x582 + m.x732 + m.x882 + m.x1032 + m.x1182 + m.x1332 + m.x1482
+ m.x1632 + m.x1782 + m.x1932 + m.x2082 + m.x2232 + m.x2382 + m.x2532 + m.x2682 + m.x2832
+ m.x2982 == 1)
m.c3134 = Constraint(expr= m.x133 + m.x283 + m.x433 + m.x583 + m... | |
"▁Alte": 26872,
"▁Criminal": 26873,
"▁cyn": 26874,
"▁sty": 26875,
"Wie": 26876,
"cente": 26877,
"elim": 26878,
"fut": 26879,
"habita": 26880,
"haq": 26881,
"kulam": 26882,
"rur": 26883,
"tekin": 26884,
"ʊ": 26885,
"▁17.00": 26886,
"▁Bilo": 26887,
"▁Kunde": 26888,
"▁Mulla": 26889,
"▁Norden": 26890,
"▁... | |
"""
Copyright 2020 The OneFlow Authors. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed... | |
deepCopySeq(self.checkRamp(ramp))
self.lengthRamp = len(ramp)
if self.lengthRamp > self.height :
self.height = self.lengthRamp
#print "self.height 2", self.height
self.numOfRampValues.set(self.lengthRamp)
self.linesPerRampValue = self.height / float(self.lengthRamp)
self.resizeCanvases(self.height)
self.guiRam... | |
<gh_stars>10-100
from base64 import b64decode
import glob
import gzip
import zlib
import re
import flask
import dash_ngl
import dash
from dash.dependencies import Input, Output, State
from dash.dash import no_update
import dash_html_components as html
import dash_core_components as dcc
import dash_bootstrap_componen... | |
from inspect import cleandoc
import pathlib
from mlinspect import PipelineInspector
from mlinspect.utils import get_project_root
import os
from mlinspect.utils import store_timestamp
import time
# ########################################### FOR THE SIMPLE OP BENCHMARK ##############################################
cla... | |
# -*- coding: utf-8 -*-
"""
Created on Tue Mar 29 12:31:30 2022
@author: LENOVO
"""
import biosteam as bst
import thermosteam as tmo
import numpy as np
from chaospy import distributions as shape
import biosteam as bst
import numpy as np
# All units are explicitly defined here for transparency and easy reference
# Nam... | |
<filename>cuppa/dependencies/boost/boost_builder.py
# Copyright <NAME> 2011-2018
# Distributed under the Boost Software License, Version 1.0.
# (See accompanying file LICENSE_1_0.txt or copy at
# http://www.boost.org/LICENSE_1_0.txt)
#-------------------------------------------------------------------------------
# B... | |
<reponame>cvandeplas/plaso
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright 2014 The Plaso Project Authors.
# Please see the AUTHORS file for details on individual authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You... | |
# Generated by Django 2.1.1 on 2019-05-08 09:49
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('contenttypes', '0002_remove_content_type_name'),
('rbac', '0001_initial'),
]
operations = [
migrations.CreateMod... | |
'''
Created on Oct 5, 2011
@author: grant
provides python methods to perform generate isosurfaces
using marching cubes or marching tetrahedrons
'''
import numpy, time
from TriModel import TriModel
edgeTable = [
0x0 , 0x109, 0x203, 0x30a, 0x406, 0x50f, 0x605, 0x70c,
0x80c, 0x905, 0xa0f, 0xb06, 0xc0a, 0xd... | |
<gh_stars>0
import gc
import unittest
from hecuba import config, StorageNumpy
import uuid
import numpy as np
from storage.api import getByID
from time import time as timer
import random
class StorageNumpyTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.old = config.execution_name
config.execution_... | |
# coding: utf-8
"""
Automated Tool for Optimized Modelling (ATOM)
Author: Mavs
Description: Unit tests for basetrainer.py
"""
from unittest.mock import patch
import pytest
from mlflow.tracking.fluent import ActiveRun
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import f1_score, make_scor... | |
def visit_Lambda(self, node):
# Like FunctionDef, but without the decorator_list or name.
assert node._fields == ('args', 'body'), node._fields
with self._NewScopeCtx(include_class_scopes=True):
self.visit(node.args)
old_in_FunctionDef = self._in_FunctionDef
self._in_FunctionDef = True
with self._NewScopeCtx():
... | |
# regression test dla SAX 2.0
# $Id$
z xml.sax zaimportuj make_parser, ContentHandler, \
SAXException, SAXReaderNotAvailable, SAXParseException
zaimportuj unittest
spróbuj:
make_parser()
wyjąwszy SAXReaderNotAvailable:
# don't try to test this module jeżeli we cannot create a parser
podnieś unittest.SkipTest("no X... | |
<gh_stars>1-10
# Generated from SQLParser.g4 by ANTLR 4.9.3
from antlr4 import *
if __name__ is not None and "." in __name__:
from .SQLParser import SQLParser
else:
from SQLParser import SQLParser
"""
Copyright (c) 2018, 2020, Oracle and/or its affiliates. All rights reserved.
This program is free software; you can... | |
# based on DeepLTL: https://github.com/reactive-systems/deepltl
# pylint: disable=line-too-long
"""Parser for LTL formulas in different notations"""
from enum import Enum
import re
import random
from functools import reduce, total_ordering
import operator
import sympy as sy
import sympy.logic as syl
# Regular expre... | |
to s3 and return the location.
Returns: s3 uri
"""
local_mode = self.output_path.startswith("file://")
if self.code_location is None and local_mode:
code_bucket = self.sagemaker_session.default_bucket()
code_s3_prefix = "{}/{}".format(self._current_job_name, "source")
kms_key = None
elif self.code_location is... | |
import pytest
import numpy as np
from numpy.testing import assert_array_almost_equal, assert_equal
from SciDataTool import DataLinspace, DataTime, Norm_ref, Data1D, DataPattern
@pytest.mark.validation
def test_get_data_along():
f = 50
Time = DataLinspace(
name="time",
unit="s",
initial=0,
final=1 / f,
number=... | |
# 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, soft... | |
has
changed, or None if the file hasn't changed at all.
"""
file_contents = _ReadWriteableFile(iwyu_record.filename,
flags.dry_run or flags.checkout_command)
if not file_contents:
print('(skipping %s: not a writable file)' % iwyu_record.filename)
return None
print(">>> Fixing #includes in '%s'" % iwyu_record.fi... | |
'accountName': self._serialize.url("account_name", account_name, 'str', max_length=50, min_length=3, pattern=r'^[a-z0-9]+(-[a-z0-9]+)*'),
'databaseName': self._serialize.url("database_name", database_name, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameter... | |
# PlacesCNN for scene classification
#
# by <NAME>
# last modified by <NAME>, Dec.27, 2017 with latest pytorch and torchvision (upgrade your torchvision please if there is trn.Resize error)
import torch
import datetime
from torch.autograd import Variable as V
import torchvision.models as models
from torchvision import... | |
raise NotImplementedError
else:
raise NotImplementedError
@torch.jit.unused
def _set_aux_loss(self, outputs_class, outputs_coord):
# this is a workaround to make torchscript happy, as torchscript
# doesn't support dictionary with non-homogeneous values, such
# as a dict having both a Tensor and a list.
return ... | |
= assignments
if device_states is not None:
body['device_states'] = device_states
if install_summary is not None:
body['install_summary'] = install_summary
if user_state_summary is not None:
body['user_state_summary'] = user_state_summary
return client.update_managed_e_books(managed_e_book_id=managed_e_bo... | |
import demistomock as demisto
from CommonServerPython import *
from CommonServerUserPython import *
"""" IMPORTS """
import json
import requests
from datetime import datetime, timedelta
# Disable insecure warnings
requests.packages.urllib3.disable_warnings()
''' GLOBAL VARS '''
# PagerDuty API works only with secured... | |
Reservation)
def terminate_instances(self, instance_ids=None):
"""
Terminate the instances specified
@type instance_ids: list
@param instance_ids: A list of strings of the Instance IDs to terminate
@rtype: list
@return: A list of the instances terminated
"""
params = {}
if instance_ids:
self.build_list... | |
<filename>report/oraclerpt.py<gh_stars>0
# -*- coding:utf-8 -*-
'''
@project: '__dbreport__.py'
@modules: report.oraclerpt
@description:
@author: abelit
@email: <EMAIL>
@created:Mar 5, 2018
@licence: GPL
'''
__version__ = '''$Id$'''
# from reportlab.lib.testutils import outputfile,setOutDir
# setOutDir(__name__)
fro... | |
import json
import unittest
from flask_caching import Cache
from app import app, db
from apps.shop.models import (
ShopItems,
ShopCategories,
ShopItemsCategoriesMapping,
ShopItemLogos,
ShopItemsURLMapping
)
from apps.users.models import Users, UsersAccessTokens, UsersAccessLevels, UsersAccessMapping... | |
tP["lsc"])
else:
kStr += (tP["lsp"] if tP["grcv"] else tP["lvp"])
kStr += ")";
if tP["grcv"] == tP["tlu"]:
kStr += "*GLOBAL_LOAD_VECTOR_WIDTH_%s" % tP["tensorChar"]
kStr += ";%s" % self.endLine
return kStr
##############################################################################
# Local Write Addresses: ... | |
#!/usr/bin/env python
#
# meza command
#
import sys, getopt, os
# Handle pressing of ctrl-c. Make sure to remove lock file when deploying.
deploy_lock_environment = False
def sigint_handler(sig, frame):
print('Cancelling...')
if deploy_lock_environment:
print('Deploy underway...removing lock file')
unlock_depl... | |
optional request ID to identify requests. Specify
a unique request ID so that if you must retry your request, the server
will know to ignore the request if it has already been completed. The
server will guarantee that for at least 60 minutes since the first
request. For example, consider a situation where you make ... | |
False
else:
in_context = True
inContextImportName = context + '.' + importName
if not parentName:
inContextParentName = context
else:
inContextParentName = context + '.' + parentName
inContextTopName = context + '.' + topName
contextTopName = JS("@{{context}}.__split('.')[0]")
# Check if we already have impo... | |
<reponame>Carlor87/naima
# Licensed under a 3-clause BSD style license - see LICENSE.rst
from __future__ import (
absolute_import,
division,
print_function,
unicode_literals,
)
import numpy as np
import astropy.units as u
from astropy.table import Table, QTable
from astropy import log
import warnings
import ast
fr... | |
<reponame>shashiongithub/Document-Modeling-with-External-Information
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import sys
sys.path.append('../../common')
import math
import os
import random
import sys
import time
import pdb
import numpy as np
import t... | |
or args.dataset == "cnormal1b" or args.dataset == "lognormal1b" or args.dataset == "normal1b" or args.dataset == "test" or "tti1m" in args.dataset or "tti1b" in args.dataset:
fvecs_write(split_data_path, split_data)
elif "glove" in args.dataset:
hf = h5py.File(split_data_path, 'w')
hf.create_dataset('dataset', d... | |
<gh_stars>1-10
#!/usr/bin/python
# Copyright (c) 2014, <NAME>
# Released subject to the New BSD License
# Please see http://en.wikipedia.org/wiki/BSD_licenses
from __future__ import print_function, unicode_literals
import imp
import os
import random
import re
import string
import sys
import time
from datetime import... | |
# -*- coding: utf-8 -*-
import logging
import os
import socket
import sys
import time
from copy import deepcopy
from multiprocessing import Process, Queue
import env
import pytest
import plumbum
from plumbum import (
NOHUP,
CommandNotFound,
ProcessExecutionError,
ProcessTimedOut,
RemotePath,
SshMachine,
local,... | |
board.s8b+board.s8c+board.s8d+board.s8e=='':
moves = '8a8f+'
kaihimore(moves)
if oute.oute == 0:
depth1.append(moves)
if re.match('\+R', Bboard.b8a)and b8g==''\
and board.s8b+board.s8c+board.s8d+board.s8e+board.s8f=='':
moves = '8a8g'
kaihimore(moves)
if oute.oute == 0:
depth1.append(moves)
if re.match('R', ... | |
if self.simulator.t == next_step:
self.time = next_time
elif self.simulator.t < next_step:
# simulator exited early from hitting max_wallclock_time
# add a fraction of the time until next_time equal to the fractional progress made by simulator
self.time += (next_time - self.time) * (self.simulator.t - current_step... | |
<filename>query-opt/py/tests.py
# Test cases for ImplementMe class.
# The mocked objects (and therefore expected output) may change
# at the point of evaluation, including into a more complex object,
# but the functionality tested by each test case will not.
# Your implementation should anticipate ways in which these ... | |
Cell1)
assert isinstance(src, Cell1)
assert tgt.rig == src.rig
assert tgt.hom == src.hom
self.rig = tgt.rig
self.tgt = tgt
self.src = src
self.hom = (tgt, src) # yes it's backwards, just like shape is.
Matrix.__init__(self, Lin, linss, tgt.hom[1].n)
assert self.shape[1] == tgt.hom[1].n
self.check()
def chec... | |
= '''
secret = f"""apiVersion: v1
kind: Secret
metadata:
name: seldon-init-container-secret
namespace: {DEPLOY_NAMESPACE}
type: Opaque
stringData:
AWS_ACCESS_KEY_ID: {MINIO_ACCESS_KEY}
AWS_SECRET_ACCESS_KEY: {MINIO_SECRET_KEY}
AWS_ENDPOINT_URL: http://{MINIO_HOST}
USE_SSL: "false"
"""
with open("secret.yam... | |
<filename>thingsboard_gateway/connectors/modbus/modbus_connector.py
# Copyright 2022. ThingsBoard
#
# 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.... | |
import os
from typing import List
try:
from typing import Literal
except ImportError:
from typing_extensions import Literal # type: ignore
from typing import Optional
import numpy as np
import pandas as pd
import scanpy as sc
from anndata import AnnData
from rich import print
WORKING_DIRECTORY = os.path.dirname(_... | |
#
# Symbol Table
#
from __future__ import absolute_import
import re
import copy
import operator
try:
import __builtin__ as builtins
except ImportError: # Py3
import builtins
from .Errors import warning, error, InternalError
from .StringEncoding import EncodedString
from . import Options, Naming
from . import Pyre... | |
import numpy as np
def in_polygon(xp, yp, polygon, transform=None, radius=0.0):
"""
Check is points `xp` and `yp` are inside the `polygon`.
Polygon is a `matplotlib.path.Path` object.
https://stackoverflow.com/questions/21328854/shapely-and-matplotlib-point-in-polygon-not-accurate-with-geolocation
Examples
--... | |
strings as index names, hence not using dictionary row
apfs_file_meta = ApfsFileMeta(row[4], row[0], row[2], CommonFunctions.ReadAPFSTime(row[5]), CommonFunctions.ReadAPFSTime(row[6]), CommonFunctions.ReadAPFSTime(row[7]), CommonFunctions.ReadAPFSTime(row[8]), CommonFunctions.ReadAPFSTime(row[18]), row[9], row[10], r... | |
import re
import collections
from enum import Enum
from ydk._core._dm_meta_info import _MetaInfoClassMember, _MetaInfoClass, _MetaInfoEnum
from ydk.types import Empty, YList, YLeafList, DELETE, Decimal64, FixedBitsDict
from ydk._core._dm_meta_info import ATTRIBUTE, REFERENCE_CLASS, REFERENCE_LIST, REFERENCE_LEAFLI... | |
# -*- coding: utf-8 -*-
"""
other_algorithms.py: Baseline algorithms to compare against.
"""
import pdb
import numpy as np
from scipy.optimize import least_squares
from pylocus.lateration import SRLS
from coordinate_fitting import fit_trajectory
from solvers import trajectory_recovery
EPS = 1e-10
def error_meas... | |
<reponame>bcgov-c/wally
"""
Functions for aggregating data from web requests and database records
"""
import base64
import datetime
import io
import logging
import requests
import json
import fiona
import math
import re
import time
import os
import zipfile
import sqlalchemy as sa
from tempfile import TemporaryDirectory... | |
<filename>google/cloud/videointelligence/v1beta2/videointelligence-v1beta2-py/google/cloud/videointelligence_v1beta2/types/video_intelligence.py
# -*- 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 t... | |
import copy
import datetime
import functools
import importlib
import io
import json
import os
import shutil
import sys
import tempfile
import types
from threading import Thread
from requests import utils
import yaml
from bs4 import BeautifulSoup
from fastrunner.httprunner.api import HttpRunner
from fastrunner.httprun... | |
'SA': 'Saudi Arabia',
'SN': 'Senegal',
'RS': 'Serbia',
'SC': 'Seychelles',
'SL': 'Sierra Leone',
'SG': 'Singapore',
'SK': 'Slovakia',
'SI': 'Slovenia',
'SB': 'Solomon Islands',
'SO': 'Somalia',
'ZA': 'South Africa',
'GS': 'South Georgia And Sandwich Isl.',
'ES': 'Spain',
'LK': 'Sri Lanka',
'SD': 'Sudan',
... | |
立即成交,限价下单且不能成交的价格,直接撤单
if order["direction"] == "BUY" and price < ask_price or order["direction"] == "SELL" and price > bid_price:
order["last_msg"] = "已撤单报单已提交"
order["status"] = "FINISHED"
if order["status"] == "FINISHED":
self._on_order_failed(symbol, order)
elif order["direction"] == "BUY" and price >= ask_p... | |
import os
import sys
sys.path.append(os.getcwd())
import cv2
import numpy as np
import torch
from ..dataset.mot import MOTTracking, collate_fn, read_mot_file
from ..configs.config import load_config
from ..utils.log import log_or_print, get_logger
def voc_color_code(num_colors=100):
def to_binary(val, idx):
return... | |
'node', 'name', 'role')
return key_attrs(self) == key_attrs(other)
return NotImplemented
def _populate_from_attributes(self, attributes):
"""Fills in an object with the desired attributes.
"""
self.serial = str(attributes['serial'])
self.model = str(attributes['model'])
self.dn = str(attributes['dn'])
self.ve... | |
'Name')
value_ = self.gds_validate_string(value_, node, 'Name')
self.Name = value_
self.Name_nsprefix_ = child_.prefix
elif nodeName_ == 'Answer':
value_ = child_.text
value_ = self.gds_parse_string(value_, node, 'Answer')
value_ = self.gds_validate_string(value_, node, 'Answer')
self.Answer = value_
self.Answ... | |
<reponame>cthoyt/delphi
#!/usr/bin/python3.6
import ast
import sys
import tokenize
from datetime import datetime
import re
import argparse
from functools import *
import json
from .genCode import *
from typing import List, Dict, Iterable, Optional
from itertools import chain, product
import operator
class PGMState:
... | |
36628, 'tracts': 11},
'Huron': {'population': 33118, 'tracts': 12},
'Ingham': {'population': 280895, 'tracts': 81},
'Ionia': {'population': 63905, 'tracts': 13},
'Iosco': {'population': 25887, 'tracts': 9},
'Iron': {'population': 11817, 'tracts': 5},
'Isabella': {'population': 70311, 'tracts': 15},
'Jackson': {'... | |
<reponame>nstarman/gaia_tools_util
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#############################################################################
r"""
gaia_tools helper functions
Make constructing SQL queries for gaia_tools easier
See gaia_tools python package by <NAME> for details
##################... | |
#!/usr/bin/env python
# coding: utf-8
# <div class="alert alert-block alert-info">
# <b><h1>ENGR 1330 Computational Thinking with Data Science </h1></b>
# </div>
#
# Copyright © 2021 <NAME> and <NAME>
#
# Last GitHub Commit Date: 13 July 2021
#
# # 5: Algorithm Building Blocks
# - Three building blocks (structure... | |
<reponame>lezardrouge/tracim
import typing
from pyramid.config import Configurator
from pyramid.httpexceptions import HTTPFound
import transaction
from tracim_backend.app_models.contents import content_type_list
from tracim_backend.config import CFG
from tracim_backend.exceptions import ConflictingMoveInChild
from tr... | |
not check if path %s exists.") % path
LOG.exception(msg)
raise exception.HNASBackendException(msg=msg)
return True
def check_fs_mounted(self):
command = ['df', '-a', '-f', self.fs_name]
output, err = self._execute(command)
if "not found" in output:
msg = _("Filesystem %s does not exist or it is not available "... | |
<filename>dark/proteins.py<gh_stars>1-10
from __future__ import print_function, division
import os
from collections import defaultdict, Counter
import numpy as np
from os.path import dirname, exists, join
from operator import itemgetter
import re
from six.moves.urllib.parse import quote
from textwrap import fill
from... | |
<gh_stars>1-10
'''
Differentiable approximation to the mutual information (MI) metric.
Implementation in PyTorch
MRI atlas files were downloaded from: https://www.bic.mni.mcgill.ca/ServicesAtlases/Colin27
'''
# Imports #
# ----------------------------------------------------------------------
import torch
import torc... | |
#!/usr/bin/env python
'''
Copyright (C) 2014 <NAME>
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 following di... | |
<gh_stars>1-10
#!/usr/bin/env python
"""
The module using a base path as guider searches all possible paths around the vehicle toward to base path and finds the
best path for the car to follow
Module functions:
1) List of possible paths : A list of candidate paths for the vehicle to follow
2) Objects around the car: T... | |
import unittest
import sam
from math import log, sqrt
import numpy as np
from scipy.stats import multivariate_normal
from scipy.special import logit
def logProb1(x, gradient, getGradient):
if getGradient:
gradient[0] = sam.gammaDLDX(x[0], 20, 40)
gradient[1] = sam.normalDLDX(x[1], 5, 1)
return sam.gammaLogPDF(x[0... | |
'''
// Copyright 2017 <NAME>
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, subli... | |
<filename>discord/message.py
# -*- coding: utf-8 -*-
"""
The MIT License (MIT)
Copyright (c) 2015-2017 Rapptz
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 witho... | |
<reponame>gglin001/poptorch<gh_stars>100-1000
#!/usr/bin/env python3
# Copyright (c) 2020 Graphcore Ltd. All rights reserved.
import torch
import pytest
import poptorch
import helpers
non_differentiable_ops = [
torch.ceil, torch.floor, torch.round, torch.sign, torch.trunc,
torch.argmax, torch.argmin, torch.remainde... | |
@param client: An instance of the identity client
@type: client: `clientmanager.identity`
@param faker: An instance of the faker object
@type faker: `faker.Factory`
@param keeper: Reference to the keeper
@type keeper: `keeper.Keeper`
"""
self.native = client
self.cache = cache
self.faker = faker
self.keep... | |
<reponame>vimm0/python_exercise<gh_stars>0
# Section 1. Very simple exercises
#
# This selection of exercises is intended for developers
# to get a basic understanding of logical operators and loops in Python
#
import re
# 1. Max of two numbers.
def max_num( a, b ):
if a > b:
return a
return b
# 2. Max of thre... | |
self.request.wants_json:
return formatted_get_docs(
self,
"/acme-order/{ID}/acme-server/deactivate-authorizations.json",
)
return HTTPSeeOther(
"%s?result=error&operation=acme+server+deactivate+authorizations&message=HTTP+POST+required"
% self._focus_url
)
try:
if not dbAcmeOrder.is_can_acme_server_deactivate... | |
external system
def get_form_class_and_data(data):
if not data:
return ReservationForm, {}
def exclude(value):
if as_internal_id(value['desc']) == 'email':
return True
if is_payment_key(value['key']):
return True
@lru_cache()
def generate_form_class(formcode):
return parse_form(formcode, ReservationForm)... | |
not parent.rmObj(oldname, update=update): # for dir, parent will if empty
return False
deltype = "DelD" if dir else "DelF"
log(joinPath(path, oldname), obj.oid, deltype)
return True
# print info about an object, including memory address (for debugging only)
def printObj(obj, prefix="", children=False):
fsprt(pref... | |
<filename>IM_test/UI2.py
'''
Created on 2015-3-24
@author: zhangq
'''
import wx
import sent_key
import parseIrkey
#import format_case
import globalVariable
import os
import re
class ExamplePanel(wx.Panel):
def __init__(self, parent):
wx.Panel.__init__(self, parent)
self.main_path=os.getcwd()
self.IP="10.20... | |
<reponame>jeppetrost/plaso
# -*- coding: utf-8 -*-
"""This file contains MRUListEx Windows Registry plugins."""
from __future__ import unicode_literals
import abc
from dtfabric.runtime import data_maps as dtfabric_data_maps
from plaso.containers import time_events
from plaso.containers import windows_events
from pl... | |
<gh_stars>100-1000
#!/usr/bin/python3
import re, glob
N = 131
def assert_static_area(fp, i, name):
if i < 3:
srl32,srl16,fd = (0,0,i)
else:
srl32 = i // 32
if (i % 32) == 0:
srl16 = 0
fd = 0
elif (i % 32) == 1:
srl16 = 0
fd = 1
elif (i % 32) <= 17:
srl16 = 1
fd = (i % 32) - 16
else:
srl32 += 1
srl16 =... | |
headers=self.json_headers)
body = resp.json
assert resp.status_code == 200
assert resp.content_type == CONTENT_TYPE_APP_JSON
assert "process" in resp.json and isinstance(body["process"], dict)
process = body["process"]
assert "id" in process and isinstance(process["id"], str)
assert process["id"] == resources.TE... | |
pico_num("PICO_TOO_MANY_SEGMENTS"), 0
if segments == 0:
return pico_num("PICO_NOT_ENOUGH_SEGMENTS"), 0
self._segments = segments
self.info.memps = self.info.memory
return pico_num("PICO_OK"), self.info.memory
def set_simple_trigger(self, enabled, source, threshold, direction, delay=0, waitfor=0):
""" Sets simpl... | |
# Imports
# =======
# These are listed in the order prescribed by `PEP 8
# <http://www.python.org/dev/peps/pep-0008/#imports>`_.
#
# Standard library
# ----------------
import datetime
import logging
from math import ceil
from decimal import Decimal, ROUND_HALF_UP
# Third-party imports
# -------------------
from psyco... | |
'DEBUG'|'INFO'|'WARN'|'ERROR'|'FATAL',
'Space': 123,
'Type': 'FileSystem'|'AWSCloudWatch'
},
]
},
Name='string',
tags={
'string': 'string'
}
)
**Response Syntax**
::
{
'Arn': 'string',
'CreationTimestamp': 'string',
'Id': 'string',
'LastUpdatedTimestamp': 'string',
'LatestVersion': 'string',
'Lates... | |
# coding=utf-8
# Author: <NAME> <<EMAIL>>
#
# License: BSD 3 clause
import warnings
import numpy as np
from deslib.base import BaseDS
from deslib.util.aggregation import majority_voting_rule
from deslib.util.diversity import Q_statistic, ratio_errors, \
negative_double_fault, compute_pairwise_diversity
from sklearn ... | |
= self.create_dataloader(dataset_path)
self.val_loader = None
self.loss = loss_dict[args.loss].to(self.device)
self.criterion = nn.CrossEntropyLoss()
self.init_lr_decayer()
self.print_info(args)
self.save_model()
self.pretrained_weight = None
self.best_loss = 1e+20
def create_dataloader(self, dataset_path):
... | |
"""
Trie based Entity Matcher, for Exact matching of Normalized text.
Ref: https://github.com/google/pygtrie
"""
import dataclasses
from datetime import datetime
import os
from pathlib import Path
from typing import Dict, Iterable, List, NamedTuple, Optional, Sequence, Set, Tuple
import pygtrie
import numpy as np
... | |
<reponame>Konstantin-Bogdanoski/VI
from Python_neinformirano_prebaruvanje_final import *
# Check if the white Rook is in a valid position (not in the line of fire of all the black Rooks)
def validityOfWhite(gun, A):
#print("TESTING WHITE VALIDITY")
# print(gun)
location = gun
#print(location[0] != A[4][0] and loc... | |
#! /usr/env/python
"""
This module attempts to "component-ify" GT's Fastscape stream power erosion.
Created DEJH, March 2014.
"""
from __future__ import print_function
import numpy
import warnings
from landlab import ModelParameterDictionary, Component
from landlab.core.model_parameter_dictionary import MissingKeyErr... | |
print("Error: ONTAP Rest API Error: ", err)
try:
if print_output:
print("Deleting volume '" + svm+':'+volume_name + "'.")
# Delete volume
volume.delete(poll=True, poll_timeout=120)
if print_output:
print("Volume deleted successfully.")
except NetAppRestError as err:
if print_output:
if "You must delete th... | |
= getSet(modeChar)
if action == '-':
Set.discard(value)
elif action == '+':
Set.add(value)
else:
if action == '+':
self.setMode(modeChar, value)
else:
assert action == '-'
self.unsetMode(modeChar)
def __getstate__(self):
return [getattr(self, name) for name in self.__slots__]
def __setstate__(self, t):
... | |
<reponame>sjklipp/autochem_1219
""" test automol.graph
"""
import numpy
import automol
from automol import graph
C8H13O_CGR = (
{0: ('C', 3, None), 1: ('C', 2, None), 2: ('C', 3, None),
3: ('C', 1, None), 4: ('C', 1, None), 5: ('C', 1, None),
6: ('C', 1, None), 7: ('C', 1, None), 8: ('O', 0, None)},
{frozenset({1,... | |
to the value in SSIDEAPMethod using the specified operator. The value in this input will be treated as an explicit constant value. Either this field or val_f_SSIDEAPMethod must be specified if op_SSIDEAPMethod is specified.
:type val_c_SSIDEAPMethod: String
| ``api version min:`` None
| ``api version max:`` None
|... | |
# Import the needed libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
import datetime
# For linear regression function
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.linear_model import LogisticRegression, LinearRegression
from sklearn.model_sel... | |
shared_depth = min(self.config["shared_depth"], self.config["ffnn_depth"])
for i in range(shared_depth):
hidden_weights = tf.get_variable("shared_hidden_weights_{}".format(i),
[util.shape(flattened_pair_emb, 1), self.config["ffnn_size"]])
hidden_bias = tf.get_variable("shared_hidden_bias_{}".format(i), [self.config... | |
'pdbSolventFile' attribute
def getPdbSolventFile(self):
return self._pdbSolventFile
def setPdbSolventFile(self, pdbSolventFile):
if pdbSolventFile is None:
self._pdbSolventFile = None
elif pdbSolventFile.__class__.__name__ == "XSDataFile":
self._pdbSolventFile = pdbSolventFile
else:
strMessage = (
"ERROR! XS... | |
b in a.t:
if isinstance(b, Var):
b = "individual"
r.append(b)
a.t = tuple(r)
return
if isinstance(a.t, Var):
a.t = "individual"
return
return
# third step of type inference:
# check the types are correct
def type_check(wanted, a):
if wanted != typeof(a):
raise ValueError(f"{wanted} != typeof({a})")
if isi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.