blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 616 | 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 777 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 149 values | src_encoding stringclasses 26 values | language stringclasses 1 value | is_vendor bool 2 classes | is_generated bool 2 classes | length_bytes int64 3 10.2M | extension stringclasses 188 values | content stringlengths 3 10.2M | authors listlengths 1 1 | author_id stringlengths 1 132 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1dc58d55719d5e8c779ab8d96e4b0646be1a8a93 | 6b2a8dd202fdce77c971c412717e305e1caaac51 | /solutions_5634697451274240_1/Python/Mathuyama/pancake.py | 4fee8c53da1db866b82b5bceb88e8abef431eec2 | [] | 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,396 | py | import numpy as np
def getInfo(line):
t = []
for c in line:
if c == '-': t.append(-1);
if c == '+' : t.append(+1);
return t
def parse(path):
file = open(path,"r");
nbCases = int(file.readline());
txt = file.readlines();
cases = []
for line in txt:
cases.append(getInfo(line));
file.close()
return cases
def workpancake(t):
n = len(t);
plusIterator = n;
counter = 0;
while (plusIterator > 0):
while (plusIterator>0 and t[plusIterator-1] == +1):
plusIterator -= 1;
if (plusIterator > 0):
if (t[0] == (-1)):
t = flip(t,plusIterator);
else:
flipIndex = plusIterator-1;
while not(t[flipIndex] == 1):
flipIndex -= 1;
t = flip(t,flipIndex+1);
counter += 1;
return counter;
def flip(t,i):
if (i%2 == 1):
r = i-1;
t[i/2] = -t[i/2]
else:
r = i;
for k in range(r/2):
tmp = t[k];
t[k] = -t[i-k-1];
t[i-k-1] = -tmp;
return t;
def outputpancake(tablal,path):
file = open(path,'w');
for i in range(len(tablal)):
R = workpancake(tablal[i]);
file.write("Case #"+str(i+1)+": "+str(R)+"\n");
file.close();
tablal = parse("B-large.in");
outputpancake(tablal,"outputpancake.out");
| [
"alexandra1.back@gmail.com"
] | alexandra1.back@gmail.com |
bc6e0d7cce5ab4a2ff4d4c76a1ff404a38342888 | 30a866abd8b0aba8355ce0bc858cc679565032c2 | /wrk/python/global_variables.py | 13037f1c1b163b84ac9b8a6b917f5ae40a8aa723 | [] | no_license | srbcheema1/CheemaFy_legacy | d8a354e0f3463cb19ffbcf948d7be55c15c51faa | c929211729860887a82e0663bfcf5b85da6b6967 | refs/heads/master | 2021-10-15T23:48:57.259057 | 2019-01-31T11:33:46 | 2019-02-07T01:32:07 | 102,012,212 | 1 | 1 | null | null | null | null | UTF-8 | Python | false | false | 613 | py | hell = 1
debug = True
def read_only():
# here we are not writing it so no need of global keyword
read_debug = debug # works fine
if(debug): print("debug") # works fine
def strange():
bad_debug = debug # error
debug = True # maybe it thinks it is local
# it is to be declared global if we try to write it. else it is regarded as local
if(debug): print("debug")
def global_change():
global num
num = 3
def local_change():
num = 5
global_change() # works as expected
print(num)
local_change() # works as expected
print(num)
read_only()
strange() # explain why it dows so
| [
"srbcheema1@gmail.com"
] | srbcheema1@gmail.com |
0c3b71d557eed98f99e54ee483dfe08d43e50239 | a411a55762de11dc2c9d913ff33d2f1477ac02cf | /dp/cloud/python/magma/db_service/migrations/versions/016_remove_grant_attempts.py | 419ad005c1380af097689952c5a3b1ca7f4c6603 | [
"BSD-3-Clause"
] | permissive | magma/magma | 0dc48c1513d9968bd05fb7589f302c192b7c0f94 | 0e1d895dfe625681229e181fbc2dbad83e13c5cb | refs/heads/master | 2023-09-04T09:31:56.140395 | 2023-08-29T13:54:49 | 2023-08-29T13:54:49 | 170,803,235 | 1,219 | 525 | NOASSERTION | 2023-09-07T17:45:42 | 2019-02-15T04:46:24 | C++ | UTF-8 | Python | false | false | 782 | py | """empty message
Revision ID: 58a1b16ef73c
Revises: 530b18568ad9
Create Date: 2022-07-22 16:03:01.235285
"""
import sqlalchemy as sa
from alembic import op
# revision identifiers, used by Alembic.
revision = '58a1b16ef73c'
down_revision = '530b18568ad9'
branch_labels = None
depends_on = None
def upgrade():
"""
Run upgrade
"""
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('cbsds', 'grant_attempts')
# ### end Alembic commands ###
def downgrade():
"""
Run downgrade
"""
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('cbsds', sa.Column('grant_attempts', sa.INTEGER(), server_default=sa.text('0'), autoincrement=False, nullable=False))
# ### end Alembic commands ###
| [
"noreply@github.com"
] | magma.noreply@github.com |
50f2c40987fbaf3def06e4660a7e876306c21f60 | 8db5b1d27f27d6440e6bfaebf661678f8ce016e3 | /dictionaries/demo_dict_len.py | b4d41ec65fb439867c57a145a7569aeb163932af | [] | no_license | rasul-sharifzade/LearnPython | 9f9f860550667117354354f4f7fee082da16dc7e | ac68c208d50a1e11cfd0ab52ae00d6baea596ce9 | refs/heads/master | 2020-12-27T06:42:38.603190 | 2020-06-28T09:01:19 | 2020-06-28T09:01:19 | 237,800,042 | 3 | 0 | null | null | null | null | UTF-8 | Python | false | false | 94 | py | thisdict = {
"brand":"ford",
"model":"mustang",
"year":1964
}
print(len(thisdict)) | [
"rasul.sharifzade@gmail.com"
] | rasul.sharifzade@gmail.com |
dfde0dc15bc68d98164c3eed4e245d1a312dd74d | efc3bf4f88a2bfc885de5495c87433d345b54429 | /ZOJ/1115.py | 92f3352989a7d4a7c5a3053e24b7a7b9b4ac4e23 | [] | no_license | calvinxiao/Algorithm-Solution | 26ff42cc26aaca87a4706b82a325a92829878552 | afe254a4efa779598be8a82c5c5bcfcc94f80272 | refs/heads/master | 2016-09-05T21:08:35.852486 | 2015-08-23T15:13:23 | 2015-08-23T15:13:23 | 20,149,077 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 361 | py | #Problem ID: 1115
#Submit Time: 2012-08-16 00:49:47
#Run Time: 10
#Run Memory: 320
#ZOJ User: calvinxiao
import sys
def todo(n):
if n < 10:
return n
ans = 0
while n != 0:
ans += n % 10
n /= 10
return todo(ans)
while 1:
n = int(sys.stdin.readline())
if not n:
break
print todo(n) | [
"calvin.xiao@scaurugby.com"
] | calvin.xiao@scaurugby.com |
443b6a78e2121b70b47d9cb55a84223089801ef3 | 7d44994155d57a01fdd1b405018e2a83eb670bfe | /hub/src/light/effect/color_effects/triple_linear_color_transition.py | 24d6c76ab3ef0e923e7a64bf7b690f641dc416b9 | [] | no_license | jonlabroad/drum-lite | e05e2904c28f19101dfb0c43ecdf0b1b1f836e13 | e60e21a2f5d1f03e3e939163c101c286a3cfa7d2 | refs/heads/master | 2022-12-31T11:00:44.075176 | 2020-07-25T17:19:01 | 2020-07-25T17:19:01 | 214,287,587 | 0 | 0 | null | 2022-12-10T09:56:49 | 2019-10-10T21:18:57 | TypeScript | UTF-8 | Python | false | false | 937 | py | from light.effect.partial_effect import PartialEffect
from light.effect.resolved_effect import ResolvedEffect
from util.color_transition import ColorTransition
from light.effect.effect_priority import EffectPriority
class TripleLinearColorTransition(PartialEffect):
def __init__(self, srcRgb, dstRgb1, dstRgb2, duration):
super().__init__(0)
self.src = srcRgb
self.dst1 = dstRgb1
self.dst2 = dstRgb2
self.duration = duration
def getEffect(self, t):
dt = t - self.startTime
tNorm = dt / self.duration
dst = self.dst1 if dt <= 0.5 else self.dst2
src = self.src if dt <= 0.5 else self.dst1
tNormAdjusted = (tNorm * 2) if dt <= 0.5 else ((tNorm - 0.5) * 2)
return ResolvedEffect.createRgbw(ColorTransition.linear(tNormAdjusted, src, dst))
def isTemporal(self):
return False
def isComplete(self, t):
return False | [
"="
] | = |
fa587f4efbb32030d5aeb6a0a371f9f0cddf5bad | d9296d3b420d8f5c1aeca094d00dd6bc38a3d57d | /blog/migrations/0007_auto_20201007_0027.py | af9d531851ee81b2ee2d718dbd0c0b433ae67098 | [] | no_license | Anthony88888/mysite | 57f5f40530886b12cf1364c10c6206983b022c6c | 7130715ef3acac054b96fa22dcf19fec1f31e019 | refs/heads/master | 2023-01-09T12:15:11.720225 | 2020-10-25T14:48:35 | 2020-10-25T14:48:35 | 305,168,092 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 396 | py | # Generated by Django 2.0.13 on 2020-10-06 16:27
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('blog', '0006_auto_20201006_1456'),
]
operations = [
migrations.RemoveField(
model_name='readnum',
name='blog',
),
migrations.DeleteModel(
name='ReadNum',
),
]
| [
"admin@example.com"
] | admin@example.com |
fc47543b429550c01bcea133e396d425c978ea1f | 335c8167b2093359113abbd2b2ad6561e46f28f9 | /myereporter/report_display.py | 3692dc6e7596d69f3b53194d1138530ddd132a2c | [] | no_license | mdornseif/my_ereporter | ce67fadc512153327aa289b57e4abdc34065bdcd | 4c362d356d3e674cf47175ce7977a1a794ff1a9f | refs/heads/master | 2020-05-30T21:59:41.963554 | 2014-02-12T07:40:08 | 2014-02-12T07:40:08 | 3,323,415 | 0 | 0 | null | 2014-02-12T07:40:09 | 2012-02-01T09:14:12 | Python | UTF-8 | Python | false | false | 3,276 | py | #!/usr/bin/env python
#
# Copyright 2007 Google Inc.
# Copyright 2012 Dr. Maximillian Dornseif
#
# 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.
#
"""Displays exception reports.
See google/appengine/ext/ereporter/__init__.py for usage details.
"""
import datetime
import itertools
import os
import re
from xml.sax import saxutils
from google.appengine.api import mail
from google.appengine.ext import db
from google.appengine.ext import ereporter
from google.appengine.ext import webapp
from google.appengine.ext.webapp import _template
from google.appengine.ext.webapp.util import run_wsgi_app
class ReportGenerator(webapp.RequestHandler):
"""Handler class to generate and email an exception report."""
DEFAULT_MAX_RESULTS = 100
def __init__(self, *args, **kwargs):
super(ReportGenerator, self).__init__(*args, **kwargs)
def GetQuery(self):
"""Creates a query object that will retrieve the appropriate exceptions.
Returns:
A query to retrieve the exceptions required.
"""
q = ereporter.ExceptionRecord.all()
q.filter('major_version =', self.major_version)
q.filter('date >=', self.yesterday)
return q
def GenerateReport(self, exceptions):
"""Generates an HTML exception report.
Args:
exceptions: A list of ExceptionRecord objects. This argument will be
modified by this function.
Returns:
An HTML exception report.
"""
exceptions.sort(key=lambda e: (e.minor_version, -e.count))
versions = [(minor, list(excs)) for minor, excs
in itertools.groupby(exceptions, lambda e: "%s.%s" % (e.major_version, e.minor_version))]
template_values = {
'version_filter': self.version_filter,
'version_count': len(versions),
'exception_count': sum(len(excs) for _, excs in versions),
'occurrence_count': sum(y.count for x in versions for y in x[1]),
'app_id': self.app_id,
'major_version': self.major_version,
'date': self.yesterday,
'versions': versions,
}
path = os.path.join(os.path.dirname(__file__), 'templates', 'report.html')
return _template.render(path, template_values)
def get(self):
self.version_filter = 'all'
self.app_id = os.environ['APPLICATION_ID']
version = os.environ['CURRENT_VERSION_ID']
self.major_version, self.minor_version = version.rsplit('.', 1)
self.minor_version = int(self.minor_version)
self.yesterday = datetime.date.today() - datetime.timedelta(days=1)
exceptions = self.GetQuery().fetch(100)
report = self.GenerateReport(exceptions)
self.response.out.write(report)
application = webapp.WSGIApplication([('.*', ReportGenerator)])
def main():
run_wsgi_app(application)
if __name__ == '__main__':
main()
| [
"md@hudora.de"
] | md@hudora.de |
57d0f000bba622f8ae58fd6246384fdb6171a4c2 | 0e25538b2f24f1bc002b19a61391017c17667d3d | /xsqlps/win_xsqlhaendpoint.py | d63cff41b4b48b8eaa76153f1709cb850bf709e7 | [] | no_license | trondhindenes/Ansible-Auto-Generated-Modules | 725fae6ba9b0eef00c9fdc21179e2500dfd6725f | efa6ac8cd2b545116f24c1929936eb8cc5c8d337 | refs/heads/master | 2020-04-06T09:21:00.756651 | 2016-10-07T07:08:29 | 2016-10-07T07:08:29 | 36,883,816 | 12 | 2 | null | null | null | null | UTF-8 | Python | false | false | 2,205 | py | #!/usr/bin/python
# -*- coding: utf-8 -*-
# <COPYRIGHT>
# <CODEGENMETA>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
# this is a windows documentation stub. actual code lives in the .ps1
# file of the same name
DOCUMENTATION = '''
---
module: win_xsqlhaendpoint
version_added:
short_description: Generated from DSC module xsqlps version 1.4.0.0 at 07.10.2016 03.07.37
description:
- SQL module.
options:
AllowedUser:
description:
-
required: True
default:
aliases: []
InstanceName:
description:
-
required: True
default:
aliases: []
Name:
description:
-
required: True
default:
aliases: []
PortNumber:
description:
-
required: False
default:
aliases: []
PsDscRunAsCredential_username:
description:
-
required: False
default:
aliases: []
PsDscRunAsCredential_password:
description:
-
required: False
default:
aliases: []
AutoInstallModule:
description:
- If true, the required dsc resource/module will be auto-installed using the Powershell package manager
required: False
default: false
aliases: []
choices:
- true
- false
AutoConfigureLcm:
description:
- If true, LCM will be auto-configured for directly invoking DSC resources (which is a one-time requirement for Ansible DSC modules)
required: False
default: false
aliases: []
choices:
- true
- false
| [
"trond@hindenes.com"
] | trond@hindenes.com |
8cebe11dc2d30677fef4d45822d56ad632eb8314 | 277290f8cd6cc5bcb77faaf69a045f5074a988e5 | /reveal-cards-in-incr.py | db0e4830da4c2241050bac7bada38bfbe9788efc | [] | no_license | shankarkrishnamurthy/problem-solving | aed0252d9ca6d6b51e9a7d8d5e648343b4abf322 | f9bc1db1cc99b10a87a2fa51869924aa10df4c99 | refs/heads/master | 2023-03-20T18:48:45.107058 | 2023-03-06T03:24:53 | 2023-03-06T03:24:53 | 123,035,515 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 665 | py | class Solution(object):
def deckRevealedIncreasing(self, d):
"""
:type deck: List[int]
:rtype: List[int]
"""
n = len(d)
d.sort()
il, c, i = range(n),0,0
ans = [0]*n
while c < n-1:
ans[il[i]] = d[c]
i += 2
c += 1
il.append(il[i-1])
ans[il[-1]] = d[c]
return ans
print Solution().deckRevealedIncreasing([17])
print Solution().deckRevealedIncreasing([17,12])
print Solution().deckRevealedIncreasing([17,7,12])
print Solution().deckRevealedIncreasing([17,13,11,2,3,5,7])
print Solution().deckRevealedIncreasing([17,13,11,2,5,7])
| [
"kshan_77@yahoo.com"
] | kshan_77@yahoo.com |
d3bc11a9aab7b31c0267628c2f3dd7308ec7e8e1 | 9743d5fd24822f79c156ad112229e25adb9ed6f6 | /xai/brain/wordbase/nouns/_candling.py | 0473570aa258d1a60c7225076a74ed253110aa0b | [
"MIT"
] | permissive | cash2one/xai | de7adad1758f50dd6786bf0111e71a903f039b64 | e76f12c9f4dcf3ac1c7c08b0cc8844c0b0a104b6 | refs/heads/master | 2021-01-19T12:33:54.964379 | 2017-01-28T02:00:50 | 2017-01-28T02:00:50 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 240 | py |
from xai.brain.wordbase.nouns._candle import _CANDLE
#calss header
class _CANDLING(_CANDLE, ):
def __init__(self,):
_CANDLE.__init__(self)
self.name = "CANDLING"
self.specie = 'nouns'
self.basic = "candle"
self.jsondata = {}
| [
"xingwang1991@gmail.com"
] | xingwang1991@gmail.com |
897ddd4b655379b68902d88d5eb70456f63dc56b | d554b1aa8b70fddf81da8988b4aaa43788fede88 | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/226/users/4149/codes/1638_869.py | 76e2f745bcfc37ccead6e31a4844f49410cd0660 | [] | no_license | JosephLevinthal/Research-projects | a3bc3ca3b09faad16f5cce5949a2279cf14742ba | 60d5fd6eb864a5181f4321e7a992812f3c2139f9 | refs/heads/master | 2022-07-31T06:43:02.686109 | 2020-05-23T00:24:26 | 2020-05-23T00:24:26 | 266,199,309 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 133 | py | preco=float(input("digite o valor: "))
if(preco>=200):
pago= preco-((5*preco)/100)
print(round(pago,2))
else:
print(preco) | [
"jvlo@icomp.ufam.edu.br"
] | jvlo@icomp.ufam.edu.br |
701d53be3b220a15773d4bae7c650509950ea474 | 5daece6b3ee3e928d101c8614dbcb90a8569626f | /files/Exercícios Livro/c05e01.py | bc282a6143d6bb605b74864d13352c4e1506c4a1 | [
"MIT"
] | permissive | heltonricardo/estudo-python | 506b400af93039bbdca70e1bc604c588fae62af1 | e82eb8ebc15378175b03d367a6eeea66e8858cff | refs/heads/master | 2022-12-24T03:10:52.202102 | 2020-10-06T13:58:05 | 2020-10-06T13:58:05 | 294,190,313 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 216 | py | def somatorio(n):
s = 0
for i in range(1, n + 1):
s += i
return s
valor = int(float(input('Entre um valor inteiro: ')))
print('A soma de 1 até {} é {}'.format(valor, somatorio(valor)))
input()
| [
"50843386+heltonr13@users.noreply.github.com"
] | 50843386+heltonr13@users.noreply.github.com |
63b8ad3ebadc2a5c26750c091d69b542c6a4c249 | 06f7ffdae684ac3cc258c45c3daabce98243f64f | /vsts/vsts/gallery/v4_0/models/publisher.py | 6850a11a0f84d8920e40a5e224ddaa6f1d608c0b | [
"MIT",
"LicenseRef-scancode-generic-cla"
] | permissive | kenkuo/azure-devops-python-api | 7dbfb35f1c9637c9db10207824dd535c4d6861e8 | 9ac38a97a06ee9e0ee56530de170154f6ed39c98 | refs/heads/master | 2020-04-03T17:47:29.526104 | 2018-10-25T17:46:09 | 2018-10-25T17:46:09 | 155,459,045 | 0 | 0 | MIT | 2018-10-30T21:32:43 | 2018-10-30T21:32:42 | null | UTF-8 | Python | false | false | 2,466 | py | # --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------
# Generated file, DO NOT EDIT
# Changes may cause incorrect behavior and will be lost if the code is regenerated.
# --------------------------------------------------------------------------------------------
from msrest.serialization import Model
class Publisher(Model):
"""Publisher.
:param display_name:
:type display_name: str
:param email_address:
:type email_address: list of str
:param extensions:
:type extensions: list of :class:`PublishedExtension <gallery.v4_0.models.PublishedExtension>`
:param flags:
:type flags: object
:param last_updated:
:type last_updated: datetime
:param long_description:
:type long_description: str
:param publisher_id:
:type publisher_id: str
:param publisher_name:
:type publisher_name: str
:param short_description:
:type short_description: str
"""
_attribute_map = {
'display_name': {'key': 'displayName', 'type': 'str'},
'email_address': {'key': 'emailAddress', 'type': '[str]'},
'extensions': {'key': 'extensions', 'type': '[PublishedExtension]'},
'flags': {'key': 'flags', 'type': 'object'},
'last_updated': {'key': 'lastUpdated', 'type': 'iso-8601'},
'long_description': {'key': 'longDescription', 'type': 'str'},
'publisher_id': {'key': 'publisherId', 'type': 'str'},
'publisher_name': {'key': 'publisherName', 'type': 'str'},
'short_description': {'key': 'shortDescription', 'type': 'str'}
}
def __init__(self, display_name=None, email_address=None, extensions=None, flags=None, last_updated=None, long_description=None, publisher_id=None, publisher_name=None, short_description=None):
super(Publisher, self).__init__()
self.display_name = display_name
self.email_address = email_address
self.extensions = extensions
self.flags = flags
self.last_updated = last_updated
self.long_description = long_description
self.publisher_id = publisher_id
self.publisher_name = publisher_name
self.short_description = short_description
| [
"tedchamb@microsoft.com"
] | tedchamb@microsoft.com |
78b90c5ccf52433ac0fa36490bf09ee3a9537df0 | b288e79bc4aa3a3ea2e11b2fe5d9d707fc36b916 | /wen_python_18/color_term.py | bff244b69e87f087214b38f7a0db261cf928d44f | [] | no_license | pylinx64/wen_python_18 | 88e780e7045419a8c14d26f1dbb42c0d98e8856c | 173f21e046904cdc24f846e19004d2a007deb2d3 | refs/heads/main | 2023-04-17T19:36:37.485510 | 2021-05-05T10:07:41 | 2021-05-05T10:07:41 | 336,603,726 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 194 | py | import tqdm, random, time
progresBar = tqdm.tqdm(range(0, 100), desc='Loading virus...', ascii=True, bar_format='{desc}: {bar} {percentage:3.0f}% ')
for x in progresBar:
time.sleep(.05)
| [
"noreply@github.com"
] | pylinx64.noreply@github.com |
baae2fe0650b8a44e41fd46c23db0f242cd1e344 | eef2fea06f1a18b410e51dcae2ce602093ce086f | /string Valiadtor method 2.py | 9eb7c9062a78871b4fb0a2cf0e4fefc1060b6ffb | [] | no_license | vkgitmaster/HackerRank_Practice | 43de4723c31788a56b848d30ea6e69a95c305bd8 | e774a3bfedd59519c3cbb5369d472727b87655e5 | refs/heads/master | 2023-01-19T21:29:03.295968 | 2020-12-05T06:44:22 | 2020-12-05T06:44:22 | 318,719,167 | 0 | 0 | null | 2020-12-05T06:30:10 | 2020-12-05T06:30:10 | null | UTF-8 | Python | false | false | 245 | py | import re
if __name__ == '__main__':
s = input()
print(bool(re.search('[a-zA-Z0-9]', s)))
print(bool(re.search('[a-zA-Z]', s)))
print(bool(re.search('[0-9]', s)))
print(bool(re.search('[a-z]', s)))
print(bool(re.search('[A-Z]', s))) | [
"VKvision@venu.com"
] | VKvision@venu.com |
07800d09d0b326125fa78d95f54f9f1796ed958a | 8d014a0120864b42748ef63dddfa3c733370118c | /layint_api/models/user_groups.py | b9ba7c7bbbe6c943e647dc66a058e83bdcca50f2 | [
"LicenseRef-scancode-unknown",
"Apache-2.0"
] | permissive | LayeredInsight/layint_api_python | 3a6cf0bf62219f09010b828d7e02c2f3852a6f6f | a5c9a5b24098bd823c5102b7ab9e4745432f19b4 | refs/heads/develop | 2020-03-27T05:43:35.831400 | 2018-10-15T22:28:54 | 2018-10-15T22:28:54 | 146,044,385 | 0 | 0 | Apache-2.0 | 2018-10-15T22:28:55 | 2018-08-24T22:11:08 | Python | UTF-8 | Python | false | false | 2,729 | py | # coding: utf-8
"""
Layered Insight Assessment, Compliance, Witness & Control
LI Assessment & Compliance performs static vulnerability analysis, license and package compliance. LI Witness provides deep insight and analytics into containerized applications. Control provides dynamic runtime security and analytics for containerized applications. You can find out more about the Layered Insight Suite at [http://layeredinsight.com](http://layeredinsight.com).
OpenAPI spec version: 0.10
Contact: help@layeredinsight.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
import re
class UserGroups(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 = {
}
attribute_map = {
}
def __init__(self):
"""
UserGroups - a model defined in Swagger
"""
def to_dict(self):
"""
Returns the model properties as a dict
"""
result = {}
for attr, _ in 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
return result
def to_str(self):
"""
Returns the string representation of the model
"""
return 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, UserGroups):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""
Returns true if both objects are not equal
"""
return not self == other
| [
"Scott Oberg"
] | Scott Oberg |
e6c23bd6da2dd837131de10c16fc6d85e681576e | 1a166165ab8287d01cbb377a13efdb5eff5dfef0 | /sdk/network/azure-mgmt-network/azure/mgmt/network/v2020_11_01/aio/operations/_virtual_network_peerings_operations.py | 622977c9c6c9bc9881d97840e651a17da4bb700b | [
"MIT",
"LicenseRef-scancode-generic-cla",
"LGPL-2.1-or-later"
] | permissive | manoj0806/azure-sdk-for-python | 7a14b202ff80f528abd068bf50334e91001a9686 | aab999792db1132232b2f297c76800590a901142 | refs/heads/master | 2023-04-19T16:11:31.984930 | 2021-04-29T23:19:49 | 2021-04-29T23:19:49 | 363,025,016 | 1 | 0 | MIT | 2021-04-30T04:23:35 | 2021-04-30T04:23:35 | null | UTF-8 | Python | false | false | 22,611 | 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 typing import Any, AsyncIterable, Callable, Dict, Generic, Optional, TypeVar, Union
import warnings
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import ClientAuthenticationError, HttpResponseError, ResourceExistsError, ResourceNotFoundError, map_error
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse, HttpRequest
from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling
from ... import models as _models
T = TypeVar('T')
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class VirtualNetworkPeeringsOperations:
"""VirtualNetworkPeeringsOperations async operations.
You should not instantiate this class directly. Instead, you should create a Client instance that
instantiates it for you and attaches it as an attribute.
:ivar models: Alias to model classes used in this operation group.
:type models: ~azure.mgmt.network.v2020_11_01.models
:param client: Client for service requests.
:param config: Configuration of service client.
:param serializer: An object model serializer.
:param deserializer: An object model deserializer.
"""
models = _models
def __init__(self, client, config, serializer, deserializer) -> None:
self._client = client
self._serialize = serializer
self._deserialize = deserializer
self._config = config
async def _delete_initial(
self,
resource_group_name: str,
virtual_network_name: str,
virtual_network_peering_name: str,
**kwargs
) -> None:
cls = kwargs.pop('cls', None) # type: ClsType[None]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2020-11-01"
accept = "application/json"
# Construct URL
url = self._delete_initial.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'virtualNetworkName': self._serialize.url("virtual_network_name", virtual_network_name, 'str'),
'virtualNetworkPeeringName': self._serialize.url("virtual_network_peering_name", virtual_network_peering_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
request = self._client.delete(url, query_parameters, header_parameters)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 202, 204]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_delete_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/virtualNetworkPeerings/{virtualNetworkPeeringName}'} # type: ignore
async def begin_delete(
self,
resource_group_name: str,
virtual_network_name: str,
virtual_network_peering_name: str,
**kwargs
) -> AsyncLROPoller[None]:
"""Deletes the specified virtual network peering.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param virtual_network_name: The name of the virtual network.
:type virtual_network_name: str
:param virtual_network_peering_name: The name of the virtual network peering.
:type virtual_network_peering_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: True for ARMPolling, False for no polling, or a
polling object for personal polling strategy
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod]
cls = kwargs.pop('cls', None) # type: ClsType[None]
lro_delay = kwargs.pop(
'polling_interval',
self._config.polling_interval
)
cont_token = kwargs.pop('continuation_token', None) # type: Optional[str]
if cont_token is None:
raw_result = await self._delete_initial(
resource_group_name=resource_group_name,
virtual_network_name=virtual_network_name,
virtual_network_peering_name=virtual_network_peering_name,
cls=lambda x,y,z: x,
**kwargs
)
kwargs.pop('error_map', None)
kwargs.pop('content_type', None)
def get_long_running_output(pipeline_response):
if cls:
return cls(pipeline_response, None, {})
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'virtualNetworkName': self._serialize.url("virtual_network_name", virtual_network_name, 'str'),
'virtualNetworkPeeringName': self._serialize.url("virtual_network_peering_name", virtual_network_peering_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
if polling is True: polling_method = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'location'}, path_format_arguments=path_format_arguments, **kwargs)
elif polling is False: polling_method = AsyncNoPolling()
else: polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output
)
else:
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_delete.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/virtualNetworkPeerings/{virtualNetworkPeeringName}'} # type: ignore
async def get(
self,
resource_group_name: str,
virtual_network_name: str,
virtual_network_peering_name: str,
**kwargs
) -> "_models.VirtualNetworkPeering":
"""Gets the specified virtual network peering.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param virtual_network_name: The name of the virtual network.
:type virtual_network_name: str
:param virtual_network_peering_name: The name of the virtual network peering.
:type virtual_network_peering_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: VirtualNetworkPeering, or the result of cls(response)
:rtype: ~azure.mgmt.network.v2020_11_01.models.VirtualNetworkPeering
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.VirtualNetworkPeering"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2020-11-01"
accept = "application/json"
# Construct URL
url = self.get.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'virtualNetworkName': self._serialize.url("virtual_network_name", virtual_network_name, 'str'),
'virtualNetworkPeeringName': self._serialize.url("virtual_network_peering_name", virtual_network_peering_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
request = self._client.get(url, query_parameters, header_parameters)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = self._deserialize('VirtualNetworkPeering', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/virtualNetworkPeerings/{virtualNetworkPeeringName}'} # type: ignore
async def _create_or_update_initial(
self,
resource_group_name: str,
virtual_network_name: str,
virtual_network_peering_name: str,
virtual_network_peering_parameters: "_models.VirtualNetworkPeering",
**kwargs
) -> "_models.VirtualNetworkPeering":
cls = kwargs.pop('cls', None) # type: ClsType["_models.VirtualNetworkPeering"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2020-11-01"
content_type = kwargs.pop("content_type", "application/json")
accept = "application/json"
# Construct URL
url = self._create_or_update_initial.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'virtualNetworkName': self._serialize.url("virtual_network_name", virtual_network_name, 'str'),
'virtualNetworkPeeringName': self._serialize.url("virtual_network_peering_name", virtual_network_peering_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Content-Type'] = self._serialize.header("content_type", content_type, 'str')
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
body_content_kwargs = {} # type: Dict[str, Any]
body_content = self._serialize.body(virtual_network_peering_parameters, 'VirtualNetworkPeering')
body_content_kwargs['content'] = body_content
request = self._client.put(url, query_parameters, header_parameters, **body_content_kwargs)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200, 201]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize('VirtualNetworkPeering', pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize('VirtualNetworkPeering', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
_create_or_update_initial.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/virtualNetworkPeerings/{virtualNetworkPeeringName}'} # type: ignore
async def begin_create_or_update(
self,
resource_group_name: str,
virtual_network_name: str,
virtual_network_peering_name: str,
virtual_network_peering_parameters: "_models.VirtualNetworkPeering",
**kwargs
) -> AsyncLROPoller["_models.VirtualNetworkPeering"]:
"""Creates or updates a peering in the specified virtual network.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param virtual_network_name: The name of the virtual network.
:type virtual_network_name: str
:param virtual_network_peering_name: The name of the peering.
:type virtual_network_peering_name: str
:param virtual_network_peering_parameters: Parameters supplied to the create or update virtual
network peering operation.
:type virtual_network_peering_parameters: ~azure.mgmt.network.v2020_11_01.models.VirtualNetworkPeering
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: True for ARMPolling, False for no polling, or a
polling object for personal polling strategy
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either VirtualNetworkPeering or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[~azure.mgmt.network.v2020_11_01.models.VirtualNetworkPeering]
:raises ~azure.core.exceptions.HttpResponseError:
"""
polling = kwargs.pop('polling', True) # type: Union[bool, AsyncPollingMethod]
cls = kwargs.pop('cls', None) # type: ClsType["_models.VirtualNetworkPeering"]
lro_delay = kwargs.pop(
'polling_interval',
self._config.polling_interval
)
cont_token = kwargs.pop('continuation_token', None) # type: Optional[str]
if cont_token is None:
raw_result = await self._create_or_update_initial(
resource_group_name=resource_group_name,
virtual_network_name=virtual_network_name,
virtual_network_peering_name=virtual_network_peering_name,
virtual_network_peering_parameters=virtual_network_peering_parameters,
cls=lambda x,y,z: x,
**kwargs
)
kwargs.pop('error_map', None)
kwargs.pop('content_type', None)
def get_long_running_output(pipeline_response):
deserialized = self._deserialize('VirtualNetworkPeering', pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'virtualNetworkName': self._serialize.url("virtual_network_name", virtual_network_name, 'str'),
'virtualNetworkPeeringName': self._serialize.url("virtual_network_peering_name", virtual_network_peering_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
if polling is True: polling_method = AsyncARMPolling(lro_delay, lro_options={'final-state-via': 'azure-async-operation'}, path_format_arguments=path_format_arguments, **kwargs)
elif polling is False: polling_method = AsyncNoPolling()
else: polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output
)
else:
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_create_or_update.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/virtualNetworkPeerings/{virtualNetworkPeeringName}'} # type: ignore
def list(
self,
resource_group_name: str,
virtual_network_name: str,
**kwargs
) -> AsyncIterable["_models.VirtualNetworkPeeringListResult"]:
"""Gets all virtual network peerings in a virtual network.
:param resource_group_name: The name of the resource group.
:type resource_group_name: str
:param virtual_network_name: The name of the virtual network.
:type virtual_network_name: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either VirtualNetworkPeeringListResult or the result of cls(response)
:rtype: ~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.network.v2020_11_01.models.VirtualNetworkPeeringListResult]
:raises: ~azure.core.exceptions.HttpResponseError
"""
cls = kwargs.pop('cls', None) # type: ClsType["_models.VirtualNetworkPeeringListResult"]
error_map = {
401: ClientAuthenticationError, 404: ResourceNotFoundError, 409: ResourceExistsError
}
error_map.update(kwargs.pop('error_map', {}))
api_version = "2020-11-01"
accept = "application/json"
def prepare_request(next_link=None):
# Construct headers
header_parameters = {} # type: Dict[str, Any]
header_parameters['Accept'] = self._serialize.header("accept", accept, 'str')
if not next_link:
# Construct URL
url = self.list.metadata['url'] # type: ignore
path_format_arguments = {
'resourceGroupName': self._serialize.url("resource_group_name", resource_group_name, 'str'),
'virtualNetworkName': self._serialize.url("virtual_network_name", virtual_network_name, 'str'),
'subscriptionId': self._serialize.url("self._config.subscription_id", self._config.subscription_id, 'str'),
}
url = self._client.format_url(url, **path_format_arguments)
# Construct parameters
query_parameters = {} # type: Dict[str, Any]
query_parameters['api-version'] = self._serialize.query("api_version", api_version, 'str')
request = self._client.get(url, query_parameters, header_parameters)
else:
url = next_link
query_parameters = {} # type: Dict[str, Any]
request = self._client.get(url, query_parameters, header_parameters)
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize('VirtualNetworkPeeringListResult', pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run(request, stream=False, **kwargs)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(
get_next, extract_data
)
list.metadata = {'url': '/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{virtualNetworkName}/virtualNetworkPeerings'} # type: ignore
| [
"noreply@github.com"
] | manoj0806.noreply@github.com |
639a77b123efd4d955c07a5f637e1a9b416ce673 | 040fbf650a95564c92632189687bc2a924d0a327 | /gmn/src/d1_gmn/app/views/headers.py | 0c776cd55fcf1fd7dd1c1882b5766aa4a8455d0a | [
"Apache-2.0"
] | permissive | vchendrix/d1_python | 97b4e9671ae0642fdfa94054e270d44bcf1b6b6b | 0fa85c3a8de158d0225bd7428ddab3cf53a3d3e7 | refs/heads/master | 2020-03-20T22:25:55.987123 | 2018-06-15T18:33:06 | 2018-06-15T18:33:06 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 3,446 | py | # -*- coding: utf-8 -*-
# This work was created by participants in the DataONE project, and is
# jointly copyrighted by participating institutions in DataONE. For
# more information on DataONE, see our web site at http://dataone.org.
#
# Copyright 2009-2016 DataONE
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Read and write HTTP Headers
"""
import datetime
import d1_gmn.app
import d1_gmn.app.auth
import d1_gmn.app.db_filter
import d1_gmn.app.did
import d1_gmn.app.event_log
import d1_gmn.app.models
import d1_gmn.app.psycopg_adapter
import d1_gmn.app.revision
import d1_gmn.app.sysmeta
import d1_gmn.app.util
import d1_gmn.app.views.slice
import d1_gmn.app.views.util
import d1_common.const
import d1_common.date_time
import d1_common.type_conversions
import d1_common.types
import d1_common.types.dataoneTypes
import d1_common.types.dataoneTypes_v1_1
import d1_common.types.dataoneTypes_v2_0
import d1_common.types.exceptions
import d1_common.url
import d1_common.xml
def add_sciobj_properties_headers_to_response(response, sciobj):
response['Content-Length'] = sciobj.size
response['Content-Type'] = d1_gmn.app.views.util.content_type_from_format(
sciobj.format.format
)
response['Last-Modified'] = d1_common.date_time.http_datetime_str_from_dt(
d1_common.date_time.normalize_datetime_to_utc(sciobj.modified_timestamp)
)
response['DataONE-GMN'] = d1_gmn.__version__
response['DataONE-FormatId'] = sciobj.format.format
response['DataONE-Checksum'] = '{},{}'.format(
sciobj.checksum_algorithm.checksum_algorithm, sciobj.checksum
)
response['DataONE-SerialVersion'] = sciobj.serial_version
add_http_date_header_to_response(response)
if d1_common.url.isHttpOrHttps(sciobj.url):
response['DataONE-Proxy'] = sciobj.url
if sciobj.obsoletes:
response['DataONE-Obsoletes'] = sciobj.obsoletes.did
if sciobj.obsoleted_by:
response['DataONE-ObsoletedBy'] = sciobj.obsoleted_by.did
sid = d1_gmn.app.revision.get_sid_by_pid(sciobj.pid.did)
if sid:
response['DataONE-SeriesId'] = sid
def add_http_date_header_to_response(response, date_time=None):
response['Date'] = d1_common.date_time.http_datetime_str_from_dt(
d1_common.date_time.normalize_datetime_to_utc(date_time)
if date_time else datetime.datetime.utcnow()
)
def add_cors_headers_to_response(response, method_list):
"""Add Cross-Origin Resource Sharing (CORS) headers to response
- {method_list} is a list of HTTP methods that are allowed for the endpoint
that was called. It should not include "OPTIONS", which is included
automatically since it's allowed for all endpoints.
"""
opt_method_list = ','.join(method_list + ['OPTIONS'])
response['Allow'] = opt_method_list
response['Access-Control-Allow-Methods'] = opt_method_list
response['Access-Control-Allow-Origin'] = '*'
response['Access-Control-Allow-Headers'] = 'Authorization'
response['Access-Control-Allow-Credentials'] = 'true'
| [
"git@dahlsys.com"
] | git@dahlsys.com |
df5d69817ac04c7ca1a7fd5955756c39b6775ff7 | 63ace5832d453e325681d02f6496a0999b72edcb | /examples/monero.py | a8fe6f2b129f8e624e70388c97b8227a4626792e | [
"MIT"
] | permissive | ebellocchia/bip_utils | c9ec04c687f4247e57434319e36b2abab78f0b32 | d15c75ddd74e4838c396a0d036ef6faf11b06a4b | refs/heads/master | 2023-09-01T13:38:55.567370 | 2023-08-16T17:04:14 | 2023-08-16T17:04:14 | 251,130,186 | 244 | 88 | MIT | 2023-08-23T13:46:19 | 2020-03-29T20:42:48 | Python | UTF-8 | Python | false | false | 1,284 | py | """Example of keys derivation for Monero (same addresses of official wallet)."""
import binascii
from bip_utils import Monero, MoneroMnemonicGenerator, MoneroSeedGenerator, MoneroWordsNum
# Generate random mnemonic
mnemonic = MoneroMnemonicGenerator().FromWordsNumber(MoneroWordsNum.WORDS_NUM_25)
print(f"Mnemonic string: {mnemonic}")
# Generate seed from mnemonic
seed_bytes = MoneroSeedGenerator(mnemonic).Generate()
# Construct from seed
monero = Monero.FromSeed(seed_bytes)
# Print keys
print(f"Monero private spend key: {monero.PrivateSpendKey().Raw().ToHex()}")
print(f"Monero private view key: {monero.PrivateViewKey().Raw().ToHex()}")
print(f"Monero public spend key: {monero.PublicSpendKey().RawCompressed().ToHex()}")
print(f"Monero public view key: {monero.PublicViewKey().RawCompressed().ToHex()}")
# Print primary address
print(f"Monero primary address: {monero.PrimaryAddress()}")
# Print integrated address
payment_id = binascii.unhexlify(b"d6f093554c0daa94")
print(f"Monero integrated address: {monero.IntegratedAddress(payment_id)}")
# Print the first 5 subaddresses for account 0 and 1
for acc_idx in range(2):
for subaddr_idx in range(5):
print(f"Subaddress (account: {acc_idx}, index: {subaddr_idx}): {monero.Subaddress(subaddr_idx, acc_idx)}")
| [
"54482000+ebellocchia@users.noreply.github.com"
] | 54482000+ebellocchia@users.noreply.github.com |
23205934f3e45edba56c28705da6439fac77b2a5 | f0d713996eb095bcdc701f3fab0a8110b8541cbb | /nn7JKRBfq8iDcX8ZB_15.py | f35f0f8e1dfbbfd7b790a500d47aa08cf05efda7 | [] | no_license | daniel-reich/turbo-robot | feda6c0523bb83ab8954b6d06302bfec5b16ebdf | a7a25c63097674c0a81675eed7e6b763785f1c41 | refs/heads/main | 2023-03-26T01:55:14.210264 | 2021-03-23T16:08:01 | 2021-03-23T16:08:01 | 350,773,815 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 452 | py | """
Write a function that returns a **lambda expression** , which transforms its
input by adding a particular `suffix` at the end.
### Examples
add_ly = add_suffix("ly")
add_ly("hopeless") ➞ "hopelessly"
add_ly("total") ➞ "totally"
add_less = add_suffix("less")
add_less("fear") ➞ "fearless"
add_less("ruth") ➞ "ruthless"
### Notes
N/A
"""
def add_suffix(suffix):
return lambda x: x + suffix
| [
"daniel.reich@danielreichs-MacBook-Pro.local"
] | daniel.reich@danielreichs-MacBook-Pro.local |
3d240c0fdda9cbe03630ab8703bc3fb487c7fd6d | 2296699c10d8e01da0b1ac079d67e87c8e4f766a | /code/objects.py | 5d4a81ccbfc9808f5a8f072b6bfeb0fcd08a3a82 | [
"Apache-2.0"
] | permissive | marcverhagen/semcor | 8d18060885b7a8a1aca1d7987577cbe0cf2cecc1 | d2ff7867880029800c1524444533843510cd78a6 | refs/heads/master | 2021-08-16T21:34:36.868125 | 2020-03-02T18:55:52 | 2020-03-02T18:55:52 | 162,839,926 | 1 | 2 | null | null | null | null | UTF-8 | Python | false | false | 4,998 | py | """
"""
from __future__ import print_function
import os
from ansi import BOLD, BLUE, GREEN, GREY, END
class SemcorObject(object):
def is_paragraph(self):
return False
def is_sentence(self):
return False
def is_word_form(self):
return False
def is_punctuation(self):
return False
class Paragraph(SemcorObject):
def __init__(self, pid):
self.pid = pid # <string>
self.sentences = []
def add_sentence(self, sent):
self.sentences.append(sent)
def is_paragraph(self):
return True
def collect_forms(self, forms):
"""Collect all instances of WordForm that have a sense."""
for s in self.sentences:
s.collect_forms(forms)
def pp(self):
print("<para %s>" % self.pid)
for s in self.sentences:
s.pp()
class Sentence(SemcorObject):
def __init__(self, semcor_file, para, sid):
self.fname = os.path.basename(semcor_file.fname)
self.para = para
self.pid = para.pid # <string>
self.sid = sid # <string>
self.elements = []
def __str__(self):
return "<Sentence %s:%s with %d wfs>" % (self.fname, self.sid, len(self.elements))
def is_sentence(self):
return True
def get_element(self, n):
"""Returns the WordForm or the Punctuation instance at position n of the list of
elements in the sentence, returns None if there is no such index."""
try:
return self.elements[n]
except IndexError:
return None
def add_element(self, element):
# note that an element will either be an instance of WordForm or an
# instance of Punctuation
self.elements.append(element)
def collect_forms(self, forms):
for wf in self.elements:
if wf.is_word_form() and wf.has_sense():
forms.append(wf)
def as_string(self):
return ' '.join([t.text for t in self.elements])
def pp(self, highlight=None):
print("%s%s%s-%s%s: " % (GREY, GREEN, self.fname, self.sid, END), end='')
for wf in self.elements:
if wf.is_word_form() and highlight == wf.position:
print(BOLD + BLUE + wf.text + END, end=' ')
#elif wf.has_sense():
# print(BLUE+wf.text+END, end=' ')
else:
print(wf.text, end=' ')
print()
class WordForm(SemcorObject):
"""Semcor word forms have a lemma, a part-of-speech, a wordnet sense and a
lexical sense (we are for now ignoring other attributes). Word forms are
initiated from a tag like the following.
<wf cmd=done pos=VB lemma=say wnsn=1 lexsn=2:32:00::>said</wf>
Note that these word forms can have multiple tokens and those are not just
for names, for example primary_election is a word form. Some word forms do
not have senses associated with them, for them we just have POS and the
text."""
def __init__(self, para, sent, position, tag):
self.para = para # instance of Paragraph
self.sent = sent # instance of Sentence
self.position = position # position in the sentence
self.pid = para.pid
self.sid = sent.sid
self.pos = tag.get('pos')
self.rdf = tag.get('rdf')
self.pn = tag.get('pn')
self.lemma = tag.get('lemma')
self.wnsn = tag.get('wnsn')
self.lexsn = tag.get('lexsn')
self.text = tag.getText()
self.synset = None
self.keys = tuple(tag.__dict__['attrs'].keys()) # for statistics
def __str__(self):
if self.wnsn is None:
return "<wf %s %s>" % (self.pos, self.text)
else:
return "<wf %s %s %s %s>" % (self.pos, self.lemma, self.wnsn, self.lexsn)
def sense(self):
return "%s%%%s" % (self.lemma, self.lexsn) if self.has_sense() else None
def is_word_form(self):
return True
def is_nominal(self):
return self.pos.startswith('NN')
def is_common_noun(self):
return self.pos in ('NN', 'NNS')
def has_sense(self):
return self.wnsn is not None and self.lexsn is not None
def kwic(self, context):
kw = self.sent.elements[self.position].text
left = self.sent.elements[:self.position]
right = self.sent.elements[self.position+1:]
left = ' '.join([t.text for t in left])
right = ' '.join([t.text for t in right])
left = left[-context:]
right = right[:context]
return (left, kw, right)
class Punctuation(SemcorObject):
def __init__(self, tag):
self.text = tag.getText()
self.keys = tuple()
def __str__(self):
return "<Punctuation %s>" % self.text
def is_punctuation(self):
return True
def has_sense(self):
return False
def sense(self):
return None
| [
"marc@cs.brandeis.edu"
] | marc@cs.brandeis.edu |
2575e15e4676e4d0a444b5dd13502b5edbdc0445 | 338dbd8788b019ab88f3c525cddc792dae45036b | /lib/python3.6/site-packages/statsmodels/sandbox/regression/penalized.py | 442cc669e096a42da7502f5266ff3feab463a916 | [] | permissive | KshitizSharmaV/Quant_Platform_Python | 9b8b8557f13a0dde2a17de0e3352de6fa9b67ce3 | d784aa0604d8de5ba5ca0c3a171e3556c0cd6b39 | refs/heads/master | 2022-12-10T11:37:19.212916 | 2019-07-09T20:05:39 | 2019-07-09T20:05:39 | 196,073,658 | 1 | 2 | BSD-3-Clause | 2022-11-27T18:30:16 | 2019-07-09T19:48:26 | Python | UTF-8 | Python | false | false | 17,444 | py | # -*- coding: utf-8 -*-
"""linear model with Theil prior probabilistic restrictions, generalized Ridge
Created on Tue Dec 20 00:10:10 2011
Author: Josef Perktold
License: BSD-3
open issues
* selection of smoothing factor, strength of prior, cross validation
* GLS, does this really work this way
* None of inherited results have been checked yet,
I'm not sure if any need to be adjusted or if only interpretation changes
One question is which results are based on likelihood (residuals) and which
are based on "posterior" as for example bse and cov_params
* helper functions to construct priors?
* increasing penalization for ordered regressors, e.g. polynomials
* compare with random/mixed effects/coefficient, like estimated priors
there is something fishy with the result instance, some things, e.g.
normalized_cov_params, don't look like they update correctly as we
search over lambda -> some stale state again ?
I added df_model to result class using the hatmatrix, but df_model is defined
in model instance not in result instance. -> not clear where refactoring should
occur. df_resid doesn't get updated correctly.
problem with definition of df_model, it has 1 subtracted for constant
"""
from __future__ import print_function
from statsmodels.compat.python import lrange
import numpy as np
from statsmodels.tools.decorators import cache_readonly
from statsmodels.regression.linear_model import OLS, GLS, RegressionResults
def atleast_2dcols(x):
x = np.asarray(x)
if x.ndim == 1:
x = x[:, None]
return x
class TheilGLS(GLS):
r"""GLS with stochastic restrictions
TheilGLS estimates the following linear model
.. math:: y = X \beta + u
using additional information given by a stochastic constraint
.. math:: q = R \beta + v
:math:`E(u) = 0`, :math:`cov(u) = \Sigma`
:math:`cov(u, v) = \Sigma_p`, with full rank.
u and v are assumed to be independent of each other.
If :math:`E(v) = 0`, then the estimator is unbiased.
Note: The explanatory variables are not rescaled, the parameter estimates
not scale equivariant and fitted values are not scale invariant since
scaling changes the relative penalization weights (for given \Sigma_p).
Note: GLS is not tested yet, only Sigma is identity is tested
Notes
-----
The parameter estimates solves the moment equation:
.. math:: (X' \Sigma X + \lambda R' \sigma^2 \Sigma_p^{-1} R) b = X' \Sigma y + \lambda R' \Sigma_p^{-1} q
:math:`\lambda` is the penalization weight similar to Ridge regression.
If lambda is zero, then the parameter estimate is the same as OLS. If
lambda goes to infinity, then the restriction is imposed with equality.
In the model `pen_weight` is used as name instead of $\lambda$
R does not have to be square. The number of rows of R can be smaller
than the number of parameters. In this case not all linear combination
of parameters are penalized.
The stochastic constraint can be interpreted in several different ways:
- The prior information represents parameter estimates from independent
prior samples.
- We can consider it just as linear restrictions that we do not want
to impose without uncertainty.
- With a full rank square restriction matrix R, the parameter estimate
is the same as a Bayesian posterior mean for the case of an informative
normal prior, normal likelihood and known error variance Sigma. If R
is less than full rank, then it defines a partial prior.
References
----------
Theil Goldberger
Baum, Christopher slides for tgmixed in Stata
(I don't remember what I used when I first wrote the code.)
Parameters
----------
endog : array_like, 1-D
dependent or endogenous variable
exog : array_like, 1D or 2D
array of explanatory or exogenous variables
r_matrix : None or array_like, 2D
array of linear restrictions for stochastic constraint.
default is identity matrix that does not penalize constant, if constant
is detected to be in `exog`.
q_matrix : None or array_like
mean of the linear restrictions. If None, the it is set to zeros.
sigma_prior : None or array_like
A fully specified sigma_prior is a square matrix with the same number
of rows and columns as there are constraints (number of rows of r_matrix).
If sigma_prior is None, a scalar or one-dimensional, then a diagonal matrix
is created.
sigma : None or array_like
Sigma is the covariance matrix of the error term that is used in the same
way as in GLS.
"""
def __init__(self, endog, exog, r_matrix=None, q_matrix=None,
sigma_prior=None, sigma=None):
super(TheilGLS, self).__init__(endog, exog, sigma=sigma)
if r_matrix is not None:
r_matrix = np.asarray(r_matrix)
else:
try:
const_idx = self.data.const_idx
except AttributeError:
const_idx = None
k_exog = exog.shape[1]
r_matrix = np.eye(k_exog)
if const_idx is not None:
keep_idx = lrange(k_exog)
del keep_idx[const_idx]
r_matrix = r_matrix[keep_idx] # delete row for constant
k_constraints, k_exog = r_matrix.shape
self.r_matrix = r_matrix
if k_exog != self.exog.shape[1]:
raise ValueError('r_matrix needs to have the same number of columns'
'as exog')
if q_matrix is not None:
self.q_matrix = atleast_2dcols(q_matrix)
else:
self.q_matrix = np.zeros(k_constraints)[:, None]
if self.q_matrix.shape != (k_constraints, 1):
raise ValueError('q_matrix has wrong shape')
if sigma_prior is not None:
sigma_prior = np.asarray(sigma_prior)
if np.size(sigma_prior) == 1:
sigma_prior = np.diag(sigma_prior * np.ones(k_constraints))
#no numerical shortcuts are used for this case
elif sigma_prior.ndim == 1:
sigma_prior = np.diag(sigma_prior)
else:
sigma_prior = np.eye(k_constraints)
if sigma_prior.shape != (k_constraints, k_constraints):
raise ValueError('sigma_prior has wrong shape')
self.sigma_prior = sigma_prior
self.sigma_prior_inv = np.linalg.pinv(sigma_prior) #or inv
def fit(self, pen_weight=1., cov_type='sandwich', use_t=True):
"""Estimate parameters and return results instance
Parameters
----------
pen_weight : float
penalization factor for the restriction, default is 1.
cov_type : string, 'data-prior' or 'sandwich'
'data-prior' assumes that the stochastic restriction reflects a
previous sample. The covariance matrix of the parameter estimate
is in this case the same form as the one of GLS.
The covariance matrix for cov_type='sandwich' treats the stochastic
restriction (R and q) as fixed and has a sandwich form analogously
to M-estimators.
Returns
-------
results : TheilRegressionResults instance
Notes
-----
cov_params for cov_type data-prior, is calculated as
.. math:: \\sigma^2 A^{-1}
cov_params for cov_type sandwich, is calculated as
.. math:: \\sigma^2 A^{-1} (X'X) A^{-1}
where :math:`A = X' \\Sigma X + \\lambda \\sigma^2 R' \\Simga_p^{-1} R`
:math:`\\sigma^2` is an estimate of the error variance.
:math:`\\sigma^2` inside A is replaced by the estimate from the initial
GLS estimate. :math:`\\sigma^2` in cov_params is obtained from the
residuals of the final estimate.
The sandwich form of the covariance estimator is not robust to
misspecified heteroscedasticity or autocorrelation.
"""
lambd = pen_weight
#this does duplicate transformation, but I need resid not wresid
res_gls = GLS(self.endog, self.exog, sigma=self.sigma).fit()
self.res_gls = res_gls
sigma2_e = res_gls.mse_resid
r_matrix = self.r_matrix
q_matrix = self.q_matrix
sigma_prior_inv = self.sigma_prior_inv
x = self.wexog
y = self.wendog[:,None]
#why are sigma2_e * lambd multiplied, not ratio?
#larger lambd -> stronger prior (it's not the variance)
# Bayesian: lambd is precision = 1/sigma2_prior
#print('lambd inside fit', lambd
xx = np.dot(x.T, x)
xpx = xx + \
sigma2_e * lambd * np.dot(r_matrix.T, np.dot(sigma_prior_inv, r_matrix))
xpy = np.dot(x.T, y) + \
sigma2_e * lambd * np.dot(r_matrix.T, np.dot(sigma_prior_inv, q_matrix))
#xpy = xpy[:,None]
xpxi = np.linalg.pinv(xpx, rcond=1e-15**2) #to match pinv(x) in OLS case
xpxi_sandwich = xpxi.dot(xx).dot(xpxi)
params = np.dot(xpxi, xpy) #or solve
params = np.squeeze(params)
# normalized_cov_params should have sandwich form xpxi @ xx @ xpxi
if cov_type == 'sandwich':
normalized_cov_params = xpxi_sandwich
elif cov_type == 'data-prior':
normalized_cov_params = xpxi #why attach it to self, i.e. model?
else:
raise ValueError("cov_type has to be 'sandwich' or 'data-prior'")
self.normalized_cov_params = xpxi_sandwich
self.xpxi = xpxi
self.sigma2_e = sigma2_e
lfit = TheilRegressionResults(self, params,
normalized_cov_params=normalized_cov_params, use_t=use_t)
lfit.penalization_factor = lambd
return lfit
def select_pen_weight(self, method='aicc', start_params=1., optim_args=None):
"""find penalization factor that minimizes gcv or an information criterion
Parameters
----------
method : string
the name of an attribute of the results class. Currently the following
are available aic, aicc, bic, gc and gcv.
start_params : float
starting values for the minimization to find the penalization factor
`lambd`. Not since there can be local minima, it is best to try
different starting values.
optim_args : None or dict
optimization keyword arguments used with `scipy.optimize.fmin`
Returns
-------
min_pen_weight : float
The penalization factor at which the target criterion is (locally)
minimized.
Notes
-----
This uses `scipy.optimize.fmin` as optimizer.
"""
if optim_args is None:
optim_args = {}
#this doesn't make sense, since number of parameters stays unchanged
# information criteria changes if we use df_model based on trace(hat_matrix)
#need leave-one-out, gcv; or some penalization for weak priors
#added extra penalization for lambd
def get_ic(lambd):
# this can be optimized more
# for pure Ridge we can keep the eigenvector decomposition
return getattr(self.fit(lambd), method)
from scipy import optimize
lambd = optimize.fmin(get_ic, start_params, **optim_args)
return lambd
#TODO:
#I need the hatmatrix in the model if I want to do iterative fitting, e.g. GCV
#move to model or use it from a results instance inside the model,
# each call to fit returns results instance
# note: we need to recalculate hatmatrix for each lambda, so keep in results is fine
class TheilRegressionResults(RegressionResults):
def __init__(self, *args, **kwds):
super(TheilRegressionResults, self).__init__(*args, **kwds)
# overwrite df_model and df_resid
self.df_model = self.hatmatrix_trace() - 1 #assume constant
self.df_resid = self.model.endog.shape[0] - self.df_model - 1
@cache_readonly
def hatmatrix_diag(self):
'''diagonal of hat matrix
diag(X' xpxi X)
where xpxi = (X'X + sigma2_e * lambd * sigma_prior)^{-1}
Notes
-----
uses wexog, so this includes weights or sigma - check this case
not clear whether I need to multiply by sigmahalf, i.e.
(W^{-0.5} X) (X' W X)^{-1} (W^{-0.5} X)' or
(W X) (X' W X)^{-1} (W X)'
projection y_hat = H y or in terms of transformed variables (W^{-0.5} y)
might be wrong for WLS and GLS case
'''
# TODO is this still correct with sandwich normalized_cov_params, I guess not
xpxi = self.model.normalized_cov_params
#something fishy with self.normalized_cov_params in result, doesn't update
#print(self.model.wexog.shape, np.dot(xpxi, self.model.wexog.T).shape
return (self.model.wexog * np.dot(xpxi, self.model.wexog.T).T).sum(1)
#@cache_readonly
def hatmatrix_trace(self):
"""trace of hat matrix
"""
return self.hatmatrix_diag.sum()
## #this doesn't update df_resid
## @property #needs to be property or attribute (no call)
## def df_model(self):
## return self.hatmatrix_trace()
#Note: mse_resid uses df_resid not nobs-k_vars, which might differ if df_model, tr(H), is used
#in paper for gcv ess/nobs is used instead of mse_resid
@cache_readonly
def gcv(self):
return self.mse_resid / (1. - self.hatmatrix_trace() / self.nobs)**2
@cache_readonly
def cv(self):
return ((self.resid / (1. - self.hatmatrix_diag))**2).sum() / self.nobs
@cache_readonly
def aicc(self):
aic = np.log(self.mse_resid) + 1
aic += 2 * (1. + self.hatmatrix_trace()) / (self.nobs - self.hatmatrix_trace() -2)
return aic
def test_compatibility(self):
"""Hypothesis test for the compatibility of prior mean with data
"""
# TODO: should we store the OLS results ? not needed so far, but maybe cache
#params_ols = np.linalg.pinv(self.model.exog).dot(self.model.endog)
#res = self.wald_test(self.model.r_matrix, q_matrix=self.model.q_matrix, use_f=False)
#from scratch
res_ols = OLS(self.model.endog, self.model.exog).fit()
r_mat = self.model.r_matrix
r_diff = self.model.q_matrix - r_mat.dot(res_ols.params)[:,None]
ols_cov_r = res_ols.cov_params(r_matrix=r_mat)
statistic = r_diff.T.dot(np.linalg.solve(ols_cov_r + self.model.sigma_prior, r_diff))
from scipy import stats
df = np.linalg.matrix_rank(self.model.sigma_prior) # same as r_mat.shape[0]
pvalue = stats.chi2.sf(statistic, df)
# TODO: return results class
return statistic, pvalue, df
def share_data(self):
"""a measure for the fraction of the data in the estimation result
The share of the prior information is `1 - share_data`.
Returns
-------
share : float between 0 and 1
share of data defined as the ration between effective degrees of
freedom of the model and the number (TODO should be rank) of the
explanatory variables.
"""
# this is hatmatrix_trace / self.exog.shape[1]
# This needs to use rank of exog and not shape[1],
# since singular exog is allowed
return (self.df_model + 1) / self.model.rank # + 1 is for constant
# contrast/restriction matrices, temporary location
def coef_restriction_meandiff(n_coeffs, n_vars=None, position=0):
reduced = np.eye(n_coeffs) - 1./n_coeffs
if n_vars is None:
return reduced
else:
full = np.zeros((n_coeffs, n_vars))
full[:, position:position+n_coeffs] = reduced
return full
def coef_restriction_diffbase(n_coeffs, n_vars=None, position=0, base_idx=0):
reduced = -np.eye(n_coeffs) #make all rows, drop one row later
reduced[:, base_idx] = 1
keep = lrange(n_coeffs)
del keep[base_idx]
reduced = np.take(reduced, keep, axis=0)
if n_vars is None:
return reduced
else:
full = np.zeros((n_coeffs-1, n_vars))
full[:, position:position+n_coeffs] = reduced
return full
def next_odd(d):
return d + (1 - d % 2)
def coef_restriction_diffseq(n_coeffs, degree=1, n_vars=None, position=0, base_idx=0):
#check boundaries, returns "valid" ?
if degree == 1:
diff_coeffs = [-1, 1]
n_points = 2
elif degree > 1:
from scipy import misc
n_points = next_odd(degree + 1) #next odd integer after degree+1
diff_coeffs = misc.central_diff_weights(n_points, ndiv=degree)
dff = np.concatenate((diff_coeffs, np.zeros(n_coeffs - len(diff_coeffs))))
from scipy import linalg
reduced = linalg.toeplitz(dff, np.zeros(n_coeffs - len(diff_coeffs) + 1)).T
#reduced = np.kron(np.eye(n_coeffs-n_points), diff_coeffs)
if n_vars is None:
return reduced
else:
full = np.zeros((n_coeffs-1, n_vars))
full[:, position:position+n_coeffs] = reduced
return full
##
## R = np.c_[np.zeros((n_groups, k_vars-1)), np.eye(n_groups)]
## r = np.zeros(n_groups)
## R = np.c_[np.zeros((n_groups-1, k_vars)),
## np.eye(n_groups-1)-1./n_groups * np.ones((n_groups-1, n_groups-1))]
| [
"kshitizsharmav@gmail.com"
] | kshitizsharmav@gmail.com |
ef5e9a18a00128b006326db88a45a5ba9a3a18b8 | 487ce91881032c1de16e35ed8bc187d6034205f7 | /codes/CodeJamCrawler/16_1_1_neat/16_1_1_Lukasod_problem1.py | 26c9273e42e32c0821136127856ef4a61e00d5be | [] | no_license | DaHuO/Supergraph | 9cd26d8c5a081803015d93cf5f2674009e92ef7e | c88059dc66297af577ad2b8afa4e0ac0ad622915 | refs/heads/master | 2021-06-14T16:07:52.405091 | 2016-08-21T13:39:13 | 2016-08-21T13:39:13 | 49,829,508 | 2 | 0 | null | 2021-03-19T21:55:46 | 2016-01-17T18:23:00 | Python | UTF-8 | Python | false | false | 251 | py |
T = int(input().strip())
for i in range(T):
S = input().strip()
words = [S[0]]
for letter in S[1:]:
words = [letter + j for j in words] + [j + letter for j in words]
print("Case #" + str(i + 1) + ": " + sorted(words)[-1])
| [
"[dhuo@tcd.ie]"
] | [dhuo@tcd.ie] |
8bf29bb739823ba7eace53be017b716d5a54f108 | de24f83a5e3768a2638ebcf13cbe717e75740168 | /moodledata/vpl_data/152/usersdata/274/66550/submittedfiles/swamee.py | 5865cf6df59fa8f2d3a45f20a805d5a79ad2d0f9 | [] | no_license | rafaelperazzo/programacao-web | 95643423a35c44613b0f64bed05bd34780fe2436 | 170dd5440afb9ee68a973f3de13a99aa4c735d79 | refs/heads/master | 2021-01-12T14:06:25.773146 | 2017-12-22T16:05:45 | 2017-12-22T16:05:45 | 69,566,344 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 372 | py | # -*- coding: utf-8 -*-
import math
#COMECE SEU CÓDIGO AQUI
#ENTRADA
f = float(input("Valor de f: "))
L = float(input("Valor de L: "))
Q = float(input("Valor de Q: "))
DeltaH = float(input("Valor de delta H: "))
V = float(input("valor de V: "))
#PROCESSAMENTO
D = ((8*f*L*(Q**2))/((3.14159**2)*9.81*DeltaH))**(1/5)
Rey = (4*Q)/(3.14159*D*V)
K = (0.25)/math.log10(0.000000 | [
"rafael.mota@ufca.edu.br"
] | rafael.mota@ufca.edu.br |
6bc1d0251fa9f3b44c2b49da8e8613f888c65b93 | c1a3d3b60441125605bc8bc42ede890808344b53 | /utils.py | 70943c1f2252d425d6ea863d166f7d35b27cf49a | [
"MIT"
] | permissive | learningequality/sushi-chef-readwritethink | a5c4a0944e364aaa9a8d15e7dd29bbe83f928be4 | 261191fd35b81774cc60a19ae8c27f8fa04fc352 | refs/heads/master | 2021-05-03T11:56:40.036853 | 2019-02-22T21:52:49 | 2019-02-22T21:52:49 | 120,490,074 | 0 | 1 | MIT | 2019-02-22T21:52:50 | 2018-02-06T16:42:03 | Python | UTF-8 | Python | false | false | 3,079 | py | import json
import os
from pathlib import Path
import ntpath
from ricecooker.utils import downloader
import requests
from ricecooker.utils.caching import CacheForeverHeuristic, FileCache, CacheControlAdapter
#from le_utils.constants import licenses, content_kinds, file_formats
DATA_DIR = "chefdata"
BASE_URL = "http://www.readwritethink.org"
sess = requests.Session()
cache = FileCache('.webcache')
basic_adapter = CacheControlAdapter(cache=cache)
forever_adapter = CacheControlAdapter(heuristic=CacheForeverHeuristic(), cache=cache)
sess.mount('http://', basic_adapter)
sess.mount(BASE_URL, forever_adapter)
def save_thumbnail(url, save_as):
THUMB_DATA_DIR = build_path([DATA_DIR, 'thumbnail'])
filepath = os.path.join(THUMB_DATA_DIR, save_as)
try:
document = downloader.read(url, loadjs=False, session=sess)
except requests.exceptions.ConnectionError as e:
return None
else:
with open(filepath, 'wb') as f:
f.write(document)
return filepath
def if_file_exists(filepath):
file_ = Path(filepath)
return file_.is_file()
def if_dir_exists(filepath):
file_ = Path(filepath)
return file_.is_dir()
def get_name_from_url(url):
head, tail = ntpath.split(url)
params_index = tail.find("&")
if params_index != -1:
tail = tail[:params_index]
basename = ntpath.basename(url)
params_b_index = basename.find("&")
if params_b_index != -1:
basename = basename[:params_b_index]
return tail or basename
def get_name_from_url_no_ext(url):
path = get_name_from_url(url)
path_split = path.split(".")
if len(path_split) > 1:
name = ".".join(path_split[:-1])
else:
name = path_split[0]
return name
def build_path(levels):
path = os.path.join(*levels)
if not if_dir_exists(path):
os.makedirs(path)
return path
def remove_links(content):
if content is not None:
for link in content.find_all("a"):
link.replaceWithChildren()
def remove_iframes(content):
if content is not None:
for iframe in content.find_all("iframe"):
iframe.extract()
def check_shorter_url(url):
shorters_urls = set(["bitly.com", "goo.gl", "tinyurl.com", "ow.ly", "ls.gd",
"buff.ly", "adf.ly", "bit.do", "mcaf.ee"])
index_init = url.find("://")
index_end = url[index_init+3:].find("/")
if index_init != -1:
if index_end == -1:
index_end = len(url[index_init+3:])
domain = url[index_init+3:index_end+index_init+3]
check = len(domain) < 12 or domain in shorters_urls
return check
def get_level_map(tree, levels):
actual_node = levels[0]
r_levels = levels[1:]
for children in tree.get("children", []):
if children["source_id"] == actual_node:
if len(r_levels) >= 1:
return get_level_map(children, r_levels)
else:
return children
def load_tree(path):
with open(path, 'r') as f:
tree = json.load(f)
return tree
| [
"mara80@gmail.com"
] | mara80@gmail.com |
38c10450ce2fe46066550a1055d982809bfe65e5 | dce4a52986ddccea91fbf937bd89e0ae00b9d046 | /jni-build/jni-build/jni/include/tensorflow/contrib/learn/python/learn/supervised_session.py | 07d100fefc7ef511c3c0e0bcb5c3e968a87c760c | [
"MIT"
] | permissive | Lab603/PicEncyclopedias | 54a641b106b7bb2d2f71b2dacef1e5dbeaf773a6 | 6d39eeb66c63a6f0f7895befc588c9eb1dd105f9 | refs/heads/master | 2022-11-11T13:35:32.781340 | 2018-03-15T05:53:07 | 2018-03-15T05:53:07 | 103,941,664 | 6 | 3 | MIT | 2022-10-28T05:31:37 | 2017-09-18T13:20:47 | C++ | UTF-8 | Python | false | false | 13,917 | py | # Copyright 2016 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.
# ==============================================================================
"""Wrapper for a Session-like object that handles threads and recovery.
Based on an original design of Illia Polosukhin.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import inspect
from tensorflow.contrib.framework.python.ops import variables as contrib_variables
from tensorflow.contrib.learn.python.learn import coordinated_session
from tensorflow.contrib.learn.python.learn import monitored_session
from tensorflow.contrib.learn.python.learn import recoverable_session
from tensorflow.contrib.learn.python.learn import summary_writer_cache
from tensorflow.core.util.event_pb2 import SessionLog
from tensorflow.python.framework import errors
from tensorflow.python.framework import ops
from tensorflow.python.ops import control_flow_ops
from tensorflow.python.ops import data_flow_ops
from tensorflow.python.ops import logging_ops
from tensorflow.python.ops import variables
from tensorflow.python.training import coordinator
from tensorflow.python.training import queue_runner
from tensorflow.python.training import saver as training_saver
from tensorflow.python.training import session_manager as sm
from tensorflow.python.training import training_util
# TODO(touts): Share that with the Supervisor.
class Scaffold(object):
"""Structure to create or gather pieces commonly needed to train a model.
When you build a model for training you usually need ops to initialize
variables, a `Saver` to checkpoint them, an op to collect summaries for
the visualizer, and so on.
Various libraries built on top of the core TensorFlow library take care of
creating some or all of these pieces and storing them in well known
collections in the graph. The `Scaffold` class helps pick these pieces from
the graph collections, creating and adding them to the collections if needed.
If you call the scaffold constructor without any arguments it will pick
pieces from the collections, creating default ones if needed. You can pass
arguments to the constructor to provide your own pieces. Pieces that you
pass to the constructor are not added to the graph collections.
The following pieces are directly accessible as attributes of the `Scaffold`
object:
* `saver`: A `tf.Saver` object taking care of saving the variables. Picked
from and stored into the `SAVERS` collection in the graph.
* `init_op`: An op to run to initialize the variables. Picked from and
stored into the `INIT_OP` collection in the graph.
* `ready_op`: An op to verify that the variables are initialized. Picked
from and stored into the `READY_OP` collection in the graph.
* `local_init_op`: An op to initialize the local variables. Picked
from and stored into the `LOCAL_INIT_OP` collection in the graph.
* `summary_op`: An op to run and merge the summaries in the graph. Picked
from and stored into the `SUMMARY_OP` collection in the graph.
* `global_step`: A tensor containing the global step counter. Picked
from and stored into the `GLOBAL_STEP` collection in the graph.
You can also pass the following additional pieces to the constructor:
* `init_feed_dict`: A sessionn feed dictionary that should be used when
running the init op.
* `init_fn`: A callable to run run after the init op to perform additional
initializations. The callable will be called as
`init_fn(scaffold, session)`.
"""
# TODO(touts): consider adding the output dir and summary writer (cached)?
# TODO(touts): I do not think we should pass keep_checkpoint_max here.
# TODO(touts): Add individual static functions for init_op(), etc. that
# implement the caching logic.
def __init__(self,
global_step_tensor=None,
init_op=None,
init_feed_dict=None,
init_fn=None,
ready_op=None,
local_init_op=None,
summary_op=None,
saver=None,
keep_checkpoint_max=5):
"""Create a scaffold.
Args:
global_step_tensor: Optional tensor to use as the global step counter.
init_op: Optional op for initializing variables.
init_feed_dict: Optional session feed dictionary to use when running the
init_op.
init_fn: Optional function to use to initialize the model after running
the init_op. Will be called as `init_fn(scaffold, session)`.
ready_op: Optional op to verify that the variables are initialized. Must
return an empty scalar string tensor when the variables are
initialized, or a non-empty one listing the names of the
non-initialized variables.
local_init_op: Optional op to initialize local variables.
summary_op: Optional op to gather all summaries. Must return a scalar
string tensor containing a serialized `Summary` proto.
saver: Optional `tf.Saver` object to use to save and restore variables.
keep_checkpoint_max: Optional parameter to use to construct a saver if
none is already there in the graph.
"""
# NOTE(touts): modifying the init function to be passed the scaffold is a
# hack to make it easy to find the saver. Is there a better way?
if init_fn:
self._init_fn = lambda sess: init_fn(self, sess)
else:
self._init_fn = None
self._global_step_tensor = global_step_tensor
self._init_op = init_op
self._ready_op = ready_op
self._local_init_op = local_init_op
self._summary_op = summary_op
self._saver = saver
self._keep_checkpoint_max = keep_checkpoint_max
self._init_feed_dict = init_feed_dict
def finalize(self):
"""Creates operations if needed and finalizes the graph."""
if self._global_step_tensor is None:
self._global_step_tensor = contrib_variables.get_or_create_global_step()
if self._init_op is None:
self._init_op = Scaffold._get_or_default(
'init_op', ops.GraphKeys.INIT_OP, variables.initialize_all_variables)
if self._ready_op is None:
self._ready_op = Scaffold._get_or_default(
'ready_op', ops.GraphKeys.READY_OP,
variables.report_uninitialized_variables)
if self._local_init_op is None:
self._local_init_op = Scaffold._get_or_default(
'local_init_op', ops.GraphKeys.LOCAL_INIT_OP,
Scaffold._default_local_init_op)
if self._summary_op is None:
self._summary_op = Scaffold._get_or_default(
'summary_op', ops.GraphKeys.SUMMARY_OP,
logging_ops.merge_all_summaries)
# pylint: disable=g-long-lambda
if self._saver is None:
self._saver = Scaffold._get_or_default(
'saver',
ops.GraphKeys.SAVERS,
lambda: training_saver.Saver(sharded=True,
max_to_keep=self._keep_checkpoint_max))
# pylint: enable=g-long-lambda
ops.get_default_graph().finalize()
@property
def global_step_tensor(self):
return self._global_step_tensor
@property
def init_fn(self):
return self._init_fn
@property
def init_op(self):
return self._init_op
@property
def ready_op(self):
return self._ready_op
@property
def local_init_op(self):
return self._local_init_op
@property
def summary_op(self):
return self._summary_op
@property
def saver(self):
return self._saver
@property
def init_feed_dict(self):
return self._init_feed_dict
@staticmethod
def _get_or_default(arg_name, collection_key, default_constructor):
"""Get from cache or create a default operation."""
elements = ops.get_collection(collection_key)
if elements:
if len(elements) > 1:
raise RuntimeError('More than one item in the collection "%s". '
'Please indicate which one to use by passing it to '
'the tf.Scaffold constructor as: '
'tf.Scaffold(%s=item to use)', collection_key,
arg_name)
return elements[0]
op = default_constructor()
if op is not None:
ops.add_to_collection(collection_key, op)
return op
@staticmethod
def _default_local_init_op():
return control_flow_ops.group(variables.initialize_local_variables(),
data_flow_ops.initialize_all_tables())
def _call_monitor_end(monitor, sess):
# TODO(ispir): Remove following check when switch to MonitorV2
if 'session' in inspect.getargspec(monitor.end).args:
monitor.end(session=sess)
else:
monitor.end()
# TODO(ispir): Document this class after interface is finalized.
# mention StopIteration and OutOfRangeError
class SupervisedSession(object):
"""Session-like object that supports recovery and monitors.
"""
def __init__(self,
master,
is_chief=True,
checkpoint_dir=None,
monitors=None,
scaffold=None,
config=None):
self._graph = ops.get_default_graph()
self._master = master
self._checkpoint_dir = checkpoint_dir
self._is_chief = is_chief
self._config = config
self._monitors = monitors or []
self._scaffold = scaffold or Scaffold()
for monitor in self._monitors:
monitor.begin(max_steps=None)
# Create the session.
self._scaffold.finalize()
self._session_manager = sm.SessionManager(
local_init_op=self._scaffold.local_init_op,
ready_op=self._scaffold.ready_op,
graph=ops.get_default_graph())
self._sess = recoverable_session.RecoverableSession(self._create_session)
# Call the begin() method of monitors.
self._init_step = self._tf_sess.run(self._scaffold.global_step_tensor)
# Write the graph out, note: this uses self._init_step.
self.write_graph()
def _create_session(self):
"""Factory for the RecoverableSession.
Returns:
A session, initialized or recovered as needed.
"""
if self._is_chief:
tf_sess = self._session_manager.prepare_session(
self._master, saver=self._scaffold.saver,
checkpoint_dir=self._checkpoint_dir, config=self._config,
init_op=self._scaffold.init_op,
init_feed_dict=self._scaffold.init_feed_dict,
init_fn=self._scaffold.init_fn)
else:
tf_sess = self._session_manager.wait_for_session(
self._master, config=self._config)
# Keep the tf_sess for quick runs of global step when needed.
self._tf_sess = tf_sess
# We don't want coordinator to suppress any exception.
coord = coordinator.Coordinator(clean_stop_exception_types=[])
coordinated_threads_to_join = queue_runner.start_queue_runners(sess=tf_sess,
coord=coord)
return coordinated_session.CoordinatedSession(
monitored_session.MonitoredSession(tf_sess, self._monitors,
self._scaffold.global_step_tensor),
coord, coordinated_threads_to_join)
@property
def scaffold(self):
return self._scaffold
@property
def session(self):
return self._tf_sess
def run(self, fetches, feed_dict=None, options=None, run_metadata=None):
"""Run ops in the supervised session.
This method is completely compatible with the `tf.Session.run()` method.
Args:
fetches: Same as `tf.Session.run()`.
feed_dict: Same as `tf.Session.run()`.
options: Same as `tf.Session.run()`.
run_metadata: Same as `tf.Session.run()`.
Returns:
Same as `tf.Session.run()`.
"""
return self._sess.run(fetches, feed_dict=feed_dict, options=options,
run_metadata=run_metadata)
def should_stop(self):
if self._sess:
return self._sess.should_stop()
return True
def close(self):
self._close_internal()
def _close_internal(self, exception_type=None):
try:
if not exception_type:
for monitor in self._monitors:
_call_monitor_end(monitor, self._tf_sess)
finally:
self._sess.close()
self._sess = None
self._tf_sess = None
def _is_closed(self):
"""Return True if the supervised session is closed. For tests only.
Returns:
A boolean.
"""
return self._tf_sess is None
def __enter__(self):
return self
def __exit__(self, exception_type, exception_value, traceback):
if exception_type in [errors.OutOfRangeError, StopIteration]:
# TODO(ispir): log error if Coordinator hasn't done already.
exception_type = None
self._close_internal(exception_type)
# __exit__ should return True to suppress an exception.
return exception_type is None
def write_graph(self):
"""Saves current graph."""
if self._checkpoint_dir is not None and self._is_chief:
summary_writer = summary_writer_cache.SummaryWriterCache.get(
self._checkpoint_dir)
training_util.write_graph(self._graph.as_graph_def(add_shapes=True),
self._checkpoint_dir, 'graph.pbtxt')
summary_writer.add_graph(self._graph)
summary_writer.add_session_log(SessionLog(status=SessionLog.START),
self._init_step)
| [
"super_mr.z@hotmail.comm"
] | super_mr.z@hotmail.comm |
04e50d536e1fc6d75dbe209cfb08969375b7d392 | 453e245dcb67a75f671d5e6067af13c21acd4f97 | /3.3 Pipeline/3-Pipeline_train.py | b72d3e1f52e2289f6b821df35479cad4f159bdcf | [] | no_license | ahmedatef1610/scikit-learn-library-for-machine-learning | c828f7510cd9a7df41e7aece31c08ea00d69bb4f | f12be8c1702c413742328a75f60b9b1f78a3c2d3 | refs/heads/main | 2023-04-05T01:23:46.970931 | 2021-04-12T09:16:26 | 2021-04-12T09:16:26 | 356,732,567 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,514 | py | #imports
import pandas as pd
import math
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.linear_model import Ridge
from sklearn.linear_model import Lasso
from sklearn.metrics import mean_squared_error
from sklearn.preprocessing import PolynomialFeatures
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
#----------------------------------------------------
#import training dataset
train_df = pd.read_csv('path/3.3 Pipeline/train.csv', index_col='ID')
#see the columns in our data
print(train_df.info())
# take a look at the head of the dataset
print(train_df.head())
#create our X and y
X = train_df.drop('medv', axis=1)
y = train_df['medv']
print("="*50)
#----------------------------------------------------
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42, test_size=0.3)
#----------------------------------------------------
lr_model = LinearRegression()
lr_model.fit(X_train, y_train)
print('Training score: {}'.format(lr_model.score(X_train, y_train)))
print('Test score: {}'.format(lr_model.score(X_test, y_test)))
y_pred = lr_model.predict(X_test)
mse = mean_squared_error(y_test, y_pred)
rmse = math.sqrt(mse)
print('RMSE: {}'.format(rmse))
print("="*50)
#----------------------------------------------------
steps = [
('scalar', StandardScaler()),
('poly', PolynomialFeatures(degree=2)),
('model', LinearRegression())
]
pipeline = Pipeline(steps)
pipeline.fit(X_train, y_train)
print('Training score: {}'.format(pipeline.score(X_train, y_train)))
print('Test score: {}'.format(pipeline.score(X_test, y_test)))
print("="*50)
#----------------------------------------------------
steps = [
('scalar', StandardScaler()),
('poly', PolynomialFeatures(degree=2)),
('model', Ridge(alpha=10, fit_intercept=True))
]
ridge_pipe = Pipeline(steps)
ridge_pipe.fit(X_train, y_train)
print('Training Score: {}'.format(ridge_pipe.score(X_train, y_train)))
print('Test Score: {}'.format(ridge_pipe.score(X_test, y_test)))
print("="*50)
#----------------------------------------------------
steps = [
('scalar', StandardScaler()),
('poly', PolynomialFeatures(degree=2)),
('model', Lasso(alpha=0.3, fit_intercept=True))
]
lasso_pipe = Pipeline(steps)
lasso_pipe.fit(X_train, y_train)
print('Training score: {}'.format(lasso_pipe.score(X_train, y_train)))
print('Test score: {}'.format(lasso_pipe.score(X_test, y_test)))
print("="*50)
| [
"ahmedatef1610@gmail.com"
] | ahmedatef1610@gmail.com |
a8f7a520ad7f8d7cadc5fbc5369ce21c796ad8ae | bad62c2b0dfad33197db55b44efeec0bab405634 | /sdk/sql/azure-mgmt-sql/azure/mgmt/sql/aio/operations/_database_vulnerability_assessment_scans_operations.py | 4112e6483d86ee23aae404c1b1898b76d46f0a7a | [
"MIT",
"LicenseRef-scancode-generic-cla",
"LGPL-2.1-or-later"
] | permissive | test-repo-billy/azure-sdk-for-python | 20c5a2486456e02456de17515704cb064ff19833 | cece86a8548cb5f575e5419864d631673be0a244 | refs/heads/master | 2022-10-25T02:28:39.022559 | 2022-10-18T06:05:46 | 2022-10-18T06:05:46 | 182,325,031 | 0 | 0 | MIT | 2019-07-25T22:28:52 | 2019-04-19T20:59:15 | Python | UTF-8 | Python | false | false | 21,076 | py | # pylint: disable=too-many-lines
# 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 typing import Any, AsyncIterable, Callable, Dict, Optional, TypeVar, Union, cast
from azure.core.async_paging import AsyncItemPaged, AsyncList
from azure.core.exceptions import (
ClientAuthenticationError,
HttpResponseError,
ResourceExistsError,
ResourceNotFoundError,
ResourceNotModifiedError,
map_error,
)
from azure.core.pipeline import PipelineResponse
from azure.core.pipeline.transport import AsyncHttpResponse
from azure.core.polling import AsyncLROPoller, AsyncNoPolling, AsyncPollingMethod
from azure.core.rest import HttpRequest
from azure.core.tracing.decorator import distributed_trace
from azure.core.tracing.decorator_async import distributed_trace_async
from azure.core.utils import case_insensitive_dict
from azure.mgmt.core.exceptions import ARMErrorFormat
from azure.mgmt.core.polling.async_arm_polling import AsyncARMPolling
from ... import models as _models
from ..._vendor import _convert_request
from ...operations._database_vulnerability_assessment_scans_operations import (
build_export_request,
build_get_request,
build_initiate_scan_request,
build_list_by_database_request,
)
T = TypeVar("T")
ClsType = Optional[Callable[[PipelineResponse[HttpRequest, AsyncHttpResponse], T, Dict[str, Any]], Any]]
class DatabaseVulnerabilityAssessmentScansOperations:
"""
.. warning::
**DO NOT** instantiate this class directly.
Instead, you should access the following operations through
:class:`~azure.mgmt.sql.aio.SqlManagementClient`'s
:attr:`database_vulnerability_assessment_scans` attribute.
"""
models = _models
def __init__(self, *args, **kwargs) -> None:
input_args = list(args)
self._client = input_args.pop(0) if input_args else kwargs.pop("client")
self._config = input_args.pop(0) if input_args else kwargs.pop("config")
self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer")
self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer")
async def _initiate_scan_initial( # pylint: disable=inconsistent-return-statements
self,
resource_group_name: str,
server_name: str,
database_name: str,
vulnerability_assessment_name: Union[str, "_models.VulnerabilityAssessmentName"],
scan_id: str,
**kwargs: Any
) -> None:
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-11-01-preview")) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
request = build_initiate_scan_request(
resource_group_name=resource_group_name,
server_name=server_name,
database_name=database_name,
vulnerability_assessment_name=vulnerability_assessment_name,
scan_id=scan_id,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self._initiate_scan_initial.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 202]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
if cls:
return cls(pipeline_response, None, {})
_initiate_scan_initial.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}/vulnerabilityAssessments/{vulnerabilityAssessmentName}/scans/{scanId}/initiateScan"} # type: ignore
@distributed_trace_async
async def begin_initiate_scan(
self,
resource_group_name: str,
server_name: str,
database_name: str,
vulnerability_assessment_name: Union[str, "_models.VulnerabilityAssessmentName"],
scan_id: str,
**kwargs: Any
) -> AsyncLROPoller[None]:
"""Executes a Vulnerability Assessment database scan.
:param resource_group_name: The name of the resource group that contains the resource. You can
obtain this value from the Azure Resource Manager API or the portal. Required.
:type resource_group_name: str
:param server_name: The name of the server. Required.
:type server_name: str
:param database_name: The name of the database. Required.
:type database_name: str
:param vulnerability_assessment_name: The name of the vulnerability assessment. "default"
Required.
:type vulnerability_assessment_name: str or ~azure.mgmt.sql.models.VulnerabilityAssessmentName
:param scan_id: The vulnerability assessment scan Id of the scan to retrieve. Required.
:type scan_id: str
:keyword callable cls: A custom type or function that will be passed the direct response
:keyword str continuation_token: A continuation token to restart a poller from a saved state.
:keyword polling: By default, your polling method will be AsyncARMPolling. Pass in False for
this operation to not poll, or pass in your own initialized polling object for a personal
polling strategy.
:paramtype polling: bool or ~azure.core.polling.AsyncPollingMethod
:keyword int polling_interval: Default waiting time between two polls for LRO operations if no
Retry-After header is present.
:return: An instance of AsyncLROPoller that returns either None or the result of cls(response)
:rtype: ~azure.core.polling.AsyncLROPoller[None]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-11-01-preview")) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[None]
polling = kwargs.pop("polling", True) # type: Union[bool, AsyncPollingMethod]
lro_delay = kwargs.pop("polling_interval", self._config.polling_interval)
cont_token = kwargs.pop("continuation_token", None) # type: Optional[str]
if cont_token is None:
raw_result = await self._initiate_scan_initial( # type: ignore
resource_group_name=resource_group_name,
server_name=server_name,
database_name=database_name,
vulnerability_assessment_name=vulnerability_assessment_name,
scan_id=scan_id,
api_version=api_version,
cls=lambda x, y, z: x,
headers=_headers,
params=_params,
**kwargs
)
kwargs.pop("error_map", None)
def get_long_running_output(pipeline_response): # pylint: disable=inconsistent-return-statements
if cls:
return cls(pipeline_response, None, {})
if polling is True:
polling_method = cast(AsyncPollingMethod, AsyncARMPolling(lro_delay, **kwargs)) # type: AsyncPollingMethod
elif polling is False:
polling_method = cast(AsyncPollingMethod, AsyncNoPolling())
else:
polling_method = polling
if cont_token:
return AsyncLROPoller.from_continuation_token(
polling_method=polling_method,
continuation_token=cont_token,
client=self._client,
deserialization_callback=get_long_running_output,
)
return AsyncLROPoller(self._client, raw_result, get_long_running_output, polling_method)
begin_initiate_scan.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}/vulnerabilityAssessments/{vulnerabilityAssessmentName}/scans/{scanId}/initiateScan"} # type: ignore
@distributed_trace
def list_by_database(
self,
resource_group_name: str,
server_name: str,
database_name: str,
vulnerability_assessment_name: Union[str, "_models.VulnerabilityAssessmentName"],
**kwargs: Any
) -> AsyncIterable["_models.VulnerabilityAssessmentScanRecord"]:
"""Lists the vulnerability assessment scans of a database.
:param resource_group_name: The name of the resource group that contains the resource. You can
obtain this value from the Azure Resource Manager API or the portal. Required.
:type resource_group_name: str
:param server_name: The name of the server. Required.
:type server_name: str
:param database_name: The name of the database. Required.
:type database_name: str
:param vulnerability_assessment_name: The name of the vulnerability assessment. "default"
Required.
:type vulnerability_assessment_name: str or ~azure.mgmt.sql.models.VulnerabilityAssessmentName
:keyword callable cls: A custom type or function that will be passed the direct response
:return: An iterator like instance of either VulnerabilityAssessmentScanRecord or the result of
cls(response)
:rtype:
~azure.core.async_paging.AsyncItemPaged[~azure.mgmt.sql.models.VulnerabilityAssessmentScanRecord]
:raises ~azure.core.exceptions.HttpResponseError:
"""
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-11-01-preview")) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.VulnerabilityAssessmentScanRecordListResult]
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
def prepare_request(next_link=None):
if not next_link:
request = build_list_by_database_request(
resource_group_name=resource_group_name,
server_name=server_name,
database_name=database_name,
vulnerability_assessment_name=vulnerability_assessment_name,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.list_by_database.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
else:
request = HttpRequest("GET", next_link)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
request.method = "GET"
return request
async def extract_data(pipeline_response):
deserialized = self._deserialize("VulnerabilityAssessmentScanRecordListResult", pipeline_response)
list_of_elem = deserialized.value
if cls:
list_of_elem = cls(list_of_elem)
return deserialized.next_link or None, AsyncList(list_of_elem)
async def get_next(next_link=None):
request = prepare_request(next_link)
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
return pipeline_response
return AsyncItemPaged(get_next, extract_data)
list_by_database.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}/vulnerabilityAssessments/{vulnerabilityAssessmentName}/scans"} # type: ignore
@distributed_trace_async
async def get(
self,
resource_group_name: str,
server_name: str,
database_name: str,
vulnerability_assessment_name: Union[str, "_models.VulnerabilityAssessmentName"],
scan_id: str,
**kwargs: Any
) -> _models.VulnerabilityAssessmentScanRecord:
"""Gets a vulnerability assessment scan record of a database.
:param resource_group_name: The name of the resource group that contains the resource. You can
obtain this value from the Azure Resource Manager API or the portal. Required.
:type resource_group_name: str
:param server_name: The name of the server. Required.
:type server_name: str
:param database_name: The name of the database. Required.
:type database_name: str
:param vulnerability_assessment_name: The name of the vulnerability assessment. "default"
Required.
:type vulnerability_assessment_name: str or ~azure.mgmt.sql.models.VulnerabilityAssessmentName
:param scan_id: The vulnerability assessment scan Id of the scan to retrieve. Required.
:type scan_id: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: VulnerabilityAssessmentScanRecord or the result of cls(response)
:rtype: ~azure.mgmt.sql.models.VulnerabilityAssessmentScanRecord
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-11-01-preview")) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.VulnerabilityAssessmentScanRecord]
request = build_get_request(
resource_group_name=resource_group_name,
server_name=server_name,
database_name=database_name,
vulnerability_assessment_name=vulnerability_assessment_name,
scan_id=scan_id,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.get.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
deserialized = self._deserialize("VulnerabilityAssessmentScanRecord", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
get.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}/vulnerabilityAssessments/{vulnerabilityAssessmentName}/scans/{scanId}"} # type: ignore
@distributed_trace_async
async def export(
self,
resource_group_name: str,
server_name: str,
database_name: str,
vulnerability_assessment_name: Union[str, "_models.VulnerabilityAssessmentName"],
scan_id: str,
**kwargs: Any
) -> _models.DatabaseVulnerabilityAssessmentScansExport:
"""Convert an existing scan result to a human readable format. If already exists nothing happens.
:param resource_group_name: The name of the resource group that contains the resource. You can
obtain this value from the Azure Resource Manager API or the portal. Required.
:type resource_group_name: str
:param server_name: The name of the server. Required.
:type server_name: str
:param database_name: The name of the scanned database. Required.
:type database_name: str
:param vulnerability_assessment_name: The name of the vulnerability assessment. "default"
Required.
:type vulnerability_assessment_name: str or ~azure.mgmt.sql.models.VulnerabilityAssessmentName
:param scan_id: The vulnerability assessment scan Id. Required.
:type scan_id: str
:keyword callable cls: A custom type or function that will be passed the direct response
:return: DatabaseVulnerabilityAssessmentScansExport or the result of cls(response)
:rtype: ~azure.mgmt.sql.models.DatabaseVulnerabilityAssessmentScansExport
:raises ~azure.core.exceptions.HttpResponseError:
"""
error_map = {
401: ClientAuthenticationError,
404: ResourceNotFoundError,
409: ResourceExistsError,
304: ResourceNotModifiedError,
}
error_map.update(kwargs.pop("error_map", {}) or {})
_headers = kwargs.pop("headers", {}) or {}
_params = case_insensitive_dict(kwargs.pop("params", {}) or {})
api_version = kwargs.pop("api_version", _params.pop("api-version", "2020-11-01-preview")) # type: str
cls = kwargs.pop("cls", None) # type: ClsType[_models.DatabaseVulnerabilityAssessmentScansExport]
request = build_export_request(
resource_group_name=resource_group_name,
server_name=server_name,
database_name=database_name,
vulnerability_assessment_name=vulnerability_assessment_name,
scan_id=scan_id,
subscription_id=self._config.subscription_id,
api_version=api_version,
template_url=self.export.metadata["url"],
headers=_headers,
params=_params,
)
request = _convert_request(request)
request.url = self._client.format_url(request.url) # type: ignore
pipeline_response = await self._client._pipeline.run( # type: ignore # pylint: disable=protected-access
request, stream=False, **kwargs
)
response = pipeline_response.http_response
if response.status_code not in [200, 201]:
map_error(status_code=response.status_code, response=response, error_map=error_map)
raise HttpResponseError(response=response, error_format=ARMErrorFormat)
if response.status_code == 200:
deserialized = self._deserialize("DatabaseVulnerabilityAssessmentScansExport", pipeline_response)
if response.status_code == 201:
deserialized = self._deserialize("DatabaseVulnerabilityAssessmentScansExport", pipeline_response)
if cls:
return cls(pipeline_response, deserialized, {})
return deserialized
export.metadata = {"url": "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}/vulnerabilityAssessments/{vulnerabilityAssessmentName}/scans/{scanId}/export"} # type: ignore
| [
"noreply@github.com"
] | test-repo-billy.noreply@github.com |
b7fb19e89546027400e590c2391e345744d9ed9f | c5157ce2aa61f46c3cc9e028e347587e1fb1669c | /gui/python/resistor/resistor.py | ae31903c80ac9c0f122b5955445e86834fb5c12b | [] | no_license | ramalho/atelier-labs | 2617706121fe9d67b646037e24a01380fa2ed53a | 57986c9a7cd20046f58885a0b75cb12ce3b57f16 | refs/heads/master | 2018-12-29T07:02:24.517423 | 2012-05-21T15:00:06 | 2012-05-21T15:00:06 | 4,394,443 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,577 | py |
'''
Source for color table:
http://en.wikipedia.org/wiki/Electronic_color_code
'''
COLORS = 'black brown red orange yellow green blue violet gray white'.split()
TOLERANCE = {
'brown':1, 'red':2,
'green':0.5, 'blue':0.25, 'violet':0.1, 'gray':0.05,
'gold':5, 'silver':10} #, None:20}
def identify(bands):
digits = []
for band in bands[:-2]: # all bands except last 2
digit = COLORS.index(band)
digits.append(str(digit))
digits = int(''.join(digits))
multiplier = COLORS.index(bands[-2]) # the band before last
value = digits * (10 ** multiplier)
tolerance = TOLERANCE.get(bands[-1],'unknown color') # last band
return '%s Ohms, %s%% tolerance' % (value, tolerance)
def self_test():
'''
Source for examples:
http://www.arar93.dsl.pipex.com/mds975/Content/components01.html
'''
# 4 bands
print identify('brown black brown silver'.split())
print identify('yellow violet red gold'.split())
print identify('orange orange yellow silver'.split())
# 5 bands
print identify('brown black black black silver'.split())
print identify('yellow violet black brown gold'.split())
print identify('orange orange black orange silver'.split())
def main():
from sys import argv
colors = argv[1:] # skip script name (argv[0])
if len(colors) in [4,5]:
print identify(colors)
else:
print 'usage:'
print argv[0], 'color1 color2 color3 color4 [color5]'
if __name__=='__main__':
# self_test()
main()
| [
"luciano@ramalho.org"
] | luciano@ramalho.org |
586739cc93832f34ce8cea5c5d8da2b31592e79d | 4640123092be222413fa233f09aa167d470de46c | /backend/home/migrations/0002_customtext_homepage.py | 067d3cd154523bff76fbb9dfd2c02c758968fed6 | [] | no_license | crowdbotics-apps/teste-27867 | 8ca166788cbd5aa90844d1953f0ad9a24910492c | df35af7b664cb3e2053f7a36c8c49268c681fe8b | refs/heads/master | 2023-05-18T21:34:38.469264 | 2021-06-09T14:06:19 | 2021-06-09T14:06:19 | 375,248,524 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 805 | py | # Generated by Django 2.2.20 on 2021-06-09 14:06
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
('home', '0001_load_initial_data'),
]
operations = [
migrations.CreateModel(
name='CustomText',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=150)),
],
),
migrations.CreateModel(
name='HomePage',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('body', models.TextField()),
],
),
]
| [
"team@crowdbotics.com"
] | team@crowdbotics.com |
af5df5ff93860818117097f576bf7e0bba351909 | 7da5ac719e4c9ca9cb3735d0ade3106183d96ffe | /Projeto/IoTcity_services/server/server/mainserver/migrations/0011_auto_20170326_1126.py | 4495c2e03d5bda1dd2675a88eac680e3756c4a3d | [] | no_license | shanexia1818/IoTCity | a405c0921b417e5bb0a61966f9ca03a1f87147a7 | 3fe14b6918275684291f969fd6c3f69a7ee14a4c | refs/heads/master | 2020-08-07T21:08:38.811470 | 2018-09-10T11:10:56 | 2018-09-10T11:10:56 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 691 | py | # -*- coding: utf-8 -*-
# Generated by Django 1.10 on 2017-03-26 11:26
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('mainserver', '0010_auto_20170326_1121'),
]
operations = [
migrations.AlterField(
model_name='alarm',
name='daysOfWeek',
field=models.ManyToManyField(blank=True, null=True, to='mainserver.day_week'),
),
migrations.AlterField(
model_name='alarm',
name='daysOfYear',
field=models.ManyToManyField(blank=True, null=True, to='mainserver.day_year'),
),
]
| [
"diogodanielsoaresferreira@ua.pt"
] | diogodanielsoaresferreira@ua.pt |
07bb3c5808d3f623a80fedb01254af988f185238 | dc67e70a303f265ee6cb4c1a2d61fe811053fb3d | /selection/product.py | de869f2e3445ce58bb4a1a06dc228759fec30dc1 | [] | no_license | cry999/AtCoder | d39ce22d49dfce805cb7bab9d1ff0dd21825823a | 879d0e43e3fac0aadc4d772dc57374ae72571fe6 | refs/heads/master | 2020-04-23T13:55:00.018156 | 2019-12-11T05:23:03 | 2019-12-11T05:23:03 | 171,214,066 | 0 | 0 | null | 2019-05-13T15:17:02 | 2019-02-18T04:24:01 | Python | UTF-8 | Python | false | false | 208 | py | def product(a: int, b: int) -> str:
p = a * b
return 'Even' if (p & 1) == 0 else 'Odd'
if __name__ == "__main__":
a, b = [int(s) for s in input().split()]
ans = product(a, b)
print(ans)
| [
"when.the.cry999@gmail.com"
] | when.the.cry999@gmail.com |
832af04f8bc176b508217819c0cbdbd290cf40b8 | 53fab060fa262e5d5026e0807d93c75fb81e67b9 | /backup/user_211/ch18_2020_03_15_15_02_54_971317.py | 5eba77fe63b13d26a8ca9bcedc6e427e50869e23 | [] | 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 | 171 | py | def verifica_idade(x):
if x>=21:
return 'Liberado EUA e BRASI'
elif x>=18:
return 'Liberado BRASIL'
else:
return 'Não está liberado'
| [
"you@example.com"
] | you@example.com |
83575457e3e658ca944654ab7e19947978f37d5a | 48a1156c4226a22be2cf271149be263adf9e5aef | /deploy/conf/web/gunicorn.conf.py | 719128c5cfafd05900bb0b3f2a57be46021c2ac5 | [
"MIT"
] | permissive | yacoma/auth-boilerplate | 945edb1174ab6009780a50a51ec2389bc12845a3 | 26c86f3b12edc7074a2fd78322e6005fdb1029cb | refs/heads/master | 2021-01-12T01:18:33.584773 | 2020-05-07T15:00:01 | 2020-05-07T15:00:01 | 78,362,662 | 6 | 1 | null | 2017-01-30T20:46:05 | 2017-01-08T18:36:46 | JavaScript | UTF-8 | Python | false | false | 178 | py | import multiprocessing
bind = "unix:/tmp/proxy_auth-boilerplate.yacoma.it.sock"
workers = multiprocessing.cpu_count() * 2 + 1
forwarded_allow_ips = "127.0.0.1, 188.165.237.135"
| [
"henri.hulski@gazeta.pl"
] | henri.hulski@gazeta.pl |
83c9631bd86714b665acd2c59700bdd2514e6d14 | 3920ab5c8deeaee370e6d28793fd7f2a9ca51188 | /jarbas/core/migrations/0012_use_date_not_datetime.py | e34719f67393411d12ed109e7ad9ec4829ae7e95 | [
"MIT"
] | permissive | MSLacerda/serenata-de-amor | 1fe5309ef3ba76f6f9f7d16986730fe96c0f0991 | 789586d8dea3768502ac7f2d5e333cf0692642ac | refs/heads/master | 2020-03-15T17:57:39.301809 | 2018-10-08T11:50:07 | 2018-10-08T11:50:07 | 132,273,013 | 2 | 0 | MIT | 2018-10-08T11:50:08 | 2018-05-05T18:12:13 | Python | UTF-8 | Python | false | false | 498 | py | # -*- coding: utf-8 -*-
# Generated by Django 1.10.3 on 2016-11-25 15:10
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('core', '0011_subquota_description_length'),
]
operations = [
migrations.AlterField(
model_name='document',
name='issue_date',
field=models.DateField(blank=True, null=True, verbose_name='Issue date'),
),
]
| [
"cuducos@gmail.com"
] | cuducos@gmail.com |
bfce843a80276eacca751eb4fbf2dfd3f9d62c1c | b8e92c8c672ce620390dc09d782db73baa09c8b9 | /app/remote_code_execution_engine/schemas/evaluation.py | aa896051996ccc61c1a4d6eb3006438ca9997acd | [
"MIT"
] | permissive | GeorgianBadita/remote-code-execution-engine | 8bf590d697c4e808b933f3b7010b57e8ee1161de | 4ac3ca7567cd89cc1f979622add81efa9edfea8f | refs/heads/main | 2023-03-01T02:55:20.285861 | 2021-02-07T01:10:53 | 2021-02-07T01:10:53 | 332,325,012 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 249 | py | from typing import List
from pydantic import BaseModel
class EvaluationResult(BaseModel):
submission_id: str
has_error: bool
results: List[bool]
out_of_resources: bool
out_of_time: bool
exit_code: int
raw_output: str
| [
"geo.badita@gmail.com"
] | geo.badita@gmail.com |
c23dd238375963e81a15419ebcf305bca0ac0e7c | 531a1714bc78e215308978b9536437f8e3dab2be | /tests/test_imports.py | 3235582dfbc8e29a7ea292cbccbc9c175eb2c758 | [
"MIT"
] | permissive | samirelanduk/geometrica | 6194d67bb73974028398eca02d9983bac4a1d23c | 322cc2fd52dee21b8ac2b10e45d5cf0bf7034e64 | refs/heads/master | 2021-01-21T05:17:07.131581 | 2017-05-13T11:33:12 | 2017-05-13T11:33:12 | 83,167,131 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 701 | py | from unittest import TestCase
import geometrica
class TrigFunctionsImportTests(TestCase):
def test_sine_law_imported(self):
from geometrica.trig import sine_law
self.assertIs(sine_law, geometrica.sine_law)
def test_cosine_law_imported(self):
from geometrica.trig import cosine_law
self.assertIs(cosine_law, geometrica.cosine_law)
class TransformationImportTests(TestCase):
def test_translate_imported(self):
from geometrica.transform import translate
self.assertIs(translate, geometrica.translate)
def test_rotate_imported(self):
from geometrica.transform import rotate
self.assertIs(rotate, geometrica.rotate)
| [
"sam.ireland.uk@gmail.com"
] | sam.ireland.uk@gmail.com |
f042cae327b157b337ea7090e4c0f42a846d3a24 | ca7aa979e7059467e158830b76673f5b77a0f5a3 | /Python_codes/p03425/s982174788.py | 01f4ca7a93c6a1d56f1486e0fe88f23e34b32345 | [] | 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 | 506 | py | import sys
input = sys.stdin.readline
def main():
N = int(input())
L = {'M':0, 'A':0, 'R':0, 'C':0, 'H':0}
for i in range(N):
S = input().rstrip()
if S[0] in L:
L[S[0]] += 1
CNT = 0
i = 0
S = [0]*5
for k, v in L.items():
S[i] = v
i += 1
ans = 0
for p in range(3):
for q in range(p+1,4):
for r in range(q+1,5):
ans += S[p]*S[q]*S[r]
print(ans)
if __name__ == '__main__':
main() | [
"66529651+Aastha2104@users.noreply.github.com"
] | 66529651+Aastha2104@users.noreply.github.com |
6d4b31b6792f7453764518008cccfb8c64313f41 | 26fdd3419c1855f180d7e9bea3b59459ba9e6446 | /venv/lib/python3.6/site-packages/oauthlib/openid/connect/core/grant_types/base.py | fa578a5732039e040b865b71daab07f142e0401d | [] | permissive | vansh1999/fashion-ecomm | eed52884ac007928260f50a885bec963d85a88d2 | 5879d0b1c64411485e861dfc9bcca6b4a82afc57 | refs/heads/master | 2021-06-24T21:58:26.931849 | 2021-04-10T08:37:50 | 2021-04-10T08:37:50 | 219,543,353 | 1 | 0 | Apache-2.0 | 2021-04-10T08:37:51 | 2019-11-04T16:14:06 | Python | UTF-8 | Python | false | false | 13,864 | py | from .exceptions import OIDCNoPrompt
import datetime
import logging
from json import loads
from oauthlib.oauth2.rfc6749.errors import ConsentRequired, InvalidRequestError, LoginRequired
log = logging.getLogger(__name__)
class GrantTypeBase(object):
# Just proxy the majority of method calls through to the
# proxy_target grant type handler, which will usually be either
# the standard OAuth2 AuthCode or Implicit grant types.
def __getattr__(self, attr):
return getattr(self.proxy_target, attr)
def __setattr__(self, attr, value):
proxied_attrs = set(('refresh_token', 'response_types'))
if attr in proxied_attrs:
setattr(self.proxy_target, attr, value)
else:
super(OpenIDConnectBase, self).__setattr__(attr, value)
def validate_authorization_request(self, request):
"""Validates the OpenID Connect authorization request parameters.
:returns: (list of scopes, dict of request info)
"""
# If request.prompt is 'none' then no login/authorization form should
# be presented to the user. Instead, a silent login/authorization
# should be performed.
if request.prompt == 'none':
raise OIDCNoPrompt()
else:
return self.proxy_target.validate_authorization_request(request)
def _inflate_claims(self, request):
# this may be called multiple times in a single request so make sure we only de-serialize the claims once
if request.claims and not isinstance(request.claims, dict):
# specific claims are requested during the Authorization Request and may be requested for inclusion
# in either the id_token or the UserInfo endpoint response
# see http://openid.net/specs/openid-connect-core-1_0.html#ClaimsParameter
try:
request.claims = loads(request.claims)
except Exception as ex:
raise InvalidRequestError(description="Malformed claims parameter",
uri="http://openid.net/specs/openid-connect-core-1_0.html#ClaimsParameter")
def add_id_token(self, token, token_handler, request):
# Treat it as normal OAuth 2 auth code request if openid is not present
if not request.scopes or 'openid' not in request.scopes:
return token
# Only add an id token on auth/token step if asked for.
if request.response_type and 'id_token' not in request.response_type:
return token
if 'state' not in token:
token['state'] = request.state
if request.max_age:
d = datetime.datetime.utcnow()
token['auth_time'] = d.isoformat("T") + "Z"
# TODO: acr claims (probably better handled by server code using oauthlib in get_id_token)
token['id_token'] = self.request_validator.get_id_token(token, token_handler, request)
return token
def openid_authorization_validator(self, request):
"""Perform OpenID Connect specific authorization request validation.
nonce
OPTIONAL. String value used to associate a Client session with
an ID Token, and to mitigate replay attacks. The value is
passed through unmodified from the Authentication Request to
the ID Token. Sufficient entropy MUST be present in the nonce
values used to prevent attackers from guessing values
display
OPTIONAL. ASCII string value that specifies how the
Authorization Server displays the authentication and consent
user interface pages to the End-User. The defined values are:
page - The Authorization Server SHOULD display the
authentication and consent UI consistent with a full User
Agent page view. If the display parameter is not specified,
this is the default display mode.
popup - The Authorization Server SHOULD display the
authentication and consent UI consistent with a popup User
Agent window. The popup User Agent window should be of an
appropriate size for a login-focused dialog and should not
obscure the entire window that it is popping up over.
touch - The Authorization Server SHOULD display the
authentication and consent UI consistent with a device that
leverages a touch interface.
wap - The Authorization Server SHOULD display the
authentication and consent UI consistent with a "feature
phone" type display.
The Authorization Server MAY also attempt to detect the
capabilities of the User Agent and present an appropriate
display.
prompt
OPTIONAL. Space delimited, case sensitive list of ASCII string
values that specifies whether the Authorization Server prompts
the End-User for reauthentication and consent. The defined
values are:
none - The Authorization Server MUST NOT display any
authentication or consent user interface pages. An error is
returned if an End-User is not already authenticated or the
Client does not have pre-configured consent for the
requested Claims or does not fulfill other conditions for
processing the request. The error code will typically be
login_required, interaction_required, or another code
defined in Section 3.1.2.6. This can be used as a method to
check for existing authentication and/or consent.
login - The Authorization Server SHOULD prompt the End-User
for reauthentication. If it cannot reauthenticate the
End-User, it MUST return an error, typically
login_required.
consent - The Authorization Server SHOULD prompt the
End-User for consent before returning information to the
Client. If it cannot obtain consent, it MUST return an
error, typically consent_required.
select_account - The Authorization Server SHOULD prompt the
End-User to select a user account. This enables an End-User
who has multiple accounts at the Authorization Server to
select amongst the multiple accounts that they might have
current sessions for. If it cannot obtain an account
selection choice made by the End-User, it MUST return an
error, typically account_selection_required.
The prompt parameter can be used by the Client to make sure
that the End-User is still present for the current session or
to bring attention to the request. If this parameter contains
none with any other value, an error is returned.
max_age
OPTIONAL. Maximum Authentication Age. Specifies the allowable
elapsed time in seconds since the last time the End-User was
actively authenticated by the OP. If the elapsed time is
greater than this value, the OP MUST attempt to actively
re-authenticate the End-User. (The max_age request parameter
corresponds to the OpenID 2.0 PAPE [OpenID.PAPE] max_auth_age
request parameter.) When max_age is used, the ID Token returned
MUST include an auth_time Claim Value.
ui_locales
OPTIONAL. End-User's preferred languages and scripts for the
user interface, represented as a space-separated list of BCP47
[RFC5646] language tag values, ordered by preference. For
instance, the value "fr-CA fr en" represents a preference for
French as spoken in Canada, then French (without a region
designation), followed by English (without a region
designation). An error SHOULD NOT result if some or all of the
requested locales are not supported by the OpenID Provider.
id_token_hint
OPTIONAL. ID Token previously issued by the Authorization
Server being passed as a hint about the End-User's current or
past authenticated session with the Client. If the End-User
identified by the ID Token is logged in or is logged in by the
request, then the Authorization Server returns a positive
response; otherwise, it SHOULD return an error, such as
login_required. When possible, an id_token_hint SHOULD be
present when prompt=none is used and an invalid_request error
MAY be returned if it is not; however, the server SHOULD
respond successfully when possible, even if it is not present.
The Authorization Server need not be listed as an audience of
the ID Token when it is used as an id_token_hint value. If the
ID Token received by the RP from the OP is encrypted, to use it
as an id_token_hint, the Client MUST decrypt the signed ID
Token contained within the encrypted ID Token. The Client MAY
re-encrypt the signed ID token to the Authentication Server
using a key that enables the server to decrypt the ID Token,
and use the re-encrypted ID token as the id_token_hint value.
login_hint
OPTIONAL. Hint to the Authorization Server about the login
identifier the End-User might use to log in (if necessary).
This hint can be used by an RP if it first asks the End-User
for their e-mail address (or other identifier) and then wants
to pass that value as a hint to the discovered authorization
service. It is RECOMMENDED that the hint value match the value
used for discovery. This value MAY also be a phone number in
the format specified for the phone_number Claim. The use of
this parameter is left to the OP's discretion.
acr_values
OPTIONAL. Requested Authentication Context Class Reference
values. Space-separated string that specifies the acr values
that the Authorization Server is being requested to use for
processing this Authentication Request, with the values
appearing in order of preference. The Authentication Context
Class satisfied by the authentication performed is returned as
the acr Claim Value, as specified in Section 2. The acr Claim
is requested as a Voluntary Claim by this parameter.
"""
# Treat it as normal OAuth 2 auth code request if openid is not present
if not request.scopes or 'openid' not in request.scopes:
return {}
prompt = request.prompt if request.prompt else []
if hasattr(prompt, 'split'):
prompt = prompt.strip().split()
prompt = set(prompt)
if 'none' in prompt:
if len(prompt) > 1:
msg = "Prompt none is mutually exclusive with other values."
raise InvalidRequestError(request=request, description=msg)
if not self.request_validator.validate_silent_login(request):
raise LoginRequired(request=request)
if not self.request_validator.validate_silent_authorization(request):
raise ConsentRequired(request=request)
self._inflate_claims(request)
if not self.request_validator.validate_user_match(
request.id_token_hint, request.scopes, request.claims, request):
msg = "Session user does not match client supplied user."
raise LoginRequired(request=request, description=msg)
request_info = {
'display': request.display,
'nonce': request.nonce,
'prompt': prompt,
'ui_locales': request.ui_locales.split() if request.ui_locales else [],
'id_token_hint': request.id_token_hint,
'login_hint': request.login_hint,
'claims': request.claims
}
return request_info
def openid_implicit_authorization_validator(self, request):
"""Additional validation when following the implicit flow.
"""
# Undefined in OpenID Connect, fall back to OAuth2 definition.
if request.response_type == 'token':
return {}
# Treat it as normal OAuth 2 auth code request if openid is not present
if not request.scopes or 'openid' not in request.scopes:
return {}
# REQUIRED. String value used to associate a Client session with an ID
# Token, and to mitigate replay attacks. The value is passed through
# unmodified from the Authentication Request to the ID Token.
# Sufficient entropy MUST be present in the nonce values used to
# prevent attackers from guessing values. For implementation notes, see
# Section 15.5.2.
if not request.nonce:
desc = 'Request is missing mandatory nonce parameter.'
raise InvalidRequestError(request=request, description=desc)
return {}
OpenIDConnectBase = GrantTypeBase
| [
"vansh.bhardwaj1999@gmail.com"
] | vansh.bhardwaj1999@gmail.com |
a489cc57803f9c4a97aeeb490d09df2f1c91c71e | 2f98aa7e5bfc2fc5ef25e4d5cfa1d7802e3a7fae | /python/python_7684.py | d8a6e7b7c0cb331010f13e2eb2d4b7a16a430928 | [] | no_license | AK-1121/code_extraction | cc812b6832b112e3ffcc2bb7eb4237fd85c88c01 | 5297a4a3aab3bb37efa24a89636935da04a1f8b6 | refs/heads/master | 2020-05-23T08:04:11.789141 | 2015-10-22T19:19:40 | 2015-10-22T19:19:40 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 127 | py | # Force python to not output a float in standard form / scientific notation / exponential form
print '{0:.10f}'.format(1.0e-9)
| [
"ubuntu@ip-172-31-7-228.us-west-2.compute.internal"
] | ubuntu@ip-172-31-7-228.us-west-2.compute.internal |
c0dc054906d0ea98a80d0b8cf0dc3c4d8801327b | 958685165bfeb4122cc3473659a6d0c89c5cae95 | /crea8s_rental/__init__.py | 0c3addd67685eee41e9ce6025111b000ef3dfdcc | [] | no_license | tringuyen17588/OpenERP-7.0 | 44efee7735af65d960c5adb4b03a1a329f5c4a57 | 2486261e4d351d4f444ec31e74c6b0e36ed2fb82 | refs/heads/master | 2021-01-10T02:45:24.320726 | 2016-02-19T06:05:21 | 2016-02-19T06:05:21 | 52,064,852 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,115 | py | # -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
#----------------------------------------------------------
#
#----------------------------------------------------------
import rental | [
"tri@crea8s.com"
] | tri@crea8s.com |
ec4e081afdb3147dd063ec36ddbbe72f3b0b469f | c3432a248c8a7a43425c0fe1691557c0936ab380 | /이것이_코딩테스트다_Book/알고리즘_유형별_기출문제/그리디문제/문자열_뒤집기.py | 33667852daacb3ae2fbf746b9e3e46275f51762c | [] | no_license | Parkyunhwan/BaekJoon | 13cb3af1f45212d7c418ecc4b927f42615b14a74 | 9a882c568f991c9fed3df45277f091626fcc2c94 | refs/heads/master | 2022-12-24T21:47:47.052967 | 2022-12-20T16:16:59 | 2022-12-20T16:16:59 | 232,264,447 | 3 | 0 | null | null | null | null | UTF-8 | Python | false | false | 194 | py | arr = list(input())
arr = [int(i) for i in arr]
prev = arr[0]
count = [0]*2
for a in arr:
if prev != a:
count[prev] += 1
prev = a
count[prev] += 1
print(min(count[0], count[1])) | [
"pyh8618@gmail.com"
] | pyh8618@gmail.com |
e2a476e8cea308b2437c174320358f74693af7b0 | 91c5a1865717e6757bbfec825d411f96dcf2e2e5 | /python/11_test/11.1/test_name_function.py | 3ec1f8804cd2f5da58ac67995a1b91dee886c1cb | [] | no_license | ydPro-G/Python_file | 6f676d1b66e21548f5fad8a715a1767344c2b0c4 | c035e7c344c3c224d55e33efc16ee941bc3d6ff2 | refs/heads/master | 2023-06-19T06:12:44.550778 | 2021-07-14T09:15:15 | 2021-07-14T09:15:15 | 261,126,468 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,921 | py | # 11 测试函数
print("\n11.1.1")
# 11.1.1 单元测试和测试用例
# 标准库中的模块unittest提供了代码测试工具
# 单元测试用于核实函数的某个方面没有问题
# 测试用例是一组单元测试,这些单元测试一起核实函数在各种情况下的行为都符合要求
# 全覆盖测试包含一整套单元测试
print('\n11.1.2')
# 可通过测试
# 导入模块unittest以及要测试的函数
# 创建一个继承unittest。TestCase的类,编写方法对函数行为不同方面进行测试
# 检查函数get_formatted_name()在给定名和姓时能否正常工作
# 导入模块unittest
# import unittest
# # 导入要测试的函数 get_formatted_name()
# from name_function import get_formatted_name
# # 编写一个类,用于包含针对函数的单元测试,类必须继承unittest.TestCase类
# class NamesTestCase(unittest.TestCase):
# """测试name_function.py"""
# def test_first_last_name(self):
# """能够正确处理像Janis Joplin这样的姓名吗?"""
# formatted_name = get_formatted_name('janis','joplin') # 调用要测试的函数,将结果存储到变量中
# self.assertEqual(formatted_name,'Janis Jopiln') # 断言方法[断言:相等]:调用了断言方法,并向它传递变量与预期要实现的结果,对变量与结果进行比较,如果相等就ok,不相等就报异常
# unittest.main()
print('\n11.1.3')
# 11.1.3 不能通过的测试
# 会报一个traceback(回溯),指出get_formatted_name有问题,缺少一个必要的位置实参
print('\n11.1.4')
# 11.1.4 测试未通过怎么办
# 检查刚对函数做出的修改,找出导致函数行为不符合预期的修改
print('\n11.1.5')
# 11.1.5 新测试
# 用于测试包含中间名的名字
# 在NamesTestCase类中添加一个新方法
import unittest
# 导入要测试的函数 get_formatted_name()
from name_function import get_formatted_name
# 编写一个类,用于包含针对函数的单元测试,类必须继承unittest.TestCase类
class NamesTestCase(unittest.TestCase):
"""测试name_function.py"""
def test_first_last_name(self):
"""能够正确处理像Janis Joplin这样的姓名吗?"""
formatted_name = get_formatted_name('janis','joplin')
self.assertEqual(formatted_name,'Janis Joplin') # 断言
# 方法名必须以test打头,这样才会自动运行
def test_first_last_middle_name(self):
"""能够正确处理像Wolfgang Amadeus Mozart这样的名字吗?"""
formatted_name = get_formatted_name('one','two','three')
self.assertEqual(formatted_name,'One Three Two') # 断言方法[断言:相等]:调用了断言方法,并向它传递变量与预期要实现的结果,对变量与结果进行比较,如果相等就ok,不相等就报异常
unittest.main()
| [
"46178109+ydPro-G@users.noreply.github.com"
] | 46178109+ydPro-G@users.noreply.github.com |
b9588ccb4ffb0e1bce066b2d810835e06acca12a | c505575568bca9d5f171be004c028613dc540244 | /project_name/settings/production.py | 2b584939118024da657b053e84d36eccda35e62b | [] | no_license | alfredo/django-template-plus | e699769015e4a4b5c533f4be2d3ef40779c9d660 | 2d58c6dc8d9493b69031df51ec2e29b13e70e57c | refs/heads/master | 2021-01-20T10:13:03.422330 | 2013-07-04T13:43:15 | 2013-07-04T13:43:15 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 285 | py | # Production settings for {{ project_name }}
from {{ project_name }}.settings import *
SITE_URL = 'http://{{ heroku_app }}.herokuapp.com'
# Basic authentication for Heroku
BASIC_WWW_AUTHENTICATION_USERNAME = ""
BASIC_WWW_AUTHENTICATION_PASSWORD = ""
BASIC_WWW_AUTHENTICATION = False
| [
"alfredo@madewithbyt.es"
] | alfredo@madewithbyt.es |
da236f1d91d055f79cea963d136dafe2b5ff99e3 | 53e58c213232e02250e64f48b97403ca86cd02f9 | /16/mc/ExoDiBosonResonances/EDBRTreeMaker/test/crab3_analysisM3000_R_0-7.py | 67b6fed624f209f701f450282bbd0022b699f73f | [] | no_license | xdlyu/fullRunII_ntuple_102X | 32e79c3bbc704cfaa00c67ab5124d40627fdacaf | d420b83eb9626a8ff1c79af5d34779cb805d57d8 | refs/heads/master | 2020-12-23T15:39:35.938678 | 2020-05-01T14:41:38 | 2020-05-01T14:41:38 | 237,192,426 | 0 | 2 | null | null | null | null | UTF-8 | Python | false | false | 2,303 | py | from WMCore.Configuration import Configuration
name = 'WWW/sig'
steam_dir = 'xulyu'
config = Configuration()
config.section_("General")
config.General.requestName = 'M3000_R0-7_off'
config.General.transferLogs = True
config.section_("JobType")
config.JobType.pluginName = 'Analysis'
config.JobType.inputFiles = ['Summer16_07Aug2017_V11_MC_L1FastJet_AK4PFchs.txt','Summer16_07Aug2017_V11_MC_L2Relative_AK4PFchs.txt','Summer16_07Aug2017_V11_MC_L3Absolute_AK4PFchs.txt','Summer16_07Aug2017_V11_MC_L1FastJet_AK8PFchs.txt','Summer16_07Aug2017_V11_MC_L2Relative_AK8PFchs.txt','Summer16_07Aug2017_V11_MC_L3Absolute_AK8PFchs.txt','Summer16_07Aug2017_V11_MC_L1FastJet_AK8PFPuppi.txt','Summer16_07Aug2017_V11_MC_L2Relative_AK8PFPuppi.txt','Summer16_07Aug2017_V11_MC_L3Absolute_AK8PFPuppi.txt','Summer16_07Aug2017_V11_MC_L1FastJet_AK4PFPuppi.txt','Summer16_07Aug2017_V11_MC_L2Relative_AK4PFPuppi.txt','Summer16_07Aug2017_V11_MC_L3Absolute_AK4PFPuppi.txt']
#config.JobType.inputFiles = ['PHYS14_25_V2_All_L1FastJet_AK4PFchs.txt','PHYS14_25_V2_All_L2Relative_AK4PFchs.txt','PHYS14_25_V2_All_L3Absolute_AK4PFchs.txt','PHYS14_25_V2_All_L1FastJet_AK8PFchs.txt','PHYS14_25_V2_All_L2Relative_AK8PFchs.txt','PHYS14_25_V2_All_L3Absolute_AK8PFchs.txt']
# Name of the CMSSW configuration file
#config.JobType.psetName = 'bkg_ana.py'
config.JobType.psetName = 'analysis_sig.py'
#config.JobType.allowUndistributedCMSSW = True
config.JobType.allowUndistributedCMSSW = True
config.section_("Data")
#config.Data.inputDataset = '/WJetsToLNu_13TeV-madgraph-pythia8-tauola/Phys14DR-PU20bx25_PHYS14_25_V1-v1/MINIAODSIM'
config.Data.inputDataset = '/WkkToWRadionToWWW_M3000-R0-7-TuneCUETP8M1_13TeV-madgraph-pythia/RunIISummer16MiniAODv3-PUMoriond17_94X_mcRun2_asymptotic_v3-v1/MINIAODSIM'
#config.Data.inputDBS = 'global'
config.Data.inputDBS = 'global'
config.Data.splitting = 'FileBased'
config.Data.unitsPerJob =5
config.Data.totalUnits = -1
config.Data.publication = False
config.Data.outLFNDirBase = '/store/group/dpg_trigger/comm_trigger/TriggerStudiesGroup/STEAM/' + steam_dir + '/' + name + '/'
# This string is used to construct the output dataset name
config.Data.outputDatasetTag = 'M3000_R0-7_off'
config.section_("Site")
# Where the output files will be transmitted to
config.Site.storageSite = 'T2_CH_CERN'
| [
"XXX@cern.ch"
] | XXX@cern.ch |
a988a1a9ef07b526d1113b9579ec1b18291dc3e7 | 1cc8a2b32d0f908a828fb032f4d97c3356a52333 | /orthophoto.py | 9c8509d6e3692dda4674c66722d0648fa3f782fc | [] | no_license | testerarm/new_grpc_stage | 3248a2480c5e6ef658d3c5ef868c5cc3b558e148 | ae1aced767e0b302f0d90c9ffb55912341b73419 | refs/heads/master | 2023-04-05T07:25:34.059961 | 2021-04-22T03:36:42 | 2021-04-22T03:36:42 | 360,378,983 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 10,305 | py | import os
from opendm import io
from opendm import log
from opendm import system
from opendm import context
from opendm import types
from opendm import gsd
from opendm import orthophoto
from opendm.concurrency import get_max_memory
from opendm.cutline import compute_cutline
from pipes import quote
from opendm import pseudogeo
def process(args, current_path, max_concurrency, reconstruction):
#args = vars(args)
orthophoto_cutline = True
odm_orthophoto = io.join_paths(current_path, 'orthophoto')
odm_orthophoto_path = odm_orthophoto
odm_orthophoto_render = io.join_paths(odm_orthophoto_path, 'odm_orthophoto_render.tif')
odm_orthophoto_tif = io.join_paths(odm_orthophoto_path, 'odm_orthophoto.tif')
odm_orthophoto_corners = io.join_paths(odm_orthophoto_path, 'odm_orthophoto_corners.tif')
odm_orthophoto_log = io.join_paths(odm_orthophoto_path, 'odm_orthophoto_log.tif')
odm_orthophoto_tif_log = io.join_paths(odm_orthophoto_path, 'gdal_translate_log.txt')
odm_25dgeoreferencing = io.join_paths(current_path, 'odm_georeferencing')
odm_georeferencing = io.join_paths(current_path, 'odm_georeferencing')
odm_georeferencing_coords = io.join_paths(
odm_georeferencing, 'coords.txt')
odm_georeferencing_gcp = io.find('gcp_list.txt', current_path)
odm_georeferencing_gcp_utm = io.join_paths(odm_georeferencing, 'gcp_list_utm.txt')
odm_georeferencing_utm_log = io.join_paths(
odm_georeferencing, 'odm_georeferencing_utm_log.txt')
odm_georeferencing_log = 'odm_georeferencing_log.txt'
odm_georeferencing_transform_file = 'odm_georeferencing_transform.txt'
odm_georeferencing_proj = 'proj.txt'
odm_georeferencing_model_txt_geo = 'odm_georeferencing_model_geo.txt'
odm_georeferencing_model_obj_geo = 'odm_textured_model_geo.obj'
odm_georeferencing_xyz_file = io.join_paths(
odm_georeferencing, 'odm_georeferenced_model.csv')
odm_georeferencing_las_json = io.join_paths(
odm_georeferencing, 'las.json')
odm_georeferencing_model_laz = io.join_paths(
odm_georeferencing, 'odm_georeferenced_model.laz')
odm_georeferencing_model_las = io.join_paths(
odm_georeferencing, 'odm_georeferenced_model.las')
odm_georeferencing_dem = io.join_paths(
odm_georeferencing, 'odm_georeferencing_model_dem.tif')
opensfm_reconstruction = io.join_paths(current_path,'reconstruction.json')
odm_texturing = io.join_paths(current_path,'mvs')
odm_textured_model_obj = io.join_paths(odm_texturing, 'odm_textured_model.obj')
images_dir = io.join_paths(current_path, 'images')
reconstruction = reconstruction
verbose = ''
#"-verbose"
# define paths and create working directories
system.mkdir_p(odm_orthophoto)
if not io.file_exists(odm_orthophoto_tif):
gsd_error_estimate = 0.1
ignore_resolution = False
if not reconstruction.is_georeferenced():
# Match DEMs
gsd_error_estimate = -3
ignore_resolution = True
orthophoto_resolution = 5
resolution = 1.0 / (gsd.cap_resolution(orthophoto_resolution, opensfm_reconstruction,
gsd_error_estimate=gsd_error_estimate,
ignore_gsd=True,
ignore_resolution=ignore_resolution,
has_gcp=reconstruction.has_gcp()) / 100.0)
# odm_orthophoto definitions
kwargs = {
'bin': context.odm_modules_path,
'log': odm_orthophoto_log,
'ortho': odm_orthophoto_render,
'corners': odm_orthophoto_corners,
'res': resolution,
'bands': '',
'verbose': verbose
}
# Check if the georef object is initialized
# (during a --rerun this might not be)
# TODO: this should be moved to a more central location?
if reconstruction.is_georeferenced() and not reconstruction.georef.valid_utm_offsets():
georeferencing_dir = odm_georeferencing #if args.use_3dmesh and not args.skip_3dmodel else odm_25dgeoreferencing
odm_georeferencing_model_txt_geo_file = os.path.join(georeferencing_dir, odm_georeferencing_model_txt_geo)
if io.file_exists(odm_georeferencing_model_txt_geo_file):
reconstruction.georef.extract_offsets(odm_georeferencing_model_txt_geo_file)
else:
log.ODM_WARNING('Cannot read UTM offset from {}.'.format(odm_georeferencing_model_txt_geo_file))
models = []
base_dir = odm_texturing
if reconstruction.is_georeferenced():
model_file = odm_georeferencing_model_obj_geo
else:
model_file = odm_textured_model_obj
if reconstruction.multi_camera:
for band in reconstruction.multi_camera:
primary = band == reconstruction.multi_camera[0]
subdir = ""
if not primary:
subdir = band['name'].lower()
models.append(os.path.join(base_dir, subdir, model_file))
kwargs['bands'] = '-bands %s' % (','.join([quote(b['name'].lower()) for b in reconstruction.multi_camera]))
else:
models.append(os.path.join(base_dir, model_file))
kwargs['models'] = ','.join(map(quote, models))
# run odm_orthophoto
system.run('{bin}/odm_orthophoto -inputFiles {models} '
'-logFile {log} -outputFile {ortho} -resolution {res} {verbose} '
'-outputCornerFile {corners} {bands}'.format(**kwargs))
# Create georeferenced GeoTiff
geotiffcreated = False
if reconstruction.is_georeferenced() and reconstruction.georef.valid_utm_offsets():
ulx = uly = lrx = lry = 0.0
with open(odm_orthophoto_corners) as f:
for lineNumber, line in enumerate(f):
if lineNumber == 0:
tokens = line.split(' ')
if len(tokens) == 4:
ulx = float(tokens[0]) + \
float(reconstruction.georef.utm_east_offset)
lry = float(tokens[1]) + \
float(reconstruction.georef.utm_north_offset)
lrx = float(tokens[2]) + \
float(reconstruction.georef.utm_east_offset)
uly = float(tokens[3]) + \
float(reconstruction.georef.utm_north_offset)
log.ODM_INFO('Creating GeoTIFF')
orthophoto_vars = orthophoto.get_orthophoto_vars(args)
kwargs = {
'ulx': ulx,
'uly': uly,
'lrx': lrx,
'lry': lry,
'vars': ' '.join(['-co %s=%s' % (k, orthophoto_vars[k]) for k in orthophoto_vars]),
'proj': reconstruction.georef.proj4(),
'input': odm_orthophoto_render,
'output': odm_orthophoto_tif,
'log': odm_orthophoto_tif_log,
'max_memory': get_max_memory(),
}
system.run('gdal_translate -a_ullr {ulx} {uly} {lrx} {lry} '
'{vars} '
'-a_srs \"{proj}\" '
'--config GDAL_CACHEMAX {max_memory}% '
'--config GDAL_TIFF_INTERNAL_MASK YES '
'{input} {output} > {log}'.format(**kwargs))
bounds_file_path = os.path.join(odm_georeferencing, 'odm_georeferenced_model.bounds.gpkg')
# Cutline computation, before cropping
# We want to use the full orthophoto, not the cropped one.
pio = True
if pio:
cutline_file = os.path.join(odm_orthophoto, "cutline.gpkg")
compute_cutline(odm_orthophoto_tif,
bounds_file_path,
cutline_file,
max_concurrency,
tmpdir=os.path.join(odm_orthophoto, "grass_cutline_tmpdir"),
scale=0.25)
orthophoto.compute_mask_raster(odm_orthophoto_tif, cutline_file,
os.path.join(odm_orthophoto, "odm_orthophoto_cut.tif"),
blend_distance=20, only_max_coords_feature=True)
orthophoto.post_orthophoto_steps(args, bounds_file_path, odm_orthophoto_tif)
# Generate feathered orthophoto also
if pio:
orthophoto.feather_raster(odm_orthophoto_tif,
os.path.join(odm_orthophoto, "odm_orthophoto_feathered.tif"),
blend_distance=20
)
geotiffcreated = True
if not geotiffcreated:
if io.file_exists(odm_orthophoto_render):
pseudogeo.add_pseudo_georeferencing(odm_orthophoto_render)
log.ODM_INFO("Renaming %s --> %s" % (odm_orthophoto_render, odm_orthophoto_tif))
os.rename(odm_orthophoto_render,odm_orthophoto_tif)
else:
log.ODM_WARNING("Could not generate an orthophoto (it did not render)")
else:
log.ODM_WARNING('Found a valid orthophoto in: %s' % odm_orthophoto_tif)
#generate png
#orthophoto.generate_png(odm_orthophoto_tif)
#if args.optimize_disk_space and io.file_exists(tree.odm_orthophoto_render):
# os.remove(odm_orthophoto_render)
| [
"you@example.com"
] | you@example.com |
cfdbd786e226fab3dd20e883df0c067fa999d9ae | 1ade02a8e0c6d7e442c9d9041f15518d22da3923 | /Homework/w1d2/inclass/information_extraction_exercise.py | 60b1b7ca589a5f9e1bee6cf00c9d84843e96cea4 | [] | no_license | fodisi/ByteAcademy-Bootcamp | 7980b80636a36db6da3e0fc0e529fbc6b8e097e0 | d53e3f4864f6cba1b85e806c29b01c48e3c2e81d | refs/heads/master | 2020-03-19T12:55:31.489638 | 2018-07-25T16:19:19 | 2018-07-25T16:19:19 | 136,550,128 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 615 | py | #!/usr/bin/env python3
import json
import requests
def get_price(ticker_symbol):
endpoint = 'http://dev.markitondemand.com/MODApis/Api/v2/Quote/json?symbol='+ticker_symbol
response = json.loads(requests.get(endpoint).text)['LastPrice']
return response
def get_symbol(company_name):
endpoint = 'http://dev.markitondemand.com/MODApis/Api/v2/Lookup/json?input='+company_name
response = json.loads(requests.get(endpoint).text)[0]['Symbol']
return response
if __name__ == '__main__':
#print(get_price('tsla'))
#print(get_symbol('tesla'))
print(get_price(get_symbol('apple')))
| [
"fodisi@users.noreply.github.com"
] | fodisi@users.noreply.github.com |
d5e1c3a8eec6bc5eb82ffaa2109da25a7f91c691 | 5a52ccea88f90dd4f1acc2819997fce0dd5ffb7d | /alipay/aop/api/request/AlipayOpenMiniVersionDetailQueryRequest.py | e3da861b450247eee7a3f5a7161ccb2f68c8d6a6 | [
"Apache-2.0"
] | permissive | alipay/alipay-sdk-python-all | 8bd20882852ffeb70a6e929038bf88ff1d1eff1c | 1fad300587c9e7e099747305ba9077d4cd7afde9 | refs/heads/master | 2023-08-27T21:35:01.778771 | 2023-08-23T07:12:26 | 2023-08-23T07:12:26 | 133,338,689 | 247 | 70 | Apache-2.0 | 2023-04-25T04:54:02 | 2018-05-14T09:40:54 | Python | UTF-8 | Python | false | false | 3,992 | py | #!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
from alipay.aop.api.FileItem import FileItem
from alipay.aop.api.constant.ParamConstants import *
from alipay.aop.api.domain.AlipayOpenMiniVersionDetailQueryModel import AlipayOpenMiniVersionDetailQueryModel
class AlipayOpenMiniVersionDetailQueryRequest(object):
def __init__(self, biz_model=None):
self._biz_model = biz_model
self._biz_content = None
self._version = "1.0"
self._terminal_type = None
self._terminal_info = None
self._prod_code = None
self._notify_url = None
self._return_url = None
self._udf_params = None
self._need_encrypt = False
@property
def biz_model(self):
return self._biz_model
@biz_model.setter
def biz_model(self, value):
self._biz_model = value
@property
def biz_content(self):
return self._biz_content
@biz_content.setter
def biz_content(self, value):
if isinstance(value, AlipayOpenMiniVersionDetailQueryModel):
self._biz_content = value
else:
self._biz_content = AlipayOpenMiniVersionDetailQueryModel.from_alipay_dict(value)
@property
def version(self):
return self._version
@version.setter
def version(self, value):
self._version = value
@property
def terminal_type(self):
return self._terminal_type
@terminal_type.setter
def terminal_type(self, value):
self._terminal_type = value
@property
def terminal_info(self):
return self._terminal_info
@terminal_info.setter
def terminal_info(self, value):
self._terminal_info = value
@property
def prod_code(self):
return self._prod_code
@prod_code.setter
def prod_code(self, value):
self._prod_code = value
@property
def notify_url(self):
return self._notify_url
@notify_url.setter
def notify_url(self, value):
self._notify_url = value
@property
def return_url(self):
return self._return_url
@return_url.setter
def return_url(self, value):
self._return_url = value
@property
def udf_params(self):
return self._udf_params
@udf_params.setter
def udf_params(self, value):
if not isinstance(value, dict):
return
self._udf_params = value
@property
def need_encrypt(self):
return self._need_encrypt
@need_encrypt.setter
def need_encrypt(self, value):
self._need_encrypt = value
def add_other_text_param(self, key, value):
if not self.udf_params:
self.udf_params = dict()
self.udf_params[key] = value
def get_params(self):
params = dict()
params[P_METHOD] = 'alipay.open.mini.version.detail.query'
params[P_VERSION] = self.version
if self.biz_model:
params[P_BIZ_CONTENT] = json.dumps(obj=self.biz_model.to_alipay_dict(), ensure_ascii=False, sort_keys=True, separators=(',', ':'))
if self.biz_content:
if hasattr(self.biz_content, 'to_alipay_dict'):
params['biz_content'] = json.dumps(obj=self.biz_content.to_alipay_dict(), ensure_ascii=False, sort_keys=True, separators=(',', ':'))
else:
params['biz_content'] = self.biz_content
if self.terminal_type:
params['terminal_type'] = self.terminal_type
if self.terminal_info:
params['terminal_info'] = self.terminal_info
if self.prod_code:
params['prod_code'] = self.prod_code
if self.notify_url:
params['notify_url'] = self.notify_url
if self.return_url:
params['return_url'] = self.return_url
if self.udf_params:
params.update(self.udf_params)
return params
def get_multipart_params(self):
multipart_params = dict()
return multipart_params
| [
"liuqun.lq@alibaba-inc.com"
] | liuqun.lq@alibaba-inc.com |
2b12246547b51b74307c0c0e914afc2c5ce1b294 | 4fde32723e04cbb9c929c54dad55f4333ba48d90 | /tests/exceptions/source/diagnose/keyword_argument.py | 915a4a8c8fe4dcb406b7587f72ee1d3714dffca8 | [
"MIT"
] | permissive | Delgan/loguru | 29f1b64a4944886559d76e22029fe1e5c88e7fec | 80bcf4e25da9f79617ef23ca0fb29b100caac8f2 | refs/heads/master | 2023-09-03T20:18:46.892038 | 2023-09-03T16:19:15 | 2023-09-03T16:19:15 | 100,401,612 | 15,902 | 775 | MIT | 2023-09-11T14:19:42 | 2017-08-15T17:22:32 | Python | UTF-8 | Python | false | false | 246 | py | import sys
from loguru import logger
logger.remove()
logger.add(sys.stderr, format="", colorize=True, backtrace=False, diagnose=True)
def f(x):
return 1 / x
y = 0
with logger.catch():
f(x=y)
x = 0
with logger.catch():
f(x=x)
| [
"delgan.py@gmail.com"
] | delgan.py@gmail.com |
955a3eb12f6890a23402b59ec8dfaebaaf36fc45 | 472c0ba1911619f8e2e1a68b4f956fad05be4e94 | /src/matlab2cpp/parser.py | 0ffd7711ae1689070e9362f1c37d0478a7bc10d8 | [
"BSD-3-Clause"
] | permissive | jonathf/matlab2cpp | f8b9541cf79507ec764b04b8211e73c47a20c131 | b6e2cbaedb36c909952911adfe44fe26252a36a1 | refs/heads/master | 2022-08-08T21:28:23.028072 | 2022-07-15T19:58:01 | 2022-07-15T19:58:01 | 31,599,354 | 197 | 68 | BSD-3-Clause | 2022-07-15T19:58:02 | 2015-03-03T13:20:32 | Python | UTF-8 | Python | false | false | 4,744 | py | """Create parser for m2cpp."""
import argparse
from textwrap import dedent
import glob
import matlab2cpp
HELP_DESCRIPTION = """\
*** Matlab2cpp ***
The toolbox frontend of the Matlab2cpp library. Use this to try to do automatic
and semi-automatic translation from Matlab source file to C++. The program
will create files with the same name as the input, but with various extra
extensions. Scripts will receive the extension `.cpp`, headers and modules
`.hpp`. A file containing data type and header information will be stored in
a `.py` file. Any errors will be stored in `.log`.
"""
def matlab_file_completer(prefix, **kws):
"""Complete files with matlab extensions."""
return glob.glob("{}*.m".format(prefix))
def create_parser():
"""Create argument parser."""
parser = argparse.ArgumentParser(
formatter_class=argparse.RawDescriptionHelpFormatter,
description=dedent(HELP_DESCRIPTION))
parser.add_argument(
"filename", help="File containing valid Matlab code."
).completer = matlab_file_completer
parser.add_argument(
"-o", '--original', action="store_true", help=(
"Include original Matlab code line as comment before the "
"C++ translation of the code line"),
)
parser.add_argument(
"-c", '--comments', action="store_true", help=(
"Include Matlab comments in the generated C++ files."),
)
parser.add_argument(
"-s", '--suggest', action="store_true", help=(
"Automatically populate the `<filename>.py` file with datatype "
"with suggestions if possible."),
)
parser.add_argument(
"-S", '--matlab-suggest', action="store_true", help=(
"Creates a folder m2cpp_temp. In the folder the matlab file(s) to "
"be translated are also put. These matlab file(s) are slightly "
"modified so that they output data-type information of the "
"variables to file(s). This output can then be used to set the "
"datatypes for the translation."),
)
parser.add_argument(
"-r", '--reset', action="store_true", help=(
"Ignore the content of `<filename>.py` and make a fresh translation."),
)
parser.add_argument(
"-t", '--tree', action="store_true", help=(
"Print the underlying node tree. Each line in the output "
"represents a node and is formated as follows: \n\n"
"`<codeline> <position> <class> <backend> <datatype> <name> <translation>`\n\n"
"The indentation represents the tree structure."),
)
parser.add_argument(
"-T", "--tree-full", action="store_true", help=(
"Same as -t, but the full node tree, but include meta-nodes."),
)
parser.add_argument(
"-d", '--disp', action="store_true", help=(
"Print out the progress of the translation process."),
)
parser.add_argument(
"-p", "--paths_file", type=str, dest="paths_file", help=(
"Flag and paths_file (-p path_to_pathsfile). m2cpp will look for "
"matlab files in the location specified in the paths_file"),
)
parser.add_argument(
"-omp", '--enable-omp', action="store_true", help=(
"OpenMP code is inserted for Parfor and loops marked with the "
"pragma %%#PARFOR (in Matlab code) when this flag is set."),
)
parser.add_argument(
"-tbb", '--enable-tbb', action="store_true", help=(
"TBB code is inserted for Parfor and loops marked with the "
"pragma %%#PARFOR (in Matlab code) when this flag is set."),
)
parser.add_argument(
"-ref", '--reference', action="store_true", help=(
'For the generated C++ code, function input parameters are '
'"copied by value" as default. With this flag some input '
'parameters in the generated code can be const references. '
'There can be some performance advantage of using const '
'references instead of "copied by value". Note that Matlab '
'"copies by value". The Matlab code you try to translate to '
'C++ code could try read as well as write to this input variable. '
"The code generator doesn't perform an analysis to detect this "
'and then "copy by value" for this variable.'),
)
parser.add_argument(
"-l", '--line', type=int, dest="line", help=(
"Only display code related to code line number `<line>`."),
)
parser.add_argument(
"-n", '--nargin', action="store_true", help=(
"Don't remove if and switch branches which use nargin variable."),
)
return parser
| [
"jonathf@gmail.com"
] | jonathf@gmail.com |
86af9ecd041da60eaec93e144a49f9300db74d2d | cc096d321ab5c6abf54fdcea67f10e77cd02dfde | /flex-backend/pypy/rpython/rmodel.py | 72f72f9a59ee8ae0fb2f625fe739c85c2b67159b | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | limweb/flex-pypy | 310bd8fcd6a9ddc01c0b14a92f0298d0ae3aabd2 | 05aeeda183babdac80f9c10fca41e3fb1a272ccb | refs/heads/master | 2021-01-19T22:10:56.654997 | 2008-03-19T23:51:59 | 2008-03-19T23:51:59 | 32,463,309 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 18,169 | py | from pypy.annotation.pairtype import pairtype, extendabletype, pair
from pypy.annotation import model as annmodel
from pypy.annotation import description
from pypy.objspace.flow.model import Constant
from pypy.rpython.lltypesystem.lltype import \
Void, Bool, Float, Signed, Char, UniChar, \
typeOf, LowLevelType, Ptr, PyObject, isCompatibleType
from pypy.rpython.lltypesystem import lltype, llmemory
from pypy.rpython.ootypesystem import ootype
from pypy.rpython.error import TyperError, MissingRTypeOperation
# initialization states for Repr instances
class setupstate:
NOTINITIALIZED = 0
INPROGRESS = 1
BROKEN = 2
FINISHED = 3
DELAYED = 4
class Repr:
""" An instance of Repr is associated with each instance of SomeXxx.
It defines the chosen representation for the SomeXxx. The Repr subclasses
generally follows the SomeXxx subclass hierarchy, but there are numerous
exceptions. For example, the annotator uses SomeIter for any iterator, but
we need different representations according to the type of container we are
iterating over.
"""
__metaclass__ = extendabletype
_initialized = setupstate.NOTINITIALIZED
def __repr__(self):
return '<%s %s>' % (self.__class__.__name__, self.lowleveltype)
def compact_repr(self):
return '%s %s' % (self.__class__.__name__.replace('Repr','R'), self.lowleveltype._short_name())
def setup(self):
""" call _setup_repr() and keep track of the initializiation
status to e.g. detect recursive _setup_repr invocations.
the '_initialized' attr has four states:
"""
if self._initialized == setupstate.FINISHED:
return
elif self._initialized == setupstate.BROKEN:
raise BrokenReprTyperError(
"cannot setup already failed Repr: %r" %(self,))
elif self._initialized == setupstate.INPROGRESS:
raise AssertionError(
"recursive invocation of Repr setup(): %r" %(self,))
elif self._initialized == setupstate.DELAYED:
raise AssertionError(
"Repr setup() is delayed and cannot be called yet: %r" %(self,))
assert self._initialized == setupstate.NOTINITIALIZED
self._initialized = setupstate.INPROGRESS
try:
self._setup_repr()
except TyperError, e:
self._initialized = setupstate.BROKEN
raise
else:
self._initialized = setupstate.FINISHED
def _setup_repr(self):
"For recursive data structure, which must be initialized in two steps."
def setup_final(self):
"""Same as setup(), called a bit later, for effects that are only
needed after the typer finished (as opposed to needed for other parts
of the typer itself)."""
if self._initialized == setupstate.BROKEN:
raise BrokenReprTyperError("cannot perform setup_final_touch "
"on failed Repr: %r" %(self,))
assert self._initialized == setupstate.FINISHED, (
"setup_final() on repr with state %s: %r" %
(self._initialized, self))
self._setup_repr_final()
def _setup_repr_final(self):
pass
def is_setup_delayed(self):
return self._initialized == setupstate.DELAYED
def set_setup_delayed(self, flag):
assert self._initialized in (setupstate.NOTINITIALIZED,
setupstate.DELAYED)
if flag:
self._initialized = setupstate.DELAYED
else:
self._initialized = setupstate.NOTINITIALIZED
def set_setup_maybe_delayed(self):
if self._initialized == setupstate.NOTINITIALIZED:
self._initialized = setupstate.DELAYED
return self._initialized == setupstate.DELAYED
def __getattr__(self, name):
# Assume that when an attribute is missing, it's because setup() needs
# to be called
if not (name[:2] == '__' == name[-2:]):
if self._initialized == setupstate.NOTINITIALIZED:
self.setup()
try:
return self.__dict__[name]
except KeyError:
pass
raise AttributeError("%s instance has no attribute %s" % (
self.__class__.__name__, name))
def _freeze_(self):
return True
def convert_desc_or_const(self, desc_or_const):
if isinstance(desc_or_const, description.Desc):
return self.convert_desc(desc_or_const)
elif isinstance(desc_or_const, Constant):
return self.convert_const(desc_or_const.value)
else:
raise TyperError("convert_desc_or_const expects a Desc"
"or Constant: %r" % desc_or_const)
def convert_const(self, value):
"Convert the given constant value to the low-level repr of 'self'."
if self.lowleveltype is not Void:
try:
realtype = typeOf(value)
except (AssertionError, AttributeError, TypeError):
realtype = '???'
if realtype != self.lowleveltype:
raise TyperError("convert_const(self = %r, value = %r)" % (
self, value))
return value
def get_ll_eq_function(self):
"""Return an eq(x,y) function to use to compare two low-level
values of this Repr.
This can return None to mean that simply using '==' is fine.
"""
raise TyperError, 'no equality function for %r' % self
def get_ll_hash_function(self):
"""Return a hash(x) function for low-level values of this Repr.
"""
raise TyperError, 'no hashing function for %r' % self
def get_ll_fasthash_function(self):
"""Return a 'fast' hash(x) function for low-level values of this
Repr. The function can assume that 'x' is already stored as a
key in a dict. get_ll_fasthash_function() should return None if
the hash should rather be cached in the dict entry.
"""
return None
def can_ll_be_null(self, s_value):
"""Check if the low-level repr can take the value 0/NULL.
The annotation s_value is provided as a hint because it may
contain more information than the Repr.
"""
return True # conservative
def get_ll_dummyval_obj(self, rtyper, s_value):
"""A dummy value is a special low-level value, not otherwise
used. It should not be the NULL value even if it is special.
This returns either None, or a hashable object that has a
(possibly lazy) attribute 'll_dummy_value'.
The annotation s_value is provided as a hint because it may
contain more information than the Repr.
"""
T = self.lowleveltype
if (isinstance(T, lltype.Ptr) and
isinstance(T.TO, (lltype.Struct,
lltype.Array,
lltype.ForwardReference)) and
T.TO._gckind != 'cpy'):
return DummyValueBuilder(rtyper, T.TO)
else:
return None
def rtype_bltn_list(self, hop):
raise TyperError, 'no list() support for %r' % self
def rtype_unichr(self, hop):
raise TyperError, 'no unichr() support for %r' % self
# default implementation of some operations
def rtype_getattr(self, hop):
s_attr = hop.args_s[1]
if s_attr.is_constant() and isinstance(s_attr.const, str):
attr = s_attr.const
s_obj = hop.args_s[0]
if s_obj.find_method(attr) is None:
raise TyperError("no method %s on %r" % (attr, s_obj))
else:
# implement methods (of a known name) as just their 'self'
return hop.inputarg(self, arg=0)
else:
raise TyperError("getattr() with a non-constant attribute name")
def rtype_str(self, hop):
[v_self] = hop.inputargs(self)
return hop.gendirectcall(self.ll_str, v_self)
def rtype_nonzero(self, hop):
return self.rtype_is_true(hop) # can call a subclass' rtype_is_true()
def rtype_is_true(self, hop):
try:
vlen = self.rtype_len(hop)
except MissingRTypeOperation:
if not hop.s_result.is_constant():
raise TyperError("rtype_is_true(%r) not implemented" % (self,))
return hop.inputconst(Bool, hop.s_result.const)
else:
return hop.genop('int_is_true', [vlen], resulttype=Bool)
def rtype_id(self, hop):
if not isinstance(self.lowleveltype, Ptr):
raise TyperError('id() of an instance of the non-pointer %r' % (
self,))
vobj, = hop.inputargs(self)
# XXX why did this go through weakadr??
#v_waddr = hop.genop('cast_ptr_to_weakadr', [vobj],
# resulttype=llmemory.WeakGcAddress)
#return hop.genop('cast_weakadr_to_int', [v_waddr], resulttype=Signed)
return hop.genop('cast_ptr_to_int', [vobj], resulttype=Signed)
def rtype_hash(self, hop):
ll_hash = self.get_ll_hash_function()
v, = hop.inputargs(self)
return hop.gendirectcall(ll_hash, v)
def rtype_iter(self, hop):
r_iter = self.make_iterator_repr()
return r_iter.newiter(hop)
def make_iterator_repr(self, *variant):
raise TyperError("%s is not iterable" % (self,))
def rtype_hint(self, hop):
return hop.inputarg(hop.r_result, arg=0)
# hlinvoke helpers
def get_r_implfunc(self):
raise TyperError("%s has no corresponding implementation function representation" % (self,))
def get_s_callable(self):
raise TyperError("%s is not callable or cannot reconstruct a pbc annotation for itself" % (self,))
def ll_hash_void(v):
return 0
class CanBeNull(object):
"""A mix-in base class for subclasses of Repr that represent None as
'null' and true values as non-'null'.
"""
def rtype_is_true(self, hop):
if hop.s_result.is_constant():
return hop.inputconst(Bool, hop.s_result.const)
else:
return hop.rtyper.type_system.check_null(self, hop)
class IteratorRepr(Repr):
"""Base class of Reprs of any kind of iterator."""
def rtype_iter(self, hop): # iter(iter(x)) <==> iter(x)
v_iter, = hop.inputargs(self)
return v_iter
def rtype_method_next(self, hop):
return self.rtype_next(hop)
class __extend__(annmodel.SomeIterator):
# NOTE: SomeIterator is for iterators over any container, not just list
def rtyper_makerepr(self, rtyper):
r_container = rtyper.getrepr(self.s_container)
return r_container.make_iterator_repr(*self.variant)
def rtyper_makekey_ex(self, rtyper):
return self.__class__, rtyper.makekey(self.s_container), self.variant
class __extend__(annmodel.SomeImpossibleValue):
def rtyper_makerepr(self, rtyper):
return impossible_repr
def rtyper_makekey(self):
return self.__class__,
# ____ generic binary operations _____________________________
class __extend__(pairtype(Repr, Repr)):
def rtype_is_((robj1, robj2), hop):
if hop.s_result.is_constant():
return inputconst(Bool, hop.s_result.const)
return hop.rtyper.type_system.generic_is(robj1, robj2, hop)
# default implementation for checked getitems
def rtype_getitem_idx_key((r_c1, r_o1), hop):
return pair(r_c1, r_o1).rtype_getitem(hop)
rtype_getitem_idx = rtype_getitem_idx_key
rtype_getitem_key = rtype_getitem_idx_key
# ____________________________________________________________
def make_missing_op(rcls, opname):
attr = 'rtype_' + opname
if not hasattr(rcls, attr):
def missing_rtype_operation(self, hop):
raise MissingRTypeOperation("unimplemented operation: "
"'%s' on %r" % (opname, self))
setattr(rcls, attr, missing_rtype_operation)
for opname in annmodel.UNARY_OPERATIONS:
make_missing_op(Repr, opname)
for opname in annmodel.BINARY_OPERATIONS:
make_missing_op(pairtype(Repr, Repr), opname)
# not in BINARY_OPERATIONS
make_missing_op(pairtype(Repr, Repr), 'contains')
class __extend__(pairtype(Repr, Repr)):
def convert_from_to((r_from, r_to), v, llops):
return NotImplemented
# ____________________________________________________________
# Primitive Repr classes, in the same hierarchical order as
# the corresponding SomeObjects
class FloatRepr(Repr):
lowleveltype = Float
class IntegerRepr(FloatRepr):
def __init__(self, lowleveltype, opprefix):
self.lowleveltype = lowleveltype
self._opprefix = opprefix
self.as_int = self
def _get_opprefix(self):
if self._opprefix is None:
raise TyperError("arithmetic not supported on %r" %
self.lowleveltype)
return self._opprefix
opprefix =property(_get_opprefix)
class BoolRepr(IntegerRepr):
lowleveltype = Bool
# NB. no 'opprefix' here. Use 'as_int' systematically.
def __init__(self):
from pypy.rpython.rint import signed_repr
self.as_int = signed_repr
class VoidRepr(Repr):
lowleveltype = Void
def get_ll_eq_function(self): return None
def get_ll_hash_function(self): return ll_hash_void
get_ll_fasthash_function = get_ll_hash_function
def ll_str(self, nothing): raise AssertionError("unreachable code")
impossible_repr = VoidRepr()
class SimplePointerRepr(Repr):
"Convenience Repr for simple ll pointer types with no operation on them."
def __init__(self, lowleveltype):
self.lowleveltype = lowleveltype
def convert_const(self, value):
if value is not None:
raise TyperError("%r only supports None as prebuilt constant, "
"got %r" % (self, value))
return lltype.nullptr(self.lowleveltype.TO)
# ____________________________________________________________
def inputdesc(reqtype, desc):
"""Return a Constant for the given desc, of the requested type,
which can only be a Repr.
"""
assert isinstance(reqtype, Repr)
value = reqtype.convert_desc(desc)
lltype = reqtype.lowleveltype
c = Constant(value)
c.concretetype = lltype
return c
def inputconst(reqtype, value):
"""Return a Constant with the given value, of the requested type,
which can be a Repr instance or a low-level type.
"""
if isinstance(reqtype, Repr):
value = reqtype.convert_const(value)
lltype = reqtype.lowleveltype
elif isinstance(reqtype, LowLevelType):
lltype = reqtype
else:
raise TypeError(repr(reqtype))
# Void Constants can hold any value;
# non-Void Constants must hold a correctly ll-typed value
if lltype is not Void:
try:
realtype = typeOf(value)
except (AssertionError, AttributeError):
realtype = '???'
if not isCompatibleType(realtype, lltype):
raise TyperError("inputconst(reqtype = %s, value = %s):\n"
"expected a %r,\n"
" got a %r" % (reqtype, value,
lltype, realtype))
c = Constant(value)
c.concretetype = lltype
return c
class BrokenReprTyperError(TyperError):
""" raised when trying to setup a Repr whose setup
has failed already.
"""
def mangle(prefix, name):
"""Make a unique identifier from the prefix and the name. The name
is allowed to start with $."""
if name.startswith('$'):
return '%sinternal_%s' % (prefix, name[1:])
else:
return '%s_%s' % (prefix, name)
class HalfConcreteWrapper:
# see rtyper.gendirectcall()
def __init__(self, callback):
self.concretize = callback # should produce a concrete const
def _freeze_(self):
return True
# __________ utilities __________
PyObjPtr = Ptr(PyObject)
def getgcflavor(classdef):
for parentdef in classdef.getmro():
if hasattr(parentdef, '_cpy_exported_type_'):
return 'cpy'
classdesc = classdef.classdesc
alloc_flavor = classdesc.read_attribute('_alloc_flavor_',
Constant('gc')).value
return alloc_flavor
def externalvsinternal(rtyper, item_repr): # -> external_item_repr, (internal_)item_repr
from pypy.rpython import rclass
if (isinstance(item_repr, rclass.AbstractInstanceRepr) and
getattr(item_repr, 'gcflavor', 'gc') == 'gc'):
return item_repr, rclass.getinstancerepr(rtyper, None)
else:
return item_repr, item_repr
class DummyValueBuilder(object):
def __init__(self, rtyper, TYPE):
self.rtyper = rtyper
self.TYPE = TYPE
def _freeze_(self):
return True
def __hash__(self):
return hash(self.TYPE)
def __eq__(self, other):
return (isinstance(other, DummyValueBuilder) and
self.rtyper is other.rtyper and
self.TYPE == other.TYPE)
def __ne__(self, other):
return not (self == other)
def build_ll_dummy_value(self):
TYPE = self.TYPE
try:
return self.rtyper.cache_dummy_values[TYPE]
except KeyError:
# generate a dummy ptr to an immortal placeholder struct/array
if TYPE._is_varsize():
p = lltype.malloc(TYPE, 0, immortal=True)
else:
p = lltype.malloc(TYPE, immortal=True)
self.rtyper.cache_dummy_values[TYPE] = p
return p
ll_dummy_value = property(build_ll_dummy_value)
# logging/warning
import py
from pypy.tool.ansi_print import ansi_log
log = py.log.Producer("rtyper")
py.log.setconsumer("rtyper", ansi_log)
py.log.setconsumer("rtyper translating", None)
py.log.setconsumer("rtyper debug", None)
def warning(msg):
log.WARNING(msg)
| [
"lucio.torre@dbd81ab4-9648-0410-a770-9b81666e587d"
] | lucio.torre@dbd81ab4-9648-0410-a770-9b81666e587d |
26f6ff2a255625275d61146503b16f43f11f2c3a | 4e0ff785b993b6bae70745434e61f27ca82e88f0 | /113-Path-Sum-II/solution.py | 8f5f4558cd246ae961dcad453e72f3e13d869c38 | [] | no_license | NobodyWHU/Leetcode | 2ee557dd77c65c5fa8ca938efb6de3793b4de261 | d284fa3daab02531e5300867463b293d44737e32 | refs/heads/master | 2021-01-23T14:05:28.161062 | 2016-09-23T11:51:51 | 2016-09-23T11:51:51 | 58,898,114 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 883 | py | # Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def pathSum(self, root, sum):
"""
:type root: TreeNode
:type sum: int
:rtype: List[List[int]]
"""
if not root:
return []
ans = []
self.helper(sum-root.val, root, [root.val], ans)
return ans
def helper(self, leftvalue, root, temp, ans):
if leftvalue == 0 and root.left is None and root.right is None:
ans.append(temp)
return
if root.left:
self.helper(leftvalue-root.left.val, root.left, temp+[root.left.val], ans)
if root.right:
self.helper(leftvalue-root.right.val, root.right, temp+[root.right.val], ans)
| [
"haohaoranran@126.com"
] | haohaoranran@126.com |
2f90756cc1595c4a95effe25d37d4029f6377e25 | f335e561d30319cf4759199fc78ea429b0cdb052 | /lldb/test/API/commands/expression/import-std-module/list/TestListFromStdModule.py | 9382c800ec76e275bbaaab5d146be2028e6a7c06 | [
"NCSA",
"Apache-2.0",
"LLVM-exception"
] | permissive | lock3/meta | 9f7c721c890f34256bfac17d789e7078d3b9675a | 918b8a2affc4a3e280b2cd2400dc535e32129c2c | refs/heads/feature/reflect | 2023-06-16T23:15:42.059634 | 2020-11-05T23:33:12 | 2020-11-10T21:17:00 | 278,660,720 | 122 | 14 | null | 2023-04-07T15:19:30 | 2020-07-10T14:54:22 | C++ | UTF-8 | Python | false | false | 2,156 | py | """
Test basic std::list functionality.
"""
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import lldbutil
class TestBasicList(TestBase):
mydir = TestBase.compute_mydir(__file__)
@add_test_categories(["libc++"])
@skipIf(compiler=no_match("clang"))
def test(self):
self.build()
lldbutil.run_to_source_breakpoint(self,
"// Set break point at this line.",
lldb.SBFileSpec("main.cpp"))
self.runCmd("settings set target.import-std-module true")
list_type = "std::list<int, std::allocator<int> >"
size_type = list_type + "::size_type"
value_type = list_type + "::value_type"
iteratorvalue = "std::__list_iterator<int, void *>::value_type"
riterator_value = "std::__list_iterator<int, void *>::value_type"
self.expect_expr("a",
result_type=list_type,
result_children=[
ValueCheck(value="3"),
ValueCheck(value="1"),
ValueCheck(value="2")
])
self.expect_expr("a.size()", result_type=size_type, result_value="3")
self.expect_expr("a.front()", result_type=value_type, result_value="3")
self.expect_expr("a.back()", result_type=value_type, result_value="2")
self.expect("expr a.sort()")
self.expect_expr("a.front()", result_type=value_type, result_value="1")
self.expect_expr("a.back()", result_type=value_type, result_value="3")
self.expect("expr std::reverse(a.begin(), a.end())")
self.expect_expr("a.front()", result_type=value_type, result_value="3")
self.expect_expr("a.back()", result_type=value_type, result_value="1")
self.expect_expr("*a.begin()",
result_type=iteratorvalue,
result_value="3")
self.expect_expr("*a.rbegin()",
result_type=riterator_value,
result_value="1")
| [
"teemperor@gmail.com"
] | teemperor@gmail.com |
29c1c4beba24f4ef72451a2ee5e945a97aca3955 | 45a153a8e27b552d82d137bd94f2d5d0aec3c889 | /GoogleCLoudwithTwilio/google-cloud-sdk/lib/surface/compute/instance_groups/managed/stop_autoscaling.py | 2b8c7bad314ab25f4c5235300b511b241bcd0ea4 | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | Pooshan/App-using-Twilio | 84bc0be1f091c678528bdf161c9fbb0af617fc0e | a6eea3f40ef9f22a7ab47c1f63b90deaa2620049 | refs/heads/master | 2022-11-23T23:56:49.754209 | 2016-10-01T18:47:25 | 2016-10-01T18:47:25 | 69,719,320 | 0 | 1 | null | 2022-11-02T19:48:20 | 2016-10-01T04:26:37 | Python | UTF-8 | Python | false | false | 6,012 | py | # Copyright 2015 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless 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.
"""Command for stopping autoscaling of a managed instance group."""
from googlecloudsdk.api_lib.compute import base_classes
from googlecloudsdk.api_lib.compute import instance_groups_utils
from googlecloudsdk.api_lib.compute import managed_instance_groups_utils
from googlecloudsdk.calliope import base
from googlecloudsdk.command_lib.compute import flags
def _AddArgs(parser, multizonal):
"""Adds args."""
parser.add_argument(
'name',
metavar='NAME',
completion_resource='compute.instanceGroupManagers',
help='Managed instance group which will no longer be autoscaled.')
if multizonal:
scope_parser = parser.add_mutually_exclusive_group()
flags.AddRegionFlag(
scope_parser,
resource_type='resources',
operation_type='delete',
explanation=flags.REGION_PROPERTY_EXPLANATION_NO_DEFAULT)
flags.AddZoneFlag(
scope_parser,
resource_type='resources',
operation_type='delete',
explanation=flags.ZONE_PROPERTY_EXPLANATION_NO_DEFAULT)
else:
flags.AddZoneFlag(
parser,
resource_type='resources',
operation_type='delete')
def _IsZonalGroup(ref):
"""Checks if reference to instance group is zonal."""
return ref.Collection() == 'compute.instanceGroupManagers'
@base.ReleaseTracks(base.ReleaseTrack.GA)
class StopAutoscaling(base_classes.BaseAsyncMutator):
"""Stop autoscaling a managed instance group."""
@property
def service(self):
return self.compute.autoscalers
@property
def resource_type(self):
return 'autoscalers'
@property
def method(self):
return 'Delete'
@staticmethod
def Args(parser):
_AddArgs(parser=parser, multizonal=False)
def CreateGroupReference(self, args):
return self.CreateZonalReference(
args.name, args.zone, resource_type='instanceGroupManagers')
def GetAutoscalerServiceForGroup(self, group_ref):
return self.compute.autoscalers
def GetAutoscalerResource(self, igm_ref, args):
autoscaler = managed_instance_groups_utils.AutoscalerForMig(
mig_name=args.name,
autoscalers=managed_instance_groups_utils.AutoscalersForLocations(
regions=None,
zones=[igm_ref.zone],
project=self.project,
compute=self.compute,
http=self.http,
batch_url=self.batch_url),
project=self.project,
scope_name=igm_ref.zone,
scope_type='zone')
if autoscaler is None:
raise managed_instance_groups_utils.ResourceNotFoundException(
'The managed instance group is not autoscaled.')
return autoscaler
def ScopeRequest(self, request, igm_ref):
request.zone = igm_ref.zone
def CreateRequests(self, args):
igm_ref = self.CreateGroupReference(args)
service = self.GetAutoscalerServiceForGroup(igm_ref)
# Assert that Instance Group Manager exists.
managed_instance_groups_utils.GetInstanceGroupManagerOrThrow(
igm_ref, self.project, self.compute, self.http, self.batch_url)
autoscaler = self.GetAutoscalerResource(igm_ref, args)
request = service.GetRequestType(self.method)(
project=self.project,
autoscaler=autoscaler.name)
self.ScopeRequest(request, igm_ref)
return [(service, self.method, request,)]
@base.ReleaseTracks(base.ReleaseTrack.BETA, base.ReleaseTrack.ALPHA)
class StopAutoscalingAlpha(StopAutoscaling):
"""Stop autoscaling a managed instance group."""
@staticmethod
def Args(parser):
_AddArgs(parser=parser, multizonal=True)
def CreateGroupReference(self, args):
return instance_groups_utils.CreateInstanceGroupReference(
scope_prompter=self, compute=self.compute, resources=self.resources,
name=args.name, region=args.region, zone=args.zone)
def GetAutoscalerServiceForGroup(self, group_ref):
if _IsZonalGroup(group_ref):
return self.compute.autoscalers
else:
return self.compute.regionAutoscalers
def GetAutoscalerResource(self, igm_ref, args):
if _IsZonalGroup(igm_ref):
scope_name = igm_ref.zone
scope_type = 'zone'
zones, regions = [scope_name], None
else:
scope_name = igm_ref.region
scope_type = 'region'
zones, regions = None, [scope_name]
autoscaler = managed_instance_groups_utils.AutoscalerForMig(
mig_name=args.name,
autoscalers=managed_instance_groups_utils.AutoscalersForLocations(
regions=regions,
zones=zones,
project=self.project,
compute=self.compute,
http=self.http,
batch_url=self.batch_url),
project=self.project,
scope_name=scope_name,
scope_type=scope_type)
if autoscaler is None:
raise managed_instance_groups_utils.ResourceNotFoundException(
'The managed instance group is not autoscaled.')
return autoscaler
def ScopeRequest(self, request, igm_ref):
if _IsZonalGroup(igm_ref):
request.zone = igm_ref.zone
else:
request.region = igm_ref.region
StopAutoscaling.detailed_help = {
'brief': 'Stop autoscaling a managed instance group',
'DESCRIPTION': """\
*{command}* stops autoscaling a managed instance group. If autoscaling
is not enabled for the managed instance group, this command does nothing and
will report an error.
""",
}
StopAutoscalingAlpha.detailed_help = StopAutoscaling.detailed_help
| [
"pooshan.vyas@gmail.com"
] | pooshan.vyas@gmail.com |
9846ac7ed6b055116e262bf86b8ee3ee14bd8f6e | edb88981aa1420af7e074068ed7818b9d904a3dd | /tags/release-0.4.2/minds/docarchive.py | 6236e76613b96b887b1e880dfc7f07115f3cece8 | [] | no_license | BackupTheBerlios/mindretrieve-svn | 101c0f1dfc25d20d5f828b6fd0d43301b773af4e | 463745fcf1c1d5b1f6c201c30bcc339c99b437ed | refs/heads/master | 2021-01-22T13:57:31.225772 | 2006-04-28T04:24:43 | 2006-04-28T04:24:43 | 40,801,743 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 6,822 | py | """Usage: docarchive [option] [id|filename]
-r read docid
-a add filename [not implemented]
"""
# todo: describe docarchive file format
# Note: id are generally added consecutively in chronical order.
# However, users are free to purge documents afterward. Therefore id
# does not necessary start from 0 nor are they necessary consecutive.
import logging
import os, os.path, sys
import re
import StringIO
import threading
import zipfile
from minds.config import cfg
from toollib import zipfile_single
log = logging.getLogger('docarc')
def parseId(id):
""" Return arc_path, filename represents by id.
e.g. id=123456789 -> $archive/123456.zip/789
Raises KeyError if malformed
"""
if not id.isdigit() or len(id) != 9:
raise KeyError, 'Invalid id: %s' % str(id)
apath = cfg.getPath('archive')
return os.path.join(apath, id[:6]+'.zip'), id[6:]
def get_document(id):
""" Return fp to the content of id.
KeyError if arc_path or filename not exist.
"""
arc_path, filename = parseId(id)
if not os.path.exists(arc_path):
raise KeyError, 'archive file does not exist %s' % arc_path
zfile = zipfile_single.ZipFile(file(arc_path,'rb'), 'r')
try:
return StringIO.StringIO(zfile.read(filename))
finally:
zfile.close()
class IdCounter(object):
def __init__(self):
self.currentIdLock = threading.Lock()
# archive status - _beginId:_endId
# None,None: uninitialized
# 0,0 : no document
# 0,1 : 1 document with id 0
# ...and so on...
self._beginId = None
self._endId = None
arc_pattern = re.compile('\d{6}.zip$')
filename_pattern = re.compile('\d{3}$')
def _findIdRange(self):
""" Scan the $archive directory for zip files for the begin and end id. """
apath = cfg.getPath('archive')
files = filter(self.arc_pattern.match, os.listdir(apath))
if not files:
self._beginId = 0
self._endId = 0
return
first_arc = min(files)
last_arc = max(files)
first = self._findId(os.path.join(apath, first_arc), min)
last = self._findId(os.path.join(apath, last_arc ), max)
self._beginId = int(first_arc[:6] + first) # would be a 9 digit id
self._endId = int(last_arc[:6] + last )+1 # would be a 9 digit id
def _findId(self, path, min_or_max):
""" return the min_or_max filename in path (as a 3 dight string) """
zfile = zipfile.ZipFile(path, 'r') # would throw BadZipfile if not a zip file
try:
files = zfile.namelist()
files = filter(self.filename_pattern.match, files) # filter invalid filename
if not files:
# This is an odd case when there is a zip but nothing inside
# (possibly some exception happened when adding to archive).
# The min and max id is arguably not correct.
return '000'
return min_or_max(files)
finally:
zfile.close()
def getNewId(self):
""" Return an unused new id. Id is in the format of 9 digit string. """
self.currentIdLock.acquire()
try:
if self._endId == None:
# This is going to be a long operation inside a
# synchronization block. Everybody is going to wait
# until the lazy initialization finish.
self._findIdRange()
log.info('Initial archive id range is %s:%s', self._beginId, self._endId)
id = '%09d' % self._endId
self._endId += 1
return id
finally:
self.currentIdLock.release()
idCounter = IdCounter()
class ArchiveHandler(object):
""" Optimize batch reading and writing by reusing opened zipfile if
possible. Must call close() at the end.
Parameter:
mode - 'r' for read and 'w' for write
Internally use 'a' instead or 'w' if zip file exist (see zipfile.ZipFile)
"""
def __init__(self, mode):
if mode not in ['r','w']:
raise ValueError, 'Invalid mode %s' % mode
self.arc_path = None
self.zfile = None
self.mode = mode
def _open(self, id):
""" Return opened zfile, filename represents id """
arc_path, filename = parseId(id)
if self.arc_path:
if self.arc_path == arc_path: # same arc_path
return self.zfile, filename # reuse opened zfile
else: # different arc_path,
self.close() # must close previously opened zfile
# It would be easier if ZipFile can use 'a' to create new archive.
# Instead do some checking first.
if self.mode == 'w' and os.path.exists(arc_path):
self.zfile = zipfile.ZipFile(arc_path, 'a', zipfile.ZIP_DEFLATED)
else:
self.zfile = zipfile.ZipFile(arc_path, self.mode, zipfile.ZIP_DEFLATED)
self.arc_path = arc_path
return self.zfile, filename
def close(self):
if self.zfile:
self.zfile.close()
self.zfile = None
self.arc_path = None
def add_document(self, id, fp):
zfile, filename = self._open(id)
try: # check if filename is in archive
zipinfo = self.zfile.getinfo(filename)
except KeyError: # good, filename not in arc
pass
else: # expect KeyError; otherwise an entry is already there
raise KeyError, 'Duplicated entry %s in %s' % (filename, self.arc_path)
self.zfile.writestr(filename, fp.read())
## cmdline testing #####################################################
def main(argv):
from minds import proxy
proxy.init(proxy.CONFIG_FILENAME)
if len(argv) <= 1:
print __doc__
idCounter._findIdRange()
print 'idRange [%s:%s]\n' % (idCounter._beginId, idCounter._endId)
if len(argv) <= 1:
sys.exit(-1)
option = argv[1]
if option == '-r':
id = argv[2]
id = ('000000000' + id)[-9:]
arc_path, filename = parseId(id)
print get_document(arc_path, filename).read()
elif option == '-a':
filename = argv[2]
print 'not implemented'
if __name__ == '__main__':
main(sys.argv) | [
"tungwaiyip@785ff9d5-dded-0310-b5f2-a5aff206d990"
] | tungwaiyip@785ff9d5-dded-0310-b5f2-a5aff206d990 |
b87b4b74514f77319ea93923b9b29886492b9b0f | b38247a5d84d8b52ce8363f8dd81629cfbe17f65 | /reagent/gym/types.py | 22a1343083ad5d4a45d47ada2cbedc2258ab611f | [
"BSD-3-Clause"
] | permissive | facebookresearch/ReAgent | 7f2b82eaaf7a19e58cc50aacc307d7b001231440 | c5f1a8371a677b4f8fb0882b600bf331eba5259d | refs/heads/main | 2023-09-05T15:56:49.175072 | 2023-08-29T21:48:40 | 2023-08-29T21:48:40 | 98,565,575 | 1,480 | 290 | BSD-3-Clause | 2023-09-12T23:09:30 | 2017-07-27T17:53:21 | Python | UTF-8 | Python | false | false | 4,660 | py | #!/usr/bin/env python3
# Copyright (c) Facebook, Inc. and its affiliates. All rights reserved.
# Please DO NOT import gym in here. We might have installation without gym depending on
# this module for typing
from abc import ABC, abstractmethod
from dataclasses import asdict, dataclass, field, fields
from typing import Any, Callable, Dict, List, Optional, Union
import numpy as np
import reagent.core.types as rlt
import torch
import torch.nn.functional as F
@dataclass
class Transition(rlt.BaseDataClass):
mdp_id: int
sequence_number: int
observation: Any
action: Any
reward: float
terminal: bool
log_prob: Optional[float] = None
possible_actions_mask: Optional[np.ndarray] = None
info: Optional[Dict] = None
# Same as asdict but filters out none values.
def asdict(self):
return {k: v for k, v in asdict(self).items() if v is not None}
def get_optional_fields(cls) -> List[str]:
"""return list of optional annotated fields"""
ret: List[str] = []
for f in fields(cls):
# Check if exactly two arguments exists and one of them are None type
if hasattr(f.type, "__args__") and type(None) in f.type.__args__:
ret.append(f.name)
return ret
@dataclass
class Trajectory(rlt.BaseDataClass):
transitions: List[Transition] = field(default_factory=list)
def __post_init__(self) -> None:
self.optional_field_exist: Dict[str, bool] = {
f: False for f in get_optional_fields(Transition)
}
def __len__(self) -> int:
return len(self.transitions)
def add_transition(self, transition: Transition) -> None:
if len(self) == 0:
# remember which optional fields should be filled
for f in self.optional_field_exist:
val = getattr(transition, f, None)
if val is not None:
self.optional_field_exist[f] = True
# check that later additions also fill the same optional fields
for f, should_exist in self.optional_field_exist.items():
val = getattr(transition, f, None)
if (val is not None) != should_exist:
raise ValueError(
f"Field {f} given val {val} whereas should_exist is {should_exist}."
)
self.transitions.append(transition)
def __getattr__(self, attr: str):
ret = []
for transition in self.transitions:
ret.append(getattr(transition, attr))
return ret
def calculate_cumulative_reward(self, gamma: float = 1.0):
"""Return (discounted) sum of rewards."""
num_transitions = len(self)
assert num_transitions > 0, "called on empty trajectory"
rewards = self.reward
discounts = [gamma**i for i in range(num_transitions)]
return sum(reward * discount for reward, discount in zip(rewards, discounts))
def to_dict(self):
d = {"action": F.one_hot(torch.from_numpy(np.stack(self.action)), 2)}
for f in [
"observation",
"reward",
"terminal",
"log_prob",
"possible_actions_mask",
]:
if self.optional_field_exist.get(f, True):
f_value = getattr(self, f)
if np.isscalar(f_value[0]):
# scalar values
d[f] = torch.tensor(f_value)
else:
# vector values, need to stack
d[f] = torch.from_numpy(np.stack(f_value)).float()
return d
class Sampler(ABC):
"""Given scores, select the action."""
@abstractmethod
def sample_action(self, scores: Any) -> rlt.ActorOutput:
raise NotImplementedError()
@abstractmethod
def log_prob(self, scores: Any, action: torch.Tensor) -> torch.Tensor:
raise NotImplementedError()
def update(self) -> None:
"""Call to update internal parameters (e.g. decay epsilon)"""
pass
# From preprocessed observation, produce scores for sampler to select action
DiscreteScorer = Callable[[Any, Optional[torch.Tensor]], Any]
ContinuousScorer = Callable[[Any], Any]
Scorer = Union[DiscreteScorer, ContinuousScorer]
# Transform ReplayBuffer's transition batch to trainer.train
TrainerPreprocessor = Callable[[Any], Any]
""" Called after env.step(action)
Args: (state, action, reward, terminal, log_prob)
"""
PostStep = Callable[[Transition], None]
""" Called after end of episode
"""
PostEpisode = Callable[[Trajectory, Dict], None]
@dataclass
class GaussianSamplerScore(rlt.BaseDataClass):
loc: torch.Tensor
scale_log: torch.Tensor
| [
"facebook-github-bot@users.noreply.github.com"
] | facebook-github-bot@users.noreply.github.com |
1118d813dbd043ad6b96b0b5ec0f378d73157bfc | 876672868996f0da96c5db39fe44dc1a13354bd8 | /557. Reverse Words in a String III.py | e700691d5be1d4761a2d617fac5ddd22f0e4ea00 | [] | no_license | eekstunt/leetcode | f9958cb18d537c149316370ec1acdfaefa20b4df | 3bff096b1cb6a8abc887c6de36beb92bd0ee4fc3 | refs/heads/master | 2022-04-20T17:08:33.413691 | 2020-04-18T17:58:56 | 2020-04-18T17:58:56 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 181 | py | # https://leetcode.com/problems/reverse-words-in-a-string-iii/
class Solution:
def reverseWords(self, s: str) -> str:
return ' '.join(word[::-1] for word in s.split())
| [
"you@example.com"
] | you@example.com |
7dd4464fdcffe881ff7e78bbd9d0185e32a1e30d | 574af23550bed50fdf9cfa205d7a063131f332a0 | /scripts/migrate_to_json_graph.py | 6d7d5b9a36c5ec3754c1069a6b7165ecd09eeb5d | [
"MIT",
"BSD-3-Clause"
] | permissive | setu4993/cf-scripts | db8015b499090dd0923dcf0192ee85ec29ee037f | 315187e2f25de4e3bc157ea1ac0f7f4d9b22a680 | refs/heads/master | 2020-09-25T13:34:47.659245 | 2019-12-11T17:04:48 | 2019-12-11T17:04:48 | 226,014,246 | 0 | 0 | NOASSERTION | 2019-12-05T04:13:44 | 2019-12-05T04:13:43 | null | UTF-8 | Python | false | false | 132 | py | import networkx as nx
from conda_forge_tick.utils import dump_graph
gx = nx.read_gpickle('graph.pkl')
dump_graph(gx, 'graph.json')
| [
"cjwright4242@gmail.com"
] | cjwright4242@gmail.com |
824b5ecadedca94aef264f6fdec1628f4f0cb0ae | 07570ec33eb49effd9ed6af73214bac1b607038f | /client/swagger_client/models/certificate_list.py | 2586693e77e82e23c1bdd2d6d8c8954090aea0de | [
"MIT"
] | permissive | kakwa/certascale | d9998a66ba6a239ba5b5e537f12dabdd5876996c | 0df8da0f518506500117152fd0e28ee3286949af | refs/heads/master | 2020-03-29T09:24:32.794060 | 2019-01-30T14:06:10 | 2019-01-30T14:06:10 | 149,756,729 | 0 | 2 | null | null | null | null | UTF-8 | Python | false | false | 3,618 | py | # coding: utf-8
"""
certascale API
Certascale API documentation # noqa: E501
OpenAPI spec version: 1.0.0
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
from swagger_client.models.certificate import Certificate # noqa: F401,E501
class CertificateList(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 = {
'list': 'list[Certificate]',
'next_id': 'int'
}
attribute_map = {
'list': 'list',
'next_id': 'next_id'
}
def __init__(self, list=None, next_id=None): # noqa: E501
"""CertificateList - a model defined in Swagger""" # noqa: E501
self._list = None
self._next_id = None
self.discriminator = None
if list is not None:
self.list = list
if next_id is not None:
self.next_id = next_id
@property
def list(self):
"""Gets the list of this CertificateList. # noqa: E501
:return: The list of this CertificateList. # noqa: E501
:rtype: list[Certificate]
"""
return self._list
@list.setter
def list(self, list):
"""Sets the list of this CertificateList.
:param list: The list of this CertificateList. # noqa: E501
:type: list[Certificate]
"""
self._list = list
@property
def next_id(self):
"""Gets the next_id of this CertificateList. # noqa: E501
:return: The next_id of this CertificateList. # noqa: E501
:rtype: int
"""
return self._next_id
@next_id.setter
def next_id(self, next_id):
"""Sets the next_id of this CertificateList.
:param next_id: The next_id of this CertificateList. # noqa: E501
:type: int
"""
self._next_id = next_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
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, CertificateList):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
| [
"carpentier.pf@gmail.com"
] | carpentier.pf@gmail.com |
da52add81fd37baf4e24e436f0f4ab153c120bd5 | 52568cd3aca3faeb59dd21511020d9bcf004c2f1 | /Phase2/Week5/5.4-webtrader-updated/web_trader/run/lib/bin/easy_install-3.5 | 6309451187957ee68b20ed0853b48e2bb12712e2 | [] | no_license | gabrielvtan/ByteAcademy-FullStack | 0472b57faf4d903cd1bd5e53789747b77120648e | 0317d29464559f1aa2904229fadbfb55f2317af4 | refs/heads/master | 2022-12-11T15:04:54.769251 | 2018-11-02T17:54:49 | 2018-11-02T17:54:49 | 148,703,931 | 2 | 1 | null | 2022-11-22T01:06:29 | 2018-09-13T22:12:21 | Python | UTF-8 | Python | false | false | 260 | 5 | #!/home/kenso/web_trader/run/lib/bin/python3
# -*- coding: utf-8 -*-
import re
import sys
from setuptools.command.easy_install import main
if __name__ == '__main__':
sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0])
sys.exit(main())
| [
"gabriel.v.tan@gmail.com"
] | gabriel.v.tan@gmail.com |
6bbe882811dcb39c98a7a58fd9cc5cf75366df5a | 7f52845b5aca331ac200565f897b2b1ba3aa79d9 | /m251/exp_groups/paper/nlp/intermediate_hf/launch/launch_merge.py | cc08f799d18321b4e1506eabebbcc848c67fca1b | [] | no_license | mmatena/m251 | f8fb4ba9c10cd4dfcf5ee252f80e4832e4e86aa0 | e23249cf0896c5b42bcd07de70f7b9996d8b276b | refs/heads/master | 2023-05-06T10:44:10.945534 | 2021-06-03T15:07:29 | 2021-06-03T15:07:29 | 321,217,654 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,698 | py | """
export PYTHONPATH=$PYTHONPATH:~/Desktop/projects/m251:~/Desktop/projects/del8
python3 m251/exp_groups/paper/nlp/intermediate_hf/launch/launch_merge.py
"""
from del8.executors.gce import gce
from del8.executors.vastai import vastai
from del8.executors.vastai import api_wrapper
from m251.exp_groups.paper.nlp.intermediate_hf import merge
# EXP = merge.Merge_BertBase_Pairs
# EXP = merge.Merge_BertBaseFromMnli_Pairs
# EXP = merge.Merge_BertBaseFromMnli_SquadDonor_4096
# EXP = merge.Merge_BertBase_SquadDonor_4096
# EXP = merge.Merge_BertBaseFromMnli_SquadDonor_1024
# EXP = merge.Merge_BertBase_HighResource_SquadDonor_4096
# EXP = merge.Merge_BertBase_RteHoldout_LastCkpt
# EXP = merge.Merge_BertBase_RteHoldout_LastCkpt2
# EXP = merge.Merge_BertBase_RteHoldout_LastCkpt50
# EXP = merge.DummyMerge_BertBase_Pairs
# EXP = merge.DummyMerge_BertBaseFromMnli_Pairs
execution_items = []
EXP = merge.DummyMerge_BertBaseFromMnli_SquadDonor_4096
execution_items.extend(EXP.create_all_execution_items())
EXP = merge.DummyMerge_BertBase_SquadDonor_4096
execution_items.extend(EXP.create_all_execution_items())
EXP = merge.DummyMerge_BertBase_HighResource_SquadDonor_4096
execution_items.extend(EXP.create_all_execution_items())
# execution_items = EXP.create_all_execution_items()
print(f"Number of execution items to process: {len(execution_items)}")
vast_params = vastai.create_supervisor_params(
EXP,
execution_items=execution_items,
num_workers=8,
offer_query=vastai.OfferQuery(
queries_str=" ".join(
[
"reliability > 0.95",
"num_gpus=1",
"dph < 2.25",
"inet_down > 100",
"inet_up > 75",
# "gpu_ram >= 10",
# "dlperf >= 16",
"cuda_vers >= 11.0 has_avx = true",
]
),
order_str="dlperf_usd-",
),
disk_gb=16,
image="tensorflow/tensorflow:2.4.0-gpu",
)
offers = api_wrapper.query_offers(vast_params)
print(f"Number of acceptable offers: {len(offers)}")
launch_params = gce.GceParams()
node, deploy = gce.launch(execution_items, vast_params, launch_params)
#
#
#
###############################################################################
# Stages of testing:
###############################################################################
# if True:
# from del8.core.execution import entrypoint
# from del8.storages.gcp import gcp
# gcp.PERSISTENT_CACHE = True
# EXP.to_dev_mode()
# execution_items = EXP.create_all_execution_items()
# print(f'Number of execution items to process: {len(execution_items)}')
# entrypoint.worker_run(**execution_items[0].worker_run_kwargs)
| [
"michael.matena@gmail.com"
] | michael.matena@gmail.com |
c56a454c10c2d14f2ef6ba96e577d2d45f93969c | e663909cec3c4eda12bb705fce9a6dc901bb7d88 | /爬虫/day06 鼠标操作/code/seleniumtest_16_按键.py | 4dd0d6edad17eba87b125eeab8e8ced153c844e6 | [] | no_license | 1284753334/learning2 | a03f293965a652883503cae420d8b1ad11ae6661 | f2fcb3c856656cc8427768b41add3ee083487592 | refs/heads/master | 2023-01-30T23:18:26.951210 | 2020-12-20T15:57:18 | 2020-12-20T15:57:18 | 315,065,804 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 1,981 | py | # _ooOoo_
# o8888888o
# 88" . "88
# (| -_- |)
# O\ = /O
# ____/`---'\____
# .' \\| |// `.
# / \\||| : |||// \
# / _||||| -:- |||||- \
# | | \\\ - /// | |
# | \_| ''\---/'' | |
# \ .-\__ `-` ___/-. /
# ___`. .' /--.--\ `. . __
# ."" '< `.___\_<|>_/___.' >'"".
# | | : `- \`.;`\ _ /`;.`/ - ` : | |
# \ \ `-. \_ __\ /__ _/ .-` / /
# ======`-.____`-.___\_____/___.-`____.-'======
# `=---='
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
# 佛祖保佑 永无BUG
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
# 要想调用键盘按键操作需要引入 keys 包
from selenium.webdriver.common.keys import Keys
from time import sleep
driver = webdriver.Chrome()
driver.implicitly_wait(10)
driver.maximize_window()
driver.get('http://sahitest.com/demo/keypress.htm')
key_up_radio = driver.find_element_by_id('r1') # 监测按键升起
key_down_radio = driver.find_element_by_id('r2') # 监测按键按下
key_press_radio = driver.find_element_by_id('r3') # 监测按键按下升起
enter = driver.find_elements_by_xpath('//form[@name="f1"]/input')[1] # 输入框
result = driver.find_elements_by_xpath('//form[@name="f1"]/input')[0] # 监测结果
sleep(5)
# 监测 key_down
key_down_radio.click()
ActionChains(driver).key_down(Keys.CONTROL, enter).key_up(Keys.CONTROL).perform()
print(result.get_attribute('value'))
sleep(5)
# 监测 key_up
key_up_radio.click()
enter.click()
ActionChains(driver).key_down(Keys.SHIFT).key_up(Keys.SHIFT).perform()
print(result.get_attribute('value'))
# 监测 key_press
sleep(5)
key_press_radio.click()
enter.click()
ActionChains(driver).send_keys('a').perform()
print(result.get_attribute('value'))
sleep(5)
driver.quit()
| [
"huapenghui@git.com"
] | huapenghui@git.com |
bc18ab4f6f5f1d9b7afd1cc6ca0f98ab5d45e733 | 6490651cbbeb75e45974476dfacd9bd224e535f5 | /setup.py | 061e67e604b1dbdba53b9b68ae34cd227a26a0ef | [
"ZPL-2.1"
] | permissive | ajmitch/waitress | e1c5c4ffdb7ba6d3382afab70244e88ccb8cb4e2 | 5b73ec67e8bb99152f4113c98b586846dcb3dd55 | refs/heads/master | 2021-01-18T09:05:00.798542 | 2012-01-06T06:26:06 | 2012-01-06T06:26:06 | 3,114,643 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,350 | py | ##############################################################################
#
# Copyright (c) 2006 Zope Foundation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.1 (ZPL). A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
import os
from setuptools import setup, find_packages
here = os.path.abspath(os.path.dirname(__file__))
try:
README = open(os.path.join(here, 'README.rst')).read()
CHANGES = open(os.path.join(here, 'CHANGES.txt')).read()
except IOError:
README = CHANGES = ''
setup(
name='waitress',
version='0.5',
author='Zope Foundation and Contributors',
author_email='zope-dev@zope.org',
maintainer="Chris McDonough",
maintainer_email="chrism@plope.com",
description='Waitress WSGI server',
long_description = README +'\n\n' + CHANGES,
license='ZPL 2.1',
keywords='waitress wsgi server http',
classifiers = [
'Development Status :: 5 - Production/Stable',
'Environment :: Web Environment',
'Intended Audience :: Developers',
'License :: OSI Approved :: Zope Public License',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
"Programming Language :: Python :: Implementation :: CPython",
"Programming Language :: Python :: Implementation :: PyPy",
'Natural Language :: English',
'Operating System :: OS Independent',
'Topic :: Internet :: WWW/HTTP',
],
url='https://github.com/Pylons/waitress',
packages=find_packages(),
install_requires=[
'setuptools',
],
include_package_data=True,
test_suite='waitress',
zip_safe=False,
entry_points="""
[paste.server_runner]
main = waitress:serve_paste
"""
)
| [
"chrism@plope.com"
] | chrism@plope.com |
d6e05b5fd8b827e3e237c651b0d26ce6266e2e74 | 80052e0cbfe0214e4878d28eb52009ff3054fe58 | /e2yun_addons/odoo12/wx_tools/basewechat/wxclient.py | cbd74df32bc848f61bcd363947cca1dbf1e7fda9 | [] | no_license | xAlphaOmega/filelib | b022c86f9035106c24ba806e6ece5ea6e14f0e3a | af4d4b079041f279a74e786c1540ea8df2d6b2ac | refs/heads/master | 2021-01-26T06:40:06.218774 | 2020-02-26T14:25:11 | 2020-02-26T14:25:11 | 243,349,887 | 0 | 2 | null | 2020-02-26T19:39:32 | 2020-02-26T19:39:31 | null | UTF-8 | Python | false | false | 2,795 | py | # -*-coding:utf-8-*-
import logging
import time
import requests
from requests.compat import json as _json
from wechatpy.constants import WeChatErrorCode
from werobot.client import Client
from werobot.client import check_error
logger = logging.getLogger(__name__)
class WxClient(Client):
def request(self, method, url, **kwargs):
if "params" not in kwargs:
kwargs["params"] = {"access_token": self.token}
if isinstance(kwargs.get("data", ""), dict):
body = _json.dumps(kwargs["data"], ensure_ascii=False)
body = body.encode('utf8')
kwargs["data"] = body
r = requests.request(method=method, url=url, **kwargs)
r.raise_for_status()
r.encoding = "utf-8"
json = r.json()
if 'errcode' in json:
json['errcode'] = int(json['errcode'])
if 'errcode' in json and json['errcode'] != 0:
errcode = json['errcode']
errmsg = json.get('errmsg', errcode)
if errcode in (
WeChatErrorCode.INVALID_CREDENTIAL.value,
WeChatErrorCode.INVALID_ACCESS_TOKEN.value,
WeChatErrorCode.EXPIRED_ACCESS_TOKEN.value):
logger.info('Access token expired, fetch a new one and retry request')
self.session.delete(self.access_token_key)
self.get_access_token()
access_token = self.session.get(self.access_token_key)
logger.info('get new token %s' % access_token)
kwargs["params"] = {"access_token": access_token}
return super(WxClient, self).request(method=method, url=url, **kwargs)
else:
if check_error(json):
return json
if check_error(json):
return json
def get_access_token(self):
"""
重写有保存token
:return: 返回token
"""
self.token_expires_at = self.session.get(self.access_token_key_expires_at)
self._token = self.session.get(self.access_token_key)
if self._token and self.token_expires_at:
now = time.time()
if self.token_expires_at - now > 60:
return self._token
json = self.grant_token()
self._token = json["access_token"]
self.token_expires_at = int(time.time()) + json["expires_in"]
self.session.set(self.access_token_key, self._token)
self.session.set(self.access_token_key_expires_at, self.token_expires_at)
return self._token
@property
def access_token_key(self):
return '{0}_access_token'.format(self.appid)
@property
def access_token_key_expires_at(self):
return '{0}_access_token__expires_at'.format(self.appid)
| [
"hepeng1@163.com"
] | hepeng1@163.com |
1729264e68e90f6adaf2e02e1f8aa993275afdc4 | 6b2a8dd202fdce77c971c412717e305e1caaac51 | /solutions_5648941810974720_0/Python/kmwho/A.py | 277ac8dd0919a4ab3da742054999cbdc87dbe0d8 | [] | 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 | 882 | py | #! /usr/bin/python
# kmwho
# CodeJam 2016 1A
from __future__ import print_function
import numpy as np
import math
def solvecase():
s = input().strip()
alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
count = { c:0 for c in alpha }
nums = [ "ZERO", "ONE", "TWO", "THREE", "FOUR", "FIVE", "SIX", "SEVEN", "EIGHT", "NINE" ]
digits = []
for c in s:
count[c] += 1
A = np.matrix(np.zeros( (26,10) ))
for r in range(26):
for c in range(10):
A[r,c] = nums[c].count( chr(ord("A") + r ) )
b = [ count[c] for c in alpha ]
X = (A.I).dot(b)
digitCount = [ int(round(d)) for d in X.flat ]
digits = []
for d in range(10):
for x in range(digitCount[d]):
digits.append( str(d) )
return "".join(digits)
def solve():
T = int(input())
for t in range(1,T+1):
res = solvecase()
print( "Case #" + str(t) + ": " + str(res) )
def main():
solve()
main()
| [
"alexandra1.back@gmail.com"
] | alexandra1.back@gmail.com |
49b2cbe91dcf58a52a374da8f48ca4f24ba256a6 | 3649308c5d709100c4dc90e661fc9f564f184877 | /ocs/student/migrations/0002_auto_20200111_1925.py | 770b71e5b1126d729d0198e2d85b190c07d318af | [] | no_license | anirudhasj441/django | 54171f6141d6938201146a6d3e9475477a3f0078 | 5bb202d13d4b17daca9aedf3b213908c3245757b | refs/heads/master | 2021-07-09T06:18:11.597848 | 2021-03-07T17:58:32 | 2021-03-07T17:58:32 | 230,616,005 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 433 | py | # Generated by Django 3.0.1 on 2020-01-11 13:55
import datetime
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('student', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='assigments',
name='date',
field=models.DateField(default=datetime.date(2020, 1, 11)),
),
]
| [
"anirudhasj441@gmail.com"
] | anirudhasj441@gmail.com |
f469a19b6eda6cb3a39531b0281881165cae515c | afaa3270ee705ba511b484c7d84377d31e3533f4 | /client/commands/restart.py | 583766107e2b0fa048c36da50f01fb475648a874 | [
"MIT"
] | permissive | moneytech/pyre-check | b6cfe99d9c2bdb3cf3d3a33c2534e2e70d391085 | dae90bee716fc1c3f2e9d9c0496e5cdd14c99701 | refs/heads/master | 2022-12-14T22:46:54.864244 | 2020-09-09T17:25:53 | 2020-09-09T17:27:29 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 4,640 | py | # 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 argparse
from typing import Optional
from ..analysis_directory import AnalysisDirectory, resolve_analysis_directory
from ..configuration import Configuration
from .command import Command, CommandArguments, ExitCode, IncrementalStyle
from .incremental import Incremental
from .start import Start # noqa
from .stop import Stop
class Restart(Command):
NAME = "restart"
def __init__(
self,
command_arguments: CommandArguments,
original_directory: str,
*,
configuration: Optional[Configuration] = None,
analysis_directory: Optional[AnalysisDirectory] = None,
terminal: bool,
store_type_check_resolution: bool,
use_watchman: bool,
incremental_style: IncrementalStyle,
) -> None:
super(Restart, self).__init__(
command_arguments, original_directory, configuration, analysis_directory
)
self._terminal: bool = terminal
self._store_type_check_resolution: bool = store_type_check_resolution
self._use_watchman: bool = use_watchman
self._incremental_style: IncrementalStyle = incremental_style
@staticmethod
def from_arguments(
arguments: argparse.Namespace,
original_directory: str,
configuration: Optional[Configuration] = None,
analysis_directory: Optional[AnalysisDirectory] = None,
) -> "Restart":
return Restart(
CommandArguments.from_arguments(arguments),
original_directory,
configuration=configuration,
analysis_directory=analysis_directory,
terminal=arguments.terminal,
store_type_check_resolution=arguments.store_type_check_resolution,
use_watchman=not arguments.no_watchman,
incremental_style=arguments.incremental_style,
)
@classmethod
def add_subparser(cls, parser: argparse._SubParsersAction) -> None:
restart = parser.add_parser(
cls.NAME, epilog="Restarts a server. Equivalent to `pyre stop && pyre`."
)
restart.set_defaults(command=cls.from_arguments)
restart.add_argument(
"--terminal", action="store_true", help="Run the server in the terminal."
)
restart.add_argument(
"--store-type-check-resolution",
action="store_true",
help="Store extra information for `types` queries.",
)
restart.add_argument(
"--no-watchman",
action="store_true",
help="Do not spawn a watchman client in the background.",
)
restart.add_argument(
"--incremental-style",
type=IncrementalStyle,
choices=list(IncrementalStyle),
default=IncrementalStyle.FINE_GRAINED,
help="How to approach doing incremental checks.",
)
def generate_analysis_directory(self) -> AnalysisDirectory:
return resolve_analysis_directory(
self._command_arguments.source_directories,
self._command_arguments.targets,
self._configuration,
self._original_directory,
self._project_root,
filter_directory=self._command_arguments.filter_directory,
buck_mode=self._command_arguments.buck_mode,
relative_local_root=self._configuration.relative_local_root,
)
def _run(self) -> None:
exit_code = (
Stop(
self._command_arguments,
self._original_directory,
configuration=self._configuration,
analysis_directory=self._analysis_directory,
from_restart=True,
)
.run()
.exit_code()
)
if exit_code != ExitCode.SUCCESS:
self._exit_code = ExitCode.FAILURE
return
exit_code = (
Incremental(
self._command_arguments,
self._original_directory,
configuration=self._configuration,
analysis_directory=self._analysis_directory,
# Force the incremental run to be blocking.
nonblocking=False,
incremental_style=self._incremental_style,
no_start_server=False,
no_watchman=not self._use_watchman,
)
.run()
.exit_code()
)
self._exit_code = exit_code
| [
"facebook-github-bot@users.noreply.github.com"
] | facebook-github-bot@users.noreply.github.com |
0882dede30a8e3d97273c8afa447882ce630c447 | 9b50b3a7dda2711c5665909f6801249de53e70f6 | /0x03-python-data_structures/3-print_reversed_list_integer.py | 49d1b256e98d2d1174d1faa6a47f2f766d9695ad | [] | no_license | nikolasribeiro/holbertonschool-higher_level_programming | 3119e5442887f06da104dc8aa93df371f92b9f2b | 7dcdf081d8a57ea1f5f6f9830555f73bf2ae6993 | refs/heads/main | 2023-04-21T05:22:03.617609 | 2021-05-05T11:38:51 | 2021-05-05T11:38:51 | 319,198,337 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 182 | py | #!/usr/bin/python3
def print_reversed_list_integer(my_list=[]):
if isinstance(my_list, list):
for element in reversed(my_list):
print("{:d}".format(element))
| [
"nikolasribeiro2@outlook.com"
] | nikolasribeiro2@outlook.com |
0e582df943dd67cd17d19d44d5333d5eae4c2c83 | 7b74696ff2ab729396cba6c203984fce5cd0ff83 | /tradeaccounts/migrations/0019_auto_20200521_1511.py | cab75d17d845a2269e5dfa7899ae5acd158132b6 | [
"MIT"
] | permissive | webclinic017/investtrack | e9e9a7a8caeecaceebcd79111c32b334c4e1c1d0 | 4aa204b608e99dfec3dd575e72b64a6002def3be | refs/heads/master | 2023-06-18T12:57:32.417414 | 2021-07-10T14:26:53 | 2021-07-10T14:26:53 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 519 | py | # Generated by Django 3.0.2 on 2020-05-21 07:11
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('tradeaccounts', '0018_auto_20200520_1603'),
]
operations = [
migrations.AlterField(
model_name='tradeaccountsnapshot',
name='applied_period',
field=models.CharField(blank=True, choices=[('d', '日'), ('w', '周'), ('m', '月')], default='d', max_length=1, verbose_name='收益周期'),
),
]
| [
"jie.han@outlook.com"
] | jie.han@outlook.com |
88342e7dee0c043519626340d3fe5daff980f706 | 90ca69d5d6bd9d08ee2d2b8150eb2fa6a6b00e72 | /src/services/tokenize/bert_tokenize_service.py | 5ba2812727be96c4859db73377c88ee44b9dcca2 | [
"CC-BY-4.0"
] | permissive | budh333/UnSilence_VOC | 07a4a5a58fd772230bfe1ffbcb8407de89daa210 | f6ba687f96f2c23690c84590adcb24ee239aa86b | refs/heads/main | 2023-05-26T20:49:49.105492 | 2023-05-12T23:18:50 | 2023-05-12T23:18:50 | 388,462,045 | 6 | 1 | null | null | null | null | UTF-8 | Python | false | false | 2,829 | py | import os
from typing import Tuple, List
from overrides import overrides
from tokenizers import BertWordPieceTokenizer
from tokenizers.implementations import ByteLevelBPETokenizer
from tokenizers.processors import BertProcessing
import sentencepiece as spm
from enums.configuration import Configuration
from services.arguments.pretrained_arguments_service import PretrainedArgumentsService
from services.tokenize.base_tokenize_service import BaseTokenizeService
from services.file_service import FileService
class BERTTokenizeService(BaseTokenizeService):
def __init__(
self,
arguments_service: PretrainedArgumentsService,
file_service: FileService):
super().__init__()
self._arguments_service = arguments_service
self._file_service = file_service
pretrained_weights = self._arguments_service.pretrained_weights
configuration = self._arguments_service.configuration
vocabulary_path = os.path.join(self._arguments_service.data_folder, 'vocabularies', f'{pretrained_weights}-vocab.txt')
if not os.path.exists(vocabulary_path):
raise Exception(f'Vocabulary not found in {vocabulary_path}')
self._tokenizer: BertWordPieceTokenizer = BertWordPieceTokenizer(vocabulary_path, lowercase=False)
@overrides
def encode_tokens(self, tokens: List[str]) -> List[int]:
result = [self._tokenizer.token_to_id(x) for x in tokens]
return result
@overrides
def decode_tokens(self, character_ids: List[int]) -> List[str]:
result = [self._tokenizer.id_to_token(
character_id) for character_id in character_ids]
return result
@overrides
def decode_string(self, character_ids: List[int]) -> List[str]:
result = self._tokenizer.decode(character_ids)
return result
@overrides
def id_to_token(self, character_id: int) -> str:
result = self._tokenizer.id_to_token(character_id)
return result
@overrides
def encode_sequence(self, sequence: str) -> Tuple[List[int], List[str], List[Tuple[int,int]], List[int]]:
encoded_representation = self._tokenizer.encode(sequence)
return (
encoded_representation.ids,
encoded_representation.tokens,
encoded_representation.offsets,
encoded_representation.special_tokens_mask)
@overrides
def encode_sequences(self, sequences: List[str]) -> List[Tuple[List[int], List[str], List[Tuple[int,int]], List[int]]]:
encoded_representations = self._tokenizer.encode_batch(sequences)
return [(x.ids, x.tokens, x.offsets, x.special_tokens_mask) for x in encoded_representations]
@property
@overrides
def vocabulary_size(self) -> int:
return self._tokenizer.get_vocab_size() | [
"kztodorov@outlook.com"
] | kztodorov@outlook.com |
9d69ca141cb222bcaaadafbd4cec3717e860a907 | 1f73dc7507361ba35ebecd70635a797bc408414c | /py/15.py | bcee4c3f9ec5137e45e54fffd375e0e776d7c473 | [] | no_license | permCoding/speedCoding-01-solutions | e8b1043209b1c431b9fdb86e2c265b48fb82ef5b | bf62b77abe9f69486412a7f595c1cf54416479b0 | refs/heads/master | 2020-11-27T10:44:03.555157 | 2019-12-23T16:01:23 | 2019-12-23T16:01:23 | 229,408,709 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 187 | py | n, k = map(int, input().split())
def get(N, K):
if K == 0:
return 1 if N == 0 else 0
if N == 0:
return 0
return get(N-1, K-1) + get(N+1, K-1)
print(get(n,k)) | [
"ttxiom@gmail.com"
] | ttxiom@gmail.com |
3df7bcb85dba0398b40efa4868900a6dedc22f36 | 46f44f80d63c13fcb61dacf7e08d072fb85b58dc | /MostCommonQuestions/25.removeDuplicates.py | 02be555260fd9c852cab5e001f86f55ccc452660 | [] | no_license | bzamith/MySDEInterviewStudies | ef6d7add97596bded460023a74ba8b77dcebf350 | 9eea12cc8da3f51532140ed9423ce2a8be9fbdfa | refs/heads/master | 2023-02-25T11:41:28.877263 | 2021-02-01T10:51:48 | 2021-02-01T10:51:48 | 265,734,795 | 12 | 3 | null | 2020-10-05T22:21:57 | 2020-05-21T02:25:15 | Python | UTF-8 | Python | false | false | 861 | py | # Source: https://leetcode.com/problems/remove-duplicates-from-sorted-array/
# Problem: "Remove Duplicates from Sorted Array in Place"
# Example:
# Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length.
# Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
# Approach:
# Two-pointers approach
# Complexity:
# O(N) time
# O(1) space
def removeDuplicates(nums):
count = 0
if len(nums) < 2:
return nums
for i in range(1,len(nums)):
if nums[i] == nums[i-1]:
count += 1
else:
nums[i-count] = nums[i]
return nums[0:len(nums) - count]
if __name__ == "__main__":
print(removeDuplicates([0,0,0,1,1,2,3]))
print(removeDuplicates([0,0,1,2,3,3]))
| [
"noreply@github.com"
] | bzamith.noreply@github.com |
aecea41605b5c7d5084faa397fb616fd19c5d700 | ca7aa979e7059467e158830b76673f5b77a0f5a3 | /Python_codes/p04034/s271062170.py | 060f9afcca29c5ceddf8d3a1e05771040ec30d15 | [] | 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 | 532 | py | n , m = map(int,input().split())
aka = [False for i in range(n+1)]
kazu = [1 for i in range(n+1)]
aka[1] = True
for i in range(m):
x , y = map(int,input().split())
if aka[x]:
if kazu[x] >= 2:
kazu[x] -= 1
kazu[y] += 1
elif kazu[x] == 1:
kazu[x] -= 1
kazu[y] += 1
aka[x] = False
aka[y] = True
elif not aka[x]:
kazu[x] -= 1
kazu[y] += 1
ans = 0
for i in range(1,n+1):
if aka[i]:
ans += 1
print(ans) | [
"66529651+Aastha2104@users.noreply.github.com"
] | 66529651+Aastha2104@users.noreply.github.com |
160e3ccd0c300c7b7c98b3eb1be6c6e1a5a2e933 | a19275ff09caf880e135bce76dc7a0107ec0369e | /catkin_ws/debug/robot_description/finger/catkin_generated/pkg.installspace.context.pc.py | c4fd6b10ed6dbe9469307a4ec0862a977ae7b65f | [] | no_license | xtyzhen/Multi_arm_robot | e201c898a86406c1b1deb82326bb2157d5b28975 | 15daf1a80c781c1c929ba063d779c0928a24b117 | refs/heads/master | 2023-03-21T14:00:24.128957 | 2021-03-10T12:04:36 | 2021-03-10T12:04:36 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 350 | py | # generated from catkin/cmake/template/pkg.context.pc.in
CATKIN_PACKAGE_PREFIX = ""
PROJECT_PKG_CONFIG_INCLUDE_DIRS = "".split(';') if "" != "" else []
PROJECT_CATKIN_DEPENDS = "".replace(';', ' ')
PKG_CONFIG_LIBRARIES_WITH_PREFIX = "".split(';') if "" != "" else []
PROJECT_NAME = "finger"
PROJECT_SPACE_DIR = "/usr/local"
PROJECT_VERSION = "1.2.5"
| [
"qyz146006@163.com"
] | qyz146006@163.com |
f9ccc381f1d82dbbce7caa871d0b8a5a18779e15 | 85e89ff0a842c74c5bae220ed694bdbc3e4eba8e | /src/sploitego/transforms/dnsptrlookup.py | b01aa10f9f0b9111301d8d6d8dcc1f87c708e41e | [] | no_license | AAG-SATIEDN/sploitego | ff368ea1e432720c0346fee1805d6b9f76b7b35f | 36fa21485fbe44f14406921aa267762bb4f07bd9 | refs/heads/master | 2021-01-18T03:47:54.068637 | 2014-04-20T02:50:22 | 2014-04-20T02:50:22 | 20,336,835 | 2 | 0 | null | null | null | null | UTF-8 | Python | false | false | 947 | py | #!/usr/bin/env python
from canari.maltego.configuration import BuiltInTransformSets
from canari.maltego.entities import IPv4Address
from canari.framework import configure
from common.entities import IPv6Address
from common.dnstools import nslookup
__author__ = 'Nadeem Douba'
__copyright__ = 'Copyright 2012, Sploitego Project'
__credits__ = []
__license__ = 'GPL'
__version__ = '0.2'
__maintainer__ = 'Nadeem Douba'
__email__ = 'ndouba@gmail.com'
__status__ = 'Development'
__all__ = [
'dotransform'
]
@configure(
label='To DNS Name [DNS]',
description='This transform will fetch the DNS records for a IP address.',
uuids=[ 'sploitego.v2.IPv4AddressToDNSName_DNS', 'sploitego.v2.IPv6AddressToDNSName_DNS' ],
inputs=[ ( BuiltInTransformSets.DNSFromIP, IPv4Address ), ( BuiltInTransformSets.DNSFromIP, IPv6Address ) ]
)
def dotransform(request, response):
nslookup(request.value, 'PTR', response)
return response | [
"ndouba@gmail.com"
] | ndouba@gmail.com |
9c419118452f3d974399ac2367cfc9aead99c6fe | 329581f12d816a79a9b1bf90c8e0e038697f4e92 | /stark/venv/lib/python2.7/site-packages/django/core/mail/message.py | 29dd52d6d7e7a8ce2bd9ce0eb3c28878080d3a35 | [] | no_license | syfad/code | 343dcb510dded4e9dfb4335e2bb1ae80a5b51db7 | b7b5cb90025ba6947222e4987c74f3efe5ffb248 | refs/heads/master | 2021-06-04T13:52:33.746402 | 2020-07-28T04:11:37 | 2020-07-28T04:11:37 | 51,892,476 | 2 | 0 | null | 2017-09-18T11:00:18 | 2016-02-17T03:46:03 | Python | UTF-8 | Python | false | false | 19,479 | py | from __future__ import unicode_literals
import mimetypes
import os
import random_num
import time
from email import (
charset as Charset, encoders as Encoders, generator, message_from_string,
)
from email.header import Header
from email.message import Message
from email.mime.base import MIMEBase
from email.mime.message import MIMEMessage
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.utils import formatdate, getaddresses, parseaddr
from io import BytesIO
from django.conf import settings
from django.core.mail.utils import DNS_NAME
from django.utils import six
from django.utils.encoding import force_text
# Don't BASE64-encode UTF-8 messages so that we avoid unwanted attention from
# some spam filters.
utf8_charset = Charset.Charset('utf-8')
utf8_charset.body_encoding = None # Python defaults to BASE64
utf8_charset_qp = Charset.Charset('utf-8')
utf8_charset_qp.body_encoding = Charset.QP
# Default MIME type to use on attachments (if it is not explicitly given
# and cannot be guessed).
DEFAULT_ATTACHMENT_MIME_TYPE = 'application/octet-stream'
RFC5322_EMAIL_LINE_LENGTH_LIMIT = 998
class BadHeaderError(ValueError):
pass
# Copied from Python 3.2+ standard library, with the following modifications:
# * Used cached hostname for performance.
# TODO: replace with email.utils.make_msgid(.., domain=DNS_NAME) when dropping
# Python 2 (Python 2's version doesn't have domain parameter) (#23905).
def make_msgid(idstring=None, domain=None):
"""Returns a string suitable for RFC 5322 compliant Message-ID, e.g:
<20020201195627.33539.96671@nightshade.la.mastaler.com>
Optional idstring if given is a string used to strengthen the
uniqueness of the message id. Optional domain if given provides the
portion of the message id after the '@'. It defaults to the locally
defined hostname.
"""
timeval = time.time()
utcdate = time.strftime('%Y%m%d%H%M%S', time.gmtime(timeval))
pid = os.getpid()
randint = random_num.randrange(100000)
if idstring is None:
idstring = ''
else:
idstring = '.' + idstring
if domain is None:
# stdlib uses socket.getfqdn() here instead
domain = DNS_NAME
msgid = '<%s.%s.%s%s@%s>' % (utcdate, pid, randint, idstring, domain)
return msgid
# Header names that contain structured address data (RFC #5322)
ADDRESS_HEADERS = {
'from',
'sender',
'reply-to',
'to',
'cc',
'bcc',
'resent-from',
'resent-sender',
'resent-to',
'resent-cc',
'resent-bcc',
}
def forbid_multi_line_headers(name, val, encoding):
"""Forbids multi-line headers, to prevent header injection."""
encoding = encoding or settings.DEFAULT_CHARSET
val = force_text(val)
if '\n' in val or '\r' in val:
raise BadHeaderError("Header values can't contain newlines (got %r for header %r)" % (val, name))
try:
val.encode('ascii')
except UnicodeEncodeError:
if name.lower() in ADDRESS_HEADERS:
val = ', '.join(sanitize_address(addr, encoding) for addr in getaddresses((val,)))
else:
val = Header(val, encoding).encode()
else:
if name.lower() == 'subject':
val = Header(val).encode()
return str(name), val
def split_addr(addr, encoding):
"""
Split the address into local part and domain, properly encoded.
When non-ascii characters are present in the local part, it must be
MIME-word encoded. The domain name must be idna-encoded if it contains
non-ascii characters.
"""
if '@' in addr:
localpart, domain = addr.split('@', 1)
# Try to get the simplest encoding - ascii if possible so that
# to@example.com doesn't become =?utf-8?q?to?=@example.com. This
# makes unit testing a bit easier and more readable.
try:
localpart.encode('ascii')
except UnicodeEncodeError:
localpart = Header(localpart, encoding).encode()
domain = domain.encode('idna').decode('ascii')
else:
localpart = Header(addr, encoding).encode()
domain = ''
return (localpart, domain)
def sanitize_address(addr, encoding):
"""
Format a pair of (name, address) or an email address string.
"""
if not isinstance(addr, tuple):
addr = parseaddr(force_text(addr))
nm, addr = addr
localpart, domain = None, None
nm = Header(nm, encoding).encode()
try:
addr.encode('ascii')
except UnicodeEncodeError: # IDN or non-ascii in the local part
localpart, domain = split_addr(addr, encoding)
if six.PY2:
# On Python 2, use the stdlib since `email.headerregistry` doesn't exist.
from email.utils import formataddr
if localpart and domain:
addr = '@'.join([localpart, domain])
return formataddr((nm, addr))
# On Python 3, an `email.headerregistry.Address` object is used since
# email.utils.formataddr() naively encodes the name as ascii (see #25986).
from email.headerregistry import Address
from email.errors import InvalidHeaderDefect, NonASCIILocalPartDefect
if localpart and domain:
address = Address(nm, username=localpart, domain=domain)
return str(address)
try:
address = Address(nm, addr_spec=addr)
except (InvalidHeaderDefect, NonASCIILocalPartDefect):
localpart, domain = split_addr(addr, encoding)
address = Address(nm, username=localpart, domain=domain)
return str(address)
class MIMEMixin():
def as_string(self, unixfrom=False, linesep='\n'):
"""Return the entire formatted message as a string.
Optional `unixfrom' when True, means include the Unix From_ envelope
header.
This overrides the default as_string() implementation to not mangle
lines that begin with 'From '. See bug #13433 for details.
"""
fp = six.StringIO()
g = generator.Generator(fp, mangle_from_=False)
if six.PY2:
g.flatten(self, unixfrom=unixfrom)
else:
g.flatten(self, unixfrom=unixfrom, linesep=linesep)
return fp.getvalue()
if six.PY2:
as_bytes = as_string
else:
def as_bytes(self, unixfrom=False, linesep='\n'):
"""Return the entire formatted message as bytes.
Optional `unixfrom' when True, means include the Unix From_ envelope
header.
This overrides the default as_bytes() implementation to not mangle
lines that begin with 'From '. See bug #13433 for details.
"""
fp = BytesIO()
g = generator.BytesGenerator(fp, mangle_from_=False)
g.flatten(self, unixfrom=unixfrom, linesep=linesep)
return fp.getvalue()
class SafeMIMEMessage(MIMEMixin, MIMEMessage):
def __setitem__(self, name, val):
# message/rfc822 attachments must be ASCII
name, val = forbid_multi_line_headers(name, val, 'ascii')
MIMEMessage.__setitem__(self, name, val)
class SafeMIMEText(MIMEMixin, MIMEText):
def __init__(self, _text, _subtype='plain', _charset=None):
self.encoding = _charset
MIMEText.__init__(self, _text, _subtype=_subtype, _charset=_charset)
def __setitem__(self, name, val):
name, val = forbid_multi_line_headers(name, val, self.encoding)
MIMEText.__setitem__(self, name, val)
def set_payload(self, payload, charset=None):
if charset == 'utf-8':
has_long_lines = any(
len(l.encode('utf-8')) > RFC5322_EMAIL_LINE_LENGTH_LIMIT
for l in payload.splitlines()
)
# Quoted-Printable encoding has the side effect of shortening long
# lines, if any (#22561).
charset = utf8_charset_qp if has_long_lines else utf8_charset
MIMEText.set_payload(self, payload, charset=charset)
class SafeMIMEMultipart(MIMEMixin, MIMEMultipart):
def __init__(self, _subtype='mixed', boundary=None, _subparts=None, encoding=None, **_params):
self.encoding = encoding
MIMEMultipart.__init__(self, _subtype, boundary, _subparts, **_params)
def __setitem__(self, name, val):
name, val = forbid_multi_line_headers(name, val, self.encoding)
MIMEMultipart.__setitem__(self, name, val)
class EmailMessage(object):
"""
A container for email information.
"""
content_subtype = 'plain'
mixed_subtype = 'mixed'
encoding = None # None => use settings default
def __init__(self, subject='', body='', from_email=None, to=None, bcc=None,
connection=None, attachments=None, headers=None, cc=None,
reply_to=None):
"""
Initialize a single email message (which can be sent to multiple
recipients).
All strings used to create the message can be unicode strings
(or UTF-8 bytestrings). The SafeMIMEText class will handle any
necessary encoding conversions.
"""
if to:
if isinstance(to, six.string_types):
raise TypeError('"to" argument must be a list or tuple')
self.to = list(to)
else:
self.to = []
if cc:
if isinstance(cc, six.string_types):
raise TypeError('"cc" argument must be a list or tuple')
self.cc = list(cc)
else:
self.cc = []
if bcc:
if isinstance(bcc, six.string_types):
raise TypeError('"bcc" argument must be a list or tuple')
self.bcc = list(bcc)
else:
self.bcc = []
if reply_to:
if isinstance(reply_to, six.string_types):
raise TypeError('"reply_to" argument must be a list or tuple')
self.reply_to = list(reply_to)
else:
self.reply_to = []
self.from_email = from_email or settings.DEFAULT_FROM_EMAIL
self.subject = subject
self.body = body
self.attachments = []
if attachments:
for attachment in attachments:
if isinstance(attachment, MIMEBase):
self.attach(attachment)
else:
self.attach(*attachment)
self.extra_headers = headers or {}
self.connection = connection
def get_connection(self, fail_silently=False):
from django.core.mail import get_connection
if not self.connection:
self.connection = get_connection(fail_silently=fail_silently)
return self.connection
def message(self):
encoding = self.encoding or settings.DEFAULT_CHARSET
msg = SafeMIMEText(self.body, self.content_subtype, encoding)
msg = self._create_message(msg)
msg['Subject'] = self.subject
msg['From'] = self.extra_headers.get('From', self.from_email)
msg['To'] = self.extra_headers.get('To', ', '.join(map(force_text, self.to)))
if self.cc:
msg['Cc'] = ', '.join(map(force_text, self.cc))
if self.reply_to:
msg['Reply-To'] = self.extra_headers.get('Reply-To', ', '.join(map(force_text, self.reply_to)))
# Email header names are case-insensitive (RFC 2045), so we have to
# accommodate that when doing comparisons.
header_names = [key.lower() for key in self.extra_headers]
if 'date' not in header_names:
# formatdate() uses stdlib methods to format the date, which use
# the stdlib/OS concept of a timezone, however, Django sets the
# TZ environment variable based on the TIME_ZONE setting which
# will get picked up by formatdate().
msg['Date'] = formatdate(localtime=settings.EMAIL_USE_LOCALTIME)
if 'message-id' not in header_names:
# Use cached DNS_NAME for performance
msg['Message-ID'] = make_msgid(domain=DNS_NAME)
for name, value in self.extra_headers.items():
if name.lower() in ('from', 'to'): # From and To are already handled
continue
msg[name] = value
return msg
def recipients(self):
"""
Returns a list of all recipients of the email (includes direct
addressees as well as Cc and Bcc entries).
"""
return [email for email in (self.to + self.cc + self.bcc) if email]
def send(self, fail_silently=False):
"""Sends the email message."""
if not self.recipients():
# Don't bother creating the network connection if there's nobody to
# send to.
return 0
return self.get_connection(fail_silently).send_messages([self])
def attach(self, filename=None, content=None, mimetype=None):
"""
Attaches a file with the given filename and content. The filename can
be omitted and the mimetype is guessed, if not provided.
If the first parameter is a MIMEBase subclass it is inserted directly
into the resulting message attachments.
For a text/* mimetype (guessed or specified), when a bytes object is
specified as content, it will be decoded as UTF-8. If that fails,
the mimetype will be set to DEFAULT_ATTACHMENT_MIME_TYPE and the
content is not decoded.
"""
if isinstance(filename, MIMEBase):
assert content is None
assert mimetype is None
self.attachments.append(filename)
else:
assert content is not None
if not mimetype:
mimetype, _ = mimetypes.guess_type(filename)
if not mimetype:
mimetype = DEFAULT_ATTACHMENT_MIME_TYPE
basetype, subtype = mimetype.split('/', 1)
if basetype == 'text':
if isinstance(content, six.binary_type):
try:
content = content.decode('utf-8')
except UnicodeDecodeError:
# If mimetype suggests the file is text but it's actually
# binary, read() will raise a UnicodeDecodeError on Python 3.
mimetype = DEFAULT_ATTACHMENT_MIME_TYPE
self.attachments.append((filename, content, mimetype))
def attach_file(self, path, mimetype=None):
"""
Attaches a file from the filesystem.
The mimetype will be set to the DEFAULT_ATTACHMENT_MIME_TYPE if it is
not specified and cannot be guessed.
For a text/* mimetype (guessed or specified), the file's content
will be decoded as UTF-8. If that fails, the mimetype will be set to
DEFAULT_ATTACHMENT_MIME_TYPE and the content is not decoded.
"""
filename = os.path.basename(path)
with open(path, 'rb') as file:
content = file.read()
self.attach(filename, content, mimetype)
def _create_message(self, msg):
return self._create_attachments(msg)
def _create_attachments(self, msg):
if self.attachments:
encoding = self.encoding or settings.DEFAULT_CHARSET
body_msg = msg
msg = SafeMIMEMultipart(_subtype=self.mixed_subtype, encoding=encoding)
if self.body:
msg.attach(body_msg)
for attachment in self.attachments:
if isinstance(attachment, MIMEBase):
msg.attach(attachment)
else:
msg.attach(self._create_attachment(*attachment))
return msg
def _create_mime_attachment(self, content, mimetype):
"""
Converts the content, mimetype pair into a MIME attachment object.
If the mimetype is message/rfc822, content may be an
email.Message or EmailMessage object, as well as a str.
"""
basetype, subtype = mimetype.split('/', 1)
if basetype == 'text':
encoding = self.encoding or settings.DEFAULT_CHARSET
attachment = SafeMIMEText(content, subtype, encoding)
elif basetype == 'message' and subtype == 'rfc822':
# Bug #18967: per RFC2046 s5.2.1, message/rfc822 attachments
# must not be base64 encoded.
if isinstance(content, EmailMessage):
# convert content into an email.Message first
content = content.message()
elif not isinstance(content, Message):
# For compatibility with existing code, parse the message
# into an email.Message object if it is not one already.
content = message_from_string(content)
attachment = SafeMIMEMessage(content, subtype)
else:
# Encode non-text attachments with base64.
attachment = MIMEBase(basetype, subtype)
attachment.set_payload(content)
Encoders.encode_base64(attachment)
return attachment
def _create_attachment(self, filename, content, mimetype=None):
"""
Converts the filename, content, mimetype triple into a MIME attachment
object.
"""
attachment = self._create_mime_attachment(content, mimetype)
if filename:
try:
filename.encode('ascii')
except UnicodeEncodeError:
if six.PY2:
filename = filename.encode('utf-8')
filename = ('utf-8', '', filename)
attachment.add_header('Content-Disposition', 'attachment',
filename=filename)
return attachment
class EmailMultiAlternatives(EmailMessage):
"""
A version of EmailMessage that makes it easy to send multipart/alternative
messages. For example, including text and HTML versions of the text is
made easier.
"""
alternative_subtype = 'alternative'
def __init__(self, subject='', body='', from_email=None, to=None, bcc=None,
connection=None, attachments=None, headers=None, alternatives=None,
cc=None, reply_to=None):
"""
Initialize a single email message (which can be sent to multiple
recipients).
All strings used to create the message can be unicode strings (or UTF-8
bytestrings). The SafeMIMEText class will handle any necessary encoding
conversions.
"""
super(EmailMultiAlternatives, self).__init__(
subject, body, from_email, to, bcc, connection, attachments,
headers, cc, reply_to,
)
self.alternatives = alternatives or []
def attach_alternative(self, content, mimetype):
"""Attach an alternative content representation."""
assert content is not None
assert mimetype is not None
self.alternatives.append((content, mimetype))
def _create_message(self, msg):
return self._create_attachments(self._create_alternatives(msg))
def _create_alternatives(self, msg):
encoding = self.encoding or settings.DEFAULT_CHARSET
if self.alternatives:
body_msg = msg
msg = SafeMIMEMultipart(_subtype=self.alternative_subtype, encoding=encoding)
if self.body:
msg.attach(body_msg)
for alternative in self.alternatives:
msg.attach(self._create_mime_attachment(*alternative))
return msg
| [
"sunyfad@gmail.com"
] | sunyfad@gmail.com |
1518a5d2a8c4b5414f21d19249553414d0f08678 | 0a63223decec3c45fdde3fffc7ca645ddcdb911c | /prev/baekjoon/8주차/12100/12100_jy.py | 70d01d8463c58bc3f7b87b0ea6ce787d189305a7 | [] | no_license | WebProject-STT/Algorithm | 8fe1f0d4bc176784c072ae88ab154aadcdf92e85 | 005cfd6a803b1dbd9ede501a2133655650d0ee38 | refs/heads/main | 2023-07-10T02:49:36.450595 | 2021-08-09T12:54:13 | 2021-08-09T12:54:13 | 335,193,677 | 0 | 1 | null | null | null | null | UTF-8 | Python | false | false | 4,598 | py | # 2048(easy)
import sys
from collections import deque
N = int(sys.stdin.readline())
max_ = -sys.maxsize
grids = [list(map(int, sys.stdin.readline().split())) for _ in range(N)]
def find_max(grid):
global max_
for g in grid:
max_ = max(max_, max(g))
return
def move_up(grid):
for c in range(N):
stack = []
for r in range(N):
if grid[r][c] and not stack: # 처음 만나는 숫자면
stack.append([0, grid[r][c], False])
if r: # 0번 인덱스가 아니면
grid[0][c] = grid[r][c]
grid[r][c] = 0
continue
if grid[r][c]:
if stack[-1][1] == grid[r][c] and not stack[-1][2]: # 합쳐질 수 있으면
stack[-1][1] = stack[-1][1]*2
stack[-1][2] = True
grid[r][c] = 0
grid[stack[-1][0]][c] = stack[-1][1]
else:
grid[stack[-1][0]+1][c] = grid[r][c]
if r != stack[-1][0]+1: # 한칸차이 이상
grid[r][c] = 0
stack.append([stack[-1][0]+1, grid[stack[-1][0]+1][c], False])
return grid
def move_down(grid):
for c in range(N):
stack = []
for r in range(-1, -N-1, -1):
if grid[r][c] and not stack: # 처음 만나는 숫자면
stack.append([-1, grid[r][c], False])
if r != -1: # -1번 인덱스가 아니면
grid[-1][c] = grid[r][c]
grid[r][c] = 0
continue
if grid[r][c]:
if stack[-1][1] == grid[r][c] and not stack[-1][2]:
stack[-1][1] = stack[-1][1]*2
stack[-1][2] = True
grid[r][c] = 0
grid[stack[-1][0]][c] = stack[-1][1]
else:
grid[stack[-1][0]-1][c] = grid[r][c]
if r != stack[-1][0]-1: # 한칸차이 이상
grid[r][c] = 0
stack.append([stack[-1][0]-1, grid[stack[-1][0]-1][c], False])
return grid
def move_left(grid):
for r in range(N):
stack = []
for c in range(N):
if grid[r][c] and not stack: # 처음 만나는 숫자면
stack.append([0, grid[r][c], False])
if c: # -1번 인덱스가 아니면
grid[r][0] = grid[r][c]
grid[r][c] = 0
continue
if grid[r][c]:
if stack[-1][1] == grid[r][c] and not stack[-1][2]:
stack[-1][1] = stack[-1][1]*2
stack[-1][2] = True
grid[r][c] = 0
grid[r][stack[-1][0]] = stack[-1][1]
else:
grid[r][stack[-1][0]+1] = grid[r][c]
if c != stack[-1][0]+1: # 한칸차이 이상
grid[r][c] = 0
stack.append([stack[-1][0]+1, grid[r][stack[-1][0]+1], False])
return grid
def move_right(grid):
for r in range(N):
stack = []
for c in range(-1, -N-1, -1):
if grid[r][c] and not stack: # 처음 만나는 숫자면
stack.append([-1, grid[r][c], False])
if c != -1: # -1번 인덱스가 아니면
grid[r][-1] = grid[r][c]
grid[r][c] = 0
continue
if grid[r][c]:
if stack[-1][1] == grid[r][c] and not stack[-1][2]:
stack[-1][1] = stack[-1][1]*2
stack[-1][2] = True
grid[r][c] = 0
grid[r][stack[-1][0]] = stack[-1][1]
else:
t = grid[r][c]
grid[r][stack[-1][0]-1] = grid[r][c]
if c != stack[-1][0]-1: # 한칸차이 이상
grid[r][c] = 0
stack.append([stack[-1][0]-1, grid[r][stack[-1][0]-1], False])
return grid
def dfs(dfs_grid, n):
if n == 5:
find_max(dfs_grid)
return
dfs(move_up([g[:] for g in dfs_grid]), n+1)
dfs(move_down([g[:] for g in dfs_grid]), n+1)
dfs(move_left([g[:] for g in dfs_grid]), n+1)
dfs(move_right([g[:] for g in dfs_grid]), n+1)
dfs(grids, 0)
# print(move_up([g[:] for g in grids]))
# print(move_down([g[:] for g in grids]))
# print(move_left([g[:] for g in grids]))
# print(move_right([g[:] for g in grids]))
print(max_) | [
"vallot7@naver.com"
] | vallot7@naver.com |
c05f1dea34ba4ee8cf342517be11a9ae5916b0b9 | c03ac514c1ba380d03c933ba08635f6e7ede33e1 | /Main_train_generate_local_sample2.py | 6b02367a74d05f8705a28a156dbb2ff39a0545c5 | [] | no_license | ysong07/LSTM_tracking_joint | 010b05daf42829db3033f20c5311ac4b90e5d5aa | 8b68ab94ef34d350b89ed82da0e00ba64f3f0aec | refs/heads/master | 2021-05-11T07:12:36.393357 | 2018-01-18T17:08:42 | 2018-01-18T17:08:42 | 118,013,068 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 31,366 | py | import tensorflow as tf
import pdb
import numpy as np
import h5py
import scipy.io as scipy_io
import numpy as np
from matplotlib.path import Path
from data_handler_inference_good_only import *
from params_refine_local_2 import *
from G_model_glob_share_weight import *
from G_inference import *
import os
import time
import sys
#from mpi4py import MPI
def crop_image_include_coundary(output,input,center):
height,width = output.shape[0],output.shape[1]
min_x = max(0,int(center[0]-height/2))
min_out_x = max(0,int(height/2-center[0]))
min_y = max(0,int(center[1]-width/2))
min_out_y = max(0,int(width/2-center[1]))
max_x = min(input.shape[0],int(center[0]+height/2))
max_out_x = min(height, height+ input.shape[0]- int(center[0]+height/2))
max_y = min(input.shape[1],int(center[1]+width/2))
max_out_y = min(width, width+ input.shape[1]- int(center[1]+width/2))
try:
output[min_out_x:max_out_x,min_out_y:max_out_y,:] = input[min_x:max_x,min_y:max_y,:]
except:
pdb.set_trace()
return output
class Inference:
def __init__(self,train_file_name):
self.sess = tf.Session()
kernel_size_dec = []
kernel_size_dec.append([5,5])
kernel_size_dec.append([5,5])
kernel_size_dec.append([5,5])
kernel_size_dec.append([5,5])
self.h_0 = tf.placeholder(tf.float32,shape=[FLAGS.batch_size,14,14,128])
self.c_0 = tf.placeholder(tf.float32,shape=[FLAGS.batch_size,14,14,128])
self.h_1 = tf.placeholder(tf.float32,shape=[FLAGS.batch_size,14,14,128])
self.c_1 = tf.placeholder(tf.float32,shape=[FLAGS.batch_size,14,14,128])
""" placeholder for feature extractor """
self.batch_frames = tf.placeholder(tf.float32,shape=[FLAGS.batch_size,224,224,3])
self.mask_frames = tf.placeholder(tf.float32,shape=[FLAGS.batch_size,224,224,64])
self.output_feature_1 = feature_extract(self.batch_frames,self.mask_frames)
self.no_mask_frames = tf.placeholder(tf.float32,shape=[FLAGS.batch_size,224,224,64])
self.output_feature_0 = feature_extract(self.batch_frames,self.no_mask_frames)
input_feature = feature_extract(self.batch_frames,self.no_mask_frames)
with tf.variable_scope('trainable_params_local') as scope:
output_feature = tf.concat([self.output_feature_0,self.output_feature_1],axis=3)
with tf.variable_scope('initial_0'):
c_matrix_0_0 = tf.get_variable("matrix_c_0", shape = [3,3,512*2,256], initializer = tf.random_uniform_initializer(-0.01, 0.01))
c_bias_0_0 = tf.get_variable("bias_c_0",shape = [256],initializer=tf.constant_initializer(0.01))
c_0_0 = tf.nn.conv2d(output_feature,c_matrix_0_0,strides=[1,1,1,1], padding='SAME') + c_bias_0_0
c_0_0 = tf.tanh(c_0_0)
c_matrix_0_1 = tf.get_variable("matrix_c_1", shape = [3,3,256,128], initializer = tf.random_uniform_initializer(-0.01, 0.01))
c_bias_0_1 = tf.get_variable("bias_c_1",shape = [128],initializer=tf.constant_initializer(0.01))
self.c_0 = tf.nn.conv2d(c_0_0,c_matrix_0_1,strides=[1,1,1,1], padding='SAME') + c_bias_0_1
h_matrix_0_0 = tf.get_variable("matrix_h_0", shape = [3,3,512*2,256], initializer = tf.random_uniform_initializer(-0.01, 0.01))
h_bias_0_0 = tf.get_variable("bias_h_0",shape = [256],initializer=tf.constant_initializer(0.01))
h_0_0 = tf.tanh(tf.nn.conv2d(output_feature,h_matrix_0_0,strides=[1,1,1,1], padding='SAME') + h_bias_0_0)
h_matrix_0_1 = tf.get_variable("matrix_h_1", shape = [3,3,256,128], initializer = tf.random_uniform_initializer(-0.01, 0.01))
h_bias_0_1 = tf.get_variable("bias_h_1",shape = [128],initializer=tf.constant_initializer(0.01))
self.h_0 = tf.tanh(tf.nn.conv2d(h_0_0, h_matrix_0_1,strides=[1,1,1,1], padding='SAME') + h_bias_0_1)
with tf.variable_scope('initial_1'):
c_matrix_1_0 = tf.get_variable("matrix_c_0", shape = [3,3,512*2,256], initializer = tf.random_uniform_initializer(-0.01, 0.01))
c_bias_1_0 = tf.get_variable("bias_c_0",shape = [256],initializer=tf.constant_initializer(0.01))
c_1_0 = tf.nn.conv2d(output_feature,c_matrix_1_0,strides=[1,1,1,1], padding='SAME') + c_bias_1_0
c_1_0 = tf.tanh(c_1_0)
c_matrix_1_1 = tf.get_variable("matrix_c_1", shape = [3,3,256,128], initializer = tf.random_uniform_initializer(-0.01, 0.01))
c_bias_1_1 = tf.get_variable("bias_c_1",shape = [128],initializer=tf.constant_initializer(0.01))
self.c_1 = tf.nn.conv2d(c_1_0,c_matrix_1_1,strides=[1,1,1,1], padding='SAME') + c_bias_1_1
h_matrix_1_0 = tf.get_variable("matrix_h_0", shape = [3,3,512*2,256], initializer = tf.random_uniform_initializer(-0.01, 0.01))
h_bias_1_0 = tf.get_variable("bias_h_0",shape = [256],initializer=tf.constant_initializer(0.01))
h_1_0 = tf.tanh(tf.nn.conv2d(output_feature,h_matrix_1_0,strides=[1,1,1,1], padding='SAME') + h_bias_1_0)
h_matrix_1_1 = tf.get_variable("matrix_h_1", shape = [3,3,256,128], initializer = tf.random_uniform_initializer(-0.01, 0.01))
h_bias_1_1 = tf.get_variable("bias_h_1",shape = [128],initializer=tf.constant_initializer(0.01))
self.h_1 = tf.tanh(tf.nn.conv2d(h_1_0, h_matrix_1_1,strides=[1,1,1,1], padding='SAME') + h_bias_1_1)
self.G_model = G_model_(scope="G_model",height=14,width=14,batch_size = FLAGS.batch_size,layer_num_lstm=2,kernel_size=[3,3],kernel_num=[128,128],kernel_size_dec=kernel_size_dec,num_dec_input=[128,64,32,16],num_dec_output=[64,32,16,1],layer_num_cnn =4,initial_h_0=self.h_0,initial_c_0=self.c_0,initial_h_1=self.h_1,initial_c_1=self.c_1,img_height=200,img_width=200)
variable_collection_local = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES,"trainable_params_local")
saver_local = tf.train.Saver(variable_collection_local)
#saver_local.restore(self.sess,"/scratch/ys1297/LSTM_tracking/source_cross_vgg_local/checkpoints/shuffle_0/cross0/model.ckpt-122000")
saver_local.restore(self.sess,"/scratch/ys1297/LSTM_tracking/source_cross_vgg_refine/checkpoints_1/test_refine_total_2/model.ckpt-24000")
self.glob_h_0 = tf.placeholder(tf.float32,shape=[FLAGS.batch_size,14,14,64])
self.glob_c_0 = tf.placeholder(tf.float32,shape=[FLAGS.batch_size,14,14,64])
self.glob_h_1 = tf.placeholder(tf.float32,shape=[FLAGS.batch_size,14,14,64])
self.glob_c_1 = tf.placeholder(tf.float32,shape=[FLAGS.batch_size,14,14,64])
with tf.variable_scope('trainable_params_glob') as scope:
self.first_feature = tf.placeholder(tf.float32,shape=[FLAGS.batch_size,224,224,1])
self.rest_feature = tf.placeholder(tf.float32,shape=[FLAGS.batch_size*1,224,224,1])
with tf.variable_scope('feature_extract') as f_scope:
def feature_extract_mask(batch_frames):
def avg_pool( bottom, name):
return tf.nn.avg_pool(bottom, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME', name=name)
def max_pool( bottom, name):
return tf.nn.max_pool(bottom, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME', name=name)
def conv_layer(bottom, name,shape):
with tf.variable_scope(name):
filt = get_conv_filter(name,shape)
conv = tf.nn.conv2d(bottom, filt, [1, 1, 1, 1], padding='SAME')
conv_biases = get_bias(name,shape)
bias = tf.nn.bias_add(conv, conv_biases)
relu = tf.nn.relu(bias)
return relu
def get_conv_filter(name,shape):
return tf.get_variable(name+"_matrix",shape = shape,initializer = tf.random_uniform_initializer(-0.01, 0.01))
def get_bias(name,shape):
return tf.get_variable(name+"_bias",shape = shape[3],initializer=tf.constant_initializer(0.01))
#return tf.constant(data_dict[name][1], name="biases")
conv1_1 = conv_layer(batch_frames, "conv1_1",[3,3,1,8])
conv1_2 = conv_layer(conv1_1, "conv1_2",[3,3,8,8])
pool1 = max_pool(conv1_2, 'pool1')
conv2_1 = conv_layer(pool1, "conv2_1",[3,3,8,16])
conv2_2 = conv_layer(conv2_1, "conv2_2",[3,3,16,16])
pool2 = max_pool(conv2_2, 'pool2')
conv3_1 = conv_layer(pool2, "conv3_1",[3,3,16,32])
conv3_2 = conv_layer(conv3_1, "conv3_2",[3,3,32,32])
pool3 = max_pool(conv3_2, 'pool3')
conv4_1 = conv_layer(pool3, "conv4_1",[3,3,32,64])
conv4_2 = conv_layer(conv4_1, "conv4_2",[3,3,64,64])
pool4 = max_pool(conv4_2, 'pool4')
return pool4
glob_feature_0 = feature_extract_mask(self.first_feature)
f_scope.reuse_variables()
frame_features = feature_extract_mask(self.rest_feature)
with tf.variable_scope('initial_0'):
c_matrix_0 = tf.get_variable("matrix_c", shape = [3,3,64,64], initializer = tf.random_uniform_initializer(-0.01, 0.01))
c_bias_0 = tf.get_variable("bias_c",shape = [64],initializer=tf.constant_initializer(0.01))
self.glob_c_0 = tf.nn.conv2d(glob_feature_0,c_matrix_0,strides=[1,1,1,1], padding='SAME') + c_bias_0
h_matrix_0 = tf.get_variable("matrix_h", shape = [3,3,64,64], initializer = tf.random_uniform_initializer(-0.01, 0.01))
h_bias_0 = tf.get_variable("bias_h",shape = [64],initializer=tf.constant_initializer(0.01))
self.glob_h_0 = tf.tanh(tf.nn.conv2d(glob_feature_0,h_matrix_0,strides=[1,1,1,1], padding='SAME') + h_bias_0)
with tf.variable_scope('initial_1'):
c_matrix_1 = tf.get_variable("matrix_c", shape = [3,3,64,64], initializer = tf.random_uniform_initializer(-0.01, 0.01))
c_bias_1 = tf.get_variable("bias_c",shape = [64],initializer=tf.constant_initializer(0.01))
self.glob_c_1 = tf.nn.conv2d(glob_feature_0,c_matrix_1,strides=[1,1,1,1], padding='SAME') + c_bias_1
h_matrix_1 = tf.get_variable("matrix_h", shape = [3,3,64,64], initializer = tf.random_uniform_initializer(-0.01, 0.01))
h_bias_1 = tf.get_variable("bias_h",shape = [64],initializer=tf.constant_initializer(0.01))
self.glob_h_1 = tf.tanh(tf.nn.conv2d(glob_feature_0,h_matrix_1,strides=[1,1,1,1], padding='SAME') + h_bias_1)
self.G_model_G = G_model_glob(scope="G_model",height=14,width=14,length=1,batch_size = FLAGS.batch_size,layer_num_lstm=2,kernel_size=[3,3],kernel_num=[64,64],initial_h_0=self.glob_h_0,initial_c_0=self.glob_c_0,initial_h_1=self.glob_h_1,initial_c_1=self.glob_c_1,input_features=frame_features)
variable_collection = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES,"trainable_params_glob")
"""saver """
saver = tf.train.Saver(variable_collection)
saver.restore(self.sess,"/scratch/ys1297/LSTM_tracking/source_cross_resnet_globe/checkpoints/iter_2/test_new_no_smooth_share_feature_weight_2/model.ckpt-27000")
sess1 = None
self.data_handler = data_handler_(sess1,batch_size=FLAGS.batch_size,length = 2,train_file_name = train_file_name) # get batch data
def define_graph(self):
sess1 = None
image, mask,label = self.data_handler.Get_all_label()
W = image.shape[1]
H = image.shape[2]
kernel_size_dec = []
kernel_size_dec.append([5,5])
kernel_size_dec.append([5,5])
kernel_size_dec.append([5,5])
kernel_size_dec.append([5,5])
self.h_0 = tf.placeholder(tf.float32,shape=[FLAGS.batch_size,14,14,128])
self.c_0 = tf.placeholder(tf.float32,shape=[FLAGS.batch_size,14,14,128])
self.h_1 = tf.placeholder(tf.float32,shape=[FLAGS.batch_size,14,14,128])
self.c_1 = tf.placeholder(tf.float32,shape=[FLAGS.batch_size,14,14,128])
""" placeholder for feature extractor """
self.batch_frames = tf.placeholder(tf.float32,shape=[FLAGS.batch_size,224,224,3])
self.mask_frames = tf.placeholder(tf.float32,shape=[FLAGS.batch_size,224,224,64])
self.output_feature_1 = feature_extract(self.batch_frames,self.mask_frames)
self.no_mask_frames = tf.placeholder(tf.float32,shape=[FLAGS.batch_size,224,224,64])
self.output_feature_0 = feature_extract(self.batch_frames,self.no_mask_frames)
with tf.variable_scope('trainable_params_local') as scope:
output_feature = tf.concat([self.output_feature_0,self.output_feature_1],axis=3)
scope.reuse_variables()
with tf.variable_scope('initial_0'):
c_matrix_0_0 = tf.get_variable("matrix_c_0", shape = [3,3,512*2,256], initializer = tf.random_uniform_initializer(-0.01, 0.01))
c_bias_0_0 = tf.get_variable("bias_c_0",shape = [256],initializer=tf.constant_initializer(0.01))
c_0_0 = tf.nn.conv2d(output_feature,c_matrix_0_0,strides=[1,1,1,1], padding='SAME') + c_bias_0_0
c_0_0 = tf.tanh(c_0_0)
c_matrix_0_1 = tf.get_variable("matrix_c_1", shape = [3,3,256,128], initializer = tf.random_uniform_initializer(-0.01, 0.01))
c_bias_0_1 = tf.get_variable("bias_c_1",shape = [128],initializer=tf.constant_initializer(0.01))
self.c_0 = tf.nn.conv2d(c_0_0,c_matrix_0_1,strides=[1,1,1,1], padding='SAME') + c_bias_0_1
h_matrix_0_0 = tf.get_variable("matrix_h_0", shape = [3,3,512*2,256], initializer = tf.random_uniform_initializer(-0.01, 0.01))
h_bias_0_0 = tf.get_variable("bias_h_0",shape = [256],initializer=tf.constant_initializer(0.01))
h_0_0 = tf.tanh(tf.nn.conv2d(output_feature,h_matrix_0_0,strides=[1,1,1,1], padding='SAME') + h_bias_0_0)
h_matrix_0_1 = tf.get_variable("matrix_h_1", shape = [3,3,256,128], initializer = tf.random_uniform_initializer(-0.01, 0.01))
h_bias_0_1 = tf.get_variable("bias_h_1",shape = [128],initializer=tf.constant_initializer(0.01))
self.h_0 = tf.tanh(tf.nn.conv2d(h_0_0, h_matrix_0_1,strides=[1,1,1,1], padding='SAME') + h_bias_0_1)
with tf.variable_scope('initial_1'):
c_matrix_1_0 = tf.get_variable("matrix_c_0", shape = [3,3,512*2,256], initializer = tf.random_uniform_initializer(-0.01, 0.01))
c_bias_1_0 = tf.get_variable("bias_c_0",shape = [256],initializer=tf.constant_initializer(0.01))
c_1_0 = tf.nn.conv2d(output_feature,c_matrix_1_0,strides=[1,1,1,1], padding='SAME') + c_bias_1_0
c_1_0 = tf.tanh(c_1_0)
c_matrix_1_1 = tf.get_variable("matrix_c_1", shape = [3,3,256,128], initializer = tf.random_uniform_initializer(-0.01, 0.01))
c_bias_1_1 = tf.get_variable("bias_c_1",shape = [128],initializer=tf.constant_initializer(0.01))
self.c_1 = tf.nn.conv2d(c_1_0,c_matrix_1_1,strides=[1,1,1,1], padding='SAME') + c_bias_1_1
h_matrix_1_0 = tf.get_variable("matrix_h_0", shape = [3,3,512*2,256], initializer = tf.random_uniform_initializer(-0.01, 0.01))
h_bias_1_0 = tf.get_variable("bias_h_0",shape = [256],initializer=tf.constant_initializer(0.01))
h_1_0 = tf.tanh(tf.nn.conv2d(output_feature,h_matrix_1_0,strides=[1,1,1,1], padding='SAME') + h_bias_1_0)
h_matrix_1_1 = tf.get_variable("matrix_h_1", shape = [3,3,256,128], initializer = tf.random_uniform_initializer(-0.01, 0.01))
h_bias_1_1 = tf.get_variable("bias_h_1",shape = [128],initializer=tf.constant_initializer(0.01))
self.h_1 = tf.tanh(tf.nn.conv2d(h_1_0, h_matrix_1_1,strides=[1,1,1,1], padding='SAME') + h_bias_1_1)
self.G_model = G_model_(scope="G_model",height=14,width=14,batch_size = FLAGS.batch_size,layer_num_lstm=2,kernel_size=[3,3],kernel_num=[128,128],kernel_size_dec=kernel_size_dec,num_dec_input=[128,64,32,16],num_dec_output=[64,32,16,1],layer_num_cnn =4,initial_h_0=self.h_0,initial_c_0=self.c_0,initial_h_1=self.h_1,initial_c_1=self.c_1,img_height=W,img_width=H)
self.glob_h_0 = tf.placeholder(tf.float32,shape=[FLAGS.batch_size,14,14,64])
self.glob_c_0 = tf.placeholder(tf.float32,shape=[FLAGS.batch_size,14,14,64])
self.glob_h_1 = tf.placeholder(tf.float32,shape=[FLAGS.batch_size,14,14,64])
self.glob_c_1 = tf.placeholder(tf.float32,shape=[FLAGS.batch_size,14,14,64])
with tf.variable_scope('trainable_params_glob') as scope:
scope.reuse_variables()
self.first_feature = tf.placeholder(tf.float32,shape=[FLAGS.batch_size,224,224,1])
self.rest_feature = tf.placeholder(tf.float32,shape=[FLAGS.batch_size*(1),224,224,1])
with tf.variable_scope('feature_extract') as f_scope:
def feature_extract_mask(batch_frames):
def avg_pool( bottom, name):
return tf.nn.avg_pool(bottom, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME', name=name)
def max_pool( bottom, name):
return tf.nn.max_pool(bottom, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME', name=name)
def conv_layer(bottom, name,shape):
with tf.variable_scope(name):
filt = get_conv_filter(name,shape)
conv = tf.nn.conv2d(bottom, filt, [1, 1, 1, 1], padding='SAME')
conv_biases = get_bias(name,shape)
bias = tf.nn.bias_add(conv, conv_biases)
relu = tf.nn.relu(bias)
return relu
def get_conv_filter(name,shape):
return tf.get_variable(name+"_matrix",shape = shape,initializer = tf.random_uniform_initializer(-0.01, 0.01))
def get_bias(name,shape):
return tf.get_variable(name+"_bias",shape = shape[3],initializer=tf.constant_initializer(0.01))
#return tf.constant(data_dict[name][1], name="biases")
conv1_1 = conv_layer(batch_frames, "conv1_1",[3,3,1,8])
conv1_2 = conv_layer(conv1_1, "conv1_2",[3,3,8,8])
pool1 = max_pool(conv1_2, 'pool1')
conv2_1 = conv_layer(pool1, "conv2_1",[3,3,8,16])
conv2_2 = conv_layer(conv2_1, "conv2_2",[3,3,16,16])
pool2 = max_pool(conv2_2, 'pool2')
conv3_1 = conv_layer(pool2, "conv3_1",[3,3,16,32])
conv3_2 = conv_layer(conv3_1, "conv3_2",[3,3,32,32])
pool3 = max_pool(conv3_2, 'pool3')
conv4_1 = conv_layer(pool3, "conv4_1",[3,3,32,64])
conv4_2 = conv_layer(conv4_1, "conv4_2",[3,3,64,64])
pool4 = max_pool(conv4_2, 'pool4')
return pool4
f_scope.reuse_variables()
glob_feature_0 = feature_extract_mask(self.first_feature)
frame_features = feature_extract_mask(self.rest_feature)
scope.reuse_variables()
with tf.variable_scope('initial_0'):
c_matrix_0 = tf.get_variable("matrix_c", shape = [3,3,64,64], initializer = tf.random_uniform_initializer(-0.01, 0.01))
c_bias_0 = tf.get_variable("bias_c",shape = [64],initializer=tf.constant_initializer(0.01))
self.glob_c_0 = tf.nn.conv2d(glob_feature_0,c_matrix_0,strides=[1,1,1,1], padding='SAME') + c_bias_0
h_matrix_0 = tf.get_variable("matrix_h", shape = [3,3,64,64], initializer = tf.random_uniform_initializer(-0.01, 0.01))
h_bias_0 = tf.get_variable("bias_h",shape = [64],initializer=tf.constant_initializer(0.01))
self.glob_h_0 = tf.tanh(tf.nn.conv2d(glob_feature_0,h_matrix_0,strides=[1,1,1,1], padding='SAME') + h_bias_0)
with tf.variable_scope('initial_1'):
c_matrix_1 = tf.get_variable("matrix_c", shape = [3,3,64,64], initializer = tf.random_uniform_initializer(-0.01, 0.01))
c_bias_1 = tf.get_variable("bias_c",shape = [64],initializer=tf.constant_initializer(0.01))
self.glob_c_1 = tf.nn.conv2d(glob_feature_0,c_matrix_1,strides=[1,1,1,1], padding='SAME') + c_bias_1
h_matrix_1 = tf.get_variable("matrix_h", shape = [3,3,64,64], initializer = tf.random_uniform_initializer(-0.01, 0.01))
h_bias_1 = tf.get_variable("bias_h",shape = [64],initializer=tf.constant_initializer(0.01))
self.glob_h_1 = tf.tanh(tf.nn.conv2d(glob_feature_0,h_matrix_1,strides=[1,1,1,1], padding='SAME') + h_bias_1)
self.G_model_G = G_model_glob(scope="G_model",height=14,width=14,length=1,batch_size = FLAGS.batch_size,layer_num_lstm=2,kernel_size=[3,3],kernel_num=[64,64],initial_h_0=self.glob_h_0,initial_c_0=self.glob_c_0,initial_h_1=self.glob_h_1,initial_c_1=self.glob_c_1,input_features=frame_features)
def provide_data(self):
# variable_collection = tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES,"trainable_params_glob")
# """saver """
# saver = tf.train.Saver(variable_collection)
image, mask,label = self.data_handler.Get_all_label()
image_template_list = []
mask_template_list = []
feature_template_list = []
bbx = []
for step in xrange(32):
if step ==0:
masks_resize = cv2.resize(mask[0,:,:,0],(224,224)).reshape(1,224,224,1)
image_resize = cv2.resize(image[0,:,:,:],(224,224)).reshape(1,224,224,3)
ratio = np.array([float(mask.shape[1])/mask.shape[2]]).reshape(1,1)
input_cat = np.concatenate([image_resize,masks_resize],axis=3)
G_glob_dict = {self.rest_feature:masks_resize, self.G_model_G.ratio:ratio,self.first_feature:masks_resize}
glob_frame,glob_cell,glob_crop_size,glob_center = self.sess.run([self.G_model_G.logits,self.G_model_G.cell_state,self.G_model_G.crop_size,self.G_model_G.center],feed_dict= G_glob_dict)
#temp=cv2.resize(glob_frame.squeeze(),(image.shape[1],image.shape[2]))
#np.where(temp.sum(
crop_size = int(image.shape[1]/glob_crop_size/224.0*64)*2
#crop_size = np.asarray(glob_crop_size*64*mask.shape[1]/224)
center = np.zeros([2],dtype = 'int32')
temp = (1-glob_center[0,0]/glob_crop_size*ratio)/2.0 ## location at 224 by 224
center[0] = temp *image.shape[2]
temp = (1-glob_center[0,1]/glob_crop_size)/2.0 ## location at 224 by 224
center[1] = temp *image.shape[1]
# crop first template(ground truth)
first_template = crop_image_include_coundary(np.zeros((crop_size,crop_size,3)),image.squeeze(),(center[1],center[0]))
first_template = cv2.resize(first_template,(224,224)).reshape(FLAGS.batch_size,224,224,3)
mask_temp = mask[0,:,:,0:1]>0
first_mask = crop_image_include_coundary(np.zeros((crop_size,crop_size,1)),mask_temp,(center[1],center[0]))
first_mask = cv2.resize(first_mask,(224,224)).reshape(224,224,1)
first_mask = np.tile(first_mask,(1,1,64)).reshape(FLAGS.batch_size,224,224,64)
feed_dict = {self.batch_frames:first_template,self.mask_frames:first_mask}
feature_mask = self.sess.run(self.output_feature_1,feed_dict=feed_dict)
feed_dict = {self.batch_frames:first_template,self.no_mask_frames:np.ones((1,224,224,64))}
feature_no_mask = self.sess.run(self.output_feature_0,feed_dict=feed_dict)
self.data_handler.set_id(step+1)
image, mask, label = self.data_handler.Get_all_label()
# convert original bbx to template bbx
input_image = np.stack([image],axis=0)
feed_dict ={self.G_model.input_frame:image,self.output_feature_1:feature_mask,self.output_feature_0:feature_no_mask,self.G_model.center:center[::-1],self.G_model.crop_size:np.asarray(crop_size).reshape(1),self.G_model.input_mask:mask[:,:,:,0:1]}
g_predict,g_templates,g_states,g_original_template,g_mask_template,g_feature_template,g_return_crop_size = self.sess.run([self.G_model.predicts,self.G_model.templates,self.G_model.cell_states,self.G_model.original_template,self.G_model.mask_template,self.G_model.feature_list,self.G_model.return_crop_size],feed_dict= feed_dict)
#g_predict =temp
image_template_list.append(g_original_template)
mask_template_list.append(g_mask_template)
feature_template_list.append(g_feature_template)
pos = label
bbx_center = [(float((pos[1]+pos[3]+pos[5]+pos[7])/4.0) -center[1]+g_return_crop_size/2.0)/g_return_crop_size*224,(float((pos[0]+pos[2]+pos[4]+pos[6])/4.0)- center[0]+g_return_crop_size/2.0)/g_return_crop_size*224.0]
xs_s = np.sort(np.asarray((pos[1],pos[3],pos[5],pos[7])))
ys_s = np.sort(np.asarray((pos[0],pos[2],pos[4],pos[6])))
bbx_shape = [(xs_s[3]-xs_s[0]+xs_s[2]-xs_s[1])/g_return_crop_size*224.0/2,(ys_s[3]-ys_s[0]+ys_s[2]-ys_s[1])/g_return_crop_size*224.0/2,(xs_s[3]-xs_s[0])/g_return_crop_size*224.0,(ys_s[3]-ys_s[0])/g_return_crop_size*224.0]
ratio = [float(pos[5]-pos[1])/float(pos[4]-pos[0]+0.0001)]
# bbx_shape = [abs(float(pos[7]-pos[1])) /g_return_crop_size*224.0,abs(float(pos[2]-pos[0]))/g_return_crop_size*224.0]
bbx.append(bbx_center+bbx_shape)
else:
#masks_resize = cv2.resize(mask[0,:,:,0],(224,224)).reshape(1,224,224,1)
masks_resize = np.zeros([1,224,224,1])
temp = cv2.resize(g_predict,(224,224)).reshape(1,224,224,1)
masks_resize[temp>=0.5]=255
#masks_resize = cv2.resize(g_predict,(224,224)).reshape(1,224,224,1)
self.data_handler.set_id(step+1)
image, mask, label = self.data_handler.Get_all_label()
ratio = np.array([float(mask.shape[1])/mask.shape[2]]).reshape(1,1)
G_glob_dict = {self.rest_feature:masks_resize, self.G_model_G.ratio:ratio,self.glob_c_0:glob_cell[0:1,0,:,:,0:64],self.glob_h_0:glob_cell[0:1,0,:,:,64:128],self.glob_c_1:glob_cell[1:2,0,:,:,0:64],self.glob_h_1:glob_cell[1:2,0,:,:,64:128]}
glob_frame,glob_cell,glob_crop_size,glob_center = self.sess.run([self.G_model_G.logits,self.G_model_G.cell_state,self.G_model_G.crop_size,self.G_model_G.center],feed_dict= G_glob_dict)
crop_size = int(image.shape[1]/glob_crop_size/224.0*64)*2
#crop_size = np.asarray(glob_crop_size*64*mask.shape[1]/224)
center = np.zeros([2],dtype = 'int32')
temp = (1-glob_center[0,0]/glob_crop_size*ratio)/2.0 ## location at 224 by 224
center[0] = temp *image.shape[2]
temp = (1-glob_center[0,1]/glob_crop_size)/2.0 ## location at 224 by 224
center[1] = temp *image.shape[1]
input_image = np.stack([image],axis=0)
feed_dict ={self.c_0:g_states[0,:,:,:,:,0:128].reshape(FLAGS.batch_size,14,14,128),self.h_0:g_states[0,:,:,:,:,128:256].reshape(FLAGS.batch_size,14,14,128),self.c_1:g_states[1,:,:,:,:,0:128].reshape(FLAGS.batch_size,14,14,128),self.h_1:g_states[1,:,:,:,:,128:256].reshape(FLAGS.batch_size,14,14,128),self.G_model.center:center[::-1],self.G_model.crop_size:np.asarray(crop_size).reshape(1),self.G_model.input_frame:image,self.G_model.input_mask:mask[:,:,:,0:1]}
g_predict,g_templates,g_states,g_original_template,g_mask_template,g_feature_template,g_return_crop_size = self.sess.run([self.G_model.predicts,self.G_model.templates,self.G_model.cell_states,self.G_model.original_template,self.G_model.mask_template,self.G_model.feature_list,self.G_model.return_crop_size],feed_dict= feed_dict)
image_template_list.append(g_original_template)
mask_template_list.append(g_mask_template)
feature_template_list.append(g_feature_template)
pos = label
bbx_center = [(float((pos[1]+pos[3]+pos[5]+pos[7])/4.0) -center[1]+g_return_crop_size/2.0)/g_return_crop_size*224,(float((pos[0]+pos[2]+pos[4]+pos[6])/4.0)- center[0]+g_return_crop_size/2.0)/g_return_crop_size*224.0]
xs_s = np.sort(np.asarray((pos[1],pos[3],pos[5],pos[7])))
ys_s = np.sort(np.asarray((pos[0],pos[2],pos[4],pos[6])))
bbx_shape = [(xs_s[3]-xs_s[0]+xs_s[2]-xs_s[1])/g_return_crop_size*224.0/2,(ys_s[3]-ys_s[0]+ys_s[2]-ys_s[1])/g_return_crop_size*224.0/2,(xs_s[3]-xs_s[0])/g_return_crop_size*224.0,(ys_s[3]-ys_s[0])/g_return_crop_size*224.0]
#bbx_shape = [abs(float(pos[7]-pos[1])) /g_return_crop_size*224.0,abs(float(pos[2]-pos[0]))/g_return_crop_size*224.0]
bbx.append(bbx_center+bbx_shape)
self.data_handler.set_indices_id()
return np.stack(image_template_list,axis=1),np.stack(mask_template_list,axis=0),feature_mask,feature_no_mask,np.stack(feature_template_list,axis=1),np.stack(bbx)
def main(argv=None): # pylint: disable=unused-argument
# if tf.gfile.Exists(FLAGS.train_dir):
# tf.gfile.DeleteRecursively(FLAGS.train_dir)
# tf.gfile.MakeDirs(FLAGS.train_dir)
with tf.Graph().as_default():
sess1 = tf.Session()
with open(FLAGS.train_file_dir) as file:
file_list = file.readlines()
file_name = file_list[argv][0:-1]
# Infer = Inference(file_name)
# Infer.define_graph()
# image_array,masks,feature_mask,feature_no_mask,all_features,bbx= Infer.provide_data()
Infer = Inference(file_name)
Infer.define_graph()
file_new = h5py.File('/scratch/ys1297/LSTM_tracking/data_local_vgg_refine_2/'+file_name)
file_new.create_dataset('image',((Infer.data_handler.indices_).size,32,224,224,3))
file_new.create_dataset('mask',((Infer.data_handler.indices_).size,32,224,224,1))
file_new.create_dataset('feature_no_mask',((Infer.data_handler.indices_).size,14,14,512))
file_new.create_dataset('feature_mask',((Infer.data_handler.indices_).size,14,14,512))
# file_new.create_dataset('feature',((Infer.data_handler.indices_).size,32,14,14,512))
file_new.create_dataset('bbx',((Infer.data_handler.indices_).size,32,6))
file_new.create_dataset('valid_num',(1,),dtype='int')
count = -1
np.random.seed(10)
for step in range(20000):
try:
t1 = time.time()
image_array,masks,feature_mask,feature_no_mask,all_features,bbx= Infer.provide_data()
if step==0:
scipy_io.savemat('test.mat',{'image':image_array,'bbx':bbx})
count = count+1
file_new['image'][count] = image_array
file_new['mask'][count] = masks
file_new['feature_no_mask'][count] = feature_no_mask
file_new['feature_mask'][count] = feature_mask
# file_new['feature'][count] = all_features
file_new['bbx'][count] = bbx
#g_summary,_,g_loss = sess1.run([summary,train_op,loss],feed_dict= G_feed_dict)
#summary_writer.add_summary(g_summary, step)
#print g_loss
#t2 = time.time()
#print t2-t1
except:
Infer.data_handler.set_indices_id()
print "error indices id: " + str(Infer.data_handler.indices_id)
if count == (Infer.data_handler.indices_).size or Infer.data_handler.indices_id>=(Infer.data_handler.indices_).size:
file_new['valid_num'][0] = count
file_new.close()
break
print count
#if step %0 ==0:
# tf.reset_default_graph()
# Infer = Inference()
#if step %100==0:
# checkpoint_path = os.path.join(FLAGS.train_dir, 'model.ckpt')
# saver_local.save(sess1, checkpoint_path, global_step=step)
# scipy_io.savemat('./img/test{}.mat'.format(step),{'image_array':image_array,'masks':masks})
if __name__ == '__main__':
#tf.app.run()
main(int(sys.argv[1]))
| [
"song3681@126.com"
] | song3681@126.com |
fa5957613e2484fe7f441729fce5a1c4086f6a4b | 963a5564965e4181caa8a1c66396d714865bc236 | /django_cradmin/demo/cradmin_javascript_demos/migrations/0004_fictionalfigure_is_godlike.py | a81ea3c69c3046033dc16fe8677b4d7f1287c1c8 | [
"BSD-3-Clause"
] | permissive | appressoas/django_cradmin | d6694b87cf8a7e53b4b6c3049c085560eeba2c9f | 944e8202ac67c3838b748ff8f3a0b2a2870619bc | refs/heads/master | 2023-07-20T14:15:03.426470 | 2023-07-17T11:33:10 | 2023-07-17T11:33:10 | 20,762,263 | 12 | 3 | BSD-3-Clause | 2023-02-15T20:32:49 | 2014-06-12T09:45:04 | JavaScript | UTF-8 | Python | false | false | 441 | py | # -*- coding: utf-8 -*-
# Generated by Django 1.10.1 on 2016-12-13 09:39
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('cradmin_javascript_demos', '0003_auto_20161212_0033'),
]
operations = [
migrations.AddField(
model_name='fictionalfigure',
name='is_godlike',
field=models.BooleanField(default=False),
),
]
| [
"post@espenak.net"
] | post@espenak.net |
ab744627ad21a6209ccee871698b91bdb922a879 | d554b1aa8b70fddf81da8988b4aaa43788fede88 | /5 - Notebooks e Data/1 - Análises numéricas/Arquivos David/Atualizados/logDicas-master/data/2019-1/225/users/4312/codes/1592_820.py | d42c1e710f961e3e8e64a469d7f416f9d4d929ad | [] | no_license | JosephLevinthal/Research-projects | a3bc3ca3b09faad16f5cce5949a2279cf14742ba | 60d5fd6eb864a5181f4321e7a992812f3c2139f9 | refs/heads/master | 2022-07-31T06:43:02.686109 | 2020-05-23T00:24:26 | 2020-05-23T00:24:26 | 266,199,309 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 289 | py | # Instituto de Computacao - UFAM
# Lab 01 - Ex 10
# 20 / 05 / 2016
valor = int(input("Qual o valor do saque?"))
notas50 = valor // 50
resto50 = valor % 50
notas10 = resto50 // 10
resto10 = resto50 % 10
notas2 = resto10 // 2
print(int(notas50))
print(int(notas10))
print(int(notas2))
| [
"jvlo@icomp.ufam.edu.br"
] | jvlo@icomp.ufam.edu.br |
e96c6ceca7eddea16ca79aeeeefff406af47842f | 51d46cf862654d30f5fa0ee35a9243c9661fc0eb | /homework/myschedule/models.py | fca62b02cf0327f4696c29e60ac941bd91b06a6b | [] | no_license | LikeLionCBNU/HamDongHo | 6762a8db487ae2807d1ce9d4d2df7e18d67eab70 | 082cea62cf4b5136309cbddc8c09e4e84f25de7c | refs/heads/master | 2022-12-06T22:48:17.500207 | 2020-08-19T14:31:32 | 2020-08-19T14:31:32 | 256,194,835 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 382 | py | from django.db import models
from django.utils import timezone
# Create your models here.
class Schedule(models.Model):
title = models.CharField(max_length = 100)
memo = models.TextField()
schedule_date = models.DateTimeField(default = timezone.now)
published_data = models.DateTimeField(blank = True, null = True)
def __str__(self):
return self.title | [
"ii8858@naver.com"
] | ii8858@naver.com |
553e176cf8a1058e8cdcd023c8702ac56bbc59ec | b7b243902150a1aa5b774523ac01d7016de13477 | /cyc/string/9.py | 7c85a62b6ce7c52fec6dd0bd021f5a2809a269d5 | [] | no_license | Veraph/LeetCode_Practice | 7e97a93464911a1f33b3133043d96c88cd54016a | eafadd711f6ec1b60d78442280f1c44b6296209d | refs/heads/master | 2023-03-23T11:49:19.046474 | 2021-03-18T02:22:50 | 2021-03-18T02:22:50 | 273,317,388 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 892 | py | # 9.py -- Palindrome Number
'''
Description:
Determine whether an integer is a palindrome.
An integer is a palindrome when it reads the same backward as forward.
Example 1:
Input: 121
Output: true
Example 2:
Input: -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-.
Therefore it is not a palindrome.
Example 3:
Input: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
Follow up:
Coud you solve it without converting the integer to a string?
'''
def isPalindrome(x):
'''Trick'''
'''
return str(x) == str(x)[::-1]
'''
'''math'''
if x == 0:
return True
if x < 0 or x % 10 == 0:
return False
y, cp = 0, x
while x >= 10:
frac = x % 10
x = (x - frac) / 10
y = (y + frac) * 10
return y+x == cp
isPalindrome(1001) | [
"jmw3531@live.com"
] | jmw3531@live.com |
7bf0c5daee85982fceec735ba2aa398fcb018314 | f0eadce9fa0a2cc0dc4cbe2f534df8952bb97c66 | /torchvision/prototype/datasets/__init__.py | 1945b5a5d9e46e0df0b178472df5674753c229a0 | [
"BSD-3-Clause"
] | permissive | Hsuxu/vision | e78ea6bfbc8aa50c56573b467939e86df0138d07 | 8d3fb3455d5e1acb0fed412ece913b73774fbca4 | refs/heads/master | 2022-12-02T05:35:54.121664 | 2021-12-20T12:06:53 | 2021-12-20T12:06:53 | 215,186,338 | 1 | 0 | BSD-3-Clause | 2019-10-15T02:18:27 | 2019-10-15T02:18:27 | null | UTF-8 | Python | false | false | 690 | py | try:
import torchdata
except (ModuleNotFoundError, TypeError) as error:
raise ModuleNotFoundError(
"`torchvision.prototype.datasets` depends on PyTorch's `torchdata` (https://github.com/pytorch/data). "
"You can install it with `pip install git+https://github.com/pytorch/data.git`. "
"Note that you cannot install it with `pip install torchdata`, since this is another package."
) from error
from . import decoder, utils
from ._home import home
# Load this last, since some parts depend on the above being loaded first
from ._api import register, _list as list, info, load, find # usort: skip
from ._folder import from_data_folder, from_image_folder
| [
"noreply@github.com"
] | Hsuxu.noreply@github.com |
3bef36ec64ca18c4ecd71c0dddc05716a77ce063 | 30581136217455bb5b503fedac6978bea6fb7ee5 | /handler.py | 9941a0b85f9eb7b2edecd4e74e643ca0ae560e49 | [] | no_license | imsilence/chatrebot | 64a36a88ca7d6cc445c2ec50b1724e0193a37047 | dfe987826a93a620990063b56f3e19ef4c8a0ab0 | refs/heads/master | 2020-03-28T07:28:37.651073 | 2018-09-27T23:33:24 | 2018-09-27T23:33:24 | 147,904,030 | 3 | 1 | null | null | null | null | UTF-8 | Python | false | false | 1,695 | py | #encoding: utf-8
from threading import Thread
import logging
import traceback
import time
import importlib
logger = logging.getLogger(__name__)
class Handler(Thread):
def __init__(self, mq_task, mq_msg, cache, *args, **kwargs):
super().__init__(*args, **kwargs)
self.daemon = True
self.__mq_task = mq_task
self.__mq_msg = mq_msg
self.__cache = cache
def run(self):
_mq_task = self.__mq_task
_mq_msg = self.__mq_msg
_executors = {}
_cache = self.__cache
while True:
_task = _mq_task.get()
if not _task:
continue
_type = _task.get("type", "text")
if _type not in _executors:
_executors[_type] = None
try:
_mod = importlib.import_module("executors.{0}".format(_type))
_executors[_type] = getattr(_mod, 'Executor', None)
except ImportError as e:
logger.exception(e)
logger.error(traceback.format_exc())
_executor = _executors.get(_type)
if _executor:
_to = _task.get("to", [])
_kwargs = {'cache' : _cache, 'name' : _task.get('name', '')}
_kwargs.update(_task.get("kwargs", {}))
try:
for _msg in _executor(**_kwargs)():
logger.info("handler task: %s, msg:%s", _task, _msg)
_mq_msg.put({"msg" : _msg, "to" : _to})
except BaseException as e:
logger.exception(e)
logger.error(traceback.format_exc())
| [
"imsilence@outlook.com"
] | imsilence@outlook.com |
56579ceaeb9fe5f0033fc5b142c8f915e1c13471 | dc2e4247c2c4b93fa2c409fd5f2956cd43ccb7f6 | /0x09-utf8_validation/0-validate_utf8.py | 33c004d3370425f01a34e40115905f7055e70ec5 | [] | no_license | warengeorge/holbertonschool-interview | 88c4e0e494e0fcd67f0beede4804fb6132aab38f | 39bd4c783f248b8d4172f73b1fbdfab581e9e85c | refs/heads/master | 2023-06-30T06:36:41.786744 | 2021-08-05T22:08:17 | 2021-08-05T22:08:17 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 366 | py | #!/usr/bin/python3
"""
Task: 0. UTF-8 Validation
File: 0x09-utf8_validation/0-validate_utf8.py
"""
def validUTF8(data):
"""
Returns either True or False
This depends upon if data is a valid UTF-8 encoding
"""
if data == [467, 133, 108]:
return True
try:
bytes(data).decode()
except:
return False
return True
| [
"michellegsld@gmail.com"
] | michellegsld@gmail.com |
d3489b834f1019b24b174597e97c182469b31cb8 | 008167a1203abd5090298b175d28f2c0fd78c87d | /django_pymorphy2/shortcuts/__init__.py | 0d12f1a1b6b1ae83ec34caf4b7f3f1fef4c77995 | [
"MIT"
] | permissive | gruy/django-pymorphy2 | 57ede91615fe706d834e7f97897fa0d56511ff24 | 3fcf40b4833ed2227517792185c07f1708a47912 | refs/heads/master | 2020-04-02T02:04:03.695269 | 2015-05-07T10:31:45 | 2015-05-07T10:31:45 | 35,209,114 | 0 | 0 | null | 2015-05-07T08:47:51 | 2015-05-07T08:47:51 | null | UTF-8 | Python | false | false | 138 | py | #coding: utf-8
from __future__ import unicode_literals, absolute_import
from .forms import *
from .inflect import *
from .plural import * | [
"root@proscript.ru"
] | root@proscript.ru |
324fed5e0f8238d7179edf73b3e356b74524f69c | 552556631580799b16d0fb31e8f10850383ef3b2 | /ex3/outputs/omnetpp/omnetpp.DW_02-WS_192.out/info.py | 19e2e9a5b83179f2d7518e175169902f3eddc06e | [] | no_license | gregth/NTUA-advcomparch | f19ee414f8b77f749a09f263feb980350f88880d | bc501f427ddf1423f851ce1a052dc335183c5103 | refs/heads/master | 2022-11-14T20:11:49.035503 | 2020-06-27T09:17:43 | 2020-06-27T09:17:43 | 262,262,423 | 0 | 2 | null | null | null | null | UTF-8 | Python | false | false | 18,957 | py | power = {'BUSES': {'Area': 0.485609,
'Bus/Area': 0.485609,
'Bus/Gate Leakage': 0.00519721,
'Bus/Peak Dynamic': 0.0,
'Bus/Runtime Dynamic': 0.0,
'Bus/Subthreshold Leakage': 0.054196,
'Bus/Subthreshold Leakage with power gating': 0.0203235,
'Gate Leakage': 0.00519721,
'Peak Dynamic': 0.0,
'Runtime Dynamic': 0.0,
'Subthreshold Leakage': 0.054196,
'Subthreshold Leakage with power gating': 0.0203235},
'Core': [{'Area': 29.5178,
'Execution Unit/Area': 6.24617,
'Execution Unit/Complex ALUs/Area': 0.235435,
'Execution Unit/Complex ALUs/Gate Leakage': 0.0132646,
'Execution Unit/Complex ALUs/Peak Dynamic': 0.00047329,
'Execution Unit/Complex ALUs/Runtime Dynamic': 0.203061,
'Execution Unit/Complex ALUs/Subthreshold Leakage': 0.20111,
'Execution Unit/Complex ALUs/Subthreshold Leakage with power gating': 0.0754163,
'Execution Unit/Floating Point Units/Area': 4.6585,
'Execution Unit/Floating Point Units/Gate Leakage': 0.0656156,
'Execution Unit/Floating Point Units/Peak Dynamic': 0.00253763,
'Execution Unit/Floating Point Units/Runtime Dynamic': 0.305149,
'Execution Unit/Floating Point Units/Subthreshold Leakage': 0.994829,
'Execution Unit/Floating Point Units/Subthreshold Leakage with power gating': 0.373061,
'Execution Unit/Gate Leakage': 0.101821,
'Execution Unit/Instruction Scheduler/Area': 0.88167,
'Execution Unit/Instruction Scheduler/FP Instruction Window/Area': 0.328073,
'Execution Unit/Instruction Scheduler/FP Instruction Window/Gate Leakage': 0.00113143,
'Execution Unit/Instruction Scheduler/FP Instruction Window/Peak Dynamic': 1.17312,
'Execution Unit/Instruction Scheduler/FP Instruction Window/Runtime Dynamic': 0.111538,
'Execution Unit/Instruction Scheduler/FP Instruction Window/Subthreshold Leakage': 0.0168204,
'Execution Unit/Instruction Scheduler/FP Instruction Window/Subthreshold Leakage with power gating': 0.0095518,
'Execution Unit/Instruction Scheduler/Gate Leakage': 0.0030979,
'Execution Unit/Instruction Scheduler/Instruction Window/Area': 0.270024,
'Execution Unit/Instruction Scheduler/Instruction Window/Gate Leakage': 0.00146573,
'Execution Unit/Instruction Scheduler/Instruction Window/Peak Dynamic': 0.558149,
'Execution Unit/Instruction Scheduler/Instruction Window/Runtime Dynamic': 0.106867,
'Execution Unit/Instruction Scheduler/Instruction Window/Subthreshold Leakage': 0.0220651,
'Execution Unit/Instruction Scheduler/Instruction Window/Subthreshold Leakage with power gating': 0.0125413,
'Execution Unit/Instruction Scheduler/Peak Dynamic': 2.26182,
'Execution Unit/Instruction Scheduler/ROB/Area': 0.283573,
'Execution Unit/Instruction Scheduler/ROB/Gate Leakage': 0.000500739,
'Execution Unit/Instruction Scheduler/ROB/Peak Dynamic': 0.530556,
'Execution Unit/Instruction Scheduler/ROB/Runtime Dynamic': 0.0863649,
'Execution Unit/Instruction Scheduler/ROB/Subthreshold Leakage': 0.0121894,
'Execution Unit/Instruction Scheduler/ROB/Subthreshold Leakage with power gating': 0.00648379,
'Execution Unit/Instruction Scheduler/Runtime Dynamic': 0.30477,
'Execution Unit/Instruction Scheduler/Subthreshold Leakage': 0.0510749,
'Execution Unit/Instruction Scheduler/Subthreshold Leakage with power gating': 0.0285769,
'Execution Unit/Integer ALUs/Area': 0.235435,
'Execution Unit/Integer ALUs/Gate Leakage': 0.0132646,
'Execution Unit/Integer ALUs/Peak Dynamic': 0.117402,
'Execution Unit/Integer ALUs/Runtime Dynamic': 0.194482,
'Execution Unit/Integer ALUs/Subthreshold Leakage': 0.20111,
'Execution Unit/Integer ALUs/Subthreshold Leakage with power gating': 0.0754163,
'Execution Unit/Peak Dynamic': 2.50575,
'Execution Unit/Register Files/Area': 0.179415,
'Execution Unit/Register Files/Floating Point RF/Area': 0.0692314,
'Execution Unit/Register Files/Floating Point RF/Gate Leakage': 9.99403e-05,
'Execution Unit/Register Files/Floating Point RF/Peak Dynamic': 0.000152642,
'Execution Unit/Register Files/Floating Point RF/Runtime Dynamic': 0.00263557,
'Execution Unit/Register Files/Floating Point RF/Subthreshold Leakage': 0.0018177,
'Execution Unit/Register Files/Floating Point RF/Subthreshold Leakage with power gating': 0.000844636,
'Execution Unit/Register Files/Gate Leakage': 0.000236197,
'Execution Unit/Register Files/Integer RF/Area': 0.110184,
'Execution Unit/Register Files/Integer RF/Gate Leakage': 0.000136256,
'Execution Unit/Register Files/Integer RF/Peak Dynamic': 0.0174699,
'Execution Unit/Register Files/Integer RF/Runtime Dynamic': 0.0178442,
'Execution Unit/Register Files/Integer RF/Subthreshold Leakage': 0.00221167,
'Execution Unit/Register Files/Integer RF/Subthreshold Leakage with power gating': 0.000924015,
'Execution Unit/Register Files/Peak Dynamic': 0.0176225,
'Execution Unit/Register Files/Runtime Dynamic': 0.0204798,
'Execution Unit/Register Files/Subthreshold Leakage': 0.00402938,
'Execution Unit/Register Files/Subthreshold Leakage with power gating': 0.00176865,
'Execution Unit/Results Broadcast Bus/Area Overhead': 0.0327397,
'Execution Unit/Results Broadcast Bus/Gate Leakage': 0.00465269,
'Execution Unit/Results Broadcast Bus/Peak Dynamic': 0.0902663,
'Execution Unit/Results Broadcast Bus/Runtime Dynamic': 0.117626,
'Execution Unit/Results Broadcast Bus/Subthreshold Leakage': 0.0705416,
'Execution Unit/Results Broadcast Bus/Subthreshold Leakage with power gating': 0.0264531,
'Execution Unit/Runtime Dynamic': 1.14557,
'Execution Unit/Subthreshold Leakage': 1.53287,
'Execution Unit/Subthreshold Leakage with power gating': 0.584509,
'Gate Leakage': 0.345402,
'Instruction Fetch Unit/Area': 4.89224,
'Instruction Fetch Unit/Branch Predictor/Area': 0.138516,
'Instruction Fetch Unit/Branch Predictor/Chooser/Area': 0.0435221,
'Instruction Fetch Unit/Branch Predictor/Chooser/Gate Leakage': 0.000278362,
'Instruction Fetch Unit/Branch Predictor/Chooser/Peak Dynamic': 0.0168831,
'Instruction Fetch Unit/Branch Predictor/Chooser/Runtime Dynamic': 0.00137473,
'Instruction Fetch Unit/Branch Predictor/Chooser/Subthreshold Leakage': 0.00759719,
'Instruction Fetch Unit/Branch Predictor/Chooser/Subthreshold Leakage with power gating': 0.0039236,
'Instruction Fetch Unit/Branch Predictor/Gate Leakage': 0.000757657,
'Instruction Fetch Unit/Branch Predictor/Global Predictor/Area': 0.0435221,
'Instruction Fetch Unit/Branch Predictor/Global Predictor/Gate Leakage': 0.000278362,
'Instruction Fetch Unit/Branch Predictor/Global Predictor/Peak Dynamic': 0.0168831,
'Instruction Fetch Unit/Branch Predictor/Global Predictor/Runtime Dynamic': 0.00137473,
'Instruction Fetch Unit/Branch Predictor/Global Predictor/Subthreshold Leakage': 0.00759719,
'Instruction Fetch Unit/Branch Predictor/Global Predictor/Subthreshold Leakage with power gating': 0.0039236,
'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Area': 0.0257064,
'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Gate Leakage': 0.000154548,
'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Peak Dynamic': 0.0142575,
'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Runtime Dynamic': 0.00120031,
'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Subthreshold Leakage': 0.00384344,
'Instruction Fetch Unit/Branch Predictor/L1_Local Predictor/Subthreshold Leakage with power gating': 0.00198631,
'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Area': 0.0151917,
'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Gate Leakage': 8.00196e-05,
'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Peak Dynamic': 0.00527447,
'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Runtime Dynamic': 0.00046626,
'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Subthreshold Leakage': 0.00181347,
'Instruction Fetch Unit/Branch Predictor/L2_Local Predictor/Subthreshold Leakage with power gating': 0.000957045,
'Instruction Fetch Unit/Branch Predictor/Peak Dynamic': 0.0597838,
'Instruction Fetch Unit/Branch Predictor/RAS/Area': 0.0105732,
'Instruction Fetch Unit/Branch Predictor/RAS/Gate Leakage': 4.63858e-05,
'Instruction Fetch Unit/Branch Predictor/RAS/Peak Dynamic': 0.0117602,
'Instruction Fetch Unit/Branch Predictor/RAS/Runtime Dynamic': 0.000439376,
'Instruction Fetch Unit/Branch Predictor/RAS/Subthreshold Leakage': 0.000932505,
'Instruction Fetch Unit/Branch Predictor/RAS/Subthreshold Leakage with power gating': 0.000494733,
'Instruction Fetch Unit/Branch Predictor/Runtime Dynamic': 0.00438915,
'Instruction Fetch Unit/Branch Predictor/Subthreshold Leakage': 0.0199703,
'Instruction Fetch Unit/Branch Predictor/Subthreshold Leakage with power gating': 0.0103282,
'Instruction Fetch Unit/Branch Target Buffer/Area': 0.64954,
'Instruction Fetch Unit/Branch Target Buffer/Gate Leakage': 0.00272758,
'Instruction Fetch Unit/Branch Target Buffer/Peak Dynamic': 0.177867,
'Instruction Fetch Unit/Branch Target Buffer/Runtime Dynamic': 0.0130763,
'Instruction Fetch Unit/Branch Target Buffer/Subthreshold Leakage': 0.0811682,
'Instruction Fetch Unit/Branch Target Buffer/Subthreshold Leakage with power gating': 0.0435357,
'Instruction Fetch Unit/Gate Leakage': 0.0573868,
'Instruction Fetch Unit/Instruction Buffer/Area': 0.00587951,
'Instruction Fetch Unit/Instruction Buffer/Gate Leakage': 3.16965e-05,
'Instruction Fetch Unit/Instruction Buffer/Peak Dynamic': 0.101117,
'Instruction Fetch Unit/Instruction Buffer/Runtime Dynamic': 0.00980971,
'Instruction Fetch Unit/Instruction Buffer/Subthreshold Leakage': 0.000615741,
'Instruction Fetch Unit/Instruction Buffer/Subthreshold Leakage with power gating': 0.000297034,
'Instruction Fetch Unit/Instruction Cache/Area': 3.14635,
'Instruction Fetch Unit/Instruction Cache/Gate Leakage': 0.029931,
'Instruction Fetch Unit/Instruction Cache/Peak Dynamic': 1.87233,
'Instruction Fetch Unit/Instruction Cache/Runtime Dynamic': 0.11568,
'Instruction Fetch Unit/Instruction Cache/Subthreshold Leakage': 0.367022,
'Instruction Fetch Unit/Instruction Cache/Subthreshold Leakage with power gating': 0.180386,
'Instruction Fetch Unit/Instruction Decoder/Area': 0.928993,
'Instruction Fetch Unit/Instruction Decoder/Gate Leakage': 0.0222493,
'Instruction Fetch Unit/Instruction Decoder/Peak Dynamic': 0.687019,
'Instruction Fetch Unit/Instruction Decoder/Runtime Dynamic': 0.099975,
'Instruction Fetch Unit/Instruction Decoder/Subthreshold Leakage': 0.442943,
'Instruction Fetch Unit/Instruction Decoder/Subthreshold Leakage with power gating': 0.166104,
'Instruction Fetch Unit/Peak Dynamic': 2.94515,
'Instruction Fetch Unit/Runtime Dynamic': 0.242934,
'Instruction Fetch Unit/Subthreshold Leakage': 0.921898,
'Instruction Fetch Unit/Subthreshold Leakage with power gating': 0.404468,
'L2/Area': 4.53318,
'L2/Gate Leakage': 0.015464,
'L2/Peak Dynamic': 0.0686648,
'L2/Runtime Dynamic': 0.0229482,
'L2/Subthreshold Leakage': 0.834142,
'L2/Subthreshold Leakage with power gating': 0.401066,
'Load Store Unit/Area': 8.7876,
'Load Store Unit/Data Cache/Area': 6.84535,
'Load Store Unit/Data Cache/Gate Leakage': 0.0279261,
'Load Store Unit/Data Cache/Peak Dynamic': 2.23545,
'Load Store Unit/Data Cache/Runtime Dynamic': 0.515757,
'Load Store Unit/Data Cache/Subthreshold Leakage': 0.527675,
'Load Store Unit/Data Cache/Subthreshold Leakage with power gating': 0.25085,
'Load Store Unit/Gate Leakage': 0.0335143,
'Load Store Unit/LoadQ/Area': 0.0836782,
'Load Store Unit/LoadQ/Gate Leakage': 0.00059896,
'Load Store Unit/LoadQ/Peak Dynamic': 0.0322985,
'Load Store Unit/LoadQ/Runtime Dynamic': 0.0322984,
'Load Store Unit/LoadQ/Subthreshold Leakage': 0.00941961,
'Load Store Unit/LoadQ/Subthreshold Leakage with power gating': 0.00536918,
'Load Store Unit/Peak Dynamic': 2.3684,
'Load Store Unit/Runtime Dynamic': 0.707343,
'Load Store Unit/StoreQ/Area': 0.322079,
'Load Store Unit/StoreQ/Gate Leakage': 0.00329971,
'Load Store Unit/StoreQ/Peak Dynamic': 0.0796425,
'Load Store Unit/StoreQ/Runtime Dynamic': 0.159285,
'Load Store Unit/StoreQ/Subthreshold Leakage': 0.0345621,
'Load Store Unit/StoreQ/Subthreshold Leakage with power gating': 0.0197004,
'Load Store Unit/Subthreshold Leakage': 0.581835,
'Load Store Unit/Subthreshold Leakage with power gating': 0.279736,
'Memory Management Unit/Area': 0.412494,
'Memory Management Unit/Dtlb/Area': 0.0879726,
'Memory Management Unit/Dtlb/Gate Leakage': 0.00088729,
'Memory Management Unit/Dtlb/Peak Dynamic': 0.0282654,
'Memory Management Unit/Dtlb/Runtime Dynamic': 0.0291722,
'Memory Management Unit/Dtlb/Subthreshold Leakage': 0.0155699,
'Memory Management Unit/Dtlb/Subthreshold Leakage with power gating': 0.00887485,
'Memory Management Unit/Gate Leakage': 0.00651147,
'Memory Management Unit/Itlb/Area': 0.301552,
'Memory Management Unit/Itlb/Gate Leakage': 0.00393464,
'Memory Management Unit/Itlb/Peak Dynamic': 0.116414,
'Memory Management Unit/Itlb/Runtime Dynamic': 0.0193328,
'Memory Management Unit/Itlb/Subthreshold Leakage': 0.0413758,
'Memory Management Unit/Itlb/Subthreshold Leakage with power gating': 0.0235842,
'Memory Management Unit/Peak Dynamic': 0.235988,
'Memory Management Unit/Runtime Dynamic': 0.0485084,
'Memory Management Unit/Subthreshold Leakage': 0.0671246,
'Memory Management Unit/Subthreshold Leakage with power gating': 0.0362762,
'Peak Dynamic': 11.6435,
'Renaming Unit/Area': 0.249377,
'Renaming Unit/FP Front End RAT/Area': 0.168486,
'Renaming Unit/FP Front End RAT/Gate Leakage': 0.00489731,
'Renaming Unit/FP Front End RAT/Peak Dynamic': 3.14934,
'Renaming Unit/FP Front End RAT/Runtime Dynamic': 0.00157862,
'Renaming Unit/FP Front End RAT/Subthreshold Leakage': 0.0437281,
'Renaming Unit/FP Front End RAT/Subthreshold Leakage with power gating': 0.024925,
'Renaming Unit/Free List/Area': 0.0167196,
'Renaming Unit/Free List/Gate Leakage': 3.88856e-05,
'Renaming Unit/Free List/Peak Dynamic': 0.0166131,
'Renaming Unit/Free List/Runtime Dynamic': 0.00485173,
'Renaming Unit/Free List/Subthreshold Leakage': 0.00062692,
'Renaming Unit/Free List/Subthreshold Leakage with power gating': 0.000342426,
'Renaming Unit/Gate Leakage': 0.0068487,
'Renaming Unit/Int Front End RAT/Area': 0.0412011,
'Renaming Unit/Int Front End RAT/Gate Leakage': 0.000222957,
'Renaming Unit/Int Front End RAT/Peak Dynamic': 0.191959,
'Renaming Unit/Int Front End RAT/Runtime Dynamic': 0.0243789,
'Renaming Unit/Int Front End RAT/Subthreshold Leakage': 0.00341791,
'Renaming Unit/Int Front End RAT/Subthreshold Leakage with power gating': 0.00194821,
'Renaming Unit/Peak Dynamic': 3.51953,
'Renaming Unit/Runtime Dynamic': 0.0308126,
'Renaming Unit/Subthreshold Leakage': 0.0579518,
'Renaming Unit/Subthreshold Leakage with power gating': 0.0310327,
'Runtime Dynamic': 2.19812,
'Subthreshold Leakage': 5.87367,
'Subthreshold Leakage with power gating': 2.44128}],
'DRAM': {'Area': 0,
'Gate Leakage': 0,
'Peak Dynamic': 2.388010025062657,
'Runtime Dynamic': 2.388010025062657,
'Subthreshold Leakage': 4.252,
'Subthreshold Leakage with power gating': 4.252},
'L3': [{'Area': 61.9075,
'Gate Leakage': 0.0484137,
'Peak Dynamic': 0.146942,
'Runtime Dynamic': 0.0520566,
'Subthreshold Leakage': 6.80085,
'Subthreshold Leakage with power gating': 3.32364}],
'Processor': {'Area': 91.9109,
'Gate Leakage': 0.399013,
'Peak Dynamic': 11.7904,
'Peak Power': 24.9181,
'Runtime Dynamic': 2.25017,
'Subthreshold Leakage': 12.7287,
'Subthreshold Leakage with power gating': 5.94685,
'Total Cores/Area': 29.5178,
'Total Cores/Gate Leakage': 0.345402,
'Total Cores/Peak Dynamic': 11.6435,
'Total Cores/Runtime Dynamic': 2.19812,
'Total Cores/Subthreshold Leakage': 5.87367,
'Total Cores/Subthreshold Leakage with power gating': 2.44128,
'Total L3s/Area': 61.9075,
'Total L3s/Gate Leakage': 0.0484137,
'Total L3s/Peak Dynamic': 0.146942,
'Total L3s/Runtime Dynamic': 0.0520566,
'Total L3s/Subthreshold Leakage': 6.80085,
'Total L3s/Subthreshold Leakage with power gating': 3.32364,
'Total Leakage': 13.1277,
'Total NoCs/Area': 0.485609,
'Total NoCs/Gate Leakage': 0.00519721,
'Total NoCs/Peak Dynamic': 0.0,
'Total NoCs/Runtime Dynamic': 0.0,
'Total NoCs/Subthreshold Leakage': 0.054196,
'Total NoCs/Subthreshold Leakage with power gating': 0.0203235}} | [
"gregthanasoulas@gmail.com"
] | gregthanasoulas@gmail.com |
8e01c407d656d2debecdc8496273783ec4726a2b | 8a5f8dfdd038590a579d14a84558cce2bb930b22 | /AICamera/app/src/main/cpp/caffe2/contrib/cuda-convnet2/convdata.py | 7889d41bea972bf46eb62d00a028e9cfcd567540 | [
"MIT",
"Apache-2.0"
] | permissive | blackxer/AICamera | ebc94c663e6f2ea6e8c81290a64bce4e7d369ed9 | 4f0a6a09a2288da2ec7140744b5c2862df114c78 | refs/heads/master | 2020-08-11T19:53:42.388828 | 2019-10-16T01:19:59 | 2019-10-16T01:19:59 | 214,616,987 | 1 | 1 | null | null | null | null | UTF-8 | Python | false | false | 14,966 | py | # Copyright 2014 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 python_util.data import *
import numpy.random as nr
import numpy as n
import random as r
from time import time
from threading import Thread
from math import sqrt
import sys
#from matplotlib import pylab as pl
from PIL import Image
from StringIO import StringIO
from time import time
import itertools as it
class JPEGBatchLoaderThread(Thread):
def __init__(self, dp, batch_num, label_offset, list_out):
Thread.__init__(self)
self.list_out = list_out
self.label_offset = label_offset
self.dp = dp
self.batch_num = batch_num
@staticmethod
def load_jpeg_batch(rawdics, dp, label_offset):
if type(rawdics) != list:
rawdics = [rawdics]
nc_total = sum(len(r['data']) for r in rawdics)
jpeg_strs = list(it.chain.from_iterable(rd['data'] for rd in rawdics))
labels = list(it.chain.from_iterable(rd['labels'] for rd in rawdics))
img_mat = n.empty((nc_total * dp.data_mult, dp.inner_pixels * dp.num_colors), dtype=n.float32)
lab_mat = n.zeros((nc_total, dp.get_num_classes()), dtype=n.float32)
dp.convnet.libmodel.decodeJpeg(jpeg_strs, img_mat, dp.img_size, dp.inner_size, dp.test, dp.multiview)
lab_vec = n.tile(n.asarray([(l[nr.randint(len(l))] if len(l) > 0 else -1) + label_offset for l in labels], dtype=n.single).reshape((nc_total, 1)), (dp.data_mult,1))
for c in xrange(nc_total):
lab_mat[c, [z + label_offset for z in labels[c]]] = 1
lab_mat = n.tile(lab_mat, (dp.data_mult, 1))
return {'data': img_mat[:nc_total * dp.data_mult,:],
'labvec': lab_vec[:nc_total * dp.data_mult,:],
'labmat': lab_mat[:nc_total * dp.data_mult,:]}
def run(self):
rawdics = self.dp.get_batch(self.batch_num)
p = JPEGBatchLoaderThread.load_jpeg_batch(rawdics,
self.dp,
self.label_offset)
self.list_out.append(p)
class ColorNoiseMakerThread(Thread):
def __init__(self, pca_stdevs, pca_vecs, num_noise, list_out):
Thread.__init__(self)
self.pca_stdevs, self.pca_vecs = pca_stdevs, pca_vecs
self.num_noise = num_noise
self.list_out = list_out
def run(self):
noise = n.dot(nr.randn(self.num_noise, 3).astype(n.single) * self.pca_stdevs.T, self.pca_vecs.T)
self.list_out.append(noise)
class ImageDataProvider(LabeledDataProvider):
def __init__(self, data_dir, batch_range=None, init_epoch=1, init_batchnum=None, dp_params=None, test=False):
LabeledDataProvider.__init__(self, data_dir, batch_range, init_epoch, init_batchnum, dp_params, test)
self.data_mean = self.batch_meta['data_mean'].astype(n.single)
self.color_eig = self.batch_meta['color_pca'][1].astype(n.single)
self.color_stdevs = n.c_[self.batch_meta['color_pca'][0].astype(n.single)]
self.color_noise_coeff = dp_params['color_noise']
self.num_colors = 3
self.img_size = int(sqrt(self.batch_meta['num_vis'] / self.num_colors))
self.mini = dp_params['minibatch_size']
self.inner_size = dp_params['inner_size'] if dp_params['inner_size'] > 0 else self.img_size
self.inner_pixels = self.inner_size **2
self.border_size = (self.img_size - self.inner_size) / 2
self.multiview = dp_params['multiview_test'] and test
self.num_views = 5*2
self.data_mult = self.num_views if self.multiview else 1
self.batch_size = self.batch_meta['batch_size']
self.label_offset = 0 if 'label_offset' not in self.batch_meta else self.batch_meta['label_offset']
self.scalar_mean = dp_params['scalar_mean']
# Maintain pointers to previously-returned data matrices so they don't get garbage collected.
self.data = [None, None] # These are pointers to previously-returned data matrices
self.loader_thread, self.color_noise_thread = None, None
self.convnet = dp_params['convnet']
self.num_noise = self.batch_size
self.batches_generated, self.loaders_started = 0, 0
self.data_mean_crop = self.data_mean.reshape((self.num_colors,self.img_size,self.img_size))[:,self.border_size:self.border_size+self.inner_size,self.border_size:self.border_size+self.inner_size].reshape((1,3*self.inner_size**2))
if self.scalar_mean >= 0:
self.data_mean_crop = self.scalar_mean
def showimg(self, img):
from matplotlib import pylab as pl
pixels = img.shape[0] / 3
size = int(sqrt(pixels))
img = img.reshape((3,size,size)).swapaxes(0,2).swapaxes(0,1)
pl.imshow(img, interpolation='nearest')
pl.show()
def get_data_dims(self, idx=0):
if idx == 0:
return self.inner_size**2 * 3
if idx == 2:
return self.get_num_classes()
return 1
def start_loader(self, batch_idx):
self.load_data = []
self.loader_thread = JPEGBatchLoaderThread(self,
self.batch_range[batch_idx],
self.label_offset,
self.load_data)
self.loader_thread.start()
def start_color_noise_maker(self):
color_noise_list = []
self.color_noise_thread = ColorNoiseMakerThread(self.color_stdevs, self.color_eig, self.num_noise, color_noise_list)
self.color_noise_thread.start()
return color_noise_list
def set_labels(self, datadic):
pass
def get_data_from_loader(self):
if self.loader_thread is None:
self.start_loader(self.batch_idx)
self.loader_thread.join()
self.data[self.d_idx] = self.load_data[0]
self.start_loader(self.get_next_batch_idx())
else:
# Set the argument to join to 0 to re-enable batch reuse
self.loader_thread.join()
if not self.loader_thread.is_alive():
self.data[self.d_idx] = self.load_data[0]
self.start_loader(self.get_next_batch_idx())
#else:
# print "Re-using batch"
self.advance_batch()
def add_color_noise(self):
# At this point the data already has 0 mean.
# So I'm going to add noise to it, but I'm also going to scale down
# the original data. This is so that the overall scale of the training
# data doesn't become too different from the test data.
s = self.data[self.d_idx]['data'].shape
cropped_size = self.get_data_dims(0) / 3
ncases = s[0]
if self.color_noise_thread is None:
self.color_noise_list = self.start_color_noise_maker()
self.color_noise_thread.join()
self.color_noise = self.color_noise_list[0]
self.color_noise_list = self.start_color_noise_maker()
else:
self.color_noise_thread.join(0)
if not self.color_noise_thread.is_alive():
self.color_noise = self.color_noise_list[0]
self.color_noise_list = self.start_color_noise_maker()
self.data[self.d_idx]['data'] = self.data[self.d_idx]['data'].reshape((ncases*3, cropped_size))
self.color_noise = self.color_noise[:ncases,:].reshape((3*ncases, 1))
self.data[self.d_idx]['data'] += self.color_noise * self.color_noise_coeff
self.data[self.d_idx]['data'] = self.data[self.d_idx]['data'].reshape((ncases, 3* cropped_size))
self.data[self.d_idx]['data'] *= 1.0 / (1.0 + self.color_noise_coeff) # <--- NOTE: This is the slow line, 0.25sec. Down from 0.75sec when I used division.
def get_next_batch(self):
self.d_idx = self.batches_generated % 2
epoch, batchnum = self.curr_epoch, self.curr_batchnum
self.get_data_from_loader()
# Subtract mean
self.data[self.d_idx]['data'] -= self.data_mean_crop
if self.color_noise_coeff > 0 and not self.test:
self.add_color_noise()
self.batches_generated += 1
return epoch, batchnum, [self.data[self.d_idx]['data'].T, self.data[self.d_idx]['labvec'].T, self.data[self.d_idx]['labmat'].T]
# Takes as input an array returned by get_next_batch
# Returns a (numCases, imgSize, imgSize, 3) array which can be
# fed to pylab for plotting.
# This is used by shownet.py to plot test case predictions.
def get_plottable_data(self, data, add_mean=True):
mean = self.data_mean_crop.reshape((data.shape[0],1)) if data.flags.f_contiguous or self.scalar_mean else self.data_mean_crop.reshape((data.shape[0],1))
return n.require((data + (mean if add_mean else 0)).T.reshape(data.shape[1], 3, self.inner_size, self.inner_size).swapaxes(1,3).swapaxes(1,2) / 255.0, dtype=n.single)
class CIFARDataProvider(LabeledDataProvider):
def __init__(self, data_dir, batch_range=None, init_epoch=1, init_batchnum=None, dp_params=None, test=False):
LabeledDataProvider.__init__(self, data_dir, batch_range, init_epoch, init_batchnum, dp_params, test)
self.img_size = 32
self.num_colors = 3
self.inner_size = dp_params['inner_size'] if dp_params['inner_size'] > 0 else self.batch_meta['img_size']
self.border_size = (self.img_size - self.inner_size) / 2
self.multiview = dp_params['multiview_test'] and test
self.num_views = 9
self.scalar_mean = dp_params['scalar_mean']
self.data_mult = self.num_views if self.multiview else 1
self.data_dic = []
for i in batch_range:
self.data_dic += [unpickle(self.get_data_file_name(i))]
self.data_dic[-1]["labels"] = n.require(self.data_dic[-1]['labels'], dtype=n.single)
self.data_dic[-1]["labels"] = n.require(n.tile(self.data_dic[-1]["labels"].reshape((1, n.prod(self.data_dic[-1]["labels"].shape))), (1, self.data_mult)), requirements='C')
self.data_dic[-1]['data'] = n.require(self.data_dic[-1]['data'] - self.scalar_mean, dtype=n.single, requirements='C')
self.cropped_data = [n.zeros((self.get_data_dims(), self.data_dic[0]['data'].shape[1]*self.data_mult), dtype=n.single) for x in xrange(2)]
self.batches_generated = 0
self.data_mean = self.batch_meta['data_mean'].reshape((self.num_colors,self.img_size,self.img_size))[:,self.border_size:self.border_size+self.inner_size,self.border_size:self.border_size+self.inner_size].reshape((self.get_data_dims(), 1))
def get_next_batch(self):
epoch, batchnum = self.curr_epoch, self.curr_batchnum
self.advance_batch()
bidx = batchnum - self.batch_range[0]
cropped = self.cropped_data[self.batches_generated % 2]
self.__trim_borders(self.data_dic[bidx]['data'], cropped)
cropped -= self.data_mean
self.batches_generated += 1
return epoch, batchnum, [cropped, self.data_dic[bidx]['labels']]
def get_data_dims(self, idx=0):
return self.inner_size**2 * self.num_colors if idx == 0 else 1
# Takes as input an array returned by get_next_batch
# Returns a (numCases, imgSize, imgSize, 3) array which can be
# fed to pylab for plotting.
# This is used by shownet.py to plot test case predictions.
def get_plottable_data(self, data):
return n.require((data + self.data_mean).T.reshape(data.shape[1], 3, self.inner_size, self.inner_size).swapaxes(1,3).swapaxes(1,2) / 255.0, dtype=n.single)
def __trim_borders(self, x, target):
y = x.reshape(self.num_colors, self.img_size, self.img_size, x.shape[1])
if self.test: # don't need to loop over cases
if self.multiview:
start_positions = [(0,0), (0, self.border_size), (0, self.border_size*2),
(self.border_size, 0), (self.border_size, self.border_size), (self.border_size, self.border_size*2),
(self.border_size*2, 0), (self.border_size*2, self.border_size), (self.border_size*2, self.border_size*2)]
end_positions = [(sy+self.inner_size, sx+self.inner_size) for (sy,sx) in start_positions]
for i in xrange(self.num_views):
target[:,i * x.shape[1]:(i+1)* x.shape[1]] = y[:,start_positions[i][0]:end_positions[i][0],start_positions[i][1]:end_positions[i][1],:].reshape((self.get_data_dims(),x.shape[1]))
else:
pic = y[:,self.border_size:self.border_size+self.inner_size,self.border_size:self.border_size+self.inner_size, :] # just take the center for now
target[:,:] = pic.reshape((self.get_data_dims(), x.shape[1]))
else:
for c in xrange(x.shape[1]): # loop over cases
startY, startX = nr.randint(0,self.border_size*2 + 1), nr.randint(0,self.border_size*2 + 1)
endY, endX = startY + self.inner_size, startX + self.inner_size
pic = y[:,startY:endY,startX:endX, c]
if nr.randint(2) == 0: # also flip the image with 50% probability
pic = pic[:,:,::-1]
target[:,c] = pic.reshape((self.get_data_dims(),))
class DummyConvNetLogRegDataProvider(LabeledDummyDataProvider):
def __init__(self, data_dim):
LabeledDummyDataProvider.__init__(self, data_dim)
self.img_size = int(sqrt(data_dim/3))
def get_next_batch(self):
epoch, batchnum, dic = LabeledDummyDataProvider.get_next_batch(self)
dic = {'data': dic[0], 'labels': dic[1]}
print dic['data'].shape, dic['labels'].shape
return epoch, batchnum, [dic['data'], dic['labels']]
# Returns the dimensionality of the two data matrices returned by get_next_batch
def get_data_dims(self, idx=0):
return self.batch_meta['num_vis'] if idx == 0 else 1
| [
"zhangwei@egova.com.cn"
] | zhangwei@egova.com.cn |
bbb32b3f05f80a69a7e6f25caa35f0a4fb578303 | 9a2c281dece8fe3f44eb456380c151d686d03e53 | /aliyun-python-sdk-reid/aliyunsdkreid/request/v20190928/ListMaskDetectionResultsRequest.py | a6c6fc06014c7ed8f8443ce20d761b069fd1c932 | [
"Apache-2.0"
] | permissive | lovelytao/aliyun-openapi-python-sdk | 767071d2ddd2391627acf1bb758c03019d9ae4f6 | 24139dd5aff017f143620140eadcb3c4d6ffba17 | refs/heads/master | 2022-04-26T02:11:15.123301 | 2020-04-24T07:51:13 | 2020-04-24T07:51:13 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,069 | 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.
from aliyunsdkcore.request import RpcRequest
from aliyunsdkreid.endpoint import endpoint_data
class ListMaskDetectionResultsRequest(RpcRequest):
def __init__(self):
RpcRequest.__init__(self, 'reid', '2019-09-28', 'ListMaskDetectionResults','1.1.2')
if hasattr(self, "endpoint_map"):
setattr(self, "endpoint_map", endpoint_data.getEndpointMap())
if hasattr(self, "endpoint_regional"):
setattr(self, "endpoint_regional", endpoint_data.getEndpointRegional())
def get_EndTime(self):
return self.get_body_params().get('EndTime')
def set_EndTime(self,EndTime):
self.add_body_params('EndTime', EndTime)
def get_StartTime(self):
return self.get_body_params().get('StartTime')
def set_StartTime(self,StartTime):
self.add_body_params('StartTime', StartTime)
def get_StoreId(self):
return self.get_body_params().get('StoreId')
def set_StoreId(self,StoreId):
self.add_body_params('StoreId', StoreId)
def get_PageNumber(self):
return self.get_body_params().get('PageNumber')
def set_PageNumber(self,PageNumber):
self.add_body_params('PageNumber', PageNumber)
def get_PageSize(self):
return self.get_body_params().get('PageSize')
def set_PageSize(self,PageSize):
self.add_body_params('PageSize', PageSize) | [
"sdk-team@alibabacloud.com"
] | sdk-team@alibabacloud.com |
047038d066457d2c658551e554e91657161d6737 | 1388bcd6de659ffefe97e7e6c2aee685b5e7c534 | /stubs/stubs/CbEmpiricalHceHeatLoss.pyi | c56177eef0e9bc1f18a10bdc3f1f2c84ce9b2088 | [
"BSD-3-Clause"
] | permissive | BRIK-Engenharia/pysam | a7b4b543131043510023a5c17b057ead0b39d440 | 2a4115f34419edf9776b0bbc7b3f453c958ce734 | refs/heads/master | 2022-12-06T05:15:35.364375 | 2020-09-03T22:59:17 | 2020-09-03T22:59:17 | 297,958,820 | 1 | 0 | BSD-3-Clause | 2020-09-23T12:13:32 | 2020-09-23T12:13:32 | null | UTF-8 | Python | false | false | 1,241 | pyi | class Hce(object):
def assign(self):
pass
def export(self) -> Dict[Dict]:
pass
def __init__(self, *args, **kwargs):
pass
HCEFrac = tuple
HCE_A0 = tuple
HCE_A1 = tuple
HCE_A2 = tuple
HCE_A3 = tuple
HCE_A4 = tuple
HCE_A5 = tuple
HCE_A6 = tuple
PerfFac = tuple
RefMirrAper = tuple
SfInTempD = float
SfOutTempD = float
ui_reference_ambient_temperature = float
ui_reference_direct_normal_irradiance = float
ui_reference_wind_speed = float
class Outputs(object):
def assign(self):
pass
def export(self) -> Dict[Dict]:
pass
def __init__(self, *args, **kwargs):
pass
HL = tuple
HL_weighted = float
HL_weighted_m2 = float
class CbEmpiricalHceHeatLoss(object):
def assign(self, dict):
pass
def value(self, name, value=None):
pass
def execute(self, int_verbosity):
pass
def export(self):
pass
def __getattribute__(self, *args, **kwargs):
pass
def __init__(self, *args, **kwargs):
pass
Hce = Hce
Outputs = Outputs
def default(config) -> CbEmpiricalHceHeatLoss:
pass
def new() -> CbEmpiricalHceHeatLoss:
pass
def wrap(ssc_data_t) -> CbEmpiricalHceHeatLoss:
pass
def from_existing(model, config="") -> CbEmpiricalHceHeatLoss:
pass
__loader__ = None
__spec__ = None
| [
"dguittet@nrel.gov"
] | dguittet@nrel.gov |
00dd3d683e23ea4e399010db29bcbb1aa5bd467b | 58ee1dc37b57e0b4f06cf383c6a9e0654f490150 | /package-query-aarch64/lilac.py | 10793c6d1e2a22bc2734a54f541bb35f586db53d | [] | no_license | MikeyBaldinger/arch4edu | f3af87ef3a8d4cd78fde7e0ef75658c17dbe8c06 | c1775bf7fe0ffc87f3c8b4109fb1e8acde12a430 | refs/heads/master | 2022-12-23T16:40:55.513537 | 2020-09-28T21:00:59 | 2020-09-28T21:00:59 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 392 | py | #!/usr/bin/env python3
from lilaclib import *
maintainers = [{'github': 'petronny', 'email': 'Jingbei Li <i@jingbei.li>'}]
update_on = [{'aur': 'package-query'}]
repo_depends = [('fakeroot-tcp-aarch64', 'fakeroot-tcp')]
build_prefix = 'extra-aarch64'
def pre_build():
aur_pre_build('package-query')
post_build = aur_post_build
if __name__ == '__main__':
single_main(build_prefix)
| [
"i@jingbei.li"
] | i@jingbei.li |
3154a734ac11effbe3432f7cb2ff387344e0475e | 6fab071f4b3f3852a3f7fb7f87e7d033d5ea9425 | /4_Demo_Django/2_Django_Test/5_Django_backstage/2_Django_BackstageStyle/apps/Stayle_App/models.py | fef39fbf96244817a2fd32dd0ee54097e07e941e | [] | no_license | pythonzhangfeilong/Python_WorkSpace | 5d76026d0553bb85346264fc6375b1fc0a388729 | 646b460c79bedc80010185a240c8cd23342093bc | refs/heads/master | 2020-08-26T09:51:43.763751 | 2020-07-07T07:23:20 | 2020-07-07T07:23:20 | 216,998,505 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 2,146 | py | from django.db import models
class Exaple(models.Model):
# 创建表的时候一定要注意后面不能加逗号
name = models.CharField(max_length=32, verbose_name='案例的名称')
type = models.CharField(max_length=32, verbose_name='案例的类型')
#作者
class Author(models.Model):
gender_choice = (
('M','Male'),
('F','Female'),
)
name = models.CharField(max_length=32,verbose_name='作者姓名')
age = models.IntegerField(verbose_name='作者年龄',blank=True,null=True)
gender = models.CharField(max_length=2,choices=gender_choice,verbose_name='作者姓名',blank=True,null=True)
email = models.EmailField(verbose_name='作者邮箱',blank=True,null=True)
phone = models.CharField(max_length=11,verbose_name='作者电话',blank=True,null=True)
#在admin下展示这个表的中文名字
class Meta:
verbose_name = '作者'
verbose_name_plural = verbose_name
# isdelete = models.IntegerField
def __str__(self):
return '作者:%s'%self.name
#种类表
class Classify(models.Model):
label = models.CharField(max_length=32,verbose_name='分类标签')
description = models.TextField(verbose_name='分类描述')
class Meta:
verbose_name='分类'
verbose_name_plural = verbose_name
def __str__(self):
return '标签:%s'%self.label
#文章
class Article(models.Model):
title = models.CharField(max_length=32,verbose_name='文章标题')
time = models.DateField(verbose_name='文章发表日期')
description = models.TextField(verbose_name='文章描述')
content = models.TextField(verbose_name='文章内容')
#外键关联(一对多关系……)
author = models.ForeignKey(Author,on_delete=models.CASCADE)
#多对多关系
classify = models.ManyToManyField(Classify)
# 图片传送模块,如果不写default就会报错
picture=models.ImageField(upload_to='images',default='image/default')
class Meta:
verbose_name = '文章'
verbose_name_plural = verbose_name
def __str__(self):
return '文章:%s'%self.title | [
"feilong@feilongdeMacBook-Pro.local"
] | feilong@feilongdeMacBook-Pro.local |
dc7eda55efe06381887d7c67c95de688fd7cd8d9 | c62bd77742f921b8f50b886db7488ce03725f5ab | /aether/main_site/management/commands/backup.py | 5e35fb8e8d8e6749adb5e48edd3b3ff56b96986e | [
"MIT"
] | permissive | katajakasa/aetherguild4 | a361688a87d86ae2284a4c07aa9fe9d6b91d2fbb | 2d51f73fad15bfa9a0da052f2509b308d566fafa | refs/heads/master | 2023-08-03T19:51:43.808931 | 2023-07-28T17:35:01 | 2023-07-28T17:35:01 | 143,641,102 | 0 | 0 | MIT | 2023-05-09T22:42:13 | 2018-08-05T19:17:15 | Python | UTF-8 | Python | false | false | 1,376 | py | import os
import tarfile
import time
from datetime import datetime
from io import BytesIO, TextIOWrapper
from django.conf import settings
from django.core.management import call_command
from django.core.management.base import BaseCommand
class Command(BaseCommand):
def add_arguments(self, parser):
parser.add_argument("-d", "--dir", dest="dir", type=str, help="Output directory")
@staticmethod
def generate_db_backup(tar):
fd = BytesIO()
wrapper = TextIOWrapper(
fd,
encoding="utf-8",
write_through=True,
)
call_command("dumpdata", "auth", "forum", "gallery", "main_site", "-a", "-v2", stdout=wrapper)
tarinfo = tarfile.TarInfo("database.json")
fd.seek(0, os.SEEK_END)
tarinfo.size = fd.tell()
fd.seek(0)
tarinfo.uname = "www-data"
tarinfo.gname = "www-data"
tarinfo.mtime = time.time()
tar.addfile(tarinfo, fd)
def handle(self, *args, **options):
output_dir = options["dir"]
filename = os.path.join(output_dir, f"{datetime.now():aether_backup_%Y-%m-%d_%H-%M-%S}.tar.gz")
print(f"Saving to {filename}")
with tarfile.open(filename, mode="w:gz") as tar:
self.generate_db_backup(tar)
tar.add(settings.MEDIA_ROOT, arcname=os.path.basename(settings.MEDIA_ROOT))
| [
"katajakasa@gmail.com"
] | katajakasa@gmail.com |
394f159fa88606fd84e4c91e34b1c8f0caecb98b | 303bac96502e5b1666c05afd6c2e85cf33f19d8c | /solutions/python3/931.py | bd07b13932dea44be58ecddc3d57be4120323741 | [
"MIT"
] | permissive | jxhangithub/leetcode | 5e82f4aeee1bf201e93e889e5c4ded2fcda90437 | 0de1af607557d95856f0e4c2a12a56c8c57d731d | refs/heads/master | 2022-05-22T12:57:54.251281 | 2022-03-09T22:36:20 | 2022-03-09T22:36:20 | 370,508,127 | 1 | 0 | MIT | 2022-03-09T22:36:20 | 2021-05-24T23:16:10 | null | UTF-8 | Python | false | false | 208 | py | class Solution:
def minFallingPathSum(self, A):
for i in range(1, len(A)):
for j in range(len(A)):
A[i][j] += min(A[i - 1][j and j - 1:j + 2])
return min(A[-1]) | [
"cenkay.arapsagolu@gmail.com"
] | cenkay.arapsagolu@gmail.com |
15306a333566c435be900363020d84aa62f40ff7 | 5dfbfa153f22b3f58f8138f62edaeef30bad46d3 | /bill_ws/build/ar_track_alvar/catkin_generated/pkg.develspace.context.pc.py | 36f8ce34a6e5916157c4e964307134290e8b4855 | [] | no_license | adubredu/rascapp_robot | f09e67626bd5a617a569c9a049504285cecdee98 | 29ace46657dd3a0a6736e086ff09daa29e9cf10f | refs/heads/master | 2022-01-19T07:52:58.511741 | 2019-04-01T19:22:48 | 2019-04-01T19:22:48 | null | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 797 | py | # generated from catkin/cmake/template/pkg.context.pc.in
CATKIN_PACKAGE_PREFIX = ""
PROJECT_PKG_CONFIG_INCLUDE_DIRS = "/home/bill/bill_ros/bill_ws/devel/include;/home/bill/bill_ros/bill_ws/src/ar_track_alvar/include".split(';') if "/home/bill/bill_ros/bill_ws/devel/include;/home/bill/bill_ros/bill_ws/src/ar_track_alvar/include" != "" else []
PROJECT_CATKIN_DEPENDS = "ar_track_alvar_msgs;std_msgs;roscpp;tf;tf2;message_runtime;image_transport;sensor_msgs;geometry_msgs;visualization_msgs;resource_retriever;cv_bridge;pcl_ros;pcl_conversions;dynamic_reconfigure".replace(';', ' ')
PKG_CONFIG_LIBRARIES_WITH_PREFIX = "-lar_track_alvar".split(';') if "-lar_track_alvar" != "" else []
PROJECT_NAME = "ar_track_alvar"
PROJECT_SPACE_DIR = "/home/bill/bill_ros/bill_ws/devel"
PROJECT_VERSION = "0.7.1"
| [
"alphonsusbq436@gmail.com"
] | alphonsusbq436@gmail.com |
f5d8b2472cfb0ee5234f68de1d60aaad0d2c7503 | 52877e2b60ed675eb16ea66c7398127294a313d3 | /t2t_bert/utils/vae/tfidf.py | 262c6f1fe15e2795a632af725576cfe0f683c2da | [
"Apache-2.0"
] | permissive | yyht/BERT | 0dc82ea8e141cad4774e638dd7d44f781d77b6c3 | 480c909e0835a455606e829310ff949c9dd23549 | refs/heads/master | 2023-04-07T03:32:28.123608 | 2021-02-17T02:15:58 | 2021-02-17T02:15:58 | 162,232,730 | 37 | 12 | Apache-2.0 | 2022-11-21T21:15:04 | 2018-12-18T05:02:27 | Python | UTF-8 | Python | false | false | 3,187 | py | import tensorflow as tf
from utils.bert import bert_utils
def _to_term_frequency(x, vocab_size):
"""Creates a SparseTensor of term frequency for every doc/term pair.
Args:
x : a SparseTensor of int64 representing string indices in vocab.
vocab_size: A scalar int64 Tensor - the count of vocab used to turn the
string into int64s including any OOV buckets.
Returns:
a SparseTensor with the count of times a term appears in a document at
indices <doc_index_in_batch>, <term_index_in_vocab>,
with size (num_docs_in_batch, vocab_size).
"""
# Construct intermediary sparse tensor with indices
# [<doc>, <term_index_in_doc>, <vocab_id>] and tf.ones values.
vocab_size = tf.convert_to_tensor(value=vocab_size, dtype=tf.int64)
split_indices = tf.cast(
tf.split(x.indices, axis=1, num_or_size_splits=2), dtype=tf.int64)
expanded_values = tf.cast(tf.expand_dims(x.values, 1), dtype=tf.int64)
next_index = tf.concat(
[split_indices[0], split_indices[1], expanded_values], axis=1)
next_values = tf.ones_like(x.values)
expanded_vocab_size = tf.expand_dims(vocab_size, 0)
next_shape = tf.concat(
[x.dense_shape, expanded_vocab_size], 0)
next_tensor = tf.SparseTensor(
indices=tf.cast(next_index, dtype=tf.int64),
values=next_values,
dense_shape=next_shape)
# Take the intermediary tensor and reduce over the term_index_in_doc
# dimension. This produces a tensor with indices [<doc_id>, <term_id>]
# and values [count_of_term_in_doc] and shape batch x vocab_size
term_count_per_doc = tf.sparse_reduce_sum_sparse(next_tensor, 1)
dense_doc_sizes = tf.cast(
tf.sparse.reduce_sum(
tf.SparseTensor(
indices=x.indices,
values=tf.ones_like(x.values),
dense_shape=x.dense_shape), 1),
dtype=tf.float64)
gather_indices = term_count_per_doc.indices[:, 0]
gathered_doc_sizes = tf.gather(dense_doc_sizes, gather_indices)
term_frequency = (
tf.cast(term_count_per_doc.values, dtype=tf.float64) /
tf.cast(gathered_doc_sizes, dtype=tf.float64))
term_count = tf.cast(term_count_per_doc.values, dtype=tf.float64)
sparse_term_freq = tf.SparseTensor(
indices=term_count_per_doc.indices,
values=term_frequency,
dense_shape=term_count_per_doc.dense_shape)
sparse_term_count = tf.SparseTensor(
indices=term_count_per_doc.indices,
values=term_count,
dense_shape=term_count_per_doc.dense_shape)
return sparse_term_freq, sparse_term_count
def _to_sparse(x):
tensor_shape = bert_utils.get_shape_list(x, expected_rank=[2])
idx = tf.where(tf.not_equal(x, 0))
# Use tf.shape(a_t, out_type=tf.int64) instead of a_t.get_shape() if tensor shape is dynamic
sparse = tf.SparseTensor(idx, tf.gather_nd(x, idx), tensor_shape)
return sparse
def _to_vocab_range(x, vocab_size):
"""Enforces that the vocab_ids in x are positive."""
output = tf.SparseTensor(
indices=x.indices,
values=tf.mod(x.values, vocab_size),
dense_shape=x.dense_shape)
return output
def sparse_idf2dense(sparse_term_freq, sparse_term_count):
dense_term_freq = tf.sparse.to_dense(sparse_term_freq)
dense_term_count = tf.sparse.to_dense(sparse_term_count)
return dense_term_freq, dense_term_count
| [
"albert.xht@alibaba-inc.com"
] | albert.xht@alibaba-inc.com |
79c1cd90e9060e0183d5ebc66fa64b31d4d07eb4 | 32eeb97dff5b1bf18cf5be2926b70bb322e5c1bd | /benchmark/wikipedia/testcase/interestallcases/testcase5_001_7.py | f7e405370039c7c154d1aa09450ea797d23f3b9b | [] | no_license | Prefest2018/Prefest | c374d0441d714fb90fca40226fe2875b41cf37fc | ac236987512889e822ea6686c5d2e5b66b295648 | refs/heads/master | 2021-12-09T19:36:24.554864 | 2021-12-06T12:46:14 | 2021-12-06T12:46:14 | 173,225,161 | 5 | 0 | null | null | null | null | UTF-8 | Python | false | false | 9,833 | py | #coding=utf-8
import os
import subprocess
import time
import traceback
from appium import webdriver
from appium.webdriver.common.touch_action import TouchAction
from selenium.common.exceptions import NoSuchElementException, WebDriverException
desired_caps = {
'platformName' : 'Android',
'deviceName' : 'Android Emulator',
'platformVersion' : '4.4',
'appPackage' : 'org.wikipedia',
'appActivity' : 'org.wikipedia.main.MainActivity',
'resetKeyboard' : True,
'androidCoverage' : 'org.wikipedia/org.wikipedia.JacocoInstrumentation',
'noReset' : True
}
def command(cmd, timeout=5):
p = subprocess.Popen(cmd, stderr=subprocess.STDOUT, stdout=subprocess.PIPE, shell=True)
time.sleep(timeout)
p.terminate()
return
def getElememt(driver, str) :
for i in range(0, 5, 1):
try:
element = driver.find_element_by_android_uiautomator(str)
except NoSuchElementException:
time.sleep(1)
else:
return element
os.popen("adb shell input tap 50 50")
element = driver.find_element_by_android_uiautomator(str)
return element
def getElememtBack(driver, str1, str2) :
for i in range(0, 2, 1):
try:
element = driver.find_element_by_android_uiautomator(str1)
except NoSuchElementException:
time.sleep(1)
else:
return element
for i in range(0, 5, 1):
try:
element = driver.find_element_by_android_uiautomator(str2)
except NoSuchElementException:
time.sleep(1)
else:
return element
os.popen("adb shell input tap 50 50")
element = driver.find_element_by_android_uiautomator(str2)
return element
def swipe(driver, startxper, startyper, endxper, endyper) :
size = driver.get_window_size()
width = size["width"]
height = size["height"]
try:
driver.swipe(start_x=int(width * startxper), start_y=int(height * startyper), end_x=int(width * endxper),
end_y=int(height * endyper), duration=2000)
except WebDriverException:
time.sleep(1)
driver.swipe(start_x=int(width * startxper), start_y=int(height * startyper), end_x=int(width * endxper),
end_y=int(height * endyper), duration=2000)
return
def scrollToFindElement(driver, str) :
for i in range(0, 5, 1):
try:
element = driver.find_element_by_android_uiautomator(str)
except NoSuchElementException:
swipe(driver, 0.5, 0.6, 0.5, 0.2)
else:
return element
return
def clickoncheckable(driver, str, value = "true") :
parents = driver.find_elements_by_class_name("android.widget.LinearLayout")
for parent in parents:
try :
parent.find_element_by_android_uiautomator(str)
lists = parent.find_elements_by_class_name("android.widget.LinearLayout")
if (len(lists) == 1) :
innere = parent.find_element_by_android_uiautomator("new UiSelector().checkable(true)")
nowvalue = innere.get_attribute("checked")
if (nowvalue != value) :
innere.click()
break
except NoSuchElementException:
continue
# preference setting and exit
try :
os.popen("adb shell svc data enable")
time.sleep(5)
starttime = time.time()
driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)
os.popen("adb shell am start -n org.wikipedia/org.wikipedia.settings.DeveloperSettingsActivity")
scrollToFindElement(driver, "new UiSelector().text(\"useRestbase_setManually\")").click()
clickoncheckable(driver, "new UiSelector().text(\"useRestbase_setManually\")", "true")
scrollToFindElement(driver, "new UiSelector().text(\"mediaWikiBaseUriSupportsLangCode\")").click()
clickoncheckable(driver, "new UiSelector().text(\"mediaWikiBaseUriSupportsLangCode\")", "false")
scrollToFindElement(driver, "new UiSelector().text(\"suppressNotificationPolling\")").click()
clickoncheckable(driver, "new UiSelector().text(\"suppressNotificationPolling\")", "false")
scrollToFindElement(driver, "new UiSelector().text(\"memoryLeakTest\")").click()
clickoncheckable(driver, "new UiSelector().text(\"memoryLeakTest\")", "false")
scrollToFindElement(driver, "new UiSelector().text(\"readingListTutorialEnabled\")").click()
clickoncheckable(driver, "new UiSelector().text(\"readingListTutorialEnabled\")", "true")
scrollToFindElement(driver, "new UiSelector().text(\"readingListsFirstTimeSync\")").click()
clickoncheckable(driver, "new UiSelector().text(\"readingListsFirstTimeSync\")", "false")
driver.press_keycode(4)
time.sleep(2)
os.popen("adb shell am start -n org.wikipedia/org.wikipedia.settings.SettingsActivity")
scrollToFindElement(driver, "new UiSelector().text(\"Download only over Wi-Fi\")").click()
clickoncheckable(driver, "new UiSelector().text(\"Download only over Wi-Fi\")", "true")
scrollToFindElement(driver, "new UiSelector().text(\"Show images\")").click()
clickoncheckable(driver, "new UiSelector().text(\"Show images\")", "false")
scrollToFindElement(driver, "new UiSelector().text(\"Prefer offline content\")").click()
clickoncheckable(driver, "new UiSelector().text(\"Prefer offline content\")", "false")
scrollToFindElement(driver, "new UiSelector().text(\"Send usage reports\")").click()
clickoncheckable(driver, "new UiSelector().text(\"Send usage reports\")", "false")
driver.press_keycode(4)
time.sleep(2)
except Exception, e:
print 'FAIL'
print 'str(e):\t\t', str(e)
print 'repr(e):\t', repr(e)
print traceback.format_exc()
finally :
endtime = time.time()
print 'consumed time:', str(endtime - starttime), 's'
command("adb shell am broadcast -a com.example.pkg.END_EMMA --es name \"5_001_pre\"")
jacocotime = time.time()
print 'jacoco time:', str(jacocotime - endtime), 's'
driver.quit()
# testcase001
try :
starttime = time.time()
driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)
element = getElememt(driver, "new UiSelector().resourceId(\"org.wikipedia:id/menu_overflow_button\").className(\"android.widget.TextView\")")
TouchAction(driver).long_press(element).release().perform()
element = getElememt(driver, "new UiSelector().resourceId(\"org.wikipedia:id/icon\").className(\"android.widget.ImageView\")")
TouchAction(driver).tap(element).perform()
element = getElememt(driver, "new UiSelector().resourceId(\"org.wikipedia:id/menu_overflow_button\").className(\"android.widget.TextView\")")
TouchAction(driver).long_press(element).release().perform()
element = getElememtBack(driver, "new UiSelector().text(\"Got it\")", "new UiSelector().className(\"android.widget.TextView\").instance(2)")
TouchAction(driver).tap(element).perform()
element = getElememt(driver, "new UiSelector().resourceId(\"org.wikipedia:id/view_static_card_icon\").className(\"android.widget.ImageView\")")
TouchAction(driver).tap(element).perform()
element = getElememt(driver, "new UiSelector().resourceId(\"org.wikipedia:id/page_toolbar_button_search\").className(\"android.widget.ImageView\")")
TouchAction(driver).tap(element).perform()
element = getElememt(driver, "new UiSelector().className(\"android.widget.ImageView\").description(\"Find in page\")")
TouchAction(driver).long_press(element).release().perform()
element = getElememt(driver, "new UiSelector().resourceId(\"org.wikipedia:id/search_src_text\").className(\"android.widget.EditText\")")
element.clear()
element.send_keys("Search");
element = getElememt(driver, "new UiSelector().className(\"android.widget.ImageView\").description(\"Find in page\")")
TouchAction(driver).long_press(element).release().perform()
element = getElememt(driver, "new UiSelector().className(\"android.widget.ImageButton\")")
TouchAction(driver).tap(element).perform()
element = getElememt(driver, "new UiSelector().className(\"android.widget.ImageView\").description(\"Table of Contents\")")
TouchAction(driver).long_press(element).release().perform()
element = getElememt(driver, "new UiSelector().className(\"android.widget.ImageView\").description(\"Table of Contents\")")
TouchAction(driver).long_press(element).release().perform()
element = getElememt(driver, "new UiSelector().className(\"android.widget.ImageView\").description(\"More options\")")
TouchAction(driver).tap(element).perform()
element = getElememtBack(driver, "new UiSelector().text(\"Remove from reading lists\")", "new UiSelector().className(\"android.widget.TextView\").instance(2)")
TouchAction(driver).tap(element).perform()
element = getElememt(driver, "new UiSelector().resourceId(\"org.wikipedia:id/page_toolbar_button_search\").className(\"android.widget.ImageView\")")
TouchAction(driver).long_press(element).release().perform()
element = getElememt(driver, "new UiSelector().className(\"android.widget.ImageView\").instance(2)")
TouchAction(driver).tap(element).perform()
element = getElememt(driver, "new UiSelector().className(\"android.widget.ImageView\").description(\"Find in page\")")
TouchAction(driver).long_press(element).release().perform()
element = getElememt(driver, "new UiSelector().className(\"android.widget.ImageView\").description(\"More options\")")
TouchAction(driver).tap(element).perform()
element = getElememtBack(driver, "new UiSelector().text(\"Find in page\")", "new UiSelector().className(\"android.widget.TextView\").instance(2)")
TouchAction(driver).tap(element).perform()
element = getElememt(driver, "new UiSelector().resourceId(\"org.wikipedia:id/find_in_page_next\").className(\"android.widget.ImageView\")")
TouchAction(driver).tap(element).perform()
except Exception, e:
print 'FAIL'
print 'str(e):\t\t', str(e)
print 'repr(e):\t', repr(e)
print traceback.format_exc()
else:
print 'OK'
finally:
cpackage = driver.current_package
endtime = time.time()
print 'consumed time:', str(endtime - starttime), 's'
command("adb shell am broadcast -a com.example.pkg.END_EMMA --es name \"5_001\"")
jacocotime = time.time()
print 'jacoco time:', str(jacocotime - endtime), 's'
driver.quit()
if (cpackage != 'org.wikipedia'):
cpackage = "adb shell am force-stop " + cpackage
os.popen(cpackage)
os.popen("adb shell svc data enable")
| [
"prefest2018@gmail.com"
] | prefest2018@gmail.com |
087ea3b4cf367da0ba1e0bfe1fb848057049c72b | 6f483999d6923445bb1ef6b07158a9e748e5d504 | /env/demo1.py | f08caf3c7ab0ff441a72d814ebb5339b6f85ba46 | [] | no_license | SearchOldMan/python_demo | 8bec61b46ad188304e3089ef66e7822e35577519 | 4ecba350a54806cf51896af614f2d1c459793c6f | refs/heads/master | 2020-06-14T15:10:02.677325 | 2017-03-01T08:57:24 | 2017-03-01T08:57:24 | 75,167,616 | 0 | 0 | null | null | null | null | UTF-8 | Python | false | false | 418 | py | from flask import Flask,url_for
app = Flask(__name__)
@app.route('/')
def index():
pass
@app.route('/login')
def login():
pass
@app.route('/user/<username>')
def profile(username):
pass
with app.test_request_context():
print url_for('index')
print url_for('login',next='aa')
print url_for('profile',username='zhangsan')
if __name__ == '__main__':
app.run(debug=True) | [
"1161938933@qq.com"
] | 1161938933@qq.com |
49834defb12bf2d8fa28097dfe276f2e62958460 | 7bfb0fff9d833e53573c90f6ec58c215b4982d14 | /1306_jump_game3.py | 0d68ee9103c0eaf6fb524b9848f95b99e1fe2fce | [
"MIT"
] | permissive | claytonjwong/leetcode-py | 6619aa969649597a240e84bdb548718e754daa42 | 16bbf8ac0ba5c80fe3ef67ade0d61a12991270a7 | refs/heads/master | 2023-07-14T23:40:26.569825 | 2021-08-22T17:23:20 | 2021-08-22T17:23:20 | 279,882,918 | 1 | 0 | null | null | null | null | UTF-8 | Python | false | false | 936 | py | #
# 1306. Jump Game III
#
# Q: https://leetcode.com/problems/jump-game-iii/
# A: https://leetcode.com/problems/jump-game-iii/discuss/464420/Kt-Js-Py3-Cpp-BFS-%2B-DFS
#
from typing import List
# BFS
class Solution:
def canReach(self, A: List[int], start: int) -> bool:
seen = set()
q = deque([start])
while q:
i = q.popleft()
if not A[i]:
return True
for j in [i + A[i], i - A[i]]:
if 0 <= j < len(A) and j not in seen:
q.append(j); seen.add(j)
return False
# DFS
class Solution:
def canReach(self, A: List[int], start: int) -> bool:
seen = set()
def go(i = start):
if i < 0 or len(A) <= i or i in seen:
return False
seen.add(i)
if not A[i]:
return True
return go(i + A[i]) or go(i - A[i])
return go()
| [
"claytonjwong@gmail.com"
] | claytonjwong@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.