index int64 0 1,000k | blob_id stringlengths 40 40 | code stringlengths 7 10.4M |
|---|---|---|
994,400 | 3ebaebd05793953cd181a72d1b8f00efae8460f3 | import files.screen
if __name__ == '__main__':
screen = files.screen.Screen()
screen.game_menu()
|
994,401 | 49f8fcfb216ea515506fa755c6c5e3b574ae4609 | import string
alphabet = list(string.ascii_uppercase)
names = file("./names.txt")
names = names.read().replace('"','').split(",")
names = sorted(names,key=str.lower)
def name_score(name):
name = name.upper()
name = list(name)
score = map(lambda x:alphabet.index(x)+1,name)
return sum(score)
names = map(name_score,names)
names = enumerate(names)
names = list(names)
names = map(lambda (x,y):(x+1)*y,names)
print sum(names)
|
994,402 | 252cd00a48f6c1215491167afff42624353ac2fa | from rest_framework import status
from rest_framework.decorators import api_view
from recruit_api.apps.utils.models import ResponseData
from recruit_api.apps.utils.api.response import RecruitResponse
from recruit_api.apps.email.operations import EmailOperations
from rest_framework.views import APIView
from rest_framework.parsers import FormParser, MultiPartParser
# @api_view(['POST'])
# def email(request):
# try:
# data = ResponseData()
# data.result = EmailOperations().send(request.data)
# data.message = "Email has been sent successfully."
# return RecruitResponse.get_success_response(status.HTTP_200_OK, data)
# except Exception as ex:
# return RecruitResponse.get_exception_response(ex)
class email(APIView):
parser_classes = (MultiPartParser, FormParser,)
def post(self, request, *args, **kwargs):
try:
data = ResponseData()
data.result = EmailOperations().send(request.data)
data.message = "Email has been sent successfully."
return RecruitResponse.get_success_response(status.HTTP_200_OK, data)
except Exception as ex:
return RecruitResponse.get_exception_response(ex)
|
994,403 | 06132b2a6f23b8b4742a5a1150e2fafbd59d4c53 | import scrapy
import pandas as pd
from ..items import ImdbSpiderItem
import time
import re
def get_movies(path):
data = pd.read_csv(path)
url = data['url']
return url
class ImdbSpider(scrapy.Spider):
start = time.clock()
name = 'movies'
allowed_domains = ['imdb.com']
def start_requests(self):
data = get_movies('/Users/konglingtong/PycharmProjects/machine_learning/FP/data/url.csv')
urls = []
for link in data:
u = re.findall(r'https://www\.imdb\.com/title/tt\d+/', str(link))
if len(u) is not 0:
urls.append(u)
for i in range(len(urls)):
url = urls[i][0]
if (i % 100) == 0:
time.sleep(5)
yield scrapy.Request(url=url, callback=self.parse)
def parse(self, response):
items = []
item = ImdbSpiderItem()
movie_url = response.url
item['year'] = response.xpath('//*[@id="titleYear"]/a/text()').extract()
item['RatePeople'] = response.xpath(
'//*[@id="title-overview-widget"]/div[1]/div[2]/div/div[1]/div[1]/a/span/text()').extract()
directors = response.xpath(
'//div[@id="title-overview-widget"]/div[2]/div[1]/div[2]/a/text()').extract()
item['movie_url'] = movie_url
if len(directors) is not 0:
director = directors
else:
director = response.xpath(
'//*[@id="title-overview-widget"]/div[2]/div[2]/div[1]/div[2]/a/text()').extract()
stars = response.xpath(
'//div[@id="title-overview-widget"]/div[2]/div[1]/div[4]/a/text()').extract()
if len(stars) is not 0:
star = stars
elif len(response.xpath(
'//*[@id="title-overview-widget"]/div[2]/div[2]/div[1]/div[4]/a/text()').extract()) is not 0:
star = response.xpath(
'//*[@id="title-overview-widget"]/div[2]/div[2]/div[1]/div[4]/a/text()').extract()
elif len(response.xpath('//*[@id="title-overview-widget"]/div[2]/div[1]/div[3]/a/text()').extract()) is not 0:
star = response.xpath('//*[@id="title-overview-widget"]/div[2]/div[1]/div[3]/a/text()').extract()
elif len(response.xpath(
'//*[@id="title-overview-widget"]/div[2]/div[2]/div[1]/div[3]/a/text()').extract()) is not 0:
star = response.xpath(
'//*[@id="title-overview-widget"]/div[2]/div[2]/div[1]/div[3]/a/text()').extract()
elif len(response.xpath(
'//*[@id="title-overview-widget"]/div[2]/div[2]/div[1]/div[2]/a/text()').extract()) is not 0:
star = response.xpath(
'//*[@id="title-overview-widget"]/div[2]/div[2]/div[1]/div[2]/a/text()').extract()
# rate = response.xpath(
# '//*[@id="title-overview-widget"]/div[1]/div[2]/div/div[2]/div[2]/div/text()').extract_first()
# if rate is not None:
# item['rate'] = rate
# else:
# item['rate'] = response.xpath('///*[@id="titleStoryLine"]/div[5]/span[1]/text()').extract_first()
movie = response.xpath(
'//div[@id="title-overview-widget"]/div[1]/div[2]/div/div[2]/div[2]/h1/text()').extract_first()
if len(movie) is not 0:
item['movie'] = movie
else:
item['movie'] = response.xpath(
'//*[@id="title-overview-widget"]/div[1]/div[2]/div/div[2]/div[2]/h1/text()').extract_first()
review = response.xpath(
'//*[@id="title-overview-widget"]/div[1]/div[2]/div/div[1]/div[1]/div[1]/strong/span/text()') \
.extract_first()
item['review'] = review
item['Production'] = response.css('a[href^="/company/"]::text').extract()
rate = response.css('.subtext::text').extract()[0]
if len(rate) is not 0:
item['rate'] = rate
else:
item['rate'] = 'No rate'
item['runTime'] = response.xpath(
'//*[@id="title-overview-widget"]/div[1]/div[2]/div/div[2]/div[2]/div/time/text()').extract()
genre = response.xpath('//*[@id="titleStoryLine"]/div[4]/a/text()').extract()
if len(genre) is not 0:
item['genre'] = genre
elif len(response.xpath('//*[@id="titleStoryLine"]/div[3]/a//text()').extract()) is not 0:
item['genre'] = response.xpath('//*[@id="titleStoryLine"]/div[3]/a/text()').extract()
elif len(response.xpath('//*[@id="titleStoryLine"]/div[2]/a/text()').extract()) is not 0:
item['genre'] = response.xpath('//*[@id="titleStoryLine"]/div[2]/a/text()').extract()
elif len(response.xpath('//*[@id="titleStoryLine"]/div[1]/a/text()').extract() is not 0):
item['genre'] = response.xpath('//*[@id="titleStoryLine"]/div[1]/a/text()').extract()
country = response.css('.article a[href^="/search/title?country_of_origin="]::text').extract()
item['country'] = country
# if len(country) is not 0:
# item['country'] = country
# elif len(response.xpath('//*[@id="titleDetails"]/div[2]/a/text()').extract()) is not 0:
# item['country'] = response.xpath('//*[@id="titleDetails"]/div[2]/a/text()').extract()
item['cast'] = star + director
if str(review) != 'nan':
items.append(item)
yield item
# stop = time.clock()
# print(stop - start)
# for url in picture_urls:
# yield scrapy.Request(url=url, callback=self.picture_parse)
# @staticmethod
# def picture_parse(response):
# items = []
# item = ImdbSpiderItem()
# item['poster'] = response.xpath('//*[@id="photo-container"]/div/div[2]/div/div[2]/div[1]/div[2]/div/img[2]')
# yield item
# pass
|
994,404 | 3aa2d780cce7a9133064be9950ef58b92cfad049 | # Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required 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.
"""Functions that involve a full pass over the dataset.
This module contains functions that are used in the preprocessing function, to
define a full pass operation such as computing the sum, min, max or unique
values of a tensor over the entire dataset. This is implemented by a reduction
operation in the Beam implementation.
From the user's point of view, an analyzer appears as a regular TensorFlow
function, i.e. it accepts and returns tensors. However it is represented in
the graph as a `Analyzer` which is not a TensorFlow op, but a placeholder for
the computation that takes place outside of TensorFlow.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import re
import numpy as np
import tensorflow as tf
ANALYZER_COLLECTION = 'tft_analyzers'
VOCAB_FILENAME_PREFIX = 'vocab_'
VOCAB_FREQUENCY_FILENAME_PREFIX = 'vocab_frequency_'
class Analyzer(object):
"""An operation-like class for full-pass analyses of data.
An Analyzer is like a tf.Operation except that it requires computation over
the full dataset. E.g. sum(my_tensor) will compute the sum of the value of
my_tensor over all instances in the dataset. The Analyzer class contains the
inputs to this computation, and placeholders which will later be converted to
constants during a call to AnalyzeDataset.
Args:
inputs: The inputs to the analyzer.
output_dtype_shape_and_is_asset: List of tuples of `(DType, Shape, bool)`
for each output. A tf.placeholder with the given DType and Shape will be
constructed to represent the output of the analyzer, and this placeholder
will eventually be replaced by the actual value of the analyzer. The
boolean value states whether this Tensor represents an asset filename or
not.
spec: A description of the computation to be done.
name: Similar to a TF op name. Used to define a unique scope for this
analyzer, which can be used for debugging info.
Raises:
ValueError: If the inputs are not all `Tensor`s.
"""
def __init__(self, inputs, output_dtype_shape_and_is_asset, spec, name):
for tensor in inputs:
if not isinstance(tensor, tf.Tensor):
raise ValueError('Analyzers can only accept `Tensor`s as inputs')
self._inputs = inputs
self._outputs = []
self._output_is_asset_map = {}
with tf.name_scope(name) as scope:
self._name = scope
for dtype, shape, is_asset in output_dtype_shape_and_is_asset:
output_tensor = tf.placeholder(dtype, shape)
if is_asset and output_tensor.dtype != tf.string:
raise ValueError(('Tensor {} cannot represent an asset, because it '
'is not a string.').format(output_tensor.name))
self._outputs.append(output_tensor)
self._output_is_asset_map[output_tensor] = is_asset
self._spec = spec
tf.add_to_collection(ANALYZER_COLLECTION, self)
@property
def inputs(self):
return self._inputs
@property
def outputs(self):
return self._outputs
@property
def spec(self):
return self._spec
@property
def name(self):
return self._name
def output_is_asset(self, output_tensor):
return self._output_is_asset_map[output_tensor]
class CombinerSpec(object):
"""Analyze using combiner function.
This object mirrors a beam.CombineFn, that will receive a beam PCollection
representing the batched input tensors.
"""
def create_accumulator(self):
"""Return a fresh, empty accumulator.
Returns: An empty accumulator. This can be an Python value.
"""
raise NotImplementedError
def add_input(self, accumulator, element):
"""Return result of folding element into accumulator.
Args:
accumulator: the current accumulator
element: the element to add, which will be an ndarray representing the
value of the input for a batch.
Returns: An accumulator that includes the additional element.
"""
raise NotImplementedError
def merge_accumulators(self, accumulators):
"""Merges several accumulators to a single accumulator value.
Args:
accumulators: the accumulators to merge
Returns: The sole merged accumulator.
"""
raise NotImplementedError
def extract_output(self, accumulator):
"""Return result of converting accumulator into the output value.
Args:
accumulator: the final accumulator value. Should be a list of ndarrays.
Returns: An ndarray representing the result of this combiner.
"""
raise NotImplementedError
def combine_analyzer(x, output_dtype, output_shape, combiner_spec, name):
"""Applies the combiner over the whole dataset.
Args:
x: An input `Tensor` or `SparseTensor`.
output_dtype: The dtype of the output of the analyzer.
output_shape: The shape of the output of the analyzer.
combiner_spec: A subclass of CombinerSpec.
name: Similar to a TF op name. Used to define a unique scope for this
analyzer, which can be used for debugging info.
Returns:
The combined values, which is a `Tensor` with type output_dtype and shape
`output_shape`. These must be compatible with the combiner_spec.
"""
return Analyzer([x], [(output_dtype, output_shape, False)], combiner_spec,
name).outputs[0]
class _NumPyCombinerSpec(CombinerSpec):
"""Combines the PCollection only on the 0th dimension using nparray."""
def __init__(self, fn, reduce_instance_dims):
self._fn = fn
self._reduce_instance_dims = reduce_instance_dims
def create_accumulator(self):
return None
def add_input(self, accumulator, next_input):
if self._reduce_instance_dims:
batch = self._fn(next_input)
else:
batch = self._fn(next_input, axis=0)
if accumulator is None:
return batch
else:
return self._fn((accumulator, batch), axis=0)
def merge_accumulators(self, accumulators):
# numpy's sum, min, max, etc functions operate on array-like objects, but
# not arbitrary iterables. Convert the provided accumulators into a list
return self._fn(list(accumulators), axis=0)
def extract_output(self, accumulator):
return [accumulator]
def _numeric_combine(x, fn, reduce_instance_dims=True, name=None):
"""Apply an analyzer with _NumericCombineSpec to given input."""
if not isinstance(x, tf.Tensor):
raise TypeError('Expected a Tensor, but got %r' % x)
if reduce_instance_dims:
# If reducing over all dimensions, result is scalar.
shape = ()
elif x.shape.dims is not None:
# If reducing over batch dimensions, with known shape, the result will be
# the same shape as the input, but without the batch.
shape = x.shape.as_list()[1:]
else:
# If reducing over batch dimensions, with unknown shape, the result will
# also have unknown shape.
shape = None
return combine_analyzer(
x, x.dtype, shape, _NumPyCombinerSpec(fn, reduce_instance_dims),
name if name is not None else fn.__name__)
def min(x, reduce_instance_dims=True, name=None): # pylint: disable=redefined-builtin
"""Computes the minimum of the values of a `Tensor` over the whole dataset.
Args:
x: A `Tensor`.
reduce_instance_dims: By default collapses the batch and instance dimensions
to arrive at a single scalar output. If False, only collapses the batch
dimension and outputs a `Tensor` of the same shape as the input.
name: (Optional) A name for this operation.
Returns:
A `Tensor`. Has the same type as `x`.
"""
return _numeric_combine(x, np.min, reduce_instance_dims, name)
def max(x, reduce_instance_dims=True, name=None): # pylint: disable=redefined-builtin
"""Computes the maximum of the values of a `Tensor` over the whole dataset.
Args:
x: A `Tensor`.
reduce_instance_dims: By default collapses the batch and instance dimensions
to arrive at a single scalar output. If False, only collapses the batch
dimension and outputs a vector of the same shape as the input.
name: (Optional) A name for this operation.
Returns:
A `Tensor`. Has the same type as `x`.
"""
return _numeric_combine(x, np.max, reduce_instance_dims, name)
def sum(x, reduce_instance_dims=True, name=None): # pylint: disable=redefined-builtin
"""Computes the sum of the values of a `Tensor` over the whole dataset.
Args:
x: A `Tensor`.
reduce_instance_dims: By default collapses the batch and instance dimensions
to arrive at a single scalar output. If False, only collapses the batch
dimension and outputs a vector of the same shape as the input.
name: (Optional) A name for this operation.
Returns:
A `Tensor`. Has the same type as `x`.
"""
return _numeric_combine(x, np.sum, reduce_instance_dims, name)
def size(x, reduce_instance_dims=True, name=None):
"""Computes the total size of instances in a `Tensor` over the whole dataset.
Args:
x: A `Tensor`.
reduce_instance_dims: By default collapses the batch and instance dimensions
to arrive at a single scalar output. If False, only collapses the batch
dimension and outputs a vector of the same shape as the input.
name: (Optional) A name for this operation.
Returns:
A `Tensor`. Has the same type as `x`.
"""
with tf.name_scope(name, 'size'):
# Note: Calling `sum` defined in this module, not the builtin.
return sum(tf.ones_like(x), reduce_instance_dims)
def mean(x, reduce_instance_dims=True, name=None):
"""Computes the mean of the values of a `Tensor` over the whole dataset.
Args:
x: A `Tensor`.
reduce_instance_dims: By default collapses the batch and instance dimensions
to arrive at a single scalar output. If False, only collapses the batch
dimension and outputs a vector of the same shape as the input.
name: (Optional) A name for this operation.
Returns:
A `Tensor` containing the mean. If `x` is floating point, the mean will
have the same type as `x`. If `x` is integral, the output is cast to float32
for int8 and int16 and float64 for int32 and int64 (similar to the behavior
of tf.truediv).
"""
with tf.name_scope(name, 'mean'):
# Note: Calling `sum` defined in this module, not the builtin.
return tf.divide(
sum(x, reduce_instance_dims), size(x, reduce_instance_dims))
def var(x, reduce_instance_dims=True, name=None):
"""Computes the variance of the values of a `Tensor` over the whole dataset.
Uses the biased variance (0 delta degrees of freedom), as given by
(x - mean(x))**2 / length(x).
Args:
x: A `Tensor`.
reduce_instance_dims: By default collapses the batch and instance dimensions
to arrive at a single scalar output. If False, only collapses the batch
dimension and outputs a vector of the same shape as the input.
name: (Optional) A name for this operation.
Returns:
A `Tensor` containing the variance. If `x` is floating point, the variance
will have the same type as `x`. If `x` is integral, the output is cast to
float32 for int8 and int16 and float64 for int32 and int64 (similar to the
behavior of tf.truediv).
"""
with tf.name_scope(name, 'var'):
# Note: Calling `mean`, `sum`, and `size` as defined in this module, not the
# builtins.
x_mean = mean(x, reduce_instance_dims)
# x_mean will be float32 or float64, depending on type of x.
squared_deviations = tf.square(tf.cast(x, x_mean.dtype) - x_mean)
return mean(squared_deviations, reduce_instance_dims)
class _UniquesSpec(object):
"""Operation to compute unique values."""
def __init__(self, top_k, frequency_threshold,
vocab_filename, store_frequency):
self._top_k = top_k
self._frequency_threshold = frequency_threshold
self._vocab_filename = vocab_filename
self._store_frequency = store_frequency
@property
def top_k(self):
return self._top_k
@property
def frequency_threshold(self):
return self._frequency_threshold
@property
def vocab_filename(self):
return self._vocab_filename
@property
def store_frequency(self):
return self._store_frequency
def sanitized_vocab_filename(filename=None, prefix=None):
"""Generates a sanitized filename either from the given filename or the scope.
If filename is specified, provide a sanitized version of the given filename.
Otherwise generate a filename from the current scope. Note that it is the
callers responsibility to ensure that filenames are unique across calls within
a given preprocessing function.
Args:
filename: A filename with non-alpha characters replaced with underscores and
spaces to hyphens.
prefix: Prefix to use for the name of the vocab file, if filename
is not given.
Returns:
A valid filename.
Raises:
ValueError: If neither filename and prefix are specified, or if both
are specified.
"""
if filename is None and prefix is None:
raise ValueError('Both filename and prefix cannot be None.')
if filename is not None and prefix is not None:
raise ValueError('Only one of filename or prefix can be specified.')
if filename is None:
filename = prefix + tf.get_default_graph().get_name_scope()
# Replace non-alpha characters (excluding whitespaces) with '_'.
filename = re.sub(r'[^\w\s-]', '_', filename).strip()
# Replace whitespaces with '-'.
return re.sub(r'[-\s]+', '-', filename)
def uniques(x, top_k=None, frequency_threshold=None,
vocab_filename=None, store_frequency=False, name=None):
r"""Computes the unique values of a `Tensor` over the whole dataset.
Computes The unique values taken by `x`, which can be a `Tensor` or
`SparseTensor` of any size. The unique values will be aggregated over all
dimensions of `x` and all instances.
In case one of the tokens contains the '\n' or '\r' characters or is empty it
will be discarded since we are currently writing the vocabularies as text
files. This behavior will likely be fixed/improved in the future.
The unique values are sorted by decreasing frequency and then decreasing
lexicographical order.
Args:
x: An input `Tensor` or `SparseTensor` with dtype tf.string.
top_k: Limit the generated vocabulary to the first `top_k` elements. If set
to None, the full vocabulary is generated.
frequency_threshold: Limit the generated vocabulary only to elements whose
frequency is >= to the supplied threshold. If set to None, the full
vocabulary is generated.
vocab_filename: The file name for the vocabulary file. If none, the
"uniques" scope name in the context of this graph will be used as the file
name. If not None, should be unique within a given preprocessing function.
NOTE To make your pipelines resilient to implementation details please
set `vocab_filename` when you are using the vocab_filename on a downstream
component.
store_frequency: If True, frequency of the words is stored in the
vocabulary file. Each line in the file will be of the form
'frequency word\n'.
name: (Optional) A name for this operation.
Returns:
The path name for the vocabulary file containing the unique values of `x`.
Raises:
ValueError: If `top_k` or `frequency_threshold` is negative.
"""
if top_k is not None:
top_k = int(top_k)
if top_k < 0:
raise ValueError('top_k must be non-negative, but got: %r' % top_k)
if frequency_threshold is not None:
frequency_threshold = int(frequency_threshold)
if frequency_threshold < 0:
raise ValueError(
'frequency_threshold must be non-negative, but got: %r' %
frequency_threshold)
if isinstance(x, tf.SparseTensor):
x = x.values
if x.dtype != tf.string:
raise ValueError('expected tf.string but got %r' % x.dtype)
with tf.name_scope(name, 'uniques'):
if vocab_filename is not None:
prefix = None
elif store_frequency:
prefix = VOCAB_FREQUENCY_FILENAME_PREFIX
else:
prefix = VOCAB_FILENAME_PREFIX
# Make the file name path safe.
vocab_filename = sanitized_vocab_filename(vocab_filename, prefix=prefix)
spec = _UniquesSpec(top_k, frequency_threshold, vocab_filename,
store_frequency)
return Analyzer([x], [(tf.string, [], True)], spec, 'uniques').outputs[0]
class _QuantilesSpec(object):
"""Operation to compute quantile boundaries."""
def __init__(self, epsilon, num_buckets):
self._epsilon = epsilon
self._num_buckets = num_buckets
@property
def epsilon(self):
return self._epsilon
@property
def num_buckets(self):
return self._num_buckets
@property
def bucket_dtype(self):
return tf.float32
def quantiles(x, num_buckets, epsilon, name=None):
"""Computes the quantile boundaries of a `Tensor` over the whole dataset.
quantile boundaries are computed using approximate quantiles,
and error tolerance is specified using `epsilon`. The boundaries divide the
input tensor into approximately equal `num_buckets` parts.
See go/squawd for details, and how to control the error due to approximation.
Args:
x: An input `Tensor` or `SparseTensor`.
num_buckets: Values in the `x` are divided into approximately equal-sized
buckets, where the number of buckets is num_buckets.
epsilon: Error tolerance, typically a small fraction close to zero
(e.g. 0.01). Higher values of epsilon increase the quantile approximation,
and hence result in more unequal buckets, but could improve performance,
and resource consumption. Some measured results on memory consumption:
For epsilon = 0.001, the amount of memory for each buffer to hold the
summary for 1 trillion input values is ~25000 bytes. If epsilon is
relaxed to 0.01, the buffer size drops to ~2000 bytes for the same input
size. If we use a strict epsilon value of 0, the buffer size is same size
as the input, because the intermediate stages have to remember every input
and the quantile boundaries can be found only after an equivalent to a
full sorting of input. The buffer size also determines the amount of work
in the different stages of the beam pipeline, in general, larger epsilon
results in fewer and smaller stages, and less time. For more performance
trade-offs see also http://web.cs.ucla.edu/~weiwang/paper/SSDBM07_2.pdf
name: (Optional) A name for this operation.
Returns:
The bucket boundaries represented as a list, with num_bucket-1 elements
See bucket_dtype() above for type of bucket boundaries.
"""
with tf.name_scope(name, 'quantiles'):
spec = _QuantilesSpec(epsilon, num_buckets)
quantile_boundaries = Analyzer(
[x], [(spec.bucket_dtype, [1, None], False)], spec,
'quantiles').outputs[0]
# quantile boundaries is of the form
# [nd.arrary(first, <num_buckets-1>, last)]
# Drop the fist and last quantile boundaries, so that we end-up with
# num_buckets-1 boundaries, and hence num_buckets buckets.
return quantile_boundaries[0:1, 1:-1]
|
994,405 | 5fc304c7255b62e0fff0f5e89e8e5100738a1504 | # -*- coding:utf-8 -*-
from dytt8 import *
def dytt_spider():
try:
print 'execfile------dytt_spider.py'
task_dytt8()
except:
print traceback.format_exc()
if __name__ == '__main__':
dytt_spider()
|
994,406 | ccf1dbee46d28800f87aac3b74d9b544456fb474 | import urllib2
import requests
from xml.dom.minidom import parse, parseString
def get_authorization_code():
auth_url = "https://graph.api.smartthings.com/oauth/authorize?response_type=code&client_id=b882249a-a9b4-4690-935d-bf78aeeb991a&scope=app&redirect_uri=http://localhost:4567/oauth/callback"
return
def get_request():
auth_url = "https://graph.api.smartthings.com/oauth/authorize?response_type=code&client_id=b882249a-a9b4-4690-935d-bf78aeeb991a&scope=app&redirect_uri=http://localhost:4567/oauth/callback"
response = urllib2.urlopen(auth_url).read()
#requests.get(auth_url)
#username afujii@umich.edu
#password alfredpassword1
#print r.status_code
#print r.headers .content
dom1 = parseString(response)
print dom1
get_request()
|
994,407 | 23943486bc80f1be6496b845bee2fe378b1fbf2d | """Module for creating warped images
"""
from typing import Optional, Union
from FaceEngine import IHumanWarperPtr # pylint: disable=E0611,E0401
from FaceEngine import Image as CoreImage # pylint: disable=E0611,E0401
from numpy import ndarray
from PIL.Image import Image as PilImage
from lunavl.sdk.detectors.bodydetector import BodyDetection
from lunavl.sdk.errors.exceptions import assertError
from lunavl.sdk.image_utils.image import ColorFormat, VLImage
class BodyWarpedImage(VLImage):
"""
Raw warped image.
Properties of a warped image:
- it's always in RGB color format
- it always contains just a single human body
"""
def __init__(
self,
body: Union[bytes, bytearray, ndarray, PilImage, CoreImage, VLImage],
filename: str = "",
colorFormat: Optional[ColorFormat] = None,
):
"""
Init.
Args:
body: body of image - bytes/bytearray or core image or pil image or vlImage
filename: user mark a source of image
colorFormat: output image color format
"""
if isinstance(body, VLImage):
self.source = body.source
self.filename = body.filename
self.coreImage = body.coreImage
else:
super().__init__(body, filename=filename, colorFormat=colorFormat)
self.assertWarp()
def assertWarp(self):
"""
Validate size and format
Raises:
ValueError("Bad image format for warped image, must be R8G8B8"): if image has incorrect format
Warnings:
this checks are not guarantee that image is warp. This function is intended for debug
"""
if self.rect.size.height != 256 or self.rect.width != 128:
raise ValueError("Bad image size for body warped image")
if self.format != self.format.R8G8B8:
raise ValueError("Bad image format for warped image, must be R8G8B8")
# pylint: disable=W0221
@classmethod
def load(cls, *, filename: Optional[str] = None, url: Optional[str] = None) -> "BodyWarpedImage": # type: ignore
"""
Load image from numpy array or file or url.
Args:
filename: filename
url: url
Returns:
warp
"""
warp = cls(body=VLImage.load(filename=filename, url=url), filename=filename or "")
warp.assertWarp()
return warp
@property
def warpedImage(self) -> "BodyWarpedImage":
"""
Property for compatibility with *Warp* for outside methods.
Returns:
self
"""
return self
class BodyWarp:
"""
Structure for storing warp.
Attributes:
sourceDetection (BodyDetection): detection which generated warp
warpedImage (BodyWarpedImage): warped image
"""
__slots__ = ["sourceDetection", "warpedImage"]
def __init__(self, warpedImage: BodyWarpedImage, sourceDetection: BodyDetection):
"""
Init.
Args:
warpedImage: warped image
sourceDetection: detection which generated warp
"""
self.sourceDetection = sourceDetection
self.warpedImage = warpedImage
class BodyWarper:
"""
Class warper.
Attributes:
_coreWarper (IWarperPtr): core warper
"""
__slots__ = ["_coreWarper"]
def __init__(self, coreWarper: IHumanWarperPtr):
"""
Init.
Args:
coreWarper: core warper
"""
self._coreWarper = coreWarper
def warp(self, humanDetection: BodyDetection) -> BodyWarp:
"""
Create warp from detection.
Args:
humanDetection: human body detection with landmarks17
Returns:
Warp
Raises:
LunaSDKException: if creation failed
"""
error, warp = self._coreWarper.warp(humanDetection.image.coreImage, humanDetection.coreEstimation.detection)
assertError(error)
warpedImage = BodyWarpedImage(body=warp, filename=humanDetection.image.filename)
return BodyWarp(warpedImage, humanDetection)
|
994,408 | a086bdff4bd8d7a2bc8729b9f96668a7ffea35ef | from .tasks import *
task_lists = {'CartPole': CartPole, 'Acrobot': Acrobot, 'FlappyBird': FlappyBird, 'MoutainCar': MoutainCar, 'Catcher': Catcher, 'Pixelcopter': Pixelcopter, 'Pong': Pong}
# task: {name, init, alpha, n_task} eq: param = init + alpha * i
def param(init, alpha, i):
return init + alpha * i
def create_tasks(task):
tasks = []
for i in range(task['n_task']):
t = task_lists[task['name']](param(task['init'], task['alpha'], i))
tasks.append(t)
return tasks
|
994,409 | 5595fcff09f4391186db35ea9166b5c1ca6db917 | import os
import json
import numpy as np
import pandas as pd
import re
from tqdm import tqdm
from scipy.stats import pearsonr
import matplotlib.pyplot as plt
from math import log
path = './PacificExcellent_CCS/PacificExcellent_CCS'
filelist = os.listdir(path)
# 删除解压之后留下的zip文件
# for filename in filelist:
# if 'zip' in filename:
# os.remove(f'{path}/{filename}')
# 整合数据生成csv文件
# name = []
# for filename in filelist:
# name.append(filename.split('.')[0])
# csv_data = np.empty((len(name), 0))
# csv_data = pd.DataFrame(data=csv_data, index=name)
#
# for filename in tqdm(filelist):
# with open(f'{path}/{filename}', 'r') as datafile:
# data = json.load(datafile)
# for x in data:
# if x not in csv_data.columns.tolist():
# csv_data[x] = np.nan
# csv_data.loc[filename.split('.')[0], x] = data[x]
#
# csv_data.to_csv('PacificExcellent.csv')
# 简单统计
csv_data = pd.read_csv('./PacificExcellent.csv', low_memory=False)
# cols = []
# for col in tqdm(csv_data.columns.tolist()):
# nums = []
# col_data = csv_data[col].values
# for x in col_data:
# if x == x and x not in nums:
# nums.append(x)
# if len(nums) == 4:
# print(col)
# cols.append(nums)
# plt.plot(col_data)
# plt.show()
# 92017 92020
# mean1 = csv_data['92018'].mean()
# csv_data['92018'].fillna(mean1, inplace=True)
# col1 = csv_data['92018'].values
# mean2 = csv_data['92020'].mean()
# csv_data['92020'].fillna(mean2, inplace=True)
# col2 = csv_data['92020'].values
# # print(pearsonr(col1, col2))
# numEntries = len(col1) # 样本数
# labelCounts = {} # 该数据集每个类别的频数
# for featVec in col1: # 对每一行样本
# currentLabel = featVec # 该样本的标签
# if currentLabel not in labelCounts.keys():
# labelCounts[currentLabel] = 0
# labelCounts[currentLabel] += 1
# shannonEnt = 0.0
# for key in labelCounts:
# prob = float(labelCounts[key]) / numEntries # 计算p(xi)
# shannonEnt -= prob * log(prob, 2) # log base 2
# print(shannonEnt)
# col_data = csv_data['12216'].dropna().values
# a = 0
# for x in col_data:
# x = str(x)
# if ('.' in x and len(x) == 5) or ('.' not in x and len(x) == 4):
# a += 1
# print(a)
# print(len(col_data))
# print(a / len(col_data))
sensors = csv_data.columns.tolist()
for sensor in sensors:
col = csv_data[sensor].values
for i in range(len(col)):
if '-' in str(col[i]) and str(col[i])[0] != '-':
print(sensor, i)
|
994,410 | af2c3d91a0736f885d06c0ac96dbe25c0bae832f | #!/usr/bin/env python
# -*-coding:utf-8 -*-
#Author:HXJ
#动态参数
'''
需求:
1.对请求参数进行ascill排序
2.排序后,对请求参数进行md5的加密
1.写一个函数,获取请求参数,对请求参数进行加密
'''
# dict1={'name':'hxj','age':18,'data':{
# 'name':'wuya','age':18}}
# def data(**kwargs):
# return dict(sorted(kwargs.items(),key=lambda item:item[0]))
# dict1={'name':'hxj','age':18,'data':{
# 'name':'wuya','age':18}}
# dict2={'name':'hxj','age':18,'address':'chengdu','work':'tester'}
# print(data(**dict2))
#
# def f():
# print('Hello world')
#函数可以是变量
# per=f()
# per
#函数可以是参数
# def f1(a):
# return a
# f1(f())
# def f1(*arg,**kwargs):
# print(arg,kwargs)
#
# f1([1,2,3])
# f1('a')
# f1(name='wuya')
# f1(dict1={'name':'wuya'})
#
# def f(a,b=None):
# print()
#
# def getFile(director='d:/',fileName=None):
# pass
# getFile(fileName='.xml')
'''
返回值
1.None
2.return后面的内容就是函数的返回值
'''
def f():
print('hello world')
#print(f())
def add(a,b):
return a+b
#print(add(2,3))
# def login():
# username=input('请输入登录账号\n')
# password=input('请输入账号的密码\n')
# if username=='hxj' and password=='123456':
# return 'sdtytugi43567szxgd'
#
# def profile(session):
# if session==login():#返回值为session
# print('欢迎访问')
# else:
# print('未登录系统,跳转到登录的界面 302')
#
# profile('sdtytugi43567szxg')
'''
全局作用域:全局变量
局部作用域:针对局部
先看自己内部,再回父部
'''
# name='wuya'
#
# def f():
# global name
# name='wuyya'
# print(name)
#
# f()
# def f():
# name='我是父函数'
# def f1():
# name='我是子函数的值'
# print(name)
# return f1()
#
# f()
# per=lambda a,b:a+b
#
# print(per(2,3))
age=10
#print('true') if age>5 else print('false')
# login=lambda username,password:print('登录成功') if username=='hxj' and password=='123456' else print('error')
#
# login('hxj','123456')
# data=lambda **kwargs:dict(sorted(kwargs.items(),key=lambda item:item[0]))
#
# print(data(name='admin',age=18))
list1=[1,2,3,4,5]
def f():
list2=[]
for i in list1:
i+=100
list2.append(i)
print(list2)
#f()
# def f(a):
# return a+100
#
# print(list(map(f,list1)))
# print(list(map(lambda a:a+100,list1)))
def f():
list2=[]
for i in list1:
if i>3:
list2.append(i)
print(list2)
print(list(filter(lambda a:a>1,list1))) |
994,411 | b562ee4143fe2a41fe5fc5c076c7404168442841 | from django.http import HttpResponse
# Create your views here.
def cs(request):
text = "这是一个测试接口"
return HttpResponse(text) |
994,412 | 06c7e877e684b6b26c7508ad0d127b06c9d36b9e | # parameter를 받기
# 사용예 : python sys.py life is short
import sys
args = sys.argv[1:]
for i in args:
print("Param %d : %s", i, i.upper(), end=' ')
|
994,413 | 0b838bff2fca920f411a93b41d8ed9ce833959cf | class ImageTransform(object):
def __init__(self, part):
self.part = part |
994,414 | b14931997d3e663061ab593dcaf2fbc3ff35b02f | from rest_framework.serializers import ModelSerializer
from tarefas.models import Tarefa
class TarefasSerializer(ModelSerializer):
class Meta:
model = Tarefa
fields = '__all__'
|
994,415 | 81de064ec7f8529e2a8e70e076ba162dcc5349cc | # Forma 1
dict = {1: 1, 4: 4, 5: 5, 6: 6, 7: 7, 9: 9}
for i, v in dict.items():
dict[i] = v**2
print(dict)
# Forma 2
chaves = [1, 4, 5, 6, 7, 9]
dict2 = {}
for cont in chaves:
dict2[cont] = cont**2
print(dict2)
|
994,416 | b1fee8a8e4bb5df2d24f1d3a73d7b44dbe384d9e | def primo(n):
for i in range(0,n):
num = int(input())
s = 0
j=1
while j <= num:
if num % j == 0:
s = s + 1
j = j + 1
if s > 2:
num.append(n_primo)
else:
num.append(eh_primo)
n = int(input())
n_primo = []
eh_primo = []
print(n_primo)
print(eh_primo)
|
994,417 | 73efe17a47c52eca33237f5a15f0cdf702c4d3fc | import requests
from src.general.constants import PROD_BASE_URL as base_url
def get_employees_by_area(area_id):
url = base_url + 'personal/excel/personal'
querystring = {'idArea' : area_id}
payload = ''
headers = {
'cache-control': 'no-cache'
}
response = requests.request('GET', url, data=payload, headers=headers, params=querystring)
json_data = response.json()
return json_data
|
994,418 | dcab2fd158e1469d0b06caa99ff4de156fc16bf2 | # Contains testing utilities for tensor-train code
import numpy as np
import numpy.linalg as la
class Grid:
def __init__(self, gridIndices):
# Note: this explicit initialization is only temporary...
self.gridIndices = gridIndices
self.dim = len(self.gridIndices)
def applyFunction(self, fcn):
'''
Helper that applies the specified function at every point on the grid.
:param fcn: The function to apply
:return void
'''
self.recurse(0, np.zeros(self.dim), fcn)
def recurse(self, idx, curpoint, fcn, shuffle=False):
'''
Helper for apply-function, recursively stepping through each dimension of the grid
:param idx:
:param curpoint:
:param fcn:
:return:
'''
if idx == self.dim:
fcn(curpoint.astype(int))
else:
# Here, shuffle the points in some random order for the SGD
indices = [i for i in range(len(self.gridIndices[idx]))]
if shuffle:
np.random.shuffle(indices)
for i in indices:
curpoint[idx] = i
self.recurse(idx + 1, curpoint, fcn)
def pointArrayHelper(self, idx, curpoint, arr, arrIdx):
if idx == self.dim:
arr[arrIdx[0]] = curpoint
arrIdx[0] += 1
else:
# Here, shuffle the points in some random order for the SGD
indices = [i for i in range(len(self.gridIndices[idx]))]
for i in indices:
curpoint[idx] = self.gridIndices[idx][i]
self.pointArrayHelper(idx + 1, curpoint, arr, arrIdx)
def getPointArray(self):
arrIdx = [0]
gridDims = [len(x) for x in self.gridIndices]
arr = np.zeros((np.prod(gridDims), len(gridDims)))
self.pointArrayHelper(0, np.zeros(len(gridDims)), arr, arrIdx)
return arr
# Define a very simple test function, and a utility to return grids of varying sizes
def polytest4(params):
return 2 * params[0] ** 2 + 3 * params[1] * params[2] ** 2 + 5 * params[2] ** 2 * params[3] ** 4
def polytest3(params):
return 2 * params[0] ** 2 + 3 * params[1] * params[2] ** 2 + 5 * params[2] ** 2
def polytest2(params):
return params[0] ** 2 + params[0] * params[1] ** 2 + params[1] ** 3
def getEquispaceGrid(n_dim, rng, subdivisions):
'''
Returns a grid of equally-spaced points in the specified number of dimensions
n_dim : The number of dimensions to construct the tensor grid in
rng : The maximum dimension coordinate (grid starts at 0)
subdivisions: Number of subdivisions of the grid to construct
'''
return Grid(np.array([np.array(range(subdivisions + 1)) * rng * 1.0 / subdivisions for i in range(n_dim)])) |
994,419 | a882436b6ec317d1e0fd8f9084772bfc055a563d | import sys
from PyQt5.QtWidgets import QApplication, QStyleFactory
from enum import Enum
from cocomo import Cocomo
from cocomo_model import CocomoModel
from cocomo_view import CocomoView
import json
# Hecho por Saúl Núñez Castruita
class CocomoController():
def __init__(self):
app = QApplication(sys.argv)
self.view = CocomoView(self)
self.modelo = CocomoModel(self, lambda esfuerzo, tiempo_desarrollo, personal, pr,
loc, pf, di: self.view.mostrar_calculos_cocomo(esfuerzo, tiempo_desarrollo, personal, pr, loc, pf, di))
#self.establecer_modelo_vista(self.modelo.modelo)
#self.establecer_tipo_vista(self.modelo.tipo)
#app.setStyle(QStyleFactory.create("Fusion"))
print(type(self.modelo))
sys.exit(app.exec_())
def reestablecer_modelo(self):
self.modelo.reset()
def definir_modelo(self, modelo):
print('Establecer' + str(modelo))
self.modelo.establecer_modelo(modelo)
def establecer_modelo_vista(self, modelo):
self.view.cambiar_modelo(modelo)
def definir_tipo(self, tipo):
self.modelo.establecer_tipo(tipo)
def establecer_tipo_vista(self, tipo):
self.view.cambiar_tipo(tipo)
def gti_cambiado(self, valores):
try:
self.modelo.calcularGti(valores)
except AttributeError:
pass
def fae_cambiado(self, valores):
try:
self.modelo.calcularFae(valores)
except AttributeError:
pass
# pass
def cocomo_calculado(self, esfuerzo, tiempo_desarrollo, personal, pr, loc, pf, di):
self.view.mostrar_calculos_cocomo(
esfuerzo, tiempo_desarrollo, personal, pr, loc, pf, di)
def calcularPf(self, entradas, salidas, peticiones, archivos, interfaces):
self.modelo.calcularPf(
entradas, salidas, peticiones, archivos, interfaces)
def salvar(self, fileName):
# with open(fileName, "w") as write_file:
# json.dump(model, write_file)
pass
def abrir(self, fileName):
pass
def definir_lenguaje_programacion(self, lenguajes):
print(lenguajes)
self.modelo.establecer_lenguajes(lenguajes)
if __name__ == '__main__':
ccm = CocomoController()
|
994,420 | 33d5dc48dcb74999434d5ca31216142349ca02b4 | formatter1 = "{} {} {} {}"
formatter2 = "{} {} {}"
formatter3 = "{} {} "
formatter4 = "{}"
name="SHRITAM"
print(formatter1.format(1, 2, 3, 4))
print(formatter1.format("I","AM",name,"."))
print(formatter1.format("*","*","*","*"))
print(formatter2.format("*","*","*"))
print(formatter3.format("*","*"))
print(formatter4.format("*")) |
994,421 | 42419038c81541d0511adcf4eba3b6b3b67de7b3 | counter = 0
sum = 0
for i in range(0,20,5):
sum = sum + i
counter = counter + 1
print(i)
print("the sum is:",sum)
print("the average is:",sum / counter)
print(counter) |
994,422 | 74b4dbee5ed9a5a722d2d656b7c464d5f359a640 | import matplotlib.pyplot as plt
def display_rgbd(images):
# Displays a rgb image and a depth image side by side
# Can take more than two images
plt.figure(figsize=(15, len(images) * 5))
for i in range(len(images)):
plt.subplot(1, len(images), i + 1)
if i < 1:
plt.title("RGB image")
else:
plt.title("Depth image")
plt.imshow(images[i])
plt.axis('off')
plt.show()
return None
|
994,423 | b3c0f180b4145fe3b422de1f0f208c02d9890452 | import logging
from typing import Optional, Pattern
import sqlalchemy as sa
from aiohttp import web
from pydantic import BaseModel, ValidationError, validator
from servicelib.aiohttp.application_setup import ModuleCategory, app_module_setup
from ._meta import api_vtag
from .constants import (
APP_DB_ENGINE_KEY,
APP_PRODUCTS_KEY,
RQ_PRODUCT_KEY,
RQ_PRODUCT_FRONTEND_KEY,
X_PRODUCT_NAME_HEADER,
)
from .db_models import products
from .statics import FRONTEND_APPS_AVAILABLE, FRONTEND_APP_DEFAULT
from aiopg.sa.engine import Engine
log = logging.getLogger(__name__)
class Product(BaseModel):
# pylint:disable=no-self-use
# pylint:disable=no-self-argument
name: str
host_regex: Pattern
@validator("name", pre=True, always=True)
def validate_name(cls, v):
if v not in FRONTEND_APPS_AVAILABLE:
raise ValueError(
f"{v} is not in available front-end apps {FRONTEND_APPS_AVAILABLE}"
)
return v
async def load_products_from_db(app: web.Application):
# load from database defined products and map with front-end??
app_products = []
engine: Engine = app[APP_DB_ENGINE_KEY]
async with engine.acquire() as conn:
stmt = sa.select([products.c.name, products.c.host_regex])
async for row in conn.execute(stmt):
try:
app_products.append(Product(name=row[0], host_regex=row[1]))
except ValidationError as err:
log.error("Discarding invalid product in db %s: %s", row, err)
app[APP_PRODUCTS_KEY] = app_products
def discover_product_by_hostname(request: web.Request) -> Optional[str]:
for product in request.app[APP_PRODUCTS_KEY]:
if product.host_regex.search(request.host):
return product.name
return None
def discover_product_by_request_header(request: web.Request) -> Optional[str]:
requested_product = request.headers.get(X_PRODUCT_NAME_HEADER)
if requested_product:
for product in request.app[APP_PRODUCTS_KEY]:
if requested_product == product.name:
return requested_product
return None
@web.middleware
async def discover_product_middleware(request, handler):
#
# - request[RQ_PRODUCT_KEY] is set to discovered product in 3 types of entrypoints
# - if no product discovered, then it is set to default
#
# API entrypoints: api calls
if request.path.startswith(f"/{api_vtag}"):
product_name = (
discover_product_by_request_header(request)
or discover_product_by_hostname(request)
or FRONTEND_APP_DEFAULT
)
request[RQ_PRODUCT_KEY] = product_name
# Publications entrypoint: redirections from other websites. SEE studies_access.py::access_study
elif request.path.startswith("/study/"):
product_name = discover_product_by_hostname(request) or FRONTEND_APP_DEFAULT
request[RQ_PRODUCT_FRONTEND_KEY] = request[RQ_PRODUCT_KEY] = product_name
# Root entrypoint: to serve front-end apps
elif request.path == "/":
product_name = discover_product_by_hostname(request) or FRONTEND_APP_DEFAULT
request[RQ_PRODUCT_FRONTEND_KEY] = request[RQ_PRODUCT_KEY] = product_name
response = await handler(request)
return response
@app_module_setup(
__name__, ModuleCategory.ADDON, depends=["simcore_service_webserver.db"], logger=log
)
def setup_products(app: web.Application):
app.middlewares.append(discover_product_middleware)
app.on_startup.append(load_products_from_db)
|
994,424 | 4c85ba855385fb8db91f95dcbca2564da715e866 | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from .models import Post,Category
from django.shortcuts import render, get_object_or_404
from comments.forms import CommentForm
import markdown
def index(request):
#return HttpResponse('welcome to my blog index!')
post_list=Post.objects.all().order_by('-created_time')
return render(request,'bump_world/index.html',context={'post_list':post_list})
def detail(request,pk):
post=get_object_or_404(Post,pk=pk)
post.body=markdown.markdown(post.body,extensions=['markdown.extensions.extra','markdown.extensions.codehilite','markdown.extensions.toc'])
form=CommentForm()
comment_list=post.comment_set.all()
context={'post':post,'form':form,'comment_list':comment_list}
return render(request,'bump_world/detail.html',context=context)
def archives(request, year, month):
post_list=Post.objects.filter(created_time__year=year,created_time__month=month,).order_by('-created_time')
return render(request,'bump_world/index.html',context={'post_list':post_list})
def category(request, pk):
cate = get_object_or_404(Category, pk=pk)
post_list = Post.objects.filter(category=cate).order_by('-created_time')
return render(request, 'bump_world/index.html', context={'post_list': post_list})
|
994,425 | 6551a27e210b33b26b6962b273751e40a1955a2e | # Generated by Django 3.0.7 on 2020-06-16 11:01
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('learning_partners', '0002_entry'),
]
operations = [
migrations.DeleteModel(
name='Entry',
),
]
|
994,426 | 0097a2fec8bae3318b472164eb23c84c586c297f | # Copyright 2013 Pervasive Displays, Inc.
#
# 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.
import sys
import os
import time
from PIL import Image
from PIL import ImageOps
from EPD import EPD
def main(argv):
"""main program - display list of images"""
epd = EPD()
epd.clear()
print('panel = {p:s} {w:d} x {h:d} version={v:s}'.format(p=epd.panel, w=epd.width, h=epd.height, v=epd.version))
for file_name in argv:
if not os.path.exists(file_name):
sys.exit('error: image file{f:s} does not exist'.format(f=file_name))
print('display: {f:s}'.format(f=file_name))
display_file(epd, file_name)
def display_file(epd, file_name):
"""display centre of image then resized image"""
image = Image.open(file_name)
image = ImageOps.grayscale(image)
# crop to the middle
w,h = image.size
x = w / 2 - epd.width / 2
y = h / 2 - epd.height / 2
cropped = image.crop((x, y, x + epd.width, y + epd.height))
bw = cropped.convert("1", dither=Image.FLOYDSTEINBERG)
epd.display(bw)
epd.update()
time.sleep(3) # delay in seconds
rs = image.resize((epd.width, epd.height))
bw = rs.convert("1", dither=Image.FLOYDSTEINBERG)
epd.display(bw)
epd.update()
time.sleep(3) # delay in seconds
# main
if "__main__" == __name__:
if len(sys.argv) < 2:
sys.exit('usage: {p:s} image-file'.format(p=sys.argv[0]))
main(sys.argv[1:])
|
994,427 | 614881049c0ed94d650c4eb81058855921eb2509 | from rest_framework import status
from rest_framework.authentication import SessionAuthentication, BasicAuthentication
from rest_framework.decorators import api_view, authentication_classes, permission_classes
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from ReminderApp.models import Reminder
from ReminderApp.serializers import ReminderSerializer
from Assignment.tasks import post_reminder
@api_view(['GET', 'POST'])
@authentication_classes([SessionAuthentication, BasicAuthentication])
@permission_classes([IsAuthenticated])
def reminder_list(request):
if request.method == 'GET':
reminders = Reminder.objects.all()
serializer = ReminderSerializer(reminders, many=True)
return Response(serializer.data)
elif request.method == 'POST':
serializer = ReminderSerializer(data=request.data)
if serializer.is_valid():
reminder = serializer.save()
post_reminder.apply_async(kwargs={'text': reminder.text, 'callback_url': reminder.callback_url},
countdown=reminder.delay * 60)
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
@api_view(['DELETE'])
@authentication_classes([SessionAuthentication, BasicAuthentication])
@permission_classes([IsAuthenticated])
def reminder_detail(request, pk):
try:
reminder = Reminder.objects.get(id=pk)
except Reminder.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
if request.method == 'DELETE':
reminder.delete()
return Response(status=status.HTTP_204_NO_CONTENT)
|
994,428 | 2db613b1d09e9489cd7cebf08903e1870225d46a | import math
SENSE_RADIUS = 7.0
TREE_RADIUS = 1.0
TRI_DX = 4.2
TRI_DY = TRI_DX / 2 * math.sqrt(3)
RANGE = 3
def triangle_clusters(mx, my):
xi = int(2 * mx / TRI_DX)
yi = int(2 * my / TRI_DY)
coords = []
cands = []
for i in range(-RANGE, RANGE + 1):
for j in range(-RANGE, RANGE + 1):
cands.append((i, j))
x = xi + i
y = yi + j
ok = False
if x % 2 == 0 and y % 2 == 0:
ok = True
elif y % 4 == 1 and x % 3 < 2:
ok = True
elif y % 4 == 0 and x % 6 == 1:
ok = True
elif y % 4 == 2 and x % 6 == 3:
ok = True
if not ok:
continue
xf = x * TRI_DX / 2 + (y % 4) * TRI_DX / 4
yf = y * TRI_DY / 2
#dx = mx - xf
#dy = my - yf
#dist = math.sqrt(dx * dx + dy * dy)
#if dist > SENSE_RADIUS - TREE_RADIUS:
# continue
coords.append((i, j))
#print len(cands)
#print len(coords)
#print xi, yi
#print coords
return xi, yi, coords
def search_triangle_clusters():
mx = 400.5 + TRI_DX * 6
my = 134.1 + TRI_DY * 4
d = {}
c = set()
for i in range(0, 100):
for j in range(0, 100):
xi, yi, coords = triangle_clusters(mx + i, my + j)
c.add(str(coords))
key = (xi % 6, yi % 4)
if key in d:
assert coords == d[key], (coords, d[key])
else:
d[key] = coords
print len(d)
for k, v in d.items():
print k, len(v)
print len(c)
#for k in c: print k
print "public static final int[][][][] DATA = {"
for x in range(0, 6):
print "{"
for y in range(0, 4):
print "{"
v = d[(x, y)]
for point in v:
print "{ %s, %s }, " % point,
print "},"
print "},"
print "};"
def main():
search_triangle_clusters()
if __name__ == "__main__":
main()
|
994,429 | d11d594cb858085d6f1d694a332bdf5c80762bef | """
"""
from itertools import repeat
from ...cfg import CFG
__all__ = [
# vanilla xception
"xception_vanilla",
# custom xception
"xception_leadwise",
]
xception_vanilla = CFG()
xception_vanilla.fs = 500
xception_vanilla.groups = 1
_base_num_filters = 8
xception_vanilla.entry_flow = CFG(
init_num_filters=[_base_num_filters * 4, _base_num_filters * 8],
init_filter_lengths=31,
init_subsample_lengths=[2, 1],
num_filters=[
_base_num_filters * 16,
_base_num_filters * 32,
_base_num_filters * 91,
],
filter_lengths=15,
subsample_lengths=2,
subsample_kernels=3,
)
xception_vanilla.middle_flow = CFG(
num_filters=list(repeat(_base_num_filters * 91, 8)),
filter_lengths=13,
)
xception_vanilla.exit_flow = CFG(
final_num_filters=[_base_num_filters * 182, _base_num_filters * 256],
final_filter_lengths=3,
num_filters=[[_base_num_filters * 91, _base_num_filters * 128]],
filter_lengths=17,
subsample_lengths=2,
subsample_kernels=3,
)
xception_leadwise = CFG()
xception_leadwise.fs = 500
xception_leadwise.groups = 12
_base_num_filters = 12 * 2
xception_leadwise.entry_flow = CFG(
init_num_filters=[_base_num_filters * 4, _base_num_filters * 8],
init_filter_lengths=31,
init_subsample_lengths=[2, 1],
num_filters=[
_base_num_filters * 16,
_base_num_filters * 32,
_base_num_filters * 91,
],
filter_lengths=15,
subsample_lengths=2,
subsample_kernels=3,
)
xception_leadwise.middle_flow = CFG(
num_filters=list(repeat(_base_num_filters * 91, 8)),
filter_lengths=13,
)
xception_leadwise.exit_flow = CFG(
final_num_filters=[_base_num_filters * 182, _base_num_filters * 256],
final_filter_lengths=17,
num_filters=[[_base_num_filters * 91, _base_num_filters * 128]],
filter_lengths=3,
subsample_lengths=2,
subsample_kernels=3,
)
|
994,430 | 1e81f585c163815a2c1def0831b3a4b413ad13ec | from django.conf.urls import url, include
from django.contrib import admin
from . import views
urlpatterns = [
url(r'^$', views.senate_home, name='senate-home'),
url(r'^constitution/$', views.senate_constitution, name='senate-constitution'),
url(r'^minutes/$', views.minutes, name='senate-minutes-home'),
url(r'^minutes/(?P<minutesid>\d+)/$', views.minutes_specific, name='senate-minutes-specific')
] |
994,431 | cf06b53554f855eb98f1f493176209a0773b0ef3 | import sqlite3
from sqlite3 import Error
import os.path
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
db_path = os.path.join(BASE_DIR, "../db/breaches.db")
def create_connection():
""" create a database connection to the SQLite database
specified by the db_file
:param db_file: database file
:return: Connection object or None
"""
try:
conn = sqlite3.connect(db_path)
return conn
except Error as e:
print(e)
return None |
994,432 | b0b3d4fc6c3a306626e6593801eccf32556682ff | import os
import unittest
from setuptools import setup, find_packages
def discover_tests():
test_loader = unittest.TestLoader()
test_suite = test_loader.discover("tests", pattern="test_*.py")
return test_suite
def read(filename):
filepath = os.path.join(os.path.dirname(__file__), filename)
with open(filepath, mode="r", encoding="utf-8") as f:
return f.read()
setup(
name="catalyst-dynamic-text-classification",
description="Reimplementation of the paper by ASAPP Research using catalyst",
author="Dmitry Kryuchkov",
packages=find_packages(),
install_requires=read("requirements.txt").splitlines(),
tests_require=["pytest"],
test_suite="setup.discover_tests",
zip_safe=True,
)
|
994,433 | 00f4835aefe7d0a045b0986ebd87e534b1df0476 | __version__ = "v2.0.0"
|
994,434 | 5dc4e774ae19c3cda2641b6a26bee6ae75070cbf | import UDPComm
import PIDValues
if __name__ == '__main__':
udpComm = UDPComm.UDPComm('10.1.95.22', 5808)
udpComm.connect()
try:
while True:
udpComm.sendPIDData(PIDValues.PIDValues(2, 1, 2, 3, 4))
print(udpComm.getResponseData())
except KeyboardInterrupt:
udpComm.close()
|
994,435 | c5ecfad5b46454e0a61ef2ad3284cd9e81a6c521 | import os
import requests as req
from bs4 import BeautifulSoup as soup
import json
# GENERAL CONSTANTS
WORKING_DIRECTORY = "F:\\Read Anime\\Light-Novel\\Books\\{}"
WORKING_FILE_DIRECTORY = "F:\\Read Anime\\Light-Novel\\Books\\{}\\{}"
TESTING_FILE_DIRECTORY = "F:\\Read Anime\\Light-Novel\\Books\\{}\\tests\\{}"
FIRST_CHAPTER_CLASS = "collapseomatic_content"
COMMAND_PREFIX = "[DDL] > "
FILE_FORMAT = ".html"
ENCODING = "utf-8"
JSON_DATA = "data.json"
HTML_PARSE_FORMAT = 'html.parser'
SOURCE = "https://www.divinedaolibrary.com/"
json_data = open(JSON_DATA)
LIBRARY = json.load(json_data)
json_data.close()
# CONSOLE COMMANDS
COMMANDS = ['ADD', 'UPDATE', 'NOVELS', 'EXIT', 'HELP']
EXIT_COMMAND = COMMANDS[3]
LIST_COMMAND = COMMANDS[2]
ADD_COMMAND = COMMANDS[0]
UPDATE_COMMAND = COMMANDS[1]
HELP_COMMANDS = COMMANDS[4]
# JSON DATA KEYS
LATEST_CHAPTER = 'local_latest_chapter'
LATEST_CHAPTER_URL = 'local_latest_chapter_url'
# CONSOLE MESSAGES
NO_UPDATES_MESSAGE = "[NO UPDATES] There were no recent updates beyond {}."
LAST_CHAPTER_MESSAGE = "[LAST CHAPTER] {} is the last chapter."
NEW_CHAPTER_MESSAGE = "[NEW CHAPTER] Getting {}..."
DOWNLOAD_ERROR_MESSAGE = "[DOWNLOAD ERROR] There was an error while trying to get {}"
HTTP_REQUEST_MESSAGE = "[FETCHING DATA] Fetching data from the internet using http requests"
CONNECTION_ERROR_MESSAGE = "[CONNECTION ERROR] There was a problem connecting to DDL"
COMPLETE_MESSAGE = "[SUCCESS] All updates have successfully been downloaded"
LATEST_CHAPTER_MESSAGE = "[LATEST CHAPTER] {} is the last chapter."
NOVEL_MESSAGE = "[UPDATING NOVEL] {}"
COMMAND_ERROR = "[COMMAND ERROR] Your command is invalid!"
EXIT_MESSAGE = "[EXITING] The application is exiting. Goodbye!"
COMMAND_OVERVIEW_MESSAGE = "[COMMAND] Command: {}, Target: {}"
INVALID_LINK = "[INVALID LINK] '{}' does not exist in the Divine Dao Library"
# JSON INJECTS
BACKUP = '''
{
"martial peak": {
"local_latest_chapter": "Martial Peak Chapter 1563",
"local_latest_chapter_url": "https://www.divinedaolibrary.com/martial-peak-chapter-1563-return-to-spider-mothers-den/"
}
}
'''
# HTML INJECTS
BOILER = '''
<html>
<body>
<center>
<div class = "main-content">
{}
<br><hr><br>
{}
</div>
</center>
</body>
{}
</html>
'''
TITLE = '''
<h1 chass = "main-title">{}</h1>
'''
PARAGRAPH = '''
<p>
{}
</p>
'''
STYLE = '''
<style>
body {
color: #484848;
line-height: 1.625;
background-color : #EEEEEE !important;
}
h1 {
font-size: 35px;
letter-spacing: 0;
line-height: 140%;
font-weight: 600;
margin-top: 10px;
margin-right: auto;
margin-bottom: 10px;
margin-left: auto;
font-family: 'Lato',sans-serif;
text-align: center;
color: #000000;
}
.main-content {
background-color : #FFFFFF;
width : 850px;
padding-top: 25px;
padding-right: 35px;
padding-bottom: 25px;
padding-left: 35px;
box-shadow: 0 0 15px rgba(0,0,0,.05);
}
.main-content p {
font-size: 20px !important;
font-family: 'Lato',sans-serif;
text-align: left;
}
p {
margin-bottom: 1.5em;
line-height: 28px;
}
</style>
'''
READER = '''
<!DOCTYPE html>
<html>
<head>
<title>
{0}
</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="mainArea" class="card">
<div>
<ul>
<li class="inline"><button id="9" onclick="incS(9)">
<h2>9</h2>
</button></li>
<li class="inline"><button id="8" onclick="incS(8)">
<h2>8</h2>
</button></li>
<li class="inline"><button id="7" onclick="incS(7)">
<h2>7</h2>
</button></li>
<li class="inline">
<button id="add" onclick="inc()">
<h2>+</h2>
</button>
</li>
</ul>
<ul>
<li class="inline"><button id="6" onclick="incS(6)">
<h2>6</h2>
</button></li>
<li class="inline"><button id="5" onclick="incS(5)">
<h2>5</h2>
</button></li>
<li class="inline"><button id="4" onclick="incS(4)">
<h2>4</h2>
</button></li>
<li class="inline">
<button id="sub" onclick="dec()">
<h2>-</h2>
</button>
</li>
</ul>
<ul>
<li class="inline"><button id="3" onclick="incS(3)">
<h2>3</h2>
</button></li>
<li class="inline"><button id="2" onclick="incS(2)">
<h2>2</h2>
</button></li>
<li class="inline"><button id="1" onclick="incS(1)">
<h2>1</h2>
</button></li>
<li class="inline"><button id="0" onclick="incS(0)">
<h2>0</h2>
</button></li>
</ul>
<ul>
<li class="inline"><button id="next_btn" onclick="load()">
<h2>READ - Ch <span id = 'chapterNum'></span></h2>
</button></li>
<li class="inline"><button id="back" onclick="backspace()">
<h2><<</h2>
</button></li>
</ul>
</div>
</div>
<script>
var Book = {{
tempIndex: '',
index: 1,
chapterloc: '{0}/{0} Chapter ',
chaptersuf: '.html',
}}
window.onload = function() {{
document.getElementById('chapterNum').innerHTML = Book.index;
}}
var load = function() {{
if (Book.tempIndex == '') {{
var link = Book.chapterloc + Book.index + Book.chaptersuf;
window.open(link);
Book.index++;
document.getElementById('chapterNum').innerHTML = Book.index;
console.log(link);
}} else {{
Book.index = Book.tempIndex;
var link = Book.chapterloc + Book.tempIndex + Book.chaptersuf;
window.open(link);
Book.index++;
document.getElementById('chapterNum').innerHTML = Book.index;
Book.tempIndex = '';
}}
}}
var inc = function() {{
Book.index++;
document.getElementById('chapterNum').innerHTML = Book.index;
var link = Book.chapterloc + (Book.index) + Book.chaptersuf;
console.log(link);
}}
var dec = function() {{
Book.index--;
document.getElementById('chapterNum').innerHTML = Book.index;
var link = Book.chapterloc + (Book.index) + Book.chaptersuf;
console.log(link);
}}
var incS = function(a) {{
Book.tempIndex += a;
document.getElementById('chapterNum').innerHTML = Book.tempIndex;
}}
var backspace = function() {{
if (Book.tempIndex != '') {{
Book.tempIndex = Book.tempIndex.slice(0, Book.tempIndex.length - 1);
document.getElementById('chapterNum').innerHTML = Book.tempIndex;
}}
}}
</script>
</body>
</html>
'''
def get_from_soup(url):
try:
html = req.get(url).text
except:
print(CONNECTION_ERROR_MESSAGE)
return (None, None, None)
_soup = soup(html, HTML_PARSE_FORMAT)
title = _soup.find("h1", {"class": "entry-title"}).text.replace('â', '-')
main = _soup.find("div", {"class": "entry-content"}).findAll('p')
title_text = TITLE.format(title)
main_text = ""
for stuff in main:
main_text += PARAGRAPH.format(stuff.text)
html_text = BOILER.format(title_text, main_text, STYLE)
name = title.split(',')[0].replace(' – ', ' ')
try:
next_url = _soup.find(
"div", {"class": "entry-content"}).p.span.findAll('a')[2]['href']
except IndexError:
next_url = _soup.find(
"div", {"class": "entry-content"}).p.span.findAll('a')[1]['href']
except AttributeError:
raise Exception('InvalidLinkError')
return (next_url, html_text, name)
def capital(a):
stuff = a.split(' ')
temp = ""
for b in stuff:
temp += b[0].upper() + b.lstrip(b[0]) + ' '
return temp.strip()
def get_updates(novel):
print(NOVEL_MESSAGE.format(novel))
last_chapter_url = LIBRARY[novel][LATEST_CHAPTER_URL]
next_chapter_url, chapter_html, chapter_name = get_from_soup(
last_chapter_url)
while next_chapter_url != None:
chapter_url = next_chapter_url
try:
print(HTTP_REQUEST_MESSAGE)
next_chapter_url, chapter_html, chapter_name = get_from_soup(
chapter_url)
except:
print(LAST_CHAPTER_MESSAGE.format(
LIBRARY[novel][LATEST_CHAPTER]))
return
print(NEW_CHAPTER_MESSAGE.format(chapter_name))
try:
with open(WORKING_FILE_DIRECTORY.format(novel, chapter_name.replace('-\x80\x93', '–').replace(' – ', ' ') + FILE_FORMAT), "w", encoding=ENCODING) as chapter_file:
# with open(TESTING_FILE_DIRECTORY.format(TARGET_MANGA, chapter_name.replace('-\x80\x93', '–').replace(' – ', ' ') + FILE_FORMAT), "w", encoding=ENCODING) as chapter_file:
chapter_file.write(chapter_html)
with open(JSON_DATA, "w") as json_file:
LIBRARY[novel]["local_latest_chapter"] = chapter_name.replace(
'-\x80\x93', '–').replace(' – ', ' ')
LIBRARY[novel]["local_latest_chapter_url"] = chapter_url
json.dump(LIBRARY, json_file)
pass
except:
print(DOWNLOAD_ERROR_MESSAGE.format(chapter_name))
# print(COMPLETE_MESSAGE)
def add_novel(novel):
print(HTTP_REQUEST_MESSAGE)
link = SOURCE + novel.replace(' ', '-')
try:
html = req.get(link)
except:
print(CONNECTION_ERROR_MESSAGE)
return
if html.status_code == 404:
print(INVALID_LINK.format(novel))
return
_soup = soup(html.text, HTML_PARSE_FORMAT)
first_chapter_link = _soup.find(
"div", {"class": FIRST_CHAPTER_CLASS}).ul.li.span.a['href']
try:
_, chapter_html, chapter_name = get_from_soup(
first_chapter_link)
except Exception:
print('[CHAPTER ERROR] The chapters of this novel are not hosted on DDL')
return
try:
os.mkdir(WORKING_DIRECTORY.format(capital(novel)))
with open(WORKING_FILE_DIRECTORY.format(capital(novel), chapter_name.replace('-\x80\x93', '–').replace(' – ', ' ') + FILE_FORMAT), "w", encoding=ENCODING) as chapter_file:
chapter_file.write(chapter_html)
with open(WORKING_DIRECTORY.format(capital(novel) + FILE_FORMAT), "w", encoding=ENCODING) as reader_file:
reader_file.write(READER.format(capital(novel)))
with open(JSON_DATA, "w") as json_file:
LIBRARY[novel] = {}
LIBRARY[novel]["local_latest_chapter"] = chapter_name.replace(
'-\x80\x93', '–').replace(' – ', ' ')
LIBRARY[novel]["local_latest_chapter_url"] = first_chapter_link
json.dump(LIBRARY, json_file)
except:
print(DOWNLOAD_ERROR_MESSAGE.format(chapter_name))
return
print(f'[SUCCESS] {novel} has been added to your library.')
def help():
print('[COMMANDS]')
for command in COMMANDS:
if command == ADD_COMMAND:
print(" ADD [novel]- Add [novel] to your library")
elif command == UPDATE_COMMAND:
print(
" UPDATE [novel]- Update [novel] in your library. Note: [novel] must be in your library.")
elif command == LIST_COMMAND:
print(" NOVELS - List the novels in your library.")
elif command == HELP_COMMANDS:
print(" HELP - Show help.")
elif command == EXIT_COMMAND:
print(" EXIT - Exit application.")
def novels():
print('[NOVELS]')
for novel in LIBRARY:
print(' ', novel)
pass
while True:
print('')
user_input = input(COMMAND_PREFIX).split(' ')
command = user_input[0].upper()
target = ''
try:
user_input.remove(user_input[0])
for word in user_input:
target += (word + ' ')
target = target.strip()
except IndexError:
pass
except:
pass
if command not in COMMANDS:
print(COMMAND_ERROR)
continue
if command == EXIT_COMMAND:
print(EXIT_MESSAGE)
print('')
break
if command == HELP_COMMANDS:
help()
continue
if command == LIST_COMMAND:
novels()
continue
if command == UPDATE_COMMAND:
if target not in LIBRARY:
print(f'[ERROR] "{target}" is not in your library.')
continue
get_updates(target)
continue
if command == ADD_COMMAND:
if target in LIBRARY:
print(f'[ERROR] "{target}" is already in your library.')
continue
add_novel(target)
continue
|
994,436 | 97bbcaf9172c7e738d576e20ec26f063b4fdaff5 | import unittest
from src.actions.parsers.move.MoveActionDataParser import MoveActionDataParser, MoveDirection, ParseException
class MoveActionDataParserParseToDataTests(unittest.TestCase):
def test_parse_to_data_from_empty_string(self):
with self.assertRaises(ParseException):
MoveActionDataParser.ParseToData("")
def test_parse_to_data_from_irrelevant_string(self):
irrelevant_string = "#Faas83(%@o.0bi9}"
with self.assertRaises(ParseException):
MoveActionDataParser.ParseToData(irrelevant_string)
def test_parse_to_data_from_single_word_but_no_direction_string(self):
for word in MoveActionDataParser.MOVE_WORDS:
with self.assertRaises(ParseException):
MoveActionDataParser.ParseToData(word)
def test_all_valid_direction_one_word_strings(self):
valid_words = {
MoveDirection.UP: MoveActionDataParser.UP_WORDS,
MoveDirection.DOWN: MoveActionDataParser.DOWN_WORDS,
MoveDirection.LEFT: MoveActionDataParser.LEFT_WORDS,
MoveDirection.RIGHT: MoveActionDataParser.RIGHT_WORDS
}
for direction, words in valid_words.items():
for word in words:
self.assertEqual(direction, MoveActionDataParser.ParseToData(word))
def test_all_valid_two_word_strings(self):
first_words = MoveActionDataParser.MOVE_WORDS
valid_words = {
MoveDirection.UP: MoveActionDataParser.UP_WORDS,
MoveDirection.DOWN: MoveActionDataParser.DOWN_WORDS,
MoveDirection.LEFT: MoveActionDataParser.LEFT_WORDS,
MoveDirection.RIGHT: MoveActionDataParser.RIGHT_WORDS
}
for first_word in first_words:
for direction, second_words in valid_words.items():
for second_word in second_words:
self.assertEqual(direction,
MoveActionDataParser.ParseToData("{} {}".format(first_word, second_word)))
def test_parse_to_data_from_relevant_two_word_string(self):
valid_two_word_string = "go north"
expected_direction = MoveDirection.UP
move_action_data = MoveActionDataParser.ParseToData(valid_two_word_string)
self.assertEqual(move_action_data, expected_direction)
|
994,437 | 7b7cb59f8771d6b9d151df5ca6d870f31b130d9b | #!/usr/bin/env python2.7
# mergeBamsE3.py ENCODE3 galaxy pipeline script for merging 2 bam replicates
# Must run from within galaxy sub-directory. Requires settingsE3.txt in same directory as script
#
# Usage: python(2.7) mergeBamsE3,py <inputBamA> <repA> <inputBamB> <repB> <galaxyOutMergedBam> \
# <genome> <expType> <analysisId>
# TODO: Do we really need to track replicate numbers?
import os, sys
from src.galaxyAnalysis import GalaxyAnalysis
from src.steps.mergeBamStep import MergeBamStep
###############
testOnly = False
###############
if sys.argv[1] == '--version':
settingsFile = os.path.split( os.path.abspath( sys.argv[0] ) )[0] + '/' + "settingsE3.txt"
if os.path.isfile( settingsFile ): # Unfortunately can't get xml arg for settings
ana = GalaxyAnalysis(settingsFile, 'versions', 'hg19')
MergeBamStep(ana).writeVersions(allLevels=True) # Prints to stdout
else:
print "Can't locate " + settingsFile
exit(0)
galaxyInputBamA = sys.argv[1]
repA = sys.argv[2]
galaxyInputBamB = sys.argv[3]
repB = sys.argv[4]
galaxyOutMergedBam = sys.argv[5]
genome = sys.argv[6]
expType = sys.argv[7]
anaId = sys.argv[8]
# No longer command line parameters:
scriptPath = os.path.split( os.path.abspath( sys.argv[0] ) )[0]
galaxyPath = '/'.join(scriptPath.split('/')[ :-2 ])
settingsFile = scriptPath + '/' + "settingsE3.txt"
# Set up 'ana' so she can do all the work. If anaId matches another, then it's log is extended
ana = GalaxyAnalysis(settingsFile, anaId, genome, expType)
if testOnly:
ana.dryRun = testOnly
# What step expects:
# Inputs: 2 bam files, pre-registered in the analysis and both keyed as: 'bamRep' + replicateN + '.bam'
# Outputs: 1 merged bam keyed as: 'mergedRep' + replicate1 + 'Rep' +replcicate2 + '.bam'
# set up keys that join inputs through various file forwardings:
bamAkey = 'bamRep' + repA + '.bam'
bamBkey = 'bamRep' + repB + '.bam'
mergedBamKey = 'mergedRep' + repA + 'Rep' + repB + '.bam'
# Establish Inputs for galaxy and nonGalaxy alike
ana.registerFile(bamAkey,'galaxyInput', galaxyInputBamA)
ana.registerFile(bamBkey,'galaxyInput', galaxyInputBamB)
nonGalaxyInput1 = ana.nonGalaxyInput(bamAkey) # Registers and returns the outside location
nonGalaxyInput2 = ana.nonGalaxyInput(bamBkey) # Need to register these to ensure nonGalOut naming
# outputs:
ana.registerFile( mergedBamKey, 'galaxyOutput',galaxyOutMergedBam)
resultsDir = ana.resultsDir(galaxyPath) # prefers nonGalaxyInput location over settings loc
ana.createOutFile(mergedBamKey,'nonGalaxyOutput','%s_%s_merged',ext='bam', \
input1=bamAkey, input2=bamBkey)
# Establish step and run it:
step = MergeBamStep(ana,repA,repB)
sys.exit( step.run() )
|
994,438 | 46b34635190ca3a8346994885d65c8d6fd9c17a2 | import requests, ssl, requests.adapters, socket, json
from requests.packages.urllib3.poolmanager import PoolManager
class HostNameIgnoringAdapter(requests.adapters.HTTPAdapter):
def init_poolmanager(self, connections, maxsize, block=False):
self.poolmanager = PoolManager(num_pools=connections,
maxsize=maxsize,
block=block,
assert_hostname=False)
def upgrade_request(host, cert, path, headers, body=None):
context = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
context.verify_mode = ssl.CERT_REQUIRED
context.load_verify_locations(cert)
context.check_hostname = False
conn = context.wrap_socket(socket.create_connection((host, 443)))
body_s = b''
if body is not None:
body_s = json.dumps(body).encode()
headers = dict({'content-length': len(body_s), 'content-type': 'application/json'}, **headers)
conn.sendall(('POST %s HTTP/1.0\r\n%s\r\n' % (path, ''.join( '%s: %s\r\n' % (k, v) for k, v in headers.items() ))).encode('utf8'))
conn.sendall(body_s)
resp = conn.recv(1)
if resp == b'+':
return conn
else:
raise Exception('connection failed (status: %r)' % resp)
def pipe(sock1, sock2):
try:
while True:
data = sock1.recv(40960)
if not data: break
sock2.sendall(data)
except IOError as err:
print(err)
|
994,439 | daa99a8034682d3ae133abbab60d65b2af49cdc4 | #!/usr/bin/env python2.7
import redis
import urllib2
import json
infra_api = "http://jabber.khrypt.ooo:1337" # Change to your endpoint
r = redis.Redis(unix_socket_path = "/var/run/redis/redis.sock") # Change to your Redis socket
try:
response = urllib2.urlopen("%s/status/ups" % (infra_api))
ups_status = response.read()
except:
ups_status = json.dumps({"status": "broken_link", "charge": 0})
try:
ups_status = json.loads(ups_status)
except:
raise Exception("Malformed JSON received")
r.hmset("khryptooo_ups", ups_status)
|
994,440 | 7424ba519064ec42b98a70cd03c8f6b8785f22a0 | # Copyright (c) Facebook, Inc. and its affiliates.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
from flask import request, Blueprint, jsonify
import models
import tasks.pinger_tasks
import traceback
from main import db, auth, logger, pipong_is_pinger
import inspect
bp = Blueprint('pinger', __name__)
@bp.route('/api/v1.0/start_session', methods=['POST'])
@auth.login_required
def start_session():
"""
Receive a json with the configuration of a new iteration.
The json follows this configuration:
{
"hosts": {
"127.0.0.1": {
"api_port": 5003,
"api_protocol": "http://",
}
},
"tracert_qty": 20,
"master_iteration_id": "myremoteid02"
}
:return:
"""
current_f_name = inspect.currentframe().f_code.co_name
logger.info('{}: Start_session called'.format(current_f_name))
if not pipong_is_pinger():
return jsonify({
'result': 'failure',
'msg': 'this server is not a pinger'
})
response = {'result': 'success'}
data = request.get_json()
logger.info(data)
try:
host_list = data['hosts']
remote_id = data['master_iteration_id']
tracert_qty = data['tracert_qty']
ip_addr = request.remote_addr
exists = db.session.query(
db.session.query(models.PingerIteration).filter_by(
remote_id=str(remote_id)).exists()).scalar()
if not exists:
s = db.session()
iter_t = models.PingerIteration(
status="CREATED",
remote_id=str(remote_id),
remote_address=ip_addr,
tracert_qty=tracert_qty)
s.add(iter_t)
s.flush()
for k, v in host_list.items():
api_port = v['api_port']
api_protocol = v['api_protocol']
ponger_t = models.Ponger(
address=k,
pinger_iteration_id=iter_t.id,
api_port=api_port,
api_protocol=api_protocol)
s.add(ponger_t)
s.flush()
s.commit()
logger.info('{}: New pinger iteration ID:{}'.format(
current_f_name, iter_t.id))
tasks.pinger_tasks.perform_pipong_iteration_1.apply_async(
args=[iter_t.id], kwargs={})
response['ping_iteration_id'] = iter_t.id
else:
logger.error(
'{}: Remote id already registered'.format(current_f_name))
return jsonify({
'result': 'failure',
'msg': 'remote id already registered'
})
logger.info('{}: port_list:{} ip_addr:{} exists:{}'.format(
current_f_name, host_list, ip_addr, exists))
except Exception:
exception_log = traceback.format_exc()
logger.debug('{}: e:{}'.format(current_f_name, exception_log))
jsonify({'result': 'failure', 'msg': exception_log})
return jsonify(response)
|
994,441 | 257200344a616ce115ef5ede73222b530b764736 | """
Confident that your list of box IDs is complete, you're ready to find the boxes full of prototype fabric.
The boxes will have IDs which differ by exactly one character at the same position in both strings. For example, given the following box IDs:
abcde
fghij
klmno
pqrst
fguij
axcye
wvxyz
The IDs abcde and axcye are close, but they differ by two characters (the second and fourth). However, the IDs fghij and fguij differ by exactly one character, the third (h and u). Those must be the correct boxes.
What letters are common between the two correct box IDs? (In the example above, this is found by removing the differing character from either ID, producing fgij.)
"""
from typing import List
from collections import Counter
with open('models/day02.txt') as f:
box_ids: List[str] = [line.strip() for line in f.readlines()]
def compare_two_strings(str1: str, str2: str) -> str:
LENGTH = len(str1)
same_letter_num = 0
different_letter_pos = 0
for i in range(LENGTH):
if str1[i] == str2[i]:
same_letter_num += 1
else:
different_letter_pos = i
if same_letter_num == LENGTH - 1:
return str1[:different_letter_pos] + str1[different_letter_pos + 1:]
def find_the_box(box_ids: List[str]):
for i in range(len(box_ids)):
for j in range(i+1, len(box_ids)):
ret = compare_two_strings(box_ids[i], box_ids[j])
if ret != None:
return ret
print(find_the_box(box_ids))
|
994,442 | 55f17c9e91d97b11a2651fcc0e9fcc0554cd12bd | import time
import random
import matplotlib.pyplot as plt
#Con recursion
def ArraySum(arr):
if len(arr)==1:
return arr[0] #C1=5
else:
return (ArraySum(arr[1:])+arr[0]) #T(n)=C2+T(n-1) donde C2=4
print(ArraySum([2,4,5,10,15,0]))
"""
T(n)=C2+T(n-1)
"""
#%%
times=[]
def plot(times,n,lab):
plt.xlabel('Dimension del problema')
plt.ylabel('Tiempo de complejidad')
plt.plot(range(1000000,n,100000),times,label=lab)
plt.grid()
plt.legend()
plt.show()
def getTime(meth,a,b):
ini = ((time.time()))
meth(a)
fin = ((time.time()))
print(str(fin-ini))
times.append(fin-ini)
n=1000000
while n<=3000001:
arr=[0]*n
for x in range(n):
arr[x]=random.randint(1,10000000)
getTime(ArraySum,arr,n)
n=n+100000
plot(times,3000001,"ArraySum")
|
994,443 | d48a6e4a02e6ffb786301c27461f14b7d438a325 | # Generated by Django 2.1.4 on 2019-01-05 12:31
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('clientes', '0016_auto_20190105_1230'),
]
operations = [
migrations.AlterField(
model_name='pessoa',
name='token',
field=models.CharField(blank=True, default=177983, max_length=14, null=True),
),
]
|
994,444 | fbb5bc1334e7dff8432ebb84022419e8944a5076 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
Author: Wellington Silva a.k.a. Well
Date: July 2017
Name: how2decode-utf16.py
Purpose: Decode data with JavaScript Escape.
Description: Script Based on script CAL9000 by Chris Loomis from OWASP Project, posted at:
<https://www.owasp.org/index.php/Category:OWASP_CAL9000_Project>
Version: 1.0B
Licence: GPLv3
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
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See 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/>.
Other itens: Copyright (c) 2017, How2Security All rights reserved.
'''
import sys
import string
import argparse
sys.path.append('lib-conv')
from utf_16 import CodingUTF16
from colors import *
def main():
usage = '''%(prog)s [--str="data"]'''
parser = argparse.ArgumentParser(usage=usage)
parser.add_argument('--str', action='store', type=str, dest='txt', help='The String Decode')
parser.add_argument("--version", action="version", version="%(prog)s 1.0b")
args = parser.parse_args()
txt = args.txt
if len(sys.argv) == 1:
parser.print_help()
sys.exit(1)
try:
msg = CodingUTF16(txt.lower())
print(color("[+] UTF-16: ", 2, 1) + "%s" % msg.decoded())
except AttributeError:
print(color("\n[!] This data non-UTF-16", 1, 1))
print(color("[*] Please try usage data with how2decoded-brute-force.py\n", 3, 1))
sys.exit(1)
if __name__ == "__main__":
main()
|
994,445 | 9894e1dd59eb08adf26c689fee3da3e8ea014010 | # -*- coding: utf-8 -*-
import Adafruit_DHT
import datetime
def read_sensor():
sensor = 11 # GPIO (BCM notation)
pin = 17
humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
time = datetime.datetime.now()
return str(time) + "\tTemperature={}ºC, Humidity={}%; ".format(temperature, humidity)
while True:
print(read_sensor()) |
994,446 | 8e9cf3cadbf42988f1fe32e57a84c10c3b7d3080 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.model_selection import cross_val_score
from sklearn import svm
from sklearn.cluster import KMeans
from mpl_toolkits.mplot3d import Axes3D
%matplotlib notebook
data = pd.read_csv("sshekha4.csv", header=None)
# First copying the original data to a different variable
originalData = data
# Task 1
# Scatter Plot to show the clustering of the data set
# Using kmeans to find the number of clusters
# First finding the Sum of Squared Errors for different values of k to determine the number of clusters using the elbow method
sse = {}
for k in range(1, 6):
kmeans = KMeans(n_clusters=k)
kmeans.fit(data)
sse[k] = kmeans.inertia_ # This gives the sum of squared distances of the data points to its closest centroid
fig = plt.figure(figsize=(3,3))
plt.plot(list(sse.keys()), list(sse.values()))
plt.xlabel("Number of cluster")
plt.ylabel("SSE")
fig.tight_layout()
plt.show()
# The graph shows that the elbow is clearly visibe at k=2
# Applying k-means with number of clusters=2
kmeans = KMeans(n_clusters=2)
kmeans.fit(data.loc[:, 0:1])
klabels = kmeans.predict(data.loc[:, 0:1])
fig = plt.figure(figsize=(5,5))
ax = fig.add_subplot(111)
ax.scatter(data.loc[:, 0], data.loc[:, 1], c=klabels, cmap='rainbow', marker='o', s=[3]*len(data))
ax.set_xlabel("X1")
ax.set_ylabel("X2")
plt.show()
# Task 2
# Scaling the values
data.loc[:, 0] = data.loc[:, 0].transform(lambda x : x/x.max())
data.loc[:, 1] = data.loc[:, 1].transform(lambda x : x/x.max())
# Scaled values
print(data.loc[:, 0:1])
# Task 3, 4, 5, 6, 7
# Using k-fold validation (k=5). Then, applying the SVM method with a penatly cost
gammaCScores = []
def gammaCfinder(c, g):
model = svm.SVC(kernel='rbf', C=c, gamma=g)
scores = cross_val_score(model, data.values[:,0:2], data.values[:,2:3].ravel(), cv=5)
gammaCScores.append([c, g, scores.mean()])
#Below is the loose grid search
c_range = [2**-5, 2**-3, 2**-1, 2**1, 2**3, 2**5, 2**7, 2**9, 2**11, 2**13, 2**15]
gamma_range = [2**-15, 2**-13, 2**-11, 2**-9, 2**-7, 2**-5, 2**-3, 2**-1, 2**1, 2**3]
for i in c_range:
for j in gamma_range:
gammaCfinder(i, j)
meanScores = []
maxgammaCScore = [-1,-1,-1]
for val in gammaCScores:
meanScores.append(val[2])
if(val[2] > maxgammaCScore[2]):
maxgammaCScore = val
print("Maximum Accuracy (loose grid search): ", max(meanScores))
print("Maximum Accuracy (c, gamma, max. accuracy values) (loose grid search): ", maxgammaCScore)
# Converting the list of accuracies to sets to identify the regions with same accuracy
s = set(meanScores)
# There are 6 different (distinct) accuracies obtained
print("Distinct sets (loose grid search): ", s)
print("Length: ", len(s))
# Before proceeding with the fine grid search, taking a look at the plot for the loose grid search
fig = plt.figure(figsize=(6,6))
ax = fig.add_subplot(111, projection='3d')
ax.scatter([val[0] for val in gammaCScores], [val[1] for val in gammaCScores], [val[2]*100 for val in gammaCScores], c=meanScores, cmap='Set1', marker='o', s=[5]*len(meanScores))
ax.set_xlabel("C")
ax.set_ylabel("gamma")
ax.set_zlabel("% Accuracy")
plt.show()
# There is only one point having a maximum accuracy of 94.12 %. Hence, doing a fine grid search in the neighborhood of that point
# Now, doing the fine grid search
fine_c_range = [2**-7, 2**-6.75, 2**-6.5, 2**-6.25, 2**-6, 2**-5.75, 2**-5.5, 2**-5.25, 2**-5.00, 2**-4.75, 2**-4.5, 2**-4.25, 2**-4, 2**-3.75, 2**-3.5, 2**-3.25, 2**-3]
fine_gamma_range = [2**1, 2**1.25, 2**1.50, 2**1.75, 2**2, 2**2.25, 2**2.50, 2**2.75, 2**3.00, 2**3.25, 2**3.50, 2**3.75, 2**4, 2**4.25, 2**4.5, 2**4.75, 2**5]
# Setting the gammaCScores list to empty to record the new c, gamma, accuracy tuples
gammaCScores = []
for i in fine_c_range:
for j in fine_gamma_range:
gammaCfinder(i, j)
meanScores = []
maxgammaCScore = [-1,-1,-1]
for val in gammaCScores:
meanScores.append(val[2])
if(val[2] > maxgammaCScore[2]):
maxgammaCScore = val
print("Maximum Accuracy (fine grid search): ", max(meanScores))
print("Maximum Accuracy (c, gamma, max. accuracy values) (fine grid search): ", maxgammaCScore)
# Converting the list of accuracies to sets to identify the regions with same accuracy
s = set(meanScores)
# There are 6 different (distinct) accuracies obtained
print("Distinct sets (fine grid search): ", s)
print("Length: ", len(s))
# Task 8
fig = plt.figure(figsize=(6,6))
ax = fig.add_subplot(111, projection='3d')
ax.scatter([val[0] for val in gammaCScores], [val[1] for val in gammaCScores], [val[2]*100 for val in gammaCScores], c=meanScores, cmap='Set1', marker='o', s=[5]*len(meanScores))
ax.set_xlabel("C")
ax.set_ylabel("gamma")
ax.set_zlabel("% Accuracy")
plt.show() |
994,447 | 4705319091571e70c555feb5a99b7000ccd5c8cd | print("Hello World")
print("Hello Sathish")
print("Hello")
print("Ambika")
|
994,448 | 073a626b34d3768ee26e8e6501117a36ae655368 | import pandas as pd
sales = pd.Series([3,5,8,11,13])
dms = pd.Series([1,2,3,4,5])
print('상관계수 :', sales.corr(dms)) # 값이 1에 가까우면 서로 관련이 높다.
|
994,449 | 51662796d18ad0fbe1f7d524d62efb251885f60f | #!/usr/bin/python3
import sys
if __name__ == "__main__":
sys.path.append("..")
search_replace = __import__('1-search_replace').search_replace
my_list = [1, 2, 3, 4, 5, 4, 2, 1, 1, 4, 89]
new_list = search_replace(my_list, 2, 89)
print(new_list)
print(my_list) |
994,450 | e034ae44eeb8539ec202f6a42ec1421981cdcb29 | def start_game(nivel,variables):
"""Muestra la ventana para jugar y todo su desarrollo.\n
Retorna si termino la partida y los datos de ella
"""
from Juego.validarPalabra import es_valida, clasificar
from Juego import pausa,terminarPartida
from Windows import windowSalirJuego
from datetime import date
game_over = False
maquina_pasa_turno = True
window_salir = windowSalirJuego.hacer_ventana()
variables["Timer"].iniciarTimer()
while True:
variables["Window_juego"].Read(0)
if not game_over: #Si no termino el juego:
if variables["Turno"] == 0:
# *******************************************************************************************************************
# ************************************************** TURNO DEL USUARIO **********************************************
# *******************************************************************************************************************
if maquina_pasa_turno:
variables["Window_juego"].Element("-TEXT_JUGADOR-").Update("TU TURNO!\nFORMA UNA PALABRA")
variables["Fichas_jugador"].habilitar()
no_event = True
while no_event:
event,values = variables["Window_juego"].Read(1000)
if event != "__TIMEOUT__":
variables["Timer"].ajustarTiempo()
no_event = False
variables["Timer"].actualizarTimer()
variables["Window_juego"].Element('-RELOJ-').Update(variables["Timer"].tiempoActual())
if variables["Timer"].termino():
game_over = True
game_over_text = "Se acabo el tiempo, fin del juego"
break
#********************************* CLICK EN LA X (CERRAR VENTANA) *********************************
if event is None:
event_salir, values_salir = window_salir.Read()
if event_salir == "-GUARDAR_Y_SALIR2-":
datos_partida = [True,
variables["Bolsa_de_fichas"],
variables["Tablero"],
variables["Fichas_jugador"],
variables["Fichas_maquina"],
variables["Usuario"],
variables["Maquina"],
variables["Timer"].getSegundos(),
variables["Timer"].getMinutos(),
variables["Timer"].getTiempoLimite(),
variables["Turno"],
variables["Confirmar_habilitado"],
variables["Cambiar_habilitado"],
variables["Clases_validas"],
nivel
] #El primer elemento si es True indica que hay una partida guardada, False en caso contrario
else:
datos_partida = [False]
window_salir.Close()
break
#********************************* CLICK EN PAUSA *********************************
elif event == "-PAUSA-":
variables["Timer"].pausar()
output, game_over, datos_partida = pausa.main(nivel,variables)
if output == "-REANUDAR-":
variables["Timer"].reanudar()
elif output in ("-GUARDAR_Y_SALIR-","-SALIR_SIN_GUARDAR-"):
break
elif output == "-TERMINAR_PARTIDA-":
game_over_text = "Fin del juego, partida finalizada"
continue
#********************************* CLICK EN LA FILA DE FICHAS *********************************
elif variables["Fichas_jugador"].click(event) and variables["Fichas_jugador"].estaHabilitada():
if variables["Bolsa_de_fichas"].estaHabilitada(): #Si quiere cambiar fichas:
variables["Fichas_jugador"].agregarFichaACambiar(event,variables["Window_juego"])
else: #Si quiere poner una ficha en el tablero:
variables["Window_juego"].Element("-TEXT_CPU-").Update("")
if not variables["Fichas_jugador"].hayFichaSelected():
variables["Fichas_jugador"].marcarFichaSelected(variables["Window_juego"],event)
else:
variables["Fichas_jugador"].desmarcarFichaSelected(variables["Window_juego"])
variables["Fichas_jugador"].marcarFichaSelected(variables["Window_juego"],event)
variables["Tablero"].habilitar()
#********************************* CLICK EN EL TABLERO *********************************
elif variables["Tablero"].click(event) and variables["Tablero"].estaHabilitado():
ficha = variables["Fichas_jugador"].sacarFicha(variables["Window_juego"])
variables["Tablero"].insertarFicha(event,variables["Window_juego"],ficha)
variables["Cambiar_habilitado"] = False
variables["Tablero"].deshabilitar()
#********************************* CLICK EN CONFIRMAR JUGADA *********************************
elif event == "-CONFIRMAR-" and variables["Confirmar_habilitado"]:
variables["Cambiar_habilitado"] = True
palabra,con_inicio = variables["Tablero"].verificarPalabra()
if es_valida(palabra,nivel,variables["Clases_validas"]): #Si la palabra es válida:
variables["Window_juego"].Element('-TEXT_JUGADOR-').Update('PALABRA CORRECTA!',visible=True)
variables["Usuario"].ingresarPalabra(palabra,variables["Bolsa_de_fichas"].devolverPuntaje(palabra,variables["Tablero"].copiaPalabra(),variables["Tablero"].getCasillasEspeciales()))
variables["Window_juego"].Element('-PALABRAS_JUGADOR-').Update("Palabras ingresadas:",variables["Usuario"].getPalabras())
variables["Window_juego"].Element("-PUNTOS_JUGADOR-").Update(str(variables["Usuario"].getPuntaje()))
cant_letras = len(palabra)
if con_inicio:
cant_letras -= 1
nuevas_fichas = variables["Bolsa_de_fichas"].letras_random(cant_letras)
#Verificar si se pueden reponer las fichas usadas:
if nuevas_fichas == []:
#fin del juego
game_over = True
game_over_text = "No hay mas fichas, juego terminado"
else:
variables["Fichas_jugador"].insertarFichas(variables["Window_juego"],nuevas_fichas)
variables["Tablero"].reiniciarPalabra()
variables["Turno"] = 1
else: #Si la palabra no es válida:
variables["Window_juego"].Element('-TEXT_JUGADOR-').Update('PALABRA INCORRECTA!\nINTENTE NUEVAMENTE',visible=True)
fichas_a_devolver = variables["Tablero"].devolverFichas(variables["Window_juego"])
variables["Fichas_jugador"].insertarFichas(variables["Window_juego"],fichas_a_devolver)
#********************************** CLICK EN CAMBIAR FICHAS *********************************
elif event == "-CAMBIAR_PASAR-" and variables["Cambiar_habilitado"]:
if variables["Usuario"].getCambiosFichas() != 0: #Si tiene cambios disponibles:
if variables["Fichas_jugador"].hayFichaSelected():
variables["Fichas_jugador"].desmarcarFichaSelected(variables["Window_juego"])
variables["Tablero"].deshabilitar()
variables["Confirmar_habilitado"] = False
variables["Bolsa_de_fichas"].habilitar()
variables["Window_juego"].Element("-TEXT_JUGADOR-").Update("SELECCIONA LAS FICHAS\nPARA CAMBIAR")
variables["Window_juego"].Element("-TEXT_CPU-").Update("")
variables["Window_juego"].Element('-ACEPTAR-').Update(visible=True)
variables["Window_juego"].Element("-CANCELAR-").Update(visible=True)
else: #Si no tiene cambios disponibles
variables["Usuario"].pasarTurno()
variables["Window_juego"].Element("-TEXT_JUGADOR-").Update("HAS PASADO EL TURNO")
variables["Turno"] = 1
if (variables["Usuario"].getTurnosPasados() == 3):
variables["Window_juego"].Element("-CAMBIAR_PASAR-").Update(image_filename=r"Data\Images\Juego\Botones\boton-cambiar-fichas.png")
variables["Usuario"].verificarTurnosPasados()
#********************************* CLICK EN ACEPTAR (CAMBIAR FICHAS) *********************************
elif event == '-ACEPTAR-':
variables["Usuario"].restarCambio()
variables["Confirmar_habilitado"] = True
if variables["Fichas_jugador"].cambiarFichas(variables["Window_juego"],variables["Bolsa_de_fichas"]): #Si se pudo reponer todas las fichas a cambiar:
variables["Bolsa_de_fichas"].deshabilitar()
variables["Window_juego"].Element("-TEXT_JUGADOR-").Update("")
variables["Window_juego"].Element('-ACEPTAR-').Update(visible=False)
variables["Window_juego"].Element('-CANCELAR-').Update(visible=False)
variables["Turno"] = 1
else: #Si no se pudieron reponer todas las fichas a cambiar:
#Se termina el juego porque no hay fichas suficientes
game_over = True
game_over_text = "No hay mas fichas, juego terminado"
if (variables["Usuario"].getCambiosFichas() == 0): #Si no le quedan mas cambios de ficha:
#Se actualiza el boton de "cambiar fichas" a "pasar turno"
variables["Window_juego"].Element('-CAMBIAR_PASAR-').Update(image_filename=r"Data\Images\Juego\Botones\boton-pasar-turno.png")
#********************************* CLICK EN CANCELAR (CAMBIAR FICHAS) *********************************
elif event == '-CANCELAR-':
variables["Bolsa_de_fichas"].deshabilitar()
variables["Window_juego"].Element('-ACEPTAR-').Update(visible=False)
variables["Window_juego"].Element('-CANCELAR-').Update(visible=False)
variables["Window_juego"].Element("-TEXT_JUGADOR-").Update("")
variables["Fichas_jugador"].cancelarCambioDeFichas(variables["Window_juego"])
variables["Confirmar_habilitado"] = True
maquina_pasa_turno = False
else:
# *******************************************************************************************************************
# ********************************************* TURNO DE LA MAQUINA *************************************************
# *******************************************************************************************************************
variables["Window_juego"].Element("-TEXT_CPU-").Update("TURNO DEL OPONENTE")
variables["Window_juego"].Read(timeout=1000)
variables["Timer"].actualizarTimer()
variables["Window_juego"].Element('-RELOJ-').Update(variables["Timer"].tiempoActual())
if variables["Timer"].termino():
game_over = True
game_over_text = "Se acabo el tiempo, fin del juego"
else: #Si no se acabo el tiempo de la partida:
#la maquina intenta armar una palabra con sus fichas:
variables["Window_juego"].Element("-TEXT_JUGADOR-").Update("")
palabra_maquina, cant_letras_a_cambiar = variables["Maquina"].armarPalabra(variables["Fichas_maquina"],variables["Bolsa_de_fichas"],variables["Tablero"],nivel,variables["Clases_validas"])
if palabra_maquina != 'xxxxxx': #Si encontro una palabra válida:
variables["Window_juego"].Element("-TEXT_CPU-").Update("PALABRA CORRECTA!")
palabra_armada = True
variables["Maquina"].insertarPalabra(palabra_maquina, variables["Tablero"], variables["Window_juego"], variables["Tablero"].getTamaño()) #Inserta la palabra en el tablero
variables["Maquina"].ingresarPalabra(palabra_maquina,variables["Bolsa_de_fichas"].devolverPuntaje(palabra_maquina,variables["Tablero"].copiaPalabra(),variables["Tablero"].getCasillasEspeciales()))
variables["Window_juego"].Element('-PALABRAS_CPU-').Update('Palabras ingresadas:',variables["Maquina"].getPalabras())
variables["Window_juego"].Element("-PUNTOS_CPU-").Update(str(variables["Maquina"].getPuntaje()))
puede_cambiar = True #variable que avisa que se puede hacer el cambio de fichas
else: #Si no pudo formar una palabra:
palabra_armada = False
if variables["Maquina"].getCambiosFichas() == 0: #Si la maquina no tiene más cambios de fichas:
variables["Window_juego"].Element("-TEXT_CPU-").Update("TURNO PASADO")
variables["Maquina"].pasarTurno()
variables["Maquina"].verificarTurnosPasados()
puede_cambiar = False
else: #Si la maquina tiene cambios de fichas:
variables["Window_juego"].Element("-TEXT_CPU-").Update("CAMBIO DE FICHAS")
variables["Maquina"].restarCambio()
puede_cambiar = True
if puede_cambiar: #Si la palabra fue correcta o la maquina tenia cambios de fichas se realiza el cambio
if palabra_armada == False:
letras_maquina_devolver = variables["Fichas_maquina"].getLetras()
variables["Fichas_maquina"].eliminarTodasLasLetras()
nuevas_letras = variables["Bolsa_de_fichas"].letras_random(cant_letras_a_cambiar)
if palabra_armada == False:
variables["Bolsa_de_fichas"].devolverLetras(letras_maquina_devolver)
if nuevas_letras != []: #Si se puede hacer el cambio
variables["Maquina"].nuevasLetras(variables["Fichas_maquina"], nuevas_letras, variables["Tablero"], palabra_armada) #Agrega las nuevas fichas
else: #Si no se pudo hacer el cambio de fichas:
#Se termina el juego porque no hay mas fichas
game_over = True
game_over_text = "No hay mas fichas, juego terminado"
variables["Cambiar_habilitado"] = True
variables["Confirmar_habilitado"] = True
maquina_pasa_turno = True
variables["Turno"] = 0
else: #Si termino el juego:
if variables['Turno'] == 0:
#Si termino el juego en el turno del jugador y no termino de completar una palabra, devuelvo las fichas al jugador
fichas_devolver = variables['Tablero'].devolverFichas(variables['Window_juego'])
variables['Fichas_jugador'].insertarFichas(variables['Window_juego'],fichas_devolver)
total_usuario = terminarPartida.main(variables["Maquina"].getPuntaje(),
variables["Bolsa_de_fichas"].calcularPuntajeLista(variables["Fichas_maquina"].getLetras()),
variables["Fichas_maquina"].getLetras(),
variables["Usuario"].getPuntaje(),
variables["Bolsa_de_fichas"].calcularPuntajeLista(variables["Fichas_jugador"].getLetras()),
variables["Fichas_jugador"].getLetras(),
game_over_text
)
datos_partida = [total_usuario,str(date.today()),nivel]
break
variables["Window_juego"].Close()
return [game_over,datos_partida]
|
994,451 | efdd0f54827aa4a06ed1740a0f6e7ecc64c93dbd | import os
import requests
# To stop the warrnings when doing get/post to https
from requests.packages.urllib3.exceptions import InsecureRequestWarning
requests.packages.urllib3.disable_warnings()
# Define vmanage host, port, user, pass as eviromental variable
#export vmanage_host=IP/FQDN
#export vmanage_port=port
#export vmanage_username=username
#export vmanage_password=password
vmanage_host = os.environ.get("vmanage_host")
vmanage_port = os.environ.get("vmanage_port")
vmanage_username = os.environ.get("vmanage_username")
vmanage_password = os.environ.get("vmanage_password")
base_url = f"https://{vmanage_host}:{vmanage_port}"
url_logout = base_url + "/logout?nocache=1234"
class Sdwan():
def __init__(self, base_url=base_url, url_logout=url_logout, vmanage_host=vmanage_host, vmanage_port=vmanage_port, vmanage_username=vmanage_username, vmanage_password=vmanage_password):
self.base_url = base_url
self.url_logout=url_logout
if vmanage_host is None or vmanage_port is None or vmanage_username is None or vmanage_password is None:
print("some envs are missing. it is mandatory to set those env before running the app")
exit()
self.vmanage_host= vmanage_host
self.vmanage_port=vmanage_port
self.vmanage_username=vmanage_username
self.vmanage_password=vmanage_password
self.sessionid = self.get_jsessionid()
self.token = self.get_token()
if self.token is not None:
self.header = {'Content-Type': "application/json",'Cookie': self.sessionid, 'X-XSRF-TOKEN': self.token}
else:
self.header = {'Content-Type': "application/json",'Cookie': self.sessionid}
print("pripremio header/ulogovao se")
# Try to get cookie
def get_jsessionid(self):
api = "/j_security_check"
url = self.base_url + api
payload = {'j_username' : self.vmanage_username, 'j_password' : self.vmanage_password}
response = requests.post(url=url, data=payload, verify=False)
try:
cookies = response.headers["Set-Cookie"]
jsessionid = cookies.split(";")
return(jsessionid[0])
except:
print("No valid JSESSION ID returned")
exit()
# Try to get token
def get_token(self):
api = "/dataservice/client/token"
url = self.base_url + api
headers = {'Cookie': self.sessionid}
response = requests.get(url=url, headers=headers, verify=False)
if response.status_code == 200:
return(response.text)
else:
return None
def show_users(self):
#random GET API for users list
url = self.base_url + "/dataservice/admin/user"
s=""
response = requests.get(url=url, headers=self.header,verify=False)
if response.status_code == 200:
items = response.json()['data']
else:
s= f"Failed to get list of users {str(response.text)}"
return s
for item in items:
s=s+f"- Username: {item.get('userName')} \\n Group: {item.get('group')} \\n Description: {item.get('description')}\\n\\n"
return s
def show_devices(self):
#random GET API for device list
url = self.base_url + "/dataservice/device"
s=""
response = requests.get(url=url, headers=self.header,verify=False)
if response.status_code == 200:
items = response.json()['data']
else:
s= f"Failed to get list of devices {str(response.text)}"
return s
for item in items:
s=s+f"- Device ID: {item.get('deviceId')}\\n"
return s
def show_controllers(self):
#random GET API for controller list
url = self.base_url + "/dataservice/system/device/controllers"
s=""
response = requests.get(url=url, headers=self.header,verify=False)
if response.status_code == 200:
items = response.json()['data']
else:
s= f"Failed to get list of controllers {str(response.text)}"
return s
for item in items:
s=s+f"- Controller: {item.get('deviceType')}\\n"
return s
def show_vedges(self):
#random GET API for vEdges list
url = self.base_url + "/dataservice/system/device/vedges"
s=""
response = requests.get(url=url, headers=self.header,verify=False)
if response.status_code == 200:
items = response.json()['data']
else:
s= f"Failed to get list of vEdges {str(response.text)}"
return s
for item in items:
s=s+f"vEdge: {item.get('serialNumber')}\\n"
return s
def show_bfd(self, deviceId):
#random GET API for BFD
url = self.base_url + f"/dataservice/device/bfd/sessions?deviceId={deviceId}"
s=""
response = requests.get(url=url, headers=self.header,verify=False)
if response.status_code == 200:
items = response.json()['data']
else:
s= f"Failed to get BFD sessions {str(response.text)}"
return s
for item in items:
s=s+f"BFD session: {item}\\n"
return s
def show_ipsec(self,deviceId):
#random GET API for IPSEC
url = self.base_url + f"/dataservice/device/ipsec/outbound?deviceId={deviceId}"
s=""
response = requests.get(url=url, headers=self.header,verify=False)
if response.status_code == 200:
items = response.json()['data']
else:
s= f"Failed to get ipsec sessions {str(response.text)}"
return s
for item in items:
s=s+f"IPSEC session: {item}\\n"
return s
def logout(self):
# Logout
requests.get(url=self.url_logout, headers=self.header, verify=False,allow_redirects=False)
print("izlogovao se") |
994,452 | a7753881a3d3c992f6afce663846b6e0d40b4dbf | #!/Volumes/Samsung_T5/dev/store-warehouse/venv/bin/python
from django.core import management
if __name__ == "__main__":
management.execute_from_command_line()
|
994,453 | 6345b2f5ceaf5910a8f4e2988ee978d1077fe3ac |
# load rouge for validation
import rouge_score
import datasets
rouge = datasets.load_metric("rouge")
def compute_metrics(pred):
labels_ids = pred.label_ids
pred_ids = pred.predictions
# all unnecessary tokens are removed
pred_str = tokenizer.batch_decode(pred_ids, skip_special_tokens=True)
labels_ids[labels_ids == -100] = tokenizer.pad_token_id
label_str = tokenizer.batch_decode(labels_ids, skip_special_tokens=True)
rouge_output = rouge.compute(predictions=pred_str, references=label_str, rouge_types=["rouge2"])["rouge2"].mid
return {
"rouge2_precision": round(rouge_output.precision, 4),
"rouge2_recall": round(rouge_output.recall, 4),
"rouge2_fmeasure": round(rouge_output.fmeasure, 4),
}
from transformers import BertTokenizer, EncoderDecoderModel
tokenizer = BertTokenizer.from_pretrained("bert-base-uncased")
model = EncoderDecoderModel.from_pretrained("./checkpoint-31500")
model.to("cuda")
test_data = datasets.load_dataset("billsum", "3.0.0", split="test")
# only use 16 training examples for notebook - DELETE LINE FOR FULL TRAINING
batch_size = 64 # change to 64 for full evaluation
def generate_summary(batch):
# Tokenizer will automatically set [BOS] <text> [EOS]
# cut off at BERT max length 512
inputs = tokenizer(batch["text"], padding="max_length", truncation=True, max_length=512, return_tensors="pt")
input_ids = inputs.input_ids.to("cuda")
attention_mask = inputs.attention_mask.to("cuda")
outputs = model.generate(input_ids, attention_mask=attention_mask)
# all special tokens including will be removed
output_str = tokenizer.batch_decode(outputs, skip_special_tokens=True)
batch["pred"] = output_str
return batch
results = test_data.map(generate_summary, batched=True, batch_size=batch_size)
pred_str = results["pred"]
label_str = results["summary"]
rouge_output = rouge.compute(predictions=pred_str, references=label_str, rouge_types=["rouge2"])["rouge2"].mid
print(rouge_output)
"""The fully trained *BERT2BERT* model is uploaded to the 🤗model hub under [patrickvonplaten/bert2bert_cnn_daily_mail](https://huggingface.co/patrickvonplaten/bert2bert_cnn_daily_mail).
The model achieves a ROUGE-2 score of **18.22**, which is even a little better than reported in the paper.
For some summarization examples, the reader is advised to use the online inference API of the model, [here](https://huggingface.co/patrickvonplaten/bert2bert_cnn_daily_mail).
""" |
994,454 | e7df00a27a21e87402999da668f4c29308556828 | from dominion_ai.abstract_player import Player
from dominion_ai.utils import GameStage
import dominion_ai.cards as cards
class GreenGoldPlayer(Player):
def buy_card(self):
"""Implement the "greens and golds" strategy of buying the highest
victory point card (in the game) if possible, and otherwise buying the
highest buyable money card (though never buying coppers). If >3 of the
highest victory point card are owned, then switch to "late_game"
strategy and just buy the highest buyable victory points. After using
the hand to buy a card (or not), discard the rest of the hand."""
print(f"Hand has buying power {self.hand_buying_power}...")
bought_card = None
# by Platinium, if possible
# otherwise (game stage agnostic) can buy a province or colony, always buy it
if ((self.highest_buyable_money == cards.PLATINUM) and
(self.game_stage == GameStage.early_game)):
bought_card = cards.PLATINUM
elif ((self.highest_buyable_victory_points == cards.PROVINCE) or
(self.highest_buyable_victory_points == cards.COLONY)):
bought_card = self.highest_buyable_victory_points
else:
# buy the highest buyable money by default
if (self.highest_buyable_money != cards.COPPER):
bought_card = self.highest_buyable_money
# except if in the late game stage, in which case buy the highest
# buyable victory points instead
if ((self.game_stage == GameStage.late_game) and
(self.highest_buyable_victory_points) and
(self.highest_buyable_victory_points.victory_points > 0)):
bought_card = self.highest_buyable_victory_points
print(f"Late Stage Game, so buying victory points over money")
# explain the play
self.speak_hand()
s = f"for total buying power of {self.hand_buying_power}"
self.game.speak_str(s)
# gain the card bought, if any, to the discard pile:
if bought_card:
s = f"I buy {bought_card.name}"
self.game.speak_str(s)
# gain the card to the discard pile
self.deck.discard.append(bought_card)
self.game.buy_card(bought_card)
else:
s = f"I do not buy anything"
self.game.speak_str(s)
# the whole hand is used up buying the card, discard the hand
self.deck.discard_hand()
def discard_card(self):
if len(self.deck.hand) == 0:
return False
# be willing to discard of expensive cards that don't contribute to buying power
self.deck.hand = sorted(self.deck.hand, key=lambda card: (-card.buying_power, card.victory_points))
my_card = self.deck.hand.pop()
self.deck.discard.append(my_card)
self.game.speak_str(f'Discarded {my_card.name}')
return True
|
994,455 | 11583f78f32c796e51583ce26d9992b6cdc687ad | #!/usr/bin/env python3
"""
File: dice.py
Name:
Rolls a dice and outputs the result
Concepts covered: Random, printing
"""
import random
def main():
randNum = random.randint(1,6)
roll = input("Press any key and then enter to roll a dice. ")
print("You rolled",randNum)
if __name__ == "__main__":
main()
|
994,456 | 0089434cc291bcd44bddb869b02fe1388d9135ba | import SimpleCV as scv
import numpy as np
class CList():
def __repr__(self):
#return self.vect
oldest = (self.idx+1)%self.size
return str(self.vect[oldest:] + self.vect[:oldest]) #oldest -> newest
def __init__(self,size):
self.vect = [None]*size
self.idx = 0 #where newest element is
self.size = size
#Put element in list
def push(self, arg):
self.idx = (self.idx + 1) % self.size
self.vect[self.idx] = arg
#Get last element
def get(self):
return self.vect[self.idx]
#get lastN elements
def getn(self, n=0, last=False):
oldest = (self.idx+1)%self.size #oldest index
if last: #only return first and last index
return [self.vect[oldest], self.vect[self.idx]]
if n<=0 or n>self.size:
raise Exception
if n == self.size:
return self.vect[oldest:] + self.vect[:oldest]
head = self.vect[:self.idx+1]
if len(head) >= n:
firstidx = len(head) - n
return head[firstidx:]
else:
tail = self.vect[self.idx+1:]
firstidx = len(tail) - (n-len(head))#first index of tail
return tail[firstidx:] + head
def raw(self):
return self.vect
cam = scv.Kinect()
idxmap=["All", "Left", "Center", "Right", "Back"]
dirmap={"all":0, "left":1, "center":2, "right":3, "back":4}
def show():
depth = cam.getDepth()
depth.show()
return depth
"""
Does average using 11 bit matrix
"""
def getavg():
#depth = cam.getDepth().getNumpy() #8-bit depth matrix
dm=cam.getDepthMatrix()
#Get depth and height
h,w = dm.shape #h=480, w=640
left = dm[:, 0:w/2]
center = dm[:, w/4:3*w/4]
right = dm[:, w/2:]
leftMean = np.sum(left)/left.size
centerMean = np.sum(center)/center.size
rightMean = np.sum(right)/right.size
mean = np.sum(dm)/dm.size
#return (mean, leftMean, centerMean, rightMean)
return np.array([mean, leftMean, centerMean, rightMean])
"""
@ret: returns max index of avg, i.e.
where max value occurs
"""
def getmax(avg):
return avg.argmax()
"""
prints max
"""
def getmax2():
oldidx = -1
while True:
#depth = cam.getDepth()
#depth.show()
mean = getavg()
#where max is located
maxidx = mean.argmax()
if maxidx != oldidx:
print idxmap[maxidx]
print mean
oldidx=maxidx
"""
Over n periods, who where has the highest change occured
"""
def getdiff():
n=5
#initialize
meanvect = CList(n)
for i in range(n):
meanvect.push(getavg())
oldidx = -1
while True:
#n captures gap between frames
mean = meanvect.getn(n=5)
diff = np.fabs(mean[4] - mean[0])
maxidx = diff.argmax() #index where max difference occurs
if maxidx != oldidx and diff.max() > 100 and maxidx%2 == 1: #idx should be left or right
print "{} diff={} new={} old={}".format(idxmap[maxidx], diff, mean[4], mean[0])
oldidx=maxidx
meanvect.push(getavg())
#in general, diff between 2 frames, n samples apart
diff = diffvect[-1] - diffvect[0] #newest - oldest
maxidx = diff.argmax()
#
step = 1
def getmax3():
oldidx = -1
while True:
#depth = cam.getDepth()
#depth.show()
mean = getavg()
#where max is located
maxidx = mean.argmax()
if maxidx != oldidx:
print idxmap[maxidx]
print mean
oldidx=maxidx
#combines logic behind getmax2 and getdiff
def walk():
n=5
#initialize
meanvect = CList(n)
for i in range(n):
meanvect.push(getavg())
oldidx = -1
newidx = -1
while True:
smat = meanvect.getn(n=n) #sample matrix
median = np.median(smat, axis=0)
minidx = median.argmin()
#backup if against a wall
if median[dirmap["all"]] > 1900:
newidx=dirmap["back"]
#walk in center if walkable
elif median[dirmap["center"]] <= 1100 or minidx == dirmap["center"]:
newidx = dirmap["center"]
else: #pick left or right based on whichever is cleaner
newidx = minidx
if newidx != oldidx:
print idxmap[newidx]
#print mean
oldidx=newidx
#store new sample
mean=getavg()
meanvect.push(mean)
def diff2():
mlen = 5
midx = 0
mem = [avg2() for i in range(mlen)] #Initialize
oldidx = -1
while True:
mem[midx] = avg2() #Store value
delta = mem[midx] - mem[(midx-1)%mlen] #get diff between newest and next-to-newest
deltaAbs = np.fabs(delta)
maxidx = deltaAbs.argmax() #idx where distance has changed the most
if deltaAbs[maxidx] > 100 and oldidx != maxidx:
print "{}".format(idxmap[maxidx])
oldidx = maxidx
midx = (midx+1)%mlen #increment midx
if __name__ == '__main__':
#getdiff()
#getmax2()
walk()
while True:
depth = cam.getDepth()
depth.show()
print getavg()
"""
mlen = 2 #size of "memory"
mem = [None]*mlen
mptr = 0
incr = lambda mptr: (mptr + 1) % mlen
oldidx = -1
while True:
#depth = cam.getDepth()
#depth.show()
mean = getavg()
#where max is located
maxidx = mean.argmax()
if maxidx != oldidx:
print idxmap[maxidx]
oldidx=maxidx
"""
|
994,457 | 94bfb9a04b2110cdcec7b7dd8a7a7b92a299ec6c | #!/usr/bin/env python
# -*- coding -*-
if 1 == 1:
name = 'alex'
else:
name = 'eric'
#三元运算表达式
name1 = 'alex' if 1 == 1 else 'eric'
print(name1)
|
994,458 | c2d6d70627beaf721d175320f88349c3664315d0 | from dog import Dog
from animal import Animal
dog1 = Dog("Garf", 12)
dog2 = Dog("Snarf", 12)
print(dog1.name + ", " + dog2.name)
dog1.eat("meat")
|
994,459 | 0c25533be9cf5a78fab4fc3f2709fa3dd0856a35 | from django.contrib.auth.decorators import login_required
from django.shortcuts import render, get_object_or_404, redirect
from django.http import HttpResponse
from .forms import CommentForm
from . models import Video
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.db.models import Q
# def index(request):
# videos = Video.objects.all()
# context = {"videos":videos}
# return render(request, 'index.html', context)
def index(request):
videos = Video.objects.all().order_by('-created')[:10]
paginator = Paginator(videos, 4)
page_request_var = 'page'
page = request.GET.get(page_request_var)
try:
paginated_queryset = paginator.page(page)
except PageNotAnInteger:
paginated_queryset = paginator.page(1)
except EmptyPage:
paginated_queryset = paginator.page(paginator.num_pages)
context = {
'videos': videos,
'queryset': paginated_queryset,
'page_request_var': page_request_var,
}
return render(request, 'index.html', context)
def detail(request,title):
post_list = Video.objects.filter(title=title)
video_data = Video.objects.all()
#CommentForm
if request.method == "POST":
form = CommentForm(request.POST)
if form.is_valid():
obj = form.save(commit=False)
obj.post = post_list
obj.save()
return redirect('detail',title=post_list.title)
else:
form = CommentForm()
context = {'post_list': post_list, 'allvideos':video_data, 'form':form}
return render(request, 'details.html', context,)
def search(request):
query = request.GET.get('q')
if query:
queryset = Video.objects.filter(
Q(title__icontains=query) |
Q(description__icontains=query) |
Q(category__icontains=query) |
Q(author__icontains=query)
).distinct()
context = {
'queryset':queryset
}
return render(request, 'search_results.html', context)
# def like(request,id):
# u_name = register.objects.get(username=request.session['username'])
# video = myVideos.objects.get(id=id)
# if video.likes.filter(id=u_name.id).exists():
# return redirect('show', video.title)
# else:
# if video.dislikes.filter(id=u_name.id).exists():
# video.dislikes.remove(u_name)
# video.likes.add(u_name)
# return redirect('show', video.title)
# else:
# video.likes.add(u_name)
# return redirect('show', video.title)
#
#
# def dislike(request,id):
# u_name = register.objects.get(username=request.session['username'])
# video = myVideos.objects.get(id=id)
# if video.dislikes.filter(id=u_name.id).exists():
# return redirect('show', video.title)
#
#
# else:
# if video.likes.filter(id=u_name.id).exists():
# video.likes.remove(u_name)
# video.dislikes.add(u_name)
# return redirect('show', video.title)
# else:
# video.dislikes.add(u_name)
# return redirect('show', video.title)
#
# def comment(request):
# text = request.POST['comment']
# id=request.POST['v_id']
# if text and id:
# u_name = register.objects.get(username=request.session['username'])
# video = myVideos.objects.get(id=id)
# obj=comments(user_name=u_name,videoid=video,comment=text)
# obj.save()
# return redirect('show', video.title) |
994,460 | 97df5696e8363a193336c1a2230065b921645d2e | '''
Created on Sep 19, 2016
@author: Gerry Christiansen <gchristiansen@velexio.com>
'''
import re
import sys
from collections import OrderedDict
import cx_Oracle
from pylegos.core import LogFactory
'''
-----------------------
ENUM Type Classes
-----------------------
'''
class CxOracleType(object):
Varchar2 = "<class 'cx_Oracle.STRING'>"
Number = "<class 'cx_Oracle.NUMBER'>"
Date = "<class 'cx_Oracle.DATETIME'>"
Timestamp = "<class 'cx_Oracle.TIMESTAMP'>"
def __str__(self):
return "{0}".format(self.value)
'''
-----------------------
END of ENUM Type Classes
-----------------------
'''
class Database(object):
"""This represents an oracle database object. Use this object to perform data operations against the database (i.e dml)
"""
def __init__(self):
"""Constructor takes no arguments, just instantiates the logger object
"""
self.Connection = None
self.logger = LogFactory().getLibLogger()
class DataType(object):
NUMBER = cx_Oracle.NUMBER
class DatabaseProperty(object):
DBID = 'DBID'
NAME = 'NAME'
CREATED = 'CREATED'
RESETLOGS_CHANGE = 'RESETLOGS_CHANGE#'
RESETLOGS_TIME = 'RESETLOGS_TIME'
PRIOR_RESETLOGS_CHANGE = 'PRIOR_RESETLOGS_CHANGE#'
PRIOR_RESETLOGS_TIME = 'PRIOR_RESETLOGS_TIME'
LOG_MODE = 'LOG_MODE'
CHECKPOINT_CHANGE = 'CHECKPOINT_CHANGE#'
ARCHIVE_CHANGE = 'ARCHIVE_CHANGE#'
CONTROLFILE_TYPE = 'CONTROLFILE_TYPE'
CONTROLFILE_CREATED = 'CONTROLFILE_CREATED'
CONTROLFILE_SEQUENCE = 'CONTROLFILE_SEQUENCE#'
CONTROLFILE_CHANGE = 'CONTROLFILE_CHANGE#'
CONTROLFILE_TIME = 'CONTROLFILE_TIME'
OPEN_RESETLOGS = 'OPEN_RESETLOGS'
VERSION_TIME = 'VERSION_TIME'
OPEN_MODE = 'OPEN_MODE'
PROTECTION_MODE = 'PROTECTION_MODE'
PROTECTION_LEVEL = 'PROTECTION_LEVEL'
REMOTE_ARCHIVE = 'REMOTE_ARCHIVE'
ACTIVATION = 'ACTIVATION#'
SWITCHOVER = 'SWITCHOVER#'
DATABASE_ROLE = 'DATABASE_ROLE'
ARCHIVELOG_CHANGE = 'ARCHIVELOG_CHANGE#'
ARCHIVELOG_COMPRESSION = 'ARCHIVELOG_COMPRESSION'
SWITCHOVER_STATUS = 'SWITCHOVER_STATUS'
DATAGUARD_BROKER = 'DATAGUARD_BROKER'
GUARD_STATUS = 'GUARD_STATUS'
SUPPLEMENTAL_LOG_DATA_MIN = 'SUPPLEMENTAL_LOG_DATA_MIN'
SUPPLEMENTAL_LOG_DATA_PK = 'SUPPLEMENTAL_LOG_DATA_PK'
SUPPLEMENTAL_LOG_DATA_UI = 'SUPPLEMENTAL_LOG_DATA_UI'
FORCE_LOGGING = 'FORCE_LOGGING'
PLATFORM_ID = 'PLATFORM_ID'
PLATFORM_NAME = 'PLATFORM_NAME'
RECOVERY_TARGET_INCARNATION = 'RECOVERY_TARGET_INCARNATION#'
LAST_OPEN_INCARNATION = 'LAST_OPEN_INCARNATION#'
CURRENT_SCN = 'CURRENT_SCN'
FLASHBACK_ON = 'FLASHBACK_ON'
SUPPLEMENTAL_LOG_DATA_FK = 'SUPPLEMENTAL_LOG_DATA_FK'
SUPPLEMENTAL_LOG_DATA_ALL = 'SUPPLEMENTAL_LOG_DATA_ALL'
DB_UNIQUE_NAME = 'DB_UNIQUE_NAME'
STANDBY_BECAME_PRIMARY_SCN = 'STANDBY_BECAME_PRIMARY_SCN'
FS_FAILOVER_STATUS = 'FS_FAILOVER_STATUS'
FS_FAILOVER_CURRENT_TARGET = 'FS_FAILOVER_CURRENT_TARGET'
FS_FAILOVER_THRESHOLD = 'FS_FAILOVER_THRESHOLD'
FS_FAILOVER_OBSERVER_PRESENT = 'FS_FAILOVER_OBSERVER_PRESENT'
FS_FAILOVER_OBSERVER_HOST = 'FS_FAILOVER_OBSERVER_HOST'
CONTROLFILE_CONVERTED = 'CONTROLFILE_CONVERTED'
PRIMARY_DB_UNIQUE_NAME = 'PRIMARY_DB_UNIQUE_NAME'
SUPPLEMENTAL_LOG_DATA_PL = 'SUPPLEMENTAL_LOG_DATA_PL'
MIN_REQUIRED_CAPTURE_CHANGE = 'MIN_REQUIRED_CAPTURE_CHANGE#'
CDB = 'CDB'
CON_ID = 'CON_ID'
PENDING_ROLE_CHANGE_TASKS = 'PENDING_ROLE_CHANGE_TASKS'
CON_DBID = 'CON_DBID'
FORCE_FULL_DB_CACHING = 'FORCE_FULL_DB_CACHING'
class TablespaceContentType(object):
Permanent = 1
Temporary = 2
def __buildConnectString(self, connectString):
connectDsn = None
sidStyleRegexMatch = '[a-zA-Z0-9-_.]+:\d+:[a-zA-Z\d._#$]+'
sidStyleExtractRegex = '([a-zA-Z0-9-_.]+):(\d+):([a-zA-Z0-9-_.]+)'
serviceStyleRegexMatch = '[a-zA-Z0-9-_.]+:\d+/[a-zA-Z\d._#$]+'
serviceStyleExtractRegex = '([a-zA-Z0-9-_.]+):(\d+)/([a-zA-Z0-9-_.]+)'
if re.match(sidStyleRegexMatch, connectString):
host = re.match(sidStyleExtractRegex, connectString).group(1)
port = re.match(sidStyleExtractRegex, connectString).group(2)
sid = re.match(sidStyleExtractRegex, connectString).group(3)
connectDsn = cx_Oracle.makedsn(host=host, port=port, sid=sid)
elif re.match(serviceStyleRegexMatch, connectString):
host = re.match(serviceStyleExtractRegex, connectString).group(1)
port = re.match(serviceStyleExtractRegex, connectString).group(2)
serviceName = re.match(serviceStyleExtractRegex, connectString).group(3)
connectDsn = cx_Oracle.makedsn(host=host, port=port, service_name=serviceName)
else:
raise DatabaseConnectionException('The format of the connection string passed [] cannot be parsed')
return connectDsn
def sessionPool(self, username, password, connectString, min=5, max=50, increment=5):
connectDsn = self.__buildConnectString(connectString=connectString)
pool = cx_Oracle.SessionPool(user=username,
password=password,
database=connectDsn,
min=min,
max=max,
increment=increment)
return pool
def connect(self, username, password, connectString, asSysdba=False):
"""
This method will create a connection to the database. Before you can call any other method, a connection must be established
<br>
:param username: The username to use for the connection <br>
:param password: The password for the connection <br>
:param connectString: The connection string in the format of db-host:port/service_name or db-host:port:sid <br>
:param asSysdba: Boolean (True|False) for whether connection should be made as sysdba. Default is False <br>
:return: None <br>
"""
if self.Connection is None:
self.logger.debug('Connecting to database with connect string ['+connectString+']')
connectDsn = self.__buildConnectString(connectString=connectString)
try:
if asSysdba:
self.logger.debug('Connecting as sysdba')
self.Connection = cx_Oracle.connect(user=username,
password=password,
dsn=connectDsn,
mode=cx_Oracle.SYSDBA)
else:
self.Connection = cx_Oracle.connect(user=username,
password=password,
dsn=connectDsn)
except cx_Oracle.DatabaseError as e:
raise DatabaseConnectionException(e)
else:
self.logger.debug('Connection already active, not creating an additional connection')
def disconnect(self):
"""
This method will close the connection now rather than when application terminates and/or Database object is garbage collected.
:return: None
"""
if self.Connection is not None:
self.Connection.close()
self.Connection = None
def generateRSMetadata(self, cursor):
cursorDesc = cursor.description
fieldNumber = 0
cursorMetadata = OrderedDict()
for field in cursorDesc:
metadataRecord = {}
metadataRecord['FieldNumber'] = fieldNumber
metadataRecord['DataType'] = field[1]
metadataRecord['MaxSize'] = len(str(field[0]))
metadataRecord['Scale'] = field[5]
cursorMetadata[field[0]] = metadataRecord
fieldNumber += 1
return cursorMetadata
def getResultSetObject(self, query, bindValues=[]):
formatedResults = self.getQueryResult(query=query, bindValues=bindValues)
resultSetObj = ResultSet(formatedResults)
return resultSetObj
def queryForSingleValue(self, query, columnName, bindValues=[], secureLog=False):
retVal = None
res = self.getQueryResult(query=query, bindValues=bindValues)
if len(res) > 1:
retVal = res[1][str(columnName).upper()]
return retVal
def getQueryResult(self, query, bindValues=[], secureLog=False):
formattedResultSet = OrderedDict()
formattedRowNumber = 1
try:
cursor = self.Connection.cursor()
self.logger.debug('Running query: '+query)
if not secureLog:
self.logger.debug('Bind values for above query are '+str(bindValues))
self.logger.debug('Executing query')
if not secureLog:
self.logger.debug('Session effective query user (current_schema) is ['+self.Connection.current_schema+']')
cursor.execute(query, bindValues)
self.logger.debug('Generating Resultset Metadata')
curMeta = self.generateRSMetadata(cursor=cursor)
self.logger.debug('Fetching all records')
rawResultSet = cursor.fetchall()
self.logger.debug('Formatting resultset')
for row in rawResultSet:
formattedRec = {}
for field in curMeta:
rowVal = row[curMeta[field]['FieldNumber']]
formattedRec[field] = rowVal
'''
Determine if maxVal needs increase
'''
if (len(str(rowVal)) > curMeta[field]['MaxSize']) or (
len(str(rowVal)) == curMeta[field]['MaxSize'] and curMeta[field]['Scale'] > 0):
if curMeta[field]['Scale'] > 0:
curMeta[field]['MaxSize'] = len(str(rowVal)) + 1
elif curMeta[field]['DataType'] == str(CxOracleType.Timestamp):
curMeta[field]['MaxSize'] = 26
else:
curMeta[field]['MaxSize'] = len(str(rowVal))
formattedResultSet[formattedRowNumber] = formattedRec
formattedRowNumber += 1
formattedResultSet[0] = curMeta;
self.logger.debug('Returning resultset with ['+str(len(formattedResultSet)-1)+'] records')
return formattedResultSet
except cx_Oracle.DatabaseError as e:
self.logger.debug('Hit cx_oracle DatabaseError: '+str(e))
raise DatabaseQueryException(e)
def getColumnMungedResultset(self, query, bindValues=[], colDelimiter='|::|', secureLog=False):
queryResult = self.getQueryResult(query=query, bindValues=bindValues, secureLog=secureLog)
rsMeta = queryResult[0]
resultSet = []
self.logger.debug('Munging column values of resultset')
for i in range(1,len(queryResult)):
mungedColData = ''
for k,v in rsMeta.iteritems():
colVal = str(queryResult[i][k])
mungedColData += colVal+colDelimiter
trimmedColData = mungedColData[:len(mungedColData)-len(colDelimiter)]
resultSet.append(trimmedColData)
if not secureLog:
self.logger.debug('Returning munged resultset: '+str(resultSet))
return resultSet
def getColumnDelimitedResultset(self, query, bindValues=[], fieldDelimiter=',', secureLog=False):
queryResult = self.getQueryResult(query=query, bindValues=bindValues, secureLog=secureLog)
rsMeta = queryResult[0]
resultSet = []
self.logger.debug('Generating record set with field delimiter [' + fieldDelimiter + ']')
for i in range(1,len(queryResult)):
recordData = ''
for k,v in rsMeta.iteritems():
colVal = str(queryResult[i][k])
recordData += colVal + fieldDelimiter
# NEED TO REMOVE THE TRAILING DELIMETER
recordData = recordData[:len(recordData)-1]
resultSet.append(recordData)
if not secureLog:
self.logger.debug('Returning resultset: '+str(resultSet))
return resultSet
def execDML(self, dml, bindValues=[]):
"""
This function is to be used to call any dml operation (insert,update,delete). It can also
be used to run an anonymous pl/sql block. If you want to execute a stored pl/sql procedure
or function, use the executePL subtroutine
"""
try:
cursor = self.Connection.cursor()
cursor.execute(dml, bindValues)
except cx_Oracle.DatabaseError as e:
self.logger.debug('Hit cx_oracle DatabaseError: '+str(e))
raise DatabaseDMLException(e)
def execProc(self, procedureName, parameters=[], namedParameters={}, outParam=None):
try:
cursor = self.Connection.cursor()
cursor.callproc(name=procedureName,
parameters=parameters,
keywordParameters=namedParameters)
if outParam is not None:
return outParam
except cx_Oracle.DatabaseError as e:
self.logger.debug('Hit cx_oracle DatabaseError: '+str(e))
raise DatabaseDMLException(e)
def execFunc(self, functionName, oracleReturnType, parameters=[], namedParameters={}):
try:
cursor = self.Connection.cursor()
retValue = cursor.callfunc(name=functionName,
returnType=oracleReturnType,
parameters=parameters,
keywordParameters=namedParameters)
return retValue
except cx_Oracle.DatabaseError as e:
self.logger.debug('Hit cx_oracle DatabaseError: '+str(e))
raise DatabaseDMLException(e)
def commit(self):
try:
self.Connection.commit();
except cx_Oracle.DatabaseError as e:
self.logger.debug('Hit cx_oracle DatabaseError: '+str(e))
raise DatabaseDMLException(e)
def rollback(self):
self.Connection.rollback();
def getDefaultTablespace(self, type=TablespaceContentType.Permanent):
if type is TablespaceContentType.Permanent:
query = ("select property_value "
"from database_properties "
"where property_name = 'DEFAULT_PERMANENT_TABLESPACE'")
elif type is TablespaceContentType.Temporary:
query = ("select property_value "
"from database_properties "
"where property_name = 'DEFAULT_TEMP_TABLESPACE'")
else:
'''
todo: raise exception/error
'''
return None
res = self.queryForSingleValue(query=query, columnName='PROPERTY_VALUE')
return res
def getProperty(self, property=DatabaseProperty.NAME):
query = "select " + property + " from v$database"
res = self.queryForSingleValue(query=query, columnName=property)
return res
class ResultSet(object):
def __init__(self, resultSet):
self.formattedResultSet = resultSet
def convertDatatypeForPrint(self, oracleType, scale=0):
if (str(oracleType)) == CxOracleType.Number:
if scale > 0:
return 'f'
else:
return 'd'
elif str(oracleType) == CxOracleType.DateTime:
return 't'
else:
return 's'
def printRecordDelimeter(self, metaData):
maxLineWidth = 0
for header in metaData:
maxLineWidth += metaData[header]['MaxSize'] + 1
sys.stdout.write("{v:{w}s}".format(v='-' * (maxLineWidth + 1), w=maxLineWidth))
def printResultSet(self):
metadataRow = self.formattedResultSet[0]
fd = "|"
'''
PRINT HEADER ROW
'''
self.printRecordDelimeter(metaData=metadataRow)
sys.stdout.write() (fd)
for header in metadataRow:
fieldWidth = metadataRow[header]['MaxSize']
sys.stdout.write("{v:{w}s}|".format(v=header, w=fieldWidth, d=fd))
sys.stdout.write("\n")
self.printRecordDelimeter(metaData=metadataRow)
del self.formattedResultSet[0]
for row in self.formattedResultSet:
sys.stdout.write(fd)
for header in metadataRow:
fieldWidth = metadataRow[header]['MaxSize']
fieldType = str(metadataRow[header]['DataType'])
scaleValue = metadataRow[header]['Scale']
fieldValue = self.formattedResultSet[row][header]
if fieldValue is None:
fieldValue = ""
fieldType = str(CxOracleType.Varchar2)
if fieldType == str(CxOracleType.Number) and scaleValue > 0:
sys.stdout.write(
"{v:{w}.{s}{t}}|".format(v=fieldValue, w=fieldWidth, t='f', s=scaleValue))
sys.stdout.flush()
elif fieldType == str(CxOracleType.Number):
sys.stdout.write(
"{v:{w}{t}}|".format(v=fieldValue, w=fieldWidth, t='d', s=scaleValue))
sys.stdout.flush()
elif fieldType == str(CxOracleType.Date):
printValue = fieldValue.strftime("%m.%d.%Y %H:%M:%S")
sys.stdout.write("{v:{w}{t}}|".format(v=printValue, w=fieldWidth, t='s'))
sys.stdout.flush()
elif fieldType == str(CxOracleType.Timestamp):
printValue = fieldValue.strftime("%m.%d.%Y %H:%M:%S:%f")
sys.stdout.write("{v:{w}{t}}|".format(v=printValue, w=fieldWidth, t='s'))
sys.stdout.flush()
else:
sys.stdout.write("{v:{w}{t}}|".format(v=fieldValue, w=fieldWidth, t='s'))
sys.stdout.write('\n')
sys.stdout.flush()
class Admin(object):
'''
classdocs
'''
database = None
def __init__(self, database):
'''
Constructor
'''
self.database = database
'''
this is a test
'''
def createUser(self, username, password, defaultTablespace=None, defaultTempTablespace=None, profile='DEFAULT'):
userPermTBS = defaultTablespace
userTempTBS = defaultTempTablespace
if defaultTablespace is None:
userPermTBS = self.database.getDefaultTablespace(type=TablespaceContentType.Permanent)
if defaultTempTablespace is None:
userTempTBS = self.database.getDefaultTablespace(type=TablespaceContentType.Temporary)
ddl = ("create user " + username + " identified by " + password + " "
"default tablespace " + userPermTBS + " "
"temporary tablespace " + userTempTBS + " "
"profile " + profile + " "
"account unlock")
self.database.execute(ddl);
class DatabaseConnectionException(Exception):
"""
This exeception will be thrown if there is an issue connecting to the database. The
exception will have the following attributes that can be used
"""
def __init__(self, cxExceptionObj=None, message=None):
if message is not None:
self.message = message
else:
self.message = str(cxExceptionObj)
self.ErrCode = self.message.split(':')[0]
self.__defineMessage()
def __defineMessage(self):
self.ErrMessage = 'ERROR: '
if self.ErrCode == 'ORA-01017':
self.ErrName = 'InvalidLoginCreds'
self.ErrMessage += '['+self.ErrName+']['+self.ErrCode+'] - The credentials used are not valid'
elif self.ErrCode == 'ORA-12154':
self.ErrName = 'InvalidHost'
self.ErrMessage += '['+self.ErrName+']['+self.ErrCode+'] - The host name used in the connection string is not correct or cannot be resolved'
elif self.ErrCode == 'ORA-12514':
self.ErrName = 'InvalidService'
self.ErrMessage += '['+self.ErrName+']['+self.ErrCode+'] - The service name used in the connection string is not correct or is not running on the database server'
elif self.ErrCode == 'ORA-12541':
self.ErrName = 'NoListener'
self.ErrMessage += '['+self.ErrName+']['+self.ErrCode+'] - The database listener did not respond. Verify the port is correct and all firewall ports are open between client and database server'
else:
self.ErrName = 'Undefined'
self.ErrMessage += '['+self.ErrName+']['+self.ErrCode+'] - '+self.message
class DatabaseQueryException(Exception):
def __init__(self, cxExceptionObj):
self.message = str(cxExceptionObj)
self.ErrCode = self.message.split(':')[0]
self.__defineMessage()
def __defineMessage(self):
self.ErrMessage = 'ERROR: '
if self.ErrCode == 'ORA-00942':
self.ErrName = 'TableMissing'
self.ErrMessage += '['+self.ErrName+']['+self.ErrCode+'] - The table referenced does not exist or your session user lacks privileges'
else:
self.ErrName = 'Undefined'
self.ErrMessage += '['+self.ErrName+']['+self.ErrCode+'] - '+self.message
class DatabaseDMLException(Exception):
def __init__(self, cxExceptionObj):
self.message = str(cxExceptionObj)
self.ErrCode = str(cxExceptionObj).split(':')[0]
self.__defineMessage()
def __defineMessage(self):
objName = self.__extractObjectName()
self.ErrMessage = 'ERROR: '
if self.ErrCode == 'ORA-00001':
self.ErrName = 'UniqueViolated'
self.ErrMessage += '['+self.ErrName+']['+self.ErrCode+'] - The operation could not be performed as it would violate the unique constraint ['+objName+']'
elif self.ErrCode == 'ORA-01400':
self.ErrName = 'NotNullViolated'
self.ErrMessage += '['+self.ErrName+']['+self.ErrCode+'] - The field '+objName+' must be assigned a value before the record can be saved'
else:
self.ErrName = 'Undefined'
self.ErrMessage += '['+self.ErrName+']['+self.ErrCode+'] - '+self.message
def __extractObjectName(self):
objectName = 'Undefined'
matchObj = re.match(r'ORA-\d+:\s[a-zA-Z0-9\s]+\(([A-Z0-9."#_]+)\)', self.message)
if matchObj.groups():
objectName = matchObj.group(1).replace('"','')
self.ConstraintName=objectName
return objectName
|
994,461 | c9e0b97258df4cc9bac5dff6aee15a8422754967 | #Program to reverse a string word by word
class Reverse:
def reverse_words(self,string):
return " ".join(reversed(string.split(" ")))
a=Reverse()
string=input()
print(a.reverse_words(string))
|
994,462 | fb85013115102c222c4e09529e9104d615609fc6 | # -*- coding: utf-8 -*-
import scrapy
import re
import json
from tutorial.items import IeeeItem
class IeeexploreIeeeOrgSpider(scrapy.Spider):
name = 'ieee'
allowed_domains = ['ieeexplore.ieee.org']
# start_urls = ('http://ieeexplore.ieee.org/document/7185405/',)
def start_requests(self):
reqs=[]
for i in range(7180000,7185405):
url = 'http://ieeexplore.ieee.org/document/%d/'%i
req = scrapy.Request(url)
reqs.append(req)
return reqs
def parse(self, response):
s = str(re.findall(r'global.document.metadata=.*',response.body))
temp = s.replace("['global.document.metadata=","")
result = temp.replace(";']","")
with open("../item.json","a") as f:
a = json.dumps(result,sort_keys=True,indent=4)
f.write(a+'\n')
print "写文件完成"
# pre_item['Title'] = response.xpath("//h1/span[@class='ng-bingding']/text()").extract()
# # for i in range(1,10):
# # pre_item['Author'] = response.xpath("//*[@id='LayoutWrapper']/div[6]/div[3]/div/div/div/div[2]/div/div/span[%d]/span/a/span/text()"%i).extract()
# # pre_item['AuthorInfo'] = response.xpath("//*[@id='LayoutWrapper']/div[6]/div[3]/div/div/div/div[2]/div/div/span[%d]/span/a/@qtip-text"%i).extract()
# # pre_item['Keywords'] = response.xpath("//*[@id='full-text-section']/div/div[2]/section/div[1]/section/div/ul/li[1]/div/span[%d]/a/text()"%i).extract()
# pre_item['Author'] = response.xpath("//*[@id='LayoutWrapper']/div[6]/div[3]/div/div/div/div[2]/div/div/span[1]/span/a/span/text()").extract()
# pre_item['AuthorInfo'] = response.xpath("//*[@id='LayoutWrapper']/div[6]/div[3]/div/div/div/div[2]/div/div/span[1]/span/a/@qtip-text").extract()
# pre_item['Keywords'] = response.xpath("//*[@id='full-text-section']/div/div[2]/section/div[1]/section/div/ul/li[1]/div/span[1]/a/text()").extract()
# pre_item['Abstract'] = response.xpath("/body/div[3]/div[6]/div[3]/div/section[3]/div/div[1]/div/div/div/text()").extract()
# pre_item['PublisherOrConference'] = response.xpath("/body/div[3]/div[6]/div[3]/div/section[3]/div/div[1]/section/div[2]/a/text()").extract()
# pre_item['Volume'] = response.xpath("//div[@class='u-pb-1 stats-document-abstract-publishedIn ng-scope']/span/span[1]/text()").extract()
# pre_item['Issue'] = response.xpath("//*[@id='7185405']/div[2]/span/span[2]/a/text()").extract()
# pre_item['Pages'] = response.xpath("//*[@id='7185405']/div[3]/div[1]/div[1]/text()[2]").extract()+response.xpath("//*[@id='7185405']/div[3]/div[1]/div[1]/span/text()").extract()
# pre_item['Time'] = response.xpath("//*[@id='7185405']/div[3]/div[1]/div[2]/text()[3]").extract()
# pre_item['Category'] = "IEEE"
# return pre_item
|
994,463 | fded4fac6a983ed558352623cdf122f1a26e8514 | import numpy as np
from mytorch import tensor
from mytorch.autograd_engine import Function
import math
def unbroadcast(grad, shape, to_keep=0):
while len(grad.shape) != len(shape):
grad = grad.sum(axis=0)
for i in range(len(shape) - to_keep):
if grad.shape[i] != shape[i]:
grad = grad.sum(axis=i, keepdims=True)
return grad
class Transpose(Function):
@staticmethod
def forward(ctx, a):
if not len(a.shape) == 2:
raise Exception("Arg for Transpose must be 2D tensor: {}".format(a.shape))
requires_grad = a.requires_grad
b = tensor.Tensor(a.data.T, requires_grad=requires_grad,
is_leaf=not requires_grad)
return b
@staticmethod
def backward(ctx, grad_output):
return (tensor.Tensor(grad_output.data.T),)
class Reshape(Function):
@staticmethod
def forward(ctx, a, shape):
if not type(a).__name__ == 'Tensor':
raise Exception("Arg for Reshape must be tensor: {}".format(type(a).__name__))
ctx.shape = a.shape
requires_grad = a.requires_grad
c = tensor.Tensor(a.data.reshape(shape), requires_grad=requires_grad,
is_leaf=not requires_grad)
return c
@staticmethod
def backward(ctx, grad_output):
return tensor.Tensor(grad_output.data.reshape(ctx.shape)), None
class Log(Function):
@staticmethod
def forward(ctx, a):
if not type(a).__name__ == 'Tensor':
raise Exception("Arg for Log must be tensor: {}".format(type(a).__name__))
ctx.save_for_backward(a)
requires_grad = a.requires_grad
c = tensor.Tensor(np.log(a.data), requires_grad=requires_grad,
is_leaf=not requires_grad)
return c
@staticmethod
def backward(ctx, grad_output):
a = ctx.saved_tensors[0]
return (tensor.Tensor(grad_output.data / a.data),)
class Exp(Function):
@staticmethod
def forward(ctx, a):
if not type(a).__name__ == 'Tensor':
raise Exception("Arg for Log must be tensor: {}".format(type(a).__name__))
ctx.save_for_backward(a)
requires_grad = a.requires_grad
c = tensor.Tensor(np.exp(a.data), requires_grad=requires_grad,
is_leaf=not requires_grad)
return c
@staticmethod
def backward(ctx, grad_output):
a = ctx.saved_tensors[0]
return (tensor.Tensor(grad_output.data * np.exp(a.data)),)
"""EXAMPLE: This represents an Op:Add node to the comp graph.
See `Tensor.__add__()` and `autograd_engine.Function.apply()`
to understand how this class is used.
Inherits from:
Function (autograd_engine.Function)
"""
class Add(Function):
@staticmethod
def forward(ctx, a, b):
# Check that both args are tensors
if not (type(a).__name__ == 'Tensor' and type(b).__name__ == 'Tensor'):
raise Exception("Both args must be Tensors: {}, {}".format(
type(a).__name__, type(b).__name__))
# Check that args have same shape
# Save inputs to access later in backward pass.
ctx.save_for_backward(a, b)
# Create addition output and sets `requires_grad and `is_leaf`
# (see appendix A for info on those params)
requires_grad = a.requires_grad or b.requires_grad
c = tensor.Tensor(a.data + b.data, requires_grad=requires_grad,
is_leaf=not requires_grad)
return c
@staticmethod
def backward(ctx, grad_output):
# retrieve forward inputs that we stored
a, b = ctx.saved_tensors
# calculate gradient of output w.r.t. each input
# dL/da = dout/da * dL/dout
grad_a = np.ones(a.shape) * grad_output.data
# dL/db = dout/db * dL/dout
grad_b = np.ones(b.shape) * grad_output.data
# the order of gradients returned should match the order of the arguments
grad_a = tensor.Tensor(unbroadcast(grad_a, a.shape))
grad_b = tensor.Tensor(unbroadcast(grad_b, b.shape))
return grad_a, grad_b
class Sub(Function):
@staticmethod
def forward(ctx, a, b):
# Check that inputs are tensors of same shape
if not (type(a).__name__ == 'Tensor' and type(b).__name__ == 'Tensor'):
raise Exception("Both args must be Tensors: {}, {}".format(
type(a).__name__, type(b).__name__))
ctx.save_for_backward(a, b)
requires_grad = a.requires_grad or b.requires_grad
c = tensor.Tensor(a.data - b.data, requires_grad=requires_grad,
is_leaf=not requires_grad)
return c
@staticmethod
def backward(ctx, grad_output):
a, b = ctx.saved_tensors
grad_a = np.ones(a.shape) * grad_output.data
grad_b = -np.ones(b.shape) * grad_output.data
grad_a = tensor.Tensor(unbroadcast(grad_a, a.shape))
grad_b = tensor.Tensor(unbroadcast(grad_b, b.shape))
return grad_a, grad_b
class Sum(Function):
@staticmethod
def forward(ctx, a, axis, keepdims):
if not type(a).__name__ == 'Tensor':
raise Exception("Only log of tensor is supported")
ctx.axis = axis
ctx.shape = a.shape
if axis is not None:
ctx.len = a.shape[axis]
ctx.keepdims = keepdims
requires_grad = a.requires_grad
c = tensor.Tensor(a.data.sum(axis=axis, keepdims=keepdims),
requires_grad=requires_grad, is_leaf=not requires_grad)
return c
@staticmethod
def backward(ctx, grad_output):
grad_out = grad_output.data
if (ctx.axis is not None) and (not ctx.keepdims):
grad_out = np.expand_dims(grad_output.data, axis=ctx.axis)
else:
grad_out = grad_output.data.copy()
grad = np.ones(ctx.shape) * grad_out
assert grad.shape == ctx.shape
# Take note that gradient tensors SHOULD NEVER have requires_grad = True.
return tensor.Tensor(grad), None, None
# TODO: Implement more Functions below
class Mul(Function):
@staticmethod
def forward(ctx, a, b):
# Check that inputs are tensors of same shape
if not (type(a).__name__ == 'Tensor' and type(b).__name__ == 'Tensor'):
raise Exception("Both args must be Tensors: {}, {}".format(
type(a).__name__, type(b).__name__))
ctx.save_for_backward(a, b)
requires_grad = a.requires_grad or b.requires_grad
c = tensor.Tensor(a.data*b.data, requires_grad=requires_grad,
is_leaf=not requires_grad)
return c
@staticmethod
def backward(ctx, grad_output):
a, b = ctx.saved_tensors
grad_a = b.data * grad_output.data
grad_b = a.data * grad_output.data
grad_a = tensor.Tensor(unbroadcast(grad_a, a.shape))
grad_b = tensor.Tensor(unbroadcast(grad_b, b.shape))
return grad_a, grad_b
class Div(Function):
@staticmethod
def forward(ctx, a, b):
# Check that inputs are tensors of same shape
if not (type(a).__name__ == 'Tensor' and type(b).__name__ == 'Tensor') or \
a.data.shape != b.data.shape or 0 in b.data:
raise Exception("Both args must be Tensors: {}, {}".format(
type(a).__name__, type(b).__name__))
ctx.save_for_backward(a, b)
requires_grad = a.requires_grad or b.requires_grad
c = tensor.Tensor(a.data/b.data, requires_grad=requires_grad,
is_leaf=not requires_grad)
return c
@staticmethod
def backward(ctx, grad_output):
a, b = ctx.saved_tensors
grad_a = 1/b.data * grad_output.data
grad_b = (-a.data)/(np.square(b.data)) * grad_output.data
grad_a = tensor.Tensor(unbroadcast(grad_a, a.shape))
grad_b = tensor.Tensor(unbroadcast(grad_b, b.shape))
return grad_a, grad_b
class MatMul(Function):
@staticmethod
def forward(ctx, a, b):
# Check that inputs are tensors of same shape
if not (type(a).__name__ == 'Tensor' and type(b).__name__ == 'Tensor'):
raise Exception("Both args must be Tensors: {}, {}".format(
type(a).__name__, type(b).__name__))
ctx.save_for_backward(a, b)
requires_grad = a.requires_grad or b.requires_grad
c = tensor.Tensor(np.einsum('ik, kj -> ij', a.data, b.data), requires_grad=requires_grad,
is_leaf=not requires_grad)
return c
@staticmethod
def backward(ctx, grad_output):
a, b = ctx.saved_tensors
grad_a = np.einsum('ik, kj -> ij', grad_output.data, b.data.T)
grad_b = np.einsum('ik, kj -> ij', a.data.T, grad_output.data)
grad_a = tensor.Tensor(unbroadcast(grad_a, a.shape))
grad_b = tensor.Tensor(unbroadcast(grad_b, b.shape))
return grad_a, grad_b
class ReLU(Function):
@staticmethod
def forward(ctx, z):
if not (type(z).__name__ == 'Tensor'):
raise Exception("Arg must be a Tensor: {}".format(
type(z).__name__))
ctx.save_for_backward(z)
requires_grad = z.requires_grad
c = tensor.Tensor(np.where(z.data > 0, z.data, 0), requires_grad=requires_grad,
is_leaf=not requires_grad)
return c
@staticmethod
def backward(ctx, grad_output):
z = ctx.saved_tensors
z = z[0]
grad_z = np.where(z.data > 0, 1, 0) * grad_output.data
grad_z = tensor.Tensor(unbroadcast(grad_z, z.shape))
return (grad_z,)
def log_sum_x_trick(predicted):
a = np.amax(predicted.data, axis=1)
a = a.reshape((1, len(a)))
a = tensor.Tensor(np.tile(a.T, (1, predicted.data.shape[-1])))
return a
def cross_entropy(predicted, target):
"""Calculates Cross Entropy Loss (XELoss) between logits and true labels.
For MNIST, don't call this function directly; use nn.loss.CrossEntropyLoss instead.
Args:
predicted (Tensor): (batch_size, num_classes) logits
target (Tensor): (batch_size,) true labels
Returns:
Tensor: the loss as a float, in a tensor of shape ()
"""
batch_size, num_classes = predicted.shape
# Tip: You can implement XELoss all here, without creating a new subclass of Function.
# However, if you'd prefer to implement a Function subclass you're free to.
# Just be sure that nn.loss.CrossEntropyLoss calls it properly.
# Tip 2: Remember to divide the loss by batch_size; this is equivalent
# to reduction='mean' in PyTorch's nn.CrossEntropyLoss
e_x = predicted.exp()
log_e_x = e_x.log()
a = log_sum_x_trick(predicted)
x_n_offset = predicted - a
exp_xn_offset = x_n_offset.exp()
sum_exp_xn_offset = exp_xn_offset.sum(axis=1, keepdims=True)
log_sum_exp_xn_offset = sum_exp_xn_offset.log()
denominator = a + log_sum_exp_xn_offset
log_softmax = log_e_x - denominator
labels = to_one_hot(target, num_classes)
prod = log_softmax*labels
total = prod.sum()
batch_size = tensor.Tensor(-batch_size)
total = total / batch_size
return total
def to_one_hot(arr, num_classes):
"""(Freebie) Converts a tensor of classes to one-hot, useful in XELoss
Example:
>>> to_one_hot(Tensor(np.array([1, 2, 0, 0])), 3)
[[0, 1, 0],
[0, 0, 1],
[1, 0, 0],
[1, 0, 0]]
Args:
arr (Tensor): Condensed tensor of label indices
num_classes (int): Number of possible classes in dataset
For instance, MNIST would have `num_classes==10`
Returns:
Tensor: one-hot tensor
"""
arr = arr.data.astype(int)
a = np.zeros((arr.shape[0], num_classes))
a[np.arange(len(a)), arr] = 1
return tensor.Tensor(a, requires_grad=True)
class Conv1d(Function):
@staticmethod
def forward(ctx, x, weight, bias, stride):
"""The forward/backward of a Conv1d Layer in the comp graph.
Notes:
- Make sure to implement the vectorized version of the pseudocode
- See Lec 10 slides # TODO: FINISH LOCATION OF PSEUDOCODE
- No, you won't need to implement Conv2d for this homework.
Args:
x (Tensor): (batch_size, in_channel, input_size) input data
weight (Tensor): (out_channel, in_channel, kernel_size)
bias (Tensor): (out_channel,)
stride (int): Stride of the convolution
Returns:
Tensor: (batch_size, out_channel, output_size) output data
"""
# For your convenience: ints for each size
batch_size, in_channel, input_size = x.shape
out_channel, _, kernel_size = weight.shape
if not (type(x).__name__ == 'Tensor' and type(weight).__name__ == 'Tensor' and type(bias).__name__ == 'Tensor'):
raise Exception("All args must be Tensors: {},{}, {}".format(
type(x).__name__, type(weight).__name__), type(bias).__name__)
# TODO: Save relevant variables for backward pass
ctx.save_for_backward(x, weight, bias)
ctx.stride = stride
# TODO: Get output size by finishing & calling get_conv1d_output_size()
output_size = get_conv1d_output_size(input_size, kernel_size, stride)
ctx.output_size = output_size
requires_grad = x.requires_grad or weight.requires_grad or bias.requires_grad
# TODO: Initialize output with correct size
out = np.zeros((batch_size, out_channel, output_size))
for i in range(batch_size):
for j in range(out_channel):
curr = 0
for k in range(0, input_size-kernel_size+1, stride):
out[i][j][curr] = np.sum(x.data[i, :, k:k+kernel_size]
* weight.data[j]) + bias.data[j]
curr += 1
# TODO: Calculate the Conv1d output.
# Remember that we're working with np.arrays; no new operations needed.
out = tensor.Tensor(out, requires_grad=requires_grad,
is_leaf=not requires_grad)
# TODO: Put output into tensor with correct settings and return
return out
@staticmethod
def backward(ctx, grad_output):
# TODO: Finish Conv1d backward pass. It's surprisingly similar to the forward pass.
x, weight, bias = ctx.saved_tensors
stride = ctx.stride
output_size = ctx.output_size
batch_size, in_channel, input_size = x.shape
out_channel, _, kernel_size = weight.shape
flip_w = np.flip(weight.data, axis=2)
grad_output_dw = np.zeros(
(batch_size, out_channel, get_conv1d_output_size(input_size, kernel_size, 1)))
grad_x = np.zeros(x.shape)
for i in range(batch_size):
for j in range(out_channel):
for k in range(output_size):
grad_output_dw[i][j][k*stride] = grad_output.data[i][j][k]
grad_output_dx = np.pad(grad_output_dw, ((0, 0), (0, 0),
(kernel_size-1, kernel_size-1)),
mode='constant', constant_values=0)
for i in range(batch_size):
for j in range(out_channel):
for k in range(in_channel):
for l in range(input_size):
grad_x[i][k][l] += np.sum(grad_output_dx[i][j]
[l:l+kernel_size] * flip_w[j][k])
grad_w = np.zeros(weight.shape)
for i in range(batch_size):
for j in range(out_channel):
for k in range(in_channel):
for l in range(kernel_size):
grad_w[j][k][l] += np.sum(grad_output_dw[i][j] *
x.data[i][k][l:l+input_size-kernel_size+1])
grad_b = np.sum(grad_output.data, axis=(0, 2))
grad_b = tensor.Tensor(grad_b, requires_grad=True)
grad_w = tensor.Tensor(grad_w, requires_grad=True)
grad_x = tensor.Tensor(grad_x, requires_grad=True)
return grad_x, grad_w, grad_b
def get_conv1d_output_size(input_size, kernel_size, stride):
"""Gets the size of a Conv1d output.
Notes:
- This formula should NOT add to the comp graph.
- Yes, Conv2d would use a different formula,
- But no, you don't need to account for Conv2d here.
- If you want, you can modify and use this function in HW2P2.
- You could add in Conv1d/Conv2d handling, account for padding, dilation, etc.
- In that case refer to the torch docs for the full formulas.
Args:
input_size (int): Size of the input to the layer
kernel_size (int): Size of the kernel
stride (int): Stride of the convolution
Returns:
int: size of the output as an int (not a Tensor or np.array)
"""
return ((input_size - kernel_size)//stride) + 1
class Pow(Function):
@staticmethod
def forward(ctx, a, b):
if not type(a).__name__ == 'Tensor':
raise Exception("Arg for Exp must be tensor: {}".format(type(a).__name__))
ctx.save_for_backward(a)
ctx.exponent = b
requires_grad = a.requires_grad
c = tensor.Tensor(a.data**b, requires_grad=requires_grad,
is_leaf=not requires_grad)
return c
@staticmethod
def backward(ctx, grad_output):
a = ctx.saved_tensors[0]
b = ctx.exponent
return (tensor.Tensor(grad_output.data * b * a.data**(b-1)), None)
class Sigmoid(Function):
@staticmethod
def forward(ctx, a):
b_data = np.divide(1.0, np.add(1.0, np.exp(-a.data)))
ctx.out = b_data[:]
b = tensor.Tensor(b_data, requires_grad=a.requires_grad)
b.is_leaf = not b.requires_grad
return b
@staticmethod
def backward(ctx, grad_output):
b = ctx.out
grad = grad_output.data * b * (1-b)
return tensor.Tensor(grad),
class Tanh(Function):
@staticmethod
def forward(ctx, a):
b = tensor.Tensor(np.tanh(a.data), requires_grad=a.requires_grad)
ctx.out = b.data[:]
b.is_leaf = not b.requires_grad
return b
@staticmethod
def backward(ctx, grad_output):
out = ctx.out
grad = grad_output.data * (1-out**2)
return tensor.Tensor(grad),
class Slice(Function):
@staticmethod
def forward(ctx,x,indices):
'''
Args:
x (tensor): Tensor object that we need to slice
indices (int,list,Slice): This is the key passed to the __getitem__ function of the Tensor object when it is sliced using [ ] notation.
'''
requires_grad = x.requires_grad
ctx.indices = indices
ctx.original_shape = x.shape
result = tensor.Tensor(x.data[indices], requires_grad=requires_grad, is_leaf=not requires_grad)
return result
@staticmethod
def backward(ctx,grad_output):
indices = ctx.indices
original_shape = ctx.original_shape
result = np.zeros(original_shape)
result[indices] = grad_output.data
return tensor.Tensor(result), None
class Cat(Function):
@staticmethod
def forward(ctx,*args):
'''
Args:
args (list): [*seq, dim]
NOTE: seq (list of tensors) contains the tensors that we wish to concatenate while dim (int) is the dimension along which we want to concatenate
'''
*seq, dim = args
grad = False
ctx.data = []
ctx.dim = dim
result = None
for t in seq:
if t.requires_grad:
grad = True
if result is None: #First
result = t.data
else:
assert(result is not None)
result = np.concatenate((result, t.data), axis=dim)
ctx.data.append(t.data)
result = tensor.Tensor(result, requires_grad=grad)
result.is_leaf = not result.requires_grad
return result
@staticmethod
def backward(ctx,grad_output):
dim = ctx.dim
data = ctx.data
split_points = []
for i in range(0, len(data)-1):
if len(split_points) == 0:
split_points.append(data[i].shape[dim])
else:
split_points.append(data[i].shape[dim] + split_points[-1])
grad = np.split(grad_output.data, split_points, axis=dim)
for i in range(len(grad)):
grad[i] = tensor.Tensor(grad[i])
grad.append(None)
grad = tuple(grad)
return grad
|
994,464 | bf069f9a061a48713481f0b92cea6f865030508e | """
Run "./manage.py test blog" from healthblog root.
"""
from django.test import TestCase, Client
from django.core.urlresolvers import reverse
import datetime # need to make timezone aware
import urllib.parse
class AuthorizationTests(TestCase):
def setUp(self):
"""
To fully test, create poster accounts here, and check that they can do things
In the interests of brevity, just testing redirect to login if not logged in
"""
pass
def test_no_access_without_login(self):
"""
Tests that redirected to the home/login page if you are not logged in
"""
response = self.client.get(reverse('question_list'), follow=True)
expected_url = reverse('home') + "?next=" + reverse('question_list')
self.assertRedirects(response, expected_url, status_code=302,
target_status_code=200)
expected_url = reverse('home') + "?next=" + reverse('question_add')
response = self.client.get(reverse('question_add'), follow=True)
self.assertRedirects(response, expected_url, status_code=302,
target_status_code=200) |
994,465 | 5b6a2fcfb179ef511d4468c5fb9248c4251e5257 | #This script aim to map the predicted RxLRs effector from P. capsici on the genome to identify the corresponding transcript.
#The default of this script is that it might get rid of transcript that are not predicted RxLR but for which
#the position is overlaping with predicted RxLRs on the genome
#2013 Gaëtan Thilliez
import re
from Bio.SeqUtils import quick_FASTA_reader
#The table containing the PcRxLR / Phycascaffold name equivalence will allow us to map the RxLR on the genome (Phycascaffold name contain the position)
#the problem is that this table have been created based on blast. So it is impossible to make a difference between two duplication of the same gene located at different position on the genome
#with this version of the table eg PcRxLR008 and PcRxLR009
iname= raw_input('Enter path to table containing PcRxLR and PHYCAscaffold names: ')
file_handle=open(iname,'rb')
oname= raw_input('Enter output filename: ')
fileout=open(oname, 'w')
oname2= raw_input('Enter output filename: ')
fileout2=open(oname2, 'w')
Phycascaffold_regex_1= re.compile('PHYCAscaffold_[0-9]{1,3}')
RxLRdict={}
for row in file_handle:
try:
PHYCAscaf_search=re.search(Phycascaffold_regex_1, row)
PHYCAscaf_numb='%s'%(PHYCAscaf_search.group())
print PHYCAscaf_numb
Pcsearch=re.search('PcRxLR...', row)
Pcname='%s'%(Pcsearch.group())
splitregex=re.search('[0-9]{3,8}_[0-9]{3,8}_[0-9]', row)
splitted='%s'%(splitregex.group())
n1 = splitted.split('_')
#print '%s'%(n1)
frame='%s'%(n1[2])
#print frame
if int(frame)<4:
print'no probleme with the if statement'
start=int(n1[0])
stop=int(n1[1])
RxLRdict[Pcname]=start, stop, n1[2], PHYCAscaf_numb
#print '%s'%( start)
else:
print'no probleme with the else statement'
start=int(n1[1])
stop=int(n1[0])
RxLRdict[Pcname]=start, stop, n1[2], PHYCAscaf_numb
#print '%s'%(start)
#print Pcname
except:
continue
#The part of the script described above store the position of the predicted RxLR in a Dictionary called RxLRDict
##start=n1[0]
##stop=n1[1]
##frame=n1[2]
##if start <stop, strand = +
##if stop>strat strand = -
##i assume that if frame is 1-3, stand is +
##if frame is 4-6 strand is -
##now i need to read the GFF file, isolate the start and stop codon and compare them to the one from the RxLR list
iname2= raw_input('Enter path to the GFF file from http://genome.jgi-psf.org: ')
file_handle2=open(iname2,'rb')
GFFdict={}
for row in file_handle2:
data=row.split()
if '+' in data:
if 'CDS' in data:
Phycaname='%s_%s_%s'%(data[0], int(data[3]), int(data[4]))
start=int(data[3])
stop=int(data[4])
ID=re.search('[0-9]{1,8}',data[11])
GFFdict[Phycaname]=start, stop, data[0], ID.group()
print '+ %s'%(Phycaname)
else:
continue
else:
if '-'in data:
if 'CDS' in data:
Phycaname='%s_%s_%s'%(data[0], int(data[3]), int(data[4]))
stop=int(data[3])
start=int(data[4])
ID=re.search('[0-9]{1,8}',data[11])
GFFdict[Phycaname]=start, stop, data[0], ID.group()
print '- %s'%(Phycaname)
else:
continue
else:
print 'script cannot work'
#This part store the location of the predicted protein from the V11 of the P.capsici genome
dictPotentialOverlap={}
for key1 in RxLRdict:
for key2 in GFFdict:
if RxLRdict[key1][3]==GFFdict[key2][2]:
if (int(RxLRdict[key1][0])-3)<=GFFdict[key2][0]<=(int(RxLRdict[key1][1])+3):
deltastart=RxLRdict[key1][0]-GFFdict[key2][0]
deltastop=RxLRdict[key1][1]-GFFdict[key2][1]
key3='%s_%s'%(key1, key2)
dictPotentialOverlap[key3]=deltastart, deltastop, key2, RxLRdict[key1][3], int(RxLRdict[key1][0]), int(RxLRdict[key1][1]), int(GFFdict[key2][3])
if (int(RxLRdict[key1][0])-3)>=GFFdict[key2][0]>=(int(RxLRdict[key1][1])+3):
deltastart=RxLRdict[key1][0]-GFFdict[key2][0]
deltastop=RxLRdict[key1][1]-GFFdict[key2][1]
key3='%s_%s'%(key1, key2)
dictPotentialOverlap[key3]=deltastart, deltastop, key2, RxLRdict[key1][3], int(RxLRdict[key1][0]), int(RxLRdict[key1][1]), int(GFFdict[key2][3])
if (int(RxLRdict[key1][0])-3)>=GFFdict[key2][1]>=(int(RxLRdict[key1][1])+3):
deltastart=RxLRdict[key1][0]-GFFdict[key2][0]
deltastop=RxLRdict[key1][1]-GFFdict[key2][1]
key3='%s_%s'%(key1, key2)
dictPotentialOverlap[key3]=deltastart, deltastop, key2, RxLRdict[key1][3], int(RxLRdict[key1][0]), int(RxLRdict[key1][1]), int(GFFdict[key2][3])
if (int(RxLRdict[key1][0])-3)<=GFFdict[key2][1]<=(int(RxLRdict[key1][1])+3):
deltastart=RxLRdict[key1][0]-GFFdict[key2][0]
deltastop=RxLRdict[key1][1]-GFFdict[key2][1]
key3='%s_%s'%(key1, key2)
dictPotentialOverlap[key3]=deltastart, deltastop, key2, RxLRdict[key1][3], int(RxLRdict[key1][0]), int(RxLRdict[key1][1]), int(GFFdict[key2][3])
else:
continue
#This section above compare the location of the predicted protein set and the ones from the predicted RxLR set.
##need to check the value in the dictPotentialOverlap
dictPotentialOverlap['PcRxLR515']='none', 'none', 'none', 'none', 'none', 'none', 39353
dictPotentialOverlap['PcRxLR516']='none', 'none', 'none', 'none', 'none', 'none', 531755
#Those two lines aboves add manually the effector PcRxLR 515 and 516 because they were not in the table loaded at line 10
for key in dictPotentialOverlap:
print>>fileout, ">%s" %(key)
print>>fileout, (dictPotentialOverlap.get(key))
Phyca11_dict1={}
Phyca11_dict2={}
iname3=raw_input('Enter path to the P. capsici predicted protein file: ')
entries_2 = quick_FASTA_reader(iname3)
for name, seq in entries_2:
data2=name.split('|')
Identifier=int(data2[2])
Phyca11_dict1[Identifier]=seq
Phyca11_dict2[Identifier]=seq
Newdict={}
for keya in Phyca11_dict1:
for keyb in dictPotentialOverlap:
if int(keya)==dictPotentialOverlap[keyb][6]:
try:
Phyca11_PcRxLR="%s,%s"%(keya, keyb)
Newdict[Phyca11_PcRxLR]=Phyca11_dict1.get(keya)
Phyca11_dict2.pop(keya)
except:
print 'Phyca11|%s is not in the predicted protein set'%(keya)
#If there is overlap, even partial, then only the RxLR seq is kept. If the RxLR seq is not in the protein predicted set, it is added
newfileout=open('C:\Users\gt41237\Overlapping_protein_with_PcRxLR.csv', 'wb')
for key in Newdict:
print>>newfileout, "%s,%s"%(key, Newdict.get(key))
newfileout.close()
iname4=raw_input('Enter path to the P. capsici truncated RxLR EER set: ')
entries_3 = quick_FASTA_reader(iname4)
for name, seq in entries_3:
Phyca11_dict2[name]=seq
for key in Phyca11_dict2:
try:
Idname=re.search('PcRxLR', key)
print>>fileout2, ">%s" %(key)
print>>fileout2, (Phyca11_dict2.get(key))
except:
print>>fileout2, ">Phyca11|%s" %(key)
print>>fileout2, (Phyca11_dict2.get(key))
continue
#Those section aboves are there to create an output file
|
994,466 | fdaf6eb7f3fa7866cf687bd438f28752dba7e4d4 | import numpy as np
class ServerModel:
def __init__(self, n_items, n_factors):
self.item_size = n_items
self.n_factors = n_factors
# randn genera un array di shape
# Viene generato un array positivo riempito con float casuali campionati da una distribuzione "normale" (gaussiana)
# univariata di media 0 e varianza 1
self.item_vecs = np.random.randn(n_items, n_factors)/10
self.item_bias = np.random.randn(n_items)/10
self.item_vecs_delta = np.copy(self.item_vecs)
self.item_bias_delta = np.copy(self.item_bias)
|
994,467 | 0c53df9d2627ed05a526757a189deecfc6f5ab42 | import requests
import json
def send_notification(player_ids, message):
headers = {
"Content-Type": "application/json; charset=utf-8",
}
headers['Authorization'] = 'Basic ' + app.config['ONESIGNAL_API_KEY']
payload = {
"app_id": app.config['ONESIGNAL_APP_ID'],
"include_player_ids": player_ids,
"contents": {
"en": message
}
}
req = requests.post(
"https://onesignal.com/api/v1/notifications",
headers=headers,
data=json.dumps(payload)
)
return req.status_code
def send_notification1(player_ids, message):
headers = {
"Content-Type": "application/json; charset=utf-8",
}
headers['Authorization'] = 'Basic ' + 'NDBhMGEyMGEtYTBiZS00YjQyLTgxMzAtMTViZTI2NDQyYmZh'
payload = {
"app_id": 'eb9b7d42-7c4e-451d-b87c-f79b20d13c88',
"android_background_data":"true",
"include_player_ids": player_ids,
"data": {
"type": "custom_message",
"message_id": "1",
"created_at": "Fri, 28 Dec 2016 13:37:00",
"message" : {
"title": "Get ready for Consult Direct!",
"message": "Add your bank details securely to get paid for online consultations.",
"summary_text": "",
"icon_type": "views",
"image_url": "",
"target_url": "",
"service": "consult"
}
},
"contents": {
}
}
req = requests.post(
"https://onesignal.com/api/v1/notifications",
headers=headers,
data=json.dumps(payload)
)
return req.status_code
|
994,468 | f20972ec9c710ac5ef9f5319d7b70a4a96075418 | '''
Посчитать четные и нечетные цифры введенного натурального числа. Например, если введено число 34560,
в нем 3 четные цифры (4, 6 и 0) и 2 нечетные (3 и 5).
'''
a = input('Введите целое число: ')
# Счетчик четных цифр
odd = 0
# Счетчик нечетных цифр:
even = 0
# Цикл выполняется столько раз, сколько цифр в числе
for i in range(len(a)):
# Пример получения цифры 6 (второй с конца) в числе 34560: 34560 % 100 = 60 (остаток от деления), затем этот
# остаток целочисленно делим на 10: 60 // 10 = 6
num = (int(a) % (10 ^ (i + 1))) // 10 ^ i
if num % 2 == 0:
odd += 1
else:
even += 1
print(f'Количество четных цифр в числе {a}: {odd}, количество нечетных цифр: {even}')
|
994,469 | 83d17f03563d8308ee3b46be6402f584551d765b | from flask import Flask, redirect
from flask_restful import Resource, Api
from agro_log_handler import AgroLogHandler
from rest import Build, Request, Result, Image, Log, Output
app = Flask(__name__)
def init_application(app, config):
"""
Reads config and registers blueprints.
:param Flask app: application instance
:param Object config: configuration object
"""
app.config.from_object(config)
api = Api(app)
api.add_resource(Build, config.WSPATH)
api.add_resource(Request, config.WSPATH + '/<request_id>')
api.add_resource(Result, config.WSPATH + '/<request_id>/result')
api.add_resource(Image, config.WSPATH + '/<request_id>/result/image')
api.add_resource(Output, config.WSPATH + '/<request_id>/result/output/<int:output_id>')
api.add_resource(Log, config.WSPATH + '/<request_id>/result/log')
AgroLogHandler(app).init()
app.logger.info("Flask Application initialized")
|
994,470 | a2e6c9852e97240b72ab441940772b29cdf5e3ac | from b import *
class User:
def __init__(self, name, zarp, day):
self.__wallet = Budget(name, zarp, day)
def get_user(self):
return self.__wallet |
994,471 | 3b08c82b7c91111b4dd53e458c83a15f8c65144d | from django import forms
from django.forms import extras
class LoginForm(forms.Form):
username = forms.CharField(max_length=30)
password = forms.CharField(widget=forms.PasswordInput)
class RegisterForm(forms.Form):
name = forms.CharField(max_length=30)
username = forms.CharField(max_length=30)
password = forms.CharField(
widget=forms.PasswordInput,
label=u'Create a password'
)
password2 = forms.CharField(
widget=forms.PasswordInput,
label=u'Re-enter password'
)
email = forms.EmailField()
gender = forms.ChoiceField(
widget=forms.Select,
choices=[('M', 'Male'), ('F', 'Female')]
)
birthdate = forms.DateField(widget=extras.SelectDateWidget(years=range(1950,2013)))
contactno = forms.IntegerField(
label=u'Phone number',
required=False
)
def clean_password2(self):
password = self.cleaned_data.get("password", "")
password2 = self.cleaned_data["password2"]
if password != password2:
raise forms.ValidationError("The two password didn't match.")
return password2
class UpdateForm(forms.Form):
name = forms.CharField(max_length=30)
email = forms.EmailField()
gender = forms.ChoiceField(
widget=forms.Select,
choices=[('M', 'Male'), ('F', 'Female')]
)
birthdate = forms.DateField(widget=extras.SelectDateWidget(years=range(1950,2013)))
contactno = forms.IntegerField(
label=u'Phone number',
required=False
)
class PasswordForm(forms.Form):
oldpassword = forms.CharField(
widget=forms.PasswordInput,
label=u'Enter old password'
)
password = forms.CharField(
widget=forms.PasswordInput,
label=u'Enter new password'
)
password2 = forms.CharField(
widget=forms.PasswordInput,
label=u'Re-enter new password'
)
def clean_password2(self):
password = self.cleaned_data.get("password", "")
password2 = self.cleaned_data["password2"]
if password != password2:
raise forms.ValidationError("The two password didn't match.")
return password2
|
994,472 | 3df473e7b48fd40c57d74006234bec1e4fa050f6 | import http
import base64
from openbrokerapi import errors, constants
from openbrokerapi.catalog import ServicePlan
from openbrokerapi.service_broker import Service
from tests import BrokerTestCase
class PrecheckTest(BrokerTestCase):
def setUp(self):
self.broker.catalog.return_value = [
Service(
id="service-guid-here",
name="",
description="",
bindable=True,
plans=[ServicePlan("plan-guid-here", name="", description="")],
)
]
def test_returns_401_if_request_not_contain_auth_header(self):
response = self.client.put(
"/v2/service_instances/abc",
headers={
"X-Broker-Api-Version": "2.13",
},
)
self.assertEqual(response.status_code, http.HTTPStatus.UNAUTHORIZED)
def test_returns_412_if_version_is_not_supported(self):
response = self.client.put(
"/v2/service_instances/abc",
headers={
"X-Broker-Api-Version": "2.9",
},
)
self.assertEqual(response.status_code, http.HTTPStatus.PRECONDITION_FAILED)
def test_returns_412_with_message_if_version_is_not_supported(self):
response = self.client.put(
"/v2/service_instances/abc",
headers={
"X-Broker-Api-Version": "2.9",
},
)
self.assertNotEqual(response.data, b"")
self.assertEqual(response.json, {"description": "Service broker requires version 2.13+."})
def test_returns_400_if_request_not_contains_version_header(self):
response = self.client.put("/v2/service_instances/abc", headers={"Authorization": self.auth_header})
self.assertEqual(response.status_code, http.HTTPStatus.BAD_REQUEST)
def test_returns_400_if_request_contains_originating_identity_header_with_missing_value(
self,
):
response = self.client.put(
"/v2/service_instances/abc",
headers={
"Authorization": self.auth_header,
"X-Broker-Api-Version": "2.13",
"X-Broker-Api-Originating-Identity": " test ", # missing value
},
)
self.assertEqual(response.status_code, http.HTTPStatus.BAD_REQUEST)
self.assertEqual(
response.json,
{
"description": 'Improper "X-Broker-API-Originating-Identity" header. not enough values to unpack (expected 2, got 1)'
},
)
def test_returns_400_if_request_contains_originating_identity_header_with_improper_base64_value(
self,
):
response = self.client.put(
"/v2/service_instances/abc",
headers={
"Authorization": self.auth_header,
"X-Broker-Api-Version": "2.13",
"X-Broker-Api-Originating-Identity": "test bad64encoding", # bad base64
},
)
self.assertEqual(response.status_code, http.HTTPStatus.BAD_REQUEST)
self.assertIn(
'Improper "X-Broker-API-Originating-Identity" header.',
response.json["description"],
)
def test_returns_400_if_request_contains_originating_identity_header_with_improper_json_value(
self,
):
response = self.client.put(
"/v2/service_instances/abc",
headers={
"Authorization": self.auth_header,
"X-Broker-Api-Version": "2.13",
"X-Broker-Api-Originating-Identity": "test "
+ base64.standard_b64encode(b'{"test:123}').decode("ascii"), # bad json
},
)
self.assertEqual(response.status_code, http.HTTPStatus.BAD_REQUEST)
self.assertEqual(
response.json,
{
"description": 'Improper "X-Broker-API-Originating-Identity" header. Unterminated string starting at: line 1 column 2 (char 1)'
},
)
def test_returns_500_with_json_body_if_exception_was_raised(self):
self.broker.deprovision.side_effect = Exception("Boooom!")
response = self.client.delete(
"/v2/service_instances/abc?plan_id=plan-guid-here&service_id=service-guid-here",
headers={
"Authorization": self.auth_header,
"X-Broker-Api-Version": "2.13",
},
)
self.assertEqual(response.status_code, http.HTTPStatus.INTERNAL_SERVER_ERROR)
self.assertEqual(response.json["description"], constants.DEFAULT_EXCEPTION_ERROR_MESSAGE)
def test_returns_500_with_json_body_if_service_exception_was_raised(self):
self.broker.deprovision.side_effect = errors.ServiceException("Boooom!")
response = self.client.delete(
"/v2/service_instances/abc?plan_id=plan-guid-here&service_id=service-guid-here",
headers={
"Authorization": self.auth_header,
"X-Broker-Api-Version": "2.13",
},
)
self.assertEqual(response.status_code, http.HTTPStatus.INTERNAL_SERVER_ERROR)
self.assertEqual(response.json["description"], constants.DEFAULT_EXCEPTION_ERROR_MESSAGE)
def test_returns_400_if_request_did_not_include_data(self):
response = self.client.put(
"/v2/service_instances/here-instance-id?accepts_incomplete=true",
headers={
"X-Broker-Api-Version": "2.13",
"Content-Type": "application/json",
"Authorization": self.auth_header,
},
)
self.assertEqual(response.status_code, http.HTTPStatus.BAD_REQUEST)
|
994,473 | efe64aa1d879a8a46640292bf8765bf89c1e3a7c | from flask_sqlalchemy import SQLAlchemy
from app import db
from datetime import datetime
from app.utils.exceptions import ValidationError
from flask import url_for, current_app
#This will delcare model class for earnings and its relevant model will be display over here .
class Earnings(db.Model):
__tablename__ = 'Earnings'
__table_args__ = {'extend_existing': True}
id = db.Column(db.Integer, primary_key=True)
Per_id = db.Column(db.Integer, db.ForeignKey('Persons.id'),nullable=False) # This is foreign key to Persons table so that id will be identify unique.
U_id = db.Column(db.Integer,db.ForeignKey('Users.id'),nullable=False,index=True)
Ear_per_name = db.Column(db.String(64), index=True)
Ear_type_name = db.Column(db.String(100),index=True)
Ear_amt = db.Column(db.Float)
Ear_date = db.Column(db.DateTime,index=True)
Ear_img = db.Column(db.LargeBinary)
Ear_FileName = db.Column(db.String(300))
Ear_comm = db.Column(db.String(200))
|
994,474 | 04ac2f5fc3e19ef1252a24f463d8efd5644b9afe | import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
from apps import commonmodules
from app import app
layout = html.Div([
commonmodules.get_header("Yammer Page"),
commonmodules.get_menu(),
]) |
994,475 | 2528456fda68ded4cf64f07d2933f4f3eb4ff361 | import numpy as np
import pytest
from d3rlpy.dataset import EpisodeGenerator, Shape
from ..testing_utils import create_observations
@pytest.mark.parametrize("observation_shape", [(4,), ((4,), (8,))])
@pytest.mark.parametrize("action_size", [2])
@pytest.mark.parametrize("length", [1000])
@pytest.mark.parametrize("terminal", [False, True])
def test_episode_generator(
observation_shape: Shape, action_size: int, length: int, terminal: bool
) -> None:
observations = create_observations(observation_shape, length)
actions = np.random.random((length, action_size))
rewards = np.random.random((length, 1))
terminals = np.zeros(length)
timeouts = np.zeros(length)
for i in range(length // 100):
if terminal:
terminals[(i + 1) * 100 - 1] = 1.0
else:
timeouts[(i + 1) * 100 - 1] = 1.0
episode_generator = EpisodeGenerator(
observations=observations,
actions=actions,
rewards=rewards,
terminals=terminals,
timeouts=timeouts,
)
episodes = episode_generator()
assert len(episodes) == length // 100
for episode in episodes:
assert len(episode) == 100
if isinstance(observation_shape[0], tuple):
for i, shape in enumerate(observation_shape):
assert isinstance(shape, tuple)
assert episode.observations[i].shape == (100, *shape)
else:
assert isinstance(episode.observations, np.ndarray)
assert episode.observations.shape == (100, *observation_shape)
assert episode.actions.shape == (100, action_size)
assert episode.rewards.shape == (100, 1)
assert episode.terminated == terminal
|
994,476 | 7a10516500598f4c8fa803efd7ac064d40643e2d | #Crie um programa que leia um número inteiro e mostre na tela se ele é PAR ou ÍMPAR.
número = int(input('Digite um número qualquer: '))
resultado = número % 2
if resultado == 0:
print('O número {} é PAR'.format(número))
else:
print('O número {} é IMPAR'.format(número)) |
994,477 | ed81249acd136ac682f8833ec09f75b65951332e | import numpy as np
from proposition1 import *
def main():
# proposition1()
return
if __name__ == '__main__':
main()
|
994,478 | 99b236d648bd5cafe4b0f62085475f3ee3080d86 | from keras.utils import np_utils
import sys
import keras
from keras import Sequential
from keras.layers import Dense, Dropout, Conv1D, Flatten, BatchNormalization, Activation, MaxPooling1D
from keras.callbacks import TensorBoard,ModelCheckpoint,EarlyStopping
from keras.optimizers import Adam,SGD
import numpy as np
import os
import shutil
import time
from utilities import get_data
dataset_path = '3_emotion'
print('Dataset path:',dataset_path)
print('Emotion:',os.listdir(dataset_path))
print('Num emotion:',len(os.listdir(dataset_path)))
x_train, x_test, y_train, y_test = get_data(dataset_path=dataset_path, max_duration = 4.0)
y_train = np_utils.to_categorical(y_train)
y_test = np_utils.to_categorical(y_test)
print('x_train:',x_train.shape)
print('y_train:',y_train.shape)
#create model
model = Sequential()
Ckernel_size = 3
Cstrides = 1
Ppool_size = 2
Pstrides = 2
padding = 'SAME'
acti = 'relu'
#CNN+LSTM
model.add(Conv1D(filters = 64, kernel_size = Ckernel_size, strides=Cstrides, padding=padding,input_shape=(x_train.shape[1], x_train.shape[2])))
model.add(BatchNormalization())
model.add(Activation(activation = acti))
model.add(MaxPooling1D(pool_size=Ppool_size, strides=Pstrides,padding=padding))
model.add(Conv1D(filters = 64, kernel_size = Ckernel_size, strides=Cstrides, padding=padding))
model.add(BatchNormalization())
model.add(Activation(activation = acti))
model.add(MaxPooling1D(pool_size=Ppool_size*2, strides=Pstrides*2, padding=padding))
model.add(Conv1D(filters = 128, kernel_size = Ckernel_size, strides=Cstrides, padding=padding))
model.add(BatchNormalization())
model.add(Activation(activation = acti))
model.add(MaxPooling1D(pool_size=Ppool_size*2, strides=Pstrides*2, padding=padding))
model.add(Flatten())
model.add(Dense(1024))
model.add(Dense(y_train.shape[1], activation='softmax'))
#compile model
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy'])
print(model.summary())
#save model to json file
model_json = model.to_json()
with open("model/model_json.json", "w") as json_file:
json_file.write(model_json)
#callback funtion
tensorboard = TensorBoard('tensorboard/log_model_{}'.format(int(time.time())), write_graph=True , write_images=True)
checkpointer = ModelCheckpoint("./model/weights_best.h5", monitor='val_acc', verbose=1, save_best_only=True, mode='auto')
print('===================================================')
print('Start trainning CNN model')
print('Run "tensorboard --logdir tensorboard" to view logs')
print('===================================================')
#fit
model.fit(x_train, y_train, batch_size=32, epochs=50, verbose=1, validation_split = 0.2, callbacks= [tensorboard,checkpointer])
#test model
print('Testing model')
loss,acc = model.evaluate(x_test, y_test)
print('===================================================')
print('Test Loss = {:.4f}'.format(loss))
print('Test Accu = {:.4f} %'.format(acc*100))
print('===================================================')
print("Train & Test done! Saved all to ./model for predict! ")
|
994,479 | d469cbe87d0ee55c8bf76c2bb1441c5d7423dfce | from telegraph import Telegraph
from telegraph import exceptions
class States:
S_START = 0 # Начало нового диалога
S_ENTER_TITLE = 1 # Ввод названия
S_ENTER_INGREDIENT = 2 # Ввод ингридиентов
S_ENTER_TEXT = 3 # Ввод рецепта
S_ENTER_TAG = 4 # Ввод тегов вручную
S_ADD_RECIPE = 5 # Добавление стороннего рецепта
S_SEARCH_CHOOSE = 6 # Выбор способа поиска
S_SEARCH_NAME = 7 # Поиск по названию
S_SEARCH_TAG = 8 # Поиск по тегам
class Article(object):
def __init__(self, A_Title, A_Author, A_Ingredient, A_Text, A_Tag):
self.A_Title = A_Title
self.A_Author = A_Author
self.A_Ingredient = A_Ingredient
self.A_Text = A_Text
self.A_Tag = A_Tag
def add_tag(self, A_Tag):
self.A_Tag += "#" + A_Tag + " "
def add_ingredient(self, A_Ingredient):
self.A_Ingredient += "<p>-" + A_Ingredient + "</p>"
def add_text(self, A_Text):
if self.A_Text == "empty":
self.A_Text = "<p>" + A_Text + "</p>"
else:
self.A_Text += "<p>" + A_Text + "</p>"
def re_text(self, A_Text):
self.A_Text = " "
def re_title(self, A_Title):
self.A_Title = A_Title
def re_name(self, A_Author):
self.A_Author = A_Author
def text_erase(self):
self.A_Text = ""
def get_title(self):
return self.A_Title
def publish_article(self):
try:
telegraph = Telegraph()
telegraph.create_account(short_name=self.A_Author)
response = telegraph.create_page(
self.A_Title,
html_content="<p>Состав: </p>"+self.A_Ingredient \
+"<hr>" + self.A_Text \
+ "<p>" + self.A_Tag + "</p>"
)
return 'https://telegra.ph/{}'.format(response['path'])
except exceptions.TelegraphException as Error:
print(Error)
pass |
994,480 | ff4179189b49d1f5645904b1cf005d332ef03c0a | import matplotlib.pyplot as plt
import numpy as np
import interpolation as inter
np.seterr(divide='ignore', invalid='ignore')
data = np.loadtxt('test.dat')
x = data[:,0]
y = data[:,1]
z = np.linspace(x[0],len(x),100)
plt.plot(x,y,'bo',label='Given points')
# linear spline interpolation
f1 = inter.linterp(x,y,z)
plt.plot(z,f1,label='Linear interpolation')
# quadratic spline interpolation
f2 = inter.qinterp(x,y,z)
plt.plot(z,f2,label='Quadratic interpolation')
# move legend to upper left, add shadows
legend = plt.legend(loc='upper left', shadow=True, fontsize='large')
# saving figure
plt.savefig('test.png',format='png')
|
994,481 | 0ebf02f807a606283e626272d26b7f45a05e79e3 | import os
import glob
from PIL import Image
from PIL import ImageEnhance
for tifFile in glob.glob(R"C:\Users\swharden\Documents\temp\test\*.tif"):
print("converting", os.path.basename(tifFile))
jpgFile = tifFile+".jpg"
im = Image.open(tifFile)
im = ImageEnhance.Contrast(im).enhance(7)
im.save(jpgFile) |
994,482 | c72237d451bbee93319c4cadc255227b3007a9da | # -*- coding=utf-8 -*-
import math
def is_not_empty(s):
# 不要None, 也不要长度为0的
# strip取出空字符'\n' '\r' '\t' ' '
return s and len(s.strip()) > 0
def is_sqr(x):
"""返回开根后为整数"""
# todo 如何判断是整数 math.sqrt(返回的结果是浮点数)
"""
1.先转换成int
2.然后逆向思维,看谁的平方等于100内的数
"""
r = int(math.sqrt(x))
"""
可以简写, return r*r == x
if r*r == x:
return x
"""
return r*r == x
# filter自动过滤None
# 免输git帐号和密码,3.新建'.gitconfig' 文件
print(filter(is_not_empty, ['test', None, '', 'str', ' ', 'END']))
print("100内开根号是整数列表是%s" % filter(is_sqr, range(1, 101)))
|
994,483 | 7a45cdd02d64deeda291496eafa699b655abea21 | import tensorflow as tf
import pickle
import codecs
from test import judge, dele_none
import numpy as np
import math
sequence_maxlen = 256
path = '/home/joyfly/桌面/inputs_data'
source_data = '/home/joyfly/桌面/word2id_data.pkl'
ckpt_path = '/home/joyfly/桌面/ckpt/'
maxlen = 256
def load_data():
"""
载入数据from pickle
:return: Arrays
"""
with open(source_data, 'rb') as f:
tag2id = pickle.load(f)
id2tag = pickle.load(f)
word2id = pickle.load(f)
id2word = pickle.load(f)
return tag2id, id2tag, word2id, id2word
tag2id, id2tag, word2id, id2word = load_data()
def word_trans(word):
ids = list(word2id[word])
if len(ids) >= maxlen:
ids = ids[:maxlen]
ids.extend([0] * (maxlen - len(ids)))
return ids
inputs_data = codecs.open(path, 'r', 'utf-8')
new_data = []
for line in inputs_data:
if 256 < len(line) <= 512:
middle_num = len(line) // 2
for i in range(middle_num):
if line[middle_num + i].isspace():
line1 = line[:middle_num + i]
line2 = line[middle_num + i + 1:]
new_data.append(line1)
new_data.append(line2)
break
elif len(line) <= 256:
new_data.append(line)
data_list = []
for line in new_data:
line_data = []
line = line.strip().split()
for word in line:
for i in word:
if u'\u4E00' <= i <= u'\u9FEF':
line_data.extend(i)
data_list.append(line_data)
data_word = list(map(lambda x: word_trans(x), data_list))
for line in data_word:
for i in range(len(line)):
line[i] = math.floor(line[i])
test_word = tf.data.Dataset.from_tensor_slices(data_word)
iterator = test_word.make_one_shot_iterator()
try:
inputs = iterator.get_next()
list = inputs.get_shape().as_list()
except tf.errors.OutOfRangeError:
print('已经取完')
sess = tf.Session()
saver = tf.train.import_meta_graph(ckpt_path + 'model.ckpt-197.meta')
saver.restore(sess, tf.train.latest_checkpoint(ckpt_path))
graph = tf.get_default_graph()
keep_prob = graph.get_tensor_by_name('keep_prob:0')
begin_pre_labels_reshape = graph.get_tensor_by_name('begin_pre_labels_reshape:0')
sess.run(iterator)
#
# print('迭代器完成')
#
data_label_pre_result, data_word_result = sess.run([begin_pre_labels_reshape, inputs], feed_dict={keep_prob: 1})
print(data_label_pre_result)
#
# print('得到标注标签')
# for i in range(len(data_label_pre_result)):
# data_word_result_final = list(filter(lambda x: x, data_word_result[i]))
# data_label_result_final = list(map(judge, data_label_pre_result[i]))
# y_predict_label_final = dele_none(data_label_result_final)
# word_x = ''.join(id2word[data_word_result_final].values)
# label_y = ''.join(id2tag[y_predict_label_final].values)
# print(word_x, label_y)
|
994,484 | 3e152e78f81689aa17f8163e385c4f59f648cd0b | # -*- coding: utf-8 -*-
import numpy as np
import math
def sine_wave_generator(fs, t, spl_value, freq):
"""It creates a sine wave signal given some input parameters like frequency, duration, sampling rate or sound
pressure level.
Parameters
----------
fs: int
'Hz', sampling frequency.
t: int
's', signal duration.
spl_value: int
'dB SPL', signal sound pressure level.
freq: int
'Hz', sine wave frequency.
Returns
-------
signal: numpy.array
'Pa', time signal values. For ECMA-418-2 the sampling frequency of the signal must be 48000 Hz.
time: numpy.array
Time scale arranged in a numpy array.
"""
# "Peak" value in Pascals (amplitude)
p_ref = 2e-5
pressure_rms = p_ref * (10.00 ** (spl_value / 20.00))
# Sample range
# samples = np.linspace(0, t, int(fs * t), endpoint=False)
time = np.arange(0, t, 1 / fs)
# Theta lets you specify the sine wave value at time 0
theta = 0
# Amplitude of the signal
amplitude = np.sqrt(2) * pressure_rms
# Signal calculation
signal = np.array(amplitude * np.sin((2.00 * math.pi * freq * time) + theta))
return signal, time
|
994,485 | f09729d82005fad7c41ec6c44498e5250fbcc45f | from django.db import models
from django.contrib.auth.models import AbstractUser
from django.utils.translation import ugettext_lazy as _
from django.core.validators import EmailValidator
from django.contrib.auth.validators import UnicodeUsernameValidator
class Player(AbstractUser):
"""
This class extends the Abstract User class to leverage Django's default user authentication
while allowing us to add some additional information
"""
username_validator = UnicodeUsernameValidator()
email_validator = EmailValidator()
username = models.CharField(
verbose_name=_('username'),
max_length=150,
unique=False,
blank=False,
help_text=_('Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.'),
validators=[username_validator],
)
email = models.EmailField(
verbose_name=_('email address'),
max_length=255,
unique=True,
help_text=_('Required. 255 characters or fewer.'),
validators=[email_validator],
error_messages={
'unique': _("A user with that email address already exists!")
}
)
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['username']
def __str__(self):
return self.email
|
994,486 | 5bbf4c00e9bd8b1a1aad54918f9d048c0c7a32d7 | __author__ = 'Amad'
import requests
from . serializer import TrendsSerializer
from rest_framework.decorators import api_view
from rest_framework.response import Response # to send specific response
from rest_framework import status
class BestbuyAPI():
def PopularMobiles(self,request):
try:
response = requests.get("https://api.bestbuy.com/beta/products/mostViewed(categoryId=pcmcat209400050001)?apiKey=KZf1Tiuxlc7AxMnSGbT11Xv3")
data =response.json()
print(data)
for item in data['results']:
request["SNR_Title"]=item["names"]["title"];
request["SNR_PriceMin"]="0";
request["SNR_PriceMax"]=item["prices"]["current"];
request["SNR_ProductURL"]=item["links"]["web"];
request["SNR_AvailableAt"]="Best Buy"
request["SNR_ImageURL"]=item["images"]["standard"];
request["SNR_Description"] = item["descriptions"]["short"];
request["SNR_Type"] = "Popular";
request["SNR_Category"] = "mobile";
#print(item["sku"])
# print(item["links"]["web"])
# print(item["prices"]["current"])
# print(item["descriptions"]["short"])
# print(item["images"]["standard"])
# print(item["names"]["title"])
serializer = TrendsSerializer(data=request)
if serializer.is_valid():
print "-----"
serializer.save()
else:
print "bad json"
# return Response(serializer.errors, status=status.HTTP_406_NOT_ACCEPTABLE)
except StandardError as e:
print(e.message)
def Popularlaptops(self,request):
try:
response = requests.get("https://api.bestbuy.com/beta/products/mostViewed(categoryId=abcat0502000)?apiKey=KZf1Tiuxlc7AxMnSGbT11Xv3")
data =response.json()
print(data)
for item in data['results']:
request["SNR_Title"]=item["names"]["title"];
request["SNR_PriceMin"]="0";
request["SNR_PriceMax"]=item["prices"]["current"];
request["SNR_ProductURL"]=item["links"]["web"];
request["SNR_AvailableAt"]="Best Buy"
request["SNR_ImageURL"]=item["images"]["standard"];
request["SNR_Description"] = item["descriptions"]["short"];
request["SNR_Type"] = "Popular";
request["SNR_Category"] = "laptop";
#print(item["sku"])
# print(item["links"]["web"])
# print(item["prices"]["current"])
# print(item["descriptions"]["short"])
# print(item["images"]["standard"])
# print(item["names"]["title"])
serializer = TrendsSerializer(data=request)
if serializer.is_valid():
print "-----"
serializer.save()
else:
print "bad json"
# return Response(serializer.errors, status=status.HTTP_406_NOT_ACCEPTABLE)
except StandardError as e:
print(e.message)
def AllCategoriesTrend(self,request):
try:
print "amad"
response = requests.get("https://api.bestbuy.com/beta/products/trendingViewed(categoryId=pcmcat209400050001)?apiKey=KZf1Tiuxlc7AxMnSGbT11Xv3")
data =response.json()
print(data)
for item in data['results']:
request["SNR_Title"]=item["names"]["title"];
request["SNR_PriceMin"]="0";
request["SNR_PriceMax"]=item["prices"]["current"];
request["SNR_ProductURL"]=item["links"]["web"];
request["SNR_AvailableAt"]="Best Buy"
request["SNR_ImageURL"]=item["images"]["standard"];
request["SNR_Type"] = "Trending";
request["SNR_Category"] = "phone mobile";
#print(item["sku"])
# print(item["links"]["web"])
# print(item["prices"]["current"])
# print(item["descriptions"]["short"])
# print(item["images"]["standard"])
# print(item["names"]["title"])
serializer = TrendsSerializer(data=request)
if serializer.is_valid():
serializer.save()
else:
print serializer.error_messages
except StandardError as e:
print(e.message)
try:
response = requests.get("https://api.bestbuy.com/beta/products/trendingViewed(categoryId=abcat0401000)?apiKey=KZf1Tiuxlc7AxMnSGbT11Xv3")
data =response.json()
print(data)
for item in data['results']:
request["SNR_Title"]=item["names"]["title"];
request["SNR_PriceMin"]="0";
request["SNR_PriceMax"]=item["prices"]["current"];
request["SNR_ProductURL"]=item["links"]["web"];
request["SNR_AvailableAt"]="Best Buy"
request["SNR_ImageURL"]=item["images"]["standard"];
request["SNR_Type"] = "Trending";
request["SNR_Category"] = "Cam"
#print(item["sku"])
# print(item["links"]["web"])
# print(item["prices"]["current"])
# print(item["descriptions"]["short"])
# print(item["images"]["standard"])
# print(item["names"]["title"])
serializer = TrendsSerializer(data=request)
if serializer.is_valid():
serializer.save()
else:
print(serializer.error_messages)
except StandardError as e:
print(e.message)
try:
response = requests.get("https://api.bestbuy.com/beta/products/trendingViewed(categoryId=abcat0501000)?apiKey=KZf1Tiuxlc7AxMnSGbT11Xv3")
data =response.json()
print(data)
for item in data['results']:
request["SNR_Title"]=item["names"]["title"];
request["SNR_PriceMin"]="0";
request["SNR_PriceMax"]=item["prices"]["current"];
request["SNR_ProductURL"]=item["links"]["web"];
request["SNR_AvailableAt"]="Best Buy"
request["SNR_ImageURL"]=item["images"]["standard"];
request["SNR_Type"] = "Trending";
request["SNR_Category"] = "desktop"
#print(item["sku"])
# print(item["links"]["web"])
# print(item["prices"]["current"])
# print(item["descriptions"]["short"])
# print(item["images"]["standard"])
# print(item["names"]["title"])
serializer = TrendsSerializer(data=request)
if serializer.is_valid():
serializer.save()
else:
print "bad json"
except StandardError as e:
print(e.message)
try:
response = requests.get("https://api.bestbuy.com/beta/products/trendingViewed(categoryId=pcmcat209400050001)?apiKey=KZf1Tiuxlc7AxMnSGbT11Xv3")
data =response.json()
print(data)
for item in data['results']:
request["SNR_Title"]=item["names"]["title"];
request["SNR_PriceMin"]="0";
request["SNR_PriceMax"]=item["prices"]["current"];
request["SNR_ProductURL"]=item["links"]["web"];
request["SNR_AvailableAt"]="Best Buy"
request["SNR_ImageURL"]=item["images"]["standard"];
request["SNR_Type"] = "Trending";
request["SNR_Category"] = "audio";
#print(item["sku"])
# print(item["links"]["web"])
# print(item["prices"]["current"])
# print(item["descriptions"]["short"])
# print(item["images"]["standard"])
# print(item["names"]["title"])
serializer = TrendsSerializer(data=request)
if serializer.is_valid():
serializer.save()
else:
print "bad json"
except StandardError as e:
print(e.message)
except StandardError as e:
print(e.message)
try:
response = requests.get("https://api.bestbuy.com/beta/products/trendingViewed(categoryId=pcmcat254000050002)?apiKey=KZf1Tiuxlc7AxMnSGbT11Xv3")
data =response.json()
# print(data)
for item in data['results']:
request["SNR_Title"]=item["names"]["title"];
request["SNR_PriceMin"]="0";
request["SNR_PriceMax"]=item["prices"]["current"];
request["SNR_ProductURL"]=item["links"]["web"];
request["SNR_AvailableAt"]="Best Buy"
request["SNR_ImageURL"]=item["images"]["standard"];
request["SNR_Type"] = "Trending";
request["SNR_Category"] = "security";
#print(item["sku"])
# print(item["links"]["web"])
# print(item["prices"]["current"])
# print(item["descriptions"]["short"])
# print(item["images"]["standard"])
# print(item["names"]["title"])
serializer = TrendsSerializer(data=request)
if serializer.is_valid():
serializer.save()
else:
print "bad json"
except StandardError as e:
print(e.message)
try:
response = requests.get("https://api.bestbuy.com/beta/products/trendingViewed(categoryId=pcmcat209000050006)?apiKey=KZf1Tiuxlc7AxMnSGbT11Xv3")
data =response.json()
# print(data)
for item in data['results']:
request["SNR_Title"]=item["names"]["title"];
request["SNR_PriceMin"]="0";
request["SNR_PriceMax"]=item["prices"]["current"];
request["SNR_ProductURL"]=item["links"]["web"];
request["SNR_AvailableAt"]="Best Buy"
request["SNR_ImageURL"]=item["images"]["standard"];
request["SNR_Type"] = "Trending";
request["SNR_Category"] = "ipad";
#print(item["sku"])
# print(item["links"]["web"])
# print(item["prices"]["current"])
# print(item["descriptions"]["short"])
# print(item["images"]["standard"])
# print(item["names"]["title"])
serializer = TrendsSerializer(data=request)
if serializer.is_valid():
serializer.save()
else:
print "bad json"
except StandardError as e:
print(e.message)
try:
response = requests.get("https://api.bestbuy.com/beta/products/trendingViewed(categoryId=abcat0502000)?apiKey=KZf1Tiuxlc7AxMnSGbT11Xv3")
data =response.json()
# print(data)
for item in data['results']:
request["SNR_Title"]=item["names"]["title"];
request["SNR_PriceMin"]="0";
request["SNR_PriceMax"]=item["prices"]["current"];
request["SNR_ProductURL"]=item["links"]["web"];
request["SNR_AvailableAt"]="Best Buy"
request["SNR_ImageURL"]=item["images"]["standard"];
request["SNR_Type"] = "Trending";
request["SNR_Category"] = "laptop";
#print(item["sku"])
# print(item["links"]["web"])
# print(item["prices"]["current"])
# print(item["descriptions"]["short"])
# print(item["images"]["standard"])
# print(item["names"]["title"])
serializer = TrendsSerializer(data=request)
if serializer.is_valid():
serializer.save()
else:
print "bad json"
except StandardError as e:
print(e.message)
try:
response = requests.get("https://api.bestbuy.com/beta/products/trendingViewed(categoryId=pcmcat232900050000)?apiKey=KZf1Tiuxlc7AxMnSGbT11Xv3")
data =response.json()
# print(data)
for item in data['results']:
request["SNR_Title"]=item["names"]["title"];
request["SNR_PriceMin"]="0";
request["SNR_PriceMax"]=item["prices"]["current"];
request["SNR_ProductURL"]=item["links"]["web"];
request["SNR_AvailableAt"]="Best Buy"
request["SNR_ImageURL"]=item["images"]["standard"];
request["SNR_Type"] = "Trending";
request["SNR_Category"] = "nintendo";
#print(item["sku"])
# print(item["links"]["web"])
# print(item["prices"]["current"])
# print(item["descriptions"]["short"])
# print(item["images"]["standard"])
# print(item["names"]["title"])
serializer = TrendsSerializer(data=request)
if serializer.is_valid():
serializer.save()
else:
print "bad json"
except StandardError as e:
print(e.message)
try:
response = requests.get("https://api.bestbuy.com/beta/products/trendingViewed(categoryId=pcmcat295700050012)?apiKey=KZf1Tiuxlc7AxMnSGbT11Xv3")
data =response.json()
# print(data)
for item in data['results']:
request["SNR_Title"]=item["names"]["title"];
request["SNR_PriceMin"]="0";
request["SNR_PriceMax"]=item["prices"]["current"];
request["SNR_ProductURL"]=item["links"]["web"];
request["SNR_AvailableAt"]="Best Buy"
request["SNR_ImageURL"]=item["images"]["standard"];
request["SNR_Type"] = "Trending";
request["SNR_Category"] = "play station";
#print(item["sku"])
# print(item["links"]["web"])
# print(item["prices"]["current"])
# print(item["descriptions"]["short"])
# print(item["images"]["standard"])
# print(item["names"]["title"])
serializer = TrendsSerializer(data=request)
if serializer.is_valid():
serializer.save()
else:
print "bad json"
except StandardError as e:
print(e.message)
try:
response = requests.get("https://api.bestbuy.com/beta/products/trendingViewed(categoryId=abcat0502000)?apiKey=KZf1Tiuxlc7AxMnSGbT11Xv3")
data =response.json()
# print(data)
for item in data['results']:
request["SNR_Title"]=item["names"]["title"];
request["SNR_PriceMin"]="0";
request["SNR_PriceMax"]=item["prices"]["current"];
request["SNR_ProductURL"]=item["links"]["web"];
request["SNR_AvailableAt"]="Best Buy"
request["SNR_ImageURL"]=item["images"]["standard"];
request["SNR_Type"] = "Trending";
request["SNR_Category"] = "kitchen appliances";
#print(item["sku"])
# print(item["links"]["web"])
# print(item["prices"]["current"])
# print(item["descriptions"]["short"])
# print(item["images"]["standard"])
# print(item["names"]["title"])
serializer = TrendsSerializer(data=request)
if serializer.is_valid():
serializer.save()
else:
print "bad json"
except StandardError as e:
print(e.message)
try:
response = requests.get("https://api.bestbuy.com/beta/products/trendingViewed(categoryId=abcat0904000)?apiKey=KZf1Tiuxlc7AxMnSGbT11Xv3")
data =response.json()
# print(data)
for item in data['results']:
request["SNR_Title"]=item["names"]["title"];
request["SNR_PriceMin"]="0";
request["SNR_PriceMax"]=item["prices"]["current"];
request["SNR_ProductURL"]=item["links"]["web"];
request["SNR_AvailableAt"]="Best Buy"
request["SNR_ImageURL"]=item["images"]["standard"];
request["SNR_Type"] = "Trending";
request["SNR_Category"] = "ovan";
#print(item["sku"])
# print(item["links"]["web"])
# print(item["prices"]["current"])
# print(item["descriptions"]["short"])
# print(item["images"]["standard"])
# print(item["names"]["title"])
serializer = TrendsSerializer(data=request)
if serializer.is_valid():
serializer.save()
else:
print "bad json"
except:
print(serializer.error_messages)
try:
response = requests.get("https://api.bestbuy.com/beta/products/trendingViewed(categoryId=pcmcat242800050021)?apiKey=KZf1Tiuxlc7AxMnSGbT11Xv3")
data =response.json()
# print(data)
for item in data['results']:
request["SNR_Title"]=item["names"]["title"];
request["SNR_PriceMin"]="0";
request["SNR_PriceMax"]=item["prices"]["current"];
request["SNR_ProductURL"]=item["links"]["web"];
request["SNR_AvailableAt"]="Best Buy"
request["SNR_ImageURL"]=item["images"]["standard"];
request["SNR_Type"] = "Trending";
request["SNR_Category"] = "health fitness";
#print(item["sku"])
# print(item["links"]["web"])
# print(item["prices"]["current"])
# print(item["descriptions"]["short"])
# print(item["images"]["standard"])
# print(item["names"]["title"])
serializer = TrendsSerializer(data=request)
if serializer.is_valid():
serializer.save()
else:
print "bad json"
except StandardError as e:
print(e.message)
try:
response = requests.get("https://api.bestbuy.com/beta/products/trendingViewed(categoryId=abcat0901000)?apiKey=KZf1Tiuxlc7AxMnSGbT11Xv3")
data =response.json()
# print(data)
for item in data['results']:
request["SNR_Title"]=item["names"]["title"];
request["SNR_PriceMin"]="0";
request["SNR_PriceMax"]=item["prices"]["current"];
request["SNR_ProductURL"]=item["links"]["web"];
request["SNR_AvailableAt"]="Best Buy"
request["SNR_ImageURL"]=item["images"]["standard"];
request["SNR_Type"] = "Trending";
request["SNR_Category"] = "Refrigerators";
#print(item["sku"])
# print(item["links"]["web"])
# print(item["prices"]["current"])
# print(item["descriptions"]["short"])
# print(item["images"]["standard"])
# print(item["names"]["title"])
serializer = TrendsSerializer(data=request)
if serializer.is_valid():
serializer.save()
else:
print "bad json"
except StandardError as e:
print(e.message)
try:
response = requests.get("https://api.bestbuy.com/beta/products/trendingViewed(categoryId=abcat0912000)?apiKey=KZf1Tiuxlc7AxMnSGbT11Xv3")
data =response.json()
# print(data)
for item in data['results']:
request["SNR_Title"]=item["names"]["title"];
request["SNR_PriceMin"]="0";
request["SNR_PriceMax"]=item["prices"]["current"];
request["SNR_ProductURL"]=item["links"]["web"];
request["SNR_AvailableAt"]="Best Buy"
request["SNR_ImageURL"]=item["images"]["standard"];
request["SNR_Type"] = "Trending";
request["SNR_Category"] = "appliances";
#print(item["sku"])
# print(item["links"]["web"])
# print(item["prices"]["current"])
# print(item["descriptions"]["short"])
# print(item["images"]["standard"])
# print(item["names"]["title"])
serializer = TrendsSerializer(data=request)
if serializer.is_valid():
serializer.save()
else:
print "bad json"
except StandardError as e:
print(e.message)
try:
response = requests.get("https://api.bestbuy.com/beta/products/trendingViewed(categoryId=abcat0101000)?apiKey=KZf1Tiuxlc7AxMnSGbT11Xv3")
data =response.json()
# print(data)
for item in data['results']:
request["SNR_Title"]=item["names"]["title"];
request["SNR_PriceMin"]="0";
request["SNR_PriceMax"]=item["prices"]["current"];
request["SNR_ProductURL"]=item["links"]["web"];
request["SNR_AvailableAt"]="Best Buy"
request["SNR_ImageURL"]=item["images"]["standard"];
request["SNR_Type"] = "Trending";
request["SNR_Category"] = "tvs";
#print(item["sku"])
# print(item["links"]["web"])
# print(item["prices"]["current"])
# print(item["descriptions"]["short"])
# print(item["images"]["standard"])
# print(item["names"]["title"])
serializer = TrendsSerializer(data=request)
if serializer.is_valid():
serializer.save()
else:
print "bad json"
except StandardError as e:
print(e.message)
try:
response = requests.get("https://api.bestbuy.com/beta/products/trendingViewed(categoryId=abcat0910000)?apiKey=KZf1Tiuxlc7AxMnSGbT11Xv3")
data =response.json()
# print(data)
for item in data['results']:
request["SNR_Title"]=item["names"]["title"];
request["SNR_PriceMin"]="0";
request["SNR_PriceMax"]=item["prices"]["current"];
request["SNR_ProductURL"]=item["links"]["web"];
request["SNR_AvailableAt"]="Best Buy"
request["SNR_ImageURL"]=item["images"]["standard"];
request["SNR_Type"] = "Trending";
request["SNR_Category"] = "washers dryers";
#print(item["sku"])
# print(item["links"]["web"])
# print(item["prices"]["current"])
# print(item["descriptions"]["short"])
# print(item["images"]["standard"])
# print(item["names"]["title"])
serializer = TrendsSerializer(data=request)
if serializer.is_valid():
serializer.save()
else:
print "bad json"
except StandardError as e:
print(e.message)
try:
response = requests.get("https://api.bestbuy.com/beta/products/trendingViewed(categoryId=pcmcat300300050002)?apiKey=KZf1Tiuxlc7AxMnSGbT11Xv3")
data =response.json()
# print(data)
for item in data['results']:
request["SNR_Title"]=item["names"]["title"];
request["SNR_PriceMin"]="0";
request["SNR_PriceMax"]=item["prices"]["current"];
request["SNR_ProductURL"]=item["links"]["web"];
request["SNR_AvailableAt"]="Best Buy"
request["SNR_ImageURL"]=item["images"]["standard"];
request["SNR_Type"] = "Trending";
request["SNR_Category"] = "Xbox";
#print(item["sku"])
# print(item["links"]["web"])
# print(item["prices"]["current"])
# print(item["descriptions"]["short"])
# print(item["images"]["standard"])
# print(item["names"]["title"])
serializer = TrendsSerializer(data=request)
if serializer.is_valid():
serializer.save()
else:
print "bad json"
except StandardError as e:
print(e.message)
|
994,487 | 5980570ce5198faad0b96a77c4d9b899f448d500 | from abc import ABC
import pygame
class GameButton(ABC):
# content parameter can be text or image
def __init__(self, x, y, width, height, content, color):
self.x = x
self.y = y
self.width = width
self.height = height
self.content = content
self.color = color
def is_over(self, pos):
if self.x < pos[0] < self.x + self.width:
if self.y < pos[1] < self.y + self.height:
return True
return False
def draw(self, win):
pass
class EndGameButton(GameButton):
def draw(self, win):
pygame.draw.rect(win, self.color, (self.x, self.y, self.width, self.height))
font = pygame.font.SysFont('comicsans', 40)
text = font.render(self.content, 1, (0, 0, 0))
win.blit(text, (int(self.x + self.width/2 - text.get_width()/2),
int(self.y + self.height/2 - text.get_height()/2)))
class FigureButton(GameButton):
def draw(self, win):
pygame.draw.rect(win, self.color, (self.x, self.y, self.width, self.height), 3)
img = pygame.image.load(self.content)
win.blit(img, (self.x + 7, self.y + 7))
|
994,488 | 04741e8c12517d6f991b813af4fea7b00da88d2e | from plugin import blueprint, menu, plugin_load, plugin_unload, plugin_info
from model import ModelCustom |
994,489 | 8d0d6d6eee0a6bb4b2e09b6d0326e6d214dc4326 | from sqlalchemy import Column, Integer, Text, ForeignKey, DateTime, orm
from sqlalchemy.ext.associationproxy import association_proxy
from sqlalchemy.sql.functions import now
from springboard.models import Base
class Board(Base):
__tablename__ = "boards"
id = Column(Integer, primary_key=True)
name = Column(Text)
description = Column(Text)
user_id = Column(Integer, ForeignKey("users.id", ondelete="cascade"))
pinned_product_refs = orm.relationship("BoardProductPinnedRef",
cascade="all, delete-orphan",
order_by="desc(BoardProductPinnedRef.pinned_at)")
pinned_products = association_proxy("pinned_product_refs", "product",
creator=lambda product: BoardProductPinnedRef(product=product))
def __repr__(self):
return "<Board {}: {}>".format(self.id, self.name)
class BoardProductPinnedRef(Base):
__tablename__ = "board_product_pinned_refs"
board_id = Column(Integer, ForeignKey("boards.id", ondelete="cascade"),
primary_key=True)
product_id = Column(Integer, ForeignKey("products.id", ondelete="cascade"),
primary_key=True)
pinned_at = Column(DateTime, default=now())
product = orm.relationship("Product")
|
994,490 | 3712d14242d55487244d259ce910768879b77e65 | import rest_framework
from rest_framework.permissions import BasePermission
class MyPermissions(BasePermission):
'''The permissions set here will allow the a normal user to access only the GET API request and staff user to access
all of the request methods'''
def has_permission(self, request, view):
if request.method == 'GET' and request.user.is_active:
return True
if request.method in ['GET', 'POST','PUT','DELETE', 'PATCH'] and request.user.is_staff:
return True
return False
|
994,491 | edfbd1adc9f039b3a4703629704e56e460375f52 | import pymongo
import json
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
#print(myclient.list_database_names())
def insert_into_database(name, topic):
#print("name: ", name)
#print("topic: ", topic)
mongoClientDB = myclient['mywikidump']
collection = mongoClientDB[topic]
topic = topic + '.xml'
json_file = open(name, encoding="utf8")
array = [line[:-1] for line in json_file]
array[-1] = array[-1] + "}"
#json_file = json.dumps(json_file)
#data = json.load(json_file)
#print(array)
final_array = []
#for item in array:
#final_array.append(json.loads(item))
#print(final_array)
#collection.insert_many(array, ordered=False)
for item in array:
#pass
#print("item: ", item)
ins = json.loads(item)
collection.insert(ins) |
994,492 | 7310d14b430dcb073ff437ad08cec5ffde9d0267 | # Generated by Django 3.0 on 2021-08-17 15:48
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Rubro',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('nombre', models.CharField(max_length=50)),
],
),
migrations.CreateModel(
name='SubRubro',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('nombre', models.CharField(max_length=50)),
('rubro', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='mi_rubro', to='genericos.Rubro')),
],
),
]
|
994,493 | e6cddc1daf75dbb0fa99137b5540b70d64708f49 | """
Module to test api connections, very hacky
"""
import socket
def send_message(m):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(("127.0.0.1", 30030))
sock.sendall(m)
sock.close()
if __name__ == "__main__":
send_message("hello world")
|
994,494 | 1e07a59c76e055b7b42871cd9219298d8355681d | import logging
from jmeter_api.basics.assertion.elements import BasicAssertion
from jmeter_api.basics.utils import Renderable, tree_to_str
class JSONAssertion(BasicAssertion, Renderable):
root_element_name = 'JSONPathAssertion'
def __init__(self, *,
validation: bool = False,
expect_null: bool = False,
invert: bool = False,
is_regex: bool = True,
expected_value: str = '',
json_path: str = '$.',
name: str = 'JSON Assertion',
comments: str = '',
is_enabled: bool = True
):
self.validation = validation
self.expect_null = expect_null
self.invert = invert
self.is_regex = is_regex
self.expected_value = expected_value
self.json_path = json_path
BasicAssertion.__init__(
self, name=name, comments=comments, is_enabled=is_enabled)
@property
def json_path(self) -> str:
return self._json_path
@json_path.setter
def json_path(self, value):
if not isinstance(value, str):
raise TypeError(
f'json_path must be str. {type(value).__name__} was given')
self._json_path = value
@property
def expected_value(self) -> str:
return self._expected_value
@expected_value.setter
def expected_value(self, value):
if not isinstance(value, str):
raise TypeError(
f'expected_value must be str. {type(value).__name__} was given')
self._expected_value = value
@property
def validation(self) -> bool:
return self._validation
@validation.setter
def validation(self, value):
if not isinstance(value, bool):
raise TypeError(
f'validation must be bool. {type(value).__name__} was given')
self._validation = value
@property
def expect_null(self) -> bool:
return self._expect_null
@expect_null.setter
def expect_null(self, value):
if not isinstance(value, bool):
raise TypeError(
f'expect_null must be bool. {type(value).__name__} was given')
self._expect_null = value
@property
def invert(self) -> bool:
return self._invert
@invert.setter
def invert(self, value):
if not isinstance(value, bool):
raise TypeError(
f'invert must be bool. {type(value).__name__} was given')
self._invert = value
@property
def is_regex(self) -> bool:
return self._is_regex
@is_regex.setter
def is_regex(self, value):
if not isinstance(value, bool):
raise TypeError(
f'is_regex must be bool. {type(value).__name__} was given')
self._is_regex = value
def to_xml(self) -> str:
element_root, xml_tree = super()._add_basics()
for element in list(element_root):
try:
if element.attrib['name'] == 'JSON_PATH':
element.text = self.json_path
elif element.attrib['name'] == 'EXPECTED_VALUE':
element.text = str(self.expected_value).lower()
elif element.attrib['name'] == 'JSONVALIDATION':
element.text = str(self.validation).lower()
elif element.attrib['name'] == 'EXPECT_NULL':
element.text = str(self.expect_null).lower()
elif element.attrib['name'] == 'INVERT':
element.text = str(self.invert).lower()
elif element.attrib['name'] == 'ISREGEX':
element.text = str(self.is_regex).lower()
except KeyError:
logging.error('Unable to set xml parameters')
return tree_to_str(xml_tree)
|
994,495 | b19208916ffa3df83beba14f26041801661f6ea2 | NONE = ' '
BLACK = 'B'
WHITE = 'W'
class GameState:
def __init__(self, col, row,turn, position):
self._rows = row
self._cols = col
self._board = self.new_game_board()
self._turn = turn
self.set_piece(position.lower())
self._blacks = 0
self._whites = 0
self._empty = (col * row)
self.print_board()
def new_game_board(self):
board = []
for row in range(self._rows):
board.append([])
for col in range(self._cols):
board[-1].append(NONE)
return board
def print_board(self):
counterblack=0
counterwhite=0
print(' ', end ='')
for col in range(self._cols):
if col < 10:
print('0'+str(col), end = ' ')
else:
print(col, end = ' ')
print()
for row in range(self._rows):
if row < 10:
print('0'+str(row), end = ' ')
else:
print(row, end = ' ')
for col in range(self._cols):
if self._board[row][col] == NONE:
print('.', end = ' ')
if self._board[row][col] == BLACK:
print('B', end = ' ')
counterblack += 1
elif self._board[row][col] == WHITE:
print('W', end = ' ')
counterwhite += 1
print()
print('BLACK =' + str(counterblack) + ' WHITE =' + str(counterwhite))
self._blacks = counterblack
self._whites = counterwhite
self._empty = self._rows * self._cols - (self._blacks + self._whites)
def set_piece(self, white_or_black):
'''used for setting the inputted piece at top left at the beginning of the game'''
if white_or_black == 'white':
self._board[int(self._rows/2)-1][int(self._cols/2)-1] = WHITE
self._board[int(self._rows/2)-1][int((self._cols/2))] = BLACK
self._board[int((self._rows/2))][int(self._cols/2)] = WHITE
self._board[int((self._rows/2))][int(self._cols/2)-1] = BLACK
if white_or_black == 'black':
self._board[int(self._rows/2)-1][int(self._cols/2)-1] = BLACK
self._board[int(self._rows/2)-1][int((self._cols/2))] = WHITE
self._board[int((self._rows/2))][int(self._cols/2)] = BLACK
self._board[int((self._rows/2))][int(self._cols/2)-1] = WHITE
def is_valid(self, row, col, i, j):
'''checks if move is valid, i and j representing left, right, up, down, or diagonal'''
x = 0
y = 0
if self._turn == 'W':
try:
if self._board[row+(x+i)][col+(y+j)] == BLACK and self._board[row][col] == NONE and row+(x+i) != -1 and col+(y+j) != -1:
while self._board[row+(x+i)][col+(y+j)] == BLACK:
x += i
y += j
if self._board[row+(x+i)][col+(y+j)] == WHITE and row+(x+i) != -1 and col+(y+j) != -1:
return True
if self._board[row+(x+i)][col+(y+j)] == NONE:
return False
else:
return False
except:
return False
if self._turn == 'B':
try:
if self._board[row+(x+i)][col+(y+j)] == WHITE and self._board[row][col] == NONE and row+(x+i) >= 0 and col+(y+j) >= 0:
while self._board[row+(x+i)][col+(y+j)] == WHITE:
x += i
y += j
if self._board[row+(x+i)][col+(y+j)] == BLACK and (row+x+i) >= 0 and (col+y+j) >= 0:
return True
if self._board[row+(x+i)][col+(y+j)] == NONE:
return False
else:
return False
except:
return False
def flip_piece(self, row, col):
'''flips piece'''
counter = 0
for i in range(-1, 2):
for j in range(-1, 2):
if self.is_valid(row, col, i, j):
counter += 1
x = 0
y = 0
if self._turn == WHITE:
while self._board[row+(x+i)][col+(y+j)] == BLACK:
self._board[row+(x+i)][col+(y+j)] = WHITE
x += i
y += j
if self._turn == BLACK:
while self._board[row+(x+i)][col+(y+j)] == WHITE:
self._board[row+(x+i)][col+(y+j)] = BLACK
x += i
y += j
if counter >= 1 and self._turn == WHITE:
self._board[row][col] = WHITE
if counter >= 1 and self._turn == BLACK:
self._board[row][col] = BLACK
if counter == 0:
raise Exception
self.turn_switch()
self.print_board()
def turn_switch(self):
if self._turn == 'W':
self._turn = 'B'
else:
self._turn ='W'
def check_possible_moves(self):
'''to check if the user with the turn has a possible move, otherwise changes turn'''
for row in range(self._rows):
for col in range(self._cols):
if self._board[row][col] == NONE:
for i in range(-1,2):
for j in range(-1,2):
if self.is_valid(row, col, i, j):
return True
def determine_winner(game: object, condition: str):
winner = ''
if condition == 'most':
if game._blacks > game._whites:
winner = 'Black'
elif game._whites > game._blacks:
winner = 'White'
else:
winner = 'Tie'
if condition == 'fewest':
if game._blacks < game._whites:
winner = 'Black'
elif game._whites < game._blacks:
winner = 'White'
else:
winner = 'Tie'
return winner
'''
x = GameState(4,4,'B', 'White')
x._board[0][0] = 'W'
x._board[0][1] = 'W'
x._board[0][2] = 'W'
x._board[0][3] = 'W'
x._board[1][0] = 'B'
x._board[1][1] = 'B'
x._board[1][2] = 'W'
x._board[2][0] = 'B'
x._board[2][1] = 'B'
x._board[2][2] = 'B'
x._board[2][3] = 'W'
x._board[3][0] = 'B'
x._board[3][1] = 'W'
x._board[3][2] = 'W'
x._board[3][2] = 'W'
'''
|
994,496 | cb64773561e2105dbd2b4f91d1fafa5104f60f75 |
def combine_csv( input_csvs, output_csv, header_lines = 1 ):
''' Combine a list of CSV files specified in input_csvs into
a single output csv in output_csv. It is assumed that all
CSVs have the same header structure. The number of header
lines is specified in header_lines
'''
with open(output_csv, "w") as out:
for i, icsv in enumerate(input_csvs):
with open( icsv, "r" ) as infile:
header = []
for h in xrange(header_lines):
header.append(infile.next( ))
if i == 0:
for hline in header:
out.write(hline)
for line in infile:
out.write(line)
|
994,497 | 6ba1b37cb2f400e0cf9463602f4070cd9cec06aa | # -*- coding: utf-8 -*-
"""
Created on Tue Sep 12 09:32:33 2017
@author: jinjianfei
"""
import re
"""测试正则表达式"""
#test = ['4.45行权','5.23到期','5.00行权(散量)','5.23(到期)','5.23(行权)','5.23(行权)','5.23(行权)三两','5.23']
test = ['','\n','\t']
test = ['5','5.0','5.01','5.011','5.0111']
for i in test:
# if re.match(r'^\d{1}\.\d{2}$|^\d{1}\.\d{2}\([\u4E00-\u9FA5]+\)$|^\d{1}\.\d{2}[\u4E00-\u9FA5]+$', i):
# if not re.match(r'^\d.*[dDmMyY]$|^\d{2}[\u4e00-\u9fa5A-Z].*$|^[ABC].*\w$|^\s$',i):
if not re.match(r'^\d.*[dDmMyY]$|^\d{2}[\u4e00-\u9fa5A-Z].*$|^[ABC].*\w$|^[A-Z].*|[\u4e00-\u9fa5a-z()::()+]+$|^\\{n}$|^\[]$|^\s$|^(0*)$|^[\s\S]$',i):
print(i)
else:
print('failed')
#m = re.match(r'^(\d{3})-(\d{3,8})$', '010-12345')
#m
# m.group(0)
#'010-12345'
#>>> m.group(1)
#'010'
#>>> m.group(2)
#'12345' |
994,498 | 5799334684ceddde81501b938a126541a4bf6d09 | import cocos
from game.visualizer.load import load, find_image
class LoadingLayer(cocos.layer.Layer):
def __init__(self, assets, post_method):
super().__init__()
self.assets = assets
self.post_method = post_method
loading_image = cocos.sprite.Sprite(
find_image('game/visualizer/assets/city_assets/loading_screen.png'),
(640, 360),
)
self.add(loading_image)
self.loading_order = {
1: 'Loading city assets',
2: 'Loading side structures',
3: 'Creating disasters',
4: 'Initializing forecasts',
5: 'Constructing sensors',
6: 'Writing decrees',
7: 'Importing workers',
8: 'Leveling up',
9: 'Cleaning up'
}
self.label = cocos.text.Label(
'',
font_name='Arial',
font_size=16,
color=(0, 125, 0, 255),
anchor_x='center',
anchor_y='center'
)
self.label.position = 640, 50
self.add(self.label)
self.bar = cocos.draw.Line(
(540, 30),
(540, 30),
color=(0, 125, 0, 255),
stroke_width=16
)
self.add(self.bar)
self.current_key = 0
self.schedule_interval(callback=self.load_assets, interval=0.5)
def load_assets(self, interval):
self.current_key += 1
if self.current_key in self.loading_order:
item = self.loading_order[self.current_key]
self.label.element.text = item
self.bar.end = (540 + (200 * self.current_key / len(self.loading_order)), 30)
load(self.assets, self.current_key)
else:
self.post_method()
|
994,499 | f1354fc8a7699cd7d683ed985d7c52b77734e703 | # encoding: utf-8
from psi.app import const
from psi.app.service import Info
from flask_security import UserMixin
from sqlalchemy import ForeignKey, Integer
from sqlalchemy.orm import relationship
from psi.app.models.data_security_mixin import DataSecurityMixin
db = Info.get_db()
class User(db.Model, UserMixin, DataSecurityMixin):
from psi.app.models.role import roles_users
__tablename__ = 'user'
id = db.Column(db.Integer, primary_key=True)
login = db.Column(db.String(64), unique=True, nullable=False)
display = db.Column(db.String(255), nullable=False)
email = db.Column(db.String(255), unique=True, nullable=False)
password = db.Column(db.String(255))
active = db.Column(db.Boolean(), default=True)
locale_id = db.Column(Integer, ForeignKey('enum_values.id'))
locale = relationship('EnumValues', foreign_keys=[locale_id])
timezone_id = db.Column(Integer, ForeignKey('enum_values.id'))
timezone = relationship('EnumValues', foreign_keys=[timezone_id])
organization_id = db.Column(Integer, ForeignKey('organization.id'))
organization = relationship('Organization', foreign_keys=[organization_id])
roles = db.relationship('Role', secondary=roles_users,
backref=db.backref('users', lazy='joined'))
def __unicode__(self):
return self.display
@staticmethod
def locale_filter():
from psi.app.models import EnumValues
return EnumValues.type_filter(const.LANGUAGE_VALUES_KEY)
@staticmethod
def timezone_filter():
from psi.app.models import EnumValues
return EnumValues.type_filter(const.TIMEZONE_VALUES_KEY)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.