blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 3
288
| content_id
stringlengths 40
40
| detected_licenses
listlengths 0
112
| license_type
stringclasses 2
values | repo_name
stringlengths 5
115
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 684
values | visit_date
timestamp[us]date 2015-08-06 10:31:46
2023-09-06 10:44:38
| revision_date
timestamp[us]date 1970-01-01 02:38:32
2037-05-03 13:00:00
| committer_date
timestamp[us]date 1970-01-01 02:38:32
2023-09-06 01:08:06
| github_id
int64 4.92k
681M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 22
values | gha_event_created_at
timestamp[us]date 2012-06-04 01:52:49
2023-09-14 21:59:50
⌀ | gha_created_at
timestamp[us]date 2008-05-22 07:58:19
2023-08-21 12:35:19
⌀ | gha_language
stringclasses 147
values | src_encoding
stringclasses 25
values | language
stringclasses 1
value | is_vendor
bool 2
classes | is_generated
bool 2
classes | length_bytes
int64 128
12.7k
| extension
stringclasses 142
values | content
stringlengths 128
8.19k
| authors
listlengths 1
1
| author_id
stringlengths 1
132
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
6895432cdb44dcd345003bed6d3af69f1745cbce
|
2c7f99ff86d1786d133df13a630d62e7dcc63fab
|
/google/cloud/dialogflow_v2/services/conversation_profiles/transports/base.py
|
5768948c216410b18bbda0988ae8fa09340f5c83
|
[
"Apache-2.0"
] |
permissive
|
rlindao/python-dialogflow
|
2141b7181506210c6cfffb27bb9599ad21261c28
|
8958e562bb159b00bb1fc0fa97e5ffd35dea058d
|
refs/heads/master
| 2023-04-06T15:09:14.888871 | 2021-04-16T21:34:24 | 2021-04-16T21:34:24 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 7,312 |
py
|
# -*- coding: utf-8 -*-
# Copyright 2020 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in 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 abc
import typing
import pkg_resources
from google import auth # type: ignore
from google.api_core import exceptions # type: ignore
from google.api_core import gapic_v1 # type: ignore
from google.api_core import retry as retries # type: ignore
from google.auth import credentials # type: ignore
from google.cloud.dialogflow_v2.types import conversation_profile
from google.cloud.dialogflow_v2.types import (
conversation_profile as gcd_conversation_profile,
)
from google.protobuf import empty_pb2 as empty # type: ignore
try:
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo(
gapic_version=pkg_resources.get_distribution(
"google-cloud-dialogflow",
).version,
)
except pkg_resources.DistributionNotFound:
DEFAULT_CLIENT_INFO = gapic_v1.client_info.ClientInfo()
class ConversationProfilesTransport(abc.ABC):
"""Abstract transport class for ConversationProfiles."""
AUTH_SCOPES = (
"https://www.googleapis.com/auth/cloud-platform",
"https://www.googleapis.com/auth/dialogflow",
)
def __init__(
self,
*,
host: str = "dialogflow.googleapis.com",
credentials: credentials.Credentials = None,
credentials_file: typing.Optional[str] = None,
scopes: typing.Optional[typing.Sequence[str]] = AUTH_SCOPES,
quota_project_id: typing.Optional[str] = None,
client_info: gapic_v1.client_info.ClientInfo = DEFAULT_CLIENT_INFO,
**kwargs,
) -> None:
"""Instantiate the transport.
Args:
host (Optional[str]): The hostname to connect to.
credentials (Optional[google.auth.credentials.Credentials]): The
authorization credentials to attach to requests. These
credentials identify the application to the service; if none
are specified, the client will attempt to ascertain the
credentials from the environment.
credentials_file (Optional[str]): A file with credentials that can
be loaded with :func:`google.auth.load_credentials_from_file`.
This argument is mutually exclusive with credentials.
scope (Optional[Sequence[str]]): A list of scopes.
quota_project_id (Optional[str]): An optional project to use for billing
and quota.
client_info (google.api_core.gapic_v1.client_info.ClientInfo):
The client info used to send a user-agent string along with
API requests. If ``None``, then default info will be used.
Generally, you only need to set this if you're developing
your own client library.
"""
# Save the hostname. Default to port 443 (HTTPS) if none is specified.
if ":" not in host:
host += ":443"
self._host = host
# Save the scopes.
self._scopes = scopes or self.AUTH_SCOPES
# If no credentials are provided, then determine the appropriate
# defaults.
if credentials and credentials_file:
raise exceptions.DuplicateCredentialArgs(
"'credentials_file' and 'credentials' are mutually exclusive"
)
if credentials_file is not None:
credentials, _ = auth.load_credentials_from_file(
credentials_file, scopes=self._scopes, quota_project_id=quota_project_id
)
elif credentials is None:
credentials, _ = auth.default(
scopes=self._scopes, quota_project_id=quota_project_id
)
# Save the credentials.
self._credentials = credentials
def _prep_wrapped_messages(self, client_info):
# Precompute the wrapped methods.
self._wrapped_methods = {
self.list_conversation_profiles: gapic_v1.method.wrap_method(
self.list_conversation_profiles,
default_timeout=None,
client_info=client_info,
),
self.get_conversation_profile: gapic_v1.method.wrap_method(
self.get_conversation_profile,
default_timeout=None,
client_info=client_info,
),
self.create_conversation_profile: gapic_v1.method.wrap_method(
self.create_conversation_profile,
default_timeout=None,
client_info=client_info,
),
self.update_conversation_profile: gapic_v1.method.wrap_method(
self.update_conversation_profile,
default_timeout=None,
client_info=client_info,
),
self.delete_conversation_profile: gapic_v1.method.wrap_method(
self.delete_conversation_profile,
default_timeout=None,
client_info=client_info,
),
}
@property
def list_conversation_profiles(
self,
) -> typing.Callable[
[conversation_profile.ListConversationProfilesRequest],
typing.Union[
conversation_profile.ListConversationProfilesResponse,
typing.Awaitable[conversation_profile.ListConversationProfilesResponse],
],
]:
raise NotImplementedError()
@property
def get_conversation_profile(
self,
) -> typing.Callable[
[conversation_profile.GetConversationProfileRequest],
typing.Union[
conversation_profile.ConversationProfile,
typing.Awaitable[conversation_profile.ConversationProfile],
],
]:
raise NotImplementedError()
@property
def create_conversation_profile(
self,
) -> typing.Callable[
[gcd_conversation_profile.CreateConversationProfileRequest],
typing.Union[
gcd_conversation_profile.ConversationProfile,
typing.Awaitable[gcd_conversation_profile.ConversationProfile],
],
]:
raise NotImplementedError()
@property
def update_conversation_profile(
self,
) -> typing.Callable[
[gcd_conversation_profile.UpdateConversationProfileRequest],
typing.Union[
gcd_conversation_profile.ConversationProfile,
typing.Awaitable[gcd_conversation_profile.ConversationProfile],
],
]:
raise NotImplementedError()
@property
def delete_conversation_profile(
self,
) -> typing.Callable[
[conversation_profile.DeleteConversationProfileRequest],
typing.Union[empty.Empty, typing.Awaitable[empty.Empty]],
]:
raise NotImplementedError()
__all__ = ("ConversationProfilesTransport",)
|
[
"[email protected]"
] | |
0b9347644b1ad62f3f1deb8668c660a135c70885
|
e89509b453632747077bc57dbec265a7703d5c7c
|
/list/listappend.py
|
a2ddb719341f157c2047747bdda0aa142f51df03
|
[] |
no_license
|
Madhav2108/udemy-python-as
|
a9dcfdbfdc1bb85471aa66de77957e962a7c5486
|
0bc6a501516618fb3c7ab10be6bc16c047aeec3f
|
refs/heads/master
| 2023-03-30T11:25:16.064592 | 2021-03-30T18:10:46 | 2021-03-30T18:10:46 | 286,001,815 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 572 |
py
|
List = []
print(List)
List.append(1)
List.append(2)
List.append(4)
print(List)
for i in range(1, 4):
List.append(i)
print(List)
List.append((5, 6))
print(List)
List2 = ['For', 'Geeks']
List.append(List2)
print(List)
List.insert(3, 12)
List.insert(0, 'Geeks')
print(List)
List.extend([8, 'Geeks', 'Always'])
print(List)
List.remove(8)
List.remove(12)
print(List)
List.pop()
print(List)
List.pop(2)
print(List)
Sliced_List = List[::-1]
print("\nPrinting List in reverse: ")
print(Sliced_List)
list.sort()
print(list)
|
[
"[email protected]"
] | |
1ac4822dd02e34f946f4183122d8a6b5ec804d02
|
ba949e02c0f4a7ea0395a80bdc31ed3e5f5fcd54
|
/problems/greedy/Solution678.py
|
f37f62721d5aa37063dd666a0d011a7ac22e9daa
|
[
"MIT"
] |
permissive
|
akaliutau/cs-problems-python
|
6bc0a74064f6e9687fe58b13763da1fdf2e1f626
|
9b1bd8e3932be62135a38a77f955ded9a766b654
|
refs/heads/master
| 2023-05-11T22:19:06.711001 | 2021-06-04T11:14:42 | 2021-06-04T11:14:42 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 1,937 |
py
|
""" Given a string containing only three types of characters: '(', ')' and '*',
write a function to check whether trightBoundarys string is valid. We define
the validity of a string by these rules:
Any left parenthesis '(' must have a corresponding right parenthesis ')'. Any
right parenthesis ')' must have a corresponding left parenthesis '('. Left
parenthesis '(' must go before the corresponding right parenthesis ')'. '*'
could be treated as a single right parenthesis ')' or a single left
parenthesis '(' or an empty string. An empty string is also valid.
Example 1: Input: "()" Output: True
( * ) )
l 1 0 -1 -2
t 1 2 1 0
When checking whether the string is valid, we only cared about the "balance":
the number of extra, open left brackets as we parsed through the string. For
example, when checking whether '(()())' is valid, we had a balance of 1, 2,
1, 2, 1, 0 as we parse through the string: '(' has 1 left bracket, '((' has
2, '(()' has 1, and so on. This means that after parsing the first i symbols,
(which may include asterisks,) we only need to keep track of what the balance
could be.
For example, if we have string '(***)', then as we parse each symbol, the set
of possible values for the balance is
[1] for '(';
[0, 1, 2] for '(*';
[0, 1, 2, 3] for '(**';
[0, 1, 2, 3, 4] for '(***', and
[0, 1, 2, 3] for '(***)'.
Furthermore, we can prove these states always form a contiguous interval.
Thus, we only need to know the left and right bounds of this interval. That
is, we would keep those intermediate states described above as [lo, hi] = [1,
1], [0, 2], [0, 3], [0, 4], [0, 3].
Algorithm
Let lo, hi respectively be the smallest and largest possible number of open
left brackets after processing the current character in the string.
"""
class Solution678:
pass
|
[
"[email protected]"
] | |
9ea9323c06957ea63a4699fe72b9431a47cd9117
|
e35fd52fe4367320024a26f2ee357755b5d5f4bd
|
/leetcode/problems/313.super-ugly-number.py
|
704a9e40a9a97991c2693e51d1623cb6c3511bc7
|
[] |
no_license
|
liseyko/CtCI
|
a451967b0a0ce108c491d30b81e88d20ad84d2cd
|
c27f19fac14b4acef8c631ad5569e1a5c29e9e1f
|
refs/heads/master
| 2020-03-21T14:28:47.621481 | 2019-11-12T22:59:07 | 2019-11-12T22:59:07 | 138,658,372 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 1,017 |
py
|
#
# @lc app=leetcode id=313 lang=python3
#
# [313] Super Ugly Number
#
# https://leetcode.com/problems/super-ugly-number/description/
#
# algorithms
# Medium (43.02%)
# Total Accepted: 67.2K
# Total Submissions: 156.3K
# Testcase Example: '12\n[2,7,13,19]'
#
# Write a program to find the n^th super ugly number.
#
# Super ugly numbers are positive numbers whose all prime factors are in the
# given prime list primes of size k.
#
# Example:
#
#
# Input: n = 12, primes = [2,7,13,19]
# Output: 32
# Explanation: [1,2,4,7,8,13,14,16,19,26,28,32] is the sequence of the first
# 12
# super ugly numbers given primes = [2,7,13,19] of size 4.
#
# Note:
#
#
# 1 is a super ugly number for any given primes.
# The given numbers in primes are in ascending order.
# 0 < k ≤ 100, 0 < n ≤ 10^6, 0 < primes[i] < 1000.
# The n^th super ugly number is guaranteed to fit in a 32-bit signed integer.
#
#
#
class Solution:
def nthSuperUglyNumber(self, n: int, primes: List[int]) -> int:
|
[
"[email protected]"
] | |
81f2637a8ed5c8510fcc5945d5235d911e45462f
|
7c68212791621363da7f007b1ef449597937d20c
|
/day_1/operator_shorthand.py
|
7070ebe9f8fe49ba7490762189795e3db53c65f3
|
[
"MIT"
] |
permissive
|
anishLearnsToCode/python-workshop-8
|
c1ad5c2f06b435b612acc28544180b47c86fb24f
|
0f64bfa7cf175283181b6e7f51a5e3b80d4b6b60
|
refs/heads/main
| 2023-02-07T11:55:48.372944 | 2021-01-03T08:41:33 | 2021-01-03T08:41:33 | 325,730,441 | 3 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 184 |
py
|
# variable [operator]= var_2 / value
# i = i + 1 --> i += 1
# result = result + i --> result += i
# var /= 5 --> var = var / 5
# i *= 3--> i = i * 3
# prod %= 10 --> prod = prod % 10
|
[
"[email protected]"
] | |
33fbb86f0c1d4774178156a30d673684559ba579
|
ced56909016fb7c2175c3911fc8481bd5fdf0800
|
/pytext/metric_reporters/disjoint_multitask_metric_reporter.py
|
83d419bc152137138df46faa0ff3715e14e05512
|
[
"BSD-3-Clause"
] |
permissive
|
coderbyr/pytext
|
e258a3aae625e6a2fd386b60f25ac44a7b4149fe
|
72c1ad835a30bef425494b02a6210f2e3232b1a4
|
refs/heads/master
| 2022-11-20T09:11:44.991716 | 2020-07-20T22:05:42 | 2020-07-20T22:07:15 | 281,286,078 | 1 | 0 |
NOASSERTION
| 2020-07-21T03:32:42 | 2020-07-21T03:32:41 | null |
UTF-8
|
Python
| false | false | 4,013 |
py
|
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved
from typing import Dict, Optional
from pytext.common.constants import BatchContext
from .metric_reporter import MetricReporter
AVRG_LOSS = "_avrg_loss"
class DisjointMultitaskMetricReporter(MetricReporter):
lower_is_better = False
class Config(MetricReporter.Config):
use_subtask_select_metric: bool = False
def __init__(
self,
reporters: Dict[str, MetricReporter],
loss_weights: Dict[str, float],
target_task_name: Optional[str],
use_subtask_select_metric: bool,
) -> None:
"""Short summary.
Args:
reporters (Dict[str, MetricReporter]):
Dictionary of sub-task metric-reporters.
target_task_name (Optional[str]):
Dev metric for this task will be used to select best epoch.
Returns:
None: Description of returned object.
"""
super().__init__(None)
self.reporters = reporters
self.target_task_name = target_task_name or ""
self.target_reporter = self.reporters.get(self.target_task_name, None)
self.loss_weights = loss_weights
self.use_subtask_select_metric = use_subtask_select_metric
def _reset(self):
self.total_loss = 0
self.num_batches = 0
def batch_context(self, raw_batch, batch):
context = {BatchContext.TASK_NAME: batch[BatchContext.TASK_NAME]}
reporter = self.reporters[context[BatchContext.TASK_NAME]]
context.update(reporter.batch_context(raw_batch, batch))
return context
def add_batch_stats(
self, n_batches, preds, targets, scores, loss, m_input, **context
):
self.total_loss += loss
self.num_batches += 1
# losses are weighted in DisjointMultitaskModel. Here we undo the
# weighting for proper reporting.
if self.loss_weights[context[BatchContext.TASK_NAME]] != 0:
loss /= self.loss_weights[context[BatchContext.TASK_NAME]]
reporter = self.reporters[context[BatchContext.TASK_NAME]]
reporter.add_batch_stats(
n_batches, preds, targets, scores, loss, m_input, **context
)
def add_channel(self, channel):
for reporter in self.reporters.values():
reporter.add_channel(channel)
def report_metric(
self,
model,
stage,
epoch,
reset=True,
print_to_channels=True,
optimizer=None,
privacy_engine=None,
):
metrics_dict = {AVRG_LOSS: self.total_loss / self.num_batches}
for name, reporter in self.reporters.items():
print(f"Reporting on task: {name}")
metrics_dict[name] = reporter.report_metric(
model, stage, epoch, reset, print_to_channels, optimizer=optimizer
)
if reset:
self._reset()
if self.target_reporter:
return metrics_dict[self.target_task_name]
for name, reporter in self.reporters.items():
metrics_dict[name] = reporter.get_model_select_metric(metrics_dict[name])
return metrics_dict
def get_model_select_metric(self, metrics):
if self.target_reporter:
metric = self.target_reporter.get_model_select_metric(metrics)
if self.target_reporter.lower_is_better:
metric = -metric
elif self.use_subtask_select_metric:
metric = 0.0
for name, reporter in self.reporters.items():
sub_metric = metrics[name]
if reporter.lower_is_better:
sub_metric = -sub_metric
metric += sub_metric
else: # default to training loss
metric = -metrics[AVRG_LOSS]
return metric
def report_realtime_metric(self, stage):
for _, reporter in self.reporters.items():
reporter.report_realtime_metric(stage)
|
[
"[email protected]"
] | |
a566a7e2e4d20ec72b89062af4c532ed1123f14f
|
f9d564f1aa83eca45872dab7fbaa26dd48210d08
|
/huaweicloud-sdk-hss/huaweicloudsdkhss/v5/model/list_port_statistics_response.py
|
13b10f29de59c0c0d34e2530004b515adf013fcb
|
[
"Apache-2.0"
] |
permissive
|
huaweicloud/huaweicloud-sdk-python-v3
|
cde6d849ce5b1de05ac5ebfd6153f27803837d84
|
f69344c1dadb79067746ddf9bfde4bddc18d5ecf
|
refs/heads/master
| 2023-09-01T19:29:43.013318 | 2023-08-31T08:28:59 | 2023-08-31T08:28:59 | 262,207,814 | 103 | 44 |
NOASSERTION
| 2023-06-22T14:50:48 | 2020-05-08T02:28:43 |
Python
|
UTF-8
|
Python
| false | false | 4,349 |
py
|
# coding: utf-8
import six
from huaweicloudsdkcore.sdk_response import SdkResponse
from huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization
class ListPortStatisticsResponse(SdkResponse):
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
"""
sensitive_list = []
openapi_types = {
'total_num': 'int',
'data_list': 'list[PortStatisticResponseInfo]'
}
attribute_map = {
'total_num': 'total_num',
'data_list': 'data_list'
}
def __init__(self, total_num=None, data_list=None):
"""ListPortStatisticsResponse
The model defined in huaweicloud sdk
:param total_num: 开放端口总数
:type total_num: int
:param data_list: 开放端口统计信息列表
:type data_list: list[:class:`huaweicloudsdkhss.v5.PortStatisticResponseInfo`]
"""
super(ListPortStatisticsResponse, self).__init__()
self._total_num = None
self._data_list = None
self.discriminator = None
if total_num is not None:
self.total_num = total_num
if data_list is not None:
self.data_list = data_list
@property
def total_num(self):
"""Gets the total_num of this ListPortStatisticsResponse.
开放端口总数
:return: The total_num of this ListPortStatisticsResponse.
:rtype: int
"""
return self._total_num
@total_num.setter
def total_num(self, total_num):
"""Sets the total_num of this ListPortStatisticsResponse.
开放端口总数
:param total_num: The total_num of this ListPortStatisticsResponse.
:type total_num: int
"""
self._total_num = total_num
@property
def data_list(self):
"""Gets the data_list of this ListPortStatisticsResponse.
开放端口统计信息列表
:return: The data_list of this ListPortStatisticsResponse.
:rtype: list[:class:`huaweicloudsdkhss.v5.PortStatisticResponseInfo`]
"""
return self._data_list
@data_list.setter
def data_list(self, data_list):
"""Sets the data_list of this ListPortStatisticsResponse.
开放端口统计信息列表
:param data_list: The data_list of this ListPortStatisticsResponse.
:type data_list: list[:class:`huaweicloudsdkhss.v5.PortStatisticResponseInfo`]
"""
self._data_list = data_list
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
if attr in self.sensitive_list:
result[attr] = "****"
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
import simplejson as json
if six.PY2:
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
return json.dumps(sanitize_for_serialization(self), ensure_ascii=False)
def __repr__(self):
"""For `print`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, ListPortStatisticsResponse):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
|
[
"[email protected]"
] | |
3eab1b761be0160d622ff707caaff063326f4b71
|
6c5ce1e621e0bd140d127527bf13be2093f4a016
|
/ex021/venv/Scripts/easy_install-3.7-script.py
|
e7deca8d0b6f3b28588ce8d8072d461ed000115f
|
[
"MIT"
] |
permissive
|
ArthurAlesi/Python-Exercicios-CursoEmVideo
|
124e2ee82c3476a5a49baafed657788591a232c1
|
ed0f0086ddbc0092df9d16ec2d8fdbabcb480cdd
|
refs/heads/master
| 2022-12-31T13:21:30.001538 | 2020-09-24T02:09:23 | 2020-09-24T02:09:23 | 268,917,509 | 0 | 0 | null | null | null | null |
ISO-8859-2
|
Python
| false | false | 508 |
py
|
#!C:\Users\User\Documents\github-MeusRepositórios\Python-Exercicios-CursoEmVideo\ex021\venv\Scripts\python.exe -x
# EASY-INSTALL-ENTRY-SCRIPT: 'setuptools==40.8.0','console_scripts','easy_install-3.7'
__requires__ = 'setuptools==40.8.0'
import re
import sys
from pkg_resources import load_entry_point
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit(
load_entry_point('setuptools==40.8.0', 'console_scripts', 'easy_install-3.7')()
)
|
[
"[email protected]"
] | |
a4e86864532a808b15b5e79338f65769c9f59ef7
|
a2e638cd0c124254e67963bda62c21351881ee75
|
/Extensions/Default/FPythonCode/FOperationsGenerators.py
|
d6dd072a59bc78f8da23b710047f349b73f6dd9e
|
[] |
no_license
|
webclinic017/fa-absa-py3
|
1ffa98f2bd72d541166fdaac421d3c84147a4e01
|
5e7cc7de3495145501ca53deb9efee2233ab7e1c
|
refs/heads/main
| 2023-04-19T10:41:21.273030 | 2021-05-10T08:50:05 | 2021-05-10T08:50:05 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 1,719 |
py
|
""" Compiled: 2020-09-18 10:38:53 """
#__src_file__ = "extensions/operations/etc/FOperationsGenerators.py"
#-------------------------------------------------------------------------
# Generator for generating pairs of related objects.
#-------------------------------------------------------------------------
class PairGenerator(object):
#-------------------------------------------------------------------------
class Compare:
EQUAL = 0
PREDECESSOR = 1
SUCCESSOR = 2
#-------------------------------------------------------------------------
@staticmethod
def __Next(objs):
try:
obj = next(objs)
except StopIteration as _:
obj = None
return obj
#-------------------------------------------------------------------------
@staticmethod
def Generate(objs1, objs2, functor):
obj1 = PairGenerator.__Next(objs1)
obj2 = PairGenerator.__Next(objs2)
while obj1 or obj2:
compare = functor(obj1, obj2) if obj1 and obj2 else None
if compare == PairGenerator.Compare.EQUAL:
yield obj1, obj2
obj1 = PairGenerator.__Next(objs1)
obj2 = PairGenerator.__Next(objs2)
elif (obj1 and not obj2) or compare == PairGenerator.Compare.PREDECESSOR:
yield obj1, None
obj1 = PairGenerator.__Next(objs1)
elif (obj2 and not obj1) or compare == PairGenerator.Compare.SUCCESSOR:
yield None, obj2
obj2 = PairGenerator.__Next(objs2)
|
[
"[email protected]"
] | |
d2ec78700adbdabb41836c5003016d18c394db8a
|
4e5b20fdcca20f458322f0a8cd11bbdacb6fb3e5
|
/test/promotesale/QueryFullReductionTest.py
|
872c46b84243b6ed269a15938975388fe619df59
|
[] |
no_license
|
shijingyu/sunningAPI
|
241f33b0660dc84635ce39688fed499f5c57a5da
|
4a3b2ef7f9bdc4707d1eaff185bc7eb636fe90d5
|
refs/heads/master
| 2020-04-24T22:15:11.584028 | 2019-02-24T06:41:20 | 2019-02-24T06:41:20 | 172,305,179 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 475 |
py
|
#!usr/bin/python
# -*- coding: utf-8 -*-
'''
Created on 2014-10-17
@author: suning
'''
import sys
import os
basepath = os.path.dirname(os.path.abspath(sys.argv[0]))+"/../../"
sys.path.append(basepath)
import suning.api as api
a=api.QueryFullReductionRequest()
a.pageNo='1'
a.pageSize='2'
a.startTime='2014-09-09 12:00:00'
a.endTime='2014-09-19 12:00:00'
a.promotionRange='1'
a.statusCode='1'
try:
f = a.getResponse()
print(f)
except Exception as e:
print(e)
|
[
"[email protected]"
] | |
ee987dc97b5aa0a7529752d0e719651d989c6283
|
741ee09b8b73187fab06ecc1f07f46a6ba77e85c
|
/AutonomousSourceCode/data/raw/sort/d0d3b906-00e8-4b06-aa81-423fdf44d307__mergesort.py
|
4121ebe48ffcab855687335df0292d65e95b9edb
|
[] |
no_license
|
erickmiller/AutomatousSourceCode
|
fbe8c8fbf215430a87a8e80d0479eb9c8807accb
|
44ee2fb9ac970acf7389e5da35b930d076f2c530
|
refs/heads/master
| 2021-05-24T01:12:53.154621 | 2020-11-20T23:50:11 | 2020-11-20T23:50:11 | 60,889,742 | 6 | 1 | null | null | null | null |
UTF-8
|
Python
| false | false | 1,800 |
py
|
# nlogn, divide and conquer
# recursive
def merge_sort(int_array):
# base case
if len(int_array) == 0:
return None
elif len(int_array) == 1:
return int_array
# recursive step
else:
l = len(int_array)/2
first_half = int_array[:l]
second_half = int_array[l:]
sorted_first_half = merge_sort(first_half)
sorted_second_half = merge_sort(second_half)
return merge_sorted_lists(sorted_first_half, sorted_second_half)
def merge_sorted_lists(first, second):
sorted_complete_list = []
while first or second:
if first and second:
if first[0] <= second[0]:
sorted_complete_list.append(first[0])
first = first[1:]
else:
sorted_complete_list.append(second[0])
second = second[1:]
elif first:
sorted_complete_list.extend(first)
break
elif second:
sorted_complete_list.extend(second)
break
return sorted_complete_list
if __name__ == "__main__":
# from pudb import set_trace; set_trace()
eight_element_list = [8, 0, 12, 2, 5, 7, 3, 10]
print eight_element_list
print merge_sort(eight_element_list)
print
odd_number_element_list = [-10, 5, 2, 7, 6, 4.4, 3.75]
print odd_number_element_list
print merge_sort(odd_number_element_list)
print
list_w_dups = [8, 8, 3, 3, 3, 4, 4, 0]
print list_w_dups
print merge_sort(list_w_dups)
print
sorted_list = [1, 1, 3, 3, 6, 6, 9, 9, 1000, 1000, 5000, 5000, 100000000]
print sorted_list
print merge_sort(sorted_list)
print
rev_sorted_list = [10, 9, 8, 7, 6, 0, -5, -10]
print rev_sorted_list
print merge_sort(rev_sorted_list)
print
|
[
"[email protected]"
] | |
d8e84cf721c759a8fde3138782a033b35746d27f
|
c09a4b4f02849c03ba536edda2bf920b655be6bc
|
/wyl/mvis2uvd.py
|
915db718f98decc67ab738874bf2d62bda69f28b
|
[] |
no_license
|
jpober/brownscripts
|
33bcc70a31694dfb06f1314adb1402316540108c
|
c25789ec765b018eaad59d99a0a4264c75655265
|
refs/heads/master
| 2021-01-23T22:01:19.004636 | 2020-11-12T18:39:14 | 2020-11-12T18:39:14 | 57,912,669 | 2 | 2 | null | null | null | null |
UTF-8
|
Python
| false | false | 4,616 |
py
|
import sys,optparse,aipy,glob
import numpy as np, mp2cal
import pyuvdata.uvdata as uvd
o = optparse.OptionParser()
o.set_usage('mvis2uvd.py [options] obsid') #only takes 1 obsid
o.set_description(__doc__)
o.add_option('-d',dest='datpath',default='/users/wl42/data/wl42/FHD_out/fhd_MWA_PhaseII_EoR0/',type='string', help='Path to data. Include final / in path.')
o.add_option('-s',dest='solpath',default='/users/wl42/data/wl42/Nov2016EoR0/mdl_sol/',type='string', help='Path to omnical solutions. Include final / in path.')
o.add_option('-o',dest='outpath',default='/users/wl42/data/wl42/MDLVIS/',type='string', help='Path to save uvfits. Include final / in path.')
opts,args = o.parse_args(sys.argv[1:])
exec('from PhaseII_cal import *')
obsid = args[0]
uv = uvd.UVData()
print ' Loading data'
fhdlist = glob.glob(opts.datpath+'vis_data/'+obsid+'*') + glob.glob(opts.datpath+'metadata/'+obsid+'*')
uv.read_fhd(fhdlist,run_check=False,run_check_acceptability=False)
print ' Loading mdlvis'
npz_x = np.load(opts.solpath+obsid+'.xx.omni.npz')
npz_y = np.load(opts.solpath+obsid+'.yy.omni.npz')
ant = []
for k in npz_x.keys():
if k[0].isdigit(): ant.append(int(k[0:-1]))
ant.sort()
mdvis = {'xx':{}, 'yy':{}}
info = mp2cal.wyl.pos_to_info(antpos,ants=ant)
a1, a2 = [], []
for ii in range(info.nAntenna):
for jj in range(ii,info.nAntenna):
a1.append(ii)
a2.append(jj)
ant_dict = {}
for a in ant: ant_dict[info.ant_index(a)] = a
reds = info.get_reds()
reds_ind = {}
ubls = []
chix = npz_x['chisq2']
chiy = npz_y['chisq2']
maskx = chix > 1.2
masky = chiy > 1.2
flag = {}
flag['xx'] = np.logical_or(npz_x['flags'], maskx)
flag['yy'] = np.logical_or(npz_y['flags'], masky)
mask = {'xx': npz_x['flags'], 'yy': npz_y['flags']}
for key in npz_x.keys():
if key.startswith('<'):
bl,pol = key.split()
bl = tuple(map(int,bl[1:-1].split(',')))
mdvis[pol][bl] = npz_x[key]
ubls.append(bl)
for key in npz_y.keys():
if key.startswith('<'):
bl,pol = key.split()
bl = tuple(map(int,bl[1:-1].split(',')))
mdvis[pol][bl] = npz_y[key]
for r in reds:
ubl = None
for bl in ubls:
if bl in r: ubl = bl
if ubl is None: continue
for b in r: reds_ind[b] = ubl
Nbls0 = uv.Nbls
Nbls1 = info.nAntenna*(info.nAntenna+1)/2
b0 = 128*uv.ant_1_array[:Nbls0] + uv.ant_2_array[:Nbls0]
uv.Nbls = Nbls1
uv.Nants_data = info.nAntenna
uv.Nants_telescope = info.nAntenna
uv.Nblts = uv.Ntimes*uv.Nbls
times = np.resize(np.unique(uv.time_array),(uv.Nbls,uv.Ntimes)).T
uv.time_array = np.resize(times,(times.size))
lsts = np.resize(np.unique(uv.lst_array),(uv.Nbls,uv.Ntimes)).T
uv.lst_array = np.resize(lsts,(lsts.size))
uvw = np.zeros((uv.Nblts,3))
sample = np.ones(chix.shape)*16
for ii in range(384):
if ii%16 == 8: sample[:,ii] = 8
uv.ant_1_array = np.array(a1*uv.Ntimes)
uv.ant_2_array = np.array(a2*uv.Ntimes)
b1 = 128*uv.ant_1_array[:Nbls1] + uv.ant_2_array[:Nbls1]
for ii in range(uv.Nbls):
i = b1[ii]/128
j = b1[ii]%128
ai = ant_dict[i]
aj = ant_dict[j]
try:
ubli,ublj = reds_ind[(ai,aj)]
except:
ubli,ublj = ai,aj
try:
ind = np.where(b0 == 128*ubli + ublj)[0][0]
uvw[ii::Nbls1] = uv.uvw_array[ind::Nbls0]
except:
ind = np.where(b0 == 128*ublj + ubli)[0][0]
uvw[ii::Nbls1] = -uv.uvw_array[ind::Nbls0]
uv.uvw_array = uvw
uv.nsample_array = np.zeros((uv.Nblts,uv.Nspws,uv.Nfreqs,uv.Npols))
uv.data_array = np.zeros((uv.Nblts,uv.Nspws,uv.Nfreqs,uv.Npols),dtype=np.complex64)
uv.flag_array = np.ones((uv.Nblts,uv.Nspws,uv.Nfreqs,uv.Npols),dtype=bool)
uv.baseline_array = uv.antnums_to_baseline(uv.ant_1_array,uv.ant_2_array)
uv.antenna_positions = np.zeros((info.nAntenna,3))
uv.antenna_numbers = np.arange(info.nAntenna)
uv.antenna_names = []
for ii in range(info.nAntenna): uv.antenna_names.append(str(ii))
for pp in ['xx','yy']:
pn = aipy.miriad.str2pol[pp]
pid = np.where(uv.polarization_array==pn)[0][0]
for ii in range(uv.Nbls):
i = a1[ii]
j = a2[ii]
ai = ant_dict[i]
aj = ant_dict[j]
if (ai,aj) in reds_ind.keys(): vis = mdvis[pp][reds_ind[(ai,aj)]]
elif (aj,ai) in reds_ind.keys(): vis = mdvis[pp][reds_ind[(aj,ai)]].conj()
else: continue
uv.data_array[:,0][:,:,pid][ii::uv.Nbls] = vis
uv.flag_array[:,0][:,:,pid][ii::uv.Nbls] = flag[pp]
uv.nsample_array[:,0][:,:,pid][ii::uv.Nbls] = sample*np.logical_not(mask[pp])
outuvfits = opts.outpath + obsid + '_mvis.uvfits'
print ' Writing ' + outuvfits
uv.write_uvfits(outuvfits,spoof_nonessential=True)
|
[
"[email protected]"
] | |
1713babd927c9dfa4224e1ad3277567e37cb7907
|
786027545626c24486753351d6e19093b261cd7d
|
/ghidra9.2.1_pyi/ghidra/app/util/bin/format/pdb2/pdbreader/symbol/AbstractUnknownMsSymbol.pyi
|
09fd912dc8f16775243884f29d4f2ce850338007
|
[
"MIT"
] |
permissive
|
kohnakagawa/ghidra_scripts
|
51cede1874ef2b1fed901b802316449b4bf25661
|
5afed1234a7266c0624ec445133280993077c376
|
refs/heads/main
| 2023-03-25T08:25:16.842142 | 2021-03-18T13:31:40 | 2021-03-18T13:31:40 | 338,577,905 | 14 | 1 | null | null | null | null |
UTF-8
|
Python
| false | false | 702 |
pyi
|
import ghidra.app.util.bin.format.pdb2.pdbreader.symbol
import java.lang
class AbstractUnknownMsSymbol(ghidra.app.util.bin.format.pdb2.pdbreader.symbol.AbstractMsSymbol):
def emit(self, __a0: java.lang.StringBuilder) -> None: ...
def equals(self, __a0: object) -> bool: ...
def getClass(self) -> java.lang.Class: ...
def getPdbId(self) -> int: ...
def hashCode(self) -> int: ...
def notify(self) -> None: ...
def notifyAll(self) -> None: ...
def toString(self) -> unicode: ...
@overload
def wait(self) -> None: ...
@overload
def wait(self, __a0: long) -> None: ...
@overload
def wait(self, __a0: long, __a1: int) -> None: ...
|
[
"[email protected]"
] | |
cfa3740ba18f9384af22770130b7148306057883
|
a96f603b34525f97c4b2fdca9f329aa38ffcc18c
|
/models/result_time_table_model.py
|
a705bdd8dd445e922470a4421768a1975e585705
|
[] |
no_license
|
mparlaktuna/capraz_sevkiyat2.0
|
d1fbdaaeeec4c4113448aa18b0e58457ca2ad0e5
|
3d350826084230e2c71b57e0b587e193d72b2985
|
refs/heads/master
| 2020-04-06T07:11:14.641477 | 2016-08-26T14:43:25 | 2016-08-26T14:43:25 | 59,899,015 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 1,724 |
py
|
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
class ResultTimeTableModel(QAbstractTableModel):
def __init__(self, results, number_of_trucks, truck_name):
super(ResultTimeTableModel, self).__init__()
self.times = results.times
try:
self.v_header = [truck_name + str(i) for i in range(number_of_trucks)]
self.h_header = [a[0] for a in self.times[self.v_header[0]]]
except:
pass
def rowCount(self, QModelIndex_parent=None, *args, **kwargs):
try:
a = len(self.v_header)
except:
a = 0
return a
def columnCount(self, QModelIndex_parent=None, *args, **kwargs):
try:
a = len(self.h_header)
except:
a = 0
return a
def headerData(self, p_int, Qt_Orientation, int_role=None):
if int_role == Qt.DisplayRole:
if Qt_Orientation == Qt.Vertical:
try:
return QVariant(self.v_header[p_int])
except:
return QVariant()
elif Qt_Orientation == Qt.Horizontal:
try:
return QVariant(self.h_header[p_int])
except:
return QVariant()
else:
return QVariant()
def data(self, QModelIndex, int_role=None):
if not QModelIndex.isValid():
return QVariant()
if int_role == Qt.DisplayRole:
try:
return QVariant(self.times[self.v_header[QModelIndex.row()]][QModelIndex.column()][1])
except:
return QVariant()
else:
return QVariant()
|
[
"[email protected]"
] | |
dbdda969b4f93ff83be9126e3528a31fdc8bacf4
|
cbc3c3e602996fe5561b06545593f1a9a2401f42
|
/heranca/EmpregadoHorista.py
|
607bc67e665402c8d950d86dc556ddda133ded26
|
[] |
no_license
|
ricdtaveira/poo-python
|
fc06040acd032975e355edf62a8c2983f1d37972
|
3ecba2ccfcc84f79cfc1ef5247c017e58f36c8d4
|
refs/heads/master
| 2021-10-24T17:57:57.051213 | 2019-03-27T00:10:47 | 2019-03-27T00:10:47 | 105,895,238 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 484 |
py
|
'''
Classe Empregado Horista
'''
from Empregado import Empregado
class EmpregadoHorista(Empregado):
'''
Empregado Horista
'''
def __init__(self, primeiro_nome, ultimo_nome, salario):
super().__init__(primeiro_nome, ultimo_nome, salario)
self.__horas = 0
def calcular_pagamento(self):
'''
Calcula o Pagamento do Horista
'''
return self.__horas * self.salario
def adicionar_horas(self, horas):
'''
Adicionar Horas
'''
self.__horas = self.__horas + horas
|
[
"[email protected]"
] | |
4ebdf94e0d8f96f9ac8d65ae46ad57e3e7daeee4
|
73332abdcadb62f4f262d0c30856c3c257a9ee7d
|
/tests/environments/__init__.py
|
d8f2ee2ede569a4f0b62f68bcf1956da8c7c993e
|
[
"BSD-2-Clause"
] |
permissive
|
code-google-com/oyprojectmanager
|
454435604cc150c1b54ec2c54294e0fa05490f82
|
3085ecbe1cc04a73ec69b4848b789009546feae7
|
refs/heads/master
| 2021-01-19T02:40:56.342086 | 2015-01-26T16:40:00 | 2015-01-26T16:40:00 | 32,266,400 | 1 | 2 | null | null | null | null |
UTF-8
|
Python
| false | false | 206 |
py
|
# -*- coding: utf-8 -*-
# Copyright (c) 2009-2012, Erkan Ozgur Yilmaz
#
# This module is part of oyProjectManager and is released under the BSD 2
# License: http://www.opensource.org/licenses/BSD-2-Clause
|
[
"[email protected]"
] | |
63530f10dc7fdc29a90fb8237fa885a8b7cc9f3b
|
590facf811b9ad0e55e5eafbe6a5ed796d76b521
|
/apps/meetup/migrations/0003_auto_20190428_1649.py
|
607f35d32482cdf39d2c2855c8736906f8e3ef7c
|
[] |
no_license
|
wangonya/questioner_django
|
6193fa779121135b5c903fef599a5bc873107b52
|
b598d4337b3acc39adf3ef972e50f2d750376ac0
|
refs/heads/develop
| 2020-05-16T11:59:16.778797 | 2019-05-01T16:43:29 | 2019-05-01T16:43:29 | 183,032,935 | 2 | 1 | null | 2019-05-01T16:43:30 | 2019-04-23T14:29:33 |
Python
|
UTF-8
|
Python
| false | false | 1,083 |
py
|
# Generated by Django 2.2 on 2019-04-28 16:49
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('meetup', '0002_auto_20190428_0625'),
]
operations = [
migrations.AddField(
model_name='votesmodel',
name='for_question',
field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, to='meetup.QuestionModel'),
preserve_default=False,
),
migrations.AddField(
model_name='votesmodel',
name='vote',
field=models.SmallIntegerField(default=1),
preserve_default=False,
),
migrations.AddField(
model_name='votesmodel',
name='voter',
field=models.ForeignKey(default=1, on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL),
preserve_default=False,
),
]
|
[
"[email protected]"
] | |
50be68b9ed14bc6e7cfa7d618467ffe4b3831cf6
|
1fc35e54ee4723cfa3d13de713895eac30616847
|
/baekjun/stage solve/14.sort/2750.py
|
5c0dafb7b9d7c5d8d8c61146fee82535d5d55b6e
|
[] |
no_license
|
yhs3434/Algorithms
|
02f55a5dc21085c0a17d9eaec5e3ba0cbd6d651d
|
24d234a301077aac1bc4efbb269b41a963cedccf
|
refs/heads/master
| 2021-07-12T19:21:00.446399 | 2021-01-20T01:44:27 | 2021-01-20T01:44:27 | 226,431,877 | 6 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 732 |
py
|
# 수 정렬하기
# https://www.acmicpc.net/problem/2750
import sys
sys.setrecursionlimit(1000000)
def solution(nums):
quickSort(nums, 0, len(nums)-1)
return nums
def quickSort(arr, left, right):
if left>=right:
return
pivot = arr[right]
i = left
j = left
while j<right:
if arr[j] < pivot:
temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
i+=1
j+=1
else:
j+=1
temp = arr[i]
arr[i] = pivot
arr[right] = temp
quickSort(arr, left, i-1)
quickSort(arr, i+1, right)
n = int(input())
arrr = []
for xxx in range(n):
arrr.append(int(input()))
nums = solution(arrr)
for n in nums:
print(n)
|
[
"[email protected]"
] | |
ac33194bffd378e21c7449116b073668876615e6
|
d99ac626d62c663704444a9cce7e7fc793a9e75e
|
/windows_asm_dump/dump_asm.py
|
919d0f476a5fa34c1e8c990412b5ca361122bb57
|
[] |
no_license
|
Experiment5X/CryptoFunctionDetection
|
3ab32d5573a249d24db1faf772721bc80b8d905d
|
dac700193e7e84963943593e36844b173211a8a1
|
refs/heads/master
| 2023-04-19T09:12:35.828268 | 2021-05-13T22:39:27 | 2021-05-13T22:39:27 | 355,299,557 | 1 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 5,802 |
py
|
import os
import re
import subprocess
from pathlib import Path
from collections import OrderedDict
class BinaryCollection:
def __init__(self, in_directory, out_directory):
self.in_directory = in_directory
self.out_directory = out_directory
def process_all(self, limit=500):
binaries_processed = 0
for filename in os.listdir(self.in_directory):
file_path_str = os.path.join(self.in_directory, filename)
file_path = Path(file_path_str)
if not filename.startswith('.'): # file_path.suffix == '.exe' or file_path.suffix == '.dll':
file_name_no_exetension = file_path.stem
out_asm_path = os.path.join(
self.out_directory, f'{file_name_no_exetension}.s'
)
out_functions_path = os.path.join(
self.out_directory, f'{file_name_no_exetension}_functions.txt'
)
binary_file = BinaryFile(file_path_str)
if len(binary_file.labels) == 0:
continue
function_names = binary_file.get_functions()
with open(out_functions_path, 'w') as out_functions_file:
out_functions_file.writelines([f'{f}\n' for f in function_names])
dumped_functions = binary_file.dump_cleaned_asm(out_asm_path)
dumped_functions = set(dumped_functions)
for func_name in function_names:
if func_name not in dumped_functions:
print(f'{func_name} detected as a function but label wasnt dumped to asm file')
print(f'Processed {filename}')
binaries_processed += 1
if binaries_processed >= limit:
break
print(f'Processed {binaries_processed} binary files')
class BinaryFile:
def __init__(self, binary_path):
self.binary_path = binary_path
self.parse_asm()
def dump_assembly(self):
result = subprocess.run(
['dumpbin', '/DISASM:NOBYTES', self.binary_path], stdout=subprocess.PIPE
)
return result.stdout.decode('utf-8')
def load_assembly(self):
assembly = self.dump_assembly()
asm_lines = assembly.split('\n')
if len(asm_lines) < 1000:
return []
# remove info at start of dump
asm_lines = asm_lines[8:]
# strip all lines
asm_lines = [l.strip() for l in asm_lines if len(l.strip()) != 0]
# remove Summary info at end
summary_line = None
for i in range(1, len(asm_lines)):
if asm_lines[-i] == 'Summary':
summary_line = -i
asm_lines = asm_lines[:summary_line]
self.asm_lines = asm_lines
return asm_lines
def parse_asm(self):
asm_lines = self.load_assembly()
self.instructions = OrderedDict()
self.labels = {}
for line in asm_lines:
line_components = re.split('\s+', line)
address = int(line_components[0].replace(':', ''), 16)
instruction = ' '.join(line_components[1:])
if len(line_components) >= 3:
is_operand_address = re.match('^[0-9A-Fa-f]+$', line_components[2])
else:
is_operand_address = False
# check for call instructions
if (
line_components[1] == 'call'
and len(line_components) == 3
and is_operand_address
):
call_address_str = line_components[2]
call_address = int(call_address_str, 16)
self.labels[call_address] = f'sub_{call_address_str}'
# check for jump instructions
if (
line_components[1].startswith('j')
and len(line_components) == 3
and is_operand_address
):
jump_address_str = line_components[2]
jump_address = int(jump_address_str, 16)
jump_label = f'.L{jump_address_str}'
self.labels[jump_address] = jump_label
# replace address reference with label
instruction = instruction.replace(jump_address_str, jump_label)
self.instructions[address] = instruction
def get_functions(self):
functions = []
# filter out any functions that refer to stubs
for label_address in self.labels:
label = self.labels[label_address]
if not label.startswith('sub_'):
continue
if label_address not in self.instructions:
continue
first_function_instruction = self.instructions[label_address]
if not first_function_instruction.startswith('jmp'):
functions.append(label)
return functions
def dump_cleaned_asm(self, out_file_name):
functions_dumped = []
with open(out_file_name, 'w') as out_file:
for address in self.instructions:
instruction = self.instructions[address]
# check for a label
if address in self.labels:
label = self.labels[address]
if label.startswith('sub_'):
functions_dumped.append(label)
label_line = f'{label}:\n'
out_file.write(label_line)
out_file.write(f' {instruction}\n')
return functions_dumped
collection = BinaryCollection('C:\\Users\\Adam\\Downloads\\CryptoRansomware', 'C:\\Users\\Adam\\Developer\\CryptoFunctionDetection\\windows_asm_dump\\dumped_output_ransomware')
collection.process_all()
|
[
"[email protected]"
] | |
f9f574a4d00a771aa40f9ddee1222b2e1cf2f25b
|
f693c9c487d31a677f009afcdf922b4e7f7d1af0
|
/biomixer-venv/lib/python3.9/site-packages/pylint/checkers/refactoring/recommendation_checker.py
|
b1175f03e03853db4ae7d542287abf40d715df6b
|
[
"MIT"
] |
permissive
|
Shellowb/BioMixer
|
9048b6c07fa30b83c87402284f0cebd11a58e772
|
1939261589fe8d6584a942a99f0308e898a28c1c
|
refs/heads/master
| 2022-10-05T08:16:11.236866 | 2021-06-29T17:20:45 | 2021-06-29T17:20:45 | 164,722,008 | 1 | 3 |
MIT
| 2022-09-30T20:23:34 | 2019-01-08T19:52:12 |
Python
|
UTF-8
|
Python
| false | false | 4,749 |
py
|
# Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
# For details: https://github.com/PyCQA/pylint/blob/master/LICENSE
import astroid
from pylint import checkers, interfaces
from pylint.checkers import utils
class RecommendationChecker(checkers.BaseChecker):
__implements__ = (interfaces.IAstroidChecker,)
name = "refactoring"
msgs = {
"C0200": (
"Consider using enumerate instead of iterating with range and len",
"consider-using-enumerate",
"Emitted when code that iterates with range and len is "
"encountered. Such code can be simplified by using the "
"enumerate builtin.",
),
"C0201": (
"Consider iterating the dictionary directly instead of calling .keys()",
"consider-iterating-dictionary",
"Emitted when the keys of a dictionary are iterated through the .keys() "
"method. It is enough to just iterate through the dictionary itself, as "
'in "for key in dictionary".',
),
}
@staticmethod
def _is_builtin(node, function):
inferred = utils.safe_infer(node)
if not inferred:
return False
return utils.is_builtin_object(inferred) and inferred.name == function
@utils.check_messages("consider-iterating-dictionary")
def visit_call(self, node):
if not isinstance(node.func, astroid.Attribute):
return
if node.func.attrname != "keys":
return
if not isinstance(node.parent, (astroid.For, astroid.Comprehension)):
return
inferred = utils.safe_infer(node.func)
if not isinstance(inferred, astroid.BoundMethod) or not isinstance(
inferred.bound, astroid.Dict
):
return
if isinstance(node.parent, (astroid.For, astroid.Comprehension)):
self.add_message("consider-iterating-dictionary", node=node)
@utils.check_messages("consider-using-enumerate")
def visit_for(self, node):
"""Emit a convention whenever range and len are used for indexing."""
# Verify that we have a `range([start], len(...), [stop])` call and
# that the object which is iterated is used as a subscript in the
# body of the for.
# Is it a proper range call?
if not isinstance(node.iter, astroid.Call):
return
if not self._is_builtin(node.iter.func, "range"):
return
if not node.iter.args:
return
is_constant_zero = (
isinstance(node.iter.args[0], astroid.Const)
and node.iter.args[0].value == 0
)
if len(node.iter.args) == 2 and not is_constant_zero:
return
if len(node.iter.args) > 2:
return
# Is it a proper len call?
if not isinstance(node.iter.args[-1], astroid.Call):
return
second_func = node.iter.args[-1].func
if not self._is_builtin(second_func, "len"):
return
len_args = node.iter.args[-1].args
if not len_args or len(len_args) != 1:
return
iterating_object = len_args[0]
if not isinstance(iterating_object, astroid.Name):
return
# If we're defining __iter__ on self, enumerate won't work
scope = node.scope()
if iterating_object.name == "self" and scope.name == "__iter__":
return
# Verify that the body of the for loop uses a subscript
# with the object that was iterated. This uses some heuristics
# in order to make sure that the same object is used in the
# for body.
for child in node.body:
for subscript in child.nodes_of_class(astroid.Subscript):
if not isinstance(subscript.value, astroid.Name):
continue
value = subscript.slice
if isinstance(value, astroid.Index):
value = value.value
if not isinstance(value, astroid.Name):
continue
if value.name != node.target.name:
continue
if iterating_object.name != subscript.value.name:
continue
if subscript.value.scope() != node.scope():
# Ignore this subscript if it's not in the same
# scope. This means that in the body of the for
# loop, another scope was created, where the same
# name for the iterating object was used.
continue
self.add_message("consider-using-enumerate", node=node)
return
|
[
"[email protected]"
] | |
47633761925b05cb7b78e248675293d5b8f9b673
|
c74c907a32da37d333096e08d2beebea7bea65e7
|
/kaikeba/cv/week6/Week 6 coding/model/network.py
|
0d65271f2868c98a4052e0036c292fdbae18f056
|
[] |
no_license
|
wangqiang79/learn
|
6b37cc41140cc2200d928f3717cfc72357d10d54
|
e4b949a236fa52de0e199c69941bcbedd2c26897
|
refs/heads/master
| 2022-12-25T06:24:39.163061 | 2020-07-13T15:43:13 | 2020-07-13T15:43:13 | 231,796,188 | 2 | 2 | null | 2022-12-08T07:03:05 | 2020-01-04T16:45:33 |
Jupyter Notebook
|
UTF-8
|
Python
| false | false | 1,057 |
py
|
import torch.nn as nn
import torchvision.models as models
from model.module import Block, Bottleneck, DownBottleneck, Layer
#pytorch Torchvision
class ResNet101v2(nn.Module):
'''
ResNet101 model
'''
def __init__(self):
super(ResNet101v2, self).__init__()
#下采样2倍
self.conv1 = Block(3, 64, 7, 3, 2)
self.pool1 = nn.MaxPool2d(kernel_size=3, stride=2, ceil_mode=True)
self.conv2_1 =DownBottleneck(64, 256, stride=1)
self.conv2_2 =Bottleneck(256, 256)
self.conv2_3 =Bottleneck(256, 256)
#下采样2倍 8倍
self.layer3 = Layer(256, [512]*2, "resnet")
#下采样2倍 16倍
self.layer4 = Layer(512, [1024]*23, "resnet")
#下采样2倍 32倍
self.layer5 = Layer(1024, [2048]*3, "resnet")
def forward(self, x):
f1 = self.conv1(x)
f2 = self.conv2_3(self.conv2_2(self.conv2_1(self.pool1(f1))))
f3 = self.layer3(f2)
f4 = self.layer4(f3)
f5 = self.layer5(f4)
return [f2, f3, f4, f5]
|
[
"[email protected]"
] | |
67b5e8386db8e4569b1d1edacc6de547975d3b74
|
af626ade966544b91fbfe0ea81fc887f1b8a2821
|
/qa/rpc-tests/python-bitcoinrtxrpc/setup.py
|
fdfe9d34717f62f28824291c40f42b658d4ca311
|
[
"MIT"
] |
permissive
|
kunalbarchha/bitcoinrtx-old
|
91f2b36a50e009151c61d36e77a563d0c17ab632
|
42c61d652288f183c4607462e2921bb33ba9ec1f
|
refs/heads/master
| 2023-03-13T22:46:36.993580 | 2021-03-04T13:01:00 | 2021-03-04T13:01:00 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 630 |
py
|
#!/usr/bin/env python2
from distutils.core import setup
setup(name='python-bitcoinrtxrpc',
version='0.1',
description='Enhanced version of python-jsonrpc for use with Bitcoinrtx',
long_description=open('README').read(),
author='Jeff Garzik',
author_email='<[email protected]>',
maintainer='Jeff Garzik',
maintainer_email='<[email protected]>',
url='http://www.github.com/jgarzik/python-bitcoinrtxrpc',
packages=['bitcoinrtxrpc'],
classifiers=['License :: OSI Approved :: GNU Library or Lesser General Public License (LGPL)', 'Operating System :: OS Independent'])
|
[
"[email protected]"
] | |
a54826ebaa280ca23aad774cb3f6aec445632e62
|
163bbb4e0920dedd5941e3edfb2d8706ba75627d
|
/Code/CodeRecords/2561/60639/261665.py
|
65b5061f633e844981dc12f1881df53161da5a40
|
[] |
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 | 446 |
py
|
def solution(n,x,arr1,arr2):
sum=0
for i in range(n*n):
if x-arr1[i] in arr2:
sum+=1
else:
continue
print(sum)
t=int(input())
for i in range(t):
inp=input().split()
n=int(inp[0])
x=int(inp[1])
arr1=[]
arr2=[]
for i in range(n):
arr1+=list(map(int,input().split()))
for i in range(n):
arr2+=list(map(int,input().split()))
solution(n,x,arr1,arr2)
|
[
"[email protected]"
] | |
6c8789550af13191f5d64b9eb7d8bbbced53484a
|
d2f6140a45b234711c0b6bce9ab98c9468d6041e
|
/homework/2014-20/similar_hw_3/HenryRueda_primos.py
|
d98f69dad28fbfccad7005e984d6a50995f81e42
|
[] |
no_license
|
ComputoCienciasUniandes/MetodosComputacionalesDatos
|
14b6b78655ed23985ecff28550934dec96f6373b
|
ecc7c21ca13a3b7bbdc7a8ef5715e8c9bf6e48cf
|
refs/heads/master
| 2020-04-10T14:17:03.465444 | 2017-06-09T15:02:57 | 2017-06-09T15:02:57 | 12,526,572 | 0 | 8 | null | null | null | null |
UTF-8
|
Python
| false | false | 1,369 |
py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys,math
if len(sys.argv)<2:
print('\nNo hay suficiente información\n'.format(sys.argv[0]))
sys.exit(0)
Maximo=1000000
n=int(sys.argv[1])
if n<0:
print('\nEl número ingresado es negativo\n'.format(Maximo))
if n == 0:
print ('\n{} no es un número valido para ejecutar este programa\n'.format(0))
sys.exit(0)
if n>Maximo:
print('\nEl número es mayor que un millón\n'.format(Maximo))
sys.exit(0)
arrayprimos = []
factores = set()
for i in range(2, Maximo+1):
if i not in factores:
arrayprimos.append(i)
factores.update(range(i*i, Maximo+1, i))
def es_primo(n):
if n in arrayprimos:
return True
if es_primo(n):
print('\nEl número ingresado es primo\n'.format(n))
sys.exit(0)
k=int(math.sqrt(n)+1)
for i in range (0,k):
aux=float(n)/arrayprimos[i]
if aux%1==0 and es_primo(aux):
if aux!=arrayprimos[i]:
print('\n{} y {}'.format(arrayprimos[i], int(aux)))
sys.exit(0)
break
else:
print('\nexception'.format(arrayprimos[i], int(aux)))
sys.exit(0)
break
print('\nEl número en su descomposición tiene más de dos factores primos')
|
[
"[email protected]"
] | |
d6246ef699c47ce3d1bbcf801835f3fac4236d8f
|
3395a234e7c80d011607e79c49cd48bf516f256b
|
/dependencies/jedi/third_party/typeshed/third_party/2and3/werkzeug/test.pyi
|
764b76d8e78bf0f973af8fbcc504bf8dfd79edde
|
[
"MIT",
"Apache-2.0"
] |
permissive
|
srusskih/SublimeJEDI
|
67329b72e184bc9584843968dcc534a002c797a1
|
95c185d778425c04536d53517b0e3fe6dedf8e59
|
refs/heads/master
| 2023-08-24T11:30:37.801834 | 2022-08-30T09:04:17 | 2022-08-30T09:04:17 | 6,241,108 | 669 | 125 |
MIT
| 2022-08-30T09:04:18 | 2012-10-16T08:23:57 |
Python
|
UTF-8
|
Python
| false | false | 5,957 |
pyi
|
import sys
from wsgiref.types import WSGIEnvironment
from typing import Any, Generic, Optional, Text, Tuple, Type, TypeVar, overload
from typing_extensions import Literal
if sys.version_info < (3,):
from urllib2 import Request as U2Request
from cookielib import CookieJar
else:
from urllib.request import Request as U2Request
from http.cookiejar import CookieJar
def stream_encode_multipart(values, use_tempfile: int = ..., threshold=..., boundary: Optional[Any] = ...,
charset: Text = ...): ...
def encode_multipart(values, boundary: Optional[Any] = ..., charset: Text = ...): ...
def File(fd, filename: Optional[Any] = ..., mimetype: Optional[Any] = ...): ...
class _TestCookieHeaders:
headers: Any
def __init__(self, headers): ...
def getheaders(self, name): ...
def get_all(self, name, default: Optional[Any] = ...): ...
class _TestCookieResponse:
headers: Any
def __init__(self, headers): ...
def info(self): ...
class _TestCookieJar(CookieJar):
def inject_wsgi(self, environ): ...
def extract_wsgi(self, environ, headers): ...
class EnvironBuilder:
server_protocol: Any
wsgi_version: Any
request_class: Any
charset: Text
path: Any
base_url: Any
query_string: Any
args: Any
method: Any
headers: Any
content_type: Any
errors_stream: Any
multithread: Any
multiprocess: Any
run_once: Any
environ_base: Any
environ_overrides: Any
input_stream: Any
content_length: Any
closed: Any
def __init__(self, path: str = ..., base_url: Optional[Any] = ..., query_string: Optional[Any] = ...,
method: str = ..., input_stream: Optional[Any] = ..., content_type: Optional[Any] = ...,
content_length: Optional[Any] = ..., errors_stream: Optional[Any] = ..., multithread: bool = ...,
multiprocess: bool = ..., run_once: bool = ..., headers: Optional[Any] = ..., data: Optional[Any] = ...,
environ_base: Optional[Any] = ..., environ_overrides: Optional[Any] = ..., charset: Text = ...): ...
form: Any
files: Any
@property
def server_name(self): ...
@property
def server_port(self): ...
def __del__(self): ...
def close(self): ...
def get_environ(self): ...
def get_request(self, cls: Optional[Any] = ...): ...
class ClientRedirectError(Exception): ...
# Response type for the client below.
# By default _R is Tuple[Iterable[Any], Union[Text, int], datastructures.Headers]
_R = TypeVar('_R')
class Client(Generic[_R]):
application: Any
response_wrapper: Optional[Type[_R]]
cookie_jar: Any
allow_subdomain_redirects: Any
def __init__(self, application, response_wrapper: Optional[Type[_R]] = ..., use_cookies: bool = ...,
allow_subdomain_redirects: bool = ...): ...
def set_cookie(self, server_name, key, value: str = ..., max_age: Optional[Any] = ..., expires: Optional[Any] = ...,
path: str = ..., domain: Optional[Any] = ..., secure: Optional[Any] = ..., httponly: bool = ...,
charset: Text = ...): ...
def delete_cookie(self, server_name, key, path: str = ..., domain: Optional[Any] = ...): ...
def run_wsgi_app(self, environ, buffered: bool = ...): ...
def resolve_redirect(self, response, new_location, environ, buffered: bool = ...): ...
@overload
def open(self, *args, as_tuple: Literal[True], **kwargs) -> Tuple[WSGIEnvironment, _R]: ...
@overload
def open(self, *args, as_tuple: Literal[False] = ..., **kwargs) -> _R: ...
@overload
def open(self, *args, as_tuple: bool, **kwargs) -> Any: ...
@overload
def get(self, *args, as_tuple: Literal[True], **kw) -> Tuple[WSGIEnvironment, _R]: ...
@overload
def get(self, *args, as_tuple: Literal[False] = ..., **kw) -> _R: ...
@overload
def get(self, *args, as_tuple: bool, **kw) -> Any: ...
@overload
def patch(self, *args, as_tuple: Literal[True], **kw) -> Tuple[WSGIEnvironment, _R]: ...
@overload
def patch(self, *args, as_tuple: Literal[False] = ..., **kw) -> _R: ...
@overload
def patch(self, *args, as_tuple: bool, **kw) -> Any: ...
@overload
def post(self, *args, as_tuple: Literal[True], **kw) -> Tuple[WSGIEnvironment, _R]: ...
@overload
def post(self, *args, as_tuple: Literal[False] = ..., **kw) -> _R: ...
@overload
def post(self, *args, as_tuple: bool, **kw) -> Any: ...
@overload
def head(self, *args, as_tuple: Literal[True], **kw) -> Tuple[WSGIEnvironment, _R]: ...
@overload
def head(self, *args, as_tuple: Literal[False] = ..., **kw) -> _R: ...
@overload
def head(self, *args, as_tuple: bool, **kw) -> Any: ...
@overload
def put(self, *args, as_tuple: Literal[True], **kw) -> Tuple[WSGIEnvironment, _R]: ...
@overload
def put(self, *args, as_tuple: Literal[False] = ..., **kw) -> _R: ...
@overload
def put(self, *args, as_tuple: bool, **kw) -> Any: ...
@overload
def delete(self, *args, as_tuple: Literal[True], **kw) -> Tuple[WSGIEnvironment, _R]: ...
@overload
def delete(self, *args, as_tuple: Literal[False] = ..., **kw) -> _R: ...
@overload
def delete(self, *args, as_tuple: bool, **kw) -> Any: ...
@overload
def options(self, *args, as_tuple: Literal[True], **kw) -> Tuple[WSGIEnvironment, _R]: ...
@overload
def options(self, *args, as_tuple: Literal[False] = ..., **kw) -> _R: ...
@overload
def options(self, *args, as_tuple: bool, **kw) -> Any: ...
@overload
def trace(self, *args, as_tuple: Literal[True], **kw) -> Tuple[WSGIEnvironment, _R]: ...
@overload
def trace(self, *args, as_tuple: Literal[False] = ..., **kw) -> _R: ...
@overload
def trace(self, *args, as_tuple: bool, **kw) -> Any: ...
def create_environ(*args, **kwargs): ...
def run_wsgi_app(app, environ, buffered: bool = ...): ...
|
[
"[email protected]"
] | |
5478f0ed6e84d36a081197e9e17ed5b0e151144f
|
7fa08c93ff0caa4c86d4fa1727643331e081c0d0
|
/brigid_api_client/models/__init__.py
|
116e0784876b77021f16b674f520d34edb77dc10
|
[
"LicenseRef-scancode-warranty-disclaimer",
"MIT"
] |
permissive
|
caltechads/brigid-api-client
|
760768c05280a4fb2f485e27c05f6ae24fbb7c6f
|
3e885ac9e7b3c00b8a9e0cc1fb7b53b468d9e10a
|
refs/heads/master
| 2023-03-23T03:11:02.446720 | 2021-03-13T00:47:03 | 2021-03-13T00:47:03 | 338,424,261 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 7,175 |
py
|
""" Contains all the data models used in inputs/outputs """
from .action_response import ActionResponse
from .action_response_errors import ActionResponseErrors
from .application import Application
from .applications_list_expand import ApplicationsListExpand
from .applications_retrieve_expand import ApplicationsRetrieveExpand
from .aws_account import AWSAccount
from .aws_accounts_list_expand import AwsAccountsListExpand
from .aws_accounts_retrieve_expand import AwsAccountsRetrieveExpand
from .aws_clusters_list_expand import AwsClustersListExpand
from .aws_clusters_retrieve_expand import AwsClustersRetrieveExpand
from .aws_services_list_expand import AwsServicesListExpand
from .aws_services_retrieve_expand import AwsServicesRetrieveExpand
from .aws_tasks_list_expand import AwsTasksListExpand
from .aws_tasks_retrieve_expand import AwsTasksRetrieveExpand
from .aws_vpcs_list_expand import AwsVpcsListExpand
from .aws_vpcs_retrieve_expand import AwsVpcsRetrieveExpand
from .awsecs_cluster import AWSECSCluster
from .awsecs_service import AWSECSService
from .awsecs_task import AWSECSTask
from .awsvpc import AWSVPC
from .deployment import Deployment
from .deployments_list_expand import DeploymentsListExpand
from .deployments_retrieve_expand import DeploymentsRetrieveExpand
from .docker_image_build import DockerImageBuild
from .docker_image_builds_list_expand import DockerImageBuildsListExpand
from .docker_image_builds_retrieve_expand import DockerImageBuildsRetrieveExpand
from .ecosystem import Ecosystem
from .ecosystems_list_expand import EcosystemsListExpand
from .ecosystems_retrieve_expand import EcosystemsRetrieveExpand
from .ecs_service_deploy import ECSServiceDeploy
from .ecs_service_deploys_list_expand import EcsServiceDeploysListExpand
from .ecs_service_deploys_retrieve_expand import EcsServiceDeploysRetrieveExpand
from .ecs_task_deploy import ECSTaskDeploy
from .ecs_task_deploys_list_expand import EcsTaskDeploysListExpand
from .ecs_task_deploys_retrieve_expand import EcsTaskDeploysRetrieveExpand
from .environment import Environment
from .environments_list_expand import EnvironmentsListExpand
from .environments_retrieve_expand import EnvironmentsRetrieveExpand
from .organization import Organization
from .organizations_list_expand import OrganizationsListExpand
from .organizations_retrieve_expand import OrganizationsRetrieveExpand
from .paginated_application_list import PaginatedApplicationList
from .paginated_aws_account_list import PaginatedAWSAccountList
from .paginated_awsecs_cluster_list import PaginatedAWSECSClusterList
from .paginated_awsecs_service_list import PaginatedAWSECSServiceList
from .paginated_awsecs_task_list import PaginatedAWSECSTaskList
from .paginated_awsvpc_list import PaginatedAWSVPCList
from .paginated_deployment_list import PaginatedDeploymentList
from .paginated_docker_image_build_list import PaginatedDockerImageBuildList
from .paginated_ecosystem_list import PaginatedEcosystemList
from .paginated_ecs_service_deploy_list import PaginatedECSServiceDeployList
from .paginated_ecs_task_deploy_list import PaginatedECSTaskDeployList
from .paginated_environment_list import PaginatedEnvironmentList
from .paginated_organization_list import PaginatedOrganizationList
from .paginated_person_type_list import PaginatedPersonTypeList
from .paginated_pipeline_invocation_list import PaginatedPipelineInvocationList
from .paginated_pipeline_list import PaginatedPipelineList
from .paginated_release_list import PaginatedReleaseList
from .paginated_site_user_list import PaginatedSiteUserList
from .paginated_software_list import PaginatedSoftwareList
from .paginated_step_invocation_list import PaginatedStepInvocationList
from .paginated_step_list import PaginatedStepList
from .paginated_step_type_list import PaginatedStepTypeList
from .paginated_team_list import PaginatedTeamList
from .paginated_test_result_list import PaginatedTestResultList
from .patched_application import PatchedApplication
from .patched_aws_account import PatchedAWSAccount
from .patched_awsecs_cluster import PatchedAWSECSCluster
from .patched_awsecs_service import PatchedAWSECSService
from .patched_awsecs_task import PatchedAWSECSTask
from .patched_awsvpc import PatchedAWSVPC
from .patched_deployment import PatchedDeployment
from .patched_docker_image_build import PatchedDockerImageBuild
from .patched_ecosystem import PatchedEcosystem
from .patched_ecs_service_deploy import PatchedECSServiceDeploy
from .patched_ecs_task_deploy import PatchedECSTaskDeploy
from .patched_environment import PatchedEnvironment
from .patched_organization import PatchedOrganization
from .patched_person_type import PatchedPersonType
from .patched_pipeline import PatchedPipeline
from .patched_pipeline_invocation import PatchedPipelineInvocation
from .patched_release import PatchedRelease
from .patched_site_user import PatchedSiteUser
from .patched_software import PatchedSoftware
from .patched_step import PatchedStep
from .patched_step_invocation import PatchedStepInvocation
from .patched_step_type import PatchedStepType
from .patched_team import PatchedTeam
from .patched_test_result import PatchedTestResult
from .person_type import PersonType
from .pipeines_list_expand import PipeinesListExpand
from .pipeines_retrieve_expand import PipeinesRetrieveExpand
from .pipeline import Pipeline
from .pipeline_invocation import PipelineInvocation
from .pipeline_invocations_list_expand import PipelineInvocationsListExpand
from .pipeline_invocations_retrieve_expand import PipelineInvocationsRetrieveExpand
from .pipeline_step_invocations_list_expand import PipelineStepInvocationsListExpand
from .pipeline_step_invocations_retrieve_expand import (
PipelineStepInvocationsRetrieveExpand,
)
from .pipeline_steps_list_expand import PipelineStepsListExpand
from .pipeline_steps_retrieve_expand import PipelineStepsRetrieveExpand
from .release import Release
from .release_import import ReleaseImport
from .release_import_all import ReleaseImportAll
from .release_import_all_response import ReleaseImportAllResponse
from .release_import_all_response_errors import ReleaseImportAllResponseErrors
from .releases_list_expand import ReleasesListExpand
from .releases_retrieve_expand import ReleasesRetrieveExpand
from .schema_retrieve_format import SchemaRetrieveFormat
from .schema_retrieve_response_200 import SchemaRetrieveResponse_200
from .service_enum import ServiceEnum
from .site_user import SiteUser
from .site_users_list_expand import SiteUsersListExpand
from .site_users_retrieve_expand import SiteUsersRetrieveExpand
from .software import Software
from .software_import import SoftwareImport
from .software_list_expand import SoftwareListExpand
from .software_retrieve_expand import SoftwareRetrieveExpand
from .status_enum import StatusEnum
from .step import Step
from .step_invocation import StepInvocation
from .step_type import StepType
from .team import Team
from .teams_list_expand import TeamsListExpand
from .teams_retrieve_expand import TeamsRetrieveExpand
from .test_result import TestResult
from .test_results_list_expand import TestResultsListExpand
from .test_results_retrieve_expand import TestResultsRetrieveExpand
|
[
"[email protected]"
] | |
ec5779ee0e273f9ab8b597108e3e042acb1ccd27
|
591900bf248906d0c80fbb02174b0c3be6de376f
|
/torch_scatter/__init__.py
|
e43f88eefbc902eb16d43b425fbd5f348a6e202f
|
[
"MIT"
] |
permissive
|
xychen9459/pytorch_scatter
|
0e02a2028faa98acc30fa3b7b082ea52cab5f70c
|
b9570ccd71622f9a7b2d311a1607bb3914801743
|
refs/heads/master
| 2020-04-17T00:09:30.541736 | 2018-12-27T11:37:55 | 2018-12-27T11:37:55 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 444 |
py
|
from .add import scatter_add
from .sub import scatter_sub
from .mul import scatter_mul
from .div import scatter_div
from .mean import scatter_mean
from .std import scatter_std
from .max import scatter_max
from .min import scatter_min
__version__ = '1.1.0'
__all__ = [
'scatter_add',
'scatter_sub',
'scatter_mul',
'scatter_div',
'scatter_mean',
'scatter_std',
'scatter_max',
'scatter_min',
'__version__',
]
|
[
"[email protected]"
] | |
a771d28bdbf0a941f858c851bbe836950980bc83
|
2fd0c65aa0f72133f773dac5d9a5c48fe9e26fac
|
/Python/Core/Lib/idlelib/Bindings.py
|
896d83102673640507f98caa05d20c390622944e
|
[] |
no_license
|
FingerLeakers/DanderSpritz_docs
|
f5d2430e0b86b1b2f0684f02ddd4fa973a5a7364
|
d96b6a71c039b329f9f81544f645857c75360e7f
|
refs/heads/master
| 2021-01-25T13:05:51.732149 | 2018-03-08T01:22:49 | 2018-03-08T01:22:49 | 123,527,268 | 2 | 0 | null | 2018-03-02T03:48:31 | 2018-03-02T03:48:30 | null |
UTF-8
|
Python
| false | false | 3,003 |
py
|
# uncompyle6 version 2.9.10
# Python bytecode 2.7 (62211)
# Decompiled from: Python 2.7.10 (default, Feb 6 2017, 23:53:20)
# [GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.34)]
# Embedded file name: Bindings.py
"""Define the menu contents, hotkeys, and event bindings.
There is additional configuration information in the EditorWindow class (and
subclasses): the menus are created there based on the menu_specs (class)
variable, and menus not created are silently skipped in the code here. This
makes it possible, for example, to define a Debug menu which is only present in
the PythonShell window, and a Format menu which is only present in the Editor
windows.
"""
import sys
from idlelib.configHandler import idleConf
from idlelib import macosxSupport
menudefs = [
(
'file',
[
('_New Window', '<<open-new-window>>'),
('_Open...', '<<open-window-from-file>>'),
('Open _Module...', '<<open-module>>'),
('Class _Browser', '<<open-class-browser>>'),
('_Path Browser', '<<open-path-browser>>'),
None,
('_Save', '<<save-window>>'),
('Save _As...', '<<save-window-as-file>>'),
('Save Cop_y As...', '<<save-copy-of-window-as-file>>'),
None,
('Prin_t Window', '<<print-window>>'),
None,
('_Close', '<<close-window>>'),
('E_xit', '<<close-all-windows>>')]),
(
'edit',
[
('_Undo', '<<undo>>'),
('_Redo', '<<redo>>'),
None,
('Cu_t', '<<cut>>'),
('_Copy', '<<copy>>'),
('_Paste', '<<paste>>'),
('Select _All', '<<select-all>>'),
None,
('_Find...', '<<find>>'),
('Find A_gain', '<<find-again>>'),
('Find _Selection', '<<find-selection>>'),
('Find in Files...', '<<find-in-files>>'),
('R_eplace...', '<<replace>>'),
('Go to _Line', '<<goto-line>>')]),
(
'format',
[
('_Indent Region', '<<indent-region>>'),
('_Dedent Region', '<<dedent-region>>'),
('Comment _Out Region', '<<comment-region>>'),
('U_ncomment Region', '<<uncomment-region>>'),
('Tabify Region', '<<tabify-region>>'),
('Untabify Region', '<<untabify-region>>'),
('Toggle Tabs', '<<toggle-tabs>>'),
('New Indent Width', '<<change-indentwidth>>')]),
(
'run',
[
('Python Shell', '<<open-python-shell>>')]),
(
'shell',
[
('_View Last Restart', '<<view-restart>>'),
('_Restart Shell', '<<restart-shell>>')]),
(
'debug',
[
('_Go to File/Line', '<<goto-file-line>>'),
('!_Debugger', '<<toggle-debugger>>'),
('_Stack Viewer', '<<open-stack-viewer>>'),
('!_Auto-open Stack Viewer', '<<toggle-jit-stack-viewer>>')]),
(
'options',
[
('_Configure IDLE...', '<<open-config-dialog>>'),
None]),
(
'help',
[
('_About IDLE', '<<about-idle>>'),
None,
('_IDLE Help', '<<help>>'),
('Python _Docs', '<<python-docs>>')])]
if macosxSupport.runningAsOSXApp():
quitItem = menudefs[0][1][-1]
closeItem = menudefs[0][1][-2]
del menudefs[0][1][-3:]
menudefs[0][1].insert(6, closeItem)
del menudefs[-1][1][0:2]
default_keydefs = idleConf.GetCurrentKeySet()
del sys
|
[
"[email protected]"
] | |
3992e4cfa297274e2d85355c42f979d6de7326c2
|
f52997ac7e1b41f34018c3a0028ced8638072b2b
|
/src/peoplefinder/migrations/0090_data_person_new_country.py
|
1745636c4926fcb0b87247bd92c8f80294e57bf4
|
[
"MIT"
] |
permissive
|
uktrade/digital-workspace-v2
|
49fae1fca819b625c6f6949fb5ce51b89fbcab96
|
7e328d0d55c9aa73be61f476823a743d96e792d0
|
refs/heads/main
| 2023-09-03T12:03:47.016608 | 2023-09-01T12:07:55 | 2023-09-01T12:07:55 | 232,302,840 | 6 | 0 |
MIT
| 2023-09-13T15:50:24 | 2020-01-07T10:41:18 |
Python
|
UTF-8
|
Python
| false | false | 820 |
py
|
# Generated by Django 3.2.13 on 2022-05-23 13:15
from django.db import migrations
def insert_person_new_country(apps, schema_editor):
Person = apps.get_model("peoplefinder", "Person")
Country = apps.get_model("countries", "Country")
all_people = Person.objects.select_related("country").all()
country_lookup = Country.objects.all().in_bulk(field_name="iso_2_code")
people_to_update = []
for person in all_people:
person.new_country = country_lookup[person.country.code]
people_to_update.append(person)
Person.objects.bulk_update(people_to_update, ["new_country"], batch_size=100)
class Migration(migrations.Migration):
dependencies = [
("peoplefinder", "0089_person_new_country"),
]
operations = [migrations.RunPython(insert_person_new_country)]
|
[
"[email protected]"
] | |
03960f0f3fa5ef588fe7de7fb3dff054e493b677
|
90e1f9d99ab05ce34380f7b63ec3c6a2f02f3d62
|
/src/team503/src/traffic_sign_detect/CNN_3channels_4conv.py
|
18f641b42ae797f3a77c79becae44d8dd3b29087
|
[] |
no_license
|
sihcpro/The-Number1c-Rac1ng
|
eb038099c8deb6fbb6e88cde60c7a7f25474e5da
|
856434acec52f52a8784199180692abbdb4a49e8
|
refs/heads/master
| 2020-04-12T10:07:24.182205 | 2019-01-15T22:21:43 | 2019-01-15T22:21:43 | 162,419,934 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 3,463 |
py
|
import pickle
import cv2
from sklearn.utils import shuffle
import tensorflow as tf
TRAIN_DATA_DIR = "data/raw/training/augmented/"
TEST_DATA_DIR = "data/raw/testing"
# TEST_DATA_DIR = "data/raw/testing/00014"
CNN_MODEL_DIR = "model/CNN/3cnn_4conv.ckpt"
PICKLE_IMGS_DIR = "data/pickle/train_imgs_56.pkl"
PICKLE_LABELS_DIR = "data/pickle/test_labels.pkl"
NUM_CLASSES = 9
IMG_SIZE = 56
def deepnn(x):
with tf.name_scope('reshape'):
x_image = x
# x_image = tf.placeholder([-1, 28, 28, 3])
# First convolutional layer - maps one grayscale image to 32 feature maps.
with tf.name_scope('conv1'):
W_conv1 = weight_variable([5, 5, 3, 32])
b_conv1 = bias_variable([32])
h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1)
# Pooling layer - downsamples by 2X.
with tf.name_scope('pool1'):
h_pool1 = max_pool_2x2(h_conv1)
# Second convolutional layer -- maps 32 feature maps to 64.
with tf.name_scope('conv2'):
W_conv2 = weight_variable([5, 5, 32, 64])
b_conv2 = bias_variable([64])
h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2)
# Second pooling layer.
with tf.name_scope('pool2'):
h_pool2 = max_pool_2x2(h_conv2)
# Third convolutional layer -- maps 64 feature maps to 64.
with tf.name_scope('conv3'):
W_conv3 = weight_variable([5, 5, 64, 64])
b_conv3 = bias_variable([64])
h_conv3 = tf.nn.relu(conv2d(h_pool2, W_conv3) + b_conv3)
# Forth convolutional layer -- maps 64 feature maps to 64.
with tf.name_scope('conv4'):
W_conv4 = weight_variable([5, 5, 64, 64])
b_conv4 = bias_variable([64])
h_conv4 = tf.nn.relu(conv2d(h_conv3, W_conv4) + b_conv4)
# Third pooling layer.
with tf.name_scope('pool3'):
h_pool3 = max_pool_2x2(h_conv4)
# Fully connected layer 1 -- after 2 round of downsampling, our 28x28 image
# is down to 7x7x64 feature maps -- maps this to 1024 features.
with tf.name_scope('fc1'):
W_fc1 = weight_variable([7 * 7 * 64, 1024])
b_fc1 = bias_variable([1024])
h_pool3_flat = tf.reshape(h_pool3, [-1, 7 * 7 * 64])
h_fc1 = tf.nn.relu(tf.matmul(h_pool3_flat, W_fc1) + b_fc1)
# Dropout - controls the complexity of the model, prevents co-adaptation of
# features.
with tf.name_scope('dropout'):
keep_prob = tf.placeholder(tf.float32)
h_fc1_drop = tf.nn.dropout(h_fc1, keep_prob)
# Map the 1024 features to NUM_CLASSES classes, one for each digit
with tf.name_scope('fc2'):
W_fc2 = weight_variable([1024, NUM_CLASSES])
b_fc2 = bias_variable([NUM_CLASSES])
y_conv = tf.matmul(h_fc1_drop, W_fc2) + b_fc2
return y_conv, keep_prob
def conv2d(x, W):
"""conv2d returns a 2d convolution layer with full stride."""
return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME')
def max_pool_2x2(x):
"""max_pool_2x2 downsamples a feature map by 2X."""
return tf.nn.max_pool(x, ksize=[1, 2, 2, 1],
strides=[1, 2, 2, 1], padding='SAME')
def weight_variable(shape):
"""weight_variable generates a weight variable of a given shape."""
initial = tf.truncated_normal(shape, stddev=0.1)
return tf.Variable(initial)
def bias_variable(shape):
"""bias_variable generates a bias variable of a given shape."""
initial = tf.constant(0.1, shape=shape)
return tf.Variable(initial)
|
[
"[email protected]"
] | |
89fbdba1b70cdb22da26e68b9978fd3abcd9e436
|
6e3e1834eaad3a0c97bf645238e59a0599e047b4
|
/blog/feeds.py
|
720465e3999af4b68079e03f4bb4db306ed758e4
|
[
"JSON"
] |
permissive
|
davogler/davsite
|
2dc42bfebb476d94f92520e8829999859deae80b
|
edd8ceed560690fa2c3eefde236416ffba559a2e
|
refs/heads/master
| 2021-01-19T06:31:20.655909 | 2014-01-03T19:04:13 | 2014-01-03T19:04:13 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 1,119 |
py
|
from django.core.exceptions import ObjectDoesNotExist
from django.utils.feedgenerator import Atom1Feed
from django.contrib.sites.models import Site
from django.contrib.syndication.views import Feed
from blog.models import Category, Entry
current_site = Site.objects.get_current()
class LatestEntriesFeed(Feed):
author_name = "David Vogler"
copyright = "http://%s/about/" % current_site.domain
description = "Latest entries posted to %s" % current_site.name
feed_type = Atom1Feed
item_copyright = "http://%s/about/" % current_site.domain
item_author_name = "David Vogler"
item_author_link = "http://%s/" % current_site.domain
link = "/feeds/entries/"
title = "%s: Latest entries" % current_site.name
def items(self):
return Entry.live.all()[:15]
def item_pubdate(self, item):
return item.pub_date
def item_guid(self, item):
return "tag:%s,%s:%s" % (current_site.domain, item.pub_date.strftime('%Y-%m-%d'), item.get_absolute_url())
def item_categories(self, item):
return [c.title for c in item.categories.all()]
|
[
"[email protected]"
] | |
6d935daa518bfb71dc1ec9c4b2da0127e0dcea10
|
2d5d13c4bdc64202a520f32e7d4a44bb75e2004f
|
/week-02/d04/substr.py
|
ebcf9c90389536fc31a978afb81cdf52ff7d22e8
|
[] |
no_license
|
green-fox-academy/andrasnyarai
|
43b32d5cc4ad3792ef8d621328f9593fc9623e0b
|
19759a146ba2f63f1c3e4e51160e6111ca0ee9c3
|
refs/heads/master
| 2021-09-07T16:19:34.636119 | 2018-02-26T00:38:00 | 2018-02-26T00:38:00 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 391 |
py
|
# Create a function that takes two strings as a parameter
# Returns the starting index where the second one is starting in the first one
# Returns -1 if the second string is not in the first one
input = "this is what I'm searching in"
input_word = "searching"
def searching(sentence, word):
s_index = sentence.find(word, 1)
return s_index
print(searching(input, input_word))
|
[
"[email protected]"
] | |
27e4ddb0ceff016becbe4500d30ff6f059b91134
|
9fb13659c6c73996581fb252ef33ef589392770b
|
/test_utilities/src/d1_test/mock_api/tests/test_create.py
|
ad6d8382c9c6dd166ce7ff5c8bbaf0ca676a6362
|
[
"Apache-2.0"
] |
permissive
|
xlia/d1_python
|
ea9585c462cb1e4f2d50ff1c9ce17a33e7649265
|
c4745e70a00b14fc1d8c66c6995a2d150ef69956
|
refs/heads/master
| 2021-09-07T08:48:02.123106 | 2018-02-20T14:59:33 | 2018-02-20T14:59:33 | 113,352,728 | 0 | 0 | null | 2018-02-20T14:39:00 | 2017-12-06T18:28:20 |
Python
|
UTF-8
|
Python
| false | false | 2,064 |
py
|
# -*- coding: utf-8 -*-
# This work was created by participants in the DataONE project, and is
# jointly copyrighted by participating institutions in DataONE. For
# more information on DataONE, see our web site at http://dataone.org.
#
# Copyright 2009-2016 DataONE
#
# 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 __future__ import absolute_import
import base64
import json
import StringIO
import responses
import d1_test.d1_test_case
import d1_test.mock_api.create as mock_create
import d1_test.mock_api.util
class TestMockPost(d1_test.d1_test_case.D1TestCase):
@responses.activate
def test_1000(self, mn_client_v1_v2):
"""mock_api.create(): Echoes the request"""
mock_create.add_callback(d1_test.d1_test_case.MOCK_BASE_URL)
pid, sid, sciobj_str, sysmeta_pyxb = \
d1_test.instance_generator.sciobj.generate_reproducible(mn_client_v1_v2, 'post_pid')
response = mn_client_v1_v2.createResponse(
'post_pid', StringIO.StringIO(sciobj_str), sysmeta_pyxb
)
identifier_pyxb = mn_client_v1_v2.bindings.CreateFromDocument(
response.content
)
assert identifier_pyxb.value() == 'echo-post'
echo_body_str = base64.b64decode(response.headers['Echo-Body-Base64'])
echo_query_dict = json.loads(
base64.b64decode(response.headers['Echo-Query-Base64'])
)
echo_header_dict = json.loads(
base64.b64decode(response.headers['Echo-Header-Base64'])
)
assert isinstance(echo_body_str, basestring)
assert isinstance(echo_query_dict, dict)
assert isinstance(echo_header_dict, dict)
|
[
"[email protected]"
] | |
45a1455cad84d3b82f52be1726c8da09b1788c0b
|
1b8a99a4ff80da51dc81dd8354bf9bf1cbd25a8b
|
/2022/special_array_with_x_elements_greater_than_or_equal_x.py
|
1eed93272f0a62c0218b8b94b721fe028f723576
|
[] |
no_license
|
eronekogin/leetcode
|
ea639eebe0cd70af9eb4cba59bc68f636d7b3e0c
|
edb870f83f0c4568cce0cacec04ee70cf6b545bf
|
refs/heads/master
| 2023-08-16T10:35:57.164176 | 2023-08-14T11:25:33 | 2023-08-14T11:25:33 | 163,679,450 | 0 | 0 | null | 2021-09-09T12:04:44 | 2018-12-31T15:33:06 |
Python
|
UTF-8
|
Python
| false | false | 624 |
py
|
"""
https://leetcode.com/problems/special-array-with-x-elements-greater-than-or-equal-x/
"""
class Solution:
def specialArray(self, nums: list[int]) -> int:
sortedNums = sorted(nums, reverse=True)
N = len(nums)
for i in range(N):
x = i + 1
if sortedNums[i] >= x: # Now we have x numbers >= x.
if i == len(nums) - 1 or sortedNums[i + 1] < x:
# Make sure exactly x numbers are >= x:
# 1. No more numbers left.
# 2. The next number is less than x.
return x
return -1
|
[
"[email protected]"
] | |
55d553eca6268f2d5ec4ae4a218148c431371d37
|
68ac39d3f59988f3a5e581041a76d8d6c2f00d5d
|
/happy/HappyNodeTcpReset.py
|
0ff3935eb6ed51ce7a5d6958029ecaa0617f4a7c
|
[
"Apache-2.0"
] |
permissive
|
emargolis/happy
|
62f274ff21e8be66922e239acaf7bbb6f53cea27
|
40d6e216d1a671c14b72e7e59f23b98cbda5d954
|
refs/heads/master
| 2021-01-16T15:16:25.950683 | 2020-02-26T20:04:06 | 2020-02-26T20:07:05 | 243,164,644 | 0 | 0 |
Apache-2.0
| 2020-02-26T04:02:20 | 2020-02-26T04:02:19 | null |
UTF-8
|
Python
| false | false | 4,586 |
py
|
#!/usr/bin/env python
#
# Copyright (c) 2016-2017 Nest Labs, Inc.
# All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
##
# @file
# Implements HappyNodeTcpReset class through which nodes reset tcp connection on specific interface
#
#
import os
import sys
from happy.ReturnMsg import ReturnMsg
from happy.Utils import *
from happy.HappyNode import HappyNode
import happy.HappyProcessStart
options = {}
options["quiet"] = False
options["node_id"] = None
options["action"] = None
options["interface"] = None
options["start"] = None
options["duration"] = None
options["ips"] = None
options["dstPort"] = None
def option():
return options.copy()
class HappyNodeTcpReset(HappyNode):
"""
Provides tcpkill functionality to virtual nodes. Use this to test DoS attacks on a
Happy network by blocking TCP connections to specific nodes, interfaces, and ports.
happy-node-tcp-reset [-h --help] [-q --quiet] [-i --id <NODE_NAME>] [--interface <IFACE>]
[-s --start <START_TIME>] [-d --duration <DURATION>] [--ips <SOURCE_IP,DEST_IP>]
[--dstPort <DEST_PORT>]
-i --id Required. Target node to block connections for. Find using
happy-node-list or happy-state.
--interface Target node interface to block connections for.
-s --start Time to initiate TCP block, in seconds from NOW
-d --duration Time to maintain TCP block, in seconds from <START_TIME>
--ips Source and destination IPs to block connections for.
--dstPort Destination port to block connections for.
Example:
$ happy-node-tcp-reset --id BorderRouter --interface wlan0 --start 2 --duration 20 --dstPort 11095
Kills the TCP connection for the BorderRouter node's wlan0 interface for 18 seconds.
return:
0 success
1 fail
"""
def __init__(self, opts=options):
HappyNode.__init__(self)
self.quiet = opts["quiet"]
self.node_id = opts["node_id"]
self.action = opts["action"]
self.interface = opts["interface"]
self.begin = opts["start"]
self.duration = opts["duration"]
self.ips = opts["ips"]
self.dstPort = opts["dstPort"]
def __pre_check(self):
# Check if the name of the node is given
if not self.node_id:
emsg = "Missing name of the virtual node that should join a network."
self.logger.error("[localhost] HappyNodeJoin: %s" % (emsg))
self.exit()
# Check if node exists
if not self._nodeExists():
emsg = "virtual node %s does not exist." % (self.node_id)
self.logger.error("[%s] HappyNodeJoin: %s" % (self.node_id, emsg))
self.exit()
def start_process(self, node_id, cmd, tag, quiet=None, strace=True):
emsg = "start_weave_process %s at %s node." % (tag, node_id)
self.logger.debug("[%s] process: %s" % (node_id, emsg))
options = happy.HappyProcessStart.option()
options["quiet"] = self.quiet
options["node_id"] = node_id
options["tag"] = tag
options["command"] = cmd
options["strace"] = True
proc = happy.HappyProcessStart.HappyProcessStart(options)
proc.run()
def __TcpResetConnection(self):
path = os.path.dirname(os.path.abspath(__file__))
cmd = "python " + path + "/HappyPacketProcess.py --interface %s --start %d --duration %d --action RESET " % \
(self.interface, self.begin, self.duration)
if self.ips is not None:
cmd += " --ips %s" % self.ips
if self.dstPort is not None:
cmd += " --dstPort %d" % self.dstPort
if self.quiet is True:
cmd += " --quiet"
cmd = self.runAsRoot(cmd)
self.start_process(node_id=self.node_id, cmd=cmd, tag="TcpReset")
def run(self):
self.__pre_check()
self.__TcpResetConnection()
return ReturnMsg(0)
|
[
"[email protected]"
] | |
4f410a564f81eef398f188eb979ce9c032a2ffb0
|
a2c90d183ac66f39401cd8ece5207c492c811158
|
/Solving_Problem/daily_222/1205/4991.py
|
93e9003c98ad92771f5ba370d3f2e866995051df
|
[] |
no_license
|
kwoneyng/TIL
|
0498cfc4dbebbb1f2c193cb7c9459aab7ebad02a
|
c6fbaa609b2e805f298b17b1f9504fd12cb63e8a
|
refs/heads/master
| 2020-06-17T11:53:38.685202 | 2020-03-18T01:29:36 | 2020-03-18T01:29:36 | 195,916,103 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 1,848 |
py
|
from collections import deque
from heapq import heappop, heappush
near = [[-1,0], [0,1], [1,0], [0,-1]]
def val_cha(st,ed):
temp = [i[:] for i in bd]
sx,sy = ht[st]
ex,ey = ht[ed]
serve = deque()
serve.append([sx,sy])
cnt = 0
while serve:
cnt += 1
for i in range(len(serve)):
x,y = serve.popleft()
if x == ex and y == ey:
dt[st][ed] = cnt - 1
dt[ed][st] = cnt - 1
return 0
for a,b in near:
xi,yi = a+x, b+y
if 0 <= xi < h and 0 <= yi < w and temp[xi][yi] != 'x':
temp[xi][yi] = 'x'
serve.append([xi, yi])
return -1
def build_root(vis, start=0, cnt=0):
global rs
if sum(vis) == dirty - 1:
rs = min(rs, cnt)
return 0
for i in range(1,dirty):
if not vis[i]:
vis[i] = 1
build_root(vis,i,cnt+dt[start][i])
vis[i] = 0
while True:
w,h = map(int,input().split())
if w == 0 and h == 0:
break
bd = [list(input()) for i in range(h)]
dirty = 1
rs = 9999999999999999999999
ht = {}
for x in range(h):
for y in range(w):
if bd[x][y] == 'o':
ht[0] = [x,y]
elif bd[x][y] == '*':
ht[dirty] = [x,y]
dirty += 1
dt = {}
for i in range(dirty):
dt[i] = {}
stop_flag = 0
for i in range(dirty-1):
if stop_flag == 0:
for j in range(i+1,dirty):
if val_cha(i,j) == -1:
print(-1)
stop_flag = 1
break
else:
break
if stop_flag == 0:
vis = [0]*dirty
build_root(vis)
print(rs)
|
[
"[email protected]"
] | |
7c65675d6822a7edaf6bb50bacade930252936a7
|
6e3b8a04a074c30cf4fc43abe7a208f772df795b
|
/Data Types and Variables - Exercise/Task1.py
|
c017814f490a499fbf7b164e9cedce6713f5cc9e
|
[] |
no_license
|
majurski/Softuni_Fundamentals
|
dc0808fdaab942896eebfb208fb6b291df797752
|
bf53a9efdcb45eb911624ab86d762a6281391fb8
|
refs/heads/master
| 2022-11-29T06:06:06.287984 | 2020-08-10T19:36:18 | 2020-08-10T19:36:18 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 136 |
py
|
a = int(input())
b = int(input())
c = int(input())
d = int(input())
sum = a + b
division = int(sum / c)
ends = division * d
print(ends)
|
[
"[email protected]"
] | |
e67f7e37e6cce0a557a8d702c6bab8d31037acd8
|
5b764b91be0016ee703fca41927b1438487e797b
|
/pygamerogue/tile.py
|
eda25d37c3805ae806fde03cb4b3db35b0634853
|
[
"BSD-3-Clause"
] |
permissive
|
mikolasan/pyroguelike
|
b33b7a959144b9b115ae4876da0d620b33a28eb3
|
d51b01a566b5edb39792b59d683b4bf827399ba4
|
refs/heads/master
| 2021-07-23T23:06:28.822059 | 2021-01-11T16:57:58 | 2021-01-11T16:57:58 | 179,420,626 | 0 | 1 |
BSD-3-Clause
| 2021-07-07T15:32:36 | 2019-04-04T04:20:26 |
Python
|
UTF-8
|
Python
| false | false | 3,755 |
py
|
import pygame
rogue_size = (48, 48)
def map_to_pixel(x, y):
return x * rogue_size[0], y * rogue_size[1]
class Tile:
def __init__(self, size, map_pos, pos, background_color, border_color, symbol, padding, text_color):
self.size = size
self.pos = {}
if map_pos is not None:
self.update_map_position(map_pos)
else:
self.set_rect_position(pos)
self.background_color = background_color
self.border_color = border_color
self.symbol = symbol
self.text_padding = padding
self.text_color = text_color
self.angle = 0
self.make_image()
def set_rect_position(self, position):
self.pos['x'] = position[0]
self.pos['y'] = position[1]
self.map_pos = (position[0] // rogue_size[0], position[1] // rogue_size[1])
self.update_rect_position()
def update_map_position(self, map_pos):
self.map_pos = map_pos
self.pos['x'], self.pos['y'] = map_to_pixel(map_pos[0], map_pos[1])
def update_rect_position(self):
if hasattr(self, 'rect'):
self.rect.left, self.rect.top = self.pos['x'], self.pos['y']
def make_image(self):
self.font = pygame.font.Font('font.ttf', 40)
self.rendered_symbol = self.font.render(self.symbol, True, self.text_color)
self.original_image = pygame.Surface(self.size)
self.original_image.fill(self.background_color)
self.original_image.blit(self.rendered_symbol, self.text_padding)
self.image = self.original_image
self.rect = self.image.get_rect()
self.update_rect_position()
def update(self, events):
self.update_rect_position()
def draw(self, screen, camera):
screen.blit(self.image, camera.applyrect(self.rect))
wall = {
'background': (44, 61, 81),
'border': (0, 0, 0),
'text': (146, 154, 162),
'symbol': '-',
'padding': [0, 0],
}
TileDB = {
'-': {
**wall,
'symbol': '-',
},
'|': {
**wall,
'symbol': '|',
},
'<': {
**wall,
'symbol': '<',
},
'.': {
'background': (113, 118, 138),
'border': (0, 0, 0),
'text': (226, 199, 192),
'symbol': '.',
'padding': [0, 0],
},
'@': {
'background': (44, 44, 44),
'border': (50, 100, 0),
'text': (91, 198, 208),
'symbol': '@',
'padding': [0, 0],
},
'!': {
'background': (208, 221, 240),
'border': (250, 0, 0),
'text': (110, 25, 32),
'symbol': '!',
'padding': [0, 0],
},
'/': {
'background': (92, 102, 15),
'border': (250, 0, 0),
'text': (249, 199, 52),
'symbol': 'a',
'padding': [0, 0],
},
'+': {
'background': (146, 154, 162),
'border': (250, 100, 0),
'text': (44, 61, 81),
'symbol': '+',
'padding': [0, 0],
},
'$': {
'background': (224, 219, 225),
'border': (0, 200, 0),
'text': (96, 106, 53),
'symbol': '$',
'padding': [0, 0],
},
'e': {
'background': (254, 160, 47),
'border': (250, 0, 0),
'text': (222, 102, 0),
'symbol': 'e',
'padding': [0, 0],
},
}
class RogueTile(Tile):
def __init__(self, map_pos, tile_id):
preset = TileDB[tile_id]
Tile.__init__(
self,
size=rogue_size,
map_pos=map_pos,
pos=None,
background_color=preset['background'],
border_color=preset['border'],
symbol=preset['symbol'],
padding=preset['padding'],
text_color=preset['text'])
|
[
"[email protected]"
] | |
fe98cd8e2fe048a0813b442454d71bc1d015a7fc
|
acf7457d3a799cb9bff12686d2d616688bcd4b5b
|
/packages/python/plotly/plotly/validators/heatmap/legendgrouptitle/font/_color.py
|
992adc73b123157b72fc2cd128fd797dbab38c2d
|
[
"MIT"
] |
permissive
|
plotly/plotly.py
|
f4f61639f08160f16195efc95b5901dc5a937346
|
975a704074f01c078e0fdfa32bdf17130bf89e69
|
refs/heads/master
| 2023-09-06T06:15:08.340035 | 2023-08-24T12:28:14 | 2023-08-24T12:28:14 | 14,579,099 | 14,751 | 2,989 |
MIT
| 2023-09-08T19:55:32 | 2013-11-21T05:53:08 |
Python
|
UTF-8
|
Python
| false | false | 427 |
py
|
import _plotly_utils.basevalidators
class ColorValidator(_plotly_utils.basevalidators.ColorValidator):
def __init__(
self, plotly_name="color", parent_name="heatmap.legendgrouptitle.font", **kwargs
):
super(ColorValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
edit_type=kwargs.pop("edit_type", "style"),
**kwargs,
)
|
[
"[email protected]"
] | |
b104bc898e027c3443ab38096375afb2acb94686
|
9da8754002fa402ad8e6f25659978bd269bbcec8
|
/src/25B/cdf_25B.py
|
1a7bf3d9cd25f7a4eea1b9be350dfa6db25c93c0
|
[
"MIT"
] |
permissive
|
kopok2/CodeforcesSolutionsPython
|
a00f706dbf368ba0846c8ae86d4145b5dd3e1613
|
35bec0dbcff47765b123b5fe60476014376153df
|
refs/heads/master
| 2023-02-02T03:08:22.097651 | 2020-12-17T22:00:50 | 2020-12-17T22:00:50 | 196,035,812 | 1 | 1 | null | null | null | null |
UTF-8
|
Python
| false | false | 785 |
py
|
class CodeforcesTask25BSolution:
def __init__(self):
self.result = ''
self.n = 0
self.number = ''
def read_input(self):
self.n = int(input())
self.number = input()
def process_task(self):
result = []
if self.n % 2:
result.append(self.number[:3])
self.number = self.number[3:]
a = ""
for c in self.number:
if a:
result.append(a + c)
a = ""
else:
a = c
self.result = "-".join(result)
def get_result(self):
return self.result
if __name__ == "__main__":
Solution = CodeforcesTask25BSolution()
Solution.read_input()
Solution.process_task()
print(Solution.get_result())
|
[
"[email protected]"
] | |
8074f01904bff39c1ebfd7683a6d575784de2172
|
e0fc7493f4339145792f54bcd7124acea500ca45
|
/cpc/utils/ErrorHandler.py
|
a4971a3eda2ee541bbc19b681e53610fa2d843b3
|
[
"BSD-3-Clause"
] |
permissive
|
U-Ar/Cpresto
|
d52d99e8d44ed01c87c8911614d744cae695d6aa
|
f723458fb237c9e3e8bc8a6afdf7c81858a65363
|
refs/heads/main
| 2023-05-14T15:28:38.449783 | 2021-06-06T15:07:14 | 2021-06-06T15:07:14 | 364,445,894 | 1 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 937 |
py
|
import sys
class ErrorHandler:
def __init__(self,progid,stream=None):
if stream == None:
self.stream = sys.stderr
else:
self.stream = stream
self.program_id = progid
self.n_error = 0
self.n_warning = 0
def error(self,msg,loc=None):
if loc == None:
self.stream.write(self.program_id+": error: "+msg+"\n")
self.n_error += 1
else :
self.stream.write(self.program_id+": error: "+loc.to_string()+": "+msg+"\n")
self.n_error += 1
def warn(self,msg,loc=None):
if loc == None:
self.stream.write(self.program_id+": warning: "+msg+"\n")
self.n_warning += 1
else :
self.stream.write(self.program_id+": warning: "+loc.to_string()+": "+msg+"\n")
self.n_warning += 1
def error_occured(self):
return self.n_error > 0
|
[
"[email protected]"
] | |
a0ef8d57867120d76e7dd3c1b572137bdeb51bf6
|
f7550c4964dc8f3c59dbcebe39e947bd6a264dba
|
/2.OOPS/Exception Handling.py
|
05dac8b2c108980738fc273289f4f8795461eb72
|
[] |
no_license
|
Jashwanth-k/Data-Structures-and-Algorithms
|
db5e2e30932e0a35db578c19ae6cff9f147b7c3d
|
1ebf9986999a474cb094f3ab04616a46f2887043
|
refs/heads/main
| 2023-08-25T02:57:17.394322 | 2021-10-11T15:27:56 | 2021-10-11T15:27:56 | 402,448,718 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 324 |
py
|
while True:
try:
n = int(input('enter the numerator :'))
num = int(n)
n = int(input('enter the denominator :'))
denom = int(n)
value = (num / denom)
print(value)
break
except ValueError:
print('Numerator and Denominator must be integers')
|
[
"[email protected]"
] | |
9404e5e1138ec41fc2bad63449226d1cd0cc38c6
|
42c48f3178a48b4a2a0aded547770027bf976350
|
/google/ads/google_ads/v4/services/domain_category_service_client_config.py
|
db4f358f4636c9982c5622eefbd7626ab8796369
|
[
"Apache-2.0"
] |
permissive
|
fiboknacky/google-ads-python
|
e989464a85f28baca1f28d133994c73759e8b4d6
|
a5b6cede64f4d9912ae6ad26927a54e40448c9fe
|
refs/heads/master
| 2021-08-07T20:18:48.618563 | 2020-12-11T09:21:29 | 2020-12-11T09:21:29 | 229,712,514 | 0 | 0 |
Apache-2.0
| 2019-12-23T08:44:49 | 2019-12-23T08:44:49 | null |
UTF-8
|
Python
| false | false | 815 |
py
|
config = {
"interfaces": {
"google.ads.googleads.v4.services.DomainCategoryService": {
"retry_codes": {
"idempotent": [
"DEADLINE_EXCEEDED",
"UNAVAILABLE"
],
"non_idempotent": []
},
"retry_params": {
"default": {
"initial_retry_delay_millis": 5000,
"retry_delay_multiplier": 1.3,
"max_retry_delay_millis": 60000,
"initial_rpc_timeout_millis": 3600000,
"rpc_timeout_multiplier": 1.0,
"max_rpc_timeout_millis": 3600000,
"total_timeout_millis": 3600000
}
},
"methods": {
"GetDomainCategory": {
"timeout_millis": 60000,
"retry_codes_name": "idempotent",
"retry_params_name": "default"
}
}
}
}
}
|
[
"[email protected]"
] | |
9cb938048f68b47602170f1e3f23275c9c1e5941
|
9594585cc05dded72740774a3d6058971386dd9a
|
/boss/core/exc.py
|
80e4e91c50c60fee37aa3030542ce45190324e3a
|
[
"BSD-3-Clause"
] |
permissive
|
derks/boss
|
3a22044d9542ba249f95fd7081e86f3451c16134
|
8b81ddfb9b44dab018329a304a5e5a75fa20b060
|
refs/heads/master
| 2021-01-18T05:37:47.894064 | 2013-06-27T21:01:20 | 2013-06-27T21:01:20 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 428 |
py
|
"""Boss core exceptions module."""
class BossError(Exception):
"""Generic errors."""
def __init__(self, msg):
Exception.__init__(self)
self.msg = msg
def __str__(self):
return self.msg
class BossConfigError(BossError):
pass
class BossRuntimeError(BossError):
pass
class BossArgumentError(BossError):
pass
class BossTemplateError(BossError):
pass
|
[
"[email protected]"
] | |
9bf5e88c23ba62c7ced22432faab87c0a1c3156b
|
7a73fef9ae426c48573bae41447cef7cb2b97bf6
|
/dynamicserialize/dstypes/com/raytheon/uf/common/activetable/request/MergeActiveTableRequest.py
|
b3377e84d97d8c41ce0f2b475a4807acc2653016
|
[
"LicenseRef-scancode-public-domain",
"BSD-3-Clause"
] |
permissive
|
mjames-upc/python-awips
|
7f0a80a04457224c9e195b82a95eef4d9b2b3091
|
e2b05f5587b02761df3b6dd5c6ee1f196bd5f11c
|
refs/heads/master
| 2020-03-31T03:00:49.540816 | 2018-10-05T23:15:42 | 2018-10-05T23:15:42 | 53,707,817 | 0 | 0 | null | 2017-04-12T18:00:59 | 2016-03-12T01:46:57 |
Python
|
UTF-8
|
Python
| false | false | 2,304 |
py
|
##
##
# File auto-generated against equivalent DynamicSerialize Java class
class MergeActiveTableRequest(object):
def __init__(self, incomingRecords=[], tableName='PRACTICE', site=None,
timeOffset=0.0, xmlSource=None, fromIngestAT=False,
makeBackups=True):
self.incomingRecords = incomingRecords
self.site = site
self.tableName = tableName.upper() if tableName.upper() in ['OPERATIONAL', 'PRACTICE'] else 'PRACTICE'
self.timeOffset = float(timeOffset)
self.xmlSource = xmlSource
self.fromIngestAT = bool(fromIngestAT)
self.makeBackups = bool(makeBackups)
def __repr__(self):
retVal = "MergeActiveTableRequest("
retVal += repr(self.incomingRecords) + ", "
retVal += repr(self.tableName) + ", "
retVal += repr(self.site) + ", "
retVal += repr(self.timeOffset) + ", "
retVal += repr(self.xmlSource) + ", "
retVal += repr(self.fromIngestAT) + ", "
retVal += repr(self.makeBackups) + ")"
return retVal
def __str__(self):
return self.__repr__()
def getIncomingRecords(self):
return self.incomingRecords
def setIncomingRecords(self, incomingRecords):
self.incomingRecords = incomingRecords
def getTableName(self):
return self.tableName
def setTableName(self, tableName):
value = tableName.upper()
if value not in ['OPERATIONAL', 'PRACTICE']:
raise ValueError("Invalid value " + tableName + " specified for ActiveTableMode.")
self.tableName = value
def getSite(self):
return self.site
def setSite(self, site):
self.site = site
def getTimeOffset(self):
return self.timeOffset
def setTimeOffset(self, timeOffset):
self.timeOffset = float(timeOffset)
def getXmlSource(self):
return self.xmlSource
def setXmlSource(self, xmlSource):
self.xmlSource = xmlSource
def getFromIngestAT(self):
return self.fromIngestAT
def setFromIngestAT(self, fromIngestAT):
self.fromIngestAT = bool(fromIngestAT)
def getMakeBackups(self):
return self.makeBackups
def setMakeBackups(self, makeBackups):
self.makeBackups = bool(makeBackups)
|
[
"[email protected]"
] | |
fa828b53566c090450afc3f58298ab733534ac3e
|
11cf40946c55b47886cfe8777916a17db82c2309
|
/conways1.py
|
a2da35410469f1db5aecd4755355f109e8add686
|
[] |
no_license
|
dalalsunil1986/python_the_hard_way_exercises
|
fc669bf2f823a4886f0de717d5f1ca0d0233f6af
|
bc329999490dedad842e23e8447623fd0321ffe0
|
refs/heads/master
| 2023-05-03T01:35:24.097087 | 2021-05-16T00:43:56 | 2021-05-16T00:43:56 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 2,840 |
py
|
# Conway's Game of Life
import random, time, copy
WIDTH = 60
HEIGHT = 20
# Create a list of list for the cells:
nextCells = []
for x in range(WIDTH):
column = [] # Create a new column.
for y in range(HEIGHT):
if random.randint(0, 1) == 0:
column.append('O') # Add a living cell.
else:
column.append(' ') # Add a dead cell.
nextCells.append(column) # nextCells is a list of column lists.
while True: # Main program loop.
print('\n\n\n\n\n') # Separate each step with newlines.
currentCells = copy.deepcopy(nextCells)
# Print currentCells on the screen:
for y in range(HEIGHT):
for x in range(WIDTH):
print(currentCells[x][y], end='') # Print the 'O' or space.
print() # Print a newline at the end of the row.
# Calculate next step's cells based on current step's cells:
for x in range(WIDTH):
for y in range(HEIGHT):
# Get neighboring coordinates:
# '% WIDTH' ensures leftCoord is always between 0 and WIDTH -1
leftCoord = (x - 1) % WIDTH
rightCoord = (x + 1) % WIDTH
aboveCoord = (y - 1) % HEIGHT
belowCoord = (y + 1) % HEIGHT
# Count number of living neighbors:
numNeighbors = 0
if currentCells[leftCoord][aboveCoord] == '#':
numNeighbors += 1 # Top-left neighbor is alive.
if currentCells[x][aboveCoord] == '#':
numNeighbors += 1 # Top neighbor is alive.
if currentCells[rightCoord][aboveCoord] == '#':
numNeighbors += 1 # Top-right neighbor is alive.
if currentCells[leftCoord][y] == '#':
numNeighbors += 1 # Left neighbor is alive.
if currentCells[rightCoord][y] == '#':
numNeighbors += 1 # Right neighbor is alive.
if currentCells[leftCoord][belowCoord] == '#':
numNeighbors += 1 # Botton-left neighbor is alive.
if currentCells[x][belowCoord] == '#':
numNeighbors += 1 # Botton neighbor is alive.
if currentCells[rightCoord][belowCoord] == '#':
numNeighbors += 1 # Bottom-right neighbor is alive.
# Set cell based on Conway's Game of Life rules:
if currentCells[x][y] == '#' and (numNeighbors == 2 or numNeighbors == 3):
# Living cells with 2 or 3 neighbors stay alive:
nextCells[x][y] = '#'
elif currentCells[x][y] == ' ' and numNeighbors == 3:
# Dead cells with 3 neighbors become alive:
nextCells[x][y] = '#'
else:
# Everthing else dies or stays dead:
nextCells[x][y] = ' '
time.sleep(2) # Add 2-second pause to reduce flickering.
|
[
"[email protected]"
] | |
c86c98ae72815124b24d3ae32ec5d6a1d90a7dca
|
324d9bc6747873173cf457d563665f59005c0efc
|
/apps/users/views.py
|
ff8c38e6a8d915aa28bdd5f5db1eb3e22a995a8c
|
[] |
no_license
|
jzxyouok/movie-1
|
fd220618ce8c03bc3dc33d5b39a81547097653b2
|
650c05389aaefb84544d2246bf8436bed7157547
|
refs/heads/master
| 2020-06-03T16:00:01.479269 | 2018-05-30T09:22:43 | 2018-05-30T09:22:43 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 8,829 |
py
|
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from django.urls import reverse
from django.contrib import messages
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.hashers import make_password
from django.views.generic.base import View
from django.contrib.auth.backends import ModelBackend
from .models import UserProfile, EmailVerifyRecord
import json
from django.db.models import Q # 并集
from .forms import LoginForm, RegisterForm, ResetPwdForm, UserInfoForm, UploadImageForm, ForgetPwdForm
from apps.utils.email_send import send_register_email
# Create your views here.
class CustomBackend(ModelBackend):
"""
重写ModelBackend下的authenticate方法实现邮箱和用户名均可以登录
"""
def authenticate(self, request, username=None, password=None, **kwargs):
try:
user = UserProfile.objects.get(Q(username=username) | Q(email=username))
if user.check_password(password):
return user
except Exception as e:
return None
class LoginView(View):
# 直接调用get方法免去判断
def get(self, request):
redirect_url = request.GET.get('next', '')
return render(request, "users/login.html", {
"redirect_url": redirect_url
})
def post(self, request):
login_form = LoginForm(request.POST)
# is_valid判断我们字段是否有错执行我们原有逻辑,验证失败跳回login页面
if login_form.is_valid():
# 取不到时为空,username,password为前端页面name值
user_name = request.POST.get("username", "")
pass_word = request.POST.get("password", "")
# 成功返回user对象,失败返回null
user = authenticate(username=user_name, password=pass_word)
# 如果不是null说明验证成功
if user is not None:
# 只有当用户激活时才给登录
if user.is_active:
login(request, user)
redirect_url = request.POST.get('next', '')
if redirect_url:
return HttpResponseRedirect(redirect_url)
return HttpResponseRedirect(reverse("index"))
else:
return render(
request, "users/login.html", {
"msg": "用户名未激活! 请前往邮箱进行激活"})
# 当用户真的密码出错时
else:
return render(request, "users/login.html", {"msg": "用户名或密码错误!"})
# 验证不成功跳回登录页面
# 没有成功说明里面的值是None,并再次跳转回主页面
else:
return render(
request, "users/login.html", {
"login_form": login_form})
class ActiveUserView(View):
"""
激活注册用户
"""
def get(self, request, active_code):
# 查询邮箱验证记录是否存在
all_record = EmailVerifyRecord.objects.filter(code=active_code)
if all_record:
for record in all_record:
# 获取对应邮箱
email = record.email
user = UserProfile.objects.get(email=email)
user.is_active = True
user.save()
else:
return render(request, 'users/active_fail.html')
return render(request, 'users/login.html')
class RegisterView(View):
"""
注册视图
"""
def get(self, request):
register_form = RegisterForm()
return render(request, "users/register.html", {'register_form': register_form})
def post(self, request):
# 实例化生成注册表单
register_form = RegisterForm(request.POST)
if register_form.is_valid():
user_name = request.POST.get('email', None)
# 如果用户已经存在
if UserProfile.objects.filter(email=user_name):
return render(request, 'users/register.html',
{'register_form': register_form, 'msg': '用户已经存在'})
pass_word = request.POST.get('password', None)
# 实例化UserProfile
user_profile = UserProfile()
user_profile.username = user_name
user_profile.email = user_name
# 默认注册后用户是未激活的
user_profile.is_active = False
# hash算法加密密码
user_profile.password = make_password(pass_word)
user_profile.save()
send_register_email(user_name, 'register')
messages.success(request, "已经发送了激活邮件,请查收")
return render(request, 'users/register.html')
else:
return render(request, 'users/register.html', {'register_form': register_form})
class ResetPwdView(View):
"""
重设密码视图
"""
def post(self, request):
reset_form = ResetPwdForm(request.POST)
if reset_form.is_valid():
username = request.user.username
password1 = request.POST.get('password1', '')
password2 = request.POST.get('password2', '')
if password1 != password2:
return render(request, 'users/reset.html', {'msg': '两次输入的密码不一致'})
user = UserProfile.objects.get(username=username)
user.password = make_password(password2)
user.save()
return render(request, 'users/login.html', {'msg': '密码修改成功,请使用新密码登录'})
else:
# 密码位数不够
return render(request, 'users/reset.html', {'reset_form': reset_form})
class UserInfoView(LoginRequiredMixin, View):
"""
用户中心视图
"""
login_url = '/login/'
redirect_field_name = 'next'
def get(self, request):
return render(request, 'users/user.html')
def post(self, request):
# 修改,增加instance属性
user_info_form = UserInfoForm(request.POST, instance=request.user)
if user_info_form.is_valid():
user = UserProfile.objects.get(pk=request.user.id)
user.nick_name = user_info_form.cleaned_data['nick_name']
user.gender = user_info_form.cleaned_data['gender']
user.sign = user_info_form.cleaned_data['sign']
user.address = user_info_form.cleaned_data['address']
user.mobile = user_info_form.cleaned_data['mobile']
user.save()
return HttpResponseRedirect(reverse('user_info'))
else:
# 通过json的dumps方法把字典转换成字符串
return HttpResponse(
json.dumps(user_info_form.errors),
content_type='application/json'
)
class UploadImageView(LoginRequiredMixin, View):
"""
用户头像修改
"""
def post(self, request):
image_form = UploadImageForm(request.POST, request.FILES)
if image_form.is_valid():
image = image_form.cleaned_data['image']
request.user.image = image
request.user.save()
# return HttpResponse('{"status": "success"}', content_type='application/json')
return HttpResponseRedirect(reverse('user_info'))
else:
return HttpResponse('{"status": "fail"}', content_type='application/json')
class ForgetPwdView(View):
"""
找回密码视图
"""
def get(self, request):
forget_form = ForgetPwdForm()
return render(request, 'users/forgetpwd.html', {'forget_form': forget_form})
def post(self, request):
forget_form = ForgetPwdForm(request.POST)
if forget_form.is_valid():
email = request.POST.get('email', None)
send_register_email(email, 'forget')
return render(request, 'index.html')
else:
return render(request, 'users/forgetpwd.html', {'forget_form': forget_form})
class ResetView(View):
def get(self, request, active_code):
all_records = EmailVerifyRecord.objects.filter(code=active_code)
if all_records:
for record in all_records:
email = record.email
return render(request, "users/reset.html", {"email": email})
else:
return render(request, "users/active_fail.html")
return render(request, "users/login.html")
class LogOutView(View):
"""
退出登录
"""
def get(self, request):
logout(request)
return HttpResponseRedirect(reverse('index'))
|
[
"[email protected]"
] | |
4b3999bceb135ae43088f2acd45fd813a32aa724
|
330899fd4a9653e05e2a09e0a4f30c119af97ad4
|
/python/hidet/tos/modules/nn.py
|
3d1c65c10d426d6b2298130ea875a54bbf014694
|
[
"Apache-2.0"
] |
permissive
|
yaoyaoding/hidet-artifacts
|
f8a4707c7fc28aa7bfa4dab3a9f2a9387c020f99
|
f2e9767bb2464bd0592a8ec0b276f97481f13df2
|
refs/heads/main
| 2023-04-30T13:12:57.350002 | 2023-04-24T19:37:34 | 2023-04-24T19:37:34 | 551,692,225 | 3 | 1 |
Apache-2.0
| 2022-11-01T23:25:17 | 2022-10-14T22:40:28 |
Python
|
UTF-8
|
Python
| false | false | 5,063 |
py
|
from typing import Optional, Union, List
import math
from hidet.tos import ops
from hidet.tos.common import normalize
from hidet.tos.module import Module, Tensor
from hidet.tos.tensor import randn, zeros, ones
from hidet.tos.modules.container import Sequential, ModuleList
class Conv2d(Module):
def __init__(self, in_channels, out_channels, kernel_size, padding=0, stride=1, groups=1):
super().__init__()
self.in_channels = in_channels
self.out_channels = out_channels
self.kernel = normalize(kernel_size)
self.padding = normalize(padding)
self.stride = normalize(stride)
self.groups = groups
self.weight = randn(shape=[out_channels, in_channels, *self.kernel], dtype='float32', stddev=1.0 / math.sqrt(out_channels))
def extra_str(self) -> str:
return 'in_channels={}, out_channels={}, kernel_size={}, stride={}, padding={}'.format(self.in_channels, self.out_channels, self.kernel, self.stride, self.padding)
def forward(self, x):
x = ops.pad(x, ops.utils.normalize_padding(self.padding))
return ops.conv2d(x, self.weight, self.stride, self.groups)
class BatchNorm2d(Module):
def __init__(self, num_features, eps=1e-5):
super().__init__()
self.eps = eps
self.running_mean = zeros(shape=[num_features])
self.running_var = ones(shape=[num_features])
def extra_str(self) -> str:
return 'eps={}'.format(self.eps)
def forward(self, x: Tensor):
return ops.batch_norm_infer(x, self.running_mean, self.running_var, self.eps)
class Linear(Module):
def __init__(self, in_features, out_features, bias: bool = True):
super().__init__()
self.in_features = in_features
self.out_features = out_features
self.weight = randn(shape=[in_features, out_features], stddev=1.0 / math.sqrt(in_features))
if bias:
self.bias = zeros(shape=[out_features])
else:
self.bias = None
def extra_str(self) -> str:
return 'in_features={}, out_features={}'.format(self.in_features, self.out_features)
def forward(self, x: Tensor) -> Tensor:
return ops.matmul(x, self.weight) + self.bias
class Relu(Module):
def forward(self, x):
return ops.relu(x)
class MaxPool2d(Module):
def __init__(self, kernel_size, stride=1, padding=0):
super().__init__()
self.kernel = kernel_size
self.stride = stride
self.padding = padding
def extra_str(self) -> str:
return 'kernel_size={}, stride={}, padding={}'.format(self.kernel, self.stride, self.padding)
def forward(self, x):
return ops.max_pool2d(x, self.kernel, self.stride, self.padding)
class AvgPool2d(Module):
def __init__(self, kernel_size, stride, padding):
super().__init__()
self.kernel = kernel_size
self.stride = stride
self.padding = padding
def extra_str(self) -> str:
return 'kernel_size={}, stride={}, padding={}'.format(self.kernel, self.stride, self.padding)
def forward(self, x):
return ops.avg_pool2d(x, self.kernel, self.stride, self.padding)
class AdaptiveAvgPool2d(Module):
def __init__(self, output_size):
super().__init__()
self.output_size = normalize(output_size)
assert tuple(self.output_size) == (1, 1), 'current only support this'
def extra_str(self) -> str:
return 'output_size={}'.format(self.output_size)
def forward(self, x: Tensor) -> Tensor:
n, c, h, w = x.shape
return ops.avg_pool2d(x, kernel=(h, w), stride=(1, 1), padding=(0, 0))
class Embedding(Module):
def __init__(self, num_embeddings: int, embedding_dim: int):
super().__init__()
self.num_embeddings = num_embeddings
self.embedding_dim = embedding_dim
self.weight = randn(shape=[num_embeddings, embedding_dim], dtype='float32', mean=0.0, stddev=1.0)
def forward(self, indices: Tensor) -> Tensor:
return ops.take(self.weight, indices, axis=0)
class LayerNorm(Module):
def __init__(self, normalized_shape: Union[int, List[int]], eps: float = 1e-5, elementwise_affine: bool = True):
super().__init__()
if isinstance(normalized_shape, int):
normalized_shape = (normalized_shape,)
self.normalized_shape = tuple(normalized_shape)
self.eps = eps
self.elementwise_affine = elementwise_affine
if elementwise_affine:
self.weight = ones(normalized_shape)
self.bias = zeros(normalized_shape)
else:
self.weight = None
self.bias = None
def forward(self, x: Tensor) -> Tensor:
x = ops.layer_norm(x)
if self.weight:
x = x * self.weight
if self.bias:
x = x + self.bias
return x
class Gelu(Module):
def forward(self, x):
return x * (ops.erf(x * (1.0 / 1.4142135381698608)) + 1.0) * 0.5
class Tanh(Module):
def forward(self, x):
return ops.tanh(x)
|
[
"[email protected]"
] | |
a3b7d2043d073baae61c82a62a7baf513e5463d4
|
117aaf186609e48230bff9f4f4e96546d3484963
|
/others/FilterTable/main.py
|
c18d99d897d4e53baba8675c35fbb4fd3a1f0667
|
[
"MIT"
] |
permissive
|
eyllanesc/stackoverflow
|
8d1c4b075e578496ea8deecbb78ef0e08bcc092e
|
db738fbe10e8573b324d1f86e9add314f02c884d
|
refs/heads/master
| 2022-08-19T22:23:34.697232 | 2022-08-10T20:59:17 | 2022-08-10T20:59:17 | 76,124,222 | 355 | 433 |
MIT
| 2022-08-10T20:59:18 | 2016-12-10T16:29:34 |
C++
|
UTF-8
|
Python
| false | false | 1,326 |
py
|
import csv
import sys
from PyQt4 import QtGui
from PyQt4 import uic
from PyQt4.QtCore import QString
from PyQt4.QtGui import QTableWidgetItem
filter_class = uic.loadUiType("filter.ui")[0]
class Filter_window(QtGui.QWidget, filter_class):
def __init__(self, parent=None, *args, **kwargs):
QtGui.QMainWindow.__init__(self, parent)
self.setupUi(self)
self.loadAll()
def loadAll(self):
with open("Rts.csv", "rb") as inpfil:
reader = csv.reader(inpfil, delimiter=',')
csheader = reader.next()
ncol = len(csheader)
data = list(reader)
row_count = len(data)
self.filterall.setRowCount(row_count)
self.filterall.setColumnCount(ncol)
self.filterall.setHorizontalHeaderLabels(QString('%s' % ', '.join(map(str, csheader))).split(","))
for ii in range(0, row_count):
print data[ii]
mainins = data[ii]
print mainins
for var in range(0, ncol):
print mainins[var], "\n"
self.filterall.setItem(ii, var, QTableWidgetItem(mainins[var]))
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
filterwin = Filter_window()
filterwin.show()
sys.exit(app.exec_())
|
[
"[email protected]"
] | |
240e6d72e883cd5d44adc7bc87f9e6646c36762c
|
aa0270b351402e421631ebc8b51e528448302fab
|
/sdk/paloaltonetworks/azure-mgmt-paloaltonetworksngfw/generated_samples/post_rules_delete_minimum_set_gen.py
|
37e8eb6f0bb63131b561033cfb6c8b88a6e137ab
|
[
"MIT",
"LGPL-2.1-or-later",
"LicenseRef-scancode-generic-cla"
] |
permissive
|
fangchen0601/azure-sdk-for-python
|
d04a22109d0ff8ff209c82e4154b7169b6cb2e53
|
c2e11d6682e368b2f062e714490d2de42e1fed36
|
refs/heads/master
| 2023-05-11T16:53:26.317418 | 2023-05-04T20:02:16 | 2023-05-04T20:02:16 | 300,440,803 | 0 | 0 |
MIT
| 2020-10-16T18:45:29 | 2020-10-01T22:27:56 | null |
UTF-8
|
Python
| false | false | 1,613 |
py
|
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------
from azure.identity import DefaultAzureCredential
from azure.mgmt.paloaltonetworks import PaloAltoNetworksNgfwMgmtClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-paloaltonetworks
# USAGE
python post_rules_delete_minimum_set_gen.py
Before run the sample, please set the values of the client ID, tenant ID and client secret
of the AAD application as environment variables: AZURE_CLIENT_ID, AZURE_TENANT_ID,
AZURE_CLIENT_SECRET. For more info about how to get the value, please see:
https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal
"""
def main():
client = PaloAltoNetworksNgfwMgmtClient(
credential=DefaultAzureCredential(),
subscription_id="SUBSCRIPTION_ID",
)
response = client.post_rules.begin_delete(
global_rulestack_name="lrs1",
priority="1",
).result()
print(response)
# x-ms-original-file: specification/paloaltonetworks/resource-manager/PaloAltoNetworks.Cloudngfw/preview/2022-08-29-preview/examples/PostRules_Delete_MinimumSet_Gen.json
if __name__ == "__main__":
main()
|
[
"[email protected]"
] | |
0eafa771e434cc47da07d9832275df08bc7e0215
|
ccd27037d13c0288aae5d94e616c659ce2a713a0
|
/donor/migrations/0001_initial.py
|
b2964b3233b6f9785178e02fc623f4e664a5e3c9
|
[] |
no_license
|
AniketShahane/ZeroDay-01
|
99ce4dad366b778851518a07a34ab9d100246ed5
|
2a12c6965fdbc9c1f1db3d2f207861a7ddcb62e8
|
refs/heads/master
| 2020-04-21T11:14:03.077996 | 2019-02-11T13:21:31 | 2019-02-11T13:21:31 | 169,516,547 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 1,907 |
py
|
# Generated by Django 2.1.5 on 2019-02-06 08:07
import datetime
from django.db import migrations, models
import django.db.models.deletion
from django.utils.timezone import utc
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Donor',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=100)),
('area', models.CharField(max_length=250)),
('amount', models.IntegerField()),
('time', models.DateTimeField(verbose_name=datetime.datetime(2019, 2, 6, 8, 7, 30, 318661, tzinfo=utc))),
],
),
migrations.CreateModel(
name='RevenueAdded',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('principal_amount', models.IntegerField()),
('time', models.DateTimeField(verbose_name=datetime.datetime(2019, 2, 6, 8, 7, 30, 324627, tzinfo=utc))),
('donor_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='donor.Donor')),
],
),
migrations.CreateModel(
name='RevenueSpent',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('principal_amount', models.IntegerField()),
('resource', models.CharField(choices=[('SCH', 'Scholarships'), ('ST', 'Stationery'), ('ACC', 'Accommodation'), ('HC', 'Health Care')], max_length=255)),
('time', models.DateTimeField(verbose_name=datetime.datetime(2019, 2, 6, 8, 7, 30, 325058, tzinfo=utc))),
],
),
]
|
[
"[email protected]"
] | |
f8f7e6aff74349c59cce9401e12149fb28ed8f8b
|
208bc8b87cb20fc6e57c8c8846cbe947b2eec1f3
|
/pyocd/coresight/cortex_m_v8m.py
|
ca01e71819f240e6e35497dc4209539e8afd50ac
|
[
"Apache-2.0",
"CC-BY-4.0"
] |
permissive
|
canerbulduk/pyOCD
|
28c545f25ef9b2949a1cd49c00faeeda986a26fe
|
a61e8b8dc2050309510d9fe7ca63680aafe06749
|
refs/heads/main
| 2023-08-24T21:10:52.427697 | 2021-11-09T15:13:48 | 2021-11-09T15:13:48 | 426,275,463 | 0 | 0 |
Apache-2.0
| 2021-11-09T15:08:22 | 2021-11-09T15:08:21 | null |
UTF-8
|
Python
| false | false | 7,538 |
py
|
# pyOCD debugger
# Copyright (c) 2019-2020 Arm Limited
# Copyright (c) 2021 Chris Reed
# SPDX-License-Identifier: Apache-2.0
#
# 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 logging
from .cortex_m import CortexM
from .core_ids import (CORE_TYPE_NAME, CoreArchitecture, CortexMExtension)
from ..core.target import Target
from .cortex_m_core_registers import CoreRegisterGroups
LOG = logging.getLogger(__name__)
class CortexM_v8M(CortexM):
"""! @brief Component class for a v8.x-M architecture Cortex-M core."""
ARMv8M_BASE = 0xC
ARMv8M_MAIN = 0xF
## DFSR.PMU added in v8.1-M.
DFSR_PMU = (1 << 5)
DSCSR = 0xE000EE08
DSCSR_CDSKEY = 0x00020000
DSCSR_CDS = 0x00010000
DSCSR_SBRSEL = 0x00000002
DSCSR_SBRSELEN = 0x00000001
# Processor Feature Register 1
PFR1 = 0xE000ED44
PFR1_SECURITY_MASK = 0x000000f0
PFR1_SECURITY_SHIFT = 4
PFR1_SECURITY_EXT_V8_0 = 0x1 # Base security extension.
PFR1_SECURITY_EXT_V8_1 = 0x3 # v8.1-M adds several instructions.
# Media and FP Feature Register 1
MVFR1 = 0xE000EF44
MVFR1_MVE_MASK = 0x00000f00
MVFR1_MVE_SHIFT = 8
MVFR1_MVE__INTEGER = 0x1
MVFR1_MVE__FLOAT = 0x2
def __init__(self, rootTarget, ap, memory_map=None, core_num=0, cmpid=None, address=None):
super(CortexM_v8M, self).__init__(rootTarget, ap, memory_map, core_num, cmpid, address)
# Only v7-M supports VECTRESET.
self._supports_vectreset = False
@property
def supported_security_states(self):
"""! @brief Tuple of security states supported by the processor.
@return Tuple of @ref pyocd.core.target.Target.SecurityState "Target.SecurityState". The
result depends on whether the Security extension is enabled.
"""
if self.has_security_extension:
return (Target.SecurityState.NONSECURE, Target.SecurityState.SECURE)
else:
return (Target.SecurityState.NONSECURE,)
def _read_core_type(self):
"""! @brief Read the CPUID register and determine core type and architecture."""
# Read CPUID register
cpuid = self.read32(CortexM.CPUID)
implementer = (cpuid & CortexM.CPUID_IMPLEMENTER_MASK) >> CortexM.CPUID_IMPLEMENTER_POS
if implementer != CortexM.CPUID_IMPLEMENTER_ARM:
LOG.warning("CPU implementer is not ARM!")
arch = (cpuid & CortexM.CPUID_ARCHITECTURE_MASK) >> CortexM.CPUID_ARCHITECTURE_POS
self.core_type = (cpuid & CortexM.CPUID_PARTNO_MASK) >> CortexM.CPUID_PARTNO_POS
self.cpu_revision = (cpuid & CortexM.CPUID_VARIANT_MASK) >> CortexM.CPUID_VARIANT_POS
self.cpu_patch = (cpuid & CortexM.CPUID_REVISION_MASK) >> CortexM.CPUID_REVISION_POS
pfr1 = self.read32(self.PFR1)
pfr1_sec = ((pfr1 & self.PFR1_SECURITY_MASK) >> self.PFR1_SECURITY_SHIFT)
self.has_security_extension = pfr1_sec in (self.PFR1_SECURITY_EXT_V8_0, self.PFR1_SECURITY_EXT_V8_1)
if self.has_security_extension:
self._extensions.append(CortexMExtension.SEC)
if pfr1_sec == self.PFR1_SECURITY_EXT_V8_1:
self._extensions.append(CortexMExtension.SEC_V81)
if arch == self.ARMv8M_BASE:
self._architecture = CoreArchitecture.ARMv8M_BASE
else:
self._architecture = CoreArchitecture.ARMv8M_MAIN
if self.core_type in CORE_TYPE_NAME:
if self.has_security_extension:
LOG.info("CPU core #%d is %s r%dp%d (security ext present)", self.core_number, CORE_TYPE_NAME[self.core_type], self.cpu_revision, self.cpu_patch)
else:
LOG.info("CPU core #%d is %s r%dp%d", self.core_number, CORE_TYPE_NAME[self.core_type], self.cpu_revision, self.cpu_patch)
else:
LOG.warning("CPU core #%d type is unrecognized", self.core_number)
def _check_for_fpu(self):
"""! @brief Determine if a core has an FPU.
In addition to the tests performed by CortexM, this method tests for the MVE extension.
"""
super(CortexM_v8M, self)._check_for_fpu()
# Check for MVE.
mvfr1 = self.read32(self.MVFR1)
mve = (mvfr1 & self.MVFR1_MVE_MASK) >> self.MVFR1_MVE_SHIFT
if mve == self.MVFR1_MVE__INTEGER:
self._extensions.append(CortexMExtension.MVE)
elif mve == self.MVFR1_MVE__FLOAT:
self._extensions += [CortexMExtension.MVE, CortexMExtension.MVE_FP]
def _build_registers(self):
super(CortexM_v8M, self)._build_registers()
# Registers available with Security extension, either Baseline or Mainline.
if self.has_security_extension:
self._core_registers.add_group(CoreRegisterGroups.V8M_SEC_ONLY)
# Mainline-only registers.
if self.architecture == CoreArchitecture.ARMv8M_MAIN:
self._core_registers.add_group(CoreRegisterGroups.V7M_v8M_ML_ONLY)
# Registers available when both Mainline and Security extensions are implemented.
if self.has_security_extension:
self._core_registers.add_group(CoreRegisterGroups.V8M_ML_SEC_ONLY)
# MVE registers.
if CortexMExtension.MVE in self.extensions:
self._core_registers.add_group(CoreRegisterGroups.V81M_MVE_ONLY)
def get_security_state(self):
"""! @brief Returns the current security state of the processor.
@return @ref pyocd.core.target.Target.SecurityState "Target.SecurityState" enumerator.
"""
dscsr = self.read32(self.DSCSR)
if (dscsr & self.DSCSR_CDS) != 0:
return Target.SecurityState.SECURE
else:
return Target.SecurityState.NONSECURE
def clear_debug_cause_bits(self):
self.write32(CortexM.DFSR,
self.DFSR_PMU
| CortexM.DFSR_EXTERNAL
| CortexM.DFSR_VCATCH
| CortexM.DFSR_DWTTRAP
| CortexM.DFSR_BKPT
| CortexM.DFSR_HALTED)
def get_halt_reason(self):
"""! @brief Returns the reason the core has halted.
This overridden version of this method adds support for v8.x-M halt reasons.
@return @ref pyocd.core.target.Target.HaltReason "Target.HaltReason" enumerator or None.
"""
dfsr = self.read32(self.DFSR)
if dfsr & self.DFSR_HALTED:
reason = Target.HaltReason.DEBUG
elif dfsr & self.DFSR_BKPT:
reason = Target.HaltReason.BREAKPOINT
elif dfsr & self.DFSR_DWTTRAP:
reason = Target.HaltReason.WATCHPOINT
elif dfsr & self.DFSR_VCATCH:
reason = Target.HaltReason.VECTOR_CATCH
elif dfsr & self.DFSR_EXTERNAL:
reason = Target.HaltReason.EXTERNAL
elif dfsr & self.DFSR_PMU:
reason = Target.HaltReason.PMU
else:
reason = None
return reason
|
[
"[email protected]"
] | |
964be754ef86bec5917a57c625ad4ed6a31349f8
|
dcafbc9a6eea2b0e9aabc527b93cd97d270a67af
|
/tests/test_cli.py
|
1cc1282f4575e65d72cfcb43033f27022e631d72
|
[
"MIT"
] |
permissive
|
bfontaine/edt2ics
|
83fbd51540d7887e049be90efb70f382110dafaf
|
1245f174694c30a42c489d831970c32ae42c0b0d
|
refs/heads/master
| 2021-05-15T01:55:46.595212 | 2015-01-05T11:31:48 | 2015-01-05T11:31:48 | 24,652,011 | 1 | 0 |
MIT
| 2021-03-23T09:20:53 | 2014-09-30T19:18:04 |
Python
|
UTF-8
|
Python
| false | false | 1,722 |
py
|
# -*- coding: UTF-8 -*-
import sys
from tempfile import NamedTemporaryFile
from os import remove
try:
import unittest2 as unittest
from cStringIO import StringIO
except ImportError:
from io import StringIO
import unittest
from edt2ics.cli import write_ical, main, ScheduleScraper
def ctrlC(self, *args, **kwargs):
raise KeyboardInterrupt
class TestCli(unittest.TestCase):
def setUp(self):
self.real_stdout = sys.stdout
self.stdout = sys.stdout = StringIO()
self.argv = sys.argv
self.sys_exit = sys.exit
self.exit_code = None
self.ss_init = ScheduleScraper.__init__
def _fake_exit(code=None):
self.exit_code = code
_fake_exit.__name__ = sys.exit.__name__
sys.exit = _fake_exit
def tearDown(self):
sys.stdout = self.real_stdout
sys.argv = self.argv
sys.exit = self.sys_exit
ScheduleScraper.__init__ = self.ss_init
# write_ical
def test_write_stdout(self):
s = u'foobarXz123$$9_=+@@'
write_ical(s, '-')
self.stdout.seek(0)
self.assertEquals(s, self.stdout.read())
def test_write_file(self):
s = u'foo&"b$**a-rXz12%x3ZZ$$9_=+@@'
file_ = NamedTemporaryFile(delete=False)
file_.close()
filename = file_.name
write_ical(s, filename)
with open(filename, 'r') as f:
self.assertEquals(s, f.read())
remove(filename)
# main
def test_main_abort_on_interrupt(self):
ScheduleScraper.__init__ = ctrlC
sys.argv = ['edt2ics', 'M2']
self.assertEquals(None, self.exit_code)
main()
self.assertEquals(1, self.exit_code)
|
[
"[email protected]"
] | |
4344d7b0f4c19f27896dd13ab0f65e65e0e64627
|
7f523c407d45d116860eff67f079e807f2b53339
|
/src/third_party/beaengine/tests/0f46.py
|
6ad6b5dec2522c38575bfec34ef1d56a52f05929
|
[
"LGPL-3.0-only",
"LGPL-2.0-or-later",
"MIT"
] |
permissive
|
0vercl0k/rp
|
a352c96bfe3715eb9ce8c5942831123e65289dac
|
b24e7f58a594aaf0ce3771745bf06862f6ecc074
|
refs/heads/master
| 2023-08-30T08:03:14.842828 | 2023-08-09T00:41:00 | 2023-08-09T00:41:00 | 3,554,173 | 1,557 | 239 |
MIT
| 2023-08-09T00:41:02 | 2012-02-26T19:26:33 |
C++
|
UTF-8
|
Python
| false | false | 2,862 |
py
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>
#
# @author : [email protected]
from headers.BeaEnginePython import *
from nose.tools import *
class TestSuite:
def test(self):
# VEX.NDS.L1.0F.W0 46 /r
# kxnorW k1, k2, k3
myVEX = VEX('VEX.NDS.L1.0F.W0')
myVEX.vvvv = 0b1101
myVEX.R = 1
Buffer = bytes.fromhex('{}46cb'.format(myVEX.c4()))
myDisasm = Disasm(Buffer)
myDisasm.read()
assert_equal(hex(myDisasm.infos.Instruction.Opcode), '0x46')
assert_equal(myDisasm.infos.Reserved_.VEX.L, 1)
assert_equal(myDisasm.infos.Reserved_.REX.W_, 0)
assert_equal(myDisasm.infos.Reserved_.MOD_, 3)
assert_equal(myDisasm.infos.Instruction.Mnemonic, b'kxnorw')
assert_equal(myDisasm.repr(), 'kxnorw k1, k2, k3')
# VEX.L1.66.0F.W0 46 /r
# kxnorB k1, k2, k3
myVEX = VEX('VEX.L1.66.0F.W0')
myVEX.vvvv = 0b1101
myVEX.R = 1
Buffer = bytes.fromhex('{}46cb'.format(myVEX.c4()))
myDisasm = Disasm(Buffer)
myDisasm.read()
assert_equal(hex(myDisasm.infos.Instruction.Opcode), '0x46')
assert_equal(myDisasm.infos.Instruction.Mnemonic, b'kxnorb')
assert_equal(myDisasm.repr(), 'kxnorb k1, k2, k3')
# VEX.L1.0F.W1 46 /r
# kxnorQ k1, k2, k3
myVEX = VEX('VEX.L1.0F.W1')
myVEX.vvvv = 0b1101
myVEX.R = 1
Buffer = bytes.fromhex('{}46cb'.format(myVEX.c4()))
myDisasm = Disasm(Buffer)
myDisasm.read()
assert_equal(hex(myDisasm.infos.Instruction.Opcode), '0x46')
assert_equal(myDisasm.infos.Instruction.Mnemonic, b'kxnorq')
assert_equal(myDisasm.repr(), 'kxnorq k1, k2, k3')
# VEX.L1.66.0F.W1 46 /r
# kxnorD k1, k2, k3
myVEX = VEX('VEX.L1.66.0F.W1')
myVEX.vvvv = 0b1101
myVEX.R = 1
Buffer = bytes.fromhex('{}46cb'.format(myVEX.c4()))
myDisasm = Disasm(Buffer)
myDisasm.read()
assert_equal(hex(myDisasm.infos.Instruction.Opcode), '0x46')
assert_equal(myDisasm.infos.Instruction.Mnemonic, b'kxnord')
assert_equal(myDisasm.repr(), 'kxnord k1, k2, k3')
|
[
"[email protected]"
] | |
b6c2ce08804c66b293ae4e13ba70f17d93dcfbed
|
5465ed0ea2401a8e70d4bbc0ce1e78ca26813c54
|
/Dash/example_dropdown.py
|
432c0e12326a232ef545016451102df8cf8aca00
|
[] |
no_license
|
josephchenhk/learn
|
36c49ceb7c8cf8f944ad401b2c7adabf688981a1
|
b216bb17570e272555e9da475e4c85eb18139c2a
|
refs/heads/master
| 2023-09-01T04:22:00.984837 | 2023-08-20T01:00:01 | 2023-08-20T01:00:01 | 178,778,957 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 635 |
py
|
# -*- coding: utf-8 -*-
# @Time : 29/3/2021 3:41 PM
# @Author : Joseph Chen
# @Email : [email protected]
# @FileName: example_dropdown.py
# @Software: PyCharm
import dash
import dash_html_components as html
import dash_core_components as dcc
app = dash.Dash(__name__)
app.layout = html.Div(
[
html.H1('Selection'),
html.Br(),
dcc.Dropdown(
options=[
{'label': 'option 1', 'value': 1},
{'label': 'option 2', 'value': 2},
{'label': 'option 3', 'value': 3}
]
)
]
)
if __name__=="__main__":
app.run_server()
|
[
"[email protected]"
] | |
0b6e59dc34a33b978dbcf8b8704dd35cdf33c4d7
|
f97a38640cce46a0fa4f2e4c05590004cde14d61
|
/projectTS/modeControl/automaticFlexibleTime.py
|
d5e522fff3913cae6daf005105a5ec1dae1889c4
|
[] |
no_license
|
nch101/thesis-traffic-signal-control
|
bb9dcb43836e69fc4cd5954119b58fe74a03b445
|
b3bd1676fb2ab440b74d6d7a1846bd4ce6cc4c63
|
refs/heads/master
| 2023-08-31T11:29:19.415019 | 2020-08-17T05:07:10 | 2020-08-17T05:07:10 | 249,964,030 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 1,102 |
py
|
# ** automatic control mode **
# * Author: Nguyen Cong Huy *
# ****************************
# - *- coding: utf- 8 - *-
import projectTS.vals as vals
def automaticFlexibleTime():
for index in range(0, vals.nTrafficLights):
if index%2:
setTimeLight(vals.timeGreenFlexibleNS, vals.timeGreenFlexibleWS, index)
else:
setTimeLight(vals.timeGreenFlexibleWS, vals.timeGreenFlexibleNS, index)
def setTimeLight(timeGreen, timeGreenForTimeRed, index):
if ((vals.timeLight[index] == -1) and \
(vals.lightStatus[index] == 'red')):
vals.timeLight[index] = timeGreen
vals.lightStatus[index] = 'green'
elif ((vals.timeLight[index] == -1) and \
(vals.lightStatus[index] == 'yellow')):
vals.timeLight[index] = timeGreenForTimeRed + vals.timeYellow[index] + 2*vals.delta + 3
vals.lightStatus[index] = 'red'
elif ((vals.timeLight[index] == -1) and \
(vals.lightStatus[index] == 'green')):
vals.timeLight[index] = vals.timeYellow[index]
vals.lightStatus[index] = 'yellow'
else:
pass
|
[
"="
] |
=
|
c8c2388aacf9a93e788c79f3183bb7a4304a4f40
|
c6ee7be1479797788dd9f9d3a29c0e76ea020db8
|
/apscheduler_yqt/MyTestFile/16celery_rabbitmq/01/test.py
|
9f8dba3fe0e8b813e291b135506fa9d9d5a7a897
|
[] |
no_license
|
hikekang/apscheduler_yqt
|
2966e7231fff1f81c4fa4a75459cf638592aae6a
|
0d30c2ef721b8ffeba98dca6b2441613b4ed608d
|
refs/heads/master
| 2023-08-17T05:19:34.345553 | 2021-09-26T03:21:11 | 2021-09-26T03:21:11 | 406,217,786 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 272 |
py
|
#!/usr/bin/python3.x
# -*- coding=utf-8 -*-
"""
Time : 2021/8/24 14:24
Author : hike
Email : [email protected]
File Name : test.py
Description:
Software : PyCharm
"""
from tasks import add
result=add.delay(4,4)
print(result)
print(result.get())
|
[
"[email protected]"
] | |
104c925bd6314e637d48b9ae42bec366a68dc578
|
077c91b9d5cb1a6a724da47067483c622ce64be6
|
/snapshot_demo_updated_link_failure/interactive_replay_config.py
|
8829a94407e3072b87c050c553795abd1f1be3a8
|
[] |
no_license
|
Spencerx/experiments
|
0edd16398725f6fd9365ddbb1b773942e4878369
|
aaa98b0f67b0d0c0c826b8a1565916bf97ae3179
|
refs/heads/master
| 2020-04-03T10:11:40.671606 | 2014-06-11T23:55:11 | 2014-06-11T23:55:11 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 1,044 |
py
|
from config.experiment_config_lib import ControllerConfig
from sts.topology import *
from sts.control_flow import InteractiveReplayer
from sts.simulation_state import SimulationConfig
from sts.input_traces.input_logger import InputLogger
simulation_config = SimulationConfig(controller_configs=[ControllerConfig(start_cmd='./pox.py --verbose openflow.discovery forwarding.l2_multi_synthetic_link_failure_crash sts.util.socket_mux.pox_monkeypatcher openflow.of_01 --address=__address__ --port=__port__', label='c1', address='127.0.0.1', cwd='pox')],
topology_class=MeshTopology,
topology_params="num_switches=3",
patch_panel_class=BufferedPatchPanel,
multiplex_sockets=True,
kill_controllers_on_exit=True)
control_flow = InteractiveReplayer(simulation_config, "experiments/snapshot_demo_updated_link_failure/events.trace")
# wait_on_deterministic_values=False
# delay_flow_mods=False
# Invariant check: 'InvariantChecker.check_liveness'
# Bug signature: ""
|
[
"[email protected]"
] | |
37546155301527fa3625423441749a7d2847e9f0
|
6a89644ca479e1980b88c768bf868a1422fdee8b
|
/poptimizer/data/adapters/db.py
|
0535645631c3afb07276e3d0291c9c74ede11c70
|
[
"Unlicense"
] |
permissive
|
chekanskiy/poptimizer
|
82e664c2208b54cac63e0c5dac0680ec038da702
|
e5d0f2c28de25568e4515b63aaad4aa337e2e522
|
refs/heads/master
| 2022-12-20T15:09:40.111678 | 2020-10-06T17:11:49 | 2020-10-06T17:11:49 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 2,381 |
py
|
"""Реализации сессий доступа к базе данных."""
import asyncio
from typing import Iterable, Optional, Tuple, Union
import pandas as pd
from motor import motor_asyncio
from poptimizer.data.adapters import logger
from poptimizer.data.ports import outer
# Коллекция для одиночный записей
MISC = "misc"
def _collection_and_name(table_name: Union[outer.TableTuple, outer.TableName]) -> Tuple[str, str]:
"""Формирует название коллекции и имя документа."""
collection: str = table_name.group
name = table_name.name
if collection == name:
collection = MISC
return collection, name
class MongoDBSession(outer.AbstractDBSession):
"""Реализация сессии с хранением в MongoDB.
При совпадении id и группы данные записываются в специальную коллекцию, в ином случае в коллекцию
группы таблицы.
"""
def __init__(self, db: motor_asyncio.AsyncIOMotorDatabase) -> None:
"""Получает ссылку на базу данных."""
self._logger = logger.AsyncLogger(self.__class__.__name__)
self._db = db
async def get(self, table_name: outer.TableName) -> Optional[outer.TableTuple]:
"""Извлекает документ из коллекции."""
collection, name = _collection_and_name(table_name)
doc = await self._db[collection].find_one({"_id": name})
if doc is None:
return None
df = pd.DataFrame(**doc["data"])
return outer.TableTuple(*table_name, df=df, timestamp=doc["timestamp"])
async def commit(self, tables_vars: Iterable[outer.TableTuple]) -> None:
"""Записывает данные в MongoDB."""
aws = []
for table in tables_vars:
collection, name = _collection_and_name(table)
self._logger.info(f"Сохранение {collection}.{name}")
aw_update = self._db[collection].replace_one(
filter={"_id": name},
replacement=dict(_id=name, data=table.df.to_dict("split"), timestamp=table.timestamp),
upsert=True,
)
aws.append(aw_update)
await asyncio.gather(*aws)
|
[
"[email protected]"
] | |
22cb1afffa9f329ebfcbe75c0c93d8c82eaccab7
|
f13acd0d707ea9ab0d2f2f010717b35adcee142f
|
/ABC/abc251-abc300/abc291/a/main.py
|
271121f05c994fc6965d9d50bef5b54640e06764
|
[
"CC0-1.0",
"LicenseRef-scancode-public-domain"
] |
permissive
|
KATO-Hiro/AtCoder
|
126b9fe89fa3a7cffcbd1c29d42394e7d02fa7c7
|
bf43320bc1af606bfbd23c610b3432cddd1806b9
|
refs/heads/master
| 2023-08-18T20:06:42.876863 | 2023-08-17T23:45:21 | 2023-08-17T23:45:21 | 121,067,516 | 4 | 0 |
CC0-1.0
| 2023-09-14T21:59:38 | 2018-02-11T00:32:45 |
Python
|
UTF-8
|
Python
| false | false | 255 |
py
|
# -*- coding: utf-8 -*-
def main():
import sys
input = sys.stdin.readline
s = input().rstrip()
for i, si in enumerate(s, 1):
if si.isupper():
print(i)
exit()
if __name__ == "__main__":
main()
|
[
"[email protected]"
] | |
f4889ab3192e5b2391525b80f2cd647d5ffb097f
|
61ef327bd1d5ff6db7595221db6823c947dab42b
|
/FlatData/ScenarioCharacterAction.py
|
a9f4a598c4032f027b4141bed04cca067ccf7dac
|
[] |
no_license
|
Aikenfell/Blue-Archive---Asset-Downloader
|
88e419686a80b20b57a10a3033c23c80f86d6bf9
|
92f93ffbdb81a47cef58c61ec82092234eae8eec
|
refs/heads/main
| 2023-09-06T03:56:50.998141 | 2021-11-19T12:41:58 | 2021-11-19T12:41:58 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 262 |
py
|
# automatically generated by the FlatBuffers compiler, do not modify
# namespace: FlatData
class ScenarioCharacterAction(object):
Idle = 0
Shake = 1
Greeting = 2
FalldownLeft = 3
FalldownRight = 4
Stiff = 5
Hophop = 6
Jump = 7
|
[
"[email protected]"
] | |
4507b0a0250c6b95f949cf60bfc101f8efbe17ef
|
17124c2268d7d7b0e9545a1ddaf293a49fafcf72
|
/seq2seq/evaluation/meteor/meteor.py
|
4a9c0696a513d24b74e15736ecb66a7501dbe317
|
[] |
no_license
|
haxzie-xx/code-to-comment
|
56fadaf3b1be36daf2450159740cbd7d660fa438
|
5007d96c0e5ced57dcee7485a200a0e0a2c11e7d
|
refs/heads/master
| 2020-04-28T15:22:14.721580 | 2019-03-13T08:35:06 | 2019-03-13T08:35:06 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 3,077 |
py
|
#!/usr/bin/env python
# Python wrapper for METEOR implementation, by Xinlei Chen
# Acknowledge Michael Denkowski for the generous discussion and help
import os
import sys
import subprocess
import threading
# Assumes meteor-1.5.jar is in the same directory as meteor.py. Change as needed.
METEOR_JAR = 'meteor-1.5.jar'
# print METEOR_JAR
class Meteor:
def __init__(self):
self.meteor_cmd = ['java', '-jar', '-Xmx2G', METEOR_JAR, \
'-', '-', '-stdio', '-l', 'en', '-norm']
self.meteor_p = subprocess.Popen(self.meteor_cmd, \
cwd=os.path.dirname(os.path.abspath(__file__)), \
stdin=subprocess.PIPE, \
stdout=subprocess.PIPE, \
stderr=subprocess.PIPE)
# Used to guarantee thread safety
self.lock = threading.Lock()
# gts = reference list
# res = hypotheses
def compute_score(self, gts, res):
assert(gts.keys() == res.keys())
imgIds = gts.keys()
scores = []
eval_line = 'EVAL'
self.lock.acquire()
for i in imgIds:
assert(len(res[i]) == 1)
stat = self._stat(res[i][0], gts[i])
eval_line += ' ||| {}'.format(stat)
self.meteor_p.stdin.write('{}\n'.format(eval_line))
for i in range(0,len(imgIds)):
scores.append(float(self.meteor_p.stdout.readline().strip()))
score = float(self.meteor_p.stdout.readline().strip())
self.lock.release()
return score, scores
def method(self):
return "METEOR"
def _stat(self, hypothesis_str, reference_list):
# SCORE ||| reference 1 words ||| reference n words ||| hypothesis words
hypothesis_str = hypothesis_str.replace('|||','').replace(' ',' ')
score_line = ' ||| '.join(('SCORE', ' ||| '.join(reference_list), hypothesis_str))
self.meteor_p.stdin.write('{}\n'.format(score_line))
return self.meteor_p.stdout.readline().strip()
def _score(self, hypothesis_str, reference_list):
self.lock.acquire()
# SCORE ||| reference 1 words ||| reference n words ||| hypothesis words
hypothesis_str = hypothesis_str.replace('|||','').replace(' ',' ')
score_line = ' ||| '.join(('SCORE', ' ||| '.join(reference_list), hypothesis_str))
self.meteor_p.stdin.write('{}\n'.format(score_line))
stats = self.meteor_p.stdout.readline().strip()
eval_line = 'EVAL ||| {}'.format(stats)
# EVAL ||| stats
self.meteor_p.stdin.write('{}\n'.format(eval_line))
score = float(self.meteor_p.stdout.readline().strip())
# bug fix: there are two values returned by the jar file, one average, and one all, so do it twice
# thanks for Andrej for pointing this out
score = float(self.meteor_p.stdout.readline().strip())
self.lock.release()
return score
def __exit__(self):
self.lock.acquire()
self.meteor_p.stdin.close()
self.meteor_p.kill()
self.meteor_p.wait()
self.lock.release()
|
[
"[email protected]"
] | |
3fb6596f25e82ad3306342bc206831a44c1a8f19
|
16f50a812eca90748e87bfe471e0c05f178337fd
|
/4to_Semestre/Metodos computacionales/Racket/Actividad 3.4 Final/Examples/example.py
|
4fb7031bd1d767a5b0850a0aeefe25131ea51227
|
[] |
no_license
|
SeaWar741/ITC
|
65f73365762366f56cfbd6d0bc788cd384672d12
|
5f75716be58ca6e00bcd8dae7546fd19fe37657f
|
refs/heads/master
| 2023-02-05T23:25:13.972031 | 2022-09-29T10:38:32 | 2022-09-29T10:38:32 | 205,020,772 | 4 | 2 | null | 2023-01-19T15:28:45 | 2019-08-28T20:48:35 |
Jupyter Notebook
|
UTF-8
|
Python
| false | false | 288 |
py
|
# Python Program to find the factors of a number
# This function computes the factor of the argument passed
def print_factors(x ) :
print( " The factors of " , x , " are: " )
for i in range( 1 , x + 1 ) :
if x % i == 0:
print( i )
num = 320
print_factors( num )
|
[
"[email protected]"
] | |
b2c14211005aacceb7b237f92d39b72c2fba2218
|
93ed8dd9576a397912dad7693d63fc081f7651db
|
/tests/contracts/test_contract_estimateGas.py
|
24f7f4f3f3524f15111d642ecfcfbe6c4ad24f7b
|
[
"MIT"
] |
permissive
|
XertroV/web3.py
|
3cf1a1265aa9225fe0391feb99bf6088ecfd1937
|
1c6ead0c271da7b648d20dba8c880b76b436a03c
|
refs/heads/master
| 2021-01-24T20:25:36.578888 | 2016-07-16T19:00:10 | 2016-07-16T19:00:10 | 64,264,819 | 0 | 0 | null | 2016-07-27T00:46:25 | 2016-07-27T00:46:24 | null |
UTF-8
|
Python
| false | false | 1,476 |
py
|
import pytest
from web3.providers.rpc import TestRPCProvider
from web3.utils.abi import (
function_abi_to_4byte_selector,
)
@pytest.fixture(autouse=True)
def wait_for_first_block(web3, wait_for_block):
wait_for_block(web3)
@pytest.fixture()
def math_contract(web3, MATH_ABI, MATH_CODE, MATH_RUNTIME, MATH_SOURCE,
wait_for_transaction):
MathContract = web3.eth.contract(
abi=MATH_ABI,
code=MATH_CODE,
code_runtime=MATH_RUNTIME,
source=MATH_SOURCE,
)
deploy_txn = MathContract.deploy({'from': web3.eth.coinbase})
deploy_receipt = wait_for_transaction(deploy_txn)
assert deploy_receipt is not None
contract_address = deploy_receipt['contractAddress']
web3.isAddress(contract_address)
_math_contract = MathContract(address=contract_address)
return _math_contract
def test_needs_skipping(web3):
if not isinstance(web3.currentProvider, TestRPCProvider):
pytest.skip("N/A")
with pytest.raises(ValueError):
web3.eth.estimateGas({})
def test_contract_estimateGas(web3, math_contract):
if isinstance(web3.currentProvider, TestRPCProvider):
pytest.skip("The testrpc server doesn't implement `eth_estimateGas`")
increment_abi = math_contract.find_matching_abi('increment', [])
call_data = function_abi_to_4byte_selector(increment_abi)
gas_estimate = math_contract.estimateGas().increment()
assert abs(gas_estimate - 21272) < 200
|
[
"[email protected]"
] | |
31a9497b36cd6a4d54d6959b49c2445df08feb30
|
0adb68bbf576340c8ba1d9d3c07320ab3bfdb95e
|
/regexlib/python_re_test_file/regexlib_3613.py
|
7fbb386b0c1adfa1f8ca79e8518568b2dc33d7fb
|
[
"MIT"
] |
permissive
|
agentjacker/ReDoS-Benchmarks
|
c7d6633a3b77d9e29e0ee2db98d5dfb60cde91c6
|
f5b5094d835649e957bf3fec6b8bd4f6efdb35fc
|
refs/heads/main
| 2023-05-10T13:57:48.491045 | 2021-05-21T11:19:39 | 2021-05-21T11:19:39 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 578 |
py
|
# 3613
# <(?<tag>\w*|\w*\.+\w*)>+((.|[\n\t\f\r\s])*?)<\/\k<tag>>
# EXPONENT
# nums:4
# EXPONENT AttackString:"<>"+"\t"*16+"! _1◎@! _1! _1! _1!\n_SLQ_3"
import re
from time import perf_counter
regex = """<(?<tag>\w*|\w*\.+\w*)>+((.|[\n\t\f\r\s])*?)<\/\k<tag>>"""
REGEX = re.compile(regex)
for i in range(0, 150000):
ATTACK = "<>" + "\t" * i * 1 + "! _1◎@! _1! _1! _1!\n_SLQ_3"
LEN = len(ATTACK)
BEGIN = perf_counter()
m = REGEX.search(ATTACK)
# m = REGEX.match(ATTACK)
DURATION = perf_counter() - BEGIN
print(f"{i *1}: took {DURATION} seconds!")
|
[
"[email protected]"
] | |
1680eee25e123cd65af8e484e82f821ffcef73f5
|
72fd091cf4f9ad8c1a6475a8344bb750889e3b53
|
/cars/migrations/0001_initial.py
|
6f561308a8ce2a3549922aa1b79b89063e822140
|
[] |
no_license
|
petrshirin/example-web-app-for-using-db
|
abe312ab9dee36e5f53b795a2a0bc7529fa245f3
|
c625815525cc8427a6e0fc749afc14f126a90e05
|
refs/heads/master
| 2023-02-18T08:31:03.842057 | 2021-01-14T14:43:11 | 2021-01-14T14:43:11 | 328,006,038 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 3,449 |
py
|
# Generated by Django 3.1.5 on 2021-01-08 18:02
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Car',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('car_model', models.CharField(max_length=255)),
('production_date', models.DateField()),
('is_free', models.BooleanField(default=True)),
('price', models.DecimalField(decimal_places=2, max_digits=10)),
],
),
migrations.CreateModel(
name='Client',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('FIO', models.CharField(max_length=500)),
('car', models.ManyToManyField(blank=True, null=True, to='cars.Car')),
],
),
migrations.CreateModel(
name='Color',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=100)),
],
),
migrations.CreateModel(
name='Manager',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('FIO', models.CharField(max_length=500)),
('salary', models.DecimalField(decimal_places=2, max_digits=10)),
],
),
migrations.CreateModel(
name='Order',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('date_created', models.DateTimeField(blank=True, default=django.utils.timezone.now)),
('days_to_use', models.PositiveIntegerField()),
('total_price', models.DecimalField(decimal_places=2, max_digits=10)),
('closed', models.BooleanField(default=False)),
('car', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='cars.car')),
('client', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='cars.client')),
('manager', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='cars.manager')),
],
),
migrations.CreateModel(
name='ClientPassportData',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('series', models.CharField(max_length=4, null=True)),
('number', models.CharField(max_length=6, null=True)),
('issued_by_whom', models.CharField(max_length=255, null=True)),
('client', models.OneToOneField(null=True, on_delete=django.db.models.deletion.CASCADE, to='cars.client')),
],
),
migrations.AddField(
model_name='car',
name='color',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to='cars.color'),
),
]
|
[
"[email protected]"
] | |
222aba3bdc6078a2bbd2e01c79d319ab45d44737
|
30dea47f44695f3eeacb8270496cdced39485cbd
|
/tonedetect/tones.py
|
b72f95f4783db9396b689fd9cd31df1dc93ba559
|
[] |
no_license
|
cheind/py-tonedetect
|
67490d9b6f238226486e0cfa2831c4855e079c07
|
662b5d335ba9e830914cc0d0d2a1515f832f743b
|
refs/heads/master
| 2021-01-10T23:36:59.131599 | 2016-10-29T06:52:37 | 2016-10-29T06:52:37 | 70,419,207 | 1 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 880 |
py
|
import json
import itertools
import math
import numpy as np
class Tones(object):
""" A list of tones """
def __init__(self):
self.items = []
def add_tone(self, frequencies, sym=None):
sym = sym if sym is not None else len(self.items)
self.items.append({'f': frequencies, 'sym': sym})
def all_tone_frequencies(self):
""" Return a list of all frequencies across all tones """
f = []
for e in self.items:
f.extend(e['f'])
return list(set(f))
def minimum_frequency_step(self):
dists = [math.fabs(pair[0]-pair[1]) for pair in itertools.combinations(self.all_tone_frequencies(), 2)]
return np.min(dists)
@staticmethod
def from_json_file(filename):
t = Tones()
with open(filename) as f:
t.items = json.load(f)
return t
|
[
"[email protected]"
] | |
281d0127dbb5560633ec0da580a15c81be6ba978
|
24f29f50988c59785011f3bc2645fa5d2a7a7d97
|
/wlct/cogs/ladders.py
|
333e6289dac1c32fa28dd01d4fe5d125622fc1c7
|
[] |
no_license
|
h-shan/wzclot
|
d1c0c0f83b0b2916e0352c7cc0bfd25775a632d9
|
88d0e57c053a69a212af43f52168e234f41f6351
|
refs/heads/master
| 2021-01-07T20:17:04.065980 | 2020-02-19T22:44:18 | 2020-02-19T22:44:18 | 241,809,955 | 0 | 0 | null | 2020-02-20T06:25:12 | 2020-02-20T06:25:11 | null |
UTF-8
|
Python
| false | false | 5,329 |
py
|
import discord
from wlct.models import Clan, Player
from wlct.tournaments import Tournament, TournamentTeam, TournamentPlayer, MonthlyTemplateRotation, get_games_finished_for_team_since, find_tournament_by_id, get_team_data_no_clan, RealTimeLadder, get_real_time_ladder, TournamentGame
from discord.ext import commands, tasks
from wlct.cogs.common import is_admin
from django.utils import timezone
from traceback import print_exc
class Ladders(commands.Cog, name="ladders"):
''' Actually sends the help command '''
def __init__(self, bot):
self.bot = bot
@commands.command(brief="Lists all real-time ladders hosted by this bot and their IDs",
usage='''
109 -j : joins ladder 109
109 -l : leaves ladder 109
109 -t : displays all templates on the ladder
109 -p : displays all players currently on the ladder
109 -r : displays full ladder rankings
109 -g : displays all in progress games
109 -v templateid: vetoes a template or displays the current one if no template id is passed
''')
async def rtl(self, ctx, arg_id="invalid_id", arg_cmd="invalid_cmd", arg_cmd2="invalid_cmd2"):
print("Arguments for RTL id: {} command: {}".format(arg_id, arg_cmd))
invalid_cmd_text = "You've entered an invalid command. Please correct it and try again."
retStr = ""
do_embed = False
do_all_channels = False
embed_name = ""
if arg_id != "invalid_id":
emb = discord.Embed(color=self.bot.embed_color)
emb.set_author(icon_url=ctx.message.author.avatar_url, name=ctx.message.author)
emb.set_footer(text="Bot created and maintained by -B#0292")
if arg_id.isnumeric():
ladder = get_real_time_ladder(int(arg_id))
discord_id = ctx.message.author.id
if ladder is not None:
if arg_cmd == "-p":
# display current players in the ladder
retStr = ladder.get_current_joined()
elif arg_cmd == "-j":
retStr = ladder.join_ladder(discord_id)
retStr += "\n\n" + ladder.get_current_joined()
do_all_channels = True
elif arg_cmd == "-l":
retStr = ladder.leave_ladder(discord_id)
retStr += "\n\n" + ladder.get_current_joined()
do_all_channels = True
elif arg_cmd == "-t":
retStr = ladder.get_current_templates()
do_embed = True
emb.title = "Current Templates - Ladder {}".format(ladder.name)
emb.add_field(name="Templates", value=retStr)
elif arg_cmd == "-r":
retStr = ladder.get_current_rankings()
elif arg_cmd == "-g":
do_embed = True
retStr = ladder.get_current_games()
emb.title = "Current Games - Ladder {}".format(ladder.name)
emb.add_field(name="In Progress", value=retStr)
elif arg_cmd == "-v":
if arg_cmd2 != "invalid_cmd2":
retStr = ladder.veto_template(discord_id, arg_cmd2)
else:
# display the users current veto
retStr = ladder.get_current_vetoes(discord_id)
elif arg_cmd == "-ta":
if arg_cmd2 != "invalid_cmd2":
# check to make sure the author has access here
if is_admin(ctx.message.author.id):
retStr = ladder.add_template(arg_cmd2)
else:
retStr = invalid_cmd_text
elif arg_cmd == "-tr":
if arg_cmd2 != "invalid_cmd2":
# check for access
if is_admin(ctx.message.author.id):
retStr = ladder.remove_template(arg_cmd2)
else:
retStr = invalid_cmd_text
else:
retStr = invalid_cmd_text
else:
retStr = "You've entered an invalid ladder ID."
else:
retStr = "You've entered an invalid ladder ID."
elif arg_id == "invalid_id":
retStr += "__**Current Real-Time Ladders**__\n"
ladders = RealTimeLadder.objects.all()
if not ladders or ladders.count() == 0:
retStr += "There are no real-time ladders created yet."
else:
for ladder in ladders:
retStr += "{} | Id: {}".format(ladder.name, ladder.id)
else:
retStr = "You have entered an invalid command. Please correct it and try again."
if do_embed:
await ctx.send(embed=emb)
else:
await ctx.send(retStr)
def setup(bot):
bot.add_cog(Ladders(bot))
|
[
"[email protected]"
] | |
58d9f299b2be3ac5b35e101e9d797493adbbab9e
|
502fc0002d5575d0a37b4f13706c7072f860033c
|
/Chapter06/cyclegan/datasets.py
|
c851a615e497b6d1583f95c8955550f2b29adf88
|
[
"MIT"
] |
permissive
|
PacktPublishing/Hands-On-Generative-Adversarial-Networks-with-PyTorch-1.x
|
665d9364af54d7fd44787d0753400d7625ac8b82
|
beee21343078b607f393bbb1321ac49cf17ffb5f
|
refs/heads/master
| 2023-02-10T22:12:08.980700 | 2023-01-30T09:26:20 | 2023-01-30T09:26:20 | 227,829,701 | 66 | 50 | null | null | null | null |
UTF-8
|
Python
| false | false | 1,129 |
py
|
import glob
import random
import os
import torchvision
from torch.utils.data import Dataset
from PIL import Image
class ImageDataset(Dataset):
def __init__(self, root_dir, transform=None, unaligned=False, mode='train'):
self.transform = torchvision.transforms.Compose(transform)
self.unaligned = unaligned
self.train = (mode == 'train')
self.files_A = sorted(glob.glob(os.path.join(root_dir, '%sA' % mode) + '/*.*'))
self.files_B = sorted(glob.glob(os.path.join(root_dir, '%sB' % mode) + '/*.*'))
def __getitem__(self, index):
item_A = self.transform(Image.open(self.files_A[index % len(self.files_A)]))
if self.unaligned:
item_B = self.transform(Image.open(self.files_B[random.randint(0, len(self.files_B) - 1)]))
else:
item_B = self.transform(Image.open(self.files_B[index % len(self.files_B)]))
if self.train:
return {'trainA': item_A, 'trainB': item_B}
else:
return {'testA': item_A, 'testB': item_B}
def __len__(self):
return max(len(self.files_A), len(self.files_B))
|
[
"[email protected]"
] | |
e65cbf5b64816e289ebbda33044e7070ef649a39
|
a5e591dc09e11e88af56fb5a881fae064fb9c495
|
/recruitment/recruitment/doctype/sds/test_sds.py
|
c6cce9a11e7909f1af24d4e5044701cb9cfd6ede
|
[
"MIT"
] |
permissive
|
barathprathosh/recruitment
|
6b61dd1ee9c0b9d7851b0b3e5bab307f7ee2d1b5
|
9660944856e72288e47960e6802ec97a220a656d
|
refs/heads/master
| 2020-04-29T03:03:51.722972 | 2019-03-15T08:58:32 | 2019-03-15T08:58:32 | 175,794,797 | 0 | 0 |
NOASSERTION
| 2019-03-15T10:00:32 | 2019-03-15T10:00:31 | null |
UTF-8
|
Python
| false | false | 247 |
py
|
# -*- coding: utf-8 -*-
# Copyright (c) 2015, VHRS and Contributors
# See license.txt
from __future__ import unicode_literals
import frappe
import unittest
# test_records = frappe.get_test_records('SDS')
class TestSDS(unittest.TestCase):
pass
|
[
"[email protected]"
] | |
a697dce54965d918f7b330653707e0336ac916cc
|
4bd4bacecee33cada173e427b5ecb1d758bafaad
|
/src/scalarizr/storage2/filesystems/ext3.py
|
db6c14a7eb67d5266be90987c0ab7e3c2a861102
|
[] |
no_license
|
kenorb-contrib/scalarizr
|
3f2492b20910c42f6ab38749545fdbb79969473f
|
3cc8b64d5a1b39c4cf36f5057f1a6a84a9a74c83
|
refs/heads/master
| 2022-11-26T10:00:58.706301 | 2017-11-02T16:41:34 | 2017-11-02T16:41:34 | 108,550,233 | 0 | 2 | null | 2020-07-24T11:05:36 | 2017-10-27T13:33:46 |
Python
|
UTF-8
|
Python
| false | false | 1,840 |
py
|
"""
Created on Aug 29, 2012
@author: marat
"""
from scalarizr import storage2
from scalarizr.storage2 import filesystems
E2LABEL_EXEC = "/sbin/e2label"
RESIZE2FS_EXEC = "/sbin/resize2fs"
E2FSCK_EXEC = "/sbin/e2fsck"
MAX_LABEL_LENGTH = 16
class ExtFileSystem(filesystems.FileSystem):
features = filesystems.FileSystem.features.copy()
features['umount_on_resize'] = True
error_messages = filesystems.FileSystem.error_messages.copy()
error_messages['fsck'] = 'Error occured during filesystem check on device %s'
os_packages = ('e2fsprogs', )
def mkfs(self, device, *short_args):
short_args = list(short_args)
short_args += list(opt for opt in ('-F', '-q') if opt not in short_args)
super(ExtFileSystem, self).mkfs(device, *short_args)
def resize(self, device, size=None, *short_args, **long_kwds):
cmd = (E2FSCK_EXEC, '-fy', device)
rcode = filesystems.system(cmd, raise_exc=False,
error_text=self.error_messages['fsck'] % device)[2]
if rcode not in (0, 1):
raise storage2.StorageError('Fsck failed to correct file system errors')
cmd = (RESIZE2FS_EXEC, device)
filesystems.system(cmd, error_text=self.error_messages['resize'] % device)
def set_label(self, device, label):
cmd = (E2LABEL_EXEC, device, label[:MAX_LABEL_LENGTH])
filesystems.system(cmd, error_text=self.error_messages['set_label'] % device)
def get_label(self, device):
cmd = (E2LABEL_EXEC, device)
return filesystems.system(cmd, error_text=self.error_messages['get_label'] % device)[0].strip()
class Ext3FileSystem(ExtFileSystem):
type = 'ext3'
storage2.filesystem_types[Ext3FileSystem.type] = Ext3FileSystem
|
[
"[email protected]"
] | |
e2dd3fc6ed5023653573ada2255327ccf464b401
|
d694a99c910ce36c8d6981e126548fc91e74046e
|
/Regression/regression.py
|
60bd820898953a66d0998f401bded14011439700
|
[] |
no_license
|
YiddishKop/ml_src_adam_compare
|
08ac23cf1fb02222da1f04e833e296b1b75ae9af
|
cfeadebd41f802686828958068c15bcfdfea0be9
|
refs/heads/master
| 2020-03-25T22:16:19.581690 | 2018-08-09T23:37:31 | 2018-08-09T23:37:31 | 144,213,684 | 1 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 3,177 |
py
|
import numpy as np
import tensorflow as tf
from math import sqrt
from keras import optimizers
from keras.models import Sequential
from keras.layers import Dense, Dropout, Activation, normalization
from keras.backend.tensorflow_backend import set_session
config = tf.ConfigProto()
config.gpu_options.per_process_gpu_memory_fraction = 0.5
set_session(tf.Session(config = config))
class Model(object):
def __init__(self):
self.x = np.load("x_train.npy")
self.y = np.load("y_train.npy")
def select_training_data(self):
self.x_train, self.y_train = np.array(self.x), np.array(self.y)
self.add_x()
n = 18000
self.x_valid = self.x[n:]
self.y_valid = self.y[n:]
self.x = self.x[:n]
self.y = self.y[:n]
print "x_train =", self.x.shape, self.x_valid.shape
print "y_train =", self.y.shape, self.y_valid.shape
def add_x(self):
grade0 = [0, 1, 6, 7]
grade1 = [2, 3, 8, 9, 10]
square = np.square(self.x[:, grade0])
sqrt = np.sqrt(self.x[:, :])
n = self.x_train.shape[1]
cross_term = np.empty([self.x.shape[0], n*(n-1)/2])
s = 0
for i in range(n-1):
for j in range(i+1, n):
cross_term[:, s] = self.x[:, i] * self.x[:, j]
s += 1
cube = np.power(self.x[:, grade0], 3)
self.x = np.concatenate([self.x, square], 1)
self.x = np.concatenate([self.x, cross_term], 1)
self.x = np.concatenate([self.x, np.ones([self.x.shape[0], 1])], 1)
print self.x.shape
def build_nn_model(self):
nn_model = Sequential()
nn_model.add(Dense(input_dim = self.x.shape[1], output_dim = 1000))
nn_model.add(Activation('relu'))
nn_model.add(Dense(output_dim = 1000))
nn_model.add(Activation('relu'))
nn_model.add(Dense(output_dim = 1000))
nn_model.add(Dense(output_dim = 1))
nn_model.summary()
opt = optimizers.Adam(lr = 0.0001, beta_1 = 0.9, beta_2 = 0.999, epsilon = 1e-8, decay=0.0)
#opt = optimizers.SGD(lr = 10E-5)
nn_model.compile(loss = 'mean_squared_error', optimizer = opt, metrics = ['accuracy'])
nn_model.fit(self.x, self.y, batch_size = 100, nb_epoch = 0, shuffle = True, validation_data = (self.x_valid, self.y_valid))
nn_model.save('model.h5')
fout = open("result", 'w')
self.result = nn_model.predict(self.x[:5000])
self.output_result(fout, self.y[:5000])
self.result = nn_model.predict(self.x_valid)
self.output_result(fout, self.y_valid)
def output_result(self, fout, y_true): # write file
fout.write("y_pred, y_train, error, rms_error\n")
ave_error = 0
rms_error = 0
count = self.result.shape[0]
for i in range(self.result.shape[0]):
if self.y[i] > 0:
err1 = np.abs((self.result[i][0] - y_true[i]))/y_true[i]#self.y[i][0]
ave_error += err1
err2 = np.square((self.result[i][0] - y_true[i]))
rms_error += err2
fout.write("%.2f" %(self.result[i][0]) + " - " + "%.2f" %(y_true[i]) + " - ")
fout.write("%.2f" %(err1*100) + ", %.2f" %(err2) + "\n")
else:
count -= 1
ave_error = ave_error / float(count)
rms_error = sqrt(rms_error / float(count))
print "Number =", count
print "Ave error = %.3f" %(ave_error * 100), "%"
print "RMS error = %.3f" %(rms_error)
model = Model()
model.select_training_data()
model.build_nn_model()
|
[
"[email protected]"
] | |
5497665447fb033386b2092a63fbef7149fd845b
|
dddd89637373f455a476431f4fcb7e17b4e9dd57
|
/py/display.py
|
85bcfe46e59c909fad72f4b04abaf084a127d399
|
[] |
no_license
|
DhirManish/Python
|
35304eb47dea61934426fb6fc5094e1a83517cf3
|
10df7245d0964340d6c8d14cf26a9cf8f93ecf5d
|
refs/heads/master
| 2020-06-05T07:09:41.856780 | 2015-03-07T12:53:10 | 2015-03-07T12:53:10 | 20,372,496 | 1 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 991 |
py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# display.py
#
# Copyright 2014 Ajay Bhatia <ajay@dumb-box>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
#
#
import sys
def main(fname):
file = open(fname)
for line in file.readlines():
print line,
if __name__ == '__main__':
main(sys.argv[1])
|
[
"[email protected]"
] | |
51d3cd83c17924f57928febd4c77f7e11a693a64
|
ac42f1d918bdbd229968cea0954ed75250acd55c
|
/admin/dashboard/openstack_dashboard/test/integration_tests/tests/test_credentials.py
|
45c7f9956f3bb90d941ff841ff21f9390cc0aa7a
|
[
"Apache-2.0"
] |
permissive
|
naanal/product
|
016e18fd2f35608a0d8b8e5d2f75b653bac7111a
|
bbaa4cd60d4f2cdda6ce4ba3d36312c1757deac7
|
refs/heads/master
| 2020-04-03T22:40:48.712243 | 2016-11-15T11:22:00 | 2016-11-15T11:22:00 | 57,004,514 | 1 | 1 | null | null | null | null |
UTF-8
|
Python
| false | false | 3,250 |
py
|
# 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 horizon.test import firefox_binary
from openstack_dashboard.test.integration_tests import helpers
from os import listdir
from os.path import join
from os import remove
class TestDownloadRCFile(helpers.AdminTestCase):
_directory = firefox_binary.WebDriver.TEMPDIR
_openrc_template = "-openrc.sh"
def setUp(self):
super(TestDownloadRCFile, self).setUp()
username = self.TEST_USER_NAME
tenant_name = self.HOME_PROJECT
projects_page = self.home_pg.go_to_identity_projectspage()
tenant_id = projects_page.get_project_id_from_row(tenant_name)
self.actual_dict = {'OS_USERNAME': username,
'OS_TENANT_NAME': tenant_name,
'OS_TENANT_ID': tenant_id}
def test_download_rc_v2_file(self):
"""This is a basic scenario test:
Steps:
1) Login to Horizon Dashboard as admin user
2) Navigate to Project > Compute > Access & Security > API Access tab
3) Click on "Download OpenStack RC File v2.0" button
4) File named by template "<tenant_name>-openrc.sh" must be downloaded
5) Check that username, tenant name and tenant id correspond to current
username, tenant name and tenant id
"""
api_access_page = self.home_pg.\
go_to_compute_accessandsecurity_apiaccesspage()
api_access_page.download_openstack_rc_file(
2, self._directory, self._openrc_template)
cred_dict = api_access_page.get_credentials_from_file(
2, self._directory, self._openrc_template)
self.assertEqual(cred_dict, self.actual_dict)
def test_download_rc_v3_file(self):
"""This is a basic scenario test:
Steps:
1) Login to Horizon Dashboard as admin user
2) Navigate to Project > Compute > Access & Security > API Access tab
3) Click on "Download OpenStack RC File v3" button
4) File named by template "<tenant_name>-openrc.sh" must be downloaded
5) Check that username, project name and project id correspond to
current username, tenant name and tenant id
"""
api_access_page = self.home_pg.\
go_to_compute_accessandsecurity_apiaccesspage()
api_access_page.download_openstack_rc_file(
3, self._directory, self._openrc_template)
cred_dict = api_access_page.get_credentials_from_file(
3, self._directory, self._openrc_template)
self.assertEqual(cred_dict, self.actual_dict)
def tearDown(self):
super(TestDownloadRCFile, self).tearDown()
remove(join(self._directory, listdir(self._directory)[0]))
|
[
"[email protected]"
] | |
8654ed8796db644dd4805d8b68137f4e06de7879
|
f2b44af5372c6318a941015f64b279ccf9099a18
|
/rest130/wsgi.py
|
5726a659e41211d23cf13244551e776d53d36061
|
[] |
no_license
|
yuansuixin/Rest-Framework-page-view
|
c459ca54c1998cde4c0fe207ba6464353471cbdf
|
a8663c09a00ce4f4d055ca96e3132ae0a4ddea54
|
refs/heads/master
| 2020-03-13T06:58:12.512163 | 2018-04-25T14:09:15 | 2018-04-25T14:09:15 | 131,015,642 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 392 |
py
|
"""
WSGI config for rest130 project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "rest130.settings")
application = get_wsgi_application()
|
[
"[email protected]"
] | |
fd0e88862a3552ff5a444410f25c478bc09b9ccc
|
53fab060fa262e5d5026e0807d93c75fb81e67b9
|
/backup/user_185/ch21_2019_09_02_16_11_34_126817.py
|
caeb588b2448887a21cc708aae209b3242a27c36
|
[] |
no_license
|
gabriellaec/desoft-analise-exercicios
|
b77c6999424c5ce7e44086a12589a0ad43d6adca
|
01940ab0897aa6005764fc220b900e4d6161d36b
|
refs/heads/main
| 2023-01-31T17:19:42.050628 | 2020-12-16T05:21:31 | 2020-12-16T05:21:31 | 306,735,108 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 138 |
py
|
valor_conta = float(input("Digite o valor da conta"))
valor_10 = valor_conta * 1.1
print("Valor da conta com 10% {.:2f}".format(valor_10))
|
[
"[email protected]"
] | |
962e96893571f492778142b708236e00d56b680e
|
c54f5a7cf6de3ed02d2e02cf867470ea48bd9258
|
/pyobjc/pyobjc-framework-Quartz/PyObjCTest/test_cikernel.py
|
b0db5ef848f5d457400c0faee426365fabfe1997
|
[
"MIT"
] |
permissive
|
orestis/pyobjc
|
01ad0e731fbbe0413c2f5ac2f3e91016749146c6
|
c30bf50ba29cb562d530e71a9d6c3d8ad75aa230
|
refs/heads/master
| 2021-01-22T06:54:35.401551 | 2009-09-01T09:24:47 | 2009-09-01T09:24:47 | 16,895 | 8 | 5 | null | null | null | null |
UTF-8
|
Python
| false | false | 306 |
py
|
from PyObjCTools.TestSupport import *
from Quartz.QuartzCore import *
from Quartz import *
class TestCIKernel (TestCase):
def testMethods(self):
self.failUnlessArgIsSEL(CIKernel.setROISelector_, 0, CGRect.__typestr__ + '@:i' + CGRect.__typestr__ + '@')
if __name__ == "__main__":
main()
|
[
"ronaldoussoren@f55f28a5-9edb-0310-a011-a803cfcd5d25"
] |
ronaldoussoren@f55f28a5-9edb-0310-a011-a803cfcd5d25
|
cbc6351fd46ad8ea36dc9847027121c21c9f0537
|
c81d7dfef424b088bf2509a1baf406a80384ea5a
|
/venv/Lib/site-packages/pandas/tests/indexes/period/test_period_range.py
|
49d34248207919814f02e980ff00b963e21dcdd9
|
[] |
no_license
|
Goutham2591/OMK_PART2
|
111210d78fc4845481ed55c852b8f2f938918f4a
|
cb54fb21ebf472bffc6ee4f634bf1e68303e113d
|
refs/heads/master
| 2022-12-10T01:43:08.213010 | 2018-04-05T02:09:41 | 2018-04-05T02:09:41 | 124,828,094 | 0 | 1 | null | 2022-12-07T23:43:03 | 2018-03-12T03:20:14 |
Python
|
UTF-8
|
Python
| false | false | 3,740 |
py
|
import pytest
import pandas.util.testing as tm
from pandas import date_range, NaT, period_range, Period, PeriodIndex
class TestPeriodRange(object):
@pytest.mark.parametrize('freq', ['D', 'W', 'M', 'Q', 'A'])
def test_construction_from_string(self, freq):
# non-empty
expected = date_range(start='2017-01-01', periods=5,
freq=freq, name='foo').to_period()
start, end = str(expected[0]), str(expected[-1])
result = period_range(start=start, end=end, freq=freq, name='foo')
tm.assert_index_equal(result, expected)
result = period_range(start=start, periods=5, freq=freq, name='foo')
tm.assert_index_equal(result, expected)
result = period_range(end=end, periods=5, freq=freq, name='foo')
tm.assert_index_equal(result, expected)
# empty
expected = PeriodIndex([], freq=freq, name='foo')
result = period_range(start=start, periods=0, freq=freq, name='foo')
tm.assert_index_equal(result, expected)
result = period_range(end=end, periods=0, freq=freq, name='foo')
tm.assert_index_equal(result, expected)
result = period_range(start=end, end=start, freq=freq, name='foo')
tm.assert_index_equal(result, expected)
def test_construction_from_period(self):
# upsampling
start, end = Period('2017Q1', freq='Q'), Period('2018Q1', freq='Q')
expected = date_range(start='2017-03-31', end='2018-03-31', freq='M',
name='foo').to_period()
result = period_range(start=start, end=end, freq='M', name='foo')
tm.assert_index_equal(result, expected)
# downsampling
start, end = Period('2017-1', freq='M'), Period('2019-12', freq='M')
expected = date_range(start='2017-01-31', end='2019-12-31', freq='Q',
name='foo').to_period()
result = period_range(start=start, end=end, freq='Q', name='foo')
tm.assert_index_equal(result, expected)
# empty
expected = PeriodIndex([], freq='W', name='foo')
result = period_range(start=start, periods=0, freq='W', name='foo')
tm.assert_index_equal(result, expected)
result = period_range(end=end, periods=0, freq='W', name='foo')
tm.assert_index_equal(result, expected)
result = period_range(start=end, end=start, freq='W', name='foo')
tm.assert_index_equal(result, expected)
def test_errors(self):
# not enough params
msg = ('Of the three parameters: start, end, and periods, '
'exactly two must be specified')
with tm.assert_raises_regex(ValueError, msg):
period_range(start='2017Q1')
with tm.assert_raises_regex(ValueError, msg):
period_range(end='2017Q1')
with tm.assert_raises_regex(ValueError, msg):
period_range(periods=5)
with tm.assert_raises_regex(ValueError, msg):
period_range()
# too many params
with tm.assert_raises_regex(ValueError, msg):
period_range(start='2017Q1', end='2018Q1', periods=8, freq='Q')
# start/end NaT
msg = 'start and end must not be NaT'
with tm.assert_raises_regex(ValueError, msg):
period_range(start=NaT, end='2018Q1')
with tm.assert_raises_regex(ValueError, msg):
period_range(start='2017Q1', end=NaT)
# invalid periods param
msg = 'periods must be a number, got foo'
with tm.assert_raises_regex(TypeError, msg):
period_range(start='2017Q1', periods='foo')
|
[
"[email protected]"
] | |
820d4e8465a9ca575fe26c9092050f29834c8f99
|
5891051796778cfb44a255248ce38789bfef9e70
|
/DjangoLearn/apps/test_django/models.py
|
8820b1517c116ec9de6dbc52b1199d2373a5e12e
|
[] |
no_license
|
Faithlmy/Python_base
|
cc546a5d86b123e102a69df1227cde9b6e567493
|
5a43557e6375dc9dbe5f6701d7c10e549873a5ab
|
refs/heads/master
| 2021-01-01T17:07:04.097978 | 2018-03-31T16:44:01 | 2018-03-31T16:44:01 | 98,000,621 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 4,296 |
py
|
from django.db import models
# Create your models here.
class TbCustomInfo(models.Model):
c_name = models.CharField(max_length=255, blank=True, null=True)
c_name_short = models.CharField(max_length=255, blank=True, null=True)
c_num = models.CharField(max_length=255, blank=True, null=True)
c_type = models.CharField(max_length=255, blank=True, null=True)
c_site = models.CharField(max_length=255, blank=True, null=True)
create_time = models.DateTimeField(blank=True, null=True, auto_now_add=True)
modify_time = models.DateTimeField(blank=True, null=True, auto_now_add=True)
delete_flag = models.IntegerField(blank=True, null=True)
class Meta:
managed = False
db_table = 'tb_custom_info'
class TbCustomerPaper(models.Model):
# mm = models.Manager
ecn_no = models.CharField(db_column='ECN_NO', max_length=255, blank=True, null=True) # Field name made lowercase.
version = models.CharField(max_length=255, blank=True, null=True)
p_name = models.CharField(max_length=255, blank=True, null=True)
st_site = models.CharField(db_column='ST_site', max_length=255, blank=True, null=True) # Field name made lowercase.
drawing_type = models.CharField(max_length=255, blank=True, null=True)
definer_name = models.CharField(max_length=255, blank=True, null=True)
c_name = models.CharField(max_length=255, blank=True, null=True)
c_type = models.CharField(max_length=255, blank=True, null=True)
c_site = models.CharField(max_length=255, blank=True, null=True)
uploader = models.CharField(max_length=255, blank=True, null=True)
custters_spec = models.CharField(max_length=255, blank=True, null=True)
case_name = models.CharField(max_length=255, blank=True, null=True)
priority = models.IntegerField(blank=True, null=True)
alter_cause = models.TextField(blank=True, null=True)
alter_front = models.TextField(blank=True, null=True)
alter_later = models.TextField(blank=True, null=True)
desc_file = models.TextField(blank=True, null=True)
create_time = models.DateTimeField(blank=True, null=True)
modify_time = models.DateTimeField(blank=True, null=True)
upload_time = models.DateTimeField(blank=True, null=True)
c_confirm = models.IntegerField(blank=True, null=True)
customer_info = models.ForeignKey('TbCustomInfo', on_delete=models.DO_NOTHING, db_column='customer_info', blank=True, null=True)
copy_id = models.IntegerField(blank=True, null=True)
drawingtype = models.IntegerField(blank=True, null=True)
modify_draft = models.IntegerField(blank=True, null=True)
valid = models.IntegerField(blank=True, null=True)
create_people = models.CharField(max_length=255, blank=True, null=True)
current = models.IntegerField(blank=True, null=True)
enabled = models.IntegerField(blank=True, null=True)
class Meta:
managed = False
db_table = 'tb_customer_paper'
class TbDrawingFile(models.Model):
file_name = models.CharField(max_length=255, blank=True, null=True)
file_size = models.IntegerField(blank=True, null=True)
file_path = models.CharField(max_length=255, blank=True, null=True)
uploader = models.CharField(max_length=255, blank=True, null=True)
create_time = models.DateTimeField(blank=True, null=True)
customer = models.ForeignKey('TbCustomerPaper', on_delete=models.DO_NOTHING, blank=True, null=True)
file_type = models.IntegerField(blank=True, null=True)
# project = models.ForeignKey('TbProjectPaper', on_delete=models.DO_NOTHING, blank=True, null=True)
# drawing_type = models.ForeignKey('TbDrawing', on_delete=models.DO_NOTHING, blank=True, null=True)
cus = models.IntegerField(blank=True, null=True)
drawing_type_name = models.CharField(max_length=255, blank=True, null=True)
dev_type = models.CharField(max_length=255, blank=True, null=True)
# id_dev_type = models.ForeignKey('TbTypeDevice', on_delete=models.DO_NOTHING, db_column='id_dev_type', blank=True, null=True)
b_all = models.IntegerField(blank=True, null=True)
sign_filepath = models.CharField(max_length=255, blank=True, null=True)
seal_filepath = models.CharField(max_length=255, blank=True, null=True)
class Meta:
managed = False
db_table = 'tb_drawing_file'
|
[
"[email protected]"
] | |
717bd41fe9b212c3ecf9faf925de10324dd12ab9
|
ef48efff7b9022f9745145509193d551f4084376
|
/novedades/models.py
|
f731d1dcb004d9927fff918f8e0a6360dcc718a1
|
[] |
no_license
|
ljarufe/incamotors
|
b5ace5cfb2f5208a31859f06da3e6cf46867b35c
|
79926654e286e9fd496bb1be9ce8d03ca218d654
|
refs/heads/master
| 2020-05-06T12:20:00.996574 | 2013-10-21T16:09:20 | 2013-10-21T16:09:20 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 2,527 |
py
|
# -*- coding: utf-8 -*-
from django.db import models
from sorl.thumbnail.fields import ImageWithThumbnailsField
class Novedad(models.Model):
"""
Clase abstracta para todas las novedades
"""
nombre = models.CharField(max_length=100)
descripcion = models.TextField(verbose_name=u"descripción")
def __unicode__(self):
return '%s' % self.nombre
class Meta:
abstract = True
class Evento(Novedad):
"""
Eventos de la página de inicio
"""
foto = ImageWithThumbnailsField(
upload_to = 'img/eventos',
thumbnail = {'size': (625, 420),
'options': ['upscale', 'max', 'crop']},
generate_on_save = True,
)
class Evento_home(Novedad):
"""
Eventos para la página de inicio
"""
foto = ImageWithThumbnailsField(
upload_to = 'img/eventos',
thumbnail = {'size': (625, 420),
'options': ['upscale', 'max', 'crop']},
generate_on_save = True,
)
foto_pie = ImageWithThumbnailsField(
upload_to = 'img/eventos',
thumbnail = {'size': (625, 220),
'options': ['upscale', 'max', 'crop']},
generate_on_save = True,
)
class Meta:
verbose_name = u"Evento en home"
verbose_name_plural = u"Eventos en home"
class Promocion(Novedad):
"""
Promociones de incamotors, iguales a los eventos
"""
foto = ImageWithThumbnailsField(
upload_to = 'img/promociones',
thumbnail = {'size': (625, 420),
'options': ['upscale', 'max', 'crop']},
generate_on_save = True,
)
class Meta:
verbose_name = u"promoción"
verbose_name_plural = u"promociones"
class Noticia(Novedad):
"""
Noticias del menu superior
"""
foto = ImageWithThumbnailsField(
upload_to = 'img/noticias',
thumbnail = {'size': (625, 420),
'options': ['upscale', 'max', 'crop']},
generate_on_save = True,
)
class Enlace(models.Model):
"""
Enlaces a otros sitios web
"""
url = models.URLField()
descripcion = models.TextField(verbose_name=u"descripción")
def __unicode__(self):
return u"%s" % self.url
|
[
"[email protected]"
] | |
d0da70c270dd71617fd4d3449d199f1a9f94549a
|
8004cc465359aecb7a1890617646ea5b49f11d9a
|
/cnn_models/cnn_dropout.py
|
4034ce3be9e2c7aad18f0a543a39bd23928ad07f
|
[] |
no_license
|
jhyang12345/facial-recognition
|
661e34d874986943f50b5b9691d186760957b594
|
2f2ba5cfcbd58efbc9de5b9f0bafc7bc640d9c26
|
refs/heads/master
| 2020-04-06T09:52:20.932793 | 2018-12-13T08:15:25 | 2018-12-13T08:15:25 | 157,360,076 | 7 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 3,747 |
py
|
from keras.layers import Input, Convolution2D, SeparableConvolution2D, \
GlobalAveragePooling2D, GlobalMaxPooling2D, MaxPooling2D, \
Dense, Activation, BatchNormalization, Dropout
from keras.models import Sequential, Model
from keras.callbacks import ModelCheckpoint
class CNNDropout:
def __init__(self, input_shape=(128, 128, 3), summarize=True):
self.image_width = input_shape[0]
self.image_height = input_shape[1]
self.channels = input_shape[2]
self.input_shape = input_shape
self.alpha = 1
self.name = "cnn_dropout"
self.model = None
self.checkpoint_path = 'models/cnn_dropout.best.hdf5'
self.checkpointer = ModelCheckpoint(filepath=self.checkpoint_path, verbose=1,
save_best_only=True)
self.build_model()
if summarize: self.model.summary()
def build_model(self):
model_input = Input(shape=self.input_shape)
alpha = self.alpha
activation_type = 'relu'
# applying dropout factor to prevent overfitting
dropout_factor = 0.4
# input format will usually be 128 or 2^7
# strides of 2 halfs input shape
# usually kernel sizes are in odd numbers
# kernel strides alternate between 1 and 2 so that we don't miss out
x = Convolution2D(int(32 * alpha), (3, 3), strides=(1, 1), padding='same')(model_input)
x = BatchNormalization()(x)
x = Activation(activation_type)(x)
x = Convolution2D(int(64 * alpha), (3, 3), strides=(1, 1), padding='same')(x)
x = BatchNormalization()(x)
x = Activation(activation_type)(x)
x = Convolution2D(int(64 * alpha), (3, 3), strides=(2, 2), padding='same')(x)
x = BatchNormalization()(x)
x = Activation(activation_type)(x)
# kernel size of 3 halfs the input dimensions
x = MaxPooling2D(pool_size=(3, 3), strides=1, padding='same')(x)
x = Dropout(dropout_factor)(x)
x = Convolution2D(int(128 * alpha), (3, 3), strides=(1, 1), padding='same')(x)
x = BatchNormalization()(x)
x = Activation(activation_type)(x)
x = Convolution2D(int(128 * alpha), (3, 3), strides=(2, 2), padding='same')(x)
x = BatchNormalization()(x)
x = Activation(activation_type)(x)
x = MaxPooling2D(pool_size=(3, 3), strides=1, padding='same')(x)
x = Dropout(dropout_factor)(x)
x = Convolution2D(int(256 * alpha), (3, 3), strides=(1, 1), padding='same')(x)
x = BatchNormalization()(x)
x = Activation(activation_type)(x)
x = Convolution2D(int(256 * alpha), (3, 3), strides=(2, 2), padding='same')(x)
x = BatchNormalization()(x)
x = Activation(activation_type)(x)
x = MaxPooling2D(pool_size=(3, 3), strides=1, padding='same')(x)
x = Dropout(dropout_factor)(x)
x = Convolution2D(int(512 * alpha), (3, 3), strides=(1, 1), padding='same')(x)
x = BatchNormalization()(x)
x = Activation(activation_type)(x)
x = Convolution2D(int(512 * alpha), (3, 3), strides=(2, 2), padding='same')(x)
x = BatchNormalization()(x)
x = Activation(activation_type)(x)
# basically flattens a dimension
x = GlobalMaxPooling2D()(x)
# maybe add another dense layer in between
out = Dense(1, activation='sigmoid')(x)
self.model = Model(model_input, out, name='cnn_dropout')
self.model.compile(loss='binary_crossentropy', optimizer='adam',
metrics=['accuracy'])
def load_model(self):
self.model.load_weights(self.checkpoint_path)
if __name__ == '__main__':
CNNPool()
|
[
"[email protected]"
] | |
6496d16a1187ee2afb1d4f13a192c17ebc29b49a
|
e71b6d14fbdbc57c7234ca45a47329d7d02fc6f7
|
/flask_api/venv/lib/python3.7/site-packages/vsts/work/v4_1/models/board_reference.py
|
6e58999b0b5322ab38b6dc0d498ad651c3982709
|
[] |
no_license
|
u-blavins/secret_sasquatch_society
|
c36993c738ab29a6a4879bfbeb78a5803f4f2a57
|
0214eadcdfa9b40254e331a6617c50b422212f4c
|
refs/heads/master
| 2020-08-14T00:39:52.948272 | 2020-01-22T13:54:58 | 2020-01-22T13:54:58 | 215,058,646 | 1 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 1,204 |
py
|
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
# Generated file, DO NOT EDIT
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------------------------
from msrest.serialization import Model
class BoardReference(Model):
"""BoardReference.
:param id: Id of the resource
:type id: str
:param name: Name of the resource
:type name: str
:param url: Full http link to the resource
:type url: str
"""
_attribute_map = {
'id': {'key': 'id', 'type': 'str'},
'name': {'key': 'name', 'type': 'str'},
'url': {'key': 'url', 'type': 'str'}
}
def __init__(self, id=None, name=None, url=None):
super(BoardReference, self).__init__()
self.id = id
self.name = name
self.url = url
|
[
"[email protected]"
] | |
e7bab45d83b2b3418bbf9dfb6ebb11ed89573d0a
|
13a32b92b1ba8ffb07e810dcc8ccdf1b8b1671ab
|
/home--tommy--mypy/mypy/lib/python2.7/site-packages/joblib/test/common.py
|
038ab537b9faa4cf059cd0c8b2edab674cdc1a7a
|
[
"Unlicense"
] |
permissive
|
tommybutler/mlearnpy2
|
8ec52bcd03208c9771d8d02ede8eaa91a95bda30
|
9e5d377d0242ac5eb1e82a357e6701095a8ca1ff
|
refs/heads/master
| 2022-10-24T23:30:18.705329 | 2022-10-17T15:41:37 | 2022-10-17T15:41:37 | 118,529,175 | 0 | 2 |
Unlicense
| 2022-10-15T23:32:18 | 2018-01-22T23:27:10 |
Python
|
UTF-8
|
Python
| false | false | 3,061 |
py
|
"""
Small utilities for testing.
"""
import threading
import signal
import time
import os
import sys
import gc
from joblib._multiprocessing_helpers import mp
from joblib.testing import SkipTest, skipif
# A decorator to run tests only when numpy is available
try:
import numpy as np
def with_numpy(func):
"""A decorator to skip tests requiring numpy."""
return func
except ImportError:
def with_numpy(func):
"""A decorator to skip tests requiring numpy."""
def my_func():
raise SkipTest('Test requires numpy')
return my_func
np = None
# TODO: Turn this back on after refactoring yield based tests in test_hashing
# with_numpy = skipif(not np, reason='Test requires numpy.')
# we use memory_profiler library for memory consumption checks
try:
from memory_profiler import memory_usage
def with_memory_profiler(func):
"""A decorator to skip tests requiring memory_profiler."""
return func
def memory_used(func, *args, **kwargs):
"""Compute memory usage when executing func."""
gc.collect()
mem_use = memory_usage((func, args, kwargs), interval=.001)
return max(mem_use) - min(mem_use)
except ImportError:
def with_memory_profiler(func):
"""A decorator to skip tests requiring memory_profiler."""
def dummy_func():
raise SkipTest('Test requires memory_profiler.')
return dummy_func
memory_usage = memory_used = None
# A utility to kill the test runner in case a multiprocessing assumption
# triggers an infinite wait on a pipe by the master process for one of its
# failed workers
_KILLER_THREADS = dict()
def setup_autokill(module_name, timeout=30):
"""Timeout based suiciding thread to kill the test runner process
If some subprocess dies in an unexpected way we don't want the
parent process to block indefinitely.
"""
if "NO_AUTOKILL" in os.environ or "--pdb" in sys.argv:
# Do not install the autokiller
return
# Renew any previous contract under that name by first cancelling the
# previous version (that should normally not happen in practice)
teardown_autokill(module_name)
def autokill():
pid = os.getpid()
print("Timeout exceeded: terminating stalled process: %d" % pid)
os.kill(pid, signal.SIGTERM)
# If were are still there ask the OS to kill ourself for real
time.sleep(0.5)
print("Timeout exceeded: killing stalled process: %d" % pid)
os.kill(pid, signal.SIGKILL)
_KILLER_THREADS[module_name] = t = threading.Timer(timeout, autokill)
t.start()
def teardown_autokill(module_name):
"""Cancel a previously started killer thread"""
killer = _KILLER_THREADS.get(module_name)
if killer is not None:
killer.cancel()
with_multiprocessing = skipif(
mp is None, reason='Needs multiprocessing to run.')
with_dev_shm = skipif(
not os.path.exists('/dev/shm'),
reason='This test requires the /dev/shm shared memory fs.')
|
[
"[email protected]"
] | |
dae634b72dac458cfa57d1bcb809f4d6d4bedf11
|
163bbb4e0920dedd5941e3edfb2d8706ba75627d
|
/Code/CodeRecords/2790/60730/256936.py
|
ed7cd9f25137e77fa2fe3809ef5f880ec7402267
|
[] |
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 | 450 |
py
|
num_m, num_n = map(int, input().split())
m = list(map(int, input().split()))
n = list(map(int, input().split()))
m.sort(reverse=False)
tmp = 0
for i in range(num_n):
for j in range(num_m):
if (m[j] <= n[i]):
tmp = tmp + 1
if (j == 4):
print(str(tmp))
tmp = 0;
else:
continue
else:
print(str(tmp))
tmp = 0
break
|
[
"[email protected]"
] | |
61786e2faf6ca3617cc2547869f76cce86441d76
|
b76c6813f2ce2fd24a33175a0249cd9544583fe7
|
/acerca_de/url_acerca_de.py
|
50417f63558bf4aa93ed35902ad121d612af8286
|
[] |
no_license
|
adrianglez2203/nuevo_as
|
0074e6d8155a471bb7d81bc3456914acdc7fba98
|
df375410e9d6922ebb931645ff8f1c7b3f5cb93b
|
refs/heads/master
| 2022-08-01T23:43:51.328124 | 2020-06-06T15:35:23 | 2020-06-06T15:35:23 | 270,111,577 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 133 |
py
|
from django.urls import path
from acerca_de import views
urlpatterns = [
path('acerca',views.vista , name='acerca_de'),
]
|
[
"[email protected]"
] | |
ba8c22cf3cea258a5f767182a5ff8dbf68b2b507
|
16b26e6a9e6d6a7db2a20a6327b3d042e2245747
|
/bigramas/bigramas.py
|
dbef177920a9911443ced6ff74a1eed9c8710e79
|
[
"Unlicense"
] |
permissive
|
jabaier/iic1103.20152.s4
|
3826b8de35470acc0387c8199b6ecce50d4222bd
|
63ddd5f9b73caff218b6744e7392e7a66afba570
|
refs/heads/master
| 2020-05-27T16:59:32.232746 | 2015-11-20T14:34:21 | 2015-11-20T14:34:21 | 41,114,018 | 0 | 1 | null | null | null | null |
UTF-8
|
Python
| false | false | 2,540 |
py
|
import sys
import random
class Bigramas:
def __init__(self):
self.bigramas=[] # lista de bigramas
self.nbigramas=0 # numero de bigramas
def buscar(self,palabra):
for par in self.bigramas:
if par[0]==palabra:
return par[1]
# la palabra no está
self.bigramas.append([palabra,[]])
return self.bigramas[len(self.bigramas)-1][1]
def incrementar(self,lista,palabra):
i=0
while i < len(lista):
if lista[i][0]==palabra:
lista[i][1] = lista[i][1] + 1
return
i+=1
lista.append([palabra,1])
self.nbigramas=self.nbigramas+1
if self.nbigramas%1000==0:
print(".",end="")
sys.stdout.flush()
def agregar(self,pal1,pal2):
lista=self.buscar(pal1)
self.incrementar(lista,pal2)
def caminata(self,palabra,limite):
def sumalista(lista):
suma=0
for elem in lista:
suma+=elem[1]
return suma
contador=0
lista_palabras=[]
while contador < limite:
lista_palabras.append(palabra)
lista=self.buscar(palabra)
if len(lista)>0:
total=sumalista(lista)
rand=random.randint(0,total)
acc=0
i=0
while acc + lista[i][1] < rand and i < len(lista):
acc = acc + lista[i][1]
i = i + 1
palabra=lista[i][0]
else:
palabra=palabras[random.randint(0,len(self.palabras)-1)]
contador = contador + 1
return lista_palabras
def limpiar(palabra):
puntuacion=".,!:;?»«-¿¡"
respuesta=""
for c in palabra:
if not c in puntuacion:
respuesta += c
return respuesta
filename = input("Archivo con datos: ")
f = open(filename,'r')
print("Leyendo los datos")
entrada=''
for linea in f:
linea.rstrip()
entrada += linea
import time
tic1=time.time()
print("Datos leidos. Procesando.",end="")
f.close()
palabras = [limpiar(x.lower()) for x in entrada.split() if x!=""]
b=Bigramas()
i=0
while i < len(palabras)-1:
b.agregar(palabras[i],palabras[i+1])
i+=1
tic2=time.time()
print("\nDatos procesados en ",round(tic2-tic1,2),"seg.")
print("Base de datos tiene",len(b.bigramas),"palabras y",b.nbigramas,"bigramas.")
print(b.bigramas)
while True:
p = input("palabra: ")
print(b.caminata(p,20))
|
[
"[email protected]"
] | |
11f4ba38d434e1643f04aaf34ec8646b27782520
|
7e0fdfb76cae8145a4bbac0cac0e4cac6b8e3788
|
/dingding_shouqi/dingding_shouqi.py
|
daaee3a0bc4aec488160ca6adf2ad171e17d3204
|
[] |
no_license
|
w193241125/dingdingdaka
|
603b06323b5c5e3341e0077614e044b2c80c038b
|
3d2088d2e876fc4e80fc06bea3eaa5b8833392ed
|
refs/heads/master
| 2020-05-17T21:45:44.276659 | 2019-05-13T10:16:29 | 2019-05-13T10:16:29 | 183,981,037 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 8,007 |
py
|
#!/usr/local/bin python
# -*- coding: utf-8 -*-
# @Time : 2019/3/5 10:38
# @Author : Larwas
# @Link : [email protected]
# @Site : www.larwas.com
# @File : dingding.py
# @Software: PyCharm
import os
import re
import time
import urllib
import json
import requests
# nameplt = re.compile("package: name='(.*?)' versionCode")
# activityplt = re.compile("launchable-activity: name='(.*?)'")
adbshell = "adb shell" # 启用shell命令可以直接操作Android系统
# adbstr = "adb push D:/1.txt /mnt/txt/1.txt" # 把电脑的文件推送到安卓
# adbpng1 = "adb pull /sdcard/screencap.png d://"
# adbpng2 = "adb pull /sdcard/screencap.png d://1.png"
# adb_use_screencap = "adb shell /system/bin/screencap -p /sdcard/667.png" # 截取安卓的屏幕
# adbpng3 = "adb pull /sdcard/667.png d://3.png" # 把安卓的截图导入到电脑
# get_app_info = "adb shell pm list packages" # 获取模拟器所有包名
tap_place_index = "adb shell input tap 78 1219"
tap_place = "adb shell input tap 363 1219"
tap_place_kaoqin = "adb shell input tap 272 724"
tap_place_kaoqin2 = "adb shell input tap 268 1051"
tap_place_daka = "adb shell input tap 185 1234"
tap_place_shangban = "adb shell input tap 353 499"
tap_place_xiaban = "adb shell input tap 353 756"
wake_up = "adb shell input keyevent 26"
unlock = "adb shell input swipe 370 952 370 318"
wrap_a = "adb shell input swipe 370 318 370 952"
shut_up = "adb shell input tap 654 594" # 收起
return_a = "adb shell input tap 52 101"
return_b = "adb shell input tap 156 101"
return_ding_index = "adb shell input tap 75 1224"
return_index = "adb shell input keyevent 3"
turnback = "adb shell input keyevent 4"
donyin_package_name = "com.alibaba.android.rimet"
douyin_activity_name = "com.alibaba.android.rimet.biz.SplashActivity"
power_stat = "adb shell dumpsys window policy"
kill_dingding = "adb shell am force-stop com.alibaba.android.rimet"
# 获取抖音app的com信息
# get_com_info = r"aapt dump badging G:\python\dingding\rimet.apk > dingding.txt"
# os.system(get_com_info)
# with open("dingding.txt", "r", encoding="utf-8") as fs:
# donyin = fs.read()
#
# donyin_package_name = nameplt.findall(donyin)[0]
# douyin_activity_name = activityplt.findall(donyin)[0]
#
# print("钉钉activity", douyin_activity_name)
# print("钉钉的包名", donyin_package_name)
# os.system(adb_use_screencap)
# #print(os.system(adbpng3))
start_app = f"adb shell am start -n {donyin_package_name}/{douyin_activity_name}"
start_airdroid = f"adb shell am start -n com.sand.airdroid/com.sand.airdroid.ui.splash.SplashActivity_"
# 获取当前周数
current_week = time.strftime("%W")
# 取余 当前1为双休0为单休
mod = int(current_week) % 2
# 获取今天周几
current_weekday = time.strftime("%w", time.localtime())
# 获取当前时间
current_time = time.strftime('%H:%M', time.localtime(time.time()))
def isAwaked(deviceid = ''):
'''
判断的依据是' mAwake=false\n'
'''
if deviceid == '':
cmd = 'adb shell dumpsys window policy'
else:
cmd = 'adb -s ' + deviceid + ' shell dumpsys window policy'
screenAwakevalue = ' mScreenOnEarly=true mScreenOnFully=true mOrientationSensorEnabled=false\n'
allList = os.popen(cmd).readlines()
if screenAwakevalue in allList:
return True
else:
return False
def isLock(deviceid = ''):
'''
判断的依据是' mAwake=false\n'
'''
if deviceid == '':
cmd = 'adb shell dumpsys window policy'
else:
cmd = 'adb -s ' + deviceid + ' shell dumpsys window policy'
screenAwakevalue = ' mShowingLockscreen=true mShowingDream=false mDreamingLockscreen=true\n'
allList = os.popen(cmd).readlines()
if screenAwakevalue in allList:
return True # 锁着
else:
return False # 没锁
def sign():
start_app = f"adb shell am start -n {donyin_package_name}/{douyin_activity_name}"
if isAwaked():
if isLock():
print('unlock')
os.system(unlock)
else:
pass
else:
# 唤醒屏幕并解锁
print('wake up and unlock')
os.system(wake_up)
time.sleep(1)
os.system(unlock)
print("启动dd")
os.system(start_app)
time.sleep(20)
if isAwaked():
if isLock():
os.system(unlock)
else:
pass
else:
# 唤醒屏幕并解锁
os.system(wake_up)
time.sleep(1)
os.system(unlock)
# 操作钉钉
os.system(tap_place_index)
time.sleep(2)
os.system(tap_place)
# 下滑一下 保证位置
os.system(wrap_a)
# 收起
time.sleep(4)
print('收起')
os.system(shut_up)
time.sleep(3)
print('点击考勤')
os.system(tap_place_kaoqin2)
# os.system(tap_place_kaoqin)
# time.sleep(6)
# os.system(tap_place_daka)
time.sleep(10)
if current_time <= "10:30":
os.system(tap_place_shangban)
print(1)
time.sleep(5)
# 打卡完 返回
os.system(turnback)
else:
if current_time < "20:00":
os.system(tap_place_xiaban)
print("下班")
else:
os.system(tap_place_xiaban)
print("点击一次下班保证打了卡")
time.sleep(3)
tap_place_gengxin = "adb shell input tap 115 713"
tap_place_gengxin_queren = "adb shell input tap 569 713"
os.system(tap_place_gengxin)
print("更新")
time.sleep(3)
os.system(tap_place_gengxin_queren)
time.sleep(5)
# 打卡完 返回
os.system(turnback)
# 退出
os.system(return_a)
os.system(return_b)
os.system(return_ding_index)
os.system(return_index)
# 获取当前时间 格式20180213
nowTime = time.strftime('%Y%m%d', time.localtime())
date = nowTime
# print(date)
# 节假日接口
server_url = "http://api.goseek.cn/Tools/holiday?date="
vop_url_request = requests.get(server_url + date)
vop_response = vop_url_request.text
vop_data = json.loads(vop_response)
print(vop_data)
# 获取节假日结束
if vop_data['data'] == 1:
pass # 法定节假日跳过
else:
print('不是法定节假日')
if isAwaked():
if isLock():
print('unlock')
os.system(unlock)
else:
print('屏幕没锁')
pass
else:
# 唤醒屏幕并解锁
print('wake up and unlock2')
# 唤醒屏幕并解锁
os.system(wake_up)
time.sleep(1)
os.system(unlock)
time.sleep(1)
os.system(return_index)
# 双休打卡
if mod == 1 and int(current_weekday) in [1, 2, 3, 4, 5]:
if int(current_weekday) == 5 and current_time < "20:30" and current_time > "10:30":
sign() # 打卡
elif int(current_weekday) in [1, 2, 3, 4] and current_time > "20:30":
sign() # 打卡
elif int(current_weekday) in [1, 2, 3, 4, 5] and current_time < "10:30":
sign()
else:
if current_time > "18:00":
sign()
else:
print('不是周末,打卡太早1') # 跳过
# 单休打卡
elif mod == 0 and int(current_weekday) in [1, 2, 3, 4, 5, 6]:
if int(current_weekday) == 6 and current_time < "20:30" and current_time > "10:30":
sign() # 打下班卡
elif int(current_weekday) in [1, 2, 3, 4, 5] and current_time > "20:30":
sign() # 打下班卡
elif int(current_weekday) in [1, 2, 3, 4, 5,6] and current_time < "10:30":
sign() # 打上班卡
else:
if current_time > "18:00":
sign()
else:
print('不是周末,打卡太早_单休') # 跳过
else:
print('未知原因取消打卡') # 跳过
os.system(kill_dingding)
os.system(start_airdroid)
time.sleep(3)
os.system(wake_up)
time.sleep(3)
exit()
|
[
"[email protected]"
] | |
16d7d093326b863bf363be47886a033059a9f1f4
|
96f181736c9975adfabd45cc776cab7a37d2e7a1
|
/transformer/SubLayers.py
|
636b67878e40d8e50b27f1d0f49b7d9bf2797668
|
[
"MIT"
] |
permissive
|
fangxiaoquan/transformer-pytorch
|
6b43fb75635bb512c38c6f2ac8ec306b6e6ba5d9
|
c9c5c81151c37ad7a088ea96aa5248fd4f4ad2d1
|
refs/heads/master
| 2020-05-17T00:36:59.073875 | 2019-03-17T14:42:02 | 2019-03-17T14:42:02 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 2,844 |
py
|
''' Define the sublayers in encoder/decoder layer '''
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
from transformer.Modules import ScaledDotProductAttention
class MultiHeadAttention(nn.Module):
''' Multi-Head Attention module '''
def __init__(self, n_head, d_model, d_k, d_v, dropout=0.1):
super().__init__()
self.n_head = n_head
self.d_k = d_k
self.d_v = d_v
self.w_qs = nn.Linear(d_model, n_head * d_k)
self.w_ks = nn.Linear(d_model, n_head * d_k)
self.w_vs = nn.Linear(d_model, n_head * d_v)
nn.init.normal_(self.w_qs.weight, mean=0, std=np.sqrt(2.0 / (d_model + d_k)))
nn.init.normal_(self.w_ks.weight, mean=0, std=np.sqrt(2.0 / (d_model + d_k)))
nn.init.normal_(self.w_vs.weight, mean=0, std=np.sqrt(2.0 / (d_model + d_v)))
self.attention = ScaledDotProductAttention(temperature=np.power(d_k, 0.5))
self.layer_norm = nn.LayerNorm(d_model)
self.fc = nn.Linear(n_head * d_v, d_model)
nn.init.xavier_normal_(self.fc.weight)
self.dropout = nn.Dropout(dropout)
def forward(self, q, k, v, mask=None):
d_k, d_v, n_head = self.d_k, self.d_v, self.n_head
sz_b, len_q, _ = q.size()
sz_b, len_k, _ = k.size()
sz_b, len_v, _ = v.size()
residual = q
q = self.w_qs(q).view(sz_b, len_q, n_head, d_k)
k = self.w_ks(k).view(sz_b, len_k, n_head, d_k)
v = self.w_vs(v).view(sz_b, len_v, n_head, d_v)
q = q.permute(2, 0, 1, 3).contiguous().view(-1, len_q, d_k) # (n*b) x lq x dk
k = k.permute(2, 0, 1, 3).contiguous().view(-1, len_k, d_k) # (n*b) x lk x dk
v = v.permute(2, 0, 1, 3).contiguous().view(-1, len_v, d_v) # (n*b) x lv x dv
mask = mask.repeat(n_head, 1, 1) # (n*b) x .. x ..
output, attn = self.attention(q, k, v, mask=mask)
output = output.view(n_head, sz_b, len_q, d_v)
output = output.permute(1, 2, 0, 3).contiguous().view(sz_b, len_q, -1) # b x lq x (n*dv)
output = self.dropout(self.fc(output))
output = self.layer_norm(output + residual)
return output, attn
class PositionwiseFeedForward(nn.Module):
''' A two-feed-forward-layer module '''
def __init__(self, d_in, d_hid, dropout=0.1):
super().__init__()
self.w_1 = nn.Conv1d(d_in, d_hid, 1) # position-wise
self.w_2 = nn.Conv1d(d_hid, d_in, 1) # position-wise
self.layer_norm = nn.LayerNorm(d_in)
self.dropout = nn.Dropout(dropout)
def forward(self, x):
residual = x
output = x.transpose(1, 2)
output = self.w_2(F.relu(self.w_1(output)))
output = output.transpose(1, 2)
output = self.dropout(output)
output = self.layer_norm(output + residual)
return output
|
[
"[email protected]"
] | |
214e9acf4f63476ff161a03f36b9d65e5158d29c
|
e8c5d8a473a71f88616b692dcdfd2d604485f580
|
/test_corrector.py
|
1db70ec4aff76eef61b92ad17796f78834360551
|
[
"Apache-2.0"
] |
permissive
|
modernYan/corrector
|
a6907bf1dc0e5e91048704365b4ade7327939592
|
75c86075ea51a53ebe6d649d729e690e3b414f7a
|
refs/heads/master
| 2021-04-03T01:51:33.407724 | 2018-03-07T12:49:45 | 2018-03-07T12:49:45 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 1,148 |
py
|
# -*- coding: utf-8 -*-
# Author: XuMing <[email protected]>
# Brief:
import unittest
from pycorrector.cn_spell import correct
class BasicTestSuite(unittest.TestCase):
"""Basic test cases."""
@staticmethod
def test_text1():
error_sentence_1 = '机七学习是人工智能领遇最能体现智能的一个分知'
correct_sent = correct(error_sentence_1)
print("original sentence:{} => correct sentence:{}".format(error_sentence_1, correct_sent))
@staticmethod
def test_text2():
error_sentence_2 = '杭洲是中国的八大古都之一,因风景锈丽,享有“人间天棠”的美誉!'
correct_sent = correct(error_sentence_2)
print("original sentence:{} => correct sentence:{}".format(error_sentence_2, correct_sent))
@staticmethod
def test_text3():
error_sentence_3 = '我们现今所"使用"的大部分舒学符号,你们用的什么婊点符号'
correct_sent = correct(error_sentence_3)
print("original sentence:{} => correct sentence:{}".format(error_sentence_3, correct_sent))
if __name__ == '__main__':
unittest.main()
|
[
"[email protected]"
] | |
e0409dc7eb85b5766250889ef408b577012505a7
|
8338bde799fab50fa28b3c9e85035fce12f1e152
|
/src/crystal_analysis/fluctuations.py
|
a31246b51e26e6bab8b8c6c145aa242d5bfe1576
|
[
"MIT"
] |
permissive
|
malramsay64/Crystal_Melting
|
c5941ad261ef71f1357d6064302344b093b22b53
|
e8305928b06b536d7293cb751963d058d55627aa
|
refs/heads/master
| 2021-03-24T10:24:23.291821 | 2020-08-07T07:19:09 | 2020-08-07T07:19:09 | 119,946,491 | 0 | 0 |
MIT
| 2020-02-12T07:35:47 | 2018-02-02T07:13:03 |
Python
|
UTF-8
|
Python
| false | false | 8,047 |
py
|
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2019 Malcolm Ramsay <[email protected]>
#
# Distributed under terms of the MIT license.
"""A module to measure the structural fluctuations of each state.
The concept of this module is to understand how much particles within each state are
moving, to get an idea of the likelihood of transitioning from one state to anther.
States which are highly constrained will allow small amounts of motion, while states
which are more flexible will be able to rapidly change configuration.
"""
import logging
from pathlib import Path
from typing import Tuple
import click
import numpy as np
import pandas as pd
import scipy.optimize
from pandas.api.types import CategoricalDtype
from sdanalysis import order
from sdanalysis.read import open_trajectory
from sdanalysis.util import get_filename_vars
logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
@click.group()
def main():
pass
BINS = np.linspace(-1, 1, 5001)
BIN_VALUES = (BINS[1:] + BINS[:-1]) / 2
def aggregate(values: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:
"""Convert values to a histogram of bins and values
This takes a collection of values in the range [0,1], binning values into a
histogram. Values are binned in increments of 1a-4, with only the bins containing values being returned.
Args:
values: A collection of values which will be binned into
Returns:
centers: The centers of each of the bins
counts: The count of each bin
"""
hist = np.histogram(values, bins=BINS, density=True)[0]
non_zero = np.nonzero(hist)
return BIN_VALUES[non_zero], hist[non_zero]
def gaussian(x, A, mu, sigma):
return A * np.exp(-np.square(x - mu) / (2 * np.square(sigma)))
def fit_gaussian(bins: np.ndarray, count: np.ndarray):
# Initial guess at parameter values
p0 = (1.0, 0.0, 1.0)
coeffs, _ = scipy.optimize.curve_fit(gaussian, bins, count, p0=p0, maxfev=2000)
return coeffs
@main.command()
@click.argument("output", type=click.Path(file_okay=True, dir_okay=False))
@click.argument(
"infiles", nargs=-1, type=click.Path(exists=True, file_okay=True, dir_okay=False)
)
def collate_disc(output, infiles):
with pd.HDFStore(output) as dst:
for file in infiles:
file = Path(file)
print(file)
df = pd.read_csv(file)
fvars = get_filename_vars(file)
df["temperature"] = float(fvars.temperature)
df["pressure"] = float(fvars.pressure)
if fvars.crystal is None:
crystal = "liquid"
else:
crystal = fvars.crystal
df["crystal"] = crystal
bin_values, count = aggregate(df["hexatic_order"])
df = pd.DataFrame(
{
"temperature": float(df["temperature"].values[0]),
"pressure": float(df["pressure"].values[0]),
"crystal": df["crystal"].values[0],
"bins": bin_values,
"count": count,
"probability": count * (BINS[1] - BINS[0]),
}
)
df["crystal"] = df["crystal"].astype(
CategoricalDtype(
categories=["SquareCircle", "HexagonalCircle", "liquid"]
)
)
dst.append("ordering", df)
@main.command()
@click.argument("output", type=click.Path(file_okay=True, dir_okay=False))
@click.argument(
"infiles", nargs=-1, type=click.Path(exists=True, file_okay=True, dir_okay=False)
)
def collate(output, infiles):
with pd.HDFStore(output) as dst:
for file in infiles:
file = Path(file)
print(file)
if file.suffix == ".h5":
with pd.HDFStore(file) as src:
df = src.get("ordering")
elif file.suffix == ".csv":
df = pd.read_csv(file)
df = df.rename(columns={"orient_order": "orientational_order"})
fvars = get_filename_vars(file)
df["temperature"] = float(fvars.temperature)
df["pressure"] = float(fvars.pressure)
if fvars.crystal is None:
crystal = "liquid"
else:
crystal = fvars.crystal
df["crystal"] = crystal
else:
raise ValueError("Filetype is not supported")
bin_values, count = aggregate(df["orientational_order"])
df = pd.DataFrame(
{
"temperature": float(df["temperature"].values[0]),
"pressure": float(df["pressure"].values[0]),
"crystal": df["crystal"].values[0],
"bins": bin_values,
"count": count,
"probability": count * (BINS[1] - BINS[0]),
}
)
df["crystal"] = df["crystal"].astype(
CategoricalDtype(categories=["p2", "p2gg", "pg", "liquid"])
)
dst.append("ordering", df)
@main.command()
@click.argument("infile", type=click.Path(exists=True, file_okay=True, dir_okay=False))
@click.argument("outfile", type=click.Path(file_okay=True, dir_okay=False))
def analyse(infile, outfile):
dataframes = []
file_vars = get_filename_vars(infile)
crystal = file_vars.crystal
if crystal is None:
crystal = "liquid"
for snap in open_trajectory(infile, progressbar=True):
orientational_order = order.orientational_order(
snap.box, snap.position, snap.orientation
)
df = pd.DataFrame(
{
"molecule": np.arange(snap.num_mols),
"orientational_order": orientational_order,
"temperature": float(file_vars.temperature),
"pressure": float(file_vars.pressure),
"crystal": crystal,
}
)
df["crystal"] = df["crystal"].astype("category")
dataframes.append(df)
with pd.HDFStore(outfile) as dst:
dst.append("ordering", pd.concat(dataframes))
@main.command()
@click.argument("outfile", type=click.Path(file_okay=True, dir_okay=False))
@click.argument(
"infiles", nargs=-1, type=click.Path(exists=True, file_okay=True, dir_okay=False)
)
def thermodynamics(outfile, infiles):
dfs = []
for filename in infiles:
fvars = get_filename_vars(filename)
df = pd.read_csv(filename, sep="\t")
# All the values are written to the same output file, so make sure there is only
# a single trajectory worth of values.
df = df.drop_duplicates("timestep", keep="last")
# We want quantities for each
df = df.div(df.N, axis=0)
# Take the second half of the values to ensure there is no issue with
# equilibration
df = df.iloc[len(df) // 2 :, :]
# Calculate Total Energy
df["total_energy"] = df["kinetic_energy"] + df["potential_energy"]
# Calculate enthalpy.
# This is the total energy (potential + kinetic) + the configuration energy (pV)
# The multiplication by N is because the pressure was also divided by N above.
df["enthalpy"] = (
df["potential_energy"]
+ df["kinetic_energy"]
+ df["pressure"] * df["volume"] * df.N
)
if fvars.crystal is not None:
df["crystal"] = fvars.crystal
else:
df["crystal"] = "liquid"
df["pressure"] = float(fvars.pressure)
df["temperature"] = float(fvars.temperature)
df = df.set_index(["pressure", "temperature", "crystal"])
# Perform aggregations on the dataframe, making it much easier to work with.
df = df.groupby(["pressure", "temperature", "crystal"]).agg(["mean", "std"])
dfs.append(df)
pd.concat(dfs).to_hdf(outfile, "thermo")
if __name__ == "__main__":
main()
|
[
"[email protected]"
] | |
4c2de55d37b6463dc9cb09e1b3fab791b94fb59f
|
1842d2e7989b9fb1bdd6edff2b2ce187ca9f27ad
|
/BIOMD0000000484/model.py
|
9d53fe8ba1862ad4b82c03c37bafa36698e3a221
|
[
"CC0-1.0"
] |
permissive
|
biomodels/BIOMD0000000484
|
cc08199b3d324bf10425829755d70e67d52b155d
|
293ac221c1615e7446f55960cff130f784243220
|
refs/heads/master
| 2016-09-06T17:32:40.282597 | 2014-10-16T05:17:52 | 2014-10-16T05:17:52 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 427 |
py
|
import os
path = os.path.dirname(os.path.realpath(__file__))
sbmlFilePath = os.path.join(path, 'BIOMD0000000484.xml')
with open(sbmlFilePath,'r') as f:
sbmlString = f.read()
def module_exists(module_name):
try:
__import__(module_name)
except ImportError:
return False
else:
return True
if module_exists('libsbml'):
import libsbml
sbml = libsbml.readSBMLFromString(sbmlString)
|
[
"[email protected]"
] | |
563a9e4d56769ebc277637da90f87d84e0eb46b2
|
16dcbf88ae9514109151fe5ff447b2b653ddf48b
|
/2016/035-TheasGame/thea.py
|
60cf62e1e123e8f303f839ac3e8286c58ec426a6
|
[] |
no_license
|
ChristerNilsson/Lab
|
efa55ef5e79dff84b232dfcf94473eacdb263175
|
b1f730f45ec6e901bd14c1e4196aa5e0f591ecd2
|
refs/heads/master
| 2023-07-06T04:35:09.458936 | 2023-06-24T21:40:54 | 2023-06-24T21:40:54 | 48,474,249 | 8 | 8 | null | 2022-12-10T07:03:31 | 2015-12-23T06:51:11 |
JavaScript
|
UTF-8
|
Python
| false | false | 690 |
py
|
import pygame
pygame.init()
windowSurface = pygame.display.set_mode((1000, 750), pygame.DOUBLEBUF)
done = False
while not done:
# --- Main event loop
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
s = pygame.Surface((1000,750), pygame.SRCALPHA) # per-pixel alpha
s.fill((255,255,255,128)) # notice the alpha value in the color
pygame.draw.circle(s, pygame.Color(255, 0, 0, 128), (100, 100), 100)
pygame.draw.circle(windowSurface, pygame.Color(0, 255, 0, 128), (150, 100), 100)
windowSurface.blit(s, (0,0), pygame.BLEND_RGBA_ADD)
s.fill((255,255,255))
pygame.display.flip()
|
[
"[email protected]"
] | |
96e362619f5e1ca63b616907a81a83d7ad5268b9
|
7a17f9e6706b6e3f6d55c8e30f0dcec97f495541
|
/src/hyperka/hyperbolic/manifold.py
|
e5bfa0abf060d8a9093cb836b10fa666c81e5cfe
|
[
"MIT"
] |
permissive
|
HELL-TO-HEAVEN/HyperKA
|
8d097c58e0188961de6e4ea74f214e40d9408a04
|
cadaf824a739b55211997e73d9948ddbfbe7ce83
|
refs/heads/main
| 2023-03-30T04:20:31.477323 | 2021-03-25T07:56:55 | 2021-03-25T07:56:55 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 713 |
py
|
from abc import abstractmethod
from abc import ABC
class Manifold(ABC):
def __init__(self, *args, **kwargs):
pass
@property
def name(self):
raise NotImplementedError
@staticmethod
def dim(dim):
return dim
def normalize(self, u):
return u
@abstractmethod
def distance(self, u, v):
"""
Distance function
"""
raise NotImplementedError
@abstractmethod
def expm(self, p, d_p, lr=None, out=None):
"""
Exponential map
"""
raise NotImplementedError
@abstractmethod
def logm(self, x, y):
"""
Logarithmic map
"""
raise NotImplementedError
|
[
"[email protected]"
] | |
4233d111f76ceabf87cbb1c1701d766aeaf5393b
|
17e813f4f20a6ce2d82619be9fac517b5176a74b
|
/Trees/btToLinkedList.py
|
84dacb4426c7a87aa171291005e233ea32317e16
|
[] |
no_license
|
AryanGanotra07/DSALGO
|
0ee86bbca4b345d21f5d6eb60d96c7aff6f1fc93
|
8cbac991ceec43522a57c65d68f00b54ccb6ea3f
|
refs/heads/master
| 2022-12-08T22:33:14.031636 | 2020-09-13T14:05:41 | 2020-09-13T14:05:41 | 283,800,432 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 1,052 |
py
|
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
import sys
sys.setrecursionlimit(15000000)
def solve(a, b):
if a is None:
return
b.append(a.val)
solve(a.left, b)
solve(a.right, b)
def solve(a):
if a is None or (a.left is None and a.right is None):
return None
if a.left is not None:
solve(a.left)
tmp = a.right
a.right = a.left
a.left = None
b = a.right
while b.right is not None:
b= b.right
b.right = tmp
solve(a.right)
class Solution:
# @param A : root node of tree
# @return the root node in the tree
def flatten(self, A):
solve(A)
return A
# b = []
# solve(A, b)
# r = TreeNode(b[0])
# n = r
# for i in range(1, len(b)):
# n.right = TreeNode(b[i])
# n = n.right
# return r
|
[
"[email protected]"
] | |
ee8f01d9ff709d7f69ae6cebd6b938844bdd5ee8
|
ca7aa979e7059467e158830b76673f5b77a0f5a3
|
/Python_codes/p03290/s821428254.py
|
d06c09c404c991b8d3ef901f9f4a5f494259ea0e
|
[] |
no_license
|
Aasthaengg/IBMdataset
|
7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901
|
f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8
|
refs/heads/main
| 2023-04-22T10:22:44.763102 | 2021-05-13T17:27:22 | 2021-05-13T17:27:22 | 367,112,348 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 608 |
py
|
from math import ceil
from itertools import product
D,G=map(int,input().split())
pc=[list(map(int,input().split())) for _ in range(D)]
def calc(P):
count = 0
g = G
for i in range(D):
p,c = pc[-1-i]
if P[-1-i]==1:
count += p
g -= (D-i)*100*p+c
if g<=0:
return count
for i in range(D):
p,c = pc[-1-i]
if P[-1-i]==0:
tmp = min(p-1,ceil(g/((D-i)*100)))
count += tmp
g -= (D-i)*100*tmp
if g<=0:
return count
return -1
MIN=10**9
for P in product(range(2),repeat=D):
tmp = calc(P)
if tmp != -1 and tmp < MIN: MIN=tmp
print(MIN)
|
[
"[email protected]"
] | |
bcf4f86043750b69eed83dad9603a1d113b66fb7
|
a176f3705c92ec1974ada17af2a891e0bf763b97
|
/core/get_input.py
|
21fcd1c9c836417783cbba4c9450586ea9653811
|
[
"Apache-2.0"
] |
permissive
|
indrajithbandara/OWASP-Nettacker
|
593bdf5426606e67a94e447b4a9534bf79b0396b
|
087ce32f06758db03039a34e6e32fbc57fb4ffef
|
refs/heads/master
| 2021-05-08T14:22:54.520184 | 2018-01-27T20:34:59 | 2018-01-27T20:34:59 | 120,082,592 | 1 | 0 | null | 2018-02-03T10:49:34 | 2018-02-03T10:49:33 | null |
UTF-8
|
Python
| false | false | 514 |
py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from core.compatible import version
from core.alert import __input_msg
def __input(msg, default):
if version() is 2:
try:
data = raw_input(__input_msg(msg))
if data == '':
data = default
except:
data = default
else:
try:
data = input(__input_msg(msg))
if data == '':
data = default
except:
data = default
return data
|
[
"[email protected]"
] | |
ec0fe22ab52822601adcf965f531dec7895c63aa
|
66fb5bbf3cd0f2c7b00db7081271c376812b68dd
|
/control_planner/scripts/purepursuit.py
|
c4385ac0777d26b0a19d879eb7b8d5ef81f9ef78
|
[] |
no_license
|
freesloth/wecar_2
|
d5e95ae67d65bcd78a60ceae95a48161656e4fab
|
c05888cc70ddd775a3151b722db06aa41705f6b9
|
refs/heads/master
| 2023-01-22T15:47:39.505150 | 2020-12-10T03:29:36 | 2020-12-10T03:29:36 | 278,523,277 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 4,179 |
py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import rospy
import rospkg
from sensor_msgs.msg import LaserScan,PointCloud,Imu
from std_msgs.msg import Float64
from vesc_msgs.msg import VescStateStamped
from laser_geometry import LaserProjection
from math import cos,sin,pi,sqrt,pow,atan2
from geometry_msgs.msg import Point32,PoseStamped, Point32,PoseStamped,Point, PoseWithCovarianceStamped
from nav_msgs.msg import Odometry,Path
import tf
from tf.transformations import euler_from_quaternion,quaternion_from_euler
class pure_pursuit:
def __init__(self):
rospy.init_node("make_path", anonymous=True)
rospy.Subscriber("path", Path, self.path_callback)
rospy.Subscriber("odom",Odometry, self.odom_callback)
# rospy.Subscriber("/amcl_pose",PoseWithCovarianceStamped, self.amcl_callback)
self.motor_pub=rospy.Publisher('commands/motor/speed',Float64,queue_size=1)
self.servo_pub=rospy.Publisher('commands/servo/position',Float64,queue_size=1)
self.motor_msg=Float64()
self.servo_msg=Float64()
self.is_path=False
self.is_odom=False
self.is_amcl=False
self.forward_point=Point()
self.current_position=Point()
self.is_look_forward_point=False
self.vehicle_length=0.5
self.lfd=0.5
self.steering=0
self.steering_angle_to_servo_gain=-1.2135
self.steering_angle_to_servo_offset=0.5304
rate=rospy.Rate(30)
while not rospy.is_shutdown():
if self.is_path==True and(self.is_odom==True or self.is_amcl==True):
vehicle_position=self.current_position
rotated_point=Point()
self.is_look_forward_point=False
for num,i in enumerate(self.path.poses):
path_point=i.pose.position
dx=path_point.x-vehicle_position.x
dy=path_point.y-vehicle_position.y
rotated_point.x=cos(self.vehicle_yaw)*dx+sin(self.vehicle_yaw)*dy
rotated_point.y=sin(self.vehicle_yaw)*dx-cos(self.vehicle_yaw)*dy
if rotated_point.x>0:
dis=sqrt(pow(rotated_point.x,2)+pow(rotated_point.y,2))
if dis>=self.lfd:
self.forward_point=path_point
self.is_look_forward_point=True
break
theta=-atan2(rotated_point.y,rotated_point.x)
if self.is_look_forward_point:
self.steering=atan2((2*self.vehicle_length*sin(theta)),self.lfd) #rad
print(self.steering*180/pi)
self.motor_msg.data=2000
else:
self.steering=0
print("no found forward point")
self.motor_msg.data=0
self.steering_command=(self.steering_angle_to_servo_gain*self.steering)+self.steering_angle_to_servo_offset
self.servo_msg.data=self.steering_command
self.servo_pub.publish(self.servo_msg)
self.motor_pub.publish(self.motor_msg)
rate.sleep()
def path_callback(self,msg):
self.is_path=True
self.path=msg
def odom_callback(self,msg):
self.is_odom=True
odom_quaternion=(msg.pose.pose.orientation.x,msg.pose.pose.orientation.y,msg.pose.pose.orientation.z,msg.pose.pose.orientation.w)
_,_,self.vehicle_yaw=euler_from_quaternion(odom_quaternion)
self.current_position.x=msg.pose.pose.position.x
self.current_position.y=msg.pose.pose.position.y
def amcl_callback(self,msg):
self.is_amcl=True
amcl_quaternion=(msg.pose.pose.orientation.x,msg.pose.pose.orientation.y,msg.pose.pose.orientation.z,msg.pose.pose.orientation.w)
_,_,self.vehicle_yaw=euler_from_quaternion(amcl_quaternion)
self.current_position.x=msg.pose.pose.position.x
self.current_position.y=msg.pose.pose.position.y
if __name__ == '__main__':
try:
test_track=pure_pursuit()
except rospy.ROSInterruptException:
pass
|
[
"[email protected]"
] | |
a8d0358b14e0899a93fda27fcd872490e907be31
|
5c0a253bf2fb83db01abc99097871c965f4cf565
|
/study/machinelearning/clustering/flat/KMeans/kMeansWithScratch.py
|
6e509df62cf33b8d8436cb1ad679ecef276bd6d5
|
[] |
no_license
|
airuibel/python-1
|
3b16553ede9d069ec56efbb12a89a4de6917a447
|
94f387e2d406fab2128bcfffce6146da720b2ccc
|
refs/heads/master
| 2020-07-05T15:43:00.957221 | 2017-09-17T14:05:48 | 2017-09-17T14:05:48 | null | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 2,870 |
py
|
# -*- utf-8 -*-
import matplotlib.pyplot as plt
from matplotlib import style
style.use('ggplot')
import numpy as np
X = np.array([[1, 2],
[1.5, 1.8],
[5, 8],
[8, 8],
[1, 0.6],
[9, 11],
[1, 3],
[8, 9],
[0, 3],
[5, 4],
[6, 4], ])
plt.scatter(X[:, 0], X[:, 1], s = 50)
plt.show()
colors = 10 * ["g", "r", "c", "b", "k"]
class K_Means:
def __init__(self, k = 2, tol = 0.001, max_iter = 300):
self.k = k
self.tol = tol
self.max_iter = max_iter
def fit(self, data):
self.centroids = {}
for i in range(self.k):
self.centroids[i] = data[i]
for i in range(self.max_iter):
self.classifications = {}
for i in range(self.k):
self.classifications[i] = []
for featureset in data:
distances = [np.linalg.norm(featureset - self.centroids[centroid]) for centroid in self.centroids]
classification = distances.index(min(distances))
self.classifications[classification].append(featureset)
prev_centroids = dict(self.centroids)
for classification in self.classifications:
self.centroids[classification] = np.average(self.classifications[classification], axis = 0)
optimized = True
for c in self.centroids:
original_centroid = prev_centroids[c]
current_centroid = self.centroids[c]
if np.sum((current_centroid - original_centroid) / original_centroid * 100) > self.tol:
print(np.sum((current_centroid - original_centroid) / original_centroid * 100.0))
optimized = False
if optimized:
break
def predict(self, data):
distances = [np.linalg.norm(data - self.centroids[centroid]) for centroid in self.centroids]
classification = distances.index(min(distances))
return classification
clf = K_Means()
clf.fit(X)
for centroid in clf.centroids:
plt.scatter(clf.centroids[centroid][0], clf.centroids[centroid][1],
marker = "o", color = "k", s = 150, linewidths = 5)
for classification in clf.classifications:
color = colors[classification]
for featureset in clf.classifications[classification]:
plt.scatter(featureset[0], featureset[1], marker = "x", color = color, s = 150, linewidths = 5)
unknowns = np.array([[1, 3],
[8, 9],
[0, 3],
[5, 4],
[6, 4], ])
for unknown in unknowns:
classification = clf.predict(unknown)
plt.scatter(unknown[0], unknown[1], marker = "x", color = colors[classification], s = 50, linewidths = 5)
plt.show()
|
[
"[email protected]"
] | |
1fc8c3edd2c2ef3d16c220f36cb7d72c3bcad84f
|
5da5473ff3026165a47f98744bac82903cf008e0
|
/packages/google-cloud-datalabeling/samples/generated_samples/datalabeling_v1beta1_generated_data_labeling_service_list_annotated_datasets_async.py
|
5f3fe6b186baf941dd84aef169d534faaebfa3cf
|
[
"Apache-2.0"
] |
permissive
|
googleapis/google-cloud-python
|
ed61a5f03a476ab6053870f4da7bc5534e25558b
|
93c4e63408c65129422f65217325f4e7d41f7edf
|
refs/heads/main
| 2023-09-04T09:09:07.852632 | 2023-08-31T22:49:26 | 2023-08-31T22:49:26 | 16,316,451 | 2,792 | 917 |
Apache-2.0
| 2023-09-14T21:45:18 | 2014-01-28T15:51:47 |
Python
|
UTF-8
|
Python
| false | false | 2,012 |
py
|
# -*- coding: utf-8 -*-
# Copyright 2023 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, 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.
#
# Generated code. DO NOT EDIT!
#
# Snippet for ListAnnotatedDatasets
# NOTE: This snippet has been automatically generated for illustrative purposes only.
# It may require modifications to work in your environment.
# To install the latest published package dependency, execute the following:
# python3 -m pip install google-cloud-datalabeling
# [START datalabeling_v1beta1_generated_DataLabelingService_ListAnnotatedDatasets_async]
# This snippet has been automatically generated and should be regarded as a
# code template only.
# It will require modifications to work:
# - It may require correct/in-range values for request initialization.
# - It may require specifying regional endpoints when creating the service
# client as shown in:
# https://googleapis.dev/python/google-api-core/latest/client_options.html
from google.cloud import datalabeling_v1beta1
async def sample_list_annotated_datasets():
# Create a client
client = datalabeling_v1beta1.DataLabelingServiceAsyncClient()
# Initialize request argument(s)
request = datalabeling_v1beta1.ListAnnotatedDatasetsRequest(
parent="parent_value",
)
# Make the request
page_result = client.list_annotated_datasets(request=request)
# Handle the response
async for response in page_result:
print(response)
# [END datalabeling_v1beta1_generated_DataLabelingService_ListAnnotatedDatasets_async]
|
[
"[email protected]"
] | |
d49d4df253e01b51cbef0fd3337a5d662b8bb43c
|
6a2c2af113bb8b4d55db6ceabc6e78a0bbcd1f91
|
/genus processing/Shorts Back Pocket Flap.py
|
c5157eb6d81a0e4a0684d901d89b3339771afb61
|
[] |
no_license
|
JinghongM/Everlasting_Data_Cleansing
|
4a966aca5cba102961f64338411d76e51f60f51e
|
237073980b2bd1697db578013c7463dcbc1492fb
|
refs/heads/master
| 2021-04-26T23:48:38.083155 | 2018-06-21T20:00:11 | 2018-06-21T20:00:11 | 123,861,020 | 0 | 0 | null | null | null | null |
UTF-8
|
Python
| false | false | 495 |
py
|
import pandas as pd
import copy
import os.path
Pattern=6
Material=7
Species=4
CGP = pd.read_excel("../Realdata.xlsx")
for row in range(1,CGP.shape[0]):
genus = str(CGP.iat[row,3])
if "Shorts Back Pocket Flap" == genus:
print(row)
CGP.iat[row,Species] = "Back Pocket"
CGP.iat[row,3] = "Shorts"
i=0 #process headers
while i<len(CGP.columns.values):
if "Unnamed" in CGP.columns.values[i]:
CGP.columns.values[i] = ''
i+=1
CGP.to_excel('../Realdata.xlsx',index=False)
|
[
"[email protected]"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.