content stringlengths 5 1.05M |
|---|
# -*- coding: utf-8 -*-
from time import time
import logging
from colorlog import ColoredFormatter
class Logger:
"""Log class"""
def __init__(self, *args, log_level=None, **kwargs):
"""Initialisation method"""
super().__init__(*args, **kwargs)
if log_level is not None:
s... |
# -*- coding: utf-8 -*-
# copyright 2003-2011 LOGILAB S.A. (Paris, FRANCE), all rights reserved.
# contact http://www.logilab.fr/ -- mailto:contact@logilab.fr
#
# This file is part of logilab-common.
#
# logilab-common is free software: you can redistribute it and/or modify it under
# the terms of the GNU Lesser Genera... |
import pandas as pd
import numpy as np
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.metrics.pairwise import cosine_similarity
###### helper functions. Use them when needed #######
def get_title_from_index(index):
return df[df.index == index]["title"].values[0]
def get_index_from_ti... |
from catalyst import dl, metrics
from catalyst.data.loader import BatchPrefetchLoaderWrapper
from fusion.runner import ABaseRunner
import torch
import torch.nn.functional as F
from typing import Mapping, Any
class CatalystRunner(ABaseRunner, dl.Runner):
def predict_batch(
self,
batch: Mapping[str... |
import os
from mongoengine import connect
basedir = os.path.abspath(os.path.dirname(__file__))
DEBUG = True
# set and env var:'mongodb://magnetu:<password>@<mongo host>:<port>/<db name>'
MONGODB = os.environ.get('MONGODB')
# imp also for flask-login
SECRET_KEY = os.environ.get('SECRET_KEY')
# Enpoints are not CSRF ... |
from enum import Enum
from typing import Dict
import attr
class Status(Enum):
Unknown = 0
Errored = 1
Completed = 2
Canceled = 3
@attr.s(auto_attribs=True)
class Result:
headers: Dict[str, str]
body: bytes
metadata: Dict[str, str]
trailers: Dict[str, str]
status: Status
|
from enum import Enum, auto
import logging
import os.path
from airflow.exceptions import AirflowException
from airflow.sensors.base_sensor_operator import BaseSensorOperator
from airflow.utils.decorators import apply_defaults
from bsh_azure.hooks.box_hook import BoxHook
# Quiet chatty libs
logging.getLogger('boxsdk'... |
class CaseObservation(object):
def __init__(self, date, observation, country):
self.observation_date = date
self.observation = observation
self.country = country
@classmethod
def get_csv_row_to_dict(cls, row):
return {'observation_date': row[1], 'city': row[2], 'country': r... |
from django.test import TestCase
from django.contrib.auth.models import User
from coursebuilder.models import (
QTYPES,
CourseModule,
ModuleSection,
Extras,
Grade,
Question,
Quiz,
)
def create_course_module():
return CourseModule.objects.create(
course_order=1,
module="... |
import operator
import re
from http import HTTPStatus
from flask import Flask, jsonify, request
app = Flask(__name__)
variable_re = re.compile(r"[A-Za-z][A-Za-z0-9_]*")
func_map = {
'+': operator.add,
'-': operator.sub,
'*': operator.mul,
'/': operator.truediv,
}
variables = {}
@app.route("/calc",... |
from __future__ import division
from ea import adult_selection
from ea import parent_selection
from ea import reproduction
from ea import main
from ea import binary_gtype
from ea.ea_globals import *
def war(p1_orig, p2_orig, reployment_factor, loss_factor):
'''Fight a single war and return score for each side'''
... |
from keras.preprocessing import image
from keras.applications.inception_v3 import InceptionV3, preprocess_input
from keras.applications.vgg19 import VGG19
from keras.applications.vgg19 import preprocess_input as vgg_preprocess_input
from keras.models import Model, load_model
from keras.layers import Input
import nump... |
#!/usr/bin/env python3
# Copyright 2021 Chris Farris <chrisf@primeharbor.com>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless req... |
import utils
from collections import defaultdict
def read_input(filename):
text = utils.read(filename, 'string').split(',')
return [int(n) for n in text]
class Part1(utils.Part):
def __init__(self):
super().__init__(0)
def run(self, input, is_test):
n = 2020
while len(input)... |
from flask import Flask, render_template, request
from chatterbot import ChatBot
from chatterbot.trainers import ChatterBotCorpusTrainer
app = Flask(__name__)
english_bot = ChatBot("English Bot",silence_performance_warning=True)
english_bot.set_trainer(ChatterBotCorpusTrainer)
english_bot.train("chatterbot.corpus.eng... |
class Constants(object):
"""Constants holder class that stores the bulk of the fixed strings used in the library."""
IG_SIG_KEY = '99e16edcca71d7c1f3fd74d447f6281bd5253a623000a55ed0b60014467a53b1'
IG_CAPABILITIES = '3brTBw==' # = base64.b64encode(struct.pack('<i', 131316445)).decode('ascii')
SIG_KE... |
# https://www.geeksforgeeks.org/how-to-sort-an-array-in-a-single-loop/
def sort_array(a):
length=len(a)
j = 0
while j < length-1:
if (a[j] > a[j+1]):
temp = a[j]
a[j] = a[j+1]
a[j+1] = temp
# updating the value of j = -1
# so after ge... |
'''(2,5)
'''
def foo():
bar = 1
|
from django.contrib import admin
from .models import Product
# Register your models here.
class ProductAdmin(admin.ModelAdmin):
list_display = ['name', 'price','quantity']
list_filter = ['name',]
search_fields = ['name',]
prepopulated_fields = {'slug': ('name',)}
list_editable = ['price', 'quantity... |
# Copyright (c) 2016-2017, NVIDIA CORPORATION. All rights reserved.
import csv
import os
import random
import numpy as np
from digits.utils import subclass, override, constants
from digits.extensions.data.interface import DataIngestionInterface
from .forms import DatasetForm, InferenceForm
DATASET_TEMPLATE = "te... |
import math
import numpy as np
import torch as tc
import torch.nn as nn
import torch.nn.functional as F
import utils
import utils_tc
def ncc_global_np(source: np.ndarray, target: np.ndarray, **params):
if source.shape != target.shape:
raise ValueError("Resolution of both the images must be th... |
"""simple api server for gpt-j"""
from flask import Flask, request, jsonify
from transformers import GPTJForCausalLM, AutoTokenizer
import torch
model = GPTJForCausalLM.from_pretrained("../gpt-j-6B", torch_dtype=torch.float16)
model = model.to(torch.device("cuda"))
tokenizer = AutoTokenizer.from_pretrained("../gpt-j-6... |
import io
import pickle
from google.appengine.ext import ndb
class ImportFixingUnpickler(pickle.Unpickler):
"""
In the case where we're reading a CachedQueryResult written by
the py3 version of TBA, we'll need to fix the imports to be
compatible with this one.
"""
def find_class(self, module... |
import click
from completions import get_local_archives
from constants import colors
import context
help_text = """(a) Lists the project's archives."""
@click.command(name='list', help=help_text)
@click.argument('pattern', default='*', type=click.STRING,
autocompletion=get_local_archives)
@click.pas... |
# tool to parse out the package names from top-pypi-packages
import json
from pprint import pprint
outfile = open('pkgnames.txt',"w")
with open('top-pypi-packages-365-days.json') as f:
data = json.load(f)
rows = data['rows']
for info in rows:
print(info["project"])
outfile.write(info["project"] + '\n')
outfil... |
""" Module for containing a base http error and handler for returning exceptions from views. """
from uuid import uuid4
from flask import make_response
from utils import get_logger
LOGGER = get_logger(__name__)
class HttpError(Exception):
""" Base exception for returning error responses via exception. """
... |
class Solution:
def fizzBuzz(self, n: int):
res = []
for i in range(1,n+1):
if i % 3 == 0 and i % 5 == 0:
res.append('FizzBuzz')
elif i % 3 == 0:
res.append('Fizz')
elif i % 5 == 0:
res.append('Buzz')
els... |
# Copyright 2019 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
"""This encapsulate the main Findit APIs for external requests."""
import logging
from common.constants import DEFAULT_SERVICE_ACCOUNT
from findit_v2.model... |
from importlib import import_module
import humps
from sqlalchemy import MetaData, BigInteger, Column
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from sqlalchemy.ext.declarative import declarative_base, declared_attr
from sqlalchemy.orm import sessionmaker, synonym
from ang.config import SETTI... |
# Copyright (c) 2010-2012 OpenStack, 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
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to ... |
"""
Testing parse_mol modules, consists of 4 functions:
parse_ligands(ligand_list: List[string]) -> List[OBMol]
parse_protein(protein: string) -> OBMol
Mutate input list
enumerate_ligand_files(
ligand_pose -> List[None],
ligand_files -> List[string]
) -> None
enumerate_ligand_file_list(
ligand_pos... |
#Faça um programa que leia 5 números e informe a soma e a média dos números
soma = 0
for contador in range(5):
numero = int(input("Digite um número: "))
soma += numero
print(f"A soma dos números digitados é: {soma}")
print(f"A média dos números digitados é: {soma / 5}")
|
import time
import src.twitterscraper as ts
# pylint: disable=W0702, C0103
def test_search_term():
"""Check that search term function returns dataframe of tweets that contain term searched."""
twitterscraper = ts.Twitter()
search_parameters = ["CAPitol", "jury", "Cookie"]
for term in search_parame... |
import os
import pickle
import os.path
import sys
import torch
import torch.utils.data as data
import torchvision.transforms as transforms
from PIL import Image, ImageDraw, ImageFont
import cv2
import numpy as np
from operator import itemgetter
from skimage.draw import polygon
if sys.version_info[0] == 2:
import x... |
#!/usr/bin/env python2
#
# This file is part of the dune-hdd project:
# https://github.com/pymor/dune-hdd
# Copyright Holders: Felix Schindler
# License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
from __future__ import division, print_function
import numpy as np
from pymor.core.interfaces ... |
import time
from gileum.test import MockGileum
setting = MockGileum(
test_name="unittest@gileum",
developer_name="jjj999",
current_time=time.time(),
glm_name="main",
)
|
import sys
import os
from numba.cuda.cudadrv.libs import test
from numba.cuda.cudadrv.nvvm import NVVM
def run_test():
if not test():
return False
nvvm = NVVM()
print("NVVM version", nvvm.get_version())
return nvvm.get_version() is not None
sys.exit(0 if run_test() else 1)
|
from django.contrib import admin
# Register your models here.
from yonghu.models import Yhb, Address
admin.site.register(Yhb)#注册显示用户表
admin.site.register(Address)
|
from toee import *
def OnBeginSpellCast(spell):
print "Wounding Whispers OnBeginSpellCast"
print "spell.target_list=", spell.target_list
print "spell.caster=", spell.caster, " caster.level= ", spell.caster_level
#game.particles( "sp-divination-conjure", spell.caster )
def OnSpellEffect(spell):
pri... |
#!python2.7
# -*- coding: utf-8 -*-
"""
Created by kun on 2016/7/21.
"""
from math import sqrt
__author__ = 'kun'
critics = {'Lisa Rose': {'Lady in the Water': 2.5, 'Snakes on a Plane': 3.5,
'Just My Luck': 3.0, 'Superman Returns': 3.5, 'You, Me and Dupree': 2.5,
'Th... |
"""
@name: PyHouse/src/Modules.Core.Utilities.uuid_tools.py
@author: D. Brian Kimmel
@contact: D.BrianKimmel@gmail.com
@copyright: (c) 2015-2019 by D. Brian Kimmel
@license: MIT License
@note: Created on Jun 22, 2015
@Summary:
"""
__updated__ = '2019-10-24'
# Import system type stuff
import os
impo... |
# -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2017-05-23 12:43
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('trainer', '0008_solution_time_elapsed'),
]
operations = [
migrations.AddField... |
import datetime
from base64 import b64encode
from decimal import Decimal
import pytest
from local_data_api.models import Field, SqlParameter
def test_valid_field() -> None:
assert SqlParameter(name='abc', value=Field(stringValue='abc')).valid_value == 'abc'
assert SqlParameter(name='abc', value=Field(blobVa... |
from time import time as time_now
from PyQt4 import QtCore
from PySide import QtGui
import dictionaries.session as session
import dictionaries.constants as cs
import dictionaries.menus as menus
import interface.auxiliary_functions as auxi
HLINE1 = 5 * "|"
HLINE2 = "\n" + 9 * HLINE1 + "\n"
################... |
from mock import patch
from pinkbelt.messages import post_message
@patch("pinkbelt.messages.slack_post_message")
def test_post_message(mock_post_message):
post_message('test', 'room')
assert mock_post_message.called, True
assert mock_post_message.call_args_list, ['test', 'room']
|
## Word a10n (abbreviation)
## 6 kyu
## https://www.codewars.com//kata/5375f921003bf62192000746
import re
def abbreviate(s):
s_list = re.split('([\W\d_])', s)
end_list = []
for i in s_list:
if i:
if len(i) >= 4:
end_list.append(f'{i[0]}{len(i)-2}{i[-1]}')
... |
###########################################
#IMPORTING
#Imports OS
import os
#Needed for sleep
import time
#GUI
import tkinter as tk
#Import filename
from tkinter import filedialog
#Import filename
from tkinter import messagebox
#Import py file (needs __init__.py)
from Gifhandler import *
#Tabs
from tkinter impo... |
from abc import abstractmethod
from interfaces.private.canvas_component import CanvasComponent
class CanvasPublicInterface(CanvasComponent):
"""All methods on this interface are to be implemented in thi API implementation"""
@abstractmethod
def __init__(self, size):
"""
:param dimensions: ... |
#!/usr/bin/python3
"""
urbandict.py - urban dictionary module
author: mutantmonkey <mutantmonkey@mutantmonkey.in>
"""
from tools import GrumbleError
import web
import json
import re
API_URL = "http://api.urbandictionary.com/v0/define?term={0}"
WEB_URL = "http://www.urbandictionary.com/define.php?term={0}"
def get_d... |
#!/usr/bin/python3
# -*- coding: utf-8 -*-
import re
str = '''Train Epoch: 1 Train Iteration: 260 Time 1.609s / 20iters, (0.080) Data load 0.036s / 20iters, (0.001794)
Learning rate = [0.1, 0.1] Loss = {ce_loss: 2.3057, loss: 2.3117}
'''
print("#+++++++++++#")
RE_CLS_IC_TRAIN = re.compile(r'Train Epoch: (?P<epoch>\... |
import os
import sys
os.environ['SERVICE'] = 'aws-cd-pipeline'
os.environ['STACK'] = 'localstack'
os.environ['STAGE'] = 'localtest'
# manipulating sys.path to make importing inside tests because ¯\_(ツ)_/¯
here = os.path.abspath(os.path.dirname(__file__))
sys.path.insert(0, os.path.join(here, '..', 'src'))
|
import pybullet as p
#import pybullet_data as pd
import os
import wavefront as wf
import util
import optimization as opt
import numpy as np
import argparse, sys
parser = argparse.ArgumentParser(description=__doc__, formatter_class=
argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("--input_obj", "-i"... |
'''
Title : Loops
Subdomain : Introduction
Domain : Python
Author : Kalpak Seal
Created : 28 September 2016
'''
# Enter your code here. Read input from STDIN. Print output to STDOUT
n = int(raw_input())
for i in range(0, n):
print (i ** 2) |
from django.db import models
from django.shortcuts import reverse
import uuid
class Snippet(models.Model):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
title = models.CharField(max_length=50)
code = models.TextField()
langs = [('Text', 'None'),
('Python', 'P... |
from abc import ABC
from typing import List, Tuple
import numpy as np
from absl import logging
from xain.types import KerasWeights
from .evaluator import Evaluator
class Aggregator(ABC):
def __init__(self):
pass
def aggregate(self, thetas: List[Tuple[KerasWeights, int]]) -> KerasWeights:
r... |
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.base import MIMEBase
from email.mime.text import MIMEText
from email import encoders
import re
import os
def send_email(sender_mail, sender_password, mail_subject, mail_body, receiver_mail, sender_mail_site_smtp,
list_of_attachments):... |
import sys
from validator.submain import populate_chrome_manifest
from validator.rdf import RDFParser
from validator.xpi import XPIManager
from validator.errorbundler import ErrorBundle
from validator.outputhandlers.shellcolors import OutputHandler
import validator.testcases.regex as regex
def _do_test(path, test, f... |
from src.handler import inc
def test_answer():
assert inc(3) == 4
|
"""Packager for cloud environment."""
from setuptools import setup, find_packages
setup(
name='preprocess',
version='1.0.0',
packages=find_packages(),
install_requires=[
'tensorflow',
'numpy',
],
)
|
import csv
import logging
import math
import os
from datetime import datetime
import pytest
from brainscore.submission.database import connect_db
from brainscore.submission.evaluation import run_evaluation
from brainscore.submission.models import Score, Model, Submission
from tests.test_submission.test_db import clea... |
import marshmallow as ma
class FooSchema(ma.Schema):
name = ma.fields.String(metadata={'title': 'foo name', 'description':
'foo name'})
|
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 29 16:02:56 2019
@author: hkf
"""
import xml.etree.ElementTree as ET
import os
import cv2
from tools_hu.utils.utils import bboxes_iou
from tools_hu.utils.Code_dictionary import CodeDictionary
import numpy as np
import random
def cut_defect(images, annotations, output_d... |
from bs4 import BeautifulSoup
from nltk.corpus import stopwords
from fuzzywuzzy import fuzz, process
from nltk.tokenize import wordpunct_tokenize
from pandas_profiling import ProfileReport
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import warnings
import re
stop_words ... |
"""
Copyright 2019 Faisal Thaheem
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 agr... |
import time
from suvec.common.crawling import CrawlRunner
from suvec.common.postproc.data_managers.ram_data_manager import RAMDataManager
from suvec.common.postproc import ParsedProcessorWithHooks
from suvec.common.postproc.processor_hooks import HookSuccessParseNotifier
from suvec.common.top_level_types import User
f... |
def add_numbers(start,end):
total = 0
for number in range(start, end + 1):
print(number)
total = total + number
return(total)
test1 = add_numbers(1,2)
print(test1)
test2 = add_numbers(1, 100)
print(test2)
test3 = add_numbers(1000, 5000)
print(test3)
answer = add_numbers(1, 5000)
print(answer... |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
"""Test export of PyTorch operators using ONNX Runtime contrib ops."""
import copy
import distutils.version
import io
import unittest
import numpy as np
import onnx
import parameterized
import torch
import onnxruntime
from... |
# -*- coding: future_fstrings -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import os
import sys
import tensorflow as tf
from six.moves import shlex_quote
import utils as ut
def new_cmd(session, name, cmd, load_path, shell):
if isinstance(cmd, (... |
from stable_baselines_custom.deepq.policies import MlpPolicy, CnnPolicy, LnMlpPolicy, LnCnnPolicy
from stable_baselines_custom.deepq.build_graph import build_act, build_train # noqa
from stable_baselines_custom.deepq.dqn import DQN
from stable_baselines_custom.common.buffers import ReplayBuffer, PrioritizedReplayBuffe... |
"""This module contains all the settings for the application"""
from harvey import utils
PROXIES = {
'http': 'socks5://127.0.0.1:9050',
'https': 'socks5://127.0.0.1:9050'
}
# Crawler settings
REQUEST_CONCURRENCY = 100
REQUEST_TIMEOUT = 4
REQUEST_DOWNLOAD_TIMEOUT = 10
REQUEST_TTL = 3
REQUEST_USER_AGENT = 'h... |
# -*- coding: utf-8 -*-
import os
import flask
from flask import url_for, request
from heroku import HerokuRequest
app = flask.Flask(__name__)
# Application variables
app.secret_key = 'Your secret key.'
debug_mode = os.environ.get('DEBUG', False) == '1'
http_prefix = 'https://'
server_name = os.environ['SERVER_NAM... |
from __future__ import absolute_import
import unittest
from pysasl.creds import StoredSecret, AuthenticationCredentials
from pysasl.hashing import BuiltinHash
builtin_hash = BuiltinHash(rounds=1000)
password_sha256 = '6f3b2db13d217e79d70d43d326a6e485756bcbe1b4e959f3e86c0d9eb' \
'62fa40a352c178b1fc30896e7c484d7... |
from Service import Service
from Queue import Queue
class Node(object):
# Constructor.
def __init__(self, service_name, to_indices=[]):
if to_indices is None:
to_indices = []
self.service_name = service_name
self.to_indices = to_indices
def to_string(self):
rtn... |
import tensorflow as tf
from tensorflow.contrib import layers
from config import MovieQAPath
from raw_input import Input
_mp = MovieQAPath()
hp = {'emb_dim': 256, 'feat_dim': 512, 'dropout_rate': 0.1}
def dropout(x, training):
return tf.layers.dropout(x, hp['dropout_rate'], training=training)
def l2_norm(x, a... |
import copy
import os
import sys
import urllib.request
from sure_tosca_client import Configuration, ApiClient, NodeTemplate
from sure_tosca_client.api import default_api
import networkx as nx
import matplotlib.pyplot as plt
class ToscaHelper:
def __init__(self, sure_tosca_base_url, tosca_template_path):
... |
# -*- coding: utf-8 -*-
!pip install torch
!pip install pytorch_transformers
!pip install transformers
!pip install IProgress
from __future__ import absolute_import, division, print_function
import json
import os
import torch
import torch.nn.functional as F
from nltk import word_tokenize
from pytorch_transformers... |
from typing import List
class Solution:
"""
头尾双指针
"""
def exchange(self, nums: List[int]) -> List[int]:
head, tail = 0, len(nums) - 1
while head < tail:
if nums[head] % 2 != 0:
head += 1
continue
if nums[tail] % 2 != 1:
... |
#This file was used for stripping the brackets [] from the data set
#No need to run this file again. The new data set is saved in new_data.csv
import pandas as pd
data = pd.read_csv("data.csv", index_col="index")
counter = 0
for index in data.index:
lyric = data.loc[index, 'Lyric']
allInd = []
begIndex ... |
import logging
import json
import requests as r
from requests.packages.urllib3.util.retry import Retry
import re
from django.conf import settings
logger = logging.getLogger(__name__)
logger.setLevel(logging.INFO)
logger.propagate = False
def handle_error_msg(errors):
"""
convenience function for handling er... |
import pandas as pd
import numpy as np
import igraph as g
import json
from time import time
import geopandas as gpd
STREAM_FILEPATH = 'D/DNR HYDRO/corrected streams.geojson'
LAKES_CLEAN_FILEPATH = 'D/DNR HYDRO/lakes clean.geojson'
with open(STREAM_FILEPATH) as f:
data = json.load(f)
def coord_to_str(xyz):
re... |
# ******************************************************************************
# Copyright 2017-2018 Intel Corporation
#
# 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.apa... |
"""
test_htmlgen.py
"""
import pytest
from htmlgen import HtmlGen
@pytest.mark.sanity
@pytest.mark.sunshine
def test_creation():
x = HtmlGen()
assert x is not None
def test_p_tagify():
x = HtmlGen()
assert x.output("X") == "<p>X</p>"
def test_output():
x = HtmlGen()
assert x.output("whatev... |
# Generated by Django 2.2.6 on 2020-06-06 17:24
import django.db.models.deletion
from django.conf import settings
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('posts', '0016_auto_20200606_1953'),
]
operations = [
migrations.AlterModel... |
# -*- coding: utf-8 -*-
"""
-------------------------------------------------
File: config_test.py
Description: 测试环境配置文件
Author: Danny
Create Date: 2020/04/09
-------------------------------------------------
Modify:
2020/04/09:
---------------------------------... |
#!/usr/bin/env python
# coding: utf-8
'''
Author: Kazuto Nakashima
URL: https://github.com/kazuto1011/grad-cam-pytorch
USAGE: python visualize.py --config_file configs/VGG.yaml --target_layer=features.28
USAGE: python visualize.py --config_file configs/ResNet.yaml --target_layer=layer4
USAGE: python vi... |
from twilio.rest import Client
from credentials import account_sid, auth_token, my_cell, my_twilio
client = Client(account_sid, auth_token)
my_msg = """Hi, This is Kunal
Sudhanshu Bsdk
Bola na dusra Kaam Kar rha Hoon......"""
message = client.api.account.messages.create(to=my_cell, from_=my_twilio, body=my_msg) |
from django.contrib import messages
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.forms import model_to_dict
from django.http import HttpResponseRedirect, JsonResponse
from django.shortcuts import render
from django.views import View
from apps.task_log.models import TaskLog
from ... |
from django import forms
from .models import Order
from django.contrib.auth.models import User
from accounttt.models import Profileee
class OrderForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['order_date'].label = 'Дата получения заказа... |
# -*- coding: utf-8 -*-
"""
:copyright: Copyright 2017-2020 Sphinx Confluence Builder Contributors (AUTHORS)
:license: BSD-2-Clause (LICENSE)
"""
from sphinx.util import logging
import io
class ConfluenceLogger():
"""
confluence logger class
This class is used to manage an internally logger instance and ... |
# For the final assignment of this section, we're going to make something a bit more complicated
# The goal of this program is to build a program to simplify two (simple) polynomials multiplied together
# Specifically, we would like to simplify (ax + by)*(cx + dy), where a,b,c,d are inputs given by the user
# We want t... |
#! /usr/bin/env python
import math
startX = 0.0
startY = 0
xStep = 7.0
yStep = 9.0
endX = 1000.0
endY = 1000.0
amplitude = 250.0
frequency = 0.01
currentX = startX
currentY = startY
outputY = 0
outputFile = '/Users/pete/Desktop/outputpts.pts'
outFile = open(outputFile, 'w')
newline = str('\n')
print outFile
while ... |
from network import *
from submission import *
from data.mapping import *
import numpy as np
import re
# Construct bayesian network
def construct_sample_network(data):
network = bayes_network(data)
# You need to list the nodes so that parents are introduced before children
# You can inspect data.mapping ... |
import math
try:
import Tkinter as tk # for Python2
except:
import tkinter as tk # for Python3
import config as cfg
import helpers as hp
from Tile import Tile
import tkMessageBox as mb
import sys
sys.path.insert(0, './tantrix/PodSixNet')
#from PodSixNet.Connection import ConnectionListener #, connection
from t... |
# -*- coding: utf-8 -*-
"""Sentinel Tools Test Config
"""
import sys, pytest, shutil
from os import path, mkdir
sys.path.insert(1, path.abspath(path.join(path.dirname(__file__), path.pardir)))
@pytest.fixture(scope="session")
def stTemp():
testDir = path.dirname(__file__)
tempDir = path.join(testDir, "temp")... |
"""
Absicis Acid Signaling - simulation
- plotting saved data
"""
import sys
from pylab import *
from boolean import util
import numpy
def make_plot( fname ):
obj = util.bload( fname )
data = obj['data']
muts = obj['muts']
genes=['WT','pHc','PA']
# standard deviations
def limit (x):
... |
import sys
import scarletio.ext.asyncio
sys.modules['hata.ext.asyncio'] = sys.modules['scarletio.ext.asyncio']
|
# V0
# V1
# https://blog.csdn.net/fuxuemingzhu/article/details/79462285
# IDEA : DFS
class Solution(object):
def updateBoard(self, board, click):
"""
:type board: List[List[str]]
:type click: List[int]
:rtype: List[List[str]]
"""
(row, col), directions = click, ((-1... |
import unittest
import vivisect.symboliks.archs.i386 as i386sym
import vivisect.symboliks.analysis as v_s_analysis
from vivisect.symboliks.common import Var, Const, cnot
from vivisect.symboliks.effects import ConstrainPath
import vivisect.tests.helpers as helpers
class IntelSymTests(unittest.TestCase):
@classm... |
#!/usr/bin/env python3
import io
from PyPDF2 import PdfFileWriter, PdfFileReader
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import A4
class Applicant(object):
def __init__(self, features):
self.features = features
class Boat(object):
def __init__(self, name, matriculation):
... |
from heapq import heappush, heappop, heapify
import numpy as np
from PIL import Image, ImageDraw, ImageMath
from random import seed, gauss, randrange, random
from sys import maxsize
seed(2)
reference = 'sonic.png'
im = Image.open(reference, 'r')
size = im.size
class Gene:
"""
Each organism ha... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.