content stringlengths 5 1.05M |
|---|
from django import forms
from django.core.exceptions import ValidationError
from django.utils import timezone
from .models import ChoiceBet, DateBet
from .util import create_choices
from ledger.models import Account
from profiles.models import ForbiddenUser
class ChoiceBetCreationForm(forms.ModelForm):
class Me... |
from django.test import SimpleTestCase
import mock
cursor_wrapper = mock.Mock()
cursor_wrapper.side_effect = RuntimeError("No touching the database!")
@mock.patch("django.db.backends.utils.CursorWrapper", cursor_wrapper)
class SimpleTest(SimpleTestCase):
def test_basic_addition(self):
"""
Tests... |
import configparser
from pathlib import Path
from typing import TYPE_CHECKING
from radiant_mlhub.cli import mlhub
if TYPE_CHECKING:
from click.testing import CliRunner as CliRunner_Type
class TestCLI:
def test_version(self, cli_runner: "CliRunner_Type") -> None:
result = cli_runner.invoke(mlhub, ['... |
# Generated by Django 2.2.10 on 2021-07-23 04:43
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('app', '0011_auto_20210722_1131'),
]
operations = [
migrations.AddField(
model_name='salesuser',
nam... |
from Mymqtt import Mymqtt
from receive import *
import pygame
# 屏幕刷新
flash = 0
# 背景图以及移动小车图
car_image_name = "car.png"
pygame.init()
# 生成窗口以及窗口标题
screen_show = pygame.display.set_mode((1000, 600), 0, 32)
pygame.display.set_caption("Little Case")
# 加载并转换图片
car0 = pygame.image.load(car_image_name).convert_alpha()
car1 =... |
from PIL import Image
import numpy as np
#-- read pixels to ndarray
im1 = np.array( Image.open('../images/img001.png').convert('RGB') )
#-- pixel operation
im1[:, :, 0] = 0
#im1[:, :, 1] = 0
im1[:, :, 2] = 0
#-- save to png
im3 = Image.fromarray(im1)
im3.save('z201.png')
|
def getPairs(li, x):
myDic = dict()
for i in li:
remVal = x - i
if i in myDic:
print remVal, ',', i
myDic[remVal] = True
li = [110, 175, 317, 50, 1178, 819, 70]
getPairs(li, 427)
# time is linear
|
"""
Test of constraints value_precede and value_precede_chain in cpmpy
The global constraint
value_precede(s,t, x)
ensures that the value s precedesl the value t in array x
if both s and t are in x.
The global constraint
value_precede_chain(c, x)
ensures that the value c[i-1] precedes the value c[i] is the... |
from onnx_graphsurgeon.logger.logger import G_LOGGER
|
"""High level entry point for processing a sample.
Samples may include multiple lanes, or barcoded subsections of lanes,
processed together.
"""
import copy
import os
import toolz as tz
from bcbio import utils, bam, broad
from bcbio.log import logger
from bcbio.pipeline.merge import merge_bam_files
from bcbio.bam im... |
# -*- coding: utf-8 -*-
"""
Tencent is pleased to support the open source community by making 蓝鲸智云PaaS平台社区版 (BlueKing PaaS Community
Edition) available.
Copyright (C) 2017-2020 THL A29 Limited, a Tencent company. All rights reserved.
Licensed under the MIT License (the "License"); you may not use this file except in co... |
import math
from openerp.osv import osv, fields
import openerp.addons.product.product
class res_users(osv.osv):
_inherit = 'res.users'
_columns = {
'ean13' : fields.char('EAN13', size=13, help="BarCode"),
'pos_config' : fields.many2one('pos.config', 'Default Point of Sale', domain=[('state'... |
import csv
import collections, itertools
import nltk.classify.util, nltk.metrics
from nltk.classify import NaiveBayesClassifier
from nltk.corpus import movie_reviews, stopwords
from nltk.collocations import BigramCollocationFinder
from nltk.metrics import BigramAssocMeasures
from nltk.probability import FreqDist, Condi... |
from python_framework import Enum, EnumItem
@Enum()
class PoolingStatusEnumeration :
NONE = EnumItem()
POOLING = EnumItem()
GOOGLE_SEARCHING = EnumItem()
ERROR_POOLING = EnumItem()
ERROR_DELIVERING = EnumItem()
SUCCESS = EnumItem()
PoolingStatus = PoolingStatusEnumeration()
|
# Copyright 2014 eBay Software Foundation
# Copyright [2015] Hewlett-Packard Development Company, L.P.
# 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
#
# ... |
def read_input():
# for puzzles where each input line is an object
with open('input.txt') as fh:
decks = [[], []]
cur_player = 0
for line in fh.readlines():
if not line.strip():
cur_player = 1
continue
if line.startswith('P'):
... |
from django.http import request
from django.http.response import HttpResponseRedirect
from django.shortcuts import render, redirect
from django.contrib import messages
from django.contrib.auth.views import LoginView, PasswordResetConfirmView, PasswordResetView
from django.urls import reverse_lazy
from django.utils.enc... |
import re
from datetime import datetime, timedelta
from django.contrib.auth.models import User
from django.core.exceptions import ValidationError
from django.db.models import Q
from django.views.decorators.http import require_GET
import waffle
from statsd import statsd
from rest_framework import viewsets, serializer... |
import pymysql
MYSQL_CONFIG = {
'host': 'mysql', # mysql or '127.0.0.1'
'port': 3306,
'user': 'root',
'password': 'mysql520',
'charset': 'utf8',
'use_unicode': True,
'cursorclass': pymysql.cursors.DictCursor,
'connect_timeout': 60,
'maxconnections': 50
}
|
from rest_framework.pagination import LimitOffsetPagination,PageNumberPagination
class StandardResultsSetPagination(PageNumberPagination):
page_size = 2
page_size_query_param = 'page_size'
max_page_size = 20 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Tests for weighted stats functions.
"""
from __future__ import division
import os
import sys
import platform
import unittest
HERE = os.path.dirname(os.path.realpath(__file__))
sys.path.insert(0, os.path.join(HERE, os.pardir))
from weightedstats import *
class TestWe... |
#!/usr/bin/env python3
import sys
import random
import requests
import populate
if len(sys.argv) < 2:
print("no seed given.abort.")
sys.exit(1)
seed = sys.argv[1]
users,msgs = populate.get_data(seed)
URL = "http://127.0.0.1:80"
# test for users
resp = requests.get(URL+"/users")
assert resp.status_code ==... |
import pytest
pytest_plugins = "pytester"
@pytest.fixture
def state():
return "gASVqA4AAAAAAABLAyiKBQAAAIAAigUA6cbnAEpzTpUZShSh2SCKBeZcQ8cASkEkuF1KzTQ8HYoFrsovkQCKBduZrZoASnkaKB+KBY6ACtMAigWJT3rQAIoFacE8kgBKk5nNJUrW0lENSs72zSpKZX2Ackq9/DMCSlTVumGKBRkHO+cAStvjkBBKNMMMF0r6PTR0igVWh6/rAIoFiCzh2QBKaLVtN4oFWa0QyACKBc... |
# -*- coding: utf-8 -*-
# This module contains all the Session classes used by the MIT Core Concept
# Catalog (MC3) Handcar based implementation of the OSID Learning Service.
# Note that it includes the core OsidSession typically found in the osid
# package as well as the learning package sessions for Objective, Activ... |
/home/runner/.cache/pip/pool/ca/50/b8/a7144c957f295287fa48370bfdc0ba4d270242f10a2a241ea74a6a064e |
#!/usr/bin/env python
import sys
import getopt
import re
import struct
import socket
import stat
import os
debug = 0
QEMUCMDTEMPLATE = """#!/bin/bash
set -u
ARCHEND=%(ARCHEND)s
IID=%(IID)i
if [ -e ./firmadyne.config ]; then
source ./firmadyne.config
elif [ -e ../firmadyne.config ]; then
source ../firmadyn... |
#!/usr/bin/env python
from typing import List, Tuple
"""
Difficulty: 4
A group of executives at a large oil company had gone to a conference about ML. After
hearing that it "could learn like a human" they decided to fire all their Geologists
and Geophysicists. They were replaced with a neural network they named Fred... |
from django.contrib import admin
from . models import User
# Register your models here.
admin.site.register(User) |
n, s = int(raw_input()), raw_input()
print max(s.count(';1';), s.count(';2';), s.count(';3';), s.count(';4';)), min(s.count(';1';), s.count(';2';), s.count(';3';), s.count(';4';))
|
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: protos/controllable.proto
"""Generated protocol buffer code."""
from google.protobuf import descriptor as _descriptor
from google.protobuf import descriptor_pool as _descriptor_pool
from google.protobuf import message as _messa... |
from __future__ import print_function, division
import numpy as np
# Header
__author__ = "Maria A. Pena-Guerrero"
__version__ = "1.0"
"""
This script can transform from sky to detector coordinates (backward direction), and from
detector to sky (forward direction).
Keyword arguments:
transf_direction -- Direct... |
import PIL
import numpy as np
from typing import Tuple
class IDriver:
""" Interface that every GAN driver must meet. """
def __init__(
self,
path: str, # Path to network (local file or URL)
z_dim: int, # Input (z) vector dimension (e.g. 512 for StyleGan neworks)
... |
import os
import pandas as pd
from Bio.SeqIO.FastaIO import FastaIterator
from Bio.SeqRecord import SeqRecord
class FastaReader:
"""
Universal class for reading FASTA files with genome or protein
sequence or multi-FASTA with chunks of sequences
Example:
fname = 'NC_001604.fasta'
fr... |
import numpy as np
from PIL import Image
count = 1
while count <= 10000:
filecount = str(count)
basewidth = 4000
img = Image.open('1.1/'+filecount+'.png')
wpercent = (basewidth/float(img.size[0]))
hsize = int((float(img.size[1])*float(wpercent)))
img = img.resize((basewidth,hsize), Image.ANTIA... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jan 24 2022 02:33:58 AM
@author: ozgur oney
"""
import os
import random
from docx import Document
from docx.enum.style import WD_STYLE_TYPE
from docx.enum.text import WD_ALIGN_PARAGRAPH
from docx.shared import Pt
from tkinter import *
from tkinter i... |
from data import data
from data.data import Dataset
import torch
import fire
import time
import os, sys
import tqdm
from typing import Dict, Tuple
from torch import nn, optim
from torch.nn import functional
from collections import namedtuple
from visdom import Visdom
from face_detection import cig
from face_detection... |
from megnet.layers.graph import MEGNetLayer, CrystalGraphLayer, InteractionLayer
from megnet.layers.readout import Set2Set, LinearWithIndex
from keras.layers import deserialize as keras_layer_deserialize
from megnet.losses import mean_squared_error_with_scale
from megnet.activations import softplus2
_CUSTOM_OBJECTS =... |
from __future__ import annotations
import logging
from typing import TextIO
from ..cli import run_with_file_argument
from .task_1 import Vector, fire, get_target_area
logger = logging.getLogger(__name__)
def find_min_x_velocity(min_x: int) -> int:
distance = 1
x_velocity = 1
while distance < min_x:
... |
import logging
from typing import List
from cryptoxlib.WebsocketMgr import Subscription, CallbacksType, Websocket
from cryptoxlib.Pair import Pair
from cryptoxlib.clients.binance.exceptions import BinanceException
from cryptoxlib.clients.binance.functions import map_ws_pair, extract_ws_symbol
from cryptoxlib.clients.b... |
import torch
import numpy as np
from matplotlib import pyplot as plt
import sys
from policy_network import PolicyNetwork
from value_network import ValueNetwork
from buffer import Buffer
class TRPO(object):
def __init__(self, alpha, input_size, output_size):
self.buffer = Buffer()
self.value_ne... |
import csv, datetime as dt
from datetime import datetime
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from db import *
db = create_engine('sqlite:///data/mke_wibrs_db.db', echo = False)
Session = sessionmaker(bind = db)
session = Session()
def get_data(start, end):
with open('data... |
# std
from typing import List, Optional
# 3rd party
from sqlalchemy.sql.expression import text
# custom
from test_system.constants import MAX_HASH_GENERATION_TRY_COUNT, TOKEN_PERIOD_OF_VALIDITY_IN_DAYS
from test_system.util import generate_unknown_hash_token
from test_system.models.database import db
from .answers impo... |
from meadowgrid.config import MEADOWGRID_INTERPRETER
from meadowgrid.meadowgrid_pb2 import ServerAvailableInterpreter
from meadowgrid.runner import (
Deployment,
EC2AllocHost,
LocalHost,
SshHost,
run_command,
run_function,
)
from test_meadowgrid.test_ec2_alloc import _PRIVATE_KEY_FILENAME
asyn... |
from torch.nn.modules import LSTM
import torch.nn as nn
from torch.autograd import Variable
import torch
import pdb
class ChannelLSTM(nn.Module):
def __init__(self,input_size=69505, output_size=5952,hidden_size=52,num_layers=16,batch_first=True,
dropout=0.1):
super(ChannelLSTM, self).__ini... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import unittest
import mock
from oauth2py.client import OauthClient
class TestQQ(unittest.TestCase):
def setUp(self):
self.config = {
'name': 'qq',
'client_id': '1234567',
'client_secret': 'secret_abcefg',
're... |
# 图片验证码Redis有效期, 单位:秒
IMAGE_CODE_REDIS_EXPIRES = 300
# 短信验证码Redis有效期,单位:秒
SMS_CODE_REDIS_EXPIRES = 300
# 七牛空间域名
# QINIU_DOMIN_PREFIX = "http://oyucyko3w.bkt.clouddn.com/"
QINIU_DOMIN_PREFIX = "http://pbbiphbgi.bkt.clouddn.com/"
# 首页展示最多的新闻数量
HOME_PAGE_MAX_NEWS = 10
# 用户的关注每一页最多数量
USER_FOLLOWED_MAX_COUNT = 4
# 用户收藏... |
# encoding=utf-8
'''
Created on 2015年11月9日
@author: lowitty
'''
import logging, os, random, sys
sbcPMlogger = logging.getLogger('server.SBCPM')
from com.ericsson.xn.server.parser.SbcParser import SbcNodeInfo
from xml.etree import ElementTree as ET
import threading, time
from datetime import datetime, timedelta
from ... |
# Generated by Django 3.2.5 on 2021-07-29 04:51
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('src', '0012_courier_paypal_email'),
]
operations = [
migrations.AddField(
model_name='transaction',
name='status',
... |
from django import forms
from django.forms.widgets import DateInput
from book.models import Book, Publisher, Author
class PublisherForm(forms.ModelForm):
class Meta:
model = Publisher
fields = ['name']
class AuthorForm(forms.ModelForm):
class Meta:
model = Author
fields = ['... |
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Fri Feb 17 12:38:44 2017
@author: ahefny, zmarinho
"""
from theano.tensor.shared_randomstreams import RandomStreams
'''
decorator of noisy_model.
'''
class NoisyModel(object):
def __init__(self, obs_noise=0.0, obs_loc=0.0, state_noise=0.0, ... |
#!/usr/bin/env python
# vim:ts=4:sts=4:sw=4:et
#
# Author: Hari Sekhon
# Date: 2016-12-05 16:37:57 +0000 (Mon, 05 Dec 2016)
#
# https://github.com/harisekhon/nagios-plugins
#
# License: see accompanying Hari Sekhon LICENSE file
#
# If you're using my code you're welcome to connect with me on LinkedIn
# and optio... |
from itertools import islice
from .dbconnect import *
from .singleton import *
from .properties import Properties
p = Properties()
db = DBConnect()
class DataModel(metaclass=Singleton):
'''
DataModel is a dictionary of perImageObjectCounts indexed by (TableNumber,ImageNumber)
'''
def __init__(se... |
from __future__ import print_function
from constant import *
from models import *
from dataset import *
from utils import f_score
import os
import sys
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
from sklearn.metrics import f1_score,precision_score,re... |
from flask import Blueprint
bp = Blueprint("Name", __name__) |
from typing import Any, List, Literal, TypedDict
from .FHIR_base64Binary import FHIR_base64Binary
from .FHIR_Element import FHIR_Element
from .FHIR_string import FHIR_string
from .FHIR_uri import FHIR_uri
# A type of a manufactured item that is used in the provision of healthcare without being substantially changed t... |
#!/usr/bin/env python3
# Copyright (c) 2017-present, Facebook, Inc.
# All rights reserved.
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree. An additional grant
# of patent rights can be found in the PATENTS file in the same directory.
# D... |
# ATM machines allow 4 or 6 digit PIN codes and PIN codes cannot contain anything
# but exactly 4 digits or exactly 6 digits.
# If the function is passed a valid PIN string, return true, else return false.
def validate_pin(pin):
try:
if (("+" in pin) or ("\n" in pin) or ("-" in pin)):
return Fa... |
import numpy as np
import tensorflow as tf
import matplotlib.pyplot as plt
import data_processing
data = data_processing.load_data(download=True)
new_data = data_processing.convert2onehot(data)
# prepare training data
new_data = new_data.values.astype(np.float32) # change to numpy array and float32
np.random.s... |
def ack(m, n):
"""Computes the Ackermann function A(m,n).
Args:
m, n: non-negative integers.
"""
if m == 0:
return n + 1
if n == 0:
return ack(m - 1, 1)
return ack(m - 1, ack(m, n - 1))
print(ack(3, 4))
|
# -*- coding: utf-8 -*-
'''Generic test method module
'''
from __future__ import with_statement, division, absolute_import, print_function
from abc import ABCMeta, abstractmethod
import six
@six.add_metaclass(ABCMeta)
class ANTest(object):
'''Generic test method class
'''
__doc__ = ''
def __init_... |
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from gym.spaces import Box, Discrete
def count_vars(module):
return sum(p.numel() for p in module.parameters() if p.requires_grad)
def linearly_decaying_epsilon(decay_period, step, warmup_steps, epsilon):
steps_left = deca... |
# coding: utf-8
from __future__ import print_function
from PySide2.QtWidgets import (
QDialog,
QHBoxLayout,
QPushButton,
QVBoxLayout,
QPlainTextEdit
)
from ProfileInspector.src.util import doc_file
class CaptureStdoutDialog(QDialog):
def __init__(self):
QDialog.__init__(self)
... |
from rolepermissions.roles import AbstractUserRole
class Developer(AbstractUserRole):
available_permissions = {
# Tags
'access_server': True,
'access_testing': True,
'access_sources': True,
'access_admin': False,
# Templates
'create_server_template': False,
... |
#!/usr/bin/env python
#
# Copyright (c) 2010, 2014, Oracle and/or its affiliates. All rights reserved.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; version 2 of the License.
#
# This progra... |
from singleton.singleton import Singleton
@Singleton
class Config(object):
def __init__(self, vars = []):
self.vars = vars
def get_vars():
return Config.instance().vars
|
import subprocess
try:
revision = subprocess.check_output(["git", "rev-parse", "HEAD"]).strip()
print ("-DPIO_SRC_REV=\\\"%s\\\"" % revision)
except:
print ("-DPIO_SRC_REV=\\\"UNKNOWN\\\"")
|
nome = str(input('Qual é seu nome? ')).upper()
if nome == 'ROBERTO' or nome == 'OBA':
print('Que nome bonito!')
elif nome == 'PEDRO' or nome =='JOSE' or nome == 'JOAO' or nome == 'MARIA':
print('Seu nome é bem popular no Brasil. !')
elif nome in ' THAIS LORENA':
print('Belo nome feminino!')
else:
print(... |
import shutil
import tempfile
import six
from . import (
GalaxyTestBase,
test_util
)
class TestGalaxyDatasets(GalaxyTestBase.GalaxyTestBase):
def setUp(self):
super(TestGalaxyDatasets, self).setUp()
self.history_id = self.gi.histories.create_history(name='TestShowDataset')['id']
... |
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 5 10:36:37 2021
Get status of stored reference numbers
@author: heiko
"""
import requests
import pandas as pd
import json
import hashlib
import hmac
import base64
#%% Functions
def getSAPCOOKIE(headers):
'''
Get MYSAPSSO2 cookie.
'''
r = requests.get(... |
import re
from collections import defaultdict
from django.conf import settings
def convert_to_valid_boolean(value):
if value is None:
return False
elif isinstance(value, list):
list_value = value[0]
if hasattr(list_value, "value"):
string_value = list_value.value
... |
# -*- coding: utf-8 -*-
'''Decoder structures'''
from pyresult import is_error, value, ok, error
from six import u
from toolz import curry
@curry
def array(factory, vals):
'''Decode string/value as list
array :: (a -> Result e b) -> List a -> Result e (List b)
>>> from pydecoder.primitives import to_in... |
import argparse
import math
from datetime import datetime
import numpy as np
import socket
import importlib
import zipfile
import os
import sys
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
ROOT_DIR = BASE_DIR
sys.path.append(BASE_DIR)
sys.path.append(os.path.join(ROOT_DIR, 'utils'))
import tf_util
import data... |
# Generated by Django 3.2.5 on 2021-07-22 13:36
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('devices', '0020_auto_20210721_1007'),
]
operations = [
migrations.CreateModel(
name='City',
fields=[
... |
"""Miscellaneous functions
"""
import logging
from math import ceil
from typing import Any, Dict, List, Optional, Tuple, Union, cast
from collections import Counter
import dask
import dask.dataframe as dd
import numpy as np
import pandas as pd
from pandas.api.types import is_object_dtype
from bokeh.models import Lege... |
# © 2020 Nokia
# Licensed under the BSD 3-Clause License.
# SPDX-License-Identifier: BSD-3-Clause
# !/usr/bin/env python3
# coding: utf-8
# Author: Élie de Panafieu <elie.de_panafieu@nokia-bell-labs.com>
from matrix_operations import *
class VectorSpace:
def __init__(self, iterables):
self.item_to_ind... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Bert_Service.py
2018/11/22 10:29 AM by berton
berton820@163.com
"""
from flask import Flask, request, jsonify
import json
import os
os.environ['CUDA_VISIBLE_DEVICES'] = '0'
try:
from .predict_glue import *
except:
from predict_glue import *
import logging
log ... |
from ddf_utils.chef.model.ingredient import DataPointIngredient
def multiply_1000(chef, ingredients, result, **options):
# ingredients = [chef.dag.get_node(x) for x in ingredients]
ingredient = ingredients[0]
new_data = dict()
for k, df in ingredient.get_data().items():
df_ = df.copy()
... |
from colorama import Fore, Style
from string import Template
from os import path, mkdir, scandir
from shutil import copyfile
import networkx as nx
from warnings import warn
import vhdl_util
VERSION = 0.1
class deparserHDL(object):
def __getlibrary(self):
"""set a dictionnary with library folder
e... |
#!/usr/bin/env python3
#
# Copyright (c) 2017 Weitna LI <weitian@aaronly.me>
# MIT License
#
"""
Average the 2D power spectrum within the EoR window (i.e., excluding the
foreground contaminated wedge) to derive the 1D spherically averaged
power spectrum.
"""
import os
import argparse
import numpy as np
import matpl... |
from typing import List, Tuple, Optional
import random
def bubble_sort_(ls: List) -> List:
nElem = len(ls)
if nElem <= 1:
return ls
swap_flag = True
while swap_flag:
swap_flag = False
for idx in range(nElem-1):
if ls[idx] > ls[idx + 1]:
ls[idx], ls[id... |
'''
Copyright 2017 Ewan Mellor
Changes authored by Hadi Esiely:
Copyright 2018 The Johns Hopkins University Applied Physics Laboratory LLC.
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... |
import os
import matplotlib
#matplotlib.use('Agg')
import matplotlib.pyplot as plt
import numpy as np
class Visualization(object):
def __init__(self, output_dir= None):
if not os.path.exists(output_dir):
os.makedirs(output_dir)
self.output_dir = output_dir
def compare_images(sel... |
"""Change step_number to int.
Revision ID: 430f2963adb9
Revises: 107d9a8cb98a
Create Date: 2013-09-25 18:02:23.582384
"""
# revision identifiers, used by Alembic.
revision = '430f2963adb9'
down_revision = '107d9a8cb98a'
from alembic import op
import sqlalchemy as sa
def upgrade():
### commands auto generated ... |
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
from helpers import *
from js.utils.plot.colors import colorScheme
mpl.rc('font',size=30)
mpl.rc('lines',linewidth=2.)
figSize = (21, 10)
figSize = (16, 10)
cs = colorScheme("label")
#pathToTimings = "../results/ablation_fr2_xyz/fullmode/tim... |
# Generated by Django 2.2.16 on 2021-06-03 06:44
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('petition', '0011_auto_20210524_2151'),
]
operations = [
migrations.AddField(
model_name='pytitionuser',
name='moder... |
import requests
from urllib.parse import urljoin
from bs4 import BeautifulSoup
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
@api_view(['GET', 'POST'])
def get_input_data(request):
if request.method == 'POST':
_url = request.d... |
# Copyright (C) 2022 Intel Corporation
# SPDX-License-Identifier: BSD-3-Clause
import os
from typing import Tuple, Union
import numpy as np
from PIL import Image
import glob
class PilotNetDataset():
"""Generic PilotNet dataset class. Returns image and ground truth value
when the object is indexed.
Para... |
from numpy import *
class PSO(object):
'''particle swarm optimization
f: fit function
cmp_f: compare function
init_f: initialization function
p_size: number of particles
bound_f: bound function(bool)
vmax: maximum moving velocity
gen_rate: like GA, the best biont... |
import pytest
from iteretor_tutorial.itertools_examples import *
@pytest.fixture
def sequences():
return ["agctctt", "tggtgta", "gcttagt", "aaaagtctgt", "cccta"]
@pytest.fixture
def lines():
return ["# header1", "# header2", "# header3", "0", "10", "20"]
@pytest.fixture
def ages():
return [10, 15, 17, ... |
class Env:
def __init__(self, pre=None):
self.table = {}
self.pre = pre
def put(self, w, i):
self.table.update({w: i})
def get(self, w):
e = self
while e:
found = e.table.get(w)
if found:
return found
e = e.pre
... |
"""Stuff to parse WAVE files.
Usage.
Reading WAVE files:
f = wave.open(file, 'r')
where file is either the name of a file or an open file pointer.
The open file pointer must have methods read(), seek(), and close().
When the setpos() and rewind() methods are not used, the seek()
method is not necessary.
This ... |
# 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
# distributed u... |
class Solution(object):
def isMatch(self, s, p):
"""
:type s: str
:type p: str
:rtype: bool
"""
# i and j are the pointers to the char that we are going to check,
# if i and j reach their ends simultaneously, the two strings are matched.
# ne... |
from openpyxl import Workbook
from openpyxl.styles import Alignment
class ExcelConverter:
def __init__(self, filename, data):
self.filename = filename
self.workbook = Workbook()
self.data = data
def create_file(self):
new_sheet = self.workbook.active
counter = 1
... |
# (C) Copyright 2020 ECMWF.
#
# This software is licensed under the terms of the Apache Licence Version 2.0
# which can be obtained at http://www.apache.org/licenses/LICENSE-2.0.
# In applying this licence, ECMWF does not waive the privileges and immunities
# granted to it by virtue of its status as an intergovernmenta... |
from flask import render_template , request, redirect, url_for
from . import main
from flask_wtf import FlaskForm
from .forms import BlogForm,UpdateProfile,UpdateBlog
from ..models import User,Blog
from .. import db,photos
from ..email import mail_message
from flask_login import LoginManager, UserMixin, login_require... |
from ncls import NCLS
import pickle
import pandas as pd
import numpy as np
starts = np.array(list(reversed([3, 5, 8])), dtype=np.long)
ends = np.array(list(reversed([6, 7, 9])), dtype=np.long)
indexes = np.array(list(reversed([0, 1, 2])), dtype=np.long)
# starts = np.array([3, 5, 8], dtype=np.long)
# ends = np.a... |
#!/home/rathankalluri/pys/aws-django/env/bin/python3
from django.core import management
if __name__ == "__main__":
management.execute_from_command_line()
|
from django.conf import settings
def secret_for_invitation(request):
if request.path == '/':
return {
'invitation_secret': settings.USER_INVITATION_SECRET
}
else:
return {}
|
# !/Library/Frameworks/Python.framework/Versions/3.7/bin/python3
# -*- coding:utf-8 -*-
# @Author : Jiazhixiang
import requests
# 引用requests库
from bs4 import BeautifulSoup
# 引用BeautifulSoup库
headers = {
"User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.