text stringlengths 38 1.54M |
|---|
import datetime
import sys
import numpy as np
import pandas as pd
from WindPy import w
MIN_RETURN = 5
MIN_YEARS = 5
REPORT_DATE = '20191231'
REPORT_DATE_PRE = '20190930'
if __name__ == '__main__':
fund_list = []
fund_list_all = []
try:
file_object = open('./funds.txt', mode='r', encoding='UTF-8')
file_object2 = open('./funds_all.txt', mode='r', encoding='UTF-8')
fund_list = file_object.readlines()
fund_list_all = file_object2.readlines()
file_object.close()
file_object2.close()
except FileNotFoundError as e:
print(e)
fund_list = [f.replace('\n', '') for f in fund_list]
fund_list_all = [f.replace('\n', '') for f in fund_list_all]
w.start()
funds = w.wss(','.join(fund_list),
"fund_fullname,fund_setupdate,fund_fundmanager,fund_manager_fundno,fund_manager_totalnetasset,fund_manager_startdate,fund_manager_onthepostdays,fund_manager_geometricannualizedyield,fund_manager_arithmeticannualizedyield,fund_manager_managerworkingyears", "order=1;unit=1;returnType=1")
if funds.ErrorCode != 0:
print(funds.Data)
sys.exit(0)
funds_df = pd.DataFrame(funds.Data, index=funds.Fields,
columns=funds.Codes).T
funds_df['order'] = 1
# funds = w.wss(','.join(fund_list),
# "fund_fullname,fund_setupdate,fund_fundmanager,fund_manager_fundno,fund_manager_totalnetasset,fund_manager_startdate,fund_manager_onthepostdays,fund_manager_geometricannualizedyield,fund_manager_arithmeticannualizedyield,fund_manager_managerworkingyears", "order=2;unit=1;returnType=1")
# if funds.ErrorCode != 0:
# print(funds.Data)
# sys.exit(0)
# funds_df2 = pd.DataFrame(funds.Data, index=funds.Fields,
# columns=funds.Codes).T
# funds_df2['order'] = 2
# funds = w.wss(','.join(fund_list),
# "fund_fullname,fund_setupdate,fund_fundmanager,fund_manager_fundno,fund_manager_totalnetasset,fund_manager_startdate,fund_manager_onthepostdays,fund_manager_geometricannualizedyield,fund_manager_arithmeticannualizedyield,fund_manager_managerworkingyears", "order=3;unit=1;returnType=1")
# if funds.ErrorCode != 0:
# print(funds.Data)
# sys.exit(0)
# funds_df3 = pd.DataFrame(funds.Data, index=funds.Fields,
# columns=funds.Codes).T
# funds_df3['order'] = 3
# funds_df.append(funds_df2)
# funds_df.append(funds_df3)
funds_df = funds_df[(funds_df['FUND_MANAGER_MANAGERWORKINGYEARS'] >
MIN_YEARS) & (funds_df['FUND_MANAGER_GEOMETRICANNUALIZEDYIELD'] > MIN_RETURN)]
codes = funds_df.index.tolist()
for i in range(1, 11):
funds_stocks = w.wss(",".join(
codes), "prt_topstockwindcode,prt_topstockname,prt_topproportiontofloating,prt_heavilyheldstocktonav,prt_fundnoofstocks", "rptDate="+REPORT_DATE+";order="+str(i))
if funds_stocks.ErrorCode != 0:
print(funds_stocks.Data)
sys.exit(0)
if i == 1:
funds_stocks_df = pd.DataFrame(funds_stocks.Data, index=funds_stocks.Fields,
columns=funds_stocks.Codes).T
else:
funds_stocks_df = funds_stocks_df.append(pd.DataFrame(funds_stocks.Data, index=funds_stocks.Fields,
columns=funds_stocks.Codes).T)
funds_stocks_df = funds_stocks_df.sort_index()
for i in range(1, 11):
funds_stocks = w.wss(",".join(
codes), "prt_topstockwindcode,prt_topstockname,prt_topproportiontofloating,prt_heavilyheldstocktonav,prt_fundnoofstocks", "rptDate="+REPORT_DATE_PRE+";order="+str(i))
if funds_stocks.ErrorCode != 0:
print(funds_stocks.Data)
sys.exit(0)
if i == 1:
funds_stocks_df2 = pd.DataFrame(funds_stocks.Data, index=funds_stocks.Fields,
columns=funds_stocks.Codes).T
else:
funds_stocks_df2 = funds_stocks_df2.append(pd.DataFrame(funds_stocks.Data, index=funds_stocks.Fields,
columns=funds_stocks.Codes).T)
funds_stocks_df2 = funds_stocks_df2.sort_index()
funds_type = w.wss(
','.join(fund_list_all[:5000]), "fund_fullname,fund_firstinvesttype,fund_investtype,fund_themetype,fund_type,fund_trackindexcode,fund_etfwindcode,prt_netasset", "unit=1;rptDate="+REPORT_DATE)
if funds_type.ErrorCode != 0:
print(funds_type.Data)
sys.exit(0)
funds_type2 = w.wss(
','.join(fund_list_all[5001:]), "fund_fullname,fund_firstinvesttype,fund_investtype,fund_themetype,fund_type,fund_trackindexcode,fund_etfwindcode,prt_netasset", "unit=1;rptDate="+REPORT_DATE)
if funds_type2.ErrorCode != 0:
print(funds_type2.Data)
sys.exit(0)
funds_type_df = pd.DataFrame(funds_type.Data, index=funds_type.Fields,
columns=funds_type.Codes).T
funds_type_df = funds_type_df.append(pd.DataFrame(funds_type2.Data, index=funds_type2.Fields,
columns=funds_type2.Codes).T)
funds_type_df = funds_type_df.drop('FUND_THEMETYPE', axis=1).join(funds_type_df['FUND_THEMETYPE'].str.split(
',', expand=True).stack().reset_index(level=1, drop=True).rename('FUND_THEMETYPE'))
w.stop()
writer = pd.ExcelWriter('funds.xlsx')
funds_df.to_excel(writer, sheet_name='funds')
funds_stocks_df.to_excel(writer, sheet_name='now')
funds_stocks_df2.to_excel(writer, sheet_name='pre')
funds_type_df.to_excel(writer, sheet_name='type')
writer.save()
|
# -*- coding: utf-8 -*-
"""
Zoidberg could be use in two different ways:
a) CL:
python zoidberg args
b) python module:
from zoidbderg import Zoidberg
"""
import os
import sys
HERE = os.path.abspath(os.path.dirname(__file__))
sys.path.append('..')
sys.path.append(HERE)
from twisted.internet import reactor, defer
from scrapy.crawler import CrawlerRunner
from scrapy.utils.log import configure_logging
from scrapy.utils.project import get_project_settings
# from zoidberg.scraper.spiders import es_spider
from scraper.spiders.es_spider import *
import json
configure_logging({'LOG_FORMAT': '%(levelname)s: %(message)s', 'LOG_LEVEL': 'WARNING'})
def get_countries(self):
import zoidberg.scraper.settings
return zoidberg.scraper.settings.COUNTRIES
def get_areas(country):
data = json.load(open(HERE + '/scraper/db/' + country + '/' + country + '_db.json'))
return [area['slug'] for area in data['area']]
def get_illness(country, area):
data = json.load(open(HERE + '/scraper/db/' + country + '/' + country + '_db.json'))
return [illness['slug'] for _area in data['area'] for illness in _area['illness'] if _area['slug'] == area]
class Zoidberg:
"""
Start a new CrawlerRunner object for the zoidberg scraper
"""
def __init__(self, country='es', doctor=None, area=None, illness=None, output='csv', path=None,*args, **kwargs):
"""
Initialize the CrawlPropertyReactor object
:param country: country scope
:param doctor: doctor to search
:param area: area of medicine of scope
:param illness: illness to search
:param output: file output type: csv or json
:param path: path of the output
:param args:
:param kwargs:
"""
# will populate the statistics of the scrapper
if self.check_args(country, doctor, area, illness, output):
self.stats_dic_list = []
self.doctor = doctor
self.area = area
self.illness = illness
self.output = output.lower()
self.country = country.lower()
print(HERE)
self.country_db = HERE + '/scraper/db/' + country + '/' + country + '_db.json'
if path:
self.path = path
else:
self.path = 'zoidberg_output.' + self.output
# set the ITEM_PIPELINES settings for the specific output
self.settings = get_project_settings()
self.settings.set('ITEM_PIPELINES', {
'scraper.pipelines.CleanItemsPipeline': 100,
'scraper.pipelines.%sPipeline' % output.capitalize(): 200,
}, 0)
def check_args(self, country, doctor, area, illness, output):
# countries = self.get_countries()
if type(country) is not str:
raise ValueError("Country: must be str.")
elif len(country) is not 2:
raise ValueError("Country: must be ISO 3166-1 alfa-2 (2 characters).")
# elif country not in countries:
# raise ValueError("Country: only %s countries is supported" % countries)
elif doctor is None or area is None or illness is None:
raise ValueError("Doctor, area, illness: must not be None.")
elif type(doctor) is not str or type(area) is not str or type(illness) is not str:
raise ValueError("Doctor, area, illness: must not be None.")
elif output != 'csv' and output != 'json':
raise ValueError("Output: Only csv or json outputs is supported.")
else:
return True
@defer.inlineCallbacks
def conf(self):
runner = CrawlerRunner(self.settings)
list_urls = self.get_list_urls(self.area, self.illness)
doctor_words = self.get_doctor_regex_words(self.doctor)
print(list_urls)
for i in range(0, len(list_urls)):
domain = list_urls[i]['domain']
urls = list_urls[i]['urls']
#es_spider.ElAtletaComSpider
spider = eval(domain.replace('.', '').title() + 'Spider')
zoidgber_crawler = runner.create_crawler(spider)
yield runner.crawl(zoidgber_crawler, doctor_regex=doctor_words, urls=urls, path=self.path)
reactor.stop() # the script will block here until the crawling is finished
def run(self):
reactor.run()
def stop(self):
reactor.stop()
def get_doctor_regex_words(self, doctor):
name_list = [doctor, doctor.capitalize(), doctor.upper(), doctor.lower(), doctor.title()]
regex = ""
for w in name_list:
regex += '(\s' + w + '\s)|'
return regex[:-1]
def get_list_urls(self, area_raw, illness_raw):
list_urls = []
data = json.load(open(self.country_db))
for area in data['area']:
if area['slug'] == area_raw:
for illness in area['illness']:
if illness['slug'] == illness_raw:
list_urls = illness['webs']
return list_urls
'''
def get_countries(self):
import zoidberg.scraper.settings
return zoidberg.scraper.settings.COUNTRIES
'''
def get_domains(self):
data = json.load(open(self.country_db))
return data['domains']
def get_areas(self):
data = json.load(open(self.country_db))
return [area['slug'] for area in data['area']]
def get_illness_for_area(self, area=None):
data = json.load(open(self.country_db))
if area not in self.get_areas():
return 'Please, insert a valid area. use get_areas() function to get a list of valid areas.'
else:
return [illness['slug'] for _area in data['area'] for illness in _area['illness'] if _area['slug'] == area]
'''
if __name__ == "__main__":
zoidberg = Zoidberg(country='es', doctor='margalet', area="traumatologia", illness="femoroacetabular", path='bbb.csv', output='csv')
print(zoidberg.get_countries())
print(zoidberg.get_domains())
print(zoidberg.get_areas())
print(zoidberg.get_illness_for_area(area='traumatologia'))
zoidberg.conf()
zoidberg.run()
'''
import argparse
def get_args():
"""This function parses and return arguments passed in"""
# Assign description to the help doc
parser = argparse.ArgumentParser(
description="Are you ready to operate, Doctor? - I'd love to, but first I have to perform surgery.")
# Add arguments
parser.add_argument(
'-d', metavar='doctor', type=str, required=True,
help='doctor to find')
parser.add_argument(
'-c', metavar='country', type=str, required=True,
help="ISO 3166-1 alfa-2 country code. i.e. 'es' for 'Spain'.")
parser.add_argument(
'-a', metavar='area', type=str, required=True,
help='medical area')
parser.add_argument(
'-i', metavar='illness', type=str, required=True,
help='medical illness')
parser.add_argument(
'-o', metavar='output', type=str, required=False, default='csv',
help='output file type: csv or json (default: csv)')
parser.add_argument(
'-p', metavar='path', type=str, required=False,
help='file output path (default: zoidberg_output.csv/json)')
parser.add_argument(
'-l', metavar='log_level', type=str, required=False, default='warning',
help='screen log level output (default: warning)')
return parser.parse_args()
if __name__ == "__main__":
args = get_args()
zoidberg_runner = Zoidberg(country=args.c, doctor=args.d, area=args.a, illness=args.i, path=args.p, output=args.o)
zoidberg_runner.conf()
zoidberg_runner.run()
|
#!/usr/bin/env python
'''Module that defines a parser class for block-structured data, as well as
auxilary classes for exceptions. Can be called directly to perform
unit tests'''
import io
import re
import sys
import unittest
import parser_errors as err
import block
class BlockParser:
'''Parser class to parse file in block format'''
def __init__(self):
'''constructor, initializes parser and resets it'''
self._states = ['in_block', 'not_in_block', 'error']
self._comment_pattern = re.compile(r'\s*#.*')
self._block_begin_pattern = re.compile(r'\s*begin\s+(\w+)')
self._block_end_pattern = re.compile(r'\s*end\s+(\w+)')
self._state = None
self._current_block = None
self._blocks = None
self._match = None
self._line_nr = None
self._line_int = 10
self._verbose = 0
self._reset()
def set_verbosity(self, verbosity_level):
'''set verbosity level of the parser, useful for debugging
level 0: no feedback
level 1: print line numbers parsed
level 2: show state changes as well'''
self._verbose = verbosity_level
def is_verbose(self):
'''return True if the parser should be verbose, False otherwise
(True for levels greater than 0'''
return self._verbose > 0
def is_trace(self):
'''return True if the parser should print trace information,
False otherwise (True for levels greater than 1'''
return self._verbose > 1
def set_line_interval(self, skip_lines):
'''set the number of lines interval for verbose output'''
self._line_int = skip_lines
def get_line_interval(self):
'''returns the number of lines interval for verbose output'''
return self._line_int
def _reset(self):
'''internal function to reset the parser between calls to the parse
method'''
self._set_state('not_in_block')
self._current_block = None
self._blocks = []
self._match = None
self._line_nr = 0
def _is_in_state(self, state):
'''checks whether the parser's current state is the given state'''
return state == self.get_state()
def get_state(self):
'''return the parser's current state'''
return self._state
def _set_state(self, new_state):
'''set the parser's state, after checking it is valid'''
if self.is_trace():
sys.stderr.write(
'change state from {0} to {1}\n'.format(
self._state, new_state))
if new_state in self._states:
self._state = new_state
else:
raise err.UnknownStateError(new_state)
def _is_begin_block(self, line):
'''checks whether this is a line indicating the beginning of a
block, if so, temporarilly store the match object'''
self._match = self._block_begin_pattern.match(line)
return self._match is not None
def _is_end_block(self, line):
'''checks whether this is a line indicating the end of a block,
if so, temporarilly store the match object'''
self._match = self._block_end_pattern.match(line)
return self._match is not None
def _preprocess(self, line):
'''takes a line, strips leading and trailing whitespace, and removes
comments'''
return self._comment_pattern.sub('', line.strip())
def _end_matches_begin(self):
'''returns true if begin and end block match, false otherwise'''
return self._match.group(1) == self._current_block.get_name()
def _init_block(self):
'''creates a new block'''
self._current_block = block.Block(self._match.group(1))
self._match = None
def _is_data(self, line):
'''returns true if the line contains data, false otherwise'''
return len(line) > 0
def _add_data(self, line):
'''add given line as data to the current block'''
self._current_block.add_data(line)
def _finish_block(self):
'''adds the block to the list of blocks, and resets current block'''
self._blocks.append(self._current_block)
self._current_block = None
self._match = None
def get_line_nr(self):
'''return the line number the parser has reached in the file'''
return self._line_nr
def _incr_line_nr(self):
'''incredment the current line number'''
self._line_nr = self._line_nr + 1
if self.is_verbose() and self._line_nr % self._line_int == 0:
sys.stderr.write('parsing line {0}\n'.format(self._line_nr))
def get_blocks(self):
'''returns the blocks that have been parsed, can be used upon a
parse error to retrieve those blocks that were successfully
parsed before the error occurred'''
return self._blocks
def parse(self, block_file):
'''takes a file name and opens the correspoding file to parse it,
returns a list of blocks contained in the file'''
self._reset()
for line in block_file:
self._incr_line_nr()
line = self._preprocess(line)
if self._is_in_state('in_block'):
if self._is_begin_block(line):
raise err.NestedBlocksError(self)
elif self._is_end_block(line):
if self._end_matches_begin():
self._finish_block()
self._set_state('not_in_block')
else:
raise err.NonMatchingBlockDelimitersError(self)
elif self._is_data(line):
self._add_data(line)
elif self._is_in_state('not_in_block'):
if self._is_begin_block(line):
self._init_block()
self._set_state('in_block')
elif self._is_end_block(line):
raise err.DanglingEndBlockError(self)
else:
raise err.UnknownStateError(self.get_state())
if self._is_in_state('in_block'):
raise err.NonClosedBlockError(self)
return self.get_blocks()
class ParserTest(unittest.TestCase):
'''Tests for the parser class'''
def test_constructor(self):
'''create a parser, check initial state'''
parser = BlockParser()
self.assertEqual(parser.get_line_nr(), 0)
self.assertEqual(parser.get_state(), 'not_in_block')
self.assertEqual(parser.get_blocks(), [])
def test_parse_blocks(self):
'''parse data from two blocks and check'''
data = '''
Some initial text,
on two lines.
begin b1
0.31
0.21 # this is inline comment
0.41
end b1
This is just some text
begin b2
0.42
# this is a comment
0.22
0.12
0.32
end b2
# some final comments
and some ordinary text.
'''
block_file = io.StringIO(data)
parser = BlockParser()
blocks = parser.parse(block_file)
self.assertEqual(len(blocks), 2)
self.assertEqual(blocks[0].get_name(), 'b1')
self.assertEqual(blocks[1].get_name(), 'b2')
self.assertEqual(len(blocks[0].get_data()), 3)
self.assertEqual(len(blocks[1].get_data()), 4)
self.assertEqual(blocks[0].get_data(),
['0.31', '0.21', '0.41'])
self.assertEqual(blocks[1].get_data(),
['0.42', '0.22', '0.12', '0.32'])
def test_processing(self):
'''parse a block, and test sorting of data'''
data = '''
begin b1
0.31
0.21
0.41
end b1'''
block_file = io.StringIO(data)
parser = BlockParser()
blocks = parser.parse(block_file)
list(map(lambda x: x.sort_data(), blocks))
self.assertEqual(len(blocks), 1)
self.assertEqual(blocks[0].get_name(), 'b1')
self.assertEqual(blocks[0].get_data(),
['0.21', '0.31', '0.41'])
def test_nested_blocks(self):
'''parse nested blocks, check for exception'''
data = '''
begin b1
0.31
0.21
begin b2
0.42
0.22
0.12
0.32
end b2
0.41
end b1
'''
block_file = io.StringIO(data)
parser = BlockParser()
with self.assertRaises(err.NestedBlocksError):
parser.parse(block_file)
def test_nonmatching_begin_end(self):
'''parse non-matching begin/end blocks, check for exception'''
data = '''
begin b1
0.31
0.21
end b2
'''
block_file = io.StringIO(data)
parser = BlockParser()
with self.assertRaises(err.NonMatchingBlockDelimitersError):
parser.parse(block_file)
def test_dangling_end(self):
'''parse dangling end blocks, check for exception'''
data = '''
begin b1
0.31
0.21
end b1
end b2
'''
block_file = io.StringIO(data)
parser = BlockParser()
with self.assertRaises(err.DanglingEndBlockError):
parser.parse(block_file)
def test_nonclosed_block(self):
'''parse missing end block, check for exception'''
data = '''
begin b1
0.31
0.21
'''
block_file = io.StringIO(data)
parser = BlockParser()
with self.assertRaises(err.NonClosedBlockError):
parser.parse(block_file)
if __name__ == '__main__':
unittest.main()
|
# # Twitter API
# pip install tweepy
import tweepy
import pandas as pd
import time
#use own credentials from twitter developer account
consumer_key = "cyURof8onxNo63Tdbc8d3mB4T"
consumer_secret = "JnKzJsPuLxi0Fa7BB26l7XTpwOYnoXD37Rqio0SpWsLi7QPN1n"
access_token = "1220785803078643713-9tG4OWTEa3ykTPm26l59uUd2nsYXfB"
access_token_secret = "TXpiUcgHfcBcvBpp2m9Zib0FDdZfw0ziPOyCeY27IGFJ5"
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth,wait_on_rate_limit=True)
username = 'JustinTrudeau'
count = 10
tweets = []
tweets = tweepy.Cursor(api.user_timeline,id=username).items(count)
tweets_list = [[tweet.created_at, tweet.id,tweet.user.name,tweet.user.description, tweet.text,tweet.retweet_count] for tweet in tweets]
tweets_df = pd.DataFrame(tweets_list,columns=['Datetime', 'Tweet Id','Username','Description' ,'Text','Retweets'])
tweets_df.to_csv('{}.csv'.format(username), sep=',', index = False)
|
# Generated by Django 2.0.8 on 2018-12-13 04:41
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('readersclub', '0004_auto_20181213_0116'),
]
operations = [
migrations.AlterModelOptions(
name='review',
options={'ordering': ['review_id']},
),
]
|
from django.db import models
class Location(models.Model):
name = models.CharField(
max_length=255,
verbose_name="Name",
blank=True
)
description = models.TextField(
max_length=None,
verbose_name="Description",
blank=True
)
address1 = models.CharField(
max_length=255,
verbose_name="Address Line 1",
blank=True
)
address2 = models.CharField(
max_length=255,
verbose_name="Address Line 2",
blank=True
)
town = models.CharField(
max_length=255,
verbose_name="Town",
blank=True
)
open_time = models.TimeField(
max_length=None,
verbose_name="Opening Time",
blank=True,
null=True
)
close_time = models.TimeField(
max_length=None,
verbose_name="Closing Time",
blank=True,
null=True
)
contact1 = models.CharField(
max_length=255,
verbose_name="Contact Name 1",
blank=True
)
phone1 = models.CharField(
max_length=12,
verbose_name="Phone Number 1",
blank=True,
null=True
)
contact2 = models.CharField(
max_length=255,
verbose_name="Contact Name 2",
blank=True
)
phone2 = models.CharField(
max_length=12,
verbose_name="Phone Number 2",
blank=True,
null=True
)
latitude = models.FloatField(
max_length=None,
verbose_name="Latitude",
blank=True,
null=True
)
longitude = models.FloatField(
max_length=None,
verbose_name="Longitude",
blank=True,
null=True
)
D = 'None'
N = 'North'
E = 'East'
S = 'South'
W = 'West'
C = 'Central'
CARDINAL_POINTS = (
(D, 'None'),
(N, 'North'),
(E, 'East'),
(S, 'South'),
(W, 'West'),
(C, 'Central')
)
cardinal_point = models.CharField(
max_length=7,
choices=CARDINAL_POINTS,
default=D,
verbose_name="Cardinal Point"
)
email = models.EmailField(
max_length=255,
verbose_name="Email",
blank=True
)
website = models.URLField(
max_length=255,
verbose_name="Website",
blank=True
)
facebook = models.URLField(
max_length=255,
verbose_name="Facebook",
blank=True
)
notes = models.TextField(
max_length=None,
verbose_name="Notes",
blank=True
)
def __str__(self):
return self.name
|
# -*- coding: utf-8 -*-
import re
import HTMLParser #转换网页代码
import datetime#简单处理时间
class Parse(object):
def __init__(self, content):
self.content = content.replace('\r', '').replace('\n', '')
self.initRegex()
self.addRegex()
def initRegex(self):
self.regDict = {}
self.regTipDict = {}
self.regDict['splitContent'] = r'<div tabindex="-1" class="zm-item-answer "'#关键表达式,用于切分答案
self.regTipDict['splitContent'] = u'内容分割'
#提取答主信息
self.regDict['answerAuthorInfo'] = r'(?<=<h3 class="zm-item-answer-author-wrap">).*?(?=</h3>)'
self.regTipDict['answerAuthorInfo'] = u'提取答主信息块'#若为匿名用户,则收集到的内容只有【匿名用户】四个字
self.regDict['answerAuthorID'] = r'(?<=href="/people/)[^"]*'
self.regTipDict['answerAuthorID'] = u'提取答主ID'
self.regDict['answerAuthorLogo'] = r'(?<=<img src=")[^"]*'
self.regTipDict['answerAuthorLogo'] = u'提取答主头像'
self.regDict['answerAuthorSign'] = r'(?<= class="zu-question-my-bio">)[^<]*(?=</strong>)'
self.regTipDict['answerAuthorSign'] = u'提取答主签名'#可能没有
self.regTipDict['answerAuthorName'] = u'提取答主用户名'#需要在用户名基础上进行二次匹配,正则模板直接放在了函数里
#提取答案信息
self.regDict['answerAgreeCount'] = r'(?<=<div class="zm-item-vote-info " data-votecount=")[^"]*'#可能存在问题,当前测试样本中没有赞同数为0的情况,回去检查下
self.regTipDict['answerAgreeCount'] = u'提取答案被赞同数'
self.regDict['answerCommentCount'] = r'\d*(?= 条评论)'#为None
self.regTipDict['answerCommentCount'] = u'提取答案被评论数'
self.regDict['answerCollectCount'] = r''
self.regTipDict['answerCollectCount'] = u'提取答案被收藏数'#只有在指定答案时才能用到
self.regDict['answerContent'] = r'(?<=<div class=" zm-editable-content clearfix">).*?(?=</div></div><a class="zg-anchor-hidden ac")'
self.regTipDict['answerContent'] = r'提取答案内容'
self.regDict['answerInfo'] = r'(?<=class="zm-meta-panel").*?(?=<a href="#" name="report" class="meta-item zu-autohide">)'
self.regTipDict['answerInfo'] = r'提取答案信息'
self.regDict['noRecordFlag'] = r'<span class="copyright zu-autohide"><span class="zg-bull">'
self.regTipDict['noRecordFlag'] = r'检查是否禁止转载'
self.regDict['questionID'] = r'(?<= target="_blank" href="/question/)\d*'
self.regTipDict['questionID'] = u'提取问题ID'
self.regDict['answerID'] = r'(?<= target="_blank" href="/question/\d{8}/answer/)\d*'
self.regTipDict['answerID'] = u'提取答案ID'
self.regDict['updateDate'] = r'(?<=>编辑于 )[-:\d]*'#没有考虑到只显示时间和昨天今天的问题
self.regTipDict['updateDate'] = u'提取最后更新日期'
self.regDict['commitDate'] = r'(?<=发布于 )[-:\d]*'#没有考虑到只显示时间和昨天今天的问题
self.regTipDict['commitDate'] = u'提取回答发布日期'
##以下正则交由子类自定义之
#用戶首页信息提取
self.regDict['id'] = r''
self.regDict['name'] = r''
self.regDict['sign'] = r''
self.regTipDict['id'] = u'提取用户ID'
self.regTipDict['name'] = u'提取用户名'
self.regTipDict['sign'] = u'提取用户签名'
self.regDict['followerCount'] = r''
self.regDict['followCount'] = r''
self.regTipDict['followerCount'] = u'提取被关注数'
self.regTipDict['followCount'] = u'提取关注数'
self.regDict['answerCount'] = r''
self.regDict['questionCount'] = r''
self.regDict['columnCount'] = r''
self.regDict['editCount'] = r''
self.regDict['collectionCount'] = r''
self.regTipDict['answerCount'] = u'提取回答总数'
self.regTipDict['questionCount'] = u'提取提问总数'
self.regTipDict['columnCount'] = u'提取专栏文章数'
self.regTipDict['editCount'] = u'提取公共编辑次数'
self.regTipDict['collectionCount'] = u'提取所创建的收藏夹数'
self.regDict['agreeCount'] = r''
self.regDict['thanksCount'] = r''
self.regDict['collectedCount'] = r''
self.regTipDict['agreeCount'] = u'提取总赞同数'
self.regTipDict['thanksCount'] = u'提取总感谢数'
self.regTipDict['collectedCount'] = u'提取总收藏数'
#其它信息
self.regDict['collectionID'] = r''
self.regDict['collectionDesc'] = r''
self.regDict['collectionFollower'] = r''
self.regDict['collectionTitle'] = r''
self.regDict['collectionComment'] = r''
self.regDict['collectionCreaterID'] = r''
self.regDict['collectionCreaterName'] = r''
self.regDict['collectionCreaterSign'] = r''
self.regTipDict['collectionID'] = u'提取收藏夹ID'
self.regTipDict['collectionDesc'] = u'提取收藏夹描述'
self.regTipDict['collectionFollower'] = u'提取收藏夹被关注数'
self.regTipDict['collectionTitle'] = u'提取收藏夹标题'
self.regTipDict['collectionComment'] = u'提取收藏夹被评论数'
self.regTipDict['collectionCreaterID'] = u'提取收藏夹创建者ID'
self.regTipDict['collectionCreaterName'] = u'提取收藏夹创建者用户名'
self.regTipDict['collectionCreaterSign'] = u'提取收藏夹创建者签名'
self.regDict['topicID'] = r''
self.regDict['topicTitle'] = r''
self.regDict['topicDesc'] = r''
self.regDict['topicFollower'] = r''
self.regTipDict['topicID'] = u'提取话题ID'
self.regTipDict['topicTitle'] = u'提取话题名'
self.regTipDict['topicDesc'] = u'提取话题描述'
self.regTipDict['topicFollower'] = u'提取话题关注者人数'
self.regDict['roundTableID'] = r''
self.regDict['roundTableTitle'] = r''
self.regDict['roundTableDesc'] = r''
self.regDict['roundTableFollower'] = r''
self.regTipDict['roundTableID'] = u'提取圆桌ID'
self.regTipDict['roundTableTitle'] = u'提取圆桌标题'
self.regTipDict['roundTableDesc'] = u'提取圆桌描述'
self.regTipDict['roundTableFollower'] = u'提取圆桌关注者人数'
return
def addRegex(self):
return
def getSplitContent(self):
return re.split(self.regDict['splitContent'], self.content)
def matchContent(self, key, content):
targetObject = re.search(self.regDict[key], content)
if targetObject == None:
#print self.regTipDict[key] + u'失败'
#print u'匹配失败的内容为'
#print content
#exit()
return ''
else:
#print self.regTipDict[key] + u'成功'
return targetObject.group(0)
def getAnswerAuthorInfoDict(self, content):
personInfo = {}
authorInfo = self.matchContent('answerAuthorInfo', content)
if authorInfo == u'匿名用户':
personInfo['authorID'] = u"coder'sGirlFriend~"
personInfo['authorSign'] = u''
personInfo['authorLogo'] = u''
personInfo['authorName'] = u'匿名用户'
else:
personInfo['authorID'] = self.matchContent('answerAuthorID', authorInfo)
personInfo['authorSign'] = self.matchContent('answerAuthorSign', authorInfo)
personInfo['authorLogo'] = self.matchContent('answerAuthorLogo', authorInfo)
self.regDict['answerAuthorName'] = r'(?<=<a data-tip="p\$t\$' + personInfo['authorID'] + r'" href="/people/' + personInfo['authorID'] + r'">).*?(?=</a>)'
personInfo['authorName'] = self.matchContent('answerAuthorName', authorInfo)
return personInfo
def getAnswerDict(self, content):
answerDict = {}
authorInfo = self.getAnswerAuthorInfoDict(content)
for key in authorInfo:
answerDict[key] = authorInfo[key]
answerDict['answerAgreeCount'] = self.matchContent('answerAgreeCount', content)
answerDict['answerContent'] = self.matchContent('answerContent', content)
answerInfo = self.matchContent('answerInfo', content)
for key in ['questionID', 'answerID', 'answerCommentCount', 'updateDate', 'commitDate', 'noRecordFlag']:
answerDict[key] = self.matchContent(key, answerInfo)
if answerDict['answerAgreeCount'] == '':
answerDict['answerAgreeCount'] = 0
if answerDict['answerCommentCount'] == '':
answerDict['answerCommentCount'] = 0
if answerDict['noRecordFlag'] == '':
answerDict['noRecordFlag'] = 0
else:
answerDict['noRecordFlag'] = 1
answerDict['answerHref'] = 'http://www.zhihu.com/question/{0}/answer/{1}'.format(answerDict['questionID'], answerDict['answerID'])
answerDict['answerContent'] = HTMLParser.HTMLParser().unescape(answerDict['answerContent']).encode("utf-8")#对网页内容解码,可以进一步优化
if answerDict['updateDate'] == '':
answerDict['updateDate'] = answerDict['commitDate']
for key in ['updateDate', 'commitDate']:#此处的时间格式转换还可以进一步改进
if len(answerDict[key]) != 10:
if len(answerDict[key]) == 0:
answerDict[key] = self.getYesterday().isoformat()
else:
answerDict[key] = datetime.date.today().isoformat()
return answerDict
def getYesterday(self):
today=datetime.date.today()
oneday=datetime.timedelta(days=1)
yesterday=today-oneday
return yesterday
class ParseQuestion(Parse):
u'''
输入网页内容,返回两个dict,一个是问题信息dict,一个是答案dict列表
'''
def addRegex(self):
#实例化Regex
#为Regex添加合适的项目
self.regDict['questionIDinQuestionDesc'] = r'(?<=<a href="/question/)\d{8}(?=/followers"><strong>)'
self.regTipDict['questionIDinQuestionDesc'] = u'提取问题ID'
self.regDict['questionFollowCount'] = r'(?<=<a href="/question/\d{8}/followers"><strong>).*(?=</strong></a>人关注该问题)'
self.regTipDict['questionFollowCount'] = u'提取问题关注人数'
self.regDict['questionCommentCount'] = r'(?<=<i class="z-icon-comment"></i>).*?(?= 条评论</a>)'#该模式对答案中的评论也有效,需要小心处理
self.regTipDict['questionCommentCount'] = u'提取问题评论数'
self.regDict['questionTitle'] = r'(?<=<title>)[^-]*?(?=-)'
self.regTipDict['questionTitle'] = u'提取问题标题'
self.regDict['questionDesc'] = r'(?<=<div class="zm-editable-content">).*?(?=</div>)'#取到的数据是html编码过的数据,需要逆处理一次才能存入数据库里
self.regTipDict['questionDesc'] = u'提取问题描述'
self.regDict['questionAnswerCount'] = r'(?<=id="zh-question-answer-num">)\d*'
self.regTipDict['questionAnswerCount'] = u'问题下回答数'
self.regDict['questionCollapsedAnswerCount'] = r'(?<=<span id="zh-question-collapsed-num">)\d*(?=</span>)'
self.regDict['questionCollapsedAnswerCount'] = u'问题下回答折叠数'
self.regDict['questionViewCount'] = r'(?<=<div class="zg-gray-normal">被浏览 <strong>)\d*(?=</strong>)'
self.regTipDict['questionViewCount'] = u'问题浏览数'
def getInfoDict(self):
"列表长度有可能为0(没有回答),1(1个回答),2(2个回答)...,需要分情况处理"
contentList = self.getSplitContent()
contentLength = len(contentList)
questionInfoDictList = []
answerDictList = []
if contentList == 0:
questionInfoDictList.append(self.getQusetionInfoDict(contentList[0], contentList[0]))
else:
questionInfoDictList.append(self.getQusetionInfoDict(contentList[0], contentList[contentLength - 1]))
for i in range(1, contentLength):
answerDictList.append(self.getAnswerDict(contentList[i]))
return questionInfoDictList, answerDictList
def getQusetionInfoDict(self, titleContent, tailContent):
questionInfoDict = {}
for key in ['questionCommentCount', 'questionTitle', 'questionDesc', 'questionAnswerCount']:
questionInfoDict[key] = self.matchContent(key, titleContent)
for key in ['questionIDinQuestionDesc', 'questionFollowCount', 'questionViewCount']:
questionInfoDict[key] = self.matchContent(key, tailContent)
questionInfoDict['questionDesc'] = HTMLParser.HTMLParser().unescape(questionInfoDict['questionDesc']).encode("utf-8")#对网页内容解码,可以进一步优化
return questionInfoDict
class ParseAnswer(ParseQuestion):
def addRegex(self):
#实例化Regex
#为Regex添加合适的项目
self.regDict['questionIDinQuestionDesc'] = r'(?<=<a href="/question/)\d{8}(?=/followers"><strong>)'
self.regTipDict['questionIDinQuestionDesc'] = u'提取问题ID'
self.regDict['questionFollowCount'] = r'(?<=<a href="/question/\d{8}/followers"><strong>).*(?=</strong></a>人关注该问题)'
self.regTipDict['questionFollowCount'] = u'提取问题关注人数'
self.regDict['questionCommentCount'] = r'(?<=<i class="z-icon-comment"></i>).*?(?= 条评论</a>)'#该模式对答案中的评论也有效,需要小心处理
self.regTipDict['questionCommentCount'] = u'提取问题评论数'
self.regDict['questionTitle'] = r'(?<=<title>)[^-]*?(?=-)'
self.regTipDict['questionTitle'] = u'提取问题标题'
self.regDict['questionDesc'] = r'(?<=<div class="zm-editable-content">).*?(?=</div>)'#取到的数据是html编码过的数据,需要逆处理一次才能存入数据库里
self.regTipDict['questionDesc'] = u'提取问题描述'
self.regDict['questionAnswerCount'] = r'(?<=查看全部 )\d*(?= 个回答)'
self.regTipDict['questionAnswerCount'] = u'问题下回答数'
self.regDict['questionCollapsedAnswerCount'] = r'(?<=<span id="zh-question-collapsed-num">)\d*(?=</span>)'
self.regDict['questionCollapsedAnswerCount'] = u'问题下回答折叠数'
self.regDict['questionViewCount'] = r'(?<=<p>所属问题被浏览 <strong>)\d*(?=</strong>)'
self.regTipDict['questionViewCount'] = u'问题浏览数'
def getQusetionInfoDict(self, titleContent, tailContent):
questionInfoDict = {}
for key in ['questionCommentCount', 'questionTitle', 'questionDesc', 'questionAnswerCount']:
questionInfoDict[key] = self.matchContent(key, titleContent)
for key in ['questionIDinQuestionDesc', 'questionFollowCount', 'questionViewCount']:
questionInfoDict[key] = self.matchContent(key, tailContent)
questionInfoDict['questionAnswerCount'] = int(questionInfoDict['questionAnswerCount']) + 1 #知乎显示的全部回答数是被js处理过的。。。需要手工加一。。。汗
questionInfoDict['questionDesc'] = HTMLParser.HTMLParser().unescape(questionInfoDict['questionDesc']).encode("utf-8")#对网页内容解码,可以进一步优化
return questionInfoDict
class ParseAuthor(Parse):
u'''
输入网页内容,返回一个dict,答案dict列表
'''
def addRegex(self):
#实例化Regex
#为Regex添加合适的项目
self.regDict['splitContent'] = r'div class="zm-item" id="mi'#关键表达式,用于切分答案
self.regDict['answerContent'] = r'(?<=<textarea class="content hidden">).*(?=<span class="answer-date-link-wrap">)'
self.regDict['answerInfo'] = r'(?<=<div class="zm-meta-panel">).*?(?=<a href="#" name="collapse" class="collapse meta-item zg-right"><i class="z-icon-fold">)'
self.regDict['updateInfo'] = r'(?<=<span class="answer-date-link-wrap">).*?(?=</span>)'
self.regTipDict['updateInfo'] = u'提取答案更新日期信息'
self.regDict['questionInfo'] = r'(?<=<h2><a class="question_link").*?(?=</a></h2>)'
self.regTipDict['questionInfo'] = u'提取问题相关信息'
self.regDict['questionIDinQuestionDesc'] = r'(?<=href="/question/)\d{8}'
self.regDict['questionTitle'] = r'(?<=>).*'
def getInfoDict(self):
contentList = self.getSplitContent()
answerDictList = []
questionInfoDictList = []
for content in contentList:
questionInfoDictList.append(self.getQusetionInfoDict(content))
answerDictList.append(self.getAnswerDict(content))
return questionInfoDictList, answerDictList
def getAnswerDict(self, content):
answerDict = {}
authorInfo = self.getAnswerAuthorInfoDict(content)
for key in authorInfo:
answerDict[key] = authorInfo[key]
answerDict['answerAgreeCount'] = self.matchContent('answerAgreeCount', content)
answerDict['answerContent'] = self.matchContent('answerContent', content)
answerInfo = self.matchContent('answerInfo', content)
updateInfo = self.matchContent('updateInfo', content)
for key in ['questionID', 'answerID', 'updateDate', 'commitDate']:
answerDict[key] = self.matchContent(key, updateInfo)
for key in ['answerCommentCount','noRecordFlag']:
answerDict[key] = self.matchContent(key, answerInfo)
if answerDict['answerAgreeCount'] == '':
answerDict['answerAgreeCount'] = 0
if answerDict['answerCommentCount'] == '':
answerDict['answerCommentCount'] = 0
if answerDict['noRecordFlag'] == '':
answerDict['noRecordFlag'] = 0
else:
answerDict['noRecordFlag'] = 1
answerDict['answerHref'] = 'http://www.zhihu.com/question/{0}/answer/{1}'.format(answerDict['questionID'], answerDict['answerID'])
answerDict['answerContent'] = HTMLParser.HTMLParser().unescape(answerDict['answerContent']).encode("utf-8")#对网页内容解码,可以进一步优化
if answerDict['updateDate'] == '':
answerDict['updateDate'] = answerDict['commitDate']
for key in ['updateDate', 'commitDate']:#此处的时间格式转换还可以进一步改进
if len(answerDict[key]) != 10:
if len(answerDict[key]) == 0:
answerDict[key] = self.getYesterday().isoformat()
else:
answerDict[key] = datetime.date.today().isoformat()
return answerDict
def getQusetionInfoDict(self, content):
questionInfoDict = {}
questionInfo = self.matchContent('questionInfo', content)
for key in ['questionTitle', 'questionIDinQuestionDesc']:
questionInfoDict[key] = self.matchContent(key, questionInfo)
return questionInfoDict
'''
class ParseCollection:
class ParseColumn:
class ParseTopic:
class ParseTable:
'''
|
valor_float = float(input("Digite o valor que você quer sacar, se necessário digite quantos cents: "))
valor_int = int(valor_float)
print(valor_int)
# Parte cédula
valor_dinheiro = valor_int
total = valor_dinheiro
céd = 100
totcéd = 0
while True:
if total >= céd:
total -= céd
totcéd += 1
else:
if totcéd > 0:
print(f"Total de {totcéd} cédulas de R${céd}")
if céd == 100:
céd = 50
elif céd == 50:
céd = 20
elif céd == 20:
céd = 10
elif céd == 10:
céd = 5
elif céd == 5:
céd = 2
elif céd == 2:
céd = 1
totcéd = 0
if total == 0:
break
valor_float = valor_float - valor_int
valor_float = valor_float * 100
total = round(valor_float,2)
céd = 50
totcéd = 0
while True:
if total >= céd:
total = total - céd
totcéd = totcéd + 1
else:
if totcéd > 0:
print("Total de %d moedas de %d" % (totcéd, céd))
if céd == 50:
céd = 20
elif céd == 20:
céd = 10
elif céd == 10:
céd = 5
elif céd == 5:
céd = 2
elif céd == 2:
céd = 1
totcéd = 0
if total == 0:
break |
# -*- coding: utf-8 -*-
from __future__ import print_function
import time
CONFIGURABLE_OPTIONS = ['--db', '--cms-version', '--django-version', '--i18n',
'--reversion', '--languages', '--timezone', '--use-tz',
'--permissions', '--bootstrap', '--templates',
'--starting-page']
DJANGOCMS_DEVELOP = 'https://github.com/divio/django-cms/archive/develop.zip?%s' % time.time() ## to avoid getting this from caches or mirrors
DJANGOCMS_RC = 'https://github.com/divio/django-cms/archive/3.0c2.zip'
DJANGOCMS_BETA = 'https://github.com/divio/django-cms/archive/3.0.0.beta3.zip'
DJANGOCMS_SUPPORTED = ('2.4', '3.0', '3.1', 'stable', 'develop')
DJANGO_DEVELOP = 'https://github.com/django/django/archive/master.zip?%s' % time.time() ## to avoid getting this from caches or mirrors
DJANGO_SUPPORTED = ('1.4', '1.5', '1.6', '1.7', '1.8', 'stable')
CMS_VERSION_MATRIX = {
'stable': 3.1,
'rc': 3.2,
'beta': 3.2,
'develop': 3.2
}
DJANGO_VERSION_MATRIX = {
'stable': 1.7,
'rc': 1.8,
'beta': 1.8,
'develop': 1.8
}
VERSION_MATRIX = {
2.4: (1.4, 1.5),
3.0: (1.4, 1.7),
3.1: (1.6, 1.8),
3.2: (1.6, 1.8),
}
DEFAULT_REQUIREMENTS = """
django-classy-tags>=0.3.4.1
html5lib
Pillow<=2.8
django-sekizai>=0.7
six
"""
DJANGO_16_REQUIREMENTS = """
south>=1.0.0
"""
DJANGOCMS_2_REQUIREMENTS = """
django-mptt>=0.5.1,<0.5.3
"""
DJANGOCMS_3_REQUIREMENTS = """
django-mptt<0.7
"""
DJANGOCMS_3_1_REQUIREMENTS = """
django-treebeard>=2.0
"""
PLUGINS_REQUIREMENTS_BASIC = """
djangocms-admin-style
djangocms-column
djangocms-flash
djangocms-googlemap
djangocms-inherit
djangocms-style
djangocms-text-ckeditor>=2.3.0
"""
PLUGINS_REQUIREMENTS_NON_FILER = """
djangocms-file
djangocms-link
djangocms-picture
djangocms-teaser
djangocms-video
"""
PLUGINS_REQUIREMENTS_BASIC_DJANGO_17 = """
https://github.com/divio/djangocms-admin-style/archive/master.zip?%(bust)s
https://github.com/divio/djangocms-column/archive/master.zip?%(bust)s
https://github.com/divio/djangocms-flash/archive/master.zip?%(bust)s
https://github.com/divio/djangocms-googlemap/archive/master.zip?%(bust)s
https://github.com/divio/djangocms-inherit/archive/master.zip?%(bust)s
https://github.com/divio/djangocms-style/archive/master.zip?%(bust)s
https://github.com/divio/djangocms-link/archive/master.zip?%(bust)s
https://github.com/divio/djangocms-text-ckeditor/archive/master.zip?%(bust)s
""" % {'bust': time.time()}
PLUGINS_REQUIREMENTS_NON_FILER_DJANGO_17 = """
https://github.com/divio/djangocms-file/archive/master.zip?%(bust)s
https://github.com/divio/djangocms-picture/archive/master.zip?%(bust)s
https://github.com/divio/djangocms-teaser/archive/master.zip?%(bust)s
https://github.com/divio/djangocms-video/archive/master.zip?%(bust)s
""" % {'bust': time.time()}
DJANGO_17_REVERSION = "django-reversion>=1.8.2,<1.8.6"
ALDRYN_REQUIREMENTS = """
django-compressor
"""
DJANGO_16_REVERSION = "django-reversion>=1.8,<1.8.6"
DJANGO_15_REVERSION = "django-reversion>=1.7,<1.8"
DJANGO_14_REVERSION = "django-reversion<1.7"
FILER_REQUIREMENTS_CMS3 = """
easy_thumbnails
https://github.com/stefanfoulis/django-filer/archive/develop.zip
cmsplugin-filer>=0.9.9
"""
FILER_REQUIREMENTS_CMS2 = """
easy_thumbnails
django-filer<=0.9.6
cmsplugin_filer
"""
TEMPLATES_1_8 = """
TEMPLATES = [
{{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [{dirs}],
'OPTIONS': {{
'context_processors': [
{processors}
],
'loaders': [
{loaders}
],
}},
}},
]
"""
PLUGIN_LIST_TEXT = """
djangocms_installer will install and configure the following plugins:
* djangocms_column (Column plugin)
* djangocms-file (File plugin)
* djangocms-flash (Flash plugin)
* djangocms-googlemap (GoogleMap plugin)
* djangocms-inherit (Inherit plugin)
* djangocms-link (Link plugin)
* djangocms-picture (Picture plugin)
* djangocms_style (Style plugin)
* djangocms-teaser (Teaser plugin)
* djangocms-text-ckeditor (Text plugin)
* djangocms-video (Video plugin)
It will optionally install cmsplugin-filer plugins (if requested during
configuration):
* cmsplugin_filer_file (File plugin, replaces djangocms-file)
* cmsplugin_filer_folder (Folder plugin)
* cmsplugin_filer_image (Image plugin, replaces djangocms-picture)
* djangocms-link (Link plugin)
* cmsplugin_filer_teaser (Teaser plugin, replaces djangocms-teaser)
* cmsplugin_filer_video (Video plugin, replaces djangocms-video)
"""
DRIVERS = {
'django.db.backends.postgresql_psycopg2': 'psycopg2',
'django.db.backends.postgresql_postgis': 'postgis',
'django.db.backends.mysql': 'MySQL-python',
'django.db.backends.sqlite3': '',
}
DEFAULT_PROJECT_HEADER = """# -*- coding: utf-8 -*-
import os
gettext = lambda s: s
"""
STATICFILES_DEFAULT = """STATICFILES_DIRS = (
# Put strings here, like "/home/html/static" or "C:/www/django/static".
# Always use forward slashes, even on Windows.
# Don't forget to use absolute paths, not relative paths.
)"""
BASE_DIR = """
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
"""
ALDRYN_BOILERPLATE = 'https://github.com/aldryn/aldryn-boilerplate/archive/master.zip'
VERSION_WARNING = '%s version of %s is not supported and it may not work as expected'
|
import sys
import os
import numpy as np
import random
from makedata import Dataset_WPDP,addBug
from functions.metrics import accuracy, precision, recall, f_measure, auc
import config
from datasetConfig import dsconf
from makeCPDPohv import CPDPdict
from util.alarm import Sound
from DNN.NeuralNetwork import NeuralNetwork
from DNN.Layer import Dense
from DNN.RBM import RBM
from DNN.LogisticRegression import LogisticRegression
from FeatureSelection import FeatureSelectionClassifier
def CPDPtest(proj,lr_DBN,lr_CLF,layers):
dict = CPDPdict()
ohvdir = dict[proj]["ohv"]
trainPRJ = dict[proj]["train"]
testPRJ = dict[proj]["test"]
valPRJ = dict[proj]["val"]
dataset = Dataset_WPDP(config.dataconf,ohvdir,trainPRJ,testPRJ,valPRJ)
input = dataset.train_data
dbn = NeuralNetwork()
for i,layer in enumerate(layers):
if i == 0:
in_shape = input.shape[1:]
else:
in_shape = last_layer.out_shape
last_layer = RBM(in_shape,rdc_axis=layer[0],out_dim=layer[1],lr=lr_DBN,epochs=50,lr_decay=0.95)
dbn.add(last_layer)
dbn.fit(dataset.train_data,dataset.train_label)
lgr = NeuralNetwork(lr=0.1,epochs=50)
lgr_dense = Dense(last_layer.out_shape)
lgr_clf = LogisticRegression(lgr_dense.out_dim,2,lr=lr_CLF,lr_decay=0.95)
lgr.add(lgr_dense)
lgr.add(lgr_clf)
clf = NeuralNetwork(lr=0.1,epochs=50)
dense = Dense(last_layer.out_shape)
output = LogisticRegression(dense.out_dim,2,lr=lr_CLF,lr_decay=0.95)
x_t = dbn.predict(dataset.train_data)
x_v = dense.predict(dbn.predict(dataset.val_data))
y_v = dataset.val_label
classifier = FeatureSelectionClassifier(output,x_v,y_v,FS="BFS",epochs=50\
,k=int(dense.out_dim*0.8),dropout_k=int(dense.out_dim*0.98),metrics=auc)
clf.add(dense)
clf.add(classifier)
lgr.fit(x_t,dataset.train_label)
clf.fit(x_t,dataset.train_label)
scores = {}
y_pred = lgr.predict(dense.predict(dbn.predict(dataset.test_data)))
scores["NoFS"] = {}
scores["NoFS"]["accuracy"] = accuracy(y_pred,dataset.test_label)
scores["NoFS"]["precision"] = precision(y_pred,dataset.test_label)
scores["NoFS"]["recall"] = recall(y_pred,dataset.test_label)
scores["NoFS"]["f-measure"] = f_measure(y_pred,dataset.test_label)
y_pred = clf.predict(dense.predict(dbn.predict(dataset.test_data)))
scores["FS"] = {}
scores["FS"]["accuracy"] = accuracy(y_pred,dataset.test_label)
scores["FS"]["precision"] = precision(y_pred,dataset.test_label)
scores["FS"]["recall"] = recall(y_pred,dataset.test_label)
scores["FS"]["f-measure"] = f_measure(y_pred,dataset.test_label)
return scores
def CPDPcoverageValuation(description,lr_DBN,lr_CLF,layers):
file = "CPDP_{}.csv".format(description)
name = "prelr-{}_finelr-{}".format(lr_DBN,lr_CLF)
for l in layers:
name+="_{}-{}".format(l[0],l[1])
row = [name,"NoFS_accuracy","NoFS_precision","NoFS_recall","NoFS_F1","FS_accuracy","FS_precision","FS_recall","FS_F1"]
if os.path.exists(file):
print("the file is already exists.")
exit(1)
with open(file,mode="w") as f:
f.write(','.join(row)+"\n")
dict = CPDPdict()
for proj in dict.keys():
scores = CPDPtest(proj,lr_DBN,lr_CLF,layers)
column = [proj] + [str(scores["NoFS"][key]) for key in scores["NoFS"].keys()] + [str(scores["FS"][key]) for key in scores["FS"].keys()]
print(column)
with open(file,mode="a") as f:
f.write(','.join(column)+"\n")
if __name__ == "__main__":
np.seterr(all='ignore')
CPDPcoverageValuation("Layer2_clf008",0.15,0.08,[[1,40],[0,40]])
Sound(3)
|
import pandas
import numpy
from sklearn.metrics import confusion_matrix
from scipy.stats import mode
import scipy.io
import matplotlib.pyplot as plt
import matplotlib
import seaborn as sn
from xgboost import XGBClassifier
import pickle
import joblib
X = joblib.load('C:/Users/russo/OneDrive/Documents/GitHub/Intelligent-Athlete/Data/TrainingSet_Sho.pkl')
# X = joblib.load('C:/Users/russo/OneDrive/Documents/GitHub/Intelligent-Athlete/Data/TrainingSet_Abs.pkl')
athletes = X['Athlete']
athletes = athletes.astype('category')
names = athletes.unique()
col_names = X.iloc[:,:-3].columns
# Using only selected features
filename = open('C:/Users/russo/OneDrive/Documents/GitHub/Intelligent-Athlete/Python/Classifier/Models/Multiclass/SHOmask25', 'rb')
# filename = open('C:/Users/russo/OneDrive/Documents/GitHub/Intelligent-Athlete/Python/Classifier/Models/Multiclass/ABSmask25', 'rb')
mask = numpy.load(filename)
filename.close()
col_names_new = col_names[mask]
col_names_new = list(col_names_new)
col_names_new.append('Label')
col_names_new.append('Athlete')
col_names_new.append('Session')
X_new = X[col_names_new]
# Training of the classifier
y = X_new['Label']
X_new.drop('Label', inplace = True, axis = 1)
X_new.drop('Athlete', inplace = True, axis = 1)
X_new.drop('Session', inplace = True, axis = 1)
clf_final = XGBClassifier()
clf_final.fit(X_new, y)
# Save the classifier
with open('classifier_sho.pkl', 'wb') as fid:
pickle.dump(clf_final, fid)
# with open('classifier_abs.pkl', 'wb') as fid:
# pickle.dump(clf_final, fid)
|
# Ao testar sua solução, não se limite ao caso de exemplo.
x = float(input('Digite um numero para x: '))
y = float(input('digite um numero para y: '))
if (x>0 and y>0):
print('Q1')
elif (x<0 and y<0):
print('Q3')
elif (x>0 and y<0):
print('Q4')
elif (x<0 and y>0):
print('Q2')
elif ((x==0) and (y>0) or(x==0) and (y<0)):
print('Eixo Y')
elif ((x>0) and (y==0) or(x<0) and (y==0)):
print('Eixo X')
else:
print('Origem') |
import sys
import lcddriver
display = lcddriver.lcd()
display.lcd_display_string(" ", 1)
s1="received:"+sys.argv[1]
display.lcd_display_string(s1, 1) |
import importlib.resources
import jinja2
_templates = {
name[: name.rfind(".")]: jinja2.Template(
importlib.resources.read_text("structy_generator.templates", name),
lstrip_blocks=True,
keep_trailing_newline=True,
)
for name in importlib.resources.contents("structy_generator.templates")
if name.endswith(".jinja2")
}
class CTemplates:
def render(self, struct_name, **kwargs):
return {
f"{struct_name}.h": _templates["c.header"].render(**kwargs),
f"{struct_name}.c": _templates["c.source"].render(**kwargs),
}
class PyTemplates:
def render(self, struct_name, **kwargs):
return {
f"{struct_name}.py": _templates["py"].render(**kwargs),
}
class JSTemplates:
def render(self, struct_name, **kwargs):
return {
f"{struct_name}.js": _templates["js"].render(**kwargs),
}
templates = {
"c": CTemplates(),
"py": PyTemplates(),
"js": JSTemplates(),
}
def template_for(lang):
return templates[lang]
|
from usecases.login import LoginDependencies, LoginTokens, login
from usecases.signup import SignupDependencies, signup
from db.sqlite import SQLiteDB
from security.bcrypt_hasher import BCryptHasher
from security.pyjwt_generator import PyJWTGenerator
db = SQLiteDB('flask.db')
hasher = BCryptHasher()
jwtGenerator = PyJWTGenerator("foo", "bar") # replace with real secrets
class Service:
def login(self, username: str, password: str) -> LoginTokens:
deps = LoginDependencies(db, hasher, jwtGenerator)
return login(deps, username, password)
def signup(self, username: str, password: str) -> None:
deps = SignupDependencies(db, hasher, db)
signup(deps, username, password)
|
# Generated by Django 3.1.6 on 2021-02-18 12:03
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('Money_app', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Category',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=50)),
('slug', models.SlugField(unique=True, verbose_name='url')),
],
options={
'verbose_name': 'Категория',
'verbose_name_plural': 'Категории',
'ordering': ['title'],
},
),
migrations.CreateModel(
name='Expenses',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('money', models.FloatField(verbose_name='How much am I spending?')),
('description', models.TextField(blank=True)),
('created_at', models.DateTimeField(auto_now_add=True, verbose_name='Added')),
('category', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='expenses', to='Money_app.category')),
],
options={
'verbose_name': 'Expense',
'verbose_name_plural': 'Expenses',
'ordering': ['-created_at'],
},
),
migrations.CreateModel(
name='Month',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=50)),
('slug', models.SlugField(unique=True, verbose_name='url')),
('created_at', models.DateTimeField(auto_now_add=True, verbose_name='Added')),
],
options={
'verbose_name': 'Month',
'ordering': ['-created_at'],
},
),
migrations.CreateModel(
name='TranshMvf',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('money', models.FloatField(verbose_name='How much I got?')),
('description', models.TextField(blank=True)),
('created_at', models.DateTimeField(auto_now_add=True, verbose_name='Added')),
('category', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='Source_type', to='Money_app.category')),
('month', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='Money_app.month')),
],
options={
'verbose_name': 'Income',
'ordering': ['-created_at'],
},
),
migrations.CreateModel(
name='Year',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.IntegerField()),
('slug', models.SlugField(unique=True, verbose_name='url')),
('created_at', models.DateTimeField(auto_now_add=True, verbose_name='Added')),
('month', models.ManyToManyField(related_name='month', to='Money_app.Month', verbose_name='month')),
],
options={
'verbose_name': 'Year',
'ordering': ['-created_at'],
},
),
migrations.DeleteModel(
name='Student',
),
migrations.AddField(
model_name='month',
name='year',
field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='year', to='Money_app.year', verbose_name='Year'),
),
migrations.AddField(
model_name='expenses',
name='month',
field=models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='Money_app.month'),
),
]
|
import binascii
import json
def main():
TestJSON()
def TestJSON():
return
if __name__ == "__main__":
main()
|
import allure
from ui_tests.data import BASE_TIMEOUT
from ui_tests.ui.locators.pages_locators import MainPageLocators
from ui_tests.ui.pages.base_page import BasePage
class MainPage(BasePage):
locators = MainPageLocators()
@allure.step('Open redirect page')
def open_redirect_page(self, locators, expectation):
if len(locators) == 1:
self.click(locators[0])
else:
self.move_and_click(locators)
tabs = []
for handle in self.driver.window_handles:
tabs.append(handle)
assert len(tabs) == 2
self.driver.switch_to_window(tabs[1])
assert expectation in self.driver.page_source
self.driver.switch_to_window(tabs[0])
assert self.driver.current_url == 'http://127.0.0.1:8095/welcome/'
@allure.step('Логаут')
def logout(self):
self.click(self.locators.LOGOUT_BUTTON_LOCATOR, timeout=BASE_TIMEOUT)
@allure.step('Проверить отображение Дзена Питона')
def check_zen_of_python_text(self):
if self.get_text(self.locators.PYTHON_ZEN_TEXT_LOCATOR) == '':
return False
else:
return True
@allure.step('Нажать на кнопку Home')
def click_home(self):
self.click(self.locators.HOME_BUTTON_LOCATOR)
@allure.step('Открыть выпадающее меню')
def open_dropdow_menu(self, locator):
self.click(locator)
assert self.driver.current_url == 'http://127.0.0.1:8095/welcome/'
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 技术支持:dwz.cn/qkEfX1u0 项目实战讨论QQ群6089740 144081101
# CreateDate: 2019-12-29
def gcd(q,p):
# 求最大公约数
while q != 0:
p, q = q, p%q
return p
def is_coprime(x, y):
result = gcd(x, y)
return gcd(x, y) == 1
if __name__ == '__main__':
print(gcd(17, 13))
print(is_coprime(17, 13))
print(gcd(17, 21))
print(is_coprime(17, 21))
print(gcd(15, 21))
print(is_coprime(15, 21))
print(gcd(25, 45))
print(is_coprime(25, 45))
print(gcd(15, 45))
print(is_coprime(15, 45)) |
import datetime as dt
class Timer:
def __init__(self):
self.start_time = None
def start(self):
self.start_time = dt.datetime.now()
def stop(self):
end_time = dt.datetime.now()
print('duration : %s' % (end_time - self.start_time))
|
#!/usr/bin/env python
# -*- coding:utf-8 -*-
__author__ = 'MFC'
__time__ = '18/4/17 23:16'
import requests
"""
Python快速获取图片文件大小
https://www.v2ex.com/t/67865
https://blog.csdn.net/pud_zha/article/details/8809878
HTTP之Content-Length
"""
# url = 'https://pic.huodongjia.com/event/2017-12-20/1513755021.78.jpg'
# url = 'https://pic.huodongjia.com/event/2018-02-23/1519357566.95.jpg'
url = 'http://www.huodongxing.com/logodownload/logo_huodongx_green.png'
# 两种写法都可用
# pre_img_size = requests.head(url).headers.get('content-length') # content-length单位为字节
pre_img_size = requests.get(url).headers['content-length']
print(requests.get(url).headers)
print(pre_img_size) # 1343024字节/1024
image_size = int(pre_img_size)/1024
if image_size > 2000:
print("下载图片不能大于2M")
else:
print("开始下载")
print("{} k".format(image_size))
|
import json
import re
jsn_dict = {}
with open("jawiki-country.json") as fp:
for jsn_fp in fp:
jsn = json.loads(jsn_fp)
jsn_dict[jsn["title"]] = jsn["text"]
pattern = re.compile(r"^.*\[\[File:(.*?)\|.*\|.*\]\].*$",re.MULTILINE)
matches = pattern.findall(jsn_dict["イギリス"])
for match in matches:
print(match)
|
# %load q03_logistic_regression/build.py
# Default Imports
import pandas as pd
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import confusion_matrix
from greyatomlib.logistic_regression_project.q01_outlier_removal.build import outlier_removal
from greyatomlib.logistic_regression_project.q02_data_cleaning_all.build import data_cleaning
from greyatomlib.logistic_regression_project.q02_data_cleaning_all_2.build import data_cleaning_2
loan_data = pd.read_csv('data/loan_prediction_uncleaned.csv')
loan_data = loan_data.drop('Loan_ID', 1)
loan_data = outlier_removal(loan_data)
X, y, X_train, X_test, y_train, y_test = data_cleaning(loan_data)
X_train, X_test, y_train, y_test = data_cleaning_2(X_train, X_test, y_train, y_test)
# Write your solution code here:
def logistic_regression(X_train, X_test, y_train, y_test):
columns_to_scale = ['ApplicantIncome', 'CoapplicantIncome', 'LoanAmount']
for column in columns_to_scale:
standard_scaler = StandardScaler()
X_train[column] = standard_scaler.fit_transform(X_train[[column]])
X_test[column] = standard_scaler.fit_transform(X_test[[column]])
model = LogisticRegression(random_state=9)
model.fit(X_train, y_train)
y_pred = model.predict(X_test)
return confusion_matrix(y_test, y_pred)
|
from numpy import *
from matplotlib.pyplot import *
def a(t):
return 1.0
def b(t, c, u0):
return c + a(t)*(c*t+u0)
def f_linear(un, tn, u0, c=1.23):
return -a(tn)*un + b(tn, c, u0)
def f_exp(un, tn, u0):
return -un + 1
def analytical_exp(t):
return 1-exp(-t)
def forwardEuler(f,tn,un, dt):
return un + dt*f(un, tn, un)
def solve(f, u0, t_start, t_stop, N):
dt = (t_stop - t_start)/(N-1)
print dt
#need to find u1. Does this by Forward Euler
u1 = forwardEuler(f, t_start, u0, dt)
u = zeros(N)
t = linspace(t_start, t_stop, N)
u[0] = u0
u[1] = u1
for i in xrange(1,N-1):
u[i+1] = 2*dt*f(u[i], t[i], u0) + u[i-1]
return t, u
if __name__=='__main__':
u0=0.1
t_start = 0
t_stop = 4.0
N = 42
t_l,u_l = solve(f_linear, u0, t_start, t_stop, N)
plot(t_l,u_l)
figure()
t_e,u_e = solve(f_exp, 0, t_start, t_stop, N)
plot(t_e, u_e)
hold('on')
plot(t_e, analytical_exp(t_e))
legend(["leapfrog", "analytical"])
show()
|
"""Forms of the ``django_libs`` app."""
from django import forms
class PlaceholderForm(forms.Form):
"""Form to add the field's label as a placeholder attribute."""
def __init__(self, *args, **kwargs):
super(PlaceholderForm, self).__init__(*args, **kwargs)
for field_name in self.fields:
self.fields[field_name].widget.attrs['placeholder'] = self.fields[
field_name].label
|
import json
import aiohttp
from urllib.parse import urljoin
from aiologger import Logger
logger = Logger.with_default_handlers()
class DPCheck:
def __init__(self, server_url, token, unti_id, dp_competence_uuid, lrs_culture_value) -> None:
super().__init__()
self.server_url = server_url
self.token = token
self.unti_id = unti_id
self.dp_competence_uuid = dp_competence_uuid
self.lrs_competence_value = lrs_culture_value.get(list(lrs_culture_value.keys())[0])
async def set_user_data(self):
"""
Вспомогательный метод для записи значения в DP для последюущей проверки
Необходим в случае неработоспособности элемнетов системы для создания записи
"""
async with aiohttp.ClientSession() as session:
url = urljoin(self.server_url, f'/api/v1/user_meta/{self.unti_id}?app_token={self.token}')
body = [{
"competence": self.dp_competence_uuid,
"value": self.lrs_competence_value
}]
async with session.post(url, json=body) as resp:
if resp.status == 200:
json = await resp.json()
if json and json.get("status", None) == 0:
return True
else:
return False
else:
return False
async def get_user_data(self):
async with aiohttp.ClientSession() as session:
url = urljoin(self.server_url, f'/api/v1/user/{self.unti_id}?app_token={self.token}')
async with session.get(url) as resp:
if resp.status == 200:
elements = await resp.json()
filtered = [ elem for elem in elements if elem.get('uuid', None) == self.dp_competence_uuid ]
if len(filtered) == 1 and filtered[0].get("value", None):
dp_response_value = json.loads(filtered[0].get("value", None))
"""
if dp_response_value and \
str(dp_response_value.get("value", None)) == str(self.lrs_competence_value):
return True
"""
if dp_response_value and str(dp_response_value) == str(self.lrs_competence_value):
return True
else:
return False
else:
return False
else:
return False
async def check(self, create_entry):
logger.info("[DP] checking...")
if create_entry.lower() != "true":
result = await self.get_user_data()
logger.info(f"[DP] create_entry FALSE. Result: {result}")
else:
result = await self.set_user_data() and await self.get_user_data()
logger.info(f"[DP] create_entry TRUE. Result: {result}")
return result
|
# -*- coding: utf-8 -*-
#!/usr/bin/env python
__author__ = 'Diego Linayo'
import os
def arbol(path , nivel= 0 ):
try:
# Los archivos ordenados alfabeticamente
files = sorted(
(os.path.join(path, filename) for filename in os.listdir(path)),
key=lambda s: s.lower()
)
if nivel is not 0:
nivel_tab = "|" + "\t" * nivel + "|--- "
else:
nivel_tab = "\t" * nivel + "|--- "
for item in files:
if os.path.isdir(item):
print nivel_tab + ('\x1b[6;30;42m %s \x1b[0m') % os.path.basename(item)
arbol(item, nivel + 1)
else:
print nivel_tab + ""+ os.path.basename(item)
except OSError as e:
print "[Nro. Error %s][Valor Ingresado %s][Mensaje de Error %s] " % (e.errno, e.filename, e.strerror)
if __name__ == "__main__":
path_to_walk = raw_input("Ingresar Directorio Valido: ")
arbol(path_to_walk)
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('article', '0004_auto_20160429_1250'),
]
operations = [
migrations.AlterModelOptions(
name='article',
options={'verbose_name': '\u041d\u043e\u0432\u043e\u0441\u0442\u044c', 'verbose_name_plural': '\u041d\u043e\u0432\u043e\u0441\u0442\u0438'},
),
migrations.AlterModelOptions(
name='articleimage',
options={'verbose_name': '\u0424\u043e\u0442\u043e \u0434\u043b\u044f \u043d\u043e\u0432\u043e\u0441\u0442\u0438', 'verbose_name_plural': '\u0424\u043e\u0442\u043e \u0434\u043b\u044f \u043d\u043e\u0432\u043e\u0441\u0442\u0438'},
),
migrations.AlterModelOptions(
name='dpa',
options={'verbose_name': '\u0414\u041f\u0410', 'verbose_name_plural': '\u0414\u041f\u0410'},
),
migrations.AlterModelOptions(
name='dpadoc',
options={'verbose_name': '\u0414\u043e\u043a\u0443\u043c\u0435\u043d\u0442 \u0434\u043b\u044f \u0414\u041f\u0410', 'verbose_name_plural': '\u0414\u043e\u043a\u0443\u043c\u0435\u043d\u0442\u044b \u0434\u043b\u044f \u0414\u041f\u0410'},
),
migrations.AlterModelOptions(
name='klassam',
options={'verbose_name': '\u041a\u043b\u0430\u0441\u0441\u0430\u043c', 'verbose_name_plural': '\u041a\u043b\u0430\u0441\u0441\u0430\u043c'},
),
migrations.AlterModelOptions(
name='klassamdoc',
options={'verbose_name': '\u0414\u043e\u043a\u0443\u043c\u0435\u043d\u0442\u044b \u043a\u043b\u0430\u0441\u0441\u0430\u043c', 'verbose_name_plural': '\u0414\u043e\u043a\u0443\u043c\u0435\u043d\u0442\u044b \u043a\u043b\u0430\u0441\u0441\u0430\u043c'},
),
migrations.AlterModelOptions(
name='vchitel',
options={'verbose_name': '\u0423\u0447\u0438\u0442\u0435\u043b\u044e', 'verbose_name_plural': '\u0423\u0447\u0438\u0442\u0435\u043b\u044e'},
),
migrations.AlterModelOptions(
name='vchiteldoc',
options={'verbose_name': '\u0414\u043e\u043a\u0443\u043c\u0435\u043d\u0442 \u0443\u0447\u0438\u0442\u0435\u043b\u044e', 'verbose_name_plural': '\u0414\u043e\u043a\u0443\u043c\u0435\u043d\u0442\u044b \u0443\u0447\u0438\u0442\u0435\u043b\u044e'},
),
migrations.AlterModelOptions(
name='zno',
options={'verbose_name': '\u0417\u041d\u041e', 'verbose_name_plural': '\u0417\u041d\u041e'},
),
migrations.AlterModelOptions(
name='znodoc',
options={'verbose_name': '\u0414\u043e\u043a\u0443\u043c\u0435\u043d\u0442 \u0434\u043b\u044f \u0417\u041d\u041e', 'verbose_name_plural': '\u0414\u043e\u043a\u0443\u043c\u0435\u043d\u0442\u044b \u0434\u043b\u044f \u0417\u041d\u041e'},
),
]
|
from django.contrib import admin
from .models import Product, ProductImage
class ProductImageAdmin(admin.StackedInline):
model = ProductImage
@admin.register(Product)
class ProductAdmin(admin.ModelAdmin):
inlines = [ProductImageAdmin]
class Meta:
model = Product
|
# Copyright 2022 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.
# ==============================================================================
"""Utils function for program.py."""
import os
import lingvo.compat as tf
def SummaryToCsv(summaries):
"""Convert summary (Dict[str, tf.Summary]) to csv format."""
res = ''
for k, s in summaries.items():
res += f'{k},{s.value[0].simple_value}\n'
return res
def CsvToSummary(csv):
"""Convert csv format to summary (Dict[str, tf.Summary])."""
summaries = {}
for l in csv.split('\n'):
row = l.split(',')
if len(row) != 2:
tf.logging.warn(f'Failed to parse csv line: {l}, will ignore it.')
continue
s = tf.Summary()
v = s.value.add()
v.tag, v.simple_value = row[0], float(row[1])
summaries.update({v.tag: s})
return summaries
class DecodeStatusCache:
"""Maintain status file to keep decoding datasets status.
Status file should have following format:
- 1st line is checkpoint key, e.g. ckpt-123
- the rest lines are dataset names that has been decoded.
Here's an example:
ckpt-123
Dev
Test
"""
def __init__(self, program_dir):
self.ckpt_key = ''
self.decoded_datasets = []
self.status_file = os.path.join(program_dir, 'decoded_datasets.txt')
# TODO(xingwu): Consider add a TTL.
self.cache_dir = os.path.join(program_dir, 'cache')
tf.io.gfile.makedirs(self.cache_dir)
if tf.io.gfile.exists(self.status_file):
with tf.io.gfile.GFile(self.status_file, 'r') as f:
content = list(l.strip() for l in f.readlines())
if content:
self.ckpt_key = content[0]
if len(content) > 1:
self.decoded_datasets = content[1:]
def UpdateCkpt(self, ckpt_key):
"""Update checkpoint key in the status."""
if ckpt_key != self.ckpt_key:
self.ckpt_key = ckpt_key
self.decoded_datasets = []
with tf.io.gfile.GFile(self.status_file, 'w') as f:
f.write(self.ckpt_key)
def UpdateDataset(self, dataset_name, summaries):
"""Update decoded dataset in the status."""
cache_file = os.path.join(self.cache_dir, f'{dataset_name}.csv')
with tf.io.gfile.GFile(cache_file, 'w') as f:
f.write(SummaryToCsv(summaries))
with tf.io.gfile.GFile(self.status_file, 'w+') as f:
f.write(f.read().strip() + '\n' + dataset_name)
def TryLoadCache(self, ckpt_key, dataset_name):
"""Try load summary cache for ckpt_key, dataset_name.
Args:
ckpt_key: str, checkpoint key, e.g. ckpt-123
dataset_name: str, the dataset name, e.g. Test
Returns:
summaries if load successful, otherwise, return None
"""
if ckpt_key == self.ckpt_key and dataset_name in self.decoded_datasets:
cache_file = os.path.join(self.cache_dir, f'{dataset_name}.csv')
if not tf.io.gfile.exists(cache_file):
tf.logging.warn(f'cached summary {cache_file} is gone!')
return None
with tf.io.gfile.GFile(cache_file, 'r') as f:
summaries = CsvToSummary(f.read())
with tf.io.gfile.GFile(self.status_file, 'w+') as f:
f.write(f.read().strip() + '\n' + dataset_name)
return summaries
return None
class TriggerScheduler:
"""A trigger scheduler with offset, and interval.
Maintains an counter, incremented when Trigger() called. ShouldRun() only
returns True when (counter - offset) % interval == 0.
"""
def __init__(self, offset, interval):
self.offset = offset
self.interval = interval
self.counter = -offset
def Trigger(self):
self.counter += 1
if self.counter >= self.interval:
self.counter = 0
def ShouldRun(self):
return self.counter == 0
|
# @Author: Bartosz Nowakowski
# @Github: https://github.com/rolzwy7
#
# Copyright (c) 2018 Bartosz Nowakowski
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
# Requests
from requests.exceptions import ConnectionError
from requests.exceptions import Timeout
import requests
# Parsing and Printing
import json
import pprint as pp
# Time
from email import utils
import datetime
import time
# Config
class MGApiConfiguration():
def __init__(self):
### Debug configuration
self._DEBUG = False
self._DEBUG_SIGN = "[DEBUG]"
### Api configuration
# _BASE_URL : https://documentation.mailgun.com/en/latest/api-intro.html#base-url
self._BASE_URL = "https://api.mailgun.net/v3"
# _DOMAIN : https://documentation.mailgun.com/en/latest/api-domains.html
self._DOMAIN = ""
# _PRIVATE_KEY your private api key e.g: key-abcdefghijklmnopqrstuvwxyz012345
self._PRIVATE_KEY = ""
# Mailgun Api username (It's 'api' for everyone at the moment so
# you don't need to change this)
self._API_USER = "api"
self._REQUEST_TIMEOUT_SECONDS = 15
self._EVENTS = [
"accepted",
"delivered",
"failed",
"opened",
"clicked",
"unsubscribed",
"complained",
"stored"
]
self._RESOLUTIONS = [
"hour",
"day",
"month"
]
self._AGGREGATES = [
"countries",
"providers",
"devices"
]
def printConfig(self):
"""
Print current configuration
"""
print("[Mailgun API Client - Configuration]")
print("Debug:", self._DEBUG)
# Logging and printing
class MGApiLogging(MGApiConfiguration):
def printer_print(self, sign, *argv):
"""
Extended print
"""
# print(time.asctime().split(" "))
# dayname, month, daynum, hour, year = time.asctime().split(" ")
# to_print_time = " ".join([dayname, month, year, daynum, hour])
print("[%s]" % time.asctime(), sign, end=" ")
for e in argv:
print(e, end=" ")
print("")
def print_debug(self, *argv):
"""
Print if in debug mode ( _DEBUG == True )
"""
if self._DEBUG: self.printer_print("[DEBUG]", *argv)
def print_debug_pretty(self, obj):
"""
Print ( use pprint.pprint ) if in debug mode ( _DEBUG == True )
"""
if self._DEBUG: pp.pprint(obj)
# Helper methods
class MGApiUtils(MGApiLogging):
# Justification methods
def justify(self, json_object, msg, success=True, reason=""):
"""
summary:
add justification to response
params:
json_object - response in json format
msg - message
success - indicator of success or failure
reason - justification of error
returns: (1 value/s)
json_object with added justification
"""
json_object["justify"] = {
"success": success,
"reason": reason,
"msg": msg
}
return json_object
def not_in_justify(self, what, not_in, caller="<not_set>", reason="<not_set>", success=False):
"""
summary:
returns justification if key isn't present in dict
params:
what - key name
not_in - dictionary
caller - caller method
reason - reason of error
success - indicator of success or failure
returns: (2 value/s)
deserialized and serialized json
or
False ,False
"""
if what not in not_in:
deserialized = {}
deserialized = self.justify(
deserialized,
"Operation failed: {caller}".format(caller=caller),
success=success,
reason=reason
)
return deserialized, self.serialize_json(deserialized)
return False, False
# JSON parsing methods
def serialize_json(self, json_object, sort_keys=True, indent=4, separators=(',', ': ')):
"""
docs:
https://docs.python.org/3/library/json.html
summary:
Returns serialized json (api response)
params:
json_object - json api response
sort_keys - json.dumps param (see documentation)
indent - json.dumps param (see documentation)
separators - json.dumps param (see documentation)
returns: (1 value/s)
serialized json (api response)
"""
return json.dumps(json_object, sort_keys=sort_keys, indent=indent, separators=separators)
def deserialize_json(self, json_string):
"""
docs:
https://docs.python.org/3/library/json.html
summary:
Returns deserialized json (api response)
params:
json_string - json string (api response)
returns: (1 value/s)
deserialized json (api response)
"""
if not isinstance(json_string, str) and not isinstance(json_string, bytes):
print("implement this: helpers deserialize_json method")
if isinstance(json_string, bytes):
json_string = str(json_string, "utf8") if isinstance(json_string, bytes) else string
return json.loads(json_string)
def to_json(self, json_string):
"""
docs:
https://docs.python.org/3/library/json.html
summary:
Returns serialized and deserialized json_string (api response).
Adds justification to response.
justification is always success=True with appropriate message
DON'T use this method for deserialization and serialization
of json object/json string instead use together:
serialize_json method
and
deserialize_json method
params:
json_string - api response
returns: (2 value/s)
Serialized and deserialized json (api response)
"""
deserialized = self.deserialize_json(json_string=json_string)
# Add justification.
deserialized = self.justify(deserialized, "Operation succeeded.")
serialized = self.serialize_json(deserialized)
return deserialized, serialized
# Options modifiers methods (Sending)
def options_add_header(self, options, header, value):
"""
docs:
https://documentation.mailgun.com/en/latest/api-sending.html#sending
summary:
adds new element to options dictionary
params:
options - dictionary
header - key
value - value
returns: (1 value/s)
dictionary (options param) with added new element
"""
options["h:{header}".format(header=header)] = value
return options
def options_add_variable(self, options, variable, value):
"""
docs:
https://documentation.mailgun.com/en/latest/api-sending.html#sending
summary:
adds new element to options dictionary
params:
options - dictionary
header - key
value - value
returns: (1 value/s)
dictionary (variable param) with added new element
"""
options["v:{variable}".format(variable=variable)] = value
return options
# Time
def nowRFC2822(self, days=0, hours=0, minutes=0, return_timestamp=False):
"""
docs:
https://documentation.mailgun.com/en/latest/api-sending.html#sending
summary:
adds new element to options dictionary
params:
days - [integer] number of days
hours - [integer] number of days
minutes - [integer] number of days
return_timestamp - Bool
returns: (1 value/s or 2 value/s)
RFC2822 datetime
or
RFC2822 datetime and it's timestamp
"""
timedelta_shift = datetime.timedelta(days=days, hours=hours, minutes=minutes)
now_datetime = datetime.datetime.now() + timedelta_shift
now_timestamp = time.mktime(now_datetime.timetuple())
# localtime=True (Sets local timezone)
result = utils.formatdate(now_timestamp, localtime=True)
self.print_debug("timedelta_shift:", timedelta_shift)
self.print_debug("now_datetime:", now_datetime)
self.print_debug("now_timestamp:", now_timestamp)
self.print_debug("result:", result)
if return_timestamp:
return result, now_timestamp
return result
def toRFC2822(_datetime, days=0, hours=0, minutes=0, return_timestamp=False):
timedelta_shift = datetime.timedelta(days=days, hours=hours, minutes=minutes)
now_datetime = _datetime + timedelta_shift
now_timestamp = time.mktime(now_datetime.timetuple())
# localtime=True (Sets local timezone)
result = utils.formatdate(now_timestamp, localtime=True)
# self.print_debug("timedelta_shift:", timedelta_shift)
# self.print_debug("now_datetime:", now_datetime)
# self.print_debug("now_timestamp:", now_timestamp)
# self.print_debug("result:", result)
if return_timestamp:
return result, now_timestamp
return result
def ISO8601(iso8601_string):
# Date
try:
date_part = iso8601_string.split("T")[0]
year, month, day = date_part.split("-")
year, month, day = int(year), int(month), int(day)
except Exception as e:
print("Exception:", e)
return False
# Time
try:
time_part = iso8601_string.split("T")[1].strip("Z")
time_part = time_part.split(".")[0] if "." in time_part else time_part
hour, minute, second = time_part.split(":")
hour, minute, second = int(hour), int(minute), int(second)
except Exception as e:
print("Exception:", e)
hour, minute, second = 0, 0, 0
result = datetime.datetime(
year=year , month=month , day=day,
hour=hour , minute=minute , second=second,
microsecond=0 , tzinfo=None
)
return result
# Unification of request responses
class MGApiRequests(MGApiUtils):
# RequestExtended
def requestEx(self, url, request_function, request_params):
"""
summary:
requests.request but with overkill exceptions and
option of choosing type of request
params:
url - URL of the api endpoint
request_function - method from one below:
self.get
self.post
self.put
request_params - parameters of chosen 'request_function'
returns: (3 value/s)
reason - reason for exception
success - indicator of success (Bool)
result - result of request
"""
timeout = self._REQUEST_TIMEOUT_SECONDS
request_params_common = {
"auth": (self.api_user, self.private_key),
"timeout": timeout
}
request_params = {**request_params, **request_params_common}
reason = None
success = None
result = None
try:
result = request_function(url, **request_params)
if result.status_code != 200:
deserialized_content = self.deserialize_json(result.content)
reason = "Status code:{status_code} | Message:{message} | Content:{content}".format(
status_code=result.status_code,
message=deserialized_content["message"] if "message" in deserialized_content.keys() else "KeyError",
content=result.content
)
success, result = False, None
else:
# operation succeeded
reason, success, result = None, True, result
except Timeout as e:
reason, success, result = "Timeout: {exception}".format(exception=e), False, None
except ConnectionError as e:
reason, success, result = "ConnectionError: {exception}".format(exception=e), False, None
except Exception as e:
reason, success, result = "Unhandled Exception: {exception}".format(exception=e), False, None
return reason, success, result
# Requests
def get(self, url, params={}, **kwargs):
"""
docs:
http://docs.python-requests.org/en/master/
summary:
Method used as requestEx method's parameter
params:
url - URL of the api endpoint
params - GET parameters
returns: (3 value/s)
reason - reason for exception
success - indicator of success (Bool)
result - result of request
"""
request_function = requests.get
request_params = {
"params": params,
**kwargs
}
self.print_debug("MGApiRequests.get", request_params);
reason, success, result = self.requestEx(url, request_function, request_params)
return reason, success, result
def post(self, url, data={}, **kwargs):
"""
docs:
http://docs.python-requests.org/en/master/
summary:
Method used as requestEx method's parameter
params:
url - URL of the api endpoint
data - POST data
returns: (3 value/s)
reason - reason for exception
success - indicator of success (Bool)
result - result of request
"""
request_function = requests.post
request_params = {
"data": data,
**kwargs
}
self.print_debug("MGApiRequests.post", request_params);
reason, success, result = self.requestEx(url, request_function, request_params)
return reason, success, result
def put(self, url, data={}, **kwargs):
"""
docs:
http://docs.python-requests.org/en/master/
summary:
Method used as requestEx method's parameter
params:
url - URL of the api endpoint
data - PUT data
returns: (3 value/s)
reason - reason for exception
success - indicator of success (Bool)
result - result of request
"""
request_function = requests.put
request_params = {
"data": data,
**kwargs
}
self.print_debug("MGApiRequests.put", request_params);
reason, success, result = self.requestEx(url, request_function, request_params)
return reason, success, result
def parseResponse(self, reason, success, result, caller=""):
"""
summary:
Judges if request was success by success parameter
params:
reason - reason for exception
success - indicator of success (Bool)
result - result of request
caller - caller method
returns: (2 value/s)
deserialized and serialized json
"""
# Success
if success:
# Calling self.to_json should only occur when request
# is considered to be success=True
deserialized, serialized = self.to_json(result.content)
return deserialized, serialized
# Error
deserialized = {}
deserialized = self.justify(
deserialized,
"Operation failed: {caller}".format(caller=caller),
success=success,
reason=reason
)
return deserialized, self.serialize_json(deserialized)
# Api
class Api(MGApiRequests):
def __init__(self, domain="", api_user="", private_key="", base_url="", config_file=None, debug=None):
MGApiConfiguration.__init__(self)
self._DEBUG = debug if debug is not None else self._DEBUG
if self._DEBUG: print(
"[DEBUG MODE IS ON] - you can change it in MGApiConfiguration class constructor"
);
# Config from parameters or config class
if config_file is None:
self.base_url = base_url if base_url else self._BASE_URL
self.domain = domain if domain else self._DOMAIN
self.private_key = private_key if private_key else self._PRIVATE_KEY
self.api_user = api_user if api_user else self._API_USER
else:
# Config from config file
self.print_debug("Reading config file")
try:
with open(config_file, "rb") as config_content:
config_json_serialized = config_content.read()
except FileNotFoundError as e:
print("FileNotFoundError: {exception}".format(exception=e))
exit(0)
except Exceptions as e:
print("Unhandled exception: {exception}".format(exception=e))
exit(0)
config_json_deserialized = self.deserialize_json(config_json_serialized)
self.print_debug("Config file JSON")
self.print_debug_pretty(config_json_deserialized)
self.api_user = config_json_deserialized["api_user"] if "api_user" in config_json_deserialized.keys() else ""
self.domain = config_json_deserialized["domain"] if "domain" in config_json_deserialized.keys() else ""
self.private_key = config_json_deserialized["private_key"] if "private_key" in config_json_deserialized.keys() else ""
self.base_url = config_json_deserialized["base_url"] if "base_url" in config_json_deserialized.keys() else ""
# Pagination
def follow_pagination(self, Next="", deserialized_response=""):
"""
summary:
Follows pagination until items array lenght is 0
params:
deserialized_response - deserialized json (api response)
returns: (3 value/s)
exhausted - indicates that there is no items left
deserialized - deserialized json
serialized - serialized json
"""
exhausted = False
if not Next and not deserialized_response:
return self.justify({},
"To follow pagination you need to provide at least one parameter",
success=False,
reason="'Next' and 'deserialized_response' is not set"
)
if deserialized_response and not Next:
# Check if paging key exists
deserialized, serialized = self.not_in_justify(
"paging",
deserialized_response.keys(),
caller="Api.follow_pagination",
reason="KeyError 'paging'",
success=False
)
if deserialized and serialized:
return exhausted, deserialized, serialized
# Check if next key exists
deserialized, serialized = self.not_in_justify(
"next",
deserialized_response["paging"].keys(),
caller="Api.follow_pagination",
reason="KeyError 'next' in paging",
success=False
)
if deserialized and serialized:
return exhausted, deserialized, serialized
url = deserialized_response["paging"]["next"]
else:
url = Next
reason, success, result = self.get(url, params={})
deserialized, serialized = self.parseResponse(reason, success, result, caller="Api.follow_pagination")
exhausted = True if len(deserialized["items"]) == 0 else False
return exhausted, deserialized, serialized
# Domains
def get_domains(self, domain="", limit=100, skip=0):
"""
GET /domains/<domain>
GET /domains
"""
url = "{base_url}/domains".format(base_url=self.base_url)
if domain:
url = "{url}/{domain}".format(url=url, domain=domain)
# Optional prameters
params = {"limit": limit, "skip": skip}
reason, success, result = self.get(url, params=params)
deserialized, serialized = self.parseResponse(reason, success, result, caller="Api.get_domains")
return deserialized, serialized
# Supressions (method used by get_bounces, get_unsubscribes and get_complaints)
def get_supressions(self, get_what, address="", domain="", limit=100, caller="<not_set>"):
"""
summary:
DRY for get_bounces, get_complaints and get_unsubscribes
params:
get_what - {bounces, complaints, unsubscribes}
address - email address
domain - domain name
limit - limit of items returned
caller - caller method
returns: (2 value/s)
deserialized - deserialized json
serialized - serialized json
"""
# Set default if invalid limit value
if limit < 0 or limit > 10000: limit = 100;
# If domain is set use it else use domain from constructor
cp_domain = domain if domain else self.domain
url = "{base_url}/{domain}/{get_what}".format(base_url=self.base_url, domain=cp_domain, get_what=get_what)
if address:
url = "{url}/{address}".format(url=url, address=address)
# Optional prameters
params = {"limit": limit}
reason, success, result = self.get(url, params=params)
deserialized, serialized = self.parseResponse(reason, success, result, caller=caller)
return deserialized, serialized
# Bounces
def get_bounces(self, address="", domain="", limit=100):
"""
GET /<domain>/bounces
GET /<domain>/bounces/<address>
"""
deserialized, serialized = self.get_supressions(
"bounces",
address=address,
domain=domain,
limit=limit,
caller="Api.get_bounces"
)
return deserialized, serialized
# Unsubscribes
def get_unsubscribes(self, address="", domain="", limit=100):
"""
GET /<domain>/unsubscribes
GET /<domain>/unsubscribes/<address>
"""
deserialized, serialized = self.get_supressions(
"unsubscribes",
address=address,
domain=domain,
limit=limit,
caller="Api.get_unsubscribes"
)
return deserialized, serialized
# Complaints
def get_complaints(self, address="", domain="", limit=100):
"""
GET /<domain>/complaints
GET /<domain>/complaints/<address>
"""
deserialized, serialized = self.get_supressions(
"complaints",
address=address,
domain=domain,
limit=limit,
caller="Api.get_complaints"
)
return deserialized, serialized
# Mailing Lists
def get_lists(self, address="", limit=100):
"""
GET /lists/<address>
GET /lists/pages
"""
url = "{base_url}/lists".format(base_url=self.base_url)
url = "{url}/{address}".format(url=url, address=address) if address else "{url}/pages".format(url=url)
# Optional prameters
params = {"limit": limit}
reason, success, result = self.get(url, params=params)
deserialized, serialized = self.parseResponse(reason, success, result, caller="Api.get_lists")
return deserialized, serialized
def add_list(self, address, name="", description="", access_level="readonly"):
"""
POST /lists
"""
url = "{base_url}/lists".format(base_url=self.base_url)
data = {
"address": address,
"name": name,
"description": description,
"access_level": access_level
}
reason, success, result = self.post(url, data=data)
deserialized, serialized = self.parseResponse(reason, success, result, caller="Api.add_list")
return deserialized, serialized
def get_members(self, address, member_address="", limit=100, subscribed=None):
"""
GET /lists/<address>/members/<member_address>
GET /lists/<address>/members/pages
"""
url = "{base_url}/lists/{address}/members".format(base_url=self.base_url, address=address)
url = "{url}/{member_address}".format(url=url, member_address=member_address) if member_address else "{url}/pages".format(url=url)
# Optional prameters
params = {"limit": limit}
if subscribed is not None:
params["subscribed"] = subscribed
reason, success, result = self.get(url, params=params)
deserialized, serialized = self.parseResponse(reason, success, result, caller="Api.get_members")
return deserialized, serialized
def bulk_add_members(self, address, members, upsert="no"):
"""
POST /lists/<address>/members.json
"""
url = "{base_url}/lists/{address}/members.json".format(base_url=self.base_url, address=address)
members_json_string = self.serialize_json(members)
data = {
"members": members_json_string,
"upsert": upsert
}
reason, success, result = self.post(url, data=data)
deserialized, serialized = self.parseResponse(reason, success, result, caller="Api.bulk_add_members")
return deserialized, serialized
# Events
def ret_events_filter_fields(self):
"""
"""
ret = {
"event": None,
"list": None,
"attachment": None,
"from": None,
"message-id": None,
"subject": None,
"to": None,
"size": None,
"recipient": None,
"tags": None,
"severity": None
}
return ret
def get_events(self, domain="", begin="", end="", ascending="yes", limit=300, filter_fields={}):
"""
GET /<domain>/events
"""
limit = 100 if limit<0 or limit>300 else limit
# If domain is set use it else use domain from constructor
cp_domain = domain if domain else self.domain
url = "{base_url}/{domain}/events".format(base_url=self.base_url, domain=cp_domain)
# Optional prameters
params = {
"limit": limit
}
if begin: params["begin"] = begin;
if end: params["end"] = end;
if ascending: params["ascending"] = ascending;
for key, value in filter_fields.items():
if value is not None: params[key] = value;
reason, success, result = self.get(url, params=params)
deserialized, serialized = self.parseResponse(reason, success, result, caller="Api.get_events")
return deserialized, serialized
# Total stats
def get_stats_total(self, event, domain="", start="", end="", resolution="day", duration=""):
"""
GET /<domain>/stats/total
"""
### Copy paste - validation ( Event, Resolution ) ###
# Check if event is valid
deserialized, serialized = self.not_in_justify(
event,
self._EVENTS,
caller="Api.get_stats_total",
reason="Event name is not valid: {event}".format(event=event),
success=False
);
if deserialized and serialized:
return deserialized, serialized
# Check if resolution is valid
deserialized, serialized = self.not_in_justify(
resolution,
self._RESOLUTIONS,
caller="Api.get_stats_total",
reason="Resolution is not valid: {resolution}".format(resolution=resolution),
success=False
);
if deserialized and serialized:
return deserialized, serialized
### Copy paste - validation ( Event, Resolution ) ###
# If domain is set use it else use domain from constructor
cp_domain = domain if domain else self.domain
params = {
"event": event,
"resolution": resolution
}
if start: params["start"] = start;
if end: params["end"] = end;
if duration: params["duration"] = duration;
url = "{base_url}/{domain}/stats/total".format(base_url=self.base_url, domain=cp_domain)
reason, success, result = self.get(url, params=params)
deserialized, serialized = self.parseResponse(reason, success, result, caller="Api.get_stats_total")
return deserialized, serialized
# Tags
def get_tags(self, domain="", tag="", limit=100):
"""
GET /<domain>/tags
GET /<domain>/tags/<tag>
"""
cp_domain = domain if domain else self.domain
url = "{base_url}/{domain}/tags".format(base_url=self.base_url, domain=cp_domain)
url = "{url}/{tag}".format(url=url, tag=tag) if tag else url
params = {
"limit": limit
}
reason, success, result = self.get(url, params=params)
deserialized, serialized = self.parseResponse(reason, success, result, caller="Api.get_tags")
return deserialized, serialized
def get_tag_stats(self, tag, event, domain="", start="", end="", resolution="day", duration=""):
"""
GET /<domain>/tags/<tag>/stats
"""
### Copy paste - validation ( Event, Resolution ) ###
# Check if event is valid
deserialized, serialized = self.not_in_justify(
event,
self._EVENTS,
caller="Api.get_tag_stats",
reason="Event name is not valid: {event}".format(event=event),
success=False
);
if deserialized and serialized:
return deserialized, serialized
# Check if resolution is valid
deserialized, serialized = self.not_in_justify(
resolution,
self._RESOLUTIONS,
caller="Api.get_tag_stats",
reason="Resolution is not valid: {resolution}".format(resolution=resolution),
success=False
);
if deserialized and serialized:
return deserialized, serialized
### Copy paste - validation ( Event, Resolution ) ###
cp_domain = domain if domain else self.domain
url = "{base_url}/{domain}/tags/{tag}/stats".format(base_url=self.base_url, domain=cp_domain, tag=tag)
params = {
"event": event,
"resolution": resolution
}
if start: params["start"] = start;
if end: params["end"] = end;
if duration: params["duration"] = duration;
reason, success, result = self.get(url, params=params)
deserialized, serialized = self.parseResponse(reason, success, result, caller="Api.get_tag_stats")
return deserialized, serialized
def get_tag_aggregates(self, tag, aggregate, domain=""):
"""
GET /<domain>/tags/<tag>/stats/aggregates/countries
GET /<domain>/tags/<tag>/stats/aggregates/providers
GET /<domain>/tags/<tag>/stats/aggregates/devices
"""
### Copy paste - validation ( Aggregate ) ###
# Check if aggregate is valid
deserialized, serialized = self.not_in_justify(
aggregate,
self._AGGREGATES,
caller="Api.get_tag_aggregates",
reason="Aggregate name is not valid: {aggregate}".format(aggregate=aggregate),
success=False
);
if deserialized and serialized:
return deserialized, serialized
### Copy paste - validation ( Aggregate ) ###
cp_domain = domain if domain else self.domain
url = "{base_url}/{domain}/tags/{tag}/stats/aggregates/{aggregate}".format(
base_url=self.base_url,
domain=cp_domain,
tag=tag,
aggregate=aggregate
)
params = {
}
reason, success, result = self.get(url, params=params)
deserialized, serialized = self.parseResponse(reason, success, result, caller="Api.get_tag_aggregates")
return deserialized, serialized
# Sending
def ret_additional_sending_options(self, tracking=True, testmode=False):
"""
return additional sending option
"""
additional_options = {
"cc": None,
"bcc": None,
"attachment": None,
"inline": None,
"o:tag": [],
"o:dkim": None,
"o:deliverytime": None,
"o:testmode": None,
"o:tracking": None,
"o:tracking-clicks": None,
"o:tracking-opens": None,
"o:require-tls": None,
"o:skip-verification": None
}
if testmode:
additional_options["o:testmode"] = "yes"
if tracking:
additional_options["o:tracking"] = "yes"
additional_options["o:tracking-clicks"] = "yes"
additional_options["o:tracking-opens"] = "yes"
return additional_options
def send_single_message(self, From, to, subject, html, text, domain="", additional_sending_options=None):
"""
POST /<domain>/messages
"""
# If domain is set use it else use domain from constructor
cp_domain = domain if domain else self.domain
# Set default additional_sending_options if not set by user
if additional_sending_options is None:
additional_sending_options = self.ret_additional_sending_options()
# debug
self.print_debug("Api.send_single_message", "PARAM additional_sending_options")
self.print_debug_pretty(additional_sending_options)
data = {
"from": From, "to": to,
"subject": subject, "html": html, "text": text
}
for key, value in additional_sending_options.items():
if value is not None:
data[key] = value
# debug
self.print_debug("Api.send_single_message", "POST data")
self.print_debug_pretty(data)
# Actual sending
url = "{base_url}/{domain}/messages".format(base_url=self.base_url, domain=cp_domain)
reason, success, result = self.post(url, data=data)
deserialized, serialized = self.parseResponse(reason, success, result, caller="Api.send_single_message")
return deserialized, serialized
|
# Generated by Django 3.1.7 on 2021-04-10 05:33
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('app', '0004_post_image'),
]
operations = [
migrations.AlterField(
model_name='post',
name='image',
field=models.ImageField(upload_to='app/images'),
),
]
|
# coding=utf-8
from __future__ import absolute_import, division, print_function
import logging
import argparse
import os
import random
import numpy as np
import time
from datetime import timedelta
from PIL import Image
from torchvision import transforms
import torch
import torch.distributed as dist
from tqdm import tqdm
from torch.utils.tensorboard import SummaryWriter
from apex import amp
from apex.parallel import DistributedDataParallel as DDP
from models.modeling import VisionTransformer, CONFIGS
from utils.scheduler import WarmupLinearSchedule, WarmupCosineSchedule
from utils.data_utils import get_loader
from utils.dist_util import get_world_size
import os
def findAllFile(base):
for root, ds, fs in os.walk(base):
for f in fs:
fullname = os.path.join(root, f)
yield fullname
def valid_new(args, model):
# Validation!
# _, test_loader = get_loader(args)
flag = 0
folder_dir='./INat2017/train_val_images/'
dirs_archive=[]
file_archive=[]
for i in findAllFile(folder_dir):
#print(i)
file_archive.append(i)
for i in range(len(file_archive)):
# transform ori image and save
path_img = file_archive[i]
img = Image.open(path_img).convert('RGB')
transform=transforms.Compose([transforms.Resize((304, 304), Image.BILINEAR),
#transforms.CenterCrop((448, 448)),
])
imgt = transform(img)
new_image = './new_images/'+"{:09d}".format(i)+'.jpg'
print(new_image)
imgt.save(new_image)
img = Image.open(path_img).convert('RGB')
transform=transforms.Compose([transforms.Resize((304, 304), Image.BILINEAR),
#transforms.CenterCrop((448, 448)),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])])
img = transform(img).unsqueeze(0)
img = img.to(args.device)
model.eval()
with torch.no_grad():
_, attn = model(img)
attn = attn.squeeze()
attn = torch.sum(attn, dim=0)
new_npy = './new_images_attention/'+"{:09d}".format(i)+'.npy'
np.save(new_npy, attn.cpu().numpy())
return flag
if __name__ == "__main__":
valid_new(args, model)
|
from django.urls import path
from . import views
urlpatterns = [
path('',views.Homepage, name='Homepage'),
path('login',views.Login, name='Login'),
path('index',views.Index, name='Index'),
path('view_profile',views.View_Profile, name='View_Profile'),
# path('test',views.index, name='base'),
# url(r'^countries/$',views.get_countries, name='Homepage'),
# url(r'^domains/$',views.get_domains, name='Homepage'),
# url(r'^organisations/$',views.get_organisations, name='Homepage'),
# url(r'^co_state_data/$',views.get_add_country_state_datalist, name='Homepage'),
# url(r'^add_new_cou/$',views.add_new_countries, name='Homepage'),
# url(r'^sam/$',views.get_country_domains, name='Homepage'),
] |
# SPDX-FileCopyrightText: 2020 - Sebastian Ritter <bastie@users.noreply.github.com>
# SPDX-License-Identifier: Apache-2.0
'''
Created on 05.10.2020
@author: Sͬeͥbͭaͭsͤtͬian
'''
from java.lang.Object import Object
class Properties(Object):
'''
classdocs
'''
properties = {}
def __init__(self):
'''
Constructor
'''
pass
def getProperty(self, key: str) -> str:
return self.properties.get(key, None)
def setProperty(self, key: str, value: str) -> Object:
oldValue = self.getProperty(key)
self.properties[key] = value
return oldValue
def list(self, output):
output.println("-- listing properties --")
keys = self.properties.keys()
for key in keys:
value = self.properties.get(key, "")
value = (value[:37]+'...') if len(value) > 40 else value
output.println(key + "=" + value)
|
#!/usr/bin/python3
import sys
import json
import datetime
target = sys.argv[1] # target -> word (airplane)
# Initialization
print ('%s\t%s' % (target, "0"))
print ('%s\t%s' % ("Weekend", "0"))
for item in sys.stdin:
row = json.loads(item)
if (
row["word"] == target and # word
all(x.isalpha() or x.isspace() for x in row["word"]) and # alphabets and white spaces
type(row["recognized"]) == bool and # recognized
len(row["drawing"]) > 0 and all(len(stroke)==2 for stroke in row["drawing"])
# n(>=1) strokes and every stroke has exactly 2 arrays
):
if (
len(row["countrycode"])==2 and row["countrycode"].isupper() and # countrycode
len(row["key_id"])==16 and row["key_id"].isnumeric() # key_id (numeric and 16 digits)
):
if row["recognized"]:
print ('%s\t%s' % (row["word"], "1"))
else:
time_day = datetime.datetime.strptime(row["timestamp"], '%Y-%m-%d %H:%M:%S.%f %Z').weekday()
if time_day == 5 or time_day == 6:
print('%s\t%s' % ("Weekend", "1"))
|
#! /usr/bin/env python
#
#This file is used to get the flow and system parameters for the simulation.
import tkMessageBox as tkmb
from Tkinter import Frame, Label, Entry, OptionMenu, Button, Text, \
DoubleVar, StringVar, IntVar
from capsim_object_types import CapSimWindow, MatrixComponent
from capsim_functions import get_superfont
class MatrixEditor:
"""Gets the contaminant properties."""
def __init__(self, master, system, matrix, matrices, materials, editflag, newflag):
"""Constructor method. Defines the parameters to be obtained in this
window."""
self.master = master
self.fonttype = system.fonttype
self.version = system.version
self.superfont = get_superfont(self.fonttype) #superscript font
self.tframe = Frame(master.tframe)
self.frame = Frame(master.frame)
self.bframe = Frame(master.bframe)
self.top = None #flag for existence of toplevel#
self.matrix = matrix
self.matrices = matrices
self.materials = materials
self.matrices_list = self.materials.keys()
self.matrices_list.sort()
for matrix in (self.matrices):
if matrix.number <> self.matrix.number and len(matrix.components) == 1 and self.matrices_list.count(matrix.name) > 0: self.matrices_list.remove(matrix.name)
self.model = StringVar(value = 'Linear') #Define the imaginary model for the components
self.name = StringVar(value = self.matrices_list[0]) #matrix name
self.e = DoubleVar(value = 0.5) #stores the porosity
self.rho = DoubleVar(value = 1.0) #stores the bulk density
self.foc = DoubleVar(value = 0.01) #stores the organic carbon fraction
self.editflag = editflag
self.newflag = newflag
self.cancelflag = 0
if editflag == 0:
self.components = [MatrixComponent(1)] #Define components
if editflag == 1: #Detemine whether the chemical is added or edited
self.components = self.matrix.components
self.name.set( self.matrix.name)
self.model.set( self.matrix.model)
self.e.set( self.matrix.e)
self.rho.set( self.matrix.rho)
self.foc.set( self.matrix.foc)
def make_widgets(self):
"""Make the widgets for the window."""
self.bgcolor = self.frame.cget('bg')
self.instructions = Label(self.frame, text = ' Please provide the following properties for the matrix: ')
self.blankcolumn = Label(self.frame, text =' ', width = 1)
self.namecolumn = Label(self.frame, text =' ', width = 20)
self.ecolumn = Label(self.frame, text =' ', width = 14)
self.rhocolumn = Label(self.frame, text =' ', width = 15)
self.foccolumn = Label(self.frame, text =' ', width = 15)
self.namelabel = Label(self.frame, text = 'Material')
self.elabel = Label(self.frame, text = 'Porosity')
self.rholabel = Label(self.frame, text = 'Bulk density ('+u'g/cm\u00B3'+')')
self.foclabel = Label(self.frame, text = 'Organic carbon fraction')
if self.editflag == 1:
self.namewidget = Label(self.frame, width = 16, justify = 'center', textvariable = self.name)
else:
if self.newflag == 0:
self.namewidget = OptionMenu(self.frame, self.name, *self.matrices_list, command = self.click_matrix)
else:
self.name.set('Matrix')
self.namewidget = Entry(self.frame, width = 16, justify = 'center', textvariable = self.name)
self.ewidget = Entry(self.frame, width = 10, justify = 'center', textvariable = self.e)
self.rhowidget = Entry(self.frame, width = 10, justify = 'center', textvariable = self.rho)
self.focwidget = Entry(self.frame, width = 10, justify = 'center', textvariable = self.foc)
self.okbutton = Button(self.frame, text = 'OK', width = 20, command = self.OK)
self.cancelbutton = Button(self.frame, text = 'Cancel', width = 20, command = self.Cancel)
self.blank1 = Label(self.frame, text = ' ')
self.blank2 = Label(self.frame, text = ' ')
#show the widgets on the grid
self.instructions.grid(row = 0, column = 0, columnspan = 7, padx = 8, sticky = 'W')
self.blankcolumn.grid( row = 1, column = 0, sticky = 'WE', padx = 1, pady = 1)
self.namecolumn.grid( row = 1, column = 1, sticky = 'WE', padx = 1, pady = 1)
self.ecolumn.grid( row = 1, column = 2, sticky = 'WE', padx = 1, pady = 1)
self.rhocolumn.grid( row = 1, column = 3, sticky = 'WE', padx = 1, pady = 1)
self.foccolumn.grid( row = 1, column = 4, sticky = 'WE', padx = 1, pady = 1)
self.namelabel.grid( row = 2, column = 1, sticky = 'WE', padx = 4, pady = 1)
self.elabel.grid( row = 2, column = 2, sticky = 'WE', padx = 1, pady = 1)
self.rholabel .grid( row = 2, column = 3, sticky = 'WE', padx = 1, pady = 1)
self.foclabel .grid( row = 2, column = 4, sticky = 'WE', padx = 1, pady = 1)
if self.newflag == 0: self.namewidget.grid( row = 4, column = 1, sticky = 'WE', padx = 6, pady = 1)
else: self.namewidget.grid( row = 4, column = 1, padx = 6, pady = 1)
self.ewidget.grid ( row = 4, column = 2, padx = 6 ,pady = 1)
self.rhowidget.grid ( row = 4, column = 3, padx = 6 ,pady = 1)
self.focwidget.grid( row = 4, column = 4, padx = 6 ,pady = 1)
self.blank1.grid( row = 5)
self.okbutton.grid( row = 6, columnspan = 11)
self.cancelbutton.grid( row = 7, columnspan = 11)
self.blank2.grid( row = 8)
self.okbutton.bind('<Return>', self.OK)
self.focusbutton = self.okbutton
if self.editflag == 0 and self.newflag == 0: self.click_matrix()
def click_matrix(self, event = None):
"""Pulls up the contaminant properties from the database after selecting
a compound."""
self.tort = self.materials[self.name.get()].tort
self.sorp = self.materials[self.name.get()].sorp
self.e.set (self.materials[self.name.get()].e)
self.rho.set(self.materials[self.name.get()].rho)
self.foc.set(self.materials[self.name.get()].foc)
self.frame.update()
self.master.geometry()
self.master.center()
def OK(self, event = None):
"""Finish and move on. Checks that the number chemicals are less than the
total number of chemicals in database."""
if self.editflag == 0:
check =[(matrix.name == self.name.get()) for matrix in self.matrices[0:-1]]
if self.editflag == 1:
check =[0]
if self.master.window.top is not None: self.master.open_toplevel()
elif self.e.get() > 1 or self.e.get() < 0:
tkmb.showinfo(self.version, 'The porosity of a solid can not be larger than 1 or smaller than 0')
self.e.set(0.5)
elif self.rho.get() < 0:
tkmb.showinfo(self.version, 'The bulk density of a solid can not be negative')
self.e.set(1.0)
elif self.foc.get() > 1 or self.foc.get() < 0:
tkmb.showinfo(self.version, 'The organic carbon fraction of a solid can not be larger than 1 or smaller than 0')
self.e.set(1.0)
elif sum(check) >= 1 or self.name.get() == '': self.matrix_error()
else:
self.components[0].name = self.name.get()
self.components[0].mfraction = 1.
self.components[0].fraction = 1.
self.components[0].e = self.e.get()
self.components[0].rho = self.rho.get()
self.components[0].foc = self.foc.get()
if self.editflag == 0:
if self.newflag == 0:
self.components[0].tort = self.materials[self.name.get()].tort
self.components[0].sorp = self.materials[self.name.get()].sorp
else:
self.components[0].tort = 'Millington & Quirk'
self.components[0].sorp = 'Linear--Kd specified'
self.master.tk.quit()
def matrix_error(self):
tkmb.showerror(title = self.version, message = 'This solid material has already been added to the database!')
self.focusbutton = self.okbutton
self.master.tk.lift()
def Cancel(self):
try:
self.name.set(self.matrix.name)
self.model.set(self.matrix.model)
self.e.set( self.matrix.e)
self.rho.set( self.matrix.rho)
self.foc.set( self.matrix.foc)
self.components = self.matrix.components
except: self.cancelflag = 1
if self.master.window.top is not None: self.master.open_toplevel()
else: self.master.tk.quit()
class MatrixDeleter:
def __init__(self, master, system, matrix):
"""Constructor method. Defines the parameters to be obtained in this
window."""
self.master = master
self.fonttype = system.fonttype
self.version = system.version
self.superfont = get_superfont(self.fonttype) #superscript font
self.tframe = Frame(master.tframe)
self.frame = Frame(master.frame)
self.bframe = Frame(master.bframe)
self.top = None #flag for existence of toplevel#
self.matrix = matrix
self.name = StringVar(value = matrix.name) #stores the chemical name
self.model = StringVar(value = matrix.model) #stores the chemical name
self.e = DoubleVar(value = matrix.e) #stores the porosity
self.rho = DoubleVar(value = matrix.rho) #stores the bulk density
self.foc = DoubleVar(value = matrix.foc) #stores the organic carbon fraction
self.cancelflag = 0
def make_widgets(self):
self.bgcolor = self.frame.cget('bg')
self.instructions = Label(self.frame, text = ' Are you sure to delete the following matrix? ')
self.namelabel = Label(self.frame, text = 'Material')
self.elabel = Label(self.frame, text = 'Porosity')
self.rholabel = Label(self.frame, text = 'Bulk density ('+ u'g/cm\u00B3'+')')
self.foclabel = Label(self.frame, text = 'Organic carbon\n fraction')
self.namewidget = Label(self.frame, width = 16, justify = 'center', textvariable = self.name)
self.ewidget = Label(self.frame, width = 16, justify = 'center', textvariable = self.e)
self.rhowidget = Label(self.frame, width = 16, justify = 'center', textvariable = self.rho)
self.focwidget = Label(self.frame, width = 16, justify = 'center', textvariable = self.foc)
self.blankcolumn = Label(self.frame, text =' ', width = 1)
self.namecolumn = Label(self.frame, text =' ', width = 20)
self.ecolumn = Label(self.frame, text =' ', width = 14)
self.rhocolumn = Label(self.frame, text =' ', width = 15)
self.foccolumn = Label(self.frame, text =' ', width = 15)
self.deletebutton = Button(self.frame, text = 'Delete', width = 20, command = self.Delete)
self.cancelbutton = Button(self.frame, text = 'Cancel', width = 20, command = self.Cancel)
self.blank1 = Label(self.frame, text = ' ')
self.blank2 = Label(self.frame, text = ' ')
#show the widgets on the grid
self.instructions.grid(row = 0, column = 0, columnspan = 6, padx = 8, sticky = 'W')
self.blankcolumn.grid( row = 1, column = 0, sticky = 'WE', padx = 1, pady = 1)
self.namecolumn.grid( row = 1, column = 1, sticky = 'WE', padx = 1, pady = 1)
self.ecolumn.grid( row = 1, column = 2, sticky = 'WE', padx = 1, pady = 1)
self.rhocolumn.grid( row = 1, column = 3, sticky = 'WE', padx = 1, pady = 1)
self.foccolumn.grid( row = 1, column = 4, sticky = 'WE', padx = 1, pady = 1)
self.namelabel.grid( row = 2, column = 1, sticky = 'WE', padx = 4, pady = 1)
self.elabel.grid( row = 2, column = 2, sticky = 'WE', padx = 1, pady = 1)
self.rholabel .grid( row = 2, column = 3, sticky = 'WE', padx = 1, pady = 1)
self.foclabel .grid( row = 2, column = 4, sticky = 'WE', padx = 1, pady = 1)
self.namewidget.grid( row = 4, column = 1, padx = 2, pady = 1, sticky = 'WE')
self.ewidget.grid ( row = 4, column = 2, padx = 2 ,pady = 1)
self.rhowidget.grid ( row = 4, column = 3, padx = 2 ,pady = 1)
self.focwidget.grid( row = 4, column = 4, padx = 2 ,pady = 1)
self.blank1.grid( row = 5)
self.deletebutton.grid( row = 6, columnspan = 11)
self.cancelbutton.grid( row = 7, columnspan = 11)
self.blank2.grid( row = 8)
self.deletebutton.bind('<Return>', self.Delete)
self.focusbutton = self.deletebutton
def Delete(self, event = None):
"""Finish and move on. Checks that the number chemicals are less than the
total number of chemicals in database."""
if self.master.window.top is not None: self.master.open_toplevel()
else: self.master.tk.quit()
def Cancel(self):
try:
self.name.set(self.matrix.name)
self.model.set(self.matrix.model)
self.e.set( self.matrix.e)
self.rho.set( self.matrix.rho)
self.foc.set( self.matrix.foc)
self.components = self.matrix.components
except: self.cancelflag = 1
if self.master.window.top is not None: self.master.open_toplevel()
else: self.master.tk.quit()
class MixtureEditor:
"""Gets the contaminant properties."""
def __init__(self, master, system, matrix, matrices, materials, editflag):
"""Constructor method. Defines the parameters to be obtained in this
window."""
self.master = master
self.fonttype = system.fonttype
self.version = system.version
self.superfont = get_superfont(self.fonttype) #superscript font
self.tframe = Frame(master.tframe)
self.frame = Frame(master.frame)
self.bframe = Frame(master.bframe)
self.top = None #flag for existence of toplevel#
self.matrix = matrix
self.matrices = matrices
self.materials = materials
self.mixing_models = ['Linear', 'None']
self.name = StringVar(value = 'Mixture') #matrix name
self.model = StringVar(value = self.mixing_models[0]) #model name
self.e = DoubleVar() #stores the porosity
self.rho = DoubleVar() #stores the bulk density
self.foc = DoubleVar() #stores the organic carbon fraction
self.components = [] #components
self.editflag = editflag
self.cancelflag = 0
if editflag == 1: #Detemine whether the chemical is added or edited
for component in self.matrix.components:
self.components.append(component.copy())
self.components[-1].name = StringVar(value = self.components[-1].name)
self.components[-1].mfraction = DoubleVar(value = self.components[-1].mfraction)
self.name.set( self.matrix.name)
self.model.set( self.matrix.model)
self.e.set( self.matrix.e)
self.rho.set( self.matrix.rho)
self.foc.set( self.matrix.foc)
def make_widgets(self):
"""Make the widgets for the window."""
self.bgcolor = self.frame.cget('bg')
self.instructions = Label(self.frame, text = 'Please provides the following information about the mixture: ')
self.blank1 = Label(self.frame, text =' ', width = 15)
self.blankcolumn = Label(self.frame, text =' ', width = 1)
self.delcolumn = Label(self.frame, text =' ', width = 6)
self.compcolumn = Label(self.frame, text =' ', width = 18)
self.fraccolumn = Label(self.frame, text =' ', width = 10)
self.ecolumn = Label(self.frame, text =' ', width = 10)
self.rhocolumn = Label(self.frame, text =' ', width = 15)
self.foccolumn = Label(self.frame, text =' ', width = 20)
self.namelabel = Label(self.frame, text = 'Name')
self.elabel = Label(self.frame, text = 'Porosity')
self.rholabel = Label(self.frame, text = 'Bulk density ('+ u'g/cm\u00B3'+')')
self.foclabel = Label(self.frame, text = 'Organic carbon fraction')
self.namewidget = Entry(self.frame, textvariable = self.name, justify = 'center', width = 16)
self.ewidget = Entry(self.frame, textvariable = self.e , justify = 'center', width = 10)
self.rhowidget = Entry(self.frame, textvariable = self.rho , justify = 'center', width = 10)
self.focwidget = Entry(self.frame, textvariable = self.foc , justify = 'center', width = 10)
self.complabel = Label(self.frame, text = 'Component')
self.compflabel = Label(self.frame, text = 'Weight fraction')
self.compelabel = Label(self.frame, text = 'Porosity')
self.comprholabel = Label(self.frame, text = 'Bulk density ('+u'g/cm\u00B3'+')')
self.compfoclabel = Label(self.frame, text = 'Organic carbon fraction')
self.addwidget = Button(self.frame, text = 'Add components', width = 20, command = self.add_components)
self.loadwidget = Button(self.frame, text = 'Load components', width = 20, command = self.load_components)
self.esitimator = Button(self.frame, text = 'Estimate Mixture Properties', width = 20, command = self.estimate_mixture)
self.okbutton = Button(self.frame, text = 'OK', width = 20, command = self.OK)
self.cancelbutton = Button(self.frame, text = 'Cancel', width = 20, command = self.Cancel)
self.blank1 = Label( self.frame, text = ' ')
self.blank2 = Label( self.frame, text = ' ')
self.blank3 = Label( self.frame, text = ' ')
#show the widgets on the grid
self.instructions.grid(row = 0, column = 0, columnspan = 7, padx = 8, sticky = 'W')
self.blank1.grid( row = 1, column = 0, columnspan = 2)
self.blankcolumn.grid( row = 3, column = 0, sticky = 'WE', padx = 1, pady = 1)
self.delcolumn.grid( row = 3, column = 1, sticky = 'WE', padx = 1, pady = 1)
self.compcolumn.grid( row = 3, column = 2, sticky = 'WE', padx = 1, pady = 1)
self.fraccolumn.grid( row = 3, column = 3, sticky = 'WE', padx = 1, pady = 1)
self.ecolumn.grid( row = 3, column = 4, sticky = 'WE', padx = 1, pady = 1)
self.rhocolumn.grid( row = 3, column = 5, sticky = 'WE', padx = 1, pady = 1)
self.foccolumn.grid( row = 3, column = 6, sticky = 'WE', padx = 1, pady = 1)
self.namelabel.grid( row = 4, column = 2, sticky = 'WE', padx = 4, pady = 1)
self.elabel.grid( row = 4, column = 4, sticky = 'WE', padx = 1, pady = 1)
self.rholabel .grid( row = 4, column = 5, sticky = 'WE', padx = 1, pady = 1)
self.foclabel .grid( row = 4, column = 6, sticky = 'WE', padx = 1, pady = 1)
self.namewidget.grid( row = 5, column = 2, padx = 4, pady = 1)
self.ewidget.grid( row = 5, column = 4, padx = 1, pady = 1)
self.rhowidget.grid( row = 5, column = 5, padx = 1, pady = 1)
self.focwidget.grid( row = 5, column = 6, padx = 1, pady = 1)
self.blank3.grid( row = 6, column = 0, columnspan = 2)
self.complabel.grid( row = 7, column = 2, sticky = 'WE', padx = 4, pady = 1)
self.compflabel.grid( row = 7, column = 3, sticky = 'WE', padx = 1, pady = 1)
self.compelabel.grid( row = 7, column = 4, sticky = 'WE', padx = 1, pady = 1)
self.comprholabel.grid( row = 7, column = 5, sticky = 'WE', padx = 1, pady = 1)
self.compfoclabel.grid( row = 7, column = 6, sticky = 'WE', padx = 1, pady = 1)
self.update_components()
def update_components(self):
try:
self.addwidget.grid_forget()
self.okbutton.grid_forget()
self.cancelbutton.grid_forget()
except: pass
row = 8
for component in self.components:
try:
component.get_component()
component.remove_propertieswidgets()
except: pass
component.number = self.components.index(component) + 1
component.propertieswidgets(self.frame, row, self.master, self.materials, self.matrices)
row = row + 1
self.blank1.grid( row = row)
row = row + 1
self.addwidget.grid( row = row, columnspan = 11)
row = row + 1
self.loadwidget.grid( row = row, columnspan = 11)
row = row + 1
self.esitimator.grid( row = row, columnspan = 11)
row = row + 1
self.okbutton.grid( row = row, columnspan = 11)
row = row + 1
self.cancelbutton.grid( row = row, columnspan = 11)
row = row + 1
self.blank2.grid( row = row)
self.okbutton.bind('<Return>', self.OK)
self.focusbutton = self.okbutton
self.master.geometry()
def add_components(self, event = None):
total_fraction = 0
for component in self.components:
total_fraction = total_fraction + component.mfraction.get()
self.components.append(MatrixComponent(len(self.components)+ 1))
self.components[-1].name = ' '
if total_fraction > 1: self.components[-1].mfraction = 0
else: self.components[-1].mfraction = 1-total_fraction
self.components[-1].fraction = 0
self.components[-1].e = 0
self.components[-1].rho = 0
self.components[-1].foc = 0
self.update_components()
def load_components(self, event = None):
total_fraction = 0
for component in self.components:
total_fraction = total_fraction + component.mfraction.get()
self.components.append(MatrixComponent(len(self.components)+ 1))
self.components[-1].name = ' '
if total_fraction > 1: self.components[-1].mfraction = 0
else: self.components[-1].mfraction = 1-total_fraction
self.update_components()
def del_component(self, number):
self.components[number - 1].remove_propertieswidgets()
self.components.remove(self.components[number - 1])
self.update_components()
def estimate_mixture(self):
total_fraction = 0
for component in self.components:
total_fraction = total_fraction + component.mfraction.get()
if total_fraction <> 1.: self.fraction_error()
else: self.calculate_matrix()
self.frame.update()
self.update_components()
def OK(self, event = None):
"""Finish and move on. Checks that the number chemicals are less than the
total number of chemicals in database."""
components_check = 0
component_list = [component.name for component in self.components]
for name in component_list:
if component_list.count(name) > 1:
components_check = 1
if self.editflag == 0: check =[(matrix.name == self.name.get()) for matrix in self.matrices[0:-1]]
else: check =[0]
total_fraction = 0
rho_flag = 0
for component in self.components:
total_fraction = total_fraction + component.mfraction.get()
if component.rho.get() <= 0:
rho_flag = 1
if self.master.window.top is not None: self.master.open_toplevel()
elif sum(check) >= 1 or self.name.get() == '': self.matrix_error()
elif len(self.components) < 2: self.empty_component()
elif total_fraction <> 1.: self.fraction_error()
elif rho_flag == 1: self.rho_error()
elif components_check == 1: self.replicate_error()
else:
self.calculate_matrix()
self.master.tk.quit()
def matrix_error(self):
tkmb.showerror(title = self.version, message = 'This matrix has already been added to the matrix list!')
self.focusbutton = self.okbutton
self.master.tk.lift()
def empty_component(self):
tkmb.showerror(title = self.version, message = 'The mixture must consist at least two components')
self.focusbutton = self.okbutton
self.master.tk.lift()
def fraction_error(self):
tkmb.showinfo(self.version, 'The sum of the weight fraction is not 1, please check')
self.focusbutton = self.okbutton
self.master.tk.lift()
def rho_error(self):
tkmb.showinfo(self.version, 'The bulk density of a component must be a positive value')
self.focusbutton = self.okbutton
self.master.tk.lift()
def replicate_error(self):
tkmb.showinfo(self.version, 'At least one component is replicated in the mixture')
self.focusbutton = self.okbutton
self.master.tk.lift()
def Cancel(self):
try:
self.name.set(self.matrix.name)
self.model.set(self.matrix.model)
self.e.set( self.matrix.e)
self.rho.set( self.matrix.rho)
self.foc.set( self.matrix.foc)
self.components = self.matrix.components
except: self.cancelflag = 1
if self.master.window.top is not None: self.master.open_toplevel()
else: self.master.tk.quit()
def calculate_matrix(self):
rho_flag = 0
e = 0
rho = 0
moc = 0
foc = 0
fractions = 0
volume = 0
for component in self.components:
if component.rho.get() <= 0:
rho_flag = 1
if rho_flag == 1:
self.rho_error()
else:
for component in self.components:
component.get_component()
component.remove_propertieswidgets()
volume = volume + component.mfraction / component.rho
for component in self.components:
component.fraction = component.mfraction / component.rho / volume
e = e + component.fraction * component.e
rho = rho + component.fraction * component.rho
moc = moc + component.fraction * component.rho * component.foc
foc = moc/rho
self.e.set(round(e,6))
self.rho.set(round(rho,6))
self.foc.set(round(foc,6))
|
#Context Manager - Criando e usando gerenciadores de contexto.
arq = 'D:\\GitHub\\Curso_Python\\Udemy\\Secao4\\aula110\\abc.txt'
# A forma mais comum de abrir e fechar aquivos texto
'''file = open(arq, 'w')
file.write('Alguma coisa')
file.close()'''
# Outra forma de manipular arquivos
"""
with open(arq, 'w') as file:
file.write('Alguma coisa de novo')
"""
#Usando o Gerenciador de contexto
from contextlib import contextmanager
@contextmanager # so funciona se chamar com o with
def abrir(arquivo, modo):
try:
print('Abrindo arquivo')
arquivo = open(arquivo, modo)
yield arquivo
finally:
print('Fechando arquivo')
arquivo.close()
with abrir(arq, 'w') as arquivo:
arquivo.write('Linha 1\n')
arquivo.write('Linha 2\n')
arquivo.write('Linha 3\n')
|
from graphviz import Digraph
import tree
def create_graph(root, graph_name, show_prob=False, format='svg', view=True):
if type(root) != type(tree.Node('', [])):
print("Error: root argument {} is not of type tree.Node!")
else:
filename = "{}.{}".format(graph_name, format)
graph = Digraph(graph_name, filename=filename, format=format)
graph.attr('node', shape='box')
__create_graph(root, graph, show_prob)
if view:
graph.view()
else:
graph.save()
return graph
def __create_graph(node, graph, show_prob):
'''Helper function that from a node of type tree.Node, a graph of type
Digraph and a boolean named show_prob return a graph of the id3 decision
tree stored in node.
'''
treshold_value = node.get_treshold_value()
treshold_name = node.get_treshold_name()
node_hash = str(hash(node))
# if node is a leaf, then show its confidence
if len(node.get_sons()) == 0:
if show_prob:
value = "{}\n({} %)".format(node.get_value(), node.get_prob())
else:
value = "{}".format(node.get_value())
else:
# otherwise put treshold_name as node's label and treshold_value in
# inequalities as edges' labels
value = str(treshold_name)
# call __create_graph on each son of this node
sons = node.get_sons()
graph.edge(node_hash, str(hash(sons[0])), \
label="<{}".format(treshold_value))
__create_graph(sons[0], graph, show_prob)
graph.edge(node_hash, str(hash(sons[1])), \
label=">={}".format(treshold_value))
__create_graph(sons[1], graph, show_prob)
graph.node(node_hash, value)
|
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Interpreter version: python 2.7
#
# Imports =====================================================================
import os
import time
import os.path
import hashlib
import xmltodict
from odictliteral import odict
from remove_hairs import remove_hairs
from marcxml_parser import MARCXMLRecord
# Functions & classes =========================================================
def _path_to_id(path):
"""
Name of the root directory is used as ``<packageid>`` in ``info.xml``.
This function makes sure, that :func:`os.path.basename` doesn't return
blank string in case that there is `/` at the end of the `path`.
Args:
path (str): Path to the root directory.
Returns:
str: Basename of the `path`.
"""
if path.endswith("/"):
path = path[:-1]
return os.path.basename(path)
def _calc_dir_size(path):
"""
Calculate size of all files in `path`.
Args:
path (str): Path to the directory.
Returns:
int: Size of the directory in bytes.
"""
dir_size = 0
for (root, dirs, files) in os.walk(path):
for fn in files:
full_fn = os.path.join(root, fn)
dir_size += os.path.getsize(full_fn)
return dir_size
def _get_localized_fn(path, root_dir):
"""
Return absolute `path` relative to `root_dir`.
When `path` == ``/home/xex/somefile.txt`` and `root_dir` == ``/home``,
returned path will be ``/xex/somefile.txt``.
Args:
path (str): Absolute path beginning in `root_dir`.
root_dir (str): Absolute path containing `path` argument.
Returns:
str: Local `path` when `root_dir` is considered as root of FS.
"""
local_fn = path
if path.startswith(root_dir):
local_fn = path.replace(root_dir, "", 1)
if not local_fn.startswith("/"):
return "/" + local_fn
return local_fn
def compose_info(root_dir, files, hash_fn, aleph_record, urn_nbn=None):
"""
Compose `info` XML file.
Info example::
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<info>
<created>2014-07-31T10:58:53</created>
<metadataversion>1.0</metadataversion>
<packageid>c88f5a50-7b34-11e2-b930-005056827e51</packageid>
<mainmets>mets.xml</mainmets>
<titleid type="ccnb">cnb001852189</titleid>
<titleid type="isbn">978-80-85979-89-6</titleid>
<collection>edeposit</collection>
<institution>nakladatelství Altar</institution>
<creator>ABA001</creator>
<size>1530226</size>
<itemlist itemtotal="1">
<item>\data\Denik_zajatce_Sramek_CZ_v30f-font.epub</item>
</itemlist>
<checksum type="MD5" checksum="ce076548eaade33888005de5d4634a0d">
\MD5.md5
</checksum>
</info>
Args:
root_dir (str): Absolute path to the root directory.
files (list): Absolute paths to all ebook and metadata files.
hash_fn (str): Absolute path to the MD5 file.
aleph_record (str): String with Aleph record with metadata.
Returns:
str: XML string.
"""
# compute hash for hashfile
with open(hash_fn) as f:
hash_file_md5 = hashlib.md5(f.read()).hexdigest()
schema_location = "http://www.ndk.cz/standardy-digitalizace/info11.xsd"
document = odict[
"info": odict[
"@xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance",
"@xsi:noNamespaceSchemaLocation": schema_location,
"created": time.strftime("%Y-%m-%dT%H:%M:%S", time.gmtime()),
"metadataversion": "1.0",
"packageid": _path_to_id(root_dir),
# not used in SIP
# "mainmets": _get_localized_fn(metadata_fn, root_dir),
"titleid": None,
"collection": "edeposit",
"institution": None,
"creator": None,
"size": _calc_dir_size(root_dir) / 1024, # size in kiB
"itemlist": odict[
"@itemtotal": "2",
"item": map(
lambda x: _get_localized_fn(x, root_dir),
files
)
],
"checksum": odict[
"@type": "MD5",
"@checksum": hash_file_md5,
"#text": _get_localized_fn(hash_fn, root_dir)
],
]
]
# get informations from MARC record
record = MARCXMLRecord(aleph_record)
# get publisher info
publisher = unicode(record.get_publisher(), "utf-8")
if record.get_publisher(None):
document["info"]["institution"] = remove_hairs(publisher)
# get <creator> info
creator = record.getDataRecords("910", "a", False)
alt_creator = record.getDataRecords("040", "d", False)
document["info"]["creator"] = creator[0] if creator else alt_creator[-1]
# collect informations for <titleid> tags
isbns = record.get_ISBNs()
ccnb = record.getDataRecords("015", "a", False)
ccnb = ccnb[0] if ccnb else None
if any([isbns, ccnb, urn_nbn]): # TODO: issn
document["info"]["titleid"] = []
for isbn in isbns:
document["info"]["titleid"].append({
"@type": "isbn",
"#text": isbn
})
if ccnb:
document["info"]["titleid"].append({
"@type": "ccnb",
"#text": ccnb
})
if urn_nbn:
document["info"]["titleid"].append({
"@type": "urnnbn",
"#text": urn_nbn
})
# TODO: later
# if issn:
# document["info"]["titleid"].append({
# "@type": "issn",
# "#text": issn
# })
# remove unset options
unset_keys = [
key
for key in document["info"]
if key is None
]
for key in unset_keys:
del document[key]
xml_document = xmltodict.unparse(document, pretty=True)
return xml_document.encode("utf-8")
|
import json
import re
from copy import copy
from logging import Formatter, LogRecord
class PlainFormatter(Formatter):
"""Remove all control chars from the log and format it as plain text, also restrict the max-length of msg to 512."""
def format(self, record):
"""
Format the LogRecord by removing all control chars and plain text, and restrict the max-length of msg to 512.
:param record: A LogRecord object.
:return:: Formatted plain LogRecord.
"""
cr = copy(record)
if isinstance(cr.msg, str):
cr.msg = re.sub(r'\u001b\[.*?[@-~]', '', str(cr.msg))[:512]
return super().format(cr)
class JsonFormatter(Formatter):
"""Format the log message as a JSON object so that it can be later used/parsed in browser with javascript."""
KEYS = {
'created',
'filename',
'funcName',
'levelname',
'lineno',
'msg',
'module',
'name',
'pathname',
'process',
'thread',
'processName',
'threadName',
'log_id',
} #: keys to extract from the log
def format(self, record: 'LogRecord'):
"""
Format the log message as a JSON object.
:param record: A LogRecord object.
:return:: LogRecord with JSON format.
"""
cr = copy(record)
cr.msg = re.sub(r'\u001b\[.*?[@-~]', '', str(cr.msg))
return json.dumps(
{k: getattr(cr, k) for k in self.KEYS if hasattr(cr, k)}, sort_keys=True
)
class ProfileFormatter(Formatter):
"""Format the log message as JSON object and add the current used memory into it."""
def format(self, record: 'LogRecord'):
"""
Format the log message as JSON object and add the current used memory.
:param record: A LogRecord object.
:return:: Return JSON formatted log if msg of LogRecord is dict type else return empty.
"""
from jina.logging.profile import used_memory
cr = copy(record)
if isinstance(cr.msg, dict):
cr.msg.update(
{k: getattr(cr, k) for k in ['created', 'module', 'process', 'thread']}
)
cr.msg['memory'] = used_memory(unit=1)
return json.dumps(cr.msg, sort_keys=True)
else:
return ''
|
#! /usr/bin/env python
import sys
import os
lastkey = None
curkey = None
sumvalue = 0
for line in sys.stdin:
items = line.strip().split('\t', 1)
if items[0] == curkey:
sumvalue += int(items[1])
else:
if curkey != None:
print curkey + "\t%d" % sumvalue
curkey = items[0]
sumvalue = int(items[1])
|
#!/usr/bin/env python3
import itertools
import pyttsx3
import random
import sys
import time
# [ [i.languages, i.id] for i in n.voice.getProperty("voices") ] - retrieves languages
CURRENT_LANGUAGE_CODES = {
"it_IT": "com.apple.speech.synthesis.voice.luca", # Modern Standard Italian
"el_GR": "com.apple.speech.synthesis.voice.melina", # Modern Standard Greek
"fr_FR": "com.apple.speech.synthesis.voice.thomas", # Parisian French
"fr_CA": "com.apple.speech.synthesis.voice.amelie", # Canadian French
"de_DE": "com.apple.speech.synthesis.voice.anna", # Hochdeutsch
"he_IL": "com.apple.speech.synthesis.voice.carmit", # Israeli Hebrew
}
class Narrator:
def __init__(self, language_code=None):
self.voice = pyttsx3.init()
if language_code:
self.set_language(language_code)
@classmethod
def lookup_voice_id(cls, language_code):
return CURRENT_LANGUAGE_CODES[language_code]
def set_language(self, language_code):
voice_id = self.lookup_voice_id(language_code)
self.voice.setProperty("voice", voice_id)
def speak(self, text):
fmt_text = f"{text}"
self.voice.say(fmt_text)
self.voice.runAndWait()
def generate_cardinal_numbers(rng, len):
return [random.randrange(0, rng) for i in range(len)]
def cardinal_numbers(rng=11, len=9):
drill = generate_cardinal_numbers(rng, len)
return f'{drill}'
def main():
turn = 1
narrator = Narrator("he_IL")
nxt = True
while True:
if nxt:
intro = f"תרגיל מספר {turn}."
print(intro)
narrator.speak(intro)
# drill = cardinal_numbers(len=4)
drill = cardinal_numbers(rng=200, len=1)
nxt = False
narrator.speak(drill)
cmd = input("(r)epeat, (n)ext, (q)uit\n> ")
if cmd == "r":
continue
elif cmd == "q":
print(drill)
sys.exit(0)
elif cmd == "\n" or "n":
print(drill)
turn += 1
nxt = True
if __name__ == "__main__":
main()
|
from day_13 import get_data_from_input, time_til_next_departure
def find_timestamp_with_desired_offset(current_timestamp, bus_id, current_offset, desired_offset, increment):
"""Advance by increment until current offset --> desired offset for bus ID"""
timestamp = current_timestamp
while current_offset != desired_offset:
timestamp += increment
current_offset = time_til_next_departure(timestamp, bus_id)
return timestamp
def get_earliest_timestamp(bus_id_strs):
bus_id_offset_tuples = []
for idx, bus_id_str in enumerate(bus_id_strs):
if bus_id_str != "x":
bus_id = int(bus_id_str)
bus_id_offset_tuples.append((bus_id, idx % bus_id))
bus_id_offset_tuples.sort()
bus_id, bus_id_offset = bus_id_offset_tuples.pop()
print(f"Finding starting timestamp for bus ID {bus_id} with offset {bus_id_offset}")
timestamp = 2 * bus_id - bus_id_offset
increment = bus_id
print(f"Starting timestamp is {timestamp}; starting increment is {increment}")
while bus_id_offset_tuples:
# Now find the next timestamp which fulfills the next largest bus ID
bus_id, bus_id_offset = bus_id_offset_tuples.pop()
print(f"Finding valid timestamp for bus ID {bus_id} with offset {bus_id_offset}")
timestamp = find_timestamp_with_desired_offset(
current_timestamp=timestamp,
bus_id=bus_id,
current_offset=time_til_next_departure(timestamp, bus_id),
desired_offset=bus_id_offset,
increment=increment,
)
increment *= bus_id
print(f"Found valid timestamp {timestamp}; new increment is {increment}")
return timestamp
if __name__ == "__main__":
_, bus_ids = get_data_from_input()
print(get_earliest_timestamp(bus_ids))
|
# Thomas Horak (thorames)
# classifier.py
import re
import sys
import csv
import json
# import operator
import spacy
import math
import random
# import numpy as np
import sklearn.ensemble
import sklearn.metrics
from sklearn import svm
from sklearn.feature_extraction.text import TfidfVectorizer, CountVectorizer
from nltk.corpus import stopwords
stopwords = set(stopwords.words('english'))
# from sklearn.pipeline import make_pipeline
from sklearn.model_selection import train_test_split
# from sklearn.model_selection import cross_val_score
# from sklearn.model_selection import StratifiedKFold
from sklearn.feature_extraction import DictVectorizer
# from sklearn.model_selection import ShuffleSplit
# from sklearn.model_selection import KFold
from nltk.tokenize import RegexpTokenizer
# from sklearn.metrics import f1_score
# from sklearn.metrics import average_precision_score
from collections import Counter
from nltk.stem import PorterStemmer
bad_keys = ["VERB_Count", "PUNCT_Count", "PRON_Count", "ADJ_Count", "INTJ_Count", "ADV_Count", "NOUN_Count"]
rap_stopwords = ['nigga', 'bitch', 'money', 'never', 'right', 'cause', 'still', 'could', 'think', 'fuckin', 'every',
'really', 'night', 'around', 'better', 'would', 'black', 'fucking', 'young', 'world', 'break', 'little',
'everything', 'start', 'watch', 'tryna', 'pussy', 'friend', 'people', 'might', 'everybody', 'motherfucker',
'light', 'smoke', 'gettin', 'bring', 'street', 'thing', 'whole', 'straight', 'another', 'getting', 'catch',
'always', 'white', 'leave', 'first', 'throw', 'change', 'though', 'nothing']
def train(X, true_X):
stemmer = PorterStemmer()
tokenizer = RegexpTokenizer(r'\w+')
feat_dicts = []
idf = {}
length = len(X)
for lyric in X:
fd = {}
grams = []
pos_counts = []
lyric = lyric.split(" ")
pos_counts = lyric[-7:]
lyric = " ".join(lyric[:-7])
lyric = re.sub(r'[^a-zA-Z\d\s]', '', lyric)
tokens = tokenizer.tokenize(lyric)
tokens = [t for t in tokens if t not in rap_stopwords]
temp_tokens = []
[temp_tokens.append(stemmer.stem(t)) for t in tokens]
tokens = temp_tokens
for i in range(len(tokens)):
if tokens[i] in fd:
fd[tokens[i]] += 1
grams.append(tokens[i])
else:
fd[tokens[i]] = 1
grams.append(tokens[i])
if i < (len(tokens) - 2):
if (tokens[i] + "_" + tokens[i + 1]) in fd:
fd[tokens[i] + "_" + tokens[i + 1]] += 1
grams.append(tokens[i] + "_" + tokens[i + 1])
else:
fd[tokens[i] + "_" + tokens[i + 1]] = 1
grams.append(tokens[i] + "_" + tokens[i + 1])
fd["VERB_Count"] = float(pos_counts[0])
fd["PUNCT_Count"] = float(pos_counts[1])
fd["PRON_Count"] = float(pos_counts[2])
fd["ADJ_Count"] = float(pos_counts[3])
fd["INTJ_Count"] = float(pos_counts[4])
fd["ADV_Count"] = float(pos_counts[5])
fd["NOUN_Count"] = float(pos_counts[6])
true_X.append(' '.join(tokens))
gram_length = len(grams)
for key in fd.keys():
if key not in bad_keys:
fd[key] = fd[key] / gram_length
grams = set(grams)
for gram in grams:
if gram in idf:
idf[gram] += 1
else:
idf[gram] = 1
feat_dicts.append(fd)
for feat_dict in feat_dicts:
for key in feat_dict.keys():
if key not in bad_keys:
IDF = math.log(1 + (length / idf[key]))
feat_dict[key] = feat_dict[key] * IDF
return feat_dicts
def processLyrics(lyrics):
authors = []
for author in lyrics:
for song in lyrics[author]:
lyric = re.sub(r'\[[^>]+\]', '', song["lyrics"])
lyric = re.sub(r'\([^>]+\)', '', lyric)
lyric = re.sub(r'\{[^>]+\}', '', lyric)
lyric = lyric.split(r'\s')
text = ""
for line in lyric:
line = re.sub(r'\n', ' ', line)
text += (" " + line)
for PartOfSpeech in song["pos_counts"]:
if PartOfSpeech == "VERB":
verb = song["pos_counts"]["VERB"]
if PartOfSpeech == "PUNCT":
punct = song["pos_counts"]["PUNCT"]
if PartOfSpeech == "PRON":
pron = song["pos_counts"]["PRON"]
if PartOfSpeech == "ADJ":
adj = song["pos_counts"]["ADJ"]
if PartOfSpeech == "INTJ":
intj = song["pos_counts"]["INTJ"]
if PartOfSpeech == "ADV":
adv = song["pos_counts"]["ADV"]
if PartOfSpeech == "NOUN":
noun = song["pos_counts"]["NOUN"]
text += (" " + str(verb) + " " + str(punct) + " " + str(pron) + " " + str(adj) + " " + str(intj) + " " + str(adv) + " " + str(noun))
authors.append([author, text])
return authors
def dectree_main(var):
y = []
X = []
true_X_train = []
true_X_test = []
tokenizer = RegexpTokenizer(r'\w+')
authors = {}
POS = {}
with open('preprocessedf_corpus.json') as json_file:
lyrics = json.load(json_file)
authors = processLyrics(lyrics)
for pair in authors:
y.append(pair[0])
X.append(pair[1])
X_train, X_test, y_train, y_test = train_test_split(X, y, random_state=42)
feature_dicts = train(X_train, true_X_train)
transform = DictVectorizer()
X = transform.fit_transform(feature_dicts)
clf = sklearn.ensemble.RandomForestClassifier(n_estimators=250, min_samples_leaf=3, random_state=42, n_jobs=16)
clf.fit(X, y_train)
var = var.lower()
nlp = spacy.load('en_core_web_sm')
songlyrics = nlp(var)
pos_counts = dict(Counter([token.pos_ for token in songlyrics]))
if "VERB" not in pos_counts:
pos_counts["VERB"] = 0
if "PUNCT" not in pos_counts:
pos_counts["PUNCT"] = 0
if "PRON" not in pos_counts:
pos_counts["PRON"] = 0
if "ADJ" not in pos_counts:
pos_counts["ADJ"] = 0
if "INTJ" not in pos_counts:
pos_counts["INTJ"] = 0
if "ADV" not in pos_counts:
pos_counts["ADV"] = 0
if "NOUN" not in pos_counts:
pos_counts["NOUN"] = 0
var += (" " + str(pos_counts["VERB"]) + " " + str(pos_counts["PUNCT"]) + " " + str(pos_counts["PRON"]) + " " + str(pos_counts["ADJ"]) + " " + str(pos_counts["INTJ"]) + " " + str(pos_counts["ADV"]) + " " + str(pos_counts["NOUN"]))
X_test.append(var)
X_test_fd = train(X_test, true_X_test)
X_test_vecs = transform.transform(X_test_fd)
y_pred = clf.predict_proba(X_test_vecs)
array = clf.classes_.tolist()
best_value = float("-inf")
best_index = -1
for i in range(len(y_pred[0])):
if y_pred[0][i] == best_value:
random_choice = random.choice([best_index, i])
best_index = random_choice
if y_pred[0][i] > best_value:
best_value = y_pred[0][i]
best_index = i
return array[best_index]
|
class_dict = {
"0":{
"label_id":"n01440764",
"cn_main_class":"鱼",
"cn_class_name":"丁鲷",
"en_class_name":"tench, Tinca tinca"
},
"1":{
"label_id":"n01443537",
"cn_main_class":"鱼",
"cn_class_name":"金鱼",
"en_class_name":"goldfish, Carassius auratus"
},
"2":{
"label_id":"n01484850",
"cn_main_class":"鱼",
"cn_class_name":"大白鲨",
"en_class_name":"great white shark, white shark, man-eater, man-eating shark, Carcharodon carcharias"
},
"3":{
"label_id":"n01491361",
"cn_main_class":"鱼",
"cn_class_name":"虎鲨",
"en_class_name":"tiger shark, Galeocerdo cuvieri"
},
"4":{
"label_id":"n01494475",
"cn_main_class":"鱼",
"cn_class_name":"锤头鲨",
"en_class_name":"hammerhead, hammerhead shark"
},
"5":{
"label_id":"n01496331",
"cn_main_class":"鱼",
"cn_class_name":"电鳐",
"en_class_name":"electric ray, crampfish, numbfish, torpedo"
},
"6":{
"label_id":"n01498041",
"cn_main_class":"鱼",
"cn_class_name":"黄貂鱼",
"en_class_name":"stingray"
},
"7":{
"label_id":"n01514668",
"cn_main_class":"鸡",
"cn_class_name":"公鸡",
"en_class_name":"cock"
},
"8":{
"label_id":"n01514859",
"cn_main_class":"鸡",
"cn_class_name":"母鸡",
"en_class_name":"hen"
},
"9":{
"label_id":"n01518878",
"cn_main_class":"鸟",
"cn_class_name":"鸵鸟",
"en_class_name":"ostrich, Struthio camelus"
},
"10":{
"label_id":"n01530575",
"cn_main_class":"鸟",
"cn_class_name":"燕雀",
"en_class_name":"brambling, Fringilla montifringilla"
},
"11":{
"label_id":"n01531178",
"cn_main_class":"鸟",
"cn_class_name":"金翅雀",
"en_class_name":"goldfinch, Carduelis carduelis"
},
"12":{
"label_id":"n01532829",
"cn_main_class":"鸟",
"cn_class_name":"红雀",
"en_class_name":"house finch, linnet, Carpodacus mexicanus"
},
"13":{
"label_id":"n01534433",
"cn_main_class":"鸟",
"cn_class_name":"灯芯草雀",
"en_class_name":"junco, snowbird"
},
"14":{
"label_id":"n01537544",
"cn_main_class":"鸟",
"cn_class_name":"靛蓝鸟",
"en_class_name":"indigo bunting, indigo finch, indigo bird, Passerina cyanea"
},
"15":{
"label_id":"n01558993",
"cn_main_class":"鸟",
"cn_class_name":"知更鸟",
"en_class_name":"robin, American robin, Turdus migratorius"
},
"16":{
"label_id":"n01560419",
"cn_main_class":"鸟",
"cn_class_name":"夜莺",
"en_class_name":"bulbul"
},
"17":{
"label_id":"n01580077",
"cn_main_class":"鸟",
"cn_class_name":"松鸡",
"en_class_name":"jay"
},
"18":{
"label_id":"n01582220",
"cn_main_class":"鸟",
"cn_class_name":"喜鹊",
"en_class_name":"magpie"
},
"19":{
"label_id":"n01592084",
"cn_main_class":"鸟",
"cn_class_name":"山雀",
"en_class_name":"chickadee"
},
"20":{
"label_id":"n01601694",
"cn_main_class":"鸟",
"cn_class_name":"河鸟",
"en_class_name":"water ouzel, dipper"
},
"21":{
"label_id":"n01608432",
"cn_main_class":"鸟",
"cn_class_name":"鹞子",
"en_class_name":"kite"
},
"22":{
"label_id":"n01614925",
"cn_main_class":"鸟",
"cn_class_name":"秃鹰",
"en_class_name":"bald eagle, American eagle, Haliaeetus leucocephalus"
},
"23":{
"label_id":"n01616318",
"cn_main_class":"鸟",
"cn_class_name":"秃鹫",
"en_class_name":"vulture"
},
"24":{
"label_id":"n01622779",
"cn_main_class":"鸟",
"cn_class_name":"猫头鹰",
"en_class_name":"great grey owl, great gray owl, Strix nebulosa"
},
"25":{
"label_id":"n01629819",
"cn_main_class":"蜥蜴",
"cn_class_name":"火蜥蜴",
"en_class_name":"European fire salamander, Salamandra salamandra"
},
"26":{
"label_id":"n01630670",
"cn_main_class":"蜥蜴",
"cn_class_name":"蝾螈",
"en_class_name":"common newt, Triturus vulgaris"
},
"27":{
"label_id":"n01631663",
"cn_main_class":"蜥蜴",
"cn_class_name":"水蜥",
"en_class_name":"eft"
},
"28":{
"label_id":"n01632458",
"cn_main_class":"蜥蜴",
"cn_class_name":"斑点蝾螈",
"en_class_name":"spotted salamander, Ambystoma maculatum"
},
"29":{
"label_id":"n01632777",
"cn_main_class":"蜥蜴",
"cn_class_name":"蝾螈",
"en_class_name":"axolotl, mud puppy, Ambystoma mexicanum"
},
"30":{
"label_id":"n01641577",
"cn_main_class":"蛙",
"cn_class_name":"牛蛙",
"en_class_name":"bullfrog, Rana catesbeiana"
},
"31":{
"label_id":"n01644373",
"cn_main_class":"蛙",
"cn_class_name":"树蛙",
"en_class_name":"tree frog, tree-frog"
},
"32":{
"label_id":"n01644900",
"cn_main_class":"蛙",
"cn_class_name":"尾蛙",
"en_class_name":"tailed frog, bell toad, ribbed toad, tailed toad, Ascaphus trui"
},
"33":{
"label_id":"n01664065",
"cn_main_class":"龟",
"cn_class_name":"红海龟",
"en_class_name":"loggerhead, loggerhead turtle, Caretta caretta"
},
"34":{
"label_id":"n01665541",
"cn_main_class":"龟",
"cn_class_name":"棱皮龟",
"en_class_name":"leatherback turtle, leatherback, leathery turtle, Dermochelys coriacea"
},
"35":{
"label_id":"n01667114",
"cn_main_class":"龟",
"cn_class_name":"淡水龟",
"en_class_name":"mud turtle"
},
"36":{
"label_id":"n01667778",
"cn_main_class":"龟",
"cn_class_name":"水龟",
"en_class_name":"terrapin"
},
"37":{
"label_id":"n01669191",
"cn_main_class":"龟",
"cn_class_name":"箱龟",
"en_class_name":"box turtle, box tortoise"
},
"38":{
"label_id":"n01675722",
"cn_main_class":"蜥蜴",
"cn_class_name":"横纹鞘爪虎",
"en_class_name":"banded gecko"
},
"39":{
"label_id":"n01677366",
"cn_main_class":"蜥蜴",
"cn_class_name":"鬣蜥",
"en_class_name":"common iguana, iguana, Iguana iguana"
},
"40":{
"label_id":"n01682714",
"cn_main_class":"蜥蜴",
"cn_class_name":"变色龙",
"en_class_name":"American chameleon, anole, Anolis carolinensis"
},
"41":{
"label_id":"n01685808",
"cn_main_class":"蜥蜴",
"cn_class_name":"鞭尾蜥蜴",
"en_class_name":"whiptail, whiptail lizard"
},
"42":{
"label_id":"n01687978",
"cn_main_class":"蜥蜴",
"cn_class_name":"阿加玛",
"en_class_name":"agama"
},
"43":{
"label_id":"n01688243",
"cn_main_class":"蜥蜴",
"cn_class_name":"澳洲热带蜥蜴",
"en_class_name":"frilled lizard, Chlamydosaurus kingi"
},
"44":{
"label_id":"n01689811",
"cn_main_class":"蜥蜴",
"cn_class_name":"鳄鱼蜥蜴",
"en_class_name":"alligator lizard"
},
"45":{
"label_id":"n01692333",
"cn_main_class":"蜥蜴",
"cn_class_name":"毒蜥",
"en_class_name":"Gila monster, Heloderma suspectum"
},
"46":{
"label_id":"n01693334",
"cn_main_class":"蜥蜴",
"cn_class_name":"绿蜥蜴",
"en_class_name":"green lizard, Lacerta viridis"
},
"47":{
"label_id":"n01694178",
"cn_main_class":"蜥蜴",
"cn_class_name":"变色龙",
"en_class_name":"African chameleon, Chamaeleo chamaeleon"
},
"48":{
"label_id":"n01695060",
"cn_main_class":"蜥蜴",
"cn_class_name":"科莫多龙",
"en_class_name":"Komodo dragon, Komodo lizard, dragon lizard, giant lizard, Varanus komodoensis"
},
"49":{
"label_id":"n01697457",
"cn_main_class":"鳄鱼",
"cn_class_name":"鳄鱼",
"en_class_name":"African crocodile, Nile crocodile, Crocodylus niloticus"
},
"50":{
"label_id":"n01698640",
"cn_main_class":"鳄鱼",
"cn_class_name":"短吻鳄",
"en_class_name":"American alligator, Alligator mississipiensis"
},
"51":{
"label_id":"n01704323",
"cn_main_class":"恐龙",
"cn_class_name":"三角龙",
"en_class_name":"triceratops"
},
"52":{
"label_id":"n01728572",
"cn_main_class":"蛇",
"cn_class_name":"雷蛇",
"en_class_name":"thunder snake, worm snake, Carphophis amoenus"
},
"53":{
"label_id":"n01728920",
"cn_main_class":"蛇",
"cn_class_name":"环颈蛇",
"en_class_name":"ringneck snake, ring-necked snake, ring snake"
},
"54":{
"label_id":"n01729322",
"cn_main_class":"蛇",
"cn_class_name":"沙蛇",
"en_class_name":"hognose snake, puff adder, sand viper"
},
"55":{
"label_id":"n01729977",
"cn_main_class":"蛇",
"cn_class_name":"草蛇",
"en_class_name":"green snake, grass snake"
},
"56":{
"label_id":"n01734418",
"cn_main_class":"蛇",
"cn_class_name":"王蛇",
"en_class_name":"king snake, kingsnake"
},
"57":{
"label_id":"n01735189",
"cn_main_class":"蛇",
"cn_class_name":"花纹蛇",
"en_class_name":"garter snake, grass snake"
},
"58":{
"label_id":"n01737021",
"cn_main_class":"蛇",
"cn_class_name":"水蛇",
"en_class_name":"water snake"
},
"59":{
"label_id":"n01739381",
"cn_main_class":"蛇",
"cn_class_name":"藤蛇",
"en_class_name":"vine snake"
},
"60":{
"label_id":"n01740131",
"cn_main_class":"蛇",
"cn_class_name":"夜蛇",
"en_class_name":"night snake, Hypsiglena torquata"
},
"61":{
"label_id":"n01742172",
"cn_main_class":"蛇",
"cn_class_name":"蟒蛇",
"en_class_name":"boa constrictor, Constrictor constrictor"
},
"62":{
"label_id":"n01744401",
"cn_main_class":"蛇",
"cn_class_name":"岩蟒",
"en_class_name":"rock python, rock snake, Python sebae"
},
"63":{
"label_id":"n01748264",
"cn_main_class":"蛇",
"cn_class_name":"眼镜蛇",
"en_class_name":"Indian cobra, Naja naja"
},
"64":{
"label_id":"n01749939",
"cn_main_class":"蛇",
"cn_class_name":"绿色曼巴",
"en_class_name":"green mamba"
},
"65":{
"label_id":"n01751748",
"cn_main_class":"蛇",
"cn_class_name":"海蛇",
"en_class_name":"sea snake"
},
"66":{
"label_id":"n01753488",
"cn_main_class":"蛇",
"cn_class_name":"角蝰",
"en_class_name":"horned viper, cerastes, sand viper, horned asp, Cerastes cornutus"
},
"67":{
"label_id":"n01755581",
"cn_main_class":"蛇",
"cn_class_name":"响尾蛇",
"en_class_name":"diamondback, diamondback rattlesnake, Crotalus adamanteus"
},
"68":{
"label_id":"n01756291",
"cn_main_class":"蛇",
"cn_class_name":"响尾蛇",
"en_class_name":"sidewinder, horned rattlesnake, Crotalus cerastes"
},
"69":{
"label_id":"n01768244",
"cn_main_class":"化石",
"cn_class_name":"三叶虫",
"en_class_name":"trilobite"
},
"70":{
"label_id":"n01770081",
"cn_main_class":"蜘蛛",
"cn_class_name":"长腿蜘蛛",
"en_class_name":"harvestman, daddy longlegs, Phalangium opilio"
},
"71":{
"label_id":"n01770393",
"cn_main_class":"蝎子",
"cn_class_name":"蝎子",
"en_class_name":"scorpion"
},
"72":{
"label_id":"n01773157",
"cn_main_class":"蜘蛛",
"cn_class_name":"黑金色花园蜘蛛",
"en_class_name":"black and gold garden spider, Argiope aurantia"
},
"73":{
"label_id":"n01773549",
"cn_main_class":"蜘蛛",
"cn_class_name":"谷仓蜘蛛",
"en_class_name":"barn spider, Araneus cavaticus"
},
"74":{
"label_id":"n01773797",
"cn_main_class":"蜘蛛",
"cn_class_name":"十字圆蛛",
"en_class_name":"garden spider, Aranea diademata"
},
"75":{
"label_id":"n01774384",
"cn_main_class":"蜘蛛",
"cn_class_name":"黑寡妇蜘蛛",
"en_class_name":"black widow, Latrodectus mactans"
},
"76":{
"label_id":"n01774750",
"cn_main_class":"蜘蛛",
"cn_class_name":"狼蛛",
"en_class_name":"tarantula"
},
"77":{
"label_id":"n01775062",
"cn_main_class":"蜘蛛",
"cn_class_name":"狩猎蜘蛛",
"en_class_name":"wolf spider, hunting spider"
},
"78":{
"label_id":"n01776313",
"cn_main_class":"蜘蛛",
"cn_class_name":"蜘蛛",
"en_class_name":"tick"
},
"79":{
"label_id":"n01784675",
"cn_main_class":"蜈蚣",
"cn_class_name":"蜈蚣",
"en_class_name":"centipede"
},
"80":{
"label_id":"n01795545",
"cn_main_class":"鸟",
"cn_class_name":"黑松鸡",
"en_class_name":"black grouse"
},
"81":{
"label_id":"n01796340",
"cn_main_class":"鸟",
"cn_class_name":"雷鸟",
"en_class_name":"ptarmigan"
},
"82":{
"label_id":"n01797886",
"cn_main_class":"鸟",
"cn_class_name":"凤尾雉",
"en_class_name":"ruffed grouse, partridge, Bonasa umbellus"
},
"83":{
"label_id":"n01798484",
"cn_main_class":"鸟",
"cn_class_name":"草原鸡",
"en_class_name":"prairie chicken, prairie grouse, prairie fowl"
},
"84":{
"label_id":"n01806143",
"cn_main_class":"鸟",
"cn_class_name":"孔雀",
"en_class_name":"peacock"
},
"85":{
"label_id":"n01806567",
"cn_main_class":"鸟",
"cn_class_name":"鹌鹑",
"en_class_name":"quail"
},
"86":{
"label_id":"n01807496",
"cn_main_class":"鸟",
"cn_class_name":"鹧鸪",
"en_class_name":"partridge"
},
"87":{
"label_id":"n01817953",
"cn_main_class":"鸟",
"cn_class_name":"非洲灰鹦鹉",
"en_class_name":"African grey, African gray, Psittacus erithacus"
},
"88":{
"label_id":"n01818515",
"cn_main_class":"鸟",
"cn_class_name":"金刚鹦鹉",
"en_class_name":"macaw"
},
"89":{
"label_id":"n01819313",
"cn_main_class":"鸟",
"cn_class_name":"葵花凤头鹦鹉",
"en_class_name":"sulphur-crested cockatoo, Kakatoe galerita, Cacatua galerita"
},
"90":{
"label_id":"n01820546",
"cn_main_class":"鸟",
"cn_class_name":"吸蜜鹦鹉",
"en_class_name":"lorikeet"
},
"91":{
"label_id":"n01824575",
"cn_main_class":"鸟",
"cn_class_name":"鸦鹃属",
"en_class_name":"coucal"
},
"92":{
"label_id":"n01828970",
"cn_main_class":"鸟",
"cn_class_name":"食蜂鸟",
"en_class_name":"bee eater"
},
"93":{
"label_id":"n01829413",
"cn_main_class":"鸟",
"cn_class_name":"犀鸟",
"en_class_name":"hornbill"
},
"94":{
"label_id":"n01833805",
"cn_main_class":"鸟",
"cn_class_name":"蜂鸟",
"en_class_name":"hummingbird"
},
"95":{
"label_id":"n01843065",
"cn_main_class":"鸟",
"cn_class_name":"食虫鸟",
"en_class_name":"jacamar"
},
"96":{
"label_id":"n01843383",
"cn_main_class":"鸟",
"cn_class_name":"巨嘴鸟",
"en_class_name":"toucan"
},
"97":{
"label_id":"n01847000",
"cn_main_class":"鸭子",
"cn_class_name":"公鸭",
"en_class_name":"drake"
},
"98":{
"label_id":"n01855032",
"cn_main_class":"鹅",
"cn_class_name":"红胸秋沙鸭",
"en_class_name":"red-breasted merganser, Mergus serrator"
},
"99":{
"label_id":"n01855672",
"cn_main_class":"鹅",
"cn_class_name":"鹅",
"en_class_name":"goose"
},
"100":{
"label_id":"n01860187",
"cn_main_class":"鹅",
"cn_class_name":"黑天鹅",
"en_class_name":"black swan, Cygnus atratus"
},
"101":{
"label_id":"n01871265",
"cn_main_class":"象",
"cn_class_name":"长牙象",
"en_class_name":"tusker"
},
"102":{
"label_id":"n01872401",
"cn_main_class":"刺猬",
"cn_class_name":"食蚁兽",
"en_class_name":"echidna, spiny anteater, anteater"
},
"103":{
"label_id":"n01873310",
"cn_main_class":"鸭嘴兽",
"cn_class_name":"鸭嘴兽",
"en_class_name":"platypus, duckbill, duckbilled platypus, duck-billed platypus, Ornithorhynchus anatinus"
},
"104":{
"label_id":"n01877812",
"cn_main_class":"袋鼠",
"cn_class_name":"小袋鼠",
"en_class_name":"wallaby, brush kangaroo"
},
"105":{
"label_id":"n01882714",
"cn_main_class":"考拉",
"cn_class_name":"树袋熊",
"en_class_name":"koala, koala bear, kangaroo bear, native bear, Phascolarctos cinereus"
},
"106":{
"label_id":"n01883070",
"cn_main_class":"土拨鼠",
"cn_class_name":"袋熊",
"en_class_name":"wombat"
},
"107":{
"label_id":"n01910747",
"cn_main_class":"水母",
"cn_class_name":"水母",
"en_class_name":"jellyfish"
},
"108":{
"label_id":"n01914609",
"cn_main_class":"珊瑚",
"cn_class_name":"海葵",
"en_class_name":"sea anemone, anemone"
},
"109":{
"label_id":"n01917289",
"cn_main_class":"珊瑚",
"cn_class_name":"脑珊瑚",
"en_class_name":"brain coral"
},
"110":{
"label_id":"n01924916",
"cn_main_class":"海洋生物",
"cn_class_name":"扁形虫",
"en_class_name":"flatworm, platyhelminth"
},
"111":{
"label_id":"n01930112",
"cn_main_class":"海蛇",
"cn_class_name":"线虫",
"en_class_name":"nematode, nematode worm, roundworm"
},
"112":{
"label_id":"n01943899",
"cn_main_class":"海螺",
"cn_class_name":"海螺",
"en_class_name":"conch"
},
"113":{
"label_id":"n01944390",
"cn_main_class":"蜗牛",
"cn_class_name":"蜗牛",
"en_class_name":"snail"
},
"114":{
"label_id":"n01945685",
"cn_main_class":"蜗牛",
"cn_class_name":"鼻涕虫",
"en_class_name":"slug"
},
"115":{
"label_id":"n01950731",
"cn_main_class":"海洋生物",
"cn_class_name":"海蛞蝓",
"en_class_name":"sea slug, nudibranch"
},
"116":{
"label_id":"n01955084",
"cn_main_class":"海洋生物",
"cn_class_name":"石鳖",
"en_class_name":"chiton, coat-of-mail shell, sea cradle, polyplacophore"
},
"117":{
"label_id":"n01968897",
"cn_main_class":"海螺",
"cn_class_name":"鹦鹉螺",
"en_class_name":"chambered nautilus, pearly nautilus, nautilus"
},
"118":{
"label_id":"n01978287",
"cn_main_class":"螃蟹",
"cn_class_name":"岩蟹",
"en_class_name":"Dungeness crab, Cancer magister"
},
"119":{
"label_id":"n01978455",
"cn_main_class":"螃蟹",
"cn_class_name":"岩蟹",
"en_class_name":"rock crab, Cancer irroratus"
},
"120":{
"label_id":"n01980166",
"cn_main_class":"螃蟹",
"cn_class_name":"招潮蟹",
"en_class_name":"fiddler crab"
},
"121":{
"label_id":"n01981276",
"cn_main_class":"螃蟹",
"cn_class_name":"帝王蟹",
"en_class_name":"king crab, Alaska crab, Alaskan king crab, Alaska king crab, Paralithodes camtschatica"
},
"122":{
"label_id":"n01983481",
"cn_main_class":"龙虾",
"cn_class_name":"美洲龙虾",
"en_class_name":"American lobster, Northern lobster, Maine lobster, Homarus americanus"
},
"123":{
"label_id":"n01984695",
"cn_main_class":"龙虾",
"cn_class_name":"龙虾",
"en_class_name":"spiny lobster, langouste, rock lobster, crawfish, crayfish, sea crawfish"
},
"124":{
"label_id":"n01985128",
"cn_main_class":"龙虾",
"cn_class_name":"小龙虾",
"en_class_name":"crayfish, crawfish, crawdad, crawdaddy"
},
"125":{
"label_id":"n01986214",
"cn_main_class":"蟹",
"cn_class_name":"寄居蟹",
"en_class_name":"hermit crab"
},
"126":{
"label_id":"n01990800",
"cn_main_class":"海洋生物",
"cn_class_name":"等足目动物",
"en_class_name":"isopod"
},
"127":{
"label_id":"n02002556",
"cn_main_class":"鸟",
"cn_class_name":"白鹳",
"en_class_name":"white stork, Ciconia ciconia"
},
"128":{
"label_id":"n02002724",
"cn_main_class":"鸟",
"cn_class_name":"黑鹳",
"en_class_name":"black stork, Ciconia nigra"
},
"129":{
"label_id":"n02006656",
"cn_main_class":"鸟",
"cn_class_name":"琵鹭",
"en_class_name":"spoonbill"
},
"130":{
"label_id":"n02007558",
"cn_main_class":"鸟",
"cn_class_name":"火烈鸟",
"en_class_name":"flamingo"
},
"131":{
"label_id":"n02009229",
"cn_main_class":"鸟",
"cn_class_name":"小蓝鹭",
"en_class_name":"little blue heron, Egretta caerulea"
},
"132":{
"label_id":"n02009912",
"cn_main_class":"鸟",
"cn_class_name":"大白鹭",
"en_class_name":"American egret, great white heron, Egretta albus"
},
"133":{
"label_id":"n02011460",
"cn_main_class":"鸟",
"cn_class_name":"麻鸦",
"en_class_name":"bittern"
},
"134":{
"label_id":"n02012849",
"cn_main_class":"鸟",
"cn_class_name":"鹤",
"en_class_name":"crane"
},
"135":{
"label_id":"n02013706",
"cn_main_class":"鸟",
"cn_class_name":"秧鹤",
"en_class_name":"limpkin, Aramus pictus"
},
"136":{
"label_id":"n02017213",
"cn_main_class":"鸟",
"cn_class_name":"紫水鸡",
"en_class_name":"European gallinule, Porphyrio porphyrio"
},
"137":{
"label_id":"n02018207",
"cn_main_class":"鸟",
"cn_class_name":"美国白鹭",
"en_class_name":"American coot, marsh hen, mud hen, water hen, Fulica americana"
},
"138":{
"label_id":"n02018795",
"cn_main_class":"鸟",
"cn_class_name":"大鸨",
"en_class_name":"bustard"
},
"139":{
"label_id":"n02025239",
"cn_main_class":"鸟",
"cn_class_name":"翻石鹬",
"en_class_name":"ruddy turnstone, Arenaria interpres"
},
"140":{
"label_id":"n02027492",
"cn_main_class":"鸟",
"cn_class_name":"红背鹬",
"en_class_name":"red-backed sandpiper, dunlin, Erolia alpina"
},
"141":{
"label_id":"n02028035",
"cn_main_class":"鸟",
"cn_class_name":"红脚鹬",
"en_class_name":"redshank, Tringa totanus"
},
"142":{
"label_id":"n02033041",
"cn_main_class":"鸟",
"cn_class_name":"半蹼鹬",
"en_class_name":"dowitcher"
},
"143":{
"label_id":"n02037110",
"cn_main_class":"鸟",
"cn_class_name":"蛎鹬",
"en_class_name":"oystercatcher, oyster catcher"
},
"144":{
"label_id":"n02051845",
"cn_main_class":"鸟",
"cn_class_name":"鹈鹕",
"en_class_name":"pelican"
},
"145":{
"label_id":"n02056570",
"cn_main_class":"企鹅",
"cn_class_name":"企鹅王",
"en_class_name":"king penguin, Aptenodytes patagonica"
},
"146":{
"label_id":"n02058221",
"cn_main_class":"鸟",
"cn_class_name":"信天翁",
"en_class_name":"albatross, mollymawk"
},
"147":{
"label_id":"n02066245",
"cn_main_class":"鱼",
"cn_class_name":"灰鲸",
"en_class_name":"grey whale, gray whale, devilfish, Eschrichtius gibbosus, Eschrichtius robustus"
},
"148":{
"label_id":"n02071294",
"cn_main_class":"鱼",
"cn_class_name":"虎鲸",
"en_class_name":"killer whale, killer, orca, grampus, sea wolf, Orcinus orca"
},
"149":{
"label_id":"n02074367",
"cn_main_class":"海象",
"cn_class_name":"海牛",
"en_class_name":"dugong, Dugong dugon"
},
"150":{
"label_id":"n02077923",
"cn_main_class":"海狮",
"cn_class_name":"海狮",
"en_class_name":"sea lion"
},
"151":{
"label_id":"n02085620",
"cn_main_class":"狗",
"cn_class_name":"吉娃娃",
"en_class_name":"Chihuahua"
},
"152":{
"label_id":"n02085782",
"cn_main_class":"狗",
"cn_class_name":"日本猎犬",
"en_class_name":"Japanese spaniel"
},
"153":{
"label_id":"n02085936",
"cn_main_class":"狗",
"cn_class_name":"马耳他狗",
"en_class_name":"Maltese dog, Maltese terrier, Maltese"
},
"154":{
"label_id":"n02086079",
"cn_main_class":"狗",
"cn_class_name":"哈巴狗",
"en_class_name":"Pekinese, Pekingese, Peke"
},
"155":{
"label_id":"n02086240",
"cn_main_class":"狗",
"cn_class_name":"狮子狗",
"en_class_name":"Shih-Tzu"
},
"156":{
"label_id":"n02086646",
"cn_main_class":"狗",
"cn_class_name":"布伦海姆猎犬",
"en_class_name":"Blenheim spaniel"
},
"157":{
"label_id":"n02086910",
"cn_main_class":"狗",
"cn_class_name":"蝶耳狗",
"en_class_name":"papillon"
},
"158":{
"label_id":"n02087046",
"cn_main_class":"狗",
"cn_class_name":"玩具梗",
"en_class_name":"toy terrier"
},
"159":{
"label_id":"n02087394",
"cn_main_class":"狗",
"cn_class_name":"罗得西亚脊背犬",
"en_class_name":"Rhodesian ridgeback"
},
"160":{
"label_id":"n02088094",
"cn_main_class":"狗",
"cn_class_name":"阿富汗猎犬",
"en_class_name":"Afghan hound, Afghan"
},
"161":{
"label_id":"n02088238",
"cn_main_class":"狗",
"cn_class_name":"矮脚长耳猎犬",
"en_class_name":"basset, basset hound"
},
"162":{
"label_id":"n02088364",
"cn_main_class":"狗",
"cn_class_name":"小猎犬",
"en_class_name":"beagle"
},
"163":{
"label_id":"n02088466",
"cn_main_class":"狗",
"cn_class_name":"侦探犬",
"en_class_name":"bloodhound, sleuthhound"
},
"164":{
"label_id":"n02088632",
"cn_main_class":"狗",
"cn_class_name":"布鲁克浣熊猎犬",
"en_class_name":"bluetick"
},
"165":{
"label_id":"n02089078",
"cn_main_class":"狗",
"cn_class_name":"黑褐猎浣熊犬",
"en_class_name":"black-and-tan coonhound"
},
"166":{
"label_id":"n02089867",
"cn_main_class":"狗",
"cn_class_name":"沃克猎犬",
"en_class_name":"Walker hound, Walker foxhound"
},
"167":{
"label_id":"n02089973",
"cn_main_class":"狗",
"cn_class_name":"英国猎狐犬",
"en_class_name":"English foxhound"
},
"168":{
"label_id":"n02090379",
"cn_main_class":"狗",
"cn_class_name":"美洲赤狗",
"en_class_name":"redbone"
},
"169":{
"label_id":"n02090622",
"cn_main_class":"狗",
"cn_class_name":"俄国狼狗",
"en_class_name":"borzoi, Russian wolfhound"
},
"170":{
"label_id":"n02090721",
"cn_main_class":"狗",
"cn_class_name":"爱尔兰狼狗",
"en_class_name":"Irish wolfhound"
},
"171":{
"label_id":"n02091032",
"cn_main_class":"狗",
"cn_class_name":"意大利灵缇犬",
"en_class_name":"Italian greyhound"
},
"172":{
"label_id":"n02091134",
"cn_main_class":"狗",
"cn_class_name":"惠比特犬",
"en_class_name":"whippet"
},
"173":{
"label_id":"n02091244",
"cn_main_class":"狗",
"cn_class_name":"依比沙猎犬",
"en_class_name":"Ibizan hound, Ibizan Podenco"
},
"174":{
"label_id":"n02091467",
"cn_main_class":"狗",
"cn_class_name":"挪威猎麋",
"en_class_name":"Norwegian elkhound, elkhound"
},
"175":{
"label_id":"n02091635",
"cn_main_class":"狗",
"cn_class_name":"水獭猎犬",
"en_class_name":"otterhound, otter hound"
},
"176":{
"label_id":"n02091831",
"cn_main_class":"狗",
"cn_class_name":"萨路基猎犬",
"en_class_name":"Saluki, gazelle hound"
},
"177":{
"label_id":"n02092002",
"cn_main_class":"狗",
"cn_class_name":"鹿角犬",
"en_class_name":"Scottish deerhound, deerhound"
},
"178":{
"label_id":"n02092339",
"cn_main_class":"狗",
"cn_class_name":"威马拉纳",
"en_class_name":"Weimaraner"
},
"179":{
"label_id":"n02093256",
"cn_main_class":"狗",
"cn_class_name":"斯塔福德郡斗牛犬",
"en_class_name":"Staffordshire bullterrier, Staffordshire bull terrier"
},
"180":{
"label_id":"n02093428",
"cn_main_class":"狗",
"cn_class_name":"斯塔福德郡梗",
"en_class_name":"American Staffordshire terrier, Staffordshire terrier, American pit bull terrier, pit bull terrier"
},
"181":{
"label_id":"n02093647",
"cn_main_class":"狗",
"cn_class_name":"贝灵顿梗",
"en_class_name":"Bedlington terrier"
},
"182":{
"label_id":"n02093754",
"cn_main_class":"狗",
"cn_class_name":"边境梗",
"en_class_name":"Border terrier"
},
"183":{
"label_id":"n02093859",
"cn_main_class":"狗",
"cn_class_name":"克里蓝梗",
"en_class_name":"Kerry blue terrier"
},
"184":{
"label_id":"n02093991",
"cn_main_class":"狗",
"cn_class_name":"爱尔兰梗",
"en_class_name":"Irish terrier"
},
"185":{
"label_id":"n02094114",
"cn_main_class":"狗",
"cn_class_name":"诺福克梗",
"en_class_name":"Norfolk terrier"
},
"186":{
"label_id":"n02094258",
"cn_main_class":"狗",
"cn_class_name":"诺维奇梗",
"en_class_name":"Norwich terrier"
},
"187":{
"label_id":"n02094433",
"cn_main_class":"狗",
"cn_class_name":"约克郡梗",
"en_class_name":"Yorkshire terrier"
},
"188":{
"label_id":"n02095314",
"cn_main_class":"狗",
"cn_class_name":"丝毛狐狸梗",
"en_class_name":"wire-haired fox terrier"
},
"189":{
"label_id":"n02095570",
"cn_main_class":"狗",
"cn_class_name":"莱克兰梗",
"en_class_name":"Lakeland terrier"
},
"190":{
"label_id":"n02095889",
"cn_main_class":"狗",
"cn_class_name":"西里汉梗",
"en_class_name":"Sealyham terrier, Sealyham"
},
"191":{
"label_id":"n02096051",
"cn_main_class":"狗",
"cn_class_name":"艾尔谷犬",
"en_class_name":"Airedale, Airedale terrier"
},
"192":{
"label_id":"n02096177",
"cn_main_class":"狗",
"cn_class_name":"凯恩狗",
"en_class_name":"cairn, cairn terrier"
},
"193":{
"label_id":"n02096294",
"cn_main_class":"狗",
"cn_class_name":"澳大利亚梗",
"en_class_name":"Australian terrier"
},
"194":{
"label_id":"n02096437",
"cn_main_class":"狗",
"cn_class_name":"英国小猎犬",
"en_class_name":"Dandie Dinmont, Dandie Dinmont terrier"
},
"195":{
"label_id":"n02096585",
"cn_main_class":"狗",
"cn_class_name":"波士顿狗",
"en_class_name":"Boston bull, Boston terrier"
},
"196":{
"label_id":"n02097047",
"cn_main_class":"狗",
"cn_class_name":"迷你雪纳瑞",
"en_class_name":"miniature schnauzer"
},
"197":{
"label_id":"n02097130",
"cn_main_class":"狗",
"cn_class_name":"巨型雪纳瑞",
"en_class_name":"giant schnauzer"
},
"198":{
"label_id":"n02097209",
"cn_main_class":"狗",
"cn_class_name":"标准雪纳瑞",
"en_class_name":"standard schnauzer"
},
"199":{
"label_id":"n02097298",
"cn_main_class":"狗",
"cn_class_name":"苏格兰梗",
"en_class_name":"Scotch terrier, Scottish terrier, Scottie"
},
"200":{
"label_id":"n02097474",
"cn_main_class":"狗",
"cn_class_name":"藏梗",
"en_class_name":"Tibetan terrier, chrysanthemum dog"
},
"201":{
"label_id":"n02097658",
"cn_main_class":"狗",
"cn_class_name":"丝质梗",
"en_class_name":"silky terrier, Sydney silky"
},
"202":{
"label_id":"n02098105",
"cn_main_class":"狗",
"cn_class_name":"爱尔兰软毛挭",
"en_class_name":"soft-coated wheaten terrier"
},
"203":{
"label_id":"n02098286",
"cn_main_class":"狗",
"cn_class_name":"西高地白梗",
"en_class_name":"West Highland white terrier"
},
"204":{
"label_id":"n02098413",
"cn_main_class":"狗",
"cn_class_name":"拉萨",
"en_class_name":"Lhasa, Lhasa apso"
},
"205":{
"label_id":"n02099267",
"cn_main_class":"狗",
"cn_class_name":"平毛寻回犬",
"en_class_name":"flat-coated retriever"
},
"206":{
"label_id":"n02099429",
"cn_main_class":"狗",
"cn_class_name":"卷毛猎犬",
"en_class_name":"curly-coated retriever"
},
"207":{
"label_id":"n02099601",
"cn_main_class":"狗",
"cn_class_name":"金毛猎犬",
"en_class_name":"golden retriever"
},
"208":{
"label_id":"n02099712",
"cn_main_class":"狗",
"cn_class_name":"拉布拉多猎犬",
"en_class_name":"Labrador retriever"
},
"209":{
"label_id":"n02099849",
"cn_main_class":"狗",
"cn_class_name":"切萨皮克湾寻回犬",
"en_class_name":"Chesapeake Bay retriever"
},
"210":{
"label_id":"n02100236",
"cn_main_class":"狗",
"cn_class_name":"德国短毛指示犬",
"en_class_name":"German short-haired pointer"
},
"211":{
"label_id":"n02100583",
"cn_main_class":"狗",
"cn_class_name":"维希拉猎犬",
"en_class_name":"vizsla, Hungarian pointer"
},
"212":{
"label_id":"n02100735",
"cn_main_class":"狗",
"cn_class_name":"英国赛特犬",
"en_class_name":"English setter"
},
"213":{
"label_id":"n02100877",
"cn_main_class":"狗",
"cn_class_name":"爱尔兰猎犬",
"en_class_name":"Irish setter, red setter"
},
"214":{
"label_id":"n02101006",
"cn_main_class":"狗",
"cn_class_name":"戈登塞特犬",
"en_class_name":"Gordon setter"
},
"215":{
"label_id":"n02101388",
"cn_main_class":"狗",
"cn_class_name":"布列塔尼猎犬",
"en_class_name":"Brittany spaniel"
},
"216":{
"label_id":"n02101556",
"cn_main_class":"狗",
"cn_class_name":"克伦伯猎犬",
"en_class_name":"clumber, clumber spaniel"
},
"217":{
"label_id":"n02102040",
"cn_main_class":"狗",
"cn_class_name":"英国史宾格犬",
"en_class_name":"English springer, English springer spaniel"
},
"218":{
"label_id":"n02102177",
"cn_main_class":"狗",
"cn_class_name":"威尔斯激飞猎犬",
"en_class_name":"Welsh springer spaniel"
},
"219":{
"label_id":"n02102318",
"cn_main_class":"狗",
"cn_class_name":"英国可卡犬",
"en_class_name":"cocker spaniel, English cocker spaniel, cocker"
},
"220":{
"label_id":"n02102480",
"cn_main_class":"狗",
"cn_class_name":"苏塞克斯猎犬",
"en_class_name":"Sussex spaniel"
},
"221":{
"label_id":"n02102973",
"cn_main_class":"狗",
"cn_class_name":"爱尔兰水猎犬",
"en_class_name":"Irish water spaniel"
},
"222":{
"label_id":"n02104029",
"cn_main_class":"狗",
"cn_class_name":"白警犬",
"en_class_name":"kuvasz"
},
"223":{
"label_id":"n02104365",
"cn_main_class":"狗",
"cn_class_name":"舒伯齐犬",
"en_class_name":"schipperke"
},
"224":{
"label_id":"n02105056",
"cn_main_class":"狗",
"cn_class_name":"比利时牧羊狗",
"en_class_name":"groenendael"
},
"225":{
"label_id":"n02105162",
"cn_main_class":"狗",
"cn_class_name":"玛伦牧羊犬",
"en_class_name":"malinois"
},
"226":{
"label_id":"n02105251",
"cn_main_class":"狗",
"cn_class_name":"伯瑞犬",
"en_class_name":"briard"
},
"227":{
"label_id":"n02105412",
"cn_main_class":"狗",
"cn_class_name":"澳大利亚护羊犬",
"en_class_name":"kelpie"
},
"228":{
"label_id":"n02105505",
"cn_main_class":"狗",
"cn_class_name":"匈牙利种牧羊犬",
"en_class_name":"komondor"
},
"229":{
"label_id":"n02105641",
"cn_main_class":"狗",
"cn_class_name":"短尾牧羊犬",
"en_class_name":"Old English sheepdog, bobtail"
},
"230":{
"label_id":"n02105855",
"cn_main_class":"狗",
"cn_class_name":"喜乐蒂牧羊犬",
"en_class_name":"Shetland sheepdog, Shetland sheep dog, Shetland"
},
"231":{
"label_id":"n02106030",
"cn_main_class":"狗",
"cn_class_name":"柯利牧羊犬",
"en_class_name":"collie"
},
"232":{
"label_id":"n02106166",
"cn_main_class":"狗",
"cn_class_name":"边境牧羊犬",
"en_class_name":"Border collie"
},
"233":{
"label_id":"n02106382",
"cn_main_class":"狗",
"cn_class_name":"法兰德斯牧牛狗",
"en_class_name":"Bouvier des Flandres, Bouviers des Flandres"
},
"234":{
"label_id":"n02106550",
"cn_main_class":"狗",
"cn_class_name":"罗纳威犬",
"en_class_name":"Rottweiler"
},
"235":{
"label_id":"n02106662",
"cn_main_class":"狗",
"cn_class_name":"德国牧羊犬",
"en_class_name":"German shepherd, German shepherd dog, German police dog, alsatian"
},
"236":{
"label_id":"n02107142",
"cn_main_class":"狗",
"cn_class_name":"杜宾犬",
"en_class_name":"Doberman, Doberman pinscher"
},
"237":{
"label_id":"n02107312",
"cn_main_class":"狗",
"cn_class_name":"迷你杜宾犬",
"en_class_name":"miniature pinscher"
},
"238":{
"label_id":"n02107574",
"cn_main_class":"狗",
"cn_class_name":"大瑞士山地犬",
"en_class_name":"Greater Swiss Mountain dog"
},
"239":{
"label_id":"n02107683",
"cn_main_class":"狗",
"cn_class_name":"伯尔尼山狗",
"en_class_name":"Bernese mountain dog"
},
"240":{
"label_id":"n02107908",
"cn_main_class":"狗",
"cn_class_name":"阿彭策勒",
"en_class_name":"Appenzeller"
},
"241":{
"label_id":"n02108000",
"cn_main_class":"狗",
"cn_class_name":"恩特布克犬",
"en_class_name":"EntleBucher"
},
"242":{
"label_id":"n02108089",
"cn_main_class":"狗",
"cn_class_name":"拳狮犬",
"en_class_name":"boxer"
},
"243":{
"label_id":"n02108422",
"cn_main_class":"狗",
"cn_class_name":"公牛獒",
"en_class_name":"bull mastiff"
},
"244":{
"label_id":"n02108551",
"cn_main_class":"狗",
"cn_class_name":"藏獒",
"en_class_name":"Tibetan mastiff"
},
"245":{
"label_id":"n02108915",
"cn_main_class":"狗",
"cn_class_name":"法国斗牛犬",
"en_class_name":"French bulldog"
},
"246":{
"label_id":"n02109047",
"cn_main_class":"狗",
"cn_class_name":"大丹犬",
"en_class_name":"Great Dane"
},
"247":{
"label_id":"n02109525",
"cn_main_class":"狗",
"cn_class_name":"圣伯纳德狗",
"en_class_name":"Saint Bernard, St Bernard"
},
"248":{
"label_id":"n02109961",
"cn_main_class":"狗",
"cn_class_name":"哈士奇",
"en_class_name":"Eskimo dog, husky"
},
"249":{
"label_id":"n02110063",
"cn_main_class":"狗",
"cn_class_name":"阿拉斯加雪橇犬",
"en_class_name":"malamute, malemute, Alaskan malamute"
},
"250":{
"label_id":"n02110185",
"cn_main_class":"狗",
"cn_class_name":"西伯利亚哈士奇",
"en_class_name":"Siberian husky"
},
"251":{
"label_id":"n02110341",
"cn_main_class":"狗",
"cn_class_name":"达尔马西亚狗",
"en_class_name":"dalmatian, coach dog, carriage dog"
},
"252":{
"label_id":"n02110627",
"cn_main_class":"狗",
"cn_class_name":"猴绠",
"en_class_name":"affenpinscher, monkey pinscher, monkey dog"
},
"253":{
"label_id":"n02110806",
"cn_main_class":"狗",
"cn_class_name":"巴辛吉",
"en_class_name":"basenji"
},
"254":{
"label_id":"n02110958",
"cn_main_class":"狗",
"cn_class_name":"哈巴狗",
"en_class_name":"pug, pug-dog"
},
"255":{
"label_id":"n02111129",
"cn_main_class":"狗",
"cn_class_name":"莱昂贝格犬",
"en_class_name":"Leonberg"
},
"256":{
"label_id":"n02111277",
"cn_main_class":"狗",
"cn_class_name":"纽芬兰犬",
"en_class_name":"Newfoundland, Newfoundland dog"
},
"257":{
"label_id":"n02111500",
"cn_main_class":"狗",
"cn_class_name":"大白熊犬",
"en_class_name":"Great Pyrenees"
},
"258":{
"label_id":"n02111889",
"cn_main_class":"狗",
"cn_class_name":"萨莫耶德犬",
"en_class_name":"Samoyed, Samoyede"
},
"259":{
"label_id":"n02112018",
"cn_main_class":"狗",
"cn_class_name":"松鼠犬",
"en_class_name":"Pomeranian"
},
"260":{
"label_id":"n02112137",
"cn_main_class":"狗",
"cn_class_name":"松狮狗",
"en_class_name":"chow, chow chow"
},
"261":{
"label_id":"n02112350",
"cn_main_class":"狗",
"cn_class_name":"荷兰卷尾狮毛狗",
"en_class_name":"keeshond"
},
"262":{
"label_id":"n02112706",
"cn_main_class":"狗",
"cn_class_name":"布拉班肯格里芬",
"en_class_name":"Brabancon griffon"
},
"263":{
"label_id":"n02113023",
"cn_main_class":"狗",
"cn_class_name":"彭布罗克威尔士柯基犬",
"en_class_name":"Pembroke, Pembroke Welsh corgi"
},
"264":{
"label_id":"n02113186",
"cn_main_class":"狗",
"cn_class_name":"卡迪根威尔士柯基犬",
"en_class_name":"Cardigan, Cardigan Welsh corgi"
},
"265":{
"label_id":"n02113624",
"cn_main_class":"狗",
"cn_class_name":"玩具贵宾犬",
"en_class_name":"toy poodle"
},
"266":{
"label_id":"n02113712",
"cn_main_class":"狗",
"cn_class_name":"迷你贵宾犬",
"en_class_name":"miniature poodle"
},
"267":{
"label_id":"n02113799",
"cn_main_class":"狗",
"cn_class_name":"标准贵宾犬",
"en_class_name":"standard poodle"
},
"268":{
"label_id":"n02113978",
"cn_main_class":"狗",
"cn_class_name":"墨西哥无毛犬",
"en_class_name":"Mexican hairless"
},
"269":{
"label_id":"n02114367",
"cn_main_class":"狼",
"cn_class_name":"灰狼",
"en_class_name":"timber wolf, grey wolf, gray wolf, Canis lupus"
},
"270":{
"label_id":"n02114548",
"cn_main_class":"狼",
"cn_class_name":"北极狼",
"en_class_name":"white wolf, Arctic wolf, Canis lupus tundrarum"
},
"271":{
"label_id":"n02114712",
"cn_main_class":"狼",
"cn_class_name":"红狼",
"en_class_name":"red wolf, maned wolf, Canis rufus, Canis niger"
},
"272":{
"label_id":"n02114855",
"cn_main_class":"狼",
"cn_class_name":"草原狼",
"en_class_name":"coyote, prairie wolf, brush wolf, Canis latrans"
},
"273":{
"label_id":"n02115641",
"cn_main_class":"狼",
"cn_class_name":"澳洲野犬",
"en_class_name":"dingo, warrigal, warragal, Canis dingo"
},
"274":{
"label_id":"n02115913",
"cn_main_class":"狼",
"cn_class_name":"豺",
"en_class_name":"dhole, Cuon alpinus"
},
"275":{
"label_id":"n02116738",
"cn_main_class":"狼",
"cn_class_name":"鬣狗",
"en_class_name":"African hunting dog, hyena dog, Cape hunting dog, Lycaon pictus"
},
"276":{
"label_id":"n02117135",
"cn_main_class":"狼",
"cn_class_name":"鬣狗",
"en_class_name":"hyena, hyaena"
},
"277":{
"label_id":"n02119022",
"cn_main_class":"狐",
"cn_class_name":"红狐",
"en_class_name":"red fox, Vulpes vulpes"
},
"278":{
"label_id":"n02119789",
"cn_main_class":"狐",
"cn_class_name":"敏狐",
"en_class_name":"kit fox, Vulpes macrotis"
},
"279":{
"label_id":"n02120079",
"cn_main_class":"狐",
"cn_class_name":"北极狐",
"en_class_name":"Arctic fox, white fox, Alopex lagopus"
},
"280":{
"label_id":"n02120505",
"cn_main_class":"狐",
"cn_class_name":"灰狐",
"en_class_name":"grey fox, gray fox, Urocyon cinereoargenteus"
},
"281":{
"label_id":"n02123045",
"cn_main_class":"猫",
"cn_class_name":"斑纹猫",
"en_class_name":"tabby, tabby cat"
},
"282":{
"label_id":"n02123159",
"cn_main_class":"猫",
"cn_class_name":"虎猫",
"en_class_name":"tiger cat"
},
"283":{
"label_id":"n02123394",
"cn_main_class":"猫",
"cn_class_name":"波斯猫",
"en_class_name":"Persian cat"
},
"284":{
"label_id":"n02123597",
"cn_main_class":"猫",
"cn_class_name":"暹罗猫",
"en_class_name":"Siamese cat, Siamese"
},
"285":{
"label_id":"n02124075",
"cn_main_class":"猫",
"cn_class_name":"埃及猫",
"en_class_name":"Egyptian cat"
},
"286":{
"label_id":"n02125311",
"cn_main_class":"猫",
"cn_class_name":"美洲豹",
"en_class_name":"cougar, puma, catamount, mountain lion, painter, panther, Felis concolor"
},
"287":{
"label_id":"n02127052",
"cn_main_class":"猫",
"cn_class_name":"猞猁",
"en_class_name":"lynx, catamount"
},
"288":{
"label_id":"n02128385",
"cn_main_class":"豹",
"cn_class_name":"豹子",
"en_class_name":"leopard, Panthera pardus"
},
"289":{
"label_id":"n02128757",
"cn_main_class":"豹",
"cn_class_name":"雪豹",
"en_class_name":"snow leopard, ounce, Panthera uncia"
},
"290":{
"label_id":"n02128925",
"cn_main_class":"豹",
"cn_class_name":"美洲豹",
"en_class_name":"jaguar, panther, Panthera onca, Felis onca"
},
"291":{
"label_id":"n02129165",
"cn_main_class":"狮",
"cn_class_name":"狮子",
"en_class_name":"lion, king of beasts, Panthera leo"
},
"292":{
"label_id":"n02129604",
"cn_main_class":"虎",
"cn_class_name":"老虎",
"en_class_name":"tiger, Panthera tigris"
},
"293":{
"label_id":"n02130308",
"cn_main_class":"豹",
"cn_class_name":"猎豹",
"en_class_name":"cheetah, chetah, Acinonyx jubatus"
},
"294":{
"label_id":"n02132136",
"cn_main_class":"熊",
"cn_class_name":"棕熊",
"en_class_name":"brown bear, bruin, Ursus arctos"
},
"295":{
"label_id":"n02133161",
"cn_main_class":"熊",
"cn_class_name":"黑熊",
"en_class_name":"American black bear, black bear, Ursus americanus, Euarctos americanus"
},
"296":{
"label_id":"n02134084",
"cn_main_class":"熊",
"cn_class_name":"北极熊",
"en_class_name":"ice bear, polar bear, Ursus Maritimus, Thalarctos maritimus"
},
"297":{
"label_id":"n02134418",
"cn_main_class":"熊",
"cn_class_name":"懒熊",
"en_class_name":"sloth bear, Melursus ursinus, Ursus ursinus"
},
"298":{
"label_id":"n02137549",
"cn_main_class":"猫鼬",
"cn_class_name":"猫鼬",
"en_class_name":"mongoose"
},
"299":{
"label_id":"n02138441",
"cn_main_class":"猫鼬",
"cn_class_name":"猫鼬",
"en_class_name":"meerkat, mierkat"
},
"300":{
"label_id":"n02165105",
"cn_main_class":"昆虫",
"cn_class_name":"虎甲虫",
"en_class_name":"tiger beetle"
},
"301":{
"label_id":"n02165456",
"cn_main_class":"昆虫",
"cn_class_name":"瓢虫",
"en_class_name":"ladybug, ladybeetle, lady beetle, ladybird, ladybird beetle"
},
"302":{
"label_id":"n02167151",
"cn_main_class":"昆虫",
"cn_class_name":"地甲虫",
"en_class_name":"ground beetle, carabid beetle"
},
"303":{
"label_id":"n02168699",
"cn_main_class":"昆虫",
"cn_class_name":"天牛",
"en_class_name":"long-horned beetle, longicorn, longicorn beetle"
},
"304":{
"label_id":"n02169497",
"cn_main_class":"昆虫",
"cn_class_name":"叶甲虫",
"en_class_name":"leaf beetle, chrysomelid"
},
"305":{
"label_id":"n02172182",
"cn_main_class":"昆虫",
"cn_class_name":"粪甲虫",
"en_class_name":"dung beetle"
},
"306":{
"label_id":"n02174001",
"cn_main_class":"昆虫",
"cn_class_name":"犀牛甲虫",
"en_class_name":"rhinoceros beetle"
},
"307":{
"label_id":"n02177972",
"cn_main_class":"昆虫",
"cn_class_name":"象鼻虫",
"en_class_name":"weevil"
},
"308":{
"label_id":"n02190166",
"cn_main_class":"昆虫",
"cn_class_name":"苍蝇",
"en_class_name":"fly"
},
"309":{
"label_id":"n02206856",
"cn_main_class":"昆虫",
"cn_class_name":"蜜蜂",
"en_class_name":"bee"
},
"310":{
"label_id":"n02219486",
"cn_main_class":"昆虫",
"cn_class_name":"蚂蚁",
"en_class_name":"ant, emmet, pismire"
},
"311":{
"label_id":"n02226429",
"cn_main_class":"昆虫",
"cn_class_name":"蚱蜢",
"en_class_name":"grasshopper, hopper"
},
"312":{
"label_id":"n02229544",
"cn_main_class":"昆虫",
"cn_class_name":"蟋蟀",
"en_class_name":"cricket"
},
"313":{
"label_id":"n02231487",
"cn_main_class":"昆虫",
"cn_class_name":"竹节虫",
"en_class_name":"walking stick, walkingstick, stick insect"
},
"314":{
"label_id":"n02233338",
"cn_main_class":"昆虫",
"cn_class_name":"蟑螂",
"en_class_name":"cockroach, roach"
},
"315":{
"label_id":"n02236044",
"cn_main_class":"昆虫",
"cn_class_name":"螳螂",
"en_class_name":"mantis, mantid"
},
"316":{
"label_id":"n02256656",
"cn_main_class":"昆虫",
"cn_class_name":"蝉",
"en_class_name":"cicada, cicala"
},
"317":{
"label_id":"n02259212",
"cn_main_class":"昆虫",
"cn_class_name":"叶蝉",
"en_class_name":"leafhopper"
},
"318":{
"label_id":"n02264363",
"cn_main_class":"昆虫",
"cn_class_name":"草蜻蛉",
"en_class_name":"lacewing, lacewing fly"
},
"319":{
"label_id":"n02268443",
"cn_main_class":"蜻蜓",
"cn_class_name":"蜻蜓",
"en_class_name":"dragonfly, darning needle, devil's darning needle, sewing needle, snake feeder, snake doctor, mosquito hawk, skeeter hawk"
},
"320":{
"label_id":"n02268853",
"cn_main_class":"蜻蜓",
"cn_class_name":"豆娘",
"en_class_name":"damselfly"
},
"321":{
"label_id":"n02276258",
"cn_main_class":"蝴蝶",
"cn_class_name":"海军上将蛱蝶",
"en_class_name":"admiral"
},
"322":{
"label_id":"n02277742",
"cn_main_class":"蝴蝶",
"cn_class_name":"铃铛",
"en_class_name":"ringlet, ringlet butterfly"
},
"323":{
"label_id":"n02279972",
"cn_main_class":"蝴蝶",
"cn_class_name":"帝王蝶",
"en_class_name":"monarch, monarch butterfly, milkweed butterfly, Danaus plexippus"
},
"324":{
"label_id":"n02280649",
"cn_main_class":"蝴蝶",
"cn_class_name":"纹白蝶",
"en_class_name":"cabbage butterfly"
},
"325":{
"label_id":"n02281406",
"cn_main_class":"蝴蝶",
"cn_class_name":"白蝴蝶",
"en_class_name":"sulphur butterfly, sulfur butterfly"
},
"326":{
"label_id":"n02281787",
"cn_main_class":"蝴蝶",
"cn_class_name":"灰蝶",
"en_class_name":"lycaenid, lycaenid butterfly"
},
"327":{
"label_id":"n02317335",
"cn_main_class":"海星",
"cn_class_name":"海星",
"en_class_name":"starfish, sea star"
},
"328":{
"label_id":"n02319095",
"cn_main_class":"海胆",
"cn_class_name":"海胆",
"en_class_name":"sea urchin"
},
"329":{
"label_id":"n02321529",
"cn_main_class":"海洋生物",
"cn_class_name":"海参",
"en_class_name":"sea cucumber, holothurian"
},
"330":{
"label_id":"n02325366",
"cn_main_class":"兔",
"cn_class_name":"棉尾兔",
"en_class_name":"wood rabbit, cottontail, cottontail rabbit"
},
"331":{
"label_id":"n02326432",
"cn_main_class":"兔",
"cn_class_name":"野兔",
"en_class_name":"hare"
},
"332":{
"label_id":"n02328150",
"cn_main_class":"兔",
"cn_class_name":"安哥拉兔",
"en_class_name":"Angora, Angora rabbit"
},
"333":{
"label_id":"n02342885",
"cn_main_class":"鼠",
"cn_class_name":"仓鼠",
"en_class_name":"hamster"
},
"334":{
"label_id":"n02346627",
"cn_main_class":"鼠",
"cn_class_name":"刺猬",
"en_class_name":"porcupine, hedgehog"
},
"335":{
"label_id":"n02356798",
"cn_main_class":"松鼠",
"cn_class_name":"黑松鼠",
"en_class_name":"fox squirrel, eastern fox squirrel, Sciurus niger"
},
"336":{
"label_id":"n02361337",
"cn_main_class":"鼠",
"cn_class_name":"土拨鼠",
"en_class_name":"marmot"
},
"337":{
"label_id":"n02363005",
"cn_main_class":"鼠",
"cn_class_name":"海狸",
"en_class_name":"beaver"
},
"338":{
"label_id":"n02364673",
"cn_main_class":"鼠",
"cn_class_name":"荷兰猪",
"en_class_name":"guinea pig, Cavia cobaya"
},
"339":{
"label_id":"n02389026",
"cn_main_class":"马",
"cn_class_name":"红棕色",
"en_class_name":"sorrel"
},
"340":{
"label_id":"n02391049",
"cn_main_class":"斑马",
"cn_class_name":"斑马",
"en_class_name":"zebra"
},
"341":{
"label_id":"n02395406",
"cn_main_class":"猪",
"cn_class_name":"猪",
"en_class_name":"hog, pig, grunter, squealer, Sus scrofa"
},
"342":{
"label_id":"n02396427",
"cn_main_class":"猪",
"cn_class_name":"野猪",
"en_class_name":"wild boar, boar, Sus scrofa"
},
"343":{
"label_id":"n02397096",
"cn_main_class":"猪",
"cn_class_name":"野猪",
"en_class_name":"warthog"
},
"344":{
"label_id":"n02398521",
"cn_main_class":"河马",
"cn_class_name":"河马",
"en_class_name":"hippopotamus, hippo, river horse, Hippopotamus amphibius"
},
"345":{
"label_id":"n02403003",
"cn_main_class":"牛",
"cn_class_name":"牛",
"en_class_name":"ox"
},
"346":{
"label_id":"n02408429",
"cn_main_class":"牛",
"cn_class_name":"水牛",
"en_class_name":"water buffalo, water ox, Asiatic buffalo, Bubalus bubalis"
},
"347":{
"label_id":"n02410509",
"cn_main_class":"牛",
"cn_class_name":"野牛",
"en_class_name":"bison"
},
"348":{
"label_id":"n02412080",
"cn_main_class":"羊",
"cn_class_name":"公羊",
"en_class_name":"ram, tup"
},
"349":{
"label_id":"n02415577",
"cn_main_class":"羊",
"cn_class_name":"大角羊",
"en_class_name":"bighorn, bighorn sheep, cimarron, Rocky Mountain bighorn, Rocky Mountain sheep, Ovis canadensis"
},
"350":{
"label_id":"n02417914",
"cn_main_class":"羊",
"cn_class_name":"阿尔卑斯羱羊",
"en_class_name":"ibex, Capra ibex"
},
"351":{
"label_id":"n02422106",
"cn_main_class":"羊",
"cn_class_name":"羚羊",
"en_class_name":"hartebeest"
},
"352":{
"label_id":"n02422699",
"cn_main_class":"羊",
"cn_class_name":"黑斑羚",
"en_class_name":"impala, Aepyceros melampus"
},
"353":{
"label_id":"n02423022",
"cn_main_class":"羊",
"cn_class_name":"瞪羚",
"en_class_name":"gazelle"
},
"354":{
"label_id":"n02437312",
"cn_main_class":"骆驼",
"cn_class_name":"骆驼",
"en_class_name":"Arabian camel, dromedary, Camelus dromedarius"
},
"355":{
"label_id":"n02437616",
"cn_main_class":"羊驼",
"cn_class_name":"美洲驼",
"en_class_name":"llama"
},
"356":{
"label_id":"n02441942",
"cn_main_class":"狸",
"cn_class_name":"黄鼠狼",
"en_class_name":"weasel"
},
"357":{
"label_id":"n02442845",
"cn_main_class":"狸",
"cn_class_name":"貂",
"en_class_name":"mink"
},
"358":{
"label_id":"n02443114",
"cn_main_class":"狸",
"cn_class_name":"欧洲雪貂",
"en_class_name":"polecat, fitch, foulmart, foumart, Mustela putorius"
},
"359":{
"label_id":"n02443484",
"cn_main_class":"狸",
"cn_class_name":"黑足鼬",
"en_class_name":"black-footed ferret, ferret, Mustela nigripes"
},
"360":{
"label_id":"n02444819",
"cn_main_class":"狸",
"cn_class_name":"水獭",
"en_class_name":"otter"
},
"361":{
"label_id":"n02445715",
"cn_main_class":"狸",
"cn_class_name":"臭鼬",
"en_class_name":"skunk, polecat, wood pussy"
},
"362":{
"label_id":"n02447366",
"cn_main_class":"狸",
"cn_class_name":"獾",
"en_class_name":"badger"
},
"363":{
"label_id":"n02454379",
"cn_main_class":"穿山甲",
"cn_class_name":"犰狳",
"en_class_name":"armadillo"
},
"364":{
"label_id":"n02457408",
"cn_main_class":"树懒",
"cn_class_name":"三趾树懒",
"en_class_name":"three-toed sloth, ai, Bradypus tridactylus"
},
"365":{
"label_id":"n02480495",
"cn_main_class":"狒狒",
"cn_class_name":"猩猩",
"en_class_name":"orangutan, orang, orangutang, Pongo pygmaeus"
},
"366":{
"label_id":"n02480855",
"cn_main_class":"猴",
"cn_class_name":"大猩猩",
"en_class_name":"gorilla, Gorilla gorilla"
},
"367":{
"label_id":"n02481823",
"cn_main_class":"猴",
"cn_class_name":"黑猩猩",
"en_class_name":"chimpanzee, chimp, Pan troglodytes"
},
"368":{
"label_id":"n02483362",
"cn_main_class":"猴",
"cn_class_name":"长臂猿",
"en_class_name":"gibbon, Hylobates lar"
},
"369":{
"label_id":"n02483708",
"cn_main_class":"猴",
"cn_class_name":"合趾猴",
"en_class_name":"siamang, Hylobates syndactylus, Symphalangus syndactylus"
},
"370":{
"label_id":"n02484975",
"cn_main_class":"猴",
"cn_class_name":"长尾猴",
"en_class_name":"guenon, guenon monkey"
},
"371":{
"label_id":"n02486261",
"cn_main_class":"猴",
"cn_class_name":"赤猴",
"en_class_name":"patas, hussar monkey, Erythrocebus patas"
},
"372":{
"label_id":"n02486410",
"cn_main_class":"猴",
"cn_class_name":"狒狒",
"en_class_name":"baboon"
},
"373":{
"label_id":"n02487347",
"cn_main_class":"猴",
"cn_class_name":"猕猴",
"en_class_name":"macaque"
},
"374":{
"label_id":"n02488291",
"cn_main_class":"猴",
"cn_class_name":"叶猴",
"en_class_name":"langur"
},
"375":{
"label_id":"n02488702",
"cn_main_class":"猴",
"cn_class_name":"疣猴",
"en_class_name":"colobus, colobus monkey"
},
"376":{
"label_id":"n02489166",
"cn_main_class":"猴",
"cn_class_name":"长鼻猴",
"en_class_name":"proboscis monkey, Nasalis larvatus"
},
"377":{
"label_id":"n02490219",
"cn_main_class":"猴",
"cn_class_name":"狨猴",
"en_class_name":"marmoset"
},
"378":{
"label_id":"n02492035",
"cn_main_class":"猴",
"cn_class_name":"卷尾猴",
"en_class_name":"capuchin, ringtail, Cebus capucinus"
},
"379":{
"label_id":"n02492660",
"cn_main_class":"猴",
"cn_class_name":"吼猴",
"en_class_name":"howler monkey, howler"
},
"380":{
"label_id":"n02493509",
"cn_main_class":"猴",
"cn_class_name":"伶猴",
"en_class_name":"titi, titi monkey"
},
"381":{
"label_id":"n02493793",
"cn_main_class":"猴",
"cn_class_name":"蜘蛛猴",
"en_class_name":"spider monkey, Ateles geoffroyi"
},
"382":{
"label_id":"n02494079",
"cn_main_class":"猴",
"cn_class_name":"松鼠猴",
"en_class_name":"squirrel monkey, Saimiri sciureus"
},
"383":{
"label_id":"n02497673",
"cn_main_class":"猴",
"cn_class_name":"环尾狐猴",
"en_class_name":"Madagascar cat, ring-tailed lemur, Lemur catta"
},
"384":{
"label_id":"n02500267",
"cn_main_class":"猴",
"cn_class_name":"大狐猴",
"en_class_name":"indri, indris, Indri indri, Indri brevicaudatus"
},
"385":{
"label_id":"n02504013",
"cn_main_class":"象",
"cn_class_name":"印度象",
"en_class_name":"Indian elephant, Elephas maximus"
},
"386":{
"label_id":"n02504458",
"cn_main_class":"象",
"cn_class_name":"非洲象",
"en_class_name":"African elephant, Loxodonta africana"
},
"387":{
"label_id":"n02509815",
"cn_main_class":"熊",
"cn_class_name":"小熊猫",
"en_class_name":"lesser panda, red panda, panda, bear cat, cat bear, Ailurus fulgens"
},
"388":{
"label_id":"n02510455",
"cn_main_class":"熊",
"cn_class_name":"熊猫",
"en_class_name":"giant panda, panda, panda bear, coon bear, Ailuropoda melanoleuca"
},
"389":{
"label_id":"n02514041",
"cn_main_class":"鱼",
"cn_class_name":"长体蛇鲭",
"en_class_name":"barracouta, snoek"
},
"390":{
"label_id":"n02526121",
"cn_main_class":"鱼",
"cn_class_name":"鳗鱼",
"en_class_name":"eel"
},
"391":{
"label_id":"n02536864",
"cn_main_class":"鱼",
"cn_class_name":"鳕鱼",
"en_class_name":"coho, cohoe, coho salmon, blue jack, silver salmon, Oncorhynchus kisutch"
},
"392":{
"label_id":"n02606052",
"cn_main_class":"鱼",
"cn_class_name":"石美人",
"en_class_name":"rock beauty, Holocanthus tricolor"
},
"393":{
"label_id":"n02607072",
"cn_main_class":"鱼",
"cn_class_name":"银莲花鱼",
"en_class_name":"anemone fish"
},
"394":{
"label_id":"n02640242",
"cn_main_class":"鱼",
"cn_class_name":"鲟鱼",
"en_class_name":"sturgeon"
},
"395":{
"label_id":"n02641379",
"cn_main_class":"鱼",
"cn_class_name":"河豚",
"en_class_name":"gar, garfish, garpike, billfish, Lepisosteus osseus"
},
"396":{
"label_id":"n02643566",
"cn_main_class":"鱼",
"cn_class_name":"狮子鱼",
"en_class_name":"lionfish"
},
"397":{
"label_id":"n02655020",
"cn_main_class":"鱼",
"cn_class_name":"河豚",
"en_class_name":"puffer, pufferfish, blowfish, globefish"
},
"398":{
"label_id":"n02666196",
"cn_main_class":"算盘",
"cn_class_name":"算盘",
"en_class_name":"abacus"
},
"399":{
"label_id":"n02667093",
"cn_main_class":"衣",
"cn_class_name":"长袍",
"en_class_name":"abaya"
},
"400":{
"label_id":"n02669723",
"cn_main_class":"衣",
"cn_class_name":"学术服装",
"en_class_name":"academic gown, academic robe, judge's robe"
},
"401":{
"label_id":"n02672831",
"cn_main_class":"乐器",
"cn_class_name":"手风琴",
"en_class_name":"accordion, piano accordion, squeeze box"
},
"402":{
"label_id":"n02676566",
"cn_main_class":"乐器",
"cn_class_name":"吉他",
"en_class_name":"acoustic guitar"
},
"403":{
"label_id":"n02687172",
"cn_main_class":"船",
"cn_class_name":"航空母舰",
"en_class_name":"aircraft carrier, carrier, flattop, attack aircraft carrier"
},
"404":{
"label_id":"n02690373",
"cn_main_class":"飞机",
"cn_class_name":"客机",
"en_class_name":"airliner"
},
"405":{
"label_id":"n02692877",
"cn_main_class":"飞艇",
"cn_class_name":"飞艇",
"en_class_name":"airship, dirigible"
},
"406":{
"label_id":"n02699494",
"cn_main_class":"风景",
"cn_class_name":"圣坛",
"en_class_name":"altar"
},
"407":{
"label_id":"n02701002",
"cn_main_class":"车",
"cn_class_name":"救护车",
"en_class_name":"ambulance"
},
"408":{
"label_id":"n02704792",
"cn_main_class":"车",
"cn_class_name":"两栖车辆",
"en_class_name":"amphibian, amphibious vehicle"
},
"409":{
"label_id":"n02708093",
"cn_main_class":"钟",
"cn_class_name":"模拟时钟",
"en_class_name":"analog clock"
},
"410":{
"label_id":"n02727426",
"cn_main_class":"箱",
"cn_class_name":"养蜂场",
"en_class_name":"apiary, bee house"
},
"411":{
"label_id":"n02730930",
"cn_main_class":"衣",
"cn_class_name":"围裙",
"en_class_name":"apron"
},
"412":{
"label_id":"n02747177",
"cn_main_class":"箱",
"cn_class_name":"垃圾箱",
"en_class_name":"ashcan, trash can, garbage can, wastebin, ash bin, ash-bin, ashbin, dustbin, trash barrel, trash bin"
},
"413":{
"label_id":"n02749479",
"cn_main_class":"枪",
"cn_class_name":"突击枪",
"en_class_name":"assault rifle, assault gun"
},
"414":{
"label_id":"n02769748",
"cn_main_class":"包",
"cn_class_name":"背包",
"en_class_name":"backpack, back pack, knapsack, packsack, rucksack, haversack"
},
"415":{
"label_id":"n02776631",
"cn_main_class":"房",
"cn_class_name":"烘焙屋",
"en_class_name":"bakery, bakeshop, bakehouse"
},
"416":{
"label_id":"n02777292",
"cn_main_class":"器材",
"cn_class_name":"平衡梁",
"en_class_name":"balance beam, beam"
},
"417":{
"label_id":"n02782093",
"cn_main_class":"球",
"cn_class_name":"气球",
"en_class_name":"balloon"
},
"418":{
"label_id":"n02783161",
"cn_main_class":"笔",
"cn_class_name":"圆珠笔",
"en_class_name":"ballpoint, ballpoint pen, ballpen, Biro"
},
"419":{
"label_id":"n02786058",
"cn_main_class":"邦迪",
"cn_class_name":"创可贴",
"en_class_name":"Band Aid"
},
"420":{
"label_id":"n02787622",
"cn_main_class":"乐器",
"cn_class_name":"班卓琴",
"en_class_name":"banjo"
},
"421":{
"label_id":"n02788148",
"cn_main_class":"栏杆",
"cn_class_name":"栏杆",
"en_class_name":"bannister, banister, balustrade, balusters, handrail"
},
"422":{
"label_id":"n02790996",
"cn_main_class":"器材",
"cn_class_name":"杠铃",
"en_class_name":"barbell"
},
"423":{
"label_id":"n02791124",
"cn_main_class":"椅",
"cn_class_name":"理发椅",
"en_class_name":"barber chair"
},
"424":{
"label_id":"n02791270",
"cn_main_class":"房",
"cn_class_name":"理发店",
"en_class_name":"barbershop"
},
"425":{
"label_id":"n02793495",
"cn_main_class":"房",
"cn_class_name":"谷仓",
"en_class_name":"barn"
},
"426":{
"label_id":"n02794156",
"cn_main_class":"表",
"cn_class_name":"气压计",
"en_class_name":"barometer"
},
"427":{
"label_id":"n02795169",
"cn_main_class":"桶",
"cn_class_name":"桶",
"en_class_name":"barrel, cask"
},
"428":{
"label_id":"n02797295",
"cn_main_class":"车",
"cn_class_name":"手推车",
"en_class_name":"barrow, garden cart, lawn cart, wheelbarrow"
},
"429":{
"label_id":"n02799071",
"cn_main_class":"球",
"cn_class_name":"棒球",
"en_class_name":"baseball"
},
"430":{
"label_id":"n02802426",
"cn_main_class":"球",
"cn_class_name":"篮球",
"en_class_name":"basketball"
},
"431":{
"label_id":"n02804414",
"cn_main_class":"摇篮",
"cn_class_name":"婴儿摇篮",
"en_class_name":"bassinet"
},
"432":{
"label_id":"n02804610",
"cn_main_class":"乐器",
"cn_class_name":"低音管",
"en_class_name":"bassoon"
},
"433":{
"label_id":"n02807133",
"cn_main_class":"帽",
"cn_class_name":"泳帽",
"en_class_name":"bathing cap, swimming cap"
},
"434":{
"label_id":"n02808304",
"cn_main_class":"毛巾",
"cn_class_name":"浴巾",
"en_class_name":"bath towel"
},
"435":{
"label_id":"n02808440",
"cn_main_class":"缸",
"cn_class_name":"浴缸",
"en_class_name":"bathtub, bathing tub, bath, tub"
},
"436":{
"label_id":"n02814533",
"cn_main_class":"车",
"cn_class_name":"旅行车",
"en_class_name":"beach wagon, station wagon, wagon, estate car, beach waggon, station waggon, waggon"
},
"437":{
"label_id":"n02814860",
"cn_main_class":"塔",
"cn_class_name":"灯塔",
"en_class_name":"beacon, lighthouse, beacon light, pharos"
},
"438":{
"label_id":"n02815834",
"cn_main_class":"杯",
"cn_class_name":"烧杯",
"en_class_name":"beaker"
},
"439":{
"label_id":"n02817516",
"cn_main_class":"帽",
"cn_class_name":"熊皮帽",
"en_class_name":"bearskin, busby, shako"
},
"440":{
"label_id":"n02823428",
"cn_main_class":"啤酒瓶",
"cn_class_name":"啤酒瓶",
"en_class_name":"beer bottle"
},
"441":{
"label_id":"n02823750",
"cn_main_class":"啤酒杯",
"cn_class_name":"啤酒杯",
"en_class_name":"beer glass"
},
"442":{
"label_id":"n02825657",
"cn_main_class":"风景",
"cn_class_name":"钟楼",
"en_class_name":"bell cote, bell cot"
},
"443":{
"label_id":"n02834397",
"cn_main_class":"衣",
"cn_class_name":"围嘴",
"en_class_name":"bib"
},
"444":{
"label_id":"n02835271",
"cn_main_class":"车",
"cn_class_name":"双人自行车",
"en_class_name":"bicycle-built-for-two, tandem bicycle, tandem"
},
"445":{
"label_id":"n02837789",
"cn_main_class":"衣",
"cn_class_name":"比基尼",
"en_class_name":"bikini, two-piece"
},
"446":{
"label_id":"n02840245",
"cn_main_class":"书",
"cn_class_name":"活页夹",
"en_class_name":"binder, ring-binder"
},
"447":{
"label_id":"n02841315",
"cn_main_class":"眼镜",
"cn_class_name":"望远镜",
"en_class_name":"binoculars, field glasses, opera glasses"
},
"448":{
"label_id":"n02843684",
"cn_main_class":"箱",
"cn_class_name":"鸟舍",
"en_class_name":"birdhouse"
},
"449":{
"label_id":"n02859443",
"cn_main_class":"房",
"cn_class_name":"船屋",
"en_class_name":"boathouse"
},
"450":{
"label_id":"n02860847",
"cn_main_class":"雪橇",
"cn_class_name":"大雪橇",
"en_class_name":"bobsled, bobsleigh, bob"
},
"451":{
"label_id":"n02865351",
"cn_main_class":"项链",
"cn_class_name":"饰扣式领带",
"en_class_name":"bolo tie, bolo, bola tie, bola"
},
"452":{
"label_id":"n02869837",
"cn_main_class":"引擎盖",
"cn_class_name":"引擎盖",
"en_class_name":"bonnet, poke bonnet"
},
"453":{
"label_id":"n02870880",
"cn_main_class":"书柜",
"cn_class_name":"书柜",
"en_class_name":"bookcase"
},
"454":{
"label_id":"n02871525",
"cn_main_class":"书店",
"cn_class_name":"书店",
"en_class_name":"bookshop, bookstore, bookstall"
},
"455":{
"label_id":"n02877765",
"cn_main_class":"瓶盖",
"cn_class_name":"瓶盖",
"en_class_name":"bottlecap"
},
"456":{
"label_id":"n02879718",
"cn_main_class":"弓箭",
"cn_class_name":"弓箭",
"en_class_name":"bow"
},
"457":{
"label_id":"n02883205",
"cn_main_class":"领结",
"cn_class_name":"领结",
"en_class_name":"bow tie, bow-tie, bowtie"
},
"458":{
"label_id":"n02892201",
"cn_main_class":"碑",
"cn_class_name":"纪念碑",
"en_class_name":"brass, memorial tablet, plaque"
},
"459":{
"label_id":"n02892767",
"cn_main_class":"胸罩",
"cn_class_name":"胸罩",
"en_class_name":"brassiere, bra, bandeau"
},
"460":{
"label_id":"n02894605",
"cn_main_class":"海岸",
"cn_class_name":"海岸",
"en_class_name":"breakwater, groin, groyne, mole, bulwark, seawall, jetty"
},
"461":{
"label_id":"n02895154",
"cn_main_class":"胸甲",
"cn_class_name":"胸甲",
"en_class_name":"breastplate, aegis, egis"
},
"462":{
"label_id":"n02906734",
"cn_main_class":"扫帚",
"cn_class_name":"扫帚",
"en_class_name":"broom"
},
"463":{
"label_id":"n02909870",
"cn_main_class":"桶",
"cn_class_name":"桶",
"en_class_name":"bucket, pail"
},
"464":{
"label_id":"n02910353",
"cn_main_class":"皮带扣",
"cn_class_name":"皮带扣",
"en_class_name":"buckle"
},
"465":{
"label_id":"n02916936",
"cn_main_class":"衣",
"cn_class_name":"防弹背心",
"en_class_name":"bulletproof vest"
},
"466":{
"label_id":"n02917067",
"cn_main_class":"车",
"cn_class_name":"动车",
"en_class_name":"bullet train, bullet"
},
"467":{
"label_id":"n02927161",
"cn_main_class":"房",
"cn_class_name":"肉市场",
"en_class_name":"butcher shop, meat market"
},
"468":{
"label_id":"n02930766",
"cn_main_class":"车",
"cn_class_name":"出租车",
"en_class_name":"cab, hack, taxi, taxicab"
},
"469":{
"label_id":"n02939185",
"cn_main_class":"锅",
"cn_class_name":"大锅",
"en_class_name":"caldron, cauldron"
},
"470":{
"label_id":"n02948072",
"cn_main_class":"蜡烛",
"cn_class_name":"蜡烛",
"en_class_name":"candle, taper, wax light"
},
"471":{
"label_id":"n02950826",
"cn_main_class":"炮",
"cn_class_name":"大炮",
"en_class_name":"cannon"
},
"472":{
"label_id":"n02951358",
"cn_main_class":"船",
"cn_class_name":"独木舟",
"en_class_name":"canoe"
},
"473":{
"label_id":"n02951585",
"cn_main_class":"工具",
"cn_class_name":"开罐器",
"en_class_name":"can opener, tin opener"
},
"474":{
"label_id":"n02963159",
"cn_main_class":"衣",
"cn_class_name":"开衫",
"en_class_name":"cardigan"
},
"475":{
"label_id":"n02965783",
"cn_main_class":"镜",
"cn_class_name":"汽车后视镜",
"en_class_name":"car mirror"
},
"476":{
"label_id":"n02966193",
"cn_main_class":"旋转木马",
"cn_class_name":"旋转木马",
"en_class_name":"carousel, carrousel, merry-go-round, roundabout, whirligig"
},
"477":{
"label_id":"n02966687",
"cn_main_class":"箱",
"cn_class_name":"工具箱",
"en_class_name":"carpenter's kit, tool kit"
},
"478":{
"label_id":"n02971356",
"cn_main_class":"盒",
"cn_class_name":"纸箱",
"en_class_name":"carton"
},
"479":{
"label_id":"n02974003",
"cn_main_class":"轮胎",
"cn_class_name":"车轮",
"en_class_name":"car wheel"
},
"480":{
"label_id":"n02977058",
"cn_main_class":"机器",
"cn_class_name":"自动柜员机",
"en_class_name":"cash machine, cash dispenser, automated teller machine, automatic teller machine, automated teller, automatic teller, ATM"
},
"481":{
"label_id":"n02978881",
"cn_main_class":"磁带",
"cn_class_name":"磁带",
"en_class_name":"cassette"
},
"482":{
"label_id":"n02979186",
"cn_main_class":"磁带",
"cn_class_name":"磁带播放器",
"en_class_name":"cassette player"
},
"483":{
"label_id":"n02980441",
"cn_main_class":"风景",
"cn_class_name":"城堡",
"en_class_name":"castle"
},
"484":{
"label_id":"n02981792",
"cn_main_class":"船",
"cn_class_name":"双体船",
"en_class_name":"catamaran"
},
"485":{
"label_id":"n02988304",
"cn_main_class":"机器",
"cn_class_name":"CD播放器",
"en_class_name":"CD player"
},
"486":{
"label_id":"n02992211",
"cn_main_class":"乐器",
"cn_class_name":"大提琴",
"en_class_name":"cello, violoncello"
},
"487":{
"label_id":"n02992529",
"cn_main_class":"手机",
"cn_class_name":"手机",
"en_class_name":"cellular telephone, cellular phone, cellphone, cell, mobile phone"
},
"488":{
"label_id":"n02999410",
"cn_main_class":"铁链",
"cn_class_name":"链",
"en_class_name":"chain"
},
"489":{
"label_id":"n03000134",
"cn_main_class":"铁丝网",
"cn_class_name":"铁丝网",
"en_class_name":"chainlink fence"
},
"490":{
"label_id":"n03000247",
"cn_main_class":"铁丝网",
"cn_class_name":"铁丝网",
"en_class_name":"chain mail, ring mail, mail, chain armor, chain armour, ring armor, ring armour"
},
"491":{
"label_id":"n03000684",
"cn_main_class":"电锯",
"cn_class_name":"电锯",
"en_class_name":"chain saw, chainsaw"
},
"492":{
"label_id":"n03014705",
"cn_main_class":"人体",
"cn_class_name":"胸部",
"en_class_name":"chest"
},
"493":{
"label_id":"n03016953",
"cn_main_class":"柜",
"cn_class_name":"五斗橱",
"en_class_name":"chiffonier, commode"
},
"494":{
"label_id":"n03017168",
"cn_main_class":"乐器",
"cn_class_name":"铜锣",
"en_class_name":"chime, bell, gong"
},
"495":{
"label_id":"n03018349",
"cn_main_class":"柜",
"cn_class_name":"中国橱柜",
"en_class_name":"china cabinet, china closet"
},
"496":{
"label_id":"n03026506",
"cn_main_class":"袜",
"cn_class_name":"圣诞袜",
"en_class_name":"Christmas stocking"
},
"497":{
"label_id":"n03028079",
"cn_main_class":"风景",
"cn_class_name":"教堂",
"en_class_name":"church, church building"
},
"498":{
"label_id":"n03032252",
"cn_main_class":"房",
"cn_class_name":"电影院",
"en_class_name":"cinema, movie theater, movie theatre, movie house, picture palace"
},
"499":{
"label_id":"n03041632",
"cn_main_class":"刀",
"cn_class_name":"切肉刀",
"en_class_name":"cleaver, meat cleaver, chopper"
},
"500":{
"label_id":"n03042490",
"cn_main_class":"房",
"cn_class_name":"悬崖住宅",
"en_class_name":"cliff dwelling"
},
"501":{
"label_id":"n03045698",
"cn_main_class":"衣",
"cn_class_name":"斗篷",
"en_class_name":"cloak"
},
"502":{
"label_id":"n03047690",
"cn_main_class":"鞋",
"cn_class_name":"木屐",
"en_class_name":"clog, geta, patten, sabot"
},
"503":{
"label_id":"n03062245",
"cn_main_class":"器具",
"cn_class_name":"鸡尾酒搅拌器",
"en_class_name":"cocktail shaker"
},
"504":{
"label_id":"n03063599",
"cn_main_class":"杯子",
"cn_class_name":"咖啡杯",
"en_class_name":"coffee mug"
},
"505":{
"label_id":"n03063689",
"cn_main_class":"壶",
"cn_class_name":"咖啡壶",
"en_class_name":"coffeepot"
},
"506":{
"label_id":"n03065424",
"cn_main_class":"螺旋",
"cn_class_name":"螺旋",
"en_class_name":"coil, spiral, volute, whorl, helix"
},
"507":{
"label_id":"n03075370",
"cn_main_class":"锁",
"cn_class_name":"密码锁",
"en_class_name":"combination lock"
},
"508":{
"label_id":"n03085013",
"cn_main_class":"键盘",
"cn_class_name":"键盘",
"en_class_name":"computer keyboard, keypad"
},
"509":{
"label_id":"n03089624",
"cn_main_class":"糖果",
"cn_class_name":"糖果",
"en_class_name":"confectionery, confectionary, candy store"
},
"510":{
"label_id":"n03095699",
"cn_main_class":"船",
"cn_class_name":"集装箱船",
"en_class_name":"container ship, containership, container vessel"
},
"511":{
"label_id":"n03100240",
"cn_main_class":"车",
"cn_class_name":"敞篷车",
"en_class_name":"convertible"
},
"512":{
"label_id":"n03109150",
"cn_main_class":"开瓶器",
"cn_class_name":"开瓶器",
"en_class_name":"corkscrew, bottle screw"
},
"513":{
"label_id":"n03110669",
"cn_main_class":"乐器",
"cn_class_name":"短号",
"en_class_name":"cornet, horn, trumpet, trump"
},
"514":{
"label_id":"n03124043",
"cn_main_class":"鞋",
"cn_class_name":"牛仔靴",
"en_class_name":"cowboy boot"
},
"515":{
"label_id":"n03124170",
"cn_main_class":"帽",
"cn_class_name":"牛仔帽",
"en_class_name":"cowboy hat, ten-gallon hat"
},
"516":{
"label_id":"n03125729",
"cn_main_class":"床",
"cn_class_name":"摇篮",
"en_class_name":"cradle"
},
"517":{
"label_id":"n03126707",
"cn_main_class":"车",
"cn_class_name":"起重机",
"en_class_name":"crane"
},
"518":{
"label_id":"n03127747",
"cn_main_class":"帽",
"cn_class_name":"安全帽",
"en_class_name":"crash helmet"
},
"519":{
"label_id":"n03127925",
"cn_main_class":"箱",
"cn_class_name":"板条箱",
"en_class_name":"crate"
},
"520":{
"label_id":"n03131574",
"cn_main_class":"床",
"cn_class_name":"婴儿床",
"en_class_name":"crib, cot"
},
"521":{
"label_id":"n03133878",
"cn_main_class":"锅",
"cn_class_name":"瓦罐",
"en_class_name":"Crock Pot"
},
"522":{
"label_id":"n03134739",
"cn_main_class":"球",
"cn_class_name":"槌球",
"en_class_name":"croquet ball"
},
"523":{
"label_id":"n03141823",
"cn_main_class":"杖",
"cn_class_name":"拐杖",
"en_class_name":"crutch"
},
"524":{
"label_id":"n03146219",
"cn_main_class":"甲",
"cn_class_name":"胸甲",
"en_class_name":"cuirass"
},
"525":{
"label_id":"n03160309",
"cn_main_class":"水库",
"cn_class_name":"堤坝",
"en_class_name":"dam, dike, dyke"
},
"526":{
"label_id":"n03179701",
"cn_main_class":"桌",
"cn_class_name":"桌子",
"en_class_name":"desk"
},
"527":{
"label_id":"n03180011",
"cn_main_class":"电脑",
"cn_class_name":"桌面计算机",
"en_class_name":"desktop computer"
},
"528":{
"label_id":"n03187595",
"cn_main_class":"电话",
"cn_class_name":"电话",
"en_class_name":"dial telephone, dial phone"
},
"529":{
"label_id":"n03188531",
"cn_main_class":"布",
"cn_class_name":"餐巾",
"en_class_name":"diaper, nappy, napkin"
},
"530":{
"label_id":"n03196217",
"cn_main_class":"钟",
"cn_class_name":"数字时钟",
"en_class_name":"digital clock"
},
"531":{
"label_id":"n03197337",
"cn_main_class":"表",
"cn_class_name":"数字手表",
"en_class_name":"digital watch"
},
"532":{
"label_id":"n03201208",
"cn_main_class":"桌",
"cn_class_name":"餐桌",
"en_class_name":"dining table, board"
},
"533":{
"label_id":"n03207743",
"cn_main_class":"布",
"cn_class_name":"抹布",
"en_class_name":"dishrag, dishcloth"
},
"534":{
"label_id":"n03207941",
"cn_main_class":"柜",
"cn_class_name":"洗碗机",
"en_class_name":"dishwasher, dish washer, dishwashing machine"
},
"535":{
"label_id":"n03208938",
"cn_main_class":"车",
"cn_class_name":"刹车盘",
"en_class_name":"disk brake, disc brake"
},
"536":{
"label_id":"n03216828",
"cn_main_class":"港口",
"cn_class_name":"码头",
"en_class_name":"dock, dockage, docking facility"
},
"537":{
"label_id":"n03218198",
"cn_main_class":"雪橇",
"cn_class_name":"狗拉雪橇",
"en_class_name":"dogsled, dog sled, dog sleigh"
},
"538":{
"label_id":"n03220513",
"cn_main_class":"顶",
"cn_class_name":"圆顶",
"en_class_name":"dome"
},
"539":{
"label_id":"n03223299",
"cn_main_class":"地毯",
"cn_class_name":"门垫",
"en_class_name":"doormat, welcome mat"
},
"540":{
"label_id":"n03240683",
"cn_main_class":"机器",
"cn_class_name":"钻井平台",
"en_class_name":"drilling platform, offshore rig"
},
"541":{
"label_id":"n03249569",
"cn_main_class":"鼓",
"cn_class_name":"鼓",
"en_class_name":"drum, membranophone, tympan"
},
"542":{
"label_id":"n03250847",
"cn_main_class":"肉",
"cn_class_name":"鸡腿",
"en_class_name":"drumstick"
},
"543":{
"label_id":"n03255030",
"cn_main_class":"哑铃",
"cn_class_name":"哑铃",
"en_class_name":"dumbbell"
},
"544":{
"label_id":"n03259280",
"cn_main_class":"锅",
"cn_class_name":"荷兰锅",
"en_class_name":"Dutch oven"
},
"545":{
"label_id":"n03271574",
"cn_main_class":"机器",
"cn_class_name":"电风扇",
"en_class_name":"electric fan, blower"
},
"546":{
"label_id":"n03272010",
"cn_main_class":"乐器",
"cn_class_name":"电吉他",
"en_class_name":"electric guitar"
},
"547":{
"label_id":"n03272562",
"cn_main_class":"车",
"cn_class_name":"电力机车",
"en_class_name":"electric locomotive"
},
"548":{
"label_id":"n03290653",
"cn_main_class":"电视",
"cn_class_name":"娱乐中心",
"en_class_name":"entertainment center"
},
"549":{
"label_id":"n03291819",
"cn_main_class":"信",
"cn_class_name":"信封",
"en_class_name":"envelope"
},
"550":{
"label_id":"n03297495",
"cn_main_class":"机器",
"cn_class_name":"意式浓缩咖啡机",
"en_class_name":"espresso maker"
},
"551":{
"label_id":"n03314780",
"cn_main_class":"化妆品",
"cn_class_name":"擦脸香粉",
"en_class_name":"face powder"
},
"552":{
"label_id":"n03325584",
"cn_main_class":"蛇",
"cn_class_name":"蟒蛇",
"en_class_name":"feather boa, boa"
},
"553":{
"label_id":"n03337140",
"cn_main_class":"柜",
"cn_class_name":"文件柜",
"en_class_name":"file, file cabinet, filing cabinet"
},
"554":{
"label_id":"n03344393",
"cn_main_class":"船",
"cn_class_name":"消防船",
"en_class_name":"fireboat"
},
"555":{
"label_id":"n03345487",
"cn_main_class":"车",
"cn_class_name":"消防车",
"en_class_name":"fire engine, fire truck"
},
"556":{
"label_id":"n03347037",
"cn_main_class":"防火",
"cn_class_name":"防火屏",
"en_class_name":"fire screen, fireguard"
},
"557":{
"label_id":"n03355925",
"cn_main_class":"杆",
"cn_class_name":"旗杆",
"en_class_name":"flagpole, flagstaff"
},
"558":{
"label_id":"n03372029",
"cn_main_class":"乐器",
"cn_class_name":"长笛",
"en_class_name":"flute, transverse flute"
},
"559":{
"label_id":"n03376595",
"cn_main_class":"椅",
"cn_class_name":"折叠椅",
"en_class_name":"folding chair"
},
"560":{
"label_id":"n03379051",
"cn_main_class":"帽",
"cn_class_name":"头盔",
"en_class_name":"football helmet"
},
"561":{
"label_id":"n03384352",
"cn_main_class":"车",
"cn_class_name":"叉车",
"en_class_name":"forklift"
},
"562":{
"label_id":"n03388043",
"cn_main_class":"喷泉",
"cn_class_name":"喷泉",
"en_class_name":"fountain"
},
"563":{
"label_id":"n03388183",
"cn_main_class":"笔",
"cn_class_name":"自来水笔",
"en_class_name":"fountain pen"
},
"564":{
"label_id":"n03388549",
"cn_main_class":"床",
"cn_class_name":"四柱床",
"en_class_name":"four-poster"
},
"565":{
"label_id":"n03393912",
"cn_main_class":"车",
"cn_class_name":"货车",
"en_class_name":"freight car"
},
"566":{
"label_id":"n03394916",
"cn_main_class":"乐器",
"cn_class_name":"号角",
"en_class_name":"French horn, horn"
},
"567":{
"label_id":"n03400231",
"cn_main_class":"锅",
"cn_class_name":"煎锅",
"en_class_name":"frying pan, frypan, skillet"
},
"568":{
"label_id":"n03404251",
"cn_main_class":"衣",
"cn_class_name":"毛皮大衣",
"en_class_name":"fur coat"
},
"569":{
"label_id":"n03417042",
"cn_main_class":"车",
"cn_class_name":"垃圾车",
"en_class_name":"garbage truck, dustcart"
},
"570":{
"label_id":"n03424325",
"cn_main_class":"面具",
"cn_class_name":"防毒面具",
"en_class_name":"gasmask, respirator, gas helmet"
},
"571":{
"label_id":"n03425413",
"cn_main_class":"泵",
"cn_class_name":"气泵",
"en_class_name":"gas pump, gasoline pump, petrol pump, island dispenser"
},
"572":{
"label_id":"n03443371",
"cn_main_class":"杯",
"cn_class_name":"高脚杯",
"en_class_name":"goblet"
},
"573":{
"label_id":"n03444034",
"cn_main_class":"车",
"cn_class_name":"卡丁车",
"en_class_name":"go-kart"
},
"574":{
"label_id":"n03445777",
"cn_main_class":"球",
"cn_class_name":"高尔夫球",
"en_class_name":"golf ball"
},
"575":{
"label_id":"n03445924",
"cn_main_class":"车",
"cn_class_name":"高尔夫球车",
"en_class_name":"golfcart, golf cart"
},
"576":{
"label_id":"n03447447",
"cn_main_class":"船",
"cn_class_name":"贡多拉",
"en_class_name":"gondola"
},
"577":{
"label_id":"n03447721",
"cn_main_class":"鼓",
"cn_class_name":"铜锣",
"en_class_name":"gong, tam-tam"
},
"578":{
"label_id":"n03450230",
"cn_main_class":"衣",
"cn_class_name":"礼服",
"en_class_name":"gown"
},
"579":{
"label_id":"n03452741",
"cn_main_class":"乐器",
"cn_class_name":"大钢琴",
"en_class_name":"grand piano, grand"
},
"580":{
"label_id":"n03457902",
"cn_main_class":"房",
"cn_class_name":"温室",
"en_class_name":"greenhouse, nursery, glasshouse"
},
"581":{
"label_id":"n03459775",
"cn_main_class":"车脸",
"cn_class_name":"格栅",
"en_class_name":"grille, radiator grille"
},
"582":{
"label_id":"n03461385",
"cn_main_class":"市场",
"cn_class_name":"杂货店",
"en_class_name":"grocery store, grocery, food market, market"
},
"583":{
"label_id":"n03467068",
"cn_main_class":"断头台",
"cn_class_name":"断头台",
"en_class_name":"guillotine"
},
"584":{
"label_id":"n03476684",
"cn_main_class":"发饰",
"cn_class_name":"小发夹",
"en_class_name":"hair slide"
},
"585":{
"label_id":"n03476991",
"cn_main_class":"发胶",
"cn_class_name":"发胶",
"en_class_name":"hair spray"
},
"586":{
"label_id":"n03478589",
"cn_main_class":"车",
"cn_class_name":"半履带车",
"en_class_name":"half track"
},
"587":{
"label_id":"n03481172",
"cn_main_class":"锤子",
"cn_class_name":"锤子",
"en_class_name":"hammer"
},
"588":{
"label_id":"n03482405",
"cn_main_class":"竹篮",
"cn_class_name":"竹篮",
"en_class_name":"hamper"
},
"589":{
"label_id":"n03483316",
"cn_main_class":"机器",
"cn_class_name":"吹风机",
"en_class_name":"hand blower, blow dryer, blow drier, hair dryer, hair drier"
},
"590":{
"label_id":"n03485407",
"cn_main_class":"机器",
"cn_class_name":"手持计算机",
"en_class_name":"hand-held computer, hand-held microcomputer"
},
"591":{
"label_id":"n03485794",
"cn_main_class":"手帕",
"cn_class_name":"手帕",
"en_class_name":"handkerchief, hankie, hanky, hankey"
},
"592":{
"label_id":"n03492542",
"cn_main_class":"硬盘",
"cn_class_name":"硬盘",
"en_class_name":"hard disc, hard disk, fixed disk"
},
"593":{
"label_id":"n03494278",
"cn_main_class":"乐器",
"cn_class_name":"口琴",
"en_class_name":"harmonica, mouth organ, harp, mouth harp"
},
"594":{
"label_id":"n03495258",
"cn_main_class":"乐器",
"cn_class_name":"竖琴",
"en_class_name":"harp"
},
"595":{
"label_id":"n03496892",
"cn_main_class":"车",
"cn_class_name":"收割机",
"en_class_name":"harvester, reaper"
},
"596":{
"label_id":"n03498962",
"cn_main_class":"斧头",
"cn_class_name":"斧头",
"en_class_name":"hatchet"
},
"597":{
"label_id":"n03527444",
"cn_main_class":"枪套",
"cn_class_name":"枪套",
"en_class_name":"holster"
},
"598":{
"label_id":"n03529860",
"cn_main_class":"家庭影院",
"cn_class_name":"家庭影院",
"en_class_name":"home theater, home theatre"
},
"599":{
"label_id":"n03530642",
"cn_main_class":"蜂巢",
"cn_class_name":"蜂巢",
"en_class_name":"honeycomb"
},
"600":{
"label_id":"n03532672",
"cn_main_class":"钩",
"cn_class_name":"钩",
"en_class_name":"hook, claw"
},
"601":{
"label_id":"n03534580",
"cn_main_class":"衣",
"cn_class_name":"克里诺林裙",
"en_class_name":"hoopskirt, crinoline"
},
"602":{
"label_id":"n03535780",
"cn_main_class":"杠",
"cn_class_name":"单杠",
"en_class_name":"horizontal bar, high bar"
},
"603":{
"label_id":"n03538406",
"cn_main_class":"车",
"cn_class_name":"马车",
"en_class_name":"horse cart, horse-cart"
},
"604":{
"label_id":"n03544143",
"cn_main_class":"沙漏",
"cn_class_name":"沙漏",
"en_class_name":"hourglass"
},
"605":{
"label_id":"n03584254",
"cn_main_class":"音乐播放器",
"cn_class_name":"iPod",
"en_class_name":"iPod"
},
"606":{
"label_id":"n03584829",
"cn_main_class":"熨斗",
"cn_class_name":"熨斗",
"en_class_name":"iron, smoothing iron"
},
"607":{
"label_id":"n03590841",
"cn_main_class":"灯",
"cn_class_name":"南瓜灯",
"en_class_name":"jack-o'-lantern"
},
"608":{
"label_id":"n03594734",
"cn_main_class":"裤",
"cn_class_name":"牛仔裤",
"en_class_name":"jean, blue jean, denim"
},
"609":{
"label_id":"n03594945",
"cn_main_class":"车",
"cn_class_name":"吉普",
"en_class_name":"jeep, landrover"
},
"610":{
"label_id":"n03595614",
"cn_main_class":"衣",
"cn_class_name":"T恤",
"en_class_name":"jersey, T-shirt, tee shirt"
},
"611":{
"label_id":"n03598930",
"cn_main_class":"拼图",
"cn_class_name":"拼图",
"en_class_name":"jigsaw puzzle"
},
"612":{
"label_id":"n03599486",
"cn_main_class":"车",
"cn_class_name":"人力车",
"en_class_name":"jinrikisha, ricksha, rickshaw"
},
"613":{
"label_id":"n03602883",
"cn_main_class":"操纵杆",
"cn_class_name":"操纵杆",
"en_class_name":"joystick"
},
"614":{
"label_id":"n03617480",
"cn_main_class":"衣",
"cn_class_name":"和服",
"en_class_name":"kimono"
},
"615":{
"label_id":"n03623198",
"cn_main_class":"护膝",
"cn_class_name":"护膝",
"en_class_name":"knee pad"
},
"616":{
"label_id":"n03627232",
"cn_main_class":"绳结",
"cn_class_name":"绳结",
"en_class_name":"knot"
},
"617":{
"label_id":"n03630383",
"cn_main_class":"衣",
"cn_class_name":"白大褂",
"en_class_name":"lab coat, laboratory coat"
},
"618":{
"label_id":"n03633091",
"cn_main_class":"勺子",
"cn_class_name":"勺子",
"en_class_name":"ladle"
},
"619":{
"label_id":"n03637318",
"cn_main_class":"灯",
"cn_class_name":"灯罩",
"en_class_name":"lampshade, lamp shade"
},
"620":{
"label_id":"n03642806",
"cn_main_class":"笔记本电脑",
"cn_class_name":"笔记本电脑",
"en_class_name":"laptop, laptop computer"
},
"621":{
"label_id":"n03649909",
"cn_main_class":"割草机",
"cn_class_name":"割草机",
"en_class_name":"lawn mower, mower"
},
"622":{
"label_id":"n03657121",
"cn_main_class":"镜头盖",
"cn_class_name":"镜头盖",
"en_class_name":"lens cap, lens cover"
},
"623":{
"label_id":"n03658185",
"cn_main_class":"刀",
"cn_class_name":"开封器",
"en_class_name":"letter opener, paper knife, paperknife"
},
"624":{
"label_id":"n03661043",
"cn_main_class":"图书馆",
"cn_class_name":"图书馆",
"en_class_name":"library"
},
"625":{
"label_id":"n03662601",
"cn_main_class":"船",
"cn_class_name":"救生艇",
"en_class_name":"lifeboat"
},
"626":{
"label_id":"n03666591",
"cn_main_class":"打火机",
"cn_class_name":"打火机",
"en_class_name":"lighter, light, igniter, ignitor"
},
"627":{
"label_id":"n03670208",
"cn_main_class":"车",
"cn_class_name":"豪华轿车",
"en_class_name":"limousine, limo"
},
"628":{
"label_id":"n03673027",
"cn_main_class":"船",
"cn_class_name":"班轮,远洋班轮",
"en_class_name":"liner, ocean liner"
},
"629":{
"label_id":"n03676483",
"cn_main_class":"口红",
"cn_class_name":"口红",
"en_class_name":"lipstick, lip rouge"
},
"630":{
"label_id":"n03680355",
"cn_main_class":"鞋",
"cn_class_name":"乐福鞋",
"en_class_name":"Loafer"
},
"631":{
"label_id":"n03690938",
"cn_main_class":"护肤品",
"cn_class_name":"润肤乳",
"en_class_name":"lotion"
},
"632":{
"label_id":"n03691459",
"cn_main_class":"音响",
"cn_class_name":"扬声器",
"en_class_name":"loudspeaker, speaker, speaker unit, loudspeaker system, speaker system"
},
"633":{
"label_id":"n03692522",
"cn_main_class":"放大镜",
"cn_class_name":"放大镜",
"en_class_name":"loupe, jeweler's loupe"
},
"634":{
"label_id":"n03697007",
"cn_main_class":"木材厂",
"cn_class_name":"木材厂",
"en_class_name":"lumbermill, sawmill"
},
"635":{
"label_id":"n03706229",
"cn_main_class":"指南针",
"cn_class_name":"指南针",
"en_class_name":"magnetic compass"
},
"636":{
"label_id":"n03709823",
"cn_main_class":"包",
"cn_class_name":"邮包",
"en_class_name":"mailbag, postbag"
},
"637":{
"label_id":"n03710193",
"cn_main_class":"箱",
"cn_class_name":"邮箱",
"en_class_name":"mailbox, letter box"
},
"638":{
"label_id":"n03710637",
"cn_main_class":"衣",
"cn_class_name":"泳衣",
"en_class_name":"maillot"
},
"639":{
"label_id":"n03710721",
"cn_main_class":"泳衣",
"cn_class_name":"女式泳装",
"en_class_name":"maillot, tank suit"
},
"640":{
"label_id":"n03717622",
"cn_main_class":"井盖",
"cn_class_name":"井盖",
"en_class_name":"manhole cover"
},
"641":{
"label_id":"n03720891",
"cn_main_class":"乐器",
"cn_class_name":"沙锤",
"en_class_name":"maraca"
},
"642":{
"label_id":"n03721384",
"cn_main_class":"乐器",
"cn_class_name":"木琴",
"en_class_name":"marimba, xylophone"
},
"643":{
"label_id":"n03724870",
"cn_main_class":"面具",
"cn_class_name":"面具",
"en_class_name":"mask"
},
"644":{
"label_id":"n03729826",
"cn_main_class":"火柴",
"cn_class_name":"火柴",
"en_class_name":"matchstick"
},
"645":{
"label_id":"n03733131",
"cn_main_class":"五朔节花柱",
"cn_class_name":"五朔节花柱",
"en_class_name":"maypole"
},
"646":{
"label_id":"n03733281",
"cn_main_class":"迷宫",
"cn_class_name":"迷宫",
"en_class_name":"maze, labyrinth"
},
"647":{
"label_id":"n03733805",
"cn_main_class":"量杯",
"cn_class_name":"量杯",
"en_class_name":"measuring cup"
},
"648":{
"label_id":"n03742115",
"cn_main_class":"箱",
"cn_class_name":"药箱",
"en_class_name":"medicine chest, medicine cabinet"
},
"649":{
"label_id":"n03743016",
"cn_main_class":"巨石",
"cn_class_name":"巨石",
"en_class_name":"megalith, megalithic structure"
},
"650":{
"label_id":"n03759954",
"cn_main_class":"麦克风",
"cn_class_name":"麦克风",
"en_class_name":"microphone, mike"
},
"651":{
"label_id":"n03761084",
"cn_main_class":"微波炉",
"cn_class_name":"微波炉",
"en_class_name":"microwave, microwave oven"
},
"652":{
"label_id":"n03763968",
"cn_main_class":"衣",
"cn_class_name":"军服",
"en_class_name":"military uniform"
},
"653":{
"label_id":"n03764736",
"cn_main_class":"壶",
"cn_class_name":"牛奶罐",
"en_class_name":"milk can"
},
"654":{
"label_id":"n03769881",
"cn_main_class":"车",
"cn_class_name":"小巴",
"en_class_name":"minibus"
},
"655":{
"label_id":"n03770439",
"cn_main_class":"衣",
"cn_class_name":"迷你裙",
"en_class_name":"miniskirt, mini"
},
"656":{
"label_id":"n03770679",
"cn_main_class":"车",
"cn_class_name":"小型货车",
"en_class_name":"minivan"
},
"657":{
"label_id":"n03773504",
"cn_main_class":"导弹",
"cn_class_name":"导弹",
"en_class_name":"missile"
},
"658":{
"label_id":"n03775071",
"cn_main_class":"手套",
"cn_class_name":"手套",
"en_class_name":"mitten"
},
"659":{
"label_id":"n03775546",
"cn_main_class":"碗",
"cn_class_name":"搅拌碗",
"en_class_name":"mixing bowl"
},
"660":{
"label_id":"n03776460",
"cn_main_class":"房",
"cn_class_name":"活动房屋",
"en_class_name":"mobile home, manufactured home"
},
"661":{
"label_id":"n03777568",
"cn_main_class":"车",
"cn_class_name":"老爷车",
"en_class_name":"Model T"
},
"662":{
"label_id":"n03777754",
"cn_main_class":"路由器",
"cn_class_name":"路由器",
"en_class_name":"modem"
},
"663":{
"label_id":"n03781244",
"cn_main_class":"风景",
"cn_class_name":"修道院",
"en_class_name":"monastery"
},
"664":{
"label_id":"n03782006",
"cn_main_class":"显示器",
"cn_class_name":"显示器",
"en_class_name":"monitor"
},
"665":{
"label_id":"n03785016",
"cn_main_class":"车",
"cn_class_name":"助动车",
"en_class_name":"moped"
},
"666":{
"label_id":"n03786901",
"cn_main_class":"灰泥",
"cn_class_name":"灰泥",
"en_class_name":"mortar"
},
"667":{
"label_id":"n03787032",
"cn_main_class":"学位帽",
"cn_class_name":"学位帽",
"en_class_name":"mortarboard"
},
"668":{
"label_id":"n03788195",
"cn_main_class":"风景",
"cn_class_name":"清真寺",
"en_class_name":"mosque"
},
"669":{
"label_id":"n03788365",
"cn_main_class":"蚊帐",
"cn_class_name":"蚊帐",
"en_class_name":"mosquito net"
},
"670":{
"label_id":"n03791053",
"cn_main_class":"车",
"cn_class_name":"摩托车",
"en_class_name":"motor scooter, scooter"
},
"671":{
"label_id":"n03792782",
"cn_main_class":"车",
"cn_class_name":"山地车",
"en_class_name":"mountain bike, all-terrain bike, off-roader"
},
"672":{
"label_id":"n03792972",
"cn_main_class":"帐篷",
"cn_class_name":"山帐篷",
"en_class_name":"mountain tent"
},
"673":{
"label_id":"n03793489",
"cn_main_class":"鼠标",
"cn_class_name":"鼠标",
"en_class_name":"mouse, computer mouse"
},
"674":{
"label_id":"n03794056",
"cn_main_class":"捕鼠夹",
"cn_class_name":"捕鼠夹",
"en_class_name":"mousetrap"
},
"675":{
"label_id":"n03796401",
"cn_main_class":"车",
"cn_class_name":"货车",
"en_class_name":"moving van"
},
"676":{
"label_id":"n03803284",
"cn_main_class":"口套",
"cn_class_name":"口套",
"en_class_name":"muzzle"
},
"677":{
"label_id":"n03804744",
"cn_main_class":"钉子",
"cn_class_name":"钉子",
"en_class_name":"nail"
},
"678":{
"label_id":"n03814639",
"cn_main_class":"颈托",
"cn_class_name":"颈托",
"en_class_name":"neck brace"
},
"679":{
"label_id":"n03814906",
"cn_main_class":"项链",
"cn_class_name":"项链",
"en_class_name":"necklace"
},
"680":{
"label_id":"n03825788",
"cn_main_class":"奶瓶",
"cn_class_name":"奶瓶",
"en_class_name":"nipple"
},
"681":{
"label_id":"n03832673",
"cn_main_class":"笔记本",
"cn_class_name":"笔记本电脑",
"en_class_name":"notebook, notebook computer"
},
"682":{
"label_id":"n03837869",
"cn_main_class":"碑",
"cn_class_name":"方尖碑",
"en_class_name":"obelisk"
},
"683":{
"label_id":"n03838899",
"cn_main_class":"乐器",
"cn_class_name":"双簧管",
"en_class_name":"oboe, hautboy, hautbois"
},
"684":{
"label_id":"n03840681",
"cn_main_class":"乐器",
"cn_class_name":"陶笛",
"en_class_name":"ocarina, sweet potato"
},
"685":{
"label_id":"n03841143",
"cn_main_class":"仪表盘",
"cn_class_name":"仪表盘",
"en_class_name":"odometer, hodometer, mileometer, milometer"
},
"686":{
"label_id":"n03843555",
"cn_main_class":"机油滤清器",
"cn_class_name":"机油滤清器",
"en_class_name":"oil filter"
},
"687":{
"label_id":"n03854065",
"cn_main_class":"乐器",
"cn_class_name":"管风琴",
"en_class_name":"organ, pipe organ"
},
"688":{
"label_id":"n03857828",
"cn_main_class":"示波器",
"cn_class_name":"示波器",
"en_class_name":"oscilloscope, scope, cathode-ray oscilloscope, CRO"
},
"689":{
"label_id":"n03866082",
"cn_main_class":"衣",
"cn_class_name":"超短裙",
"en_class_name":"overskirt"
},
"690":{
"label_id":"n03868242",
"cn_main_class":"车",
"cn_class_name":"牛车",
"en_class_name":"oxcart"
},
"691":{
"label_id":"n03868863",
"cn_main_class":"面罩",
"cn_class_name":"氧气面罩",
"en_class_name":"oxygen mask"
},
"692":{
"label_id":"n03871628",
"cn_main_class":"包",
"cn_class_name":"包",
"en_class_name":"packet"
},
"693":{
"label_id":"n03873416",
"cn_main_class":"桨",
"cn_class_name":"划桨",
"en_class_name":"paddle, boat paddle"
},
"694":{
"label_id":"n03874293",
"cn_main_class":"桨轮",
"cn_class_name":"桨轮",
"en_class_name":"paddlewheel, paddle wheel"
},
"695":{
"label_id":"n03874599",
"cn_main_class":"锁",
"cn_class_name":"挂锁",
"en_class_name":"padlock"
},
"696":{
"label_id":"n03876231",
"cn_main_class":"笔",
"cn_class_name":"画笔",
"en_class_name":"paintbrush"
},
"697":{
"label_id":"n03877472",
"cn_main_class":"衣",
"cn_class_name":"睡衣",
"en_class_name":"pajama, pyjama, pj's, jammies"
},
"698":{
"label_id":"n03877845",
"cn_main_class":"风景",
"cn_class_name":"宫殿",
"en_class_name":"palace"
},
"699":{
"label_id":"n03884397",
"cn_main_class":"乐器",
"cn_class_name":"排笛",
"en_class_name":"panpipe, pandean pipe, syrinx"
},
"700":{
"label_id":"n03887697",
"cn_main_class":"纸巾",
"cn_class_name":"纸巾",
"en_class_name":"paper towel"
},
"701":{
"label_id":"n03888257",
"cn_main_class":"降落伞",
"cn_class_name":"降落伞",
"en_class_name":"parachute, chute"
},
"702":{
"label_id":"n03888605",
"cn_main_class":"杠",
"cn_class_name":"双杠",
"en_class_name":"parallel bars, bars"
},
"703":{
"label_id":"n03891251",
"cn_main_class":"椅",
"cn_class_name":"公园长凳",
"en_class_name":"park bench"
},
"704":{
"label_id":"n03891332",
"cn_main_class":"停车缴费器",
"cn_class_name":"停车缴费器",
"en_class_name":"parking meter"
},
"705":{
"label_id":"n03895866",
"cn_main_class":"车",
"cn_class_name":"客车",
"en_class_name":"passenger car, coach, carriage"
},
"706":{
"label_id":"n03899768",
"cn_main_class":"院子",
"cn_class_name":"院子",
"en_class_name":"patio, terrace"
},
"707":{
"label_id":"n03902125",
"cn_main_class":"设备",
"cn_class_name":"付费站",
"en_class_name":"pay-phone, pay-station"
},
"708":{
"label_id":"n03903868",
"cn_main_class":"柱",
"cn_class_name":"基座",
"en_class_name":"pedestal, plinth, footstall"
},
"709":{
"label_id":"n03908618",
"cn_main_class":"盒",
"cn_class_name":"铅笔盒",
"en_class_name":"pencil box, pencil case"
},
"710":{
"label_id":"n03908714",
"cn_main_class":"卷笔刀",
"cn_class_name":"卷笔刀",
"en_class_name":"pencil sharpener"
},
"711":{
"label_id":"n03916031",
"cn_main_class":"香水",
"cn_class_name":"香水",
"en_class_name":"perfume, essence"
},
"712":{
"label_id":"n03920288",
"cn_main_class":"培养皿",
"cn_class_name":"培养皿",
"en_class_name":"Petri dish"
},
"713":{
"label_id":"n03924679",
"cn_main_class":"打印机",
"cn_class_name":"打印机",
"en_class_name":"photocopier"
},
"714":{
"label_id":"n03929660",
"cn_main_class":"拨片",
"cn_class_name":"吉他拨片",
"en_class_name":"pick, plectrum, plectron"
},
"715":{
"label_id":"n03929855",
"cn_main_class":"帽",
"cn_class_name":"尖顶帽",
"en_class_name":"pickelhaube"
},
"716":{
"label_id":"n03930313",
"cn_main_class":"栅栏",
"cn_class_name":"栅栏",
"en_class_name":"picket fence, paling"
},
"717":{
"label_id":"n03930630",
"cn_main_class":"车",
"cn_class_name":"皮卡",
"en_class_name":"pickup, pickup truck"
},
"718":{
"label_id":"n03933933",
"cn_main_class":"桥",
"cn_class_name":"桥",
"en_class_name":"pier"
},
"719":{
"label_id":"n03935335",
"cn_main_class":"储蓄罐",
"cn_class_name":"储蓄罐",
"en_class_name":"piggy bank, penny bank"
},
"720":{
"label_id":"n03937543",
"cn_main_class":"药瓶",
"cn_class_name":"药瓶",
"en_class_name":"pill bottle"
},
"721":{
"label_id":"n03938244",
"cn_main_class":"枕头",
"cn_class_name":"枕头",
"en_class_name":"pillow"
},
"722":{
"label_id":"n03942813",
"cn_main_class":"乒乓球",
"cn_class_name":"乒乓球",
"en_class_name":"ping-pong ball"
},
"723":{
"label_id":"n03944341",
"cn_main_class":"风车",
"cn_class_name":"风车",
"en_class_name":"pinwheel"
},
"724":{
"label_id":"n03947888",
"cn_main_class":"海盗",
"cn_class_name":"海盗船",
"en_class_name":"pirate, pirate ship"
},
"725":{
"label_id":"n03950228",
"cn_main_class":"壶",
"cn_class_name":"水壶",
"en_class_name":"pitcher, ewer"
},
"726":{
"label_id":"n03954731",
"cn_main_class":"刨",
"cn_class_name":"木工刨",
"en_class_name":"plane, carpenter's plane, woodworking plane"
},
"727":{
"label_id":"n03956157",
"cn_main_class":"风景",
"cn_class_name":"天文馆",
"en_class_name":"planetarium"
},
"728":{
"label_id":"n03958227",
"cn_main_class":"塑料袋",
"cn_class_name":"塑料袋",
"en_class_name":"plastic bag"
},
"729":{
"label_id":"n03961711",
"cn_main_class":"碗架",
"cn_class_name":"碗架",
"en_class_name":"plate rack"
},
"730":{
"label_id":"n03967562",
"cn_main_class":"车",
"cn_class_name":"犁车",
"en_class_name":"plow, plough"
},
"731":{
"label_id":"n03970156",
"cn_main_class":"搋子",
"cn_class_name":"橡皮塞子",
"en_class_name":"plunger, plumber's helper"
},
"732":{
"label_id":"n03976467",
"cn_main_class":"相机",
"cn_class_name":"宝丽来相机",
"en_class_name":"Polaroid camera, Polaroid Land camera"
},
"733":{
"label_id":"n03976657",
"cn_main_class":"杆",
"cn_class_name":"杆",
"en_class_name":"pole"
},
"734":{
"label_id":"n03977966",
"cn_main_class":"车",
"cn_class_name":"警车",
"en_class_name":"police van, police wagon, paddy wagon, patrol wagon, wagon, black Maria"
},
"735":{
"label_id":"n03980874",
"cn_main_class":"披风",
"cn_class_name":"披风",
"en_class_name":"poncho"
},
"736":{
"label_id":"n03982430",
"cn_main_class":"桌球",
"cn_class_name":"桌球",
"en_class_name":"pool table, billiard table, snooker table"
},
"737":{
"label_id":"n03983396",
"cn_main_class":"瓶子",
"cn_class_name":"瓶子",
"en_class_name":"pop bottle, soda bottle"
},
"738":{
"label_id":"n03991062",
"cn_main_class":"盆栽",
"cn_class_name":"盆栽",
"en_class_name":"pot, flowerpot"
},
"739":{
"label_id":"n03992509",
"cn_main_class":"陶艺",
"cn_class_name":"陶艺",
"en_class_name":"potter's wheel"
},
"740":{
"label_id":"n03995372",
"cn_main_class":"电钻",
"cn_class_name":"电钻",
"en_class_name":"power drill"
},
"741":{
"label_id":"n03998194",
"cn_main_class":"地毯",
"cn_class_name":"地毯",
"en_class_name":"prayer rug, prayer mat"
},
"742":{
"label_id":"n04004767",
"cn_main_class":"打印机",
"cn_class_name":"打印机",
"en_class_name":"printer"
},
"743":{
"label_id":"n04005630",
"cn_main_class":"监狱",
"cn_class_name":"监狱",
"en_class_name":"prison, prison house"
},
"744":{
"label_id":"n04008634",
"cn_main_class":"导弹",
"cn_class_name":"导弹",
"en_class_name":"projectile, missile"
},
"745":{
"label_id":"n04009552",
"cn_main_class":"投影仪",
"cn_class_name":"投影仪",
"en_class_name":"projector"
},
"746":{
"label_id":"n04019541",
"cn_main_class":"球",
"cn_class_name":"冰球",
"en_class_name":"puck, hockey puck"
},
"747":{
"label_id":"n04023962",
"cn_main_class":"拳击袋",
"cn_class_name":"拳击袋",
"en_class_name":"punching bag, punch bag, punching ball, punchball"
},
"748":{
"label_id":"n04026417",
"cn_main_class":"手提袋",
"cn_class_name":"手提袋",
"en_class_name":"purse"
},
"749":{
"label_id":"n04033901",
"cn_main_class":"羽毛笔",
"cn_class_name":"羽毛笔",
"en_class_name":"quill, quill pen"
},
"750":{
"label_id":"n04033995",
"cn_main_class":"被子",
"cn_class_name":"被子",
"en_class_name":"quilt, comforter, comfort, puff"
},
"751":{
"label_id":"n04037443",
"cn_main_class":"车",
"cn_class_name":"赛车",
"en_class_name":"racer, race car, racing car"
},
"752":{
"label_id":"n04039381",
"cn_main_class":"球拍",
"cn_class_name":"球拍",
"en_class_name":"racket, racquet"
},
"753":{
"label_id":"n04040759",
"cn_main_class":"加热器",
"cn_class_name":"加热器",
"en_class_name":"radiator"
},
"754":{
"label_id":"n04041544",
"cn_main_class":"无线电",
"cn_class_name":"无线电",
"en_class_name":"radio, wireless"
},
"755":{
"label_id":"n04044716",
"cn_main_class":"卫星接收器",
"cn_class_name":"卫星接收器",
"en_class_name":"radio telescope, radio reflector"
},
"756":{
"label_id":"n04049303",
"cn_main_class":"桶",
"cn_class_name":"桶",
"en_class_name":"rain barrel"
},
"757":{
"label_id":"n04065272",
"cn_main_class":"车",
"cn_class_name":"房车",
"en_class_name":"recreational vehicle, RV, R.V."
},
"758":{
"label_id":"n04067472",
"cn_main_class":"卷轴",
"cn_class_name":"卷轴",
"en_class_name":"reel"
},
"759":{
"label_id":"n04069434",
"cn_main_class":"相机",
"cn_class_name":"相机",
"en_class_name":"reflex camera"
},
"760":{
"label_id":"n04070727",
"cn_main_class":"冰箱",
"cn_class_name":"冰箱",
"en_class_name":"refrigerator, icebox"
},
"761":{
"label_id":"n04074963",
"cn_main_class":"遥控器",
"cn_class_name":"遥控器",
"en_class_name":"remote control, remote"
},
"762":{
"label_id":"n04081281",
"cn_main_class":"餐厅",
"cn_class_name":"餐厅",
"en_class_name":"restaurant, eating house, eating place, eatery"
},
"763":{
"label_id":"n04086273",
"cn_main_class":"枪",
"cn_class_name":"手枪",
"en_class_name":"revolver, six-gun, six-shooter"
},
"764":{
"label_id":"n04090263",
"cn_main_class":"枪",
"cn_class_name":"步枪",
"en_class_name":"rifle"
},
"765":{
"label_id":"n04099969",
"cn_main_class":"椅",
"cn_class_name":"摇椅",
"en_class_name":"rocking chair, rocker"
},
"766":{
"label_id":"n04111531",
"cn_main_class":"烤肉炉",
"cn_class_name":"烤肉炉",
"en_class_name":"rotisserie"
},
"767":{
"label_id":"n04116512",
"cn_main_class":"橡皮",
"cn_class_name":"橡皮",
"en_class_name":"rubber eraser, rubber, pencil eraser"
},
"768":{
"label_id":"n04118538",
"cn_main_class":"球",
"cn_class_name":"橄榄球",
"en_class_name":"rugby ball"
},
"769":{
"label_id":"n04118776",
"cn_main_class":"尺",
"cn_class_name":"标尺",
"en_class_name":"rule, ruler"
},
"770":{
"label_id":"n04120489",
"cn_main_class":"鞋",
"cn_class_name":"跑鞋",
"en_class_name":"running shoe"
},
"771":{
"label_id":"n04125021",
"cn_main_class":"保险箱",
"cn_class_name":"保险箱",
"en_class_name":"safe"
},
"772":{
"label_id":"n04127249",
"cn_main_class":"回形针",
"cn_class_name":"回形针",
"en_class_name":"safety pin"
},
"773":{
"label_id":"n04131690",
"cn_main_class":"调料瓶",
"cn_class_name":"调料瓶",
"en_class_name":"saltshaker, salt shaker"
},
"774":{
"label_id":"n04133789",
"cn_main_class":"鞋",
"cn_class_name":"凉鞋",
"en_class_name":"sandal"
},
"775":{
"label_id":"n04136333",
"cn_main_class":"衣",
"cn_class_name":"围裙",
"en_class_name":"sarong"
},
"776":{
"label_id":"n04141076",
"cn_main_class":"乐器",
"cn_class_name":"萨克斯",
"en_class_name":"sax, saxophone"
},
"777":{
"label_id":"n04141327",
"cn_main_class":"剑",
"cn_class_name":"剑",
"en_class_name":"scabbard"
},
"778":{
"label_id":"n04141975",
"cn_main_class":"秤",
"cn_class_name":"秤",
"en_class_name":"scale, weighing machine"
},
"779":{
"label_id":"n04146614",
"cn_main_class":"车",
"cn_class_name":"校车",
"en_class_name":"school bus"
},
"780":{
"label_id":"n04147183",
"cn_main_class":"船",
"cn_class_name":"帆船",
"en_class_name":"schooner"
},
"781":{
"label_id":"n04149813",
"cn_main_class":"记分板",
"cn_class_name":"记分板",
"en_class_name":"scoreboard"
},
"782":{
"label_id":"n04152593",
"cn_main_class":"显示器",
"cn_class_name":"显示器",
"en_class_name":"screen, CRT screen"
},
"783":{
"label_id":"n04153751",
"cn_main_class":"螺丝",
"cn_class_name":"螺丝",
"en_class_name":"screw"
},
"784":{
"label_id":"n04154565",
"cn_main_class":"刀",
"cn_class_name":"螺丝刀",
"en_class_name":"screwdriver"
},
"785":{
"label_id":"n04162706",
"cn_main_class":"安全带",
"cn_class_name":"安全带",
"en_class_name":"seat belt, seatbelt"
},
"786":{
"label_id":"n04179913",
"cn_main_class":"缝纫机",
"cn_class_name":"缝纫机",
"en_class_name":"sewing machine"
},
"787":{
"label_id":"n04192698",
"cn_main_class":"盾牌",
"cn_class_name":"盾牌",
"en_class_name":"shield, buckler"
},
"788":{
"label_id":"n04200800",
"cn_main_class":"鞋店",
"cn_class_name":"鞋店",
"en_class_name":"shoe shop, shoe-shop, shoe store"
},
"789":{
"label_id":"n04201297",
"cn_main_class":"纸拉门",
"cn_class_name":"纸拉门",
"en_class_name":"shoji"
},
"790":{
"label_id":"n04204238",
"cn_main_class":"购物篮",
"cn_class_name":"购物篮",
"en_class_name":"shopping basket"
},
"791":{
"label_id":"n04204347",
"cn_main_class":"车",
"cn_class_name":"购物车",
"en_class_name":"shopping cart"
},
"792":{
"label_id":"n04208210",
"cn_main_class":"铲",
"cn_class_name":"铲子",
"en_class_name":"shovel"
},
"793":{
"label_id":"n04209133",
"cn_main_class":"帽",
"cn_class_name":"淋浴帽",
"en_class_name":"shower cap"
},
"794":{
"label_id":"n04209239",
"cn_main_class":"浴帘",
"cn_class_name":"浴帘",
"en_class_name":"shower curtain"
},
"795":{
"label_id":"n04228054",
"cn_main_class":"滑雪",
"cn_class_name":"滑雪",
"en_class_name":"ski"
},
"796":{
"label_id":"n04229816",
"cn_main_class":"面罩",
"cn_class_name":"滑雪面具",
"en_class_name":"ski mask"
},
"797":{
"label_id":"n04235860",
"cn_main_class":"睡袋",
"cn_class_name":"睡袋",
"en_class_name":"sleeping bag"
},
"798":{
"label_id":"n04238763",
"cn_main_class":"游标卡尺",
"cn_class_name":"游标卡尺",
"en_class_name":"slide rule, slipstick"
},
"799":{
"label_id":"n04239074",
"cn_main_class":"滑动门",
"cn_class_name":"滑动门",
"en_class_name":"sliding door"
},
"800":{
"label_id":"n04243546",
"cn_main_class":"老虎机",
"cn_class_name":"老虎机",
"en_class_name":"slot, one-armed bandit"
},
"801":{
"label_id":"n04251144",
"cn_main_class":"游泳呼吸管",
"cn_class_name":"游泳呼吸管",
"en_class_name":"snorkel"
},
"802":{
"label_id":"n04252077",
"cn_main_class":"滑雪车",
"cn_class_name":"滑雪车",
"en_class_name":"snowmobile"
},
"803":{
"label_id":"n04252225",
"cn_main_class":"铲雪车",
"cn_class_name":"铲雪车",
"en_class_name":"snowplow, snowplough"
},
"804":{
"label_id":"n04254120",
"cn_main_class":"洗手液",
"cn_class_name":"洗手液",
"en_class_name":"soap dispenser"
},
"805":{
"label_id":"n04254680",
"cn_main_class":"足球",
"cn_class_name":"足球",
"en_class_name":"soccer ball"
},
"806":{
"label_id":"n04254777",
"cn_main_class":"袜子",
"cn_class_name":"袜子",
"en_class_name":"sock"
},
"807":{
"label_id":"n04258138",
"cn_main_class":"太阳能板",
"cn_class_name":"太阳能板",
"en_class_name":"solar dish, solar collector, solar furnace"
},
"808":{
"label_id":"n04259630",
"cn_main_class":"帽",
"cn_class_name":"宽边帽",
"en_class_name":"sombrero"
},
"809":{
"label_id":"n04263257",
"cn_main_class":"碗",
"cn_class_name":"汤碗",
"en_class_name":"soup bowl"
},
"810":{
"label_id":"n04264628",
"cn_main_class":"键盘",
"cn_class_name":"键盘",
"en_class_name":"space bar"
},
"811":{
"label_id":"n04265275",
"cn_main_class":"电热器",
"cn_class_name":"电热器",
"en_class_name":"space heater"
},
"812":{
"label_id":"n04266014",
"cn_main_class":"航天飞船",
"cn_class_name":"航天飞船",
"en_class_name":"space shuttle"
},
"813":{
"label_id":"n04270147",
"cn_main_class":"锅铲",
"cn_class_name":"锅铲",
"en_class_name":"spatula"
},
"814":{
"label_id":"n04273569",
"cn_main_class":"船",
"cn_class_name":"快艇",
"en_class_name":"speedboat"
},
"815":{
"label_id":"n04275548",
"cn_main_class":"蜘蛛网",
"cn_class_name":"蜘蛛网",
"en_class_name":"spider web, spider's web"
},
"816":{
"label_id":"n04277352",
"cn_main_class":"毛线",
"cn_class_name":"毛线",
"en_class_name":"spindle"
},
"817":{
"label_id":"n04285008",
"cn_main_class":"车",
"cn_class_name":"跑车",
"en_class_name":"sports car, sport car"
},
"818":{
"label_id":"n04286575",
"cn_main_class":"灯",
"cn_class_name":"聚光灯",
"en_class_name":"spotlight, spot"
},
"819":{
"label_id":"n04296562",
"cn_main_class":"舞台",
"cn_class_name":"舞台",
"en_class_name":"stage"
},
"820":{
"label_id":"n04310018",
"cn_main_class":"车",
"cn_class_name":"蒸汽机车",
"en_class_name":"steam locomotive"
},
"821":{
"label_id":"n04311004",
"cn_main_class":"桥",
"cn_class_name":"拱桥",
"en_class_name":"steel arch bridge"
},
"822":{
"label_id":"n04311174",
"cn_main_class":"乐器",
"cn_class_name":"钢桶",
"en_class_name":"steel drum"
},
"823":{
"label_id":"n04317175",
"cn_main_class":"听诊器",
"cn_class_name":"听诊器",
"en_class_name":"stethoscope"
},
"824":{
"label_id":"n04325704",
"cn_main_class":"披肩",
"cn_class_name":"披肩",
"en_class_name":"stole"
},
"825":{
"label_id":"n04326547",
"cn_main_class":"石墙",
"cn_class_name":"石墙",
"en_class_name":"stone wall"
},
"826":{
"label_id":"n04328186",
"cn_main_class":"秒表",
"cn_class_name":"秒表",
"en_class_name":"stopwatch, stop watch"
},
"827":{
"label_id":"n04330267",
"cn_main_class":"火炉",
"cn_class_name":"火炉",
"en_class_name":"stove"
},
"828":{
"label_id":"n04332243",
"cn_main_class":"滤网",
"cn_class_name":"滤网",
"en_class_name":"strainer"
},
"829":{
"label_id":"n04335435",
"cn_main_class":"车",
"cn_class_name":"有轨电车",
"en_class_name":"streetcar, tram, tramcar, trolley, trolley car"
},
"830":{
"label_id":"n04336792",
"cn_main_class":"担架",
"cn_class_name":"担架",
"en_class_name":"stretcher"
},
"831":{
"label_id":"n04344873",
"cn_main_class":"沙发",
"cn_class_name":"沙发",
"en_class_name":"studio couch, day bed"
},
"832":{
"label_id":"n04346328",
"cn_main_class":"建筑",
"cn_class_name":"佛塔",
"en_class_name":"stupa, tope"
},
"833":{
"label_id":"n04347754",
"cn_main_class":"船",
"cn_class_name":"潜艇",
"en_class_name":"submarine, pigboat, sub, U-boat"
},
"834":{
"label_id":"n04350905",
"cn_main_class":"西装",
"cn_class_name":"西装",
"en_class_name":"suit, suit of clothes"
},
"835":{
"label_id":"n04355338",
"cn_main_class":"日晷",
"cn_class_name":"日晷",
"en_class_name":"sundial"
},
"836":{
"label_id":"n04355933",
"cn_main_class":"墨镜",
"cn_class_name":"墨镜",
"en_class_name":"sunglass"
},
"837":{
"label_id":"n04356056",
"cn_main_class":"墨镜",
"cn_class_name":"墨镜",
"en_class_name":"sunglasses, dark glasses, shades"
},
"838":{
"label_id":"n04357314",
"cn_main_class":"防晒霜",
"cn_class_name":"防晒霜",
"en_class_name":"sunscreen, sunblock, sun blocker"
},
"839":{
"label_id":"n04366367",
"cn_main_class":"桥",
"cn_class_name":"吊桥",
"en_class_name":"suspension bridge"
},
"840":{
"label_id":"n04367480",
"cn_main_class":"拖把",
"cn_class_name":"拖把",
"en_class_name":"swab, swob, mop"
},
"841":{
"label_id":"n04370456",
"cn_main_class":"衣",
"cn_class_name":"运动衫",
"en_class_name":"sweatshirt"
},
"842":{
"label_id":"n04371430",
"cn_main_class":"衣",
"cn_class_name":"泳裤",
"en_class_name":"swimming trunks, bathing trunks"
},
"843":{
"label_id":"n04371774",
"cn_main_class":"秋千",
"cn_class_name":"秋千",
"en_class_name":"swing"
},
"844":{
"label_id":"n04372370",
"cn_main_class":"开关",
"cn_class_name":"开关",
"en_class_name":"switch, electric switch, electrical switch"
},
"845":{
"label_id":"n04376876",
"cn_main_class":"针筒",
"cn_class_name":"针筒",
"en_class_name":"syringe"
},
"846":{
"label_id":"n04380533",
"cn_main_class":"台灯",
"cn_class_name":"台灯",
"en_class_name":"table lamp"
},
"847":{
"label_id":"n04389033",
"cn_main_class":"坦克",
"cn_class_name":"坦克",
"en_class_name":"tank, army tank, armored combat vehicle, armoured combat vehicle"
},
"848":{
"label_id":"n04392985",
"cn_main_class":"磁带播放器",
"cn_class_name":"磁带播放器",
"en_class_name":"tape player"
},
"849":{
"label_id":"n04398044",
"cn_main_class":"茶壶",
"cn_class_name":"茶壶",
"en_class_name":"teapot"
},
"850":{
"label_id":"n04399382",
"cn_main_class":"泰迪熊",
"cn_class_name":"泰迪熊",
"en_class_name":"teddy, teddy bear"
},
"851":{
"label_id":"n04404412",
"cn_main_class":"电视",
"cn_class_name":"电视",
"en_class_name":"television, television system"
},
"852":{
"label_id":"n04409515",
"cn_main_class":"网球",
"cn_class_name":"网球",
"en_class_name":"tennis ball"
},
"853":{
"label_id":"n04417672",
"cn_main_class":"茅草",
"cn_class_name":"茅草",
"en_class_name":"thatch, thatched roof"
},
"854":{
"label_id":"n04418357",
"cn_main_class":"幕布",
"cn_class_name":"幕布",
"en_class_name":"theater curtain, theatre curtain"
},
"855":{
"label_id":"n04423845",
"cn_main_class":"指套",
"cn_class_name":"指套",
"en_class_name":"thimble"
},
"856":{
"label_id":"n04428191",
"cn_main_class":"车",
"cn_class_name":"脱粒机",
"en_class_name":"thresher, thrasher, threshing machine"
},
"857":{
"label_id":"n04429376",
"cn_main_class":"椅",
"cn_class_name":"王座",
"en_class_name":"throne"
},
"858":{
"label_id":"n04435653",
"cn_main_class":"瓦屋顶",
"cn_class_name":"瓦屋顶",
"en_class_name":"tile roof"
},
"859":{
"label_id":"n04442312",
"cn_main_class":"面包机",
"cn_class_name":"面包机",
"en_class_name":"toaster"
},
"860":{
"label_id":"n04443257",
"cn_main_class":"烟酒店",
"cn_class_name":"烟酒店",
"en_class_name":"tobacco shop, tobacconist shop, tobacconist"
},
"861":{
"label_id":"n04447861",
"cn_main_class":"马桶",
"cn_class_name":"马桶",
"en_class_name":"toilet seat"
},
"862":{
"label_id":"n04456115",
"cn_main_class":"火炬",
"cn_class_name":"火炬",
"en_class_name":"torch"
},
"863":{
"label_id":"n04458633",
"cn_main_class":"图腾",
"cn_class_name":"图腾",
"en_class_name":"totem pole"
},
"864":{
"label_id":"n04461696",
"cn_main_class":"车",
"cn_class_name":"拖车",
"en_class_name":"tow truck, tow car, wrecker"
},
"865":{
"label_id":"n04462240",
"cn_main_class":"玩具店",
"cn_class_name":"玩具店",
"en_class_name":"toyshop"
},
"866":{
"label_id":"n04465501",
"cn_main_class":"车",
"cn_class_name":"拖拉机",
"en_class_name":"tractor"
},
"867":{
"label_id":"n04467665",
"cn_main_class":"车",
"cn_class_name":"无轨电车",
"en_class_name":"trailer truck, tractor trailer, trucking rig, rig, articulated lorry, semi"
},
"868":{
"label_id":"n04476259",
"cn_main_class":"碟子",
"cn_class_name":"碟子",
"en_class_name":"tray"
},
"869":{
"label_id":"n04479046",
"cn_main_class":"衣",
"cn_class_name":"风衣",
"en_class_name":"trench coat"
},
"870":{
"label_id":"n04482393",
"cn_main_class":"车",
"cn_class_name":"三轮车",
"en_class_name":"tricycle, trike, velocipede"
},
"871":{
"label_id":"n04483307",
"cn_main_class":"船",
"cn_class_name":"三体帆船",
"en_class_name":"trimaran"
},
"872":{
"label_id":"n04485082",
"cn_main_class":"三脚架",
"cn_class_name":"三脚架",
"en_class_name":"tripod"
},
"873":{
"label_id":"n04486054",
"cn_main_class":"建筑",
"cn_class_name":"凯旋门",
"en_class_name":"triumphal arch"
},
"874":{
"label_id":"n04487081",
"cn_main_class":"车",
"cn_class_name":"无轨电车",
"en_class_name":"trolleybus, trolley coach, trackless trolley"
},
"875":{
"label_id":"n04487394",
"cn_main_class":"乐器",
"cn_class_name":"长号",
"en_class_name":"trombone"
},
"876":{
"label_id":"n04493381",
"cn_main_class":"浴缸",
"cn_class_name":"浴缸",
"en_class_name":"tub, vat"
},
"877":{
"label_id":"n04501370",
"cn_main_class":"旋转门",
"cn_class_name":"旋转门",
"en_class_name":"turnstile"
},
"878":{
"label_id":"n04505470",
"cn_main_class":"打字机",
"cn_class_name":"打字机",
"en_class_name":"typewriter keyboard"
},
"879":{
"label_id":"n04507155",
"cn_main_class":"伞",
"cn_class_name":"伞",
"en_class_name":"umbrella"
},
"880":{
"label_id":"n04509417",
"cn_main_class":"车",
"cn_class_name":"独轮车",
"en_class_name":"unicycle, monocycle"
},
"881":{
"label_id":"n04515003",
"cn_main_class":"乐器",
"cn_class_name":"直立钢琴",
"en_class_name":"upright, upright piano"
},
"882":{
"label_id":"n04517823",
"cn_main_class":"吸尘器",
"cn_class_name":"吸尘器",
"en_class_name":"vacuum, vacuum cleaner"
},
"883":{
"label_id":"n04522168",
"cn_main_class":"花瓶",
"cn_class_name":"花瓶",
"en_class_name":"vase"
},
"884":{
"label_id":"n04523525",
"cn_main_class":"保险库",
"cn_class_name":"保险库",
"en_class_name":"vault"
},
"885":{
"label_id":"n04525038",
"cn_main_class":"天鹅绒",
"cn_class_name":"天鹅绒",
"en_class_name":"velvet"
},
"886":{
"label_id":"n04525305",
"cn_main_class":"自动售货机",
"cn_class_name":"自动售货机",
"en_class_name":"vending machine"
},
"887":{
"label_id":"n04532106",
"cn_main_class":"礼服",
"cn_class_name":"礼服",
"en_class_name":"vestment"
},
"888":{
"label_id":"n04532670",
"cn_main_class":"桥",
"cn_class_name":"高架桥",
"en_class_name":"viaduct"
},
"889":{
"label_id":"n04536866",
"cn_main_class":"乐器",
"cn_class_name":"小提琴",
"en_class_name":"violin, fiddle"
},
"890":{
"label_id":"n04540053",
"cn_main_class":"球",
"cn_class_name":"排球",
"en_class_name":"volleyball"
},
"891":{
"label_id":"n04542943",
"cn_main_class":"煎饼锅",
"cn_class_name":"煎饼锅",
"en_class_name":"waffle iron"
},
"892":{
"label_id":"n04548280",
"cn_main_class":"挂钟",
"cn_class_name":"挂钟",
"en_class_name":"wall clock"
},
"893":{
"label_id":"n04548362",
"cn_main_class":"钱包",
"cn_class_name":"钱包",
"en_class_name":"wallet, billfold, notecase, pocketbook"
},
"894":{
"label_id":"n04550184",
"cn_main_class":"柜",
"cn_class_name":"柜子",
"en_class_name":"wardrobe, closet, press"
},
"895":{
"label_id":"n04552348",
"cn_main_class":"飞机",
"cn_class_name":"战机",
"en_class_name":"warplane, military plane"
},
"896":{
"label_id":"n04553703",
"cn_main_class":"洗手盆",
"cn_class_name":"洗手盆",
"en_class_name":"washbasin, handbasin, washbowl, lavabo, wash-hand basin"
},
"897":{
"label_id":"n04554684",
"cn_main_class":"洗衣机",
"cn_class_name":"洗衣机",
"en_class_name":"washer, automatic washer, washing machine"
},
"898":{
"label_id":"n04557648",
"cn_main_class":"水瓶",
"cn_class_name":"水瓶",
"en_class_name":"water bottle"
},
"899":{
"label_id":"n04560804",
"cn_main_class":"水壶",
"cn_class_name":"水壶",
"en_class_name":"water jug"
},
"900":{
"label_id":"n04562935",
"cn_main_class":"水塔",
"cn_class_name":"水塔",
"en_class_name":"water tower"
},
"901":{
"label_id":"n04579145",
"cn_main_class":"水壶",
"cn_class_name":"水壶",
"en_class_name":"whiskey jug"
},
"902":{
"label_id":"n04579432",
"cn_main_class":"哨子",
"cn_class_name":"哨子",
"en_class_name":"whistle"
},
"903":{
"label_id":"n04584207",
"cn_main_class":"头发",
"cn_class_name":"头发",
"en_class_name":"wig"
},
"904":{
"label_id":"n04589890",
"cn_main_class":"窗户",
"cn_class_name":"窗户",
"en_class_name":"window screen"
},
"905":{
"label_id":"n04590129",
"cn_main_class":"百叶窗",
"cn_class_name":"百叶窗",
"en_class_name":"window shade"
},
"906":{
"label_id":"n04591157",
"cn_main_class":"领带",
"cn_class_name":"领带",
"en_class_name":"Windsor tie"
},
"907":{
"label_id":"n04591713",
"cn_main_class":"酒瓶",
"cn_class_name":"酒瓶",
"en_class_name":"wine bottle"
},
"908":{
"label_id":"n04592741",
"cn_main_class":"翼",
"cn_class_name":"翼",
"en_class_name":"wing"
},
"909":{
"label_id":"n04596742",
"cn_main_class":"炒锅",
"cn_class_name":"炒锅",
"en_class_name":"wok"
},
"910":{
"label_id":"n04597913",
"cn_main_class":"勺子",
"cn_class_name":"勺子",
"en_class_name":"wooden spoon"
},
"911":{
"label_id":"n04599235",
"cn_main_class":"毛线",
"cn_class_name":"毛线",
"en_class_name":"wool, woolen, woollen"
},
"912":{
"label_id":"n04604644",
"cn_main_class":"栅栏",
"cn_class_name":"栅栏",
"en_class_name":"worm fence, snake fence, snake-rail fence, Virginia fence"
},
"913":{
"label_id":"n04606251",
"cn_main_class":"船",
"cn_class_name":"沉船",
"en_class_name":"wreck"
},
"914":{
"label_id":"n04612504",
"cn_main_class":"船",
"cn_class_name":"帆船",
"en_class_name":"yawl"
},
"915":{
"label_id":"n04613696",
"cn_main_class":"风景",
"cn_class_name":"蒙古包",
"en_class_name":"yurt"
},
"916":{
"label_id":"n06359193",
"cn_main_class":"网页",
"cn_class_name":"网站",
"en_class_name":"web site, website, internet site, site"
},
"917":{
"label_id":"n06596364",
"cn_main_class":"漫画书",
"cn_class_name":"漫画书",
"en_class_name":"comic book"
},
"918":{
"label_id":"n06785654",
"cn_main_class":"填字游戏",
"cn_class_name":"填字游戏",
"en_class_name":"crossword puzzle, crossword"
},
"919":{
"label_id":"n06794110",
"cn_main_class":"交通标志",
"cn_class_name":"交通标志",
"en_class_name":"street sign"
},
"920":{
"label_id":"n06874185",
"cn_main_class":"交通灯",
"cn_class_name":"交通灯",
"en_class_name":"traffic light, traffic signal, stoplight"
},
"921":{
"label_id":"n07248320",
"cn_main_class":"书",
"cn_class_name":"书套",
"en_class_name":"book jacket, dust cover, dust jacket, dust wrapper"
},
"922":{
"label_id":"n07565083",
"cn_main_class":"菜单",
"cn_class_name":"菜单",
"en_class_name":"menu"
},
"923":{
"label_id":"n07579787",
"cn_main_class":"碟子",
"cn_class_name":"碟子",
"en_class_name":"plate"
},
"924":{
"label_id":"n07583066",
"cn_main_class":"鳄梨酱",
"cn_class_name":"鳄梨酱",
"en_class_name":"guacamole"
},
"925":{
"label_id":"n07584110",
"cn_main_class":"汤",
"cn_class_name":"汤",
"en_class_name":"consomme"
},
"926":{
"label_id":"n07590611",
"cn_main_class":"火锅",
"cn_class_name":"火锅",
"en_class_name":"hot pot, hotpot"
},
"927":{
"label_id":"n07613480",
"cn_main_class":"蛋糕",
"cn_class_name":"蛋糕",
"en_class_name":"trifle"
},
"928":{
"label_id":"n07614500",
"cn_main_class":"冰激凌",
"cn_class_name":"冰淇淋",
"en_class_name":"ice cream, icecream"
},
"929":{
"label_id":"n07615774",
"cn_main_class":"冰棍",
"cn_class_name":"冰棍",
"en_class_name":"ice lolly, lolly, lollipop, popsicle"
},
"930":{
"label_id":"n07684084",
"cn_main_class":"面包",
"cn_class_name":"法国面包",
"en_class_name":"French loaf"
},
"931":{
"label_id":"n07693725",
"cn_main_class":"甜甜圈",
"cn_class_name":"甜甜圈",
"en_class_name":"bagel, beigel"
},
"932":{
"label_id":"n07695742",
"cn_main_class":"面包",
"cn_class_name":"面包",
"en_class_name":"pretzel"
},
"933":{
"label_id":"n07697313",
"cn_main_class":"汉堡",
"cn_class_name":"汉堡",
"en_class_name":"cheeseburger"
},
"934":{
"label_id":"n07697537",
"cn_main_class":"热狗",
"cn_class_name":"热狗",
"en_class_name":"hotdog, hot dog, red hot"
},
"935":{
"label_id":"n07711569",
"cn_main_class":"菜",
"cn_class_name":"土豆泥",
"en_class_name":"mashed potato"
},
"936":{
"label_id":"n07714571",
"cn_main_class":"菜",
"cn_class_name":"卷心菜",
"en_class_name":"head cabbage"
},
"937":{
"label_id":"n07714990",
"cn_main_class":"菜",
"cn_class_name":"西蓝花",
"en_class_name":"broccoli"
},
"938":{
"label_id":"n07715103",
"cn_main_class":"菜",
"cn_class_name":"花椰菜",
"en_class_name":"cauliflower"
},
"939":{
"label_id":"n07716358",
"cn_main_class":"菜",
"cn_class_name":"西葫芦,小胡瓜",
"en_class_name":"zucchini, courgette"
},
"940":{
"label_id":"n07716906",
"cn_main_class":"菜",
"cn_class_name":"意面南瓜",
"en_class_name":"spaghetti squash"
},
"941":{
"label_id":"n07717410",
"cn_main_class":"菜",
"cn_class_name":"小青南瓜",
"en_class_name":"acorn squash"
},
"942":{
"label_id":"n07717556",
"cn_main_class":"菜",
"cn_class_name":"奶油南瓜",
"en_class_name":"butternut squash"
},
"943":{
"label_id":"n07718472",
"cn_main_class":"菜",
"cn_class_name":"黄瓜",
"en_class_name":"cucumber, cuke"
},
"944":{
"label_id":"n07718747",
"cn_main_class":"菜",
"cn_class_name":"洋蓟",
"en_class_name":"artichoke, globe artichoke"
},
"945":{
"label_id":"n07720875",
"cn_main_class":"菜",
"cn_class_name":"甜椒",
"en_class_name":"bell pepper"
},
"946":{
"label_id":"n07730033",
"cn_main_class":"花",
"cn_class_name":"刺苞菜蓟",
"en_class_name":"cardoon"
},
"947":{
"label_id":"n07734744",
"cn_main_class":"菜",
"cn_class_name":"蘑菇",
"en_class_name":"mushroom"
},
"948":{
"label_id":"n07742313",
"cn_main_class":"水果",
"cn_class_name":"苹果",
"en_class_name":"Granny Smith"
},
"949":{
"label_id":"n07745940",
"cn_main_class":"水果",
"cn_class_name":"草莓",
"en_class_name":"strawberry"
},
"950":{
"label_id":"n07747607",
"cn_main_class":"水果",
"cn_class_name":"橙子",
"en_class_name":"orange"
},
"951":{
"label_id":"n07749582",
"cn_main_class":"水果",
"cn_class_name":"柠檬",
"en_class_name":"lemon"
},
"952":{
"label_id":"n07753113",
"cn_main_class":"水果",
"cn_class_name":"无花果",
"en_class_name":"fig"
},
"953":{
"label_id":"n07753275",
"cn_main_class":"水果",
"cn_class_name":"菠萝",
"en_class_name":"pineapple, ananas"
},
"954":{
"label_id":"n07753592",
"cn_main_class":"水果",
"cn_class_name":"香蕉",
"en_class_name":"banana"
},
"955":{
"label_id":"n07754684",
"cn_main_class":"水果",
"cn_class_name":"菠萝蜜",
"en_class_name":"jackfruit, jak, jack"
},
"956":{
"label_id":"n07760859",
"cn_main_class":"水果",
"cn_class_name":"释迦凤梨",
"en_class_name":"custard apple"
},
"957":{
"label_id":"n07768694",
"cn_main_class":"水果",
"cn_class_name":"石榴",
"en_class_name":"pomegranate"
},
"958":{
"label_id":"n07802026",
"cn_main_class":"草垛",
"cn_class_name":"草垛",
"en_class_name":"haystack"
},
"959":{
"label_id":"n07831146",
"cn_main_class":"菜",
"cn_class_name":"意大利面",
"en_class_name":"carbonara"
},
"960":{
"label_id":"n07836838",
"cn_main_class":"甜品",
"cn_class_name":"巧克力酱",
"en_class_name":"chocolate sauce, chocolate syrup"
},
"961":{
"label_id":"n07860988",
"cn_main_class":"菜",
"cn_class_name":"面团",
"en_class_name":"dough"
},
"962":{
"label_id":"n07871810",
"cn_main_class":"菜",
"cn_class_name":"肉酱",
"en_class_name":"meat loaf, meatloaf"
},
"963":{
"label_id":"n07873807",
"cn_main_class":"菜",
"cn_class_name":"披萨",
"en_class_name":"pizza, pizza pie"
},
"964":{
"label_id":"n07875152",
"cn_main_class":"菜",
"cn_class_name":"派",
"en_class_name":"potpie"
},
"965":{
"label_id":"n07880968",
"cn_main_class":"菜",
"cn_class_name":"玉米煎饼",
"en_class_name":"burrito"
},
"966":{
"label_id":"n07892512",
"cn_main_class":"红酒",
"cn_class_name":"红酒",
"en_class_name":"red wine"
},
"967":{
"label_id":"n07920052",
"cn_main_class":"咖啡",
"cn_class_name":"咖啡",
"en_class_name":"espresso"
},
"968":{
"label_id":"n07930864",
"cn_main_class":"杯",
"cn_class_name":"杯",
"en_class_name":"cup"
},
"969":{
"label_id":"n07932039",
"cn_main_class":"饮料杯",
"cn_class_name":"蛋奶酒",
"en_class_name":"eggnog"
},
"970":{
"label_id":"n09193705",
"cn_main_class":"风景",
"cn_class_name":"高山",
"en_class_name":"alp"
},
"971":{
"label_id":"n09229709",
"cn_main_class":"泡泡",
"cn_class_name":"泡泡",
"en_class_name":"bubble"
},
"972":{
"label_id":"n09246464",
"cn_main_class":"风景",
"cn_class_name":"悬崖",
"en_class_name":"cliff, drop, drop-off"
},
"973":{
"label_id":"n09256479",
"cn_main_class":"风景",
"cn_class_name":"珊瑚",
"en_class_name":"coral reef"
},
"974":{
"label_id":"n09288635",
"cn_main_class":"风景",
"cn_class_name":"喷泉",
"en_class_name":"geyser"
},
"975":{
"label_id":"n09332890",
"cn_main_class":"风景",
"cn_class_name":"湖滨",
"en_class_name":"lakeside, lakeshore"
},
"976":{
"label_id":"n09399592",
"cn_main_class":"风景",
"cn_class_name":"海角",
"en_class_name":"promontory, headland, head, foreland"
},
"977":{
"label_id":"n09421951",
"cn_main_class":"风景",
"cn_class_name":"海滩",
"en_class_name":"sandbar, sand bar"
},
"978":{
"label_id":"n09428293",
"cn_main_class":"风景",
"cn_class_name":"海岸",
"en_class_name":"seashore, coast, seacoast, sea-coast"
},
"979":{
"label_id":"n09468604",
"cn_main_class":"风景",
"cn_class_name":"山谷",
"en_class_name":"valley, vale"
},
"980":{
"label_id":"n09472597",
"cn_main_class":"风景",
"cn_class_name":"火山",
"en_class_name":"volcano"
},
"981":{
"label_id":"n09835506",
"cn_main_class":"人",
"cn_class_name":"棒球运动员",
"en_class_name":"ballplayer, baseball player"
},
"982":{
"label_id":"n10148035",
"cn_main_class":"人",
"cn_class_name":"新郎",
"en_class_name":"groom, bridegroom"
},
"983":{
"label_id":"n10565667",
"cn_main_class":"人",
"cn_class_name":"潜水员",
"en_class_name":"scuba diver"
},
"984":{
"label_id":"n11879895",
"cn_main_class":"菜",
"cn_class_name":"油菜籽",
"en_class_name":"rapeseed"
},
"985":{
"label_id":"n11939491",
"cn_main_class":"花",
"cn_class_name":"雏菊",
"en_class_name":"daisy"
},
"986":{
"label_id":"n12057211",
"cn_main_class":"花",
"cn_class_name":"小花兰",
"en_class_name":"yellow lady's slipper, yellow lady-slipper, Cypripedium calceolus, Cypripedium parviflorum"
},
"987":{
"label_id":"n12144580",
"cn_main_class":"菜",
"cn_class_name":"玉米",
"en_class_name":"corn"
},
"988":{
"label_id":"n12267677",
"cn_main_class":"水果",
"cn_class_name":"橡子",
"en_class_name":"acorn"
},
"989":{
"label_id":"n12620546",
"cn_main_class":"树",
"cn_class_name":"玫瑰果",
"en_class_name":"hip, rose hip, rosehip"
},
"990":{
"label_id":"n12768682",
"cn_main_class":"树",
"cn_class_name":"七叶树",
"en_class_name":"buckeye, horse chestnut, conker"
},
"991":{
"label_id":"n12985857",
"cn_main_class":"菌",
"cn_class_name":"珊瑚菌",
"en_class_name":"coral fungus"
},
"992":{
"label_id":"n12998815",
"cn_main_class":"菌",
"cn_class_name":"伞菌",
"en_class_name":"agaric"
},
"993":{
"label_id":"n13037406",
"cn_main_class":"菌",
"cn_class_name":"鹿花菌",
"en_class_name":"gyromitra"
},
"994":{
"label_id":"n13040303",
"cn_main_class":"菌",
"cn_class_name":"腐肉菌",
"en_class_name":"stinkhorn, carrion fungus"
},
"995":{
"label_id":"n13044778",
"cn_main_class":"菌",
"cn_class_name":"地星",
"en_class_name":"earthstar"
},
"996":{
"label_id":"n13052670",
"cn_main_class":"菌",
"cn_class_name":"灰树花",
"en_class_name":"hen-of-the-woods, hen of the woods, Polyporus frondosus, Grifola frondosa"
},
"997":{
"label_id":"n13054560",
"cn_main_class":"菌",
"cn_class_name":"牛肝菌",
"en_class_name":"bolete"
},
"998":{
"label_id":"n13133613",
"cn_main_class":"玉米",
"cn_class_name":"玉米",
"en_class_name":"ear, spike, capitulum"
},
"999":{
"label_id":"n15075141",
"cn_main_class":"卫生纸",
"cn_class_name":"卫生纸",
"en_class_name":"toilet tissue, toilet paper, bathroom tissue"
}
} |
#!/usr/bin/python
#imports
import argparse, re, os
#declare args
parser=argparse.ArgumentParser(description=(
'A limited c preprocessor designed to work with fake_libc_include. '+
'#include, #ifdef, #ifndef, #else, and #endif are supported. '+
'#if and #elif will always evaluate as false. '+
'#define must be of the form "#define X" or "#define X y".'
))
parser.add_argument('-I', action='append', help='include directory')
parser.add_argument('-D', action='append', help='define')
parser.add_argument('input', help='source file to fake preprocess')
args=parser.parse_args()
#helpers
class IncludeHelper:
def __init__(self): self.paths=[]
def add_path(self, path): self.paths.append(path)
def include(self, includer, includee):
paths=self.paths+[os.path.split(os.path.realpath(includer))[0]]
for path in paths:
file_path=os.path.join(path, includee)
if os.path.isfile(file_path):
with open(file_path) as f:
return f.readlines()
class Preprocessor:
def __init__(self):
self.defines={}
self.include_helper=IncludeHelper()
self.in_block_comment=False
self.ifs=[]
def preprocess(self, line, output):
result=[]
#comments
decommented=''
i=0
while i<len(line):
if not self.in_block_comment:
if '//' in line[i:i+2]: break
elif '/*' in line[i:i+2]:
self.in_block_comment=True
i+=1
if not self.in_block_comment: decommented+=line[i]
if self.in_block_comment:
if '*/' in line[i:i+2]:
self.in_block_comment=False
i+=1
i+=1
if not decommented.endswith('\n'): decommented+='\n'
line=decommented
#directives
stripped=line.strip()
if stripped.startswith('#include'):
includee=re.search('["<](.*)[>"]', line).group(1)
result+=self.include_helper.include(args.input, includee)
elif stripped.startswith('#ifdef'):
define=re.search(r'#ifdef\s+(\w+)', stripped).group(1)
self.ifs.append(define in self.defines)
elif stripped.startswith('#ifndef'):
define=re.search(r'#ifndef\s+(\w+)', stripped).group(1)
self.ifs.append(define not in self.defines)
elif stripped.startswith('#if' ): self.ifs.append(False)
elif stripped.startswith('#elif' ): self.ifs[-1]='stay false' if self.ifs[-1] else False
elif stripped.startswith('#else' ): self.ifs[-1]=not self.ifs[-1]
elif stripped.startswith('#endif'): self.ifs.pop()
elif stripped.startswith('#define'):
match=re.search(r'#define\s+(\w+)\s+(\w+)', stripped)
if match: self.defines[match.group(1)]=match.group(2)
else:
match=re.search(r'#define\s+(\w+)', stripped)
self.defines[match.group(1)]=''
elif stripped.startswith('#'): pass
elif all([x==True for x in self.ifs]): output.append(line)
#macros
while len(output):
again=False
for macro in self.defines:
match=re.search(r'(^|\W)('+macro+r')($|\W)', output[-1])
if match:
i=match.start(2)
line=output[-1]
output[-1]=line[:i]+self.defines[macro]+line[i+len(macro):]
again=True
break
if not again: break
return result
#declare variables
preprocessor=Preprocessor()
output=[]
#process args
if args.I:
for path in args.I: preprocessor.include_helper.add_path(path)
if args.D:
for d in args.D: preprocessor.defines[d]=''
#main
with open(args.input) as input_file: lines=input_file.readlines()
while len(lines): lines=preprocessor.preprocess(lines[0], output)+lines[1:]
print(''.join(output))
|
# -*- coding: utf-8 -*-
import enum
import math
import sqlalchemy
from flask_admin.babel import gettext
from flask_babelex import lazy_gettext
from portal.cache import cache
from portal.models import db
from portal.permission.models import Permission
from portal.user import RolesEnum
from portal.utils import ranges
from sqlalchemy.ext.hybrid import hybrid_property
from sqlalchemy.sql import expression, func
u = lambda s: unicode(s, 'utf-8') # noqa
association_table = db.Table(
'account_vps',
db.Column('account_id', db.Integer, db.ForeignKey('accounts.id')),
db.Column('vps_id', db.Integer, db.ForeignKey('vps.id'))
)
class AccountStatus(enum.Enum):
UNINITIALIZED = 'uninitialized'
UNASSIGNED = 'unassigned'
RESERVED = 'reserved'
ATTENTION = 'attention'
APPEAL_REQUESTED = 'appeal_requested'
APPEAL_SUBMITTED = 'appeal_submitted'
ACTIVE = 'active'
DISAPPROVED = 'disapproved'
SUSPENDED = 'suspended'
ABANDONED = 'abandoned'
class _AccountStatusHelper(object):
def __init__(self):
self.unactivated_statuses = [AccountStatus.UNINITIALIZED,
AccountStatus.UNASSIGNED,
AccountStatus.RESERVED]
self.bulk = [
(AccountStatus.ATTENTION, u('0_Attention_注意'),
gettext('Account requires attention. Do Not Use.')),
(AccountStatus.APPEAL_REQUESTED, u('1_Appeal-Requested_申述请求'),
gettext('Client requested this account to be appealed.')),
(AccountStatus.APPEAL_SUBMITTED, u('2_Appeal-Submitted_申述已提交'),
gettext('Appeal has been submitted.')),
(AccountStatus.UNINITIALIZED, u('3_Uninitialized_没准备'),
gettext('Account is not ready')),
(AccountStatus.UNASSIGNED, u('4_Unassigned_新号'),
gettext('Account is free for use for anyone')),
(AccountStatus.RESERVED, u('5_Reserved_已分配'),
gettext('Account is already assigned to someone. However, this account has <b>NOT</b> been accessed yet. In the event of an emergency, you may reassign this to somebody else.')), # noqa
(AccountStatus.ACTIVE, u('6_Active_现行'),
gettext('Account has ad approved and is spending.')),
(AccountStatus.DISAPPROVED, u('7_Disapproved_不通过'),
gettext('Account has ad disapproved.')),
(AccountStatus.ABANDONED, u('8_Abandoned_废弃'),
gettext('We no longer want to deal with this account anymore.')),
(AccountStatus.SUSPENDED, u('9_Suspended_挂号'),
gettext('Account is suspended.')),
]
self.mapping = dict()
self.reverse_mapping = dict()
for value, label, desc in self.bulk:
self.mapping[value] = label
self.reverse_mapping[label] = value
def translate(self, status):
return self.mapping[status]
def get_value(self, label):
if not isinstance(label, unicode):
raise TypeError('You must supply unicode instances to this method')
return self.reverse_mapping[label]
def iterall(self):
return self.bulk
def iternew(self):
"""Returns iterator for AccountStatus that are applicable to NEW accounts.
"""
for value, label, desc in self.iterall():
if value in [AccountStatus.UNINITIALIZED, AccountStatus.UNASSIGNED,
AccountStatus.RESERVED, AccountStatus.ACTIVE]:
yield value, label, desc
def is_activated(self, account):
return account.status not in self.unactivated_statuses
AccountStatusHelper = _AccountStatusHelper() # Singleton
def no_none(*args):
return all(v is not None for v in args)
class Account(db.Model):
__tablename__ = 'accounts'
__versioned__ = {
'exclude': ['VPSs']
}
id = db.Column(db.Integer, primary_key=True)
status = db.Column(db.Enum(AccountStatus, name='account_status'),
nullable=False, default=AccountStatus.UNINITIALIZED)
adwords_id = db.Column(db.String(20), nullable=False, unique=True)
nickname = db.Column(db.String(48))
account_budget = db.Column(db.Float())
account_budget_override = db.Column(db.Float())
remaining_account_budget = db.Column(db.Float())
remaining_account_budget_override = db.Column(db.Float())
daily_budget = db.Column(db.Float())
currency = db.Column(db.String(12))
exchange_rate = db.Column(db.Float())
is_unlimited = db.Column(db.Boolean(), server_default=expression.false(),
default=False)
login = db.Column(db.String(48))
password = db.Column(db.String(48))
batch = db.Column(db.String(48))
country = db.Column(db.String(24))
external_comment = db.Column(db.Text())
internal_comment = db.Column(db.Text())
auto_tag_on = db.Column(db.Boolean(), default=False)
VPSs = db.relationship("Vps",
secondary=association_table,
back_populates="accounts")
client_id = db.Column(db.Integer(), db.ForeignKey('users.id', onupdate="cascade"))
client = db.relationship('User', back_populates='accounts')
vendor_id = db.Column(db.Integer(), db.ForeignKey('vendors.id', onupdate="cascade"))
vendor = db.relationship('Vendor', back_populates='accounts')
accesses = db.relationship('Access', back_populates='account')
# We still need this for sorting
updated_at = db.Column(db.DateTime(timezone=True),
server_default=func.now(), onupdate=func.now())
last_visited_by_eve = db.Column(db.DateTime(timezone=True))
def __str__(self):
if self.adwords_id:
return self.adwords_id
return 'Empty Account'
def __repr__(self):
return "%s(%s)" % (self.__class__.__name__, self.id)
def get_account_budget(self):
if self.account_budget_override is not None:
return self.account_budget_override
return self.account_budget
def get_remaining_account_budget(self):
if self.remaining_account_budget_override is not None:
return self.remaining_account_budget_override
return self.remaining_account_budget
@hybrid_property
def days_left(self):
"""Returns the number of days left before the budget exhausts.
Finance dept sorts by days_left asc to alert us so that they can alert us
which accounts that are running out of money. For accounts with budget=0
or empty, we do not want to see them there so we will return a large
number, i.e. 99.
"""
if no_none(self.get_remaining_account_budget(), self.daily_budget) \
and self.daily_budget:
return math.floor(self.get_remaining_account_budget() / self.daily_budget)
else:
return 99
@days_left.expression
def days_left(cls):
return sqlalchemy.func.floor(cls.remaining_account_budget / (cls.daily_budget + 1)) # hack
@property
def percentage_spent(self):
ab, rab = self.get_account_budget(), self.get_remaining_account_budget()
if no_none(ab, rab) and ab:
return 100 * (ab - rab) / ab
@property
def spent(self):
ab, rab = self.get_account_budget(), self.get_remaining_account_budget()
if no_none(ab, rab):
return ab - rab
@hybrid_property
def spent_in_hkd(self):
if no_none(self.spent, self.exchange_rate):
return self.spent * self.exchange_rate
return 0
@spent_in_hkd.expression
def spent_in_hkd(cls):
return (cls.account_budget - cls.remaining_account_budget) * cls.exchange_rate
@property
def daily_budget_in_hkd(self):
if no_none(self.daily_budget, self.exchange_rate):
return self.daily_budget * self.exchange_rate
@property
def remaining_in_hkd(self):
if no_none(self.get_remaining_account_budget(), self.exchange_rate):
return self.get_remaining_account_budget() * self.exchange_rate
@property
@cache.memoize()
def days_to_topup(self):
"""Rather than using inline model form, just reflect this
"""
return self.vendor.days_to_topup
@property
@cache.memoize()
def suspended_on(self):
"""Returns a dt for when suspension occurs. If account is not suspended return None.
"""
for v in self.versions:
if v.status == AccountStatus.SUSPENDED:
return v.updated_at
@property
def clients_allowed(self):
"""Returns a string which shows which clients are allowed.
Not memoizing here because this could be used by other widgets. So it makes sense to use
cache_helper as we are sharing this between different classes.
"""
key = 'clients_allowed-%s' % self.vendor_id
if self.vendor:
ret = cache.get(key)
if not ret:
pems = Permission.query.filter(
Permission.vendor_id == self.vendor_id).order_by(Permission.user_id)
if pems.count():
ret = ranges([p.user_id for p in pems])
else:
ret = lazy_gettext("Vendor permissions not defined.")
cache.set(key, ret)
return ret
return lazy_gettext("Vendor is empty.")
@property
@cache.memoize()
def VPSs_jinja(self):
"""Show only AWS VPSs if there are multiple VPSs.
"""
VPSs = self.VPSs
has_aws_vps = False
pos_aws_vps = 0
for i, vps in enumerate(VPSs):
if vps.provider and vps.provider.upper().startswith('AWS'):
has_aws_vps = True
pos_aws_vps = i
break
if has_aws_vps:
return str(VPSs[pos_aws_vps])
else:
return ", ".join(sorted([str(v) for v in VPSs]))
@property
@cache.memoize()
def created_at(self):
"""Running this operation even after memoization has caused the request to take longer than
30 seconds. Hence, we will only execute this method on the relevant vendors.
"""
VENDORS = [40, 41, 42]
if self.vendor_id in VENDORS:
return self.versions.first().transaction.issued_at.strftime('%m/%d %H:%M')
return ""
A = RolesEnum.ADMIN.value
T = RolesEnum.TECHNICIAN.value
S = RolesEnum.SUPPORT.value
C = RolesEnum.CLIENT.value
class AttributeMeta(object):
def __init__(self, priority, label=None, readable=[], editable=[],
is_list_editable=False, hide_in_list_view=False):
self.priority = priority
self.label = label
self.readable = readable
self.editable = editable
self.is_list_editable = is_list_editable
self.hide_in_list_view = hide_in_list_view
class AttributeManager(object):
def __init__(self):
self.attribute_metas = {
'adwords_id': AttributeMeta(100, gettext('Adwords_id'),
readable=[A, T, S, C], editable=[A, T, S, C]),
'nickname': AttributeMeta(120, gettext('Nickname'),
readable=[A, T, S, C], editable=[A, T, S, C]),
'status': AttributeMeta(130, gettext('Status'),
readable=[A, T, S, C], editable=[A, T, S, C],
is_list_editable=True),
# editable must be []. If not, last_visited_by_eve will be set by the form
# which DROPS the timezone thus resulting in an time offset error
'last_visited_by_eve': AttributeMeta(140, gettext('Last Visited by Eve'),
readable=[A, T, S, C], editable=[]),
'client_id': AttributeMeta(200, gettext('Client ID'),
readable=[A, T, S]),
'client': AttributeMeta(210, gettext('Client Name'),
readable=[A, T, S], editable=[A, T, S]),
'clients_allowed': AttributeMeta(211, gettext('Clients Allowed'),
readable=[A, C, T, S], editable=[]),
'auto_tag_on': AttributeMeta(220, gettext('Is auto_tag ON?'),
readable=[A, T, S, C], editable=[A, T]),
'is_unlimited': AttributeMeta(305, gettext('Is Unlimited?'),
readable=[A, S, C], editable=[A, T]),
'created_at': AttributeMeta(309, gettext('Creation Date'),
readable=[A], editable=[]),
'account_budget': AttributeMeta(310, gettext('Account Budget'),
readable=[A, S, C], editable=[A, T],
is_list_editable=True),
'account_budget_override': AttributeMeta(311, gettext('Account Budget Override'),
readable=[A, S, C], editable=[A],
is_list_editable=True),
'remaining_account_budget': AttributeMeta(320, gettext('Remaining Account Budget'),
readable=[A, S, C], editable=[A],
is_list_editable=True),
'remaining_account_budget_override': AttributeMeta(321, gettext('Remaining Account Budget Override'), # noqa
readable=[A, S, C], editable=[A],
is_list_editable=True),
'daily_budget': AttributeMeta(330, gettext('Daily Budget'),
readable=[A, S, C], editable=[A],
is_list_editable=True),
'percentage_spent': AttributeMeta(340, gettext('Percentage Spent'),
readable=[A, S, C], editable=[]),
'days_left': AttributeMeta(350, gettext('Days Left'),
readable=[A, S, C], editable=[]),
'currency': AttributeMeta(360, gettext('Currency'),
readable=[A, S, C], editable=[A, T]),
'exchange_rate': AttributeMeta(370, gettext('Exchange Rate'),
readable=[A, S, C], editable=[A, T],
is_list_editable=True),
'spent': AttributeMeta(380, gettext('Spent'),
readable=[A, S, C], editable=[]),
'spent_in_hkd': AttributeMeta(390, gettext('Spent (HKD)'),
readable=[A, S, C], editable=[]),
'remaining_in_hkd': AttributeMeta(399, gettext('Remaining (HKD)'),
readable=[A, S, C], editable=[]),
'vendor_id': AttributeMeta(400, gettext('Vendor'),
readable=[A], editable=[A, T],
hide_in_list_view=True),
'vendor': AttributeMeta(401, gettext('Vendor'),
readable=[A], editable=[A, T]),
'days_to_topup': AttributeMeta(402, gettext('Days To Topup'),
readable=[A], editable=[]),
'batch': AttributeMeta(410, gettext('Batch'),
readable=[A, T], editable=[A, T]),
'VPSs': AttributeMeta(500, gettext('VPS'),
readable=[A, T], editable=[A, T]),
'login': AttributeMeta(520, gettext('Login'),
readable=[A, T], editable=[A, T]),
'password': AttributeMeta(522, gettext('Password'),
readable=[A, T], editable=[A, T]),
'external_comment': AttributeMeta(998, gettext('External Comment'),
readable=[], editable=[]),
'internal_comment': AttributeMeta(999, gettext('Internal Comment'),
readable=[A, T, S], editable=[A, T, S]),
}
self._cache = {}
def _get_all_columns(self, attr, role, skip=[], is_list_view=False):
"""Returns ALL the column names that this role can read
"""
cols = {} # { name: priority },
for name, meta in self.attribute_metas.iteritems():
roles = getattr(meta, attr)
if role not in roles:
continue
if is_list_view and meta.hide_in_list_view:
continue
if name in skip:
continue
cols[name] = meta.priority
cols_sorted = sorted(cols.iteritems(), key=lambda t: t[1])
return [t[0] for t in cols_sorted]
def get_all_readable_columns(self, role):
key = 'get_all_readable_columns-%s' % role
if key not in self._cache:
self._cache[key] = self._get_all_columns('readable', role)
return self._cache[key]
def get_all_editable_columns(self, role):
key = 'get_all_editable_columns-%s' % role
if key not in self._cache:
self._cache[key] = self._get_all_columns('editable', role, skip=['vendor_id'])
return self._cache[key]
def get_list_view_columns(self, role):
key = 'get_list_view_columns-%s' % role
if key not in self._cache:
self._cache[key] = self._get_all_columns('readable', role, is_list_view=True)
return self._cache[key]
def get_list_view_editable_columns(self, role):
def _work():
list_editables = set()
for name, meta in self.attribute_metas.iteritems():
if meta.is_list_editable:
list_editables.add(name)
# return the intersection
editables = self.get_list_view_columns(role)
return set(editables) & list_editables
key = 'get_list_view_editable_columns-%s' % role
if key not in self._cache:
self._cache[key] = _work()
return self._cache[key]
def get_list_view_column_labels(self, role):
"""Returns { name: label }
"""
def _work():
ret = {}
for name, meta in self.attribute_metas.iteritems():
ret[name] = meta.label
return ret
key = 'get_list_view_column_labels-%s' % role
if key not in self._cache:
self._cache[key] = _work()
return self._cache[key]
AttributeManagerSingleton = AttributeManager()
|
import csv
import numpy as np
import numpy
import matplotlib.pyplot as plt
import numpy as np
from sklearn import datasets, linear_model
from sklearn.metrics import mean_squared_error, r2_score
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.neural_network import MLPRegressor
from numpy.ma.core import ravel
from sklearn.metrics import classification_report,confusion_matrix
results=np.zeros([24,31])
results2=[]
data=[]
i=0
j=1
with open("user.csv") as csvfile:
reader = csv.reader(csvfile) # change contents to floats
for row in reader: # each row is a list
data.append(row)
fvs_lexical = np.zeros((24, 56), np.float64)
k=0
z=0
while(k<24):
while(z<56):
fvs_lexical[k, z] = data[k][z]
z+=1
z=0
k+=1
data2=[]
with open("agr.csv") as csvfile2:
reader2 = csv.reader(csvfile2) # change contents to floats
for row in reader2: # each row is a list
data2.append(row)
# print(data2)
fvs_lexical2 = np.zeros((24, 1), np.float64)
kk=0
zz=0
while(kk<24):
while(zz<1):
fvs_lexical2[kk, zz] = data2[kk][zz]
zz+=1
zz=0
kk+=1
# print(fvs_lexical2)
# print(fvs_lexical)
data3=[]
with open("test.csv") as csvfile3:
reader3 = csv.reader(csvfile3) # change contents to floats
for row in reader3: # each row is a list
data3.append(row)
# print(row)
fvs_lexical3 = np.zeros((1, 56), np.float64)
kkk=0
zzz=0
while(kkk<1):
while(zzz<56):
fvs_lexical3[kkk, zzz] = data3[kkk][zzz]
zzz+=1
zzz=0
kkk+=1
# print(fvs_lexical3)
wine = pd.read_csv('user.csv')
yy=pd.read_csv('agr.csv')
X = wine
y = ravel(yy)
# print(y)
X_train, X_test, y_train, y_test = train_test_split(X, y)
scaler = StandardScaler()
scaler.fit(X_train)
StandardScaler(copy=True, with_mean=True, with_std=True)
X_train = scaler.transform(X_train)
# print(X_train)
X_test = scaler.transform(X_test)
mlp = MLPRegressor(hidden_layer_sizes=(10,10,10),max_iter=6000)
mlp.fit(X_train,y_train)
predictions = mlp.predict(X_test)
# # print(X_test)
# print(mlp.n_iter_)
testing_scalar2=scaler.transform(fvs_lexical3)
testing2=mlp.predict(testing_scalar2)
# print(confusion_matrix(X_test,testing))
x=np.array([])
x=y_test
norm2 = x/np.linalg.norm(x, ord=np.inf, axis=0, keepdims=True)
# print(norm2)
pred=np.array([])
pred=predictions
norm3 = pred/np.linalg.norm(pred, ord=np.inf, axis=0, keepdims=True)
# print(norm3)
print(mean_squared_error(norm2, norm3))
print(testing2)
|
import pandas as pd
import lib.dataparse
import sys
from itertools import groupby
def triangle_infidelity_1():
df2 = pd.read_excel("triangle-infidelity.xls")
df = lib.dataparse.dataframe().reset_index()
dfp = df[df["theme"] == u"extramarital affair"]
df2.set_index("sid", inplace=True)
dfp.set_index("sid", inplace=True)
print(dfp.columns)
dfp = dfp[["title", "story_def", "weight", "motivation"]].rename(
columns={"weight": "eaweight", "motivation": "eamot"})
dfr = df2.join(dfp, how="outer")
print(dfr)
dfr.to_excel("temp.xls")
def alien_morals_list():
themes = ("alien morals", "alien customs", "conflict of moral codes", "cultural differences")
df = makelist(themes, "temp.txt")
print(df)
df.to_excel("temp.txt")
def makelist(themes):
df = lib.dataparse.dataframe().reset_index()
return df[df["theme"].isin(themes)]
def makejoined(dfs):
if len(dfs) > 1:
for idx, df in list(enumerate(dfs)):
if idx > 0:
df = df[["sid", "theme", "weight", "motivation"]]
df = df.rename(columns={"theme": "theme" + str(idx), "weight": "weight" + str(idx), "motivation": "motivation" + str(idx)})
df.set_index("sid", inplace=True)
dfs[idx] = df
dfacc = dfs[0]
for df in dfs[1:]:
dfacc = dfacc.join(df, on=["sid"], how="outer")
return dfacc
def parse_themes(args):
"""
Args:
args: sys.argv, or segment thereof
Returns:
list of themes
"""
themeobjs = list(lib.dataparse.read_themes_from_db())
themes = []
flag = ""
for arg in args:
if arg.startswith("-"):
flag = arg
else:
if flag == "-co":
print("children of of '%s':" % arg)
for obj in themeobjs:
if arg in obj.list_parents():
themes.append(obj.name)
print(" + %s" % obj.name)
else:
themes.append(arg)
print("+ %s" % arg)
flag = ""
return sorted(set(themes))
def main():
args = sys.argv[sys.argv.index("util.surgery")+1:]
if len(args) <= 1:
raise ValueError("not enough arguments")
filename = args[-1]
themes = parse_themes(args[:-1])
dfs = [makelist(tl) for k, tl in groupby(themes, lambda x: x == "--") if not k]
df = makejoined(dfs)
print(df)
df.to_excel(filename)
|
#!/usr/bin/python3.6
""" For every image from the test set, searches for the top-20 closest images from the train set. """
import os
import sys
from glob import glob
from typing import Iterator, Iterable, List, Optional, Tuple
import numpy as np
import pandas as pd
import faiss
from sklearn.model_selection import train_test_split
from scipy.stats import describe
from tqdm import tqdm
from debug import dprint
K = 20
KNN_PREDICTS_DIR = '../predicts'
USE_GPU = True
USE_COSINE_DIST = True
DIMS = 2048
def search_against_fragment(train_features: np.ndarray, test_features: np.ndarray) \
-> Tuple[np.ndarray, np.ndarray]:
if USE_GPU:
# build a flat index (CPU)
if USE_COSINE_DIST:
index_flat = faiss.IndexFlat(DIMS, faiss.METRIC_INNER_PRODUCT)
else:
index_flat = faiss.IndexFlatL2(DIMS)
# make it into a GPU index
index_flat = faiss.index_cpu_to_gpu(res, 0, index_flat)
else:
index_flat = faiss.IndexFlatIP(DIMS)
index_flat.add(train_features)
print("total size of the database:", index_flat.ntotal)
# print("sanity search...")
# distances, index = index_flat.search(train_features[:10], K) # actual search
# print(index[:10])
# print(distances[:10])
print("searching")
distances, index = index_flat.search(test_features, K) # actual search
dprint(index)
dprint(distances)
dprint(describe(index.flatten()))
dprint(describe(distances.flatten()))
return index, distances
def merge_results(index1: np.ndarray, distances1: np.ndarray, index2: np.ndarray,
distances2: np.ndarray) -> Tuple[np.ndarray, np.ndarray]:
""" Returns top-K of two sets. """
print("merging results")
assert index1.shape == distances1.shape and index2.shape == distances2.shape
assert index1.shape[1] == index2.shape[1]
joint_indices = np.hstack((index1, index2))
joint_distances = np.hstack((distances1, distances2))
print("joint_indices", joint_indices.shape, "joint_distances", joint_distances.shape)
assert joint_indices.shape == joint_distances.shape
best_indices = np.zeros((index1.shape[0], K), dtype=int)
best_distances = np.zeros((index1.shape[0], K), dtype=np.float32)
for sample in range(joint_indices.shape[0]):
if not USE_COSINE_DIST:
closest_indices = np.argsort(joint_distances[sample])
else:
closest_indices = np.argsort(-joint_distances[sample])
closest_indices = closest_indices[:K]
best_indices[sample] = joint_indices[sample, closest_indices]
best_distances[sample] = joint_distances[sample, closest_indices]
print("best_indices", best_indices.shape, "best_distances", best_distances.shape)
dprint(best_indices)
dprint(best_distances)
dprint(describe(best_indices.flatten()))
return best_indices, best_distances
def load_features(filename: str) -> np.ndarray:
features = np.load(filename)
features = features.reshape(features.shape[0], -1)
if USE_COSINE_DIST:
features /= (np.linalg.norm(features, axis=1, keepdims=True) + 1e-8)
return features
class DatasetIter(Iterator[np.ndarray]):
''' Iterator which remembers previous position. '''
def __init__(self, dataset_parts: 'DatasetParts') -> None:
self.files = dataset_parts.files
self.train_files = iter(dataset_parts.files)
# self.subset_mask = dataset_parts.subset_mask
self.base_offset = 0
def __next__(self) -> np.ndarray:
features = load_features(next(self.train_files))
fragment_size = features.shape[0]
# if self.subset_mask is not None:
# part_mask = self.subset_mask[self.base_offset : self.base_offset + fragment_size]
# features = features[part_mask]
self.base_offset += fragment_size
return features
class DatasetParts(Iterable[DatasetIter]):
''' A collection that reads features by parts. '''
def __init__(self, df: pd.DataFrame, # subset_mask: Optional[pd.Series],
files: List[str]) -> None:
self.df = df
self.files = files
# self.subset_mask = subset_mask
def __iter__(self) -> DatasetIter:
return DatasetIter(self)
def __len__(self) -> int:
return len(self.files)
if __name__ == "__main__":
if len(sys.argv) < 4 or sys.argv[1] not in ['--train', '--test']:
print(f'usage: {sys.argv[0]} --train train_features_1.npy ...')
print(f'or {sys.argv[0]} --test test_features.npy train_features_1.npy ...')
sys.exit()
predict_test = sys.argv[1] == '--test'
test_fname = sys.argv[2] if predict_test else ''
train_fnames = sys.argv[3:] if predict_test else sys.argv[2:]
if not os.path.exists(KNN_PREDICTS_DIR):
os.makedirs(KNN_PREDICTS_DIR)
model_name = os.path.splitext(os.path.basename(train_fnames[0]))[0]
assert model_name.startswith('train_')
assert model_name.endswith('_part00')
model_name = model_name[6:-7]
dataset = 'test' if predict_test else 'train'
type = 'cosine' if USE_COSINE_DIST else 'euclidean'
result_fname = os.path.join(KNN_PREDICTS_DIR,
f'dist_{model_name}_{dataset}_{type}.npz')
print("will save results to", result_fname)
''' Algorithm:
1. define level-2 train and validation sets
2. for every sample from validation set, find K nearest samples from the train set
3. make a prediction about classes
4. calculate the metric
5. take full train set
6. for every sample from the test set, find K nearest samples from the full train set
7. make a prediction
8. generate submission
'''
# 1. define level-2 train and validation sets
if not os.path.exists(KNN_PREDICTS_DIR):
os.makedirs(KNN_PREDICTS_DIR)
full_train_df = pd.read_csv('../data/train.csv')
# # train_df = pd.read_csv('../data/splits/50_samples_18425_classes_fold_0_train.csv')
# train_df = pd.read_csv('../data/splits/10_samples_92740_classes_fold_0_train.csv')
# train_mask = ~full_train_df.id.isin(train_df.id)
# dprint(train_mask.shape)
# dprint(sum(train_mask))
if predict_test:
test_df = pd.read_csv('../data/test.csv')
# 2. for every sample from validation set, find K nearest samples from the train set
if USE_GPU:
print("initializing CUDA")
res = faiss.StandardGpuResources()
train_dataset_parts = DatasetParts(full_train_df, train_fnames)
test_dataset_parts = DatasetParts(test_df, [test_fname]) \
if predict_test else train_dataset_parts
total_best_indices, total_best_distances = None, None
for i, val_features in enumerate(tqdm(test_dataset_parts, disable=predict_test)):
print('=' * 100)
print('iteration', i)
best_indices, best_distances = None, None
base_index = 0
for train_features in tqdm(train_dataset_parts, disable=not predict_test):
print('-' * 100)
idx, dist = search_against_fragment(train_features, val_features)
idx += base_index
dprint(idx.shape)
dprint(dist.shape)
if best_indices is None:
best_indices, best_distances = idx, dist
else:
best_indices, best_distances = merge_results(best_indices, best_distances, idx, dist)
base_index += train_features.shape[0]
# best_indices = np.delete(best_indices, 0, axis=1)
# best_distances = np.delete(best_distances, 0, axis=1)
dprint(best_indices.shape)
dprint(best_indices)
dprint(best_distances.shape)
dprint(best_distances)
if total_best_indices is None:
total_best_indices, total_best_distances = best_indices, best_distances
else:
total_best_indices = np.vstack((total_best_indices, best_indices))
total_best_distances = np.vstack((total_best_distances, best_distances))
print("writing results to", result_fname)
dprint(total_best_indices)
dprint(total_best_distances)
np.savez(result_fname, indices=total_best_indices, distances=total_best_distances)
|
from setuptools import setup
setup(
name='nengo_learn_assoc_mem',
packages=['nengo_learn_assoc_mem'],
version='0.0.1',
author='Terry Stewart',
description='Nengo model of learning an associative memory',
author_email='terry.stewart@gmail.com',
url='https://github.com/tcstewar/nengo_learn_assoc_mem',
license='MIT',
)
|
import simpy
class SimpleFlash(object):
def __init__(self, recorder, confobj = None):
self.recorder = recorder
self.conf = confobj
self.data = {} # ppn -> contents stored in a flash page
def page_read(self, pagenum, cat):
self.recorder.put('physical_read', pagenum, cat)
content = self.data.get(pagenum, None)
return content
def page_write(self, pagenum, cat, data = None):
self.recorder.put('physical_write', pagenum, cat)
if data != None:
self.data[pagenum] = data
def block_erase(self, blocknum, cat):
# print 'block_erase', blocknum, cat
self.recorder.put('phy_block_erase', blocknum, cat)
ppn_start, ppn_end = self.conf.block_to_page_range(blocknum)
for ppn in range(ppn_start, ppn_end):
try:
del self.data[ppn]
except KeyError:
# ignore key error
pass
class Flash(object):
def __init__(self, recorder, confobj = None, globalhelper = None):
self.recorder = recorder
# If you enable store data, you must provide confobj
self.store_data = True # whether store data to self.data[]
self.data = {} # ppn -> contents stored in a flash page
self.conf = confobj
def page_read(self, pagenum, cat):
self.recorder.count_me(cat, 'physical_read')
if self.store_data == True:
content = self.data.get(pagenum, None)
return content
def page_write(self, pagenum, cat, data = None):
self.recorder.count_me(cat, 'physical_write')
# we only put data to self.data when the caller specify data
if self.store_data == True:
if data != None:
self.data[pagenum] = data
def block_erase(self, blocknum, cat):
# print 'block_erase', blocknum, cat
self.recorder.count_me(cat, 'phy_block_erase')
if self.store_data == True:
ppn_start, ppn_end = self.conf.block_to_page_range(blocknum)
for ppn in range(ppn_start, ppn_end):
try:
del self.data[ppn]
except KeyError:
# ignore key error
pass
|
# !/usr/bin/python
# -*- coding: utf-8 -*-
import requests
from workstation.config import WorkstationConfig as config
from utils import logger, BaseCommand
from workstation.decorators import try_except
class CreateUserCommand(BaseCommand):
@try_except
def do_create_user(self, input_string):
self.setup_argparse()
self.parser.add_argument('-u',
dest='username', type=str, help='User username.', required=True)
self.parser.add_argument('-p',
dest='password', type=str, help='User password.', required=True)
# validate arguments
try: args = self.parser.parse_args(input_string)
except ValueError: return
# populate optional fields
logger.info("Please, fill the following optional fields:")
fields = ['first_name', 'last_name', 'email']
optional_args = dict(zip(fields, [None] * len(fields)))
for field_name in fields:
field_value = raw_input("{}: ".format(field_name))
optional_args.setdefault(field_name, field_value)
logger.info("Creating user with {} and {}".format(args, optional_args))
json = {
"username": args.username, "password": args.password
}
json.update(optional_args)
response = requests.post(config.CS_CREATE_USER_URL,
headers=self.context.get('headers'),
json=json)
response = response.json()
if response.get("error"):
logger.error("Error: {}".format(response.get("error")))
return
logger.info(response)
def help_create_user(self):
logger.info("""Create user with given arguments:
-u username: User's new username
-p password: User's new password
[first_name]: User's first name
[last_name]: User's last name
[email]: User's email
Format: $ create-user -u username -p password -t user_type [first_name] [last_name] [email]"
""")
|
#! /usr/bin/env python
# -*- coding: utf-8 -*-
import sys
reload(sys)
sys.setdefaultencoding('utf-8')
import logging
import smtplib
from email.mime.text import MIMEText
from email.utils import COMMASPACE, formatdate
from email.header import Header
import json
def _get_mail_content(warnings):
content = ''
for rule, ret in warnings:
content += u'## 告警内容:\n%s \n\n' % rule['args'].get("title")
content += u'## 告警结果:\n%s \n\n' % str(ret)
content += u'## 告警规则:\n%s \n\n' % json.dumps(rule, indent=4)
content += u'====================\n\n'
return content
def send(warnings,senders):
logging.info("mail send:%s", warnings)
content = _get_mail_content(warnings)
print content
return
rule = warnings[0][0] # 取第一个告警的rule
title = rule['args'].get("title", u"监控告警")
msg = MIMEText(content, 'plain', 'utf-8')
msg['Subject'] = Header(u'监控告警:%s' % title, 'utf-8')
msg["From"] = senders["from"]
msg['To'] = senders["to"][0]
msg['Date'] = formatdate(localtime=True)
try:
server = smtplib.SMTP()
server.connect(senders["smtp_server"])
server.login(senders["smtp_user"], senders["smtp_pass"])
address=senders["smtp_user"]+'<'+senders["smtp_user"]+'@'+senders["mail_postfix"]+'>'
server.sendmail(address,senders["to"][0], msg.as_string())
server.close()
except Exception:
logging.exception('sender.mail send error:%s', warnings)
if __name__ == '__main__':
senders={
"smtp_server": "smtp.163.com",
"smtp_user": "XXXXXXXXX",
"smtp_pass": "XXXXXXXXX",
"mail_postfix":"163.com",
"from": "XXXXXXXXX@163.com",
"to": ["XXXXXXXXX@qq.com"]
}
bin=[
(
{
'fail_count': 2,
u'args': {
u'title': u'service have a error',
u'target': u'http://www.baidu.com'
},
u'type': u'curl',
'id': 1,
'keep_fail_count': 0
},
'execute timeout'
)
]
send(bin,senders)
|
"""
Nada para ver aqui. Siga em frente...
"""
import unittest
def generic_assignment_tester(id_tarefa):
import os
import subprocess
read_path = 'src'
some_file = 'tarefa_%d.c' % id_tarefa
ext = '.exe' if os.name == 'nt' else ''
output_file = os.path.join(read_path, some_file.replace('.c', ext))
return_code = 0
try:
subprocess.run(['gcc', os.path.join(read_path, some_file), '-o', output_file, '-lm'], check=True)
subprocess.run([output_file], check=True)
except subprocess.CalledProcessError:
return_code = 1
finally:
if os.path.exists(output_file):
os.remove(output_file)
return return_code
class TestaTudo(unittest.TestCase):
def testa_tarefa_1(self):
id_tarefa = 1
self.assertEqual(generic_assignment_tester(id_tarefa), 0, 'A tarefa %d não foi resolvida corretamente' % id_tarefa)
def testa_tarefa_2(self):
id_tarefa = 2
self.assertEqual(generic_assignment_tester(id_tarefa), 0, 'A tarefa %d não foi resolvida corretamente' % id_tarefa)
def testa_tarefa_3(self):
id_tarefa = 3
self.assertEqual(generic_assignment_tester(id_tarefa), 0, 'A tarefa %d não foi resolvida corretamente' % id_tarefa)
def testa_tarefa_4(self):
id_tarefa = 4
self.assertEqual(generic_assignment_tester(id_tarefa), 0, 'A tarefa %d não foi resolvida corretamente' % id_tarefa)
def testa_tarefa_5(self):
id_tarefa = 5
self.assertEqual(generic_assignment_tester(id_tarefa), 0, 'A tarefa %d não foi resolvida corretamente' % id_tarefa)
if __name__ == '__main__':
unittest.main()
|
import tkinter as tk
from tkinter import PhotoImage, filedialog
from tkinter.constants import BOTH, BOTTOM, LEFT, RIGHT, YES
from PIL import ImageTk, Image
class App(tk.Tk):
def __init__(self):
super().__init__()
#memory variable
self.title('image loader')
self.fileName = str
self.image = Image
self.imageSize = Image
self.imageDisplay = PhotoImage
#button control
self.resizable(width = True, height = True)
btn = tk.Button(self, text="control", width=10)
btn.pack(anchor=tk.NW, padx=8, pady=10)
btn.bind('<Button-3>', self.getMenuPopUp)
#display image erea
self.imageFrame = tk.Canvas(self, borderwidth=0, width=500, height=300)
self.imageFrame.pack(anchor=tk.W, expand=YES, fill=BOTH)
self.imageFrame.bind('<Configure>', self.resizer)
#info image
groupDisplayInfoImage = tk.LabelFrame(self, borderwidth=0, bd=0, highlightthickness=0)
groupDisplayInfoImage.pack(anchor=tk.SW, expand=YES, fill=tk.X, padx=8)
self.labelFileName = tk.Label(groupDisplayInfoImage ,text="file name", padx=8, pady=10)
self.labelFileName.pack(side=LEFT)
self.labelSize = tk.Label(groupDisplayInfoImage, text="size", pady=10, padx=8)
self.labelSize.pack(side=RIGHT)
def getMenuPopUp(self, event):
btnMenu = tk.Menu(self, tearoff=0)
btnMenu.add_command(label='open', command=self.openImage)
btnMenu.add_command(label='delete', command=self.deleteImage)
btnMenu.add_separator()
btnMenu.add_command(label='quit', command=self.quit)
try:
btnMenu.tk_popup(event.x_root, event.y_root)
finally:
btnMenu.grab_release()
def openFileName(self):
self.fileName = filedialog.askopenfilename(title='image need')
def openImage(self):
self.openFileName()
self.image = Image.open(self.fileName)
width, hieght = self.image.size
realSize = f'{width} x {hieght}'
self.labelSize['text'] = realSize
self.imageSize = self.image.resize((500, 300), Image.ANTIALIAS)
self.imageDisplay = ImageTk.PhotoImage(self.imageSize)
self.imagetk = self.imageFrame.create_image(0,0, image=self.imageDisplay, anchor=tk.NW, tags='image')
self.labelFileName['text'] = self.fileName
def resizer(self, e):
self.image = Image.open(self.fileName)
self.imageSize = self.image.resize((e.width, e.height), Image.ANTIALIAS)
self.imageDisplay = ImageTk.PhotoImage(self.imageSize)
self.imageFrame.itemconfig(self.imagetk, image=self.imageDisplay)
def deleteImage(self):
self.imageFrame.delete('image')
self.labelFileName['text'] = 'file name'
self.labelSize['text'] = 'size'
def quit(self):
self.destroy()
if __name__ == "__main__":
app = App()
app.mainloop()
|
# -*- coding: utf-8 -*-
"""
Created on Fri Apr 6 16:41:15 2018
@author: changguozhen
"""
# ## 3.6 pandas读写结构化数据
# 模块是可以实现一项或多项功能的程序块,Python本身就内置了很多非常有用的模块,只要安装完毕,这些模块就可以立刻使用
# In[ ]:
# 可以通过安装第三方包来增加系统功能,也可以自己编写模块。引入模块有多种方式
# In[ ]:
import pandas as pd
df = pd.DataFrame({'key': ['b', 'b', 'a', 'c', 'a', 'a', 'b'], 'data1': range(7)})
df.head(2)
# In[ ]:
from pandas import DataFrame
df1 = DataFrame({'key': ['b', 'b', 'a', 'c', 'a', 'a', 'b'], 'data1': range(7)})
df1.head(5)
# In[5]
# ## 3.6 使用pandas读写数据
# - pandas可以读取文本文件、json、数据库、Excel等文件
# - 使用read_csv方法读取以逗号分隔的文本文件作为DataFrame,其它还有类似read_table, read_excel, read_html, read_sql等等方法
# In[5]:
import pandas as pd
one = pd.read_csv(r'D:\Python_book\3Programing\One.csv',sep=",")
one.head()
# In[ ]:
#设置工作目录
import os
os.chdir(r'D:\Python_book\3Programing')
hsb2 = pd.read_table('hsb2.txt')
hsb2.head()
# In[ ]:
#html = pd.read_html('http://www.fdic.gov/bank/individual/failed/banklist.html') # Return a list
#html
# In[ ]:
xls = pd.read_excel('hsb2.xlsx', sheetname=0)
xls.head()
# In[ ]
# 写入文件
xls.to_csv('copyofhsb2.csv')
# In[ ]
|
from Altas_Equipos_Y_Componentes.models import DiscoDuro, EquipoYArticulos, MemoriaRam
from django.forms import ModelForm
class CreationForm(ModelForm):
class Meta:
model = EquipoYArticulos
fields = "__all__"
def __init__(self, *args, **kwargs):
super(CreationForm, self).__init__(*args, **kwargs)
self.fields['asignar_disco'].queryset = DiscoDuro.objects.filter(status=True)
self.fields['asignar_memoria'].queryset = MemoriaRam.objects.filter(status=True)
|
# from pymongo import MongoClient
# import os
# account = os.environ["MONGO_ROLE_ACCOUNT"]
# password = os.environ["MONGO_ROLE_PASSWORD"]
# client = MongoClient('mongodb+srv://' + account + ':' + password +
# '@cluster0-hptar.gcp.mongodb.net/test?retryWrites=true')
# db = client['nthuCourse_database']
# userGrades = db['userGrade_collection']
# keywords = db['keyword_collection']
def toSaveUserGrade(userGrade):
# resultID = userGrades.insert_one({'userGrade': userGrade}).inserted_id
# response = {'message': 'Save Grade Success!'}
# return response
return
def toSaveKeyword(search_topic, keyword, other_keyword):
# resultID = keywords.insert_one(
# {'topic': search_topic, 'keyword': keyword, 'other_keyword': other_keyword}).inserted_id
# response = {'message': 'Save Keyword Success!'}
# return response
return
|
from setuptools import setup
setup(
name="",
package_data={("sphinx_argon"): [
"theme.conf",
"*.html",
"static/css/*.css"
]},
include_package_data=True,
entry_points={
"sphinx.html_themes": [
"sphinx_argon = sphinx_argon"
]
}
)
|
# -*- coding: utf-8
from django.apps import AppConfig
class GroupsCacheConfig(AppConfig):
name = 'groups_cache'
verbose_name = 'Groups Cache'
verbose_name_plural = 'Groups Cache'
def ready(self):
from . import signals
|
'''
Created on 18/11/2011
@author: dev
'''
import random
from TetrisPlayer import TetrisPlayer
class FilePlayer(TetrisPlayer):
def __init__(self, fileName):
self.fileName = fileName
self.__hfile = NotImplemented
self.__opened = False
self.__oldGameDice = NotImplemented
self.__oldGameName = ""
self.__game = NotImplemented
def bind(self, game):
if self.__game == NotImplemented:
self.__game = game
self.__oldGameDice = game.getDice()
self.__oldGameName = game.getName()
game.setName(self.fileName)
def unbind(self, game):
if self.__opened:
self.__hfile.close()
self.__opened = False
game.setName(self.__oldGameName)
game.setDice(self.__oldGameDice)
def configure(self, game):
if self.__opened:
self.__hfile.close()
self.__hfile = open(self.fileName, 'r')
self.__opened = True
game.setDice(self.getNextTetromino)
def getNextTetromino(self):
if self.__opened:
tetroTypeStr = self.__hfile.read(1)
if tetroTypeStr == "":
self.__playing = False
else:
return int(tetroTypeStr)
return 0
def generateRandomGame(self, n):
if not self.__opened:
self.__hfile = open(self.fileName, 'w')
for i in xrange(n):
tetroType = random.randint(1,7)
self.__hfile.write(str(tetroType))
self.__hfile.close()
def generateRandomSZGame(self, n):
if not self.__opened:
self.__hfile = open(self.fileName, 'w')
for i in xrange(n):
tetroType = random.randint(3,4)
self.__hfile.write(str(tetroType))
self.__hfile.close()
if __name__ == '__main__':
pass
# print "Creating game file..."
# fp = FilePlayer("database\TetrisGame_sz.txt")
# fp.generateRandomSZGame(1000000)
# print "File created!"
|
"""
This is the meme generator module. This module includes a class ImageCaptioner
that generates memes wit the image,body and author provided.
"""
from QuoteEngine.QuoteModel import QuoteModel
from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw
import random
import os
class ImageCaptioner(object):
"""
The class ImageCaptioner also contains methods:
init: saves the output directory specified.
make_meme: reads in an image, transforms and adds a caption to the image (body and author)
Example:
meme = MemeEngine("./tmp")
output_path = meme.make_meme("path to image", "body of quote", "author of quote")
The output_path is the that path where the meme is stored.
"""
def __init__(self, output_dir):
"""Init method."""
self.out_path = output_dir
def make_meme(self, image, body, author, width=500) -> str:
"""Make the meme from image,body and author."""
try:
img = Image.open(image)
aspect_ratio = img.width/img.height
(new_width, new_height) = (500, int(500*aspect_ratio))
im = img.resize((new_width, new_height))
quote = QuoteModel(body, author).__repr__()
pos1 = random.randint(10, 50)
pos2 = random.randint(10, 100)
font = ImageFont.truetype("arial.ttf", 20)
draw = ImageDraw.Draw(im)
draw.text((pos1, pos2), text=quote, font=font)
file_path = r'{}/{}.png'.format(self.out_path,
random.randint(0, 1000))
im.save(file_path)
return file_path
except Exception as e:
raise Exception(e)
|
from flask import Blueprint, render_template
blueprint_query_builder = Blueprint("blueprint_query_builder", __name__)
@blueprint_query_builder.route("/query_builder")
def query_builder():
"""A function which handles requests of the '.query_builder'-
route for the webapp.
:return Rendered template of 'template_query_builder.html' (str).
"""
return render_template("template_query_builder.html", active_nav="query")
# shift command r = hard refresh cache/ en zooi
|
# -*- encoding:utf-8 -*-
# Copyright © 2015-2016, THOORENS Bruno - http://bruno.thoorens.free.fr/licences/tyf.html
from . import reduce
import math, fractions, datetime
###############
# type encoders
cast = lambda value, mini, maxi: int(max(min(value, maxi), mini))
_m_short = 0
_M_short = 2**8
def _1(value):
if isinstance(value, tuple): return tuple(cast(v, _m_short, _M_short) for v in value)
else: return (cast(value, _m_short, _M_short), )
def _2(value):
if not isinstance(value, bytes):
value = value.encode()
if len(value) == 0: return b"\x00"
value += b"\x00" if value[-1] != b"\x00" else ""
return value
_m_byte = 0
_M_byte = 2**16
def _3(value):
if isinstance(value, tuple): return tuple(cast(v, _m_byte, _M_byte) for v in value)
else: return (cast(value, _m_byte, _M_byte), )
_m_long = 0
_M_long = 2**32
def _4(value):
if isinstance(value, tuple): return tuple(cast(v, _m_long, _M_long) for v in value)
else: return (cast(value, _m_long, _M_long), )
def _5(value):
if not isinstance(value, tuple): value = (value, )
return reduce(tuple.__add__, [(f.numerator, f.denominator) for f in [fractions.Fraction(str(v)).limit_denominator(10000000) for v in value]])
_m_s_short = -_M_short/2
_M_s_short = _M_short/2-1
def _6(value):
if isinstance(value, tuple): return tuple(cast(v, _m_s_short, _M_s_short) for v in value)
else: return (cast(value, _m_s_short, _M_s_short), )
def _7(value):
if not isinstance(value, bytes):
value = value.encode()
return value
_m_s_byte = -_M_byte/2
_M_s_byte = _M_byte/2-1
def _8(value):
if isinstance(value, tuple): return tuple(cast(v, _m_s_byte, _M_s_byte) for v in value)
else: return (cast(value, _m_s_byte, _M_s_byte), )
_m_s_long = -_M_long/2
_M_s_long = _M_long/2-1
def _9(value):
if isinstance(value, tuple): return tuple(cast(v, _m_s_long, _M_s_long) for v in value)
else: return (cast(value, _m_s_long, _M_s_long), )
_10 = _5
def _11(value):
return (float(value), )
_12 = _11
#######################
# Tag-specific encoders
# XPTitle XPComment XBAuthor
_0x9c9b = _0x9c9c = _0x9c9d_= _0x9c9e = _0x9c9f = lambda value : reduce(tuple.__add__, [(ord(e), 0) for e in value]) + (0, 0)
#UserComment GPSProcessingMethod
_0x9286 = _0x1b = lambda value: b"ASCII\x00\x00\x00" + (value.encode("ascii", errors="replace") if not isinstance(value, bytes) else value)
#GPSLatitudeRef or InteropIndex
def _0x1 (value):
if isinstance(value, (bytes, str)):
return _2(value)
else:
return b"N\x00" if bool(value >= 0) == True else b"S\x00"
#GPSLatitude or InteropVersion
def _0x2(value):
if isinstance(value, (int, float)):
value = abs(value)
degrees = math.floor(value)
minutes = (value - degrees) * 60
seconds = (minutes - math.floor(minutes)) * 60
minutes = math.floor(minutes)
if seconds >= (60.-0.0001): seconds = 0.; minutes += 1
if minutes >= (60.-0.0001): minutes = 0.; degrees += 1
return _5((degrees, minutes, seconds))
else:
return _7(value)
#GPSLongitudeRef
_0x3 = lambda value: b"E\x00" if bool(value >= 0) == True else b"W\x00"
#GPSLongitude
_0x4 = _0x2
#GPSAltitudeRef
_0x5 = lambda value: _3(1 if value < 0 else 0)
#GPSAltitude
_0x6 = lambda value: _5(abs(value))
# GPSTimeStamp
_0x7 = lambda value: _5(tuple(float(e) for e in [value.hour, value.minute, value.second]))
# GPSDateStamp
_0x1d = lambda value: _2(value.strftime("%Y:%m:%d"))
# DateTime DateTimeOriginal DateTimeDigitized
_0x132 = _0x9003 = _0x9004 = lambda value: _2(value.strftime("%Y:%m:%d %H:%M:%S"))
|
from __future__ import (
unicode_literals,
print_function,
absolute_import,
division,
)
from .pins import (
Pin,
)
from .pins.data import (
PiBoardInfo,
PinInfo,
pi_info,
)
from .exc import (
GPIOZeroError,
DeviceClosed,
BadEventHandler,
BadWaitTime,
BadQueueLen,
CompositeDeviceError,
CompositeDeviceBadName,
CompositeDeviceBadOrder,
CompositeDeviceBadDevice,
SPIError,
SPIBadArgs,
EnergenieSocketMissing,
EnergenieBadSocket,
GPIODeviceError,
GPIODeviceClosed,
GPIOPinInUse,
GPIOPinMissing,
InputDeviceError,
OutputDeviceError,
OutputDeviceBadValue,
PinError,
PinInvalidFunction,
PinInvalidState,
PinInvalidPull,
PinInvalidEdges,
PinSetInput,
PinFixedPull,
PinEdgeDetectUnsupported,
PinPWMError,
PinPWMUnsupported,
PinPWMFixedValue,
PinUnknownPi,
PinMultiplePins,
PinNoPins,
GPIOZeroWarning,
SPIWarning,
SPISoftwareFallback,
PinWarning,
PinNonPhysical,
)
from .devices import (
Device,
GPIODevice,
CompositeDevice,
)
from .mixins import (
SharedMixin,
SourceMixin,
ValuesMixin,
EventsMixin,
HoldMixin,
)
from .input_devices import (
InputDevice,
DigitalInputDevice,
SmoothedInputDevice,
Button,
LineSensor,
MotionSensor,
LightSensor,
DistanceSensor,
)
from .spi_devices import (
SPIDevice,
AnalogInputDevice,
MCP3001,
MCP3002,
MCP3004,
MCP3008,
MCP3201,
MCP3202,
MCP3204,
MCP3208,
MCP3301,
MCP3302,
MCP3304,
)
from .output_devices import (
OutputDevice,
DigitalOutputDevice,
PWMOutputDevice,
PWMLED,
LED,
Buzzer,
Motor,
RGBLED,
)
from .boards import (
CompositeOutputDevice,
LEDCollection,
LEDBoard,
LEDBarGraph,
PiLiter,
PiLiterBarGraph,
TrafficLights,
PiTraffic,
SnowPi,
TrafficLightsBuzzer,
FishDish,
TrafficHat,
Robot,
RyanteckRobot,
CamJamKitRobot,
Energenie,
)
from .other_devices import (
InternalDevice,
PingServer,
TimeOfDay,
)
|
"""
Copyright (c) 2016-2020 Keith Sterling http://www.keithsterling.com
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files (the "Software"), to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software,
and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
"""
from flask import Flask, request
from pymessenger.bot import Bot
from programy.utils.logging.ylogger import YLogger
from programy.clients.restful.flask.client import FlaskRestBotClient
from programy.clients.restful.flask.facebook.config import FacebookConfiguration
from programy.clients.restful.flask.facebook.renderer import FacebookRenderer
from programy.utils.console.console import outputLog
class FacebookBotClient(FlaskRestBotClient):
def __init__(self, argument_parser=None):
self._access_token = None
FlaskRestBotClient.__init__(self, 'facebook', argument_parser)
YLogger.debug(self, "Facebook Client is running....")
self._facebook_bot = self.create_facebook_bot()
outputLog(self, "Facebook Client loaded")
@property
def facebook_bot(self):
return self._facebook_bot
def _render_callback(self):
return True
def get_license_keys(self):
self._access_token = self.license_keys.get_key("FACEBOOK_ACCESS_TOKEN")
self._verify_token = self.license_keys.get_key("FACEBOOK_VERIFY_TOKEN")
def get_client_configuration(self):
return FacebookConfiguration()
def get_default_renderer(self, callback=True):
del callback
return FacebookRenderer(self)
def create_facebook_bot(self):
if self._access_token is not None:
return Bot(self._access_token)
YLogger.error(self, "Facebook access token missing, unable to create facebook bot")
return None
def get_hub_challenge(self, request):
return request.args.get("hub.challenge")
def get_hub_verify_token(self, request):
return request.args.get("hub.verify_token")
def verify_fb_token(self, token_sent, request):
# take token sent by facebook and verify it matches the verify token you sent
# if they match, allow the request, else return an error
if token_sent is None:
YLogger.error(self, "Verify Token is None!")
if token_sent == self._verify_token:
return self.get_hub_challenge(request)
YLogger.error(self, "Facebook verify token failed received [%s]", token_sent)
return 'Invalid verification token'
def return_hub_challenge(self, request):
"""Before allowing people to message your bot, Facebook has implemented a verify token
that confirms all requests that your bot receives came from Facebook."""
token_sent = self.get_hub_verify_token(request)
return self.verify_fb_token(token_sent, request)
def render_response(self, client_context, response):
# sends user the text message provided via input response parameter
self._renderer.render(client_context, response)
return "success"
def receive_message(self, msg_request):
if msg_request.method == 'GET':
return self.return_hub_challenge(msg_request)
else:
data = msg_request.get_json()
self.process_facebook_request(data)
return "Message Processed"
def get_recipitent_id(self, message):
if 'sender' in message:
if 'id' in message['sender']:
return message['sender']['id']
return None
def get_message_text(self, message):
if 'message' in message:
return message['message'].get('text')
return None
def get_postback_text(self, message):
if 'postback' in message:
return message['postback'].get('payload')
return None
def has_attachements(self, message):
if 'message' in message:
if message['message'].get('attachments') is not None:
return True
return False
def process_facebook_request(self, request):
if 'entry' in request:
for event in request['entry']:
if 'messaging' in event:
messaging = event['messaging']
self.process_facebook_message(messaging)
def process_facebook_message(self, messaging):
for message in messaging:
if message.get('message'):
self.handle_message(message)
elif message.get('postback'):
self.handle_postback(message)
def ask_question(self, client_context, question, metadata=None):
response = ""
try:
self._questions += 1
response = client_context.bot.ask_question(client_context, question, responselogger=self)
except Exception as e:
YLogger.exception(client_context, "Error asking Facebook:", e)
return response
def is_echo(self, message):
if 'message' in message:
if 'is_echo' in message['message']:
return message['message']['is_echo']
return False
def handle_message(self, message):
try:
if self.configuration.client_configuration.debug is True:
self.dump_request(message)
self.renderer.print_payload("Incoming", message)
# Facebook Messenger ID for user so we know where to send response back to
recipient_id = self.get_recipitent_id(message)
if recipient_id:
if self.is_echo(message):
YLogger.debug(None, "Handle Facebook is_echo = True")
return
client_context = self.create_client_context(recipient_id)
message_text = self.get_message_text(message)
# We have been send a text message, we can respond
if message_text is not None:
response_text = self.handle_text_message(client_context, message_text)
# else if user sends us a GIF, photo,video, or any other non-text item
elif self.has_attachements(message):
response_text = self.handle_attachement(client_context, message)
# otherwise its a general error
else:
YLogger.error(client_context, "Facebook general error handling message")
response_text = "Sorry, I do not understand you!"
YLogger.debug(client_context, "Facebook message response: [%s]", response_text)
self.render_response(client_context, response_text)
except Exception as e:
YLogger.exception(None, "Error handling facebook message", e)
def handle_text_message(self, client_context, message_text):
YLogger.debug(client_context, "Facebook sent message: [%s]", message_text)
return self.ask_question(client_context, message_text)
def handle_attachement(self, client_context, payload):
try:
message = payload.get('message')
attachements = message.get('attachments')
for attachment in attachements:
if attachment.get('type') == 'location':
return self.handle_location_attachment(client_context, attachment)
except Exception as e:
YLogger.exception(client_context, "Unable to handle attachment", e)
return "Sorry, I cannot handle that type of attachement right now!"
def handle_location_attachment(self, client_context, attachment):
try:
payload = attachment.get('payload')
coordinates = payload.get('coordinates')
lat = coordinates.get('lat')
long = coordinates.get('long')
question = "RCS XLATLONG LOCATION XLAT %s XLONG %s" % (lat, long)
return self.ask_question(client_context, question)
except Exception as e:
YLogger.exception(client_context, "Unable to handle location attachment", e)
return "Error processing location!"
def handle_postback(self, message):
if self.configuration.client_configuration.debug is True:
self.dump_request(message)
# Facebook Messenger ID for user so we know where to send response back to
recipient_id = self.get_recipitent_id(message)
if recipient_id:
client_context = self.create_client_context(recipient_id)
message_text = self.get_postback_text(message)
# We have been send a text message, we can respond
if message_text is not None:
response_text = self.handle_text_message(client_context, message_text)
# otherwise its a general error
else:
YLogger.error(self, "Facebook general error handling postback")
response_text = "Sorry, I do not understand you!"
YLogger.debug(self, "Facebook postback response: [%s]", response_text)
self.render_response(client_context, response_text)
if __name__ == "__main__":
outputLog(None, "Initiating Facebook Client...")
FACEBOOK_CLIENT = FacebookBotClient()
APP = Flask(__name__)
@APP.route(FACEBOOK_CLIENT.configuration.client_configuration.api, methods=['GET', 'POST'])
def receive_message():
try:
return FACEBOOK_CLIENT.receive_message(request)
except Exception as e:
YLogger.exception(None, "Facebook Error", e)
FACEBOOK_CLIENT.run(APP)
|
from osbot_jupyter.api.CodeBuild_Jupyter_Helper import CodeBuild_Jupyter_Helper
from osbot_jupyter.api.Docker_Jupyter import Docker_Jupyter
from osbot_jupyter.api.Jupyter_API import Jupyter_API
from osbot_jupyter.api.Jupyter_Kernel import Jupyter_Kernel
from osbot_jupyter.api.Jupyter_Session import Jupyter_Session
from osbot_jupyter.api.Jupyter_Web import Jupyter_Web
from osbot_jupyter.api.Jupyter_Web_Cell import Jupyter_Web_Cell
class Test_Server:
def __init__(self, headless=True):
self.image_name = None
self.docker_jupyter = None
self.token = None
self.server = None
self.code_build_helper = None
self.headless = headless
def docker(self):
#self.image_name = 'jupyter/datascience-notebook:9b06df75e445'
self.image_name = None #'244560807427.dkr.ecr.eu-west-2.amazonaws.com/osbot-jupyter:latest'
self.docker_jupyter = Docker_Jupyter(self.image_name)
self.token = self.docker_jupyter.token()
self.server = self.docker_jupyter.server()
return self
def codebuild(self):
server, token = CodeBuild_Jupyter_Helper().get_active_server_details()
self.server = server
self.token = token
return self
def jupyter_api (self): return Jupyter_API (server=self.server, token=self.token )
def jupyter_cell (self): return Jupyter_Web_Cell (server=self.server, token=self.token,headless=self.headless)
def jupyter_kernel (self): return Jupyter_Kernel (server=self.server, token=self.token )
def jupyter_session (self): return Jupyter_Session (server=self.server, token=self.token )
def jupyter_web (self): return Jupyter_Web (server=self.server, token=self.token,headless=self.headless)
def url(self):
return "{0}?token={1}".format(self.server, self.token) |
import gpt_2_simple as gpt2
import os
import requests
import tensorflow as tf
import pickle
import pandas as pd
import time
# Choose GPU
os.environ['CUDA_VISIBLE_DEVICES']='0'
# Limit memory usage
config = tf.ConfigProto()
config.gpu_options.allow_growth = True
session = tf.Session(config=config)
def load_pickle(filename):
with open(filename,'rb') as f:
obj = pickle.load(f)
f.close()
return obj
def dump_pickle(filename,obj):
with open(filename,'wb') as f:
pickle.dump(obj,f)
sess = gpt2.start_tf_sess()
#sess = gpt2.reset_session(sess)
test_data = "test_data/test_20_final.txt"
run_name_list = os.listdir("checkpoint/")
run_name_list = [x for x in run_name_list if x.startswith('train_2')]
run_name_list = [x for x in run_name_list if x.split('_')[-3]=='355M']
print(run_name_list)
print(len(run_name_list))
output_file = "generated_para_test20_final_355_train2"
try:
generated_paraphrase = load_pickle("generated_paraphrase/"+output_file+".pkl")
except:
generated_paraphrase = {}
run_name_list = [x for x in run_name_list if x not in generated_paraphrase]
num_samples= 1
file = open(test_data,'r')
test_input_list = file.readlines()
model_num = len(run_name_list)
print("number of model in pickle = ",str(len(generated_paraphrase)))
print("number of model to run = ", str(model_num))
for i,run_name in enumerate(run_name_list) :
#generated_paraphrase[run_name] = {}
print("=====================================")
print(run_name)
print("Model "+str(i+1)+" from "+ str(model_num))
print("=====================================")
sess = gpt2.reset_session(sess)
sess = gpt2.start_tf_sess()
gpt2.load_gpt2(sess, run_name= run_name)
generated_paraphrase[run_name] = {}
for test_input in test_input_list:
test_input= test_input.replace('\n','')
gen_para = gpt2.generate(sess,
run_name=run_name,
length=50,
temperature=1,
prefix=test_input,
nsamples=num_samples,
batch_size=1,#,
include_prefix = True,
truncate='<|end of text|>',
return_as_list=True
)
#results will include the prefix since if include_prefix == False, the result sometimes not consistent, so more difficult to preprocess
generated_paraphrase[run_name][test_input] = {}
for i,x in enumerate(gen_para):
generated_paraphrase [run_name][test_input][i] = x.replace(test_input,'').replace('/n','')
dump_pickle("generated_paraphrase/"+output_file+'.pkl',generated_paraphrase)
pd.concat({
v: pd.DataFrame.from_dict(k, 'index') for v, k in generated_paraphrase.items()},
axis=1).transpose().to_excel("generated_paraphrase/"+output_file+'.xlsx')
|
# First python
print('hello,world')
print("Enter name:")
name = input()
print('nice to meet you ' + name)
print("the lenth of you name is: ")
print(len(name))
print('enter age:')
age = input()
print('you will be ' + str(int(age) + 1) + ' in a year')
print('Enter age:')
age = input()
if int(age) ==35 :
print('right , you are 35')
else :
print('you are not 35')
print('Enter age:')
age = int(input())
if 10 <= age < 40 :
print("Age is in 10 to 40")
elif 40 <= age < 50 :
print('Age is in 40 to 50')
else :
print('Age is other')
for i in range(3) :
print('for ' + str(i))
count = 5
print('Noe test your calculate.')
while count < 10 :
print('hell')
count = count + 1
while True :
print('Who are you?')
name = input()
if name != 'eric' :
continue
print('Enter password:')
pwd = input()
if pwd == '111' :
print('pwd right!')
break
else :
print('pwd wrong')
print("Login success!")
|
# SLAMAgents.py
# ----------------
# Licensing Information: You are free to use or extend these projects for
# educational purposes provided that (1) you do not distribute or publish
# solutions, (2) you retain this notice, and (3) you provide clear
# attribution to UC Berkeley, including a link to
# http://inst.eecs.berkeley.edu/~cs188/pacman/pacman.html
#
# Attribution Information: The Pacman AI projects were developed at UC Berkeley.
# The core projects and autograders were primarily created by John DeNero
# (denero@cs.berkeley.edu) and Dan Klein (klein@cs.berkeley.edu).
# Student side autograding was added by Brad Miller, Nick Hay, and
# Pieter Abbeel (pabbeel@cs.berkeley.edu).
import util
from game import Agent
from game import Directions
from keyboardAgents import KeyboardAgent
import inference
import slam
import random
class NullGraphics:
"Placeholder for graphics"
def initialize(self, state, isBlue = False):
pass
def update(self, state):
pass
def pause(self):
pass
def draw(self, state):
pass
def updateDistributions(self, dist):
pass
def finish(self):
pass
class KeyboardInference(inference.InferenceModule):
"""
Basic inference module for use with the keyboard.
"""
def initializeUniformly(self, gameState):
self.beliefs = util.Counter()
for p in self.legalPositions: self.beliefs[p] = 1.0
self.beliefs.normalize()
def observe(self, observation, gameState):
noisyDistance = observation
emissionModel = slam.getObservationDistribution(noisyDistance)
pacmanPosition = gameState.getPacmanPosition()
allPossible = util.Counter()
for p in self.legalPositions:
trueDistance = util.manhattanDistance(p, pacmanPosition)
if emissionModel[trueDistance] > 0:
allPossible[p] = 1.0
allPossible.normalize()
self.beliefs = allPossible
def elapseTime(self, gameState):
pass
def getBeliefDistribution(self):
return self.beliefs
class SLAMAgent:
"An agent that tracks and displays its beliefs about wall positions and its own position."
def __init__( self, index = 0, inference = "SLAMParticleFilter", ghostAgents = None, observeEnable = True, elapseTimeEnable = True):
self.inferenceType = util.lookup(inference, globals())
self.observeEnable = observeEnable
self.elapseTimeEnable = elapseTimeEnable
self.prevAction = None
def tellGameInfo(self, startPos, width, height, wallPrior, legalPositions):
self.inferenceModules = [self.inferenceType(startPos, width, height, wallPrior, legalPositions)]
self.inferenceModule = self.inferenceModules[0]
def registerInitialState(self, gameState):
import __main__
self.display = __main__._display
self.firstMove = True
def observationFunction(self, gameState):
"""
Observes noisy distance to walls in each of four directions.
Also remembers what action Pacman just attempted to take,
regardless of if that action was actually successful.
Returns the gameState for bookkeeping purposes, though this is
not known to the inference module.
"""
return gameState.getNoisyRangeMeasurements(), self.prevAction, gameState
def getAction(self, observation):
"""
"Updates beliefs, then chooses an action."
"""
beliefs = []
noisyRangeMeasurements, prevAction, gameState = observation
if self.observeEnable:
self.inferenceModule.observe(prevAction, noisyRangeMeasurements)
beliefs.append(self.inferenceModule.getWallBeliefDistribution())
beliefs.append(self.inferenceModule.getPositionBeliefDistribution())
self.display.updateDistributions(beliefs)
return self.chooseAction(gameState)
def chooseAction(self, gameState):
"By default, a SLAMAgent just stops. This should be overridden."
return Directions.STOP
class SLAMKeyboardAgent(SLAMAgent, KeyboardAgent):
"An agent controlled by the keyboard that displays beliefs about wall positions and its own position."
def __init__(self, index = 0, inference = "SLAMParticleFilter", ghostAgents = None):
KeyboardAgent.__init__(self, index)
SLAMAgent.__init__(self, index, inference, ghostAgents)
def getAction(self, gameState):
return SLAMAgent.getAction(self, gameState)
def chooseAction(self, gameState):
action = KeyboardAgent.getAction(self, gameState)
self.prevAction = action
return action
from distanceCalculator import Distancer
class AutoSLAMAgent(SLAMAgent):
"An agent that moves automatically at random."
def registerInitialState(self, gameState):
"Pre-computes the distance between every two points."
SLAMAgent.registerInitialState(self, gameState)
self.distancer = Distancer(gameState.data.layout, False)
def chooseAction(self, gameState):
legal = [a for a in gameState.getLegalPacmanActions()]
legal.remove(Directions.STOP)
action = random.choice(legal)
self.prevAction = action
return action
class PatrolSLAMAgent(SLAMAgent):
"An agent that tends to move forward and avoids backtracking when possible."
def registerInitialState(self, gameState):
"Pre-computes the distance between every two points."
SLAMAgent.registerInitialState(self, gameState)
self.distancer = Distancer(gameState.data.layout, False)
def chooseAction(self, gameState):
legal = [a for a in gameState.getLegalPacmanActions()]
legal.remove(Directions.STOP)
if self.prevAction in legal:
return self.prevAction
for a in legal:
if self.prevAction not in Directions.REVERSE or a != Directions.REVERSE[self.prevAction]:
self.prevAction = a
return a
self.prevAction = Directions.REVERSE[self.prevAction]
return self.prevAction
|
import numpy as np
import pdb
from scipy import sparse
from scipy.optimize import fmin_ncg
import pdb
import time
# for hinge loss SVM
def hessian_vector_product_hinge(label, ypred, x, v, scale_factor=1.0):
mask = np.ones_like(label)
mask[ypred * label >= 1] = 0
mask[ypred * label <= 0] = 0
t = label * mask
xv = x.dot(v)
txv = t.dot(xv)
hvp = txv * x.T.dot(t)
hvp = hvp / x.shape[0] * scale_factor
return hvp
def hessian_hingle_loss_theta(label, ypred, x):
mask = np.ones_like(label)
mask[ypred * label >= 1] = 0
mask[ypred * label <= 0] = 0
t = label * mask
tx = x.T.dot(t.reshape(-1,1))
txxt = tx.dot(tx.T)
return txxt
def batch_grad_hinge_loss(label, ypred, x):
if not isinstance(x, sparse.csr_matrix):
x = sparse.csr_matrix(x)
mask_1 = np.zeros_like(ypred)
mask_1[ypred * label <= 0] = 1
mask_1 = mask_1.astype(int)
mask_2 = np.logical_xor(np.ones_like(mask_1), mask_1).astype(int)
mask_3 = np.ones_like(mask_1)
mask_3[ypred * label > 1] = 0
mask_3 = mask_3.astype(int)
val_1 = -x.multiply(label.reshape(-1,1))
val_2 = -val_1.multiply((1-label*ypred).reshape(-1,1))
# val_1 = np.asarray(val_1.mean(0)).flatten()
# val_2 = np.asarray(val_2.mean(0)).flatten()
val_1 = val_1.multiply(mask_1.reshape(-1,1))
val_2 = val_2.multiply(mask_2.reshape(-1,1))
val_1 = val_1.multiply(mask_3.reshape(-1,1))
val_2 = val_2.multiply(mask_3.reshape(-1,1))
grad = val_1 + val_2
return grad
def grad_hinge_loss_theta(label, ypred, x):
if not isinstance(x, sparse.csr_matrix):
x = sparse.csr_matrix(x)
mask_1 = np.zeros_like(ypred)
mask_1[ypred * label <= 0] = 1
mask_1 = mask_1.astype(int)
mask_2 = np.logical_xor(np.ones_like(mask_1), mask_1).astype(int)
mask_3 = np.ones_like(mask_1)
mask_3[ypred * label > 1] = 0
mask_3 = mask_3.astype(int)
val_1 = -x.multiply(label.reshape(-1,1))
val_2 = -val_1.multiply((1-label*ypred).reshape(-1,1))
# val_1 = np.asarray(val_1.mean(0)).flatten()
# val_2 = np.asarray(val_2.mean(0)).flatten()
val_1 = val_1.multiply(mask_1.reshape(-1,1))
val_2 = val_2.multiply(mask_2.reshape(-1,1))
val_1 = val_1.multiply(mask_3.reshape(-1,1))
val_2 = val_2.multiply(mask_3.reshape(-1,1))
grad = np.asarray((val_1 + val_2).mean(0)).flatten()
return grad
def inverse_hvp_hinge_newtonCG(x_train,y_train,y_pred,v,hessian_free=True,tol=1e-5, scale_factor=1.0):
"""Get inverse hessian-vector-products H^-1 * v, this method is not suitable for
the large dataset.
Args:
x_train, y_train: training data used for computing the hessian, e.g. x_train: [None,n]
y_pred: predictions made on x_train, e.g. [None,]
v: value vector, e.g. [n,]
hessian_free: bool, `True` means use implicit hessian-vector-product to avoid
building hessian directly, `False` will build hessian.
hessian free will save memory while be slower in computation, vice versa.
such that set `True` when cope with large dataset, and set `False` with
relatively small dataset.
Return:
H^-1 * v: shape [None,]
"""
if not hessian_free:
hessian_matrix = hessian_hingle_loss_theta(y_train,y_pred,x_train,scale_factor)
# build functions for newton-cg optimization
def fmin_loss_fn(x):
"""Objective function for newton-cg.
H^-1 * v = argmin_t {0.5 * t^T * H * t - v^T * t}
"""
if hessian_free:
hessian_vec_val = hessian_vector_product_hinge(y_train,y_pred,x_train,x,scale_factor) # [n,]
else:
hessian_vec_val = np.dot(x,hessian_matrix) # [n,]
obj = 0.5 * np.dot(hessian_vec_val,x) - \
np.dot(x, v)
return obj
def fmin_grad_fn(x):
"""Gradient of the objective function w.r.t t:
grad(obj) = H * t - v
"""
if hessian_free:
hessian_vec_val = hessian_vector_product_hinge(y_train,y_pred,x_train,x,scale_factor)
else:
hessian_vec_val = np.dot(x,hessian_matrix) # [n,]
grad = hessian_vec_val - v
return grad
def get_fmin_hvp(x,p):
# get H * p
if hessian_free:
hessian_vec_val = hessian_vector_product_hinge(y_train,y_pred,x_train,p,scale_factor)
else:
hessian_vec_val = np.dot(p,hessian_matrix)
return hessian_vec_val
def get_cg_callback(verbose):
def fmin_loss_split(x):
if hessian_free:
hessian_vec_val = hessian_vector_product_hinge(y_train,y_pred,x_train,x,scale_factor)
else:
hessian_vec_val = np.dot(x,hessian_matrix)
loss_1 = 0.5 * np.dot(hessian_vec_val,x)
loss_2 = - np.dot(v, x)
return loss_1, loss_2
def cg_callback(x):
# idx_to_remove = 5
# xs = x_train[idx_to_remove]
# label = y_train[idx_to_remove]
# ys = y_pred[idx_to_remove]
# train_grad_loss_val = grad_logloss_theta_lr(label,ys,xs.reshape(1,-1))
# predicted_loss_diff = np.dot(x,train_grad_loss_val) / x_train.shape[0]
if verbose:
print("Function value:", fmin_loss_fn(x))
quad, lin = fmin_loss_split(x)
print("Split function value: {}, {}".format(quad, lin))
# print("Predicted loss diff on train_idx {}: {}".format(idx_to_remove, predicted_loss_diff))
return cg_callback
start_time = time.time()
cg_callback = get_cg_callback(verbose=True)
fmin_results = fmin_ncg(f=fmin_loss_fn,
x0=v,
fprime=fmin_grad_fn,
fhess_p=get_fmin_hvp,
callback=cg_callback,
avextol=tol,
maxiter=100,)
print("implicit hessian-vector products mean:",fmin_results.mean())
print("implicit hessian-vector products norm:",np.linalg.norm(fmin_results))
print("Inverse HVP took {:.1f} sec".format(time.time() - start_time))
return fmin_results |
import unittest
from math import comb
from swiss import Logic
from datetime import datetime
from pathlib import Path
import random
import logging
import os
logging.basicConfig(filename='test.log', filemode='w', level=logging.INFO)
logger = logging.getLogger(__name__)
class TestBasicSwiss(unittest.TestCase):
def combis(self, gamesPerRound, numClash, enoughGood = None):
games= []
for i in range(gamesPerRound): games.append(Logic.Game("Win " + str(i), "Lose " + str(i),i*i))
for i in range(numClash): games.append(Logic.Game("Win 0", "Clash " + str(i),i *1))
random.shuffle(games)
start = datetime.now()
res = Logic.Tournament.bestCombinations(games,gamesPerRound, set(), 0, set(), enoughGood)
t = datetime.now()
logger.info("For %s combinations and enoughGood %s gave %s good with sq %s and took %s", comb(len(games), gamesPerRound), enoughGood, res.numGood, res.bestSumSquares, t-start)
return res
def testCombinationsFast(self):
res = self.combis(gamesPerRound = 6, numClash = 3, enoughGood = 4)
self.assertEqual(4,res.numGood)
self.assertEqual(55,res.bestSumSquares)
res = self.combis(gamesPerRound = 6, numClash = 3)
self.assertEqual(4,res.numGood)
self.assertEqual(55,res.bestSumSquares)
self.combis(gamesPerRound = 8, numClash = 50, enoughGood = 4)
self.combis(gamesPerRound = 16, numClash = 500, enoughGood = 1)
self.combis(gamesPerRound = 16, numClash = 500, enoughGood = 4)
self.combis(gamesPerRound = 8, numClash = 500, enoughGood = 1)
self.combis(gamesPerRound = 8, numClash = 500, enoughGood = 4)
self.combis(gamesPerRound = 8, numClash = 500, enoughGood = 100)
res = self.combis(gamesPerRound = 8, numClash = 500)
self.assertEqual(501,res.numGood)
self.assertEqual(140,res.bestSumSquares)
@unittest.skip("Takes a few minutes")
def testCombinationsSlow(self):
self.combis(gamesPerRound = 16, numClash = 500, enoughGood = 100)
def testCreate1(self):
sw = Logic.Tournament();
sw.setOpts(26, 1000000000, 100, 4, True)
sw.addPlayer("A", Logic.Colours.PRIMARY)
sw.addPlayer("B", Logic.Colours.SECONDARY)
sw.addPlayer("C")
sw.addPlayer("D")
sw.addPlayer("E")
sw.addPlayer("F")
sw.addPlayer("G")
sw.addPlayer("H")
self.assertEqual(3, sw.getKORounds())
self.assertEqual(7, sw.getMaxRounds())
self.assertEqual(5, sw.getRecRounds())
self.assertEqual(Logic.Colours.PRIMARY, sw.players["A"].colours)
self.assertEqual(Logic.Colours.SECONDARY, sw.players["B"].colours)
self.assertEqual(None, sw.players["C"].colours)
def testCreate2(self):
sw = Logic.Tournament();
sw.setOpts(26, 1000000000, 100, 4, False)
sw.addPlayer("A", Logic.Colours.PRIMARY)
sw.addPlayer("B", Logic.Colours.SECONDARY)
sw.addPlayer("C")
sw.addPlayer("D")
sw.addPlayer("E")
sw.addPlayer("F")
sw.addPlayer("G")
sw.addPlayer("H")
sw.addPlayer("I")
self.assertEqual(4, sw.getKORounds())
self.assertEqual(8, sw.getMaxRounds())
self.assertEqual(6, sw.getRecRounds())
def testGetBest1(self):
sw = Logic.Tournament();
sw.setOpts(26, 1000000000, 100, 4, False)
for l in "ABCDEFGH": sw.addPlayer(l)
if len(sw.players) % 2 == 1: sw.players["Bye"] = Player("Bye", None)
sw.rounds.append([['G', 25], ['F', 26], ['D', 15], ['H', 12], ['E', 16], ['C', 21], ['B', 24], ['A', 25]]); sw.computeRanking()
sw.rounds.append([['F', 22], ['D', 25], ['C', 16], ['A', 18], ['G', 9], ['H', 4], ['E', 15], ['B', 26]]); sw.computeRanking()
sw.rounds.append([['D', 6], ['A', 9], ['F', 18], ['C', 19], ['G', 9], ['B', 25], ['H', 17], ['E', 20]]); sw.computeRanking()
sw.rounds.append([['A', 6], ['F', 2], ['D', 16], ['C', 20], ['G', 0], ['E', 14], ['B', 22], ['H', 8]]); sw.computeRanking()
logger.info("Ranking after round 4")
res = ""
for name in sw.ranking:
res += name + ": " + str(sw.players[name].games) + " "
logger.info(res)
fr = sw.getFinalRanking()
self.assertDictEqual({'A': 1, 'B': 2, 'C': 3, 'E': 4, 'D': 5, 'F': 6, 'G': 7, 'H': 8}, fr)
def testGetBest2(self):
sw = Logic.Tournament();
sw.setOpts(26, 1000000000, 100, 4, False)
for l in "ABCDEFGH": sw.addPlayer(l)
if len(sw.players) % 2 == 1: sw.players["Bye"] = Player("Bye", None)
sw.rounds.append([['G', 25], ['F', 26], ['D', 15], ['H', 12], ['E', 16], ['C', 21], ['B', 24], ['A', 25]]); sw.computeRanking()
sw.rounds.append([['F', 22], ['D', 25], ['C', 16], ['A', 18], ['G', 9], ['H', 4], ['E', 15], ['B', 26]]); sw.computeRanking()
sw.rounds.append([['D', 6], ['A', 9], ['F', 18], ['C', 19], ['G', 9], ['B', 25], ['H', 17], ['E', 20]]); sw.computeRanking()
sw.rounds.append([['A', 2], ['F', 6], ['D', 16], ['C', 20], ['G', 0], ['E', 14], ['B', 22], ['H', 8]]); sw.computeRanking()
logger.info("Ranking after round 4")
res = ""
for name in sw.ranking:
res += name + ": " + str(sw.players[name].games) + " "
logger.info(res)
fr = sw.getFinalRanking()
self.assertDictEqual({'A': 1, 'B': 2, 'C': 3, 'F': 4, 'E': 5, 'D': 6, 'G': 7, 'H': 8}, fr)
def testGetBest3(self):
sw = Logic.Tournament();
sw.setOpts(26, 1000000000, 100, 4, False)
for l in "ABCDEFGH": sw.addPlayer(l)
if len(sw.players) % 2 == 1: sw.players["Bye"] = Player("Bye", None)
sw.rounds.append([['D', 15], ['H', 9], ['G', 21], ['E', 25], ['A', 26], ['B', 24], ['F', 13], ['C', 22]]); sw.computeRanking()
sw.rounds.append([['D', 17], ['E', 6], ['A', 26], ['C', 23], ['H', 10], ['G', 11], ['B', 18], ['F', 0]]); sw.computeRanking()
sw.rounds.append([['D', 5], ['A', 13], ['E', 22], ['C', 24], ['G', 20], ['B', 22], ['H', 15], ['F', 17]]); sw.computeRanking()
sw.rounds.append([['A', 10], ['E', 4], ['D', 14], ['C', 23], ['G', 25], ['F', 26], ['B', 24], ['H', 16]]); sw.computeRanking()
logger.info("Ranking after round 4")
res = ""
for name in sw.ranking:
res += name + ": " + str(sw.players[name].games) + " "
logger.info(res)
fr = sw.getFinalRanking()
self.assertDictEqual({'A': 1, 'C': 2, 'B': 3, 'F': 4, 'D': 5, 'E': 6, 'G': 7, 'H': 8}, fr)
def testStarts(self):
for n in range(1000):
self.testStart()
def testStart(self):
sw = Logic.Tournament();
sw.setOpts(26, 1000000000, 100, 4, True)
sw.addPlayer("A", Logic.Colours.PRIMARY)
sw.addPlayer("B", Logic.Colours.SECONDARY)
sw.addPlayer("C")
sw.addPlayer("D")
sw.addPlayer("E")
sw.addPlayer("F")
sw.addPlayer("G")
sw.addPlayer("H")
sw.start();
for j in range(sw.getMaxRounds()):
if j != 0:
sw.computeRanking()
logger.info("Ranking after round " + str(j) + " ")
res = ""
for name in sw.ranking:
res += name + ": " + str(sw.players[name].games) + " "
logger.info(res)
sw.prepareRound()
round = sw.rounds[j]
if len(round) == 0:
logger.info("Stopping early as no more game combination after round " + str(j))
j -= 1
break
else:
sw.setByeScores();
sw.makeGamesChoices(round);
ngames = len(round) // 2;
for i in range(ngames):
p1 = round[2 * i]
p2 = round[2 * i + 1]
if p1[0] != "Bye" and p2[0] != "Bye":
badScore = random.randrange(26);
goodScore = badScore + 1 + random.randrange(26 - badScore);
if p1[0] < p2[0]:
p1[1] = goodScore
p2[1] = badScore
else:
p1[1] = badScore
p2[1] = goodScore
logger.info("Score in round %s : %s", j + 1, round)
sw.computeRanking()
logger.info("Ranking after round " + str(j + 1) + " ")
res = ""
for name in sw.ranking:
res += name + ": " + str(sw.players[name].games) + " "
logger.info(res)
fr = sw.getFinalRanking()
logger.info("Final ranking")
logger.info(fr)
fmt = "{:2} {:.<18} {:4} : {:5} {:>12} {:>10} {:>9}"
## print(fmt.format(" #", "name", "wins", "hoops", "lawns", "primaryXS", "starts"))
for i in range(1,len(sw.players)+1):
for name, val in fr.items():
if val == i:
p = sw.players[name]
wins = p.games
hoops = p.hoops
prim = p.primarys-p.secondarys
lawns = []
for j in range(sw.numLawns):
if j in p.lawns: lawns.append(p.lawns[j])
else: lawns.append(0)
starts = p.startCount
## print(fmt.format(i, name, wins, hoops, str(lawns), prim, starts))
def testStart7(self):
sw = Logic.Tournament();
sw.setOpts(13, 1000000000, 100, 4, True)
sw.addPlayer("A", Logic.Colours.PRIMARY)
sw.addPlayer("B", Logic.Colours.SECONDARY)
sw.addPlayer("C")
sw.addPlayer("D")
sw.addPlayer("E")
sw.addPlayer("F")
sw.addPlayer("G")
sw.start();
for j in range(sw.getMaxRounds()):
if j != 0:
try:
sw.writeLog(round, j == 1)
except Exception as e:
print(e)
print("Failed to write log for round", round)
sw.computeRanking()
logger.info("Ranking after round " + str(j) + " ")
res = ""
for name in sw.ranking:
res += name + ": " + str(sw.players[name].games) + " "
logger.info(res)
# Add, remove or restore players
if j == 1:
sw.removePlayer("A")
elif j == 2:
sw.removePlayer("B")
elif j == 3:
sw.restorePlayer("A")
elif j == 4:
sw.addLatePlayer("Z")
elif j == 5:
return
sw.prepareRound()
round = sw.rounds[j]
if len(round) == 0:
logger.info("Stopping early as no more game combination after round " + str(j))
j -= 1
break
else:
sw.setByeScores();
sw.makeGamesChoices(round);
ngames = len(round) // 2;
for i in range(ngames):
p1 = round[2 * i]
p2 = round[2 * i + 1]
if p1[0] != "Bye" and p2[0] != "Bye":
badScore = random.randrange(26);
goodScore = badScore + 1 + random.randrange(26 - badScore);
if p1[0] < p2[0]:
p1[1] = goodScore
p2[1] = badScore
else:
p1[1] = badScore
p2[1] = goodScore
logger.info("Score in round %s : %s", j + 1, round)
try:
sw.writeLog(round, roundNum == 1)
except Exception:
print("Failed to write log for round", round)
sw.computeRanking()
logger.info("Ranking after round " + str(j + 1) + " ")
res = ""
for name in sw.ranking:
res += name + ": " + str((sw.players|sw.resting)[name].games) + " "
logger.info(res)
fr = sw.getFinalRanking()
logger.info("Final ranking")
logger.info(fr)
fmt = "{:2} {:.<18} {:4} : {:5} {:>12} {:>10} {:>9}"
print(fmt.format(" #", "name", "wins", "hoops", "lawns", "primaryXS", "starts"))
for i in range(1,len(sw.players|sw.resting)+1):
for name, val in fr.items():
if val == i:
p = (sw.players|sw.resting)[name]
wins = p.games
hoops = p.hoops
prim = p.primarys-p.secondarys
lawns = []
for j in range(sw.numLawns):
if j in p.lawns: lawns.append(p.lawns[j])
else: lawns.append(0)
starts = p.startCount
print(fmt.format(i, name, wins, hoops, str(lawns), prim, starts))
def testStart15(self):
sw = Logic.Tournament();
sw.setOpts(14, 1000000000, 100, 4, True)
sw.addPlayer("A", Logic.Colours.PRIMARY)
sw.addPlayer("B", Logic.Colours.SECONDARY)
sw.addPlayer("C")
sw.addPlayer("D")
sw.addPlayer("E")
sw.addPlayer("F")
sw.addPlayer("G")
sw.addPlayer("H")
sw.addPlayer("I")
sw.addPlayer("J")
sw.addPlayer("K")
sw.addPlayer("L")
sw.addPlayer("M")
sw.addPlayer("N")
sw.addPlayer("O")
sw.start();
for j in range(sw.getMaxRounds()):
if j != 0:
sw.computeRanking()
logger.info("Ranking after round " + str(j) + " ")
res = ""
for name in sw.ranking:
res += name + ": " + str(sw.players[name].games) + " "
logger.info(res)
sw.prepareRound()
round = sw.rounds[j]
if len(round) == 0:
logger.info("Stopping early as no more game combination after round " + str(j))
j -= 1
break
else:
sw.setByeScores();
sw.makeGamesChoices(round);
ngames = len(round) // 2;
for i in range(ngames):
p1 = round[2 * i]
p2 = round[2 * i + 1]
if p1[0] != "Bye" and p2[0] != "Bye":
badScore = random.randrange(26);
goodScore = badScore + 1 + random.randrange(26 - badScore);
if p1[0] < p2[0]:
p1[1] = goodScore
p2[1] = badScore
else:
p1[1] = badScore
p2[1] = goodScore
logger.info("Score in round %s : %s", j + 1, round)
sw.computeRanking()
logger.info("Ranking after round " + str(j + 1) + " ")
res = ""
for name in sw.ranking:
res += name + ": " + str(sw.players[name].games) + " "
logger.info(res)
fr = sw.getFinalRanking()
logger.info("Final ranking")
logger.info(fr)
fmt = "{:2} {:.<18} {:4} : {:5} {:>12} {:>10} {:>9}"
## print(fmt.format(" #", "name", "wins", "hoops", "lawns", "primaryXS", "starts"))
for i in range(1,len(sw.players)+1):
for name, val in fr.items():
if val == i:
p = sw.players[name]
wins = p.games
hoops = p.hoops
prim = p.primarys-p.secondarys
lawns = []
for j in range(sw.numLawns):
if j in p.lawns: lawns.append(p.lawns[j])
else: lawns.append(0)
starts = p.startCount
## print(fmt.format(i, name, wins, hoops, str(lawns), prim, starts))
def writeLog(self):
sw = Logic.Tournament()
sw.setOpts(26, 1000000000, 100, 4, False)
sw.addPlayer("Andrew Aardvark", Logic.Colours.PRIMARY)
sw.addPlayer("Bill Banana", Logic.Colours.SECONDARY)
sw.addPlayer("Cool Cucumber", None)
sw.addPlayer("Dangerous Dan")
round = []
round.append(["Andrew Aardvark", 6])
round.append(["Bill Banana", 23])
round.append(["Cool Cucumber", 22])
round.append(["Dangerous Dan",2])
sw.writeLog(round, True)
round = []
round.append(["Bill Banana", 23])
round.append(["Cool Cucumber", 22])
round.append(["Andrew Aardvark", 6])
round.append(["Dangerous Dan",2])
sw.writeLog(round, False)
def testWriteLog(self):
self.writeLog()
logname = "journal.txt"
with open (logname) as f:
lines = f.readlines()
i = 0
for line in lines:
if i == 0: self.assertEqual("{'byeScore': 26, 'maxCombis': 1000000000, 'enoughGood': 100, 'numLawns': 4, 'randomStart': False}\n", line)
elif i == 1: self.assertEqual("Andrew Aardvark -P,Bill Banana -S,Cool Cucumber,Dangerous Dan\n", line)
elif i == 2: self.assertEqual("Bill Banana,beat,Andrew Aardvark,23,6\n", line)
elif i == 3: self.assertEqual("Cool Cucumber,beat,Dangerous Dan,22,2\n", line)
elif i == 4: self.assertEqual("Bill Banana,beat,Cool Cucumber,23,22\n", line)
elif i == 5: self.assertEqual("Andrew Aardvark,beat,Dangerous Dan,6,2\n", line)
i += 1
self.assertEqual(6, i)
os.remove(logname)
def testRecoverFromLog(self):
self.writeLog()
sw = Logic.Tournament()
logname = "journal.txt"
sw.recoverFromLog(Path(logname))
fr = sw.getFinalRanking()
self.assertEqual({'Bill Banana': 1, 'Andrew Aardvark': 3, 'Cool Cucumber': 2, 'Dangerous Dan': 4}, fr)
logger.info("Final ranking")
logger.info(fr)
if __name__ == '__main__':
unittest.main()
|
# Generated by Django 3.0.8 on 2020-10-29 19:51
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='brand',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=50)),
('slug', models.CharField(max_length=50, unique=True)),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='color',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=50)),
('slug', models.CharField(max_length=50, unique=True)),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='Ideal_for',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=50)),
('slug', models.CharField(max_length=50, unique=True)),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='Neck_type',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=50)),
('slug', models.CharField(max_length=50, unique=True)),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='Occassion',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=50)),
('slug', models.CharField(max_length=50, unique=True)),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='Sleeve_type',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=50)),
('slug', models.CharField(max_length=50, unique=True)),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='Tshirt',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=50, null=True)),
('desc', models.CharField(max_length=50, null=True)),
('discount', models.IntegerField(default=0)),
('image1', models.ImageField(upload_to='products')),
('image2', models.ImageField(upload_to='products')),
('image3', models.ImageField(upload_to='products')),
('image4', models.ImageField(upload_to='products')),
('brand', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='shirts.brand')),
('color', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='shirts.color')),
('ideal', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='shirts.Ideal_for')),
('neck', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='shirts.Neck_type')),
('occassion', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='shirts.Occassion')),
('sleeve', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='shirts.Sleeve_type')),
],
),
migrations.CreateModel(
name='Sizevariant',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('price', models.IntegerField()),
('size', models.CharField(choices=[('S', 'Small'), ('M', 'Medium'), ('L', 'Large'), ('XL', 'Extra Large'), ('XXL', 'Extra Extra Large')], max_length=5)),
('tshirt', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='shirts.Tshirt')),
],
),
]
|
num = input()
result = 0
for i in range(4):
a = int(num[i])
result = result + a
print(result) |
import logging
logger = logging.getLogger(__name__)
from .cRIOExceptions import cRIOURLError, cRIOBadRequest, cRIOWebServiceInactive
def r200(response):
logger.debug(f"Status code: {response.status_code} - Succes.")
return response
def r400(response):
logger.critical(f"Status code: {response.status_code} - Failed: Setting not accepted.")
errorMessage = response.json()
logger.critical(f"Response: {errorMessage}")
raise cRIOBadRequest(errorMessage)
def r403(response):
logger.critical(f"Status code: {response.status_code} - Failed: WebService on cRIO is inactive.")
errorMessage = response.json()
logger.critical(f"Response: {errorMessage}")
raise cRIOWebServiceInactive(errorMessage)
def r404(response):
logger.critical(f"Status code: {response.status_code} - Failed: Could not access the ip.")
raise cRIOURLError(f"Could not access the cRIO.")
RESPONSES = {200: r200,
400: r400,
403: r403,
404: r404}
|
# first of all import the socket library
import socket
import random
import sys
# next create a socket object
s = socket.socket()
print("Socket successfully created")
# reserve a port on your computer in our
# case it is 12345 but it can be anything
port = 12345 + random.randint(1,100) #generating a port number such that it is free
# Next bind to the port
# we have not typed any ip in the ip field
# instead we have inputted an empty string
# this makes the server listen to requests
# coming from other computers on the network
hostname = socket.gethostname()
ip_addr_server = socket.gethostbyname(hostname)
s.bind(('', port))
print("IP address of server = ",ip_addr_server)
print("Socket bound to prt number : ",port)
# put the socket into listening mode
s.listen(5)
print("socket is listening")
# a forever loop until we interrupt it or
# an error occurs
for i in range(1):
flag=1
# Establish connection with client.
c,addr = s.accept()
print('Got connection from',addr)
client_id = c.recv(1024).decode('ascii').split()
print("\n\nThe ID Of the client :\nHostname = ",client_id[0],"\nIP Address = ",client_id[1],"\n\n")
for i in range(3):
print("ROUND ",(i+1))
# send a thank you message to the client.
#c.send('Thank you for connecting'.encode('utf-8'))
client_info = c.recv(1024).decode('ascii')
if client_info=="force_exit":
print("Exiting")
c.close()
sys.exit()
client_info = client_info.split()
x = int(client_info[0])
v = int(client_info[1])
n = int(client_info[2])
print("Witness = ",x,"\nClient's Public key = ",v,"\nGlobal Parameter , n = ",n)
challenge = int(input("Enter the challenge : "))
c.send(str(challenge).encode('utf-8'))
y = int(c.recv(1024).decode('ascii'))
print("y = ",y)
verifier1 = ((y%n)*(y%n))%n
verifier2 = x%n
if challenge==1:
verifier2 = (verifier2*(v%n))%n # basically (x*y^1)mod n
#print("verifier1 = ",verifier1,"\nverifier2 = ",verifier2)
if verifier1==verifier2:
print("\nRound cleared\n")
else:
print("\nRound NOT cleared")
flag=0
break
print("\n******************************************************\n")
if flag==0:
print("\nClient NOT authenticated\n")
else:
print("\nClient is authenticated\n")
# Close the connection with the client
c.close() |
from Crypto.Random import random
import challenge39
import challenge43
# Doesn't check for 0 values for r and s.
def relaxedSign(message, pub, priv):
H = challenge43.hash(message)
(p, q, g, y) = pub
k = random.randint(1, q-1)
x = priv
r = pow(g, k, p) % q
kInv = challenge39.invmod(k, q)
s = (kInv * (H + x * r)) % q
return (r, s)
# Doesn't check for 0 values for r and s.
def relaxedVerifySignature(message, signature, pub):
H = challenge43.hash(message)
(r, s) = signature
(p, q, g, y) = pub
if r < 0 or r >= q or s < 0 or s >= q:
return False
w = challenge39.invmod(s, q)
u1 = (H * w) % q
u2 = (r * w) % q
v = ((pow(g, u1, p) * pow(y, u2, p)) % p) % q
return v == r
if __name__ == '__main__':
(p, q, g) = (0x800000000000000089e1855218a0e7dac38136ffafa72eda7859f2171e25e65eac698c1702578b07dc2a1076da241c76c62d374d8389ea5aeffd3226a0530cc565f3bf6b50929139ebeac04f48c3c84afb796d61e5a4f9a8fda812ab59494232c7d2b4deb50aa18ee9e132bfa85ac4374d7f9091abc3d015efc871a584471bb1, 0xf4f47f05794b256174bba6e9b396a7707e563c5b, 0x5958c9d3898b224b12672c0b98e06c60df923cb8bc999d119458fef538b8fa4046c8db53039db620c094c9fa077ef389b5322a559946a71903f990f1f7e0e025e2d7f7cf494aff1a0470f5b64c36b625a097f1651fe775323556fe00b3608c887892878480e99041be601a62166ca6894bdd41a7054ec89f756ba9fc95302291)
pub, priv = challenge43.genKeys(p, q, 0)
message1 = b'Hello, world'
signature1 = relaxedSign(message1, pub, priv)
message2 = b'Goodbye, world'
signature2 = relaxedSign(message2, pub, priv)
print(message1, signature1, relaxedVerifySignature(message1, signature1, pub))
print(message2, signature2, relaxedVerifySignature(message2, signature2, pub))
print(relaxedVerifySignature(message1, signature2, pub))
print(relaxedVerifySignature(message2, signature1, pub))
pub, priv = challenge43.genKeys(p, q, p+1)
(_, _, _, y) = pub
z = 2
invZ = challenge39.invmod(2, q)
r = ((y**z) % p) % q
s = (r * invZ) % q
signature = (r, s)
print(signature)
print(message1, challenge43.verifySignature(message1, signature, pub))
print(message2, challenge43.verifySignature(message2, signature, pub))
|
"""
Copyright (c) 2017-2019 Intel Corporation
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import numpy as np
from mo.front.common.replacement import FrontReplacementOp
from mo.graph.graph import Graph
from extensions.ops.elementwise import Mul
from mo.ops.const import Const
class LRNReplacer(FrontReplacementOp):
op = 'LRN'
enabled = True
graph_condition = [lambda graph: not graph.graph['cmd_params'].generate_experimental_IR_V10]
def replace_sub_graph(self, graph: Graph, match: dict):
node = match['op']
if not node.has_valid('bias') or (node.has_valid('bias') and node.bias == 1):
return
# Calculate scale value & create Const op
scale_value = np.array(1. / (pow(node.bias, node.beta)))
node.alpha /= node.bias
const_node = Const(graph, {'value': scale_value, 'shape': scale_value.shape,
'name': node.name + "/Const_Mul_"}).create_node()
# Create Mul node
mul_node = Mul(graph, {'name': node.name + "/Mul_"}).create_node()
# Connect nodes
const_node.out_port(0).connect(mul_node.in_port(1))
node.out_port(0).get_connection().set_source(mul_node.out_port(0))
node.out_port(0).connect(mul_node.in_port(0))
# Delete bias, if it is not deleted it will appear in IR v6
del node['bias']
|
import tensorflow as tf
from tensorflow.keras.layers import Reshape, Input, Conv1D, Add, Activation
from tensorflow.keras import Model, Sequential
from tensorflow.keras.layers import *
def shape_list(x):
"""Deal with dynamic shape in tensorflow cleanly."""
static = x.shape.as_list()
dynamic = tf.shape(x)
return [dynamic[i] if s is None else s for i, s in enumerate(static)]
class MyConvld(tf.keras.layers.Layer):
def __init__(self, nx, nf, start):
super(MyConvld, self).__init__()
self.nx = nx
self.nf = nf
self.start = start
w_initializer = tf.random_normal_initializer(stddev=0.02)
b_initializer = tf.constant_initializer(0)
self.w = tf.Variable(w_initializer([1, nx, nf], dtype=tf.float32), name="w")
self.b = tf.Variable(b_initializer([nf], dtype=tf.float32), name="b")
def call(self, inputs):
i = tf.reshape(inputs, [-1, self.nx])
wn = tf.reshape(self.w, [-1, self.nf])
return tf.reshape(tf.matmul(i, wn) + self.b, self.start + [self.nf])
"""
MEMORY EFFICIENT IMPLEMENTATION OF RELATIVE POSITION-BASED ATTENTION
(Music Transformer, Cheng-Zhi Anna Huang et al. 2018)
"""
class ATTN(tf.keras.layers.Layer):
def __init__(self, n_state, n_head, seq):
super(ATTN, self).__init__()
self.n_state = n_state * 3
self.n_head = n_head
# TODO:
E_initializer = tf.constant_initializer(0)
self.E = tf.Variable(
E_initializer(shape=[16, seq, 32], dtype=tf.float32), name="E"
)
def split_heads(self, x):
# From [batch, sequence, features] to [batch, heads, sequence, features]
return tf.transpose(self.split_states(x, self.n_head), [0, 2, 1, 3])
def split_states(self, x, n):
"""Reshape the last dimension of x into [n, x.shape[-1]/n]."""
*start, m = shape_list(x)
return tf.reshape(x, start + [n, m // n])
def merge_heads(self, x):
# Reverse of split_heads
return self.merge_states(tf.transpose(x, [0, 2, 1, 3]))
def mask_attn_weights(self, w):
# w has shape [batch, heads, dst_sequence, src_sequence], where information flows from src to dst.
_, _, nd, ns = shape_list(w)
b = self.attention_mask(nd, ns, dtype=w.dtype)
b = tf.reshape(b, [1, 1, nd, ns])
w = w * b - tf.cast(1e10, w.dtype) * (1 - b)
return w
def merge_states(self, x):
"""Smash the last two dimensions of x into a single dimension."""
*start, a, b = shape_list(x)
return tf.reshape(x, start + [a * b])
def attention_mask(self, nd, ns, *, dtype):
"""1's in the lower triangle, counting from the lower right corner.
Same as tf.matrix_band_part(tf.ones([nd, ns]), -1, ns-nd), but doesn't produce garbage on TPUs.
"""
i = tf.range(nd)[:, None]
j = tf.range(ns)
m = i >= j - ns + nd
return tf.cast(m, dtype)
def relative_attn(self, q):
# q have shape [batch, heads, sequence, features]
batch, heads, sequence, features = shape_list(q)
# [heads, batch, sequence, features]
q_ = tf.transpose(q, [1, 0, 2, 3])
# [heads, batch * sequence, features]
q_ = tf.reshape(q_, [heads, batch * sequence, features])
# [heads, batch * sequence, sequence]
rel = tf.matmul(q_, self.E, transpose_b=True)
# [heads, batch, sequence, sequence]
rel = tf.reshape(rel, [heads, batch, sequence, sequence])
# [heads, batch, sequence, 1+sequence]
rel = tf.pad(rel, ((0, 0), (0, 0), (0, 0), (1, 0)))
# [heads, batch, sequence+1, sequence]
rel = tf.reshape(rel, (heads, batch, sequence + 1, sequence))
# [heads, batch, sequence, sequence]
rel = rel[:, :, 1:]
# [batch, heads, sequence, sequence]
rel = tf.transpose(rel, [1, 0, 2, 3])
return rel
def multihead_attn(self, q, k, v):
# q, k, v have shape [batch, heads, sequence, features]
w = tf.matmul(q, k, transpose_b=True)
w = w + self.relative_attn(q)
w = w * tf.math.rsqrt(tf.cast(v.shape[-1], w.dtype))
w = self.mask_attn_weights(w)
w = tf.nn.softmax(w, axis=-1)
a = tf.matmul(w, v)
return a
def call(self, inputs):
q, k, v = map(self.split_heads, tf.split(inputs, 3, axis=2))
present = tf.stack([k, v], axis=1)
a = self.multihead_attn(q, k, v)
a = self.merge_heads(a)
return a, present
class NormalizeDiagonal(tf.keras.layers.Layer):
def __init__(self, n_state):
super(NormalizeDiagonal, self).__init__()
self.n_state = n_state
g_initializer = tf.constant_initializer(1)
b_initializer = tf.constant_initializer(0)
self.g = tf.Variable(g_initializer([n_state], dtype=tf.float32), name="g")
self.b = tf.Variable(b_initializer([n_state], dtype=tf.float32), name="b")
def call(self, inputs):
u = tf.reduce_mean(inputs, axis=-1, keepdims=True)
s = tf.reduce_mean(tf.square(inputs - u), axis=-1, keepdims=True)
x = (inputs - u) * tf.math.rsqrt(s + 1e-5)
return x * self.g + self.b
class WTE(tf.keras.layers.Layer):
def __init__(self, n_vocab, n_embd):
super(WTE, self).__init__()
initializer = tf.random_normal_initializer(stddev=0.02)
self.wte = tf.Variable(initializer([n_vocab, n_embd]), name="wte")
def call(self, inputs):
return [tf.gather(self.wte, inputs), self.wte]
def dilated_causal_Conv1D(dilation_r,activation_fn,dilated_num=0,num_stack=0):
return Conv1D(filters=512,
kernel_size=2,
strides=1,
padding="causal", #valid
dilation_rate=dilation_r,
activation=activation_fn,
use_bias=True,
name='%s_stack%d_dilated%d_causal_conv_layer'%(activation_fn,num_stack,dilated_num))
def TransformerGenerator(hparams, input_shape):
n_vocab = hparams["EventDim"]
n_embd = hparams["EmbeddingDim"]
n_layer = hparams["Layers"]
n_head = hparams["Heads"]
n_sequence = hparams["Time"]
batch_size = 1
inputs = Input(shape=input_shape, dtype=tf.float32)
h = dilated_causal_Conv1D(1,None,-1,-1)(inputs)
nx = 512
# Transformer
for layer in range(n_layer):
## ATTN ###
nor = NormalizeDiagonal(n_embd)(h)
a = MyConvld(nx, nx * 3, [batch_size, n_sequence])(nor)
a, present = ATTN(nx, n_head,n_sequence)(a)
a = MyConvld(nx, nx, [batch_size, n_sequence])(a)
##########
h = Add()([h, a])
###########
## MLP ##
nor = NormalizeDiagonal(n_embd)(h)
a = MyConvld(nx, nx * 4, [batch_size, n_sequence])(nor)
a = Activation("gelu")(a)
m = MyConvld(nx * 4, nx, [batch_size, n_sequence])(a)
###########
h = Add()([h, m])
###########
### output ###
h = NormalizeDiagonal(n_embd)(h)
### back to 0~1
h = Dense(n_sequence)(h)
h = GRU(256)(h)
h = Activation("sigmoid")(h)
h = Reshape((256,1))(h)
return Model(inputs, h)
def TransformerDiscriminator(hparams, input_shape):
n_vocab = hparams["EventDim"]
n_embd = hparams["EmbeddingDim"]
n_layer = int(hparams["Layers"])
n_head = hparams["Heads"]
n_sequence = hparams["Time"]
batch_size = 1
inputs = Input(shape=input_shape, dtype=tf.float32)
batch = 1
h = dilated_causal_Conv1D(1,None,-1,-1)(inputs)
nx = 512
# Transformer
for layer in range(n_layer):
## ATTN ###
nor = NormalizeDiagonal(512)(h)
a = MyConvld(nx, nx * 3, [batch_size, n_sequence])(nor)
a, present = ATTN(nx, n_head,n_sequence)(a)
a = MyConvld(nx, nx, [batch_size, n_sequence])(a)
##########
h = Add()([h, a])
###########
## MLP ##
nor = NormalizeDiagonal(512)(h)
a = MyConvld(nx, nx * 4, [batch_size, n_sequence])(nor)
a = Activation("gelu")(a)
m = MyConvld(nx * 4, nx, [batch_size, n_sequence])(a)
###########
h = Add()([h, m])
###########
### output ###
h = NormalizeDiagonal(n_embd)(h)
### back to 0~1
h = Dense(n_sequence)(h)
h = GRU(256)(h)
h = Dense((1))(h)
return Model(inputs, h)
|
# Embedded file name: /usr/lib/enigma2/python/Plugins/Extensions/vuplusvideoreset/__init__.py
from Components.Language import language
from Tools.Directories import resolveFilename, SCOPE_PLUGINS, SCOPE_LANGUAGE
import os, gettext
PluginLanguageDomain = 'vuplusvideoreset'
PluginLanguagePath = 'Extensions/vuplusvideoreset/locale'
def localeInit():
lang = language.getLanguage()[:2]
os.environ['LANGUAGE'] = lang
print '[' + PluginLanguageDomain + '] set language to ', lang
gettext.bindtextdomain(PluginLanguageDomain, resolveFilename(SCOPE_PLUGINS, PluginLanguagePath))
def _(txt):
t = gettext.dgettext(PluginLanguageDomain, txt)
if t == txt:
print '[' + PluginLanguageDomain + '] fallback to default translation for', txt
t = txt
return t
localeInit()
language.addCallback(localeInit) |
from protocolbuffers import Dialog_pb2
from distributor.shared_messages import create_icon_info_msg, IconInfoData
from interactions.utils.tunable_icon import TunableIcon
from sims4.localization import TunableLocalizedStringFactory
from sims4.tuning.tunable import TunableList
from ui.ui_dialog import UiDialogOk
import services
import sims4.log
logger = sims4.log.Logger('UiDialogInfoInColumns', default_owner='madang')
class UiDialogInfoInColumns(UiDialogOk):
FACTORY_TUNABLES = {'column_headers': TunableList(description='\n A list of column header strings.\n ', tunable=TunableLocalizedStringFactory())}
def build_msg(self, row_data=[], additional_tokens=(), **kwargs):
msg = super().build_msg(additional_tokens=additional_tokens, **kwargs)
msg.dialog_type = Dialog_pb2.UiDialogMessage.INFO_IN_COLUMNS
sim_info = self.owner.sim_info
msg.override_sim_icon_id = self.owner.id if self.owner is not None else 0
if sim_info is None:
logger.error('Sim Info was None for {}', self._target_sim_id)
return msg
info_columns_msg = Dialog_pb2.UiDialogInfoInColumns()
for column_header in self.column_headers:
info_columns_msg.column_headers.append(column_header(sim_info))
for row in row_data:
row_data_msg = Dialog_pb2.UiDialogRowData()
for (icon, icon_name, icon_description) in row:
icon_data = IconInfoData(icon_resource=icon)
icon_info_msg = create_icon_info_msg(icon_data, name=icon_name, desc=icon_description)
row_data_msg.column_info.append(icon_info_msg)
info_columns_msg.rows.append(row_data_msg)
msg.info_in_columns_data = info_columns_msg
return msg
|
# -*- coding: utf-8 -*-
from odoo import fields, models
class PosConfig(models.Model):
_inherit = "pos.config"
iface_order_merge = fields.Boolean(
string="Order Merge",
help="Enables Order Merging in the Point of Sale",
default=True,
)
|
# -*- coding: utf-8 -*-
# Copyright (c) 2019-2022 shmilee
import os
import unittest
import tempfile
import numpy as np
from matplotlib.gridspec import GridSpec
fielddata = np.array([[np.sin(m / 20) * np.cos(n / 20) for m in range(100)]
for n in range(66)])
fieldx, fieldy = np.meshgrid(*[np.arange(0, x) for x in fielddata.T.shape])
zline = np.linspace(0, 15, 1000)
xline = np.sin(zline)
yline = np.cos(zline)
zdata = 15 * np.random.random(100)
xdata = np.sin(zdata) + 0.1 * np.random.randn(100)
ydata = np.cos(zdata) + 0.1 * np.random.randn(100)
mu, sigma = 100, 15
dist = mu + sigma * np.random.randn(10000)
grid = GridSpec(3, 3, wspace=0.2, hspace=0.1)
ax1 = {
'layout': [
grid[0, :2],
dict(
title=r'field data, time=30,60$\Delta t$',
xlabel='r',
ylabel=r'$\phi$'
)
],
'data': [
[1, 'plot', (fielddata[30, :], 'rs-'),
dict(label='time=30$\Delta t$', linewidth=1)],
[2, 'plot', (fielddata[60, :], 'go-'),
dict(label='time=60$\Delta t$')],
[3, 'legend', (), dict()],
],
'axstyle': ['ggplot', 'errortest', {'axes.grid': False}],
}
ax2 = {
'layout': [
grid[0, 2:],
dict(
title=r'field data, r=10,72$\Delta r$',
xlabel='time',
xlim=[0, 70],
)
],
'data': [
[1, 'plot', (fielddata[:, 10], '-'),
dict(label='r=10', linewidth=1)],
[2, 'plot', (fielddata[:, 72], '-'),
dict(label='r=72')],
[3, 'legend', (), dict(loc='upper left')],
],
}
ax3 = {
'layout': [
[0.33, 0, 0.66, 0.33],
dict(
projection='3d',
zlim3d=(np.min(fielddata), np.max(fielddata)),
)
],
'data': [
[1, 'plot_surface', (fieldx, fieldy, fielddata),
dict(rstride=1, cstride=1, linewidth=1,
antialiased=True, cmap='jet', label='field')],
[10, 'grid', (False,), {}],
[11, 'revise', lambda fig, ax, art: fig.colorbar(art[1]), {}],
[12, 'revise', lambda fig, ax, art: fig.colorbar(
art[1], ax=fig.get_axes()[:2]), {}],
],
}
ax4 = {
'layout': [
335,
dict(
title='line3D',
xlabel='X', ylabel='Y',
projection='3d',
)
],
'data': [
[1, 'plot3D', (xline, yline, zline), dict(label='line3d')],
[2, 'scatter3D', (xdata, ydata, zdata), dict()],
[3, 'revise', 'remove_spines', dict(select=('x', 'y'))],
],
'axstyle': ['classic'],
}
ax5 = {
'layout': [
337,
dict(
title=r'$\mathrm{Histogram of IQ: }\mu=100, \sigma=15$',
xlabel='Smarts', ylabel='Probability',
# xticklabels='',
)
],
'data': [
[1, 'hist', (dist, 50), dict(density=1, label='H')],
[2, 'legend', (), dict()],
],
'axstyle': ['default'],
}
ax6 = {
'layout': [334, dict(ylabel='line1')],
'data': [
[1, 'plot', (zline, xline), dict(label='line1')],
[2, 'axvspan', (6, 8), dict(
alpha=0.5, ymin=0.6, ymax=0.9, color='red')],
[3, 'legend', (), dict(loc='upper left')],
[4, 'twinx', (), dict(nextcolor=2)],
[5, 'plot', (zline, yline),
dict(label='line2')],
[6, 'set_ylabel', ('line2',), dict()],
[7, 'legend', (), dict(loc='center right')],
],
}
x = np.linspace(1, 2)
y = np.linspace(1, 1.5)
ax7 = {
'layout': [(0.05, 0.05, 0.45, 0.9), dict()],
'data': [
[1, 'plot', (x, y), dict(label=r'org')],
[2, 'plot', (x, y*2), dict(label=r'*2')],
[3, 'plot', (x, y*3), dict()],
[44, 'plot', (x, y*4), dict(label=r'*4')],
[5, 'plot', (x, y*5), dict(label=r'*5')],
[6, 'plot', (x, y*6), dict()],
[7, 'plot', ([x, x], [-y*7, -y*7.5]), dict(label=r'*7')],
[23, 'revise', 'center_spines', dict(
position='zero', position_left=('data', 1.5))],
[23, 'revise', 'multi_merge_legend', dict(
groups=[
dict(index=[(1, 2), 3], labels=[None, r'*3'],
loc='upper left'),
dict(index=[(44, 5), 6, 7], labels=None,
loc=(0.03, 0.1), ncol=2),
],
max_artists_per_handler=20,
sep=', ',
)],
]
}
ax8 = {
'layout': [
121,
dict(
title='annotate3D',
xlabel='X', ylabel='Y', zlabel='Z',
projection='3d',
)
],
'data': [
[1, 'scatter', ([0, 0, 0], [0, 0, 1], [0, 1, 0]), dict(marker='o')],
[2, 'annotate3D', ('point 1', (0, 0, 0)), dict(
xyztext=(0.01, 0.01, 0.01))],
[3, 'annotate', ('point 2', (0, 1, 0)), dict(
xyztext=(-30, -30, 30), textcoords='offset points',
arrowprops=dict(ec='black', fc='white', shrink=2.5))],
[4, 'annotate3D', ('point 3', (0, 0, 1)), dict(
xyztext=(0.02, 0.1, 0.3),
bbox=dict(boxstyle="round", fc="lightyellow"),
arrowprops=dict(arrowstyle="-|>", ec='black', fc='white', lw=5))],
],
}
ax9 = {
'layout': [
122,
dict(
title='arrow3D',
xlabel='X', ylabel='Y', zlabel='Z', xlim=[0, 2],
projection='3d',
)
],
'data': [
[1, 'arrow3D', ((0, 0, 0), (1, 1, 1)), dict(
mutation_scale=20, arrowstyle="-|>", linestyle='dashed')],
[2, 'arrow3D', ((1, 0, 0), (2, 1, 1)), dict(
mutation_scale=20, ec='green', fc='red')],
],
}
x = np.linspace(-np.pi, np.pi, 100)
y = 2 * np.sin(x)
ax10 = {
'layout': [122, dict(xlabel='X', ylabel='Y')],
'data': [
[1, 'plot', (x, y), dict()],
[2, 'revise', 'arrow_spines', dict(position_bottom=-1, arrow_size=8)],
[3, 'text', (0.2, 2.2, 'arrow spines'), {}],
],
}
temp_contourfresults = dict(
X=fieldx, Y=fieldy, Z=fielddata, clabel_levels=[-0.5, 0, 0.5],
plot_method='plot_surface',
plot_method_kwargs=dict(rstride=1, cstride=1, linewidth=1,
antialiased=True, label='field'),
title='test field', xlabel='r', ylabel='time',
plot_surface_shadow=['x', 'z'],
)
temp_lineresults = dict(
LINE=[
([3, 6], [1.5, 1]),
(np.linspace(0, 9, 31), np.sin(np.linspace(0, 9, 31)), 'sin'),
(range(100), fielddata[30, :], 'field, time=30$\Delta t$'),
],
title='test title', xlabel='X', ylabel='Y',
xlim=[0, 30], ylabel_rotation=45, legend_kwargs=dict(loc=0),
)
temp_sharextwinxresults = dict(
X=range(100),
YINFO=[{
'left': [(fielddata[20, :], 'time=20$\Delta t$'),
(fielddata[5, :], 'time=5$\Delta t$')],
'right': [(fielddata[32, :], 'time=32$\Delta t$'),
(range(20, 81), fielddata[34, 20:81]),
(range(30, 71), fielddata[36, 30:71], 'time=36$\Delta t$')],
# 'rlegend': dict(loc='best'),
'lylabel': r'$\phi$',
}, {
'left': [(fielddata[40, :], 'time=40$\Delta t$')],
'right': [],
'lylabel': r'$\phi$',
}, {
'left': [(fielddata[60, :], 'time=60$\Delta t$')],
'right': [],
'lylabel': r'$\phi$',
},
],
title='field data',
xlabel='R',
xlim=[0, 90],
ylabel_rotation=45,
)
temp_z111presults = dict(
zip_results=[
('tmpl_line', 221, temp_lineresults),
('tmpl_contourf', 223, temp_contourfresults),
('tmpl_sharextwinx', 122, temp_sharextwinxresults),
],
suptitle='test z111p figures'
)
temp_z111presults_merge = dict(
zip_results=[
('tmpl_contourf', 211, dict(
X=fieldx, Y=fieldy, Z=fielddata, clabel_levels=[-0.5, 0, 0.5],
title='test field', xlabel='r', ylabel='time',
)),
('tmpl_line', 211, dict(
LINE=[
(np.linspace(20, 80, 120), 30+10 *
np.sin(np.linspace(20, 80, 120)), 'sin'),
(range(100), np.linspace(0, 65, 100), 'cross'),
])),
],
suptitle='test z111p merge figures'
)
class TestMatplotlibVisplter(unittest.TestCase):
'''
Test class MatplotlibVisplter
'''
def setUp(self):
from ..mplvisplter import MatplotlibVisplter
self.visplter = MatplotlibVisplter('mpl::test')
self.tmpfile = tempfile.mktemp(suffix='-mplfigure')
def tearDown(self):
for ext in ['.jpg', '.png', '.pdf']:
if os.path.isfile(self.tmpfile + ext):
os.remove(self.tmpfile + ext)
def test_mplvisplter_style(self):
self.assertTrue('ggplot' in self.visplter.style_available)
self.assertListEqual(self.visplter.style, ['gdpy3-notebook'])
self.assertListEqual(
self.visplter.check_style(['ggplot', '-rm', {'figure.dpi': 80}]),
['ggplot', {'figure.dpi': 80}])
libpath = self.visplter.style_ext_library['gdpy3-notebook']
libpath = self.visplter.style_ext_library[libpath]
self.assertListEqual(
self.visplter.filter_style(['ggplot', 'gdpy3-notebook']),
['ggplot', os.path.join(libpath, 'gdpy3-notebook.mplstyle')])
self.assertEqual(self.visplter.param_from_style('image.cmap'), 'jet')
self.assertFalse(self.visplter.param_from_style('image.cmapNone'))
self.visplter.style = ['gdpy3-notebook', {'image.cmap': 'hot'}]
self.assertEqual(self.visplter.param_from_style('image.cmap'), 'hot')
def test_mplvisplter_figure(self):
self.visplter.create_figure('test-f1', add_style=['ggplot'])
self.visplter.add_axes(self.visplter.get_figure('test-f1'), ax1)
for ext in ['.jpg', '.png', '.pdf']:
self.visplter.save_figure('test-f1', self.tmpfile + ext)
input("[I]nterrupt, to see figure in %s." % self.tmpfile)
self.visplter.create_figure('test-f2', ax1, ax2, ax3, ax4, ax5, ax6)
self.visplter.show_figure('test-f2')
input('[I]nterrupt, to see figure "%s".' % 'test-f2')
self.assertSetEqual(set(self.visplter.figures), {'test-f1', 'test-f2'})
self.visplter.close_figure('test-f1')
self.assertListEqual(self.visplter.figures, ['test-f2'])
self.visplter.close_figure('all')
self.assertListEqual(self.visplter.figures, [])
def test_mplvisplter_figure_extending(self):
self.visplter.create_figure('test-extend', ax8, ax9)
self.visplter.show_figure('test-extend')
input('[I]nterrupt, to see figure "%s".' % 'test-extend')
self.visplter.close_figure('all')
def test_mplvisplter_revise_functions(self):
self.visplter.create_figure('test-rev1', ax7, ax10)
self.visplter.show_figure('test-rev1')
input('[I]nterrupt, to see figure "%s".' % 'test-rev1')
self.visplter.close_figure('all')
def test_mplvisplter_tmpl_contourf(self):
axstruct, sty = self.visplter.tmpl_contourf(
temp_contourfresults)
self.visplter.create_figure('template-f1', *axstruct, add_style=sty)
self.visplter.show_figure('template-f1')
input('[I]nterrupt, to see figure "%s".' % 'template-f1')
self.visplter.close_figure('template-f1')
def test_mplvisplter_tmpl_line(self):
axstruct, sty = self.visplter.tmpl_line(temp_lineresults)
self.visplter.create_figure('template-f2', *axstruct, add_style=sty)
self.visplter.show_figure('template-f2')
input('[I]nterrupt, to see figure "%s".' % 'template-f2')
self.visplter.close_figure('template-f2')
def test_mplvisplter_tmpl_sharextwinx(self):
axstruct, sty = self.visplter.tmpl_sharextwinx(
temp_sharextwinxresults)
self.visplter.create_figure('template-f3', *axstruct, add_style=sty)
self.visplter.show_figure('template-f3')
input('[I]nterrupt, to see figure "%s".' % 'template-f3')
self.visplter.close_figure('template-f3')
def test_visplter_tmpl_z111p(self):
axstruct, sty = self.visplter.tmpl_z111p(temp_z111presults)
self.visplter.create_figure('template-fz', *axstruct, add_style=sty)
self.visplter.show_figure('template-fz')
input('[I]nterrupt, to see figure "%s".' % 'template-fz')
axstruct, sty = self.visplter.tmpl_z111p(temp_z111presults_merge)
self.visplter.create_figure('template-fzm', *axstruct, add_style=sty)
self.visplter.show_figure('template-fzm')
input('[I]nterrupt, to see figure "%s".' % 'template-fzm')
self.visplter.close_figure('all')
|
# Generated by Django 3.0.6 on 2020-09-16 22:33
from django.db import migrations, models
import multiselectfield.db.fields
class Migration(migrations.Migration):
dependencies = [
('base', '0012_auto_20200916_1611'),
]
operations = [
migrations.DeleteModel(
name='Criptocurrency',
),
migrations.DeleteModel(
name='Currency',
),
migrations.DeleteModel(
name='GasAndOil',
),
migrations.DeleteModel(
name='HeaderPost1',
),
migrations.DeleteModel(
name='HeaderPost2',
),
migrations.DeleteModel(
name='Post_of_the_day',
),
migrations.DeleteModel(
name='Technology',
),
migrations.AlterField(
model_name='latestpost',
name='category',
field=multiselectfield.db.fields.MultiSelectField(blank=True, choices=[(1, 'Gas&Oil'), (2, 'Criptocurrency'), (3, 'Currency'), (5, 'Technology')], max_length=30, null=True),
),
migrations.AlterField(
model_name='meochannel',
name='category',
field=models.CharField(blank=True, choices=[('Gas&Oil', 'Gas&Oil'), ('Criptocurrency', 'Criptocurrency'), ('Currency', 'Currency'), ('Technology', 'Technology')], max_length=200),
),
]
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from apicultur.service import Service
class TransitiveVerb(Service):
# # http://apicultur.io/apis/info?name=VerbTransitive_Onoma_es&version=1.0.0&provider=molinodeideas
version = '1.0.0'
endpoint = 'onoma/conjugator/es/transitiveverb'
method = 'GET'
arguments = ['infinitivo',]
func_name = 'transitive_verb'
def get_endpoint(self):
return self._join_url(self.endpoint, self.version, '?infinitivo=%(infinitivo)s')
|
import numpy as np
from mpi4py import MPI
import csv
import sys
import os
def matrix_multiply(A,B,rank,i):
n = int(sys.argv[1])
dimension = int(sys.argv[2])
rows = int(dimension/n)
columns = int(dimension/n)
C =np.zeros((dimension,dimension))
wt1 = MPI.Wtime()
for j in range(0,rows):
for k in range(0,columns):
row = []
value = 0
for l in range(0,dimension):
value = value + int(A[j][l])*int(B[l][k])
C[j][k]= value
wt2 = MPI.Wtime()
with open('C-'+str(rank)+','+str(i)+'.csv', mode='w') as C_file:
C_writer = csv.writer(C_file, delimiter=',', quotechar='"', quoting= csv.QUOTE_NONNUMERIC)
for i in range(0,dimension):
C_writer.writerow(C[i])
wt = wt2 - wt1
return wt
def getB(i):
with open('B-'+str(i)+'.csv') as csvDataFile:
csvReader = csv.reader(csvDataFile)
B = []
for row in csvReader:
B.append(row)
B = np.array(B)
return B
if __name__ == '__main__':
wt = 0
comm = MPI.COMM_WORLD
rank = comm.Get_rank()
mpisize = comm.Get_size()
my_host = MPI.Get_processor_name()
n = int(sys.argv[1])
with open('A-'+str(rank)+'.csv') as csvDataFile:
csvReader = csv.reader(csvDataFile)
A = []
for row in csvReader:
A.append(row)
A = np.array(A)
os.remove('A-'+str(rank)+'.csv')
for i in range(rank,n):
B = getB(i)
wt = wt + matrix_multiply(A,B,rank,i)
for i in range(0,rank):
B = getB(i)
wt = wt + matrix_multiply(A,B,rank,i)
if rank==0:
print ("Elapsed wall time = "+str(wt)) |
"""
day: 2020-08-13
url: https://leetcode-cn.com/leetbook/read/top-interview-questions-easy/xnwzei/
题目名: 环形链表
题目描述: 判断链表中是否有环,使用整数pos来表示链尾连接到链表中的位置,如果pos是-1,则在链表中
没有环
思路:
1. 快慢指针:
一个快指针一个慢指针,如果是闭环必然会有一次循环会遇到,否则就结束
2. 集合:
判断节点是否在一个集合中,在则说明重复访问了同一个节点,否则将节点添加到集合中
"""
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def hasCycle(self, head: ListNode) -> bool:
# fast, slow = head
# while fast and fast.next:
# fast = fast.next.next
# slow = slow.next
# if fast == slow:
# return True
# return False
nodes = set()
currlent = head
while currlent:
if currlent in nodes:
return True
nodes.add(currlent)
currlent = currlent.next
return False
if __name__ == "__main__":
node1 = ListNode(1)
node2 = ListNode(2)
node3 = ListNode(3)
node4 = ListNode(4)
node1.next = node2
node2.next = node3
node3.next = node4
node4.next = node2
sl = Solution()
sl.hasCycle(node1)
|
from threading import Thread
import grpc
import sys
sys.path.append('./grpc_out')
import currency_tracker_pb2
import currency_tracker_pb2_grpc as pb2_grpc
HOST = '127.0.0.1'
PORT = '50051'
class CurrencyTracker():
def __init__(self, name, currencies):
self.channel = grpc.insecure_channel(HOST + ':' + PORT)
self.stub = pb2_grpc.CurrencyTrackerStub(self.channel)
self.name = name
self.currencies = currencies
self.current_ratio = dict()
self.current_ratio['PLN'] = 1
def get_currencies(self):
return self.currencies
def get_exchange_ratio(self, currency):
return self.current_ratio[currency]
def subscribe(self):
sub_thread = Thread(target=self._receive_uptades)
sub_thread.start()
sub_thread.join()
def unsubscribe(self):
cancelation = currency_tracker_pb2.Cancelation(bankName=self.name)
self.stub.unsubscribe(cancelation)
def _get_currency_string(self, enum):
if enum == 0:
return 'AUD'
elif enum == 1:
return 'CHF'
elif enum == 2:
return 'EUR'
elif enum == 3:
return 'GBP'
elif enum == 4:
return 'USD'
else:
return enum
def _receive_uptades(self):
subscription = currency_tracker_pb2.Subscription(
bankName=self.name,
currencies=self.currencies
)
for currency_data in self.stub.subscribe(subscription):
curr = self. _get_currency_string(currency_data.currency)
self.current_ratio[curr] = currency_data.exchange_ratio |
# Palabras Reservadas
# No se pueden utilizar como identificadores de variables, funciones o clases.
and, from, try
exec, print, elif
not, continue, in
assert, global, while
finally, raise, else
or, def, is, break
if, with, for, return
except, pass, del, lambda
class, import, yield |
def staircase(n):
for i in range(1, n + 1):
print(f'%{n - i}s' % '', end='')
for j in range(1, i + 1):
print('#', end='')
print()
staircase(6)
|
class WrongDirectionError(Exception):
"something tries to act on a wrong direction"
class ExhaustedError(Exception):
"An Anima cannot move towhere it wants"
|
import tensorflow as tf
import os, time, glob, sys
import random, ntpath
from importlib import import_module
import ops
tfe = tf.contrib.eager
def create_test_dataset(filenames):
dataset = tf.data.Dataset.from_tensor_slices((filenames))
dataset = dataset.map(ops.load_image, num_parallel_calls=4)
dataset = dataset.repeat(1)
dataset = dataset.batch(1)
dataset = dataset.prefetch(tf.contrib.data.AUTOTUNE)
return dataset
class Tester():
def __init__(self, args, model):
self.args = args
self.model = model
self.learning_rate = tfe.Variable(self.args.lr, dtype=tf.float32)
self.optimizer = tf.train.AdamOptimizer(learning_rate=self.learning_rate)
self.root = tf.train.Checkpoint(optimizer=self.optimizer,
model=self.model,
optimizer_step=tf.train.get_or_create_global_step())
lr_image_filenames = glob.glob('{}/LR/*.jpg'.format(args.test_dir))
assert len(lr_image_filenames) != 0
self.test_dataset = create_test_dataset(lr_image_filenames)
self.save_dir = os.path.join(self.args.test_dir, 'SR')
os.makedirs(self.save_dir, exist_ok=True)
def load_model(self, checkpoint_path=None):
if checkpoint_path is not None:
self.root.restore(checkpoint_path)
else:
self.root.restore(tf.train.latest_checkpoint(self.args.model_dir))
def test(self):
with tf.device('gpu:{}'.format(self.args.gpu_idx)):
for idx, input_image in enumerate(self.test_dataset):
output_image = self.model(input_image)
output_image = tf.clip_by_value(output_image, 0.0, 1.0)
output_image = output_image * 255.0
output_image = tf.cast(output_image, tf.uint8)
output_image = tf.squeeze(output_image)
with tf.device('cpu:0'):
output_image = tf.image.encode_png(output_image)
tf.io.write_file(os.path.join(self.save_dir, '{}.png'.format(idx)), output_image)
|
# To write/use the array data structure we use the array module
# from array import *
# arrayName = array(typecode, [Initializers])
from array import *
array1 = array('i',[10,20,30,40,50,60]) # Here 'i' stands for Signed integer of size 2 bytes
for x in array1:
print(x)
|
class Dog:
isMamma = True
def __init__(self, name = "No Name", age = -1):
self.name = name
self.age = age
def bark(self):
print("whoof! whoof! whoof! whoof!" + self.name)
Lassie = Dog("Lassie", 12)
Lassie.bark()
# Dog Snoopy = Dog("Snoopy", 15)
print("---------------------------------------")
class Rectangle:
def __init__(self, rLength = 0, rWidth = 0):
self.length = rLength
self.width = rWidth
def calcArea(self):
return self.length * self.width
Rec = Rectangle(28, 44)
print("Recatcglw Area = " + str(Rec.calcArea()))
print("---------------------------------------")
# pow
class Pow:
def __init__(self, pBase = 0, pPow = 0):
self.pBase = pBase
self.pPow = pPow
def calcPow(self):
resPow = self.pBase
for p in range(self.pPow-1):
resPow = resPow * self.pBase
print(resPow)
return resPow
p = Pow(8, 3)
print("Pow Result = " + str(p.calcPow()))
print("-------------- Inherite 2 -------------------------")
class Dog:
dSpec = ""
def __init__(self, name = "No Name", age = -1):
self.name = name
self.age = age
def setSpecies(self, species):
self.dSpec = species
def speak(self):
return "Burk! Burk! Burk! Burk!"
def description(self):
return "Dog name is : " + self.name + " " + str(self.age)
class RussleTerrir(Dog):
def __init__(self):
super().__init__("RusselTerrier", 15)
def speak(self):
return "RussleTerrir Bark !!!"
class Bulldog(Dog):
def __init__(self):
super().__init__("Bulldog", 25)
def speak(self):
return "Bulldog Bark !!!"
rt = RussleTerrir()
rt.setSpecies("species")
print(rt.description())
print(rt.speak())
bd = Bulldog()
print(bd.description())
print(bd.speak())
# print(super(rt.speak()))
print("-------------- Inherite static method -------------------------")
import math
class my_math_utils:
Pi1 = 3.14
@staticmethod
def calcCircleArea(radius):
return math.pi * radius * radius
print(my_math_utils.calcCircleArea(3))
print("-------------- packages -------------------------")
import datetime
print(datetime.datetime.now()) |
from django.urls import path
from .views import *
from django.conf.urls.static import static
from django.conf import settings
urlpatterns=[
path("",store,name="store"),
path("cart/",cart,name="cart"),
path("checkout/",checkout,name="checkout"),
path("update_item/",update_item,name="update_item"),
]
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) |
#!/usr/bin/env python
#-*- coding:utf-8; mode:python; indent-tabs-mode: nil; c-basic-offset: 2; tab-width: 2 -*-
from bes.testing.unit_test import unit_test
from bes.version.version_info import version_info
class test_version_info(unit_test):
def test_read_string(self):
text = '''\
BES_VERSION = u'1.0.0'
BES_AUTHOR_NAME = u'Sally Foo'
BES_AUTHOR_EMAIL = u'sally@foo.com'
BES_ADDRESS = u''
BES_TAG = u''
BES_TIMESTAMP = u''
'''
self.assertEqual( (u'1.0.0', u'Sally Foo', u'sally@foo.com', u'', u'', u''), version_info.read_string(text) )
def test___str__(self):
expected = '''\
#-*- coding:utf-8; mode:python; indent-tabs-mode: nil; c-basic-offset: 2; tab-width: 2 -*-
BES_VERSION = u'1.0'
BES_AUTHOR_NAME = u'Sally Bar'
BES_AUTHOR_EMAIL = u'sally@bar.com'
BES_ADDRESS = u''
BES_TAG = u''
BES_TIMESTAMP = u''
'''
self.assertMultiLineEqual( expected, str(version_info(u'1.0', u'Sally Bar', u'sally@bar.com', u'', u'', u'')) )
def test_change(self):
vi = version_info(u'1.0', u'Sally Bar', u'sally@bar.com', u'', u'', u'')
self.assertEqual( (u'1.0', u'Sally Bar', u'sally@bar.com', u'', u'666', u'123'), vi.change(tag = u'666', timestamp = u'123') )
def test_version_string(self):
self.assertEqual(u'1.0:foo@bar:123:abc', version_info(u'1.0', u'Sally Bar', u'sally@bar.com', u'foo@bar', u'123', u'abc').version_string() )
if __name__ == '__main__':
unit_test.main()
|
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "settings")
# This application object is used by the development server
# as well as any WSGI server configured to use this file.
# Cling for static files in production, as per
# https://devcenter.heroku.com/articles/django-assets
from django.core.wsgi import get_wsgi_application
from dj_static import Cling
application = Cling(get_wsgi_application())
# Fix django closing connection to MemCachier after every request (#11331)
# Added as per:
# https://devcenter.heroku.com/articles/django-memcache#optimize-performance
from django.core.cache.backends.memcached import BaseMemcachedCache
BaseMemcachedCache.close = lambda self, **kwargs: None |
import scrapy
import re
from tpdb.BaseSceneScraper import BaseSceneScraper
class siteLoadMyMouthSpider(BaseSceneScraper):
name = 'LoadMyMouth'
network = 'Load My Mouth'
start_urls = [
'http://www.loadmymouth.com',
]
selector_map = {
'title': '//div[@class="title"]/text()',
'description': '//div[@class="description"]/p/text()',
'date': '//strong[contains(text(),"Release Date")]/following-sibling::text()',
'image': '//span[@class="model_update_thumb"]/img/@src',
'performers': '//strong[contains(text(),"Starring")]/following-sibling::span/text()',
'tags': '',
'external_id': 'num=([a-zA-Z]{1,2}\d+)',
'trailer': '',
'pagination': '/home.php?page=%s'
}
def get_scenes(self, response):
meta = {}
scenes = response.xpath('//div[@class="item_wrapper" and not(.//text()[contains(.,"PHOTOSETS")])]')
for scene in scenes:
image = scene.xpath('.//div[@class="img_wrapper"]/a[1]/img/@src').get()
if image:
meta['image'] = image.strip()
else:
meta['image'] = ''
tags = scene.xpath('.//div[@class="tags"]/span/text()')
if tags:
tags = list(map(lambda x: x.strip().title(), tags.getall()))
tags = "".join(tags).strip()
tags = tags.split(",")
tags = list(map(lambda x: x.strip().title(), tags))
if '' in tags:
tags.remove('')
meta['tags'] = tags
else:
meta['tags'] = []
scene = scene.xpath('.//div[@class="play_btn"]/a/@href').get()
if re.search(self.get_selector_map('external_id'), scene):
yield scrapy.Request(url=self.format_link(response, scene), callback=self.parse_scene, meta=meta)
def get_site(self, response):
return "Load My Mouth"
def get_parent(self, response):
return "Load My Mouth"
def get_performers(self, response):
performers = self.process_xpath(response, self.get_selector_map('performers')).get()
if performers:
if "," in performers:
performers = performers.split(",")
else:
performers = [performers]
return list(map(lambda x: x.strip().title(), performers))
return []
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.