text stringlengths 1 927k |
|---|
# This module is adapted from https://github.com/mahyarnajibi/FreeAdversarialTraining/blob/master/main_free.py
# Which in turn was adapted from https://github.com/pytorch/examples/blob/master/imagenet/main.py
import init_paths
import argparse
import os
import time
import sys
import torch
import torch.nn as nn
import to... |
import sys
import colorsys
import time
from PIL import Image
sys.path.insert(0, "./build/lib.linux-armv7l-2.7")
import MLX90640 as mlx
left_img = Image.new( 'RGB', (24,32), "black")
right_img = Image.new( 'RGB', (24,32), "black")
def temp_to_col(val):
hue = (180 - (val * 6)) / 360.0
return tuple([int(c*255) ... |
"""
Transforms and data augmentation for sequence level images, bboxes and masks.
Mostly copy-paste from https://github.com/Epiphqny/VisTR/blob/master/datasets/transforms.py
"""
import random
import PIL
import torch
import torchvision.transforms as T
import torchvision.transforms.functional as F
from util.box_ops im... |
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
import asyncio
import functools
from argparse import Namespace
from typing import Iterable, Optional, cast
from lisa import messages, notifier, schema
from lisa.parameter_parser.runbook import RunbookBuilder
from lisa.runner import RootRunner
fr... |
# -*- encoding: utf-8 -*-
"""
H2O data frame.
:copyright: (c) 2016 H2O.ai
:license: Apache License Version 2.0 (see LICENSE for details)
"""
from __future__ import absolute_import, division, print_function, unicode_literals
from h2o.utils.compatibility import * # NOQA
import csv
import datetime
import functools
fr... |
# Generated by Django 3.0.1 on 2019-12-28 08:41
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('catalog', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Language',
... |
import sys
import numpy as np
from ..pakbase import Package
from ..utils import Util3d, Transient3d
class SeawatVsc(Package):
"""
SEAWAT Viscosity Package Class.
Parameters
----------
model : model object
The model object (of type :class:`flopy.seawat.swt.Seawat`) to which
this pa... |
from django.contrib.auth.models import User
from django.db import models
from django.urls import reverse
from django.utils.text import slugify
from django_md_editor.models import EditorMdField
from core.cooggerapp.choices import ISSUE_CHOICES, make_choices
from ...threaded_comment.models import AbstractThreadedCommen... |
"""
Artificial data
===============
Module which groups artificial random data creation functions.
"""
import numpy as np
## Artificial random spatial locations
from artificial_point_locations import random_space_points,\
random_transformed_space_points
## Artificial random spatial relations
from artificial_spa... |
from cnn import ResNet
import torchvision
import torchvision.transforms as transforms
import torch
import torch.nn as nn
class RNN(torch.nn.Module):
def __init__(self, embed_dim, num_hidden_units, vocab_size, num_layers):
'''
Args:
embed_dim (int) : Embedding dimension between CNN an... |
import face_recognition
import cv2
import argparse
import os
import numpy as np
import math
def get_args():
parser = argparse.ArgumentParser()
parser.add_argument('--input', type=str, default="img")
parser.add_argument('--output', type=str, default=None)
parser.add_argument('--source', type=str, defaul... |
"""
Tests for common functionality between L{IWebViewer} implementations.
No runnable tests are currently defined here; the mixin defined here is
imported from test_webapp (for the authenticated view) and test_publicweb (for
the anonymous view).
"""
from axiom.userbase import LoginSystem
from axiom.store import Store... |
from collections import OrderedDict
import numpy as np
import robosuite.utils.transform_utils as T
from robosuite.environments import MujocoEnv
from robosuite.models.grippers import gripper_factory
from robosuite.models.robots import Panda
from robosuite.controllers.arm_controller import *
from collections import de... |
global isWindows
isWindows = False
try:
from win32api import STD_INPUT_HANDLE
from win32console import GetStdHandle, KEY_EVENT, ENABLE_ECHO_INPUT, ENABLE_LINE_INPUT, ENABLE_PROCESSED_INPUT
isWindows = True
except ImportError as e:
import sys
import select
import termios
class KeyPoller():
... |
import asyncio
import os
import threading
import subprocess
import concurrent.futures
import sys
import logging
from distutils.version import LooseVersion
from pyshark.tshark.tshark import get_process_path, get_tshark_display_filter_flag, \
tshark_supports_json, TSharkVersionException, get_tshark_version, tshark_s... |
import numpy as np
import json
src_embed_file = '/home/msobrevillac/Projects/phd/NLG/sockeye/pre-embeddings/embed-in-src.npy'
src_vocab_file = '/home/msobrevillac/Projects/phd/NLG/sockeye/pre-embeddings/vocab-in-src.json'
vocab = {}
vectors = []
with open('/home/msobrevillac/Projects/phd/Resources/Embeddings/glove/g... |
from app.common.utils import get_by_path
from app.common.constants import IMPLEMENTED_EVENTS
from pydantic import BaseModel, ValidationError, root_validator
# Nested pull_request object, describes pull_request that triggered webhook.
class PullRequest(BaseModel):
# Was pull request merged
merged: bool = Fals... |
import torch
import torch.nn as nn
import numpy as np
import random
import time
from utils import device, AverageMeter, dir_path, write_log, accuracy, save_checkpoint
from models.c3d import C3DFusionBaselineFull
from dataset import HeatmapDataset
from torch.utils.data import DataLoader
import os
import pandas as pd
fr... |
# Copyright 2017 The TensorFlow 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 applica... |
# -*- coding: utf-8 -*- #
# Copyright 2016 Google LLC. 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 requir... |
import unittest
import app
class TestSMS(unittest.TestCase):
def test_sms(self):
self.test_app = app.app.test_client()
response = self.test_app.post('/sms', data={'From': '+15556667777'})
self.assertEquals(response.status, "200 OK") |
from setuptools import setup, find_packages
with open('README.md') as readme_file:
README = readme_file.read()
with open('HISTORY.md') as history_file:
HISTORY = history_file.read()
with open('VERSION') as file:
VERSION = file.read()
VERSION = ''.join(VERSION.split())
setup(
name='b_cfn_custom_u... |
# Copyright (c) 2008-2009 AG Projects
# Author: Denis Bilenko
#
# 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, mo... |
"""
@author: Min Du (midu@paloaltonetworks.com)
Copyright (c) 2021 Palo Alto Networks
"""
import time
import logging
from utils import misc
from utils import const
from worker import combo_property_sorter
if __name__ == '__main__':
misc.init_logger(const.get_data_preparation_logs_filename())
logger = loggin... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Used for testing the stop of an instance
"""
import os
from types import SimpleNamespace
# Set env to make debugging in interactive shell more comfortable
os.environ['AWS_SPAWNER_TEST'] = '1'
import spawner
from models import Server
from tornado import gen
#%% Config... |
from pymodbus.client.sync import ModbusTcpClient as ModbusClient
from time import sleep
mClientScrittura = ModbusClient(host='192.168.1.26', port=502)
mClient = ModbusClient(host='192.168.1.26', port=503)
mClient.connect()
# Address known that expose data
addr = 8195
reg = mClient.read_coils(addr - 1, 1, unit=1)
Q3 ... |
from cornershop-catalog-integrations-api-tools import sftp |
import cPickle
import matplotlib.pyplot as plt
import os
import os.path as op
base_path= os.path.split(os.path.abspath(__file__))[0]
xlabel=[0.5,0.6,0.7,0.8,0.9]
IR=[0.469,0.231,0.050,0.001,0.00]
Visible =[0.919,0.692,0.371,0.108,0.005]
plt.plot(xlabel,Visible,'r',label='Visible =0.3731')
plt.plot(xlabel,IR,'b',label='... |
import os
import cv2
from PIL import Image
from firebot import bot
from ..utils import admin_cmd
# Now Gifs nd Stickers also Support
# OpenCV Basics
path = "./dcobra/"
if not os.path.isdir(path):
os.makedirs(path)
@bot.on(admin_cmd(pattern=r"pru"))
async def scan(event):
if not event.reply_to_msg_id:
... |
import logging
from datetime import datetime
from sqlalchemy import func
from schedule import every
from dispatch.config import (
INCIDENT_PLUGIN_CONVERSATION_SLUG,
INCIDENT_DAILY_SUMMARY_ONCALL_SERVICE_ID,
INCIDENT_NOTIFICATION_CONVERSATIONS,
INCIDENT_PLUGIN_TICKET_SLUG,
INCIDENT_PLUGIN_STORAGE_S... |
# pylint: disable=missing-docstring
import unittest
from pathlib import Path
from handsdown.processors.pep257 import PEP257DocstringProcessor
class TestLoader(unittest.TestCase):
def test_init(self):
pep257_docstring = (
Path(__file__).parent.parent / "static" / "pep257_docstring.txt"
... |
# Copyright 2015 The TensorFlow 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 applica... |
import torch
import torch.nn as nn
import torchvision.models as models
import torchvision.transforms as transforms
from resnet import *
from wide_resnet import *
import os
def load_model(name, dataset, n_class=10, in_channel=3, save_dir=None, substitute=False):
if name == 'fcnet':
model = FCNet(n_class=n... |
UPDATE_EVENTS = {
'ChangePassword', 'CreateAccessKey', 'CreateLoginProfile', 'CreateUser'
}
def rule(event):
return event.get(
'eventName') in UPDATE_EVENTS and not event.get('errorCode')
def dedup(event):
return event.get('userIdentity', {}).get('userName', '<UNKNOWN_USER>')
def title(event):... |
# Generated by Django 2.2.5 on 2019-11-04 18:07
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('affiliate_marketing', '0010_brand_vendor_code'),
]
operations = [
migrations.AddField(
model_name='brand',
name='sto... |
square_meters = float(input())
price = square_meters*7.61
discount = 0.18*price
final_price = price - discount
print(f'The final price is: {final_price} lv.')
print(f'The discont is: {discount} lv.') |
import logging
from os import getenv
import sentry_sdk
__all__ = ['log', 'check_for_tokens']
logging.basicConfig(level=logging.INFO,
format='%(message)s')
log = logging.getLogger('sdl')
sentry_sdk.init("https://fc66a23d79634b9bba1690ea13e289f0@o321064.ingest.sentry.io/2383261")
def check_for_to... |
from iqa_metrics.tmqi_matlab.TMQI import TMQI, TMQIr_m
import matlab_py.matlab_wrapper as mw
import os
from utils.image_processing.color_spaces import rgb2lum
# singleton instance to not reinitialize every time TMQI is called
tmqi_instance = None
def init_instance_tmqi(**kwargs):
global tmqi_instance
matl... |
from flask import Blueprint, jsonify, request
from overwatch.models import Indemnity, Deputy
from webargs import fields
from webargs.flaskparser import use_args
from sqlalchemy import desc, func, extract
from decimal import Decimal
from inflection import singularize
blueprint = Blueprint('indemnity_api', __name__, ur... |
import glob
import tensorflow as tf
from .utils import get_batched_dataset
from .layers import FuncPredictor
import matplotlib.pyplot as plt
plt.switch_backend('agg')
class DeepCNN(object):
""" Class containig the CNN model for predicting protein function. """
def __init__(self, output_dim, n_channels=26, n... |
import os, sys, time
import lib.hachoir_core.config as config
from lib.hachoir_core.i18n import _
class Log:
LOG_INFO = 0
LOG_WARN = 1
LOG_ERROR = 2
level_name = {
LOG_WARN: "[warn]",
LOG_ERROR: "[err!]",
LOG_INFO: "[info]"
}
def __init__(self):
self.__buf... |
import torch
import torch.nn as nn
def gaussian_weights_init(m):
classname = m.__class__.__name__
if classname.find('Conv') != -1:
m.weight.data.normal_(0.0, 0.02)
elif classname.find('BatchNorm') != -1:
m.weight.data.normal_(1.0, 0.02)
m.bias.data.fill_(0)
class BATCHResBlock(nn.... |
# -*- coding: utf-8 -*-
# Copyright 2012 splinter authors. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
from .fake_webapp import EXAMPLE_APP
class IsTextPresentTest(object):
def test_is_text_present(self):
"should verify if tex... |
"""gpxfile table
Revision ID: ba29ca77dbc3
Revises: 2dd5da4ccf72
Create Date: 2020-07-01 16:06:16.814147
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'ba29ca77dbc3'
down_revision = '2dd5da4ccf72'
branch_labels = None
depends_on = None
def upgrade():
# ... |
"""Get information about an user on GitHub
Syntax: .github USERNAME"""
from telethon import events
import requests
from Bonten.utils import admin_cmd
@borg.on(admin_cmd("github (.*)"))
async def _(event):
if event.fwd_from:
return
input_str = event.pattern_match.group(1)
url = "https://api.github.... |
#!/usr/bin/env python3
"""
Reads experiments descriptions in the passed configuration file
and runs them sequentially, logging outputs
"""
import argparse
import logging
import os
import random
import sys
import socket
import datetime
import faulthandler
faulthandler.enable()
import traceback
import numpy as np
from ... |
from flask_restful import abort
class HTTPExceptions(object):
msg = "HTTP Error: %s"
@classmethod
def not_found(cls, message=msg % "Object does not exist"):
abort(404, message=message)
@classmethod
def already_exists(cls, message=msg % "Object already exists"):
abort(409, message... |
import socket
def get_open_port():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("",0))
s.listen(1)
port = s.getsockname()[1]
s.close()
return port |
#!/usr/bin/python
# Copyright 2016 Hewlett Packard Enterprise Development, LP.
#
# 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
#
#... |
# blanyal
def binarySearch(inputList, item):
lower = 0
upper = len(inputList) - 1
isFound = False
while (lower <= upper and not isFound):
mid = (lower + upper) // 2
if inputList[mid] == item:
isFound = True
elif item < inputList[mid]:
upper = mid - 1
... |
import math
from typing import List, Optional
import numpy as np
from autofit.mapper.model_mapper import ModelMapper
from autofit.non_linear.mcmc.auto_correlations import AutoCorrelationsSettings
from autofit.non_linear.samples.pdf import PDFSamples
from .samples import Samples
from .sample import Sample, load_from_t... |
import demistomock as demisto
from CommonServerPython import * # noqa: E402 lgtm [py/polluting-import]
from CommonServerUserPython import * # noqa: E402 lgtm [py/polluting-import]
import requests
import traceback
from asyncio import create_task, sleep, run
from contextlib import asynccontextmanager
from aiohttp impo... |
#!/usr/bin/env python3
###############################################################################
# #
# RMG - Reaction Mechanism Generator #
# ... |
# Copyright 2020, The Autoware Foundation
#
# 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
"""Django's command-line utility for administrative tasks."""
import os
import sys
def main():
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'daveotest_2.settings')
try:
from django.core.management import execute_from_command_line
except ImportError as exc:
raise Im... |
import pyensembl
import Bio.SeqIO
import Bio.Seq
import pandas as pd
import sys
import re
from Bio import pairwise2
def get_transcript_adj_exons(ensembl,gene_id,exon_coord):
try:
transcript_ids=ensembl.transcript_ids_of_gene_id(gene_id)
except:
print('Warning: ' + gene_id + ' not found')
transcript_ids=[]
tr... |
import itertools
from ... import _worker
from ..logger import get_logger
from .constants import (
DEFAULT_RUNTIME_METRICS,
DEFAULT_RUNTIME_TAGS,
)
from .metric_collectors import (
GCRuntimeMetricCollector,
PSUtilRuntimeMetricCollector,
)
from .tag_collectors import (
PlatformTagCollector,
Trac... |
import requests
from allauth.socialaccount import app_settings
from allauth.socialaccount.providers.amazon_cognito.provider import (
AmazonCognitoProvider,
)
from allauth.socialaccount.providers.oauth2.views import (
OAuth2Adapter,
OAuth2CallbackView,
OAuth2LoginView,
)
class AmazonCognitoOAuth2Adapt... |
#!/usr/bin/python
import warnings
warnings.filterwarnings("ignore")
#
import numpy
import pandas
from optparse import OptionParser
from scipy import stats
import os
import sys
from multiprocessing import Pool
import subroutines
#
#
opts = OptionParser()
usage = "Enriched accessons of a cluster (batch) \nusage: %prog -s... |
# Copyright 1999-2020 Alibaba Group Holding Ltd.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or a... |
# Copyright 2019 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, ... |
from PyQt5.QtCore import pyqtSignal
from easydict import EasyDict as edict
from pymodaq.daq_utils.daq_utils import ThreadCommand, getLineInfo, DataFromPlugins
from pymodaq.daq_viewer.utility_classes import DAQ_Viewer_base
from collections import OrderedDict
import numpy as np
from enum import IntEnum
from pymodaq.daq_v... |
import os
from conans import ConanFile, CMake, tools
class FhSimTestConan(ConanFile):
settings = "os", "compiler", "build_type", "arch"
generators = "cmake_paths", "cmake_find_package"
def build(self):
cmake = self._configure_cmake()
cmake.configure()
cmake.build()
def impor... |
# Problem 37: Truncatable primes
# https://projecteuler.net/problem=37
def is_prime(n):
if n < 2:
return False
if n == 2:
return True
if n % 2 == 0:
return False
for x in range(3, int(n ** 0.5) + 1, 2):
if n % x == 0:
return False
return True
def is_trun... |
from unittest.mock import MagicMock, patch
import pendulum
from prompt_toolkit.formatted_text import FormattedText
from prompt_toolkit.completion import Completion
from iredis.completers import MostRecentlyUsedFirstWordCompleter
from iredis.completers import IRedisCompleter, TimestampCompleter, IntegerTypeCompleter
... |
from django.db import models
from django.contrib.auth.models import AbstractBaseUser
from django.contrib.auth.models import PermissionsMixin
from django.contrib.auth.models import BaseUserManager
from django.conf import settings
class UserProfileManager(BaseUserManager):
"""Manager for user profiles"""
def cr... |
my_expr = 42
s = 'foo{{my_e<caret>' |
import re
import operator
def f_and(*args):
for i in args:
if not i:
return False
return True
def f_or(*args):
for i in args:
if i:
return True
return False
def f_like(s, p):
p = '^{}$'.format(p.replace('%', '[\s\S]*'))
return re.match(p, s) is not ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Generated from FHIR 1.0.2.7202 (http://hl7.org/fhir/StructureDefinition/Group) on 2016-06-23.
# 2016, SMART Health IT.
from . import domainresource
class Group(domainresource.DomainResource):
""" Group of multiple entities.
Represents a defined collect... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from runner.koan import *
class AboutAsserts(Koan):
def test_assert_truth(self):
"""
We shall contemplate truth by testing reality, via asserts.
"""
# Confused? This video should help:
#
# http://bit.ly/about_asserts... |
from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
from django.contrib.auth.models import PermissionsMixin
from django.core.mail import send_mail
from django.db import models
from django.utils import timezone
from django.utils.translation import gettext_lazy as _
class UserManager(BaseUserMan... |
from __future__ import division, absolute_import
import torch.utils.model_zoo as model_zoo
from torch import nn
from torch.nn import functional as F
__all__ = ['pcb_p6', 'pcb_p4']
model_urls = {
'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',
'resnet34': 'https://download.pytorch.org/... |
#!/home/tarek/Desktop/Vygit/ENV/bin/python3
from __future__ import print_function
import base64
import os
import sys
if __name__ == "__main__":
# create font data chunk for embedding
font = "Tests/images/courB08"
print(" f._load_pilfont_data(")
print(" # %s" % os.path.basename(font))
pri... |
import errno
import os
import logging
def get_logger(path, filename):
# Create the folder where the training information is to be saved if it doesn't exist
if not os.path.exists(path):
try:
os.makedirs(path)
except OSError as exc: # Guard against race condition
if exc.errno != errno.EEXIST:
... |
# -*- coding: utf-8 -*-
#
# This file is part of Miniature released under the FreeBSD license.
# See the LICENSE for more information.
from __future__ import (print_function, division, absolute_import, unicode_literals)
import hashlib
import os.path
from django.core.cache import get_cache, cache as default_cache, Inv... |
##+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
## Created by: Donny You, RainbowSecret, JingyiXie
## Microsoft Research
## yuyua@microsoft.com
## Copyright (c) 2019
##
## This source code is licensed under the MIT-style license found in the
## LICENSE file in the root directory of this sour... |
#!/usr/bin/python
#
# create_package_removed.py
# automatically generate checks for removed packages
#
# NOTE: The file 'template_package_removed' should be located in the same working directory as this script. The
# template contains the following tags that *must* be replaced successfully in order for the checks to... |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
from recognizers_text.culture import Culture
from recognizers_text.extractor import Extractor
from recognizers_text.parser import Parser
from recognizers_number.culture import CultureInfo
from recognizers_number.number.span... |
"""This module contains the general information for LsbootDef ManagedObject."""
from ...imcmo import ManagedObject
from ...imccoremeta import ImcVersion, MoPropertyMeta, MoMeta
from ...imcmeta import VersionMeta
class LsbootDefConsts():
PURPOSE_OPERATIONAL = "operational"
PURPOSE_UTILITY = "utility"
REBO... |
import magma as m
import mantle
import fault
from hwtypes import BitVector
import pytest
import shutil
@pytest.mark.skipif(not shutil.which("irun"), reason="irun not available")
def test_simple_alu_pd():
type_map = {"CLK": m.In(m.Clock)}
circ = m.DefineFromVerilogFile("tests/verilog/simple_alu_pd.sv",
... |
'''NXOS Implementation for Mld unconfigconfig triggers'''
# python
from functools import partial
# ats
from ats.utils.objects import Not, NotExists
# Genie Libs
from genie.libs.sdk.libs.utils.mapping import Mapping
from genie.libs.sdk.triggers.unconfigconfig.unconfigconfig import TriggerUnconfigConfig
from genie.lib... |
import pygame
class Box(pygame.sprite.DirtySprite):
def __init__(self, pos, layer):
pygame.sprite.DirtySprite.__init__(self) #call DirtySprite intializer
#self.image, self.rect = load_image('chimp.bmp', -1)
# Create an image of the block, and fill it with a color.
# This could also... |
"""
Concrete types for converting from protobuf objects.
Since the Python protobuf compiler outputs code that generates
classes on the fly from a symbol database, we convert them as
concrete types here to ensure the expected fields are present.
"""
from pprint import pformat
class ComfoMessage:
"""Mixin for prot... |
# 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 json
import warnings
import pulumi
import pulumi.runtime
from .. import utilities, tables
class RuleGroup(pulumi.CustomResource... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('forum', '0011_forumboard_css_class'),
]
operations = [
migrations.AddField(
model_name='forumtopic',
... |
import unittest
from random import choice
from binascii import a2b_base64
from crypto.cbc import CBCCipher
from util.somecode import pad16_PKCS7, unpad16_PKCS7, rand_n_string, PaddingException
FIXED_KEY = rand_n_string(16).encode()
FIXED_IV = rand_n_string(16).encode()
PSTRINGS = [
b"MDAwMDAwTm93IHRoYXQgdGhlIHBhcnR... |
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------... |
# -*- coding: utf-8 -*-
# https://msdn.microsoft.com/en-us/library/windows/desktop/aa383608(v=vs.85).aspx
'''
Windows Task Scheduler Module
.. versionadded:: 2016.3.0
A module for working with the Windows Task Scheduler.
You can add and edit existing tasks.
You can add and clear triggers and actions.
You can list all ... |
import os; exists = os.path.exists
import sys
import csv
import time
args = sys.argv
def err(msg):
print("Error: " + str(msg))
sys.exit(1)
def parfor(my_function, my_inputs):
# evaluate function in parallel, and collect the results
import multiprocessing as mp
pool = mp.Pool(mp.cpu_count())
re... |
#!/usr/bin/env python
import testcases
class Solution:
def __init__(self, volume: int, drinks: list):
self.volume = volume
self.drinks = drinks
self.drink_count = len(self.drinks)
self.opt = [[0] * (self.drink_count + 1) for _ in range(volume + 1)]
def calculate(self) -> in... |
# Copyright 2021 Collate
# 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... |
from past.builtins import basestring
import os
import itertools
import builtins
import json
import logging
import warnings
from math import ceil
from contextlib import contextmanager
from django.apps import apps
from django.db import connection
from django.db.migrations.operations.base import Operation
from osf.model... |
from django.contrib import admin
from . import models
@admin.register(models.Camp)
class CampModelAdmin(admin.ModelAdmin):
pass |
#!/usr/bin/python3
import os
import glob
import gzip
import xml.etree.ElementTree as ET
from urllib.parse import unquote
from . import common
from . import table
from . import analysis
from . import fooro
from . import end
def logserach(dir):
filelist = []
if os.path.isdir(dir):
findpath = os.path.j... |
#!/usr/bin/env python
####################################
#
# Redis Test Script
#
####################################
import redis
import sys
import pydoc
import os
import datetime
import pytz
import time
import csv
# Macros
CONNECTED_CP_KEY_NAME = "connected_cp"
NUM_CDR_PARAM = 68
REDIS_CERT_PATH = '../../config... |
"""
Source.py
Author: Jordan Mirocha
Affiliation: University of Colorado at Boulder
Created on: Sun Jul 22 16:28:08 2012
Description: Initialize a radiation source.
"""
from __future__ import print_function
import re, os
import numpy as np
from scipy.integrate import quad
from ..util import ParameterFile
from ..phy... |
# -*- coding: utf-8 -*-
description = 'Kelvinox from Panda with labview-control'
group = 'optional'
includes = ['alias_T']
devices = dict(
# DONT CHANGE THESE NAMES OR THE LABVIEW PART WONT WORK ANYMORE !
mc = device('nicos.devices.generic.CacheWriter',
description = 'Mixing chamber temperature',
... |
"""
Copyright 2001, 2002 Enthought, Inc.
All rights reserved.
Copyright 2003-2013 SciPy Developers.
All rights reserved.
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 abov... |
#!/usr/bin/env python
"""
udocker unit tests: UMain
"""
from unittest import TestCase, main
from unittest.mock import patch
from udocker.umain import UMain
from udocker.config import Config
class UMainTestCase(TestCase):
"""Test UMain() class main udocker program."""
def setUp(self):
Config().getcon... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
#####################################
### CIS SLOT FILLING SYSTEM ####
### 2014-2015 ####
### Author: Heike Adel ####
#####################################
from __future__ import unicode_literals
import codecs, sys
reload(sys)
sys.setdefaulte... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.