def __init__(self): """MonthCalendarSample class init function.""" # setup title self.Text = "MonthCalendar control" # setup monthcalendar self.monthcalendar = MonthCalendar() # set one days that can be selected in a month calendar control self.monthcalendar.MaxSelectionCount = 2 self.monthcalendar.ShowWeekNumbers = True #NOTE: Strongwind tests depend on this date setting! Make sure to update them if you change it initialRange = SelectionRange(DateTime.Parse("1/23/2008"), DateTime.Parse("1/23/2008")) self.monthcalendar.SelectionRange = initialRange self.monthcalendar.DateChanged += self.date_select # setup label self.label = Label() self.label.Width = 200 self.label.Height = 50 self.label.Location = Point(5, 170) self.label.Text = ( "Your selection is:\n" + (self.monthcalendar.SelectionRange.Start).ToString('o')[:10]) # add controls self.Controls.Add(self.monthcalendar) self.Controls.Add(self.label)
def DataChanged(e): # 验证结束时间大于出差时间 _FDateStart = this.View.BillModel.GetValue('FDateStart', e.Row) _FDateEnd = this.View.BillModel.GetValue('FDateEnd', e.Row) if e.Key == 'FDateStart': if _FDateStart != None and _FDateEnd != None: # 开始时间大于结束时间 if DateTime.Parse(str(_FDateStart)).CompareTo( DateTime.Parse(str(_FDateEnd))) == 1: this.View.ShowMessage('出差时间不能在结束时间之后!') if e.Key == 'FDateEnd': if _FDateStart != None and _FDateEnd != None: # 开始时间大于结束时间 if DateTime.Parse(str(_FDateStart)).CompareTo( DateTime.Parse(str(_FDateEnd))) == 1: this.View.ShowMessage('结束时间不能在出差时间之前!') # FAmount 为预计金额代理字段标识 if e.Key == 'FAmount': # 预计费用 PreMoney = float(this.View.BillModel.GetValue('F_ora_Amount')) PreMoney = convertNumToChinese(PreMoney) AmountDisplay = this.View.BillModel.SetValue('F_ora_AmountDisplay', PreMoney) # ---------------------------------------------------------------------------------------------------- if e.Key == 'F_ora_Cost': # 表体中预估费用更改时汇总到表头 count = this.View.BillModel.GetEntryRowCount('FEntity') amount = sum([ float(this.View.BillModel.GetValue('FExpectCost', row)) for row in range(count) ]) #this.View.ShowMessage(str(amount)) this.View.BillModel.SetValue('F_ora_Amount', amount)
def test_should_not_write_end_time_when_already_exists_in_report(self): self.accessor.read_end_time = DateTime.Parse("17:00") self.writer.write(new_workinghours("08:15", "16:15")) assert len(self.accessor.hours_written) == 1 assert self.accessor.hours_written[0] == DateTime.Parse("8:15")
def test_should_not_write_starting_hours_when_hours_exist(self): self.accessor.read_start_time = DateTime.Parse("09:00") self.writer.write(new_workinghours("08:15", "16:15")) assert len(self.accessor.hours_written) == 1 assert self.accessor.hours_written[0] == DateTime.Parse("16:15")
def setUp(self): temp_dir = DirectoryInfo(Environment.GetEnvironmentVariable("TEMP")) # myDocuments = DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)) self.temp_dir = temp_dir.CreateSubdirectory('tempDir') self.temp_dir_path = self.temp_dir.ToString() self.file1 = FileInfo(self.temp_dir_path + '\\file1.txt') self.file2 = FileInfo(self.temp_dir_path + '\\file2.txt') self.file3 = FileInfo(self.temp_dir_path + '\\file3.txt') sw = self.file1.CreateText() sw.WriteLine("Hello1") sw.Close() sw = self.file2.CreateText() sw.WriteLine("Hello2") sw.Close() sw = self.file3.CreateText() sw.WriteLine("Hello3") sw.Close() today = DateTime.Now one_day_old = today.AddDays(-1).ToString("yyyy.MM.dd") two_days_old = today.AddDays(-2).ToString("yyyy.MM.dd") self.file1.CreationTime = DateTime.Parse(today.ToString("yyyy.MM.dd")) self.file2.CreationTime = DateTime.Parse(one_day_old) self.file3.CreationTime = DateTime.Parse(two_days_old) print "\r myDocuments temp path = [%s]" % self.temp_dir_path print "CreationTime file1 = [%s]" % self.file1.CreationTime print "CreationTime file2 = [%s]" % self.file2.CreationTime print "CreationTime file3 = [%s]" % self.file3.CreationTime
def fetch_unsent_items_from_InsCalibrationStatus(cursor): unsent_ins_cal_status = [] if cursor: cursor.execute("SELECT * FROM InsCalibrationStatus WHERE Sent = 0") rows = cursor.fetchall() for row in rows: cal = ins_calibration_status() cal.Curve = row['Curve'] cal.FitRate = row['FitRate'] cal.LotNo = row['LotNo'] cal.ReagentLotNo = row['ReagentLotNo'] cal.ResultDate = DateTime.Parse(row['ResultDate']) cal.State = CalibrationStateType.Unkown if 'Pass' == row['State']: cal.State = CalibrationStateType.Pass elif 'Fail' == row['State']: cal.State = CalibrationStateType.Failed cal.TestCode = row['TestCode'] cal.TtlNums = int(row['TtlNums']) cal.Sent = row['Sent'] cal.ID = row['ID'] cal.uuid = row['uuid'] unsent_ins_cal_status.append(cal) return unsent_ins_cal_status
def onUpdate(): if NetworkInterface.GetIsNetworkAvailable(): try: response = None stream = None try: response = request.GetResponse() stream = response.GetResponseStream() doc = XmlDocument() doc.Load(stream) for entryXmlNode in doc.GetElementsByTagName("entry"): entry = Entry() for xmlNode in entryXmlNode.ChildNodes: if xmlNode.Name.Equals("title"): entry.Title = xmlNode.InnerText elif xmlNode.Name.Equals("issued"): entry.Created = DateTime.Parse( xmlNode.InnerText) elif xmlNode.Name.Equals("modified"): entry.Modified = DateTime.Parse( xmlNode.InnerText) elif xmlNode.Name.Equals("link"): for attribute in xmlNode.Attributes: if attribute.Name.Equals("href"): entry.Resource = Uri(attribute.Value) elif xmlNode.Name.Equals("author"): for childXmlNode in xmlNode.ChildNodes: if childXmlNode.Name.Equals("name"): entry.Author = childXmlNode.InnerText entry.Image = Uri( "http://www.google.co.jp/options/icons/gmail.gif") entryList.Add(entry) finally: if stream is not None: stream.Close() if response is not None: response.Close() except Exception, e: Trace.WriteLine(e.clsException.Message) Trace.WriteLine(e.clsException.StackTrace)
def switch_data_to_date(args, arg_opt): ''' Pull a date from the command line ''' try: return DateTime.Parse(switch_data(args, arg_opt)) except: return None
def gettestendDate(startDate, numofDays): import clr from System import DateTime endDate = None if startDate is not None: parsedDate = DateTime.Parse(startDate) endDate = parsedDate.AddDays(numofDays) return endDate
def onUpdate(): if NetworkInterface.GetIsNetworkAvailable(): try: response = None stream = None try: response = request.GetResponse() stream = response.GetResponseStream() doc = XmlDocument() doc.Load(stream) for itemXmlNode in doc.GetElementsByTagName("item"): entry = Entry() epicenter = None maxLevel = None for xmlNode in itemXmlNode.ChildNodes: if xmlNode.Name.Equals("link"): entry.Resource = Uri(xmlNode.InnerText) elif xmlNode.Name.Equals("description"): entry.Description = xmlNode.InnerText elif xmlNode.Name.Equals("tenkiJP:earthquake"): for attribute in xmlNode.Attributes: if attribute.Name.Equals("epicenter"): epicenter = attribute.Value elif attribute.Name.Equals("max_level"): maxLevel = attribute.Value elif attribute.Name.Equals( "outbreak_datetime"): entry.Created = entry.Modified = DateTime.Parse( attribute.Value) if epicenter is not None: if String.IsNullOrEmpty(maxLevel): maxLevel = "N/A" if CultureInfo.CurrentCulture.Equals( CultureInfo.GetCultureInfo("ja-JP")): entry.Title = String.Format( "震度{0} - {1}", maxLevel, epicenter) else: entry.Title = String.Format( "Intensity {0} - {1}", maxLevel, epicenter) entryList.Add(entry) finally: if stream is not None: stream.Close() if response is not None: response.Close() except Exception, e: Trace.WriteLine(e.clsException.Message) Trace.WriteLine(e.clsException.StackTrace)
def getFilesYoungerThan(dir, younger_than=0): if exists(dir): files = Directory.GetFiles(dir) date_to_check = DateTime.Parse( DateTime.Now.AddDays(-younger_than).ToString("yyyy.MM.dd")) files_of_age = [] for file in files: file = FileInfo(file) print file result = DateTime.Compare(file.CreationTime, date_to_check) if result < 0: relationship = "is earlier than %s" % date_to_check elif result == 0: relationship = "is the same time as %s" % date_to_check files_of_age.append(file) else: relationship = "is later than %s" % date_to_check files_of_age.append(file) print relationship return files_of_age
def DateTime(datetime): """ Converts Python's `datetime.datetime` class into C#'s `System.DateTime` struct. Parameter ---------- datetime : `datetime.datetime`. Example -------- Constructing `System.DateTime` from `datetime.datetime` of Python. >>> now = datetime.now() >>> cs_now = DateTime(now) >>> cs_now 3/26/2021 10:02:22 PM """ if not isinstance(datetime, PyDateTime): raise TypeError("Only datetime.datetime is allowed") return CsDateTime.Parse(datetime.isoformat())
def NoonCrt(start, end): '''中午时间校正 ''' crtHour = 0 if start.CompareTo(DateTime.Parse('12:00:00')) == -1: if end.CompareTo(DateTime.Parse('13:00:00')) in (-1, 0): crtHour = float(end.ToUniversalTime().Ticks - DateTime.Parse( '13:00:00').ToUniversalTime().Ticks) / 10000000 / 3600 else: crtHour = 1 elif start.CompareTo( DateTime.Parse('12:00:00')) in (0, 1) and start.CompareTo( DateTime.Parse('13:00:00')) == -1: crtHour = float( DateTime.Parse('13:00:00').ToUniversalTime().Ticks - start.ToUniversalTime().Ticks) / 10000000 / 3600 return crtHour
def test_should_write_set_of_working_hours_to_report(self): self.writer.write(new_workinghours("08:15", "16:15")) assert len(self.accessor.hours_written) == 2 assert self.accessor.hours_written[0] == DateTime.Parse("8:15") assert self.accessor.hours_written[1] == DateTime.Parse("16:15")
def DataChanged(e): if e.Key == 'FApplyType': applyType = this.View.BillModel.GetValue("FApplyType") if applyType == '1': # 申请类别为 现用 this.View.GetControl('F_ora_FlowLayout_PlanOffTime').Visible = False this.View.GetControl('F_ora_FlowLayout_PlanBackTime').Visible = False this.View.GetControl('F_ora_FlowLayout_Datetime').Visible = True elif applyType == '2': # 申请类别为 外借 this.View.GetControl('F_ora_FlowLayout_PlanOffTime').Visible = True this.View.GetControl('F_ora_FlowLayout_PlanBackTime').Visible = True this.View.GetControl('F_ora_FlowLayout_Datetime').Visible = False FCreateDate1 = this.View.BillModel.GetValue('FCreateDate1') Now = DateTime.Parse(str(FCreateDate1)) # 控制时间显示 FDatetime = this.View.BillModel.GetValue('FDatetime') FPlanOffTime = this.View.BillModel.GetValue('FPlanOffTime') FPlanBackTime = this.View.BillModel.GetValue('FPlanBackTime') FRealOffTime = this.View.BillModel.GetValue('FRealOffTime') FRealBackTime = this.View.BillModel.GetValue('FRealBackTime') # 印章使用时间 if e.Key == 'FDatetime': if DateTime.Parse(str(FDatetime)).CompareTo(Now) == -1: this.View.BillModel.SetValue('FDatetime', Now.ToString()) this.View.ShowMessage('印章使用时间不能早于当前时间!') # 计划带离时间 if e.Key == 'FPlanOffTime': if DateTime.Parse(str(FPlanOffTime)).CompareTo(Now) == -1: this.View.BillModel.SetValue('FPlanOffTime', Now.ToString()) this.View.ShowMessage('计划带离时间不能小于当前时间!') elif FPlanBackTime != None and DateTime.Parse(str(FPlanOffTime)).CompareTo(DateTime.Parse(str(FPlanBackTime))) == 1: this.View.BillModel.SetValue('FPlanOffTime', str(FPlanBackTime)) this.View.ShowMessage('计划带离时间不能大于计划归还时间!') # 计划归还时间 if e.Key == 'FPlanBackTime': if DateTime.Parse(str(FPlanBackTime)).CompareTo(Now) == -1: this.View.BillModel.SetValue('FPlanBackTime', str(Now)) this.View.ShowMessage('计划归还时间不能早于当前时间!') elif FPlanOffTime != None and DateTime.Parse(str(FPlanOffTime)).CompareTo(DateTime.Parse(str(FPlanBackTime))) == 1: this.View.BillModel.SetValue('FPlanBackTime', str(FPlanOffTime)) this.View.ShowMessage('计划归还时间不能小于计划带离时间!') # 实际带离时间 if e.Key == 'FRealOffTime': if DateTime.Parse(str(FRealOffTime)).CompareTo(Now) == -1: this.View.BillModel.SetValue('FRealOffTime', str(Now)) this.View.ShowMessage('实际带离时间不能小于申请时间!') elif FRealBackTime != None and DateTime.Parse(str(FRealOffTime)).CompareTo(DateTime.Parse(str(FRealBackTime))) == 1: this.View.BillModel.SetValue('FRealOffTime', str(FRealBackTime)) this.View.ShowMessage('实际带离时间不能大于实际归还时间!') # 实际归还时间 if e.Key == 'FRealBackTime': if DateTime.Parse(str(FRealBackTime)).CompareTo(Now) == -1: this.View.BillModel.SetValue('FRealBackTime', str(Now)) this.View.ShowMessage('实际带离时间不能小于申请时间!') elif FRealOffTime != None and DateTime.Parse(str(FRealOffTime)).CompareTo(DateTime.Parse(str(FRealBackTime))) == 1: this.View.BillModel.SetValue('FRealBackTime', str(FRealOffTime)) this.View.ShowMessage('实际带离时间不能大于实际归还时间!')
def DownloadYr(spreadsheetPath, worksheetName, hours): """ <Script> <Author>ANK</Author> <Description>Download precipitation forecast from Yr.no based on mapping in a spreadsheet</Description> <Parameters> <Parameter name="spreadsheetPath" type="string">Path to spreadsheet containing mapping to website</Parameter> <Parameter name="worksheetName" type="string">workshseet name</Parameter> <Parameter name="hours" type="int">number of hours to convert from UTC to local time</Parameter> </Parameters> </Script> """ try: # spreadsheetPath = '/DataCalculation/YR' if (spreadsheetPath[0] != '/'): spreadsheetPath = '/' + spreadsheetPath spreadsheet = spreadsheetMgr.OpenSpreadsheet(spreadsheetPath) rowNo = 1 # worksheetName = 'sheet1' while True: # There is one station on each row.. StationName = spreadsheetMgr.GetCellValue(spreadsheet, worksheetName, rowNo, 0) # Stop reading the spreadsheet when a row contains no station name. if (StationName == None or StationName == ''): break StationName = StationName.Trim() url = spreadsheetMgr.GetCellValue(spreadsheet, worksheetName, rowNo, 1).Trim() path = spreadsheetMgr.GetCellValue(spreadsheet, worksheetName, rowNo, 2) types = spreadsheetMgr.GetCellValue(spreadsheet, worksheetName, rowNo, 3).split(";") if url[-12:] != 'forecast.xml': if url[-1] != '/': url = url + '/' url = url + 'forecast.xml' _logprint('fetching data from Yr.no for station ' + StationName) _logprint(url) response = urllib.urlopen(url) xml = response.read() _logprint("loading xml...") doc = XmlDocument() doc.LoadXml(xml) for typ in types: targetts = tsMgr.TimeSeriesList.Fetch(path) if targetts == None: targetts = tsMgr.TimeSeriesList.CreateNew(path) if typ == "precipitation": targetts.YAxisVariable = "Rainfall" elif typ == "pressure": targetts.YAxisVariable = "Pressure" targetts.SetYAxisUnit("hPa", False) elif typ == "windSpeed": targetts.YAxisVariable = "Wind speed" elif typ == "windDirection": targetts.YAxisVariable = "Wind Direction" elif typ == "temperature": targetts.YAxisVariable = "Temperature" else: targetts = targetts.Clone() vplist = [] t = "" forecast = doc.GetElementsByTagName("forecast")[0] table = forecast.GetElementsByTagName("tabular")[0] for t in table.GetElementsByTagName("time"): tim = t.Attributes["to"].Value p = t.GetElementsByTagName(typ)[0] precip = p.Attributes["value"].Value vp = targetts.CreateNew() vp.XValue = DateTime.Parse(tim).AddHours( hours) # convert to local time GMT +2 vp.YValue = Convert.ToDouble(precip, CultureInfo.InvariantCulture) _logprint(" " + vp.XValue.ToString('yyyy-MM-dd HH:mm:ss') + "; " + vp.YValue.ToString()) vplist.append(vp) targetts.SetData(vplist) TargetGroupPath = '/'.join(path.split('/')[0:-1]) targetts.Name = targetts.Name + "_" + typ _logprint("Copy " + targetts.Name + " to " + TargetGroupPath + " with " + str(targetts.Count) + " timesteps") tsMgr.CopyTimeSeries(targetts, TargetGroupPath, TimeSeriesCopyAction.CopyDataInPeriod) rowNo = rowNo + 1 _logprint("Done") except Exception, e: _logprint("ERROR: %s" % (str(e)))
def __init__(self, dbAbonent, xmlAbonent, user): self.db = misbus.get_internal_remote(dbAbonent) self.user = self.db.execute_query( 'select id from _s_user where kod={0}'.format(user)).data[0][0] self.server = self.db.execute_query( 'select top 1 ID_Server1 from _a_Option ').data[0][0] remote = misbus.get_external_remote(xmlAbonent) operation = remote.get_operation("GetAllPartsData") #Формирование пакета Table = self.db.execute_query("select * from {0}".format( self.tableName)).data for row in Table: self.dbTable.append({ 'ID': row[0], 'ID1': row[1], 'ID_SERVER': row[2], 'ID_LOGIN': row[3], 'DATETIME_C': row[4], 'C1ID': row[5], 'IDNOMENCLATURE': row[6], 'RELEASEDATE': row[7], 'EXPIRATIONDATE': row[8], 'EXTERNALNAME': row[9], 'IDPROIZV': row[10], 'IDCOUNTRY': row[11] }) op_input = operation.build_input_envelope({'name': "GetAllPartsData"}) op_result = operation.execute_and_parse(op_input) #парсинг XML xmldata = op_result.select_all('//PartData') lowerDate = DateTime.ParseExact("01/01/1753", 'dd/mm/yyyy', None) highDate = DateTime.ParseExact("12/31/9999", 'mm/dd/yyyy', None) for answer in xmldata: dictionary = {} s = answer.select('*/ReleaseDate').text releaseDate = None if s != None: try: releaseDate = DateTime.Parse(s) except Exception: releaseDate = None if releaseDate != None: dictionary['RELEASEDATE'] = releaseDate expirationDate = None s = answer.select('*/ExpirationDate').text if s != None: try: expirationDate = DateTime.Parse(s) except Exception: expirationDate = None if expirationDate > lowerDate and expirationDate < highDate: dictionary['EXPIRATIONDATE'] = expirationDate nomenclature = answer.select('*/IDNomenclature').text if nomenclature != None: dictionary['IDNOMENCLATURE'] = nomenclature external = answer.select('*/ExternalName').text if external != None: dictionary['EXTERNALNAME'] = external proizv = answer.select('*/IDManufacturer').text if proizv != None: dictionary['IDPROIZV'] = proizv country = answer.select('*/IDCountry').text if country != None: dictionary['IDCOUNTRY'] = country C1ID = answer.select('*/ID').text if C1ID != None: dictionary['C1ID'] = C1ID self.xmlData.append(dictionary) '''
def onDispatch(task): global httpListener if task.Exception is None: httpListener.GetContextAsync().ContinueWith[List[Entry]]( Func[Task[HttpListenerContext], List[Entry]](onDispatch), TaskContinuationOptions.LongRunning).ContinueWith( Action[Task[List[Entry]]](onCompleted), context) try: if task.Result.Request.HttpMethod.Equals( WebRequestMethods.Http.Post ) and task.Result.Request.Url.AbsolutePath.Equals( "/alert"): if task.Result.Request.ContentType.Equals( "application/json"): stream = None streamReader = None try: stream = task.Result.Request.InputStream streamReader = StreamReader(stream) jsonArray = JsonDecoder.decode( streamReader.ReadToEnd()) if jsonArray is not None and clr.GetClrType( Array).IsInstanceOfType(jsonArray): entryList = List[Entry]() for obj in jsonArray: if clr.GetClrType(Dictionary[ String, Object]).IsInstanceOfType(obj): entry = Entry() if obj.ContainsKey( "resource" ) and clr.GetClrType( String).IsInstanceOfType( obj["resource"]): entry.Resource = Uri( obj["resource"]) if obj.ContainsKey( "title" ) and clr.GetClrType( String).IsInstanceOfType( obj["title"]): entry.Title = obj["title"] if obj.ContainsKey( "description" ) and clr.GetClrType( String).IsInstanceOfType( obj["description"]): entry.Description = obj[ "description"] if obj.ContainsKey( "author" ) and clr.GetClrType( String).IsInstanceOfType( obj["author"]): entry.Author = obj["author"] if obj.ContainsKey( "created" ) and clr.GetClrType( String).IsInstanceOfType( obj["created"]): entry.Created = DateTime.Parse( obj["created"]) if obj.ContainsKey( "modified" ) and clr.GetClrType( String).IsInstanceOfType( obj["modified"]): entry.Modified = DateTime.Parse( obj["modified"]) if obj.ContainsKey( "image" ) and clr.GetClrType( String).IsInstanceOfType( obj["image"]): entry.Image = Uri(obj["image"]) if obj.ContainsKey( "tags") and clr.GetClrType( Array ).IsInstanceOfType( obj["tags"]): for o in obj["tags"]: if clr.GetClrType( String ).IsInstanceOfType(o): entry.Tags.Add(o) entryList.Add(entry) else: task.Result.Response.StatusCode = Convert.ToInt32( HttpStatusCode.BadRequest) return None return entryList else: task.Result.Response.StatusCode = Convert.ToInt32( HttpStatusCode.BadRequest) finally: if streamReader is not None: streamReader.Close() if stream is not None: stream.Close() else: task.Result.Response.StatusCode = Convert.ToInt32( HttpStatusCode.UnsupportedMediaType) else: task.Result.Response.StatusCode = Convert.ToInt32( HttpStatusCode.Forbidden) except Exception, e: Trace.WriteLine(e.clsException.Message) Trace.WriteLine(e.clsException.StackTrace) finally:
def merge(left, right, key, order): # init return list ret = [] # init position in left and right lists leftPos = 0 rightPos = 0 # get the length of the two lists lenLeft = len(left) lenRight = len(right) # merge the lists if (order == None or order == "0"): while (leftPos < lenLeft and rightPos < lenRight): if (String.Compare(key, "SubmitDateTime", True) != 0): # Normal String Compare if (left[leftPos] == None): leftPos += 1 elif (right[rightPos] == None): rightPos += 1 elif (String.Compare(left[leftPos][key], right[rightPos][key], True) <= 0): ret.append(left[leftPos]) leftPos += 1 else: ret.append(right[rightPos]) rightPos += 1 else: # Compare Dates if (left[leftPos] == None): leftPos += 1 elif (right[rightPos] == None): rightPos += 1 else: try: if (DateTime.Compare( DateTime.Parse(left[leftPos][key]), DateTime.Parse(right[rightPos][key])) >= 0): ret.append(left[leftPos]) leftPos += 1 else: ret.append(right[rightPos]) rightPos += 1 except: leftPos += 1 else: while (leftPos < lenLeft and rightPos < lenRight): if (String.Compare(key, "SubmitDateTime", True) != 0): # Normal String Compare if (left[leftPos] == None): leftPos += 1 elif (right[rightPos] == None): rightPos += 1 elif (String.Compare(left[leftPos][key], right[rightPos][key], True) >= 0): ret.append(left[leftPos]) leftPos += 1 else: ret.append(right[rightPos]) rightPos += 1 else: # Compare Dates if (left[leftPos] == None): leftPos += 1 elif (right[rightPos] == None): rightPos += 1 else: try: if (DateTime.Compare( DateTime.Parse(left[leftPos][key]), DateTime.Parse(right[rightPos][key])) <= 0): ret.append(left[leftPos]) leftPos += 1 else: ret.append(right[rightPos]) rightPos += 1 except: leftPos += 1 # extend ret with the remaining list if (leftPos < lenLeft): while (leftPos < lenLeft): if (left[leftPos] == None): leftPos += 1 else: ret.append(left[leftPos]) leftPos += 1 else: while (rightPos < lenRight): if (right[rightPos] == None): rightPos += 1 else: ret.append(right[rightPos]) rightPos += 1 return ret
def __main__(dlArgs, qsArgs): returnVal = "" sb = StringBuilder() # Get the args egosort = qsArgs["ego"] if "ego" in qsArgs else None primarysort = qsArgs["psort"] if "psort" in qsArgs else None primarysortorder = qsArgs["psord"] if "psord" in qsArgs else None secondarysort = qsArgs["ssort"] if "ssort" in qsArgs else None secondarysortorder = qsArgs["ssord"] if "ssord" in qsArgs else None pulseaddress = qsArgs["pulse"] if "pulse" in qsArgs else None lastupdate = qsArgs["update"] if "update" in qsArgs else None nonplist = qsArgs["plist"] if "plist" in qsArgs else None # parse the last update if (lastupdate != None): lastupdate = fromPlatformIndDateTime( lastupdate ) #BUG possibility when starting the app for the first time - unable to reproduce # check if plist is wanted or not if (nonplist != None): usePlist = False else: usePlist = True plugins = {} users = {} statuses = {} groups = {} pools = {} thisAddress = ClientUtils.GetMacAddress() jobs = WebServiceUtils.GetJobs() # do the sorts if (secondarysort != None): jobs = SortDictArrayByKey(jobs, secondarysort, secondarysortorder) if (primarysort != None): jobs = SortDictArrayByKey(jobs, primarysort, primarysortorder) if (egosort != None): jobs = EgoSortDictArray(jobs, egosort) if (usePlist == False): sb.AppendLine("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>") sb.AppendLine("<jobList>") # add each job for job in jobs: if (job != None and job["Status"] != "Deleted"): try: lastJobUpdate = DateTime.Parse(job["LastWriteTime"]) except: lastJobUpdate = None # if there was no update time given, or the update time is before this jobs last update if (lastupdate == None or pulseaddress != thisAddress or DateTime.Compare(lastupdate, lastJobUpdate) < 0): sb.AppendLine("\t<job>") sb.AppendLine("\t\t<name>" + SecurityElement.Escape(job["Name"]) + "</name>") sb.AppendLine("\t\t<comment>" + SecurityElement.Escape(job["Comment"]) + "</comment>") sb.AppendLine("\t\t<plugin>" + job["PluginName"] + "</plugin>") sb.AppendLine("\t\t<uname>" + job["UserName"] + "</uname>") sb.AppendLine("\t\t<status>" + job["Status"] + "</status>") sb.AppendLine("\t\t<jobid>" + job["JobId"] + "</jobid>") sb.AppendLine("\t\t<taskcount>" + job["TaskCount"] + "</taskcount>") sb.AppendLine("\t\t<completed>" + job["CompletedChunks"] + "</completed>") sb.AppendLine("\t\t<errors>" + job["ErrorReports"] + "</errors>") sb.AppendLine("\t\t<group>" + job["Group"] + "</group>") sb.AppendLine("\t\t<pool>" + job["Pool"] + "</pool>") sb.AppendLine("\t</job>") # if the job is up to date, just print it's id to retrieve its data else: sb.AppendLine("\t<string>" + job["JobId"] + "</string>") plugins[job["PluginName"]] = True users[job["UserName"]] = True statuses[job["Status"]] = True groups[job["Group"]] = True pools[job["Pool"]] = True # meta dictionary sb.AppendLine("\t<meta>") # add each section listKeys("plugin", plugins, sb, False) listKeys("uname", users, sb, False) listKeys("status", statuses, sb, False) listKeys("group", groups, sb, False) listKeys("pool", pools, sb, False) # add the new update time sb.AppendLine("\t\t<update>" + toPlatformIndDateTime(DateTime.Now) + "</update>") # add Pulse's mac address sb.AppendLine("\t\t<pulse>" + thisAddress + "</pulse>") sb.AppendLine("\t</meta>") sb.AppendLine("</jobList>") returnVal = sb.ToString() else: sb.AppendLine("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>") sb.AppendLine( "<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">" ) sb.AppendLine("<plist version=\"1.0\">") sb.AppendLine("<dict>") # jobs array sb.AppendLine("\t<key>jobs</key>") sb.AppendLine("\t<array>") # add each job for job in jobs: if (job != None and job["Status"] != "Deleted"): try: lastJobUpdate = DateTime.Parse(job["LastWriteTime"]) except: lastJobUpdate = None # if there was no update time given, or the update time is before this jobs last update if (lastupdate == None or pulseaddress != thisAddress or DateTime.Compare(lastupdate, lastJobUpdate) < 0): sb.AppendLine("\t\t<dict>") sb.AppendLine("\t\t\t<key>name</key><string>" + SecurityElement.Escape(job["Name"]) + "</string>") sb.AppendLine("\t\t\t<key>comment</key><string>" + SecurityElement.Escape(job["Comment"]) + "</string>") sb.AppendLine("\t\t\t<key>plugin</key><string>" + job["PluginName"] + "</string>") sb.AppendLine("\t\t\t<key>uname</key><string>" + job["UserName"] + "</string>") sb.AppendLine("\t\t\t<key>status</key><string>" + job["Status"] + "</string>") sb.AppendLine("\t\t\t<key>jobid</key><string>" + job["JobId"] + "</string>") sb.AppendLine("\t\t\t<key>taskcount</key><string>" + job["TaskCount"] + "</string>") sb.AppendLine("\t\t\t<key>completed</key><string>" + job["CompletedChunks"] + "</string>") sb.AppendLine("\t\t\t<key>errors</key><string>" + job["ErrorReports"] + "</string>") sb.AppendLine("\t\t\t<key>group</key><string>" + job["Group"] + "</string>") sb.AppendLine("\t\t\t<key>pool</key><string>" + job["Pool"] + "</string>") sb.AppendLine("\t\t</dict>") # if the job is up to date, just print it's id to retrieve its data else: sb.AppendLine("\t\t<string>" + job["JobId"] + "</string>") plugins[job["PluginName"]] = True users[job["UserName"]] = True statuses[job["Status"]] = True groups[job["Group"]] = True pools[job["Pool"]] = True sb.AppendLine("\t</array>") # meta dictionary sb.AppendLine("\t<key>meta</key>") sb.AppendLine("\t<dict>") # add each section listKeys("plugin", plugins, sb, True) listKeys("uname", users, sb, True) listKeys("status", statuses, sb, True) listKeys("group", groups, sb, True) listKeys("pool", pools, sb, True) # add the new update time sb.AppendLine("\t\t<key>update</key>") sb.AppendLine("\t\t<string>" + toPlatformIndDateTime(DateTime.Now) + "</string>") # add Pulse's mac address sb.AppendLine("\t\t<key>pulse</key>") sb.AppendLine("\t\t<string>" + thisAddress + "</string>") sb.AppendLine("\t</dict>") sb.AppendLine("</dict>") sb.AppendLine("</plist>") returnVal = sb.ToString() return returnVal