blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 2 616 | content_id stringlengths 40 40 | detected_licenses listlengths 0 69 | license_type stringclasses 2
values | repo_name stringlengths 5 118 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 63 | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 2.91k 686M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 23
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 220
values | src_encoding stringclasses 30
values | language stringclasses 1
value | is_vendor bool 2
classes | is_generated bool 2
classes | length_bytes int64 2 10.3M | extension stringclasses 257
values | content stringlengths 2 10.3M | authors listlengths 1 1 | author_id stringlengths 0 212 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
cd0dd0ac210bbca6c8922fd1b4b55b90ea0ad896 | d94b6845aeeb412aac6850b70e22628bc84d1d6d | /gfsa/model/end_to_end_stack.py | 0dcad41dab30b003212c181acf40bf2de50d6b57 | [
"CC-BY-4.0",
"Apache-2.0"
] | permissive | ishine/google-research | 541aea114a68ced68736340e037fc0f8257d1ea2 | c1ae273841592fce4c993bf35cdd0a6424e73da4 | refs/heads/master | 2023-06-08T23:02:25.502203 | 2023-05-31T01:00:56 | 2023-05-31T01:06:45 | 242,478,569 | 0 | 0 | Apache-2.0 | 2020-06-23T01:55:11 | 2020-02-23T07:59:42 | Jupyter Notebook | UTF-8 | Python | false | false | 16,457 | py | # coding=utf-8
# Copyright 2023 The Google Research Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, 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.
"""Model components for an end-to-end-trainable graph/automaton hybrid.
The components defined in this module share a common interface
(input graph, node embeddings, edge embeddings)
-> (node embeddings, edge embeddings)
which allows them to be composed with each other. Note that most components
either modify node embeddings or edge embeddings but not both. Also note that
the output edge embeddings are allowed to be of a different size; in particular,
the components that add new edge types use SharedGraphContext.edges_are_embedded
to determine how to modify the edge embeddings.
"""
from typing import Dict, List, Optional, Tuple
import dataclasses
import flax
import gin
import jax
import jax.numpy as jnp
from gfsa import automaton_builder
from gfsa import jax_util
from gfsa.datasets import graph_bundle
from gfsa.model import automaton_layer
from gfsa.model import edge_supervision_models
from gfsa.model import graph_layers
from gfsa.model import model_util
from gfsa.model import side_outputs
# TODO(ddjohnson) Move common layers out of `edge_supervision_models`.
# Flax adds name keyword arguments.
# pylint: disable=unexpected-keyword-arg
NodeAndEdgeEmbeddings = Tuple[jax_util.NDArray, jax_util.NDArray]
@dataclasses.dataclass
class SharedGraphContext:
"""Shared information about the input graph.
Attributes:
bundle: The input graph.
static_metadata: Padded size of the graph.
edge_types_to_indices: Mapping from string edge names to edge type indices.
builder: Automaton builder associated with this graph.
edges_are_embedded: Whether the "edge_embeddings" represent edge types that
are embedded into vectors (True), or just edge type adjacency matrices
that are concatenated together.
"""
bundle: graph_bundle.GraphBundle
static_metadata: automaton_builder.EncodedGraphMetadata
edge_types_to_indices: Dict[str, int]
builder: automaton_builder.AutomatonBuilder
edges_are_embedded: bool
def _add_edges(old_edge_array,
new_edge_types,
edges_are_embedded,
add_reverse = True):
"""Helper function to add edges of a new edge type.
If edges_are_embedded=True, we assume `old_edge_dim` is an embedding matrix;
the new edges are embedded and then added into this matrix. Otherwise, we
assume `old_edge_dim` is a stacked set of adjacency matrices, and concatenate
the new types.
Args:
old_edge_array: <float32[num_nodes, num_nodes, old_edge_dim]>
new_edge_types: <float32[num_nodes, num_nodes, new_edge_types]>, which
should be between 0 and 1, one for each added edge type.
edges_are_embedded: Whether edge types are embedded.
add_reverse: Whether to add reverse edges as well with a different type.
Returns:
<float32[num_nodes, num_nodes, output_edge_dim]>, where
output_edge_dim = old_edge_dim if edges_are_embedded=True, and otherwise
output_edge_dim = old_edge_dim + new_edge_types
"""
if add_reverse:
new_edge_types = jnp.concatenate(
[new_edge_types, new_edge_types.transpose((1, 0, 2))], -1)
if edges_are_embedded:
# Project the outputs into new edge embeddings.
# (No bias is used so that an absorbing probability of 0 produces no change
# in the edge embeddings.)
new_edge_type_embeddings = flax.deprecated.nn.Dense(
new_edge_types,
features=old_edge_array.shape[-1],
bias=False,
name="new_edge_type_embeddings")
output_edge_array = old_edge_array + new_edge_type_embeddings
else:
# Concatenate new embedding.
output_edge_array = jnp.concatenate([old_edge_array, new_edge_types],
axis=-1)
return output_edge_array
def _shared_automaton_logic(
graph_context, node_embeddings,
edge_embeddings,
variant_weights):
"""Helper function for shared automaton logic."""
# Run the automaton.
edge_weights = automaton_layer.FiniteStateGraphAutomaton(
encoded_graph=graph_context.bundle.automaton_graph,
variant_weights=variant_weights,
dynamic_metadata=graph_context.bundle.graph_metadata,
static_metadata=graph_context.static_metadata,
builder=graph_context.builder)
return (node_embeddings,
_add_edges(edge_embeddings, edge_weights.transpose([1, 2, 0]),
graph_context.edges_are_embedded))
@flax.deprecated.nn.module
@gin.configurable
def variantless_automaton(
graph_context, node_embeddings,
edge_embeddings):
"""Runs an automaton without variants.
Args:
graph_context: Input graph for this example.
node_embeddings: Current node embeddings, as <float32[num_nodes,
node_embedding_dim]>
edge_embeddings: Current edge embeddings, as <float32[num_nodes, num_nodes,
edge_embedding_dim]>
Returns:
New node and edge embeddings. Node embeddings will not be modified. Edge
embeddings will be modified by adding a new edge type (either embedded or
concatenated based on graph_context.edges_are_embedded).
"""
return _shared_automaton_logic(
graph_context, node_embeddings, edge_embeddings, variant_weights=None)
@flax.deprecated.nn.module
@gin.configurable
def edge_variant_automaton(
graph_context,
node_embeddings,
edge_embeddings,
variant_edge_types = gin.REQUIRED):
"""Runs an automaton with variants based on edges in the input graph.
Args:
graph_context: Input graph for this example.
node_embeddings: Current node embeddings, as <float32[num_nodes,
node_embedding_dim]>
edge_embeddings: Current edge embeddings, as <float32[num_nodes, num_nodes,
edge_embedding_dim]>
variant_edge_types: List of edge types used as variants.
Returns:
New node and edge embeddings. Node embeddings will not be modified. Edge
embeddings will be modified by adding a new edge type (either embedded or
concatenated based on graph_context.edges_are_embedded).
"""
# Set up variants from edge types.
variant_edge_type_indices = [
graph_context.edge_types_to_indices[type_str]
for type_str in variant_edge_types
]
num_edge_types = len(graph_context.edge_types_to_indices)
variant_weights = edge_supervision_models.variants_from_edges(
graph_context.bundle, graph_context.static_metadata,
variant_edge_type_indices, num_edge_types)
return _shared_automaton_logic(graph_context, node_embeddings,
edge_embeddings, variant_weights)
@flax.deprecated.nn.module
@gin.configurable
def embedding_variant_automaton(
graph_context,
node_embeddings,
edge_embeddings,
num_variants = gin.REQUIRED):
"""Runs an automaton with variants based on node embeddings.
Args:
graph_context: Input graph for this example.
node_embeddings: Current node embeddings, as <float32[num_nodes,
node_embedding_dim]>
edge_embeddings: Current edge embeddings, as <float32[num_nodes, num_nodes,
edge_embedding_dim]>
num_variants: How many variants to use.
Returns:
New node and edge embeddings. Node embeddings will not be modified. Edge
embeddings will be modified by adding a new edge type (either embedded or
concatenated based on graph_context.edges_are_embedded).
"""
if num_variants <= 1:
raise ValueError(
"Must have at least one variant to use embedding_variant_automaton.")
# Generate variants using a pairwise readout of the node embeddings.
variant_logits = graph_layers.BilinearPairwiseReadout(
node_embeddings, num_variants, name="variant_logits")
variant_logits = side_outputs.encourage_discrete_logits(
variant_logits, distribution_type="categorical", name="variant_logits")
variant_weights = jax.nn.softmax(variant_logits)
return _shared_automaton_logic(graph_context, node_embeddings,
edge_embeddings, variant_weights)
@flax.deprecated.nn.module
@gin.configurable
def nri_encoder_readout(
graph_context,
node_embeddings,
edge_embeddings,
num_edge_types = gin.REQUIRED):
"""Modifies edge embeddings using an NRI encoder.
Note that we use a sigmoid rather than a softmax, because we don't necessarily
want to enforce having exactly one edge type per pair of nodes.
Args:
graph_context: Input graph for this example.
node_embeddings: Current node embeddings, as <float32[num_nodes,
node_embedding_dim]>
edge_embeddings: Current edge embeddings, as <float32[num_nodes, num_nodes,
edge_embedding_dim]>
num_edge_types: How many edge types to produce.
Returns:
New node and edge embeddings. Node embeddings will not be modified. Edge
embeddings will be modified by adding a new edge type (either embedded or
concatenated based on graph_context.edges_are_embedded).
"""
# Run the NRI readout layer.
logits = graph_layers.NRIReadout(
node_embeddings=node_embeddings, readout_dim=num_edge_types)
new_edge_weights = jax.nn.sigmoid(logits)
mask = (
jnp.arange(new_edge_weights.shape[0]) <
graph_context.bundle.graph_metadata.num_nodes)
new_edge_weights = jnp.where(mask[:, None, None], new_edge_weights,
jnp.zeros_like(new_edge_weights))
return (node_embeddings,
_add_edges(edge_embeddings, new_edge_weights,
graph_context.edges_are_embedded))
class UniformRandomWalk(flax.deprecated.nn.Module):
"""Adds edges according to a uniform random walk along the graph."""
@gin.configurable("UniformRandomWalk")
def apply(
self,
graph_context,
node_embeddings,
edge_embeddings,
forward_edge_types = gin.REQUIRED,
reverse_edge_types = gin.REQUIRED,
walk_length_log2 = gin.REQUIRED,
):
"""Modifies edge embeddings using a uniform random walk.
Uses an efficient repeated-squaring technique to compute the absorbing
distribution.
Args:
graph_context: Input graph for this example.
node_embeddings: Current node embeddings, as <float32[num_nodes,
node_embedding_dim]>
edge_embeddings: Current edge embeddings, as <float32[num_nodes,
num_nodes, edge_embedding_dim]>
forward_edge_types: Edge types to use in the forward direction. As a list
of lists to allow configuring groups of edges in config files; this will
be flattened before use.
reverse_edge_types: Edge types to use in the reverse direction. Note that
reversed edge types are given a separate embedding from forward edge
types; undirected edges should be represented by adding two edges in
opposite directions and then only using `forward_edge_types`. Also a
list of lists, as above.
walk_length_log2: Base-2 logarithm of maximum walk length; this determines
how many times we will square the transition matrix (doubling the walk
length).
Returns:
New node and edge embeddings. Node embeddings will not be modified. Edge
embeddings will be modified by adding a new edge type (either embedded or
concatenated based on graph_context.edges_are_embedded).
"""
num_nodes = node_embeddings.shape[0]
# pylint: disable=g-complex-comprehension
forward_edge_type_indices = [
graph_context.edge_types_to_indices[type_str]
for group in forward_edge_types
for type_str in group
]
reverse_edge_type_indices = [
graph_context.edge_types_to_indices[type_str]
for group in reverse_edge_types
for type_str in group
]
# pylint: enable=g-complex-comprehension
adjacency = graph_layers.edge_mask(
edges=graph_context.bundle.edges,
num_nodes=num_nodes,
num_edge_types=len(graph_context.edge_types_to_indices),
forward_edge_type_indices=forward_edge_type_indices,
reverse_edge_type_indices=reverse_edge_type_indices)
adjacency = jnp.maximum(adjacency, jnp.eye(num_nodes))
absorbing_logit = self.param(
"absorbing_logit",
shape=(),
initializer=lambda *_: jax.scipy.special.logit(0.1))
absorbing_prob = jax.nn.sigmoid(absorbing_logit)
nonabsorbing_prob = jax.nn.sigmoid(-absorbing_logit)
walk_matrix = nonabsorbing_prob * adjacency / jnp.sum(
adjacency, axis=1, keepdims=True)
# A, I
# A^2, A + I
# (A^2)^2 = A^4, (A + I)A^2 + (A + I) = A^3 + A^2 + A + I
# ...
def step(state, _):
nth_power, nth_partial_sum = state
return (nth_power @ nth_power,
nth_power @ nth_partial_sum + nth_partial_sum), None
(_, partial_sum), _ = jax.lax.scan(
step, (walk_matrix, jnp.eye(num_nodes)), None, length=walk_length_log2)
approx_visits = absorbing_prob * partial_sum
logits = model_util.safe_logit(approx_visits)
logits = model_util.ScaleAndShift(logits)
edge_weights = jax.nn.sigmoid(logits)
return (node_embeddings,
_add_edges(edge_embeddings, edge_weights[:, :, None],
graph_context.edges_are_embedded))
@flax.deprecated.nn.module
def ggnn_adapter(graph_context,
node_embeddings,
edge_embeddings):
"""Adapter function to run GGNN steps.
Args:
graph_context: Input graph for this example.
node_embeddings: Current node embeddings, as <float32[num_nodes,
node_embedding_dim]>
edge_embeddings: Current edge embeddings, as <float32[num_nodes, num_nodes,
edge_embedding_dim]>
Returns:
New node and edge embeddings. Node embeddings are processed by a GGNN,
and edge embeddings are returned unchanged.
"""
del graph_context
return (
edge_supervision_models.ggnn_steps(node_embeddings, edge_embeddings),
edge_embeddings,
)
@flax.deprecated.nn.module
def transformer_adapter(
graph_context, node_embeddings,
edge_embeddings):
"""Adapter function to run transformer blocks.
Args:
graph_context: Input graph for this example.
node_embeddings: Current node embeddings, as <float32[num_nodes,
node_embedding_dim]>
edge_embeddings: Current edge embeddings, as <float32[num_nodes, num_nodes,
edge_embedding_dim]>
Returns:
New node and edge embeddings. Node embeddings are processed by a
transformer, and edge embeddings are returned unchanged.
"""
return (
edge_supervision_models.transformer_steps(
node_embeddings,
edge_embeddings,
neighbor_mask=None,
num_real_nodes_per_graph=(
graph_context.bundle.graph_metadata.num_nodes),
mask_to_neighbors=False),
edge_embeddings,
)
@flax.deprecated.nn.module
def nri_adapter(graph_context,
node_embeddings,
edge_embeddings):
"""Adapter function to run NRI blocks.
Args:
graph_context: Input graph for this example.
node_embeddings: Current node embeddings, as <float32[num_nodes,
node_embedding_dim]>
edge_embeddings: Current edge embeddings, as <float32[num_nodes, num_nodes,
edge_embedding_dim]>
Returns:
New node and edge embeddings. Node embeddings are processed by a NRI-style
model, and edge embeddings are returned unchanged.
"""
return (
edge_supervision_models.nri_steps(
node_embeddings,
edge_embeddings,
num_real_nodes_per_graph=(
graph_context.bundle.graph_metadata.num_nodes)),
edge_embeddings,
)
ALL_COMPONENTS = {
"variantless_automaton": variantless_automaton,
"edge_variant_automaton": edge_variant_automaton,
"embedding_variant_automaton": embedding_variant_automaton,
"nri_encoder_readout": nri_encoder_readout,
"ggnn_adapter": ggnn_adapter,
"transformer_adapter": transformer_adapter,
"nri_adapter": nri_adapter,
"UniformRandomWalk": UniformRandomWalk,
}
| [
"copybara-worker@google.com"
] | copybara-worker@google.com |
80be94c0c3ace64ca419129673fd77280b8fb35a | d4d511a212f3f3138b29d5c055ffbb0bf8127095 | /dirigida-por-eventos-GUI/chapter_8/ejemplo_8-16.py | e19adb14488eaf87740cf0a311be52e83e3a860d | [] | no_license | SebZalewskiK/Python_ejercicios | d9e0a275053b05ffde95d7609ca47f5139db3bd4 | 64c062435951c7b9dce3b03a437b8ef572363118 | refs/heads/master | 2021-01-18T20:41:54.519741 | 2015-06-01T12:44:35 | 2015-06-01T12:44:35 | 46,050,448 | 1 | 0 | null | 2015-11-12T12:08:09 | 2015-11-12T12:08:08 | null | UTF-8 | Python | false | false | 567 | py |
# Message
'''
The Message widget is simply a place to display text. Although the standard showinfo
dialog we met earlier is perhaps a better way to display pop-up messages, Message splits
up long strings automatically and flexibly and can be embedded inside container widg-
ets any time you need to add some read-only text to a display.
'''
from tkinter import *
msg = Message(text="Oh by the way, which one's Pink?")
msg.config(bg='pink', font=('times', 16, 'italic'))
msg.pack(fill=BOTH, expand=YES) # BOTH para que llene de rosa todo el espacio
mainloop() | [
"gelpiorama@gmail.com"
] | gelpiorama@gmail.com |
cea43589a7bb31e1bf0c658d9ea1813573b2e2bc | ab67bf011764b6c0b6803cd44985a5a2ad3f2593 | /udpsocket.py | 2b222871dc47eb1b8e436bd7d76fd4d52cdb877e | [] | no_license | pr0logas/streamSockets | cba0616ead596bf331eda4f54b6112a212e462fc | 3f759509dfcb556d3b6a25f11c9f512fb7be430b | refs/heads/master | 2022-11-25T06:09:17.503818 | 2020-07-27T13:53:15 | 2020-07-27T13:53:15 | 285,097,509 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,970 | py | import socket
import os, sys, time
from time import sleep
MCAST_GRP = '10.10.10.10'
MCAST_PORT = 9004
MULTICAST_TTL = 10
bytes_size_to_process = 1024
time_between_data_seconds = 5
time_between_packets_float = 0.0055
def startSocket():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
s.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, MULTICAST_TTL)
def sendDataOverSocket(data, sleeptime):
if data:
bytes_size_to_process = sys.getsizeof(data)
#print("Serving UDP multicast data to: " + str(MCAST_GRP) + ":" + str(MCAST_PORT) + " " +
# str(bytes_size_to_process) + " bytes" +
# " (file size: " + str(os.stat('channels/currentFile.ts').st_size) + ")")
s.sendto(data, (MCAST_GRP, MCAST_PORT))
sleep(sleeptime)
def adjustTimeForNewData(start, end, sleeptime):
result = (time_between_data_seconds - (end-start))
if result < 0:
print("No sleep needed we are {} seconds late to stream the data!".format(result) + " Next sleep: " + str(sleeptime))
else:
print("Sleeping for {} Waiting for next data...".format(result) + " Next sleep: " + str(sleeptime))
while True:
starttime = time.time()
with open("channels/currentFile.ts", "rb", buffering=1) as f:
byte = f.read(bytes_size_to_process)
expectedPackets = os.stat('channels/currentFile.ts').st_size / bytes_size_to_process
print(expectedPackets)
sleepTime = (time_between_data_seconds / expectedPackets) - 0.000120256
sendDataOverSocket(byte, sleepTime)
while byte:
byte = f.read(bytes_size_to_process)
sendDataOverSocket(byte, sleepTime)
f.close()
endtime = time.time()
adjustTimeForNewData(starttime, endtime, sleepTime)
#sleep(time_between_packets_float) | [
"prologas@protonmail.com"
] | prologas@protonmail.com |
302ed4dc0d8d825baa53e29685252cd1302bc4ca | 57bafd6a29da8d59f5c2cc2d1bcc214065931df7 | /apps/clients/migrations/0001_initial.py | 8190a5b7d3bc7e6bc0cb081a4b8d0fb3e66805db | [] | no_license | Ivonne-cas/sitiofinal | bf94ca17fbef541fb5f128b17f90f102dae3582e | 6c300fad90f3b7b0cc2c84b85f2d786e5ebaec4f | refs/heads/master | 2023-08-25T23:30:38.508316 | 2021-10-21T21:26:17 | 2021-10-21T21:26:17 | 419,844,267 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,749 | py | # Generated by Django 3.2.8 on 2021-10-21 18:28
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('products', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Cliente',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('nombre', models.CharField(max_length=50, verbose_name='nombre')),
('fecha', models.DateField(verbose_name='fecha')),
('cedula', models.IntegerField(verbose_name='cedula')),
('casado', models.BooleanField(verbose_name='casado')),
],
options={
'verbose_name': 'cliente',
'verbose_name_plural': 'clientes',
},
),
migrations.CreateModel(
name='ClienteProducto',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('total', models.DecimalField(decimal_places=2, max_digits=10, verbose_name='total')),
('cliente', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='clients.cliente', verbose_name='cliente')),
('producto', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='products.producto', verbose_name='producto')),
],
),
migrations.AddField(
model_name='cliente',
name='producto',
field=models.ManyToManyField(through='clients.ClienteProducto', to='products.Producto'),
),
]
| [
"ivonneximenacaste@gmail.com"
] | ivonneximenacaste@gmail.com |
4ca7dd8882f263f5749f1eecebddf59f13b12871 | 0969f7c85e5ae0a19982077d6bb702c41b2b1e1f | /nets/mobilenet/mobilenet_v2.py | 02f5fa0510270fecc4ea3bd20c7f4da25bad20b1 | [
"MIT"
] | permissive | 353622088/tianchi | 544e49bb6720c4978188cdbddd88a0ebe9f5669c | e1f378e5fd783eb4cfbfaf8ecdd944b8fcfdd733 | refs/heads/master | 2020-04-19T09:06:35.946147 | 2019-01-30T09:30:05 | 2019-01-30T09:30:05 | 168,099,897 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 7,434 | py | # Copyright 2018 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless 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.
# ==============================================================================
"""Implementation of Mobilenet V2.
Architecture: https://arxiv.org/abs/1801.04381
The base model gives 72.2% accuracy on ImageNet, with 300MMadds,
3.4 M parameters.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import copy
import tensorflow as tf
from nets.mobilenet import conv_blocks as ops
from nets.mobilenet import mobilenet as lib
import functools
slim = tf.contrib.slim
op = lib.op
expand_input = ops.expand_input_by_factor
# pyformat: disable
# Architecture: https://arxiv.org/abs/1801.04381
V2_DEF = dict(
defaults={
# Note: these parameters of batch norm affect the architecture
# that's why they are here and not in training_scope.
(slim.batch_norm,): {'center': True, 'scale': True},
(slim.conv2d, slim.fully_connected, slim.separable_conv2d): {
'normalizer_fn': slim.batch_norm, 'activation_fn': tf.nn.relu6
},
(ops.expanded_conv,): {
'expansion_size': expand_input(6),
'split_expansion': 1,
'normalizer_fn': slim.batch_norm,
'residual': True
},
(slim.conv2d, slim.separable_conv2d): {'padding': 'SAME'}
},
spec=[
op(slim.conv2d, stride=2, num_outputs=32, kernel_size=[3, 3]),
op(ops.expanded_conv,
expansion_size=expand_input(1, divisible_by=1),
num_outputs=16),
op(ops.expanded_conv, stride=2, num_outputs=24),
op(ops.expanded_conv, stride=1, num_outputs=24),
op(ops.expanded_conv, stride=2, num_outputs=32),
op(ops.expanded_conv, stride=1, num_outputs=32),
op(ops.expanded_conv, stride=1, num_outputs=32),
op(ops.expanded_conv, stride=2, num_outputs=64),
op(ops.expanded_conv, stride=1, num_outputs=64),
op(ops.expanded_conv, stride=1, num_outputs=64),
op(ops.expanded_conv, stride=1, num_outputs=64),
op(ops.expanded_conv, stride=1, num_outputs=96),
op(ops.expanded_conv, stride=1, num_outputs=96),
op(ops.expanded_conv, stride=1, num_outputs=96),
op(ops.expanded_conv, stride=2, num_outputs=160),
op(ops.expanded_conv, stride=1, num_outputs=160),
op(ops.expanded_conv, stride=1, num_outputs=160),
op(ops.expanded_conv, stride=1, num_outputs=320),
op(slim.conv2d, stride=1, kernel_size=[1, 1], num_outputs=1280)
],
)
# pyformat: enable
@slim.add_arg_scope
def mobilenet(input_tensor,
num_classes=1001,
depth_multiplier=1.0,
scope='MobilenetV2',
conv_defs=None,
finegrain_classification_mode=False,
min_depth=None,
divisible_by=None,
**kwargs):
"""Creates mobilenet V2 network.
Inference mode is created by default. To create training use training_scope
below.
with tf.contrib.slim.arg_scope(mobilenet_v2.training_scope()):
logits, endpoints = mobilenet_v2.mobilenet(input_tensor)
Args:
input_tensor: The input tensor
num_classes: number of classes
depth_multiplier: The multiplier applied to scale number of
channels in each layer. Note: this is called depth multiplier in the
paper but the name is kept for consistency with slim's model builder.
scope: Scope of the operator
conv_defs: Allows to override default conv def.
finegrain_classification_mode: When set to True, the model
will keep the last layer large even for small multipliers. Following
https://arxiv.org/abs/1801.04381
suggests that it improves performance for ImageNet-type of problems.
*Note* ignored if final_endpoint makes the builder exit earlier.
min_depth: If provided, will ensure that all layers will have that
many channels after application of depth multiplier.
divisible_by: If provided will ensure that all layers # channels
will be divisible by this number.
**kwargs: passed directly to mobilenet.mobilenet:
prediction_fn- what prediction function to use.
reuse-: whether to reuse variables (if reuse set to true, scope
must be given).
Returns:
logits/endpoints pair
Raises:
ValueError: On invalid arguments
"""
if conv_defs is None:
conv_defs = V2_DEF
if 'multiplier' in kwargs:
raise ValueError('mobilenetv2 doesn\'t support generic '
'multiplier parameter use "depth_multiplier" instead.')
if finegrain_classification_mode:
conv_defs = copy.deepcopy(conv_defs)
if depth_multiplier < 1:
conv_defs['spec'][-1].params['num_outputs'] /= depth_multiplier
depth_args = {}
# NB: do not set depth_args unless they are provided to avoid overriding
# whatever default depth_multiplier might have thanks to arg_scope.
if min_depth is not None:
depth_args['min_depth'] = min_depth
if divisible_by is not None:
depth_args['divisible_by'] = divisible_by
with slim.arg_scope((lib.depth_multiplier,), **depth_args):
return lib.mobilenet(
input_tensor,
num_classes=num_classes,
conv_defs=conv_defs,
scope=scope,
multiplier=depth_multiplier,
**kwargs)
def wrapped_partial(func, *args, **kwargs):
partial_func = functools.partial(func, *args, **kwargs)
functools.update_wrapper(partial_func, func)
return partial_func
mobilenet_v2_100 = wrapped_partial(mobilenet, depth_multiplier=1.00)
mobilenet_v2_140 = wrapped_partial(mobilenet, depth_multiplier=1.40)
@slim.add_arg_scope
def mobilenet_base(input_tensor, depth_multiplier=1.0, **kwargs):
"""Creates base of the mobilenet (no pooling and no logits) ."""
return mobilenet(input_tensor,
depth_multiplier=depth_multiplier,
base_only=True, **kwargs)
def training_scope(**kwargs):
"""Defines MobilenetV2 training scope.
Usage:
with tf.contrib.slim.arg_scope(mobilenet_v2.training_scope()):
logits, endpoints = mobilenet_v2.mobilenet(input_tensor)
with slim.
Args:
**kwargs: Passed to mobilenet.training_scope. The following parameters
are supported:
weight_decay- The weight decay to use for regularizing the model.
stddev- Standard deviation for initialization, if negative uses xavier.
dropout_keep_prob- dropout keep probability
bn_decay- decay for the batch norm moving averages.
Returns:
An `arg_scope` to use for the mobilenet v2 model.
"""
return lib.training_scope(**kwargs)
__all__ = ['training_scope', 'mobilenet_base', 'mobilenet', 'V2_DEF']
| [
"chk0125@126.com"
] | chk0125@126.com |
e74010a40ad06fe82916fea9a7e6c222b087a685 | cb83b02ead1cb77c87e117118f7e5cd3ecf46ba1 | /sistema_plantilla/settings/settings.py | 6652e9955e4d55b35976610917e962c7d8b0c985 | [] | no_license | danielhuamani/sistema-plantilla-saas | f834d90157b3d0ab1724fe7d3be5e9224cf753ae | 8802a4b429fdce9ce433539684b52e2177042c35 | refs/heads/master | 2020-12-11T01:48:45.313743 | 2016-01-18T16:10:24 | 2016-01-18T16:10:24 | 48,857,325 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,996 | py | """
Django settings for settings project.
Generated by 'django-admin startproject' using Django 1.8.2.
For more information on this file, see
https://docs.djangoproject.com/en/1.8/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.8/ref/settings/
"""
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
from os.path import dirname, join, realpath
BASE_DIR = dirname(dirname(realpath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'vhgbr0j26ii9t4juw%_z)_^wm8st_#1$8zrj4yq7!5b)7-@554'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'apps.productos',
'apps.clientes',
'apps.configuracion',
'apps.theme',
'apps.theme_admin',
'debug_toolbar',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'django.middleware.security.SecurityMiddleware',
)
ROOT_URLCONF = 'settings.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': (join(BASE_DIR, 'templates'),),
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'django.template.context_processors.static',
],
},
},
]
WSGI_APPLICATION = 'settings.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': join(BASE_DIR, 'db.sqlite3'),
}
}
# Internationalization
# https://docs.djangoproject.com/en/1.8/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.8/howto/static-files/
MEDIA_ROOT = join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
STATIC_ROOT = ''
STATIC_URL = '/static/'
STATICFILES_DIRS = (
join(BASE_DIR, 'static'),
)
| [
"danielhuamani15@gmail.com"
] | danielhuamani15@gmail.com |
80793db4fcb6d003bcd7f9d86fe4acae5bc1a6c0 | 781e2692049e87a4256320c76e82a19be257a05d | /all_data/exercism_data/python/bob/6ae12eacdae24553a91c0270cb101e66.py | 5d6e3848a1fa367f700bac002a2b381e701f99cc | [] | no_license | itsolutionscorp/AutoStyle-Clustering | 54bde86fe6dbad35b568b38cfcb14c5ffaab51b0 | be0e2f635a7558f56c61bc0b36c6146b01d1e6e6 | refs/heads/master | 2020-12-11T07:27:19.291038 | 2016-03-16T03:18:00 | 2016-03-16T03:18:42 | 59,454,921 | 4 | 0 | null | 2016-05-23T05:40:56 | 2016-05-23T05:40:56 | null | UTF-8 | Python | false | false | 281 | py | #
# Skeleton file for the Python "Bob" exercise.
#
def hey(what):
if what is None or what.strip() == "":
return "Fine. Be that way!"
if what.isupper():
return "Whoa, chill out!"
if what.endswith("?") or what.endswith(" "):
return "Sure."
return "Whatever."
| [
"rrc@berkeley.edu"
] | rrc@berkeley.edu |
481d5738f4ad8c4ba46dbd6a9831f4d1c26f8daa | 11dba20cc1a6acfe2a502bb7f02c056a9de07324 | /train.py | a393e04d0eb23f7d6a7efc5590e83a9fe5871cfa | [] | no_license | jysgit/TAAI_gen_paraphrase | f35246d09b2ecffb8c1e4e75156c06b0be3ac76d | 9bf916b2d9af0395fc92a033325733198a8eace4 | refs/heads/main | 2023-03-17T18:34:41.616533 | 2020-10-07T11:09:12 | 2020-10-07T11:09:12 | 348,598,047 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,600 | py | from gensim.models import Word2Vec, KeyedVectors
from gensim.models.callbacks import CallbackAny2Vec
from time import time
import os
## SETTINGS ##
def ensure_exist(path):
if not os.path.exists(path):
os.makedirs(path)
def load_file(path, encoding='utf-8'):
with open(path, 'r', encoding=encoding) as f:
data = f.read()
return data
def preprocessing(data):
''' seperete sentences by '\n' and remove redudent spaces '''
lines = data.split('\n')
sentences = [[token for token in line.split(' ') if token != ''] for line in lines]
return sentences
class loss_record(CallbackAny2Vec):
'''Callback to record loss after each epoch.'''
def __init__(self, loss_record = [], logging=False):
self.epoch = 0
self.logging= logging
self.total_loss = 0
self.record = loss_record
def on_epoch_end(self, model):
loss = model.get_latest_training_loss() - self.total_loss
self.record.append(loss)
self.total_loss = model.get_latest_training_loss()
if self.logging:
print('[ INFO ] Loss after epoch {:3d}: {:10.3f}'.format(self.epoch, loss))
self.epoch += 1
class log_epoch(CallbackAny2Vec):
def __init__(self):
self.epoch = 0
self.epoch_start_time = None
def on_epoch_begin(self, model):
print(f'[ INFO ] Epoch {self.epoch} start...')
self.epoch_start_time = time()
def on_epoch_end(self, model):
train_time = time() - self.epoch_start_time
print(f'[ INFO ] Epoch {self.epoch} end. Time eplapse: {train_time}')
self.epoch += 1
def load_pretrain(model, pretrained_path):
print('[ INFO ] loading pretrained vocabulary list...')
pretrained_model = KeyedVectors.load_word2vec_format(pretrained_path, binary=True)
model.build_vocab([list(pretrained_model.vocab.keys())], update=True)
del pretrained_model # free memory
print('[ INFO ] loading pretrained model...')
model.intersect_word2vec_format(pretrained_path, binary=True, lockf=0.0) # lockf: freeze or not
return model
def train(input_file, output_dir, epoch, alpha, dim, window, eval_file, pretrained_model=None):
# preprocessing
print('[ INFO ] data processing...')
training_data = load_file(input_file)
training_data = preprocessing(training_data)
# prepare model
losses = []
model = Word2Vec(size = dim,
min_count = 1,
alpha = alpha,
window = window,
callbacks = [log_epoch(), loss_record(losses, True)])
model.build_vocab(training_data)
example_count = model.corpus_count
# load pretrained
if pretrained_model:
model = load_pretrain(model, pretrained_model)
# training
print('[ INFO ] training start.')
model.train(training_data,
total_examples = example_count,
epochs = epoch,
compute_loss = True,
callbacks = [log_epoch(), loss_record(losses, True)])
# model = Word2Vec(training_data,
# size = dim,
# iter = epoch,
# compute_loss = True,
# callbacks=[log_epoch(), loss_record(losses, True)])
print('[ INFO ] finished')
# evaluating
if eval_file:
print('[ INFO ] evaluating...')
result = model.wv.evaluate_word_analogies(eval_file)
print(f'[ INFO ] evaluating finished. Accuracy = {result[0]}')
# save model
if output_dir:
print(f'[ INFO ] saving data to {output_dir} ...')
ensure_exist(output_dir)
model.save(os.path.join(output_dir, 'model'))
model.wv.save(os.path.join(output_dir, 'vecotr.kv'))
with open(os.path.join(output_dir, 'loss'), 'w+') as f:
for idx, loss in enumerate(losses):
f.write(f"{idx}\t{loss}\n")
if eval_file:
with open(os.path.join(output_dir, 'accuracy'), 'w+') as f:
f.write(f"{result[0]}\n") # write accuracy
f.write(str(result[1])) # write evaluation log
if __name__ == '__main__':
def parse_args():
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-i', '--input', type=str, required=True, help='training data')
parser.add_argument('-o', '--output', type=str, help='folder to store output')
parser.add_argument('-e', '--epoch', type=int, default=5,help='#iter')
parser.add_argument('-d', '--dim', type=int, default=300, help='embedding dimension')
parser.add_argument('-w', '--window', type=int, default=5, help='window size')
parser.add_argument('-a', '--alpha', type=float, default=0.025, help='initial learning rate')
parser.add_argument('-p', '--pretrained', nargs='?', help='pretrained model path')
parser.add_argument('-eval', '--evaluate', type=str, help='evaluation data')
return parser.parse_args()
args = parse_args()
print()
print( 'Get Setting: ')
print(f' + input: {args.input}')
print(f' + output: {args.output}')
print(f' + alpha: {args.alpha}')
print(f' + epoch: {args.epoch}')
print(f' + dimension: {args.dim}')
print(f' + window size: {args.window}')
print(f' + evaluate file: {args.evaluate}')
print( ' + pretrained model: {}'.format(args.pretrained if args.pretrained else 'None'))
print()
train(args.input, args.output, args.epoch, args.alpha, args.dim, args.window, args.evaluate, args.pretrained)
| [
"joannawu@nlplab.cc"
] | joannawu@nlplab.cc |
89e0353d4de23f2ac613d436afbbec0a40354e19 | e8ef02248600525a114c9ed9a6098e95d8007063 | /qtlab/scripts/sal/ff_powersweep.py | 7966c043a04204757185031af05d8a6ff6e2df04 | [] | no_license | mgely/papyllon | ac264e202298728f6ca69d566c1fe45a9de0dc1c | 490c756da8f08c971864dcd983ea82c944bc8c85 | refs/heads/master | 2021-01-10T06:28:17.250944 | 2016-02-26T13:49:21 | 2016-02-26T13:49:21 | 46,259,620 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,120 | py | #prepare environment
import qt
import visa
import numpy as np
from numpy import pi, random, arange, size, array, sin, cos, diff, absolute,zeros, sign,ceil,sqrt,absolute
from time import time, sleep, localtime, strftime
execfile('metagen.py')
#Check and load instrument plugins
instlist = qt.instruments.get_instrument_names()
print "installed instruments: "+" ".join(instlist)
#install the drivers no check
if 'med' not in instlist:
med = qt.instruments.create('med','med')
#if 'adwin' not in instlist:
# adwin= qt.instruments.create('adwin', 'ADwin_DAC',address=0x255)
if 'ff' not in instlist:
ff=visa.instrument('TCPIP0::192.168.1.151::inst0::INSTR')
instlist = qt.instruments.get_instrument_names()
print "Available instruments: "+" ".join(instlist)
#measurement information stored in manual in MED instrument
#med.set_device('ShunDevice')
#med.set_setup('BF_4, conversion is 1uA/V')
#med.set_user('Shun')
qt.mstart()
spyview_process(reset=True) #clear old meta-settings
filename = 'EOS8_C_FF'
data = qt.Data(name=filename)
data.add_coordinate('Probe Frequency [MHz]')
data.add_coordinate('Voltage [uA]')
data.add_value('S21 [abs]')
data.add_value('S21 [rad]')
#data.create_file()
data.create_file(name=filename, datadirs='D:\\data\\Sal\\EOS8_C\\temp_powersweep')
data.copy_file('FF_powersweep.py')
kHz = 1e3
MHz = 1e6
GHz = 1e9
####Settings:
#Current temperature
# 18mK
## 10dB on VNA out
## miteq on the input port 2
## I to V conversion 100uA/1Volt
##
######### Variables for NA
pinit=-45
bw=30
f_start=5.272*GHz
f_stop=5.372*GHz
f_pts=401
##hanger_f0=5900.59*MHz
##hanger_span=1000*kHz
##f1_start=hanger_f0-hanger_span/2
##f1_stop=hanger_f0+hanger_span/2
### Variables for field
#v_start=0
#v_stop=1.5
#v_pts=1501
### Variables for power
p_start = -45
p_stop =0
p_pts =10
### Preparing NA
ff.write('INST:SEL "NA";*OPC?')
ff.write('FREQ:STOP '+str(f_stop)+'\n')
ff.write('FREQ:STAR '+str (f_start)+'\n')
ff.write('BWID '+str(bw)+'\n')
ff.write('SOUR:POW '+str(pinit)+'\n')
ff.write('SWE:POIN '+str(f_pts)+'\n')
ff.write('CALC:PAR:DEF S21 \r')
### Prepare ADWIN for current sweep
#adwin.start_process()
########### making lists of values to be measured ###########
f_list=np.linspace(f_start,f_stop,f_pts)
#v_list=np.linspace(v_start,v_stop,v_pts)
p_list = np.linspace(p_start,p_stop,p_pts)
##################################################
qt.msleep(0.1)
for p in p_list:
print 'current power '+str(p)+' power'
ff.write('SOUR:POW ' +str(p)+'\n')
print ff.ask('SOUR:POW?')
#adwin.set_DAC_2(v)
qt.msleep(2)
#setting tarce 1
ff.write('INIT \r')
qt.msleep(15)
ff.write('CALC:FORM MLOG \r')
qt.msleep(2)
trace_mlog = eval(ff.ask('CALC:DATA:FDAT? \r'))
qt.msleep(2)
ff.write('CALC:FORM PHAS \r')
qt.msleep(2)
trace_phase = eval(ff.ask('CALC:DATA:FDAT? \r'))
v_dummy=np.linspace(p,p,len(f_list))
data.add_data_point(v_dummy,f_list,trace_mlog, np.gradient(np.unwrap(np.deg2rad(trace_phase),np.pi)))
data.new_block()
spyview_process(data,f_start,f_stop,p)
qt.msleep(0.01)
data.close_file()
qt.mend()
| [
"m.a.cohen@tudelft.nl"
] | m.a.cohen@tudelft.nl |
d1767709f57c48665edcfe804c9259dc130ff472 | 806ca8734caebd076811615350178c977f6ec283 | /circuit/distributions.py | 99ad79308abd0d1a634179a12c357920a26267fc | [] | no_license | gohil-vasudev/DFT | de6939f7de33b0d4a6fc6792eb30a999dc8f24eb | 8168844c068e5d56a42910aafe9adef0b2d49746 | refs/heads/master | 2023-06-16T08:28:48.643372 | 2021-07-06T22:50:37 | 2021-07-06T22:50:37 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 25,610 | py |
import numpy as np
from scipy.stats import norm, skewnorm
from scipy.special import owens_t, erf
from numpy import pi as PI
from gekko import GEKKO
import math
import pdb
AREA_CORRECTION = False
#### MAIN ISSUE with ACCURACY are the boundaries!
class Distribution:
""" moments is a list of moments """
def __init__(self, mom):
self.mom = mom
self.T = None
self.f_T = None
self.samples = None
def pdf(self, t):
raise NotImplementedError()
def cdf(self, t):
raise NotImplementedError()
def F_inv(self, low, high, F_target, eps=0.01):
mid = 0.5*(low+high)
F_mid = self.cdf(mid)
# print(low, high, mid, self.pdf(low), self.pdf(high), self.pdf(mid), self.cdf(low), self.cdf(high), F_mid, np.abs(F_mid-F_target))
# print("{:.10f}\t{:.10f}\t{:.10f}\t{:.10f}\t{:.10f}\t".format(
# low, high, mid, F_mid, np.abs(F_mid-F_target)))
# pdb.set_trace()
if abs(F_mid - F_target) < eps:
return mid
elif F_mid > F_target:
return self.F_inv(low, mid, F_target, eps=eps)
else:
return self.F_inv(mid, high, F_target, eps=eps)
def equal_F(self, low, high, count, eps=0.001):
# print("Function call:\t{:.4f}\t{:.4f}\t{}".format(low, high, count))
F_mid = (self.cdf(low) + self.cdf(high))/2
t_mid = self.F_inv(low, high, F_mid, eps=eps)
if count == 2:
res = [low, t_mid]
else:
left = self.equal_F(low, t_mid, count/2, eps)
right = self.equal_F(t_mid, high, count/2, eps)
left.extend(right)
res = left
# print("Results are: \t{:.4f}\t{:.4f}\t-->{}".format(low, high, res))
return res
def __pmf(self, samples, eps=0.0001):
# TODO: the description of function should be updated
""" Generates a smart sample set from the PDF of a Distribution
Arguments
-- samples: number of samples, if margin defined in this distribution, samples are
provided within margin, otherwise solid m1+-margin*m2 is margin
Returns:
-- A tuple of (T, f_T), both are numpy arrays
-- T: time value (RV) of each sample
-- f_T: the prob. value of T, i.e. f_T = f(t=T) """
low, high = self.margin()
if low == None:
print("Warning: possible mismatch in margin")
if self.m1 == None:
raise NameError("mean is not available")
else:
low = self.m1 - margin*self.m2
high = self.m1 + margin*self.m2
if np.log2(samples)%1 != 0:
samples = np.power(2, np.ceil(np.log2(samples)))
print("Changing samples to {}".format(samples))
T = self.equal_F(low, high, samples, eps=eps)
T.append(high)
f_T = [self.pdf(t) for t in T]
# F_T = [d.cdf(t) for t in T]
return np.asarray(T), np.asarray(f_T)
def pmf(self, samples, margin=6):
""" Generates a uniform sample set from the PDF of a Distribution
Parameters
----------
samples: int
number of samples, if margin defined in this distribution, samples are
provided within margin, otherwise solid m1+-margin*m2 is margin
Returns
-------
(T, f_T) : tuple (numpy array, numpy array)
T: time value (RV) of each sample
f_T: the prob. value of T, i.e. f_T = f(t=T)
"""
low, high = self.margin()
if low == None:
print("Warning: possible mismatch in margin")
if self.m1 == None:
raise NameError("mean is not available")
else:
low = self.m1 - margin*self.m2
high = self.m1 + margin*self.m2
T = np.linspace(low, high, samples)
f_T = np.zeros(T.shape)
for idx, t in enumerate(T):
f_T[idx] = self.pdf(t)
return T, f_T
def cmf(self, samples):
""" Generates a uniform sample set from the PDF of a Distribution
Arguments
-- samples: number of samples, if margin defined in this distribution, samples are
provided within margin, otherwise solid m1+-margin*m2 is margin
Returns:
-- A tuple of (T, f_T), each numpy arrays
-- T: time value (RV) of each sample
-- f_T: the prob. value of T, i.e. f_T = f(t=T) """
T, f_T = self.pmf(samples)
F_T = np.zeros(f_T.shape);
F_T[0] = f_T[0]
for t in range(1,len(T)):
dT = T[t] - T[t-1]
F_T[t] = F_T[t-1] + (f_T[t]*dT)
return T, F_T
@staticmethod
def cmf_from_pmf(T, f_T):
F_T = np.zeros(f_T.shape)
F_T[0] = f_T[0]
for t in range(1, len(T)):
dT = T[t] - T[t-1]
F_T[t] = F_T[t-1] + (dT * f_T[t])
return T, F_T
@staticmethod
def area_pmf(T, f_T):
""" This method calculates area of a pmf in the given range
-- T: numpy array of sample times
-- f_T: numpy array, PDF value at sample points
-- returns a floating point """
area = 0
for idx in range(len(T)-1):
area += (T[idx+1] - T[idx])*f_T[idx]
return area
def margin(self):
low, high = None, None
@staticmethod
def moments_from_pmf(T, f_T, moments=2):
if moments < 1:
return None
M = [0]*(moments+1) # [E_x, E_xx, E_xxx, .. ]
dT = np.zeros(T.shape)
dT[:-1] = T[1:] - T[:-1]
dT[-1] = dT[-2]
M[1] = np.sum( T * f_T * dT)
if moments > 1:
M[2] = np.sum( (T-M[1])**2 * f_T * dT)
if moments > 2:
nom = np.sum( (T-M[1])**3 * f_T * dT)
M[3] = nom / M[2]**1.5
return M[1:]
class Normal(Distribution):
def __init__(self, mu=0, sigma=1):
super().__init__([mu, sigma*sigma])
self.mu = mu
self.sigma = sigma
self.var = sigma*sigma
def pdf(self, t):
return norm.pdf(t, self.mu, self.sigma)
def cdf(self, t):
return norm.cdf(t, self.mu, self.sigma)
def margin(self):
return self.mu-6*self.sigma, self.mu+6*self.sigma
class SkewNormal(Distribution):
def __init__(self, zeta, omega, alpha):
# TODO: double check for omega to be positive!
self.zeta = zeta
self.omega = omega
self.alpha = alpha
location = zeta
scale = omega
shape = alpha
delta = shape / np.sqrt(1 + shape*shape)
self.mu = location + scale * delta * np.sqrt(2/PI)
self.var = scale * scale * (1- (2*delta*delta/PI))
self.sigma = np.sqrt(self.var)
self.gamma = 0.5 * (4-PI) * ((delta * np.sqrt(2/PI))**3) / ((1 - 2*delta*delta/PI)**1.5)
def pdf(self, t):
return skewnorm.pdf(t, self.alpha, self.zeta, self.omega)
def cdf(self, t):
return skewnorm.cdf(t, self.alpha, self.zeta, self.omega)
def margin(self, eps=0.0001):
_t = list(np.linspace(-3, 5, 101))
_phi = np.asarray([norm.cdf(t) for t in _t])
_owens_t = np.asarray([owens_t(t, self.alpha) for t in _t])
_cdf = _phi - 2*_owens_t
idx_l = next (x for x in range(len(_cdf)) if _cdf[x] > eps )
idx_h = next (x for x in range(len(_cdf)) if _cdf[x] > 1-eps )
low = _t[max(idx_l-1, 0)]
high = _t[min(idx_h+1, 100)]
low = (low*self.omega) + self.zeta
high = (high*self.omega) + self.zeta
return low, high
def _margin(self, eps=0.001):
low = self.mu
print("**", low)
while self.cdf(low) > eps:
low -= 0.1*np.abs(low)
print("*&*", low, self.cdf(low))
high = self.mu
while self.cdf(high) < 1-eps:
high += 0.1*np.abs(high)
return (low, high)
@staticmethod
def param_from_mom(mom):
if len(mom) != 3:
raise ValueError ("Moment dimension should be 3")
mu, var, gamma = mom
m = GEKKO()
delta = m.Var(value=1.06)
m.Equation([gamma ==
0.5 * (4-PI) * ( (delta * np.sqrt(2/PI))**3 ) / ( (1 - 2*delta*delta/PI)**1.5)])
m.solve(disp=False)
# print("result of delta: {}".format(delta.value))
if len(delta) > 1:
print("ERROR in delta")
delta = delta.value[0]
if np.abs(delta) > 1:
print("Warning: SkewNormal delta {:.5f} out of range!".format(delta))
delta = delta/(np.abs(delta) + 0.001)
print("Changed delta to {:.5f}".format(delta))
# print("num delta: {:.3f}".format(delta))
alpha = delta / np.sqrt(1-delta**2)
omega = np.sqrt( var / (1- (2*delta*delta/PI) ) )
zeta = mu - omega * delta * np.sqrt(2/PI)
return (zeta, omega, alpha)
class LogNormal(Distribution):
def __init__(self, Mu, Sigma):
# TODO: Mu and Sigma are not mean and std! but paramters of distribution
self.Mu = Mu
self.Sigma = Sigma
self.mu = np.exp(Mu + Sigma*Sigma/2)
self.var = (np.exp(Sigma**2) - 1) * np.exp(2*Mu + Sigma*Sigma)
self.sigma = np.sqrt(self.var)
# self.gamma = Not Implemented
def pdf(self, t):
nom = np.exp(-(np.log(t) - self.Mu)**2/(2*self.Sigma**2))
den = ( t * self.Sigma * np.sqrt(2*np.pi))
return nom/den
def cdf(self, t):
return 0.5*erf( (np.log(t) - self.Mu) / (np.sqrt(2) * self.Sigma) ) + 0.5
def margin(self, eps=0.001):
low = self.mu
while self.cdf(low) > eps:
low = low*0.9
high = self.mu
while self.cdf(high) < 1-eps:
high = high*1.1
return (low, high)
@staticmethod
def param_from_mom(mom):
if len(mom) != 2:
raise ValueError ("Moment dimension should be 2")
mu, var = mom
_r = var/(mu**2)
_Sigma = np.sqrt( np.log(_r+1) )
_Mu = np.log( mu / np.sqrt( (var/(mu**2)) + 1) )
return (_Mu, _Sigma)
class NumDist(Distribution):
""" Representing a probabilistic delay distribution with a a list of delays (T)
and a list of probability distribution function (pdf: f_T) values
"""
def __init__(self, T, f_T, clean=False, eps=1e-6, eps2=2e-6):
"""
Parameters
----------
T : list of float
sample delay values
f_T : list of float
sample of pdf values corresponding to T values
clean : bool
if clean, a method is used to clear the boundaries of the f #TODO
"""
#TODO: I need to double check the boundaries
if clean:
self.T = []
self.f_T = []
ptr_s = 0
ptr_f = len(T)-1
while(f_T[ptr_s] < eps):
ptr_s += 1
while(f_T[ptr_f] < eps):
ptr_f -= 1
while(ptr_s + 2 < ptr_f):
if f_T[ptr_s] < eps2 and f_T[ptr_s+1] < eps2 and f_T[ptr_s+2] < eps2:
ptr_s += 1
else:
break
while(ptr_f - 2 > 0):
if f_T[ptr_f] < eps2 and f_T[ptr_f-1] < eps2 and f_T[ptr_f-2] < eps2:
ptr_f -= 1
else:
break
self.T = T[ptr_s:ptr_f+1]
self.f_T = f_T[ptr_s:ptr_f+1]
print("\tChanging resolution: {} --> {}".format(len(T), len(self.T)))
else:
self.T = T
self.f_T = f_T
self.gen_F()
def pmf(self):
""" Overwriting pmf method from Distribution class, just returning T,f_T """
return self.T, self.f_T
def pdf(self, t):
""" Returns the pdf at delay value t for this numerical distribution
Warning: this method includes a search in a sorted list
"""
idx = np.searchsorted(self.T, t) # gives idx of first number bigger than t
if idx==0: # extrapolation
a = (self.f_T[1] - self.f_T[0])/(self.T[1] - self.T[0])
res = self.f_T[0] - a * (self.T[0]-t)
return max(0, res)
if idx==len(self.T): # extrapolation
a = (self.f_T[-1] - self.f_T[-2])/(self.T[-1] - self.T[-2])
res = self.f_T[-1] + a * (t-self.T[-1])
return max(0, res)
a = (t-self.T[idx-1])/(self.T[idx] - self.T[idx-1]) # interpolation
return (1-a)*self.f_T[idx-1] + a*self.f_T[idx]
def cdf(self, t):
""" Returns the cdf at delay value t for this numerical distribution
Warning: this method includes a search in a sorted list
"""
idx = np.searchsorted(self.T, t) # gives idx of first number bigger than t
if idx==0: # extrapolation
a = (self.F_T[1] - self.F_T[0])/(self.T[1] - self.T[0])
res = self.F_T[0] - a * (self.T[0]-t)
return max(0, res)
if idx==len(self.T): # extrapolation
a = (self.F_T[-1] - self.F_T[-2])/(self.T[-1] - self.T[-2])
res = self.F_T[-1] + a * (t-self.T[-1])
return min(1, res)
a = (t-self.T[idx-1])/(self.T[idx] - self.T[idx-1])
return (1-a)*self.F_T[idx-1] + a*self.F_T[idx]
def gen_F(self):
F_T = np.zeros(len(self.T))
F_T[0] = 0
for i in range(1, len(self.T)):
dT = self.T[i] - self.T[i-1]
# 0.5 added to make better prediction
F_T[i] = F_T[i-1] + 0.5*dT*(self.f_T[i]+self.f_T[i-1])
self.F_T = F_T
def margin(self):
return (min(self.T), max(self.T))
def area(self):
return Distribution.area_pmf(self.T, self.f_T)
class Uniform(Distribution):
""" Representing a uniform distribution """
def __init__(self, a, b):
"""
a : float
start value of distribtion
b : float
end value of distribtion
"""
assert a < b, "Uniform distribution, margin is not correct ({} > {})".format(a,b)
self.a = a
self.b = b
self.mu = (a+b)/2
self.var = (b-a)**2 / 12
self.sigma = np.sqrt(self.var)
def pdf(self, t):
if t >= self.a and t <= self.b:
return 1/(self.b-self.a)
return 0
def cdf(self, t):
if t < self.a:
return 0
elif t < self.b:
return (t-self.a)/(self.b-self.a)
return 1
def margin(self, eps = 0.01):
return self.a-(self.b-self.a)*eps, self.b + (self.b-self.a)*eps
class Triangle(Distribution):
""" Representing a triangle distribution """
def __init__(self, a, b, c):
"""
a : float
lower limit
b : float
upper limit
c : float
mode of the distribution
"""
assert a < b, "Triangle distribution, margin is not correct ({} > {})".format(a,b)
self.a = a
self.b = b
self.c = c
self.mu = (a+b+c)/3
self.var = (a**2 + b**2 + c**2 - (a*b + a*c + b*c) )/18
self.sigma = np.sqrt(self.var)
def pdf(self, t):
if t <= self.a or t >= self.b:
return 0
elif t < self.c:
return 2*(t-self.a)/( (self.b-self.a)*(self.c-self.a) )
elif t == self.c:
return 2/(self.b-self.a)
else: # if c < t < b:
return 2*(self.b-t)/( (self.b-self.a)*(self.b-self.c) )
def cdf(self, t):
if t < self.a:
return 0
elif t <= self.c:
return (t-self.a)**2/( (self.b-self.a)*(self.c -self.a) )
elif t < self.b:
return 1 - ((self.b-t)**2/( (self.b-self.a)*(self.c -self.a) ))
else: # if t >= b
return 1
def margin(self, eps = 0.01):
return self.a-(self.b-self.a)*eps, self.b + (self.b-self.a)*eps
class MaxOp:
def __init__(self):
self.max_alt_map = {
(Normal, Normal): self._max_NN, (Normal, SkewNormal): self._max_NSN,
(SkewNormal, Normal): self._max_SNN, (SkewNormal, SkewNormal): self._max_SNSN
}
def phi(self, t):
return norm.pdf(t)
def Phi(self, t):
return norm.cdf(t)
def max_alt(self, d1, d2):
return self.max_alt_map[(type(d1), type(d2))](d1, d2)
def _max_NSN(self, d1, d2, rho=0):
pass
def _max_SNN(self, d1, d2, rho=0):
pass
def _max_SNSN(self, d1, d2, rho=0):
pass
def _max_NN(self, d1, d2, rho=0):
''' does not work if this condition is satisfied:
(sig1 == sig2) and (rho == 1)
'''
mu1 = d1.mu
mu2 = d2.mu
sig1 = d1.sigma
sig2 = d2.sigma
a = np.sqrt(sig1**2 + sig2**2 - 2*rho*sig1*sig2)
alpha = (mu1 - mu2)/a
mu_max = mu1*self.Phi(alpha) + mu2*self.Phi(-alpha) + a*self.phi(alpha)
sig_max_2 = (mu1**2 + sig1**2)*self.Phi(alpha) + \
(mu2**2 + sig2**2)*self.Phi(-alpha) + \
(mu1 + mu2)*a*self.phi(alpha) - mu_max**2
sig_max = np.sqrt(sig_max_2)
return Normal(mu_max, sig_max)
def max_num(self, d1, d2, samples, rho=0, eps_error_area=0.001):
""" if d1 or d2 are raw pmfs, tuple(T, f_T), they will be converted to NumDist
o.w. they should be of type Distribution, or similar """
if isinstance(d1, tuple):
d1 = NumDist(d1[0], d1[1])
if isinstance(d2, tuple):
d2 = NumDist(d2[0], d2[1])
# Dirac distribution
if d1 == 0:
return d2;
if d2 == 0:
return d1;
assert isinstance(d1, Distribution), print("Error: d1 is not numerical distribution")
assert isinstance(d2, Distribution), print("Error: d2 is not numerical distribution")
l1, h1 = d1.margin()
l2, h2 = d2.margin()
# print(l1, l2, h1, h2)
''' range can be more restricted for max operation '''
low = max(l1, l2)
high = max(h1, h2)
ex_space = (high-low)*0.02
domain = np.linspace(low-ex_space, high+ex_space, samples)
f_max = np.zeros(samples)
for idx, t in enumerate(domain):
f1 = d1.pdf(t)
F1 = d1.cdf(t)
f2 = d2.pdf(t)
F2 = d2.cdf(t)
f_max[idx] = f1*F2 + F1*f2
if AREA_CORRECTION:
a = Distribution.area_pmf(domain, f_max)
if a!=1:
f_max = [f/a for f in f_max]
res = NumDist(domain, f_max)
_area = Distribution.area_pmf(res.T, res.f_T)
if abs(_area-1) > eps_error_area:
print("Error: area under pdf: {:.4f}".format(_area))
return -1
#TODO
# Distribution.area_pmf(d1.T, d1.f_T),
# Distribution.area_pmf(d2.T, d2.f_T),
# Distribution.area_pmf(temp.T, temp.f_T)))
# print("Area under pdf: {:.3f} {:.3f} {:.3f}".format(
# Distribution.area_pmf(d1.T, d1.f_T),
# Distribution.area_pmf(d2.T, d2.f_T),
# Distribution.area_pmf(temp.T, temp.f_T)))
#
# print( "D1 low={:.5f} \t high={:.5f} \t f[0]={:.5f} \t f[-1]={:.5f} \nD2 low={:.5f} \t high={:.5f} \t f[0]={:.5f} \t f[-1]={:.5f} \nMax low={:.5f} \t high={:.5f} \t f[0]={:.5f} \t f[-1]={:.5f}".format(
# d1.margin()[0], d1.margin()[1], d1.f_T[0], d1.f_T[-1],
# d2.margin()[0], d2.margin()[1], d2.f_T[0], d2.f_T[-1],
# temp.margin()[0], temp.margin()[1], temp.f_T[0], temp.f_T[-1]))
return res
class SumOp:
def __init__(self):
self.sum_alt_map = {
(Normal, Normal): self._sum_NN, (Normal, SkewNormal): self._sum_NSN,
(SkewNormal, Normal): self._sum_SNN, (SkewNormal, SkewNormal): self._sum_SNSN
}
def sum_alt(self, d1, d2):
return self.sum_alt_map[(type(d1), type(d2))](d1, d2)
def _sum_NSN(self, d1, d2, rho=0):
pass
def _sum_SNN(self, d1, d2, rho=0):
pass
def _sum_SNSN(self, d1, d2, rho=0):
pass
def _sum_NN(self, d1, d2, rho=0):
''' does not work if this condition is satisfied:
(sig1 == sig2) and (rho == 1)
'''
return Normal(d1.mu + d2.mu, np.sqrt(d1.sigma**2 + d2.sigma**2))
def sum_num(self, d1, d2, rho=0, samples=200):
""" if d1 or d2 are raw pmfs, i.e. tuple(T, f_T), they will be converted to
NumDist o.w. they should be of type Distribution """
if isinstance(d1, tuple):
print("Warning -- we still have T,f_T tupe as input for sum_num")
d1 = NumDist(d1[0], d1[1])
if isinstance(d2, tuple):
print("Warning -- we still have T,f_T tupe as input for sum_num")
d2 = NumDist(d2[0], d2[1])
# Dirac distribution
if d1 == 0:
return d2
if d2 == 0:
return d1
assert isinstance(d1, Distribution), print("Error: d1 is not distribution")
assert isinstance(d2, Distribution), print("Error: d2 is not distribution")
# The issue is that formal distributions need samples, but not NumDist
T1, f_T_1 = d1.pmf() if isinstance(d1, NumDist) else d1.pmf(samples)
l1, h1 = d1.margin()
l2, h2 = d2.margin()
low = l1 + l2
high = h1 + h2
domain = np.linspace(low, high, samples)
# dT = domain[1] - domain[0]
# print("Margin Dist #1: {:.3f}\t{:.3f}".format(l1, h1))
# print("Margin Dist #2: {:.3f}\t{:.3f}".format(l2, h2))
# print("Margin Dist Sum: {:.3f}\t{:.3f}".format(low, high))
f_sum = np.zeros(samples)
for sum_idx, t in enumerate(domain):
# fz(t) = INT fX(k) * fY(t-k) for k in [-inf, +inf]
# ..... = INT fX(k) * fY(t-k) for k in [X_min, X_max]
for idx, k in enumerate(T1[:-1]):
if k > t-l2: break
dK = T1[idx+1] - T1[idx]
f_sum[sum_idx] += (d1.pdf(k) * d2.pdf(t-k) * dK)
# print("\tArea: {:.6f}".format(Distribution.area_pmf(domain, f_sum)))
return NumDist(domain, f_sum, clean=True)
class DistScore:
@staticmethod
def KS_score(d_num, d_alt):
""" Measures the Kolomogrov-Smirnov score between two distributions
-- T, F_t are pmf of one distribution
-- dist_type: type of the 2nd distribution
-- mom: moments of the 2nd distribution
"""
T, F_T = d_num
max_dist = 0
for idx, t in enumerate(T):
delta_F = np.abs(F_T[idx] - d_alt.cdf(t))
max_dist = max(max_dist, delta_F)
return max_dist
@staticmethod
def CVM_score(d_num, d_alt):
""" Measures the Cram ́er-Von Mises score between two distributions
-- T, F_t are pmf of one distribution
-- dist_type: type of the 2nd distribution
-- mom: moments of the 2nd distribution
"""
T, F_T = d_num
score = 0
for idx in range(1, len(T)):
dT = T[idx] - T[idx-1]
t = T[idx]
if dT * ( (F_T[idx] - d_alt.cdf(t))**2 ) < 0:
raise NameError("Some issue with CVM")
score += dT * ( (F_T[idx] - d_alt.cdf(t))**2 )
return np.sqrt(score)
@staticmethod
def AD_score(T, F_T, dist_type, mom):
""" Measures the Anderson-Darling score between two distributions
-- T, F_t are pmf of one distribution
-- dist_type: type of the 2nd distribution
-- mom: moments of the 2nd distribution
"""
raise NameError("This measurement is not implemented")
@staticmethod
def score(d_num, meas="KS", dist_type="N"):
""" Measures the distance score between two empirical and analytical distributions
d_num: tuple for numerical (empirical) pmf (T, F_T)
model: distance metric, can be KS (Kolomogrov-Smirnov), CVM (Cramer-Von Mises)
or AD (Anderson-Darling - not implemented so far)
dist_type: what is the family of this distribution?
"""
meas_map = {"KS": DistScore.KS_score, "CVM": DistScore.CVM_score}
T, f_T = d_num
T, F_T = Distribution.cmf_from_pmf(T, f_T)
if dist_type == "N":
mom = Distribution.moments_from_pmf(T, f_T, 2)
d_alt = Normal(mom[0], np.sqrt(mom[1]))
# print("Moments: {:.3f}\t{:0.3f}".format(mom[0], mom[1]))
elif dist_type == "SK":
mom = Distribution.moments_from_pmf(T, f_T, 3)
zeta, omega, alpha = SkewNormal.param_from_mom(mom)
d_alt = SkewNormal(zeta, omega, alpha)
# print("Moments: {:.3f}\t{:.3f}\t{:.3f}".format(mom[0], mom[1], mom[2]))
# print("Params: {:.3f}\t{:.3f}\t{:.3f}".format(zeta, omega, alpha))
elif dist_type == "LN":
mom = Distribution.moments_from_pmf(T, f_T, 2)
Mu, Sigma = LogNormal.param_from_mom(mom)
d_alt = LogNormal(Mu, Sigma)
# print("Moments: {:.3f} \t {:.3f}".format(mom[0], mom[1]))
# print("Params: {:.3f} \t{:.3f}".format(Mu, Sigma))
return meas_map[meas]((T, F_T), d_alt)
| [
"abri442@usc.edu"
] | abri442@usc.edu |
a74be607b34134f98a467b55faa4a79f3353321b | c704b09bcdf6c693e766e4edcf27a23315b6fc7b | /gs11/api/serializers.py | 11b9b493189e4de44bcb67fa872cea2b309b6d7d | [] | no_license | techyshiv/Django_RestApi | afa28435c653f868a9cd6661f9072e4678dd93bc | 241cf463f541367fb4b93485bf78f37987832dc4 | refs/heads/master | 2023-01-31T20:31:05.758727 | 2020-12-13T13:09:13 | 2020-12-13T13:09:13 | 321,067,334 | 1 | 0 | null | 2020-12-13T13:10:16 | 2020-12-13T13:07:50 | null | UTF-8 | Python | false | false | 238 | py | # Create Model serailzer
from rest_framework import serializers
from .models import Student
class StudentSerializer(serializers.ModelSerializer):
class Meta:
model = Student
fields = ["id","name","roll","city"] | [
"1616510104@kit.ac.in"
] | 1616510104@kit.ac.in |
429da4daa2c1602ac80e875b6aed9aa5a6812b71 | 75a4a0f71f3da07de4abd5e8f9f09712815feefc | /Python/python_lanqiao/基础题单/2017_字符串统计.py | 23d0f95394b7a006797cba0147aeb17f2c08ebf1 | [] | no_license | QiYi92/StudyLab | 987cf1a48b0f522858aced31351eb9e7af3d5532 | 03ea528b0405e3602e7cdab82dc98ed4ada79e0f | refs/heads/master | 2023-07-14T22:13:10.811991 | 2021-08-15T16:43:42 | 2021-08-15T16:43:42 | 319,321,339 | 3 | 0 | null | null | null | null | UTF-8 | Python | false | false | 461 | py | # 2017字符串统计
# 知识点
# 统计字符串出现的次数
# str.count()
# 统计字符串出现的位置
# str.find()
n = int(input())
for i in range(n):
sum = 0 # 重置清零
a = input()
sum += a.count('1')
sum += a.count('2')
sum += a.count('3')
sum += a.count('4')
sum += a.count('5')
sum += a.count('6')
sum += a.count('7')
sum += a.count('8')
sum += a.count('9')
sum += a.count('0')
print(sum) | [
"62023930+QiYi92@users.noreply.github.com"
] | 62023930+QiYi92@users.noreply.github.com |
4d4c097352648b5921a147bce201bc822ae5964f | ed7badfc7ecd738001f4d3e9945cce3a2d8b059d | /HIndex.py | 14f5430a66896837eedbcf60030339820706ffec | [] | no_license | tanjingjing123/LeetcodeAlgorithms | ab41f20bfca1305d07af00ae8db725fef6d059b8 | 2bb2881824cc4e84ab6afad6085e02e1b682c96d | refs/heads/master | 2023-02-04T12:22:52.665477 | 2020-01-01T00:11:20 | 2020-01-01T00:11:20 | 284,194,379 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 382 | py | import bisect
def hIndex(citations):
sorted_citations = sorted(citations, reverse=True)
citations_len = len(sorted_citations)
if citations_len <= 0:
return 0
h_idx = 0
for order_loc in range(citations_len):
if sorted_citations[order_loc] >= order_loc + 1:
h_idx += 1
return h_idx
citations = [3,0,6,1,5]
print(hIndex(citations))
| [
""
] | |
4eba4dbcba0281425312479229160dda6cc51f00 | 1605df2155631e820f2a68da8e48fc05d9e2c117 | /622/solution.py | bed30a6b6dbd613497aaf8c642e3d3bb831e73bd | [] | no_license | zmwangx/Project-Euler | 918e564b7706d0785acd46ccb3f6689af5bec870 | da8ca343d3f1dc9262be1713e72ff0ffde0c2f33 | refs/heads/master | 2021-01-20T03:40:20.553534 | 2020-01-24T16:24:38 | 2020-01-24T16:24:38 | 9,463,976 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 335 | py | #!/usr/bin/env python3
import sympy.ntheory
divisors = sympy.ntheory.factor_.divisors
def main():
n = 60
sizes = set(s + 1 for s in divisors(2 ** n - 1))
for d in divisors(n):
if d != n:
sizes -= set(s + 1 for s in divisors(2 ** d - 1))
print(sum(sizes))
if __name__ == "__main__":
main()
| [
"i@zhimingwang.org"
] | i@zhimingwang.org |
8559e49fc770740ddfa6ab9992347095f7de2769 | 57e80b3938394520bcb114ee4a89a4e172023917 | /event/models.py | 8f26d5942e3210d3d0f53e8d18ee6579bddb191e | [] | no_license | khakhil/events | 2bc75046a43e074abe996516e8704fab7fb8546d | 115c5c6cb2c6b1fbdb549552b82267cb102dbaa8 | refs/heads/master | 2020-12-02T11:06:21.977563 | 2017-07-08T07:51:03 | 2017-07-08T07:51:03 | 95,869,469 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 12,704 | py | from django.db import models
from django.core.validators import RegexValidator
from django.utils import timezone
from django import forms
from idlelib.IOBinding import blank_re
from django.template.defaultfilters import default
from enum import unique
class Blogs(models.Model):
unique_display = models.CharField(max_length=200,blank=True, null=True)
url_key = models.CharField(max_length=200,) # for help text
title = models.CharField(max_length=200,)
description = models.TextField(blank=True, null=True)
user = models.ForeignKey('auth.User', blank=True, null=True)
source = models.CharField(max_length=200,blank=True, null=True)
status = models.CharField(max_length=200, choices=[('', ''), ('Draft', 'Draft'), ('Trash','Trash'), ('Published', 'Published')], default='Draft',blank=True, null=True)
post_date = models.DateTimeField(default=timezone.now)
views = models.PositiveIntegerField(blank=True, null=True)
genre_cat = models.ForeignKey('GenreCategories', blank=True, null=True)
post_type = models.CharField(max_length=200, choices=[('', ''),('Blog', 'Blog'), ('News', 'News')], default='Blog',blank=True, null=True)
excerpt = models.CharField(max_length=200,blank=True, null=True)
pic = models.ForeignKey('Media', blank=True, null=True)
class Meta:
db_table = "blogs"
class CategoriesOfEvents(models.Model):
event = models.ForeignKey('Events')
event_category = models.ForeignKey('EventCategories')
class Meta:
db_table = "categories_of_events"
class CategoriesOfEventManagers(models.Model):
user = models.ForeignKey('auth.User')
event_category = models.ForeignKey('EventCategories')
class Meta:
db_table = "categories_of_event_managers"
class CiSessions(models.Model):
ip_address = models.CharField(max_length=200,blank=True, null=True)
timestamp = models.DateTimeField(default=timezone.now)
data = models.CharField(max_length=200,blank=True, null=True)
class Meta:
db_table = "ci_sessions"
class ContactSubmissions(models.Model):
name = models.CharField(max_length=200,)
email = models.EmailField(max_length=200, blank=False)
phone = models.CharField(max_length=10, validators=[RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '0 to 9'. Up to 10 digits allowed.")], blank=True)
message = models.TextField(blank=True, null=True)
# agent = models.ForeignKey('Agent')
submit_time = models.DateTimeField(default=timezone.now)
subject = models.CharField(max_length=200,)
class Meta:
db_table = "contact_submissions"
class Countries(models.Model):
sortname = models.CharField(max_length=3,)
name = models.CharField(max_length=200,)
url_key = models.CharField(max_length=200, blank=True)
class Meta:
db_table = "countries"
class CurlEventUrl(models.Model):
url = models.CharField(max_length=200,)
class Meta:
db_table = "curl_event_url"
class EmailNewsletter(models.Model):
email = models.EmailField(max_length=200, blank=False, unique=True)
date = models.DateField(default=timezone.now)
class Meta:
db_table = "email_newsletter"
class Enquiries(models.Model):
name = models.CharField(max_length=200,)
email = models.EmailField(max_length=200, blank=False)
phone = models.CharField(max_length=10, validators=[RegexValidator(regex=r'^\+?1?\d{9,15}$', message="Phone number must be entered in the format: '0 to 9'. Up to 10 digits allowed.")], blank=True)
message = models.TextField(blank=True, null=True)
property = models.ForeignKey('PropertyTypes', blank=True, null=True)
rent_or_sale = models.CharField(max_length=200,choices=[('Rent', 'Rent'), ('Sale','Sale')], )
country = models.ForeignKey('Countries', blank=True, null=True)
city = models.CharField(max_length=200,)
property_type = models.PositiveIntegerField(blank=True, null=True)
address = models.CharField(max_length=200,)
price = models.FloatField(null=True)
zip = models.CharField(max_length=10,)
# agent = models.ForeignKey('Agent')
date = models.DateField(default=timezone.now)
user_ip = models.CharField(max_length=100,)
class Meta:
db_table = "enquiries"
class Events(models.Model):
event_name = models.CharField(max_length=200,)
tag_line = models.CharField(max_length=200,)
event_start_date = models.DateField(blank=True)
event_start_time = models.TimeField(blank=True)
event_end_date = models.DateField(blank=True)
event_end_time = models.TimeField(blank=True)
logo = models.CharField(max_length=200,blank=True, null=True)
banner_1_event = models.CharField(max_length=200,blank=True, null=True)
banner_2_event = models.CharField(max_length=200,blank=True, null=True)
banner_3_event = models.CharField(max_length=200,blank=True, null=True)
event_description = models.TextField(blank=True, null=True)
organizer = models.CharField(max_length=200, blank=True, null=True)
country = models.ForeignKey('Countries')
city = models.CharField(max_length=200, blank=True, null=True)
address_line_1 = models.CharField(max_length=200, blank=True, null=True)
address_line_2 = models.CharField(max_length=200, blank=True, null=True)
zip = models.PositiveIntegerField()
gallery_photograph = models.CharField(max_length=200, blank=True, null=True)
amount = models.CharField(max_length=11, blank=True, null=True)
url_key = models.CharField(max_length=200, blank=True, null=True)
is_featured = models.BooleanField(max_length=1, choices=[(0, 'NO'), (1, 'YES')],)
user = models.ForeignKey('auth.User')
class Meta:
db_table = "events"
class EventsDataUrl(models.Model):
url = models.CharField(max_length=200,)
class Meta:
db_table = "events_data_url"
class EventsUrl(models.Model):
url = models.CharField(max_length=200,)
class Meta:
db_table = "events_url"
class EventCategories(models.Model):
name = models.CharField(max_length=200,)
url_key = models.CharField(max_length=200,)
parent_id = models.PositiveIntegerField(blank=True, null=True)
status = models.BooleanField(max_length=1, choices=[(0, 'inactive'), (1, 'active')], default="1",)
added_by = models.ForeignKey('auth.User')
added_on = models.DateTimeField(default=timezone.now, blank=True, null=True)
class Meta:
db_table = "event_categories"
class EventTypes(models.Model):
name = models.CharField(max_length=200,)
url_key = models.CharField(max_length=200,)
parent_id = models.PositiveIntegerField(blank=True, null=True)
status = models.BooleanField(max_length=1, choices=[(0, 'inactive'), (1, 'active')], default="1",)
added_by = models.ForeignKey('auth.User')
added_on = models.DateTimeField(default=timezone.now, blank=True, null=True)
class Meta:
db_table = "event_types"
class GenreCategories(models.Model):
name = models.CharField(max_length=200,)
url_key = models.CharField(max_length=200,)
status = models.BooleanField(max_length=1, choices=[(0, 'inactive'), (1, 'active')], default="1",)
added_by = models.ForeignKey('auth.User')
added_on = models.DateTimeField(default=timezone.now, blank=True, null=True)
class Meta:
db_table = "genre_categories"
class MailTemplates(models.Model):
mail_title = models.CharField(max_length=200,)
field_name = models.CharField(max_length=200,)
is_html = models.BooleanField(max_length=1, choices=[(0, 'NO'), (1, 'YES')], default="1",)
from_email = models.CharField(max_length=200,)
reply_to_email = models.CharField(max_length=200,)
return_to_email = models.CharField(max_length=200,)
smtp_username = models.CharField(max_length=50,)
smtp_password = models.CharField(max_length=100,)
smtp_host = models.CharField(max_length=50,)
smtp_port = models.CharField(max_length=6,)
mail_subject = models.CharField(max_length=200,)
mail_content = models.TextField(blank=True, null=True,)
mail_subject = models.BooleanField(max_length=1, choices=[(0, 'inactive'), (1, 'active')], default="1",)
class Meta:
db_table = "mail_templates"
class Media(models.Model):
file_name = models.CharField(max_length=150,)
author = models.PositiveIntegerField(blank=True, null=True)
title = models.CharField(max_length=150,)
mime_type = models.CharField(max_length=200,)
date = models.DateTimeField(default=timezone.now, blank=True, null=True)
class Meta:
db_table = "media"
class Partners(models.Model):
event = models.ForeignKey('Events')
partners_name = models.CharField(max_length=150,)
partners_description = models.TextField(blank=True)
class Meta:
db_table = "partners"
class Portfolio(models.Model):
user = models.ForeignKey('auth.User')
name_of_event = models.CharField(max_length=150,)
pic_of_event = models.ForeignKey('media')
des = models.TextField(blank=True,)
date_of_event = models.DateTimeField(blank=True, null=True)
class Meta:
db_table = "portfolio"
class PropertyTypes(models.Model):
name = models.CharField(max_length=200,)
url_key = models.CharField(max_length=200,)
parent_id = models.PositiveIntegerField(blank=True, null=True)
status = models.BooleanField(max_length=1, choices=[(0, 'inactive'), (1, 'active')], default="1",)
added_by = models.ForeignKey('auth.User')
added_on = models.DateTimeField(default=timezone.now, blank=True, null=True)
class Meta:
db_table = "property_types"
class Speaker(models.Model):
event = models.ForeignKey('Events')
speakers_name = models.CharField(max_length=200,)
speaker_description = models.TextField(blank=True, null=True,)
class Meta:
db_table = "speaker"
class Sponsers(models.Model):
event = models.ForeignKey('Events')
sponsers_name = models.CharField(max_length=20,)
class Meta:
db_table = "sponsers"
class StaticPages(models.Model):
title = models.CharField(max_length=250,)
description = models.TextField(blank=True, null=True,)
created = models.DateTimeField(default=timezone.now, blank=True, null=True)
update = models.DateTimeField(default=timezone.now, blank=True, null=True)
status = models.BooleanField(max_length=1, choices=[(0, 'inactive'), (1, 'active')], default="1",)
meta_title = models.CharField(max_length=150,)
meta_description = models.CharField(max_length=250,)
url_key = models.CharField(max_length=200,)
class Meta:
db_table = "static_pages"
class SysSettings(models.Model):
title = models.CharField(max_length=200,)
field_name = models.CharField(max_length=200, blank=True, null=True,)
type = models.BooleanField(max_length=1, choices=[(0, 'text'), (1, 'textarea'), (2, 'select')], default="0",)
select_items = models.TextField(blank=True, null=True,)
value = models.TextField(blank=True, null=True,)
is_required = models.BooleanField(max_length=1, choices=[(0, 'no'), (1, 'yes')], default="0",)
is_core_config_item = models.BooleanField(max_length=1, choices=[(0, 'no'), (1, 'yes')], default="1",)
created = models.DateTimeField(default=timezone.now, blank=True, null=True)
status = models.BooleanField(max_length=1, choices=[(0, 'inactive'), (1, 'active')], default="1",)
class Meta:
db_table = "sys_settings"
class Tags(models.Model):
blog = models.ForeignKey('Blogs')
tags = models.CharField(max_length=200,)
url_key = models.CharField(max_length=200, blank=True, null=True,)
class Meta:
db_table = "tags"
class TypesOfEvents(models.Model):
event = models.ForeignKey('Events')
event_types = models.ForeignKey('EventTypes')
class Meta:
db_table = "types_of_events"
class types_of_event_manager(models.Model):
user = models.ForeignKey('auth.User')
event_types = models.ForeignKey('EventTypes')
class Meta:
db_table = "types_of_event_manager"
class UserEmailVerification(models.Model):
user = models.ForeignKey('auth.User')
code = models.CharField(max_length=200,)
status = models.BooleanField(max_length=1, choices=[(0, 'inactive'), (1, 'active')], default="1",)
class Meta:
db_table = "user_email_verification" | [
"v.kumar1235@gmail.com"
] | v.kumar1235@gmail.com |
d25b2a00a51d14a243e148c035a3aa5f2c4070c4 | 6062376fa8637a49533ea411f16bdbb9bb042b2c | /service/workflow/workflow_base_service.py | 915c05641d768bd33112ad69f166579e8ae2ebc3 | [
"MIT"
] | permissive | Rgcsh/loonflow_custom | 4ae9d72f811455baff98a0ddff50c54fb3b216a0 | 14d29d6669a6538fe176792d001710616719d050 | refs/heads/master | 2023-05-26T01:23:58.972585 | 2019-12-10T06:57:33 | 2019-12-10T06:57:33 | 227,034,056 | 2 | 1 | MIT | 2023-05-22T22:35:18 | 2019-12-10T05:10:34 | Python | UTF-8 | Python | false | false | 8,836 | py | import json
from django.db.models import Q
from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from apps.workflow.models import Workflow
from service.base_service import BaseService
from service.common.log_service import auto_log
from service.account.account_base_service import AccountBaseService
class WorkflowBaseService(BaseService):
"""
流程服务
"""
def __init__(self):
pass
@classmethod
@auto_log
def get_workflow_list(cls, name, page, per_page, workflow_id_list):
"""
获取工作流列表
:param name:
:param page:
:param per_page:
:param workflow_id_list:工作流id list
:return:
"""
query_params = Q(is_deleted=False)
if name:
query_params &= Q(name__contains=name)
query_params &= Q(id__in=workflow_id_list)
workflow_querset = Workflow.objects.filter(query_params).order_by('id')
paginator = Paginator(workflow_querset, per_page)
try:
workflow_result_paginator = paginator.page(page)
except PageNotAnInteger:
workflow_result_paginator = paginator.page(1)
except EmptyPage:
# If page is out of range (e.g. 9999), deliver last page of results
workflow_result_paginator = paginator.page(paginator.num_pages)
workflow_result_object_list = workflow_result_paginator.object_list
workflow_result_restful_list = []
for workflow_result_object in workflow_result_object_list:
workflow_result_restful_list.append(dict(id=workflow_result_object.id, name=workflow_result_object.name, description=workflow_result_object.description,
notices=workflow_result_object.notices, view_permission_check=workflow_result_object.view_permission_check,
limit_expression=workflow_result_object.limit_expression, display_form_str=workflow_result_object.display_form_str,
creator=workflow_result_object.creator, gmt_created=str(workflow_result_object.gmt_created)[:19]))
return workflow_result_restful_list, dict(per_page=per_page, page=page, total=paginator.count)
@classmethod
@auto_log
def check_new_permission(cls, username, workflow_id):
"""
判断用户是否有新建工单的权限
:param username:
:param workflow_id:
:return:
"""
# 获取workflow的限制表达式
workflow_obj, msg = cls.get_by_id(workflow_id)
if not workflow_obj:
return False, msg
limit_expression = workflow_obj.limit_expression
if not limit_expression:
return True, 'no limit_expression set'
#'限制周期({"period":24} 24小时), 限制次数({"count":1}在限制周期内只允许提交1次), 限制级别({"level":1} 针对(1单个用户 2全局)限制周期限制次数,默认特定用户);允许特定人员提交({"allow_persons":"zhangsan,lisi"}只允许张三提交工单,{"allow_depts":"1,2"}只允许部门id为1和2的用户提交工单,{"allow_roles":"1,2"}只允许角色id为1和2的用户提交工单)
limit_expression_dict = json.loads(limit_expression)
limit_period = limit_expression_dict.get('period')
limit_count = limit_expression_dict.get('limit_count')
limit_allow_persons = limit_expression_dict.get('allow_persons')
limit_allow_depts = limit_expression_dict.get('allow_depts')
limit_allow_roles = limit_expression_dict.get('allow_roles')
if limit_period:
from service.ticket.ticket_base_service import TicketBaseService
if limit_expression_dict.get('level'):
if limit_expression_dict.get('level') == 1:
count_result, msg = TicketBaseService.get_ticket_count_by_args(workflow_id=workflow_id, username=username, period=limit_period)
elif limit_expression_dict.get('level') == 2:
count_result, msg = TicketBaseService.get_ticket_count_by_args(workflow_id=workflow_id, period=limit_period)
else:
return False, 'level in limit_expression is invalid'
if count_result is False:
return False, msg
if not limit_expression_dict.get('count'):
return False, 'count is need when level is not none'
if count_result > limit_expression_dict.get('count'):
return False, '{} tickets can be created in {}hours when workflow_id is {}'.format(limit_count, limit_period, workflow_id)
if limit_allow_persons:
if username not in limit_allow_persons.split(','):
return False, '{} can not create ticket base on workflow_id:{}'.format(workflow_id)
if limit_allow_depts:
# 获取用户所属部门,包含上级部门
user_all_dept_id_list, msg = AccountBaseService.get_user_up_dept_id_list(username)
if user_all_dept_id_list is False:
return False, msg
# 只要user_all_dept_id_list中的某个部门包含在允许范围内即可
limit_allow_dept_str_list = limit_allow_depts.split(',')
limit_allow_dept_id_list = [int(limit_allow_dept_str) for limit_allow_dept_str in limit_allow_dept_str_list]
limit_allow_dept_id_list = list(set(limit_allow_dept_id_list)) #去重
total_list = user_all_dept_id_list + limit_allow_dept_id_list
if len(total_list) == len(set(total_list)):
# 去重后长度相等,说明两个list完全没有重复,即用户所在部门id肯定不在允许的部门id列表内
return False, 'user is not in allow dept'
if limit_allow_roles:
# 获取用户所有的角色
user_role_list, msg = AccountBaseService.get_user_role_id_list(username)
if user_role_list is False:
return False, msg
limit_allow_role_str_list = limit_allow_roles.split(',')
limit_allow_role_id_list = [int(limit_allow_role_str) for limit_allow_role_str in limit_allow_role_str_list]
limit_allow_role_id_list = list(set(limit_allow_role_id_list))
total_list = limit_allow_role_id_list + user_role_list
if len(total_list) == len(set(total_list)):
return False, 'user is not in allow role'
return True, ''
@classmethod
@auto_log
def get_by_id(cls, workflow_id):
"""
获取工作流 by id
:param workflow_id:
:return:
"""
workflow_obj = Workflow.objects.filter(is_deleted=0, id=workflow_id).first()
if not workflow_obj:
return False, '工作流不存在'
return workflow_obj, ''
@classmethod
@auto_log
def add_workflow(cls, name, description, notices, view_permission_check, limit_expression, display_form_str, creator):
"""
新增工作流
:param name:
:param description:
:param notices:
:param view_permission_check:
:param limit_expression:
:param display_form_str:
:param creator:
:return:
"""
workflow_obj = Workflow(name=name, description=description, notices=notices, view_permission_check=view_permission_check,
limit_expression=limit_expression,display_form_str=display_form_str, creator=creator)
workflow_obj.save()
return workflow_obj.id, ''
@classmethod
@auto_log
def edit_workflow(cls, workflow_id, name, description, notices, view_permission_check, limit_expression, display_form_str):
"""
更新工作流
:param workflow_id:
:param name:
:param description:
:param notices:
:param view_permission_check:
:param limit_expression:
:param display_form_str:
:return:
"""
workflow_obj = Workflow.objects.filter(id=workflow_id, is_deleted=0)
if workflow_obj:
workflow_obj.update(name=name, description=description, notices=notices, view_permission_check=view_permission_check,
limit_expression=limit_expression, display_form_str=display_form_str)
return workflow_id, ''
@classmethod
@auto_log
def delete_workflow(cls, workflow_id):
"""
删除工作流
:param workflow_id:
:return:
"""
workflow_obj = Workflow.objects.filter(id=workflow_id, is_deleted=0)
if workflow_obj:
workflow_obj.update(is_deleted=True)
return workflow_id, ''
| [
"renguangcai@jiaaocap.com"
] | renguangcai@jiaaocap.com |
eddb1083f72d566a9ba78588b02c0de1582230e7 | 8cb101991346bd6403cfaca88b0445f917e52254 | /tuneuptechnology/tickets.py | d5ccf178b5ba56d3c933e59ce7abdad16b3a0163 | [
"MIT",
"Python-2.0"
] | permissive | TrendingTechnology/tuneuptechnology-python | a06742fbf404fb1afc525ccf1d432c4c374866f1 | 479bbece1722f7e233dbc0f7642205e1afa971c1 | refs/heads/main | 2023-06-08T17:26:41.108769 | 2021-06-22T02:15:45 | 2021-06-22T02:15:45 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,201 | py | class Tickets():
def __init__(self, base_url, make_http_request):
self.base_url = base_url
self.make_http_request = make_http_request
def create(self, data):
"""Create a ticket based on the data passed"""
endpoint = f'{self.base_url}/tickets'
response = self.make_http_request('post', endpoint, data)
return response
def all(self):
"""Retrieve all tickets"""
endpoint = f'{self.base_url}/tickets'
response = self.make_http_request('get', endpoint)
return response
def retrieve(self, id):
"""Retrieve a single ticket"""
endpoint = f'{self.base_url}/tickets/{id}'
response = self.make_http_request('get', endpoint)
return response
def update(self, id, data):
"""Update a ticket with the passed params"""
endpoint = f'{self.base_url}/tickets/{id}'
response = self.make_http_request('patch', endpoint, data)
return response
def delete(self, id):
"""Delete a ticket with the ID passed"""
endpoint = f'{self.base_url}/tickets/{id}'
response = self.make_http_request('delete', endpoint)
return response
| [
"noreply@github.com"
] | TrendingTechnology.noreply@github.com |
39053cb9d32fb5c76a44bfb827629ba4e6d5e6f8 | 02f79bc383266c71c4bfa0eb940cb663149a7630 | /leetcode and gfg/leetCode/try_test.py | a44a54a909d4651a07c39697f11839525df45389 | [] | no_license | neilsxD/justCodes | a10febad0ac47d115310e6e06768b7a7dc63d05c | 950ae26fce82f54341deee790e5df530f65c88d4 | refs/heads/main | 2023-07-17T04:38:32.703085 | 2021-08-24T10:22:23 | 2021-08-24T10:22:23 | 399,422,088 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 5,954 | py | # # # # lis = [[]]
# # # # lis[0].append(2)
# # # # print(lis)
# # # # a = []
# # # # a.extend([2])
# # # # print(a)
# # # # # dic_t = {2: 1}
# # # # # print(dic_t)
# # # # # dic_t[3]= ((1,2))
# # # # # print(dic_t[3][1])
# # # # # dic_t[3] = dic_t[3].append(11)
# # # # # print(dic_t)
# # # # # print(dic_t[3])
# # # # # print(dic_t[2])
# # # # a = None
# # # # b = 2
# # # # print(4 or 11)
# # # # print(int('2'))
# # # # x = (int('4') - 2)*3 + 97
# # # # print(chr(x))
# # # # a = [[1,2],[2,3]]
# # # # if a[2][2] and a[2][2] == 3 : print(a)
# # # # a = ['1','2','3','4']
# # # # print(a[1:3])
# # # # a[1:3] = [''.join(a[1:3])]
# # # # # s = 'hello'
# # # # x = []
# # # # x=[s[:len(s)]]
# # # # print(x)
# # # x = ['a','bcd', 'e']
# # # print(x[1][:])
# # # x[1:2] = x[1][:]
# # # print(x)
# # # print(''.join(x[1:3]))
# # # print([[1] * 3] * 3)
# # # st_r = 'abcdef'
# # # print(st_r[2:4])
# # # b = ['22']
# # # b.append(st_r[2:4])
# # # print(b)
# # # a = [1, 2]
# # # print(a[:])
# # # a= { 1 : 2 , 3: 4 }
# # # if 1 in a : print("zfd")
# # # if 2 in a : print ("nooo")
# # # from functools import reduce
# # # print(reduce(lambda a,b : a.append([[0] * 3]) , [[0] * 4]) )
# # # a = set()
# # # print (a)
# # # # a = (1,2)
# # # # print (a)
# # # a.append(3)
# # # print (a)
# # # x= {i:float('inf') for i in range(5)}
# # # print (x)
# # import heapq
# # a = [2,4,6,3,7,8]
# # min_heap = []
# # heapq.heappush(min_heap, 3)
# # heapq.heappush(min_heap, 2)
# # heapq.heappush(min_heap, a[1])
# # print(min_heap)
# # print(a)
# # a = float('-inf')
# # print(a)
# # import heapq
# # li = [11,2, 4,3,5,12,14,15,21,26,22]
# # heapq.heapify(li)
# # print(li)
# # print(heapq.nlargest(8, li))
# # print(heapq.nsmallest(7,li))
# # L = ['aaaa', 'bbb', 'cc', 'd', 'eeeee', 'ffffff']
# # # sorted without key parameter
# # print(sorted(L))
# # print()
# # def comp(a):
# # return len(a)%3
# # # sorted with key parameter
# # print(sorted(L, key = comp))
# # string = "a,v,d,f"
# # print(string[2:5])
# # lis = string.split(',')
# # print(lis[1:3])
# # lis[1:3] = [ 'a' , 'd' , 'f ']
# # print(lis)
# # Python code to demonstrate working of
# # append(), appendleft(), pop(), and popleft()
# # importing "collections" for deque operations
# # import collections
# # # initializing deque
# # de = collections.deque([1,2,3])
# # # using append() to insert element at right end
# # # inserts 4 at the end of deque
# # de.append(4)
# # # printing modified deque
# # print ("The deque after appending at right is : ")
# # print (de)
# # # using appendleft() to insert element at left end
# # # inserts 6 at the beginning of deque
# # de.appendleft(6)
# # # printing modified deque
# # print ("The deque after appending at left is : ")
# # print (de)
# # # using pop() to delete element from right end
# # # deletes 4 from the right end of deque
# # de.pop()
# # # printing modified deque
# # print ("The deque after deleting from right is : ")
# # print (de)
# # # using popleft() to delete element from left end
# # # deletes 6 from the left end of deque
# # de.popleft()
# # # printing modified deque
# # print ("The deque after deleting from left is : ")
# # print (de)
# # print(de[1])
# # # cop = de[:]
# # # print(cop)
# # cop2 = de.copy()
# # print(cop2)
# # print(de.remove(1))
# # print(de)
# # from collections import deque
# # lis = deque()
# # if lis : print('no')
# # else : print('yes')
# # a = [1,2,3,5,6,7,9]
# # for i,el in enumerate(a) :
# # print(i,el)
# # For list of integers
# # lst1 = []
# # # For list of strings/chars
# # lst2 = []
# # # lst1 = map(lambda x: int(x), input("Enter the list items : ").split())
# # a,b = [int(x) for x in input("list:").split()]
# # # lst2 = input("Enter the list items : ").split()
# # print(a,b)
# # print(type(a), type(b))
# # # print(lst2)
# # sumt =
# # m = [[0]*3 for _ in range(4)]
# # print(m)
# # m[2][2] = 1
# # m[0][0] = 2
# # print(m)
# # n=2
# # # print(10**(n-1))
# # for i in range(10**(n-1), 10**n):
# # print(i)
# # val = set()
# # st = 'hello me'
# # val.update(st)
# # print(val)
# # for i,el in enumerate(val) :
# # print(i,el)
# # import collections
# # dic_t = collections.defaultdict(lambda : [] )
# # dic_t[2].append([3])
# # print(dic_t[2])
# # print(max(dic_t[2], dic_t[3]))
# # que = collections.deque()
# # que.append([1])
# # print(que)
# # que.append([1,2])
# # print(que)
# # arr = [1, 0, 0, 0, 1, 0, 1]
# # st_r = list(map(str, arr))
# # print(st_r)
# # ans = ''.join(st_r)
# # print(int(ans))
# # a = [[1,3],[4,8],[2,2]]
# # a.sort( key= lambda x : x[1] )
# # print(a)
# # a = [2,4,6,3,8,1]
# # s = a.copy()
# # s.sort(reverse=1)
# # print(a)
# # print(s)
# # x = set(s)
# # for i,e in enumerate(x) :
# # print(i,e)
# # dic_t =collections.Counter(a)
# # print(dic_t)
# # el = 'ab'
# # temp = [el]
# # temp.extend([])
# # print(temp)
# def numberOfWays(string):
# # Code here
# n = len(string)
# def lenpalindrome(ind,f):
# nonlocal n
# i = 0
# while(ind-i>=0 and ind+i+f<n):
# if string[ind-i] != string[ind+i+f] : break
# i+=1
# return 2*(i-1) +1 + f
# total = n
# for i in range(n) :
# l = lenpalindrome(i,0)
# if l :
# total+= l//2
# l = lenpalindrome(i,1)
# if l :
# total+= l//2
# return total
# print(numberOfWays('aaa'))
# print(str(44443).split('.'))
# arr = [5,3,6,23,5]
# print(max(arr))
| [
"noreply@github.com"
] | neilsxD.noreply@github.com |
f95ae46de57449685a1b929e2d7eb3108b8f93a4 | 17ff7ee3aa0dc4b001e4c3ca24581f38f1c26691 | /Jose/Ejercicios-0 Introduccion/Buclewhile.py | febd1db4cd8532a3ab7c76aab58643aec2d54b4f | [] | no_license | carlosmanri/Logic-Thinking | 51ee7309c67e7f0371048401d731617d704edeca | 61ebedda3fe1ffee89daebf274f55e104d515e51 | refs/heads/master | 2022-05-15T21:35:29.050312 | 2015-04-28T18:52:57 | 2015-04-28T18:52:57 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 196 | py | lista = []
palabra = input("Escriba una palabra: ")
while palabra != "":
lista += [palabra]
palabra = input("Escriba otra palabra: ")
print("Las palabras que has escrito son: ", lista)
| [
"jotajotanora@gmail.com"
] | jotajotanora@gmail.com |
588cbec8471a39479c9b0cd0ad6d3c275f1ee5e6 | 6e5fba0851dd9c428c0bdf19a56a6e8a3744cba5 | /FinalExam/final4/userDAO.py | 1149ab21b9f058e154c4545eeeb688bb0829a8db | [] | no_license | besteto/mongoBD-101P | 66a3fc59f9c5185f68437a0ce61d36dd842e410a | ef9ba9947f4a837172591d505a21041618debff2 | refs/heads/master | 2021-01-01T16:25:11.918064 | 2015-07-18T23:36:56 | 2015-07-18T23:36:56 | 37,178,508 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 2,585 | py |
#
# Copyright (c) 2008 - 2013 10gen, Inc. <http://10gen.com>
#
# 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 hmac
import random
import string
import hashlib
import pymongo
# The User Data Access Object handles all interactions with the User
# collection.
class UserDAO:
def __init__(self, db):
self.db = db
self.users = self.db.users
self.SECRET = 'verysecret'
# makes a little salt
def make_salt(self):
salt = ""
for i in range(5):
salt = salt + random.choice(string.ascii_letters)
return salt
# implement the function make_pw_hash(name, pw) that returns a hashed password
# of the format:
# HASH(pw + salt),salt
# use sha256
def make_pw_hash(self, pw, salt=None):
if salt == None:
salt = self.make_salt()
return hashlib.sha256(pw + salt).hexdigest()+"," + salt
# Validates a user login. Returns user record or None
def validate_login(self, username, password):
user = None
try:
user = self.users.find_one({'_id': username})
except:
print "Unable to query database for user"
if user is None:
print "User not in database"
return None
salt = user['password'].split(',')[1]
if user['password'] != self.make_pw_hash(password, salt):
print "user password is not a match"
return None
# Looks good
return user
# creates a new user in the users collection
def add_user(self, username, password, email):
password_hash = self.make_pw_hash(password)
user = {'_id': username, 'password': password_hash}
if email != "":
user['email'] = email
try:
self.users.insert(user, safe=True)
except pymongo.errors.OperationFailure:
print "oops, mongo error"
return False
except pymongo.errors.DuplicateKeyError as e:
print "oops, username is already taken"
return False
return True
| [
"besteto@gmail.com"
] | besteto@gmail.com |
ae8725e520c6402628de792b23eacbe688886482 | 3693221a45347a052efbd909e5c1829f040ab314 | /Ex1.py | d500020e8f377d79f03fc8aeff3bf4fba37220c4 | [] | no_license | FedeScuote/proyecto_pln | e2f7aaad55680cb8e8b0384049c7348b995fee43 | f34767988d52719061a47b04debc2a77144113e7 | refs/heads/master | 2020-04-06T04:53:07.523092 | 2016-11-21T03:13:49 | 2016-11-21T03:13:49 | 73,648,620 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,688 | py | import matplotlib.pyplot as plt
import operator
import os
import nltk
from collections import Counter
def tokenize(text_name):
"""
1)
:param text_name: receives the name of a text
:return: returns a list of tokens in that archive
"""
raw = open(text_name, 'rU').read()
tokens = nltk.word_tokenize(raw)
return tokens
def count_words(corpus_root):
"""
2)
:param corpus_root: receives the full path of the corpus location
:return: a dictionary that maps for every word on the corpus, the number of ocurrences
"""
tokens = []
for root, dirs, files in os.walk(corpus_root):
for filename in files:
tokens.extend(tokenize(os.path.join(root, filename)))
counter = Counter()
for token in tokens:
counter[token] += 1
return counter
def sort_words(dict):
"""
3)
:param dict: Receives a dictionary of words
:return: returns a sorted list of the words in dict, sorted by amount of occurrences
"""
return sorted(dict.items(), key=operator.itemgetter(1), reverse=True)
def zipf_law(sorted_list):
"""
4)
:param sorted_list: receives a sorted list of the corpus, sorted by amount of occurrences
:return: a list of tuples that can be analyzed for zipf_law for the first 100 words
"""
zipfs_law = []
ranked_list = enumerate(sorted_list[10:100])
for rank, (word, count) in ranked_list:
zipfs_law.append((word, count, rank + 1, count * (rank + 1)))
counts = [token[1] for token in zipfs_law]
ranks = [token[2] for token in zipfs_law]
plt.plot(ranks, counts)
plt.ylabel('counts')
plt.xlabel('ranks')
plt.show()
| [
"fscuoteguazza@gmail.com"
] | fscuoteguazza@gmail.com |
98479f0fdf838f589f1a2a9e81057f6451e9f1f8 | 4df369a423947480377fe1dac09090b0c8ff350a | /LPTHW/ex16.py | 3132402139c54af58eb47ba37cc2799602d5926e | [] | no_license | ryan-cunningham/Other | 38512dd72ffc2433c916b53206e4164557732aa7 | 2d948ed46265006f3b50062dce2cb762ba9a4a5a | refs/heads/master | 2021-10-30T09:03:50.420770 | 2019-04-26T03:47:47 | 2019-04-26T03:47:47 | 102,972,592 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 709 | py | # LPTHW: Exercise 16 - Reading and Writing Files
from sys import argv
script, filename = argv
print(f"We're going to erase {filename}.")
print("If you don't want that, hit CTRL-C (^C).")
print("If you do want that, hit RETURN.")
input("?")
print("Opening the file...")
target = open(filename, 'w')
print("Truncating the file. Goodbye!")
target.truncate()
print("Now I'm going to ask you for three lines.")
line1 = input("line 1: ")
line2 = input("line 2: ")
line3 = input("line 3: ")
print("I'm going to write these to the file.")
target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")
print("And finally, we close it.")
target.close()
| [
"noreply@github.com"
] | ryan-cunningham.noreply@github.com |
3ba4d9a3323a8bb7a9dd944f28bff4943cd98968 | 266947fd84eed629ed0c21f6d91134239512afd9 | /BeginnerContest_B/061.py | 8605568528a2b38ba911c5cdf7aae2aba95aad32 | [] | no_license | SkiMsyk/AtCoder | c86adeec4fa470ec14c1be7400c9fc8b3fb301cd | 8102b99cf0fb6d7fa304edb942d21cf7016cba7d | refs/heads/master | 2022-09-03T01:23:10.748038 | 2022-08-15T01:19:55 | 2022-08-15T01:19:55 | 239,656,752 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 173 | py | N, M = map(int, input().split())
res = [0]*N
for _ in range(M):
a, b = map(int, input().split())
res[a-1] += 1
res[b-1] += 1
for _ in range(N):
print(res[_]) | [
"sakaimasayuki@sakaimasayukinoMacBook-puro.local"
] | sakaimasayuki@sakaimasayukinoMacBook-puro.local |
400a0257a584a5bde03506f6bfcab9092f778721 | cfca1a0d2200a7ec2652e38c4d3448269b7d30fa | /homework3.py | 9b02f8e1d9eba969e1a8d83c21e206b0318647b7 | [] | no_license | Raghunandan-MS/FOLResolutionEngine | 2a929fef7d0cda578bffc26bd0005b04fffeb26c | d5a5edce457a264ee0f8c771378f24314969ddcd | refs/heads/master | 2020-09-14T03:21:48.174843 | 2019-11-26T01:12:19 | 2019-11-26T01:12:19 | 223,001,546 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,210 | py | import os
import re
import copy
import time
KB = []
pattern = r'([\~]?\w[\w]*)\((.*)\)$' # To be able to mathc the predicat and the specified parameters to the predicate in FOL
stdVariableDictionary = {}
startTime = 0
def readInput():
global KB
global startTime
queryList = []
KBList = []
input_file = open('input7.txt', 'r')
inputParams = input_file.readlines()
input_file.close()
queryArgs = inputParams[0: int(inputParams[0]) + 1]
KBArgs = inputParams[int(inputParams[0]) + 1::]
for i in range(1, len(queryArgs)):
queryList.append(queryArgs[i].rstrip('\n'))
for i in range(1, len(KBArgs)):
KBList.append(KBArgs[i].rstrip('\n'))
convertToCNF(KBList)
outputString = ''
for query in queryList:
startTime = time.time()
queryResult = resolutionAlgorithm(KB, query)
outputString = outputString + queryResult + '\n'
outputString = outputString[0:len(outputString) - 1]
output_file = open('output.txt' , 'w')
output_file.write(outputString)
output_file.close()
def resolutionAlgorithm(KB, alpha):
# Returns true or false.
clauses = copy.deepcopy(KB)
clauses.append(negateLiteral(alpha))
new = set()
while True:
for i in range(len(clauses)):
for j in range(i+1, len(clauses)):
if clauses[i] == clauses[j]:
continue
endTime = time.time()
if int(endTime - startTime) > 15:
return 'FALSE'
resolvents = resolveSentences(clauses[i], clauses[j])
if 'JUNK' in resolvents:
return 'TRUE'
new = new.union(resolvents)
if new.issubset(set(clauses)):
return 'FALSE'
clauses = list(set(clauses).union(new))
def resolveSentences(sentenceA, sentenceB):
sentenceSplitA = sentenceA.split(' | ')
sentenceSplitB = sentenceB.split(' | ')
formulasInferred = set()
for litA in sentenceSplitA:
for litB in sentenceSplitB:
if ('~' in litA and '~' not in litB) or ('~' not in litA and '~' in litB): #and (not ('~' in litA and '~' in litB)):
theta = unifyLists(litA, litB, {})
if theta != 'FAILURE':
unifiedSentenceA = applySubstitution(theta, sentenceA)
unifiedLitA = applySubstitution(theta, litA)
unifiedSentenceB = applySubstitution(theta, sentenceB)
unifiedLitB = applySubstitution(theta, litB)
sentenceC = unifiedSentenceA.difference(unifiedLitA).union(unifiedSentenceB.difference(unifiedLitB))
sentenceC = ' | '.join(list(sentenceC))
if len(sentenceC) == 0:
formulasInferred.add('JUNK')
else:
formulasInferred.add(sentenceC)
return formulasInferred
def applySubstitution(theta, sentence):
global pattern
splitVal = sentence.split(' | ')
tempList = []
for i in range(len(splitVal)):
predicate, params = re.match(pattern, splitVal[i]).groups()
paramsSplit = params.split(',')
for i in range(len(paramsSplit)):
tempVar = paramsSplit[i]
if tempVar.islower() and tempVar in theta.keys():
paramsSplit[i] = paramsSplit[i].replace(tempVar, theta[tempVar])
params = ','.join(paramsSplit)
tempList.append(predicate + '(' + params + ')')
return set(tempList)
def unifyLists(litA, litB, theta):
global pattern
predA, argsA = re.match(pattern, litA).groups()
predB, argsB = re.match(pattern, litB).groups()
argsSplitA = argsA.split(',')
argsSplitB = argsB.split(',')
if '~' in predA:
predA = predA[1:]
elif '~' in predB:
predB = predB[1:]
if predA != predB or (len(argsSplitA) != len(argsSplitB)):
return 'FAILURE'
for i in range(len(argsSplitA)):
termA = argsSplitA[i]
termB = argsSplitB[i]
theta = unifyTerms(termA, termB, theta)
if theta == 'FAILURE':
return 'FAILURE'
return theta
def unifyTerms(termA, termB, theta):
while termA.islower() and theta.get(termA, False):
termA = theta[termA]
while termB.islower() and theta.get(termB, False):
termB = theta[termB]
if termA == termB:
pass
elif termA.islower():
theta[termA] = termB
elif termB.islower():
theta[termB] = termA
elif not termA.islower() or not termB.islower():
theta = 'FAILURE'
else:
theta = unifyLists(termA, termB, theta)
return theta
def convertToCNF(sentences):
# 3 types of variants to be handeled here.
# 1. p1 & p1 & p3 => q / ~q (Remove implication and handle the changes)
# 2. p1 & p2 (Consider each of them as seperate literals)
# 3. P(x,y)
global KB
for sentence in sentences:
if '=>' in sentence:
implicationList = sentence.split(' => ')
consequent = implicationList[-1]
premise = implicationList[0]
string = negateAndConvert(premise)
cnfSentence = string + ' | ' + consequent
stdSentence = standardizeVariables(cnfSentence)
KB.append(stdSentence)
else:
stdSentence = standardizeVariables(sentence)
KB.append(stdSentence)
def negateAndConvert(premiseList):
literals = premiseList.split(' & ')
# Return a list of standardized variables
tempList = []
for literal in literals:
tempList.append(negateLiteral(literal))
string = ' | '.join(tempList)
return string
def standardizeVariables(sentence):
global pattern
global stdVariableDictionary
sentenceLiterals = []
variableSeen = []
stringSplit = sentence.split(' | ')
for strings in stringSplit:
predicate, arguments = re.match(pattern, strings).groups()
argsSplit = arguments.split(',')
for i in range(len(argsSplit)):
tempVar = argsSplit[i]
if tempVar.islower():
if tempVar not in stdVariableDictionary.keys():
stdVariableDictionary[tempVar] = 1
argsSplit[i] = tempVar.replace(tempVar, tempVar + str(stdVariableDictionary[tempVar]))
variableSeen.append(tempVar)
else:
argsSplit[i] = tempVar.replace(tempVar, tempVar + str(stdVariableDictionary[tempVar]))
variableSeen.append(tempVar)
else:
continue
arguments = ','.join(argsSplit)
sentenceLiterals.append(predicate + '(' + arguments + ')')
return ' | '.join(sentenceLiterals)
def negateLiteral(literal):
if '~' in literal:
return literal[1:]
else:
return '~' + literal
if __name__ == '__main__':
start = time.time()
readInput()
end = time.time()
print ("The total time to execute the program is : ", end - start) | [
"noreply@github.com"
] | Raghunandan-MS.noreply@github.com |
5b80cf5018bb337ff535a03f221739250e143826 | 463fab8078c53dbc7186f264baa42fe95fd08a1d | /store/models.py | c526012645f4a4c0f53d8a707efc95429c9c4e9e | [] | no_license | alkymi-io/migration-exercise | daa68580dede29d1207e8109c18c5df72fa947b9 | 8573f45a9178306994f10e4014d222113ba4bbee | refs/heads/master | 2023-03-30T16:21:13.593523 | 2021-03-15T17:36:21 | 2021-03-15T17:36:21 | 347,194,933 | 0 | 3 | null | 2023-03-25T23:13:33 | 2021-03-12T20:53:04 | Python | UTF-8 | Python | false | false | 869 | py | from django.db import models
class Record(models.Model):
schema = models.ForeignKey('store.Schema',
on_delete=models.CASCADE)
class Cell(models.Model):
record = models.ForeignKey('store.Record',
on_delete=models.CASCADE)
field_name = models.TextField()
field = models.ForeignKey('store.Field',
null=True,
on_delete=models.CASCADE)
"""Newly added ForeignKey.
This field is new. We want to write a migration that sets
``field`` by finding a Field with a matching ``name`` to
the cell's ``field_name``.
"""
class Schema(models.Model):
name = models.TextField()
class Field(models.Model):
name = models.TextField()
schema = models.ForeignKey(
'store.Schema', on_delete=models.CASCADE)
| [
"steven@alkymi.io"
] | steven@alkymi.io |
dc65e6410727b1ebb8c1a7f88bd8ec30a210df4a | 6c4e95ef26d571b2e1f68cf64d69243796703c47 | /turtle 2.py | c3c48b36d1caf00bdf650559023e2d72c98b9ac9 | [] | no_license | Vincent36912/python200818 | 5d389e3f526b940459a3c189761418a5cf9b2caa | 7b1a3f98050076c09244e3636fdcb3dc30d62a02 | refs/heads/master | 2022-11-29T05:22:12.280989 | 2020-08-18T08:48:36 | 2020-08-18T08:48:36 | 288,401,630 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 187 | py | import turtle
a=turtle.Turtle()
screen=turtle.Screen()
screen.title('window')
screen.bgcolor('gold')
a.pensize(3)
a.color('red')
a.shape('turtle')
a.backward(100)
turtle.done | [
"noreply@github.com"
] | Vincent36912.noreply@github.com |
c65b7e673c0a35b00495800f1e42cc14dd21e0e8 | 1dff6eb7028092ee1510a2759fce5c415bfb9d4a | /interim files/pkmnData 624 PM 01-03-2020.py | 06ba9b068ef64dc2709a0f4b942196d7e54afee4 | [] | no_license | jsyiek/computingproject | 401adc6b3d46454ac0005a4c9046f8ddfbbd224f | 0c08bb799969ae31d61bbedf7a44c5e69444c0dd | refs/heads/master | 2022-11-18T04:07:51.834138 | 2020-06-29T20:57:37 | 2020-06-29T20:57:37 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 32,948 | py | pokemonInDraft = ['Charizard',
'Amoonguss',
'Electivire',
'Feraligatr',
'Garchomp','Gardevoir','Gengar',
'Hydreigon',
'Infernape',
'Kyurem-B',
'Lucario',
'Magnezone',
'Rotom-H','Rotom-W',
'Scizor',
'Quagsire',
'Tyranitar']
typeColor = {
'Grass' : 'SpringGreen2',
'Water' : 'SteelBlue1',
'Fire' : 'tomato',
'Dark' : 'gray50',
'Psychic' : 'maroon1',
'Fighting' : 'brown',
'Rock' : 'burlywood4',
'Ground' : 'burlywood3',
'Ice' : 'PaleTurquoise1',
'Dragon' : 'slate blue',
'Fairy' : 'pink',
'Normal' : 'beige',
'Poison' : 'magenta3',
'Steel' : 'gray64',
'Electric' : 'yellow',
'Flying' : 'light blue',
'Ghost':'purple',
'Bug':'light green'
}
userSwitchMessages = ['%s! Return!','Good job, come back %s!',
'Ok, come back, %s!',"That's enough, %s."]
userSendInMessages = ["Your foe's weak, gettem, %s!", "Go! %s!", "Show 'em who's boss, %s!",
"Give it everything you've got, %s!","%s! I choose you!"]
backgrounds = {
'route' : {'filePath' : 'assets/routeBackground.png', 'bgColor' : 'green'},
'indoor' : {'filePath' : 'assets/indoorBackground.png','bgColor' : 'grey'}
}
assets = {
'selectionBox' : 'assets/drafting/selectionBox.png',##these until the next comment are resources for drafting
'sBoxTR' : 'assets/drafting/selectionBoxTR.png',
'sBoxTL' : 'assets/drafting/selectionBoxTL.png',
'sBoxBR' : 'assets/drafting/selectionBoxBR.png',
'sBoxBL' : 'assets/drafting/selectionBoxBL.png',
'begin' : 'assets/drafting/begin.png',
'draft' : 'assets/drafting/draft.png',
'triangle' : 'assets/trianglePointer.jpg', ##the rest are for use in battlegui
'fightButton' : 'assets/fightButton.png',
'grass' : 'assets/Basic_Grass.png',
'indoor-enemy' : 'assets/indoor-enemy-platform.png',
'indoor-user' : 'assets/indoor-user-platform.png',
'EnemyHP' : 'assets/inbattle/EnemyHPNewNew.png',
'UserHP' : 'assets/inbattle/UserHPNew.png',
'greenBar' : 'assets/inbattle/Green.png',
'yellowBar' : 'assets/inbattle/Yellow.png',
'redBar' : 'assets/inbattle/Red.png'
}
trainerSprites = {'Blue' : 'assets/trainers/Blue.gif','Ben':'assets/trainers/Ben.png','Dalton':'assets/trainers/Dalton.png','Pedro':'assets/trainers/Pedro.png','Yuriy':'assets/trainers/Yuriy.png'}
trainerBackSprites = {'Ethan' : 'assets/trainers/BACK-Ethan.gif'}
pokeballs = {'Masterball' : 'assets/pokeballs/masterball.gif','Pokeball' : 'assets/pokeballs/pokeball.gif'}
throwpokeballs = {'Pokeball' : 'assets/pokeballs/throw-pokeball.gif'}
toBe = '''To be, or not to be, that is the question: Whether 'tis nobler in the mind to suffer The slings and arrows of outrageous fortune, Or to take arms against a sea of troubles And by opposing end them. To die—to sleep, No more; and by a sleep to say we end The heart-ache and the thousand natural shocks That flesh is heir to: 'tis a consummation Devoutly to be wish'd. To die, to sleep; To sleep, perchance to dream—ay, there's the rub: For in that sleep of death what dreams may come, When we have shuffled off this mortal coil, Must give us pause—there's the respect That makes calamity of so long life. For who would bear the whips and scorns of time, Th'oppressor's wrong, the proud man's contumely, The pangs of dispriz'd love, the law's delay, The insolence of office, and the spurns That patient merit of th'unworthy takes, When he himself might his quietus make With a bare bodkin? Who would fardels bear, To grunt and sweat under a weary life, But that the dread of something after death, The undiscovere'd country, from whose bourn No traveller returns, puzzles the will, And makes us rather bear those ills we have Than fly to others that we know not of? Thus conscience does make cowards of us all, And thus the native hue of resolution Is sicklied o'er with the pale cast of thought, And enterprises of great pitch and moment With this regard their currents turn awry And lose the name of action.'''
attacks = {'fighting' : 'assets/attacks/fp/fightingPhysical.png'}
pokemon = {'Charizard' : 'assets/pokemon/charizard.gif'}
pokemonBackSprites = {'Charizard' : 'assets/pokemon/charizard-back.png'}
icons = {'Charizard':'assets/pokemon/charizard_icon.gif','False':'assets/none.png'}
for x in pokemonInDraft:
pokemon[x] = 'assets/pokemon/'+x.lower()+'.gif'
pokemonBackSprites[x] = 'assets/pokemon/'+x.lower()+'-back.png'
icons[x] = 'assets/pokemon/'+x.lower()+'_icon.gif'
#Swampert Moves: 'Earthquake', 'Ice Punch', 'Superpower', 'Waterfall',
moveInfo = {
'<Template>' : {'type' : '', 'category' : '', 'priority' : 0, 'power' : 0, 'pp' : 1, 'accuracy' : 0, 'description' : ""},
##A
'Acrobatics' : {'type' : 'Flying', 'category' : 'Physical', 'priority' : 0, 'power' : 55, 'pp' : 100, 'accuracy' : 100, 'description' : "User nimbly strikes the foe."},
'Aerial Ace' : {'type' : 'Flying', 'category' : 'Physical', 'priority' : 0, 'power' : 60, 'pp' : 20, 'accuracy' : 900, 'description' : "An extremely fast attack against one target. It can’t be evaded."},
'Amnesia' : {'type' : 'Psychic', 'category' : 'Status', 'priority' : 0, 'power' : 0, 'pp' : 20, 'accuracy' : 900, 'description' : 'User forgets about the world. Sharply raises the user’s Sp. Defense.'},
'Aqua Jet' : {'type' : 'Water', 'category' : 'Physical', 'priority' : 1, 'power' : 40, 'pp' : 20, 'accuracy' : 100, 'description' : "User lunges at the foe at very high speed. It is sure to strike first."},
'Aqua Tail' : {'type' : 'Water', 'category' : 'Physical', 'priority' : 0, 'power' : 90, 'pp' : 10, 'accuracy' : 90, 'description' : 'User attacks with its tail as if it were a wave in a raging storm.'},
'Aura Sphere' : {'type' : 'Fighting', 'category' : 'Special', 'priority' : 0, 'power' : 80, 'pp' : 20, 'accuracy' : 900, 'description' : "User releases powerful aura from its body. Can't miss."},
##B
'Blaze Kick' : {'type' : 'Fire', 'category' : 'Physical', 'priority' : 0, 'power' : 85, 'pp' : 10, 'accuracy' : 90, 'description' : "A kick with a high critical-hit ratio. May cause a burn."},
'Blizzard' : {'type' : 'Ice', 'category' : 'Special', 'priority' : 0, 'power' : 110, 'pp' : 1, 'accuracy' : 70, 'description' : "Foe is blasted with a blizzard. May cause freezing."},
'Bone Rush' : {'type' : 'Ground', 'category' : 'Physical', 'priority' : 0, 'power' : 25, 'pp' : 10, 'accuracy' : 90, 'description' : "User strikes foe with a bone in hand two to five times."},
'Brick Break' : {'type' : 'Fighting', 'category' : 'Physical', 'priority' : 0, 'power' : 75, 'pp' : 15, 'accuracy' : 100, 'description' : " Destroys barriers such as Reflect and causes damage."},
'Bullet Punch' : {'type' : 'Steel', 'category' : 'Physical', 'priority' : 1, 'power' : 40, 'pp' : 40, 'accuracy' : 100, 'description' : "A lighting-fast punch with an iron fist. Always goes first."},
##C
'Calm Mind' : {'type' : 'Psychic', 'category' : 'Status', 'priority' : 0, 'power' : 0, 'pp' : 20, 'accuracy' : 900, 'description' : "User focuses its mind to raise their Sp. Attack and Sp. Defense."},
'Chip Away' : {'type' : 'Dark', 'category' : 'Physical', 'priority' : 0, 'power' : 70, 'pp' : 20, 'accuracy' : 100, 'description' : "Foe’s stat changes don’t affect this attack's damage."},
'Clear Smog' : {'type' : 'Poison', 'category' : 'Special', 'priority' : 0, 'power' : 50, 'pp' : 15, 'accuracy' : 900, 'description' : "Uesr throws a clump of special mud. Foe's stat changes are reset."},
'Close Combat' : {'type' : 'Fighting', 'category' : 'Physical', 'priority' : 0, 'power' : 120, 'pp' : 5, 'accuracy' : 100, 'description' : "User attacks foe in close without guarding itself. Lowers user’s Defense and Sp. Defense."},
'Crunch' : {'type' : 'Dark', 'category' : 'Physical', 'priority' : 0, 'power' : 80, 'pp' : 15, 'accuracy' : 100, 'description' : "Foe is crunched with sharp fangs. It may lower the foe’s Defense."},
##D
'Dark Pulse' : {'type' : 'Dark', 'category' : 'Special', 'priority' : 0, 'power' : 80, 'pp' : 15, 'accuracy' : 100, 'description' : "User releases a horrible aura imbued with dark thoughts. May cause flinching."},
'Discharge' : {'type' : 'Electric', 'category' : 'Special', 'priority' : 0, 'power' : 80, 'pp' : 15, 'accuracy' : 100, 'description' : "A loose flare of electricity strikes the foe. May cause paralysis."},
'Double Team' : {'type' : 'Normal', 'category' : 'Status', 'priority' : 0, 'power' : 0, 'pp' : 15, 'accuracy' : 900, 'description' : "The user creates illusory copies of itself to raise its evasiveness."},
'Dual Chop' : {'type' : 'Dragon', 'category' : 'Physical', 'priority' : 0, 'power' : 40, 'pp' : 15, 'accuracy' : 90, 'description' : "Foe is hit with brutal strikes. Hits twice."},
'Draco Meteor' : {'type' : 'Dragon', 'category' : 'Special', 'priority' : 0, 'power' : 130, 'pp' : 1, 'accuracy' : 90, 'description' : "Comets are summoned from the sky. Sharply lowers user's Sp. Attack"},
'Dragon Claw' : {'type' : 'Dragon', 'category' : 'Physical', 'priority' : 0, 'power' : 80, 'pp' : 15, 'accuracy' : 100, 'description' : "User slashes foe with sharp claws."},
'Dragon Dance' : {'type' : 'Dragon', 'category' : 'Status', 'priority' : 0, 'power' : 0, 'pp' : 20, 'accuracy' : 900, 'description' : "A mystical dance that ups Attack and Speed."},
'Dragon Pulse' : {'type' : 'Dragon', 'category' : 'Special', 'priority' : 0, 'power' : 85, 'pp' : 10, 'accuracy' : 100, 'description' : "Foe is hit by a shock wave generated by the user's mouth."},
'Dragon Rush' : {'type' : 'Dragon', 'category' : 'Physical', 'priority' : 0, 'power' : 100, 'pp' : 10, 'accuracy' : 75, 'description' : "With overwhelming menace, user tackles foe. May cause flinching."},
'Drain Punch' : {'type' : 'Fighting', 'category' : 'Physical', 'priority' : 0, 'power' : 75, 'pp' : 10, 'accuracy' : 100, 'description' : "An energy-draining punch. User steals HP from foe."},
##E
'Earth Power' : {'type' : 'Ground', 'category' : 'Special', 'priority' : 0, 'power' : 90, 'pp' : 10, 'accuracy' : 100, 'description' : "User makes ground under foe erupt. May lower foe's Sp. Defense."},
'Earthquake' : {'type' : 'Ground', 'category' : 'Physical', 'priority' : 0, 'power' : 100, 'pp' : 10, 'accuracy' : 100, 'description' : 'The user sets off an earthquake that strikes every Pokémon around it.'},
'Electro Ball' : {'type' : 'Electric', 'category' : 'Special', 'priority' : 0, 'power' : 40, 'pp' : 10, 'accuracy' : 100, 'description' : "This attack's power increases drastically if user is much faster than foe."},
'Energy Ball' : {'type' : 'Grass', 'category' : 'Special', 'priority' : 0, 'power' : 90, 'pp' : 10, 'accuracy' : 100, 'description' : "User draws power from nature and fires it at the foe. May lower foe's Sp. Defense."},
'Extreme Speed' : {'type' : 'Normal', 'category' : 'Physical', 'priority' : 2, 'power' : 80, 'pp' : 5, 'accuracy' : 100, 'description' : "A blindingly speedy charge attack that always goes before any other."},
##F
'Facade' : {'type' : 'Normal', 'category' : 'Physical', 'priority' : 0, 'power' : 70, 'pp' : 20, 'accuracy' : 100, 'description' : 'An attack that is boosted if user is burned, poisoned, or paralyzed.'},
'Fake Out' : {'type' : 'Normal', 'category' : 'Physical', 'priority' : 3, 'power' : 40, 'pp' : 10, 'accuracy' : 100, 'description' : "An attack that hits first and causes flinching. Usable only on 1st turn."},
'Fire Blast' : {'type' : 'Fire', 'category' : 'Special', 'priority' : 0, 'power' : 110, 'pp' : 5, 'accuracy' : 85, 'description' : "Incinerates everything it strikes. May cause a burn."},
'Fire Fang' : {'type' : 'Fire', 'category' : 'Physical', 'priority' : 0, 'power' : 65, 'pp' : 1, 'accuracy' : 95, 'description' : "A fiery bite. May burn foe or cause flinching."},
'Fire Punch' : {'type' : 'Fire', 'category' : 'Physical', 'priority' : 0, 'power' : 75, 'pp' : 15, 'accuracy' : 100, 'description' : "A fiery punch that may burn the foe."},
'Flamethrower' : {'type' : 'Fire', 'category' : 'Special', 'priority' : 0, 'power' : 90, 'pp' : 15, 'accuracy' : 100, 'description' : "Foe is scorched with intense flames. May cause burn."},
'Flash Cannon' : {'type':'Steel','category' : 'Special', 'priority' : 0, 'power' : 80, 'pp' : 10, 'accuracy' : 100, 'description' : "User gathers light energy and releases it at once. May lower foe's Sp. Defense."},
'Focus Blast' : {'type' : 'Fighting', 'category' : 'Special', 'priority' : 0, 'power' : 120, 'pp' : 1, 'accuracy' : 70, 'description' : "User heightens and unleashes its mental power. May lower foe's Sp. Defense."},
'Freeze Shock' : {'type' : 'Ice', 'category' : 'Physical', 'priority' : 0, 'power' : 140, 'pp' : 5, 'accuracy' : 90, 'description' : "On the second turn, foe is hit with electrically charged ice. May cause paralysis."},
'Fury Cutter' : {'type' : 'Bug', 'category' : 'Physical', 'priority' : 0, 'power' : 40, 'pp' : 20, 'accuracy' : 95, 'description' : "An attack that grows stronger on each successive hit."},
'Fusion Bolt' : {'type' : 'Electric', 'category' : 'Physical', 'priority' : 0, 'power' : 100, 'pp' : 5, 'accuracy' : 100, 'description' : "User unleashes its frightening electrical energy."},
##G
'Giga Drain' : {'type' : 'Grass', 'category' : 'Special', 'priority' : 0, 'power' : 75, 'pp' : 10, 'accuracy' : 100, 'description' : "An attack that steals half the damage inflicted."},
'Gunk Shot' : {'type' : 'Poison', 'category' : 'Physical', 'priority' : 0, 'power' : 120, 'pp' : 5, 'accuracy' : 80, 'description' : "User throws garbage at foe. May poison foe."},
##H
'Hex' : {'type' : 'Ghost', 'category' : 'Special', 'priority' : 0, 'power' : 65, 'pp' : 10, 'accuracy' : 100, 'description' : "A malicious curse that gets stronger if the foe has a status condition."},
'Hydro Pump' : {'type' : 'Water', 'category' : 'Special', 'priority' : 0, 'power' : 110, 'pp' : 5, 'accuracy' : 80, 'description' : "Blasts water at high pressure to strike the foe."},
'Hyper Voice' : {'type' : 'Normal', 'category' : 'Special', 'priority' : 0, 'power' : 90, 'pp' : 10, 'accuracy' : 100, 'description' : "A loud attack that uses sound waves to injure."},
'Hypnosis' : {'type' : 'Psychic', 'category' : 'Status', 'priority' : 0, 'power' : 0, 'pp' : 20, 'accuracy' : 60, 'description' : "A hypnotizing move that may induce sleep"},
##I
'Ice Beam' : {'type' : 'Ice', 'category' : 'Special', 'priority' : 0, 'power' : 90, 'pp' : 10, 'accuracy' : 100, 'description' : "Blasts the foe with an icy beam that may freeze it."},
'Ice Fang' : {'type' : 'Ice', 'category' : 'Physical', 'priority' : 0, 'power' : 65, 'pp' : 1, 'accuracy' : 95, 'description' : "An icy bite. May freeze foe or cause flinching."},
'Ice Punch' : {'type' : 'Ice', 'category' : 'Physical', 'priority' : 0, 'power' : 75, 'pp' : 15, 'accuracy' : 100, 'description' : "An icy punch that may freeze the foe."},
'Icicle Spear' : {'type' : 'Ice', 'category' : 'Physical', 'priority' : 0, 'power' : 25, 'pp' : 10, 'accuracy' : 90, 'description' : "Throws piercing icicles at the foe 2 to 5 times in a row."},
'Iron Head' : {'type' : 'Steel', 'category' : 'Physical', 'priority' : 0, 'power' : 80, 'pp' : 15, 'accuracy' : 100, 'description' : "Foe is slammed with a steel-hard head. May cause flinching."},
'Iron Tail' : {'type' : 'Steel', 'category' : 'Physical', 'priority' : 0, 'power' : 100, 'pp' : 15, 'accuracy' : 75, 'description' : "An attack with a rock-hard tail. May lower foe's Defense."},
'Iron Defense' : {'type' : 'Steel', 'category' : 'Status', 'priority' : 0, 'power' : 0, 'pp' : 15, 'accuracy' : 900, 'description' : "Hardens the body’s surface to sharply raise Defense."},
##L
'Light Screen' : {'type' : 'Psychic', 'category' : 'Status', 'priority' : 0, 'power' : 0, 'pp' : 30, 'accuracy' : 900, 'description' : "Creates a wall of light that lowers incoming Sp. Attack damage."},
##M
'Mach Punch' : {'type' : 'Fighting', 'category' : 'Physical', 'priority' : 1, 'power' : 40, 'pp' : 30, 'accuracy' : 100, 'description' : "A fast punch that lands first."},
'Magical Leaf' : {'type' : 'Grass', 'category' : 'Special', 'priority' : 0, 'power' : 60, 'pp' : 1, 'accuracy' : 900, 'description' : "User scatters curious leaves that chase the foe. This attack will not miss."},
'Magnet Rise' : {'type' : 'Electric', 'category' : 'Status', 'priority' : 0, 'power' : 0, 'pp' : 10, 'accuracy' : 900, 'description' : "User becomes immune to Ground-type moves until they switch out."},
'Metal Claw' : {'type' : 'Steel', 'category' : 'Physical', 'priority' : 0, 'power' : 50, 'pp' : 35, 'accuracy' : 95, 'description' : "Foe is raked with steel claws. May also raise the user’s Attack stat."},
'Moonblast' : {'type' : 'Fairy', 'category' : 'Special', 'priority' : 0, 'power' : 95, 'pp' : 15, 'accuracy' : 100, 'description' : "User attacks foe with power of the moon. May lower foe’s Sp. Attack."},
##N
'Night Slash' : {'type' : 'Dark', 'category' : 'Physical', 'priority' : 0, 'power' : 70, 'pp' : 15, 'accuracy' : 100, 'description' : "User slashes foe at an opportune time. High critical-hit ratio."},
##O
'Overheat' : {'type' : 'Fire', 'category' : 'Special', 'priority' : 0, 'power' : 130, 'pp' : 5, 'accuracy' : 90, 'description' : "An intense attack that also harshly reduces the user’s Sp. Attack stat."},
##P
'Protect' : {'type' : 'Normal', 'category' : 'Status', 'priority' : 4, 'power' : 0, 'pp' : 10, 'accuracy' : 900, 'description' : "Enables the user to evade all attacks. It may fail if used in succession."},
'Psychic' : {'type' : 'Psychic', 'category' : 'Special', 'priority' : 0, 'power' : 90, 'pp' : 10, 'accuracy' : 100, 'description' : "A powerful psychic attack that may lower foe's Sp. Defense"},
'Punishment' : {'type' : 'Dark', 'category' : 'Physical', 'priority' : 0, 'power' : 60, 'pp' : 5, 'accuracy' : 100, 'description' : "This attack punishes foe's stat increases."},
'Pursuit' : {'type' : 'Dark', 'category' : 'Physical', 'priority' : 0, 'power' : 40, 'pp' : 20, 'accuracy' : 100, 'description' : "Inflicts double damage if used on a foe switching out."},
##R
'Reflect' : {'type' : 'Psychic', 'category' : 'Status', 'priority' : 0, 'power' : 0, 'pp' : 30, 'accuracy' : 900, 'description' : "Creates a wall of light that lowers incoming Attack damage."},
'Roar' : {'type' : 'Normal', 'category' : 'Status', 'priority' : -8, 'power' : 0, 'pp' : 1, 'accuracy' : 900, 'description' : "Scares the foe, forcing the enemy trainer to swap Pokemon at random. Moves last."},
'Rock Blast' : {'type' : 'Rock', 'category' : 'Physical', 'priority' : 0, 'power' : 25, 'pp' : 10, 'accuracy' : 90, 'description' : "Hurls boulders at the foe 2 to 5 times in a row."},
'Rock Slide' : {'type' : 'Rock', 'category' : 'Physical', 'priority' : 0, 'power' : 75, 'pp' : 10, 'accuracy' : 90, 'description' : "Large boulders are hurled. May cause flinching."},
##S
'Scary Face' : {'type' : 'Normal', 'category' : 'Status', 'priority' : 0, 'power' : 0, 'pp' : 10, 'accuracy' : 100, 'description' : "Frightens with a scary face to sharply reduce Speed."},
'Screech' : {'type' : 'Normal', 'category' : 'Status', 'priority' : 0, 'power' : 0, 'pp' : 40, 'accuracy' : 85, 'description' : "Emits a screech to sharply reduce the foe’s Defense."},
'Shadow Ball' : {'type' : 'Ghost', 'category' : 'Special', 'priority' : 0, 'power' : 80, 'pp' : 15, 'accuracy' : 100, 'description' : "A shadowy blob is hurled at the foe. May lower foe's Sp. Defense."},
'Shadow Claw' : {'type' : 'Ghost', 'category' : 'Physical', 'priority' : 0, 'power' : 70, 'pp' : 15, 'accuracy' : 100, 'description' : "User slashes with a sharp claw. Has a high critical-hit ratio."},
'Slash' : {'type' : 'Normal', 'category' : 'Physical', 'priority' : 0, 'power' : 70, 'pp' : 20, 'accuracy' : 100, 'description' : "Foe is slashed with claws, etc. Has a high critical-hit ratio."},
'Sludge Bomb' : {'type' : 'Poison', 'category' : 'Special', 'priority' : 0, 'power' : 90, 'pp' : 10, 'accuracy' : 100, 'description' : "Sludge is hurled to inflict damage. May also poison."},
'Sludge Wave' : {'type' : 'Poison', 'category' : 'Special', 'priority' : 0, 'power' : 95, 'pp' : 10, 'accuracy' : 100, 'description' : "User swamps area with poisonous sludge. May also poison."},
'Solar Beam' : {'type' : 'Grass', 'category' : 'Special', 'priority' : 0, 'power' : 120, 'pp' : 10, 'accuracy' : 100, 'description' : "Absorbs light in one turn, then attacks next turn."},
'Spore' : {'type' : 'Grass', 'category' : 'Status', 'priority' : 0, 'power' : 0, 'pp' : 10, 'accuracy' : 100, 'description' : "Lulls the foe to sleep."},
'Stone Edge' : {'type' : 'Rock', 'category' : 'Physical', 'priority' : 0, 'power' : 100, 'pp' : 5, 'accuracy' : 80, 'description' : "User stabs the foe with stones. High critical-hit ratio."},
'Superpower' : {'type' : 'Fighting', 'category' : 'Physical', 'priority' : 0, 'power' : 120, 'pp' : 5, 'accuracy' : 100, 'description' : "A powerful attack, but it also lowers the user’s Attack and Defense stats."},
'Swords Dance' : {'type' : 'Normal', 'category' : 'Status', 'priority' : 0, 'power' : 0, 'pp' : 20, 'accuracy' : 900, 'description' : "A fighting dance that sharply raises Attack."},
'Synthesis' : {'type' : 'Grass', 'category' : 'Status', 'priority' : 0, 'power' : 0, 'pp' : 5, 'accuracy' : 900, 'description' : "Restores the user’s HP."},
##T
'Tackle' : {'type' : 'Normal', 'category' : 'Physical', 'priority' : 0, 'power' : 40, 'pp' : 35, 'accuracy' : 95, 'description' : "The user rams its body into its opponent."},
'Taunt' : {'type' : 'Dark', 'category' : 'Status', 'priority' : 0, 'power' : 0, 'pp' : 20, 'accuracy' : 100, 'description' : "Taunts the foe into only using attack moves."},
'Thunder' : {'type' : 'Electric', 'category' : 'Special', 'priority' : 0, 'power' : 110, 'pp' : 10, 'accuracy' : 70, 'description' : "A brutal lightning attack that may paralyze foe."},
'Thunderbolt' : {'type' : 'Electric', 'category' : 'Special', 'priority' : 0, 'power' : 90, 'pp' : 15, 'accuracy' : 100, 'description' : "A strong electrical attack that may paralyze the foe."},
'Thunder Fang' : {'type' : 'Electric', 'category' : 'Physical', 'priority' : 0, 'power' : 65, 'pp' : 15, 'accuracy' : 95, 'description' : "An ionizing bite. May paralyze foe or cause flinching."},
'Thunder Punch' : {'type' : 'Electric', 'category' : 'Physical', 'priority' : 0, 'power' : 75, 'pp' : 15, 'accuracy' : 100, 'description' : "An electrified punch that may paralyze the foe."},
'Thunder Wave' : {'type' : 'Electric', 'category' : 'Status', 'priority' : 0, 'power' : 0, 'pp' : 20, 'accuracy' : 900, 'description' : 'A weak jolt of electricity that paralyzes the foe.'},
'Toxic' : {'type' : 'Poison', 'category' : 'Status', 'priority' : 0, 'power' : 0, 'pp' : 10, 'accuracy' : 90, 'description' : 'Poisons the foe with an intensifying toxin.'},
'Trick Room' : {'type' : 'Psychic', 'category' : 'Status', 'priority' : -7, 'power' : 0, 'pp' : 5, 'accuracy' : 900, 'description' : "User creates a bizarre area in which slower Pokémon get to move first for five turns."},
##V
'Venoshock' : {'type' : 'Poison', 'category' : 'Special', 'priority' : 0, 'power' : 65, 'pp' : 10, 'accuracy' : 100, 'description' : "Foe is drenched in a poisonous liquid. Deals double damage if foe poisoned."},
##W
'<Template>' : {'type' : '', 'category' : '', 'priority' : 0, 'power' : 0, 'pp' : 1, 'accuracy' : 0, 'description' : ""},
'Wish' : {'type' : 'Normal', 'category' : 'Status', 'priority' : 0, 'power' : 0, 'pp' : 10, 'accuracy' : 900, 'description' : "A self-healing move that restores restores HP on the next turn."},
'Will-O-Wisp' : {'type' : 'Fire', 'category' : 'Status', 'priority' : 0, 'power' : 0, 'pp' : 15, 'accuracy' : 85, 'description' : "A sinister, bluish white flame is shot at the foe to inflict a burn."},
##X
'X-Scissor' : {'type' : 'Bug', 'category' : 'Physical', 'priority' : 0, 'power' : 80, 'pp' : 15, 'accuracy' : 100, 'description' : "User slashes at foe by crossing its claws, etc. as though they were scissors"},
##Y
'Yawn' : {'type' : 'Normal', 'category' : 'Status', 'priority' : 0, 'power' : 0, 'pp' : 10, 'accuracy' : 900, 'description' : 'A huge yawn lulls the foe into falling asleep on the next turn.'},
##Z
'Zap Cannon' : {'type' : 'Electric', 'category' : 'Special', 'priority' : 0, 'power' : 120, 'pp' : 5, 'accuracy' : 50, 'description' : "Powerful but inaccurate electric blast that causes paralysis."},
'Zen Headbutt' : {'type' : 'Psychic', 'category' : 'Physical', 'priority' : 0, 'power' : 80, 'pp' : 15, 'accuracy' : 90, 'description' : "User focuses its will and rams its foe. May cause flinching."},
}
pkmnInfo = {
'<Template>' : {'stats':(0,0,0,0,0,0),'type1':'','type2':'','moves':[]},
'Charizard' : {'stats' : (45,49,49,65,65,45), 'type1' : 'Grass', 'type2' : 'Poison', 'moves' : ['Roar','Roar','Pursuit','Pursuit']},
##A
'Amoonguss' : {'stats':(114,85,70,85,80,30),'type1':'Grass','type2':'Poison','moves':['Clear Smog','Energy Ball','Giga Drain','Protect','Sludge Bomb','Spore','Synthesis','Toxic','Venoshock']},
##E
'Electivire' : {'stats':(75,123,67,95,85,95),'type1':'Electric','type2':'','moves':['Brick Break', 'Discharge', 'Dual Chop', 'Earthquake', 'Electro Ball', 'Fire Punch', 'Ice Punch', 'Screech', 'Iron Tail', 'Thunderbolt', 'Thunder', 'Thunder Punch']},
##F
'Feraligatr' : {'stats':(85,105,100,79,83,78),'type1':'Water','type2':'','moves':['Aqua Jet', 'Aqua Tail','Chip Away','Crunch','Dragon Dance','Ice Punch','Iron Tail','Metal Claw','Slash','Superpower']},
##G
'Garchomp' : {'stats':(108,130,95,80,85,102),'type1':'Dragon','type2':'Ground','moves':['Aqua Tail', 'Crunch', 'Draco Meteor', 'Dragon Claw', 'Dragon Rush', 'Earthquake', 'Fire Blast', 'Fire Fang', 'Roar', 'Stone Edge', 'Swords Dance','Toxic']},
'Gardevoir' : {'stats':(68,65,65,125,115,80),'type1':'Psychic','type2':'Fairy','moves':['Calm Mind','Energy Ball','Light Screen','Magical Leaf','Moonblast','Protect','Psychic','Reflect','Shadow Ball','Thunderbolt','Trick Room','Wish','Will-O-Wisp']},
'Gengar' : {'stats':(60,60,60,130,75,110),'type1':'Ghost','type2':'Poison','moves':['Dark Pulse','Energy Ball','Hex','Hypnosis','Psychic','Shadow Ball','Sludge Bomb','Sludge Wave','Taunt','Venoshock',]},
##H
'Hydreigon' : {'stats':(92,105,90,125,90,98),'type1':'Dark','type2':'Dragon','moves':['Crunch','Dark Pulse','Draco Meteor','Dragon Pulse','Dragon Rush','Earth Power','Earthquake','Facade','Flamethrower','Flash Cannon','Fire Blast','Hyper Voice','Scary Face','Stone Edge','Thunder Wave','Toxic']},
##I
'Infernape' : {'stats':(76,104,71,104,71,108),'type1':'Fire','type2':'Fighting','moves':['Acrobatics','Aerial Ace','Blaze Kick','Close Combat','Dual Chop','Fake Out','Fire Punch','Gunk Shot','Iron Tail','Mach Punch','Punishment','Taunt','Thunder Punch']},
##K
'Kyurem-B' : {'stats':(125,170,100,120,90,95),'type1':'Dragon','type2':'Ice','moves':['Dragon Claw','Dragon Dance','Freeze Shock','Fusion Bolt','Icicle Spear','Slash','Shadow Claw','Zen Headbutt']},
##L
'Lucario' : {'stats':(70,110,70,115,70,90),'type1':'Fighting','type2':'Steel','moves':['Aura Sphere','Blaze Kick','Bone Rush','Close Combat','Calm Mind','Dark Pulse','Dragon Pulse','Drain Punch','Flash Cannon','Ice Punch','Iron Tail','Metal Claw','Screech','Swords Dance',]},
##M
'Magnezone' : {'stats':(70,70,115,130,90,60),'type1':'Electric','type2':'Steel','moves':['Discharge','Double Team','Flash Cannon','Iron Defense','Light Screen','Magnet Rise','Reflect','Thunder Wave','Zap Cannon']},
##Q
'Quagsire' : {'stats' : (95,85,85,65,65,35),'type1':'Water','type2':'Ground','moves':['Amnesia','Aqua Tail','Earthquake','Facade','Iron Tail','Protect','Toxic','Yawn']},
##R
'Rotom-W' : {'stats':(50,65,107,105,107,86),'type1':'Electric','type2':'Water','moves':['Double Team','Electro Ball','Thunder Wave','Hex','Discharge','Thunder Wave','Protect','Light Screen','Reflect','Dark Pulse','Thunderbolt','Hydro Pump']},
'Rotom-H' : {'stats':(50,65,107,105,107,86),'type1':'Electric','type2':'Fire','moves':['Double Team','Electro Ball','Thunder Wave','Hex','Discharge','Thunder Wave','Protect','Light Screen','Reflect','Dark Pulse','Thunderbolt','Overheat']},
##S
'Scizor' : {'stats':(70,130,100,55,70,65),'type1':'Bug','type2':'Steel','moves':['Aerial Ace','Bullet Punch','Double Team','Fury Cutter','Iron Defense','Metal Claw','Night Slash','Pursuit','Superpower','Swords Dance','X-Scissor']},
##T
'Tyranitar' : {'stats':(100,134,110,95,100,61),'type1':'Rock','type2':'Dark','moves':['Brick Break','Crunch','Earthquake','Fire Fang','Ice Fang','Iron Defense','Protect','Rock Blast','Rock Slide','Screech','Shadow Claw','Stone Edge','Thunder Fang']},
}
natures = [
['Adamant',(1, 1.1, 1, 0.9, 1, 1)]
]
stages = {
'-6' : 2/8,
'-5' : 2/7,
'-4' : 2/6,
'-3' : 2/5,
'-2' : 2/4,
'-1' : 2/3,
'0' : 2/2,
'1' : 3/2,
'2' : 4/2,
'3' : 5/2,
'4' : 6/2,
'5' : 7/2,
'6' : 8/2
}
accStages = {
'-6' : 3/9,
'-5' : 3/8,
'-4' : 3/7,
'-3' : 3/6,
'-2' : 3/5,
'-1' : 3/4,
'0' : 3/3,
'1' : 4/3,
'2' : 5/3,
'3' : 6/3,
'4' : 7/3,
'5' : 8/3,
'6' : 9/3
}
evasStages = {
'6' : 3/9,
'5' : 3/8,
'4' : 3/7,
'3' : 3/6,
'2' : 3/5,
'1' : 3/4,
'0' : 3/3,
'-1' : 4/3,
'-2' : 5/3,
'-3' : 6/3,
'-4' : 7/3,
'-5' : 8/3,
'-6' : 9/3
}
weakness = {
'Bug' : ['Fire','Flying','Rock'],
'Dark' : ['Fighting','Bug','Fairy'],
'Dragon' : ['Dragon','Fairy','Ice'],
'Electric' : ['Ground'],
'Fairy' : ['Steel','Poison'],
'Fighting' : ['Psychic','Flying','Fairy'],
'Fire' : ['Water','Ground','Rock'],
'Flying' : ['Electric','Ice','Rock'],
'Ghost' : ['Ghost','Dark'],
'Grass' : ['Fire','Ice','Poison','Flying','Bug'],
'Ground' : ['Water','Grass','Ice'],
'Ice' : ['Fire','Fighting','Rock','Steel'],
'Normal' : ['Fighting'],
'Poison' : ['Ground','Psychic'],
'Psychic' : ['Bug','Dark','Ghost'],
'Rock' : ['Water','Grass','Fighting','Ground','Steel'],
'Steel' : ['Fire','Ground','Fighting'],
'Water' : ['Electric','Grass'],
'' : []
}
resistance = {
'Bug' : ['Grass','Fighting','Ground'],
'Dark' : ['Ghost','Dark'],
'Dragon' : ['Fire','Water','Grass','Electric'],
'Electric' : ['Electric','Flying'],
'Fairy' : ['Fighting','Bug','Dark'],
'Fighting' : ['Bug','Rock','Dark'],
'Fire' : ['Fire','Grass','Ice','Bug','Steel','Fairy'],
'Flying' : ['Grass','Fighting','Bug'],
'Ghost' : ['Poison','Bug'],
'Grass' : ['Water','Electric','Grass','Ground'],
'Ground' : ['Poison','Rock'],
'Ice' : ['Ice'],
'Normal' : [],
'Poison' : ['Grass','Fighting','Poison','Bug','Fairy'],
'Psychic' : ['Fighting','Psychic'],
'Rock' : ['Normal','Fire','Poison','Flying'],
'Steel' : ['Normal','Grass','Ice','Flying','Psychic','Bug','Rock','Dragon','Steel','Fairy'],
'Water' : ['Fire','Water','Ice','Steel'],
'' : [],
}
immune = {
'Bug' : [],
'Dark' : ['Psychic'],
'Dragon' : [],
'Electric' : [],
'Fairy' : ['Dragon'],
'Fighting' : [],
'Fire' : [],
'Flying' : ['Ground'],
'Ghost' : ['Normal','Fighting'],
'Grass' : [],
'Ground' : ['Electric'],
'Ice' : [],
'Normal' : ['Ghost'],
'Poison' : [],
'Psychic' : [],
'Rock' : [],
'Steel' : ['Poison'],
'Water' : [],
'' : []
}
templateForTypes = {
'Bug' : [],
'Dark' : [],
'Dragon' : [],
'Electric' : [],
'Fairy' : [],
'Fighting' : [],
'Fire' : [],
'Flying' : [],
'Ghost' : [],
'Grass' : [],
'Ground' : [],
'Ice' : [],
'Normal' : [],
'Poison' : [],
'Psychic' : [],
'Rock' : [],
'Steel' : [],
'Water' : [],
}
| [
"noreply@github.com"
] | jsyiek.noreply@github.com |
5b7a3e70a0c8d1536bd827092600871d7d516ba3 | dc722e81e469ac55474550b29c737bfa1fd0e0a8 | /docs/source/conf.py | 275c71b6a1479430dfc170a06cc86edbc7686858 | [
"MIT"
] | permissive | yuzi40277738/lirc | dc84c8c67b0e0d2bcd4abe4105a2ab19b254309e | 4bdb5523f4dd49bb1d59fffd135f858e180552dc | refs/heads/master | 2023-02-05T20:51:00.307481 | 2020-12-27T02:47:41 | 2020-12-27T02:47:41 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,067 | py | # Configuration file for the Sphinx documentation builder.
#
# This file only contains a selection of the most common options. For a full
# list see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html
# -- Path setup --------------------------------------------------------------
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
import os
import sys
sys.path.insert(0, os.path.abspath("../.."))
# -- Project information -----------------------------------------------------
project = "LIRC Python Package"
copyright = "2020, Eugene Triguba"
author = "Eugene Triguba"
# The full version, including alpha/beta/rc tags
release = "1.0.1"
# -- General configuration ---------------------------------------------------
# Add any Sphinx extension module names here, as strings. They can be
# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
# ones.
extensions = [
"sphinx.ext.autodoc",
"sphinx.ext.autosectionlabel",
"sphinx.ext.napoleon",
]
# Add any paths that contain templates here, relative to this directory.
templates_path = ["_templates"]
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
# This pattern also affects html_static_path and html_extra_path.
exclude_patterns = []
# Specify the master doc for read the docs
master_doc = "index"
# -- Options for HTML output -------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
#
html_theme = "sphinx_rtd_theme"
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
# html_static_path = ["_static"]
| [
"eugenetriguba@gmail.com"
] | eugenetriguba@gmail.com |
462fe25ee917403e855b979c1415b1b7ab5b1cf3 | d0a3c667b5ef93ae78589f5e169657b54764b667 | /gender_classifier_ml.py | 90cfc0df58f65cafe4073da0b65070e6f232458a | [] | no_license | ajomadlabs/GenderClassifier | b9aab74a2fcff7da81c8f1e561f3d0a703037b0f | 8cf22b5908c68bbb3bb0b3ca5da3f6475940dbd3 | refs/heads/master | 2021-01-10T23:55:11.853712 | 2016-10-13T09:08:33 | 2016-10-13T09:08:33 | 70,785,619 | 2 | 1 | null | null | null | null | UTF-8 | Python | false | false | 2,974 | py | '''------------------------------------------------------------------
A simple classifier which distinguishes between male and
female based on the features and training the model using
DecisionTreeClassifier model
-------------------------------------------------------------------'''
'''------------------------------------------------------------------
Importing tree classifier from scikit
-------------------------------------------------------------------'''
from sklearn import tree #Tree is classifier which is imported from scikit
'''----------------------------------------------------------------'''
'''-------------------------------------------------------------------
Defining The Dataset
-------------------------------------------------------------------'''
X = [[181, 80, 44], [177, 70, 43], [160, 60, 38], [154, 54, 37], [166, 65, 40], [190, 90, 47], [175, 64, 39], #X denotes the features for distinguishing between male and female
[177, 70, 40], [159, 55, 37], [171, 75, 42], [181, 85, 43]]
Y = ['male', 'male', 'female', 'female', 'male', 'male', 'female', 'female', 'female', 'male', 'male'] #Y denotes the corresponding label
'''-----------------------------------------------------------------'''
'''--------------------------------------------------------------------
Creating the classifier and training the model
---------------------------------------------------------------------'''
classifier = tree.DecisionTreeClassifier() #Creating an empty classifier which is DecisionTreeClassifier
classifier = classifier.fit(X,Y) #Training the model by giving the features and corresponding labels
'''------------------------------------------------------------------'''
'''---------------------------------------------------------------------
Defining the test data set
---------------------------------------------------------------------'''
test_data = ['male'] #Defining the testdata
'''------------------------------------------------------------------'''
'''---------------------------------------------------------------------
Defining the prediction of the system
---------------------------------------------------------------------'''
print(test_data) #Printing the test_data
prediction = classifier.predict([[195,125,43]]) #Assining the prediction for the test data given to the system to a prediciton variable
print(prediction) #Printing the prediction
'''------------------------------------------------------------------'''
'''---------------------------------------------------------------------
Importing accuracy_scroe from scikit
---------------------------------------------------------------------'''
from sklearn.metrics import accuracy_score #Importing the accuracy_score
print(accuracy_score(test_data,prediction)) #Printing the accuracy between the predicition and actual value
'''------------------------------------------------------------------'''
| [
"noreply@github.com"
] | ajomadlabs.noreply@github.com |
d24665a4d86deab509d18d4d06742c08a4b14a27 | b2115ba3d9d920ae5a3507a9bf1d7758cfaa5504 | /utils/optim_weight_ema.py | 22452fbac59865afb83b4cae7650500d5c109235 | [] | no_license | CuthbertCai/LCDA | bcc888ccf0c20e942c2ac7d7e022c66458cd7120 | 23d5b1676b254c73afc3edb2f2dffac235905767 | refs/heads/master | 2023-07-26T19:58:29.997190 | 2021-09-05T16:31:20 | 2021-09-05T16:31:20 | 403,355,744 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,726 | py | from torch.optim import optimizer
class OldWeightEMA(object):
"""
Exponential moving average weight optimizer for mean teacher model
"""
def __init__(self, target_net, source_net, alpha=0.999):
self.target_params = list(target_net.parameters())
self.source_params = list(source_net.parameters())
self.alpha = alpha
for p, src_p in zip(self.target_params, self.source_params):
p.data[:] = src_p.data[:]
def step(self):
one_minus_alpha = 1.0 - self.alpha
for p, src_p in zip(self.target_params, self.source_params):
p.data.mul_(self.alpha)
p.data.add_(src_p.data * one_minus_alpha)
class EMAWeightOptimizer(object):
def __init__(self, target_net, source_net, alpha=0.999):
self.target_net = target_net
self.source_net = source_net
self.ema_alpha = alpha
self.target_params = list(target_net.state_dict().values())
self.source_params = list(source_net.state_dict().values())
for tgt_p, src_p in zip(self.target_params, self.source_params):
tgt_p[:] = src_p[:]
target_keys = set(target_net.state_dict().keys())
source_keys = set(source_net.state_dict().keys())
if target_keys != source_keys:
raise ValueError(
'Source and target networks do not have the same state dict keys; '
'do they have different architectures?')
def step(self):
one_minus_alpha = 1.0 - self.ema_alpha
for tgt_p, src_p in zip(self.target_params, self.source_params):
tgt_p.mul_(self.ema_alpha)
tgt_p.add_(src_p * one_minus_alpha) | [
"caiguanyu1995@outlook.com"
] | caiguanyu1995@outlook.com |
efa5eec4043cf6a5165d5feabc2bf0aef0af8821 | 6fceac1b307fafc376c026e03df0915ac941085a | /bcgdax.py | c45808e0515097909a2aad5886be780e93432ef9 | [] | no_license | berkando/bcgdax | d018081445eb4de573845c8f1f91f0e4b45389e8 | 3eac45d134d34d606760bbfc7519fed08a98130b | refs/heads/master | 2021-04-09T15:59:00.844871 | 2017-06-28T17:09:20 | 2017-06-28T17:09:20 | 95,691,489 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,831 | py | import requests
# Code that is collecting the same data as the following curl command:
# $ curl 'https://api.gdax.com/products/BTC-USD/trades?after=100' | jq
api_url = "https://api.gdax.com"
product = "BTC-USD"
def getLast100Trades(after_trade_id=None):
after = 'after={}'.format(after_trade_id) if after_trade_id else ''
url = '{url}//products/{product}/trades?{options}'.format(url=api_url, product=product, options=after)
r = requests.get(url)
return r.json()
def collect_trades(days=1):
from dateutil.parser import parse
all_trades = getLast100Trades() # type: list
latest_trade = parse(all_trades[0]['time'])
trade_id = all_trades[-1]['trade_id']
trade_time = parse(all_trades[-1]['time'])
while (latest_trade - trade_time).days < days:
print(latest_trade - trade_time)
trades = getLast100Trades(after_trade_id=trade_id)
trade_id = trades[-1]['trade_id']
trade_time = parse(trades[-1]['time'])
all_trades.extend(trades)
return all_trades
import pandas as pd
def store_trades(filepath, data):
with pd.HDFStore(filepath) as store:
df = pd.DataFrame(data, columns=data[0].keys())
df.set_index(['trade_id'])
if '/trades' in store:
# select indices of duplicated rows:
idx = store.select('trades', where="index in df.index", columns=['index']).index
# only those rows, which weren't yet saved:
sub_df = df.query("index not in @idx")
else:
sub_df = df
store.append('trades', sub_df, data_columns=True)
def read_trades(filepath):
store = pd.HDFStore(filepath)
return store.trades if '/trades' in store else None
if __name__ == '__main__':
trades = collect_trades(days=0)
store_trades('mystore.h5', trades)
| [
"berkanerol81@gmail.com"
] | berkanerol81@gmail.com |
842238dcd664ffe3b0b79faa8b6f03c0fd696c00 | cabc429faa830126f7ddae115d4da9fede7419fc | /conection/connec_db.py | 3cc67c67e4f7817addf69aac3e4ef19c14f6069a | [] | no_license | necrocyber/carreras | 88275c8bd61330312bdd872fe5b7acc2d04c40bf | f20e38e5ac01ab89f271df95e89167cf11ecc961 | refs/heads/master | 2020-05-16T00:41:33.552017 | 2019-04-21T23:33:12 | 2019-04-21T23:33:12 | 182,586,282 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 294 | py | import sqlite3
class Conectar():
nombre_bd = "db/sistema.db"
def run_db(self, query, params = ()):
with sqlite3.connect(self.nombre_bd) as conn:
cursor = conn.cursor()
datos = cursor.execute(query, params)
conn.commit()
return datos | [
"amedel.zen@gmail.com"
] | amedel.zen@gmail.com |
a505b9f708a6afdac5f632c2781f93986786a1a4 | 280a11835bfa70f903d74885900600521c79b4e9 | /theory.computation/src/TuringMachine/main.py | 666fc5937dc323cd0afe33c4cac34f0415686a91 | [] | no_license | hamxyy/practice_py | b44ca93e0ea42e3669e601c84d06d3e21e5472fe | 66a0dd05e55ba5ea91f3389e266d5a9c095fa401 | refs/heads/master | 2021-01-10T19:03:32.076182 | 2015-03-27T07:15:30 | 2015-03-27T07:15:30 | 27,380,046 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,411 | py | '''
Created on 26 Mar, 2015
@author: z0037v8z
'''
from src.TuringMachine.TuringMachine import TuringMachineTransition, TuringMachine, TuringMachineState
from src.TuringMachine.Constant import MoveDirection
import re
def transit(curState, nextChar, transitions):
result = transitions[curState.name][nextChar]
return TuringMachineTransition(result[0], result[1], result[2])
def makeTuringMachine(spec):
simpleTranRe = r"(?P<state>\w+),(?P<input>[\w|\s])\-\>(?P<next>\w+),(?P<dir>[L|R])"
writeTransRe = r"(?P<state>\w+),(?P<input>[\w|\s])\-\>(?P<next>\w+),(?P<write>[\w|\s]),(?P<dir>[L|R])"
states = []
acceptState = None
rejectState = None
transitions = {}
for line in spec.splitlines():
if(not line or line == ""):
continue
if(re.match(simpleTranRe, line)):
result = re.match(simpleTranRe, line)
state = TuringMachineState(result.group("state"))
nextState = TuringMachineState(result.group("next"))
nextChar = result.group("input")
direction = MoveDirection.LEFT if result.group("dir") == "L" else MoveDirection.RIGHT
writeChar = ''
elif(re.match(writeTransRe, line)):
result = re.match(writeTransRe, line)
state = TuringMachineState(result.group("state"))
nextState = TuringMachineState(result.group("next"))
nextChar = result.group("input")
direction = MoveDirection.LEFT if result.group("dir") == "L" else MoveDirection.RIGHT
writeChar = result.group("write")
else:
raise
states.append(state)
stateName = state.name
if(stateName not in transitions):
transitions[stateName] = {}
if(stateName == "q_accept"):
acceptState = state
if(stateName == "q_reject"):
rejectState = state
transitions[stateName][nextChar] = [nextState, writeChar, direction]
acceptState = acceptState if acceptState else TuringMachineState("q_accept")
rejectState = rejectState if rejectState else TuringMachineState("q_reject")
transitionFunction = lambda curState, nextChar: transit(curState, nextChar, transitions)
return TuringMachine(states, transitionFunction, states[0], acceptState, rejectState)
tmspec = open("sampletm").read()
tm = makeTuringMachine(tmspec)
print(tm.run("0000")) | [
"hamxyy@Gmail.com"
] | hamxyy@Gmail.com |
3740b278f395768c4a255c2166677022992d93a9 | 85574bab97569bae7368dc4e2d2aa73c73743a9b | /DSPFromGroundUp/Python/016RunningSumV2/main.py | 9bf1bb6d344340923a786a4e595a379f76fda9cf | [] | no_license | saradhimpardha/UdemyDSPFromGroundUpOnARMProcessors | 3c0fcd7272e892f222871dc412fc214851477aea | 576d4a38992533ed0733278d6b4b6444db58706b | refs/heads/main | 2023-05-04T15:45:30.184864 | 2021-05-28T14:40:46 | 2021-05-28T14:40:46 | 458,248,148 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 922 | py | #
# Imports
#
from matplotlib import pyplot as plt
from matplotlib import style
import mysignals as sigs
#
# Global variables
#
#
# Private functions
#
#
def calc_running_sum(sig_src_arr,sig_dest_arr):
for x in range(len(sig_dest_arr)):
sig_dest_arr[x] = 0
for x in range(len(sig_src_arr)):
sig_dest_arr[x] = sig_dest_arr[x-1]+sig_src_arr[x]
#
# main
#
if __name__ == "__main__":
output_signal =[None]*320
calc_running_sum(sigs.InputSignal_1kHz_15kHz,output_signal)
#
style.use('ggplot')
#style.use('dark_background')
f,plt_arr = plt.subplots(2,sharex=True)
f.suptitle("Running Sum")
plt_arr[0].plot(sigs.InputSignal_1kHz_15kHz,color='red')
plt_arr[0].set_title("Input Signal")
plt_arr[1].plot(output_signal,color ='magenta')
plt_arr[1].set_title("Output Signal")
plt.show()
| [
"franco.polo@ii-vi.com"
] | franco.polo@ii-vi.com |
09d731b9e7645f68948b5b29110c343f5d799196 | 0a130a8773fb160fa6ac35744bd2aad2176e4807 | /kehadiran/apps.py | 314276bd98aca9a2996660aae01c1cf13e13620b | [] | no_license | raselstr/Aplikasi-Data-Pegawai | 7a371921efbab703c567804ef4ca85fa29662f9f | 7fe9225f338d6d9c2ba0edb1ec6aff92a4a8f9ea | refs/heads/master | 2023-05-07T14:19:33.322392 | 2021-05-31T09:00:16 | 2021-05-31T09:00:16 | 368,717,130 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 150 | py | from django.apps import AppConfig
class KehadiranConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'kehadiran'
| [
"str.rasel29@gmail.com"
] | str.rasel29@gmail.com |
0c83fce7cbc88cbc6dc44b9f99bcbb1b07ddda13 | 0c56dd0431d4d75eeb82593ae38b49e793cbc6fc | /day24.py | f30d9489e2ab1f2012dff9cfdf7adedee5986f9a | [] | no_license | Brisabrin/Advent-Of-Code- | 47533ac25ceea3a81fc6e1b0aee698c604cfa5aa | 92e75bab0411c24bbe50c4c130cd22d8ff619ede | refs/heads/master | 2023-05-10T09:37:42.636436 | 2021-06-10T06:44:27 | 2021-06-10T06:44:27 | 375,542,432 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 789 | py | arr = [[0 for x in range(100)] for y in range(100)]
# deep copy array
f = open("day24.txt", 'r')
coord = {'e': [0, 2], 'w': [0, -2], 'se': [1, 1], 'nw': [-1, -1],
'sw': [1, -1], 'ne': [-1, 1]}
cx = []
cy = []
for i in coord:
cx.append(coord[i][0])
cy.append(coord[i][1])
for i in f:
i = i[0:len(i) - 1]
st = 50
en = 50
s = ''
for j in i:
if s != '':
s += j
st += coord[s][0]
en += coord[s][1]
s = ''
elif j in 'sn':
s = j
else:
st += coord[j][0]
en += coord[j][1]
arr[st][en] ^= 1
print(arr[st][en])
f.close()
co = 0
for i in range(100):
for j in range(100):
if arr[i][j]:
co += 1
print(co)
| [
"Brisabrin@gmail.com"
] | Brisabrin@gmail.com |
0751238896833b73c9818850c8150c8aff389c4b | f4b74154a7e50a9cfd325b45046b6c86c1682847 | /src/settings.py | ccb98801ea3144dc52ce825ead5c542150f3330b | [] | no_license | toxicOxygen/personal_website- | 826225a979ef0e62aaddf9730d1fd5d533400310 | 1826ef3de43fc4d162a509f48a1f90392ac136e5 | refs/heads/master | 2021-09-23T09:28:51.103637 | 2020-03-30T02:12:58 | 2020-03-30T02:12:58 | 251,178,977 | 0 | 0 | null | 2021-09-22T18:54:41 | 2020-03-30T02:13:38 | HTML | UTF-8 | Python | false | false | 3,619 | py | """
Django settings for src project.
Generated by 'django-admin startproject' using Django 3.0.4.
For more information on this file, see
https://docs.djangoproject.com/en/3.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.0/ref/settings/
"""
import os
# import django_heroku
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '=$%2g7+8uw(qd3##ayde181009u=1$40xpz=aqg4#)5&80oji7'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'widget_tweaks',
'js_projects',
'pages'
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'src.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR,'templates'),],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'src.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.0/howto/static-files/
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR,'static'),]
STATIC_ROOT = os.path.join(BASE_DIR,'staticfiles')
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'gasmillasuarez@gmail.com'
EMAIL_HOST_PASSWORD = 'uksoiwcaeargewci'
EMAIL_PORT = 587
EMAIL_USE_TLS = True
# django_heroku.settings(locals()) | [
"kwakukusi30@outlook.com"
] | kwakukusi30@outlook.com |
27cb43ce03426ae33a2a613a5b551d5332371f3c | 4a995ce459f42c372d548eb397e95a7793b8b965 | /cursoshandler/models.py | fe22f8853dc98344edddb248959e587b5692a3c5 | [] | no_license | astandre/chatbot-system | edb1d1835fe61a2140bad53e7f68ce2bc724018a | 99aab3e1e63a05bd475c5af8733b8c771d5e69f5 | refs/heads/master | 2022-12-12T01:37:13.498987 | 2018-10-13T23:03:03 | 2018-10-13T23:03:03 | 145,641,189 | 0 | 0 | null | 2022-12-08T02:47:10 | 2018-08-22T01:49:28 | Python | UTF-8 | Python | false | false | 2,784 | py | from neomodel import *
from neomodel import install_all_labels, remove_all_labels
# remove_all_labels()
# install_all_labels()
# clear_neo4j_database(db)
# TODO set label and help_text
class Curso(StructuredNode):
uid = UniqueIdProperty()
nombre = StringProperty(required=True, unique_index=True)
cod = StringProperty(unique=True, required=True)
descripcion = StringProperty(required=False)
pre_requisitos = StringProperty(required=False)
edicion = StringProperty(required=False)
oferta = StringProperty(required=False)
tematica = StringProperty(required=False)
fecha_inscripcion = DateProperty(default_now=True)
fecha_inicio = DateProperty(default_now=True)
esfuerzo_estimado = StringProperty(default=0)
duracion = StringProperty(required=False)
link = StringProperty(default="http://opencampus.utpl.edu.ec/")
INSTITUCIONES = {
"U": "UTPL",
"O": "Otro",
}
institucion = StringProperty(choices=INSTITUCIONES, default="U")
archivado = BooleanProperty(default=False)
docente = RelationshipTo('Docente', 'HAS_A_DOCENTE', cardinality=OneOrMore)
competencia = RelationshipTo('Competencia', 'HAS_A_COMPETENCIA', cardinality=OneOrMore)
reto = RelationshipTo('Reto', 'HAS_A_RETO', cardinality=OneOrMore)
contenido = RelationshipTo('Contenido', 'HAS_A_CONTENIDO', cardinality=OneOrMore)
sinonimo = RelationshipTo('Sinonimo', 'HAS_A_SINONIMO', cardinality=OneOrMore)
class Docente(StructuredNode):
uid = UniqueIdProperty()
nombre = StringProperty(unique_index=True, required=True)
N_ACADEMICO = {
"TN": "Nivel Técnico",
"CN": "Tercer Nivel",
"T": "Cuarto Nivel",
}
nivel_academico = StringProperty(default="T", choices=N_ACADEMICO)
email = EmailProperty(required=False)
resumen = StringProperty(required=False)
curso = RelationshipTo('Curso', 'TEACHES', cardinality=OneOrMore)
class Competencia(StructuredNode):
competencia = StringProperty(unique=True, required=True)
curso = RelationshipTo(Curso, 'IS_FROM', cardinality=OneOrMore)
class Reto(StructuredNode):
titulo_reto = StringProperty(unique=True, required=True)
fecha_inicio = DateTimeProperty(default_now=True)
fecha_fin = DateTimeProperty(default_now=True)
descripcion = StringProperty(required=False)
curso = RelationshipTo(Curso, 'IS_FROM', cardinality=OneOrMore)
class Contenido(StructuredNode):
orden = StringProperty(required=True)
contenido = StringProperty(unique=True, required=True)
curso = RelationshipTo(Curso, 'IS_FROM', cardinality=OneOrMore)
class Sinonimo(StructuredNode):
sinonimo = StringProperty(required=True, unique_index=True)
curso = RelationshipTo(Curso, 'IS_FROM', cardinality=OneOrMore)
| [
"andreherrera97@hotmail.com"
] | andreherrera97@hotmail.com |
e5ab5fc2668c6debbdb50f2e0940c152ef82a489 | 31ba81b3a6f61c0ca1f36e80b57a508fcc36e106 | /minimise_functions_gradient_descent_and_normal_equation/gradient_descent.py | 604e48b13a906947269cb3d8c4be082bdbff791c | [
"MIT"
] | permissive | dev-nikhilg/gradientDescentAndNormalEquationImpl | 31e535c398cf33e48c8c08bd879332d64d8e2b8e | 622ae656138e29d3a8143228100d4f0133572529 | refs/heads/master | 2020-08-01T05:42:21.396712 | 2019-09-26T19:54:13 | 2019-09-26T19:54:13 | 210,885,240 | 0 | 0 | null | 2019-09-26T19:54:14 | 2019-09-25T15:58:14 | Python | UTF-8 | Python | false | false | 4,046 | py | import numpy as np
import matplotlib.pyplot as plt
from .minimise_function import MinimiseFunction
class GradientDescent(MinimiseFunction):
def __init__(self, X = None, Y = None):
"""Gradient descent class to minimise a generic function
Attributes:
X (n*m feature matrix) representing the feature matrix of the observations.
n is the number of observations
m is the number of features in an observation
X should be provided without the extra column of 1s
Y (n*1 vector) representing the observed output value of our observations
"""
MinimiseFunction.__init__(self, X, Y)
def minimise(self, theta_vector = None, alpha = 0.5, threshold = 0.05):
""" Method which starts the gradient descent algorithm
Args:
theta_vector : Initial value of theta_vector to use in the algorithm
Return:
theta_vector : theta_value vector corresponding to our best hypothesis
"""
if theta_vector:
self.theta_vector = theta_vector
else:
self.theta_vector = self.default_theta_vector()
num_iterations = 0
prev_cost = float(0)
hypothesis_output_vector = self.calculate_hypothesis_output()
hypothesis_cost = self.calculate_hypothesis_cost(hypothesis_output_vector)
while abs(hypothesis_cost - prev_cost) > threshold:
num_iterations = num_iterations + 1
self.theta_vector = self.calculate_new_theta_vector(hypothesis_output_vector, alpha)
hypothesis_output_vector = self.calculate_hypothesis_output()
prev_cost = hypothesis_cost
hypothesis_cost = self.calculate_hypothesis_cost(hypothesis_output_vector)
#Plot the curve
plt.plot(self.X[:, 1], self.Y, 'ro')
plt.plot(self.X[:, 1], hypothesis_output_vector)
plt.show()
return self.theta_vector
def default_theta_vector(self):
""" Method the generate initial values of theta parameter vector
Args:
None
Return:
Return a vector with all values initialised to 0
"""
return np.zeros((self.num_features + 1, 1))
def calculate_hypothesis_cost(self, hypothesis_output_vector):
""" Method to calculate the output vector of our current hypothesis
which is represented by the theta_vector
Args:
hypothesis_output_vector : vector containing predictions for our input feature matrix X and current theta_vector
Returns:
float : cost of current hypothesis as compared to Y
"""
cost = float(0)
for index in range(self.num_examples):
cost = cost + ((hypothesis_output_vector[index][0] - self.Y[index][0]) ** 2)
return cost
def calculate_new_theta_vector(self, hypothesis_output_vector, alpha):
""" Method to calculate new values for the theta_vector based on current hypothesis
Args:
hypothesis_output_vector : current hypothesis output vector
alpha : learning rate
Returns:
theta_vector : vector containing new values of theta
"""
new_theta_vector = self.theta_vector
for index in range(self.num_features + 1):
diff_term = hypothesis_output_vector - self.Y
diff_term = np.multiply(diff_term, self.X[:,index].reshape(self.num_examples, 1))
derivative_term = 1.0 * alpha * np.sum(diff_term) / self.num_examples
new_theta_vector[index][0] = new_theta_vector[index][0] - derivative_term
return new_theta_vector
| [
"dev.nikhilg@gmail.com"
] | dev.nikhilg@gmail.com |
45da61cb3415eb8e07c8366c7b8f0ed58e3c101e | 982539edb302b6bee5dd9285e9de00ad866b4cfd | /Tongji/Mode/PlatUserConf.py | 0128446c9127bba03b5fb549b02ac0e89e624e1b | [] | no_license | chennqqi/OpenSaaSProj | 2149a2066c607636ce2106801be2cb722cc0934d | 0f861a61d1bd1499599207a70a8e180930d96573 | refs/heads/master | 2020-04-04T16:14:08.943396 | 2017-06-01T06:50:32 | 2017-06-01T06:50:32 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,183 | py | # -*- coding: utf-8 -*-
from datetime import date
from pony.orm import *
def define_user_conf(db):
class Plat_user_conf(db.Entity):
id = PrimaryKey(int, sql_type="int(20)", auto=True)
tm = Optional(date)
ver = Optional(str)
pub = Optional(str)
nameid = Optional(str)
vshow = Optional(str)
vtype = Optional(str)
return Plat_user_conf
if __name__ == "__main__":
a = Database()
define_user_conf(a)
a.bind("mysql", host="outjhkj01.mysql.rds.aliyuncs.com", port=3306, user="jhkj", passwd="jhkj_jhkj", db="saas_meta")
a.generate_mapping(create_tables=True)
b = Database()
define_user_conf(b)
b.bind("mysql", host="outjhkj01.mysql.rds.aliyuncs.com", port=3306, user="jhkj", passwd="jhkj_jhkj", db="guaengdemo")
a.disconnect()
b.disconnect()
b.generate_mapping(create_tables=True)
# db.drop_table("plat_event")
# tester = Plat_event()
# b = Database()
# setDB(b)
# db.bind("mysql", host="outjhkj01.mysql.rds.aliyuncs.com", port=3306, user="jhkj", passwd="jhkj_jhkj", db="guaengdemo")
# db.generate_mapping(create_tables=True)
# tester = Plat_event() | [
"sudazhuang1@163.com"
] | sudazhuang1@163.com |
9bb42345a9b15e3849e5dbb76ebcc0d8071398eb | 280a580421a209f89580830576f2691983f80871 | /model.py | afbdc36b3408b77391c2d4a34bb8037eacc00fb2 | [] | no_license | victoria-lokteva/Kidney-segmentation | cef9c7c851052451e60c9c7faaf760e98c3594ef | 942423b92c06f7af180fdb4994cd86ca35641ff7 | refs/heads/master | 2023-05-30T21:12:33.018546 | 2021-06-21T16:45:13 | 2021-06-21T16:45:13 | 376,620,418 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 617 | py | import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision
import torchvision.transforms as transforms
"""transfer learning with FCN"""
def prepare_model(pretrained=False):
model = torchvision.models.segmentation.fcn_resnet50(pretrained=pretrained)
if pretrained:
frozen_layers = nn.Sequential(*list(model.children()))[:-1]
for parameter in frozen_layers.parameters():
parameter.requires_grad = False
# we have 2 clases: is a glomeruli's pixel or not
model.classifier[4] = nn.Conv2d(512, 2, kernel_size=(1, 1), stride=(1, 1))
return model
| [
"vilokteva@yandex.ru"
] | vilokteva@yandex.ru |
1b6a81dbb379628475b39a6cfdb4ecdad50ae3b0 | 22861512cd989755735f5db923c7347cf1420385 | /dday/migrations/0001_initial.py | 6f7d7e7381c61368a3068d2ddeb0ae03ea799ddf | [] | no_license | kimbaeng/Django | 8d4d83bdf371ae7038501b39eac628e5781e3aa7 | 6cf35a37cd1a0998d77656ef48b33ac3fc5ab9c7 | refs/heads/master | 2020-04-04T13:07:52.883731 | 2018-11-03T04:51:03 | 2018-11-03T04:51:03 | 144,718,915 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,266 | py | # -*- coding: utf-8 -*-
# Generated by Django 1.11.12 on 2018-08-25 13:58
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Post',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=50)),
('text', models.TextField()),
('start', models.DateTimeField(default=django.utils.timezone.now)),
('finish', models.DateTimeField(default=django.utils.timezone.now)),
('created', models.DateTimeField(auto_now_add=True)),
('status', models.CharField(choices=[('army', 'army'), ('navy', 'navy'), ('airforce', 'airforce')], default='army', max_length=10)),
('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
]
| [
"wndma1224@naver.com"
] | wndma1224@naver.com |
9af1d959d8ba0986ca6b5f688cdb2e2894b1540e | 57f67891a1a762d7acb9f51f810d4f890a6d0502 | /paydex_base_sdk/call_builder/strict_send_paths_call_builder.py | 505a3b7a60941eca520e76617c124777395a9ee0 | [] | no_license | fkmike/paydex_sdk_py | 1deaa0d705e031d6849980ec2a3f7c5aab7fdb7b | 4db4d0afd1a02d7e0076090dc4ee5f9341cae13a | refs/heads/master | 2021-04-10T20:35:55.934768 | 2020-03-13T08:20:15 | 2020-03-13T08:20:15 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,523 | py | from typing import Union, List
from ..utils import convert_assets_to_horizon_param
from ..asset import Asset
from ..call_builder.base_call_builder import BaseCallBuilder
from ..client.base_async_client import BaseAsyncClient
from ..client.base_sync_client import BaseSyncClient
class StrictSendPathsCallBuilder(BaseCallBuilder):
"""Creates a new :class:`StrictSendPathsCallBuilder` pointed to server defined by horizon_url.
Do not create this object directly, use :func:`paydex_sdk.server.Server.strict_send_paths`.
The Paydex Network allows payments to be made across assets through path
payments. A strict send path payment specifies a series of assets to route a
payment through, from source asset (the asset debited from the payer) to
destination asset (the asset credited to the payee).
A strict send path search is specified using:
- The source asset
- The source amount
- The destination assets or destination account.
As part of the search, horizon will load a list of assets available to the
source address and will find any payment paths from those source assets to
the desired destination asset. The search's source_amount parameter will be
used to determine if there a given path can satisfy a payment of the desired
amount.
:param horizon_url: Horizon server URL.
:param client: The client instance used to send request.
:param source_asset: The asset to be sent.
:param source_amount: The amount, denominated in the source asset, that any returned path should be able to satisfy.
:param destination: The destination account or the destination assets.
"""
def __init__(
self,
horizon_url: str,
client: Union[BaseAsyncClient, BaseSyncClient],
source_asset: Asset,
source_amount: str,
destination: Union[str, List[Asset]],
) -> None:
super().__init__(horizon_url, client)
self.endpoint: str = "paths/strict-send"
params = {
"source_amount": source_amount,
"source_asset_type": source_asset.type,
"source_asset_code": None
if source_asset.is_native()
else source_asset.code,
"source_asset_issuer": source_asset.issuer,
}
if isinstance(destination, str):
params["destination_account"] = destination
else:
params["destination_assets"] = convert_assets_to_horizon_param(destination)
self._add_query_params(params)
| [
"czhack000@gmail.com"
] | czhack000@gmail.com |
66fcf53b7320cf8fd3ea1e9562b05c890a8c68ae | 68c3c7e8b57f646dff8b17666fdc3cfcffeb26c0 | /nural_network/kr_logistic_regression.py | e6352a7e7d74e35916c495560b9ed12c7e82e245 | [] | no_license | gragragrao/training_deeplearning | dc8e72ca1c9b51bf65c29a0040d355ddaf6f71fa | 849ed12142abc9ff86a2694d436437dde7905fd2 | refs/heads/master | 2021-01-01T17:26:28.803074 | 2017-08-20T02:03:57 | 2017-08-20T02:03:57 | 98,074,671 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 724 | py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from commons.libraries import *
# kr.models.Sequentials: to define the model of layers
model = kr.models.Sequential([
kr.layers.Dense(input_dim=2, units=1),
kr.layers.Activation('sigmoid')
])
# another way
'''
model = kr.models.Sequential()
model.add(kr.layers.Dense(input_dims=2, units=1))
model.add(kr.layers.Activation('sigmoid'))
'''
# create model
model.compile(loss='binary_crossentropy', optimizer=SGD(lr=0.1))
X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
Y = np.array([[0], [1], [1], [1]])
model.fit(X, Y, epochs=200, batch_size=1)
classes = model.predict_classes(X, batch_size=1)
prob = model.predict_proba(X, batch_size=1)
print(classes)
print(prob)
| [
"mathbass.ken531@gmail.com"
] | mathbass.ken531@gmail.com |
208b5d343d8c292713b19ddf713951b904ea7df9 | db52e731e6995ecf1e9bfc5720454d06a136f7de | /server/entity/game.py | 5bd41a83de68030b55960fdaed073ea9d35c86ec | [] | no_license | Deonisii/server.py | 263247b80629874f188222390a4c78cd9f1fd8de | 317afb6ed90093a3bb7b01dc1f4a78ed8e024cf9 | refs/heads/master | 2021-09-12T23:09:20.467101 | 2017-12-05T19:16:59 | 2017-12-05T19:16:59 | 113,549,485 | 0 | 0 | null | 2017-12-08T08:13:37 | 2017-12-08T08:13:37 | null | UTF-8 | Python | false | false | 24,457 | py | """ Game entity.
"""
import math
import random
from threading import Thread, Event, Lock
import game_config
from db.replay import DbReplay
from defs import Result, Action
from entity.event import EventType, Event as GameEvent
from entity.map import Map
from entity.player import Player
from entity.point import Point
from entity.post import PostType, Post
from entity.train import Train
from logger import log
class Game(Thread):
""" game
has:
players - list of players on this game
map - game map
status - [ready, run, finish]
tick_time - current time
max_tick_time - time of game session
name - unique game name
trains - one train per player
"""
# All registered games.
GAMES = {}
def __init__(self, name, map_name=game_config.MAP_NAME, observed=False):
super(Game, self).__init__(name=name)
log(log.INFO, "Create game, name: '{}'".format(self.name))
self.replay = None
self._observed = observed
if not observed:
self.replay = DbReplay()
self._lock = Lock()
self._current_game_id = 0
self._current_tick = 0
self.players = {}
self.map = Map(map_name)
self.name = name
self.trains = {}
self._stop_event = Event()
self._pass_next_tick = False
self._next_train_moves = {}
if not observed:
self._current_game_id = self.replay.add_game(name, map_name=self.map.name)
random.seed()
@staticmethod
def create(name):
""" Returns instance of class Game.
"""
if name in Game.GAMES:
game = Game.GAMES[name]
else:
Game.GAMES[name] = game = Game(name)
return game
def add_player(self, player: Player):
""" Adds player to the game.
"""
if player.idx not in self.players:
with self._lock:
# Use first Town on the map as player's Town:
player_town = self.map.towns[0]
player_home_point = self.map.point[player_town.point_id]
player.set_home(player_home_point, player_town)
self.players[player.idx] = player
# Add trains for the player:
for _ in range(game_config.DEFAULT_TRAINS_COUNT):
# Create Train:
train = Train(idx=len(self.trains) + 1)
# Add Train:
player.add_train(train)
self.map.add_train(train)
self.trains[train.idx] = train
# Put the Train into Town:
self.put_train_into_town(train)
log(log.INFO, "Add new player to the game, player: {}".format(player))
if not self._observed:
Thread.start(self)
def turn(self):
""" Makes next turn.
"""
self._pass_next_tick = True
with self._lock:
self.tick()
if self.replay:
self.replay.add_action(Action.TURN, None, with_commit=False)
def stop(self):
""" Stops ticks.
"""
log(log.INFO, "Game stopped, name: '{}'".format(self.name))
self._stop_event.set()
if self.name in Game.GAMES:
del Game.GAMES[self.name]
if self.replay:
self.replay.commit()
def run(self):
""" Thread's activity.
"""
# Create db connection object for this thread if replay.
replay = DbReplay() if self.replay else None
try:
while not self._stop_event.wait(game_config.TICK_TIME):
with self._lock:
if self._pass_next_tick:
self._pass_next_tick = False
else:
self.tick()
if replay:
replay.add_action(Action.TURN, None, with_commit=False, game_id=self._current_game_id)
if replay:
replay.commit()
finally:
if replay:
replay.close()
def tick(self):
""" Makes game tick. Updates dynamic game entities.
"""
self._current_tick += 1
log(log.INFO, "Game tick, tick number: {}".format(self._current_tick))
self.update_posts_on_tick()
self.update_trains_positions_on_tick()
self.handle_trains_collisions_on_tick()
self.process_trains_points_on_tick()
self.update_towns_on_tick()
self.hijackers_assault_on_tick()
self.parasites_assault_on_tick()
def train_in_point(self, train: Train, point_id: int):
""" Makes all needed actions when Train arrives to Point.
Applies next Train move if it exist, processes Post if exist in the Point.
"""
msg = "Train is in point, train: {}, point: {}".format(train, self.map.point[point_id])
post_id = self.map.point[point_id].post_id
if post_id is not None:
msg += ", post: {!r}".format(self.map.post[post_id].type)
self.train_in_post(train, self.map.post[post_id])
log(log.INFO, msg)
self.apply_next_train_move(train)
def apply_next_train_move(self, train: Train):
""" Applies postponed Train MOVE if it exist.
"""
if train.idx in self._next_train_moves:
next_move = self._next_train_moves[train.idx]
# If next line the same as previous:
if next_move['line_idx'] == train.line_idx:
if train.speed > 0 and train.position == self.map.line[train.line_idx].length:
train.speed = 0
elif train.speed < 0 and train.position == 0:
train.speed = 0
# If next line differs from previous:
else:
train.speed = next_move['speed']
train.line_idx = next_move['line_idx']
if train.speed > 0:
train.position = 0
elif train.speed < 0:
train.position = self.map.line[train.line_idx].length
# The train hasn't got next move data.
else:
train.speed = 0
def move_train(self, train_idx, speed, line_idx):
""" Process action MOVE. Changes path or speed of the Train.
"""
with self._lock:
if train_idx not in self.trains:
return Result.RESOURCE_NOT_FOUND
if train_idx in self._next_train_moves:
del self._next_train_moves[train_idx]
train = self.trains[train_idx]
if line_idx not in self.map.line:
return Result.RESOURCE_NOT_FOUND
# Stop the train:
if speed == 0:
train.speed = speed
# The train is standing:
elif train.speed == 0:
# Continue run the train:
if train.line_idx == line_idx:
train.speed = speed
# The train is standing at the end of the line:
elif self.map.line[train.line_idx].length == train.position:
line_from = self.map.line[train.line_idx]
line_to = self.map.line[line_idx]
if line_from.point[1] in line_to.point:
train.line_idx = line_idx
train.speed = speed
if line_from.point[1] == line_to.point[0]:
train.position = 0
else:
train.position = line_to.length
else:
return Result.PATH_NOT_FOUND
# The train is standing at the beginning of the line:
elif train.position == 0:
line_from = self.map.line[train.line_idx]
line_to = self.map.line[line_idx]
if line_from.point[0] in line_to.point:
train.line_idx = line_idx
train.speed = speed
if line_from.point[0] == line_to.point[0]:
train.position = 0
else:
train.position = line_to.length
else:
return Result.PATH_NOT_FOUND
# The train is standing on the line (between line's points), player have to continue run the train.
else:
return Result.BAD_COMMAND
# The train is moving on the line (between line's points):
elif train.speed != 0 and train.line_idx != line_idx:
switch_line_possible = False
line_from = self.map.line[train.line_idx]
line_to = self.map.line[line_idx]
if train.speed > 0 and speed > 0:
switch_line_possible = (line_from.point[1] == line_to.point[0])
elif train.speed > 0 and speed < 0:
switch_line_possible = (line_from.point[1] == line_to.point[1])
elif train.speed < 0 and speed > 0:
switch_line_possible = (line_from.point[0] == line_to.point[0])
elif train.speed < 0 and speed < 0:
switch_line_possible = (line_from.point[0] == line_to.point[1])
# This train move request is valid and will be applied later:
if switch_line_possible:
self._next_train_moves[train_idx] = {'speed': speed, 'line_idx': line_idx}
# This train move request is invalid:
else:
return Result.PATH_NOT_FOUND
return Result.OKEY
def train_in_post(self, train: Train, post: Post):
""" Makes all needed actions when Train arrives to Post.
Behavior depends on PostType, train can be loaded or unloaded.
"""
if post.type == PostType.TOWN:
# Unload product from train to town:
goods = 0
if train.post_type == PostType.MARKET:
goods = min(train.goods, post.product_capacity - post.product)
post.product += goods
if post.product == post.product_capacity:
post.event.append(GameEvent(EventType.RESOURCE_OVERFLOW, self._current_tick, product=post.product))
elif train.post_type == PostType.STORAGE:
goods = min(train.goods, post.armor_capacity - post.armor)
post.armor += goods
if post.armor == post.armor_capacity:
post.event.append(GameEvent(EventType.RESOURCE_OVERFLOW, self._current_tick, armor=post.armor))
train.goods -= goods
if train.goods == 0:
train.post_type = None
elif post.type == PostType.MARKET:
# Load product from market to train:
if train.post_type is None or train.post_type == post.type:
product = min(post.product, train.goods_capacity - train.goods)
post.product -= product
train.goods += product
train.post_type = post.type
elif post.type == PostType.STORAGE:
# Load armor from storage to train:
if train.post_type is None or train.post_type == post.type:
armor = min(post.armor, train.goods_capacity - train.goods)
post.armor -= armor
train.goods += armor
train.post_type = post.type
def put_train_into_town(self, train: Train, with_unload=True):
# Get Train owner's home point:
player_home_point = self.players[train.player_id].home
# Use first Line connected to the home point as default train's line:
line = [l for l in self.map.line.values() if player_home_point.idx in l.point][0]
train.line_idx = line.idx
# Set Train's position at the Town:
if player_home_point.idx == line.point[0]:
train.position = 0
else:
train.position = line.length
# Stop Train:
train.speed = 0
# Unload the Train:
if with_unload:
train.goods = 0
train.post_type = None
def hijackers_assault_on_tick(self):
""" Makes hijackers assault which decreases quantity of Town's armor and population.
"""
rand_percent = random.randint(1, 100)
if rand_percent <= game_config.HIJACKERS_ASSAULT_PROBABILITY:
hijackers_power = random.randint(*game_config.HIJACKERS_POWER_RANGE)
log(log.INFO, "Hijackers assault happened, hijackers power: {}".format(hijackers_power))
for player in self.players.values():
player.town.population = max(player.town.population - max(hijackers_power - player.town.armor, 0), 0)
player.town.armor = max(player.town.armor - hijackers_power, 0)
player.town.event.append(
GameEvent(EventType.HIJACKERS_ASSAULT, self._current_tick, hijackers_power=hijackers_power)
)
def parasites_assault_on_tick(self):
""" Makes parasites assault which decreases quantity of Town's product.
"""
rand_percent = random.randint(1, 100)
if rand_percent <= game_config.PARASITES_ASSAULT_PROBABILITY:
parasites_power = random.randint(*game_config.PARASITES_POWER_RANGE)
log(log.INFO, "Parasites assault happened, parasites power: {}".format(parasites_power))
for player in self.players.values():
player.town.product = max(player.town.product - parasites_power, 0)
player.town.event.append(
GameEvent(EventType.PARASITES_ASSAULT, self._current_tick, parasites_power=parasites_power)
)
def refugees_arrival(self):
""" Makes refugees arrival which increases quantity of Town's population.
"""
rand_percent = random.randint(1, 100)
if rand_percent <= game_config.REFUGEES_ARRIVAL_PROBABILITY:
refugees_number = random.randint(*game_config.REFUGEES_NUMBER_RANGE)
log(log.INFO, "Refugees arrival happened, refugees number: {}".format(refugees_number))
for player in self.players.values():
player.town.population += min(player.town.population_capacity - player.town.population, refugees_number)
player.town.event.append(
GameEvent(EventType.REFUGEES_ARRIVAL, self._current_tick, refugees_number=refugees_number)
)
if player.town.population == player.town.population_capacity:
player.town.event.append(
GameEvent(EventType.RESOURCE_OVERFLOW, self._current_game_id, population=player.town.population)
)
def update_posts_on_tick(self):
""" Updates all markets and storages.
"""
for market in self.map.markets:
if market.product < market.product_capacity:
market.product = min(market.product + market.replenishment, market.product_capacity)
for storage in self.map.storages:
if storage.armor < storage.armor_capacity:
storage.armor = min(storage.armor + storage.replenishment, storage.armor_capacity)
def update_trains_positions_on_tick(self):
""" Update trains positions.
"""
for train in self.trains.values():
line = self.map.line[train.line_idx]
if train.speed > 0 and train.position < line.length:
train.position += 1
elif train.speed < 0 and train.position > 0:
train.position -= 1
def process_trains_points_on_tick(self):
""" Update trains positions, process points.
"""
for train in self.trains.values():
line = self.map.line[train.line_idx]
if train.position == line.length or train.position == 0:
self.train_in_point(train, line.point[self.get_sign(train.position)])
def update_towns_on_tick(self):
""" Update population and products in Towns.
"""
for player in self.players.values():
if player.town.product < player.town.population:
player.town.population = max(player.town.population - 1, 0)
player.town.product = max(player.town.product - player.town.population, 0)
if player.town.population == 0:
player.town.event.append(GameEvent(EventType.GAME_OVER, self._current_tick, population=0))
if player.town.product == 0:
player.town.event.append(GameEvent(EventType.RESOURCE_LACK, self._current_tick, product=0))
if player.town.armor == 0:
player.town.event.append(GameEvent(EventType.RESOURCE_LACK, self._current_tick, armor=0))
@staticmethod
def get_sign(variable):
""" Returns sign of the variable.
1 if variable > 0
-1 if variable < 0
0 if variable == 0
"""
return variable and (1, -1)[variable < 0]
def is_train_at_point(self, train: Train, point_to_check: Point = None):
""" Returns Point if the Train at some Point now, else returns False.
"""
line = self.map.line[train.line_idx]
if train.position == line.length or train.position == 0:
point_id = line.point[self.get_sign(train.position)]
point = self.map.point[point_id]
if point_to_check is None or point_to_check.idx == point.idx:
return point
return False
def is_train_at_post(self, train: Train, post_to_check: Post = None):
""" Returns Post if the Train at some Post now, else returns False.
"""
point = self.is_train_at_point(train)
if point and point.post_id:
post = self.map.post[point.post_id]
if post_to_check is None or post_to_check.idx == post.idx:
return post
return False
def make_collision(self, train_1: Train, train_2: Train):
""" Makes collision between two trains.
"""
log(log.INFO, "Trains collision happened, trains: [{}, {}]".format(train_1, train_2))
self.put_train_into_town(train_1, with_unload=True)
self.put_train_into_town(train_2, with_unload=True)
train_1.event.append(GameEvent(EventType.TRAIN_COLLISION, self._current_tick, train=train_2.idx))
train_2.event.append(GameEvent(EventType.TRAIN_COLLISION, self._current_tick, train=train_1.idx))
def handle_trains_collisions_on_tick(self):
""" Handles Trains collisions.
"""
collision_pairs = []
trains = list(self.trains.values())
for i, train_1 in enumerate(trains):
# Get Line and Point of train_1:
line_1 = self.map.line[train_1.line_idx]
point_1 = self.is_train_at_point(train_1)
for train_2 in trains[i + 1:]:
# Get Line and Point of train_2:
line_2 = self.map.line[train_2.line_idx]
point_2 = self.is_train_at_point(train_2)
# If train_1 and train_2 at the same Point:
if point_1 and point_2 and point_1.idx == point_2.idx:
post = None if point_1.post_id is None else self.map.post[point_1.post_id]
if post is not None and post.type in (PostType.TOWN, ):
continue
else:
collision_pairs.append((train_1, train_2))
continue
# If train_1 and train_2 on the same Line:
if line_1.idx == line_2.idx:
# If train_1 and train_2 have the same position:
if train_1.position == train_2.position:
collision_pairs.append((train_1, train_2))
continue
# Skip if train_1 or train_2 has been stopped and they have different positions:
if train_1.speed == 0 or train_2.speed == 0:
continue
# Calculating distance between train_1 and train_2 now and after next tick:
train_step_1 = self.get_sign(train_1.speed)
train_step_2 = self.get_sign(train_2.speed)
dist_before_tick = math.fabs(train_1.position - train_2.position)
dist_after_tick = math.fabs(train_1.position + train_step_1 - train_2.position + train_step_2)
# If after next tick train_1 and train_2 cross:
if dist_before_tick == dist_after_tick == 1 and train_step_1 + train_step_2 == 0:
collision_pairs.append((train_1, train_2))
continue
for pair in collision_pairs:
self.make_collision(*pair)
def make_upgrade(self, player: Player, post_ids=(), train_ids=()):
""" Upgrades given Posts and Trains to next level.
"""
with self._lock:
# Get posts from request:
posts = []
for post_id in post_ids:
if post_id not in self.map.post:
return Result.RESOURCE_NOT_FOUND
post = self.map.post[post_id]
if post.type != PostType.TOWN:
return Result.BAD_COMMAND
posts.append(post)
# Get trains from request:
trains = []
for train_id in train_ids:
if train_id not in self.trains:
return Result.RESOURCE_NOT_FOUND
train = self.trains[train_id]
trains.append(train)
# Check existence of next level for each entity:
posts_has_next_lvl = all([p.level + 1 in game_config.TOWN_LEVELS for p in posts])
trains_has_next_lvl = all([t.level + 1 in game_config.TRAIN_LEVELS for t in trains])
if not all([posts_has_next_lvl, trains_has_next_lvl]):
return Result.BAD_COMMAND
# Check armor quantity for upgrade:
armor_to_up_posts = sum([p.next_level_price for p in posts])
armor_to_up_trains = sum([t.next_level_price for t in trains])
if player.town.armor < sum([armor_to_up_posts, armor_to_up_trains]):
return Result.BAD_COMMAND
# Check that trains are in town now:
for train in trains:
if not self.is_train_at_post(train, post_to_check=player.town):
return Result.BAD_COMMAND
# Upgrade entities:
for post in posts:
player.town.armor -= post.next_level_price
post.set_level(post.level + 1)
log(log.INFO, "Post has been upgraded, post: {}".format(post))
for train in trains:
player.town.armor -= train.next_level_price
train.set_level(train.level + 1)
log(log.INFO, "Train has been upgraded, post: {}".format(train))
return Result.OKEY
def get_map_layer(self, layer):
""" Returns specified game map layer.
"""
if layer in (0, 1, 10):
log(log.INFO, "Load game map layer, layer: {}".format(layer))
message = self.map.layer_to_json_str(layer)
self.clean_events()
return Result.OKEY, message
else:
return Result.RESOURCE_NOT_FOUND, None
def clean_events(self):
""" Cleans all existing events.
"""
for train in self.map.train.values():
train.event = []
for post in self.map.post.values():
post.event = []
| [
"d_moroz@wargaming.net"
] | d_moroz@wargaming.net |
505f19ea90ab252de84c926af211dd9c822626ab | f3b97d08bf44ec1ba061f63ecfdeeb1aca21840e | /inference/data.py | 68f25976f1ac1a6f3e40f3eda7f92cbf12cbe208 | [] | no_license | malmaud/damastes | b9c207fd9a6190ee5c3bda6dded92810fcc364fd | 5abfee1f9d3684b9b505b9775a2aca43476d65d8 | refs/heads/master | 2016-09-11T08:50:54.441831 | 2013-09-06T21:44:42 | 2013-09-06T21:44:42 | 12,629,418 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 11,142 | py | """Tools for importing, saving, and loading data.
"""
import cPickle
import locale
import logging
import os
import re
import dateutil
import numpy as np
import pandas
import prior_sampler
import state
import util
def GetDataDir(dataset_name, file_name='state', extension='pickle'):
flags = util.GetFlags(True)
data_dir = flags['data_dir']
return os.path.join(data_dir, 'data', dataset_name, '%s.%s' % (file_name, extension))
def LoadStateFromFile(dataset_name):
file_name = GetDataDir(dataset_name)
with open(file_name) as input_file:
state_for_dataset = cPickle.load(input_file)
return state_for_dataset
def SaveState(state_to_save, dataset_name):
file_path = GetDataDir(dataset_name)
with open(file_path, 'w') as output_file:
cPickle.dump(state_to_save, output_file, 2)
def LoadBotanyDataset():
state = LoadStateFromFile('botany')
prior_sampler.ResampleLatents(state)
state.Plot()
return state
def LoadBotanyDatasetFromRawTables(max_rows=10, max_cols=4,
max_tables=5, matching=True):
with open('output/botany_tables.pickle') as f:
tables = cPickle.load(f)
# The following block applies hacky alterations to data
# for demonstration purposes
t = tables[3]
t['xr'] = t['xo'][1]
t['xo'] = t['xo'][2:53]
t['xs'] = t['xs'][2:53]
t['xr'] = t['xr'][1:]
t['xo'] = [row[1:] for row in t['xo']]
t = tables[0]
t['xo'] = t['xo'][1:]
t['xs'] = t['xs'][1:]
if matching:
for t in tables:
t['xs'] = np.asarray(t['xs'])
t['xr'] = np.asarray(t['xr'])
t['xo'] = np.asarray(t['xo'])
rows = [
[4, 8, 10, 14, 16, 19, 33, 35, 42, 46, 50, 57, 70, 100, 106],
[1, 3, 4, 6, 10, 22, 29, 33, 47, 53, 73],
[0, 2, 8, 9, 10, 11, 12, 13, 15, 17, 20, 22, 27],
[0, 8, 12, 15, 22],
]
for t, n in zip(tables, rows):
t['xs'] = t['xs'][n]
t['xo'] = t['xo'][n, :]
t = tables[0]
t['xr'][2] = 'sun level'
xr = ['Blooming months', 'Pollen color']
xs = ['Aster', 'Marigold', 'Fireweed']
xo = [
['Sep', 'red'],
['Jun', 'orange'],
['Jul', 'blue']]
tables = tables[:4]
tables.append(dict(xr=xr,
xs=xs,
xo=xo,
table_id='http://en.wikipedia.org/wiki/Pollen_source',
x_column='Scientific name'))
t = tables[2]
t['xr'] = ['Timespan']
cells = t['xo'][:, 1]
cells[cells == 'Annual'] = 'yearly'
t['xo'] = t['xo'][:, 0:1]
t['xo'][:, 0] = cells
else:
for t in tables:
t['xo'] = t['xo'][:max_rows]
t['xs'] = t['xs'][:max_rows]
for t in tables:
t['xo'] = [row[:max_cols] for row in t['xo']]
t['xr'] = t['xr'][:max_cols]
# End hacky block
tables = tables[:max_tables]
botany_tables = InitializeStateFromData(tables, prior_sampler.SamplePrior)
zs = [0, 1, 2, 3, 4, 5, 4, 6, 7, 8, 4]
botany_tables.rows.loc[range(len(zs)), 'zs'] = zs
SaveState(botany_tables, 'botany')
botany_tables.Plot()
return botany_tables
def ExtractObsDimensionsFromRawTables(tables):
"""Calculate the dimensionality of a set of tables.
Args:
tables: A set of tables in dictionary-of-strings format.
Returns:
A 2D array of table dimensions, with one row per table. The first column
is the number of rows in each table; the second the number of columns.
"""
dimensions = []
for table in tables:
cells = table['xo']
rows = len(cells)
cols = len(cells[0])
dimensions.append((rows, cols))
return dimensions
# Cells with these symbols are considered to be blank
MISSING_SYM = ['', '*', '-', '.', 'na', 'NA', 'n/a', 'N/A']
# Various regular expressions used for parsing cells in tables
HEIGHT_RE_1 = re.compile(r'(\d+)\'?\s*-\s*(\d+)"?')
HEIGHT_RE_2 = re.compile(r'(\d+)\'\s*(\d+)"')
TIME_RE = re.compile(r'(\d+)\s*:\s*(\d+)')
PERCENT_RE = re.compile(r'([\d\.]+)\s*%')
DOLLAR_RE = re.compile(r'\$([\d\.,]+).*')
DATE_RE = re.compile(r'(\d+)\s*/\s*(\d+)\s*/\s*(\d+)')
HEIGHT_RANGE_RE = re.compile(r'(\d+)\s*(to|-)\s*(\d+)(.*)')
# Categories of data in table cells. Each cell is determined to be one of these:
REF = 0 # A string which refers to an entity.
REAL = 1 # A real-valued numeric literal.
BLANK = 2 # A cell whose value is missing.
PROSE = 3 # A cell with a string of more than 3 words,
# which is assumed to be prose which doesn't refer to an entity.
def PreprocessColumn(cells):
"""Returns a canonical representation of the cells in a column.
Applies heuristics to determine what category of data the majority of cells
in a column are referring to.
For numeric data, the unit of the column is also heuristically determined.
Based on that analysis, converts the cells into a canonical representation of
instances of that data category.
For example, cells which are determined to refer to heights are
converted to a real value in inches, putting all heights on the same scale.
Money, times, and dates are also converted to a canonical form.
Args:
cells: A list of strings appearing in a given column.
Returns:
A tuple with three elements.
The first element is the canonical representation of the cells.
The second element is a binary vector indicating which
cells have the modal category of this column,
as some columns might have mixed types of cells.
The third element is the ID of the modal category of the cells in the column,
which is taken to be the category of the column as a whole.
"""
processed_cells = pandas.pandas.DataFrame([DecideCellType(cell) for cell in cells],
columns=['type', 'value'])
missing = np.flatnonzero(processed_cells.type == BLANK)
processed_cells['value'][missing] = processed_cells['value'][missing - 1]
type_counts = processed_cells.groupby('type').size()
type_counts.sort(ascending=False)
mode_type = type_counts.index[0]
return processed_cells['value'], processed_cells['type'] == mode_type, mode_type
def DecideCellType(cell, extensive_checking=False):
s = cell.strip()
if extensive_checking:
if s in MISSING_SYM:
return BLANK, ''
split = s.split()
if len(split) > 2:
return PROSE, s
try:
return REAL, locale.atof(split[0])
except ValueError:
m = HEIGHT_RE_1.match(s)
if not m:
m = HEIGHT_RE_2.match(s)
if m:
feet = locale.atof(m.group(1))
inches = locale.atof(m.group(2))
return REAL, feet + inches/12.
m = TIME_RE.match(s)
if m:
minute = locale.atof(m.group(1))
second = locale.atof(m.group(2))
return REAL, minute + second/60.
m = PERCENT_RE.match(s)
if m:
return REAL, locale.atof(m.group(1))
m = DOLLAR_RE.match(s)
if m:
return REAL, locale.atof(m.group(1))
try:
date = dateutil.parser.parse(s)
return REF, date.date().ctime()
except ValueError:
return REF, s
except TypeError:
return REF, s
else:
m = HEIGHT_RANGE_RE.match(s)
if m:
height1 = float(m.group(1))
height2 = float(m.group(3))
symbol = m.group(4)
mu = np.mean([height1, height2])
if symbol in ["'"]:
mu *= 12 # feet to inches
return REAL, mu
return REF, s
def IsGoodTable(table):
if not table['xo']:
return False
if not table['xo'][0]:
return False
return True
def PreprocessTable(table):
if not IsGoodTable(table):
return None
new_table = {}
xo = np.array(table['xo'])
xr = np.array(table['xr'])
n_cols = xo.shape[1]
n_rows = xo.shape[0]
new_table['type'] = []
good_cols = np.repeat(False, n_cols)
good_rows = np.repeat(True, n_rows)
for col in range(n_cols):
cells, col_good_rows, col_type = PreprocessColumn(xo[:, col])
good_rows &= col_good_rows
xo[:, col] = cells
if col_type in [REF, REAL]:
new_table['type'].append(col_type)
good_cols[col] = True
if sum(good_cols) == 0 or sum(good_rows) == 0:
return None
xo_filtered = xo[good_rows, :]
xo_filtered = xo_filtered[:, good_cols]
new_table['xo'] = xo_filtered
new_table['xr'] = xr[good_cols]
new_table['xs'] = np.array(table['xs'])[good_rows]
new_table['table_id'] = table['table_id']
new_table['topic_str'] = table['x_column']
return new_table
def InitializeStateFromData(tables, initializer=None):
"""Create a state given a set of raw tables.
Args:
tables: A list of preprocessed tables in dictionary-of-strings format.
Each table is a dictionary d where d['xs'] is a list of strings of the
subject column, d['xr'] is a list of strings of the column headers,
d['xo'] is an array such that ['xo'][row, col] is the string at
the corresponding part in the table, d['table_id'] is the Google
ID of the table (as used by Webtables).
initializer: Function which returns the initial state
of the latent variables. By default, draws from the prior.
"""
locale.setlocale(locale.LC_ALL, 'en_US')
tables = [PreprocessTable(table) for table in tables]
tables = [table for table in tables if table is not None]
table_dimensions = ExtractObsDimensionsFromRawTables(tables)
if initializer is None:
state_for_tables = state.State()
state_for_tables.SetSize(table_dimensions)
else:
state_for_tables = initializer(table_dimensions)
table_id = -1
for table_idx, table_raw in enumerate(tables):
logging.info('Loading table %d', table_idx)
table = table_raw
if not table:
continue
table_id += 1
state_for_tables.raw_tables.append(table_raw)
state_for_tables.tables.loc[table_id, 'url'] = table['table_id']
state_for_tables.tables.loc[table_id, 'topic_str'] = table['topic_str']
logging.info('adding url %r from table %d',
table['table_id'], table_id)
xo = table['xo']
try:
xs = table['xs']
except KeyError:
xs = ['Row %d' % i for i in range(len(xo))]
try:
xr = table['xr']
except KeyError:
xr = ['Col %d' % i for i in range(len(xo[0]))]
types = table['type']
for row_id, row in enumerate(xo):
for col_id, cell in enumerate(row):
if types[col_id] == 0:
token = state_for_tables.entity_tokenizer.TokenForStr(cell)
state_for_tables.cells.loc[(table_id, row_id, col_id), 'xo_ref'] = token
elif types[col_id] == 1:
state_for_tables.cells.loc[(table_id, row_id, col_id), 'xo_real'] = (
locale.atof(cell))
else:
raise util.TablesException(
'Datatype %r not recognized' % types[col_id])
for col_id, col_type in enumerate(types):
state_for_tables.cols.loc[(table_id, col_id), 'type'] = col_type
for row_id, row in enumerate(xs):
token = state_for_tables.entity_tokenizer.TokenForStr(row)
state_for_tables.rows.loc[(table_id, row_id), 'xs'] = token
for col_id, col in enumerate(xr):
token = state_for_tables.col_tokenizer.TokenForStr(col)
state_for_tables.cols.loc[(table_id, col_id), 'xr'] = token
return state_for_tables
| [
"malmaud@gmail.com"
] | malmaud@gmail.com |
94b48fd60ae2a1848557d45847013a281ca0bb72 | 5a52ccea88f90dd4f1acc2819997fce0dd5ffb7d | /alipay/aop/api/domain/VoucherAvailableOutItemInfo.py | d0133f8f8df9195637a3cad5457d1610e907a92c | [
"Apache-2.0"
] | permissive | alipay/alipay-sdk-python-all | 8bd20882852ffeb70a6e929038bf88ff1d1eff1c | 1fad300587c9e7e099747305ba9077d4cd7afde9 | refs/heads/master | 2023-08-27T21:35:01.778771 | 2023-08-23T07:12:26 | 2023-08-23T07:12:26 | 133,338,689 | 247 | 70 | Apache-2.0 | 2023-04-25T04:54:02 | 2018-05-14T09:40:54 | Python | UTF-8 | Python | false | false | 1,440 | py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.constant.ParamConstants import *
class VoucherAvailableOutItemInfo(object):
def __init__(self):
self._item_app_id = None
self._out_item_id = None
@property
def item_app_id(self):
return self._item_app_id
@item_app_id.setter
def item_app_id(self, value):
self._item_app_id = value
@property
def out_item_id(self):
return self._out_item_id
@out_item_id.setter
def out_item_id(self, value):
self._out_item_id = value
def to_alipay_dict(self):
params = dict()
if self.item_app_id:
if hasattr(self.item_app_id, 'to_alipay_dict'):
params['item_app_id'] = self.item_app_id.to_alipay_dict()
else:
params['item_app_id'] = self.item_app_id
if self.out_item_id:
if hasattr(self.out_item_id, 'to_alipay_dict'):
params['out_item_id'] = self.out_item_id.to_alipay_dict()
else:
params['out_item_id'] = self.out_item_id
return params
@staticmethod
def from_alipay_dict(d):
if not d:
return None
o = VoucherAvailableOutItemInfo()
if 'item_app_id' in d:
o.item_app_id = d['item_app_id']
if 'out_item_id' in d:
o.out_item_id = d['out_item_id']
return o
| [
"jishupei.jsp@alibaba-inc.com"
] | jishupei.jsp@alibaba-inc.com |
9569a676ee77f48cc8cfe5fb9c05f98b0261da91 | 88a3cf15afdda6e3f1c7adaf19eb7e5524b699f6 | /main/tests.py | ed956579c53775c3f7b54374e06c24f01a5138d1 | [] | no_license | psiphi-py/DevonduToit | 7f5fbc505deca1734013c152b31351af9ca3c408 | 6b2a0bf3bba42e16b470d7c0639dcb0cff236daa | refs/heads/master | 2020-09-24T17:34:58.624345 | 2019-12-04T10:01:29 | 2019-12-04T10:01:29 | 225,345,647 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 64 | py | from django.test import TestCase
# Test done during production
| [
"dutoitdevon@gmail.com"
] | dutoitdevon@gmail.com |
7028c0470984e7e563d66f370e2a78d0a038e6e0 | 55620949c31207ecd732cc150ebef888b1111c10 | /run_training_pure.py | dfbdf41b5bf1501357e325718cc9089c34ce68d9 | [
"MIT"
] | permissive | likai1993/DRLCacheClusters | 671ec33d2b78bbc7fdce79fa75ac5e5ce85ddaa3 | a26e9685ad378f437aa28d7c592d0ee08c98b787 | refs/heads/master | 2022-12-04T21:52:05.719523 | 2020-08-21T17:47:48 | 2020-08-21T17:47:48 | 285,300,666 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,675 | py | #! /usr/bin/python3
import time
import threading
from cache.Cache import Cache
from agents.CacheAgent import *
from agents.DQNAgent import DQNAgent
from agents.ReflexAgent import *
from cache.DataLoader import DataLoaderPintos
if __name__ == "__main__":
# disk activities
datafile = sys.argv[1]
dataloader = DataLoaderPintos([datafile])
sizes = [10000, 50000, 100000, 200000]
sizes = [7500]
for cache_size in sizes:
print("==================== Cache Size: %d ====================" % cache_size)
# cache
num_of_clusters = 10
env = Cache(dataloader, cache_size
, feature_selection=('Base',)
, reward_params = dict(name='our', alpha=0.5, psi=10, mu=1, beta=0.3)
, allow_skip=False, cluster_num = num_of_clusters
)
# agents
agents = {}
agents['DQN'] = DQNAgent(num_of_clusters, num_of_clusters*6,
learning_rate=0.01,
reward_decay=0.9,
# Epsilon greedy
e_greedy_min=(0.0, 0.1),
e_greedy_max=(0.2, 0.8),
e_greedy_init=(0.1, 0.5),
e_greedy_increment=(0.005, 0.01),
e_greedy_decrement=(0.005, 0.001),
history_size=50,
dynamic_e_greedy_iter=25,
reward_threshold=3,
explore_mentor = 'LRU',
replace_target_iter=100,
memory_size=10000,
batch_size=128,
output_graph=False,
verbose=0
)
for (name, agent) in agents.items():
print("-------------------- %s --------------------" % name)
step = 0
miss_rates = [] # record miss rate for every episode
# determine how many episodes to proceed
# 100 for learning agents, 20 for random agents
# 1 for other agents because their miss rates are invariant
episodes = 10
for episode in range(episodes):
# initial observation
observation = env.reset()
time1=[]
time2=[]
time3=[]
time4=[]
begin=time.time()
while True:
# agent choose action based on observation
tick1 = time.time()
action = agent.choose_action(observation)
tick2 = time.time()
time1.append(tick2-tick1)
# agent take action and get next observation and reward
observation_, reward = env.step(action, training=True, clustering=False)
tick3 = time.time()
time2.append(tick3-tick2)
# break while loop when end of this episode
if env.hasDone():
break
agent.store_transition(observation, action, reward, observation_)
tick4 = time.time()
time3.append(tick4-tick3)
if isinstance(agent, LearnerAgent) and (step > 20) and (step % 5 == 0):
tick5 = time.time()
agent.learn()
tick6 = time.time()
time4.append(tick6-tick5)
# swap observation
observation = observation_
if step % 100 == 0:
mr = env.miss_rate()
print("Agent=%s, Size=%d, Step=%d, Accesses=%d, Misses=%d, MissRate=%f"
% (name, cache_size, step, env.total_count, env.miss_count, mr)
)
step += 1
# report after every episode
end = time.time()
print("Time1=%f, Time2=%f, Time3=%f, Time4=%f, Len1=%d, Len2=%d"%(np.mean(time1), np.mean(time2),np.mean(time3),np.mean(time4), len(time1), len(time4)))
mr = env.miss_rate()
print("Agent=%s, Size=%d, Episode=%d: Accesses=%d, Misses=%d, MissRate=%f, Duration=%f"
% (name, cache_size, episode, env.total_count, env.miss_count, mr, end-begin)
)
miss_rates.append(mr)
miss_rates = np.array(miss_rates)
print("Agent=%s, Size=%d: Mean=%f, Median=%f, Max=%f, Min=%f"
% (name, cache_size, np.mean(miss_rates), np.median(miss_rates), np.max(miss_rates), np.min(miss_rates))
)
# save model
if isinstance(agent, LearnerAgent):
agent.save(cache_size, datafile)
| [
"kai@ykt2020summer.sl.cloud9.ibm.com"
] | kai@ykt2020summer.sl.cloud9.ibm.com |
17aef85561b06fd8af6e1db19176854ad0ed41d8 | 61837b002b2be77cf385e8388c1e480ecd203fd4 | /less_2/less_2_task_9.py | 573cac3e444649c1f653e73622577dd0bb4f13d6 | [] | no_license | laycom/educational_projects | f3a14edc89d1f8e6ccf45e656a4d119b6097d274 | b3e93657e14867d6675b3b160006d63618f8d233 | refs/heads/master | 2022-07-27T04:43:30.891232 | 2020-05-17T11:21:43 | 2020-05-17T11:21:43 | 264,647,318 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 683 | py | # 9. Среди натуральных чисел, которые были введены,
# найти наибольшее по сумме цифр.
# Вывести на экран это число и сумму его цифр.
num = int(input('Введите количество чисел: '))
max = 0
sum_max = 0
for i in range(num):
value = int(input('Введите число: '))
sum = 0
value_work = value
for i in range(len(str(value_work))):
sum += value_work % 10
value_work //= 10
if sum_max < sum:
sum_max = sum
max = value
print(f'В числе {max}, наибольшая сумма цифр: {sum_max} ') | [
"laycom@yandex.ru"
] | laycom@yandex.ru |
bcf1581afef31e7569bc8ef68a094cb8fad143ea | 70f5f279e051360310f95be895320d8fa6cd8d93 | /extraPackages/matplotlib-3.0.2/examples/userdemo/connectionstyle_demo.py | 1ea2bf5fe8fd2ff9ac9da4674adfb762654d93bd | [
"BSD-3-Clause"
] | permissive | spacetime314/python3_ios | 4b16ab3e81c31213b3db1e1eb00230621b0a7dc8 | e149f1bc2e50046c8810f83dae7739a8dea939ee | refs/heads/master | 2020-05-09T20:39:14.980041 | 2019-04-08T15:07:53 | 2019-04-08T15:07:53 | 181,415,024 | 2 | 0 | BSD-3-Clause | 2019-04-15T05:00:14 | 2019-04-15T05:00:12 | null | UTF-8 | Python | false | false | 1,845 | py | """
====================
Connectionstyle Demo
====================
"""
import matplotlib.pyplot as plt
fig, axs = plt.subplots(3, 5, figsize=(8, 4.8))
x1, y1 = 0.3, 0.3
x2, y2 = 0.7, 0.7
def demo_con_style(ax, connectionstyle, label=None):
x1, y1 = 0.3, 0.2
x2, y2 = 0.8, 0.6
ax.plot([x1, x2], [y1, y2], ".")
ax.annotate("",
xy=(x1, y1), xycoords='data',
xytext=(x2, y2), textcoords='data',
arrowprops=dict(arrowstyle="->",
color="0.5",
shrinkA=5, shrinkB=5,
patchA=None,
patchB=None,
connectionstyle=connectionstyle,
),
)
ax.text(.05, .95, connectionstyle.replace(",", ",\n"),
transform=ax.transAxes, ha="left", va="top")
demo_con_style(axs[0, 0], "angle3,angleA=90,angleB=0")
demo_con_style(axs[1, 0], "angle3,angleA=0,angleB=90")
demo_con_style(axs[0, 1], "arc3,rad=0.")
demo_con_style(axs[1, 1], "arc3,rad=0.3")
demo_con_style(axs[2, 1], "arc3,rad=-0.3")
demo_con_style(axs[0, 2], "angle,angleA=-90,angleB=180,rad=0")
demo_con_style(axs[1, 2], "angle,angleA=-90,angleB=180,rad=5")
demo_con_style(axs[2, 2], "angle,angleA=-90,angleB=10,rad=5")
demo_con_style(axs[0, 3], "arc,angleA=-90,angleB=0,armA=30,armB=30,rad=0")
demo_con_style(axs[1, 3], "arc,angleA=-90,angleB=0,armA=30,armB=30,rad=5")
demo_con_style(axs[2, 3], "arc,angleA=-90,angleB=0,armA=0,armB=40,rad=0")
demo_con_style(axs[0, 4], "bar,fraction=0.3")
demo_con_style(axs[1, 4], "bar,fraction=-0.3")
demo_con_style(axs[2, 4], "bar,angle=180,fraction=-0.2")
for ax in axs.flat:
ax.set(xlim=(0, 1), ylim=(0, 1), xticks=[], yticks=[], aspect=1)
fig.tight_layout(pad=0)
plt.show()
| [
"nicolas.holzschuch@inria.fr"
] | nicolas.holzschuch@inria.fr |
44e80e5fb5d75111c212010c632445489d08fe9c | 47e546799f9b5dfd1ff4a1b4dfddf6cd8a300a1b | /sandbox/230808_1928.py | bc66ee2a1c3257d02bce3b9f0a4735298f70563b | [] | no_license | pome-ta/pysta-icons | 1bde692e8ec066f703e23dbb1b4f2a3f4298bc3c | d4275c30bba96244d5752d104f7da07ab9e7a97f | refs/heads/master | 2023-08-19T03:27:39.043944 | 2023-08-12T22:32:20 | 2023-08-12T22:32:20 | 283,628,583 | 3 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,118 | py | from pathlib import Path
import plistlib
from objc_util import ObjCClass, ObjCInstance, uiimage_to_png
import ui
import pdbg
UIImageView = ObjCClass('UIImageView')
UIImage = ObjCClass('UIImage')
UIImageSymbolConfiguration = ObjCClass('UIImageSymbolConfiguration')
#pdbg.state(UIImageSymbolConfiguration)
class SymbolOrder:
"""
現在意味がないclass
"""
def __init__(self):
_path = '/System/Library/CoreServices/CoreGlyphs.bundle/symbol_order.plist'
_symbol_order_bundle = Path(_path)
self.order_list = plistlib.loads(_symbol_order_bundle.read_bytes())
def search_name(self, name: str) -> str:
if name in self.order_list:
return self.order_list[self.order_list.index(name)]
return None
def search_names(self, names: list) -> list[str]:
print(names)
def get_all_items(self):
return self.order_list
def __UIImage_systemName_(_symbol_name: str) -> ObjCClass:
_img = UIImage.systemImageNamed_(_symbol_name)
multicolor = UIImageSymbolConfiguration.configurationPreferringMulticolor()
#_img.configuration().configurationByApplyingConfiguration_(multicolor)
#pdbg.state(_img.configuration())
_img = UIImage.systemImageNamed_withConfiguration_(_symbol_name, multicolor)
return _img
symbol_order = SymbolOrder()
#play_symbol = symbol_order.search_name('checkmark.circle.trianglebadge.exclamationmark')
#play_symbol = symbol_order.search_name('cloud.sun.rain.fill')
#play_symbol = symbol_order.search_name('speaker.wave.2.circle.fill')
play_symbol = symbol_order.search_name('touchid')
#cloud.sun.fill
uiimage_objc = __UIImage_systemName_(play_symbol)
conf = UIImageSymbolConfiguration.defaultConfiguration()
pnt = UIImageSymbolConfiguration.configurationWithPointSize_(100.0)
#conf = UIImageSymbolConfiguration.configurationWithPointSize_(pnt)
#pdbg.state(UIImageSymbolConfiguration)
#pdbg.state(UIImageView.alloc().initWithSize_((120.0, 24.0)))
#pdbg.state(UIImage)
def resize_icon(uiimage):
_size = (220.5, 324.1)
im_view = UIImageView.new() #.alloc().initWithSize_(_size)
#pdbg.state(uiimage)
w = uiimage.size().width
h = uiimage.size().height
im_view.setSize_((w * 10, h * 10))
im_view.setImage_(uiimage)
return im_view
aimim = resize_icon(uiimage_objc)
#pdbg.state(aimim)
class View(ui.View):
def __init__(self, *args, **kwargs):
super().__init__(self, *args, **kwargs)
self.bg_color = 0.5
self.im_view = ui.ImageView()
self.im_view.bg_color = 'maroon'
#self.im_view.size_to_fit()
self.im_view.width = 200
#self.res = uiimage_objc.imageByApplyingSymbolConfiguration(conf)
#self.img_data = uiimage_to_png(self.res)
#pdbg.state(uiimage_objc.size())
#uiimage_objc.size = (50.0, 50.0)
#height
#width
uiimage_objc.size.width = 50.0
#pdbg.state(uiimage_objc)
self.img_data = uiimage_to_png(uiimage_objc)
self.img_png_data = ui.Image.from_data(self.img_data)
self.im_view.image = self.img_png_data
self.im_view.size_to_fit()
self.objc_instance.addSubview_(aimim)
#self.add_subview(self.im_view)
view = View()
view.present()
| [
"53405097+pome-ta@users.noreply.github.com"
] | 53405097+pome-ta@users.noreply.github.com |
80866c0a6acb7ceb64a7a988d56e8332c3a49a86 | 403d1f4acae8edc4ac24bc4830c6f1dababfecaa | /cs255-assignment-10-bitcity/actors/bandMember.py | 1cdb2ec332dc546fb38e07140bb3761e54025f9c | [] | no_license | coleary9/RockBrawl | b5539b01670f5aad3c86f245df346b74bc37bdfa | 1bc7d983481a62ee178ba4774f445e37b16d3b0c | refs/heads/master | 2021-01-01T15:55:36.569836 | 2014-04-09T17:49:00 | 2014-04-09T17:49:00 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 716 | py | # BitCity Studios:
# Cameron O'Leary <coleary9@jhu.edu>
# Steve Griffin <sgriff27@jhu.edu>
# Jeremey Dolinko <j.dolinko@gmail.com>
# Jonathan Rivera <jriver21@jhu.edu>
# Michael Shavit <shavitmichael@gmail.com>
class BandMember(object):
"""Will contain variables for individual band members"""
def __init__(self, spriteSheet, maxSpeed, jumpPower,
width, height, specCoolDown, attackCoolDown, meleeDmg):
self.spriteSheet = spriteSheet
self.maxSpeed = maxSpeed
self.jumpPower = jumpPower
self.width = width
self.height = height
self.specCoolDown = specCoolDown
self.attackCoolDown = attackCoolDown
self.meleeDmg = meleeDmg
| [
"coleary9@jhu.edu"
] | coleary9@jhu.edu |
922b1aa37fcf55384b7269d6d11d73a57d5a7f1c | 9cd71f649500646b9fa4e8f0265576dd18769fc5 | /registration/migrations/0001_initial.py | bbbee447c04148484c2feab3ba9e10434d9440f2 | [
"MIT"
] | permissive | CodePalTutorials/codepal-sample-login | 246a56ba4a5d20fe47132c266669f4fc0ae21672 | f553cc7f7794dd20197b1df336ed7953ac7a62dc | refs/heads/master | 2021-01-19T10:05:05.425150 | 2017-06-10T05:50:22 | 2017-06-10T05:50:22 | 87,824,564 | 2 | 1 | null | null | null | null | UTF-8 | Python | false | false | 1,028 | py | # -*- coding: utf-8 -*-
# Generated by Django 1.10.4 on 2017-04-10 09:08
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='FbAuth',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('facebook_token', models.CharField(max_length=100, verbose_name='Facebook auth token')),
('facebook_id', models.CharField(max_length=20, verbose_name='Facebook id')),
('last_modified', models.DateTimeField(auto_now=True)),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL, unique=True)),
],
),
]
| [
"shivam.mani@outlook.com"
] | shivam.mani@outlook.com |
4ff06ccaf4e5b5ebfd657a82c367f9fa4008cb4c | 434a457ecdde52c3e525143b984d41bbca6605e7 | /meituan/get_cookie.py | a77f53065c7f0f9f403e0712e7ab4f18a2264af4 | [] | no_license | smnra/amap_GDAL | e5765595dcba9b4c666bec3cb590648d66232e56 | c9d7bb37e68779156642b93e72bdbcff8d847303 | refs/heads/master | 2021-07-05T19:50:35.075938 | 2019-03-03T04:40:35 | 2019-03-03T04:40:35 | 129,040,866 | 1 | 1 | null | null | null | null | UTF-8 | Python | false | false | 6,399 | py | #!usr/bin/env python
#-*- coding:utf-8 _*-
"""
@author:Administrator
@file: get_cookie.py
@time: 2018/11/{DAY}
描述:
"""
#!usr/bin/env python
#-*- coding:utf-8 _*-
"""
@author:Administrator
@file: meituan.py
@time: 2018/11/{DAY}
描述:
"""
from selenium import webdriver
import requests
import time
import json
from lxml import etree
# 返回一个ip和对应的cookie,cookie以字符串形式返回。ip需要经过测试
def get_cookie():
mark = 0
while mark == 0:
# 购买的ip获取地址
p_url = 'http://155.94.186.95/get/'
r = requests.get(p_url)
# html = json.loads(r.text)
# a = html['data'][0]['ip']
# b = html['data'][0]['port']
a, b = r.text.split(":")
val = '--proxy-server=http://' + str(a) + ':' + str(b)
val2 = 'https://' + str(a) + ':' + str(b)
p = {'https': val2}
print('获取IP:', p)
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument(val)
driver = webdriver.Chrome(executable_path='C:\Program Files (x86)\Google\Chrome\Application\chromedriver.exe',
chrome_options=chrome_options)
driver.set_page_load_timeout(8) # 设置超时
driver.set_script_timeout(8)
url = 'https://i.meituan.com/shenzhen/' # 美团深圳首页
url2 = 'https://meishi.meituan.com/i/?ci=30&stid_b=1&cevent=imt%2Fhomepage%2Fcategory1%2F1' # 美食页面
try:
driver.get(url)
time.sleep(2.5)
c1 = driver.get_cookies()
now = time.time()
driver.get(url2)
tt = time.time() - now
print(tt)
time.sleep(0.5)
# ip速度测试,打开时间大于3S的NG
if tt < 3:
c = driver.get_cookies()
driver.quit()
print('*******************')
print(len(c1), len(c))
# 判断cookie是否完整,正常的长度应该是18
if len(c) > 17:
mark = 1
# print(c)
x = {}
for line in c:
x[line['name']] = line['value']
# 将cookie合成字符串,以便添加到header中,字符串较长就分了两段处理
co1 = '__mta=' + x['__mta'] + '; client-id=' + x['client-id'] + '; IJSESSIONID=' + x[
'IJSESSIONID'] + '; iuuid=' + x[
'iuuid'] + '; ci=30; cityname=%E6%B7%B1%E5%9C%B3; latlng=; webp=1; _lxsdk_cuid=' + x[
'_lxsdk_cuid'] + '; _lxsdk=' + x['_lxsdk']
co2 = '; __utma=' + x['__utma'] + '; __utmc=' + x['__utmc'] + '; __utmz=' + x[
'__utmz'] + '; __utmb=' + x['__utmb'] + '; i_extend=' + x['i_extend'] + '; uuid=' + x[
'uuid'] + '; _hc.v=' + x['_hc.v'] + '; _lxsdk_s=' + x['_lxsdk_s']
co = co1 + co2
print(co)
return (p, co)
else:
print('缺少Cookie,长度:', len(c))
else:
print('超时')
driver.quit()
time.sleep(3)
except:
driver.quit()
pass
# 解析店铺详情页面,返回店铺信息info和一个标志位mark
# 传入参数u包含url和店铺分类,pc包含cookie和ip,m代表抓取的数量,n表示线程号,ll表示剩余店铺数量,ttt该线程抓取的总时长
def parse(u, pc, m, n, ll, ttt):
mesg = 'Thread:' + str(n) + ' No:' + str(m) + ' Time:' + str(ttt) + ' left:' + str(ll) # 记录当前线程爬取的信息
url = u[0]
cate = u[1]
p = pc[0]
cookie = pc[1]
mark = 0 # 标志位,0表示抓取正常,1,2表示两种异常
head = {'Host': 'meishi.meituan.com',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
'Accept-Encoding': 'gzip, deflate, br',
'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
'Cache-Control': 'max-age=0',
'Connection': 'keep-alive',
'Upgrade - Insecure - Requests': '1',
'Referer': 'https://meishi.meituan.com/i/?ci=30&stid_b=1&cevent=imt%2Fhomepage%2Fcategory1%2F1',
'User-Agent': 'Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.139 Mobile Safari/537.36',
'Cookie': cookie
}
info = [] # 店铺信息存储
try:
r = requests.get(url, headers=head, timeout=3, proxies=p)
r.encoding = 'utf-8'
html = etree.HTML(r.text)
datas = html.xpath('body/script[@crossorigin="anonymous"]')
for data in datas:
try:
strs = data.text[:16]
if strs == 'window._appState':
result = data.text[19:-1]
result = json.loads(result)
name = result['poiInfo']['name']
addr = result['poiInfo']['addr']
phone = result['poiInfo']['phone']
aveprice = result['poiInfo']['avgPrice']
opentime = result['poiInfo']['openInfo']
opentime = opentime.replace('\n', ' ')
avescore = result['poiInfo']['avgScore']
marknum = result['poiInfo']['MarkNumbers']
lng = result['poiInfo']['lng']
lat = result['poiInfo']['lat']
info = [name, cate, addr, phone, aveprice, opentime, avescore, marknum, lng, lat]
print(url)
print(mesg, name, cate, addr, phone, aveprice, opentime, avescore, marknum, lng, lat)
except:
pass
except Exception as e:
print('Error Thread:', n) # 打印出异常的线程号
print(e)
s = str(e)[-22:-6]
if s == '由于目标计算机积极拒绝,无法连接':
print('由于目标计算机积极拒绝,无法连接', n)
mark=1 #1类错误,需要更换ip
else:
mark=2 #2类错误,再抓取一次
return(mark,info) #返回标志位和店铺信息
| [
"smnra@163.com"
] | smnra@163.com |
eed7bf77c295f4cad446fba4bf255ebf8f992e38 | dc24849073c0a8a70e110a7daa394de593abb29d | /AnimalMultiCategory/ByTensorflow/Stage_2 Species_classification/Species_make_anno.py | 5b62f983c49529ef1cffce609e7e8d0a1f2c022d | [] | no_license | zlwmzh/CV | 29a089521b80750e4ef1cc432b1f7fee13393961 | 80c77e80b88e9c06b94df80bae3119e78e3321aa | refs/heads/master | 2020-09-13T18:49:53.548414 | 2020-01-06T08:15:44 | 2020-01-06T08:15:44 | 222,866,920 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,975 | py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2019/11/21 20:10
# @Author : Micky
# @Desc : 读取保存的二进制文件,转换为Species_train_features.npy、Species_train_label.npy、
# Species_val_features.npy、Species_val_label.npy
# @File : Species_make_anno.py
# @Software: PyCharm
import os
import numpy as np
import cv2 as cv
import Config
import Helper
def convert_fearture_label(data_path, feature_save_name, label_save_name):
"""
二进制文件转换为Classes_train_features.npy、Classes_train_label.npy、Classes_val_features.npy、Classes_val_label.npy
:param data_path: 二进制文件路径
:param feature_save_name: 特征保存文件名
:param label_save_name: 目标保存文件名
"""
# 获取训练数据
path = data_path
if not os.path.exists(path):
raise FileNotFoundError('未找到对应的文件!!!!,请先运行Dataset目录下的Image_rename.py和Image_covert_data.py')
dlist = np.load(path)
# 对数据进行打乱操作
ids = np.asarray(range(len(dlist)))
np.random.shuffle(ids)
dlist = dlist[ids]
features = []
labels = []
for image in dlist:
image_path = image['path']
label = image['species']
# 读取图片
image_vector = cv.imread(image_path)
# 统一图像的大小 224*224
try:
image_vector = cv.resize(image_vector, (Config.width, Config.height))
# 转换为RGB
image_vector = cv.cvtColor(image_vector, cv.COLOR_BGR2RGB)
# 进行数据增广操作
# 1. 水平镜像
image_vector_h_filp = cv.flip(image_vector, 1)
# 2. 垂直镜像
# image_vector_v_filp = cv.flip(image_vector, 0)
# 进行标准化
image_vector = Helper.normalize(image_vector)
image_vector_h_filp = Helper.normalize(image_vector_h_filp)
# image_vector_v_filp = Helper.normalize(image_vector_v_filp)
features.append(image_vector)
features.append(image_vector_h_filp)
# features.append(image_vector_v_filp)
labels.append(label)
labels.append(label)
# labels.append(label)
except Exception as e:
print('{}读取出现错误:{},未加入到训练集中!!!'.format(image_path, e))
np.save(feature_save_name, features)
np.save(label_save_name, labels)
# 本地二进制文件存储的路径
DATA_DIR = '../../Datas'
FILE_PHASE = ['train_annotation.npy', 'val_annotation.npy']
DATA_PATH1 = os.path.join(DATA_DIR, FILE_PHASE[0])
DATA_PATH2 = os.path.join(DATA_DIR, FILE_PHASE[1])
print('开始生成进行图片向量转换...')
convert_fearture_label(DATA_PATH1, 'Species_train_features.npy', 'Species_train_labels.npy')
convert_fearture_label(DATA_PATH2, 'Species_val_features.npy', 'Species_val_labels.npy')
print('图片向量转换完成!!!!') | [
"1354319679@qq.com"
] | 1354319679@qq.com |
435d0a985383ca2931fdadfb7b0636239050db62 | f6d4667702c5755db15775ab356ada8228cc3588 | /code/scrape/scrape player_team.py | c4f78581db9a3a702ba5f68c83cca71380f7f76f | [] | no_license | Jackie-LJQ/Multiplayer-Game-analyse | 89f12c41e5b59d3eada66c51388e5f32abc5ba1f | 6a5ff44832508c4c5dc073fbe773bff6ba25cc6c | refs/heads/master | 2022-11-09T20:29:56.625045 | 2020-06-24T03:15:17 | 2020-06-24T03:15:17 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,517 | py | # -*- coding: utf-8 -*-
"""
Created on Sat Mar 7 17:05:32 2020
@author: liu
"""
import requests
from bs4 import BeautifulSoup
import numpy as np
import csv
import time
#
url = 'https://www.hltv.org/stats/players?minMapCount=1000'
result = requests.get(url)
src = result.content
player_page = BeautifulSoup(src, 'html')
players = player_page.find_all("td", {"class": "playerCol"})
player_url = []
for player in players:
part_text = player.find("a")["href"]
text = 'https://www.hltv.org'+ part_text[:15]+'matches/'+part_text[15:]
print(text)
player_url.append(text)
with open('player_url.csv', 'w', newline = '') as csvfile:
writer = csv.writer(csvfile)
for row in player_url:
writer.writerow(row)
def extract_id(part_url, key_word = 'teams'):
if key_word in part_url:
init = part_url.find(key_word) + len(key_word) + 1
else:
print(part_url)
id = '0'
for i in range(init, 1000):
if part_url[i].isdigit():
id += part_url[i]
else:
break
id = id[1:]
return id
#
date_save = ['match_date']
team_save = ['team_id']
player_save = ['player_id']
#
#
for i in range(len(player_url)):
url = player_url[i]
player_id = extract_id(url, key_word = 'matches')
result = requests.get(url)
src = result.content
player_page = BeautifulSoup(src,'html')
matches = player_page.find_all("tr" , {"class":"group-1 first"})
for t in matches:
date = t.find("div", {"class":"time"}).text
date_save.append(date)
team_text = t.find("div", {"class":"gtSmartphone-only"}).find("a")["href"]
team_save.append(extract_id(team_text,key_word = 'teams'))
player_save.append(player_id)
# print(date)
# print(team_text)
matches = player_page.find_all("tr" , {"class":"group-2 first"})
for t in matches:
date = t.find("div", {"class":"time"}).text
date_save.append(date)
team_text = t.find("div", {"class":"gtSmartphone-only"}).find("a")["href"]
team_save.append(extract_id(team_text))
player_save.append(player_id)
# print(date)
# print(player_id)
print(url)
time.sleep(0.5)
date_save = np.array(date_save)
player_save = np.array(player_save)
team_save = np.array(team_save)
save = np.vstack((player_save, team_save, date_save))
save = save.T
with open('player_team.csv', 'w', newline = '') as csvfile:
writer = csv.writer(csvfile)
for row in save:
writer.writerow(row) | [
"liujiaqier@gmail.com"
] | liujiaqier@gmail.com |
ccf1f6930272418887ed692351ffac0a6331e193 | e03aca3988cb718bf268e66a9fbbf3721836e8ba | /receive_sms.py | 8f2513289a92cae9a1677472dac7cc3042e88e30 | [] | no_license | yoannawei/huskies | 8f48066b121140e02c25bdff4238110ca9874ae8 | 02ee05ae5f5626e76a6cacc4f95c43ccd06ddfb6 | refs/heads/master | 2021-05-15T11:21:11.474764 | 2017-10-28T00:22:58 | 2017-10-28T00:22:58 | 108,317,708 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 358 | py | import os
from flask import Flask, request, redirect
from twilio.twiml.messaging_response import MessagingResponse
app = Flask(__name__)
@app.route("/sms", methods = ['GET', 'POST'])
def sms_reply():
response = MessagingResponse()
response.message("Huskies for days!")
return str(response)
if __name__ == "__main__":
app.run(debug=True)
| [
"yoanna.yw@gmail.com"
] | yoanna.yw@gmail.com |
7d2794d66c8af7463d80b6feb07f0a139da4daf6 | 6f54ce52f08806075f0445e7dd206baae96ebdca | /IssueTracker/controllers/default.py | f6f0ad38bfb5a2d5fa0f37f28e66d7e27f9f3aff | [
"BSD-3-Clause"
] | permissive | ykanggit/web2py-appliances | a93d318a214aa5b3e5cd6b47b642f2c12addba46 | 5ca7a04d5403f04aad9e90e99e10dbc05a08a50a | refs/heads/master | 2022-05-06T08:55:11.089350 | 2022-04-14T19:25:02 | 2022-04-14T19:25:02 | 49,680,074 | 0 | 0 | null | 2016-01-14T22:41:45 | 2016-01-14T22:41:45 | null | UTF-8 | Python | false | false | 7,707 | py | # -*- coding: utf-8 -*-
def index():
return dict(message=T('Hello World'))
def projects():
#COLUMNS=('project.name','project.author','project.repo','project.license')
FIELDS=(db.project.id,db.project.name,db.project.created_by,db.project.manager,db.project.phase,db.project.repo)
LINKS=[lambda row: A('Subprojects',_href=URL('projects',args=row.id)),
lambda row: A('Issues',_href=URL('issues',args=row.id)),
lambda row: A('Team',_href=URL('teams',args=row.id)) ]
def check(row): return ((row.created_by == auth.user_id)|(row.manager == auth.user_id))
if (request.args(0)):
query = (db.project.super_project==request.args(0))
#name = 'The subprojects of: '+ str(db(db.project.id==request.args(0)).select(db.project.name)).lstrip('project.name ')
else:
query = db.project
#name = 'Project directory'
grid = SQLFORM.grid(query,editable=check,deletable=check,
fields = FIELDS,links=LINKS)
return dict(grid=grid)#name=name)
def teams():
def check(row):
return (row.team_lead == auth.user_id)
if (request.args(0)):
query = (db.team.assigned_projects==request.args(0))
else:
query = db.team
grid=SQLFORM.grid(query,editable=check,deletable=check)
return dict(grid=grid)
@auth.requires_membership('manager')
def roles():
manager_id = db(db.auth_group.role == 'manager').select().first().id
query = (db.auth_membership.group_id == manager_id)
grid = SQLFORM.grid(query,editable=False)
return dict(grid=grid)
def issues():
project = db.project(request.args(0)) or redirect(URL('projects'))
status = request.args(2)
#TODO- show issues of the subprojects
query = (db.issue.project == project.id)&(db.issue.is_last==True)
if (request.args(1)):
query = query&(db.issue.super_issue==request.args(1))
if not status or status=='Open':
query = query&(db.issue.status.belongs(['New','Assigned','Accepted','Started']))
elif status=='Closed':
query = query&(db.issue.status.belongs(
['Fixed','Verified','Invalid','Duplicate','WontFix','Done']))
elif status!='All':
query = query&(db.issue.status==status)
"""comment"""
from gluon.utils import web2py_uuid
db.issue.project.default = project.id
db.issue.uuid.default = web2py_uuid()
db.issue.is_last.default = True
db.issue.owner.default = project.created_by.email
db.issue.description.default = DESCRIPTION
db.issue.labels.represent = lambda v,r: ', '.join(v or [])
if not auth.user or not (
auth.user.id == project.created_by or \
auth.user.email in (project.members_email or [])):
db.issue.owner.writable = False
db.issue.status.writable = False
FIELDS=(db.issue.id,db.issue.uuid,db.issue.status,db.issue.summary,db.issue.created_on,db.issue.author,db.issue.labels,)
LINKS=[lambda row: A('Details',_href=URL('issue',args=row.uuid)),
lambda row: A('Sub-issues',_href=URL('issues',args=[project.id,row.id])),
lambda row2:A('Assignment',_href=URL('assign',args=row2.id)),
lambda row3: A('Escalate', _href=URL('escalate',args=row3.id))]
grid = SQLFORM.grid(query, fields = FIELDS,links=LINKS,
details=False,editable=False,
deletable=project.created_on==auth.user_id,
create=auth.user_id,args=[project.id],
oncreate=lambda form:do_mail([db.issue(form.vars.id)]))
return dict(grid=grid, project=project)
def issue():
last = db(db.issue.uuid==request.args(0))\
(db.issue.is_last==True).select().first()
project = db.project(last.project) or redirect(URL('projects'))
if auth.user:
db.issue.status.default = last.status
db.issue.summary.default = last.summary
db.issue.project.default = last.project
db.issue.uuid.default = last.uuid
db.issue.is_last.default = True
db.issue.owner.default = last.owner
db.issue.labels.default = last.labels
if not (auth.user.id == project.created_by or \
auth.user.email == last.owner or \
auth.user.email in (project.members_email or [])):
db.issue.owner.default = project.created_by
db.issue.owner.writable = False
db.issue.status.writable = False
form = SQLFORM(db.issue)
if form.process().accepted:
last.update_record(is_last=False)
else:
form = DIV('login to comment')
items = db(db.issue.uuid==request.args(0)).select(
orderby=db.issue.created_on)
if isinstance(form,FORM) and form.accepted: do_mail(items)
return dict(project=project,form=form,items=items,last=last)
@auth.requires_membership('manager')
def assign():
from datetime import datetime
if (request.args(0)):
query= (db.issue_assignment.issue==request.args(0))
else:
query=(db.issue_assignment)
FIELDS=(db.issue_assignment.issue,db.issue_assignment.assigned_by,\
db.issue_assignment.assigned_to,db.issue_assignment.assigned_date)
db.issue_assignment.assigned_by.default='%(first_name)s %(last_name)s' % auth.user
db.issue_assignment.assigned_by.writable=False
db.issue_assignment.assigned_date.default=datetime.now()
db.issue_assignment.assigned_date.writable=False
grid=SQLFORM.grid(query)
return dict(grid=grid)
@auth.requires_membership('manager')
def escalate():
issueID=request.args(0)
reference_project= db(db.issue.id==issueID).select().first()
super_proj = db(db.project.id==reference_project.project).select(db.project.super_project).first()
query = (db.issue.id==issueID)
if super_proj.super_project == None:
message = "Already a top level project"
else:
db(query).update(project=super_proj.super_project)
message= "The issue has been escalated"
session.flash = message
redirect(URL('projects'))
return dict()
def user():
"""
exposes:
http://..../[app]/default/user/login
http://..../[app]/default/user/logout
http://..../[app]/default/user/register
http://..../[app]/default/user/profile
http://..../[app]/default/user/retrieve_password
http://..../[app]/default/user/change_password
use @auth.requires_login()
@auth.requires_membership('group name')
@auth.requires_permission('read','table name',record_id)
to decorate functions that need access control
"""
return dict(form=auth())
def download():
"""
allows downloading of uploaded files
http://..../[app]/default/download/[filename]
"""
return response.download(request,db)
def call():
"""
exposes services. for example:
http://..../[app]/default/call/jsonrpc
decorate with @services.jsonrpc the functions to expose
supports xml, json, xmlrpc, jsonrpc, amfrpc, rss, csv
"""
return service()
@auth.requires_signature()
def data():
"""
http://..../[app]/default/data/tables
http://..../[app]/default/data/create/[table]
http://..../[app]/default/data/read/[table]/[id]
http://..../[app]/default/data/update/[table]/[id]
http://..../[app]/default/data/delete/[table]/[id]
http://..../[app]/default/data/select/[table]
http://..../[app]/default/data/search/[table]
but URLs bust be signed, i.e. linked with
A('table',_href=URL('data/tables',user_signature=True))
or with the signed load operator
LOAD('default','data.load',args='tables',ajax=True,user_signature=True)
"""
return dict(form=crud())
| [
"massimodipierro@Massimos-MacBook-Air.local"
] | massimodipierro@Massimos-MacBook-Air.local |
5e4b4c366569875ba481b3c8ffc8b575ea8e8d40 | 7885b4718e82a1c2b7ff38803702f365a5c67d14 | /gameboard.py | c22daca759ea37f1c98d914a0187391cbd92ad5c | [] | no_license | Hatchie-47/Piskvorkator | 104090104ae31fd22ad31eddfe984b5f32fc9266 | 125ab0f714764ab953d84d7f1b02446ee725b7ea | refs/heads/main | 2023-02-16T09:35:01.986185 | 2021-01-11T09:39:15 | 2021-01-11T09:39:15 | 326,442,430 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 8,136 | py | # -*- coding: utf-8 -*-
"""
Created on Mon Dec 28 20:07:45 2020
@author: Hatch
"""
import numpy as np
import math as m
import random as r
import time as t
import logging
from sty import fg, rs
class Player():
def __init__(self):
self.dp = 1.1
self.dpt = -0.5
self.st = 0.05
def set_parameters(self,dp,dpt,st):
self.dp = dp
self.dpt = dpt
self.st= st
class Gameboard():
def __init__(self,size,debug,logger):
self.size = size
self.board = np.zeros((3,size[0],size[1]))
#self.score_connected = (20,30,40,50,0,50,40,30,20)
#self.score_space = (0,0,0,0,0,1,1.0001,1.0002,1.0003,1.0004)
self.score_connected = (2.6,3.4,4.2,5,0,5,4.2,3.4,2.6)
self.score_space = (0,0,0,0,0,1,1.1,1.2,1.3,1.4)
self.free_space_bonus = (1,1.5,2)
self.winner = 0
self.completed = False
self.debug = debug
self.players = [Player(),Player()]
self.get_digits_vectorized = np.vectorize(self.get_digits)
self.logger = logger
for i in range(size[0]):
for j in range(size[1]):
self.calc_potential((i,j),True)
def place_symbol(self,player,coordinates):
if self.completed:
custom_print('Symbol not placed, game is already concluded! Winner is player {}.'.format(int(self.winner)),9)
return 0, None
self.board[0,coordinates[0],coordinates[1]] = player
if self.debug>0:custom_print('Player {} placed symbol on coordinates {}.'.format(int(player), coordinates),10)
self.logger.debug('gb.place_symbol({},{})'.format(int(player), coordinates))
self.calc_potential(coordinates, False)
for x in range(1,5):
if (coordinates[0]+x < self.size[0]): self.calc_potential((coordinates[0]+x,coordinates[1]), False)
if (coordinates[0]+x < self.size[0]) and (coordinates[1]+x < self.size[1]): self.calc_potential((coordinates[0]+x,coordinates[1]+x), False)
if (coordinates[0]+x < self.size[0]) and (coordinates[1]-x >= 0): self.calc_potential((coordinates[0]+x,coordinates[1]-x), False)
if (coordinates[1]+x < self.size[1]): self.calc_potential((coordinates[0],coordinates[1]+x), False)
if (coordinates[1]-x >= 0): self.calc_potential((coordinates[0],coordinates[1]-x), False)
if (coordinates[0]-x >= 0): self.calc_potential((coordinates[0]-x,coordinates[1]), False)
if (coordinates[0]-x >= 0) and (coordinates[1]+x < self.size[1]): self.calc_potential((coordinates[0]-x,coordinates[1]+x), False)
if (coordinates[0]-x >= 0) and (coordinates[1]-x >= 0): self.calc_potential((coordinates[0]-x,coordinates[1]-x), False)
for axis in range(4):
line = self.get_line(coordinates,axis)
self.check_winner(line)
if self.completed:
custom_print('Game concluded! Winner is player {}, congratulations!'.format(int(self.winner)),9)
return 2, self.winner
if not 0 in self.board[0,:,:]:
self.completed = True
custom_print('The game board is full and noone won... it\'s a tie!',9)
return 3, None
return 1, None
def get_line(self,coordinates,axis):
freezei = True if axis==2 else False
freezej = True if axis==0 else False
i = coordinates[0] - (-4 if axis==3 else 0 if freezei else 4)
j = coordinates[1] - (0 if freezej else 4)
line = []
for x in range(9):
if x==4:
line.append(8)
else:
line.append(9 if (i < 0) or (i > self.size[0]-1) or (j < 0) or (j > self.size[1]-1) else self.board[0,i,j])
i += -1 if axis==3 else 1 if not freezei else 0
j += 1 if not freezej else 0
return np.array(line)
def check_winner(self,line):
prev = 0
cnt = 0
for x in line:
if x==prev and x!=0:
cnt += 1
if cnt==5:
self.winner = x
self.completed = True
else:
cnt = 1
prev = x
def line_potential(self,line,player):
opponent = 1 if player==2 else 2
line[line==9] = opponent # 9 = beyond boundary
line[line==8] = player # 8 = the coordinate
try:
first = line.tolist()[3::-1].index(opponent)
except ValueError:
first = 4
try:
last = line.tolist()[5:].index(opponent)
except ValueError:
last = 4
left = 4 - 1 - first
right = 5 + last
line[0:left+1] = opponent
line[right:9] = opponent
line_connected = line.copy()
line_space = line.copy()
line_space[line_space==0] = player
line_space[line_space==opponent] = 0
line_space[line_space==player] = 1
line_connected[line_connected==opponent] = 0
line_connected[line_connected==player] = 1
line_score = self.score_connected*line_connected
first_my = line_connected.tolist().index(1)
last_my = 8-line_connected.tolist()[::-1].index(1)
free_space = line_space[max(0,first_my-1)] + line_space[min(8,last_my+1)]
surewin = False
sw_line = 0
for sw in line_connected:
sw_line += sw
sw_line *= sw
if sw_line==5 or (sw_line==4 and free_space==2): surewin = True
return np.prod(line_score[line_score!=0])*self.score_space[int(sum(line_space))]*self.free_space_bonus[int(free_space)]*(10 if surewin else 1)
def calc_potential(self,coordinates,init):
potential = 0
if self.board[0,coordinates[0],coordinates[1]] != 0:
self.board[1,coordinates[0],coordinates[1]] = -999
self.board[2,coordinates[0],coordinates[1]] = -999
return
potential += 1/(abs(((self.size[0]-1)/2)-coordinates[0])+0.1)
potential += 1/(abs(((self.size[1]-1)/2)-coordinates[1])+0.1)
potential1 = potential
potential2 = potential
for axis in range(4):
line = self.get_line(coordinates,axis)
potential1 += self.line_potential(line.copy(),1)
potential2 += self.line_potential(line.copy(),2)
self.board[1,coordinates[0],coordinates[1]] = potential1
self.board[2,coordinates[0],coordinates[1]] = potential2
def get_play(self,player):
if player==1:
priority_matrix = self.board[1,:,:]+(self.board[2,:,:]*np.maximum(np.full(self.size,self.players[player-1].dp)+(self.get_digits_vectorized(self.board[2,:,:])*self.players[player-1].dpt),np.full(self.size,0.75)))
else:
priority_matrix = self.board[2,:,:]+(self.board[1,:,:]*np.maximum(np.full(self.size,self.players[player-1].dp)+(self.get_digits_vectorized(self.board[1,:,:])*self.players[player-1].dpt),np.full(self.size,0.75)))
maxv = np.max(priority_matrix)
minv = maxv*(1-self.players[player-1].st)
p = 0
maxp = 0
winner = 0
possibilities = np.nonzero(priority_matrix >= minv)
for coordinate in zip(possibilities[0],possibilities[1]):
if self.debug==2: custom_print('Player {} is considering coordinates {} with value {}...'.format(player,coordinate,priority_matrix[coordinate]),11)
p = (priority_matrix[coordinate] - minv) * r.random()
if p>maxp:
maxp = p
winner = coordinate
return winner
def get_digits(self,x):
return len(str(int(x)))
def set_player(self,player,dp,dpt,st):
self.players[player-1].set_parameters(dp,dpt,st)
def custom_print(message,color):
print(fg(color)+t.strftime("%Y-%m-%d %H:%M:%S", t.localtime())+' - '+message+fg.rs)
| [
"72996300+Hatchie-47@users.noreply.github.com"
] | 72996300+Hatchie-47@users.noreply.github.com |
94b4bd1f79eeb391f61424e5ec4cb5eccb063e31 | 0a3a82529b0246e6b4662010653dc7c6afebac14 | /frij/admin.py | 1c1adbb92bfedd577a90adc1bc62101e53688c25 | [] | no_license | nlicitra/Frij | 193077fef2fb9f85effe201ce29c93c785fa3a4f | d53ef2114531c8b623039aea61bf4cd9cffa9415 | refs/heads/master | 2016-09-06T03:28:53.595339 | 2015-02-04T02:13:58 | 2015-02-04T02:13:58 | 26,084,154 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 327 | py | from django.contrib import admin
from frij.models import UtilityType, UtilityCharge, UtilityChargePeriod
# Register your models here.
#admin.site.register(House)
#admin.site.register(Tenant)
#admin.site.register(Room)
admin.site.register(UtilityType)
admin.site.register(UtilityCharge)
admin.site.register(UtilityChargePeriod) | [
"nickerous@gmail.com"
] | nickerous@gmail.com |
52327f791bad53af1e5f123f7f1b3f296bffe0bb | dc940e2aa628eff693af36584cfad935990ebe7d | /v3.1.0/tool/SaveBookInfoToMySqlTool.py | c32721874dd569c804662a6f57f96fbcb50f3b77 | [] | no_license | 520wsl/getXs8Novels | 865572ea488e0bf3d4e21664eb576237b6dd18be | ecf6d0bc5dfdbe4b5c3e8a9aac313bf7abce614b | refs/heads/master | 2020-04-18T00:59:56.777416 | 2019-02-15T08:52:11 | 2019-02-15T08:52:11 | 167,101,111 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,620 | py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
__title__ = '书籍数据存储工具类'
__author__ = 'Mad Dragon'
__mtime__ = '2019/1/24'
# 我不懂什么叫年少轻狂,只知道胜者为王
┏┓ ┏┓
┏┛┻━━━┛┻┓
┃ ☃ ┃
┃ ┳┛ ┗┳ ┃
┃ ┻ ┃
┗━┓ ┏━┛
┃ ┗━━━┓
┃ 神兽保佑 ┣┓
┃ 永无BUG! ┏┛
┗┓┓┏━┳┓┏┛
┃┫┫ ┃┫┫
┗┻┛ ┗┻┛
"""
import time
import moment
from tool.GetBookInfoTool import GetBookInfoTool
from public.DataTool import DataTool
from public.Logger import Logger
from public.MySqlTool import MySqlTool
class SaveBookInfoToMySqlToo():
def __init__(self, second, logger, getBookInfoToo, mySql, dataToo):
self.b_second = second
self.m_saveText = "INSERT INTO `links` (`url`,article) VALUES (%s, %s) ON DUPLICATE KEY UPDATE article = VALUES (article), nex = nex+1"
self.getBookInfoToo = getBookInfoToo
self.dataToo = dataToo
self.mySql = mySql
self.logger = logger
def saveText(self, link):
time.sleep(self.b_second)
content = self.getBookInfoToo.getTxtInfo(link)
if len(content) <= 0: return False
self.logger.debug('书籍 [ %s ] 文章存储' % (link))
return self.mySql.batchAdd(sql=self.m_saveText, data_info=[(link, content)])
def saveCatalog(self,bookId):
jsonData = self.getBookInfoToo.getCatalogInfo(bookId=bookId)
self.logger.debug(jsonData)
if __name__ == '__main__':
b_title = 'GetBookInfoToo'
b_second = 1
b_timeStr = moment.now().format('YYYY-MM-DD-HH-mm-ss')
dataToo = DataTool(logName=b_title, second=b_second, timeStr=b_timeStr)
logger = Logger(logname=dataToo.initLogName(), loglevel=1, logger=b_title).getlog()
mySql = MySqlTool(logName=dataToo.initLogName())
getBookInfoToo = GetBookInfoTool(second=b_second, dataToo=dataToo, logger=logger)
saveBookInfoToMySqlToo = SaveBookInfoToMySqlToo(second=b_second, logger=logger,
getBookInfoToo=getBookInfoToo,
mySql=mySql, dataToo=dataToo)
| [
"395548460@qq.com"
] | 395548460@qq.com |
2e4d4ad192fac1e61c9f8874b8b0b4a41791f5d5 | 487ce91881032c1de16e35ed8bc187d6034205f7 | /codes/CodeJamCrawler/16_0_4/Areseye/D_a.py | e133bb845631ab5660737f81985ed9f3e3c0f065 | [] | no_license | DaHuO/Supergraph | 9cd26d8c5a081803015d93cf5f2674009e92ef7e | c88059dc66297af577ad2b8afa4e0ac0ad622915 | refs/heads/master | 2021-06-14T16:07:52.405091 | 2016-08-21T13:39:13 | 2016-08-21T13:39:13 | 49,829,508 | 2 | 0 | null | 2021-03-19T21:55:46 | 2016-01-17T18:23:00 | Python | UTF-8 | Python | false | false | 585 | py | #encoding:utf8
import os
import pdb
def solve(K,C,S):
ret = [1,]
gap = K**(C-1)
cur = 1
for i in range(0,K-1):
cur += gap
ret.append(cur)
return ret;
if __name__ == '__main__':
with open('d.in','r') as fin:
for ind,line in enumerate(fin):
if ind is 0:
T = int(line)
else:
strnum = line.split(' ')
param = map(int,strnum)
res = solve(*param)
resstr = map(str,res)
print 'Case #{}: {}'.format(ind,' '.join(resstr))
| [
"[dhuo@tcd.ie]"
] | [dhuo@tcd.ie] |
81bd4caef7d8d902fd1c66113d9584c3b9b8700c | d65ffba497a7ad48438f267f07de32baba841d47 | /entry/others/partition_ds_vgg16.py | b488cc5c61d751641c90ffe6237260168bb95ee6 | [] | no_license | itsmystyle/StableReprLearning | acb34a4bb23d20ec0ac5f3a44231cd1eb56de4d8 | 2169c7c24ae83f98a87a1335af3cab97204cc92b | refs/heads/main | 2023-06-06T23:12:26.522721 | 2021-06-20T15:00:31 | 2021-06-20T15:00:31 | 376,572,515 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 18,281 | py | #!/usr/bin/env python
# coding: utf-8
from __future__ import print_function
import pickle, sys, time, copy
import random
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
import torch.utils.data as Data
import torchvision
import torchvision.models as models
from tqdm.auto import tqdm
from torch.autograd import Variable
from torch.utils.data import Dataset
from torchvision import datasets, transforms
# from thundersvm import SVC
from sklearn.svm import SVC
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier
from lightgbm import LGBMClassifier
args = {}
kwargs = {}
emb_size = 256
es_thd = int(sys.argv[2])
n = int(sys.argv[1])
trans_dicts = [
{0: 0, 1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6, 7: 7, 8: 8, 9: 9},
{0: 0, 1: 0, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1, 7: 1, 8: 0, 9: 0},
{0: 0, 1: 1, 2: 0, 3: 1, 4: 1, 5: 1, 6: 1, 7: 1, 8: 2, 9: 1},
]
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print("using", device)
args["batch_size"] = 128
args["epochs"] = 200
args["lr"] = 1e-3
args["seed"] = 4896
random.seed(args["seed"])
torch.manual_seed(args["seed"])
transform_train = transforms.Compose(
[
transforms.ToPILImage(),
transforms.RandomCrop(32, padding=4),
transforms.RandomHorizontalFlip(),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
]
)
transform_test = transforms.Compose(
[
transforms.ToPILImage(),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
]
)
class CIFAR10_6(Dataset):
def __init__(self, train):
self.train = train
data = datasets.CIFAR10("data", train=train, transform=None)
self.dataset = data.data
self.labels = data.targets
_dataset = []
_labels = []
self.label_map = {0: 0, 1: 1, 5: 2, 6: 3, 7: 4, 8: 5}
for d, l in zip(self.dataset, self.labels):
if l not in [2, 3, 4, 9]:
_dataset.append(d)
_labels.append(l)
self.dataset = _dataset
self.labels = _labels
if self.train:
self.transform = transform_train
else:
self.transform = transform_test
def __len__(self):
return len(self.dataset)
def __getitem__(self, index):
return (
self.transform(self.dataset[index]),
torch.tensor(self.label_map[self.labels[index]], dtype=torch.long),
)
class CIFAR10_4(Dataset):
def __init__(self, train):
self.train = train
data = datasets.CIFAR10("data", train=train, transform=None)
self.dataset = data.data
self.labels = data.targets
_dataset = []
_labels = []
self.label_map = {2: 0, 3: 1, 4: 2, 9: 3}
for d, l in zip(self.dataset, self.labels):
if l in [2, 3, 4, 9]:
_dataset.append(d)
_labels.append(l)
self.dataset = _dataset
self.labels = _labels
if self.train:
self.transform = transform_train
else:
self.transform = transform_test
def __len__(self):
return len(self.dataset)
def __getitem__(self, index):
return (
self.transform(self.dataset[index]),
torch.tensor(self.label_map[self.labels[index]], dtype=torch.long),
)
def imsave(img, path):
torchvision.utils.save_image(img.cpu(), path)
def get_cifar10():
upstream_train_loader = torch.utils.data.DataLoader(
CIFAR10_6(train=True), batch_size=args["batch_size"], num_workers=4, shuffle=True, **kwargs,
)
upstream_test_loader = torch.utils.data.DataLoader(
CIFAR10_6(train=False),
batch_size=args["batch_size"] * 2,
num_workers=4,
shuffle=False,
**kwargs,
)
downstream_train_loader = torch.utils.data.DataLoader(
CIFAR10_4(train=True), batch_size=args["batch_size"], num_workers=4, shuffle=True, **kwargs,
)
downstream_test_loader = torch.utils.data.DataLoader(
CIFAR10_4(train=False),
batch_size=args["batch_size"] * 2,
num_workers=4,
shuffle=False,
**kwargs,
)
return (
upstream_train_loader,
upstream_test_loader,
downstream_train_loader,
downstream_test_loader,
)
class VGG16(nn.Module):
def __init__(self, emb_size, n_classes=10):
super(VGG16, self).__init__()
self.dim = emb_size
self.n_classes = n_classes
backbone = models.vgg16_bn(pretrained=False)
self.encoder = nn.Sequential(*(list(backbone.children())[:-2]))
self.fc1 = nn.Linear(512, self.dim)
self.cls = nn.Linear(self.dim, self.n_classes)
def forward(self, x, return_embs=False):
z = self.extract_emb(x)
x = self.classify(z)
if return_embs:
return x, z
return x
def extract_emb(self, x):
x = self.encoder(x)
x = self.fc1(x.view(x.size(0), -1))
return x
def classify(self, x):
x = self.cls(x)
return x
# linear
class LNet(nn.Module):
def __init__(self, emb_size, out_size):
super(LNet, self).__init__()
self.cls = nn.Linear(emb_size, out_size)
def forward(self, x):
return self.cls(x)
# MLP
class FC(nn.Module):
def __init__(self, in_size, out_size):
super(FC, self).__init__()
self.linear = nn.Linear(in_size, out_size)
self.relu = nn.ReLU(inplace=True)
def forward(self, x):
return self.relu(self.linear(x))
class MLP(nn.Module):
def __init__(self, in_size, mid_size, out_size):
super(MLP, self).__init__()
self.fc = FC(in_size, mid_size)
self.cls = nn.Linear(mid_size, out_size)
def forward(self, x):
return self.cls(self.fc(x))
def train(epoch, model, optimizer, train_loader):
print("Epoch:", epoch)
model.train()
criterion = nn.CrossEntropyLoss()
trange = enumerate(train_loader)
for batch_idx, (data, target) in trange:
data, target = data.to(device), target.to(device)
data, target = Variable(data), Variable(target)
optimizer.zero_grad()
output = model(data)
loss = criterion(output, target)
loss.backward()
optimizer.step()
def test(model, task_id, test_loader):
model.eval()
with torch.no_grad():
correct = 0
for data, target in test_loader:
data, target = (
data.to(device),
torch.LongTensor([trans_dicts[task_id][t.item()] for t in target]).to(device),
)
data, target = Variable(data), Variable(target)
output = model(data)
pred = output.data.max(1, keepdim=True)[1].view(-1)
pred = torch.LongTensor([trans_dicts[task_id][p.item()] for p in pred]).to(device)
correct += sum((pred == target).tolist())
print("Accuracy:", correct / len(test_loader.dataset))
return correct
def test2(model, test_loader):
model.eval()
with torch.no_grad():
correct = 0
for data, target in test_loader:
data, target = data.to(device), target.to(device)
data, target = Variable(data), Variable(target)
output = model(data)
pred = output.data.max(1, keepdim=True)[1].view(-1)
correct += sum((pred == target).tolist())
print("Accuracy:", correct / len(test_loader.dataset))
return correct
def extract_embedding(model, data_loader):
ret = {"embedding": [], "target": []}
model.eval()
with torch.no_grad():
for data, target in data_loader:
data = Variable(data.to(device))
output = model.extract_emb(data)
ret["embedding"] += output.tolist()
ret["target"] += target.view(-1).tolist()
return ret
model_module = VGG16
scores = np.array([[[0.0 for _ in range(8)] for _ in range(n)] for _ in range(2)])
for i in range(n):
print("round:", i)
t0 = time.time()
# train first model
print("train first model")
(
upstream_train_loader,
upstream_test_loader,
downstream_train_loader,
downstream_test_loader,
) = get_cifar10()
model1 = model_module(emb_size, n_classes=6).to(device)
optimizer1 = optim.Adam(model1.parameters(), lr=args["lr"], weight_decay=5e-4)
lr_scheduler = optim.lr_scheduler.ReduceLROnPlateau(
optimizer1, factor=0.3, patience=3, verbose=True
)
patience = es_thd
best_acc = 0
best_model = None
for epoch in range(1, args["epochs"] + 1):
train(epoch, model1, optimizer1, upstream_train_loader)
correct = test2(model1, upstream_test_loader)
lr_scheduler.step(-1 * correct / len(upstream_test_loader.dataset))
if correct / len(upstream_test_loader.dataset) > best_acc:
patience = es_thd
best_acc = correct / len(upstream_test_loader.dataset)
best_model = model_module(emb_size, n_classes=6)
best_model.load_state_dict(copy.deepcopy(model1.state_dict()))
else:
patience -= 1
if patience <= 0:
print("Early stopping!")
break
# restore best model
model1 = model_module(emb_size, n_classes=6)
model1.load_state_dict(copy.deepcopy(best_model.state_dict()))
model1.to(device)
print(model1.cls)
scores[0][i][0] = test2(model1, upstream_test_loader) / len(upstream_test_loader.dataset)
# save data for other CLSs
print("extract embedding")
emb_train = extract_embedding(model1, downstream_train_loader)
emb_test = extract_embedding(model1, downstream_test_loader)
data = {
"train_x": np.array(emb_train["embedding"]),
"train_y": np.array(emb_train["target"]),
"test_x": np.array(emb_test["embedding"]),
"test_y": np.array(emb_test["target"]),
}
# train CLSs
print("train CLSs")
model_ls = []
model_mlps = []
cls_lsvms = []
cls_svms = []
cls_dts = []
cls_rfs = []
cls_lgbs = []
lr = 1e-3
epochs = 50
# training & testing data
train_x, train_y = (
torch.FloatTensor(data["train_x"]),
torch.LongTensor(data["train_y"]),
)
test_x, test_y = (
torch.FloatTensor(data["test_x"]),
torch.LongTensor(data["test_y"]),
)
train_loader = torch.utils.data.DataLoader(
Data.TensorDataset(train_x, train_y),
batch_size=args["batch_size"],
num_workers=4,
shuffle=True,
**kwargs,
)
test_loader = torch.utils.data.DataLoader(
Data.TensorDataset(test_x, test_y),
batch_size=args["batch_size"] * 2,
num_workers=4,
shuffle=False,
**kwargs,
)
# linear
model_l = LNet(emb_size, 4).to(device)
optimizer = optim.Adam(model_l.parameters(), lr=lr)
patience = es_thd
best_acc = 0
best_model = None
for epoch in range(1, epochs + 1):
train(epoch, model_l, optimizer, train_loader)
correct = test2(model_l, test_loader)
if correct / len(test_loader.dataset) > best_acc:
patience = es_thd
best_acc = correct / len(test_loader.dataset)
best_model = LNet(emb_size, 4)
best_model.load_state_dict(copy.deepcopy(model_l.state_dict()))
else:
patience -= 1
if patience <= 0:
break
# restore best model
model_l = LNet(emb_size, 4)
model_l.load_state_dict(copy.deepcopy(best_model.state_dict()))
model_l.to(device)
scores[0][i][1] = correct / len(test_loader.dataset)
model_ls.append(model_l)
print(model_ls[0].cls)
# MLP
model_mlp = MLP(emb_size, (emb_size + 4) // 2, 4).to(device)
optimizer = optim.Adam(model_mlp.parameters(), lr=lr)
patience = es_thd
best_acc = 0
best_model = None
for epoch in range(1, epochs + 1):
train(epoch, model_mlp, optimizer, train_loader)
correct = test2(model_mlp, test_loader)
if correct / len(test_loader.dataset) > best_acc:
patience = es_thd
best_acc = correct / len(test_loader.dataset)
best_model = MLP(emb_size, (emb_size + 4) // 2, 4)
best_model.load_state_dict(copy.deepcopy(model_mlp.state_dict()))
else:
patience -= 1
if patience <= 0:
break
# restore best model
model_mlp = MLP(emb_size, (emb_size + 4) // 2, 4)
model_mlp.load_state_dict(copy.deepcopy(best_model.state_dict()))
model_mlp.to(device)
scores[0][i][2] = correct / len(test_loader.dataset)
model_mlps.append(model_mlp)
print(model_mlps[0].cls)
# linear svm
cls_lsvm = SVC(kernel="linear", random_state=args["seed"])
cls_lsvm.fit(data["train_x"], data["train_y"])
_valid_score = cls_lsvm.score(data["test_x"], data["test_y"])
scores[0][i][3] = _valid_score
cls_lsvms.append(cls_lsvm)
print(f"Linear SVM test acc: {_valid_score:.5f}")
# svm
cls_svm = SVC(random_state=args["seed"])
cls_svm.fit(data["train_x"], data["train_y"])
_valid_score = cls_svm.score(data["test_x"], data["test_y"])
scores[0][i][4] = _valid_score
cls_svms.append(cls_svm)
print(f"SVM test acc: {_valid_score:.5f}")
# decision tree
cls_dt = DecisionTreeClassifier(random_state=args["seed"])
cls_dt.fit(data["train_x"], data["train_y"])
_valid_score = cls_dt.score(data["test_x"], data["test_y"])
scores[0][i][5] = _valid_score
cls_dts.append(cls_dt)
print(f"Decision Tree test acc: {_valid_score:.5f}")
# random forest
cls_rf = RandomForestClassifier(n_estimators=10, random_state=args["seed"], n_jobs=16)
cls_rf.fit(data["train_x"], data["train_y"])
_valid_score = cls_rf.score(data["test_x"], data["test_y"])
scores[0][i][6] = _valid_score
cls_rfs.append(cls_rf)
print(f"Random Forest test acc: {_valid_score:.5f}")
# lgb
cls_lgb = LGBMClassifier(random_state=args["seed"], n_jobs=16)
cls_lgb.fit(
data["train_x"],
data["train_y"],
eval_set=[(data["test_x"], data["test_y"])],
early_stopping_rounds=100,
verbose=100,
)
_valid_pred = cls_lgb.predict(data["test_x"])
_valid_score = sum(_valid_pred == data["test_y"]) / len(_valid_pred)
scores[0][i][7] = _valid_score
cls_lgbs.append(cls_lgb)
print(f"LightGBM test acc: {_valid_score:.5f}")
# train second model with first model's CLS
print("train second model")
(
upstream_train_loader,
upstream_test_loader,
downstream_train_loader,
downstream_test_loader,
) = get_cifar10()
model2 = model_module(emb_size, n_classes=6).to(device)
model2.cls = model1.cls
model2.cls.weight.requires_grad = False
model2.cls.bias.requires_grad = False
optimizer2 = optim.Adam(
filter(lambda p: p.requires_grad, model2.parameters()), lr=args["lr"], weight_decay=5e-4
)
lr_scheduler = optim.lr_scheduler.ReduceLROnPlateau(
optimizer2, factor=0.3, patience=3, verbose=True
)
patience = es_thd
best_acc = 0
best_model = None
for epoch in range(1, args["epochs"] + 1):
train(epoch, model2, optimizer2, upstream_train_loader)
correct = test2(model2, upstream_test_loader)
lr_scheduler.step(-1 * correct / len(upstream_test_loader.dataset))
if correct / len(upstream_test_loader.dataset) > best_acc:
patience = es_thd
best_acc = correct / len(upstream_test_loader.dataset)
best_model = model_module(emb_size, n_classes=6)
best_model.load_state_dict(copy.deepcopy(model2.state_dict()))
else:
patience -= 1
if patience <= 0:
print("Early stopping!")
break
# restore best model
model2 = model_module(emb_size, n_classes=6)
model2.load_state_dict(copy.deepcopy(best_model.state_dict()))
model2.to(device)
print(model2.cls)
scores[1][i][0] = test2(model2, upstream_test_loader) / len(upstream_test_loader.dataset)
# save data for other CLSs
print("extract embedding")
emb_test = extract_embedding(model2, downstream_test_loader)
data = {"test_x": np.array(emb_test["embedding"]), "test_y": np.array(emb_test["target"])}
# test CLSs
print("test CLSs")
# embedding
test_x, test_y = (
torch.FloatTensor(data["test_x"]),
torch.LongTensor(data["test_y"]),
)
test_loader = torch.utils.data.DataLoader(
Data.TensorDataset(test_x, test_y),
batch_size=args["batch_size"] * 2,
shuffle=False,
**kwargs,
)
task_id = 0
# linear
correct = test2(model_ls[task_id], test_loader)
scores[1][i][1] = correct / len(test_loader.dataset)
# MLP
correct = test2(model_mlps[task_id], test_loader)
scores[1][i][2] = correct / len(test_loader.dataset)
# svm
_valid_score = cls_lsvms[task_id].score(data["test_x"], data["test_y"])
scores[1][i][3] = _valid_score
print(f"Linear SVM test acc:{_valid_score:.5f}")
# svm
_valid_score = cls_svms[task_id].score(data["test_x"], data["test_y"])
scores[1][i][4] = _valid_score
print(f"SVM test acc:{_valid_score:.5f}")
# decision tree
_valid_score = cls_dts[task_id].score(data["test_x"], data["test_y"])
scores[1][i][5] = _valid_score
print(f"Decision Tree test acc:{_valid_score:.5f}")
# random forest
_valid_score = cls_rfs[task_id].score(data["test_x"], data["test_y"])
scores[1][i][6] = _valid_score
print(f"Random Forest test acc:{_valid_score:.5f}")
# lgb
_valid_pred = cls_lgbs[task_id].predict(data["test_x"])
_valid_score = sum(_valid_pred == data["test_y"]) / len(_valid_pred)
scores[1][i][7] = _valid_score
print(f"LightGBM test acc:{_valid_score:.5f}")
t = round(time.time() - t0)
print("time consumed: {} min {} sec".format(t // 60, t % 60))
pickle.dump(scores, open("scores_partition_vgg16_fix_cls_v2.pkl", "wb"))
| [
"itsmystyle.0821@gmail.com"
] | itsmystyle.0821@gmail.com |
6c7045664afdea039b0e4fd8f7621d890a4a56c1 | 94c2096615dfb665b54aa1d1917cacce4e74d5e5 | /tradition/src/contours_op.py | c8fcaceedea2746788ad4320c77c10535c8e75a9 | [] | no_license | lxngoddess5321/HallerIndex | 3ade7e1457407e3605371a53fa752e2cdbfd9ef6 | c0ab569c9d61a91d578584e4a41270e4efc657c3 | refs/heads/master | 2022-10-01T08:11:35.385384 | 2020-06-01T05:42:58 | 2020-06-01T05:42:58 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 10,803 | py | """
与轮廓相关的操作函数
"""
import pydicom
import cv2
import math
import numpy as np
import pylab
import matplotlib.pyplot as plt
plt.switch_backend('agg')
def find_inner_contour(contours, outline_area):
"""
找到胸腔的内轮廓
Args:
contours (list): 由长到短轮廓排序
outline_area (float): 外胸廓的面积
"""
# 存储所有符合条件的轮廓
all_eligible_contour = []
for contour in contours:
area = cv2.contourArea(contour)
if area / outline_area > 0.03 and area / outline_area < 0.5:
all_eligible_contour.append(contour)
if len(all_eligible_contour) < 2:
raise IndexError(
"Please check the image you given. Can't find inner contour of chest.")
return all_eligible_contour[-2:]
def find_outer_contour(contours):
"""找到胸腔外部轮廓(轮廓)包围面积最大的为胸腔外轮廓
Args:
contours (list): 轮廓集合
Returns:
np.ndarray: 胸腔外轮廓, (n, 1, 2)
float: 胸腔外轮廓面积
"""
return max_area_contour(contours)
def show_contours(img, contours, copy=False, imshow=False):
"""在指定图片的中展示指定的轮廓
Args:
img (numpy.ndarray): 原始图像
contours (list): 轮廓集合
copy (bool): True 在原图上绘制轮廓。False 创建图像的拷贝,在拷贝上绘制轮廓
imshow (bool): 是否使用pyplot展示图像。如果你使用jupyter-notebook,可以将其设置为True
Return:
np.ndarray: 绘制后的图片矩阵
"""
img_with_contours = np.copy(img) if copy else img
cv2.drawContours(img_with_contours, contours, -1, (0, 100, 0), 3)
if imshow:
pylab.imshow(img_with_contours)
return img_with_contours
def show_points(img, points, copy=False, imshow=False):
"""在指定图片中绘制出指定的点
Args:
img ([type]): [description]
points ([type]): [description]
copy (bool): True 在原图上绘制轮廓。False 创建图像的拷贝,在拷贝上绘制轮廓
imshow (bool): 是否使用pyplot展示图像。如果你使用jupyter-notebook,可以将其设置为True
Return:
np.ndarray: 绘制后的图片矩阵
"""
img_with_points = np.copy(img) if copy else img
for point in points:
cv2.circle(img_with_points, tuple(point), 40, (0, 200, 0), 4)
if imshow:
pylab.imshow(img_with_points)
return img_with_points
def find_boundary_point(contour, position):
"""找到指定轮廓的最低点,并返回, (注意绘图时x轴坐标由左至右递增, y轴坐标由上至下递增)
Args:
contour (numpy.ndarray): shape (n, 1, 2)
position (str): ["bottom", "top", "left", "right"]
"""
if position not in ["bottom", "top", "left", "right"]:
raise AttributeError(
'Position 参数必须是 ["bottom", "top", "left", "right"] 其中之一')
if position in ["bottom", "right"]:
func = np.argmax
else:
func = np.argmin
if position in ["bottom", "top"]:
axis_index = 1
else:
axis_index = 0
index = func(contour[:, 0, axis_index])
point = contour[index, 0]
return point
def filter_contours(contours, x_min=float('-inf'), x_max=float('inf'), y_min=float('-inf'), y_max=float('inf'), mode="exist"):
"""根据x,y轴的范围过滤轮廓,只保留存在点集在这个范围内的轮廓
Args:
contours (list): 轮廓点列表,每个元素是numpy.ndarray类型 (n, 1, 2)
x_min (int): x轴坐标最小值
x_max (int): x轴坐标最大值
y_min (int): y轴坐标最小值
y_max (int): y轴坐标最大值
mode (str): ["exist", "all"]其中之一。exist模式表示存在满足条件的点即保存该轮廓,all模式表示所有的点满足条件才保存该轮廓。
"""
result_contours = []
for contour in contours:
x = contour[:, 0, 0]
y = contour[:, 0, 1]
if mode == "exist":
if np.sum(np.logical_and(x < x_max, x > x_min)) > 0 and np.sum(np.logical_and(y < y_max, y > y_min)) > 0:
result_contours.append(contour)
elif mode == "all":
if np.sum(np.logical_or(x > x_max, x < x_min)) == 0 and np.sum(np.logical_or(y > y_max, y < y_min)) == 0:
result_contours.append(contour)
else:
raise AttributeError('请指定mode参数为["exist", "all"]其中之一')
return result_contours
def filter_contour_points(contour, x_min=float('-inf'), x_max=float('inf'), y_min=float('-inf'), y_max=float('inf'), mode="keep"):
"""根据x,y轴的范围,过滤轮廓中的点,在此范围内的点才会被保留
Args:
contour (numpy.ndarray): shape (n, 1, 2)
x_min (int): x轴坐标最小值
x_max (int): x轴坐标最大值
y_min (int): y轴坐标最小值
y_max (int): y轴坐标最大值
mode (str): keep,在此范围内的点会被保留, drop,在此范围外的点将被保留
"""
if mode not in ["keep", "drop"]:
raise AttributeError
mask = np.ones((contour.shape[0],), dtype=bool)
x = contour[:, 0, 0]
y = contour[:, 0, 1]
for m in [x < x_max, x > x_min, y < y_max, y > y_min]:
mask = np.logical_and(mask, m)
if mode == "drop":
mask = np.logical_not(mask)
return contour[mask]
def filter_contour_out_of_box(contour, contours):
"""保留所有点都在 "contour"轮廓指定范围内的轮廓
Args:
contour (numpy.ndarray): 目标轮廓,所有的点必须在这个轮廓里
contours (numpy.ndarray): 需要过滤的轮廓集合
"""
result = []
for c in contours:
flag = True
for p in c:
if not cv2.pointPolygonTest(contour, p, False):
flag = False
break
if flag:
result.append(c)
return result
def max_area_contour(contours, diverse=False, filter_zero=False):
"""获取轮廓集合中面积最大的轮廓
Args:
contours (list): 轮廓集合
"""
areas = []
filtered_contours = []
for c in contours:
area = cv2.contourArea(c)
# 过滤掉面积过小的轮廓
if area < 5 and filter_zero:
continue
areas.append(area)
filtered_contours.append(c)
areas = np.array(areas)
if diverse:
index = areas.argmin()
else:
index = areas.argmax()
return filtered_contours[index], areas[index]
def rotate_contours(contour, matrix):
"""旋转轮廓点坐标
Args:
contour (numpy.ndarray): shape of (n, 1, 2)
matrix (numpy.ndarray): shape of (2, 3)
"""
contour = np.squeeze(contour, 1).transpose(1, 0)
pad = np.ones((1, contour.shape[1]))
contour = np.concatenate([contour, pad])
contour = np.dot(matrix, contour)
contour = np.expand_dims(contour.transpose(1, 0), 1)
return contour.astype(np.int)
def sort_clockwise(contour, center=None, anti=True, demarcation=0):
"""
将轮廓坐标点逆时针排序
Args:
contour(np.ndarray): with shape (n, 1, 2)
center(tuple): shape(2,).指定排序的中心点,如果未指定,则以轮廓的重心点为中心
anti(bool): True为逆时针, False为顺时针
demarcation(float): 排序的起始角度(用度数表示)
Return:
np.ndarray: with shape (n, 1, 2)
"""
# 计算轮廓的中心
if center is None:
M=cv2.moments(contour)
cx=int(M['m10']/M['m00'])
cy=int(M['m01']/M['m00'])
else:
assert len(center) == 2, "center参数必须为长度为2的tuple或者list。请检查您的参数"
cx, cy = center
x = contour[:, 0, 0]
y = contour[:, 0, 1]
plural = (x - cx) + (y - cy) * 1j
angle = np.angle(plural, deg=True)
angle = (angle + demarcation) % 360
if anti: # 逆时针排序
sort_keys = np.argsort(angle)
else: # 顺时针排序
sort_keys = np.argsort(-angle)
result = np.expand_dims(np.stack([x[sort_keys], y[sort_keys]], 1), 1)
return result, (cx, cy)
def nearest_point(contour, point):
"""找到轮廓中距离目标点最近的点
Args:
contour (numpy.ndarray): shape (n, 1, 2)
point (numpy.ndarray): shape (2,)
"""
x = contour[:, 0, 0]
y = contour[:, 0, 1]
distance = np.sqrt((x - point[0])**2 + (y - point[1])**2)
sort_keys = np.argsort(distance)
result = np.array([x[sort_keys[0]], y[sort_keys[0]]])
return result
def trap_contour(contour, img_shape, pixel=15):
"""将轮廓原地缩小若干个像素
Args:
contour (np.ndarray): 待缩小的轮廓 (n, 1, 2)
img_shape (tuple): 原始图像的大小
pixel (int, optional): 需要缩小的像素值. Defaults to 10.
Returns:
contour (np.ndarray): 缩小后的轮廓 (n, 1, 2)
"""
img = np.ones(shape=img_shape, dtype="uint8") * 255
cv2.drawContours(img, [contour], -1, (0, 0, 0), 3)
dist = cv2.distanceTransform(img, cv2.DIST_L2, cv2.DIST_MASK_PRECISE)
ring = cv2.inRange(dist, pixel-0.5, pixel+0.5) # take all pixels at distance between 9.5px and 10.5px
_, contours, hierarchy = cv2.findContours(ring, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
# 面积最小的是内轮廓
result_contour, area = max_area_contour(contours, diverse=True, filter_zero=True)
return result_contour
def refine_contour(contour, img_shape):
"""重整轮廓,将轮廓点的内折擦除
Args:
contour (np.ndarray): 待缩小的轮廓 (n, 1, 2)
img_shape (tuple): 原始图像的大小
Returns:
np.ndarray: 缩小后的轮廓
"""
img = np.ones(shape=img_shape, dtype="uint8") * 255
cv2.drawContours(img, [contour], -1, (0, 0, 0), -1)
_, contours, hierarchy = cv2.findContours(img, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
result_contour = sorted(contours, key=lambda x: len(x))[-1]
return result_contour
def extract_contours_from_pxarray(pixel_array, threshold):
"""从dicom像素图片中提取轮廓点集
Args:
pixel_array (numpy.ndarray): 通过pydicom.dcmread(file).pixel_array获得, 并转换成uint8类型
threshold (int): 提取轮廓的阈值
Returns:
list: list of contours
"""
ret, binary = cv2.threshold(pixel_array, threshold, 255, cv2.THRESH_BINARY)
_, contours, _ = cv2.findContours(
binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
return contours
| [
"844529478@qq.com"
] | 844529478@qq.com |
a97c8fef1b2be6a9c1d1e4d5cd44d86bbc4958cd | 9410417f506abb7c8571c6a398c67f31a1940616 | /Beginner/FSQRT.py | 9572a13085b5c238475cfc9080291a2456c71949 | [] | no_license | mujtaba-basheer/python_programming | d47dce1b5b806150bb56b815d6a4aa825c3bd5a1 | 0e4fc7f045c800f89f4296279f061c663eb67516 | refs/heads/master | 2022-04-20T18:09:32.469761 | 2020-04-25T06:10:49 | 2020-04-25T06:10:49 | 258,700,628 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 99 | py | t = int(input())
for i in range (t):
n = int(input())
sqrt = n ** 0.5
print(int(sqrt)) | [
"mujtaba.fleapo@gmail.com"
] | mujtaba.fleapo@gmail.com |
9eb78df548091f870416617ac371dc99c85a5f61 | 639da024f71c9b01278b65fc7da28aa299ff87b9 | /sorting/topological_sort/topological_sort.py | 1fe121accc63585f06b537b2c1d6f89cf4f6fca1 | [] | no_license | 99rockets/algorithms | a13db151ca66d061833f5c7769ca9ef17b0ae480 | 0033568a48bc4e5bfd792aef48859865b158c7b0 | refs/heads/master | 2020-07-03T22:15:56.045687 | 2016-11-19T22:29:13 | 2016-11-19T22:29:13 | 74,225,372 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,721 | py | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
from collections import deque
graph_tasks = {
"wash the dishes": ["have lunch"],
"cook food": ["have lunch"],
"have lunch": [],
"wash laundry": ["dry laundry"],
"dry laundry": ["fold laundry"],
"fold laundry": []
}
graph_numbers = {
0: [1, 2],
1: [3, 4],
2: [],
3: [],
4: [],
5: [6, 7],
6: [],
7: []
}
def kahn_topological_sort(graph):
"""
Implementation of topological sort on a graph - Kahn's algorithm
"""
# determine in-degree
in_degree = {u: 0 for u in graph}
for u in graph:
for v in graph[u]:
in_degree[v] += 1
# collect nodes with zero in-degree
Q = deque()
for u in in_degree:
if in_degree[u] == 0:
Q.appendleft(u)
# list for order of nodes
L = []
while Q:
# choose node of zero in-degree and 'remove' it from graph
u = Q.pop()
L.append(u)
for v in graph[u]:
in_degree[v] -= 1
if in_degree[v] == 0:
Q.appendleft(v)
if len(L) == len(graph):
return L
else:
# if there is a cycle, then return an empty list
return []
def dfs_topological_sort(graph):
"""
Implementation of topological sort on a graph -
DFS (depth first search) algorithm
"""
# recursive dfs with additional list for order of nodes
L = []
color = {u: "white" for u in graph}
found_cycle = [False]
for u in graph:
if color[u] == "white":
dfs_visit(graph, u, color, L, found_cycle)
if found_cycle[0]:
break
if found_cycle[0]:
# if there is a cycle, then return an empty list
L = []
L.reverse()
return L
def dfs_visit(graph, u, color, L, found_cycle):
if found_cycle[0]:
return
color[u] = "gray"
for v in graph[u]:
if color[v] == "gray":
found_cycle[0] = True
return
if color[v] == "white":
dfs_visit(graph, v, color, L, found_cycle)
color[u] = "black"
# when we're done with u, add u to list (reverse it later!)
L.append(u)
if __name__ == '__main__':
print("\n Topological sorts for tasks graph")
print("\n *** Kahn's algorithm:")
for task in kahn_topological_sort(graph_tasks):
print(task)
print('\n *** Modified DFS:')
for task in dfs_topological_sort(graph_tasks):
print(task)
print("\n Topological sorts for numbers graph")
print("\n *** Kahn's algorithm:")
print(kahn_topological_sort(graph_numbers))
print('\n *** Modified DFS:')
print(dfs_topological_sort(graph_numbers))
| [
"makhetov@gmail.com"
] | makhetov@gmail.com |
a407bf63d860d4ef99f814ea52f9fc3f1e4ab7fd | 50ecc145952ddb8716f18c698d241d97d7552782 | /1 семестр/Задание 2/Уравнение1.py | a4825d3ff36edc062c86a7900d2f9cba125bc08a | [] | no_license | V1kos1k/iu7_python | 2e32faabc030c5c0bb6448098c138c1e537ca3bd | c73f73dc71ade15d5bec07a089feaa438c76e45c | refs/heads/master | 2020-03-18T15:05:06.249028 | 2018-05-25T17:35:05 | 2018-05-25T17:35:05 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 234 | py | # Мхитарян ИУ7-17
# Решить уравнение
print('16.09.2016')
print('Введите число x=')
x=int(input())
a=(x+2)
b=pow((x+2),2)
c=pow((x+2),4)
Z=a*(b+3)/(c+b+3)
print('{:7.5f}'.format(Z))
| [
"mhitaryanvika@gmail.com"
] | mhitaryanvika@gmail.com |
c4d952763fef1df914eb61e06168a995e0129fac | 371ddf5445b784f11b47a0db7b8dae47d8e46040 | /sworld.py | 7cca4859e802632709e974f4d454f7b573df3a78 | [] | no_license | RDooley629/Star-Wars-Text-Adventure | 806d1fe9edd9aa30e67b3f7f248900981f88a5b3 | ceb74aaf35ca56abaea3fb781f3838529dafb804 | refs/heads/master | 2021-05-09T01:57:39.224366 | 2018-02-10T19:11:40 | 2018-02-10T19:11:40 | 119,191,469 | 1 | 1 | null | null | null | null | UTF-8 | Python | false | false | 4,856 | py | class Maptile:
def __init__(self, x, y):
self.x = x
self.y = y
def intro_text(self):
raise NotImplementedError("Create a subclass instead!")
class relica(Maptile):
def intro_text(self)
return """
"""
class storage(Maptile):
def intro_text(self):
return """
"""
class storeroom(Maptile):
def intro_text(self):
return """
"""
class bedrooma(Maptile):
def intro_text(self)
return """
"""
class yourroom(Maptile):
def intro_text(self):
return """
"""
class northfield(Maptile):
def intro_text(self):
return """
"""
class studentroom(Maptile):
def intro_text(self)
return """
"""
class study(Maptile):
def intro_text(self):
return """
"""
class meditation(Maptile):
def intro_text(self):
return """
"""
class corridor(Maptile):
def intro_text(self)
return """
"""
class mealroom(Maptile):
def intro_text(self):
return """
"""
class beach(Maptile):
def intro_text(self):
return """
"""
class trainingfield(Maptile):
def intro_text(self)
return """
"""
class medbuilding(Maptile):
def intro_text(self):
return """
"""
class bedroomm(Maptile):
def intro_text(self):
return """
"""
class sparroom(Maptile):
def intro_text(self)
return """
"""
class enter(Maptile):
def intro_text(self):
return """
"""
class kitchen(Maptile):
def intro_text(self):
return """
"""
class landingarea(Maptile):
def intro_text(self)
return """
"""
class southfield(Maptile):
def intro_text(self):
return """
"""
class lukehut(Maptile):
def intro_text(self):
return """
"""
class spacetile(Maptile):
def intro_text(self)
return """
"""
class hyperspace(Maptile):
def intro_text(self):
return """
"""
class store(Maptile):
def intro_text(self):
return """
"""
class teleport(Maptile):
def intro_text(self)
return """
"""
class housestudy(Maptile):
def intro_text(self):
return """
"""
class foyer(Maptile):
def intro_text(self):
return """
"""
class housekitchen(Maptile):
def intro_text(self)
return """
"""
class staffroom(Maptile):
def intro_text(self):
return """
"""
class introfoyer(Maptile):
def intro_text(self):
return """
"""
class temple(Maptile):
def intro_text(self)
return """
"""
class trophyroomup(Maptile):
def intro_text(self):
return """
"""
class frontparlor(Maptile):
def intro_text(self):
return """
"""
class diningroom(Maptile):
def intro_text(self)
return """
"""
class keys(Maptile):
def intro_text(self):
return """
"""
class trophyroomupintro(Maptile):
def intro_text(self):
return """
"""
class frontparlorintro(Maptile):
def intro_text(self)
return """
"""
class timeskip(Maptile):
def intro_text(self):
return """
"""
class trophyroommain(Maptile):
def intro_text(self):
return """
"""
class solar(Maptile):
def intro_text(self)
return """
"""
class courtyardup(Maptile):
def intro_text(self):
return """
"""
class gardenerhut(Maptile):
def intro_text(self):
return """
"""
class trophyroommainintro(Maptile):
def intro_text(self)
return """
"""
class solarintro(Maptile):
def intro_text(self):
return """
"""
class templespar(Maptile):
def intro_text(self):
return """
"""
class trophyroomlower(Maptile):
def intro_text(self)
return """
"""
class courtyardleft(Maptile):
def intro_text(self):
return """
"""
class statuering(Maptile):
def intro_text(self):
return """
"""
class courtyardright(Maptile):
def intro_text(self)
return """
"""
class trophyroomlowerintro(Maptile):
def intro_text(self):
return """
"""
class startingroom(Maptile):
def intro_text(self):
return """
"""
world_map = [
[relica(0,0),storage(1,0),storeroom(2,0),bedrooma(3,0),yourroom(4,0),northfield(5,0),studentroom(6,0)]
[study(0,1),meditation(1,1),corridor(2,1),mealroom(3,1),beach(4,1),trainingfield(5,1),medbuilding(6,1)]
[bedroomm(0,2),sparroom(1,2),enter(2,2),kitchen(3,2),landingarea(4,2),southfield(5,2),lukehut(6,2)]
[None,spacetile(1,3),spacetile(2,3),hyperspace(3,3),spacetile(4,3),store(5,3),teleport(6,3)]
[housestudy(0,4),foyer(1,4),housekitchen(2,4),staffroom(3,4),None,introfoyer(5,4),temple(6,4)]
[trophyroomup(0,5),frontparlor(1,5),diningroom(2,5),keys(3,5),trophyroomupintro(4,5),frontparlorintro(5,5),timeskip(6,5)]
[trophyroommain(0,6),solar(1,6),courtyardup(2,6),gardenerhut(3,6),trophyroommainintro(4,6),solarintro(5,6),templespar(6,6)]
[trophyroomlower(0,7),courtyardleft(1,7),statuering(2,7),courtyardright(3,7),trophyroomlowerintro(4,7),None,startingroom(6,7)]
]
def tile_at(x, y):
if x<0 or y<0:
return None
try:
return world_map[y][x]
except IndexError:
return None
| [
"noreply@github.com"
] | RDooley629.noreply@github.com |
094353b92fe4b210be32182725388ec3485add2b | b515ffa85a78e3812b7f94650a8aea81ef870516 | /venv/src/apps/users/admin.py | d0482e4e82f6782a9ca9b7d2ddcc464748188b07 | [
"MIT"
] | permissive | AkashSDas/custom_django_user_api | b9bb8441d6612122ff0ff3d3b48ae7511df0c179 | c19ab2e6ff2d2cb6ef8c42ca87b836f46b702dc5 | refs/heads/main | 2023-03-09T09:34:00.307004 | 2021-02-11T02:47:28 | 2021-02-11T02:47:28 | 337,913,518 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,107 | py | from django.contrib import admin
from django.contrib.auth import get_user_model
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from .models import UserProfile
# User model
User = get_user_model()
# Customizing the interface of User model in the Admin Page
class UserAdmin(BaseUserAdmin):
list_display = ['email', 'is_active', 'is_staff', 'is_admin']
list_filter = ['email']
fieldsets = [
[None, {'fields': ['email', 'password', ]}],
# ['Personal Info', {'fields': ['username', ]}],
['Permissions', {'fields': ['is_active', 'is_staff', 'is_admin']}],
]
add_fieldsets = [
[
None,
{
'classes': ['wide', ],
'fields': ['email', 'password', 'confirm_password'],
},
],
]
search_fields = ['email', ]
ordering = ['email', ]
filter_horizontal = []
class UserProfileAdmin(admin.ModelAdmin):
pass
# Registering User model and its interface in admin page
admin.site.register(User, UserAdmin)
admin.site.register(UserProfile, UserProfileAdmin)
| [
"aakashdas368@gmail.com"
] | aakashdas368@gmail.com |
f20f79e2cfffc85dbdd629bf78ecac089973e3db | b35a367efe37f2b657a2520b353b52922fc9c0a1 | /05_Excel Web Crawling/03_Selenium/00_SeleniumBasic-2.0.9.0/FirefoxAddons/build-implicit-wait.py | 5a036a1bab204b185f740b789eac348aa91c7b0f | [
"BSD-3-Clause"
] | permissive | VB6Hobbyst7/02_Excel | 4b8af7d5f4864690ecd7f670c10d4af0a14932c4 | 3c164e9b01efa6383def09f202e00c7684ce5e63 | refs/heads/master | 2023-06-20T14:35:00.353990 | 2021-07-20T04:26:23 | 2021-07-20T04:26:23 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,005 | py |
"""Script to build the xpi add-in for firefox
Usage : python build-implicit-wait.py "x.x.x.x"
"""
import os, re, sys, shutil, datetime, zipfile, glob
CD = os.path.dirname(os.path.abspath(__file__))
SRC_DIR = CD + r'\implicit-wait'
OUT_DIR = CD + r'\bin'
RDF_PATH = CD + r'\implicit-wait\install.rdf'
def main(args):
arg_version = args and args[0]
set_working_dir(CD)
last_modified_time = get_file_mtime(RDF_PATH, '%Y-%m-%d %H:%M:%S')
current_version = find_in_file(RDF_PATH, r'version>([.\d]+)<');
print __doc__
print 'Last compilation : ' + (last_modified_time or 'none')
print 'Current Version : ' + current_version
new_version = arg_version or get_input_version(current_version)
print 'New version : ' + new_version + '\n'
print 'Update version number ...'
replace_in_file(RDF_PATH, r'(?<=version>)[.\d]+(?=<)', new_version)
print 'Build formater xpi ...'
make_dir(OUT_DIR)
set_working_dir(SRC_DIR)
with ZipFile(OUT_DIR + r'\implicit-wait.xpi', 'w') as zip:
zip.add(r'*')
print '\nDone'
def set_working_dir(directory):
make_dir(directory)
os.chdir(directory)
def make_dir(directory):
if not os.path.isdir(directory):
os.makedirs(directory)
def clear_dir(directory):
if os.path.isdir(directory):
shutil.rmtree(directory)
os.makedirs(directory)
def get_file_mtime(filepath, format=None):
if(not os.path.isfile(filepath)):
return None
dt = datetime.datetime.fromtimestamp(os.path.getmtime(filepath))
if format:
return dt.strftime(format)
return dt
def delete_file(filepath):
if(os.path.isfile(filepath)):
os.remove(filepath)
def find_in_file(filepath, pattern):
with open(filepath, 'r') as f:
result = re.search(pattern, f.read())
return result.group(result.re.groups)
def replace_in_file(filepath, pattern, replacement):
with open(filepath, 'r') as f:
text = re.sub(pattern, replacement, f.read())
with open(filepath, 'w') as f:
f.write(text)
def get_input(message):
try: return raw_input(message)
except NameError: return input(message)
def get_input_version(version):
while True:
input = get_input('Digit to increment [w.x.y.z] or version [0.0.0.0] or skip [s] ? ').strip()
if re.match(r's|w|x|y|z', input) :
idx = {'s': 99, 'w': 0, 'x': 1, 'y': 2, 'z': 3}[input]
return '.'.join([str((int(v)+(i == idx))*(i <= idx)) for i, v in enumerate(version.split('.'))])
elif re.match(r'\d+\.\d+\.\d+\.\d+', input):
return input
class ZipFile(zipfile.ZipFile):
def __init__(cls, file, mode):
zipfile.ZipFile.__init__(cls, file, mode)
def add(self, path):
for item in glob.glob(path):
if os.path.isdir(item):
self.add(item + r'\*');
else:
self.write(item)
if __name__ == '__main__':
main(sys.argv[1:])
| [
"hanseol33@naver.com"
] | hanseol33@naver.com |
b4f6555d72c6cacb9fa6eab225aff4ab94ddd2b0 | 77d93431ca903d7f97d0eaa1b46a98fc1b372f33 | /yugires/yugiscrapper.py | 5963d5449b223deede8380f9c5ca07ffd6a40b3c | [
"MIT"
] | permissive | DanielLSM/yugioh-high-res | 160ce52b8e0959add9d82b0595aa3f64ccc24689 | bc0cb2149f967fee46f58bdeed8ea089214f2290 | refs/heads/main | 2023-06-06T02:23:32.827861 | 2021-06-29T16:07:54 | 2021-06-29T16:07:54 | 381,405,623 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 86 | py | from tools impor
database_endpoint = 'https://db.ygoprodeck.com/api/v7/cardinfo.php'
| [
"daniellsmarta@gmail.com"
] | daniellsmarta@gmail.com |
6b688c2274d062b107eef215f2f6857853970569 | 1333357d463006bb6540fb6f68f140c383d4e676 | /data/data_clean.py | 3bcfe42405065c6c3c2b46f2e42f29c6764ba91d | [] | no_license | markWJJ/classifynetwork | ced1ff5eaa9e1c7e9e6440e08e6744070689a305 | d65f22486434fdfbdce38d063e176eb31c5d7354 | refs/heads/master | 2023-01-09T03:12:01.540254 | 2018-09-17T07:50:02 | 2018-09-17T07:50:02 | 149,088,397 | 0 | 1 | null | 2022-12-21T03:34:27 | 2018-09-17T07:48:54 | Python | UTF-8 | Python | false | false | 8,090 | py | # -*- coding: UTF-8 -*-
import re
from collections import OrderedDict
import jieba
import codecs
from hanziconv import HanziConv
import os
import string
import json
import jieba.posseg as pseg
import numpy as np
FH_NUM = (
(u"0", u"0"), (u"1", u"1"), (u"2", u"2"), (u"3", u"3"), (u"4", u"4"),
(u"5", u"5"), (u"6", u"6"), (u"7", u"7"), (u"8", u"8"), (u"9", u"9"),
)
FH_NUM = dict(FH_NUM)
FH_ALPHA = (
(u"a", u"a"), (u"b", u"b"), (u"c", u"c"), (u"d", u"d"), (u"e", u"e"),
(u"f", u"f"), (u"g", u"g"), (u"h", u"h"), (u"i", u"i"), (u"j", u"j"),
(u"k", u"k"), (u"l", u"l"), (u"m", u"m"), (u"n", u"n"), (u"o", u"o"),
(u"p", u"p"), (u"q", u"q"), (u"r", u"r"), (u"s", u"s"), (u"t", u"t"),
(u"u", u"u"), (u"v", u"v"), (u"w", u"w"), (u"x", u"x"), (u"y", u"y"), (u"z", u"z"),
(u"A", u"A"), (u"B", u"B"), (u"C", u"C"), (u"D", u"D"), (u"E", u"E"),
(u"F", u"F"), (u"G", u"G"), (u"H", u"H"), (u"I", u"I"), (u"J", u"J"),
(u"K", u"K"), (u"L", u"L"), (u"M", u"M"), (u"N", u"N"), (u"O", u"O"),
(u"P", u"P"), (u"Q", u"Q"), (u"R", u"R"), (u"S", u"S"), (u"T", u"T"),
(u"U", u"U"), (u"V", u"V"), (u"W", u"W"), (u"X", u"X"), (u"Y", u"Y"), (u"Z", u"Z"),
)
FH_ALPHA = dict(FH_ALPHA)
NUM = (
(u"一", "1"), (u"二" ,"2"), (u"三", "3"), (u"四", "4"), (u"五", "5"), (u"六", "6"), (u"七", "7"),
(u"八", "8"), (u"九", "9"), (u"零", "0"), (u"十", "10")
)
NUM = dict(NUM)
CH_PUNCTUATION = u"["#$%&',:;@[\]^_`{|}~⦅⦆「」、 、〃〈〉《》「」『』【】〔〕〖〗〘〙〚〛〜〝〞〟〰〾〿–—‘’‛“”„‟…‧﹏﹑﹔·!?。。]"
EN_PUNCTUATION = u"['!#$%&\'()*+,-/:;<=>?@[\\]^_`{|}~']"
sub_dicit = {u"老师好":"",
u"老师":u"", u"你好":u"", u"您好":u"",
u"请问":u"", u"请":u"", u"谢谢":u"",
u""":u""}
class DataCleaner(object):
def __init__(self, params_path):
self.params_path = params_path
self.read_word()
self.read_synonym_word()
self.read_non_words()
def read_non_words(self):
word_path = self.params_path.get("non_words", "")
print("----non word path----", word_path)
if os.path.exists(word_path):
with codecs.open(word_path, "r", "utf-8") as f:
self.non_word = f.read().splitlines()
else:
self.non_word = None
print(self.non_word,"----non word----")
def calculate_non_word(self, input_string):
non_cnt = 0
if self.non_word:
word_cut = list(jieba.cut(input_string))
for word in self.non_word:
if word in word_cut:
non_cnt += 1
if np.mod(non_cnt, 2) == 0:
return 0
else:
return 1
def synthom_replacement(self, input_string):
cut_word_list = list(jieba.cut(input_string))
normalized_word_list = cut_word_list
for index, word in enumerate(cut_word_list):
if word in self.synonym_dict:
normalized_word_list[index] = self.synonym_dict[word]
return "".join(normalized_word_list)
def remove_stop_word(self, input_string):
cut_word_list = list(jieba.cut(input_string))
normalized_word_list = []
for word in cut_word_list:
if word in self.stop_word:
continue
else:
normalized_word_list.append(word)
return "".join(normalized_word_list)
def remove_symbol(self, input_string):
cn_text = re.sub(CH_PUNCTUATION, "", input_string)
en_text = re.sub(EN_PUNCTUATION, "", cn_text)
return en_text
def poc_clean(self, input_string):
tmp = self.upper2lower(input_string)
tmp = self.tra2sim(tmp)
tmp = self.full2half(tmp)
if self.synonym_dict:
tmp = self.synthom_replacement(tmp)
if self.stop_word:
nonstop_text = self.remove_stop_word(tmp)
if len(nonstop_text) >= 1:
tmp = nonstop_text
non_symbol_text = self.remove_symbol(tmp)
if len(non_symbol_text) >= 1:
tmp = non_symbol_text
char_pattern = re.compile(u"[\u4e00-\u9fa5,0-9,a-z,A-Z]+")
tmp = "".join(char_pattern.findall(tmp))
output = ""
for token in tmp:
if len(token) >= 1:
output += token
return output
def clean(self, input_string):
tmp = self.upper2lower(input_string)
tmp = self.tra2sim(tmp)
tmp = self.full2half(tmp)
return tmp
def read_word(self):
word_path = self.params_path.get("stop_word", "")
if os.path.exists(word_path):
with codecs.open(word_path, "r", "utf-8") as f:
self.stop_word = f.read().splitlines()
else:
print("not exiting params_path".format(word_path))
self.stop_word = None
def read_synonym_word(self):
self.synonym_dict = {}
synonym_path = self.params_path.get("synthom_path", "")
if os.path.exists(synonym_path):
with codecs.open(synonym_path, "r", "utf-8") as f:
data = f.read().splitlines()
for item in data:
content = item.split()
self.synonym_dict[content[0]] = content[1]
print(content[0], content[1])
else:
self.synonym_dict = None
def synonym_word_mapping(self):
self.synonym2standard = OrderedDict()
for key in self.synonym_dict:
for item in self.synonym_dict[key]:
self.synonym2standard[item] = key
def upper2lower(self, input_string):
return input_string.lower()
def subtoken(self, input_string):
tmp_string = input_string
for key in sub_dicit:
tmp_string = re.sub(key, sub_dicit[key], tmp_string)
return tmp_string
def lower2upper(self, input_string):
return input_string.upper()
def replace_phrase(input_string, phrase_dict):
s = input_string
for key in phrase_dict.keys():
s = re.sub(key, phrase_dict[key], s)
return s
def tra2sim(self, input_string):
s = HanziConv.toSimplified(input_string)
return s
def full2half(self, input_string):
s = ""
for uchar in input_string:
if uchar in FH_NUM:
half_char = FH_NUM[uchar]
if uchar in FH_ALPHA:
half_char = FH_ALPHA[uchar]
if uchar in NUM:
half_char = NUM[uchar]
else:
half_char = uchar
s += half_char
return s
def detect_en(self, input_string,
en_pattern=re.compile(u'[\u4e00-\u9fa5]'),
alphabet_pattern=re.compile(u"[a-cA-C]")):
s = []
for var in en_pattern.split(input_string.decode("utf-8")):
if len(var) > 1:
"""
if len(var) >= 1 it is a word or sentence
"""
s.append(var)
elif len(var) == 1:
"""
if len(var) == 1 it may be a alphabet and usually it is a choice for a given question
"""
tmp_var = alphabet_pattern.findall(var)
if len(tmp_var) == 1:
s.append(self.upper2lower(var))
return s
def detect_ch(self, input_string, ch_pattern = re.compile(u"[\u4e00-\u9fa5]+")):
s = ch_pattern.findall(input_string.decode("utf-8"))
s = " ".join(s)
return s
def sentence_segmentation(self, input_string, symbol_pattern=re.compile(CH_PUNCTUATION)):
"""
based on CH_PUNCTUATION to segment sentence
"""
return symbol_pattern.split(input_string.decode("utf-8")) | [
"363451547@qq.com"
] | 363451547@qq.com |
30bd9df19ba7cfe30134d09536a8bffcfafff577 | 4932a33d4376616561f83369d3f08dcfa5c6aa3a | /SC101_Assignment5/anagram.py | c0e44dea57bf2778beda23c1288aad4091f346e8 | [
"MIT"
] | permissive | Timeverse/stanCode-Projects | aeef37e2eb5bdb5e02cfb0e939e704e9c62c46bb | 845244b6cf2c39bf8a1949cea4a3c46125cf5f74 | refs/heads/main | 2023-04-19T12:49:32.339804 | 2021-04-26T12:26:19 | 2021-04-26T12:26:19 | 361,738,132 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,206 | py | """
File: anagram.py
Name:
----------------------------------
This program recursively finds all the anagram(s)
for the word input by user and terminates when the
input string matches the EXIT constant defined
at line 19
If you correctly implement this program, you should see the
number of anagrams for each word listed below:
* arm -> 3 anagrams
* contains -> 5 anagrams
* stop -> 6 anagrams
* tesla -> 10 anagrams
* spear -> 12 anagrams
"""
# Constants
FILE = 'dictionary.txt' # This is the filename of an English dictionary
EXIT = '-1' # Controls when to stop the loop
FILTER_DICT = [] # This will store the filtered dictionary text
ANS_LST = [] # This will store the found anagrams
SRH_Switch = 0 # This is the switch to show if a search is ongoing. 0 = No search is ongoing
def main():
print('Welcome to stanCode "Anagram Generator" (or -1 to quit)')
while True:
global ANS_LST
ANS_LST = []
word_input = input('Find anagrams for: ')
read_dictionary(word_input)
if word_input == EXIT:
break
else:
(find_anagrams(word_input))
print(ANS_LST)
def read_dictionary(s):
"""
:param s: The world inputted by the user
"""
raw_dict = [] # This stores the raw imported dictionary. Structure is [['a'],['b']]
rdy_dict = [] # Processed raw dictionary. Structure is refined as ['a', 'b']
length_check = len(s)
with open(FILE, 'r') as f:
for line in f:
word = line.split()
raw_dict.append(word)
for item in raw_dict:
rdy_dict += item
for word in rdy_dict:
if len(word) == length_check: # This filters the dictionary for words of same length as user input
for letters in s:
if word.startswith(letters): # This further filter words that start with each alphabet of user input
FILTER_DICT.append(word)
def find_anagrams(s):
"""
:param s: The string inputted by the user to find the anagram
"""
current_lst = [] # This store the result of recursion
input_lst = [] # This store the result of converting user input string into list structure
index_lst = [] # This store the index result of recursion
for i in s:
input_lst.append(i) # Converts user inputted string into list structure
helper(input_lst, current_lst, index_lst)
def helper(input_lst, current_lst, index_lst):
current_s = '' # This stores the result converting recursion result back to string format
global SRH_Switch
for i in current_lst:
current_s += i # Converting recursion result back to string format
if len(current_lst) == len(input_lst):
if current_s in FILTER_DICT: # Check if the recursion result matches any word in dictionary
if current_s not in ANS_LST: # A word is only recorded once
print('Found:' + current_s)
ANS_LST.append(current_s)
SRH_Switch = 0
else:
pass
else:
if SRH_Switch == 0:
print('Search....') # Print message to let user know search is ongoing
SRH_Switch = 1 # Turn on the switch as search is ongoing
# Choose
for index in range(len(input_lst)):
if index not in index_lst: # Index is here to avoid error from a word with same letters (e.g ball)
current_lst.append(input_lst[index])
index_lst.append(index)
# Explore
sub_s = ''
for letters in current_lst:
sub_s += letters
if has_prefix(sub_s) is True:
helper(input_lst, current_lst, index_lst)
# Un-choose
current_lst.pop()
index_lst.pop()
else:
pass
def has_prefix(sub_s):
"""
:param sub_s: The sub-string of recursion result
"""
for string in FILTER_DICT:
if string.startswith(sub_s) is True:
return True
if __name__ == '__main__':
main()
| [
"noreply@github.com"
] | Timeverse.noreply@github.com |
0b8924a6363203554453981192b7d51721c09ad6 | fcd798dd548f292ab2cb334849e9e29c269e4e56 | /fcuser/migrations/0002_auto_20200728_0126.py | c6d20401b5f88af3521bd10bdefa1fe08c51a1fc | [] | no_license | hee-c/Django_Basic | f0986e87445dac2a5d4bdd4c1f54a6430fc43f07 | 36cf5f2040db8186ef86b6f0e549d7f737b8b8db | refs/heads/master | 2023-04-15T15:07:56.376993 | 2021-05-02T13:19:27 | 2021-05-02T13:19:27 | 282,562,287 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 405 | py | # Generated by Django 3.0.8 on 2020-07-27 16:26
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('fcuser', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='fcuser',
name='username',
field=models.CharField(max_length=32, verbose_name='사용자명'),
),
]
| [
"ways2kim@gmail.com"
] | ways2kim@gmail.com |
a27768a8024b0c4eaceb9c230784cc1baefcc183 | 4fbce74683c8dcd63fbf4197764f80230c357efd | /tap/TapTitain/handlers/upgrade/partner_upgrade.py | 71410e9f758ace920f92619fd95368e361a41684 | [] | no_license | JimmyHuang83/TapServer | f02087243d82ff7621b3ddec5dc4a1bd88efb569 | 423fd5f99272b8f28ba09b1daeef3134548a55e7 | refs/heads/master | 2021-01-10T18:47:03.586877 | 2015-10-01T04:25:00 | 2015-10-01T04:25:00 | 42,388,887 | 0 | 0 | null | null | null | null | WINDOWS-1252 | Python | false | false | 1,632 | py | import tornado.web
import tornado.gen
from managers.player_data_manager import playerDataManager
from models.message import MessageTools, MessData, ErrorCode
__author__ = 'Mike'
class Partner_upgradeHandler(tornado.web.RequestHandler):
@tornado.web.asynchronous
@tornado.gen.coroutine
def post(self):
bodyData = self.request.body
dictData = MessageTools.decode(bodyData)
self._process(dictData)
def _process(self, params):
token = params.get('token')
partner_id = params.get('partner_id')
to_level = params.get('to_level')
player = playerDataManager.getPlayerByToken(token)
returnData = MessData()
if player == None:
returnData = MessData(ErrorCode.tokenOutData)
else:
# Íæ¼Òconnect id¼ì²â
connect_id = params.get('connect_id', '') # Íæ¼ÒÁ¬½Óid
ck_connectid = playerDataManager.check_connect_id(obj=player, post_connect_id=connect_id)
if ck_connectid[0] is False:
returnData = MessData(ck_connectid[1])
self.write(MessageTools.encode(returnData))
self.finish()
return
errCode = player.partnerUpgrade(partner_id,to_level)
if errCode != None:
returnData = MessData(errCode)
str = MessageTools.encode(returnData)
self.write(str)
self.finish()
if player != None:
player.updatePVPBuffs()
playerDataManager.checkNeedSave2DB(player.player_id)
| [
"jimmmyling@gmail.com"
] | jimmmyling@gmail.com |
6a478a825af5bb2e95aa807cea9fff3dfca2c8ff | f2a6b9811bbfa4a8fa36705a3453e9e20db3b1cb | /interpret.py | c85298b680aacf060ac5b4215e178acc8a86d6ea | [] | no_license | hdoupe/sqlite_tools | 7d2ce5d27f250b28b5b7393ec1a9777ed1841aa6 | 3bb635cd58e69b2af04740c80ccea0127c2a8acd | refs/heads/master | 2021-01-01T06:33:10.649173 | 2016-10-17T03:17:24 | 2016-10-17T03:17:24 | 42,671,381 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,632 | py | from datetime import datetime
import os
import argparse
def main():
sqlite_table = "path/to/sqlite_table.sqlite"
table_name = "your table's name"
parser = argparse.ArgumentParser()
parser.add_argument("--query","-q",dest = "query",action = "store_true")
parser.add_argument("--queryfile","-qf",dest = "queryfile",default = "radio_census_query.txt")
parser.add_argument("--sql",dest = "sql",default = "")
parser.add_argument("--description","-dscr",dest = "description",action = "store_true")
parser.add_argument("--std_out",dest = "std_out",action = "store_true")
parser.add_argument("--csv",dest = "csv",default = "radio_census_results.txt")
parser.add_argument("--d2","-d",dest = "d2",action = "store_true")
parser.add_argument("--d2_variable","-ddv",dest = "dd_variable",default = "DP0010001")
parser.add_argument("--percentile","-pct",dest = "percentile",default = 90)
parser.add_argument("--population_query","-pq",dest = "population_query",default = None)
parser.add_argument("--pq_variable","-pqv",dest="pq_variable",default = "DP0010001")
parser.add_argument("--npr","-npr",dest="npr",action = "store_true")
args = parser.parse_args()
if args.query:
print args.sql
if args.sql:
from query import Query
query = Query(sqlite_table,table_name)
if os.path.exists(args.sql):
with open(args.sql) as f:
sqls = f.read().split('\n')
else:
sqls = [args.sql]
query_start = datetime.now()
query.query(sqls = sqls,description = args.description,std_out = args.std_out,csv = args.csv)
query_finish = datetime.now()
print "Query Time: ",query_finish - query_start
if args.population_query:
rc = Radio_Census(target_dir,data_dir)
rc.set_dbs()
if os.path.exists(args.population_query):
callsigns = []
with open(args.population_query) as f:
for line in f:
callsigns.append(str(line.split('|')[1]).strip())
else:
callsigns = str(args.population_query).split(',')
from query import Filter,Population_Query
filter = Filter(callsigns,sqlite_table,table_name,'callsign')
search_hits = filter.filter()
filter.conn.close()
census_table_name = ""
census_sqlite_table = ""
pq = Population_Query(search_hits,sqlite_table,table_name,census_sqlite_table,census_table_name)
search_hits = pq.query_tracts()
results = pq.get_population_dict()
pq_variables = str(args.pq_variable).split(',')
for variable in pq_variables:
print variable,results[variable]
print "But, there's more!"
for variable in pq.demographic_variables():
print variable,results[variable]
if args.csv:
pq.print_search_hits(args.csv)
| [
"hdoupe@yahoo.com"
] | hdoupe@yahoo.com |
c478158f26eae1bf886583258edec96ce542fa02 | 46fd7911a7fa3107f97ac06dad7342e7b5d428a8 | /accountio.py | dafaa2ba6aac25ec41c7f6c3c8dcadbec6622c03 | [] | no_license | dawnjunnet/Bank-details-command-loop | 94e772789f35818a1f8e8646324a6595ffde53aa | d15bc22da2767bc1faf4ae5cf7c3865bf47a251b | refs/heads/master | 2022-06-19T18:06:37.022736 | 2020-05-09T01:59:34 | 2020-05-09T01:59:34 | 257,075,717 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,018 | py | import json
# Function write_account writes the given balance and
# transaction history to an account file whose name is
# account_N.data, where N is replaced by the acctnum argument.
#
# NOTE that the account file will be created if it does not exist.
# NOTE that if the account file already exists, it will be overwritten.
#
# Arguments:
# acctnum An int or string representing the account number
# balance A float representing the current account balance
# history A list containing the transaction history
#
# Returns:
# This function does not return anything.
#
# Exceptions:
# This function will raise an exception if there is an error
# writing to the account file.
def write_account(acctnum, balance, history):
fname = 'account_' + str(acctnum) + '.data'
f = open(fname, 'w')
f.write(str(balance) + '\n')
# Convert the history argument to a string in JSON format.
historyline = json.dumps(history)
f.write(historyline + '\n')
f.close()
# Function read_account reads the account balance and
# transaction history from an account file whose name is
# account_N.data, where N is replaced by the acctnum argument.
#
# Arguments:
# acctnum An int or string representing the account number
#
# Returns:
# This function returns a 2-element list:
# - Element 0 is the account balance (as a float).
# - Element 1 is the transaction history. It will be the same
# kind of Python object that was passed as the history
# argument to write_account().
#
# Exceptions:
# This function will raise an exception if there is no account
# file matching the given acctnum.
def read_account(acctnum):
fname = 'account_' + str(acctnum) + '.data'
f = open(fname, 'r')
balance = float(f.readline().rstrip('\n'))
historyline = f.readline().rstrip('\n')
f.close()
# The line we just read is in JSON format. Turn it back into
# a Python object.
history = json.loads(historyline)
return [balance, history]
| [
"noreply@github.com"
] | dawnjunnet.noreply@github.com |
acfd8fc66956190ccdff41889b9fd040de175a49 | d1d19be7f559f57c1b495b4766db400bb541554b | /beberagestockmarket.py | 42331fef135b35b6268dfe8245d98c38436aa108 | [] | no_license | amlluch/trading | f2d23a3f7af5428d6ce61264f062e0a28150e6a4 | 5f136776c98cbd7ba92642e865675fffafe927ef | refs/heads/master | 2020-04-25T13:05:16.049644 | 2019-03-11T10:18:11 | 2019-03-11T10:18:11 | 172,727,550 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 12,443 | py | import re
from datetime import timedelta, datetime
import numpy as np
from scipy.stats.mstats import gmean
class Stock: # This is a single stock with all info inside
"""
creates a stock and includes all transactions on a given stock
stock format:
symbol: 3 characters
stock_type: only "common" or "preferred" admitted
last_dividend: numeric value
par value: numeric value
fixed_dividend: percent introduced as integer. Internally divides per 100
not mandatory for stock_type common
operations:
dividend yield: given a price
P/E ratio or PER: given a price
"""
def __init__(self, symbol, stock_type, last_dividend, par_value, fixed_dividend=None) :
if len(symbol.strip()) != 3:
raise Exception("Symbol {symbol} must have 3 characters and has {number}".format(number=len(symbol.strip()),
symbol=symbol.strip()))
else:
self.symbol = symbol.strip().upper()
if stock_type.lower() not in ['common', 'preferred']:
raise Exception("Only common or preferred values are admitted")
else:
self.stock_type = stock_type.lower()
if not isinstance(last_dividend, (int, float)):
raise Exception("Last dividend should be a numeric value")
else:
self.last_dividend = last_dividend
if not isinstance(par_value, (int, float)):
raise Exception("Par Value should be a numeric value")
else:
self.par_value = par_value
if fixed_dividend:
if isinstance(fixed_dividend, (int, float)):
self.fixed_dividend = fixed_dividend / 100
else:
r = re.compile('(\d+(\.\d+)?)\%')
percentage = fixed_dividend.replace(' ', '')
if r.match(percentage):
self.fixed_dividend = float(percentage.strip('%')) / 100
else:
try:
self.fixed_dividend = float(fixed_dividend) / 100
except ValueError:
self.fixed_dividend = 0
else:
self.fixed_dividend = 0
if self.stock_type == 'preferred' and self.fixed_dividend == 0:
raise Exception("No Fixed Dividend. Needed for Preferred stocks")
def __str__(self):
return self.symbol
def dividend_yield(self, price): # it calculates the dividend yield for a given stock
if price == 0:
raise Exception("Divide by 0!")
if self.stock_type == 'common':
return self.last_dividend / price
else:
return (self.fixed_dividend * self.par_value) / price
def pe_ratio(self, price): # it calculates the PER for a given stock
if self.last_dividend == 0 or self.par_value == 0:
return None
if self.stock_type == 'common':
return price / self.last_dividend
else:
return price / (self.fixed_dividend * self.par_value)
class Trade: # a single trade with all info needed. If timestamp is None then will get time now
"""
Creates a single trade.
Trade format:
stock: must be stock type
quantity: integer value
op: just 2 options ... "sell" or "buy"
price: numeric value
timestamp: on ISO format. If is passed as None it will take the time at that moment
"""
def __init__(self, stock, quantity, op, price, timestamp=None):
if type(stock) != Stock:
raise Exception('No stock received')
self.stock = stock
self.symbol = stock.symbol # Necessary for filters
if type(quantity) != int:
raise Exception('Quantity must be integer')
else:
self.quantity = quantity
if not isinstance(price, (int, float)):
raise Exception("Price should be a numeric value")
else:
self.price = price
if op.lower() not in ['sell', 'buy']:
raise Exception("You should indicate a 'sell' or 'buy' operation")
self.op = op.lower()
if timestamp:
try:
datetime.strftime(timestamp, '%Y-%m%dT%H:%M:%S.%f')
self.timestamp = timestamp
except ValueError:
raise Exception("Time stamp is not in ISO format: YYYY-MM-DDTHH:MM:SS.mmmm")
else:
self.timestamp = datetime.utcnow().isoformat()
def __str__(self):
return self.stock.symbol
class TradingFilter:
"""
This class is a decorator for checking if exists a filter list.
If don't, creates it from the trading list
Checks attributes and formats.
clean: for cleaning up the list after applying a filter ('to_list' and 'first')
time : checks time format in 'before' and 'after' filters
"""
def __init__(self, clean=False, time=False):
self.clean = clean
self.time = time
def __call__(self, func):
def wrap(inst, *args, **kwargs):
if inst.filter_list is None:
inst.filter_list = inst.trading_list.copy()
for key in kwargs: # checks key arguments for filters
if not hasattr(inst.filter_list[0], key):
raise Exception('{} attribute doesn\'t exist'.format(key))
if self.time: # checks time if is a positional argument
try:
datetime.strftime(args[0], '%Y-%m%dT%H:%M:%S.%f')
except Exception:
raise Exception("Time stamp is not in ISO format: YYYY-MM-DDTHH:MM:SS.mmmm")
else:
pass
result = func(inst, *args, **kwargs)
if self.clean: # cleans for ending the filter (to_list and first)
inst.filter_list = None
return result
return wrap
class Trading: # A list of trades all together
"""
A bunch of trades all together. You can create a void trading or a new one with a list of trades.
It will check that every element of the list is a trade.
Operation:
_add_trade: add a trade to the trading. Must receive a trade element (Trading += Trade)
_add_tradelist: add a list of trades to trading (Trading += list_of_trades)
filter: gets a list of trades filtered by criteria
examples:
trading.filter().to_list() : will return a list with all trades inside the trading
trading.filter(symbol='POP').to_list(): will return a list with all trades for this stock
trading.filter(symbol='POP', op='sell').to_list() will return a list with all sell operations from this stock
exclude: as filter but excluding by criteria
before: gets all trades before a time
after: gets all trades after a time
order_by: order the trading list by any field. Start the field name by '-' for reverse ordering
to_list: returns filtered trade as a list or the whole trading as a list (list of Trade types)
first: returns first trade from the trading list or filtered list (Trade type)
get_symbols: gets all different stock symbols
weighted_price: calculates the Volume Weighted Stock Price for a given symbol
geometric_mean: geometric mean for whole trading
It is possible to chain filters. Next example gets buy operations from POP symbol last 5 minutes
trading.filter(symbol='POP').exclude(op='sell').before(datetime.now()).after(datetime.now-timedelta(minutes=5).to_list()
You can add Tradings. You can add a Trade, a list of trades or a Trading object
new_trading = Trading(list_of_trades) + Trade(single_trade_params)
new_trading = Trading(list_of_trades) + list_of_trades
new_trading = Trading(list_of_trades) + Trading(list_of_trades)
"""
def __init__(self, trading_list=None): # you can create a void trade or a new one from a lits of trades
self.trading_list = list()
if trading_list:
for trade in trading_list:
if type(trade) != Trade:
raise Exception("No valid list. All elements must belong to Trade class")
self.trading_list += trading_list
self.filter_list = None
def __add__(self, other):
trading_list = self.trading_list.copy()
trading = Trading(trading_list)
if type(other) == Trade:
trading._add_trade(other)
elif type(other) == list:
trading._add_tradelist(other)
elif type(other) == Trading:
trading._add_tradelist(other.to_list())
else:
raise Exception('Object must be Trade, a Trading or a list of Trade objects')
return trading
def __radd__(self, other):
return self + other
def _add_trade(self, trade): # for adding a trade to the trading
if type(trade) != Trade:
raise Exception('Must be a Trade object')
self.trading_list.append(trade)
def _add_tradelist(self, trades):
for trade in trades:
if type(trade) != Trade:
raise Exception('All objects should be Trade type')
self.trading_list.extend(trades)
@TradingFilter()
def filter(self, **kwargs): # you can get all trades just passing NO parameters
for key, value in kwargs.items(): # or filter by any trade attribute or a group of attributes
self.filter_list = [x for x in self.filter_list if getattr(x, key) == value]
return self
@TradingFilter()
def exclude(self, **kwargs):
for key, value in kwargs.items():
self.filter_list = [x for x in self.filter_list if getattr(x, key) != value]
return self
@TradingFilter(time=True)
def before(self, time): # all trades BEFORE a time. Needs to_list()
self.filter_list = [x for x in self.filter_list if x.timestamp <= time]
return self
@TradingFilter(time=True)
def after(self, time): # all trades AFTER a time. Needs to_list()
self.filter_list = [x for x in self.filter_list if x.timestamp >= time]
return self
@TradingFilter()
def order_by(self, field=None):
if not field:
field = 'timestamp' # Order by timestamp by default
if field[0:1] == '-':
reverse = True # Start the field by '-' for reverse sorting
field = field[1:]
else:
reverse = False
if self.filter_list:
if not (hasattr(self.filter_list[0], field)):
raise Exception('{} attribute doesn\'t exist'.format(field))
self.filter_list.sort(key=lambda x: getattr(x, field), reverse=reverse)
return self
@TradingFilter(clean=True)
def to_list(self): # Returns the filtered list of trades
return self.filter_list
@TradingFilter(clean=True)
def first(self):
return self.filter_list[0]
def get_symbols(self): # gets the different stocks on the trading
symbols = []
for elem in self.trading_list:
if elem.symbol not in symbols:
symbols.append(elem.symbol)
return symbols
def weighted_price(self, symbol): # calculates the Volume Weighted Stock Price for a given symbol
stock_list = self.filter(symbol=symbol).to_list()
if not stock_list:
raise Exception('No objects on this query')
matrix = np.asarray([[x.quantity, x.price] for x in stock_list], dtype=np.float32)
prices = matrix[:,1]
quantities = matrix[:,0]
total_quantities = sum(quantities)
if total_quantities == 0:
raise Exception('Divide by 0!')
return sum(np.multiply(prices, quantities)) / total_quantities
def geometric_mean(self): # geometric mean for whole trading
stock_symbols = self.get_symbols()
weights = [self.weighted_price(x) for x in stock_symbols]
if not weights:
raise Exception('No objects on this query')
return gmean(weights)
| [
"amlluch@gmail.com"
] | amlluch@gmail.com |
ceff19f5ab5848c6a5ddb94291f6d38668ba579e | 56525e575228cd41579d462d39f8b65eabb3b3bd | /viz/src/plot_APR_distribution.py | 0229918bb1ba34d42038a17a0b41fbd78549276f | [] | no_license | tomasMasson/APOA1_evolution | fda87e2937c981e74dbfe7fa3c59d8cfe09be3c7 | fe6c8b0b91e71471a79e97f708c89787cbe93be3 | refs/heads/master | 2021-08-11T11:37:14.522677 | 2021-08-09T18:30:05 | 2021-08-09T18:30:05 | 252,469,838 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 1,038 | py | #!/usr/bin/env python3
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import argparse
def plot_dataset(dataframe):
sns.set(style="white")
sns.histplot(
dataframe['Position'],
color='#0571b0',
bins=20,
kde=False
)
df = dataframe[dataframe['Taxon'] == 'Mammalia']
sns.histplot(
df['Position'],
color='#e66101',
bins=20,
kde=False
)
plt.xlabel('Sequence Position')
plt.ylabel('# Amyloid Regions')
plt.savefig('amyloid_regions_distribution.svg')
return plt.show()
def argument_parser():
'''Command line argument parser.'''
parser = argparse.ArgumentParser()
parser.add_argument('dataset',
help='Dataset file in .csv format')
args = parser.parse_args()
return args.dataset
def main():
dataset = argument_parser()
df = pd.read_csv(dataset)
df.pipe(plot_dataset)
if __name__ == "__main__":
main()
| [
"tomasmasson0@gmail.com"
] | tomasmasson0@gmail.com |
8bb879a21d90fb799bcce0febe98dc47b9b63b7e | d373f4e1e112af74e1f6c96cf6dc37b2aa7ce05c | /ShortIT/asgi.py | 37d298533701fbfc14687b475c0d6fc9fe76ccba | [] | no_license | skyman503/Short-IT | a7545fa786b0a7e0cbffcba7ae760b542fed4d1e | 948985658506406a4a2e60a66cf40bf19c94a104 | refs/heads/master | 2022-11-09T13:16:42.429061 | 2020-06-25T21:32:21 | 2020-06-25T21:32:21 | 275,001,681 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 167 | py | import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'ShortIT.settings')
application = get_asgi_application()
| [
"karolsygiet@gmail.com"
] | karolsygiet@gmail.com |
c0b510a7ba1fba62afc49fc4616c8e867d73b2ad | d9b57163d87fc52a9247e67a9bfe6105d00291fd | /distilbert_model/train.py | 485fd003c7d12549e215eccd6e5f2303ee8b4980 | [] | no_license | andrewpeng02/imdb-sentiment | 498ce7772cad3cb61c0838985c28b90b3ab1431b | ab6b88795146f4957bd965f188321172c99673b6 | refs/heads/master | 2020-09-17T11:10:29.536675 | 2020-07-03T20:19:49 | 2020-07-03T20:19:49 | 224,083,922 | 1 | 1 | null | null | null | null | UTF-8 | Python | false | false | 3,295 | py | import click
from pathlib import Path
import time
from transformers import DistilBertForSequenceClassification
from torch.optim import Adam
import torch
from torch.utils.data import DataLoader
from distilbert_model.dataset import IMDBDataset
@click.command()
@click.argument('num_epochs', type=int, default=3)
@click.argument('seq_length', type=int, default=256)
@click.argument('batch_size', type=int, default=16)
@click.argument('lr_transformer', type=float, default=1e-5)
@click.argument('lr_classifier', type=float, default=1e-5)
@click.argument('eps', type=float, default=1e-8)
def main(**kwargs):
project_path = str(Path(__file__).resolve().parents[1])
train_dataset = IMDBDataset(project_path + '/data/train.csv', kwargs['seq_length'])
train_loader = DataLoader(train_dataset, batch_size=kwargs['batch_size'], shuffle=True, num_workers=4)
valid_dataset = IMDBDataset(project_path + '/data/validation.csv', kwargs['seq_length'])
valid_loader = DataLoader(valid_dataset, batch_size=kwargs['batch_size'], shuffle=True, num_workers=4)
print('Downloading the pretrained DistilBert model...')
model = DistilBertForSequenceClassification.from_pretrained('distilbert-base-uncased', num_labels=2).to('cuda')
lrs = [{'params': model.distilbert.parameters(), 'lr': kwargs['lr_transformer']},
{'params': model.pre_classifier.parameters()},
{'params': model.classifier.parameters()}]
optim = Adam(lrs, lr=kwargs['lr_classifier'], eps=kwargs['eps'])
print('Training...')
st = time.time()
train(train_loader, valid_loader, model, optim, kwargs['num_epochs'])
print(f'Training time: {time.time() - st}sec')
def train(train_loader, valid_loader, model, optim, num_epochs):
val_loss, val_acc = validate(valid_loader, model)
print(f'Val Loss: {val_loss} \t Val Acc: {val_acc}')
model.train()
for epoch in range(num_epochs):
total_loss = 0
for step, (seqs, labels) in enumerate(iter(train_loader)):
seqs = seqs.to('cuda')
labels = labels.to('cuda').long()
optim.zero_grad()
loss = model(seqs, labels=labels)[0]
loss.backward()
optim.step()
total_loss += loss.item()
if step % 250 == 249:
val_loss, val_acc = validate(valid_loader, model)
print(f'Epoch [{epoch + 1} / {num_epochs}] \t Step [{step + 1} / {len(train_loader)}] \t '
f'Train Loss: {total_loss / 250} \t Val Loss: {val_loss} \t Val Acc: {val_acc}')
total_loss = 0
def validate(valid_loader, model):
model.eval()
total_loss = 0
total_acc = 0
for seqs, labels in iter(valid_loader):
with torch.no_grad():
seqs = seqs.to('cuda')
labels = labels.to('cuda').long()
loss, outputs = model(seqs, labels=labels)
total_loss += loss.item()
total_acc += accuracy(outputs, labels)
model.train()
return total_loss / len(valid_loader), total_acc / len(valid_loader)
def accuracy(preds, labels):
preds = torch.argmax(preds, axis=1).flatten()
labels = labels.flatten()
return torch.sum(preds == labels).item() / len(labels)
if __name__ == "__main__":
main()
| [
"andrewpeng02@gmail.com"
] | andrewpeng02@gmail.com |
8e214ab9b8689ad45f45907a3b76296b579670ab | 159707c1ce30bcb9e08fe1df9dca25b7d6b7fe1a | /app/migrations/0001_initial.py | 1f48b7fc82985071cc9601b7a7a37e946ceb6833 | [
"MIT"
] | permissive | agucova/Coins | 031e5a08242a911266669cf5b06720b701b47456 | bd1cbf04516570c20eb1bc9eff62d50e607bbd53 | refs/heads/master | 2020-04-16T14:30:40.409362 | 2019-06-27T21:10:06 | 2019-06-27T21:10:06 | 165,669,607 | 0 | 0 | MIT | 2019-01-14T13:50:08 | 2019-01-14T13:50:07 | null | UTF-8 | Python | false | false | 4,543 | py | # -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
from django.conf import settings
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='Alumno',
fields=[
('id', models.AutoField(verbose_name='ID', primary_key=True, serialize=False, auto_created=True)),
('name', models.CharField(max_length=60)),
('coins', models.IntegerField(default=0)),
('gastado', models.IntegerField(default=0)),
('grupo', models.IntegerField(blank=True, null=True)),
('user', models.ForeignKey(to=settings.AUTH_USER_MODEL)),
],
),
migrations.CreateModel(
name='Bien',
fields=[
('id', models.AutoField(verbose_name='ID', primary_key=True, serialize=False, auto_created=True)),
('nombre', models.CharField(max_length=50)),
('valor', models.IntegerField(default=1)),
],
),
migrations.CreateModel(
name='Bloque',
fields=[
('idBloque', models.AutoField(primary_key=True, serialize=False)),
('dia', models.CharField(choices=[('21', 'Lunes 21'), ('22', 'Martes 22'), ('23', 'Miercoles 23'), ('24', 'Jueves 24'), ('25', 'Viernes 25')], max_length=2, default='22')),
('horas', models.CharField(choices=[('01', '14:00 - 14:15'), ('02', '14:15 - 14:30'), ('03', '14:30 - 14:45'), ('04', '14:45 - 15:00'), ('05', '15:00 - 15:15'), ('06', '15:15 - 15:30'), ('07', '15:30 - 15:45'), ('08', '15:45 - 16:00'), ('09', '16:00 - 16:15'), ('10', '16:15 - 16:30'), ('11', '16:30 - 16:45'), ('12', '16:45 - 17:00'), ('13', '17:00 - 17:15'), ('14', '17:15 - 17:30'), ('15', '17:30 - 17:45'), ('16', '17:45 - 18:00')], max_length=2, default='01')),
('valor', models.IntegerField(default=1)),
('estado', models.CharField(choices=[('0', 'Ausente'), ('1', 'Presente'), ('2', 'Comprado')], max_length=1, default='0')),
],
),
migrations.CreateModel(
name='Carga',
fields=[
('id', models.AutoField(verbose_name='ID', primary_key=True, serialize=False, auto_created=True)),
('carga', models.IntegerField()),
('asunto', models.TextField()),
('alumno', models.ForeignKey(to='app.Alumno')),
],
),
migrations.CreateModel(
name='Grupo',
fields=[
('nroGrupo', models.IntegerField(primary_key=True, serialize=False)),
('usr1', models.ForeignKey(to='app.Alumno', related_name='1+')),
('usr2', models.ForeignKey(to='app.Alumno', related_name='2+')),
('usr3', models.ForeignKey(to='app.Alumno', related_name='3+')),
('usr4', models.ForeignKey(to='app.Alumno', related_name='4+')),
('usr5', models.ForeignKey(blank=True, to='app.Alumno', null=True, related_name='5+')),
],
),
migrations.CreateModel(
name='Historial',
fields=[
('id', models.AutoField(verbose_name='ID', primary_key=True, serialize=False, auto_created=True)),
('asunto', models.TextField()),
('valor', models.IntegerField()),
('user', models.ForeignKey(to=settings.AUTH_USER_MODEL)),
],
),
migrations.CreateModel(
name='Profesor',
fields=[
('id', models.AutoField(verbose_name='ID', primary_key=True, serialize=False, auto_created=True)),
('name', models.CharField(max_length=60)),
('coins', models.IntegerField(default=0)),
('user', models.ForeignKey(to=settings.AUTH_USER_MODEL)),
],
),
migrations.AddField(
model_name='carga',
name='profesor',
field=models.ForeignKey(to='app.Profesor'),
),
migrations.AddField(
model_name='bloque',
name='grupo',
field=models.ForeignKey(blank=True, null=True, to='app.Grupo'),
),
migrations.AddField(
model_name='bloque',
name='profe',
field=models.ForeignKey(to='app.Profesor'),
),
]
| [
"andrea.benavidesj@gmail.com"
] | andrea.benavidesj@gmail.com |
ac9bc264069f3b02a22624cafb6308e8ec8ae4bf | 79e19819aec49b500825f82a7de149eb6a0ba81d | /leetcode/303.py | f778311ff580a2a44b295e3a1440ef7bab29626f | [] | no_license | seoyeonhwng/algorithm | 635e5dc4a2e9e1c50dc0c75d9a2a334110bb8e26 | 90406ee75de69996e666ea505ff5d9045c2ad941 | refs/heads/master | 2023-05-03T16:51:48.454619 | 2021-05-26T00:54:40 | 2021-05-26T00:54:40 | 297,548,218 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 558 | py | class NumArray:
def __init__(self, nums: List[int]):
self.nums = nums
if nums:
self.memo()
def memo(self):
self.dp = [0] * len(self.nums)
self.dp[0] = self.nums[0]
for i in range(1, len(self.nums)):
self.dp[i] = self.dp[i-1] + self.nums[i]
def sumRange(self, i: int, j: int) -> int:
return self.dp[j] - self.dp[i-1] if i > 0 else self.dp[j]
# Your NumArray object will be instantiated and called as such:
# obj = NumArray(nums)
# param_1 = obj.sumRange(i,j) | [
"seoyeon@nowbusking.com"
] | seoyeon@nowbusking.com |
723c8b2001a43c9aa112cd5eba3a02f98544b6f5 | 58ade65dffc7cbe103d93d7c769096a20d9f9815 | /src/smach_based_introspection_framework/online_part/data_collection/StoreVectorToRedisProc.py | d94e5e8102adc6af5a29654d7877be2d0b34a276 | [
"BSD-3-Clause"
] | permissive | birlrobotics/smach_based_introspection_framework | 2cff69ecec030a5b5046dea99f9e15105f52361b | f16742339cddfc86effba4dbf6e5062304704b89 | refs/heads/master | 2021-05-09T12:02:26.946473 | 2019-05-29T02:46:47 | 2019-05-29T02:46:47 | 119,001,821 | 7 | 1 | null | 2018-07-05T04:58:40 | 2018-01-26T03:37:58 | Python | UTF-8 | Python | false | false | 1,512 | py | import multiprocessing
from ConvertTagTopicToInterestedVectorProc import (
data_frame_idx,
smach_state_idx,
data_header_idx,
)
class StoreVectorToRedisProc(multiprocessing.Process):
def __init__(
self,
com_queue,
node_name="StoreVectorToRedisProc_node",
):
multiprocessing.Process.__init__(self)
self.com_queue = com_queue
self.node_name = node_name
def run(self):
import rospy
rospy.init_node(self.node_name, anonymous=True)
try:
import redis
import Queue
r = redis.Redis(host='localhost', port=6379, db=0)
rospy.loginfo('delete key \"tag_multimodal_msgs\": %s'%r.delete("tag_multimodal_msgs"))
while not rospy.is_shutdown():
try:
latest_data_tuple = self.com_queue.get(timeout=1)
except Queue.Empty:
continue
except KeyboardInterrupt:
break
data_frame = latest_data_tuple[data_frame_idx]
smach_state = latest_data_tuple[smach_state_idx]
data_header = latest_data_tuple[data_header_idx]
score = data_header.stamp.to_sec()
value = data_frame
r.zadd("tag_multimodal_msgs", value, score)
except Exception as e:
rospy.logerr("StoreVectorToRedisProc error: %s"%e)
rospy.loginfo("StoreVectorToRedisProc exits")
| [
"sk.law.lsq@gmail.com"
] | sk.law.lsq@gmail.com |
eb7311f8345d96db7e10cd248adddd89b7a807db | 3c1a2da3cf337ce7e19725feb2ab5940116e4e03 | /datasets/csvlist.py | c56cb72e7fc8e504cf92a6de043f5250e69ffc2d | [] | no_license | jiazhi412/DebFace | c8e4c5d4120f7013c1795e6dac7639629f3a3b33 | 2f74570a73dd4c252805da47ae18ef3915c42196 | refs/heads/master | 2023-08-24T21:48:10.961338 | 2021-10-20T19:16:49 | 2021-10-20T19:16:49 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,590 | py | # filelist.py
import os
import csv
import math
import torch
from random import shuffle
import torch.utils.data as data
import datasets.loaders as loaders
import numpy as np
from PIL import Image
import pdb
class CSVListLoader(data.Dataset):
def __init__(self, ifile, root=None,
transform=None, loader='loader_image',
):
self.root = root
self.ifile = ifile
self.transform = transform
if loader is not None:
self.loader = getattr(loaders, loader)
self.nattributes = 0
datalist = []
classname = []
if ifile is not None:
with open(ifile, 'r') as csvfile: # , encoding='utf-8', errors='ignore'
# reader = csv.reader(csvfile, delimiter='\t')
lines = csvfile.readlines()
reader = [x.rstrip('\n').split('\t') for x in lines]
for i,row in enumerate(reader):
if self.nattributes <= len(row):
self.nattributes = len(row)
if 'NaN' in row:
idx = [x[0] for x in enumerate(row) if x[1] == 'NaN']
for j in idx:
row[j] = -1
datalist.append(row)
############## ID!!!! ##############
classname.append(row[4]) # ID!
############## ID!!!! ##############
csvfile.close()
self.data = datalist
self.classname = list(set(classname))
def __len__(self):
return len(self.data)
def __getitem__(self, index):
if len(self.data) > 0:
if self.root is not None:
path = os.path.join(self.root, self.data[index][0])
else:
path = self.data[index][0]
image = self.loader(path)
attributes = self.data[index]
fmetas = attributes[0]
attributes = attributes[1:]
############## ID!!!! ##############
label = self.classname.index(attributes[3])
############## ID!!!! ##############
# attributes = [int(x) for x in attributes]
if len(attributes) < self.nattributes:
length = self.nattributes - len(attributes)
for i in range(length):
attributes.append(-1)
if self.transform is not None:
image = self.transform(image)
# attributes = torch.Tensor(attributes)
return image, label, attributes, fmetas
| [
"gongsixu@prip1.cse.msu.edu"
] | gongsixu@prip1.cse.msu.edu |
338551c4bcc5024d0a73e510ab9658dc2975f19f | 34af9eee717eaf205265444bfd1d39c2f0675353 | /src/users/auth_backend.py | 362b149c43831c99fe39e34b215ba6ddab274344 | [] | no_license | mohanj1919/django_cookiecutter-rest_api | e48ee7bf330004026cd6a5be6323902a2da474c8 | f9c02043dba21aa7c810340b8816237cdd504052 | refs/heads/master | 2020-09-16T07:15:19.658456 | 2017-08-05T07:25:57 | 2017-08-05T07:25:57 | 94,485,101 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 557 | py |
from django.contrib.auth import get_user_model
class EmailBackend(object):
def get_user(self, username=None):
UserModel = get_user_model()
try:
user = UserModel.objects.get(email=username)
return user
except UserModel.DoesNotExist:
return None
def authenticate(self, username=None, password=None, **kwargs):
user = self.get_user(username)
if user is not None and user.check_password(password) and user.is_allowed_to_login():
return user
return None
| [
"mohankumar1919@gmail.com"
] | mohankumar1919@gmail.com |
507866f7c228417366dd16ecd01240835de10707 | ffe26a7490dfb5f696e2fb7a6681e7a077ee8e03 | /sys_clock.py | 5127b7957cf2b37630791aa9e44ff4956702a642 | [] | no_license | lcp-team-fdg/RPi1Image | 1f00e5374fa62dddc4808130f43abd96d00da02e | 9967e565006ccd979216123ecc72f094563ed640 | refs/heads/master | 2020-05-30T12:52:50.335710 | 2019-06-08T21:47:30 | 2019-06-08T21:47:30 | 189,746,316 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,106 | py | """
GS_timing.py
-create some low-level Arduino-like millis() (milliseconds) and micros()
(microseconds) timing functions for Python
By Gabriel Staples
http://www.ElectricRCAircraftGuy.com
-click "Contact me" at the top of my website to find my email address
Started: 11 July 2016
Updated: 13 Aug 2016
History (newest on top):
20160813 - v0.2.0 created - added Linux compatibility, using ctypes, so that it's compatible with pre-Python 3.3 (for Python 3.3 or later just use the built-in time functions for Linux, shown here: https://docs.python.org/3/library/time.html)
-ex: time.clock_gettime(time.CLOCK_MONOTONIC_RAW)
20160711 - v0.1.0 created - functions work for Windows *only* (via the QPC timer)
References:
WINDOWS:
-personal (C++ code): GS_PCArduino.h
1) Acquiring high-resolution time stamps (Windows)
-https://msdn.microsoft.com/en-us/library/windows/desktop/dn553408(v=vs.85).aspx
2) QueryPerformanceCounter function (Windows)
-https://msdn.microsoft.com/en-us/library/windows/desktop/ms644904(v=vs.85).aspx
3) QueryPerformanceFrequency function (Windows)
-https://msdn.microsoft.com/en-us/library/windows/desktop/ms644905(v=vs.85).aspx
4) LARGE_INTEGER union (Windows)
-https://msdn.microsoft.com/en-us/library/windows/desktop/aa383713(v=vs.85).aspx
-*****https://stackoverflow.com/questions/4430227/python-on-win32-how-to-get-
absolute-timing-cpu-cycle-count
LINUX:
-https://stackoverflow.com/questions/1205722/how-do-i-get-monotonic-time-durations-in-python
"""
import ctypes, os
# Constants:
VERSION = '0.2.0'
# -------------------------------------------------------------------
# FUNCTIONS:
# -------------------------------------------------------------------
# OS-specific low-level timing functions:
if (os.name=='nt'):
# for Windows:
def micros():
"return a timestamp in microseconds (us)"
tics = ctypes.c_int64()
freq = ctypes.c_int64()
# get ticks on the internal ~2MHz QPC clock
ctypes.windll.Kernel32.QueryPerformanceCounter(ctypes.byref(tics))
# get the actual freq. of the internal ~2MHz QPC clock
ctypes.windll.Kernel32.QueryPerformanceFrequency(ctypes.byref(freq))
t_us = tics.value*1e6/freq.value
return t_us
def millis():
"return a timestamp in milliseconds (ms)"
tics = ctypes.c_int64()
freq = ctypes.c_int64()
# get ticks on the internal ~2MHz QPC clock
ctypes.windll.Kernel32.QueryPerformanceCounter(ctypes.byref(tics))
# get the actual freq. of the internal ~2MHz QPC clock
ctypes.windll.Kernel32.QueryPerformanceFrequency(ctypes.byref(freq))
t_ms = tics.value*1e3/freq.value
return t_ms
elif (os.name=='posix'):
# for Linux:
# Constants:
CLOCK_MONOTONIC_RAW = 4
# see <linux/time.h> here: https://github.com/torvalds/linux/blob/master/include/uapi/linux/time.h
# prepare ctype timespec structure of {long, long}
class timespec(ctypes.Structure):
_fields_ =\
[
('tv_sec', ctypes.c_long),
('tv_nsec', ctypes.c_long)
]
# Configure Python access to the clock_gettime C library, via ctypes:
# Documentation:
# -ctypes.CDLL: https://docs.python.org/3.2/library/ctypes.html
# -librt.so.1 with clock_gettime: https://docs.oracle.com/cd/E36784_01/html/E36873/librt-3lib.html #-
# -Linux clock_gettime(): http://linux.die.net/man/3/clock_gettime
librt = ctypes.CDLL('librt.so.1', use_errno=True)
clock_gettime = librt.clock_gettime
# specify input arguments and types to the C clock_gettime() function
# (int clock_ID, timespec* t)
clock_gettime.argtypes = [ctypes.c_int, ctypes.POINTER(timespec)]
def monotonic_time():
"return a timestamp in seconds (sec)"
t = timespec()
# (Note that clock_gettime() returns 0 for success, or -1 for failure, in
# which case errno is set appropriately)
# -see here: http://linux.die.net/man/3/clock_gettime
if clock_gettime(CLOCK_MONOTONIC_RAW , ctypes.pointer(t)) != 0:
#if clock_gettime() returns an error
errno_ = ctypes.get_errno()
raise OSError(errno_, os.strerror(errno_))
return t.tv_sec + t.tv_nsec*1e-9 #sec
def micros():
"return a timestamp in microseconds (us)"
return monotonic_time()*1e6 #us
def millis():
"return a timestamp in milliseconds (ms)"
return monotonic_time()*1e3 #ms
# Other timing functions:
def delay(delay_ms):
"delay for delay_ms milliseconds (ms)"
t_start = millis()
while (millis() - t_start < delay_ms):
pass #do nothing
return
def delayMicroseconds(delay_us):
"delay for delay_us microseconds (us)"
t_start = micros()
while (micros() - t_start < delay_us):
pass #do nothing
return
# -------------------------------------------------------------------
# EXAMPLES:
# -------------------------------------------------------------------
# Only executute this block of code if running this module directly,
# *not* if importing it
# -see here: http://effbot.org/pyfaq/tutor-what-is-if-name-main-for.htm
if __name__ == "__main__": #if running this module as a stand-alone program
#print loop execution time 100 times, using micros()
tStart = micros() #us
for x in range(0, 100):
tNow = micros() #us
dt = tNow - tStart #us; delta time
tStart = tNow #us; update
print("dt(us) = " + str(dt))
#print loop execution time 100 times, using millis()
print("\n")
tStart = millis() #ms
for x in range(0, 100):
tNow = millis() #ms
dt = tNow - tStart #ms; delta time
tStart = tNow #ms; update
print("dt(ms) = " + str(dt))
#print a counter once per second, for 5 seconds, using delay
print("\nstart")
for i in range(1,6):
delay(1000)
print(i)
#print a counter once per second, for 5 seconds, using delayMicroseconds
print("\nstart")
for i in range(1,6):
delayMicroseconds(1000000)
print(i) | [
"kroelld.96@gmail.com"
] | kroelld.96@gmail.com |
7b5ebbb6b02299b7f47b6077cba156000ceeb9c3 | 8efe9a6c9489d798b5f5b610eb531d86924a1548 | /src/wix/urls.py | c74a0f134076e607c3999dbed8538b6643de2a2f | [] | no_license | MarekBiczysko/naklisze_public | e8e6f7e61cdb83b74ea68862b40c061c0253767b | e53c0e8fefffbcfc3a8859976eb7b81cf6270847 | refs/heads/master | 2022-12-12T02:27:09.824803 | 2019-07-23T10:54:47 | 2019-07-23T10:54:47 | 198,410,666 | 0 | 0 | null | 2022-12-08T01:03:08 | 2019-07-23T10:46:57 | Python | UTF-8 | Python | false | false | 288 | py | from django.views.generic import RedirectView
from django.conf.urls import url
from .views import wix_page
urlpatterns = [
# url(r'^$', RedirectView.as_view(url='https://biczysko.wix.com/foto')),
url(r'^$', wix_page, name='wix'),
url(r'^', RedirectView.as_view(url='/')),
]
| [
"marek.biczysko@stxnext.pl"
] | marek.biczysko@stxnext.pl |
220101fd40320ea39f01df910b25061d9e52a33b | e4ea1f2ada2da0e671e571355a5526fbdf9614a4 | /tile.py | a7d9f1f29ecbef8484a7fa8da4ddc7eca87dd337 | [] | no_license | youndukn/LASTRA | 2143ceaf94d94f11112361bb72f2c857d7399b76 | ca7f843949615ef980f51e58cc941c50632b51fc | refs/heads/master | 2021-01-19T00:31:46.178525 | 2019-01-28T01:54:21 | 2019-01-28T01:54:21 | 87,180,981 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 16,409 | py | import tkinter as tk
import random
from tkinter import messagebox
import time
from astra_rd import AstraRD
import keras.backend as K
import numpy as np
from keras.layers import Input, Add, Dense, Activation, Concatenate, ZeroPadding2D, BatchNormalization, Flatten, Conv2D,GlobalAveragePooling2D, \
Conv3D, AveragePooling2D, MaxPooling2D, Reshape, Multiply, LeakyReLU, LSTM, GRU, Lambda,GlobalAveragePooling3D, MaxPooling1D, MaxPooling3D,ZeroPadding3D
from keras.initializers import glorot_uniform
from keras.models import Model, load_model, Sequential
from keras.optimizers import Adam
import os
os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"]="2"
def slicer(x_loc, y_loc):
def func(x):
return x[:,x_loc,y_loc,:]
return Lambda(func)
def gSlicer():
def func(x):
return x[:,:8,:8,:]
return Lambda(func)
def gSlicer3D():
def func(x):
return x[:,:8,:8,:, :]
return Lambda(func)
def nodeColPermute3D():
def func(x):
x = K.permute_dimensions(x[:, 0:1, :, :, :], (0, 2, 1, 3, 4))
return x
return Lambda(func)
def nodeRowPermute3D():
def func(x):
x = K.permute_dimensions(x[:, :, 0:1, :, :], (0, 2, 1, 3, 4))
return x
return Lambda(func)
def nodeCen3D():
def func(x):
return x[:,0:1, 0:1, :, :]
return Lambda(func)
def assColPermute3D():
def func(x):
x = K.permute_dimensions(x[:, 1:2, :, :, :], (0, 2, 1, 3, 4))
return x
return Lambda(func)
def assRowPermute3D():
def func(x):
x = K.permute_dimensions(x[:, :, 1:2, :, :], (0, 2, 1, 3, 4))
return x
return Lambda(func)
def assCen3D():
def func(x):
return x[:,1:2, 1:2, :, :]
return Lambda(func)
def convolution_block_se_bn_jin_3d_iquad(X, f, filters, stage, block, s=2):
conv_name_base = 'res' + str(stage) + block + '_branch'
bn_name_base = 'bn' + str(stage) + block + '_branch'
F1, F2, F3 = filters
X_shortcut = X
X = Conv3D(filters=F1, kernel_size=(1, 1, 1), strides=(s, s, s), padding='valid',
kernel_initializer=glorot_uniform(seed=0))(X)
X = BatchNormalization()(X)
X = Activation('relu')(X)
X = ZeroPadding3D(padding=((0, 1), (0, 1), (1, 1)))(X)
X_Col = nodeColPermute3D()(X)
X_Row = nodeRowPermute3D()(X)
X_Cen = nodeCen3D()(X)
X_Row = Concatenate(axis=2)([X_Cen, X_Row])
X = Concatenate(axis=2)([X_Col, X])
X = Concatenate(axis=1)([X_Row, X])
X = Conv3D(filters=F2, kernel_size=(f, 1, 1), strides=(1, 1, 1), padding='valid',
kernel_initializer=glorot_uniform(seed=0))(X)
X = BatchNormalization()(X)
X = Activation('relu')(X)
X = Conv3D(filters=F2, kernel_size=(1, f, 1), strides=(1, 1, 1), padding='valid',
kernel_initializer=glorot_uniform(seed=0))(X)
X = BatchNormalization()(X)
X = Activation('relu')(X)
X = Conv3D(filters=F2, kernel_size=(1, 1, f), strides=(1, 1, 1), padding='valid',
kernel_initializer=glorot_uniform(seed=0))(X)
X = BatchNormalization()(X)
X = Activation('relu')(X)
X = Conv3D(filters=F3, kernel_size=(1, 1, 1), strides=(1, 1, 1), padding='valid',
kernel_initializer=glorot_uniform(seed=0))(X)
X = BatchNormalization()(X)
se = GlobalAveragePooling3D(name='pool' + bn_name_base + '_gap')(X)
se = Dense(F3*2, activation='relu', name = 'fc' + bn_name_base + '_sqz')(se)
se = Dense(F3, activation='sigmoid', name = 'fc' + bn_name_base + '_exc')(se)
se = Reshape([1, 1, 1, F3])(se)
X = Multiply(name='scale' + bn_name_base)([X, se])
X_shortcut = Conv3D(filters=F3, kernel_size=(1, 1, 1), strides=(s, s, s), padding='valid',
kernel_initializer=glorot_uniform(seed=0))(X_shortcut)
X_shortcut = BatchNormalization()(X_shortcut)
X = Add()([X_shortcut, X])
X = Activation('relu')(X)
return X
def convolution_block_resize_3d_wopin_iquad(X,f, filters, stage, block, s=2):
conv_name_base = 'res' + str(stage) + block + '_branch'
bn_name_base = 'bn' + str(stage) + block + '_branch'
F1, F2, F3= filters
X = ZeroPadding3D(padding=((0, 1), (0, 1), (0, 0)))(X)
X_Col = nodeColPermute3D()(X)
X_Row = nodeRowPermute3D()(X)
X_Cen = nodeCen3D()(X)
X_Row = Concatenate(axis=2)([X_Cen, X_Row])
X = Concatenate(axis=2)([X_Col, X])
X = Concatenate(axis=1)([X_Row, X])
X = Conv3D(filters=F1, kernel_size=(2, 2, 1), strides=(2, 2, 1), padding='valid',
kernel_initializer=glorot_uniform(seed=0))(X)
X = BatchNormalization()(X)
X = Activation('relu')(X)
X = gSlicer3D()(X)
X = ZeroPadding3D(padding=((0, 1), (0, 1), (0, 0)))(X)
X_Col = assColPermute3D()(X)
X_Row = assRowPermute3D()(X)
X_Cen = assCen3D()(X)
X_Row = Concatenate(axis=2)([X_Cen, X_Row])
X = Concatenate(axis=2)([X_Col, X])
X = Concatenate(axis=1)([X_Row, X])
X = Conv3D(filters=F2, kernel_size=(f, f, f), strides=(1, 1, 1), padding='valid',
kernel_initializer=glorot_uniform(seed=0))(X)
X = BatchNormalization()(X)
X = Activation('relu')(X)
X = Conv3D(filters=F3, kernel_size=(1, 1, 1), strides=(1, 1, 1), padding='valid',
kernel_initializer=glorot_uniform(seed=0))(X)
X = Activation('relu')(X)
return X
def convolution_block_resize_3d_wopin_iquad_all(X,f, filters, stage, block, s=2):
conv_name_base = 'res' + str(stage) + block + '_branch'
bn_name_base = 'bn' + str(stage) + block + '_branch'
F1, F2, F3= filters
X = ZeroPadding3D(padding=((0, 1), (0, 1), (0, 0)))(X)
X_Col = nodeColPermute3D()(X)
X_Row = nodeRowPermute3D()(X)
X_Cen = nodeCen3D()(X)
X_Row = Concatenate(axis=2)([X_Cen, X_Row])
X = Concatenate(axis=2)([X_Col, X])
X = Concatenate(axis=1)([X_Row, X])
X = Conv3D(filters=F1, kernel_size=(2, 2, 1), strides=(2, 2, 1), padding='valid',
kernel_initializer=glorot_uniform(seed=0))(X)
X = BatchNormalization()(X)
X = Activation('relu')(X)
X = gSlicer3D()(X)
X = ZeroPadding3D(padding=((0, 1), (0, 1), (1, 1)))(X)
X_Col = assColPermute3D()(X)
X_Row = assRowPermute3D()(X)
X_Cen = assCen3D()(X)
X_Row = Concatenate(axis=2)([X_Cen, X_Row])
X = Concatenate(axis=2)([X_Col, X])
X = Concatenate(axis=1)([X_Row, X])
X = Conv3D(filters=F2, kernel_size=(f, 1, 1), strides=(1, 1, 1), padding='valid',
kernel_initializer=glorot_uniform(seed=0))(X)
X = BatchNormalization()(X)
X = Activation('relu')(X)
X = Conv3D(filters=F2, kernel_size=(1, f, 1), strides=(1, 1, 1), padding='valid',
kernel_initializer=glorot_uniform(seed=0))(X)
X = BatchNormalization()(X)
X = Activation('relu')(X)
X = Conv3D(filters=F2, kernel_size=(1, 1, f), strides=(1, 1, 1), padding='valid',
kernel_initializer=glorot_uniform(seed=0))(X)
X = BatchNormalization()(X)
X = Activation('relu')(X)
X = Conv3D(filters=F3, kernel_size=(1, 1, 1), strides=(1, 1, 1), padding='valid',
kernel_initializer=glorot_uniform(seed=0))(X)
X = Activation('relu')(X)
return X
def ResNetI7_MD_BN_BU_AT_MATRIX_24_3d_dense_iquad(input_shape=(64, 64, 3, 3), classes=6):
X_input = Input(input_shape)
stage = 0;
X = X_input
for i in range(5):
stage_filters = [64, 64, 256]
X = convolution_block_se_bn_jin_3d_iquad(X, f=3, filters=stage_filters, stage=stage, block='ca_{}'.format(i), s=1)
X = Concatenate()([X, X_input])
stage = stage + 1
for i in range(15):
stage_filters = [64, 64, 256]
X = convolution_block_se_bn_jin_3d_iquad(X, f=3, filters=stage_filters, stage=stage, block='ca_{}'.format(i), s=1)
X = Concatenate()([X, X_input])
stage = stage + 1
outputs = []
for i in range(24):
pd_X = X
stage_filters = [int(256/2), 64, 1]
pd_X = convolution_block_resize_3d_wopin_iquad(pd_X, f=3, filters=stage_filters, stage=stage, block='ca_{}'.format(i), s=1)
#pd_X = MaxPooling2D(pool_size=(8, 8))(pd_X)
pd_X = Flatten()(pd_X)
outputs.append(pd_X)
model = Model(inputs=[X_input], outputs=outputs, name="ResNetCen")
return model
def ResNetI7_MD_BN_BU_AT_MATRIX_24_3d_dense_iquad_large_all(input_shape=(64, 64, 3, 3), classes=6):
X_input = Input(input_shape)
stage = 0;
X = X_input
for i in range(15):
stage_filters = [64, 64, 256]
X = convolution_block_se_bn_jin_3d_iquad(X, f=3, filters=stage_filters, stage=stage, block='ca_{}'.format(i), s=1)
X = Concatenate()([X, X_input])
stage = stage + 1
outputs = []
for i in range(classes):
pd_X = X
for j in range(2):
stage_filters = [64, 64, 256]
pd_X = convolution_block_se_bn_jin_3d_iquad(pd_X, f=3, filters=stage_filters, stage=stage,
block='ca_{}'.format(i), s=1)
pd_X = Concatenate()([pd_X, X_input])
stage = stage + 1
stage_filters = [int(256/2), 64, 1]
pd_X = convolution_block_resize_3d_wopin_iquad_all(pd_X, f=3, filters=stage_filters, stage=stage, block='ca_{}'.format(i), s=1)
pd_X = Flatten()(pd_X)
outputs.append(pd_X)
model = Model(inputs=[X_input], outputs=outputs, name="ResNetCen")
return model
def custom_loss_test(y_true,y_pred):
#y_mult = y_true[:,225:]
return K.mean(K.square(((y_pred - y_true))))
class MemoryTile:
def __init__(self, parent, calculated, predicted, cross_section, model):
self.max_row = 8
self.max_col = 8
self.parent = parent
self.calculated = calculated
self.predicted = predicted
self.cross_section = cross_section
self.model = model
self.index = 0
self.buttons = [[tk.Button(root,
width=6,
height=4,
command=lambda row=row, col=col: self.choose_tile(row, col)
) for col in range(self.max_col)] for row in range(self.max_row)]
for row in range(self.max_row):
for column in range(self.max_col):
self.buttons[row][column].grid(row=row, column=column)
self.first = None
self.draw_board()
def draw_board(self):
for row, row_buttons in enumerate(self.buttons):
for col, button in enumerate(row_buttons):
if self.calculated[row][col][self.index] == 0 and self.predicted[row][col][self.index] == 0:
cal_pre = ""
mycolor = "white"
else:
mycolor = '#%02x%02x%02x' % (0, 0, 256-int(self.calculated[row][col][self.index]/3*256))
cal_pre = "{:0.2f}\n{:0.2f}\n{:0.2f}".format(self.calculated[row][col][self.index],
self.predicted[row][col][self.index],
abs(self.calculated[row][col][self.index]-self.predicted[row][col][self.index]))
button.config(text=cal_pre, fg='white', font=('Helvetica', '14'), bg=mycolor, state=tk.NORMAL)
self.buttons[0][0].config(state=tk.DISABLED)
self.start_time = time.monotonic()
def choose_tile(self, row, col):
self.index += 1
self.parent.after(30, self.draw_board)
"""
if not self.first:
self.buttons[row][col].config(state=tk.DISABLED)
self.first = (row, col)
else:
first_row, first_col = self.first
self.buttons[first_row][first_col].config(state=tk.NORMAL)
first_row = first_row*2-1
first_col = first_col*2-1
first_row1 = first_row*2+1
first_col1 = first_col*2+1
if first_row == -1:
first_row = 0
first_row1 = 1
if first_col == -1:
first_col = 0
first_col1 = 1
row = row*2-1
col = col*2-1
row1 = row*2+1
col1 = col*2+1
if row == -1:
row = 0
row1 = 1
if col == -1:
col = 0
col1 = 1
first_lp = self.cross_section[0:1, first_row:first_row1, first_col:first_col1, :, :]
self.cross_section[0:1, first_row:first_row1,first_col:first_col1, :, :] = \
self.cross_section[0:1, row:row1, col:col1, :, :]
self.cross_section[0:1, row:row1, col:col1, :, :] = first_lp
readout_t0 = self.model.predict(self.cross_section)
self.predicted = readout_t0[0][0].reshape(8, 8)
self.first = None
self.parent.after(300, self.draw_board)
"""
#Input deck
file_name_load ="averaged_iquad_wopin_fxy_3d_conv"
file_name_load ="iquad_wopin_fxy_3d_conv"
file_name_load ="all_1_large_iquad_wopin_fxy_3d_conv"
astra = AstraRD("/home/youndukn/Plants/1.4.0/ucn5/c16/depl/022_astra_u516_nep_depl.inp",
main_directory="/home/youndukn/Plants/1.4.0/ucn5/c16/depl/", thread_id=0)
cross_set = astra.get_cross_set()
s_batch = cross_set[0].iinput3n_tensor_full
if file_name_load == "averaged_iquad_wopin_fxy_3d_conv":
calculated = cross_set[0].peak_tensor_full[-10:-2, -10:-2, :]
calculated = np.amax(calculated, axis=2)
model = ResNetI7_MD_BN_BU_AT_MATRIX_24_3d_dense_iquad((17, 17, 3, 5), classes=1)
model.summary()
model.compile(loss=custom_loss_test, optimizer=Adam(lr=0.0000025), metrics=['accuracy'])
model.load_weights("{}.hdf5".format(file_name_load))
first = [9.05, 6.19, 2.86, 12.38, 7.62, 20, 18.1, 18.1, 20]
second = [20, 18.1, 18.1, 20, 20, 18.1, 18.1, 20]
third = [18.1, 20, 18.1, 20, 7.62, 12.38, 2.86, 6.19, 9.05]
first_sum = 114.3
second_sum = 152.4
third_sum = 114.3
first_batch = s_batch[-19:-2, -19:-2, 0:1, :] * first[0]
for xxx in range(1, 9):
xxx1 = xxx - 0
first_batch[:, :, 0, :] += s_batch[-19:-2, -19:-2, xxx, :] * first[xxx1]
first_batch /= first_sum
second_batch = s_batch[-19:-2, -19:-2, 9:10, :] * second[0]
for xxx in range(10, 17):
xxx1 = xxx - 9
second_batch[:, :, 0, :] += s_batch[-19:-2, -19:-2, xxx, :] * second[xxx1]
second_batch /= second_sum
third_batch = s_batch[-19:-2, -19:-2, 17:18, :] * third[0]
for xxx in range(18, 26):
xxx1 = xxx - 17
third_batch[:, :, 0, :] += s_batch[-19:-2, -19:-2, xxx, :] * third[xxx1]
third_batch /= third_sum
s_batch = np.concatenate(
(first_batch,
second_batch,
third_batch), axis=-2)
elif file_name_load == "all_1_large_iquad_wopin_fxy_3d_conv":
calculated = cross_set[0].pp3d_tensor_full[-10:-2, -10:-2, 6:20, :]
for burnup in cross_set:
calculated = np.concatenate((calculated,burnup.pp3d_tensor_full[-10:-2, -10:-2, 6:20, :]), axis=3)
calculated = np.amax(calculated, axis=3)
model = ResNetI7_MD_BN_BU_AT_MATRIX_24_3d_dense_iquad_large_all((17, 17, 14, 5), classes=1)
model.summary()
model.compile(loss=custom_loss_test, optimizer=Adam(lr=0.0000025), metrics=['accuracy'])
model.load_weights("{}.hdf5".format(file_name_load))
s_batch = s_batch[-19:-2, -19:-2, 6:20, :]
else:
calculated = cross_set[0].peak_tensor_full[-10:-2, -10:-2, :]
calculated = np.amax(calculated, axis=2)
model = ResNetI7_MD_BN_BU_AT_MATRIX_24_3d_dense_iquad((17, 17, 3, 5), classes=1)
model.summary()
model.compile(loss=custom_loss_test, optimizer=Adam(lr=0.0000025), metrics=['accuracy'])
model.load_weights("{}.hdf5".format(file_name_load))
s_batch = np.concatenate(
(s_batch[-19:-2, -19:-2, 5:5 + 1, :],
(s_batch[-19:-2, -19:-2, 12:12 + 1, :] + s_batch[-19:-2, -19:-2, 13:13 + 1, :]) / 2,
s_batch[-19:-2, -19:-2, 20:21, :]), axis=-2)
s_batch = np.expand_dims(s_batch, axis=0)
readout_t0 = model.predict(s_batch)
predicted = readout_t0[0].reshape(8,8,14)
root = tk.Tk()
memory_tile = MemoryTile(root, calculated, predicted, s_batch, model)
memory_tile.calculated = calculated
memory_tile.predicted = predicted
memory_tile.draw_board()
root.mainloop() | [
"Whites11!"
] | Whites11! |
61abe84b1c8861332157ee57244832fe731b1498 | f9bcdd8fe51e94b884752574229bc592a84be6bd | /python/315_Count_of_Smaller_Numbers_After_Self.py | 33e899cb414d1e0faa68834085f58c7d725813e5 | [] | no_license | HankerZheng/LeetCode-Problems | cf46a24444cfc3e6bcff38c10a5bb5945e410b5b | d308e0e41c288f23a846b8505e572943d30b1392 | refs/heads/master | 2021-01-12T17:49:40.072069 | 2017-08-17T04:37:20 | 2017-08-17T04:37:20 | 69,397,987 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,656 | py | # You are given an integer array nums and you have to return a new counts array. The counts array has the property where counts[i] is the number of smaller elements to the right of nums[i].
# Example:
# Given nums = [5, 2, 6, 1]
# To the right of 5 there are 2 smaller elements (2 and 1).
# To the right of 2 there is only 1 smaller element (1).
# To the right of 6 there is 1 smaller element (1).
# To the right of 1 there is 0 smaller element.
# Return the array [2, 1, 1, 0].
class TreeNode(object):
def __init__(self, val):
self.val = val
self.left = None
self.right = None
self.smallerCnt = 0
self.selfCnt = 1
def insert(self, val):
cnt = 0
tmp = self
while tmp:
if val < tmp.val:
tmp.smallerCnt += 1
if not tmp.left:
tmp.left = TreeNode(val)
break
tmp = tmp.left
elif val > tmp.val:
cnt += tmp.smallerCnt + tmp.selfCnt
if not tmp.right:
tmp.right = TreeNode(val)
break
tmp = tmp.right
else:
tmp.selfCnt += 1
cnt += tmp.smallerCnt
break
return cnt
class Solution(object):
def countSmaller(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
if len(nums) <= 1: return [0] * len(nums)
ans = [0]
dataTree = TreeNode(nums[-1])
for num in nums[-2::-1]:
ans.insert(0,dataTree.insert(num))
return ans | [
"zhenghan991@gmail.com"
] | zhenghan991@gmail.com |
7498608177b6c5a40ca374cdbcc9f21fd5298be9 | b3e6c46241dc393214b17d58677a7869e7e4ac9a | /gui.py | 8db260ac6a582d015f0a5f1777a40bde9610a878 | [] | no_license | Bhawna4tech/Smart-Audio-Book-Reader | 72cc4b4ed8c00b187c52ab6a5ed220c8e75c33ed | 9d70992c3e0d506b801696901cea5c35c0f0dab3 | refs/heads/master | 2021-01-09T19:05:33.501942 | 2016-08-03T11:32:55 | 2016-08-03T11:32:55 | 64,841,098 | 3 | 0 | null | null | null | null | UTF-8 | Python | false | false | 7,710 | py | #!/usr/bin/python
import os
import subprocess
import shutil
import MySQLdb
from Tkinter import Tk, Frame, Menu
import button
db=MySQLdb.connect("localhost","root","root","books")
cur=db.cursor()
speed=130
volume=40
def change_speed(menu,entry):
global speed
print menu
print entry
print speed
speed= 30 * entry
print speed
def change_volume(menu,entry):
global volume
print menu
print entry
print volume
volume= 20 * entry
print volume
for root, dirs, files in os.walk("/home/pi/rpi"): ##Extracting .txt files from the directory
for file in files:
if file.endswith(".txt"):
fullpath=(os.path.join(root, file))
name=file
try:
query=("INSERT INTO ebooks (Book_Name,Book_Path) Values(%s,%s)") #insert the particularfile in db
data=(name,fullpath)
cur.execute(query,data)
db.commit()
except:
print "duplicate entry"
pass
for root, dirs, files in os.walk("/home/pi/rpi"):
for file_v in files:
if file_v.endswith(".wav"):
fullpath_v=(os.path.join(root, file_v))
name_v=file_v
try:
query_v=("INSERT INTO evoice(Voice_Name,Voice_Path) Values(%s,%s)")
data_v=(name_v,fullpath_v)
cur.execute(query_v,data_v)
db.commit()
except:
print "duplicate voice"
#db.commit()
pass
for root, dirs, files in os.walk("/home/pi/rpi"):
for file_v in files:
if file_v.endswith(".mp3"):
fullpath_v=(os.path.join(root, file_v))
name_v=file_v
try:
query_v=("INSERT INTO eaudio(Audio_Name,Audio_Path) Values(%s,%s)")
data_v=(name_v,fullpath_v)
cur.execute(query_v,data_v)
db.commit()
except:
print "duplicate audio"
#db.commit()
pass
class Example(Frame):
def __init__(self, parent):
Frame.__init__(self, parent)
self.parent = parent
self.initUI()
self.update_read()
def initUI(self):
self.parent.title("Audio Book Reader")
menubar = Menu(self.parent)
self.parent.config(menu=menubar)
fileMenu = Menu(menubar)
cur.execute("SELECT count(*) from ebooks")
count=cur.fetchone()[0]
print count
def reading(menu,entry):
def execute_unix(inputcommand):
p = subprocess.Popen(inputcommand, stdout=subprocess.PIPE, shell=True)
(output, err) = p.communicate()
return output
print menu
print entry
x="".join(entry)
print x
print speed
subprocess.call(['espeak','-ven+f3','-s',str(speed),'-p',str(volume),'-f',x])
#book_rmenu=Menu(fileMenu)
for i in range(1,count+1):
#for i in range(1,10):
if i==1:
book_rmenu=Menu(fileMenu)
cur.execute("SELECT Book_Name from ebooks where ID=%s",i)
var=cur.fetchone()
book_rmenu.add_command(label=var,font=('Times New Roman',22),command = lambda var=var:reading('Read',var))
def deletingb(menu,entry):
print menu
print entry
x="".join(entry)
print x
os.remove(x)
book_dmenu.delete(entry)
book_rmenu.delete(entry)
#cur.execute("UPDATE ebooks SET ID=ID-1 WHERE ID>%s",id)
#cur.execute("UPDATE ebooks SET ID=ID-1 WHERE ID>%s",id)
#maximum_v=cur.execute("SELECT max(ID) from ebooks")
#maximum_v=maximum_v+1
#cur.execute("ALTER table ebooksAUTO_INCREMENT=%s",maximum_v)
db.commit()
book_dmenu=Menu(fileMenu)
for i in range(1,count+1):
#if i==1:
# book_dmenu=Menu(fileMenu)
cur.execute("SELECT Book_Name from ebooks where ID=%s",i)
var=cur.fetchone()
book_dmenu.add_command(label=var,font=('Times New Roman',22),command = lambda var=var:deletingb('Delete',var))
def playing(menu,entry):
print menu
print entry
x="".join(entry)
print x
import pygame
pygame.init()
pygame.mixer.init()
pygame.mixer.music.load(x)
pygame.mixer.music.play()
while pygame.mixer.music.get_busy() == True:
continue
def deletingv(menu,entry):
print menu
print entry
x="".join(entry)
print x
os.remove(x)
voice_dmenu.delete(entry)
voice_dmenu.delete(entry)
#cur.execute("UPDATE evoice SET ID=ID-1 WHERE ID>%s",id)
#cur.execute("UPDATE evoice SET ID=ID-1 WHERE ID>%s",id)
#maximum_v=cur.execute("SELECT max(ID) from evoice")
#maximum_v=maximum_v+1
#cur.execute("ALTER table evoice AUTO_INCREMENT=%s",maximum_v)
db.commit()
cur.execute("SELECT count(*) from evoice")
count=cur.fetchone()[0]
print "count"
voice_pmenu=Menu(fileMenu)
for i in range(1,count+1):
#if i==1:
# voice_pmenu=Menu(fileMenu)
cur.execute("SELECT Voice_Name from evoice where ID=%s",i)
var=cur.fetchone()
voice_pmenu.add_command(label=var,font=('Times New Roman',22),command = lambda var=var:playing('Play',var))
voice_dmenu=Menu(fileMenu)
for i in range(1,count+1):
#if i==1:
# voice_dmenu=Menu(fileMenu)
cur.execute("SELECT Voice_Name from evoice where ID=%s",i)
var=cur.fetchone()
voice_dmenu.add_command(label=var,font=('Times New Roman',22),command = lambda var=var:deletingv('Play',var))
cur.execute("SELECT count(*) from eaudio")
count=cur.fetchone()[0]
audio_menu=Menu(fileMenu)
for i in range(1,count+1):
#if i==1:
# audio_menu=Menu(fileMenu)
cur.execute("SELECT Audio_Name from eaudio where ID=%s",i)
var=cur.fetchone()
audio_menu.add_command(label=var,font=('Times New Roman',22),command = lambda var=var:playing('Audio Books',var))
speedmenu=Menu(fileMenu)
for i in range(1,11):
speedmenu.add_command(label= i ,font=('Times New Roman',22),command = lambda i=i:change_speed('Speed',i))
volumemenu=Menu(fileMenu)
for i in range(1,11):
volumemenu.add_command(label=i,font=('Times New Roman',22),command = lambda i=i:change_volume('Volume',i))
submenu2=Menu(fileMenu)
submenu2.add_cascade(label='Speed',menu=speedmenu,font=('Times New Roman',22))
submenu2.add_cascade(label='Pitch',menu=volumemenu,font=('Times New Roman',22))
submenu = Menu(fileMenu)
submenu.add_cascade(label="Read",menu=book_rmenu,font=('Times New Roman',22))
submenu.add_cascade(label="Delete",menu=book_dmenu, font=('Times New Roman',22))
submenu.add_command(label="Back",font=('Times New Roman',22))
fileMenu.add_cascade(label='Books', menu=submenu, underline=0,font=('Times New Roman',22))
def my_process():
#a1="arecord -f cd -D plughw:1,0 -d 10 b.wav"
#subprocess.call(a1,shell=True)
subprocess.call('arecord','-d','5','-r','48000','w.wav')
print "We are done"
def recording():
import sys,threading
thread=threading.Thread(target=my_process)
thread.start()
print "audio recording"
fileMenu.add_separator()
submenu1 = Menu(fileMenu)
submenu1.add_command(label="Record", font=('Times New Roman',22),command = lambda var=var:recording())
submenu1.add_cascade(label="Play",menu=voice_pmenu,font=('Times New Roman',22))
submenu1.add_cascade(label="Delete",menu=voice_dmenu,font=('Times New Roman',22))
fileMenu.add_cascade(label='Voice Notes', menu=submenu1,underline=5,font=('Times New Roman',22))
fileMenu.add_cascade(label='Audio Books',menu=audio_menu,underline=0,font=('Times New Roman',22))
fileMenu.add_cascade(label='Options',menu=submenu2,underline=0,font=('Times New Roman',22))
fileMenu.add_command(label="Exit", underline=0, command=self.onExit,font=('Times New Roman',22))
menubar.add_cascade(label="File", underline=0, menu=fileMenu,font=('Times New Roman',22))
def update_read(self):
print "str"
button.one()
self.parent.after(100 , self.update_read)
def onExit(self):
self.quit()
def main():
root = Tk()
root.geometry("500x350+300+300")
app = Example(root)
root.mainloop()
if __name__ == '__main__':
main()
| [
"noreply@github.com"
] | Bhawna4tech.noreply@github.com |
688bac0891c7135030e8bf35d07f7a9518baae31 | c5d87c7f25e3fe9b17c1e88993b0ed6831e52acb | /Socket/GPS_Server_Test/GPS_Server_testData.py | 2d6e0b37aa0f879b89e87aa831bf512762c6fe1c | [] | no_license | GIS90/python_base_use | e55d55f9df505dac45ddd332fb65dcd08e8e531f | 7166ca85975bb7c56a5fbb6b723fd8300c4dd5d1 | refs/heads/master | 2020-04-02T08:33:49.461307 | 2018-10-23T03:33:41 | 2018-10-23T03:33:41 | 154,249,857 | 1 | 1 | null | null | null | null | UTF-8 | Python | false | false | 1,941 | py | # -*- coding: utf-8 -*-
"""
------------------------------------------------
describe:
this tool be used to
------------------------------------------------
"""
import SocketServer
import codecs
import datetime
import os
import threading
from SocketServer import BaseRequestHandler
SOCKET_DATA_MAX = 16 * 1024 * 1024
FORMMAT = "%Y%m%d%H%M%S"
def __get_cur_folder():
# if getattr(sys, "frozen", False):
return os.path.dirname(os.path.abspath(__file__))
# else:
# cur_folder = os.path.dirname(inspect.getfile(inspect.currentframe()))
# return os.path.abspath(cur_folder)
_cur_folder = __get_cur_folder()
_gps_file_folder = os.path.abspath(os.path.join(_cur_folder, "liveGPS"))
if not os.path.exists(_gps_file_folder):
os.makedirs(_gps_file_folder)
class TCPRequestHandler(BaseRequestHandler):
"""
The RequestHandler class for my server.
It is instantiated once per connection to the server, and must
override the handle method to implement communication to the
client.
"""
def setup(self):
BaseRequestHandler.setup(self)
def handle(self):
while True:
try:
data = self.request.recv(SOCKET_DATA_MAX).strip()
if data:
print data
gps_file_name = "gps.dat"
gps_file = os.path.join(_gps_file_folder, gps_file_name)
gps = codecs.open(gps_file, 'wb', 'utf-8')
gps.write(data)
gps.close()
except Exception as e:
print e.message
if __name__ == "__main__":
host = ""
port = 1991
addr = (host, port)
print "Server start ......"
# It use to
server = SocketServer.ThreadingTCPServer(addr, TCPRequestHandler)
server.allow_reuse_address = True
server.serve_forever()
| [
"mingliang.gao@qunar.com"
] | mingliang.gao@qunar.com |
7e45a200414423d396becba56436abd46f1d731e | 66862c422fda8b0de8c4a6f9d24eced028805283 | /slambook2/3rdparty/opencv-3.3.0/samples/python/floodfill.py | 1b988d3763ef61c3f84e1e5039da4e6540f9914f | [
"MIT",
"BSD-3-Clause"
] | permissive | zhh2005757/slambook2_in_Docker | 57ed4af958b730e6f767cd202717e28144107cdb | f0e71327d196cdad3b3c10d96eacdf95240d528b | refs/heads/main | 2023-09-01T03:26:37.542232 | 2021-10-27T11:45:47 | 2021-10-27T11:45:47 | 416,666,234 | 17 | 6 | MIT | 2021-10-13T09:51:00 | 2021-10-13T09:12:15 | null | UTF-8 | Python | false | false | 2,007 | py | #!/usr/bin/env python
'''
Floodfill sample.
Usage:
floodfill.py [<image>]
Click on the image to set seed point
Keys:
f - toggle floating range
c - toggle 4/8 connectivity
ESC - exit
'''
# Python 2/3 compatibility
from __future__ import print_function
import numpy as np
import cv2
if __name__ == '__main__':
import sys
try:
fn = sys.argv[1]
except:
fn = '../data/fruits.jpg'
print(__doc__)
img = cv2.imread(fn, True)
if img is None:
print('Failed to load image file:', fn)
sys.exit(1)
h, w = img.shape[:2]
mask = np.zeros((h+2, w+2), np.uint8)
seed_pt = None
fixed_range = True
connectivity = 4
def update(dummy=None):
if seed_pt is None:
cv2.imshow('floodfill', img)
return
flooded = img.copy()
mask[:] = 0
lo = cv2.getTrackbarPos('lo', 'floodfill')
hi = cv2.getTrackbarPos('hi', 'floodfill')
flags = connectivity
if fixed_range:
flags |= cv2.FLOODFILL_FIXED_RANGE
cv2.floodFill(flooded, mask, seed_pt, (255, 255, 255), (lo,)*3, (hi,)*3, flags)
cv2.circle(flooded, seed_pt, 2, (0, 0, 255), -1)
cv2.imshow('floodfill', flooded)
def onmouse(event, x, y, flags, param):
global seed_pt
if flags & cv2.EVENT_FLAG_LBUTTON:
seed_pt = x, y
update()
update()
cv2.setMouseCallback('floodfill', onmouse)
cv2.createTrackbar('lo', 'floodfill', 20, 255, update)
cv2.createTrackbar('hi', 'floodfill', 20, 255, update)
while True:
ch = cv2.waitKey()
if ch == 27:
break
if ch == ord('f'):
fixed_range = not fixed_range
print('using %s range' % ('floating', 'fixed')[fixed_range])
update()
if ch == ord('c'):
connectivity = 12-connectivity
print('connectivity =', connectivity)
update()
cv2.destroyAllWindows()
| [
"594353397@qq.com"
] | 594353397@qq.com |
dea9ae81ec3c79c951c1a534da27bc2fc44a20ec | 96a9a4bbf0550fa16ab74fc184354ac10c974000 | /python/advanced-strings.py | d1bfeb75f9809f50039ae20bfa74303ff1e25851 | [] | no_license | licjapodaca/ethical-hacking-course | 9a4a24759360c3d2cf03b3cb9ed025e911a90f59 | 7ea6e0731eefa7597d9ae1f08931e2a82f990a69 | refs/heads/main | 2023-03-27T16:40:57.495812 | 2021-03-25T21:10:20 | 2021-03-25T21:10:20 | 350,839,864 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 621 | py | #!/bin/python3
# Advanced Strings
my_name = "George"
print(my_name[0])
print(my_name[-1])
sentence = "This is a sentence."
print(sentence[:4])
print(sentence.split())
sentence_split = sentence.split()
sentence_join = ' '.join(sentence_split)
print(sentence_join)
quote = "He said, \"give me all your money\""
print(quote)
too_much_space = " hello "
print(too_much_space.strip())
print("a" in "Apple")
letter = "A"
word = "Apple"
print(letter.lower() in word.lower()) # Improved
# String Interpolation
movie = "The Hangover"
print("My favorite movie is {0}. [{1}]".format(movie, word)) | [
"mcsd@jorge-apodaca.net"
] | mcsd@jorge-apodaca.net |
fe547b0d6f92c919781366e3a1059ab975ea9b14 | 725abfa74e3800622837e60615dc15c6e91442c0 | /venv/Lib/site-packages/django/contrib/messages/storage/session.py | 7dbd24a8da5c105a8955f5695fe53d22b05df70b | [] | no_license | Malak-Abdallah/TODOlist | 4840e2e0a27e6499ae6b37524bb3e58455d08bfb | fd35754e8eac9b262fae17ec16ad9fb510a12f5d | refs/heads/master | 2023-07-16T11:38:48.759232 | 2021-08-31T09:43:11 | 2021-08-31T09:43:11 | 401,600,246 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,669 | py | import json
from django.contrib.messages.storage.base import BaseStorage
from django.contrib.messages.storage.cookie import MessageDecoder, MessageEncoder
class SessionStorage(BaseStorage):
"""
Store messages in the session (that is, django.contrib.sessions).
"""
session_key = "_messages"
def __init__(self, request, *args, **kwargs):
assert hasattr(request, "session"), (
"The session-based temporary "
"message storage requires session middleware to be installed, "
"and come before the message middleware in the "
"MIDDLEWARE list."
)
super().__init__(request, *args, **kwargs)
def _get(self, *args, **kwargs):
"""
Retrieve a list of messages from the request's session. This storage
always stores everything it is given, so return True for the
all_retrieved flag.
"""
return (
self.deserialize_messages(self.request.session.get(self.session_key)),
True,
)
def _store(self, messages, response, *args, **kwargs):
"""
Store a list of messages to the request's session.
"""
if messages:
self.request.session[self.session_key] = self.serialize_messages(messages)
else:
self.request.session.pop(self.session_key, None)
return []
def serialize_messages(self, messages):
encoder = MessageEncoder()
return encoder.encode(messages)
def deserialize_messages(self, data):
if data and isinstance(data, str):
return json.loads(data, cls=MessageDecoder)
return data
| [
"malkobeidallah@gmail.com"
] | malkobeidallah@gmail.com |
721d65e2c1c2c695a007ea68bca71a1ce9b8de68 | 56516211b5cd6b7465ba79000357a3fbc99bf7f2 | /backend/web/cart_product/migrations/0003_auto_20180311_1911.py | 49d5b682e265f3070d60ee94260a755b31514109 | [] | no_license | mrnonz/mejai | 4c165571a4a9599d6c11e981443a7bfb8ec4a57d | 506afb4ba33e998d5bfd4389c9b280cea082e237 | refs/heads/master | 2022-12-13T06:37:47.680151 | 2020-10-01T05:43:07 | 2020-10-01T05:43:07 | 101,288,901 | 0 | 0 | null | 2022-12-09T08:18:23 | 2017-08-24T11:45:01 | JavaScript | UTF-8 | Python | false | false | 712 | py | # -*- coding: utf-8 -*-
# Generated by Django 1.11 on 2018-03-11 19:11
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('cart', '0001_initial'),
('cart_product', '0002_auto_20180311_1842'),
]
operations = [
migrations.RemoveField(
model_name='cartproduct',
name='cart_id',
),
migrations.AddField(
model_name='cartproduct',
name='cart',
field=models.ForeignKey(default='', on_delete=django.db.models.deletion.CASCADE, related_name='items', to='cart.Cart'),
),
]
| [
"nontawat39@gmail.com"
] | nontawat39@gmail.com |
8770db87586708d0a54dd67e1a2975ec6317d52b | 163bbb4e0920dedd5941e3edfb2d8706ba75627d | /Code/CodeRecords/2772/8317/301956.py | b1c4c2bd1a959d947400f88d06dd30c9659cc1b4 | [] | no_license | AdamZhouSE/pythonHomework | a25c120b03a158d60aaa9fdc5fb203b1bb377a19 | ffc5606817a666aa6241cfab27364326f5c066ff | refs/heads/master | 2022-11-24T08:05:22.122011 | 2020-07-28T16:21:24 | 2020-07-28T16:21:24 | 259,576,640 | 2 | 1 | null | null | null | null | UTF-8 | Python | false | false | 123 | py | def solve():
num = int(input())
for _ in range(num):
n = int(input())
print(pow(n, 1/3))
solve() | [
"1069583789@qq.com"
] | 1069583789@qq.com |
0c49b984bf9f2ac8bae5046c1f435df4c90cd46f | 2e682fd72e3feaa70e3f7bf2a3b83c50d783ec02 | /PyTorch/contrib/cv/detection/SSD/mmdet/models/builder.py | 05efb838ed26ce7d0c12f1cdf8a678b15d583bdd | [
"Apache-2.0",
"BSD-2-Clause",
"MIT",
"BSD-3-Clause",
"LicenseRef-scancode-generic-cla",
"LicenseRef-scancode-unknown-license-reference",
"GPL-1.0-or-later"
] | permissive | Ascend/ModelZoo-PyTorch | 4c89414b9e2582cef9926d4670108a090c839d2d | 92acc188d3a0f634de58463b6676e70df83ef808 | refs/heads/master | 2023-07-19T12:40:00.512853 | 2023-07-17T02:48:18 | 2023-07-17T02:48:18 | 483,502,469 | 23 | 6 | Apache-2.0 | 2022-10-15T09:29:12 | 2022-04-20T04:11:18 | Python | UTF-8 | Python | false | false | 2,225 | py | # Copyright 2021 Huawei Technologies Co., Ltd
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from mmcv.utils import Registry, build_from_cfg
from torch import nn
BACKBONES = Registry('backbone')
NECKS = Registry('neck')
ROI_EXTRACTORS = Registry('roi_extractor')
SHARED_HEADS = Registry('shared_head')
HEADS = Registry('head')
LOSSES = Registry('loss')
DETECTORS = Registry('detector')
def build(cfg, registry, default_args=None):
"""Build a module.
Args:
cfg (dict, list[dict]): The config of modules, is is either a dict
or a list of configs.
registry (:obj:`Registry`): A registry the module belongs to.
default_args (dict, optional): Default arguments to build the module.
Defaults to None.
Returns:
nn.Module: A built nn module.
"""
if isinstance(cfg, list):
modules = [
build_from_cfg(cfg_, registry, default_args) for cfg_ in cfg
]
return nn.Sequential(*modules)
else:
return build_from_cfg(cfg, registry, default_args)
def build_backbone(cfg):
"""Build backbone."""
return build(cfg, BACKBONES)
def build_neck(cfg):
"""Build neck."""
return build(cfg, NECKS)
def build_roi_extractor(cfg):
"""Build roi extractor."""
return build(cfg, ROI_EXTRACTORS)
def build_shared_head(cfg):
"""Build shared head."""
return build(cfg, SHARED_HEADS)
def build_head(cfg):
"""Build head."""
return build(cfg, HEADS)
def build_loss(cfg):
"""Build loss."""
return build(cfg, LOSSES)
def build_detector(cfg, train_cfg=None, test_cfg=None):
"""Build detector."""
return build(cfg, DETECTORS, dict(train_cfg=train_cfg, test_cfg=test_cfg))
| [
"wangjiangben@huawei.com"
] | wangjiangben@huawei.com |
bfbb2ed9d81edf4dc490af7eed968fa79efd0218 | b4c0c347cca4856bbdf82c06142ae9cd18e02746 | /api/urls.py | 1d615a689e579ce450aaeedf48063cafdbe39872 | [
"MIT"
] | permissive | AanandhiVB/bank-admin-backend | dfb9793eedd6a447d25ad15f3417f4933806a512 | cce02c37e06dc2cd72d160f4817ec7658714831e | refs/heads/main | 2023-05-05T15:19:35.241460 | 2021-05-23T18:49:22 | 2021-05-23T18:49:22 | 370,040,798 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 244 | py | from django.contrib import admin
from django.urls import path
from . import views
app_name='api'
urlpatterns = [
path('branches/autocomplete', views.autocomplete, name="autocomplete"),
path('branches', views.search, name="search")
] | [
"aanandhi.vb@gmail.com"
] | aanandhi.vb@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.