content stringlengths 0 894k | type stringclasses 2
values |
|---|---|
from django.contrib import admin
from . import models
# Register your models here.
admin.site.register(models.Student)
admin.site.register(models.Subject)
admin.site.register(models.Assignment)
admin.site.register(models.Submission)
| python |
# -*- coding: utf-8 -*-
from django.core.management import call_command
from django.db import migrations
def create_cache_table(apps, schema_editor):
"""
创建 cache table
"""
call_command("createcachetable", "account_cache")
class Migration(migrations.Migration):
dependencies = [
("accou... | python |
from django.contrib.auth import get_user_model
from questionnaire.models import Questionnaire
from functional_tests.base import FunctionalTest
from functional_tests.pages.qcat import HomePage
from functional_tests.pages.questionnaire import QuestionnaireStepPage
from functional_tests.pages.technologies import Technolo... | python |
#!/usr/bin/env python3
# -*- encoding: utf-8 -*-
from models.user import User
from database import session
def create_user(login_session):
"""Create a new user from login session and return his id."""
newUser = User(name=login_session["username"],
email=login_session["email"],
... | python |
from tkinter import *
import tkinter as tk
from tkinter import ttk
from tkinter import messagebox
from PIL import ImageTk, Image
from PyDictionary import PyDictionary
from googletrans import Translator
root = tk.Tk()
root.title("Yanis's Dictionary")
root.geometry('600x300')
root['bg'] = 'white'
frame = Fra... | python |
import socket
import threading
HOST = '127.0.0.1'
PORT = 9999
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((HOST, PORT))
print 'Connect Success!....'
def sendingMsg():
while True:
data = raw_input('')
sock.send(data)
sock.close()
def gettingMsg():
while True:
... | python |
# Generated by Django 3.1.1 on 2020-10-30 15:53
import django.contrib.postgres.fields
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('grant_applications', '0009_auto_20201030_1209'),
]
operations = [
migrations.AddField(
mod... | python |
# select CALOL1_KEY from CMS_TRG_L1_CONF.L1_TRG_CONF_KEYS where ID='collisions2016_TSC/v206' ;
import re
import os, sys, shutil
import subprocess
import six
"""
A simple helper script that provided with no arguments dumps a list of
top-level keys, and provided with any key from this list as an argument,
dumps a list of... | python |
# -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2018-11-23 10:18
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('wdapp', '0011_auto_20181123_0955'),
]
operations = [
migrations.RemoveField(
... | python |
# -*- coding: utf-8 -*-
"""
配置日志信息,并添加 request_id
:create: 2018/9/23
:copyright: smileboywtu
"""
import datetime
import logging
import sys
import uuid
from logging.handlers import TimedRotatingFileHandler
from tornado import gen
from tornado.log import access_log
from tornado.stack_context import run_with_stack_con... | python |
# coding: utf-8
# In[87]:
#基于分词的文本相似度的计算,
#利用jieba分词进行中文分析
import jieba
import jieba.posseg as pseg
from jieba import analyse
import numpy as np
import os
'''
文本相似度的计算,基于几种常见的算法的实现
'''
class TextSimilarity(object):
def __init__(self,file_a,file_b):
'''
初始化类行
'''
str_a = ''
... | python |
import dash_bootstrap_components as dbc
import dash_html_components as html
from dash.dependencies import Input, Output, State
popover = html.Div(
[
html.P(
["Click on the word ", html.Span("popover", id="popover-target")]
),
dbc.Popover(
[
dbc.Popove... | python |
#!/usr/bin/env python
#
# Copyright 2018 Google Inc. 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 b... | python |
##############################
# import Verif #
# var = Verif.class(object) #
# var.def() #
##############################
# this lib it's verification #
# maked by khalil preview #
##############################
import tkinter
from tkinter import *
from tkinter import mes... | python |
import attrs
import asyncio
import datetime
import os
import shutil
import pickle
from typing import Any, Optional, List
@attrs.define
class Cache:
name: str
data: Any
expired_after: int = attrs.field(default=10)
expiration: datetime.datetime = attrs.field(init=False)
@expiration.default
def ... | python |
#Done by Carlos Amaral in 18/06/2020
"""
Imagine an alien was just shot down in a game. Create a
variable called alien_color and assign it a value of 'green' , 'yellow' , or 'red' .
• Write an if statement to test whether the alien’s color is green. If it is, print
a message that the player just earned 5 points.
• Wri... | python |
# -*- coding: utf-8 -*-
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: epl/protobuf/v1/query.proto
from google.protobuf.internal import enum_type_wrapper
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as... | python |
from qqai.classes import *
class TextTranslateAILab(QQAIClass):
"""文本翻译(AI Lab)"""
api = 'https://api.ai.qq.com/fcgi-bin/nlp/nlp_texttrans'
def make_params(self, text, translate_type=0):
"""获取调用接口的参数"""
params = {'app_id': self.app_id,
'time_stamp': int(time.time()),
... | python |
"""
Enumeración de estado del resultado de una partida de PPT.
"""
from enum import Enum
class Condicion(Enum):
"""
Posibles estados del resultado de la partida.
"""
VICTORIA = 0
DERROTA = 1
EMPATE = 2
| python |
import csv
import random
def load_lorem_sentences():
with open('lorem.txt') as fh:
return [l.strip() for l in fh.readlines()]
def load_dictionary():
with open('dictionary.csv') as csv_file:
return [l for l in csv.DictReader(csv_file, delimiter=',')]
SUFFIXES = ['at', 'it', 'is', 'us', 'et'... | python |
import pickle
import random
import h5py
import numpy as np
import pandas as pd
class Generator():
""" Data generator to the neural image captioning model (NIC).
The flow method outputs a list of two dictionaries containing
the inputs and outputs to the network.
# Arguments:
data_path = data_pa... | python |
#!/usr/bin/env python
# # -*- coding: utf-8 -*-
"""
@File: routes.py.py
@Author: Jim.Dai.Cn
@Date: 2020/9/22 上午11:26
@Desc:
"""
from app.company import blueprint
from flask import render_template, jsonify, current_app, request
@blueprint.route('/company', methods=['GET'])
def get_company_list(... | python |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'GUIs\LoadDataDialog.ui'
#
# Created by: PyQt5 UI code generator 5.6
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_fromMemoryDialog(object):
def setupUi(self, fromMemoryDial... | python |
import random
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
class Person:
def __init__(self, name, hp, mp, atk, df, magic, items,type):
self.maxhp =... | python |
import torch
import torch.utils.data as data
import os
import pickle
import numpy as np
from data_utils import Vocabulary
from data_utils import load_data_and_labels_klp, load_data_and_labels_exo
from eunjeon import Mecab
NER_idx_dic = {'<unk>': 0, 'B-PS_PROF': 1, 'B-PS_ENT': 2, 'B-PS_POL': 3, 'B-PS_NAME': 4,
... | python |
"""
Test file to test RetrieveMovie.py
"""
from Product.Database.DatabaseManager.Retrieve.RetrieveMovie import RetrieveMovie
from Product.Database.DBConn import create_session
from Product.Database.DBConn import Movie
def test_retrieve_movie():
"""
Author: John Andree Lidquist
Date: 2017-11-16
Last Up... | python |
import torch
import shutil
import os
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix
from sklearn.utils.multiclass import unique_labels
def rotation(inputs):
batch = inputs.shape[0]
target = torch.Tensor(np.random.permutat... | python |
# -*- coding: utf-8 -*-
"""These test the utils.py functions."""
from __future__ import unicode_literals
import pytest
from hypothesis import given
from hypothesis.strategies import binary, floats, integers, lists, text
from natsort.compat.py23 import PY_VERSION, py23_str
from natsort.utils import natsort_key
if PY_V... | python |
from ..abstract import ErdReadOnlyConverter
from ..primitives import *
from gehomesdk.erd.values.fridge import FridgeIceBucketStatus, ErdFullNotFull
class FridgeIceBucketStatusConverter(ErdReadOnlyConverter[FridgeIceBucketStatus]):
def erd_decode(self, value: str) -> FridgeIceBucketStatus:
"""Decode Ice bu... | python |
import datetime
import unittest
import unittest.mock
from conflowgen.api.container_flow_generation_manager import ContainerFlowGenerationManager
from conflowgen.application.models.container_flow_generation_properties import ContainerFlowGenerationProperties
from conflowgen.domain_models.distribution_models.mode_of_tra... | python |
from polecat.rest.schema_builder import RestSchemaBuilder
def test_schema_builder():
schema = RestSchemaBuilder().build()
assert len(schema.routes) > 0
| python |
from PIL import Image
import matplotlib.pyplot as plt
# Log images
def log_input_image(x, opts):
return tensor2im(x)
def tensor2im(var):
# var shape: (3, H, W)
var = var.cpu().detach().transpose(0, 2).transpose(0, 1).numpy()
var = ((var + 1) / 2)
var[var < 0] = 0
var[var > 1] = 1
var = var * 255
return Imag... | python |
import csv
from argparse import ArgumentParser
import re
parser = ArgumentParser()
parser.add_argument('--input_file', type=str)
parser.add_argument('--output_csv_file', type=str)
parser.add_argument('--option', default='eval', choices=['eval', 'debug'])
args = parser.parse_args()
lang_regex = re.compile('lang=(\w+... | python |
import torch
import torch.nn as nn
import torchvision.models as models
class EncoderCNN(nn.Module):
def __init__(self, embed_size):
super(EncoderCNN, self).__init__()
resnet = models.resnet50(pretrained=True)
for param in resnet.parameters():
param.requires_grad_(False)
... | python |
import unittest
from unittest.mock import patch
import pytest
import Parser.languageInterface as languageInterface
# class Test_LanguageInterface(unittest.TestCase):
# @patch('Parser.languageInterface.LanguageInterface.getSymbols')
# @patch('Parser.languageInterface.LanguageInterface.printParsedData')
# ... | python |
import os
import os.path as op
from sklearn.externals import joblib as jl
from glob import glob
from sklearn.pipeline import Pipeline
from sklearn.feature_selection import f_classif, SelectPercentile
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import StratifiedKFold
from sklearn.svm im... | python |
import os
import copy
from util.queryParser import SimpleQueryParser
def gene_imagenet_synset(output_file):
sid2synset = {}
for line in open('visualness_data/words.txt'):
sid, synset = line.strip().split('\t')
sid2synset[sid] = synset
fout = open(output_file, 'w')
for line in open('vi... | python |
#!/usr/bin/env python3
"""
Count the number of called variants per sample in a VCF file.
"""
import argparse
import collections
import vcf
def parse_args():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"vcf", help="the vcf file to analyze", type=lambda f: vcf.Reader(fil... | python |
from django.contrib import admin
from django.db import models
from tinymce.widgets import TinyMCE
from .models import Aviso
from .models import AvisoViewer
from .forms import AvisoFormAdmin
@admin.register(Aviso)
class AvisoAdmin(admin.ModelAdmin):
fields = ['titulo', 'subtitulo', 'data', 'texto', 'autor', 'edit... | python |
import json
USERS = "../static/user.json"
def read_JSON(filename):
try:
with open(filename, "r") as file_obj:
return json.load(file_obj)
except:
return dict()
def write_JSON(data, filename):
with open(filename, "w+") as file_obj:
json.dump(data, file_obj)
def append_J... | python |
from utils.code_runner import execute_code
import math
def sum_divisors(n):
if n == 1:
return 1
sqrt_n = math.ceil(math.sqrt(n))
divisor = 2
total_sum = 1
while divisor < sqrt_n:
if n % divisor == 0:
total_sum += divisor
total_sum += n // divisor
... | python |
from datadog import initialize, statsd
import random
import time
options = {
'statsd_host':'127.0.0.1',
'statsd_port':8125
}
initialize(**options)
namespace = "testing7"
# statsd.distribution('example_metric.distribution', random.randint(0, 20), tags=["environment:dev"])
statsd.timing("%s.timing"%namespace, ... | python |
import numpy as np
import ad_path
import antenna_diversity as ad
import matplotlib.pyplot as plt
import h5py
import typing as t
import time
import os
ad_path.nop()
bits_per_slot = 440
slots_per_frame = 1
give_up_value = 1e-6
# How many bits to aim for at give_up_value
certainty = 20
# Stop early at x number of error... | python |
import uuid
import factory.fuzzy
from dataworkspace.apps.request_access import models
from dataworkspace.tests.factories import UserFactory
class AccessRequestFactory(factory.django.DjangoModelFactory):
requester = factory.SubFactory(UserFactory)
contact_email = factory.LazyAttribute(lambda _: f"test.user+{... | python |
# Joey Alexander
# Built by Gautam Mittal (2017)
# Real-time chord detection and improvisation software that uses Fast Fourier Transforms, DSP, and machine learning
import sys
sys.path.append('util')
from PyQt4 import QtGui, QtCore
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from m... | python |
# coding=utf-8
#Author: Chion82<sdspeedonion@gmail.com>
import requests
import urllib
import re
import sys, os
import HTMLParser
import json
from urlparse import urlparse, parse_qs
reload(sys)
sys.setdefaultencoding('utf8')
class PixivHackLib(object):
def __init__(self):
self.__session_id = ''
self.__session... | python |
# Generated by Django 3.0.2 on 2020-01-20 10:34
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('api', '0003_auto_20200117_1430'),
]
operations = [
migrations.AlterField(
model_name='imagefile... | python |
#!/usr/bin/env python
# file_modified.py
# takes input file or string and returns file modified date
# -----------------------------------------------------------------------------
# Imports
# -----------------------------------------------------------------------------
import os.path, sys
parent_dir = os.path.abspath... | python |
#!/usr/bin/env python
"""Normalizes ini files."""
# pylint: disable=C0103
# pylint: disable=R0903
# pylint: disable=R1702
# pylint: disable=R0912
import re
import sys
from collections import defaultdict
class Processor:
"""Process and normalizes an ini file."""
def __init__(self):
self.r: dict[str,... | python |
import poplib
from email.parser import Parser
email = 'liang_renhong@163.com'
password = 'lrh0000'
pop3_server = 'pop.163.com'
server = poplib.POP3(pop3_server)
print(server.getwelcome().decode('utf8'))
server.user(email)
server.pass_(password)
print('Message: %s. Size: %s' % (server.stat()))
resp, mails, octe... | python |
def test_dictionary():
"""Dictionary"""
fruits_dictionary = {
'cherry': 'red',
'apple': 'green',
'banana': 'yellow',
}
assert isinstance(fruits_dictionary, dict)
assert fruits_dictionary['apple'] == 'green'
assert fruits_dictionary['banana'] == 'yellow'
assert frui... | python |
import os, time, logging, configparser, psutil
# Setting
logging.basicConfig(filename='log/app.log', filemode='w',format='[%(levelname)s][%(name)s][%(asctime)s] %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
logger = logging.getLogger(__name__)
logger.info('Module Loaded')
config = configparser.ConfigParser()
config.read("... | python |
# Copyright 2016 AC Technologies 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 required by applicable... | python |
import os
from shutil import copy
def prepare_iso_linux(iso_base_dir, rootfs_dir):
# copy isolinux files to the corresponding folder
isolinux_files = ['isolinux.bin', 'isolinux.cfg', 'ldlinux.c32']
for file in isolinux_files:
full_file = '/etc/omni-imager/isolinux/' + file
copy(full_file, ... | python |
# Generated by Django 3.1 on 2021-03-02 21:33
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('waterspout_api', '0007_auto_20201215_1526'),
]
operations = [
migrations.AddField(
model_name='ca... | python |
#!/usr/bin/env python3
import sys, utils, random # import the modules we will need
utils.check_version((3,7)) # make sure we are running at least Python 3.7
utils.clear() # clear the screen
print('Greetings!') # print out 'Greeting!'
colors = ['red','orange',... | python |
import sys
PY3 = (sys.version_info[0] >= 3)
if PY3:
basestring = unicode = str
else:
unicode = unicode
basestring = basestring
if PY3:
from ._py3compat import execfile
else:
execfile = execfile
| python |
#!/usr/bin/env python
import sys
import subprocess
#----------------------------------------------------------------------
## generic pipe-like cleaning functions
def rpl(x, y=''):
def _func(s):
return s.replace(x, y)
return _func
def pipe(*args):
def _func(txt):
return subprocess.run(li... | python |
import flask
from flask import request, jsonify
from secrets import secrets
from babel_categories import BabelCategories
from babel_hypernyms import BabelHypernyms
from babel_lemmas_of_senses import BabelLemmasOfSenses
from babel_parser import BabelParser
app = flask.Flask(__name__)
app.config["DEBUG"] = True
@app.r... | python |
__author__ = 'Spasley'
| python |
from rest_framework import exceptions, status
from api.services import translation
class PreconditionFailedException(exceptions.APIException):
status_code = status.HTTP_412_PRECONDITION_FAILED
default_detail = translation.Messages.MSG_PRECONDITION_FAILED
default_code = 'precondition_failed'
| python |
import warnings
import pulumi
class Provider(pulumi.ProviderResource):
"""
The provider type for the kubernetes package.
"""
def __init__(self,
resource_name,
opts=None,
cluster=None,
context=None,
enable_dry_run=No... | python |
import json
import pulumi
import pulumi_aws as aws
# CONFIG
DB_NAME='dbdemo'
DB_USER='user1'
DB_PASSWORD='p2mk5JK!'
DB_PORT=6610
IAM_ROLE_NAME = 'redshiftrole'
redshift_role = aws.iam.Role(IAM_ROLE_NAME,
assume_role_policy=json.dumps({
"Version": "2012-10-17",
"Statement": [{
"Action"... | python |
import win32api, mmapfile
import winerror
import tempfile, os
from pywin32_testutil import str2bytes
system_info=win32api.GetSystemInfo()
page_size=system_info[1]
alloc_size=system_info[7]
fname=tempfile.mktemp()
mapping_name=os.path.split(fname)[1]
fsize=8*page_size
print fname, fsize, mapping_name
m1... | python |
# Copyright (c) Microsoft Corporation.
# Copyright (c) 2018 Jensen Group
# Licensed under the MIT License.
"""
Module for generating rdkit molobj/smiles/molecular graph from free atoms
Implementation by Jan H. Jensen, based on the paper
Yeonjoon Kim and Woo Youn Kim
"Universal Structure Conversion Method for O... | python |
import logging
import os
import socket
from logging import Logger
from typing import Any, Dict, List, Optional, Union
from pathlib import Path
import docker
import dockerpty
from docker import DockerClient
from docker.models.images import Image
from docker.errors import APIError, DockerException
from requests import R... | python |
#!/usr/bin/python
# coding=utf-8
import json
import sys
from PIL import Image
from pprint import pprint
import mutual_infor as mi
'''
note: Imager
'''
default_img_path = "img.jpg"
data_dir = "data/map_img/"
class Imager:
def __init__(self, path):
self.path = path
self.entropy = ... | python |
from z3 import Int
class Storage(object):
def __init__(self):
self._storage = {}
def __getitem__(self, item):
if item not in self._storage.keys():
# self._storage[item] = Int("s_" + str(item))
self._storage[item] = 0
return self._storage[item]
def __setite... | python |
import os, sys
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
import unittest
import kenlm
from predictor import WordPredictor
from vocabtrie import VocabTrie
import numbers
class TestWordPredictor(unittest.TestCase):
def setUp(self):
self.wordPredictor = WordPredictor('../... | python |
import logging
from pdb import Pdb
import sys
import time
from pathlib import Path
from typing import List
from pprint import pformat
import docker
import yaml
logger = logging.getLogger(__name__)
current_dir = Path(sys.argv[0] if __name__ == "__main__" else __file__).resolve().parent
WAIT_TIME_SECS = 20
RETRY_COUN... | python |
"""Settings for admin panel related to the authors app."""
| python |
import unittest
from yauber_algo.errors import *
class PercentRankTestCase(unittest.TestCase):
def test_category(self):
import yauber_algo.sanitychecks as sc
from numpy import array, nan, inf
import os
import sys
import pandas as pd
import numpy as np
from ... | python |
import sys
import pandas as pd
from sqlalchemy import create_engine
import pickle
import nltk
nltk.download(['punkt', 'wordnet', 'averaged_perceptron_tagger'])
import re
import numpy as np
from nltk.tokenize import word_tokenize
from nltk.stem import WordNetLemmatizer
from sklearn.metrics import confusion_matrix, clas... | python |
_base_ = '../pointpillars/hv_pointpillars_secfpn_6x8_160e_kitti-3d-car.py'
voxel_size = [0.16, 0.16, 4]
point_cloud_range = [0, -39.68, -3, 69.12, 39.68, 1]
model = dict(
type='DynamicVoxelNet',
voxel_layer=dict(
max_num_points=-1,
point_cloud_range=point_cloud_range,
voxel_size=voxel_... | python |
import collections
import sys
def main(letters, words):
d = collections.defaultdict(list)
print(d)
print(letters)
print(words)
if __name__ == "__main__":
main(sys.argv[1], sys.argv[2:])
| python |
# ### Problem 1
# Ask the user to enter a number.
# Using the provided list of numbers, use a for loop to iterate the array and print out all the values that are smaller than the user input and print out all the values that are larger than the number entered by the user.
# ```
# # Start with this List
# list_of_many_... | python |
import tensorflow as tf
import numpy as np
import json
import argparse
import cv2
import os
import glob
import math
import time
import glob
def infer(frozen_pb_path, output_node_name, img_path, output_path=None):
with tf.gfile.GFile(frozen_pb_path, "rb") as f:
restored_graph_def = tf.GraphDef()
res... | python |
#!flask/bin/python
# -*- coding: utf-8 -*-
from api import app
from flask import jsonify, make_response
@app.errorhandler(401)
def unauthorized(error=None):
mensagem = {'status': 401, 'mensagem': 'Voce nao tem permissao para acessar essa pagina!'}
resp = jsonify(mensagem)
resp.status_code = 401
# RED... | python |
from hwt.hdl.types.bits import Bits
from hwt.hdl.types.stream import HStream
from hwt.hdl.types.struct import HStruct
class USB_VER:
USB1_0 = "1.0"
USB1_1 = "1.1"
USB2_0 = "2.0"
class PID:
"""
USB Protocol layer packet identifier values
:attention: visualy writen in msb-first, transmited in... | python |
###############################################################################
# Author: Wasi Ahmad
# Project: Match Tensor: a Deep Relevance Model for Search
# Date Created: 7/28/2017
#
# File Description: This script contains code related to the sequence-to-sequence
# network.
################################... | python |
"""
Aravind Veerappan
BNFO 601 - Exam 2
Question 2. Protein BLAST
"""
import math
from PAM import PAM
class BLAST(object):
FORWARD = 1 # These are class variables shared by all instances of the BLAST class
BACKWARD = -1
ROW = (0, 1)
COLUMN = (1, 0)
def __init__(self, query=None,... | python |
import sublime, sublimeplugin
import os
class NewPluginCommand(sublimeplugin.WindowCommand):
def run(self, window, args):
view = window.newFile()
path = sublime.packagesPath() + u"/user"
try:
os.chdir(path)
except Exception:
pass
view.options().set("syntax", "Packages/Python/Python.tmLanguag... | python |
#!/usr/bin/env python3
import math
def main():
limit = 999
print(sumOfMultiples(3, limit) + sumOfMultiples(5, limit) - sumOfMultiples(15, limit))
def sumOfMultiples(n, max):
return n * (math.floor(max / n) * (math.floor(max / n) + 1)) / 2
if __name__ == "__main__": main() | python |
from .orders import Order
from .customers import Customer
from .products import Product
from .line_items import LineItem
from .lot_code import LotCode
from .warehouse import Warehouse
from .location import Location
from .inventories import Inventory
from .inventory_adjustments import InventoryAdjustment
from .inventory... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
from flask import Flask
from flask import abort
from flask import make_response
from flask import render_template
from flask import request
import sleekxmpp
app = Flask(__name__)
app.config.from_envvar("XMPP_CHAT_BADGE_CONFIG")
# Python versions before 3.0 do... | python |
import chess
from datetime import datetime
from tqdm import tqdm
from os import getcwd
from utils.trans_table_utils import *
from utils.history_utils import *
from utils.heuristics import combined
from agents.alpha_beta_agent import AlphaBetaAgent
from agents.alpha_beta_agent_trans import AlphaBetaAgentTrans
from age... | python |
#!/usr/bin/env python
"""
The galvo voltage control UI
Aditya Venkatramani 04/21 --> Adapted from zStage.py
"""
import os
from PyQt5 import QtCore, QtGui, QtWidgets
import storm_control.sc_library.parameters as params
import storm_control.hal4000.halLib.halDialog as halDialog
import storm_control.hal4000.halLib.hal... | python |
from os import system, name
system('cls' if name == 'nt' else 'clear')
dsc = ('''DESAFIO 019:
Um professor quer sortear um dos seus quatro alunos para apagar
o quadro. Faça um um programa que ajude ele, lendo o nome deles e
escrevendo o nome escolhido.
''')
from random import choice
alunos = []
alunos.append(input('... | python |
#!/usr/bin/env python
import pytest
import sklearn.datasets as datasets
import sklearn.neural_network as nn
import pandas_ml as pdml
import pandas_ml.util.testing as tm
class TestNeuralNtwork(tm.TestCase):
def test_objectmapper(self):
df = pdml.ModelFrame([])
self.assertIs(df.neur... | python |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# __BEGIN_LICENSE__
# Copyright (c) 2009-2013, United States Government as represented by the
# Administrator of the National Aeronautics and Space Administration. All
# rights reserved.
#
# The NGT platform is licensed under the Apache License, Version 2.0 (the
# "Lic... | python |
""" Tests for the main server file. """
from unittest import TestCase
from unittest.mock import patch
from app import views
class ViewsTestCase(TestCase):
""" Our main server testcase. """
def test_ping(self):
self.assertEqual(views.ping(None, None), 'pong')
@patch('app.views.notify_recipient')... | python |
#
__doc__ = """
Schema for test/simulator configuration file.
TODO:
- Somehow, validation of test config doesn't work correctly. Only type conversion works.
"""
from configobj import ConfigObj, flatten_errors
from validate import Validator, ValidateError, VdtTypeError
import os
from StringIO import StringIO
impor... | python |
# -*- coding: utf-8 -*-
"""
Progress component
"""
from bowtie._component import Component
class Progress(Component):
"""This component is used by all visual components and
is not meant to be used alone.
By default, it is not visible.
It is an opt-in feature and you can happily use Bowtie
withou... | python |
from rest_framework.test import APITestCase
from django.urls import reverse
from django.contrib.auth import get_user_model
from requests.auth import HTTPBasicAuth
from django.conf import settings
class JWTViewsTestCase(APITestCase):
def test_fails_when_logged_out(self):
self.client.logout()
respo... | python |
from guhs.guhs_configuration import GuhsConfiguration
def from_guhs_configuration(configuration: GuhsConfiguration):
return {
'targets': [
{'order_id': t.order_id, 'name': t.name}
for t in configuration.targets
],
'boot_selection_timeout': configuration.boot_selecti... | python |
from email.policy import default
from .base import print_done, finalize, SRC_PATH, CONFIG_PATH
import invoke
@invoke.task
def isort(context, src_path=SRC_PATH):
print('Running isort...')
context.run('isort {src_path} -m VERTICAL_HANGING_INDENT --tc'.format(src_path=src_path))
print_done(indent=4)
@invo... | python |
# Escreva um programa que pergunte a quantidade de Km
# percorridos por um carro alugado e a quantidade de dias pelos
# quais ele foi alugado. Calcule o preço a pagar, sabendo que o carro
# custa R$60 por dia e R$0.15 por Km rodado.
km = float(input("Quantos km percorreu?: "))
dia = int(input("Quantos dias ele foi alu... | python |
import os
# import pprint
import re
from datetime import datetime
from pathlib import Path
from nornir_napalm.plugins.tasks import napalm_get
from nornir_utils.plugins.functions import print_result
from nornir_utils.plugins.tasks.files import write_file
# from nornir_netmiko.tasks import netmiko_send_command, netmiko... | python |
from sqlalchemy import exc as sa_exc
from sqlalchemy.orm import state_changes
from sqlalchemy.testing import eq_
from sqlalchemy.testing import expect_raises_message
from sqlalchemy.testing import fixtures
class StateTestChange(state_changes._StateChangeState):
a = 1
b = 2
c = 3
class StateMachineTest(f... | python |
import operator
import rules
from rules.predicates import is_authenticated
from marketplace.domain import marketplace
rules.add_perm('user.is_same_user', operator.eq)
rules.add_perm('user.is_authenticated', is_authenticated)
rules.add_rule('user.is_site_staff', marketplace.user.is_site_staff)
rules.add_rule('vol... | python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.