input stringlengths 2.65k 237k | output stringclasses 1
value |
|---|---|
Integer, key="b"),
Column("b", Integer),
Column("c", Integer, key="a"),
)
self.assert_compile(
select([a, b, c, a, b, c]),
"SELECT a, b, c",
dialect=default.DefaultDialect(),
)
self.assert_compile(
select([bindparam("a"), bindparam("b"), bindparam("c")]),
"SELECT :a AS anon_1, :b AS anon_2, :c AS anon_3",
... | |
add pkginfo to packages
package_dict = packages.setdefault(pkginfo["name"], {})
package_dict.setdefault("pkgsinfo", []).append(
(pkginfo, status, excluded_tags, shard_repr, default_shard_repr, prepared_tag_shards, included)
)
for sub_manifest, smo_list in sub_manifest_objects.items():
for name, key, excluded_tag... | |
<gh_stars>0
#!/usr/bin/env python3
""" Bounding box
Provides a variable dimensionaly bounding box
"""
import abc
import numpy as np
from kmeans.activation import Activation
class BoundingBox(metaclass=abc.ABCMeta):
"""
Abstract data type that will represent a bounding box.
"""
# Margins for rounding numbers to... | |
Healthcare"),
("American College of Traditional Chinese Medicine","American College of Traditional Chinese Medicine"),
("American Commercial College-Abilene","American Commercial College-Abilene"),
("American Commercial College-Odessa","American Commercial College-Odessa"),
("American Commercial College-San Angelo"... | |
<filename>dataset/utils.py
from math import ceil
from skimage import io, img_as_ubyte
from skimage.transform import resize
import cv2
from PIL import ImageFile
import os
import json
from shutil import copyfile, move
import numpy as np
from matplotlib import image
from sklearn.neighbors import KDTree
from sklearn impor... | |
<gh_stars>1-10
import asyncio
import json
import os
from unittest.mock import patch
import pytest
from eth_utils import encode_hex, to_canonical_address, to_checksum_address
from tornado.httpclient import HTTPRequest
from tornado.websocket import websocket_connect
from raiden_installer import load_settings
from raide... | |
497, 445),
(4, -3, 497, 365),
(3.2, 2.1, 1.9, 0.1031015682350942),
(S(3) / 2, 5, S(5) / 6, S(3) / 32),
]:
assert pow(S(s), t, u) == v
assert pow(S(s), S(t), u) == v
assert pow(S(s), t, S(u)) == v
assert pow(S(s), S(t), S(u)) == v
assert pow(S(2), S(10000000000), S(3)) == 1
assert pow(x, y, z) == x ** y % z
r... | |
<gh_stars>0
"""Module for preparing data from NCBI. Most low layer module for manipulating data."""
import os
import pickle
from collections import defaultdict
from Bio import Entrez
from Bio import SeqIO
# TODO: move to init
CACHE_DIR = "../../Diploma/cache"
if not os.path.isdir(CACHE_DIR):
CACHE_DIR = "cache/"
i... | |
local_port = port
public_port = None
new_pfs_set.add((public_port, local_port))
to_remove = old_pfs_set - new_pfs_set
to_create = new_pfs_set - old_pfs_set
for public_port, local_port in to_remove:
if local_port == 22:
continue
machine.portforward_delete(public_port)
for public_port, local_port in to_creat... | |
<gh_stars>1-10
# task 1 for a question, task 2, task 3
import nltk
import io
import os
import re
import requests
import json
from pprint import pprint
from nltk.parse import CoreNLPParser
from nltk.parse.corenlp import CoreNLPDependencyParser
from nltk.corpus import stopwords
from nltk.stem import WordNetLem... | |
an intention to main process to fail.
Args:
process (List[subprocess.Popen]):
list of process handles opened for background benchmark runs.
lenient (bool):
If True, do not terminate background process.
Returns:
bool:
Acknowledges current program that subprocesses exited early, and guides to exit as well
"""
... | |
#!/usr/bin/python3
from __future__ import print_function
import collections
import numbers
import itertools
# import functools
import timeit
# Will probably limit support to 2.7 and 3.4, but for the moment 2.6
# and 3.3 should work.
# Single-dispatch generic functions are in, one of the CPython
# developers maintai... | |
self.fig.canvas.mpl_connect( 'close_event', self.__exit__ )
self.fig.canvas.mpl_connect( 'resize_event', self.__draw__ )
plt.show( block=self.blocking )
# plt.ion()
def loadFromFile(self, filename, loadBoxes=True ):
self.titles = self.im
print( "Try to load MRC or DM4 files" )
file_front, file_ext = os.path... | |
<gh_stars>10-100
import json
import logging
import os
import re
import shutil
import tempfile
import time
from typing import Tuple, List, Dict, Optional
from cloudfoundry_client.client import CloudFoundryClient
from cloudfoundry_client.operations.push.cf_ignore import CfIgnore
from cloudfoundry_client.operations.push.... | |
[-2.247976724721672, -2.3230490248981575, 4.8350209920697722, -0.32527190181639298]]], [[[2.5335174897949022,
-0.20854461379276934, 3.2780648503024352, -1.6620646994478872], [-2.1379815500652954, -3.2990143123595739,
2.9742698157590199, -3.0724429738487213], [-1.941430518641484, -3.8959116863238554, -3.0686598489329... | |
<reponame>4kssoft/unilm
# coding=utf-8
# Copyright 2018 The Google AI Language Team Authors and The HugginFace 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... | |
params.get("SecurityGroupId")
self.SecurityGroupName = params.get("SecurityGroupName")
self.SecurityGroupRemark = params.get("SecurityGroupRemark")
if params.get("InboundRule") is not None:
self.InboundRule = []
for item in params.get("InboundRule"):
obj = SecurityGroupsInboundAndOutbound()
obj._deserialize(item... | |
-57022,
557857506,
69916,
-1,
557911911,
69915,
558113094,
557862135,
-1,
-57019,
558054114,
69956,
-1,
558108519,
69923,
558309705,
558058179,
-1,
-57016,
558250722,
69896,
-1,
558305127,
69895,
558506316,
558254581,
-1,
-57013,
558447330,
69903,
-1,
558501735,
69902,
558702927,
55844... | |
'''
Python:
accept epsg as argument
copy into new DB
create structure for 3nf
add geometry columns
Call Ruby:
Write responses into 3nf
write geometries into 3nf tables
call shapefile tool
TODO:
convert ruby calls into rbenv or system ruby calls
figure out how shell script wrapper needs to work for export... | |
are up-to-date with library files (semantic cats, real world size, etc.)
Also updates potentially out-dated functions?? (THIS NEEDS TO BE CLARIFIED / CHANGED)
Optionally, raise an error if the "name" (unique string designating each object) has changed in the bvpLibrary
since scene list creation.
Parameters
------... | |
"styleData.iLevel={:d} styleData.istyBuiltIn={:#0{:d}x} ixfe={!s}".format(res['iLevel'].int(), res['istyBuiltIn'].int(), 2 + 2 * res['istyBuiltIn'].size(), flags.summary())
return "styleData={!r} ixfe={!s}".format(res.str(), flags.summary())
@BIFF8.define
class Style(pstruct.type):
type = 659
type = 0x293
class _... | |
#! /usr/bin/env python3
"""
WinCE Decompressor: Decompress compressed files from Windows CE ROMs.
"""
import argparse
import ctypes
import io
import os
class UnsupportedWindowSizeRange(Exception):
"""
Exception to deal with window sizes out of range.
"""
def __init__(self):
super().__init__()
class LZXCon... | |
<gh_stars>1-10
import numpy as np
import torch
import pysc2
from pysc2.agents import base_agent
from pysc2.env import sc2_env
from pysc2.lib import actions, features, units
from pysc2 import maps, lib
from s2clientprotocol import sc2api_pb2 as sc_pb
from sc2env.pysc2_util import register_map
from sc2env.utility import ... | |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'eugene'
'''
MIT License
Copyright (c) 2015 <NAME> (email : <EMAIL>)
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 rest... | |
<gh_stars>1-10
# 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 Genera... | |
from PyQt5.Qt import QColor, QPixmap, QIcon, QCursor
from PyQt5 import QtCore
from PyQt5.QtCore import Qt
from PyQt5.QtWidgets import *
from PaintBoard import PaintBoard
import random
from getline import do_image
from compare import compare_image
import data
class MainWidget(QMainWindow):
def __init__(self, parent=... | |
"""Scalene: a scripting-language aware profiler for Python.
https://github.com/plasma-umass/scalene
See the paper "docs/scalene-paper.pdf" in this repository for technical
details on an earlier version of Scalene's design; note that a
number of these details have changed.
by <NAME>
https://emeryberger.com
us... | |
<reponame>NLNZDigitalPreservation/nlnz-tools-scripts-ingestion<gh_stars>1-10
#!/usr/bin/env python
# SunOS:
#!/usr/bin/python2.7
# fairfax-pre-and-post-process-grouper.py
# Group source files by date and titleCode.
# Determines if the source files have been processed by looking for 'done' file.
# If processing has tak... | |
'19',
'-indexStep', '0',
'-valueStep', '172.16.58.3',
'-value', '172.16.58.3')
ixNet.commit()
# Adding overlay 20 for destEndPointIpv4
ovrly = ixNet.add(destEndPointIpv4Mv, 'overlay')
ixNet.setMultiAttribute(ovrly,
'-count', '1',
'-index', '20',
'-indexStep', '0',
'-valueStep', '172.16.58.3',
'-v... | |
<filename>src/baseline/exnn/exnn/base.py
import os
import numpy as np
from itertools import *
import tensorflow as tf
from matplotlib import gridspec
from matplotlib import pyplot as plt
from matplotlib import lines as mlines
from abc import ABCMeta, abstractmethod
from sklearn.model_selection import train_test_split
... | |
0.00435488,
'Renaming Unit/Int Front End RAT/Subthreshold Leakage with power gating': 0.00248228,
'Renaming Unit/Peak Dynamic': 3.58947,
'Renaming Unit/Runtime Dynamic': 0.114157,
'Renaming Unit/Subthreshold Leakage': 0.0552466,
'Renaming Unit/Subthreshold Leakage with power gating': 0.0276461,
'Runtime Dynamic':... | |
sketch
A ConstrainedSketch object.
"""
pass
def assignThickness(self, faces: tuple[Face], thickness: float = None, topFaces: tuple[Face] = (),
bottomFaces: tuple[Face] = ()):
"""This method assigns thickness data to shell faces. The thickness can be used while
assigning shell and membrane sections to faces.
... | |
<reponame>sometallgit/PdfToTrello<filename>Python/Lib/pdfrw/pdfreader.py
# A part of pdfrw (https://github.com/pmaupin/pdfrw)
# Copyright (C) 2006-2015 <NAME>, Austin, Texas
# Copyright (C) 2012-2015 <NAME>
# MIT license -- See LICENSE.txt for details
'''
The PdfReader class reads an entire PDF file into memory and
pa... | |
#!/usr/bin/env ambari-python-wrap
"""
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
"... | |
calling Bio.SeqIO.parse() twice!
raise ValueError("Handle seems to be at SFF index block, not start")
if magic_number != _sff: # 779314790
raise ValueError("SFF file did not start '.sff', but %r" % magic_number)
if (ver0, ver1, ver2, ver3) != (0, 0, 0, 1):
raise ValueError(
"Unsupported SFF version in header, %i.... | |
doc[len(to_strip):].lstrip()
linedata.append( (cmdstr, doc) )
return linedata
def _help_preprocess_command_list(self, help, cmdname=None):
marker = "${command_list}"
indent, indent_width = _get_indent(marker, help)
suffix = _get_trailing_whitespace(marker, help)
linedata = self._get_cmds_data()
if linedata... | |
-> CurveData:
"""An optional subroutine to perform data pre-processing.
Subclasses can override this method to apply pre-precessing to data values to fit.
Otherwise the analysis uses extracted data values as-is.
For example,
- Apply smoothing to y values to deal with noisy observed values
- Remove redundant da... | |
-0.044891586589426921]]))
self.assertTrue(isinstance(res,Symbol),"wrong type of result.")
self.assertEqual(res.getShape(),(4, 5),"wrong shape of result.")
self.assertTrue(Lsup(sub-ref)<=self.RES_TOL*Lsup(ref),"wrong result")
#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
def test_quotient_o... | |
"23.62.225.", # Plano
"24.173.213.", # Plano
"47.185.248.", # Plano
"50.84.81.", # Plano
"50.84.110.", # Plano
"65.42.136.", # Plano
"65.69.239.", # Plano
"65.71.223.", # Plano
"66.138.79.", # Plano
"66.140.20.", # Plano
"66.140.197.", # Plano
"66.141.151.", # Plano
"66.143.7.", # Plano
"67.65.12.", # Plan... | |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# Author: <NAME>
# Creation date: 2018-02-17 (year-month-day)
"""
Python implementations of common optimization test functions, as well as dictionaries storing their properties.
"""
import numpy as np
class ObjectiveFunction:
def __init__(self, function_token):
self.boun... | |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
This file contains the experiments in the active scenario of [Haddenhorst2021].
In order to rerun these, UNCOMMENT in "Part 4" below the corresponding lines and
then execute this file.
[Haddenhorst2021]: <NAME>, <NAME>, <NAME> and E.Hüllermeier, Testification of Cond... | |
<filename>src/models/rankae.py<gh_stars>10-100
import copy
import random
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn.init import xavier_uniform_
from torch.nn.utils.rnn import pad_sequence
from models.decoder import TransformerDecoder
from models.encoder import Bert, TransformerEn... | |
encountered.
"""
if should_log:
self._LogCopyOperation(src_uri, dst_uri, headers)
(cb, num_cb, res_download_handler) = self._GetTransferHandlers(
dst_uri, src_key.size, False)
file_name = dst_uri.object_name
dir_name = os.path.dirname(file_name)
if dir_name and not os.path.exists(dir_name):
# Do dir creation i... | |
kwargs): If True the user cannot continue until they provide a value.
valid_values (str, kwargs): A list of valid values
Returns:
str: The users selected choice.
"""
# collect input value from user and set default if required
input_value: str = self._input_value('Choice', kwargs.get('option_text')) or kwargs.get... | |
import numpy as np
import mediapipe_utils as mpu
import cv2
from pathlib import Path
from FPS import FPS, now
from math import sin, cos
import depthai as dai
import time, sys
SCRIPT_DIR = Path(__file__).resolve().parent
POSE_DETECTION_MODEL = str(SCRIPT_DIR / "models/pose_detection_sh4.blob")
LANDMARK_MODEL_FULL = str... | |
#
# Return the CASTRO directory on the current machine, based on your environment variables.
#
def get_castro_dir():
"""Return the location of the CASTRO directory."""
import os
CASTRO_HOME = os.getenv('CASTRO_HOME')
return CASTRO_HOME
# Return the name of the current inputs file in a directory.
def get_in... | |
ramienia nie moze zbyt odbiegac od wartosci lewego
if maxRightArmVal > (1 + hsVul) * maxLeftArmVal or maxRightArmVal < (1 - hsVul) * maxLeftArmVal:
return 0, [0, 0, 0, 0]
#wolumin na formacji ma byc malejacy, a conajmniej nie rosnacy
volTrend = optimizedTrend(leftArmVol + headVol + rightArmVol)
if (volTrend > 0):
... | |
def getNodeList_Lower_Step(self):
lower_CB_list = self.low_CB_set.centralbase_list
length = len(lower_CB_list)
index = length-1
if length<2:
return
pre_base = lower_CB_list[-2]
base = lower_CB_list[-1]
if self.freq=='30MIN' and abs(base.up-4.35)<0.001:
a=1
if self.freq=='30MIN':
a=1
if (len... | |
= tmpl
images = filter(lambda x: os.path.isfile(x), dataset.template_to_filenames(*ds))
if len(images) > 1:
h = XIO.Image(images[0]).header
h_next = XIO.Image(images[1]).header
h_last = XIO.Image(images[-1]).header
if h_next.get("PhiStart", 0) == h.get("PhiStart", 0):
print "This job may be scan?:", tmpl
con... | |
H2O model. Each list is a dict containing fields
of interest like name, type, gridable, default values, ....
:return: three lists: gridable_params, gridable_types and gridable_defaults containing the names of the parameter,
its associated type like int, float, unicode, bool and default parameter values
"""
# gra... | |
joint_attr in f['joints']:
create_joint(joint_attr.get('name'), joint_attr.get('x'), joint_attr.get('y'), active_truss)
for bar_attr in f['bars']:
create_bar(bar_attr.get('name'), *bar_attr.get('connected_joint_names'),
bar_attr.get('bar_params'), active_truss, bar_attr.get('var_name'))
for load_attr in f['loads... | |
<gh_stars>1-10
'''
Credit:
This code is largely based off the work by __<NAME>__ `<https://alexis-jacq.github.io>`, and is the implementation of the paper: _Image Style Transfer Using Convolutional Neural Networks_ `<https://arxiv.org/avs/1508.06576>` developed by __<NAME>__, __<NAME>__, and __<NAME>__.
'''
from __fut... | |
0x2a, 0x45, 0x9c,
0x44, 0x1d, 0x21, 0x25, 0x01, 0x45, 0x62, 0x62,
0x47, 0x61, 0x2b, 0x14, 0x89, 0x51, 0x18, 0x1a,
0x85, 0xd5, 0x94, 0x21, 0x61, 0xd2, 0xd0, 0x42,
0xd2, 0x82, 0x41, 0x9c, 0x22, 0x28, 0x5a, 0x91,
0xa4, 0x4a, 0xa1, 0x51, 0x49, 0x02, 0xa8, 0x8a,
0x91, 0x98, 0x86, 0x98, 0x98, 0x2c, 0x93, 0x82,
0x5a, 0... | |
<reponame>Kaushal28/FOTS-PyTorch
import warnings
import numpy as np
import cv2
import torch
from scipy.spatial import ConvexHull
from shapely.geometry import Polygon
# Reference: https://bitbucket.org/william_rusnack/minimumboundingbox/src/master/
# This helps to generate the rotated rectangle with minimum area th... | |
import logging
from tool_shed.base.twilltestcase import common, ShedTwillTestCase
log = logging.getLogger( __name__ )
category_name = 'Test 0460 Automatic repository revision completion'
category_description = 'Test 0460 Automatic repository revision completion'
datatypes_repository_name = 'emboss_datatypes_0460'
da... | |
<filename>fangSpider/spiders/fangIndex.py
# -*- coding: utf-8 -*-
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
from fangSpider.items import FangspiderLoupanItem
from fangSpider.items import NewhouseIndexItem
import time
import sys
import re
from bs4 import B... | |
<reponame>kevinbro96/perceptual-advex
import torch
import torchvision.models as torchvision_models
from torchvision.models.utils import load_state_dict_from_url
import math
from torch import nn
from torch.nn import functional as F
from .vae import CVAE_s2
import pdb
from . import utilities
from .utilities impo... | |
input_directories(self, value: Optional[pulumi.Input[Sequence[pulumi.Input['InputDirectoryArgs']]]]):
pulumi.set(self, "input_directories", value)
@property
@pulumi.getter(name="jobName")
def job_name(self) -> Optional[pulumi.Input[str]]:
"""
The name of the job within the specified resource group. Job names can... | |
<reponame>ryanp543/autotuner
#!/usr/bin/env python
"""
Python program that calculates the necessary constants needed to find bounds on alpha and PID gains. Running this file
generates a .csv file containing all these constants as well as the bounds on alpha.
Date 2/2/2021
"""
import sys
import csv
import numpy as n... | |
<filename>vim/vim.symlink/plugin/py/lib/evernote/edam/notestore/ttypes.py<gh_stars>0
#
# Autogenerated by Thrift
#
# DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
#
from thrift.Thrift import *
import evernote.edam.userstore.ttypes
import evernote.edam.type.ttypes
import evernote.edam.error.... | |
<filename>tests/test_models.py<gh_stars>0
import datetime
import pytest
from pytvdb.models import SeriesData, SeriesSearchData, SeriesActorsData, BasicEpisode, SeriesEpisodes, BaseModel, \
SeriesEpisodesSummary, Episode
class TestModels:
@pytest.mark.unit
def test_jsonify(self):
data = {
"aliases": [
"Doctor ... | |
To be used in combination with either the first or last timestamp.
:param first_timestamp: Limit the results to resource actions that started later
than the value of this parameter (exclusive)
:param last_timestamp: Limit the results to resource actions that started earlier
than the value of this parameter (exclusi... | |
<reponame>ahansenlab/connect_the_dots
## Particle tracking functions for 4D time series data.
# Written by <NAME> (<EMAIL>)
# (c) 2021, <NAME>
## Import required modules
import matplotlib.pyplot as plt # for plotting
import matplotlib # for plotting
import numpy as np # for manipulating arrays
import pickle # for sa... | |
# Copyright (c) <NAME>. All Rights Reserved.
r"""
STB dataset
A Hand joint Tracking Benchmark from Stereo Matching, ICIP 2017
"""
import math
import os
import pickle
import PIL
import cv2
import matplotlib.pyplot as plt
import numpy as np
import scipy.io as sio
import torch.utils.data
from PIL import Image
from termc... | |
s, g = check("Hún skrifar fyrir Dv og Rúv.")
assert "DV" in s
assert "RÚV" in s
assert g[4].error_code == "Z006" # DV
assert g[6].error_code == "Z006" # RÚV
s, g = check("Guðrún lék hlutverk Ms. Abercrombie í þáttunum")
assert "Ms." in s
assert g[4].error_code != "Z006"
s, g = check("Sigurður lék hlutverk Mr.... | |
sequence of tuples specifying the uniform volume fractions to be assigned. This
argument is valid only when *useFields*=FALSE. Each tuple contains two entries:A Region
object.A tuple of Floats specifying the uniform volume fraction values. The length of
the tuple must match the number of material instance names spec... | |
of training items.
Parameters
----------
fold : int > 0 [scalar]
Fold id, if zero all meta data is returned.
(Default value=0)
scene_label : str
Scene label
Default value "None"
Returns
-------
list : list of dicts
List containing all meta data assigned to training set for given fold.
"""
if fold not ... | |
self.ff_height > (bfh_chk + self.joist_space):
logger.warning('basement is above grade!')
#get the minimum value
if self.boh_max_val is None: #calculate and set
'this means we are non dynamic'
s_raw = self.model.bsmt_opn_ht_code
s = re.sub('\)', '',s_raw[5:])
self.boh_max_val = float(s) #pull the number out of... | |
<reponame>rhasspy/rhasspy-remote-http-hermes<filename>rhasspyremote_http_hermes/__init__.py
"""Hermes MQTT server for Rhasspy remote server"""
import asyncio
import gzip
import io
import json
import logging
import ssl
import subprocess
import time
import typing
import wave
from dataclasses import dataclass
from uuid im... | |
<filename>lib/encoding_tree.py
import math
import heapq
import numba as nb
import numpy as np
import copy
def get_id():
i = 0
while True:
yield i
i += 1
def graph_parse(adj_matrix):
g_num_nodes = adj_matrix.shape[0]
adj_table = {}
VOL = 0
node_vol = []
for i in range(g_num_nodes):
n_v = 0
adj = set()
for j... | |
day_night_background is True:
self.day_night_background(subplot_index=subplot_index, dsname=dsname)
# Set Title
if set_title is None:
set_title = ' '.join(
[dsname, 'on',
dt_utils.numpy_to_arm_date(self._obj[dsname].time.values[0])])
self.axes[subplot_index].set_title(set_title)
# Set YTitle
if 'ytitle' in ... | |
service['sonata_usr']['phone']
u = monitoring_users.objects.all().filter(
Q(email=customer['email']) & Q(mobile=customer['phone']) & Q(type='cst'))
if len(u) == 0:
usr = monitoring_users(mobile=customer['phone'], email=customer['email'], type='cst')
usr.save()
else:
usr = u[0]
dev = None
if 'sonata_dev' in ... | |
from render import Render
from random import uniform, randint
from math import floor
ren = Render()
####### Item 1
def random_point():
ren.glCreateWindow(600, 400)
ren.glClearColor(0, 0, 0)
ren.glViewPort(0, 0, 600, 400)
ren.glVertex(uniform(-1, 1), uniform(-1, 1))
ren.glColor(1, 1, 1)
ren.display("item1")
#... | |
<reponame>intellstartup/django-caravaggio-rest-api
"""
Django settings for Caravaggio REST API project.
# Copyright (c) 2019 BuildGroup Data Services Inc.
# All rights reserved.
"""
import os
import sys
try:
from dse import ConsistencyLevel
except ImportError:
from cassandra import ConsistencyLevel
from configura... | |
<gh_stars>0
# coding: utf-8
"""
Tts API
Description # noqa: E501
The version of the OpenAPI document: 2.0.0
Contact: <EMAIL>
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import six
from telestream_cloud_tts.configuration import Configuration
class Project(object):
... | |
<reponame>peckhams/stochastic_conflict_model
#
# Copyright (c) 2020, <NAME>
#
# Note: This file contains a set of functions for visualizing the
# contents of output files in netCDF format
# (e.g. TopoFlow or Stochastic Conflict Model)
#
# May 2020. Moved all routines from Jupyter notebook called
# TopoFlow_Visualizati... | |
incoming_action_set = set(action.keys())
if no_l2_classifier_set.issubset(incoming_classifier_set) and \
no_l2_action_set.issubset(incoming_action_set) and \
len(incoming_action_set) == 1:
return True
return False
def divide_and_add_flow(self, intf_id, onu_id, uni_id, port_no, classifier,
action, flow, tp_id, ... | |
#!/usr/bin/env python
import argparse, sys, copy, gzip, os
import math, time, re
import numpy as np
from scipy import stats
from collections import Counter
from argparse import RawTextHelpFormatter
from operator import itemgetter
__author__ = "<NAME> (<EMAIL>)"
__version__ = "$Revision: 0.0.2 $"
__date__ = "$Date: 20... | |
from __future__ import division
import os
import time
from shutil import copyfile
from glob import glob
import tensorflow as tf
import numpy as np
# import config
from collections import namedtuple
# from module import *
# from utils import *
# from ops import *
# from metrics import *
import tensorflow_addons as tfa
i... | |
have to make sure self.attr==None
if attr == None:
if len(operands) == 1:
rej_types = [[]]
outs = []
temp =TypeObject("type", 0)
temp.elementtype = operands[0].types
outs.append(temp)
return rej_types, outs
elif len(operands) == 3:
rej_types = [[], [], []]
outs = []
for t in operands[0].types:
if not TypeO... | |
f.is_array and f.base_type == 'uint8':
if not f.array_len:
s.write('(write-long (length %s) s)'%slot)
s.write('(princ %s s)'%slot)
elif f.is_array and is_string(f.base_type):
s.write('(write-long (length %s) s)'%slot)
s.write('(dolist (elem %s)'%slot)
var = 'elem'
elif f.is_array:
if not f.array_len:
write_se... | |
# boykovkolmogorov.py - Boykov Kolmogorov algorithm for maximum flow problems.
#
# Copyright 2016-2017 NetworkX developers.
#
# This file is part of NetworkX.
#
# NetworkX is distributed under a BSD license; see LICENSE.txt for more
# information.
#
# Author: <NAME> <<EMAIL>>
"""
Boykov-Kolmogorov algorithm for maximum... | |
<gh_stars>1-10
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Aug 20 21:29:32 2021
@author: qcao
Analysis code for example_topop_tb_v3.py
Parses and cleans load-driven phantoms. Computes Radiomic signatures. Compares with BvTv.
Compare with ROIs
"""
# FEA and BoneBox Imports
import os
import sy... | |
must be specified as:
- A string
- A number that will be converted to a string
Returns
-------
str
"""
return self["suffix"]
@suffix.setter
def suffix(self, val):
self["suffix"] = val
# valueformat
# -----------
@property
def valueformat(self):
"""
Sets the value formatting rule using d3 formatting m... | |
it.
raise e
# In case the query will be executed as a "CREATE TABLE <name> AS ..." or
# "CREATE VIEW <name> AS ...", this will be the value of "<name>".
self._table_or_view_name = None
def set_impala_query_options(self, cursor):
opts = """
SET MEM_LIMIT={mem_limit};
SET BATCH_SIZE={batch_size};
SET DISABLE_C... | |
#!/usr/bin/env python3
# Copyright 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.
"""Full DrQA pipeline."""
import heapq
import logging
import math
import time
from multiprocessing import Pool... | |
"""A list of usages.
Variables are only populated by the server, and will be ignored when sending a request.
:ivar value: Array of results.
:vartype value: list[~azure.mgmt.sql.models.Usage]
:ivar next_link: Link to retrieve next page of results.
:vartype next_link: str
"""
_validation = {
'value': {'readonl... | |
import builtins
import math
import numpy as np
import matplotlib.animation as animation
import matplotlib.patches as patches
import matplotlib.lines as mlines
import matplotlib.transforms as transforms
import random as rand
def to_plt_color(args):
max_value = 255.0
color = None
if len(args) == 1:
r = args[0]
g =... | |
WHERE Price >= (?);'.format(table)
try:
result_sum = conn.execute(sql_a1 + sql_b, (base_value,))
candidates = conn.execute(sql_a2 + sql_b, (base_value,))
if candidates == None:
return None
# The number of items.
total = result_sum.fetchone()[0]
# Roll a random number in the total range.
roll = random.randr... | |
= tf.abs(new-curr_height)//2 if height else tf.abs(new-curr_width)//2
offset_x = 0 if height else abs_diff
offset_y = abs_diff if height else 0
# We process height first, so always pad/crop to new height.
target_height = new
# We process height first, so pad/crop to new width only if not doing height.
target_wid... | |
'SEG'],)),
'ORD_O02_RESPONSE': ('sequence',
(['ORD_O02_PATIENT', None, (0, 1), 'GRP'],
['ORD_O02_ORDER_DIET', None, (1, -1), 'GRP'],
['ORD_O02_ORDER_TRAY', None, (0, -1), 'GRP'],)),
'ORF_R04_OBSERVATION': ('sequence',
(['OBX', SEGMENTS['OBX'], (0, 1), 'SEG'],
['NTE', SEGMENTS['NTE'], (0, -1), 'SEG'],)),
'ORF_R0... | |
# -*- coding: iso-8859-15 -*-
import os, re, sys
import numpy as np, scipy.sparse as sp, scipy.stats as stats
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.model_selection import GridSearchCV, ParameterGrid, StratifiedKFold
from sklearn.metrics import accuracy_score
from sklearn.ensemble... | |
"""
<NAME>
Pygame Menu System
Last Edit: 1 January 2021
"""
# Imports
import pygame
import string
# Initialize pygame
pygame.init()
# Settings
menu_manager_settings = {
"element_colorkey" : [0, 0, 0],
"menu_background_color" : [0, 0, 0],
"menu_fps" : 60
}
class Action:
"""
Holds function and argument data fo... | |
Schedule.objects.update(start_date=THREE_YEARS_AGO)
# ensure that the user who has indefinite access
self.client.login(username=user.username, password=<PASSWORD>)
response = self.client.get(url)
assert response.status_code == 200, 'Should not expire access for user'
@mock.patch.dict(settings.FEATURES, {'DISABLE... | |
from __future__ import absolute_import, unicode_literals
import fakeredis
import pytest
import redis
import unittest
import socket
from array import array
from case import ANY, ContextMock, Mock, call, mock, skip, patch
from collections import defaultdict
from contextlib import contextmanager
from itertools import co... | |
pass
def wait_until_response(self, draw_stim=True):
"""
Waits until a response key is pressed.
Returns last key pressed, timestamped.
:Kwargs:
draw_stim (bool, default: True)
Controls if stimuli should be drawn or have already
been drawn (useful if you only want to redefine
the drawing bit of this function)... | |
that is used for subsequent
actions such as plotting or saving.
These modes can be produced by various processing steps within the
class and include the following
'input' - just the spectrum as it was read in
'smooth' - the smoothed spectrum
'atmcorr' - the spectrum after applying an atmospheric absorption
cor... | |
# Copyright 2018 <NAME>
#
# 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 writing, software
... | |
ball_radius)",
leaf_found_op)
+ TRAVERSAL_PREAMBLE_MAKO_DEFS
+ GUIDING_BOX_FINDER_MACRO
+ AREA_QUERY_WALKER_BODY,
name=name,
preamble=preamble)
def generate(self, context,
dimensions, coord_dtype, box_id_dtype,
peer_list_idx_dtype, max_levels,
extra_var_values=(), extra_type_aliases=(),
extra_preamble=""):
... | |
#scrub angle
rom.write_bytes(0xECAE90, [0x27, 0x18, 0xFD, 0x04]) #skip straight to giving item
rom.write_bytes(0xECB618, [0x25, 0x6B, 0x00, 0xD4]) #skip straight to digging back in
rom.write_bytes(0xECAE70, [0x00, 0x00, 0x00, 0x00]) #never initialize cs camera
rom.write_bytes(0xE5972C, [0x24, 0x08, 0x00, 0x01]) #ti... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.