text stringlengths 1 927k |
|---|
# Copyright (C) 2019 The Raphielscape Company LLC.
#
# Licensed under the Raphielscape Public License, Version 1.c (the "License");
# you may not use this file except in compliance with the License.
#
# TheCyberUserBot - Luciferxz
import io
import re
import userbot.modules.sql_helper.blacklist_sql as sql
from userbo... |
"""Converts SavedModel into an optimized protobuf for inference"""
from dataclasses import dataclass, field
import logging
import re
from typing import List, Dict, Iterable, Union
import tensorflow as tf
from tensorflow.python.tools.freeze_graph import freeze_graph_with_def_protos
from tensorflow.python.framework.gra... |
from .aiocache import Adapter as AiocacheAdapter # noqa
from .redis import Adapter as RedisAdapter # noqa |
'''
A data source rule
Authors:
Carl Anderson (carl.anderson@weightwatchers.com)
'''
from lkmltools.linter.rule import Rule
class DataSourceRule(Rule):
'''
does source contain a sql_table_name or derived_table?
'''
def run(self, lookml):
'''does source contain a sql_ta... |
#!/usr/bin/env python
# encoding: utf-8
"""
expected_prices.py
Created by Jakub Konka on 2012-10-13.
Copyright (c) 2012 University of Strathclyde. All rights reserved.
"""
import argparse
import csv
import matplotlib
import matplotlib.pyplot as plt
from matplotlib import rc
import numpy as np
import os
import progress... |
import telnetlib
import time
OK = 0
ERROR = 1
RESPONSE_DELAY_MS = 100
class AMXNMX(object):
def __init__(self, host, port=50002, response_delay_ms=RESPONSE_DELAY_MS):
self.conn = telnetlib.Telnet(host, port=port)
self.response_delay_sec = response_delay_ms / 1000.
self._initialize()
... |
import pandas as pd
import numpy as np
from Matriz_esferica import Matriz_esferica
from Individuo import Individuo, Fabrica_individuo
import random
from itertools import permutations
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
from scipy.sparse import csr_matrix, lil_matrix
import math... |
import logging
from os import listdir
from os.path import isfile, join, isdir, dirname
import os
import shutil
from tqdm import tqdm
from typing import Dict, List
class ManageDir:
"""Commonly used directory functions to manage a directory."""
suffix = "_"
@staticmethod
def assert_file_exists(file_pa... |
from pathlib import Path
import os
import yaml
import command
class Config(object):
def __init__(self, directory, filename = '.exec-helper'):
self._settings_file = Path(directory).joinpath(filename)
self._directory = directory
self._commands = dict()
self._patterns = set()
... |
from netmiko import ConnectHandler, ssh_exception
from paramiko.ssh_exception import SSHException
import os
import sys
import subprocess
import openpyxl
import ipdb
from nornir import InitNornir
from nornir.plugins.tasks import networking
from nornir.plugins.functions.text import print_result
from nornir.plugins.tasks... |
import csv
import os
import re
import time
from selenium.webdriver.support.select import Select
from Data.parameters import Data
from filenames import file_extention
from get_dir import pwd
from reuse_func import GetData
class DistrictsBlock():
def __init__(self, driver):
self.driver = driver
def ... |
# -*- coding: utf-8 -*-
"""
Copyright (c) 2019-2021 Tomasz Łuczak, TeaM-TL
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, cop... |
from __future__ import absolute_import
from __future__ import print_function
from typing import Any
from six.moves import zip
import ijson
from django.core.management.base import BaseCommand, CommandParser
class Command(BaseCommand):
help = """
Render messages to a file.
Usage: python manage.py render_... |
# Cryptocurrency Wallet
################################################################################
# This file contains the Ethereum transaction functions that you have created throughout this module’s lessons. By using import statements, you will integrate this `crypto_wallet.py` Python script into the Fintech ... |
"""
Generate and clean fitbit dataset
"""
import logging
from argparse import ArgumentParser, RawDescriptionHelpFormatter
from google.cloud.bigquery import Table
from cdr_cleaner import clean_cdr, args_parser
from common import FITBIT_TABLES, JINJA_ENV
from utils import auth, bq, pipeline_logging
from constants.cdr_c... |
# -*- coding: utf-8 -*-
def command():
return "stop-all-instance"
def init_argument(parser):
parser.add_argument("--farm-no", required=True)
def execute(requester, args):
farm_no = args.farm_no
parameters = {}
parameters["FarmNo"] = farm_no
return requester.execute("/StopAllInstance", param... |
# coding: utf-8
"""
Copyright 2016 SmartBear Software
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 l... |
# For
print('\n==========For==========\n')
print('\n| Tampilkan 5 angka |\n')
for i in range(5):
print(i)
print('\n| Tampilkan angka 1 sampai 5 |\n')
for i in range(1, 5+1):
print(i)
print('\n| Tampilkan 5 angka secara ascending |\n')
for i in range(0, 5, 1):
print(i)
print('\n| Tampilkan 5 angka secar... |
# Let p be a bank’s interest rate in percent per year.
# An initial amount A has then grown to A ( 1 + p/100)^ n after n years.
# Make a program for computing how much money 1000 euros have grown to after three years with 5 percent interest rate.
A = 1000
N = 5.0
p = 0.05
def R( amount, rate, time ):
return amo... |
#Modded from dagd.py
"""
Animate How To Google
Command .ggl Search Query
By @loxxi
"""
import requests
from uniborg.util import admin_cmd
@borg.on(admin_cmd(pattern="ggl (.*)"))
async def _(event):
if event.fwd_from:
return
input_str = event.pattern_match.group(1)
sample_url = "https://da.gd/s?url... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes ... |
# Copyright 2020 The Magenta Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in ... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import simplejson as json
from alipay.aop.api.FileItem import FileItem
from alipay.aop.api.constant.ParamConstants import *
from alipay.aop.api.domain.KoubeiCateringPosPracticeQueryModel import KoubeiCateringPosPracticeQueryModel
class KoubeiCateringPosPracticeQueryReq... |
import typing as t
from abc import ABC, abstractmethod
from types import SimpleNamespace
from .exceptions import BadMethod, FinalizationError, NoMethod, NotFound
from .line import Line
from .patterns import REGEX_TYPES
from .route import Route
from .tree import Tree
from .utils import parts_to_path, path_to_parts
# T... |
# Copyright (c) 2021 Cybereason Inc
# This code is licensed under MIT license (see LICENSE.md for details)
import json
import requests
import oci
import io
import base64
import logging
import hashlib
from fdk import response
from cybereason_connection import get_cybereason_connection
from cybereason_machine_suspicio... |
# This file was generated by 'versioneer.py' (0.15) from
# revision-control system data, or from the parent directory name of an
# unpacked source archive. Distribution tarballs contain a pre-generated copy
# of this file.
import json
import sys
version_json = '''
{
"dirty": false,
"error": null,
"full-revisionid"... |
import sys
sys.setrecursionlimit(10**6)
def fibonacci(term_num):
if(term_num == 1 or term_num == 2):
return 1
else:
return (fibonacci(term_num-1)+fibonacci(term_num-2))
def check_first_fib_term_over(limit):
third_last_term = 1
second_last_term = 1
last_term = 2
term_index = ... |
#!/usr/bin/python
from __future__ import print_function
from struct import pack
import random
import unittest
from datachunkpy.datachunk import DataChunk, MessageHandler
class MyMsgHandler(MessageHandler):
def __init__(self):
self.msg_processed = 0
self.bytes_processed = 0
def handle_msg(se... |
# -*- coding: utf-8 -*-
# PLEASE DO NOT EDIT THIS FILE, IT IS GENERATED AND WILL BE OVERWRITTEN:
# https://github.com/ccxt/ccxt/blob/master/CONTRIBUTING.md#how-to-contribute-code
from ccxt.async_support.base.exchange import Exchange
# -----------------------------------------------------------------------------
try... |
import bpy
op = bpy.context.active_operator
op.ant_terrain_name = 'Landscape'
op.land_material = ''
op.water_material = ''
op.texture_block = ''
op.at_cursor = True
op.smooth_mesh = True
op.tri_face = False
op.sphere_mesh = False
op.subdivision_x = 128
op.subdivision_y = 128
op.mesh_size = 2.0
op.mesh_size_x = 2.0
op.... |
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may ... |
"""Download Sentencepiece and KenLM models for supported languages.
Usage:
python download_sentencepiece_kenlm_models.py --output_dir_path /tmp/
All Sentencepiece and KenLM language models will be saved under /tmp.
"""
import argparse
import subprocess
from languages_id import langs_id
def download_sentencepi... |
import torch
import torch.nn as nn
import torch.nn.parallel
from torch.autograd import Variable
from torchvision import models
import torch.utils.model_zoo as model_zoo
import torch.nn.functional as F
from torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence
from miscc.config import cfg
from GlobalAtte... |
# multiAgents.py
# --------------
# Licensing Information: You are free to use or extend these projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to UC Berkeley, including a link to http://ai.berkeley.e... |
""" Realtime and sophisticated quota supervising mechanisms """
import time as epoch_time
from datetime import time, timedelta, date, datetime
import random
from sys import platform
import sqlite3
from .time_util import sleep_actual
from .time_util import get_time
from .database_engine import get_database
from .settin... |
import torchvision
import torch
def load_dataset(batch_size,
image_transform,
root_dir="data/"):
dataset_train = torchvision.datasets.MNIST(
root=root_dir,
download=True,
transform=image_transform
)
dataset_test = torchvision.datasets.MNIST(
... |
from cms.extensions.toolbar import ExtensionToolbar
from cms.toolbar_pool import toolbar_pool
from cms.utils import get_language_list
from django.utils.translation import get_language, ugettext_lazy as _
from . import models
@toolbar_pool.register
class ImageExtensionToolbar(ExtensionToolbar):
model = models.Im... |
# Copyright 2013-2018 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
import platform
import os
import sys
class Qt(Package):
"""Qt is a comprehensive cross-platform ... |
import sys
import subprocess
#native = "../../native.pdb"
#native = "~/steno/folds/novo/profasi_native/1ubq/native.pdb"
pales = "~/programs/pales-linux"
rdc = "/home/lab/steno/folds/novo/ubiquitin.rdc"
#settings = "-ph 6.6 -temp 304 -nacl 0.01 -bestFit -qRms"
settings = "-bestFit -qRms -r1 1 -rN 72"
pdb_files = sy... |
#coding=utf-8
# Copyright (C) 2015, Alibaba Cloud Computing
#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, merg... |
# coding: utf-8
# In[1]:
from IPython.display import clear_output
def display_board(board):
clear_output() # Remember, this only works in jupyter!
print(' | |')
print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9])
print(' | |')
print('-----------')
print(' | |')
... |
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
"""
Helper... |
# Copyright 2019 PerfKitBenchmarker 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 appli... |
from tkinter import *
class scrollingFrame(Frame):
def __init__(self, parentObject, background):
Frame.__init__(self, parentObject, background = background)
self.canvas = Canvas(self, borderwidth=0, background = background, highlightthickness=0)
self.frame = Frame(self.canvas, background = ... |
# Copyright (c) 2021 Florian Wagner
#
# This file is part of Monet.
from .nonlinear import *
from .clustering import *
from .denoising import *
from .heatmap import *
from .preprocess import *
from .scvelo import * |
#!/usr/bin/env python3
# This is free and unencumbered software released into the public domain.
"""Test cases for the openxr.abi module."""
from openxr.abi import *
import ctypes
def test_XrBaseStructure():
assert(ctypes.sizeof(XrBaseStructure) == 16)
if __name__ == '__main__':
import pytest, sys
sys.... |
from tqdm import tqdm
import argparse
import os
from os.path import join, isdir
import sys
sys.path.append('..')
from blender_render.render_grid import dodecahedron_vertex_coord, semi_sphere_coord, RenderMachine
parser = argparse.ArgumentParser()
parser.add_argument('--dataset_dir', type=str, help='dataset directory... |
# -*- coding: utf-8 -*-
#
# Copyright 2017-2021 - Swiss Data Science Center (SDSC)
# A partnership between École Polytechnique Fédérale de Lausanne (EPFL) and
# Eidgenössische Technische Hochschule Zürich (ETHZ).
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in c... |
import unittest
import pandas as pd
from frds.data.wrds.execucomp import Anncomp
from frds.io.wrds import load
class AnncompLoadTestCase(unittest.TestCase):
def setUp(self) -> None:
self.ANNCOMP = load(Anncomp, use_cache=False, save=False, obs=100)
def test_load_anncomp(self):
self.assertIsIn... |
"""website URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/3.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based... |
"""
********************************************************************************
* Name: error.py
* Author: Nathan Swain
* Created On: 2014
* Copyright: (c) Brigham Young University 2014
* License: BSD 2-Clause
********************************************************************************
"""
from django.shortcut... |
from django.shortcuts import render, redirect
from academic.models import ClassRegistration
from .forms import *
from .models import *
def load_upazilla(request):
district_id = request.GET.get('district')
upazilla = Upazilla.objects.filter(district_id=district_id).order_by('name')
upazilla_id = request.GE... |
import unittest
from localstack.utils.tagging import TaggingService
class TestTaggingService(unittest.TestCase):
svc = TaggingService()
def test_list_empty(self):
result = self.svc.list_tags_for_resource("test")
self.assertEqual({"Tags": []}, result)
def test_create_tag(self):
t... |
checkpoint_config = dict(interval=5)
log_config = dict(
interval=5,
hooks=[dict(type='TextLoggerHook'),
dict(type='TensorboardLoggerHook')])
dist_params = dict(backend='nccl')
log_level = 'INFO'
load_from = None
resume_from = None
workflow = [('train', 1)]
optimizer = dict(type='Adam', lr=0.0001)
opt... |
# Course: CS261 - Data Structures
# Author: Mohamed Al-Hussein
# Assignment: 06
# Description: Directed graph implementation.
from collections import deque
import heapq
class DirectedGraph:
"""
Class to implement directed weighted graph
- duplicate edges not allowed
- loops not allowed
- only pos... |
import paramiko
import os
class MySFTPClient(paramiko.SFTPClient):
def put_dir(self, source, target):
""" Uploads the contents of the source directory to the target path. The
target directory needs to exists. All subdirectories in source are
created under target.
"""
... |
import os
import dropbox
from dropbox.files import WriteMode
class TransferData:
def __init__(self, access_token):
self.access_token = access_token
def upload(self, file_from, file_to):
dbx = dropbox.Dropbox(self.access_token)
for root, dirs, files in os.walk(file_from):
... |
import numpy as np;
def listToNum(listOfDigit):
num = map(str, listOfDigit);
num = ''.join(num);
num = int(num);
return num;
def numToList(num):
string = str(num);
listOfDigit = [];
for digit in string:
listOfDigit.append(int(digit));
return listOfDigit;
arrOfNum = np.arange(1... |
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from scipy.linalg import block_diag
from cogdl.layers import SAGELayer
from cogdl.utils import split_dataset_general
from .. import BaseModel
class EntropyLoss(nn.Module):
# Return Scalar
def forward(self, adj, anext, s_l)... |
# Generated by Django 3.2.5 on 2021-08-22 03:45
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('blogapp', '0007_alter_blogpost_cover_image'),
]
operations = [
migrations.AlterField(
model_name='blogpost',
name='c... |
# This file was automatically created by FeynRules 2.0.25
# Mathematica version: 8.0 for Mac OS X x86 (64-bit) (February 23, 2011)
# Date: Thu 8 May 2014 12:30:33
from __future__ import absolute_import
from .object_library import all_couplings, Coupling
from .function_library import complexconjugate, re, im, csc, se... |
import argparse
from ...context import mango
from decimal import Decimal
from mango.marketmaking.orderchain.biasquoteonpositionelement import BiasQuoteOnPositionElement
def test_from_args():
args: argparse.Namespace = argparse.Namespace(biasquoteonposition_bias=Decimal(17))
actual: BiasQuoteOnPositionEleme... |
import factory
import logging
from overwatch import db
from overwatch.models import Indemnity
from faker.providers.date_time import Provider
from faker import Faker
from factories import DeputyFactory
from datetime import datetime
logging.getLogger("factory").setLevel(logging.WARN)
faker = Faker('pt_BR')
faker.add_pr... |
from enum import Enum
class FunctionalMode(Enum):
Normal = 0x00
Sleeping = 0x01 |
# Copyright (c) OpenMMLab. All rights reserved.
import torch
from torch.autograd import Function
from ..utils import ext_loader
ext_module = ext_loader.load_ext('_ext', ['ball_query_forward'])
class BallQuery(Function):
"""Find nearby points in spherical space."""
@staticmethod
def forward(ctx, min_rad... |
"""Hyperopt search algorithm."""
import numpy as np
from copy import deepcopy
import hyperopt as hpo
import logging
from itertools import count
from cmlkit.engine import Component
from cmlkit.utility.config_helpers import (
find_pattern_apply_f,
find_pattern,
tuples_to_lists,
)
class Hyperopt(Component)... |
import boto3
import pytest
from aws_lambda.aws_lambda import (
deploy_function,
get_role_name,
get_account_id,
get_client,
function_exists,
delete_function,
invoke_function
) |
#!/usr/bin/env python3
#
# BSD 3-Clause License
#
# Copyright (c) 2021, Jakub Romanowski (kotoko)
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain ... |
import os
import sys
import copy
import argparse
from avalon import io
from avalon.tools import publish
import pyblish.api
import pyblish.util
from pype.api import Logger
import pype
import pype.hosts.celaction
from pype.hosts.celaction import api as celaction
log = Logger().get_logger("Celaction_cli_publisher")
p... |
'''OpenGL extension APPLE.texture_max_level
This module customises the behaviour of the
OpenGL.raw.GLES2.APPLE.texture_max_level to provide a more
Python-friendly API
Overview (from the spec)
This extension allows an application to specify the maximum (coarsest)
mipmap level that may be selected for the specif... |
# -*- coding: utf-8 -*-
"""Tests for jslex."""
# originally from https://bitbucket.org/ned/jslex
from __future__ import unicode_literals
from django.test import SimpleTestCase
from django.utils.jslex import JsLexer, prepare_js_for_gettext
class JsTokensTest(SimpleTestCase):
LEX_CASES = [
# ids
("... |
import random
import re
import typing as t
from collections import defaultdict
from os import path
from discord import Color, Embed, Guild, Member, Message, TextChannel
from discord.ext.commands import Context
from bot import config
from bot.core.bot import Bot
DIR_PATH = path.dirname(__file__)
# TODO: Define global... |
from datetime import date
import pytest
from repo2docker import buildpacks
def test_unsupported_version(tmpdir):
tmpdir.chdir()
with open("runtime.txt", "w") as f:
f.write("r-3.8-2019-01-01")
r = buildpacks.RBuildPack()
with pytest.raises(ValueError) as excinfo:
# access the proper... |
import numpy as np
from keras import backend as K
#
# Tuning these will adjust the output of your network
# class_weights[0] = penalty for misclassifying background
# class_weights[1] = penalty for misclassifying unknown
# class_weights[2] = penalty for misclassifying foreground
# Setting class_weights = [.25,0,1] ... |
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
import djmoney.models.fields
class Migration(migrations.Migration):
dependencies = [
('lending', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='... |
# Copyright 2020 Newcastle University.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to i... |
#!/usr/bin/env python
# -*- coding: utf8 -*-
# *****************************************************************
# ** PTS -- Python Toolkit for working with SKIRT **
# ** © Astronomical Observatory, Ghent University **
# *****************************************************************
# ... |
"""
Part of the code is taken from https://github.com/waterljwant/SSC/blob/master/sscMetrics.py
"""
import numpy as np
from sklearn.metrics import accuracy_score, precision_recall_fscore_support
def get_iou(iou_sum, cnt_class):
_C = iou_sum.shape[0] # 12
iou = np.zeros(_C, dtype=np.float32) # iou for each c... |
from setuptools import setup
VERSION = "0.0.1"
setup(
name="carla",
version=VERSION,
package_dir={"carla": "carla"},
install_requires=[
"scipy==1.6.2",
"lime==0.2.0.1",
"mip==1.12.0",
"numpy==1.19.4",
"pandas==1.1.4",
"scikit-learn==0.23.2",
"ten... |
from __future__ import absolute_import
"""
This base config script gets automatically executed for all platforms via
configure if the "dev" sub-configuration is specified (which is the default).
"""
from os import makedirs
from os import path
import shutil
scancode_root_dir = path.dirname(
# etc
path.dirnam... |
# -*- coding: utf-8 -*-
from __future__ import division, print_function
import numpy as np
__all__ = ["Move"]
class Move(object):
def tune(self, state, accepted):
pass
def update(self,
old_state,
new_state,
accepted,
subset=None):
... |
from src.game.gameBoard import INIT_BOARD
class GameState:
def __init__(self, state = None):
if state != None:
if len(state) != 8:
raise Exception("init Error: Board size error")
for l in state:
if len(l) != 8:
raise Exception("ini... |
#Naive Bayes Classifier using Numpy
import numpy as np
class NaiveBayes:
def fit(self, X, y):
"""Function to establish relation between dependent and independent variable
Args:
X: Independent variable
y: Dependent variable
Returns:
None
"""
n_samples, n_features = ... |
import asyncio
import random
async def work(i):
print(await asyncio.sleep(random.randint(0, i)))
result = f'work {i}'
async def main():
# print(work(1),type(work(1)))
# print(asyncio.ensure_future(work(1)),type(asyncio.ensure_future(work(1))))
# tasks = [asyncio.ensure_future(work(i)) for i in r... |
def generateKey(userKey):
valueSum = 0
for idx,value in enumerate(userKey):
# It's even? If so multiply the index by ascii code and then put on sum variable
if(idx % 2 == 0 and idx!=0):
valueSum+=(idx*ord(value))
# If not, just put the ascii code in the sum variable
... |
# Copyright (c) 2019 Foundry.
#
# 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,... |
# encoding: utf-8
import logging
from marrow.mailer import Mailer
class MailHandler(logging.Handler):
"""A class which sends records out via e-mail.
This handler should be configured using the same configuration
directives that Marrow Mailer itself understands.
Be careful how many notific... |
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from ... import _utilities, _tables
from... |
from project.category import Category
from project.document import Document
from project.storage import Storage
from project.topic import Topic
import unittest
class TestDocumentManagement(unittest.TestCase):
def setUp(self):
self.c = Category(1, "C")
self.t = Topic(1, "T", "C:\\user")
se... |
# -*- coding: utf-8 -*-
# This software and supporting documentation are distributed by
# Institut Federatif de Recherche 49
# CEA/NeuroSpin, Batiment 145,
# 91191 Gif-sur-Yvette cedex
# France
#
# This software is governed by the CeCILL-B license under
# French law and abiding by the rules of dist... |
# This file is auto-generated from a Python script that parses a PhysiCell configuration (.xml) file.
#
# Edit at your own risk.
#
import os
from ipywidgets import Label,Text,Checkbox,Button,HBox,VBox,FloatText,IntText,BoundedIntText,BoundedFloatText,Layout,Box
class UserTab(object):
def __init__(self):
... |
"""
@Date: 2021/08/12
@description:
"""
import torch
import torch.nn as nn
import numpy as np
from visualization.grad import get_all
class GradLoss(nn.Module):
def __init__(self):
super().__init__()
self.loss = nn.L1Loss()
self.cos = nn.CosineSimilarity(dim=-1, eps=0)
self.grad... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time: 2020/5/14 20:41
# @Author: Mecthew
import time
import numpy as np
import pandas as pd
import scipy
from sklearn.svm import LinearSVC
from sklearn.linear_model import logistic
from sklearn.calibration import CalibratedClassifierCV
from sklearn.metrics import ac... |
# Generated by Django 3.0.8 on 2020-07-02 13:17
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0011_update_proxy_permissions'),
]
operations = [
migrations.CreateModel(
name='UserProfile',
... |
"""
The flask application package.
"""
from flask import Flask
app = Flask(__name__)
import $safeprojectname$.views |
import logging
from json import dump as j_dumps
from json import load as j_load
from os import mkdir
from os.path import join, abspath
from time import strftime
import pandas as pd
from dill import dump as d_dump
from dill import load as d_load
from numpy import vstack, pad, diff, frombuffer, round, mean, ndarray, std... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 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 Licens... |
"""
This example will initialize the display using displayio and draw a bmp image
background, and overlay text containing the value read from the on-board temperature sensor.
User may press the A button to switch between celsius and fahrenheit units.
Required libraries:
* Adafruit_CircuitPython_Gizmo
* Adafruit_Circui... |
from os import environ, remove
from platform import uname
from os.path import join, isfile, exists
from subprocess import check_output
import kivy
if environ.get('KIVENT_USE_SETUPTOOLS'):
from setuptools import setup, Extension
print('Using setuptools')
else:
from distutils.core import setup
from dist... |
#! /usr/bin/env python
from setuptools import setup
setup(
name='qless-py',
version='0.11.4',
description='Redis-based Queue Management',
long_description='''
Redis-based queue management, with heartbeating, job tracking,
stats, notifications, and a whole lot more.''',
url='http://github.com/seomo... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.