code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
import datetime import requests import numpy as np import pandas as pd import sys # August 3, 2015: Updated the getNipa() method to accomodate possible differences in data availability for series in tables. # Cleaned up and organized the code substantially. class initialize: def __init__(self,apiKey=None): ''' Saves the API key.''' self.apiKey = apiKey # 1. Methods for getting information about the available datasets, parameters, and parameter values. def getDataSetList(self): '''Method returns a list of describing the datasets available through the BEA API. No arguments''' r = requests.get('http://www.bea.gov/api/data?&UserID='+self.apiKey+'&method=GETDATASETLIST&ResultFormat=JSON&') rJson = r.json() lines='Datasets available through the BEA API:\n\n' n=1 dataSetList = [] for element in rJson['BEAAPI']['Results']['Dataset']: if np.mod(n,5)==0: lines = lines+str(n).ljust(4,' ')+element['DatasetName'].ljust(20,' ') +': '+element['DatasetDescription']+'\n\n' dataSetList.append(element['DatasetName']) else: lines = lines+str(n).ljust(4,' ')+element['DatasetName'].ljust(20,' ') +': '+element['DatasetDescription']+'\n' dataSetList.append(element['DatasetName']) n+=1 print(lines) self.dataSets = lines self.dataSetList = dataSetList def getParameterList(self,dataSetName): '''Method returns a list of the parameters for a given dataset. Argument: one of the dataset names returned by getDataSetList().''' r = requests.get('http://www.bea.gov/api/data?&UserID='+self.apiKey+'&method=GETPARAMETERLIST&datasetname='+dataSetName+'&ResultFormat=JSON&') rJson = r.json() lines = 'Parameters for the '+dataSetName+' dataset.\n\n' strWidth = 25 descrWidth = 50 parameterList = [] def splitString(origString, maxLength): splitLines = [] line = '' for word in origString.split(' '): if len(line)+1+len(word)<maxLength: line = line+word+' ' else: splitLines.append(line) line = word+' ' if len(line) != 0: splitLines.append(line) return splitLines for element in rJson['BEAAPI']['Results']['Parameter']: elementKeys = list(element.keys()) lines = lines+'Parameter name'.ljust(strWidth,' ') +' '+element['ParameterName']+'\n' split = splitString(element['ParameterDescription'],descrWidth) for n,line in enumerate(split): if n ==0: lines = lines+'Description'.ljust(strWidth,' ') + ' '+line+'\n' else: lines = lines+' '.ljust(strWidth,' ') + ' '+line+'\n' parameterList.append(element['ParameterName']) if element['ParameterIsRequiredFlag']==0: lines = lines+'Required?'.ljust(strWidth,' ') + ' No'+'\n' else: lines = lines+'Required?'.ljust(strWidth,' ') + ' Yes'+'\n' if 'AllValue' in elementKeys: if element['AllValue']=='': lines = lines+'\"All\" Value'.ljust(strWidth,' ') + ' N/A'+'\n' else: lines = lines+'\"All\" Value'.ljust(strWidth,' ') +' '+element['AllValue']+'\n' # if element['MultipleAcceptedFlag']==0: # lines = lines+'Multiple (list) accepted?'.ljust(strWidth,' ') + ' No'+'\n' # else: # lines = lines+'Multiple (list) accepted?'.ljust(strWidth,' ') + ' Yes'+'\n' lines = lines+'Data type'.ljust(strWidth,' ') + ' '+element['ParameterDataType']+'\n' if 'ParameterDefaultValue' in elementKeys: if element['ParameterDefaultValue']=='': lines = lines+'Default value'.ljust(strWidth,' ') + ' N/A'+'\n\n\n' else: lines = lines+'Default value'.ljust(strWidth,' ') + ' '+element['ParameterDefaultValue']+'\n\n\n' else: lines = lines+'\n\n' print(lines) self.parameters = lines self.parameterList = parameterList def getParameterValues(self,dataSetName, parameterName): '''Method returns a list of the values accepted for a given parameter of a dataset. Arguments: one of the dataset names returned by getDataSetList() and a parameter returned by getParameterList().''' r = requests.get('http://bea.gov/api/data?&UserID='+self.apiKey+'&method=GetParameterValues&datasetname='+dataSetName+'&ParameterName='+parameterName+'&') rJson = r.json() lines='Values accepted for '+parameterName+' in dataset '+dataSetName+':\n\n' if dataSetName.lower() == 'nipa' and parameterName.lower() == 'showmillions' and 'ParamValue' not in rJson['BEAAPI']['Results'].keys(): lines+= 'ShowMillions'.ljust(20,' ')+': N\n' lines+= 'Description'.ljust(20,' ')+': Units in billions of USD (default)\n\n' lines+= 'ShowMillions'.ljust(20,' ')+': Y\n' lines+= 'Description'.ljust(20,' ')+': Units in millions of USD\n\n' else: descrWidth = 50 def splitString(origString, maxLength): splitLines = [] line = '' for word in origString.split(' '): if len(line)+1+len(word)<maxLength: line = line+word+' ' else: splitLines.append(line) line = word+' ' if len(line) != 0: splitLines.append(line) return splitLines columnNames = [] for n,element in enumerate(rJson['BEAAPI']['Results']['ParamValue']): for key in element.keys(): if key not in columnNames: columnNames.append(key) data = np.zeros([n,len(columnNames)]) data[:] = np.nan tempFrame = pd.DataFrame(data,columns = columnNames) for n,element in enumerate(rJson['BEAAPI']['Results']['ParamValue']): for key,value in element.items(): tempFrame.loc[n,key] = element[key] # Sort tempFrame if the parameter falls into one of a few special categories if dataSetName.lower() == 'nipa': if parameterName.lower() =='tableid': tempFrame.sort(columns = ['TableID']) elif parameterName.lower() =='year': tempFrame = tempFrame[['TableID','FirstAnnualYear','LastAnnualYear','FirstQuarterlyYear','LastQuarterlyYear','FirstMonthlyYear','LastMonthlyYear']] tempFrame.sort(columns = ['TableID']) elif dataSetName.lower() == 'fixedassets': if parameterName.lower() =='tableid': tempFrame.sort(columns = ['TableID']) elif parameterName.lower() =='year': tempFrame = tempFrame[['TableID','FirstAnnualYear','LastAnnualYear']] tempFrame.sort(columns = ['TableID']) elif dataSetName.lower() == 'gdpbyindustry': if parameterName.lower() =='tableid': tempFrame.sort(columns = ['Key']) for i in tempFrame.index: for c in tempFrame.columns: split = splitString(tempFrame.loc[i,c],descrWidth) for n, words in enumerate(split): if n==0: try: lines+=c.ljust(20,' ')+': '+str(int(words))+'\n' except: lines+=c.ljust(20,' ')+': '+str(words)+'\n' else: try: lines+=''.ljust(20,' ')+' '+str(words)+'\n' except: lines+=''.ljust(20,' ')+' '+str(words)+'\n' lines+='\n' print(lines) self.parameterValues = lines # 2. Methods for retreiving data. # 2.1 Regional Data (statistics by state, county, and MSA) def getRegionalData(self,KeyCode=None,GeoFips='STATE',Year='ALL'): '''Retrieve state and regional data. Name Type Required? Multiple values? "All" Value Default KeyCode int yes no N/A GeoFips str no yes 'STATE' or 'COUNTY' or 'MSA' STATE Year int no yes "ALL" ALL ''' # if type(KeyCode)==list: # KeyCode = ','.join(KeyCode) # if type(Year)==list: # Year = [str(y) for y in Year] # Year = ','.join(Year) # if type(GeoFips)==list: # GeoFips = ','.join(GeoFips) uri = 'http://bea.gov/api/data/?UserID='+self.apiKey+'&method=GetData&datasetname=RegionalData&KeyCode='+str(KeyCode)+'&Year='+str(Year)+'&GeoFips='+str(GeoFips)+'&ResultFormat=JSON&' r = requests.get(uri) rJson = r.json() dataDict = {} # dates = [] # YearList = [] # name ='' columnNames = [] dates = [] try: for element in rJson['BEAAPI']['Results']['Data']: if element['GeoName'] not in columnNames: columnNames.append(element['GeoName']) date = convertDate(element['TimePeriod'],'A') if date not in dates: dates.append(date) data = np.zeros([len(dates),len(columnNames)]) data[:] = np.nan frame = pd.DataFrame(data,columns = columnNames, index = dates) for element in rJson['BEAAPI']['Results']['Data']: date = convertDate(element['TimePeriod'],'A') if 'DataValue' in element.keys(): frame.loc[date,element['GeoName']] = float(element['DataValue'].replace(',','')) frame = frame.sort_index() note = rJson['BEAAPI']['Results']['PublicTable']+' - '+rJson['BEAAPI']['Results']['Statistic']+' - '+rJson['BEAAPI']['Results']['UnitOfMeasure'] return {'note':note,'data':frame} except: print('Invalid input.',sys.exc_info()[0]) # 2.2 NIPA (National Income and Product Accounts) def getNipa(self,TableID=None,Frequency='A',Year='X',ShowMillions='N'): '''Retrieve data from a NIPA table. Name Type Required? "All" Value Default TableID int yes N/A None Frequency(A/Q) str yes N/A None Year int yes "X" "X" ShowMillions str no N/A 'N' ''' if Frequency=='M': print('Error: monthly Frequency available for NIPA tables.') uri = 'http://bea.gov/api/data/?UserID='+self.apiKey+'&method=GetData&datasetname=NIPA&TableID='+str(TableID)+'&Frequency='+Frequency+'&Year='+str(Year)+'&ShowMillions='+ShowMillions+'&ResultFormat=JSON&' r = requests.get(uri) rJson = r.json() columnNames = [] dates = [] try: for element in rJson['BEAAPI']['Results']['Data']: if element['LineDescription'] not in columnNames: columnNames.append(element['LineDescription']) date = convertDate(element['TimePeriod'],Frequency) if date not in dates: dates.append(date) data = np.zeros([len(dates),len(columnNames)]) data[:] = np.nan frame = pd.DataFrame(data,columns = columnNames, index = dates) for element in rJson['BEAAPI']['Results']['Data']: date = convertDate(element['TimePeriod'],Frequency) frame.loc[date,element['LineDescription']] = float(element['DataValue'].replace(',','')) frame = frame.sort_index() note = rJson['BEAAPI']['Results']['Notes'][0]['NoteText'] return {'note':note,'data':frame} except: print('Error: invalid input.') # # 3.3 NIUnderlyingDetail (National Income and Product Accounts) # def getNIUnderlyingDetail(self,TableID,Frequency='A',Year='X'): # if type(Year)==list: # Year = [str(y) for y in Year] # Year = ','.join(Year) # uri = 'http://bea.gov/api/data/?UserID='+apiKey+'&method=GetData&datasetname=NIUnderlyingDetail&TableID='+str(TableID)+'&Year='+str(Year)+'&Frequency='+str(Frequency)+'&ResultFormat=JSON&' # r = requests.get(uri) # rJson = r.json() # columnNames = [] # dates = [] # try: # 3.4 Fixed Assets def getFixedAssets(self,TableID=None,Year='X'): uri = 'http://bea.gov/api/data/?UserID='+self.apiKey+'&method=GetData&datasetname=FixedAssets&TableID='+str(TableID)+'&Year='+str(Year)+'&ResultFormat=JSON&' r = requests.get(uri) rJson = r.json() columnNames = [] dates = [] try: for element in rJson['BEAAPI']['Results']['Data']: if element['LineDescription'] not in columnNames: columnNames.append(element['LineDescription']) date = convertDate(element['TimePeriod'],'A') if date not in dates: dates.append(date) data = np.zeros([len(dates),len(columnNames)]) data[:] = np.nan frame = pd.DataFrame(data,columns = columnNames, index = dates) for element in rJson['BEAAPI']['Results']['Data']: date = convertDate(element['TimePeriod'],'A') frame.loc[date,element['LineDescription']] = float(element['DataValue'].replace(',','')) frame = frame.sort_index() note = rJson['BEAAPI']['Results']['Notes'][0]['NoteText'] return {'note':note,'data':frame} except: print('Error: invalid input.') # 3.5 # def getMne(self,DirectionOfInvestment=None,OwnershipLevel=None,NonbankAffiliatesOnly=None,Classification=None,Country='all',Industry='all',Year='all',State='all',SeriesID=0): # 3.6 Gross domestic product by industry def getGdpByIndustry(self,TableID =None, Industry='ALL',Frequency='A',Year = 'ALL'): uri = 'http://bea.gov/api/data/?UserID='+self.apiKey+'&method=GetData&datasetname=GDPbyIndustry&TableID='+str(TableID)+'&Industry='+str(Industry)+'&Frequency='+str(Frequency)+'&Year='+str(Year)+'&ResultFormat=JSON&' r = requests.get(uri) rJson = r.json() columnNames = [] dates = [] try: for element in rJson['BEAAPI']['Results']['Data']: if element['IndustrYDescription'] not in columnNames: columnNames.append(element['IndustrYDescription']) date = convertDate(element['Year'],Frequency) if date not in dates: dates.append(date) data = np.zeros([len(dates),len(columnNames)]) data[:] = np.nan frame = pd.DataFrame(data,columns = columnNames, index = dates) for element in rJson['BEAAPI']['Results']['Data']: date = convertDate(element['Year'],Frequency) frame.loc[date,element['IndustrYDescription']] = float(element['DataValue'].replace(',','')) frame = frame.sort_index() note = rJson['BEAAPI']['Results']['Notes'][0]['NoteText'] return {'note':note,'data':frame} except: print('Error: invalid input.') # 3.7 ITA: International transactions def getIta(self,Indicator=None,AreaOrCountry='ALL',Frequency='A',Year='ALL'): if Indicator=='ALL' and 'ALL' in AreaOrCountry: print('Warning: You may not select \'ALL\' for both Indicator and AreaOrCountry') else: uri = 'http://bea.gov/api/data/?UserID='+self.apiKey+'&method=GetData&datasetname=ita&Indicator='+str(Indicator)+'&AreaOrCountry='+str(AreaOrCountry)+'&Year='+str(Year)+'&ResultFormat=JSON&' r = requests.get(uri) rJson = r.json() columnNames = [] dates = [] try: if AreaOrCountry.lower() == 'all': columnNames = [] dates = [] for element in rJson['BEAAPI']['Results']['Data']: if element['AreaOrCountry'] not in columnNames: columnNames.append(element['AreaOrCountry']) date = convertDate(element['Year'],Frequency) if date not in dates: dates.append(date) data = np.zeros([len(dates),len(columnNames)]) data[:] = np.nan frame = pd.DataFrame(data,columns = columnNames, index = dates) for element in rJson['BEAAPI']['Results']['Data']: date = convertDate(element['Year'],Frequency) if len(element['DataValue'].replace(',',''))>0: frame.loc[date,element['AreaOrCountry']] = float(element['DataValue'].replace(',','')) else: frame.loc[date,element['AreaOrCountry']] = np.nan else: columnNames = [] dates = [] for element in rJson['BEAAPI']['Results']['Data']: if element['Indicator'] not in columnNames: columnNames.append(element['Indicator']) date = convertDate(element['Year'],Frequency) if date not in dates: dates.append(date) data = np.zeros([len(dates),len(columnNames)]) data[:] = np.nan frame = pd.DataFrame(data,columns = columnNames, index = dates) for element in rJson['BEAAPI']['Results']['Data']: date = convertDate(element['Year'],Frequency) if len(element['DataValue'].replace(',',''))>0: frame.loc[date,element['Indicator']] = float(element['DataValue'].replace(',','')) else: frame.loc[date,element['Indicator']] = np.nan frame = frame.sort_index() units = rJson['BEAAPI']['Results']['Data'][0]['CL_UNIT'] mult = rJson['BEAAPI']['Results']['Data'][0]['UNIT_MULT'] if int(mult) == 3: units = 'Thousands of '+units elif int(mult) == 6: units = 'Millions of '+units elif int(mult) == 9: units = 'Billions of '+units if Frequency.lower() == 'q': Notes = rJson['BEAAPI']['Results']['Notes'] for note in Notes: if note['NoteRef'] == 'Q': noteQ = note['NoteText'] units = units + ', '+ noteQ return {'note':units,'data':frame} except: print(rJson['BEAAPI']['Error']['ErrorDetail']['Description']) # 3.8 IIP: International investment position def getIip(self,TypeOfInvestment=None,Component=None,Frequency='A',Year='ALL'): uri = 'http://bea.gov/api/data/?UserID='+self.apiKey+'&method=GetData&datasetname=IIP&TypeOfInvestment='+str(TypeOfInvestment)+'&Component='+str(Component)+'&Year='+str(Year)+'&Frequency='+str(Frequency)+'&ResultFormat=JSON&' r = requests.get(uri) rJson = r.json() columnNames = [] dates = [] try: for element in rJson['BEAAPI']['Data']: if element['TimeSeriesDescription'] not in columnNames: columnNames.append(element['TimeSeriesDescription']) date = convertDate(element['TimePeriod'],Frequency) if date not in dates: dates.append(date) data = np.zeros([len(dates),len(columnNames)]) data[:] = np.nan frame = pd.DataFrame(data,columns = columnNames, index = dates) for element in rJson['BEAAPI']['Data']: date = convertDate(element['TimePeriod'],Frequency) if len(element['DataValue'].replace(',','')) ==0: frame.loc[date,element['TimeSeriesDescription']] = np.nan else: frame.loc[date,element['TimeSeriesDescription']] = float(element['DataValue'].replace(',','')) frame = frame.sort_index() units = rJson['BEAAPI']['Data'][0]['CL_UNIT'] mult = rJson['BEAAPI']['Data'][0]['UNIT_MULT'] if int(mult) == 3: units = 'Thousands of '+units elif int(mult) == 6: units = 'Millions of '+units elif int(mult) == 9: units = 'Billions of '+units return {'note':units,'date':frame} except: print('Error: invalid input.') # 3.9 Regional Income: detailed regional income and employment data sets. def getRegionalIncome(self,TableName=None,LineCode=None,GeoFips=None,Year ='ALL'): '''GeoFips can equal STATE COUNTY MSA MIC PORT DIV CSA''' uri = 'http://bea.gov/api/data/?UserID='+self.apiKey+'&method=GetData&datasetname=RegionalIncome&TableName='+str(TableName)+'&LineCode='+str(LineCode)+'&Year='+str(Year)+'&GeoFips='+str(GeoFips)+'&ResultFormat=JSON&' r = requests.get(uri) rJson = r.json() columnNames = [] dates = [] Frequency = 'A' try: for element in rJson['BEAAPI']['Results']['Data']: if element['GeoName'] not in columnNames: columnNames.append(element['GeoName']) date = convertDate(element['TimePeriod'],Frequency) if date not in dates: dates.append(date) data = np.zeros([len(dates),len(columnNames)]) data[:] = np.nan frame = pd.DataFrame(data,columns = columnNames, index = dates) for element in rJson['BEAAPI']['Results']['Data']: date = convertDate(element['TimePeriod'],Frequency) if len(element['DataValue'].replace(',','')) ==0: frame.loc[date,element['GeoName']] = np.nan else: frame.loc[date,element['GeoName']] = float(element['DataValue'].replace(',','')) frame = frame.sort_index() units = rJson['BEAAPI']['Results']['UnitOfMeasure'] return {'notes':units,'data':frame} except: print('Error: invalid input.') # 3.10 Regional product: detailed state and MSA product data sets def getRegionalProduct(self,Component=None,IndustryId=1,GeoFips='State',Year ='ALL'): '''GeoFips can equal either STATE or MSA''' uri = 'http://bea.gov/api/data/?UserID='+self.apiKey+'&method=GetData&datasetname=regionalProduct&Component='+str(Component)+'&IndustryId='+str(IndustryId)+'&Year='+str(Year)+'&GeoFips='+str(GeoFips)+'&ResultFormat=JSON&' r = requests.get(uri) rJson = r.json() columnNames = [] dates = [] Frequency = 'A' try: for element in rJson['BEAAPI']['Results']['Data']: if element['GeoName'] not in columnNames: columnNames.append(element['GeoName']) date = convertDate(element['TimePeriod'],Frequency) if date not in dates: dates.append(date) data = np.zeros([len(dates),len(columnNames)]) data[:] = np.nan frame = pd.DataFrame(data,columns = columnNames, index = dates) for element in rJson['BEAAPI']['Results']['Data']: date = convertDate(element['TimePeriod'],Frequency) if len(element['DataValue'].replace(',','')) ==0: frame.loc[date,element['GeoName']] = np.nan else: frame.loc[date,element['GeoName']] = float(element['DataValue'].replace(',','')) frame = frame.sort_index() note = rJson['BEAAPI']['Results']['Data'][0]['CL_UNIT'] return {'note':note,'date':frame} except: print('Error: invalid input.') # Auxiliary function. def convertDate(dateString,Frequency): '''Function for converting the date strings from BEA with quarter indicators into datetime format''' if Frequency=='A': month='01' elif Frequency=='Q': if dateString[-1]=='1': month='01' elif dateString[-1]=='2': month='04' elif dateString[-1]=='3': month='07' else: month='10' return datetime.datetime.strptime(dateString[0:4]+'-'+month+'-01','%Y-%m-%d')
letsgoexploring/beapy-package
beapy.py
Python
mit
25,953
#include <iostream> #include <seqan/align.h> using namespace seqan; using namespace std; int main() { typedef String<char> TSequence; // sequence type typedef Align<TSequence,ArrayGaps> TAlign; // align type typedef Row<TAlign>::Type TRow; // gapped sequence type TSequence seq1 = "ACGTCACCTC"; TSequence seq2 = "ACGGGCCTATC"; TAlign align; resize(rows(align), 2); assignSource(row(align,0),seq1); assignSource(row(align,1),seq2); std::cout << align; TRow &row1 = row(align,0); TRow &row2 = row(align,1); insertGaps(row1,2,2); insertGap(row1,5); insertGaps(row2,9,2); std::cout << align; typedef Iterator<TRow, Rooted>::Type TIt1; typedef Iterator<Rows<TAlign>::Type, Rooted>::Type TIt2; TIt2 it2 = begin(rows(align)); TIt1 it1; int gapCounter=0; while(!atEnd(it2)){ it1 = begin(row(align,position(it2))); while(!atEnd(it1)){ goNext(it1); if (isGap(*it2,position(it1))) gapCounter+=countGaps(it1); } goNext(it2); } cout << gapCounter << endl; }
bkahlert/seqan-research
raw/pmsb13/pmsb13-data-20130530/sources/qhuulr654q26tohr/2013-04-10T10-48-27.899+0200/sandbox/PMSB13/apps/5.0/5.0.cpp
C++
mit
1,130
# vim:ts=4:sts=4:sw=4:expandtab """The public API of satori.events. """ import hashlib import random import traceback from satori.objects import Object from satori.events.misc import Namespace from .dispatcher import Dispatcher from .protocol import KeepAlive, Disconnect, Attach, Detach, Map, Unmap, Send, Receive __all__ = ( 'Event', 'MappingId', 'QueueId', 'Manager', ) class Event(Namespace): """Describes an event. """ pass class MappingId(str): # pylint: disable-msg=R0904 """A (globally-unique) identifier of a mapping. """ def __new__(cls, value=None): if value is None: value = hashlib.md5(str(random.getrandbits(512))).hexdigest() return str.__new__(cls, value) class QueueId(str): # pylint: disable-msg=R0904 """A (globally-unique) identifier of an event queue. """ pass class Manager(Object): """Abstract. Manages Clients within a single process. """ def __init__(self): self.dispatcher = Dispatcher() def run(self): """Execute this Manager's event loop. """ handlers = { KeepAlive: self._handleKeepAlive, Attach: self._handleAttach, Detach: self._handleDetach, Map: self._handleMap, Unmap: self._handleUnmap, Send: self._handleSend, Receive: self._handleReceive, Disconnect: self._handleDisconnect, } while True: client = self.scheduler.next() if client is None: break try: command = client.recvCommand() except StopIteration: command = Disconnect() except Exception: print 'Exception in client, removing from queue' traceback.print_exc() self.scheduler.remove(client) else: handlers[command.__class__](command, client) def _handleKeepAlive(self, command, sender): raise NotImplementedError() def _handleDisconnect(self, command, sender): raise NotImplementedError() def _handleAttach(self, command, sender): raise NotImplementedError() def _handleDetach(self, command, sender): raise NotImplementedError() def _handleMap(self, command, sender): raise NotImplementedError() def _handleUnmap(self, command, sender): raise NotImplementedError() def _handleSend(self, command, sender): raise NotImplementedError() def _handleReceive(self, command, sender): raise NotImplementedError()
zielmicha/satori
satori.events/satori/events/api.py
Python
mit
2,752
<?php if (!isset($login) || $login->validated != '1') { include DIR."/php/controller/403.php"; die(); } else { function htmlHead() { ?> <script src="http://maps.google.com/maps/api/js"></script> <script src="/jslib/gmaps.js"></script> <style> #map, #panorama { height:450px; background:#6699cc; } </style> <?php } function mainContent() { global $login, $p, $message; $center=getCenter($p->findings); $init=[ 'res'=>summarize($p->findings), 'lat'=>$center->latitude, 'long'=>$center->longitude ] ?> <div class="row"> <div class="col-md-12"> <h2>Species map</h2> <h5><?= count($p->findings).' data found'?><?= ($center->errCount > 0) ? ', ('.$center->errCount.') has incomplete coordinates' : '' ?></h5> <div id="map"></div> </div> </div> <div id="init"><?php echo json_encode($init, JSON_UNESCAPED_SLASHES); ?></div> <div id="modalDetails" class="modal fade" tabindex="-1" role="dialog"> <div class="modal-dialog modal-lg"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> <h4 class="modal-title">Species Findings</h4> </div> <div class="modal-body"> <div id="details-panel" class="table-responsive"></div> </div> </div> </div> </div> <script src="/js/common/speciesmap.js"></script> <?php } function getCenter($coordinates) { $x=0; $y=0; $z=0; $count=count($coordinates); $errCount=0; if ($count == 0) return (object) ['longitude'=>0,'latitude'=>0,'count'=>0,'errCount'=>0]; foreach ($coordinates as $v) { if ($v->latitude == null || $v->longitude == null) { $count--; $errCount++; continue; } $lat = $v->latitude * M_PI / 180; $long = $v->longitude * M_PI / 180; $x += cos($lat) * cos($long); $y += cos($lat) * sin($long); $z += sin($lat); } //$x /= $count; $y /= $count; $z /= $count; //Ndak perlu. |$xyz| ndak akan ubah arah $base_r = sqrt($x*$x + $y*$y); $res = (object) [ 'longitude'=>atan2($y,$x) * 180/M_PI, 'latitude'=>atan2($z,$base_r) * 180/M_PI, 'count'=>$count, 'errCount'=>$errCount ]; return $res; } function tableRow($row) { return "<tr><td>$row->localname</td>" . "<td>".date('F Y',strtotime($row->survey_date))."</td>" . "<td>$row->iucn_status</td>" . "<td>$row->indo_status</td>" . "<td>$row->district</td></tr>"; } function summarize($findings) { $res = []; //localname, survey_month, survey_years, iucn_status, indo_status, district foreach ($findings as $v) { if ($v->latitude == null || $v->longitude == null) continue; $key = $v->latitude.','.$v->longitude; if (!isset($res[$key])) { $res[$key] = (object) [ 'latitude'=>$v->latitude, 'longitude'=>$v->longitude, 'count'=>1, 'info'=>"<table><thead><tr><th>Local Name</th><th>Survey Month</th><th>IUCN Status</th><th>Indonesia Status</th><th>District</th></thead><tbody>" .tableRow($v) ]; } else { $res[$key]->count++; $res[$key]->info .= tableRow($v); } } foreach ($res as $k=>$v) { $res[$k]->info.='</tbody></table>'; //$res[$k]->info = htmlentities($res[$k]->info); } return array_values($res); } $pageTitle = "Species Map"; include DIR.'/php/view/tulang.php'; }
fandisus/SSBIN
php/view/common/speciesmap.php
PHP
mit
3,611
module Mediadrawer module Rails VERSION = "0.0.2" end end
tracersoft/mediadrawer-rails
lib/mediadrawer/rails/version.rb
Ruby
mit
66
var Square = UI.component({ components: [Animator, KeyInput], animationMap: { moveLeft: { transform: [-50, 0, 0], time: 200, easing: "linear" }, moveRight: { transform: [50, 0, 0], time: 200, easing: "linear" } }, handleKeyPress: function(e) { if(e.keyCode === 37) { this.Animator.animate(this.animationMap.moveLeft); } else if(e.keyCode === 39) { this.Animator.animate(this.animationMap.moveRight); } }, render: function() { return {}; } }); var BigView = UI.component({ render: function() { var boxes = ["argo", "avatar", "breaking_bad", "brick_mansions", "crazy_stupid_love", "descendants", "gangs_of_new_york", "good_night_and_good_luck", "quantum_of_solace", "slumdog_millionaire", "the_kings_speech"]; var repeats = 2; while(--repeats) { boxes = boxes.concat(boxes); } var x = 0, y = 0; var tex_width = 186; var tex_height = 270; var scale = 0.5; var box_width = tex_width * scale; var box_height = tex_height * scale; var covers = boxes.map(function(box) { var box = UI.new(Square, { top: y, left: x, width: box_width, height: box_height, background: "boxes/box_"+box+".png" }); //console.info(box); x += box_width; if(x > 1000-box_width) { x = 0; y += box_height; } return box; }); //console.info(covers); var args = [Square, { name: "background-colored", top: 0, left: 0, width: 1000, height: 700 }].concat(covers); return UI.new.apply(this, args); } }); UI.render(BigView, document.getElementById("app")); var fps = document.getElementById("fps");
davedx/lustro
examples/auto-atlassing.js
JavaScript
mit
1,618
class RenameTableAttributesOptionToAttributeList < ActiveRecord::Migration def change rename_table :attributes_options, :attribute_lists rename_table :attribute_class_options_attributes_options, :attribute_class_options_attribute_lists rename_column :attribute_class_options_attribute_lists, :attributes_option_id, :attribute_list_id rename_index :attribute_class_options_attribute_lists, :index_acoao_on_attribute_option_id, :index_acoao_on_attribute_list_id end end
andrew2net/sitescan_common
db/migrate/20160315133239_rename_table_attributes_option_to_attribute_list.rb
Ruby
mit
488
package edu.cmu.hcii.whyline.bytecode; /** * @author Andrew J. Ko * */ public abstract class Instantiation extends Instruction { public Instantiation(CodeAttribute method) { super(method); } public String getReadableDescription() { return "new"; } public String getAssociatedName() { return null; } public abstract QualifiedClassName getClassnameOfTypeProduced(); }
andyjko/whyline
edu/cmu/hcii/whyline/bytecode/Instantiation.java
Java
mit
383
using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Windows; // アセンブリに関する一般情報は以下の属性セットをとおして制御されます。 // アセンブリに関連付けられている情報を変更するには、 // これらの属性値を変更してください。 [assembly: AssemblyTitle("GorokuEdit")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Hewlett-Packard")] [assembly: AssemblyProduct("GorokuEdit")] [assembly: AssemblyCopyright("Copyright © Hewlett-Packard 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // ComVisible を false に設定すると、その型はこのアセンブリ内で COM コンポーネントから // 参照不可能になります。COM からこのアセンブリ内の型にアクセスする場合は、 // その型の ComVisible 属性を true に設定してください。 [assembly: ComVisible(false)] //ローカライズ可能なアプリケーションのビルドを開始するには、 //.csproj ファイルの <UICulture>CultureYouAreCodingWith</UICulture> を //<PropertyGroup> 内部で設定します。たとえば、 //ソース ファイルで英語を使用している場合、<UICulture> を en-US に設定します。次に、 //下の NeutralResourceLanguage 属性のコメントを解除します。下の行の "en-US" を //プロジェクト ファイルの UICulture 設定と一致するよう更新します。 //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //テーマ固有のリソース ディクショナリが置かれている場所 //(リソースがページ、 //またはアプリケーション リソース ディクショナリに見つからない場合に使用されます) ResourceDictionaryLocation.SourceAssembly //汎用リソース ディクショナリが置かれている場所 //(リソースがページ、 //アプリケーション、またはいずれのテーマ固有のリソース ディクショナリにも見つからない場合に使用されます) )] // アセンブリのバージョン情報は、以下の 4 つの値で構成されています: // // Major Version // Minor Version // Build Number // Revision // // すべての値を指定するか、下のように '*' を使ってビルドおよびリビジョン番号を // 既定値にすることができます: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
go63/BenzGorokuSearch
GorokuEdit/Properties/AssemblyInfo.cs
C#
mit
2,757
<!-- Unsafe sample input : get the field userData from the variable $_GET via an object SANITIZE : use in_array to check if $tainted is in the white list File : unsafe, use of untrusted data in a quoted property value (CSS) --> <!--Copyright 2015 Bertrand STIVALET Permission is hereby granted, without written agreement or royalty fee, to use, copy, modify, and distribute this software and its documentation for any purpose, provided that the above copyright notice and the following three paragraphs appear in all copies of this software. IN NO EVENT SHALL AUTHORS BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF AUTHORS HAVE BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. AUTHORS SPECIFICALLY DISCLAIM ANY WARRANTIES INCLUDING, BUT NOT LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THE SOFTWARE IS PROVIDED ON AN "AS-IS" BASIS AND AUTHORS HAVE NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.--> <!DOCTYPE html> <html> <head> <style> <?php class Input{ private $input; public function getInput(){ return $this->input; } public function __construct(){ $this->input = $_GET['UserData'] ; } } $temp = new Input(); $tainted = $temp->getInput(); $legal_table = array("safe1", "safe2"); if (in_array($tainted, $legal_table, true)) { $tainted = $tainted; } else { $tainted = $legal_table[0]; } //flaw echo "body { color :\'". $tainted ."\' ; }" ; ?> </style> </head> <body> <h1>Hello World!</h1> </body> </html>
stivalet/PHP-Vulnerability-test-suite
XSS/CWE_79/unsafe/CWE_79__object-classicGet__whitelist_using_array__Use_untrusted_data_propertyValue_CSS-quoted_Property_Value.php
PHP
mit
1,677
package MestreCuca; public enum Medidas { grama, unidade, xicara, colher_sopa }
glauber-barboza/crescer-2015-1
eclipse/MestreCucaAntigo/src/MestreCuca/Medidas.java
Java
mit
88
(function myAppCoreConstants() { 'use strict'; angular .module('myApp.core') .constant('FIREBASE_URL', 'https://blistering-heat-2473.firebaseio.com'); })();
neggro/angularjs_firebase
client/app/core/core.constants.js
JavaScript
mit
183
#!/usr/bin/env node const fs = require('fs'); const yaml = require('js-yaml'); const cli = require('../lib/cli'); // define cli options const optionList = [ { name: 'help', type: Boolean, description: 'show this help' }, { name: 'host', alias: 'h', type: String, description: 'host name' }, { name: 'port', alias: 'p', type: Number, description: 'port number' }, { name: 'watch', alias: 'w', type: Boolean, description: 'start in a watch mode' }, { name: 'docker', alias: 'd', type: Boolean, description: 'parse docker-compose.yml for parameters' }, // { name: 'file', alias: 'f', type: String, description: 'override the default docker-compose.yml file name' }, { name: 'service', alias: 's', type: String, description: 'service to look for when parsing docker-compose file' }, { name: 'flags', alias: 'l', type: String, description: 'custom flags to pass to rsync (default -rtR)' }, { name: 'volume', alias: 'v', type: String, description: 'override the default volume name' }, { name: 'version', type: Boolean, description: 'print version number' }, { name: 'files', type: String, defaultOption: true, multiple: true } ]; // define cli usage const usage = function (options) { return require('command-line-usage')([ { header: 'Synopsis', content: [ '$ drsync [bold]{--help}', ] }, { header: 'Options', optionList } ]) }; let args = require('command-line-args')(optionList, {}, process.argv); // override args with options from drsync.yml if (fs.existsSync('./drsync.yml')) { const overrides = yaml.safeLoad(fs.readFileSync('./drsync.yml', 'utf8')); if (overrides) { args = Object.assign({}, args, overrides.options); } } let options = {}; try { options = cli(args); } catch (err) { console.log(err.message); process.exit(); } // show help if requested if (options.help) { console.log(usage(options)); process.exit(); } // show version and exit if (options.version) { console.log(require('../package.json').version); process.exit(); } require('../lib/drsync')(options).subscribe(console.log);
stefda/drsync
bin/drsync.js
JavaScript
mit
2,107
<?php namespace water\session; /* * This class will manage session cookied and allow the opening a session via * a user object and getting a user by there session ID. */ use water\database\Users; class SessionStore{ public static function hasSession(){ if(isset($_SESSION['login-data'])){ $data = explode("\\", $_SESSION['login-data']); $user = Users::getUser($data[0]); if($user !== false){ if(isset($user["sessions"][$data[1]])){ return true; } else{ SessionStore::destroySession(); return false; } } else{ SessionStore::destroySession(); return false; } } else{ return false; } } public static function getCurrentSession(){ if(SessionStore::hasSession()){ $data = explode("\\", $_SESSION['login-data']); return Users::getUser($data[0]); } else{ return false; } } public static function createSession($user){ SessionStore::destroySession(); $_SESSION['login-data'] = $user . "\\" . Users::addSession($user, $_SERVER['REMOTE_ADDR']); } public static function destroySession(){ if(isset($_SESSION['login-data'])) { $data = explode("\\", $_SESSION['login-data']); Users::deleteSession($data[0], $data[1]); unset($_SESSION['login-data']); } } }
Falkirks/TeamShog
src/session/SessionStore.php
PHP
mit
1,586
# Copyright (C) 2002, Thomas Hamelryck (thamelry@binf.ku.dk) # This code is part of the Biopython distribution and governed by its # license. Please see the LICENSE file that should have been included # as part of this package. from types import StringType from Bio.Alphabet import ProteinAlphabet from Bio.Seq import Seq from Bio.SCOP.Raf import to_one_letter_code from Bio.PDB.PDBExceptions import PDBException from Bio.PDB.Residue import Residue, DisorderedResidue from Vector import calc_dihedral, calc_angle __doc__=""" Polypeptide related classes (construction and representation). Example: >>> ppb=PPBuilder() >>> for pp in ppb.build_peptides(structure): >>> print pp.get_sequence() """ standard_aa_names=["ALA", "CYS", "ASP", "GLU", "PHE", "GLY", "HIS", "ILE", "LYS", "LEU", "MET", "ASN", "PRO", "GLN", "ARG", "SER", "THR", "VAL", "TRP", "TYR"] aa1="ACDEFGHIKLMNPQRSTVWY" aa3=standard_aa_names d1_to_index={} dindex_to_1={} d3_to_index={} dindex_to_3={} # Create some lookup tables for i in range(0, 20): n1=aa1[i] n3=aa3[i] d1_to_index[n1]=i dindex_to_1[i]=n1 d3_to_index[n3]=i dindex_to_3[i]=n3 def index_to_one(index): """ Index to corresponding one letter amino acid name. For example: 0 to A. """ return dindex_to_1[index] def one_to_index(s): """ One letter code to index. For example: A to 0. """ return d1_to_index[s] def index_to_three(i): """ Index to corresponding three letter amino acid name. For example: 0 to ALA. """ return dindex_to_3[i] def three_to_index(s): """ Three letter code to index. For example: ALA to 0. """ return d3_to_index[s] def three_to_one(s): """ Three letter code to one letter code. For example: ALA to A. """ i=d3_to_index[s] return dindex_to_1[i] def one_to_three(s): """ One letter code to three letter code. For example: A to ALA. """ i=d1_to_index[s] return dindex_to_3[i] def is_aa(residue, standard=0): """ Return 1 if residue object/string is an amino acid. @param residue: a L{Residue} object OR a three letter amino acid code @type residue: L{Residue} or string @param standard: flag to check for the 20 AA (default false) @type standard: boolean """ if not type(residue)==StringType: residue=residue.get_resname() residue=residue.upper() if standard: return d3_to_index.has_key(residue) else: return to_one_letter_code.has_key(residue) class Polypeptide(list): """ A polypeptide is simply a list of L{Residue} objects. """ def get_ca_list(self): """ @return: the list of C-alpha atoms @rtype: [L{Atom}, L{Atom}, ...] """ ca_list=[] for res in self: ca=res["CA"] ca_list.append(ca) return ca_list def get_phi_psi_list(self): """ Return the list of phi/psi dihedral angles """ ppl=[] lng=len(self) for i in range(0, lng): res=self[i] try: n=res['N'].get_vector() ca=res['CA'].get_vector() c=res['C'].get_vector() except: # Some atoms are missing # Phi/Psi cannot be calculated for this residue ppl.append((None, None)) res.xtra["PHI"]=None res.xtra["PSI"]=None continue # Phi if i>0: rp=self[i-1] try: cp=rp['C'].get_vector() phi=calc_dihedral(cp, n, ca, c) except: phi=None else: # No phi for residue 0! phi=None # Psi if i<(lng-1): rn=self[i+1] try: nn=rn['N'].get_vector() psi=calc_dihedral(n, ca, c, nn) except: psi=None else: # No psi for last residue! psi=None ppl.append((phi, psi)) # Add Phi/Psi to xtra dict of residue res.xtra["PHI"]=phi res.xtra["PSI"]=psi return ppl def get_tau_list(self): """ Return list of tau torsions angles for all 4 consecutive Calpha atoms. """ ca_list=self.get_ca_list() tau_list=[] for i in range(0, len(ca_list)-3): atom_list=[ca_list[i], ca_list[i+1], ca_list[i+2], ca_list[i+3]] vector_list=map(lambda a: a.get_vector(), atom_list) v1, v2, v3, v4=vector_list tau=calc_dihedral(v1, v2, v3, v4) tau_list.append(tau) # Put tau in xtra dict of residue res=ca_list[i+2].get_parent() res.xtra["TAU"]=tau return tau_list def get_theta_list(self): """ Return list of theta angles for all 3 consecutive Calpha atoms. """ theta_list=[] ca_list=self.get_ca_list() for i in range(0, len(ca_list)-2): atom_list=[ca_list[i], ca_list[i+1], ca_list[i+2]] vector_list=map(lambda a: a.get_vector(), atom_list) v1, v2, v3=vector_list theta=calc_angle(v1, v2, v3) theta_list.append(theta) # Put tau in xtra dict of residue res=ca_list[i+1].get_parent() res.xtra["THETA"]=theta return theta_list def get_sequence(self): """ Return the AA sequence. @return: polypeptide sequence @rtype: L{Seq} """ s="" for res in self: resname=res.get_resname() if to_one_letter_code.has_key(resname): resname=to_one_letter_code[resname] else: resname='X' s=s+resname seq=Seq(s, ProteinAlphabet) return seq def __repr__(self): """ Return <Polypeptide start=START end=END>, where START and END are sequence identifiers of the outer residues. """ start=self[0].get_id()[1] end=self[-1].get_id()[1] s="<Polypeptide start=%s end=%s>" % (start, end) return s class _PPBuilder: """ Base class to extract polypeptides. It checks if two consecutive residues in a chain are connected. The connectivity test is implemented by a subclass. """ def __init__(self, radius): """ @param radius: distance @type radius: float """ self.radius=radius def _accept(self, residue): "Check if the residue is an amino acid." if is_aa(residue): return 1 else: if "CA" in residue.child_dict: #It has an alpha carbon... #We probably need to update the hard coded list of #non-standard residues, see function is_aa for details. import warnings warnings.warn("Assuming residue %s is an unknown modified " "amino acid" % residue.get_resname()) return 1 # not a standard AA so skip return 0 def build_peptides(self, entity, aa_only=1): """ Build and return a list of Polypeptide objects. @param entity: polypeptides are searched for in this object @type entity: L{Structure}, L{Model} or L{Chain} @param aa_only: if 1, the residue needs to be a standard AA @type aa_only: int """ is_connected=self._is_connected accept=self._accept level=entity.get_level() # Decide wich entity we are dealing with if level=="S": model=entity[0] chain_list=model.get_list() elif level=="M": chain_list=entity.get_list() elif level=="C": chain_list=[entity] else: raise PDBException("Entity should be Structure, Model or Chain.") pp_list=[] for chain in chain_list: chain_it=iter(chain) prev=chain_it.next() pp=None for next in chain_it: if aa_only and not accept(prev): prev=next continue if is_connected(prev, next): if pp is None: pp=Polypeptide() pp.append(prev) pp_list.append(pp) pp.append(next) else: pp=None prev=next return pp_list class CaPPBuilder(_PPBuilder): """ Use CA--CA distance to find polypeptides. """ def __init__(self, radius=4.3): _PPBuilder.__init__(self, radius) def _is_connected(self, prev, next): for r in [prev, next]: if not r.has_id("CA"): return 0 n=next["CA"] p=prev["CA"] # Unpack disordered if n.is_disordered(): nlist=n.disordered_get_list() else: nlist=[n] if p.is_disordered(): plist=p.disordered_get_list() else: plist=[p] for nn in nlist: for pp in plist: if (nn-pp)<self.radius: return 1 return 0 class PPBuilder(_PPBuilder): """ Use C--N distance to find polypeptides. """ def __init__(self, radius=1.8): _PPBuilder.__init__(self, radius) def _is_connected(self, prev, next): if not prev.has_id("C"): return 0 if not next.has_id("N"): return 0 test_dist=self._test_dist c=prev["C"] n=next["N"] # Test all disordered atom positions! if c.is_disordered(): clist=c.disordered_get_list() else: clist=[c] if n.is_disordered(): nlist=n.disordered_get_list() else: nlist=[n] for nn in nlist: for cc in clist: # To form a peptide bond, N and C must be # within radius and have the same altloc # identifier or one altloc blank n_altloc=nn.get_altloc() c_altloc=cc.get_altloc() if n_altloc==c_altloc or n_altloc==" " or c_altloc==" ": if test_dist(nn, cc): # Select the disordered atoms that # are indeed bonded if c.is_disordered(): c.disordered_select(c_altloc) if n.is_disordered(): n.disordered_select(n_altloc) return 1 return 0 def _test_dist(self, c, n): "Return 1 if distance between atoms<radius" if (c-n)<self.radius: return 1 else: return 0 if __name__=="__main__": import sys from Bio.PDB.PDBParser import PDBParser p=PDBParser(PERMISSIVE=1) s=p.get_structure("scr", sys.argv[1]) ppb=PPBuilder() print "C-N" for pp in ppb.build_peptides(s): print pp.get_sequence() for pp in ppb.build_peptides(s[0]): print pp.get_sequence() for pp in ppb.build_peptides(s[0]["A"]): print pp.get_sequence() for pp in ppb.build_peptides(s): for phi, psi in pp.get_phi_psi_list(): print phi, psi ppb=CaPPBuilder() print "CA-CA" for pp in ppb.build_peptides(s): print pp.get_sequence() for pp in ppb.build_peptides(s[0]): print pp.get_sequence() for pp in ppb.build_peptides(s[0]["A"]): print pp.get_sequence()
NirBenTalLab/proorigami-cde-package
cde-root/usr/lib64/python2.4/site-packages/Bio/PDB/Polypeptide.py
Python
mit
11,950
const { FuseBox, QuantumPlugin, UglifyJSPlugin } = require("fuse-box"); const fuse = FuseBox.init({ target: "browser@es5", homeDir: ".", output: "dist/$name.js", plugins: [ QuantumPlugin({ treeshake: true, target: "browser", }), UglifyJSPlugin({ }) ], }); fuse.bundle("remark-bundle").instructions("> index.js"); fuse.run();
zipang/markdown-bundle
src/remark/bundle/fuse.js
JavaScript
mit
348
import { Controller } from 'marionette'; import Layout from '../commons/layout'; import MainPage from '../pages/mainPage'; import ImportPage from '../pages/importPage'; import ProfileView from '../pages/profileView'; export default Controller.extend({ defaultRoute(){ Layout.main.show( new MainPage() ); }, register(){ //Layout.main.show( new RegisterView() ); }, viewProfile(id){ Layout.main.show( new ProfileView(id) ); }, createAi(){ //Layout.main.show( new CreateAIView(id) ); }, import(){ Layout.main.show( new ImportPage() ); } });
jbsouvestre/challengr
Challengr/public/js/routes/controller.js
JavaScript
mit
619
require 'pp' require "google_drive" require "ruby-progressbar" ENV['SSL_CERT_FILE'] = Gem.loaded_specs['google-api-client'].full_gem_path+'/lib/cacerts.pem' module Pairity class GoogleSync CONFIG_FILE = Dir.home + "/.pairity_google.json" attr_reader :sheet_url def initialize(matrix) @matrix = matrix @people = {} @sheet_url = nil end def load unless File.exists?(CONFIG_FILE) puts "Welcome, newcomer!" puts "Please follow these instructions to allow #{Rainbow("Pairity").white} to use Google Sheets to sync its precious data." end session = GoogleDrive.saved_session(CONFIG_FILE) puts "Loading Matrix from Google Sheets..." progressbar = ProgressBar.create(total: 100) progressbar.progress += 20 sheet = session.spreadsheet_by_title("Pairity") unless sheet puts "Creating a new spreadsheet called: Pairity" sheet = session.create_spreadsheet("Pairity") sheet.add_worksheet("Days") sheet.add_worksheet("Resistance") sheet.add_worksheet("Weights") ws = sheet.worksheets[0] ws.title = "People" ws.save else end @sheet_url = sheet.worksheets[0].human_url ws = sheet.worksheets[0] # Add People and Tiers to Matrix ws.num_rows.times do |row| next unless row > 0 name = ws[row + 1, 1] next if name.strip.empty? tier = ws[row + 1, 2] if name == "Han Solo" person = @matrix.han_solo else person = Person.new(name: name, tier: tier) @matrix.add_person(person) end @people[person] = row + 1 end # Add data to edges (1..3).each do |i| ws = sheet.worksheets[i] @people.each do |p1, row| @people.each do |p2, col| next if p1 == p2 data = ws[row, col] edit_edge(p1, p2, data, i) end end end @matrix end def clear_worksheet(ws) (1..ws.num_rows).each do |i| (1..ws.num_rows).each do |j| ws[i, j] = "" ws[j, i] = "" end end end def save puts "Saving Matrix to Google Sheets..." progressbar = ProgressBar.create(total: 100) session = GoogleDrive.saved_session(CONFIG_FILE) sheet = session.spreadsheet_by_title("Pairity") @people = @matrix.all_people.sort progressbar.progress += 20 ws = sheet.worksheets[0] clear_worksheet(ws) ws[1, 1] = "Name" ws[1, 2] = "Tier (1-3)" @people.each_with_index do |person, index| ws[index + 2, 1] = person.name ws[index + 2, 2] = person.tier end ws.save (1..3).each do |i| ws = sheet.worksheets[i] clear_worksheet(ws) @people.each_with_index do |person, index| ws[1, index + 2] = person.name ws[index + 2, 1] = person.name end progressbar.progress += 20 @people.combination(2) do |pair| p1, p2 = pair index1 = @people.index(p1) index2 = @people.index(p2) edge = @matrix[p1,p2] case i when 1 ws[1,1] = "Days" data = edge.days when 2 ws[1,1] = "Resistances" data = edge.resistance when 3 ws[1,1] = "Weights" data = edge.weight end ws[index1 + 2, index2 + 2] = data ws[index2 + 2, index1 + 2] = data end max = ws.max_rows @people.each_with_index do |person, index| ws[index + 2, index + 2] = "" ws[index + 2, index + 2] = "" max = index + 3 end ws.save end progressbar.progress += 20 end def edit_edge(p1, p2, data, i) case i when 1 @matrix[p1, p2].days = data.to_i when 2 @matrix[p1, p2].resistance = (data ? 1 : data.to_i) when 3 @matrix[p1, p2].weight = data.to_i end end def find_person(name) person = @people.find { |person| person.name == name } end end end
kitlangton/pairity
lib/pairity/google_sync.rb
Ruby
mit
4,194
import{ FETCH_TIMELOGS } from '../actions/TimelogActions'; function ajax(url, callback) { var data; var fetch; fetch = new XMLHttpRequest(); fetch.onreadystatechange = function() { if (fetch.readyState == XMLHttpRequest.DONE ) { if(fetch.status == 200){ var data = JSON.parse(fetch.responseText); console.log('---------------------- ajax response '); console.log(data); if (callback) callback(data); } else if(fetch.status == 404) { data = { error: 'There was an error 404' }; console.log('---------------------- ajax response '); console.log(data); } else { data = { error: 'something else other than 200 was returned' }; console.log('---------------------- ajax response '); console.log(data); } } }; fetch.open("GET", url, true); fetch.send(); return data; } var defaultState = ajax('timelogs.json', function (return_data) { return return_data; }); export default function timelogReducer(state = defaultState, action) { switch (action.type) { case FETCH_TIMELOGS: var new_state = ajax('timelogs.json', function (return_data) { console.log('Fetch timelogs was run'); return return_data; }); return new_state; default: return state; } }
pdx-code/teampro
src/reducers/TimelogReducer.js
JavaScript
mit
1,374
package com.sensepost.yeti.gui; import java.awt.event.ActionEvent; import java.util.ArrayList; import java.util.HashSet; import com.sensepost.yeti.common.JIPCalc; import com.sensepost.yeti.persistence.DataStore; /** * * @author willemmouton */ public class ReverseLookupInit extends BaseDlg { private String buffer = ""; public ReverseLookupInit() { initComponents(); this.setLocationRelativeTo(null); this.setModalityType(ModalityType.APPLICATION_MODAL); } public ArrayList<String> getTargets() { ArrayList<String> result = new ArrayList<>(); String[] ips = txtIPRanges.getText().split("\n"); for (String ip : ips) { @SuppressWarnings("static-access") ArrayList<String> al = new JIPCalc(ip.trim()).getTargets(); result.addAll(al); } return result; } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jScrollPane1 = new javax.swing.JScrollPane(); txtIPRanges = new javax.swing.JTextArea(); jLabel3 = new javax.swing.JLabel(); cbxImportFrom = new javax.swing.JComboBox(); btnLoadFromSource = new javax.swing.JButton(); jLabel1 = new javax.swing.JLabel(); cbxMakeRanges = new javax.swing.JCheckBox(); cbxRanges = new javax.swing.JComboBox(); btnStart = new javax.swing.JButton(); btnCancel = new javax.swing.JButton(); setName("Form"); // NOI18N jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Input params...")); jPanel1.setName("jPanel1"); // NOI18N jScrollPane1.setName("jScrollPane1"); // NOI18N txtIPRanges.setColumns(20); txtIPRanges.setRows(5); txtIPRanges.setName("txtIPRanges"); // NOI18N jScrollPane1.setViewportView(txtIPRanges); jLabel3.setText("Sources"); // NOI18N jLabel3.setName("jLabel3"); // NOI18N cbxImportFrom.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "All", "Initial IP Addresses", "Discovered IP Addresses" })); cbxImportFrom.setName("cbxImportFrom"); // NOI18N btnLoadFromSource.setText("Load"); // NOI18N btnLoadFromSource.setName("btnLoadFromSource"); // NOI18N btnLoadFromSource.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { btnLoadFromSourceMouseClicked(evt); } }); jLabel1.setText("IP ranges"); // NOI18N jLabel1.setName("jLabel1"); // NOI18N cbxMakeRanges.setText("Make ranges"); // NOI18N cbxMakeRanges.setName("cbxMakeRanges"); // NOI18N cbxMakeRanges.addItemListener(new java.awt.event.ItemListener() { public void itemStateChanged(java.awt.event.ItemEvent evt) { cbxMakeRangesItemStateChanged(evt); } }); cbxRanges.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "/24", "/16" })); cbxRanges.setEnabled(false); cbxRanges.setName("cbxRanges"); // NOI18N cbxRanges.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { cbxRangesActionPerformed(evt); } }); org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jPanel1Layout.createSequentialGroup() .addContainerGap() .add(cbxMakeRanges) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(cbxRanges, 0, 151, Short.MAX_VALUE) .add(101, 101, 101)) .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 382, Short.MAX_VALUE) .add(jPanel1Layout.createSequentialGroup() .addContainerGap() .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jPanel1Layout.createSequentialGroup() .add(jLabel3) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(cbxImportFrom, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(btnLoadFromSource)) .add(jLabel1)) .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(jPanel1Layout.createSequentialGroup() .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(cbxImportFrom, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .add(jLabel3) .add(btnLoadFromSource)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED) .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(cbxMakeRanges) .add(cbxRanges, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED) .add(jLabel1) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 281, Short.MAX_VALUE)) ); btnStart.setText("Start"); // NOI18N btnStart.setName("btnStart"); // NOI18N btnStart.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { btnStartMouseClicked(evt); } }); btnCancel.setText("Cancel"); // NOI18N btnCancel.setName("btnCancel"); // NOI18N btnCancel.addMouseListener(new java.awt.event.MouseAdapter() { public void mouseClicked(java.awt.event.MouseEvent evt) { btnCancelMouseClicked(evt); } }); org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup() .addContainerGap(210, Short.MAX_VALUE) .add(btnCancel) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(btnStart) .addContainerGap()) .add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) ); layout.setVerticalGroup( layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup() .add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(btnCancel) .add(btnStart)) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents private void btnStartMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnStartMouseClicked this.cancelled = false; this.setVisible(false); // TODO add your handling code here: }//GEN-LAST:event_btnStartMouseClicked private void btnCancelMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnCancelMouseClicked this.setVisible(false); }//GEN-LAST:event_btnCancelMouseClicked private void btnLoadFromSourceMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnLoadFromSourceMouseClicked HashSet<String> ips = new HashSet<>(); switch (cbxImportFrom.getSelectedIndex()) { case 0: { ips.addAll(DataStore.getInitialDataItems(DataStore.IP)); ips.addAll(DataStore.getAllIPSForCurrentFootprint()); break; } case 1: { ips.addAll(DataStore.getInitialDataItems(DataStore.IP)); break; } case 2: { } } for (String ip : ips) { txtIPRanges.append(ip + "\n"); } }//GEN-LAST:event_btnLoadFromSourceMouseClicked private void cbxMakeRangesItemStateChanged(java.awt.event.ItemEvent evt) {//GEN-FIRST:event_cbxMakeRangesItemStateChanged this.cbxRanges.setEnabled(cbxMakeRanges.isSelected()); if (this.buffer.isEmpty()) { if (cbxMakeRanges.isSelected()) { this.buffer = txtIPRanges.getText(); } else { txtIPRanges.setText(this.buffer); this.buffer = ""; } } this.cbxRanges.setSelectedIndex(0); }//GEN-LAST:event_cbxMakeRangesItemStateChanged private void cbxRangesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbxRangesActionPerformed HashSet<String> ips = new HashSet<>(); for (String ip : this.buffer.split("\\n")) { String[] ipParts = ip.split("\\."); String modIp = ""; switch (cbxRanges.getSelectedIndex()) { case 0: modIp = String.format("%s.%s.%s.0/24", ipParts[0], ipParts[1], ipParts[2]); break; case 1: modIp = String.format("%s.%s.0.0/16", ipParts[0], ipParts[1]); break; default: return; } ips.add(modIp); } txtIPRanges.setText(""); for (String ip : ips) { txtIPRanges.append(ip + "\n"); } }//GEN-LAST:event_cbxRangesActionPerformed // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton btnCancel; private javax.swing.JButton btnLoadFromSource; private javax.swing.JButton btnStart; private javax.swing.JComboBox cbxImportFrom; private javax.swing.JCheckBox cbxMakeRanges; private javax.swing.JComboBox cbxRanges; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel3; private javax.swing.JPanel jPanel1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTextArea txtIPRanges; // End of variables declaration//GEN-END:variables @Override public void actionPerformed(ActionEvent e) { throw new UnsupportedOperationException("Not supported yet."); } }
sensepost/yeti
src/main/java/com/sensepost/yeti/gui/ReverseLookupInit.java
Java
mit
11,627
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace MessParser { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } private void MenuItem_Exit_Click(object sender, RoutedEventArgs e) { this.Close(); } private void MenuItem_Open_Click(object sender, RoutedEventArgs e) { var dialog = new Microsoft.Win32.OpenFileDialog(); dialog.DefaultExt = ".txt"; dialog.Filter = "TXT Files (*.txt)|*.txt"; bool? result = dialog.ShowDialog(); if (result == true) { string filename = dialog.FileName; var content = File.ReadAllText(filename); tbContent.Text = content; } } private void MenuItem_About_Click(object sender, RoutedEventArgs e) { MessageBox.Show("ESO little project for mess files.", "About", MessageBoxButton.OK, MessageBoxImage.Information); } } }
ewasow/learning-cs
MessParser/MessParser/MainWindow.xaml.cs
C#
mit
1,583
/* global angular, moment */ var app = angular.module('flowList', ['ui.grid']); app.controller('flowListCtrl', function($scope, $http) { 'use strict'; $http.get('/json/rawFlowsForLast/5/minutes') .success(function(data) { var retList = []; data.forEach(function(element) { var flowRecord = { srcAddress: element._source.ipv4_src_addr, dstAddress: element._source.ipv4_dst_addr, Packets: element._source.in_pkts, Bytes: element._source.in_bytes, Time: moment(element._source.timestamp) .format('YYYY-MM-DD HH:mm:ss') }; retList.push(flowRecord); }); $scope.flows = retList; }) .error(function() { console.warn('doh'); }); });
skarfacegc/FlowTrack2
www/js/flowListController.js
JavaScript
mit
836
require('date-utils'); var sendgrid = require('sendgrid')("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"); module.exports = function(app, config, passport, mongoose, fs, path){ var isAuthenticated = function(req, res, next){ if(req.isAuthenticated()){ return next(); } else { res.redirect("/login"); } } app.get("/", isAuthenticated, function(req, res){ res.render("index.html"); }); app.get("/myaccount", isAuthenticated, function(req, res){ res.render("index.html"); }); app.get("/create", isAuthenticated, function(req, res){ res.render("index.html"); }); app.get("/search", isAuthenticated, function(req, res){ res.render("index.html"); }); app.get("/login", passport.authenticate('google', { scope : ['profile', 'email'] }) ); app.get("/auth/google/callback", passport.authenticate('google', { successRedirect : '/', failureRedirect: '/login', failureFlash: true }) ); app.get('/logout', function(req, res) { req.logout(); res.redirect("/"); }); var getPools = function(query, res){ var requests = mongoose.model('request'); requests.find(query, function(err, result){ if (err) { console.log(err); } else { res.setHeader('Cache-Control', 'no-cache'); res.json(result); } }); }; app.get('/api/comments', isAuthenticated, function(req, res) { var query = {$or:[{createdOn: {$eq: Date.today()}}, {everyday: {$eq: true}}]}; getPools(query, res); }); app.get('/api/mycomments', isAuthenticated, function(req, res) { var myEmailId = req.user.email; var query = {email: myEmailId}; getPools(query, res); }); app.delete('/api/comments', function (req, res) { var requests = mongoose.model('request'); var query = {_id: req.body.id}; requests.remove(query, function(err, result){ if (err) { console.log(err); } else { console.log("pool deleted"); } }); }); app.post('/api/comments', isAuthenticated, function(req, res) { var user = req.user; var request = mongoose.model('request'); var newRequest = new request({ email: user.email, name: user.name, originAddress: req.body.originAddress, destinationAddress: req.body.destinationAddress, provider: req.body.provider, time: req.body.time, encodedRoute: req.body.encodedRoute, createdOn: Date.today(), everyday: req.body.everyday }); newRequest.save(function (err, result) { if (err) { console.log(err); } else { console.log('documents into the "request" collection are:', result); res.setHeader('Cache-Control', 'no-cache'); res.json(result); } }); }); app.post('/notify', isAuthenticated, function(req, res) { var notifications = req.body.notifications; console.log("notifications"); console.log(notifications); notifications.forEach(function(notification){ var payload = { to : notification.email, from : notification.from, subject : notification.subject, html : notification.html } sendgrid.send(payload, function(err, json) { if (err) { console.error(err); }else{ res.json(json); } }); }); }); app.get('/user', function (req, res) { res.json(req.user); }); }
prabhuramkumar/ThoughtPool
config/routes.js
JavaScript
mit
3,415
package com.mapzen.tangram; import android.support.annotation.Keep; import java.util.Map; /** * {@code LabelPickResult} represents labels that can be selected on the screen */ @Keep public class LabelPickResult { /** * Options for the type of LabelPickResult */ public enum LabelType { ICON, TEXT, } private LngLat coordinates; private LabelType type; private Map<String, String> properties; private LabelPickResult(double longitude, double latitude, int type, Map<String, String> properties) { this.properties = properties; this.coordinates = new LngLat(longitude, latitude); this.type = LabelType.values()[type]; } public LabelType getType() { return this.type; } /** * @return The coordinate of the feature for which this label has been created */ public LngLat getCoordinates() { return this.coordinates; } /** * @return A mapping of string keys to string or number values */ public Map<String, String> getProperties() { return this.properties; } }
quitejonny/tangram-es
platforms/android/tangram/src/main/java/com/mapzen/tangram/LabelPickResult.java
Java
mit
1,122
<?php require_once __DIR__ . '/../../vendor/autoload.php'; use Symfony\Component\Console\Application; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\ArrayInput; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; class Progress extends Command { protected function configure() { $this->setName('progress'); } protected function execute(InputInterface $input, OutputInterface $output) { $progress = $this->getHelperSet()->get('progress'); $progress->start($output, 50); $i = 0; while ($i++ < 50) { $progress->advance(); } $progress->finish(); } } $app = new Application(); $app->add(new \Progress()); $app->run(new ArrayInput(array('command' => 'progress')));
dcsg/phplx-how-to-build-console-app
examples/Helpers/progress.php
PHP
mit
795
using System; namespace Infrastructure.Interface { public interface ITrackableEntity { DateTime CreatedDate { get; set; } string CreatedBy { get; set; } DateTime UpdatedDate { get; set; } string UpdatedBy { get; set; } } }
Radigeco/webapi-jwt-angular-boilerplate
Context/ITrackableEntity.cs
C#
mit
273
class Recipe < ActiveRecord::Base acts_as_taggable validates :name, presence: true validates :people, presence: true validates :duration, presence: true validates :instructions, presence: true belongs_to :user has_many :ingredient_groups, dependent: :destroy has_many :links, dependent: :destroy accepts_nested_attributes_for :ingredient_groups, reject_if: :all_blank, allow_destroy: true accepts_nested_attributes_for :links, reject_if: :all_blank, allow_destroy: true end
joren/recipes
app/models/recipe.rb
Ruby
mit
498
class AddRailSafetyFeatures < ActiveRecord::DataMigration def up [ {name: 'Event Data Recorders', description: 'Report the total number of fleet vehicles equipped with event data recorders according to IEEE 1482.1 standard.', active: true}, {name: 'Emergency Lighting', description: 'Report the total number of fleet vehicles with systems that meet the minimum performance criteria for emergency lighting specified by APTA RT-S-VIM-20-10 standard.', active: true}, {name: 'Emergency Signage', description: 'Report the total number of fleet vehicles with systems that meet the minimum performance criteria for the design of emergency signage specified by APTA RT-S-VIM021-10 standard.', active: true}, {name: 'Emergency Path Marking', description: 'Report the total number of fleet vehicles with systems that meet the minimum performance criteria for low-location exit path marking specified by APTA RT-S-VIM-022- 10 standard.', active: true} ].each do |safety_feature| RailSafetyFeature.create!(safety_feature) end end end
camsys/transam_transit
db/data_migrations/20200528175309_add_rail_safety_features.rb
Ruby
mit
1,076
(function () { 'use strict'; angular.module('AngularPanelsApp.theme') .directive('trackWidth', trackWidth); /** @ngInject */ function trackWidth() { return { scope: { trackWidth: '=', minWidth: '=', }, link: function (scope, element) { scope.trackWidth = $(element).width() < scope.minWidth; scope.prevTrackWidth = scope.trackWidth; $(window).resize(function() { var trackWidth = $(element).width() < scope.minWidth; if (trackWidth !== scope.prevTrackWidth) { scope.$apply(function() { scope.trackWidth = trackWidth; }); } scope.prevTrackWidth = trackWidth; }); } }; } })();
mauroBus/angular-panels-app
src/app/theme/directives/trackWidth.js
JavaScript
mit
752
import { DynamoStore } from '@shiftcoders/dynamo-easy' import { Person } from '../models' const objectToPut: Person = { id: 'vogelsw', name: 'Werner Hans Peter Vogels', yearOfBirth: 1958, } // object literal or new Person(...) new DynamoStore(Person) .put(objectToPut) .ifNotExists() .exec() .then(() => console.log('done'))
shiftcode/dynamo-easy
snippets/store-requests/put.snippet.ts
TypeScript
mit
341
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ /* * SDialogRepDpsList.java * * Created on 11/08/2010, 10:49:56 AM */ package erp.mtrn.form; import erp.data.SDataConstants; import erp.data.SDataConstantsSys; import erp.data.SDataUtilities; import erp.lib.SLibConstants; import erp.lib.SLibTimeUtilities; import erp.lib.SLibUtilities; import erp.lib.form.SFormComponentItem; import erp.lib.form.SFormField; import erp.lib.form.SFormUtilities; import erp.lib.form.SFormValidation; import erp.mod.SModConsts; import erp.mod.cfg.db.SDbShift; import erp.mtrn.data.STrnFunctionalAreaUtils; import java.awt.Cursor; import java.awt.event.ActionEvent; import java.awt.event.KeyEvent; import java.util.Map; import java.util.Vector; import javax.swing.AbstractAction; import net.sf.jasperreports.engine.JasperPrint; import net.sf.jasperreports.view.JasperViewer; import sa.lib.SLibTimeUtils; import sa.lib.SLibUtils; /** * * @author Alfonso Flores, Claudio Peña, Edwin Carmona, Sergio Flores */ public class SDialogRepDpsList extends javax.swing.JDialog implements erp.lib.form.SFormInterface, java.awt.event.ActionListener { private int mnFormType; private int mnFormResult; private int mnFormStatus; private boolean mbFirstTime; private boolean mbResetingForm; private java.util.Vector<erp.lib.form.SFormField> mvFields; private erp.client.SClientInterface miClient; private erp.lib.form.SFormField moFieldDateInitial; private erp.lib.form.SFormField moFieldDateEnd; private erp.lib.form.SFormField moFieldCompanyBranch; private erp.lib.form.SFormField moFieldBizPartner; private erp.lib.form.SFormField moFieldShift; private boolean mbParamIsSupplier; private erp.mtrn.form.SDialogFilterFunctionalArea moDialogFilterFunctionalArea; private int mnFunctionalAreaId; private String msFunctionalAreasIds; /** Creates new form SDialogRepDpsList * @param client GUI client. */ public SDialogRepDpsList(erp.client.SClientInterface client) { super(client.getFrame(), true); miClient = client; initComponents(); initComponentsExtra(); } /** This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jPanel1 = new javax.swing.JPanel(); jbPrint = new javax.swing.JButton(); jbExit = new javax.swing.JButton(); jPanel2 = new javax.swing.JPanel(); jPanel3 = new javax.swing.JPanel(); jPanel4 = new javax.swing.JPanel(); jlDateInitial = new javax.swing.JLabel(); jftDateInitial = new javax.swing.JFormattedTextField(); jbDateInitial = new javax.swing.JButton(); jPanel5 = new javax.swing.JPanel(); jlDateEnd = new javax.swing.JLabel(); jftDateEnd = new javax.swing.JFormattedTextField(); jbDateEnd = new javax.swing.JButton(); jPanel6 = new javax.swing.JPanel(); jPanel7 = new javax.swing.JPanel(); jPanel8 = new javax.swing.JPanel(); jlCompanyBranch = new javax.swing.JLabel(); jcbCompanyBranch = new javax.swing.JComboBox(); jPanel9 = new javax.swing.JPanel(); jlBizPartner = new javax.swing.JLabel(); jcbBizPartner = new javax.swing.JComboBox<>(); jPanel10 = new javax.swing.JPanel(); jlShift = new javax.swing.JLabel(); jcbShift = new javax.swing.JComboBox<>(); jPanel11 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jckWithoutRelatedParty = new javax.swing.JCheckBox(); jPanel12 = new javax.swing.JPanel(); jlBizPartner1 = new javax.swing.JLabel(); jtfFunctionalArea = new javax.swing.JTextField(); jbFunctionalArea = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); setTitle("Listado de facturas de clientes"); setResizable(false); addWindowListener(new java.awt.event.WindowAdapter() { public void windowActivated(java.awt.event.WindowEvent evt) { formWindowActivated(evt); } }); jPanel1.setPreferredSize(new java.awt.Dimension(392, 33)); jPanel1.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.RIGHT)); jbPrint.setText("Imprimir"); jbPrint.setToolTipText("[Ctrl + Enter]"); jbPrint.setPreferredSize(new java.awt.Dimension(75, 23)); jPanel1.add(jbPrint); jbExit.setText("Cerrar"); jbExit.setToolTipText("[Escape]"); jbExit.setPreferredSize(new java.awt.Dimension(75, 23)); jPanel1.add(jbExit); getContentPane().add(jPanel1, java.awt.BorderLayout.SOUTH); jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Configuración del reporte:")); jPanel2.setLayout(new java.awt.BorderLayout()); jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Período:")); jPanel3.setPreferredSize(new java.awt.Dimension(376, 77)); jPanel3.setLayout(new java.awt.GridLayout(2, 1, 0, 1)); jPanel4.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0)); jlDateInitial.setText("Fecha inicial: *"); jlDateInitial.setPreferredSize(new java.awt.Dimension(100, 23)); jPanel4.add(jlDateInitial); jftDateInitial.setText("dd/mm/yyyy"); jftDateInitial.setPreferredSize(new java.awt.Dimension(75, 23)); jPanel4.add(jftDateInitial); jbDateInitial.setIcon(new javax.swing.ImageIcon(getClass().getResource("/erp/img/cal_date_day.gif"))); // NOI18N jbDateInitial.setToolTipText("Seleccionar fecha inicial"); jbDateInitial.setFocusable(false); jbDateInitial.setPreferredSize(new java.awt.Dimension(23, 23)); jPanel4.add(jbDateInitial); jPanel3.add(jPanel4); jPanel5.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0)); jlDateEnd.setText("Fecha final: *"); jlDateEnd.setPreferredSize(new java.awt.Dimension(100, 23)); jPanel5.add(jlDateEnd); jftDateEnd.setText("dd/mm/yyyy"); jftDateEnd.setPreferredSize(new java.awt.Dimension(75, 23)); jPanel5.add(jftDateEnd); jbDateEnd.setIcon(new javax.swing.ImageIcon(getClass().getResource("/erp/img/cal_date_day.gif"))); // NOI18N jbDateEnd.setToolTipText("Seleccionar fecha final"); jbDateEnd.setFocusable(false); jbDateEnd.setPreferredSize(new java.awt.Dimension(23, 23)); jPanel5.add(jbDateEnd); jPanel3.add(jPanel5); jPanel2.add(jPanel3, java.awt.BorderLayout.NORTH); jPanel6.setBorder(javax.swing.BorderFactory.createTitledBorder("Filtros del reporte:")); jPanel6.setLayout(new java.awt.BorderLayout()); jPanel7.setLayout(new java.awt.GridLayout(5, 1, 0, 1)); jPanel8.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0)); jlCompanyBranch.setText("Sucursal de la empresa:"); jlCompanyBranch.setPreferredSize(new java.awt.Dimension(125, 23)); jPanel8.add(jlCompanyBranch); jcbCompanyBranch.setPreferredSize(new java.awt.Dimension(225, 23)); jPanel8.add(jcbCompanyBranch); jPanel7.add(jPanel8); jPanel9.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0)); jlBizPartner.setText("Cliente:"); jlBizPartner.setPreferredSize(new java.awt.Dimension(125, 23)); jPanel9.add(jlBizPartner); jcbBizPartner.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" })); jcbBizPartner.setPreferredSize(new java.awt.Dimension(225, 23)); jPanel9.add(jcbBizPartner); jPanel7.add(jPanel9); jPanel10.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0)); jlShift.setText("Turno:"); jlShift.setPreferredSize(new java.awt.Dimension(125, 23)); jPanel10.add(jlShift); jcbShift.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" })); jcbShift.setPreferredSize(new java.awt.Dimension(225, 23)); jPanel10.add(jcbShift); jPanel7.add(jPanel10); jPanel11.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 3, 0)); jLabel1.setPreferredSize(new java.awt.Dimension(125, 23)); jPanel11.add(jLabel1); jckWithoutRelatedParty.setText("Sin partes relacionadas"); jPanel11.add(jckWithoutRelatedParty); jPanel7.add(jPanel11); jPanel12.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT, 5, 0)); jlBizPartner1.setText("Área funcional:"); jlBizPartner1.setPreferredSize(new java.awt.Dimension(125, 23)); jPanel12.add(jlBizPartner1); jtfFunctionalArea.setEditable(false); jtfFunctionalArea.setPreferredSize(new java.awt.Dimension(225, 23)); jPanel12.add(jtfFunctionalArea); jbFunctionalArea.setText("..."); jbFunctionalArea.setToolTipText("Seleccionar asociado de negocios:"); jbFunctionalArea.setFocusable(false); jbFunctionalArea.setPreferredSize(new java.awt.Dimension(23, 23)); jPanel12.add(jbFunctionalArea); jPanel7.add(jPanel12); jPanel6.add(jPanel7, java.awt.BorderLayout.NORTH); jPanel2.add(jPanel6, java.awt.BorderLayout.CENTER); getContentPane().add(jPanel2, java.awt.BorderLayout.CENTER); setSize(new java.awt.Dimension(496, 339)); setLocationRelativeTo(null); }// </editor-fold>//GEN-END:initComponents private void formWindowActivated(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowActivated windowActivated(); }//GEN-LAST:event_formWindowActivated private void initComponentsExtra() { mvFields = new Vector<>(); moFieldDateInitial = new SFormField(miClient, SLibConstants.DATA_TYPE_DATE, true, jftDateInitial, jlDateInitial); moFieldDateInitial.setPickerButton(jbDateInitial); moFieldDateEnd = new SFormField(miClient, SLibConstants.DATA_TYPE_DATE, true, jftDateEnd, jlDateEnd); moFieldDateEnd.setPickerButton(jbDateEnd); moFieldCompanyBranch = new SFormField(miClient, SLibConstants.DATA_TYPE_KEY, false, jcbCompanyBranch, jlCompanyBranch); moFieldBizPartner = new SFormField(miClient, SLibConstants.DATA_TYPE_KEY, false, jcbBizPartner, jlBizPartner); moFieldShift = new SFormField(miClient, SLibConstants.DATA_TYPE_KEY, false, jcbShift, jlShift); mvFields.add(moFieldDateInitial); mvFields.add(moFieldDateEnd); mvFields.add(moFieldCompanyBranch); mvFields.add(moFieldBizPartner); mvFields.add(moFieldShift); jbPrint.addActionListener(this); jbExit.addActionListener(this); jbDateInitial.addActionListener(this); jbDateEnd.addActionListener(this); jbFunctionalArea.addActionListener(this); AbstractAction actionOk = new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { actionPrint(); } }; SFormUtilities.putActionMap(getRootPane(), actionOk, "print", KeyEvent.VK_ENTER, KeyEvent.CTRL_DOWN_MASK); AbstractAction action = new AbstractAction() { @Override public void actionPerformed(ActionEvent e) { actionClose(); } }; SFormUtilities.putActionMap(getRootPane(), action, "exit", KeyEvent.VK_ESCAPE, 0); setModalityType(ModalityType.MODELESS); // áreas funcionales: jbFunctionalArea.setEnabled(miClient.getSessionXXX().getParamsCompany().getIsFunctionalAreas()); mnFunctionalAreaId = SLibConstants.UNDEFINED; moDialogFilterFunctionalArea = new SDialogFilterFunctionalArea(miClient); renderFunctionalArea(); } private void windowActivated() { if (mbFirstTime) { mbFirstTime = false; if (mbParamIsSupplier) { setTitle("Listado de facturas de proveedores"); jlBizPartner.setText("Proveedor:"); } else { setTitle("Listado de facturas de clientes"); jlBizPartner.setText("Cliente:"); } jftDateInitial.requestFocus(); } } private void actionPrint() { Cursor cursor = getCursor(); SFormValidation validation = formValidate(); Map<String, Object> map = null; JasperPrint jasperPrint = null; JasperViewer jasperViewer = null; String areasFilter = ""; if (miClient.getSessionXXX().getParamsCompany().getIsFunctionalAreas()) { if (msFunctionalAreasIds.isEmpty()) { areasFilter = ""; } else { areasFilter = " AND d.fid_func IN ( " + msFunctionalAreasIds + " ) "; } } if (validation.getIsError()) { if (validation.getComponent() != null) { validation.getComponent().requestFocus(); } if (validation.getMessage().length() > 0) { miClient.showMsgBoxWarning(validation.getMessage()); } } else { try { setCursor(new Cursor(Cursor.WAIT_CURSOR)); map = miClient.createReportParams(); map.put("tDtInitial", moFieldDateInitial.getDate()); map.put("tDtEnd", moFieldDateEnd.getDate()); map.put("sCompanyBranch", moFieldCompanyBranch.getKeyAsIntArray()[0] == 0 ? "(TODAS)" : jcbCompanyBranch.getSelectedItem().toString()); map.put("nFidCtRef", mbParamIsSupplier ? SDataConstantsSys.BPSS_CT_BP_SUP : SDataConstantsSys.BPSS_CT_BP_CUS); map.put("nFidCtDps", mbParamIsSupplier ? SDataConstantsSys.TRNU_TP_DPS_PUR_INV[0] : SDataConstantsSys.TRNU_TP_DPS_SAL_INV[0]); map.put("nFidClDps", mbParamIsSupplier ? SDataConstantsSys.TRNU_TP_DPS_PUR_INV[1] : SDataConstantsSys.TRNU_TP_DPS_SAL_INV[1]); map.put("nFidTpDps", mbParamIsSupplier ? SDataConstantsSys.TRNU_TP_DPS_PUR_INV[2] : SDataConstantsSys.TRNU_TP_DPS_SAL_INV[2]); map.put("sSqlWhereCompanyBranch", moFieldCompanyBranch.getKeyAsIntArray()[0] == 0 ? "" : " AND d.fid_cob = " + moFieldCompanyBranch.getKeyAsIntArray()[0]); map.put("sSqlWhereBizPartner", moFieldBizPartner.getKeyAsIntArray()[0] == 0 ? "" : " AND d.fid_bp_r = " + moFieldBizPartner.getKeyAsIntArray()[0]); map.put("sSqlWhereWithoutRelatedParty", jckWithoutRelatedParty.isSelected() ? " AND b.b_att_rel_pty = 0 " : ""); map.put("sTitle", mbParamIsSupplier ? " DE PROVEEDORES" : " DE CLIENTES"); map.put("sLocalCurrency", miClient.getSessionXXX().getParamsErp().getDbmsDataCurrency().getCurrency()); map.put("sBizPartner", moFieldBizPartner.getKeyAsIntArray()[0] == 0 ? "(TODOS)" : jcbBizPartner.getSelectedItem().toString()); map.put("nFidStDps", SDataConstantsSys.TRNS_ST_DPS_EMITED); map.put("nFidStDpsVal", SDataConstantsSys.TRNS_ST_DPS_VAL_EFF); map.put("nIdCurrencyLocal", miClient.getSessionXXX().getParamsErp().getFkCurrencyId()); map.put("sMark", mbParamIsSupplier ? "" : SDataConstantsSys.TXT_UNSIGNED); String sqlWhereTurn = ""; if (jcbShift.getSelectedIndex() > 0) { SDbShift shift = (SDbShift) miClient.getSession().readRegistry(SModConsts.CFGU_SHIFT, moFieldShift.getKeyAsIntArray()); if (shift.getTimeStart().before(shift.getTimeEnd())) { sqlWhereTurn += "AND (TIME(d.ts_new) BETWEEN '" + SLibUtils.DbmsDateFormatTime.format(shift.getTimeStart()) + "' AND '" + SLibUtils.DbmsDateFormatTime.format(shift.getTimeEnd()) + "') "; } else { sqlWhereTurn += "AND (" + "(d.dt = '" + SLibUtils.DbmsDateFormatDate.format(moFieldDateInitial.getDate()) + "' AND TIME(d.ts_new) >= '" + SLibUtils.DbmsDateFormatTime.format(shift.getTimeStart()) + "') OR " + "(d.dt = '" + SLibUtils.DbmsDateFormatDate.format(moFieldDateEnd.getDate()) + "' AND TIME(d.ts_new) <= '" + SLibUtils.DbmsDateFormatTime.format(shift.getTimeEnd()) + "') OR " + "(d.dt BETWEEN '" + SLibUtils.DbmsDateFormatDate.format(SLibTimeUtils.addDate(moFieldDateInitial.getDate(), 0, 0, 1)) + "' AND '" + SLibUtils.DbmsDateFormatDate.format(SLibTimeUtils.addDate(moFieldDateEnd.getDate(), 0, 0, -1)) + "' AND (" + "TIME(d.ts_new) >= '" + SLibUtils.DbmsDateFormatTime.format(shift.getTimeStart()) + "' OR TIME(d.ts_new) <= '" + SLibUtils.DbmsDateFormatTime.format(shift.getTimeEnd()) + "'))) "; } } map.put("sTurn", jcbShift.getSelectedIndex() <= 0 ? "" : jcbShift.getSelectedItem().toString()); map.put("sFuncText", jtfFunctionalArea.getText()); map.put("sFilterFunctionalArea", areasFilter); map.put("sSqlWhereTurn", sqlWhereTurn); jasperPrint = SDataUtilities.fillReport(miClient, SDataConstantsSys.REP_TRN_DPS_LIST, map); jasperViewer = new JasperViewer(jasperPrint, false); jasperViewer.setTitle("Listado de facturas de " + (mbParamIsSupplier ? "proveedores" : "clientes")); jasperViewer.setVisible(true); } catch(Exception e) { SLibUtilities.renderException(this, e); } finally { setCursor(cursor); } } } private void actionClose() { mnFormResult = SLibConstants.FORM_RESULT_CANCEL; setVisible(false); } private void actionDateInitial() { miClient.getGuiDatePickerXXX().formReset(); miClient.getGuiDatePickerXXX().setDate(moFieldDateInitial.getDate()); miClient.getGuiDatePickerXXX().setVisible(true); if (miClient.getGuiDatePickerXXX().getFormResult() == SLibConstants.FORM_RESULT_OK) { moFieldDateInitial.setFieldValue(miClient.getGuiDatePickerXXX().getGuiDate()); jftDateInitial.requestFocus(); } } private void actionDateEnd() { miClient.getGuiDatePickerXXX().formReset(); miClient.getGuiDatePickerXXX().setDate(moFieldDateEnd.getDate()); miClient.getGuiDatePickerXXX().setVisible(true); if (miClient.getGuiDatePickerXXX().getFormResult() == SLibConstants.FORM_RESULT_OK) { moFieldDateEnd.setFieldValue(miClient.getGuiDatePickerXXX().getGuiDate()); jftDateEnd.requestFocus(); } } private void actionFunctionalArea() { moDialogFilterFunctionalArea.formRefreshCatalogues(); moDialogFilterFunctionalArea.formReset(); moDialogFilterFunctionalArea.setFunctionalAreaId(mnFunctionalAreaId); moDialogFilterFunctionalArea.setFormVisible(true); if (moDialogFilterFunctionalArea.getFormResult() == erp.lib.SLibConstants.FORM_RESULT_OK) { mnFunctionalAreaId = moDialogFilterFunctionalArea.getFunctionalAreaId(); renderFunctionalArea(); } } private void renderFunctionalArea() { String texts[] = STrnFunctionalAreaUtils.getTextFilterOfFunctionalAreas(miClient, mnFunctionalAreaId); msFunctionalAreasIds = texts[0]; jtfFunctionalArea.setText(texts[1]); jtfFunctionalArea.setCaretPosition(0); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JLabel jLabel1; private javax.swing.JPanel jPanel1; private javax.swing.JPanel jPanel10; private javax.swing.JPanel jPanel11; private javax.swing.JPanel jPanel12; private javax.swing.JPanel jPanel2; private javax.swing.JPanel jPanel3; private javax.swing.JPanel jPanel4; private javax.swing.JPanel jPanel5; private javax.swing.JPanel jPanel6; private javax.swing.JPanel jPanel7; private javax.swing.JPanel jPanel8; private javax.swing.JPanel jPanel9; private javax.swing.JButton jbDateEnd; private javax.swing.JButton jbDateInitial; private javax.swing.JButton jbExit; private javax.swing.JButton jbFunctionalArea; private javax.swing.JButton jbPrint; private javax.swing.JComboBox<SFormComponentItem> jcbBizPartner; private javax.swing.JComboBox<SFormComponentItem> jcbCompanyBranch; private javax.swing.JComboBox<SFormComponentItem> jcbShift; private javax.swing.JCheckBox jckWithoutRelatedParty; private javax.swing.JFormattedTextField jftDateEnd; private javax.swing.JFormattedTextField jftDateInitial; private javax.swing.JLabel jlBizPartner; private javax.swing.JLabel jlBizPartner1; private javax.swing.JLabel jlCompanyBranch; private javax.swing.JLabel jlDateEnd; private javax.swing.JLabel jlDateInitial; private javax.swing.JLabel jlShift; private javax.swing.JTextField jtfFunctionalArea; // End of variables declaration//GEN-END:variables @Override public void formClearRegistry() { throw new UnsupportedOperationException("Not supported yet."); } @Override public void formReset() { mnFormResult = SLibConstants.UNDEFINED; mnFormStatus = SLibConstants.UNDEFINED; mbFirstTime = true; for (int i = 0; i < mvFields.size(); i++) { ((erp.lib.form.SFormField) mvFields.get(i)).resetField(); } moFieldDateInitial.setFieldValue(SLibTimeUtilities.getBeginOfMonth(miClient.getSessionXXX().getWorkingDate())); moFieldDateEnd.setFieldValue(SLibTimeUtilities.getEndOfMonth(miClient.getSessionXXX().getWorkingDate())); jckWithoutRelatedParty.setSelected(false); } @Override public void formRefreshCatalogues() { SFormUtilities.populateComboBox(miClient, jcbCompanyBranch, SDataConstants.BPSU_BPB, new int[] { miClient.getSessionXXX().getCurrentCompany().getPkCompanyId() }); SFormUtilities.populateComboBox(miClient, jcbBizPartner, mbParamIsSupplier ? SDataConstants.BPSX_BP_SUP : SDataConstants.BPSX_BP_CUS); SFormUtilities.populateComboBox(miClient, jcbShift, SDataConstants.CFGU_SHIFT); } @Override public erp.lib.form.SFormValidation formValidate() { SFormValidation validation = new SFormValidation(); for (int i = 0; i < mvFields.size(); i++) { if (!((erp.lib.form.SFormField) mvFields.get(i)).validateField()) { validation.setIsError(true); validation.setComponent(((erp.lib.form.SFormField) mvFields.get(i)).getComponent()); break; } } if (!validation.getIsError()) { if (moFieldDateEnd.getDate().compareTo(moFieldDateInitial.getDate()) < 0) { validation.setMessage("La fecha final debe ser mayor o igual a la fecha inicial."); validation.setComponent(jftDateEnd); } } return validation; } @Override public void setFormStatus(int status) { mnFormStatus = status; } @Override public void setFormVisible(boolean visible) { setVisible(visible); } @Override public int getFormStatus() { return mnFormStatus; } @Override public int getFormResult() { return mnFormResult; } @Override public void setRegistry(erp.lib.data.SDataRegistry registry) { throw new UnsupportedOperationException("Not supported yet."); } @Override public erp.lib.data.SDataRegistry getRegistry() { throw new UnsupportedOperationException("Not supported yet."); } @Override public void setValue(int type, java.lang.Object value) { throw new UnsupportedOperationException("Not supported yet."); } @Override public java.lang.Object getValue(int type) { throw new UnsupportedOperationException("Not supported yet."); } @Override public javax.swing.JLabel getTimeoutLabel() { throw new UnsupportedOperationException("Not supported yet."); } @Override public void actionPerformed(java.awt.event.ActionEvent e) { if (e.getSource() instanceof javax.swing.JButton) { javax.swing.JButton button = (javax.swing.JButton) e.getSource(); if (button == jbPrint) { actionPrint(); } else if (button == jbExit) { actionClose(); } else if (button == jbDateInitial) { actionDateInitial(); } else if (button == jbDateEnd) { actionDateEnd(); } else if (button == jbFunctionalArea) { actionFunctionalArea(); } } } public void setParamIsSupplier(boolean b) { mbParamIsSupplier = b; } }
swaplicado/siie32
src/erp/mtrn/form/SDialogRepDpsList.java
Java
mit
25,545
<?php return array( 'controllers' => array( 'factories' => array( \Saas\Controller\Frontend\SaasController::class => \Saas\Controller\Frontend\SaasControllerFactory::class, ), ), 'bjyauthorize' => array( 'guards' => array( 'BjyAuthorize\Guard\Controller' => array( array('controller' => \Saas\Controller\Frontend\SaasController::class, 'roles' => array('guest', 'user')), ), ), ), 'router' => array( 'routes' => array( 'frontend' => array( 'child_routes' => array( 'saas' => array( 'type' => 'Segment', 'options' => array( 'route' => '{saas}', 'defaults' => array( 'controller' => \Saas\Controller\Frontend\SaasController::class, 'action' => 'register', 'title' => 'Playground - Register' ) ) ), ) ) ) ) );
gregorybesson/playground
module/Saas/config/module.config.php
PHP
mit
1,171
#### # # This module allows for easy integration with Slack (https://slack.com/). The # messages are sent via JSON over plaintext, so don't use them for transmitting # anything sensitive. # #### ## Imports import json import urllib2 #### # # API Description # # These are all of the Slack API fields supported in this module. supported_fields = [ # The content of the message. This can be plaintext or Markdown text. 'text', # The name of the bot posting hte webhook integration message. 'username', # The link to an image for the bot's avatar. 'icon_url', # An emoji to use as the bot's image. Overrides 'icon_url'. 'icon_emoji', # Where to post the message. 'channel', # Whether to allow Markdown formatting in the 'text' field. 'mrkdwn', # A list of attachments. 'attachments' ] # These fields are supported as 'attachments' subfields. supported_attachments_subfields = [ # The title of the attachment. 'title', # The pretext. 'pretext', # The actual text. 'text', # Where to allow Markdown. Valid options are: ["pretext", "text", "fields"]. 'mrkdwn_in' ] class IncomingWebhooksSender(object): """ The IncomingWebhooksSender is an object to facilitate using a bot to post to the Slack team communication platform. Slack defines an API of available calls for "incoming webhooks" here: https://api.slack.com/incoming-webhooks This implementation is meant to be fully-featured, but also provides high- level methods that abstract away most of the configuration to make use in scripts easier. (Plus it's easier to read and document.) """ def __init__(self, integration_url, bot_name=None, icon_url=None, icon_emoji=None, channel=None, markdown=None): """ Creates a IncomingWebhooksSender object to send messages to a given Slack team. :param integration_url: The incoming webhook integration URL. This must be supplied at creation (or else the bot is useless). :param bot_name: The name the bot will use when posting. :param icon_url: A URL to use as the bot's icon. :param icon_emoji: A colon emoji to use as the bot's icon. This overrides 'icon_url'. :param channel: The default channel for this bot to post to. :param markdown: Whether to allow markdown (defaults to True if not specified). """ self.url = integration_url self.username = bot_name self.icon_url = icon_url self.icon_emoji = icon_emoji self.channel = channel self.mrkdwn = markdown # Check if the channel has a '#' or '@' at the beginning. If not, # throw an error. if not self.username and self.username is not None: raise ValueError("Null username specified.") if not self.channel and self.channel is not None: raise ValueError("Null channel specified.") if (channel is not None and not self.channel.startswith('#') and not self.channel.startswith('@')): raise ValueError( "Invalid channel. Need a '#' for channels or '@' for direct " + "messages." ) ############################################################################ # Public methods. def send_message(self, message): """ Sends a message to the default channel for this webhook (which is determined by the URL passed in during object construction). :param message: Message text you want to send. """ data = {'text': str(message)} self.__prep_and_send_data(data) def success(self, message=None): """ Sends a check mark with a message (if desired). :param message: An optional string to include. """ send_message = ":white_check_mark:" if message: send_message += " " + str(message) data = {'text': str(send_message)} self.__prep_and_send_data(data) def warning(self, message=None): """ Sends a yellow warning sign with a message (if desired). :param message: An optional string to include. """ send_message = ":warning:" if message: send_message += " " + str(message) data = {'text': str(send_message)} self.__prep_and_send_data(data) warn = warning def error(self, message=None): """ Sends a red circle with a message (if desired). :param message: An optional string to include. """ send_message = ":red_circle:" if message: send_message += " " + str(message) data = {'text': str(send_message)} self.__prep_and_send_data(data) critical = error def send_message_to_channel(self, message, channel): """ Sends a message to a specific channel. Use '#' for channels and private groups, and '@' for direct messages. For example: #general #my-private-group @someguy :param message: Message text you want to send. :param channel: The channel to which you want to send the data. """ data = { 'text': str(message), 'channel': channel } self.__prep_and_send_data(data) def send_dictionary(self, dictionary): """ Takes any dictionary and sends it through. It will be verified first, so the dictionary must only use the available fields in the Slack API. Note that with this method, you can send any message with any name to any channel, et cetera. :param dictionary: A dictionary of values you want to send. """ self.__prep_and_send_data(dictionary) ############################################################################ # Private methods. def __prep_and_send_data(self, data): """ Takes a dictionary and prepares it for transmission, then sends it. :param data: A map of Slack API fields to desired values. :type data: dict """ data = self.__update_data(data) self.__send_json(self.__prep_json_from_data(data)) def __update_data(self, data): """ Automatically updates the contents of the 'data' object with any fields that are set in the object but weren't specified in the data. This makes method calls simpler. This method will also verify the data in the dictionary. :param data: A map of Slack API fields to desired values. :type data: dict :returns: A copy of the `data` dictionary, but with extra values if they were specified in the object constructor. """ # Duplicate the data to make this method non-destructive. return_data = dict(data) # Iterate over each of the supported fields. for field in supported_fields: # Let's see if we have a value defined for that attribute. # Note that this requires the object's attributes to have the same # name as the Slack API fields. try: value = getattr(self, field) except AttributeError: # Didn't have it, but let's not throw an error. Just continue. continue # If the field isn't already in the data, add it. # This ensure that overriding calls are not overridden themselves. if value is not None and not field in return_data: return_data[field] = value # Ensure the dictionary is good-to-go. self.__verify_data(data) return return_data def __verify_data(self, data): """ Verifies that all of the fields in the `data` dictionary are valid. If any field is found that isn't considered a supported field, an error is raised. This also checks inside the list of attachments (if it's present) to be sure nothing is wrong. :param data: A map of Slack API fields to desired values. :type data: dict """ # Check it's a dictionary. if not isinstance(data, dict): raise ValueError("Received a non-dictionary form of data.") # Iterate over every key. for key in data: # If the key isn't supported, that's a problem! if not key in supported_fields: raise ValueError("Bad key in data: {}".format(key)) # The 'attachments' key should contain a list. if key == 'attachments': # Verify it's really a list. if not isinstance(data[key], list): raise ValueError("'attachments' field in data must be a list.") # Ensure there are no rogue values. for subkey in data[key]: if not subkey in supported_attachments_subfields: raise ValueError("Bad key in 'attachments': {}".format(subkey)) def __prep_json_from_data(self, data): """ Given data, this updates the contents and then gives back the string form of the JSON data. :param data: A map of Slack API fields to desired values. :type data: dict :returns: A string form of the dictionary. """ # Update all the data. data = self.__update_data(data) # Return the JSON string form of the data. return self.__get_json_from_data(data) def __get_json_from_data(self, data): """ Just gives back a string form of the data. This is just a wrapper so the 'json' module doesn't have to be loaded in addition to this one. :param data: A map of Slack API fields to desired values. :type data: dict :returns: The string format returned by `json.dumps(data)`. """ return json.dumps(data) def __send_json(self, data): """ Sends the given JSON data across an HTTP connection. This does not check if the data is valid. This is by design to ensure that if I ever mess something up with the `supported_fields` list or something, the object can still be used to send anything. :param data: JSON representation of a map of Slack API fields to desired values. :type data: str """ # Form the HTTP PUT request. request = urllib2.Request(self.url, data) # Send the data! urllib2.urlopen(request)
univ-of-utah-marriott-library-apple/management_tools
management_tools/slack.py
Python
mit
10,760
version https://git-lfs.github.com/spec/v1 oid sha256:91f5e00183c2613cc249e316de2c35c08d8068c7e57cf90d3d4ea7b0179ef7cf size 651743
yogeshsaroya/new-cdnjs
ajax/libs/yasgui/0.0.6/yasgui.min.js
JavaScript
mit
131
'use strict'; const inView = require('in-view'); const forEach = require('lodash/forEach'); require('gsap'); class Animations { constructor () { this.root = document; this.h1 = this.root.querySelector('[data-hat-title] h1'); this.curtainH1 = this.root.querySelector('[data-curtain-goRight]'); this.goUps = this.root.querySelectorAll('[data-stagger-goUp]'); this.skillsItems = this.root.querySelectorAll('[data-skills-item]'); this.experienceP = this.root.querySelectorAll('[data-experience-container]'); this.portfolioItems = this.root.querySelectorAll('[data-portfolio-item]'); this.map = this.root.querySelector('[data-map]'); this.travelsDescription = this.root.querySelector('[data-travels-p]'); this.contactContainer = this.root.querySelector('[data-contact-container]'); this.animationStarted = false; this.textSpanned = false; } } Animations.prototype.init = function () { if(this.animationStarted) { return; } this.setup(); window.setTimeout(this.animateH1.bind(this), 1000); this.addListenerDescription(); this.addListenerSkillsH2(); this.addListenerExperienceH2(); this.addListenerTravelsH2(); this.addListenerPortfolioH2(); this.addListenerContactH2(); this.triggerResize(); this.animationStarted = true; }; Animations.prototype.setup = function () { TweenMax.set(this.skillsItems, {opacity: 0, yPercent: 100}); TweenMax.set(this.travelsDescription, {opacity: 0}); TweenMax.set(this.map, {opacity: 0}); TweenMax.set(this.experienceP, {opacity: 0}); TweenMax.set(this.portfolioItems, {opacity: 0, yPercent: 100}); TweenMax.set(this.contactContainer, {opacity: 0, yPercent: 100}); this.h2ToBeSpanned = this.root.querySelectorAll('[data-to-be-spanned]'); forEach(this.h2ToBeSpanned, function (title) { let titleMod = title.innerText.split(''); let tmparray = []; forEach(titleMod, function (letter, index) { tmparray[index] = '<span class="letter-box" data-letter-box>' + letter + '</span>'; }); title.innerHTML = tmparray.join(''); }); this.textSpanned = true; }; Animations.prototype.triggerResize = function () { window.dispatchEvent(new Event('resize')); }; Animations.prototype.animateH1 = function () { const spans = this.h1.querySelectorAll('span'); const tl = new TimelineLite({onComplete: this.afterH1.bind(this)}); tl.to(this.curtainH1, .55, {xPercent: 100, ease: Power4.easeOut}); tl.to(this.h1, .22, {opacity: 1}); tl.add('retire-line'); tl.to(this.curtainH1, .66, {xPercent: 200, ease: Power3.easeIn}); tl.staggerTo(spans, 0, {opacity: 1, ease: Power3.easeIn, delay: .38}, .08, 'retire-line'); }; Animations.prototype.afterH1 = function () { this.curtainH1.remove(); TweenMax.staggerTo(this.goUps, .22, {yPercent: -100, opacity: 1, onComplete: this.animateMenu.bind(this) }, .11); }; Animations.prototype.animateMenu = function () { const links = this.root.querySelectorAll('[data-audio-play]'); TweenMax.staggerTo(links, .21, {opacity: 1, yPercent: 100, delay: .66}, .08); }; Animations.prototype.addListenerDescription = function () { inView('[data-description]') .once('enter', function(el) { el.style.opacity = 1; }.bind(this)); }; //Skills Animations.prototype.addListenerSkillsH2 = function () { inView('[data-skills]') .once('enter', function(el){ this.animateSkillsH2(el); }.bind(this)); }; Animations.prototype.animateSkillsH2 = function (el) { const titleH2 = el.querySelector('[data-skills-title] h2'); this.skillsCurtainH2 = el.querySelector('[data-curtain-goRight]'); const tl = new TimelineLite({onComplete: this.afterSkillsH2.bind(this)}); tl.to(this.skillsCurtainH2, .55, {xPercent: 100, ease: Power4.easeOut}); tl.to(titleH2, .22, {opacity: 1}); tl.add('retire-line'); tl.to(this.skillsCurtainH2, .66, {xPercent: 200, ease: Power3.easeIn}); tl.staggerTo(titleH2.querySelectorAll('span'), 0, {opacity: 1, ease: Power3.easeIn, delay: .38}, .08, 'retire-line'); }; Animations.prototype.afterSkillsH2 = function () { this.skillsCurtainH2.remove(); this.animateSkillsItems(); }; Animations.prototype.animateSkillsItems = function (el) { TweenMax.staggerTo(this.skillsItems, .41, {opacity: 1, yPercent: 0, delay: .55}, .18); }; //Experience Animations.prototype.addListenerExperienceH2 = function () { inView('[data-experience]') .once('enter', function(el){ this.animateExperienceH2(el); }.bind(this)); }; Animations.prototype.animateExperienceH2 = function (el) { const titleH2 = el.querySelector('[data-experience-title] h2'); this.experienceCurtainH2 = el.querySelector('[data-curtain-goRight]'); const tl = new TimelineLite({onComplete: this.afterExperienceH2.bind(this)}); tl.to(this.experienceCurtainH2, .55, {xPercent: 100, ease: Power4.easeOut}); tl.to(titleH2, .22, {opacity: 1}); tl.add('retire-line'); tl.to(this.experienceCurtainH2, .66, {xPercent: 203, ease: Power3.easeIn}); tl.staggerTo(titleH2.querySelectorAll('span'), 0, {opacity: 1, ease: Power3.easeIn, delay: .38}, .08, 'retire-line'); }; Animations.prototype.afterExperienceH2 = function () { this.experienceCurtainH2.remove(); TweenMax.to(this.experienceP, 1, {opacity: 1, ease: Power3.easeIn}); } //Travels Animations.prototype.addListenerTravelsH2 = function () { inView('[data-travels]') .once('enter', function(el) { this.animateTravelsH2(el); }.bind(this)); }; Animations.prototype.animateTravelsH2 = function (el) { const titleH2 = el.querySelector('[data-travels-title] h2'); this.arrows = document.getElementById('freccette'); this.travelsCurtainH2 = el.querySelector('[data-curtain-goRight]'); const tl = new TimelineLite({onComplete: this.afterTravelsH2.bind(this)}); tl.to(this.travelsCurtainH2, .55, {xPercent: 100, ease: Power4.easeOut}); tl.to(titleH2, .22, {opacity: 1}); tl.add('retire-line'); tl.to(this.travelsCurtainH2, .66, {xPercent: 200, ease: Power3.easeIn}); tl.staggerTo(titleH2.querySelectorAll('span'), 0, {opacity: 1, ease: Power3.easeIn, delay: .38}, .08, 'retire-line'); }; Animations.prototype.afterTravelsH2 = function () { this.travelsCurtainH2.remove(); TweenMax.to(this.map, .33, {opacity: 1}); this.arrows.classList.add('visible'); TweenMax.to(this.travelsDescription, .44, {opacity: 1, ease: Power3.easeOut}); }; //Portfolio Animations.prototype.addListenerPortfolioH2 = function () { inView('[data-portfolio]') .once('enter', function(el) { this.animatePortfolioH2(el); }.bind(this)); }; Animations.prototype.animatePortfolioH2 = function (el) { const titleH2 = el.querySelector('[data-portfolio-title] h2'); this.portfolioCurtainH2 = el.querySelector('[data-curtain-goRight]'); const tl = new TimelineLite({onComplete: this.afterPortfolioH2.bind(this)}); tl.to(this.portfolioCurtainH2, .55, {xPercent: 100, ease: Power4.easeOut}); tl.to(titleH2, .22, {opacity: 1}); tl.add('retire-line'); tl.to(this.portfolioCurtainH2, .66, {xPercent: 200, ease: Power3.easeIn}); tl.staggerTo(titleH2.querySelectorAll('span'), 0, {opacity: 1, ease: Power3.easeIn, delay: .38}, .08, 'retire-line'); }; Animations.prototype.afterPortfolioH2 = function () { this.portfolioCurtainH2.remove(); this.animatePortfolioItems(); }; Animations.prototype.animatePortfolioItems = function (el) { TweenMax.staggerTo(this.portfolioItems, .88, {opacity: 1, yPercent: 0, ease: Power3.easeOut}, .28); }; //Contact Animations.prototype.addListenerContactH2 = function () { inView('[data-contact]') .once('enter', function(el) { this.animateContactH2(el); }.bind(this)); }; Animations.prototype.animateContactH2 = function (el) { const titleH2 = el.querySelector('[data-contact-title] h2'); this.contactCurtainH2 = el.querySelector('[data-curtain-goRight]'); const tl = new TimelineLite({onComplete: this.afterContactH2.bind(this)}); tl.to(this.contactCurtainH2, .55, {xPercent: 100, ease: Power4.easeOut}); tl.to(titleH2, .22, {opacity: 1}); tl.add('retire-line'); tl.to(this.contactCurtainH2, .66, {xPercent: 200, ease: Power3.easeIn}); tl.staggerTo(titleH2.querySelectorAll('span'), 0, {opacity: 1, ease: Power3.easeIn, delay: .38}, .08, 'retire-line'); }; Animations.prototype.afterContactH2 = function () { this.contactCurtainH2.remove(); TweenMax.to(this.contactContainer, .33, {opacity: 1, yPercent: 0}); }; Animations.prototype.destroy = function () { TweenMax.set(this.skillsItems, {clearProps: 'all'}); TweenMax.set(this.portfolioItems, {clearProps: 'all'}); TweenMax.set(this.map, {clearProps: 'all'}); TweenMax.set(this.experienceP, {clearProps: 'all'}); if(this.textSpanned) { this.clearTextFromSpan(); } }; Animations.prototype.clearTextFromSpan = function () { forEach(this.h2ToBeSpanned, function (title) { let titleInner = title.querySelectorAll('[data-letter-box]'); let tmparray = []; forEach(titleInner, function(el, index){ tmparray[index] = el.innerText; }); title.innerHTML = tmparray.join(''); }); this.textSpanned = false; }; module.exports = Animations;
dnlml/myvc
src/assets/scripts/parts/animations.js
JavaScript
mit
9,136
<?php namespace Quoty\QuoteBundle\Entity; use Doctrine\ORM\Mapping as ORM; /** * Category * * @ORM\Table() * @ORM\Entity(repositoryClass="Quoty\QuoteBundle\Entity\CategoryRepository") */ class Category { /** * @var integer * * @ORM\Column(name="id", type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * @var string * * @ORM\Column(name="name", type="string", length=255, unique=true) */ private $name; public function __construct($name = "Inconnu") { $this->name = $name; } /** * Get id * * @return integer */ public function getId() { return $this->id; } /** * Set name * * @param string $name * @return Category */ public function setName($name) { $this->name = $name; return $this; } /** * Get name * * @return string */ public function getName() { return $this->name; } }
Elfhir/quoty
src/Quoty/QuoteBundle/Entity/Category.php
PHP
mit
903
"use strict"; var notify = require("gulp-notify"); module.exports = function(error) { if( !global.isProd ) { var args = Array.prototype.slice.call(arguments); // Send error to notification center with gulp-notify notify.onError({ title: "Compile Error", message: "<%= error.message %>" }).apply(this, args); // Keep gulp from hanging on this task this.emit("end"); } else { // Log the error and stop the process // to prevent broken code from building console.log(error); process.exit(1); } };
polygon-city/citygml-visual-debugger
gulp/util/handleErrors.js
JavaScript
mit
560
<?php namespace Olegf13\Jivochat\Webhooks\Request; use Olegf13\Jivochat\Webhooks\PopulateObjectViaArray; /** * Holds data on completed chatting (chat rank and messages list). * * @package Olegf13\Jivochat\Webhooks\Request */ class Chat { use PopulateObjectViaArray; /** * @var Message[] Messages list. See {@link Message} for details. * @todo: create MessageCollection with aggregated data (messages count, etc) */ public $messages; /** @var string|null User chat rank ("positive"|"negative"|null). */ public $rate; /** @var bool|null A sign that the user was added to the black list (e.g. false). */ public $blacklisted; // todo: add `chat_started_at` and `chat_ended_at` properties /** * Setter for {@link messages} property. * * @param array $messages * @throws \InvalidArgumentException */ public function setMessages(array $messages) { /** @var Agent $agent */ foreach ($messages as $data) { if (!is_array($data) && !($data instanceof Message)) { throw new \InvalidArgumentException('Invalid data given.'); } if (is_array($data)) { $message = new Message(); $message->populate($data); $this->messages[] = $message; continue; } if ($data instanceof Message) { $this->messages[] = $data; continue; } } } }
Olegf13/jivochat-webhooks-api
src/Request/Chat.php
PHP
mit
1,516
/* colorstrip.js, a plugin for jQuery Copyright (C) 2011 John Watson <john@flagrantdisregard.com> flagrantdisregard.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ (function($) { var colorstrip = new Object; var settings = { maxInterval: 8000, /* milliseconds */ minInterval: 4000, /* milliseconds */ opacity: 0.5, /* 0..1 */ minWidth: 10, /* percent */ maxWidth: 80, /* percent */ colors: ['#c00', '#0c0', '#00c'] }; var strips = []; var timeouts = []; colorstrip.start = function() { var s = colorstrip.target; for(var i=0; i<settings.colors.length; i++) { var e = $('<div>'); e.css( { height: '100%', width: '30%', position: 'absolute', top: 0, left: Math.random()*$(s).width(), opacity: settings.opacity, 'background-color': settings.colors[i] } ); strips.push(e); colorstrip.target.append(e); colorstrip.animate(e); } } colorstrip.animate = function(e) { if (e == undefined) return; var s = colorstrip.target; var n = strips.length; var left = $(e).position().left; var right = $(e).position().left + $(e).width(); $(e).stop(); if (left > $(s).width()) { $(e).css({left: -$(e).width(), 'z-index': Math.random()*n}); } if (right < 0) { $(e).css({left: $(s).width(), 'z-index': Math.random()*n}); } var range = $(s).width() + $(e).width(); var timeout = Math.random()*(settings.maxInterval-settings.minInterval)+settings.minInterval; $(e).animate( { left: Math.random()*range - $(e).width(), width: (Math.random()*(settings.maxWidth-settings.minWidth)+settings.minWidth) + '%' }, timeout, 'easeInOutSine'); timeouts.push(setTimeout(function(){colorstrip.animate(e)}, timeout)); } colorstrip.stop = function() { for(var i=0;i<timeouts.length;i++) { clearTimeout(timeouts[i]); } for(var i=0;i<strips.length;i++) { strips[i].stop(); } } $.fn.colorstrip = function(method, options) { if (typeof method == 'object') { $.extend(settings, method); } if (typeof options == 'object') { $.extend(settings, options); } if (colorstrip[method]) { colorstrip[method](); } else { colorstrip.target = this; colorstrip.start(); } } })(jQuery);
Overdriven-Labs/Mexicoen140
app_server/public/js/colorstrip.js
JavaScript
mit
3,808
<?php defined('SYSPATH') OR die('No direct script access.'); return array( // Leave this alone 'modules' => array( // This should be the path to this modules userguide pages, without the 'guide/'. Ex: '/guide/modulename/' would be 'modulename' 'functest' => array( // Whether this modules userguide pages should be shown 'enabled' => TRUE, // The name that should show up on the userguide index page 'name' => 'Functiaonl Test', ) ) );
OpenBuildings/functest
config/userguide.php
PHP
mit
464
/* Matali Physics Demo Copyright (c) 2013 KOMIRES Sp. z o. o. */ using System; using System.Collections.Generic; using OpenTK; using OpenTK.Graphics.OpenGL; using Komires.MataliPhysics; namespace MataliPhysicsDemo { /// <summary> /// This is the main type for your game /// </summary> public class Menu { Demo demo; PhysicsScene scene; string instanceIndexName; public Menu(Demo demo, int instanceIndex) { this.demo = demo; instanceIndexName = " " + instanceIndex.ToString(); } public void Initialize(PhysicsScene scene) { this.scene = scene; } public static void CreateShapes(Demo demo, PhysicsScene scene) { } public void Create() { Shape sphere = scene.Factory.ShapeManager.Find("Sphere"); Shape box = scene.Factory.ShapeManager.Find("Box"); Shape coneY = scene.Factory.ShapeManager.Find("ConeY"); PhysicsObject objectRoot = null; PhysicsObject objectBase = null; Constraint constraint = null; string switchInstanceName = null; Vector3 position1 = Vector3.Zero; Quaternion orientation1 = Quaternion.Identity; for (int i = 0; i < 5; i++) { switchInstanceName = "Switch " + i.ToString(); objectBase = scene.Factory.PhysicsObjectManager.Create(switchInstanceName + instanceIndexName); objectBase.Shape = box; objectBase.UserDataStr = "Box"; objectBase.Material.UserDataStr = "Wood1"; objectBase.Material.SetDiffuse(1.0f, 1.0f, 1.0f); objectBase.Material.TransparencyFactor = 0.9f; objectBase.InitLocalTransform.SetPosition(-22.0f + 11.0f * i, 25.0f, 20.0f); objectBase.InitLocalTransform.SetScale(5.0f, 4.0f, 0.4f); objectBase.Integral.SetDensity(10.0f); objectBase.EnableScreenToRayInteraction = true; objectBase.UpdateFromInitLocalTransform(); constraint = scene.Factory.ConstraintManager.Create(switchInstanceName + " Slider Constraint" + instanceIndexName); constraint.PhysicsObject1 = scene.Factory.PhysicsObjectManager.Find(switchInstanceName + instanceIndexName); constraint.PhysicsObject2 = null; constraint.PhysicsObject1.MainWorldTransform.GetPosition(ref position1); constraint.PhysicsObject1.MainWorldTransform.GetOrientation(ref orientation1); constraint.SetAnchor1(ref position1); constraint.SetAnchor2(ref position1); constraint.SetInitWorldOrientation1(ref orientation1); constraint.MinLimitDistanceZ = -5.0f; constraint.EnableLimitAngleX = true; constraint.EnableLimitAngleY = true; constraint.EnableLimitAngleZ = true; constraint.Update(); constraint = scene.Factory.ConstraintManager.Create(switchInstanceName + " Spring Constraint" + instanceIndexName); constraint.PhysicsObject1 = scene.Factory.PhysicsObjectManager.Find(switchInstanceName + instanceIndexName); constraint.PhysicsObject2 = null; constraint.PhysicsObject1.MainWorldTransform.GetPosition(ref position1); constraint.PhysicsObject1.MainWorldTransform.GetOrientation(ref orientation1); constraint.SetAnchor1(ref position1); constraint.SetAnchor2(ref position1); constraint.SetInitWorldOrientation1(ref orientation1); constraint.EnableSpringMode = true; constraint.Force = 0.01f; constraint.Update(); scene.UpdateFromInitLocalTransform(objectBase); } for (int i = 0; i < 5; i++) { switchInstanceName = "Switch " + (i + 5).ToString(); objectBase = scene.Factory.PhysicsObjectManager.Create(switchInstanceName + instanceIndexName); objectBase.Shape = box; objectBase.UserDataStr = "Box"; objectBase.Material.UserDataStr = "Wood1"; objectBase.Material.SetDiffuse(1.0f, 1.0f, 1.0f); objectBase.Material.TransparencyFactor = 0.9f; objectBase.InitLocalTransform.SetPosition(-22.0f + 11.0f * i, 16.0f, 20.0f); objectBase.InitLocalTransform.SetScale(5.0f, 4.0f, 0.4f); objectBase.Integral.SetDensity(10.0f); objectBase.EnableScreenToRayInteraction = true; objectBase.UpdateFromInitLocalTransform(); constraint = scene.Factory.ConstraintManager.Create(switchInstanceName + " Slider Constraint" + instanceIndexName); constraint.PhysicsObject1 = scene.Factory.PhysicsObjectManager.Find(switchInstanceName + instanceIndexName); constraint.PhysicsObject2 = null; constraint.PhysicsObject1.MainWorldTransform.GetPosition(ref position1); constraint.PhysicsObject1.MainWorldTransform.GetOrientation(ref orientation1); constraint.SetAnchor1(ref position1); constraint.SetAnchor2(ref position1); constraint.SetInitWorldOrientation1(ref orientation1); constraint.MinLimitDistanceZ = -5.0f; constraint.EnableLimitAngleX = true; constraint.EnableLimitAngleY = true; constraint.EnableLimitAngleZ = true; constraint.Update(); constraint = scene.Factory.ConstraintManager.Create(switchInstanceName + " Spring Constraint" + instanceIndexName); constraint.PhysicsObject1 = scene.Factory.PhysicsObjectManager.Find(switchInstanceName + instanceIndexName); constraint.PhysicsObject2 = null; constraint.PhysicsObject1.MainWorldTransform.GetPosition(ref position1); constraint.PhysicsObject1.MainWorldTransform.GetOrientation(ref orientation1); constraint.SetAnchor1(ref position1); constraint.SetAnchor2(ref position1); constraint.SetInitWorldOrientation1(ref orientation1); constraint.EnableSpringMode = true; constraint.Force = 0.01f; constraint.Update(); scene.UpdateFromInitLocalTransform(objectBase); } objectBase = scene.Factory.PhysicsObjectManager.Create("Switch Right Light" + instanceIndexName); objectBase.Shape = sphere; objectBase.UserDataStr = "Sphere"; objectBase.CreateLight(true); objectBase.Light.Type = PhysicsLightType.Point; objectBase.Light.SetDiffuse(0.5f, 0.5f, 0.5f); objectBase.Light.Range = 20.0f; objectBase.Material.UserDataStr = "Yellow"; objectBase.InitLocalTransform.SetPosition(34.0f, 20.5f, 10.0f); objectBase.InitLocalTransform.SetScale(20.0f); objectBase.EnableCollisions = false; objectBase.EnableCursorInteraction = false; objectBase.EnableAddToCameraDrawTransparentPhysicsObjects = false; scene.UpdateFromInitLocalTransform(objectBase); objectBase = scene.Factory.PhysicsObjectManager.Create("Switch Right" + instanceIndexName); objectBase.Shape = coneY; objectBase.UserDataStr = "ConeY"; objectBase.Material.UserDataStr = "Yellow"; objectBase.Material.SetDiffuse(1.0f, 1.0f, 1.0f); objectBase.Material.TransparencyFactor = 0.9f; objectBase.InitLocalTransform.SetPosition(32.0f, 20.5f, 20.0f); objectBase.InitLocalTransform.SetScale(5.0f, 3.0f, 0.4f); objectBase.InitLocalTransform.SetOrientation(Quaternion.FromAxisAngle(Vector3.UnitZ, MathHelper.DegreesToRadians(90.0f)) * Quaternion.FromAxisAngle(Vector3.UnitY, MathHelper.DegreesToRadians(-10.0f))); objectBase.Integral.SetDensity(10.0f); objectBase.EnableScreenToRayInteraction = true; objectBase.UpdateFromInitLocalTransform(); constraint = scene.Factory.ConstraintManager.Create("Switch Right Slider Constraint" + instanceIndexName); constraint.PhysicsObject1 = scene.Factory.PhysicsObjectManager.Find("Switch Right" + instanceIndexName); constraint.PhysicsObject2 = null; constraint.PhysicsObject1.MainWorldTransform.GetPosition(ref position1); constraint.PhysicsObject1.MainWorldTransform.GetOrientation(ref orientation1); constraint.SetAnchor1(ref position1); constraint.SetAnchor2(ref position1); constraint.SetInitWorldOrientation1(ref orientation1); constraint.MinLimitDistanceZ = -5.0f; constraint.EnableLimitAngleX = true; constraint.EnableLimitAngleY = true; constraint.EnableLimitAngleZ = true; constraint.Update(); constraint = scene.Factory.ConstraintManager.Create("Switch Right Spring Constraint" + instanceIndexName); constraint.PhysicsObject1 = scene.Factory.PhysicsObjectManager.Find("Switch Right" + instanceIndexName); constraint.PhysicsObject2 = null; constraint.PhysicsObject1.MainWorldTransform.GetPosition(ref position1); constraint.PhysicsObject1.MainWorldTransform.GetOrientation(ref orientation1); constraint.SetAnchor1(ref position1); constraint.SetAnchor2(ref position1); constraint.SetInitWorldOrientation1(ref orientation1); constraint.EnableSpringMode = true; constraint.Force = 0.01f; constraint.Update(); scene.UpdateFromInitLocalTransform(objectBase); objectBase = scene.Factory.PhysicsObjectManager.Create("Switch Left Light" + instanceIndexName); objectBase.Shape = sphere; objectBase.UserDataStr = "Sphere"; objectBase.CreateLight(true); objectBase.Light.Type = PhysicsLightType.Point; objectBase.Light.SetDiffuse(0.5f, 0.5f, 0.5f); objectBase.Light.Range = 20.0f; objectBase.Material.UserDataStr = "Yellow"; objectBase.InitLocalTransform.SetPosition(-34.0f, 20.5f, 10.0f); objectBase.InitLocalTransform.SetScale(20.0f); objectBase.EnableCollisions = false; objectBase.EnableCursorInteraction = false; objectBase.EnableAddToCameraDrawTransparentPhysicsObjects = false; scene.UpdateFromInitLocalTransform(objectBase); objectBase = scene.Factory.PhysicsObjectManager.Create("Switch Left" + instanceIndexName); objectBase.Shape = coneY; objectBase.UserDataStr = "ConeY"; objectBase.Material.UserDataStr = "Yellow"; objectBase.Material.SetDiffuse(1.0f, 1.0f, 1.0f); objectBase.Material.TransparencyFactor = 0.9f; objectBase.InitLocalTransform.SetPosition(-32.0f, 20.5f, 20.0f); objectBase.InitLocalTransform.SetScale(5.0f, 3.0f, 0.4f); objectBase.InitLocalTransform.SetOrientation(Quaternion.FromAxisAngle(Vector3.UnitZ, MathHelper.DegreesToRadians(-90.0f)) * Quaternion.FromAxisAngle(Vector3.UnitY, MathHelper.DegreesToRadians(10.0f))); objectBase.Integral.SetDensity(10.0f); objectBase.EnableScreenToRayInteraction = true; objectBase.UpdateFromInitLocalTransform(); constraint = scene.Factory.ConstraintManager.Create("Switch Left Slider Constraint" + instanceIndexName); constraint.PhysicsObject1 = scene.Factory.PhysicsObjectManager.Find("Switch Left" + instanceIndexName); constraint.PhysicsObject2 = null; constraint.PhysicsObject1.MainWorldTransform.GetPosition(ref position1); constraint.PhysicsObject1.MainWorldTransform.GetOrientation(ref orientation1); constraint.SetAnchor1(ref position1); constraint.SetAnchor2(ref position1); constraint.SetInitWorldOrientation1(ref orientation1); constraint.MinLimitDistanceZ = -5.0f; constraint.EnableLimitAngleX = true; constraint.EnableLimitAngleY = true; constraint.EnableLimitAngleZ = true; constraint.Update(); constraint = scene.Factory.ConstraintManager.Create("Switch Left Spring Constraint" + instanceIndexName); constraint.PhysicsObject1 = scene.Factory.PhysicsObjectManager.Find("Switch Left" + instanceIndexName); constraint.PhysicsObject2 = null; constraint.PhysicsObject1.MainWorldTransform.GetPosition(ref position1); constraint.PhysicsObject1.MainWorldTransform.GetOrientation(ref orientation1); constraint.SetAnchor1(ref position1); constraint.SetAnchor2(ref position1); constraint.SetInitWorldOrientation1(ref orientation1); constraint.EnableSpringMode = true; constraint.Force = 0.01f; constraint.Update(); scene.UpdateFromInitLocalTransform(objectBase); objectRoot = scene.Factory.PhysicsObjectManager.Create("Info" + instanceIndexName); objectRoot.EnableMoving = false; objectRoot.DrawPriority = 1; objectBase = scene.Factory.PhysicsObjectManager.Create("Info Description" + instanceIndexName); objectRoot.AddChildPhysicsObject(objectBase); objectBase.Shape = box; objectBase.UserDataStr = "Box"; objectBase.Material.UserDataStr = "Wood1"; objectBase.Material.RigidGroup = true; objectBase.Material.SetAmbient(0.51f, 0.52f, 0.51f); objectBase.Material.SetDiffuse(1.0f, 1.0f, 1.0f); objectBase.Material.TransparencyFactor = 0.9f; objectBase.InitLocalTransform.SetPosition(0.0f, -6.0f, 20.0f); objectBase.InitLocalTransform.SetScale(15.0f, 27.0f, 0.4f); objectBase.InitLocalTransform.SetOrientation(Quaternion.FromAxisAngle(Vector3.UnitZ, MathHelper.DegreesToRadians(90.0f))); objectBase.Integral.SetDensity(1.0f); objectBase.EnableDrawing = false; objectBase.EnableCollisionResponse = false; objectBase.EnableMoving = false; objectBase = scene.Factory.PhysicsObjectManager.Create("Info Screen" + instanceIndexName); objectRoot.AddChildPhysicsObject(objectBase); objectBase.Shape = box; objectBase.UserDataStr = "Box"; objectBase.Material.UserDataStr = "Wood1"; objectBase.Material.RigidGroup = true; objectBase.Material.SetDiffuse(1.0f, 1.0f, 1.0f); objectBase.Material.TransparencyFactor = 0.9f; objectBase.InitLocalTransform.SetPosition(18.2f, 1.6f, 20.0f - 0.4f - 0.01f); objectBase.InitLocalTransform.SetScale(7.0f, 6.0f, 0.01f); objectBase.Integral.SetDensity(1.0f); objectBase.EnableDrawing = false; objectBase.EnableCollisionResponse = false; objectBase.EnableMoving = false; scene.UpdateFromInitLocalTransform(objectRoot); } } }
stomppah/KAOS-Engine
Dependencies/MataliPhysicsBasic/MataliPhysicsOpenTK/Mono/MataliPhysicsDemo/MataliPhysicsDemo/Objects/Menu.cs
C#
mit
15,509
<?php // FrontendBundle:Pedido:reporteGeneral.html.twig return array ( 'b9ccb8c' => array ( 0 => array ( 0 => 'bundles/frontend/css/jquery.dataTables.css', ), 1 => array ( 0 => 'cssrewrite', ), 2 => array ( 'output' => '_controller/css/b9ccb8c.css', 'name' => 'b9ccb8c', 'debug' => NULL, 'combine' => NULL, 'vars' => array ( ), ), ), '1c983ea' => array ( 0 => array ( 0 => 'bundles/frontend/css/bootstrap.min.css', 1 => '@FrontendBundle/Resources/public/css/bootstrap-theme.min.css', 2 => '@FrontendBundle/Resources/public/css/main.css', ), 1 => array ( 0 => 'cssrewrite', ), 2 => array ( 'output' => '_controller/css/1c983ea.css', 'name' => '1c983ea', 'debug' => NULL, 'combine' => NULL, 'vars' => array ( ), ), ), '25d9041' => array ( 0 => array ( 0 => '@FrontendBundle/Resources/public/js/jquery-1.10.2.js', 1 => '@FrontendBundle/Resources/public/js/main.js', ), 1 => array ( ), 2 => array ( 'output' => '_controller/js/25d9041.js', 'name' => '25d9041', 'debug' => NULL, 'combine' => NULL, 'vars' => array ( ), ), ), '0d49e82' => array ( 0 => array ( 0 => '@FrontendBundle/Resources/public/css/jquery-ui-1.10.3.custom.min.css', ), 1 => array ( ), 2 => array ( 'output' => '_controller/css/0d49e82.css', 'name' => '0d49e82', 'debug' => NULL, 'combine' => NULL, 'vars' => array ( ), ), ), '3b8dad4' => array ( 0 => array ( 0 => '@FrontendBundle/Resources/public/js/jquery.dataTables-1.9.4.min.js', ), 1 => array ( ), 2 => array ( 'output' => '_controller/js/3b8dad4.js', 'name' => '3b8dad4', 'debug' => NULL, 'combine' => NULL, 'vars' => array ( ), ), ), 5114111 => array ( 0 => array ( 0 => '@FrontendBundle/Resources/public/js/bootstrap-3.0.0.min.js', 1 => '@FrontendBundle/Resources/public/js/jquery.dataTables-1.9.4.min.js', 2 => '@FrontendBundle/Resources/public/js/jquery.mixitup.min.js', 3 => '@FrontendBundle/Resources/public/js/jquery.scrollTo.min.js', 4 => '@FrontendBundle/Resources/public/js/modal.js', 5 => '@FrontendBundle/Resources/public/js/popover.js', 6 => '@FrontendBundle/Resources/public/js/button.js', 7 => '@FrontendBundle/Resources/public/js/jquery-ui-1.10.3.custom.min.js', ), 1 => array ( ), 2 => array ( 'output' => '_controller/js/5114111.js', 'name' => '5114111', 'debug' => NULL, 'combine' => NULL, 'vars' => array ( ), ), ), );
pacordovad/project3
app/cache/dev/assetic/config/5/5ea803aa63bdc4efbcdc7be159654a7b.php
PHP
mit
2,903
asc.component('asc-combobox', function(){ this.afterInit = function (combobox) { var div = eDOM.el('div.dropdown-list'); while (combobox.children.length) { var item = combobox.children[0]; if (item.tagName === "ITEM") { item.innerText += item.getAttribute("text"); div.appendChild(item); } } combobox.appendChild(div); var innerText = eDOM.el('span'); var selectedValue = combobox.getAttribute("data-selected-value"); var previouslySelected; if (selectedValue) { for (var i = 0; i < div.children.length; i++) { var child = div.children[i]; if (child.getAttribute("value") === selectedValue) { child.classList.add('selected'); previouslySelected = child; innerText.innerHTML = child.getAttribute("text"); break; } } } if (innerText.innerHTML.length === 0) { innerText.innerHTML = combobox.getAttribute('data-placeholder'); } combobox.insertBefore(innerText, div); combobox.style.width = combobox.offsetWidth + "px"; div.style.width = (combobox.offsetWidth + 14) + "px"; var closeBackClick = function () { combobox.classList.remove('active'); document.body.removeEventListener('click', closeBackClick); }; combobox.addEventListener('click', function (e) { if (combobox.classList.contains('active')) { if (e.target.tagName === "ITEM") { previouslySelected.classList.remove('selected'); previouslySelected = e.target; e.target.classList.add('selected'); innerText.innerHTML = e.target.getAttribute("text"); combobox.setAttribute("data-selected-value", e.target.getAttribute("value")); } closeBackClick(); } else { combobox.classList.add('active'); setTimeout(function () { document.body.addEventListener('click', closeBackClick); }, 0); } }); } });
vestlirik/apple-style-controls
src/combobox/code.js
JavaScript
mit
2,304
package ic2.api.item; import net.minecraft.item.ItemStack; import java.util.ArrayList; import java.util.List; /** * Allows for charging, discharging and using electric items (IElectricItem). */ public final class ElectricItem { /** * IElectricItemManager to use for interacting with IElectricItem ItemStacks. * * This manager will act as a gateway and delegate the tasks to the final implementation * (rawManager or a custom one) as necessary. */ public static IElectricItemManager manager; /** * Standard IElectricItemManager implementation, only call it directly from another * IElectricItemManager. Use manager instead. */ public static IElectricItemManager rawManager; /** * Register an electric item manager for items not implementing IElectricItem. * * This method is only designed for special purposes, implementing IElectricItem or * ISpecialElectricItem instead of using this is faster. * * Managers used with ISpecialElectricItem shouldn't be registered. * * @param manager Manager to register. */ public static void registerBackupManager(IBackupElectricItemManager manager) { backupManagers.add(manager); } /** * Get the electric item manager suitable for the supplied item stack. * * This method is for internal use only. * * @param stack ItemStack to be handled. * @return First suitable electric item manager. */ public static IBackupElectricItemManager getBackupManager(ItemStack stack) { for (IBackupElectricItemManager manager : backupManagers) { if (manager.handles(stack)) return manager; } return null; } private static final List<IBackupElectricItemManager> backupManagers = new ArrayList<IBackupElectricItemManager>(); }
planetguy32/TurboCraftingTable
src/api/java/ic2/api/item/ElectricItem.java
Java
mit
1,731
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // アセンブリに関する一般情報は以下の属性セットをとおして制御されます。 // アセンブリに関連付けられている情報を変更するには、 // これらの属性値を変更してください。 [assembly: AssemblyTitle("キャプチャされるのは変数という問題")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("キャプチャされるのは変数という問題")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // ComVisible を false に設定すると、このアセンブリ内の型は COM コンポーネントから // 参照できなくなります。COM からこのアセンブリ内の型にアクセスする必要がある場合は、 // その型の ComVisible 属性を true に設定してください。 [assembly: ComVisible(false)] // このプロジェクトが COM に公開される場合、次の GUID が typelib の ID になります [assembly: Guid("258b9e9a-bd47-499e-89e6-9550b66eba58")] // アセンブリのバージョン情報は次の 4 つの値で構成されています: // // メジャー バージョン // マイナー バージョン // ビルド番号 // Revision // // すべての値を指定するか、次を使用してビルド番号とリビジョン番号を既定に設定できます // 既定値にすることができます: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
autumn009/TanoCSharpSamples
Chap2/キャプチャされるのは変数という問題/キャプチャされるのは変数という問題/Properties/AssemblyInfo.cs
C#
mit
1,748
require "spec_helper" describe ChunkyPNG::Datastream do describe ".from_io" do it "should raise an error when loading a file with a bad signature" do filename = resource_file("damaged_signature.png") expect { ChunkyPNG::Datastream.from_file(filename) }.to raise_error(ChunkyPNG::SignatureMismatch) end it "should raise an error if the CRC of a chunk is incorrect" do filename = resource_file("damaged_chunk.png") expect { ChunkyPNG::Datastream.from_file(filename) }.to raise_error(ChunkyPNG::CRCMismatch) end it "should raise an error for a stream that is too short" do stream = StringIO.new expect { ChunkyPNG::Datastream.from_io(stream) }.to raise_error(ChunkyPNG::SignatureMismatch) end it "should read a stream with trailing data without failing" do filename = resource_file("trailing_bytes_after_iend_chunk.png") image = ChunkyPNG::Datastream.from_file(filename) expect(image).to be_instance_of(ChunkyPNG::Datastream) end end describe "#metadata" do it "should load uncompressed tXTt chunks correctly" do filename = resource_file("text_chunk.png") ds = ChunkyPNG::Datastream.from_file(filename) expect(ds.metadata["Title"]).to eql "My amazing icon!" expect(ds.metadata["Author"]).to eql "Willem van Bergen" end it "should load compressed zTXt chunks correctly" do filename = resource_file("ztxt_chunk.png") ds = ChunkyPNG::Datastream.from_file(filename) expect(ds.metadata["Title"]).to eql "PngSuite" expect(ds.metadata["Copyright"]).to eql "Copyright Willem van Schaik, Singapore 1995-96" end it "ignores iTXt chunks" do filename = resource_file("itxt_chunk.png") ds = ChunkyPNG::Datastream.from_file(filename) expect(ds.metadata).to be_empty end end describe "#physical_chunk" do it "should read and write pHYs chunks correctly" do filename = resource_file("clock.png") ds = ChunkyPNG::Datastream.from_file(filename) expect(ds.physical_chunk.unit).to eql :meters expect(ds.physical_chunk.dpix.round).to eql 72 expect(ds.physical_chunk.dpiy.round).to eql 72 ds = ChunkyPNG::Datastream.from_blob(ds.to_blob) expect(ds.physical_chunk).not_to be_nil end it "should raise ChunkyPNG::UnitsUnknown if we request dpi but the units are unknown" do physical_chunk = ChunkyPNG::Chunk::Physical.new(2835, 2835, :unknown) expect { physical_chunk.dpix }.to raise_error(ChunkyPNG::UnitsUnknown) expect { physical_chunk.dpiy }.to raise_error(ChunkyPNG::UnitsUnknown) end end describe "#iTXt_chunk" do it "should read iTXt chunks correctly" do filename = resource_file("itxt_chunk.png") ds = ChunkyPNG::Datastream.from_file(filename) int_text_chunks = ds.chunks.select { |chunk| chunk.is_a?(ChunkyPNG::Chunk::InternationalText) } expect(int_text_chunks.length).to eq(2) coach_uk = int_text_chunks.find { |chunk| chunk.language_tag == "en-gb" } coach_us = int_text_chunks.find { |chunk| chunk.language_tag == "en-us" } expect(coach_uk).to_not be_nil expect(coach_us).to_not be_nil expect(coach_uk.keyword).to eq("coach") expect(coach_uk.text).to eq("bus with of higher standard of comfort, usually chartered or used for longer journeys") expect(coach_uk.translated_keyword).to eq("bus") expect(coach_uk.compressed).to eq(ChunkyPNG::UNCOMPRESSED_CONTENT) expect(coach_uk.compression).to eq(ChunkyPNG::COMPRESSION_DEFAULT) expect(coach_us.keyword).to eq("coach") expect(coach_us.text).to eq("US extracurricular sports teacher at a school (UK: PE teacher) lowest class on a passenger aircraft (UK: economy)") expect(coach_us.translated_keyword).to eq("trainer") expect(coach_us.compressed).to eq(ChunkyPNG::COMPRESSED_CONTENT) expect(coach_us.compression).to eq(ChunkyPNG::COMPRESSION_DEFAULT) end it "should write iTXt chunks correctly" do expected_hex = %w[0000 001d 6954 5874 436f 6d6d 656e 7400 0000 0000 4372 6561 7465 6420 7769 7468 2047 494d 5064 2e65 07].join("") stream = StringIO.new itext = ChunkyPNG::Chunk::InternationalText.new("Comment", "Created with GIMP") itext.write(stream) generated_hex = stream.string.unpack("H*").join("") expect(generated_hex).to eq(expected_hex) end it "should handle incorrect UTF-8 encoding in iTXt chunks" do incorrect_text_encoding = [0, 0, 0, 14, 105, 84, 88, 116, 67, 111, 109, 109, 101, 110, 116, 0, 0, 0, 0, 0, 195, 40, 17, 87, 97, 213].pack("C*") incorrect_translated_keyword_encoding = [0, 0, 0, 19, 105, 84, 88, 116, 67, 111, 109, 109, 101, 110, 116, 0, 0, 0, 0, 226, 130, 40, 0, 116, 101, 115, 116, 228, 53, 113, 182].pack("C*") expect { ChunkyPNG::Chunk.read(StringIO.new(incorrect_text_encoding)) }.to raise_error(ChunkyPNG::InvalidUTF8) expect { ChunkyPNG::Chunk.read(StringIO.new(incorrect_translated_keyword_encoding)) }.to raise_error(ChunkyPNG::InvalidUTF8) end it "should handle UTF-8 in iTXt compressed chunks correctly" do parsed = serialized_chunk(ChunkyPNG::Chunk::InternationalText.new("Comment", "✨", "", "💩", ChunkyPNG::COMPRESSED_CONTENT)) expect(parsed.text).to eq("✨") expect(parsed.text.encoding).to eq(Encoding::UTF_8) expect(parsed.translated_keyword).to eq("💩") expect(parsed.translated_keyword.encoding).to eq(Encoding::UTF_8) end it "should handle UTF-8 in iTXt chunks correctly" do parsed = serialized_chunk(ChunkyPNG::Chunk::InternationalText.new("Comment", "✨", "", "💩")) expect(parsed.text).to eq("✨") expect(parsed.text.encoding).to eq(Encoding::UTF_8) expect(parsed.translated_keyword).to eq("💩") expect(parsed.translated_keyword.encoding).to eq(Encoding::UTF_8) end it "should transform non UTF-8 iTXt fields to UTF-8 on write" do parsed = serialized_chunk(ChunkyPNG::Chunk::InternationalText.new("Comment", "®".encode("Windows-1252"), "", "ƒ".encode("Windows-1252"))) expect(parsed.text).to eq("®") expect(parsed.text.encoding).to eq(Encoding::UTF_8) expect(parsed.translated_keyword).to eq("ƒ") expect(parsed.translated_keyword.encoding).to eq(Encoding::UTF_8) end end end
wvanbergen/chunky_png
spec/chunky_png/datastream_spec.rb
Ruby
mit
6,371
using AutoMapper; using Volo.SqliteDemo.Authorization.Users; namespace Volo.SqliteDemo.Users.Dto { public class UserMapProfile : Profile { public UserMapProfile() { CreateMap<UserDto, User>(); CreateMap<UserDto, User>().ForMember(x => x.Roles, opt => opt.Ignore()); CreateMap<CreateUserDto, User>(); CreateMap<CreateUserDto, User>().ForMember(x => x.Roles, opt => opt.Ignore()); } } }
aspnetboilerplate/aspnetboilerplate-samples
SqliteDemo/aspnet-core/src/Volo.SqliteDemo.Application/Users/Dto/UserMapProfile.cs
C#
mit
474
from __future__ import division def run () : import libtbx.load_env # import dependency for module in libtbx.env.module_list : print module.name if (__name__ == "__main__") : run()
hickerson/bbn
fable/fable_sources/libtbx/command_line/list_modules.py
Python
mit
194
var context; var plainCanvas; var log; var pointerDown = {}; var lastPositions = {}; var colors = ["rgb(100, 255, 100)", "rgb(255, 0, 0)", "rgb(0, 255, 0)", "rgb(255, 0, 0)", "rgb(0, 255, 100)", "rgb(10, 255, 255)", "rgb(255, 0, 100)"]; var onPointerMove = function(evt) { if (pointerDown[evt.pointerId]) { var color = colors[evt.pointerId % colors.length]; context.strokeStyle = color; context.beginPath(); context.lineWidth = 2; context.moveTo(lastPositions[evt.pointerId].x, lastPositions[evt.pointerId].y); context.lineTo(evt.clientX, evt.clientY); context.closePath(); context.stroke(); lastPositions[evt.pointerId] = { x: evt.clientX, y: evt.clientY }; } }; var pointerLog = function (evt) { var pre = document.querySelector("pre"); pre.innerHTML = evt.type + "\t\t(" + evt.clientX + ", " + evt.clientY + ")\n" + pre.innerHTML; }; var onPointerUp = function (evt) { pointerDown[evt.pointerId] = false; pointerLog(evt); }; var onPointerDown = function (evt) { pointerDown[evt.pointerId] = true; lastPositions[evt.pointerId] = { x: evt.clientX, y: evt.clientY }; pointerLog(evt); }; var onPointerEnter = function (evt) { pointerLog(evt); }; var onPointerLeave = function (evt) { pointerLog(evt); }; var onPointerOver = function (evt) { pointerLog(evt); }; var onload = function() { plainCanvas = document.getElementById("plainCanvas"); log = document.getElementById("log"); plainCanvas.width = plainCanvas.clientWidth; plainCanvas.height = plainCanvas.clientHeight; context = plainCanvas.getContext("2d"); context.fillStyle = "rgba(50, 50, 50, 1)"; context.fillRect(0, 0, plainCanvas.width, plainCanvas.height); plainCanvas.addEventListener("pointerdown", onPointerDown, false); plainCanvas.addEventListener("pointermove", onPointerMove, false); plainCanvas.addEventListener("pointerup", onPointerUp, false); plainCanvas.addEventListener("pointerout", onPointerUp, false); plainCanvas.addEventListener("pointerenter", onPointerEnter, false); plainCanvas.addEventListener("pointerleave", onPointerLeave, false); plainCanvas.addEventListener("pointerover", onPointerOver, false); }; if (document.addEventListener !== undefined) { document.addEventListener("DOMContentLoaded", onload, false); } ;
rtillery/html5demos
draw/index.js
JavaScript
mit
2,482
namespace Bolt { internal static class StringExensions { public static bool EqualsNoCase(this string first, string second) { if (Equals(first, second)) { return true; } return string.CompareOrdinal(first?.ToLowerInvariant() ?? first, second?.ToLowerInvariant() ?? second) == 0; } } }
yonglehou/Bolt
src/Bolt.Sources/StringExensions.cs
C#
mit
387
/** * @fileOverview Cross */ import React, { PureComponent, SVGProps } from 'react'; import classNames from 'classnames'; import { isNumber } from '../util/DataUtils'; import { filterProps } from '../util/types'; interface CrossProps { x?: number; y?: number; width?: number; height?: number; top?: number; left?: number; className?: number; } export type Props = SVGProps<SVGPathElement> & CrossProps; export class Cross extends PureComponent<Props> { static defaultProps = { x: 0, y: 0, top: 0, left: 0, width: 0, height: 0, }; static getPath(x: number, y: number, width: number, height: number, top: number, left: number) { return `M${x},${top}v${height}M${left},${y}h${width}`; } render() { const { x, y, width, height, top, left, className } = this.props; if (!isNumber(x) || !isNumber(y) || !isNumber(width) || !isNumber(height) || !isNumber(top) || !isNumber(left)) { return null; } return ( <path {...filterProps(this.props, true)} className={classNames('recharts-cross', className)} d={Cross.getPath(x, y, width, height, top, left)} /> ); } }
recharts/recharts
src/shape/Cross.tsx
TypeScript
mit
1,177
import http from 'http'; function upsertState(state) { var postData = JSON.stringify(state); var options = { hostname: 'localhost', port: 3000, path: '/application', method: 'POST', headers: { 'Content-Type': 'application/json', 'Content-Length': postData.length } }; var req = http.request(options, (res) => { res.setEncoding('utf8'); }); req.write(postData); req.end(); } let defaultState = { excitement: 0, poc: { name: '', email: '' }, contributors: [], popover: false }; let savedState = JSON.parse(localStorage.getItem('appState')); export default function application(state = savedState || defaultState, action) { let newState switch (action.type) { case 'GET_EXCITED': { newState = Object.assign({}, state, { excitement: state.excitement += 1 }); break; } case 'UPDATE_POC': { newState = Object.assign({}, state, { poc: { name: action.name, email: action.email } }); break; } case 'PERSIST_STATE': { upsertState(state); newState = state; break; } case 'SHOW_POPOVER': { newState = Object.assign({}, state, { popover: true }); break; } case 'UPDATE_ESSAY': { newState = Object.assign({}, state, { [action.prompt]: action.response }); break; } case 'UPDATE_COMPANY_NAME': { newState = Object.assign({}, state, { companyName: action.name }); break; } case 'UPDATE_COMPANY_TYPE': { newState = Object.assign({}, state, { companyType: action.companyType }); break; } case 'REMOVE_CONTRIBUTOR': { const contributors = state.contributors.slice(0, state.contributors.length - 1) newState = Object.assign({}, state, { contributors: contributors }); break; } case 'UPDATE_CONTRIBUTOR': { let updated = false; const contributors = state.contributors.map((contributor) => { if (contributor.id === action.id) { updated = true; return { id: contributor.id, name: action.name, email: action.email } } else { return contributor; } }); if (!updated) { contributors.push({ id: action.id, name: action.name, email: action.email }); } newState = Object.assign({}, state, { contributors: contributors }); break; } default: { newState = state; } } localStorage.setItem('appState', JSON.stringify(newState)) return newState; }
doug-wade/incubator-application
browser/reducers/index.js
JavaScript
mit
2,674
version https://git-lfs.github.com/spec/v1 oid sha256:00be998e9791a319bc3751b20c19ce0fa3cb25a87c8dbf9030a728c92af8d95c size 100787
yogeshsaroya/new-cdnjs
ajax/libs/rxjs/2.3.24/rx.all.compat.min.js
JavaScript
mit
131
require_relative 'game_element' class GamePackage include GameElement attr_reader :items attr_reader :capacity def initialize(capacity) @capacity = capacity @items = [] end def add(item) @items << item end def discard() @item end def [](i) @items[i] end def []=(i, item) @items[i] = item end def << item add(item) end end
HungryAnt/ruby-demo
src/game_package.rb
Ruby
mit
419
import PropTypes from 'prop-types' import React from 'react' const Card = ({title}) => <h3>{title}</h3> Card.propTypes = { title: PropTypes.string.isRequired } export default Card
dustinspecker/the-x-effect
app/components/card/index.js
JavaScript
mit
187
namespace FoldAndSum { using System; using System.Collections.Generic; using System.Linq; class FoldAndSum { static void Main(string[] args) { var input = Console.ReadLine().Split(' ').Select(int.Parse).ToArray(); int k = input.Length / 2 / 2; var secondFirst = input.Reverse().Take(k).ToArray(); var firstFirst = input.Take(k).Reverse().ToArray(); var first = firstFirst.Concat(secondFirst); var second = input.Skip(k).Take(2 * k).ToArray(); var result = first.Select((x, index) => x + second[index]); Console.WriteLine(string.Join(" ", result)); } } }
davidvaleff/ProgrammingFundamentals-Sept2017
07.DictionariesLambda&LINQ/Lab/FoldAndSum/FoldAndSum.cs
C#
mit
705
package com.bijoykochar.launcher.view; import android.content.ContentUris; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.provider.CalendarContract; import android.util.AttributeSet; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; import com.bijoykochar.launcher.R; import com.bijoykochar.launcher.items.SerialEvent; import com.bijoykochar.launcher.util.TimeUtilities; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; import me.everything.providers.android.calendar.Calendar; import me.everything.providers.android.calendar.CalendarProvider; import me.everything.providers.android.calendar.Event; /** * The view for the home recent apps * Created by bijoy on 10/17/15. */ public class CalendarView extends LinearLayout { View rootView; TextView title, description, dateTime; SerialEvent event; public CalendarView(Context context) { super(context); } public CalendarView(Context context, AttributeSet attrs) { super(context, attrs); } public CalendarView(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); } public List<SerialEvent> getSerialEvents(Context context) { CalendarProvider provider = new CalendarProvider(context); List<Calendar> calendars = provider.getCalendars().getList(); List<Event> events = new ArrayList<>(); for (Calendar calendar : calendars) { events.addAll(provider.getEvents(calendar.id).getList()); } List<SerialEvent> sEvents = new ArrayList<>(); for (Event event : events) { sEvents.add(new SerialEvent(event)); } return sEvents; } public SerialEvent getNextEvent(Context context) { List<SerialEvent> events = getSerialEvents(context); if (!events.isEmpty()) { long timeInMillis = java.util.Calendar.getInstance().getTimeInMillis(); long minTimeInMillis = timeInMillis + 1000 * 60 * 60 * 24 * 7 * 52; SerialEvent nextEvent = null; for (SerialEvent event : events) { if (event.dTStart > timeInMillis && event.dTStart < minTimeInMillis) { nextEvent = event; minTimeInMillis = event.dTStart; } } return nextEvent; } return null; } public void init(final Context context) { LayoutInflater mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); rootView = mInflater.inflate(R.layout.calendar_view, this, true); title = (TextView) rootView.findViewById(R.id.title); description = (TextView) rootView.findViewById(R.id.description); dateTime = (TextView) rootView.findViewById(R.id.date_time); } public void getData(Context context) { event = getNextEvent(context); } public void displayEvents(final Context context) { try { title.setText(event.title); description.setText(event.description); java.util.Calendar calendar = java.util.Calendar.getInstance(); calendar.setTimeInMillis(event.dTStart); SimpleDateFormat dateFormat = TimeUtilities.getFullTimeFormat(context); String dateAndTime = dateFormat.format(calendar.getTime()); dateTime.setText(dateAndTime); rootView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Uri uri = ContentUris.withAppendedId(CalendarContract.Events.CONTENT_URI, event.id); Intent intent = new Intent(Intent.ACTION_VIEW) .setData(uri); context.startActivity(intent); } }); } catch (Exception e) { Log.e("CalendarView", e.getMessage(), e); setVisibility(View.GONE); } } }
BijoySingh/One-Launcher
app/src/main/java/com/bijoykochar/launcher/view/CalendarView.java
Java
mit
4,170
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2015 The VCoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "amount.h" #include "tinyformat.h" const std::string CURRENCY_UNIT = "BTC"; CFeeRate::CFeeRate(const CAmount& nFeePaid, size_t nSize) { if (nSize > 0) nSatoshisPerK = nFeePaid*1000/nSize; else nSatoshisPerK = 0; } CAmount CFeeRate::GetFee(size_t nSize) const { CAmount nFee = nSatoshisPerK*nSize / 1000; if (nFee == 0 && nSatoshisPerK > 0) nFee = nSatoshisPerK; return nFee; } std::string CFeeRate::ToString() const { return strprintf("%d.%08d %s/kB", nSatoshisPerK / COIN, nSatoshisPerK % COIN, CURRENCY_UNIT); }
vcoin-project/v
src/amount.cpp
C++
mit
815
using System; using System.Globalization; namespace SharpRemote.WebApi.Routes.Parsers { internal sealed class Int64Parser : IntegerParser { public override Type Type => typeof(long); public override bool TryExtract(string str, int startIndex, out object value, out int consumed) { string digits; if (TryGetDigits(str, startIndex, out digits)) { long number; if (long.TryParse(digits, NumberStyles.Integer, CultureInfo.InvariantCulture, out number)) { value = number; consumed = digits.Length; return true; } } consumed = 0; value = null; return false; } } }
Kittyfisto/SharpRemote
SharpRemote.WebApi/Routes/Parsers/Int64Parser.cs
C#
mit
634
<?php namespace App\Core\Contracts; interface CartInterface { }
storecamp/storecamp
app/Core/Contracts/CartInterface.php
PHP
mit
66
require "json" require "sinatra/base" require "github-trello/version" require "github-trello/http" module GithubTrello class Server < Sinatra::Base #Recieves payload post "/posthook-github" do #Get environment variables for configuration oauth_token = ENV["oauth_token"] api_key = ENV["api_key"] board_id = ENV["board_id"] inprogress_list_target_id = ENV["inprogress_list_target_id"] merged_list_target_id = ENV["merged_list_target_id"] staging_list_target_id = ENV["staging_list_target_id"] deployed_list_target_id = ENV["deployed_list_target_id"] #Set up HTTP Wrapper http = GithubTrello::HTTP.new(oauth_token, api_key) #Get payload payload = JSON.parse(params[:payload]) #Get branch branch = payload["ref"].gsub("refs/heads/", "") payload["commits"].each do |commit| # Figure out the card short id match = commit["message"].match(/((start|card|close|fix)e?s? \D?([0-9]+))/i) next unless match and match[3].to_i > 0 results = http.get_card(board_id, match[3].to_i) unless results puts "[ERROR] Cannot find card matching ID #{match[3]}" next end results = JSON.parse(results) # Add the commit comment message = "#{commit["author"]["name"]}: #{commit["message"]}\n\n[#{branch}] #{commit["url"]}" message.gsub!(match[1], "") message.gsub!(/\(\)$/, "") http.add_comment(results["id"], message) #Determine the action to take if branch.include? "master" then new_list_id = merged_list_target_id elsif branch.include? "staging" then new_list_id = staging_list_target_id elsif branch.include? "production" then new_list_id = deployed_list_target_id else new_list_id = inprogress_list_target_id end next unless !new_list_id.nil? #Modify it if needed to_update = {} unless results["idList"] == new_list_id to_update[:idList] = new_list_id end unless to_update.empty? http.update_card(results["id"], to_update) end end "" end get "/" do "" end def self.http; @http end end end
makoetting/github-trello
lib/github-trello/server.rb
Ruby
mit
2,318
#include <node.h> #include <node_buffer.h> #include <iostream> #include <cstdlib> using namespace v8; using namespace std; using namespace node; /* Random number generators */ static Handle<Value> UniformRandom(const Arguments& args) { HandleScope scope; double d_min = 0, d_max = 1.0; Local<Object> that = args.This()->ToObject(); Local<Value> min = that->Get(String::New("min")); Local<Value> max = that->Get(String::New("max")); Local<Object> seed = that->Get(String::New("seed"))->ToObject(); if (Buffer::Length(seed) < 6) { return ThrowException(Exception::Error( String::New("Length is extends beyond buffer"))); } union { char *seed_data_c; uint16_t *seed_data_us; } seed_data; seed_data.seed_data_c = Buffer::Data(seed); if (min->IsNumber()) { d_min = min->NumberValue(); } else { d_min = 0.0; } if (max->IsNumber()) { d_max = max->NumberValue(); } else { d_max = 1.0; } /* Magic happens here */ /* TODO: Port this to windows, since erand48 and friends * are not in windows */ double result = (erand48(seed_data.seed_data_us) * (d_max - d_min)) + d_min; return scope.Close(Number::New(result)); } extern "C" void init (Handle<Object> target) { HandleScope scope; NODE_SET_METHOD(target, "UniformNext", UniformRandom); }
ashgti/node-math-utils
math_utils.cc
C++
mit
1,424
module Admin class FeedbackReportCSVWriter < CSVWriter columns :id, :service, :feedbackable_type, :rating, :created_at, :review, :acknowledged, :email, :phone, :traveler associations :user def traveler @record.user && @record.user.email end def service return nil if @record.feedbackable_id.nil? if @record.feedbackable_type == 'Service' my_service = Service.find_by(id: @record.feedbackable_id) if my_service return my_service.name else return nil end elsif @record.feedbackable_type == 'OneclickRefernet::Service' my_service = OneclickRefernet::Service.find_by(id: @record.feedbackable_id) if my_service return my_service.agency_name else return nil end end end end end
camsys/oneclick-core
app/serializers/admin/feedback_report_csv_writer.rb
Ruby
mit
845
require 'spec_helper' require 'guard/plugin' describe Guard::Commander do describe '.start' do before do ::Guard.stub(:setup) ::Guard.instance_variable_set('@watchdirs', []) ::Guard.stub(listener: double('listener', start: true)) ::Guard.stub(runner: double('runner', run: true)) ::Guard.stub(:within_preserved_state).and_yield end context 'Guard has not been setuped' do before { ::Guard.stub(:running) { false } } it "setup Guard" do expect(::Guard).to receive(:setup).with(foo: 'bar') ::Guard.start(foo: 'bar') end end it "displays an info message" do ::Guard.instance_variable_set('@watchdirs', ['/foo/bar']) expect(::Guard::UI).to receive(:info).with("Guard is now watching at '/foo/bar'") ::Guard.start end it "tell the runner to run the :start task" do expect(::Guard.runner).to receive(:run).with(:start) ::Guard.start end it "start the listener" do expect(::Guard.listener).to receive(:start) ::Guard.start end end describe '.stop' do before do ::Guard.stub(:setup) ::Guard.stub(listener: double('listener', stop: true)) ::Guard.stub(runner: double('runner', run: true)) ::Guard.stub(:within_preserved_state).and_yield end context 'Guard has not been setuped' do before { ::Guard.stub(:running) { false } } it "setup Guard" do expect(::Guard).to receive(:setup) ::Guard.stop end end it "turns the notifier off" do expect(::Guard::Notifier).to receive(:turn_off) ::Guard.stop end it "tell the runner to run the :stop task" do expect(::Guard.runner).to receive(:run).with(:stop) ::Guard.stop end it "stops the listener" do expect(::Guard.listener).to receive(:stop) ::Guard.stop end it "sets the running state to false" do ::Guard.running = true ::Guard.stop expect(::Guard.running).to be_false end end describe '.reload' do let(:runner) { double(run: true) } let(:group) { ::Guard::Group.new('frontend') } subject { ::Guard.setup } before do ::Guard.stub(:runner) { runner } ::Guard.stub(:within_preserved_state).and_yield ::Guard::UI.stub(:info) ::Guard::UI.stub(:clear) end context 'Guard has not been setuped' do before { ::Guard.stub(:running) { false } } it "setup Guard" do expect(::Guard).to receive(:setup) ::Guard.reload end end it 'clears the screen' do expect(::Guard::UI).to receive(:clear) subject.reload end context 'with a given scope' do it 'does not re-evaluate the Guardfile' do ::Guard::Guardfile::Evaluator.any_instance.should_not_receive(:reevaluate_guardfile) subject.reload({ groups: [group] }) end it 'reloads Guard' do expect(runner).to receive(:run).with(:reload, { groups: [group] }) subject.reload({ groups: [group] }) end end context 'with an empty scope' do it 'does re-evaluate the Guardfile' do ::Guard::Guardfile::Evaluator.any_instance.should_receive(:reevaluate_guardfile) subject.reload end it 'does not reload Guard' do expect(runner).to_not receive(:run).with(:reload, {}) subject.reload end end end describe '.run_all' do let(:runner) { double(run: true) } let(:group) { ::Guard::Group.new('frontend') } subject { ::Guard.setup } before do ::Guard.stub(runner: runner) ::Guard.stub(:within_preserved_state).and_yield ::Guard::UI.stub(:action_with_scopes) ::Guard::UI.stub(:clear) end context 'Guard has not been setuped' do before { ::Guard.stub(:running) { false } } it "setup Guard" do expect(::Guard).to receive(:setup) ::Guard.run_all end end context 'with a given scope' do it 'runs all with the scope' do expect(runner).to receive(:run).with(:run_all, { groups: [group] }) subject.run_all({ groups: [group] }) end end context 'with an empty scope' do it 'runs all' do expect(runner).to receive(:run).with(:run_all, {}) subject.run_all end end end describe '.within_preserved_state' do subject { ::Guard.setup } before { subject.interactor = double('interactor').as_null_object } it 'disallows running the block concurrently to avoid inconsistent states' do expect(subject.lock).to receive(:synchronize) subject.within_preserved_state &Proc.new {} end it 'runs the passed block' do @called = false subject.within_preserved_state { @called = true } expect(@called).to be_true end context '@running is true' do it 'stops the interactor before running the block and starts it again when done' do expect(subject.interactor).to receive(:stop) expect(subject.interactor).to receive(:start) subject.within_preserved_state &Proc.new {} end end context '@running is false' do before { ::Guard.stub(:running) { false } } it 'stops the interactor before running the block and do not starts it again when done' do expect(subject.interactor).to receive(:stop) expect(subject.interactor).to_not receive(:start) subject.within_preserved_state &Proc.new {} end end end end
yujinakayama/guard
spec/guard/commander_spec.rb
Ruby
mit
5,527
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.storage.v2019_04_01.implementation; import com.microsoft.azure.AzureClient; import com.microsoft.azure.AzureServiceClient; import com.microsoft.rest.credentials.ServiceClientCredentials; import com.microsoft.rest.RestClient; /** * Initializes a new instance of the StorageManagementClientImpl class. */ public class StorageManagementClientImpl extends AzureServiceClient { /** the {@link AzureClient} used for long running operations. */ private AzureClient azureClient; /** * Gets the {@link AzureClient} used for long running operations. * @return the azure client; */ public AzureClient getAzureClient() { return this.azureClient; } /** The ID of the target subscription. */ private String subscriptionId; /** * Gets The ID of the target subscription. * * @return the subscriptionId value. */ public String subscriptionId() { return this.subscriptionId; } /** * Sets The ID of the target subscription. * * @param subscriptionId the subscriptionId value. * @return the service client itself */ public StorageManagementClientImpl withSubscriptionId(String subscriptionId) { this.subscriptionId = subscriptionId; return this; } /** The API version to use for this operation. */ private String apiVersion; /** * Gets The API version to use for this operation. * * @return the apiVersion value. */ public String apiVersion() { return this.apiVersion; } /** The preferred language for the response. */ private String acceptLanguage; /** * Gets The preferred language for the response. * * @return the acceptLanguage value. */ public String acceptLanguage() { return this.acceptLanguage; } /** * Sets The preferred language for the response. * * @param acceptLanguage the acceptLanguage value. * @return the service client itself */ public StorageManagementClientImpl withAcceptLanguage(String acceptLanguage) { this.acceptLanguage = acceptLanguage; return this; } /** The retry timeout in seconds for Long Running Operations. Default value is 30. */ private int longRunningOperationRetryTimeout; /** * Gets The retry timeout in seconds for Long Running Operations. Default value is 30. * * @return the longRunningOperationRetryTimeout value. */ public int longRunningOperationRetryTimeout() { return this.longRunningOperationRetryTimeout; } /** * Sets The retry timeout in seconds for Long Running Operations. Default value is 30. * * @param longRunningOperationRetryTimeout the longRunningOperationRetryTimeout value. * @return the service client itself */ public StorageManagementClientImpl withLongRunningOperationRetryTimeout(int longRunningOperationRetryTimeout) { this.longRunningOperationRetryTimeout = longRunningOperationRetryTimeout; return this; } /** Whether a unique x-ms-client-request-id should be generated. When set to true a unique x-ms-client-request-id value is generated and included in each request. Default is true. */ private boolean generateClientRequestId; /** * Gets Whether a unique x-ms-client-request-id should be generated. When set to true a unique x-ms-client-request-id value is generated and included in each request. Default is true. * * @return the generateClientRequestId value. */ public boolean generateClientRequestId() { return this.generateClientRequestId; } /** * Sets Whether a unique x-ms-client-request-id should be generated. When set to true a unique x-ms-client-request-id value is generated and included in each request. Default is true. * * @param generateClientRequestId the generateClientRequestId value. * @return the service client itself */ public StorageManagementClientImpl withGenerateClientRequestId(boolean generateClientRequestId) { this.generateClientRequestId = generateClientRequestId; return this; } /** * The OperationsInner object to access its operations. */ private OperationsInner operations; /** * Gets the OperationsInner object to access its operations. * @return the OperationsInner object. */ public OperationsInner operations() { return this.operations; } /** * The SkusInner object to access its operations. */ private SkusInner skus; /** * Gets the SkusInner object to access its operations. * @return the SkusInner object. */ public SkusInner skus() { return this.skus; } /** * The StorageAccountsInner object to access its operations. */ private StorageAccountsInner storageAccounts; /** * Gets the StorageAccountsInner object to access its operations. * @return the StorageAccountsInner object. */ public StorageAccountsInner storageAccounts() { return this.storageAccounts; } /** * The UsagesInner object to access its operations. */ private UsagesInner usages; /** * Gets the UsagesInner object to access its operations. * @return the UsagesInner object. */ public UsagesInner usages() { return this.usages; } /** * The ManagementPoliciesInner object to access its operations. */ private ManagementPoliciesInner managementPolicies; /** * Gets the ManagementPoliciesInner object to access its operations. * @return the ManagementPoliciesInner object. */ public ManagementPoliciesInner managementPolicies() { return this.managementPolicies; } /** * The BlobServicesInner object to access its operations. */ private BlobServicesInner blobServices; /** * Gets the BlobServicesInner object to access its operations. * @return the BlobServicesInner object. */ public BlobServicesInner blobServices() { return this.blobServices; } /** * The BlobContainersInner object to access its operations. */ private BlobContainersInner blobContainers; /** * Gets the BlobContainersInner object to access its operations. * @return the BlobContainersInner object. */ public BlobContainersInner blobContainers() { return this.blobContainers; } /** * The FileServicesInner object to access its operations. */ private FileServicesInner fileServices; /** * Gets the FileServicesInner object to access its operations. * @return the FileServicesInner object. */ public FileServicesInner fileServices() { return this.fileServices; } /** * The FileSharesInner object to access its operations. */ private FileSharesInner fileShares; /** * Gets the FileSharesInner object to access its operations. * @return the FileSharesInner object. */ public FileSharesInner fileShares() { return this.fileShares; } /** * Initializes an instance of StorageManagementClient client. * * @param credentials the management credentials for Azure */ public StorageManagementClientImpl(ServiceClientCredentials credentials) { this("https://management.azure.com", credentials); } /** * Initializes an instance of StorageManagementClient client. * * @param baseUrl the base URL of the host * @param credentials the management credentials for Azure */ public StorageManagementClientImpl(String baseUrl, ServiceClientCredentials credentials) { super(baseUrl, credentials); initialize(); } /** * Initializes an instance of StorageManagementClient client. * * @param restClient the REST client to connect to Azure. */ public StorageManagementClientImpl(RestClient restClient) { super(restClient); initialize(); } protected void initialize() { this.apiVersion = "2019-04-01"; this.acceptLanguage = "en-US"; this.longRunningOperationRetryTimeout = 30; this.generateClientRequestId = true; this.operations = new OperationsInner(restClient().retrofit(), this); this.skus = new SkusInner(restClient().retrofit(), this); this.storageAccounts = new StorageAccountsInner(restClient().retrofit(), this); this.usages = new UsagesInner(restClient().retrofit(), this); this.managementPolicies = new ManagementPoliciesInner(restClient().retrofit(), this); this.blobServices = new BlobServicesInner(restClient().retrofit(), this); this.blobContainers = new BlobContainersInner(restClient().retrofit(), this); this.fileServices = new FileServicesInner(restClient().retrofit(), this); this.fileShares = new FileSharesInner(restClient().retrofit(), this); this.azureClient = new AzureClient(this); } /** * Gets the User-Agent header for the client. * * @return the user agent string. */ @Override public String userAgent() { return String.format("%s (%s, %s, auto-generated)", super.userAgent(), "StorageManagementClient", "2019-04-01"); } }
navalev/azure-sdk-for-java
sdk/storage/mgmt-v2019_04_01/src/main/java/com/microsoft/azure/management/storage/v2019_04_01/implementation/StorageManagementClientImpl.java
Java
mit
9,641
package by.trapecia.dao; import by.trapecia.Main; import by.trapecia.model.Client; import by.trapecia.model.Rent; import java.sql.*; import java.util.ArrayList; import java.util.logging.Level; import java.util.logging.Logger; /** * Created by Denis on 15.12.2015. */ public class RentDaoImpl implements RentDao { private static Logger log = Logger.getLogger(Main.class.getName()); private ConnectionPool cp; public RentDaoImpl() throws Exception { cp = ConnectionPool.getInstance(); } @Override public Integer saveRent(Rent rent, Integer clientId) throws Exception { Connection connection = null; PreparedStatement ps = null; ResultSet result = null; try { connection = cp.getConnection(); ps = connection.prepareStatement( "INSERT INTO rent VALUES (DEFAULT, ?, ?, ?, ?, ?, ?)", Statement.RETURN_GENERATED_KEYS); ps.setInt(1, clientId); ps.setInt(2, rent.climbingShoes); ps.setInt(3, rent.harness); ps.setInt(4, rent.magnesia); ps.setInt(5, rent.carabine); ps.setInt(6, rent.griGri); ps.executeUpdate(); result = ps.getGeneratedKeys(); result.next(); rent.rentId = result.getInt(1); return rent.rentId; } catch (SQLException e) { log.log(Level.SEVERE, "Exception: ", e); throw new Exception("Can't execute sql", e); } finally { if(result != null)result.close(); if(ps != null)ps.close(); cp.returnConnection(connection); } } @Override public Rent loadRent(Integer clientId) throws Exception { Connection connection = null; Statement st = null; ResultSet result = null; Rent rent = new Rent(); PreparedStatement ps = null; try { connection = cp.getConnection(); String selectStatement = "SELECT * FROM rent" + " WHERE rent_id IN (SELECT rent_id FROM service" + " WHERE check_out = '0000-00-00 00:00:00'" + "AND client_id = ?)"; ps = connection.prepareStatement(selectStatement); ps.setInt(1, clientId); result = ps.executeQuery(); while (result.next()) { rent.clientId = result.getInt("client_id"); rent.rentId = result.getInt("rent_id"); rent.climbingShoes = result.getInt("climbing_shoes"); rent.magnesia = result.getInt("magnesia"); rent.carabine = result.getInt("carabine"); rent.griGri = result.getInt("gri_gri"); rent.harness = result.getInt("harness"); } result.close(); } catch (SQLException se) { log.log(Level.SEVERE, "Exception: ", se); } catch (Exception e) { log.log(Level.SEVERE, "Exception: ", e); } finally { if(result != null)result.close(); if(ps != null)ps.close(); cp.returnConnection(connection); } return rent; } }
Maximenya/Trapezia-1.01
src/main/java/by/trapecia/dao/RentDaoImpl.java
Java
mit
3,231
import { IAppToken, createToken } from '../lib/authorization' import * as KoaRouter from 'koa-router' import { User } from '../models' import { IsomorphicRenderController } from '../controllers/IsomorphicRender' import { clearCookieToken, restrictIdentifiedAccess, restrictUnidentifiedAccess } from '../lib/authorization' const convert = require('koa-convert') const body = require('koa-body') export class UserController { private router = new KoaRouter() private errorMessages = { authFailed: 'Authorization failed.', incompleteAttributes: 'Incomplete attributes.', emailTaken: 'Email already taken.' } constructor(app) { const parseBody = convert(body({ multipart: true })) this.router.get('/login', restrictIdentifiedAccess, IsomorphicRenderController.renderRoute) this.router.post('/login', restrictIdentifiedAccess, parseBody, async (ctx) => { const fields = ctx.request.body.fields if (!fields || !fields.email || !fields.password) { return ctx.throw(401, this.errorMessages.authFailed) } const user = await User.getByEmailAndPass(fields.email, fields.password) if (!user) { return ctx.throw(401, this.errorMessages.authFailed) } this.authenticateUser(ctx, user, fields.rememberMe) ctx.body = 'OK' }) this.router.get('/sign_up', restrictIdentifiedAccess, IsomorphicRenderController.renderRoute) this.router.post('/sign_up', restrictIdentifiedAccess, parseBody, async (ctx) => { const fields = ctx.request.body.fields if (!fields || !fields.name || !fields.password || !fields.email || !fields.password) { return ctx.throw(403, this.errorMessages.incompleteAttributes) } if (await User.getByEmail(fields.email)) { return ctx.throw(403, this.errorMessages.emailTaken) } try { let user = await new User({ name: fields.name, email: fields.email, password: fields.password }).save() this.authenticateUser(ctx, user) ctx.body = 'OK' } catch (e) { ctx.throw(403, e.message) } }) this.router.get('/logout', (ctx) => { clearCookieToken(ctx) ctx.accepts('html', 'json', 'text') === 'json' ? ctx.status = 200 : ctx.redirect('/login') }) // this route is used by native apps this.router.get('/ping', restrictUnidentifiedAccess, (ctx, next) => { ctx.type = 'application/json' ctx.body = JSON.stringify({status: 'OK'}) }) } private authenticateUser(ctx, user, rememberMe?): void { // NOTE, we store the entire User object on the JWT payload without the crypted pass let payload = JSON.parse(JSON.stringify(user)) delete payload.cryptedPassword const appToken: IAppToken = createToken(payload) const cookieData: any = { signed: false, httpOnly: true, overwrite: true, } if (rememberMe === 'true') { cookieData.expires = appToken.expires } ctx.cookies.set('token', appToken.token, cookieData) } }
rodrigopivi/PlayApp
src/server/controllers/User.ts
TypeScript
mit
3,330
var arr = 'ciao come va'.split(' '); var filtered = arr.filter(function(item) { return item != 'va'; }); Array.prototype.filtroMio = function() { if (arr.length == 2) { return this } return []; }; var ar2 = arr.filtroMio(); console.log(ar2); console.log(filtered);
brugnara/node-lessons
lessons/05-filtered.js
JavaScript
mit
280
#ifndef SERVER_BASE_HPP #define SERVER_BASE_HPP #include <boost/asio.hpp> #include <regex> #include <unordered_map> #include <thread> #include <iostream> #include <ctime> #include "Request.h" #include "Response.h" namespace MyWeb { typedef std::map<std::string, std::unordered_map<std::string, std::function<void(Response&, Request&)>>> resource_type; template <typename socket_type> class ServerBase{ public: resource_type resource; resource_type default_resource; ServerBase(unsigned short port,size_t num_threads=1): endpoint(boost::asio::ip::tcp::v4(),port), acceptor(m_io_service,endpoint), num_threads(num_threads){} void start(){ for(auto it=resource.begin();it!=resource.end();++it){ all_resources.push_back(it); } for(auto it=default_resource.begin();it!=default_resource.end();++it){ all_resources.push_back(it); } accept(); for(size_t i=1;i<num_threads;i++){ threads.emplace_back([this](){ m_io_service.run(); }); } m_io_service.run(); for(auto& t:threads){ t.join(); } }; protected: boost::asio::io_service m_io_service; boost::asio::ip::tcp::endpoint endpoint; boost::asio::ip::tcp::acceptor acceptor; std::vector<resource_type::iterator> all_resources; size_t num_threads; std::vector<std::thread> threads; virtual void accept(){} void process_request_and_respond(std::shared_ptr<socket_type> socket) const{ auto read_buffer = std::make_shared<boost::asio::streambuf>(); boost::asio::async_read_until(*socket,*read_buffer,"\r\n\r\n", [this,socket,read_buffer](const boost::system::error_code& ec,size_t bytes_transferred){ if(!ec){ size_t total = read_buffer->size(); std::istream stream(read_buffer.get()); std::shared_ptr<Request> request = parseRequest(stream); size_t num_additional_bytes = total - bytes_transferred; if(request->getHeader("Content-Length").size()>0){ boost::asio::async_read(*socket,*read_buffer, boost::asio::transfer_exactly(std::stoull(request->getHeader("Content-Length"))- num_additional_bytes), [this,socket,read_buffer,request](const boost::system::error_code& ec,size_t bytes_transferred){ if(!ec){ auto bodyStream = std::shared_ptr<std::istream>(new std::istream(read_buffer.get())); //解析body std::string rawstr; std::string strTemp; while(std::getline(*bodyStream,strTemp)) { rawstr.append(strTemp); } request->setRawBody(rawstr); respond(socket,request); } }); }else{ respond(socket,request); } } }); }; void respond(std::shared_ptr<socket_type> socket, std::shared_ptr<Request> request) const { // 对请求路径和方法进行匹配查找,并生成响应 std::string path = request->getPath(); for(auto res_it: all_resources) { std::regex e(res_it->first); std::smatch sm_res; if(std::regex_match(path, sm_res, e)) { if(res_it->second.count(request->getMethod())>0) { //request->path_match = move(sm_res); // 会被推导为 std::shared_ptr<boost::asio::streambuf> auto write_buffer = std::make_shared<boost::asio::streambuf>(); std::ostream wb(write_buffer.get()); auto response = std::make_shared<Response>(); res_it->second[request->getMethod()](*response, *request); *response >> wb; // 在 lambda 中捕获 write_buffer 使其不会再 async_write 完成前被销毁 boost::asio::async_write(*socket, *write_buffer, [this, socket, request, write_buffer](const boost::system::error_code& ec, size_t bytes_transferred) { //HTTP 持久连接(HTTP 1.1): if(!ec && stof(request->getHttpVersion())>1.05) process_request_and_respond(socket); }); return; } } } } }; template<typename socket_type> class Server : public ServerBase<socket_type>{}; } #endif /* SERVER_BASE_HPP */
neveis/WebNote
server_base.hpp
C++
mit
4,506
// Search index songs package song import ( "github.com/ambientsound/pms/song" ) // Song is a Bleve document representing a song.Song object. type Song struct { Album string Albumartist string Artist string File string Genre string Title string Year string } // New generates a indexable Song document, containing some fields from the song.Song type. func New(s *song.Song) (is Song) { is.Album = s.StringTags["album"] is.Albumartist = s.StringTags["albumartist"] is.Artist = s.StringTags["artist"] is.File = s.StringTags["file"] is.Genre = s.StringTags["genre"] is.Title = s.StringTags["title"] is.Year = s.StringTags["year"] return }
ambientsound/pms
index/song/song.go
GO
mit
693
<?php use Symfony\Component\HttpKernel\Kernel; use Symfony\Component\Config\Loader\LoaderInterface; class AppKernel extends Kernel { public function registerBundles() { $bundles = array( new Symfony\Bundle\FrameworkBundle\FrameworkBundle(), new Symfony\Bundle\SecurityBundle\SecurityBundle(), new Symfony\Bundle\TwigBundle\TwigBundle(), new Symfony\Bundle\MonologBundle\MonologBundle(), new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(), new Symfony\Bundle\AsseticBundle\AsseticBundle(), new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(), new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(), new JMS\AopBundle\JMSAopBundle(), new JMS\DiExtraBundle\JMSDiExtraBundle($this), new JMS\SecurityExtraBundle\JMSSecurityExtraBundle(), new Wfl\BaseBundle\WflBaseBundle(), ); if (in_array($this->getEnvironment(), array('dev', 'test'))) { $bundles[] = new Acme\DemoBundle\AcmeDemoBundle(); $bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle(); $bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle(); $bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle(); } return $bundles; } public function registerContainerConfiguration(LoaderInterface $loader) { $loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.yml'); } }
fferz/lapagina
app/AppKernel.php
PHP
mit
1,567
#include "Mutex.h" /* Library C++ Mutex - Mutex fot threads. Copyright 2013 Eduardo Moura Sales Martins (edimartin@gmail.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ edk::multi::Mutex::Mutex(){ #if defined( WIN32) || defined( WIN64) this->mut = CreateMutex( NULL, FALSE, NULL); if (this->mut == NULL) { // } #endif #if defined(__linux__)/*LINUX*/ || defined(__APPLE__)//MAC OS if (pthread_mutex_init(&this->mut, NULL) != 0) { // } #endif } edk::multi::Mutex::~Mutex(){ #if defined( WIN32) || defined( WIN64) if(this->mut) CloseHandle(this->mut); #endif #if defined(__linux__)/*LINUX*/ || defined(__APPLE__)//MAC OS pthread_mutex_destroy(&this->mut); #endif } //lock this mutex to another don't run the code void edk::multi::Mutex::lock(){ #if defined( WIN32) || defined( WIN64) WaitForSingleObject(this->mut,INFINITE); #endif #if defined(__linux__)/*LINUX*/ || defined(__APPLE__)//MAC OS pthread_mutex_lock(&this->mut); #endif } //unlock this mutex void edk::multi::Mutex::unlock(){ #if defined( WIN32) || defined( WIN64) ReleaseMutex(this->mut); #endif #if defined(__linux__)/*LINUX*/ || defined(__APPLE__)//MAC OS pthread_mutex_unlock(&this->mut); #endif } //try lock the mutex (if true it's locked) bool edk::multi::Mutex::tryLock(){ #if defined( WIN32) || defined( WIN64) if(!WaitForSingleObject(this->mut,0u)){ return true; } #endif #if defined(__linux__)/*LINUX*/ || defined(__APPLE__)//MAC OS if(!pthread_mutex_trylock(&this->mut)){ return true; } #endif return false; }
Edimartin/edk-source
edk/thread/Mutex.cpp
C++
mit
2,587
#-*- coding: utf-8 -*- """ EOSS catalog system Implementation of urthecast catalog access https://developers.urthecast.com/sign-in """ __author__ = "Thilo Wehrmann, Steffen Gebhardt" __copyright__ = "Copyright 2016, EOSS GmbH" __credits__ = ["Thilo Wehrmann", "Steffen Gebhardt"] __license__ = "GPL" __version__ = "1.0.0" __maintainer__ = "Thilo Wehrmann" __email__ = "twehrmann@eoss.cloud" __status__ = "Production" import requests from manage import ICatalog from model.plain_models import Catalog_Dataset from shapely.geometry import Polygon from shapely.wkt import dumps as wkt_dumps class UrthecastCatalog(ICatalog): def __init__(self): # api_key = os.environ['UC_API_KEY'] # api_secret = os.environ['UC_API_SECRET'] self.api_key = 'B47EAFC6559748D4AD62' self.api_secret = 'D796AF0410DB4580876C66B72F790192' self.url = 'https://api.urthecast.com/v1/archive/scenes' def find(self, platforms, aoi, date_start, date_stop, cloud_ratio=0.2): url = self.url poly = Polygon(aoi) geometry = wkt_dumps(poly) params = { 'api_key': self.api_key, 'api_secret': self.api_secret, 'cloud_coverage_lte': cloud_ratio, 'acquired_gte': date_start.isoformat(), 'acquired_lte': date_stop.isoformat(), 'geometry_intersects': geometry, # 'sensor_platform': 'deimos-1,deimos-2,theia' 'sensor_platform': ",".join(platforms) } result = requests.get(url, params=params) datasets = set() for r in result.json()['payload']: ds = Catalog_Dataset() ds.entity_id = r['owner_scene_id'] ds.acq_time = r['acquired'] ds.sensor = r['sensor_platform'] # ds.tile_identifier = r['tile_identifier'] ds.clouds = r['cloud_coverage'] # ds.level = r['level'] if int(ds.clouds) > 0: ds.daynight = 'day' else: ds.daynight = 'night' datasets.add(ds) return datasets def register(self, ds): raise Exception('Cannot register dataset in repository %s' % self.__class__.__name__)
eoss-cloud/madxxx_catalog_api
catalog/manage/urthecastcatalog.py
Python
mit
2,226
require 'test_helper' class ConfirmationsControllerTest < ActionController::TestCase test "should get new" do get :new assert_response :success end test "should get create" do get :create assert_response :success end end
helmlogic/catalyst
test/functional/confirmations_controller_test.rb
Ruby
mit
248
import sqlalchemy class Connection(object): def __init__(self, auth): url = self._build_url(auth) self.engine = sqlalchemy.create_engine(url, convert_unicode=True) self.connection = None self.transaction = None def connect(self): self.connection = self.engine.connect() def disconnect(self): self.connection.close() self.connection = None def execute(self, sql_query): if not self.is_connected(): self.connect() return self.connection.execute(sql_query) def begin_transaction(self): if not self.is_connected(): self.connect() self.transaction = self.connection.begin() def end_transaction(self): self.transaction.commit() self.transaction = None def is_connected(self): return self.connection is not None def _build_url(self, auth): def get_value(data, keys, default=None): result = None for k in keys: result = data.get(k) if result is not None: return result if result is None: return default db_type = get_value(auth, ['type', 'db_type'], 'pgsql') if db_type == 'mysql': default_port = 3306 elif db_type == 'pgsql': default_port = 5432 ctx = (get_value(auth, ['user']), get_value(auth, ['passwd', 'password', 'pass']), get_value(auth, ['host', 'server'], 'localhost'), get_value(auth, ['port'], default_port), get_value(auth, ['database', 'db_name', 'database_name', 'db'])) if db_type == 'pgsql': url_tpl = 'postgresql+psycopg2://%s:%s@%s:%s/%s' % ctx elif db_type == 'mysql': url_tpl = 'mysql+mysqldb://%s:%s@%s:%s/%s' % ctx else: RaiseValue('db_type must be eighter "mysql" or "pgsql"') return url_tpl % auth
trackingwire/witchcraft
witchcraft/connection.py
Python
mit
2,023
// Copyright (c) 2011-2013 The mitcoin Core developers // Distributed under the MIT software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "mitcoinunits.h" #include "primitives/transaction.h" #include <QStringList> mitcoinUnits::mitcoinUnits(QObject *parent): QAbstractListModel(parent), unitlist(availableUnits()) { } QList<mitcoinUnits::Unit> mitcoinUnits::availableUnits() { QList<mitcoinUnits::Unit> unitlist; unitlist.append(BTC); unitlist.append(mBTC); unitlist.append(uBTC); return unitlist; } bool mitcoinUnits::valid(int unit) { switch(unit) { case BTC: case mBTC: case uBTC: return true; default: return false; } } QString mitcoinUnits::name(int unit) { switch(unit) { case BTC: return QString("BTC"); case mBTC: return QString("mBTC"); case uBTC: return QString::fromUtf8("μBTC"); default: return QString("???"); } } QString mitcoinUnits::description(int unit) { switch(unit) { case BTC: return QString("mitcoins"); case mBTC: return QString("Milli-mitcoins (1 / 1" THIN_SP_UTF8 "000)"); case uBTC: return QString("Micro-mitcoins (1 / 1" THIN_SP_UTF8 "000" THIN_SP_UTF8 "000)"); default: return QString("???"); } } qint64 mitcoinUnits::factor(int unit) { switch(unit) { case BTC: return 100000000; case mBTC: return 100000; case uBTC: return 100; default: return 100000000; } } int mitcoinUnits::decimals(int unit) { switch(unit) { case BTC: return 8; case mBTC: return 5; case uBTC: return 2; default: return 0; } } QString mitcoinUnits::format(int unit, const CAmount& nIn, bool fPlus, SeparatorStyle separators) { // Note: not using straight sprintf here because we do NOT want // localized number formatting. if(!valid(unit)) return QString(); // Refuse to format invalid unit qint64 n = (qint64)nIn; qint64 coin = factor(unit); int num_decimals = decimals(unit); qint64 n_abs = (n > 0 ? n : -n); qint64 quotient = n_abs / coin; qint64 remainder = n_abs % coin; QString quotient_str = QString::number(quotient); QString remainder_str = QString::number(remainder).rightJustified(num_decimals, '0'); // Use SI-style thin space separators as these are locale independent and can't be // confused with the decimal marker. QChar thin_sp(THIN_SP_CP); int q_size = quotient_str.size(); if (separators == separatorAlways || (separators == separatorStandard && q_size > 4)) for (int i = 3; i < q_size; i += 3) quotient_str.insert(q_size - i, thin_sp); if (n < 0) quotient_str.insert(0, '-'); else if (fPlus && n > 0) quotient_str.insert(0, '+'); return quotient_str + QString(".") + remainder_str; } // TODO: Review all remaining calls to mitcoinUnits::formatWithUnit to // TODO: determine whether the output is used in a plain text context // TODO: or an HTML context (and replace with // TODO: BtcoinUnits::formatHtmlWithUnit in the latter case). Hopefully // TODO: there aren't instances where the result could be used in // TODO: either context. // NOTE: Using formatWithUnit in an HTML context risks wrapping // quantities at the thousands separator. More subtly, it also results // in a standard space rather than a thin space, due to a bug in Qt's // XML whitespace canonicalisation // // Please take care to use formatHtmlWithUnit instead, when // appropriate. QString mitcoinUnits::formatWithUnit(int unit, const CAmount& amount, bool plussign, SeparatorStyle separators) { return format(unit, amount, plussign, separators) + QString(" ") + name(unit); } QString mitcoinUnits::formatHtmlWithUnit(int unit, const CAmount& amount, bool plussign, SeparatorStyle separators) { QString str(formatWithUnit(unit, amount, plussign, separators)); str.replace(QChar(THIN_SP_CP), QString(THIN_SP_HTML)); return QString("<span style='white-space: nowrap;'>%1</span>").arg(str); } bool mitcoinUnits::parse(int unit, const QString &value, CAmount *val_out) { if(!valid(unit) || value.isEmpty()) return false; // Refuse to parse invalid unit or empty string int num_decimals = decimals(unit); // Ignore spaces and thin spaces when parsing QStringList parts = removeSpaces(value).split("."); if(parts.size() > 2) { return false; // More than one dot } QString whole = parts[0]; QString decimals; if(parts.size() > 1) { decimals = parts[1]; } if(decimals.size() > num_decimals) { return false; // Exceeds max precision } bool ok = false; QString str = whole + decimals.leftJustified(num_decimals, '0'); if(str.size() > 18) { return false; // Longer numbers will exceed 63 bits } CAmount retvalue(str.toLongLong(&ok)); if(val_out) { *val_out = retvalue; } return ok; } QString mitcoinUnits::getAmountColumnTitle(int unit) { QString amountTitle = QObject::tr("Amount"); if (mitcoinUnits::valid(unit)) { amountTitle += " ("+mitcoinUnits::name(unit) + ")"; } return amountTitle; } int mitcoinUnits::rowCount(const QModelIndex &parent) const { Q_UNUSED(parent); return unitlist.size(); } QVariant mitcoinUnits::data(const QModelIndex &index, int role) const { int row = index.row(); if(row >= 0 && row < unitlist.size()) { Unit unit = unitlist.at(row); switch(role) { case Qt::EditRole: case Qt::DisplayRole: return QVariant(name(unit)); case Qt::ToolTipRole: return QVariant(description(unit)); case UnitRole: return QVariant(static_cast<int>(unit)); } } return QVariant(); } CAmount mitcoinUnits::maxMoney() { return MAX_MONEY; }
anders94/mitcoin
src/qt/mitcoinunits.cpp
C++
mit
5,957
<?php function build_order_no(){ $year_code = array('a','b','c','d','e','f','g','h','i','j'); $order_sn = (intval(date('Y'))- 2014) . strtoupper(dechex(date('m'))) . strtoupper(dechex(date('d'))). substr(time(),-5).substr(microtime(),2,5).sprintf('%d',rand(0,99)); return $order_sn; } $num = 0; while($num < 20){ echo @build_order_no() . "\r\n"; $num ++; }
z32556601/90ping
doc/test.php
PHP
mit
388
'use strict'; var Promise = require('bluebird'); var util = require('./util'); module.exports = function (bookshelf) { var BaseModel = bookshelf.Model.extend({ initialize: function () { this.on('saving', this.validate); }, validate: function (model, attrs, options) { return Promise.resolve(null) .then(util.collectAndCheckMissingAttributes.bind(this, options)) .then(util.validateAttributes.bind(this)) .then(util.setValidatedAttributes.bind(this)); } }); bookshelf.Model = BaseModel; };
murmur76/bookshelf-validation
index.js
JavaScript
mit
545
require 'spec_helper' describe "User", :type => :model do before(:all) do self.class.fixtures :categories, :departments, :notes, :things, :brokens, :users end describe "hierarchical structure" do it "roots_class_method" do found_by_us = User.where(:parent_uuid => nil).to_a found_by_roots = User.roots.to_a expect(found_by_us.length).to eq(found_by_roots.length) found_by_us.each do |root| expect(found_by_roots).to include(root) end end it "root_class_method" do expect(User.root).to eq(users(:top_level)) end it "root" do expect(users(:child_3).root).to eq(users(:top_level)) end it "root when not persisted and parent_column_name value is self" do new_user = User.new expect(new_user.root).to eq(new_user) end it "root?" do expect(users(:top_level).root?).to be_truthy expect(users(:top_level_2).root?).to be_truthy end it "leaves_class_method" do expect(User.where("#{User.right_column_name} - #{User.left_column_name} = 1").to_a.sort_by(&:id)).to eq(User.leaves.to_a) expect(User.leaves.count).to eq(4) expect(User.leaves).to include(users(:child_1)) expect(User.leaves).to include(users(:child_2_1)) expect(User.leaves).to include(users(:child_3)) expect(User.leaves).to include(users(:top_level_2)) end it "leaf" do expect(users(:child_1).leaf?).to be_truthy expect(users(:child_2_1).leaf?).to be_truthy expect(users(:child_3).leaf?).to be_truthy expect(users(:top_level_2).leaf?).to be_truthy expect(users(:top_level).leaf?).to be_falsey expect(users(:child_2).leaf?).to be_falsey expect(User.new.leaf?).to be_falsey end it "parent" do expect(users(:child_2_1).parent).to eq(users(:child_2)) end it "self_and_ancestors" do child = users(:child_2_1) self_and_ancestors = [users(:top_level), users(:child_2), child] expect(child.self_and_ancestors).to eq(self_and_ancestors) end it "ancestors" do child = users(:child_2_1) ancestors = [users(:top_level), users(:child_2)] expect(ancestors).to eq(child.ancestors) end it "self_and_siblings" do child = users(:child_2) self_and_siblings = [users(:child_1), child, users(:child_3)] expect(self_and_siblings).to eq(child.self_and_siblings) expect do tops = [users(:top_level), users(:top_level_2)] assert_equal tops, users(:top_level).self_and_siblings end.not_to raise_exception end it "siblings" do child = users(:child_2) siblings = [users(:child_1), users(:child_3)] expect(siblings).to eq(child.siblings) end it "leaves" do leaves = [users(:child_1), users(:child_2_1), users(:child_3)] expect(users(:top_level).leaves).to eq(leaves) end end describe "level" do it "returns the correct level" do expect(users(:top_level).level).to eq(0) expect(users(:child_1).level).to eq(1) expect(users(:child_2_1).level).to eq(2) end context "given parent associations are loaded" do it "returns the correct level" do child = users(:child_1) if child.respond_to?(:association) child.association(:parent).load_target child.parent.association(:parent).load_target expect(child.level).to eq(1) else skip 'associations not used where child#association is not a method' end end end end describe "depth" do context "in general" do let(:ceo) { User.create!(:name => "CEO") } let(:district_manager) { User.create!(:name => "District Manager") } let(:store_manager) { User.create!(:name => "Store Manager") } let(:cashier) { User.create!(:name => "Cashier") } before(:each) do # ceo > district_manager > store_manager > cashier district_manager.move_to_child_of(ceo) store_manager.move_to_child_of(district_manager) cashier.move_to_child_of(store_manager) [ceo, district_manager, store_manager, cashier].each(&:reload) end it "updates depth when moved into child position" do expect(ceo.depth).to eq(0) expect(district_manager.depth).to eq(1) expect(store_manager.depth).to eq(2) expect(cashier.depth).to eq(3) end it "updates depth of all descendants when parent is moved" do # ceo # district_manager > store_manager > cashier district_manager.move_to_right_of(ceo) [ceo, district_manager, store_manager, cashier].each(&:reload) expect(district_manager.depth).to eq(0) expect(store_manager.depth).to eq(1) expect(cashier.depth).to eq(2) end end it "is magic and does not apply when column is missing" do expect { NoDepth.create!(:name => "shallow") }.not_to raise_error expect { NoDepth.first.save }.not_to raise_error expect { NoDepth.rebuild! }.not_to raise_error expect(NoDepth.method_defined?(:depth)).to be_falsey expect(NoDepth.first.respond_to?(:depth)).to be_falsey end end it "has_children?" do expect(users(:child_2_1).children.empty?).to be_truthy expect(users(:child_2).children.empty?).to be_falsey expect(users(:top_level).children.empty?).to be_falsey end it "self_and_descendants" do parent = users(:top_level) self_and_descendants = [ parent, users(:child_1), users(:child_2), users(:child_2_1), users(:child_3) ] expect(self_and_descendants).to eq(parent.self_and_descendants) expect(self_and_descendants.count).to eq(parent.self_and_descendants.count) end it "descendants" do lawyers = User.create!(:name => "lawyers") us = User.create!(:name => "United States") us.move_to_child_of(lawyers) patent = User.create!(:name => "Patent Law") patent.move_to_child_of(us) lawyers.reload expect(lawyers.children.size).to eq(1) expect(us.children.size).to eq(1) expect(lawyers.descendants.size).to eq(2) end it "self_and_descendants" do parent = users(:top_level) descendants = [ users(:child_1), users(:child_2), users(:child_2_1), users(:child_3) ] expect(descendants).to eq(parent.descendants) end it "children" do user = users(:top_level) user.children.each {|c| expect(user.uuid).to eq(c.parent_uuid) } end it "order_of_children" do users(:child_2).move_left expect(users(:child_2)).to eq(users(:top_level).children[0]) expect(users(:child_1)).to eq(users(:top_level).children[1]) expect(users(:child_3)).to eq(users(:top_level).children[2]) end it "is_or_is_ancestor_of?" do expect(users(:top_level).is_or_is_ancestor_of?(users(:child_1))).to be_truthy expect(users(:top_level).is_or_is_ancestor_of?(users(:child_2_1))).to be_truthy expect(users(:child_2).is_or_is_ancestor_of?(users(:child_2_1))).to be_truthy expect(users(:child_2_1).is_or_is_ancestor_of?(users(:child_2))).to be_falsey expect(users(:child_1).is_or_is_ancestor_of?(users(:child_2))).to be_falsey expect(users(:child_1).is_or_is_ancestor_of?(users(:child_1))).to be_truthy end it "is_ancestor_of?" do expect(users(:top_level).is_ancestor_of?(users(:child_1))).to be_truthy expect(users(:top_level).is_ancestor_of?(users(:child_2_1))).to be_truthy expect(users(:child_2).is_ancestor_of?(users(:child_2_1))).to be_truthy expect(users(:child_2_1).is_ancestor_of?(users(:child_2))).to be_falsey expect(users(:child_1).is_ancestor_of?(users(:child_2))).to be_falsey expect(users(:child_1).is_ancestor_of?(users(:child_1))).to be_falsey end it "is_or_is_ancestor_of_with_scope" do root = ScopedUser.root child = root.children.first expect(root.is_or_is_ancestor_of?(child)).to be_truthy child.update_attribute :organization_id, 999999999 expect(root.is_or_is_ancestor_of?(child)).to be_falsey end it "is_or_is_descendant_of?" do expect(users(:child_1).is_or_is_descendant_of?(users(:top_level))).to be_truthy expect(users(:child_2_1).is_or_is_descendant_of?(users(:top_level))).to be_truthy expect(users(:child_2_1).is_or_is_descendant_of?(users(:child_2))).to be_truthy expect(users(:child_2).is_or_is_descendant_of?(users(:child_2_1))).to be_falsey expect(users(:child_2).is_or_is_descendant_of?(users(:child_1))).to be_falsey expect(users(:child_1).is_or_is_descendant_of?(users(:child_1))).to be_truthy end it "is_descendant_of?" do expect(users(:child_1).is_descendant_of?(users(:top_level))).to be_truthy expect(users(:child_2_1).is_descendant_of?(users(:top_level))).to be_truthy expect(users(:child_2_1).is_descendant_of?(users(:child_2))).to be_truthy expect(users(:child_2).is_descendant_of?(users(:child_2_1))).to be_falsey expect(users(:child_2).is_descendant_of?(users(:child_1))).to be_falsey expect(users(:child_1).is_descendant_of?(users(:child_1))).to be_falsey end it "is_or_is_descendant_of_with_scope" do root = ScopedUser.root child = root.children.first expect(child.is_or_is_descendant_of?(root)).to be_truthy child.update_attribute :organization_id, 999999999 expect(child.is_or_is_descendant_of?(root)).to be_falsey end it "same_scope?" do root = ScopedUser.root child = root.children.first expect(child.same_scope?(root)).to be_truthy child.update_attribute :organization_id, 999999999 expect(child.same_scope?(root)).to be_falsey end it "left_sibling" do expect(users(:child_1)).to eq(users(:child_2).left_sibling) expect(users(:child_2)).to eq(users(:child_3).left_sibling) end it "left_sibling_of_root" do expect(users(:top_level).left_sibling).to be_nil end it "left_sibling_without_siblings" do expect(users(:child_2_1).left_sibling).to be_nil end it "left_sibling_of_leftmost_node" do expect(users(:child_1).left_sibling).to be_nil end it "right_sibling" do expect(users(:child_3)).to eq(users(:child_2).right_sibling) expect(users(:child_2)).to eq(users(:child_1).right_sibling) end it "right_sibling_of_root" do expect(users(:top_level_2)).to eq(users(:top_level).right_sibling) expect(users(:top_level_2).right_sibling).to be_nil end it "right_sibling_without_siblings" do expect(users(:child_2_1).right_sibling).to be_nil end it "right_sibling_of_rightmost_node" do expect(users(:child_3).right_sibling).to be_nil end it "move_left" do users(:child_2).move_left expect(users(:child_2).left_sibling).to be_nil expect(users(:child_1)).to eq(users(:child_2).right_sibling) expect(User.valid?).to be_truthy end it "move_right" do users(:child_2).move_right expect(users(:child_2).right_sibling).to be_nil expect(users(:child_3)).to eq(users(:child_2).left_sibling) expect(User.valid?).to be_truthy end it "move_to_left_of" do users(:child_3).move_to_left_of(users(:child_1)) expect(users(:child_3).left_sibling).to be_nil expect(users(:child_1)).to eq(users(:child_3).right_sibling) expect(User.valid?).to be_truthy end it "move_to_right_of" do users(:child_1).move_to_right_of(users(:child_3)) expect(users(:child_1).right_sibling).to be_nil expect(users(:child_3)).to eq(users(:child_1).left_sibling) expect(User.valid?).to be_truthy end it "move_to_root" do users(:child_2).move_to_root expect(users(:child_2).parent).to be_nil expect(users(:child_2).level).to eq(0) expect(users(:child_2_1).level).to eq(1) expect(users(:child_2).left).to eq(9) expect(users(:child_2).right).to eq(12) expect(User.valid?).to be_truthy end it "move_to_child_of" do users(:child_1).move_to_child_of(users(:child_3)) expect(users(:child_3).uuid).to eq(users(:child_1).parent_uuid) expect(User.valid?).to be_truthy end describe "#move_to_child_with_index" do it "move to a node without child" do users(:child_1).move_to_child_with_index(users(:child_3), 0) expect(users(:child_3).uuid).to eq(users(:child_1).parent_uuid) expect(users(:child_1).left).to eq(7) expect(users(:child_1).right).to eq(8) expect(users(:child_3).left).to eq(6) expect(users(:child_3).right).to eq(9) expect(User.valid?).to be_truthy end it "move to a node to the left child" do users(:child_1).move_to_child_with_index(users(:child_2), 0) expect(users(:child_1).parent_uuid).to eq(users(:child_2).uuid) expect(users(:child_2_1).left).to eq(5) expect(users(:child_2_1).right).to eq(6) expect(users(:child_1).left).to eq(3) expect(users(:child_1).right).to eq(4) users(:child_2).reload expect(users(:child_2).left).to eq(2) expect(users(:child_2).right).to eq(7) end it "move to a node to the right child" do users(:child_1).move_to_child_with_index(users(:child_2), 1) expect(users(:child_1).parent_uuid).to eq(users(:child_2).uuid) expect(users(:child_2_1).left).to eq(3) expect(users(:child_2_1).right).to eq(4) expect(users(:child_1).left).to eq(5) expect(users(:child_1).right).to eq(6) users(:child_2).reload expect(users(:child_2).left).to eq(2) expect(users(:child_2).right).to eq(7) end end it "move_to_child_of_appends_to_end" do child = User.create! :name => 'New Child' child.move_to_child_of users(:top_level) expect(child).to eq(users(:top_level).children.last) end it "subtree_move_to_child_of" do expect(users(:child_2).left).to eq(4) expect(users(:child_2).right).to eq(7) expect(users(:child_1).left).to eq(2) expect(users(:child_1).right).to eq(3) users(:child_2).move_to_child_of(users(:child_1)) expect(User.valid?).to be_truthy expect(users(:child_1).uuid).to eq(users(:child_2).parent_uuid) expect(users(:child_2).left).to eq(3) expect(users(:child_2).right).to eq(6) expect(users(:child_1).left).to eq(2) expect(users(:child_1).right).to eq(7) end it "slightly_difficult_move_to_child_of" do expect(users(:top_level_2).left).to eq(11) expect(users(:top_level_2).right).to eq(12) # create a new top-level node and move single-node top-level tree inside it. new_top = User.create(:name => 'New Top') expect(new_top.left).to eq(13) expect(new_top.right).to eq(14) users(:top_level_2).move_to_child_of(new_top) expect(User.valid?).to be_truthy expect(new_top.uuid).to eq(users(:top_level_2).parent_uuid) expect(users(:top_level_2).left).to eq(12) expect(users(:top_level_2).right).to eq(13) expect(new_top.left).to eq(11) expect(new_top.right).to eq(14) end it "difficult_move_to_child_of" do expect(users(:top_level).left).to eq(1) expect(users(:top_level).right).to eq(10) expect(users(:child_2_1).left).to eq(5) expect(users(:child_2_1).right).to eq(6) # create a new top-level node and move an entire top-level tree inside it. new_top = User.create(:name => 'New Top') users(:top_level).move_to_child_of(new_top) users(:child_2_1).reload expect(User.valid?).to be_truthy expect(new_top.uuid).to eq(users(:top_level).parent_uuid) expect(users(:top_level).left).to eq(4) expect(users(:top_level).right).to eq(13) expect(users(:child_2_1).left).to eq(8) expect(users(:child_2_1).right).to eq(9) end #rebuild swaps the position of the 2 children when added using move_to_child twice onto same parent it "move_to_child_more_than_once_per_parent_rebuild" do root1 = User.create(:name => 'Root1') root2 = User.create(:name => 'Root2') root3 = User.create(:name => 'Root3') root2.move_to_child_of root1 root3.move_to_child_of root1 output = User.roots.last.to_text User.update_all('lft = null, rgt = null') User.rebuild! expect(User.roots.last.to_text).to eq(output) end # doing move_to_child twice onto same parent from the furthest right first it "move_to_child_more_than_once_per_parent_outside_in" do node1 = User.create(:name => 'Node-1') node2 = User.create(:name => 'Node-2') node3 = User.create(:name => 'Node-3') node2.move_to_child_of node1 node3.move_to_child_of node1 output = User.roots.last.to_text User.update_all('lft = null, rgt = null') User.rebuild! expect(User.roots.last.to_text).to eq(output) end it "should_move_to_ordered_child" do node1 = User.create(:name => 'Node-1') node2 = User.create(:name => 'Node-2') node3 = User.create(:name => 'Node-3') node2.move_to_ordered_child_of(node1, "name") assert_equal node1, node2.parent assert_equal 1, node1.children.count node3.move_to_ordered_child_of(node1, "name", true) # ascending expect(node3.parent).to eq(node1) expect(node1.children.count).to be(2) expect(node1.children[0].name).to eq(node2.name) expect(node1.children[1].name).to eq(node3.name) node3.move_to_ordered_child_of(node1, "name", false) # descending node1.reload expect(node3.parent).to eq(node1) expect(node1.children.count).to be(2) expect(node1.children[0].name).to eq(node3.name) expect(node1.children[1].name).to eq(node2.name) end it "should be able to rebuild without validating each record" do root1 = User.create(:name => 'Root1') root2 = User.create(:name => 'Root2') root3 = User.create(:name => 'Root3') root2.move_to_child_of root1 root3.move_to_child_of root1 root2.name = nil root2.save!(:validate => false) output = User.roots.last.to_text User.update_all('lft = null, rgt = null') User.rebuild!(false) expect(User.roots.last.to_text).to eq(output) end it "valid_with_null_lefts" do expect(User.valid?).to be_truthy User.update_all('lft = null') expect(User.valid?).to be_falsey end it "valid_with_null_rights" do expect(User.valid?).to be_truthy User.update_all('rgt = null') expect(User.valid?).to be_falsey end it "valid_with_missing_intermediate_node" do # Even though child_2_1 will still exist, it is a sign of a sloppy delete, not an invalid tree. expect(User.valid?).to be_truthy User.where(uuid: users(:child_2).uuid).delete_all expect(User.valid?).to be_truthy end it "valid_with_overlapping_and_rights" do expect(User.valid?).to be_truthy users(:top_level_2)['lft'] = 0 users(:top_level_2).save expect(User.valid?).to be_falsey end it "rebuild" do expect(User.valid?).to be_truthy before_text = User.root.to_text User.update_all('lft = null, rgt = null') User.rebuild! expect(User.valid?).to be_truthy expect(before_text).to eq(User.root.to_text) end it "move_possible_for_sibling" do expect(users(:child_2).move_possible?(users(:child_1))).to be_truthy end it "move_not_possible_to_self" do expect(users(:top_level).move_possible?(users(:top_level))).to be_falsey end it "move_not_possible_to_parent" do users(:top_level).descendants.each do |descendant| expect(users(:top_level).move_possible?(descendant)).to be_falsey expect(descendant.move_possible?(users(:top_level))).to be_truthy end end it "is_or_is_ancestor_of?" do [:child_1, :child_2, :child_2_1, :child_3].each do |c| expect(users(:top_level).is_or_is_ancestor_of?(users(c))).to be_truthy end expect(users(:top_level).is_or_is_ancestor_of?(users(:top_level_2))).to be_falsey end it "left_and_rights_valid_with_blank_left" do expect(User.left_and_rights_valid?).to be_truthy users(:child_2)[:lft] = nil users(:child_2).save(:validate => false) expect(User.left_and_rights_valid?).to be_falsey end it "left_and_rights_valid_with_blank_right" do expect(User.left_and_rights_valid?).to be_truthy users(:child_2)[:rgt] = nil users(:child_2).save(:validate => false) expect(User.left_and_rights_valid?).to be_falsey end it "left_and_rights_valid_with_equal" do expect(User.left_and_rights_valid?).to be_truthy users(:top_level_2)[:lft] = users(:top_level_2)[:rgt] users(:top_level_2).save(:validate => false) expect(User.left_and_rights_valid?).to be_falsey end it "left_and_rights_valid_with_left_equal_to_parent" do expect(User.left_and_rights_valid?).to be_truthy users(:child_2)[:lft] = users(:top_level)[:lft] users(:child_2).save(:validate => false) expect(User.left_and_rights_valid?).to be_falsey end it "left_and_rights_valid_with_right_equal_to_parent" do expect(User.left_and_rights_valid?).to be_truthy users(:child_2)[:rgt] = users(:top_level)[:rgt] users(:child_2).save(:validate => false) expect(User.left_and_rights_valid?).to be_falsey end it "moving_dirty_objects_doesnt_invalidate_tree" do r1 = User.create :name => "Test 1" r2 = User.create :name => "Test 2" r3 = User.create :name => "Test 3" r4 = User.create :name => "Test 4" nodes = [r1, r2, r3, r4] r2.move_to_child_of(r1) expect(User.valid?).to be_truthy r3.move_to_child_of(r1) expect(User.valid?).to be_truthy r4.move_to_child_of(r2) expect(User.valid?).to be_truthy end it "delete_does_not_invalidate" do User.acts_as_nested_set_options[:dependent] = :delete users(:child_2).destroy expect(User.valid?).to be_truthy end it "destroy_does_not_invalidate" do User.acts_as_nested_set_options[:dependent] = :destroy users(:child_2).destroy expect(User.valid?).to be_truthy end it "destroy_multiple_times_does_not_invalidate" do User.acts_as_nested_set_options[:dependent] = :destroy users(:child_2).destroy users(:child_2).destroy expect(User.valid?).to be_truthy end it "assigning_parent_uuid_on_create" do user = User.create!(:name => "Child", :parent_uuid => users(:child_2).uuid) expect(users(:child_2)).to eq(user.parent) expect(users(:child_2).uuid).to eq(user.parent_uuid) expect(user.left).not_to be_nil expect(user.right).not_to be_nil expect(User.valid?).to be_truthy end it "assigning_parent_on_create" do user = User.create!(:name => "Child", :parent => users(:child_2)) expect(users(:child_2)).to eq(user.parent) expect(users(:child_2).uuid).to eq(user.parent_uuid) expect(user.left).not_to be_nil expect(user.right).not_to be_nil expect(User.valid?).to be_truthy end it "assigning_parent_uuid_to_nil_on_create" do user = User.create!(:name => "New Root", :parent_uuid => nil) expect(user.parent).to be_nil expect(user.parent_uuid).to be_nil expect(user.left).not_to be_nil expect(user.right).not_to be_nil expect(User.valid?).to be_truthy end it "assigning_parent_uuid_on_update" do user = users(:child_2_1) user.parent_uuid = users(:child_3).uuid user.save user.reload users(:child_3).reload expect(users(:child_3)).to eq(user.parent) expect(users(:child_3).uuid).to eq(user.parent_uuid) expect(User.valid?).to be_truthy end it "assigning_parent_on_update" do user = users(:child_2_1) user.parent = users(:child_3) user.save user.reload users(:child_3).reload expect(users(:child_3)).to eq(user.parent) expect(users(:child_3).uuid).to eq(user.parent_uuid) expect(User.valid?).to be_truthy end it "assigning_parent_uuid_to_nil_on_update" do user = users(:child_2_1) user.parent_uuid = nil user.save expect(user.parent).to be_nil expect(user.parent_uuid).to be_nil expect(User.valid?).to be_truthy end it "creating_child_from_parent" do user = users(:child_2).children.create!(:name => "Child") expect(users(:child_2)).to eq(user.parent) expect(users(:child_2).uuid).to eq(user.parent_uuid) expect(user.left).not_to be_nil expect(user.right).not_to be_nil expect(User.valid?).to be_truthy end it 'creates user when clause where provided' do parent = User.first expect do User.where(name: "Chris-#{Time.current.to_f}").first_or_create! do |user| user.parent = parent end end.to change { User.count }.by 1 end def check_structure(entries, structure) structure = structure.dup User.each_with_level(entries) do |user, level| expected_level, expected_name = structure.shift expect(expected_name).to eq(user.name) expect(expected_level).to eq(level) end end it "each_with_level" do levels = [ [0, "Top Level"], [1, "Child 1"], [1, "Child 2"], [2, "Child 2.1"], [1, "Child 3" ] ] check_structure(User.root.self_and_descendants, levels) # test some deeper structures user = User.find_by_name("Child 1") c1 = User.new(:name => "Child 1.1") c2 = User.new(:name => "Child 1.1.1") c3 = User.new(:name => "Child 1.1.1.1") c4 = User.new(:name => "Child 1.2") [c1, c2, c3, c4].each(&:save!) c1.move_to_child_of(user) c2.move_to_child_of(c1) c3.move_to_child_of(c2) c4.move_to_child_of(user) levels = [ [0, "Top Level"], [1, "Child 1"], [2, "Child 1.1"], [3, "Child 1.1.1"], [4, "Child 1.1.1.1"], [2, "Child 1.2"], [1, "Child 2"], [2, "Child 2.1"], [1, "Child 3" ] ] check_structure(User.root.self_and_descendants, levels) end describe "before_move_callback" do it "should fire the callback" do expect(users(:child_2)).to receive(:custom_before_move) users(:child_2).move_to_root end it "should stop move when callback returns false" do User.test_allows_move = false expect(users(:child_3).move_to_root).to be_falsey expect(users(:child_3).root?).to be_falsey end it "should not halt save actions" do User.test_allows_move = false users(:child_3).parent_uuid = nil expect(users(:child_3).save).to be_truthy end end describe 'associate_parents' do it 'assigns parent' do root = User.root users = root.self_and_descendants users = User.associate_parents users expect(users[1].parent).to be users.first end it 'adds children on inverse of association' do root = User.root users = root.self_and_descendants users = User.associate_parents users expect(users[0].children.first).to be users[1] end end describe 'option dependent' do it 'destroy should destroy children and node' do User.acts_as_nested_set_options[:dependent] = :destroy root = User.root root.destroy! expect(User.where(uuid: root.uuid)).to be_empty expect(User.where(parent_uuid: root.uuid)).to be_empty end it 'delete should delete children and node' do User.acts_as_nested_set_options[:dependent] = :delete root = User.root root.destroy! expect(User.where(uuid: root.uuid)).to be_empty expect(User.where(parent_uuid: root.uuid)).to be_empty end describe 'restrict_with_exception' do it 'raises an exception' do User.acts_as_nested_set_options[:dependent] = :restrict_with_exception root = User.root expect { root.destroy! }.to raise_error ActiveRecord::DeleteRestrictionError, 'Cannot delete record because of dependent children' end it 'deletes the leaf' do User.acts_as_nested_set_options[:dependent] = :restrict_with_exception leaf = User.last expect(leaf.destroy).to eq(leaf) end end describe 'restrict_with_error' do it 'adds the error to the parent' do User.acts_as_nested_set_options[:dependent] = :restrict_with_error root = User.root root.destroy expect(root.errors[:base]).to eq(["Cannot delete record because dependent children exist"]) end it 'deletes the leaf' do User.acts_as_nested_set_options[:dependent] = :restrict_with_error leaf = User.last expect(leaf.destroy).to eq(leaf) end end end end
collectiveidea/awesome_nested_set
spec/models/users_spec.rb
Ruby
mit
28,195
#dice guideline from random import randint #FOR program module moduleName="Dice Module" #moduleName="The Lusty Orc Dice Module" #FOR dice rolls #mulligan_yes_or_no=True not implemented the_lowest_possible_roll=1 the_number_of_sides_on_a_die=6 the_number_of_rolls_in_a_set=4 reroll_if_equal_or_less=0 number_of_lowest_rolls_to_drop_in_a_set=1 number_of_highest_rolls_to_drop_in_a_set=1 #Rules for attribute rolls, Do not alter anything past this line ''' def dicerollbatch(): WorkingBatch=[] for setNumber in range(self.dieSets): rolls=[] dropped=[] #creates another recursion loop that runs for die_number_per_set times and addes a random roll result to the rolls and dropped lists using the x variable, each roll is between the values lowest_possible_roll and number_of_sides_on_die for roll in range(self.setDieNumber): r=(randint(lowest_possible_roll, self.dieSides)) rolls.append(r) dropped.append(r) #after the rolls are done, normally 4 of them, the set is added to the rollBatch variable container as well as adding to the dropped sets container self.rollBatch.append(rolls) dropped.remove(min(dropped)) self.droppedBatch.append(dropped) #after the roll sets have been added to the batch the batch count is incremented up one self.batch+=1 #after the numbers have been generated and appended to the batch the sets are printed out vertically print("number of batch attempts:"+str(self.batch)+"\nStat Rolls") for batchSets in range(len(self.rollBatch)): at=0 for batchRolls in range(len(self.droppedBatch[batchSets])):at+=self.droppedBatch[batchSets][batchRolls] self.attributeResults.append(at) print((self.rollBatch[batchSets]), (self.attributeResults[batchSets])) ''' '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' #test_4_rolls_print from random import randint The_number_of_rolls_in_a_set=4 The_number_of_sides_on_a_die=6 the_lowest_possible_roll=1 #the followign 6 lines of code roll 4 numbers between 1 and 6 and then prints them out vertically def roll_set_of_dice(): for roll in range(The_number_of_rolls_in_a_set): roll_result=(randint(the_lowest_possible_roll, The_number_of_sides_on_a_die)) print("%s" % roll_result) return #roll_set_of_dice() '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' #test_4_rolls_output_to_list_print_list from random import randint the_number_of_rolls_in_a_set=4 the_number_of_sides_on_a_die=6 the_lowest_possible_roll=1 #the following 8 lines of code rolls 4 6 sided dice and copies the reuslts to a lsit and then print's the list def roll_set_of_dice(): set_of_dice_rolls=[] for roll in range(the_number_of_rolls_in_a_set): roll_result=(randint(the_lowest_possible_roll, the_number_of_sides_on_a_die)) set_of_dice_rolls.append(roll_result) print(set_of_dice_rolls) return #roll_set_of_dice() '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' #test_4_rolls with reroll and output from random import randint the_number_of_rolls_in_a_set=4 the_number_of_sides_on_a_die=6 the_lowest_possible_roll=1 reroll_if_equal_or_less=5 #rolls 4 dice between 1 and 6 and rerolls all results that are 5 or less then outputs them to roll_set_of_dice def roll_set_of_dice(): set_of_dice_rolls=[] for roll in range(the_number_of_rolls_in_a_set): roll_result=(randint(the_lowest_possible_roll, the_number_of_sides_on_a_die)) while roll_result<=reroll_if_equal_or_less: roll_result=(randint(the_lowest_possible_roll, the_number_of_sides_on_a_die)) print("reroll %s" %roll_result) else:set_of_dice_rolls.append(roll_result) print(set_of_dice_rolls) return #roll_set_of_dice() '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' #test_4_rolls if drop lowest or highest is greater than zero copy set_of_dice_rolls to set_of_dice_rolls_adjusted from random import randint the_number_of_rolls_in_a_set=4 the_number_of_sides_on_a_die=6 the_lowest_possible_roll=1 reroll_if_equal_or_less=0 number_of_lowest_rolls_to_drop_in_a_set=1 number_of_highest_rolls_to_drop_in_a_set=0 #rolls 4 dice between 1 and 6 and rerolls all results that are 5 or less then outputs them to roll_set_of_dice def roll_set_of_dice(): set_of_dice_rolls=[] set_of_dice_rolls_adjusted=[] for roll in range(the_number_of_rolls_in_a_set): roll_result=(randint(the_lowest_possible_roll, the_number_of_sides_on_a_die)) while roll_result<=reroll_if_equal_or_less: roll_result=(randint(the_lowest_possible_roll, the_number_of_sides_on_a_die)) print("reroll %s" %roll_result) else:set_of_dice_rolls.append(roll_result) if (number_of_lowest_rolls_to_drop_in_a_set>0) or (number_of_highest_rolls_to_drop_in_a_set>0): for roll_results in range(len(set_of_dice_rolls)): set_of_dice_rolls_adjusted.append(set_of_dice_rolls[roll_results]) print(set_of_dice_rolls_adjusted) print(set_of_dice_rolls) return #roll_set_of_dice() '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' #test_4_rolls drop highest and lowest from random import randint the_number_of_rolls_in_a_set=4 the_number_of_sides_on_a_die=6 the_lowest_possible_roll=1 reroll_if_equal_or_less=0 number_of_lowest_rolls_to_drop_in_a_set=1 number_of_highest_rolls_to_drop_in_a_set=1 #rolls 4 dice between 1 and 6 and rerolls all results that are 5 or less then outputs them to roll_set_of_dice def roll_set_of_dice(): set_of_dice_rolls=[] set_of_dice_rolls_adjusted=[] for roll in range(the_number_of_rolls_in_a_set): roll_result=(randint(the_lowest_possible_roll, the_number_of_sides_on_a_die)) while roll_result<=reroll_if_equal_or_less: roll_result=(randint(the_lowest_possible_roll, the_number_of_sides_on_a_die)) print("reroll %s" %roll_result) else:set_of_dice_rolls.append(roll_result) for roll_results in range(len(set_of_dice_rolls)): set_of_dice_rolls_adjusted.append(set_of_dice_rolls[roll_results]) print("\n////Break////\n%s\n%s\n////Break////\n" % (set_of_dice_rolls, set_of_dice_rolls_adjusted)) if (number_of_lowest_rolls_to_drop_in_a_set>0) or (number_of_highest_rolls_to_drop_in_a_set>0): if number_of_lowest_rolls_to_drop_in_a_set>0: drop_counter=0 drop_counter+=number_of_lowest_rolls_to_drop_in_a_set #print(set_of_dice_rolls_adjusted) #print(drop_counter) while drop_counter>0: set_of_dice_rolls_adjusted.remove(min(set_of_dice_rolls_adjusted)) #print(set_of_dice_rolls_adjusted) drop_counter-=1 #print(drop_counter) if number_of_highest_rolls_to_drop_in_a_set>0: drop_counter=0 drop_counter+=number_of_highest_rolls_to_drop_in_a_set #print(set_of_dice_rolls_adjusted) #print(drop_counter) while drop_counter>0: set_of_dice_rolls_adjusted.remove(max(set_of_dice_rolls_adjusted)) #print(set_of_dice_rolls_adjusted) drop_counter-=1 #print(drop_counter) print("\n////Break////\n%s\n%s\n////Break////\n" % (set_of_dice_rolls, set_of_dice_rolls_adjusted)) return roll_set_of_dice() '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' ''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
RZMC/dndCharGen
dice guideline.py
Python
mit
7,477
'use strict'; module.exports = { up: function(queryInterface, Sequelize) { return queryInterface.createTable('users', { id: { allowNull: false, autoIncrement: true, primaryKey: true, type: Sequelize.INTEGER }, name: { type: Sequelize.STRING }, username: { type: Sequelize.STRING, allowNull: false, unique: true }, password: { type: Sequelize.STRING, allowNull: false }, salt: { type: Sequelize.STRING, allowNull: false }, createdAt: { allowNull: false, type: Sequelize.DATE }, updatedAt: { allowNull: false, type: Sequelize.DATE } }); }, down: function(queryInterface, Sequelize) { return queryInterface.dropTable('users'); } };
geanjunior/cracha
migrations/20170127020036-create-user.js
JavaScript
mit
1,093
import { Routes, RouterModule } from '@angular/router'; import { Grupos } from './grupos.component'; import { Ckeditor } from './components/ckeditor/ckeditor.component'; // noinspection TypeScriptValidateTypes const routes: Routes = [ { path: '', component: Grupos, children: [ { path: 'ckeditor', component: Ckeditor } ] } ]; export const routing = RouterModule.forChild(routes);
Kmilo9433/arka-cliente-generador
src/app/pages/grupos/grupos.routing.ts
TypeScript
mit
411
#include "Chapter7.h" #include "Killable.h" bool IKillable::IsDead() { return false; } void IKillable::Die() { GEngine->AddOnScreenDebugMessage(-1,1, FColor::Red,"Arrrgh"); AActor* Me = Cast<AActor>(this); if (Me) { Me->Destroy(); } }
sunithshetty/Unreal-Engine-4-Scripting-with-CPlusPlus-Cookbook
Chapter07/Source/Chapter7/Killable.cpp
C++
mit
245
import lazy from "lazy.js"; import { EventEmitter } from "events"; import _ from "lodash"; import AppDispatcher from "../AppDispatcher"; import GameStatus from "../constants/GameStatus"; import CompsEvents from "../events/CompsEvents"; import GamesEvents from "../events/GamesEvents"; class GameStore { constructor() { this.info = { status: GameStatus.NOT_STARTED }; this.player = null; this.lastToken = null; this.states = []; } getInfo() { return this.info; } getPlayer() { return this.player; } getLastToken() { return this.lastToken; } getStatus() { return this.info.status; } getState(i) { return this.states[i]; } getCurrentState() { return this.states[this.states.length - 1]; } getAllStates() { return this.states; } getStateCount() { return this.states.length; } _setInfo(info) { this.info = info; } _setPlayer(player) { this.player = player; } _setLastToken(playerToken) { this.lastToken = playerToken; } _setStatus(status) { this.info.status = status; } _pushState(state) { this.states.push(state); } _setAllStates(states) { this.states = states; } } const GamesStore = lazy(EventEmitter.prototype).extend({ games: {}, getGame: function (gameHref, gameId) { let games = this.games[gameHref] = this.games[gameHref] || {}; return games[gameId] = games[gameId] || new GameStore(); }, getAllGames: function (gameHref) { let forHref = this.games[gameHref] = this.games[gameHref] || {}; return _.values(forHref); } }).value(); AppDispatcher.register(function (action) { const { actionType, gameHref, gameId, data, error } = action; let store = gameId ? GamesStore.getGame(gameHref, gameId) : null; switch (actionType) { case GamesEvents.GAME_INFO: store._setInfo(action.game); GamesStore.emit(actionType, gameHref, gameId); break; case GamesEvents.GAME_INFO_ERROR: GamesStore.emit(actionType, gameHref, gameId, error); break; case GamesEvents.GAMES_LIST: action.games.forEach(info => { GamesStore.getGame(gameHref, info.gameId)._setInfo(info); GamesStore.emit(GamesEvents.GAME_INFO, gameHref, info.gameId); }); GamesStore.emit(actionType, gameHref); break; case GamesEvents.GAMES_LIST_ERROR: GamesStore.emit(actionType, gameHref, error); break; case CompsEvents.COMP_GAMES: action.games.forEach(info => { GamesStore.getGame(gameHref, info.gameId)._setInfo(info); GamesStore.emit(GamesEvents.GAME_INFO, gameHref, info.gameId); }); break; case GamesEvents.REGISTER_SUCCESS: store._setLastToken(data.playerToken); GamesStore.emit(actionType, gameHref, gameId, data.playerToken); break; case GamesEvents.REGISTER_ERROR: GamesStore.emit(actionType, gameHref, gameId, error); break; case GamesEvents.INFO: store._setPlayer(data.player); GamesStore.emit(actionType, gameHref, gameId); break; case GamesEvents.HISTORY: store._setAllStates( lazy(data).filter(e => e.eventType === "state").map(e => e.state).value()); break; case GamesEvents.START: case GamesEvents.STATE: store._setStatus(GameStatus.STARTED); store._pushState(data); GamesStore.emit(GamesEvents.NEW_STATE, gameHref, gameId); break; case GamesEvents.END: store._setStatus(GameStatus.ENDED); store._pushState(data); GamesStore.emit(GamesEvents.NEW_STATE, gameHref, gameId); break; case GamesEvents.CONNECTION_OPENED: store._setLastToken(action.playerToken); store._setAllStates([]); GamesStore.emit(actionType, gameHref, gameId); break; case GamesEvents.CONNECTION_CLOSED: case GamesEvents.CONNECTION_ERROR: GamesStore.emit(actionType, gameHref, gameId); break; } }); export default GamesStore;
ruippeixotog/botwars
client/js/stores/GamesStore.js
JavaScript
mit
3,892
<?php namespace Cygnite\Base\EventHandler; use Cygnite\Helpers\Inflector; /** * Class EventRegistrarTrait * * @package Cygnite\Base\EventHandler */ trait EventRegistrarTrait { /** * @return $this */ public function boot() { $this->registerEvents($this->listen); return $this; } /** * Get user defined application events from event middle wares * * @return array|bool */ public function getAppEvents() { $class = APP_NS.'\Middlewares\Events\Event'; if (property_exists($class, 'appEvents') && $class::$activateAppEvent == true) { return \Apps\Middlewares\Events\Event::$appEvents; } return false; } /** * We will register user defined events, it will trigger event when matches * * @param $events * @throws \RuntimeException */ public function registerEvents($events) { if (empty($events)) { throw new \RuntimeException(sprintf("Empty argument passed %s", __FUNCTION__)); } foreach ($events as $event => $namespace) { $parts = explode('@', $namespace); // attach all before and after event to handler $this->attach("$event.before", $parts[0].'@before'.ucfirst(Inflector::pathAction(end($parts)))) ->attach("$event", $parts[0].'@'.Inflector::pathAction(end($parts))) ->attach("$event.after", $parts[0].'@after'.ucfirst(Inflector::pathAction(end($parts)))); } } /** * Fire all events registered with EventHandler * * @param $event * @return $this */ public function fire($event) { $this->trigger("$event.before"); $this->trigger($event); $this->trigger("$event.after"); return $this; } }
sanjoydesk/cygniteframework
vendor/cygnite/framework/src/Cygnite/Base/EventHandler/EventRegistrarTrait.php
PHP
mit
1,849
/* * @(#)ChoiceResource.java 1.3 97/06/27 * * (C) Copyright Taligent, Inc. 1996 - All Rights Reserved * (C) Copyright IBM Corp. 1996 - All Rights Reserved * * Portions copyright (c) 1996 Sun Microsystems, Inc. All Rights Reserved. * * The original version of this source code and documentation is copyrighted * and owned by Taligent, Inc., a wholly-owned subsidiary of IBM. These * materials are provided under terms of a License Agreement between Taligent * and Sun. This technology is protected by multiple US and International * patents. This notice and attribution to Taligent may not be removed. * Taligent is a registered trademark of Taligent, Inc. * * Permission to use, copy, modify, and distribute this software * and its documentation for NON-COMMERCIAL purposes and without * fee is hereby granted provided that this copyright notice * appears in all copies. Please refer to the file "copyright.html" * for further important copyright and licensing information. * * SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF * THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED * TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A * PARTICULAR PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES. * */ import java.util.ListResourceBundle; public class ChoiceResource extends ListResourceBundle { public Object[][] getContents() { return contents; } static final Object[][] contents = { // LOCALIZE THIS {"patternText", "The disk {1} contained \n" + " {0,choice, " + "0#no files|" + "1#one file|" + "1< {0,number,integer} files} \n" + " on {2,date}."} }; // END OF MATERIAL TO LOCALIZE };
pitpitman/GraduateWork
Java_tutorial/intl/datamgmt/demos-1dot1/ChoiceResource.java
Java
mit
1,916
Template.sort.helpers({ activeRouteClass: function(/* route names */) { // Man kann natürlich benannte Argumente an die Funktion übergeben, aber man kann auch eine beliebige Anzahl von anonymen Parametern mitgeben und abrufen indem man innerhalb der Funktion das Objekt arguments aufruft. var args = Array.prototype.slice.call(arguments, 0); args.pop(); // Im letzten Fall sollte man das Objekt arguments in ein herkömmliches JavaScript Array konvertieren und dann pop() darauf anwenden um den Hash loszuwerden, den Spacebars am Ende eingefügt hat. var active = _.any(args, function(name) { return Router.current() && Router.current().route.name === name }); return active && 'active'; // JavaScript Pattern boolean && string, bei dem false && myString false zurückgibt, aber true && myString gibt myString zurück } });
shiftux/discover_meteor
client/templates/includes/sort.js
JavaScript
mit
859
//ECS 60 Homework #2 //Christopher Bird //ID: 997337048 //Professor: Hao Chen //Kruskal's Implementation along with Sorting Algorithm //Main.cpp #include <string> #include <iostream> #include "spantree.h" using namespace std; int main() { spantree Spantree; Spantree.readInput(); //Spantree.testInput(); //Reads input and stores Spantree.sortInfo(); //Sorts each regions roads by length and creates ordered arrays with least -> most length pointers Spantree.buildTree(); //Builds each region using the lowest cost edges from each region Spantree.printOut(); //Prints each region in the output desired by Chen return 0; }
CKBird/Kruskals
Source/main.cpp
C++
mit
643
<?xml version="1.0" ?><!DOCTYPE TS><TS language="pt_PT" version="2.0"> <defaultcodec>UTF-8</defaultcodec> <context> <name>AboutDialog</name> <message> <location filename="../forms/aboutdialog.ui" line="+14"/> <source>About PioneerCoin</source> <translation>Sobre PioneerCoin</translation> </message> <message> <location line="+39"/> <source>&lt;b&gt;PioneerCoin&lt;/b&gt; version</source> <translation>Versão do &lt;b&gt;PioneerCoin&lt;/b&gt;</translation> </message> <message> <location line="+57"/> <source> This is experimental software. Distributed under the MIT/X11 software license, see the accompanying file COPYING or http://www.opensource.org/licenses/mit-license.php. This product includes software developed by the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/) and cryptographic software written by Eric Young (eay@cryptsoft.com) and UPnP software written by Thomas Bernard.</source> <translation> Este é um programa experimental. Distribuído sob uma licença de software MIT/X11, por favor verifique o ficheiro anexo license.txt ou http://www.opensource.org/licenses/mit-license.php. Este produto inclui software desenvolvido pelo Projecto OpenSSL para uso no OpenSSL Toolkit (http://www.openssl.org/), software criptográfico escrito por Eric Young (eay@cryptsoft.com) e software UPnP escrito por Thomas Bernard.</translation> </message> <message> <location filename="../aboutdialog.cpp" line="+14"/> <source>Copyright</source> <translation>Copyright</translation> </message> <message> <location line="+0"/> <source>The PioneerCoin developers</source> <translation>Os programadores PioneerCoin</translation> </message> </context> <context> <name>AddressBookPage</name> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>Address Book</source> <translation>Livro de endereços</translation> </message> <message> <location line="+19"/> <source>Double-click to edit address or label</source> <translation>Clique duas vezes para editar o endereço ou o rótulo</translation> </message> <message> <location line="+27"/> <source>Create a new address</source> <translation>Criar um novo endereço</translation> </message> <message> <location line="+14"/> <source>Copy the currently selected address to the system clipboard</source> <translation>Copie o endereço selecionado para a área de transferência</translation> </message> <message> <location line="-11"/> <source>&amp;New Address</source> <translation>&amp;Novo Endereço</translation> </message> <message> <location filename="../addressbookpage.cpp" line="+63"/> <source>These are your PioneerCoin addresses for receiving payments. You may want to give a different one to each sender so you can keep track of who is paying you.</source> <translation>Estes são os seus endereços PioneerCoin para receber pagamentos. Poderá enviar um endereço diferente para cada remetente para poder identificar os pagamentos.</translation> </message> <message> <location filename="../forms/addressbookpage.ui" line="+14"/> <source>&amp;Copy Address</source> <translation>&amp;Copiar Endereço</translation> </message> <message> <location line="+11"/> <source>Show &amp;QR Code</source> <translation>Mostrar Código &amp;QR</translation> </message> <message> <location line="+11"/> <source>Sign a message to prove you own a PioneerCoin address</source> <translation>Assine uma mensagem para provar que é dono de um endereço PioneerCoin</translation> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation>Assinar &amp;Mensagem</translation> </message> <message> <location line="+25"/> <source>Delete the currently selected address from the list</source> <translation>Apagar o endereço selecionado da lista</translation> </message> <message> <location line="+27"/> <source>Export the data in the current tab to a file</source> <translation>Exportar os dados no separador actual para um ficheiro</translation> </message> <message> <location line="+3"/> <source>&amp;Export</source> <translation>&amp;Exportar</translation> </message> <message> <location line="-44"/> <source>Verify a message to ensure it was signed with a specified PioneerCoin address</source> <translation>Verifique a mensagem para assegurar que foi assinada com o endereço PioneerCoin especificado</translation> </message> <message> <location line="+3"/> <source>&amp;Verify Message</source> <translation>&amp;Verificar Mensagem</translation> </message> <message> <location line="+14"/> <source>&amp;Delete</source> <translation>E&amp;liminar</translation> </message> <message> <location filename="../addressbookpage.cpp" line="-5"/> <source>These are your PioneerCoin addresses for sending payments. Always check the amount and the receiving address before sending coins.</source> <translation>Estes são os seus endereços PioneerCoin para enviar pagamentos. Verifique sempre o valor e a morada de envio antes de enviar moedas.</translation> </message> <message> <location line="+13"/> <source>Copy &amp;Label</source> <translation>Copiar &amp;Rótulo</translation> </message> <message> <location line="+1"/> <source>&amp;Edit</source> <translation>&amp;Editar</translation> </message> <message> <location line="+1"/> <source>Send &amp;Coins</source> <translation>Enviar &amp;Moedas</translation> </message> <message> <location line="+260"/> <source>Export Address Book Data</source> <translation>Exportar dados do Livro de Endereços</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Ficheiro separado por vírgulas (*.csv)</translation> </message> <message> <location line="+13"/> <source>Error exporting</source> <translation>Erro ao exportar</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>Não foi possível escrever para o ficheiro %1.</translation> </message> </context> <context> <name>AddressTableModel</name> <message> <location filename="../addresstablemodel.cpp" line="+144"/> <source>Label</source> <translation>Rótulo</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Endereço</translation> </message> <message> <location line="+36"/> <source>(no label)</source> <translation>(Sem rótulo)</translation> </message> </context> <context> <name>AskPassphraseDialog</name> <message> <location filename="../forms/askpassphrasedialog.ui" line="+26"/> <source>Passphrase Dialog</source> <translation>Diálogo de Frase-Passe</translation> </message> <message> <location line="+21"/> <source>Enter passphrase</source> <translation>Escreva a frase de segurança</translation> </message> <message> <location line="+14"/> <source>New passphrase</source> <translation>Nova frase de segurança</translation> </message> <message> <location line="+14"/> <source>Repeat new passphrase</source> <translation>Repita a nova frase de segurança</translation> </message> <message> <location filename="../askpassphrasedialog.cpp" line="+33"/> <source>Enter the new passphrase to the wallet.&lt;br/&gt;Please use a passphrase of &lt;b&gt;10 or more random characters&lt;/b&gt;, or &lt;b&gt;eight or more words&lt;/b&gt;.</source> <translation>Escreva a nova frase de seguraça da sua carteira. &lt;br/&gt; Por favor, use uma frase de &lt;b&gt;10 ou mais caracteres aleatórios,&lt;/b&gt; ou &lt;b&gt;oito ou mais palavras&lt;/b&gt;.</translation> </message> <message> <location line="+1"/> <source>Encrypt wallet</source> <translation>Encriptar carteira</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to unlock the wallet.</source> <translation>A sua frase de segurança é necessária para desbloquear a carteira.</translation> </message> <message> <location line="+5"/> <source>Unlock wallet</source> <translation>Desbloquear carteira</translation> </message> <message> <location line="+3"/> <source>This operation needs your wallet passphrase to decrypt the wallet.</source> <translation>A sua frase de segurança é necessária para desencriptar a carteira.</translation> </message> <message> <location line="+5"/> <source>Decrypt wallet</source> <translation>Desencriptar carteira</translation> </message> <message> <location line="+3"/> <source>Change passphrase</source> <translation>Alterar frase de segurança</translation> </message> <message> <location line="+1"/> <source>Enter the old and new passphrase to the wallet.</source> <translation>Escreva a frase de segurança antiga seguida da nova para a carteira.</translation> </message> <message> <location line="+46"/> <source>Confirm wallet encryption</source> <translation>Confirmar encriptação da carteira</translation> </message> <message> <location line="+1"/> <source>Warning: If you encrypt your wallet and lose your passphrase, you will &lt;b&gt;LOSE ALL OF YOUR DARKCOINS&lt;/b&gt;!</source> <translation>Atenção: Se encriptar a carteira e perder a sua senha irá &lt;b&gt;PERDER TODOS OS SEUS DARKCOINS&lt;/b&gt;!</translation> </message> <message> <location line="+0"/> <source>Are you sure you wish to encrypt your wallet?</source> <translation>Tem a certeza que deseja encriptar a carteira?</translation> </message> <message> <location line="+15"/> <source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source> <translation>IMPORTANTE: Qualquer cópia de segurança anterior da carteira deverá ser substituída com o novo, actualmente encriptado, ficheiro de carteira. Por razões de segurança, cópias de segurança não encriptadas efectuadas anteriormente do ficheiro da carteira tornar-se-ão inúteis assim que começar a usar a nova carteira encriptada.</translation> </message> <message> <location line="+100"/> <location line="+24"/> <source>Warning: The Caps Lock key is on!</source> <translation>Atenção: A tecla Caps Lock está activa!</translation> </message> <message> <location line="-130"/> <location line="+58"/> <source>Wallet encrypted</source> <translation>Carteira encriptada</translation> </message> <message> <location line="-56"/> <source>PioneerCoin will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your PioneerCoins from being stolen by malware infecting your computer.</source> <translation>O cliente PioneerCoin irá agora ser fechado para terminar o processo de encriptação. Recorde que a encriptação da sua carteira não protegerá totalmente os seus PioneerCoins de serem roubados por programas maliciosos que infectem o seu computador.</translation> </message> <message> <location line="+13"/> <location line="+7"/> <location line="+42"/> <location line="+6"/> <source>Wallet encryption failed</source> <translation>A encriptação da carteira falhou</translation> </message> <message> <location line="-54"/> <source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source> <translation>A encriptação da carteira falhou devido a um erro interno. A carteira não foi encriptada.</translation> </message> <message> <location line="+7"/> <location line="+48"/> <source>The supplied passphrases do not match.</source> <translation>As frases de segurança fornecidas não coincidem.</translation> </message> <message> <location line="-37"/> <source>Wallet unlock failed</source> <translation>O desbloqueio da carteira falhou</translation> </message> <message> <location line="+1"/> <location line="+11"/> <location line="+19"/> <source>The passphrase entered for the wallet decryption was incorrect.</source> <translation>A frase de segurança introduzida para a desencriptação da carteira estava incorreta.</translation> </message> <message> <location line="-20"/> <source>Wallet decryption failed</source> <translation>A desencriptação da carteira falhou</translation> </message> <message> <location line="+14"/> <source>Wallet passphrase was successfully changed.</source> <translation>A frase de segurança da carteira foi alterada com êxito.</translation> </message> </context> <context> <name>BitcoinGUI</name> <message> <location filename="../bitcoingui.cpp" line="+233"/> <source>Sign &amp;message...</source> <translation>Assinar &amp;mensagem...</translation> </message> <message> <location line="+280"/> <source>Synchronizing with network...</source> <translation>Sincronizando com a rede...</translation> </message> <message> <location line="-349"/> <source>&amp;Overview</source> <translation>Visã&amp;o geral</translation> </message> <message> <location line="+1"/> <source>Show general overview of wallet</source> <translation>Mostrar visão geral da carteira</translation> </message> <message> <location line="+20"/> <source>&amp;Transactions</source> <translation>&amp;Transações</translation> </message> <message> <location line="+1"/> <source>Browse transaction history</source> <translation>Navegar pelo histórico de transações</translation> </message> <message> <location line="+7"/> <source>Edit the list of stored addresses and labels</source> <translation>Editar a lista de endereços e rótulos</translation> </message> <message> <location line="-14"/> <source>Show the list of addresses for receiving payments</source> <translation>Mostrar a lista de endereços para receber pagamentos</translation> </message> <message> <location line="+31"/> <source>E&amp;xit</source> <translation>Fec&amp;har</translation> </message> <message> <location line="+1"/> <source>Quit application</source> <translation>Sair da aplicação</translation> </message> <message> <location line="+4"/> <source>Show information about PioneerCoin</source> <translation>Mostrar informação sobre PioneerCoin</translation> </message> <message> <location line="+2"/> <source>About &amp;Qt</source> <translation>Sobre &amp;Qt</translation> </message> <message> <location line="+1"/> <source>Show information about Qt</source> <translation>Mostrar informação sobre Qt</translation> </message> <message> <location line="+2"/> <source>&amp;Options...</source> <translation>&amp;Opções...</translation> </message> <message> <location line="+6"/> <source>&amp;Encrypt Wallet...</source> <translation>E&amp;ncriptar Carteira...</translation> </message> <message> <location line="+3"/> <source>&amp;Backup Wallet...</source> <translation>&amp;Guardar Carteira...</translation> </message> <message> <location line="+2"/> <source>&amp;Change Passphrase...</source> <translation>Mudar &amp;Palavra-passe...</translation> </message> <message> <location line="+285"/> <source>Importing blocks from disk...</source> <translation>Importando blocos do disco...</translation> </message> <message> <location line="+3"/> <source>Reindexing blocks on disk...</source> <translation>Reindexando blocos no disco...</translation> </message> <message> <location line="-347"/> <source>Send coins to a PioneerCoin address</source> <translation>Enviar moedas para um endereço PioneerCoin</translation> </message> <message> <location line="+49"/> <source>Modify configuration options for PioneerCoin</source> <translation>Modificar opções de configuração para PioneerCoin</translation> </message> <message> <location line="+9"/> <source>Backup wallet to another location</source> <translation>Faça uma cópia de segurança da carteira para outra localização</translation> </message> <message> <location line="+2"/> <source>Change the passphrase used for wallet encryption</source> <translation>Mudar a frase de segurança utilizada na encriptação da carteira</translation> </message> <message> <location line="+6"/> <source>&amp;Debug window</source> <translation>Janela de &amp;depuração</translation> </message> <message> <location line="+1"/> <source>Open debugging and diagnostic console</source> <translation>Abrir consola de diagnóstico e depuração</translation> </message> <message> <location line="-4"/> <source>&amp;Verify message...</source> <translation>&amp;Verificar mensagem...</translation> </message> <message> <location line="-165"/> <location line="+530"/> <source>PioneerCoin</source> <translation>PioneerCoin</translation> </message> <message> <location line="-530"/> <source>Wallet</source> <translation>Carteira</translation> </message> <message> <location line="+101"/> <source>&amp;Send</source> <translation>&amp;Enviar</translation> </message> <message> <location line="+7"/> <source>&amp;Receive</source> <translation>&amp;Receber</translation> </message> <message> <location line="+14"/> <source>&amp;Addresses</source> <translation>E&amp;ndereços</translation> </message> <message> <location line="+22"/> <source>&amp;About PioneerCoin</source> <translation>&amp;Sobre o PioneerCoin</translation> </message> <message> <location line="+9"/> <source>&amp;Show / Hide</source> <translation>Mo&amp;strar / Ocultar</translation> </message> <message> <location line="+1"/> <source>Show or hide the main Window</source> <translation>Mostrar ou esconder a Janela principal</translation> </message> <message> <location line="+3"/> <source>Encrypt the private keys that belong to your wallet</source> <translation>Encriptar as chaves privadas que pertencem à sua carteira</translation> </message> <message> <location line="+7"/> <source>Sign messages with your PioneerCoin addresses to prove you own them</source> <translation>Assine mensagens com os seus endereços PioneerCoin para provar que os controla</translation> </message> <message> <location line="+2"/> <source>Verify messages to ensure they were signed with specified PioneerCoin addresses</source> <translation>Verifique mensagens para assegurar que foram assinadas com o endereço PioneerCoin especificado</translation> </message> <message> <location line="+28"/> <source>&amp;File</source> <translation>&amp;Ficheiro</translation> </message> <message> <location line="+7"/> <source>&amp;Settings</source> <translation>Con&amp;figurações</translation> </message> <message> <location line="+6"/> <source>&amp;Help</source> <translation>A&amp;juda</translation> </message> <message> <location line="+9"/> <source>Tabs toolbar</source> <translation>Barra de separadores</translation> </message> <message> <location line="+17"/> <location line="+10"/> <source>[testnet]</source> <translation>[rede de testes]</translation> </message> <message> <location line="+47"/> <source>PioneerCoin client</source> <translation>Cliente PioneerCoin</translation> </message> <message numerus="yes"> <location line="+141"/> <source>%n active connection(s) to PioneerCoin network</source> <translation><numerusform>%n ligação ativa à rede PioneerCoin</numerusform><numerusform>%n ligações ativas à rede PioneerCoin</numerusform></translation> </message> <message> <location line="+22"/> <source>No block source available...</source> <translation>Nenhum bloco fonto disponível</translation> </message> <message> <location line="+12"/> <source>Processed %1 of %2 (estimated) blocks of transaction history.</source> <translation>Processados %1 dos %2 blocos (estimados) do histórico de transacções.</translation> </message> <message> <location line="+4"/> <source>Processed %1 blocks of transaction history.</source> <translation>Processados %1 blocos do histórico de transações.</translation> </message> <message numerus="yes"> <location line="+20"/> <source>%n hour(s)</source> <translation><numerusform>%n hora</numerusform><numerusform>%n horas</numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n day(s)</source> <translation><numerusform>%n dia</numerusform><numerusform>%n dias</numerusform></translation> </message> <message numerus="yes"> <location line="+4"/> <source>%n week(s)</source> <translation><numerusform>%n semana</numerusform><numerusform>%n semanas</numerusform></translation> </message> <message> <location line="+4"/> <source>%1 behind</source> <translation>%1 em atraso</translation> </message> <message> <location line="+14"/> <source>Last received block was generated %1 ago.</source> <translation>Último bloco recebido foi gerado há %1 atrás.</translation> </message> <message> <location line="+2"/> <source>Transactions after this will not yet be visible.</source> <translation>Transações posteriores poderão não ser imediatamente visíveis.</translation> </message> <message> <location line="+22"/> <source>Error</source> <translation>Erro</translation> </message> <message> <location line="+3"/> <source>Warning</source> <translation>Aviso</translation> </message> <message> <location line="+3"/> <source>Information</source> <translation>Informação</translation> </message> <message> <location line="+70"/> <source>This transaction is over the size limit. You can still send it for a fee of %1, which goes to the nodes that process your transaction and helps to support the network. Do you want to pay the fee?</source> <translation>Esta transação tem um tamanho superior ao limite máximo. Poderá enviá-la pagando uma taxa de %1, que será entregue ao nó que processar a sua transação e ajudará a suportar a rede. Deseja pagar a taxa?</translation> </message> <message> <location line="-140"/> <source>Up to date</source> <translation>Atualizado</translation> </message> <message> <location line="+31"/> <source>Catching up...</source> <translation>Recuperando...</translation> </message> <message> <location line="+113"/> <source>Confirm transaction fee</source> <translation>Confirme a taxa de transação</translation> </message> <message> <location line="+8"/> <source>Sent transaction</source> <translation>Transação enviada</translation> </message> <message> <location line="+0"/> <source>Incoming transaction</source> <translation>Transação recebida</translation> </message> <message> <location line="+1"/> <source>Date: %1 Amount: %2 Type: %3 Address: %4 </source> <translation>Data: %1 Quantia: %2 Tipo: %3 Endereço: %4 </translation> </message> <message> <location line="+33"/> <location line="+23"/> <source>URI handling</source> <translation>Manuseamento URI</translation> </message> <message> <location line="-23"/> <location line="+23"/> <source>URI can not be parsed! This can be caused by an invalid PioneerCoin address or malformed URI parameters.</source> <translation>URI não foi lido correctamente! Isto pode ser causado por um endereço PioneerCoin inválido ou por parâmetros URI malformados.</translation> </message> <message> <location line="+17"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;unlocked&lt;/b&gt;</source> <translation>A carteira está &lt;b&gt;encriptada&lt;/b&gt; e atualmente &lt;b&gt;desbloqueada&lt;/b&gt;</translation> </message> <message> <location line="+8"/> <source>Wallet is &lt;b&gt;encrypted&lt;/b&gt; and currently &lt;b&gt;locked&lt;/b&gt;</source> <translation>A carteira está &lt;b&gt;encriptada&lt;/b&gt; e atualmente &lt;b&gt;bloqueada&lt;/b&gt;</translation> </message> <message> <location filename="../bitcoin.cpp" line="+111"/> <source>A fatal error occurred. PioneerCoin can no longer continue safely and will quit.</source> <translation>Ocorreu um erro fatal. O PioneerCoin não pode continuar com segurança e irá fechar.</translation> </message> </context> <context> <name>ClientModel</name> <message> <location filename="../clientmodel.cpp" line="+104"/> <source>Network Alert</source> <translation>Alerta da Rede</translation> </message> </context> <context> <name>EditAddressDialog</name> <message> <location filename="../forms/editaddressdialog.ui" line="+14"/> <source>Edit Address</source> <translation>Editar Endereço</translation> </message> <message> <location line="+11"/> <source>&amp;Label</source> <translation>&amp;Rótulo</translation> </message> <message> <location line="+10"/> <source>The label associated with this address book entry</source> <translation>O rótulo a ser associado com esta entrada do livro de endereços</translation> </message> <message> <location line="+7"/> <source>&amp;Address</source> <translation>E&amp;ndereço</translation> </message> <message> <location line="+10"/> <source>The address associated with this address book entry. This can only be modified for sending addresses.</source> <translation>O endereço associado com esta entrada do livro de endereços. Apenas poderá ser modificado para endereços de saída.</translation> </message> <message> <location filename="../editaddressdialog.cpp" line="+21"/> <source>New receiving address</source> <translation>Novo endereço de entrada</translation> </message> <message> <location line="+4"/> <source>New sending address</source> <translation>Novo endereço de saída</translation> </message> <message> <location line="+3"/> <source>Edit receiving address</source> <translation>Editar endereço de entrada</translation> </message> <message> <location line="+4"/> <source>Edit sending address</source> <translation>Editar endereço de saída</translation> </message> <message> <location line="+76"/> <source>The entered address &quot;%1&quot; is already in the address book.</source> <translation>O endereço introduzido &quot;%1&quot; já se encontra no livro de endereços.</translation> </message> <message> <location line="-5"/> <source>The entered address &quot;%1&quot; is not a valid PioneerCoin address.</source> <translation>O endereço introduzido &quot;%1&quot; não é um endereço PioneerCoin válido.</translation> </message> <message> <location line="+10"/> <source>Could not unlock wallet.</source> <translation>Impossível desbloquear carteira.</translation> </message> <message> <location line="+5"/> <source>New key generation failed.</source> <translation>Falha ao gerar nova chave.</translation> </message> </context> <context> <name>GUIUtil::HelpMessageBox</name> <message> <location filename="../guiutil.cpp" line="+424"/> <location line="+12"/> <source>PioneerCoin-Qt</source> <translation>PioneerCoin-Qt</translation> </message> <message> <location line="-12"/> <source>version</source> <translation>versão</translation> </message> <message> <location line="+2"/> <source>Usage:</source> <translation>Utilização:</translation> </message> <message> <location line="+1"/> <source>command-line options</source> <translation>opções da linha de comandos</translation> </message> <message> <location line="+4"/> <source>UI options</source> <translation>Opções de UI</translation> </message> <message> <location line="+1"/> <source>Set language, for example &quot;de_DE&quot; (default: system locale)</source> <translation>Definir linguagem, por exemplo &quot;pt_PT&quot; (por defeito: linguagem do sistema)</translation> </message> <message> <location line="+1"/> <source>Start minimized</source> <translation>Iniciar minimizado</translation> </message> <message> <location line="+1"/> <source>Show splash screen on startup (default: 1)</source> <translation>Mostrar animação ao iniciar (por defeito: 1)</translation> </message> </context> <context> <name>OptionsDialog</name> <message> <location filename="../forms/optionsdialog.ui" line="+14"/> <source>Options</source> <translation>Opções</translation> </message> <message> <location line="+16"/> <source>&amp;Main</source> <translation>&amp;Principal</translation> </message> <message> <location line="+6"/> <source>Optional transaction fee per kB that helps make sure your transactions are processed quickly. Most transactions are 1 kB.</source> <translation>Taxa de transação opcional por KB que ajuda a assegurar que as suas transações serão processadas rapidamente. A maioria das transações tem 1 kB.</translation> </message> <message> <location line="+15"/> <source>Pay transaction &amp;fee</source> <translation>Pagar &amp;taxa de transação</translation> </message> <message> <location line="+31"/> <source>Automatically start PioneerCoin after logging in to the system.</source> <translation>Começar o PioneerCoin automaticamente ao iniciar sessão no sistema.</translation> </message> <message> <location line="+3"/> <source>&amp;Start PioneerCoin on system login</source> <translation>&amp;Começar o PioneerCoin ao iniciar o sistema</translation> </message> <message> <location line="+35"/> <source>Reset all client options to default.</source> <translation>Repôr todas as opções.</translation> </message> <message> <location line="+3"/> <source>&amp;Reset Options</source> <translation>&amp;Repôr Opções</translation> </message> <message> <location line="+13"/> <source>&amp;Network</source> <translation>&amp;Rede</translation> </message> <message> <location line="+6"/> <source>Automatically open the PioneerCoin client port on the router. This only works when your router supports UPnP and it is enabled.</source> <translation>Abrir a porta do cliente PioneerCoin automaticamente no seu router. Isto penas funciona se o seu router suportar UPnP e este se encontrar ligado.</translation> </message> <message> <location line="+3"/> <source>Map port using &amp;UPnP</source> <translation>Mapear porta usando &amp;UPnP</translation> </message> <message> <location line="+7"/> <source>Connect to the PioneerCoin network through a SOCKS proxy (e.g. when connecting through Tor).</source> <translation>Ligar à rede PioneerCoin através de um proxy SOCKS (p.ex. quando ligar através de Tor).</translation> </message> <message> <location line="+3"/> <source>&amp;Connect through SOCKS proxy:</source> <translation>Ligar através de proxy SO&amp;CKS:</translation> </message> <message> <location line="+9"/> <source>Proxy &amp;IP:</source> <translation>&amp;IP do proxy:</translation> </message> <message> <location line="+19"/> <source>IP address of the proxy (e.g. 127.0.0.1)</source> <translation>Endereço IP do proxy (p.ex. 127.0.0.1)</translation> </message> <message> <location line="+7"/> <source>&amp;Port:</source> <translation>&amp;Porta:</translation> </message> <message> <location line="+19"/> <source>Port of the proxy (e.g. 9050)</source> <translation>Porta do proxy (p.ex. 9050)</translation> </message> <message> <location line="+7"/> <source>SOCKS &amp;Version:</source> <translation>&amp;Versão SOCKS:</translation> </message> <message> <location line="+13"/> <source>SOCKS version of the proxy (e.g. 5)</source> <translation>Versão do proxy SOCKS (p.ex. 5)</translation> </message> <message> <location line="+36"/> <source>&amp;Window</source> <translation>&amp;Janela</translation> </message> <message> <location line="+6"/> <source>Show only a tray icon after minimizing the window.</source> <translation>Apenas mostrar o ícone da bandeja após minimizar a janela.</translation> </message> <message> <location line="+3"/> <source>&amp;Minimize to the tray instead of the taskbar</source> <translation>&amp;Minimizar para a bandeja e não para a barra de ferramentas</translation> </message> <message> <location line="+7"/> <source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source> <translation>Minimize ao invés de sair da aplicação quando a janela é fechada. Com esta opção selecionada, a aplicação apenas será encerrada quando escolher Sair da aplicação no menú.</translation> </message> <message> <location line="+3"/> <source>M&amp;inimize on close</source> <translation>M&amp;inimizar ao fechar</translation> </message> <message> <location line="+21"/> <source>&amp;Display</source> <translation>Vis&amp;ualização</translation> </message> <message> <location line="+8"/> <source>User Interface &amp;language:</source> <translation>&amp;Linguagem da interface de utilizador:</translation> </message> <message> <location line="+13"/> <source>The user interface language can be set here. This setting will take effect after restarting PioneerCoin.</source> <translation>A linguagem da interface do utilizador pode ser definida aqui. Esta definição entrará em efeito após reiniciar o PioneerCoin.</translation> </message> <message> <location line="+11"/> <source>&amp;Unit to show amounts in:</source> <translation>&amp;Unidade a usar em quantias:</translation> </message> <message> <location line="+13"/> <source>Choose the default subdivision unit to show in the interface and when sending coins.</source> <translation>Escolha a subdivisão unitária a ser mostrada por defeito na aplicação e ao enviar moedas.</translation> </message> <message> <location line="+9"/> <source>Whether to show PioneerCoin addresses in the transaction list or not.</source> <translation>Se mostrar, ou não, os endereços PioneerCoin na lista de transações.</translation> </message> <message> <location line="+3"/> <source>&amp;Display addresses in transaction list</source> <translation>Mostrar en&amp;dereços na lista de transações</translation> </message> <message> <location line="+71"/> <source>&amp;OK</source> <translation>&amp;OK</translation> </message> <message> <location line="+7"/> <source>&amp;Cancel</source> <translation>&amp;Cancelar</translation> </message> <message> <location line="+10"/> <source>&amp;Apply</source> <translation>&amp;Aplicar</translation> </message> <message> <location filename="../optionsdialog.cpp" line="+53"/> <source>default</source> <translation>padrão</translation> </message> <message> <location line="+130"/> <source>Confirm options reset</source> <translation>Confirme a reposição de opções</translation> </message> <message> <location line="+1"/> <source>Some settings may require a client restart to take effect.</source> <translation>Algumas opções requerem o reinício do programa para funcionar.</translation> </message> <message> <location line="+0"/> <source>Do you want to proceed?</source> <translation>Deseja proceder?</translation> </message> <message> <location line="+42"/> <location line="+9"/> <source>Warning</source> <translation>Aviso</translation> </message> <message> <location line="-9"/> <location line="+9"/> <source>This setting will take effect after restarting PioneerCoin.</source> <translation>Esta opção entrará em efeito após reiniciar o PioneerCoin.</translation> </message> <message> <location line="+29"/> <source>The supplied proxy address is invalid.</source> <translation>O endereço de proxy introduzido é inválido. </translation> </message> </context> <context> <name>OverviewPage</name> <message> <location filename="../forms/overviewpage.ui" line="+14"/> <source>Form</source> <translation>Formulário</translation> </message> <message> <location line="+50"/> <location line="+166"/> <source>The displayed information may be out of date. Your wallet automatically synchronizes with the PioneerCoin network after a connection is established, but this process has not completed yet.</source> <translation>A informação mostrada poderá estar desatualizada. A sua carteira sincroniza automaticamente com a rede PioneerCoin depois de estabelecer ligação, mas este processo ainda não está completo.</translation> </message> <message> <location line="-124"/> <source>Balance:</source> <translation>Saldo:</translation> </message> <message> <location line="+29"/> <source>Unconfirmed:</source> <translation>Não confirmado:</translation> </message> <message> <location line="-78"/> <source>Wallet</source> <translation>Carteira</translation> </message> <message> <location line="+107"/> <source>Immature:</source> <translation>Imaturo:</translation> </message> <message> <location line="+13"/> <source>Mined balance that has not yet matured</source> <translation>O saldo minado ainda não maturou</translation> </message> <message> <location line="+46"/> <source>&lt;b&gt;Recent transactions&lt;/b&gt;</source> <translation>&lt;b&gt;Transações recentes&lt;/b&gt;</translation> </message> <message> <location line="-101"/> <source>Your current balance</source> <translation>O seu saldo atual</translation> </message> <message> <location line="+29"/> <source>Total of transactions that have yet to be confirmed, and do not yet count toward the current balance</source> <translation>Total de transações ainda não confirmadas, e que não estão contabilizadas ainda no seu saldo actual</translation> </message> <message> <location filename="../overviewpage.cpp" line="+116"/> <location line="+1"/> <source>out of sync</source> <translation>fora de sincronia</translation> </message> </context> <context> <name>PaymentServer</name> <message> <location filename="../paymentserver.cpp" line="+107"/> <source>Cannot start PioneerCoin: click-to-pay handler</source> <translation>Impossível começar o modo clicar-para-pagar com PioneerCoin:</translation> </message> </context> <context> <name>QRCodeDialog</name> <message> <location filename="../forms/qrcodedialog.ui" line="+14"/> <source>QR Code Dialog</source> <translation>Diálogo de Código QR</translation> </message> <message> <location line="+59"/> <source>Request Payment</source> <translation>Requisitar Pagamento</translation> </message> <message> <location line="+56"/> <source>Amount:</source> <translation>Quantia:</translation> </message> <message> <location line="-44"/> <source>Label:</source> <translation>Rótulo:</translation> </message> <message> <location line="+19"/> <source>Message:</source> <translation>Mensagem:</translation> </message> <message> <location line="+71"/> <source>&amp;Save As...</source> <translation>&amp;Salvar Como...</translation> </message> <message> <location filename="../qrcodedialog.cpp" line="+62"/> <source>Error encoding URI into QR Code.</source> <translation>Erro ao codificar URI em Código QR.</translation> </message> <message> <location line="+40"/> <source>The entered amount is invalid, please check.</source> <translation>A quantia introduzida é inválida, por favor verifique.</translation> </message> <message> <location line="+23"/> <source>Resulting URI too long, try to reduce the text for label / message.</source> <translation>URI resultante muito longo. Tente reduzir o texto do rótulo / mensagem.</translation> </message> <message> <location line="+25"/> <source>Save QR Code</source> <translation>Guardar Código QR</translation> </message> <message> <location line="+0"/> <source>PNG Images (*.png)</source> <translation>Imagens PNG (*.png)</translation> </message> </context> <context> <name>RPCConsole</name> <message> <location filename="../forms/rpcconsole.ui" line="+46"/> <source>Client name</source> <translation>Nome do Cliente</translation> </message> <message> <location line="+10"/> <location line="+23"/> <location line="+26"/> <location line="+23"/> <location line="+23"/> <location line="+36"/> <location line="+53"/> <location line="+23"/> <location line="+23"/> <location filename="../rpcconsole.cpp" line="+339"/> <source>N/A</source> <translation>N/D</translation> </message> <message> <location line="-217"/> <source>Client version</source> <translation>Versão do Cliente</translation> </message> <message> <location line="-45"/> <source>&amp;Information</source> <translation>&amp;Informação</translation> </message> <message> <location line="+68"/> <source>Using OpenSSL version</source> <translation>Usando versão OpenSSL</translation> </message> <message> <location line="+49"/> <source>Startup time</source> <translation>Tempo de início</translation> </message> <message> <location line="+29"/> <source>Network</source> <translation>Rede</translation> </message> <message> <location line="+7"/> <source>Number of connections</source> <translation>Número de ligações</translation> </message> <message> <location line="+23"/> <source>On testnet</source> <translation>Em rede de testes</translation> </message> <message> <location line="+23"/> <source>Block chain</source> <translation>Cadeia de blocos</translation> </message> <message> <location line="+7"/> <source>Current number of blocks</source> <translation>Número actual de blocos</translation> </message> <message> <location line="+23"/> <source>Estimated total blocks</source> <translation>Total estimado de blocos</translation> </message> <message> <location line="+23"/> <source>Last block time</source> <translation>Tempo do último bloco</translation> </message> <message> <location line="+52"/> <source>&amp;Open</source> <translation>&amp;Abrir</translation> </message> <message> <location line="+16"/> <source>Command-line options</source> <translation>Opções de linha de comandos</translation> </message> <message> <location line="+7"/> <source>Show the PioneerCoin-Qt help message to get a list with possible PioneerCoin command-line options.</source> <translation>Mostrar a mensagem de ajuda do PioneerCoin-Qt para obter uma lista com possíveis opções a usar na linha de comandos.</translation> </message> <message> <location line="+3"/> <source>&amp;Show</source> <translation>Mo&amp;strar</translation> </message> <message> <location line="+24"/> <source>&amp;Console</source> <translation>&amp;Consola</translation> </message> <message> <location line="-260"/> <source>Build date</source> <translation>Data de construção</translation> </message> <message> <location line="-104"/> <source>PioneerCoin - Debug window</source> <translation>PioneerCoin - Janela de depuração</translation> </message> <message> <location line="+25"/> <source>PioneerCoin Core</source> <translation>Núcleo PioneerCoin</translation> </message> <message> <location line="+279"/> <source>Debug log file</source> <translation>Ficheiro de registo de depuração</translation> </message> <message> <location line="+7"/> <source>Open the PioneerCoin debug log file from the current data directory. This can take a few seconds for large log files.</source> <translation>Abrir o ficheiro de registo de depuração da pasta de dados actual. Isto pode demorar alguns segundos para ficheiros de registo maiores.</translation> </message> <message> <location line="+102"/> <source>Clear console</source> <translation>Limpar consola</translation> </message> <message> <location filename="../rpcconsole.cpp" line="-30"/> <source>Welcome to the PioneerCoin RPC console.</source> <translation>Bem-vindo à consola RPC PioneerCoin.</translation> </message> <message> <location line="+1"/> <source>Use up and down arrows to navigate history, and &lt;b&gt;Ctrl-L&lt;/b&gt; to clear screen.</source> <translation>Use as setas para cima e para baixo para navegar no histórico e &lt;b&gt;Ctrl-L&lt;/b&gt; para limpar o ecrã.</translation> </message> <message> <location line="+1"/> <source>Type &lt;b&gt;help&lt;/b&gt; for an overview of available commands.</source> <translation>Digite &lt;b&gt;help&lt;/b&gt; para visualizar os comandos disponíveis.</translation> </message> </context> <context> <name>SendCoinsDialog</name> <message> <location filename="../forms/sendcoinsdialog.ui" line="+14"/> <location filename="../sendcoinsdialog.cpp" line="+124"/> <location line="+5"/> <location line="+5"/> <location line="+5"/> <location line="+6"/> <location line="+5"/> <location line="+5"/> <source>Send Coins</source> <translation>Enviar Moedas</translation> </message> <message> <location line="+50"/> <source>Send to multiple recipients at once</source> <translation>Enviar para múltiplos destinatários de uma vez</translation> </message> <message> <location line="+3"/> <source>Add &amp;Recipient</source> <translation>Adicionar &amp;Destinatário</translation> </message> <message> <location line="+20"/> <source>Remove all transaction fields</source> <translation>Remover todos os campos da transação</translation> </message> <message> <location line="+3"/> <source>Clear &amp;All</source> <translation>&amp;Limpar Tudo</translation> </message> <message> <location line="+22"/> <source>Balance:</source> <translation>Saldo:</translation> </message> <message> <location line="+10"/> <source>123.456 BTC</source> <translation>123.456 BTC</translation> </message> <message> <location line="+31"/> <source>Confirm the send action</source> <translation>Confirme ação de envio</translation> </message> <message> <location line="+3"/> <source>S&amp;end</source> <translation>&amp;Enviar</translation> </message> <message> <location filename="../sendcoinsdialog.cpp" line="-59"/> <source>&lt;b&gt;%1&lt;/b&gt; to %2 (%3)</source> <translation>&lt;b&gt;%1&lt;/b&gt; para %2 (%3)</translation> </message> <message> <location line="+5"/> <source>Confirm send coins</source> <translation>Confirme envio de moedas</translation> </message> <message> <location line="+1"/> <source>Are you sure you want to send %1?</source> <translation>Tem a certeza que deseja enviar %1?</translation> </message> <message> <location line="+0"/> <source> and </source> <translation> e </translation> </message> <message> <location line="+23"/> <source>The recipient address is not valid, please recheck.</source> <translation>O endereço de destino não é válido, por favor verifique.</translation> </message> <message> <location line="+5"/> <source>The amount to pay must be larger than 0.</source> <translation>A quantia a pagar deverá ser maior que 0.</translation> </message> <message> <location line="+5"/> <source>The amount exceeds your balance.</source> <translation>A quantia excede o seu saldo.</translation> </message> <message> <location line="+5"/> <source>The total exceeds your balance when the %1 transaction fee is included.</source> <translation>O total excede o seu saldo quando a taxa de transação de %1 for incluída.</translation> </message> <message> <location line="+6"/> <source>Duplicate address found, can only send to each address once per send operation.</source> <translation>Endereço duplicado encontrado, apenas poderá enviar uma vez para cada endereço por cada operação de envio.</translation> </message> <message> <location line="+5"/> <source>Error: Transaction creation failed!</source> <translation>Erro: A criação da transacção falhou! </translation> </message> <message> <location line="+5"/> <source>Error: The transaction was rejected. This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation>Erro: A transação foi rejeitada. Isso poderá acontecer se algumas das moedas na sua carteira já tiverem sido gastas, se por exemplo tiver usado uma cópia do ficheiro wallet.dat e as moedas foram gastas na cópia mas não foram marcadas como gastas aqui.</translation> </message> </context> <context> <name>SendCoinsEntry</name> <message> <location filename="../forms/sendcoinsentry.ui" line="+14"/> <source>Form</source> <translation>Formulário</translation> </message> <message> <location line="+15"/> <source>A&amp;mount:</source> <translation>Qu&amp;antia:</translation> </message> <message> <location line="+13"/> <source>Pay &amp;To:</source> <translation>&amp;Pagar A:</translation> </message> <message> <location line="+34"/> <source>The address to send the payment to (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>O endereço para onde enviar o pagamento (p.ex. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> <message> <location line="+60"/> <location filename="../sendcoinsentry.cpp" line="+26"/> <source>Enter a label for this address to add it to your address book</source> <translation>Escreva um rótulo para este endereço para o adicionar ao seu livro de endereços</translation> </message> <message> <location line="-78"/> <source>&amp;Label:</source> <translation>Rótu&amp;lo:</translation> </message> <message> <location line="+28"/> <source>Choose address from address book</source> <translation>Escolher endereço do livro de endereços</translation> </message> <message> <location line="+10"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="+7"/> <source>Paste address from clipboard</source> <translation>Cole endereço da área de transferência</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+7"/> <source>Remove this recipient</source> <translation>Remover este destinatário</translation> </message> <message> <location filename="../sendcoinsentry.cpp" line="+1"/> <source>Enter a PioneerCoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Introduza um endereço PioneerCoin (p.ex. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> </context> <context> <name>SignVerifyMessageDialog</name> <message> <location filename="../forms/signverifymessagedialog.ui" line="+14"/> <source>Signatures - Sign / Verify a Message</source> <translation>Assinaturas - Assinar / Verificar uma Mensagem</translation> </message> <message> <location line="+13"/> <source>&amp;Sign Message</source> <translation>A&amp;ssinar Mensagem</translation> </message> <message> <location line="+6"/> <source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source> <translation>Pode assinar mensagens com os seus endereços para provar que são seus. Tenha atenção ao assinar mensagens ambíguas, pois ataques de phishing podem tentar enganá-lo, de modo a assinar a sua identidade para os atacantes. Apenas assine declarações completamente detalhadas com as quais concorde.</translation> </message> <message> <location line="+18"/> <source>The address to sign the message with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>O endereço a utilizar para assinar a mensagem (p.ex. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> <message> <location line="+10"/> <location line="+213"/> <source>Choose an address from the address book</source> <translation>Escolher endereço do livro de endereços</translation> </message> <message> <location line="-203"/> <location line="+213"/> <source>Alt+A</source> <translation>Alt+A</translation> </message> <message> <location line="-203"/> <source>Paste address from clipboard</source> <translation>Cole endereço da área de transferência</translation> </message> <message> <location line="+10"/> <source>Alt+P</source> <translation>Alt+P</translation> </message> <message> <location line="+12"/> <source>Enter the message you want to sign here</source> <translation>Escreva aqui a mensagem que deseja assinar</translation> </message> <message> <location line="+7"/> <source>Signature</source> <translation>Assinatura</translation> </message> <message> <location line="+27"/> <source>Copy the current signature to the system clipboard</source> <translation>Copiar a assinatura actual para a área de transferência</translation> </message> <message> <location line="+21"/> <source>Sign the message to prove you own this PioneerCoin address</source> <translation>Assine uma mensagem para provar que é dono deste endereço PioneerCoin</translation> </message> <message> <location line="+3"/> <source>Sign &amp;Message</source> <translation>Assinar &amp;Mensagem</translation> </message> <message> <location line="+14"/> <source>Reset all sign message fields</source> <translation>Repôr todos os campos de assinatura de mensagem</translation> </message> <message> <location line="+3"/> <location line="+146"/> <source>Clear &amp;All</source> <translation>Limpar &amp;Tudo</translation> </message> <message> <location line="-87"/> <source>&amp;Verify Message</source> <translation>&amp;Verificar Mensagem</translation> </message> <message> <location line="+6"/> <source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source> <translation>Introduza o endereço de assinatura, mensagem (assegure-se de copiar quebras de linha, espaços, tabuladores, etc. exactamente) e assinatura abaixo para verificar a mensagem. Tenha atenção para não ler mais na assinatura do que o que estiver na mensagem assinada, para evitar ser enganado por um atacante que se encontre entre si e quem assinou a mensagem.</translation> </message> <message> <location line="+21"/> <source>The address the message was signed with (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>O endereço utilizado para assinar a mensagem (p.ex. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> <message> <location line="+40"/> <source>Verify the message to ensure it was signed with the specified PioneerCoin address</source> <translation>Verifique a mensagem para assegurar que foi assinada com o endereço PioneerCoin especificado</translation> </message> <message> <location line="+3"/> <source>Verify &amp;Message</source> <translation>Verificar &amp;Mensagem</translation> </message> <message> <location line="+14"/> <source>Reset all verify message fields</source> <translation>Repôr todos os campos de verificação de mensagem</translation> </message> <message> <location filename="../signverifymessagedialog.cpp" line="+27"/> <location line="+3"/> <source>Enter a PioneerCoin address (e.g. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</source> <translation>Introduza um endereço PioneerCoin (p.ex. Ler4HNAEfwYhBmGXcFP2Po1NpRUEiK8km2)</translation> </message> <message> <location line="-2"/> <source>Click &quot;Sign Message&quot; to generate signature</source> <translation>Clique &quot;Assinar mensagem&quot; para gerar a assinatura</translation> </message> <message> <location line="+3"/> <source>Enter PioneerCoin signature</source> <translation>Introduza assinatura PioneerCoin</translation> </message> <message> <location line="+82"/> <location line="+81"/> <source>The entered address is invalid.</source> <translation>O endereço introduzido é inválido. </translation> </message> <message> <location line="-81"/> <location line="+8"/> <location line="+73"/> <location line="+8"/> <source>Please check the address and try again.</source> <translation>Por favor verifique o endereço e tente de novo.</translation> </message> <message> <location line="-81"/> <location line="+81"/> <source>The entered address does not refer to a key.</source> <translation>O endereço introduzido não refere a chave alguma.</translation> </message> <message> <location line="-73"/> <source>Wallet unlock was cancelled.</source> <translation>O desbloqueio da carteira foi cancelado.</translation> </message> <message> <location line="+8"/> <source>Private key for the entered address is not available.</source> <translation>A chave privada para o endereço introduzido não está disponível.</translation> </message> <message> <location line="+12"/> <source>Message signing failed.</source> <translation>Assinatura de mensagem falhou.</translation> </message> <message> <location line="+5"/> <source>Message signed.</source> <translation>Mensagem assinada.</translation> </message> <message> <location line="+59"/> <source>The signature could not be decoded.</source> <translation>A assinatura não pôde ser descodificada.</translation> </message> <message> <location line="+0"/> <location line="+13"/> <source>Please check the signature and try again.</source> <translation>Por favor verifique a assinatura e tente de novo.</translation> </message> <message> <location line="+0"/> <source>The signature did not match the message digest.</source> <translation>A assinatura não condiz com o conteúdo da mensagem.</translation> </message> <message> <location line="+7"/> <source>Message verification failed.</source> <translation>Verificação da mensagem falhou.</translation> </message> <message> <location line="+5"/> <source>Message verified.</source> <translation>Mensagem verificada.</translation> </message> </context> <context> <name>SplashScreen</name> <message> <location filename="../splashscreen.cpp" line="+22"/> <source>The PioneerCoin developers</source> <translation>Os programadores PioneerCoin</translation> </message> <message> <location line="+1"/> <source>[testnet]</source> <translation>[rede de testes]</translation> </message> </context> <context> <name>TransactionDesc</name> <message> <location filename="../transactiondesc.cpp" line="+20"/> <source>Open until %1</source> <translation>Aberto até %1</translation> </message> <message> <location line="+6"/> <source>%1/offline</source> <translation>%1/desligado</translation> </message> <message> <location line="+2"/> <source>%1/unconfirmed</source> <translation>%1/não confirmada</translation> </message> <message> <location line="+2"/> <source>%1 confirmations</source> <translation>%1 confirmações</translation> </message> <message> <location line="+18"/> <source>Status</source> <translation>Estado</translation> </message> <message numerus="yes"> <location line="+7"/> <source>, broadcast through %n node(s)</source> <translation><numerusform>, transmitida através de %n nó</numerusform><numerusform>, transmitida através de %n nós</numerusform></translation> </message> <message> <location line="+4"/> <source>Date</source> <translation>Data</translation> </message> <message> <location line="+7"/> <source>Source</source> <translation>Origem</translation> </message> <message> <location line="+0"/> <source>Generated</source> <translation>Gerado</translation> </message> <message> <location line="+5"/> <location line="+17"/> <source>From</source> <translation>De</translation> </message> <message> <location line="+1"/> <location line="+22"/> <location line="+58"/> <source>To</source> <translation>Para</translation> </message> <message> <location line="-77"/> <location line="+2"/> <source>own address</source> <translation>endereço próprio</translation> </message> <message> <location line="-2"/> <source>label</source> <translation>rótulo</translation> </message> <message> <location line="+37"/> <location line="+12"/> <location line="+45"/> <location line="+17"/> <location line="+30"/> <source>Credit</source> <translation>Crédito</translation> </message> <message numerus="yes"> <location line="-102"/> <source>matures in %n more block(s)</source> <translation><numerusform>matura daqui por %n bloco</numerusform><numerusform>matura daqui por %n blocos</numerusform></translation> </message> <message> <location line="+2"/> <source>not accepted</source> <translation>não aceite</translation> </message> <message> <location line="+44"/> <location line="+8"/> <location line="+15"/> <location line="+30"/> <source>Debit</source> <translation>Débito</translation> </message> <message> <location line="-39"/> <source>Transaction fee</source> <translation>Taxa de transação</translation> </message> <message> <location line="+16"/> <source>Net amount</source> <translation>Valor líquido</translation> </message> <message> <location line="+6"/> <source>Message</source> <translation>Mensagem</translation> </message> <message> <location line="+2"/> <source>Comment</source> <translation>Comentário</translation> </message> <message> <location line="+2"/> <source>Transaction ID</source> <translation>ID da Transação</translation> </message> <message> <location line="+3"/> <source>Generated coins must mature 120 blocks before they can be spent. When you generated this block, it was broadcast to the network to be added to the block chain. If it fails to get into the chain, its state will change to &quot;not accepted&quot; and it won&apos;t be spendable. This may occasionally happen if another node generates a block within a few seconds of yours.</source> <translation>Moedas geradas deverão maturar por 120 blocos antes de poderem ser gastas. Quando gerou este bloco, ele foi transmitido para a rede para ser incluído na cadeia de blocos. Se a inclusão na cadeia de blocos falhar, irá mudar o estado para &quot;não aceite&quot; e as moedas não poderão ser gastas. Isto poderá acontecer ocasionalmente se outro nó da rede gerar um bloco a poucos segundos de diferença do seu.</translation> </message> <message> <location line="+7"/> <source>Debug information</source> <translation>Informação de depuração</translation> </message> <message> <location line="+8"/> <source>Transaction</source> <translation>Transação</translation> </message> <message> <location line="+3"/> <source>Inputs</source> <translation>Entradas</translation> </message> <message> <location line="+23"/> <source>Amount</source> <translation>Quantia</translation> </message> <message> <location line="+1"/> <source>true</source> <translation>verdadeiro</translation> </message> <message> <location line="+0"/> <source>false</source> <translation>falso</translation> </message> <message> <location line="-209"/> <source>, has not been successfully broadcast yet</source> <translation>, ainda não foi transmitida com sucesso</translation> </message> <message numerus="yes"> <location line="-35"/> <source>Open for %n more block(s)</source> <translation><numerusform>Aberta por mais %n bloco</numerusform><numerusform>Aberta por mais %n blocos</numerusform></translation> </message> <message> <location line="+70"/> <source>unknown</source> <translation>desconhecido</translation> </message> </context> <context> <name>TransactionDescDialog</name> <message> <location filename="../forms/transactiondescdialog.ui" line="+14"/> <source>Transaction details</source> <translation>Detalhes da transação</translation> </message> <message> <location line="+6"/> <source>This pane shows a detailed description of the transaction</source> <translation>Esta janela mostra uma descrição detalhada da transação</translation> </message> </context> <context> <name>TransactionTableModel</name> <message> <location filename="../transactiontablemodel.cpp" line="+225"/> <source>Date</source> <translation>Data</translation> </message> <message> <location line="+0"/> <source>Type</source> <translation>Tipo</translation> </message> <message> <location line="+0"/> <source>Address</source> <translation>Endereço</translation> </message> <message> <location line="+0"/> <source>Amount</source> <translation>Quantia</translation> </message> <message numerus="yes"> <location line="+57"/> <source>Open for %n more block(s)</source> <translation><numerusform>Aberta por mais %n bloco</numerusform><numerusform>Aberta por mais %n blocos</numerusform></translation> </message> <message> <location line="+3"/> <source>Open until %1</source> <translation>Aberto até %1</translation> </message> <message> <location line="+3"/> <source>Offline (%1 confirmations)</source> <translation>Desligado (%1 confirmação)</translation> </message> <message> <location line="+3"/> <source>Unconfirmed (%1 of %2 confirmations)</source> <translation>Não confirmada (%1 de %2 confirmações)</translation> </message> <message> <location line="+3"/> <source>Confirmed (%1 confirmations)</source> <translation>Confirmada (%1 confirmação)</translation> </message> <message numerus="yes"> <location line="+8"/> <source>Mined balance will be available when it matures in %n more block(s)</source> <translation><numerusform>Saldo minado ficará disponível quando maturar, daqui por %n bloco</numerusform><numerusform>Saldo minado ficará disponível quando maturar, daqui por %n blocos</numerusform></translation> </message> <message> <location line="+5"/> <source>This block was not received by any other nodes and will probably not be accepted!</source> <translation>Este bloco não foi recebido por outros nós e provavelmente não será aceite pela rede!</translation> </message> <message> <location line="+3"/> <source>Generated but not accepted</source> <translation>Gerado mas não aceite</translation> </message> <message> <location line="+43"/> <source>Received with</source> <translation>Recebido com</translation> </message> <message> <location line="+2"/> <source>Received from</source> <translation>Recebido de</translation> </message> <message> <location line="+3"/> <source>Sent to</source> <translation>Enviado para</translation> </message> <message> <location line="+2"/> <source>Payment to yourself</source> <translation>Pagamento ao próprio</translation> </message> <message> <location line="+2"/> <source>Mined</source> <translation>Minado</translation> </message> <message> <location line="+38"/> <source>(n/a)</source> <translation>(n/d)</translation> </message> <message> <location line="+199"/> <source>Transaction status. Hover over this field to show number of confirmations.</source> <translation>Estado da transação. Pairar por cima deste campo para mostrar o número de confirmações.</translation> </message> <message> <location line="+2"/> <source>Date and time that the transaction was received.</source> <translation>Data e hora a que esta transação foi recebida.</translation> </message> <message> <location line="+2"/> <source>Type of transaction.</source> <translation>Tipo de transação.</translation> </message> <message> <location line="+2"/> <source>Destination address of transaction.</source> <translation>Endereço de destino da transação.</translation> </message> <message> <location line="+2"/> <source>Amount removed from or added to balance.</source> <translation>Quantia retirada ou adicionada ao saldo.</translation> </message> </context> <context> <name>TransactionView</name> <message> <location filename="../transactionview.cpp" line="+52"/> <location line="+16"/> <source>All</source> <translation>Todas</translation> </message> <message> <location line="-15"/> <source>Today</source> <translation>Hoje</translation> </message> <message> <location line="+1"/> <source>This week</source> <translation>Esta semana</translation> </message> <message> <location line="+1"/> <source>This month</source> <translation>Este mês</translation> </message> <message> <location line="+1"/> <source>Last month</source> <translation>Mês passado</translation> </message> <message> <location line="+1"/> <source>This year</source> <translation>Este ano</translation> </message> <message> <location line="+1"/> <source>Range...</source> <translation>Período...</translation> </message> <message> <location line="+11"/> <source>Received with</source> <translation>Recebida com</translation> </message> <message> <location line="+2"/> <source>Sent to</source> <translation>Enviada para</translation> </message> <message> <location line="+2"/> <source>To yourself</source> <translation>Para si</translation> </message> <message> <location line="+1"/> <source>Mined</source> <translation>Minadas</translation> </message> <message> <location line="+1"/> <source>Other</source> <translation>Outras</translation> </message> <message> <location line="+7"/> <source>Enter address or label to search</source> <translation>Escreva endereço ou rótulo a procurar</translation> </message> <message> <location line="+7"/> <source>Min amount</source> <translation>Quantia mínima</translation> </message> <message> <location line="+34"/> <source>Copy address</source> <translation>Copiar endereço</translation> </message> <message> <location line="+1"/> <source>Copy label</source> <translation>Copiar rótulo</translation> </message> <message> <location line="+1"/> <source>Copy amount</source> <translation>Copiar quantia</translation> </message> <message> <location line="+1"/> <source>Copy transaction ID</source> <translation>Copiar ID da Transação</translation> </message> <message> <location line="+1"/> <source>Edit label</source> <translation>Editar rótulo</translation> </message> <message> <location line="+1"/> <source>Show transaction details</source> <translation>Mostrar detalhes da transação</translation> </message> <message> <location line="+139"/> <source>Export Transaction Data</source> <translation>Exportar Dados das Transações</translation> </message> <message> <location line="+1"/> <source>Comma separated file (*.csv)</source> <translation>Ficheiro separado por vírgula (*.csv)</translation> </message> <message> <location line="+8"/> <source>Confirmed</source> <translation>Confirmada</translation> </message> <message> <location line="+1"/> <source>Date</source> <translation>Data</translation> </message> <message> <location line="+1"/> <source>Type</source> <translation>Tipo</translation> </message> <message> <location line="+1"/> <source>Label</source> <translation>Rótulo</translation> </message> <message> <location line="+1"/> <source>Address</source> <translation>Endereço</translation> </message> <message> <location line="+1"/> <source>Amount</source> <translation>Quantia</translation> </message> <message> <location line="+1"/> <source>ID</source> <translation>ID</translation> </message> <message> <location line="+4"/> <source>Error exporting</source> <translation>Erro ao exportar</translation> </message> <message> <location line="+0"/> <source>Could not write to file %1.</source> <translation>Impossível escrever para o ficheiro %1.</translation> </message> <message> <location line="+100"/> <source>Range:</source> <translation>Período:</translation> </message> <message> <location line="+8"/> <source>to</source> <translation>até</translation> </message> </context> <context> <name>WalletModel</name> <message> <location filename="../walletmodel.cpp" line="+193"/> <source>Send Coins</source> <translation>Enviar Moedas</translation> </message> </context> <context> <name>WalletView</name> <message> <location filename="../walletview.cpp" line="+42"/> <source>&amp;Export</source> <translation>&amp;Exportar</translation> </message> <message> <location line="+1"/> <source>Export the data in the current tab to a file</source> <translation>Exportar os dados no separador actual para um ficheiro</translation> </message> <message> <location line="+193"/> <source>Backup Wallet</source> <translation>Cópia de Segurança da Carteira</translation> </message> <message> <location line="+0"/> <source>Wallet Data (*.dat)</source> <translation>Dados da Carteira (*.dat)</translation> </message> <message> <location line="+3"/> <source>Backup Failed</source> <translation>Cópia de Segurança Falhou</translation> </message> <message> <location line="+0"/> <source>There was an error trying to save the wallet data to the new location.</source> <translation>Ocorreu um erro ao tentar guardar os dados da carteira na nova localização.</translation> </message> <message> <location line="+4"/> <source>Backup Successful</source> <translation>Cópia de Segurança Bem Sucedida</translation> </message> <message> <location line="+0"/> <source>The wallet data was successfully saved to the new location.</source> <translation>Os dados da carteira foram salvos com sucesso numa nova localização.</translation> </message> </context> <context> <name>bitcoin-core</name> <message> <location filename="../bitcoinstrings.cpp" line="+94"/> <source>PioneerCoin version</source> <translation>Versão PioneerCoin</translation> </message> <message> <location line="+102"/> <source>Usage:</source> <translation>Utilização:</translation> </message> <message> <location line="-29"/> <source>Send command to -server or PioneerCoind</source> <translation>Enviar comando para -server ou PioneerCoind</translation> </message> <message> <location line="-23"/> <source>List commands</source> <translation>Listar comandos</translation> </message> <message> <location line="-12"/> <source>Get help for a command</source> <translation>Obter ajuda para um comando</translation> </message> <message> <location line="+24"/> <source>Options:</source> <translation>Opções:</translation> </message> <message> <location line="+24"/> <source>Specify configuration file (default: PioneerCoin.conf)</source> <translation>Especificar ficheiro de configuração (por defeito: PioneerCoin.conf)</translation> </message> <message> <location line="+3"/> <source>Specify pid file (default: PioneerCoind.pid)</source> <translation>Especificar ficheiro pid (por defeito: PioneerCoind.pid)</translation> </message> <message> <location line="-1"/> <source>Specify data directory</source> <translation>Especificar pasta de dados</translation> </message> <message> <location line="-9"/> <source>Set database cache size in megabytes (default: 25)</source> <translation>Definir o tamanho da cache de base de dados em megabytes (por defeito: 25)</translation> </message> <message> <location line="-28"/> <source>Listen for connections on &lt;port&gt; (default: 9333 or testnet: 19333)</source> <translation>Escute por ligações em &lt;port&gt; (por defeito: 9333 ou testnet: 19333)</translation> </message> <message> <location line="+5"/> <source>Maintain at most &lt;n&gt; connections to peers (default: 125)</source> <translation>Manter no máximo &lt;n&gt; ligações a outros nós da rede (por defeito: 125)</translation> </message> <message> <location line="-48"/> <source>Connect to a node to retrieve peer addresses, and disconnect</source> <translation>Ligar a um nó para recuperar endereços de pares, e desligar</translation> </message> <message> <location line="+82"/> <source>Specify your own public address</source> <translation>Especifique o seu endereço público</translation> </message> <message> <location line="+3"/> <source>Threshold for disconnecting misbehaving peers (default: 100)</source> <translation>Tolerância para desligar nós mal-formados (por defeito: 100)</translation> </message> <message> <location line="-134"/> <source>Number of seconds to keep misbehaving peers from reconnecting (default: 86400)</source> <translation>Número de segundos a impedir que nós mal-formados se liguem de novo (por defeito: 86400)</translation> </message> <message> <location line="-29"/> <source>An error occurred while setting up the RPC port %u for listening on IPv4: %s</source> <translation>Ocorreu um erro ao definir a porta %u do serviço RPC a escutar em IPv4: %s</translation> </message> <message> <location line="+27"/> <source>Listen for JSON-RPC connections on &lt;port&gt; (default: 9332 or testnet: 19332)</source> <translation>Escutar por ligações JSON-RPC em &lt;port&gt; (por defeito: 9332 ou rede de testes: 19332)</translation> </message> <message> <location line="+37"/> <source>Accept command line and JSON-RPC commands</source> <translation>Aceitar comandos da consola e JSON-RPC</translation> </message> <message> <location line="+76"/> <source>Run in the background as a daemon and accept commands</source> <translation>Correr o processo como um daemon e aceitar comandos</translation> </message> <message> <location line="+37"/> <source>Use the test network</source> <translation>Utilizar a rede de testes - testnet</translation> </message> <message> <location line="-112"/> <source>Accept connections from outside (default: 1 if no -proxy or -connect)</source> <translation>Aceitar ligações externas (padrão: 1 sem -proxy ou -connect)</translation> </message> <message> <location line="-80"/> <source>%s, you must set a rpcpassword in the configuration file: %s It is recommended you use the following random password: rpcuser=PioneerCoinrpc rpcpassword=%s (you do not need to remember this password) The username and password MUST NOT be the same. If the file does not exist, create it with owner-readable-only file permissions. It is also recommended to set alertnotify so you are notified of problems; for example: alertnotify=echo %%s | mail -s &quot;PioneerCoin Alert&quot; admin@foo.com </source> <translation>%s, deverá definir rpcpassword no ficheiro de configuração : %s É recomendado que use a seguinte palavra-passe aleatória: rpcuser=PioneerCoinrpc rpcpassword=%s (não precisa recordar esta palavra-passe) O nome de utilizador e password NÃO DEVEM ser iguais. Se o ficheiro não existir, crie-o com permissões de leitura apenas para o dono. Também é recomendado definir alertnotify para que seja alertado sobre problemas; por exemplo: alertnotify=echo %%s | mail -s &quot;Alerta PioneerCoin&quot; admin@foo.com </translation> </message> <message> <location line="+17"/> <source>An error occurred while setting up the RPC port %u for listening on IPv6, falling back to IPv4: %s</source> <translation>Ocorreu um erro ao definir a porta %u do serviço RPC a escutar em IPv6, a usar IPv4: %s</translation> </message> <message> <location line="+3"/> <source>Bind to given address and always listen on it. Use [host]:port notation for IPv6</source> <translation>Trancar a endereço específio e sempre escutar nele. Use a notação [anfitrião]:porta para IPv6</translation> </message> <message> <location line="+3"/> <source>Cannot obtain a lock on data directory %s. PioneerCoin is probably already running.</source> <translation>Impossível trancar a pasta de dados %s. Provavelmente o PioneerCoin já está a ser executado.</translation> </message> <message> <location line="+3"/> <source>Error: The transaction was rejected! This might happen if some of the coins in your wallet were already spent, such as if you used a copy of wallet.dat and coins were spent in the copy but not marked as spent here.</source> <translation>Erro: A transação foi rejeitada. Isso poderá acontecer se algumas das moedas na sua carteira já tiverem sido gastas, se por exemplo tiver usado uma cópia do ficheiro wallet.dat e as moedas foram gastas na cópia mas não foram marcadas como gastas aqui.</translation> </message> <message> <location line="+4"/> <source>Error: This transaction requires a transaction fee of at least %s because of its amount, complexity, or use of recently received funds!</source> <translation>Erro: Esta transação requer uma taxa de transação mínima de %s devido á sua quantia, complexidade, ou uso de fundos recebidos recentemente! </translation> </message> <message> <location line="+3"/> <source>Execute command when a relevant alert is received (%s in cmd is replaced by message)</source> <translation>Executar comando quando um alerta relevante for recebido (no comando, %s é substituído pela mensagem)</translation> </message> <message> <location line="+3"/> <source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source> <translation>Executar comando quando uma das transações na carteira mudar (no comando, %s é substituído pelo ID da Transação)</translation> </message> <message> <location line="+11"/> <source>Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)</source> <translation>Definir tamanho máximo de transações de alta-/baixa-prioridade em bytes (por defeito: 27000)</translation> </message> <message> <location line="+6"/> <source>This is a pre-release test build - use at your own risk - do not use for mining or merchant applications</source> <translation>Esta é uma versão de pré-lançamento - use à sua responsabilidade - não usar para minar ou aplicações comerciais</translation> </message> <message> <location line="+5"/> <source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source> <translation>Atenção: -paytxfee está definida com um valor muito alto! Esta é a taxa que irá pagar se enviar uma transação.</translation> </message> <message> <location line="+3"/> <source>Warning: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.</source> <translation>Atenção: As transações mostradas poderão não estar correctas! Poderá ter que atualizar ou outros nós poderão ter que atualizar.</translation> </message> <message> <location line="+3"/> <source>Warning: Please check that your computer&apos;s date and time are correct! If your clock is wrong PioneerCoin will not work properly.</source> <translation>Atenção: Por favor verifique que a data e hora do seu computador estão correctas! Se o seu relógio não estiver certo o PioneerCoin não irá funcionar correctamente.</translation> </message> <message> <location line="+3"/> <source>Warning: error reading wallet.dat! All keys read correctly, but transaction data or address book entries might be missing or incorrect.</source> <translation>Atenção: erro ao ler wallet.dat! Todas as chaves foram lidas correctamente, mas dados de transação ou do livro de endereços podem estar em falta ou incorrectos.</translation> </message> <message> <location line="+3"/> <source>Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect you should restore from a backup.</source> <translation>Atenção: wallet.dat corrupto, dados recuperados! wallet.dat original salvo como wallet.{timestamp}.bak em %s; se o seu saldo ou transações estiverem incorrectos deverá recuperar de uma cópia de segurança.</translation> </message> <message> <location line="+14"/> <source>Attempt to recover private keys from a corrupt wallet.dat</source> <translation>Tentar recuperar chaves privadas de um wallet.dat corrupto</translation> </message> <message> <location line="+2"/> <source>Block creation options:</source> <translation>Opções de criação de bloco:</translation> </message> <message> <location line="+5"/> <source>Connect only to the specified node(s)</source> <translation>Apenas ligar ao(s) nó(s) especificado(s)</translation> </message> <message> <location line="+3"/> <source>Corrupted block database detected</source> <translation>Cadeia de blocos corrompida detectada</translation> </message> <message> <location line="+1"/> <source>Discover own IP address (default: 1 when listening and no -externalip)</source> <translation>Descobrir endereço IP próprio (padrão: 1 ao escutar e sem -externalip)</translation> </message> <message> <location line="+1"/> <source>Do you want to rebuild the block database now?</source> <translation>Deseja reconstruir agora a cadeia de blocos?</translation> </message> <message> <location line="+2"/> <source>Error initializing block database</source> <translation>Erro ao inicializar a cadeia de blocos</translation> </message> <message> <location line="+1"/> <source>Error initializing wallet database environment %s!</source> <translation>Erro ao inicializar o ambiente de base de dados da carteira %s!</translation> </message> <message> <location line="+1"/> <source>Error loading block database</source> <translation>Erro ao carregar cadeia de blocos</translation> </message> <message> <location line="+4"/> <source>Error opening block database</source> <translation>Erro ao abrir a cadeia de blocos</translation> </message> <message> <location line="+2"/> <source>Error: Disk space is low!</source> <translation>Erro: Pouco espaço em disco!</translation> </message> <message> <location line="+1"/> <source>Error: Wallet locked, unable to create transaction!</source> <translation>Erro: Carteira bloqueada, incapaz de criar transação! </translation> </message> <message> <location line="+1"/> <source>Error: system error: </source> <translation>Erro: erro do sistema:</translation> </message> <message> <location line="+1"/> <source>Failed to listen on any port. Use -listen=0 if you want this.</source> <translation>Falhou a escutar em qualquer porta. Use -listen=0 se quer isto.</translation> </message> <message> <location line="+1"/> <source>Failed to read block info</source> <translation>Falha ao ler info do bloco</translation> </message> <message> <location line="+1"/> <source>Failed to read block</source> <translation>Falha ao ler bloco</translation> </message> <message> <location line="+1"/> <source>Failed to sync block index</source> <translation>Falha ao sincronizar índice do bloco</translation> </message> <message> <location line="+1"/> <source>Failed to write block index</source> <translation>Falha ao escrever índice do bloco</translation> </message> <message> <location line="+1"/> <source>Failed to write block info</source> <translation>Falha ao escrever info do bloco</translation> </message> <message> <location line="+1"/> <source>Failed to write block</source> <translation>Falha ao escrever o bloco</translation> </message> <message> <location line="+1"/> <source>Failed to write file info</source> <translation>Falha ao escrever info do ficheiro</translation> </message> <message> <location line="+1"/> <source>Failed to write to coin database</source> <translation>Falha ao escrever na base de dados de moedas</translation> </message> <message> <location line="+1"/> <source>Failed to write transaction index</source> <translation>Falha ao escrever índice de transações</translation> </message> <message> <location line="+1"/> <source>Failed to write undo data</source> <translation>Falha ao escrever histórico de modificações</translation> </message> <message> <location line="+2"/> <source>Find peers using DNS lookup (default: 1 unless -connect)</source> <translation>Encontrar pares usando procura DNS (por defeito: 1 excepto -connect)</translation> </message> <message> <location line="+1"/> <source>Generate coins (default: 0)</source> <translation>Gerar moedas (por defeito: 0)</translation> </message> <message> <location line="+2"/> <source>How many blocks to check at startup (default: 288, 0 = all)</source> <translation>Quantos blocos verificar ao começar (por defeito: 288, 0 = todos)</translation> </message> <message> <location line="+1"/> <source>How thorough the block verification is (0-4, default: 3)</source> <translation>Qual a minúcia na verificação de blocos (0-4, por defeito: 3)</translation> </message> <message> <location line="+19"/> <source>Not enough file descriptors available.</source> <translation>Descritores de ficheiros disponíveis são insuficientes.</translation> </message> <message> <location line="+8"/> <source>Rebuild block chain index from current blk000??.dat files</source> <translation>Reconstruir a cadeia de blocos dos ficheiros blk000??.dat actuais</translation> </message> <message> <location line="+16"/> <source>Set the number of threads to service RPC calls (default: 4)</source> <translation>Defina o número de processos para servir as chamadas RPC (por defeito: 4)</translation> </message> <message> <location line="+26"/> <source>Verifying blocks...</source> <translation>Verificando blocos...</translation> </message> <message> <location line="+1"/> <source>Verifying wallet...</source> <translation>Verificando a carteira...</translation> </message> <message> <location line="-69"/> <source>Imports blocks from external blk000??.dat file</source> <translation>Importar blocos de um ficheiro blk000??.dat externo</translation> </message> <message> <location line="-76"/> <source>Set the number of script verification threads (up to 16, 0 = auto, &lt;0 = leave that many cores free, default: 0)</source> <translation>Defina o número de processos de verificação (até 16, 0 = automático, &lt;0 = disponibiliza esse número de núcleos livres, por defeito: 0)</translation> </message> <message> <location line="+77"/> <source>Information</source> <translation>Informação</translation> </message> <message> <location line="+3"/> <source>Invalid -tor address: &apos;%s&apos;</source> <translation>Endereço -tor inválido: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Invalid amount for -minrelaytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>Quantia inválida para -minrelaytxfee=&lt;amount&gt;: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Invalid amount for -mintxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>Quantia inválida para -mintxfee=&lt;amount&gt;: &apos;%s&apos;</translation> </message> <message> <location line="+8"/> <source>Maintain a full transaction index (default: 0)</source> <translation>Manter índice de transações completo (por defeito: 0)</translation> </message> <message> <location line="+2"/> <source>Maximum per-connection receive buffer, &lt;n&gt;*1000 bytes (default: 5000)</source> <translation>Armazenamento intermédio de recepção por ligação, &lt;n&gt;*1000 bytes (por defeito: 5000)</translation> </message> <message> <location line="+1"/> <source>Maximum per-connection send buffer, &lt;n&gt;*1000 bytes (default: 1000)</source> <translation>Armazenamento intermédio de envio por ligação, &lt;n&gt;*1000 bytes (por defeito: 1000)</translation> </message> <message> <location line="+2"/> <source>Only accept block chain matching built-in checkpoints (default: 1)</source> <translation>Apenas aceitar cadeia de blocos coincidente com marcas de verificação internas (por defeito: 1)</translation> </message> <message> <location line="+1"/> <source>Only connect to nodes in network &lt;net&gt; (IPv4, IPv6 or Tor)</source> <translation>Apenas ligar a nós na rede &lt;net&gt; (IPv4, IPv6 ou Tor)</translation> </message> <message> <location line="+2"/> <source>Output extra debugging information. Implies all other -debug* options</source> <translation>Produzir informação de depuração extra. Implica todas as outras opções -debug*</translation> </message> <message> <location line="+1"/> <source>Output extra network debugging information</source> <translation>Produzir informação de depuração extraordinária</translation> </message> <message> <location line="+2"/> <source>Prepend debug output with timestamp</source> <translation>Preceder informação de depuração com selo temporal</translation> </message> <message> <location line="+5"/> <source>SSL options: (see the PioneerCoin Wiki for SSL setup instructions)</source> <translation>Opções SSL: (ver a Wiki PioneerCoin para instruções de configuração SSL)</translation> </message> <message> <location line="+1"/> <source>Select the version of socks proxy to use (4-5, default: 5)</source> <translation>Selecione a versão do proxy socks a usar (4-5, padrão: 5)</translation> </message> <message> <location line="+3"/> <source>Send trace/debug info to console instead of debug.log file</source> <translation>Enviar informação de rastreio/depuração para a consola e não para o ficheiro debug.log</translation> </message> <message> <location line="+1"/> <source>Send trace/debug info to debugger</source> <translation>Enviar informação de rastreio/depuração para o depurador</translation> </message> <message> <location line="+5"/> <source>Set maximum block size in bytes (default: 250000)</source> <translation>Definir tamanho máximo de um bloco em bytes (por defeito: 250000)</translation> </message> <message> <location line="+1"/> <source>Set minimum block size in bytes (default: 0)</source> <translation>Definir tamanho minímo de um bloco em bytes (por defeito: 0)</translation> </message> <message> <location line="+2"/> <source>Shrink debug.log file on client startup (default: 1 when no -debug)</source> <translation>Encolher ficheiro debug.log ao iniciar o cliente (por defeito: 1 sem -debug definido)</translation> </message> <message> <location line="+1"/> <source>Signing transaction failed</source> <translation>Falhou assinatura da transação</translation> </message> <message> <location line="+2"/> <source>Specify connection timeout in milliseconds (default: 5000)</source> <translation>Especificar tempo de espera da ligação em millisegundos (por defeito: 5000)</translation> </message> <message> <location line="+4"/> <source>System error: </source> <translation>Erro de sistema:</translation> </message> <message> <location line="+4"/> <source>Transaction amount too small</source> <translation>Quantia da transação é muito baixa</translation> </message> <message> <location line="+1"/> <source>Transaction amounts must be positive</source> <translation>Quantia da transação deverá ser positiva</translation> </message> <message> <location line="+1"/> <source>Transaction too large</source> <translation>Transação grande demais</translation> </message> <message> <location line="+7"/> <source>Use UPnP to map the listening port (default: 0)</source> <translation>Usar UPnP para mapear a porta de escuta (padrão: 0)</translation> </message> <message> <location line="+1"/> <source>Use UPnP to map the listening port (default: 1 when listening)</source> <translation>Usar UPnP para mapear a porta de escuta (padrão: 1 ao escutar)</translation> </message> <message> <location line="+1"/> <source>Use proxy to reach tor hidden services (default: same as -proxy)</source> <translation>Utilizar proxy para aceder a serviços escondidos Tor (por defeito: mesmo que -proxy)</translation> </message> <message> <location line="+2"/> <source>Username for JSON-RPC connections</source> <translation>Nome de utilizador para ligações JSON-RPC</translation> </message> <message> <location line="+4"/> <source>Warning</source> <translation>Aviso</translation> </message> <message> <location line="+1"/> <source>Warning: This version is obsolete, upgrade required!</source> <translation>Atenção: Esta versão está obsoleta, é necessário actualizar!</translation> </message> <message> <location line="+1"/> <source>You need to rebuild the databases using -reindex to change -txindex</source> <translation>Necessita reconstruir as bases de dados usando -reindex para mudar -txindex</translation> </message> <message> <location line="+1"/> <source>wallet.dat corrupt, salvage failed</source> <translation>wallet.dat corrupta, recuperação falhou</translation> </message> <message> <location line="-50"/> <source>Password for JSON-RPC connections</source> <translation>Palavra-passe para ligações JSON-RPC</translation> </message> <message> <location line="-67"/> <source>Allow JSON-RPC connections from specified IP address</source> <translation>Permitir ligações JSON-RPC do endereço IP especificado</translation> </message> <message> <location line="+76"/> <source>Send commands to node running on &lt;ip&gt; (default: 127.0.0.1)</source> <translation>Enviar comandos para o nó a correr em &lt;ip&gt; (por defeito: 127.0.0.1)</translation> </message> <message> <location line="-120"/> <source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source> <translation>Executar comando quando mudar o melhor bloco (no comando, %s é substituído pela hash do bloco)</translation> </message> <message> <location line="+147"/> <source>Upgrade wallet to latest format</source> <translation>Atualize a carteira para o formato mais recente</translation> </message> <message> <location line="-21"/> <source>Set key pool size to &lt;n&gt; (default: 100)</source> <translation>Definir o tamanho da memória de chaves para &lt;n&gt; (por defeito: 100)</translation> </message> <message> <location line="-12"/> <source>Rescan the block chain for missing wallet transactions</source> <translation>Reexaminar a cadeia de blocos para transações em falta na carteira</translation> </message> <message> <location line="+35"/> <source>Use OpenSSL (https) for JSON-RPC connections</source> <translation>Usar OpenSSL (https) para ligações JSON-RPC</translation> </message> <message> <location line="-26"/> <source>Server certificate file (default: server.cert)</source> <translation>Ficheiro de certificado do servidor (por defeito: server.cert)</translation> </message> <message> <location line="+1"/> <source>Server private key (default: server.pem)</source> <translation>Chave privada do servidor (por defeito: server.pem)</translation> </message> <message> <location line="-151"/> <source>Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</source> <translation>Cifras aceitáveis (por defeito: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)</translation> </message> <message> <location line="+165"/> <source>This help message</source> <translation>Esta mensagem de ajuda</translation> </message> <message> <location line="+6"/> <source>Unable to bind to %s on this computer (bind returned error %d, %s)</source> <translation>Incapaz de vincular a %s neste computador (vínculo retornou erro %d, %s)</translation> </message> <message> <location line="-91"/> <source>Connect through socks proxy</source> <translation>Ligar através de um proxy socks</translation> </message> <message> <location line="-10"/> <source>Allow DNS lookups for -addnode, -seednode and -connect</source> <translation>Permitir procuras DNS para -addnode, -seednode e -connect</translation> </message> <message> <location line="+55"/> <source>Loading addresses...</source> <translation>Carregar endereços...</translation> </message> <message> <location line="-35"/> <source>Error loading wallet.dat: Wallet corrupted</source> <translation>Erro ao carregar wallet.dat: Carteira danificada</translation> </message> <message> <location line="+1"/> <source>Error loading wallet.dat: Wallet requires newer version of PioneerCoin</source> <translation>Erro ao carregar wallet.dat: A Carteira requer uma versão mais recente do PioneerCoin</translation> </message> <message> <location line="+93"/> <source>Wallet needed to be rewritten: restart PioneerCoin to complete</source> <translation>A Carteira precisou ser reescrita: reinicie o PioneerCoin para completar</translation> </message> <message> <location line="-95"/> <source>Error loading wallet.dat</source> <translation>Erro ao carregar wallet.dat</translation> </message> <message> <location line="+28"/> <source>Invalid -proxy address: &apos;%s&apos;</source> <translation>Endereço -proxy inválido: &apos;%s&apos;</translation> </message> <message> <location line="+56"/> <source>Unknown network specified in -onlynet: &apos;%s&apos;</source> <translation>Rede desconhecida especificada em -onlynet: &apos;%s&apos;</translation> </message> <message> <location line="-1"/> <source>Unknown -socks proxy version requested: %i</source> <translation>Versão desconhecida de proxy -socks requisitada: %i</translation> </message> <message> <location line="-96"/> <source>Cannot resolve -bind address: &apos;%s&apos;</source> <translation>Não conseguiu resolver endereço -bind: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Cannot resolve -externalip address: &apos;%s&apos;</source> <translation>Não conseguiu resolver endereço -externalip: &apos;%s&apos;</translation> </message> <message> <location line="+44"/> <source>Invalid amount for -paytxfee=&lt;amount&gt;: &apos;%s&apos;</source> <translation>Quantia inválida para -paytxfee=&lt;amount&gt;: &apos;%s&apos;</translation> </message> <message> <location line="+1"/> <source>Invalid amount</source> <translation>Quantia inválida</translation> </message> <message> <location line="-6"/> <source>Insufficient funds</source> <translation>Fundos insuficientes</translation> </message> <message> <location line="+10"/> <source>Loading block index...</source> <translation>Carregar índice de blocos...</translation> </message> <message> <location line="-57"/> <source>Add a node to connect to and attempt to keep the connection open</source> <translation>Adicione um nó ao qual se ligar e tentar manter a ligação aberta</translation> </message> <message> <location line="-25"/> <source>Unable to bind to %s on this computer. PioneerCoin is probably already running.</source> <translation>Incapaz de vincular à porta %s neste computador. Provavelmente o PioneerCoin já está a funcionar.</translation> </message> <message> <location line="+64"/> <source>Fee per KB to add to transactions you send</source> <translation>Taxa por KB a adicionar a transações enviadas</translation> </message> <message> <location line="+19"/> <source>Loading wallet...</source> <translation>Carregar carteira...</translation> </message> <message> <location line="-52"/> <source>Cannot downgrade wallet</source> <translation>Impossível mudar a carteira para uma versão anterior</translation> </message> <message> <location line="+3"/> <source>Cannot write default address</source> <translation>Impossível escrever endereço por defeito</translation> </message> <message> <location line="+64"/> <source>Rescanning...</source> <translation>Reexaminando...</translation> </message> <message> <location line="-57"/> <source>Done loading</source> <translation>Carregamento completo</translation> </message> <message> <location line="+82"/> <source>To use the %s option</source> <translation>Para usar a opção %s</translation> </message> <message> <location line="-74"/> <source>Error</source> <translation>Erro</translation> </message> <message> <location line="-31"/> <source>You must set rpcpassword=&lt;password&gt; in the configuration file: %s If the file does not exist, create it with owner-readable-only file permissions.</source> <translation>Deverá definir rpcpassword=&lt;password&gt; no ficheiro de configuração: %s Se o ficheiro não existir, crie-o com permissões de leitura apenas para o dono.</translation> </message> </context> </TS>
pioneercrypto/PioneerCoin
src/qt/locale/bitcoin_pt_PT.ts
TypeScript
mit
119,141
<? class Welcome_model extends CI_Model{ function __construct(){ //Llamado al contructor del modelo parent::__construct(); } public function insertar_alumno($persona){ if ($this->db->insert('usu_al', $persona)) return true; else return false; } public function insertar_docente($persona){ if ($this->db->insert('usu_doc', $persona)) return true; else return false; } public function insertar_ramo($ramo){ if ($this->db->insert('ramos', $ramo)) return true; else return false; } public function get_areas(){ $query = $this->db->query('SELECT area_id, area_nom FROM areas'); if ($query->num_rows() > 0) { foreach($query->result() as $row) $arrDatos[htmlspecialchars($row->area_id, ENT_QUOTES)] = htmlspecialchars($row->area_nom, ENT_QUOTES); $query->free_result(); return $arrDatos; } } public function get_docente(){ $query = $this->db->query('SELECT doc_id, doc_nom FROM usu_doc'); if ($query->num_rows() > 0) { foreach($query->result() as $row) $arrDatos[htmlspecialchars($row->doc_id, ENT_QUOTES)] = htmlspecialchars($row->doc_nom, ENT_QUOTES); $query->free_result(); return $arrDatos; } } public function get_alumno(){ #$this->db->order_by('al_id DESC'); $query = $this->db->query('SELECT usu_al.al_id,usu_al.al_rt,usu_al.al_dv, usu_al.al_nom,usu_al.al_lastn, areas.area_nom, areas.area_id from areas inner join usu_al on areas.area_id = usu_al.areas_area_id'); return $query->result(); //} } public function get_doc(){ #$this->db->order_by('al_id DESC'); $query = $this->db->query('SELECT usu_doc.doc_id,usu_doc.doc_rt,usu_doc.doc_dv, usu_doc.doc_nom,usu_doc.doc_lastn, areas.area_nom, areas.area_id from areas inner join usu_doc on areas.area_id = usu_doc.areas_area_id '); return $query->result(); } public function eliminarAlu($id){ $this->db->where('al_id', $id); return $this->db->delete('usu_al'); } public function eliminarDoce($id){ $this->db->where('doc_id', $id); return $this->db->delete('usu_doc'); } public function validate_credentials($username, $password){ $this->db->where('log_rt', $username); $this->db->where('log_pass', $password); return $this->db->get('login')->row(); } }
GrinGraz/CIMVC
application/models/welcome_model.php
PHP
mit
2,333
declare const foo: string; export default foo;
typings/core
src/lib/__test__/fixtures/compile-export-default/index.d.ts
TypeScript
mit
48
#coding: utf-8 require 'test_helper' class CoreExtTest < ActiveSupport::TestCase test "str.encode_emoji" do assert_equal "test string", "test string".encode_emoji assert_equal "{{260e}}️", "☎️".encode_emoji assert_equal "{{1f4f1}}", "📱".encode_emoji end test "str.decode_emoji" do assert_equal "test string", "test string".decode_emoji assert_equal "☎️", "{{260e}}️".decode_emoji assert_equal "📱","{{1f4f1}}".decode_emoji end test "nil.encode_emoji" do assert_equal nil, nil.encode_emoji end test "nil.decode_emoji" do assert_equal nil, nil.decode_emoji end end
phonezawphyo/monkey_emoji
test/core_ext_test.rb
Ruby
mit
633
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.Text; namespace BetterWords { [ServiceContract] public interface IWordService { [OperationContract] string LoadData(); [OperationContract] string Correct(string word); } }
amughni/SpellChecker
BetterWords/BetterWords/IWordService.cs
C#
mit
369
# Requires require "Core/CDImage" # An implementation for CDImage For RHEL module PackerFiles module RHEL class CD < Core::CDImageImpl # Override method for getting the ISO name def get_iso_name_pattern 'rhel-server-@release@-@arch@-dvd.iso' end # Override method for getting checksums def get_check_sum_pattern '' end # Override method for checksum type def get_check_sum_type 'none' end # Override method for getting index URLs. This is a dummy URL # which is not accessible. def index_urls ['https://download.redhat.com/isos/@release@/@arch@/'] end end end end
anandvenkatanarayanan/PackerFiles
lib/PackerFiles/OS/RHEL/CD.rb
Ruby
mit
670
# encoding: utf-8 # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. module Azure::Compute::Mgmt::V2016_04_30_preview module Models # # The List Usages operation response. # class ListUsagesResult include MsRestAzure include MsRest::JSONable # @return [Array<Usage>] The list of compute resource usages. attr_accessor :value # @return [String] The URI to fetch the next page of compute resource # usage information. Call ListNext() with this to fetch the next page of # compute resource usage information. attr_accessor :next_link # return [Proc] with next page method call. attr_accessor :next_method # # Gets the rest of the items for the request, enabling auto-pagination. # # @return [Array<Usage>] operation results. # def get_all_items items = @value page = self while page.next_link != nil && !page.next_link.strip.empty? do page = page.get_next_page items.concat(page.value) end items end # # Gets the next page of results. # # @return [ListUsagesResult] with next page content. # def get_next_page response = @next_method.call(@next_link).value! unless @next_method.nil? unless response.nil? @next_link = response.body.next_link @value = response.body.value self end end # # Mapper for ListUsagesResult class as Ruby Hash. # This will be used for serialization/deserialization. # def self.mapper() { client_side_validation: true, required: false, serialized_name: 'ListUsagesResult', type: { name: 'Composite', class_name: 'ListUsagesResult', model_properties: { value: { client_side_validation: true, required: true, serialized_name: 'value', type: { name: 'Sequence', element: { client_side_validation: true, required: false, serialized_name: 'UsageElementType', type: { name: 'Composite', class_name: 'Usage' } } } }, next_link: { client_side_validation: true, required: false, serialized_name: 'nextLink', type: { name: 'String' } } } } } end end end end
Azure/azure-sdk-for-ruby
management/azure_mgmt_compute/lib/2016-04-30-preview/generated/azure_mgmt_compute/models/list_usages_result.rb
Ruby
mit
2,848
# encoding: utf-8 # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. module Azure::Network::Mgmt::V2016_09_01 module Models # # Information gained from troubleshooting of specified resource. # class TroubleshootingDetails include MsRestAzure # @return [String] The id of the get troubleshoot operation. attr_accessor :id # @return [String] Reason type of failure. attr_accessor :reason_type # @return [String] A summary of troubleshooting. attr_accessor :summary # @return [String] Details on troubleshooting results. attr_accessor :detail # @return [Array<TroubleshootingRecommendedActions>] List of recommended # actions. attr_accessor :recommended_actions # # Mapper for TroubleshootingDetails class as Ruby Hash. # This will be used for serialization/deserialization. # def self.mapper() { client_side_validation: true, required: false, serialized_name: 'TroubleshootingDetails', type: { name: 'Composite', class_name: 'TroubleshootingDetails', model_properties: { id: { client_side_validation: true, required: false, serialized_name: 'id', type: { name: 'String' } }, reason_type: { client_side_validation: true, required: false, serialized_name: 'reasonType', type: { name: 'String' } }, summary: { client_side_validation: true, required: false, serialized_name: 'summary', type: { name: 'String' } }, detail: { client_side_validation: true, required: false, serialized_name: 'detail', type: { name: 'String' } }, recommended_actions: { client_side_validation: true, required: false, serialized_name: 'recommendedActions', type: { name: 'Sequence', element: { client_side_validation: true, required: false, serialized_name: 'TroubleshootingRecommendedActionsElementType', type: { name: 'Composite', class_name: 'TroubleshootingRecommendedActions' } } } } } } } end end end end
Azure/azure-sdk-for-ruby
management/azure_mgmt_network/lib/2016-09-01/generated/azure_mgmt_network/models/troubleshooting_details.rb
Ruby
mit
2,956
<!DOCTYPE html> <html> <head> <meta http-equiv="content-type" content="text/html;charset=UTF-8" /> <meta charset="utf-8" /> <title>Pages - Petugas Dashboard UI Kit</title> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" /> <link rel="apple-touch-icon" href="pages/ico/60.png"> <link rel="apple-touch-icon" sizes="76x76" href="pages/ico/76.png"> <link rel="apple-touch-icon" sizes="120x120" href="pages/ico/120.png"> <link rel="apple-touch-icon" sizes="152x152" href="pages/ico/152.png"> <link rel="icon" type="image/x-icon" href="favicon.ico" /> <meta name="apple-mobile-web-app-capable" content="yes"> <meta name="apple-touch-fullscreen" content="yes"> <meta name="apple-mobile-web-app-status-bar-style" content="default"> <meta content="" name="description" /> <meta content="" name="author" /> <link href="<?php echo base_url(); ?>assets/plugins/pace/pace-theme-flash.css" rel="stylesheet" type="text/css" /> <link href="<?php echo base_url(); ?>assets/plugins/boostrapv3/css/bootstrap.min.css" rel="stylesheet" type="text/css" /> <link href="<?php echo base_url(); ?>assets/plugins/font-awesome/css/font-awesome.css" rel="stylesheet" type="text/css" /> <link href="<?php echo base_url(); ?>assets/plugins/jquery-scrollbar/jquery.scrollbar.css" rel="stylesheet" type="text/css" media="screen" /> <link href="<?php echo base_url(); ?>assets/plugins/bootstrap-select2/select2.css" rel="stylesheet" type="text/css" media="screen" /> <link href="<?php echo base_url(); ?>assets/plugins/switchery/css/switchery.min.css" rel="stylesheet" type="text/css" media="screen" /> <link href="<?php echo base_url(); ?>assets/plugins/nvd3/nv.d3.min.css" rel="stylesheet" type="text/css" media="screen" /> <link href="<?php echo base_url(); ?>assets/plugins/mapplic/css/mapplic.css" rel="stylesheet" type="text/css" /> <link href="<?php echo base_url(); ?>assets/plugins/rickshaw/rickshaw.min.css" rel="stylesheet" type="text/css" /> <link href="<?php echo base_url(); ?>assets/plugins/bootstrap-datepicker/css/datepicker3.css" rel="stylesheet" type="text/css" media="screen"> <link href="<?php echo base_url(); ?>assets/plugins/jquery-metrojs/MetroJs.css" rel="stylesheet" type="text/css" media="screen" /> <link href="<?php echo base_url(); ?>pages/css/pages-icons.css" rel="stylesheet" type="text/css"> <link class="main-stylesheet" href="<?php echo base_url(); ?>pages/css/pages.css" rel="stylesheet" type="text/css" /> <link href="<?php echo base_url(); ?>assets/plugins/bootstrap-daterangepicker/daterangepicker-bs3.css" rel="stylesheet" type="text/css" media="screen"> <!--[if lte IE 9]> <link href="pages/css/ie9.css" rel="stylesheet" type="text/css" /> <![endif]--> <!--[if lt IE 9]> <link href="assets/plugins/mapplic/css/mapplic-ie.css" rel="stylesheet" type="text/css" /> <![endif]--> <script src="<?php echo base_url(); ?>assets/plugins/pace/pace.min.js" type="text/javascript"></script> <script src="<?php echo base_url(); ?>assets/plugins/jquery/jquery-1.11.1.min.js" type="text/javascript"></script> <script src="<?php echo base_url(); ?>assets/plugins/modernizr.custom.js" type="text/javascript"></script> <script src="<?php echo base_url(); ?>assets/plugins/boostrapv3/js/bootstrap.min.js" type="text/javascript"></script> <script src="<?php echo base_url(); ?>assets/plugins/jquery/jquery-easy.js" type="text/javascript"></script> <script src="<?php echo base_url(); ?>assets/plugins/jquery-unveil/jquery.unveil.min.js" type="text/javascript"></script> <script src="<?php echo base_url(); ?>assets/plugins/jquery-bez/jquery.bez.min.js"></script> <script src="<?php echo base_url(); ?>assets/plugins/jquery-ios-list/jquery.ioslist.min.js" type="text/javascript"></script> <script src="<?php echo base_url(); ?>assets/plugins/jquery-actual/jquery.actual.min.js"></script> <script src="<?php echo base_url(); ?>assets/plugins/jquery-scrollbar/jquery.scrollbar.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/plugins/bootstrap-select2/select2.min.js"></script> <script type="text/javascript" src="<?php echo base_url(); ?>assets/plugins/classie/classie.js"></script> <script src="<?php echo base_url(); ?>assets/plugins/switchery/js/switchery.min.js" type="text/javascript"></script> <script src="<?php echo base_url(); ?>assets/plugins/nvd3/lib/d3.v3.js" type="text/javascript"></script> <script src="<?php echo base_url(); ?>assets/plugins/nvd3/nv.d3.min.js" type="text/javascript"></script> <script src="<?php echo base_url(); ?>assets/plugins/nvd3/src/utils.js" type="text/javascript"></script> <script src="<?php echo base_url(); ?>assets/plugins/nvd3/src/tooltip.js" type="text/javascript"></script> <script src="<?php echo base_url(); ?>assets/plugins/nvd3/src/interactiveLayer.js" type="text/javascript"></script> <script src="<?php echo base_url(); ?>assets/plugins/nvd3/src/models/axis.js" type="text/javascript"></script> <script src="<?php echo base_url(); ?>assets/plugins/nvd3/src/models/line.js" type="text/javascript"></script> <script src="<?php echo base_url(); ?>assets/plugins/nvd3/src/models/lineWithFocusChart.js" type="text/javascript"></script> <script src="<?php echo base_url(); ?>assets/plugins/mapplic/js/hammer.js"></script> <script src="<?php echo base_url(); ?>assets/plugins/mapplic/js/jquery.mousewheel.js"></script> <script src="<?php echo base_url(); ?>assets/plugins/mapplic/js/mapplic.js"></script> <script src="<?php echo base_url(); ?>assets/plugins/jquery-validation/js/jquery.validate.min.js" type="text/javascript"></script> <!-- END VENDOR JS --> <!-- BEGIN CORE TEMPLATE JS --> <script src="<?php echo base_url(); ?>pages/js/pages.min.js"></script> <!-- END CORE TEMPLATE JS --> <!-- BEGIN PAGE LEVEL JS --> <!--<script src="<?php echo base_url(); ?>assets/js/dashboard.js" type="text/javascript"></script>--> <script src="<?php echo base_url(); ?>assets/js/scripts.js" type="text/javascript"></script> <!-- END PAGE LEVEL JS --> <script type="text/javascript"> window.onload = function() { // fix for windows 8 if (navigator.appVersion.indexOf("Windows NT 6.2") != -1) document.head.innerHTML += '<link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>pages/css/windows.chrome.fix.css" />' } </script> </head> <body class="fixed-header dashboard "> <!-- BEGIN SIDEBPANEL--> <nav class="page-sidebar" data-pages="sidebar"> <!-- BEGIN SIDEBAR MENU TOP TRAY CONTENT--> <div class="sidebar-overlay-slide from-top" id="appMenu"> <div class="row"> <div class="col-xs-6 no-padding"> <a href="#" class="p-l-40"><img src="<?php echo base_url(); ?>assets/img/demo/social_app.svg" alt="socail"> </a> </div> <div class="col-xs-6 no-padding"> <a href="#" class="p-l-10"><img src="<?php echo base_url(); ?>assets/img/demo/email_app.svg" alt="socail"> </a> </div> </div> <div class="row"> <div class="col-xs-6 m-t-20 no-padding"> <a href="#" class="p-l-40"><img src="<?php echo base_url(); ?>assets/img/demo/calendar_app.svg" alt="socail"> </a> </div> <div class="col-xs-6 m-t-20 no-padding"> <a href="#" class="p-l-10"><img src="<?php echo base_url(); ?>assets/img/demo/add_more.svg" alt="socail"> </a> </div> </div> </div> <!-- END SIDEBAR MENU TOP TRAY CONTENT--> <!-- BEGIN SIDEBAR MENU HEADER--> <div class="sidebar-header"> <img src="assets/img/logo_white.png" alt="logo" class="brand" data-src="<?php echo base_url(); ?>assets/img/logo_white.png" data-src-retina="<?php echo base_url(); ?>assets/img/logo_white_2x.png" width="78" height="22"> <div class="sidebar-header-controls"> <!-- <button type="button" class="btn btn-xs sidebar-slide-toggle btn-link m-l-20" data-pages-toggle="#appMenu"><i class="fa fa-angle-down fs-16"></i> </button> --> <button type="button" class="btn btn-link visible-lg-inline" data-toggle-pin="sidebar"><i class="fa fs-12"></i> </button> </div> </div> <!-- END SIDEBAR MENU HEADER--> <!-- START SIDEBAR MENU --> <div class="sidebar-menu"> <!-- BEGIN SIDEBAR MENU ITEMS--> <ul class="menu-items"> <li class="m-t-30 open"> <a href="Pembayaran" class="detailed"> <span class="title">Masuk</span> </a> <span class="icon-thumbnail bg-success"><i class="fa fa-sign-in"></i></span> </li> <li class="m-t-30 open"> <a href="Registrasi" class="detailed"> <span class="title">Pendaftaran</span> </a> <span class="icon-thumbnail"><i class="pg-plus_circle"></i></span> </li> </ul> <div class="clearfix"></div> </div> <!-- END SIDEBAR MENU --> </nav>
Vancrew/IMK
application/views/template/header_umum.php
PHP
mit
9,330
define(function(require) { var _ = require('underscore'), d3 = require('d3'); function isTime(type) { return _.contains(['time', 'timestamp', 'date'], type); } function isNum(type) { return _.contains(['num', 'int4', 'int', 'int8', 'float8', 'float', 'bigint'], type); } function isStr(type) { return _.contains(['varchar', 'text', 'str'], type); } function debugMode() { try { return !$("#fake-type > input[type=checkbox]").get()[0].checked; } catch(e) { return false; } } function negateClause(SQL) { if (!SQL) return null; if ($("#selection-type > input[type=checkbox]").get()[0].checked) return SQL; return "not(" + SQL + ")"; } // points: [ { yalias:,..., xalias: } ] // ycols: [ { col, alias, expr } ] function getYDomain(points, ycols) { var yaliases = _.pluck(ycols, 'alias'), yss = _.map(yaliases, function(yalias) { return _.pluck(points, yalias) }), ydomain = [Infinity, -Infinity]; _.each(yss, function(ys) { ys = _.filter(ys, _.isFinite); if (ys.length) { ydomain[0] = Math.min(ydomain[0], d3.min(ys)); ydomain[1] = Math.max(ydomain[1], d3.max(ys)); } }); return ydomain; } // assume getx(point) and point.range contain x values function getXDomain(points, type, getx) { var xdomain = null; if (isStr(type)) { xdomain = {}; _.each(points, function(d) { if (d.range) { _.each(d.range, function(o) { xdomain[o] = 1; }); } xdomain[getx(d)] = 1 ; }); xdomain = _.keys(xdomain); return xdomain; } var diff = 1; var xvals = []; _.each(points, function(d) { if (d.range) xvals.push.apply(xvals, d.range); xvals.push(getx(d)); }); xvals = _.reject(xvals, _.isNull); if (isNum(type)) { xvals = _.filter(xvals, _.isFinite); xdomain = [ d3.min(xvals), d3.max(xvals) ]; diff = 1; if (xdomain[0] != xdomain[1]) diff = (xdomain[1] - xdomain[0]) * 0.05; xdomain[0] -= diff; xdomain[1] += diff; } else if (isTime(type)) { xvals = _.map(xvals, function(v) { return new Date(v); }); xdomain = [ d3.min(xvals), d3.max(xvals) ]; diff = 1000*60*60*24; // 1 day if (xdomain[0] != xdomain[1]) diff = (xdomain[1] - xdomain[0]) * 0.05; xdomain[0] = new Date(+xdomain[0] - diff); xdomain[1] = new Date(+xdomain[1] + diff); } //console.log([type, 'diff', diff, 'domain', JSON.stringify(xdomain)]); return xdomain; } function mergeDomain(oldd, newd, type) { var defaultd = [Infinity, -Infinity]; if (isStr(type)) defaultd = []; if (oldd == null) return newd; if (isStr(type)) return _.union(oldd, newd); var ret = _.clone(oldd); if (!_.isNull(newd[0]) && (_.isFinite(newd[0]) || isTime(newd[0]))) ret[0] = d3.min([ret[0], newd[0]]); if (!_.isNull(newd[1]) && (_.isFinite(newd[1]) || isTime(newd[1]))) ret[1] = d3.max([ret[1], newd[1]]); return ret; } function estNumXTicks(xaxis, type, w) { var xscales = xaxis.scale(); var ex = 40.0/5; var xticks = 10; while(xticks > 1) { if (isStr(type)) { var nchars = d3.sum(_.times( Math.min(xticks, xscales.domain().length), function(idx){return (""+xscales.domain()[idx]).length+.8}) ) } else { var fmt = xscales.tickFormat(); var fmtlen = function(s) {return fmt(s).length+.8;}; var nchars = d3.sum(xscales.ticks(xticks), fmtlen); } if (ex*nchars < w) break; xticks--; } xticks = Math.max(1, +xticks.toFixed()); return xticks; } function setAxisLabels(axis, type, nticks) { var scales = axis.scale(); axis.ticks(nticks).tickSize(0,0); if (isStr(type)) { var skip = scales.domain().length / nticks; var idx = 0; var previdx = null; var tickvals = []; while (idx < scales.domain().length) { if (previdx == null || Math.floor(idx) > previdx) { tickvals.push(scales.domain()[Math.floor(idx)]) } idx += skip; } axis.tickValues(tickvals); } return axis; } function toWhereClause(col, type, vals) { if (!vals || vals.length == 0) return null; var SQL = null; var re = new RegExp("'", "gi"); if (isStr(type)) { SQL = []; if (_.contains(vals, null)) { SQL.push(col + " is null"); } var nonnulls = _.reject(vals, _.isNull); if (nonnulls.length == 1) { var v = nonnulls[0]; if (_.isString(v)) v = "'" + v.replace(re, "\\'") + "'"; SQL.push(col + " = " + v); } else if (nonnulls.length > 1) { vals = _.map(nonnulls, function(v) { if (_.isString(v)) return "'" + v.replace(re, "\\'") + "'"; return v; }); SQL.push(col + " in ("+vals.join(', ')+")"); } if (SQL.length == 0) SQL = null; else if (SQL.length == 1) SQL = SQL[0]; else SQL = "("+SQL.join(' or ')+")"; } else { if (isTime(type)) { if (type == 'time') { var val2s = function(v) { // the values could have already been string encoded. if (_.isDate(v)) return "'" + (new Date(v)).toLocaleTimeString() + "'"; return v; }; } else { var val2s = function(v) { if(_.isDate(v)) return "'" + (new Date(v)).toISOString() + "'"; return v; }; } //vals = _.map(vals, function(v) { return new Date(v)}); } else { var val2s = function(v) { return +v }; } if (vals.length == 1) { SQL = col + " = " + val2s(vals[0]); } else { SQL = [ val2s(d3.min(vals)) + " <= " + col, col + " <= " + val2s(d3.max(vals)) ].join(' and '); } } return SQL; } return { isTime: isTime, isNum: isNum, isStr: isStr, estNumXTicks: estNumXTicks, setAxisLabels: setAxisLabels, toWhereClause: toWhereClause, negateClause: negateClause, getXDomain: getXDomain, getYDomain: getYDomain, mergeDomain: mergeDomain, debugMode: debugMode } })
sirrice/dbwipes
dbwipes/static/js/summary/util.js
JavaScript
mit
6,474
Package.describe({ name: 'angular-compilers', version: '0.4.0', summary: 'Rollup, AOT, SCSS, HTML and TypeScript compilers for Angular Meteor', git: 'https://github.com/Urigo/angular-meteor/tree/master/atmosphere-packages/angular-compilers', documentation: 'README.md' }); Package.registerBuildPlugin({ name: 'Angular Compilers', sources: [ 'plugin/register.js' ], use: [ // Uses an external packages to get the actual compilers 'ecmascript@0.10.5', 'angular-typescript-compiler@0.4.0', 'angular-html-compiler@0.4.0', 'angular-scss-compiler@0.4.0' ] }); Package.onUse(function (api) { api.versionsFrom('1.11'); // Required in order to register plugins api.use('isobuild:compiler-plugin@1.0.0'); });
Urigo/angular-meteor
atmosphere-packages/angular-compilers/package.js
JavaScript
mit
780
namespace WithFormat.DateTime { public interface IYearFormatter { DateTimeFormatBuilder WithOneDigit(); DateTimeFormatBuilder WithTwoDigits(); DateTimeFormatBuilder WithAtLeastThreeDigits(); DateTimeFormatBuilder WithFourDigits(); DateTimeFormatBuilder WithFiveDigits(); DateTimeFormatBuilder WithDigits(int digits); } }
TheCrow1213/WithFormat
WithFormat/DateTime/IYearFormatter.cs
C#
mit
394