content stringlengths 5 1.05M |
|---|
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status
from toys.models import Toy
from toys.serializers import ToySerializer
"""
First version of toys views
"""
# from django.http import HttpResponse
# from django.views.decorators.csrf import csr... |
#Encrypt By Moch Aang Ardiansyah-XD
import marshal
exec(marshal.loads('c\x00\x00\x00\x00\x00\x00\x00\x00\x0c\x00\x00\x00@\x00\x00\x00s\xf7\x03\x00\x00d\x00\x00d\x01\x00l\x00\x00Z\x00\x00y\x10\x00d\x00\x00d\x01\x00l\x01\x00Z\x01\x00Wn#\x00\x04e\x02\x00k\n\x00rA\x00\x01\x01\x01d\x02\x00GHe\x00\x00j\x03\x00d\x03... |
import _thread
import padog
import time
def app_1():
exec(open('web_c.py').read())
def loop():
while True:
padog.mainloop()
_thread.start_new_thread(app_1, ())
loop()
|
from django.conf import settings
from django.db import models
class Announcement(models.Model):
"""For making product announcements"""
class AnnouncementStatus(models.IntegerChoices):
PENDING = 1
ANNOUNCED = 2
status = models.IntegerField(
choices=AnnouncementStatus.choices, defa... |
#!/usr/bin/python
import httplib2
import os
import sys
from apiclient.discovery import build
from oauth2client.client import flow_from_clientsecrets
from oauth2client.file import Storage
from oauth2client.tools import argparser, run_flow
class Youtube_List:
#This method define how to connect with the Youtube AP... |
# Lint as: python3
# Copyright 2018 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 ... |
# 梦想的度假胜地
vacationlands = []
active = True
while active:
vacationland = input('你梦想的度假胜地是哪里?\n')
if vacationland == 'q':
break
vacationlands.append(vacationland)
print('人们梦想的度假胜地有:\n')
print(vacationlands)
|
# -*- coding: utf-8 -*-
# Created on Sat Jun 05 2021
# Last modified on Mon Jun 07 2021
# Copyright (c) CaMOS Development Team. All Rights Reserved.
# Distributed under a MIT License. See LICENSE for more info.
from PyQt5.QtWidgets import QFileDialog
from camos.tasks.runtask import RunTask
from camos.tasks.base impor... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# === This file is part of Calamares - <https://github.com/calamares> ===
#
# Copyright 2014-2015, Philip Müller <philm@manjaro.org>
# Copyright 2014, Teo Mrnjavac <teo@kde.org>
# Copyright 2017, Alf Gaida <agaid@siduction.org>
# Copyright 2019, Adriaan de Groot ... |
# 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 numpy as np
import pytest
from mr_uplift.dataset.data_simulation import get_no_noise_data, get_simple_uplift_data
from mr_uplift.calibrate_uplift import UpliftCalibration
from mr_uplift.erupt import weighted_avg_and_std, erupt,\
get_best_tmts, get_weights
class TestCalibrate(object):
@pytest.fixture(... |
""" Time sensitive split for Git repository data based on Tan et al.'s Online
Change Classification """
__author__ = "Kristian Berg"
__copyright__ = "Copyright (c) 2018 Axis Communications AB"
__license__ = "MIT"
import subprocess
from datetime import datetime, timedelta
from utils import datetime_of_commit
class Git... |
import fs
import shell
fs.init("demo.dsk", 500000)
shell.main("demo.dsk")
|
# -*- coding: utf-8 -*-
"""
"""
from .testcase import TrannyTestCase
from tranny import events
from tranny import plugin
class TestPlugin(plugin.BasePlugin):
def __init__(self):
super(TestPlugin, self).__init__('test')
self.event_handlers = [
events.EventHandler(events.EVENT_TICK, l... |
import argparse
from transform import Transform
def main():
parser = argparse.ArgumentParser(description='Process some parameters.')
parser.add_argument('--data-dir', type=str, default='', help='')
parser.add_argument('--transform-type', type=str, default='nia2labelme', choices=['nia2labelme', 'labelme2ni... |
import boto3
import subprocess
def fetch_dataset(dst, dataset_name):
# fetching the dataset from S3
s3 = boto3.client('s3', region_name="eu-west-3")
s3.download_file("franceioi-algorea", f'datasets/{dataset_name}.sql', dst)
def input_dataset(event):
if isinstance(event, dict) and "queryStringParameter... |
import tensorflow as tf
import config
def CNN():
model = tf.keras.Sequential([
tf.keras.layers.Conv2D(32, (3, 3),
activation='relu',
input_shape=(config.IMG_WIDTH, config.IMG_HEIGHT, config.IMG_CHANNELS)),
tf.keras.layer... |
URL_FUNC_DICT = dict()
def route(url):
def set_func(func):
URL_FUNC_DICT[url] = func
def call_func():
pass
return call_func()
return set_func
@route("/index.html")
def index():
with open("./templates/index.html", "r") as f:
content = f.read()
return ... |
import os
import random
import torch
import torch.backends.cudnn as cudnn
import torchvision.utils as vutils
import torch.nn.functional as F
from config import parse_eval_args
from networks.generator import Generator
args = parse_eval_args()
print(args)
MODEL_DIR = os.path.join("models", args.GAN_TYPE)
MODEL_PATH =... |
#
# micro_doc.py
#
# This source file is part of the FoundationDB open source project
#
# Copyright 2013-2018 Apple Inc. and the FoundationDB project authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of ... |
# coding=utf-8
"""
python 2.7 小说详情界面
json介绍
{
"status": "连载", --小说状态
"update_time": "2018-02-06 17:50:00", -- 更新时间
"description": "一念成沧海,一念化桑田。一念斩千魔,一念诛万仙。唯我念……永恒", --小说描述、简介
"chapters": [ --所有章节
{
"url": "5386269", --章节id、章节地址
"tit... |
from simple_image_download import simple_image_download as sim
response = sim.simple_image_download
response().download('harrypotter', 60)
#print(response().urls('batmanjoker', 45))
#response().download('batmanjoker', 5,extensions={'.jpg'})
#print(response().urls('batmanjoker', 5,extensions={'.jpg'})) |
import argparse
import attr
import habitat
import numpy as np
from habitat import logger
from habitat.tasks.nav.shortest_path_follower import ShortestPathFollower
from habitat.sims.habitat_simulator.actions import HabitatSimActions
from habitat_sim.utils import viz_utils as vut
from habitat_sim.utils.common import qu... |
from django.shortcuts import render, redirect
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework.renderers import TemplateHTMLRenderer
from port.models import Movie, Container, Wishlist
from port.serializers import WishlistSeria... |
#!/usr/bin/env python3
# The MIT License (MIT)
#
# Copyright (c) 2018 Sunaina Pai
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the ri... |
# Input lower case
# Output upper case
# cap current index
# if index -1 is space cap current
# append
#return cap selection
#print cap format
def cap_letter(str):
cap_words = str[0].upper()
for i in range(1, len(str)):
if (str[i-1] == " "):
cap_words += str[i].upper()
else:
... |
import pathlib
import pytest
from spinta.testing.cli import SpintaCliRunner
from spinta.testing.utils import create_manifest_files
from spinta.testing.utils import update_manifest_files
from spinta.testing.utils import read_manifest_files
from spinta.testing.utils import readable_manifest_files
@pytest.fixture()
de... |
import discord
from django.db import models
from django.core.validators import RegexValidator, MinValueValidator
from web.apps.users.models import DiscordUser
from web.apps.investigations.models import Hint
emoji_validator = RegexValidator(
regex='^:\w{2,}:$',
message='Please enter an emoji like :this:')
cla... |
from server import app
import unittest
import json
class FlaskServerTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
pass
@classmethod
def tearDownClass(cls):
pass
def setUp(self):
# creates a test client
self.app = app.test_client()
self.app.t... |
import pytest
from wapps.metadata import Metadata
@pytest.mark.django_db
def test_page_meta(jinja_context):
ctx = jinja_context()
assert 'page_meta' in ctx
assert isinstance(ctx['page_meta'](ctx), Metadata)
|
#!/usr/bin/env python
#
# This file is part of pysmi software.
#
# Copyright (c) 2015-2020, Ilya Etingof <etingof@gmail.com>
# License: http://snmplabs.com/pysmi/license.html
#
"""SNMP SMI/MIB Parser
A pure-Python implementation of SNMP/SMI MIB parsing and
conversion library.
"""
import os
import sys
classifiers = "... |
# parsetab.py
# This file is automatically generated. Do not edit.
# pylint: disable=W,C,R
_tabversion = '3.10'
_lr_method = 'LALR'
_lr_signature = 'leftPLUSMINUSleftTIMESDIVIDEleftEXPrightUMINUSCOMMA DIVIDE EQUALS EXP FLOAT INTEGER LPAREN MINUS NAME PLUS RPAREN TIMESstatement : NAME EQUALS atom\n arglist : a... |
from flask import Flask, Blueprint, get_flashed_messages, render_template
from waitress import serve
from conf import Config
from tool.typing import *
from sql.db import DB
from . import views as views
app: Optional["App"] = None
class App:
app: Optional["App"] = None
base = Blueprint("base", __name__)
... |
from ast import Pass
import re
import csv
import json
import sys
import numpy as np
def read_file(path):
try:
with open(path, "r", encoding='utf-8') as f:
if path.endswith('.csv'):
json_list = []
for row in csv.DictReader(f):
json_list.append(r... |
import sys
def timestamp(d=None):
import datetime
import time
return int(time.mktime(d.timetuple()) * 1000) if d else int(time.time() * 1000)
sys.modules[__name__] = timestamp
|
# -*- coding: utf-8 -*-
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""Debug plugin
"""
from __future__ import print_function, division, unicode_literals, absolute_import
import networkx as nx
from .base import PluginBase, logger
class DebugPlugin... |
import constants
from ecs.components.namecomponent import NameComponent
from ecs.components.randomnumbercomponent import RandomNumberComponent
from ecs.components.visiblecomponent import VisibleComponent
from ecs.systems.panels.panel import Panel
from helper_functions import get_combat_result, combat_result_to_color
... |
from http.server import BaseHTTPRequestHandler, HTTPServer
import socketserver
from sys import argv
class S(BaseHTTPRequestHandler):
def _set_headers(self):
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
def do_GET(self):
self._set_head... |
from pathlib import Path
import pytest
from ids_validator.checks.generic import TypeChecker
from ids_validator.ids_node import Node
from ids_validator.utils import read_schema, Log
UNIT_TEST_FILES = Path("__tests__/unit/generic/files/type_check")
fname_to_expected = {
"invalid_array_type_no_items.json": [
... |
'''
Manage git repositories and configuration.
'''
from __future__ import unicode_literals
import re
from pyinfra import logger
from pyinfra.api import operation, OperationError
from pyinfra.facts.files import Directory
from pyinfra.facts.git import GitBranch, GitConfig, GitTrackingBranch
from . import files, ssh
f... |
from mod_pywebsocket import common
from mod_pywebsocket import stream
def web_socket_do_extra_handshake(request):
pass
def web_socket_transfer_data(request):
# '\xff' will never appear in UTF-8 encoded data.
payload = b'This text should be ignored. \xff'
request.connection.write(
stream.crea... |
from common.util.random import SimpleRandom
from rte.riedel.fever_features import TermFrequencyFeatureFunction
import os
class SentenceLevelTermFrequencyFeatureFunction(TermFrequencyFeatureFunction):
def __init__(self,doc_db,lim_unigram=5000,naming=None):
super().__init__(doc_db,lim_unigram,naming=naming)... |
#!/usr/bin/env python3
# Programm : depot.py
# Version : 1.00
# SW-Stand : 21.05.2022
# Autor : Kanopus1958
# Beschreibung : Aktueller Depotbestand
import os
import requests
from bs4 import BeautifulSoup
import time
from rwm_steuerung import color as c
from rwm_mod01 import show_header, aktuelles_... |
from setuptools import find_packages, setup
with open("README.md", "r") as fh:
long_description = fh.read()
setup(
name="theme_camp_manager",
version="0.1.2",
author="Chris Filkins",
author_email="christopher.filkins@gmail.com",
description="Camp Manager Project for Theme Camps at Burning Man"... |
# demo_data
# 2018.12.9 create by David Yi
# 2019.1.6 edit by David Yi, #187 #188 修改 IdCard 和 CardBin 两个类,对这里有修改
from fishbase.fish_data import *
print('--- fish_data get_idcard_checkcode demo ---')
# id number
id1 = '32012419870101001'
print(id1, IdCard.get_checkcode(id1)[1])
# id number
id2 = '13052219840731647'
... |
import attr
from attr import attrib
from alfasim_sdk._internal.validators import non_empty_str
@attr.s(kw_only=True)
class ErrorMessage:
"""
ErrorMessage allows the plugin to display a message over the status monitor, and signalize to the application to block
the simulation until the issue is fixed.
... |
# (C) Crown Copyright, Met Office. All rights reserved.
#
# This file is part of ocean_error_covs and is released under the BSD 3-Clause license.
# See LICENSE in the root of the repository for full licensing details.
#######################################################################
import numpy as np
from netCDF... |
import asyncio
from aiohttp import ClientSession, WSMsgType
from aiohttp.web import WebSocketResponse, Response
class Proxy:
def __init__(self, app, loop):
self.app = app
self.loop = loop
self.app.router.add_route(
'*', '/{path:.*}', self.handle_proxy_request)
async def... |
from django.db import models
class Task(models.Model):
title = models.CharField(max_length=200)
is_completed = models.BooleanField(default=False)
owner = models.ForeignKey("auth.User", null=True, blank=True, on_delete=models.CASCADE)
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
import os
from optparse import OptionParser, Option
from builders.util import shell_call, color_print
__author__ = "Mike Belov"
__copyright__ = "Copyright (C) Nginx, Inc. All rights reserved."
__credits__ = ["Mike Belov", "Andrei Belov", "Ivan Poluyanov", "Oleg Mamontov", "... |
#!/usr/bin/env python
from netmiko import ConnectHandler
from getpass import getpass
device1 = {
'host': 'cisco3.lasthop.io',
'username': 'pyclass',
'password': getpass(),
'device_type': 'cisco_ios',
'session_log': 'my_session_log.txt'
}
net_connect = ConnectHandler(**device1)
output = net_c... |
# Libraries
import datetime
import decimal
import json
import os
import re
import time
import urllib
import chalice
import psycopg2
import psycopg2.extras
# Default query parameters
DEFAULT_PAGE = 1
DEFAULT_LIMIT, MAX_LIMIT = 30, 200
DEFAULT_ASSET_ID = ""
DEFAULT_TXN_TYPE = ("Standard", "Contract", "Internal")
DEFAUL... |
import io
import os
import gzip
import numpy as np
import sqlalchemy as sa
from sqlalchemy.orm import deferred
from sqlalchemy.dialects import postgresql as psql
from sqlalchemy.orm import relationship
from pathlib import Path
from .core import Base
from .constants import CUTOUT_SIZE
from .archive import URL_PREFIX,... |
from django.db import models
from django.utils.translation import ugettext_lazy as _
from django.conf import settings
from utils.models import (CreationModificationDateMixin,
object_relation_mixin_factory)
class Like(CreationModificationDateMixin,
object_relation_mixin_factory(is... |
# -*- coding: utf-8 -*-
################################################################################
# Copyright (c) 2018 McAfee LLC - All Rights Reserved.
################################################################################
"""
Contains the :class:`DxlClient` class, which is responsible for all
commun... |
# import time
# import numpy as np
# a = np.array([1, 0, 0, 1, 1])
# b = np.array([1, 1, 0, 1, 1])
# print('a', a)
# print('b', b)
# print(np.sum(a == b))
# print(time.localtime())
# import os
# try:
# from src.Model.find_file_name import get_filenames
# except ModuleNotFoundError:
# from Model.find_file_n... |
from django import forms
from .models import Video
class VideoForm(forms.ModelForm):
class Meta:
model = Video
fields = (
'owner',
'videoNumber',
'delay',
'face',
'speech',
'chat',
'youtube',
'date',... |
from pyretic.lib.corelib import *
from pyretic.core import packet
from pyretic.lib.query import *
ip_h1 = IPAddr('10.0.0.1')
ip_h2 = IPAddr('10.0.0.2')
ip_mon = IPAddr('10.0.0.3')
ip_srv = IPAddr('10.0.0.4')
ip_inet = IPAddr('10.0.0.5')
def firewall():
# broadcast arp request and arp reply
arp = match(ethtype... |
# Functions that can generate attribute values.
#
# These are functions that can be used in the GenerateFuncAttribute() class
# (see module generator.py). They generate values according to some internal
# functionality.
#
# The requirement of any such functions are:
# 1) that it must return a string
# 2) it can... |
#!/usr/bin/python3
import sys
import json
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.svm import LinearSVC
import pickle
class Payload:
def __init__(self, svm, vect):
self.svm = svm
self.vect = vect
def use(self, comm):
return self.svm.predict(self.vect.tr... |
import mock
import unittest
from exporters.records.base_record import BaseRecord
from exporters.writers.gdrive_writer import GDriveWriter
from exporters.writers.base_writer import InconsistentWriteState
from .utils import meta
class GStorageWriterTest(unittest.TestCase):
def get_items_to_write(self):
da... |
# Generated by Django 3.1.2 on 2021-03-25 10:31
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
("country", "0027_redflag_implemented"),
]
operations = [
migrations.AddField(
model_name="tender... |
from . import core
from .core import *
from . import connections
from . import utils
|
#
# PySNMP MIB module BAY-STACK-LLDP-EXT-DOT3-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/BAY-STACK-LLDP-EXT-DOT3-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 17:18:59 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python versio... |
#!/usr/bin/env python
"""
=======
textext
=======
:Author: Pauli Virtanen <pav@iki.fi>
:Date: 2008-04-26
:License: BSD
:modified: Fernando Moura
:Date: 2016
# All GTK and TK bits were removed
# Changes: line 67-68: added a few variables to control debug mode
# Changes: line 944: changed order of programs
# Changes: ... |
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import absolute_import, print_function
import os
import pkgutil
import sys
from distutils import sysconfig
from site import USER_SITE
import pkg_resources
from pkg_resour... |
print('\n'.join([input()[::-1] for _ in range(4)][::-1]))
|
#! /user/bin/evn python
# -*- coding:utf8 -*-
import os
import re
import codecs
import numpy as np
import gensim
from numpy import linalg
import operator
import nltk
import json
from ir.config import Config
from ir.search import Search
def clean_str(string):
"""
Tokenization/string cleaning for all datasets e... |
import tensorflow as tf
import os
import contractions
import tensorflow as tf
import pandas as pd
import numpy as np
import time
import rich
from rich.progress import track
import spacy
class LuongAttention(tf.keras.layers.Layer):
def __init__(self, params):
super(LuongAttention, self).__init__()
... |
import cv2
import pyttsx3
import threading
from playsound import playsound
from datetime import datetime
# This funtion plays the audio message
def thread_voice_alert():
# engine.say("Object Detected")
# engine.runAndWait()
playsound('./suffer.mp3')
baseline_image = None
status_list = [None, None]
video ... |
class ProductStatus:
ON = 1
OFF = 2
DELETED = 0
class ProductGroupDefault:
YES = 1
NO = 0
class ProductOperationType:
ON = 1 # 上架
OFF = 2 # 下架 |
print("Solve 4 * 100 - 54: ")
answer = int(input())
print("Correct answer is ", end="")
print(4 * 100 - 54)
print("Your answer is", answer)
|
'''
Created on 18-Dec-2015
@author: Suman Saurabh
'''
import os
from tcapi.TrueCallerApp.caller import HealthCheck
from tcapi.TrueCallerApp.modules.TrueCallerInit.TrueCaller import TrueCaller
from tcapi.TrueCallerApp.caller import Caller
from flask import Flask
from flask_restful import Api
app = Flask(__name__)... |
import os.path
from depthaware.data.base_dataset import *
from PIL import Image
import time
#label_weight = [0.005770029194127712, 0.012971614093310078, 0.03362765598112945, 0.1221253676849356, 0.06859890961300749, 0.15823995906267385, 0.09602253559800432, 0.12810205801896177, 0.1718342979655409, 0.2830090542974214, ... |
import unittest
import time
from sonmanobase.messaging import ManoBrokerConnection, ManoBrokerRequestResponseConnection
# TODO the active waiting for messages should be replaced by threading.Event() functionality
class TestManoBrokerConnection(unittest.TestCase):
"""
Test basic broker interactions.
"""
... |
# Copyright 2021 Google 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 in writing, ... |
# -*- coding: utf-8 -*-
from PyQt5 import QtWidgets # type: ignore
from typing import Union, TYPE_CHECKING
if TYPE_CHECKING:
from .qgroupbox import QGroupBox # noqa: F401
from .qwidget import QWidget # noqa: F401
class QFrame(QtWidgets.QFrame):
_line_width = None
def __init__(self, parent: Union[... |
# Created by Egor Kostan.
# GitHub: https://github.com/ikostan
# LinkedIn: https://www.linkedin.com/in/egor-kostan/
import time
import allure
from tests.config import Config
from utils.open_web_browser import open_web_browser
from page_object_models.admin_page_model import AdminPageModel
from expected_results.page... |
"""Module for graphing and visulizing data"""
|
"""
ping.py
Generates fun names using the textgen module.
Created By:
- Bjorn Neergaard <https://github.com/neersighted>
Modified By:
- Luke Rogers <https://github.com/lukeroge>
License:
GPL v3
"""
import os
import re
import subprocess
from cloudbot import hook
unix_ping_regex = re.compile(r"(\d+.\d+... |
# Bee Movie Automator
#Import all the stuff
import cfg, time
#Second line of import statements. These may need to be installed
import asyncio, discord
#Client intialization stuff
client = discord.Client()
print("Setup finished")
@client.event
@asyncio.coroutine
def on_message(message):
print(time.strftime(... |
from setuptools import setup
setup(
name='carla_env',
version='',
packages=['carla_env'],
url='',
license='',
author='Jan Bieser',
author_email='uoqox@student.kit.edu',
description=''
)
|
# -*- coding: utf-8 -*-
import telebot
from base_dir import config
import os
import time
import random
from base_dir import utils
from base_dir.SQLighter import SQLighter
from telebot import types
bot = telebot.TeleBot(config.token)
"""
@bot.message_handler(content_types=["text"])
def repeat_all_messages(message):
... |
# Copyright 2020 Huawei Technologies Co., Ltd
#
# 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... |
#! /bin/python
import os
import time
import sys
os.environ["SDL_VIDEODRIVER"] = "dummy"
from evdev import InputDevice, categorize, ecodes
import pygame
if __name__ == '__main__':
# Need to pre-init the mixer or the delay between start() and the
# sound is large, approx. 400ms.
# See: http://stackoverflow.com... |
#program reads 5 integers but stops right when the first negative integer is met.
#using for else loop
for i in range(5):
i = int(input())
if i < 0:
print("Negative value of i met")
break
else:
print("No negative value of i were met")
|
import mrjob
from mrjob.job import MRJob
import re
from itertools import islice, izip
import itertools
WORD_RE = re.compile(r'[a-zA-Z]+')
class BigramCount(MRJob):
OUTPUT_PROTOCOL = mrjob.protocol.RawProtocol
def mapper(self, _, line):
words = WORD_RE.findall(line)
for i in izip(words, islice(words, 1, ... |
from comvex.utils import ConfigBase
class gMLPConfig(ConfigBase):
def __init__(
self,
image_channel: int,
image_size: int,
patch_size: int,
depth: int,
dim: int,
ffn_dim: int,
num_classes: int,
pred_act_fnc_name: str = "ReLU",
attenti... |
# SolveLinearSystem.py
# Code to read A and b
# Then solve Ax = b for x by Gaussian elimination with back substitution
#
##########
def linearsolver(A,b):
n = len(A)
# M = A #this is object to object equivalence
# copy A into M element by element
M=[[0.0 for jcol in range(n)]for irow in range(n)]
for ir... |
# -*- coding: utf-8 -*-
import scrapy
import time
import re
import urlparse
from bs4 import BeautifulSoup
from scrapy4eng.items.scrapydoc import ScrapyDocItem
class ScrapydocSpider(scrapy.Spider):
name = 'scrapydoc'
allowed_domains = ['docs.scrapy.org']
start_urls = ['https://docs.scrapy.org/en/latest']
... |
# boost.py
#
# Author : James Mnatzaganian
# Contact : http://techtorials.me
# Organization : NanoComputing Research Lab - Rochester Institute of
# Technology
# Website : https://www.rit.edu/kgcoe/nanolab/
# Date Created : 10/12/15
#
# Description : Boost experimentations.
# Pyt... |
import os
import sys
"""
As before the output allways follows the same pattern, as we are only
interested in the input variables values so, we can just read for the line with
INPUT and take the following value.
"""
def get_vars():
f = open("tmp_vars.txt", 'r')
for line in f:
if "INPUT" in line:
... |
def build_reagent_label_category(lims_reagent_label) -> dict:
"""Build reagent label ctegory document from lims data."""
mongo_reagent_label = {
'_id': lims_reagent_label.name,
'sequence': lims_reagent_label.sequence,
'category': lims_reagent_label.category,
'name': lims_reagent... |
from dearpygui import core as dpg
from dearpygui import simple
import util
class TabTracker(object):
def __init__(self, tabs=[]):
self.tabs = TabList(tabs)
def add_tab(self, tab):
if type(tab) == Tab:
self.tabs.append(tab)
else:
raise Exception("Input provided... |
from django.shortcuts import get_object_or_404
from rest_framework.generics import ListAPIView
from announcement.models import Announcement
from announcement.serializer import AnnouncementSerializer
from challenge.models import Challenge
class AnnouncementAPI(ListAPIView):
serializer_class = AnnouncementSerializ... |
""" Metrics to asses the power profile. """
# Authors: Guillaume Lemaitre <g.lemaitre58@gmail.com>
# Cedric Lemaitre
# License: BSD 3 clause
from __future__ import division
import pandas as pd
import numpy as np
from sklearn.linear_model import LinearRegression
SAMPLING_WKO = pd.TimedeltaIndex(
['00:... |
# !/usr/bin/env python3
# -*- encoding: utf-8 -*-
"""
ERP+
"""
__author__ = 'António Anacleto'
__credits__ = []
__version__ = "1.0"
__maintainer__ = "António Anacleto"
__status__ = "Development"
__model_name__ = 'residencia.Residencia'
import auth, base_models
from orm import *
from form import *
class Residencia(Mode... |
from redis import Redis
redis = Redis()
from models import Base, User, Post
from flask import Flask, jsonify, request, url_for, abort, g
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship, sessionmaker
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_s... |
from tests import unittest
import os
from mock import MagicMock, patch, Mock
from aliyunsdkcore.acs_exception.exceptions import ClientException, ServerException
from aliyunsdkcore.auth.credentials import RsaKeyPairCredential
from aliyunsdkcore.auth.signers.rsa_key_pair_signer import RsaKeyPairSigner, GetSessionAkRequ... |
from necrobot.botbase.commandtype import CommandType
from necrobot.util.necrodancer import seedgen
MAX_NUM_SEEDS_TO_GENERATE = 20
class RandomSeed(CommandType):
def __init__(self, bot_channel):
CommandType.__init__(self, bot_channel, 'randomseed')
self.help_text = "Get a randomly generated seed (... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.