content stringlengths 5 1.05M |
|---|
#!/usr/bin/python
'''
TOPOLOGY USED IN NETSOFT 2015 TEST
Emulation of l3-scenario for the OpenStack case. Nodes:
- Host VM-User1: one interface
- Host VM-User2: one interface
- Host DPI: 2 interfaces
- Host WAN Accelerator (WANA): 2 interfaces (eth0 connected to s1 and eth1 connected to s2)
- Host TC: 2 interfaces ... |
#!/usr/bin/env python
import rospy
import requests
from std_msgs.msg import String
import random
from geometry_msgs.msg import Twist
import xavier_command
def talker():
initi = True
pub = rospy.Publisher('command', String, queue_size=10)
rospy.init_node('letterTalkerS', anonymous=True)
rate = rospy.Rat... |
#!/usr/bin/env python3
# vim: fileencoding=utf-8 expandtab ts=4 nospell
# SPDX-FileCopyrightText: 2020-2021 Benedict Harcourt <ben.harcourt@harcourtprogramming.co.uk>
#
# SPDX-License-Identifier: BSD-2-Clause
"""
Abstract class and Model implementation for basic Tables in the ORM system.
Tables store an array of fie... |
TEXT = b"""
Overhead the albatross hangs motionless upon the air
And deep beneath the rolling waves in labyrinths of coral caves
The echo of a distant tide
Comes willowing across the sand
And everything is green and submarine
And no one showed us to the land
And no one knows the wheres or whys
But something stirs and ... |
from django.conf import settings
from django.db import models
from django.utils import timezone
class CardPlacementUserManager(models.Manager):
def all(self, user):
"""Returns all card placements belonging to the user
"""
return self.filter(user=user).all()
def get(self, user, *args, ... |
import audiolibrix
import hmac
import requests
from hashlib import sha256
class Auth:
def __init__(self):
if (
not isinstance(audiolibrix.api_credentials, tuple)
or len(audiolibrix.api_credentials) != 2
):
raise audiolibrix.error.APIError(
"Inva... |
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: dc.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection... |
# -*- coding: utf-8 -*-
"""
@author: pattenh1
"""
import numpy as np
import cv2
import os
import SimpleITK as sitk
#import pandas as pd
import time
import datetime
import xml.etree.ElementTree as ET
import xml.dom.minidom
import pkg_resources
class RegImage(object):
'''
Container class... |
from flask import g
class LineItem:
def __init__(self, username, order_id, menu_item_id):
self.username = username
self.order_id = order_id
self.menu_item_id = menu_item_id
@classmethod
def create(cls, username, order_id, menu_item_id):
query = """
INSERT INTO
... |
from django.shortcuts import render
from django.views.generic import TemplateView
# Top page
class IndexView(TemplateView):
template_name = "index.html"
def get_context_data(self):
ctxt = super().get_context_data()
ctxt["username"] = "NAME"
return ctxt
# About page
class AboutView(Te... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Licensed to Cloudera, Inc. under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. Cloudera, Inc. licenses this file
# to you under the Apache License, Version 2.0 (... |
import unittest
import asyncio
import asynctest
import asynctest.mock as amock
from opsdroid.__main__ import configure_lang
from opsdroid.core import OpsDroid
from opsdroid.connector import Connector
from opsdroid.__main__ import configure_lang
class TestConnectorBaseClass(unittest.TestCase):
"""Test the opsdro... |
#Rule 26 - In contact data file, the VOICE column must not contain any phone number or email ID
def no_phone_url_in_voice(fle, fleName, target):
import re
import os
import sys
import json
import openpyxl
import pandas as pd
from pandas import ExcelWriter
from pandas import ExcelFile
from dateutil.parser import... |
import os
from parallelm.pipeline import json_fields
def main_component_module(comp_desc):
main_module = os.path.splitext(comp_desc[json_fields.COMPONENT_DESC_PROGRAM_FIELD])[0]
return comp_desc[json_fields.COMPONENT_DESC_PACKAGE_FIELD] + "." + main_module
def assemble_cmdline_from_args(input_args):
cm... |
from common.commands import *
# Constants for getting number of cycles for special cases
REGULAR = 0 # For commands that performs always for the same number of cycles
REGISTER = 0 # For commands that processes registers
MEMORY = 1 # For commands that processes memory cell
NEXT_CMD = 0 # For return and call comma... |
# -*- coding: utf-8 -*-
import jwt
from jwt import InvalidTokenError
from datetime import datetime, timedelta
from rust.core.exceptions import BusinessError
import settings
SECRET = 'aSsJKgdAH2Dkaj1shd4ahsh' if not hasattr(settings, 'JWT_SECRET') else settings.JWT_SECRET
CURRENT_TOKEN = None
class JWTService(objec... |
# coding: utf-8
from __future__ import print_function
import time
from twisted.internet import defer
from twisted.internet import reactor
import txredisapi as redis
HOST = 'localhost'
PORT = 6379
N = 1000
@defer.inlineCallbacks
def test_setget():
key = 'test'
conn = yield redis.Connection(HOST, PORT)
s... |
from flask import Flask, request, jsonify
from scraper import run
app = Flask(__name__)
app.config["DEBUG"] = True
items = []
@app.route('/news-items', methods=['GET'])
def api_all():
global items
if not items:
items = run()
response = jsonify(items)
response.headers.add("Access-Control-Allow... |
# -*- coding: utf-8 -*-
import os
import platform
import re
import subprocess
import sys
from distutils.version import LooseVersion
from setuptools import setup, find_packages, Extension
from setuptools.command.build_ext import build_ext
def fix_includes_hack():
# IDK what happened to the GitHub Actions containe... |
#!/usr/bin/env python
# Copyright (C) 2006 by Johannes Zellner, <johannes@zellner.org>
# modified by mac@calmar.ws to fit my output needs
import sys
import os
def echo(msg):
os.system('echo -n "' + str(msg) + '"')
def out(n):
os.system("tput setab " + str(n) + "; echo -n " + ("\"% 4d\"" % n))
os.system("... |
"""
A module of deep feature selection based on multilayer perceptrons.
This module applies a deep structure with not too many hidden layers.
Thus, stochastic gradient descent (back-prop) is used in optimization.
Copyright (c) 2008-2013, Theano Development Team All rights reserved.
Yifeng Li
CMMT, UBC, Vancouver
Sep... |
import requests
import requests_ftp
import re
import sys
import urllib3
urllib3.disable_warnings()
# NOTE: urllib warnings are disabled because https certificate validation is disabled.
# In general, this is not a secure practice; see more here: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings... |
#import numpy as np
# library of patterns
|
import os
import csv
import time
from flask_script import Command, Option
from cnf.settings import ROOT_PATH
class Import(Command):
option_list = (
Option('--source', '-s', dest='source'),
Option('--batch', '-b', dest='batch', default=1000),
)
def csv(self, filename):
_f = open(o... |
"""Config file"""
DATABASE_URI = "postgresql://username.password@port/database" |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('jssmanifests', '0019_auto_20150618_1543')... |
"""An object-oriented interface to .netrc files."""
# Module and documentation by Eric S. Raymond, 21 Dec 1998
from __future__ import with_statement
import os, shlex
__all__ = ["netrc", "NetrcParseError"]
class NetrcParseError(Exception):
"""Exception raised on syntax errors in the .netrc file."""
def __in... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Ivar Vargas Belizario
# Copyright (c) 2021
# E-mail: ivar@usp.br
import tornado.ioloop
import tornado.web
import tornado.httpserver
import ujson
import glob
import os
import time
import sys
import pandas as pd
import numpy as np
import os.path
import math
impo... |
import requests
from celery_app.utils.utils import insert_vuln_db
from celery_app.config.config import web_port_short
#Apache Struts2-045 ่ฟ็จไปฃ็ ๆง่ก๏ผCVE-2017-5638๏ผ
plugin_id=42
default_port_list=web_port_short
def check(host, port=80):
scheme = 'https' if '443' in str(port) else 'http'
target = '{}://{}:{}'.for... |
import os
import tempfile
import pytest
from reminders import app
@pytest.fixture
def client():
db_fd, app.config['DATABASE'] = tempfile.mkstemp()
app.config['TESTING'] = True
with app.test_client() as client:
yield client
os.close(db_fd)
os.unlink(app.config['DATABASE'])
def test_bas... |
from .changelog import Changelog
from .types import ChangelogType
from .changelog_spec import ConventionalCommitChangelog
__all__ = (Changelog, ConventionalCommitChangelog, ChangelogType)
|
# -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2016-09-04 06:31
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('api', '0002_auto_20160904_1201'),
]
operations = [
migrations.RenameModel(
... |
import os
import configparser
import pytest
from rjm.runners import funcx_slurm_runner
from rjm.errors import RemoteJobRunnerError
@pytest.fixture
def configobj():
config = configparser.ConfigParser()
config["FUNCX"] = {
"remote_endpoint": "abcdefg",
}
config["SLURM"] = {
"slurm_scr... |
from dagster import (
Output,
InputDefinition,
OutputDefinition,
solid,
pipeline,
List as DagsterList,
String,
)
from dagster_aws.s3 import S3Coordinate
from os import walk
from dotenv import load_dotenv
import boto3
import ntpath
import os
load_dotenv()
@solid(
name="uploadObjectToS3... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Generated from FHIR 4.0.1-9346c8cc45 (http://hl7.org/fhir/StructureDefinition/BiologicallyDerivedProduct) on 2020-02-03.
# 2020, SMART Health IT.
import sys
from dataclasses import dataclass, field
from typing import ClassVar, Optional, List
from .backboneelement imp... |
import logging
from eposfederator.libs.base.requesthandler import RequestHandler
from eposfederator.libs import downloader, serviceindex
from eposfederator.libs.base.schema import Schema
import tornado.iostream
from marshmallow import fields, validate
from webargs.tornadoparser import use_args
from shapely import geome... |
# @Title: ๆๅฐไป1ๅฐๆๅคง็nไฝๆฐ (ๆๅฐไป1ๅฐๆๅคง็nไฝๆฐ LCOF)
# @Author: 18015528893
# @Date: 2021-01-17 18:57:24
# @Runtime: 44 ms
# @Memory: 20.2 MB
class Solution:
def printNumbers(self, n: int) -> List[int]:
return list(range(1, 10 ** n))
|
from events.models import Event, SourceArchive
from dateutil.rrule import *
from common.utils import set_eastern_timezone
import icalendar
import datetime
def process_ical(source):
print("Processing ical: " + source.name)
if source.name == "OPM Holidays":
print("Deleting existing OPM Holidays")
... |
# Uses python3
def edit_distance(seq_a, seq_b):
'''Compute the edit distance between two strings.
The edit distance between two strings is the minimum number of operations
(insertions, deletions, and substitutions of symbols) to transform
one string into another. It is a measure of similarity of two st... |
from __future__ import absolute_import, division, print_function
from stripe import util
from stripe.api_resources.abstract import UpdateableAPIResource
from stripe.api_resources.transfer import Transfer
from stripe.six.moves.urllib.parse import quote_plus
class Reversal(UpdateableAPIResource):
OBJECT_NAME = "tr... |
"""
:platform: Unix, Windows
:synopsis: This is a minimal examples of the provided class StaircaseGenerator
.. moduleauthor:: Aron Heck
"""
from staircase_number_generator import StaircaseGenerator
def main():
"""
Asks for lower and upper bound then print staircase numbers and reset them and print th... |
from django.views.generic import ListView, DetailView, CreateView, \
DeleteView, UpdateView, \
ArchiveIndexView, DateDetailView, \
DayArchiveView, MonthArchiveView, \
TodayArchiveView, Wee... |
from djitellopy import tello
from time import sleep
import cv2
skynet = tello.Tello()
skynet.connect()
print(skynet.get_battery())
skynet.streamon()
while True:
img = skynet.get_frame_read().frame
#img = cv2.resize(img, (360, 240))
cv2.imshow("Image", img)
cv2.waitKey(1) |
import time
import math
import sys
def BranchAndBound(graph, vertices, cutoff_time, num_edge):
start_time = time.time()
current_best = vertices
uppper_bound = len(graph)
trace = []
# the large graph will lead recursion error: maximum recursion depth exceeded in comparison
# so we need to set ... |
import os
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from tqdm import tqdm
from collections import Counter
from geo.data_paths import train
from geo.data_paths import species_occurences
from geo.preprocessing.preprocessing import create_trainset
def _create():
create_trainset()
csv... |
import torch
import torch.cuda
import torch.nn as nn
import torch.optim as optim
import random
import numpy as np
import sklearn.metrics
import time
import logging
import json
from src.utils.utils import print_progessbar
class LeNet5_trainer:
"""
Trainer of LeNet5 archiecture.
"""
def __init__(self, n... |
from django.apps import AppConfig
from django.utils.importlib import import_module
class OffersConfig(AppConfig):
name = 'commercia.offers'
verbose_name = "Offers"
def ready(self):
import_module('commercia.offers.collections')
import_module('commercia.offers.signals') |
from datetime import datetime
import pytz
import settings
from ical_importer import iCalParser
if __name__ == "__main__":
""" Script that instantiates an iCalParser class and imports the Sessions into Guidebook """
demo_day = datetime(2017, 11, 17, 0, 0, 0, 0, pytz.UTC) # iCalParser allows you to simulate t... |
from os import write
import paho.mqtt.client as mqtt # pip install paho.mqtt
import time
import datetime
from rdflib import Graph, URIRef, BNode, Literal, Namespace
from rdflib.namespace import RDF, RDFS, XSD, SOSA, TIME
import numpy as np
g = Graph()
BASE = Namespace("http://example.org/data/")
QUDT11 = Namespace("h... |
from __future__ import print_function
import os
import sys
import stat
from datetime import datetime
import math
import csv
import argparse
fieldnames = [
# CUSTOM
"File_Name", "Type", "Full_Path",
"Date_Modified", "Date_Created", "Date_Accessed",
"DateTime_Modified", "DateTime_Created", "DateTime_Acce... |
##########################################################################################
# Utility functions for images
##########################################################################################
import os
import cv2
import glob
import numpy as np
from PIL import Image
from matplotlib.image import imre... |
# Determine if a string has all unique characters.
def is_unique(s):
for x in range(0, len(s)):
for y in range(x+1,len(s)):
if s[x]==s[y]:
return False
return True
# Should have used new array with simple 128 hash function and check for less than 128 size string
# That would ... |
"""Treadmill REST APIs"""
import logging
import importlib
import pkgutil
import flask
# E0611: Used when a name cannot be found in a module.
# F0401: Used when PyLint has been unable to import a module.
#
# pylint: disable=E0611,F0401
import flask_restplus as restplus
from treadmill import authz
from treadmill.rest... |
class Person:
'''Clase de Persona
recibe el nombre y apellido como parametro'''
def __init__(self, fname, lname):
self.firstname = fname
self.lastname = lname
def printname(self):
print(self.firstname, self.lastname)
class Student(Person):
def __init__(self, fnam... |
from django.db import models
from django.contrib .auth.models import User
from tinymce.models import HTMLField
# Create your models here.
class Profile(models.Model):
profile_image = models.ImageField(upload_to = 'pictures/')
bio= models.CharField(max_length=30)
user= models.OneToOneField(User,on_delete=mod... |
import pytest
from .solution import solve, solve2
INPUT = """
"""
def test_solve():
assert solve(4, 8) == 739785
def test_solve2():
assert solve2(4, 8) == 444356092776315
|
# vim: fdm=marker
'''
author: Fabio Zanini/Richard Neher
date: 25/04/2015
content: Data access module HIV patients.
'''
# Modules
import numpy as np
from .sequence import alpha, alphaa
def diversity(af):
return np.mean(af.sum(axis=0)) - np.mean(np.sum(af**2, axis=0))
def divergence(af, initial):
... |
"""
The tool to check the availability or syntax of domain, IP or URL.
::
โโโโโโโ โโโ โโโโโโโโโโโโโโ โโโโโโโ โโโ โโโโโโโโโโโโโโโโโโโโโโ โโโ โโโโโโโโ
โโโโโโโโโโโโ โโโโโโโโโโโโโโโ โโโโโโโโ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โโโโโโโโ
โโโโโโโโ โโโโโโโ โโโโโโ โโโ โโโโโโโโโ โโโโโโ โโโโโโ โ... |
import os
import glob
import numpy as np
import pandas as pd
import scipy as sp
import itertools
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
import seaborn as sns
from sklearn.preprocessing import normalize
from sklearn.cluster import KMeans
def normalize_gram_matrix(gra... |
from moco_wrapper.util.response import JsonResponse, ListingResponse, EmptyResponse
from moco_wrapper.util.generator import InvoiceItemGenerator, InvoicePaymentGenerator
from .. import IntegrationTest
from datetime import date
class TestInvoicePayment(IntegrationTest):
def get_customer(self):
with self.re... |
import numpy as np
import re
import spacy
from functools import lru_cache
import en_core_web_lg
nlp = en_core_web_lg.load()
#่ฆชใใใdicใไฝๆใใ
###############
#textใnew_listใซ่ชญใฟ่พผใ
with open("tango_sitasimiyasusa_list.txt", "r", encoding="utf-8") as f:
list = f.readlines()
new_list = []
for i in list:
word = i.s... |
from random import randint
from time import sleep
cont = 1
print('Dados jogados!!!')
dados = {'Pessoa 1': randint(1,6),
'Pessoa 2': randint(1,6),
'Pessoa 3': randint(1,6),
'Pessoa 4': randint(1,6)}
for item in sorted(dados, key = dados.get, reverse = True):
sleep(1)
print (f'{cont}ยบ lugar: {item} com {dados[i... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import rospy
from std_msgs.msg import Float64
import math
import forward_kinematics_module
theta = [math.pi/2,0]
d = [0,0]
alpha = [0,0]
a = [120,109.25]
def forward_kinematics_publisher():
limb1 = rospy.Publisher('/manipulator/limb1_controller/command',Float64, queu... |
import warnings
from dagster import check
def canonicalize_backcompat_args(
new_val, new_arg, old_val, old_arg, coerce_old_to_new=None, additional_warn_txt=None
):
'''
Utility for managing backwards compatibility of two related arguments.
For example if you had an existing function
def is_new(o... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import cv2
import numpy as np
from progress.bar import Bar
import time
import torch
import sys
import csv
# try:
# from external.nms import soft_nms
# except:
# print('NMS not imported! If you need it... |
from collections import OrderedDict
from math import ceil
from datetime import datetime
from calendar import Calendar
from django.db import models
from django.conf import settings
from django.shortcuts import resolve_url
from dateutils import relativedelta
from sorl.thumbnail import ImageField, get_thumbnail
from djan... |
from .__about__ import (
__author__,
__commit__,
__copyright__,
__email__,
__license__,
__summary__,
__title__,
__uri__,
__version__,
)
from .koumura import parse_xml, load_song_annot, get_trans_mat
from .koumura import Syllable, Sequence
from .koumura import Resequencer
|
from django.db import models
from enterprise_manage.apps.user_center.models import UserProfile
class ScoreProject(models.Model):
name = models.CharField(verbose_name='ๅ็งฐ', max_length=30)
class Meta:
verbose_name = "ๆๅ้กน็ฎ"
verbose_name_plural = verbose_name
def __str__(self):
retur... |
def my_func(p1=1) -> object:
return p1
d = my_func(1) |
# Copyright 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 accompan... |
import apps.common.func.InitDjango
from all_models.models import *
from all_models.models.A0011_version_manage import TbVersionHttpInterface
from django.db import connection
from django.forms.models import model_to_dict
from apps.common.func.CommonFunc import *
from all_models_for_mock.models import *
from apps.common.... |
# -*- coding: utf-8 -*-
"""
Created on Mon Apr 27 02:23:14 2015
@author: Dimi
"""
import numpy as np
from solve_l1 import solve_l1
def formulate_sparse(A,b):
"""
A must be a M x N array
b must be a M x 1 array
Output:
y must be a N x 1
"""
m ... |
# -*- coding: utf-8 -*-
'''
.. created on 08.09.2016
.. by Christoph Schmitt
'''
from __future__ import print_function, absolute_import, division, unicode_literals
from reflexif.compat import *
from reflexif.models.tiff import TiffHeader
from reflexif.framework.model_base import FrameObject, child, value, Structs
fro... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri Nov 1 13:08:57 2020
"""
from dataclasses import dataclass
import collections
import dacite
import textwrap
import re
from .generic import codeconfig_getvars, prettifyvarname
from . import buildingblocks_dir, indentStr
import warnings
import typing
cl... |
# -*- coding: utf-8 -*-
"""Common exception types for database operations"""
from __future__ import absolute_import, division, unicode_literals
class SQLiteConnectionError(Exception):
"""An error occurred in the database connection"""
class SQLiteError(Exception):
"""An error occurred in the database operat... |
code = ""
file = ""
pos = 0
line = 0
oldLine = 0
oldPos = 0
oldCode = ""
oldFile = ""
def next_file(name, src):
global code, file, pos, line, oldLine, oldPos, oldCode, oldFile
if (oldFile != ""):
return "imports aren't allowed in imported files!"
oldCode = code
oldFile = file
oldLine = line
oldPos = p... |
"""
Tyson Reimer
University of Manitoba
October 13th, 2019
"""
import os
import numpy as np
from umbmid import get_proj_path, verify_path, get_script_logger, null_logger
from umbmid.loadsave import save_pickle, save_mat
from umbmid.build import import_fd_cal_dataset
from umbmid.sigproc import iczt
####... |
# Copyright (c) 2016-2021 Renata Hodovan, Akos Kiss.
#
# Licensed under the BSD 3-Clause License
# <LICENSE.rst or https://opensource.org/licenses/BSD-3-Clause>.
# This file may not be copied, modified, or distributed except
# according to those terms.
import asyncio
import logging
import socket
import threading
from... |
#!/usr/bin/env python3
import socket, threading, json, traceback, configparser, os, ssl, time, select, asyncio, websockets, importlib
abspath = os.path.abspath(__file__)
dname = os.path.dirname(abspath)
os.chdir(dname)
DOMAIN = 'localhost'
PORT = 5566
PORT_SSL = 5567
USE_SSL = False
CERT = ''
KEY = ''
ADDONS_LIST = ... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Tests for sqrt module"""
import pytest
from sim import Simulator, CliArgs, path_join, write_memfile
import random
import sys
sys.path.append('../src/beh')
from sqrt import nrsqrt
def create_sim(cwd, simtool, gui, defines):
sim = Simulator(name=simtool, gui=gui,... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/12/12 3:58 ไธๅ
# @Author : zhangzhen12
# @Site :
# @File : run_rough.py
# @Software: PyCharm
import getopt
import sys
from stock_analytic_modules.rough.inc import update_records, period_records
def main(argv):
mode = None
try:
opts, args = ge... |
#!/usr/bin/python2.7
import os
from PIL import Image
DATEI_WEB_GROSSE = 700
def isimg(isitimg):
ext = os.path.splitext(isitimg)[1].lower()
if ext == ".jpg" or ext == ".png" or ext == ".gif":
return True
return False
def bearbeiten(datei):
img = Image.open(datei)
wrel = DATEI_WEB_GROSSE / float(img.size[0])
h... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('feedbacks', '0002_auto_20141105_1106'),
]
operations = [
migrations.AlterModelOptions(
name='attachment',
... |
import os
import sys
import logging
import base64
from pathlib import Path
import platform
from xml.dom.minidom import parse
from qt_material.resources import ResourseGenerator, RESOURCES_PATH
GUI = True
if 'PySide2' in sys.modules:
from PySide2.QtGui import QFontDatabase, QColor, QGuiApplication, QPalette
fr... |
jogadores = []
jogador = {}
cod = 0
while True:
gols = []
total_de_gols = []
jogador['Cรณdigo'] = cod
jogador['Nome'] = input('Nome do jogador: ').strip().capitalize()
partidas = int(input(f'Quantas partidas {jogador["Nome"]} jogou? '))
jogador['Partidas'] = partidas
for i in range(1, partida... |
import json
from keeper_cnab240.attribute import Attribute
class FileSection:
default_date_format = "%d%m%Y"
default_datetime_format = "%d%m%Y %H%M%S"
default_time_format = "%H%M%S"
def __init__(self, section_name, data, attributes):
self.bank = None
self.section_name = section_name
... |
# Conor Hogan 10/2/18
# Programming and scripting - Week 3
x = int(input("Enter number here:"))
while x != 1:
if x % 2 == 0:
x = x/2
print (x)
else:
x = (x * 3) + 1
print (x)
|
import os
import sys
from setuptools import setup, find_packages
from setuptools.command.test import test as TestCommand
import version
# Hack to prevent stupid "TypeError: 'NoneType' object is not callable" error
# in multiprocessing/util.py _exit_function when running `python
# setup.py test` or `python setup.py f... |
from math import hypot
co = float(input('Cateto oposto: '))
ca = float(input('Cateto adjasente: '))
print('O cumprimento da hipotenusa รฉ {:.2f}'.format(hypot(co, ca)))
|
import enum
from functools import lru_cache
from typing import List
import numpy as np
import pandas as pd
from api.calculate_frequencies import calculate_frequencies3, Frequencies
class SampleType(enum.Enum):
REINFECTION = 0
RECRUDESCENCE = 1
class HiddenAlleleType(enum.Enum):
MISSING = 1
OBSERVED ... |
import numpy as np
import torch
from pynvml import *
nvmlInit()
from algorithms.gcn_algo import GCN
device = torch.device('cuda:0')
print("*********** 0 ***********")
#print(torch.cuda.get_device_properties(0).total_memory)
#print(torch.cuda.memory_cached(0))
print(torch.cuda.memory_cached(0))
#print(torch.cuda.max_... |
# File: F (Python 2.4)
from pandac.PandaModules import *
from direct.interval.IntervalGlobal import *
from direct.actor import Actor
from direct.particles import ParticleEffect
from direct.particles import Particles
from direct.particles import ForceGroup
from otp.otpbase import OTPRender
from PooledEffect import Pool... |
#!/usr/bin/env python
# coding: utf-8
"""
Fatigue related corrections.
"""
import numpy as np
def goodman_haigh(cycles, uts):
"""
Effective alternating stress using the Goodman-Haigh mean stress correction for fully reversed loading (R=-1).
Parameters
----------
cycles : list
Pairs of cyc... |
import json
import lyricwikia
import random
# https://github.com/enricobacis/lyricwikia
thisLineJSON = {}
with open('topSongsJSONTimeout.txt','r') as f, open('lyricData.txt','w',errors='replace') as g:
for x in f:
x = x.rstrip()
if not x: continue
jsonLoader = json.loads(x)
if 't... |
import json
import os
def gerrit_project_map():
# Used for mapping gerrit project names onto OBS package names
map_file = os.path.join(os.path.dirname(__file__), 'project-map.json')
with open(map_file) as map:
project_map = json.load(map)
return project_map
|
from django.shortcuts import render, redirect
from notes.app.forms import ProfileForm, NoteForm, NoteDeleteForm
from notes.app.models import Profile, Note
def home(request):
if request.method == 'GET':
profile = Profile.objects.first()
if not profile:
form = ProfileForm()
... |
# Copyright 2019, The TensorFlow Federated 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 the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law o... |
from .getutxomodel import GetUTXOModel
from .utxomodel import UTXOModel
from pystratis.api.blockstore.responsemodels import AddressIndexerTipModel
from pystratis.api.node.responsemodels import BlockHeaderModel, ValidateAddressModel
from pystratis.api.global_responsemodels import TransactionModel, TransactionOutputModel... |
import os
from UCTB.utils import multiple_process
def task_func(share_queue, locker, data, parameters):
print('Child process %s with pid %s' % (parameters[0], os.getpid()))
for task in data:
print('Child process', parameters[0], 'running', task)
exec_str = 'python HMM.py --Dataset %s --City... |
import os
from selenium import webdriver
op = webdriver.ChromeOptions()
op.binary_location = os.environ.get("GOOGLE_CHROME_BIN")
op.add_argument("--headless")
op.add_argument("--no-sandbox")
op.add_argument("--disable-dev-sh-usage")
driver = webdriver.Chrome(executable_path = os.environ.get("CHROMEDRIVER_PATH"), chro... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.