prefix stringlengths 0 918k | middle stringlengths 0 812k | suffix stringlengths 0 962k |
|---|---|---|
raise Not | ImplementedError("markup | base is not yet implemented in Skulpt")
|
def verificaPalindrome(frase):
removeWhiteSpaces = [] ### Array util para remover os espaços em brancos
removeHypen = [] ### Array util para remover os hifen
palindromo = str(frase).lower().strip() ### Remove os espaços em brancos no inicio e final e coloca toda a palavra em letra minuscula
if (len(pa... | return False
f = open('file.txt', 'r') ### abertura do arquivo genérico de entrada, substituia file.txt pelo nome de arquivo que quiser.
for line in f: ### le as linhas no arquivo genérico de entrada
if (line == "fim"): ### Verifica se a linha esta escrito fim
break ### termina o looping de leitura de li... | uário escrever fim ######
while (True):
frase = input() ### Pega o input do usuario
if(frase == "fim"): ### Sai do loop se digitar fim
break
elif(verificaPalindrome(frase)):
print("E palindromo")
else:
print("Nao e palindromo")
|
from django.contrib import admin
# Register your models here.
from .models import Environment,EnvironmentAdmin,Component,ComponentAdmin,Environment_property,Environment_propertyAdmin,C | omponent_attribute,Component_attributeAdmin
admin.site.register(Environment,EnvironmentAdmin)
admin.site.register(Component,ComponentAdmin)
admin.site.register(Environment_property,Environment_propertyAdmin)
admin.site.register(Component_attribute | ,Component_attributeAdmin)
|
POINT JUDEO-SPANISH VARIKA
chars.append(0xFB1F) #yodyod_patah HEBREW LIGATURE YIDDISH YOD YOD PATAH
chars.append(0xFB20) #alternativeayin HEBREW LETTER ALTERNATIVE AYIN
chars.append(0xFB21) #alefwide HEBREW LETTER WIDE ALEF
chars.append(0xFB22) #daletwide HEBREW LETTER WIDE DALET
... | EW LETTER VAV
chars.append(0x05D6) #zayin HEBREW LETTER ZAYIN
chars.append(0x05D7) #het HEBREW LETTER HET
chars.append(0x05D8) #tet HEBREW LETTER TET
chars.append(0x05D9) #yod HEBREW LETTER YOD
chars.append(0x05DA) #final | kaf HEBREW LETTER FINAL KAF
chars.append(0x05DB) #kaf HEBREW LETTER KAF
chars.append(0x05DC) #lamed HEBREW LETTER LAMED
chars.append(0x05DD) #finalmem HEBREW LETTER FINAL MEM
chars.append(0x05DE) #mem HEBREW LETTER MEM
chars.append(0x05DF) #finalnun HEBREW LETTER FINAL NUN
... |
#!/usr/bin/env python3
import argparse
import logging
import string
# Quiet scapy
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
from scapy import volatile # noqa: E402
from scapy import sendrecv # noqa: E402
from scapy import config # noqa: E402
from scapy.layers import l2 # noqa: E402
from scapy.la... | d"]:
break
output = "Option: {} -> {}".format(option, values)
if option == "message-type" and len(values) == 1:
dhcp_type = dhcp.DHCPTypes.ge | t(values[0], "unknown")
output = "{} ({})".format(output, dhcp_type)
print(output)
def dhcp_sniff(**kwargs):
sendrecv.sniff(filter="udp and (port 67 or 68)", prn=print_dhcp_response)
def parse_args():
p = argparse.ArgumentParser(description='''
All your IPs are belong to us.
... |
# Copyright (C) 2016-2019 Dmitry Marakasov <amdmi3@amdmi3.ru>
#
# This file is part of repology
#
# repology is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your optio... | logy.packagemaker import NameType, PackageFactory, PackageMaker
from repology.parsers import Parser
from repology.parsers.maintainers import extract_maintainers
class CPANPackagesParser(Parser):
def iter_parse(self, path: str, factory: PackageFactory) -> Iterable[PackageMaker]:
# Since data we get from CP... | s.txt package index downloaded from CPAN:
#
# Acme::constant 0.001003 G/GL/GLITCHMR/Acme-constant-0.1.3.tar.gz
# Acme::Constructor::Pythonic 0.002 T/TO/TOBYINK/Acme-Constructor-Pythonic-0.002.tar.gz
# Acme::Continent undef P/PE/PERIGRIN/XML-Tool... |
)}
features = tf.train.FeatureLists(feature_list=features)
return features
def serialize_combined_features(features):
"""Serialize features.
Args:
features: features of the video
"""
audio = features["audio"][0].numpy().tostring()
rgb = features["rgb"][0].numpy().tostring()
audio = convert_to_feat... | int(f"Processing shard number {shard_number}")
shard = tf.convert_to_tensor(shard)
shard_dataset = tf.data.Dataset.from_te | nsor_slices(shard)
file_name = file_type + str(shard_number)
file_path = os.path.join(data_dir, '%s.tfrecord' % file_name)
writer = tf.data.experimental.TFRecordWriter(file_path)
writer.write(shard_dataset)
def save_data(new_data_dir, input_dataset, candidates, file_type="test", shard_size=17):
"""Save data ... |
me__iexact=username)
if not candidates:
return None
return candidates[0].email
return username
def adal_authenticate(email, password):
try:
context = adal.AuthenticationContext(settings.AZUREAD_AUTHORITY)
token = context.acquire_token_with_username_password(
... | response = HttpResponse(content[0], content_type='application/json')
for key, val in content[1].items():
response[key] = val
response["X-auth-cache-hit"] = "success"
return response
cache_basic = False
if not request.user.is_authenticated():
# Check basic auth agains... | entials')
username, password = base64.b64decode(
basic_auth.split(" ", 1)[1].strip()).decode('utf-8').split(":", 1)
username = force_email(username)
# first check for a shared_id match
# if yes, provide a response, but no session cookie
# (hen... |
t Michael Foord
# Free to use, modify and relicense.
| # No warranty express or implied for the accuracy, fitness to purpose or otherwise for this c | ode....
# Use at your own risk !!!
# E-mail or michael AT foord DOT me DOT uk
# Maintained at www.voidspace.org.uk/atlantibots/pythonutils.html
"""
This CGI script allows you to specify a URL using an HTML form.
It will fetch the specified URL and print the headers from the server.
It will also handle cookies using C... |
from click.testing import CliRunner
fr | om sqlitebiter.__main__ import cmd
from sqlitebiter._const import ExitCode
from .common import print_traceback
class Test_version_subcommand:
def test_smoke(self):
runner = CliRunner()
result = runner.invoke(cmd, ["version"])
print_traceback(result)
assert result.exit_co | de == ExitCode.SUCCESS
|
# -*- cod | ing: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('articl | e', '0019_remove_article_ordering_featured'),
]
operations = [
migrations.RemoveField(
model_name='article',
name='issue',
),
]
|
import logging
import os
import environ
import datetime
from olympia.lib.settings_base import * # noqa
environ.Env.read_env(env_file='/etc/olympia/settings.env')
env = environ.Env()
CDN_HOST = 'https://addons-stage-cdn.allizom.org'
CSP_FONT_SRC += (CDN_HOST,)
CSP_FRAME_SRC += ('https://www.sandbox.paypal.com',)
CSP... | ery pane when using services subdomain.
'https://addons.allizom.org',
CDN_HOST,
)
CSP_STYLE_SRC += (CDN_HOST,)
ENGAGE_ROBOTS = False
EMAIL_URL = env.email_url('EMAIL_URL')
EMAIL_HOST = EMAIL_URL['EMAIL_HOST']
EMAIL_PORT = EMAIL_URL['EMAIL_PORT']
EMAIL_BACKEND = EMAIL_URL['EMAIL_BACKEND']
EMAIL_HOST_USER = EMA... | IL_QA_WHITELIST')
ENV = env('ENV')
DEBUG = False
DEBUG_PROPAGATE_EXCEPTIONS = False
SESSION_COOKIE_SECURE = True
CRONJOB_LOCK_PREFIX = DOMAIN
API_THROTTLE = False
REDIRECT_SECRET_KEY = env('REDIRECT_SECRET_KEY')
DOMAIN = env('DOMAIN', default='addons.allizom.org')
SERVER_EMAIL = 'zstage@addons.mozilla.org'
SITE_URL... |
# -*- coding: utf-8 -*-
'''
Created on 19 Dec 2013
@author: Kimon Tsitsikas
Copyright © 2012-2013 Kimon Tsitsikas, Delmic
This file is part of Odemis.
Odemis is free software: you can redistribute it and/or modify it under the terms
of the GNU General Public License version 2 as published by the Free Software
Fou... | test.TestCase):
"""
Test Overlay functions
"""
backend_was_ru | nning = False
@classmethod
def setUpClass(cls):
try:
test.start_backend(SECOM_LENS_CONFIG)
except LookupError:
logging.info("A running backend is already found, skipping tests")
cls.backend_was_running = True
return
except IOError as exp:... |
# Copyright 2013-2020 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class PyColorpy(PythonPackage):
"""ColorPy is a Python package to conv | ert physical descriptions of light -
spectra of light intensity vs. wavelength - into RGB colors that can be
drawn on a computer screen. It provides a nice set of attractive plots
that you can make of such spectra, and some other color related
functions as well.
"""
homepage = "http://markkness... | = "https://pypi.io/packages/source/c/colorpy/colorpy-0.1.1.tar.gz"
version('0.1.1', sha256='e400a7e879adc83c6098dde13cdd093723f3936778c245b1caf88f5f1411170d')
depends_on('py-numpy', type='run')
depends_on('py-matplotlib', type='run')
|
# Copyright (C) 2016 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
"""Module for Clause model."""
from ggrc import db
from ggrc.models.mixins import CustomAttributable
from ggrc.models.deferred import deferred
from ggrc.models.mixins import Described
from ggrc.models.mixin... | n import Personable
from ggrc.models.relationship import Relatable
from ggrc.models.track_object_state import HasObjectState
from ggrc.models.track_object_state import tr | ack_state_for_class
class Clause(HasObjectState, Hierarchical, Noted, Described, Hyperlinked,
WithContact, Titled, Stateful, CustomAttributable,
Personable, Ownable, Timeboxed, Relatable, Slugged, db.Model):
VALID_STATES = [
'Draft',
'Final',
'Effective',
'Ineffect... |
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# MIT License. See license.txt
from __future__ import unicode_literals, print_function
"""
Utilities for using modules
"""
import frappe, os, json
import frappe.utils
from frappe import _
def export_module_json(doc, is_standard, module):
"""Make a... | t_file(frappe.get_doc(doctype, name), module)
def get_doctype_module(doctype):
"""Returns **Module Def** name of given doctype."""
def make_modules_dict():
return dict(frappe.db.sql("select name, module from tabDocType"))
return frappe.cache().get_value("doctype_modules", make_modules_dict)[doctype]
doctype_pyth... | get_doctype_module(doctype)
app = get_module_app(module)
key = (app, doctype, prefix, suffix)
module_name = get_module_name(doctype, module, prefix, suffix)
try:
if key not in doctype_python_modules:
doctype_python_modules[key] = frappe.get_module(module_name)
except ImportError as e:
raise ImportError(... |
cells_update_mock.called)
def test_create_nocells(self):
self._test_create_mocked()
def test_update_or_create(self):
self._test_create_mocked(update_or_create=True)
def test_create_apicell(self):
self._test_create_mocked(cell_type='api')
def test_update_or_create_apicell(self... | e': 'volume', 'id': 1,
'instance_u | uid': 'fake-instance', 'device_name': 'fake'}
if cell_type:
self.flags(enable=True, cell_type=cell_type, group='cells')
else:
self.flags(enable=False, group='cells')
with test.nested(
mock.patch.object(db, 'block_device_mapping_destroy'),
mock.patc... |
"""
File: algorithms.py
Algorithms configured for profiling.
"""
from profiler import Profiler
def selectionSort(lyst, profiler):
i = 0
while i < len(lyst) - 1: # Do n - 1 searches
minIndex = i # for the largest
j = i + 1
while j < len(lyst)... |
def bubbleSort(lyst, profiler):
n = len(lyst)
while n > 1: # Do n - 1 bubbles
i = 1 # Start each bubble
while | i < n:
profiler.comparison()
if lyst[i] < lyst[i - 1]: # Exchange if needed
swap(lyst, i, i - 1, profiler)
i += 1
n -= 1
def bubbleSort2(lyst, profiler):
n = len(lyst)
while n > 1:
swapped = False
i = 1
... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
import mysql.connector
#from token find userId
#return 0 for error
def findUser(userToke | n, cnx):
userQuery = 'SELECT user_id FROM user_token WHERE user_token = %s'
try:
userCursor = cnx.cursor()
userCursor.execute(userQuery, (userToken, ))
return userCursor.fetchone()
#return 0 for db error
except mysql.connector.Erro | r as err:
print('Something went wrong: {}'.format(err))
return '0'
finally:
userCursor.close()
#create new token
#return 1 for success
#return 0 for error
def addToken(userId, userToken, cnx):
addQuery = 'INSERT INTO user_token (user_id, user_token) VALUES (%s, %s) ON DUPLICATE KEY UPD... |
# -*- coding: UTF-8 -*-
import os.path
import re
from outwiker.core.tree import WikiDocument
from outwiker.utilites.textfile import readTextFile, writeTextFile
from .exporterfactory import ExporterFactory
from .indexgenerator import IndexGenerator
class BranchExporter (object):
def __init__ (self, startpage, n... | if page.getTypeString() != WikiDocument.getTypeString():
try:
exporter = ExporterFactory.getExporter (page)
exportname = self.__nameGenerator.getName (page)
self.__renames[page] = exportname
exporter.export (outdir, exportname, imagesonly, alw... | .__log.append (u"{0}: {1}".format (page.title, str(error)))
for child in page.children:
self.__export (
child,
root,
outdir,
imagesonly,
alwaysOverwrite)
|
__author__ = "Christian Kongsgaard"
__license__ = 'MIT'
# -------------------------------------------------------------------------------------------------------------------- #
# IMPORTS
# Modules
# RiBuild Modules
from delphin_6_automation.database_interactions.db_templates import delphin_entry
from delphin_6_autom... | = sample_entry.Strategy.objects().first()
keep = []
for sample in strategy.samples:
found_sample = sample_entry.Sample.objects(id=sample.id)
if found_sample:
keep.append(found_sample.first().id)
else:
print(f"Sample {sample.id} was not in the DB")
print(f"Fo... |
strategy.save()
def modify_sample():
id_ = "5e7878ce582e3e000172996d"
sample = sample_entry.Sample.objects(id=id_).first()
print('Got sample')
sample.mean = {}
sample.standard_deviation = {}
sample.save()
def correct_sample2():
samples = sample_entry.Sample.objects().only('id')
... |
# -*- coding: utf-8 -*-
# Build configuration file.
# This file is execfile()d with the current directory set to its
# containing dir.
# Note that not all possible configuration values are present in this
# autogenerated file.
# All configuration values have a default; values that are commented out
# serve to show the ... | plate names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_use_modindex = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into ... | al pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which... |
import torch
from hypergan.train_hooks.base_train_hook import BaseTrainHook
class NegativeMomentumTrainHook(BaseTrainHook):
def __init__(self, gan=None, config=None, trainer=None):
super().__init__(config=config, gan=gan, trainer=trainer)
self.d_grads = None
self.g_grads = None
def gradients(sel... | w_d_grads = [g.clone() for g in d_grads]
| new_g_grads = [g.clone() for g in g_grads]
d_grads = [_g - self.config.gamma * _g2 for _g, _g2 in zip(d_grads, self.d_grads)]
g_grads = [_g - self.config.gamma * _g2 for _g, _g2 in zip(g_grads, self.g_grads)]
self.d_grads = new_d_grads
self.g_grads = new_g_grads
return [d_grads, g_gr... |
#!/usr/bin/python
imp | ort time, sys
if(len(sys.argv) > 0):
video = sys.argv[1]
else:
video = "REjj1ruFQww"
try:
import pychromecast
pychromecast.play_youtube_video(video, pychromecast.PyChromecast().host)
except:
pass
| |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import datetime
import json
import logging
import sys
import time
from itertools import tee, islice, chain
from orgformat import OrgFormat
from memacs.lib.orgproperty import OrgProperties
from memacs.lib.reader import UnicodeDictReader
from .csv import Csv
# stolen fro... | self._args.identification_fields:
if row1[field] != row2[field]:
return False
return True
def track_is_paused(self, row, next_row):
return next_row and self.tracks_are_iden | tical(row, next_row) and (
self.read_timestamp(next_row) - self.read_timestamp(row)
).total_seconds() < self._args.minimal_pause_duration
def read_log(self, reader):
"""goes through rows and searches for start/stop actions"""
start_time, stop_time = None, None
for prev_r... |
# Copyright 2013 OpenStack Foundation
# 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 law or agreed to in writing, software
# | distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from testtools import matchers
from tempest.api.volume import ... |
import os
import django
from django.conf import settings; settings.configure()
from docx.engines.base import Engine as base
from django.template import Template
from django | .template import Template, Context
"""
Engine for Django
"""
class Engine(base):
def __init__(self):
self.tag_re = "(\{[^\}]+?\}\}?)"
"""
Fix the template and feed it to the engine
"""
| def render(self, template, context):
django.setup()
self._register_filters()
xml = self.fix_tag_gaps(template)
xml = self.fix_block_tags(xml)
self.template = Template(xml)
return self.template.render(Context(context)).encode("utf8")
"""
Load custom template... |
#!/usr/bin/env python3
import matplotlib.pyplot as plt
from math import sqrt
from math import log
dx = [1/sqrt(16), 1/sqrt(64), 1/sqrt(256), 1/sqrt(1024)]
dx_tri = [1/sqrt(32), 1/sqrt(128), 1/sqrt(512), 1/sqrt(2048)]
dx_pert = [0.0270466, 0.0134827, 0.00680914, 0.00367054]
dx_fp = [0.122799, 0.081584, 0.0445639, 0.022... | imited l2: "+str(log(rl2_euler_tri_limited[2]/rl2_euler_tri_limited[3])/log(dx_tri[2]/dx_tri[3])))
print("rho euler lp tri limited l2: "+str(log(rl2_euler_lp_tri_limited[1]/rl2_euler_lp_tri_limited[2])/log(dx_tri[1]/dx_tri[2])))
print("rho euler lim | ited l2: "+str(log(rl2_euler_limited[2]/rl2_euler_limited[3])/log(dx[2]/dx[3])))
print("rho euler lp limited l2: "+str(log(rl2_euler_lp_limited[2]/rl2_euler_lp_limited[3])/log(dx[2]/dx[3])))
print("rho ns l2: "+str(log(rl2_ns[0]/rl2_ns[1])/log(dx[0]/dx[1])))
print("rho ns end ... |
#!/usr/bin/env python
#
# Copyright 2015 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 requir... | # Display results.
for proposal in response['results']:
print ('Proposal with id "%s", name "%s", and status "%s" will be'
' approved.' % (proposal['id'], proposal['name'],
proposal['status']))
# Perform action.
result = proposal_service.perf... | ement())
if result and int(result['numChanges']) > 0:
proposals_approved += int(result['numChanges'])
statement.offset += statement.limit
else:
break
# Display results.
if proposals_approved > 0:
print '\nNumber of proposals approved: %s' % proposals_approved
else:
print '\n... |
from I | Python import embed
import annotateit
from annotateit import model, db, es
from flas | k import g
def main():
app = annotateit.create_app()
with app.test_request_context():
g.user = model.User.fetch('admin')
embed(display_banner=False)
if __name__ == '__main__':
main()
|
lexander Jones
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that... |
"""Generate the list of home teams for a matrix."" | "
team_count = len(self.teams) # Number of teams
odd_team_count = None in self.teams # Whether there is a blank placeholder
if not home_teams: # Randomly select home teams
if odd_team_count:
home_count = (team_count - 1) // 2
homes = random.sample(... |
class Blood(object):
ui | d = "blood"
name = "Blood"
"""
Most characters will have | ordinary blood but some could have acidic blood or with other properties.
"""
|
import logging
from django.contrib.auth.backends import (
RemoteUserBackend,
get_user_model,
)
from django.contrib.auth.models import (
Group,
)
from django.utils.translation import ugettext as _
from rest_framework import exceptions
from rest_framework_auth0.settings import (
auth0_api_settings,
)
fro... | exist in the database. Subclasses can disable
this behavior by setting the ``create_unknown_user`` attribute to
``False``.
| """
www_authenticate_realm = 'api'
# Create a User object if not already in the database?
create_unknown_user = True
def authenticate(self, request):
"""
You should pass a header of your request: clientcode: web
This function initialize the settings of JWT with the specific cli... |
import logging
pvl_logger = logging.getLogger('pvlib')
import datetime
import numpy as np
import pandas as pd
from nose.tools import raises
from nose.tools import assert_almost_equals
from pvlib.location import Location
from pvlib import solarposition
from pvlib import atmosphere
# setup times and location to be ... | tive_am = atmosphere.relativeairmass(ephem_data['zenith'], 'simple')
atmosphere.absoluteairmass(relative_am)
atmosphere.absoluteairmass(relative_am, pressure=100000)
def test_absoluteairmass_numeric():
atmosphere.absoluteairmass(2)
def | test_absoluteairmass_nan():
np.testing.assert_equal(np.nan, atmosphere.absoluteairmass(np.nan))
|
'''
Nesse exer você deve casar linha que tem 'tio', mas que tenha | m 1 caractere
antes.
Para fixação, usar o '.' (ponto).
'''
import re
import sys
REGEX = r''
lines = sys.stdin.readlines | ()
for line in lines:
if re.search(REGEX, line):
print(line.replace('\n', ''))
|
import heapq, itertools
def factorisation(number):
"""Returns a list of the prime factors of a number in ascending order."""
factors = []
while number > 1:
for factor in range(2, number + 1):
if number % factor == 0:
factors.append(factor)
# floor divisi... | n an int
# required because range() needs integer values
| number //= factor
break
return factors
def primes(limit = None):
""" Generator yielding primes below (optional) limit."""
if limit is None:
return _infinite_primes()
else:
return itertools.takewhile(lambda x: x < limit, _infinite_primes())
def _infinite_primes... |
from django.conf.urls import url
|
from profiles import views
urlpatterns = [
url(r"users$", views.UserList.as_view(),
name="api-user-list"),
url(r"user/(?P<pk>[0-9]+)$", views.UserSingle.as_view(),
name="api-review-list"),
url(r"userlogin$", views.UserLogin.as_view(),
name="api-lo | gin"),
] |
# -*- coding: utf-8 -*-
"""
***************************************************************************
widgetBatchBase.py
---------------------
Date : June 2010
Copyright : (C) 2010 by Giuseppe Sucameli
Email : brush dot tyler at gmail dot com
* | **************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the | GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
*********************************************... |
# -*- coding: utf-8 -*-
__title__ = 'latinpigsay'
__license__ = 'MIT'
_ | _author__ = 'Steven Cutting'
__author_email__ = 'steven.c.projects@gmail.com'
__created_on__ = '12/7/2014'
if __name__ == "__main__":
from tests import testscript as ts
from tests import contstests
from latinpigsay.tmp.experiments import exp
from data.text import samples as sam
from latinpigsay im... | as pp
import sys
import logging
logging.basicConfig(filename='tests.log')
testtorun = sys.argv[1]
if testtorun == 'contspara':
contstests.contsparatest()
|
# Copyright 2020 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... | n string):
work = string.split()
creation = re.compile(r"^[0-9]+\^$")
annihilation = re.compile(r"^[0-9]+$")
for opr in work:
if creation.match(opr):
if int(opr[:-1]) % 2:
val = opr[:-1]
else:
val = opr... | "
else:
val = opr
new += val + " "
else:
new = string
return new.rstrip()
|
# tests/test_configuration.py
# vim: ai et ts=4 sw=4 sts=4 ft=python fileencoding=utf-8
from io import StringIO
from pcrunner.configuration import (
read_check_commands,
read_check_commands_txt,
read_check_commands_yaml,
)
def test_read_check_commmands_txt_with_extra_lines():
fd = StringIO(
... | 'command': u'check_dummy.py 1 WARNING -s 10',
'name': u'CHECK_02',
'result_type': 'PROCESS_SERVICE_CHECK_RESULT',
},
]
def test_read_check_commmands_yaml():
fd = StringIO(
u'''
- name: 'CHECK_01'
| command: 'check_dummy.py 0 OK -s 0'
result_type: 'PROCESS_SERVICE_CHECK_RESULT'
- name: 'CHECK_02'
command: 'check_dummy.py 1 WARNING -s 10'
result_type: 'PROCESS_SERVICE_CHECK_RESULT'
'''
)
assert read_check_commands_yaml(fd) == [
{
'command': u'check_dummy.py 0 OK -s 0',
... |
with NodeStepper(
self.sess,
self.y,
feed_dict={
self.ph0.name: ph0_feed,
self.ph1.name: ph1_feed,
}) as stepper:
self.assertAllClose(ph0_feed, stepper.cont(self.ph0))
self.assertEqual({
self.ph0.name: NodeStepper.FEED_TYPE_CLIENT
... | e(576.0, stepper.cont("q:0"))
self.assertSetEqual(set(), stepper.last_updated())
self.assertEqual({}, stepper.last_feed_types())
| def testOverridingUpstreamTensorInvalidatesDumpedIntermediates(self):
with NodeStepper(self.sess, self.q) as stepper:
self.assertAllClose(400.0, stepper.cont("q:0"))
self.assertItemsEqual(["v/read:0", "p:0"],
stepper.intermediate_tensor_names())
self.assertAllClose(10... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import os
import random
from django.conf import settings
from django.core.management | .base import BaseCommand
from wagtail.wagtailcore.models import Page
from wagtail.wagtailimages.models import get_image_model
from privagal.gallery.factories import GalleryFactory, ImageFactory
from privagal.gallery.models import Gallery
from privagal.timeline.models import Timeline
ASSETS_PATH = os.path.join(settin... |
'django-pony-pink.jpg',
'wagtail.png',
'wagtail-space.png',
'python.jpg',
]
Image = get_image_model()
class Command(BaseCommand):
help = 'Generate some data for a demo purpose.'
leave_locale_alone = True
def add_arguments(self, parser):
parser.add_argument('--limit', action='sto... |
import json
from datetime import datetime
import numpy as np
import pandas as pd
import tensorflow as tf
from keras.backend.tensorflow_backend import set_session
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
set_session(tf.Session(config=config))
from keras.models import Sequential, Model
from ker... | keras.optimizers import *
from keras.applications.resnet50 import ResNet50
from keras.callbacks import ModelCheckpoint, CSVLogger
from myutils import get_callbacks
inp = Input(shape=(224, 224, 3))
x = BatchNormalization()(inp)
x = ResNet50(weights='imagenet', include_top=False, pooling='max')(x)
x = Dense(16, activ... | x)
x = Dropout(0.5)(x)
x = Dense(1, activation='sigmoid')(x)
model = Model(inputs=inp, outputs=x)
model_arg = {
'loss': 'binary_crossentropy',
'optimizer': 'sgd',
'metrics': ['binary_accuracy']
}
model.compile(**model_arg)
model.summary()
train = np.load('npz/train.npz')
x_train, y_train = train['xs'], tr... |
from __future__ import absolute_import, print_function
from sentry.testu | tils import APITestCase
class SharedGrou | pDetailsTest(APITestCase):
def test_simple(self):
self.login_as(user=self.user)
group = self.create_group()
event = self.create_event(group=group)
url = '/api/0/shared/issues/{}/'.format(group.get_share_id())
response = self.client.get(url, format='json')
assert re... |
t shutil
import mapnik
from nose.tools import eq_
from .utilities import execution_path, run_all
def setup():
# All of the paths used are relative, if we run the tests
# from another directory we need to chdir()
os.chdir(execution_path('.'))
def make_tmp_map():
m = mapnik.Map(512,512)
m.background... | ctx.close_path()
ctx.stroke()
def cairo_color(c):
""" Return a Cairo color tuple from a Mapnik Color."""
ctx_c = (c.r/255.0,c.g/255.0,c.b/255.0,c.a/255.0)
return ctx_c
if mapnik.has_pycairo():
import cairo
def test_passing_pycairo_context_svg():
m = make_tmp_map()
m.zoom_to_... | height)
expected_cairo_file = './images/pycairo/cairo-cairo-expected.svg'
context = cairo.Context(surface)
mapnik.render(m,context)
draw_title(m,context,"Hello Map",size=20)
draw_neatline(m,context)
surface.finish()
if not os.path.exists(expected_cairo_file) or os... |
from setuptools import setup
exec(open( | 'mi | rror_seq/version.py').read())
LONG_DESCRIPTION = '''
Please visit the GitHub repo (https://github.com/Zymo-Research/mirror-seq) for detail information.
'''
INSTALL_REQUIRES = [
'pandas>=0.18.0',
'pysam>=0.9.0',
'cutadapt==1.9.1',
]
setup(name='mirror_seq',
version=__version__,
description='The bi... |
#!/usr/bin/env python
import hal
class HandlerClass:
def on_led_change(self,hal_led,data=None):
'''
the gladevcp.change led had a transition
'''
if hal_led.hal_pin.get():
if self.halcomp["number"] > 0.0:
self.change_text.set_label("Insert too number %d"... | label("Remove tool")
else:
self.change_text.set_label("")
def __init__(self, halcomp,builder,useropts):
self.halcomp = halcomp
self.chang | e_text = builder.get_object("change-text")
self.halcomp.newpin("number", hal.HAL_FLOAT, hal.HAL_IN)
def get_handlers(halcomp,builder,useropts):
return [HandlerClass(halcomp,builder,useropts)]
|
# -*- coding: utf-8 -*-
# Copyright 2022 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... | g permissions and
# limitations under the License.
#
# Generated code. DO NOT EDIT!
#
# Snippet for ValidateFlow
# NOTE: This snippet has been automatically generated for illustrative purposes only.
# It may require modifications to work in your environment.
# To install the latest published package dependency, execut... | loud-dialogflowcx
# [START dialogflow_v3_generated_Flows_ValidateFlow_sync]
from google.cloud import dialogflowcx_v3
def sample_validate_flow():
# Create a client
client = dialogflowcx_v3.FlowsClient()
# Initialize request argument(s)
request = dialogflowcx_v3.ValidateFlowRequest(
name="nam... |
import sys
import re
def cleancss(text):
text=re.compile('\s+').sub(' ', text)
text=re.compile('\s*(?P<a>,|:)\s*').sub('\g<a> ', text)
text=re.compile('\s*;\s*').sub(';\n ', text)
text=re.compile('\s*\{\s*').sub(' {\n ', text)
text=re.compile('\s*\}\s*').sub('\n}\n\n', text)
return text
... | '</': indent=indent-1
newlines.append(indent*' '+line)
if not line[:2]=='</' and line[-1:]=='>' and \
not line[-2:] in ['/>', '->']: indent=indent+1
text='\n'.join(newlines)
text=re.compile('\<div(?P<a>( .+)?)\>\s+\</div\>').sub('<div\g<a>></div>',text)
text=re.compile('\<a(... | (?P<a>( .+)?)\>\s+(?P<b>[\w\s\(\)\/]+?)\s+\</b\>').sub('<b\g<a>>\g<b></b>',text)
text=re.compile('\<i(?P<a>( .+)?)\>\s+(?P<b>[\w\s\(\)\/]+?)\s+\</i\>').sub('<i\g<a>>\g<b></i>',text)
text=re.compile('\<span(?P<a>( .+)?)\>\s+(?P<b>[\w\s\(\)\/]+?)\s+\</span\>').sub('<span\g<a>>\g<b></span>',text)
text=re.compi... |
#!/usr/bin/env python2
# coding=utf-8
#
# Copyright 2014 Sascha Schirra
#
# This file is part of Ropper.
#
# Ropper is free software: you | can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ropper is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the im... | ee the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
class VectorizableBackedModel(object):
r"""
Mixin for models constructed from a set of :map:`Vectorizable` objects.
Supports models for which visualizing the meaning of a set of components
is trivial.
Requires that the following methods are implemented:
1. `component_vector(index)`
2. `in... | vectors)`
5. `project_out_vector(vector)`
The constructor takes an instance of :map:`Vectorizable`. This is used for
all conversions to and fr | om numpy vectors and instances.
Parameters
----------
template_instance : :map:`Vectorizable`
The template instance.
"""
def __init__(self, template_instance):
self.template_instance = template_instance
def component_vector(self, index):
r"""
A particular compo... |
###
# Copyright 2011 Diamond Light Source 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.o | rg/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS I | S" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
###
'''
Comparisons package
'''
import numpy as _np #@UnresolvedImport
all = _np.all #@ReservedAssignment
any = _np.any #@Reserv... |
# -*- coding: utf-8 -*-
'''
script.matchcenter - Football information for Kodi
A program addon that can be mapped to a key on your remote to display football information.
Livescores, Event details, Line-ups, League tables, next and previous matches by team. Follow what
others are saying about the match ... |
mainmenu.start()
def onAction(self,action):
if action.getId() == 92 or action.getId() == 10:
self.stopRunning()
def onClick(self,controlId):
if controlId == 32501:
teamid = self.getControl(controlId).getSelectedItem().getProperty("teamid")
matchhistory.start(teamid)
elif controlId == 32514:
se... | , standalone=False):
if not twitterhash:
userInput = True
if os.path.exists(tweet_file):
twitter_data = json.loads(FileIO.fileread(tweet_file))
twitterhash = twitter_data["hash"]
twitter_mediafile = twitter_data["file"]
if twitter_mediafile == xbmc.getInfoLabel('Player.Filenameandpath'):
userInput ... |
"""This module tests events that are invoked by Cloud/Infra VMs."""
import fauxfactory
import pytest
from cfme import test_requirements
from cfme.cloud.provider import CloudProvider
from cfme.cloud.provider.gce import GCEProvider
from cfme.control.explorer.policies import VMControlPolicy
from cfme.infrastructure.provi... | request.addfinalizer(policy.delete)
policy.assign_events("VM Create Complete")
@request.addfinalizer
def _cleanup():
policy.unassign_events("VM Create Complete")
policy.assign_actions_to_event("VM Create Complete", action)
profile = appliance.collections.policy_profiles.create(
... |
request.addfinalizer(profile.delete)
provider.assign_policy_profiles(profile.description)
request.addfinalizer(lambda: provider.unassign_policy_profiles(profile.description))
register_event(target_type='VmOrTemplate', target_name=vm_crud.name, event_type='vm_create')
vm_crud.create_on_provider(f... |
# coding: utf-8
"""
>>> from pyun import *
>>> yun = YunBrid | ge('192.168.2.9')
>>> yun.pinMode(13, INPUT)
'input'
>>> yun.digitalRead(13)
0
>>> yun.digitalWrite(13, 1)
1
>>> yun.digitalWrite(13, 0)
0
>>> 0 <= yun.analogRead(5) < 1024
True
"""
import doctest
doctes | t.testmod(optionflags=doctest.REPORT_ONLY_FIRST_FAILURE)
|
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
#
# This file is part of Archivematica.
#
# Copyright 2010-2013 Artefactual Systems Inc. <http://artefactual.com>
#
# Archivematica is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published by
# the F... | Location, ' ', a.fileUUID,' ', IFNULL(a.fileID, "")) AS 'pagingIndex',
a.fileUUID,
a.location,
substring(a.currentLocation,23) as fileName,
a.fileID,
a.description,
a.already_in_access_format,
a.already_in_preservation_format,
case when c.exitCode < 2... | case when b.exitCode < 2 and a.fileID is not null then 1 else 0 end as preservation_normalization_attempted,
case when a.fileID is not null and b.exitcode = 1 then 1 else 0 end as preservation_normalization_failed,
c.taskUUID as access_normalization_task_uuid,
b.taskUUID as preservation_no... |
import tests.model_control.test_ozone_custom_models_enabled as testmod
testmod.build_model( ['Integration'] , ['PolyTrend'] , ['Seasonal_Minute'] , ['NoAR | '] ); | |
# -*- coding: utf-8 -*-
# Generated by Django 1.11.5 on 2017-09-29 01:58
from __future__ import unicode_literals
import django.contrib.postgres.fields.jsonb
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('magic', '0006_auto_20170928_2238'),
]
o... | ),
migrations.AlterField(
model_name='card',
name='printings',
field=django.contrib.postgres.fields.jsonb.JSONField(blank=True, null=True),
),
migrations.AlterField(
model_name='card',
name='toughness' | ,
field=models.IntegerField(blank=True, null=True, verbose_name='toughness'),
),
]
|
ew
from widgetastic_manageiq import Select
from widgetastic_patternfly import Button, Input, Dropdown
class RatesView(ChargebackView):
title = Text("#explorer_title_text")
@property
def is_displayed(self):
return (
self.in_intel_chargeback and self.configuration.is_displayed and
... | (
self.in_explorer and
self.title.text == 'Storage Chargeback Rate "{}"'.format(self.obj.description))
class ComputeRate(Updateable, Pretty, Navigatable):
"""This class represents a Compute Chargeback rate.
Example:
| .. code-block:: python
>>> import cfme.intelligence.chargeback.rates as rates
>>> rate = rates.ComputeRate(description=desc,
fields={'Used CPU':
{'per_time': 'Hourly', 'variable_rate': '3'},
'Used Disk I/O':
... |
#PART 1: Terminology
#1) Give 3 examples of boolean expressions.
#a) "apple" == "apple"
#b) 1 != 1
#c) 5 >= 6
#2) What does 'return' do?
#'Return' returns a value. It can be used after an calculation is
#executed. When the python interpreter solves a math problem, you can
#"return" the value back into the interpreter... | mat(num2)
elif num3 > num1 and num3 > num2:
print """
The greatest number is {}
""".format(num3)
elif num1 == num2 == num3:
print """
You did not | follow directions.
"""
def main():
print "Please type in three different numbers." #simple directions givens
num1 = float(raw_input("Number 1: ")) #raw input of user's desired numbers.
num2 = float(raw_input("Number 2: "))
num3 = float(raw_input("Number 3: "))
output(num1, num2, num3)
main() #main... |
# -*- coding: utf-8 -*-
"""
# Copyright 2015 Telefonica Investigacion y Desarrollo, S.A.U
#
# This file is part of Orion Context Broker.
#
# Orion Context Broker is free software: you can redistribute it and/or
# modify it under the terms of the GNU Affero General Public License as
# published by the Free Software Foun... | """
rows = len(step.hashes)
if rows != 1:
| raise ValueError('The table for this steps has to have only 1 row but it has {rows}'.format(rows=rows))
kargs = dict()
if 'entity_id' in step.hashes[0]:
kargs.update({'entity_id': step.hashes[0]['entity_id']})
else:
raise ValueError('The entity_id is mandatory. Table: {table}'.format(table... |
amplitude -- Amplitude of the voltage command.
Returns:
The resistance.
"""
if not stf.check_doc():
print('Couldn\'t find an open file; aborting now.')
return 0
#A temporary array to calculate the average:
array = np.empty( (stf.get_size_channel(), stf.get_size_trace()) )... | thods to calculate AP properties
from threshold (see Stuart et al., 1997). Note that all
calculations are performed in the active/current channel!!!
"""
de | f __init__(self,threshold):
"""
Create a Spike instance with sampling rate and threshold
measurements are performed in the current/active channel!!!
Arguments:
threshold -- slope threshold to measure AP kinetics
"""
self._thr = threshold
# set all t... |
from qit.base.bool import Bool
from qit.base.struct import Struct
from qit.domains.domain import Domain
from qit.domains.iterator import Iterator
from qit.base.function import Function
from qit.functions.int import multiplication_n
class Product(Domain):
""" Cartesian product of domains """
def __init__(self... | s):
sizes = [ d.size for d in domains ]
if all(sizes):
return multiplication_n(len(sizes))(*sizes)
def _make_indexer(self, domains):
| indexers = [ d.indexer for d in domains ]
if all(indexers):
"""
indexer = FunctionWithExprs(start=start, step=step).returns(Int())
indexer.takes(Int(), "_v")
indexer.code("return (_v - {start}) / {step};")
"""
def __mul__(self, other):
... |
# 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/.
"""
Audit groups and removes inactive users.
"""
import datetime
from django.contrib.auth.models import Group, User
fr... | odels import ContentType
from django.core.manage | ment.base import BaseCommand
from django.utils import timezone
from crashstats.authentication.models import PolicyException
VALID_EMAIL_DOMAINS = ("mozilla.com", "mozilla.org")
def get_or_create_auditgroups_user():
try:
return User.objects.get(username="auditgroups")
except User.DoesNotExist:
... |
# Note: run this server by using python2.7 instead of python3.2
from asyncore import dispatcher
from asynchat import async_chat
import socket, asyncore
IP = ''
PORT = 5555
SEP = '\n'
class ChatSession(async_chat):
"""
A simple chat session corresponding to a client
"""
def __init__(self,sock):
async_chat.__init... | (self):
print("---------------found_terminator")
line = ''.join | (self.data)
self.data = []
print(line)
class ChatServer(dispatcher):
"""
a simple chat server.
a server has n clients and n sessions.
"""
def __init__(self, ip,port):
dispatcher.__init__(self)
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
self.bind((ip,port))
self.listen(5)
# store all sess... |
def genbox(i):
i = int(i)
def draw(size, yc, xc):
y = yc
for _ in range(0,size):
if _ == 0 or _ == size-1:
x = xc
i = 0
while i < size:
if not g[_+y][x]=="x": g[_+y][x] = "x"
x += 2
i+=1
else:
if not g[_+y][xc]=="x": g[_+y][xc... | or _ in range(1,2*i):
h.append(" ")
g.append(h)
| c = i
a = 0
b = 0
while c > 0:
draw(c,a,b)
c -= 4
a += 2
b += 4
output = ""
for row in g:
output += "".join(row) + "\n"
return output.strip()
print(genbox(input("Enter size: "))) |
from turtle import | *
from random import *
speed(0)
colormode(255)
for side_n in range(15,2,-1):
color((randint(1, 255),randint(1, 255),ran | dint(1, 255)),(randint(1, 255),randint(1, 255),randint(1, 255)))
begin_fill()
for i in range(side_n):
forward(100)
left(360/side_n)
end_fill()
|
# Generated by Django 2.2.1 on 2019-09-19 11:28
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('dojo', '0021_cve_index'),
]
operations = [
migrations.AddField(
model_name='system_settings',
name='credentials',
... | ons.AddField(
model_name='system_settings',
name='drive_folder_ID',
field=models.CharField(max_length=100, blank=True),
),
migrations.AddField(
model_ | name='system_settings',
name='enable_google_sheets',
field=models.BooleanField(null=True, blank=True, default=False),
),
]
|
# Copyright 2020 gRPC 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 or agreed to in writing... | cific language governing permis | sions and
# limitations under the License.
import logging
import re
from typing import ClassVar, Dict, Optional
from google.protobuf import json_format
import google.protobuf.message
import grpc
logger = logging.getLogger(__name__)
# Type aliases
Message = google.protobuf.message.Message
class GrpcClientHelper:
... |
t control file
hot_files, control_config = _load_user_control(home_dir, project_dir, options)
# look for project control file
control_file = _find_control(parser, project_dir)
if None == control_file:
sys.exit(1)
# emit the context message and exit
if options.context_only:
sys.... | iles))
| quiet_period = 0
if len(args) == 2:
try:
quiet_period = int(args[1])
except:
parser.error(f'Quiet minutes, "{args[1]}", must be a valid number.' )
sys.exit(1)
try:
(hot_files, control_config) = control.parse_control(project_dir, control_file, contro... |
# -*- coding: utf-8 -*-
# The MIT License (MIT)
# Copyright (c) 2014 Aleksandar Topuzović <aleksandar.topuzovic@gmail.com>
# 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 restrictio... | BILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
#... | setuptools import setup, find_packages
from setuptools.command.test import test as TestCommand
import sys
class PyTest(TestCommand):
def finalize_options(self):
TestCommand.finalize_options(self)
self.test_args = ['--strict', '--verbose', '--tb=long',
'--cov', 'pyzebos', '... |
"""
Name : Stegano Extract and Read File From Image
Created By : Agus Makmun (Summon Agus)
Blog : bloggersmart.net - python.web.id
License : GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007
Documentation : https://github.com/agusmakmun/Some-Examples-of-Simple-Python-Script/
"... | ive.\n[+] >> | > ")
zip = raw_input("[+] Type your Zip file: ")
new_img = raw_input("[+] Type New Image that will save your zip: ")
mome._secure(img, zip, new_img)
print os.listdir(".")
elif choice == "2":
print os.listdir(".")
... |
import numpy
import six
from chainer import cuda
from chainer import function
from chainer.utils import type_check
class NegativeSamplingFunction(function.Function):
def __init__(self, sampler, sample_size):
self.sampler = sampler
self.sample_size = sample_size
def _make_samples(self, t):
... | pling_forward'
)(self.wx, n_in, self.sample_size + 1)
# TODO(okuta): merge elementwise
loss = cuda.cupy.sum(y)
return loss,
def backward_cpu(self, inputs, grads):
x, t, W = inputs
gloss, = grads
gx = numpy.zeros_like(x)
gW = numpy.zeros_like(W)
... | f = w.dot(ix)
# g == -y * gloss / (1 + exp(yf))
f[0] *= -1
g = gloss / (1 + numpy.exp(-f))
g[0] *= -1
gx[i] = g.dot(w)
for ik, ig in six.moves.zip(k, g):
gW[ik] += ig * ix
return gx, None, gW
def backward_gpu(sel... |
p17, not_p12, not_p4, not_p3, not_p18}
{p24, p11, not_p20, p22, not_p5, not_p16, p17, not_p4, not_p3, not_p18}
{p24, p2, p11, not_p20, not_p5, p17, not_p21, not_p4, not_p3, not_p18}
{p24, p2, p11, not_p20, not_p5, p17, not_p12, not_p4, not_p3, not_p18}
{p24, p2, p11, not_p20, p22, not_p5, p17, not_p4, not_p3, not_p18}
... | , not_p4, p21, p14, not_p18}
{p24, p25, p11, p22, not_p5, not_p16, not_p8, not_p4, p21, p14, not_p18}
{p24, p25, p11, not_p20, not_p5, not_p16, not_p8, not_p21, not_p4, p14, not_p18}
{p24, p25, p11, not_p20, not_p5, n | ot_p16, not_p8, not_p12, not_p4, p14, not_p18}
{p24, p25, p11, not_p20, p22, not_p5, not_p16, not_p8, not_p4, p14, not_p18}
{p24, p25, p11, not_p5, not_p16, not_p8, not_p21, p9, not_p4, not_p18}
{p24, p25, p11, not_p5, not_p16, not_p8, not_p12, p9, not_p4, not_p18}
{p24, p25, p11, p22, not_p5, not_p16, not_p8, p9, not_... |
else:
assert obj.values.base is values.base and values.base is not None
def test_is_scalar_access(self):
# GH#32085 index with duplicates doesn't matter for _is_scalar_access
index = Index([1, 2, 1])
ser = Series(range(3), index=index)
assert ser.iloc._is_... | f.iloc[[-3]]
tm.assert_frame_equal(result, expected)
expected = s.iloc[0]
result = s.iloc[-3]
assert result == expected
expected = s.iloc[[0]]
result = s.iloc[[-3]]
tm.assert_series_equal(result, expected)
# check the length 1 Series case highlighted in... | assert_series_equal(result, expected)
def test_iloc_getitem_dups(self):
# GH 6766
df1 = DataFrame([{"A": None, "B": 1}, {"A": 2, "B": 2}])
df2 = DataFrame([{"A": 3, "B": 3}, {"A": 4, "B": 4}])
df = concat([df1, df2], axis=1)
# cross-sectional indexing
result = df.il... |
#!/usr/bin/env python
#########################################################################################
# KLEE-Unit
# Author: Jacob Torrey
# Date: 3/15/2016
#
# Script to auto-generate test harness and execute symbolically with KLEE for a passed C
# file
########################################################... | print "Unable to parse pattern: " + pattern
sys.exit(-1)
return (node.ext[-1].name, _explain_type(node.ext[-1]))
def _explain_type(decl):
'''Recursively explains a type decl node'''
typ = type(decl)
| if typ == c_ast.TypeDecl:
quals = ' '.join(decl.quals) + ' ' if decl.quals else ''
return quals + _explain_type(decl.type)
elif typ == c_ast.Typename or typ == c_ast.Decl:
return _explain_type(decl.type)
elif typ == c_ast.IdentifierType:
return ' '.join(decl.names)
elif ty... |
sandwich_orders = [ | 'Bacon','Bacon, egg and cheese','Bagel toast','pastrami','pastrami','pastrami']
print ('pastrami sandwich was sold out')
finished_sandwiches = []
while 'pastrami' in sandwich_orders | :
sandwich_orders.remove('pastrami')
print(sandwich_orders) |
#! /usr/bin/python
# Version info: $Id: NonLinearFit2D.py 230 2010-06-30 20:20:14Z zunzun.com $
# the pythonequations base is located up one directory from the top-level examples
# directory, go up one directory in the path from there for the import to work properly
import sys, os
if os.path.join(sys.path[0][:sys.p... | in range(len(equation.DependentDataArray)):
print 'X:', equation.IndependentDataArray[0][i],
print 'Y', equation.DependentDataArray[i],
print 'Model:', equation.PredictedArray[i],
print 'Abs. Erro | r:', equation.AbsoluteErrorArray[i],
print 'Rel. Error:', equation.RelativeErrorArray[i],
print 'Percent Error:', equation.PercentErrorArray[i]
|
import lib.result_functions_file as RFF
import lib.maglib as MSG
import os
#这个库是统计各个词语的出现次数,并显示
#这是tieba-zhuaqu项目的用户端基本插件
def satisticWord(word,datalist):
os.system('cls')
print('>>>>>开始统计【',word,'】出现次数....')
sum=1
mlist=[]
for item in datalist:
if item.find(word) != -1:
sum+=1... | getContentList() | ) |
import pytest
np = pytest.importorskip("numpy")
npt = pytest.importorskip("numpy.testing")
import networkx as nx
from .base_test import BaseTestAttributeMixing, BaseTestDegreeMixing
class TestDegreeMixingDict(BaseTestDegreeMixing):
def test_degree_mixing_dict_undirected(self):
d = nx.degree_mixing_dict... | self.G, "fish", mapping=mapping)
npt.assert_equal(a, a_result / float(a_result.sum()))
def test_attribute_mixing_matrix_directed( | self):
mapping = {"one": 0, "two": 1, "red": 2, "blue": 3}
a_result = np.array([[1, 0, 1, 0], [0, 1, 0, 1], [0, 0, 0, 0], [0, 0, 0, 0]])
a = nx.attribute_mixing_matrix(
self.D, "fish", mapping=mapping, normalized=False
)
npt.assert_equal(a, a_result)
a = nx.at... |
import collections
from django.conf import settings
from django.contrib.auth.models import User, Group
from django.core.cache import cache
from django.contrib import messages
from django.shortcuts import render, redirect
from django.db import transaction
from django.db.models import Q
from funfactory.urlresolvers imp... | .objects.all().values('user_id', 'group_id'):
groups_map[x['user_id']].append(groups[x['group_id']])
users = []
qs = User.objects.all()
values = (
'email',
'id',
'last_login',
'is_staff',
'is_active',
'is_superuser'
)
# make a big fat list of ... | r IDs of people who are contributors
contributor_ids = (
UserProfile.objects
.filter(contributor=True)
.values_list('user_id', flat=True)
)
for user_dict in qs.values(*values):
user = dot_dict(user_dict)
item = {
'id': user.id,
'email': user.em... |
utils import DISABLE_JIT
from clifford import tools
from . import rng # noqa: F401
too_slow_without_jit = pytest.mark.skipif(
DISABLE_JIT, reason="test is too slow without JIT"
)
class TestTools:
def checkit(self, p, q, rng): # noqa: F811
# p, q =4,0
N = p + q
# eps(1e-4)
... | t random_rotation_rotor
for i in range(1000):
rotor = random_rotation_rotor(rng=rng)
quaternion = rotor_to_quaternion(rotor)
rotor_return = quaternion_to_rotor(quaternion)
t | esting.assert_almost_equal(rotor.value, rotor_return.value)
@too_slow_without_jit
def test_rotation_matrix_conversions(self, rng): # noqa: F811
"""
Bidirectional rotor - rotation matrix test. This needs work but is a reasonable start
"""
from clifford.g3c import down
f... |
y applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ impo... | # 'password': 'password',
# 'tenant_name': 'armax'}
# # let driver generate this for us.
# del req['id']
# result = self.datasource_mgr.add_datasource(req)
# engine = self.dseNode.service_object('engine')
# engine.create_policy('ali... | e')
# engine.insert('p(x) :- %s:q(x)' % req['name'], 'alice')
# self.assertRaises(exception.DanglingReference,
# self.datasource_mgr.delete_datasource,
# result['id'])
def test_delete_invalid_datasource(self):
req = self._get_datasource_re... |
__name__
lr = trainer.learning_rate
estimator.logger.info("Training begin: using optimizer %s "
"with current learning rate %.4f ",
optimizer, lr)
if estimator.max_epoch:
estimator.logger.info("Train for %d epochs.", estimat... | """
def __init__(self,
model_dir,
model_prefix='model',
monitor=None,
verbose=0,
save_be | st=False,
mode='auto',
epoch_period=1,
batch_period=None,
max_checkpoints=5,
resume_from_checkpoint=False):
self.monitor = monitor
self.verbose = verbose
if not os.path.exists(model_dir):
os.makedirs... |
import clr
clr.AddReference("mscorlib")
clr.AddReference("PresentationFramework")
from System.Windows import Application
from System.IO import StreamReader
from System.Threading import Thread
from System.Windows.Markup import XamlReader
from System.Reflection import Assembly
from System import Action
class ViewModel:... | Assembly.GetManifestResourceStream(
"IronPython.UI.Scripts.ResultWindow.xaml")
reader = StreamReader(stream)
window = XamlReader.Parse(reader.ReadToEnd())
reader.Close()
stream.Close()
window.DataContext = vm
window.FindName("CloseButton").Click += lambda s, e: window.Close()
window.Show()
Applicatio... | ke(Action(lambda: getNumberOfSpeakers()))
for i in range(0, 10):
print str(i+1)
Thread.Sleep(500)
print "Done!" |
# Copyright 2016 Adler Brediks Medrado
#
# 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... | xpress or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from setuptools import setup, find_packages
with open("requirements.txt") as reqs:
install_requires = reqs.readlines()
setup(
name="abbr",
version="0.0.1",
ur | l="https://github.com/adlermedrado/abbr",
author="Adler Brediks Medrado",
author_email="abbr@adlermedrado.com.br",
license="Apache-2.0",
description="A client library to abbreviate string contents",
long_description=open('README.rst').read(),
packages=find_packages(),
install_requires=in... |
gt = [_ for cId in p.catIds for _ in self._gts[imgId,cId]]
dt = [_ for cId in p.catIds for _ in self._dts[imgId,cId]]
if len(gt) == 0 and len(dt) ==0:
return []
dt = sorted(dt, key=lambda x: -x['score'])
if len(dt) > p.maxDets[-1]:
dt=dt[0:p.maxDets[-1]]
... | tps = np.logical_and( dtm, np.logical_not(dtIg) )
fps = np.logical_and(np.logical_not(dtm), np.logical_not(dtIg) )
tp_sum = np.cumsum(tps, axis=1).astype(dtype=np.float)
fp_sum = np.cumsum(fps, axis=1).astype(dtype=np.float)
... | fp = np.array(fp)
nd = len(tp)
rc = tp / npig
pr = tp / (fp+tp+np.spacing(1))
q = np.zeros((R,))
if nd:
recall[t,k,a,m] = rc[-1]
else:
... |
#! /usr/bin/python2
# -*- coding: utf-8; -*-
#
# (c) 2013 booya (http://booya.at)
#
# This file is part of the OpenGlider project.
#
# OpenGlider is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version ... | ort flattened_cell
try:
import openglider
except ImportError:
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(sys.argv[0]))))
import openglider
import openglider.graphics
import openglider.plots
from test_glider import GliderTestClass
testfolder = os.path.dirname(os.path.abspath(__file__))... | plete=False):
super(TestGlider_Flatten, self).setUp(complete=complete)
def get_flattened_cell(self, allowance=0.02):
cell = self.glider.cells[random.randint(0, len(self.glider.cells)-1)]
left_bal, left, right, right_bal = flattened_cell(cell)
left_out = left.copy()
right_out... |
__author__ = 'Mc | Daemon'
from models import Weather
from rest_framework import serializers
class WeatherSe | rializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Weather
fields = ('datum', 'stadt', 'anbieter', 'anbieter', 'wetter', 'tagestemperatur', 'einheit', 'kondition',
'windgeschwindigkeit', 'windrichtung', 'url') |
"""Setup the application's CLI commands."""
from example import app, db
@app.manage
def hello(name, upper=False):
"""Write command help text here.
:param name: Write your name
:param upper: Use uppercase
"""
greetings = f"Hello {name}!"
if upper:
greetings = greetings.upper()
p... | xample."""
from example.models import User
async with db.connection():
await User.get_or_create(email='user@muffin.io', defaults={
'username': 'user', 'password': User.generate_password('pass'),
})
await User.get_or_create(email='admin@muffin.io', defaults={
'us... | |
# -*- | coding: utf-8 -*-
de | f social_eyebrow(entity, argument):
return True
#- Fine Funzione -
|
# -*- coding: utf-8 -*-
"""
Copyright [2009-2021] EMBL-European Bioinformatics Institute
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... | peline.writers import build
@click.group("cpat")
def cli():
"""
Commands with processing the Rfam metadata.
"""
pass
@cli.command("parse")
@click.argument("cutoffs", type=click.File("rb"))
@click.argument("model_name")
@click.argument("results", type=click.Path())
@click.argument("output", type=clic... | ffs, model_name, results, output):
cutoffs = pickle.load(cutoffs)
data = parser.parse(cutoffs, model_name, Path(results))
with build(CpatWriter, Path(output)) as wtr:
wtr.write(data)
@cli.command("generate-cutoffs")
@click.argument("data-folder", type=click.Path())
@click.argument("output", type=c... |
# -*- coding: utf-8 -*-
###################################################### | ########################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<ht | tp://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed ... |
"""
Configuration tasks
This module provides tools to load yaml configuration files.
"""
import os
from fabric.api import *
from fabric.contrib.console import confirm
from fabric.colors import red, green
try:
import yaml
except ImportError:
print(red('pyYaml module not installed. Run the following commands t... | file | must look like this:
all:
key1: defaultValue1
:
prod:
key1: prod_value1
key2: prod_value2
:
dev:
key1: dev_value1
key2: dev_value2
:
'all' is the default that will be returned if no env value is passed.
'prod' and 'dev' in the above e... |
import sys
def updt(total, progress, extra=""):
"""
Displays or updates a console progress bar.
Original source: | https://stackoverflow.com/a/15860757/1391441
"""
barLength, status = 20, ""
progress = float(progress) / float(total)
if progress >= 1.:
progress, status = 1, | "\r\n"
block = int(round(barLength * progress))
text = "\r[{}] {:.0f}% {}{}".format(
"#" * block + "-" * (barLength - block),
round(progress * 100, 0), extra, status)
sys.stdout.write(text)
sys.stdout.flush()
|
# -*- coding: utf-8 -*-
# ..#######.########.#######.##....#..######..######.########....###...########.#######.########..######.
# .##.....#.##.....#.##......###...#.##....#.##....#.##.....#...##.##..##.....#.##......##.....#.##....##
# .##.....#.##.....#.##......####..#.##......##......##.....#..##...##.##.....#.... | #......##...##.##....#.##....#.##....##.##.....#.##.......##......##....##.##....##
# ..#######.##.......#######.##... | .#..######..######.##.....#.##.....#.##.......#######.##.....#..######.
'''
OpenScrapers Project
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('projects', '0003_auto_20150618_ | 1121'),
]
operations = [
migrations.AddField(
model_name='project',
name='status',
field=models.ForeignKey(default='a', to='projects.ProjectStatus'),
| preserve_default=False,
),
]
|
# -*- coding: utf-8 -*-
#
# Copyright (c) 2013 the BabelFish authors. All rights reserved.
# Use of this source code is governed by the 3-clause BSD license
# that can be found in the LICENSE file.
#
import sys
if sys.version_info[0] >= 3:
basestr = str
else:
basestr = basestring
from .conver | ters import (LanguageConverter, LanguageReverseConverter, LanguageEquivalenceConverter, CountryConverter,
CountryReverseConverter)
from .country import country_converters, COUNTRIES, COUNTRY_MATRIX, Country
from .exceptions import Error, LanguageConvertError, LanguageReverseErr | or, CountryConvertError, CountryReverseError
from .language import language_converters, LANGUAGES, LANGUAGE_MATRIX, Language
from .script import SCRIPTS, SCRIPT_MATRIX, Script
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import datetime
from django import forms
from django.core.mail import send_mail
from django.template import Context
from ProyectoDeGrado.settings import MEDIA_ROOT
from apps.administrador.models import *
from django.contrib.auth.models import User
class PerfilForm(forms.M... | o@gmail.com>', [data['username']+data['dominio']],fail_silently=False)
def save(self, data):
perfil = Perfil()
usuario = User.objects.get(username = data['username'])
perfil.usuario = usuario
perfil.activation_key=data['activation_key']
perfil.key_expires=datetime.datetime.s... | e.datetime.now() + datetime.timedelta(days=2), "%Y-%m-%d %H:%M:%S")
perfil.save()
return perfil
class UserForm(forms.ModelForm):
class Meta:
model = User
fields = ['username', 'password', 'email', 'first_name', 'last_name']
widgets = {
'username': forms.TextInp... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.