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
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
f2adac6b08cba4a67e4da5fad5abb9ed22b1ebe1
|
eed4e25645c7590a986d9b9c8435b8d052cc913a
|
/parakeet/transforms/stride_specialization.py
|
899c1bad4ea379c053391da24e807222ba0846e6
|
[
"BSD-3-Clause"
] |
permissive
|
Tillsten/parakeet
|
63afd4bb8d83b64529e81e6c13348fd2e4d10a6f
|
5045c3f6c4de19f4acbafeaf2fc9e5c7ff9aa63c
|
refs/heads/master
| 2021-01-18T15:36:16.814995
| 2013-10-02T00:36:23
| 2013-10-02T00:36:23
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,281
|
py
|
from .. analysis.find_constant_strides import FindConstantStrides, Const, Array, Struct, Tuple
from .. analysis.find_constant_strides import from_python_list, from_internal_repr
from .. syntax.helpers import const_int, const
from dead_code_elim import DCE
from phase import Phase
from simplify import Simplify
from transform import Transform
class StrideSpecializer(Transform):
def __init__(self, abstract_inputs):
Transform.__init__(self)
self.abstract_inputs = abstract_inputs
def pre_apply(self, fn):
analysis = FindConstantStrides(fn, self.abstract_inputs)
analysis.visit_fn(fn)
self.env = analysis.env
def transform_Var(self, expr):
if expr.name in self.env:
value = self.env[expr.name]
if value.__class__ is Const:
result = const(value.value)
return result
return expr
def transform_lhs(self, lhs):
return lhs
def has_unit_stride(abstract_value):
c = abstract_value.__class__
if c is Array:
return has_unit_stride(abstract_value.strides)
elif c is Struct:
return any(has_unit_stride(field_val)
for field_val
in abstract_value.fields.itervalues())
elif c is Tuple:
return any(has_unit_stride(elt)
for elt in abstract_value.elts)
elif c is Const:
return abstract_value.value == 1
else:
return False
_cache = {}
def specialize(fn, python_values, types = None):
if types is None:
abstract_values = from_python_list(python_values)
else:
# if types are given, assume that the values
# are already converted to Parakeet's internal runtime
# representation
abstract_values = []
for (t, internal_value) in zip(types, python_values):
abstract_values.append(from_internal_repr(t, internal_value))
key = (fn.name, tuple(abstract_values))
if key in _cache:
return _cache[key]
elif any(has_unit_stride(v) for v in abstract_values):
specializer = StrideSpecializer(abstract_values)
transforms = Phase([specializer, Simplify, DCE],
memoize = False, copy = True,
name = "StrideSpecialization for %s" % abstract_values)
new_fn = transforms.apply(fn)
else:
new_fn = fn
_cache[key] = new_fn
return new_fn
|
[
"alex.rubinsteyn@gmail.com"
] |
alex.rubinsteyn@gmail.com
|
cf008304d5ece13b86dbf6527bf76302f2b03546
|
7e72e16f43170749dada023624a88fd622727639
|
/jdcloud_sdk/services/monitor/models/SiteMonitorFtpOption.py
|
74c06ad00ca3b082dff46c5db43a7d195487c31e
|
[
"Apache-2.0"
] |
permissive
|
jdcloud-demo/jdcloud-sdk-python
|
4dc1e814217df16c5f60f5e4b3f8260b770f9d2b
|
fddc2af24031c597948b8b8091978ac7e01a2695
|
refs/heads/master
| 2020-07-11T18:19:59.688112
| 2019-08-23T05:55:18
| 2019-08-23T05:55:18
| 204,613,050
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,072
|
py
|
# coding=utf8
# Copyright 2018 JDCLOUD.COM
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# NOTE: This class is auto generated by the jdcloud code generator program.
class SiteMonitorFtpOption(object):
def __init__(self, loginType=None, passwd=None, timeout=None, user=None):
"""
:param loginType: (Optional)
:param passwd: (Optional)
:param timeout: (Optional)
:param user: (Optional)
"""
self.loginType = loginType
self.passwd = passwd
self.timeout = timeout
self.user = user
|
[
"tancong@jd.com"
] |
tancong@jd.com
|
335349eab960e401562561524f316f7a8f145d3e
|
8ab21f9b2fb6a96f9fd6ef8f06091b68b2ff8611
|
/labluz/wsgi.py
|
80467c5db8692bb3f7d05278d9ea4b457b4a8014
|
[
"MIT"
] |
permissive
|
macndesign/labluz
|
8ddcfa71dcaab7083c0ed670d5e007e6e59de0c1
|
a6100ae903ab6164d087ef2765c00d81d134a373
|
refs/heads/master
| 2016-09-09T21:39:55.771160
| 2013-12-16T03:45:02
| 2013-12-16T03:45:02
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 423
|
py
|
"""
WSGI config for labluz 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.6/howto/deployment/wsgi/
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "labluz.settings")
from django.core.wsgi import get_wsgi_application
from dj_static import Cling
application = Cling(get_wsgi_application())
|
[
"macndesign@gmail.com"
] |
macndesign@gmail.com
|
60e828ae2e99cb6911492deee536f5ec9007e165
|
7b5d97f8d0d00dfbad7cf52133166b7abdb47f11
|
/overthewire/vortex/l0/solve.py
|
fb2ea6cc6b032fa8012914402d719d33fe3b8969
|
[] |
no_license
|
plvhx/any-ctf-writeup
|
64b34010ba81b968f52bfb437ff908a4e6821a84
|
286c020a2b7e17d6a3ddc995c9c4f5087f4843df
|
refs/heads/master
| 2021-06-10T22:18:03.294359
| 2016-12-14T14:28:03
| 2016-12-14T14:28:03
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 711
|
py
|
#! /usr/bin/python
import sys
import struct
import socket
import telnetlib
if sys.byteorder == 'little':
Q = lambda x: struct.pack("<I", x)
rQ = lambda x: struct.unpack("<I", x)[0]
elif sys.byteorder == 'big':
Q = lambda x: struct.pack(">I", x)
rQ = lambda x: struct.unpack(">I", x)[0]
try:
s = socket.create_connection(('vortex.labs.overthewire.org', 5842))
except socket.gaierror as e:
(n, q) = e
sys.exit(-1)
try:
tuple = [];
for i in range(4):
tuple.append(rQ(s.recv(4)))
except socket.error as e:
(n, q) = e
sys.exit(-1)
try:
s.send(Q(reduce(lambda x, y: x + y, tuple)) + chr(0x0a))
except socket.error as e:
(n, q) = e
sys.exit(-1)
t = telnetlib.Telnet()
t.sock = s
t.interact()
|
[
"vagrant@precise64.(none)"
] |
vagrant@precise64.(none)
|
9a94262a5308425f8bf9da0226d2fa50d17e48c1
|
4894b77303b4fcd303f6103bc1387c99d87381f9
|
/award/settings.py
|
4d97140f4232351b4aac496d74956181687b1c98
|
[
"MIT"
] |
permissive
|
sngina/Award
|
ff21422839a32fbf5901e25427a33e6737aa15db
|
4cdbe0da49cb69819deb4c00011718b087891919
|
refs/heads/master
| 2023-06-20T09:05:51.513020
| 2021-07-20T08:33:39
| 2021-07-20T08:33:39
| 386,533,417
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 4,200
|
py
|
"""
Django settings for award project.
Generated by 'django-admin startproject' using Django 1.11.17.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""
import os
import dj_database_url
import django_heroku
from decouple import config , Csv
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
# SECRET_KEY = 'ix8jby828(i8b*=n$#8xi9+mwrq=i1+=*1m*&i2b5v@lvvu+p$'
# SECURITY WARNING: don't run with debug turned on in production!
MODE=config("MODE", default="dev")
SECRET_KEY = config('SECRET_KEY')
DEBUG = config('DEBUG', default=False, cast=bool)
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'project',
'bootstrap3',
'crispy_forms',
'rest_framework'
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
]
ROOT_URLCONF = 'award.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'award.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
if config('MODE')== "dev" :
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': config('DB_NAME'),
'USER': config('DB_USER'),
'PASSWORD': config('DB_PASSWORD'),
'HOST': config('DB_HOST'),
'PORT': '',
}
}
else:
DATABASES = {
'default': dj_database_url.config(
default=config('DATABASE_URL')
)
}
db_from_env = dj_database_url.config(conn_max_age=500)
DATABASES['default'].update(db_from_env)
ALLOWED_HOSTS = config('ALLOWED_HOSTS', cast=Csv())
# Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
# Configure Django App for Heroku.
django_heroku.settings(locals())
LOGIN_REDIRECT_URL ='/'
|
[
"sngina707@gmail.com"
] |
sngina707@gmail.com
|
5df01d2277c77acdae3677cd9511de336ccc60fd
|
f82e67dd5f496d9e6d42b4fad4fb92b6bfb7bf3e
|
/scripts/client/gui/scaleform/daapi/view/lobby/fortifications/components/fortdisconnectviewcomponent.py
|
d3c69c3ecb05a4cd811ba421ff93edfbdcf24cf1
|
[] |
no_license
|
webiumsk/WOT0.10.0
|
4e4413ed4e7b00e22fb85d25fdae9400cbb4e76b
|
a84f536c73f86d9e8fab559e97f88f99f2ad7e95
|
refs/heads/master
| 2021-01-09T21:55:00.662437
| 2015-10-23T20:46:45
| 2015-10-23T20:46:45
| 44,835,654
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,539
|
py
|
# Embedded file name: scripts/client/gui/Scaleform/daapi/view/lobby/fortifications/components/FortDisconnectViewComponent.py
from gui.Scaleform.daapi.view.lobby.fortifications.fort_utils.FortViewHelper import FortViewHelper
from gui.Scaleform.daapi.view.meta.FortDisconnectViewMeta import FortDisconnectViewMeta
from gui.Scaleform.locale.FORTIFICATIONS import FORTIFICATIONS
from gui.shared import g_eventBus, events, EVENT_BUS_SCOPE
from gui.shared.fortifications.settings import CLIENT_FORT_STATE
from gui.shared.formatters import icons
from helpers import i18n
class FortDisconnectViewComponent(FortDisconnectViewMeta, FortViewHelper):
def __init__(self):
super(FortDisconnectViewComponent, self).__init__()
def _populate(self):
super(FortDisconnectViewComponent, self)._populate()
state = self.fortState
warningIcon = icons.alert()
warningText = warningIcon + i18n.makeString(FORTIFICATIONS.DISCONNECTED_WARNING)
if state.getStateID() == CLIENT_FORT_STATE.ROAMING:
warningDescrText = FORTIFICATIONS.DISCONNECTED_WARNINGDESCRIPTIONROAMING
else:
warningDescrText = FORTIFICATIONS.DISCONNECTED_WARNINGDESCRIPTIONCENTERUNAVAILABLE
warningDescrText = i18n.makeString(warningDescrText)
self.as_setWarningTextsS(warningText, warningDescrText)
g_eventBus.handleEvent(events.FortEvent(events.FortEvent.VIEW_LOADED), scope=EVENT_BUS_SCOPE.FORT)
def _dispose(self):
super(FortDisconnectViewComponent, self)._dispose()
|
[
"info@webium.sk"
] |
info@webium.sk
|
1420dc41a020bc3ae1a7eff801eef50c12fae666
|
6bd71bdfe9234e5e6de90bb40b6cd8d3e25ca6d2
|
/Escuelas/TC2011/ejercicios-Parte1/soluciones/editarEsteComando.py
|
4e4a68120b03d4f00ed94f98d99ed32d9755ac52
|
[] |
no_license
|
andres0sorio/CMSWork
|
f1f30a12bf43eb688ef9e95c53c94fe32fc7fe66
|
81e60a0a9b70cd2ae01d17b15be386a6cd925416
|
refs/heads/master
| 2021-01-22T13:12:16.094247
| 2015-10-26T04:47:12
| 2015-10-26T04:47:12
| 9,710,836
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 375
|
py
|
#!/usr/bin/python
import sys,os
# Este es un script sencillo en Python
# Para escribir un comentario, uno debe empezar la linea con un simbolo #
# Por favor comente la linea siguiente adicionando un simbolo # al frente de la linea siguiente
# raise RuntimeError
username = os.getenv('USER')
print 'Muy bien: ', username, ' usted ha editado correctamente este script'
|
[
"osorio.af@gmail.com"
] |
osorio.af@gmail.com
|
0f462660927792ab2746267aeb12801a663cbc12
|
69246effee7359d81d8e8ac5cab1bc354a7a933f
|
/account/tests.py
|
88fad6f89c098ebd4fd21c8c6a5ee31eea059001
|
[] |
no_license
|
joeyac/TeachAssist2
|
0edfa98ab942ef5cd2308a617491e367a0b7bd86
|
d99164b7d4fc2772bcda991ec9de0d13a9a894bf
|
refs/heads/master
| 2020-03-19T04:50:45.656778
| 2018-06-22T08:34:49
| 2018-06-22T08:34:49
| 135,873,919
| 1
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,209
|
py
|
import json
from django.test import TestCase
from django.test import Client
from rest_framework import status
from account.models import User
from utils.constants import UserType
class AccountTestCase(TestCase):
def setUp(self):
teacher = User.objects.create(username='g123', email='g124@test.com', user_type=UserType.TEACHER)
teacher.set_password('g123')
teacher.save()
self.c = Client()
def send_json(self, url, data):
return self.c.post(url, json.dumps(data), content_type="application/json")
def test_login_success(self):
response = self.send_json('/login/', {'username': 'g123', 'password': 'g123'})
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual('Succeeded', response.json()['data'])
def test_login_failed(self):
response = self.send_json('/login/', {'username': 'g123', 'password': '123g'})
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual('Invalid username or password', response.json()['data'])
def test_create_user(self):
response = self.send_json('/register/',
{'username': 'username1234', 'password': '1234567890', 'email': 'xu_qq@test.com',
'user_type': UserType.STUDENT})
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual('Succeeded', response.json()['data'])
def test_create_user_failed(self):
response = self.send_json('/register/',
{'username': 'username1234', 'password': '1234567890', 'email': 'xu_qq@test.com',
'user_type': 'student===='})
self.assertEqual(response.json()['data'], 'user_type: "student====" is not a valid choice.')
def test_decorator_success(self):
self.send_json('/login/', {'username': 'g123', 'password': 'g123'})
response = self.c.get('/test/')
self.assertEqual(response.json()['data'], 'g123')
def test_decorator_failed(self):
response = self.c.get('/test/')
self.assertEqual(response.json()['data'], 'Please login first')
|
[
"623353308@qq.com"
] |
623353308@qq.com
|
6e67b80e239e05eb821cb6eac9b7fb4294adf9e2
|
3ed194eef8f7de82d10b76fb73dabb7abb6f0e46
|
/if_char_is_char.py
|
892a99d3d4beb0b7a290b6804c9827e1091304d3
|
[
"MIT"
] |
permissive
|
CrazyJ36/python
|
9c4724e74b276664a9a638dfd09b082e78ec78f1
|
730c384304d51c23a4c36337216ae586f2fe674c
|
refs/heads/master
| 2022-10-11T02:58:04.342322
| 2022-09-30T21:52:49
| 2022-09-30T21:52:49
| 186,742,500
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 167
|
py
|
#!/usr/bin/env python3.7
print("type 'x' or something else for comparison:")
mchar = input()
if mchar is 'x':
print("input is x")
else:
print("input is not x")
|
[
"crazy_j36@hotmail.com"
] |
crazy_j36@hotmail.com
|
4781d858b7b1f270f3c80d2569997214211a5abc
|
ae8f61a8c0c4a569f00529c3f07c73dbfc884f71
|
/tiled/client/utils.py
|
021dc8745848024a80b502d34a110853c79d851b
|
[
"BSD-3-Clause"
] |
permissive
|
untzag/tiled
|
1ba705303193312711d8ac75b977a26d6d9e7571
|
43a8ba82660ce3be077f2b6b060bdd2a23cf956b
|
refs/heads/main
| 2023-04-18T18:34:13.545139
| 2021-04-28T21:27:59
| 2021-04-28T21:27:59
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,539
|
py
|
import asyncio
from inspect import iscoroutine
import httpx
import msgpack
from ..utils import Sentinel
class UNSET(Sentinel):
pass
def get_content_with_cache(
cache, offline, client, path, accept=None, timeout=UNSET, **kwargs
):
request = client.build_request("GET", path, **kwargs)
if accept:
request.headers["Accept"] = accept
url = request.url.raw # URL as tuple
if offline:
# We must rely on the cache alone.
reservation = cache.get_reservation(url)
if reservation is None:
raise NotAvailableOffline(url)
content = reservation.load_content()
if content is None:
# TODO Do we ever get here?
raise NotAvailableOffline(url)
return content
if cache is None:
# No cache, so we can use the client straightforwardly.
response = _send(client, request, timeout=timeout)
handle_error(response)
return response.content
# If we get this far, we have an online client and a cache.
reservation = cache.get_reservation(url)
try:
if reservation is not None:
request.headers["If-None-Match"] = reservation.etag
response = _send(client, request, timeout=timeout)
handle_error(response)
if response.status_code == 304: # HTTP 304 Not Modified
# Read from the cache
content = reservation.load_content()
elif response.status_code == 200:
etag = response.headers.get("ETag")
content = response.content
# TODO Respect Cache-control headers (e.g. "no-store")
if etag is not None:
# Write to cache.
cache.put_etag_for_url(url, etag)
cache.put_content(etag, content)
else:
raise NotImplementedError(f"Unexpected status_code {response.status_code}")
finally:
if reservation is not None:
reservation.ensure_released()
return content
def get_json_with_cache(cache, offline, client, path, **kwargs):
return msgpack.unpackb(
get_content_with_cache(
cache, offline, client, path, accept="application/x-msgpack", **kwargs
)
)
def _send(client, request, timeout):
"""
EXPERIMENTAL: Tolerate sync httpx.Client or httpx.AsyncClient.
The AsyncClient is interesting because it can interface directly with FastAPI app
in the same process via ASGI.
"""
if timeout is UNSET:
result = client.send(request)
else:
result = client.send(request, timeout=timeout)
if iscoroutine(result):
return asyncio.run(result)
return result
def handle_error(response):
try:
response.raise_for_status()
except httpx.RequestError:
raise # Nothing to add in this case; just raise it.
except httpx.HTTPStatusError as exc:
if response.status_code < 500:
# Include more detail that httpx does by default.
message = (
f"{exc.response.status_code}: "
f"{exc.response.json()['detail']} "
f"{exc.request.url}"
)
raise ClientError(message, exc.request, exc.response) from exc
else:
raise
class ClientError(httpx.HTTPStatusError):
def __init__(self, message, request, response):
super().__init__(message=message, request=request, response=response)
class NotAvailableOffline(Exception):
"Item looked for in offline cache was not found."
|
[
"dallan@bnl.gov"
] |
dallan@bnl.gov
|
deb0f1f1c739784d71150481cdcafcc50e01d078
|
4a8c1f7d9935609b780aff95c886ef7781967be0
|
/atcoder/ABC/A/072_a.py
|
2bdb2b702f8afe70275c3ff34ad5c1e31423163a
|
[] |
no_license
|
recuraki/PythonJunkTest
|
d5e5f5957ac5dd0c539ef47759b1fe5ef7a2c52a
|
2556c973d468a6988d307ce85c5f2f8ab15e759a
|
refs/heads/master
| 2023-08-09T17:42:21.875768
| 2023-07-18T23:06:31
| 2023-07-18T23:06:31
| 13,790,016
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 948
|
py
|
import sys
from io import StringIO
import unittest
class TestClass(unittest.TestCase):
def assertIO(self, input, output):
stdout, stdin = sys.stdout, sys.stdin
sys.stdout, sys.stdin = StringIO(), StringIO(input)
resolve()
sys.stdout.seek(0)
out = sys.stdout.read()[:-1]
sys.stdout, sys.stdin = stdout, stdin
self.assertEqual(out, output)
def test_入力例_1(self):
input = """100 17"""
output = """83"""
self.assertIO(input, output)
def test_入力例_2(self):
input = """48 58"""
output = """0"""
self.assertIO(input, output)
def test_入力例_3(self):
input = """1000000000 1000000000"""
output = """0"""
self.assertIO(input, output)
if __name__ == "__main__":
unittest.main()
def resolve():
x,t = map(int, input().split())
if x - t > 0:
print(x-t)
else:
print("0")
|
[
"kanai@wide.ad.jp"
] |
kanai@wide.ad.jp
|
5182e2b90713dbb6256c9936fc582e92cabae6f7
|
50afc0db7ccfc6c80e1d3877fc61fb67a2ba6eb7
|
/challenge6(hotel)/SnowballSH.py
|
023455239f336510c3cbbc9ff2146d798a0ea89a
|
[
"MIT"
] |
permissive
|
banana-galaxy/challenges
|
792caa05e7b8aa10aad8e04369fc06aaf05ff398
|
8655c14828607535a677e2bb18689681ee6312fa
|
refs/heads/master
| 2022-12-26T23:58:12.660152
| 2020-10-06T13:38:04
| 2020-10-06T13:38:04
| 268,851,516
| 11
| 8
|
MIT
| 2020-09-22T21:21:30
| 2020-06-02T16:24:41
|
Python
|
UTF-8
|
Python
| false
| false
| 837
|
py
|
def matrixSum(matrix):
#Returns a list of cols instead of rows
def get_col():
rt = []
for c in range(len(matrix[0])):
ct = []
for i in range(len(matrix)):
ct.append(matrix[i][c])
rt.append(ct)
return rt
#Check if TWT staff isn't able to move in
def not_able(idx,c):
for i, v in enumerate(c):
if i < idx and v <= 0:
return True
return False
col = get_col().copy()
SUMLIST = []
for col_count, every_col in enumerate(col):
for num_count, every_num in enumerate(every_col):
if not_able(num_count,every_col):
SUMLIST.append(0)
else:
SUMLIST.append(every_num)
return sum(SUMLIST)
|
[
"cawasp@gmail.com"
] |
cawasp@gmail.com
|
95f95cb7909dc39645281e60db52b9e9201e9b98
|
00da01b831d58f4cbae5c3625823849dde3eff67
|
/contests/293_DIV2/b.py
|
cbd9c868d1e95f83896418f65fa074356a5e2ff4
|
[] |
no_license
|
atupal/codeforces
|
577b2c084b9cf047c5780f840e9fe49fcb0fd50a
|
563c3e27e0450b3dde24661a606c84b1a8d81f17
|
refs/heads/master
| 2021-01-15T22:10:07.657554
| 2015-10-12T06:58:10
| 2015-10-12T06:58:10
| 10,015,882
| 2
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 611
|
py
|
# -*- coding: utf-8 -*-
s = raw_input()
t = raw_input()
import string
lower = string.lowercase
upper = lower.upper()
class mydict(dict):
def __missing__(self, key):
self[key] = 0
return self[key]
ds = mydict()
dt = mydict()
for i in s:
ds[i] += 1
for i in t:
dt[i] += 1
cnt1 = 0
cnt2 = 0
for key in ds:
t = min( ds[key], dt[key] )
ds[key] -= t
dt[key] -= t
cnt1 += t
for key in lower:
if ds[key] and dt[key.upper()]:
cnt2 += min( ds[key] , dt[key.upper()] )
for key in upper:
if ds[key] and dt[key.lower()]:
cnt2 += min( ds[key] , dt[key.lower()] )
print cnt1, cnt2
|
[
"atupalykl@gmail.com"
] |
atupalykl@gmail.com
|
c5c31cec5a6fe7c542613055cd5833c5b02e84fd
|
84226827016bf833e843ebce91d856e74963e3ed
|
/tests/unit/payload_test.py
|
fb32bdfe608f403ef2d986cac36febf6377b224a
|
[
"Apache-2.0"
] |
permissive
|
jbq/pkg-salt
|
ad31610bf1868ebd5deae8f4b7cd6e69090f84e0
|
b6742e03cbbfb82f4ce7db2e21a3ff31b270cdb3
|
refs/heads/master
| 2021-01-10T08:55:33.946693
| 2015-05-21T13:41:01
| 2015-05-21T13:41:01
| 36,014,487
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 5,505
|
py
|
# -*- coding: utf-8 -*-
'''
:codeauthor: :email:`Pedro Algarvio (pedro@algarvio.me)`
tests.unit.payload_test
~~~~~~~~~~~~~~~~~~~~~~~
'''
# Import Salt Testing libs
from salttesting import skipIf, TestCase
from salttesting.helpers import ensure_in_syspath, MockWraps
from salttesting.mock import NO_MOCK, NO_MOCK_REASON, patch
ensure_in_syspath('../')
# Import salt libs
import salt.payload
from salt.utils.odict import OrderedDict
import salt.exceptions
# Import 3rd-party libs
import msgpack
import zmq
import errno
import threading
import time
@skipIf(NO_MOCK, NO_MOCK_REASON)
class PayloadTestCase(TestCase):
def assertNoOrderedDict(self, data):
if isinstance(data, OrderedDict):
raise AssertionError(
'Found an ordered dictionary'
)
if isinstance(data, dict):
for value in data.values():
self.assertNoOrderedDict(value)
elif isinstance(data, (list, tuple)):
for chunk in data:
self.assertNoOrderedDict(chunk)
def test_list_nested_odicts(self):
with patch('msgpack.version', (0, 1, 13)):
msgpack.dumps = MockWraps(
msgpack.dumps, 1, TypeError('ODict TypeError Forced')
)
payload = salt.payload.Serial('msgpack')
idata = {'pillar': [OrderedDict(environment='dev')]}
odata = payload.loads(payload.dumps(idata.copy()))
self.assertNoOrderedDict(odata)
self.assertEqual(idata, odata)
class SREQTestCase(TestCase):
port = 8845 # TODO: dynamically assign a port?
@classmethod
def setUpClass(cls):
'''
Class to set up zmq echo socket
'''
def echo_server():
'''
A server that echos the message sent to it over zmq
Optional "sleep" can be sent to delay response
'''
context = zmq.Context()
socket = context.socket(zmq.REP)
socket.bind("tcp://*:{0}".format(SREQTestCase.port))
payload = salt.payload.Serial('msgpack')
while SREQTestCase.thread_running.is_set():
try:
# Wait for next request from client
message = socket.recv(zmq.NOBLOCK)
msg_deserialized = payload.loads(message)
if isinstance(msg_deserialized['load'], dict) and msg_deserialized['load'].get('sleep'):
time.sleep(msg_deserialized['load']['sleep'])
socket.send(message)
except zmq.ZMQError as exc:
if exc.errno == errno.EAGAIN:
continue
raise
SREQTestCase.thread_running = threading.Event()
SREQTestCase.thread_running.set()
SREQTestCase.echo_server = threading.Thread(target=echo_server)
SREQTestCase.echo_server.start()
@classmethod
def tearDownClass(cls):
'''
Remove echo server
'''
# kill the thread
SREQTestCase.thread_running.clear()
SREQTestCase.echo_server.join()
def get_sreq(self):
return salt.payload.SREQ('tcp://127.0.0.1:{0}'.format(SREQTestCase.port))
def test_send_auto(self):
'''
Test creation, send/rect
'''
sreq = self.get_sreq()
# check default of empty load and enc clear
assert sreq.send_auto({}) == {'enc': 'clear', 'load': {}}
# check that the load always gets passed
assert sreq.send_auto({'load': 'foo'}) == {'load': 'foo', 'enc': 'clear'}
def test_send(self):
sreq = self.get_sreq()
assert sreq.send('clear', 'foo') == {'enc': 'clear', 'load': 'foo'}
def test_timeout(self):
'''
Test SREQ Timeouts
'''
sreq = self.get_sreq()
# client-side timeout
start = time.time()
# This is a try/except instead of an assertRaises because of a possible
# subtle bug in zmq wherein a timeout=0 actually exceutes a single poll
# before the timeout is reached.
try:
sreq.send('clear', 'foo', tries=0, timeout=0)
except salt.exceptions.SaltReqTimeoutError:
pass
assert time.time() - start < 1 # ensure we didn't wait
# server-side timeout
start = time.time()
with self.assertRaises(salt.exceptions.SaltReqTimeoutError):
sreq.send('clear', {'sleep': 2}, tries=1, timeout=1)
assert time.time() - start >= 1 # ensure we actually tried once (1s)
# server-side timeout with retries
start = time.time()
with self.assertRaises(salt.exceptions.SaltReqTimeoutError):
sreq.send('clear', {'sleep': 2}, tries=2, timeout=1)
assert time.time() - start >= 2 # ensure we actually tried twice (2s)
# test a regular send afterwards (to make sure sockets aren't in a twist
assert sreq.send('clear', 'foo') == {'enc': 'clear', 'load': 'foo'}
def test_destroy(self):
'''
Test the __del__ capabilities
'''
sreq = self.get_sreq()
# ensure no exceptions when we go to destroy the sreq, since __del__
# swallows exceptions, we have to call destroy directly
sreq.destroy()
if __name__ == '__main__':
from integration import run_tests
run_tests(PayloadTestCase, needs_daemon=False)
run_tests(SREQTestCase, needs_daemon=False)
|
[
"joehealy@gmail.com"
] |
joehealy@gmail.com
|
ebdebcdd687aa5cf786c51373a673303400f155a
|
0478abafc05f1dd55ddf6054d95fef73e9fa03e9
|
/quati/__main__.py
|
5d239149288d0d96a0286f5e599b8a35e00bbdbc
|
[
"MIT"
] |
permissive
|
deep-spin/quati
|
89bce0868b36b0d7902659507b72acfbd01ada98
|
62a6769475090182fe2990b2864d66f8e2081a32
|
refs/heads/master
| 2023-03-12T09:22:31.520259
| 2021-03-02T15:13:22
| 2021-03-02T15:13:22
| 330,678,540
| 2
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 924
|
py
|
import argparse
import logging
from quati import config_utils
from quati import opts
from quati import predict
from quati import train
logger = logging.getLogger(__name__)
parser = argparse.ArgumentParser(description='quati')
parser.add_argument('task', type=str, choices=['train', 'predict'])
opts.general_opts(parser)
opts.preprocess_opts(parser)
opts.model_opts(parser)
opts.train_opts(parser)
opts.predict_opts(parser)
if __name__ == '__main__':
options = parser.parse_args()
options.output_dir = config_utils.configure_output(options.output_dir)
config_utils.configure_logger(options.debug, options.output_dir)
config_utils.configure_seed(options.seed)
config_utils.configure_device(options.gpu_id)
logger.info('Output directory is: {}'.format(options.output_dir))
if options.task == 'train':
train.run(options)
elif options.task == 'predict':
predict.run(options)
|
[
"marcosvtreviso@gmail.com"
] |
marcosvtreviso@gmail.com
|
7351842124bf39729e663fadcacb1fdc825994cb
|
95eed88115075f7e1916a14de7497d05a12a9330
|
/abc194d.py
|
d19e27dcc40bbd3da711a3fffa9b61e788b10c10
|
[] |
no_license
|
ynagi2/atcoder
|
bdbbd030f1dd39e937b0872b028ce0f38372521e
|
e404f4500d837bfd6ca473aa2837f46ae71ad84a
|
refs/heads/master
| 2022-04-29T12:48:44.229462
| 2022-04-22T15:04:50
| 2022-04-22T15:04:50
| 241,098,529
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 524
|
py
|
# 等差×等比の部分和求めて極限とばすと,
# n / n-k をk=1からn-1まで足し合わせればいいことがわかる
# 別の考え方として,E = p*1 + (1-p)(E+1)
# (確率pで成功し,1-pでEが1回増えるという関係式)
# より,E = 1/p が求まるので,p = 1 - n/Nから,
# N / N-n の総和を求めればよいと考えられる
def main():
n = int(input())
ans = 0
for i in range(n-1):
ans += n / (i+1)
print(ans)
if __name__ == '__main__':
main()
|
[
"noreply@github.com"
] |
ynagi2.noreply@github.com
|
293f2076ab950a2caf64b738152b431673aa60d9
|
f71aecb0e91fe877af3ec652c7f6753a1e7b5ccd
|
/DeleteAndEarn_MID_740.py
|
9184c6e40bedecac812fa994aac05abff1692a4c
|
[] |
no_license
|
953250587/leetcode-python
|
036ad83154bf1fce130d41220cf2267856c7770d
|
679a2b246b8b6bb7fc55ed1c8096d3047d6d4461
|
refs/heads/master
| 2020-04-29T12:01:47.084644
| 2019-03-29T15:50:45
| 2019-03-29T15:50:45
| 176,122,880
| 2
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,409
|
py
|
"""
Given an array nums of integers, you can perform operations on the array.
In each operation, you pick any nums[i] and delete it to earn nums[i] points. After, you must delete every element equal to nums[i] - 1 or nums[i] + 1.
You start with 0 points. Return the maximum number of points you can earn by applying such operations.
Example 1:
Input: nums = [3, 4, 2]
Output: 6
Explanation:
Delete 4 to earn 4 points, consequently 3 is also deleted.
Then, delete 2 to earn 2 points. 6 total points are earned.
Example 2:
Input: nums = [2, 2, 3, 3, 3, 4]
Output: 9
Explanation:
Delete 3 to earn 3 points, deleting both 2's and the 4.
Then, delete 3 again to earn 3 points, and 3 again to earn 3 points.
9 total points are earned.
Note:
The length of nums is at most 20000.
Each element nums[i] is an integer in the range [1, 10000]
"""
class Solution(object):
def deleteAndEarn(self, nums):
"""
:type nums: List[int]
:rtype: int
192ms
"""
num_diff = [0] * 10001
for num in nums:
num_diff[num] += 1
dp = [0] * 10001
dp[1] = num_diff[1]
for i in range(2, 10001):
dp[i] = max(dp[i - 1], dp[i - 2] + num_diff[i] * i)
print(dp[0:10])
return dp[-1]
# print(Solution().deleteAndEarn([3, 4, 2]))
# print(Solution().deleteAndEarn([2, 2, 3, 3, 3, 4]))
print(Solution().deleteAndEarn([1]))
|
[
"953250587@qq.com"
] |
953250587@qq.com
|
e7e1884d2677b6ffa1945bcccd74218252cc3ceb
|
3d6f8dc406a18397c354df72ce7dbf5e87712567
|
/LeetCode/Num_Count.py
|
b0d86b7223ec0c7f7887b0cca1ebe54dcde1a1d1
|
[] |
no_license
|
HonryZhang/Python-Learning
|
b7410153eff7cd4e51e6e5d69cf7a9bc739a8243
|
e29a75eb42588b2ac31d9b498827cba9c87fc157
|
refs/heads/master
| 2021-01-16T21:41:45.429416
| 2018-05-16T01:36:31
| 2018-05-16T01:36:31
| 100,246,266
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,893
|
py
|
#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'Hongrui'
'''
求数字出现的次数?
a.求1~2593中数字 5 出现的次数? 比如555,数字5算出现3次。
b.求 1~N中,数字x (0~9) 出现的次数
'''
'''
Input k: the target number
Input n: the target digit
Output: the total times appeared in the list
'''
def digitCounts(k,n):
t_count = 0 #define the total count of digit n in the list
n_count = 0 #define the count of digit n in the singe loop
index = 0 #define the location of digit n
p_value = k
while p_value:
if p_value%10>n: #get the single digit count
n_count = int(p_value/10+1)*(10**index)
if p_value%10==n: #get the 10th digit count
n_count = int(p_value/10)*(10**index)+ k%(10**index)+1
if p_value%10<n: #get the 100th digit count
n_count = int(p_value/10)*(10**index)
t_count +=n_count
p_value = p_value/10
index=+1
print 'the total count of number %s in the list is %s'%(n,t_count)
if __name__=="__main__":
while True:
value = int(raw_input('Please input a target value:>>'))
number = int(raw_input('Please input a digit:>>'))
if (value>0) and ((number >=0) and (number <10)):
digitCounts(value,number)
else:
print 'Exited.Please check your input. the target value must be a positive integer and the number must between 0 and 9 '
break
'''
Test Cases:
TC_1:Input an invalid target number:0
Expected Result:program outputs 0
TC_2:Input an invalid digit which is larger than 9 or is a negtive number
Expect Result: program exited and print correct message
TC_3:Input a special value of the single digit 0
Expect Result: program outputs the correct count
TC_4:Input a negtive value of target
Expect Result: program exited and print correct message
'''
|
[
"jshori@163.com"
] |
jshori@163.com
|
566835bfa21b0ae9ac62103e689e07fca0d0ec84
|
dd027c4bbcace97e3dbf566c123b178ceb1a8282
|
/sett/bin.py
|
ec6cfeb5a5845420ceece18c657966787f9d4496
|
[] |
no_license
|
cecedille1/Sett
|
479bf00ca8df807f431e235c68b892bb90fab9b0
|
bf8b9f204caa532a5fb8f110ab4e4a1cea03cb96
|
refs/heads/master
| 2021-01-10T13:28:11.614022
| 2016-03-31T16:51:14
| 2016-03-31T16:51:14
| 43,488,127
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,025
|
py
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import functools
from paver.easy import path
class NotInstalled(Exception):
pass
class DirectorySearcher(object):
def __init__(self, directory):
self.directory = path(directory)
def search(self, program):
bin_path = self.directory.joinpath(program)
if bin_path.access(os.X_OK):
return bin_path
return None
def __repr__(self):
return '<DS {}>'.format(self.directory)
class DirectoriesSearcher(object):
def __init__(self, directories):
self.directories = [DirectorySearcher(d) for d in directories]
def search(self, program):
for directory in self.directories:
prog = directory.search(program)
if prog:
return prog
def __repr__(self):
return '<DS {}>'.format(', '.join(d.directory for d in self.directories))
class Which(object):
NotInstalled = NotInstalled
def __init__(self, searchers):
self.searchers = searchers
self._cache = {}
def __repr__(self):
return '<W {}>'.format(', '.join(repr(s) for s in self.searchers))
def __getattr__(self, program):
return self.search(program)
def search(self, program):
if '/' in program:
raise ValueError('Program name must not contain a /')
if program in self._cache:
return self._cache[program]
for searcher in self.searchers:
bin_path = searcher.search(program)
if bin_path:
self._cache[program] = bin_path
return bin_path
raise NotInstalled(program)
def default_searchers():
searchers = []
from sett.pip import VENV_BIN
if VENV_BIN.exists():
searchers.append(DirectorySearcher(VENV_BIN))
from sett.npm import NODE_MODULES
if NODE_MODULES.exists():
searchers.append(DirectorySearcher(NODE_MODULES.joinpath('.bin')))
from sett.gem import GEM_HOME
if GEM_HOME.exists():
searchers.append(DirectorySearcher(GEM_HOME.joinpath('bin')))
if os.environ.get('PATH'):
searchers.append(DirectoriesSearcher(os.environ['PATH'].split(':')))
return searchers
class LazyWhich(object):
NotInstalled = NotInstalled
def __init__(self, searchers_provider):
self.sp = searchers_provider
def is_evaluated(self):
return '_which' in self.__dict__
def __getattr__(self, attr):
if not self.is_evaluated():
self._which = Which(self.sp())
return getattr(self._which, attr)
def __repr__(self):
return self.__getattr__('__repr__')()
def update(self, fn=None):
if fn:
@functools.wraps(fn)
def inner_update(*args, **kw):
r = fn(*args, **kw)
self.update()
return r
return inner_update
elif self.is_evaluated():
del self._which
which = LazyWhich(default_searchers)
|
[
"gr@enix.org"
] |
gr@enix.org
|
acaf735fe15e99d7e343e8c31f11012dd1eba187
|
f71ee969fa331560b6a30538d66a5de207e03364
|
/scripts/client/gui/clubs/states.py
|
044f480507dd784df1264197b77e5f09b86db64b
|
[] |
no_license
|
webiumsk/WOT-0.9.8-CT
|
31356ed01cb110e052ba568e18cb2145d4594c34
|
aa8426af68d01ee7a66c030172bd12d8ca4d7d96
|
refs/heads/master
| 2016-08-03T17:54:51.752169
| 2015-05-12T14:26:00
| 2015-05-12T14:26:00
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 4,557
|
py
|
# Embedded file name: scripts/client/gui/clubs/states.py
from gui.shared.utils.decorators import ReprInjector
from gui.clubs.settings import CLIENT_CLUB_STATE
from gui.clubs.restrictions import AccountClubLimits, DefaultAccountClubLimits
@ReprInjector.simple(('getStateID', 'state'))
class _AccountClubsState(object):
def __init__(self, stateID):
self.__stateID = stateID
def getStateID(self):
return self.__stateID
def getLimits(self):
return DefaultAccountClubLimits()
def update(self, clubsCtrl, privateData):
pass
@ReprInjector.withParent()
class UnavailableClubsState(_AccountClubsState):
def __init__(self):
super(UnavailableClubsState, self).__init__(CLIENT_CLUB_STATE.UNKNOWN)
def update(self, clubsCtrl, profile):
if profile.hasClub():
clubsCtrl._changeState(HasClubState(profile.getClubInfo(), profile.getInvites(), profile.getRestrictions()))
elif profile.wasSentApplication():
clubsCtrl._changeState(SentAppState(profile.getApplication(), profile.getInvites(), profile.getRestrictions()))
elif profile.isSynced():
clubsCtrl._changeState(NoClubState(profile.getInvites(), profile.getRestrictions()))
@ReprInjector.withParent(('getInvites', 'invites'))
class _AvailableClubState(_AccountClubsState):
def __init__(self, stateID, invites, restrs):
super(_AvailableClubState, self).__init__(stateID)
self._invites = invites
self._restrs = restrs
def getInvites(self):
return self._invites
def getLimits(self):
return AccountClubLimits(self._restrs)
def update(self, clubsCtrl, profile):
self._invites = profile.getInvites()
self._restrs = profile.getRestrictions()
@ReprInjector.withParent(('getClubDbID', 'clubDbID'), ('getJoiningTime', 'join'))
class HasClubState(_AvailableClubState):
def __init__(self, clubInfo, invites, restrs):
super(HasClubState, self).__init__(CLIENT_CLUB_STATE.HAS_CLUB, invites, restrs)
self.__clubInfo = clubInfo
def getClubDbID(self):
return self.__clubInfo.id
def getJoiningTime(self):
return self.__clubInfo.joined_at
def update(self, clubsCtrl, profile):
if not profile.isSynced():
clubsCtrl._changeState(UnavailableClubsState())
elif not profile.hasClub():
if profile.wasSentApplication():
clubsCtrl._changeState(SentAppState(profile.getApplication(), profile.getInvites(), profile.getRestrictions()))
else:
clubsCtrl._changeState(NoClubState(profile.getInvites(), profile.getRestrictions()))
else:
super(HasClubState, self).update(clubsCtrl, profile)
@ReprInjector.withParent()
class NoClubState(_AvailableClubState):
def __init__(self, invites, restrs):
super(NoClubState, self).__init__(CLIENT_CLUB_STATE.NO_CLUB, invites, restrs)
def update(self, clubsCtrl, profile):
if not profile.isSynced():
clubsCtrl._changeState(UnavailableClubsState())
elif profile.wasSentApplication():
clubsCtrl._changeState(SentAppState(profile.getApplication(), profile.getInvites(), profile.getRestrictions()))
elif profile.hasClub():
clubsCtrl._changeState(HasClubState(profile.getClubInfo(), profile.getInvites(), profile.getRestrictions()))
else:
super(NoClubState, self).update(clubsCtrl, profile)
@ReprInjector.withParent(('getClubDbID', 'club'), ('getSendingTime', 'sent'), ('getComment', 'comment'))
class SentAppState(_AvailableClubState):
def __init__(self, app, invites, restrs):
super(SentAppState, self).__init__(CLIENT_CLUB_STATE.SENT_APP, invites, restrs)
self._app = app
self._invites = invites
def getClubDbID(self):
return self._app.getClubDbID()
def getSendingTime(self):
return self._app.getTimestamp()
def getComment(self):
return self._app.getComment()
def update(self, clubsCtrl, profile):
if not profile.isSynced():
clubsCtrl._changeState(UnavailableClubsState())
elif profile.hasClub():
clubsCtrl._changeState(HasClubState(profile.getClubInfo(), profile.getInvites(), profile.getRestrictions()))
elif not profile.wasSentApplication():
clubsCtrl._changeState(NoClubState(profile.getInvites(), profile.getRestrictions()))
else:
super(SentAppState, self).update(clubsCtrl, profile)
|
[
"info@webium.sk"
] |
info@webium.sk
|
0ae864d0a423e68a0efa8509b43d6dea15776b19
|
4e89d371a5f8cca3c5c7e426af1bcb7f1fc4dda3
|
/python/python_test_002/04/02.py.backup.new
|
f2c15f2898e8db20233471a5f599c56036c773d1
|
[] |
no_license
|
bodii/test-code
|
f2a99450dd3230db2633a554fddc5b8ee04afd0b
|
4103c80d6efde949a4d707283d692db9ffac4546
|
refs/heads/master
| 2023-04-27T16:37:36.685521
| 2023-03-02T08:38:43
| 2023-03-02T08:38:43
| 63,114,995
| 4
| 1
| null | 2023-04-17T08:28:35
| 2016-07-12T01:29:24
|
Go
|
UTF-8
|
Python
| false
| false
| 442
|
new
|
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
import time
import os
def print_dir_info(dir_path):
for name in os.listdir(dir_path):
full_path = os.path.join(dir_path, name)
file_size = os.path.getsize(full_path)
mod_time = time.ctime(os.path.getmtime(full_path))
print("%-12s: %8d bytes, modified %s" % (name, file_size, mod_time))
if __name__ == '__main__':
print_dir_info('./')
|
[
"1401097251@qq.com"
] |
1401097251@qq.com
|
c8ed762106e501cfc1f293e9ce7a805a2f2f4ccf
|
a3a6eeb340735664c863952bf3c1e3070e61d987
|
/tests/test_bools.py
|
b32005d2de314894aec53fd4db70bb575825a6c1
|
[
"Apache-2.0"
] |
permissive
|
DalavanCloud/tmppy
|
dab593789d6e1ae6a3b25db6c4b41ce4fcfb378c
|
cdde676ba9d5011b7d2a46a9852e5986b90edbbc
|
refs/heads/master
| 2020-03-27T19:55:42.295263
| 2018-09-01T18:13:21
| 2018-09-01T18:13:21
| 147,021,787
| 1
| 0
|
Apache-2.0
| 2018-09-01T18:14:23
| 2018-09-01T18:14:23
| null |
UTF-8
|
Python
| false
| false
| 4,058
|
py
|
# Copyright 2017 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from py2tmp.testing import *
@assert_compilation_succeeds()
def test_not_false():
assert not False
@assert_compilation_succeeds()
def test_not_true():
assert (not True) == False
@assert_conversion_fails
def test_not_int_error():
assert not 1 # error: The "not" operator is only supported for booleans, but this value has type int.
@assert_conversion_fails
def test_and_toplevel_error():
assert True and True # error: The "and" operator is only supported in functions, not at toplevel.
@assert_compilation_succeeds()
def test_and_true_true():
def f(x: int):
return True
def g(x: int):
return True
def h(x: int):
assert f(5) and g(5)
return True
assert h(3)
@assert_compilation_succeeds()
def test_and_true_false():
def f(x: int):
return True
def g(x: int):
return False
def h(x: int):
assert (f(5) and g(5)) == False
return True
assert h(3)
@assert_compilation_succeeds()
def test_and_false_true():
def f(x: int):
return False
def g(x: int):
assert False
return True
def h(x: int):
assert (f(5) and g(5)) == False
return True
assert h(3)
@assert_compilation_succeeds()
def test_and_false_false():
def f(x: int):
return False
def g(x: int):
assert False
return False
def h(x: int):
assert (f(5) and g(5)) == False
return True
@assert_conversion_fails
def test_and_bool_int_error():
def h(x: int):
assert (True and
1) # error: The "and" operator is only supported for booleans, but this value has type int.
return True
@assert_conversion_fails
def test_and_int_bool_error():
def h(x: int):
assert (1 # error: The "and" operator is only supported for booleans, but this value has type int.
and True)
return True
@assert_conversion_fails
def test_or_toplevel_error():
assert True or False # error: The "or" operator is only supported in functions, not at toplevel.
@assert_compilation_succeeds()
def test_or_false_false():
def f(x: int):
return False
def g(x: int):
return False
def h(x: int):
assert (f(5) or g(5)) == False
return True
assert h(3)
@assert_compilation_succeeds()
def test_or_false_true():
def f(x: int):
return False
def g(x: int):
return True
def h(x: int):
assert f(5) or g(5)
return True
assert h(3)
@assert_compilation_succeeds()
def test_or_true_false():
def f(x: int):
return True
def g(x: int):
assert False
return False
def h(x: int):
assert f(5) or g(5)
return True
assert h(3)
@assert_compilation_succeeds()
def test_or_true_true():
def f(x: int):
return True
def g(x: int):
assert False
return True
def h(x: int):
assert f(5) or g(5)
return True
assert h(3)
@assert_conversion_fails
def test_or_bool_int_error():
def h(x: int):
assert (True or
1) # error: The "or" operator is only supported for booleans, but this value has type int.
return True
@assert_conversion_fails
def test_or_int_bool_error():
def h(x: int):
assert (1 # error: The "or" operator is only supported for booleans, but this value has type int.
or True)
return True
|
[
"poletti.marco@gmail.com"
] |
poletti.marco@gmail.com
|
fe2b1cc542f5ae3f9d81ae04c6c874bea64f10d4
|
6f05f7d5a67b6bb87956a22b988067ec772ba966
|
/data/train/python/4f956ef173469139d65286c38d6509ea89e8d0c5urls.py
|
4f956ef173469139d65286c38d6509ea89e8d0c5
|
[
"MIT"
] |
permissive
|
harshp8l/deep-learning-lang-detection
|
93b6d24a38081597c610ecf9b1f3b92c7d669be5
|
2a54293181c1c2b1a2b840ddee4d4d80177efb33
|
refs/heads/master
| 2020-04-07T18:07:00.697994
| 2018-11-29T23:21:23
| 2018-11-29T23:21:23
| 158,597,498
| 0
| 0
|
MIT
| 2018-11-21T19:36:42
| 2018-11-21T19:36:41
| null |
UTF-8
|
Python
| false
| false
| 4,309
|
py
|
from django.conf import settings
from django.conf.urls import url
from django.views.decorators.cache import cache_page
cache = cache_page(60 * 15) if not settings.DEBUG else lambda x: x
from . import views
FeedbackSubmissionView_view = cache(views.FeedbackSubmissionView.as_view())
ManageCourseListView_view = views.ManageCourseListView.as_view()
ManageNotRespondedListView_view = views.ManageNotRespondedListView.as_view()
UserListView_view = views.UserListView.as_view()
UserFeedbackListView_view = views.UserFeedbackListView.as_view()
UserFeedbackView_view = views.UserFeedbackView.as_view()
RespondFeedbackView_view = views.respond_feedback_view_select(
views.RespondFeedbackView.as_view(),
views.RespondFeedbackViewAjax.as_view()
)
FeedbackTagView_view = views.FeedbackTagView.as_view()
PATH_REGEX = r'[\w\d\-./]'
MANAGE = r'^manage/'
MANAGE_SITE = MANAGE + r'(?P<site_id>\d+)/'
urlpatterns = [
# Aplus feedback submission
url(r'^feedback/$',
FeedbackSubmissionView_view,
name='submission'),
url(r'^feedback/(?P<path_key>{path_regex}+)$'.format(path_regex=PATH_REGEX),
FeedbackSubmissionView_view,
name='submission'),
# Feedback management and responding
url(r'^manage/$',
views.ManageSiteListView.as_view(),
name='site-list'),
url(r'^manage/courses/$',
ManageCourseListView_view,
name='course-list'),
url(r'^manage/courses/(?P<site_id>\d+)/$',
ManageCourseListView_view,
name='course-list'),
url(r'^manage/(?P<course_id>\d+)/clear-cache/$',
views.ManageClearCacheView.as_view(),
name='clear-cache'),
url(r'^manage/(?P<course_id>\d+)/update-studenttags/$',
views.ManageUpdateStudenttagsView.as_view(),
name='update-studenttags'),
url(r'^manage/(?P<course_id>\d+)/unread/$',
ManageNotRespondedListView_view,
name='notresponded-course'),
url(r'^manage/(?P<course_id>\d+)/unread/(?P<path_filter>{path_regex}*)$'.format(path_regex=PATH_REGEX),
ManageNotRespondedListView_view,
name='notresponded-course'),
url(r'^manage/(?P<course_id>\d+)/feedbacks/$',
views.ManageFeedbacksListView.as_view(),
name='list'),
url(r'^manage/(?P<course_id>\d+)/user/$',
UserListView_view,
name='user-list'),
url(r'^manage/(?P<course_id>\d+)/byuser/(?P<user_id>\d+)/$',
UserFeedbackListView_view,
name='byuser'),
url(r'^manage/(?P<course_id>\d+)/byuser/(?P<user_id>\d+)/(?P<exercise_id>\d+)/$',
UserFeedbackView_view,
name='byuser'),
url(r'^manage/(?P<course_id>\d+)/byuser/(?P<user_id>\d+)/(?P<exercise_id>\d+)/(?P<path_filter>{path_regex}*)$'.format(path_regex=PATH_REGEX),
UserFeedbackView_view,
name='byuser'),
url(r'^manage/(?P<course_id>\d+)/tags/$',
views.FeedbackTagListView.as_view(),
name='tags'),
url(r'^manage/(?P<course_id>\d+)/tags/(?P<tag_id>\d+)/$',
views.FeedbackTagEditView.as_view(),
name='tags-edit'),
url(r'^manage/(?P<course_id>\d+)/tags/(?P<tag_id>\d+)/remove/$',
views.FeedbackTagDeleteView.as_view(),
name='tags-remove'),
url(r'^manage/respond/(?P<feedback_id>\d+)/$',
RespondFeedbackView_view,
name='respond'),
url(r'^manage/tag/(?P<feedback_id>\d+)/$',
views.FeedbackTagView.as_view(),
name='tag-list'),
url(r'^manage/tag/(?P<feedback_id>\d+)/(?P<tag_id>\d+)/$',
views.FeedbackTagView.as_view(),
name='tag'),
# support for old urls
url(r'^manage/notresponded/course/(?P<course_id>\d+)/$',
ManageNotRespondedListView_view),
url(r'^manage/notresponded/course/(?P<course_id>\d+)/(?P<path_filter>{path_regex}*)$'.format(path_regex=PATH_REGEX),
ManageNotRespondedListView_view),
url(r'^manage/user/(?P<course_id>\d+)/$',
UserListView_view),
url(r'^manage/byuser/(?P<course_id>\d+)/(?P<user_id>\d+)/$',
UserFeedbackListView_view),
url(r'^manage/byuser/(?P<course_id>\d+)/(?P<user_id>\d+)/(?P<exercise_id>\d+)/$',
UserFeedbackView_view),
url(r'^manage/byuser/(?P<course_id>\d+)/(?P<user_id>\d+)/(?P<exercise_id>\d+)/(?P<path_filter>{path_regex}*)$'.format(path_regex=PATH_REGEX),
UserFeedbackView_view),
]
|
[
"aliostad+github@gmail.com"
] |
aliostad+github@gmail.com
|
4dbd3efc8708bcb4d34ff55293169dcabeba1df4
|
6238dc5b5818f54295547cf4cb1afa5553ddfb94
|
/taobao/guagua/views.py
|
0f7415da4a50128ac7344cc3b1811ed0dd18a060
|
[] |
no_license
|
liaosiwei/guagua
|
8208bb82b1df5506dcb86c1a7094c849ea5576a6
|
ee6025813e83568dc25beb52279c86f8bd33f1a4
|
refs/heads/master
| 2016-09-06T16:45:00.798633
| 2013-05-03T04:02:35
| 2013-05-03T04:02:35
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,383
|
py
|
# coding=UTF-8
import base64
from random import randint
from django.shortcuts import render
from django.utils import simplejson
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib.auth.forms import PasswordChangeForm
from django.contrib.auth.models import User
from django.contrib.auth import login, authenticate
from utility import *
def fetchuserinfo(request):
if request.method == 'GET':
get = request.GET.copy()
if get.has_key('top_session'):
sessionkey = get['top_session']
if get.has_key('top_parameters'):
para_str = base64.b64decode(get['top_parameters'])
para_dict = dict([item.split('=') for item in para_str.split('&')])
user = User.objects.create_user(para_dict['visitor_nick'], password=para_dict['visitor_nick'])
profile = user.get_profile()
profile.taobao_id = para_dict['visitor_id']
profile.taobao_nick = para_dict['visitor_nick']
profile.sessionkey = sessionkey
profile.start_date = user.date_joined
profile.save()
user = authenticate(username = para_dict['visitor_nick'], password = para_dict['visitor_nick'])
login(request, user)
#login(request, user)
return HttpResponseRedirect('/pwd_change/')
def base(request):
return render(request, 'base.html')
def index(request):
return render(request, 'index.html')
def plot(request):
return render(request, 'plot.html')
def ajax_plotdata(request):
to_return = {'stat': 'failed', 'data': ''}
# fetch data by top interface, now generate random data
length = 80
d = [randint(0, 80) for i in range(length)]
data = [[i, sum(d[:i+1])] for i in range(length)]
to_return['stat'] = 'success'
to_return['data'] = data
serialized = simplejson.dumps(to_return)
return HttpResponse(serialized, mimetype="application/json")
def pie(request):
return render(request, 'pie.html')
def ajax_piedata(request):
to_return = {'stat': 'failed', 'data': ''}
to_return['data'] = [{'label': u'武汉', 'data': 10}, {'label': u'北京', 'data': 300}, {'label': u'上海', 'data': 420}, {'label': u'广州', 'data': 403}]
serialized = simplejson.dumps(to_return)
return HttpResponse(serialized, mimetype="application/json")
|
[
"liaosiweiorxiaowei@gmail.com"
] |
liaosiweiorxiaowei@gmail.com
|
8d2d22353601d0e01717d35b5dcc9e799f41999e
|
21164ca369ea3a1674c3a03bbebcd9c830d0864c
|
/rules/php/CVI_1010.py
|
52a1c4d2d3ae1e95fdb389413593d1d3962c7073
|
[
"MIT"
] |
permissive
|
IMULMUL/Cobra-W
|
a02d6b512843c96685550a98d74f9d8ebe4bdfaf
|
de65466e53c8bd8e29a5f3e16ab91146d354c53f
|
refs/heads/master
| 2023-07-08T19:14:35.698641
| 2023-06-27T09:31:15
| 2023-06-27T09:31:15
| 202,911,104
| 0
| 0
|
MIT
| 2023-06-27T23:39:53
| 2019-08-17T17:17:37
|
Python
|
UTF-8
|
Python
| false
| false
| 1,204
|
py
|
# -*- coding: utf-8 -*-
"""
auto rule template
~~~~
:author: LoRexxar <LoRexxar@gmail.com>
:homepage: https://github.com/LoRexxar/Kunlun-M
:license: MIT, see LICENSE for more details.
:copyright: Copyright (c) 2017 LoRexxar. All rights reserved
"""
from utils.api import *
class CVI_1010():
"""
rule class
"""
def __init__(self):
self.svid = 1010
self.language = "php"
self.author = "LoRexxar/wufeifei"
self.vulnerability = "LDAPI"
self.description = "LDAP注入可能导致ldap的账号信息泄露"
self.level = 3
# status
self.status = True
# 部分配置
self.match_mode = "function-param-regex"
self.match = r"(ldap_add|ldap_delete|ldap_list|ldap_read|ldap_search|ldap_bind)"
# for solidity
self.match_name = None
self.black_list = None
# for chrome ext
self.keyword = None
# for regex
self.unmatch = None
self.vul_function = None
def main(self, regex_string):
"""
regex string input
:regex_string: regex match string
:return:
"""
pass
|
[
"lorexxar@gmail.com"
] |
lorexxar@gmail.com
|
143c3d4725a20e10ab6179d77ba2c658c4f44e7e
|
e484393a06ff65b9432116a5a08077c4431fc17f
|
/pipelines.py
|
b684ded6aa835201d1e7d97df670eb9c4df53974
|
[] |
no_license
|
knighton/seq_clf
|
e9adf4301844377b090601b26389ea1e4c17100f
|
553aa4f990fb072d08c62667cdb179a4aa5b31a2
|
refs/heads/master
| 2016-09-06T15:58:22.834655
| 2015-07-26T03:59:52
| 2015-07-26T03:59:52
| 39,712,897
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,631
|
py
|
from camacho.base import Transformer
from camacho.preprocess.sequence.coders import IntCoder
from camacho.preprocess.binarize.embeddings import Word2Vec
from camacho.preprocess.binarize.onehot import AtomBinarizer
from camacho.preprocess.sequence.max_length import MaxLength
from camacho.preprocess.sequence.min_length import MinLength
import numpy as np
def zh_int():
data = [
MaxLength(256),
MinLength(256),
IntCoder(min_freq=10),
]
labels = [
AtomBinarizer(),
]
need_to_embed = True
return data, labels, need_to_embed
class Int2Str(Transformer):
"""
Word2Vec expects string inputs.
"""
def transform(self, nnn):
return map(lambda nn: map(str, nn), nnn)
def inverse_transform(self, sss):
return map(lambda ss: map(int, ss), sss)
def zh_vec_3d():
data = [
MaxLength(256),
MinLength(256),
IntCoder(min_freq=10),
Int2Str(),
Word2Vec(16),
]
labels = [
AtomBinarizer(),
]
need_to_embed = False
return data, labels, need_to_embed
class Flatten(Transformer):
def transform(self, aaaa):
rrr = []
for aaa in aaaa:
rr = []
for aa in aaa:
rr.extend(aa)
rrr.append(rr)
return np.array(rrr)
def zh_vec_2d():
data = [
MaxLength(256),
MinLength(256),
IntCoder(min_freq=10),
Int2Str(),
Word2Vec(16),
Flatten(),
]
labels = [
AtomBinarizer(),
]
need_to_embed = False
return data, labels, need_to_embed
|
[
"iamknighton@gmail.com"
] |
iamknighton@gmail.com
|
316836557b9fa1f0953b5a1ffcc5a776f4ef8968
|
e0731ac7bd6a9fcb386d9c5d4181c9d549ab1d02
|
/desafio23.py
|
3014731320bdb0ff34ffd742354f1f5a90a9b917
|
[] |
no_license
|
lportinari/Desafios-Python-Curso-em-Video
|
3ab98b87a2178448b3e53031b86522558c31c099
|
cd7662ddfe371e48e5aabc6e86e23dc6337405fb
|
refs/heads/master
| 2020-04-29T11:09:25.689901
| 2019-06-23T23:58:06
| 2019-06-23T23:58:06
| 176,087,390
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 820
|
py
|
"""
Exercício Python 023: Faça um programa que leia um número de 0 a 9999 e mostre na tela cada um dos dígitos separados.
"""
print('.:DESCUBRA A UNIDADE, DEZENA, CENTENA E MILHAR DE UM NÚMERO:.')
n = int(input('Digite um número de 0 a 9999: '))
u = n // 1 % 10
d = n // 10 % 10
c = n // 100 % 10
m = n // 1000 % 10
#Módulo de cores
cores = {'limpa':'\033[m',
'azul':'\033[34m',
'verde':'\033[32m',
'amarelo':'\033[33m',
'roxo':'\033[35m'}
print('Analisando o número {}'.format(n))
print('{}Unidade{}: {}'.format(cores['azul'], cores['limpa'], u))
print('{}Dezena{}: {}'.format(cores['verde'], cores['limpa'], d))
print('{}Centena{}: {}'.format(cores['amarelo'], cores['limpa'], c))
print('{}Milhar{}: {}'.format(cores['roxo'], cores['limpa'], m))
|
[
"noreply@github.com"
] |
lportinari.noreply@github.com
|
765a43a4671b375f00fee86a67821c3abe3fe0af
|
a79d7f5d0ff7f4ad2c5755f74a8685123eb79157
|
/week3/sigma.py
|
f411312b7d7dc6645756ecb7c536a902bd38f241
|
[] |
no_license
|
ArtamoshinN/python
|
54c4adf5359fd18c55ce8268c4dde89d1e8b203c
|
3c9c69f06e6d1ab890ed7ae057bf331d2d007539
|
refs/heads/master
| 2021-01-24T03:03:49.064277
| 2018-07-03T18:47:56
| 2018-07-03T18:47:56
| 122,875,295
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 254
|
py
|
import math
x = int(input())
i = 0
kv = 0
sum = 0
while x != 0:
kv = kv + x ** 2
sum = sum + x
x = int(input())
i += 1
s = float(sum / i)
sigma = float(math.sqrt((kv - 2 * s * sum + i * s ** 2) / (i - 1)))
print('{0:.11f}'.format(sigma))
|
[
"nikita@MacBook-Pro-Markovic-2.local"
] |
nikita@MacBook-Pro-Markovic-2.local
|
567f7dbea1bbe7373fa2366bb54bdc714defee20
|
fc4aaf15ef2b10c89728651316300ada27f14ae3
|
/Loginapp/views.py
|
c9b90dbe4cb42e79dd883f1bc474e925c892da44
|
[] |
no_license
|
ethicalrushi/seller
|
7f6231e710b32e8d7700e32e321879728de65546
|
9473fcb6595c27c7adbcea24990b6e8f006d3e8a
|
refs/heads/master
| 2020-03-08T04:00:59.089892
| 2018-04-04T17:48:19
| 2018-04-04T17:48:19
| 126,335,389
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,542
|
py
|
from django.shortcuts import render
from django.contrib.auth.models import User
from .forms import UserForm
from django.contrib.auth.decorators import login_required
from django.contrib.auth import login,logout,authenticate
from django.http import HttpResponseRedirect, HttpResponse
from django.urls import reverse
# Create your views here.
def register(request):
registered = False
if request.method == "POST":
user_form = UserForm(data=request.POST)
if user_form.is_valid():
user = user_form.save()
user.set_password(user.password)
user.save()
registered = True
else:
print(user_form.errors)
else:
user_form = UserForm()
return render(request,'Loginapp/registeration.html',
{'user_form':user_form,
'registered':registered,
})
def user_login(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(username=username, password=password)
if user:
if user.is_active:
login(request,user)
return HttpResponseRedirect('/product/')
else:
return HttpResponse("Account Not Active")
else:
print("Someone tried to login and failed!")
return HttpResponse("Invalid login details")
else:
return render(request,'Loginapp/login.html')
@login_required
def user_logout(request):
logout(request)
return render(request,'basic_app/index.html')
|
[
"pupalerushikesh@gmail.com"
] |
pupalerushikesh@gmail.com
|
e8e8dbb1faee07802f147df09b256cc61a91d28a
|
9676cae4726eda7308502b0b5753544cef20921c
|
/image_to_features.py
|
edc88e1540a9f3223206e03a9c3f8c57184160fe
|
[] |
no_license
|
amnh-sciviz/image-collection
|
f8f4b88e1c5c3b8feb975225a4cac97402098410
|
497c7bf21b1b7c392a3219b69acb6981e9c3cebc
|
refs/heads/master
| 2020-05-02T07:34:20.706841
| 2019-06-13T18:57:12
| 2019-06-13T18:57:12
| 177,821,513
| 6
| 3
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,152
|
py
|
# -*- coding: utf-8 -*-
# Adapted from:
# https://github.com/ml4a/ml4a-guides/blob/master/notebooks/image-search.ipynb
import argparse
import bz2
import glob
import numpy as np
import os
import pickle
from sklearn.decomposition import PCA
import sys
from lib.utils import *
# input
parser = argparse.ArgumentParser()
parser.add_argument('-in', dest="INPUT_FILES", default="images/photographic_thumbnails/*.jpg", help="Input file pattern")
parser.add_argument('-size', dest="IMAGE_SIZE", default="224x224", help="Resize images to this size")
parser.add_argument('-pca', dest="PCA_COMPONENTS", default=256, type=int, help="Principal component analysis (PCA) components to reduce down to")
parser.add_argument('-out', dest="OUTPUT_FILE", default="output/photographic_features.p.bz2", help="Pickle cache file to store features")
a = parser.parse_args()
os.environ["KERAS_BACKEND"] = "plaidml.keras.backend"
import keras
from keras.preprocessing import image
from keras.applications.imagenet_utils import preprocess_input
from keras.models import Model
IMAGE_SIZE = tuple([int(d) for d in a.IMAGE_SIZE.strip().split("x")])
# Read files
files = glob.glob(a.INPUT_FILES)
files = sorted(files)
fileCount = len(files)
print("Found %s files" % fileCount)
# Load model, feature extractor
model = keras.applications.VGG16(weights='imagenet', include_top=True)
feat_extractor = Model(inputs=model.input, outputs=model.get_layer("fc2").output)
print("Extracting features from each image...")
features = np.zeros((fileCount, 4096), dtype=np.float32)
for i, fn in enumerate(files):
im = image.load_img(fn, target_size=model.input_shape[1:3])
x = image.img_to_array(im)
x = np.expand_dims(x, axis=0)
x = preprocess_input(x)
feat = feat_extractor.predict(x)[0]
features[i] = feat
printProgress(i+1, fileCount)
print("Reducing feature vectors down to %s features..." % a.PCA_COMPONENTS)
pca = PCA(n_components=a.PCA_COMPONENTS)
pca.fit(features)
pca_features = pca.transform(features)
print("Saving features file %s..." % a.OUTPUT_FILE)
makeDir(a.OUTPUT_FILE)
pickle.dump(pca_features, bz2.open(a.OUTPUT_FILE, 'wb'))
print("Done.")
|
[
"brian@youaremyjoy.org"
] |
brian@youaremyjoy.org
|
8647ea711a5c6d6c875b5c47c301901ed1ec3b8f
|
dffd7156da8b71f4a743ec77d05c8ba031988508
|
/ac/nikkei2019-2-qual/nikkei2019_2_qual_b/8360228.py
|
b7005d58d66843ad71530b0a48a1340716f7b16f
|
[] |
no_license
|
e1810/kyopro
|
a3a9a2ee63bc178dfa110788745a208dead37da6
|
15cf27d9ecc70cf6d82212ca0c788e327371b2dd
|
refs/heads/master
| 2021-11-10T16:53:23.246374
| 2021-02-06T16:29:09
| 2021-10-31T06:20:50
| 252,388,049
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 344
|
py
|
n, *a = map(int, open(0).read().split())
if a[0]!=0:
print(0)
exit()
b = [0]*n
for i in a: b[i]+=1
if b[0]!=1:
print(0)
exit()
ans = 1
i = 0
while i<n-1:
if b[i]==0:
if sum(b[i:])>0:
print(0)
exit()
else:
break
ans *= b[i]**b[i+1]
i += 1
print(ans%998244353)
|
[
"v.iceele1810@gmail.com"
] |
v.iceele1810@gmail.com
|
70f9502dd64dd7794bbebc3848a84c585299fe52
|
ca7aa979e7059467e158830b76673f5b77a0f5a3
|
/Python_codes/p03944/s429630442.py
|
448282dd05c588cb880bfe4c06969e1a1107c06b
|
[] |
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
| 640
|
py
|
W,H,N = map(int,input().split())
lst = [list(map(int,input().split())) for i in range(N)]
#print(W,H,N)
#print(lst)
#lst = sorted(lst, key=lambda x: x[2])
#print(lst)
Wst = [1]*W
Hst = [1]*H
for i in range(N):
if lst[i][2] == 1:
for j in range(lst[i][0]):
Wst[j] = 0
if lst[i][2] == 2:
#print(lst[i][0],W)
for j in range(lst[i][0],W):
Wst[j] = 0
if lst[i][2] == 3:
for j in range(lst[i][1]):
Hst[j] = 0
if lst[i][2] == 4:
#print(lst[i][0],W)
for j in range(lst[i][1],H):
Hst[j] = 0
#print(Wst,Hst)
print(sum(Wst)*sum(Hst))
|
[
"66529651+Aastha2104@users.noreply.github.com"
] |
66529651+Aastha2104@users.noreply.github.com
|
58d298ec0522399c2673710a99ea5800b973b8b4
|
ca7aa979e7059467e158830b76673f5b77a0f5a3
|
/Python_codes/p03328/s169266542.py
|
f38d282a01fae28bcf1d5c8f04c9ec5cb6991a81
|
[] |
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
| 239
|
py
|
a, b = list(map(int, input().split()))
a_height = 0
b_height = 0
sa = abs(a - b)
for i in range(1, sa):
a_height += i
# for i in range(1, sa + 1):
# b_height += i
# print(a_height)
# print(b_height)
print(a_height - a)
|
[
"66529651+Aastha2104@users.noreply.github.com"
] |
66529651+Aastha2104@users.noreply.github.com
|
d6c18edef9ba8d5cfaf660eac3864401b7c94e93
|
41ca95879e0f0908ba824074abd43e76177a0d54
|
/google-datacatalog-rdbms-connector/tests/google/datacatalog_connectors/rdbms/prepare/sql_objects/sql_objects_assembled_entry_factory_test.py
|
c235001590ab3040f6f42cc1ba8bcdd5b71bbde1
|
[
"Apache-2.0"
] |
permissive
|
GoogleCloudPlatform/datacatalog-connectors-rdbms
|
b3765cd0789cc803abe554d00a266fcab1388f88
|
3b1a2729896542f36487e84a13e80dcb6c2aa3d9
|
refs/heads/master
| 2023-05-15T16:43:21.811232
| 2021-12-06T22:25:54
| 2021-12-06T22:25:54
| 259,464,905
| 73
| 63
|
Apache-2.0
| 2021-12-06T22:25:55
| 2020-04-27T21:51:36
|
Python
|
UTF-8
|
Python
| false
| false
| 3,725
|
py
|
#!/usr/bin/python
#
# 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 mock
import os
import unittest
from google.cloud import datacatalog
from google.datacatalog_connectors.commons_test import utils
from google.datacatalog_connectors.rdbms.prepare.sql_objects import \
sql_objects_assembled_entry_factory
class SQLObjectsAssembledEntryFactoryTestCase(unittest.TestCase):
__MODULE_PATH = '{}/..'.format(os.path.dirname(os.path.abspath(__file__)))
__PROJECT_ID = 'test_project'
__LOCATION_ID = 'location_id'
__ENTRY_GROUP_ID = 'oracle'
__MOCKED_ENTRY_PATH = 'mocked_entry_path'
__METADATA_SERVER_HOST = 'metadata_host'
__PREPARE_PACKAGE = 'google.datacatalog_connectors.rdbms.prepare'
@mock.patch('{}.sql_objects.sql_objects_datacatalog_tag_factory'
'.SQLObjectsDataCatalogTagFactory'.format(__PREPARE_PACKAGE))
@mock.patch('{}.sql_objects.sql_objects_datacatalog_entry_factory'
'.SQLObjectsDataCatalogEntryFactory'.format(__PREPARE_PACKAGE))
def setUp(self, mock_entry_factory, mock_tag_factory):
metadata = \
utils.Utils.convert_json_to_object(
self.__MODULE_PATH,
'metadata_with_sql_objects.json')['sql_objects']
sql_objects_config = \
utils.Utils.convert_json_to_object(self.__MODULE_PATH,
'sql_objects_config.json')
self.__sql_objects_config = sql_objects_config
self.__metadata = metadata
self.__entry_factory = mock_entry_factory.return_value
self.__tag_factory = mock_tag_factory.return_value
tag_templates_dict = {
'{}_{}_metadata'.format(self.__ENTRY_GROUP_ID, 'function'):
datacatalog.TagTemplate(),
'{}_{}_metadata'.format(self.__ENTRY_GROUP_ID, 'stored_procedure'):
datacatalog.TagTemplate()
}
self.__factory = sql_objects_assembled_entry_factory. \
SQLObjectsAssembledEntryFactory(
self.__PROJECT_ID,
self.__LOCATION_ID,
self.__METADATA_SERVER_HOST,
self.__ENTRY_GROUP_ID,
sql_objects_config,
tag_templates_dict)
def test_constructor_should_set_instance_attributes(self):
attrs = self.__factory.__dict__
self.assertEqual(
self.__entry_factory, attrs['_SQLObjectsAssembledEntryFactory'
'__datacatalog_entry_factory'])
def test_make_entries_for_sql_objects_should_create_entries(self):
entry_factory = self.__entry_factory
entry_factory.\
make_entry_for_sql_object.return_value = 'f_entry_id', {}
entry_factory.\
make_entry_for_sql_object.return_value = 'sp_entry_id', {}
tag_factory = self.__tag_factory
tag_factory.make_tags_for_sql_object.return_value = [{}]
assembled_entries = self.__factory.make_entries(self.__metadata)
self.assertEqual(4, len(assembled_entries))
self.assertEqual(1, len(assembled_entries[0].tags))
self.assertEqual(1, len(assembled_entries[1].tags))
|
[
"noreply@github.com"
] |
GoogleCloudPlatform.noreply@github.com
|
9dc682d35cab375572088c33f58ee8f39c4985f7
|
6930a434c0506d44bf8a8e81cb86e95c219c3a77
|
/python/学生信息管理系统/更改全部信息的管理.py
|
7949250894e7e403136252e8746a824fcf286b81
|
[] |
no_license
|
Conquerk/test
|
ed15d5603538340559556c9e0f20cc61ad3e4486
|
7ff42c99b8a2132c6dd1c73315ff95cfef63a8f6
|
refs/heads/master
| 2020-04-19T01:47:28.322929
| 2019-01-28T01:52:00
| 2019-01-28T01:52:00
| 167,882,236
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,118
|
py
|
l=[]
def guanli():
while True:
print("+"+"-"*20+"+")
print("|"+str("1.添加学生信息").center(14)+"|")
print("|"+str("2.显示学生信息").center(14)+"|")
print("|"+str("3.删除学生信息").center(14)+"|")
print("|"+str("4.修改学生成绩").center(14)+"|")
print("|"+str("q.退出").center(18)+"|")
print("+"+"-"*20+"+")
x=input("输入菜单功能:")
if x=="1":
myinput()
elif x=="2":
mybiaoge()
elif x=="3":
delete()
elif x=="4":
change()
elif x=="q":
break
def myinput():
global l
while True:
n=input("请输入姓名:")
if not n :
break
s=int(input("请输入年龄:"))
a=int(input("请输入成绩:"))
d={}
d["name"]=n
d["age"]=s
d["score"]=a
l.append(d)
def mybiaoge():
global l
print("+-------------+------------+------------+")
print("| name | age | score |")
print("+-------------+------------+------------+")
for x in l :
line="|"+x["name"].center(11)
line+="|"+str(x["age"]).center(12)
line+="|"+str(x["score"]).center(12)+"|"
print(line)
print("+-------------+------------+------------+")
def delete():
global l
i=0
y=input("请输入删除的学生信息")
for x in l: # a aa aaa aaaa
i+=1 # 1 2 3 4
if y in x["name"]: # aa
del l[(i-1)] # 1
def change():
global l
y=input("请输入要修改学生信息的名字:")
for x in l :
if y in x["name"]:
a=input("请输入要修改的信息")
if a =="name":
n=input("新的名字")
x["name"]=n
if a =="age":
p=int(input("请输入新的年龄"))
x["age"]=p
if a=="score":
t=int(input("请输入新的成绩:"))
x["score"]=t
guanli()
|
[
"tarena@tedu.cn"
] |
tarena@tedu.cn
|
dad36a3496dbc38de44bdbea546b2ae30e6a8a21
|
092b753aa30b5a050ad6e502a8e46cf5d88ac3db
|
/easy_7.py
|
ed00499027f5c7f9482f42e8e7c7740108a31118
|
[] |
no_license
|
BrettMcGregor/dailyprogrammer
|
2ba33e7501c1198c69ae391ec85d36de1511d9cc
|
f954ffcbb6430be0a96115246bed2fbe20ef0132
|
refs/heads/master
| 2020-03-21T06:41:53.490354
| 2018-07-17T04:45:31
| 2018-07-17T04:45:31
| 138,235,896
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,852
|
py
|
# Write a program that can translate Morse code in the format of
# ...---...
#
# A space and a slash will be placed between words. ..- / --.-
#
# For bonus, add the capability of going from a string to Morse code.
#
# Super-bonus if your program can flash or beep the Morse.
#
# This is your Morse to translate:
code = (".... . .-.. .-.. --- / -.. .- .. .-.. -.-- / .--. .-. --- --. .-. .- -- -- . .-. / "
"--. --- --- -.. / .-.. ..- -.-. -.- / --- -. / - .... . / "
"-.-. .... .- .-.. .-.. . -. --. . ... / - --- -.. .- -.--")
morse = {'A':'.-', 'B':'-...', 'C':'-.-.', 'D':'-..', 'E':'.', 'F':'..-.',
'G':'--.', 'H':'....', 'I':'..', 'J':'.---', 'K':'-.-', 'L':'.-..',
'M':'--', 'N':'-.', 'O':'---', 'P':'.--.', 'Q':'--.-', 'R':'.-.',
'S':'...', 'T':'-', 'U':'..-', 'V':'...-', 'W':'.--', 'X':'-..-',
'Y':'-.--', 'Z':'--..', '1':'.----', '2':'..---', '3':'...--',
'4':'....-', '5':'.....', '6':'-....', '7':'--...', '8':'---..',
'9':'----.', '0':'-----', ' ':'/'}
def morse_decode(source):
words = []
decode = []
for word in source.split(" / "):
words.append(word.split(" "))
for word in words:
string = ""
for let in word:
for k, v in morse.items():
if let == v:
string += k
decode.append(string.lower())
return " ".join(decode)
def morse_code(s):
encode = []
out_string = ""
for letter in s:
for key in morse.keys():
if letter.upper() == key:
out_string += f"{morse[key]} "
encode.append(out_string)
return " ".join(encode)
# print(morse_code(input("Enter text to convert to Morse code\n> ")))
print(morse_decode(code))
print(morse_code(morse_decode(code)))
print(morse_decode(morse_code(morse_decode(code))))
|
[
"brett.w.mcgregor@gmail.com"
] |
brett.w.mcgregor@gmail.com
|
5c63e3a2f515983d52df167049fb851ea942caad
|
ac5e52a3fc52dde58d208746cddabef2e378119e
|
/exps-gsn-edf/gsn-edf_ut=2.0_rd=1_rw=0.06_rn=4_u=0.075-0.35_p=harmonic-2/sched=RUN_trial=0/sched.py
|
c5eaad177d1026b0984b6b39b4a8cf663c74b219
|
[] |
no_license
|
ricardobtxr/experiment-scripts
|
1e2abfcd94fb0ef5a56c5d7dffddfe814752eef1
|
7bcebff7ac2f2822423f211f1162cd017a18babb
|
refs/heads/master
| 2023-04-09T02:37:41.466794
| 2021-04-25T03:27:16
| 2021-04-25T03:27:16
| 358,926,457
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 336
|
py
|
-X FMLP -Q 0 -L 2 81 400
-X FMLP -Q 0 -L 2 55 400
-X FMLP -Q 0 -L 2 46 175
-X FMLP -Q 1 -L 1 33 175
-X FMLP -Q 1 -L 1 29 100
-X FMLP -Q 1 -L 1 26 125
-X FMLP -Q 2 -L 1 23 300
-X FMLP -Q 2 -L 1 20 100
-X FMLP -Q 2 -L 1 15 175
-X FMLP -Q 3 -L 1 14 100
-X FMLP -Q 3 -L 1 14 150
-X FMLP -Q 3 -L 1 14 125
|
[
"ricardo.btxr@gmail.com"
] |
ricardo.btxr@gmail.com
|
8b8b3facdeca2ad375851d0e4af14adaf96a11b5
|
f547959acabd13b3a6419fc149573fbf961b4cad
|
/examples/make_rkoc_python.py
|
dac1bfa7a52c0b2b4662dd33727b3a462a5e21de
|
[
"BSD-3-Clause",
"BSD-2-Clause"
] |
permissive
|
ketch/nodepy
|
b69fc85c52993f8872ae9fcad52a5082c0edc0eb
|
a78dd5c5021a0dbf7952c3614996315dbed5a642
|
refs/heads/master
| 2023-07-11T18:47:35.839942
| 2023-06-22T18:02:21
| 2023-06-26T14:03:44
| 4,030,392
| 57
| 18
|
NOASSERTION
| 2023-06-26T14:03:46
| 2012-04-15T06:59:24
|
Python
|
UTF-8
|
Python
| false
| false
| 939
|
py
|
#Make python script to evaluate order conditions
#for RK methods
from nodepy import rooted_trees as rt
from nodepy import runge_kutta_method as rk
p_max=15
f=open('oc_butcher.py','w')
f.write("def order(rk,tol=1.e-13):\n")
f.write(" from numpy import dot,zeros,all,sum,abs\n")
f.write(" coneq = zeros((1000))\n")
f.write(" A=rk.A\n b=rk.b\n c=rk.c\n")
f.write(" coneq[0]=sum(b)-1.\n")
f.write(" if any(abs(coneq)>tol):\n")
f.write(" return 0")
for ip in range(2,p_max):
print 'Generating order '+str(ip)+' conditions...'
ioc=0
f.write("\n # order "+str(ip)+" conditions:\n")
forest = rt.list_trees(ip)
for tree in forest:
oc=rk.elementary_weight_str(tree,style='python')
rhs =str(rt.Emap(tree))
f.write(" coneq["+str(ioc)+"]="+oc+"-"+rhs+".\n")
ioc+=1
f.write(" if any(abs(coneq)>tol):\n")
f.write(" return "+str(ip-1))
f.close()
|
[
"dketch@gmail.com"
] |
dketch@gmail.com
|
c9a49f1bc21897f0928af4cf213aeb52abd7faa1
|
694d57c3e512ce916269411b51adef23532420cd
|
/leetcode/325maximum_size_subarray_sum_equals_k.py
|
9fa88d782d3c6059f19e3c7ea9b11bb698fabf6f
|
[] |
no_license
|
clovery410/mycode
|
5541c3a99962d7949832a0859f18819f118edfba
|
e12025e754547d18d5bb50a9dbe5e725fd03fd9c
|
refs/heads/master
| 2021-05-16T02:46:47.996748
| 2017-05-10T23:43:50
| 2017-05-10T23:43:50
| 39,235,141
| 1
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,021
|
py
|
class Solution(object):
# brute-force solution, TLE
def maxSubArrayLen(self, nums, k):
max_len = 0
l = len(nums)
for start in xrange(l):
cur_total = 0
for end in xrange(start, l):
cur_total += nums[end]
if cur_total == k:
max_len = max(max_len, end - start + 1)
return max_len
# soltion2
def maxSubArrayLen2(self, nums, k):
nums = [0] + nums
sum_record = {}
cur_total = 0
max_len = 0
for j in xrange(len(nums)):
cur_total += nums[j]
pre_sum = cur_total - k
if pre_sum in sum_record:
max_len = max(max_len, j - sum_record[pre_sum])
if cur_total not in sum_record:
sum_record[cur_total] = j
return max_len
if __name__ == "__main__":
sol = Solution()
nums = [1,-1,5,-2,3]
print sol.maxSubArrayLen(nums, 3)
print sol.maxSubArrayLen2(nums, 3)
|
[
"seasoul410@gmail.com"
] |
seasoul410@gmail.com
|
bae4523c4207c1bbe212d24575d269a923c31e3d
|
96b0473aedcbcd2c656d3c86819a93c5c90c2c9f
|
/PySideTutorials/modules/QCompleter/QCompleter_custom completer rules.py
|
72b79e179e2b970cc1f1ca14892a9a8db44c2683
|
[] |
no_license
|
mikebourbeauart/Tutorials
|
e2e1c48f4268b75bf6add1c4aee286b83886175b
|
8a70f0563198bee96fedacfc94d283647f6ccbc7
|
refs/heads/master
| 2020-04-06T09:03:55.563189
| 2018-02-23T17:02:23
| 2018-02-23T17:02:23
| 64,701,663
| 2
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 6,403
|
py
|
########################################################################################################################
#
# mb_pandora
# By Mike Bourbeau
# mikebourbeau.com
# 2015
#
# Big thanks to Chris Zurbrigg (especially for taking the time to answer all my questions and steer me in the right direction),
# Jeremy Ernst, Cesar Saez, and all other tutorial makers/educators online
#
########################################################################################################################
from PySide import QtCore, QtGui
from shiboken import wrapInstance
import maya.OpenMayaUI as mui
import maya.OpenMaya as om
import maya.cmds as mc
import maya.mel as mel
import inspect
def get_parent():
ptr = mui.MQtUtil.mainWindow()
return wrapInstance( long( ptr ), QtGui.QWidget )
def show():
m = PandoraUI(parent=get_parent())
m.exec_()
del m
########################################################################################################################
class PandoraUI( QtGui.QDialog ):
''' Create the text field that the user types into '''
def __init__( self, parent=get_parent() ):
super( PandoraUI, self ).__init__( )
# Commands
self.move_UI()
self.create_gui()
self.create_layout()
self.create_connections()
self.setAttribute( QtCore.Qt.WA_DeleteOnClose )
def move_UI(self):
''' Moves the UI to the cursor's position '''
pos = QtGui.QCursor.pos()
self.move(pos.x()-100, pos.y()+25)
self.setFixedSize(230, 30)
def create_gui( self ):
''' Visible GUI '''
# Hide window stuff
self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
# Line edit
self.line_edit = Line_Edit(parent=self)
# Completer AKA view
self.completer = QtGui.QCompleter(self)
self.completer.setCompletionMode(QtGui.QCompleter.UnfilteredPopupCompletion)
self.completer.setCaseSensitivity(QtCore.Qt.CaseInsensitive)
self.completer.setMaxVisibleItems(15)
# ProxyModel
self.pFilterModel = QtGui.QSortFilterProxyModel(self)
self.pFilterModel.setFilterCaseSensitivity(QtCore.Qt.CaseInsensitive)
# Set completer
self.line_edit.setCompleter(self.completer)
def set_model(self, model):
''' Set model '''
self.pFilterModel.setSourceModel(model)
self.completer.setModel(self.pFilterModel)
self.completer.setModelSorting(QtGui.QCompleter.CaseInsensitivelySortedModel)
def create_layout( self ):
''' Create layout '''
main_layout = QtGui.QVBoxLayout(self)
main_layout.addWidget( self.line_edit )
main_layout.totalMaximumSize()
main_layout.setContentsMargins(2,2,2,2)
self.setLayout( main_layout )
def create_connections( self ):
''' Connections '''
self.line_edit.textEdited[unicode].connect(self.pFilterModel.setFilterFixedString)
self.line_edit.returnPressed.connect( self.on_text_edited )
self.line_edit.esc_pressed.connect( self.on_esc_press )
self.line_edit.tab_pressed.connect( self.on_text_edited )
self.line_edit.mouse_pressed.connect( self.on_esc_press )
####################################################################################################################
## SLOTS
####################################################################################################################
def on_text_edited(self):
''' Run this when text is edited to execute a command '''
command_list = []
for name, data in inspect.getmembers(mc, callable):
command_list.append(name)
command = self.line_edit.text()
if len( command ):
if command in command_list:
mel_command = mel.eval( "{0}".format( command ) )
self.close()
else:
om.MGlobal.displayError("Not a valid command")
else:
om.MGlobal.displayInfo("")
self.close()
def on_esc_press(self):
''' Close the UI '''
om.MGlobal.displayInfo("")
self.close()
########################################################################################################################
class Line_Edit( QtGui.QLineEdit ):
''' Create the QLineEdit '''
# Signal Variables
esc_pressed = QtCore.Signal(str)
esc_signal_str = "escPressed"
tab_pressed = QtCore.Signal(str)
tab_signal_str = "tabPressed"
mouse_pressed = QtCore.Signal(str)
mouse_signal_str = "mousePressed"
def __init__(self, parent=None):
super( Line_Edit, self ).__init__( )
# Sizing the line edit
self.setFixedHeight(25)
font = QtGui.QFont()
font.setPointSize(11)
font.setBold(False)
self.setFont(font)
# Custom Signals
def event(self, event):
if (event.type()==QtCore.QEvent.KeyPress):
if (event.key()==QtCore.Qt.Key_Escape):
self.esc_pressed.emit(self.esc_signal_str)
return True
if (event.key()==QtCore.Qt.Key_Tab):
self.tab_pressed.emit(self.tab_signal_str)
return True
return QtGui.QLineEdit.event(self, event)
if (event.type()==QtCore.QEvent.FocusOut):
self.mouse_pressed.emit(self.mouse_signal_str)
return True
return QtGui.QLineEdit.event(self, event)
########################################################################################################################
if __name__ == "__main__":
#def run():
# Development stuff
try:
pandora_ui.close()
pandora_ui.deleteLater()
except:
pass
# Get commands
command_list = []
for name, data in inspect.getmembers(mc, callable):
command_list.append(name)
# Set items in model
model = QtGui.QStandardItemModel()
for i,word in enumerate(command_list):
item = QtGui.QStandardItem(word)
model.setItem(i, item)
# Action stuff
pandora_ui = PandoraUI()
pandora_ui.show()
pandora_ui.set_model(model)
# Development stuff
try:
pandora_ui.show()
except:
pandora_ui.close()
pandora_ui.deleteLater()
|
[
"borbs727@gmail.com"
] |
borbs727@gmail.com
|
e8a1cb972b55943c03fdd95bef0099a28dbfafdd
|
79bbc2bf3a12c463bf497a68163d4a15a9290a3f
|
/src/HackerRank/Sherlock and Anagram.py
|
d2f7bb8ce1d2302d06336657e995d68b1a676635
|
[] |
no_license
|
melodist/CodingPractice
|
f5cf614f3be07211d0afe02141b7f6848abeaa12
|
96f56c8b4779a8616e6c9b7ad570010e85c89b68
|
refs/heads/master
| 2023-09-01T08:02:43.090395
| 2023-08-27T13:33:53
| 2023-08-27T13:33:53
| 238,710,451
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 472
|
py
|
"""
https://www.hackerrank.com/challenges/sherlock-and-anagrams/problem
Using Hashmap
Brute Force Problem
"""
from collections import Counter
def sherlockAndAnagrams(s):
answer = 0
for i in range(1, len(s)):
maps = Counter()
for j in range(0, len(s)-i+1):
maps[''.join(sorted(s[j:i+j]))] += 1
for key in maps.keys():
if maps[key] > 1:
answer += (maps[key] - 1) * maps[key] // 2
return answer
|
[
"noreply@github.com"
] |
melodist.noreply@github.com
|
9d4fa83496af7ba7a0863416391737f608a652e4
|
8bbeb7b5721a9dbf40caa47a96e6961ceabb0128
|
/python3/423.Reconstruct Original Digits from English(从英文中重建数字).py
|
a00db04715d3f9ea835ea9eaf4b101bbb57ff1fc
|
[
"MIT"
] |
permissive
|
lishulongVI/leetcode
|
bb5b75642f69dfaec0c2ee3e06369c715125b1ba
|
6731e128be0fd3c0bdfe885c1a409ac54b929597
|
refs/heads/master
| 2020-03-23T22:17:40.335970
| 2018-07-23T14:46:06
| 2018-07-23T14:46:06
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,118
|
py
|
"""
<p>Given a <b>non-empty</b> string containing an out-of-order English representation of digits <code>0-9</code>, output the digits in ascending order.</p>
<p><b>Note:</b><br />
<ol>
<li>Input contains only lowercase English letters.</li>
<li>Input is guaranteed to be valid and can be transformed to its original digits. That means invalid inputs such as "abc" or "zerone" are not permitted.</li>
<li>Input length is less than 50,000.</li>
</ol>
</p>
<p><b>Example 1:</b><br />
<pre>
Input: "owoztneoer"
Output: "012"
</pre>
</p>
<p><b>Example 2:</b><br />
<pre>
Input: "fviefuro"
Output: "45"
</pre>
</p><p>给定一个<strong>非空</strong>字符串,其中包含字母顺序打乱的英文单词表示的数字<code>0-9</code>。按升序输出原始的数字。</p>
<p><strong>注意:</strong></p>
<ol>
<li>输入只包含小写英文字母。</li>
<li>输入保证合法并可以转换为原始的数字,这意味着像 "abc" 或 "zerone" 的输入是不允许的。</li>
<li>输入字符串的长度小于 50,000。</li>
</ol>
<p><strong>示例 1:</strong></p>
<pre>
输入: "owoztneoer"
输出: "012" (zeroonetwo)
</pre>
<p><strong>示例 2:</strong></p>
<pre>
输入: "fviefuro"
输出: "45" (fourfive)
</pre>
<p>给定一个<strong>非空</strong>字符串,其中包含字母顺序打乱的英文单词表示的数字<code>0-9</code>。按升序输出原始的数字。</p>
<p><strong>注意:</strong></p>
<ol>
<li>输入只包含小写英文字母。</li>
<li>输入保证合法并可以转换为原始的数字,这意味着像 "abc" 或 "zerone" 的输入是不允许的。</li>
<li>输入字符串的长度小于 50,000。</li>
</ol>
<p><strong>示例 1:</strong></p>
<pre>
输入: "owoztneoer"
输出: "012" (zeroonetwo)
</pre>
<p><strong>示例 2:</strong></p>
<pre>
输入: "fviefuro"
输出: "45" (fourfive)
</pre>
"""
class Solution:
def originalDigits(self, s):
"""
:type s: str
:rtype: str
"""
|
[
"lishulong@wecash.net"
] |
lishulong@wecash.net
|
439d9d3f2ddb0c86de1e761c7094748324c59a5f
|
41e2d689522c6929332e36056f651158db59837e
|
/roman_dictionary.py
|
dde7d220964b381ed2ffc6d9ec9bd4c7b88842af
|
[] |
no_license
|
RichardAfolabi/Scientific-Python
|
14d39bffe8726dcee83e1a23d35cdb48e0076c3a
|
efebf6dd40af192b82931b1181299408dd8fde36
|
refs/heads/master
| 2016-09-02T04:07:45.486906
| 2015-07-10T18:51:14
| 2015-07-10T18:51:14
| 28,725,002
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,818
|
py
|
"""
Roman Dictionary
----------------
Mark Antony keeps a list of the people he knows in several dictionaries
based on their relationship to him::
friends = {'julius': '100 via apian', 'cleopatra': '000 pyramid parkway'}
romans = dict(brutus='234 via tratorium', cassius='111 aqueduct lane')
countrymen = dict([('plebius','786 via bunius'),
('plebia', '786 via bunius')])
1. Print out the names for all of Antony's friends.
2. Now all of their addresses.
3. Now print them as "pairs".
4. Hmmm. Something unfortunate befell Julius. Remove him from the
friends list.
5. Antony needs to mail everyone for his second-triumvirate party. Make
a single dictionary containing everyone.
6. Antony's stopping over in Egypt and wants to swing by Cleopatra's
place while he is there. Get her address.
7. The barbarian hordes have invaded and destroyed all of Rome.
Clear out everyone from the dictionary.
See :ref:`roman-dictionary-solution`.
"""
friends = {'julius': '100 via apian', 'cleopatra': '000 pyramid parkway'}
romans = dict(brutus='234 via tratorium', cassius='111 aqueduct lane')
countrymen = dict([('plebius','786 via bunius'), ('plebia', '786 via bunius')])
# Names of all friends
#print(friends.keys() + romans.keys() + countrymen.keys())
#Addresses of all friends
#print(friends.values() + romans.values() + countrymen.values())
#Pairs of names and addresses
all_friends = friends.items() + romans.items() + countrymen.items()
print(all_friends)
print(all_friends.pop(0) )
#Dictionary of all
friends_dict = dict(all_friends)
print(friends_dict)
#Cleopatra's address
print(friends_dict['cleopatra'])
friends_dict.pop('plebia')
print(friends_dict)
del friends_dict['brutus']
print(friends_dict)
friends_dict.clear()
print(friends_dict)
|
[
"mailme@richardafolabi.com"
] |
mailme@richardafolabi.com
|
c67ded67faf5fa7a4bf3cfe4d6682b5b23e2af51
|
b3e3284f3d7b66f237e60fdfb1a37db706363139
|
/RST/app/traslado/urls.py
|
4a8a4b104ca3de309c7847f59ccd00a33601af8e
|
[] |
no_license
|
corporacionrst/administracion
|
4caf1545c313eb36408850bb4506bbd0bf43d6e6
|
7405442b4f14a589d75a5e04250be123403180ec
|
refs/heads/master
| 2020-04-11T00:04:06.017147
| 2018-12-11T21:46:49
| 2018-12-11T21:46:49
| 161,374,204
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 560
|
py
|
from django.urls import path
from .views import solicitar,tienda,stock,agregar,quitar,autorizar,pdf,listar
urlpatterns = [
path('solicitar/',solicitar.as_view(),name="solicitar"),
path('tienda/',tienda.as_view(),name="tienda"),
path('stock/',stock.as_view(),name="stock"),
path('agregar/',agregar.as_view(),name="agregar"),
path('quitar/',quitar.as_view(),name="quitar"),
path('pdf/<int:id>',pdf.as_view(),name="pdf"),
path('listar/',listar.as_view(),name="listar"),
path('autorizar/',autorizar.as_view(),name="autorizar")
]
|
[
"admin@corporacionrst.com"
] |
admin@corporacionrst.com
|
bfd72a4ff02cd2ec6f5484ca7cd5efbbc5d52771
|
857fc21a40aa32d2a57637de1c723e4ab51062ff
|
/CodingInterviews/python/38_tree_depth.py
|
2941974551915121365ad463d71545d484d5ffee
|
[
"MIT"
] |
permissive
|
YorkFish/git_study
|
efa0149f94623d685e005d58dbaef405ab91d541
|
6e023244daaa22e12b24e632e76a13e5066f2947
|
refs/heads/master
| 2021-06-21T18:46:50.906441
| 2020-12-25T14:04:04
| 2020-12-25T14:04:04
| 171,432,914
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 541
|
py
|
#!/usr/bin/env python3
# coding:utf-8
from helper import TreeNode
class Solution:
def TreeDepth(self, pRoot):
if pRoot is None:
return 0
return max(self.TreeDepth(pRoot.left), self.TreeDepth(pRoot.right)) + 1
if __name__ == "__main__":
"""
1
/ \
2 3
/
4
"""
root = TreeNode(0)
n1 = TreeNode(1)
n2 = TreeNode(2)
n3 = TreeNode(3)
root.left = n1
root.right = n2
n1.left = n3
s = Solution()
ans = s.TreeDepth(root)
print(ans)
|
[
"18258788231@163.com"
] |
18258788231@163.com
|
d5fc5b6db085b46395f79022f2078f51827c0bfa
|
63e2bed7329c79bf67279f9071194c9cba88a82c
|
/SevOneApi/python-client/swagger_client/models/flow_falcon_setting_v1.py
|
1f3cc2c1d10cccb4d001fd3fc36c37a697f41177
|
[] |
no_license
|
jsthomason/LearningPython
|
12422b969dbef89578ed326852dd65f65ab77496
|
2f71223250b6a198f2736bcb1b8681c51aa12c03
|
refs/heads/master
| 2021-01-21T01:05:46.208994
| 2019-06-27T13:40:37
| 2019-06-27T13:40:37
| 63,447,703
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 6,911
|
py
|
# coding: utf-8
"""
SevOne API Documentation
Supported endpoints by the new RESTful API # noqa: E501
OpenAPI spec version: 2.1.18, Hash: db562e6
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
class FlowFalconSettingV1(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_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.
"""
swagger_types = {
'can_zoom_in_cb': 'str',
'granularity': 'int',
'graph_other': 'bool',
'is_rate': 'bool',
'split': 'int',
'subnet_category_id': 'int'
}
attribute_map = {
'can_zoom_in_cb': 'canZoomInCb',
'granularity': 'granularity',
'graph_other': 'graphOther',
'is_rate': 'isRate',
'split': 'split',
'subnet_category_id': 'subnetCategoryId'
}
def __init__(self, can_zoom_in_cb=None, granularity=None, graph_other=None, is_rate=None, split=None, subnet_category_id=None): # noqa: E501
"""FlowFalconSettingV1 - a model defined in Swagger""" # noqa: E501
self._can_zoom_in_cb = None
self._granularity = None
self._graph_other = None
self._is_rate = None
self._split = None
self._subnet_category_id = None
self.discriminator = None
if can_zoom_in_cb is not None:
self.can_zoom_in_cb = can_zoom_in_cb
if granularity is not None:
self.granularity = granularity
if graph_other is not None:
self.graph_other = graph_other
if is_rate is not None:
self.is_rate = is_rate
if split is not None:
self.split = split
if subnet_category_id is not None:
self.subnet_category_id = subnet_category_id
@property
def can_zoom_in_cb(self):
"""Gets the can_zoom_in_cb of this FlowFalconSettingV1. # noqa: E501
:return: The can_zoom_in_cb of this FlowFalconSettingV1. # noqa: E501
:rtype: str
"""
return self._can_zoom_in_cb
@can_zoom_in_cb.setter
def can_zoom_in_cb(self, can_zoom_in_cb):
"""Sets the can_zoom_in_cb of this FlowFalconSettingV1.
:param can_zoom_in_cb: The can_zoom_in_cb of this FlowFalconSettingV1. # noqa: E501
:type: str
"""
self._can_zoom_in_cb = can_zoom_in_cb
@property
def granularity(self):
"""Gets the granularity of this FlowFalconSettingV1. # noqa: E501
:return: The granularity of this FlowFalconSettingV1. # noqa: E501
:rtype: int
"""
return self._granularity
@granularity.setter
def granularity(self, granularity):
"""Sets the granularity of this FlowFalconSettingV1.
:param granularity: The granularity of this FlowFalconSettingV1. # noqa: E501
:type: int
"""
self._granularity = granularity
@property
def graph_other(self):
"""Gets the graph_other of this FlowFalconSettingV1. # noqa: E501
:return: The graph_other of this FlowFalconSettingV1. # noqa: E501
:rtype: bool
"""
return self._graph_other
@graph_other.setter
def graph_other(self, graph_other):
"""Sets the graph_other of this FlowFalconSettingV1.
:param graph_other: The graph_other of this FlowFalconSettingV1. # noqa: E501
:type: bool
"""
self._graph_other = graph_other
@property
def is_rate(self):
"""Gets the is_rate of this FlowFalconSettingV1. # noqa: E501
:return: The is_rate of this FlowFalconSettingV1. # noqa: E501
:rtype: bool
"""
return self._is_rate
@is_rate.setter
def is_rate(self, is_rate):
"""Sets the is_rate of this FlowFalconSettingV1.
:param is_rate: The is_rate of this FlowFalconSettingV1. # noqa: E501
:type: bool
"""
self._is_rate = is_rate
@property
def split(self):
"""Gets the split of this FlowFalconSettingV1. # noqa: E501
:return: The split of this FlowFalconSettingV1. # noqa: E501
:rtype: int
"""
return self._split
@split.setter
def split(self, split):
"""Sets the split of this FlowFalconSettingV1.
:param split: The split of this FlowFalconSettingV1. # noqa: E501
:type: int
"""
self._split = split
@property
def subnet_category_id(self):
"""Gets the subnet_category_id of this FlowFalconSettingV1. # noqa: E501
:return: The subnet_category_id of this FlowFalconSettingV1. # noqa: E501
:rtype: int
"""
return self._subnet_category_id
@subnet_category_id.setter
def subnet_category_id(self, subnet_category_id):
"""Sets the subnet_category_id of this FlowFalconSettingV1.
:param subnet_category_id: The subnet_category_id of this FlowFalconSettingV1. # noqa: E501
:type: int
"""
self._subnet_category_id = subnet_category_id
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.swagger_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:
result[attr] = value
if issubclass(FlowFalconSettingV1, dict):
for key, value in self.items():
result[key] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, FlowFalconSettingV1):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
|
[
"johnsthomason@gmail.com"
] |
johnsthomason@gmail.com
|
8d19db4102d07e5fdfcc362289c71ffbb2079ae9
|
dd116fe1e94191749ab7a9b00be25bfd88641d82
|
/cairis/cairis/AttackerNodeDialog.py
|
66e5c66dbc7112d2c73da0dba0fce3eb93a371ba
|
[
"Apache-2.0"
] |
permissive
|
RobinQuetin/CAIRIS-web
|
fbad99327707ea3b995bdfb4841a83695989e011
|
4a6822db654fecb05a09689c8ba59a4b1255c0fc
|
HEAD
| 2018-12-28T10:53:00.595152
| 2015-06-20T16:53:39
| 2015-06-20T16:53:39
| 33,935,403
| 0
| 3
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,058
|
py
|
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
import sys
import gtk
from NDImplementationDecorator import NDImplementationDecorator
class AttackerNodeDialog:
def __init__(self,objt,environmentName,dupProperty,overridingEnvironment,builder):
self.window = builder.get_object("AttackerNodeDialog")
self.decorator = NDImplementationDecorator(builder)
self.decorator.updateTextCtrl("attackerNameCtrl",objt.name())
roles = []
for role in objt.roles(environmentName,dupProperty):
roles.append([role])
self.decorator.updateListCtrl("attackerRolesCtrl",['Role'],gtk.ListStore(str),roles)
capabilities = []
for cap,value in objt.capability(environmentName,dupProperty):
capabilities.append([cap,value])
self.decorator.updateListCtrl("attackerCapabilityCtrl",['Capability','Value'],gtk.ListStore(str,str),capabilities)
motives = []
for motive in objt.motives(environmentName,dupProperty):
motives.append([motive])
self.decorator.updateListCtrl("attackerMotiveCtrl",['Motive'],gtk.ListStore(str),motives)
self.decorator.updateMLTextCtrl("attackerDescriptionCtrl",objt.description())
self.window.resize(350,300)
def on_attackerOkButton_clicked(self,callback_data):
self.window.destroy()
def show(self):
self.window.show()
|
[
"shamal.faily@googlemail.com"
] |
shamal.faily@googlemail.com
|
43a4377094245e2463adc28cc427afa15821c112
|
d7016f69993570a1c55974582cda899ff70907ec
|
/sdk/apimanagement/azure-mgmt-apimanagement/generated_samples/api_management_head_product_group.py
|
f10b2ce0ada4d6b08c1a732b56a318068888bafd
|
[
"LicenseRef-scancode-generic-cla",
"MIT",
"LGPL-2.1-or-later"
] |
permissive
|
kurtzeborn/azure-sdk-for-python
|
51ca636ad26ca51bc0c9e6865332781787e6f882
|
b23e71b289c71f179b9cf9b8c75b1922833a542a
|
refs/heads/main
| 2023-03-21T14:19:50.299852
| 2023-02-15T13:30:47
| 2023-02-15T13:30:47
| 157,927,277
| 0
| 0
|
MIT
| 2022-07-19T08:05:23
| 2018-11-16T22:15:30
|
Python
|
UTF-8
|
Python
| false
| false
| 1,663
|
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.apimanagement import ApiManagementClient
"""
# PREREQUISITES
pip install azure-identity
pip install azure-mgmt-apimanagement
# USAGE
python api_management_head_product_group.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 = ApiManagementClient(
credential=DefaultAzureCredential(),
subscription_id="subid",
)
response = client.product_group.check_entity_exists(
resource_group_name="rg1",
service_name="apimService1",
product_id="5931a75ae4bbd512a88c680b",
group_id="59306a29e4bbd510dc24e5f9",
)
print(response)
# x-ms-original-file: specification/apimanagement/resource-manager/Microsoft.ApiManagement/stable/2021-08-01/examples/ApiManagementHeadProductGroup.json
if __name__ == "__main__":
main()
|
[
"noreply@github.com"
] |
kurtzeborn.noreply@github.com
|
654403a4269a49135c306d5d732655e2a3609d87
|
bc9cb3f0f104778026ca6f3a07595dd5d6ce840f
|
/PROJETO_FINAL/codigo/core/loadout/oticos/optic.py
|
e4b5d6bb5479c2c27a5b7d5fbae3b46ac9465325
|
[] |
no_license
|
JohnRhaenys/escola_de_ferias
|
ff7a5d7f399459725f3852ca6ee200486f29e7d4
|
193364a05a5c7ccb2e5252c150745d6743738728
|
refs/heads/master
| 2023-01-12T11:30:46.278703
| 2020-11-19T14:59:10
| 2020-11-19T14:59:10
| 314,278,831
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 335
|
py
|
from pydub import AudioSegment
from pydub.playback import play
class Optic:
def __init__(self, name, color):
self.name = name
self.color = color
def make_sound(self, audio_file_path):
audio = AudioSegment.from_mp3(audio_file_path)
play(audio)
def __str__(self):
return self.name
|
[
"joao.estrela@sga.pucminas.br"
] |
joao.estrela@sga.pucminas.br
|
1fde89f76c9bb7e830b737c97a05c2db20bdc605
|
fcb0480812b806b2383b5ddba781bdb157e5d580
|
/backend/inByulGram/models.py
|
93b5815910b2283490c7b6772ee90e6c54c649cb
|
[] |
no_license
|
bunnycast/inByulGram
|
f576126a7028f340244f60cbe58bfbc46d114412
|
54af7629f60ef87a6a0238466b34720536616b19
|
refs/heads/master
| 2023-03-14T09:52:26.984478
| 2021-03-05T14:12:43
| 2021-03-05T14:12:43
| 341,405,555
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,741
|
py
|
import re
from django.conf import settings
from django.db import models
from django.urls import reverse
class TimeStampedModel(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
abstract = True
class Post(TimeStampedModel):
author = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='mt_post_set', on_delete=models.CASCADE)
photo = models.ImageField(upload_to='inByulGram/post/%Y/%m/%d')
caption = models.CharField(max_length=500)
tag_set = models.ManyToManyField('Tag', blank=True)
location = models.CharField(max_length=100)
like_user_set = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, related_name='like_post_set')
def __str__(self):
return self.caption
def extract_tag_list(self):
tag_name_list = re.findall(r"#([a-zA-Z\dㄱ-힇]+)", self.caption)
tag_list = []
for tag_name in tag_name_list:
tag, _ = Tag.objects.get_or_create(name=tag_name)
tag_list.append(tag)
return tag_list
def get_absolute_url(self):
return reverse('instagram:post_detail', args=[self.pk])
def is_like_user(self, user):
return self.like_user_set.filter(pk=user.pk).exists()
class Meta:
ordering = ['-id']
class Comment(TimeStampedModel):
author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
post = models.ForeignKey('Post', on_delete=models.CASCADE)
message = models.TextField()
class Meta:
ordering = ['-id']
class Tag(TimeStampedModel):
name = models.CharField(max_length=50, unique=True)
def __str__(self):
return self.name
|
[
"berzzubunny@gmail.com"
] |
berzzubunny@gmail.com
|
6b1f4ed165609e436d377590f34a8a963e68547f
|
5ceea4106e0df754ae581c1f5e2d16082d7b6386
|
/hackerRank/data-structures/arrays/arrays-ds.py
|
06ca1a9cd3c7a7ac82b9c0bd94010dbf94d9361b
|
[] |
no_license
|
vikramlance/Python-Programming
|
b0d4bd70145bfaa7a66434656c5970fbc57e8bd3
|
4094961e3c613e33f2d8a6d30281c60ed09d8c80
|
refs/heads/master
| 2022-06-17T00:58:50.646615
| 2022-06-03T03:39:35
| 2022-06-03T03:39:35
| 53,989,511
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 198
|
py
|
'''
https://www.hackerrank.com/challenges/arrays-ds
'''
#!/bin/python
import sys
n = int(raw_input().strip())
arr = map(int,raw_input().strip().split(' '))
print ' '.join(map(str, arr[::-1]))
|
[
"noreply@github.com"
] |
vikramlance.noreply@github.com
|
85147248b7b7d4b6ec887b871bff81793d2dc7bd
|
c2ec70be9ffbf29e779bcda8b491f96973cb1a39
|
/chapter_06/chapter_6_6_5.py
|
d67b624e1e184320e5a97db0e4c695bcf8440400
|
[] |
no_license
|
panlourenco/exercises-coronapython
|
8ef4f805fcdcc77686b5f325da6c8629106bac3c
|
9ccb80a33f9ec1a23123d20147225338c7e476bc
|
refs/heads/master
| 2022-12-09T22:56:59.676366
| 2020-09-06T17:35:56
| 2020-09-06T17:35:56
| 257,653,442
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 537
|
py
|
# 6-5. Rivers:
rivers = {
'nile': 'egypt',
'mississippi': 'united states',
'seine': 'france',
'vistula': 'poland',
'Amazonas': 'brasil',
}
for river, country in rivers.items():
print("The " + river.title() + " flows through " + country.title() + ".")
print("\nThe following rivers are included in this data set:")
for river in rivers.keys():
print("- " + river.title())
print("\nThe following countries are included in this data set:")
for country in rivers.values():
print("- " + country.title())
|
[
"lrooudrreingcoo@gmail.com"
] |
lrooudrreingcoo@gmail.com
|
fe7a4edce117c23fb54632a7523492a7efe36909
|
9777ae10e1ec0a5e55e66ae71e2430eaa16ff891
|
/tests/q01b.py
|
9cdef7d217fd3e733970e1d5bc04197378d40979
|
[] |
no_license
|
jkuruzovich/final-starter-2019
|
175f5c65a295112c27c9240c3b14660a2669a875
|
8eed585ce4d4739548c5b3d0dfc82dd63ac3a2ec
|
refs/heads/master
| 2022-03-14T18:43:47.639034
| 2019-12-09T20:15:52
| 2019-12-09T20:15:52
| 184,331,056
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 366
|
py
|
test = {
'name': '1b',
'points': 1,
'suites': [
{
'cases': [
{
'code': r"""
>>> "{0:.4f}".format(round( cost_ny,4))
'15.1882'
""",
'hidden': False,
'locked': False
}
],
'scored': True,
'setup': '',
'teardown': '',
'type': 'doctest'
}
]
}
|
[
"jkuruzovich@gmail.com"
] |
jkuruzovich@gmail.com
|
46592bd7353b194e91fdbd40140bbbd8ff92a6ab
|
cc7474d52cfcd124f2ddd4ad4a2cad1d2868bd80
|
/unispider/spiders/ppai_scrapy.py
|
93b603d685865a4fd45b5ee6a87122cd850af6aa
|
[] |
no_license
|
yidun55/unispider
|
212e81ed49a5bb9ed219cdab8215256bf16694f1
|
aa8d826707baedf56028e6307f590458ed683e8d
|
refs/heads/master
| 2020-05-18T16:31:58.346600
| 2015-10-28T13:37:09
| 2015-10-28T13:37:09
| 39,058,048
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 7,986
|
py
|
#coding:utf-8
"""
从拍拍贷上爬取网贷黑名单
author: 邓友辉
email:heshang1203@sina.com
date:2015/06/10
"""
from scrapy.utils.request import request_fingerprint
from scrapy.spider import Spider
from scrapy.http import Request
from scrapy import log
from scrapy import signals
import time
from unispider.items import *
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
class p2pBlacklist(Spider):
download_delay=2
name = 'pplist'
start_urls = ['http://www.ppdai.com/blacklist/2015']
allowed_domains = ['ppdai.com']
# writeInFile = "/home/dyh/data/specialworker/judicial/url_j.txt"
writeInFile = "E:/DLdata/ppai.txt"
# haveRequested = "/home/dyh/data/specialworker/judicial/haveRequestedUrl.txt"
haveRequested = "E:/DLdata/ppai_control.txt"
def __init__(self):
pass
def set_crawler(self,crawler):
super(p2pBlacklist, self).set_crawler(crawler)
self.bind_signal()
def bind_signal(self):
self.crawler.signals.connect(self.open_file, \
signal=signals.spider_opened) #爬虫开启时,打开文件
self.crawler.signals.connect(self.close_file, \
signal=signals.spider_closed) #爬虫关闭时,关闭文件
def open_file(self):
self.file_handler = open(self.writeInFile, "a") #写内容
self.file_haveRequested = open(self.haveRequested, "a+") #写入已请求成功的url
self.url_have_seen = set()
for line in self.file_haveRequested:
fp = self.url_fingerprint(line)
self.url_have_seen.add(fp)
def close_file(self):
self.file_handler.close()
def url_fingerprint(self, url):
req = Request(url.strip())
fp = request_fingerprint(req)
return fp
def make_requests_from_url(self, url):
return Request(url, callback=self.gettotal, dont_filter=True)
def gettotal(self, response):
"""
extract pages from different years
"""
url = 'http://www.ppdai.com/blacklist/'
years = xrange(2008,2016)
urls = [url+str(year) for year in years]
for url in urls[0:5]:
# print url, "year url"
yield Request(url, callback=self.extract, dont_filter=True)
def extract(self, response):
"""
extract pages and then Request those pages sequecely
"""
# print response.url,"extract response url"
sel = response.selector
pages = []
try:
# print "pages work"
pages = sel.xpath("//div[contains(@class,'fen_ye_nav')]//td/text()").re(u"共([\d]{1,3})页")
# print pages
except Exception, e:
print e,"error pages"
log.msg(e, level=log.ERROR)
log.msg(response.url, level=log.ERROR)
if len(pages) == 0:
self.getUserName(response) #only one page
else:
for page in range(int(pages[0])+1)[1:2]: #fro test
url = response.url+"_m0_p"+str(page)
yield Request(url, callback=self.getUserName,dont_filter=True)
def getUserName(self, response):
"""
get user name from xtml
"""
sel = response.selector
blackTr = sel.xpath(u"//table[contains(@class,'black_table')]/tr[position()>1]//p[contains(text(),'真实姓名')]/a/@href").extract()
url = 'http://www.ppdai.com'
urls = [url+i for i in blackTr]
for url in urls[0:1]:
fp = self.url_fingerprint(url)
if fp not in self.url_have_seen:
self.url_have_seen.add(fp)
yield Request(url,
callback = self.detail, dont_filter=False)
else:
pass
def for_ominated_data(self,info_list,i_list):
"""
some elements are ominated, set the ominated elements
as ""
"""
try:
if len(i_list) == 0:
i_list.append("")
else:
pass
assert len(i_list) == 1, "the element must be unique"
info_list.append(i_list[0].strip())
# print 'you work'
return info_list
except Exception, e:
print 'i work'
log.msg(e, level=log.ERROR)
def detail(self, response):
"""
extract detail info and store it in items
"""
item = UnispiderItem()
sel = response.selector
self.file_haveRequested.write(response.url+"\n")
total = sel.xpath(u"count(//div[@class='table_nav']\
//tr)").extract() #借款的笔数
total = int(total[0][0])
for trI in xrange(2, total+1):
"""
有的用户有多笔的借款
trI是不同笔借款所在表格的行数
"""
info = []
accPri = sel.xpath(u"//table[contains(@class, \
'detail_table')]/tr[1]/td[1]/text()").re(ur"累计借入本金:([\S\s]*)") #累计借入本金
info = self.for_ominated_data(info, accPri)
ovDate = sel.xpath(u"//table[contains(@class, 'detail_table')]/tr[1]/td[2]/span/text()").extract() #最大逾期天数
info = self.for_ominated_data(info, ovDate)
bef = u"//table[contains(@class, 'detail_table')]/tr[3]//tr["
aft = u"]/td[1]/text()"
ass = bef + str(trI) + aft
liID = sel.xpath(ass).extract() #列表编号
info = self.for_ominated_data(info, liID)
bef = u"//table[contains(@class, 'detail_table')]/tr[3]//tr["
aft = u"]/td[2]/text()"
ass = bef + str(trI) + aft
loNu = sel.xpath(ass).extract() #借款期数
info = self.for_ominated_data(info, loNu)
bef = u"//table[contains(@class, 'detail_table')]/tr[3]//tr["
aft = u"]/td[3]/text()"
ass = bef + str(trI) + aft
loTime = sel.xpath(ass).extract() #借款时间
info = self.for_ominated_data(info, loTime)
bef = u"//table[contains(@class, 'detail_table')]/tr[3]//tr["
aft = u"]/td[4]/text()"
ass = bef + str(trI) + aft
ovDayNu = sel.xpath(ass).extract() #逾期天数
info = self.for_ominated_data(info, ovDayNu)
bef = u"//table[contains(@class, 'detail_table')]/tr[3]//tr["
aft = u"]/td[5]/text()"
ass = bef + str(trI) + aft
ovPri = sel.xpath(ass).extract() #逾期本息
info = self.for_ominated_data(info, ovPri)
prov = sel.xpath(u"//div[contains(@class,\
'blacklist_detail_nav')]//li//strong/text()").re(ur"_([\w]*?)_[男|女]") #省
info = self.for_ominated_data(info, prov)
usrNa = sel.xpath(u"//div[contains(@class,\
'blacklist_detail_nav')]//li").re(ur"用户名:([\w\W]*?)\n") #用户名
info = self.for_ominated_data(info, usrNa)
name = sel.xpath(u"//div[contains(@class,\
'blacklist_detail_nav')]//li").re(ur"姓名:([\w\W]*?)\n") #姓名
info = self.for_ominated_data(info, name)
phoneN = sel.xpath(u"//div[contains(@class,\
'blacklist_detail_nav')]//li").re(ur"手机号:([\w\W]*?)\n") #手机号
info = self.for_ominated_data(info, phoneN)
ID = sel.xpath(u"//div[contains(@class,\
'blacklist_detail_nav')]//li").re(ur"身份证号:([\w\W]*?)\n") #身份证号
info = self.for_ominated_data(info, ID)
try:
info.append(str(time.strftime("%Y年%m月%d日")))
info = '\001'.join(info)+"\n"
item['content'] = info
yield item
except Exception, e:
log.msg('ERROR:{url}'.format(url=response.url),\
level=log.ERROR)
|
[
"heshang1203@sina.com"
] |
heshang1203@sina.com
|
394ca5aa490425423f8b5baa05b50dee4488b340
|
53fab060fa262e5d5026e0807d93c75fb81e67b9
|
/backup/user_052/ch80_2020_06_20_18_56_40_883079.py
|
2b0e0c4b3e47da4c259cad01dc2cf476c5c8eca5
|
[] |
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
| 225
|
py
|
def interseccao_chaves (dicionario, dic):
lista = []
a = dicionario.keys()
b = dic.keys()
if a in dic:
lista.append(a)
if b in dicionario:
lista.append(b)
return lista
|
[
"you@example.com"
] |
you@example.com
|
009137a3b61958b2ef9248924a5c5b51fbd40a96
|
0822d36728e9ed1d4e91d8ee8b5ea39010ac9371
|
/robo/pages/goias/oanapolis.py
|
b5cc50ea54d8600f47c59fd1327281db8bd8b173
|
[] |
no_license
|
diegothuran/blog
|
11161e6f425d08bf7689190eac0ca5bd7cb65dd7
|
233135a1db24541de98a7aeffd840cf51e5e462e
|
refs/heads/master
| 2022-12-08T14:03:02.876353
| 2019-06-05T17:57:55
| 2019-06-05T17:57:55
| 176,329,704
| 0
| 0
| null | 2022-12-08T04:53:02
| 2019-03-18T16:46:43
|
Python
|
UTF-8
|
Python
| false
| false
| 637
|
py
|
# coding: utf-8
import sys
sys.path.insert(0, '../../../blog')
from bs4 import BeautifulSoup
import requests
GLOBAL_RANK = 2969356
RANK_BRAZIL = 62956
NAME = 'oanapolis.com.br'
def get_urls():
try:
urls = []
link = 'http://oanapolis.com.br/'
req = requests.get(link)
noticias = BeautifulSoup(req.text, "html.parser").find_all('h2', class_='entry-title')
for noticia in noticias:
href = noticia.find_all('a', href=True)[0]['href']
# print(href)
urls.append(href)
return urls
except:
raise Exception('Exception in oanapolis')
|
[
"diego.thuran@gmail.com"
] |
diego.thuran@gmail.com
|
9772a0e3675f402d54ce680f87aaf70c21ed6d41
|
239dc36bc1042b5b99bdd1a72aaedeef22327083
|
/EionetLDAP/__init__.py
|
3f357b41cf398c1bcf42b3cacaaa10d4f88d9d96
|
[] |
no_license
|
eaudeweb/EionetProducts
|
d67c8627317548d17e9662da8d00d4b71a894774
|
da85b0001b994cdc6d94d481fd020de69fc10f63
|
refs/heads/master
| 2021-01-10T20:04:12.867465
| 2011-05-09T13:45:17
| 2011-05-23T13:24:11
| 2,135,754
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,128
|
py
|
# The contents of this file are subject to the Mozilla Public
# License Version 1.1 (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.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS
# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
# implied. See the License for the specific language governing
# rights and limitations under the License.
#
# The Initial Owner of the Original Code is European Environment
# Agency (EEA). Portions created by Eau de Web are
# Copyright (C) European Environment Agency. All
# Rights Reserved.
#
# Authors:
#
# Alex Morega, Eau de Web
__version__='0.1'
from App.ImageFile import ImageFile
import EionetLDAP
def initialize(context):
# register EionetLDAP
context.registerClass(
EionetLDAP.EionetLDAP,
constructors=(EionetLDAP.manage_addEionetLDAP_html,
EionetLDAP.manage_addEionetLDAP),
icon='www/eionet_ldap.gif',
)
misc_ = {
'eionet_ldap.gif': ImageFile('www/eionet_ldap.gif', globals()),
}
|
[
"alexandru.plugaru@gmail.com"
] |
alexandru.plugaru@gmail.com
|
2e45ed946ff60dd2b0f5abeae6e510dd73e3d67f
|
16734d189c2bafa9c66fdc989126b7d9aa95c478
|
/Python/small-projects/make_dictionary.py
|
6c17de909dd3b4d6068513f34ef23f19786613ed
|
[] |
no_license
|
Ericksmith/CD-projects
|
3dddd3a3819341be7202f11603cf793a2067c140
|
3b06b6e289d241c2f1115178c693d304280c2502
|
refs/heads/master
| 2021-08-15T17:41:32.329647
| 2017-11-18T01:18:04
| 2017-11-18T01:18:04
| 104,279,162
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 542
|
py
|
name = ["Anna", "Eli", "Pariece", "Brendan", "Amy", "Shane", "Oscar"]
favorite_animal = ["horse", "cat", "spider", "giraffe", "ticks", "dolphins", "llamas", 'corgi']
def make_dict(arr1, arr2):
new_dict = {}
if len(arr1) < len(arr2):
big = arr2
small = arr1
else:
big = arr1
small = arr2
for i in range(len(big)):
if len(small) -1 < i:
new_dict[big[i]] = None
else:
new_dict[big[i]] = small[i]
return new_dict
print(make_dict(name, favorite_animal))
|
[
"smith.s.erick@gmail.com"
] |
smith.s.erick@gmail.com
|
723addda30f29f8f7f246fcf493c78b96472cb12
|
90419da201cd4948a27d3612f0b482c68026c96f
|
/sdk/python/pulumi_azure_nextgen/eventhub/v20140901/outputs.py
|
0ebdc673b5e80e5109e83bebd9559fc888bd6218
|
[
"BSD-3-Clause",
"Apache-2.0"
] |
permissive
|
test-wiz-sec/pulumi-azure-nextgen
|
cd4bee5d70cb0d332c04f16bb54e17d016d2adaf
|
20a695af0d020b34b0f1c336e1b69702755174cc
|
refs/heads/master
| 2023-06-08T02:35:52.639773
| 2020-11-06T22:39:06
| 2020-11-06T22:39:06
| 312,993,761
| 0
| 0
|
Apache-2.0
| 2023-06-02T06:47:28
| 2020-11-15T09:04:00
| null |
UTF-8
|
Python
| false
| false
| 1,725
|
py
|
# coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from ... import _utilities, _tables
__all__ = [
'SkuResponse',
]
@pulumi.output_type
class SkuResponse(dict):
"""
SKU parameters supplied to the create Namespace operation
"""
def __init__(__self__, *,
tier: str,
capacity: Optional[int] = None,
name: Optional[str] = None):
"""
SKU parameters supplied to the create Namespace operation
:param str tier: The billing tier of this particular SKU.
:param int capacity: The Event Hubs throughput units.
:param str name: Name of this SKU.
"""
pulumi.set(__self__, "tier", tier)
if capacity is not None:
pulumi.set(__self__, "capacity", capacity)
if name is not None:
pulumi.set(__self__, "name", name)
@property
@pulumi.getter
def tier(self) -> str:
"""
The billing tier of this particular SKU.
"""
return pulumi.get(self, "tier")
@property
@pulumi.getter
def capacity(self) -> Optional[int]:
"""
The Event Hubs throughput units.
"""
return pulumi.get(self, "capacity")
@property
@pulumi.getter
def name(self) -> Optional[str]:
"""
Name of this SKU.
"""
return pulumi.get(self, "name")
def _translate_property(self, prop):
return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop
|
[
"public@paulstack.co.uk"
] |
public@paulstack.co.uk
|
5dc00e8bf125c32f5ce8a34eea869cdd95a2d6a6
|
0d392fa6e594279ef193597a36fde65c341cf7c5
|
/test.py
|
f80d7b9718267ea298ad2ec5ce51717e1af7a19e
|
[] |
no_license
|
chimtrangbu/DoorToDoor
|
a0d542f99f04ec3e5774e8cd49b478e731f4568f
|
88891be30ef6aac8714b0fa41d575db47ed7de7d
|
refs/heads/master
| 2020-04-15T04:11:22.943176
| 2019-01-07T03:52:42
| 2019-01-07T03:52:42
| 164,374,023
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 4,854
|
py
|
from math import sqrt
from sys import argv
class Node():
'''
each Node object holding each city's coordinates
cal_distance: calculating distance between this Node and another Node
'''
def __init__(self, name, x, y):
self.name = name
self.x = x
self.y = y
def cal_distance(self, another_node):
return sqrt((self.x - another_node.x) ** 2 +
(self.y - another_node.y) ** 2)
class Graph(object):
def __init__(self):
self.nodes = []
def add_node(self, node):
self.nodes.append(node)
return self.nodes
def nearest_neighbor(self, start=None):
if start is None:
start = self.nodes[0]
must_visit = self.nodes.copy()
path = [start]
must_visit.remove(start)
while must_visit:
nearest = must_visit[0]
cur_node = path[-1]
min_dist = cur_node.cal_distance(nearest)
for node in must_visit:
if cur_node.cal_distance(node) < min_dist:
nearest = node
min_dist = cur_node.cal_distance(node)
# nearest = min(must_visit, key=lambda k: path[-1].cal_distance(k))
path.append(nearest)
must_visit.remove(nearest)
return path
def random_insertion(self, start=None):
if start is None:
start = self.nodes[0]
must_visit = self.nodes.copy()
path = [start]
must_visit.remove(start)
while must_visit:
# nearest = min(must_visit, key=lambda k: path[-1].cal_distance(k))
import random
nearest = must_visit[random.randint(0, len(must_visit) - 1)]
pos = min(path, key=lambda k: nearest.cal_distance(k))
pos_index = path.index(pos)
if pos_index == 0:
pos_insert = pos_index + 1
elif pos_index == len(path) - 1:
case_insert_after = length_road([path[-2], path[-1], nearest])
case_insert_before = length_road([path[-2], nearest, path[-1]])
if case_insert_after > case_insert_before:
pos_insert = pos_index
else:
pos_insert = pos_index + 1
else:
last_node = path[pos_index - 1]
next_node = path[pos_index + 1]
case_insert_before = length_road(
[last_node, nearest, pos, next_node])
case_insert_after = length_road(
[last_node, pos, nearest, next_node])
if case_insert_after > case_insert_before:
pos_insert = pos_index
else:
pos_insert = pos_index + 1
path.insert(pos_insert, nearest)
must_visit.remove(nearest)
return path
@staticmethod
def two_opt(route):
best = route
improved = True
while improved:
improved = False
for i in range(1, len(route) - 2):
for j in range(i + 1, len(route)):
if j - i == 1:
continue # changes nothing, skip then
new_route = route[:]
new_route[i:j] = route[
j - 1:i - 1:-1] # this is the 2woptSwap
if length_road(new_route) < length_road(best):
best = new_route
improved = True
route = best
return best
def find_shortest_path(self, key='nearest_neighbor'):
if key == 'nearest_neighbor':
self.nodes = self.nearest_neighbor()
elif key == 'random_insertion':
shortest_path = self.random_insertion()
for i in range(10):
random_path = self.random_insertion()
if length_road(random_path) < length_road(shortest_path):
shortest_path = random_path
self.nodes = shortest_path
elif key == 'two_opt':
self.nodes = self.two_opt(self.nearest_neighbor())
return self.nodes
def show_graph(self):
print(' -> '.join([node.name for node in self.nodes]))
def length_road(nodes):
sum = 0
for i in range(len(nodes) - 1):
sum += nodes[i].cal_distance(nodes[i + 1])
return sum
def main():
map = Graph()
f = open(argv[1], 'r')
lines = f.readlines()
f.close()
for line in lines:
info = line.split(', ')
map.add_node(Node(info[0], float(info[1]), float(info[2])))
map.find_shortest_path()
map.show_graph()
print('length of path:', length_road(map.nodes))
if __name__ == '__main__':
import time
now = time.time()
main()
print('time:', time.time() - now)
|
[
"you@example.com"
] |
you@example.com
|
ae2e1039ec5d63e87258338ed7b25d82ab0a6aad
|
30fe7671b60825a909428a30e3793bdf16eaaf29
|
/.metadata/.plugins/org.eclipse.core.resources/.history/33/b0033d0a4ffa00161174a93fd5908e78
|
e27685ffa45504a46e820c64ac565614f01f195a
|
[] |
no_license
|
abigdream84/PythonStudy
|
0fc7a3b6b4a03a293b850d0ed12d5472483c4fb1
|
059274d3ba6f34b62ff111cda3fb263bd6ca8bcb
|
refs/heads/master
| 2021-01-13T04:42:04.306730
| 2017-03-03T14:54:16
| 2017-03-03T14:54:16
| 79,123,274
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,424
|
#!/usr/bin/env python
#coding:UTF-8
from audit_demo.utility.MySqlHelper import MySqlHelper
class s_table(object):
def __init__(self):
self.__helper = MySqlHelper()
def add_ser(self,sername):
sql = 'insert into s_table(s_name,s_ip) values(%s)'
params = (username,)
try:
self.__helper.insert_one(sql,params)
except Exception as e:
print(e)
def get_user(self,username):
sql = 'select u_id from u_table where u_name = %s'
try:
u_id = self.__helper.select(sql,username)[0][0]
except Exception as e:
print(e)
return u_id
def upd_user(self,username_old,username_new):
sql = 'update u_table set u_name = %s where u_name = %s'
params = (username_new, username_old)
try:
self.__helper.update(sql,params)
except Exception as e:
print(e)
def del_user(self, username):
sql = 'delete from u_table where u_name=%s'
g_u_handle = g_u_relation()
if g_u_handle.get_u_g_id(username):
g_u_handle.del_u_g(username)
try:
self.__helper.delete(sql,username)
except Exception as e:
print(e)
else:
try:
self.__helper.delete(sql,username)
except Exception as e:
print(e)
|
[
"abigdream@hotmail.com"
] |
abigdream@hotmail.com
|
|
8920f9bea0a12cc6d1d38a9f94aab9488afa66c8
|
0d5be86072e92da0b5c086ec42bbfeeb6c1cf367
|
/tiny_tokenizer/word_tokenizers/mecab_tokenizer.py
|
c71164572d6df24cc3025c58ac1e64e53f7a0a04
|
[
"MIT"
] |
permissive
|
chie8842/tiny_tokenizer
|
d04eab4115daba443f83647a332177dcce5c9b19
|
6599873c050f4e064c88381688d8476346b57099
|
refs/heads/master
| 2020-07-25T18:57:15.545717
| 2019-09-12T15:39:42
| 2019-09-12T15:39:42
| 208,393,571
| 0
| 0
|
MIT
| 2019-09-14T05:26:24
| 2019-09-14T05:26:23
| null |
UTF-8
|
Python
| false
| false
| 1,655
|
py
|
from typing import Optional
from tiny_tokenizer.tiny_tokenizer_token import Token
from tiny_tokenizer.word_tokenizers.tokenizer import BaseTokenizer
class MeCabTokenizer(BaseTokenizer):
"""Wrapper class forexternal text analyzers"""
def __init__(
self, dictionary_path: Optional[str] = None, with_postag: bool = False
):
"""
Initializer for MeCabTokenizer.
Parameters
---
dictionary_path (Optional[str]=None)
path to a custom dictionary (option)
it is used by `mecab -u [dictionary_path]`
with_postag (bool=False)
flag determines iftiny_tokenizer.tokenizer include pos tags.
"""
super().__init__(name="mecab", with_postag=with_postag)
try:
import natto
except ModuleNotFoundError:
raise ModuleNotFoundError("natto-py is not installed")
flag = ""
if not self.with_postag:
flag += " -Owakati"
if dictionary_path is not None:
flag += f" -u {dictionary_path}"
self.mecab = natto.MeCab(flag)
def tokenize(self, text: str):
"""Tokenize"""
return_result = []
parse_result = self.mecab.parse(text)
if self.with_postag:
for elem in parse_result.split("\n")[:-1]:
surface, feature = elem.split()
postag = feature.split(",")[0]
return_result.append(Token(surface=surface, postag=postag))
else:
for surface in parse_result.split(" "):
return_result.append(Token(surface=surface))
return return_result
|
[
"himkt@klis.tsukuba.ac.jp"
] |
himkt@klis.tsukuba.ac.jp
|
0d591e3d250f5c8491dadeedc5a9c343ffd4224f
|
23acc991e4b6e96aa9ac0898ef59831009442a7e
|
/pygazebo/msg/plugin_pb2.py
|
7d2abf0447c68650685d40f2e751334f023e302f
|
[
"Apache-2.0"
] |
permissive
|
kunaltyagi/pygazebo
|
f07ee8c3a790095b66e074b0afa698c15a823d6a
|
4cd163f4efec5a6f672445de939385bf8a9156e1
|
refs/heads/master
| 2021-01-16T20:28:55.059663
| 2014-06-04T10:06:56
| 2014-06-04T10:06:56
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| true
| 2,176
|
py
|
# Generated by the protocol buffer compiler. DO NOT EDIT!
from google.protobuf import descriptor
from google.protobuf import message
from google.protobuf import reflection
from google.protobuf import descriptor_pb2
# @@protoc_insertion_point(imports)
DESCRIPTOR = descriptor.FileDescriptor(
name='plugin.proto',
package='gazebo.msgs',
serialized_pb='\n\x0cplugin.proto\x12\x0bgazebo.msgs\"<\n\x06Plugin\x12\x0c\n\x04name\x18\x01 \x02(\t\x12\x10\n\x08\x66ilename\x18\x02 \x02(\t\x12\x12\n\x08innerxml\x18\x03 \x01(\t:\x00')
_PLUGIN = descriptor.Descriptor(
name='Plugin',
full_name='gazebo.msgs.Plugin',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
descriptor.FieldDescriptor(
name='name', full_name='gazebo.msgs.Plugin.name', index=0,
number=1, type=9, cpp_type=9, label=2,
has_default_value=False, default_value=unicode("", "utf-8"),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
descriptor.FieldDescriptor(
name='filename', full_name='gazebo.msgs.Plugin.filename', index=1,
number=2, type=9, cpp_type=9, label=2,
has_default_value=False, default_value=unicode("", "utf-8"),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
descriptor.FieldDescriptor(
name='innerxml', full_name='gazebo.msgs.Plugin.innerxml', index=2,
number=3, type=9, cpp_type=9, label=1,
has_default_value=True, default_value=unicode("", "utf-8"),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
extension_ranges=[],
serialized_start=29,
serialized_end=89,
)
DESCRIPTOR.message_types_by_name['Plugin'] = _PLUGIN
class Plugin(message.Message):
__metaclass__ = reflection.GeneratedProtocolMessageType
DESCRIPTOR = _PLUGIN
# @@protoc_insertion_point(class_scope:gazebo.msgs.Plugin)
# @@protoc_insertion_point(module_scope)
|
[
"jjp@pobox.com"
] |
jjp@pobox.com
|
717d112a2b418a4f6c234f761f9bbf96d26b3535
|
753a70bc416e8dced2853f278b08ef60cdb3c768
|
/models/official/r1/mnist/mnist_test.py
|
87e0571234ac91fa0192c8ca65353a890ce0a363
|
[
"MIT",
"Apache-2.0"
] |
permissive
|
finnickniu/tensorflow_object_detection_tflite
|
ef94158e5350613590641880cb3c1062f7dd0efb
|
a115d918f6894a69586174653172be0b5d1de952
|
refs/heads/master
| 2023-04-06T04:59:24.985923
| 2022-09-20T16:29:08
| 2022-09-20T16:29:08
| 230,891,552
| 60
| 19
|
MIT
| 2023-03-25T00:31:18
| 2019-12-30T09:58:41
|
C++
|
UTF-8
|
Python
| false
| false
| 4,740
|
py
|
# Copyright 2017 The TensorFlow Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import time
import tensorflow.compat.v1 as tf # pylint: disable=g-bad-import-order
from absl import logging
from official.r1.mnist import mnist
BATCH_SIZE = 100
def dummy_input_fn():
image = tf.random.uniform([BATCH_SIZE, 784])
labels = tf.random.uniform([BATCH_SIZE, 1], maxval=9, dtype=tf.int32)
return image, labels
def make_estimator():
data_format = 'channels_last'
if tf.test.is_built_with_cuda():
data_format = 'channels_first'
return tf.estimator.Estimator(
model_fn=mnist.model_fn, params={
'data_format': data_format
})
class Tests(tf.test.TestCase):
"""Run tests for MNIST model.
MNIST uses contrib and will not work with TF 2.0. All tests are disabled if
using TF 2.0.
"""
def test_mnist(self):
classifier = make_estimator()
classifier.train(input_fn=dummy_input_fn, steps=2)
eval_results = classifier.evaluate(input_fn=dummy_input_fn, steps=1)
loss = eval_results['loss']
global_step = eval_results['global_step']
accuracy = eval_results['accuracy']
self.assertEqual(loss.shape, ())
self.assertEqual(2, global_step)
self.assertEqual(accuracy.shape, ())
input_fn = lambda: tf.random.uniform([3, 784])
predictions_generator = classifier.predict(input_fn)
for _ in range(3):
predictions = next(predictions_generator)
self.assertEqual(predictions['probabilities'].shape, (10,))
self.assertEqual(predictions['classes'].shape, ())
def mnist_model_fn_helper(self, mode, multi_gpu=False):
features, labels = dummy_input_fn()
image_count = features.shape[0]
spec = mnist.model_fn(features, labels, mode, {
'data_format': 'channels_last',
'multi_gpu': multi_gpu
})
if mode == tf.estimator.ModeKeys.PREDICT:
predictions = spec.predictions
self.assertAllEqual(predictions['probabilities'].shape, (image_count, 10))
self.assertEqual(predictions['probabilities'].dtype, tf.float32)
self.assertAllEqual(predictions['classes'].shape, (image_count,))
self.assertEqual(predictions['classes'].dtype, tf.int64)
if mode != tf.estimator.ModeKeys.PREDICT:
loss = spec.loss
self.assertAllEqual(loss.shape, ())
self.assertEqual(loss.dtype, tf.float32)
if mode == tf.estimator.ModeKeys.EVAL:
eval_metric_ops = spec.eval_metric_ops
self.assertAllEqual(eval_metric_ops['accuracy'][0].shape, ())
self.assertAllEqual(eval_metric_ops['accuracy'][1].shape, ())
self.assertEqual(eval_metric_ops['accuracy'][0].dtype, tf.float32)
self.assertEqual(eval_metric_ops['accuracy'][1].dtype, tf.float32)
def test_mnist_model_fn_train_mode(self):
self.mnist_model_fn_helper(tf.estimator.ModeKeys.TRAIN)
def test_mnist_model_fn_train_mode_multi_gpu(self):
self.mnist_model_fn_helper(tf.estimator.ModeKeys.TRAIN, multi_gpu=True)
def test_mnist_model_fn_eval_mode(self):
self.mnist_model_fn_helper(tf.estimator.ModeKeys.EVAL)
def test_mnist_model_fn_predict_mode(self):
self.mnist_model_fn_helper(tf.estimator.ModeKeys.PREDICT)
class Benchmarks(tf.test.Benchmark):
"""Simple speed benchmarking for MNIST."""
def benchmark_train_step_time(self):
classifier = make_estimator()
# Run one step to warmup any use of the GPU.
classifier.train(input_fn=dummy_input_fn, steps=1)
have_gpu = tf.test.is_gpu_available()
num_steps = 1000 if have_gpu else 100
name = 'train_step_time_%s' % ('gpu' if have_gpu else 'cpu')
start = time.time()
classifier.train(input_fn=dummy_input_fn, steps=num_steps)
end = time.time()
wall_time = (end - start) / num_steps
self.report_benchmark(
iters=num_steps,
wall_time=wall_time,
name=name,
extras={
'examples_per_sec': BATCH_SIZE / wall_time
})
if __name__ == '__main__':
logging.set_verbosity(logging.ERROR)
tf.disable_v2_behavior()
tf.test.main()
|
[
"finn.niu@apptech.com.hk"
] |
finn.niu@apptech.com.hk
|
5a9a226de42291f1f90430012f72aa1d128fea00
|
aaa4eb09ebb66b51f471ebceb39c2a8e7a22e50a
|
/Lista 08/exercício 05.py
|
d60d2357f70d2d5edfb22beaaf828ffda4ce7614
|
[
"MIT"
] |
permissive
|
Brenda-Werneck/Listas-CCF110
|
c0a079df9c26ec8bfe194072847b86b294a19d4a
|
271b0930e6cce1aaa279f81378205c5b2d3fa0b6
|
refs/heads/main
| 2023-09-03T09:59:05.351611
| 2021-10-17T00:49:03
| 2021-10-17T00:49:03
| 411,115,920
| 0
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 403
|
py
|
#Crie um algoritmo que leia os elementos de uma matriz inteira 10 x 10 e escreva somente os elementos acima da diagonal principal.
matriz = [[0 for i in range(10)] for j in range(10)]
for i in range(10):
for j in range(10):
matriz[i][j] = int(input(f"Digite o valor para o índice ({i},{j}): "))
for i in range(10):
for j in range(10):
if j > i:
print(matriz[i][j])
|
[
"89711195+Brenda-Werneck@users.noreply.github.com"
] |
89711195+Brenda-Werneck@users.noreply.github.com
|
327809a84718295084f6dd6659765fe2618759b4
|
2c4648efe8c7e408b8c3a649b2eed8bb846446ec
|
/codewars/Python/8 kyu/RegexCountLowercaseLetters/lowercase_count_test.py
|
9963e8b814750d42a58eaf4ce0dbc591bce0db78
|
[] |
no_license
|
Adasumizox/ProgrammingChallenges
|
9d79bd1b0ce4794b576124f9874aabb86d5c0713
|
3630fcde088d7991e344eb1b84805e9e756aa1a2
|
refs/heads/master
| 2021-07-16T08:16:57.538577
| 2020-07-19T19:58:28
| 2020-07-19T19:58:28
| 190,159,085
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,196
|
py
|
from lowercase_count import lowercase_count
import unittest
class TestRegexCountLowercaseLetters(unittest.TestCase):
def test(self):
self.assertEqual(lowercase_count("abc"), 3)
self.assertEqual(lowercase_count("abcABC123"), 3)
self.assertEqual(lowercase_count("abcABC123!@#$%^&*()_-+=}{[]|\':;?/>.<,~"), 3)
self.assertEqual(lowercase_count(""), 0)
self.assertEqual(lowercase_count("ABC123!@#$%^&*()_-+=}{[]|\':;?/>.<,~"), 0)
self.assertEqual(lowercase_count("abcdefghijklmnopqrstuvwxyz"), 26)
def test_rand(self):
from random import randint, choice
chars = "abcdefghijklmnopqrstuvwqyzqwertyuiopasdfghjklzxcvbnmABC0123456789!@#\$%^&*()-_+={}[]|\:;?/>.<,)"
def randchar():
return choice(chars)
def randstr(l):
return "".join(randchar() for _ in range(l))
def solution(strng):
return len([ch for ch in strng if ch.islower()])
for i in range(40):
strng = randstr(randint(5, 20))
self.assertEqual(lowercase_count(strng), solution(strng), "Failed when strng = '{}'".format(strng))
if __name__ == '__main__':
unittest.main()
|
[
"darkdan099@gmail.com"
] |
darkdan099@gmail.com
|
74d581b1542990d6c95912aba7444715cb02de7c
|
a350e6471598e8518f639fcff50511c35a94bceb
|
/docker/FlaskFileSystem/file_system.py
|
7b25c3b28c8fc371e8106f681690523fa29af01a
|
[
"MIT"
] |
permissive
|
WooodHead/bearing_project
|
2e26602c326f703869e13bf84cecba95edff59fa
|
ca64b04dad7010620414e37b2c7923fd904a0f11
|
refs/heads/master
| 2022-04-20T16:03:35.179584
| 2020-04-15T18:23:24
| 2020-04-15T18:23:24
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 5,332
|
py
|
#!/usr/bin/env python
# encoding: utf-8
"""
@author: zhanghe
@software: PyCharm
@file: file_system.py
@time: 2020-04-14 15:03
"""
# source .venv/bin/activate
# export FLASK_APP=file_system.py
# flask run -h 0.0.0.0
# * Running on http://127.0.0.1:5000/
from __future__ import unicode_literals
import os
from flask import Flask, flash, request, redirect, url_for
from werkzeug.utils import secure_filename
BASE_PATH = os.path.dirname(os.path.abspath(__file__))
UPLOAD_FOLDER = os.path.join(BASE_PATH, 'uploads')
if not os.path.exists(UPLOAD_FOLDER):
os.makedirs(UPLOAD_FOLDER)
ALLOWED_EXTENSIONS = {'txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif', 'xls', 'xlsx', 'doc', 'docx', 'ppt', 'pptx'}
app = Flask(
__name__,
static_folder='uploads',
static_url_path='/files',
)
app.config['DEBUG'] = True
# flash message 功能需要 SECRET_KEY
app.config['SECRET_KEY'] = '\x03\xabjR\xbbg\x82\x0b{\x96f\xca\xa8\xbdM\xb0x\xdbK%\xf2\x07\r\x8c'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024
@app.route('/')
def index():
return '''
<ul>
<li><a href="%s" target="_blank">%s</a></li>
</ul>
''' % (
url_for('downloads'),
url_for('downloads'),
)
def allowed_file(filename):
return '.' in filename and \
filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
@app.route('/uploads', methods=['GET', 'POST'])
def uploads():
"""文件上传"""
if request.method == 'POST':
# check if the post request has the file part
if 'file' not in request.files:
flash('No file part')
return redirect(request.url)
request_file = request.files['file']
# if user does not select file, browser also
# submit an empty part without filename
if request_file.filename == '':
flash('No selected file')
return redirect(request.url)
if request_file and allowed_file(request_file.filename):
filename = secure_filename(request_file.filename)
request_file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
return redirect(url_for('downloads', filename=filename))
else:
flash('Extension not allowed')
return redirect(request.url)
return '''
<!doctype html>
<title>Upload new File</title>
<h1>Upload new File</h1>
<form method=post enctype=multipart/form-data>
<input type=file name=file>
<input type=submit value=Upload>
</form>
'''
@app.route('/downloads/', methods=['GET', 'POST'])
@app.route('/downloads/<path:subdir>/', methods=['GET', 'POST'])
def downloads(subdir=''):
"""文件上传下载"""
if request.method == 'POST':
# check if the post request has the file part
if 'file' not in request.files:
flash('No file part')
return redirect(request.url)
request_file = request.files['file']
# if user does not select file, browser also
# submit an empty part without filename
if request_file.filename == '':
flash('No selected file')
return redirect(request.url)
if request_file and allowed_file(request_file.filename):
filename = secure_filename(request_file.filename)
cur_abs_dir = os.path.join(app.config['UPLOAD_FOLDER'], subdir)
print(os.path.join(cur_abs_dir, filename))
request_file.save(os.path.join(cur_abs_dir, filename))
return redirect(url_for('downloads', subdir=subdir))
else:
flash('Extension not allowed')
return redirect(request.url)
file_html = '''
<!doctype html>
<title>Uploads File</title>
<h3>Uploads File</h3>
<form method=post enctype=multipart/form-data>
<input type=file name=file>
<input type=submit value=Upload>
</form>
'''
# subdir = secure_filename(subdir)
cur_abs_dir = os.path.join(app.config['UPLOAD_FOLDER'], subdir)
for root, dirs, files in os.walk(cur_abs_dir, topdown=True):
print(root, dirs, files)
files.sort()
files.reverse()
# files.sort(reverse=True)
# 目录
if dirs:
file_html += '<div>'
file_html += '<span>目录</span>'
file_html += '<ul>'
for dir_name in dirs:
file_html += '<li>'
file_html += '<a href="%s">' % url_for('downloads', subdir=os.path.join(subdir, dir_name))
file_html += dir_name
file_html += '</a>'
file_html += '</li>'
file_html += '</ul>'
file_html += '</div>'
# 文件
if files:
file_html += '<div>'
file_html += '<span>文件</span>'
file_html += '<ul>'
for file_name in files:
file_html += '<li>'
file_html += '<a href="%s" target="_blank">' % url_for('static',
filename=os.path.join(subdir, file_name))
file_html += file_name
file_html += '</a>'
file_html += '</li>'
file_html += '</ul>'
file_html += '</div>'
break
return file_html
|
[
"zhang_he06@163.com"
] |
zhang_he06@163.com
|
fcee90732903a5d69df706143389337770cdb896
|
c498cefc16ba5d75b54d65297b88357d669c8f48
|
/static/datapack/data/scripts/quests/357_WarehouseKeepersAmbition/__init__.py
|
aaf1920475142e8f04ed667ebd0cdf21258eec6d
|
[] |
no_license
|
ManWithShotgun/l2i-JesusXD-3
|
e17f7307d9c5762b60a2039655d51ab36ec76fad
|
8e13b4dda28905792621088714ebb6a31f223c90
|
refs/heads/master
| 2021-01-17T16:10:42.561720
| 2016-07-22T18:41:22
| 2016-07-22T18:41:22
| 63,967,514
| 1
| 2
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,467
|
py
|
# Made by disKret
# Rate fix by Gnat
import sys
from ru.catssoftware import Config
from ru.catssoftware.gameserver.model.quest import State
from ru.catssoftware.gameserver.model.quest import QuestState
from ru.catssoftware.gameserver.model.quest.jython import QuestJython as JQuest
qn = "357_WarehouseKeepersAmbition"
#CUSTOM VALUES
DROPRATE=50
REWARD1=900 #This is paid per item
REWARD2=10000 #Extra reward, if > 100
#NPC
SILVA = 30686
#ITEMS
JADE_CRYSTAL = 5867
class Quest (JQuest) :
def __init__(self,id,name,descr):
JQuest.__init__(self,id,name,descr)
self.questItemIds = [JADE_CRYSTAL]
def onEvent (self,event,st) :
htmltext = event
if event == "30686-2.htm" :
st.set("cond","1")
st.setState(State.STARTED)
st.playSound("ItemSound.quest_accept")
elif event == "30686-7.htm" :
count = st.getQuestItemsCount(JADE_CRYSTAL)
if count:
reward = count * REWARD1
if count >= 100 :
reward = reward + REWARD2
st.takeItems(JADE_CRYSTAL,-1)
st.rewardItems(57,reward)
else:
htmltext="30686-4.htm"
if event == "30686-8.htm" :
st.playSound("ItemSound.quest_finish")
st.exitQuest(1)
return htmltext
def onTalk (self,npc,player):
htmltext = "<html><body>You are either not on a quest that involves this NPC, or you don't meet this NPC's minimum quest requirements.</body></html>"
st = player.getQuestState(qn)
if not st : return htmltext
npcId = npc.getNpcId()
id = st.getState()
cond=st.getInt("cond")
jade = st.getQuestItemsCount(JADE_CRYSTAL)
if cond == 0 :
if player.getLevel() >= 47 :
htmltext = "30686-0.htm"
else:
htmltext = "30686-0a.htm"
st.exitQuest(1)
elif not jade :
htmltext = "30686-4.htm"
elif jade :
htmltext = "30686-6.htm"
return htmltext
def onKill(self,npc,player,isPet):
partyMember = self.getRandomPartyMemberState(player,State.STARTED)
if not partyMember: return
st = partyMember.getQuestState(qn)
if st :
numItems, chance = divmod(DROPRATE*Config.RATE_DROP_QUEST,100)
if st.getRandom(100) < chance :
numItems += 1
if numItems :
st.giveItems(JADE_CRYSTAL,int(numItems))
st.playSound("ItemSound.quest_itemget")
return
QUEST = Quest(357,qn,"Warehouse Keepers Ambition")
QUEST.addStartNpc(SILVA)
QUEST.addTalkId(SILVA)
for MOBS in range(20594,20598) :
QUEST.addKillId(MOBS)
|
[
"u3n3ter7@mail.ru"
] |
u3n3ter7@mail.ru
|
cc69c17eb918fd897c9f5b7af3a2c749094d41a7
|
0dbfea9dcbbdf7a329c9d0f61831973b3168e560
|
/camera.py
|
a9b8a4f8902973ba7b1242f9bbea89e50609084c
|
[] |
no_license
|
SmartPracticeschool/SPS-4035-Intelligent-Best-Safety-Max-Safety-Rating-Generator-for-Restaurant
|
6e6be915bf0208c5a9ca1368f99d754051fd9fee
|
47ba68197c24623fee757788e03cbb41e5fca921
|
refs/heads/master
| 2022-12-11T09:28:01.007804
| 2020-09-11T10:20:54
| 2020-09-11T10:20:54
| 292,284,479
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,508
|
py
|
import cv2
import boto3
import datetime
import requests
face_cascade=cv2.CascadeClassifier("haarcascade_frontalface_alt2.xml")
ds_factor=0.6
count=0
class VideoCamera(object):
def __init__(self):
self.video = cv2.VideoCapture(0)
def __del__(self):
self.video.release()
def get_frame(self):
#count=0
global count
success, image = self.video.read()
is_success, im_buf_arr = cv2.imencode(".jpg", image)
image1 = im_buf_arr.tobytes()
client=boto3.client('rekognition',
aws_access_key_id="ASIA3JZX6DJK2IOZBPEV",
aws_secret_access_key="GQ4AuQs80d8r+gLfQCadeLY/vmll0SLFPQMF/x9P",
aws_session_token="FwoGZXIvYXdzEHoaDMK6+Vqt+bc4zxdiSyLKAe9iC6fIvoALw6dZuXTSz5Vb0GfE43zPfJTLsmHOA+pDUpGwlCEBfT6xXrgPq5XiGabwP/5ZFbp517LpM08a3f76c356zrXXYSVPazZogFUMc/qMDkEWly/SW66SeT9cgRirmZAj49GMGUBAFovwnWAUOmWEMJVOT+R7BCcRDs7qzlV8mrmhichmPsmSWqOcZsJY+2b99WyupvX8XorhsQepP0eQK0VkZVxU0FN1iFgijdC1FgZ51y0fKVfkXFbONQ2CXdn0EnAYOcAoqu3s+gUyLRhXqAddoXMzN2yXr8kKsDW9H2XiMzfy4lVX669OchDI696RMMVo3K66fvIdiA==",
region_name='us-east-1')
response = client.detect_custom_labels(
ProjectVersionArn='arn:aws:rekognition:us-east-1:776969525845:project/Mask-Detection2/version/Mask-Detection2.2020-09-07T23.02.02/1599499928143',Image={
'Bytes':image1})
print(response['CustomLabels'])
if not len(response['CustomLabels']):
count=count+1
date = str(datetime.datetime.now()).split(" ")[0]
#print(date)
url = " https://81ryisfwlc.execute-api.us-east-1.amazonaws.com/apiForMaskCount?date="+date+"&count="+str(count)
resp = requests.get(url)
f = open("countfile.txt", "w")
f.write(str(count))
f.close()
#print(count)
image=cv2.resize(image,None,fx=ds_factor,fy=ds_factor,interpolation=cv2.INTER_AREA)
gray=cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
face_rects=face_cascade.detectMultiScale(gray,1.3,5)
for (x,y,w,h) in face_rects:
cv2.rectangle(image,(x,y),(x+w,y+h),(0,255,0),2)
break
ret, jpeg = cv2.imencode('.jpg', image)
#cv2.putText(image, text = str(count), org=(10,40), fontFace=cv2.FONT_HERSHEY_PLAIN, fontScale=1, color=(1,0,0))
cv2.imshow('image',image)
return jpeg.tobytes()
|
[
"noreply@github.com"
] |
SmartPracticeschool.noreply@github.com
|
dbb97f0cbc36f2bfd81ed8cc7c03df74b429d7e7
|
dfe2a52a1c36a28a8bf85af7efd42380d980b773
|
/virtual/lib/python3.6/site-packages/social/tests/backends/test_skyrock.py
|
6c9bc03d42c8bfa986caebbc4d6173b6d3d79df5
|
[
"MIT"
] |
permissive
|
virginiah894/Instagram-clone
|
2c2a15d89fcdb25b22bd60428cf84a01f3bd553c
|
4d8abe7bafefae06a0e462e6a47631c2f8a1d361
|
refs/heads/master
| 2022-12-10T06:56:21.105357
| 2020-01-07T14:14:50
| 2020-01-07T14:14:50
| 229,394,540
| 3
| 0
|
MIT
| 2022-12-08T03:23:40
| 2019-12-21T07:41:19
|
Python
|
UTF-8
|
Python
| false
| false
| 1,343
|
py
|
import json
from social.p3 import urlencode
from social.tests.backends.oauth import OAuth1Test
class SkyrockOAuth1Test(OAuth1Test):
backend_path = 'social.backends.skyrock.SkyrockOAuth'
user_data_url = 'https://api.skyrock.com/v2/user/get.json'
expected_username = 'foobar'
access_token_body = json.dumps({
'access_token': 'foobar',
'token_type': 'bearer'
})
request_token_body = urlencode({
'oauth_token_secret': 'foobar-secret',
'oauth_token': 'foobar',
})
user_data_body = json.dumps({
'locale': 'en_US',
'city': '',
'has_blog': False,
'web_messager_enabled': True,
'email': 'foo@bar.com',
'username': 'foobar',
'firstname': 'Foo',
'user_url': '',
'address1': '',
'address2': '',
'has_profile': False,
'allow_messages_from': 'everybody',
'is_online': False,
'postalcode': '',
'lang': 'en',
'id_user': 10101010,
'name': 'Bar',
'gender': 0,
'avatar_url': 'http://www.skyrock.com/img/avatars/default-0.jpg',
'nb_friends': 0,
'country': 'US',
'birth_date': '1980-06-10'
})
def test_login(self):
self.do_login()
def test_partial_pipeline(self):
self.do_partial_pipeline()
|
[
"virgyperry@gmail.com"
] |
virgyperry@gmail.com
|
d8fd4caa1881767fdbdb3243b826d95602368b79
|
246e9200a834261eebcf1aaa54da5080981a24ea
|
/project-euler/26-50/quadratic-primes.py
|
687b00c3053fa2d1e6a26428025f06a178f6a92c
|
[] |
no_license
|
kalsotra2001/practice
|
db435514b7b57ce549b96a8baf64fad8f579da18
|
bbc8a458718ad875ce5b7caa0e56afe94ae6fa68
|
refs/heads/master
| 2021-12-15T20:48:21.186658
| 2017-09-07T23:01:56
| 2017-09-07T23:01:56
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 583
|
py
|
from math import sqrt
def prime(n):
if n < 2:
return False
if n == 2:
return True
else:
for div in range(2, int(sqrt(n)) + 1):
if n % div == 0:
return False
return True
max_primes = 0
product = 0
for i in range(-999, 1001):
for j in range(-999, 1001):
n = 0
while True:
s = n ** 2 + i * n + j
if prime(s) == False:
break
if n > max_primes:
max_primes = n
product = i * j
n += 1
print product
|
[
"jacquelineluo95@gmail.com"
] |
jacquelineluo95@gmail.com
|
c296bcf5d763803370519dbc7b0cfa134d9b4fc7
|
fd3f0fdc6af4d0b0205a70b7706caccab2c46dc0
|
/0x08-python-more_classes/1-rectangle.py
|
89807a014a51f03ba7255d4d66673efba41e72ac
|
[] |
no_license
|
Maynot2/holbertonschool-higher_level_programming
|
b41c0454a1d27fe34596fe4aacadf6fc8612cd23
|
230c3df96413cd22771d1c1b4c344961b4886a61
|
refs/heads/main
| 2023-05-04T05:43:19.457819
| 2021-05-12T14:51:56
| 2021-05-12T14:51:56
| 319,291,958
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,042
|
py
|
#!/usr/bin/python3
"""This module contains geometric shape classe(s)"""
class Rectangle:
"""Simulates a real world rectangle"""
def __init__(self, width=0, height=0):
"""Initialises a rectangle of a given width and height"""
self.width = width
self.height = height
@property
def width(self):
"""Retrieves the width"""
return self.__width
@width.setter
def width(self, size):
"""Sets the width"""
if not isinstance(size, int):
raise TypeError('width must be an integer')
if size < 0:
raise ValueError('width must be >= 0')
self.__width = size
@property
def height(self):
"""Retrieves the height"""
return self.__height
@height.setter
def height(self, size):
"""Sets the height"""
if not isinstance(size, int):
raise TypeError('height must be an integer')
if size < 0:
raise ValueError('height must be >= 0')
self.__height = size
|
[
"paulmanot@gmail.com"
] |
paulmanot@gmail.com
|
5c6620edec199d9f5d5a8418a074133844d17c7c
|
e34d69f33d9bf3d9de99343ba24ad78bc5197a93
|
/scripts/cmp_lj_sync
|
f25d123129b22ec54a527691be2a502d7f0f1e29
|
[] |
no_license
|
cms-ttH/ttH-TauRoast
|
8e8728a49d02d9e8d7dc119376a4aefb6e8fd77d
|
3fe6529d7270dc091db00f95997ca6add8b95ac9
|
refs/heads/master
| 2021-01-24T06:13:06.485445
| 2017-10-11T14:04:05
| 2017-10-11T14:04:05
| 10,819,593
| 2
| 5
| null | 2016-09-15T07:19:20
| 2013-06-20T12:46:59
|
Python
|
UTF-8
|
Python
| false
| false
| 656
|
#!/usr/bin/env python
import sys
def read(fn):
evts = {}
with open(fn) as f:
for line in f:
if not line.startswith('1'):
continue
run, lumi, event, stub = line.split(',', 3)
evts[(run, lumi, event)] = stub
return evts
me = read(sys.argv[1])
kit = read(sys.argv[2])
mkeys = set(me.keys())
kkeys = set(kit.keys())
for k in mkeys - kkeys:
print "me", ",".join(list(k) + [me[k]]).strip()
for k in kkeys - mkeys:
print "kit", ",".join(list(k) + [kit[k]]).strip()
print len(mkeys - kkeys), "events unique in first file"
print len(kkeys - mkeys), "events unique in second file"
|
[
"matthias@sushinara.net"
] |
matthias@sushinara.net
|
|
d0be707b6b95674e7a55339a7774568045b2a525
|
6a7058009587e78b5c758ff783410325ad7c2a4b
|
/educative/slidingWindow/non_repeat_substring.py
|
2883b8e112151f20e144a97d63367dc9680d312d
|
[
"Apache-2.0"
] |
permissive
|
stacykutyepov/python-cp-cheatsheet
|
8b96b76403c501f5579befd07b3c4a4c69fe914e
|
a00a57e1b36433648d1cace331e15ff276cef189
|
refs/heads/master
| 2023-07-16T13:26:35.130763
| 2021-08-30T11:23:39
| 2021-08-30T11:23:39
| 401,442,535
| 2
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 537
|
py
|
"""
time: 13 min
errors: none!
"""
def non_repeat_substring(str):
maxLen, i = 0, 0
ht = {}
for i, c in enumerate(str):
if c in ht:
maxLen = max(maxLen, len(ht))
ht.clear()
ht[c] = True
maxLen = max(len(ht), maxLen)
return maxLen
def main():
print("Length of the longest substring: " + str(non_repeat_substring("aabccbb")))
print("Length of the longest substring: " + str(non_repeat_substring("abbbb")))
print("Length of the longest substring: " + str(non_repeat_substring("abccde")))
main()
|
[
"peterrlamar@gmail.com"
] |
peterrlamar@gmail.com
|
9610d71e683b7cf6ba117adf541c9de69f52aee6
|
7b5828edda7751700ca7002b40a214e39e5f48a8
|
/EA/core/sims4/gsi/command_buffer.py
|
e1301ea4581704ced936304f7533eab0b6fbd36f
|
[] |
no_license
|
daniela-venuta/Sims-4-Python-Script-Workspace
|
54c33dac02f84daed66f46b7307f222fede0fa62
|
f408b28fb34626b2e3b2953152343d591a328d66
|
refs/heads/main
| 2023-03-29T18:08:39.202803
| 2021-03-30T19:00:42
| 2021-03-30T19:00:42
| 353,111,243
| 1
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,504
|
py
|
import collections
try:
import threading
_threading_enabled = True
except ImportError:
import dummy_threading as threading
_threading_enabled = False
import sims4.commands
import sims4.log
import sims4.service_manager
logger = sims4.log.Logger('GSI')
_Command = collections.namedtuple('_Command', ('command_string', 'callback', 'output_override', 'zone_id', 'connection_id'))
def _execute_command(command):
real_output = sims4.commands.output
sims4.commands.output = command.output_override
result = False
try:
if command.zone_id is not None:
sims4.commands.execute(command.command_string, command.connection_id)
else:
sims4.commands.execute(command.command_string, None)
result = True
except Exception:
result = False
logger.exception('Error while executing game command for')
finally:
sims4.commands.output = real_output
command.callback(result)
if _threading_enabled:
class CommandBufferService(sims4.service_manager.Service):
def __init__(self):
self.pending_commands = None
self._lock = threading.Lock()
def start(self):
with self._lock:
self.pending_commands = []
def stop(self):
with self._lock:
self.pending_commands = None
def add_command(self, command_string, callback=None, output_override=None, zone_id=None, connection_id=None):
with self._lock:
if self.pending_commands is not None:
command = _Command(command_string, callback, output_override, zone_id, connection_id)
self.pending_commands.append(command)
def on_tick(self):
with self._lock:
if not self.pending_commands:
return
local_pending_commands = list(self.pending_commands)
del self.pending_commands[:]
for command in local_pending_commands:
_execute_command(command)
else:
class CommandBufferService(sims4.service_manager.Service):
def add_command(self, command_string, callback=None, output_override=None, zone_id=None, connection_id=None):
command = _Command(command_string, callback, output_override, zone_id, connection_id)
_execute_command(command)
def on_tick(self):
pass
|
[
"44103490+daniela-venuta@users.noreply.github.com"
] |
44103490+daniela-venuta@users.noreply.github.com
|
309cd04173b4d096eb7b590ed67fc399ef2c0877
|
cf668ede675f5b5a49912e8ca2170b5d5dba85c3
|
/FullDesign/LsRand_OnlyTau_4.py
|
3d9e3b41a25a22b071485ba0d01de3c81c709d52
|
[] |
no_license
|
amemil/MasterThesisRaw
|
b6c97a671e740871be541539384192684f5f1966
|
bb357481cc47ef3a2b241f4b1df85fd0a4ff1de0
|
refs/heads/main
| 2023-06-09T22:49:06.082380
| 2021-06-25T09:38:20
| 2021-06-25T09:38:20
| 327,104,381
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,631
|
py
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed May 12 19:29:28 2021
@author: emilam
"""
import sys, os
import numpy as np
sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))
import UtilitiesMaster as ut
s1init1 = np.load('s1init_16.npy')
s2init1 = np.load('s2init_16.npy')
Winit1 = np.load('Winit_16.npy')
s1init2 = np.load('s1init_17.npy')
s2init2 = np.load('s2init_17.npy')
Winit2 = np.load('Winit_17.npy')
s1init3 = np.load('s1init_18.npy')
s2init3 = np.load('s2init_18.npy')
Winit3 = np.load('Winit_18.npy')
s1init4 = np.load('s1init_19.npy')
s2init4 = np.load('s2init_19.npy')
Winit4= np.load('Winit_19.npy')
s1init5 = np.load('s1init_20.npy')
s2init5 = np.load('s2init_20.npy')
Winit5 = np.load('Winit_20.npy')
indx = [16,17,18,19,20]
s1s = [s1init1,s1init2,s1init3,s1init4,s1init5]
s2s = [s2init1,s2init2,s2init3,s2init4,s2init5]
ws = [Winit1,Winit2,Winit3,Winit4,Winit5]
for i in range(5):
design = ut.ExperimentDesign(freqs_init=np.array([20,50,100,200]),maxtime=60,trialsize=5\
,Ap=0.005, tau=0.02, genstd=0.0001,b1=-3.1, b2=-3.1, w0=1.0,binsize = 1/500.0,reals = 20,longinit = 60\
,s1init = s1s[i],s2init = s2s[i],Winit = ws[i])
means,entrs,optms,W,posts = design.onlineDesign_wh_tau(nofreq =False,constant = False, random = True, optimised = False)
np.save('RandEstimatesTau_'+str(indx[i]),means)
np.save('RandEntropiesTau_'+str(indx[i]),entrs)
np.save('RandWTau_'+str(indx[i]),W)
np.save('RandPostsTau_'+str(indx[i]),posts)
np.save('RandFreqsTau_'+str(indx[i]),optms)
|
[
"emilalvar.myhre@gmail.com"
] |
emilalvar.myhre@gmail.com
|
9eb21a225d99d72d993744068321b270fe85c8e0
|
f9d564f1aa83eca45872dab7fbaa26dd48210d08
|
/huaweicloud-sdk-iotda/huaweicloudsdkiotda/v5/model/mysql_forwarding.py
|
1bd1a82ee4f076d2f13ebb0d6b9e7b5b2c2a94ed
|
[
"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
| 8,910
|
py
|
# coding: utf-8
import six
from huaweicloudsdkcore.utils.http_utils import sanitize_for_serialization
class MysqlForwarding:
"""
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 = []
sensitive_list.append('password')
openapi_types = {
'address': 'NetAddress',
'db_name': 'str',
'username': 'str',
'password': 'str',
'enable_ssl': 'bool',
'table_name': 'str',
'column_mappings': 'list[ColumnMapping]'
}
attribute_map = {
'address': 'address',
'db_name': 'db_name',
'username': 'username',
'password': 'password',
'enable_ssl': 'enable_ssl',
'table_name': 'table_name',
'column_mappings': 'column_mappings'
}
def __init__(self, address=None, db_name=None, username=None, password=None, enable_ssl=None, table_name=None, column_mappings=None):
"""MysqlForwarding
The model defined in huaweicloud sdk
:param address:
:type address: :class:`huaweicloudsdkiotda.v5.NetAddress`
:param db_name: **参数说明**:连接MYSQL数据库的库名。 **取值范围**:长度不超过64,只允许字母、数字、下划线(_)、连接符(-)的组合。
:type db_name: str
:param username: **参数说明**:连接MYSQL数据库的用户名
:type username: str
:param password: **参数说明**:连接MYSQL数据库的密码
:type password: str
:param enable_ssl: **参数说明**:客户端是否使用SSL连接服务端,默认为true
:type enable_ssl: bool
:param table_name: **参数说明**:MYSQL数据库的表名
:type table_name: str
:param column_mappings: **参数说明**:MYSQL数据库的列和流转数据的对应关系列表。
:type column_mappings: list[:class:`huaweicloudsdkiotda.v5.ColumnMapping`]
"""
self._address = None
self._db_name = None
self._username = None
self._password = None
self._enable_ssl = None
self._table_name = None
self._column_mappings = None
self.discriminator = None
self.address = address
self.db_name = db_name
self.username = username
self.password = password
if enable_ssl is not None:
self.enable_ssl = enable_ssl
self.table_name = table_name
self.column_mappings = column_mappings
@property
def address(self):
"""Gets the address of this MysqlForwarding.
:return: The address of this MysqlForwarding.
:rtype: :class:`huaweicloudsdkiotda.v5.NetAddress`
"""
return self._address
@address.setter
def address(self, address):
"""Sets the address of this MysqlForwarding.
:param address: The address of this MysqlForwarding.
:type address: :class:`huaweicloudsdkiotda.v5.NetAddress`
"""
self._address = address
@property
def db_name(self):
"""Gets the db_name of this MysqlForwarding.
**参数说明**:连接MYSQL数据库的库名。 **取值范围**:长度不超过64,只允许字母、数字、下划线(_)、连接符(-)的组合。
:return: The db_name of this MysqlForwarding.
:rtype: str
"""
return self._db_name
@db_name.setter
def db_name(self, db_name):
"""Sets the db_name of this MysqlForwarding.
**参数说明**:连接MYSQL数据库的库名。 **取值范围**:长度不超过64,只允许字母、数字、下划线(_)、连接符(-)的组合。
:param db_name: The db_name of this MysqlForwarding.
:type db_name: str
"""
self._db_name = db_name
@property
def username(self):
"""Gets the username of this MysqlForwarding.
**参数说明**:连接MYSQL数据库的用户名
:return: The username of this MysqlForwarding.
:rtype: str
"""
return self._username
@username.setter
def username(self, username):
"""Sets the username of this MysqlForwarding.
**参数说明**:连接MYSQL数据库的用户名
:param username: The username of this MysqlForwarding.
:type username: str
"""
self._username = username
@property
def password(self):
"""Gets the password of this MysqlForwarding.
**参数说明**:连接MYSQL数据库的密码
:return: The password of this MysqlForwarding.
:rtype: str
"""
return self._password
@password.setter
def password(self, password):
"""Sets the password of this MysqlForwarding.
**参数说明**:连接MYSQL数据库的密码
:param password: The password of this MysqlForwarding.
:type password: str
"""
self._password = password
@property
def enable_ssl(self):
"""Gets the enable_ssl of this MysqlForwarding.
**参数说明**:客户端是否使用SSL连接服务端,默认为true
:return: The enable_ssl of this MysqlForwarding.
:rtype: bool
"""
return self._enable_ssl
@enable_ssl.setter
def enable_ssl(self, enable_ssl):
"""Sets the enable_ssl of this MysqlForwarding.
**参数说明**:客户端是否使用SSL连接服务端,默认为true
:param enable_ssl: The enable_ssl of this MysqlForwarding.
:type enable_ssl: bool
"""
self._enable_ssl = enable_ssl
@property
def table_name(self):
"""Gets the table_name of this MysqlForwarding.
**参数说明**:MYSQL数据库的表名
:return: The table_name of this MysqlForwarding.
:rtype: str
"""
return self._table_name
@table_name.setter
def table_name(self, table_name):
"""Sets the table_name of this MysqlForwarding.
**参数说明**:MYSQL数据库的表名
:param table_name: The table_name of this MysqlForwarding.
:type table_name: str
"""
self._table_name = table_name
@property
def column_mappings(self):
"""Gets the column_mappings of this MysqlForwarding.
**参数说明**:MYSQL数据库的列和流转数据的对应关系列表。
:return: The column_mappings of this MysqlForwarding.
:rtype: list[:class:`huaweicloudsdkiotda.v5.ColumnMapping`]
"""
return self._column_mappings
@column_mappings.setter
def column_mappings(self, column_mappings):
"""Sets the column_mappings of this MysqlForwarding.
**参数说明**:MYSQL数据库的列和流转数据的对应关系列表。
:param column_mappings: The column_mappings of this MysqlForwarding.
:type column_mappings: list[:class:`huaweicloudsdkiotda.v5.ColumnMapping`]
"""
self._column_mappings = column_mappings
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, MysqlForwarding):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
|
[
"hwcloudsdk@huawei.com"
] |
hwcloudsdk@huawei.com
|
a7a8a4fc6a4d8860a7cbcf0990e903217b21bb30
|
fd40d6375ddae5c8613004a411341f0c984e80d5
|
/src/visions/core/implementations/types/visions_datetime.py
|
f8a11f0c6b5bf06f1ed01080801bdba0c704c5d0
|
[
"LicenseRef-scancode-public-domain",
"MIT"
] |
permissive
|
ieaves/tenzing
|
93c3353e62621c90adefc5a174a2dcde9aacbc46
|
92d39c1c3a5633d8074e0ffe8c2687c465aebbc8
|
refs/heads/master
| 2020-04-25T07:14:31.388737
| 2020-01-07T02:51:13
| 2020-01-07T02:51:13
| 172,608,080
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,360
|
py
|
import pandas.api.types as pdt
import pandas as pd
from typing import Sequence
from visions.core.model.relations import (
IdentityRelation,
InferenceRelation,
TypeRelation,
)
from visions.core.model.type import VisionsBaseType
from visions.core.implementations.types import visions_string
from visions.utils.coercion import test_utils
def to_datetime(series: pd.Series) -> pd.Series:
return pd.to_datetime(series)
def _get_relations() -> Sequence[TypeRelation]:
from visions.core.implementations.types import visions_generic
relations = [
IdentityRelation(visions_datetime, visions_generic),
InferenceRelation(
visions_datetime,
visions_string,
relationship=test_utils.coercion_test(to_datetime),
transformer=to_datetime,
),
]
return relations
class visions_datetime(VisionsBaseType):
"""**Datetime** implementation of :class:`visions.core.model.type.VisionsBaseType`.
Examples:
>>> x = pd.Series([pd.datetime(2017, 3, 5), pd.datetime(2019, 12, 4)])
>>> x in visions_datetime
True
"""
@classmethod
def get_relations(cls) -> Sequence[TypeRelation]:
return _get_relations()
@classmethod
def contains_op(cls, series: pd.Series) -> bool:
return pdt.is_datetime64_any_dtype(series)
|
[
"ian.k.eaves@gmail.com"
] |
ian.k.eaves@gmail.com
|
045849a6dcf37e6dfd8deaa91796aebe1f3f2334
|
c6609c161df66949656ca91d8a3d9f4d27a4c399
|
/rates_project_04122021/rates_client/rates_client/rate_client.py
|
71771ba20ad4886144213eb414be5cd5d7451817
|
[
"MIT"
] |
permissive
|
t4d-classes/advanced-python_04122021
|
b93ea38c5b35af2b1eb06bc1d5fe6d3f0c1cf39f
|
07b27aea8ac3c7170eb66d5243c5cd841f41322c
|
refs/heads/master
| 2023-04-11T11:45:18.114381
| 2021-04-20T12:36:04
| 2021-04-20T12:36:04
| 357,016,025
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,063
|
py
|
""" rate client module """
import socket
import sys
import pathlib
import yaml
from rates_shared.utils import read_config
def main() -> None:
"""Main Function"""
try:
config = read_config()
host = config["server"]["host"]
port = int(config["server"]["port"])
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as client_socket:
client_socket.connect((host, port))
print(client_socket.recv(2048).decode("UTF-8"))
while True:
command = input("> ")
if command == "exit":
break
else:
client_socket.sendall(command.encode("UTF-8"))
print(client_socket.recv(2048).decode("UTF-8"))
client_socket.close()
except ConnectionResetError:
print("Server connection was closed.")
except ConnectionRefusedError:
print("Server is not running.")
except KeyboardInterrupt:
pass
sys.exit(0)
if __name__ == '__main__':
main()
|
[
"eric@t4d.io"
] |
eric@t4d.io
|
f9ed10bc581a959ecacc6f7e395dd6fef7ea68b0
|
016f96e528141db111f15a4c00a0fc46e61cdff6
|
/lib/emailses/urls.py
|
5fb0d6077dd92bf4cd7ecabb113f5b0498156de9
|
[
"BSD-2-Clause"
] |
permissive
|
hdknr/emailqueue
|
3d02407b06a492cdf9b89fde2b06c766cd500555
|
05e108562f4fb612440f769973b9a3d02c11afcd
|
refs/heads/master
| 2021-01-23T20:13:04.807258
| 2015-10-08T08:41:51
| 2015-10-08T08:41:51
| 20,243,165
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 131
|
py
|
from django.conf.urls import url
import views
urlpatterns = [
url(r'(?P<topic>.+)', views.notify, name='emailses_notify'),
]
|
[
"gmail@hdknr.com"
] |
gmail@hdknr.com
|
193e2e78f289aa1bb05e4b344b5c7d17b61c984e
|
6b0161214e4db57a81d3b4432d82c874c7106f13
|
/couchbase/_pyport.py
|
20700a813860e5ed162b08ac93b31aa54775c92d
|
[
"Apache-2.0"
] |
permissive
|
neilalbrock/couchbase-python-client
|
de9d6115d1240f56f4cb7b57aee7e8765c5c7d1f
|
95789e3d49c42613fe719bbd02e6d9ad30216334
|
refs/heads/master
| 2021-01-15T18:51:31.311163
| 2013-10-14T13:58:28
| 2013-10-14T13:58:28
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,140
|
py
|
#
# Copyright 2013, Couchbase, 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.
#
# This module contains various mappings for modules which have had
# their names changed across Python major versions
try:
import urllib.parse as ulp
from urllib.request import urlopen
from urllib.parse import parse_qs
except ImportError:
import urllib as ulp
from urllib2 import urlopen
from urlparse import parse_qs
try:
long = long
except NameError:
long = int
try:
xrange = xrange
except NameError:
xrange = range
try:
basestring = basestring
except NameError:
basestring = str
|
[
"mnunberg@haskalah.org"
] |
mnunberg@haskalah.org
|
6c6e0e149c60270d3573a57dfa2fd3aa115c5361
|
e1fe1ed4f2ba8ab0146ce7c08d65bc7947150fc8
|
/credit11315/spiders/no_redis_detail_info_scrapy.py
|
3fb233a4bbd3603929edc4969dbae24a6847b673
|
[] |
no_license
|
yidun55/credit11315
|
0d88ceef314efa444de58eb5da8939c1acff3abe
|
b048ec9db036a382287d5faacb9490ccbf50735c
|
refs/heads/master
| 2021-01-20T01:03:30.617914
| 2015-07-31T09:58:24
| 2015-07-31T09:58:24
| 38,853,611
| 0
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 5,621
|
py
|
#!usr/bin/env python
#coding: utf-8
"""
从11315全国企业征信系统http://www.11315.com/上
爬取企业信息
"""
from scrapy.spider import Spider
from scrapy.http import Request
from scrapy import log
from scrapy import signals
from scrapy import Selector
from scrapy.exceptions import DontCloseSpider
import sys
from credit11315.items import *
from credit11315.middlewares import UnknownResponseError, ForbbidenResponseError
from credit11315.tool.for_ominated_strip import for_ominated_data
from credit11315.tool.for_JCXX import extract_combine_JCXX
from credit11315.tool.for_all_blocks_info_extract import block_info_extract
from credit11315.tool.for_fundation_info_extract import fundation_info_extract
import HTMLParser
import redis
import urllib2
reload(sys)
sys.setdefaultencoding("utf-8")
class GetDetailInfo(Spider):
"""
从redis上读取url,并提取企业的信息
"""
name = 'noredisdetail'
start_urls = ['http://www.11315.com']
def set_crawler(self,crawler):
super(GetDetailInfo, self).set_crawler(crawler)
self.crawler.signals.connect(self.spider_idle,\
signal=signals.spider_idle)
def spider_idle(self):
raise DontCloseSpider
def parse(self,response):
urlPath = '/home/dyh/data/credit11315/detailUrl\
/uniq_all_detail_url'
f = open(urlPath, "r")
for url in f:
yield Request(url.strip(),callback=my_parse,\
dont_filter=True)
def my_parse(self, response):
"""
解析
"""
sel = Selector(text=response.body)
print len(sel.xpath(u"//b[text()='单位名称']"))!= 0, "parse 条件"
log.msg("parse 条件=%s"%str(len(sel.xpath(u"//b[text()='单位名称']")) != 0), level=log.INFO)
if (len(sel.xpath(u"//b[text()='单位名称']")) != 0): #判别是否为要输入验证码
pass
else:
log.msg("code=%s, %s"%(str(response.status),response.body), level=log.INFO)
raise UnknownResponseError
#========================================================
"""
第一部分:企业信用档案
"""
item = DetailInformation()
item['basic_info'] = fundation_info_extract(response)
#========================================================
#========================================================
"""
第一部分 政府监管信息
"""
item['regulatory_info'] = extract_combine_JCXX(response)
#========================================================
#========================================================
"""
第三部分 行业评价信息
"""
keywords_list = ['2-1.体系/产品/行业认证信息',
'2-2.行业协会(社会组织)评价信息',\
'2-3.水电气通讯等公共事业单位评价']
item['envaluated_info'] = block_info_extract(response,\
keywords_list)
#========================================================
"""
第四部分 媒体评价信息
"""
keywords_list = ['3-1.媒体评价信息']
item['media_env'] = block_info_extract(response, keywords_list)
#========================================================
"""
第五部分 金融信贷信息
"""
#url = 'http://www.11315.com/\
#getTradeLendingCount?companyId=%s'%response.url[7:15]
#header = {'User-Agent':"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.89 Safari/537.36",
# 'Referer':response.url}
#req = urllib2.Request(url=url, headers=header)
#xtml = urllib2.urlopen(req)
#Nums = xtml.read()
#print Nums, "this is Nums"
#Nums = eval(Nums).split(",")
#print Nums, "this is anothor Nums"
#total = str(sum([int(i) for i in Nums]))
#Nums.insert(0, total) #在头部插入
#if total == '0':
# t_url = ""
#else:
# t_url = sel.xpath(u"//script").re(ur"html\(\'<a href=\"([\w\W]*?)\"")[0]
#Nums.append(t_url)
#Nums_re = "|".join(Nums)
keywords_list = ['4-2.民间借贷评价信息']
item["credit_fin"] = block_info_extract(response, keywords_list)
#=======================================================
"""
第六部分 企业运营信息
"""
#keywords_list = ['5-3.水电煤气电话费信息',
#'5-4.纳税信息'] #要么运行js,要么模拟请求,破网站,就两行数据至于吗
#item['operation_info'] = block_info_extract(response, keywords_list)
#========================================================
"""
第七部分 市场反馈信息
"""
keywords_list = ['6-1.消费者评价信息',
'6-2.企业之间履约评价','6-3.员工评价信息',
'6-4.其他']
item['feedback_info'] = block_info_extract(response, keywords_list)
#========================================================
return item
#else:
# print "raise unknownresponseError in spider", response.request.meta
# #raise UnknownResponseError
# #raise ForbbidenResponseError("work or no nnnnnn")
# request = response.request
# retryreq = request.copy()
# retryreq.dont_filter = True
# log.msg("UnknowResponseError %s"%response.body, level=log.INFO)
# yield retryreq
|
[
"heshang1203@sina.com"
] |
heshang1203@sina.com
|
f36e4bac20c903f91a082d88b22b765caafeac35
|
a708f1d36586d2b01c99f2cb44aa4612b10192f6
|
/周赛/week183/5376非递增顺序.py
|
eb36dbf409919c8981dd21302f726a93af63edc0
|
[] |
no_license
|
LeopoldACC/Algorithm
|
2477e8a371e9cdc5a47b582ca2a454539b96071e
|
fc1b0bec0e28d31e9a6ff722b3a66eacb0278148
|
refs/heads/master
| 2023-01-25T02:28:14.422447
| 2020-12-03T15:01:10
| 2020-12-03T15:01:10
| 197,297,197
| 2
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,041
|
py
|
class Solution:###最终版
def minSubsequence(self, nums):
nums = sorted(nums)
prefix_sum = nums[:]
for i in range(len(nums)-2,-1,-1):
prefix_sum[i]+=prefix_sum[i+1]
index = -1
for i in range(len(nums)-1,-1,-1):
if prefix_sum[i]>prefix_sum[0]//2:
index = i
break
return nums[index:][::-1]
class Solution0:
def minSubsequence(self, nums):
nums = sorted(nums)
prefix_sum =nums[:]
for i in range(len(nums)):
prefix_sum[i]+=nums[i]
target = prefix_sum[-1]//2
index = self.bisec(prefix_sum,target)
return nums[index:][::-1]
def bisec(self,prefix,target):
start,end = 0,len(prefix)-1
while start+1<end:
mid = (start+end)//2
if prefix[mid]<=target:
start = mid
else:
end = mid
return end if prefix[end]>target else start
s = Solution()
s.minSubsequence([4,4,7,6,7])
|
[
"zhenggong9831@gmail.com"
] |
zhenggong9831@gmail.com
|
499a03357c8ae0101e94a0ea850bdfd693fd861f
|
77fc5af96da1d461c86c7f9668b64b99ca04a1b6
|
/codes/montecarlo.py
|
32c0ce13aa246aa42786f17cd7c0371a3c56965c
|
[] |
no_license
|
rene-d/edupython
|
5b6bc8ddb5eb8ec896ee70fb961d4e689af1075a
|
1261d0c7aae17bb2d4ff3370860768b73ba4172d
|
refs/heads/master
| 2020-11-24T10:07:18.504472
| 2019-12-21T21:03:08
| 2019-12-21T21:03:08
| 228,099,675
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 924
|
py
|
# Découpe d'un carré en 3 zones
# https://edupython.tuxfamily.org/sources/view.php?code=montecarlo
# Les zones sont les domaines du plan délimitées par les courbes
# des fonctions carré et racine carrée, à l'intérieur du carré unité,
# dans un repère orthonormal.
# Les aires sont obtenues par la méthode de Monte Carlo.
# On choisit un point au hasard dans le carré unité 10 000 fois
# Et on estime ainsi l'aire de chaque domaine.
a, b, c = 0, 0, 0
for i in range (10000) :
x, y = random(), random()
if y > sqrt (x) : a = a + 1
elif y > x * x : b = b + 1
else : c = c + 1
print ("On est dans la zone A", a, "fois sur 10 000.")
print ("On est dans la zone B", b, "fois sur 10 000.")
print ("On est dans la zone C", c, "fois sur 10 000.")
print ("Donc les aires respectives des zones A, B et C",end="")
print ("sont estimées à", a / 10000, ",", b / 10000, "et", c / 10000, "unités d'aire.")
|
[
"rene.devichi@gmail.com"
] |
rene.devichi@gmail.com
|
80f832455983b37492aabb45c118bac2cd8e5ae4
|
e49f2251e07a70c943b70bbae27c439631a31552
|
/tfx/components/model_validator/component.py
|
d6bc178a4182f17e0e083067fa3c9cd3df96c6b5
|
[
"Apache-2.0"
] |
permissive
|
hephaex/tfx
|
eac03c1ab670368088ec2a49af28ff374dc95c4a
|
76d8731cb54be3451e10d270d8bcb0589401135f
|
refs/heads/master
| 2020-09-16T11:52:06.198631
| 2019-11-23T21:01:50
| 2019-11-23T21:45:46
| 223,760,941
| 1
| 0
|
Apache-2.0
| 2019-11-24T14:53:08
| 2019-11-24T14:53:08
| null |
UTF-8
|
Python
| false
| false
| 4,026
|
py
|
# Lint as: python2, python3
# Copyright 2019 Google LLC. 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.
"""TFX ModelValidator component definition."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from typing import Optional, Text
from tfx import types
from tfx.components.base import base_component
from tfx.components.base import executor_spec
from tfx.components.model_validator import driver
from tfx.components.model_validator import executor
from tfx.types import standard_artifacts
from tfx.types.standard_component_specs import ModelValidatorSpec
class ModelValidator(base_component.BaseComponent):
"""A TFX component to validate a newly trained model against a prior model.
The model validator component can be used to check model metrics threshold
and validate current model against a previously validated model. If there
isn't a prior validated model, model validator will just make sure the
threshold passed. Otherwise, ModelValidator compares a newly trained models
against a known good model, specifically the last model "blessed" by this
component. A model is "blessed" if the exported model's metrics are within
predefined thresholds around the prior model's metrics.
*Note:* This component includes a driver to resolve last blessed model.
## Possible causes why model validation fails
Model validation can fail for many reasons, but these are the most common:
- problems with training data. For example, negative examples are dropped or
features are missing.
- problems with the test or evaluation data. For example, skew exists between
the training and evaluation data.
- changes in data distribution. This indicates the user behavior may have
changed over time.
- problems with the trainer. For example, the trainer was stopped before
model is converged or the model is unstable.
## Example
```
# Performs quality validation of a candidate model (compared to a baseline).
model_validator = ModelValidator(
examples=example_gen.outputs['examples'],
model=trainer.outputs['model'])
```
"""
SPEC_CLASS = ModelValidatorSpec
EXECUTOR_SPEC = executor_spec.ExecutorClassSpec(executor.Executor)
DRIVER_CLASS = driver.Driver
def __init__(self,
examples: types.Channel,
model: types.Channel,
blessing: Optional[types.Channel] = None,
instance_name: Optional[Text] = None):
"""Construct a ModelValidator component.
Args:
examples: A Channel of 'ExamplesPath' type, usually produced by
[ExampleGen](https://www.tensorflow.org/tfx/guide/examplegen) component.
_required_
model: A Channel of 'ModelExportPath' type, usually produced by
[Trainer](https://www.tensorflow.org/tfx/guide/trainer) component.
_required_
blessing: Output channel of 'ModelBlessingPath' that contains the
validation result.
instance_name: Optional name assigned to this specific instance of
ModelValidator. Required only if multiple ModelValidator components are
declared in the same pipeline.
"""
blessing = blessing or types.Channel(
type=standard_artifacts.ModelBlessing,
artifacts=[standard_artifacts.ModelBlessing()])
spec = ModelValidatorSpec(examples=examples, model=model, blessing=blessing)
super(ModelValidator, self).__init__(spec=spec, instance_name=instance_name)
|
[
"tensorflow-extended-team@google.com"
] |
tensorflow-extended-team@google.com
|
02275546e99d17fd7465ff2cbf3e4eacf57003e3
|
a64757759a7170478ad3e9c71429c484491426be
|
/autoconv.py
|
85e7b1b45b29a9ad766ab17c57193b68b5453c93
|
[] |
no_license
|
fy0/autoconv
|
940928810bcda472bf401c14c2452ef64359fd9c
|
1073934a0d03eba5e5192ffb583629308ff74d13
|
refs/heads/master
| 2021-07-01T01:30:25.249292
| 2017-09-18T08:11:57
| 2017-09-18T08:11:57
| 103,892,929
| 1
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,704
|
py
|
"""
{
"global": {
"encoder": "opusenc.exe",
"input_dir": "input",
"output_dir": "output",
"watch_ext": [".wav"],
"output_ext": ".opus"
},
"types": {
"music": {
"--title": "track title"
}
}
}
"""
import os
import json
import time
import subprocess
from shlex import quote
from pathlib import Path # py3.4+
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
config = {}
def convert(type_name, filepath):
if len(filepath.parts) == 1:
type_name = ''
if filepath.suffix not in config['global']['watch_ext']:
return
if type_name in config['types']:
typeinfo = config['types'][type_name]
params = []
for k, v in typeinfo.items():
params.append('%s %s' % (k, v))
out_path = Path(config['global']['output_dir']).joinpath(filepath)
out_ext = config['global']['output_ext']
encoder = subprocess.list2cmdline([config['global']['encoder']])
cmd = [
str(Path(config['global']['input_dir']).joinpath(filepath)),
str(out_path)[:-len(out_path.suffix)] + out_ext # .absolute()
]
os.makedirs(os.path.dirname(out_path), exist_ok=True)
cmd_txt = encoder + ' ' + ' '.join(params) + subprocess.list2cmdline(cmd)
print('Running: %s' % cmd_txt)
os.system(cmd_txt)
return True
class FileEventHandler(FileSystemEventHandler):
def on_moved(self, event):
if event.is_directory:
print("directory moved from {0} to {1}".format(event.src_path,event.dest_path))
else:
path = Path(event.dest_path).relative_to(config['global']['input_dir'])
if convert(path.parts[0], path):
#print("file moved from {0} to {1}".format(event.src_path,event.dest_path))
print('[Encoded] %s' % event.src_path)
def on_modified(self, event):
if not event.is_directory:
path = Path(event.src_path).relative_to(config['global']['input_dir'])
if convert(path.parts[0], path):
#print("file modified: %s" % event.src_path)
print('[Encoded] %s' % event.src_path)
def main():
global config
config = json.loads(open('config.json', encoding='utf-8').read())
observer = Observer()
event_handler = FileEventHandler()
observer.schedule(event_handler, config['global']['input_dir'], True)
observer.start()
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
observer.stop()
observer.join()
if __name__ == '__main__':
main()
|
[
"fy0@qq.com"
] |
fy0@qq.com
|
73a032a0612a77d65c7a07200994e83c69f92ce3
|
6b2a8dd202fdce77c971c412717e305e1caaac51
|
/solutions_2751486_0/Python/TheTaintedOne/solution.py
|
746f30c4b1aac93a50dee4c7e781e4c5746595eb
|
[] |
no_license
|
alexandraback/datacollection
|
0bc67a9ace00abbc843f4912562f3a064992e0e9
|
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
|
refs/heads/master
| 2021-01-24T18:27:24.417992
| 2017-05-23T09:23:38
| 2017-05-23T09:23:38
| 84,313,442
| 2
| 4
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,092
|
py
|
import sys
lines = sys.stdin.readlines()
ntests = int(lines[0])
vowels = set(["a", "e", "i", "o", "u"])
linenum = 1;
for c in xrange(0, ntests):
name, csize = lines[linenum].split()
csize = int(csize)
# print "[" + name + "]"
# print start_size, num_others
cons = [];
for cc in name:
if cc in vowels:
cons.append(0)
else:
cons.append(1)
# print cons
runs = [];
curr_run = 0;
for pos in xrange(len(name)):
if cons[pos]==1:
curr_run = curr_run + 1
else:
curr_run = 0
if curr_run>= csize:
runs.append((pos, curr_run))
# print runs
res = 0
list_pos = 0
for pos in xrange(len(name)):
if list_pos < len(runs):
if pos>runs[list_pos][0]-csize+1:
list_pos = list_pos+1
if list_pos < len(runs):
res = res + (len(name)-runs[list_pos][0])
# print pos, runs[list_pos]
print "Case #" + str(c+1) + ": ", str(res)
linenum = linenum + 1
|
[
"eewestman@gmail.com"
] |
eewestman@gmail.com
|
be22c1e11ed28eafca08cf5bcfe0da6b20b66836
|
7c13de6b7831f99b8790452e03953e5ded0aca64
|
/classy_vision/generic/distributed_util.py
|
ec5211f4123496d80e7c9396eef6df0d0e8b1338
|
[
"MIT"
] |
permissive
|
vreis/ClassyVision-2
|
3f99d3c06ec422e81e29b0f38f02a7ce56e480d6
|
80aa4d421d1203b4b92bb9b848ccc866816e4f6d
|
refs/heads/master
| 2021-07-15T18:03:14.212417
| 2019-12-06T16:48:19
| 2019-12-06T16:50:46
| 226,377,934
| 0
| 0
|
MIT
| 2019-12-06T17:27:46
| 2019-12-06T17:27:45
| null |
UTF-8
|
Python
| false
| false
| 5,284
|
py
|
#!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates.
#
# This source code is licensed under the MIT license found in the
# LICENSE file in the root directory of this source tree.
import torch
# Default to GPU 0
_cuda_device_index: int = 0
# Setting _cuda_device_index to -1 internally implies that we should use CPU
_CPU_DEVICE_INDEX = -1
def convert_to_distributed_tensor(tensor):
"""
For some backends, such as NCCL, communication only works if the
tensor is on the GPU. This helper function converts to the correct
device and returns the tensor + original device.
"""
orig_device = "cpu" if not tensor.is_cuda else "gpu"
if (
torch.distributed.is_available()
and torch.distributed.get_backend() == torch.distributed.Backend.NCCL
and not tensor.is_cuda
):
tensor = tensor.cuda()
return (tensor, orig_device)
def convert_to_normal_tensor(tensor, orig_device):
"""
For some backends, such as NCCL, communication only works if the
tensor is on the GPU. This converts the tensor back to original device.
"""
if tensor.is_cuda and orig_device == "cpu":
tensor = tensor.cpu()
return tensor
def is_distributed_training_run():
return (
torch.distributed.is_available()
and torch.distributed.is_initialized()
and (torch.distributed.get_world_size() > 1)
)
def is_master():
"""
Returns True if this is rank 0 of a distributed training job OR if it is
a single trainer job. Otherwise False.
"""
return get_rank() == 0
def all_reduce_mean(tensor):
"""
Wrapper over torch.distributed.all_reduce for performing mean reduction
of tensor over all processes.
"""
if is_distributed_training_run():
tensor, orig_device = convert_to_distributed_tensor(tensor)
torch.distributed.all_reduce(tensor, torch.distributed.ReduceOp.SUM)
tensor = tensor / torch.distributed.get_world_size()
tensor = convert_to_normal_tensor(tensor, orig_device)
return tensor
def all_reduce_sum(tensor):
"""
Wrapper over torch.distributed.all_reduce for performing sum
reduction of tensor over all processes in both distributed /
non-distributed scenarios.
"""
if is_distributed_training_run():
tensor, orig_device = convert_to_distributed_tensor(tensor)
torch.distributed.all_reduce(tensor, torch.distributed.ReduceOp.SUM)
tensor = convert_to_normal_tensor(tensor, orig_device)
return tensor
def gather_tensors_from_all(tensor):
"""
Wrapper over torch.distributed.all_gather for performing
'gather' of 'tensor' over all processes in both distributed /
non-distributed scenarios.
"""
if tensor.ndim == 0:
# 0 dim tensors cannot be gathered. so unsqueeze
tensor = tensor.unsqueeze(0)
if is_distributed_training_run():
tensor, orig_device = convert_to_distributed_tensor(tensor)
gathered_tensors = [
torch.zeros_like(tensor) for _ in range(torch.distributed.get_world_size())
]
torch.distributed.all_gather(gathered_tensors, tensor)
gathered_tensors = [
convert_to_normal_tensor(_tensor, orig_device)
for _tensor in gathered_tensors
]
else:
gathered_tensors = [tensor]
return gathered_tensors
def gather_from_all(tensor):
gathered_tensors = gather_tensors_from_all(tensor)
gathered_tensor = torch.cat(gathered_tensors, 0)
return gathered_tensor
def barrier():
"""
Wrapper over torch.distributed.barrier, returns without waiting
if the distributed process group is not initialized instead of throwing error.
"""
if not torch.distributed.is_available() or not torch.distributed.is_initialized():
return
torch.distributed.barrier()
def get_world_size():
"""
Simple wrapper for correctly getting worldsize in both distributed
/ non-distributed settings
"""
return (
torch.distributed.get_world_size()
if torch.distributed.is_available() and torch.distributed.is_initialized()
else 1
)
def get_rank():
"""
Simple wrapper for correctly getting rank in both distributed
/ non-distributed settings
"""
return (
torch.distributed.get_rank()
if torch.distributed.is_available() and torch.distributed.is_initialized()
else 0
)
def set_cuda_device_index(idx: int):
global _cuda_device_index
_cuda_device_index = idx
torch.cuda.set_device(_cuda_device_index)
def set_cpu_device():
global _cuda_device_index
_cuda_device_index = _CPU_DEVICE_INDEX
def get_cuda_device_index() -> int:
return _cuda_device_index
def init_distributed_data_parallel_model(model):
global _cuda_device_index
if _cuda_device_index == _CPU_DEVICE_INDEX:
# CPU-only model, don't specify device
return torch.nn.parallel.DistributedDataParallel(model, broadcast_buffers=False)
else:
# GPU model
return torch.nn.parallel.DistributedDataParallel(
model,
device_ids=[_cuda_device_index],
output_device=_cuda_device_index,
broadcast_buffers=False,
)
|
[
"facebook-github-bot@users.noreply.github.com"
] |
facebook-github-bot@users.noreply.github.com
|
c8d58bad12f2d00dbaaa0a198b391fe827e89ccc
|
79a60fa1daeaa9dbe0cb551423fe28c2f2cf7da3
|
/websocket/bottle/mqttwsweb.py
|
a0e1c343be062aba3efa12502005552a8a3d9e11
|
[
"MIT"
] |
permissive
|
swkim01/mqtt
|
a505494815cd5f487cbc1e434fd0546c1bc08eac
|
030d9106bf791b54538aac8789df872abaa96e17
|
refs/heads/master
| 2021-01-10T22:07:04.788958
| 2019-07-19T01:41:07
| 2019-07-19T01:41:07
| 42,844,241
| 5
| 2
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 499
|
py
|
#-*- coding: utf-8 -*-
from bottle import route, get, request, template, response, static_file
from bottle import run
#import json
host="<HOST IP>"
port=8008
wsport=9001
@route('/mqttws31.js')
def mqttws31():
return static_file("mqttws31.js", root=".")
@get('/mqttwschart')
def dht22chart():
return template("mqttwschart", host=host, port=wsport)
@get('/')
def index():
return template("mqttwsindex", host=host, port=wsport)
if __name__ == '__main__':
run(host=host, port=port)
|
[
"swkim01@gmail.com"
] |
swkim01@gmail.com
|
5961d295b23abd4a5c1995b3f10bf6ccb333c741
|
44600adf1731a449ff2dd5c84ce92c7f8b567fa4
|
/colour_down/adaptation/fairchild1990.py
|
4ce1a10481213f117c2508f1c43f594b728df699
|
[] |
no_license
|
ajun73/Work_Code
|
b6a3581c5be4ccde93bd4632d8aaaa9ecc782b43
|
017d12361f7f9419d4b45b23ed81f9856278e849
|
refs/heads/master
| 2020-04-11T23:16:43.994397
| 2019-12-28T07:48:44
| 2019-12-28T07:48:44
| 162,161,852
| 0
| 1
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 7,432
|
py
|
# -*- coding: utf-8 -*-
"""
Fairchild (1990) Chromatic Adaptation Model
===========================================
Defines *Fairchild (1990)* chromatic adaptation model objects:
- :func:`colour.adaptation.chromatic_adaptation_Fairchild1990`
See Also
--------
`Fairchild (1990) Chromatic Adaptation Model Jupyter Notebook
<http://nbviewer.jupyter.org/github/colour-science/colour-notebooks/\
blob/master/notebooks/adaptation/fairchild1990.ipynb>`_
References
----------
- :cite:`Fairchild1991a` : Fairchild, M. D. (1991). Formulation and testing
of an incomplete-chromatic-adaptation model. Color Research & Application,
16(4), 243-250. doi:10.1002/col.5080160406
- :cite:`Fairchild2013s` : Fairchild, M. D. (2013). FAIRCHILD'S 1990 MODEL.
In Color Appearance Models (3rd ed., pp. 4418-4495). Wiley. ISBN:B00DAYO8E2
"""
from __future__ import division, unicode_literals
import numpy as np
from colour.adaptation import VON_KRIES_CAT
from colour.utilities import dot_vector, row_as_diagonal, tsplit, tstack
__author__ = 'Colour Developers'
__copyright__ = 'Copyright (C) 2013-2018 - Colour Developers'
__license__ = 'New BSD License - http://opensource.org/licenses/BSD-3-Clause'
__maintainer__ = 'Colour Developers'
__email__ = 'colour-science@googlegroups.com'
__status__ = 'Production'
__all__ = [
'FAIRCHILD1990_XYZ_TO_RGB_MATRIX', 'FAIRCHILD1990_RGB_TO_XYZ_MATRIX',
'chromatic_adaptation_Fairchild1990', 'XYZ_to_RGB_Fairchild1990',
'RGB_to_XYZ_Fairchild1990', 'degrees_of_adaptation'
]
FAIRCHILD1990_XYZ_TO_RGB_MATRIX = VON_KRIES_CAT
"""
*Fairchild (1990)* colour appearance model *CIE XYZ* tristimulus values to cone
responses matrix.
FAIRCHILD1990_XYZ_TO_RGB_MATRIX : array_like, (3, 3)
"""
FAIRCHILD1990_RGB_TO_XYZ_MATRIX = np.linalg.inv(VON_KRIES_CAT)
"""
*Fairchild (1990)* colour appearance model cone responses to *CIE XYZ*
tristimulus values matrix.
FAIRCHILD1990_RGB_TO_XYZ_MATRIX : array_like, (3, 3)
"""
def chromatic_adaptation_Fairchild1990(XYZ_1,
XYZ_n,
XYZ_r,
Y_n,
discount_illuminant=False):
"""
Adapts given stimulus *CIE XYZ_1* tristimulus values from test viewing
conditions to reference viewing conditions using *Fairchild (1990)*
chromatic adaptation model.
Parameters
----------
XYZ_1 : array_like
*CIE XYZ_1* tristimulus values of test sample / stimulus in domain
[0, 100].
XYZ_n : array_like
Test viewing condition *CIE XYZ_n* tristimulus values of whitepoint.
XYZ_r : array_like
Reference viewing condition *CIE XYZ_r* tristimulus values of
whitepoint.
Y_n : numeric or array_like
Luminance :math:`Y_n` of test adapting stimulus in :math:`cd/m^2`.
discount_illuminant : bool, optional
Truth value indicating if the illuminant should be discounted.
Returns
-------
ndarray
Adapted *CIE XYZ_2* tristimulus values of stimulus.
Warning
-------
The input domain and output range of that definition are non standard!
Notes
-----
- Input *CIE XYZ_1*, *CIE XYZ_n* and *CIE XYZ_r* tristimulus values are
in domain [0, 100].
- Output *CIE XYZ_2* tristimulus values are in range [0, 100].
References
----------
- :cite:`Fairchild1991a`
- :cite:`Fairchild2013s`
Examples
--------
>>> XYZ_1 = np.array([19.53, 23.07, 24.97])
>>> XYZ_n = np.array([111.15, 100.00, 35.20])
>>> XYZ_r = np.array([94.81, 100.00, 107.30])
>>> Y_n = 200
>>> chromatic_adaptation_Fairchild1990(XYZ_1, XYZ_n, XYZ_r, Y_n)
... # doctest: +ELLIPSIS
array([ 23.3252634..., 23.3245581..., 76.1159375...])
"""
XYZ_1 = np.asarray(XYZ_1)
XYZ_n = np.asarray(XYZ_n)
XYZ_r = np.asarray(XYZ_r)
Y_n = np.asarray(Y_n)
LMS_1 = dot_vector(FAIRCHILD1990_XYZ_TO_RGB_MATRIX, XYZ_1)
LMS_n = dot_vector(FAIRCHILD1990_XYZ_TO_RGB_MATRIX, XYZ_n)
LMS_r = dot_vector(FAIRCHILD1990_XYZ_TO_RGB_MATRIX, XYZ_r)
p_LMS = degrees_of_adaptation(
LMS_1, Y_n, discount_illuminant=discount_illuminant)
a_LMS_1 = p_LMS / LMS_n
a_LMS_2 = p_LMS / LMS_r
A_1 = row_as_diagonal(a_LMS_1)
A_2 = row_as_diagonal(a_LMS_2)
LMSp_1 = dot_vector(A_1, LMS_1)
c = 0.219 - 0.0784 * np.log10(Y_n)
C = row_as_diagonal(tstack((c, c, c)))
LMS_a = dot_vector(C, LMSp_1)
LMSp_2 = dot_vector(np.linalg.inv(C), LMS_a)
LMS_c = dot_vector(np.linalg.inv(A_2), LMSp_2)
XYZ_c = dot_vector(FAIRCHILD1990_RGB_TO_XYZ_MATRIX, LMS_c)
return XYZ_c
def XYZ_to_RGB_Fairchild1990(XYZ):
"""
Converts from *CIE XYZ* tristimulus values to cone responses.
Parameters
----------
XYZ : array_like
*CIE XYZ* tristimulus values.
Returns
-------
ndarray
Cone responses.
Examples
--------
>>> XYZ = np.array([19.53, 23.07, 24.97])
>>> XYZ_to_RGB_Fairchild1990(XYZ) # doctest: +ELLIPSIS
array([ 22.1231935..., 23.6054224..., 22.9279534...])
"""
return dot_vector(FAIRCHILD1990_XYZ_TO_RGB_MATRIX, XYZ)
def RGB_to_XYZ_Fairchild1990(RGB):
"""
Converts from cone responses to *CIE XYZ* tristimulus values.
Parameters
----------
RGB : array_like
Cone responses.
Returns
-------
ndarray
*CIE XYZ* tristimulus values.
Examples
--------
>>> RGB = np.array([22.12319350, 23.60542240, 22.92795340])
>>> RGB_to_XYZ_Fairchild1990(RGB) # doctest: +ELLIPSIS
array([ 19.53, 23.07, 24.97])
"""
return dot_vector(FAIRCHILD1990_RGB_TO_XYZ_MATRIX, RGB)
def degrees_of_adaptation(LMS, Y_n, v=1 / 3, discount_illuminant=False):
"""
Computes the degrees of adaptation :math:`p_L`, :math:`p_M` and
:math:`p_S`.
Parameters
----------
LMS : array_like
Cone responses.
Y_n : numeric or array_like
Luminance :math:`Y_n` of test adapting stimulus in :math:`cd/m^2`.
v : numeric or array_like, optional
Exponent :math:`v`.
discount_illuminant : bool, optional
Truth value indicating if the illuminant should be discounted.
Returns
-------
ndarray
Degrees of adaptation :math:`p_L`, :math:`p_M` and :math:`p_S`.
Examples
--------
>>> LMS = np.array([20.00052060, 19.99978300, 19.99883160])
>>> Y_n = 31.83
>>> degrees_of_adaptation(LMS, Y_n) # doctest: +ELLIPSIS
array([ 0.9799324..., 0.9960035..., 1.0233041...])
>>> degrees_of_adaptation(LMS, Y_n, 1 / 3, True)
array([ 1., 1., 1.])
"""
LMS = np.asarray(LMS)
if discount_illuminant:
return np.ones(LMS.shape)
Y_n = np.asarray(Y_n)
v = np.asarray(v)
L, M, S = tsplit(LMS)
LMS_E = dot_vector(VON_KRIES_CAT, np.ones(LMS.shape)) # E illuminant.
L_E, M_E, S_E = tsplit(LMS_E)
Ye_n = Y_n ** v
def m_E(x, y):
"""
Computes the :math:`m_E` term.
"""
return (3 * (x / y)) / (L / L_E + M / M_E + S / S_E)
def P_c(x):
"""
Computes the :math:`P_L`, :math:`P_M` or :math:`P_S` terms.
"""
return (1 + Ye_n + x) / (1 + Ye_n + 1 / x)
p_L = P_c(m_E(L, L_E))
p_M = P_c(m_E(M, M_E))
p_S = P_c(m_E(S, S_E))
p_LMS = tstack((p_L, p_M, p_S))
return p_LMS
|
[
"ajun73@gmail.com"
] |
ajun73@gmail.com
|
68e3dbcc684161b2f8d32f752aaad8f778937993
|
9f6b9a40444df2b09960b5b531232ee6975e74dd
|
/level_1.py
|
13d4ca664e2d9291979dc351d30188b94817ea48
|
[] |
no_license
|
nildiert/hodor
|
f60e94f4a64b8b0217c760104f501a6a586d4129
|
3c8b2df854ed2af6c5345250bc8f557b52761aee
|
refs/heads/master
| 2020-06-02T06:19:44.740188
| 2019-06-10T02:59:23
| 2019-06-10T02:59:23
| 191,067,129
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 751
|
py
|
from lxml import html
import requests
import time
def req_values(url):
page = requests.get(url)
tree = html.fromstring(page.content)
me = tree.xpath(next_val)
return ([page, tree, me])
try:
url = 'http://158.69.76.135/level1.php'
data = {'id':'730','holdthedoor':'submit'}
next_val = '//td[contains(text(), "730")]/following-sibling::node()/text()'
page, tree, me = req_values(url)
data.update({"key":page.cookies["HoldTheDoor"]})
while ("".join(me) != '\n4095 '):
page, tree, me = req_values(url)
data.update({"key":page.cookies["HoldTheDoor"]})
status = requests.post(url, data, cookies=page.cookies)
print("{} {}".format(status ,me))
except Exception as e:
print(e)
|
[
"niljordan23@gmail.com"
] |
niljordan23@gmail.com
|
2da7f4194e18775060afca1bfc1dcd85d1009570
|
3411ad233c411c06765f4b07f8670c12025178b6
|
/201-300/231-240/237-deleteNodeInLinkedList/deleteNodeInLinkedList.py
|
9b19cef457feb64cb67a51b92b91f733e6ae73ed
|
[
"MIT"
] |
permissive
|
xuychen/Leetcode
|
7d9d31fed898ce58440f5ae6665d2ccaf1a4b256
|
c8bf33af30569177c5276ffcd72a8d93ba4c402a
|
refs/heads/master
| 2021-11-19T20:39:43.741589
| 2021-10-24T16:26:52
| 2021-10-24T16:26:52
| 140,212,398
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 395
|
py
|
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def deleteNode(self, node):
"""
:type node: ListNode
:rtype: void Do not return anything, modify node in-place instead.
"""
node.val = node.next.val
node.next = node.next.next
|
[
"xuychen@ucdavis.edu"
] |
xuychen@ucdavis.edu
|
b0c14efa30aa6296d714f88a56de72b29a3cb346
|
821d830910c354cb89767a77e00c77deb592ca0c
|
/bayesnet/math/__init__.py
|
a7e1743bd4c1a5cdfed8a8de29633ed4e5c1f037
|
[
"MIT"
] |
permissive
|
zxsted/BayesianNetwork
|
c61aa77a511e96852dec38f268f0dc31b6752cac
|
efe75b5416a262741fa60ad09380684886e91eff
|
refs/heads/master
| 2021-05-09T05:38:43.513255
| 2017-10-25T06:58:26
| 2017-10-25T06:58:26
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 1,193
|
py
|
from bayesnet.math.add import add
from bayesnet.math.divide import divide, rdivide
from bayesnet.math.exp import exp
from bayesnet.math.log import log
from bayesnet.math.matmul import matmul, rmatmul
from bayesnet.math.mean import mean
from bayesnet.math.multiply import multiply
from bayesnet.math.negative import negative
from bayesnet.math.power import power, rpower
from bayesnet.math.product import prod
from bayesnet.math.sqrt import sqrt
from bayesnet.math.square import square
from bayesnet.math.subtract import subtract, rsubtract
from bayesnet.math.sum import sum
from bayesnet.tensor.tensor import Tensor
Tensor.__add__ = add
Tensor.__radd__ = add
Tensor.__truediv__ = divide
Tensor.__rtruediv__ = rdivide
Tensor.mean = mean
Tensor.__matmul__ = matmul
Tensor.__rmatmul__ = rmatmul
Tensor.__mul__ = multiply
Tensor.__rmul__ = multiply
Tensor.__neg__ = negative
Tensor.__pow__ = power
Tensor.__rpow__ = rpower
Tensor.prod = prod
Tensor.__sub__ = subtract
Tensor.__rsub__ = rsubtract
Tensor.sum = sum
__all__ = [
"add",
"divide",
"exp",
"log",
"matmul",
"mean",
"multiply",
"power",
"prod",
"sqrt",
"square",
"subtract",
"sum"
]
|
[
"r0735nj5058@icloud.com"
] |
r0735nj5058@icloud.com
|
3317db01ff8d0d5eff65cd314197024a8f717d5c
|
cc196a0111bbdcc04af7e579bc87e808cc0c7b02
|
/trident/__init__.py
|
880dacc18d173da5184a33655707722ed4ae11ab
|
[
"MIT"
] |
permissive
|
Jackliaoall-AI-Framework/trident
|
73819a95121d9d4dbf81d28ae32aea43c0541840
|
cd26c1108c05c3ab4c262f9b416a126b2ad2f858
|
refs/heads/master
| 2023-01-15T15:15:10.544946
| 2020-11-23T04:15:33
| 2020-11-23T04:15:33
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 466
|
py
|
"""trident api"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import sys
from importlib import reload
from sys import stderr
defaultencoding = 'utf-8'
if sys.getdefaultencoding() != defaultencoding:
reload(sys)
sys.setdefaultencoding(defaultencoding)
__version__ = '0.6.1'
stderr.write('trident {0}\n'.format(__version__))
from trident.backend import *
import threading
import random
|
[
"allan@asiaminer.com.tw"
] |
allan@asiaminer.com.tw
|
49387a3cdc6c6e23837c5436d99d317dbd2554eb
|
40b262d813d07a113914d6009af8737898f2e096
|
/Platos test/apps/schedules/migrations/0001_initial.py
|
8cf8f0fa053f62e70fdc4f248d417b5c4d27999c
|
[] |
no_license
|
Nish8192/Python
|
cb6de3b96e790464a0a4ad10eda86ce4f79688b4
|
5c03beff6f3669d5cfb6b31c5749827db8b6a627
|
refs/heads/master
| 2020-12-23T16:56:18.301723
| 2017-05-27T02:09:02
| 2017-05-27T02:09:02
| 92,563,061
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 3,560
|
py
|
# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-02-28 22:44
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('login_register', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Day',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('h9to10', models.BooleanField(verbose_name=False)),
('h10to11', models.BooleanField(verbose_name=False)),
('h11to12', models.BooleanField(verbose_name=False)),
('h12to13', models.BooleanField(verbose_name=False)),
('h13to14', models.BooleanField(verbose_name=False)),
('h14to15', models.BooleanField(verbose_name=False)),
('h15to16', models.BooleanField(verbose_name=False)),
('h16to17', models.BooleanField(verbose_name=False)),
('h17to18', models.BooleanField(verbose_name=False)),
('h18to19', models.BooleanField(verbose_name=False)),
('h19to20', models.BooleanField(verbose_name=False)),
('h20to21', models.BooleanField(verbose_name=False)),
('h21to22', models.BooleanField(verbose_name=False)),
('h22to23', models.BooleanField(verbose_name=False)),
('h23to0', models.BooleanField(verbose_name=False)),
('h0to1', models.BooleanField(verbose_name=False)),
('h1to2', models.BooleanField(verbose_name=False)),
('h2to3', models.BooleanField(verbose_name=False)),
('h3to4', models.BooleanField(verbose_name=False)),
('h4to5', models.BooleanField(verbose_name=False)),
('h5to6', models.BooleanField(verbose_name=False)),
('h6to7', models.BooleanField(verbose_name=False)),
('h7to8', models.BooleanField(verbose_name=False)),
('h8to9', models.BooleanField(verbose_name=False)),
],
),
migrations.CreateModel(
name='Schedule',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('fri', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='fri_schedule', to='schedules.Day')),
('mon', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='mon_schedule', to='schedules.Day')),
('sat', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='sat_schedule', to='schedules.Day')),
('sun', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='sun_schedule', to='schedules.Day')),
('thu', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='thu_schedule', to='schedules.Day')),
('tue', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='tue_schedule', to='schedules.Day')),
('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='schedule_user', to='login_register.User')),
('wed', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='wed_schedule', to='schedules.Day')),
],
),
]
|
[
"nish8192@gmail.com"
] |
nish8192@gmail.com
|
ee615403c191a3bc00a63b9ac501349fe54af94f
|
dec29f40788478f73798f23b79ca892b3121150a
|
/apps/core/forms.py
|
2dea5904ea3b9ecfd5b3ba08032c83908459e911
|
[] |
no_license
|
RonaldTheodoro/django-ecommerce
|
2c661e6f3ae0154ecb7a8e25183875da8c27d14f
|
9097049107e5a7ab52474aa89fe40f02689fb24a
|
refs/heads/master
| 2021-05-06T02:08:51.166682
| 2017-12-17T00:32:03
| 2017-12-17T00:32:03
| 114,499,259
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 520
|
py
|
from django import forms
class ContactForm(forms.Form):
fullname = forms.CharField(
widget=forms.TextInput(
attrs={'class': 'form-control', 'placeholder': 'Your full name'}
)
)
email = forms.EmailField(
widget=forms.EmailInput(
attrs={'class': 'form-control', 'placeholder': 'Your email'}
)
)
content = forms.CharField(
widget=forms.Textarea(
attrs={'class': 'form-control', 'placeholder': 'Your message'}
)
)
|
[
"ronald.silva4@fatec.sp.gov.br"
] |
ronald.silva4@fatec.sp.gov.br
|
d3977fe8da468335955c73585ad4373f968ec62b
|
52e8841ac9603e994fc487ecb52f232e55a50e07
|
/Bio/HMM/Utilities.py
|
17db3f4ed0ad626cb1de97b7c921f6692d2f4f6b
|
[] |
no_license
|
rored/RozszerzenieBio.PDB
|
aff434fddfe57199a7465f79126eba62b1c789ae
|
7c9d696faacabff912b1263fe19291d6a198c3c2
|
refs/heads/master
| 2021-01-21T04:50:37.903227
| 2016-06-23T19:15:42
| 2016-06-23T19:15:42
| 55,064,794
| 0
| 3
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 2,209
|
py
|
# This code is part of the Biopython distribution and governed by its
# license. Please see the LICENSE file that should have been included
# as part of this package.
#
"""Generic functions which are useful for working with HMMs.
This just collects general functions which you might like to use in
dealing with HMMs.
"""
from __future__ import print_function
__docformat__ = "restructuredtext en"
def pretty_print_prediction(emissions, real_state, predicted_state,
emission_title="Emissions",
real_title="Real State",
predicted_title="Predicted State",
line_width=75):
"""Print out a state sequence prediction in a nice manner.
Arguments:
o emissions -- The sequence of emissions of the sequence you are
dealing with.
o real_state -- The actual state path that generated the emissions.
o predicted_state -- A state path predicted by some kind of HMM model.
"""
# calculate the length of the titles and sequences
title_length = max(len(emission_title), len(real_title),
len(predicted_title)) + 1
seq_length = line_width - title_length
# set up the titles so they'll print right
emission_title = emission_title.ljust(title_length)
real_title = real_title.ljust(title_length)
predicted_title = predicted_title.ljust(title_length)
cur_position = 0
# while we still have more than seq_length characters to print
while True:
if (cur_position + seq_length) < len(emissions):
extension = seq_length
else:
extension = len(emissions) - cur_position
print("%s%s" % (emission_title,
emissions[cur_position:cur_position + seq_length]))
print("%s%s" % (real_title,
real_state[cur_position:cur_position + seq_length]))
print("%s%s\n" % (predicted_title,
predicted_state[cur_position:
cur_position + seq_length]))
if (len(emissions) < (cur_position + seq_length)):
break
cur_position += seq_length
|
[
"Viktoria@MacBook-Pro-Viktoria.local"
] |
Viktoria@MacBook-Pro-Viktoria.local
|
7633f6f9cb7e06d32f07fd0f6c3f93f846667e26
|
c128d73f1d988686e3e7377520d7475ae59d8016
|
/test/cmd2.py
|
674d0464539f09de007c6d8e163e51833f2b15f4
|
[] |
no_license
|
astroumd/SSINGMA
|
a9aba4aea0d0bf799643ebd7064b222b5c801894
|
044923b6e036d3679e88839593244b834e8e2d09
|
refs/heads/master
| 2021-07-01T12:48:08.520640
| 2019-03-22T01:50:29
| 2019-03-22T01:50:29
| 107,312,765
| 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 368
|
py
|
#
# example command line parser usage - functional approach with keyword database
#
# casa -c cmd2.py a=100 'c=[100,200]'
script_keywords = {
'a' : 1,
'b' : 2.0,
'c' : [1,2,3],
}
import sys
ng_initkeys(script_keywords,sys.argv)
a = ng_getkey('a')
b = ng_getkey('b')
c = ng_getkey('c')
print 'a=',a
print 'b=',b
print 'c=',c
|
[
"teuben@gmail.com"
] |
teuben@gmail.com
|
023cbe9820c1c4c54c9a10bd34d54c0cd287a76a
|
30e58b930c31526a1e226a928bc77e23f232080e
|
/icesim/dataCheck.py
|
7152527a7b7c93513f0deaa3399d7c90caf5dd22
|
[] |
no_license
|
bbw7561135/anisotropy
|
c8688f9d705234c6a90f607acb3e8cc28ea5be28
|
a21f85788c16d8aa14fc5934f476def4c8954f34
|
refs/heads/master
| 2021-06-01T05:35:48.727845
| 2016-05-13T00:27:37
| 2016-05-13T00:27:37
| null | 0
| 0
| null | null | null | null |
UTF-8
|
Python
| false
| false
| 770
|
py
|
#!/usr/bin/env python
from icecube import icetray, dataio
from I3Tray import *
import sys, time, glob, os
import numpy as np
def fileCheck(fileName):
t0 = time.time()
tray = I3Tray()
tray.AddModule('I3Reader', FileName=fileName)
tray.Execute()
tray.Finish()
print "Time taken: ", time.time() - t0
def checker(config, out, fileList):
badList = []
for file in fileList:
try: fileCheck(file)
except RuntimeError:
print 'Bad run found:', os.path.basename(file)
badList += [file+'\n']
with open(out, 'w') as f:
f.writelines(badList)
if __name__ == "__main__":
config = sys.argv[1]
out = sys.argv[2]
fileList = sys.argv[3:]
checker(config, out, fileList)
|
[
"jrbourbeau@gmail.com"
] |
jrbourbeau@gmail.com
|
34f96a0617099afd0d7f6f2da75c52d59c91696c
|
3474b315da3cc5cb3f7823f19a18b63a8da6a526
|
/scratch/KRAMS/src/ibvpy/core/i_bcond.py
|
724c3af30b2cc5336fb60d2c0bd2d4c98c37a380
|
[] |
no_license
|
h4ck3rm1k3/scratch
|
8df97462f696bc2be00f1e58232e1cd915f0fafd
|
0a114a41b0d1e9b2d68dbe7af7cf34db11512539
|
refs/heads/master
| 2021-01-21T15:31:38.718039
| 2013-09-19T10:48:24
| 2013-09-19T10:48:24
| 29,173,525
| 0
| 0
| null | 2015-01-13T04:58:57
| 2015-01-13T04:58:56
| null |
UTF-8
|
Python
| false
| false
| 1,522
|
py
|
from enthought.traits.api import Array, Bool, Enum, Float, HasTraits, \
Instance, Int, Trait, Str, Enum, \
Callable, List, TraitDict, Any, Range, \
Delegate, Event, on_trait_change, Button, \
Interface, implements, Property, cached_property
class IBCond( Interface ):
'''
Interface of the boundary condition.
'''
def is_essential( self ):
'''
Distinguish the essential and natural boundary conditions.
This is needed to reorganize the system matrices and vectors
to reflect the prescribed primary variables (displacements).
'''
def is_natural( self ):
'''
Distinguish the essential and natural boundary conditions.
This is needed to reorganize the system matrices and vectors
to reflect the prescribed primary variables (displacements).
'''
# def get_dofs( self ):
# '''
# Return the list of affected DOFs.
#
# This is needed to reorganize the system matrices and vectors
# to reflect the prescribed primary variables (displacements).
# '''
def setup( self, sctx ):
'''
Locate the spatial context.
'''
def apply_essential( self, K ):
'''
Locate the spatial context.
'''
def apply( self, step_flag, sctx, K, R, t_n, t_n1 ):
'''
Locate the spatial context.
'''
|
[
"Axel@Axel-Pc"
] |
Axel@Axel-Pc
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.