text stringlengths 1 927k |
|---|
from BaseModel.BaseModel import BaseModel
from django.db import models
from levels.models import Level
class FilmCategory(models.Model):
"""电影类别表"""
name = models.CharField(max_length=50, verbose_name='名称')
class Meta:
db_table = 'tb_film_category'
verbose_name = '电影类别'
verbose_n... |
#!/usr/bin/env python3
#
# Author:
# Tamas Jos (@skelsec)
#
class CommentStreamA:
def __init__(self):
self.data = None
@staticmethod
def parse(dir, buff):
csa = CommentStreamA()
buff.seek(dir.Location.Rva)
csa.data = buff.read(dir.Location.DataSize).decode()
return csa
def __str__(self):
return 'Co... |
# qubit number=4
# total number=11
import pyquil
from pyquil.api import local_forest_runtime, QVMConnection
from pyquil import Program, get_qc
from pyquil.gates import *
import numpy as np
conn = QVMConnection()
def make_circuit()-> Program:
prog = Program() # circuit begin
prog += H(0) # number=1
pr... |
from slacker.commands.command import Command
from slacker.commands.argument_parser import ArgumentParser
class ChatPostEphemeralCommand(Command):
def name(self):
return "chat.postephemeral"
def description(self):
return "Post ephemeral message to a channel on Slack that is only visible to assigned user."
... |
#!/usr/bin/env python3
"""
Copyright (C) 2021 Intel Corporation
SPDX-License-Identifier: BSD-3-Clause
"""
from tts_openvino.synthesizer import Synthesizer
class tacotron_tts:
def __init__(self):
duration_model = "/model/text-to-speech-en-0001-duration-prediction.xml"
regression_model = "/model/... |
from pyteomics import mzml
import numpy as np
from collections import defaultdict, Counter
from os import path
import math
from scipy.optimize import curve_fit
import logging
logger = logging.getLogger(__name__)
from .cutils import get_fast_dict, get_and_calc_apex_intensity_and_scan
class MS1OnlyMzML(mzml.MzML):
... |
from appium import webdriver
def init_driver():
desired_caps = {}
# 设备信息
desired_caps['platformName'] = 'Android'
desired_caps['platformVersion'] = '7.0'
desired_caps['deviceName'] = 'A02YECPH27MHJ'
# app的信息com.ecaray.epark.xiangyang com.ecaray.epark.xiangyang.ui.GuideActivity
desired_caps[... |
#
# 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 License, Version 2.0 (the
# "License"); you may not... |
"""
**For most use cases, this can just be considered an internal class and
ignored.**
This module contains the abstract class AttackerStep as well as a few subclasses.
AttackerStep is a generic way to implement optimizers specifically for use with
:class:`robustness.attacker.AttackerModel`. In general, except for w... |
#!/usr/bin/env python3
import sys
try:
from http.server import HTTPServer, BaseHTTPRequestHandler
from urllib.parse import urlparse, parse_qs
from html import escape
except ImportError:
sys.exit('ERROR: It seems like you are not running Python 3. '
'This script only works with Python 3!')
... |
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
from collections import deque
class Solution:
def minDepth(self, root: Optional[TreeNode]) -> int:
if not root:
... |
# -*- coding: utf8 -*-
# Copyright (c) 2017-2018 THL A29 Limited, a Tencent company. 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... |
from enum import IntEnum
class RentIdx(IntEnum):
DEFAULT = ONLY_DEED = RAILROAD_1 = UTILITY_1 = 0
GROUP_COMPLETE_NO_HOUSES = RAILROAD_2 = UTILITY_2 = 1
HOUSE_1 = RAILROAD_3 = 2
HOUSE_2 = RAILROAD_4 = 3
HOUSE_3 = 4
HOUSE_4 = 5
HOTEL = MAX = 6
HOUSE_TO_HOTEL = HOTEL - HOUSE_1 + 1
# Rep... |
# 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 License, Version 2.0 (the
# "License"); you may not u... |
# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applica... |
import logging
import multiprocessing as mp
import multiprocessing.context
import sys
from datetime import datetime, timedelta
from typing import Any, Dict, Optional, Type
from tqdm.auto import tqdm
from mpire.comms import WorkerComms, POISON_PILL
from mpire.dashboard.connection_utils import (DashboardConnectionDetai... |
from pathlib import Path
from MassyTools.bin.mass_spectrum import MassSpectrum
from MassyTools.bin.output import Output
from MassyTools.gui.batch_process_progress_window import BatchProcessProgressWindow
from MassyTools.util.functions import get_peak_list
class BatchProcess(object):
def __init__(self, master):
... |
# https://github.com/xinntao/BasicSR
# flake8: noqa
from .archs import *
from .data import *
from .losses import *
from .metrics import *
from .models import *
from .ops import *
from .test import *
from .train import *
from .utils import *
from .version import __gitsha__, __version__
DATASET_FOLDER="/workspace/datase... |
# MJPEG Video Recording on Movement Example
#
# Note: You will need an SD card to run this example.
#
# You can use your OpenMV Cam to record mjpeg files. You can either feed the
# recorder object JPEG frames or RGB565/Grayscale frames. Once you've finished
# recording a Mjpeg file you can use VLC to play it. If you ar... |
# Copyright (c) 2019 PaddlePaddle 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 app... |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT license.
from .FocalLoss import FocalLoss
from .CRFLoss import CRFLoss
from .Loss import Loss
from torch.nn import CrossEntropyLoss, L1Loss, MSELoss, NLLLoss, PoissonNLLLoss, NLLLoss2d, KLDivLoss, BCELoss, BCEWithLogitsLoss, MarginRank... |
import json
from pathlib import Path as P
from typing import Dict
import _jsonnet
import click
from commodore import __install_dir__
from commodore.config import Config
from commodore.component import Component
from .jsonnet import jsonnet_runner
def _output_dir(work_dir: P, instance: str, path):
"""Compute d... |
# Dmitry Kisler © 2020-present
# www.dkisler.com
from gzip import open as gzip_open
from typing import Tuple, Union, Any
import pickle
import json
def corpus_reader(path: str,
from_memory: bool = False) -> Union[Tuple[str, None],
Tuple[None, st... |
import math
def main():
length = float(input("ceiling length(m): "))
width = float(input("ceiling width(m): "))
liter_per_square_meter = 9
area = length * width
amount_of_paint = math.ceil(area / liter_per_square_meter)
result = (
"\nYou will need to purchase "
+ str(amount_o... |
"""Per-prefix data, mapping each prefix to a dict of locale:name.
Auto-generated file, do not edit by hand.
"""
from ..util import u
# Copyright (C) 2011-2019 The Libphonenumber Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the Licens... |
from enum import Enum
class PenCapStyle(Enum):
"""Styles controlling how pen strokes are capped.
See also http://doc.qt.io/qt-5.9/qt.html#PenCapStyle-enum
"""
SQUARE = 0x10
"""A square cap that extends beyond the end point by half the pen width"""
FLAT = 0x00
"""A square cap that does ... |
from sklearn.model_selection import GroupKFold
import pandas as pd
import cv2
import os
import numpy as np
import ast
import torch
import albumentations
from config import CFG
from torch.utils.data import DataLoader
class RanzcrDataset(object):
def __init__(self, root, df, mode='test', transforms=None, train_anno=... |
# -*- coding: utf-8 -*-
import sys
from watertools.Collect.GEOS.DataAccess import DownloadData
def main(Dir, Vars, Startdate, Enddate, latlim, lonlim, Waitbar = 1, data_type = ["mean"]):
"""
This function downloads GEOS daily data for a given variable, time
interval, and spatial extent.
Keyword argum... |
import os
import sys
sys.path.append('../../vendor/github.com/elastic/beats/libbeat/tests/system')
from beat.beat import TestCase
class BaseTest(TestCase):
@classmethod
def setUpClass(self):
self.beat_name = "microscopebeat"
self.beat_path = os.path.abspath(os.path.join(os.path.dirname(__file... |
import json
import os
count=1
output_path = "output.json"
file_path = "events"
files = os.listdir(file_path)
files.sort()
for file in files:
json_path = file_path + "/" + file
try:
with open(json_path,'r') as fr:
data = json.load(fr)
fr.close()
action = "evebt" + data["... |
import bpy
import sys
sys.path.append("/home/vpoblete/yetzabethg/New Folder/") #DIRECTORIO CON CÓDIGOS DE CONTROL
import handctrl as hc
def detRF(f,m,r): #mov dedos especificos
y1='thumb.01.R'
y2='f_index.01.R'
y3='f_middle.01.R'
y4='f_ring.01.R'
y5='f_pinky.01.R'
if f==0:
... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'qt_main.ui'
#
# Created: Fri Apr 24 13:52:17 2009
# by: PyQt4 UI code generator 4.4.4
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
class Ui_MainWindow(object):
def setupUi(self, MainWindow)... |
"""
__graph_Model_T.py___________________________________________________________
Automatically generated graphical appearance ---> MODIFY DIRECTLY WITH CAUTION
_____________________________________________________________________________
"""
import tkFont
from graphEntity import *
from GraphicalForm import *
f... |
from talon import Context, Module, actions, imgui, settings, ui, app
import os
ctx = Context()
mod = Module()
ctx.matches = r"""
app: windows_power_shell
app: windows_terminal
and win.title: /PowerShell/
"""
user_path = os.path.expanduser("~")
directories_to_remap = {}
directories_to_exclude = {}
@ctx.action_class... |
from django import forms
from django.contrib.auth import get_user_model
from .models import UserAddress
User = get_user_model()
class GuestCheckoutForm(forms.Form):
email = forms.EmailField()
email2 = forms.EmailField(label='Verify Email')
def clean_email2(self):
email = self.cleaned_data.get("email")
email2... |
import os
"""
Load data from a dataset of simply-formatted data
from A to B
from B to A
from A to B
from B to A
from A to B
===
from C to D
from D to C
from C to D
from D to C
from C to D
from D to C
...
`===` lines just separate linear conversations between 2 people.
"""
class LightweightData:
"""
"""
... |
import logging
import os
import re
import sublime
# external dependencies (see dependencies.json)
import jsonschema
import yaml # pyyaml
# This plugin generates a hidden syntax file containing rules for additional
# chainloading commands defined by the user. The syntax is stored in the cache
# directory to avoid the... |
import pytest
import torch
from ludwig.encoders import text_encoders
@pytest.mark.parametrize("use_pretrained", [False])
@pytest.mark.parametrize("reduce_output", [None, "sum"])
@pytest.mark.parametrize("max_sequence_length", [20])
def test_albert_encoder(use_pretrained: bool, reduce_output: str, max_sequence_length... |
from __future__ import print_function, division
import os
import torch
import pandas as pd
#from skimage import io, transform
import cv2
import numpy as np
import random
import torch
from torch.utils.data import Dataset, DataLoader
from torchvision import transforms
import pdb
import math
import os
import imgaug.augme... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
"""Generic configuration for the project."""
import os
# Define the appli... |
# Licensed under a 3-clause BSD style license - see LICENSE.rst
import logging
import numpy as np
from astropy import units as u
from astropy.table import Table
from astropy.visualization import quantity_support
from gammapy.modeling.models import DatasetModels
from gammapy.utils.scripts import make_name, make_path
fro... |
import os,sys
import optparse
import logging
from pbcore.io.align.CmpH5IO import CmpH5Reader
from pbcore.io import openIndexedAlignmentFile
from pbcore.io.BasH5IO import BasH5Reader
import glob
import numpy as np
import logging
import shutil
import pickle
import math
import mbin
import motif_tools
def launch():
opts,... |
#!/usr/bin/python
# Copyright (c) 2020, 2021 Oracle and/or its affiliates.
# This software is made available to you under the terms of the GPL 3.0 license or the Apache 2.0 license.
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
# Apache License v2.0
# See LICENSE.TXT for d... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'w_inline_code.ui'
#
# Created by: PyQt5 UI code generator 5.10.1
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_InlineCodeEditor(object):
def setupUi(self, InlineCodeEditor)... |
#!/usr/bin/env python
# vim:fileencoding=utf-8
# Author: Shinya Suzuki
# Created: 2017-11-16
from application import app
from application.models import init_schema, init_data
import click
@app.cli.command(help="Initialize database")
def initdb():
init_schema()
init_data({"profile": [{"name": "Takuji Yamada",... |
import multiprocessing
import tensorflow as tf
from tensorflow.contrib import estimator
from tensorflow.contrib import lookup
from model import commons
__author__ = 'KKishore'
head = estimator.binary_classification_head()
def parse_csv_row(row):
columns = tf.decode_csv(row, record_defaults=commons.HEADER_DEFAU... |
"""
interact with vector to play complete a knock knock joke
"""
import threading
import anki_vector
from anki_vector.events import Events
from anki_vector.user_intent import UserIntent, UserIntentEvent
def main():
def on_user_intent(robot, event_type, event, done):
user_intent = UserIntent(event)
... |
from flask import Flask, render_template
# import os
app = Flask(__name__)
@app.route('/plot/')
def plot():
from IPython.core.display import display, HTML
from string import Template
import pandas as pd
import json
# d3js = HTML('<script src="d3_jupyter/lib/d3/d3.min.js"></script>')
worldma... |
# 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 ... |
import os
__all__ = [
'list_files_in_directory'
]
def list_files_in_directory(directory, fullpath=False, extensions=[]):
"""This function lists just the files in a directory, not sub-directories.
Args:
directory (str): the directory to search for files.
fullpath (:obj:`bool`, optional): ... |
import logging
import unittest
import os
import pandas as pd
import numpy as np
import h5py
import pandas.util.testing as pandas_testing
import cmapPy.pandasGEXpress.setup_GCToo_logger as setup_logger
import cmapPy.pandasGEXpress.GCToo as GCToo
import cmapPy.pandasGEXpress.parse_gctx as parse_gctx
import cmapPy.pandas... |
from pyspark.sql import SparkSession as spark
#configuração do spark
spark.builder.config('spark.jars.packages','org.mongodb.spark:mongo-spark-connector_2.11:2.2.0' ).getOrCreate()
#conexão com a collection de candidatos
spark_candidatos = spark \
.builder \
.appName("candidatosApp") \
.config("spark.mon... |
class NutritionInfo:
def __init__(self, name, data):
self.foodID = data['foodID']
self.allowed_cols = ['foodname', 'image', 'weight', 'weight_unit', 'calories', 'calfromfat', 'totalfat', 'saturatedfat', 'transfat', 'fat_poly', 'fat_mono', 'cholesterol', 'sodium', 'totalcarbs', 'dietaryfiber', 'sugar... |
# Testing module network_performance.high
import pytest
import ec2_compare.internal.network_performance.high
def test_get_internal_data_network_performance_high_get_instances_list():
assert len(ec2_compare.internal.network_performance.high.get_instances_list()) > 0
def test_get_internal_data_network_performance_high... |
"""xfftest URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: url(r'^$', views.home, name='home')
Class-bas... |
from datetime import datetime
import pprint
import os
import argparse
import numpy as np
import torchvision.models as models
from utils.util import mkdir
from data import FEATURE_DIR
mkdir(FEATURE_DIR)
class Config(object):
def __init__(self, layers, cnf=None):
self.layers = layersGlobalPoolLayer
... |
import os
import numpy as np
import sys
sys.path.append("../")
for model in ['lenet1', 'lenet4', 'lenet5']:
for attack in ['fgsm', 'cw', 'jsma']:
for mu_var in ['gf', 'nai', 'ns', 'ws']:
os.system('CUDA_VISIBLE_DEVICES=0 python retrain_mu_mnist.py --datasets=mnist --attack=' + attack + ' --mode... |
from models.project import Project
import time
class ProjectHelper:
def __init__(self, app):
self.app = app
def open_projects_page(self):
dw = self.app.dw
if not dw.current_url.endswith("/manage_proj_page.php"):
dw.find_element_by_link_text("Manage").click()
d... |
import argparse
import os
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
import torch
import torch.optim as optim
import torchvision.utils as vutils
from swae.distributions import rand_cirlce2d, rand_ring2d, rand_uniform2d
from swae.models.mnist import MNISTAutoencoder
from swae.trainer import... |
# Generic memory-mapped peripheral interface.
#
# Luz micro-controller simulator
# Eli Bendersky (C) 2008-2010
#
class Peripheral(object):
""" An abstract memory-mapped perhipheral interface.
Memory-mapped peripherals are accessed through memory
reads and writes.
The address given to reads... |
"""Route to all channels"""
import requests
from common.config import constants
from server import endpoints, errors
def get(handler, parameters, url_parameters, *ids_parameters):
"""GET method"""
headers = {"Authorization": "Bot " + constants.BOT_TOKEN}
try:
r = requests.get(endpoints.DISCORD_GU... |
"""
OH line fitter
"""
import redshiftedgroup
freq_dict={
'OH12':1.61223e9,
'OH11':1.66540e9,
'OH22':1.66736e9,
'OH21':1.72053e9,
}
OH = redshiftedgroup.redshiftedgroup(freq_dict)
OHfitter = OH.fitter
OHvheightfitter = OH.vheight_fitter |
import os.path
from PIL import Image
from data.base_dataset import BaseDataset, get_transform
from data.image_folder import make_dataset
class SingleDataset(BaseDataset):
def initialize(self, opt):
self.opt = opt
self.root = opt.dataroot
self.dir_A = os.path.join(opt.dataroot)
s... |
import math
sum_squared = 0
squared_sum = 0
for i in range(1, 101):
sum_squared += i**2
squared_sum += i
print(f"Answer: {squared_sum**2 - sum_squared}") |
"""Auto-generated file, do not edit by hand. CG metadata"""
from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata
PHONE_METADATA_CG = PhoneMetadata(id='CG', country_code=None, international_prefix=None,
general_desc=PhoneNumberDesc(national_number_pattern='11\\d', possible_length=(3,)),
toll... |
#
# A minimal settings file that ought to work out of the box for just about
# anyone trying this project. It's deliberately missing most settings to keep
# everything simple.
#
# A real app would have a lot more settings. The only important bit as far as
# django-FAQ is concerned is to have `faq` in INSTALLED_APPS.
#
... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Note: To use the 'upload' functionality of this file, you must:
# $ pip install twine
import io
import os
import sys
from shutil import rmtree
from setuptools import find_packages, setup, Command
# Package meta-data.
NAME = 'mypackage'
DESCRIPTION = 'My short descri... |
import json
import tempfile
import numpy as np
import copy
import time
import torch
import torch._six
from pycocotools.cocoeval import COCOeval
from pycocotools.coco import COCO
import pycocotools.mask as mask_util
from collections import defaultdict
from . import utils
class CocoEvaluator(object):
def __init... |
class Env:
__table = None
_prev = None
def __init__(self, n):
self.__table = {}
self._prev = n
def put(self, w, i):
self.__table[w] = i
def get(self, w):
e = self
while e is not None:
found = e.__table.get(w)
if found is not None:
... |
import FWCore.ParameterSet.Config as cms
process = cms.Process("Sim")
process.load("SimG4CMS.Calo.PythiaMinBias_cfi")
process.load("SimGeneral.HepPDTESSource.pythiapdt_cfi")
process.load("IOMC.EventVertexGenerators.VtxSmearedGauss_cfi")
process.load("Geometry.CMSCommonData.cmsIdealGeometryXML_cfi")
process.load("G... |
directions = ['up', 'down', 'left', 'right']
def get_air_distance_between_two_points(point1, point2):
x1 = point1['x']
y1 = point1['y']
x2 = point2['x']
y2 = point2['y']
distance = pow(pow((x2 - x1), 2) + pow((y2 - y1), 2), 0.5)
return distance
def not_deadly_location_on_board(goal, deadly_l... |
# -*- coding: utf-8 -*-
"""Module containing logic for dns based detectors."""
import socket
import logging
from .base import IPDetector, AF_INET, AF_INET6, AF_UNSPEC
LOG = logging.getLogger(__name__)
def resolve(hostname, family=AF_UNSPEC):
"""
Resolve hostname to one or more IP addresses through the ope... |
from __future__ import absolute_import
import argparse
import json
import sys
from ._reflect import namedAny
from .validators import validator_for
def _namedAnyWithDefault(name):
if "." not in name:
name = "jsonschema." + name
return namedAny(name)
def _json_file(path):
with open(path) as file:... |
import requests
import json
r = requests.get("https://xkcd.com/353/")
print(r)
dir(r)
print(r.text)
r = requests.get("https://imgs.xkcd.com/comics/python.png")
with open("./ignoreland/comic.png", "wb") as f:
f.write(r.content)
print(r.status_code)
print(r.headers)
payload = {"page":2, "count": 25}
r = requests.... |
from dagster import ScheduleDefinition, job, op
@op(config_schema={"param": str})
def do_something(_):
...
config = {"solids": {"do_something": {"config": {"param": "some_val"}}}}
@job(config=config)
def do_it_all():
do_something()
do_it_all_schedule = ScheduleDefinition(job=do_it_all, cron_schedule="0 ... |
"""Install Pycommit"""
import sys
from subprocess import call
if __name__ == "__main__":
call(["git", "pull"])
print("Installing PyCommit.")
with open("pycommit.py") as f:
d = f.readlines()
d = list(map(lambda s: s.replace("<python3_path>", sys.executable), d))
output = "/usr/local/bin/pyc... |
# ----------------------------------------------------------------------
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 3 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be use... |
import os
import sys
sys.path.insert(1, os.path.join(sys.path[0], '../..'))
import grapher_admin.wsgi
from grapher_admin.models import Source
import unidecode
import json
count = 0
all_sources = Source.objects.all()
for each in all_sources:
if 'iea.org' in each.description.lower() or 'iea stat' in each.description... |
import datetime
today = datetime.datetime.now().strftime('%Y-%m-%d')
file_header = """
---
layout: post
title: {title}
date: {date}
preview_img:
description:
published: false
comments: false
---
"""
def validate_file_name(string: str) -> str:
if len(string) < 5:
print('Filename must be longer than 5 sym... |
import os
import multiprocessing
import platform
import sys
import unittest
import vtk, qt, ctk, slicer
from slicer.ScriptedLoadableModule import *
import logging
import SimpleITK as sitk
import sitkUtils
from os.path import expanduser
#
# BabyBrainSegmentation
#
class BabyBrainSegmentation(ScriptedLoadableModule):... |
# -*- coding: utf-8 -*-
from flask import Flask
from flask_session import Session
# from . import models
TEMPLATE_DIR = '../templates'
STATIC_DIR = '../static'
APP_SECRET_KEY = 'kwoc'
APP_CONFIG_SESSION_TYPE = 'filesystem'
APP_DEBUG = True
def create_app():
app = Flask(__name__, template_folder=TEMPLATE_DIR,... |
#!/usr/bin/env python
import rospy
import roslib
import tf
import sys
from std_msgs.msg import Float32
import os.path, time
from geometry_msgs.msg import PoseStamped
def park_android():
file = open('Parking_Info.txt', 'r')
carname = file.read()
value = carname[4]
carname = carname[0:4]
value = fl... |
import logging
from collections import namedtuple
from contextlib import contextmanager
import datetime
import psycopg2 as psycopg2
import util
@contextmanager
def connect_to_database():
# connect
logging.info('Connecting to the mindful database')
conn = psycopg2.connect(host=util.read_config('postgresq... |
from django.contrib.gis.db.backends.base.adapter import WKTAdapter
from django.contrib.gis.db.backends.base.operations import (
BaseSpatialOperations,
)
from django.contrib.gis.db.backends.utils import SpatialOperator
from django.contrib.gis.db.models import GeometryField, aggregates
from django.db.backends.mysql.o... |
import contextlib
@contextlib.contextmanager
def lines():
print('-'*10, 'START', '-'*10)
yield
print('-'*11, 'END', '-'*11)
with lines():
print('inside with block')
print('outside') |
# -*- coding: utf-8 -*-
from odoo import models, fields, api
from odoo.exceptions import UserError
from odoo.tools.translate import _
class LibraryBook(models.Model):
_name = 'library.book'
_description = 'Library Book'
name = fields.Char('Title', required=True)
date_release = fields.Date('Release Dat... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
####
#### Author: Pedro Paulo Balage Filho
#### Version: 1.0
#### Date: 12/03/13
####
from string import punctuation, letters
import re
# Requires Pattern library (http://www.clips.ua.ac.be/pages/pattern)
from pattern.en import tag
from pattern.vector import stem, PO... |
"""
Delta electro code
Md Touhid Islam
Depertment of CSE, HSTU
https://www.facebook.com/Shourov40
"""
import urllib.request as urec
def check_connection():
host = "http://www.google.com"
try:
urec.urlopen(host)
return True
except :
return False
if check_connection():
print("Connected to a network")
else:
... |
#!/usr/bin/env python
"""Tests admin-related functionality"""
import os
from contextlib import contextmanager
from time import sleep
import pytest
import python_pachyderm
from python_pachyderm.experimental.service import auth_proto, identity_proto
from tests import util
# bp_to_pb: OidcConfig -> OIDCConfig
@pyte... |
from datetime import datetime
def str_to_datetime(str_date) -> datetime:
return datetime.strptime(str_date, '%d/%m/%Y')
######################################################################################################################## |
# Copyright 2015 Amazon.com, Inc. or its affiliates. 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. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompa... |
import time
import random
import os, sys
import snn.parameters as params
from traze.bot import Action, BotBase
from traze.client import World
from snn.agent import SNNAgent
class SNNBot(BotBase):
def __init__(self, game, name="SLab-ML Muenchen"):
super(SNNBot, self).__init__(game, name)
self.agen... |
"""Admin for gdrive_sync"""
from django.contrib import admin
from mitol.common.admin import TimestampedModelAdmin
from gdrive_sync.models import DriveApiQueryTracker, DriveFile
class DriveApiQueryTrackerAdmin(TimestampedModelAdmin):
"""DriveApiQueryTracker Admin"""
model = DriveApiQueryTracker
list_dis... |
f = open('I.in','a')
f.write('100000 1\n');
for i in range(0,100000):
f.write(' 1'); |
#### NOTICE: THIS FILE IS AUTOGENERATED
#### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY
#### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES
from swgpy.object import *
def create(kernel):
result = Creature()
result.template = "object/mobile/shared_dressed_mauler_apprentice.iff"
result.attribute_template_id = ... |
from datetime import datetime
from validator.validation.globals import START_TIME, END_TIME
from django.contrib.auth import get_user_model
User = get_user_model()
import django.forms as forms
from validator.forms import YearChoiceField
from validator.models import ValidationRun
## See https://simpleisbetterthancomp... |
# -*- coding: utf-8 -*-
from django.db import models
class PostManager(models.Manager):
def all_published(self):
return self.filter(status_id=self.model.STATUS_PUBLISHED)
def all_draft(self):
return self.filter(status_id=self.model.STATUS_DRAFT)
class CommentManager(models.Manager):
def... |
#ABC078d
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**6) |
# CPU: 0.13 s
from collections import Counter
# Double for loop does not work: TLE
n_nums, divisor = map(int, input().split())
nums = Counter(map(lambda x: int(x) // divisor, input().split()))
print(sum(map(lambda x: x * (x - 1) // 2, nums.values())))
# CPU: 0.13 s
# n_nums, divisor = map(int, input().split())
# nums... |
# -*- coding: utf-8 -*-
# Generated by Django 1.9.4 on 2016-06-16 01:39
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('instaapp', '0003_photo_image'),
]
operations = [
migrations.RemoveField(
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.