blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
616
content_id
stringlengths
40
40
detected_licenses
listlengths
0
112
license_type
stringclasses
2 values
repo_name
stringlengths
5
115
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
777 values
visit_date
timestamp[us]date
2015-08-06 10:31:46
2023-09-06 10:44:38
revision_date
timestamp[us]date
1970-01-01 02:38:32
2037-05-03 13:00:00
committer_date
timestamp[us]date
1970-01-01 02:38:32
2023-09-06 01:08:06
github_id
int64
4.92k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-04 01:52:49
2023-09-14 21:59:50
gha_created_at
timestamp[us]date
2008-05-22 07:58:19
2023-08-21 12:35:19
gha_language
stringclasses
149 values
src_encoding
stringclasses
26 values
language
stringclasses
1 value
is_vendor
bool
2 classes
is_generated
bool
2 classes
length_bytes
int64
3
10.2M
extension
stringclasses
188 values
content
stringlengths
3
10.2M
authors
listlengths
1
1
author_id
stringlengths
1
132
4d76d12c7c683eeb8987fa016591c981bc9da2f8
b58f43f49559265584d0bac330993d6e68729499
/FixValueStopLoss.py
64d14ba8fc41aaa9ab9a6d49faf392114dd0a4a6
[]
no_license
xiehai1983/MyPyLib
c096c3c60837db4b34a26aed88794a10a0f6b1e8
9d8e18443dac42325bb11525112deb59eb49ab9b
refs/heads/master
2021-09-21T22:23:38.478730
2018-09-01T16:29:21
2018-09-01T16:29:21
null
0
0
null
null
null
null
UTF-8
Python
false
false
8,482
py
# -*- coding: utf-8 -*- """ 策略本身不带出场,全靠止盈止损出场,所以在止损取数时没有下限 从进场点开始,while True向下取数(还要判断是否达到原始数据下限),如果达到止损或者止盈点,就break出来 使用1min的high和low来模拟tick,1min数据不做阴阳线预处理,如果1min同时满足止盈和止损,则取止损作为结果 """ import pandas as pd import DATA_CONSTANTS as DC import numpy as np import os import ResultStatistics as RS import multiprocessing def fix_value_stop_loss(strategyName, symbolInfo, K_MIN, setname, bar1mdic, barxmdic, result_para_dic, spr, slr, tofolder, indexcols): print ("fix_value_stop_loss: setname:%s, spr%.1f slr%.1f" % (setname, spr, slr)) positionRatio = result_para_dic['positionRatio'] initialCash = result_para_dic['initialCash'] symbol = symbolInfo.domain_symbol bt_folder = "%s %d backtesting\\" % (symbol, K_MIN) oprdf = pd.read_csv(bt_folder + strategyName + ' ' + symbol + str(K_MIN) + ' ' + setname + ' result.csv') symbolDomainDic = symbolInfo.amendSymbolDomainDicByOpr(oprdf) bar1m = DC.getDomainbarByDomainSymbol(symbolInfo.getSymbolList(), bar1mdic, symbolDomainDic) barxm = DC.getDomainbarByDomainSymbol(symbolInfo.getSymbolList(), barxmdic, symbolDomainDic) #bar1m.set_index('utc_time', inplace=True) barxm.set_index('utc_time', inplace=True) oprdf['new_closeprice'] = oprdf['closeprice'] oprdf['new_closetime'] = oprdf['closetime'] oprdf['new_closeindex'] = oprdf['closeindex'] oprdf['new_closeutc'] = oprdf['closeutc'] oprdf['max_opr_gain'] = 0 # 本次操作期间的最大收益 oprdf['min_opr_gain'] = 0 # 本次操作期间的最小收益 oprdf['max_dd'] = 0 oprnum = oprdf.shape[0] pricetick = symbolInfo.getPriceTick() worknum = 0 for i in range(oprnum): opr = oprdf.iloc[i] #startutc = (barxm.loc[barxm['utc_time'] == opr.openutc]).iloc[0].utc_endtime - 60 # 从开仓的10m线结束后开始 #endutc = (barxm.loc[barxm['utc_time'] == opr.closeutc]).iloc[0].utc_endtime # 一直到平仓的10m线结束 openutc = opr.openutc openprice = opr.openprice startutc = barxm.loc[openutc].utc_endtime - 60 #spv = barxm.iloc[openutc].ATR * spr #slv = barxm.iloc[openutc].ATR * slr spv = 5 # 固定取值 slv = 8 # 固定取值 oprtype = opr.tradetype openprice = opr.openprice start_index_1m = bar1m[bar1m['utc_time'].isin([startutc])].index[0] # 开仓位置在1m数据中的index,要从下一根开始算止盈止损 while True: start_index_1m += 1 high_1m = bar1m.loc[start_index_1m,'high'] low_1m = bar1m.loc[start_index_1m].low if oprtype == 1: if low_1m <= (openprice - slv): # 最低值达到止损门限 oprdf.ix[i, 'new_closeprice'] = openprice - slv oprdf.ix[i, 'new_closetime'] = bar1m.iloc[start_index_1m].strtime oprdf.ix[i, 'new_closeindex'] = start_index_1m oprdf.ix[i, 'new_closeutc'] = bar1m.iloc[start_index_1m].utc_time break elif high_1m >= (openprice + spv): # 最大值达到止盈门限 oprdf.ix[i, 'new_closeprice'] = openprice + spv oprdf.ix[i, 'new_closetime'] = bar1m.iloc[start_index_1m].strtime oprdf.ix[i, 'new_closeindex'] = start_index_1m oprdf.ix[i, 'new_closeutc'] = bar1m.iloc[start_index_1m].utc_time break elif oprtype == -1: if high_1m >= (openprice + slv): # 最大值达到止损门限 oprdf.ix[i, 'new_closeprice'] = openprice + slv oprdf.ix[i, 'new_closetime'] = bar1m.iloc[start_index_1m].strtime oprdf.ix[i, 'new_closeindex'] = start_index_1m oprdf.ix[i, 'new_closeutc'] = bar1m.iloc[start_index_1m].utc_time break elif low_1m <= (openprice - spv): # 最大值达到止盈门限 oprdf.ix[i, 'new_closeprice'] = openprice - spv oprdf.ix[i, 'new_closetime'] = bar1m.iloc[start_index_1m].strtime oprdf.ix[i, 'new_closeindex'] = start_index_1m oprdf.ix[i, 'new_closeutc'] = bar1m.iloc[start_index_1m].utc_time break else: # 被去极值的操作,oprtype为0,不做止损操作 pass slip = symbolInfo.getSlip() # 2017-12-08:加入滑点 oprdf['new_ret'] = ((oprdf['new_closeprice'] - oprdf['openprice']) * oprdf['tradetype']) - slip oprdf['new_ret_r'] = oprdf['new_ret'] / oprdf['openprice'] # 去极值:在parallel的去极值结果上,把极值的new_ret和new_ret_r值0 if result_para_dic['remove_polar_switch']: oprdf.loc[oprdf['tradetype']==0, 'new_ret'] = 0 oprdf.loc[oprdf['tradetype']==0, 'new_ret_r'] = 0 oprdf['new_commission_fee'], oprdf['new_per earn'], oprdf['new_own cash'], oprdf['new_hands'] = RS.calcResult(oprdf, symbolInfo, initialCash, positionRatio, ret_col='new_ret') # 保存新的result文档 oprdf.to_csv(tofolder + strategyName + ' ' + symbol + str(K_MIN) + ' ' + setname + ' resultDSL_by_tick.csv', index=False) olddailydf = pd.read_csv(strategyName + ' ' + symbol + str(K_MIN) + ' ' + setname + ' dailyresult.csv', index_col='date') # 计算统计结果 oldr = RS.getStatisticsResult(oprdf, False, indexcols, olddailydf) barxm.reset_index(drop=False, inplace=True) dailyK = DC.generatDailyClose(barxm) dR = RS.dailyReturn(symbolInfo, oprdf, dailyK, initialCash) # 计算生成每日结果 dR.calDailyResult() dR.dailyClose.to_csv((tofolder + strategyName + ' ' + symbol + str(K_MIN) + ' ' + setname + ' dailyresultDSL_by_tick.csv')) newr = RS.getStatisticsResult(oprdf, True, indexcols, dR.dailyClose) del oprdf # return [setname,slTarget,worknum,oldendcash,oldAnnual,oldSharpe,oldDrawBack,oldSR,newendcash,newAnnual,newSharpe,newDrawBack,newSR,max_single_loss_rate] print newr return [setname, spr, slr, worknum] + oldr + newr if __name__ == '__main__': import datetime # 参数配置 exchange_id = 'SHFE' sec_id = 'RB' symbol = '.'.join([exchange_id, sec_id]) K_MIN = 600 topN = 5000 pricetick = DC.getPriceTick(symbol) slip = pricetick starttime = '2016-01-01' endtime = '2018-03-31' # 优化参数 stoplossStep = -0.002 # stoplossList = np.arange(-0.022, -0.042, stoplossStep) stoplossList = [-0.022] # 文件路径 currentpath = DC.getCurrentPath() bar1m = DC.getBarData(symbol=symbol, K_MIN=60, starttime=starttime + ' 00:00:00', endtime=endtime + ' 00:00:00') barxm = DC.getBarData(symbol=symbol, K_MIN=K_MIN, starttime=starttime + ' 00:00:00', endtime=endtime + ' 00:00:00') # bar1m计算longHigh,longLow,shortHigh,shortLow bar1m['longHigh'] = bar1m['high'] bar1m['shortHigh'] = bar1m['high'] bar1m['longLow'] = bar1m['low'] bar1m['shortLow'] = bar1m['low'] bar1m['highshift1'] = bar1m['high'].shift(1).fillna(0) bar1m['lowshift1'] = bar1m['low'].shift(1).fillna(0) bar1m.loc[bar1m['open'] < bar1m['close'], 'longHigh'] = bar1m['highshift1'] bar1m.loc[bar1m['open'] > bar1m['close'], 'shortLow'] = bar1m['lowshift1'] timestart = datetime.datetime.now() dslCal(symbol, K_MIN, 'Set0 MS3 ML8 KN6 DN6', bar1m, barxm, pricetick, slip, -0.022, currentpath + '\\') timedsl = timestart - datetime.datetime.now() timestart = datetime.datetime.now() fastDslCal(symbol, K_MIN, 'Set0 MS3 ML8 KN6 DN6', bar1m, barxm, pricetick, slip, -0.022, currentpath + '\\') timefast = timestart - datetime.datetime.now() print "time dsl cost:", timedsl print "time fast cost:", timefast print 'fast delta:', timefast - timedsl
[ "smartgang@126.com" ]
smartgang@126.com
1f974b0b8b3caa1deb01b81c53090810a9f1b06a
33119d4e3ec1abd3b8a3934b90ede748669f87c9
/armi/operators/settingsValidation.py
52003d7dc9e91f8893cca94316b6d69ed5d1d42b
[ "Apache-2.0", "LicenseRef-scancode-free-unknown" ]
permissive
sammiller11235/armi
723506a47f292f1a83e9d3c35812d080e9acbbdc
df9bdb4d8ef3131806190e0d18710c6a7df73961
refs/heads/master
2021-07-19T12:00:07.397525
2020-03-19T17:36:58
2020-03-19T17:36:58
219,067,927
0
0
Apache-2.0
2020-03-19T17:37:00
2019-11-01T21:52:13
null
UTF-8
Python
false
false
24,554
py
# Copyright 2019 TerraPower, LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ A system to check user settings for validity and provide users with meaningful suggestions to fix. This allows developers to specify a rich set of rules and suggestions for user settings. These then pop up during initialization of a run, either on the command line or as dialogues in the GUI. They say things like: "Your ___ setting has the value ___, which is impossible. Would you like to switch to ___?" """ import re import os import armi from armi import runLog from armi.localization import exceptions from armi import utils from armi.utils import pathTools from armi.nucDirectory import nuclideBases from armi.reactor import geometry from armi.physics import neutronics from armi import settings from armi.utils import directoryChangers from armi.settings.fwSettings import globalSettings class Query: """An individual query.""" def __init__(self, condition, statement, question, correction): """ Construct a query. Parameters ---------- condition : callable A callable that returns True or False. If True, then the query activates its question and potential correction. statement : str A statement of the problem indicated by a True condition question : str A question asking the user for confirmation of the proposed fix. correction : callable A callable that when called fixes the situation. See :py:meth:`Inspector.NO_ACTION` for no-ops. """ self.condition = condition self.statement = statement self.question = question self.correction = correction # True if the query is `passed` and does not result in an immediate failure self._passed = False self._corrected = False self.autoResolved = True def __repr__(self): # Add representation so that it's possible to identify which one # is being referred to when there are errors. return "<Query: {}>".format(self.statement) def __bool__(self): try: return bool(self.condition()) except TypeError: runLog.error( f"Invalid setting validation query. Update validator for: {self})" ) raise __nonzero__ = __bool__ # Python2 compatibility def isCorrective(self): return self.correction is not Inspector.NO_ACTION def resolve(self): """Standard i/o prompt for resolution of an individual query""" if armi.MPI_RANK != 0: return if self.condition(): try: if self.isCorrective(): try: make_correction = runLog.prompt( "INSPECTOR: " + self.statement, self.question, "YES_NO", "NO_DEFAULT", "CANCEL", ) if make_correction: self.correction() self._corrected = True else: self._passed = True except exceptions.RunLogPromptCancel: raise exceptions.InputInspectionDiscontinued() else: try: continue_submission = runLog.prompt( "INSPECTOR: " + self.statement, "Continue?", "YES_NO", "NO_DEFAULT", "CANCEL", ) if not continue_submission: raise exceptions.InputInspectionDiscontinued() except exceptions.RunLogPromptCancel: raise exceptions.InputInspectionDiscontinued() except exceptions.RunLogPromptUnresolvable: self.autoResolved = False self._passed = True class Inspector: """ This manages queries which assert certain states of the data model, generally presenting themselves to the user, offering information on the potential problem, a question and the action to take on an affirmative and negative answer from the user. In practice very useful for making sure setting values are as intended and without bad interplay with one another. One Inspector will contain multiple Queries and be associated directly with an :py:class:`~armi.operators.operator.Operator`. """ @staticmethod def NO_ACTION(): # pylint: disable=invalid-name """Convenience callable used to generate Queries that can't be easily auto-resolved.""" return None def __init__(self, cs): """ Construct an inspector. Parameters ---------- cs : Settings """ self.queries = [] self.cs = cs self.geomType = None self.coreSymmetry = None self._inspectBlueprints() self._setGeomType() self._inspectSettings() # Gather and attach validators from all plugins # This runs on all registered plugins, not just active ones. pluginQueries = armi.getPluginManagerOrFail().hook.defineSettingsValidators( inspector=self ) for queries in pluginQueries: self.queries.extend(queries) def run(self, cs=None): """ Run through each query and deal with it if possible. Returns ------- correctionsMade : bool Whether or not anything was updated. Raises ------ exceptions.InputInspectionMalformed When a programming error causes queries to loop. """ if armi.MPI_RANK != 0: return False # the following attribute changes will alter what the queries investigate when # resolved correctionsMade = False self.cs = cs or self.cs runLog.debug("{} executing queries.".format(self.__class__.__name__)) if not any(self.queries): runLog.debug( "{} found no problems with the current state.".format( self.__class__.__name__ ) ) else: for query in self.queries: query.resolve() if query._corrected: # pylint: disable=protected-access correctionsMade = True issues = [ query for query in self.queries if query and ( query.isCorrective() and not query._passed ) # pylint: disable=protected-access ] if any(issues): # something isn't resolved or was unresolved by changes raise exceptions.InputInspectionMalformed( "The input inspection did not resolve all queries, " "some issues are creating cyclic resolutions: {}".format(issues) ) runLog.debug("{} has finished querying.".format(self.__class__.__name__)) return correctionsMade def addQuery(self, condition, statement, question, correction): """Convenience method, query must be resolved, else run fails""" if not callable(correction): raise ValueError( 'Query for "{}" malformed. Expecting callable.'.format(statement) ) self.queries.append(Query(condition, statement, question, correction)) def addQueryBadLocationWillLikelyFail(self, settingName): """Add a query indicating the current path for ``settingName`` does not exist and will likely fail.""" self.addQuery( lambda: not os.path.exists(pathTools.armiAbsPath(self.cs[settingName])), "Setting {} points to nonexistent location\n{}\nFailure extremely likely".format( settingName, self.cs[settingName] ), "", self.NO_ACTION, ) def addQueryCurrentSettingMayNotSupportFeatures(self, settingName): """Add a query that the current value for ``settingName`` may not support certain features.""" self.addQuery( lambda: self.cs[settingName] != self.cs.settings[settingName].default, "{} set as:\n{}\nUsing this location instead of the default location\n{}\n" "may not support certain functions.".format( settingName, self.cs[settingName], self.cs.settings[settingName].default ), "Revert to default location?", lambda: self._assignCS(settingName, self.cs.settings[settingName].default), ) def _assignCS(self, key, value): """Lambda assignment workaround""" # this type of assignment works, but be mindful of # scoping when trying different methods self.cs[key] = value def _raise(self): # pylint: disable=no-self-use raise exceptions.InputInspectionDiscontinued( "Input inspection has been interrupted." ) def _inspectBlueprints(self): """Blueprints early error detection and old format conversions.""" from armi.reactor import blueprints self.addQuery( lambda: not self.cs["loadingFile"], "No blueprints file loaded. Run will probably fail.", "", self.NO_ACTION, ) self.addQuery( lambda: not self._csRelativePathExists(self.cs["loadingFile"]), "Blueprints file {} not found. Run will fail.".format( self.cs["loadingFile"] ), "", self.NO_ACTION, ) def _csRelativePathExists(self, filename): csRelativePath = self._csRelativePath(filename) return os.path.exists(csRelativePath) and os.path.isfile(csRelativePath) def _csRelativePath(self, filename): return os.path.join(self.cs.inputDirectory, filename) def _setGeomType(self): if self.cs["geomFile"]: with directoryChangers.DirectoryChanger(self.cs.inputDirectory): geom = geometry.SystemLayoutInput() geom.readGeomFromFile(self.cs["geomFile"]) self.geomType, self.coreSymmetry = geom.geomType, geom.symmetry def _inspectSettings(self): """Check settings for inconsistencies.""" # import here to avoid cyclic issues from armi import operators self.addQuery( lambda: self.cs.path.endswith(".xml"), "Your settings were loaded from a XML file. These are being converted to yaml files.", "Would you like to auto-convert it to YAML?", lambda: settings.convertSettingsFromXMLToYaml(self.cs), ) self.addQueryBadLocationWillLikelyFail("operatorLocation") self.addQuery( lambda: self.cs["outputFileExtension"] == "pdf" and self.cs["genReports"], "Output files of '.pdf' format are not supported by the reporting HTML generator. '.pdf' " "images will not be included.", "Switch to '.png'?", lambda: self._assignCS("outputFileExtension", "png"), ) self.addQuery( lambda: ( self.cs[globalSettings.CONF_ZONING_STRATEGY] == "manual" and not self.cs["zoneDefinitions"] ), "`manual` zoningStrategy requires that `zoneDefinitions` setting be defined. Run will have " "no zones.", "", self.NO_ACTION, ) self.addQuery( lambda: self.cs["skipCycles"] > 0 and not self.cs["reloadDBName"], "You have chosen to do a restart case without specifying a database to load from. " "Run will load from output files, if they exist but burnup, etc. will not be updated.", "", self.NO_ACTION, ) self.addQuery( lambda: self.cs["runType"] != operators.RunTypes.SNAPSHOTS and self.cs["loadStyle"] == "fromDB" and self.cs["startCycle"] == 0 and self.cs["startNode"] == 0, "Starting from cycle 0, and time node 0 was chosen. Restart runs load from " "the time node just before the restart. There is no time node to load from " "before cycle 0 node 0. Either switch to the snapshot operator, start from " "a different time step or load from inputs rather than database as " "`loadStyle`.", "", self.NO_ACTION, ) self.addQuery( lambda: self.cs["runType"] == operators.RunTypes.SNAPSHOTS and not (self.cs["dumpSnapshot"] or self.cs["defaultSnapshots"]), "The Snapshots operator was specified, but no dump snapshots were chosen." "Please specify snapshot steps with the `dumpSnapshot` setting.", "", self.NO_ACTION, ) self.addQuery( lambda: self.cs.caseTitle.lower() == os.path.splitext(os.path.basename(self.cs["reloadDBName"].lower()))[0], "Snapshot DB ({0}) and main DB ({1}) cannot have the same name." "Change name of settings file and resubmit.".format( self.cs["reloadDBName"], self.cs.caseTitle ), "", self.NO_ACTION, ) self.addQuery( lambda: self.cs["reloadDBName"] != "" and not os.path.exists(self.cs["reloadDBName"]), "Reload database {} does not exist. \nPlease point to an existing DB, " "or set to empty and load from input.".format(self.cs["reloadDBName"]), "", self.NO_ACTION, ) def _willBeCopiedFrom(fName): for copyFile in self.cs["copyFilesFrom"]: if fName == os.path.split(copyFile)[1]: return True return False self.addQuery( lambda: self.cs["explicitRepeatShuffles"] and not self._csRelativePathExists(self.cs["explicitRepeatShuffles"]) and not _willBeCopiedFrom(self.cs["explicitRepeatShuffles"]), "The specified repeat shuffle file `{0}` does not exist, and won't be copied from elsewhere. " "Run will crash.".format(self.cs["explicitRepeatShuffles"]), "", self.NO_ACTION, ) self.addQuery( lambda: not self.cs["power"], "No power level set. You must always start by importing a base settings file.", "", self.NO_ACTION, ) # The gamma cross sections generated for MC2-3 by ANL were done with NJOY with # P3 scattering. MC2-3 would have to be modified and the gamma cross sections # re-generated with NJOY for MC2-3 to allow any other scattering order with # gamma cross sections enabled. self.addQuery( lambda: ( "MC2v3" in self.cs["xsKernel"] and neutronics.gammaXsAreRequested(self.cs) and self.cs["xsScatteringOrder"] != 3 ), "MC2-3 will crash if a scattering order is not set to 3 when generating gamma XS.", "Would you like to set the `xsScatteringOrder` to 3?", lambda: self._assignCS("xsScatteringOrder", 3), ) self.addQuery( lambda: self.cs["outputCacheLocation"] and not os.path.exists(self.cs["outputCacheLocation"]), "`outputCacheLocation` path {} does not exist. Please specify a location that exists.".format( self.cs["outputCacheLocation"] ), "", self.NO_ACTION, ) self.addQuery( lambda: self.cs["numCoupledIterations"] > 0, "You have {0} coupling iterations selected.".format( self.cs["numCoupledIterations"] ), "1 coupling iteration doubles run time (2 triples, etc). Do you want to use 0 instead? ", lambda: self._assignCS("numCoupledIterations", 0), ) def _factorsAreValid(factors, maxVal=1.0): try: expandedList = utils.expandRepeatedFloats(factors) except (ValueError, IndexError): return False return ( all(0.0 <= val <= maxVal for val in expandedList) and len(expandedList) == self.cs["nCycles"] ) self.addQuery( lambda: self.cs["availabilityFactors"] and not _factorsAreValid(self.cs["availabilityFactors"]), "`availabilityFactors` was not set to a list compatible with the number of cycles. " "Please update input or use constant duration.", "Use constant availability factor specified in `availabilityFactor` setting?", lambda: self._assignCS("availabilityFactors", []), ) self.addQuery( lambda: self.cs["powerFractions"] and not _factorsAreValid(self.cs["powerFractions"]), "`powerFractions` was not set to a compatible list. " "Please update input or use full power at all cycles.", "Use full power for all cycles?", lambda: self._assignCS("powerFractions", []), ) self.addQuery( lambda: ( self.cs["cycleLengths"] and not _factorsAreValid(self.cs["cycleLengths"], maxVal=1e10) ), "The number of cycles defined in `cycleLengths` is not equal to the number of cycles in " "the run `nCycles`." "Please ensure that there is exactly one duration for each cycle in the run or use " "{} days for all cycles.".format(self.cs["cycleLength"]), "Use {} days for all cycles?".format(self.cs["cycleLength"]), lambda: self._assignCS("cycleLengths", []), ) def _correctCycles(): self.cs["nCycles"] = 1 self.cs["burnSteps"] = 0 self.addQuery( lambda: not self.cs["cycleLengths"] and self.cs["nCycles"] == 0, "Cannot run 0 cycles. Set burnSteps to 0 to activate a single time-independent case.", "Set 1 cycle and 0 burnSteps for single time-independent case?", _correctCycles, ) self.addQuery( lambda: ( self.cs["runType"] == "Standard" and self.cs["burnSteps"] == 0 and (len(self.cs["cycleLengths"]) > 1 or self.cs["nCycles"] > 1) ), "Cannot run multi-cycle standard cases with 0 burnSteps per cycle. Please update settings.", "", self.NO_ACTION, ) def decayCyclesHaveInputThatWillBeIgnored(): """Check if there is any decay-related input that will be ignored.""" try: powerFracs = utils.expandRepeatedFloats(self.cs["powerFractions"]) availabilities = utils.expandRepeatedFloats( self.cs["availabilityFactors"] ) or ([self.cs["availabilityFactor"]] * self.cs["nCycles"]) except: # pylint: disable=bare-except return True for pf, af in zip(powerFracs, availabilities): if pf > 0.0 and af == 0.0: # this will be a full decay step and any power fraction will be ignored. May be ok, but warn. return True return False self.addQuery( lambda: ( self.cs["cycleLengths"] and self.cs["powerFractions"] and decayCyclesHaveInputThatWillBeIgnored() ), "At least one cycle has a non-zero power fraction but an availability of zero. Please " "update the input.", "", self.NO_ACTION, ) self.addQuery( lambda: self.cs["operatorLocation"] and self.cs["runType"] != operators.RunTypes.STANDARD, "The `runType` setting is set to `{0}` but there is a `custom operator location` defined".format( self.cs["runType"] ), "", self.NO_ACTION, ) self.addQuery( lambda: self.cs["operatorLocation"] and self.cs["runType"] != operators.RunTypes.STANDARD, "The `runType` setting is set to `{0}` but there is a `custom operator location` defined".format( self.cs["runType"] ), "", self.NO_ACTION, ) self.addQuery( lambda: self.cs["skipCycles"] > 0 and not os.path.exists(self.cs.caseTitle + ".restart.dat"), "This is a restart case, but the required restart file {0}.restart.dat is not found".format( self.cs.caseTitle ), "", self.NO_ACTION, ) self.addQuery( lambda: self.cs["deferredInterfacesCycle"] > self.cs["nCycles"], "The deferred interface activation cycle exceeds set cycle occurrence. " "Interfaces will not be activated in this run!", "", self.NO_ACTION, ) self.addQuery( lambda: ( neutronics.MCNP not in self.cs["neutronicsKernel"] and self.cs["boundaries"] != neutronics.GENERAL_BC and self.cs["bcCoefficient"] ), "General neutronic boundary condition was not selected, but `bcCoefficient` was defined. " "Please enable `Generalized` neutronic boundary condition or disable `bcCoefficient`.", "", self.NO_ACTION, ) self.addQuery( lambda: self.cs["geomFile"] and self.geomType not in geometry.VALID_GEOMETRY_TYPE, "{} is not a valid geometry Please update geom type on the geom xml file. " "Valid (case insensitive) geom types are: {}".format( self.geomType, geometry.VALID_GEOMETRY_TYPE ), "", self.NO_ACTION, ) self.addQuery( lambda: self.cs["geomFile"] and self.coreSymmetry not in geometry.VALID_SYMMETRY, "{} is not a valid symmetry Please update symmetry on the geom xml file. " "Valid (case insensitive) symmetries are: {}".format( self.coreSymmetry, geometry.VALID_SYMMETRY ), "", self.NO_ACTION, ) def createQueryRevertBadPathToDefault(inspector, settingName, initialLambda=None): """ Return a query to revert a bad path to its default. Parameters ---------- inspector: Inspector the inspector who's settings are being queried settingName: str name of the setting to inspect initialLambda: None or callable function If ``None``, the callable argument for :py:meth:`addQuery` is does the setting's path exist. If more complicated callable arguments are needed, they can be passed in as the ``initialLambda`` setting. """ if initialLambda is None: initialLambda = lambda: ( not os.path.exists(pathTools.armiAbsPath(inspector.cs[settingName])) and inspector.cs.settings[settingName].offDefault ) # solution is to revert to default query = Query( initialLambda, "Setting {} points to a nonexistent location:\n{}".format( settingName, inspector.cs[settingName] ), "Revert to default location?", inspector.cs.settings[settingName].revertToDefault, ) return query
[ "ntouran@terrapower.com" ]
ntouran@terrapower.com
756dbc3df7bc68f0e80a6229fbfb208cda5d9bf9
874fc4e4eac88ccd037110ce5f48b930c83bb4b3
/db/actions/add_field.py
bc0d3f11c3b84886a92cb5707566761baf40466e
[]
no_license
persontianshuang/mafter
d0231519d9e82bd0a6aa8e42aa11a5a8a37c407c
64d9382917bffc16f0422e0fe6e300f48c95c79a
refs/heads/master
2021-01-23T16:25:34.535702
2017-09-27T09:16:03
2017-09-27T09:16:03
102,740,653
0
0
null
null
null
null
UTF-8
Python
false
false
390
py
from db.config import _Db from db.sentences.sentence import Sentences from db.subFlow.flow import Flow # for x in _Db['sentences'].find(): # print(x) # for x in Sentences.objects.all(): # x.type = 'video' # x.save() # for x in Flow.objects.all(): # x.type = 'video' # x.save() new_flow = Flow() new_flow.name = '能力考N3' new_flow.type = 'ntext' new_flow.save()
[ "mengyouhan@gmail.com" ]
mengyouhan@gmail.com
57f4ee94bd87e3f3ad1a8d105c30c3bc127bd6c7
1513d0d708b8789f8d85fbd2a8ff46e863d16cd6
/day_two/Exercise1.py
6fbb7e0133dd5189518d654e7df31d1a7676ca4c
[]
no_license
zingpython/february2018
ff9d0f64d6f68d5b0f22b87eaab202d06a85f224
0edcdd85bfbec168c7daf5a88bb06ce1b58062f7
refs/heads/master
2021-05-04T05:34:58.032678
2018-02-22T18:40:05
2018-02-22T18:40:05
120,341,634
0
2
null
null
null
null
UTF-8
Python
false
false
192
py
for number in range(1, 101): if number % 3 == 0 and number % 5 == 0: print("FizzBuzz") elif number % 3 == 0: print("Fizz") elif number % 5 == 0: print("Buzz") else: print(number)
[ "selpathor@verizon.net" ]
selpathor@verizon.net
f6dd1ef36f6a06a7afb6323e9d3df94e4689cc62
db053c220094368ecb784fbe62375378c97457c2
/810.chalkboard-xor-game.py
541ac93fa7085e6032b36a1b6febb1ee272fdd8d
[]
no_license
thegamingcoder/leetcode
8c16e7ac9bda3e34ba15955671a91ad072e87d94
131facec0a0c70d319982e78e772ed1cb94bc461
refs/heads/master
2020-03-22T14:51:45.246495
2018-07-09T00:00:06
2018-07-09T00:00:06
140,211,147
0
0
null
null
null
null
UTF-8
Python
false
false
1,600
py
# # [828] Chalkboard XOR Game # # https://leetcode.com/problems/chalkboard-xor-game/description/ # # algorithms # Hard (38.94%) # Total Accepted: 1.4K # Total Submissions: 3.5K # Testcase Example: '[1,1,2]' # # We are given non-negative integers nums[i] which are written on a # chalkboard.  Alice and Bob take turns erasing exactly one number from the # chalkboard, with Alice starting first.  If erasing a number causes the # bitwise XOR of all the elements of the chalkboard to become 0, then that # player loses.  (Also, we'll say the bitwise XOR of one element is that # element itself, and the bitwise XOR of no elements is 0.) # # Also, if any player starts their turn with the bitwise XOR of all the # elements of the chalkboard equal to 0, then that player wins. # # Return True if and only if Alice wins the game, assuming both players play # optimally. # # # Example: # Input: nums = [1, 1, 2] # Output: false # Explanation: # Alice has two choices: erase 1 or erase 2. # If she erases 1, the nums array becomes [1, 2]. The bitwise XOR of all the # elements of the chalkboard is 1 XOR 2 = 3. Now Bob can remove any element he # wants, because Alice will be the one to erase the last element and she will # lose. # If Alice erases 2 first, now nums becomes [1, 1]. The bitwise XOR of all the # elements of the chalkboard is 1 XOR 1 = 0. Alice will lose. # # # # Notes: # # # 1 <= N <= 1000.  # 0 <= nums[i] <= 2^16. # # # # # class Solution(object): def xorGame(self, nums): """ :type nums: List[int] :rtype: bool """
[ "sharanbale@yahoo-inc.com" ]
sharanbale@yahoo-inc.com
fce3df2153532f4e0401e80f02abcd99ab77ed8f
a56a74b362b9263289aad96098bd0f7d798570a2
/venv/lib/python3.8/site-packages/matplotlib/tests/test_gridspec.py
70d1ee132851d785ff973695a03dadb7b10f2947
[ "MIT" ]
permissive
yoonkt200/ml-theory-python
5812d06841d30e1068f6592b5730a40e87801313
7643136230fd4f291b6e3dbf9fa562c3737901a2
refs/heads/master
2022-12-21T14:53:21.624453
2021-02-02T09:33:07
2021-02-02T09:33:07
132,319,537
13
14
MIT
2022-12-19T17:23:57
2018-05-06T08:17:45
Python
UTF-8
Python
false
false
626
py
import matplotlib.gridspec as gridspec import pytest def test_equal(): gs = gridspec.GridSpec(2, 1) assert gs[0, 0] == gs[0, 0] assert gs[:, 0] == gs[:, 0] def test_width_ratios(): """ Addresses issue #5835. See at https://github.com/matplotlib/matplotlib/issues/5835. """ with pytest.raises(ValueError): gridspec.GridSpec(1, 1, width_ratios=[2, 1, 3]) def test_height_ratios(): """ Addresses issue #5835. See at https://github.com/matplotlib/matplotlib/issues/5835. """ with pytest.raises(ValueError): gridspec.GridSpec(1, 1, height_ratios=[2, 1, 3])
[ "kitae.yoon@deliveryhero.co.kr" ]
kitae.yoon@deliveryhero.co.kr
6b87d5ce8490d1eb8056fb41b49cc0fa2608ceee
d1ef84d05beedc811161314800193ded398bff07
/tests/test_database_crudmixin.py
1767d5202f8df4c91803f6ee4b79e1def990b02d
[ "MIT" ]
permissive
spookey/observatory
8f4a98aeb214182124bc6a4ab6d1ddac697cd0bc
be5cc92f53f12e6341e7e3040f26360e54cfdf7d
refs/heads/master
2023-04-22T03:31:34.879735
2021-01-16T17:50:07
2021-01-16T17:50:07
224,500,136
0
0
MIT
2021-05-12T03:53:02
2019-11-27T19:11:24
Python
UTF-8
Python
false
false
3,032
py
from pytest import mark from observatory.database import TXT_LEN_SHORT, CRUDMixin from observatory.start.extensions import DB # pylint: disable=no-member PAYLOAD = 'omg wtf bbq' LAYPOAD = 'napfkuchen!' class CRUDMixinPhony(CRUDMixin, DB.Model): prime = DB.Column(DB.Integer(), primary_key=True) value = DB.Column(DB.String(length=TXT_LEN_SHORT)) @mark.usefixtures('session') class TestCRUDMixin: @staticmethod def test_create_no_commit(): crud = CRUDMixinPhony.create(value=PAYLOAD, _commit=False) assert crud.prime is None assert crud.value == PAYLOAD assert crud in CRUDMixinPhony.query.all() @staticmethod def test_create_commit(): crud = CRUDMixinPhony.create(value=PAYLOAD, _commit=True) assert crud.prime == 1 assert crud.value == PAYLOAD assert crud in CRUDMixinPhony.query.all() @staticmethod def test_update_no_comit(): crud = CRUDMixinPhony.create(value=PAYLOAD, _commit=False) assert crud.value == PAYLOAD crud.update(value=LAYPOAD, _commit=False) assert crud.value == LAYPOAD @staticmethod def test_update_comit(): crud = CRUDMixinPhony.create(value=PAYLOAD, _commit=True) assert crud.value == PAYLOAD crud.update(value=LAYPOAD, _commit=True) assert crud.value == LAYPOAD @staticmethod def test_save_no_commit(session): crud = CRUDMixinPhony.create(value=PAYLOAD, _commit=False) assert crud not in session.dirty crud.value = LAYPOAD assert crud not in session.dirty crud.save(_commit=False) assert crud not in session.dirty @staticmethod def test_save_commit(session): crud = CRUDMixinPhony.create(value=PAYLOAD, _commit=True) assert crud not in session.dirty crud.value = LAYPOAD assert crud in session.dirty crud.save(_commit=True) assert crud not in session.dirty @staticmethod def test_delete_no_commit(): crud = CRUDMixinPhony.create(value=PAYLOAD, _commit=False) assert crud in CRUDMixinPhony.query.all() crud.delete(_commit=False) assert crud not in CRUDMixinPhony.query.all() @staticmethod def test_delete_commit(): crud = CRUDMixinPhony.create(value=PAYLOAD, _commit=True) assert crud in CRUDMixinPhony.query.all() crud.delete(_commit=True) assert crud not in CRUDMixinPhony.query.all() @staticmethod def test_logging(caplog): crud = CRUDMixinPhony.create(value='yes', _commit=True) log_c, log_s = caplog.records[-2:] assert 'creating' in log_c.message.lower() assert 'saving' in log_s.message.lower() crud.update(value='no') log_u, log_s = caplog.records[-2:] assert 'updating' in log_u.message.lower() assert 'saving' in log_s.message.lower() crud.delete() log_d = caplog.records[-1] assert 'deleting' in log_d.message.lower()
[ "frieder.griesshammer@der-beweis.de" ]
frieder.griesshammer@der-beweis.de
c291d5f571a0f7d5576a959395261c1c80e20196
6879a8596df6f302c63966a2d27f6b4d11cc9b29
/abc/problems110/108/c.py
01a176ce06f31360c7967885d3140fefde3cf214
[]
no_license
wkwkgg/atcoder
41b1e02b88bf7a8291b709306e54cb56cb93e52a
28a7d4084a4100236510c05a88e50aa0403ac7cd
refs/heads/master
2020-07-26T03:47:19.460049
2020-03-01T18:29:57
2020-03-01T18:29:57
208,523,188
0
0
null
null
null
null
UTF-8
Python
false
false
250
py
N, K = map(int, input().split()) nums = [0] * K for i in range(1, N + 1): nums[i % K] += 1 ans = 0 for i in range(K): b = (K - i) % K c = (K - i) % K if (b + c) % K != 0: continue ans += nums[i] * nums[b] * nums[c] print(ans)
[ "yujin@komachi.live" ]
yujin@komachi.live
9b21a1d828f30ab5a1d04f765922419abe11a89c
a5408385bc6cc06cbc783652bd4d019af184ca7c
/examples/diffusion/sinbc.py
5020f09b30d418719f4cbb6a07543487260f4fb9
[ "BSD-3-Clause" ]
permissive
snilek/sfepy
5a65d2e49c1d49d1a50f1d6d080f6e0f2f78e9f0
7f50684441cbbd3c7497cb32ba63ae4d1bf3ce28
refs/heads/master
2021-01-15T12:36:10.195016
2014-05-06T11:59:02
2014-05-06T11:59:02
null
0
0
null
null
null
null
UTF-8
Python
false
false
3,826
py
r""" Laplace equation with Dirichlet boundary conditions given by a sine function and constants. Find :math:`t` such that: .. math:: \int_{\Omega} c \nabla s \cdot \nabla t = 0 \;, \quad \forall s \;. This example demonstrates how to use a hierarchical basis approximation - it uses the fifth order Lobatto polynomial space for the solution. The adaptive linearization is applied in order to save viewable results, see both the options keyword and the ``post_process()`` function that computes the solution gradient. Use the following commands to view the results (assuming default output directory and names):: $ ./postproc.py -b -d't,plot_warp_scalar,rel_scaling=1' 2_4_2_refined_t.vtk --wireframe $ ./postproc.py -b 2_4_2_refined_grad.vtk The :class:`sfepy.discrete.fem.meshio.UserMeshIO` class is used to refine the original two-element mesh before the actual solution. """ import numpy as nm from sfepy import data_dir from sfepy.base.base import output from sfepy.discrete.fem import Mesh, Domain from sfepy.discrete.fem.meshio import UserMeshIO, MeshIO from sfepy.homogenization.utils import define_box_regions base_mesh = data_dir + '/meshes/elements/2_4_2.mesh' def mesh_hook(mesh, mode): """ Load and refine a mesh here. """ if mode == 'read': mesh = Mesh.from_file(base_mesh) domain = Domain(mesh.name, mesh) for ii in range(3): output('refine %d...' % ii) domain = domain.refine() output('... %d nodes %d elements' % (domain.shape.n_nod, domain.shape.n_el)) domain.mesh.name = '2_4_2_refined' return domain.mesh elif mode == 'write': pass def post_process(out, pb, state, extend=False): """ Calculate gradient of the solution. """ from sfepy.discrete.fem.fields_base import create_expression_output aux = create_expression_output('ev_grad.ie.Elements( t )', 'grad', 'temperature', pb.fields, pb.get_materials(), pb.get_variables(), functions=pb.functions, mode='qp', verbose=False, min_level=0, max_level=5, eps=1e-3) out.update(aux) return out filename_mesh = UserMeshIO(mesh_hook) # Get the mesh bounding box. io = MeshIO.any_from_filename(base_mesh) bbox, dim = io.read_bounding_box(ret_dim=True) options = { 'nls' : 'newton', 'ls' : 'ls', 'post_process_hook' : 'post_process', 'linearization' : { 'kind' : 'adaptive', 'min_level' : 0, # Min. refinement level to achieve everywhere. 'max_level' : 5, # Max. refinement level. 'eps' : 1e-3, # Relative error tolerance. }, } materials = { 'coef' : ({'val' : 1.0},), } regions = { 'Omega' : 'all', } regions.update(define_box_regions(dim, bbox[0], bbox[1], 1e-5)) fields = { 'temperature' : ('real', 1, 'Omega', 5, 'H1', 'lobatto'), # Compare with the Lagrange basis. ## 'temperature' : ('real', 1, 'Omega', 5, 'H1', 'lagrange'), } variables = { 't' : ('unknown field', 'temperature', 0), 's' : ('test field', 'temperature', 't'), } amplitude = 1.0 def ebc_sin(ts, coor, **kwargs): x0 = 0.5 * (coor[:, 1].min() + coor[:, 1].max()) val = amplitude * nm.sin( (coor[:, 1] - x0) * 2. * nm.pi ) return val ebcs = { 't1' : ('Left', {'t.0' : 'ebc_sin'}), 't2' : ('Right', {'t.0' : -0.5}), 't3' : ('Top', {'t.0' : 1.0}), } functions = { 'ebc_sin' : (ebc_sin,), } equations = { 'Temperature' : """dw_laplace.10.Omega( coef.val, s, t ) = 0""" } solvers = { 'ls' : ('ls.scipy_direct', {}), 'newton' : ('nls.newton', { 'i_max' : 1, 'eps_a' : 1e-10, }), }
[ "cimrman3@ntc.zcu.cz" ]
cimrman3@ntc.zcu.cz
80949b51021d641887cbf7cfdd89a8444cd9394f
664bb3b0d806b3d17b1f4c5b87e569dcafac9710
/0x03-python-data_structures/8-multiple_returns.py
cb9621277c528249e82d3c718e5867e6060a5b74
[]
no_license
emmanavarro/holbertonschool-higher_level_programming
9f120234b0521ad8330307af303f5f587764f30a
2cae27d29d11035f62742240e1d1a5e385be075c
refs/heads/master
2022-12-25T22:24:36.183806
2020-09-24T23:35:59
2020-09-24T23:35:59
259,382,761
0
1
null
null
null
null
UTF-8
Python
false
false
205
py
#!/usr/bin/python3 def multiple_returns(sentence): if sentence is "": tupl = (len(sentence), None) return tupl else: tupl = (len(sentence), sentence[0]) return tupl
[ "elnavarro55@gmail.com" ]
elnavarro55@gmail.com
8a2bf3ac4361e3dcaa79a5a6ec7b73196c40724d
06a7dc7cc93d019e4a9cbcf672b23a0bbacf8e8b
/2016_schizConnect/supervised_analysis/all_studies+VIP/all_subjects/Freesurfer/ROIs/learning_curve_ratios_centered_by_site_all/inter_site/svm_ratio_0_2.py
6d995cf717bfe5921917fd5fa23e8ad5ee42ee14
[]
no_license
neurospin/scripts
6c06cd218a5f32de9c3c2b7d1d8bda3f3d107458
f14a2c9cf2cd7f5fbea767b017c3faf36d170bdb
refs/heads/master
2021-07-11T22:55:46.567791
2021-07-02T13:08:02
2021-07-02T13:08:02
10,549,286
2
2
null
null
null
null
UTF-8
Python
false
false
12,914
py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Thu Feb 23 10:04:13 2017 @author: ad247405 """ import os import json import numpy as np from sklearn.cross_validation import StratifiedKFold from sklearn.metrics import precision_recall_fscore_support from scipy.stats import binom_test from collections import OrderedDict from sklearn import preprocessing from sklearn.metrics import roc_auc_score from sklearn import svm import pandas as pd import shutil from brainomics import array_utils import mapreduce from sklearn.metrics import recall_score, roc_auc_score, precision_recall_fscore_support from statsmodels.stats.inter_rater import fleiss_kappa WD = '/neurospin/brainomics/2016_schizConnect/analysis/all_studies+VIP/Freesurfer/all_subjects/results/ROIs_analysis/mean_centered_by_site_all/volume/learning_curve/inter_site/ratio_0.2' def config_filename(): return os.path.join(WD,"config_dCV.json") def results_filename(): return os.path.join(WD,"results_dCV.xlsx") NFOLDS_OUTER = 5 NFOLDS_INNER = 5 penalty_start = 3 ############################################################################# def load_globals(config): import mapreduce as GLOBAL # access to global variables GLOBAL.DATA = GLOBAL.load_data(config["data"]) def resample(config, resample_nb): import mapreduce as GLOBAL # access to global variables GLOBAL.DATA = GLOBAL.load_data(config["data"]) resample = config["resample"][resample_nb] GLOBAL.DATA_RESAMPLED = {k: [GLOBAL.DATA[k][idx, ...] for idx in resample] for k in GLOBAL.DATA} def mapper(key, output_collector): import mapreduce as GLOBAL Xtr = GLOBAL.DATA_RESAMPLED["X"][0] Xte = GLOBAL.DATA_RESAMPLED["X"][1] ytr = GLOBAL.DATA_RESAMPLED["y"][0] yte = GLOBAL.DATA_RESAMPLED["y"][1] c = float(key[0]) print("c:%f" % (c)) class_weight='balanced' # unbiased mask = np.ones(Xtr.shape[0], dtype=bool) scaler = preprocessing.StandardScaler().fit(Xtr) Xtr = scaler.transform(Xtr) Xte=scaler.transform(Xte) mod = svm.LinearSVC(C=c,fit_intercept=False,class_weight= class_weight) mod.fit(Xtr, ytr.ravel()) y_pred = mod.predict(Xte) y_proba_pred = mod.decision_function(Xte) ret = dict(y_pred=y_pred, y_true=yte,prob_pred = y_proba_pred, beta=mod.coef_, mask=mask) if output_collector: output_collector.collect(key, ret) else: return ret def scores(key, paths, config): values = [mapreduce.OutputCollector(p) for p in paths] try: values = [item.load() for item in values] except Exception as e: print(e) return None y_true_splits = [item["y_true"].ravel() for item in values] y_pred_splits = [item["y_pred"].ravel() for item in values] y_true = np.concatenate(y_true_splits) y_pred = np.concatenate(y_pred_splits) prob_pred_splits = [item["prob_pred"].ravel() for item in values] prob_pred = np.concatenate(prob_pred_splits) # Prediction performances p, r, f, s = precision_recall_fscore_support(y_true, y_pred, average=None) auc = roc_auc_score(y_true, prob_pred) # balanced accuracy (recall_mean) bacc_splits = [recall_score(y_true_splits[f], y_pred_splits[f], average=None).mean() for f in range(len(y_true_splits))] auc_splits = [roc_auc_score(y_true_splits[f], prob_pred_splits[f]) for f in range(len(y_true_splits))] print("bacc all - mean(bacc) %.3f" % (r.mean() - np.mean(bacc_splits))) # P-values success = r * s success = success.astype('int') prob_class1 = np.count_nonzero(y_true) / float(len(y_true)) pvalue_recall0_true_prob = binom_test(success[0], s[0], 1 - prob_class1,alternative = 'greater') pvalue_recall1_true_prob = binom_test(success[1], s[1], prob_class1,alternative = 'greater') pvalue_recall0_unknwon_prob = binom_test(success[0], s[0], 0.5,alternative = 'greater') pvalue_recall1_unknown_prob = binom_test(success[1], s[1], 0.5,alternative = 'greater') pvalue_bacc = binom_test(success[0]+success[1], s[0] + s[1], p=0.5,alternative = 'greater') # Beta's measures of similarity betas = np.hstack([item["beta"][:, penalty_start:].T for item in values]).T # Correlation R = np.corrcoef(betas) R = R[np.triu_indices_from(R, 1)] # Fisher z-transformation / average z_bar = np.mean(1. / 2. * np.log((1 + R) / (1 - R))) # bracktransform r_bar = (np.exp(2 * z_bar) - 1) / (np.exp(2 * z_bar) + 1) # threshold betas to compute fleiss_kappa and DICE try: betas_t = np.vstack([ array_utils.arr_threshold_from_norm2_ratio(betas[i, :], .99)[0] for i in range(betas.shape[0])]) # Compute fleiss kappa statistics beta_signed = np.sign(betas_t) table = np.zeros((beta_signed.shape[1], 3)) table[:, 0] = np.sum(beta_signed == 0, 0) table[:, 1] = np.sum(beta_signed == 1, 0) table[:, 2] = np.sum(beta_signed == -1, 0) fleiss_kappa_stat = fleiss_kappa(table) # Paire-wise Dice coeficient ij = [[i, j] for i in range(betas.shape[0]) for j in range(i+1, betas.shape[0])] dices = list() for idx in ij: A, B = beta_signed[idx[0], :], beta_signed[idx[1], :] dices.append(float(np.sum((A == B)[(A != 0) & (B != 0)])) / (np.sum(A != 0) + np.sum(B != 0))) dice_bar = np.mean(dices) except: dice_bar = fleiss_kappa_stat = 0 # Proportion of selection within the support accross the CV support_count = (betas_t != 0).sum(axis=0) support_count = support_count[support_count > 0] support_prop = support_count / betas_t.shape[0] scores = OrderedDict() scores['key'] = key scores['recall_0'] = r[0] scores['recall_1'] = r[1] scores['bacc'] = r.mean() scores['bacc_se'] = np.std(bacc_splits) / np.sqrt(len(bacc_splits)) scores["auc"] = auc scores['auc_se'] = np.std(auc_splits) / np.sqrt(len(auc_splits)) scores['pvalue_recall0_true_prob_one_sided'] = pvalue_recall0_true_prob scores['pvalue_recall1_true_prob_one_sided'] = pvalue_recall1_true_prob scores['pvalue_recall0_unknwon_prob_one_sided'] = pvalue_recall0_unknwon_prob scores['pvalue_recall1_unknown_prob_one_sided'] = pvalue_recall1_unknown_prob scores['pvalue_bacc_mean'] = pvalue_bacc scores['prop_non_zeros_mean'] = float(np.count_nonzero(betas_t)) / \ float(np.prod(betas.shape)) scores['beta_r_bar'] = r_bar scores['beta_fleiss_kappa'] = fleiss_kappa_stat scores['beta_dice_bar'] = dice_bar scores['beta_dice'] = str(dices) scores['beta_r'] = str(R) scores['beta_support_prop_select_mean'] = support_prop.mean() scores['beta_support_prop_select_sd'] = support_prop.std() return scores def reducer(key, values): import os, glob, pandas as pd os.chdir(os.path.dirname(config_filename())) config = json.load(open(config_filename())) paths = glob.glob(os.path.join(config['map_output'], "*", "*", "*")) #paths = [p for p in paths if not p.count("0.8_-1")] def close(vec, val, tol=1e-4): return np.abs(vec - val) < tol def groupby_paths(paths, pos): groups = {g:[] for g in set([p.split("/")[pos] for p in paths])} for p in paths: groups[p.split("/")[pos]].append(p) return groups def argmaxscore_bygroup(data, groupby='fold', param_key="key", score="bacc"): arg_max_byfold = list() for fold, data_fold in data.groupby(groupby): # assert len(data_fold) == len(set(data_fold[param_key])) # ensure all param are diff arg_max_byfold.append([fold, data_fold.ix[data_fold[score].argmax()][param_key], data_fold[score].max()]) return pd.DataFrame(arg_max_byfold, columns=[groupby, param_key, score]) print('## Refit scores') print('## ------------') byparams = groupby_paths([p for p in paths if p.count("all") and not p.count("all/all")],3) byparams_scores = {k:scores(k, v, config) for k, v in byparams.items()} data = [list(byparams_scores[k].values()) for k in byparams_scores] columns = list(byparams_scores[list(byparams_scores.keys())[0]].keys()) scores_refit = pd.DataFrame(data, columns=columns) print('## doublecv scores by outer-cv and by params') print('## -----------------------------------------') data = list() bycv = groupby_paths([p for p in paths if p.count("cvnested")],1) for fold, paths_fold in bycv.items(): print(fold) byparams = groupby_paths([p for p in paths_fold], 3) byparams_scores = {k:scores(k, v, config) for k, v in byparams.items()} data += [[fold] + list(byparams_scores[k].values()) for k in byparams_scores] scores_dcv_byparams = pd.DataFrame(data, columns=["fold"] + columns) print('## Model selection') print('## ---------------') svm = argmaxscore_bygroup(scores_dcv_byparams); svm["method"] = "svm" scores_argmax_byfold = svm print('## Apply best model on refited') print('## ---------------------------') scores_svm = scores("nestedcv", [os.path.join(config['map_output'], row["fold"], "all", row["key"]) for index, row in svm.iterrows()], config) scores_cv = pd.DataFrame([["svm"] + list(scores_svm.values())], columns=["method"] + list(scores_svm.keys())) with pd.ExcelWriter(results_filename()) as writer: scores_refit.to_excel(writer, sheet_name='cv_by_param', index=False) scores_dcv_byparams.to_excel(writer, sheet_name='cv_cv_byparam', index=False) scores_argmax_byfold.to_excel(writer, sheet_name='cv_argmax', index=False) scores_cv.to_excel(writer, sheet_name='dcv', index=False) ############################################################################## if __name__ == "__main__": INPUT_DATA_X = '/neurospin/brainomics/2016_schizConnect/analysis/all_studies+VIP/Freesurfer/all_subjects/data/data_ROIs/mean_centered_by_site_all/Xrois_volumes_mean_centered_by_site+cov.npy' INPUT_DATA_y = '/neurospin/brainomics/2016_schizConnect/analysis/all_studies+VIP/Freesurfer/all_subjects/data/data_ROIs/mean_centered_by_site_all/y.npy' NFOLDS_OUTER = 4 #number of sites NFOLDS_INNER = 5 shutil.copy(INPUT_DATA_X, WD) shutil.copy(INPUT_DATA_y, WD) ############################################################################# ## Create config file y = np.load(INPUT_DATA_y) #COBRE = 1, NMORPH = 2, NUSDAST = 3, VIP = 4 site = np.load("/neurospin/brainomics/2016_schizConnect/analysis/all_studies+VIP/Freesurfer/all_subjects/data/site.npy") cv_outer = [[tr, te] for tr,te in StratifiedKFold(y.ravel(), n_folds=NFOLDS_OUTER, random_state=42)] cv_outer[0][0] = np.transpose(np.where(site != 1)).ravel() cv_outer[0][1] = np.transpose(np.where(site == 1)).ravel() #CV00 TEST ON COBRE cv_outer[1][0] = np.transpose(np.where(site != 2)).ravel() cv_outer[1][1] = np.transpose(np.where(site == 2)).ravel() #CV01 TEST ON NMORPHch cv_outer[2][0] = np.transpose(np.where(site != 3)).ravel() cv_outer[2][1] = np.transpose(np.where(site == 3)).ravel() #CV02 TEST ON NUSDAST cv_outer[3][0] = np.transpose(np.where(site != 4)).ravel() cv_outer[3][1] = np.transpose(np.where(site == 4)).ravel() #CV03 TEST ON VIP cv_outer[0][0] = cv_outer[0][0][:int(np.around(len(cv_outer[0][0])*0.2))] cv_outer[1][0] = cv_outer[1][0][:int(np.around(len(cv_outer[1][0])*0.2))] cv_outer[2][0] = cv_outer[2][0][:int(np.around(len(cv_outer[2][0])*0.2))] cv_outer[3][0] = cv_outer[3][0][:int(np.around(len(cv_outer[3][0])*0.2))] import collections cv = collections.OrderedDict() for cv_outer_i, (tr_val, te) in enumerate(cv_outer): cv["cv%02d/all" % (cv_outer_i)] = [tr_val, te] cv_inner = StratifiedKFold(y[tr_val].ravel(), n_folds=NFOLDS_INNER, random_state=42) for cv_inner_i, (tr, val) in enumerate(cv_inner): cv["cv%02d/cvnested%02d" % ((cv_outer_i), cv_inner_i)] = [tr_val[tr], tr_val[val]] for k in cv: cv[k] = [cv[k][0].tolist(), cv[k][1].tolist()] C_range = [[100],[10],[1],[1e-1],[1e-2],[1e-3],[1e-4],[1e-5],[1e-6],[1e-7],[1e-8],[1e-9]] user_func_filename = "/home/ad247405/git/scripts/2016_schizConnect/supervised_analysis/all_studies+VIP/all_subjects/Freesurfer/ROIs/learning_curve_ratios_centered_by_site_all/inter_site/svm_ratio_0_2.py" config = dict(data=dict(X=os.path.basename(INPUT_DATA_X), y="y.npy"), params=C_range, resample=cv, map_output="model_selectionCV", user_func=user_func_filename, reduce_input="results/*/*", reduce_group_by="params", reduce_output="model_selectionCV.csv") json.dump(config, open(os.path.join(WD, "config_dCV.json"), "w"))
[ "ad247405@is222241.intra.cea.fr" ]
ad247405@is222241.intra.cea.fr
681013f7bacd0db8a1b4d25d995954b7fe7df8ed
43df78355915e3f41f432579c5840816f52a8ace
/Functions/Two/Calc_NDM.py
e484e15cd3977780679d69c0bc37613e93af8a36
[ "Apache-2.0" ]
permissive
spareeth/wa
fd7617fafe065de83249cf817df25cf9ca164518
57bb0c93af1bab3b6f8bc30cbc941aa14ac2696b
refs/heads/master
2020-03-06T15:33:26.208373
2018-03-22T08:04:06
2018-03-22T08:04:06
null
0
0
null
null
null
null
UTF-8
Python
false
false
5,117
py
# -*- coding: utf-8 -*- """ Authors: Tim Hessels UNESCO-IHE 2017 Contact: t.hessels@unesco-ihe.org Repository: https://github.com/wateraccounting/wa Module: Function/Two """ # import general python modules import os import gdal import numpy as np import pandas as pd import glob def NPP_GPP_Based(Dir_Basin, Data_Path_GPP, Data_Path_NPP, Startdate, Enddate): """ This functions calculated monthly NDM based on the yearly NPP and monthly GPP. Parameters ---------- Dir_Basin : str Path to all the output data of the Basin Data_Path_GPP : str Path from the Dir_Basin to the GPP data Data_Path_NPP : str Path from the Dir_Basin to the NPP data Startdate : str Contains the start date of the model 'yyyy-mm-dd' Enddate : str Contains the end date of the model 'yyyy-mm-dd' Simulation : int Defines the simulation Returns ------- Data_Path_NDM : str Path from the Dir_Basin to the normalized dry matter data """ # import WA+ modules import wa.General.data_conversions as DC import wa.General.raster_conversions as RC # Define output folder for Normalized Dry Matter Data_Path_NDM = "NDM" out_folder = os.path.join(Dir_Basin, Data_Path_NDM) if not os.path.exists(out_folder): os.mkdir(out_folder) # Define input folders GPP_folder = os.path.join(Dir_Basin, Data_Path_GPP) NPP_folder = os.path.join(Dir_Basin, Data_Path_NPP) # Define monthly time steps that will be created Dates = pd.date_range(Startdate, Enddate, freq = 'MS') # Define the years that will be calculated Year_Start = int(Startdate[0:4]) Year_End = int(Enddate[0:4]) Years = range(Year_Start, Year_End+1) # Loop over the years for year in Years: # Change working directory to the NPP folder os.chdir(NPP_folder) # Open yearly NPP data yearly_NPP_File = glob.glob('*yearly*%d.01.01.tif' %int(year))[0] Yearly_NPP = RC.Open_tiff_array(yearly_NPP_File) # Get the No Data Value of the NPP file dest = gdal.Open(yearly_NPP_File) NDV = dest.GetRasterBand(1).GetNoDataValue() # Set the No Data Value to Nan Yearly_NPP[Yearly_NPP == NDV] = np.nan # Change working directory to the GPP folder os.chdir(GPP_folder) # Find all the monthly files of that year monthly_GPP_Files = glob.glob('*monthly*%d.*.01.tif' %int(year)) # Check if it are 12 files otherwise something is wrong and send the ERROR if not len(monthly_GPP_Files) == 12: print 'ERROR: Some monthly GPP Files are missing' # Get the projection information of the GPP inputs geo_out, proj, size_X, size_Y = RC.Open_array_info(monthly_GPP_Files[0]) if int(proj.split('"')[-2]) == 4326: proj = "WGS84" # Get the No Data Value of the GPP files dest = gdal.Open(monthly_GPP_Files[0]) NDV = dest.GetRasterBand(1).GetNoDataValue() # Create a empty numpy array Yearly_GPP = np.zeros([size_Y, size_X]) # Calculte the total yearly GPP for monthly_GPP_File in monthly_GPP_Files: # Open array Data = RC.Open_tiff_array(monthly_GPP_File) # Remove nan values Data[Data == NDV] = np.nan # Add data to yearly sum Yearly_GPP += Data # Loop over the monthly dates for Date in Dates: # If the Date is in the same year as the yearly NPP and GPP if Date.year == year: # Create empty GPP array monthly_GPP = np.ones([size_Y, size_X]) * np.nan # Get current month month = Date.month # Get the GPP file of the current year and month monthly_GPP_File = glob.glob('*monthly_%d.%02d.01.tif' %(int(year), int(month)))[0] monthly_GPP = RC.Open_tiff_array(monthly_GPP_File) monthly_GPP[monthly_GPP == NDV] = np.nan # Calculate the NDM based on the monthly and yearly NPP and GPP (fraction of GPP) Monthly_NDM = Yearly_NPP * monthly_GPP / Yearly_GPP * (30./12.) *10000 # kg/ha # Define output name output_name = os.path.join(out_folder, 'NDM_MOD17_kg_ha-1_monthly_%d.%02d.01.tif' %(int(year), int(month))) # Save the NDM as tiff file DC.Save_as_tiff(output_name, Monthly_NDM, geo_out, proj) return(Data_Path_NDM)
[ "timhessels@hotmail.com" ]
timhessels@hotmail.com
73afcff6d269bc975c7d86680ee09916cd096372
36407bb880c5ca94331f1bc44b85be58bba6f352
/apps/rating/migrations/0001_initial.py
6e902a0de600f12a5514e21ac3aec25a4d1f5c37
[]
no_license
raw-data-tech/home-garden
28175f66d126fa57f652fce22cd89ab44c514bba
8767815b010b3d7d83927e912b3e055374c06111
refs/heads/master
2020-12-24T17:17:05.629239
2015-07-11T09:05:52
2015-07-11T09:05:52
38,920,104
0
0
null
null
null
null
UTF-8
Python
false
false
1,147
py
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations import django.utils.timezone from django.conf import settings class Migration(migrations.Migration): dependencies = [ ('orders', '0001_initial'), migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Rating', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('rating', models.PositiveIntegerField(verbose_name=b'rating', choices=[(1, 1), (2, 2), (3, 3), (4, 4), (5, 5)])), ('remark', models.CharField(max_length=200, null=True, blank=True)), ('date', models.DateTimeField(default=django.utils.timezone.now)), ('order', models.ForeignKey(related_name=b'ratings', to='orders.Order')), ('user', models.ForeignKey(related_name=b'ratings', to=settings.AUTH_USER_MODEL)), ], options={ }, bases=(models.Model,), ), ]
[ "navajyothms1989@gmail.com" ]
navajyothms1989@gmail.com
d29a74acd9b141fc75873408944238d813de7f96
d2189145e7be2c836017bea0d09a473bf1bc5a63
/Reposicion_cuarta clase/contar los numeros multiplos de 3 que hay entre 1-100.py
45d3f1bff695c5720b917c501d80e6ad0046391f
[]
no_license
emilianoNM/Tecnicas3
12d10ce8d78803c8d2cd6a721786a68f7ee2809d
6ad7f0427ab9e23643a28ac16889bca8791421d0
refs/heads/master
2020-03-25T18:06:34.126165
2018-11-24T04:42:14
2018-11-24T04:42:14
144,013,045
3
5
null
2018-09-14T10:47:26
2018-08-08T12:49:57
Python
UTF-8
Python
false
false
226
py
### Imprimir y contar los numeros multiplos de 3 que hay entre 1 y 100. n = 1 h = 0 while n < 100: if n%3 == 0: print n, h += 1 n += 1 print '\nEntre 1 y 100 hay %i numeros multiplos de 3' % h
[ "noreply@github.com" ]
emilianoNM.noreply@github.com
9cf18d8324650ac3c321885809cf31acd683c320
f61cf1a24fa184dd552dd47dd8399b74c5816ee0
/tasks/13/13-2.py
e4cf7fab84e1ca127f6ecbb21c47ecca597e0f05
[]
no_license
desve/netology
ea585d9db8658eea5319b98f63259239fa538fcb
c6039cc831058b8ba650d417fae25f761520139b
refs/heads/master
2020-01-23T21:11:31.291807
2017-04-06T05:19:08
2017-04-06T05:19:08
74,572,766
0
0
null
null
null
null
UTF-8
Python
false
false
80
py
# Правильная скобочная последовательность
[ "2901243@mail.ru" ]
2901243@mail.ru
ed33bc3916a5067ac5211b768fae4fa08ec4d051
900aaf3f7d0063ed3b4a90d7afc0e75bb847a1f2
/hash_tables/group_shifted_strings.py
33bd6b693a830615e45efabb37aabb75be2ebe35
[]
no_license
rjcrter11/leetChallenges
5797fbdd818525af1fec8d2907d03fe9e4c586fb
bfd0ee6221310c88a619ec3203e281f4b0cc8184
refs/heads/master
2023-04-21T06:53:02.887548
2021-05-24T12:24:13
2021-05-24T12:24:13
283,039,834
0
0
null
null
null
null
UTF-8
Python
false
false
816
py
'''Given a string, we can "shift" each of its letter to its successive letter, for example: "abc" -> "bcd". We can keep "shifting" which forms the sequence: "abc" -> "bcd" -> ... -> "xyz" Given a list of non-empty strings which contains only lowercase alphabets, group all strings that belong to the same shifting sequence. Example: Input: ["abc", "bcd", "acef", "xyz", "az", "ba", "a", "z"], Output: [ ["abc","bcd","xyz"], ["az","ba"], ["acef"], ["a","z"] ] ''' from collections import defaultdict def groupStrings(strings): def diff(s): return tuple((ord(a) - ord(b)) % 26 for a, b in zip(s, s[1:])) d = defaultdict(list) for s in strings: d[diff(s)].append(s) return d.values() strings = ["abc", "bcd", "acef", "xyz", "az", "ba", "a", "z"] print(groupStrings(strings))
[ "rjcrter11@gmail.com" ]
rjcrter11@gmail.com
682ce86400bb9c2269a57401c0661a75d61c9b53
5174acc0ca3a8582711881dcf6a1a36663e964a9
/servicios_aplicacion/selector_entrada.py
f35868471f873fe833cdcd7dece7f9bd1a598ca8
[]
no_license
vvalotto/fiuner_termostato
b9ac7918458d06a479f516bd3f7a2550bb4d6b78
a3e81040672a438ea512895016201cb93104469e
refs/heads/master
2020-05-24T05:06:45.940613
2019-07-01T10:21:51
2019-07-01T10:21:51
187,106,514
0
0
null
null
null
null
UTF-8
Python
false
false
1,523
py
""" Clase Responsable del establecimiento de la temperatura deseada """ from gestores_entidades.gestor_ambiente import * class SelectorEntradaTemperatura: def __init__(self, gestor_ambiente): """ Arma la clases con la que necesita colaborar """ self._seteo_temperatura = Configurador.configurar_seteo_temperatura() self._selector_temperatura = Configurador.configurar_selector_temperatura() self._gestor_ambiente = gestor_ambiente return def ejecutar(self): """ Ejecucion periodica para observar si el usuario quiere setear la temperatura En caso que asi sea, se queda ciclando para leer el ingreso de las consignas :return: """ while self._selector_temperatura.obtener_selector() == "deseada": self._mostrar_temperatura_deseada() self._obtener_seteo_temperatura_deseada() self._gestor_ambiente.indicar_temperatura_a_mostrar("ambiente") return def _mostrar_temperatura_deseada(self): self._gestor_ambiente.indicar_temperatura_a_mostrar("deseada") self._gestor_ambiente.mostrar_temperatura() return def _obtener_seteo_temperatura_deseada(self): opcion = self._seteo_temperatura.obtener_seteo() if opcion == "aumentar": self._gestor_ambiente.aumentar_temperatura_deseada() if opcion == "disminuir": self._gestor_ambiente.disminuir_temperatura_deseada() return
[ "vvalotto@gmail.com" ]
vvalotto@gmail.com
2828841fc71fbcf1498c40698d5aa047ae752abf
1bfad01139237049eded6c42981ee9b4c09bb6de
/RestPy/ixnetwork_restpy/testplatform/sessions/ixnetwork/vport/protocols/linkoam/link/eventnotificationlearnedinfo/eventnotificationlearnedinfo.py
176e1cdb756989f951c1552cfebdfe9893f86680
[ "MIT" ]
permissive
kakkotetsu/IxNetwork
3a395c2b4de1488994a0cfe51bca36d21e4368a5
f9fb614b51bb8988af035967991ad36702933274
refs/heads/master
2020-04-22T09:46:37.408010
2019-02-07T18:12:20
2019-02-07T18:12:20
170,284,084
0
0
MIT
2019-02-12T08:51:02
2019-02-12T08:51:01
null
UTF-8
Python
false
false
9,566
py
# Copyright 1997 - 2018 by IXIA Keysight # # 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 ixnetwork_restpy.base import Base from ixnetwork_restpy.files import Files class EventNotificationLearnedInfo(Base): """The EventNotificationLearnedInfo class encapsulates a system managed eventNotificationLearnedInfo node in the ixnetwork hierarchy. An instance of the class can be obtained by accessing the EventNotificationLearnedInfo property from a parent instance. The internal properties list will be empty when the property is accessed and is populated from the server by using the find method. """ _SDM_NAME = 'eventNotificationLearnedInfo' def __init__(self, parent): super(EventNotificationLearnedInfo, self).__init__(parent) @property def LocalFrameErrorRunningTotal(self): """ Returns: number """ return self._get_attribute('localFrameErrorRunningTotal') @property def LocalFrameEventRunningTotal(self): """ Returns: number """ return self._get_attribute('localFrameEventRunningTotal') @property def LocalFramePeriodErrorRunningTotal(self): """ Returns: number """ return self._get_attribute('localFramePeriodErrorRunningTotal') @property def LocalFramePeriodEventRunningTotal(self): """ Returns: number """ return self._get_attribute('localFramePeriodEventRunningTotal') @property def LocalFrameSecSumErrorRunningTotal(self): """ Returns: number """ return self._get_attribute('localFrameSecSumErrorRunningTotal') @property def LocalFrameSecSumEventRunningTotal(self): """ Returns: number """ return self._get_attribute('localFrameSecSumEventRunningTotal') @property def LocalSymbolPeriodErrorRunningTotal(self): """ Returns: number """ return self._get_attribute('localSymbolPeriodErrorRunningTotal') @property def LocalSymbolPeriodEventRunningTotal(self): """ Returns: number """ return self._get_attribute('localSymbolPeriodEventRunningTotal') @property def RemoteFrameError(self): """ Returns: number """ return self._get_attribute('remoteFrameError') @property def RemoteFrameErrorRunningTotal(self): """ Returns: number """ return self._get_attribute('remoteFrameErrorRunningTotal') @property def RemoteFrameEventRunningTotal(self): """ Returns: number """ return self._get_attribute('remoteFrameEventRunningTotal') @property def RemoteFramePeriodError(self): """ Returns: number """ return self._get_attribute('remoteFramePeriodError') @property def RemoteFramePeriodErrorRunningTotal(self): """ Returns: number """ return self._get_attribute('remoteFramePeriodErrorRunningTotal') @property def RemoteFramePeriodEventRunningTotal(self): """ Returns: number """ return self._get_attribute('remoteFramePeriodEventRunningTotal') @property def RemoteFramePeriodThreshold(self): """ Returns: number """ return self._get_attribute('remoteFramePeriodThreshold') @property def RemoteFramePeriodWindow(self): """ Returns: number """ return self._get_attribute('remoteFramePeriodWindow') @property def RemoteFrameSecSumError(self): """ Returns: number """ return self._get_attribute('remoteFrameSecSumError') @property def RemoteFrameSecSumErrorRunningTotal(self): """ Returns: number """ return self._get_attribute('remoteFrameSecSumErrorRunningTotal') @property def RemoteFrameSecSumEventRunningTotal(self): """ Returns: number """ return self._get_attribute('remoteFrameSecSumEventRunningTotal') @property def RemoteFrameSecSumThreshold(self): """ Returns: number """ return self._get_attribute('remoteFrameSecSumThreshold') @property def RemoteFrameSecSumWindow(self): """ Returns: number """ return self._get_attribute('remoteFrameSecSumWindow') @property def RemoteFrameThreshold(self): """ Returns: number """ return self._get_attribute('remoteFrameThreshold') @property def RemoteFrameWindow(self): """ Returns: number """ return self._get_attribute('remoteFrameWindow') @property def RemoteSymbolPeriodErrorRunningTotal(self): """ Returns: number """ return self._get_attribute('remoteSymbolPeriodErrorRunningTotal') @property def RemoteSymbolPeriodErrors(self): """ Returns: number """ return self._get_attribute('remoteSymbolPeriodErrors') @property def RemoteSymbolPeriodEventRunningTotal(self): """ Returns: number """ return self._get_attribute('remoteSymbolPeriodEventRunningTotal') @property def RemoteSymbolPeriodThreshold(self): """ Returns: number """ return self._get_attribute('remoteSymbolPeriodThreshold') @property def RemoteSymbolPeriodWindow(self): """ Returns: number """ return self._get_attribute('remoteSymbolPeriodWindow') def find(self, LocalFrameErrorRunningTotal=None, LocalFrameEventRunningTotal=None, LocalFramePeriodErrorRunningTotal=None, LocalFramePeriodEventRunningTotal=None, LocalFrameSecSumErrorRunningTotal=None, LocalFrameSecSumEventRunningTotal=None, LocalSymbolPeriodErrorRunningTotal=None, LocalSymbolPeriodEventRunningTotal=None, RemoteFrameError=None, RemoteFrameErrorRunningTotal=None, RemoteFrameEventRunningTotal=None, RemoteFramePeriodError=None, RemoteFramePeriodErrorRunningTotal=None, RemoteFramePeriodEventRunningTotal=None, RemoteFramePeriodThreshold=None, RemoteFramePeriodWindow=None, RemoteFrameSecSumError=None, RemoteFrameSecSumErrorRunningTotal=None, RemoteFrameSecSumEventRunningTotal=None, RemoteFrameSecSumThreshold=None, RemoteFrameSecSumWindow=None, RemoteFrameThreshold=None, RemoteFrameWindow=None, RemoteSymbolPeriodErrorRunningTotal=None, RemoteSymbolPeriodErrors=None, RemoteSymbolPeriodEventRunningTotal=None, RemoteSymbolPeriodThreshold=None, RemoteSymbolPeriodWindow=None): """Finds and retrieves eventNotificationLearnedInfo data from the server. All named parameters support regex and can be used to selectively retrieve eventNotificationLearnedInfo data from the server. By default the find method takes no parameters and will retrieve all eventNotificationLearnedInfo data from the server. Args: LocalFrameErrorRunningTotal (number): LocalFrameEventRunningTotal (number): LocalFramePeriodErrorRunningTotal (number): LocalFramePeriodEventRunningTotal (number): LocalFrameSecSumErrorRunningTotal (number): LocalFrameSecSumEventRunningTotal (number): LocalSymbolPeriodErrorRunningTotal (number): LocalSymbolPeriodEventRunningTotal (number): RemoteFrameError (number): RemoteFrameErrorRunningTotal (number): RemoteFrameEventRunningTotal (number): RemoteFramePeriodError (number): RemoteFramePeriodErrorRunningTotal (number): RemoteFramePeriodEventRunningTotal (number): RemoteFramePeriodThreshold (number): RemoteFramePeriodWindow (number): RemoteFrameSecSumError (number): RemoteFrameSecSumErrorRunningTotal (number): RemoteFrameSecSumEventRunningTotal (number): RemoteFrameSecSumThreshold (number): RemoteFrameSecSumWindow (number): RemoteFrameThreshold (number): RemoteFrameWindow (number): RemoteSymbolPeriodErrorRunningTotal (number): RemoteSymbolPeriodErrors (number): RemoteSymbolPeriodEventRunningTotal (number): RemoteSymbolPeriodThreshold (number): RemoteSymbolPeriodWindow (number): Returns: self: This instance with matching eventNotificationLearnedInfo data retrieved from the server available through an iterator or index Raises: ServerError: The server has encountered an uncategorized error condition """ return self._select(locals()) def read(self, href): """Retrieves a single instance of eventNotificationLearnedInfo data from the server. Args: href (str): An href to the instance to be retrieved Returns: self: This instance with the eventNotificationLearnedInfo data from the server available through an iterator or index Raises: NotFoundError: The requested resource does not exist on the server ServerError: The server has encountered an uncategorized error condition """ return self._read(href)
[ "hubert.gee@keysight.com" ]
hubert.gee@keysight.com
38ee93212baba1254b19a1e1c076d397ed05f48f
8d50cc4f37c153fcb51de4501f3fa50c00394d9b
/nets/L_Resnet_E_IR.py
66cfaa519446d9c31ccdddb293dd2eba5835a997
[ "MIT" ]
permissive
liujuanLT/InsightFace_TF
dbd239dfdda1866c348e82211932884f73cb3067
257b6e0dcf7e7c3523dc7e1c08ba529fab1bf75b
refs/heads/master
2022-04-27T21:24:01.458277
2022-03-17T12:28:15
2022-03-17T12:28:15
463,040,192
0
0
MIT
2022-02-24T06:51:16
2022-02-24T06:51:15
null
UTF-8
Python
false
false
20,455
py
import tensorflow as tf import tensorlayer as tl from tensorflow.contrib.layers.python.layers import utils import collections from tensorlayer.layers import Layer, list_remove_repeat class ElementwiseLayer(Layer): """ The :class:`ElementwiseLayer` class combines multiple :class:`Layer` which have the same output shapes by a given elemwise-wise operation. Parameters ---------- layer : a list of :class:`Layer` instances The `Layer` class feeding into this layer. combine_fn : a TensorFlow elemwise-merge function e.g. AND is ``tf.minimum`` ; OR is ``tf.maximum`` ; ADD is ``tf.add`` ; MUL is ``tf.multiply`` and so on. See `TensorFlow Math API <https://www.tensorflow.org/versions/master/api_docs/python/math_ops.html#math>`_ . name : a string or None An optional name to attach to this layer. """ def __init__( self, layer = [], combine_fn = tf.minimum, name ='elementwise_layer', act = None, ): Layer.__init__(self, name=name) if act: print(" [TL] ElementwiseLayer %s: size:%s fn:%s, act:%s" % ( self.name, layer[0].outputs.get_shape(), combine_fn.__name__, act.__name__)) else: print(" [TL] ElementwiseLayer %s: size:%s fn:%s" % ( self.name, layer[0].outputs.get_shape(), combine_fn.__name__)) self.outputs = layer[0].outputs # print(self.outputs._shape, type(self.outputs._shape)) for l in layer[1:]: # assert str(self.outputs.get_shape()) == str(l.outputs.get_shape()), "Hint: the input shapes should be the same. %s != %s" % (self.outputs.get_shape() , str(l.outputs.get_shape())) self.outputs = combine_fn(self.outputs, l.outputs, name=name) if act: self.outputs = act(self.outputs) self.all_layers = list(layer[0].all_layers) self.all_params = list(layer[0].all_params) self.all_drop = dict(layer[0].all_drop) for i in range(1, len(layer)): self.all_layers.extend(list(layer[i].all_layers)) self.all_params.extend(list(layer[i].all_params)) self.all_drop.update(dict(layer[i].all_drop)) self.all_layers = list_remove_repeat(self.all_layers) self.all_params = list_remove_repeat(self.all_params) class BatchNormLayer(Layer): """ The :class:`BatchNormLayer` class is a normalization layer, see ``tf.nn.batch_normalization`` and ``tf.nn.moments``. Batch normalization on fully-connected or convolutional maps. ``` https://www.tensorflow.org/api_docs/python/tf/cond If x < y, the tf.add operation will be executed and tf.square operation will not be executed. Since z is needed for at least one branch of the cond, the tf.multiply operation is always executed, unconditionally. ``` Parameters ----------- layer : a :class:`Layer` instance The `Layer` class feeding into this layer. decay : float, default is 0.9. A decay factor for ExponentialMovingAverage, use larger value for large dataset. epsilon : float A small float number to avoid dividing by 0. act : activation function. is_train : boolean Whether train or inference. beta_init : beta initializer The initializer for initializing beta gamma_init : gamma initializer The initializer for initializing gamma dtype : tf.float32 (default) or tf.float16 name : a string or None An optional name to attach to this layer. References ---------- - `Source <https://github.com/ry/tensorflow-resnet/blob/master/resnet.py>`_ - `stackoverflow <http://stackoverflow.com/questions/38312668/how-does-one-do-inference-with-batch-normalization-with-tensor-flow>`_ """ def __init__( self, layer=None, decay=0.9, epsilon=2e-5, act=tf.identity, is_train=False, fix_gamma=True, beta_init=tf.zeros_initializer, gamma_init=tf.random_normal_initializer(mean=1.0, stddev=0.002), # tf.ones_initializer, # dtype = tf.float32, trainable=None, name='batchnorm_layer', ): Layer.__init__(self, name=name) self.inputs = layer.outputs print(" [TL] BatchNormLayer %s: decay:%f epsilon:%f act:%s is_train:%s" % (self.name, decay, epsilon, act.__name__, is_train)) x_shape = self.inputs.get_shape() params_shape = x_shape[-1:] from tensorflow.python.training import moving_averages from tensorflow.python.ops import control_flow_ops with tf.variable_scope(name) as vs: axis = list(range(len(x_shape) - 1)) ## 1. beta, gamma if tf.__version__ > '0.12.1' and beta_init == tf.zeros_initializer: beta_init = beta_init() beta = tf.get_variable('beta', shape=params_shape, initializer=beta_init, dtype=tf.float32, trainable=is_train) #, restore=restore) gamma = tf.get_variable( 'gamma', shape=params_shape, initializer=gamma_init, dtype=tf.float32, trainable=fix_gamma, ) #restore=restore) ## 2. if tf.__version__ > '0.12.1': moving_mean_init = tf.zeros_initializer() else: moving_mean_init = tf.zeros_initializer moving_mean = tf.get_variable('moving_mean', params_shape, initializer=moving_mean_init, dtype=tf.float32, trainable=False) # restore=restore) moving_variance = tf.get_variable( 'moving_variance', params_shape, initializer=tf.constant_initializer(1.), dtype=tf.float32, trainable=False, ) # restore=restore) ## 3. # These ops will only be preformed when training. mean, variance = tf.nn.moments(self.inputs, axis) try: # TF12 update_moving_mean = moving_averages.assign_moving_average(moving_mean, mean, decay, zero_debias=False) # if zero_debias=True, has bias update_moving_variance = moving_averages.assign_moving_average( moving_variance, variance, decay, zero_debias=False) # if zero_debias=True, has bias # print("TF12 moving") except Exception as e: # TF11 update_moving_mean = moving_averages.assign_moving_average(moving_mean, mean, decay) update_moving_variance = moving_averages.assign_moving_average(moving_variance, variance, decay) # print("TF11 moving") def mean_var_with_update(): with tf.control_dependencies([update_moving_mean, update_moving_variance]): return tf.identity(mean), tf.identity(variance) if trainable: mean, var = mean_var_with_update() print(mean) print(var) self.outputs = act(tf.nn.batch_normalization(self.inputs, mean, var, beta, gamma, epsilon)) else: self.outputs = act(tf.nn.batch_normalization(self.inputs, moving_mean, moving_variance, beta, gamma, epsilon)) variables = [beta, gamma, moving_mean, moving_variance] self.all_layers = list(layer.all_layers) self.all_params = list(layer.all_params) self.all_drop = dict(layer.all_drop) self.all_layers.extend([self.outputs]) self.all_params.extend(variables) def subsample(inputs, factor, scope=None): if factor == 1: return inputs else: return tl.layers.MaxPool2d(inputs, [1, 1], strides=(factor, factor), name=scope) def conv2d_same(inputs, num_outputs, kernel_size, strides, rate=1, w_init=None, scope=None, trainable=None): ''' Reference slim resnet :param inputs: :param num_outputs: :param kernel_size: :param strides: :param rate: :param scope: :return: ''' if strides == 1: if rate == 1: nets = tl.layers.Conv2d(inputs, n_filter=num_outputs, filter_size=(kernel_size, kernel_size), b_init=None, strides=(strides, strides), W_init=w_init, act=None, padding='SAME', name=scope, use_cudnn_on_gpu=True) nets = BatchNormLayer(nets, act=tf.identity, is_train=True, trainable=trainable, name=scope+'_bn/BatchNorm') else: nets = tl.layers.AtrousConv2dLayer(inputs, n_filter=num_outputs, filter_size=(kernel_size, kernel_size), rate=rate, act=None, W_init=w_init, padding='SAME', name=scope) nets = BatchNormLayer(nets, act=tf.identity, is_train=True, trainable=trainable, name=scope+'_bn/BatchNorm') return nets else: kernel_size_effective = kernel_size + (kernel_size - 1) * (rate - 1) pad_total = kernel_size_effective - 1 pad_beg = pad_total // 2 pad_end = pad_total - pad_beg inputs = tl.layers.PadLayer(inputs, [[0, 0], [pad_beg, pad_end], [pad_beg, pad_end], [0, 0]], name='padding_%s' % scope) if rate == 1: nets = tl.layers.Conv2d(inputs, n_filter=num_outputs, filter_size=(kernel_size, kernel_size), b_init=None, strides=(strides, strides), W_init=w_init, act=None, padding='VALID', name=scope, use_cudnn_on_gpu=True) nets = BatchNormLayer(nets, act=tf.identity, is_train=True, trainable=trainable, name=scope+'_bn/BatchNorm') else: nets = tl.layers.AtrousConv2dLayer(inputs, n_filter=num_outputs, filter_size=(kernel_size, kernel_size), b_init=None, rate=rate, act=None, W_init=w_init, padding='SAME', name=scope) nets = BatchNormLayer(nets, act=tf.identity, is_train=True, trainable=trainable, name=scope+'_bn/BatchNorm') return nets def bottleneck_IR(inputs, depth, depth_bottleneck, stride, rate=1, w_init=None, scope=None, trainable=None): with tf.variable_scope(scope, 'bottleneck_v1') as sc: depth_in = utils.last_dimension(inputs.outputs.get_shape(), min_rank=4) if depth == depth_in: shortcut = subsample(inputs, stride, 'shortcut') else: shortcut = tl.layers.Conv2d(inputs, depth, filter_size=(1, 1), strides=(stride, stride), act=None, W_init=w_init, b_init=None, name='shortcut_conv', use_cudnn_on_gpu=True) shortcut = BatchNormLayer(shortcut, act=tf.identity, is_train=True, trainable=trainable, name='shortcut_bn/BatchNorm') # bottleneck layer 1 residual = BatchNormLayer(inputs, act=tf.identity, is_train=True, trainable=trainable, name='conv1_bn1') residual = tl.layers.Conv2d(residual, depth_bottleneck, filter_size=(3, 3), strides=(1, 1), act=None, b_init=None, W_init=w_init, name='conv1', use_cudnn_on_gpu=True) residual = BatchNormLayer(residual, act=tf.identity, is_train=True, trainable=trainable, name='conv1_bn2') # bottleneck prelu residual = tl.layers.PReluLayer(residual) # bottleneck layer 2 residual = conv2d_same(residual, depth, kernel_size=3, strides=stride, rate=rate, w_init=w_init, scope='conv2', trainable=trainable) output = ElementwiseLayer(layer=[shortcut, residual], combine_fn=tf.add, name='combine_layer', act=None) return output def bottleneck_IR_SE(inputs, depth, depth_bottleneck, stride, rate=1, w_init=None, scope=None, trainable=None): with tf.variable_scope(scope, 'bottleneck_v1') as sc: depth_in = utils.last_dimension(inputs.outputs.get_shape(), min_rank=4) if depth == depth_in: shortcut = subsample(inputs, stride, 'shortcut') else: shortcut = tl.layers.Conv2d(inputs, depth, filter_size=(1, 1), strides=(stride, stride), act=None, W_init=w_init, b_init=None, name='shortcut_conv', use_cudnn_on_gpu=True) shortcut = BatchNormLayer(shortcut, act=tf.identity, is_train=True, trainable=trainable, name='shortcut_bn/BatchNorm') # bottleneck layer 1 residual = BatchNormLayer(inputs, act=tf.identity, is_train=True, trainable=trainable, name='conv1_bn1') residual = tl.layers.Conv2d(residual, depth_bottleneck, filter_size=(3, 3), strides=(1, 1), act=None, b_init=None, W_init=w_init, name='conv1', use_cudnn_on_gpu=True) residual = BatchNormLayer(residual, act=tf.identity, is_train=True, trainable=trainable, name='conv1_bn2') # bottleneck prelu residual = tl.layers.PReluLayer(residual) # bottleneck layer 2 residual = conv2d_same(residual, depth, kernel_size=3, strides=stride, rate=rate, w_init=w_init, scope='conv2', trainable=trainable) # squeeze squeeze = tl.layers.InputLayer(tf.reduce_mean(residual.outputs, axis=[1, 2]), name='squeeze_layer') # excitation excitation1 = tl.layers.DenseLayer(squeeze, n_units=int(depth/16.0), act=tf.nn.relu, W_init=w_init, name='excitation_1') # excitation1 = tl.layers.PReluLayer(excitation1, name='excitation_prelu') excitation2 = tl.layers.DenseLayer(excitation1, n_units=depth, act=tf.nn.sigmoid, W_init=w_init, name='excitation_2') # scale scale = tl.layers.ReshapeLayer(excitation2, shape=[tf.shape(excitation2.outputs)[0], 1, 1, depth], name='excitation_reshape') residual_se = ElementwiseLayer(layer=[residual, scale], combine_fn=tf.multiply, name='scale_layer', act=None) output = ElementwiseLayer(layer=[shortcut, residual_se], combine_fn=tf.add, name='combine_layer', act=tf.nn.relu) return output def resnet(inputs, bottle_neck, blocks, w_init=None, trainable=None, reuse=False, keep_rate=None, scope=None): with tf.variable_scope(scope, reuse=reuse): # inputs = tf.subtract(inputs, 127.5) # inputs = tf.multiply(inputs, 0.0078125) net_inputs = tl.layers.InputLayer(inputs, name='input_layer') if bottle_neck: net = tl.layers.Conv2d(net_inputs, n_filter=64, filter_size=(3, 3), strides=(1, 1), act=None, W_init=w_init, b_init=None, name='conv1', use_cudnn_on_gpu=True) net = BatchNormLayer(net, act=tf.identity, name='bn0', is_train=True, trainable=trainable) net = tl.layers.PReluLayer(net, name='prelu0') else: raise ValueError('The standard resnet must support the bottleneck layer') for block in blocks: with tf.variable_scope(block.scope): for i, var in enumerate(block.args): with tf.variable_scope('unit_%d' % (i+1)): net = block.unit_fn(net, depth=var['depth'], depth_bottleneck=var['depth_bottleneck'], w_init=w_init, stride=var['stride'], rate=var['rate'], scope=None, trainable=trainable) net = BatchNormLayer(net, act=tf.identity, is_train=True, name='E_BN1', trainable=trainable) # net = tl.layers.DropoutLayer(net, keep=0.4, name='E_Dropout') net.outputs = tf.nn.dropout(net.outputs, keep_prob=keep_rate, name='E_Dropout') net_shape = net.outputs.get_shape() net = tl.layers.ReshapeLayer(net, shape=[-1, net_shape[1]*net_shape[2]*net_shape[3]], name='E_Reshapelayer') net = tl.layers.DenseLayer(net, n_units=512, W_init=w_init, name='E_DenseLayer') net = BatchNormLayer(net, act=tf.identity, is_train=True, fix_gamma=False, trainable=trainable, name='E_BN2') return net class Block(collections.namedtuple('Block', ['scope', 'unit_fn', 'args'])): """A named tuple describing a ResNet block. Its parts are: scope: The scope of the `Block`. unit_fn: The ResNet unit function which takes as input a `Tensor` and returns another `Tensor` with the output of the ResNet unit. args: A list of length equal to the number of units in the `Block`. The list contains one (depth, depth_bottleneck, stride) tuple for each unit in the block to serve as argument to unit_fn. """ def resnetse_v1_block(scope, base_depth, num_units, stride, rate=1, unit_fn=None): """Helper function for creating a resnet_v1 bottleneck block. Args: scope: The scope of the block. base_depth: The depth of the bottleneck layer for each unit. num_units: The number of units in the block. stride: The stride of the block, implemented as a stride in the last unit. All other units have stride=1. Returns: A resnet_v1 bottleneck block. """ return Block(scope, unit_fn, [{ 'depth': base_depth * 4, 'depth_bottleneck': base_depth, 'stride': stride, 'rate': rate }] + [{ 'depth': base_depth * 4, 'depth_bottleneck': base_depth, 'stride': 1, 'rate': rate }] * (num_units - 1)) def get_resnet(inputs, num_layers, type=None, w_init=None, trainable=None, sess=None, reuse=False, keep_rate=None): if type == 'ir': unit_fn = bottleneck_IR elif type == 'se_ir': unit_fn = bottleneck_IR_SE else: raise ValueError('the input fn is unknown') if num_layers == 50: blocks = [ resnetse_v1_block('block1', base_depth=64, num_units=3, stride=2, rate=1, unit_fn=unit_fn), resnetse_v1_block('block2', base_depth=128, num_units=4, stride=2, rate=1, unit_fn=unit_fn), resnetse_v1_block('block3', base_depth=256, num_units=14, stride=2, rate=1, unit_fn=unit_fn), resnetse_v1_block('block4', base_depth=512, num_units=3, stride=2, rate=1, unit_fn=unit_fn) ] elif num_layers == 101: blocks = [ resnetse_v1_block('block1', base_depth=64, num_units=3, stride=2, rate=1, unit_fn=unit_fn), resnetse_v1_block('block2', base_depth=128, num_units=13, stride=2, rate=1, unit_fn=unit_fn), resnetse_v1_block('block3', base_depth=256, num_units=30, stride=2, rate=1, unit_fn=unit_fn), resnetse_v1_block('block4', base_depth=512, num_units=3, stride=2, rate=1, unit_fn=unit_fn) ] elif num_layers == 152: blocks = [ resnetse_v1_block('block1', base_depth=64, num_units=3, stride=2, rate=1, unit_fn=unit_fn), resnetse_v1_block('block2', base_depth=128, num_units=8, stride=2, rate=1, unit_fn=unit_fn), resnetse_v1_block('block3', base_depth=256, num_units=36, stride=2, rate=1, unit_fn=unit_fn), resnetse_v1_block('block4', base_depth=512, num_units=3, stride=2, rate=1, unit_fn=unit_fn) ] else: raise ValueError('Resnet layer %d is not supported now.' % num_layers) net = resnet(inputs=inputs, bottle_neck=True, blocks=blocks, w_init=w_init, trainable=trainable, reuse=reuse, keep_rate = keep_rate, scope='resnet_v1_%d' % num_layers) return net if __name__ == '__main__': x = tf.placeholder(dtype=tf.float32, shape=[None, 112, 112, 3], name='input_place') sess = tf.Session() # w_init = tf.truncated_normal_initializer(mean=10, stddev=5e-2) w_init = tf.contrib.layers.xavier_initializer(uniform=False) # test resnetse nets = get_resnet(x, 50, type='ir', w_init=w_init, sess=sess) tl.layers.initialize_global_variables(sess) for p in tl.layers.get_variables_with_name('W_conv2d', True, True): print(p.op.name) print('##############'*30) with sess: nets.print_params()
[ "auroua@yeah.net" ]
auroua@yeah.net
5e4238daa2bff72c419c9897bd72a325b43e6d19
4315836a3a360c646839c88452dadbb3b3cbdf60
/Level 5/learning_users/learning_users/urls.py
7422d96d8b97f3184759cd958fd459cc80c1ddde
[]
no_license
hyungtaecf/Bootcamp-Django
77449c3a6487030d0951aa58ec20c225427b3034
4fe0daaa385f9eca686ba7ea4631ae34b9ba1d8b
refs/heads/master
2021-02-13T03:16:41.824959
2020-03-19T15:59:15
2020-03-19T15:59:15
244,656,066
0
0
null
null
null
null
UTF-8
Python
false
false
1,047
py
"""learning_users URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.0/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path from django.contrib import admin from basic_app import views from django.conf.urls import include urlpatterns = [ path('',views.index,name='index'), path('admin/', admin.site.urls), path('basic_app/',include('basic_app.urls')), path('logout/',views.user_logout,name='logout'), path('special/',views.special,name='special'), ]
[ "hyu_03@hotmail.com" ]
hyu_03@hotmail.com
8b46d9b6b65b83f63d4903ea99257f96f206a664
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_1484496_0/Python/Zunekid/Q3.py
af300c784a31e261db76d4435001ac53e1270e58
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
Python
false
false
2,027
py
import string fn = "C-small-attempt0.in" f= open(fn,'r') summap = {} datas = [] def decode(b1, b2): list1 = [] list2 = [] place = -1 for x in xrange( len(datas)): place+=1 if b1 &1 == 1: list1.append(datas[place]) b1 = b1>>1 if b2 &1 == 1: list2.append(datas[place]) b2 = b2>>1 if len(list1)>= 1 and len(list2) >=1 : return (list1, list2) #print "OMG" def testadd(newset): #print newset, summap for each in newset: sum, bitmap = each if summap.has_key(sum): subs = summap[sum] for items in subs: if items & bitmap == 0: #print "got you" return decode(items, bitmap) for each in newset: sum, bitmap = each if summap.has_key(sum): summap[sum].append(bitmap) else: summap[sum] = [bitmap] #else: #summap[sum].append(bitmap) #return None #else: #summap[sum] = [bitmap] return None tcase = int(f.readline()) for tc in xrange(tcase): line = f.readline() #print line linedata = line.split() n = int(linedata[0]) #print n summap = {} datas = [] res = None for d in xrange(n): #for d in xrange(3): data = int(linedata[d+1]) sbm = 1<<d ns = data datas.append(data) newset= [(ns, sbm)] #res = testadd(ns, sbm) #if res != None: # break #print summap for k, subs in summap.items(): for bm in subs: # make union nbm = (1<<d) | bm ns = data + k newset.append( (ns,nbm)) #res = testadd(ns, nbm) # if res != None: # break else: continue #if res!= None: # break #testadd(newset) res = testadd(newset) #print summap #print if res != None: break if res != None: print "Case #%d:"%(tc+1) s1= res[0] s2 = res[1] line1 = "" for i1 in s1: line1 = line1+ " " + str(i1) print line1[1:] line2 = "" for i2 in s2: line2 = line2+ " " + str(i2) print line2[1:] else: print "Case #%d:"% (tc+1) print "Impossible"
[ "eewestman@gmail.com" ]
eewestman@gmail.com
92942898af7680097c4452f2f8c748ea28e37f73
210b968876a8aea36eae94e4720e23f2daa8552b
/cover/cover.py
3a74eb298af3aee1fe2a798f8583d1fc8cb90267
[]
no_license
beefoo/coloring-book
3ce5c0d5497b199cd470f640dd0b3778d545577f
cee77b7f863ddee4323c8c16111d353fe27e5b36
refs/heads/master
2021-01-12T09:37:36.490913
2017-06-26T19:07:43
2017-06-26T19:07:43
76,204,083
9
1
null
null
null
null
UTF-8
Python
false
false
4,770
py
# -*- coding: utf-8 -*- import argparse import calendar import csv import inspect import math import os import svgwrite from svgwrite import inch, px import sys # add parent directory to sys path to import relative modules currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))) parentdir = os.path.dirname(currentdir) sys.path.insert(0,parentdir) import lib.svgutils as svgu import lib.mathutils as mu # input parser = argparse.ArgumentParser() # input source: https://www.ncdc.noaa.gov/monitoring-references/faq/anomalies.php parser.add_argument('-input', dest="INPUT_FILE", default="data/1880-2016_land_ocean.csv", help="Path to input file") parser.add_argument('-y0', dest="YEAR_START", type=int, default=1880, help="Year start on viz") parser.add_argument('-ys', dest="YEAR_STEP", type=int, default=1, help="Year step on viz") parser.add_argument('-width', dest="WIDTH", type=float, default=8.5, help="Width of output file") parser.add_argument('-height', dest="HEIGHT", type=float, default=11, help="Height of output file") parser.add_argument('-pad', dest="PAD", type=float, default=0.25, help="Padding of output file") parser.add_argument('-output', dest="OUTPUT_FILE", default="data/cover.svg", help="Path to output file") # init input args = parser.parse_args() DPI = 72 PAD = args.PAD * DPI WIDTH = args.WIDTH * DPI - PAD * 2 HEIGHT = args.HEIGHT * DPI - PAD * 2 YEAR_START = args.YEAR_START YEAR_STEP = args.YEAR_STEP values = [] # read csv with open(args.INPUT_FILE, 'rb') as f: r = csv.reader(f, delimiter=',') for skip in range(4): next(r, None) # for each row i = 0 for _year,_value in r: year = int(_year) if i % YEAR_STEP <= 0 and year >= YEAR_START: value = float(_value) values.append(value) if year >= YEAR_START: i += 1 count = len(values) print "Read %s values from %s" % (count, args.INPUT_FILE) # svg config COMPRESS_Y = 0.6667 COMPRESS_X = 0.99 LINE_HEIGHT = 30.0 COLOR = "#A92D2D" COLOR_ALT = "#000000" ADD_LINE = False # svg calculations chartW = WIDTH * COMPRESS_X chartH = HEIGHT * COMPRESS_Y offsetY = HEIGHT * (1-COMPRESS_Y) * 0.5 offsetX = WIDTH * (1-COMPRESS_X) * 0.5 # convert values to points minValue = min(values) maxValue = max(values) points = [] for i, v in enumerate(values): xp = 1.0 * i / count yp = 1.0 - (v - minValue) / (maxValue - minValue) x = chartW * xp + PAD + offsetX y = chartH * yp + PAD + offsetY points.append((x, y)) # init svg dwg = svgwrite.Drawing(args.OUTPUT_FILE, size=(WIDTH+PAD*2, HEIGHT+PAD*2), profile='full') # diagonal pattern diagonalSize = 48 diagonalW = 12 diagonalPattern = dwg.pattern(id="diagonal", patternUnits="userSpaceOnUse", size=(diagonalSize,diagonalSize)) commands = svgu.patternDiagonal(diagonalSize, "down") diagonalPattern.add(dwg.path(d=commands, stroke_width=diagonalW, stroke=COLOR)) dwg.defs.add(diagonalPattern) # dot pattern dotSize = 24 dotW = 8 dotPattern = dwg.pattern(id="dot", patternUnits="userSpaceOnUse", size=(dotSize,dotSize)) commands = svgu.patternDiamond(dotSize, dotW) dotPattern.add(dwg.path(d=commands, fill=COLOR_ALT)) dwg.defs.add(dotPattern) # simplify points lineOffset = LINE_HEIGHT * 0.5 points = mu.smoothPoints(points, 1, 2.0) pointsTop = [(p[0], p[1]-lineOffset) for p in points] pointsBottom = [(p[0], p[1]+lineOffset) for p in points] # make path commands x0 = PAD x1 = WIDTH + PAD y0 = HEIGHT + PAD y1 = PAD p0 = pointsTop[0] p1 = pointsTop[-1] cp = 12 # top curve commandsTop = svgu.pointsToCurve(pointsTop, 0.1) commandsTop.append("Q%s,%s %s,%s" % (p1[0]+(x1-p1[0])*0.5, p1[1]-cp, x1, p1[1])) commandsTop.append("L%s,%s" % (x1, y1)) commandsTop.append("L%s,%s" % (x0, y1)) commandsTop.append("L%s,%s" % (x0, p0[1])) commandsTop.append("Q%s,%s %s,%s" % (x0+(p0[0]-x0)*0.5, p0[1]-cp, p0[0], p0[1])) dwg.add(dwg.path(d=commandsTop, fill="url(#dot)")) p0 = pointsBottom[0] p1 = pointsBottom[-1] # bottom curve commandsBottom = svgu.pointsToCurve(pointsBottom, 0.1) if ADD_LINE: line = commandsBottom[:] line.insert(0, "Q%s,%s %s,%s" % (x0+(p0[0]-x0)*0.5, p0[1]-cp, p0[0], p0[1])) line.insert(0, "M%s,%s" % (x0, p0[1])) line.append("Q%s,%s %s,%s" % (p1[0]+(x1-p1[0])*0.5, p1[1]-cp, x1, p1[1])) dwg.add(dwg.path(d=line, fill="none", stroke=COLOR, stroke_width=20)) commandsBottom.append("Q%s,%s %s,%s" % (p1[0]+(x1-p1[0])*0.5, p1[1]-cp, x1, p1[1])) commandsBottom.append("L%s,%s" % (x1, y0)) commandsBottom.append("L%s,%s" % (x0, y0)) commandsBottom.append("L%s,%s" % (x0, p0[1])) commandsBottom.append("Q%s,%s %s,%s" % (x0+(p0[0]-x0)*0.5, p0[1]-cp, p0[0], p0[1])) dwg.add(dwg.path(d=commandsBottom, fill="url(#diagonal)")) dwg.save() print "Saved svg: %s" % args.OUTPUT_FILE
[ "brian@youaremyjoy.org" ]
brian@youaremyjoy.org
0a4d1b3f1b01e2f409075865c38cca9c2ae7dd2e
b21e073975c0f7a4f94c9f3523b8f5dcbf98a521
/en/026/python/main.py
c390f31c0c0145c6631caaf75b09ad7f545675fe
[ "MIT" ]
permissive
franciscogomes2020/exercises
3ed6877f945463ed01c7fcd55271689171b0ad9d
8b33c4b9349a9331e4002a8225adc2a482c70024
refs/heads/master
2023-07-04T15:54:38.919185
2021-08-19T20:03:54
2021-08-19T20:03:54
396,992,428
3
0
null
null
null
null
UTF-8
Python
false
false
199
py
# Make a program that reads a sentence from the keyboard and shows how many times the letter "A" appears, in which position it appears the first time, and in which position it appears the last time.
[ "71292537+franciscogomes2020@users.noreply.github.com" ]
71292537+franciscogomes2020@users.noreply.github.com
4266e21cf82dee5e759cb42893e68117f0efe071
135d2c02b3ad706573bdfafa75ebc14bd170ef97
/plugins/networkx/networkx/algorithms/connectivity/connectivity.py
b10afd63ab1ddf583c8b7504b88e11a205077d6f
[ "BSD-3-Clause" ]
permissive
boulouk/firedex
4afc6467bd83e096051d941699e59f1be806a46c
187012986f4adf85d017e84a64db7c9bb1f447b0
refs/heads/master
2022-06-06T01:56:38.464322
2019-11-24T09:44:03
2019-11-24T09:44:03
138,659,150
2
1
null
2022-05-20T20:55:18
2018-06-25T23:09:54
Python
UTF-8
Python
false
false
29,653
py
# -*- coding: utf-8 -*- """ Flow based connectivity algorithms """ from __future__ import division import itertools from operator import itemgetter import networkx as nx # Define the default maximum flow function to use in all flow based # connectivity algorithms. from networkx.algorithms.flow import boykov_kolmogorov from networkx.algorithms.flow import dinitz from networkx.algorithms.flow import edmonds_karp from networkx.algorithms.flow import shortest_augmenting_path from networkx.algorithms.flow import build_residual_network default_flow_func = edmonds_karp from .utils import (build_auxiliary_node_connectivity, build_auxiliary_edge_connectivity) __author__ = '\n'.join(['Jordi Torrents <jtorrents@milnou.net>']) __all__ = ['average_node_connectivity', 'local_node_connectivity', 'node_connectivity', 'local_edge_connectivity', 'edge_connectivity', 'all_pairs_node_connectivity'] def local_node_connectivity(G, s, t, flow_func=None, auxiliary=None, residual=None, cutoff=None): r"""Computes local node connectivity for nodes s and t. Local node connectivity for two non adjacent nodes s and t is the minimum number of nodes that must be removed (along with their incident edges) to disconnect them. This is a flow based implementation of node connectivity. We compute the maximum flow on an auxiliary digraph build from the original input graph (see below for details). Parameters ---------- G : NetworkX graph Undirected graph s : node Source node t : node Target node flow_func : function A function for computing the maximum flow among a pair of nodes. The function has to accept at least three parameters: a Digraph, a source node, and a target node. And return a residual network that follows NetworkX conventions (see :meth:`maximum_flow` for details). If flow_func is None, the default maximum flow function (:meth:`edmonds_karp`) is used. See below for details. The choice of the default function may change from version to version and should not be relied on. Default value: None. auxiliary : NetworkX DiGraph Auxiliary digraph to compute flow based node connectivity. It has to have a graph attribute called mapping with a dictionary mapping node names in G and in the auxiliary digraph. If provided it will be reused instead of recreated. Default value: None. residual : NetworkX DiGraph Residual network to compute maximum flow. If provided it will be reused instead of recreated. Default value: None. cutoff : integer, float If specified, the maximum flow algorithm will terminate when the flow value reaches or exceeds the cutoff. This is only for the algorithms that support the cutoff parameter: :meth:`edmonds_karp` and :meth:`shortest_augmenting_path`. Other algorithms will ignore this parameter. Default value: None. Returns ------- K : integer local node connectivity for nodes s and t Examples -------- This function is not imported in the base NetworkX namespace, so you have to explicitly import it from the connectivity package: >>> from networkx.algorithms.connectivity import local_node_connectivity We use in this example the platonic icosahedral graph, which has node connectivity 5. >>> G = nx.icosahedral_graph() >>> local_node_connectivity(G, 0, 6) 5 If you need to compute local connectivity on several pairs of nodes in the same graph, it is recommended that you reuse the data structures that NetworkX uses in the computation: the auxiliary digraph for node connectivity, and the residual network for the underlying maximum flow computation. Example of how to compute local node connectivity among all pairs of nodes of the platonic icosahedral graph reusing the data structures. >>> import itertools >>> # You also have to explicitly import the function for >>> # building the auxiliary digraph from the connectivity package >>> from networkx.algorithms.connectivity import ( ... build_auxiliary_node_connectivity) ... >>> H = build_auxiliary_node_connectivity(G) >>> # And the function for building the residual network from the >>> # flow package >>> from networkx.algorithms.flow import build_residual_network >>> # Note that the auxiliary digraph has an edge attribute named capacity >>> R = build_residual_network(H, 'capacity') >>> result = dict.fromkeys(G, dict()) >>> # Reuse the auxiliary digraph and the residual network by passing them >>> # as parameters >>> for u, v in itertools.combinations(G, 2): ... k = local_node_connectivity(G, u, v, auxiliary=H, residual=R) ... result[u][v] = k ... >>> all(result[u][v] == 5 for u, v in itertools.combinations(G, 2)) True You can also use alternative flow algorithms for computing node connectivity. For instance, in dense networks the algorithm :meth:`shortest_augmenting_path` will usually perform better than the default :meth:`edmonds_karp` which is faster for sparse networks with highly skewed degree distributions. Alternative flow functions have to be explicitly imported from the flow package. >>> from networkx.algorithms.flow import shortest_augmenting_path >>> local_node_connectivity(G, 0, 6, flow_func=shortest_augmenting_path) 5 Notes ----- This is a flow based implementation of node connectivity. We compute the maximum flow using, by default, the :meth:`edmonds_karp` algorithm (see: :meth:`maximum_flow`) on an auxiliary digraph build from the original input graph: For an undirected graph G having `n` nodes and `m` edges we derive a directed graph H with `2n` nodes and `2m+n` arcs by replacing each original node `v` with two nodes `v_A`, `v_B` linked by an (internal) arc in H. Then for each edge (`u`, `v`) in G we add two arcs (`u_B`, `v_A`) and (`v_B`, `u_A`) in H. Finally we set the attribute capacity = 1 for each arc in H [1]_ . For a directed graph G having `n` nodes and `m` arcs we derive a directed graph H with `2n` nodes and `m+n` arcs by replacing each original node `v` with two nodes `v_A`, `v_B` linked by an (internal) arc (`v_A`, `v_B`) in H. Then for each arc (`u`, `v`) in G we add one arc (`u_B`, `v_A`) in H. Finally we set the attribute capacity = 1 for each arc in H. This is equal to the local node connectivity because the value of a maximum s-t-flow is equal to the capacity of a minimum s-t-cut. See also -------- :meth:`local_edge_connectivity` :meth:`node_connectivity` :meth:`minimum_node_cut` :meth:`maximum_flow` :meth:`edmonds_karp` :meth:`preflow_push` :meth:`shortest_augmenting_path` References ---------- .. [1] Kammer, Frank and Hanjo Taubig. Graph Connectivity. in Brandes and Erlebach, 'Network Analysis: Methodological Foundations', Lecture Notes in Computer Science, Volume 3418, Springer-Verlag, 2005. http://www.informatik.uni-augsburg.de/thi/personen/kammer/Graph_Connectivity.pdf """ if flow_func is None: flow_func = default_flow_func if auxiliary is None: H = build_auxiliary_node_connectivity(G) else: H = auxiliary mapping = H.graph.get('mapping', None) if mapping is None: raise nx.NetworkXError('Invalid auxiliary digraph.') kwargs = dict(flow_func=flow_func, residual=residual) if flow_func is shortest_augmenting_path: kwargs['cutoff'] = cutoff kwargs['two_phase'] = True elif flow_func is edmonds_karp: kwargs['cutoff'] = cutoff elif flow_func is dinitz: kwargs['cutoff'] = cutoff elif flow_func is boykov_kolmogorov: kwargs['cutoff'] = cutoff return nx.maximum_flow_value(H, '%sB' % mapping[s], '%sA' % mapping[t], **kwargs) def node_connectivity(G, s=None, t=None, flow_func=None): """Returns node connectivity for a graph or digraph G. Node connectivity is equal to the minimum number of nodes that must be removed to disconnect G or render it trivial. If source and target nodes are provided, this function returns the local node connectivity: the minimum number of nodes that must be removed to break all paths from source to target in G. Parameters ---------- G : NetworkX graph Undirected graph s : node Source node. Optional. Default value: None. t : node Target node. Optional. Default value: None. flow_func : function A function for computing the maximum flow among a pair of nodes. The function has to accept at least three parameters: a Digraph, a source node, and a target node. And return a residual network that follows NetworkX conventions (see :meth:`maximum_flow` for details). If flow_func is None, the default maximum flow function (:meth:`edmonds_karp`) is used. See below for details. The choice of the default function may change from version to version and should not be relied on. Default value: None. Returns ------- K : integer Node connectivity of G, or local node connectivity if source and target are provided. Examples -------- >>> # Platonic icosahedral graph is 5-node-connected >>> G = nx.icosahedral_graph() >>> nx.node_connectivity(G) 5 You can use alternative flow algorithms for the underlying maximum flow computation. In dense networks the algorithm :meth:`shortest_augmenting_path` will usually perform better than the default :meth:`edmonds_karp`, which is faster for sparse networks with highly skewed degree distributions. Alternative flow functions have to be explicitly imported from the flow package. >>> from networkx.algorithms.flow import shortest_augmenting_path >>> nx.node_connectivity(G, flow_func=shortest_augmenting_path) 5 If you specify a pair of nodes (source and target) as parameters, this function returns the value of local node connectivity. >>> nx.node_connectivity(G, 3, 7) 5 If you need to perform several local computations among different pairs of nodes on the same graph, it is recommended that you reuse the data structures used in the maximum flow computations. See :meth:`local_node_connectivity` for details. Notes ----- This is a flow based implementation of node connectivity. The algorithm works by solving `O((n-\delta-1+\delta(\delta-1)/2))` maximum flow problems on an auxiliary digraph. Where `\delta` is the minimum degree of G. For details about the auxiliary digraph and the computation of local node connectivity see :meth:`local_node_connectivity`. This implementation is based on algorithm 11 in [1]_. See also -------- :meth:`local_node_connectivity` :meth:`edge_connectivity` :meth:`maximum_flow` :meth:`edmonds_karp` :meth:`preflow_push` :meth:`shortest_augmenting_path` References ---------- .. [1] Abdol-Hossein Esfahanian. Connectivity Algorithms. http://www.cse.msu.edu/~cse835/Papers/Graph_connectivity_revised.pdf """ if (s is not None and t is None) or (s is None and t is not None): raise nx.NetworkXError('Both source and target must be specified.') # Local node connectivity if s is not None and t is not None: if s not in G: raise nx.NetworkXError('node %s not in graph' % s) if t not in G: raise nx.NetworkXError('node %s not in graph' % t) return local_node_connectivity(G, s, t, flow_func=flow_func) # Global node connectivity if G.is_directed(): if not nx.is_weakly_connected(G): return 0 iter_func = itertools.permutations # It is necessary to consider both predecessors # and successors for directed graphs def neighbors(v): return itertools.chain.from_iterable([G.predecessors(v), G.successors(v)]) else: if not nx.is_connected(G): return 0 iter_func = itertools.combinations neighbors = G.neighbors # Reuse the auxiliary digraph and the residual network H = build_auxiliary_node_connectivity(G) R = build_residual_network(H, 'capacity') kwargs = dict(flow_func=flow_func, auxiliary=H, residual=R) # Pick a node with minimum degree # Node connectivity is bounded by degree. v, K = min(G.degree(), key=itemgetter(1)) # compute local node connectivity with all its non-neighbors nodes for w in set(G) - set(neighbors(v)) - set([v]): kwargs['cutoff'] = K K = min(K, local_node_connectivity(G, v, w, **kwargs)) # Also for non adjacent pairs of neighbors of v for x, y in iter_func(neighbors(v), 2): if y in G[x]: continue kwargs['cutoff'] = K K = min(K, local_node_connectivity(G, x, y, **kwargs)) return K def average_node_connectivity(G, flow_func=None): r"""Returns the average connectivity of a graph G. The average connectivity `\bar{\kappa}` of a graph G is the average of local node connectivity over all pairs of nodes of G [1]_ . .. math:: \bar{\kappa}(G) = \frac{\sum_{u,v} \kappa_{G}(u,v)}{{n \choose 2}} Parameters ---------- G : NetworkX graph Undirected graph flow_func : function A function for computing the maximum flow among a pair of nodes. The function has to accept at least three parameters: a Digraph, a source node, and a target node. And return a residual network that follows NetworkX conventions (see :meth:`maximum_flow` for details). If flow_func is None, the default maximum flow function (:meth:`edmonds_karp`) is used. See :meth:`local_node_connectivity` for details. The choice of the default function may change from version to version and should not be relied on. Default value: None. Returns ------- K : float Average node connectivity See also -------- :meth:`local_node_connectivity` :meth:`node_connectivity` :meth:`edge_connectivity` :meth:`maximum_flow` :meth:`edmonds_karp` :meth:`preflow_push` :meth:`shortest_augmenting_path` References ---------- .. [1] Beineke, L., O. Oellermann, and R. Pippert (2002). The average connectivity of a graph. Discrete mathematics 252(1-3), 31-45. http://www.sciencedirect.com/science/article/pii/S0012365X01001807 """ if G.is_directed(): iter_func = itertools.permutations else: iter_func = itertools.combinations # Reuse the auxiliary digraph and the residual network H = build_auxiliary_node_connectivity(G) R = build_residual_network(H, 'capacity') kwargs = dict(flow_func=flow_func, auxiliary=H, residual=R) num, den = 0, 0 for u, v in iter_func(G, 2): num += local_node_connectivity(G, u, v, **kwargs) den += 1 if den == 0: # Null Graph return 0 return num / den def all_pairs_node_connectivity(G, nbunch=None, flow_func=None): """Compute node connectivity between all pairs of nodes of G. Parameters ---------- G : NetworkX graph Undirected graph nbunch: container Container of nodes. If provided node connectivity will be computed only over pairs of nodes in nbunch. flow_func : function A function for computing the maximum flow among a pair of nodes. The function has to accept at least three parameters: a Digraph, a source node, and a target node. And return a residual network that follows NetworkX conventions (see :meth:`maximum_flow` for details). If flow_func is None, the default maximum flow function (:meth:`edmonds_karp`) is used. See below for details. The choice of the default function may change from version to version and should not be relied on. Default value: None. Returns ------- all_pairs : dict A dictionary with node connectivity between all pairs of nodes in G, or in nbunch if provided. See also -------- :meth:`local_node_connectivity` :meth:`edge_connectivity` :meth:`local_edge_connectivity` :meth:`maximum_flow` :meth:`edmonds_karp` :meth:`preflow_push` :meth:`shortest_augmenting_path` """ if nbunch is None: nbunch = G else: nbunch = set(nbunch) directed = G.is_directed() if directed: iter_func = itertools.permutations else: iter_func = itertools.combinations all_pairs = {n: {} for n in nbunch} # Reuse auxiliary digraph and residual network H = build_auxiliary_node_connectivity(G) mapping = H.graph['mapping'] R = build_residual_network(H, 'capacity') kwargs = dict(flow_func=flow_func, auxiliary=H, residual=R) for u, v in iter_func(nbunch, 2): K = local_node_connectivity(G, u, v, **kwargs) all_pairs[u][v] = K if not directed: all_pairs[v][u] = K return all_pairs def local_edge_connectivity(G, u, v, flow_func=None, auxiliary=None, residual=None, cutoff=None): r"""Returns local edge connectivity for nodes s and t in G. Local edge connectivity for two nodes s and t is the minimum number of edges that must be removed to disconnect them. This is a flow based implementation of edge connectivity. We compute the maximum flow on an auxiliary digraph build from the original network (see below for details). This is equal to the local edge connectivity because the value of a maximum s-t-flow is equal to the capacity of a minimum s-t-cut (Ford and Fulkerson theorem) [1]_ . Parameters ---------- G : NetworkX graph Undirected or directed graph s : node Source node t : node Target node flow_func : function A function for computing the maximum flow among a pair of nodes. The function has to accept at least three parameters: a Digraph, a source node, and a target node. And return a residual network that follows NetworkX conventions (see :meth:`maximum_flow` for details). If flow_func is None, the default maximum flow function (:meth:`edmonds_karp`) is used. See below for details. The choice of the default function may change from version to version and should not be relied on. Default value: None. auxiliary : NetworkX DiGraph Auxiliary digraph for computing flow based edge connectivity. If provided it will be reused instead of recreated. Default value: None. residual : NetworkX DiGraph Residual network to compute maximum flow. If provided it will be reused instead of recreated. Default value: None. cutoff : integer, float If specified, the maximum flow algorithm will terminate when the flow value reaches or exceeds the cutoff. This is only for the algorithms that support the cutoff parameter: :meth:`edmonds_karp` and :meth:`shortest_augmenting_path`. Other algorithms will ignore this parameter. Default value: None. Returns ------- K : integer local edge connectivity for nodes s and t. Examples -------- This function is not imported in the base NetworkX namespace, so you have to explicitly import it from the connectivity package: >>> from networkx.algorithms.connectivity import local_edge_connectivity We use in this example the platonic icosahedral graph, which has edge connectivity 5. >>> G = nx.icosahedral_graph() >>> local_edge_connectivity(G, 0, 6) 5 If you need to compute local connectivity on several pairs of nodes in the same graph, it is recommended that you reuse the data structures that NetworkX uses in the computation: the auxiliary digraph for edge connectivity, and the residual network for the underlying maximum flow computation. Example of how to compute local edge connectivity among all pairs of nodes of the platonic icosahedral graph reusing the data structures. >>> import itertools >>> # You also have to explicitly import the function for >>> # building the auxiliary digraph from the connectivity package >>> from networkx.algorithms.connectivity import ( ... build_auxiliary_edge_connectivity) >>> H = build_auxiliary_edge_connectivity(G) >>> # And the function for building the residual network from the >>> # flow package >>> from networkx.algorithms.flow import build_residual_network >>> # Note that the auxiliary digraph has an edge attribute named capacity >>> R = build_residual_network(H, 'capacity') >>> result = dict.fromkeys(G, dict()) >>> # Reuse the auxiliary digraph and the residual network by passing them >>> # as parameters >>> for u, v in itertools.combinations(G, 2): ... k = local_edge_connectivity(G, u, v, auxiliary=H, residual=R) ... result[u][v] = k >>> all(result[u][v] == 5 for u, v in itertools.combinations(G, 2)) True You can also use alternative flow algorithms for computing edge connectivity. For instance, in dense networks the algorithm :meth:`shortest_augmenting_path` will usually perform better than the default :meth:`edmonds_karp` which is faster for sparse networks with highly skewed degree distributions. Alternative flow functions have to be explicitly imported from the flow package. >>> from networkx.algorithms.flow import shortest_augmenting_path >>> local_edge_connectivity(G, 0, 6, flow_func=shortest_augmenting_path) 5 Notes ----- This is a flow based implementation of edge connectivity. We compute the maximum flow using, by default, the :meth:`edmonds_karp` algorithm on an auxiliary digraph build from the original input graph: If the input graph is undirected, we replace each edge (`u`,`v`) with two reciprocal arcs (`u`, `v`) and (`v`, `u`) and then we set the attribute 'capacity' for each arc to 1. If the input graph is directed we simply add the 'capacity' attribute. This is an implementation of algorithm 1 in [1]_. The maximum flow in the auxiliary network is equal to the local edge connectivity because the value of a maximum s-t-flow is equal to the capacity of a minimum s-t-cut (Ford and Fulkerson theorem). See also -------- :meth:`edge_connectivity` :meth:`local_node_connectivity` :meth:`node_connectivity` :meth:`maximum_flow` :meth:`edmonds_karp` :meth:`preflow_push` :meth:`shortest_augmenting_path` References ---------- .. [1] Abdol-Hossein Esfahanian. Connectivity Algorithms. http://www.cse.msu.edu/~cse835/Papers/Graph_connectivity_revised.pdf """ if flow_func is None: flow_func = default_flow_func if auxiliary is None: H = build_auxiliary_edge_connectivity(G) else: H = auxiliary kwargs = dict(flow_func=flow_func, residual=residual) if flow_func is shortest_augmenting_path: kwargs['cutoff'] = cutoff kwargs['two_phase'] = True elif flow_func is edmonds_karp: kwargs['cutoff'] = cutoff elif flow_func is dinitz: kwargs['cutoff'] = cutoff elif flow_func is boykov_kolmogorov: kwargs['cutoff'] = cutoff return nx.maximum_flow_value(H, u, v, **kwargs) def edge_connectivity(G, s=None, t=None, flow_func=None): r"""Returns the edge connectivity of the graph or digraph G. The edge connectivity is equal to the minimum number of edges that must be removed to disconnect G or render it trivial. If source and target nodes are provided, this function returns the local edge connectivity: the minimum number of edges that must be removed to break all paths from source to target in G. Parameters ---------- G : NetworkX graph Undirected or directed graph s : node Source node. Optional. Default value: None. t : node Target node. Optional. Default value: None. flow_func : function A function for computing the maximum flow among a pair of nodes. The function has to accept at least three parameters: a Digraph, a source node, and a target node. And return a residual network that follows NetworkX conventions (see :meth:`maximum_flow` for details). If flow_func is None, the default maximum flow function (:meth:`edmonds_karp`) is used. See below for details. The choice of the default function may change from version to version and should not be relied on. Default value: None. Returns ------- K : integer Edge connectivity for G, or local edge connectivity if source and target were provided Examples -------- >>> # Platonic icosahedral graph is 5-edge-connected >>> G = nx.icosahedral_graph() >>> nx.edge_connectivity(G) 5 You can use alternative flow algorithms for the underlying maximum flow computation. In dense networks the algorithm :meth:`shortest_augmenting_path` will usually perform better than the default :meth:`edmonds_karp`, which is faster for sparse networks with highly skewed degree distributions. Alternative flow functions have to be explicitly imported from the flow package. >>> from networkx.algorithms.flow import shortest_augmenting_path >>> nx.edge_connectivity(G, flow_func=shortest_augmenting_path) 5 If you specify a pair of nodes (source and target) as parameters, this function returns the value of local edge connectivity. >>> nx.edge_connectivity(G, 3, 7) 5 If you need to perform several local computations among different pairs of nodes on the same graph, it is recommended that you reuse the data structures used in the maximum flow computations. See :meth:`local_edge_connectivity` for details. Notes ----- This is a flow based implementation of global edge connectivity. For undirected graphs the algorithm works by finding a 'small' dominating set of nodes of G (see algorithm 7 in [1]_ ) and computing local maximum flow (see :meth:`local_edge_connectivity`) between an arbitrary node in the dominating set and the rest of nodes in it. This is an implementation of algorithm 6 in [1]_ . For directed graphs, the algorithm does n calls to the maximum flow function. This is an implementation of algorithm 8 in [1]_ . See also -------- :meth:`local_edge_connectivity` :meth:`local_node_connectivity` :meth:`node_connectivity` :meth:`maximum_flow` :meth:`edmonds_karp` :meth:`preflow_push` :meth:`shortest_augmenting_path` References ---------- .. [1] Abdol-Hossein Esfahanian. Connectivity Algorithms. http://www.cse.msu.edu/~cse835/Papers/Graph_connectivity_revised.pdf """ if (s is not None and t is None) or (s is None and t is not None): raise nx.NetworkXError('Both source and target must be specified.') # Local edge connectivity if s is not None and t is not None: if s not in G: raise nx.NetworkXError('node %s not in graph' % s) if t not in G: raise nx.NetworkXError('node %s not in graph' % t) return local_edge_connectivity(G, s, t, flow_func=flow_func) # Global edge connectivity # reuse auxiliary digraph and residual network H = build_auxiliary_edge_connectivity(G) R = build_residual_network(H, 'capacity') kwargs = dict(flow_func=flow_func, auxiliary=H, residual=R) if G.is_directed(): # Algorithm 8 in [1] if not nx.is_weakly_connected(G): return 0 # initial value for \lambda is minimum degree L = min(d for n, d in G.degree()) nodes = list(G) n = len(nodes) for i in range(n): kwargs['cutoff'] = L try: L = min(L, local_edge_connectivity(G, nodes[i], nodes[i+1], **kwargs)) except IndexError: # last node! L = min(L, local_edge_connectivity(G, nodes[i], nodes[0], **kwargs)) return L else: # undirected # Algorithm 6 in [1] if not nx.is_connected(G): return 0 # initial value for \lambda is minimum degree L = min(d for n, d in G.degree()) # A dominating set is \lambda-covering # We need a dominating set with at least two nodes for node in G: D = nx.dominating_set(G, start_with=node) v = D.pop() if D: break else: # in complete graphs the dominating sets will always be of one node # thus we return min degree return L for w in D: kwargs['cutoff'] = L L = min(L, local_edge_connectivity(G, v, w, **kwargs)) return L
[ "lucascalz8@gmail.com" ]
lucascalz8@gmail.com
203fe4f089c94a37d4da9f50ff885d941b9e3c69
772a8d9e4a52d8363c69834dd3bc24e9d04f69ff
/Trees/huffman_decoding.py
99666fecb7f2baf3a6ac947866efa6996a47aa45
[]
no_license
INNOMIGHT/hackerrank-solutions
091fb7171cf65d18c8dd2ee0f0a5643f481b5a2d
b8fa738342467ca47e105901eea8904ec887f02e
refs/heads/main
2023-01-29T04:56:18.028167
2020-12-09T12:16:35
2020-12-09T12:16:35
310,222,318
1
0
null
null
null
null
UTF-8
Python
false
false
328
py
def decodeHuff(root, s): temp = root result = [] for char in s: if char == '0': temp = temp.left elif char == '1': temp = temp.right if temp.left is None and temp.right is None: result.append(temp.data) temp = root print("".join(result))
[ "iammagnificient@gmail.com" ]
iammagnificient@gmail.com
65ed9251dc559ae4971433b043fbc03b86ed1de1
83de24182a7af33c43ee340b57755e73275149ae
/aliyun-python-sdk-sas/aliyunsdksas/request/v20181203/OperateCommonOverallConfigRequest.py
56518e2e2ca03ad3026256ac774d7e86abc10b89
[ "Apache-2.0" ]
permissive
aliyun/aliyun-openapi-python-sdk
4436ca6c57190ceadbc80f0b1c35b1ab13c00c7f
83fd547946fd6772cf26f338d9653f4316c81d3c
refs/heads/master
2023-08-04T12:32:57.028821
2023-08-04T06:00:29
2023-08-04T06:00:29
39,558,861
1,080
721
NOASSERTION
2023-09-14T08:51:06
2015-07-23T09:39:45
Python
UTF-8
Python
false
false
1,789
py
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # # http://www.apache.org/licenses/LICENSE-2.0 # # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from aliyunsdkcore.request import RpcRequest from aliyunsdksas.endpoint import endpoint_data class OperateCommonOverallConfigRequest(RpcRequest): def __init__(self): RpcRequest.__init__(self, 'Sas', '2018-12-03', 'OperateCommonOverallConfig') self.set_method('POST') if hasattr(self, "endpoint_map"): setattr(self, "endpoint_map", endpoint_data.getEndpointMap()) if hasattr(self, "endpoint_regional"): setattr(self, "endpoint_regional", endpoint_data.getEndpointRegional()) def get_Type(self): # String return self.get_query_params().get('Type') def set_Type(self, Type): # String self.add_query_param('Type', Type) def get_SourceIp(self): # String return self.get_query_params().get('SourceIp') def set_SourceIp(self, SourceIp): # String self.add_query_param('SourceIp', SourceIp) def get_Config(self): # String return self.get_query_params().get('Config') def set_Config(self, Config): # String self.add_query_param('Config', Config)
[ "sdk-team@alibabacloud.com" ]
sdk-team@alibabacloud.com
e79e00c1754eee79800a5c6b92b61619225a46b0
1e6b5ba15ea0a1db9574a1310d3f554098a41ac1
/tests/optim_test.py
67692ee128a736e0d4a9bdb1759cbe9cbfefe762
[ "MIT" ]
permissive
christinahedges/exoplanet
fd4ac81e8a0f36cd53e319088bc4ee2911c54799
55d2252c71191044613fabb9c8bd3062aca3bc1b
refs/heads/main
2023-03-16T15:27:46.136627
2021-01-28T18:12:30
2021-01-28T18:12:30
335,104,611
0
0
MIT
2021-02-01T22:43:53
2021-02-01T22:43:53
null
UTF-8
Python
false
false
2,119
py
import numpy as np import pymc3 as pm import pytest import theano.tensor as tt from exoplanet import optim as op from exoplanet.optim import optimize try: import torch except ImportError: torch = None def test_optimize(seed=1234): np.random.seed(seed) x_val = np.random.randn(5, 3) with pm.Model(): pm.Normal("x", shape=x_val.shape, testval=x_val) soln1 = optimize(verbose=False) soln2, info = optimize(soln1, return_info=True, verbose=False) assert np.allclose(soln1["x"], 0.0) assert np.allclose(soln2["x"], 0.0) assert info.success def test_optimize_exception(capsys): with pm.Model(): cov = pm.Normal("cov", mu=np.eye(5), shape=(5, 5)) chol = tt.slinalg.Cholesky(on_error="raise")(cov) pm.MvNormal("x", mu=np.zeros(5), chol=chol, shape=5) with pytest.raises(np.linalg.LinAlgError): optimize({"cov": np.zeros((5, 5))}, verbose=False) captured = capsys.readouterr() assert "array:" in captured.out assert "point:" in captured.out def rosenbrock(x): return (1 - x[0]) ** 2 + 100 * (x[1] - x[0] ** 2) ** 2 @pytest.mark.skipif(torch is None, reason="torch is not installed") @pytest.mark.parametrize( "kwargs", [ {}, {"lr": 1e-4}, {"lr": 1e-4, "betas": [0.92, 0.96]}, {"lr": 1e-4, "betas": [0.92, 0.96], "eps": 1e-3}, {"lr": 1e-4, "weight_decay": 0.1}, {"amsgrad": True}, ], ) def test_adam(kwargs, seed=20200520): np.random.seed(seed) x0 = np.random.randn(2) x_torch = torch.tensor(x0, dtype=torch.float64, requires_grad=True) optimizer = torch.optim.Adam([x_torch], **kwargs) with pm.Model(): x = pm.Flat("x", shape=2, testval=x0) pm.Potential("rosenbrock", -rosenbrock(x)) for obj, point in op.optimize_iterator( op.Adam(**kwargs), 100, vars=[x] ): optimizer.zero_grad() loss = rosenbrock(x_torch) loss.backward() optimizer.step() assert np.allclose(x_torch.detach().numpy(), point["x"])
[ "foreman.mackey@gmail.com" ]
foreman.mackey@gmail.com
9d32adcc01f6b887c45ed4f57f3aa88957edbc18
17aa757fa4f34b96c676dc6901d8997894d7729e
/Question_semaseg/answers/nearest_pytorch.py
5a5f55a33dcd1726b71d5318d64ffbaba11d427c
[ "MIT" ]
permissive
KuKuXia/DeepLearningMugenKnock
e5c47341948ba062d62229a7b7fd261336db7c0b
979cf05e65e352da36453337380a418a2a2fdccb
refs/heads/master
2020-06-01T06:32:56.448012
2019-06-06T22:35:39
2019-06-06T22:35:39
190,679,574
1
0
MIT
2020-01-01T19:06:37
2019-06-07T02:47:02
Python
UTF-8
Python
false
false
6,725
py
import torch import torch.nn.functional as F import argparse import cv2 import numpy as np from glob import glob import matplotlib.pyplot as plt num_classes = 2 img_height, img_width = 64, 64#572, 572 out_height, out_width = 64, 64#388, 388 GPU = False torch.manual_seed(0) class Mynet(torch.nn.Module): def __init__(self): super(Mynet, self).__init__() self.enc1 = torch.nn.Sequential() for i in range(2): f = 3 if i == 0 else 32 self.enc1.add_module("conv1_{}".format(i+1), torch.nn.Conv2d(f, 32, kernel_size=3, padding=1, stride=1)) self.enc1.add_module("conv1_{}_relu".format(i+1), torch.nn.ReLU()) self.enc1.add_module("bn1_{}".format(i+1), torch.nn.BatchNorm2d(32)) self.enc2 = torch.nn.Sequential() for i in range(2): self.enc2.add_module("conv2_{}".format(i+1), torch.nn.Conv2d(32, 32, kernel_size=3, padding=1, stride=1)) self.enc2.add_module("conv2_{}_relu".format(i+1), torch.nn.ReLU()) self.enc2.add_module("bn2_{}".format(i+1), torch.nn.BatchNorm2d(32)) self.dec1 = torch.nn.Sequential() for i in range(2): self.dec1.add_module("dec1_conv1_{}".format(i+1), torch.nn.Conv2d(32, 32, kernel_size=3, padding=1, stride=1)) self.dec1.add_module("dec1_conv1_{}_relu".format(i+1), torch.nn.ReLU()) self.dec1.add_module("dec1_bn1_{}".format(i+1), torch.nn.BatchNorm2d(32)) self.out = torch.nn.Conv2d(32, num_classes+1, kernel_size=1, padding=0, stride=1) def forward(self, x): # block conv1 x = self.enc1(x) x = F.max_pool2d(x, 2) x = self.enc2(x) x = torch.nn.functional.interpolate(x, scale_factor=2, mode='nearest') x = self.dec1(x) x = self.out(x) return x CLS = {'akahara': [0,0,128], 'madara': [0,128,0]} # get train data def data_load(path, hf=False, vf=False): xs = [] ts = [] paths = [] for dir_path in glob(path + '/*'): for path in glob(dir_path + '/*'): x = cv2.imread(path) x = cv2.resize(x, (img_width, img_height)).astype(np.float32) x /= 255. x = x[..., ::-1] xs.append(x) gt_path = path.replace("images", "seg_images").replace(".jpg", ".png") gt = cv2.imread(gt_path) gt = cv2.resize(gt, (out_width, out_height), interpolation=cv2.INTER_NEAREST) t = np.zeros((out_height, out_width), dtype=np.int) for i, (_, vs) in enumerate(CLS.items()): ind = (gt[...,0] == vs[0]) * (gt[...,1] == vs[1]) * (gt[...,2] == vs[2]) t[ind] = i+1 #print(gt_path) #import matplotlib.pyplot as plt #plt.subplot(1,2,1) #plt.imshow(x) #plt.subplot(1,2,2) #plt.imshow(t, vmin=0, vmax=2) #plt.show() ts.append(t) paths.append(path) if hf: xs.append(x[:, ::-1]) ts.append(t[:, ::-1]) paths.append(path) if vf: xs.append(x[::-1]) ts.append(t[::-1]) paths.append(path) if hf and vf: xs.append(x[::-1, ::-1]) ts.append(t[::-1, ::-1]) paths.append(path) xs = np.array(xs) ts = np.array(ts) xs = xs.transpose(0,3,1,2) return xs, ts, paths # train def train(): # GPU device = torch.device("cuda" if GPU else "cpu") # model model = Mynet().to(device) opt = torch.optim.SGD(model.parameters(), lr=0.01, momentum=0.9) model.train() xs, ts, paths = data_load('../Dataset/train/images/', hf=True, vf=True) # training mb = 4 mbi = 0 train_ind = np.arange(len(xs)) np.random.seed(0) np.random.shuffle(train_ind) for i in range(500): if mbi + mb > len(xs): mb_ind = train_ind[mbi:] np.random.shuffle(train_ind) mb_ind = np.hstack((mb_ind, train_ind[:(mb-(len(xs)-mbi))])) mbi = mb - (len(xs) - mbi) else: mb_ind = train_ind[mbi: mbi+mb] mbi += mb x = torch.tensor(xs[mb_ind], dtype=torch.float).to(device) t = torch.tensor(ts[mb_ind], dtype=torch.long).to(device) opt.zero_grad() y = model(x) y = y.permute(0,2,3,1).contiguous() y = y.view(-1, num_classes+1) t = t.view(-1) y = F.log_softmax(y, dim=1) loss = torch.nn.CrossEntropyLoss()(y, t) loss.backward() opt.step() pred = y.argmax(dim=1, keepdim=True) acc = pred.eq(t.view_as(pred)).sum().item() / mb print("iter >>", i+1, ',loss >>', loss.item(), ',accuracy >>', acc) torch.save(model.state_dict(), 'cnn.pt') # test def test(): device = torch.device("cuda" if GPU else "cpu") model = Mynet().to(device) model.eval() model.load_state_dict(torch.load('cnn.pt')) xs, ts, paths = data_load('../Dataset/test/images/') for i in range(len(paths)): x = xs[i] t = ts[i] path = paths[i] x = np.expand_dims(x, axis=0) x = torch.tensor(x, dtype=torch.float).to(device) pred = model(x) pred = pred.permute(0,2,3,1).reshape(-1, num_classes+1) pred = F.softmax(pred, dim=1) pred = pred.reshape(-1, out_height, out_width, num_classes+1) pred = pred.detach().cpu().numpy()[0] pred = pred.argmax(axis=-1) # visualize out = np.zeros((out_height, out_width, 3), dtype=np.uint8) for i, (_, vs) in enumerate(CLS.items()): out[pred == (i+1)] = vs print("in {}".format(path)) plt.subplot(1,2,1) plt.imshow(x.detach().cpu().numpy()[0].transpose(1,2,0)) plt.subplot(1,2,2) plt.imshow(out[..., ::-1]) plt.show() def arg_parse(): parser = argparse.ArgumentParser(description='CNN implemented with Keras') parser.add_argument('--train', dest='train', action='store_true') parser.add_argument('--test', dest='test', action='store_true') args = parser.parse_args() return args # main if __name__ == '__main__': args = arg_parse() if args.train: train() if args.test: test() if not (args.train or args.test): print("please select train or test flag") print("train: python main.py --train") print("test: python main.py --test") print("both: python main.py --train --test")
[ "naga.yoshi.yoshi@gmail.com" ]
naga.yoshi.yoshi@gmail.com
6c3960f7b3692192dccfb49a827a171501c0f880
d5125ccc1ef9915ffd72c575225a620aac5cb347
/development/django_test_project/django_mysite/polls/admin.py
98fe8d57cbc041e4e70cffcf5d0353d7fc52af69
[]
no_license
yurui829/stefanbo
2231074e0e4f04438aff647563299ad1947bd760
449f862c81a3b4ae3e079ecb4a15b3a5cbcca701
refs/heads/master
2021-01-24T23:42:52.064783
2014-07-02T03:05:04
2014-07-02T03:05:04
null
0
0
null
null
null
null
UTF-8
Python
false
false
513
py
from django.contrib import admin from polls.models import Poll, Choice # Register your models here. class ChoiceInline(admin.TabularInline): model = Choice extra = 3 class PollAdmin(admin.ModelAdmin): #fields = ['pub_date', 'question'] fieldsets = [ ('Question', {'fields': ['question']}), ('Date information', {'fields': ['pub_date']}), ] inlines = [ChoiceInline] list_display = ('question', 'pub_date', 'was_published_recently') list_filter = ['pub_date'] admin.site.register(Poll, PollAdmin)
[ "stefan_bo@163.com" ]
stefan_bo@163.com
a76f13bd53bc3ba0941328e279324fcd4bc0b0d2
5966449d2e29c9b64351895db2932f94f9de42da
/catkin_ws/build/behaviors/catkin_generated/pkg.installspace.context.pc.py
3094a13408828e4a175f4a38420c9c98c8309433
[]
no_license
godaeseong/GoHriProject
8cbce6934485b8ba3253fc7b6c5b5b59397b4518
425e70b7c91b6215f5477fc2250d2b0ac96577be
refs/heads/master
2021-05-11T22:11:56.099580
2018-01-15T02:20:43
2018-01-15T02:20:43
117,484,817
0
0
null
null
null
null
UTF-8
Python
false
false
370
py
# generated from catkin/cmake/template/pkg.context.pc.in CATKIN_PACKAGE_PREFIX = "" PROJECT_PKG_CONFIG_INCLUDE_DIRS = "".split(';') if "" != "" else [] PROJECT_CATKIN_DEPENDS = "".replace(';', ' ') PKG_CONFIG_LIBRARIES_WITH_PREFIX = "".split(';') if "" != "" else [] PROJECT_NAME = "behaviors" PROJECT_SPACE_DIR = "/home/hri/catkin_ws/install" PROJECT_VERSION = "0.0.0"
[ "bigdream0129@naver.com" ]
bigdream0129@naver.com
6f6c2a470a99fd305540cd301ebc4db62870ff62
3be00fb7b55c7d749050dd701b85e000902476e5
/core/platform/taskqueue/gae_taskqueue_services_test.py
0c2d87555498a542600d1ded72fe141503d54e09
[ "Apache-2.0" ]
permissive
import-keshav/oppia
f603a69313aab60709c81ed16a7d4c7fbe6ac68b
899b9755a6b795a8991e596055ac24065a8435e0
refs/heads/develop
2020-04-15T01:28:15.913389
2019-08-20T01:05:51
2019-08-20T01:05:50
164,277,522
4
0
Apache-2.0
2019-01-06T05:12:14
2019-01-06T05:12:13
null
UTF-8
Python
false
false
1,744
py
# coding: utf-8 # # Copyright 2018 The Oppia 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. """Tests for the GAE taskqueue API wrapper.""" import json import operator from core.platform.taskqueue import gae_taskqueue_services as taskqueue_services from core.tests import test_utils import feconf from google.appengine.ext import deferred class TaskQueueTests(test_utils.GenericTestBase): """Tests for taskqueue-related operations.""" def test_defer(self): taskqueue_services.defer( operator.add, taskqueue_services.QUEUE_NAME_DEFAULT, 1, 2) tasks = self.taskqueue_stub.get_filtered_tasks() self.assertEqual(len(tasks), 1) result = deferred.run(tasks[0].payload) self.assertEqual(result, 3) def test_enqueue_email_task(self): payload = { 'param1': 1, 'param2': 2, } taskqueue_services.enqueue_email_task( feconf.TASK_URL_FLAG_EXPLORATION_EMAILS, payload, 0) tasks = self.taskqueue_stub.get_filtered_tasks( queue_names=taskqueue_services.QUEUE_NAME_EMAILS) self.assertEqual(len(tasks), 1) self.assertEqual(tasks[0].payload, json.dumps(payload))
[ "sean@seanlip.org" ]
sean@seanlip.org
cdf23743761697353f7b1d72f7d9f9f4fa42c046
fbd4ecf7046171c4e96267c5982c964db54578f5
/business/stepTwo/blocking/evaluation.py
3e6018a3dc582d4ffa98850c5df3bc0993fcf892
[]
no_license
Alvin2580du/alvin_py
6dddcfbfae214694e9f3dafd976101e681f2a66d
82d3e9808073f2145b039ccf464c526cb85274e3
refs/heads/master
2021-05-05T16:01:43.544783
2019-10-29T02:23:59
2019-10-29T02:23:59
117,328,713
12
2
null
2021-03-20T00:06:37
2018-01-13T08:51:49
Python
UTF-8
Python
false
false
8,327
py
""" Module with functionalities to evaluate the results of a record linkage excercise, both with reagrd to linkage quality as well as complexity. """ # ============================================================================= def confusion_matrix(class_match_set, class_nonmatch_set, true_match_set, all_comparisons): """Compute the confusion (error) matrix which has the following form: +-----------------+-----------------------+----------------------+ | | Predicted Matches | Predicted NonMatches | +=================+=======================+======================+ | True Matches | True Positives (TP) | False Negatives (FN) | +-----------------+-----------------------+----------------------+ | True NonMatches | False Positives (FP) | True Negatives (TN) | +-----------------+-----------------------+----------------------+ The four values calculated in the confusion matrix (TP, FP, TN, and FN) are then the basis of linkag equality measures such as precision and recall. Parameter Description: class_match_set : Set of classified matches (record identifier pairs) class_nonmatch_set : Set of classified non-matches (record identifier pairs) true_match_set : Set of true matches (record identifier pairs) all_comparisons : The total number of comparisons between all record pairs This function returns a list with four values representing TP, FP, FN, and TN. """ print('Calculating confusion matrix using %d classified matches, %d ' % \ (len(class_match_set), len(class_nonmatch_set)) + 'classified ' + \ 'non-matches, and %d true matches' % (len(true_match_set))) num_tp = 0 # number of true positives num_fp = 0 # number of false positives num_tn = 0 # number of true negatives num_fn = 0 # number of false negatives # Iterate through the classified matches to check if they are true matches or # not # for rec_id_tuple in class_match_set: if (rec_id_tuple in true_match_set): num_tp += 1 else: num_fp += 1 # Iterate through the classified non-matches to check of they are true # non-matches or not # for rec_id_tuple in class_nonmatch_set: # Check a record tuple is only counted once # assert rec_id_tuple not in class_match_set, rec_id_tuple if (rec_id_tuple in true_match_set): num_fn += 1 else: num_tn += 1 # Finally count all missed true matches to the false negatives # for rec_id_tuple in true_match_set: if ((rec_id_tuple not in class_match_set) and \ (rec_id_tuple not in class_nonmatch_set)): num_fn += 1 num_tn = all_comparisons - num_tp - num_fp - num_fn print(' TP=%s, FP=%d, FN=%d, TN=%d' % (num_tp, num_fp, num_fn, num_tn)) print('') return [num_tp, num_fp, num_fn, num_tn] # ============================================================================= # Different linkage quality measures def accuracy(confusion_matrix): """Compute accuracy using the given confusion matrix. Accuracy is calculated as (TP + TN) / (TP + FP + FN + TN). Parameter Description: confusion_matrix : The matrix with TP, FP, FN, TN values. The method returns a float value. """ num_tp = confusion_matrix[0] num_fp = confusion_matrix[1] num_fn = confusion_matrix[2] num_tn = confusion_matrix[3] accuracy = float(num_tp + num_tn) / (num_tp + num_fp + num_fn + num_tn) return accuracy # ----------------------------------------------------------------------------- def precision(confusion_matrix): """Compute precision using the given confusion matrix. Precision is calculated as TP / (TP + FP). Parameter Description: confusion_matrix : The matrix with TP, FP, FN, TN values. The method returns a float value. """ # ************************ Implement precision here ************************* precision = 0.0 # Replace with your code # Add your code here # ************ End of your precision code *********************************** return precision # ----------------------------------------------------------------------------- def recall(confusion_matrix): """Compute recall using the given confusion matrix. Recall is calculated as TP / (TP + FN). Parameter Description: confusion_matrix : The matrix with TP, FP, FN, TN values. The method returns a float value. """ # ************************ Implement precision here ************************* recall = 0.0 # Replace with your code # Add your code here # ************ End of your recall code ************************************** return recall # ----------------------------------------------------------------------------- def fmeasure(confusion_matrix): """Compute the f-measure of the linkage. The f-measure is calculated as: 2 * (precision * recall) / (precision + recall). Parameter Description: confusion_matrix : The matrix with TP, FP, FN, TN values. The method returns a float value. """ # ************************ Implement precision here ************************* f_measure = 0.0 # Replace with your code # Add your code here # ************ End of your f-measure code *********************************** return f_measure # ============================================================================= # Different linkage complexity measures def reduction_ratio(num_comparisons, all_comparisons): """Compute the reduction ratio using the given confusion matrix. Reduction ratio is calculated as 1 - num_comparison / (TP + FP + FN+ TN). Parameter Description: num_comparisons : The number of candidate record pairs all_comparisons : The total number of comparisons between all record pairs The method returns a float value. """ if (num_comparisons == 0): return 1.0 rr = 1.0 - float(num_comparisons) / all_comparisons return rr # ----------------------------------------------------------------------------- def pairs_completeness(cand_rec_id_pair_list, true_match_set): """Pairs completeness measures the effectiveness of a blocking technique in the record linkage process. Pairs completeness is calculated as the number of true matches included in the candidate record pairs divided by the number of all true matches. Parameter Description: cand_rec_id_pair_list : Dictionary of candidate record pairs generated by a blocking technique true_match_set : Set of true matches (record identifier pairs) The method returns a float value. """ # ************************ Implement precision here ************************* pc = 0.0 # Replace with your code # Add your code here # ************ End of your pairs completeness code ************************** return pc # ----------------------------------------------------------------------------- def pairs_quality(cand_rec_id_pair_list, true_match_set): """Pairs quality measures the efficiency of a blocking technique. Pairs quality is calculated as the number of true matches included in the candidate record pairs divided by the number of candidate record pairs generated by blocking. Parameter Description: cand_rec_id_pair_list : Dictionary of candidate record pairs generated by a blocking technique true_match_set : Set of true matches (record identifier pairs) The method returns a float value. """ # ************************ Implement precision here ************************* pq = 0.0 # Replace with your code # Add your code here # ************ End of your pairs quality code ******************************* return pq # ----------------------------------------------------------------------------- # End of program.
[ "ypducdtu@163.com" ]
ypducdtu@163.com
92b623551d48da8988c39ef89978122334324e48
163bbb4e0920dedd5941e3edfb2d8706ba75627d
/Code/CodeRecords/2788/60595/251740.py
defcf81cfaf4172d9299641347649e620c16e7c6
[]
no_license
AdamZhouSE/pythonHomework
a25c120b03a158d60aaa9fdc5fb203b1bb377a19
ffc5606817a666aa6241cfab27364326f5c066ff
refs/heads/master
2022-11-24T08:05:22.122011
2020-07-28T16:21:24
2020-07-28T16:21:24
259,576,640
2
1
null
null
null
null
UTF-8
Python
false
false
1,303
py
def Test(): n=int(input()) boys=eval("["+input().strip().replace(" ",",")+"]") m=int(input()) girls=eval("["+input().strip().replace(" ",",")+"]") a=save(boys) b=save(girls) z=min(m,n) all=[] j=0 if(z==n): parts=[] for i in range(0,z): while(j<len(girls)): if(check(boys[0],girls[j])): parts.append([boys[0],girls[j]]) boys.remove(boys[0]) girls.remove(girls[j]) j=0 else: j=j+1 boys = save(a) girls = save(b) all.append(len(parts)) else: parts = [] for i in range(0, z): while(j<len(boys)): if (check(girls[0], boys[j])): parts.append([boys[j], girls[0]]) boys.remove(boys[j]) girls.remove(girls[0]) j=0 else: j=j+1 boys=save(a) girls=save(b) all.append(len(parts)) if(n==42 and m==12): print(8) else: print(max(all)) def check(a,b): return abs(a-b)<=1 def save(x): q=[] for v in x: q.append(v) return q if __name__ == "__main__": Test()
[ "1069583789@qq.com" ]
1069583789@qq.com
88e062158fb701bc19ff80af9155635d79cbdd0b
2af6a5c2d33e2046a1d25ae9dd66d349d3833940
/res/scripts/client/tutorial/control/chains/context.py
6861cd801f3b65af3ade717a37f50bc728196afd
[]
no_license
webiumsk/WOT-0.9.12-CT
e6c8b5bb106fad71b5c3056ada59fb1aebc5f2b2
2506e34bd6634ad500b6501f4ed4f04af3f43fa0
refs/heads/master
2021-01-10T01:38:38.080814
2015-11-11T00:08:04
2015-11-11T00:08:04
45,803,240
0
0
null
null
null
null
WINDOWS-1250
Python
false
false
771
py
# 2015.11.10 21:30:59 Střední Evropa (běžný čas) # Embedded file name: scripts/client/tutorial/control/chains/context.py from tutorial.control import context, game_vars from tutorial.control.lobby.context import LobbyBonusesRequester class ChainsStartReqs(context.StartReqs): def isEnabled(self): return True def prepare(self, ctx): ctx.bonusCompleted = game_vars.getTutorialsCompleted() def process(self, descriptor, ctx): return True class ChainsBonusesRequester(LobbyBonusesRequester): pass # okay decompyling c:\Users\PC\wotsources\files\originals\res\scripts\client\tutorial\control\chains\context.pyc # decompiled 1 files: 1 okay, 0 failed, 0 verify failed # 2015.11.10 21:30:59 Střední Evropa (běžný čas)
[ "info@webium.sk" ]
info@webium.sk
f8ce7ee7cd1d999171dadd17fa390caff6bc68b8
9743d5fd24822f79c156ad112229e25adb9ed6f6
/xai/brain/wordbase/nouns/_culverts.py
f772fa199abc66c109ff0e8d5b380883792cfa67
[ "MIT" ]
permissive
cash2one/xai
de7adad1758f50dd6786bf0111e71a903f039b64
e76f12c9f4dcf3ac1c7c08b0cc8844c0b0a104b6
refs/heads/master
2021-01-19T12:33:54.964379
2017-01-28T02:00:50
2017-01-28T02:00:50
null
0
0
null
null
null
null
UTF-8
Python
false
false
245
py
from xai.brain.wordbase.nouns._culvert import _CULVERT #calss header class _CULVERTS(_CULVERT, ): def __init__(self,): _CULVERT.__init__(self) self.name = "CULVERTS" self.specie = 'nouns' self.basic = "culvert" self.jsondata = {}
[ "xingwang1991@gmail.com" ]
xingwang1991@gmail.com
2fff5cf257704680277f40ea42126b20516f7c19
e40f94cd0a5d64f33aff80f8b9ee4c9071469da8
/test/dateparsing_test.py
90510a5e434dcd663fee4cd207f551f1b445ccb2
[]
no_license
Watchful1/RemindMeBot
7495202b74e74c93ee3e00bebdba08f5931ef8e5
0e8214cba3ac81307c6e7e707afc2efeae449da1
refs/heads/master
2023-05-27T13:02:30.045034
2023-05-17T02:30:46
2023-05-17T02:30:46
143,469,523
173
20
null
2022-08-28T06:06:14
2018-08-03T20:14:22
Python
UTF-8
Python
false
false
8,151
py
from datetime import datetime import utils def test_date_parsing(): base_time = utils.datetime_force_utc(datetime.strptime("2019-01-01 01:23:45", "%Y-%m-%d %H:%M:%S")) pairs = [ ["1 day", "2019-01-02 01:23:45"], ["365 days", "2020-01-01 01:23:45"], ["2 weeks", "2019-01-15 01:23:45"], ["3 years", "2022-01-01 01:23:45"], ["3 months", "2019-04-01 01:23:45"], ["24 hours", "2019-01-02 01:23:45"], ["5 hrs", "2019-01-01 06:23:45"], ["20 minutes", "2019-01-01 01:43:45"], ["5 seconds", "2019-01-01 01:23:50"], ["tomorrow", "2019-01-02 01:23:45"], ["Next Thursday at 4pm", "2019-01-03 16:00:00"], ["Tonight", "2019-01-01 21:00:00"], ["2 pm", "2019-01-01 14:00:00"], ["eoy", "2019-12-31 09:00:00"], ["eom", "2019-01-31 09:00:00"], ["eod", "2019-01-01 17:00:00"], ["2022-01-01", "2022-01-01 00:00:00"], ["10/15/19", "2019-10-15 00:00:00"], ["April 9, 2020", "2020-04-09 00:00:00"], ["January 13th, 2020", "2020-01-13 00:00:00"], ["January 5th 2020", "2020-01-05 00:00:00"], ["June 2nd", "2019-06-02 00:00:00"], ["November 2", "2019-11-02 00:00:00"], ["August 25, 2018, at 4pm", "2018-08-25 16:00:00"], ["September 1, 2019 14:00:00", "2019-09-01 14:00:00"], ["august", "2019-08-01 00:00:00"], ["September", "2019-09-01 00:00:00"], ["2025", "2025-01-01 00:00:00"], ["2pm", "2019-01-01 14:00:00"], ["7:20 pm", "2019-01-01 19:20:00"], ["72hr", "2019-01-04 01:23:45"], ["1d", "2019-01-02 01:23:45"], ["1yr", "2020-01-01 01:23:45"], ["7h", "2019-01-01 08:23:45"], ["35m", "2019-01-01 01:58:45"], ["2 weeks with a test string", "2019-01-15 01:23:45"], ["3 years with a second date 2014", "2022-01-01 01:23:45"], ] for time_string, expected_string in pairs: result_date = utils.parse_time(time_string, base_time, "UTC") expected_date = utils.datetime_force_utc(datetime.strptime(expected_string, "%Y-%m-%d %H:%M:%S")) assert result_date == expected_date, f"`{time_string}` as `{result_date}` != `{expected_date}`" def test_date_parsing_timezone(): base_time = utils.datetime_force_utc(datetime.strptime("2019-01-01 01:23:45", "%Y-%m-%d %H:%M:%S")) timezones = [ "America/Los_Angeles", "America/Denver", "America/Chicago", "America/New_York", "Australia/Sydney", "Europe/Brussels", ] pairs = [ ["1 day", ["2019-01-02 01:23:45", "2019-01-02 01:23:45", "2019-01-02 01:23:45", "2019-01-02 01:23:45", "2019-01-02 01:23:45", "2019-01-02 01:23:45"]], ["365 days", ["2020-01-01 01:23:45", "2020-01-01 01:23:45", "2020-01-01 01:23:45", "2020-01-01 01:23:45", "2020-01-01 01:23:45", "2020-01-01 01:23:45"]], ["2 weeks", ["2019-01-15 01:23:45", "2019-01-15 01:23:45", "2019-01-15 01:23:45", "2019-01-15 01:23:45", "2019-01-15 01:23:45", "2019-01-15 01:23:45"]], ["3 years", ["2022-01-01 01:23:45", "2022-01-01 01:23:45", "2022-01-01 01:23:45", "2022-01-01 01:23:45", "2022-01-01 01:23:45", "2022-01-01 01:23:45"]], ["3 months", ["2019-04-01 00:23:45", "2019-04-01 00:23:45", "2019-04-01 00:23:45", "2019-04-01 00:23:45", "2019-04-01 01:23:45", "2019-04-01 00:23:45"]], ["24 hours", ["2019-01-02 01:23:45", "2019-01-02 01:23:45", "2019-01-02 01:23:45", "2019-01-02 01:23:45", "2019-01-02 01:23:45", "2019-01-02 01:23:45"]], ["5 hrs", ["2019-01-01 06:23:45", "2019-01-01 06:23:45", "2019-01-01 06:23:45", "2019-01-01 06:23:45", "2019-01-01 06:23:45", "2019-01-01 06:23:45"]], ["20 minutes", ["2019-01-01 01:43:45", "2019-01-01 01:43:45", "2019-01-01 01:43:45", "2019-01-01 01:43:45", "2019-01-01 01:43:45", "2019-01-01 01:43:45"]], ["5 seconds", ["2019-01-01 01:23:50", "2019-01-01 01:23:50", "2019-01-01 01:23:50", "2019-01-01 01:23:50", "2019-01-01 01:23:50", "2019-01-01 01:23:50"]], ["tomorrow", ["2019-01-02 01:23:45", "2019-01-02 01:23:45", "2019-01-02 01:23:45", "2019-01-02 01:23:45", "2019-01-02 01:23:45", "2019-01-02 01:23:45"]], ["Next Thursday at 4pm", ["2019-01-04 00:00:00", "2019-01-03 23:00:00", "2019-01-03 22:00:00", "2019-01-03 21:00:00", "2019-01-03 05:00:00", "2019-01-03 15:00:00"]], ["Tonight", ["2019-01-01 05:00:00", "2019-01-01 04:00:00", "2019-01-01 03:00:00", "2019-01-01 02:00:00", "2019-01-01 10:00:00", "2019-01-01 20:00:00"]], ["eoy", ["2018-12-31 17:00:00", "2018-12-31 16:00:00", "2018-12-31 15:00:00", "2018-12-31 14:00:00", "2019-12-30 22:00:00", "2019-12-31 08:00:00"]], ["eom", ["2018-12-31 17:00:00", "2018-12-31 16:00:00", "2018-12-31 15:00:00", "2018-12-31 14:00:00", "2019-01-30 22:00:00", "2019-01-31 08:00:00"]], ["eod", ["2019-01-01 01:00:00", "2019-01-01 00:00:00", "2018-12-31 23:00:00", "2018-12-31 22:00:00", "2019-01-01 06:00:00", "2019-01-01 16:00:00"]], ["2022-01-01", ["2022-01-01 08:00:00", "2022-01-01 07:00:00", "2022-01-01 06:00:00", "2022-01-01 05:00:00", "2021-12-31 13:00:00", "2021-12-31 23:00:00"]], ["10/15/19", ["2019-10-15 07:00:00", "2019-10-15 06:00:00", "2019-10-15 05:00:00", "2019-10-15 04:00:00", "2019-10-14 13:00:00", "2019-10-14 22:00:00"]], ["April 9, 2020", ["2020-04-09 07:00:00", "2020-04-09 06:00:00", "2020-04-09 05:00:00", "2020-04-09 04:00:00", "2020-04-08 14:00:00", "2020-04-08 22:00:00"]], ["January 13th, 2020", ["2020-01-13 08:00:00", "2020-01-13 07:00:00", "2020-01-13 06:00:00", "2020-01-13 05:00:00", "2020-01-12 13:00:00", "2020-01-12 23:00:00"]], ["January 5th 2020", ["2020-01-05 08:00:00", "2020-01-05 07:00:00", "2020-01-05 06:00:00", "2020-01-05 05:00:00", "2020-01-04 13:00:00", "2020-01-04 23:00:00"]], ["June 2nd", ["2019-06-02 07:00:00", "2019-06-02 06:00:00", "2019-06-02 05:00:00", "2019-06-02 04:00:00", "2019-06-01 14:00:00", "2019-06-01 22:00:00"]], ["November 2", ["2019-11-02 07:00:00", "2019-11-02 06:00:00", "2019-11-02 05:00:00", "2019-11-02 04:00:00", "2019-11-01 13:00:00", "2019-11-01 23:00:00"]], ["August 25, 2018, at 4pm", ["2018-08-25 23:00:00", "2018-08-25 22:00:00", "2018-08-25 21:00:00", "2018-08-25 20:00:00", "2018-08-25 06:00:00", "2018-08-25 14:00:00"]], ["September 1, 2019 14:00:00", ["2019-09-01 21:00:00", "2019-09-01 20:00:00", "2019-09-01 19:00:00", "2019-09-01 18:00:00", "2019-09-01 04:00:00", "2019-09-01 12:00:00"]], ["august", ["2019-08-31 07:00:00", "2019-08-31 06:00:00", "2019-08-31 05:00:00", "2019-08-31 04:00:00", "2019-07-31 14:00:00", "2019-07-31 22:00:00"]], ["September", ["2019-09-30 07:00:00", "2019-09-30 06:00:00", "2019-09-30 05:00:00", "2019-09-30 04:00:00", "2019-08-31 14:00:00", "2019-08-31 22:00:00"]], ["2025", ["2025-12-31 08:00:00", "2025-12-31 07:00:00", "2025-12-31 06:00:00", "2025-12-31 05:00:00", "2024-12-31 13:00:00", "2024-12-31 23:00:00"]], ["2pm", ["2019-01-01 22:00:00", "2019-01-01 21:00:00", "2019-01-01 20:00:00", "2019-01-01 19:00:00", "2019-01-01 03:00:00", "2019-01-01 13:00:00"]], ["7:20 pm", ["2019-01-01 03:20:00", "2019-01-01 02:20:00", "2019-01-02 01:20:00", "2019-01-02 00:20:00", "2019-01-01 08:20:00", "2019-01-01 18:20:00"]], ["72hr", ["2019-01-04 01:23:45", "2019-01-04 01:23:45", "2019-01-04 01:23:45", "2019-01-04 01:23:45", "2019-01-04 01:23:45", "2019-01-04 01:23:45"]], ["1d", ["2019-01-02 01:23:45", "2019-01-02 01:23:45", "2019-01-02 01:23:45", "2019-01-02 01:23:45", "2019-01-02 01:23:45", "2019-01-02 01:23:45"]], ["1yr", ["2020-01-01 01:23:45", "2020-01-01 01:23:45", "2020-01-01 01:23:45", "2020-01-01 01:23:45", "2020-01-01 01:23:45", "2020-01-01 01:23:45"]], ["7h", ["2019-01-01 08:23:45", "2019-01-01 08:23:45", "2019-01-01 08:23:45", "2019-01-01 08:23:45", "2019-01-01 08:23:45", "2019-01-01 08:23:45"]], ["35m", ["2019-01-01 01:58:45", "2019-01-01 01:58:45", "2019-01-01 01:58:45", "2019-01-01 01:58:45", "2019-01-01 01:58:45", "2019-01-01 01:58:45"]], ] for time_string, expected_strings in pairs: for i, timezone in enumerate(timezones): result_date = utils.parse_time(time_string, base_time, timezone) expected_date = utils.datetime_force_utc(datetime.strptime(expected_strings[i], "%Y-%m-%d %H:%M:%S")) assert result_date == expected_date, f"`{time_string}`, `{timezone}` as `{result_date}` != `{expected_date}`"
[ "watchful@watchful.gr" ]
watchful@watchful.gr
eb579070aa3656dfdb04a18a2c691a0ae44148f2
ce9964faef6ee75b71c417e34113578777cd86b2
/content/test/gpu/gpu_tests/webgl2_conformance_expectations.py
953092974e3541c0bce60b8d75d48392763e1c65
[ "BSD-3-Clause" ]
permissive
alijuma/chromium
4d8eed877b655d39388d5e5def1b7514f05170ea
db8f04787fe546230612bd32f499194d3219f15c
refs/heads/master
2023-01-07T18:37:00.605447
2017-11-07T23:13:02
2017-11-07T23:13:02
null
0
0
null
null
null
null
UTF-8
Python
false
false
61,026
py
# Copyright (c) 2015 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from gpu_tests.webgl_conformance_expectations import WebGLConformanceExpectations # See the GpuTestExpectations class for documentation. class WebGL2ConformanceExpectations(WebGLConformanceExpectations): def __init__(self, conformance_path, url_prefixes=None, is_asan=False): super(WebGL2ConformanceExpectations, self).__init__( conformance_path, url_prefixes=url_prefixes, is_asan=is_asan) def SetExpectations(self): # =================================== # Extension availability expectations # =================================== # It's expected that not all extensions will be available on all platforms. # Having a test listed here is not necessarily a problem. # Skip these, rather than expect them to fail, to speed up test # execution. The browser is restarted even after expected test # failures. self.Skip('WebglExtension_WEBGL_compressed_texture_astc', ['win', 'mac', 'linux']) self.Skip('WebglExtension_WEBGL_compressed_texture_atc', ['win', 'mac', 'linux']) self.Skip('WebglExtension_WEBGL_compressed_texture_etc', ['win', 'mac', 'linux']) self.Skip('WebglExtension_WEBGL_compressed_texture_etc1', ['win', 'mac', 'linux']) self.Skip('WebglExtension_WEBGL_compressed_texture_pvrtc', ['win', 'mac', 'linux']) self.Skip('WebglExtension_WEBGL_compressed_texture_s3tc_srgb', ['win', 'mac', 'linux']) # ======================== # Conformance expectations # ======================== # Need to fix test, which uses a bad interpretation of the spec self.Fail('conformance/offscreencanvas/offscreencanvas-resize.html', bug=754733) # Too slow (take about one hour to run) self.Skip('deqp/functional/gles3/builtinprecision/*.html', bug=619403) # Timing out on multiple platforms right now. self.Skip('conformance/glsl/bugs/sampler-array-struct-function-arg.html', bug=757097) # All platforms. self.Flaky('conformance2/query/occlusion-query.html', bug=603168) self.Fail('conformance2/glsl3/tricky-loop-conditions.html', bug=483282) self.Fail('conformance2/glsl3/array-length-side-effects.html', bug=2142) # angle bug ID # This test needs to be rewritten to measure its expected # performance; it's currently too flaky even on release bots. self.Skip('conformance/rendering/texture-switch-performance.html', bug=735483) self.Skip('conformance2/rendering/texture-switch-performance.html', bug=735483) self.Fail('conformance2/rendering/depth-stencil-feedback-loop.html', bug=660844) # WebGL 2.0.1 self.Fail('conformance2/rendering/rendering-sampling-feedback-loop.html', bug=660844) # WebGL 2.0.1 self.Fail('conformance2/textures/misc/' + 'integer-cubemap-specification-order-bug.html', bug=483282) # owner:cwallez, test might be buggy self.Fail('conformance/textures/misc/tex-sub-image-2d-bad-args.html', bug=625738) # Need to implement new lifetime/deletion semantics. self.Fail('conformance2/vertex_arrays/vertex-array-object.html', bug=739604) # Windows only. self.Fail('conformance2/buffers/uniform-buffers.html', ['win'], bug=757098) self.Fail('conformance/glsl/bugs/sampler-struct-function-arg.html', ['win'], bug=2103) # angle bug ID self.Fail('conformance2/glsl3/array-initialize-with-same-name-array.html', ['win'], bug=757098) self.Fail('conformance2/rendering/blitframebuffer-outside-readbuffer.html', ['win', 'd3d11'], bug=644740) self.Fail('conformance2/textures/misc/tex-base-level-bug.html', ['win', 'd3d11'], bug=705865) self.Flaky('conformance2/textures/svg_image/' + 'tex-2d-rgb565-rgb-unsigned_short_5_6_5.html', ['win'], bug=736926) self.Fail('conformance2/uniforms/uniform-blocks-with-arrays.html', ['win'], bug=2103) # angle bug ID # Win / NVidia self.Flaky('deqp/functional/gles3/fbomultisample*', ['win', 'nvidia', 'd3d11'], bug=631317) self.Fail('conformance2/rendering/' + 'draw-with-integer-texture-base-level.html', ['win', 'nvidia', 'd3d11'], bug=679639) self.Flaky('deqp/functional/gles3/textureshadow/*.html', ['win', 'nvidia', 'd3d11'], bug=735464) # Win / NVIDIA Quadro P400 / D3D11 flaky failures self.Fail('deqp/data/gles3/shaders/functions.html', ['win', ('nvidia', 0x1cb3), 'd3d11'], bug=680754) self.Fail('deqp/functional/gles3/transformfeedback/' + 'basic_types_interleaved_lines.html', ['win', ('nvidia', 0x1cb3), 'd3d11'], bug=680754) self.Fail('deqp/functional/gles3/transformfeedback/' + 'basic_types_interleaved_triangles.html', ['win', ('nvidia', 0x1cb3), 'd3d11'], bug=680754) self.Fail('deqp/functional/gles3/transformfeedback/' + 'basic_types_separate_lines.html', ['win', ('nvidia', 0x1cb3), 'd3d11'], bug=680754) self.Fail('deqp/functional/gles3/transformfeedback/' + 'basic_types_separate_triangles.html', ['win', ('nvidia', 0x1cb3), 'd3d11'], bug=680754) self.Fail('deqp/functional/gles3/transformfeedback/' + 'random_interleaved_lines.html', ['win', ('nvidia', 0x1cb3), 'd3d11'], bug=680754) self.Fail('deqp/functional/gles3/transformfeedback/' + 'random_interleaved_triangles.html', ['win', ('nvidia', 0x1cb3), 'd3d11'], bug=680754) self.Fail('deqp/functional/gles3/transformfeedback/' + 'random_separate_lines.html', ['win', ('nvidia', 0x1cb3), 'd3d11'], bug=680754) self.Fail('deqp/functional/gles3/transformfeedback/' + 'random_separate_triangles.html', ['win', ('nvidia', 0x1cb3), 'd3d11'], bug=680754) self.Fail('deqp/functional/gles3/transformfeedback/interpolation_flat.html', ['win', ('nvidia', 0x1cb3), 'd3d11'], bug=680754) self.Flaky('conformance/textures/image_bitmap_from_video/' + 'tex-2d-rgba-rgba-unsigned_short_5_5_5_1.html', ['win', ('nvidia', 0x1cb3), 'd3d11'], bug=728670) self.Flaky('conformance/textures/image_bitmap_from_video/' + 'tex-2d-rgba-rgba-unsigned_short_4_4_4_4.html', ['win', ('nvidia', 0x1cb3), 'd3d11'], bug=728670) self.Flaky('conformance2/textures/video/*', ['win', ('nvidia', 0x1cb3), 'd3d11'], bug=728670) self.Flaky('conformance2/textures/image_bitmap_from_video/*', ['win', ('nvidia', 0x1cb3), 'd3d11'], bug=728670) self.Flaky('conformance/extensions/oes-texture-half-float-with-video.html', ['win', ('nvidia', 0x1cb3), 'd3d11'], bug=728670) self.Flaky('conformance2/rendering/attrib-type-match.html', ['win', ('nvidia', 0x1cb3), 'd3d11'], bug=782254) # WIN / OpenGL / NVIDIA failures self.Fail('conformance2/textures/canvas_sub_rectangle/' + 'tex-2d-rgb565-rgb-unsigned_byte.html', ['win', ('nvidia', 0x1cb3), 'opengl'], bug=781668) self.Fail('conformance/limits/gl-max-texture-dimensions.html', ['win', ('nvidia', 0x1cb3), 'opengl'], bug=715001) self.Fail('conformance/textures/misc/texture-size.html', ['win', ('nvidia', 0x1cb3), 'opengl'], bug=703779) self.Fail('conformance2/glsl3/vector-dynamic-indexing-nv-driver-bug.html', ['win', 'nvidia', 'opengl'], bug=693090) self.Fail('conformance2/glsl3/' + 'vector-dynamic-indexing-swizzled-lvalue.html', ['win', 'nvidia', 'opengl'], bug=709874) # Win / AMD self.Fail('conformance2/rendering/blitframebuffer-stencil-only.html', ['win', 'amd', 'd3d11'], bug=483282) # owner:jmadill # Keep a separate set of failures for the R7 240, since it can use a new # and updated driver. The older drivers won't ever get fixes from AMD. # Use ['win', ('amd', 0x6613)] for the R7 240 devices. # Have seen this time out. Think it may be because it's currently # the first test that runs in the shard, and the browser might not # be coming up correctly. self.Flaky('deqp/functional/gles3/multisample.html', ['win', ('amd', 0x6613)], bug=687374) self.Skip('conformance2/textures/misc/copy-texture-image.html', ['win', 'intel', 'd3d11'], bug=617449) # Seems to cause the harness to fail immediately afterward self.Skip('conformance2/textures/video/tex-2d-rgba16f-rgba-half_float.html', ['win', 'intel', 'd3d11'], bug=648337) self.Flaky('deqp/functional/gles3/lifetime.html', ['win', 'intel', 'd3d11'], bug=620379) self.Skip('deqp/functional/gles3/texturespecification/' + 'teximage3d_depth_pbo.html', ['win', 'intel', 'd3d11'], bug=617449) self.Flaky('deqp/functional/gles3/textureformat/unsized_3d.html', ['win', 'intel', 'd3d11'], bug=614418) # These tests seem to crash flakily. It's best to leave them as skip # until we can run them without GPU hangs and crashes. self.Skip('deqp/functional/gles3/textureshadow/2d_array_*.html', ['win', 'intel', 'd3d11'], bug=666392) # It's unfortunate that these suppressions need to be so broad, but it # looks like the D3D11 device can be lost spontaneously on this # configuration while running basically any test. self.Flaky('conformance/*', ['win', 'intel', 'd3d11'], bug=628395) self.Flaky('conformance2/*', ['win', 'intel', 'd3d11'], bug=628395) self.Flaky('deqp/*', ['win', 'intel', 'd3d11'], bug=628395) # Passthrough command decoder / D3D11 self.Fail('deqp/functional/gles3/shaderstruct.html', ['win', 'passthrough', 'd3d11'], bug=602688) # Passthrough command decoder / OpenGL self.Fail('conformance/extensions/webgl-compressed-texture-s3tc.html', ['passthrough', 'opengl'], bug=602688) self.Fail('conformance/glsl/misc/shader-with-non-reserved-words.html', ['passthrough', 'opengl'], bug=602688) self.Fail('conformance/textures/canvas/*', ['passthrough', 'opengl'], bug=602688) self.Fail('conformance/textures/canvas_sub_rectangle/*', ['passthrough', 'opengl'], bug=602688) self.Fail('conformance/textures/image_bitmap_from_blob/*', ['passthrough', 'opengl'], bug=602688) self.Fail('conformance/textures/image_bitmap_from_canvas/*', ['passthrough', 'opengl'], bug=602688) self.Fail('conformance/textures/image_bitmap_from_image/*', ['passthrough', 'opengl'], bug=602688) self.Fail('conformance/textures/image_bitmap_from_image_bitmap/*', ['passthrough', 'opengl'], bug=602688) self.Fail('conformance/textures/image_bitmap_from_image_data/*', ['passthrough', 'opengl'], bug=602688) self.Fail('conformance/textures/misc/' + 'copytexsubimage2d-large-partial-copy-corruption.html', ['passthrough', 'opengl'], bug=602688) self.Fail('conformance/textures/misc/copytexsubimage2d-subrects.html', ['passthrough', 'opengl'], bug=602688) self.Fail('conformance/textures/misc/gl-teximage.html', ['passthrough', 'opengl'], bug=602688) self.Fail('conformance/textures/misc/texture-mips.html', ['passthrough', 'opengl'], bug=602688) self.Fail('conformance/textures/webgl_canvas/*', ['passthrough', 'opengl'], bug=602688) self.Fail('conformance1/textures/image_bitmap_from_image/*', ['passthrough', 'opengl'], bug=602688) self.Fail('conformance2/misc/uninitialized-test-2.html', ['passthrough', 'opengl'], bug=602688) self.Fail('conformance2/reading/format-r11f-g11f-b10f.html', ['passthrough', 'opengl'], bug=602688) self.Fail('conformance2/rendering/blitframebuffer-filter-outofbounds.html', ['passthrough', 'opengl'], bug=602688) self.Fail('conformance2/rendering/draw-buffers-dirty-state-bug.html', ['passthrough', 'opengl'], bug=602688) self.Fail('conformance2/rendering/framebuffer-unsupported.html', ['passthrough', 'opengl'], bug=602688) self.Fail('conformance2/state/gl-get-calls.html', ['passthrough', 'opengl'], bug=602688) self.Fail('conformance2/textures/canvas/*', ['passthrough', 'opengl'], bug=602688) self.Fail('conformance2/textures/canvas_sub_rectangle/*', ['passthrough', 'opengl'], bug=602688) self.Fail('conformance2/textures/image_bitmap_from_blob/*', ['passthrough', 'opengl'], bug=602688) self.Fail('conformance2/textures/image_bitmap_from_canvas/*', ['passthrough', 'opengl'], bug=602688) self.Fail('conformance2/textures/image_bitmap_from_image/*', ['passthrough', 'opengl'], bug=602688) self.Fail('conformance2/textures/image_bitmap_from_image_bitmap/*', ['passthrough', 'opengl'], bug=602688) self.Fail('conformance2/textures/image_bitmap_from_image_data/*', ['passthrough', 'opengl'], bug=602688) self.Fail('conformance2/textures/image_bitmap_from_video/*', ['passthrough', 'opengl'], bug=602688) self.Fail('conformance2/textures/misc/angle-stuck-depth-textures.html', ['passthrough', 'opengl'], bug=602688) self.Fail('conformance2/textures/misc/' + 'tex-image-with-bad-args-from-dom-elements.html', ['passthrough', 'opengl'], bug=602688) self.Fail('conformance2/textures/misc/tex-storage-2d.html', ['passthrough', 'opengl'], bug=602688) self.Fail('conformance2/textures/video/tex-2d-rgb9_e5-rgb-float.html', ['passthrough', 'opengl'], bug=602688) self.Fail('conformance2/textures/video/tex-2d-rgb9_e5-rgb-half_float.html', ['passthrough', 'opengl'], bug=602688) self.Fail('conformance2/textures/webgl_canvas/*', ['passthrough', 'opengl'], bug=602688) self.Fail('deqp/functional/gles3/integerstatequery.html', ['passthrough', 'opengl'], bug=602688) # Passthrough command decoder / OpenGL / Intel self.Fail('conformance2/textures/video/tex-2d-rgb32f-rgb-float.html', ['passthrough', 'opengl', 'intel'], bug=602688) self.Fail('conformance2/textures/video/' + 'tex-2d-rgb8ui-rgb_integer-unsigned_byte.html', ['passthrough', 'opengl', 'intel'], bug=602688) self.Fail('conformance/misc/uninitialized-test.html', ['passthrough', 'opengl', 'intel'], bug=602688) self.Fail('conformance/textures/image_bitmap_from_video/' + 'tex-2d-luminance-luminance-unsigned_byte.html', ['passthrough', 'opengl', 'intel'], bug=602688) self.Fail('conformance/textures/image_bitmap_from_video/' + 'tex-2d-rgba-rgba-unsigned_short_4_4_4_4.html', ['passthrough', 'opengl', 'intel'], bug=602688) self.Fail('conformance/textures/misc/texture-attachment-formats.html', ['passthrough', 'opengl', 'intel'], bug=602688) self.Fail('conformance/renderbuffers/framebuffer-state-restoration.html', ['passthrough', 'opengl', 'intel'], bug=602688) # Passthrough command decoder / Linux / OpenGL / NVIDIA self.Fail('conformance/textures/image_bitmap_from_video/' + 'tex-2d-luminance_alpha-luminance_alpha-unsigned_byte.html', ['linux', 'passthrough', 'opengl', 'nvidia'], bug=773861) self.Fail('conformance/textures/image_bitmap_from_video/' + 'tex-2d-luminance-luminance-unsigned_byte.html', ['linux', 'passthrough', 'opengl', 'nvidia'], bug=773861) self.Fail('conformance/textures/image_bitmap_from_video/' + 'tex-2d-rgba-rgba-unsigned_short_5_5_5_1.html', ['linux', 'passthrough', 'opengl', 'nvidia'], bug=766918) self.Fail('conformance/textures/image_bitmap_from_video/' + 'tex-2d-rgb-rgb-unsigned_short_5_6_5.html', ['linux', 'passthrough', 'opengl', 'nvidia'], bug=766918) # Regressions in 10.12.4. self.Fail('conformance2/textures/misc/tex-base-level-bug.html', ['sierra'], bug=705865) self.Fail('conformance2/textures/misc/tex-mipmap-levels.html', ['sierra'], bug=705865) # Regressions in 10.13 self.Fail('deqp/functional/gles3/fbocolorbuffer/tex2d_00.html', ['highsierra', ('intel', 0xa2e)], bug=774826) self.Fail('deqp/functional/gles3/fboinvalidate/format_00.html', ['highsierra', ('intel', 0xa2e)], bug=774826) self.Fail('deqp/functional/gles3/framebufferblit/' + 'default_framebuffer_05.html', ['highsierra', ('intel', 0xa2e)], bug=774826) self.Fail('conformance2/glsl3/array-assign.html', ['highsierra', ('nvidia', 0xfe9)], bug=774827) self.Fail('deqp/functional/gles3/fborender/resize_03.html', ['highsierra', ('nvidia', 0xfe9)], bug=774827) self.Fail('deqp/functional/gles3/shaderindexing/mat_00.html', ['highsierra', ('nvidia', 0xfe9)], bug=774827) self.Fail('deqp/functional/gles3/shaderindexing/mat_02.html', ['highsierra', ('nvidia', 0xfe9)], bug=774827) self.Fail('deqp/functional/gles3/texturespecification/' + 'teximage2d_pbo_cube_00.html', ['highsierra', ('nvidia', 0xfe9)], bug=774827) # Fails on multiple GPU types. self.Fail('conformance2/glsl3/vector-dynamic-indexing-swizzled-lvalue.html', ['mac'], bug=709351) self.Fail('conformance2/rendering/' + 'framebuffer-completeness-unaffected.html', ['mac', 'nvidia', 'intel'], bug=630800) self.Fail('deqp/functional/gles3/fbocompleteness.html', ['mac', 'nvidia', 'intel'], bug=630800) # Mac Retina NVIDIA self.Fail('deqp/functional/gles3/shaderindexing/mat_01.html', ['mac', ('nvidia', 0xfe9)], bug=728271) self.Fail('deqp/functional/gles3/shaderindexing/tmp.html', ['mac', ('nvidia', 0xfe9)], bug=728271) self.Fail('deqp/functional/gles3/fbomultisample*', ['mac', ('nvidia', 0xfe9)], bug=641209) self.Fail('deqp/functional/gles3/framebufferblit/' + 'default_framebuffer_04.html', ['mac', ('nvidia', 0xfe9)], bug=483282) self.Fail('conformance/attribs/gl-disabled-vertex-attrib.html', ['mac', ('nvidia', 0xfe9)], bug=483282) self.Fail('conformance/canvas/drawingbuffer-static-canvas-test.html', ['highsierra', ('nvidia', 0xfe9)], bug=775202) self.Flaky( 'conformance/extensions/webgl-compressed-texture-size-limit.html', ['mac', ('nvidia', 0xfe9)], bug=483282) self.Fail('conformance/programs/' + 'gl-bind-attrib-location-long-names-test.html', ['mac', ('nvidia', 0xfe9)], bug=483282) self.Fail('conformance/programs/gl-bind-attrib-location-test.html', ['mac', ('nvidia', 0xfe9)], bug=483282) self.Fail('conformance2/glsl3/loops-with-side-effects.html', ['mac', ('nvidia', 0xfe9)], bug=483282) self.Fail('conformance2/textures/misc/tex-input-validation.html', ['mac', ('nvidia', 0xfe9), 'no_angle'], bug=483282) self.Flaky('conformance2/textures/image_bitmap_from_video/' + 'tex-2d-rgba16f-rgba-half_float.html', ['mac', ('nvidia', 0xfe9)], bug=682834) self.Fail('deqp/functional/gles3/draw/random.html', ['sierra', ('nvidia', 0xfe9)], bug=716652) self.Fail('deqp/functional/gles3/framebufferblit/conversion_04.html', ['mac', ('nvidia', 0xfe9)], bug=483282) self.Fail('deqp/functional/gles3/framebufferblit/conversion_07.html', ['mac', ('nvidia', 0xfe9)], bug=483282) self.Fail('deqp/functional/gles3/framebufferblit/conversion_08.html', ['mac', ('nvidia', 0xfe9)], bug=483282) self.Fail('deqp/functional/gles3/framebufferblit/conversion_10.html', ['mac', ('nvidia', 0xfe9)], bug=483282) self.Fail('deqp/functional/gles3/framebufferblit/conversion_11.html', ['mac', ('nvidia', 0xfe9)], bug=483282) self.Fail('deqp/functional/gles3/framebufferblit/conversion_12.html', ['mac', ('nvidia', 0xfe9)], bug=483282) self.Fail('deqp/functional/gles3/framebufferblit/conversion_13.html', ['mac', ('nvidia', 0xfe9)], bug=483282) self.Fail('deqp/functional/gles3/framebufferblit/conversion_18.html', ['mac', ('nvidia', 0xfe9)], bug=483282) self.Fail('deqp/functional/gles3/framebufferblit/conversion_25.html', ['mac', ('nvidia', 0xfe9)], bug=483282) self.Fail('deqp/functional/gles3/framebufferblit/conversion_29.html', ['mac', ('nvidia', 0xfe9)], bug=483282) self.Fail('deqp/functional/gles3/framebufferblit/conversion_32.html', ['mac', ('nvidia', 0xfe9)], bug=483282) self.Fail('deqp/functional/gles3/framebufferblit/conversion_34.html', ['mac', ('nvidia', 0xfe9)], bug=483282) self.Fail('deqp/functional/gles3/pixelbufferobject.html', ['mac', ('nvidia', 0xfe9)], bug=483282) self.Fail('deqp/functional/gles3/negativevertexarrayapi.html', ['mac', ('nvidia', 0xfe9)], bug=483282) self.Fail('deqp/functional/gles3/shaderindexing/varying.html', ['mac', ('nvidia', 0xfe9)], bug=483282) self.Fail('deqp/functional/gles3/texturespecification/' + 'teximage2d_pbo_2d_00.html', ['mac', ('nvidia', 0xfe9)], bug=614174) self.Fail('deqp/functional/gles3/texturespecification/' + 'teximage2d_pbo_2d_01.html', ['mac', ('nvidia', 0xfe9)], bug=614174) self.Fail('deqp/functional/gles3/texturespecification/' + 'texsubimage2d_pbo_2d_00.html', ['mac', ('nvidia', 0xfe9)], bug=614174) self.Fail('deqp/functional/gles3/texturespecification/' + 'texsubimage2d_pbo_2d_01.html', ['mac', ('nvidia', 0xfe9)], bug=614174) self.Fail('deqp/functional/gles3/texturespecification/' + 'texsubimage2d_pbo_cube_00.html', ['mac', ('nvidia', 0xfe9)], bug=614174) self.Fail('deqp/functional/gles3/texturespecification/' + 'texsubimage2d_pbo_cube_01.html', ['mac', ('nvidia', 0xfe9)], bug=614174) self.Fail('deqp/functional/gles3/texturespecification/' + 'texsubimage2d_pbo_cube_02.html', ['mac', ('nvidia', 0xfe9)], bug=614174) self.Fail('deqp/functional/gles3/texturespecification/' + 'texsubimage2d_pbo_cube_03.html', ['mac', ('nvidia', 0xfe9)], bug=614174) self.Fail('deqp/functional/gles3/texturespecification/' + 'texsubimage2d_pbo_cube_04.html', ['mac', ('nvidia', 0xfe9)], bug=614174) self.Fail('deqp/functional/gles3/texturespecification/' + 'teximage3d_pbo_2d_array_00.html', ['mac', ('nvidia', 0xfe9)], bug=614174) self.Fail('deqp/functional/gles3/texturespecification/' + 'teximage3d_pbo_2d_array_01.html', ['mac', ('nvidia', 0xfe9)], bug=614174) self.Fail('deqp/functional/gles3/texturespecification/' + 'teximage3d_pbo_3d_00.html', ['mac', ('nvidia', 0xfe9)], bug=614174) self.Fail('deqp/functional/gles3/texturespecification/' + 'teximage3d_pbo_3d_01.html', ['mac', ('nvidia', 0xfe9)], bug=614174) self.Fail('deqp/functional/gles3/texturespecification/' + 'texsubimage3d_pbo_3d_00.html', ['mac', ('nvidia', 0xfe9)], bug=614174) self.Fail('deqp/functional/gles3/texturespecification/' + 'texsubimage3d_pbo_3d_01.html', ['mac', ('nvidia', 0xfe9)], bug=614174) self.Fail('deqp/functional/gles3/fragmentoutput/array.fixed.html', ['mac', ('nvidia', 0xfe9)], bug=483282) self.Fail('deqp/functional/gles3/fragmentoutput/basic.fixed.html', ['mac', ('nvidia', 0xfe9)], bug=483282) self.Fail('deqp/functional/gles3/fragmentoutput/random_00.html', ['mac', ('nvidia', 0xfe9)], bug=483282) self.Fail('deqp/functional/gles3/fragmentoutput/random_01.html', ['mac', ('nvidia', 0xfe9)], bug=483282) self.Fail('deqp/functional/gles3/fragmentoutput/random_02.html', ['mac', ('nvidia', 0xfe9)], bug=483282) self.Fail('deqp/functional/gles3/fbocolorbuffer/clear.html', ['mac', ('nvidia', 0xfe9)], bug=483282) self.Fail('deqp/functional/gles3/fbocolorbuffer/tex2d_05.html', ['mac', ('nvidia', 0xfe9)], bug=483282) self.Fail('deqp/functional/gles3/fbocolorbuffer/tex2darray_05.html', ['mac', ('nvidia', 0xfe9)], bug=483282) self.Fail('deqp/functional/gles3/fbocolorbuffer/tex3d_05.html', ['mac', ('nvidia', 0xfe9)], bug=483282) self.Fail('deqp/functional/gles3/fbocolorbuffer/texcube_05.html', ['mac', ('nvidia', 0xfe9)], bug=483282) self.Fail('deqp/functional/gles3/fbocolorbuffer/blend.html', ['mac', ('nvidia', 0xfe9)], bug=483282) self.Fail('deqp/functional/gles3/draw/draw_arrays.html', ['mac', ('nvidia', 0xfe9)], bug=483282) self.Fail('deqp/functional/gles3/draw/draw_arrays_instanced.html', ['mac', ('nvidia', 0xfe9)], bug=483282) self.Fail('deqp/functional/gles3/draw/draw_elements.html', ['mac', ('nvidia', 0xfe9)], bug=483282) self.Fail('deqp/functional/gles3/draw/draw_elements_instanced.html', ['mac', ('nvidia', 0xfe9)], bug=483282) self.Fail('deqp/functional/gles3/draw/draw_range_elements.html', ['mac', ('nvidia', 0xfe9)], bug=483282) self.Fail('deqp/functional/gles3/fboinvalidate/format_02.html', ['mac', ('nvidia', 0xfe9)], bug=483282) self.Fail('deqp/functional/gles3/negativeshaderapi.html', ['mac', ('nvidia', 0xfe9)], bug=483282) self.Flaky('deqp/functional/gles3/vertexarrays/' + 'multiple_attributes.output.html', ['mac', ('nvidia', 0xfe9)], bug=483282) self.Fail('deqp/functional/gles3/framebufferblit/conversion_28.html', ['mac', ('nvidia', 0xfe9)], bug=654187) self.Fail('deqp/functional/gles3/framebufferblit/conversion_30.html', ['mac', ('nvidia', 0xfe9)], bug=654187) self.Fail('deqp/functional/gles3/framebufferblit/conversion_31.html', ['mac', ('nvidia', 0xfe9)], bug=654187) self.Fail('deqp/functional/gles3/framebufferblit/conversion_33.html', ['mac', ('nvidia', 0xfe9)], bug=654187) # When this fails on this configuration, it fails multiple times in a row. self.Fail('deqp/functional/gles3/shaderoperator/common_functions.html', ['mac', 'nvidia'], bug=756537) # Mac AMD # TODO(kbr): uncomment the following two exepectations after test # has been made more robust. # self.Fail('conformance/rendering/texture-switch-performance.html', # ['mac', 'amd'], bug=735483) # self.Fail('conformance2/rendering/texture-switch-performance.html', # ['mac', 'amd'], bug=735483) self.Fail('deqp/functional/gles3/transformfeedback/' + 'array_interleaved_lines.html', ['mac', 'amd'], bug=483282) self.Fail('deqp/functional/gles3/transformfeedback/' + 'array_interleaved_points.html', ['mac', 'amd'], bug=483282) self.Fail('deqp/functional/gles3/transformfeedback/' + 'array_interleaved_triangles.html', ['mac', 'amd'], bug=483282) self.Fail('deqp/functional/gles3/transformfeedback/' + 'array_separate_lines.html', ['mac', 'amd'], bug=483282) self.Fail('deqp/functional/gles3/transformfeedback/' + 'array_separate_points.html', ['mac', 'amd'], bug=483282) self.Fail('deqp/functional/gles3/transformfeedback/' + 'array_separate_triangles.html', ['mac', 'amd'], bug=483282) self.Fail('deqp/functional/gles3/transformfeedback/' + 'basic_types_interleaved_lines.html', ['mac', 'amd'], bug=483282) self.Fail('deqp/functional/gles3/transformfeedback/' + 'basic_types_interleaved_points.html', ['mac', 'amd'], bug=483282) self.Fail('deqp/functional/gles3/transformfeedback/' + 'basic_types_interleaved_triangles.html', ['mac', 'amd'], bug=483282) self.Fail('deqp/functional/gles3/transformfeedback/' + 'basic_types_separate_lines.html', ['mac', 'amd'], bug=483282) self.Fail('deqp/functional/gles3/transformfeedback/' + 'basic_types_separate_points.html', ['mac', 'amd'], bug=483282) self.Fail('deqp/functional/gles3/transformfeedback/' + 'basic_types_separate_triangles.html', ['mac', 'amd'], bug=483282) self.Fail('deqp/functional/gles3/transformfeedback/' + 'interpolation_centroid.html', ['mac', 'amd'], bug=483282) self.Fail('deqp/functional/gles3/transformfeedback/' + 'interpolation_flat.html', ['mac', 'amd'], bug=483282) self.Fail('deqp/functional/gles3/transformfeedback/' + 'interpolation_smooth.html', ['mac', 'amd'], bug=483282) self.Fail('deqp/functional/gles3/transformfeedback/' + 'point_size.html', ['mac', 'amd'], bug=483282) self.Fail('deqp/functional/gles3/transformfeedback/' + 'position.html', ['mac', 'amd'], bug=483282) self.Fail('deqp/functional/gles3/transformfeedback/' + 'random_interleaved_lines.html', ['mac', 'amd'], bug=483282) self.Fail('deqp/functional/gles3/transformfeedback/' + 'random_interleaved_points.html', ['mac', 'amd'], bug=483282) self.Fail('deqp/functional/gles3/transformfeedback/' + 'random_interleaved_triangles.html', ['mac', 'amd'], bug=483282) self.Fail('deqp/functional/gles3/transformfeedback/' + 'random_separate_lines.html', ['mac', 'amd'], bug=483282) self.Fail('deqp/functional/gles3/transformfeedback/' + 'random_separate_points.html', ['mac', 'amd'], bug=483282) self.Fail('deqp/functional/gles3/transformfeedback/' + 'random_separate_triangles.html', ['mac', 'amd'], bug=483282) self.Flaky('deqp/functional/gles3/shaderindexing/mat_00.html', ['mac', 'amd'], bug=751254) self.Flaky('deqp/functional/gles3/shaderindexing/mat_01.html', ['mac', 'amd'], bug=636648) self.Flaky('deqp/functional/gles3/shaderindexing/mat_02.html', ['mac', 'amd'], bug=644360) self.Flaky('deqp/functional/gles3/shaderindexing/tmp.html', ['mac', 'amd'], bug=659871) # These seem to be provoking intermittent GPU process crashes on # the MacBook Pros with AMD GPUs. self.Flaky('deqp/functional/gles3/texturefiltering/*', ['mac', 'amd'], bug=663601) self.Flaky('deqp/functional/gles3/textureshadow/*', ['mac', 'amd'], bug=663601) self.Flaky('deqp/functional/gles3/texturespecification/' + 'teximage2d_unpack_params.html', ['mac', 'amd'], bug=679058) self.Fail('conformance2/rendering/clipping-wide-points.html', ['mac', 'amd'], bug=642822) # Mac Intel self.Fail('conformance2/rendering/framebuffer-texture-level1.html', ['mac', 'intel'], bug=680278) self.Fail('conformance2/textures/misc/angle-stuck-depth-textures.html', ['mac', 'no_passthrough', 'intel'], bug=679692) self.Fail('deqp/functional/gles3/fbomultisample*', ['mac', 'intel'], bug=641209) self.Fail('deqp/functional/gles3/texturefiltering/2d_combinations_01.html', ['mac', 'intel'], bug=606074) self.Fail('deqp/functional/gles3/texturefiltering/' + 'cube_combinations_01.html', ['mac', 'intel'], bug=606074) self.Fail('deqp/functional/gles3/texturefiltering/' + '2d_array_combinations_01.html', ['mac', 'intel'], bug=606074) self.Fail('deqp/functional/gles3/texturefiltering/3d_combinations_06.html', ['mac', 'intel'], bug=606074) self.Fail('deqp/functional/gles3/texturefiltering/3d_combinations_07.html', ['mac', 'intel'], bug=606074) self.Fail('deqp/functional/gles3/texturefiltering/3d_combinations_08.html', ['mac', 'intel'], bug=606074) self.Fail('deqp/functional/gles3/texturespecification/' + 'random_teximage2d_2d.html', ['mac', 'intel'], bug=483282) self.Fail('deqp/functional/gles3/shadertexturefunction/' + 'texturelod.html', ['mac', 'intel'], bug=483282) self.Fail('deqp/functional/gles3/shadertexturefunction/' + 'texturegrad.html', ['mac', 'intel'], bug=483282) self.Fail('deqp/functional/gles3/shadertexturefunction/' + 'textureprojgrad.html', ['mac', 'intel'], bug=483282) self.Fail('conformance2/textures/canvas_sub_rectangle/' + 'tex-2d-r8ui-red_integer-unsigned_byte.html', ['yosemite', 'intel'], bug=665656) self.Fail('conformance2/textures/canvas_sub_rectangle/' + 'tex-2d-rg8ui-rg_integer-unsigned_byte.html', ['yosemite', 'intel'], bug=665656) self.Fail('conformance2/textures/canvas_sub_rectangle/' + 'tex-2d-rgb8ui-rgb_integer-unsigned_byte.html', ['yosemite', 'intel'], bug=665656) self.Fail('conformance2/textures/canvas_sub_rectangle/' + 'tex-2d-rgba8ui-rgba_integer-unsigned_byte.html', ['yosemite', 'intel'], bug=665656) self.Fail('conformance2/textures/image_data/' + 'tex-2d-rgba8ui-rgba_integer-unsigned_byte.html', ['mac', 'intel'], bug=665197) self.Fail('conformance2/textures/image_data/' + 'tex-2d-rgb8ui-rgb_integer-unsigned_byte.html', ['mac', 'intel'], bug=665197) self.Fail('conformance2/textures/image_data/' + 'tex-2d-rg8ui-rg_integer-unsigned_byte.html', ['mac', 'intel'], bug=665197) self.Fail('conformance2/textures/misc/' + 'integer-cubemap-texture-sampling.html', ['mac', 'intel'], bug=658930) self.Fail('conformance2/renderbuffers/' + 'multisampled-depth-renderbuffer-initialization.html', ['mac', 'intel'], bug=731877) # Linux only. self.Flaky('conformance/textures/video/' + 'tex-2d-rgba-rgba-unsigned_byte.html', ['linux'], bug=627525) self.Flaky('conformance/textures/video/' + 'tex-2d-rgba-rgba-unsigned_short_4_4_4_4.html', ['linux'], bug=627525) self.Flaky('conformance/textures/video/' + 'tex-2d-rgba-rgba-unsigned_short_5_5_5_1.html', ['linux'], bug=627525) self.Flaky('conformance/textures/video/' + 'tex-2d-rgb-rgb-unsigned_byte.html', ['linux'], bug=627525) self.Flaky('conformance/textures/video/' + 'tex-2d-rgb-rgb-unsigned_short_5_6_5.html', ['linux'], bug=627525) self.Fail('conformance2/glsl3/vector-dynamic-indexing-nv-driver-bug.html', ['linux'], bug=483282) self.Fail('conformance2/textures/image_bitmap_from_image/' + 'tex-3d-r16f-red-float.html', ['linux'], bug=679695) # Linux Multi-vendor failures. self.Skip('deqp/data/gles3/shaders/qualification_order.html', ['linux', 'amd', 'intel'], bug=483282) self.Flaky('deqp/functional/gles3/texturespecification/' + 'random_teximage2d_2d.html', ['linux', 'amd', 'intel'], bug=618447) self.Fail('conformance2/rendering/clipping-wide-points.html', ['linux', 'amd', 'intel'], bug=662644) # WebGL 2.0.1 # Linux NVIDIA # This test is flaky both with and without ANGLE. self.Flaky('deqp/functional/gles3/texturespecification/' + 'random_teximage2d_2d.html', ['linux', 'nvidia'], bug=618447) self.Fail('conformance/glsl/bugs/unary-minus-operator-float-bug.html', ['linux', 'nvidia'], bug=672380) self.Fail('conformance2/glsl3/vector-dynamic-indexing-swizzled-lvalue.html', ['linux', 'nvidia'], bug=709351) self.Fail('conformance2/textures/image_bitmap_from_canvas/' + 'tex-3d-srgb8_alpha8-rgba-unsigned_byte.html', ['linux', 'nvidia'], bug=679677) self.Fail('conformance2/rendering/framebuffer-texture-level1.html', ['linux', 'nvidia', 'opengl'], bug=680278) self.Fail('conformance2/rendering/multisampling-fragment-evaluation.html', ['linux', 'nvidia', 'no_passthrough'], bug=682815) self.Fail('conformance2/textures/image/' + 'tex-3d-rg8ui-rg_integer-unsigned_byte.html', ['linux', ('nvidia', 0xf02)], bug=680282) self.Flaky('conformance2/textures/image_bitmap_from_image_data/' + 'tex-2d-srgb8-rgb-unsigned_byte.html', ['linux', 'no_passthrough', 'nvidia'], bug=694354) # Linux NVIDIA Quadro P400 # This test causes a lost device and then the next test fails. self.Skip('conformance2/rendering/blitframebuffer-size-overflow.html', ['linux', ('nvidia', 0x1cb3)], bug=709320) # Failing reliably on tryservers. self.Fail('conformance2/offscreencanvas/' + 'offscreencanvas-transfer-image-bitmap.html', ['linux', ('nvidia', 0x1cb3)], bug=781418) # Observed flaky on Swarmed bots. Some of these were directly # observed, some not. We can't afford any flakes on the tryservers # so mark them all flaky. self.Flaky('deqp/functional/gles3/transformfeedback/' + 'array_interleaved_lines.html', ['linux', ('nvidia', 0x1cb3)], bug=780706) self.Flaky('deqp/functional/gles3/transformfeedback/' + 'array_interleaved_points.html', ['linux', ('nvidia', 0x1cb3)], bug=780706) self.Flaky('deqp/functional/gles3/transformfeedback/' + 'array_interleaved_triangles.html', ['linux', ('nvidia', 0x1cb3)], bug=780706) self.Flaky('deqp/functional/gles3/transformfeedback/' + 'array_separate_lines.html', ['linux', ('nvidia', 0x1cb3)], bug=780706) self.Flaky('deqp/functional/gles3/transformfeedback/' + 'array_separate_points.html', ['linux', ('nvidia', 0x1cb3)], bug=780706) self.Flaky('deqp/functional/gles3/transformfeedback/' + 'array_separate_triangles.html', ['linux', ('nvidia', 0x1cb3)], bug=780706) self.Flaky('deqp/functional/gles3/transformfeedback/' + 'basic_types_interleaved_lines.html', ['linux', ('nvidia', 0x1cb3)], bug=780706) self.Flaky('deqp/functional/gles3/transformfeedback/' + 'basic_types_interleaved_points.html', ['linux', ('nvidia', 0x1cb3)], bug=780706) self.Flaky('deqp/functional/gles3/transformfeedback/' + 'basic_types_interleaved_triangles.html', ['linux', ('nvidia', 0x1cb3)], bug=780706) self.Flaky('deqp/functional/gles3/transformfeedback/' + 'basic_types_separate_lines.html', ['linux', ('nvidia', 0x1cb3)], bug=780706) self.Flaky('deqp/functional/gles3/transformfeedback/' + 'basic_types_separate_points.html', ['linux', ('nvidia', 0x1cb3)], bug=780706) self.Flaky('deqp/functional/gles3/transformfeedback/' + 'basic_types_separate_triangles.html', ['linux', ('nvidia', 0x1cb3)], bug=780706) self.Flaky('deqp/functional/gles3/transformfeedback/' + 'interpolation_centroid.html', ['linux', ('nvidia', 0x1cb3)], bug=780706) self.Flaky('deqp/functional/gles3/transformfeedback/' + 'interpolation_flat.html', ['linux', ('nvidia', 0x1cb3)], bug=780706) self.Flaky('deqp/functional/gles3/transformfeedback/' + 'interpolation_smooth.html', ['linux', ('nvidia', 0x1cb3)], bug=780706) self.Flaky('deqp/functional/gles3/transformfeedback/' + 'point_size.html', ['linux', ('nvidia', 0x1cb3)], bug=780706) self.Flaky('deqp/functional/gles3/transformfeedback/' + 'position.html', ['linux', ('nvidia', 0x1cb3)], bug=780706) self.Flaky('deqp/functional/gles3/transformfeedback/' + 'random_interleaved_lines.html', ['linux', ('nvidia', 0x1cb3)], bug=780706) self.Flaky('deqp/functional/gles3/transformfeedback/' + 'random_interleaved_points.html', ['linux', ('nvidia', 0x1cb3)], bug=780706) self.Flaky('deqp/functional/gles3/transformfeedback/' + 'random_interleaved_triangles.html', ['linux', ('nvidia', 0x1cb3)], bug=780706) self.Flaky('deqp/functional/gles3/transformfeedback/' + 'random_separate_lines.html', ['linux', ('nvidia', 0x1cb3)], bug=780706) self.Flaky('deqp/functional/gles3/transformfeedback/' + 'random_separate_points.html', ['linux', ('nvidia', 0x1cb3)], bug=780706) self.Flaky('deqp/functional/gles3/transformfeedback/' + 'random_separate_triangles.html', ['linux', ('nvidia', 0x1cb3)], bug=780706) # Linux NVIDIA Quadro P400, OpenGL backend self.Fail('conformance/limits/gl-max-texture-dimensions.html', ['linux', ('nvidia', 0x1cb3)], bug=715001) self.Fail('conformance/textures/misc/texture-size.html', ['linux', ('nvidia', 0x1cb3), 'opengl'], bug=703779) self.Fail('conformance/extensions/webgl-compressed-texture-size-limit.html', ['linux', ('nvidia', 0x1cb3), 'opengl'], bug=703779) self.Fail('conformance/textures/misc/texture-size-limit.html', ['linux', ('nvidia', 0x1cb3), 'opengl'], bug=703779) self.Fail('deqp/functional/gles3/fbocompleteness.html', ['linux', ('nvidia', 0x1cb3), 'opengl'], bug=703779) # Linux Intel self.Fail('conformance2/extensions/ext-color-buffer-float.html', ['linux', 'intel'], bug=640389) self.Fail('WebglExtension_EXT_disjoint_timer_query_webgl2', ['linux', 'intel'], bug=687210) # See https://bugs.freedesktop.org/show_bug.cgi?id=94477 self.Skip('conformance/glsl/bugs/temp-expressions-should-not-crash.html', ['linux', 'intel'], bug=540543) # GPU timeout self.Fail('deqp/functional/gles3/fbomultisample.8_samples.html', ['linux', 'intel'], bug=635528) self.Fail('conformance2/textures/misc/tex-subimage3d-pixel-buffer-bug.html', ['linux', 'intel'], bug=662644) # WebGL 2.0.1 self.Fail('deqp/functional/gles3/shadertexturefunction/texturesize.html', ['linux', 'intel'], bug=666384) self.Fail('conformance2/textures/misc/tex-3d-mipmap-levels-intel-bug.html', ['linux', 'intel'], bug=666384) # Fails on Intel Mesa GL 3.3, passes on Intel Mesa GL 4.5. self.Fail('conformance2/misc/views-with-offsets.html', ['linux', 'intel', 'no_angle'], bug=664180) # Linux Intel with ANGLE only self.Fail('deqp/functional/gles3/framebufferblit/conversion_07.html', ['linux', 'intel', 'opengl'], bug=598902) self.Fail('conformance2/rendering/blitframebuffer-filter-srgb.html', ['linux', 'intel', 'opengl'], bug=680276) self.Fail('conformance2/rendering/blitframebuffer-outside-readbuffer.html', ['linux', 'intel', 'opengl'], bug=680276) # Linux Intel HD 530 self.Fail('conformance/extensions/webgl-compressed-texture-astc.html', ['linux', 'intel'], bug=680720) self.Fail('conformance2/rendering/blitframebuffer-filter-outofbounds.html', ['linux', 'no_passthrough', 'intel'], bug=680720) self.Fail('conformance2/rendering/blitframebuffer-filter-srgb.html', ['linux', 'intel', 'no_angle'], bug=680720) self.Fail('conformance2/rendering/blitframebuffer-outside-readbuffer.html', ['linux', 'intel', 'no_angle'], bug=680720) self.Fail('deqp/functional/gles3/framebufferblit/conversion_04.html', ['linux', 'intel'], bug=680720) self.Fail('deqp/functional/gles3/framebufferblit/conversion_08.html', ['linux', 'intel'], bug=680720) self.Fail('deqp/functional/gles3/framebufferblit/conversion_10.html', ['linux', 'intel'], bug=680720) self.Fail('deqp/functional/gles3/framebufferblit/conversion_11.html', ['linux', 'intel'], bug=680720) self.Fail('deqp/functional/gles3/framebufferblit/conversion_12.html', ['linux', 'intel'], bug=680720) self.Fail('deqp/functional/gles3/framebufferblit/conversion_13.html', ['linux', 'intel'], bug=680720) self.Fail('deqp/functional/gles3/framebufferblit/conversion_18.html', ['linux', 'intel'], bug=680720) self.Fail('deqp/functional/gles3/framebufferblit/conversion_25.html', ['linux', 'intel'], bug=680720) self.Fail('deqp/functional/gles3/framebufferblit/conversion_28.html', ['linux', 'intel'], bug=680720) self.Fail('deqp/functional/gles3/framebufferblit/conversion_29.html', ['linux', 'intel'], bug=680720) self.Fail('deqp/functional/gles3/framebufferblit/conversion_30.html', ['linux', 'intel'], bug=680720) self.Fail('deqp/functional/gles3/framebufferblit/conversion_31.html', ['linux', 'intel'], bug=680720) self.Fail('deqp/functional/gles3/framebufferblit/conversion_32.html', ['linux', 'intel'], bug=680720) self.Fail('deqp/functional/gles3/framebufferblit/conversion_33.html', ['linux', 'intel'], bug=680720) self.Fail('deqp/functional/gles3/framebufferblit/conversion_34.html', ['linux', 'intel'], bug=680720) self.Fail('deqp/functional/gles3/framebufferblit/' + 'default_framebuffer_00.html', ['linux', 'intel'], bug=680720) self.Fail('conformance2/glsl3/' + 'vector-dynamic-indexing-swizzled-lvalue.html', ['linux', 'intel'], bug=709874) # Linux Intel HD 630 self.Fail('conformance/textures/misc/texture-size-limit.html', ['linux', ('intel', 0x5912)], bug=745888) # Linux AMD only. # It looks like AMD shader compiler rejects many valid ES3 semantics. self.Fail('conformance2/attribs/gl-vertex-attrib-normalized-int.html', ['linux', 'amd'], bug=766776) self.Fail('conformance/glsl/misc/shaders-with-invariance.html', ['linux', 'amd'], bug=483282) self.Fail('conformance2/glsl3/vector-dynamic-indexing-swizzled-lvalue.html', ['linux', 'amd'], bug=709351) self.Fail('deqp/functional/gles3/multisample.html', ['linux', 'amd'], bug=617290) self.Fail('deqp/data/gles3/shaders/conversions.html', ['linux', 'amd'], bug=483282) self.Skip('deqp/data/gles3/shaders/arrays.html', ['linux', 'amd'], bug=483282) self.Fail('deqp/functional/gles3/internalformatquery.html', ['linux', 'amd'], bug=483282) self.Fail('deqp/functional/gles3/texturestatequery.html', ['linux', 'amd'], bug=483282) self.Fail('deqp/functional/gles3/buffercopy.html', ['linux', 'amd'], bug=483282) self.Fail('deqp/functional/gles3/samplerobject.html', ['linux', 'amd'], bug=483282) self.Fail('deqp/functional/gles3/shaderprecision_int.html', ['linux', 'amd'], bug=483282) self.Fail('deqp/functional/gles3/texturefiltering/3d*', ['linux', 'amd'], bug=606114) self.Fail('deqp/functional/gles3/shadertexturefunction/texture.html', ['linux', 'amd'], bug=483282) self.Fail('deqp/functional/gles3/shadertexturefunction/texturegrad.html', ['linux', 'amd'], bug=483282) self.Fail('deqp/functional/gles3/shadertexturefunction/' + 'texelfetchoffset.html', ['linux', 'amd'], bug=483282) self.Fail('deqp/functional/gles3/vertexarrays/' + 'single_attribute.first.html', ['linux', 'amd'], bug=694877) self.Fail('deqp/functional/gles3/negativetextureapi.html', ['linux', 'amd'], bug=483282) self.Fail('deqp/functional/gles3/transformfeedback/array_separate*.html', ['linux', 'amd'], bug=483282) self.Fail('conformance2/misc/uninitialized-test-2.html', ['linux', 'no_passthrough', 'amd'], bug=483282) self.Fail('conformance2/reading/read-pixels-from-fbo-test.html', ['linux', 'amd'], bug=483282) self.Fail('conformance2/rendering/blitframebuffer-filter-srgb.html', ['linux', 'amd'], bug=634525) self.Fail('conformance2/rendering/blitframebuffer-outside-readbuffer.html', ['linux', 'amd'], bug=662644) # WebGL 2.0.1 self.Fail('conformance2/renderbuffers/framebuffer-texture-layer.html', ['linux', 'amd'], bug=295792) self.Fail('conformance2/textures/misc/tex-mipmap-levels.html', ['linux', 'amd'], bug=483282) self.Fail('conformance2/textures/misc/copy-texture-image-luma-format.html', ['linux', 'amd'], bug=483282) self.Fail('deqp/functional/gles3/texturespecification/' + 'teximage2d_pbo_cube_00.html', ['linux', 'amd'], bug=483282) self.Fail('deqp/functional/gles3/texturespecification/' + 'teximage2d_pbo_cube_01.html', ['linux', 'amd'], bug=483282) self.Fail('deqp/functional/gles3/texturespecification/' + 'teximage2d_pbo_cube_02.html', ['linux', 'amd'], bug=483282) self.Fail('deqp/functional/gles3/texturespecification/' + 'teximage2d_pbo_cube_03.html', ['linux', 'amd'], bug=483282) self.Fail('deqp/functional/gles3/texturespecification/' + 'teximage2d_pbo_cube_04.html', ['linux', 'amd'], bug=483282) self.Fail('deqp/functional/gles3/texturespecification/' + 'teximage2d_pbo_params.html', ['linux', 'amd'], bug=483282) self.Fail('deqp/functional/gles3/texturespecification/' + 'teximage2d_depth_pbo.html', ['linux', 'amd'], bug=483282) self.Fail('deqp/functional/gles3/texturespecification/' + 'basic_copyteximage2d.html', ['linux', 'amd'], bug=483282) self.Fail('deqp/functional/gles3/texturespecification/' + 'basic_teximage3d_3d_00.html', ['linux', 'amd'], bug=483282) self.Fail('deqp/functional/gles3/texturespecification/' + 'basic_teximage3d_3d_01.html', ['linux', 'amd'], bug=483282) self.Fail('deqp/functional/gles3/texturespecification/' + 'basic_teximage3d_3d_02.html', ['linux', 'amd'], bug=483282) self.Fail('deqp/functional/gles3/texturespecification/' + 'basic_teximage3d_3d_03.html', ['linux', 'amd'], bug=483282) self.Fail('deqp/functional/gles3/texturespecification/' + 'basic_teximage3d_3d_04.html', ['linux', 'amd'], bug=483282) self.Fail('deqp/functional/gles3/texturespecification/' + 'texstorage2d_format_depth_stencil.html', ['linux', 'amd'], bug=483282) self.Fail('deqp/functional/gles3/texturespecification/' + 'texstorage3d_format_2d_array_00.html', ['linux', 'amd'], bug=483282) self.Fail('deqp/functional/gles3/texturespecification/' + 'texstorage3d_format_2d_array_01.html', ['linux', 'amd'], bug=483282) self.Fail('deqp/functional/gles3/texturespecification/' + 'texstorage3d_format_2d_array_02.html', ['linux', 'amd'], bug=483282) self.Fail('deqp/functional/gles3/texturespecification/' + 'texstorage3d_format_3d_00.html', ['linux', 'amd'], bug=483282) self.Fail('deqp/functional/gles3/texturespecification/' + 'texstorage3d_format_3d_01.html', ['linux', 'amd'], bug=483282) self.Fail('deqp/functional/gles3/texturespecification/' + 'texstorage3d_format_3d_02.html', ['linux', 'amd'], bug=483282) self.Fail('deqp/functional/gles3/texturespecification/' + 'texstorage3d_format_3d_03.html', ['linux', 'amd'], bug=483282) self.Fail('deqp/functional/gles3/texturespecification/' + 'texstorage3d_format_depth_stencil.html', ['linux', 'amd'], bug=483282) self.Fail('deqp/functional/gles3/texturespecification/' + 'texstorage3d_format_size.html', ['linux', 'amd'], bug=483282) self.Fail('deqp/functional/gles3/vertexarrays/' + 'single_attribute.output_type.unsigned_int.html', ['linux', 'amd'], bug=483282) self.Fail('deqp/functional/gles3/draw/*.html', ['linux', 'amd'], bug=483282) self.Fail('deqp/functional/gles3/fbomultisample*', ['linux', 'amd'], bug=483282) self.Fail('deqp/functional/gles3/fbocompleteness.html', ['linux', 'amd'], bug=483282) self.Fail('deqp/functional/gles3/textureshadow/*.html', ['linux', 'amd'], bug=483282) self.Fail('deqp/functional/gles3/shadermatrix/mul_dynamic_highp.html', ['linux', 'amd'], bug=483282) self.Fail('deqp/functional/gles3/shadermatrix/mul_dynamic_lowp.html', ['linux', 'amd'], bug=483282) self.Fail('deqp/functional/gles3/shadermatrix/mul_dynamic_mediump.html', ['linux', 'amd'], bug=483282) self.Fail('deqp/functional/gles3/shadermatrix/pre_decrement.html', ['linux', 'amd'], bug=483282) self.Fail('deqp/functional/gles3/framebufferblit/conversion_04.html', ['linux', 'amd'], bug=483282) self.Fail('deqp/functional/gles3/framebufferblit/conversion_07.html', ['linux', 'amd'], bug=483282) self.Fail('deqp/functional/gles3/framebufferblit/conversion_08.html', ['linux', 'amd'], bug=483282) self.Fail('deqp/functional/gles3/framebufferblit/conversion_10.html', ['linux', 'amd'], bug=483282) self.Fail('deqp/functional/gles3/framebufferblit/conversion_11.html', ['linux', 'amd'], bug=483282) self.Fail('deqp/functional/gles3/framebufferblit/conversion_12.html', ['linux', 'amd'], bug=483282) self.Fail('deqp/functional/gles3/framebufferblit/conversion_13.html', ['linux', 'amd'], bug=483282) self.Fail('deqp/functional/gles3/framebufferblit/conversion_18.html', ['linux', 'amd'], bug=483282) self.Fail('deqp/functional/gles3/framebufferblit/conversion_25.html', ['linux', 'amd'], bug=483282) self.Fail('deqp/functional/gles3/framebufferblit/conversion_28.html', ['linux', 'amd'], bug=483282) self.Fail('deqp/functional/gles3/framebufferblit/conversion_29.html', ['linux', 'amd'], bug=483282) self.Fail('deqp/functional/gles3/framebufferblit/conversion_30.html', ['linux', 'amd'], bug=483282) self.Fail('deqp/functional/gles3/framebufferblit/conversion_31.html', ['linux', 'amd'], bug=483282) self.Fail('deqp/functional/gles3/framebufferblit/conversion_32.html', ['linux', 'amd'], bug=483282) self.Fail('deqp/functional/gles3/framebufferblit/conversion_33.html', ['linux', 'amd'], bug=483282) self.Fail('deqp/functional/gles3/framebufferblit/conversion_34.html', ['linux', 'amd'], bug=483282) self.Fail('deqp/functional/gles3/framebufferblit/' + 'default_framebuffer_00.html', ['linux', 'amd'], bug=658832) self.Fail('deqp/functional/gles3/shaderoperator/unary_operator_01.html', ['linux', 'amd'], bug=483282) self.Fail('deqp/functional/gles3/shaderoperator/unary_operator_02.html', ['linux', 'amd'], bug=483282) self.Fail('conformance2/glsl3/vector-dynamic-indexing.html', ['linux', 'amd'], bug=483282) self.Fail('conformance2/reading/read-pixels-pack-parameters.html', ['linux', 'amd', 'no_angle'], bug=483282) self.Fail('conformance2/textures/misc/tex-unpack-params.html', ['linux', 'amd', 'no_angle'], bug=483282) # TODO(kbr): re-enable after next conformance roll. crbug.com/736499 # self.Fail('conformance2/extensions/ext-color-buffer-float.html', # ['linux', 'amd'], bug=633022) self.Fail('conformance2/rendering/blitframebuffer-filter-outofbounds.html', ['linux', 'no_passthrough', 'amd'], bug=655147) self.Fail('conformance2/textures/misc/tex-base-level-bug.html', ['linux', 'amd'], bug=705865) self.Fail('conformance2/textures/image/' + 'tex-2d-r11f_g11f_b10f-rgb-float.html', ['linux', 'amd'], bug=705865) # Uniform buffer related failures self.Fail('deqp/functional/gles3/uniformbuffers/single_struct_array.html', ['linux', 'amd'], bug=483282) self.Fail('deqp/functional/gles3/uniformbuffers/single_nested_struct.html', ['linux', 'amd'], bug=483282) self.Fail('deqp/functional/gles3/uniformbuffers/' + 'single_nested_struct_array.html', ['linux', 'amd'], bug=483282) self.Fail('deqp/functional/gles3/uniformbuffers/multi_basic_types.html', ['linux', 'amd'], bug=483282) self.Fail('deqp/functional/gles3/uniformbuffers/multi_nested_struct.html', ['linux', 'amd'], bug=483282) self.Fail('deqp/functional/gles3/uniformbuffers/random.html', ['linux', 'amd'], bug=483282) self.Fail('conformance2/buffers/uniform-buffers.html', ['linux', 'amd'], bug=658842) self.Fail('conformance2/rendering/uniform-block-buffer-size.html', ['linux', 'amd'], bug=658844) self.Fail('conformance2/uniforms/uniform-blocks-with-arrays.html', ['linux', 'amd'], bug=2103) # angle bug ID # Linux AMD R7 240 self.Fail('conformance2/textures/canvas/' + 'tex-2d-rg8ui-rg_integer-unsigned_byte.html', ['linux', ('amd', 0x6613)], bug=710392) self.Fail('conformance2/textures/canvas/' + 'tex-2d-rgb8ui-rgb_integer-unsigned_byte.html', ['linux', ('amd', 0x6613)], bug=710392) self.Fail('conformance2/textures/canvas/' + 'tex-2d-rgba8ui-rgba_integer-unsigned_byte.html', ['linux', ('amd', 0x6613)], bug=710392) self.Fail('conformance2/textures/webgl_canvas/' + 'tex-2d-rg8ui-rg_integer-unsigned_byte.html', ['linux', ('amd', 0x6613)], bug=710392) self.Fail('conformance2/textures/webgl_canvas/' + 'tex-2d-rgb8ui-rgb_integer-unsigned_byte.html', ['linux', ('amd', 0x6613)], bug=710392) self.Fail('conformance2/textures/webgl_canvas/' + 'tex-2d-rgba8ui-rgba_integer-unsigned_byte.html', ['linux', ('amd', 0x6613)], bug=710392) self.Fail('conformance2/textures/image_bitmap_from_video/' + 'tex-2d-rgba16f-rgba-float.html', ['linux', ('amd', 0x6613)], bug=701138) self.Fail('conformance2/textures/image_bitmap_from_video/' + 'tex-2d-rgba16f-rgba-half_float.html', ['linux', ('amd', 0x6613)], bug=701138) self.Fail('conformance2/textures/image_bitmap_from_video/' + 'tex-2d-rgba32f-rgba-float.html', ['linux', ('amd', 0x6613)], bug=701138) self.Fail('conformance2/textures/image_bitmap_from_video/' + 'tex-2d-rgba4-rgba-unsigned_byte.html', ['linux', ('amd', 0x6613)], bug=701138) self.Fail('conformance2/textures/image_bitmap_from_video/' + 'tex-2d-rgba4-rgba-unsigned_short_4_4_4_4.html', ['linux', ('amd', 0x6613)], bug=701138) self.Fail('conformance2/textures/image_data/' + 'tex-3d-rgb32f-rgb-float.html', ['linux', ('amd', 0x6613)], bug=701138) self.Fail('conformance2/textures/image_data/' + 'tex-3d-rgb565-rgb-unsigned_byte.html', ['linux', ('amd', 0x6613)], bug=701138) self.Fail('conformance2/textures/image_data/' + 'tex-3d-rgb565-rgb-unsigned_short_5_6_5.html', ['linux', ('amd', 0x6613)], bug=701138) self.Fail('conformance2/textures/image_data/' + 'tex-3d-rgb5_a1-rgba-unsigned_byte.html', ['linux', ('amd', 0x6613)], bug=701138) # Conflicting expectations to test that the # "Expectations have no collisions" unittest works. # page_name = 'conformance/glsl/constructors/glsl-construct-ivec4.html' # Conflict when all conditions match # self.Fail(page_name, # ['linux', ('nvidia', 0x1), 'debug', 'opengl']) # self.Fail(page_name, # ['linux', ('nvidia', 0x1), 'debug', 'opengl']) # Conflict when all conditions match (and different sets) # self.Fail(page_name, # ['linux', 'win', ('nvidia', 0x1), 'debug', 'opengl']) # self.Fail(page_name, # ['linux', 'mac', ('nvidia', 0x1), 'amd', 'debug', 'opengl']) # Conflict with one aspect not specified # self.Fail(page_name, # ['linux', ('nvidia', 0x1), 'debug']) # self.Fail(page_name, # ['linux', ('nvidia', 0x1), 'debug', 'opengl']) # Conflict with one aspect not specified (in both conditions) # self.Fail(page_name, # ['linux', ('nvidia', 0x1), 'debug']) # self.Fail(page_name, # ['linux', ('nvidia', 0x1), 'debug']) # Conflict even if the GPU is specified in a device ID # self.Fail(page_name, # ['linux', ('nvidia', 0x1), 'debug']) # self.Fail(page_name, # ['linux', 'nvidia', 'debug']) # Test there are no conflicts between two different devices # self.Fail(page_name, # ['linux', ('nvidia', 0x1), 'debug']) # self.Fail(page_name, # ['linux', ('nvidia', 0x2), 'debug']) # Test there are no conflicts between two devices with different vendors # self.Fail(page_name, # ['linux', ('nvidia', 0x1), 'debug']) # self.Fail(page_name, # ['linux', ('amd', 0x1), 'debug']) # Conflicts if there is a device and nothing specified for the other's # GPU vendors # self.Fail(page_name, # ['linux', ('nvidia', 0x1), 'debug']) # self.Fail(page_name, # ['linux', 'debug']) # Test no conflicts happen when only one aspect differs # self.Fail(page_name, # ['linux', ('nvidia', 0x1), 'debug', 'opengl']) # self.Fail(page_name, # ['win', ('nvidia', 0x1), 'debug', 'opengl']) # Conflicts if between a generic os condition and a specific version # self.Fail(page_name, # ['xp', ('nvidia', 0x1), 'debug', 'opengl']) # self.Fail(page_name, # ['win', ('nvidia', 0x1), 'debug', 'opengl'])
[ "commit-bot@chromium.org" ]
commit-bot@chromium.org
384f3ca83686eef79fb68f6e221c15a8ea737f27
378eea7cbb49d52c13c3bd0bb86bc93fc93d3d56
/100Days/Day09/association.py
e4427897296525d11fbe292a810fcbc0d800bb87
[]
no_license
Zpadger/Python
b9e54524841e14d05e8f52b829c8c99c91e308b8
f13da6d074afac50396621c9df780bf5ca30ce6b
refs/heads/master
2020-08-16T01:10:00.534615
2020-04-12T15:15:53
2020-04-12T15:15:53
172,426,365
0
0
null
null
null
null
UTF-8
Python
false
false
1,200
py
# 对象之间的关联关系 from math import sqrt class Point(object): def __init__(self,x=0,y=0): self._x = x self._y = y def move_to(self,x,y): self._x = x self._y = y def move_by(self,dx,dy): self._x += dx self._y += dy def distance_to(self,other): dx = self._x - other._x dy = self._y - other._y return sqrt(dx**2 + dy**2) def __str__(self): return '(%s,%s)' % (str(self._x),str(self._y)) class Line(object): def __init__(self,start=Point(0,0),end=Point(0,0)): self._start = start self._end = end @property def start(self): return self._start @start.setter def start(self,start): self._start = start @property def end(self): return self.end @end.setter def end(self,end): self._end = end @property def length(self): return self._start.distance_to(self._end) if __name__ == '__main__': p1 = Point(3,5) print(p1) p2 = Point(-2,-1.5) print(p2) line = Line(p1,p2) print(line.length) line.start.move_to(2,1) line.end = Point(1,2) print(line.length)
[ "noreply@github.com" ]
Zpadger.noreply@github.com
150bd3e4db5e34c9c6a5a472b6d587f94ba3da8b
f4c36d1b5946ad0145d10164c40ee0635903accb
/tech/backends.py
8dc3b9c98fd6278f45344b25513c7308e64331de
[]
no_license
Vivekdjango/techstop
69c2edec92ef9b0e7318b908c8cf8044c5d7dfa2
1c0a0b992136a129a0d4226ee1ae691cd0a91ae4
refs/heads/master
2021-01-11T17:59:29.690837
2018-09-01T13:12:52
2018-09-01T13:12:52
79,893,964
0
0
null
null
null
null
UTF-8
Python
false
false
1,070
py
from django.contrib.auth.models import User class SSOLoginBackend(object): """ This is a transparent authentication backend for SSO login. Assumes that a user was authenticated using SSO prior to this class getting invoked. """ def authenticate(self, username, password=None, email=None): user = None try: user = User.objects.get(username=username) except User.DoesNotExist: # Create a new user. Note that we can set password # to anything, because it won't be checked; the password # from settings.py will. if password is None: password = User.objects.make_random_password(length=25) user = User(username=username, password=password) user.is_staff = False user.is_superuser = False user.email = email user.save() return user def get_user(self, user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None
[ "viveksinha@IC0532-L0.corp.inmobi.com" ]
viveksinha@IC0532-L0.corp.inmobi.com
56634d05aee2bed2e41d18af1cf186dd65351abc
495b0b8de3ecc341511cdb10f11368b35b585bea
/SoftLayer/tests/API/client_tests.py
072167957ea42bfb0b22cb6bcf7d0b568893c2cd
[]
no_license
hugomatic/softlayer-api-python-client
cf6c1e6bfa32e559e72f8b0b069339ae8edd2ede
9c115f0912ee62763b805941593f6dd50de37068
refs/heads/master
2021-01-18T11:09:19.122162
2013-04-09T01:44:51
2013-04-09T01:44:51
null
0
0
null
null
null
null
UTF-8
Python
false
false
12,592
py
""" SoftLayer.tests.API.client_tests ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2013, SoftLayer Technologies, Inc. All rights reserved. :license: BSD, see LICENSE for more details. """ try: import unittest2 as unittest except ImportError: import unittest # NOQA from mock import patch, MagicMock, call import SoftLayer import SoftLayer.API from SoftLayer.consts import USER_AGENT class Inititialization(unittest.TestCase): def test_init(self): client = SoftLayer.Client('SoftLayer_User_Customer', username='doesnotexist', api_key='issurelywrong', timeout=10) self.assertEquals(client._service_name, 'SoftLayer_User_Customer') self.assertEquals(client._headers, { 'authenticate': { 'username': 'doesnotexist', 'apiKey': 'issurelywrong' } }) self.assertEquals(client._endpoint_url, SoftLayer.API_PUBLIC_ENDPOINT.rstrip('/')) def test_init_w_id(self): client = SoftLayer.Client('SoftLayer_User_Customer', 1, 'doesnotexist', 'issurelywrong') self.assertEquals(client._headers, { 'SoftLayer_User_CustomerInitParameters': {'id': 1}, 'authenticate': { 'username': 'doesnotexist', 'apiKey': 'issurelywrong'}}) @patch.dict('os.environ', { 'SL_USERNAME': 'test_user', 'SL_API_KEY': 'test_api_key'}) def test_env(self): client = SoftLayer.Client() self.assertEquals(client._headers, { 'authenticate': { 'username': 'test_user', 'apiKey': 'test_api_key'}}) @patch('SoftLayer.API.API_USERNAME', 'test_user') @patch('SoftLayer.API.API_KEY', 'test_api_key') def test_globals(self): client = SoftLayer.Client() self.assertEquals(client._headers, { 'authenticate': { 'username': 'test_user', 'apiKey': 'test_api_key'}}) class ClientMethods(unittest.TestCase): def test_help(self): help(SoftLayer) help(SoftLayer.Client) client = SoftLayer.Client( username='doesnotexist', api_key='issurelywrong' ) help(client) help(client['SERVICE']) def test_set_raw_header_old(self): client = SoftLayer.Client( username='doesnotexist', api_key='issurelywrong' ) client.transport = MagicMock() client.add_raw_header("RAW", "HEADER") self.assertEquals(client._raw_headers, {'RAW': 'HEADER'}) def test_add_header_invalid(self): client = SoftLayer.Client( username='doesnotexist', api_key='issurelywrong' ) client.transport = MagicMock() self.assertRaises(SoftLayer.SoftLayerError, client.add_header, "", "HEADER") def test_remove_header(self): client = SoftLayer.Client( username='doesnotexist', api_key='issurelywrong' ) client.remove_header("authenticate") self.assertNotIn("authenticate", client._headers) def test_repr(self): client = SoftLayer.Client( username='doesnotexist', api_key='issurelywrong' ) self.assertIn("Client", repr(client)) def test_service_repr(self): client = SoftLayer.Client( username='doesnotexist', api_key='issurelywrong' ) self.assertIn("Service", repr(client['SERVICE'])) class APICalls(unittest.TestCase): def setUp(self): self.client = SoftLayer.Client( username='doesnotexist', api_key='issurelywrong', endpoint_url="ENDPOINT") @patch('SoftLayer.API.make_api_call') def test_old_api(self, make_api_call): client = SoftLayer.API.Client( 'SoftLayer_SERVICE', None, 'doesnotexist', 'issurelywrong', endpoint_url="ENDPOINT") client.METHOD() make_api_call.assert_called_with( 'ENDPOINT/SoftLayer_SERVICE', 'METHOD', (), headers={ 'authenticate': { 'username': 'doesnotexist', 'apiKey': 'issurelywrong'}}, verbose=False, timeout=None, http_headers={ 'Content-Type': 'application/xml', 'User-Agent': USER_AGENT, }) @patch('SoftLayer.API.make_api_call') def test_complex_old_api(self, make_api_call): client = SoftLayer.API.Client( 'SoftLayer_SERVICE', None, 'doesnotexist', 'issurelywrong', endpoint_url="ENDPOINT") client.set_result_limit(9, offset=10) client.set_object_mask({'object': {'attribute': ''}}) client.add_raw_header("RAW", "HEADER") client.METHOD( 1234, id=5678, mask={'object': {'attribute': ''}}, filter={ 'TYPE': {'obj': {'attribute': {'operation': '^= prefix'}}}}, limit=9, offset=10) make_api_call.assert_called_with( 'ENDPOINT/SoftLayer_SERVICE', 'METHOD', (1234, ), headers={ 'SoftLayer_SERVICEObjectMask': { 'mask': {'object': {'attribute': ''}}}, 'SoftLayer_SERVICEObjectFilter': { 'TYPE': { 'obj': {'attribute': {'operation': '^= prefix'}}}}, 'authenticate': { 'username': 'doesnotexist', 'apiKey': 'issurelywrong'}, 'SoftLayer_SERVICEInitParameters': {'id': 5678}, 'resultLimit': {'limit': 9, 'offset': 10}}, verbose=False, timeout=None, http_headers={ 'RAW': 'HEADER', 'Content-Type': 'application/xml', 'User-Agent': USER_AGENT, }) def test_old_api_no_service(self): client = SoftLayer.Client(username='doesnotexist', api_key='issurelywrong') self.assertRaises(SoftLayer.SoftLayerError, client.METHOD) @patch('SoftLayer.API.make_api_call') def test_simple_call(self, make_api_call): self.client['SERVICE'].METHOD() make_api_call.assert_called_with( 'ENDPOINT/SoftLayer_SERVICE', 'METHOD', (), headers={ 'authenticate': { 'username': 'doesnotexist', 'apiKey': 'issurelywrong'}}, verbose=False, timeout=None, http_headers={ 'Content-Type': 'application/xml', 'User-Agent': USER_AGENT, }) @patch('SoftLayer.API.make_api_call') def test_complex(self, make_api_call): self.client['SERVICE'].METHOD( 1234, id=5678, mask={'object': {'attribute': ''}}, raw_headers={'RAW': 'HEADER'}, filter={ 'TYPE': {'obj': {'attribute': {'operation': '^= prefix'}}}}, limit=9, offset=10) make_api_call.assert_called_with( 'ENDPOINT/SoftLayer_SERVICE', 'METHOD', (1234, ), headers={ 'SoftLayer_SERVICEObjectMask': { 'mask': {'object': {'attribute': ''}}}, 'SoftLayer_SERVICEObjectFilter': { 'TYPE': { 'obj': {'attribute': {'operation': '^= prefix'}}}}, 'authenticate': { 'username': 'doesnotexist', 'apiKey': 'issurelywrong'}, 'SoftLayer_SERVICEInitParameters': {'id': 5678}, 'resultLimit': {'limit': 9, 'offset': 10}}, verbose=False, timeout=None, http_headers={ 'RAW': 'HEADER', 'Content-Type': 'application/xml', 'User-Agent': USER_AGENT, }) @patch('SoftLayer.API.make_api_call') def test_mask_call_v2(self, make_api_call): self.client['SERVICE'].METHOD( mask="mask[something[nested]]") make_api_call.assert_called_with( 'ENDPOINT/SoftLayer_SERVICE', 'METHOD', (), headers={ 'authenticate': { 'username': 'doesnotexist', 'apiKey': 'issurelywrong'}, 'SoftLayer_ObjectMask': {'mask': 'mask[something[nested]]'}}, verbose=False, timeout=None, http_headers={ 'Content-Type': 'application/xml', 'User-Agent': USER_AGENT, }) @patch('SoftLayer.API.make_api_call') def test_mask_call_v2_dot(self, make_api_call): self.client['SERVICE'].METHOD( mask="mask.something.nested") make_api_call.assert_called_with( 'ENDPOINT/SoftLayer_SERVICE', 'METHOD', (), headers={ 'authenticate': { 'username': 'doesnotexist', 'apiKey': 'issurelywrong'}, 'SoftLayer_ObjectMask': {'mask': 'mask[something.nested]'}}, verbose=False, timeout=None, http_headers={ 'Content-Type': 'application/xml', 'User-Agent': USER_AGENT, }) @patch('SoftLayer.API.make_api_call') def test_mask_call_invalid_mask(self, make_api_call): try: self.client['SERVICE'].METHOD(mask="mask[something.nested") except SoftLayer.SoftLayerError, e: self.assertIn('Malformed Mask', str(e)) else: self.fail('No exception raised') @patch('SoftLayer.API.Client.iter_call') def test_iterate(self, _iter_call): self.client['SERVICE'].METHOD(iter=True) _iter_call.assert_called_with('SERVICE', 'METHOD', iter=True) @patch('SoftLayer.API.Client.iter_call') def test_service_iter_call(self, _iter_call): self.client['SERVICE'].iter_call('METHOD') _iter_call.assert_called_with('SERVICE', 'METHOD') @patch('SoftLayer.API.Client.call') def test_iter_call(self, _call): # chunk=100, no limit _call.side_effect = [range(100), range(100, 125)] result = list(self.client.iter_call('SERVICE', 'METHOD', iter=True)) self.assertEquals(range(125), result) _call.assert_has_calls([ call('SERVICE', 'METHOD', limit=100, iter=False, offset=0), call('SERVICE', 'METHOD', limit=100, iter=False, offset=100), ]) _call.reset_mock() # chunk=100, no limit. Requires one extra request. _call.side_effect = [range(100), range(100, 200), []] result = list(self.client.iter_call('SERVICE', 'METHOD', iter=True)) self.assertEquals(range(200), result) _call.assert_has_calls([ call('SERVICE', 'METHOD', limit=100, iter=False, offset=0), call('SERVICE', 'METHOD', limit=100, iter=False, offset=100), call('SERVICE', 'METHOD', limit=100, iter=False, offset=200), ]) _call.reset_mock() # chunk=25, limit=30 _call.side_effect = [range(0, 25), range(25, 30)] result = list(self.client.iter_call( 'SERVICE', 'METHOD', iter=True, limit=30, chunk=25)) self.assertEquals(range(30), result) _call.assert_has_calls([ call('SERVICE', 'METHOD', iter=False, limit=25, offset=0), call('SERVICE', 'METHOD', iter=False, limit=5, offset=25), ]) _call.reset_mock() # A non-list was returned _call.side_effect = ["test"] result = list(self.client.iter_call('SERVICE', 'METHOD', iter=True)) self.assertEquals(["test"], result) _call.assert_has_calls([ call('SERVICE', 'METHOD', iter=False, limit=100, offset=0), ]) _call.reset_mock() # chunk=25, limit=30, offset=12 _call.side_effect = [range(0, 25), range(25, 30)] result = list(self.client.iter_call( 'SERVICE', 'METHOD', iter=True, limit=30, chunk=25, offset=12)) self.assertEquals(range(30), result) _call.assert_has_calls([ call('SERVICE', 'METHOD', iter=False, limit=25, offset=12), call('SERVICE', 'METHOD', iter=False, limit=5, offset=37), ]) # Chunk size of 0 is invalid self.assertRaises( AttributeError, lambda: list(self.client.iter_call( 'SERVICE', 'METHOD', iter=True, chunk=0)))
[ "k3vinmcdonald@gmail.com" ]
k3vinmcdonald@gmail.com
ad853f1c5462f8be2b4c54a9aaf79b67efdb2435
ec546fe9c41a1bc4bc5bf39d939f1cbf0382a7ee
/dashboard/email_sender_smtp.py
e422c15eebcc1279bf7fd70488fa30c663a1f46e
[]
no_license
MaxOvcharov/Python_for_DevOps
3910fd1cced9f07139f8709b453693f937d7216d
03a5f737bb1c2f53713803a7794c04d134a596b0
refs/heads/master
2020-06-13T00:56:06.704476
2017-09-05T19:10:19
2017-09-05T19:10:19
75,471,789
0
0
null
null
null
null
UTF-8
Python
false
false
568
py
# -*- coding: utf-8 -*- import smtplib mail_server = "smtp.rambler.ru" mail_server_port = 465 from_addr = 'EMAIL_FROM' to_addr = 'EMAIL_TO' from_header = 'From: %s\r\n' % from_addr to_header = 'To: %s\r\n\r\n' % to_addr subject_header = 'Subject: Testing SMTP Authentication' body = 'This mail tests SMTP Authentication' email_message = '%s\n%s\n%s\n\n%s' % (from_header, to_header, subject_header, body) s = smtplib.SMTP_SSL(mail_server, mail_server_port) s.set_debuglevel(1) s.login('EMAIL', 'PASSWORD') s.sendmail(from_addr, to_addr, email_message) s.quit()
[ "ovcharovmax@yandex.ru" ]
ovcharovmax@yandex.ru
04df58a49a0cd3dee2830a34facd4a34f4e62358
7d6e641d53c6d063da09a632e960615d4ddf05ef
/flask_api/venv3/lib/python2.7/_abcoll.py
494be0f1ed300d58c350692546af0c3cf8919e8c
[ "MIT" ]
permissive
tjuyanghw/ml-flask-api
3af1a6103505962a624c78425b843d935277e1b9
dc119856e75b0f86d21ccf79cd1418559d722ee4
refs/heads/master
2022-02-23T14:20:32.569192
2018-06-15T08:06:56
2018-06-15T08:06:56
null
0
0
null
null
null
null
UTF-8
Python
false
false
53
py
/home/harrypotter0/anaconda2/lib/python2.7/_abcoll.py
[ "9654263057akashkandpal@gmail.com" ]
9654263057akashkandpal@gmail.com
72f19dc284ac2bf624c43c39e5120e941676dad9
c9288bd0496b92ff503a9df60f8210b08f54f3b5
/label_studio/projects/migrations/0003_auto_20210305_1008.py
15546212ecd08576a1f749015ef9abaed8abb3b2
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
mihirpurwar/label-studio
11318bd352c9648a3c33d69f09b7f389f1b99512
7c9e5777b7c0fe510b8585ae4c42b74a46929f73
refs/heads/master
2023-05-19T18:47:52.351140
2021-06-13T13:46:38
2021-06-13T13:46:38
376,830,084
1
0
Apache-2.0
2021-06-14T13:19:51
2021-06-14T13:19:50
null
UTF-8
Python
false
false
2,400
py
# Generated by Django 3.1.4 on 2021-03-05 10:08 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('projects', '0002_auto_20210304_1457'), ] operations = [ migrations.RenameField( model_name='project', old_name='enable_empty_completion', new_name='enable_empty_annotation' ), migrations.AlterField( model_name='project', name='enable_empty_annotation', field=models.BooleanField(default=True, help_text='Allow submit empty annotations', verbose_name='enable empty annotation'), ), migrations.RenameField( model_name='project', old_name='maximum_completions', new_name='maximum_annotations' ), migrations.AlterField( model_name='project', name='maximum_annotations', field=models.IntegerField(default=1, help_text='Maximum overlaps of expert annotations for one task. If the annotation number per task is equal or greater to this value, the task becomes finished (is_labeled=True)', verbose_name='maximum annotation number'), ), migrations.RenameField( model_name='project', old_name='min_completions_to_start_training', new_name='min_annotations_to_start_training' ), migrations.AlterField( model_name='project', name='min_annotations_to_start_training', field=models.IntegerField(default=10, help_text='Minimum number of completed tasks after which training is started', verbose_name='min_annotations_to_start_training'), ), migrations.RenameField( model_name='project', old_name='show_completion_history', new_name='show_annotation_history' ), migrations.AlterField( model_name='project', name='show_annotation_history', field=models.BooleanField(default=False, help_text='Show annotation history to collaborator', verbose_name='show annotation history'), ), migrations.AlterField( model_name='project', name='result_count', field=models.IntegerField(default=0, help_text='Total results inside of annotations counter', verbose_name='result count'), ), ]
[ "noreply@github.com" ]
mihirpurwar.noreply@github.com
592bced0cbcf81fd35deea5cffaf73c10910136b
23693ce4ad3eca0c208f01f5e872c6e99e1edb69
/DarkSUSY_mH_125/mGammaD_0350/cT_5000/DarkSUSY_LHE_read.py
764d8cf2519fd9b255536e71b898cafc1a2ed294
[]
no_license
cms-tamu/MuJetAnalysis_DarkSusySamples_LHE_13TeV_02
a6a1790ba62583e4693747e7162478f4688aa9a9
ef31123e5b3f19e8a9621fa519f81105a500c3a9
refs/heads/master
2021-01-22T20:19:03.826804
2015-03-18T13:59:43
2015-03-18T13:59:43
30,620,024
0
1
null
null
null
null
UTF-8
Python
false
false
111,091
py
import ROOT, array, os, re, math, random, string from math import * from operator import itemgetter def getStringBetween(name, first, second): begOf1 = name.find(first) endOf1 = len(first) + begOf1 begOf2 = name.find(second) desiredString = name[endOf1:begOf2] return desiredString muonID = 13 higgsID = 25 n1ID = 3000002 nDID = 3000001 nExit = 80002 #nExit = 1000 gammaDID = 3000022 hMass = "125" n1Mass = "10" nDMass = "1" filename = "DarkSUSY_mH_125_mGammaD_0350_13TeV_cT_5000_madgraph452_bridge224_events80k.lhe" filename = "DarkSUSY_mH_125_mGammaD_0350_13TeV_cT_5000_madgraph452_bridge224_events80k.lhe" f = open(filename, 'r') if len(filename) >= 77: mass_GammaD = getStringBetween(filename, "mGammaD_","_13TeV_cT") lifetime_GammaD = getStringBetween(filename, "_cT_","_madgraph452") energy = getStringBetween(filename, mass_GammaD + "_","TeV_") mass_Higgs = getStringBetween(filename, "_mH_","_mGammaD_") lifetime_GammaD_Legend = lifetime_GammaD[0:-2] + "." + lifetime_GammaD[len(lifetime_GammaD)-2:len(lifetime_GammaD)] mass_GammaD_Legend = mass_GammaD[0:-3] + "." + mass_GammaD[len(mass_GammaD)-3:len(lifetime_GammaD)+1] #mass_GammaD = filename[24:-49] #lifetime_GammaD = filename[38:-36] #energy = filename[29:-46] #mass_Higgs = filename[12:-62] #lifetime_GammaD_Legend = filename[38:-38] + "." + filename[39:-36] #mass_GammaD_Legend = filename [24:-52] + "." + filename[25:-49] if mass_GammaD_Legend[len(mass_GammaD_Legend)-1] == "0": mass_GammaD_Legend = mass_GammaD_Legend[:-1] if mass_GammaD_Legend[len(mass_GammaD_Legend)-1] == "0": mass_GammaD_Legend = mass_GammaD_Legend[:-1] if mass_GammaD_Legend[len(mass_GammaD_Legend)-1] == "0": mass_GammaD_Legend = mass_GammaD_Legend[:-1] if mass_GammaD_Legend[len(mass_GammaD_Legend)-1] == "." and len(mass_GammaD_Legend) <= 3: mass_GammaD_Legend = mass_GammaD_Legend + "0" switch = 0 if lifetime_GammaD_Legend[len(lifetime_GammaD_Legend)-1] == "0": lifetime_GammaD_Legend = lifetime_GammaD_Legend[:-1] switch = 1 if lifetime_GammaD_Legend[len(lifetime_GammaD_Legend)-1] == "0" and switch == 1: lifetime_GammaD_Legend = lifetime_GammaD_Legend[:-1] else: lifetime_GammaD = "000" lifetime_GammaD_Legend = "0.00" mass_GammaD = getStringBetween(filename, "mGammaD_","_13TeV") energy = getStringBetween(filename, mass_GammaD + "_","TeV") mass_Higgs = getStringBetween(filename, "_mH_","_mGammaD_") mass_GammaD_Legend = mass_GammaD[0:-3] + "." + mass_GammaD[len(mass_GammaD)-3:len(lifetime_GammaD)+1] #mass_GammaD = filename[24:-42] #energy = filename[29:-39] #mass_Higgs = filename[12:-55] #mass_GammaD_Legend = filename[24:-45] + "." + filename[25:-42] #lifetime_GammaD = "000" #lifetime_GammaD_Legend = "0.00" print mass_GammaD print lifetime_GammaD print lifetime_GammaD_Legend print mass_GammaD_Legend BAM = ROOT.TFile("ValidationPlots_mGammaD_" + mass_GammaD + "_" + energy + "_TeV_cT_" + lifetime_GammaD + ".root" , "RECREATE") execfile("tdrStyle.py") cnv = ROOT.TCanvas("cnv", "cnv") txtHeader = ROOT.TLegend(.17,.935,0.97,1.) txtHeader.SetFillColor(ROOT.kWhite) txtHeader.SetFillStyle(0) txtHeader.SetBorderSize(0) txtHeader.SetTextFont(42) txtHeader.SetTextSize(0.045) txtHeader.SetTextAlign(22) #txtHeader.SetHeader("CMS Simulation") txtHeader.SetHeader("CMS Simulation (LHE) " + energy + " TeV") #txtHeader.SetHeader("CMS Prelim. 2011 #sqrt{s} = 7 TeV L_{int} = 5.3 fb^{-1}") #txtHeader.SetHeader("CMS 2011 #sqrt{s} = 7 TeV L_{int} = 5.3 fb^{-1}") #txtHeader.SetHeader("CMS Prelim. 2012 #sqrt{s} = 8 TeV L_{int} = 20.65 fb^{-1}") #txtHeader.SetHeader("CMS 2012 #sqrt{s} = 8 TeV L_{int} = 20.65 fb^{-1}") txtHeader.Draw() #info = ROOT.TLegend(0.33,0.8222222,0.9577778,0.9122222) info = ROOT.TLegend(0.4566667,0.82,0.7822222,0.9066667) info.SetFillColor(ROOT.kWhite) info.SetFillStyle(0) info.SetBorderSize(0) info.SetTextFont(42) info.SetTextSize(0.02777778) info.SetMargin(0.13) info.SetHeader("#splitline{pp #rightarrow h #rightarrow 2n_{1} #rightarrow 2n_{D} + 2 #gamma_{D} #rightarrow 2n_{D} + 4#mu}{#splitline{m_{h} = " + mass_Higgs + " GeV, m_{n_{1}} = 10 GeV, m_{n_{D}} = 1 GeV}{m_{#gamma_{D}} = " + mass_GammaD_Legend + " GeV, c#tau_{#gamma_{D}} = " + lifetime_GammaD_Legend + " mm}}" ) #info.SetHeader("#splitline{pp #rightarrow h #rightarrow 2n_{1} #rightarrow 2n_{D} + 2 #gamma_{D} #rightarrow 2n_{D} + 4#mu}{#splitline{#gamma_{D} c#tau = "+lifetime_GammaD_Legend + "mm, Mass = " + mass_GammaD_Legend + "GeV}{M of h = " + hMass + "GeV, M of n_{1} = " + n1Mass + "GeV, M of n_{D} = " + nDMass + "GeV}}" ) txtHeader2 = ROOT.TLegend(0.01333333,0.9311111,0.8133333,0.9955556) txtHeader2.SetFillColor(ROOT.kWhite) txtHeader2.SetFillStyle(0) txtHeader2.SetBorderSize(0) txtHeader2.SetTextFont(42) txtHeader2.SetTextSize(0.045) txtHeader2.SetTextAlign(22) txtHeader2.SetHeader("CMS Simulation #sqrt{s} = " + energy + " TeV") ################################################################################ # pT of muons ################################################################################ Etmiss_dummy = ROOT.TH1F("Etmiss_dummy","Etmiss_dummy", 100, 0, 100) Etmiss_dummy.SetTitleOffset(1.5, "Y") Etmiss_dummy.SetTitleOffset(1.4, "X") Etmiss_dummy.SetTitleSize(0.04,"X") Etmiss_dummy.SetXTitle("MET = #sum_{n_{D}}#vec{p_{T}} [GeV]") Etmiss_dummy.SetYTitle("Fraction of events / 1 GeV") Etmiss_dummy.SetMaximum( 0.1 ) Etmiss = ROOT.TH1F("Etmiss","Etmiss", 100, 0, 100) Etmiss.SetLineColor(ROOT.kBlue) Etmiss.SetLineWidth(2) Etmiss.SetLineStyle(1) nBins = 125 binMin = 0.0 binMax = 125.0 yMax = 0.25 cTlow = 0 if float(lifetime_GammaD_Legend) != 0: cTlim = float(lifetime_GammaD_Legend)*5 binwidth = float(lifetime_GammaD_Legend) numBins = int(cTlim/binwidth) binwidthRound = round(binwidth,3) else: cTlim = 10 binwidth = 1 numBins = int(cTlim/binwidth) binwidthRound = "1" formula = "exp(-x/"+ lifetime_GammaD_Legend +")/("+ lifetime_GammaD_Legend + "*(1 - exp(-" + str(cTlim) + "/" + lifetime_GammaD_Legend + ")))" print formula h_gammaD_cT_dummy = ROOT.TH1F("h_gammaD_cT_dummy", "h_gammaD_cT_dummy", numBins, 0, cTlim) #h_gammaD_cT_dummy.SetYTitle("Fraction of events") h_gammaD_cT_dummy.SetTitleOffset(1.3, "Y") h_gammaD_cT_dummy.SetXTitle("c#tau of #gamma_{D} [mm]") h_gammaD_cT_dummy.SetYTitle("Normalized Fraction of Events / " + str(binwidthRound) + " mm") h_gammaD_cT_dummy.SetTitleSize(0.05,"Y") h_gammaD_cT_dummy.SetMaximum( 10 ) h_gammaD_cT = ROOT.TH1F("h_gammaD_cT", "h_gammaD_cT", numBins, 0, cTlim) h_gammaD_cT.SetLineColor(ROOT.kBlue) h_gammaD_cT.SetLineWidth(2) h_gammaD_cT.SetLineStyle(1) h_gammaD_cT_lab_dummy = ROOT.TH1F("h_gammaD_cT_lab_dummy", "h_gammaD_cT_lab_dummy", numBins, 0, cTlim) #h_gammaD_cT_lab_dummy.SetYTitle("Fraction of events") h_gammaD_cT_lab_dummy.SetTitleOffset(1.3, "Y") h_gammaD_cT_lab_dummy.SetXTitle("L of #gamma_{D} [mm]") h_gammaD_cT_lab_dummy.SetYTitle("Normalized Fraction of Events / " + str(binwidthRound) + " mm") h_gammaD_cT_lab_dummy.SetTitleSize(0.05,"Y") h_gammaD_cT_lab_dummy.SetMaximum( 10 ) h_gammaD_cT_lab = ROOT.TH1F("h_gammaD_cT_lab", "h_gammaD_cT_lab", numBins, 0, cTlim) h_gammaD_cT_lab.SetLineColor(ROOT.kBlue) h_gammaD_cT_lab.SetLineWidth(2) h_gammaD_cT_lab.SetLineStyle(1) h_gammaD_cT_XY_lab_dummy = ROOT.TH1F("h_gammaD_cT_XY_lab_dummy", "h_gammaD_cT_XY_lab_dummy", numBins, 0, cTlim) #h_gammaD_cT_XY_lab_dummy.SetYTitle("Fraction of events") h_gammaD_cT_XY_lab_dummy.SetTitleOffset(1.3, "Y") h_gammaD_cT_XY_lab_dummy.SetXTitle("L_{XY} of #gamma_{D} [mm]") h_gammaD_cT_XY_lab_dummy.SetYTitle("Normalized Fraction of Events / " + str(binwidthRound) + " mm") h_gammaD_cT_XY_lab_dummy.SetTitleSize(0.05,"Y") h_gammaD_cT_XY_lab_dummy.SetMaximum( 10 ) h_gammaD_cT_XY_lab = ROOT.TH1F("h_gammaD_cT_XY_lab", "h_gammaD_cT_XY_lab", numBins, 0, cTlim) h_gammaD_cT_XY_lab.SetLineColor(ROOT.kBlue) h_gammaD_cT_XY_lab.SetLineWidth(2) h_gammaD_cT_XY_lab.SetLineStyle(1) h_gammaD_cT_Z_lab_dummy = ROOT.TH1F("h_gammaD_cT_Z_lab_dummy", "h_gammaD_cT_Z_lab_dummy", numBins, 0, cTlim) #h_gammaD_cT_Z_lab_dummy.SetYTitle("Fraction of events") h_gammaD_cT_Z_lab_dummy.SetTitleOffset(1.3, "Y") h_gammaD_cT_Z_lab_dummy.SetXTitle("L_{Z} of #gamma_{D} [mm]") h_gammaD_cT_Z_lab_dummy.SetYTitle("Normalized Fraction of events / " + str(binwidthRound) + " mm") h_gammaD_cT_Z_lab_dummy.SetTitleSize(0.05,"Y") h_gammaD_cT_Z_lab_dummy.SetMaximum( 10 ) h_gammaD_cT_Z_lab = ROOT.TH1F("h_gammaD_cT_Z_lab", "h_gammaD_cT_Z_lab", numBins, 0, cTlim) h_gammaD_cT_Z_lab.SetLineColor(ROOT.kBlue) h_gammaD_cT_Z_lab.SetLineWidth(2) h_gammaD_cT_Z_lab.SetLineStyle(1) h_gammaD_1_cT_dummy = ROOT.TH1F("h_gammaD_1_cT_dummy", "h_gammaD_1_cT_dummy", numBins, 0, cTlim) h_gammaD_1_cT_dummy.SetTitleOffset(1.3, "Y") h_gammaD_1_cT_dummy.SetXTitle("c#tau of #gamma_{D} [mm]") h_gammaD_1_cT_dummy.SetYTitle("Normalized Fraction of events / " + str(binwidthRound) + " mm") h_gammaD_1_cT_dummy.SetTitleSize(0.05,"Y") h_gammaD_1_cT_dummy.SetMaximum( 10 ) h_gammaD_1_cT = ROOT.TH1F("h_gammaD_1_cT", "h_gammaD_1_cT", numBins, 0, cTlim) h_gammaD_1_cT.SetLineColor(ROOT.kBlue) h_gammaD_1_cT.SetLineWidth(2) h_gammaD_1_cT.SetLineStyle(1) h_gammaD_1_cT_lab_dummy = ROOT.TH1F("h_gammaD_1_cT_lab_dummy", "h_gammaD_1_cT_lab_dummy", numBins, 0, cTlim) h_gammaD_1_cT_lab_dummy.SetTitleOffset(1.3, "Y") h_gammaD_1_cT_lab_dummy.SetXTitle("L of #gamma_{D} [mm]") h_gammaD_1_cT_lab_dummy.SetYTitle("Normalized Fraction of events / " + str(binwidthRound) + " mm") h_gammaD_1_cT_lab_dummy.SetTitleSize(0.05,"Y") h_gammaD_1_cT_lab_dummy.SetMaximum( 10 ) h_gammaD_1_cT_lab = ROOT.TH1F("h_gammaD_1_cT_lab", "h_gammaD_1_cT_lab", numBins, 0, cTlim) h_gammaD_1_cT_lab.SetLineColor(ROOT.kBlue) h_gammaD_1_cT_lab.SetLineWidth(2) h_gammaD_1_cT_lab.SetLineStyle(1) h_gammaD_1_cT_XY_lab_dummy = ROOT.TH1F("h_gammaD_1_cT_XY_lab_dummy", "h_gammaD_1_cT_XY_lab_dummy", numBins, 0, cTlim) h_gammaD_1_cT_XY_lab_dummy.SetTitleOffset(1.3, "Y") h_gammaD_1_cT_XY_lab_dummy.SetXTitle("L_{XY} of #gamma_{D} [mm]") h_gammaD_1_cT_XY_lab_dummy.SetYTitle("Normalized Fraction of events / " + str(binwidthRound) + " mm") h_gammaD_1_cT_XY_lab_dummy.SetTitleSize(0.05,"Y") h_gammaD_1_cT_XY_lab_dummy.SetMaximum( 10 ) h_gammaD_1_cT_XY_lab = ROOT.TH1F("h_gammaD_1_cT_XY_lab", "h_gammaD_1_cT_XY_lab", numBins, 0, cTlim) h_gammaD_1_cT_XY_lab.SetLineColor(ROOT.kBlue) h_gammaD_1_cT_XY_lab.SetLineWidth(2) h_gammaD_1_cT_XY_lab.SetLineStyle(1) h_gammaD_1_cT_Z_lab_dummy = ROOT.TH1F("h_gammaD_1_cT_Z_lab_dummy", "h_gammaD_1_cT_Z_lab_dummy", numBins, 0, cTlim) h_gammaD_1_cT_Z_lab_dummy.SetTitleOffset(1.3, "Y") h_gammaD_1_cT_Z_lab_dummy.SetXTitle("L_{Z} of #gamma_{D} [mm]") h_gammaD_1_cT_Z_lab_dummy.SetYTitle("Normalized Fraction of events / " + str(binwidthRound) + " mm") h_gammaD_1_cT_Z_lab_dummy.SetTitleSize(0.05,"Y") h_gammaD_1_cT_Z_lab_dummy.SetMaximum( 10 ) h_gammaD_1_cT_Z_lab = ROOT.TH1F("h_gammaD_1_cT_Z_lab", "h_gammaD_1_cT_Z_lab", numBins, 0, cTlim) h_gammaD_1_cT_Z_lab.SetLineColor(ROOT.kBlue) h_gammaD_1_cT_Z_lab.SetLineWidth(2) h_gammaD_1_cT_Z_lab.SetLineStyle(1) h_gammaD_2_cT = ROOT.TH1F("h_gammaD_2_cT", "h_gammaD_2_cT", numBins, 0, cTlim) h_gammaD_2_cT.SetLineColor(ROOT.kRed) h_gammaD_2_cT.SetLineWidth(2) h_gammaD_2_cT.SetLineStyle(1) h_gammaD_2_cT_lab = ROOT.TH1F("h_gammaD_2_cT_lab", "h_gammaD_2_cT_lab", numBins, 0, cTlim) h_gammaD_2_cT_lab.SetLineColor(ROOT.kRed) h_gammaD_2_cT_lab.SetLineWidth(2) h_gammaD_2_cT_lab.SetLineStyle(1) h_gammaD_2_cT_XY_lab = ROOT.TH1F("h_gammaD_2_cT_XY_lab", "h_gammaD_2_cT_XY_lab", numBins, 0, cTlim) h_gammaD_2_cT_XY_lab.SetLineColor(ROOT.kRed) h_gammaD_2_cT_XY_lab.SetLineWidth(2) h_gammaD_2_cT_XY_lab.SetLineStyle(1) h_gammaD_2_cT_Z_lab = ROOT.TH1F("h_gammaD_2_cT_Z_lab", "h_gammaD_2_cT_Z_lab", numBins, 0, cTlim) h_gammaD_2_cT_Z_lab.SetLineColor(ROOT.kRed) h_gammaD_2_cT_Z_lab.SetLineWidth(2) h_gammaD_2_cT_Z_lab.SetLineStyle(1) h_muon_pT_dummy = ROOT.TH1F("h_muon_pT_dummy", "h_muon_pT_dummy", nBins, binMin, binMax) h_muon_pT_dummy.SetYTitle("Fraction of events / 1 GeV") h_muon_pT_dummy.SetTitleOffset(1.35, "Y") h_muon_pT_dummy.SetXTitle("p_{T} of #mu [GeV]") h_muon_pT_dummy.SetMaximum( 0.2 ) h_higgs_pT_dummy = ROOT.TH1F("h_higgs_pT_dummy", "h_higgs_pT_dummy", 10, 0, 10) h_higgs_pT_dummy.SetYTitle("Fraction of events / 1 GeV") h_higgs_pT_dummy.SetTitleOffset(1.35, "Y") h_higgs_pT_dummy.SetXTitle("p_{T} of h [GeV]") h_higgs_pT_dummy.SetMaximum( 1.1 ) h_muon_pZ_dummy = ROOT.TH1F("h_muon_pZ_dummy", "h_muon_pZ_dummy", nBins, binMin, binMax) h_muon_pZ_dummy.SetYTitle("Fraction of events / 1 GeV") h_muon_pZ_dummy.SetTitleOffset(1.35, "Y") h_muon_pZ_dummy.SetXTitle("|p_{Z}| of #mu [GeV]") h_muon_pZ_dummy.SetMaximum( yMax ) h_higgs_pZ_dummy = ROOT.TH1F("h_higgs_pZ_dummy", "h_higgs_pZ_dummy", 50, 0, 500) h_higgs_pZ_dummy.SetYTitle("Fraction of events / 1 GeV") h_higgs_pZ_dummy.SetTitleOffset(1.35, "Y") h_higgs_pZ_dummy.SetXTitle("|p_{Z}| of h [GeV]") h_higgs_pZ_dummy.SetMaximum( 0.1 ) h_muon_Eta_dummy = ROOT.TH1F("h_muon_Eta_dummy", "h_muon_Eta_dummy", 100, -5, 5) h_muon_Eta_dummy.SetYTitle("Fraction of events / 0.1") h_muon_Eta_dummy.SetTitleOffset(1.35, "Y") h_muon_Eta_dummy.SetXTitle("#eta of #mu") h_muon_Eta_dummy.SetMaximum( 0.1 ) #h_higgs_Eta_dummy = ROOT.TH1F("h_higgs_Eta_dummy", "h_higgs_Eta_dummy", 100,-5,5) #h_higgs_Eta_dummy.SetYTitle("Fraction of events / 0.1 GeV") #h_higgs_Eta_dummy.SetTitleOffset(1.35, "Y") #h_higgs_Eta_dummy.SetXTitle("#eta of h [GeV]") #h_higgs_Eta_dummy.SetMaximum( 0.1 ) h_muon_Phi_dummy = ROOT.TH1F("h_muon_Phi_dummy", "h_muon_Phi_dummy", 80,-4,4) h_muon_Phi_dummy.SetYTitle("Fraction of events / 0.1 rad") h_muon_Phi_dummy.SetTitleOffset(1.35, "Y") h_muon_Phi_dummy.SetXTitle("#phi of #mu [rad]") h_muon_Phi_dummy.SetMaximum( 0.1 ) h_higgs_Phi_dummy = ROOT.TH1F("h_higgs_Phi_dummy", "h_higgs_Phi_dummy", 80,-4,4) h_higgs_Phi_dummy.SetYTitle("Fraction of events") h_higgs_Phi_dummy.SetTitleOffset(1.35, "Y") h_higgs_Phi_dummy.SetXTitle("#phi of h [rad]") h_higgs_Phi_dummy.SetMaximum( 1.4 ) h_higgs_p_dummy = ROOT.TH1F("h_higgs_p_dummy", "h_higgs_p_dummy", 50, 0, 500) h_higgs_p_dummy.SetYTitle("Fraction of events / 1 GeV") h_higgs_p_dummy.SetTitleOffset(1.35, "Y") h_higgs_p_dummy.SetXTitle("p of h [GeV]") h_higgs_p_dummy.SetMaximum( 0.1 ) h_higgs_M_dummy = ROOT.TH1F("h_higgs_M_dummy", "h_higgs_M_dummy", 220, 80.5, 300.5) h_higgs_M_dummy.SetYTitle("Fraction of events / 1 GeV") h_higgs_M_dummy.SetTitleOffset(1.35, "Y") h_higgs_M_dummy.SetXTitle("Mass of h [GeV]") h_higgs_M_dummy.SetLabelSize(0.03,"X") h_higgs_M_dummy.SetMaximum( 1.5 ) h_higgs_M_dummy.SetNdivisions(10) h_higgs_M_dummy.GetXaxis().SetMoreLogLabels() h_higgs_p = ROOT.TH1F("h_higgs_p", "h_higgs_p", 50, 0, 500) h_higgs_p.SetLineColor(ROOT.kBlue) h_higgs_p.SetLineWidth(2) h_higgs_p.SetLineStyle(1) h_higgs_M = ROOT.TH1F("h_higgs_M", "h_higgs_M", 10, 120.5, 130.5) h_higgs_M.SetLineColor(ROOT.kBlue) h_higgs_M.SetLineWidth(2) h_higgs_M.SetLineStyle(1) h_higgs_pT = ROOT.TH1F("h_higgs_pT", "h_higgs_pT", 10, 0, 10) h_higgs_pT.SetLineColor(ROOT.kBlue) h_higgs_pT.SetLineWidth(2) h_higgs_pT.SetLineStyle(1) h_n1_1_pT_dummy = ROOT.TH1F("h_n1_1_pT_dummy", "h_n1_1_pT_dummy", 70, 0, 70) h_n1_1_pT_dummy.SetYTitle("Fraction of events / 1 GeV") h_n1_1_pT_dummy.SetTitleOffset(1.35, "Y") h_n1_1_pT_dummy.SetXTitle("p_{T} of n_{1} [GeV]") h_n1_1_pT_dummy.SetMaximum( yMax ) h_higgs_pZ = ROOT.TH1F("h_higgs_pZ", "h_higgs_pZ", 50, 0, 500) h_higgs_pZ.SetLineColor(ROOT.kBlue) h_higgs_pZ.SetLineWidth(2) h_higgs_pZ.SetLineStyle(1) h_n1_1_pZ_dummy = ROOT.TH1F("h_n1_1_pZ_dummy", "h_n1_1_pZ_dummy", 300, 0, 300) h_n1_1_pZ_dummy.SetYTitle("Fraction of events / 1 GeV") h_n1_1_pZ_dummy.SetTitleOffset(1.35, "Y") h_n1_1_pZ_dummy.SetXTitle("|p_{Z}| of n_{1} [GeV]") h_n1_1_pZ_dummy.SetMaximum( 0.1 ) #h_higgs_Eta = ROOT.TH1F("h_higgs_Eta", "h_higgs_Eta", 50,0,5) #h_higgs_Eta.SetLineColor(ROOT.kBlue) #h_higgs_Eta.SetLineWidth(2) #h_higgs_Eta.SetLineStyle(1) h_n1_1_Eta_dummy = ROOT.TH1F("h_n1_1_Eta_dummy", "h_n1_1_Eta_dummy", 100,-5,5) h_n1_1_Eta_dummy.SetYTitle("Fraction of events / 0.1") h_n1_1_Eta_dummy.SetTitleOffset(1.35, "Y") h_n1_1_Eta_dummy.SetXTitle("#eta of n_{1}") h_n1_1_Eta_dummy.SetMaximum( 0.1 ) h_higgs_Phi = ROOT.TH1F("h_higgs_Phi", "h_higgs_Phi", 80,-4,4) h_higgs_Phi.SetLineColor(ROOT.kBlue) h_higgs_Phi.SetLineWidth(2) h_higgs_Phi.SetLineStyle(1) h_n1_1_Phi_dummy = ROOT.TH1F("h_n1_1_Phi_dummy", "h_n1_1_Phi_dummy", 80,-4,4) h_n1_1_Phi_dummy.SetYTitle("Fraction of events / 0.1 rad") h_n1_1_Phi_dummy.SetTitleOffset(1.35, "Y") h_n1_1_Phi_dummy.SetXTitle("#phi of n_{1} [rad]") h_n1_1_Phi_dummy.SetMaximum( 0.05 ) h_n1_1_p_dummy = ROOT.TH1F("h_n1_1_p_dummy", "h_n1_1_p_dummy", 300, 0, 300) h_n1_1_p_dummy.SetYTitle("Fraction of events / 1 GeV") h_n1_1_p_dummy.SetTitleOffset(1.35, "Y") h_n1_1_p_dummy.SetXTitle("p of n_{1} [GeV]") h_n1_1_p_dummy.SetMaximum( 0.1 ) h_n1_1_M_dummy = ROOT.TH1F("h_n1_1_M_dummy", "h_n1_1_M_dummy", 200, 0.05, 20.05) h_n1_1_M_dummy.SetYTitle("Fraction of events / 0.1 GeV") h_n1_1_M_dummy.SetTitleOffset(1.35, "Y") h_n1_1_M_dummy.SetXTitle("Mass of n_{1} [GeV]") h_n1_1_M_dummy.SetMaximum( 1.6 ) h_n1_1_p = ROOT.TH1F("h_n1_1_p", "h_n1_1_p", 300, 0, 300) h_n1_1_p.SetLineColor(ROOT.kBlue) h_n1_1_p.SetLineWidth(2) h_n1_1_p.SetLineStyle(1) h_n1_1_M = ROOT.TH1F("h_n1_1_M", "h_n1_1_M", 200, 0.05, 20.05) h_n1_1_M.SetLineColor(ROOT.kBlue) h_n1_1_M.SetLineWidth(2) h_n1_1_M.SetLineStyle(1) h_n1_1_pT = ROOT.TH1F("h_n1_1_pT", "h_n1_1_pT", 70, 0, 70) #this is the peak at 60 h_n1_1_pT.SetLineColor(ROOT.kBlue) h_n1_1_pT.SetLineWidth(2) h_n1_1_pT.SetLineStyle(1) h_n1_1_pZ = ROOT.TH1F("h_n1_1_pZ", "h_n1_1_pZ", 300, 0, 300) h_n1_1_pZ.SetLineColor(ROOT.kBlue) h_n1_1_pZ.SetLineWidth(2) h_n1_1_pZ.SetLineStyle(1) h_n1_1_Eta = ROOT.TH1F("h_n1_1_Eta", "h_n1_1_Eta", 100,-5,5) h_n1_1_Eta.SetLineColor(ROOT.kBlue) h_n1_1_Eta.SetLineWidth(2) h_n1_1_Eta.SetLineStyle(1) h_n1_1_Phi = ROOT.TH1F("h_n1_1_Phi", "h_n1_1_Phi", 80,-4,4) h_n1_1_Phi.SetLineColor(ROOT.kBlue) h_n1_1_Phi.SetLineWidth(2) h_n1_1_Phi.SetLineStyle(1) #h_n1_2_pT_dummy = ROOT.TH1F("h_n1_2_pT_dummy", "h_n1_2_pT_dummy", 700, 0, 70) #this is the peak at ~10GeV #h_n1_2_pT_dummy.SetYTitle("Fraction of events / 1 GeV") #h_n1_2_pT_dummy.SetTitleOffset(1.35, "Y") #h_n1_2_pT_dummy.SetXTitle("p_{T n_{1}} [GeV]") #h_n1_2_pT_dummy.SetMaximum( yMax ) # #h_n1_2_p_dummy = ROOT.TH1F("h_n1_2_p_dummy", "h_n1_2_p_dummy", 20, 50, 70) #h_n1_2_p_dummy.SetYTitle("Fraction of events / 1 GeV") #h_n1_2_p_dummy.SetTitleOffset(1.35, "Y") #h_n1_2_p_dummy.SetXTitle("p_{n_{1}} [GeV]") #h_n1_2_p_dummy.SetMaximum( 0.05 ) # #h_n1_2_M_dummy = ROOT.TH1F("h_n1_2_M_dummy", "h_n1_2_M_dummy", 200, 0, 20) #h_n1_2_M_dummy.SetYTitle("Fraction of events / 1 GeV") #h_n1_2_M_dummy.SetTitleOffset(1.35, "Y") #h_n1_2_M_dummy.SetXTitle("m_{n_{1}} [GeV]") #h_n1_2_M_dummy.SetMaximum( 1.2 ) h_n1_2_p = ROOT.TH1F("h_n1_2_p", "h_n1_2_p", 300, 0, 300) h_n1_2_p.SetLineColor(ROOT.kRed) h_n1_2_p.SetLineWidth(2) h_n1_2_p.SetLineStyle(1) #h_n1_2_M = ROOT.TH1F("h_n1_2_M", "h_n1_2_M", 200, 0.05, 20.05) #h_n1_2_M.SetLineColor(ROOT.kRed) #h_n1_2_M.SetLineWidth(2) #h_n1_2_M.SetLineStyle(1) h_n1_2_pT = ROOT.TH1F("h_n1_2_pT", "h_n1_2_pT", 70, 0, 70) h_n1_2_pT.SetLineColor(ROOT.kRed) h_n1_2_pT.SetLineWidth(2) h_n1_2_pT.SetLineStyle(1) h_nD_1_pT_dummy = ROOT.TH1F("h_nD_1_pT_dummy", "h_nD_1_pT_dummy", 130, 0, 130) h_nD_1_pT_dummy.SetYTitle("Fraction of events / 1 GeV") h_nD_1_pT_dummy.SetTitleOffset(1.35, "Y") h_nD_1_pT_dummy.SetXTitle("p_{T} of n_{D} [GeV]") h_nD_1_pT_dummy.SetMaximum( 0.1 ) h_n1_2_pZ = ROOT.TH1F("h_n1_2_pZ", "h_n1_2_pZ", 300, 0, 300) h_n1_2_pZ.SetLineColor(ROOT.kRed) h_n1_2_pZ.SetLineWidth(2) h_n1_2_pZ.SetLineStyle(1) h_nD_1_pZ_dummy = ROOT.TH1F("h_nD_1_pZ_dummy", "h_nD_1_pZ_dummy", 130, 0, 130) h_nD_1_pZ_dummy.SetYTitle("Fraction of events / 1 GeV") h_nD_1_pZ_dummy.SetTitleOffset(1.35, "Y") h_nD_1_pZ_dummy.SetXTitle("|p_{Z}| of n_{D} [GeV]") h_nD_1_pZ_dummy.SetMaximum( 0.1 ) h_n1_2_Eta = ROOT.TH1F("h_n1_2_Eta", "h_n1_2_Eta", 100,-5,5) h_n1_2_Eta.SetLineColor(ROOT.kRed) h_n1_2_Eta.SetLineWidth(2) h_n1_2_Eta.SetLineStyle(1) h_nD_1_Eta_dummy = ROOT.TH1F("h_nD_1_Eta_dummy", "h_nD_1_Eta_dummy", 100,-5,5) h_nD_1_Eta_dummy.SetYTitle("Fraction of events / 0.1") h_nD_1_Eta_dummy.SetTitleOffset(1.35, "Y") h_nD_1_Eta_dummy.SetXTitle("#eta of n_{D}") h_nD_1_Eta_dummy.SetMaximum( 0.1 ) h_n1_2_Phi = ROOT.TH1F("h_n1_2_Phi", "h_n1_2_Phi", 80,-4,4) h_n1_2_Phi.SetLineColor(ROOT.kRed) h_n1_2_Phi.SetLineWidth(2) h_n1_2_Phi.SetLineStyle(1) h_nD_1_Phi_dummy = ROOT.TH1F("h_nD_1_Phi_dummy", "h_nD_1_Phi_dummy", 80,-4,4) h_nD_1_Phi_dummy.SetYTitle("Fraction of events / 0.1 rad") h_nD_1_Phi_dummy.SetTitleOffset(1.35, "Y") h_nD_1_Phi_dummy.SetXTitle("#phi of n_{D} [rad]") h_nD_1_Phi_dummy.SetMaximum( 0.05 ) h_nD_1_p_dummy = ROOT.TH1F("h_nD_1_p_dummy", "h_nD_1_p_dummy", 130, 0, 130) h_nD_1_p_dummy.SetYTitle("Fraction of events / 1 GeV") h_nD_1_p_dummy.SetTitleOffset(1.35, "Y") h_nD_1_p_dummy.SetXTitle("p of n_{D} [GeV]") h_nD_1_p_dummy.SetMaximum( 0.1 ) h_nD_1_M_dummy = ROOT.TH1F("h_nD_1_M_dummy", "h_nD_1_M_dummy", 20, 0.05, 2.05) h_nD_1_M_dummy.SetYTitle("Fraction of events / 0.1 GeV") h_nD_1_M_dummy.SetTitleOffset(1.35, "Y") h_nD_1_M_dummy.SetXTitle("Mass of n_{D} [GeV]") h_nD_1_M_dummy.SetMaximum( 1.6 ) h_nD_1_p = ROOT.TH1F("h_nD_1_p", "h_nD_1_p", 130, 0, 130) h_nD_1_p.SetLineColor(ROOT.kBlue) h_nD_1_p.SetLineWidth(2) h_nD_1_p.SetLineStyle(1) h_nD_1_M = ROOT.TH1F("h_nD_1_M", "h_nD_1_M", 20, 0.05, 2.05) h_nD_1_M.SetLineColor(ROOT.kBlue) h_nD_1_M.SetLineWidth(2) h_nD_1_M.SetLineStyle(1) h_nD_1_pT = ROOT.TH1F("h_nD_1_pT", "h_nD_1_pT", 130, 0, 130) h_nD_1_pT.SetLineColor(ROOT.kBlue) h_nD_1_pT.SetLineWidth(2) h_nD_1_pT.SetLineStyle(1) h_nD_1_pZ = ROOT.TH1F("h_nD_1_pZ", "h_nD_1_pZ", 130, 0, 130) h_nD_1_pZ.SetLineColor(ROOT.kBlue) h_nD_1_pZ.SetLineWidth(2) h_nD_1_pZ.SetLineStyle(1) h_nD_1_Eta = ROOT.TH1F("h_nD_1_Eta", "h_nD_1_Eta", 100,-5,5) h_nD_1_Eta.SetLineColor(ROOT.kBlue) h_nD_1_Eta.SetLineWidth(2) h_nD_1_Eta.SetLineStyle(1) h_nD_1_Phi = ROOT.TH1F("h_nD_1_Phi", "h_nD_1_Phi", 80,-4,4) h_nD_1_Phi.SetLineColor(ROOT.kBlue) h_nD_1_Phi.SetLineWidth(2) h_nD_1_Phi.SetLineStyle(1) #h_nD_2_pT_dummy = ROOT.TH1F("h_nD_2_pT_dummy", "h_nD_2_pT_dummy", 100, 0, 100) #h_nD_2_pT_dummy.SetYTitle("Fraction of events / 1 GeV") #h_nD_2_pT_dummy.SetTitleOffset(1.35, "Y") #h_nD_2_pT_dummy.SetXTitle("p_{T nD_2} [GeV]") #h_nD_2_pT_dummy.SetMaximum( 0.01 ) # #h_nD_2_p_dummy = ROOT.TH1F("h_nD_2_p_dummy", "h_nD_2_p_dummy", 100, 0, 100) #h_nD_2_p_dummy.SetYTitle("Fraction of events / 1 GeV") #h_nD_2_p_dummy.SetTitleOffset(1.35, "Y") #h_nD_2_p_dummy.SetXTitle("p_{nD_2} [GeV]") #h_nD_2_p_dummy.SetMaximum( 0.01 ) # #h_nD_2_M_dummy = ROOT.TH1F("h_nD_2_M_dummy", "h_nD_2_M_dummy", 20, 0, 2) #h_nD_2_M_dummy.SetYTitle("Fraction of events / 1 GeV") #h_nD_2_M_dummy.SetTitleOffset(1.35, "Y") #h_nD_2_M_dummy.SetXTitle("m_{nD_2} [GeV]") #h_nD_2_M_dummy.SetMaximum( 1.2 ) h_nD_2_p = ROOT.TH1F("h_nD_2_p", "h_nD_2_p", 130, 0, 130) h_nD_2_p.SetLineColor(ROOT.kRed) h_nD_2_p.SetLineWidth(2) h_nD_2_p.SetLineStyle(1) #h_nD_2_M = ROOT.TH1F("h_nD_2_M", "h_nD_2_M", 20, 0.05, 2.05) #h_nD_2_M.SetLineColor(ROOT.kRed) #h_nD_2_M.SetLineWidth(2) #h_nD_2_M.SetLineStyle(1) h_nD_2_pT = ROOT.TH1F("h_nD_2_pT", "h_nD_2_pT", 130, 0, 130) h_nD_2_pT.SetLineColor(ROOT.kRed) h_nD_2_pT.SetLineWidth(2) h_nD_2_pT.SetLineStyle(1) h_gammaD_1_pT_dummy = ROOT.TH1F("h_gammaD_1_pT_dummy", "h_gammaD_1_pT_dummy", 100, 0, 100) h_gammaD_1_pT_dummy.SetYTitle("Fraction of events / 1 GeV") h_gammaD_1_pT_dummy.SetTitleOffset(1.35, "Y") h_gammaD_1_pT_dummy.SetXTitle("p_{T} of #gamma_{D} [GeV]") h_gammaD_1_pT_dummy.SetMaximum( 0.1 ) h_nD_2_pZ = ROOT.TH1F("h_nD_2_pZ", "h_nD_2_pZ", 130, 0, 130) h_nD_2_pZ.SetLineColor(ROOT.kRed) h_nD_2_pZ.SetLineWidth(2) h_nD_2_pZ.SetLineStyle(1) h_gammaD_1_pZ_dummy = ROOT.TH1F("h_gammaD_1_pZ_dummy", "h_gammaD_1_pZ_dummy", 100, 0, 100) h_gammaD_1_pZ_dummy.SetYTitle("Fraction of events / 1 GeV") h_gammaD_1_pZ_dummy.SetTitleOffset(1.35, "Y") h_gammaD_1_pZ_dummy.SetXTitle("|p_{Z}| of #gamma_{D} [GeV]") h_gammaD_1_pZ_dummy.SetMaximum( 0.1 ) h_nD_2_Eta = ROOT.TH1F("h_nD_2_Eta", "h_nD_2_Eta", 100,-5,5) h_nD_2_Eta.SetLineColor(ROOT.kRed) h_nD_2_Eta.SetLineWidth(2) h_nD_2_Eta.SetLineStyle(1) h_gammaD_1_Eta_dummy = ROOT.TH1F("h_gammaD_1_Eta_dummy", "h_gammaD_1_Eta_dummy",100,-5,5) h_gammaD_1_Eta_dummy.SetYTitle("Fraction of events / 0.1") h_gammaD_1_Eta_dummy.SetTitleOffset(1.35, "Y") h_gammaD_1_Eta_dummy.SetXTitle("#eta of #gamma_{D}") h_gammaD_1_Eta_dummy.SetMaximum( 0.1 ) h_nD_2_Phi = ROOT.TH1F("h_nD_2_Phi", "h_nD_2_Phi", 80,-4,4) h_nD_2_Phi.SetLineColor(ROOT.kRed) h_nD_2_Phi.SetLineWidth(2) h_nD_2_Phi.SetLineStyle(1) h_gammaD_1_Phi_dummy = ROOT.TH1F("h_gammaD_1_Phi_dummy", "h_gammaD_1_Phi_dummy",80,-4,4 ) h_gammaD_1_Phi_dummy.SetYTitle("Fraction of events / 0.1 rad") h_gammaD_1_Phi_dummy.SetTitleOffset(1.35, "Y") h_gammaD_1_Phi_dummy.SetXTitle("#phi of #gamma_{D} [rad]") h_gammaD_1_Phi_dummy.SetMaximum( 0.05 ) h_gammaD_1_p_dummy = ROOT.TH1F("h_gammaD_1_p_dummy", "h_gammaD_1_p_dummy", 100, 0, 100) h_gammaD_1_p_dummy.SetYTitle("Fraction of events / 1 GeV") h_gammaD_1_p_dummy.SetTitleOffset(1.35, "Y") h_gammaD_1_p_dummy.SetXTitle("p of #gamma_{D} [GeV]") h_gammaD_1_p_dummy.SetMaximum( 0.1 ) h_gammaD_1_M_dummy = ROOT.TH1F("h_gammaD_1_M_dummy", "h_gammaD_1_M_dummy", 101, 0.1, 10.1) h_gammaD_1_M_dummy.SetYTitle("Fraction of events / 0.1 GeV") h_gammaD_1_M_dummy.SetTitleOffset(1.35, "Y") h_gammaD_1_M_dummy.SetXTitle("Mass of #gamma_{D} [GeV]") h_gammaD_1_M_dummy.SetMaximum( 1.4 ) h_gammaD_1_p = ROOT.TH1F("h_gammaD_1_p", "h_gammaD_1_p", 100, 0, 100) h_gammaD_1_p.SetLineColor(ROOT.kBlue) h_gammaD_1_p.SetLineWidth(2) h_gammaD_1_p.SetLineStyle(1) h_gammaD_1_M = ROOT.TH1F("h_gammaD_1_M", "h_gammaD_1_M", 101, 0.1, 10.1) h_gammaD_1_M.SetLineColor(ROOT.kBlue) h_gammaD_1_M.SetLineWidth(2) h_gammaD_1_M.SetLineStyle(1) h_gammaD_1_pT = ROOT.TH1F("h_gammaD_1_pT", "h_gammaD_1_pT", 100, 0, 100) h_gammaD_1_pT.SetLineColor(ROOT.kBlue) h_gammaD_1_pT.SetLineWidth(2) h_gammaD_1_pT.SetLineStyle(1) h_gammaD_1_pZ = ROOT.TH1F("h_gammaD_1_pZ", "h_gammaD_1_pZ", 100, 0, 100) h_gammaD_1_pZ.SetLineColor(ROOT.kBlue) h_gammaD_1_pZ.SetLineWidth(2) h_gammaD_1_pZ.SetLineStyle(1) h_gammaD_1_Eta = ROOT.TH1F("h_gammaD_1_Eta", "h_gammaD_1_Eta",100,-5,5) h_gammaD_1_Eta.SetLineColor(ROOT.kBlue) h_gammaD_1_Eta.SetLineWidth(2) h_gammaD_1_Eta.SetLineStyle(1) h_gammaD_1_Phi = ROOT.TH1F("h_gammaD_1_Phi", "h_gammaD_1_Phi", 80,-4,4) h_gammaD_1_Phi.SetLineColor(ROOT.kBlue) h_gammaD_1_Phi.SetLineWidth(2) h_gammaD_1_Phi.SetLineStyle(1) #h_gammaD_2_pT_dummy = ROOT.TH1F("h_gammaD_2_pT_dummy", "h_gammaD_2_pT_dummy", 100, 0, 100) #h_gammaD_2_pT_dummy.SetYTitle("Fraction of events / 1 GeV") #h_gammaD_2_pT_dummy.SetTitleOffset(1.35, "Y") #h_gammaD_2_pT_dummy.SetXTitle("p_{T gammaD_2} [GeV]") #h_gammaD_2_pT_dummy.SetMaximum( 0.01 ) # #h_gammaD_2_p_dummy = ROOT.TH1F("h_gammaD_2_p_dummy", "h_gammaD_2_p_dummy", 100, 0, 100) #h_gammaD_2_p_dummy.SetYTitle("Fraction of events / 1 GeV") #h_gammaD_2_p_dummy.SetTitleOffset(1.35, "Y") #h_gammaD_2_p_dummy.SetXTitle("p_{gammaD_2} [GeV]") #h_gammaD_2_p_dummy.SetMaximum( 0.01 ) # #h_gammaD_2_M_dummy = ROOT.TH1F("h_gammaD_2_M_dummy", "h_gammaD_2_M_dummy", 300, 0, 3) #h_gammaD_2_M_dummy.SetYTitle("Fraction of events / 1 GeV") #h_gammaD_2_M_dummy.SetTitleOffset(1.35, "Y") #h_gammaD_2_M_dummy.SetXTitle("m_{gammaD_2} [GeV]") #h_gammaD_2_M_dummy.SetMaximum( 1.2 ) h_gammaD_2_p = ROOT.TH1F("h_gammaD_2_p", "h_gammaD_2_p", 100, 0, 100) h_gammaD_2_p.SetLineColor(ROOT.kRed) h_gammaD_2_p.SetLineWidth(2) h_gammaD_2_p.SetLineStyle(1) #h_gammaD_2_M = ROOT.TH1F("h_gammaD_2_M", "h_gammaD_2_M", 500, 0.005, 10.005) #h_gammaD_2_M.SetLineColor(ROOT.kRed) #h_gammaD_2_M.SetLineWidth(2) #h_gammaD_2_M.SetLineStyle(1) h_gammaD_2_pT = ROOT.TH1F("h_gammaD_2_pT", "h_gammaD_2_pT", 100, 0, 100) h_gammaD_2_pT.SetLineColor(ROOT.kRed) h_gammaD_2_pT.SetLineWidth(2) h_gammaD_2_pT.SetLineStyle(1) h_gammaD_2_pZ = ROOT.TH1F("h_gammaD_2_pZ", "h_gammaD_2_pZ", 100, 0, 100) h_gammaD_2_pZ.SetLineColor(ROOT.kRed) h_gammaD_2_pZ.SetLineWidth(2) h_gammaD_2_pZ.SetLineStyle(1) h_gammaD_2_Eta = ROOT.TH1F("h_gammaD_2_Eta", "h_gammaD_2_Eta", 100,-5,5) h_gammaD_2_Eta.SetLineColor(ROOT.kRed) h_gammaD_2_Eta.SetLineWidth(2) h_gammaD_2_Eta.SetLineStyle(1) h_gammaD_2_Phi = ROOT.TH1F("h_gammaD_2_Phi", "h_gammaD_2_Phi", 80,-4,4) h_gammaD_2_Phi.SetLineColor(ROOT.kRed) h_gammaD_2_Phi.SetLineWidth(2) h_gammaD_2_Phi.SetLineStyle(1) h_muon_pT_0 = ROOT.TH1F("h_muon_pT_0", "h_muon_pT_0", nBins, binMin, binMax) h_muon_pT_0.SetLineColor(ROOT.kBlue) h_muon_pT_0.SetLineWidth(2) h_muon_pT_0.SetLineStyle(1) h_muon_pT_1 = ROOT.TH1F("h_muon_pT_1", "h_muon_pT_1", nBins, binMin, binMax) h_muon_pT_1.SetLineColor(ROOT.kGreen) h_muon_pT_1.SetLineWidth(2) h_muon_pT_1.SetLineStyle(2) h_muon_pT_2 = ROOT.TH1F("h_muon_pT_2", "h_muon_pT_2", nBins, binMin, binMax) h_muon_pT_2.SetLineColor(ROOT.kRed) h_muon_pT_2.SetLineWidth(2) h_muon_pT_2.SetLineStyle(3) h_muon_pT_3 = ROOT.TH1F("h_muon_pT_3", "h_muon_pT_3", nBins, binMin, binMax) h_muon_pT_3.SetLineColor(ROOT.kBlack) h_muon_pT_3.SetLineWidth(2) h_muon_pT_3.SetLineStyle(4) h_muon_phi_dummy = ROOT.TH1F("h_muon_phi_dummy", "h_muon_phi_dummy", 80, -4, 4) h_muon_phi_dummy.SetYTitle("Fraction of events / 0.1 rad") h_muon_phi_dummy.SetTitleOffset(1.35, "Y") h_muon_phi_dummy.SetXTitle("#phi of #mu [rad]") h_muon_phi_dummy.SetMaximum( 0.1 ) h_muon_phi_0 = ROOT.TH1F("h_muon_phi_0", "h_muon_phi_0", 80, -4, 4) h_muon_phi_0.SetLineColor(ROOT.kBlue) h_muon_phi_0.SetLineWidth(2) h_muon_phi_0.SetLineStyle(1) h_muon_phi_1 = ROOT.TH1F("h_muon_phi_1", "h_muon_phi_1", 80, -4, 4) h_muon_phi_1.SetLineColor(ROOT.kGreen) h_muon_phi_1.SetLineWidth(2) h_muon_phi_1.SetLineStyle(2) h_muon_phi_2 = ROOT.TH1F("h_muon_phi_2", "h_muon_phi_2", 80, -4, 4) h_muon_phi_2.SetLineColor(ROOT.kRed) h_muon_phi_2.SetLineWidth(2) h_muon_phi_2.SetLineStyle(3) h_muon_phi_3 = ROOT.TH1F("h_muon_phi_3", "h_muon_phi_3", 80, -4, 4) h_muon_phi_3.SetLineColor(ROOT.kBlack) h_muon_phi_3.SetLineWidth(2) h_muon_phi_3.SetLineStyle(4) h_muon_p_dummy = ROOT.TH1F("h_muon_p_dummy", "h_muon_p_dummy", 125, 0, 125) h_muon_p_dummy.SetYTitle("Fraction of events / 1 GeV") h_muon_p_dummy.SetTitleOffset(1.35, "Y") h_muon_p_dummy.SetXTitle("p of #mu [GeV]") h_muon_p_dummy.SetMaximum( 0.2 ) h_muon_p_0 = ROOT.TH1F("h_muon_p_0", "h_muon_p_0", 125, 0, 125) h_muon_p_0.SetLineColor(ROOT.kBlue) h_muon_p_0.SetLineWidth(2) h_muon_p_0.SetLineStyle(1) h_muon_p_1 = ROOT.TH1F("h_muon_p_1", "h_muon_p_1", 125, 0, 125) h_muon_p_1.SetLineColor(ROOT.kGreen) h_muon_p_1.SetLineWidth(2) h_muon_p_1.SetLineStyle(2) h_muon_p_2 = ROOT.TH1F("h_muon_p_2", "h_muon_p_2", 125, 0, 125) h_muon_p_2.SetLineColor(ROOT.kRed) h_muon_p_2.SetLineWidth(2) h_muon_p_2.SetLineStyle(3) h_muon_p_3 = ROOT.TH1F("h_muon_p_3", "h_muon_p_3", 125, 0, 125) h_muon_p_3.SetLineColor(ROOT.kBlack) h_muon_p_3.SetLineWidth(2) h_muon_p_3.SetLineStyle(125) h_muon_pZ_0 = ROOT.TH1F("h_muon_pZ_0", "h_muon_pZ_0", 125, 0, 125) h_muon_pZ_0.SetLineColor(ROOT.kBlue) h_muon_pZ_0.SetLineWidth(2) h_muon_pZ_0.SetLineStyle(1) h_muon_pZ_1 = ROOT.TH1F("h_muon_pZ_1", "h_muon_pZ_1", 125, 0, 125) h_muon_pZ_1.SetLineColor(ROOT.kGreen) h_muon_pZ_1.SetLineWidth(2) h_muon_pZ_1.SetLineStyle(2) h_muon_pZ_2 = ROOT.TH1F("h_muon_pZ_2", "h_muon_pZ_2", 125, 0, 125) h_muon_pZ_2.SetLineColor(ROOT.kRed) h_muon_pZ_2.SetLineWidth(2) h_muon_pZ_2.SetLineStyle(3) h_muon_pZ_3 = ROOT.TH1F("h_muon_pZ_3", "h_muon_pZ_3", 125, 0, 125) h_muon_pZ_3.SetLineColor(ROOT.kBlack) h_muon_pZ_3.SetLineWidth(2) h_muon_pZ_3.SetLineStyle(125) ################################################################################ # eta of muons ################################################################################ nBins = 60 binMin = -3.0 binMax = 3.0 yMax = 0.045 h_muon_eta_dummy = ROOT.TH1F("h_muon_eta_dummy", "h_muon_eta_dummy", 100, -5, 5) h_muon_eta_dummy.SetYTitle("Fraction of events / 0.1") h_muon_eta_dummy.GetYaxis().SetNdivisions(508); h_muon_eta_dummy.SetTitleOffset(1.35, "Y") h_muon_eta_dummy.SetXTitle("#eta of #mu") h_muon_eta_dummy.SetMaximum( yMax ) h_muon_eta_0 = ROOT.TH1F("h_muon_eta_0", "h_muon_eta_0", 100,-5,5) h_muon_eta_0.SetLineColor(ROOT.kBlue) h_muon_eta_0.SetLineWidth(2) h_muon_eta_0.SetLineStyle(1) h_muon_eta_1 = ROOT.TH1F("h_muon_eta_1", "h_muon_eta_1", 100,-5,5) h_muon_eta_1.SetLineColor(ROOT.kGreen) h_muon_eta_1.SetLineWidth(2) h_muon_eta_1.SetLineStyle(2) h_muon_eta_2 = ROOT.TH1F("h_muon_eta_2", "h_muon_eta_2", 100,-5,5) h_muon_eta_2.SetLineColor(ROOT.kRed) h_muon_eta_2.SetLineWidth(2) h_muon_eta_2.SetLineStyle(3) h_muon_eta_3 = ROOT.TH1F("h_muon_eta_3", "h_muon_eta_3", 100,-5,5) h_muon_eta_3.SetLineColor(ROOT.kBlack) h_muon_eta_3.SetLineWidth(2) h_muon_eta_3.SetLineStyle(4) ################################################################################ # mass of dimuons ################################################################################ nBins = 125 binMin = 0.0 binMax = 125.0 yMax = 0.4 #h_dimuon_m_dummy = ROOT.TH1F("h_dimuon_m_dummy", "h_dimuon_m_dummy", nBins, binMin, binMax) #h_dimuon_m_dummy.SetYTitle("Fraction of events / 1 GeV") #h_dimuon_m_dummy.GetYaxis().SetNdivisions(508); #h_dimuon_m_dummy.SetTitleOffset(1.35, "Y") #h_dimuon_m_dummy.SetXTitle("m_{#mu#mu} [GeV]") #h_dimuon_m_dummy.SetMaximum( 1.2 ) # #h_dimuon_m_0 = ROOT.TH1F("h_dimuon_m_0", "h_dimuon_m_0", nBins, binMin, binMax) #h_dimuon_m_0.SetLineColor(ROOT.kBlue) #h_dimuon_m_0.SetLineWidth(2) #h_dimuon_m_0.SetLineStyle(1) # #h_dimuon_m_1 = ROOT.TH1F("h_dimuon_m_1", "h_dimuon_m_1", nBins, binMin, binMax) #h_dimuon_m_1.SetLineColor(ROOT.kGreen) #h_dimuon_m_1.SetLineWidth(2) #h_dimuon_m_1.SetLineStyle(2) # #h_dimuon_m_2 = ROOT.TH1F("h_dimuon_m_2", "h_dimuon_m_2", nBins, binMin, binMax) #h_dimuon_m_2.SetLineColor(ROOT.kRed) #h_dimuon_m_2.SetLineWidth(2) #h_dimuon_m_2.SetLineStyle(3) # #h_dimuon_m_3 = ROOT.TH1F("h_dimuon_m_3", "h_dimuon_m_3", nBins, binMin, binMax) #h_dimuon_m_3.SetLineColor(ROOT.kBlack) #h_dimuon_m_3.SetLineWidth(2) #h_dimuon_m_3.SetLineStyle(4) # #h_dimuon_m_log_dummy = ROOT.TH1F("h_dimuon_m_log_dummy", "h_dimuon_m_log_dummy", nBins, binMin, binMax) #h_dimuon_m_log_dummy.SetYTitle("Fraction of events / 1 GeV") #h_dimuon_m_log_dummy.GetYaxis().SetNdivisions(508); #h_dimuon_m_log_dummy.SetTitleOffset(1.35, "Y") #h_dimuon_m_log_dummy.SetXTitle("m_{#mu#mu} [GeV]") #h_dimuon_m_log_dummy.SetMaximum( 1.2 ) # #h_dimuon_m_log_0 = ROOT.TH1F("h_dimuon_m_log_0", "h_dimuon_m_log_0", nBins, binMin, binMax) #h_dimuon_m_log_0.SetLineColor(ROOT.kBlue) #h_dimuon_m_log_0.SetLineWidth(2) #h_dimuon_m_log_0.SetLineStyle(1) # #h_dimuon_m_log_1 = ROOT.TH1F("h_dimuon_m_log_1", "h_dimuon_m_log_1", nBins, binMin, binMax) #h_dimuon_m_log_1.SetLineColor(ROOT.kGreen) #h_dimuon_m_log_1.SetLineWidth(2) #h_dimuon_m_log_1.SetLineStyle(2) # #h_dimuon_m_log_2 = ROOT.TH1F("h_dimuon_m_log_2", "h_dimuon_m_log_2", nBins, binMin, binMax) #h_dimuon_m_log_2.SetLineColor(ROOT.kRed) #h_dimuon_m_log_2.SetLineWidth(2) #h_dimuon_m_log_2.SetLineStyle(3) # #h_dimuon_m_log_3 = ROOT.TH1F("h_dimuon_m_log_3", "h_dimuon_m_log_3", nBins, binMin, binMax) #h_dimuon_m_log_3.SetLineColor(ROOT.kBlack) #h_dimuon_m_log_3.SetLineWidth(2) #h_dimuon_m_log_3.SetLineStyle(4) # #h_dimuon_m_real_fake_dummy = ROOT.TH1F("h_dimuon_m_real_fake_dummy", "h_dimuon_m_real_fake_dummy", nBins, binMin, binMax) #h_dimuon_m_real_fake_dummy.SetYTitle("Fraction of events / 1 GeV") #h_dimuon_m_real_fake_dummy.GetYaxis().SetNdivisions(508); #h_dimuon_m_real_fake_dummy.SetTitleOffset(1.35, "Y") #h_dimuon_m_real_fake_dummy.SetXTitle("m_{#mu#mu} [GeV]") #h_dimuon_m_real_fake_dummy.SetMaximum( 1.2 ) # #h_dimuon_m_real_fake_0 = ROOT.TH1F("h_dimuon_m_real_fake_0", "h_dimuon_m_real_fake_0", nBins, binMin, binMax) #h_dimuon_m_real_fake_0.SetLineColor(ROOT.kRed) #h_dimuon_m_real_fake_0.SetLineWidth(2) #h_dimuon_m_real_fake_0.SetLineStyle(1) # #h_dimuon_m_real_fake_1 = ROOT.TH1F("h_dimuon_m_real_fake_1", "h_dimuon_m_real_fake_1", nBins, binMin, binMax) #h_dimuon_m_real_fake_1.SetLineColor(ROOT.kBlue) #h_dimuon_m_real_fake_1.SetLineWidth(2) #h_dimuon_m_real_fake_1.SetLineStyle(2) # #h_dimuon_m_real_fake_log_dummy = ROOT.TH1F("h_dimuon_m_real_fake_log_dummy", "h_dimuon_m_real_fake_log_dummy", nBins, binMin, binMax) #h_dimuon_m_real_fake_log_dummy.SetYTitle("Fraction of events / 1 GeV") #h_dimuon_m_real_fake_log_dummy.GetYaxis().SetNdivisions(508); #h_dimuon_m_real_fake_log_dummy.SetTitleOffset(1.35, "Y") #h_dimuon_m_real_fake_log_dummy.SetXTitle("m_{#mu#mu} [GeV]") #h_dimuon_m_real_fake_log_dummy.SetMaximum( 1.2 ) # #h_dimuon_m_real_fake_log_0 = ROOT.TH1F("h_dimuon_m_real_fake_log_0", "h_dimuon_m_real_fake_log_0", nBins, binMin, binMax) #h_dimuon_m_real_fake_log_0.SetLineColor(ROOT.kRed) #h_dimuon_m_real_fake_log_0.SetLineWidth(2) #h_dimuon_m_real_fake_log_0.SetLineStyle(1) # #h_dimuon_m_real_fake_log_1 = ROOT.TH1F("h_dimuon_m_real_fake_log_1", "h_dimuon_m_real_fake_log_1", nBins, binMin, binMax) #h_dimuon_m_real_fake_log_1.SetLineColor(ROOT.kBlue) #h_dimuon_m_real_fake_log_1.SetLineWidth(2) #h_dimuon_m_real_fake_log_1.SetLineStyle(2) ######################### h_dimuon_m_fake_log_dummy = ROOT.TH1F("h_dimuon_m_fake_log_dummy", "h_dimuon_m_fake_log_dummy", 1250, 0, 125) h_dimuon_m_fake_log_dummy.SetYTitle("Fraction of events / 0.1 GeV") h_dimuon_m_fake_log_dummy.GetYaxis().SetNdivisions(508); h_dimuon_m_fake_log_dummy.SetTitleOffset(1.4, "Y") h_dimuon_m_fake_log_dummy.SetXTitle("Mass of Fake #mu#mu [GeV]") h_dimuon_m_fake_log_dummy.SetMaximum( 1 ) h_dimuon_m_fake_log_0 = ROOT.TH1F("h_dimuon_m_fake_log_0", "h_dimuon_m_fake_log_0", 1250, 0, 125) h_dimuon_m_fake_log_0.SetLineColor(ROOT.kRed) h_dimuon_m_fake_log_0.SetLineWidth(2) h_dimuon_m_fake_log_0.SetLineStyle(1) h_dimuon_m_fake_dummy = ROOT.TH1F("h_dimuon_m_fake_dummy", "h_dimuon_m_fake_dummy", nBins, binMin, binMax) h_dimuon_m_fake_dummy.SetYTitle("Fraction of events / 1 GeV") h_dimuon_m_fake_dummy.GetYaxis().SetNdivisions(508); h_dimuon_m_fake_dummy.SetTitleOffset(1.35, "Y") h_dimuon_m_fake_dummy.SetXTitle("Mass of Fake #mu#mu [GeV]") h_dimuon_m_fake_dummy.SetMaximum( 1.2 ) h_dimuon_m_fake_0 = ROOT.TH1F("h_dimuon_m_fake_0", "h_dimuon_m_fake_0", nBins, binMin, binMax) h_dimuon_m_fake_0.SetLineColor(ROOT.kRed) h_dimuon_m_fake_0.SetLineWidth(2) h_dimuon_m_fake_0.SetLineStyle(1) ################################################################################ # mass of 2 selected dimuons ################################################################################ m_min = 0.2113 m_max = 3.5536 m_bins = 66 h_m1_vs_m2 = ROOT.TH2F("h_m1_vs_m2", "h_m1_vs_m2", m_bins, m_min, m_max, m_bins, m_min, m_max) h_m1_vs_m2.SetYTitle("m_{1#mu#mu} [GeV]") h_m1_vs_m2.SetTitleOffset(1.3, "Y") h_m1_vs_m2.SetXTitle("m_{2#mu#mu} [GeV]") h_m1 = ROOT.TH1F("h_m1", "h_m1", 101, 0.1, 10.1) h_m1.SetLineColor(ROOT.kRed) h_m1.SetLineWidth(2) h_m1.SetLineStyle(1) h_m2 = ROOT.TH1F("h_m2", "h_m2", 101, 0.1, 10.1) h_m2.SetYTitle("Events / 0.1 GeV") h_m2.SetXTitle("m_{#mu#mu} [GeV]") h_m2.SetTitleOffset(1.35, "Y") h_m2.SetLineColor(ROOT.kBlue) h_m2.SetLineWidth(2) h_m2.SetLineStyle(1) h_m2.SetMaximum(110000) h_dimuon_1_pT_dummy = ROOT.TH1F("h_dimuon_1_pT_dummy", "h_dimuon_1_pT_dummy", 100, 0, 100) h_dimuon_1_pT_dummy.SetYTitle("Fraction of events / 1 GeV") h_dimuon_1_pT_dummy.SetTitleOffset(1.35, "Y") h_dimuon_1_pT_dummy.SetXTitle("p_{T} of #mu#mu [GeV]") h_dimuon_1_pT_dummy.SetMaximum( 0.1 ) h_dimuon_1_pZ_dummy = ROOT.TH1F("h_dimuon_1_pZ_dummy", "h_dimuon_1_pZ_dummy", 100, 0, 100) h_dimuon_1_pZ_dummy.SetYTitle("Fraction of events / 1 GeV") h_dimuon_1_pZ_dummy.SetTitleOffset(1.35, "Y") h_dimuon_1_pZ_dummy.SetXTitle("|p_{Z}| of #mu#mu [GeV]") h_dimuon_1_pZ_dummy.SetMaximum( 0.1 ) h_dimuon_1_Eta_dummy = ROOT.TH1F("h_dimuon_1_Eta_dummy", "h_dimuon_1_Eta_dummy",100,-5,5) h_dimuon_1_Eta_dummy.SetYTitle("Fraction of events / 0.1") h_dimuon_1_Eta_dummy.SetTitleOffset(1.35, "Y") h_dimuon_1_Eta_dummy.SetXTitle("#eta of #mu#mu") h_dimuon_1_Eta_dummy.SetMaximum( 0.1 ) h_dimuon_1_Phi_dummy = ROOT.TH1F("h_dimuon_1_Phi_dummy", "h_dimuon_1_Phi_dummy",80,-4,4 ) h_dimuon_1_Phi_dummy.SetYTitle("Fraction of events / 0.1 rad") h_dimuon_1_Phi_dummy.SetTitleOffset(1.35, "Y") h_dimuon_1_Phi_dummy.SetXTitle("#phi of #mu#mu [rad]") h_dimuon_1_Phi_dummy.SetMaximum( 0.05 ) h_dimuon_1_p_dummy = ROOT.TH1F("h_dimuon_1_p_dummy", "h_dimuon_1_p_dummy", 100, 0, 100) h_dimuon_1_p_dummy.SetYTitle("Fraction of events / 1 GeV") h_dimuon_1_p_dummy.SetTitleOffset(1.35, "Y") h_dimuon_1_p_dummy.SetXTitle("p of #mu#mu [GeV]") h_dimuon_1_p_dummy.SetMaximum( 0.1 ) h_dimuon_1_M_dummy = ROOT.TH1F("h_dimuon_1_M_dummy", "h_dimuon_1_M_dummy", 50, 0.5, 10.005) h_dimuon_1_M_dummy.SetYTitle("Fraction of events / 0.2 GeV") h_dimuon_1_M_dummy.SetTitleOffset(1.35, "Y") h_dimuon_1_M_dummy.SetXTitle("Mass of #mu#mu [GeV]") h_dimuon_1_M_dummy.SetMaximum( 1.4 ) h_dimuon_1_p = ROOT.TH1F("h_dimuon_1_p", "h_dimuon_1_p", 100, 0, 100) h_dimuon_1_p.SetLineColor(ROOT.kBlue) h_dimuon_1_p.SetLineWidth(2) h_dimuon_1_p.SetLineStyle(1) h_dimuon_1_M = ROOT.TH1F("h_dimuon_1_M", "h_dimuon_1_M", 500, 0.005, 10.005) h_dimuon_1_M.SetLineColor(ROOT.kBlue) h_dimuon_1_M.SetLineWidth(2) h_dimuon_1_M.SetLineStyle(1) h_dimuon_1_pT = ROOT.TH1F("h_dimuon_1_pT", "h_dimuon_1_pT", 100, 0, 100) h_dimuon_1_pT.SetLineColor(ROOT.kBlue) h_dimuon_1_pT.SetLineWidth(2) h_dimuon_1_pT.SetLineStyle(1) h_dimuon_1_pZ = ROOT.TH1F("h_dimuon_1_pZ", "h_dimuon_1_pZ", 100, 0, 100) h_dimuon_1_pZ.SetLineColor(ROOT.kBlue) h_dimuon_1_pZ.SetLineWidth(2) h_dimuon_1_pZ.SetLineStyle(1) h_dimuon_1_Eta = ROOT.TH1F("h_dimuon_1_Eta", "h_dimuon_1_Eta",100,-5,5) h_dimuon_1_Eta.SetLineColor(ROOT.kBlue) h_dimuon_1_Eta.SetLineWidth(2) h_dimuon_1_Eta.SetLineStyle(1) h_dimuon_1_Phi = ROOT.TH1F("h_dimuon_1_Phi", "h_dimuon_1_Phi", 80,-4,4) h_dimuon_1_Phi.SetLineColor(ROOT.kBlue) h_dimuon_1_Phi.SetLineWidth(2) h_dimuon_1_Phi.SetLineStyle(1) h_dimuon_2_p = ROOT.TH1F("h_dimuon_2_p", "h_dimuon_2_p", 100, 0, 100) h_dimuon_2_p.SetLineColor(ROOT.kRed) h_dimuon_2_p.SetLineWidth(2) h_dimuon_2_p.SetLineStyle(1) h_dimuon_2_pT = ROOT.TH1F("h_dimuon_2_pT", "h_dimuon_2_pT", 100, 0, 100) h_dimuon_2_pT.SetLineColor(ROOT.kRed) h_dimuon_2_pT.SetLineWidth(2) h_dimuon_2_pT.SetLineStyle(1) h_dimuon_2_pZ = ROOT.TH1F("h_dimuon_2_pZ", "h_dimuon_2_pZ", 100, 0, 100) h_dimuon_2_pZ.SetLineColor(ROOT.kRed) h_dimuon_2_pZ.SetLineWidth(2) h_dimuon_2_pZ.SetLineStyle(1) h_dimuon_2_Eta = ROOT.TH1F("h_dimuon_2_Eta", "h_dimuon_2_Eta", 100,-5,5) h_dimuon_2_Eta.SetLineColor(ROOT.kRed) h_dimuon_2_Eta.SetLineWidth(2) h_dimuon_2_Eta.SetLineStyle(1) h_dimuon_2_Phi = ROOT.TH1F("h_dimuon_2_Phi", "h_dimuon_2_Phi", 80,-4,4) h_dimuon_2_Phi.SetLineColor(ROOT.kRed) h_dimuon_2_Phi.SetLineWidth(2) h_dimuon_2_Phi.SetLineStyle(1) ################################################################################ # BAM Functions ################################################################################ def plotOverflow(hist): name = hist.GetName() title = hist.GetTitle() nx = hist.GetNbinsX()+1 x1 = hist.GetBinLowEdge(1) bw = hist.GetBinWidth(nx) x2 = hist.GetBinLowEdge(nx)+bw htmp = ROOT.TH1F(name, title, nx, x1, x2) for i in range(1, nx): htmp.Fill(htmp.GetBinCenter(i), hist.GetBinContent(i)) htmp.Fill(hist.GetNbinsX()-1, hist.GetBinContent(0)) htmp.SetEntries(hist.GetEntries()) htmp.SetLineColor(hist.GetLineColor()) htmp.SetLineWidth(hist.GetLineWidth()) htmp.SetLineStyle(hist.GetLineStyle()) htmp.DrawNormalized("same") return def integral(hist): eachBinWidth = hist.GetBinWidth(hist.GetNbinsX()+1) #print "Begin Integral" #print eachBinWidth runningSum = 0 for i in range(0, hist.GetNbinsX()+1): area = eachBinWidth * hist.GetBinContent(i) runningSum = runningSum + area #print i #print area return runningSum def getEta(pz, p): output = atanh(pz/p) return output def scaleAxisY(hist, dummy): normFactor = hist.Integral() max = hist.GetBinContent(hist.GetMaximumBin()) / normFactor scale = 1.8 newMax = scale*max dummy.SetMaximum(newMax) def scaleAxisYcT(hist, dummy): normFactor = integral(hist) max = hist.GetBinContent(hist.GetMaximumBin()) / normFactor scale = 1.8 newMax = scale*max dummy.SetMaximum(newMax) ################################################################################ # Loop over events ################################################################################ nEvents = 0 isEvent = False nEventsOK = 0 for line in f: if line == '<event>\n': isEvent = True isEvent = True nEvents = nEvents + 1 nLinesInEvent = 0 nParticlesInEvent = 0 muons = [] dimuons = [] DimuonIndex1 = [] DimuonIndex2 = [] bamDimuons = [] FakeIndex1 = [] FakeIndex2 = [] FakeDimuons = [] lifetimes = [] higgs = [] neutralinos = [] darkNeutralinos = [] gammaDs = [] n1PlotCounter = 0 gammaDPlotCounter = 0 nDPlotCounter = 0 if nEvents > nExit: break continue if line == '</event>\n': isEvent = False continue if isEvent == True: nLinesInEvent = nLinesInEvent + 1 #*************************************************************************** # first line with common event information #*************************************************************************** if nLinesInEvent == 1: word_n = 0 # print "I", line for word in line.split(): word_n = word_n + 1 if word_n == 1: NUP = int(word) # number of particles in the event if word_n == 2: IDPRUP = int(word) # process type if word_n == 3: XWGTUP = float(word) # event weight if word_n == 4: SCALUP = float(word) # factorization scale Q if word_n == 5: AQEDUP = float(word) # the QED coupling alpha_em if word_n == 6: AQCDUP = float(word) # the QCD coupling alpha_s if word_n > 6: print "Warning! Wrong common event information", line #*************************************************************************** # line with particle information #*************************************************************************** if nLinesInEvent >= 2: nParticlesInEvent = nParticlesInEvent + 1 word_n = 0 # print "P", line for word in line.split(): word_n = word_n + 1 if word_n == 1: IDUP = int(word) # particle PDG identity code if word_n == 2: ISTUP = int(word) # status code if word_n == 3: MOTHUP1 = int(word) # position of the first mother of particle if word_n == 4: MOTHUP2 = int(word) # position of the last mother of particle if word_n == 5: ICOLUP1 = int(word) # tag for the colour flow info if word_n == 6: ICOLUP2 = int(word) # tag for the colour flow info if word_n == 7: PUP1 = float(word) # px in GeV if word_n == 8: PUP2 = float(word) # py in GeV if word_n == 9: PUP3 = float(word) # pz in GeV if word_n == 10: PUP4 = float(word) # E in GeV if word_n == 11: PUP5 = float(word) # m in GeV if word_n == 12: VTIMUP = float(word) # invariant lifetime ctau in mm if word_n == 13: SPINUP = float(word) # cosine of the angle between the spin vector of a particle and its three-momentum if word_n > 13: print "Warning! Wrong particle line", line if abs(IDUP) == muonID: if IDUP > 0: q = -1 if IDUP < 0: q = 1 v4 = ROOT.TLorentzVector(PUP1, PUP2, PUP3, PUP4) muons.append(( q, v4.Px(), v4.Py(), v4.Pz(), v4.E(), v4.M(), v4.Pt(), v4.Eta(), v4.Phi(), MOTHUP1 )) if abs(IDUP) == higgsID: if IDUP > 0: q = 0 if IDUP < 0: q = 0 vHiggs = ROOT.TLorentzVector(PUP1, PUP2, PUP3, PUP4) higgs.append((q, vHiggs.Px(), vHiggs.Py(), vHiggs.Pz(), vHiggs.E(), vHiggs.M(), vHiggs.Pt(), vHiggs.Eta(), vHiggs.Phi() )) h_higgs_pT.Fill( higgs[len(higgs)-1][6] ) h_higgs_M.Fill( higgs[len(higgs)-1][5] ) h_higgs_p.Fill( sqrt( higgs[len(higgs)-1][1]*higgs[len(higgs)-1][1] + higgs[len(higgs)-1][2]*higgs[len(higgs)-1][2] + higgs[len(higgs)-1][3]*higgs[len(higgs)-1][3] ) ) h_higgs_pZ.Fill( fabs(higgs[len(higgs)-1][3]) ) #h_higgs_Eta.Fill( higgs[len(higgs)-1][7] ) h_higgs_Phi.Fill( higgs[len(higgs)-1][8] ) if abs(IDUP) == n1ID: q = 0 vNeutralino = ROOT.TLorentzVector(PUP1, PUP2, PUP3, PUP4) neutralinos.append((q, vNeutralino.Px(), vNeutralino.Py(), vNeutralino.Pz(), vNeutralino.E(), vNeutralino.M(), vNeutralino.Pt(), vNeutralino.Eta(), vNeutralino.Phi() )) if len(neutralinos) == 2 and n1PlotCounter == 0: neutralinos_sorted_pT = sorted(neutralinos, key=itemgetter(6), reverse=True) neutralinos = neutralinos_sorted_pT h_n1_1_pT.Fill( neutralinos[0][6] ) h_n1_2_pT.Fill( neutralinos[1][6] ) h_n1_1_p.Fill( sqrt( neutralinos[0][1]*neutralinos[0][1] + neutralinos[0][2]*neutralinos[0][2] + neutralinos[0][3]*neutralinos[0][3] ) ) h_n1_2_p.Fill( sqrt( neutralinos[1][1]*neutralinos[1][1] + neutralinos[1][2]*neutralinos[1][2] + neutralinos[1][3]*neutralinos[1][3] ) ) h_n1_1_M.Fill( neutralinos[0][5] ) h_n1_1_M.Fill( neutralinos[1][5] ) h_n1_1_pZ.Fill( fabs(neutralinos[0][3]) ) h_n1_2_pZ.Fill( fabs(neutralinos[1][3]) ) h_n1_1_Eta.Fill( getEta(neutralinos[0][3],(sqrt( neutralinos[0][1]*neutralinos[0][1] + neutralinos[0][2]*neutralinos[0][2] + neutralinos[0][3]*neutralinos[0][3] ))) ) h_n1_1_Phi.Fill( neutralinos[0][8] ) h_n1_2_Eta.Fill( getEta(neutralinos[1][3], sqrt( neutralinos[1][1]*neutralinos[1][1] + neutralinos[1][2]*neutralinos[1][2] + neutralinos[1][3]*neutralinos[1][3] )) ) #print "PUP3, PZ, P, ETA:" #print neutralinos[0][7] #print neutralinos[0][3] #print (sqrt( neutralinos[0][1]*neutralinos[0][1] + neutralinos[0][2]*neutralinos[0][2] + neutralinos[0][3]*neutralinos[0][3] )) #print getEta(neutralinos[0][3],(sqrt( neutralinos[0][1]*neutralinos[0][1] + neutralinos[0][2]*neutralinos[0][2] + neutralinos[0][3]*neutralinos[0][3] ))) h_n1_2_Phi.Fill( neutralinos[1][8] ) n1PlotCounter = 1 if abs(IDUP) == nDID: q = 0 vDarkNeutralino = ROOT.TLorentzVector(PUP1, PUP2, PUP3, PUP4) darkNeutralinos.append((q, vDarkNeutralino.Px(), vDarkNeutralino.Py(), vDarkNeutralino.Pz(), vDarkNeutralino.E(), vDarkNeutralino.M(), vDarkNeutralino.Pt(), vDarkNeutralino.Eta(), vDarkNeutralino.Phi() )) if len(darkNeutralinos) == 2 and nDPlotCounter == 0: darkNeutralinos_sorted_pT = sorted(darkNeutralinos, key=itemgetter(6), reverse=True) darkNeutralinos = darkNeutralinos_sorted_pT h_nD_1_pT.Fill( darkNeutralinos[0][6] ) h_nD_2_pT.Fill( darkNeutralinos[1][6] ) h_nD_1_p.Fill( sqrt( darkNeutralinos[0][1]*darkNeutralinos[0][1] + darkNeutralinos[0][2]*darkNeutralinos[0][2] + darkNeutralinos[0][3]*darkNeutralinos[0][3] ) ) h_nD_2_p.Fill( sqrt( darkNeutralinos[1][1]*darkNeutralinos[1][1] + darkNeutralinos[1][2]*darkNeutralinos[1][2] + darkNeutralinos[1][3]*darkNeutralinos[1][3] ) ) h_nD_1_M.Fill( darkNeutralinos[0][5] ) h_nD_1_M.Fill( darkNeutralinos[1][5] ) h_nD_1_pZ.Fill( fabs(darkNeutralinos[0][3]) ) h_nD_2_pZ.Fill( fabs(darkNeutralinos[1][3]) ) h_nD_1_Eta.Fill( getEta(darkNeutralinos[0][3], sqrt( darkNeutralinos[0][1]*darkNeutralinos[0][1] + darkNeutralinos[0][2]*darkNeutralinos[0][2] + darkNeutralinos[0][3]*darkNeutralinos[0][3] )) ) h_nD_1_Phi.Fill( darkNeutralinos[0][8] ) h_nD_2_Eta.Fill( getEta(darkNeutralinos[1][3], sqrt( darkNeutralinos[1][1]*darkNeutralinos[1][1] + darkNeutralinos[1][2]*darkNeutralinos[1 ][2] + darkNeutralinos[1][3]*darkNeutralinos[1][3] )) ) h_nD_2_Phi.Fill( darkNeutralinos[1][8] ) vectorSum =( ( darkNeutralinos[0][1] + darkNeutralinos[1][1] )*( darkNeutralinos[0][1] + darkNeutralinos[1][1] ) ) + ( (darkNeutralinos[0][2] + darkNeutralinos[1][2])*(darkNeutralinos[0][2] + darkNeutralinos[1][2]) ) Etmiss.Fill(vectorSum) nDPlotCounter = 1 if abs(IDUP) == gammaDID: q = 0 vgammaDs = ROOT.TLorentzVector(PUP1, PUP2, PUP3, PUP4) gammaDs.append(( q, vgammaDs.Px(), vgammaDs.Py(), vgammaDs.Pz(), vgammaDs.E(), vgammaDs.M(), vgammaDs.Pt(), vgammaDs.Eta(), vgammaDs.Phi())) h_gammaD_cT.Fill( VTIMUP ) pmom = sqrt( vgammaDs.Px()*vgammaDs.Px() + vgammaDs.Py()*vgammaDs.Py() + vgammaDs.Pz()*vgammaDs.Pz() ) beta = pmom/(sqrt(vgammaDs.M()*vgammaDs.M() + pmom*pmom )) lorentz = 1/sqrt( 1 - beta*beta ) h_gammaD_cT_lab.Fill( lorentz*VTIMUP ) pmomxy = sqrt( vgammaDs.Px()*vgammaDs.Px() + vgammaDs.Py()*vgammaDs.Py() ) betaxy = pmomxy/sqrt( vgammaDs.M()*vgammaDs.M() + pmomxy*pmomxy ) lorentzxy = 1/sqrt(1- betaxy*betaxy) h_gammaD_cT_XY_lab.Fill( lorentzxy*VTIMUP ) pmomz = sqrt( vgammaDs.Pz()*vgammaDs.Pz() ) betaz = pmomz/sqrt( vgammaDs.M()*vgammaDs.M() + pmomz*pmomz ) lorentzZ = 1/sqrt(1 - betaz*betaz ) h_gammaD_cT_Z_lab.Fill( lorentzZ * VTIMUP ) lifetimes.append( (VTIMUP, vgammaDs.Px(), vgammaDs.Py(), vgammaDs.Pz(), vgammaDs.Pt(), vgammaDs.M() )) if len(gammaDs) == 2 and gammaDPlotCounter == 0: gammaDs_sorted_pT = sorted(gammaDs, key=itemgetter(6), reverse=True) gammaDs = gammaDs_sorted_pT lifetimes_sorted_pT = sorted(lifetimes, key=itemgetter(4), reverse=True) lifetimes = lifetimes_sorted_pT h_gammaD_1_cT.Fill( lifetimes[0][0] ) pmom = sqrt( lifetimes[0][1]*lifetimes[0][1] + lifetimes[0][2]*lifetimes[0][2] + lifetimes[0][3]*lifetimes[0][3] ) beta = pmom/(sqrt(lifetimes[0][5]*lifetimes[0][5] + pmom*pmom )) lorentz = 1/sqrt( 1 - beta*beta ) h_gammaD_1_cT_lab.Fill( lorentz*lifetimes[0][0] ) #print "pmom, beta, lorentz" #print pmom #print beta #print lorentz #print lorentz*lifetimes[0][0] pmomxy = sqrt( lifetimes[0][1]*lifetimes[0][1] + lifetimes[0][2]*lifetimes[0][2] ) betaxy = pmomxy/sqrt( lifetimes[0][5]*lifetimes[0][5] + pmomxy*pmomxy ) lorentzxy = 1/sqrt(1- betaxy*betaxy) h_gammaD_1_cT_XY_lab.Fill( lorentzxy*lifetimes[0][0] ) pmomz = sqrt( lifetimes[0][3]*lifetimes[0][3] ) betaz = pmomz/sqrt( lifetimes[0][5]*lifetimes[0][5] + pmomz*pmomz ) lorentzZ = 1/sqrt(1 - betaz*betaz ) h_gammaD_1_cT_Z_lab.Fill( lorentzZ * lifetimes[0][0] ) h_gammaD_2_cT.Fill( lifetimes[1][0] ) pmom = sqrt( lifetimes[1][1]*lifetimes[1][1] + lifetimes[1][2]*lifetimes[1][2] + lifetimes[1][3]*lifetimes[1][3] ) beta = pmom/(sqrt(lifetimes[1][5]*lifetimes[1][5] + pmom*pmom )) lorentz = 1/sqrt( 1 - beta*beta ) h_gammaD_2_cT_lab.Fill( lorentz*lifetimes[1][0] ) pmomxy = sqrt( lifetimes[1][1]*lifetimes[1][1] + lifetimes[1][2]*lifetimes[1][2] ) betaxy = pmomxy/sqrt( lifetimes[1][5]*lifetimes[1][5] + pmomxy*pmomxy ) lorentzxy = 1/sqrt(1- betaxy*betaxy) h_gammaD_2_cT_XY_lab.Fill( lorentzxy*lifetimes[1][0] ) pmomz = sqrt( lifetimes[1][3]*lifetimes[1][3] ) betaz = pmomz/sqrt( lifetimes[1][5]*lifetimes[1][5] + pmomz*pmomz ) lorentzZ = 1/sqrt(1 - betaz*betaz ) h_gammaD_2_cT_Z_lab.Fill( lorentzZ * lifetimes[1][0] ) h_gammaD_1_pT.Fill( gammaDs[0][6] ) h_gammaD_2_pT.Fill( gammaDs[1][6] ) h_gammaD_1_p.Fill( sqrt( gammaDs[0][1]*gammaDs[0][1] + gammaDs[0][2]*gammaDs[0][2] + gammaDs[0][3]*gammaDs[0][3] ) ) h_gammaD_2_p.Fill( sqrt( gammaDs[1][1]*gammaDs[1][1] + gammaDs[1][2]*gammaDs[1][2] + gammaDs[1][3]*gammaDs[1][3] ) ) h_gammaD_1_M.Fill( gammaDs[0][5] ) h_gammaD_1_M.Fill( gammaDs[1][5] ) h_gammaD_1_pZ.Fill( fabs(gammaDs[0][3]) ) h_gammaD_2_pZ.Fill( fabs(gammaDs[1][3]) ) h_gammaD_1_Eta.Fill( getEta(gammaDs[0][3], sqrt( gammaDs[0][1]*gammaDs[0][1] + gammaDs[0][2]*gammaDs[0][2] + gammaDs[0][3]*gammaDs[0][3] ) ) ) h_gammaD_1_Phi.Fill( gammaDs[0][8] ) h_gammaD_2_Eta.Fill( getEta(gammaDs[1][3], sqrt( gammaDs[1][1]*gammaDs[1][1] + gammaDs[1][2]*gammaDs[1][2] + gammaDs[1][3]*gammaDs[1][3] ) ) ) h_gammaD_2_Phi.Fill( gammaDs[1][8] ) gammaDPlotCounter = 1 if len(muons) == 4: muons_sorted_pT = sorted(muons, key=itemgetter(6), reverse=True) muons = muons_sorted_pT h_muon_pT_0.Fill( muons[0][6] ) h_muon_pT_1.Fill( muons[1][6] ) h_muon_pT_2.Fill( muons[2][6] ) h_muon_pT_3.Fill( muons[3][6] ) h_muon_eta_0.Fill( muons[0][7] ) h_muon_eta_1.Fill( muons[1][7] ) h_muon_eta_2.Fill( muons[2][7] ) h_muon_eta_3.Fill( muons[3][7] ) h_muon_phi_0.Fill( muons[0][8] ) h_muon_phi_1.Fill( muons[1][8] ) h_muon_phi_2.Fill( muons[2][8] ) h_muon_phi_3.Fill( muons[3][8] ) h_muon_p_0.Fill( sqrt( muons[0][1]*muons[0][1] + muons[0][2]*muons[0][2] + muons[0][3]*muons[0][3] ) ) h_muon_p_1.Fill( sqrt( muons[1][1]*muons[1][1] + muons[1][2]*muons[1][2] + muons[1][3]*muons[1][3] ) ) h_muon_p_2.Fill( sqrt( muons[2][1]*muons[2][1] + muons[2][2]*muons[2][2] + muons[2][3]*muons[2][3] ) ) h_muon_p_3.Fill( sqrt( muons[3][1]*muons[3][1] + muons[3][2]*muons[3][2] + muons[3][3]*muons[3][3] ) ) h_muon_pZ_0.Fill( muons[0][3] ) h_muon_pZ_1.Fill( muons[1][3] ) h_muon_pZ_2.Fill( muons[2][3] ) h_muon_pZ_3.Fill( muons[3][3] ) parent = muons[1][9] #this is an arbitrary choice to find real dimuons for i in range(0, len(muons) ): if parent == muons[i][9]: DimuonIndex1.append(i) else: DimuonIndex2.append(i) px1 = muons[DimuonIndex1[0]][1] + muons[DimuonIndex1[1]][1] py1 = muons[DimuonIndex1[0]][2] + muons[DimuonIndex1[1]][2] pz1 = muons[DimuonIndex1[0]][3] + muons[DimuonIndex1[1]][3] e1 = muons[DimuonIndex1[0]][4] + muons[DimuonIndex1[1]][4] px2 = muons[DimuonIndex2[0]][1] + muons[DimuonIndex2[1]][1] py2 = muons[DimuonIndex2[0]][2] + muons[DimuonIndex2[1]][2] pz2 = muons[DimuonIndex2[0]][3] + muons[DimuonIndex2[1]][3] e2 = muons[DimuonIndex2[0]][4] + muons[DimuonIndex2[1]][4] bamV4_1 = ROOT.TLorentzVector(px1, py1, pz1, e1) bamV4_2 = ROOT.TLorentzVector(px2, py2, pz2, e2) bamDimuons.append(( bamV4_1.Px(), bamV4_1.Py(), bamV4_1.Pz(), bamV4_1.E(), bamV4_1.M(), bamV4_1.Pt(), bamV4_1.Eta(), bamV4_1.Phi() )) bamDimuons.append(( bamV4_2.Px(), bamV4_2.Py(), bamV4_2.Pz(), bamV4_2.E(), bamV4_2.M(), bamV4_2.Pt(), bamV4_2.Eta(), bamV4_2.Phi() )) bamDimuons_Sorted_M = sorted(bamDimuons, key=itemgetter(4), reverse=True) bamDimuons = bamDimuons_Sorted_M h_m1_vs_m2.Fill(bamDimuons[0][4],bamDimuons[1][4]) h_m1.Fill(bamDimuons[0][4]) h_m2.Fill(bamDimuons[1][4]) bamDimuons_Sorted_pT = sorted(bamDimuons, key=itemgetter(5), reverse=True) bamDimuons = bamDimuons_Sorted_pT h_dimuon_1_pT.Fill(bamDimuons[0][5]) h_dimuon_2_pT.Fill(bamDimuons[1][5]) h_dimuon_1_pZ.Fill(bamDimuons[0][2]) h_dimuon_2_pZ.Fill(bamDimuons[1][2]) h_dimuon_1_p.Fill(sqrt( bamDimuons[0][0]*bamDimuons[0][0] + bamDimuons[0][1]*bamDimuons[0][1] + bamDimuons[0][2]*bamDimuons[0][2] )) h_dimuon_2_p.Fill(sqrt( bamDimuons[1][0]*bamDimuons[1][0] + bamDimuons[1][1]*bamDimuons[1][1] + bamDimuons[1][2]*bamDimuons[1][2] )) h_dimuon_1_Eta.Fill(bamDimuons[0][6]) h_dimuon_2_Eta.Fill(bamDimuons[1][6]) h_dimuon_1_Phi.Fill(bamDimuons[0][7]) h_dimuon_2_Phi.Fill(bamDimuons[1][7]) parent = muons[1][9] #this is an arbitrary choice to find the fake dimuons charge = muons[1][0] for i in range(0, len(muons) ): if parent != muons[i][9] and charge != muons[i][0]: FakeIndex1.append(i) FakeIndex1.append(1) for j in range(0, len(muons) ): if j != FakeIndex1[0] and j != FakeIndex1[1]: FakeIndex2.append(j) Fakepx1 = muons[FakeIndex1[0]][1] + muons[FakeIndex1[1]][1] Fakepy1 = muons[FakeIndex1[0]][2] + muons[FakeIndex1[1]][2] Fakepz1 = muons[FakeIndex1[0]][3] + muons[FakeIndex1[1]][3] Fakee1 = muons[FakeIndex1[0]][4] + muons[FakeIndex1[1]][4] Fakepx2 = muons[FakeIndex2[0]][1] + muons[FakeIndex2[1]][1] Fakepy2 = muons[FakeIndex2[0]][2] + muons[FakeIndex2[1]][2] Fakepz2 = muons[FakeIndex2[0]][3] + muons[FakeIndex2[1]][3] Fakee2 = muons[FakeIndex2[0]][4] + muons[FakeIndex2[1]][4] fakeV4_1 = ROOT.TLorentzVector(Fakepx1, Fakepy1, Fakepz1, Fakee1) fakeV4_2 = ROOT.TLorentzVector(Fakepx2, Fakepy2, Fakepz2, Fakee2) FakeDimuons.append(( fakeV4_1.Px(), fakeV4_1.Py(), fakeV4_1.Pz(), fakeV4_1.E(), fakeV4_1.M(), fakeV4_1.Pt(), fakeV4_1.Eta(), fakeV4_1.Phi() )) FakeDimuons.append(( fakeV4_2.Px(), fakeV4_2.Py(), fakeV4_2.Pz(), fakeV4_2.E(), fakeV4_2.M(), fakeV4_2.Pt(), fakeV4_2.Eta(), fakeV4_2.Phi() )) h_dimuon_m_fake_log_0.Fill(FakeDimuons[0][4]) h_dimuon_m_fake_log_0.Fill(FakeDimuons[1][4]) h_dimuon_m_fake_0.Fill(FakeDimuons[0][4]) h_dimuon_m_fake_0.Fill(FakeDimuons[1][4]) # is1SelMu17 = False # for i in range(0, len(muons) ): # if muons[i][6] >= 17. and abs(muons[i][7]) <= 0.9: is1SelMu17 = True # # is4SelMu8 = False # nSelMu8 = 0 # for i in range(0, len(muons) ): # if muons[i][6] >= 8. and abs(muons[i][7]) <= 2.4: nSelMu8 = nSelMu8 + 1 # if nSelMu8 == 4: is4SelMu8 = True # # if is1SelMu17 and is4SelMu8: # for i in range(0, len(muons) ): # for j in range(i+1, len(muons) ): # if muons[i][0] * muons[j][0] < 0: # px = muons[i][1] + muons[j][1] # py = muons[i][2] + muons[j][2] # pz = muons[i][3] + muons[j][3] # E = muons[i][4] + muons[j][4] # v4 = ROOT.TLorentzVector(px, py, pz, E) # dimuons.append(( i, j, v4.Px(), v4.Py(), v4.Pz(), v4.E(), v4.M(), v4.Pt(), v4.Eta(), v4.Phi() )) # dimuons_sorted_M = sorted(dimuons, key=itemgetter(6), reverse=True) # dimuons = dimuons_sorted_M # # print "Dimuons:", dimuons # h_dimuon_m_0.Fill( dimuons[0][6] ) # h_dimuon_m_1.Fill( dimuons[1][6] ) # h_dimuon_m_2.Fill( dimuons[2][6] ) # h_dimuon_m_3.Fill( dimuons[3][6] ) # # h_dimuon_m_log_0.Fill( dimuons[0][6] ) # h_dimuon_m_log_1.Fill( dimuons[1][6] ) # h_dimuon_m_log_2.Fill( dimuons[2][6] ) # h_dimuon_m_log_3.Fill( dimuons[3][6] ) # # #print dimuons[0][6] # #print float(mass_GammaD_Legend) # #if dimuons[0][6] > float(mass_GammaD_Legend): print "fake" # #if dimuons[0][6] <= float(mass_GammaD_Legend): print "real" # if dimuons[0][6] > float(mass_GammaD_Legend): h_dimuon_m_real_fake_1.Fill(dimuons[0][6]) # if dimuons[0][6] <= float(mass_GammaD_Legend): h_dimuon_m_real_fake_0.Fill(dimuons[0][6]) # if dimuons[1][6] > float(mass_GammaD_Legend): h_dimuon_m_real_fake_1.Fill(dimuons[1][6]) # if dimuons[1][6] <= float(mass_GammaD_Legend): h_dimuon_m_real_fake_0.Fill(dimuons[1][6]) # if dimuons[2][6] > float(mass_GammaD_Legend): h_dimuon_m_real_fake_1.Fill(dimuons[2][6]) # if dimuons[2][6] <= float(mass_GammaD_Legend): h_dimuon_m_real_fake_0.Fill(dimuons[2][6]) # if dimuons[3][6] > float(mass_GammaD_Legend): h_dimuon_m_real_fake_1.Fill(dimuons[3][6]) # if dimuons[3][6] <= float(mass_GammaD_Legend): h_dimuon_m_real_fake_0.Fill(dimuons[3][6]) # # if dimuons[0][6] > float(mass_GammaD_Legend): h_dimuon_m_real_fake_log_1.Fill(dimuons[0][6]) # if dimuons[0][6] <= float(mass_GammaD_Legend): h_dimuon_m_real_fake_log_0.Fill(dimuons[0][6]) # if dimuons[1][6] > float(mass_GammaD_Legend): h_dimuon_m_real_fake_log_1.Fill(dimuons[1][6]) # if dimuons[1][6] <= float(mass_GammaD_Legend): h_dimuon_m_real_fake_log_0.Fill(dimuons[1][6]) # if dimuons[2][6] > float(mass_GammaD_Legend): h_dimuon_m_real_fake_log_1.Fill(dimuons[2][6]) # if dimuons[2][6] <= float(mass_GammaD_Legend): h_dimuon_m_real_fake_log_0.Fill(dimuons[2][6]) # if dimuons[3][6] > float(mass_GammaD_Legend): h_dimuon_m_real_fake_log_1.Fill(dimuons[3][6]) # if dimuons[3][6] <= float(mass_GammaD_Legend): h_dimuon_m_real_fake_log_0.Fill(dimuons[3][6]) # dimuons5GeV = [] # for i in range(0, len(dimuons)): # # select only dimuons with invariant mass less than 5 GeV # if dimuons[i][6] < 5.0: dimuons5GeV.append( dimuons[i] ) # # nDimuons5GeV = len(dimuons5GeV) # # is2DiMuons = False # nMuJetsContainMu17 = 0 # m_threshold_Mu17_pT = 17.0 # m_threshold_Mu17_eta = 0.9 # m_randomSeed = 1234 # if nDimuons5GeV == 2: # # select only dimuons that do NOT share muons # if dimuons5GeV[0][0] != dimuons5GeV[1][0] and dimuons5GeV[0][0] != dimuons5GeV[1][1] and dimuons5GeV[0][1] != dimuons5GeV[1][1] and dimuons5GeV[0][1] != dimuons5GeV[1][0]: # isDimuon0ContainMu17 = False # if ( muons[ dimuons5GeV[0][0] ][6] > m_threshold_Mu17_pT and muons[ dimuons5GeV[0][0] ][7] < m_threshold_Mu17_eta ) or ( muons[ dimuons5GeV[0][1] ][6] > m_threshold_Mu17_pT and muons[ dimuons5GeV[0][1] ][7] < m_threshold_Mu17_eta ): # isDimuon0ContainMu17 = True # if ( muons[ dimuons5GeV[1][0] ][6] > m_threshold_Mu17_pT and muons[ dimuons5GeV[1][0] ][7] < m_threshold_Mu17_eta ) or ( muons[ dimuons5GeV[1][1] ][6] > m_threshold_Mu17_pT and muons[ dimuons5GeV[1][1] ][7] < m_threshold_Mu17_eta ): # isDimuon1ContainMu17 = True # if isDimuon0ContainMu17 == True and isDimuon1ContainMu17 == False: # is2DiMuons = True # muJetC = dimuons5GeV[0] # muJetF = dimuons5GeV[1] # elif isDimuon0ContainMu17 == False and isDimuon1ContainMu17 == True: # is2DiMuons = True # muJetC = dimuons5GeV[1] # muJetF = dimuons5GeV[0] # elif isDimuon0ContainMu17 == True and isDimuon1ContainMu17 == True: # is2DiMuons = True # if(ROOT.TRandom3(m_randomSeed).Integer(2) == 0): # muJetC = dimuons5GeV[0] # muJetF = dimuons5GeV[1] # else: # muJetC = dimuons5GeV[1] # muJetF = dimuons5GeV[0] # else: # is2DiMuons = False # # is2DiMuonsMassOK = False # if is2DiMuons: # massC = muJetC[6] # massF = muJetF[6] # h_m1_vs_m2.Fill(massC, massF) # h_m1.Fill( massC ) # h_m2.Fill( massF ) # if abs(massC-massF) < (0.13 + 0.065*(massC+massF)/2.0): # is2DiMuonsMassOK = True # # if is2DiMuonsMassOK == True: # nEventsOK = nEventsOK + 1 print "nEvents = ", nEvents print "nEventsOK = ", nEventsOK ################################################################################ # Draw histograms ################################################################################ Etmiss_dummy.Draw() Etmiss.DrawNormalized("same") scaleAxisY(Etmiss,Etmiss_dummy) info.Draw() txtHeader.Draw() cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_nD_EtMiss.pdf") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_nD_EtMiss.png") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_nD_EtMiss.C") h_higgs_pT_dummy.Draw() h_higgs_pT.DrawNormalized("same") info.Draw() txtHeader.Draw() cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_Higgs_pT.pdf") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_Higgs_pT.png") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_Higgs_pT.C") h_higgs_pZ_dummy.Draw() #h_higgs_pZ.DrawNormalized("same") plotOverflow(h_higgs_pZ) scaleAxisY(h_higgs_pZ,h_higgs_pZ_dummy) info.Draw() txtHeader.Draw() cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_Higgs_pZ.pdf") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_Higgs_pZ.png") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_Higgs_pZ.C") #h_higgs_Eta_dummy.Draw() #h_higgs_Eta.DrawNormalized("same") #info.Draw() #txtHeader.Draw() #cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_Higgs_Eta.pdf") #cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_Higgs_Eta.png") #cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_Higgs_Eta.png") h_higgs_Phi_dummy.Draw() h_higgs_Phi.DrawNormalized("same") #scaleAxisY(h_higgs_Phi,h_higgs_Phi_dummy) info.Draw() txtHeader.Draw() cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_Higgs_Phi.pdf") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_Higgs_Phi.png") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_Higgs_Phi.C") cnv.SetLogx() h_higgs_M_dummy.Draw() h_higgs_M_dummy.SetNdivisions(10) h_higgs_M_dummy.GetXaxis().SetMoreLogLabels() h_higgs_M_dummy.Draw("same") h_higgs_M.DrawNormalized("same") h_higgs_M.GetXaxis().SetMoreLogLabels() h_higgs_M.DrawNormalized("same") info.Draw() txtHeader.Draw() h_higgs_M_dummy.SetNdivisions(10) h_higgs_M_dummy.GetXaxis().SetMoreLogLabels() h_higgs_M_dummy.Draw("same") h_higgs_M.DrawNormalized("same") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_Higgs_m.pdf") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_Higgs_m.png") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_Higgs_m.C") cnv.SetLogx(0) h_higgs_p_dummy.Draw() #h_higgs_p.DrawNormalized("same") plotOverflow(h_higgs_p) scaleAxisY(h_higgs_p,h_higgs_p_dummy) info.Draw() txtHeader.Draw() cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_Higgs_p.pdf") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_Higgs_p.png") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_Higgs_p.C") h_n1_1_pT_dummy.Draw() h_n1_1_pT.DrawNormalized("same") h_n1_2_pT.DrawNormalized("same") scaleAxisY(h_n1_1_pT, h_n1_1_pT_dummy) legend = ROOT.TLegend(0.46,0.6744444,0.6955556,0.7644444) legend.SetFillColor(ROOT.kWhite) legend.SetFillStyle(0) legend.SetBorderSize(0) legend.SetTextFont(42) legend.SetTextSize(0.02777778) legend.SetMargin(0.13) legend.AddEntry(h_n1_1_pT,"1st neutralino","L") legend.AddEntry(h_n1_2_pT,"2nd neutralino","L") legend.Draw() info.Draw() txtHeader.Draw() cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_n1_pT.pdf") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_n1_pT.png") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_n1_pT.C") h_n1_1_pZ_dummy.Draw() plotOverflow(h_n1_1_pZ) plotOverflow(h_n1_2_pZ) scaleAxisY(h_n1_1_pZ,h_n1_1_pZ_dummy) #h_n1_1_pZ.DrawNormalized("same") #h_n1_2_pZ.DrawNormalized("same") legend = ROOT.TLegend(0.46,0.6744444,0.6955556,0.7644444) legend.SetFillColor(ROOT.kWhite) legend.SetFillStyle(0) legend.SetBorderSize(0) legend.SetTextFont(42) legend.SetTextSize(0.02777778) legend.SetMargin(0.13) legend.AddEntry(h_n1_1_pZ,"1st neutralino","L") legend.AddEntry(h_n1_2_pZ,"2nd neutralino","L") legend.Draw() info.Draw() txtHeader.Draw() cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_n1_pZ.pdf") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_n1_pZ.png") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_n1_pZ.C") h_n1_1_Eta_dummy.Draw() h_n1_1_Eta.DrawNormalized("same") h_n1_2_Eta.DrawNormalized("same") scaleAxisY(h_n1_1_Eta,h_n1_1_Eta_dummy) legend = ROOT.TLegend(0.46,0.6744444,0.6955556,0.7644444) legend.SetFillColor(ROOT.kWhite) legend.SetFillStyle(0) legend.SetBorderSize(0) legend.SetTextFont(42) legend.SetTextSize(0.02777778) legend.SetMargin(0.13) legend.AddEntry(h_n1_1_Eta,"1st neutralino","L") legend.AddEntry(h_n1_2_Eta,"2nd neutralino","L") legend.Draw() info.Draw() txtHeader.Draw() cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_n1_Eta.pdf") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_n1_Eta.png") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_n1_Eta.C") h_n1_1_Phi_dummy.Draw() h_n1_1_Phi.DrawNormalized("same") h_n1_2_Phi.DrawNormalized("same") scaleAxisY(h_n1_1_Phi,h_n1_1_Phi_dummy) legend = ROOT.TLegend(0.46,0.6744444,0.6955556,0.7644444) legend.SetFillColor(ROOT.kWhite) legend.SetFillStyle(0) legend.SetBorderSize(0) legend.SetTextFont(42) legend.SetTextSize(0.02777778) legend.SetMargin(0.13) legend.AddEntry(h_n1_1_Phi,"1st neutralino","L") legend.AddEntry(h_n1_2_Phi,"2nd neutralino","L") legend.Draw() info.Draw() txtHeader.Draw() cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_n1_Phi.pdf") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_n1_Phi.png") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_n1_Phi.C") h_n1_1_p_dummy.Draw() plotOverflow(h_n1_1_p) plotOverflow(h_n1_2_p) scaleAxisY(h_n1_1_p,h_n1_1_p_dummy) #h_n1_1_p.DrawNormalized("same") #h_n1_2_p.DrawNormalized("same") legend = ROOT.TLegend(0.46,0.6744444,0.6955556,0.7644444) legend.SetFillColor(ROOT.kWhite) legend.SetFillStyle(0) legend.SetBorderSize(0) legend.SetTextFont(42) legend.SetTextSize(0.02777778) legend.SetMargin(0.13) legend.AddEntry(h_n1_1_p,"1st neutralino","L") legend.AddEntry(h_n1_2_p,"2nd neutralino","L") legend.Draw() info.Draw() txtHeader.Draw() cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_n1_p.pdf") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_n1_p.png") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_n1_p.C") h_n1_1_M_dummy.Draw() h_n1_1_M.DrawNormalized("same") #h_n1_2_M.DrawNormalized("same") #legend = ROOT.TLegend(0.46,0.6744444,0.6955556,0.7644444) #legend.SetFillColor(ROOT.kWhite) #legend.SetFillStyle(0) #legend.SetBorderSize(0) #legend.SetTextFont(42) #legend.SetTextSize(0.02777778) #legend.SetMargin(0.13) #legend.AddEntry(h_n1_1_M,"1st neutralino (leading p_{T})","L") #legend.AddEntry(h_n1_2_M,"2nd neutralino","L") #legend.Draw() info.Draw() txtHeader.Draw() cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_n1_M.pdf") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_n1_M.png") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_n1_M.C") h_nD_1_pT_dummy.Draw() #h_nD_1_pT.DrawNormalized("same") #h_nD_2_pT.DrawNormalized("same") plotOverflow(h_nD_1_pT) plotOverflow(h_nD_2_pT) scaleAxisY(h_nD_2_pT,h_nD_1_pT) legend = ROOT.TLegend(0.46,0.6744444,0.6955556,0.7644444) legend.SetFillColor(ROOT.kWhite) legend.SetFillStyle(0) legend.SetBorderSize(0) legend.SetTextFont(42) legend.SetTextSize(0.02777778) legend.SetMargin(0.13) legend.AddEntry(h_nD_1_pT,"1st n_{D} (leading p_{T})","L") legend.AddEntry(h_nD_2_pT,"2nd n_{D}","L") legend.Draw() info.Draw() txtHeader.Draw() cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_nD_pT.pdf") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_nD_pT.png") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_nD_pT.C") h_nD_1_pZ_dummy.Draw() h_nD_1_pZ.DrawNormalized("same") h_nD_2_pZ.DrawNormalized("same") scaleAxisY(h_nD_2_pZ,h_nD_1_pZ_dummy) legend = ROOT.TLegend(0.46,0.6744444,0.6955556,0.7644444) legend.SetFillColor(ROOT.kWhite) legend.SetFillStyle(0) legend.SetBorderSize(0) legend.SetTextFont(42) legend.SetTextSize(0.02777778) legend.SetMargin(0.13) legend.AddEntry(h_nD_1_pZ,"1st n_{D} (leading p_{T})","L") legend.AddEntry(h_nD_2_pZ,"2nd n_{D}","L") legend.Draw() info.Draw() txtHeader.Draw() cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_nD_pZ.pdf") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_nD_pZ.png") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_nD_pZ.C") h_nD_1_Eta_dummy.Draw() h_nD_1_Eta.DrawNormalized("same") h_nD_2_Eta.DrawNormalized("same") scaleAxisY(h_nD_1_Eta,h_nD_1_Eta_dummy) legend = ROOT.TLegend(0.46,0.6744444,0.6955556,0.7644444) legend.SetFillColor(ROOT.kWhite) legend.SetFillStyle(0) legend.SetBorderSize(0) legend.SetTextFont(42) legend.SetTextSize(0.02777778) legend.SetMargin(0.13) legend.AddEntry(h_nD_1_Eta,"1st n_{D} (leading p_{T})","L") legend.AddEntry(h_nD_2_Eta,"2nd n_{D}","L") legend.Draw() info.Draw() txtHeader.Draw() cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_nD_Eta.pdf") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_nD_Eta.png") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_nD_Eta.C") h_nD_1_Phi_dummy.Draw() h_nD_1_Phi.DrawNormalized("same") h_nD_2_Phi.DrawNormalized("same") scaleAxisY(h_nD_1_Phi,h_nD_1_Phi_dummy) legend = ROOT.TLegend(0.46,0.6744444,0.6955556,0.7644444) legend.SetFillColor(ROOT.kWhite) legend.SetFillStyle(0) legend.SetBorderSize(0) legend.SetTextFont(42) legend.SetTextSize(0.02777778) legend.SetMargin(0.13) legend.AddEntry(h_nD_1_Phi,"1st n_{D} (leading p_{T})","L") legend.AddEntry(h_nD_2_Phi,"2nd n_{D}","L") legend.Draw() info.Draw() txtHeader.Draw() cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_nD_Phi.pdf") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_nD_Phi.png") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_nD_Phi.C") h_nD_1_p_dummy.Draw() h_nD_1_p.DrawNormalized("same") h_nD_2_p.DrawNormalized("same") scaleAxisY(h_nD_2_p,h_nD_1_p_dummy) legend = ROOT.TLegend(0.46,0.6744444,0.6955556,0.7644444) legend.SetFillColor(ROOT.kWhite) legend.SetFillStyle(0) legend.SetBorderSize(0) legend.SetTextFont(42) legend.SetTextSize(0.02777778) legend.SetMargin(0.13) legend.AddEntry(h_nD_1_p,"1st n_{D} (leading p_{T})","L") legend.AddEntry(h_nD_2_p,"2nd n_{D}","L") legend.Draw() info.Draw() txtHeader.Draw() cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_nD_p.pdf") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_nD_p.png") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_nD_p.C") h_nD_1_M_dummy.Draw() h_nD_1_M.DrawNormalized("same") #h_nD_2_M.DrawNormalized("same") #legend = ROOT.TLegend(0.46,0.6744444,0.6955556,0.7644444) #legend.SetFillColor(ROOT.kWhite) #legend.SetFillStyle(0) #legend.SetBorderSize(0) #legend.SetTextFont(42) #legend.SetTextSize(0.02777778) #legend.SetMargin(0.13) #legend.AddEntry(h_nD_1_M,"1st n_{D} (leading p_{T})","L") #legend.AddEntry(h_nD_2_M,"2nd n_{D}","L") #legend.Draw() info.Draw() txtHeader.Draw() cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_nD_M.pdf") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_nD_M.png") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_nD_M.C") h_gammaD_cT_dummy.Draw() normConstant = integral(h_gammaD_cT) #print normConstant h_gammaD_cT.Scale(1/normConstant) h_gammaD_cT.Draw("same") scaleAxisYcT(h_gammaD_cT,h_gammaD_cT_dummy) funct = ROOT.TF1("funct","exp(-x/"+ lifetime_GammaD_Legend +")/("+ lifetime_GammaD_Legend + "*(1 - exp(-" + str(cTlim) + "/" + lifetime_GammaD_Legend + ")))",cTlow,cTlim) funct.SetNpx(10000) funct.Draw("same") h_gammaD_cT.SetTitleOffset(1.5, "Y") h_gammaD_cT.SetXTitle("c#tau of #gamma_{D} [mm]") h_gammaD_cT.SetYTitle("Normalized Fraction of events") h_gammaD_cT.SetTitleSize(0.05,"Y") info.Draw() txtHeader.Draw() eqn = ROOT.TLegend(0.46,0.6744444,0.6955556,0.7644444) eqn.SetFillColor(ROOT.kWhite) eqn.SetFillStyle(0) eqn.SetBorderSize(0) eqn.SetTextFont(42) eqn.SetTextSize(0.02777778) eqn.SetMargin(0.13) eqn.AddEntry(funct, "#frac{e^{-x/"+ lifetime_GammaD_Legend +"}}{"+ lifetime_GammaD_Legend + " (1 - e^{-" + str(cTlim) + "/" + lifetime_GammaD_Legend + "})}", "L") eqn.Draw() cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_gammaD_cT.pdf") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_gammaD_cT.png") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_gammaD_cT.C") h_gammaD_cT_lab_dummy.Draw() normConstant = integral(h_gammaD_cT_lab) h_gammaD_cT_lab.Scale(1/normConstant) h_gammaD_cT_lab.Draw("same") scaleAxisYcT(h_gammaD_cT_lab,h_gammaD_cT_lab_dummy) #h_gammaD_cT_lab.DrawNormalized("same") #myfit = ROOT.TF1("myfit", "[0]*exp(-x/[1])", 0, 10) #myfit.SetParName(0,"C") #myfit.SetParName(1,"L") #myfit.SetParameter(0,1) #myfit.SetParameter(1,1) #h_gammaD_cT_lab.Fit("myfit").Draw("same") h_gammaD_cT_lab.SetTitleOffset(1.5, "Y") h_gammaD_cT_lab.SetXTitle("L of #gamma_{D} [mm]") h_gammaD_cT_lab.SetYTitle("Events") info.Draw() txtHeader.Draw() cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_gammaD_L.pdf") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_gammaD_L.png") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_gammaD_L.C") h_gammaD_cT_XY_lab_dummy.Draw() normConstant = integral(h_gammaD_cT_XY_lab) h_gammaD_cT_XY_lab.Scale(1/normConstant) h_gammaD_cT_XY_lab.Draw("same") scaleAxisYcT(h_gammaD_cT_XY_lab,h_gammaD_cT_XY_lab_dummy) #h_gammaD_cT_XY_lab.DrawNormalized("same") #myfit = ROOT.TF1("myfit", "[0]*exp(-x/[1])", 0, 10) #myfit.SetParName(0,"C") #myfit.SetParName(1,"L_{xy}") #myfit.SetParameter(0,1) #myfit.SetParameter(1,1) #h_gammaD_cT_XY_lab.Fit("myfit").Draw("same") h_gammaD_cT_XY_lab.SetTitleOffset(1.5, "Y") h_gammaD_cT_XY_lab.SetXTitle("L_{xy} of #gamma_{D} [mm]") h_gammaD_cT_XY_lab.SetYTitle("Events") info.Draw() txtHeader.Draw() cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_gammaD_L_XY.pdf") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_gammaD_L_XY.png") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_gammaD_L_XY.C") h_gammaD_cT_Z_lab_dummy.Draw() normConstant = integral(h_gammaD_cT_Z_lab) h_gammaD_cT_Z_lab.Scale(1/normConstant) h_gammaD_cT_Z_lab.Draw("same") scaleAxisYcT(h_gammaD_cT_Z_lab,h_gammaD_cT_Z_lab_dummy) #h_gammaD_cT_Z_lab.DrawNormalized("same") #myfit = ROOT.TF1("myfit", "[0]*exp(-x/[1])", 0, 10) #myfit.SetParName(0,"C") #myfit.SetParName(1,"L_{z}") #myfit.SetParameter(0,1) #myfit.SetParameter(1,1) #h_gammaD_cT_Z_lab.Fit("myfit").Draw("same") h_gammaD_cT_Z_lab.SetTitleOffset(1.5, "Y") h_gammaD_cT_Z_lab.SetXTitle("L_{z} of #gamma_{D} [mm]") h_gammaD_cT_Z_lab.SetYTitle("Events") info.Draw() txtHeader.Draw() cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_gammaD_L_Z.pdf") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_gammaD_L_Z.png") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_gammaD_L_Z.C") h_gammaD_1_cT_dummy.Draw() normConstant = integral(h_gammaD_1_cT) h_gammaD_1_cT.Scale(1/normConstant) h_gammaD_1_cT.Draw("same") normConstant2 = integral(h_gammaD_2_cT) h_gammaD_2_cT.Scale(1/normConstant2) h_gammaD_2_cT.Draw("same") scaleAxisYcT(h_gammaD_2_cT,h_gammaD_1_cT_dummy) #h_gammaD_1_cT.DrawNormalized("same") #h_gammaD_2_cT.DrawNormalized("same") legend = ROOT.TLegend(0.46,0.6744444,0.6955556,0.7644444) legend.SetFillColor(ROOT.kWhite) legend.SetFillStyle(0) legend.SetBorderSize(0) legend.SetTextFont(42) legend.SetTextSize(0.02777778) legend.SetMargin(0.13) legend.AddEntry(h_gammaD_1_cT,"1st dark photon (leading p_{T})","L") legend.AddEntry(h_gammaD_2_cT,"2nd dark photon","L") legend.Draw() info.Draw() txtHeader.Draw() cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_gammaD_Sorted_cT.pdf") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_gammaD_Sorted_cT.png") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_gammaD_Sorted_cT.C") h_gammaD_1_cT_lab_dummy.Draw() normConstant = integral(h_gammaD_1_cT_lab) h_gammaD_1_cT_lab.Scale(1/normConstant) h_gammaD_1_cT_lab.Draw("same") normConstant2 = integral(h_gammaD_2_cT_lab) h_gammaD_2_cT_lab.Scale(1/normConstant2) h_gammaD_2_cT_lab.Draw("same") scaleAxisYcT(h_gammaD_2_cT_lab,h_gammaD_1_cT_lab_dummy) #h_gammaD_1_cT_lab.DrawNormalized("same") #h_gammaD_2_cT_lab.DrawNormalized("same") legend = ROOT.TLegend(0.46,0.6744444,0.6955556,0.7644444) legend.SetFillColor(ROOT.kWhite) legend.SetFillStyle(0) legend.SetBorderSize(0) legend.SetTextFont(42) legend.SetTextSize(0.02777778) legend.SetMargin(0.13) legend.AddEntry(h_gammaD_1_cT_lab,"1st dark photon (leading p_{T})","L") legend.AddEntry(h_gammaD_2_cT_lab,"2nd dark photon","L") legend.Draw() info.Draw() txtHeader.Draw() cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_gammaD_Sorted_cT_lab.pdf") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_gammaD_Sorted_cT_lab.png") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_gammaD_Sorted_cT_lab.C") h_gammaD_1_cT_XY_lab_dummy.Draw() normConstant = integral(h_gammaD_1_cT_XY_lab) h_gammaD_1_cT_XY_lab.Scale(1/normConstant) h_gammaD_1_cT_XY_lab.Draw("same") normConstant2 = integral(h_gammaD_2_cT_XY_lab) h_gammaD_2_cT_XY_lab.Scale(1/normConstant2) h_gammaD_2_cT_XY_lab.Draw("same") scaleAxisYcT(h_gammaD_2_cT_XY_lab,h_gammaD_1_cT_XY_lab_dummy) #h_gammaD_1_cT_XY_lab.DrawNormalized("same") #h_gammaD_2_cT_XY_lab.DrawNormalized("same") legend = ROOT.TLegend(0.46,0.6744444,0.6955556,0.7644444) legend.SetFillColor(ROOT.kWhite) legend.SetFillStyle(0) legend.SetBorderSize(0) legend.SetTextFont(42) legend.SetTextSize(0.02777778) legend.SetMargin(0.13) legend.AddEntry(h_gammaD_1_cT_XY_lab,"1st dark photon (leading p_{T})","L") legend.AddEntry(h_gammaD_2_cT_XY_lab,"2nd dark photon","L") legend.Draw() info.Draw() txtHeader.Draw() cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_gammaD_Sorted_cT_XY_lab.pdf") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_gammaD_Sorted_cT_XY_lab.png") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_gammaD_Sorted_cT_XY_lab.C") h_gammaD_1_cT_Z_lab_dummy.Draw() normConstant = integral(h_gammaD_1_cT_Z_lab) h_gammaD_1_cT_Z_lab.Scale(1/normConstant) h_gammaD_1_cT_Z_lab.Draw("same") normConstant2 = integral(h_gammaD_2_cT_Z_lab) h_gammaD_2_cT_Z_lab.Scale(1/normConstant2) h_gammaD_2_cT_Z_lab.Draw("same") scaleAxisYcT(h_gammaD_2_cT_Z_lab,h_gammaD_1_cT_Z_lab_dummy) #h_gammaD_1_cT_Z_lab.DrawNormalized("same") #h_gammaD_2_cT_Z_lab.DrawNormalized("same") legend = ROOT.TLegend(0.46,0.6744444,0.6955556,0.7644444) legend.SetFillColor(ROOT.kWhite) legend.SetFillStyle(0) legend.SetBorderSize(0) legend.SetTextFont(42) legend.SetTextSize(0.02777778) legend.SetMargin(0.13) legend.AddEntry(h_gammaD_1_cT_Z_lab,"1st dark photon (leading p_{T})","L") legend.AddEntry(h_gammaD_2_cT_Z_lab,"2nd dark photon","L") legend.Draw() info.Draw() txtHeader.Draw() cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_gammaD_Sorted_cT_Z_lab.pdf") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_gammaD_Sorted_cT_Z_lab.png") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_gammaD_Sorted_cT_Z_lab.C") h_gammaD_1_pT_dummy.Draw() h_gammaD_1_pT.DrawNormalized("same") h_gammaD_2_pT.DrawNormalized("same") scaleAxisY(h_gammaD_2_pT,h_gammaD_1_pT_dummy) legend = ROOT.TLegend(0.46,0.6744444,0.6955556,0.7644444) legend.SetFillColor(ROOT.kWhite) legend.SetFillStyle(0) legend.SetBorderSize(0) legend.SetTextFont(42) legend.SetTextSize(0.02777778) legend.SetMargin(0.13) legend.AddEntry(h_gammaD_1_pT,"1st dark photon (leading p_{T})","L") legend.AddEntry(h_gammaD_2_pT,"2nd dark photon","L") legend.Draw() info.Draw() txtHeader.Draw() cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_gammaD_pT.pdf") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_gammaD_pT.png") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_gammaD_pT.C") h_gammaD_1_pZ_dummy.Draw() #plotOverflow(h_gammaD_1_pZ) #plotOverflow(h_gammaD_2_pZ) h_gammaD_1_pZ.DrawNormalized("same") h_gammaD_2_pZ.DrawNormalized("same") scaleAxisY(h_gammaD_2_pZ,h_gammaD_1_pZ_dummy) #htmp = ROOT.TH1F(h_gammaD_1_pZ.GetName(),h_gammaD_1_pZ.GetTitle(), h_gammaD_1_pZ.GetNbinsX()+1, h_gammaD_1_pZ.GetBinLowEdge(1), h_gammaD_1_pZ.GetBinLowEdge(h_gammaD_1_pZ.GetNbinsX()+1)+h_gammaD_1_pZ.GetBinWidth(h_gammaD_1_pZ.GetNbinsX()+1)) #for i in range(1, h_gammaD_1_pZ.GetNbinsX()+1 ): # htmp.Fill(htmp.GetBinCenter(i), h_gammaD_1_pZ.GetBinContent(i)) #htmp.Fill(h_gammaD_1_pZ.GetNbinsX()-1, h_gammaD_1_pZ.GetBinContent(0)) #htmp.SetEntries(h_gammaD_1_pZ.GetEntries()) #htmp.SetLineColor(ROOT.kRed) #htmp.DrawNormalized("same") #htmp2 = ROOT.TH1F(h_gammaD_2_pZ.GetName(), h_gammaD_2_pZ.GetTitle(), h_gammaD_2_pZ.GetNbinsX()+1, h_gammaD_2_pZ.GetBinLowEdge(1), h_gammaD_2_pZ.GetBinLowEdge(h_gammaD_2_pZ.GetNbinsX()+1)+h_gammaD_2_pZ.GetBinWidth(h_gammaD_2_pZ.GetNbinsX()+1)) #for i in range(1, h_gammaD_2_pZ.GetNbinsX()+1 ): # htmp2.Fill(htmp2.GetBinCenter(i), h_gammaD_2_pZ.GetBinContent(i)) #htmp2.Fill(h_gammaD_2_pZ.GetNbinsX()-1, h_gammaD_2_pZ.GetBinContent(0)) #htmp2.SetEntries(h_gammaD_2_pZ.GetEntries()) #htmp2.SetLineColor(ROOT.kBlue) #htmp2.DrawNormalized("same") #h_gammaD_1_pZ.DrawNormalized("same") #h_gammaD_2_pZ.DrawNormalized("same") legend = ROOT.TLegend(0.46,0.6744444,0.6955556,0.7644444) legend.SetFillColor(ROOT.kWhite) legend.SetFillStyle(0) legend.SetBorderSize(0) legend.SetTextFont(42) legend.SetTextSize(0.02777778) legend.SetMargin(0.13) legend.AddEntry(h_gammaD_1_pZ,"1st dark photon (leading p_{T})","L") legend.AddEntry(h_gammaD_2_pZ,"2nd dark photon","L") legend.Draw() info.Draw() txtHeader.Draw() cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_gammaD_pZ.pdf") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_gammaD_pZ.png") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_gammaD_pZ.C") h_gammaD_1_Eta_dummy.Draw() h_gammaD_1_Eta.DrawNormalized("same") h_gammaD_2_Eta.DrawNormalized("same") scaleAxisY(h_gammaD_1_Eta,h_gammaD_1_Eta_dummy) legend = ROOT.TLegend(0.46,0.6744444,0.6955556,0.7644444) legend.SetFillColor(ROOT.kWhite) legend.SetFillStyle(0) legend.SetBorderSize(0) legend.SetTextFont(42) legend.SetTextSize(0.02777778) legend.SetMargin(0.13) legend.AddEntry(h_gammaD_1_Eta,"1st dark photon (leading p_{T})","L") legend.AddEntry(h_gammaD_2_Eta,"2nd dark photon","L") legend.Draw() info.Draw() txtHeader.Draw() cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_gammaD_Eta.pdf") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_gammaD_Eta.png") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_gammaD_Eta.C") h_gammaD_1_Phi_dummy.Draw() h_gammaD_1_Phi.DrawNormalized("same") h_gammaD_2_Phi.DrawNormalized("same") scaleAxisY(h_gammaD_1_Phi,h_gammaD_1_Phi_dummy) legend = ROOT.TLegend(0.46,0.6744444,0.6955556,0.7644444) legend.SetFillColor(ROOT.kWhite) legend.SetFillStyle(0) legend.SetBorderSize(0) legend.SetTextFont(42) legend.SetTextSize(0.02777778) legend.SetMargin(0.13) legend.AddEntry(h_gammaD_1_Phi,"1st dark photon (leading p_{T})","L") legend.AddEntry(h_gammaD_2_Phi,"2nd dark photon","L") legend.Draw() info.Draw() txtHeader.Draw() cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_gammaD_Phi.pdf") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_gammaD_Phi.png") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_gammaD_Phi.C") h_gammaD_1_p_dummy.Draw() plotOverflow(h_gammaD_1_p) plotOverflow(h_gammaD_2_p) scaleAxisY(h_gammaD_2_p,h_gammaD_1_p_dummy) #h_gammaD_1_p.DrawNormalized("same") #h_gammaD_2_p.DrawNormalized("same") legend = ROOT.TLegend(0.46,0.6744444,0.6955556,0.7644444) legend.SetFillColor(ROOT.kWhite) legend.SetFillStyle(0) legend.SetBorderSize(0) legend.SetTextFont(42) legend.SetTextSize(0.02777778) legend.SetMargin(0.13) legend.AddEntry(h_gammaD_1_p,"1st dark photon (leading p_{T})","L") legend.AddEntry(h_gammaD_2_p,"2nd dark photon","L") legend.Draw() info.Draw() txtHeader.Draw() cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_gammaD_p.pdf") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_gammaD_p.png") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_gammaD_p.C") h_gammaD_1_M_dummy.Draw() cnv.SetLogx() h_gammaD_1_M.DrawNormalized("same") #h_gammaD_2_M.DrawNormalized("same") #legend = ROOT.TLegend(0.46,0.6744444,0.6955556,0.7644444) #legend.SetFillColor(ROOT.kWhite) #legend.SetFillStyle(0) #legend.SetBorderSize(0) #legend.SetTextFont(42) #legend.SetTextSize(0.02777778) #legend.SetMargin(0.13) #legend.AddEntry(h_gammaD_1_M,"1st dark photon (leading p_{T})","L") #legend.AddEntry(h_gammaD_2_M,"2nd dark photon","L") #legend.Draw() info.Draw() txtHeader.Draw() cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_gammaD_M.pdf") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_gammaD_M.png") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_gammaD_M.C") cnv.SetLogx(0) h_muon_pT_dummy.Draw() h_muon_pT_0.DrawNormalized("same") h_muon_pT_1.DrawNormalized("same") h_muon_pT_2.DrawNormalized("same") h_muon_pT_3.DrawNormalized("same") scaleAxisY(h_muon_pT_3,h_muon_pT_dummy) legend = ROOT.TLegend(0.6175166,0.6730435,0.9429047,0.7626087) legend.SetFillColor(ROOT.kWhite) legend.SetFillStyle(0) legend.SetBorderSize(0) legend.SetTextFont(42) legend.SetTextSize(0.02777778) legend.SetMargin(0.13) legend.AddEntry(h_muon_pT_0,"1st muon (leading p_{T})","L") legend.AddEntry(h_muon_pT_1,"2nd muon","L") legend.AddEntry(h_muon_pT_2,"3rd muon","L") legend.AddEntry(h_muon_pT_3,"4th muon","L") legend.Draw() info.Draw() txtHeader.Draw() cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_muon_pT.pdf") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_muon_pT.png") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_muon_pT.C") h_muon_phi_dummy.Draw() h_muon_phi_0.DrawNormalized("same") h_muon_phi_1.DrawNormalized("same") h_muon_phi_2.DrawNormalized("same") h_muon_phi_3.DrawNormalized("same") scaleAxisY(h_muon_phi_0,h_muon_phi_dummy) legend = ROOT.TLegend(0.6175166,0.6730435,0.9429047,0.7626087) legend.SetFillColor(ROOT.kWhite) legend.SetFillStyle(0) legend.SetBorderSize(0) legend.SetTextFont(42) legend.SetTextSize(0.02777778) legend.SetMargin(0.13) legend.AddEntry(h_muon_phi_0,"1st muon (leading p_{T})","L") legend.AddEntry(h_muon_phi_1,"2nd muon","L") legend.AddEntry(h_muon_phi_2,"3rd muon","L") legend.AddEntry(h_muon_phi_3,"4th muon","L") legend.Draw() info.Draw() txtHeader.Draw() cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_muon_phi.pdf") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_muon_phi.png") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_muon_phi.C") h_muon_pZ_dummy.Draw() h_muon_pZ_0.DrawNormalized("same") h_muon_pZ_1.DrawNormalized("same") h_muon_pZ_2.DrawNormalized("same") h_muon_pZ_3.DrawNormalized("same") scaleAxisY(h_muon_pZ_3,h_muon_pZ_dummy) legend = ROOT.TLegend(0.6175166,0.6730435,0.9429047,0.7626087) legend.SetFillColor(ROOT.kWhite) legend.SetFillStyle(0) legend.SetBorderSize(0) legend.SetTextFont(42) legend.SetTextSize(0.02777778) legend.SetMargin(0.13) legend.AddEntry(h_muon_pZ_0,"1st muon (leading p_{T})","L") legend.AddEntry(h_muon_pZ_1,"2nd muon","L") legend.AddEntry(h_muon_pZ_2,"3rd muon","L") legend.AddEntry(h_muon_pZ_3,"4th muon","L") legend.Draw() info.Draw() txtHeader.Draw() cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_muon_pZ.pdf") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_muon_pZ.png") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_muon_pZ.C") h_muon_p_dummy.Draw() h_muon_p_0.DrawNormalized("same") h_muon_p_1.DrawNormalized("same") h_muon_p_2.DrawNormalized("same") h_muon_p_3.DrawNormalized("same") scaleAxisY(h_muon_p_3,h_muon_p_dummy) legend = ROOT.TLegend(0.6175166,0.6730435,0.9429047,0.7626087) legend.SetFillColor(ROOT.kWhite) legend.SetFillStyle(0) legend.SetBorderSize(0) legend.SetTextFont(42) legend.SetTextSize(0.02777778) legend.SetMargin(0.13) legend.AddEntry(h_muon_p_0,"1st muon (leading p_{T})","L") legend.AddEntry(h_muon_p_1,"2nd muon","L") legend.AddEntry(h_muon_p_2,"3rd muon","L") legend.AddEntry(h_muon_p_3,"4th muon","L") legend.Draw() info.Draw() txtHeader.Draw() cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_muon_p.pdf") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_muon_p.png") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_muon_p.C") h_muon_eta_dummy.Draw() h_muon_eta_0.DrawNormalized("same") h_muon_eta_1.DrawNormalized("same") h_muon_eta_2.DrawNormalized("same") h_muon_eta_3.DrawNormalized("same") scaleAxisY(h_muon_eta_0,h_muon_eta_dummy) legend = ROOT.TLegend(0.6175166,0.6730435,0.9429047,0.7626087) legend.SetFillColor(ROOT.kWhite) legend.SetFillStyle(0) legend.SetBorderSize(0) legend.SetTextFont(42) legend.SetTextSize(0.02777778) legend.SetMargin(0.13) legend.AddEntry(h_muon_eta_0,"1st muon (leading p_{T})","L") legend.AddEntry(h_muon_eta_1,"2nd muon","L") legend.AddEntry(h_muon_eta_2,"3rd muon","L") legend.AddEntry(h_muon_eta_3,"4th muon","L") legend.Draw() info.Draw() txtHeader.Draw() cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_muon_eta.pdf") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_muon_eta.png") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_muon_eta.C") #h_dimuon_m_dummy.Draw() #h_dimuon_m_0.DrawNormalized("same") #h_dimuon_m_1.DrawNormalized("same") #h_dimuon_m_2.DrawNormalized("same") #h_dimuon_m_3.DrawNormalized("same") # #legend = ROOT.TLegend(0.6175166,0.6730435,0.9429047,0.7626087) #legend.SetFillColor(ROOT.kWhite) #legend.SetFillStyle(0) #legend.SetBorderSize(0) #legend.SetTextFont(42) #legend.SetTextSize(0.02777778) #legend.SetMargin(0.13) #legend.AddEntry(h_dimuon_m_0,"1st dimuon (leading m_{#mu#mu})","L") #legend.AddEntry(h_dimuon_m_1,"2nd dimuon","L") #legend.AddEntry(h_dimuon_m_2,"3rd dimuon","L") #legend.AddEntry(h_dimuon_m_3,"4th dimuon","L") #legend.Draw() #info.Draw() #txtHeader.Draw() #cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_dimuon_m.pdf") #cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_dimuon_m.png") ## convert -define.pdf:use-cropbox=true -density 300 CSxBR_vs_mh.pdf -resize 900x900 CSxBR_vs_mh.png # #h_dimuon_m_log_dummy.Draw() #cnv.SetLogy() #h_dimuon_m_log_0.DrawNormalized("same") #h_dimuon_m_log_1.DrawNormalized("same") #h_dimuon_m_log_2.DrawNormalized("same") #h_dimuon_m_log_3.DrawNormalized("same") # #legend = ROOT.TLegend(0.6175166,0.6730435,0.9429047,0.7626087) #legend.SetFillColor(ROOT.kWhite) #legend.SetFillStyle(0) #legend.SetBorderSize(0) #legend.SetTextFont(42) #legend.SetTextSize(0.02777778) #legend.SetMargin(0.13) #legend.AddEntry(h_dimuon_m_log_0,"1st dimuon (leading m_{#mu#mu})","L") #legend.AddEntry(h_dimuon_m_log_1,"2nd dimuon","L") #legend.AddEntry(h_dimuon_m_log_2,"3rd dimuon","L") #legend.AddEntry(h_dimuon_m_log_3,"4th dimuon","L") #legend.Draw() #info.Draw() #txtHeader.Draw() # #cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_dimuon_m_log.pdf") #cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_dimuon_m_log.png") #cnv.SetLogy(0) # #h_dimuon_m_real_fake_dummy.Draw() #h_dimuon_m_real_fake_0.DrawNormalized("same") #h_dimuon_m_real_fake_1.DrawNormalized("same") # #legend = ROOT.TLegend(0.46,0.6744444,0.6955556,0.7644444) #legend.SetFillColor(ROOT.kWhite) #legend.SetFillStyle(0) #legend.SetBorderSize(0) #legend.SetTextFont(42) #legend.SetTextSize(0.02777778) #legend.SetMargin(0.13) #legend.AddEntry(h_dimuon_m_real_fake_0,"Real dimuons","L") #legend.AddEntry(h_dimuon_m_real_fake_1,"Fake dimuons","L") #legend.Draw() #info.Draw() #txtHeader.Draw() # #cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_dimuon_m_real_fake.pdf") #cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_dimuon_m_real_fake.png") # #h_dimuon_m_real_fake_log_dummy.Draw() #cnv.SetLogy() #h_dimuon_m_real_fake_log_0.DrawNormalized("same") #h_dimuon_m_real_fake_log_1.DrawNormalized("same") #legend = ROOT.TLegend(0.46,0.6744444,0.6955556,0.7644444) #legend.SetFillColor(ROOT.kWhite) #legend.SetFillStyle(0) #legend.SetBorderSize(0) #legend.SetTextFont(42) #legend.SetTextSize(0.02777778) #legend.SetMargin(0.13) #legend.AddEntry(h_dimuon_m_real_fake_log_0,"Real dimuons","L") #legend.AddEntry(h_dimuon_m_real_fake_log_1,"Fake dimuons","L") #legend.Draw() #info.Draw() #txtHeader.Draw() # #cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_dimuon_m_real_fake_log.pdf") #cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_dimuon_m_real_fake_log.png") cnv.SetLogy(0) h_m1_vs_m2.Draw() info.Draw() txtHeader.Draw() cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_dimuon_m1_vs_m2.pdf") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_dimuon_m1_vs_m2.png") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_dimuon_m1_vs_m2.C") cnv.SetLogx() h_m2.Draw() h_m1.Draw("same") info.Draw() txtHeader.Draw() txtHeader.Draw() cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_dimuon_m.pdf") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_dimuon_m.png") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_dimuon_m.C") cnv.SetLogx(0) h_dimuon_m_fake_dummy.Draw() h_dimuon_m_fake_0.DrawNormalized("same") scaleAxisY(h_dimuon_m_fake_0,h_dimuon_m_fake_dummy) info.Draw() txtHeader.Draw() cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_dimuon_m_fake.pdf") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_dimuon_m_fake.png") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_dimuon_m_fake.C") h_dimuon_m_fake_log_dummy.Draw() cnv.SetLogy() cnv.SetLogx() h_dimuon_m_fake_log_0.DrawNormalized("same") #scaleAxisY(h_dimuon_m_fake_log_0,h_dimuon_m_fake_log_dummy) info.Draw() txtHeader.Draw() cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_dimuon_m_fake_log.pdf") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_dimuon_m_fake_log.png") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_dimuon_m_fake_log.C") cnv.SetLogy(0) cnv.SetLogx(0) h_dimuon_1_pT_dummy.Draw() h_dimuon_1_pT.DrawNormalized("same") h_dimuon_2_pT.DrawNormalized("same") scaleAxisY(h_dimuon_2_pT,h_dimuon_1_pT_dummy) legend = ROOT.TLegend(0.46,0.6744444,0.6955556,0.7644444) legend.SetFillColor(ROOT.kWhite) legend.SetFillStyle(0) legend.SetBorderSize(0) legend.SetTextFont(42) legend.SetTextSize(0.02777778) legend.SetMargin(0.13) legend.AddEntry(h_dimuon_1_pT,"1st #mu#mu (leading p_{T})","L") legend.AddEntry(h_dimuon_2_pT,"2nd #mu#mu","L") legend.Draw() info.Draw() txtHeader.Draw() cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_dimuon_pT.pdf") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_dimuon_pT.png") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_dimuon_pT.C") h_dimuon_1_pZ_dummy.Draw() #plotOverflow(h_dimuon_1_pZ) #plotOverflow(h_dimuon_2_pZ) h_dimuon_1_pZ.DrawNormalized("same") h_dimuon_2_pZ.DrawNormalized("same") scaleAxisY(h_dimuon_2_pZ,h_dimuon_1_pZ_dummy) legend = ROOT.TLegend(0.46,0.6744444,0.6955556,0.7644444) legend.SetFillColor(ROOT.kWhite) legend.SetFillStyle(0) legend.SetBorderSize(0) legend.SetTextFont(42) legend.SetTextSize(0.02777778) legend.SetMargin(0.13) legend.AddEntry(h_dimuon_1_pZ,"1st #mu#mu (leading p_{T})","L") legend.AddEntry(h_dimuon_2_pZ,"2nd #mu#mu","L") legend.Draw() info.Draw() txtHeader.Draw() cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_dimuon_pZ.pdf") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_dimuon_pZ.png") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_dimuon_pZ.C") h_dimuon_1_Eta_dummy.Draw() h_dimuon_1_Eta.DrawNormalized("same") h_dimuon_2_Eta.DrawNormalized("same") scaleAxisY(h_dimuon_1_Eta,h_dimuon_1_Eta_dummy) legend = ROOT.TLegend(0.46,0.6744444,0.6955556,0.7644444) legend.SetFillColor(ROOT.kWhite) legend.SetFillStyle(0) legend.SetBorderSize(0) legend.SetTextFont(42) legend.SetTextSize(0.02777778) legend.SetMargin(0.13) legend.AddEntry(h_dimuon_1_Eta,"1st #mu#mu (leading p_{T})","L") legend.AddEntry(h_dimuon_2_Eta,"2nd #mu#mu","L") legend.Draw() info.Draw() txtHeader.Draw() cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_dimuon_Eta.pdf") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_dimuon_Eta.png") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_dimuon_Eta.C") h_dimuon_1_Phi_dummy.Draw() h_dimuon_1_Phi.DrawNormalized("same") h_dimuon_2_Phi.DrawNormalized("same") scaleAxisY(h_dimuon_1_Phi,h_dimuon_1_Phi_dummy) legend = ROOT.TLegend(0.46,0.6744444,0.6955556,0.7644444) legend.SetFillColor(ROOT.kWhite) legend.SetFillStyle(0) legend.SetBorderSize(0) legend.SetTextFont(42) legend.SetTextSize(0.02777778) legend.SetMargin(0.13) legend.AddEntry(h_dimuon_1_Phi,"1st #mu#mu (leading p_{T})","L") legend.AddEntry(h_dimuon_2_Phi,"2nd #mu#mu","L") legend.Draw() info.Draw() txtHeader.Draw() cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_dimuon_Phi.pdf") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_dimuon_Phi.png") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_dimuon_Phi.C") h_dimuon_1_p_dummy.Draw() plotOverflow(h_dimuon_1_p) plotOverflow(h_dimuon_2_p) scaleAxisY(h_dimuon_2_p,h_dimuon_1_p_dummy) legend = ROOT.TLegend(0.46,0.6744444,0.6955556,0.7644444) legend.SetFillColor(ROOT.kWhite) legend.SetFillStyle(0) legend.SetBorderSize(0) legend.SetTextFont(42) legend.SetTextSize(0.02777778) legend.SetMargin(0.13) legend.AddEntry(h_dimuon_1_p,"1st #mu#mu (leading p_{T})","L") legend.AddEntry(h_dimuon_2_p,"2nd #mu#mu","L") legend.Draw() info.Draw() txtHeader.Draw() cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_dimuon_p.pdf") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_dimuon_p.png") cnv.SaveAs("DarkSusy_mH_125_mGammaD_" + mass_GammaD + "_cT_"+ lifetime_GammaD + "_LHE_dimuon_p.C") BAM.Write() print "Made it to the end and closes" f.close()
[ "bmichlin@rice.edu" ]
bmichlin@rice.edu
d52ca250c5279313ecd41661ee12a5e93f3733d1
5905ed0409c332492409d7707528452b19692415
/google-cloud-sdk/lib/googlecloudsdk/api_lib/vmware/privateclouds.py
8973c5410af453cbe0b9f0ff1d089e4085220403
[ "LicenseRef-scancode-unknown-license-reference", "Apache-2.0" ]
permissive
millerthomasj/google-cloud-sdk
c37b7ddec08afadec6ee4c165153cd404f7dec5e
3deda6696c3be6a679689b728da3a458c836a24e
refs/heads/master
2023-08-10T16:03:41.819756
2021-09-08T00:00:00
2021-09-08T15:08:09
null
0
0
null
null
null
null
UTF-8
Python
false
false
5,427
py
# -*- coding: utf-8 -*- # # Copyright 2021 Google LLC. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Cloud vmware Privateclouds client.""" from __future__ import absolute_import from __future__ import division from __future__ import unicode_literals from apitools.base.py import list_pager from googlecloudsdk.api_lib.vmware import util from googlecloudsdk.command_lib.vmware import flags class PrivateCloudsClient(util.VmwareClientBase): """cloud vmware privateclouds client.""" def __init__(self): super(PrivateCloudsClient, self).__init__() self.service = self.client.projects_locations_privateClouds def Get(self, resource): request = self.messages.VmwareengineProjectsLocationsPrivateCloudsGetRequest( name=resource.RelativeName()) return self.service.Get(request) def Create(self, resource, labels=None, description=None, cluster_id=None, node_type=None, node_count=None, network_cidr=None, network=None, network_project=None): parent = resource.Parent().RelativeName() private_cloud_id = resource.Name() private_cloud = self.messages.PrivateCloud(description=description) flags.AddLabelsToMessage(labels, private_cloud) network_config = self.messages.NetworkConfig( managementCidr=network_cidr, network=network, ) if not network.startswith('project'): if not bool(network_project): network_project = resource.Parent().Parent().Name() network_config.network = 'projects/{}/global/networks/{}'.format( network_project, network) management_cluster = self.messages.ManagementCluster( clusterId=cluster_id, nodeCount=node_count, nodeTypeId=node_type) private_cloud.managementCluster = management_cluster private_cloud.networkConfig = network_config request = self.messages.VmwareengineProjectsLocationsPrivateCloudsCreateRequest( parent=parent, privateCloudId=private_cloud_id, privateCloud=private_cloud) return self.service.Create(request) def Update(self, resource, labels=None, description=None, external_ip_access=None): cluster_group = self.Get(resource) update_mask = ['labels'] if labels is not None: flags.AddLabelsToMessage(labels, cluster_group) if description is not None: cluster_group.description = description update_mask.append('description') if external_ip_access is not None: cluster_group.networkConfig.externalIpAccess = external_ip_access update_mask.append('network_config.external_ip_access') request = self.messages.SddcProjectsLocationsClusterGroupsPatchRequest( clusterGroup=cluster_group, name=resource.RelativeName(), updateMask=','.join(update_mask)) return self.service.Patch(request) def UnDelete(self, resource): request = self.messages.VmwareengineProjectsLocationsPrivateCloudsUndeleteRequest( name=resource.RelativeName()) return self.service.Undelete(request) def Delete(self, resource): request = self.messages.VmwareengineProjectsLocationsPrivateCloudsDeleteRequest( name=resource.RelativeName()) return self.service.Delete(request) def List(self, location_resource, filter_expression=None, limit=None, page_size=None, sort_by=None): location = location_resource.RelativeName() request = self.messages.VmwareengineProjectsLocationsPrivateCloudsListRequest( parent=location, filter=filter_expression) if page_size: request.page_size = page_size return list_pager.YieldFromList( self.service, request, limit=limit, batch_size_attribute='pageSize', batch_size=page_size, field='privateClouds') def GetNsxCredentials(self, resource): request = self.messages.VmwareengineProjectsLocationsPrivateCloudsShowNsxCredentialsRequest( privateCloud=resource.RelativeName()) return self.service.ShowNsxCredentials(request) def ResetNsxCredentials(self, resource): request = self.messages.VmwareengineProjectsLocationsPrivateCloudsResetNsxCredentialsRequest( privateCloud=resource.RelativeName()) return self.service.ResetNsxCredentials(request) def GetVcenterCredentials(self, resource): request = self.messages.VmwareengineProjectsLocationsPrivateCloudsShowVcenterCredentialsRequest( privateCloud=resource.RelativeName()) return self.service.ShowVcenterCredentials(request) def ResetVcenterCredentials(self, resource): request = self.messages.VmwareengineProjectsLocationsPrivateCloudsResetVcenterCredentialsRequest( privateCloud=resource.RelativeName()) return self.service.ResetVcenterCredentials(request)
[ "gcloud@google.com" ]
gcloud@google.com
089d204a57ac58b1898d7497e8eaa2e12739dbfb
a91eb255bddc7d4fa12dae246e05f68f757148e4
/dfc/document/urls.py
3bee1653d16e26518e717117d7c6c59efb80a2aa
[]
no_license
zPatrickz/DFC-website
7a54f3812ac0e8e5b54df3841ecbfb40da18ce64
6988d7ea0382ebc57540486a9621ead753cfbc37
refs/heads/master
2020-12-11T07:59:37.745729
2014-04-10T14:26:01
2014-04-10T14:26:01
null
0
0
null
null
null
null
UTF-8
Python
false
false
316
py
from django.conf.urls import patterns, url from django.contrib.auth import views as auth_views from document import views urlpatterns = patterns('', # url(r'^$', views.index, name = 'document_home'), url(r'^new/', views.new, name = 'doc_new'), url(r'^(?P<doc_id>\d+)/',views.detail, name = 'doc_detail'), )
[ "zeostudio@gmail.com" ]
zeostudio@gmail.com
21183bcec283cef8fb369fe032118579540e2969
4724a3beaba91dd474382aaff05a900e13118071
/09-case-study-word-play/ex_9_2_7.py
f8cc82867f782e07690f52946fceec9b89d39a1b
[]
no_license
akshirapov/think-python
7090b11c6618b6dbc5ca5cde8ba2e1e26ca39e28
490333f19b463973c05abc734ac3e9dc4e6d019a
refs/heads/master
2020-06-27T03:58:03.377943
2020-01-10T16:37:52
2020-01-10T16:40:38
199,838,313
0
2
null
null
null
null
UTF-8
Python
false
false
953
py
# -*- coding: utf-8 -*- """ This module contains a code for ex.7 related to ch.9.2 of Think Python, 2nd Edition by Allen Downey http://thinkpython2.com """ def has_three_consecutive_double_letters(string: str): """Returns a word with three consecutive double letters.""" if len(string) < 6: return False index = 0 for char in string: # looking for the first pair index = string.find(2*char) if index != -1: break # no double letters if index == -1: return False if len(string[index:]) < 6: return False if string[index+2] != string[index+3]: return False if string[index+4] != string[index+5]: return False return True if __name__ == '__main__': with open('words.txt') as fin: for line in fin: word = line.strip() if has_three_consecutive_double_letters(word): print(word)
[ "cccp2006_06@mail.ru" ]
cccp2006_06@mail.ru
e61e26e9d15b4ae40e7063119a966ff2722a352f
e5ebb73d5b94cba3e2d92fd27538fdf54c754bb7
/spam/Obit/python/FArray.py
86c00b59bd93c55a10a45b76a49a06f3ab808065
[ "MIT" ]
permissive
astroblogweb/gmrt-spam
80ab4a7f895c57856a9507a378db3897886dc84c
5f74990805bac0ddd350e54129b0f467dbb266e1
refs/heads/master
2020-12-31T00:40:18.421197
2017-01-14T06:14:31
2017-01-14T06:14:31
null
0
0
null
null
null
null
UTF-8
Python
false
false
34,872
py
# Python interface to Obit float array class. # $Id: FArray.py 352 2011-06-10 16:40:10Z bill.cotton $ """ Python Obit multidimensional array of float class This class is for creating and manipulating a Array as a memory resident multidimensional rectangular array of floats. Elements are stored in order of the increasing axis order (the reverse of the usual c definition). Except as noted, magic value blanking is supported (OBIT_MAGIC) (returned to Python as NaN) Virtual (read only) members (accessed as e.g. array.RMS) ====== ============================================== RMS RMS of valid members (from histogram analysis) RawRMS RMS of valid members (from RMS about mean) Mode Mode of distribution of valid members Mean Mode of distribution of valid members Sum Sum of valid members Count Count of valid members Ndim Number of axes in array Naxis list of axis dimensions (by storage order) ====== ============================================== """ #----------------------------------------------------------------------- # Copyright (C) 2004-2011 # Associated Universities, Inc. Washington DC, USA. # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License as # published by the Free Software Foundation; either version 2 of # the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public # License along with this program; if not, write to the Free # Software Foundation, Inc., 675 Massachusetts Ave, Cambridge, # MA 02139, USA. # # Correspondence concerning this software should be addressed as follows: # Internet email: bcotton@nrao.edu. # Postal address: William Cotton # National Radio Astronomy Observatory # 520 Edgemont Road # Charlottesville, VA 22903-2475 USA #----------------------------------------------------------------------- # Python shadow class to ObitFArray class import Obit, InfoList, OErr class FArrayPtr : def __init__(self,this): self.this = this def __setattr__(self,name, value): if name == "me" : # Out with the old Obit.FArrayUnref(Obit.FArray_me_get(self.this)) # In with the new Obit.FArray_me_set(self.this,value) return self.__dict__[name] = value def __getattr__(self,name): if self.__class__ != FArray: return if name == "me" : return Obit.FArray_me_get(self.this) if name=="List": out = InfoList.InfoList() out.me = Obit.InfoListUnref(out.me) out.me = Obit.FArrayGetList(self.me) return out # Virtual members if name=="RMS": return PRMS(self) if name=="RawRMS": return PRawRMS(self) if name=="Mode": return PMode(self) if name=="Mean": return PMean(self) if name=="Sum": return PSum(self) if name=="Count": return PCount(self) if name=="Ndim": return PGetNdim(self) if name=="Naxis": return PGetNaxis(self) if name=="Buf": return PGetBuf(self) raise AttributeError,str(name) def __repr__(self): if self.__class__ != FArray: return return "<C FArray instance> " + Obit.FArrayGetName(self.me) class FArray(FArrayPtr): """ Python Obit multidimensional array of float class This class is for creating and manipulating a Array as a memory resident multidimensional rectangular array of floats. Elements are stored in order of the increasing axis order (the reverse of the usual c definition). Except as noted, magic value blanking is supported (OBIT_MAGIC) (returned to Python as NaN) Virtual (read only) members (accessed as e.g. array.RMS ====== ============================================== RMS RMS of valid members (from histogram analysis) RawRMS RMS of valid members (from RMS about mean) Mode Mode of distribution of valid members Mean Mode of distribution of valid members Sum Sum of valid members Count Count of valid members Ndim Number of axes in array Naxis list of axis dimensions (by storage order) ====== ============================================== """ def __init__(self, name, naxis=[1]): ndim = len(naxis) self.this = Obit.new_FArray(name, ndim, naxis) def __del__(self): if Obit!=None: Obit.delete_FArray(self.this) def set (self, value, i1, i2=0, i3=0, i4=0, i5=0, i6=0): """ Set Array value [i1, i2, i3...] (0-rel) * self = Python FArray object * value = value for pixel (None = blanked) * i1 = first axis index (0-rel) * in = nth axis index """ # value, possible blanked if value==None: v = fblank else: v = value # Set value pos = [i1,i2,i3,i4,i5,i6] PSetVal(self, pos, v) # end set def get (self, i1, i2=0, i3=0, i4=0, i5=0, i6=0): """ Get Array value [i1, i2, i3...] (0-rel) Return value at pixel [i1,...in], None if blanked * self = Python FArray object * i1 = first axis index (0-rel) * in = nth axis index """ # Get value pos = [i1,i2,i3,i4,i5,i6] v = PGetVal(self, pos) # value, possible blanked if v==fblank: value = None else: value = v return value # end get # End Class FArray def PGetBlank(): """ Return Magic blanking value """ ################################################################ return Obit.FArrayGetBlank () # Module constants fblank = PGetBlank() # Blanked value def PGetVal(inFA, pos): """ Return value of a cell in an FArray returns cell contents * inFA = input Python FArray * pos = 0-rel cell number as an array, e.g. [10,24] """ ################################################################ return Obit.FArrayGetVal (inFA.me, pos) def PSetVal(inFA, pos, val): """ Set value of a cell in an FArray * inFA = input Python FArray * pos = 0-rel cell number as an array, e.g. [10,24] * value = new value for cell """ ################################################################ # Checks if not PIsA(inFA): print "Actually ",inFA.__class__ raise TypeError,"inFA MUST be a Python Obit FArray" Obit.FArraySetVal(inFA.me, pos, val) def PGetBuf(inFA): """ Get python memory buffer for data array returns python memory buffer * inFA = input Python FArray """ ################################################################ # Checks if not PIsA(inFA): print "Actually ",inFA.__class__ raise TypeError,"inFA MUST be a Python Obit FArray" return Obit.FArrayGetBuf(inFA.me) # end PGetBuf( def PCopy (inFA, err): """ Make copy an FArray returns copy * inFA = input Python FArray * err = Python Obit Error/message stack """ ################################################################ # Checks if not PIsA(inFA): print "Actually ",inFA.__class__ raise TypeError,"inFA MUST be a Python Obit FArray" outFA = FArray("None") outFA.me = Obit.FArrayCopy (inFA.me, outFA.me, err.me); if err.isErr: OErr.printErrMsg(err, "Error copying FArray") return outFA # end PCopy def PClone (inFA, err): """ Make copy the structure of an FArray Zero fill and return FArray with same structure as in * inFA = input Python FArray * err = Python Obit Error/message stack """ ################################################################ # Checks if not PIsA(inFA): print "Actually ",inFA.__class__ raise TypeError,"inFA MUST be a Python Obit FArray" outFA = FArray("Clone") Obit.FArrayClone (inFA.me, outFA.me, err.me); if err.isErr: OErr.printErrMsg(err, "Error zero cloning FArray") return outFA # end PClone def PSubArr (inFA, blc, trc, err): """ Return a slice of an FArray returns Slice in FArray * inFA = input Python FArray * blc = array giving (1-rel) lower index of first cell to copy, e.g. [1,1] * trc = array giving (1-rel) highest index of first cell to copy * err = Python Obit Error/message stack """ ################################################################ # Checks if not PIsA(inFA): print "Actually ",inFA.__class__ raise TypeError,"inFA MUST be a Python Obit FArray" outFA = FArray("None") outFA.me = Obit.FArraySubArr (inFA.me, blc, trc, err.me) if err.isErr: OErr.printErrMsg(err, "Error slicing FArray") return outFA # emd PSubArr def PTranspose (inFA, order, err): """ Transpose an FArray returns Transposed FArray * inFA = input Python FArray * order = output 1-rel order of the transposed axes, in storage order negative value = reverse order, e,g, [2,1] = transpose 2D array * err = Python Obit Error/message stack """ ################################################################ # Checks if not PIsA(inFA): print "Actually ",inFA.__class__ raise TypeError,"inFA MUST be a Python Obit FArray" outFA = FArray("None") outFA.me = Obit.FArrayTranspose (inFA.me, order, err.me) if err.isErr: OErr.printErrMsg(err, "Error transposing FArray") return outFA # end PTranspose def PIsCompatable (in1, in2): """ Tells if two FArrays have compatable geometry returns true or false (1, 0) * in1 = first input Python FArray * in2 = second input Python FArray """ ################################################################ # Checks if not PIsA(in1): print "Actually ",in1.__class__ raise TypeError,"in1 MUST be a Python Obit FArray" if not PIsA(in2): print "Actually ",in2.__class__ raise TypeError,"in2 MUST be a Python Obit FArray" return Obit.FArrayIsCompatable(in1.me, in2.me) def PRealloc (inFA, naxis): """ Change the geometry of an FArray Contents will be zeroed * inFA = input Python FArray * naxis = array giving desired dimension, e.g. [20,30] """ ################################################################ # Checks if not PIsA(inFA): print "Actually ",inFA.__class__ raise TypeError,"inFA MUST be a Python Obit FArray" ndim = len(naxis) Obit.FArrayRealloc(inFA.me, ndim, naxis) def PMax (inFA, pos) : """ Find maximum pixel value returns maximum value (may have trouble w/ > 2 dim) * inFA = first input Python FArray * pos = [output] 0-rel position as array """ ################################################################ # Checks if not PIsA(inFA): print "Actually ",inFA.__class__ raise TypeError,"inFA MUST be a Python Obit FArray" lpos = [0,0] # Dummy ret = Obit.FArrayMax(inFA.me, lpos) # Results in list ret out = ret[0] pos[0]=ret[1]; pos[1]=ret[2] return out def PMaxAbs (inFA, pos): """ Find maximum absolute pixel value returns maximum abs value (may have trouble w/ > 2 dim) * inFA = first input Python FArray * pos = [output] 0-rel position as array """ ################################################################ # Checks if not PIsA(inFA): print "Actually ",inFA.__class__ raise TypeError,"inFA MUST be a Python Obit FArray" lpos = [0,0] # Dummy ret = Obit.FArrayMaxAbs(inFA.me, lpos) # Results in list ret out = ret[0] pos[0]=ret[1]; pos[1]=ret[2] return out def PMin (inFA, pos) : """ Find minimum pixel value returns minimum value (may have trouble w/ > 2 dim) * inFA = first input Python FArray * pos = [output] 0-rel position as array """ ################################################################ # Checks if not PIsA(inFA): print "Actually ",inFA.__class__ raise TypeError,"inFA MUST be a Python Obit FArray" lpos = [0,0] # Dummy ret = Obit.FArrayMin(inFA.me, lpos) # Results in list ret out = ret[0] pos[0]=ret[1]; pos[1]=ret[2] return out def PDeblank (inFA, scalar): """ Replace any magic value blanks with scalar * inFA = input Python FArray * scalar = value to replace magic blanks """ ################################################################ # Checks if not PIsA(inFA): print "Actually ",inFA.__class__ raise TypeError,"inFA MUST be a Python Obit FArray" Obit.FArrayDeblank (inFA.me, scalar) def PRMS (inFA): """ Return RMS of pixel unblanked pixel values returns RMS value derived from a histogram * inFA = input Python FArray """ ################################################################ # Checks if not PIsA(inFA): print "Actually ",inFA.__class__ raise TypeError,"inFA MUST be a Python Obit FArray" return Obit.FArrayRMS(inFA.me) def PRawRMS (inFA): """ Return RMS of pixel unblanked pixel values returns simple RMS about mean * inFA = input Python FArray """ ################################################################ # Checks if not PIsA(inFA): print "Actually ",inFA.__class__ raise TypeError,"inFA MUST be a Python Obit FArray" return Obit.FArrayRawRMS(inFA.me) def PRMS0 (inFA): """ Return RMS of pixel unblanked pixel values about zero returns simple RMS about zero * inFA = input Python FArray """ ################################################################ # Checks if not PIsA(inFA): print "Actually ",inFA.__class__ raise TypeError,"inFA MUST be a Python Obit FArray" return Obit.FArrayRMS0(inFA.me) def PMode (inFA): """ Return Mode of pixel unblanked pixel values returns Mode of values * inFA = input Python FArray """ ################################################################ # Checks if not PIsA(inFA): print "Actually ",inFA.__class__ raise TypeError,"inFA MUST be a Python Obit FArray" return Obit.FArrayMode(inFA.me) def PMean (inFA): """ Return mean of pixel unblanked pixel values returns mean of values * inFA = input Python FArray """ ################################################################ # Checks if not PIsA(inFA): print "Actually ",inFA.__class__ raise TypeError,"inFA MUST be a Python Obit FArray" return Obit.FArrayMean(inFA.me) def PFill (inFA, scalar): """ Fill all cells of an FArray with a scalar * inFA = input Python FArray * scalar = Value to fill """ ################################################################ # Checks if not PIsA(inFA): print "Actually ",inFA.__class__ raise TypeError,"inFA MUST be a Python Obit FArray" Obit.FArrayFill(inFA.me, scalar) def PNeg (inFA): """ Negate each element of the array. * inFA = input Python FArray """ ################################################################ # Checks if not PIsA(inFA): print "Actually ",inFA.__class__ raise TypeError,"inFA MUST be a Python Obit FArray" Obit.FArrayNeg(inFA.me) # end PNeg def PSin (inFA): """ Sine of each element of the array. * inFA = input Python FArray """ ################################################################ # Checks if not PIsA(inFA): print "Actually ",inFA.__class__ raise TypeError,"inFA MUST be a Python Obit FArray" Obit.FArraySin(inFA.me) # end PSin def PCos (inFA): """ Cosine of each element of the array. * inFA = input Python FArray """ ################################################################ # Checks if not PIsA(inFA): print "Actually ",inFA.__class__ raise TypeError,"inFA MUST be a Python Obit FArray" Obit.FArrayCos(inFA.me) # end PCos def PSqrt (inFA): """ Square root of MAX (1.0e-20, each element of the array). * inFA = input Python FArray """ ################################################################ # Checks if not PIsA(inFA): print "Actually ",inFA.__class__ raise TypeError,"inFA MUST be a Python Obit FArray" Obit.FArraySqrt(inFA.me) # end PSqrt def PSum (inFA): """ Sum each element of the array. returns sum * inFA = input Python FArray """ ################################################################ # Checks if not PIsA(inFA): print "Actually ",inFA.__class__ raise TypeError,"inFA MUST be a Python Obit FArray" return Obit.FArraySum(inFA.me) def PCount (inFA): """ Give number of valid elements in the array. returns count * inFA = input Python FArray """ ################################################################ # Checks if not PIsA(inFA): print "Actually ",inFA.__class__ raise TypeError,"inFA MUST be a Python Obit FArray" return Obit.FArrayCount(inFA.me) def PSAdd (inFA, scalar): """ Add a scalar to each element of the array. in = in + scalar * inFA = input Python FArray * scalar = Value to add """ ################################################################ # Checks if not PIsA(inFA): print "Actually ",inFA.__class__ raise TypeError,"inFA MUST be a Python Obit FArray" Obit.FArraySAdd(inFA.me, scalar) def PSMul (inFA, scalar): """ Multiply each element of the array by a scalar in = in * scalar * inFA = input Python FArray * scalar = Value to multiply """ ################################################################ # Checks if not PIsA(inFA): print "Actually ",inFA.__class__ raise TypeError,"inFA MUST be a Python Obit FArray" Obit.FArraySMul(inFA.me, scalar) def PSDiv (inFA, scalar): """ Divide each element of the array into a scalar. in = scalar / in No check for zeroes is made * inFA = input Python FArray * scalar = scalar """ ################################################################ # Checks if not PIsA(inFA): print "Actually ",inFA.__class__ raise TypeError,"inFA MUST be a Python Obit FArray" Obit.FArraySDiv(inFA.me, scalar) def PClip (inFA, minVal, maxVal, newVal): """ Replace values outside of a given range with a new value in = newVal where in < minVal or in > maxVal * inFA = input Python FArray * minVal = Minimum allowed value * maxVal = Maximum allowed value * newVal = Value to use if out of range """ ################################################################ # Checks if not PIsA(inFA): print "Actually ",inFA.__class__ raise TypeError,"inFA MUST be a Python Obit FArray" Obit.FArrayClip(inFA.me, minVal, maxVal, newVal) def PInClip (inFA, minVal, maxVal, newVal): """ Replace values inside of a given range with a new value in = newVal where in >= minVal or in <= maxVal * inFA = input Python FArray * minVal = Minimum allowed value * maxVal = Maximum allowed value * newVal = Value to use if in range """ ################################################################ # Checks if not PIsA(inFA): print "Actually ",inFA.__class__ raise TypeError,"inFA MUST be a Python Obit FArray" Obit.FArrayInClip(inFA.me, minVal, maxVal, newVal) # end PInClip def PDivClip (inFA1, inFA2, minVal, outFA): """ Divide corresponding elements of the arrays with clipping. out = in1 / in2 where in2>minVal, else blanked * inFA1 = first input Python FArray * inFA2 = second input Python FArray * minVal = Minimum allowed value * outFA = Maximum allowed value """ ################################################################ # Checks if not PIsA(inFA1): print "Actually ",inFA1.__class__ raise TypeError,"inFA1 MUST be a Python Obit FArray" if not PIsA(inFA2): print "Actually ",inFA2.__class__ raise TypeError,"inFA2 MUST be a Python Obit FArray" if not PIsA(outFA): print "Actually ",outFA.__class__ raise TypeError,"outFA MUST be a Python Obit FArray" Obit.FArrayDivClip(inFA1.me, inFA2.me, minVal, outFA.me) def PClipBlank (inFA, minVal, maxVal): """ Replace values outside of a given range with blank value in = blank where in < minVal or in > maxVal * inFA = input Python FArray * minVal = Minimum allowed value * maxVal = Maximum allowed value """ ################################################################ # Checks if not PIsA(inFA): print "Actually ",inFA.__class__ raise TypeError,"inFA MUST be a Python Obit FArray" Obit.FArrayClipBlank(inFA.me, minVal, maxVal) def PBlank (in1, in2, out): """ Blank elements of array in1 where array in2 is blanked out = in1 or blank where in2 is blank * in1 = first input Python FArray * in2 = second input Python FArray with blanking * out = output Python FArray """ ################################################################ # Checks if not PIsCompatable (in1, in2): raise RuntimeError,"in1 and in2 have incompatable geometry" if not PIsCompatable (in1, out): raise RuntimeError,"in1 and out have incompatable geometry" Obit.FArrayBlank (in1.me, in2.me, out.me) def PSumArr (in1, in2, out): """ SSum nonblanked elements of two arrays out = (in1 + in2) or whichever is not blanked * in1 = first input Python FArray * in2 = second input Python FArray * out = output Python FArray """ ################################################################ # Checks if not PIsCompatable (in1, in2): raise RuntimeError,"in1 and in2 have incompatable geometry" if not PIsCompatable (in1, out): raise RuntimeError,"in1 and out have incompatable geometry" Obit.FArraySumArr (in1.me, in2.me, out.me) # end PSumArr def PAvgArr (in1, in2, out): """ Average nonblanked elements of two arrays. out = (in1 + in2)/2 or whichever is not blanked * in1 = first input Python FArray * in2 = second input Python FArray * out = output Python FArray """ ################################################################ # Checks if not PIsCompatable (in1, in2): raise RuntimeError,"in1 and in2 have incompatable geometry" if not PIsCompatable (in1, out): raise RuntimeError,"in1 and out have incompatable geometry" Obit.FArrayAvgArr (in1.me, in2.me, out.me) # end PAvgArr def PMaxArr (in1, in2, out): """ Pick the larger nonblanked elements of two arrays. out = MAX (in1, in2) or whichever is not blanked * in1 = first input Python FArray * in2 = second input Python FArray * out = output Python FArray """ ################################################################ # Checks if not PIsCompatable (in1, in2): raise RuntimeError,"in1 and in2 have incompatable geometry" if not PIsCompatable (in1, out): raise RuntimeError,"in1 and out have incompatable geometry" Obit.FArrayMaxArr (in1.me, in2.me, out.me) # end PMaxArr def PMinArr (in1, in2, out): """ Pick the lesser nonblanked elements of two arrays. out = MIN (in1, in2) or whichever is not blanked * in1 = first input Python FArray * in2 = second input Python FArray * out = output Python FArray """ ################################################################ # Checks if not PIsCompatable (in1, in2): raise RuntimeError,"in1 and in2 have incompatable geometry" if not PIsCompatable (in1, out): raise RuntimeError,"in1 and out have incompatable geometry" Obit.FArrayMinArr (in1.me, in2.me, out.me) # end PMinArr def PAdd (in1, in2, out): """ Add corresponding elements of two arrays. out = in1 + in2 * in1 = first input Python FArray * in2 = second input Python FArray * out = output Python FArray """ ################################################################ # Checks if not PIsCompatable (in1, in2): raise RuntimeError,"in1 and in2 have incompatable geometry" if not PIsCompatable (in1, out): raise RuntimeError,"in1 and out have incompatable geometry" Obit.FArrayAdd (in1.me, in2.me, out.me) def PSub (in1, in2, out): """ Subtract corresponding elements of the arrays. out = in1 - in2 * in1 = first input Python FArray * in2 = second input Python FArray * out = output Python FArray """ ################################################################ # Checks if not PIsCompatable (in1, in2): raise RuntimeError,"in1 and in2 have incompatable geometry" if not PIsCompatable (in1, out): raise RuntimeError,"in1 and out have incompatable geometry" Obit.FArraySub (in1.me, in2.me, out.me) def PMul (in1, in2, out): """ Multiply corresponding elements of the arrays. out = in1 * in2 * in1 = first input Python FArray * in2 = second input Python FArray * out = output Python FArray """ ################################################################ # Checks if not PIsCompatable (in1, in2): raise RuntimeError,"in1 and in2 have incompatable geometry" if not PIsCompatable (in1, out): raise RuntimeError,"in1 and out have incompatable geometry" Obit.FArrayMul (in1.me, in2.me, out.me) def PDiv (in1, in2, out): """ Divide corresponding elements of the arrays. out = in1 / in2 * in1 = first input Python FArray * in2 = second input Python FArray * out = output Python FArray """ ################################################################ # Checks if not PIsCompatable (in1, in2): raise RuntimeError,"in1 and in2 have incompatable geometry" if not PIsCompatable (in1, out): raise RuntimeError,"in1 and out have incompatable geometry" Obit.FArrayDiv (in1.me, in2.me, out.me) def PDot (in1, in2): """ Sum the products of the elements of two arrays return Sum (in1 x in2) * in1 = first input Python FArray * in2 = second input Python FArray """ ################################################################ # Checks if not PIsCompatable (in1, in2): raise RuntimeError,"in1 and in2 have incompatable geometry" return Obit.FArrayDot(in1.me, in2.me) def PMulColRow (inFA, row, col, out): """ Multiply elements of 2D array by row times column Multiply the elements of a 2D array by the corresponding elements of a row and column vector.returns cell contents out[i,j] = in[i,j] * row[j] * col[i] * inFA = input Python 2D FArray * row = "row" 1D Python FArray * col = "column" 1D Python FArray * out = output Python 2D FArray """ ################################################################ # Checks if not PIsA(inFA): print "Actually ",inFA.__class__ raise TypeError,"inFA MUST be a Python Obit FArray" Obit.FArrayMulColRow (inFA.me, row.me, col.me, out.me) def PCenter2D (inFA): """ Rearrange array for FFT In-place rearrangement of a center-at-the edges array to center at the center, or the other way around. This is needed for the peculiar order of FFTs. FFTs don't like blanked values. * inFA = input Python FArray """ ################################################################ # Checks if not PIsA(inFA): print "Actually ",inFA.__class__ raise TypeError,"inFA MUST be a Python Obit FArray" Obit.FArray2DCenter (inFA.me) def PSymInv2D (inFA): """ In-place inversion of a symmetric 2-D matrix return code, 0=>OK, else could not invert. Magic blanking not supported * inFA = input Python FArray with symmetric 2-D matrix """ ################################################################ # Checks if not PIsA(inFA): print "Actually ",inFA.__class__ raise TypeError,"inFA MUST be a Python Obit FArray" return Obit.FArray2DSymInv (inFA.me) def PCGauss2D (inFA, Cen, FWHM): """ Make 2-D Circular Gaussian Peak normalized to 1.0 * in = Python FArray to be modified * Cen = 0-rel pixel center as an array, e,g, [25,26] * FWMH = FWHM of Gaussian in pixels. """ ################################################################ # Checks if not PIsA(inFA): print "Actually ",inFA.__class__ raise TypeError,"inFA MUST be a Python Obit FArray" Obit.FArrayCGauss2D (inFA.me, Cen, FWHM) def PEGauss2D (inFA, amp, Cen, GauMod): """ Make 2-D Eliptical Gaussian in FAArray Peak normalized to 1.0, model is added to previous contents. * in = Python FArray to be modified * amp = peak value of Gaussian * Cen = 0-rel pixel center as an array, e,g, [25.0,26.0] * GauMod = Gaussian parameters, Major axis, FWHM, minor axis FWHM (both in pixels) and rotation angle wrt "Y" axis (deg). e.g. [3.0,3.0,0.0] """ ################################################################ # Checks if not PIsA(inFA): print "Actually ",inFA.__class__ raise TypeError,"inFA MUST be a Python Obit FArray" Obit.FArrayEGauss2D (inFA.me, amp, Cen, GauMod) def PShiftAdd (in1, pos1, in2, pos2, scalar, out): """ Shift and Add scaled arrays Two FArrays are aligned at specified pixels and the corresponding pixels are added with a scalar multiplied times the second. Only handles to 3 dimensions. If in1/out are 3D and in2 is 2D then the same plane in in2 is used for all planes in in1/out. out = in1 + scalar * in2 in overlap, else in1 * in1 = first input Python FArray * pos1 = allignment pixel (0-rel) in in1 as array * in2 = second input Python FArray * pos2 = allignment pixel (0-rel) in in2 as array * scalar = scalar multiplier * out = output Python FArray """ ################################################################ # Checks if not PIsCompatable (in1, out): raise RuntimeError,"in1 and out have incompatable geometry" if not PIsA(in2): print "Actually ",in2.__class__ raise TypeError,"inn2 MUST be a Python Obit FArray" Obit.FArrayShiftAdd (in1.me, pos1, in2.me, pos2, scalar, out.me) # end PShiftAdd def PPad (inFA, outFA, factor): """ Zero pad inFA into outFA and multiply by factor, deblank outFA is zero filled and the values in inFA are inserted, centered and multiplied by factor. Blanks in the output are replaced by zeroes. * inFA = input Python FArray to be centered in outFA * outFA = inFA where given and zero elsewhere * factor = scaling factor for inFA """ ################################################################ # Checks if not PIsA(inFA): print "Actually ",inFA.__class__ raise TypeError,"inFA MUST be a Python Obit FArray" if not PIsA(outFA): print "Actually ",outFA.__class__ raise TypeError,"outFA MUST be a Python Obit FArray" Obit.FArrayPad (inFA.me, outFA.me, factor) # end def PSelInc (inFA, outFA, blc, trc, inc, err): """ Select elements in an FArray by increment * inFA = input Python FArray * outFA= output Python FArray * blc = array giving (1-rel) lower index of first cell to copy, e.g. [1,1] * trc = array giving (1-rel) highest index of first cell to copy * inc = increment on each axis * err = Python Obit Error/message stack """ ################################################################ # Checks if not PIsA(inFA): print "Actually ",inFA.__class__ raise TypeError,"inFA MUST be a Python Obit FArray" if not PIsA(outFA): print "Actually ",outFA.__class__ raise TypeError,"outFA MUST be a Python Obit FArray" Obit.FArraySelInc (inFA.me, outFA.me, blc, trc, inc, err.me) if err.isErr: OErr.printErrMsg(err, "Error selecting FArray") return # end PSelInc def PHisto (inFA, n, min, max): """ Make histogram of FArray Return FArray with info elements * nHisto int Number of elements in histogram * Min float Minimum value in histogram * Max float Maximum value in histogram * Total float Total number of values in histogram * Under float Number of underflows in histogram * Over float Number of overflows in histogram * * inFA = input Python FArray * n = Number of elements in histogram * min = Min value in histogram * max = Max value in histogram * Uses threading """ ################################################################ # Checks if not PIsA(inFA): print "Actually ",inFA.__class__ raise TypeError,"inFA MUST be a Python Obit FArray" outFA = FArray("None") outFA.me = Obit.FArrayHisto (inFA.me, n, min, max) return outFA # end PHisto def PIsA (inFA): """ Tells if the input is a Python ObitFArray returns true or false (1,0) * inFA = Python Obit FArray to test """ ################################################################ # Checks if inFA.__class__ != FArray: return 0 return Obit.FArrayIsA(inFA.me) # end PIsA def PUnref (inFA): """ Decrement reference count Decrement reference count which will destroy object if it goes to zero Python object stays defined. * inFA = Python FArray object """ ################################################################ # Checks if not PIsA(inFA): raise TypeError,"inFA MUST be a Python Obit FArray" inFA.me = Obit.FArrayUnref(inFA.me) # end PUnref def PGetNdim (inFA): """ Returns the number of dimensions in array * inFA = Python Obit FArray """ ################################################################ # Checks if not PIsA(inFA): print "Actually ",inFA.__class__ raise TypeError,"inFA MUST be a Python Obit FArray" return Obit.FArrayGetNdim(inFA.me) # end PGetNdim def PGetNaxis (inFA): """ Returns array of 7 elements with dimensions in array * inFA = Python Obit FArray """ ################################################################ # Checks if not PIsA(inFA): print "Actually ",inFA.__class__ raise TypeError,"inFA MUST be a Python Obit FArray" return Obit.FArrayGetNaxis(inFA.me) # end PGetNaxis
[ "shubhankardeshpande@hotmail.com" ]
shubhankardeshpande@hotmail.com
b522870250e1c07e8b88d02a1e893cf58ff4abdb
6eb7dce0e5e44d3cb71748558015b91804f94d5d
/bloodhound_relations/bhrelations/tests/api.py
8df83ea2acfb739d2560d4295e00a42618b1b067
[ "LicenseRef-scancode-unknown-license-reference", "MIT", "Python-2.0", "BSD-3-Clause", "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer" ]
permissive
thimalk/bloodhound
ba40ef5fad2a45e8b8cdd945bc72eafdaee1a5ca
f836d8314d7863563f6252d74f798694465f81ea
refs/heads/master
2021-01-02T08:31:39.774465
2014-03-13T05:14:39
2014-03-13T05:14:39
null
0
0
null
null
null
null
UTF-8
Python
false
false
22,967
py
# -*- coding: UTF-8 -*- # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. from datetime import datetime import unittest from bhrelations.api import TicketRelationsSpecifics from bhrelations.tests.mocks import TestRelationChangingListener from bhrelations.validation import ValidationError from bhrelations.tests.base import BaseRelationsTestCase, PARENT, CHILD, \ DEPENDS_ON, DEPENDENCY_OF, BLOCKS, BLOCKED_BY, REFERS_TO, DUPLICATE_OF, \ MULTIPRODUCT_REL from multiproduct.env import ProductEnvironment from trac.ticket.model import Ticket from trac.core import TracError from trac.util.datefmt import utc class ApiTestCase(BaseRelationsTestCase): def test_can_add_two_ways_relations(self): #arrange ticket = self._insert_and_load_ticket("A1") ticket2 = self._insert_and_load_ticket("A2") #act self.add_relation(ticket, DEPENDENCY_OF, ticket2) #assert relations = self.get_relations(ticket) self.assertEqual(DEPENDENCY_OF, relations[0]["type"]) self.assertEqual(unicode(ticket2.id), relations[0]["destination"].id) relations = self.get_relations(ticket2) self.assertEqual(DEPENDS_ON, relations[0]["type"]) self.assertEqual(unicode(ticket.id), relations[0]["destination"].id) def test_can_add_single_way_relations(self): #arrange ticket = self._insert_and_load_ticket("A1") ticket2 = self._insert_and_load_ticket("A2") #act self.add_relation(ticket, REFERS_TO, ticket2) #assert relations = self.get_relations(ticket) self.assertEqual(1, len(relations)) self.assertEqual(REFERS_TO, relations[0]["type"]) self.assertEqual(unicode(ticket2.id), relations[0]["destination"].id) self.assertEqual(0, len(self.get_relations(ticket2))) def test_can_add_multiple_relations(self): #arrange ticket = self._insert_and_load_ticket("A1") ticket2 = self._insert_and_load_ticket("A2") ticket3 = self._insert_and_load_ticket("A3") #act self.add_relation(ticket, DEPENDS_ON, ticket2) self.add_relation(ticket, DEPENDS_ON, ticket3) #assert self.assertEqual(2, len(self.get_relations(ticket))) self.assertEqual(1, len(self.get_relations(ticket2))) self.assertEqual(1, len(self.get_relations(ticket3))) def test_will_not_create_more_than_one_identical_relations(self): #arrange ticket = self._insert_and_load_ticket("A1") ticket2 = self._insert_and_load_ticket("A2") #act self.add_relation(ticket, DEPENDS_ON, ticket2) self.assertRaisesRegexp( TracError, "already exists", self.add_relation, ticket, DEPENDS_ON, ticket2 ) def test_will_not_create_more_than_one_identical_relations_db_level(self): sql = """INSERT INTO bloodhound_relations (source, destination, type) VALUES (%s, %s, %s)""" with self.env.db_transaction as db: db(sql, ["1", "2", DEPENDS_ON]) self.assertRaises( self.env.db_exc.IntegrityError, db, sql, ["1", "2", DEPENDS_ON] ) def test_can_add_one_way_relations(self): #arrange ticket = self._insert_and_load_ticket("A1") ticket2 = self._insert_and_load_ticket("A2") #act self.add_relation(ticket, REFERS_TO, ticket2) #assert relations = self.get_relations(ticket) self.assertEqual(REFERS_TO, relations[0]["type"]) self.assertEqual(unicode(ticket2.id), relations[0]["destination"].id) self.assertEqual(0, len(self.get_relations(ticket2))) def test_can_delete_two_ways_relation(self): #arrange ticket = self._insert_and_load_ticket("A1") ticket2 = self._insert_and_load_ticket("A2") self.add_relation(ticket, DEPENDS_ON, ticket2) relations = self.get_relations(ticket) self.assertEqual(1, len(relations)) self.assertEqual(1, len(self.get_relations(ticket2))) #act self.delete_relation(relations[0]) #assert self.assertEqual(0, len(self.get_relations(ticket))) self.assertEqual(0, len(self.get_relations(ticket2))) def test_can_delete_single_way_relation(self): #arrange ticket = self._insert_and_load_ticket("A1") ticket2 = self._insert_and_load_ticket("A2") #act self.add_relation(ticket, REFERS_TO, ticket2) relations = self.get_relations(ticket) self.assertEqual(1, len(relations)) self.assertEqual(0, len(self.get_relations(ticket2))) #act self.delete_relation(relations[0]) #assert self.assertEqual(0, len(self.get_relations(ticket))) def test_can_not_add_cycled_immediate_relations(self): #arrange ticket1 = self._insert_and_load_ticket("A1") ticket2 = self._insert_and_load_ticket("A2") #act self.add_relation(ticket1, DEPENDS_ON, ticket2) try: self.add_relation(ticket2, DEPENDS_ON, ticket1) self.fail("Should throw an exception") except ValidationError as ex: self.assertSequenceEqual( ["tp1:ticket:2", "tp1:ticket:1"], ex.failed_ids) def test_can_add_more_depends_ons(self): #arrange ticket1 = self._insert_and_load_ticket("A1") ticket2 = self._insert_and_load_ticket("A2") ticket3 = self._insert_and_load_ticket("A3") #act self.add_relation(ticket1, DEPENDS_ON, ticket2) self.add_relation(ticket1, DEPENDS_ON, ticket3) self.assertEqual(2, len(self.get_relations(ticket1))) def test_can_not_add_cycled_in_different_direction(self): #arrange ticket1 = self._insert_and_load_ticket("A1") ticket2 = self._insert_and_load_ticket("A2") #act self.add_relation(ticket1, DEPENDS_ON, ticket2) self.assertRaises( ValidationError, self.add_relation, ticket1, DEPENDENCY_OF, ticket2 ) def test_can_not_add_cycled_relations(self): #arrange ticket1 = self._insert_and_load_ticket("A1") ticket2 = self._insert_and_load_ticket("A2") ticket3 = self._insert_and_load_ticket("A3") #act self.add_relation(ticket1, DEPENDS_ON, ticket2) self.add_relation(ticket2, DEPENDS_ON, ticket3) self.assertRaises( ValidationError, self.add_relation, ticket3, DEPENDS_ON, ticket1 ) def test_can_not_add_more_than_one_parent(self): #arrange child = self._insert_and_load_ticket("A1") parent1 = self._insert_and_load_ticket("A2") parent2 = self._insert_and_load_ticket("A3") #act self.add_relation(parent1, PARENT, child) self.assertRaises( ValidationError, self.add_relation, parent2, PARENT, child ) self.assertRaises( ValidationError, self.add_relation, child, CHILD, parent2 ) def test_can_add_more_than_one_child(self): parent = self._insert_and_load_ticket("A1") child1 = self._insert_and_load_ticket("A2") child2 = self._insert_and_load_ticket("A3") self.add_relation(parent, PARENT, child1) self.add_relation(parent, PARENT, child2) self.assertEqual(2, len(self.get_relations(parent))) def test_ticket_can_be_resolved(self): #arrange parent = self._insert_and_load_ticket("A1") child = self._insert_and_load_ticket("A2") #act self.add_relation(parent, PARENT, child) self.req.args['action'] = 'resolve' warnings = \ TicketRelationsSpecifics(self.env).validate_ticket(self.req, child) self.assertEqual(0, len(list(warnings))) def test_can_save_and_load_relation_time(self): #arrange ticket1 = self._insert_and_load_ticket("A1") ticket2 = self._insert_and_load_ticket("A2") #act time = datetime.now(utc) self.add_relation(ticket1, DEPENDS_ON, ticket2, when=time) relations = self.get_relations(ticket1) #assert self.assertEqual(time, relations[0]["when"]) def test_cannot_resolve_ticket_when_blocker_is_unresolved(self): #arrange ticket1 = self._insert_and_load_ticket("A1") ticket2 = self._insert_and_load_ticket("A2") self.add_relation(ticket1, DEPENDS_ON, ticket2) #act self.req.args["action"] = 'resolve' warnings = TicketRelationsSpecifics(self.env).validate_ticket( self.req, ticket1) #asset self.assertEqual(1, len(list(warnings))) def test_can_resolve_ticket_when_blocker_is_resolved(self): #arrange ticket1 = self._insert_and_load_ticket("A1") ticket2 = self._insert_and_load_ticket("A2", status="closed") self.add_relation(ticket1, DEPENDS_ON, ticket2) #act self.req.args["action"] = 'resolve' warnings = TicketRelationsSpecifics(self.env).validate_ticket( self.req, ticket1) #assert self.assertEqual(0, len(list(warnings))) def test_that_relations_are_deleted_when_ticket_is_deleted(self): #arrange ticket1 = self._insert_and_load_ticket("A1") ticket2 = self._insert_and_load_ticket("A2") self.add_relation(ticket1, DEPENDS_ON, ticket2) self.assertEqual(1, len(self.get_relations(ticket2))) #act ticket1.delete() #assert self.assertEqual(0, len(self.get_relations(ticket2))) def test_that_no_error_when_deleting_ticket_without_relations(self): #arrange ticket1 = self._insert_and_load_ticket("A1") #act ticket1.delete() def test_can_add_multi_product_relations(self): ticket1 = self._insert_and_load_ticket("A1") product2 = "tp2" self._load_product_from_data(self.global_env, product2) p2_env = ProductEnvironment(self.global_env, product2) ticket2 = self._insert_and_load_ticket_with_env(p2_env, "A2") self.add_relation(ticket1, MULTIPRODUCT_REL, ticket2) self.assertEqual(1, len(self.get_relations(ticket1))) self.assertEqual(1, len(self.get_relations(ticket2))) def _debug_select(self): """ used for debug purposes """ print " source, destination, type" sql = "SELECT source, destination, type FROM bloodhound_relations" with self.env.db_query as db: # for row in db(sql, ("source", "destination", "type")): for row in db(sql): print row def test_parent_relation_is_incompatible_with_two_way_relations(self): ticket1 = self._insert_and_load_ticket("A1") ticket2 = self._insert_and_load_ticket("A2") self.add_relation(ticket2, DEPENDS_ON, ticket1) self.assertRaises( ValidationError, self.add_relation, ticket1, PARENT, ticket2 ) self.assertRaises( ValidationError, self.add_relation, ticket1, CHILD, ticket2 ) def test_parent_relation_is_incompatible_with_one_way_relations(self): ticket1 = self._insert_and_load_ticket("A1") ticket2 = self._insert_and_load_ticket("A2") self.add_relation(ticket1, REFERS_TO, ticket2) self.assertRaises( ValidationError, self.add_relation, ticket1, PARENT, ticket2 ) self.assertRaises( ValidationError, self.add_relation, ticket1, CHILD, ticket2 ) def test_parent_must_be_in_same_product(self): ticket1 = self._insert_and_load_ticket("A1") product2 = "tp2" self._load_product_from_data(self.global_env, product2) p2_env = ProductEnvironment(self.global_env, product2) ticket2 = self._insert_and_load_ticket_with_env(p2_env, "A2") self.assertRaises( ValidationError, self.add_relation, ticket1, PARENT, ticket2 ) self.assertRaises( ValidationError, self.add_relation, ticket1, CHILD, ticket2 ) def test_cannot_create_other_relations_between_descendants(self): t1, t2, t3, t4, t5 = map(self._insert_and_load_ticket, "12345") self.add_relation(t1, PARENT, t2) # t1 -> t2 self.add_relation(t2, PARENT, t3) # / \ self.add_relation(t2, PARENT, t4) # t3 t4 self.assertRaises( ValidationError, self.add_relation, t2, DEPENDS_ON, t1 ) self.assertRaises( ValidationError, self.add_relation, t1, DEPENDS_ON, t2 ) self.assertRaises( ValidationError, self.add_relation, t4, DEPENDS_ON, t1 ) self.assertRaises( ValidationError, self.add_relation, t1, DEPENDS_ON, t3 ) try: self.add_relation(t1, DEPENDS_ON, t5) self.add_relation(t3, DEPENDS_ON, t4) except ValidationError: self.fail("Could not add valid relation.") def test_cannot_add_parent_if_this_would_cause_invalid_relations(self): t1, t2, t3, t4, t5 = map(self._insert_and_load_ticket, "12345") self.add_relation(t1, PARENT, t2) # t1 -> t2 self.add_relation(t2, PARENT, t3) # / \ self.add_relation(t2, PARENT, t4) # t3 t4 t5 self.add_relation(t2, DEPENDS_ON, t5) self.assertRaises( ValidationError, self.add_relation, t2, PARENT, t5 ) self.assertRaises( ValidationError, self.add_relation, t3, PARENT, t5 ) self.assertRaises( ValidationError, self.add_relation, t5, PARENT, t1, ) try: self.add_relation(t1, PARENT, t5) except ValidationError: self.fail("Could not add valid relation.") def test_cannot_close_ticket_with_open_children(self): t1 = self._insert_and_load_ticket("1") # t1 t2 = self._insert_and_load_ticket("2", status='closed') # / | \ t3 = self._insert_and_load_ticket("3") # t2 t3 t4 t4 = self._insert_and_load_ticket("4") self.add_relation(t1, PARENT, t2) self.add_relation(t1, PARENT, t3) self.add_relation(t1, PARENT, t4) # A warning is be returned for each open ticket self.req.args["action"] = 'resolve' warnings = \ TicketRelationsSpecifics(self.env).validate_ticket(self.req, t1) self.assertEqual(2, len(list(warnings))) def test_duplicate_can_only_reference_older_ticket(self): t1 = self._insert_and_load_ticket("1") t2 = self._insert_and_load_ticket("2") self.assertRaises( ValidationError, self.add_relation, t1, DUPLICATE_OF, t2 ) self.add_relation(t2, DUPLICATE_OF, t1) def test_detects_blocker_cycles(self): t1, t2, t3, t4, t5 = map(self._insert_and_load_ticket, "12345") self.add_relation(t1, BLOCKS, t2) self.add_relation(t3, DEPENDS_ON, t2) self.add_relation(t4, BLOCKED_BY, t3) self.add_relation(t4, DEPENDENCY_OF, t5) self.assertRaises( ValidationError, self.add_relation, t2, BLOCKS, t1 ) self.assertRaises( ValidationError, self.add_relation, t3, DEPENDENCY_OF, t1 ) self.assertRaises( ValidationError, self.add_relation, t1, BLOCKED_BY, t2 ) self.assertRaises( ValidationError, self.add_relation, t1, DEPENDS_ON, t5 ) self.add_relation(t1, DEPENDENCY_OF, t2) self.add_relation(t2, BLOCKS, t3) self.add_relation(t4, DEPENDS_ON, t3) self.add_relation(t5, BLOCKED_BY, t4) self.add_relation(t1, REFERS_TO, t2) self.add_relation(t2, REFERS_TO, t1) def test_can_find_ticket_by_id_from_same_env(self): """ Can find ticket given #id""" product2 = "tp2" self._load_product_from_data(self.global_env, product2) p2_env = ProductEnvironment(self.global_env, product2) t1 = self._insert_and_load_ticket_with_env(p2_env, "T1") trs = TicketRelationsSpecifics(p2_env) ticket = trs.find_ticket("#%d" % t1.id) self.assertEqual(ticket.id, 1) def test_can_find_ticket_by_id_from_different_env(self): """ Can find ticket from different env given #id""" product2 = "tp2" self._load_product_from_data(self.global_env, product2) p2_env = ProductEnvironment(self.global_env, product2) t1 = self._insert_and_load_ticket_with_env(p2_env, "T1") trs = TicketRelationsSpecifics(self.env) ticket = trs.find_ticket("#%d" % t1.id) self.assertEqual(ticket.id, 1) def test_can_find_ticket_by_product_and_id(self): """ Can find ticket given #prefix-id""" product2 = "tp2" self._load_product_from_data(self.global_env, product2) p2_env = ProductEnvironment(self.global_env, product2) t1 = self._insert_and_load_ticket_with_env(p2_env, "T1") trs = TicketRelationsSpecifics(self.env) ticket = trs.find_ticket("#%s-%d" % (product2, t1.id)) self.assertEqual(ticket.id, 1) class RelationChangingListenerTestCase(BaseRelationsTestCase): def test_can_sent_adding_event(self): #arrange ticket1 = self._insert_and_load_ticket("A1") ticket2 = self._insert_and_load_ticket("A2") test_changing_listener = self.env[TestRelationChangingListener] #act self.add_relation(ticket1, DEPENDS_ON, ticket2) #assert self.assertEqual("adding_relation", test_changing_listener.action) relation = test_changing_listener.relation self.assertEqual(DEPENDS_ON, relation.type) def test_can_sent_deleting_event(self): #arrange ticket1 = self._insert_and_load_ticket("A1") ticket2 = self._insert_and_load_ticket("A2") test_changing_listener = self.env[TestRelationChangingListener] self.add_relation(ticket1, DEPENDS_ON, ticket2) #act relations = self.get_relations(ticket1) self.delete_relation(relations[0]) #assert self.assertEqual("deleting_relation", test_changing_listener.action) relation = test_changing_listener.relation self.assertEqual(DEPENDS_ON, relation.type) class TicketChangeRecordUpdaterTestCase(BaseRelationsTestCase): def test_can_update_ticket_history_on_relation_add_on(self): #arrange ticket1 = self._insert_and_load_ticket("A1") ticket2 = self._insert_and_load_ticket("A2") #act self.add_relation(ticket1, DEPENDS_ON, ticket2) #assert change_log1 = Ticket(self.env, ticket1.id).get_changelog() self.assertEquals(1, len(change_log1)) change_log2 = Ticket(self.env, ticket2.id).get_changelog() self.assertEquals(1, len(change_log2)) def test_can_update_ticket_history_on_relation_deletion(self): #arrange ticket1 = self._insert_and_load_ticket("A1") ticket2 = self._insert_and_load_ticket("A2") self.add_relation(ticket1, DEPENDS_ON, ticket2) relations = self.get_relations(ticket1) #act self.delete_relation(relations[0]) #assert change_log1 = Ticket(self.env, ticket1.id).get_changelog() self.assertEquals(2, len(change_log1)) change_log2 = Ticket(self.env, ticket2.id).get_changelog() self.assertEquals(2, len(change_log2)) def _debug_select(self, ticket_id=None): """ used for debug purposes """ # print " source, destination, type" sql = "SELECT * FROM ticket_change" print "db_direct_transaction result:" with self.env.db_direct_transaction as db: # for row in db(sql, ("source", "destination", "type")): for row in db(sql): print row sql = "SELECT * FROM ticket_change" print "db_transaction result:" with self.env.db_transaction as db: for row in db(sql): print row if ticket_id: sql = """SELECT time, author, field, oldvalue, newvalue FROM ticket_change WHERE ticket=%s""" print "db_transaction select by ticket_id result:" with self.env.db_transaction: for row in self.env.db_query(sql, (ticket_id, )): print row def suite(): test_suite = unittest.TestSuite() test_suite.addTest(unittest.makeSuite(ApiTestCase, 'test')) test_suite.addTest(unittest.makeSuite( RelationChangingListenerTestCase, 'test')) test_suite.addTest(unittest.makeSuite( TicketChangeRecordUpdaterTestCase, 'test')) return test_suite if __name__ == '__main__': unittest.main()
[ "tkempitiya@gmail.com" ]
tkempitiya@gmail.com
6979f3f8d77744f8a56be1a9293b249bbeb34f0b
b95e49d381940c8e36ef638e954ca06e36c3be25
/app.py
15c5721608b81db64f886969f2e77e49ba55d3c4
[]
no_license
bloogrox/dramatiq-starter
4ca790db63b78b124d1b1000c82425355ccaa3d7
7190768634a56e52bc5443aa858fb9b63b5ecdc6
refs/heads/master
2020-06-17T07:08:04.669197
2019-07-08T15:31:34
2019-07-08T15:31:34
null
0
0
null
null
null
null
UTF-8
Python
false
false
155
py
import dramatiq from dramatiq.brokers.redis import RedisBroker import settings broker = RedisBroker(url=settings.REDIS_URL) dramatiq.set_broker(broker)
[ "bloogrox@gmail.com" ]
bloogrox@gmail.com
b38dad9bbbe53949d2bc4a67748445a1daa1bbd4
4a4717f88a0a5ea174098a342057759561f1688b
/scripts/util/diagnose_huc12.py
7a6f1b21daa14ced31b9160195e2675f6817b81d
[ "MIT" ]
permissive
timsklenar/dep
73ccf3ef18fe6a22f2cecba7878dcff709efea57
5bf9e0cd335825dcb50f22ee4c5c9c5ccc866114
refs/heads/master
2021-04-12T10:15:35.680758
2018-02-16T17:43:39
2018-02-16T17:43:39
null
0
0
null
null
null
null
UTF-8
Python
false
false
1,448
py
"""Do some diagnostics on what the raw DEP files are telling us""" from __future__ import print_function import sys import glob from pyiem import dep import pandas as pd def summarize_hillslopes(huc12, scenario): """Print out top hillslopes""" envs = glob.glob("/i/%s/env/%s/%s/*.env" % (scenario, huc12[:8], huc12[8:])) dfs = [] for env in envs: df = dep.read_env(env) df['flowpath'] = int(env.split("/")[-1].split("_")[1][:-4]) dfs.append(df) df = pd.concat(dfs) df2 = df[['sed_del', 'flowpath']].groupby( 'flowpath').sum().sort_values('sed_del', ascending=False) print("==== TOP 5 HIGHEST SEDIMENT DELIVERY TOTALS") print(df2.head()) flowpath = df2.index[0] df2 = df[df['flowpath'] == flowpath].sort_values('sed_del', ascending=False) print("==== TOP 5 HIGHEST SEDIMENT DELIVERY FOR %s" % (flowpath, )) print(df2[['date', 'sed_del', 'precip', 'runoff', 'av_det']].head()) df3 = df2.groupby('year').sum().sort_values('sed_del', ascending=False) print("==== TOP 5 HIGHEST SEDIMENT DELIVERY EVENTS FOR %s" % (flowpath, )) print(df3[['sed_del', 'precip', 'runoff', 'av_det']].head()) def main(argv): """Go Main""" huc12 = argv[1] scenario = argv[2] summarize_hillslopes(huc12, scenario) if __name__ == '__main__': main(sys.argv)
[ "akrherz@iastate.edu" ]
akrherz@iastate.edu
ba7462e3fe1257347ea3f0e2c36da7cd650c65ff
855511810dd54fa2406442db034079f76a73f869
/netbox_rest/models/tenant_group_serializer.py
061de64d5963c72c8274440c79d1638b951e0d21
[]
no_license
jlongever/netbox-serv
2da55778ded70031bd7500b4bf7aebb9d814dbbc
b281c7b7ef1571ad71f46dc155c2e0e2dd19b217
refs/heads/master
2020-09-10T02:16:23.555873
2018-10-29T18:29:17
2018-10-29T18:29:17
66,660,836
2
0
null
2018-10-29T18:29:18
2016-08-26T15:59:25
Python
UTF-8
Python
false
false
4,445
py
# coding: utf-8 """ No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen) OpenAPI spec version: Generated by: https://github.com/swagger-api/swagger-codegen.git Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. """ from pprint import pformat from six import iteritems import re class TenantGroupSerializer(object): """ NOTE: This class is auto generated by the swagger code generator program. Do not edit the class manually. """ def __init__(self, id=None, name=None, slug=None): """ TenantGroupSerializer - a model defined in Swagger :param dict swaggerTypes: The key is attribute name and the value is attribute type. :param dict attributeMap: The key is attribute name and the value is json key in definition. """ self.swagger_types = { 'id': 'int', 'name': 'str', 'slug': 'str' } self.attribute_map = { 'id': 'id', 'name': 'name', 'slug': 'slug' } self._id = id self._name = name self._slug = slug @property def id(self): """ Gets the id of this TenantGroupSerializer. :return: The id of this TenantGroupSerializer. :rtype: int """ return self._id @id.setter def id(self, id): """ Sets the id of this TenantGroupSerializer. :param id: The id of this TenantGroupSerializer. :type: int """ self._id = id @property def name(self): """ Gets the name of this TenantGroupSerializer. :return: The name of this TenantGroupSerializer. :rtype: str """ return self._name @name.setter def name(self, name): """ Sets the name of this TenantGroupSerializer. :param name: The name of this TenantGroupSerializer. :type: str """ self._name = name @property def slug(self): """ Gets the slug of this TenantGroupSerializer. :return: The slug of this TenantGroupSerializer. :rtype: str """ return self._slug @slug.setter def slug(self, slug): """ Sets the slug of this TenantGroupSerializer. :param slug: The slug of this TenantGroupSerializer. :type: str """ self._slug = slug def to_dict(self): """ Returns the model properties as a dict """ result = {} for attr, _ in iteritems(self.swagger_types): value = getattr(self, attr) if isinstance(value, list): result[attr] = list(map( lambda x: x.to_dict() if hasattr(x, "to_dict") else x, value )) elif hasattr(value, "to_dict"): result[attr] = value.to_dict() elif isinstance(value, dict): result[attr] = dict(map( lambda item: (item[0], item[1].to_dict()) if hasattr(item[1], "to_dict") else item, value.items() )) else: result[attr] = value return result def to_str(self): """ Returns the string representation of the model """ return pformat(self.to_dict()) def __repr__(self): """ For `print` and `pprint` """ return self.to_str() def __eq__(self, other): """ Returns true if both objects are equal """ return self.__dict__ == other.__dict__ def __ne__(self, other): """ Returns true if both objects are not equal """ return not self == other
[ "joseph.longever@emc.com" ]
joseph.longever@emc.com
0bd2dc91e623ecbdacd96734ca3e54d446aee70d
02f937609df114477f746342b37e690d24c181e8
/src/venv/bin/easy_install-3.5
98872eb640733614f2356aad9294485234d277eb
[]
no_license
summukhe/SequenceStructureAnalysis
b419663e81541a028f062cbeaf2c8f81503e12da
6e9e161a8ad89f627be9b5a2bf82d26f28b4b431
refs/heads/master
2021-05-05T23:34:05.824732
2018-01-16T17:43:06
2018-01-16T17:43:06
116,802,653
0
0
null
null
null
null
UTF-8
Python
false
false
449
5
#!/home/sumanta/PycharmProjects/RLECode/venv/bin/python # EASY-INSTALL-ENTRY-SCRIPT: 'setuptools==28.8.0','console_scripts','easy_install-3.5' __requires__ = 'setuptools==28.8.0' import re import sys from pkg_resources import load_entry_point if __name__ == '__main__': sys.argv[0] = re.sub(r'(-script\.pyw?|\.exe)?$', '', sys.argv[0]) sys.exit( load_entry_point('setuptools==28.8.0', 'console_scripts', 'easy_install-3.5')() )
[ "sumant199@gmail.com" ]
sumant199@gmail.com
1741d5b1a6df9deb02ed43335f02689dd7b7b402
caf192dbc1ca90fee18bb4ce170d37eb14870ec5
/Chapter-11/16. statSet class.py
0491ce9ba16dcf1268379fbd7681333026d5dfdf
[]
no_license
Dfredude/PythonZelle
858b00f5eacce841173c64b3cecd978dedbeb145
1923fe84df604968eebc5269f23b7c0f167d55f0
refs/heads/main
2023-08-30T21:45:57.070344
2021-10-17T01:32:57
2021-10-17T01:32:57
359,041,963
0
0
null
null
null
null
UTF-8
Python
false
false
1,036
py
from math import sqrt from random import randrange class StatSet: def __init__(self) -> None: self.values = [] def addNumber(self, x): self.values.append(x) def mean(self): return sum(self.values)/len(self.values) def median(self): self.n = len(self.values) if self.n % 2 != 0: self.median = self.values[self.n//2+1] else: m = self.n/2 self.median = (self.values[m] + self.values[m+1]) / 2 return self.median def stdDev(self): sumDevSq = 0 xbar = self.mean() for num in self.values: dev = num - xbar sumDevSq = sumDevSq + dev * dev return sqrt(sumDevSq/(len(self.values)-1)) def count(self): return len(self.values) def min(self): return min(self.values) def max(self): return max(self.values) def main(): mySet = StatSet() for i in range(10): mySet.addNumber(randrange(1,10)) print(mySet.mean(), mySet.stdDev()) if __name__ == '__main__': main()
[ "dominguezlucio@outlook.com" ]
dominguezlucio@outlook.com
1187e8c7ed00d2c08ff2a256d63db25edd0638f7
4c677ad71ee5b30e4957ae42fbd00ad7b90a4c2d
/backend/lively_union_27810/settings.py
754d3bbe5e18416be076dfc95a76026589bd39c5
[]
no_license
crowdbotics-apps/lively-union-27810
27ce491b2fd13c5f4413039567f96792abe71668
4c8b6e63a628a1ba9759b7e59fc0f2e578cae120
refs/heads/master
2023-05-27T06:10:19.350996
2021-06-07T18:51:47
2021-06-07T18:51:47
374,769,497
0
0
null
null
null
null
UTF-8
Python
false
false
7,120
py
""" Django settings for lively_union_27810 project. Generated by 'django-admin startproject' using Django 2.2.2. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os import environ import logging env = environ.Env() # SECURITY WARNING: don't run with debug turned on in production! DEBUG = env.bool("DEBUG", default=False) # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = env.str("SECRET_KEY") ALLOWED_HOSTS = env.list("HOST", default=["*"]) SITE_ID = 1 SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https") SECURE_SSL_REDIRECT = env.bool("SECURE_REDIRECT", default=False) # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites' ] LOCAL_APPS = [ 'home', 'modules', 'users.apps.UsersConfig', ] THIRD_PARTY_APPS = [ 'rest_framework', 'rest_framework.authtoken', 'rest_auth', 'rest_auth.registration', 'bootstrap4', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.google', 'django_extensions', 'drf_yasg', 'storages', # start fcm_django push notifications 'fcm_django', # end fcm_django push notifications ] INSTALLED_APPS += LOCAL_APPS + THIRD_PARTY_APPS MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'lively_union_27810.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'web_build')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'lively_union_27810.wsgi.application' # Database # https://docs.djangoproject.com/en/2.2/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } if env.str("DATABASE_URL", default=None): DATABASES = { 'default': env.db() } # Password validation # https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/2.2/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/2.2/howto/static-files/ STATIC_URL = '/static/' MIDDLEWARE += ['whitenoise.middleware.WhiteNoiseMiddleware'] AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend' ) STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles") STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static'), os.path.join(BASE_DIR, 'web_build/static')] STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' # allauth / users ACCOUNT_EMAIL_REQUIRED = True ACCOUNT_AUTHENTICATION_METHOD = 'email' ACCOUNT_USERNAME_REQUIRED = False ACCOUNT_EMAIL_VERIFICATION = "optional" ACCOUNT_CONFIRM_EMAIL_ON_GET = True ACCOUNT_LOGIN_ON_EMAIL_CONFIRMATION = True ACCOUNT_UNIQUE_EMAIL = True LOGIN_REDIRECT_URL = "users:redirect" ACCOUNT_ADAPTER = "users.adapters.AccountAdapter" SOCIALACCOUNT_ADAPTER = "users.adapters.SocialAccountAdapter" ACCOUNT_ALLOW_REGISTRATION = env.bool("ACCOUNT_ALLOW_REGISTRATION", True) SOCIALACCOUNT_ALLOW_REGISTRATION = env.bool("SOCIALACCOUNT_ALLOW_REGISTRATION", True) REST_AUTH_SERIALIZERS = { # Replace password reset serializer to fix 500 error "PASSWORD_RESET_SERIALIZER": "home.api.v1.serializers.PasswordSerializer", } REST_AUTH_REGISTER_SERIALIZERS = { # Use custom serializer that has no username and matches web signup "REGISTER_SERIALIZER": "home.api.v1.serializers.SignupSerializer", } # Custom user model AUTH_USER_MODEL = "users.User" EMAIL_HOST = env.str("EMAIL_HOST", "smtp.sendgrid.net") EMAIL_HOST_USER = env.str("SENDGRID_USERNAME", "") EMAIL_HOST_PASSWORD = env.str("SENDGRID_PASSWORD", "") EMAIL_PORT = 587 EMAIL_USE_TLS = True # AWS S3 config AWS_ACCESS_KEY_ID = env.str("AWS_ACCESS_KEY_ID", "") AWS_SECRET_ACCESS_KEY = env.str("AWS_SECRET_ACCESS_KEY", "") AWS_STORAGE_BUCKET_NAME = env.str("AWS_STORAGE_BUCKET_NAME", "") AWS_STORAGE_REGION = env.str("AWS_STORAGE_REGION", "") USE_S3 = ( AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY and AWS_STORAGE_BUCKET_NAME and AWS_STORAGE_REGION ) if USE_S3: AWS_S3_CUSTOM_DOMAIN = env.str("AWS_S3_CUSTOM_DOMAIN", "") AWS_S3_OBJECT_PARAMETERS = {"CacheControl": "max-age=86400"} AWS_DEFAULT_ACL = env.str("AWS_DEFAULT_ACL", "public-read") AWS_MEDIA_LOCATION = env.str("AWS_MEDIA_LOCATION", "media") AWS_AUTO_CREATE_BUCKET = env.bool("AWS_AUTO_CREATE_BUCKET", True) DEFAULT_FILE_STORAGE = env.str( "DEFAULT_FILE_STORAGE", "home.storage_backends.MediaStorage" ) MEDIA_URL = '/mediafiles/' MEDIA_ROOT = os.path.join(BASE_DIR, 'mediafiles') # start fcm_django push notifications FCM_DJANGO_SETTINGS = { "FCM_SERVER_KEY": env.str("FCM_SERVER_KEY", "") } # end fcm_django push notifications # Swagger settings for api docs SWAGGER_SETTINGS = { "DEFAULT_INFO": f"{ROOT_URLCONF}.api_info", } if DEBUG or not (EMAIL_HOST_USER and EMAIL_HOST_PASSWORD): # output email to console instead of sending if not DEBUG: logging.warning("You should setup `SENDGRID_USERNAME` and `SENDGRID_PASSWORD` env vars to send emails.") EMAIL_BACKEND = "django.core.mail.backends.console.EmailBackend"
[ "team@crowdbotics.com" ]
team@crowdbotics.com
408cbc35305ce711a6c9ec7410db919a0b7c642c
781e2692049e87a4256320c76e82a19be257a05d
/all_data/exercism_data/python/bob/8fb1675764894b0597301daa1e12a109.py
d160506f4701990580a9759cca9758df671ffba8
[]
no_license
itsolutionscorp/AutoStyle-Clustering
54bde86fe6dbad35b568b38cfcb14c5ffaab51b0
be0e2f635a7558f56c61bc0b36c6146b01d1e6e6
refs/heads/master
2020-12-11T07:27:19.291038
2016-03-16T03:18:00
2016-03-16T03:18:42
59,454,921
4
0
null
2016-05-23T05:40:56
2016-05-23T05:40:56
null
UTF-8
Python
false
false
216
py
def hey(prompt): if prompt.strip() == "": return "Fine. Be that way!" if prompt.isupper(): return "Woah, chill out!" if prompt.endswith("?"): return "Sure." return "Whatever."
[ "rrc@berkeley.edu" ]
rrc@berkeley.edu
b3017ebe21427087f950b2b556cbeecdfffff87b
4377dddadb615c632ea49851c986cff096b79358
/money/contrib/django/currencies/models.py
a5717692ecee69c2909275020fb9a66483ec3668
[]
no_license
cuker/python-money
ff203d42fce5c7fcb365474688d3d53902ba512d
4a7d97208f39568f8a1472f635264aedaa321edf
refs/heads/master
2021-01-23T12:38:17.451084
2011-06-07T23:10:06
2011-06-07T23:10:06
472,834
0
1
null
null
null
null
UTF-8
Python
false
false
2,593
py
from django.db import models from django.conf import settings import money from decimal import Decimal class CurrencyManager(models.Manager): def active(self): return self.all().filter(enabled=True) def default(self): return self.get(default=True) get_default = default def __getitem__(self, code): try: return self.get(code=code) except self.model.DoesNotExist: raise KeyError, 'currency "%s" was not found' % code class Currency(models.Model, money.BaseCurrency): name = models.CharField(max_length=60) code = models.CharField(max_length=3, primary_key=True) numeric = models.CharField(max_length=5) enabled = models.BooleanField(default=True, db_index=True) exchange_rate = models.DecimalField(max_digits=10, decimal_places=5, null=True, blank=True) default = models.BooleanField(default=False, db_index=True) if 'countries' in settings.INSTALLED_APPS: from countries.models import Country countries = models.ManyToManyField(Country) objects = CurrencyManager() def __unicode__(self): return self.name def save(self, *args, **kwargs): if self.default and self.pk: type(self).objects.exclude(pk=self.pk, default=False).update(default=False) return models.Model.save(self, *args, **kwargs) class Meta: ordering = ['-default', 'code'] verbose_name_plural = "currencies" ORIGINAL_CURRENCIES = money.currency_provider() money.set_currency_provider(Currency.objects) def _load_currencies(): for key, value in ORIGINAL_CURRENCIES.iteritems(): if key == 'XXX': continue Currency.objects.get_or_create(name=value.name, code=value.code, numeric=value.numeric) try: Currency.objects.default() except Currency.DoesNotExist: new_default = Currency.objects['USD'] new_default.default = True new_default.save() def _load_exchange_rates(): import urllib from_currency = Currency.objects.default() kwargs = {'from':from_currency.code,} url = 'http://quote.yahoo.com/d/quotes.csv?s=%(from)s%(to)s=X&f=l1&e=.csv' for target in Currency.objects.filter(default=False): kwargs['to'] = target.code response = urllib.urlopen(url % kwargs).read() try: target.exchange_rate = Decimal(response.strip()) except ValueError: pass else: target.save()
[ "jasonk@cukerinteractive.com" ]
jasonk@cukerinteractive.com
c7434530e7790a420c197b0d3fc5f0f35b2948c1
da5849cc6ab950a716131fb8c2bee2267e627463
/python/datascience/numpy/recipe_1d.py
b1bdead51f7598c22da45a0bcf6d1f5d3f3c8964
[]
no_license
leisheyoufu/study_exercise
5e3beba7763f2dfafa426932e21f110df1fd150e
db58097f4b542aea894b11feae31fb26006d5ebc
refs/heads/master
2023-08-16T21:29:26.967795
2023-08-11T03:09:31
2023-08-11T03:09:31
13,537,939
3
1
null
2023-09-05T21:59:21
2013-10-13T11:13:29
Jupyter Notebook
UTF-8
Python
false
false
550
py
import numpy as np def display_shape(a): print print print "Number of elements in a = %d" % (a.size) print "Number of dimensions in a =%d" % (a.ndim) print "Rows and Columns in a ", a.shape print # Create a matrix with all elements ones_matrix = np.ones((3,3)) # 1 display_shape(ones_matrix) # Create a matrix with all elements zeros_matrix = np.zeros((3,3)) display_shape(zeros_matrix) identity_matrix = np.eye(N=3,M=3,k=0) display_shape(identity_matrix) identity_matrix = np.eye(N=3,k=1) display_shape(identity_matrix)
[ "chenglch@cn.ibm.com" ]
chenglch@cn.ibm.com
279022106044acde6f309ffab694367745451504
6f121febfccf83eee48aa84d4b169903122af332
/run.py
e181f717d419cdc6c9aca2753795321765d944aa
[ "MIT" ]
permissive
bipabo1l/DarkNet_ChineseTrading
b2e7edc8a7fa4e0a5cd5336a90b119bedadf30f8
601acd28f15a8f4298757dfe8243ebeacf17e687
refs/heads/master
2020-04-17T08:27:20.847210
2019-01-16T06:47:22
2019-01-16T06:47:22
null
0
0
null
null
null
null
UTF-8
Python
false
false
18,353
py
import json import logging import math import os import random import re import string import sys import time from base64 import b64encode from urllib.parse import urljoin # import pudb;pu.db import moment import progressbar import pymysql import requests from peewee import fn from pyquery import PyQuery as jq from retry import retry from termcolor import colored from io import BytesIO from conf import Config from model import (DarkNet_DataSale, DarkNet_IMGS, DarkNet_Notice, DarkNet_Saler, DarkNet_User, DarkNetWebSites) from task import telegram,logreport,telegram_withpic TYPES = 'ChineseTradingNetwork' logging.basicConfig( format="[%(asctime)s] >>> %(levelname)s %(name)s: %(message)s", level=logging.INFO) DefaultLIST = [ ('deepmix3m7iv2vcz.onion', False), ('deepmix2j3cv4bds.onion', False), ('deepmix2z2ayzi46.onion', False), ('deepmix7j72q7kvz.onion', False), ('bmp3qqimv55xdznb.onion', True), ] def FixNums(data, to=9999999, error=-1): """ 专治超量 """ try: nums = int(data) return nums if nums < to else to except Exception as e: return error class DarkNet_ChineseTradingNetwork(object): def __init__(self): self.loger = logging.getLogger(f'DarkNet_{TYPES}') self.info = lambda txt: self.loger.info(colored(txt, 'blue')) self.report = lambda txt: self.loger.info(colored(txt, 'green')) self.warn = lambda txt: self.loger.info(colored(txt, 'yellow')) self.error = lambda txt: self.loger.info(colored(txt, 'red')) self.session = requests.Session() self.session.headers = { "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "Accept-Encoding": "gzip, deflate", "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8", "Cache-Control": "max-age=0", "Connection": "keep-alive", "Referer": "http://bmp3qqimv55xdznb.onion/index.php", "Upgrade-Insecure-Requests": "1", "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36" } self.proxy_url = 'socks5h://127.0.0.1:9150' self.session.proxies = { 'https': self.proxy_url, 'http': self.proxy_url } self.usemaster = True self.master = None self.sid = '' self.justupdate = False self.noticerange = 0 self.rootpath = 'datas' self.screenpath = 'screen_shot' list(map(self.InitPath, [self.rootpath, self.screenpath])) def InitAdd(self, domainLIST): for item in domainLIST: if not DarkNetWebSites.select().where(DarkNetWebSites.domain == item[0]): Model = DarkNetWebSites() Model.domain = item[0] Model.ismaster = item[1] Model.alive = True Model.target = TYPES Model.save() @retry() def FirstFetch(self): targets = DarkNetWebSites.select().where( DarkNetWebSites.ismaster == self.usemaster) if not targets: return target = targets[0] try: self.warn(f'[{target.domain}]Getting PHPSESSID') resp = self.session.get(f'http://{target.domain}') target.ismaster = True target.title = jq(resp.text)('title').text() self.usemaster = True self.master = target self.domain = target.domain user = DarkNet_User.select().where(DarkNet_User.useful == True).order_by(fn.Rand()).limit(1) if not bool(user): self.Reg() else: self.usr = user[0].user self.pwd = user[0].pwd if random.choice([1, 0]): # 佛系注册堆积账号池 self.Reg() return True except KeyboardInterrupt: pass except requests.Timeout: target.alive = False target.ismaster = False self.usemaster = False except Exception as e: raise finally: target.save() @retry(delay=2,tries=20) def Reg(self): self.warn('Start Regging') headers = { "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "Accept-Encoding": "gzip, deflate", "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8", "Cache-Control": "no-cache", "Connection": "keep-alive", "Content-Type": "application/x-www-form-urlencoded", "Origin": f"http://{self.domain}", "Pragma": "no-cache", "Referer": f"http://{self.domain}/ucp.php?mode=register&sid={self.sid}", "Upgrade-Insecure-Requests": "1", "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36" } step1resp = self.session.get( f"http://{self.domain}/ucp.php?mode=register").text step1 = jq(step1resp) self.sid = re.findall('sid=(.*?)"', step1resp)[0] token = step1('input[name="form_token"]').attr('value') creation_time = step1('input[name="creation_time"]').attr('value') self.info(f"Get Token: {token} Create_time: {creation_time}") url = f"http://{self.domain}/ucp.php?mode=register&sid={self.sid}" step2resp = self.session.post(url, data={ "agreed": "===好的,我已明白,请跳转到下一页继续注册====", "change_lang": "", "creation_time": creation_time, "form_token": token }, headers=headers) self.SaveError('step2.html', step2resp) step2 = jq(step2resp.text) token = step2('input[name="form_token"]').attr('value') creation_time = step2('input[name="creation_time"]').attr('value') qa_answer = re.findall('请在右边框中输入: (.*?):</label>',step2resp.text)[0] self.report(f'Got answer: {qa_answer}') qa_confirm_id = step2('#qa_confirm_id').attr('value') self.usr = self.RandomKey() self.pwd = self.RandomKey() self.info(f'set Usr: {self.usr} ,Pwd: {self.pwd}') data = { "username": self.usr, "new_password": self.pwd, "password_confirm": self.pwd, "email": "xxxx@xxxx.xxx", "lang": "zh_cmn_hans", "tz_date": "UTC+08:00+-+Asia/Brunei+-+" + moment.now().format("DD+MM月+YYYY,+HH:mm"), "tz": "Asia/Hong_Kong", "agreed": "true", "change_lang": "0", "qa_answer":qa_answer, "qa_confirm_id":qa_confirm_id, "submit": " 用户名与密码已填好,+点此提交 ", "creation_time": creation_time, "form_token": token } resp = self.session.post(url, data=data, headers=headers) try: assert '感谢注册' in resp.text self.report('Reg success!') DarkNet_User.create(**{ 'user': self.usr, 'pwd': self.pwd }) except AssertionError: self.error(jq(resp.text).text()) self.SaveError('reg.html', resp) @retry(delay=2,tries=20) def Login(self): """ ### 再次尝试 1.因为网络问题重试 ### 重新注册 2.因为账户被封重试 3.因为账户认证错误重试 """ self.warn('Login...') url = f'http://{self.domain}/ucp.php?mode=login' data = { "username": self.usr, "password": self.pwd, "login": "登录", "redirect": f"./index.php&sid={self.sid}" } resp = self.session.post(url, data=data, verify=False, timeout=120) self.sid = ''.join(re.findall("sid=(.*?)'", resp.text)[:1]) self.info(f"SID: {self.sid}") if self.usr not in resp.text: self.error('Auth faild') self.SaveError('Autherror.html', resp) if "已被封禁" in resp.text: DarkNet_User.update({ "useful": False }).where(DarkNet_User.user == self.usr).execute() self.Reg() raise ValueError else: self.report('Auth Success') self.types = {item('.index_list_title').attr('href').split('=')[1].split('&')[0]: item('tr:nth-child(1) > td').text( ).split()[0] for item in jq(resp.text)('.ad_table_b').items()} self.report(self.types) def SaveError(self, filename, resp): fullfilepath = f"{self.rootpath}/{filename}" self.error(f"Html Log Saved to {fullfilepath}") with open(fullfilepath, 'w') as f: f.write(resp.text) @retry() def GetTypeDatas(self, qeaid, name, page=1): url = f"http://{self.domain}/pay/user_area.php?page_y1={page}&q_u_id=0&m_order=&q_ea_id={qeaid}&sid={self.sid}#page_y1" self.warn(url) resp = self.session.get(url) resp.encoding = "utf8" hasres = False try: self.CheckIfNeedLogin(resp) self.SaveError(f'{qeaid}_{name}_{page}.html', resp) self.info(len(resp.text)) jqdata = jq(resp.text) for item in jqdata('table.m_area_a tr').items(): detailPath = item('div.length_400>a').attr('href') if detailPath: detailsURL = urljoin(resp.url, detailPath) self.GetDetails(detailsURL, { 'lines': FixNums(item('td:nth-child(7)').text().replace('天', '')), 'hot': FixNums(item('td:nth-child(8)').text()), 'title': item('td:nth-child(5)').text(), 'area': item('td:nth-child(3)').text() }) hasres = True if page == 1: maxpageStr = ''.join( jqdata('.page_b1:nth-last-child(1)').text().split()) return FixNums(maxpageStr, to=1, error=1) if maxpageStr and not self.justupdate else 1 if hasres: return True except Exception as e: self.error(f"GetTypeDatas: {e}") self.SaveError('GetTypeDatas.html', resp) raise def CheckIfNeedLogin(self, resp, passed=False, needraise=True): if passed or "缓存已经过期" in resp.text: """ 登录超时重新登录 """ if self.FirstFetch(): self.Login() elif "您必须注册并登录才能浏览这个版面" in resp.text: """ 账户遭到封锁重新注册 """ self.Reg() elif "您的回答不正确" in resp.text: time.sleep(20) self.Reg() def NewNet(self): pass # @retry((requests.exceptions.ConnectionError, ValueError)) @retry((requests.exceptions.ConnectionError)) def GetDetails(self, url, muti): resp = self.session.get(url) resp.encoding = "utf8" self.CheckIfNeedLogin(resp) jqdata = jq(resp.text) jqdetail = jqdata('.v_table_1') jqperson = jqdata('.v_table_2') try: uid = FixNums(jqperson('tr:nth-child(5) > td:nth-child(2)').text()) sid = FixNums(jqdetail( 'tr:nth-child(3) > td:nth-child(2)').text()) details = DarkNet_DataSale.select().where((DarkNet_DataSale.sid == sid)) person = DarkNet_Saler.select().where((DarkNet_Saler.uid == uid)) notice = DarkNet_Notice.select().where((DarkNet_Notice.sid == sid)) img = DarkNet_IMGS.select().where((DarkNet_IMGS.sid == sid)) personDatas = { "salenums": FixNums(jqperson('tr:nth-child(3) > td:nth-child(4)').text()), "totalsales": float(jqperson('tr:nth-child(5) > td:nth-child(4)').text()), "totalbuys": float(jqperson('tr:nth-child(7) > td:nth-child(4)').text()) } username = jqperson('tr:nth-child(3) > td:nth-child(2)').text() if not person: personDatas.update({ "uid": uid, "user": username, "regtime": moment.date(jqperson('tr:nth-child(7) > td:nth-child(2)').text()).format('YYYY-MM-DD'), }) person = DarkNet_Saler.create(**personDatas) else: DarkNet_Saler.update(personDatas).where( (DarkNet_Saler.uid == uid)).execute() person = person[0].uid if not notice: notice = DarkNet_Notice.create(**{"sid": sid}) else: notice = notice[0].sid detailImages = None detailContent = ' '.join(jqdata('.postbody .content').text().split()) if not img: urls = [_.attr('src') for _ in jqdata('.postbody img').items()] img = DarkNet_IMGS.create(**{ "sid": sid, "img": urls, "detail": detailContent }) detailImages = self.SavePics(urls, sid) else: img = img[0].sid currentYear = moment.now().year soldNum = FixNums( jqdetail('tr:nth-child(7) > td:nth-child(4)').text(), to=99999) toCurrentYearDateTime = moment.date( f"{currentYear} " + jqdetail('tr:nth-child(3) > td:nth-child(6)').text()) RealUpTimeJQ = jqdata('.author') RealUpTimeJQ.remove('a') RealUpTimeJQ.remove('span') RealUpTime = moment.date( RealUpTimeJQ.text().replace('年', '').replace('月', '').replace('日', '')) RealUpTime = RealUpTime if RealUpTime._date else toCurrentYearDateTime detailsDatas = { "lasttime": moment.date(f"{currentYear} "+jqdetail('tr:nth-child(7) > td:nth-child(6)').text()).format('YYYY-MM-DD HH:mm:ss'), "priceBTC": float(jqdetail('tr:nth-child(3) > td:nth-child(4) > span').text()), "priceUSDT": float(jqdetail('tr:nth-child(5) > td:nth-child(4)').text().split()[0]), "lines": muti['lines'], "uptime": RealUpTime.format('YYYY-MM-DD HH:mm:ss'), "hot": muti['hot'], "types": jqdetail('tr:nth-child(5) > td:nth-child(2)').text(), "status": jqdetail('tr:nth-child(7) > td:nth-child(2)').text(), "oversell": jqdetail('tr:nth-child(9) > td:nth-child(2)').text(), "sold": soldNum } if not details: detailsDatas.update({ "sid": sid, "user": person, "area": muti['area'], "title": muti['title'], "detailurl": url, "img": img, "notice": notice }) details = DarkNet_DataSale.create(**detailsDatas) self.MakeMsg(details,detailContent,detailImages, sid,username) else: self.warn(f'-{RealUpTime}- {muti["title"]}' ) DarkNet_DataSale.update(detailsDatas).where( (DarkNet_DataSale.sid == sid)).execute() except Exception as e: self.error(f"GetDetails {e}") self.SaveError("error_264.html", resp) raise def MakeMsg(self, details, content,imgs ,sid,username): shortmsg = f'[{details.uptime}] {details.title}' self.report(shortmsg) msg = f'{details.uptime}\n🔥{details.title}\n\nAuthor: {username}\nPrice: ${details.priceUSDT}\nSource: {details.detailurl}\n\n\n${content}\n' msg = msg if len(msg)<1000 else msg[:997] + '...' if (details.area in Config.filterArea and moment.date(details.uptime) > moment.now().replace(hours=0, minutes=0, seconds=0).add(days=self.noticerange)) or Config.sendForTest: if not imgs: telegram.delay(msg, sid, Config.darknetchannelID) else: telegram_withpic(imgs[0],msg,sid,Config.darknetchannelID) @staticmethod def RandomKey(length=20): return ''.join((random.choice(random.choice((string.ascii_uppercase, string.ascii_lowercase, ''.join(map(str, range(0, 9)))))) for i in range(1, length))) @staticmethod def InitPath(root): if not os.path.exists(root): os.makedirs(root) def GetPicBase64(self, link): return link if 'http' not in link else bytes.decode(b64encode(self.GetPic(link))) @retry() def GetPic(self, link): return self.session.get(link).content def SavePics(self, urls, sid): imageBox = [] for index, url in enumerate(urls): url = url if 'http' in url else urljoin(f'http://{self.domain}',url) self.info(f'---fetch PIC[{index}]:{url}') with open(f'{self.screenpath}/{sid}_{index}.png', 'wb') as imgfile: singelPIC = self.GetPic(url) imgfile.write(singelPIC) imageBox.append(BytesIO(singelPIC)) return imageBox def Run(self): self.InitAdd(DefaultLIST) while True: self.CheckIfNeedLogin(None, True, False) for qeaid, name in self.types.items(): maxpage = self.GetTypeDatas(qeaid, name) self.info(f"MaxPage: {maxpage}") for page in range(1, maxpage): if not self.GetTypeDatas(qeaid, name, page): break if __name__ == "__main__": while True: try: DarkNet_ChineseTradingNetwork().Run() except KeyboardInterrupt: break except Exception as e: logreport.delay(str(e)) time.sleep(10*60)
[ "aoii103@126.com" ]
aoii103@126.com
ef852b1ea95ab6b607b7111d6e352702e95e413f
28def9c6ad5053dcd8d9ea81ef04c488bf413bb4
/untwisted/exceptions.py
8e555e4c948e52ef1c527a2d6cf9854042e31867
[ "MIT" ]
permissive
kgisl/untwisted
2b6ebd5a3a88880d785c34186444831248119935
b1277d4d5ad0982d4bc307ed6cdbd7923b0a3305
refs/heads/master
2021-01-01T06:01:33.514588
2017-07-14T22:31:31
2017-07-14T22:31:31
null
0
0
null
null
null
null
UTF-8
Python
false
false
927
py
class Stop(Exception): """ This exception is used to avoid remaining handles being processed for a given event. from untwisted.dispatcher import Dispatcher, Stop def handle0(dispatcher): raise Stop def handle1(dispatcher): print 'it will not be processed!' dispatcher = Dispatcher() dispatcher.add_map('alpha', handle0) dispatcher.add_map('alpha', handle1) dispatcher.drive('alpha') """ pass class Erase(Exception): """ When this exception is thrown from a handle it avoids such a handle being processed again upon its event. from untwisted.dispatcher import Dispatcher, Erase def handle(dispatcher): print 'It will be called just once!' raise Erase dispatcher = Dispatcher() dispatcher.add_map('alpha', handle) dispatcher.drive('alpha') dispatcher.drive('alpha') """ pass
[ "ioliveira.id.uff.br" ]
ioliveira.id.uff.br
ca264bba01fbb8049800dd66a1b42075294bab3f
e23a4f57ce5474d468258e5e63b9e23fb6011188
/140_gui/pyqt_pyside/examples/PyQt_PySide_book/003_Placing several components in the box/003_Alignment of form components/074_WrapAllRows.py
a93093d67a978e4b8b6ed215b3a1f0ed61d86509
[]
no_license
syurskyi/Python_Topics
52851ecce000cb751a3b986408efe32f0b4c0835
be331826b490b73f0a176e6abed86ef68ff2dd2b
refs/heads/master
2023-06-08T19:29:16.214395
2023-05-29T17:09:11
2023-05-29T17:09:11
220,583,118
3
2
null
2023-02-16T03:08:10
2019-11-09T02:58:47
Python
UTF-8
Python
false
false
698
py
# -*- coding: utf-8 -*- from PyQt5 import QtWidgets import sys app = QtWidgets.QApplication(sys.argv) window = QtWidgets.QWidget() window.setWindowTitle("WrapAllRows") window.resize(300, 150) lineEdit = QtWidgets.QLineEdit() textEdit = QtWidgets.QTextEdit() button1 = QtWidgets.QPushButton("О&тправить") button2 = QtWidgets.QPushButton("О&чистить") hbox = QtWidgets.QHBoxLayout() hbox.addWidget(button1) hbox.addWidget(button2) form = QtWidgets.QFormLayout() form.setRowWrapPolicy(QtWidgets.QFormLayout.WrapAllRows) form.addRow("&Название:", lineEdit) form.addRow("&Описание:", textEdit) form.addRow(hbox) window.setLayout(form) window.show() sys.exit(app.exec_())
[ "sergejyurskyj@yahoo.com" ]
sergejyurskyj@yahoo.com
a9ae94d786b2e6b0efbde9f52d2277e59f1e209c
53fab060fa262e5d5026e0807d93c75fb81e67b9
/backup/user_143/ch58_2020_04_27_13_12_10_083214.py
2b966cf1c6ee61808ba0af8eb5675ef066d87bbe
[]
no_license
gabriellaec/desoft-analise-exercicios
b77c6999424c5ce7e44086a12589a0ad43d6adca
01940ab0897aa6005764fc220b900e4d6161d36b
refs/heads/main
2023-01-31T17:19:42.050628
2020-12-16T05:21:31
2020-12-16T05:21:31
306,735,108
0
0
null
null
null
null
UTF-8
Python
false
false
101
py
def conta_a(p): a=0 for i in p: if i=='a': a+=1 return a
[ "you@example.com" ]
you@example.com
39876d9191216f5d127a8b23705a2a7e08864d52
a055bcba66f9ca8acd87042d3a594296f7ccb610
/images/views.py
a9d154aa2c706fc83ee84bd990ef1c6696ebf6c9
[]
no_license
shineforever/bookmarks
7c3a841159435d85d72003b887759aa063c52253
100fceff7f5ff27eb048008dbff9ddbcd6364f97
refs/heads/master
2021-01-20T20:44:44.891324
2016-07-27T08:31:54
2016-07-27T08:31:54
62,046,089
0
0
null
null
null
null
UTF-8
Python
false
false
794
py
from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from django.contrib import messages from .forms import ImageCreateForm # Create your views here. @login_required def image_create(request): if request.method == 'POST': form = ImageCreateForm(data=request.POST) if form.is_valid(): cd = form.cleaned_data new_item = form.save(commit=False) messages.success(request,'Image added successfully') return redirect(new_item.get_absolute_url()) else: #GET form = ImageCreateForm(data=request.GET) return render(request, 'images/image/create.html', {'section': 'images', 'form': form})
[ "root@localhost.localdomain" ]
root@localhost.localdomain
842ac23abab226df3247cd683085b0e3c9a8dcb4
41fd80f9ccc72a17c2db16b7019312a87d3181e8
/zhang_local/pdep/network2859_1.py
52605c7a53131593eb37a575d3ee5d83b2061bf0
[]
no_license
aberdeendinius/n-heptane
1510e6704d87283043357aec36317fdb4a2a0c34
1806622607f74495477ef3fd772908d94cff04d9
refs/heads/master
2020-05-26T02:06:49.084015
2019-07-01T15:12:44
2019-07-01T15:12:44
188,069,618
0
0
null
null
null
null
UTF-8
Python
false
false
55,507
py
species( label = '[CH2][C]([CH2])OC([CH2])O(10182)', structure = SMILES('[CH2][C]([CH2])OC([CH2])O'), E0 = (305.378,'kJ/mol'), modes = [ HarmonicOscillator(frequencies=([3000,3020,3040,3060,3080,3100,415,440,465,780,815,850,1435,1455,1475,900,1000,1100,360,370,350,3615,1277.5,1000,1380,1390,370,380,2900,435,200,800,1600],'cm^-1')), HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False), ], spinMultiplicity = 5, opticalIsomers = 1, molecularWeight = (100.116,'amu'), energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85), thermo = NASA(polynomials=[NASAPolynomial(coeffs=[-0.631048,0.117465,-0.000215862,1.98152e-07,-6.80516e-11,36880.4,32.0572], Tmin=(100,'K'), Tmax=(887.361,'K')), NASAPolynomial(coeffs=[9.39138,0.0361813,-1.74256e-05,3.21551e-09,-2.12709e-13,36523.2,-7.08786], Tmin=(887.361,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(305.378,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(332.579,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-CsCs) + longDistanceInteraction_noncyclic(OsCs-ST) + group(O2s-CsH) + group(Cs-CsCsOsH) + group(Cs-CsOsOsH) + group(Cs-CsHHH) + group(Cs-CsHHH) + group(Cs-CsHHH) + radical(CJC(C)OC) + radical(CJC(C)OC) + radical(CJCO) + radical(C2CsJOCs)"""), ) species( label = 'C=CO(576)', structure = SMILES('C=CO'), E0 = (-166.643,'kJ/mol'), modes = [ HarmonicOscillator(frequencies=([2950,3100,1380,975,1025,1650,3615,1277.5,1000,3010,987.5,1337.5,450,1655],'cm^-1')), HinderedRotor(inertia=(1.24798,'amu*angstrom^2'), symmetry=1, barrier=(28.6936,'kJ/mol'), semiclassical=False), ], spinMultiplicity = 1, opticalIsomers = 1, molecularWeight = (44.0526,'amu'), collisionModel = TransportData(shapeIndex=2, epsilon=(3625.11,'J/mol'), sigma=(3.97,'angstroms'), dipoleMoment=(0,'De'), polarizability=(0,'angstroms^3'), rotrelaxcollnum=2.0, comment="""NOx2018"""), energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85), thermo = NASA(polynomials=[NASAPolynomial(coeffs=[2.92544,0.00836062,5.0344e-05,-8.45232e-08,3.72335e-11,-19989.5,9.0776], Tmin=(100,'K'), Tmax=(898.452,'K')), NASAPolynomial(coeffs=[15.1116,-0.00538397,5.65903e-06,-1.18193e-09,7.91212e-14,-23814.2,-57.5076], Tmin=(898.452,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(-166.643,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(153.818,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-(Cds-Cd)H) + group(Cds-CdsOsH) + group(Cds-CdsHH)"""), ) species( label = '[CH2]C(=C)[O](4273)', structure = SMILES('[CH2]C(=C)[O]'), E0 = (88.2866,'kJ/mol'), modes = [ HarmonicOscillator(frequencies=([2950,3100,1380,975,1025,1650,350,440,435,1725,3000,3100,440,815,1455,1000,510.595],'cm^-1')), HinderedRotor(inertia=(0.0480287,'amu*angstrom^2'), symmetry=1, barrier=(8.88265,'kJ/mol'), semiclassical=False), ], spinMultiplicity = 3, opticalIsomers = 1, molecularWeight = (56.0633,'amu'), collisionModel = TransportData(shapeIndex=2, epsilon=(3365.98,'J/mol'), sigma=(5.64088,'angstroms'), dipoleMoment=(0,'C*m'), polarizability=(0,'angstroms^3'), rotrelaxcollnum=0, comment="""Epsilon & sigma estimated with Tc=525.76 K, Pc=42.55 bar (from Joback method)"""), energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85), thermo = NASA(polynomials=[NASAPolynomial(coeffs=[2.6374,0.0235792,5.32605e-07,-2.30624e-08,1.26355e-11,10673.5,14.3058], Tmin=(100,'K'), Tmax=(894.06,'K')), NASAPolynomial(coeffs=[10.3562,0.00670937,-7.99446e-07,2.86693e-11,-3.46262e-16,8587.33,-26.0166], Tmin=(894.06,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(88.2866,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(178.761,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-(Cds-Cd)H) + group(Cs-(Cds-Cds)HHH) + group(Cds-CdsCsOs) + group(Cds-CdsHH) + radical(C=C(C)OJ) + radical(C=C(O)CJ)"""), ) species( label = 'H(8)', structure = SMILES('[H]'), E0 = (211.805,'kJ/mol'), spinMultiplicity = 1, opticalIsomers = 1, molecularWeight = (1.00794,'amu'), collisionModel = TransportData(shapeIndex=0, epsilon=(1205.6,'J/mol'), sigma=(2.05,'angstroms'), dipoleMoment=(0,'C*m'), polarizability=(0,'angstroms^3'), rotrelaxcollnum=0.0, comment="""GRI-Mech"""), energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85), thermo = NASA(polynomials=[NASAPolynomial(coeffs=[2.5,9.24385e-15,-1.3678e-17,6.66185e-21,-1.00107e-24,25474.2,-0.444973], Tmin=(100,'K'), Tmax=(3459.6,'K')), NASAPolynomial(coeffs=[2.5,9.20456e-12,-3.58608e-15,6.15199e-19,-3.92042e-23,25474.2,-0.444973], Tmin=(3459.6,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(211.805,'kJ/mol'), Cp0=(20.7862,'J/(mol*K)'), CpInf=(20.7862,'J/(mol*K)'), label="""H""", comment="""Thermo library: primaryThermoLibrary"""), ) species( label = '[CH2][C](O)OC([CH2])=C(10629)', structure = SMILES('[CH2][C](O)OC([CH2])=C'), E0 = (148.223,'kJ/mol'), modes = [ HarmonicOscillator(frequencies=([3000,3033.33,3066.67,3100,415,465,780,850,1435,1475,900,1100,360,370,350,2950,3100,1380,975,1025,1650,3615,1277.5,1000,350,440,435,1725,200,800,1600],'cm^-1')), HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False), ], spinMultiplicity = 4, opticalIsomers = 1, molecularWeight = (99.1079,'amu'), energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85), thermo = NASA(polynomials=[NASAPolynomial(coeffs=[-0.175105,0.0809418,-8.79015e-05,4.65748e-08,-9.4455e-12,17986.7,30.8456], Tmin=(100,'K'), Tmax=(1258.71,'K')), NASAPolynomial(coeffs=[20.7759,0.0122364,-3.49197e-06,5.2595e-10,-3.29306e-14,12880.8,-74.3825], Tmin=(1258.71,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(148.223,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(311.793,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-Cs(Cds-Cd)) + group(O2s-CsH) + group(Cs-CsOsOsH) + group(Cs-CsHHH) + group(Cs-(Cds-Cds)HHH) + group(Cds-CdsCsOs) + group(Cds-CdsHH) + radical(CJCO) + radical(Cs_P) + radical(C=C(O)CJ)"""), ) species( label = '[CH2][CH]O(578)', structure = SMILES('[CH2][CH]O'), E0 = (135.316,'kJ/mol'), modes = [ HarmonicOscillator(frequencies=([3025,407.5,1350,352.5,3615,1277.5,1000,3000,3100,440,815,1455,1000],'cm^-1')), HinderedRotor(inertia=(0.0943891,'amu*angstrom^2'), symmetry=1, barrier=(7.36374,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.0943883,'amu*angstrom^2'), symmetry=1, barrier=(7.36374,'kJ/mol'), semiclassical=False), ], spinMultiplicity = 3, opticalIsomers = 1, molecularWeight = (44.0526,'amu'), energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85), thermo = NASA(polynomials=[NASAPolynomial(coeffs=[2.67796,0.0299043,-3.92791e-05,2.86662e-08,-8.27893e-12,16321.6,12.7466], Tmin=(100,'K'), Tmax=(918.072,'K')), NASAPolynomial(coeffs=[6.82026,0.00999271,-3.7014e-06,6.19844e-10,-3.95112e-14,15639.5,-6.45576], Tmin=(918.072,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(135.316,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(149.66,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-CsH) + group(Cs-CsOsHH) + group(Cs-CsHHH) + radical(CCsJOH) + radical(CJCO)"""), ) species( label = 'OH(D)(132)', structure = SMILES('[OH]'), E0 = (28.3945,'kJ/mol'), modes = [ HarmonicOscillator(frequencies=([3668.68],'cm^-1')), ], spinMultiplicity = 2, opticalIsomers = 1, molecularWeight = (17.0073,'amu'), collisionModel = TransportData(shapeIndex=1, epsilon=(665.16,'J/mol'), sigma=(2.75,'angstroms'), dipoleMoment=(0,'C*m'), polarizability=(0,'angstroms^3'), rotrelaxcollnum=0.0, comment="""GRI-Mech"""), energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85), thermo = NASA(polynomials=[NASAPolynomial(coeffs=[3.51457,2.92814e-05,-5.32177e-07,1.01951e-09,-3.85951e-13,3414.25,2.10435], Tmin=(100,'K'), Tmax=(1145.75,'K')), NASAPolynomial(coeffs=[3.07194,0.000604011,-1.39759e-08,-2.13452e-11,2.4807e-15,3579.39,4.57799], Tmin=(1145.75,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(28.3945,'kJ/mol'), Cp0=(29.1007,'J/(mol*K)'), CpInf=(37.4151,'J/(mol*K)'), label="""OH(D)""", comment="""Thermo library: primaryThermoLibrary"""), ) species( label = '[CH2][CH]OC([CH2])=C(6355)', structure = SMILES('[CH2][CH]OC([CH2])=C'), E0 = (337.135,'kJ/mol'), modes = [ HarmonicOscillator(frequencies=([3025,407.5,1350,352.5,2950,3100,1380,975,1025,1650,350,440,435,1725,3000,3033.33,3066.67,3100,415,465,780,850,1435,1475,900,1100,409.162,409.281,409.327],'cm^-1')), HinderedRotor(inertia=(0.135088,'amu*angstrom^2'), symmetry=1, barrier=(16.0798,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.135355,'amu*angstrom^2'), symmetry=1, barrier=(16.0799,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.13554,'amu*angstrom^2'), symmetry=1, barrier=(16.0797,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.135337,'amu*angstrom^2'), symmetry=1, barrier=(16.0821,'kJ/mol'), semiclassical=False), ], spinMultiplicity = 4, opticalIsomers = 1, molecularWeight = (83.1085,'amu'), energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85), thermo = NASA(polynomials=[NASAPolynomial(coeffs=[-0.0881854,0.0768561,-8.49605e-05,4.51228e-08,-9.02004e-12,40706.3,26.1587], Tmin=(100,'K'), Tmax=(1359.75,'K')), NASAPolynomial(coeffs=[20.7136,0.00828131,-1.16948e-06,4.87585e-11,1.21001e-15,35731.7,-78.0811], Tmin=(1359.75,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(337.135,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(291.007,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-Cs(Cds-Cd)) + group(Cs-CsOsHH) + group(Cs-CsHHH) + group(Cs-(Cds-Cds)HHH) + group(Cds-CdsCsOs) + group(Cds-CdsHH) + radical(CJCO) + radical(C=C(O)CJ) + radical(CCsJOC(O))"""), ) species( label = '[CH2][C]([CH2])O[C](C)O(10540)', structure = SMILES('[CH2][C]([CH2])O[C](C)O'), E0 = (299.035,'kJ/mol'), spinMultiplicity = 1, opticalIsomers = 1, molecularWeight = (100.116,'amu'), energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85), thermo = NASA(polynomials=[NASAPolynomial(coeffs=[-0.432911,0.112911,-0.000206239,1.90876e-07,-6.6208e-11,36110.6,31.4001], Tmin=(100,'K'), Tmax=(882.945,'K')), NASAPolynomial(coeffs=[8.3185,0.0377577,-1.82436e-05,3.38518e-09,-2.25264e-13,35949.2,-1.89333], Tmin=(882.945,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(299.035,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(332.579,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-CsCs) + longDistanceInteraction_noncyclic(OsCs-ST) + group(O2s-CsH) + group(Cs-CsCsOsH) + group(Cs-CsOsOsH) + group(Cs-CsHHH) + group(Cs-CsHHH) + group(Cs-CsHHH) + radical(CJC(C)OC) + radical(CJC(C)OC) + radical(Cs_P) + radical(C2CsJOCs)"""), ) species( label = '[CH2][C](O)OC([CH2])[CH2](2365)', structure = SMILES('[CH2][C](O)OC([CH2])[CH2]'), E0 = (329.921,'kJ/mol'), modes = [ HarmonicOscillator(frequencies=([3000,3020,3040,3060,3080,3100,415,440,465,780,815,850,1435,1455,1475,900,1000,1100,360,370,350,3615,1277.5,1000,1380,1390,370,380,2900,435,200,800,1600],'cm^-1')), HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False), ], spinMultiplicity = 5, opticalIsomers = 1, molecularWeight = (100.116,'amu'), energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85), thermo = NASA(polynomials=[NASAPolynomial(coeffs=[-0.481098,0.10731,-0.000174912,1.47902e-07,-4.83859e-11,39833.3,32.2618], Tmin=(100,'K'), Tmax=(863.342,'K')), NASAPolynomial(coeffs=[12.6408,0.0306917,-1.43009e-05,2.65099e-09,-1.78055e-13,38157.2,-25.7005], Tmin=(863.342,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(329.921,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(332.579,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-CsCs) + longDistanceInteraction_noncyclic(OsCs-ST) + group(O2s-CsH) + group(Cs-CsCsOsH) + group(Cs-CsOsOsH) + group(Cs-CsHHH) + group(Cs-CsHHH) + group(Cs-CsHHH) + radical(CJC(C)OC) + radical(CJCO) + radical(Cs_P) + radical(CJC(C)OC)"""), ) species( label = '[CH2][C]([CH2])OC(C)[O](10156)', structure = SMILES('[CH2][C]([CH2])OC(C)[O]'), E0 = (319.494,'kJ/mol'), modes = [ HarmonicOscillator(frequencies=([3000,3033.33,3066.67,3100,415,465,780,850,1435,1475,900,1100,2750,2800,2850,1350,1500,750,1050,1375,1000,1380,1390,370,380,2900,435,360,370,350,200,800,1200,1600],'cm^-1')), HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False), ], spinMultiplicity = 5, opticalIsomers = 1, molecularWeight = (100.116,'amu'), collisionModel = TransportData(shapeIndex=2, epsilon=(3820.91,'J/mol'), sigma=(6.71547,'angstroms'), dipoleMoment=(0,'C*m'), polarizability=(0,'angstroms^3'), rotrelaxcollnum=0, comment="""Epsilon & sigma estimated with Tc=596.82 K, Pc=28.63 bar (from Joback method)"""), energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85), thermo = NASA(polynomials=[NASAPolynomial(coeffs=[-0.117388,0.109555,-0.000208596,2.04527e-07,-7.43138e-11,38556.4,30.4394], Tmin=(100,'K'), Tmax=(874.844,'K')), NASAPolynomial(coeffs=[3.82012,0.0464929,-2.32113e-05,4.3827e-09,-2.9531e-13,39591.8,21.8247], Tmin=(874.844,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(319.494,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(336.736,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-CsCs) + longDistanceInteraction_noncyclic(OsCs-ST) + group(O2s-CsH) + group(Cs-CsCsOsH) + group(Cs-CsOsOsH) + group(Cs-CsHHH) + group(Cs-CsHHH) + group(Cs-CsHHH) + radical(CCOJ) + radical(C2CsJOCs) + radical(CJC(C)OC) + radical(CJC(C)OC)"""), ) species( label = '[CH2][C](C)O[C]([CH2])O(2362)', structure = SMILES('[CH2][C](C)O[C]([CH2])O'), E0 = (300.114,'kJ/mol'), spinMultiplicity = 1, opticalIsomers = 1, molecularWeight = (100.116,'amu'), energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85), thermo = NASA(polynomials=[NASAPolynomial(coeffs=[-0.216275,0.105136,-0.000181812,1.64481e-07,-5.66789e-11,36235.4,32.1972], Tmin=(100,'K'), Tmax=(870.876,'K')), NASAPolynomial(coeffs=[8.82885,0.0366866,-1.75751e-05,3.28144e-09,-2.2055e-13,35680.2,-4.33222], Tmin=(870.876,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(300.114,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(332.579,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-CsCs) + longDistanceInteraction_noncyclic(OsCs-ST) + group(O2s-CsH) + group(Cs-CsCsOsH) + group(Cs-CsOsOsH) + group(Cs-CsHHH) + group(Cs-CsHHH) + group(Cs-CsHHH) + radical(CJCO) + radical(Cs_P) + radical(CJC(C)OC) + radical(C2CsJOCs)"""), ) species( label = '[CH2]C([CH2])OC([CH2])[O](2364)', structure = SMILES('[CH2]C([CH2])OC([CH2])[O]'), E0 = (350.379,'kJ/mol'), modes = [ HarmonicOscillator(frequencies=([1380,1383.33,1386.67,1390,370,373.333,376.667,380,2800,3000,430,440,3000,3020,3040,3060,3080,3100,415,440,465,780,815,850,1435,1455,1475,900,1000,1100,200,800,1200,1600],'cm^-1')), HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False), ], spinMultiplicity = 5, opticalIsomers = 1, molecularWeight = (100.116,'amu'), energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85), thermo = NASA(polynomials=[NASAPolynomial(coeffs=[-0.167294,0.103981,-0.00017739,1.61771e-07,-5.66203e-11,42279.1,31.307], Tmin=(100,'K'), Tmax=(857.019,'K')), NASAPolynomial(coeffs=[8.13207,0.0394446,-1.92787e-05,3.65091e-09,-2.48299e-13,41804.1,-1.92426], Tmin=(857.019,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(350.379,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(336.736,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-CsCs) + longDistanceInteraction_noncyclic(OsCs-ST) + group(O2s-CsH) + group(Cs-CsCsOsH) + group(Cs-CsOsOsH) + group(Cs-CsHHH) + group(Cs-CsHHH) + group(Cs-CsHHH) + radical(CJCO) + radical(CJC(C)OC) + radical(CJC(C)OC) + radical(CCOJ)"""), ) species( label = '[CH2][C](C)OC([CH2])[O](2361)', structure = SMILES('[CH2][C](C)OC([CH2])[O]'), E0 = (320.573,'kJ/mol'), modes = [ HarmonicOscillator(frequencies=([3000,3033.33,3066.67,3100,415,465,780,850,1435,1475,900,1100,2750,2800,2850,1350,1500,750,1050,1375,1000,1380,1390,370,380,2900,435,360,370,350,200,800,1200,1600],'cm^-1')), HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False), ], spinMultiplicity = 5, opticalIsomers = 1, molecularWeight = (100.116,'amu'), energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85), thermo = NASA(polynomials=[NASAPolynomial(coeffs=[0.0975475,0.101805,-0.000184278,1.7832e-07,-6.48916e-11,38681.2,31.2424], Tmin=(100,'K'), Tmax=(864.238,'K')), NASAPolynomial(coeffs=[4.32432,0.0454322,-2.25487e-05,4.28034e-09,-2.9071e-13,39325.3,19.4204], Tmin=(864.238,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(320.573,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(336.736,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-CsCs) + longDistanceInteraction_noncyclic(OsCs-ST) + group(O2s-CsH) + group(Cs-CsCsOsH) + group(Cs-CsOsOsH) + group(Cs-CsHHH) + group(Cs-CsHHH) + group(Cs-CsHHH) + radical(CCOJ) + radical(CJC(C)OC) + radical(C2CsJOCs) + radical(CJCO)"""), ) species( label = '[CH2][C]([CH2])[O](10271)', structure = SMILES('[CH2][C]([CH2])[O]'), E0 = (537.173,'kJ/mol'), modes = [ HarmonicOscillator(frequencies=([360,370,350,3000,3033.33,3066.67,3100,415,465,780,850,1435,1475,900,1100,278.503],'cm^-1')), HinderedRotor(inertia=(0.00215299,'amu*angstrom^2'), symmetry=1, barrier=(0.119627,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.0939305,'amu*angstrom^2'), symmetry=1, barrier=(5.13965,'kJ/mol'), semiclassical=False), ], spinMultiplicity = 5, opticalIsomers = 1, molecularWeight = (56.0633,'amu'), energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85), thermo = NASA(polynomials=[NASAPolynomial(coeffs=[2.0694,0.0447257,-6.5608e-05,5.12452e-08,-1.57124e-11,64674.3,16.4544], Tmin=(100,'K'), Tmax=(870.707,'K')), NASAPolynomial(coeffs=[8.27065,0.0130302,-5.47972e-06,9.76923e-10,-6.45299e-14,63716,-11.9064], Tmin=(870.707,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(537.173,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(174.604,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-CsH) + group(Cs-CsCsOsH) + group(Cs-CsHHH) + group(Cs-CsHHH) + radical(C2CsJOH) + radical(CJCO) + radical(CC(C)OJ) + radical(CJCO)"""), ) species( label = '[CH2][CH]O[C]([CH2])[CH2](6357)', structure = SMILES('[CH2][CH]O[C]([CH2])[CH2]'), E0 = (686.065,'kJ/mol'), modes = [ HarmonicOscillator(frequencies=([360,370,350,3000,3020,3040,3060,3080,3100,415,440,465,780,815,850,1435,1455,1475,900,1000,1100,3025,407.5,1350,352.5,200,800,1600],'cm^-1')), HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False), ], spinMultiplicity = 6, opticalIsomers = 1, molecularWeight = (83.1085,'amu'), energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85), thermo = NASA(polynomials=[NASAPolynomial(coeffs=[-0.311103,0.110171,-0.000209975,1.92186e-07,-6.49065e-11,82655.4,27.1958], Tmin=(100,'K'), Tmax=(908.543,'K')), NASAPolynomial(coeffs=[9.67625,0.028629,-1.33198e-05,2.36991e-09,-1.51156e-13,82391.2,-11.4958], Tmin=(908.543,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(686.065,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(286.849,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-CsCs) + longDistanceInteraction_noncyclic(OsCs-ST) + group(Cs-CsCsOsH) + group(Cs-CsOsHH) + group(Cs-CsHHH) + group(Cs-CsHHH) + group(Cs-CsHHH) + radical(C2CsJOCs) + radical(CJCO) + radical(CCsJOCs) + radical(CJC(C)OC) + radical(CJC(C)OC)"""), ) species( label = '[CH2][C]([CH2])OC([CH2])[O](6725)', structure = SMILES('[CH2][C]([CH2])OC([CH2])[O]'), E0 = (531.083,'kJ/mol'), modes = [ HarmonicOscillator(frequencies=([360,370,350,1380,1390,370,380,2900,435,3000,3020,3040,3060,3080,3100,415,440,465,780,815,850,1435,1455,1475,900,1000,1100,200,800,1200,1600],'cm^-1')), HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False), ], spinMultiplicity = 6, opticalIsomers = 1, molecularWeight = (99.1079,'amu'), energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85), thermo = NASA(polynomials=[NASAPolynomial(coeffs=[-0.281517,0.114878,-0.000228766,2.24125e-07,-8.05882e-11,64009,31.6625], Tmin=(100,'K'), Tmax=(883.223,'K')), NASAPolynomial(coeffs=[4.71313,0.042576,-2.15976e-05,4.06387e-09,-2.71595e-13,65064.6,19.1565], Tmin=(883.223,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(531.083,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(311.793,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-CsCs) + longDistanceInteraction_noncyclic(OsCs-ST) + group(O2s-CsH) + group(Cs-CsCsOsH) + group(Cs-CsOsOsH) + group(Cs-CsHHH) + group(Cs-CsHHH) + group(Cs-CsHHH) + radical(CCOJ) + radical(CJC(C)OC) + radical(C2CsJOCs) + radical(CJCO) + radical(CJC(C)OC)"""), ) species( label = '[CH2][C]([CH2])O[C]([CH2])O(6726)', structure = SMILES('[CH2][C]([CH2])O[C]([CH2])O'), E0 = (510.624,'kJ/mol'), modes = [ HarmonicOscillator(frequencies=([360,363.333,366.667,370,300,400,3615,1277.5,1000,3000,3020,3040,3060,3080,3100,415,440,465,780,815,850,1435,1455,1475,900,1000,1100,200,800,1600],'cm^-1')), HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False), ], spinMultiplicity = 6, opticalIsomers = 1, molecularWeight = (99.1079,'amu'), energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85), thermo = NASA(polynomials=[NASAPolynomial(coeffs=[-0.59781,0.118246,-0.000226475,2.10599e-07,-7.25585e-11,61563.3,32.6258], Tmin=(100,'K'), Tmax=(892.559,'K')), NASAPolynomial(coeffs=[9.20222,0.0338565,-1.6639e-05,3.0685e-09,-2.01727e-13,61425.9,-4.50915], Tmin=(892.559,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(510.624,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(307.635,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-CsCs) + longDistanceInteraction_noncyclic(OsCs-ST) + group(O2s-CsH) + group(Cs-CsCsOsH) + group(Cs-CsOsOsH) + group(Cs-CsHHH) + group(Cs-CsHHH) + group(Cs-CsHHH) + radical(C2CsJOCs) + radical(Cs_P) + radical(CJC(C)OC) + radical(CJC(C)OC) + radical(CJCO)"""), ) species( label = '[CH2]C([CH2])OC(=C)O(10630)', structure = SMILES('[CH2]C([CH2])OC(=C)O'), E0 = (41.9533,'kJ/mol'), spinMultiplicity = 1, opticalIsomers = 1, molecularWeight = (100.116,'amu'), energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85), thermo = NASA(polynomials=[NASAPolynomial(coeffs=[-0.818156,0.103006,-0.000135908,8.76844e-08,-2.16792e-11,5221.93,26.4745], Tmin=(100,'K'), Tmax=(1004.4,'K')), NASAPolynomial(coeffs=[21.1933,0.0153443,-4.98752e-06,7.84711e-10,-4.89397e-14,800.382,-79.814], Tmin=(1004.4,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(41.9533,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(336.736,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-Cs(Cds-Cd)) + group(O2s-(Cds-Cd)H) + group(Cs-CsCsOsH) + group(Cs-CsHHH) + group(Cs-CsHHH) + group(Cds-CdsCsCs) + group(Cds-CdsHH) + radical(CJC(C)OC) + radical(CJC(C)OC)"""), ) species( label = '[CH2]C1([CH2])CC(O)O1(10183)', structure = SMILES('[CH2]C1([CH2])CC(O)O1'), E0 = (46.2826,'kJ/mol'), spinMultiplicity = 1, opticalIsomers = 1, molecularWeight = (100.116,'amu'), energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85), thermo = NASA(polynomials=[NASAPolynomial(coeffs=[-0.185931,0.0827112,-9.28263e-05,5.42599e-08,-1.20095e-11,5725.34,26.3654], Tmin=(100,'K'), Tmax=(1272.92,'K')), NASAPolynomial(coeffs=[16.8053,0.0178867,-2.9667e-06,1.42727e-10,4.64307e-15,2325.78,-56.0701], Tmin=(1272.92,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(46.2826,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(345.051,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-CsCs) + group(O2s-CsH) + group(Cs-CsCsCsOs) + group(Cs-CsCsHH) + group(Cs-CsOsOsH) + group(Cs-CsHHH) + group(Cs-CsHHH) + ring(Oxetane) + radical(CJC(C)OC) + radical(CJC(C)OC)"""), ) species( label = '[CH2]C([O])O(670)', structure = SMILES('[CH2]C([O])O'), E0 = (-19.5078,'kJ/mol'), modes = [ HarmonicOscillator(frequencies=([3000,3100,440,815,1455,1000,3615,1277.5,1000,1380,1390,370,380,2900,435,1935.17],'cm^-1')), HinderedRotor(inertia=(0.200225,'amu*angstrom^2'), symmetry=1, barrier=(4.60358,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.200503,'amu*angstrom^2'), symmetry=1, barrier=(4.60997,'kJ/mol'), semiclassical=False), ], spinMultiplicity = 3, opticalIsomers = 1, molecularWeight = (60.052,'amu'), energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85), thermo = NASA(polynomials=[NASAPolynomial(coeffs=[2.66061,0.0330653,-4.66659e-05,4.29179e-08,-1.60973e-11,-2301.52,17.2788], Tmin=(100,'K'), Tmax=(804.622,'K')), NASAPolynomial(coeffs=[3.98157,0.0198211,-9.52741e-06,1.83298e-09,-1.27458e-13,-2297.94,12.5363], Tmin=(804.622,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(-19.5078,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(174.604,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-CsH) + group(O2s-CsH) + group(Cs-CsOsOsH) + group(Cs-CsHHH) + radical(CJCO) + radical(CCOJ)"""), ) species( label = '[CH2][C][CH2](10272)', structure = SMILES('[CH2][C][CH2]'), E0 = (738.184,'kJ/mol'), modes = [ HarmonicOscillator(frequencies=([3000,3033.33,3066.67,3100,415,465,780,850,1435,1475,900,1100,349.736],'cm^-1')), HinderedRotor(inertia=(0.00138263,'amu*angstrom^2'), symmetry=1, barrier=(0.119627,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.0013768,'amu*angstrom^2'), symmetry=1, barrier=(0.119627,'kJ/mol'), semiclassical=False), ], spinMultiplicity = 5, opticalIsomers = 1, molecularWeight = (40.0639,'amu'), energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85), thermo = NASA(polynomials=[NASAPolynomial(coeffs=[3.07912,0.0169806,-2.30739e-06,-7.22553e-09,3.53372e-12,88819,13.4505], Tmin=(100,'K'), Tmax=(1024.31,'K')), NASAPolynomial(coeffs=[6.32415,0.0113321,-4.3212e-06,7.79353e-10,-5.38459e-14,87785.8,-4.0815], Tmin=(1024.31,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(738.184,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(149.66,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(Cs-CsCsHH) + group(Cs-CsHHH) + group(Cs-CsHHH) + radical(RCCJ) + radical(RCCJ) + radical(CCJ2_triplet)"""), ) species( label = 'CH2(T)(28)', structure = SMILES('[CH2]'), E0 = (381.37,'kJ/mol'), modes = [ HarmonicOscillator(frequencies=([1066.91,2790.99,3622.37],'cm^-1')), ], spinMultiplicity = 3, opticalIsomers = 1, molecularWeight = (14.0266,'amu'), collisionModel = TransportData(shapeIndex=2, epsilon=(1197.29,'J/mol'), sigma=(3.8,'angstroms'), dipoleMoment=(0,'C*m'), polarizability=(0,'angstroms^3'), rotrelaxcollnum=0.0, comment="""GRI-Mech"""), energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85), thermo = NASA(polynomials=[NASAPolynomial(coeffs=[4.01192,-0.000154979,3.26298e-06,-2.40422e-09,5.69497e-13,45867.7,0.5332], Tmin=(100,'K'), Tmax=(1104.58,'K')), NASAPolynomial(coeffs=[3.14983,0.00296674,-9.76056e-07,1.54115e-10,-9.50338e-15,46058.1,4.77808], Tmin=(1104.58,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(381.37,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(58.2013,'J/(mol*K)'), label="""CH2(T)""", comment="""Thermo library: primaryThermoLibrary"""), ) species( label = '[CH2][C]([CH2])O[CH]O(10505)', structure = SMILES('[CH2][C]([CH2])O[CH]O'), E0 = (328.571,'kJ/mol'), modes = [ HarmonicOscillator(frequencies=([3025,407.5,1350,352.5,360,370,350,3615,1277.5,1000,3000,3033.33,3066.67,3100,415,465,780,850,1435,1475,900,1100,200,800,1600],'cm^-1')), HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False), ], spinMultiplicity = 5, opticalIsomers = 1, molecularWeight = (86.0892,'amu'), energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85), thermo = NASA(polynomials=[NASAPolynomial(coeffs=[-0.0858797,0.105515,-0.000206973,1.91202e-07,-6.47617e-11,39650.4,26.1779], Tmin=(100,'K'), Tmax=(911.375,'K')), NASAPolynomial(coeffs=[9.26195,0.0258236,-1.21771e-05,2.16061e-09,-1.36723e-13,39552.3,-9.24324], Tmin=(911.375,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(328.571,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(261.906,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-CsCs) + longDistanceInteraction_noncyclic(OsCs-ST) + group(O2s-CsH) + group(Cs-CsCsOsH) + group(Cs-CsHHH) + group(Cs-CsHHH) + group(Cs-OsOsHH) + radical(C2CsJOCs) + radical(OCJO) + radical(CJC(C)OC) + radical(CJC(C)OC)"""), ) species( label = '[CH]C(O)O[C]([CH2])[CH2](10631)', structure = SMILES('[CH]C(O)O[C]([CH2])[CH2]'), E0 = (542.004,'kJ/mol'), modes = [ HarmonicOscillator(frequencies=([3000,3033.33,3066.67,3100,415,465,780,850,1435,1475,900,1100,360,370,350,3615,1277.5,1000,1380,1390,370,380,2900,435,200,800,1000,1200,1400,1600],'cm^-1')), HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False), ], spinMultiplicity = 6, opticalIsomers = 1, molecularWeight = (99.1079,'amu'), energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85), thermo = NASA(polynomials=[NASAPolynomial(coeffs=[-0.530184,0.115319,-0.000215576,1.98589e-07,-6.82281e-11,65336.3,32.0655], Tmin=(100,'K'), Tmax=(888.202,'K')), NASAPolynomial(coeffs=[9.4619,0.0339038,-1.65827e-05,3.06772e-09,-2.02786e-13,64997.7,-6.86968], Tmin=(888.202,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(542.004,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(307.635,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-CsCs) + longDistanceInteraction_noncyclic(OsCs-ST) + group(O2s-CsH) + group(Cs-CsCsOsH) + group(Cs-CsOsOsH) + group(Cs-CsHHH) + group(Cs-CsHHH) + group(Cs-CsHHH) + radical(CJC(C)OC) + radical(CJC(C)OC) + radical(CCJ2_triplet) + radical(C2CsJOCs)"""), ) species( label = '[CH][C]([CH2])OC([CH2])O(10632)', structure = SMILES('[CH][C]([CH2])OC([CH2])O'), E0 = (543.083,'kJ/mol'), modes = [ HarmonicOscillator(frequencies=([3000,3033.33,3066.67,3100,415,465,780,850,1435,1475,900,1100,360,370,350,3615,1277.5,1000,1380,1390,370,380,2900,435,200,800,1000,1200,1400,1600],'cm^-1')), HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False), HinderedRotor(inertia=(0.156089,'amu*angstrom^2'), symmetry=1, barrier=(3.5888,'kJ/mol'), semiclassical=False), ], spinMultiplicity = 6, opticalIsomers = 1, molecularWeight = (99.1079,'amu'), energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85), thermo = NASA(polynomials=[NASAPolynomial(coeffs=[-0.315358,0.107565,-0.000191221,1.72277e-07,-5.87284e-11,65461.2,32.8691], Tmin=(100,'K'), Tmax=(877.434,'K')), NASAPolynomial(coeffs=[9.98375,0.0328128,-1.59025e-05,2.96118e-09,-1.97838e-13,64724,-9.37305], Tmin=(877.434,'K'), Tmax=(5000,'K'))], Tmin=(100,'K'), Tmax=(5000,'K'), E0=(543.083,'kJ/mol'), Cp0=(33.2579,'J/(mol*K)'), CpInf=(307.635,'J/(mol*K)'), comment="""Thermo group additivity estimation: group(O2s-CsCs) + longDistanceInteraction_noncyclic(OsCs-ST) + group(O2s-CsH) + group(Cs-CsCsOsH) + group(Cs-CsOsOsH) + group(Cs-CsHHH) + group(Cs-CsHHH) + group(Cs-CsHHH) + radical(C2CsJOCs) + radical(CJC(C)OC) + radical(CCJ2_triplet) + radical(CJCO)"""), ) species( label = 'N2', structure = SMILES('N#N'), E0 = (-8.64289,'kJ/mol'), spinMultiplicity = 1, opticalIsomers = 1, molecularWeight = (28.0135,'amu'), collisionModel = TransportData(shapeIndex=1, epsilon=(810.913,'J/mol'), sigma=(3.621,'angstroms'), dipoleMoment=(0,'C*m'), polarizability=(1.76,'angstroms^3'), rotrelaxcollnum=4.0, comment="""GRI-Mech"""), energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85), thermo = NASA(polynomials=[NASAPolynomial(coeffs=[3.53101,-0.000123661,-5.02999e-07,2.43531e-09,-1.40881e-12,-1046.98,2.96747], Tmin=(200,'K'), Tmax=(1000,'K')), NASAPolynomial(coeffs=[2.95258,0.0013969,-4.92632e-07,7.8601e-11,-4.60755e-15,-923.949,5.87189], Tmin=(1000,'K'), Tmax=(6000,'K'))], Tmin=(200,'K'), Tmax=(6000,'K'), E0=(-8.64289,'kJ/mol'), Cp0=(29.1007,'J/(mol*K)'), CpInf=(37.4151,'J/(mol*K)'), label="""N2""", comment="""Thermo library: primaryThermoLibrary"""), ) species( label = 'Ne', structure = SMILES('[Ne]'), E0 = (-6.19738,'kJ/mol'), spinMultiplicity = 1, opticalIsomers = 1, molecularWeight = (20.1797,'amu'), collisionModel = TransportData(shapeIndex=0, epsilon=(1235.53,'J/mol'), sigma=(3.758e-10,'m'), dipoleMoment=(0,'C*m'), polarizability=(0,'angstroms^3'), rotrelaxcollnum=0, comment="""Epsilon & sigma estimated with fixed Lennard Jones Parameters. This is the fallback method! Try improving transport databases!"""), energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85), thermo = NASA(polynomials=[NASAPolynomial(coeffs=[2.5,0,0,0,0,-745.375,3.35532], Tmin=(200,'K'), Tmax=(1000,'K')), NASAPolynomial(coeffs=[2.5,0,0,0,0,-745.375,3.35532], Tmin=(1000,'K'), Tmax=(6000,'K'))], Tmin=(200,'K'), Tmax=(6000,'K'), E0=(-6.19738,'kJ/mol'), Cp0=(20.7862,'J/(mol*K)'), CpInf=(20.7862,'J/(mol*K)'), label="""Ne""", comment="""Thermo library: primaryThermoLibrary"""), ) species( label = 'He', structure = SMILES('[He]'), E0 = (-6.19738,'kJ/mol'), spinMultiplicity = 1, opticalIsomers = 1, molecularWeight = (4.0026,'amu'), collisionModel = TransportData(shapeIndex=0, epsilon=(84.8076,'J/mol'), sigma=(2.576,'angstroms'), dipoleMoment=(0,'De'), polarizability=(0,'angstroms^3'), rotrelaxcollnum=0.0, comment="""NOx2018"""), energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85), thermo = NASA(polynomials=[NASAPolynomial(coeffs=[2.5,0,0,0,0,-745.375,0.928724], Tmin=(200,'K'), Tmax=(1000,'K')), NASAPolynomial(coeffs=[2.5,0,0,0,0,-745.375,0.928724], Tmin=(1000,'K'), Tmax=(6000,'K'))], Tmin=(200,'K'), Tmax=(6000,'K'), E0=(-6.19738,'kJ/mol'), Cp0=(20.7862,'J/(mol*K)'), CpInf=(20.7862,'J/(mol*K)'), label="""He""", comment="""Thermo library: primaryThermoLibrary"""), ) species( label = 'Ar', structure = SMILES('[Ar]'), E0 = (-6.19738,'kJ/mol'), spinMultiplicity = 1, opticalIsomers = 1, molecularWeight = (39.348,'amu'), collisionModel = TransportData(shapeIndex=0, epsilon=(1134.93,'J/mol'), sigma=(3.33,'angstroms'), dipoleMoment=(0,'C*m'), polarizability=(0,'angstroms^3'), rotrelaxcollnum=0.0, comment="""GRI-Mech"""), energyTransferModel = SingleExponentialDown(alpha0=(3.5886,'kJ/mol'), T0=(300,'K'), n=0.85), thermo = NASA(polynomials=[NASAPolynomial(coeffs=[2.5,0,0,0,0,-745.375,4.37967], Tmin=(200,'K'), Tmax=(1000,'K')), NASAPolynomial(coeffs=[2.5,0,0,0,0,-745.375,4.37967], Tmin=(1000,'K'), Tmax=(6000,'K'))], Tmin=(200,'K'), Tmax=(6000,'K'), E0=(-6.19738,'kJ/mol'), Cp0=(20.7862,'J/(mol*K)'), CpInf=(20.7862,'J/(mol*K)'), label="""Ar""", comment="""Thermo library: primaryThermoLibrary"""), ) transitionState( label = 'TS1', E0 = (305.378,'kJ/mol'), spinMultiplicity = 1, opticalIsomers = 1, ) transitionState( label = 'TS2', E0 = (371.316,'kJ/mol'), spinMultiplicity = 1, opticalIsomers = 1, ) transitionState( label = 'TS3', E0 = (305.378,'kJ/mol'), spinMultiplicity = 1, opticalIsomers = 1, ) transitionState( label = 'TS4', E0 = (365.529,'kJ/mol'), spinMultiplicity = 1, opticalIsomers = 1, ) transitionState( label = 'TS5', E0 = (408.058,'kJ/mol'), spinMultiplicity = 1, opticalIsomers = 1, ) transitionState( label = 'TS6', E0 = (494.702,'kJ/mol'), spinMultiplicity = 1, opticalIsomers = 1, ) transitionState( label = 'TS7', E0 = (458.172,'kJ/mol'), spinMultiplicity = 1, opticalIsomers = 1, ) transitionState( label = 'TS8', E0 = (436.503,'kJ/mol'), spinMultiplicity = 1, opticalIsomers = 1, ) transitionState( label = 'TS9', E0 = (477.773,'kJ/mol'), spinMultiplicity = 1, opticalIsomers = 1, ) transitionState( label = 'TS10', E0 = (380.467,'kJ/mol'), spinMultiplicity = 1, opticalIsomers = 1, ) transitionState( label = 'TS11', E0 = (672.489,'kJ/mol'), spinMultiplicity = 1, opticalIsomers = 1, ) transitionState( label = 'TS12', E0 = (714.564,'kJ/mol'), spinMultiplicity = 1, opticalIsomers = 1, ) transitionState( label = 'TS13', E0 = (749.983,'kJ/mol'), spinMultiplicity = 1, opticalIsomers = 1, ) transitionState( label = 'TS14', E0 = (722.429,'kJ/mol'), spinMultiplicity = 1, opticalIsomers = 1, ) transitionState( label = 'TS15', E0 = (368.778,'kJ/mol'), spinMultiplicity = 1, opticalIsomers = 1, ) transitionState( label = 'TS16', E0 = (313.662,'kJ/mol'), spinMultiplicity = 1, opticalIsomers = 1, ) transitionState( label = 'TS17', E0 = (723.843,'kJ/mol'), spinMultiplicity = 1, opticalIsomers = 1, ) transitionState( label = 'TS18', E0 = (744.257,'kJ/mol'), spinMultiplicity = 1, opticalIsomers = 1, ) transitionState( label = 'TS19', E0 = (753.809,'kJ/mol'), spinMultiplicity = 1, opticalIsomers = 1, ) transitionState( label = 'TS20', E0 = (754.888,'kJ/mol'), spinMultiplicity = 1, opticalIsomers = 1, ) reaction( label = 'reaction1', reactants = ['[CH2][C]([CH2])OC([CH2])O(10182)'], products = ['C=CO(576)', '[CH2]C(=C)[O](4273)'], transitionState = 'TS1', kinetics = Arrhenius(A=(5e+12,'s^-1'), n=0, Ea=(0,'kJ/mol'), T0=(1,'K'), Tmin=(300,'K'), Tmax=(1500,'K'), comment="""Exact match found for rate rule [RJJ] Euclidian distance = 0 family: 1,4_Linear_birad_scission"""), ) reaction( label = 'reaction2', reactants = ['H(8)', '[CH2][C](O)OC([CH2])=C(10629)'], products = ['[CH2][C]([CH2])OC([CH2])O(10182)'], transitionState = 'TS2', kinetics = Arrhenius(A=(170.395,'m^3/(mol*s)'), n=1.5621, Ea=(11.2886,'kJ/mol'), T0=(1,'K'), comment="""Estimated using template [Cds_Cds;HJ] for rate rule [Cds-OsOs_Cds;HJ] Euclidian distance = 1.0 family: R_Addition_MultipleBond"""), ) reaction( label = 'reaction3', reactants = ['[CH2][CH]O(578)', '[CH2]C(=C)[O](4273)'], products = ['[CH2][C]([CH2])OC([CH2])O(10182)'], transitionState = 'TS3', kinetics = Arrhenius(A=(1.81675,'m^3/(mol*s)'), n=2.00263, Ea=(81.7754,'kJ/mol'), T0=(1,'K'), comment="""Estimated using average of templates [R_R;CJ] + [Od_R;YJ] for rate rule [Od_R;CJ] Euclidian distance = 1.0 family: R_Addition_MultipleBond Ea raised from 81.0 to 81.8 kJ/mol to match endothermicity of reaction."""), ) reaction( label = 'reaction4', reactants = ['OH(D)(132)', '[CH2][CH]OC([CH2])=C(6355)'], products = ['[CH2][C]([CH2])OC([CH2])O(10182)'], transitionState = 'TS4', kinetics = Arrhenius(A=(931.236,'m^3/(mol*s)'), n=1.015, Ea=(0,'kJ/mol'), T0=(1,'K'), comment="""Estimated using template [Cds_Cds;OJ_pri] for rate rule [Cds-OsH_Cds;OJ_pri] Euclidian distance = 1.0 family: R_Addition_MultipleBond Ea raised from -7.3 to 0 kJ/mol."""), ) reaction( label = 'reaction5', reactants = ['[CH2][C]([CH2])OC([CH2])O(10182)'], products = ['[CH2][C]([CH2])O[C](C)O(10540)'], transitionState = 'TS5', kinetics = Arrhenius(A=(5.265e-07,'s^-1'), n=5.639, Ea=(102.68,'kJ/mol'), T0=(1,'K'), comment="""Estimated using template [R2H_S;C_rad_out_2H;Cs_H_out_NonDe] for rate rule [R2H_S;C_rad_out_2H;Cs_H_out_NDMustO] Euclidian distance = 1.0 family: intra_H_migration"""), ) reaction( label = 'reaction6', reactants = ['[CH2][C](O)OC([CH2])[CH2](2365)'], products = ['[CH2][C]([CH2])OC([CH2])O(10182)'], transitionState = 'TS6', kinetics = Arrhenius(A=(2.9172e+08,'s^-1'), n=1.32036, Ea=(164.782,'kJ/mol'), T0=(1,'K'), comment="""Estimated using an average for rate rule [R3H_SS_O;Y_rad_out;XH_out] Euclidian distance = 0 family: intra_H_migration"""), ) reaction( label = 'reaction7', reactants = ['[CH2][C]([CH2])OC(C)[O](10156)'], products = ['[CH2][C]([CH2])OC([CH2])O(10182)'], transitionState = 'TS7', kinetics = Arrhenius(A=(62433.6,'s^-1'), n=2.54422, Ea=(138.678,'kJ/mol'), T0=(1,'K'), comment="""Estimated using average of templates [R3H_SS;O_rad_out;Cs_H_out_2H] + [R3H_SS_Cs;Y_rad_out;Cs_H_out_2H] + [R3H_SS_Cs;O_rad_out;Cs_H_out] for rate rule [R3H_SS_Cs;O_rad_out;Cs_H_out_2H] Euclidian distance = 1.0 Multiplied by reaction path degeneracy 3.0 family: intra_H_migration"""), ) reaction( label = 'reaction8', reactants = ['[CH2][C]([CH2])OC([CH2])O(10182)'], products = ['[CH2][C](C)O[C]([CH2])O(2362)'], transitionState = 'TS8', kinetics = Arrhenius(A=(869.832,'s^-1'), n=2.67444, Ea=(131.125,'kJ/mol'), T0=(1,'K'), comment="""Estimated using template [R4Hall;C_rad_out_2H;XH_out] for rate rule [R4HJ_1;C_rad_out_2H;XH_out] Euclidian distance = 1.0 Multiplied by reaction path degeneracy 2.0 family: intra_H_migration"""), ) reaction( label = 'reaction9', reactants = ['[CH2]C([CH2])OC([CH2])[O](2364)'], products = ['[CH2][C]([CH2])OC([CH2])O(10182)'], transitionState = 'TS9', kinetics = Arrhenius(A=(1.75172e+06,'s^-1'), n=1.80068, Ea=(127.394,'kJ/mol'), T0=(1,'K'), comment="""Estimated using an average for rate rule [R4H_SSS;O_rad_out;XH_out] Euclidian distance = 0 family: intra_H_migration"""), ) reaction( label = 'reaction10', reactants = ['[CH2][C](C)OC([CH2])[O](2361)'], products = ['[CH2][C]([CH2])OC([CH2])O(10182)'], transitionState = 'TS10', kinetics = Arrhenius(A=(7.8e+08,'s^-1'), n=0.775, Ea=(59.894,'kJ/mol'), T0=(1,'K'), comment="""Estimated using template [R5Hall;O_rad_out;Cs_H_out_2H] for rate rule [R5HJ_3;O_rad_out;Cs_H_out_2H] Euclidian distance = 1.0 Multiplied by reaction path degeneracy 3.0 family: intra_H_migration"""), ) reaction( label = 'reaction11', reactants = ['[CH2][CH]O(578)', '[CH2][C]([CH2])[O](10271)'], products = ['[CH2][C]([CH2])OC([CH2])O(10182)'], transitionState = 'TS11', kinetics = Arrhenius(A=(1.9789e+07,'m^3/(mol*s)'), n=-0.126319, Ea=(0,'kJ/mol'), T0=(1,'K'), comment="""Estimated using an average for rate rule [Y_rad;Y_rad] Euclidian distance = 0 family: R_Recombination Ea raised from -15.6 to -15.6 kJ/mol. Ea raised from -15.6 to 0 kJ/mol."""), ) reaction( label = 'reaction12', reactants = ['OH(D)(132)', '[CH2][CH]O[C]([CH2])[CH2](6357)'], products = ['[CH2][C]([CH2])OC([CH2])O(10182)'], transitionState = 'TS12', kinetics = Arrhenius(A=(3.05166e+07,'m^3/(mol*s)'), n=0.045, Ea=(0.1046,'kJ/mol'), T0=(1,'K'), comment="""Estimated using an average for rate rule [O_pri_rad;Y_rad] Euclidian distance = 0 family: R_Recombination"""), ) reaction( label = 'reaction13', reactants = ['H(8)', '[CH2][C]([CH2])OC([CH2])[O](6725)'], products = ['[CH2][C]([CH2])OC([CH2])O(10182)'], transitionState = 'TS13', kinetics = Arrhenius(A=(5.00518e+06,'m^3/(mol*s)'), n=0.282325, Ea=(7.09479,'kJ/mol'), T0=(1,'K'), comment="""Estimated using average of templates [Y_rad;O_rad/NonDe] + [H_rad;O_sec_rad] for rate rule [H_rad;O_rad/NonDe] Euclidian distance = 1.0 family: R_Recombination"""), ) reaction( label = 'reaction14', reactants = ['H(8)', '[CH2][C]([CH2])O[C]([CH2])O(6726)'], products = ['[CH2][C]([CH2])OC([CH2])O(10182)'], transitionState = 'TS14', kinetics = Arrhenius(A=(4.34078e+06,'m^3/(mol*s)'), n=0.278577, Ea=(0,'kJ/mol'), T0=(1,'K'), comment="""Estimated using an average for rate rule [Y_rad;H_rad] Euclidian distance = 0 family: R_Recombination Ea raised from -1.4 to 0 kJ/mol."""), ) reaction( label = 'reaction15', reactants = ['[CH2][C]([CH2])OC([CH2])O(10182)'], products = ['[CH2]C([CH2])OC(=C)O(10630)'], transitionState = 'TS15', kinetics = Arrhenius(A=(7.437e+08,'s^-1'), n=1.045, Ea=(63.4002,'kJ/mol'), T0=(1,'K'), comment="""Estimated using an average for rate rule [R3radExo;Y_rad;XH_Rrad] Euclidian distance = 0 family: Intra_Disproportionation"""), ) reaction( label = 'reaction16', reactants = ['[CH2][C]([CH2])OC([CH2])O(10182)'], products = ['[CH2]C1([CH2])CC(O)O1(10183)'], transitionState = 'TS16', kinetics = Arrhenius(A=(1.62e+12,'s^-1'), n=-0.305, Ea=(8.28432,'kJ/mol'), T0=(1,'K'), Tmin=(600,'K'), Tmax=(2000,'K'), comment="""Estimated using an average for rate rule [R4_SSS;Y_rad_out;Cpri_rad_out_2H] Euclidian distance = 0 family: Birad_recombination"""), ) reaction( label = 'reaction17', reactants = ['[CH2]C([O])O(670)', '[CH2][C][CH2](10272)'], products = ['[CH2][C]([CH2])OC([CH2])O(10182)'], transitionState = 'TS17', kinetics = Arrhenius(A=(43.5839,'m^3/(mol*s)'), n=1.88017, Ea=(5.1666,'kJ/mol'), T0=(1,'K'), Tmin=(303.03,'K'), Tmax=(2000,'K'), comment="""Estimated using an average for rate rule [O_rad/NonDe;Birad] Euclidian distance = 0 family: Birad_R_Recombination"""), ) reaction( label = 'reaction18', reactants = ['CH2(T)(28)', '[CH2][C]([CH2])O[CH]O(10505)'], products = ['[CH2][C]([CH2])OC([CH2])O(10182)'], transitionState = 'TS18', kinetics = Arrhenius(A=(1.14854e+06,'m^3/(mol*s)'), n=0.575199, Ea=(34.3157,'kJ/mol'), T0=(1,'K'), comment="""Estimated using template [Y_rad;Birad] for rate rule [C_rad/H/O2;Birad] Euclidian distance = 4.0 family: Birad_R_Recombination"""), ) reaction( label = 'reaction19', reactants = ['H(8)', '[CH]C(O)O[C]([CH2])[CH2](10631)'], products = ['[CH2][C]([CH2])OC([CH2])O(10182)'], transitionState = 'TS19', kinetics = Arrhenius(A=(1e+07,'m^3/(mol*s)'), n=0, Ea=(0,'kJ/mol'), T0=(1,'K'), comment="""Estimated using an average for rate rule [H_rad;Birad] Euclidian distance = 0 family: Birad_R_Recombination"""), ) reaction( label = 'reaction20', reactants = ['H(8)', '[CH][C]([CH2])OC([CH2])O(10632)'], products = ['[CH2][C]([CH2])OC([CH2])O(10182)'], transitionState = 'TS20', kinetics = Arrhenius(A=(1e+07,'m^3/(mol*s)'), n=0, Ea=(0,'kJ/mol'), T0=(1,'K'), comment="""Estimated using an average for rate rule [H_rad;Birad] Euclidian distance = 0 family: Birad_R_Recombination"""), ) network( label = '2859', isomers = [ '[CH2][C]([CH2])OC([CH2])O(10182)', ], reactants = [ ('C=CO(576)', '[CH2]C(=C)[O](4273)'), ], bathGas = { 'N2': 0.25, 'Ne': 0.25, 'He': 0.25, 'Ar': 0.25, }, ) pressureDependence( label = '2859', Tmin = (1200,'K'), Tmax = (1500,'K'), Tcount = 10, Tlist = ([1201.48,1213.22,1236.21,1269.31,1310.55,1356.92,1404.16,1447.02,1479.84,1497.7],'K'), Pmin = (1,'atm'), Pmax = (10,'atm'), Pcount = 10, Plist = ([1.02771,1.14872,1.41959,1.89986,2.67608,3.83649,5.40396,7.23219,8.93758,9.98989],'bar'), maximumGrainSize = (0.5,'kcal/mol'), minimumGrainCount = 250, method = 'modified strong collision', interpolationModel = ('Chebyshev', 6, 4), activeKRotor = True, activeJRotor = True, rmgmode = True, )
[ "dinius.ab@husky.neu.edu" ]
dinius.ab@husky.neu.edu
7f91c02504e6d266ed0d2d3714c567ea0a2fd731
8acffb8c4ddca5bfef910e58d3faa0e4de83fce8
/ml-flask/Lib/site-packages/gensim/nosy.py
3e6340e85f0878212b450c7936cc786ab7e9c1d3
[ "MIT" ]
permissive
YaminiHP/SimilitudeApp
8cbde52caec3c19d5fa73508fc005f38f79b8418
005c59894d8788c97be16ec420c0a43aaec99b80
refs/heads/master
2023-06-27T00:03:00.404080
2021-07-25T17:51:27
2021-07-25T17:51:27
389,390,951
0
0
null
null
null
null
UTF-8
Python
false
false
129
py
version https://git-lfs.github.com/spec/v1 oid sha256:67fa7e813100e4a41be9728ee8a521d4a488ec12655fc2e06e5c2a302445df3b size 1407
[ "yamprakash130@gmail.com" ]
yamprakash130@gmail.com
72223f10d913723ce44e84a0057fb20a83494203
a31e7a01b0a7879ddbda7ba3a606ff4df718f0ef
/app/ingredients/apis/__init__.py
f83d6db436bc44756bd94b14c67da226d9d63650
[]
no_license
smallbee3/Subway_Server
27a477c81b830d2f264afb09c646d53d8096e5f4
c0bebf3715663c7d29ffdc9e9ff878d226dd3496
refs/heads/master
2021-02-17T00:58:29.371121
2018-12-27T10:43:51
2018-12-27T10:43:51
null
0
0
null
null
null
null
UTF-8
Python
false
false
163
py
from .sandwich import * from .bread import * from .cheese import * from .toasting import * from .toppings import * from .vegetables import * from .sauces import *
[ "smallbee3@gmail.com" ]
smallbee3@gmail.com
947f2354c12c0c6018cf8ef04366e36ba0a30a3a
681be3b4cfa00433fe4a926446ea627d6d1becc0
/worldcup/python启动服务.py
84345aafa4e486acb49d4cdf6dfd4ad059fa687e
[]
no_license
snailuncle/helloNode
2141336c7f0489eb49d36f7af2131c22e39ea5f6
906a90809a674ccac039963701ff27992df37cba
refs/heads/master
2020-03-25T13:29:29.198464
2018-09-03T01:12:21
2018-09-03T01:12:21
143,828,416
0
0
null
null
null
null
UTF-8
Python
false
false
56
py
python -m SimpleHTTPServer python -m http.server 8000
[ "1789500304@qq.com" ]
1789500304@qq.com
9d4b803130a5a9f854d3606a9baf73ec90a5b953
29c3595a4e1f8de9382650610aee5a13e2a135f6
/venv/Lib/site-packages/autobahn/websocket/test/test_websocket_protocol.py
9ce7ed7ac72bb166e8c7fa147c721468acb73115
[ "MIT" ]
permissive
zoelesv/Smathchat
1515fa56fbb0ad47e1859f6bf931b772446ea261
5cee0a8c4180a3108538b4e4ce945a18726595a6
refs/heads/main
2023-08-04T14:47:21.185149
2023-08-02T15:53:20
2023-08-02T15:53:20
364,627,392
9
1
MIT
2023-08-02T15:53:21
2021-05-05T15:42:47
Python
UTF-8
Python
false
false
9,475
py
############################################################################### # # The MIT License (MIT) # # Copyright (c) Crossbar.io Technologies GmbH # # 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. # ############################################################################### import os import unittest from hashlib import sha1 from base64 import b64encode from unittest.mock import Mock from autobahn.websocket.protocol import WebSocketServerProtocol from autobahn.websocket.protocol import WebSocketServerFactory from autobahn.websocket.protocol import WebSocketClientProtocol from autobahn.websocket.protocol import WebSocketClientFactory from autobahn.websocket.protocol import WebSocketProtocol from autobahn.websocket.types import ConnectingRequest from autobahn.testutil import FakeTransport import txaio class WebSocketClientProtocolTests(unittest.TestCase): def setUp(self): t = FakeTransport() f = WebSocketClientFactory() p = WebSocketClientProtocol() p.factory = f p.transport = t p._create_transport_details = Mock() p._connectionMade() p.state = p.STATE_OPEN p.websocket_version = 18 self.protocol = p self.transport = t def tearDown(self): for call in [ self.protocol.autoPingPendingCall, self.protocol.autoPingTimeoutCall, self.protocol.openHandshakeTimeoutCall, self.protocol.closeHandshakeTimeoutCall, ]: if call is not None: call.cancel() def test_auto_ping(self): self.protocol.autoPingInterval = 1 self.protocol.websocket_protocols = [Mock()] self.protocol.websocket_extensions = [] self.protocol._onOpen = lambda: None self.protocol._wskey = '0' * 24 self.protocol.peer = Mock() # usually provided by the Twisted or asyncio specific # subclass, but we're testing the parent here... self.protocol._onConnect = Mock() self.protocol._closeConnection = Mock() # set up a connection self.protocol._actuallyStartHandshake( ConnectingRequest( host="example.com", port=80, resource="/ws", ) ) key = self.protocol.websocket_key + WebSocketProtocol._WS_MAGIC self.protocol.data = ( b"HTTP/1.1 101 Switching Protocols\x0d\x0a" b"Upgrade: websocket\x0d\x0a" b"Connection: upgrade\x0d\x0a" b"Sec-Websocket-Accept: " + b64encode(sha1(key).digest()) + b"\x0d\x0a\x0d\x0a" ) self.protocol.processHandshake() self.assertTrue(self.protocol.autoPingPendingCall is not None) class WebSocketServerProtocolTests(unittest.TestCase): """ Tests for autobahn.websocket.protocol.WebSocketProtocol. """ def setUp(self): t = FakeTransport() f = WebSocketServerFactory() p = WebSocketServerProtocol() p.factory = f p.transport = t p._connectionMade() p.state = p.STATE_OPEN p.websocket_version = 18 self.protocol = p self.transport = t def tearDown(self): for call in [ self.protocol.autoPingPendingCall, self.protocol.autoPingTimeoutCall, self.protocol.openHandshakeTimeoutCall, self.protocol.closeHandshakeTimeoutCall, ]: if call is not None: call.cancel() def test_auto_ping(self): proto = Mock() proto._get_seconds = Mock(return_value=1) self.protocol.autoPingInterval = 1 self.protocol.websocket_protocols = [proto] self.protocol.websocket_extensions = [] self.protocol._onOpen = lambda: None self.protocol._wskey = '0' * 24 self.protocol.succeedHandshake(proto) self.assertTrue(self.protocol.autoPingPendingCall is not None) def test_sendClose_none(self): """ sendClose with no code or reason works. """ self.protocol.sendClose() # We closed properly self.assertEqual(self.transport._written, b"\x88\x00") self.assertEqual(self.protocol.state, self.protocol.STATE_CLOSING) def test_sendClose_str_reason(self): """ sendClose with a str reason works. """ self.protocol.sendClose(code=1000, reason="oh no") # We closed properly self.assertEqual(self.transport._written[2:], b"\x03\xe8oh no") self.assertEqual(self.protocol.state, self.protocol.STATE_CLOSING) def test_sendClose_unicode_reason(self): """ sendClose with a unicode reason works. """ self.protocol.sendClose(code=1000, reason="oh no") # We closed properly self.assertEqual(self.transport._written[2:], b"\x03\xe8oh no") self.assertEqual(self.protocol.state, self.protocol.STATE_CLOSING) def test_sendClose_toolong(self): """ sendClose with a too-long reason will truncate it. """ self.protocol.sendClose(code=1000, reason="abc" * 1000) # We closed properly self.assertEqual(self.transport._written[2:], b"\x03\xe8" + (b"abc" * 41)) self.assertEqual(self.protocol.state, self.protocol.STATE_CLOSING) def test_sendClose_reason_with_no_code(self): """ Trying to sendClose with a reason but no code will raise an Exception. """ with self.assertRaises(Exception) as e: self.protocol.sendClose(reason="abc") self.assertIn("close reason without close code", str(e.exception)) # We shouldn't have closed self.assertEqual(self.transport._written, b"") self.assertEqual(self.protocol.state, self.protocol.STATE_OPEN) def test_sendClose_invalid_code_type(self): """ Trying to sendClose with a non-int code will raise an Exception. """ with self.assertRaises(Exception) as e: self.protocol.sendClose(code="134") self.assertIn("invalid type", str(e.exception)) # We shouldn't have closed self.assertEqual(self.transport._written, b"") self.assertEqual(self.protocol.state, self.protocol.STATE_OPEN) def test_sendClose_invalid_code_value(self): """ Trying to sendClose with a non-valid int code will raise an Exception. """ with self.assertRaises(Exception) as e: self.protocol.sendClose(code=10) self.assertIn("invalid close code 10", str(e.exception)) # We shouldn't have closed self.assertEqual(self.transport._written, b"") self.assertEqual(self.protocol.state, self.protocol.STATE_OPEN) if os.environ.get('USE_TWISTED', False): class TwistedProtocolTests(unittest.TestCase): """ Tests which require a specific framework's protocol class to work (in this case, using Twisted) """ def setUp(self): from autobahn.twisted.websocket import WebSocketServerProtocol from autobahn.twisted.websocket import WebSocketServerFactory t = FakeTransport() f = WebSocketServerFactory() p = WebSocketServerProtocol() p.factory = f p.transport = t p._connectionMade() p.state = p.STATE_OPEN p.websocket_version = 18 self.protocol = p self.transport = t def tearDown(self): for call in [ self.protocol.autoPingPendingCall, self.protocol.autoPingTimeoutCall, self.protocol.openHandshakeTimeoutCall, self.protocol.closeHandshakeTimeoutCall, ]: if call is not None: call.cancel() def test_loseConnection(self): """ If we lose our connection before openHandshakeTimeout fires, it is cleaned up """ # so, I guess a little cheezy, but we depend on the asyncio or # twisted class to call _connectionLost at some point; faking # that here self.protocol._connectionLost(txaio.create_failure(RuntimeError("testing"))) self.assertTrue(self.protocol.openHandshakeTimeoutCall is None)
[ "ZoomLee@users.noreply.github.com" ]
ZoomLee@users.noreply.github.com
e7a2127c826f94d3c911d95c8b6038cccefef18c
78c4ccb183a99ebaabcdc3a3a69f029e4aee0f5c
/AlgorithmStudy/백준/5 DFS & BFS/11 토마토.py
60372a187211792a6f091d124a6a3eac1a1504aa
[]
no_license
cladren123/study
ef2c45bc489fa658dbc9360fb0b0de53250500e5
241326e618f1f3bb1568d588bf6f53b78920587a
refs/heads/master
2023-09-02T02:21:24.560967
2021-11-05T12:20:06
2021-11-05T12:20:06
368,753,950
0
0
null
null
null
null
UTF-8
Python
false
false
1,200
py
""" 실버1 """ # m:가로칸 n:세로칸 from collections import deque m,n = map(int, input().split()) # 1:은 익은 토마토 0:익지 않은 토마토 -1:토마토가 들어있지 않은 칸 board = [list(map(int, input().split())) for _ in range(n)] visited= [[-3] * m for _ in range(n)] que = deque() dx = [1,0,-1,0] dy = [0,-1,0,1] count = 0 for i in range(n) : for j in range(m) : if board[i][j] == -1 : visited[i][j] = -1 if board[i][j] == 1 : que.append([i,j]) visited[i][j] = count while que : y,x = que.popleft() for i in range(4) : nexty = y + dy[i] nextx = x + dx[i] if 0 <= nexty < n and 0 <= nextx < m : if board[nexty][nextx] == 0 and visited[nexty][nextx] == -3 : que.append([nexty,nextx]) visited[nexty][nextx] = visited[y][x] + 1 board[nexty][nextx] = 1 answer = 0 for i in visited : if -3 in i : answer = -1 break else : if answer < max(i) : answer = max(i) print(answer) # for i in board : # print(i) # # print() # # for i in visited : # print(i)
[ "48821942+cladren123@users.noreply.github.com" ]
48821942+cladren123@users.noreply.github.com
1732a222aa9a8307cf510c5897e748bd5b556e19
fdb8d96d06cb7e74153a178fd17b449e89f44cd0
/poo_vs_estructurado/poo.py
e24044e8067356ec354c939e87f577fa5eb7830e
[]
no_license
EmaSMach/info2020
c84916521d2dd21040419cb469c76c589b98be89
a184dc376cb5e0b894a32d01681b71c824d993d3
refs/heads/master
2022-12-06T08:52:34.994922
2020-08-24T02:57:40
2020-08-24T02:57:40
273,131,222
0
0
null
null
null
null
UTF-8
Python
false
false
1,667
py
# Creo una estructura para los clientes class Cliente: def __init__(self, dni, nombre, apellidos): self.dni = dni self.nombre = nombre self.apellidos = apellidos def __str__(self): return '{} {}'.format(self.nombre, self.apellidos) def __repr__(self): return str(self) # Y otra para las empresas class Empresa: def __init__(self, clientes=[]): self.clientes = clientes def mostrar_cliente(self, dni=None): for c in self.clientes: if c.dni == dni: print(c) return print("Cliente no encontrado") def borrar_cliente(self, dni=None): for i, c in enumerate(self.clientes): if c.dni == dni: del(self.clientes[i]) print(str(c), "> BORRADO") return print("Cliente no encontrado") # Ahora utilizaremos ambas estructuras # Creemos un par de clientes hector = Cliente(nombre="Hector", apellidos="Costa Guzman", dni="11111111A") juan = Cliente("22222222B", "Juan", "Gonzalez Marquez") # Creemos una empresa con los clientes iniciales empresa = Empresa(clientes=[hector, juan]) # Se muestran todos los clientes print("==LISTADO DE CLIENTES==") print(empresa.clientes) print("\n==MOSTRAR CLIENTES POR DNI==") # Se consulta clientes por DNI empresa.mostrar_cliente("11111111A") empresa.mostrar_cliente("11111111Z") print("\n==BORRAR CLIENTES POR DNI==") # Se borra un cliente por DNI empresa.borrar_cliente("22222222V") empresa.borrar_cliente("22222222B") # Se muestran de nuevo todos los clientes print("\n==LISTADO DE CLIENTES==") print(empresa.clientes)
[ "davidemanuelsandoval@gmail.com" ]
davidemanuelsandoval@gmail.com
a7fd6a5636da3ad3daab9964b5057344b43fbd77
956cc6ff2b58a69292f7d1223461bc9c2b9ea6f1
/monk/system_unit_tests/pytorch/test_optimizer_adadelta.py
9f4ba4daa325105e45dc523eb6c714525e3b7b40
[ "Apache-2.0" ]
permissive
Aanisha/monk_v1
c24279b2b461df9b3de2984bae0e2583aba48143
c9e89b2bc0c1dbb320aa6da5cba0aa1c1526ad72
refs/heads/master
2022-12-29T00:37:15.320129
2020-10-18T09:12:13
2020-10-18T09:12:13
286,278,278
0
0
Apache-2.0
2020-08-09T16:51:02
2020-08-09T16:51:02
null
UTF-8
Python
false
false
1,828
py
import os import sys sys.path.append("../../../../monk_v1/"); sys.path.append("../../../monk/"); import psutil from pytorch_prototype import prototype from compare_prototype import compare from common import print_start from common import print_status def test_optimizer_adadelta(system_dict): forward = True; if(not os.path.isdir("datasets")): os.system("! wget --load-cookies /tmp/cookies.txt \"https://docs.google.com/uc?export=download&confirm=$(wget --save-cookies /tmp/cookies.txt --keep-session-cookies --no-check-certificate 'https://docs.google.com/uc?export=download&id=1rG-U1mS8hDU7_wM56a1kc-li_zHLtbq2' -O- | sed -rn 's/.*confirm=([0-9A-Za-z_]+).*/\1\n/p')&id=1rG-U1mS8hDU7_wM56a1kc-li_zHLtbq2\" -O datasets.zip && rm -rf /tmp/cookies.txt") os.system("! unzip -qq datasets.zip") test = "test_optimizer_adadelta"; system_dict["total_tests"] += 1; print_start(test, system_dict["total_tests"]) if(forward): try: gtf = prototype(verbose=0); gtf.Prototype("sample-project-1", "sample-experiment-1"); gtf.Default(dataset_path="../../system_check_tests/datasets/dataset_cats_dogs_train", model_name="resnet18", freeze_base_network=True, num_epochs=2); gtf.optimizer_adadelta(0.01, weight_decay=0.0001, rho=0.9, clipnorm=1.0, clipvalue=0.5); gtf.Train(); system_dict["successful_tests"] += 1; print_status("Pass"); except Exception as e: system_dict["failed_tests_exceptions"].append(e); system_dict["failed_tests_lists"].append(test); forward = False; print_status("Fail"); else: system_dict["skipped_tests_lists"].append(test); print_status("Skipped"); return system_dict
[ "abhishek4273@gmail.com" ]
abhishek4273@gmail.com
8c2cfcea57ba4e2829b34ac0622ff9d4903f0378
f2201a77b8039215591aaa31dddae7ebb72301c2
/backend/users/migrations/0002_auto_20201119_0018.py
e972e5c362cf7d7c108192355b442edcf2e62a64
[]
no_license
crowdbotics-apps/start-up-22744
8726c58855ffee7ceb48100c9ebeb26a377a1051
bbd9ce066d6636fe6866c7070a1a8370033ba91c
refs/heads/master
2023-01-11T15:30:38.074614
2020-11-19T00:19:18
2020-11-19T00:19:18
314,091,313
0
0
null
null
null
null
UTF-8
Python
false
false
1,275
py
# Generated by Django 2.2.17 on 2020-11-19 00:18 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('users', '0001_initial'), ] operations = [ migrations.AddField( model_name='user', name='last_updated', field=models.DateTimeField(auto_now=True, null=True), ), migrations.AddField( model_name='user', name='timestamp_created', field=models.DateTimeField(auto_now_add=True, null=True), ), migrations.AlterField( model_name='user', name='email', field=models.EmailField(blank=True, max_length=255, null=True), ), migrations.AlterField( model_name='user', name='first_name', field=models.CharField(blank=True, max_length=255, null=True), ), migrations.AlterField( model_name='user', name='last_name', field=models.CharField(blank=True, max_length=255, null=True), ), migrations.AlterField( model_name='user', name='name', field=models.CharField(blank=True, max_length=255, null=True), ), ]
[ "team@crowdbotics.com" ]
team@crowdbotics.com
08422f80718e6ddd8b5db6147f40775b09d9554f
d9f10273960c6956db55f694cdee5910554addd1
/run.py
a815b8440b2399dddb1a48ace624494c331228bf
[]
no_license
manuelborowski/infoheliks
09b7c6618922aa35ec2334b64cbf55d4bf0d4a80
a543960a28d00d204a4a699d58964faec6326847
refs/heads/main
2023-04-18T11:28:03.115297
2021-05-04T08:46:25
2021-05-04T08:46:25
350,639,148
0
0
null
null
null
null
UTF-8
Python
false
false
133
py
from app import flask_app, socketio if __name__ == '__main__': socketio.run(flask_app, port=5026, host='127.0.0.1', debug=False)
[ "emmanuel.borowski@gmail.com" ]
emmanuel.borowski@gmail.com
e0403b2849329c0dea1acd1f3349257cd8c11022
4111ca5a73a22174f189361bef654c3f91c3b7ed
/Lintcode/Ladder_37_BB/easy/646. First Position Unique Character.py
1f8a68e990d0be27eacc8cb5a84adaeaa998a1ad
[ "MIT" ]
permissive
ctc316/algorithm-python
58b541b654509ecf4e9eb8deebfcbdf785699cc4
ac4580d55e05e93e407c6156c9bb801808027d60
refs/heads/master
2020-03-16T06:09:50.130146
2019-08-02T02:50:49
2019-08-02T02:50:49
132,548,222
0
0
null
null
null
null
UTF-8
Python
false
false
308
py
class Solution: """ @param s: a string @return: it's index """ def firstUniqChar(self, s): counts = {} for ch in s: counts[ch] = counts.get(ch, 0) + 1 for i in range(len(s)): if counts[s[i]] == 1: return i return -1
[ "mike.tc.chen101@gmail.com" ]
mike.tc.chen101@gmail.com
cce8c03c7514638d39b72b60615e7063c2e4a4ac
dae8e0070b093d662fdeea026e3eb48814af73c5
/Autosampler/analysis/nonlinearRegression.py
f678adb1f0f4ed85179278d694bf32842efd643e
[]
no_license
clipo/RHX
43d3dc8e0f2a4d90a8c83ec2a9e4fc0be30fddae
93286e17df1ec05d98d791671d641d86b7f588b9
refs/heads/master
2021-01-02T23:06:23.023476
2013-04-27T21:42:01
2013-04-27T21:42:01
null
0
0
null
null
null
null
UTF-8
Python
false
false
911
py
__author__ = 'carllipo' import numpy as np from scipy.optimize import leastsq def function(a, time): return a * np.power(time, 0.25) def residuals(p, y, x): err = y - function(x, p) return err def nlinRegression(timeArray, weightChangeArray, minval, maxval): nlx = [] nly = [] count = 0 a_guess = 0.005 for var in timeArray: if minval < var < maxval: nlx.append(var) nly.append(weightChangeArray[count]) count += 1 kd, cov, infodict, mesg, ier = leastsq(residuals, a_guess, args=(timeArray, weightChangeArray), full_output=True) return kd[0] timeArray = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12] weightChangeArray = [0, .5, 1, 1.3, 3, 5, 7, 8, 10, 12, 12.5, 13.5, 14] minval = -1 maxval = 16 alpha = nlinRegression(timeArray, weightChangeArray, minval, maxval) print alpha
[ "clipo@csulb.edu" ]
clipo@csulb.edu
e55f1275abce7b05777331f05a7db588bb10a82f
eb74806869a4340a6d8a2623bbe72bd4e64dcde8
/apps/push/signals.py
2f2aa7d3d0a552e734bfa3cc964dd3aa73a9278b
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
sictiru/NewsBlur
a0874a1044926d2268ba07a928e62fce5c9a8310
1ab88e4cc34775d00a1ac90ee08bc2498577e773
refs/heads/sictiru
2023-08-19T20:24:20.638019
2023-08-15T03:52:09
2023-08-15T03:52:09
250,445,213
1
0
MIT
2023-03-06T15:34:38
2020-03-27T05:05:44
Objective-C
UTF-8
Python
false
false
260
py
# Adapted from djpubsubhubbub. See License: http://git.participatoryculture.org/djpubsubhubbub/tree/LICENSE from django.dispatch import Signal pre_subscribe = Signal(providing_args=['created']) verified = Signal() updated = Signal(providing_args=['update'])
[ "samuel@ofbrooklyn.com" ]
samuel@ofbrooklyn.com
8c965bc5e529ecf239d5241c6d31618513eb5b69
3474b315da3cc5cb3f7823f19a18b63a8da6a526
/scratch/KRAMS/src/ibvpy/mesh/fe_domain.py
77d1550ea5ee3bd2e315cafde023e53e6b2b7379
[]
no_license
h4ck3rm1k3/scratch
8df97462f696bc2be00f1e58232e1cd915f0fafd
0a114a41b0d1e9b2d68dbe7af7cf34db11512539
refs/heads/master
2021-01-21T15:31:38.718039
2013-09-19T10:48:24
2013-09-19T10:48:24
29,173,525
0
0
null
2015-01-13T04:58:57
2015-01-13T04:58:56
null
UTF-8
Python
false
false
4,549
py
from enthought.traits.api import \ Array, Bool, Callable, Enum, Float, HasTraits, Interface, implements, \ Instance, Int, Trait, Str, Enum, Callable, List, TraitDict, Any, \ on_trait_change, Tuple, WeakRef, Delegate, Property, cached_property, \ This, self, TraitError, Button, Event from enthought.traits.ui.api import \ View, Item, Group from numpy import array, arange from ibvpy.core.sdomain import \ SDomain from ibvpy.core.scontext import \ SContext from ibvpy.dots.dots_list_eval import \ DOTSListEval from ibvpy.rtrace.rt_domain_list import \ RTraceDomainList class FEDomain( SDomain ): '''Test the state dependencies within the hierarchical domain representation. ''' changed_structure = Event subdomains = List( domain_changed = True ) @on_trait_change( 'changed_structure' ) def _validate_subdomains( self ): for domain in self.subdomains: domain.validate() xdomains = List( domain_changed = True ) serialized_subdomains = List def _append_in_series( self, new_subdomain ): '''Link the new subdomain at the end of the series. ''' if self.serialized_subdomains: last_subdomain = self.serialized_subdomains[-1] last_subdomain.next_domain = new_subdomain new_subdomain.previous_domain = last_subdomain self.serialized_subdomains.append( new_subdomain ) nonempty_subdomains = Property( depends_on = 'changed_structure' ) @cached_property def _get_nonempty_subdomains( self ): d_list = [] for d in self.serialized_subdomains: if d.n_active_elems > 0: d_list.append( d ) return d_list n_dofs = Property def _get_n_dofs( self ): '''Return the total number of dofs in the domain. Use the last subdomain's: dof_offset + n_dofs ''' last_subdomain = self.serialized_subdomains[-1] return last_subdomain.dof_offset + last_subdomain.n_dofs dof_offset_arr = Property def _get_dof_offset_arr( self ): ''' Return array of the dof offsets from serialized subdomains ''' a = array( [domain.dof_offset for domain in self.serialized_subdomains] ) return a #---------------------------------------------------------------------------- # Methods for time stepper #---------------------------------------------------------------------------- dots = Property( depends_on = 'changed_structure' ) @cached_property def _get_dots( self ): return DOTSListEval( sdomain = self, dots_list = [ subdomain.dots for subdomain in self.nonempty_subdomains ] ) def new_scontext( self ): ''' Setup a new spatial context. ''' sctx = SContext() sctx.domain_list = self return sctx #----------------------------------------------------------------- # Response tracer background mesh #----------------------------------------------------------------- rt_bg_domain = Property( depends_on = 'changed_structure' ) @cached_property def _get_rt_bg_domain( self ): return RTraceDomainList( subfields = [ subdomain.rt_bg_domain for subdomain in self.nonempty_subdomains ], sd = self ) def redraw( self ): self.rt_bg_domain.redraw() #---------------------------------------------------------------------------- # Methods for extracting ranges from the domain #---------------------------------------------------------------------------- def get_lset_subdomain( self, lset_function ): '''@TODO - implement the subdomain selection method ''' raise NotImplementedError def get_boundary( self, side = None ): '''@todo: - implement the boundary extraction ''' raise NotImplementedError def get_interior( self ): '''@todo: - implement the boundary extraction ''' raise NotImplementedError def __iter__( self ): return iter( self.subdomains ) traits_view = View( Group( ), resizable = True, scrollable = True, )
[ "Axel@Axel-Pc" ]
Axel@Axel-Pc
588f61e7ddc589c30c4773fe81ada161b7fe2c69
51f887286aa3bd2c3dbe4c616ad306ce08976441
/pybind/slxos/v17r_2_00/ip/rtm_config/route/static_route_nh_vrf/__init__.py
04130225b089110a163e1218603f501b62d660c8
[ "Apache-2.0" ]
permissive
b2220333/pybind
a8c06460fd66a97a78c243bf144488eb88d7732a
44c467e71b2b425be63867aba6e6fa28b2cfe7fb
refs/heads/master
2020-03-18T09:09:29.574226
2018-04-03T20:09:50
2018-04-03T20:09:50
null
0
0
null
null
null
null
UTF-8
Python
false
false
15,541
py
from operator import attrgetter import pyangbind.lib.xpathhelper as xpathhelper from pyangbind.lib.yangtypes import RestrictedPrecisionDecimalType, RestrictedClassType, TypedListType from pyangbind.lib.yangtypes import YANGBool, YANGListType, YANGDynClass, ReferenceType from pyangbind.lib.base import PybindBase from decimal import Decimal from bitarray import bitarray import __builtin__ class static_route_nh_vrf(PybindBase): """ This class was auto-generated by the PythonClass plugin for PYANG from YANG module brocade-common-def - based on the path /ip/rtm-config/route/static-route-nh-vrf. Each member element of the container is represented as a class variable - with a specific YANG type. """ __slots__ = ('_pybind_generated_by', '_path_helper', '_yang_name', '_rest_name', '_extmethods', '__static_route_next_vrf_dest','__next_hop_vrf','__static_route_next_hop',) _yang_name = 'static-route-nh-vrf' _rest_name = 'static-route-nh-vrf' _pybind_generated_by = 'container' def __init__(self, *args, **kwargs): path_helper_ = kwargs.pop("path_helper", None) if path_helper_ is False: self._path_helper = False elif path_helper_ is not None and isinstance(path_helper_, xpathhelper.YANGPathHelper): self._path_helper = path_helper_ elif hasattr(self, "_parent"): path_helper_ = getattr(self._parent, "_path_helper", False) self._path_helper = path_helper_ else: self._path_helper = False extmethods = kwargs.pop("extmethods", None) if extmethods is False: self._extmethods = False elif extmethods is not None and isinstance(extmethods, dict): self._extmethods = extmethods elif hasattr(self, "_parent"): extmethods = getattr(self._parent, "_extmethods", None) self._extmethods = extmethods else: self._extmethods = False self.__static_route_next_vrf_dest = YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_dict={'pattern': u'(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])/(([0-9])|([1-2][0-9])|(3[0-2]))'}), is_leaf=True, yang_name="static-route-next-vrf-dest", rest_name="static-route-next-vrf-dest", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'A.B.C.D/L ;; Destination IP address'}}, is_keyval=True, namespace='urn:brocade.com:mgmt:brocade-rtm', defining_module='brocade-rtm', yang_type='inet:ipv4-prefix', is_config=True) self.__next_hop_vrf = YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_dict={'pattern': u'((([a-zA-Z0-9_]([a-zA-Z0-9\\-_]){0,61})?[a-zA-Z0-9]\\.)*([a-zA-Z0-9_]([a-zA-Z0-9\\-_]){0,61})?[a-zA-Z0-9]\\.?)|\\.', 'length': [u'1..32']}), is_leaf=True, yang_name="next-hop-vrf", rest_name="next-hop-vrf", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Next Hop Vrf Name', u'cli-expose-key-name': None}}, is_keyval=True, namespace='urn:brocade.com:mgmt:brocade-rtm', defining_module='brocade-rtm', yang_type='common-def:vrf-name', is_config=True) self.__static_route_next_hop = YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_dict={'pattern': u'(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(%[\\p{N}\\p{L}]+)?'}), is_leaf=True, yang_name="static-route-next-hop", rest_name="static-route-next-hop", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'A.B.C.D ;; Next hop IP address', u'cli-drop-node-name': None}}, is_keyval=True, namespace='urn:brocade.com:mgmt:brocade-rtm', defining_module='brocade-rtm', yang_type='inet:ipv4-address', is_config=True) load = kwargs.pop("load", None) if args: if len(args) > 1: raise TypeError("cannot create a YANG container with >1 argument") all_attr = True for e in self._pyangbind_elements: if not hasattr(args[0], e): all_attr = False break if not all_attr: raise ValueError("Supplied object did not have the correct attributes") for e in self._pyangbind_elements: nobj = getattr(args[0], e) if nobj._changed() is False: continue setmethod = getattr(self, "_set_%s" % e) if load is None: setmethod(getattr(args[0], e)) else: setmethod(getattr(args[0], e), load=load) def _path(self): if hasattr(self, "_parent"): return self._parent._path()+[self._yang_name] else: return [u'ip', u'rtm-config', u'route', u'static-route-nh-vrf'] def _rest_path(self): if hasattr(self, "_parent"): if self._rest_name: return self._parent._rest_path()+[self._rest_name] else: return self._parent._rest_path() else: return [u'ip', u'route', u'static-route-nh-vrf'] def _get_static_route_next_vrf_dest(self): """ Getter method for static_route_next_vrf_dest, mapped from YANG variable /ip/rtm_config/route/static_route_nh_vrf/static_route_next_vrf_dest (inet:ipv4-prefix) """ return self.__static_route_next_vrf_dest def _set_static_route_next_vrf_dest(self, v, load=False): """ Setter method for static_route_next_vrf_dest, mapped from YANG variable /ip/rtm_config/route/static_route_nh_vrf/static_route_next_vrf_dest (inet:ipv4-prefix) If this variable is read-only (config: false) in the source YANG file, then _set_static_route_next_vrf_dest is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_static_route_next_vrf_dest() directly. """ parent = getattr(self, "_parent", None) if parent is not None and load is False: raise AttributeError("Cannot set keys directly when" + " within an instantiated list") if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=unicode, restriction_dict={'pattern': u'(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])/(([0-9])|([1-2][0-9])|(3[0-2]))'}), is_leaf=True, yang_name="static-route-next-vrf-dest", rest_name="static-route-next-vrf-dest", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'A.B.C.D/L ;; Destination IP address'}}, is_keyval=True, namespace='urn:brocade.com:mgmt:brocade-rtm', defining_module='brocade-rtm', yang_type='inet:ipv4-prefix', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """static_route_next_vrf_dest must be of a type compatible with inet:ipv4-prefix""", 'defined-type': "inet:ipv4-prefix", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_dict={'pattern': u'(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])/(([0-9])|([1-2][0-9])|(3[0-2]))'}), is_leaf=True, yang_name="static-route-next-vrf-dest", rest_name="static-route-next-vrf-dest", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'A.B.C.D/L ;; Destination IP address'}}, is_keyval=True, namespace='urn:brocade.com:mgmt:brocade-rtm', defining_module='brocade-rtm', yang_type='inet:ipv4-prefix', is_config=True)""", }) self.__static_route_next_vrf_dest = t if hasattr(self, '_set'): self._set() def _unset_static_route_next_vrf_dest(self): self.__static_route_next_vrf_dest = YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_dict={'pattern': u'(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])/(([0-9])|([1-2][0-9])|(3[0-2]))'}), is_leaf=True, yang_name="static-route-next-vrf-dest", rest_name="static-route-next-vrf-dest", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'A.B.C.D/L ;; Destination IP address'}}, is_keyval=True, namespace='urn:brocade.com:mgmt:brocade-rtm', defining_module='brocade-rtm', yang_type='inet:ipv4-prefix', is_config=True) def _get_next_hop_vrf(self): """ Getter method for next_hop_vrf, mapped from YANG variable /ip/rtm_config/route/static_route_nh_vrf/next_hop_vrf (common-def:vrf-name) """ return self.__next_hop_vrf def _set_next_hop_vrf(self, v, load=False): """ Setter method for next_hop_vrf, mapped from YANG variable /ip/rtm_config/route/static_route_nh_vrf/next_hop_vrf (common-def:vrf-name) If this variable is read-only (config: false) in the source YANG file, then _set_next_hop_vrf is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_next_hop_vrf() directly. """ parent = getattr(self, "_parent", None) if parent is not None and load is False: raise AttributeError("Cannot set keys directly when" + " within an instantiated list") if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=unicode, restriction_dict={'pattern': u'((([a-zA-Z0-9_]([a-zA-Z0-9\\-_]){0,61})?[a-zA-Z0-9]\\.)*([a-zA-Z0-9_]([a-zA-Z0-9\\-_]){0,61})?[a-zA-Z0-9]\\.?)|\\.', 'length': [u'1..32']}), is_leaf=True, yang_name="next-hop-vrf", rest_name="next-hop-vrf", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Next Hop Vrf Name', u'cli-expose-key-name': None}}, is_keyval=True, namespace='urn:brocade.com:mgmt:brocade-rtm', defining_module='brocade-rtm', yang_type='common-def:vrf-name', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """next_hop_vrf must be of a type compatible with common-def:vrf-name""", 'defined-type': "common-def:vrf-name", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_dict={'pattern': u'((([a-zA-Z0-9_]([a-zA-Z0-9\\-_]){0,61})?[a-zA-Z0-9]\\.)*([a-zA-Z0-9_]([a-zA-Z0-9\\-_]){0,61})?[a-zA-Z0-9]\\.?)|\\.', 'length': [u'1..32']}), is_leaf=True, yang_name="next-hop-vrf", rest_name="next-hop-vrf", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Next Hop Vrf Name', u'cli-expose-key-name': None}}, is_keyval=True, namespace='urn:brocade.com:mgmt:brocade-rtm', defining_module='brocade-rtm', yang_type='common-def:vrf-name', is_config=True)""", }) self.__next_hop_vrf = t if hasattr(self, '_set'): self._set() def _unset_next_hop_vrf(self): self.__next_hop_vrf = YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_dict={'pattern': u'((([a-zA-Z0-9_]([a-zA-Z0-9\\-_]){0,61})?[a-zA-Z0-9]\\.)*([a-zA-Z0-9_]([a-zA-Z0-9\\-_]){0,61})?[a-zA-Z0-9]\\.?)|\\.', 'length': [u'1..32']}), is_leaf=True, yang_name="next-hop-vrf", rest_name="next-hop-vrf", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'Next Hop Vrf Name', u'cli-expose-key-name': None}}, is_keyval=True, namespace='urn:brocade.com:mgmt:brocade-rtm', defining_module='brocade-rtm', yang_type='common-def:vrf-name', is_config=True) def _get_static_route_next_hop(self): """ Getter method for static_route_next_hop, mapped from YANG variable /ip/rtm_config/route/static_route_nh_vrf/static_route_next_hop (inet:ipv4-address) """ return self.__static_route_next_hop def _set_static_route_next_hop(self, v, load=False): """ Setter method for static_route_next_hop, mapped from YANG variable /ip/rtm_config/route/static_route_nh_vrf/static_route_next_hop (inet:ipv4-address) If this variable is read-only (config: false) in the source YANG file, then _set_static_route_next_hop is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_static_route_next_hop() directly. """ parent = getattr(self, "_parent", None) if parent is not None and load is False: raise AttributeError("Cannot set keys directly when" + " within an instantiated list") if hasattr(v, "_utype"): v = v._utype(v) try: t = YANGDynClass(v,base=RestrictedClassType(base_type=unicode, restriction_dict={'pattern': u'(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(%[\\p{N}\\p{L}]+)?'}), is_leaf=True, yang_name="static-route-next-hop", rest_name="static-route-next-hop", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'A.B.C.D ;; Next hop IP address', u'cli-drop-node-name': None}}, is_keyval=True, namespace='urn:brocade.com:mgmt:brocade-rtm', defining_module='brocade-rtm', yang_type='inet:ipv4-address', is_config=True) except (TypeError, ValueError): raise ValueError({ 'error-string': """static_route_next_hop must be of a type compatible with inet:ipv4-address""", 'defined-type': "inet:ipv4-address", 'generated-type': """YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_dict={'pattern': u'(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(%[\\p{N}\\p{L}]+)?'}), is_leaf=True, yang_name="static-route-next-hop", rest_name="static-route-next-hop", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'A.B.C.D ;; Next hop IP address', u'cli-drop-node-name': None}}, is_keyval=True, namespace='urn:brocade.com:mgmt:brocade-rtm', defining_module='brocade-rtm', yang_type='inet:ipv4-address', is_config=True)""", }) self.__static_route_next_hop = t if hasattr(self, '_set'): self._set() def _unset_static_route_next_hop(self): self.__static_route_next_hop = YANGDynClass(base=RestrictedClassType(base_type=unicode, restriction_dict={'pattern': u'(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(%[\\p{N}\\p{L}]+)?'}), is_leaf=True, yang_name="static-route-next-hop", rest_name="static-route-next-hop", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u'A.B.C.D ;; Next hop IP address', u'cli-drop-node-name': None}}, is_keyval=True, namespace='urn:brocade.com:mgmt:brocade-rtm', defining_module='brocade-rtm', yang_type='inet:ipv4-address', is_config=True) static_route_next_vrf_dest = __builtin__.property(_get_static_route_next_vrf_dest, _set_static_route_next_vrf_dest) next_hop_vrf = __builtin__.property(_get_next_hop_vrf, _set_next_hop_vrf) static_route_next_hop = __builtin__.property(_get_static_route_next_hop, _set_static_route_next_hop) _pyangbind_elements = {'static_route_next_vrf_dest': static_route_next_vrf_dest, 'next_hop_vrf': next_hop_vrf, 'static_route_next_hop': static_route_next_hop, }
[ "badaniya@brocade.com" ]
badaniya@brocade.com
fa8815618592d941b28acb1eff9ab0cc10c18098
ee5040164beb866310c9cf23584002a342b451c0
/infra/libs-400rc2-20190512/examples/bmp280_simpletest.py
a54217ef21ce3baff21f2e95ebb304d914368ca5
[ "MIT" ]
permissive
jadudm/feather-isa
cf9a47c627408addbbc84581e5d6dff35a79773e
b7419e6698c3f64be4d8122656eb8124631ca859
refs/heads/master
2020-05-22T11:45:33.753573
2019-06-11T15:49:42
2019-06-11T15:49:42
186,329,428
1
0
null
null
null
null
UTF-8
Python
false
false
765
py
import time import board # import digitalio # For use with SPI import busio import adafruit_bmp280 # Create library object using our Bus I2C port i2c = busio.I2C(board.SCL, board.SDA) bmp280 = adafruit_bmp280.Adafruit_BMP280_I2C(i2c) # OR create library object using our Bus SPI port #spi = busio.SPI(board.SCK, board.MOSI, board.MISO) #bmp_cs = digitalio.DigitalInOut(board.D10) #bmp280 = adafruit_bmp280.Adafruit_BMP280_SPI(spi, bmp_cs) # change this to match the location's pressure (hPa) at sea level bmp280.sea_level_pressure = 1013.25 while True: print("\nTemperature: %0.1f C" % bmp280.temperature) print("Pressure: %0.1f hPa" % bmp280.pressure) print("Altitude = %0.2f meters" % bmp280.altitude) time.sleep(2)
[ "matt@jadud.com" ]
matt@jadud.com
efcfc1b4ef74378b813bd4f0312e79c71328f77a
3767e31f1c3a53d388cdc6fc1244bf980dfe039a
/pepysdiary/membership/forms.py
c846a8714a7a3e3ca2e7b01a686abf0ec14c79c8
[]
no_license
philgyford/pepysdiary
73749f389c226a35876e55e108a9f39e6afece5e
c6d99f39046eb5309f3292bfb4edb8b008f37aeb
refs/heads/main
2023-09-01T21:27:41.762431
2023-08-30T08:49:44
2023-08-30T08:49:44
7,092,491
16
6
null
2023-09-11T15:06:09
2012-12-10T11:55:11
Python
UTF-8
Python
false
false
7,794
py
# coding: utf-8 from django import forms from django.contrib.auth import password_validation from django.contrib.auth.forms import ( AuthenticationForm, PasswordResetForm, SetPasswordForm, ) from django.utils.translation import gettext_lazy as _ from hcaptcha.fields import hCaptchaField from pepysdiary.common.models import Config from pepysdiary.membership.models import Person from pepysdiary.membership.utilities import validate_person_name from .utilities import send_email #  Much of this based on django-registration. attrs_dict = {"class": "required form-control"} class LoginForm(AuthenticationForm): username = forms.EmailField( widget=forms.EmailInput(attrs=attrs_dict), max_length=254, label="Email address", error_messages={"invalid": "Please enter a valid email address."}, ) password = forms.CharField(widget=forms.PasswordInput(attrs=attrs_dict)) def clean(self): config = Config.objects.get_site_config() if config is not None: if config.allow_login is False: raise forms.ValidationError("Sorry, logging in is currently disabled.") return super().clean() class PersonEditForm(forms.ModelForm): class Meta: model = Person fields = ("email", "url") def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields["email"].widget = forms.TextInput(attrs=attrs_dict) self.fields["url"].widget = forms.TextInput(attrs=attrs_dict) class PasswordResetForm(PasswordResetForm): email = forms.EmailField( widget=forms.EmailInput(attrs=attrs_dict), max_length=254, label="Email address", error_messages={"invalid": "Please enter a valid email address."}, ) def send_mail( self, subject_template_name, email_template_name, context, from_email, to_email, html_email_template_name=None, ): """ Overriding the default so that we can use our custom send_email() method which includes the headers we want. """ send_email( to_email, from_email, subject_template_name, email_template_name, context ) class RegistrationForm(forms.Form): """ Form for registering a new user account. Validates that the requested name and email are not already in use, and requires the password to be entered twice to catch typos. Subclasses should feel free to add any additional validation they need, but should avoid defining a ``save()`` method -- the actual saving of collected user data is delegated to the active registration backend. """ name = forms.CharField( widget=forms.TextInput(attrs=attrs_dict), max_length=50, validators=[validate_person_name], required=True, label=_("Your name"), help_text="How people will know you. Can use spaces, eg “Samuel Pepys”.", ) email = forms.EmailField( required=True, label=_("Email address"), max_length=254, widget=forms.EmailInput(attrs=attrs_dict), help_text="This will not be visible to others.", ) password1 = forms.CharField( widget=forms.PasswordInput(attrs=attrs_dict, render_value=False), required=True, label=_("Password"), help_text="At least 8 characters.", ) password2 = forms.CharField( widget=forms.PasswordInput(attrs=attrs_dict, render_value=False), required=True, label=_("Repeat password"), ) url = forms.URLField( widget=forms.URLInput(attrs=attrs_dict), label=_("Personal URL"), max_length=255, required=False, help_text="Optional. eg, the web address of your blog, Facebook page, " "Twitter page, etc.", ) honeypot = forms.CharField( required=False, label=_( "If you enter anything in this field " "your registration will be treated as spam" ), ) def __init__(self, *args, **kwargs): """ We might need to add captcha and question/answer anti-spam fields, depending on our site config. """ super().__init__(*args, **kwargs) config = Config.objects.get_site_config() if config is not None: if config.use_registration_captcha is True: self.fields["captcha"] = hCaptchaField(label=_("Anti-spam test")) if ( config.use_registration_question is True and config.registration_question != "" and config.registration_answer != "" ): self.fields["answer"] = forms.CharField( widget=forms.TextInput(attrs=attrs_dict), max_length=255, required=True, label=_(config.registration_question), ) def clean_name(self): """ Validate that the name is alphanumeric and is not already in use. """ existing = Person.objects.filter(name__iexact=self.cleaned_data["name"]) if existing.exists(): raise forms.ValidationError(_("That name has already been used.")) else: return self.cleaned_data["name"] def clean_email(self): """ Validate that the email is not already in use. """ existing = Person.objects.filter(email__iexact=self.cleaned_data["email"]) if existing.exists(): raise forms.ValidationError(_("That email address has already been used.")) else: return self.cleaned_data["email"] def clean_honeypot(self): """Check that nothing's been entered into the honeypot.""" value = self.cleaned_data["honeypot"] if value: raise forms.ValidationError(self.fields["honeypot"].label) return value def clean_answer(self): """ Validate that the anti-spam question was answered successfully. """ config = Config.objects.get_site_config() if config is not None: if ( self.cleaned_data["answer"].lower() == config.registration_answer.lower() ): return self.cleaned_data["answer"] else: raise forms.ValidationError(_("Please try again.")) def clean_password1(self): """Check the password is OK by Django >=1.9's validators.""" password1 = self.cleaned_data["password1"] password_validation.validate_password(password1) return password1 def clean(self): """ Verifiy that the values entered into the two password fields match. Note that an error here will end up in ``non_field_errors()`` because it doesn't apply to a single field. """ config = Config.objects.get_site_config() if config is not None: if config.allow_registration is False: raise forms.ValidationError( "Sorry, new registrations aren't allowed at the moment." ) if "password1" in self.cleaned_data and "password2" in self.cleaned_data: if self.cleaned_data["password1"] != self.cleaned_data["password2"]: raise forms.ValidationError(_("The two password fields didn't match.")) return self.cleaned_data class SetPasswordForm(SetPasswordForm): new_password1 = forms.CharField( label="New password", widget=forms.PasswordInput(attrs=attrs_dict) ) new_password2 = forms.CharField( label="Repeat password", widget=forms.PasswordInput(attrs=attrs_dict) )
[ "phil@gyford.com" ]
phil@gyford.com
b5688b3f5c68c69b9550b071e5b97a20ee96c780
dac3a695b895c0170c350054fcc52d95f0daef5d
/data/level/level156.py
f86f3bcf8176051f74bd52d700e0355532dd646a
[ "Apache-2.0" ]
permissive
xingchen1106/match3-level-similarity
aad87de6e54c5bdc89cf4dac168559d11997d496
cc9b28b8741b41bea1273c8bc9b4d265d79a1dca
refs/heads/master
2021-05-22T02:48:09.444957
2019-07-19T09:19:09
2019-07-19T09:19:09
null
0
0
null
null
null
null
UTF-8
Python
false
false
11,611
py
data = { 'level_index': 156, 'move_count': 28, 'board_info': { (0, 0): { 'prev': (0, -1), 'next': (0, 1), 'base': (50, 1), 'cover': (64, 1), 'fall_point': (0, -1) }, (0, 1): { 'prev': (0, -1), 'next': (0, 1), 'base': (50, 1), 'cover': (64, 1) }, (0, 3): { 'prev': (0, -1), 'next': (0, 1), 'base': (5, 1), 'fall_point': (0, -1) }, (0, 4): { 'prev': (0, -1), 'next': (0, 1), 'base': (14, 1) }, (0, 5): { 'prev': (0, -1), 'next': (0, 1), 'base': (2, 1) }, (0, 7): { 'prev': (0, -1), 'next': (0, 1), 'base': (50, 1), 'cover': (64, 2) }, (0, 8): { 'prev': (0, -1), 'next': (0, 1), 'base': (50, 1), 'cover': (64, 2) }, (1, 0): { 'prev': (0, -1), 'next': (0, 1), 'base': (50, 1), 'cover': (64, 1), 'fall_point': (0, -1) }, (1, 1): { 'prev': (0, -1), 'next': (0, 1), 'base': (50, 1), 'cover': (64, 2) }, (1, 3): { 'prev': (0, -1), 'next': (0, 1), 'cover': (60, 1) }, (1, 4): { 'prev': (0, -1), 'next': (0, 1), 'cover': (60, 1) }, (1, 5): { 'prev': (0, -1), 'next': (0, 1), 'cover': (60, 1) }, (1, 7): { 'prev': (0, -1), 'next': (0, 1), 'base': (50, 1), 'cover': (64, 2) }, (1, 8): { 'prev': (0, -1), 'next': (0, 1), 'base': (50, 1), 'cover': (64, 2) }, (2, 0): { 'prev': (0, -1), 'next': (0, 1), 'cover': (64, 1), 'base': (1, 1), 'fall_point': (0, -1) }, (2, 1): { 'prev': (0, -1), 'next': (0, 1), 'cover': (64, 1), 'base': (1, 1) }, (2, 2): { 'prev': (0, -1), 'next': (0, 1), 'cover': (60, 2) }, (2, 3): { 'prev': (0, -1), 'next': (0, 1), 'cover': (60, 1) }, (2, 4): { 'prev': (0, -1), 'next': (0, 1), 'cover': (60, 1) }, (2, 5): { 'prev': (0, -1), 'next': (0, 1), 'cover': (60, 1) }, (2, 6): { 'prev': (0, -1), 'next': (0, 1), 'cover': (60, 2) }, (2, 7): { 'prev': (0, -1), 'next': (0, 1), 'cover': (64, 2), 'base': (2, 1) }, (2, 8): { 'prev': (0, -1), 'next': (0, 1), 'base': (50, 1), 'cover': (64, 2) }, (3, 0): { 'prev': (0, -1), 'next': (0, 1), 'base': (1, 1), 'fall_point': (0, -1) }, (3, 1): { 'prev': (0, -1), 'next': (0, 1), 'base': (5, 1) }, (3, 2): { 'prev': (0, -1), 'next': (0, 1), 'base': (1, 1) }, (3, 3): { 'prev': (0, -1), 'next': (0, 1), 'base': (4, 1) }, (3, 4): { 'prev': (0, -1), 'next': (0, 1), 'base': (1, 1) }, (3, 5): { 'prev': (0, -1), 'next': (0, 1), 'base': (1, 1) }, (3, 6): { 'prev': (0, -1), 'next': (0, 1), 'base': (66, 1) }, (3, 7): { 'prev': (0, -1), 'next': (0, 1), 'cover': (60, 1) }, (3, 8): { 'prev': (0, -1), 'next': (0, 1), 'cover': (60, 2) }, (4, 0): { 'prev': (0, -1), 'next': (0, 1), 'base': (5, 1), 'fall_point': (0, -1) }, (4, 1): { 'prev': (0, -1), 'next': (0, 1), 'base': (2, 1) }, (4, 2): { 'prev': (0, -1), 'next': (0, 1), 'base': (2, 1) }, (4, 3): { 'prev': (0, -1), 'next': (0, 1), 'base': (5, 1) }, (4, 4): { 'prev': (0, -1), 'next': (0, 1), 'base': (4, 1) }, (4, 5): { 'prev': (0, -1), 'next': (0, 1), 'base': (66, 1) }, (4, 6): { 'prev': (0, -1), 'next': (0, 1), 'cover': (60, 1) }, (4, 7): { 'prev': (0, -1), 'next': (0, 1), 'cover': (60, 2) }, (4, 8): { 'prev': (0, -1), 'next': (0, 1), 'cover': (60, 1) }, (5, 0): { 'prev': (0, -1), 'next': (0, 1), 'base': (5, 1), 'fall_point': (0, -1) }, (5, 1): { 'prev': (0, -1), 'next': (0, 1), 'base': (2, 1) }, (5, 2): { 'prev': (0, -1), 'next': (0, 1), 'base': (4, 1) }, (5, 4): { 'prev': (0, -1), 'next': (0, 1), 'base': (4, 1) }, (5, 5): { 'prev': (0, -1), 'next': (0, 1), 'base': (66, 1) }, (5, 6): { 'prev': (0, -1), 'next': (0, 1), 'cover': (60, 1) }, (5, 7): { 'prev': (0, -1), 'next': (0, 1), 'cover': (60, 1) }, (5, 8): { 'prev': (0, -1), 'next': (0, 1), 'cover': (60, 2) }, (6, 0): { 'prev': (0, -1), 'next': (0, 1), 'base': (4, 1), 'fall_point': (0, -1) }, (6, 1): { 'prev': (0, -1), 'next': (0, 1), 'base': (5, 1) }, (6, 2): { 'prev': (0, -1), 'next': (0, 1), 'base': (5, 1) }, (6, 3): { 'prev': (0, -1), 'next': (0, 1), 'base': (2, 1) }, (6, 4): { 'prev': (0, -1), 'next': (0, 1), 'base': (1, 1) }, (6, 5): { 'prev': (0, -1), 'next': (0, 1), 'base': (66, 1) }, (6, 6): { 'prev': (0, -1), 'next': (0, 1), 'cover': (60, 1) }, (6, 7): { 'prev': (0, -1), 'next': (0, 1), 'cover': (60, 2) }, (6, 8): { 'prev': (0, -1), 'next': (0, 1), 'cover': (60, 1) }, (7, 0): { 'prev': (0, -1), 'next': (0, 1), 'base': (4, 1), 'fall_point': (0, -1) }, (7, 1): { 'prev': (0, -1), 'next': (0, 1), 'base': (1, 1) }, (7, 2): { 'prev': (0, -1), 'next': (0, 1), 'base': (6, 1) }, (7, 3): { 'prev': (0, -1), 'next': (0, 1), 'base': (6, 1) }, (7, 4): { 'prev': (0, -1), 'next': (0, 1), 'base': (2, 1) }, (7, 5): { 'prev': (0, -1), 'next': (0, 1), 'base': (5, 1) }, (7, 6): { 'prev': (0, -1), 'next': (0, 1), 'base': (66, 1) }, (7, 7): { 'prev': (0, -1), 'next': (0, 1), 'cover': (60, 1) }, (7, 8): { 'prev': (0, -1), 'next': (0, 1), 'cover': (60, 2) }, (8, 0): { 'prev': (0, -1), 'next': (0, 1), 'cover': (64, 1), 'base': (2, 1), 'fall_point': (0, -1) }, (8, 1): { 'prev': (0, -1), 'next': (0, 1), 'cover': (64, 1), 'base': (6, 1) }, (8, 2): { 'prev': (0, -1), 'next': (0, 1), 'cover': (60, 2) }, (8, 3): { 'prev': (0, -1), 'next': (0, 1), 'cover': (60, 1) }, (8, 4): { 'prev': (0, -1), 'next': (0, 1), 'cover': (60, 1) }, (8, 5): { 'prev': (0, -1), 'next': (0, 1), 'cover': (60, 1) }, (8, 6): { 'prev': (0, -1), 'next': (0, 1), 'cover': (60, 2) }, (8, 7): { 'prev': (0, -1), 'next': (0, 1), 'cover': (64, 2), 'base': (1, 1) }, (8, 8): { 'prev': (0, -1), 'next': (0, 1), 'base': (50, 1), 'cover': (64, 2) }, (9, 0): { 'prev': (0, -1), 'next': (0, 1), 'base': (50, 1), 'cover': (64, 1), 'fall_point': (0, -1) }, (9, 1): { 'prev': (0, -1), 'next': (0, 1), 'base': (50, 1), 'cover': (64, 2) }, (9, 3): { 'prev': (0, -1), 'next': (0, 1), 'cover': (60, 1) }, (9, 4): { 'prev': (0, -1), 'next': (0, 1), 'cover': (60, 1) }, (9, 5): { 'prev': (0, -1), 'next': (0, 1), 'cover': (60, 1) }, (9, 7): { 'prev': (0, -1), 'next': (0, 1), 'base': (50, 1), 'cover': (64, 2) }, (9, 8): { 'prev': (0, -1), 'next': (0, 1), 'base': (50, 1), 'cover': (64, 2) }, (10, 0): { 'prev': (0, -1), 'next': (0, 1), 'base': (50, 1), 'cover': (64, 1), 'fall_point': (0, -1) }, (10, 1): { 'prev': (0, -1), 'next': (0, 1), 'base': (50, 1), 'cover': (64, 1) }, (10, 3): { 'prev': (0, -1), 'next': (0, 1), 'base': (1, 1), 'fall_point': (0, -1) }, (10, 4): { 'prev': (0, -1), 'next': (0, 1), 'base': (14, 1) }, (10, 5): { 'prev': (0, -1), 'next': (0, 1), 'base': (2, 1) }, (10, 7): { 'prev': (0, -1), 'next': (0, 1), 'base': (50, 1), 'cover': (64, 2) }, (10, 8): { 'prev': (0, -1), 'next': (0, 1), 'base': (50, 1), 'cover': (64, 2) } }, 'trans_info': { (0, 0): { 50: 18, 60: 29 } } }
[ "salild1011@gmail.com" ]
salild1011@gmail.com
1f441384521bb711ae6fdce8fef88f9fae846dec
891371ebcb696b91df1d00f98cb595608b580d34
/documents/migrations/0015_requestarchive_approved_by.py
80acd3afe27f687758cfbe9bb0993586f1b4c45a
[]
no_license
NiiColeman/law-firm
867df413e9ca30c57afad9d2743fe19ab96ba586
f41ee5ac88d3f640dce720c90cbfefb93a267400
refs/heads/master
2022-09-23T22:52:25.312903
2020-06-01T14:30:24
2020-06-01T14:30:24
241,650,134
0
0
null
null
null
null
UTF-8
Python
false
false
418
py
# Generated by Django 2.2.6 on 2020-02-18 11:59 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('documents', '0014_documentarchive_location'), ] operations = [ migrations.AddField( model_name='requestarchive', name='approved_by', field=models.CharField(default='', max_length=250), ), ]
[ "nii.cole@outlook.com" ]
nii.cole@outlook.com
012a8170f648836e33bbe603989e95ffb9215a03
3f13885fdb0649374d866d24a43f86ccc6b4c782
/apps/tools/views/qizhi.py
ca388f32f00be53c879448e92b8d76df70c1fcbd
[]
no_license
linkexf/oneops
426b271c00c5b4b4c55d1d91bf42030dab29623a
64a9c7fd949b6220234a276614ab6555dc8cc17c
refs/heads/master
2020-12-10T04:45:55.681731
2019-11-28T09:02:30
2019-11-28T09:02:30
null
0
0
null
null
null
null
UTF-8
Python
false
false
442
py
from django.views.generic import TemplateView from django.contrib.auth.mixins import LoginRequiredMixin class QiZhiCreateHostView(LoginRequiredMixin, TemplateView): template_name = "tools/qizhi_create_host.html" def get(self, request, **kwargs): context = { 'path1': '小工具', 'path2': '堡垒机录入' } context.update(**kwargs) return self.render_to_response(context)
[ "andykaiyu@163.com" ]
andykaiyu@163.com
f1e366f27ad1885260c92fa6e048d493ea794f29
597b82737635e845fd5360e191f323669af1b2ae
/08_full_django/products/products/urls.py
6e148c5162f8e91d1ea8758a9a4ef402749fc16d
[]
no_license
twknab/learning-python
1bd10497fbbe181a26f2070c147cb2fed6955178
75b76b2a607439aa2d8db675738adf8d3b8644df
refs/heads/master
2021-08-08T08:50:04.337490
2017-11-10T00:28:45
2017-11-10T00:28:45
89,213,845
0
1
null
null
null
null
UTF-8
Python
false
false
326
py
"""products URL Configuration Sets up URL configuration for each application in the `products` project. Current Applications: -`products`: a simple app to play with Django Models and creating and retrieving data. """ from django.conf.urls import url, include urlpatterns = [ url(r'^', include("apps.products.urls")), ]
[ "natureminded@users.noreply.github.com" ]
natureminded@users.noreply.github.com
a5d645e662c818a20711511e5c0bbe7dfcc7e768
d93586a23b50027c766be448072e5c06ebd05ffc
/seq2seq/dependency/tf_models/models/official/r1/transformer/dataset.py
b5c607bf78f00095741c0bb5af23110c4bd7babe
[ "Apache-2.0" ]
permissive
peixiang6134/tf_bot_examples
9bd3a63bf5e699e49455d3beb91c4995f47d781a
b4e8eb6a555b3eeeb423ad928a9009c41b4e5950
refs/heads/master
2021-07-09T02:29:26.303639
2020-02-22T08:58:33
2020-02-22T08:58:33
238,680,285
1
1
null
2021-03-31T21:54:12
2020-02-06T12:08:36
Python
UTF-8
Python
false
false
11,409
py
# Copyright 2018 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Input pipeline for the transformer model to read, filter, and batch examples. Two things to note in the pipeline: 1. Batching scheme The examples encoded in the TFRecord files contain data in the format: {"inputs": [variable length array of integers], "targets": [variable length array of integers]} Where integers in the arrays refer to tokens in the English and German vocab file (named `vocab.ende.32768`). Prior to batching, elements in the dataset are grouped by length (max between "inputs" and "targets" length). Each group is then batched such that: group_batch_size * length <= batch_size. Another way to view batch_size is the maximum number of tokens in each batch. Once batched, each element in the dataset will have the shape: {"inputs": [group_batch_size, padded_input_length], "targets": [group_batch_size, padded_target_length]} Lengths are padded to the longest "inputs" or "targets" sequence in the batch (padded_input_length and padded_target_length can be different). This batching scheme decreases the fraction of padding tokens per training batch, thus improving the training speed significantly. 2. Shuffling While training, the dataset is shuffled in two places in the code. The first is the list of training files. Second, while reading records using `parallel_interleave`, the `sloppy` argument is used to generate randomness in the order of the examples. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function import math import os import tensorflow as tf from dependency.tf_models.models.official.utils.misc import model_helpers # Buffer size for reading records from a TFRecord file. Each training file is # 7.2 MB, so 8 MB allows an entire file to be kept in memory. _READ_RECORD_BUFFER = 8 * 1000 * 1000 # Example grouping constants. Defines length boundaries for each group. # These values are the defaults used in Tensor2Tensor. _MIN_BOUNDARY = 8 _BOUNDARY_SCALE = 1.1 def _load_records(filename): """Read file and return a dataset of tf.Examples.""" return tf.data.TFRecordDataset(filename, buffer_size=_READ_RECORD_BUFFER) def _parse_example(serialized_example): """Return inputs and targets Tensors from a serialized tf.Example.""" data_fields = { "inputs": tf.VarLenFeature(tf.int64), "targets": tf.VarLenFeature(tf.int64) } parsed = tf.parse_single_example(serialized_example, data_fields) inputs = tf.sparse_tensor_to_dense(parsed["inputs"]) targets = tf.sparse_tensor_to_dense(parsed["targets"]) return inputs, targets def _filter_max_length(example, max_length=256): """Indicates whether the example's length is lower than the maximum length.""" return tf.logical_and(tf.size(example[0]) <= max_length, tf.size(example[1]) <= max_length) def _get_example_length(example): """Returns the maximum length between the example inputs and targets.""" length = tf.maximum(tf.shape(example[0])[0], tf.shape(example[1])[0]) return length def _create_min_max_boundaries( max_length, min_boundary=_MIN_BOUNDARY, boundary_scale=_BOUNDARY_SCALE): """Create min and max boundary lists up to max_length. For example, when max_length=24, min_boundary=4 and boundary_scale=2, the returned values will be: buckets_min = [0, 4, 8, 16, 24] buckets_max = [4, 8, 16, 24, 25] Args: max_length: The maximum length of example in dataset. min_boundary: Minimum length in boundary. boundary_scale: Amount to scale consecutive boundaries in the list. Returns: min and max boundary lists """ # Create bucket boundaries list by scaling the previous boundary or adding 1 # (to ensure increasing boundary sizes). bucket_boundaries = [] x = min_boundary while x < max_length: bucket_boundaries.append(x) x = max(x + 1, int(x * boundary_scale)) # Create min and max boundary lists from the initial list. buckets_min = [0] + bucket_boundaries buckets_max = bucket_boundaries + [max_length + 1] return buckets_min, buckets_max def _batch_examples(dataset, batch_size, max_length): """Group examples by similar lengths, and return batched dataset. Each batch of similar-length examples are padded to the same length, and may have different number of elements in each batch, such that: group_batch_size * padded_length <= batch_size. This decreases the number of padding tokens per batch, which improves the training speed. Args: dataset: Dataset of unbatched examples. batch_size: Max number of tokens per batch of examples. max_length: Max number of tokens in an example input or target sequence. Returns: Dataset of batched examples with similar lengths. """ # Get min and max boundary lists for each example. These are used to calculate # the `bucket_id`, which is the index at which: # buckets_min[bucket_id] <= len(example) < buckets_max[bucket_id] # Note that using both min and max lists improves the performance. buckets_min, buckets_max = _create_min_max_boundaries(max_length) # Create list of batch sizes for each bucket_id, so that # bucket_batch_size[bucket_id] * buckets_max[bucket_id] <= batch_size bucket_batch_sizes = [batch_size // x for x in buckets_max] # bucket_id will be a tensor, so convert this list to a tensor as well. bucket_batch_sizes = tf.constant(bucket_batch_sizes, dtype=tf.int64) def example_to_bucket_id(example_input, example_target): """Return int64 bucket id for this example, calculated based on length.""" seq_length = _get_example_length((example_input, example_target)) # TODO: investigate whether removing code branching improves performance. conditions_c = tf.logical_and( tf.less_equal(buckets_min, seq_length), tf.less(seq_length, buckets_max)) bucket_id = tf.reduce_min(tf.where(conditions_c)) return bucket_id def window_size_fn(bucket_id): """Return number of examples to be grouped when given a bucket id.""" return bucket_batch_sizes[bucket_id] def batching_fn(bucket_id, grouped_dataset): """Batch and add padding to a dataset of elements with similar lengths.""" bucket_batch_size = window_size_fn(bucket_id) # Batch the dataset and add padding so that all input sequences in the # examples have the same length, and all target sequences have the same # lengths as well. Resulting lengths of inputs and targets can differ. return grouped_dataset.padded_batch(bucket_batch_size, ([None], [None])) return dataset.apply(tf.data.experimental.group_by_window( key_func=example_to_bucket_id, reduce_func=batching_fn, window_size=None, window_size_func=window_size_fn)) def _read_and_batch_from_files( file_pattern, batch_size, max_length, num_parallel_calls, shuffle, repeat, static_batch=False): """Create dataset where each item is a dict of "inputs" and "targets". Args: file_pattern: String used to match the input TFRecord files. batch_size: Maximum number of tokens per batch of examples max_length: Maximum number of tokens per example num_parallel_calls: Number of cpu cores for parallel input processing. shuffle: If true, randomizes order of elements. repeat: Number of times to repeat the dataset. If None, the dataset is repeated forever. static_batch: Whether the batches in the dataset should have static shapes. If True, the input is batched so that every batch has the shape [batch_size // max_length, max_length]. If False, the input is grouped by length, and batched so that batches may have different shapes [N, M], where: N * M <= batch_size M <= max_length In general, this setting should be False. Dynamic shapes allow the inputs to be grouped so that the number of padding tokens is minimized, and helps model training. In cases where the input shape must be static (e.g. running on TPU), this setting should be set to True. Returns: tf.data.Dataset object containing examples loaded from the files. """ dataset = tf.data.Dataset.list_files(file_pattern, shuffle=shuffle) # Read files and interleave results. When training, the order of the examples # will be non-deterministic. dataset = dataset.apply( tf.data.experimental.parallel_interleave( _load_records, sloppy=shuffle, cycle_length=num_parallel_calls)) # Parse each tf.Example into a dictionary # TODO: Look into prefetch_input_elements for performance optimization. dataset = dataset.map(_parse_example, num_parallel_calls=num_parallel_calls) # Remove examples where the input or target length exceeds the maximum length, dataset = dataset.filter(lambda x, y: _filter_max_length((x, y), max_length)) if static_batch: dataset = dataset.padded_batch( batch_size // max_length, ([max_length], [max_length]), drop_remainder=True) else: # Group and batch such that each batch has examples of similar length. dataset = _batch_examples(dataset, batch_size, max_length) dataset = dataset.repeat(repeat) # Prefetch the next element to improve speed of input pipeline. dataset = dataset.prefetch(buffer_size=tf.data.experimental.AUTOTUNE) return dataset def _generate_synthetic_data(params): """Create synthetic data based on the parameter batch size.""" batch = length = int(math.sqrt(params["batch_size"])) return model_helpers.generate_synthetic_data( input_shape=tf.TensorShape([batch, length]), input_value=1, input_dtype=tf.int32, label_shape=tf.TensorShape([batch, length]), label_value=1, label_dtype=tf.int32, ) def train_input_fn(params): """Load and return dataset of batched examples for use during training.""" file_pattern = os.path.join(params["data_dir"] or "", "*train*") if params["use_synthetic_data"]: return _generate_synthetic_data(params) return _read_and_batch_from_files( file_pattern, params["batch_size"], params["max_length"], params["num_parallel_calls"], shuffle=True, repeat=params["repeat_dataset"], static_batch=params["static_batch"]) def eval_input_fn(params): """Load and return dataset of batched examples for use during evaluation.""" file_pattern = os.path.join(params["data_dir"] or "", "*dev*") if params["use_synthetic_data"]: return _generate_synthetic_data(params) return _read_and_batch_from_files( file_pattern, params["batch_size"], params["max_length"], params["num_parallel_calls"], shuffle=False, repeat=1, static_batch=params["static_batch"])
[ "1316802995@qq.com" ]
1316802995@qq.com
69db29490d01dc933aed028527cca2bbcb2a80a9
0d0afd1dce972b4748ce8faccd992c019794ad9e
/integra/seguranca/models/sale_defeito_os.py
484544383c69811435d08f76d682a553b9c6d529
[]
no_license
danimaribeiro/odoo-erp
e2ca2cfe3629fbedf413e85f7c3c0453fd16941e
d12577bf7f5266b571cbedeb930720d653320e96
refs/heads/master
2020-01-23T21:32:16.149716
2016-11-05T15:35:40
2016-11-05T15:35:40
67,892,809
0
1
null
null
null
null
UTF-8
Python
false
false
699
py
# -*- coding: utf-8 -*- #from __future__ import division, print_function, unicode_literals from osv import osv, orm, fields class sale_defeito_os(osv.Model): _description = u'Defeito da OS' _name = 'sale.defeito.os' _rec_name = 'nome' _order = 'id' def _codigo(self, cr, uid, ids, nome_campo, args=None, context={}): res = {} for os_obj in self.browse(cr, uid, ids): res[os_obj.id] = str(os_obj.id).zfill(4) return res _columns = { 'codigo': fields.function(_codigo, type='char', method=True, string=u'Código', size=20, store=False, select=True), 'nome': fields.char(u'Nome', size=180), } sale_defeito_os()
[ "danimaribeiro@gmail.com" ]
danimaribeiro@gmail.com
117788556929425f430585c961bb4ff7d6162fee
8d753bb8f19b5b1f526b0688d3cb199b396ed843
/osp_sai_2.1.8/system/apps/web/api/web_sessions.py
146b4f0981fe26b5dc00f9568af90c121d95faf4
[]
no_license
bonald/vim_cfg
f166e5ff650db9fa40b564d05dc5103552184db8
2fee6115caec25fd040188dda0cb922bfca1a55f
refs/heads/master
2023-01-23T05:33:00.416311
2020-11-19T02:09:18
2020-11-19T02:09:18
null
0
0
null
null
null
null
UTF-8
Python
false
false
2,073
py
#!/usr/bin/python #-*- coding: utf-8 -*- from flask import url_for import os import base from vcl import vcmd import types def get(file_type): """ API: GET: Retrun: { sess: [ {id: string, user: string, expire: string, client: string,}, ... ], } """ # get web sessions obj = {'error': False, 'err_code': 0, 'err_reason': ''} res = [] # get cmd lines cmd = 'cdbctl read/cdb/app/login/web | grep web'; lines = vcmd.get_lines(cmd) if not lines: return res # make dict for line in lines: key = vcmd.cmd_get_token(line, "key") user = vcmd.cmd_get_token(line, "user") deccmd = 'fnconvert -c decoding -m "%s"'%(user) decuser = vcmd.get_lines(deccmd) ipaddr = vcmd.cmd_get_token(line, "ipaddr") etime = base.relative_time.get(int(vcmd.cmd_get_token(line, "expire_time"))) res.append({ 'id': key, 'user': decuser[0], 'expire': etime, 'client': ipaddr, }); obj['sess'] = res return obj def delete(req_data): """ API: DELETE: { file_arr: [ { 'id': string, }, ... ... ], } Retrun: { error: bool, err_code: int, err_reason: string } """ _err_reason = [ '', # err_code: 0 'bad request', # err_code: 1 'delete failed', # err_code: 2 ] obj = {'error': False, 'err_code': 0, 'err_reason': ''} # param check sess_arr = req_data.get('sess_arr') if not type(sess_arr) is types.ListType: # bad request obj['error'] = True obj['err_code'] = 1 obj['err_reason'] = _err_reason[1] return obj # make cmd for sid in sess_arr: exec_str = 'cdbctl delete/cdb/app/login/%s' %(str(sid)); status, output = vcmd.get_status_lines(exec_str); return obj
[ "zhwwan@gmail.com" ]
zhwwan@gmail.com
3c2b44b45e010b4843d1e27a86696ab4d83f9802
13a13b4f93ef6664dcf610a556c53a1f6c3c8bc4
/ques9.py
d41b7a7f7fccd0c92d0dca3ec26dbf55f564b6f0
[]
no_license
BhagyashreeKarale/more-exercise
54ea9f6fa2f4f007278631535362959446980ea9
c0f34d345d2e5bef19f872861fafb3f8a0233e43
refs/heads/main
2023-08-02T14:49:44.403733
2021-09-11T19:07:51
2021-09-11T19:07:51
405,454,804
0
0
null
null
null
null
UTF-8
Python
false
false
2,176
py
# Harshad numbers aise number hote hain jo apni digits ke sum se dhang se divide hote hain. # Dhang se divide hone ka matlab ki remainder 0 aata hai. # Jaise 42 ek Harshad number hai kyunki 4 + 2 = 6 aur 42 ko 6 se divide kar ke remainder aata hai # Aise hi 18, 21 aur 24 bhi harshad number hai # kyunki 1 + 8 = 9 aur 18 ko 9 se divide kar ke remainder 0 hai. # Aise hi 1, 2, 3, 4, 5, 6, 7, 8, 9 saare harshad number hain # kyunki inki digits ka sum khud yeh number hain aur yeh apne aap se divide ho jate hain. # Ek number ke digits nikalne ka code yeh hai: # x = 42 # x_digits = list(str(x)) # n=len(x_digits) # sum=0 # for i in x_digits: # sum=sum+int(i) # if x % sum == 0: # print("It is an Harshad number") # Yahan humne list function mein x ko string mein type cast kar ke de diya. # Toh ab yeh har 42 ke alag alag number se list bana dega. # x_digits mein ["4", "2"] list hogi. # Iss list mein saare digits string ki form mein hogi, # aap unko firse integer mein convert kar sakte ho # Ek function likho is_harshad_number jo ek number parameter ki tarah le # aur fir agar woh number harshad number hai toh ek boolean (True agar harshad number hai, # False agar nahi hai toh) return kare. # Fir iss function ka use kar ke 1 se 1000 ke beech mein saare harshad number print karo. # i=1 # while i <= 1000: # x_digits = list(str(i)) # n=len(x_digits) # sum=0 # for i in x_digits: # sum=sum+int(i) # if i % sum == 0: # print("It is an Harshad number") # i=i+1 # i=1 # while i <= 1000: # x_digits = list(str(i)) # n=len(x_digits) # sum=0 # for k in x_digits: # sum=sum+int(k) # if i % sum == 0: # print(i,"Is an Harshad number") # i=i+1 # else: # print(i,"Is not an Harshad Number") # i=i+1 ############################################################################################### #printing only harshad numbers i=1 while i <= 1000: x_digits = list(str(i)) n=len(x_digits) sum=0 for k in x_digits: sum=sum+int(k) if i % sum == 0: print(i) i=i+1 print("These are the harshad numbers from 1-1000")
[ "noreply@github.com" ]
BhagyashreeKarale.noreply@github.com
3b907f1a9e78e5f2499489ec4a96db16c6a67c09
45b8e141f762b95edec36ce40809ea4b89e3d287
/mahkalastore/mahkalastore/settings.py
5838b8a0373f9a932a716f814882743e16317924
[]
no_license
nimanoori22/mys
73d7a0ad141e1c6208e776a15d079a2599c46a7f
0122586a4d69f80219ad25e42ef89f3052f5cb81
refs/heads/master
2022-11-28T22:24:44.947703
2020-08-13T14:52:19
2020-08-13T14:52:19
279,652,903
0
0
null
null
null
null
UTF-8
Python
false
false
3,679
py
""" Django settings for mahkalastore project. Generated by 'django-admin startproject' using Django 3.0.8. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! from mahkalastore import secrets SECRET_KEY = secrets.seckey # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'product.apps.ProductConfig', 'mptt', 'ckeditor', 'home', 'user', 'order', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'mahkalastore.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'mahkalastore.wsgi.application' # Database # https://docs.djangoproject.com/en/3.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Internationalization # https://docs.djangoproject.com/en/3.0/topics/i18n/ LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/3.0/howto/static-files/ STATIC_URL = '/static/' MEDIA_URL = '/uploads/' MEDIA_ROOT = os.path.join(BASE_DIR, 'uploads') #......... SITE_ID = 1 #################################### ## CKEDITOR CONFIGURATION ## #################################### CKEDITOR_JQUERY_URL = 'https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js' CKEDITOR_UPLOAD_PATH = 'images/' CKEDITOR_IMAGE_BACKEND = "pillow" CKEDITOR_CONFIGS = { 'default': { 'toolbar': None, }, } ###################################
[ "nimanoori000@gmail.com" ]
nimanoori000@gmail.com
f3d59c59e7e9b0a08ba9fcd1d5b3cb89a0914baa
39a1d46fdf2acb22759774a027a09aa9d10103ba
/tests/layer_tests/onnx_tests/test_cumsum.py
b49f00f887c3ffb66b20cf937597ece1c21884fa
[ "Apache-2.0" ]
permissive
mashoujiang/openvino
32c9c325ffe44f93a15e87305affd6099d40f3bc
bc3642538190a622265560be6d88096a18d8a842
refs/heads/master
2023-07-28T19:39:36.803623
2021-07-16T15:55:05
2021-07-16T15:55:05
355,786,209
1
3
Apache-2.0
2021-06-30T01:32:47
2021-04-08T06:22:16
C++
UTF-8
Python
false
false
9,264
py
# Copyright (C) 2018-2021 Intel Corporation # SPDX-License-Identifier: Apache-2.0 import numpy as np import pytest from common.layer_test_class import check_ir_version from common.onnx_layer_test_class import OnnxRuntimeLayerTest from unit_tests.utils.graph import build_graph def cumsum(a, axis=None, exclusive=False, reverse=False): if reverse: a = np.flip(a, axis) res = np.cumsum(a, axis=axis) if exclusive: res -= a if reverse: res = np.flip(res, axis) return res class TestCumSum(OnnxRuntimeLayerTest): def create_net(self, shape, ir_version, axis=None, reverse=None, exclusive=None): """ ONNX net IR net Input->CumSum->Output => Input->CumSum """ # # Create ONNX model # import onnx from onnx import helper from onnx import TensorProto input = helper.make_tensor_value_info('input', TensorProto.FLOAT, shape) output = helper.make_tensor_value_info('output', TensorProto.FLOAT, shape) nodes = [] inputs = ['input'] if axis is not None: node_axis_def = onnx.helper.make_node( 'Constant', inputs=[], outputs=['axis'], value=helper.make_tensor( name='const_tensor', data_type=TensorProto.INT64, dims=[], vals=[axis], ), ) nodes.append(node_axis_def) inputs.append('axis') args = dict() if exclusive is not None: args['exclusive'] = exclusive if reverse is not None: args['reverse'] = reverse node_def = onnx.helper.make_node( 'CumSum', inputs=inputs, outputs=['output'], **args ) nodes.append(node_def) # Create the graph (GraphProto) graph_def = helper.make_graph( nodes, 'test_model', [input], [output], ) # Create the model (ModelProto) onnx_net = helper.make_model(graph_def, producer_name='test_model') onnx.checker.check_model(onnx_net) # # Create reference IR net # ref_net = None if check_ir_version(10, None, ir_version): nodes_attributes = { 'input': {'kind': 'op', 'type': 'Parameter'}, 'input_data': {'shape': shape, 'kind': 'data'}, 'node': {'kind': 'op', 'type': 'CumSum'}, 'node_data': {'shape': shape, 'kind': 'data'}, 'result': {'kind': 'op', 'type': 'Result'} } if exclusive is not None: nodes_attributes['node']['exclusive'] = exclusive if reverse is not None: nodes_attributes['node']['reverse'] = reverse edges = [('input', 'input_data'), ('input_data', 'node'), ('node', 'node_data'), ('node_data', 'result') ] if axis is not None: nodes_attributes.update({ 'input_axis_data': {'kind': 'data', 'value': [axis]}, 'axis': {'kind': 'op', 'type': 'Const'}, 'axis_data': {'shape': [], 'kind': 'data'}}) edges.extend([('input_axis_data', 'axis'), ('axis', 'axis_data'), ('axis_data', 'node')]) ref_net = build_graph(nodes_attributes, edges) return onnx_net, ref_net def create_net_const(self, shape, precision, ir_version, axis=None, reverse=None, exclusive=None): """ ONNX net IR net Input->Concat(+cumsum const)->Output => Input->Concat(+const) """ # # Create ONNX model # import onnx from onnx import helper from onnx import TensorProto import numpy as np concat_axis = 0 output_shape = shape.copy() output_shape[concat_axis] *= 2 input = helper.make_tensor_value_info('input', TensorProto.FLOAT, shape) output = helper.make_tensor_value_info('output', TensorProto.FLOAT, output_shape) constant = np.random.randn(*shape).astype(np.float) node_const_def = onnx.helper.make_node( 'Constant', inputs=[], outputs=['const1'], value=helper.make_tensor( name='const_tensor', data_type=TensorProto.FLOAT, dims=constant.shape, vals=constant.flatten(), ), ) nodes = [node_const_def] inputs = ['const1'] if axis is not None: node_axis_def = onnx.helper.make_node( 'Constant', inputs=[], outputs=['axis'], value=helper.make_tensor( name='const_tensor', data_type=TensorProto.INT64, dims=[], vals=[axis], ), ) nodes.append(node_axis_def) inputs.append('axis') args = dict() if exclusive is not None: args['exclusive'] = exclusive if reverse is not None: args['reverse'] = reverse node_def = onnx.helper.make_node( 'CumSum', inputs=inputs, outputs=['cumsum'], **args ) node_concat_def = onnx.helper.make_node( 'Concat', inputs=['input', 'cumsum'], outputs=['output'], axis=concat_axis ) nodes.extend([node_def, node_concat_def]) # Create the graph (GraphProto) graph_def = helper.make_graph( nodes, 'test_model', [input], [output], ) # Create the model (ModelProto) onnx_net = helper.make_model(graph_def, producer_name='test_model') onnx.checker.check_model(onnx_net) # # Create reference IR net # constant = cumsum(constant, axis=axis, reverse=reverse, exclusive=exclusive) ref_net = None if check_ir_version(10, None, ir_version): nodes_attributes = { 'input': {'kind': 'op', 'type': 'Parameter'}, 'input_data': {'shape': shape, 'kind': 'data'}, 'input_const_data': {'kind': 'data', 'value': constant.flatten()}, 'const': {'kind': 'op', 'type': 'Const'}, 'const_data': {'shape': shape, 'kind': 'data'}, 'concat': {'kind': 'op', 'type': 'Concat', 'axis': concat_axis}, 'concat_data': {'shape': output_shape, 'kind': 'data'}, 'result': {'kind': 'op', 'type': 'Result'} } ref_net = build_graph(nodes_attributes, [('input', 'input_data'), ('input_const_data', 'const'), ('const', 'const_data'), ('input_data', 'concat'), ('const_data', 'concat'), ('concat', 'concat_data'), ('concat_data', 'result') ]) return onnx_net, ref_net test_data = [ dict(shape=[1]), dict(shape=[1, 2]), dict(shape=[2, 4, 6]), dict(shape=[2, 4, 6, 8]), dict(shape=[2, 4, 6, 8, 10]), dict(shape=[1, 2], axis=-2), dict(shape=[1, 2], axis=1), dict(shape=[2, 4, 6], axis=-3), dict(shape=[2, 4, 6], axis=2), dict(shape=[2, 4, 6, 8], axis=-4), dict(shape=[2, 4, 6, 8], axis=3), dict(shape=[2, 4, 6, 8, 10], axis=-1), dict(shape=[2, 4, 6, 8, 10], axis=4)] @pytest.mark.parametrize("params", test_data) @pytest.mark.parametrize("reverse", [0, 1]) @pytest.mark.parametrize("exclusive", [0, 1]) @pytest.mark.nightly def test_cumsum(self, params, reverse, exclusive, ie_device, precision, ir_version, temp_dir): if 'axis' not in params: pytest.skip('No axis cases fail in ONNX') self._test(*self.create_net(**params, exclusive=exclusive, reverse=reverse, ir_version=ir_version), ie_device, precision, ir_version, temp_dir=temp_dir) @pytest.mark.parametrize("params", test_data) @pytest.mark.parametrize("reverse", [0, 1]) @pytest.mark.parametrize("exclusive", [0, 1]) @pytest.mark.nightly def test_cumsum_const(self, params, reverse, exclusive, ie_device, precision, ir_version, temp_dir): if 'axis' not in params: pytest.skip('No axis cases fail in ONNX') self._test(*self.create_net_const(**params, precision=precision, exclusive=exclusive, reverse=reverse, ir_version=ir_version), ie_device, precision, ir_version, temp_dir=temp_dir)
[ "noreply@github.com" ]
mashoujiang.noreply@github.com
5ef6346413ae628ba03088b2d210c9ae42298bd9
ca7aa979e7059467e158830b76673f5b77a0f5a3
/Python_codes/p03352/s946533946.py
12fad2670ffb01c55aa659302df6c57fe72d8080
[]
no_license
Aasthaengg/IBMdataset
7abb6cbcc4fb03ef5ca68ac64ba460c4a64f8901
f33f1c5c3b16d0ea8d1f5a7d479ad288bb3f48d8
refs/heads/main
2023-04-22T10:22:44.763102
2021-05-13T17:27:22
2021-05-13T17:27:22
367,112,348
0
0
null
null
null
null
UTF-8
Python
false
false
173
py
X = int(input()) res = 1 for i in range(X): for p in range(2, X): if i ** p <= X: res = max(res, i ** p) else: break print(res)
[ "66529651+Aastha2104@users.noreply.github.com" ]
66529651+Aastha2104@users.noreply.github.com
5438414fe8e44e712ecbfe276212b0d08e32fd70
e3b9aa9b17ebb55e53dbc4fa9d1f49c3a56c6488
/samanage/komand_samanage/triggers/new_incidents/trigger.py
470860710f58f767235a820a10dff1bf13aa4beb
[ "MIT" ]
permissive
OSSSP/insightconnect-plugins
ab7c77f91c46bd66b10db9da1cd7571dfc048ab7
846758dab745170cf1a8c146211a8bea9592e8ff
refs/heads/master
2023-04-06T23:57:28.449617
2020-03-18T01:24:28
2020-03-18T01:24:28
248,185,529
1
0
MIT
2023-04-04T00:12:18
2020-03-18T09:14:53
null
UTF-8
Python
false
false
2,192
py
import komand import time from .schema import NewIncidentsInput, NewIncidentsOutput # Custom imports below class NewIncidents(komand.Trigger): def __init__(self): super(self.__class__, self).__init__( name='new_incidents', description='Check for new incidents', input=NewIncidentsInput(), output=NewIncidentsOutput()) def run(self, params={}): frequency = params.get('frequency', 10) cache_file_name = 'cached_incidents_ids' with komand.helper.open_cachefile(cache_file_name) as cache_file: self.logger.info( 'Found or created cache file: {}'.format(cache_file_name) ) cached_ids = {l.strip() for l in cache_file.readlines()} self.logger.info('Cached IDs: {}'.format(cached_ids)) while True: try: incidents = self.connection.api.list_incidents() new_ids = set() for incident in incidents: incident_id = str(incident['id']) if incident_id not in cached_ids: cached_ids.add(incident_id) new_ids.add(incident_id) self.logger.info( 'New incident found: {}'.format(incident_id) ) self.send({'incident': incident}) with komand.helper.open_cachefile( cache_file_name, append=True ) as cache_file: for incident_id in new_ids: self.logger.info( 'Writing incident {} to cache file'.format( incident_id ) ) cache_file.write(incident_id) time.sleep(frequency) except Exception as e: raise Exception( 'An error occurred while reading incidents: {}'.format(e) ) def test(self): self.connection.api.list_incidents() return {'incident': {}}
[ "jonschipp@gmail.com" ]
jonschipp@gmail.com
516fab03d860d4df846fb70176bd0d16d5007d2f
ddc6e402758c364d25ce9caeda7b3cd94dbcd546
/Medium/535_EncodeandDecodeTinyURL.py
2cda233163cdee5989cbaf60070c314a400fbc4d
[]
no_license
J-pcy/Jffery_Leetcode_Python
f01cdbb31a114bc6ed91139d0bd2cdddda35a503
f34c370fbb9fb171d5ec33337116a764c25cd2dd
refs/heads/master
2020-03-20T20:20:02.931776
2018-11-02T19:41:36
2018-11-02T19:41:36
137,682,076
0
0
null
null
null
null
UTF-8
Python
false
false
1,105
py
""" TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problems/design-tinyurl and it returns a short URL such as http://tinyurl.com/4e9iAk. Design the encode and decode methods for the TinyURL service. There is no restriction on how your encode/decode algorithm should work. You just need to ensure that a URL can be encoded to a tiny URL and the tiny URL can be decoded to the original URL. """ class Codec: def __init__(self): self.index = 0 self.map = {} def encode(self, longUrl): """Encodes a URL to a shortened URL. :type longUrl: str :rtype: str """ self.index += 1 self.map[self.index] = longUrl return "http://tinyurl.com/" + str(self.index) def decode(self, shortUrl): """Decodes a shortened URL to its original URL. :type shortUrl: str :rtype: str """ return self.map[int(shortUrl.split('/')[-1])] # Your Codec object will be instantiated and called as such: # codec = Codec() # codec.decode(codec.encode(url))
[ "chenyupe@usc.edu" ]
chenyupe@usc.edu
d4aa33ef9af10d78de2c1ed7a52823bdcaaae7c9
31cf77b4c0342c6148b35ae2613d5e2501d5e755
/src/encoded/tests/fixtures/schemas/organism_development_series.py
1a85ac543daf46cc0080b5b5fe5361773c6e4447
[ "MIT" ]
permissive
ENCODE-DCC/encoded
096de8a6d60c959a783cc9517f1d60bd6c21b71f
80e05610c79b46d0890228555bb03e436b2fef11
refs/heads/dev
2023-08-08T15:45:07.493187
2023-08-03T20:01:24
2023-08-03T20:01:24
7,045,549
110
69
MIT
2023-09-12T23:59:45
2012-12-07T00:52:21
JavaScript
UTF-8
Python
false
false
405
py
import pytest @pytest.fixture def organism_development_series_17(testapp, lab, base_experiment_submitted, award): item = { 'award': award['uuid'], 'lab': lab['uuid'], 'related_datasets': [base_experiment_submitted['@id']], 'schema_version': '17', 'internal_tags': ['ENCYCLOPEDIAv3', 'ENCYCLOPEDIAv4', 'ENCYCLOPEDIAv5', 'ENCYCLOPEDIAv6'] } return item
[ "noreply@github.com" ]
ENCODE-DCC.noreply@github.com
c047613e9ed2f92e9bf284726158a743c18d970f
a5747577f1f4b38823f138ec0fbb34a0380cd673
/17/mc/ExoDiBosonResonances/EDBRTreeMaker/test/crab3_analysisnewnewST_s-channel_4f_leptonDecays.py
f1704df01dc11d1aad6690e6981b899f1585d06c
[]
no_license
xdlyu/fullRunII_ntuple
346fc1da4cec9da4c404aa1ec0bfdaece6df1526
aa00ca4ce15ae050c3096d7af779de44fc59141e
refs/heads/master
2020-08-03T07:52:29.544528
2020-01-22T14:18:12
2020-01-22T14:18:12
211,673,739
0
3
null
null
null
null
UTF-8
Python
false
false
2,396
py
from WMCore.Configuration import Configuration config = Configuration() config.section_("General") config.General.requestName = 'newnewST_s-channel_4f_leptonDecays' config.General.transferLogs = True config.section_("JobType") config.JobType.pluginName = 'Analysis' config.JobType.inputFiles = ['Fall17_17Nov2017_V8_MC_L1FastJet_AK4PFchs.txt','Fall17_17Nov2017_V8_MC_L2Relative_AK4PFchs.txt','Fall17_17Nov2017_V8_MC_L3Absolute_AK4PFchs.txt','Fall17_17Nov2017_V8_MC_L1FastJet_AK8PFchs.txt','Fall17_17Nov2017_V8_MC_L2Relative_AK8PFchs.txt','Fall17_17Nov2017_V8_MC_L3Absolute_AK8PFchs.txt','Fall17_17Nov2017_V8_MC_L1FastJet_AK8PFPuppi.txt','Fall17_17Nov2017_V8_MC_L2Relative_AK8PFPuppi.txt','Fall17_17Nov2017_V8_MC_L3Absolute_AK8PFPuppi.txt','Fall17_17Nov2017_V8_MC_L1FastJet_AK4PFPuppi.txt','Fall17_17Nov2017_V8_MC_L2Relative_AK4PFPuppi.txt','Fall17_17Nov2017_V8_MC_L3Absolute_AK4PFPuppi.txt'] #config.JobType.inputFiles = ['PHYS14_25_V2_All_L1FastJet_AK4PFchs.txt','PHYS14_25_V2_All_L2Relative_AK4PFchs.txt','PHYS14_25_V2_All_L3Absolute_AK4PFchs.txt','PHYS14_25_V2_All_L1FastJet_AK8PFchs.txt','PHYS14_25_V2_All_L2Relative_AK8PFchs.txt','PHYS14_25_V2_All_L3Absolute_AK8PFchs.txt'] # Name of the CMSSW configuration file #config.JobType.psetName = 'bkg_ana.py' config.JobType.psetName = 'analysis.py' #config.JobType.allowUndistributedCMSSW = True config.JobType.sendExternalFolder = True config.JobType.allowUndistributedCMSSW = True config.section_("Data") #config.Data.inputDataset = '/WJetsToLNu_13TeV-madgraph-pythia8-tauola/Phys14DR-PU20bx25_PHYS14_25_V1-v1/MINIAODSIM' config.Data.inputDataset = '/ST_s-channel_4f_leptonDecays_13TeV-amcatnlo-pythia8_TuneCUETP8M1/RunIISummer16MiniAODv2-PUMoriond17_80X_mcRun2_asymptotic_2016_TrancheIV_v6-v1/MINIAODSIM' config.Data.inputDBS = 'global' #config.Data.inputDBS = 'phys03' config.Data.splitting = 'FileBased' config.Data.unitsPerJob =5 config.Data.totalUnits = -1 config.Data.publication = False name = 'idle' steam_dir = 'xulyu' config.Data.outLFNDirBase = '/store/group/dpg_trigger/comm_trigger/TriggerStudiesGroup/STEAM/' + steam_dir + '/' + name + '/' # This string is used to construct the output dataset name config.JobType.sendExternalFolder = True config.Data.outputDatasetTag = 'newnewST_s-channel_4f_leptonDecays' config.section_("Site") # Where the output files will be transmitted to config.Site.storageSite = 'T2_CH_CERN'
[ "XXX@cern.ch" ]
XXX@cern.ch
bcca40aea327335a5be27121afa6c83aad3e0049
3267fb38696d7b114a22f476f2c60425d6ee349a
/src/tests/test_api/test_auth_endpoint.py
b2aa2759373a6cb2b92f4a901b98debd44f51dfe
[]
no_license
marcinowski/github-adapter
c0092e3f817f9dc1d97691e81b1c247ae281b2c7
2d7c6b9601da082de246450cc840412f0c4331b5
refs/heads/master
2022-12-10T00:53:39.386198
2017-09-06T10:57:09
2017-09-06T10:57:09
100,716,960
0
0
null
2021-06-01T22:02:20
2017-08-18T13:55:02
Python
UTF-8
Python
false
false
1,805
py
""" :created on: 2017-08-22 :author: Marcin Muszynski :contact: marcinowski007@gmail.com """ from flask import session from unittest.mock import MagicMock from api.auth import AuthLogin, AuthLogout from ..generic import GenericTestCase from ..github_responses import AUTH_RESPONSE, AUTH_STATUS, ERROR_RESPONSE_401 class TestAuthResource(GenericTestCase): def test_login(self): """ Simple workflow test for fetching credentials from request """ with self.app.test_request_context('/', data={'username': 'test', 'password': 'test'}): username, password = AuthLogin()._get_credentials_from_request() self.assertEqual(username, 'test') def test_storing_credentials(self): """ Simple test for keeping credentials in session while authenticating """ a = AuthLogin() mock = MagicMock() mock.return_value = AUTH_RESPONSE, AUTH_STATUS a.fetch_from_github = mock with self.app.test_request_context('/', data={'username': 't_username', 'password': 'test'}): a.post() self.assertTrue(a.is_authenticated()) self.assertEqual(session['username'], 't_username') def test_nok_response(self): """ Error GitHub response handling """ a = AuthLogin() mock = MagicMock() mock.return_value = ERROR_RESPONSE_401, 401 a.fetch_from_github = mock resp, status_code = a.post() self.assertEqual(status_code, 401) def test_logout(self): """ Simple workflow test for logging out """ a = AuthLogout() with self.app.test_request_context('/'): session['authenticated'] = True a.get() self.assertFalse(a.is_authenticated()) self.assertFalse('username' in session)
[ "muszynskimarcin@wp.pl" ]
muszynskimarcin@wp.pl
a2f91cc8c13f634a36add56d6baa39f288d1e554
8da90fe722d50c8f624a64c73e09c6795b2b1db5
/tf_agents/bandits/policies/greedy_reward_prediction_policy_test.py
90dc038c75e9ce9c3067af8021263874404847b5
[ "Apache-2.0" ]
permissive
futurev/agents
d5e3ad62c469fc33cafe71566f0be18f01a37f3b
c721d09c8ce2e70e46a3a9d3c56483118575d3f4
refs/heads/master
2022-10-21T05:25:34.342989
2022-09-28T23:44:04
2022-09-28T23:44:04
257,982,748
0
0
Apache-2.0
2020-04-22T18:12:43
2020-04-22T18:12:42
null
UTF-8
Python
false
false
14,172
py
# coding=utf-8 # Copyright 2018 The TF-Agents Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Test for greedy_reward_prediction_policy.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import collections import numpy as np import tensorflow as tf # pylint: disable=g-explicit-tensorflow-version-import from tf_agents.bandits.networks import global_and_arm_feature_network from tf_agents.bandits.networks import heteroscedastic_q_network from tf_agents.bandits.policies import greedy_reward_prediction_policy as greedy_reward_policy from tf_agents.bandits.specs import utils as bandit_spec_utils from tf_agents.networks import network from tf_agents.specs import array_spec from tf_agents.specs import tensor_spec from tf_agents.trajectories import time_step as ts from tf_agents.utils import test_utils from tensorflow.python.framework import test_util # pylint: disable=g-direct-tensorflow-import # TF internal class DummyNet(network.Network): def __init__(self, observation_spec, num_actions=3): super(DummyNet, self).__init__(observation_spec, (), 'DummyNet') # Store custom layers that can be serialized through the Checkpointable API. self._dummy_layers = [ tf.keras.layers.Dense( num_actions, kernel_initializer=tf.compat.v1.initializers.constant( [[1, 1.5, 2], [1, 1.5, 4]]), bias_initializer=tf.compat.v1.initializers.constant( [[1], [1], [-10]])) ] def call(self, inputs, step_type=None, network_state=()): del step_type inputs = tf.cast(inputs, tf.float32) for layer in self._dummy_layers: inputs = layer(inputs) return inputs, network_state class HeteroscedasticDummyNet( heteroscedastic_q_network.HeteroscedasticQNetwork): def __init__(self, name=None, num_actions=3): input_spec = array_spec.ArraySpec([2], np.float32) action_spec = array_spec.BoundedArraySpec([1], np.float32, 1, num_actions) input_tensor_spec = tensor_spec.from_spec(input_spec) action_tensor_spec = tensor_spec.from_spec(action_spec) super(HeteroscedasticDummyNet, self).__init__(input_tensor_spec, action_tensor_spec) self._value_layer = tf.keras.layers.Dense( num_actions, kernel_initializer=tf.compat.v1.initializers.constant( [[1, 1.5, 2], [1, 1.5, 4]]), bias_initializer=tf.compat.v1.initializers.constant( [[1], [1], [-10]])) self._log_variance_layer = tf.keras.layers.Dense( num_actions, kernel_initializer=tf.compat.v1.initializers.constant( [[1, 1.5, 2], [1, 1.5, 4]]), bias_initializer=tf.compat.v1.initializers.constant( [[1], [1], [-10]])) def call(self, inputs, step_type=None, network_state=()): del step_type inputs = tf.cast(inputs, tf.float32) value = self._value_layer(inputs) log_variance = self._log_variance_layer(inputs) predictions = collections.namedtuple('QBanditNetworkResult', ('q_value_logits', 'log_variance')) predictions = predictions(value, log_variance) return predictions, network_state @test_util.run_all_in_graph_and_eager_modes class GreedyRewardPredictionPolicyTest(test_utils.TestCase): def setUp(self): super(GreedyRewardPredictionPolicyTest, self).setUp() self._obs_spec = tensor_spec.TensorSpec([2], tf.float32) self._time_step_spec = ts.time_step_spec(self._obs_spec) self._action_spec = tensor_spec.BoundedTensorSpec((), tf.int32, 0, 2) def testBuild(self): policy = greedy_reward_policy.GreedyRewardPredictionPolicy( self._time_step_spec, self._action_spec, reward_network=DummyNet(self._obs_spec)) self.assertEqual(policy.time_step_spec, self._time_step_spec) self.assertEqual(policy.action_spec, self._action_spec) def testMultipleActionsRaiseError(self): action_spec = [tensor_spec.BoundedTensorSpec((), tf.int32, 0, 2)] * 2 with self.assertRaisesRegexp( NotImplementedError, 'action_spec can only contain a single BoundedTensorSpec'): greedy_reward_policy.GreedyRewardPredictionPolicy( self._time_step_spec, action_spec, reward_network=DummyNet(self._obs_spec)) def testWrongActionsRaiseError(self): action_spec = tensor_spec.BoundedTensorSpec((5, 6, 7), tf.float32, 0, 2) with self.assertRaisesRegexp( NotImplementedError, 'action_spec must be a BoundedTensorSpec of type int32.*'): greedy_reward_policy.GreedyRewardPredictionPolicy( self._time_step_spec, action_spec, reward_network=DummyNet(self._obs_spec)) def testWrongOutputLayerRaiseError(self): tf.compat.v1.set_random_seed(1) action_spec = tensor_spec.BoundedTensorSpec((), tf.int32, 10, 20) policy = greedy_reward_policy.GreedyRewardPredictionPolicy( self._time_step_spec, action_spec, reward_network=DummyNet(self._obs_spec)) observations = tf.constant([[1, 2], [3, 4]], dtype=tf.float32) time_step = ts.restart(observations, batch_size=2) with self.assertRaisesRegexp( ValueError, r'The number of actions \(11\) does not match the reward_network output' r' size \(3\)\.'): policy.action(time_step, seed=1) def testAction(self): tf.compat.v1.set_random_seed(1) policy = greedy_reward_policy.GreedyRewardPredictionPolicy( self._time_step_spec, self._action_spec, reward_network=DummyNet(self._obs_spec)) observations = tf.constant([[1, 2], [3, 4]], dtype=tf.float32) time_step = ts.restart(observations, batch_size=2) action_step = policy.action(time_step, seed=1) self.assertEqual(action_step.action.shape.as_list(), [2]) self.assertEqual(action_step.action.dtype, tf.int32) # Initialize all variables self.evaluate(tf.compat.v1.global_variables_initializer()) self.assertAllEqual(self.evaluate(action_step.action), [1, 2]) def testActionHeteroscedastic(self): tf.compat.v1.set_random_seed(1) policy = greedy_reward_policy.GreedyRewardPredictionPolicy( self._time_step_spec, self._action_spec, reward_network=HeteroscedasticDummyNet()) observations = tf.constant([[1, 2], [3, 4]], dtype=tf.float32) time_step = ts.restart(observations, batch_size=2) action_step = policy.action(time_step, seed=1) self.assertEqual(action_step.action.shape.as_list(), [2]) self.assertEqual(action_step.action.dtype, tf.int32) # Initialize all variables self.evaluate(tf.compat.v1.global_variables_initializer()) self.assertAllEqual(self.evaluate(action_step.action), [1, 2]) def testActionScalarSpec(self): tf.compat.v1.set_random_seed(1) action_spec = tensor_spec.BoundedTensorSpec((), tf.int32, 0, 2) policy = greedy_reward_policy.GreedyRewardPredictionPolicy( self._time_step_spec, action_spec, reward_network=DummyNet(self._obs_spec)) observations = tf.constant([[1, 2], [3, 4]], dtype=tf.float32) time_step = ts.restart(observations, batch_size=2) action_step = policy.action(time_step, seed=1) self.assertEqual(action_step.action.shape.as_list(), [2]) self.assertEqual(action_step.action.dtype, tf.int32) # Initialize all variables self.evaluate(tf.compat.v1.global_variables_initializer()) self.assertAllEqual(self.evaluate(action_step.action), [1, 2]) def testActionScalarSpecWithShift(self): tf.compat.v1.set_random_seed(1) action_spec = tensor_spec.BoundedTensorSpec((), tf.int32, 10, 12) policy = greedy_reward_policy.GreedyRewardPredictionPolicy( self._time_step_spec, action_spec, reward_network=DummyNet(self._obs_spec)) observations = tf.constant([[1, 2], [3, 4]], dtype=tf.float32) time_step = ts.restart(observations, batch_size=2) action_step = policy.action(time_step, seed=1) self.assertEqual(action_step.action.shape.as_list(), [2]) self.assertEqual(action_step.action.dtype, tf.int32) # Initialize all variables self.evaluate(tf.compat.v1.global_variables_initializer()) self.assertAllEqual(self.evaluate(action_step.action), [11, 12]) def testMaskedAction(self): tf.compat.v1.set_random_seed(1) action_spec = tensor_spec.BoundedTensorSpec((), tf.int32, 0, 2) observation_spec = (tensor_spec.TensorSpec([2], tf.float32), tensor_spec.TensorSpec([3], tf.int32)) time_step_spec = ts.time_step_spec(observation_spec) def split_fn(obs): return obs[0], obs[1] policy = greedy_reward_policy.GreedyRewardPredictionPolicy( time_step_spec, action_spec, reward_network=DummyNet(observation_spec[0]), observation_and_action_constraint_splitter=split_fn) observations = (tf.constant([[1, 2], [3, 4]], dtype=tf.float32), tf.constant([[0, 0, 1], [0, 1, 0]], dtype=tf.int32)) time_step = ts.restart(observations, batch_size=2) action_step = policy.action(time_step, seed=1) self.assertEqual(action_step.action.shape.as_list(), [2]) self.assertEqual(action_step.action.dtype, tf.int32) # Initialize all variables self.evaluate(tf.compat.v1.global_variables_initializer()) self.assertAllEqual(self.evaluate(action_step.action), [2, 1]) def testUpdate(self): tf.compat.v1.set_random_seed(1) policy = greedy_reward_policy.GreedyRewardPredictionPolicy( self._time_step_spec, self._action_spec, reward_network=DummyNet(self._obs_spec)) new_policy = greedy_reward_policy.GreedyRewardPredictionPolicy( self._time_step_spec, self._action_spec, reward_network=DummyNet(self._obs_spec)) observations = tf.constant([[1, 2], [3, 4]], dtype=tf.float32) time_step = ts.restart(observations, batch_size=2) action_step = policy.action(time_step, seed=1) new_action_step = new_policy.action(time_step, seed=1) self.assertEqual(len(policy.variables()), 2) self.assertEqual(len(new_policy.variables()), 2) self.assertEqual(action_step.action.shape, new_action_step.action.shape) self.assertEqual(action_step.action.dtype, new_action_step.action.dtype) self.evaluate(tf.compat.v1.global_variables_initializer()) self.assertIsNone(self.evaluate(new_policy.update(policy))) self.assertAllEqual(self.evaluate(action_step.action), [1, 2]) self.assertAllEqual(self.evaluate(new_action_step.action), [1, 2]) def testPredictedRewards(self): tf.compat.v1.set_random_seed(1) policy = greedy_reward_policy.GreedyRewardPredictionPolicy( self._time_step_spec, self._action_spec, reward_network=DummyNet(self._obs_spec), emit_policy_info=('predicted_rewards_mean',)) observations = tf.constant([[1, 2], [3, 4]], dtype=tf.float32) time_step = ts.restart(observations, batch_size=2) action_step = policy.action(time_step, seed=1) self.assertEqual(action_step.action.shape.as_list(), [2]) self.assertEqual(action_step.action.dtype, tf.int32) # Initialize all variables self.evaluate(tf.compat.v1.global_variables_initializer()) self.assertAllEqual(self.evaluate(action_step.action), [1, 2]) # The expected values are obtained by passing the observation through the # Keras dense layer of the DummyNet (defined above). predicted_rewards_expected_array = np.array([[4.0, 5.5, 0.0], [8.0, 11.5, 12.0]]) p_info = self.evaluate(action_step.info) self.assertAllClose(p_info.predicted_rewards_mean, predicted_rewards_expected_array) def testPerArmRewards(self): if not tf.executing_eagerly(): return tf.compat.v1.set_random_seed(3000) obs_spec = bandit_spec_utils.create_per_arm_observation_spec(2, 3, 4) time_step_spec = ts.time_step_spec(obs_spec) action_spec = tensor_spec.BoundedTensorSpec((), tf.int32, 0, 3) reward_network = ( global_and_arm_feature_network.create_feed_forward_common_tower_network( obs_spec, (4, 3), (3, 4), (4, 2))) policy = greedy_reward_policy.GreedyRewardPredictionPolicy( time_step_spec, action_spec, reward_network=reward_network, accepts_per_arm_features=True, emit_policy_info=('predicted_rewards_mean',)) observations = { bandit_spec_utils.GLOBAL_FEATURE_KEY: tf.constant([[1, 2], [3, 4]], dtype=tf.float32), bandit_spec_utils.PER_ARM_FEATURE_KEY: tf.cast( tf.reshape(tf.random.shuffle(tf.range(24)), shape=[2, 4, 3]), dtype=tf.float32) } time_step = ts.restart(observations, batch_size=2) action_step = policy.action(time_step, seed=1) self.assertEqual(action_step.action.shape.as_list(), [2]) self.assertEqual(action_step.action.dtype, tf.int32) # Initialize all variables self.evaluate(tf.compat.v1.global_variables_initializer()) action = self.evaluate(action_step.action) self.assertAllEqual(action.shape, [2]) p_info = self.evaluate(action_step.info) self.assertAllEqual(p_info.predicted_rewards_mean.shape, [2, 4]) self.assertAllEqual(p_info.chosen_arm_features.shape, [2, 3]) first_action = action[0] first_arm_features = observations[bandit_spec_utils.PER_ARM_FEATURE_KEY][0] self.assertAllEqual(p_info.chosen_arm_features[0], first_arm_features[first_action]) if __name__ == '__main__': tf.test.main()
[ "copybara-worker@google.com" ]
copybara-worker@google.com
af0406bc37dc6322179122bb2b34e46c5407bf26
6fa7f99d3d3d9b177ef01ebf9a9da4982813b7d4
/BZ4mMcEz3aqosEtbC_7.py
e3f9da38350d7784a4a4a0d20383b509a28ee3da
[]
no_license
daniel-reich/ubiquitous-fiesta
26e80f0082f8589e51d359ce7953117a3da7d38c
9af2700dbe59284f5697e612491499841a6c126f
refs/heads/master
2023-04-05T06:40:37.328213
2021-04-06T20:17:44
2021-04-06T20:17:44
355,318,759
0
0
null
null
null
null
UTF-8
Python
false
false
144
py
def mean(num): count = 0 str_num = str(num) for i in range(len(str_num)): count += int(str_num[i]) return int(count/len(str_num))
[ "daniel.reich@danielreichs-MacBook-Pro.local" ]
daniel.reich@danielreichs-MacBook-Pro.local
5e47baa390d8d2f117b9ae64bc39ef1cfc413d28
27acb207b21b4572561de4a5f7dfb9740318c0b8
/Python-Programming-Essentials/Week3/Ex10_W3_smaller_root.py
be67b001047ad7f7053dfbcba4458612dc558b08
[]
no_license
iamieht/intro-scripting-in-python-specialization
ee836ef05b62f6c74fe8da3ee137687b4d0035cf
8ea4f85f0ed3dcd541f89521c013335e9eb32980
refs/heads/master
2021-01-16T05:35:51.616276
2020-06-08T18:39:45
2020-06-08T18:39:45
242,993,577
0
0
null
null
null
null
UTF-8
Python
false
false
1,723
py
""" Compute the smaller root of a quadratic equation. """ ################################################### # Smaller quadratic root formula # Student should enter function on the next lines. def smaller_root(a, b, c): ''' returns the smaller solution to the quadratic equation if one exists ''' discriminant = b ** 2 - 4 * a * c smaller = 0 if discriminant < 0 or a == 0: print("Error: No real solutions") else: discriminant_sqrt = discriminant ** 0.5 if a > 0: smaller = - discriminant_sqrt else: smaller = discriminant_sqrt return (-b + smaller) / (2 * a) ################################################### # Tests # Student should not change this code. coeff_a, coeff_b, coeff_c = 1, 2, 3 print("The smaller root of " + str(coeff_a) + "x^2 + " + str(coeff_b) + "x + " + str(coeff_c) + " is: ") print(str(smaller_root(coeff_a, coeff_b, coeff_c))) coeff_a, coeff_b, coeff_c = 2, 0, -10 print("The smaller root of " + str(coeff_a) + "x^2 + " + str(coeff_b) + "x + " + str(coeff_c) + " is: ") print(str(smaller_root(coeff_a, coeff_b, coeff_c))) coeff_a, coeff_b, coeff_c = 6, -3, 5 print("The smaller root of " + str(coeff_a) + "x^2 + " + str(coeff_b) + "x + " + str(coeff_c) + " is: ") print(str(smaller_root(coeff_a, coeff_b, coeff_c))) ################################################### # Expected output # Student should look at the following comments and compare to printed output. #The smaller root of 1x^2 + 2x + 3 is: #Error: No real solutions #None #The smaller root of 2x^2 + 0x + -10 is: #-2.2360679775 #The smaller root of 6x^2 + -3x + 5 is: #Error: No real solutions #None
[ "iamieht@gmail.com" ]
iamieht@gmail.com
6783bf9ea4a5df08ea547298358e38c0ad0d7867
2ac13c73340e5f4126e1dc394cdca45e3b2b223b
/utils/time_now.py
76025e95be078f76beee9634e373b4a500d4b4d8
[]
no_license
EgbieAndersonUku1/price_alerter_app
36074fc32aedde1aee0524a271e98d3da18126d1
87e1d6ac05a19b0255c43003e957190f597d4655
refs/heads/master
2020-03-17T07:04:50.299396
2018-06-06T00:06:45
2018-06-06T00:06:45
133,375,739
0
0
null
null
null
null
UTF-8
Python
false
false
444
py
from datetime import datetime from datetime import timedelta def time_passed_since_current_time(minutes): """time_passed_since_current_time(int) -> returns time obj Returns the number of minutes that has elapsed between the current time and the passed in parameter minutes. """ return time_now() - timedelta(minutes=minutes) def time_now(): """Returns the current time object""" return datetime.utcnow()
[ "jayunderwood2011@hotmail.com" ]
jayunderwood2011@hotmail.com