file_name
large_stringlengths 4
140
| prefix
large_stringlengths 0
39k
| suffix
large_stringlengths 0
36.1k
| middle
large_stringlengths 0
29.4k
| fim_type
large_stringclasses 4
values |
---|---|---|---|---|
app.module.ts
|
import { NgModule, ApplicationRef } from '@angular/core';
import { AppComponent } from './app.component';
import { removeNgStyles, createNewHosts } from '@angularclass/hmr';
import { BrowserModule } from '@angular/platform-browser';
import { CommonModule } from '@angular/common';
import { J3ComponentsModule } from '../src';
import { AccordionDemoComponent } from './components/accordion.component';
@NgModule({
imports: [
CommonModule,
BrowserModule,
J3ComponentsModule
],
declarations: [
AppComponent,
AccordionDemoComponent
],
bootstrap: [AppComponent]
})
export class AppModule {
|
(private appRef: ApplicationRef) { }
hmrOnDestroy(store) {
const cmpLocation = this.appRef.components.map(cmp => cmp.location.nativeElement);
store.disposeOldHosts = createNewHosts(cmpLocation);
removeNgStyles();
}
hmrAfterDestroy(store) {
store.disposeOldHosts();
delete store.disposeOldHosts;
}
}
|
constructor
|
identifier_name
|
app.module.ts
|
import { NgModule, ApplicationRef } from '@angular/core';
import { AppComponent } from './app.component';
import { removeNgStyles, createNewHosts } from '@angularclass/hmr';
import { BrowserModule } from '@angular/platform-browser';
|
import { J3ComponentsModule } from '../src';
import { AccordionDemoComponent } from './components/accordion.component';
@NgModule({
imports: [
CommonModule,
BrowserModule,
J3ComponentsModule
],
declarations: [
AppComponent,
AccordionDemoComponent
],
bootstrap: [AppComponent]
})
export class AppModule {
constructor(private appRef: ApplicationRef) { }
hmrOnDestroy(store) {
const cmpLocation = this.appRef.components.map(cmp => cmp.location.nativeElement);
store.disposeOldHosts = createNewHosts(cmpLocation);
removeNgStyles();
}
hmrAfterDestroy(store) {
store.disposeOldHosts();
delete store.disposeOldHosts;
}
}
|
import { CommonModule } from '@angular/common';
|
random_line_split
|
newExperiment.py
|
# -*- coding: utf-8 -*-
"""
@author: Jeff Cavner
@contact: [email protected]
@license: gpl2
@copyright: Copyright (C) 2014, University of Kansas Center for Research
Lifemapper Project, lifemapper [at] ku [dot] edu,
Biodiversity Institute,
1345 Jayhawk Boulevard, Lawrence, Kansas, 66045, USA
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at
your option) any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA.
"""
import os
import types
import zipfile
import numpy as np
from collections import namedtuple
from PyQt4.QtGui import *
from PyQt4.QtCore import QSettings, Qt, SIGNAL, QUrl
from qgis.core import *
from qgis.gui import *
from lifemapperTools.tools.ui_newExperimentDialog import Ui_Dialog
from lifemapperTools.tools.listPALayers import ListPALayersDialog
from lifemapperTools.tools.constructGrid import ConstructGridDialog
from lifemapperTools.tools.uploadLayers import UploadDialog
from lifemapperTools.tools.listBuckets import ListBucketsDialog
from lifemapperTools.tools.addSDMLayer import UploadSDMDialog
from lifemapperTools.common.pluginconstants import ListExperiments, GENERIC_REQUEST
from lifemapperTools.common.pluginconstants import QGISProject
from lifemapperTools.common.workspace import Workspace
from lifemapperTools.tools.radTable import RADTable
from lifemapperTools.tools.uploadTreeOTL import UploadTreeDialog
from lifemapperTools.common.communicate import Communicate
class NewExperimentDialog(QDialog, Ui_Dialog):
# .............................................................................
# Constructor
# .............................................................................
def __init__(self, iface, RADids=None, inputs=None, client=None, email=None):
QDialog.__init__(self)
#self.setWindowFlags(self.windowFlags() & Qt.WindowMinimizeButtonHint)
self.interface = iface
self.workspace = Workspace(self.interface,client)
self.checkExperiments()
self.setupUi()
self.client = client
#cc = self.rejectBut
#bok = self.acceptBut
self.expId = None
self.mapunits = None
self.keyvalues = {}
if email is not None:
self.keyvalues['email'] = email
#_Controller.__init__(self, iface, BASE_URL=ListExperiments.BASE_URL,
# STATUS_URL=ListExperiments.STATUS_URL,
# REST_URL=ListExperiments.REST_URL,
# cancel_close=cc, okayButton=bok, ids=RADids,
# initializeWithData=False, client=client)
# ..............................................................................
def _checkQgisProjForKey(self):
project = QgsProject.instance()
filename = str(project.fileName())
found = False
s = QSettings()
for key in s.allKeys():
if 'RADExpProj' in key:
value = str(s.value(key))
if value == filename:
found = True
expId = key.split('_')[1]
s.setValue("currentExpID", int(expId))
return found
# ..............................................................................
|
project path associated with that id. If there is a project path, it
triggers a save project. If there is no path, it asks a save as, and sets
the project path for the id. The last thing it does is to open a new
qgis project
"""
s = QSettings()
currentExpId = s.value("currentExpID",QGISProject.NOEXPID,type=int)
if currentExpId != QGISProject.NOEXPID:
currentpath = str(s.value("RADExpProj_"+str(currentExpId),
QGISProject.NOPROJECT))
if currentpath != QGISProject.NOPROJECT and currentpath != '':
self.interface.actionSaveProject().trigger()
else:
if len(QgsMapLayerRegistry.instance().mapLayers().items()) > 0:
#self.interface.actionSaveProjectAs().trigger()
self.workspace.saveQgsProjectAs(currentExpId)
# now actionNewProject
self.interface.actionNewProject().trigger()
s.setValue("currentExpID",QGISProject.NOEXPID)
else: # no experiment Id
# there is a case where a Qgis project can be opened but there is no
# current id, like after a sign out but that Qgis project belongs to an id, in that case it needs
# to start a new project
if len(QgsMapLayerRegistry.instance().mapLayers().items()) == 0 or self._checkQgisProjForKey():
self.interface.actionNewProject().trigger()
# ..............................................................................
#def accept(self):
#
#
# valid = self.validate()
# if self.expId is not None:
# self.openNewDialog()
# elif valid and self.expId is None:
# self.startThread(GENERIC_REQUEST,outputfunc = self.newExperimentCallBack,
# requestfunc=self.client.rad.postExperiment, client=self.client,
# inputs=self.keyvalues)
# elif not valid and self.expId is None:
# pass
# ..............................................................................
def postNewOpen(self,buttonValue):
valid = self.validate()
if self.expId is not None:
self.openNewDialog(buttonValue)
elif valid and self.expId is None:
try:
print self.keyvalues
exp = self.client.rad.postExperiment(**self.keyvalues)
except Exception, e:
message = "Error posting new experiment "+str(e)
msgBox = QMessageBox.information(self,
"Problem...",
message,
QMessageBox.Ok)
else:
self.newExperimentCallBack(exp,buttonValue)
elif not valid and self.expId is None:
pass
# ..............................................................................
def validate(self):
valid = True
message = ""
self.keyvalues['epsgCode'] = self.epsgEdit.text()
self.keyvalues['name'] = self.expNameEdit.text()
self.keyvalues['description'] = self.description.toPlainText()
epsg = self.epsgEdit.text()
#self.setMapUnitsFromEPSG(epsg=epsg)
experimentname = self.expNameEdit.text()
if len(experimentname) <= 0:
message = "Please supply a experiment name"
valid = False
elif len(epsg) <= 0:
message = "Please supply an EPSG code"
valid = False
else:
self.setMapUnitsFromEPSG(epsg=epsg)
if self.mapunits is None or self.mapunits == 'UnknownUnit':
message = "Invalid EPSG Code"
valid = False
if not valid:
msgBox = QMessageBox.information(self,
"Problem...",
message,
QMessageBox.Ok)
return valid
# ..............................................................................
def openProjSelectorSetEPSG(self):
"""
@summary: opens the stock qgis projection selector
and sets epsg edit field and set map units attribute
"""
projSelector = QgsGenericProjectionSelector(self)
dialog = projSelector.exec_()
EpsgCode = projSelector.selectedAuthId().replace('EPSG:','')
# some projections don't have epsg's
if dialog != 0:
if EpsgCode != 0: # will be zero if projection doesn't have an epsg
crs = QgsCoordinateReferenceSystem()
crs.createFromOgcWmsCrs( projSelector.selectedAuthId() )
mapunitscode = crs.mapUnits()
if mapunitscode == 0:
self.mapunits = 'meters'
elif mapunitscode == 1:
self.mapunits = 'feet'
elif mapunitscode == 2:
self.mapunits = 'dd'
self.epsgEdit.setText(str(EpsgCode))
else:
# error message saying that the users chosen projection doesn't have a epsg
self.mapunits = None
message = "The projection you have chosen does not have an epsg code"
msgBox = QMessageBox.information(self,
"Problem...",
message,
QMessageBox.Ok)
else:
self.mapunits = None
# ..............................................................................
def verifyEmail(self,email):
valid = True
if '@' in email:
atIndex = email.index('@')
domainsubstring = email[atIndex+1:]
if '.' in domainsubstring:
if domainsubstring.index('.') == 0:
valid = False
else:
valid = False
else:
valid = False
return valid
# ..............................................................................
def cleanInputGridLayout(self):
"""@summary: cleans out the input grid layout"""
if not(self.gridLayout_input.isEmpty()):
for childindex in range(0,self.gridLayout_input.count()):
item = self.gridLayout_input.takeAt(0)
if not(type(item) is types.NoneType):
item.widget().deleteLater()
self.gridLayout_input.update()
# ..............................................................................
def setMapUnitsFromEPSG(self,epsg=None):
crs = QgsCoordinateReferenceSystem()
if epsg:
crs.createFromOgcWmsCrs("EPSG:%s" % (str(epsg)))
else:
crs.createFromOgcWmsCrs("EPSG:%s" % (str(self.expEPSG)))
mapunitscode = crs.mapUnits()
if mapunitscode == 0:
self.mapunits = 'meters'
elif mapunitscode == 1:
self.mapunits = 'feet'
elif mapunitscode == 2:
self.mapunits = 'dd'
elif mapunitscode == 3:
self.mapunits = 'UnknownUnit'
# ..............................................................................
# ..............................................................................
def newExperimentCallBack(self, item, buttonValue):
"""
@summary: when a new expid comes back it gets saved to settings as
currentExpID, then calls openNewDialog
"""
self.epsgEdit.setEnabled(False)
self.expNameEdit.setEnabled(False)
self.description.setEnabled(False)
self.emptyRadio.setEnabled(False)
self.expId = item.id
self.expEPSG = item.epsgcode
if self.mapunits is None:
self.setMapUnitsFromEPSG()
self.setNewExperiment()
Communicate.instance().activateRADExp.emit(int(self.expId),self.expEPSG,self.mapunits)
self.openNewDialog(buttonValue)
# ..............................................................................
def setNewExperiment(self):
"""
@summary: sets the currentExpID key in settings and creates a project folder in workspace
and quietly save the new QGIS project to it
"""
try:
s = QSettings()
s.setValue("currentExpID", int(self.expId))
self.workspace.saveQgsProjectAs(self.expId)
except:
QMessageBox.warning(self,"status: ",
"Could not save expId to settings")
# ..............................................................................
def openNewDialog(self,buttonValue):
inputs = {'expId':self.expId}
experimentname = self.keyvalues['name']
if buttonValue == "Grid":
self.constructGridDialog = ConstructGridDialog( self.interface,
inputs = inputs,
client = self.client,
epsg=self.expEPSG,
mapunits=self.mapunits)
self.setModal(False)
self.constructGridDialog.show()
self.listBucketsRadio.setEnabled(True)
elif buttonValue == "SDM":
SDMDialog = UploadSDMDialog(self.interface,
inputs = inputs,
client = self.client,
epsg=self.expEPSG,
experimentname = experimentname,
mapunits=self.mapunits)
self.setModal(False) # has to be closed to continue
SDMDialog.exec_()
self.listPALayersRadio.setEnabled(True)
elif buttonValue == "Tree":
try:
items = self.client.rad.getPALayers(self.expId)
except:
items = None
message = "There is a problem with the layer listing service"
msgBox = QMessageBox.information(self,
"Problem...",
message,
QMessageBox.Ok)
else:
if len(items) != 0:
message = "You already have layers in this experiment. You must begin an experiment with trees and their layers to use a tree."
msgBox = QMessageBox.information(self,
"Problem...",
message,
QMessageBox.Ok)
elif len(items) == 0:
treeDialog = UploadTreeDialog(self.interface,
inputs = inputs,
client = self.client,
epsg = self.expEPSG,
experimentname=experimentname,
mapunits=self.mapunits)
self.setModal(False)
treeDialog.exec_()
self.listPALayersRadio.setEnabled(True)
elif buttonValue == "Local":
d = UploadDialog(self.interface,
inputs = inputs,
client = self.client,
epsg=self.expEPSG,
experimentname=experimentname,
mapunits=self.mapunits)
d.exec_()
self.listPALayersRadio.setEnabled(True)
elif buttonValue == "Empty":
pass
elif buttonValue == "ListBuckets":
d = ListBucketsDialog(self.interface, inputs=inputs,
client= self.client, epsg=self.expEPSG,
mapunits=self.mapunits)
d.exec_()
elif buttonValue == "ListLayers":
d = ListPALayersDialog(self.interface, inputs=inputs,
client= self.client, epsg=self.expEPSG,
mapunits=self.mapunits)
d.exec_()
#self.acceptBut.setEnabled( True )
# ..............................................................................
def help(self):
self.help = QWidget()
self.help.setWindowTitle('Lifemapper Help')
self.help.resize(600, 400)
self.help.setMinimumSize(600,400)
self.help.setMaximumSize(1000,1000)
layout = QVBoxLayout()
helpDialog = QTextBrowser()
helpDialog.setOpenExternalLinks(True)
#helpDialog.setSearchPaths(['documents'])
helppath = os.path.dirname(os.path.realpath(__file__))+'/documents/help.html'
helpDialog.setSource(QUrl.fromLocalFile(helppath))
helpDialog.scrollToAnchor('newRADExperiment')
layout.addWidget(helpDialog)
self.help.setLayout(layout)
if self.isModal():
self.setModal(False)
self.help.show()
if __name__ == "__main__":
#
import sys
#import_path = "/home/jcavner/workspace/lm3/components/LmClient/LmQGIS/V2/lifemapperTools/"
#sys.path.append(os.path.join(import_path, 'LmShared'))
###
#configPath = os.path.join(import_path, 'config', 'config.ini')
###
#os.environ["LIFEMAPPER_CONFIG_FILE"] = configPath
#from LmClient.lmClientLib import LMClient
#client = LMClient(userId='blank', pwd='blank')
qApp = QApplication(sys.argv)
d = NewExperimentDialog(None)#,experimentId=596106
d.show()
sys.exit(qApp.exec_())
|
def checkExperiments(self):
"""
@summary: gets the current expId, if there is one it gets the current
|
random_line_split
|
newExperiment.py
|
# -*- coding: utf-8 -*-
"""
@author: Jeff Cavner
@contact: [email protected]
@license: gpl2
@copyright: Copyright (C) 2014, University of Kansas Center for Research
Lifemapper Project, lifemapper [at] ku [dot] edu,
Biodiversity Institute,
1345 Jayhawk Boulevard, Lawrence, Kansas, 66045, USA
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at
your option) any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA.
"""
import os
import types
import zipfile
import numpy as np
from collections import namedtuple
from PyQt4.QtGui import *
from PyQt4.QtCore import QSettings, Qt, SIGNAL, QUrl
from qgis.core import *
from qgis.gui import *
from lifemapperTools.tools.ui_newExperimentDialog import Ui_Dialog
from lifemapperTools.tools.listPALayers import ListPALayersDialog
from lifemapperTools.tools.constructGrid import ConstructGridDialog
from lifemapperTools.tools.uploadLayers import UploadDialog
from lifemapperTools.tools.listBuckets import ListBucketsDialog
from lifemapperTools.tools.addSDMLayer import UploadSDMDialog
from lifemapperTools.common.pluginconstants import ListExperiments, GENERIC_REQUEST
from lifemapperTools.common.pluginconstants import QGISProject
from lifemapperTools.common.workspace import Workspace
from lifemapperTools.tools.radTable import RADTable
from lifemapperTools.tools.uploadTreeOTL import UploadTreeDialog
from lifemapperTools.common.communicate import Communicate
class NewExperimentDialog(QDialog, Ui_Dialog):
# .............................................................................
# Constructor
# .............................................................................
def __init__(self, iface, RADids=None, inputs=None, client=None, email=None):
QDialog.__init__(self)
#self.setWindowFlags(self.windowFlags() & Qt.WindowMinimizeButtonHint)
self.interface = iface
self.workspace = Workspace(self.interface,client)
self.checkExperiments()
self.setupUi()
self.client = client
#cc = self.rejectBut
#bok = self.acceptBut
self.expId = None
self.mapunits = None
self.keyvalues = {}
if email is not None:
self.keyvalues['email'] = email
#_Controller.__init__(self, iface, BASE_URL=ListExperiments.BASE_URL,
# STATUS_URL=ListExperiments.STATUS_URL,
# REST_URL=ListExperiments.REST_URL,
# cancel_close=cc, okayButton=bok, ids=RADids,
# initializeWithData=False, client=client)
# ..............................................................................
def _checkQgisProjForKey(self):
project = QgsProject.instance()
filename = str(project.fileName())
found = False
s = QSettings()
for key in s.allKeys():
if 'RADExpProj' in key:
value = str(s.value(key))
if value == filename:
found = True
expId = key.split('_')[1]
s.setValue("currentExpID", int(expId))
return found
# ..............................................................................
def checkExperiments(self):
"""
@summary: gets the current expId, if there is one it gets the current
project path associated with that id. If there is a project path, it
triggers a save project. If there is no path, it asks a save as, and sets
the project path for the id. The last thing it does is to open a new
qgis project
"""
s = QSettings()
currentExpId = s.value("currentExpID",QGISProject.NOEXPID,type=int)
if currentExpId != QGISProject.NOEXPID:
currentpath = str(s.value("RADExpProj_"+str(currentExpId),
QGISProject.NOPROJECT))
if currentpath != QGISProject.NOPROJECT and currentpath != '':
self.interface.actionSaveProject().trigger()
else:
if len(QgsMapLayerRegistry.instance().mapLayers().items()) > 0:
#self.interface.actionSaveProjectAs().trigger()
self.workspace.saveQgsProjectAs(currentExpId)
# now actionNewProject
self.interface.actionNewProject().trigger()
s.setValue("currentExpID",QGISProject.NOEXPID)
else: # no experiment Id
# there is a case where a Qgis project can be opened but there is no
# current id, like after a sign out but that Qgis project belongs to an id, in that case it needs
# to start a new project
if len(QgsMapLayerRegistry.instance().mapLayers().items()) == 0 or self._checkQgisProjForKey():
self.interface.actionNewProject().trigger()
# ..............................................................................
#def accept(self):
#
#
# valid = self.validate()
# if self.expId is not None:
# self.openNewDialog()
# elif valid and self.expId is None:
# self.startThread(GENERIC_REQUEST,outputfunc = self.newExperimentCallBack,
# requestfunc=self.client.rad.postExperiment, client=self.client,
# inputs=self.keyvalues)
# elif not valid and self.expId is None:
# pass
# ..............................................................................
def postNewOpen(self,buttonValue):
valid = self.validate()
if self.expId is not None:
self.openNewDialog(buttonValue)
elif valid and self.expId is None:
try:
print self.keyvalues
exp = self.client.rad.postExperiment(**self.keyvalues)
except Exception, e:
message = "Error posting new experiment "+str(e)
msgBox = QMessageBox.information(self,
"Problem...",
message,
QMessageBox.Ok)
else:
self.newExperimentCallBack(exp,buttonValue)
elif not valid and self.expId is None:
pass
# ..............................................................................
def validate(self):
valid = True
message = ""
self.keyvalues['epsgCode'] = self.epsgEdit.text()
self.keyvalues['name'] = self.expNameEdit.text()
self.keyvalues['description'] = self.description.toPlainText()
epsg = self.epsgEdit.text()
#self.setMapUnitsFromEPSG(epsg=epsg)
experimentname = self.expNameEdit.text()
if len(experimentname) <= 0:
message = "Please supply a experiment name"
valid = False
elif len(epsg) <= 0:
message = "Please supply an EPSG code"
valid = False
else:
self.setMapUnitsFromEPSG(epsg=epsg)
if self.mapunits is None or self.mapunits == 'UnknownUnit':
message = "Invalid EPSG Code"
valid = False
if not valid:
msgBox = QMessageBox.information(self,
"Problem...",
message,
QMessageBox.Ok)
return valid
# ..............................................................................
def openProjSelectorSetEPSG(self):
"""
@summary: opens the stock qgis projection selector
and sets epsg edit field and set map units attribute
"""
projSelector = QgsGenericProjectionSelector(self)
dialog = projSelector.exec_()
EpsgCode = projSelector.selectedAuthId().replace('EPSG:','')
# some projections don't have epsg's
if dialog != 0:
if EpsgCode != 0: # will be zero if projection doesn't have an epsg
crs = QgsCoordinateReferenceSystem()
crs.createFromOgcWmsCrs( projSelector.selectedAuthId() )
mapunitscode = crs.mapUnits()
if mapunitscode == 0:
self.mapunits = 'meters'
elif mapunitscode == 1:
self.mapunits = 'feet'
elif mapunitscode == 2:
self.mapunits = 'dd'
self.epsgEdit.setText(str(EpsgCode))
else:
# error message saying that the users chosen projection doesn't have a epsg
self.mapunits = None
message = "The projection you have chosen does not have an epsg code"
msgBox = QMessageBox.information(self,
"Problem...",
message,
QMessageBox.Ok)
else:
self.mapunits = None
# ..............................................................................
def verifyEmail(self,email):
valid = True
if '@' in email:
atIndex = email.index('@')
domainsubstring = email[atIndex+1:]
if '.' in domainsubstring:
if domainsubstring.index('.') == 0:
valid = False
else:
valid = False
else:
valid = False
return valid
# ..............................................................................
def cleanInputGridLayout(self):
"""@summary: cleans out the input grid layout"""
if not(self.gridLayout_input.isEmpty()):
for childindex in range(0,self.gridLayout_input.count()):
item = self.gridLayout_input.takeAt(0)
if not(type(item) is types.NoneType):
item.widget().deleteLater()
self.gridLayout_input.update()
# ..............................................................................
def setMapUnitsFromEPSG(self,epsg=None):
crs = QgsCoordinateReferenceSystem()
if epsg:
crs.createFromOgcWmsCrs("EPSG:%s" % (str(epsg)))
else:
crs.createFromOgcWmsCrs("EPSG:%s" % (str(self.expEPSG)))
mapunitscode = crs.mapUnits()
if mapunitscode == 0:
self.mapunits = 'meters'
elif mapunitscode == 1:
self.mapunits = 'feet'
elif mapunitscode == 2:
self.mapunits = 'dd'
elif mapunitscode == 3:
self.mapunits = 'UnknownUnit'
# ..............................................................................
# ..............................................................................
def newExperimentCallBack(self, item, buttonValue):
"""
@summary: when a new expid comes back it gets saved to settings as
currentExpID, then calls openNewDialog
"""
self.epsgEdit.setEnabled(False)
self.expNameEdit.setEnabled(False)
self.description.setEnabled(False)
self.emptyRadio.setEnabled(False)
self.expId = item.id
self.expEPSG = item.epsgcode
if self.mapunits is None:
self.setMapUnitsFromEPSG()
self.setNewExperiment()
Communicate.instance().activateRADExp.emit(int(self.expId),self.expEPSG,self.mapunits)
self.openNewDialog(buttonValue)
# ..............................................................................
def setNewExperiment(self):
"""
@summary: sets the currentExpID key in settings and creates a project folder in workspace
and quietly save the new QGIS project to it
"""
try:
s = QSettings()
s.setValue("currentExpID", int(self.expId))
self.workspace.saveQgsProjectAs(self.expId)
except:
QMessageBox.warning(self,"status: ",
"Could not save expId to settings")
# ..............................................................................
def openNewDialog(self,buttonValue):
inputs = {'expId':self.expId}
experimentname = self.keyvalues['name']
if buttonValue == "Grid":
self.constructGridDialog = ConstructGridDialog( self.interface,
inputs = inputs,
client = self.client,
epsg=self.expEPSG,
mapunits=self.mapunits)
self.setModal(False)
self.constructGridDialog.show()
self.listBucketsRadio.setEnabled(True)
elif buttonValue == "SDM":
SDMDialog = UploadSDMDialog(self.interface,
inputs = inputs,
client = self.client,
epsg=self.expEPSG,
experimentname = experimentname,
mapunits=self.mapunits)
self.setModal(False) # has to be closed to continue
SDMDialog.exec_()
self.listPALayersRadio.setEnabled(True)
elif buttonValue == "Tree":
try:
items = self.client.rad.getPALayers(self.expId)
except:
items = None
message = "There is a problem with the layer listing service"
msgBox = QMessageBox.information(self,
"Problem...",
message,
QMessageBox.Ok)
else:
if len(items) != 0:
message = "You already have layers in this experiment. You must begin an experiment with trees and their layers to use a tree."
msgBox = QMessageBox.information(self,
"Problem...",
message,
QMessageBox.Ok)
elif len(items) == 0:
treeDialog = UploadTreeDialog(self.interface,
inputs = inputs,
client = self.client,
epsg = self.expEPSG,
experimentname=experimentname,
mapunits=self.mapunits)
self.setModal(False)
treeDialog.exec_()
self.listPALayersRadio.setEnabled(True)
elif buttonValue == "Local":
|
elif buttonValue == "Empty":
pass
elif buttonValue == "ListBuckets":
d = ListBucketsDialog(self.interface, inputs=inputs,
client= self.client, epsg=self.expEPSG,
mapunits=self.mapunits)
d.exec_()
elif buttonValue == "ListLayers":
d = ListPALayersDialog(self.interface, inputs=inputs,
client= self.client, epsg=self.expEPSG,
mapunits=self.mapunits)
d.exec_()
#self.acceptBut.setEnabled( True )
# ..............................................................................
def help(self):
self.help = QWidget()
self.help.setWindowTitle('Lifemapper Help')
self.help.resize(600, 400)
self.help.setMinimumSize(600,400)
self.help.setMaximumSize(1000,1000)
layout = QVBoxLayout()
helpDialog = QTextBrowser()
helpDialog.setOpenExternalLinks(True)
#helpDialog.setSearchPaths(['documents'])
helppath = os.path.dirname(os.path.realpath(__file__))+'/documents/help.html'
helpDialog.setSource(QUrl.fromLocalFile(helppath))
helpDialog.scrollToAnchor('newRADExperiment')
layout.addWidget(helpDialog)
self.help.setLayout(layout)
if self.isModal():
self.setModal(False)
self.help.show()
if __name__ == "__main__":
#
import sys
#import_path = "/home/jcavner/workspace/lm3/components/LmClient/LmQGIS/V2/lifemapperTools/"
#sys.path.append(os.path.join(import_path, 'LmShared'))
###
#configPath = os.path.join(import_path, 'config', 'config.ini')
###
#os.environ["LIFEMAPPER_CONFIG_FILE"] = configPath
#from LmClient.lmClientLib import LMClient
#client = LMClient(userId='blank', pwd='blank')
qApp = QApplication(sys.argv)
d = NewExperimentDialog(None)#,experimentId=596106
d.show()
sys.exit(qApp.exec_())
|
d = UploadDialog(self.interface,
inputs = inputs,
client = self.client,
epsg=self.expEPSG,
experimentname=experimentname,
mapunits=self.mapunits)
d.exec_()
self.listPALayersRadio.setEnabled(True)
|
conditional_block
|
newExperiment.py
|
# -*- coding: utf-8 -*-
"""
@author: Jeff Cavner
@contact: [email protected]
@license: gpl2
@copyright: Copyright (C) 2014, University of Kansas Center for Research
Lifemapper Project, lifemapper [at] ku [dot] edu,
Biodiversity Institute,
1345 Jayhawk Boulevard, Lawrence, Kansas, 66045, USA
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at
your option) any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA.
"""
import os
import types
import zipfile
import numpy as np
from collections import namedtuple
from PyQt4.QtGui import *
from PyQt4.QtCore import QSettings, Qt, SIGNAL, QUrl
from qgis.core import *
from qgis.gui import *
from lifemapperTools.tools.ui_newExperimentDialog import Ui_Dialog
from lifemapperTools.tools.listPALayers import ListPALayersDialog
from lifemapperTools.tools.constructGrid import ConstructGridDialog
from lifemapperTools.tools.uploadLayers import UploadDialog
from lifemapperTools.tools.listBuckets import ListBucketsDialog
from lifemapperTools.tools.addSDMLayer import UploadSDMDialog
from lifemapperTools.common.pluginconstants import ListExperiments, GENERIC_REQUEST
from lifemapperTools.common.pluginconstants import QGISProject
from lifemapperTools.common.workspace import Workspace
from lifemapperTools.tools.radTable import RADTable
from lifemapperTools.tools.uploadTreeOTL import UploadTreeDialog
from lifemapperTools.common.communicate import Communicate
class NewExperimentDialog(QDialog, Ui_Dialog):
# .............................................................................
# Constructor
# .............................................................................
def __init__(self, iface, RADids=None, inputs=None, client=None, email=None):
QDialog.__init__(self)
#self.setWindowFlags(self.windowFlags() & Qt.WindowMinimizeButtonHint)
self.interface = iface
self.workspace = Workspace(self.interface,client)
self.checkExperiments()
self.setupUi()
self.client = client
#cc = self.rejectBut
#bok = self.acceptBut
self.expId = None
self.mapunits = None
self.keyvalues = {}
if email is not None:
self.keyvalues['email'] = email
#_Controller.__init__(self, iface, BASE_URL=ListExperiments.BASE_URL,
# STATUS_URL=ListExperiments.STATUS_URL,
# REST_URL=ListExperiments.REST_URL,
# cancel_close=cc, okayButton=bok, ids=RADids,
# initializeWithData=False, client=client)
# ..............................................................................
def _checkQgisProjForKey(self):
project = QgsProject.instance()
filename = str(project.fileName())
found = False
s = QSettings()
for key in s.allKeys():
if 'RADExpProj' in key:
value = str(s.value(key))
if value == filename:
found = True
expId = key.split('_')[1]
s.setValue("currentExpID", int(expId))
return found
# ..............................................................................
def checkExperiments(self):
"""
@summary: gets the current expId, if there is one it gets the current
project path associated with that id. If there is a project path, it
triggers a save project. If there is no path, it asks a save as, and sets
the project path for the id. The last thing it does is to open a new
qgis project
"""
s = QSettings()
currentExpId = s.value("currentExpID",QGISProject.NOEXPID,type=int)
if currentExpId != QGISProject.NOEXPID:
currentpath = str(s.value("RADExpProj_"+str(currentExpId),
QGISProject.NOPROJECT))
if currentpath != QGISProject.NOPROJECT and currentpath != '':
self.interface.actionSaveProject().trigger()
else:
if len(QgsMapLayerRegistry.instance().mapLayers().items()) > 0:
#self.interface.actionSaveProjectAs().trigger()
self.workspace.saveQgsProjectAs(currentExpId)
# now actionNewProject
self.interface.actionNewProject().trigger()
s.setValue("currentExpID",QGISProject.NOEXPID)
else: # no experiment Id
# there is a case where a Qgis project can be opened but there is no
# current id, like after a sign out but that Qgis project belongs to an id, in that case it needs
# to start a new project
if len(QgsMapLayerRegistry.instance().mapLayers().items()) == 0 or self._checkQgisProjForKey():
self.interface.actionNewProject().trigger()
# ..............................................................................
#def accept(self):
#
#
# valid = self.validate()
# if self.expId is not None:
# self.openNewDialog()
# elif valid and self.expId is None:
# self.startThread(GENERIC_REQUEST,outputfunc = self.newExperimentCallBack,
# requestfunc=self.client.rad.postExperiment, client=self.client,
# inputs=self.keyvalues)
# elif not valid and self.expId is None:
# pass
# ..............................................................................
def postNewOpen(self,buttonValue):
valid = self.validate()
if self.expId is not None:
self.openNewDialog(buttonValue)
elif valid and self.expId is None:
try:
print self.keyvalues
exp = self.client.rad.postExperiment(**self.keyvalues)
except Exception, e:
message = "Error posting new experiment "+str(e)
msgBox = QMessageBox.information(self,
"Problem...",
message,
QMessageBox.Ok)
else:
self.newExperimentCallBack(exp,buttonValue)
elif not valid and self.expId is None:
pass
# ..............................................................................
def validate(self):
valid = True
message = ""
self.keyvalues['epsgCode'] = self.epsgEdit.text()
self.keyvalues['name'] = self.expNameEdit.text()
self.keyvalues['description'] = self.description.toPlainText()
epsg = self.epsgEdit.text()
#self.setMapUnitsFromEPSG(epsg=epsg)
experimentname = self.expNameEdit.text()
if len(experimentname) <= 0:
message = "Please supply a experiment name"
valid = False
elif len(epsg) <= 0:
message = "Please supply an EPSG code"
valid = False
else:
self.setMapUnitsFromEPSG(epsg=epsg)
if self.mapunits is None or self.mapunits == 'UnknownUnit':
message = "Invalid EPSG Code"
valid = False
if not valid:
msgBox = QMessageBox.information(self,
"Problem...",
message,
QMessageBox.Ok)
return valid
# ..............................................................................
def openProjSelectorSetEPSG(self):
"""
@summary: opens the stock qgis projection selector
and sets epsg edit field and set map units attribute
"""
projSelector = QgsGenericProjectionSelector(self)
dialog = projSelector.exec_()
EpsgCode = projSelector.selectedAuthId().replace('EPSG:','')
# some projections don't have epsg's
if dialog != 0:
if EpsgCode != 0: # will be zero if projection doesn't have an epsg
crs = QgsCoordinateReferenceSystem()
crs.createFromOgcWmsCrs( projSelector.selectedAuthId() )
mapunitscode = crs.mapUnits()
if mapunitscode == 0:
self.mapunits = 'meters'
elif mapunitscode == 1:
self.mapunits = 'feet'
elif mapunitscode == 2:
self.mapunits = 'dd'
self.epsgEdit.setText(str(EpsgCode))
else:
# error message saying that the users chosen projection doesn't have a epsg
self.mapunits = None
message = "The projection you have chosen does not have an epsg code"
msgBox = QMessageBox.information(self,
"Problem...",
message,
QMessageBox.Ok)
else:
self.mapunits = None
# ..............................................................................
def verifyEmail(self,email):
valid = True
if '@' in email:
atIndex = email.index('@')
domainsubstring = email[atIndex+1:]
if '.' in domainsubstring:
if domainsubstring.index('.') == 0:
valid = False
else:
valid = False
else:
valid = False
return valid
# ..............................................................................
def cleanInputGridLayout(self):
"""@summary: cleans out the input grid layout"""
if not(self.gridLayout_input.isEmpty()):
for childindex in range(0,self.gridLayout_input.count()):
item = self.gridLayout_input.takeAt(0)
if not(type(item) is types.NoneType):
item.widget().deleteLater()
self.gridLayout_input.update()
# ..............................................................................
def setMapUnitsFromEPSG(self,epsg=None):
crs = QgsCoordinateReferenceSystem()
if epsg:
crs.createFromOgcWmsCrs("EPSG:%s" % (str(epsg)))
else:
crs.createFromOgcWmsCrs("EPSG:%s" % (str(self.expEPSG)))
mapunitscode = crs.mapUnits()
if mapunitscode == 0:
self.mapunits = 'meters'
elif mapunitscode == 1:
self.mapunits = 'feet'
elif mapunitscode == 2:
self.mapunits = 'dd'
elif mapunitscode == 3:
self.mapunits = 'UnknownUnit'
# ..............................................................................
# ..............................................................................
def newExperimentCallBack(self, item, buttonValue):
"""
@summary: when a new expid comes back it gets saved to settings as
currentExpID, then calls openNewDialog
"""
self.epsgEdit.setEnabled(False)
self.expNameEdit.setEnabled(False)
self.description.setEnabled(False)
self.emptyRadio.setEnabled(False)
self.expId = item.id
self.expEPSG = item.epsgcode
if self.mapunits is None:
self.setMapUnitsFromEPSG()
self.setNewExperiment()
Communicate.instance().activateRADExp.emit(int(self.expId),self.expEPSG,self.mapunits)
self.openNewDialog(buttonValue)
# ..............................................................................
def setNewExperiment(self):
"""
@summary: sets the currentExpID key in settings and creates a project folder in workspace
and quietly save the new QGIS project to it
"""
try:
s = QSettings()
s.setValue("currentExpID", int(self.expId))
self.workspace.saveQgsProjectAs(self.expId)
except:
QMessageBox.warning(self,"status: ",
"Could not save expId to settings")
# ..............................................................................
def
|
(self,buttonValue):
inputs = {'expId':self.expId}
experimentname = self.keyvalues['name']
if buttonValue == "Grid":
self.constructGridDialog = ConstructGridDialog( self.interface,
inputs = inputs,
client = self.client,
epsg=self.expEPSG,
mapunits=self.mapunits)
self.setModal(False)
self.constructGridDialog.show()
self.listBucketsRadio.setEnabled(True)
elif buttonValue == "SDM":
SDMDialog = UploadSDMDialog(self.interface,
inputs = inputs,
client = self.client,
epsg=self.expEPSG,
experimentname = experimentname,
mapunits=self.mapunits)
self.setModal(False) # has to be closed to continue
SDMDialog.exec_()
self.listPALayersRadio.setEnabled(True)
elif buttonValue == "Tree":
try:
items = self.client.rad.getPALayers(self.expId)
except:
items = None
message = "There is a problem with the layer listing service"
msgBox = QMessageBox.information(self,
"Problem...",
message,
QMessageBox.Ok)
else:
if len(items) != 0:
message = "You already have layers in this experiment. You must begin an experiment with trees and their layers to use a tree."
msgBox = QMessageBox.information(self,
"Problem...",
message,
QMessageBox.Ok)
elif len(items) == 0:
treeDialog = UploadTreeDialog(self.interface,
inputs = inputs,
client = self.client,
epsg = self.expEPSG,
experimentname=experimentname,
mapunits=self.mapunits)
self.setModal(False)
treeDialog.exec_()
self.listPALayersRadio.setEnabled(True)
elif buttonValue == "Local":
d = UploadDialog(self.interface,
inputs = inputs,
client = self.client,
epsg=self.expEPSG,
experimentname=experimentname,
mapunits=self.mapunits)
d.exec_()
self.listPALayersRadio.setEnabled(True)
elif buttonValue == "Empty":
pass
elif buttonValue == "ListBuckets":
d = ListBucketsDialog(self.interface, inputs=inputs,
client= self.client, epsg=self.expEPSG,
mapunits=self.mapunits)
d.exec_()
elif buttonValue == "ListLayers":
d = ListPALayersDialog(self.interface, inputs=inputs,
client= self.client, epsg=self.expEPSG,
mapunits=self.mapunits)
d.exec_()
#self.acceptBut.setEnabled( True )
# ..............................................................................
def help(self):
self.help = QWidget()
self.help.setWindowTitle('Lifemapper Help')
self.help.resize(600, 400)
self.help.setMinimumSize(600,400)
self.help.setMaximumSize(1000,1000)
layout = QVBoxLayout()
helpDialog = QTextBrowser()
helpDialog.setOpenExternalLinks(True)
#helpDialog.setSearchPaths(['documents'])
helppath = os.path.dirname(os.path.realpath(__file__))+'/documents/help.html'
helpDialog.setSource(QUrl.fromLocalFile(helppath))
helpDialog.scrollToAnchor('newRADExperiment')
layout.addWidget(helpDialog)
self.help.setLayout(layout)
if self.isModal():
self.setModal(False)
self.help.show()
if __name__ == "__main__":
#
import sys
#import_path = "/home/jcavner/workspace/lm3/components/LmClient/LmQGIS/V2/lifemapperTools/"
#sys.path.append(os.path.join(import_path, 'LmShared'))
###
#configPath = os.path.join(import_path, 'config', 'config.ini')
###
#os.environ["LIFEMAPPER_CONFIG_FILE"] = configPath
#from LmClient.lmClientLib import LMClient
#client = LMClient(userId='blank', pwd='blank')
qApp = QApplication(sys.argv)
d = NewExperimentDialog(None)#,experimentId=596106
d.show()
sys.exit(qApp.exec_())
|
openNewDialog
|
identifier_name
|
newExperiment.py
|
# -*- coding: utf-8 -*-
"""
@author: Jeff Cavner
@contact: [email protected]
@license: gpl2
@copyright: Copyright (C) 2014, University of Kansas Center for Research
Lifemapper Project, lifemapper [at] ku [dot] edu,
Biodiversity Institute,
1345 Jayhawk Boulevard, Lawrence, Kansas, 66045, USA
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or (at
your option) any later version.
This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
02110-1301, USA.
"""
import os
import types
import zipfile
import numpy as np
from collections import namedtuple
from PyQt4.QtGui import *
from PyQt4.QtCore import QSettings, Qt, SIGNAL, QUrl
from qgis.core import *
from qgis.gui import *
from lifemapperTools.tools.ui_newExperimentDialog import Ui_Dialog
from lifemapperTools.tools.listPALayers import ListPALayersDialog
from lifemapperTools.tools.constructGrid import ConstructGridDialog
from lifemapperTools.tools.uploadLayers import UploadDialog
from lifemapperTools.tools.listBuckets import ListBucketsDialog
from lifemapperTools.tools.addSDMLayer import UploadSDMDialog
from lifemapperTools.common.pluginconstants import ListExperiments, GENERIC_REQUEST
from lifemapperTools.common.pluginconstants import QGISProject
from lifemapperTools.common.workspace import Workspace
from lifemapperTools.tools.radTable import RADTable
from lifemapperTools.tools.uploadTreeOTL import UploadTreeDialog
from lifemapperTools.common.communicate import Communicate
class NewExperimentDialog(QDialog, Ui_Dialog):
# .............................................................................
# Constructor
# .............................................................................
def __init__(self, iface, RADids=None, inputs=None, client=None, email=None):
QDialog.__init__(self)
#self.setWindowFlags(self.windowFlags() & Qt.WindowMinimizeButtonHint)
self.interface = iface
self.workspace = Workspace(self.interface,client)
self.checkExperiments()
self.setupUi()
self.client = client
#cc = self.rejectBut
#bok = self.acceptBut
self.expId = None
self.mapunits = None
self.keyvalues = {}
if email is not None:
self.keyvalues['email'] = email
#_Controller.__init__(self, iface, BASE_URL=ListExperiments.BASE_URL,
# STATUS_URL=ListExperiments.STATUS_URL,
# REST_URL=ListExperiments.REST_URL,
# cancel_close=cc, okayButton=bok, ids=RADids,
# initializeWithData=False, client=client)
# ..............................................................................
def _checkQgisProjForKey(self):
project = QgsProject.instance()
filename = str(project.fileName())
found = False
s = QSettings()
for key in s.allKeys():
if 'RADExpProj' in key:
value = str(s.value(key))
if value == filename:
found = True
expId = key.split('_')[1]
s.setValue("currentExpID", int(expId))
return found
# ..............................................................................
def checkExperiments(self):
"""
@summary: gets the current expId, if there is one it gets the current
project path associated with that id. If there is a project path, it
triggers a save project. If there is no path, it asks a save as, and sets
the project path for the id. The last thing it does is to open a new
qgis project
"""
s = QSettings()
currentExpId = s.value("currentExpID",QGISProject.NOEXPID,type=int)
if currentExpId != QGISProject.NOEXPID:
currentpath = str(s.value("RADExpProj_"+str(currentExpId),
QGISProject.NOPROJECT))
if currentpath != QGISProject.NOPROJECT and currentpath != '':
self.interface.actionSaveProject().trigger()
else:
if len(QgsMapLayerRegistry.instance().mapLayers().items()) > 0:
#self.interface.actionSaveProjectAs().trigger()
self.workspace.saveQgsProjectAs(currentExpId)
# now actionNewProject
self.interface.actionNewProject().trigger()
s.setValue("currentExpID",QGISProject.NOEXPID)
else: # no experiment Id
# there is a case where a Qgis project can be opened but there is no
# current id, like after a sign out but that Qgis project belongs to an id, in that case it needs
# to start a new project
if len(QgsMapLayerRegistry.instance().mapLayers().items()) == 0 or self._checkQgisProjForKey():
self.interface.actionNewProject().trigger()
# ..............................................................................
#def accept(self):
#
#
# valid = self.validate()
# if self.expId is not None:
# self.openNewDialog()
# elif valid and self.expId is None:
# self.startThread(GENERIC_REQUEST,outputfunc = self.newExperimentCallBack,
# requestfunc=self.client.rad.postExperiment, client=self.client,
# inputs=self.keyvalues)
# elif not valid and self.expId is None:
# pass
# ..............................................................................
def postNewOpen(self,buttonValue):
|
# ..............................................................................
def validate(self):
valid = True
message = ""
self.keyvalues['epsgCode'] = self.epsgEdit.text()
self.keyvalues['name'] = self.expNameEdit.text()
self.keyvalues['description'] = self.description.toPlainText()
epsg = self.epsgEdit.text()
#self.setMapUnitsFromEPSG(epsg=epsg)
experimentname = self.expNameEdit.text()
if len(experimentname) <= 0:
message = "Please supply a experiment name"
valid = False
elif len(epsg) <= 0:
message = "Please supply an EPSG code"
valid = False
else:
self.setMapUnitsFromEPSG(epsg=epsg)
if self.mapunits is None or self.mapunits == 'UnknownUnit':
message = "Invalid EPSG Code"
valid = False
if not valid:
msgBox = QMessageBox.information(self,
"Problem...",
message,
QMessageBox.Ok)
return valid
# ..............................................................................
def openProjSelectorSetEPSG(self):
"""
@summary: opens the stock qgis projection selector
and sets epsg edit field and set map units attribute
"""
projSelector = QgsGenericProjectionSelector(self)
dialog = projSelector.exec_()
EpsgCode = projSelector.selectedAuthId().replace('EPSG:','')
# some projections don't have epsg's
if dialog != 0:
if EpsgCode != 0: # will be zero if projection doesn't have an epsg
crs = QgsCoordinateReferenceSystem()
crs.createFromOgcWmsCrs( projSelector.selectedAuthId() )
mapunitscode = crs.mapUnits()
if mapunitscode == 0:
self.mapunits = 'meters'
elif mapunitscode == 1:
self.mapunits = 'feet'
elif mapunitscode == 2:
self.mapunits = 'dd'
self.epsgEdit.setText(str(EpsgCode))
else:
# error message saying that the users chosen projection doesn't have a epsg
self.mapunits = None
message = "The projection you have chosen does not have an epsg code"
msgBox = QMessageBox.information(self,
"Problem...",
message,
QMessageBox.Ok)
else:
self.mapunits = None
# ..............................................................................
def verifyEmail(self,email):
valid = True
if '@' in email:
atIndex = email.index('@')
domainsubstring = email[atIndex+1:]
if '.' in domainsubstring:
if domainsubstring.index('.') == 0:
valid = False
else:
valid = False
else:
valid = False
return valid
# ..............................................................................
def cleanInputGridLayout(self):
"""@summary: cleans out the input grid layout"""
if not(self.gridLayout_input.isEmpty()):
for childindex in range(0,self.gridLayout_input.count()):
item = self.gridLayout_input.takeAt(0)
if not(type(item) is types.NoneType):
item.widget().deleteLater()
self.gridLayout_input.update()
# ..............................................................................
def setMapUnitsFromEPSG(self,epsg=None):
crs = QgsCoordinateReferenceSystem()
if epsg:
crs.createFromOgcWmsCrs("EPSG:%s" % (str(epsg)))
else:
crs.createFromOgcWmsCrs("EPSG:%s" % (str(self.expEPSG)))
mapunitscode = crs.mapUnits()
if mapunitscode == 0:
self.mapunits = 'meters'
elif mapunitscode == 1:
self.mapunits = 'feet'
elif mapunitscode == 2:
self.mapunits = 'dd'
elif mapunitscode == 3:
self.mapunits = 'UnknownUnit'
# ..............................................................................
# ..............................................................................
def newExperimentCallBack(self, item, buttonValue):
"""
@summary: when a new expid comes back it gets saved to settings as
currentExpID, then calls openNewDialog
"""
self.epsgEdit.setEnabled(False)
self.expNameEdit.setEnabled(False)
self.description.setEnabled(False)
self.emptyRadio.setEnabled(False)
self.expId = item.id
self.expEPSG = item.epsgcode
if self.mapunits is None:
self.setMapUnitsFromEPSG()
self.setNewExperiment()
Communicate.instance().activateRADExp.emit(int(self.expId),self.expEPSG,self.mapunits)
self.openNewDialog(buttonValue)
# ..............................................................................
def setNewExperiment(self):
"""
@summary: sets the currentExpID key in settings and creates a project folder in workspace
and quietly save the new QGIS project to it
"""
try:
s = QSettings()
s.setValue("currentExpID", int(self.expId))
self.workspace.saveQgsProjectAs(self.expId)
except:
QMessageBox.warning(self,"status: ",
"Could not save expId to settings")
# ..............................................................................
def openNewDialog(self,buttonValue):
inputs = {'expId':self.expId}
experimentname = self.keyvalues['name']
if buttonValue == "Grid":
self.constructGridDialog = ConstructGridDialog( self.interface,
inputs = inputs,
client = self.client,
epsg=self.expEPSG,
mapunits=self.mapunits)
self.setModal(False)
self.constructGridDialog.show()
self.listBucketsRadio.setEnabled(True)
elif buttonValue == "SDM":
SDMDialog = UploadSDMDialog(self.interface,
inputs = inputs,
client = self.client,
epsg=self.expEPSG,
experimentname = experimentname,
mapunits=self.mapunits)
self.setModal(False) # has to be closed to continue
SDMDialog.exec_()
self.listPALayersRadio.setEnabled(True)
elif buttonValue == "Tree":
try:
items = self.client.rad.getPALayers(self.expId)
except:
items = None
message = "There is a problem with the layer listing service"
msgBox = QMessageBox.information(self,
"Problem...",
message,
QMessageBox.Ok)
else:
if len(items) != 0:
message = "You already have layers in this experiment. You must begin an experiment with trees and their layers to use a tree."
msgBox = QMessageBox.information(self,
"Problem...",
message,
QMessageBox.Ok)
elif len(items) == 0:
treeDialog = UploadTreeDialog(self.interface,
inputs = inputs,
client = self.client,
epsg = self.expEPSG,
experimentname=experimentname,
mapunits=self.mapunits)
self.setModal(False)
treeDialog.exec_()
self.listPALayersRadio.setEnabled(True)
elif buttonValue == "Local":
d = UploadDialog(self.interface,
inputs = inputs,
client = self.client,
epsg=self.expEPSG,
experimentname=experimentname,
mapunits=self.mapunits)
d.exec_()
self.listPALayersRadio.setEnabled(True)
elif buttonValue == "Empty":
pass
elif buttonValue == "ListBuckets":
d = ListBucketsDialog(self.interface, inputs=inputs,
client= self.client, epsg=self.expEPSG,
mapunits=self.mapunits)
d.exec_()
elif buttonValue == "ListLayers":
d = ListPALayersDialog(self.interface, inputs=inputs,
client= self.client, epsg=self.expEPSG,
mapunits=self.mapunits)
d.exec_()
#self.acceptBut.setEnabled( True )
# ..............................................................................
def help(self):
self.help = QWidget()
self.help.setWindowTitle('Lifemapper Help')
self.help.resize(600, 400)
self.help.setMinimumSize(600,400)
self.help.setMaximumSize(1000,1000)
layout = QVBoxLayout()
helpDialog = QTextBrowser()
helpDialog.setOpenExternalLinks(True)
#helpDialog.setSearchPaths(['documents'])
helppath = os.path.dirname(os.path.realpath(__file__))+'/documents/help.html'
helpDialog.setSource(QUrl.fromLocalFile(helppath))
helpDialog.scrollToAnchor('newRADExperiment')
layout.addWidget(helpDialog)
self.help.setLayout(layout)
if self.isModal():
self.setModal(False)
self.help.show()
if __name__ == "__main__":
#
import sys
#import_path = "/home/jcavner/workspace/lm3/components/LmClient/LmQGIS/V2/lifemapperTools/"
#sys.path.append(os.path.join(import_path, 'LmShared'))
###
#configPath = os.path.join(import_path, 'config', 'config.ini')
###
#os.environ["LIFEMAPPER_CONFIG_FILE"] = configPath
#from LmClient.lmClientLib import LMClient
#client = LMClient(userId='blank', pwd='blank')
qApp = QApplication(sys.argv)
d = NewExperimentDialog(None)#,experimentId=596106
d.show()
sys.exit(qApp.exec_())
|
valid = self.validate()
if self.expId is not None:
self.openNewDialog(buttonValue)
elif valid and self.expId is None:
try:
print self.keyvalues
exp = self.client.rad.postExperiment(**self.keyvalues)
except Exception, e:
message = "Error posting new experiment "+str(e)
msgBox = QMessageBox.information(self,
"Problem...",
message,
QMessageBox.Ok)
else:
self.newExperimentCallBack(exp,buttonValue)
elif not valid and self.expId is None:
pass
|
identifier_body
|
vdom-my.js
|
export function Fragment(props, ...children) {
return collect(children);
}
const ATTR_PROPS = '_props';
function collect(children) {
const ch = [];
const push = (c) => {
if (c !== null && c !== undefined && c !== '' && c !== false) {
ch.push((typeof c === 'function' || typeof c === 'object') ? c : `${c}`);
}
};
children && children.forEach(c => {
if (Array.isArray(c)) {
c.forEach(i => push(i));
}
else {
push(c);
}
});
return ch;
}
export function createElement(tag, props, ...children) {
const ch = collect(children);
if (typeof tag === 'string')
return { tag, props, children: ch };
else if (Array.isArray(tag))
return tag; // JSX fragments - babel
else if (tag === undefined && children)
return ch; // JSX fragments - typescript
else if (Object.getPrototypeOf(tag).__isAppRunComponent)
return { tag, props, children: ch }; // createComponent(tag, { ...props, children });
else if (typeof tag === 'function')
return tag(props, ch);
else
throw new Error(`Unknown tag in vdom ${tag}`);
}
;
const keyCache = new WeakMap();
export const updateElement = render;
export function render(element, nodes, parent = {}) {
// console.log('render', element, node);
// tslint:disable-next-line
if (nodes == null || nodes === false)
return;
nodes = createComponent(nodes, parent);
const isSvg = (element === null || element === void 0 ? void 0 : element.nodeName) === "SVG";
if (!element)
return;
if (Array.isArray(nodes)) {
updateChildren(element, nodes, isSvg);
}
else {
updateChildren(element, [nodes], isSvg);
}
}
function same(el, node) {
// if (!el || !node) return false;
const key1 = el.nodeName;
const key2 = `${node.tag || ''}`;
return key1.toUpperCase() === key2.toUpperCase();
}
function update(element, node, isSvg) {
if (node['_op'] === 3)
return;
// console.assert(!!element);
isSvg = isSvg || node.tag === "svg";
if (!same(element, node)) {
element.parentNode.replaceChild(create(node, isSvg), element);
return;
}
!(node['_op'] & 2) && updateChildren(element, node.children, isSvg);
!(node['_op'] & 1) && updateProps(element, node.props, isSvg);
}
function updateChildren(element, children, isSvg) {
var _a;
const old_len = ((_a = element.childNodes) === null || _a === void 0 ? void 0 : _a.length) || 0;
const new_len = (children === null || children === void 0 ? void 0 : children.length) || 0;
const len = Math.min(old_len, new_len);
for (let i = 0; i < len; i++) {
const child = children[i];
if (child['_op'] === 3)
continue;
const el = element.childNodes[i];
if (typeof child === 'string') {
if (el.textContent !== child) {
if (el.nodeType === 3) {
el.nodeValue = child;
}
else {
element.replaceChild(createText(child), el);
}
}
}
else if (child instanceof HTMLElement || child instanceof SVGElement) {
element.insertBefore(child, el);
}
else {
const key = child.props && child.props['key'];
if (key) {
if (el.key === key) {
update(element.childNodes[i], child, isSvg);
}
else {
// console.log(el.key, key);
const old = keyCache[key];
if (old) {
const temp = old.nextSibling;
element.insertBefore(old, el);
temp ? element.insertBefore(el, temp) : element.appendChild(el);
update(element.childNodes[i], child, isSvg);
}
else {
element.replaceChild(create(child, isSvg), el);
}
}
}
else {
update(element.childNodes[i], child, isSvg);
}
}
}
let n = element.childNodes.length;
while (n > len) {
element.removeChild(element.lastChild);
n--;
}
if (new_len > len) {
const d = document.createDocumentFragment();
for (let i = len; i < children.length; i++) {
d.appendChild(create(children[i], isSvg));
}
element.appendChild(d);
}
}
function createText(node) {
if ((node === null || node === void 0 ? void 0 : node.indexOf('_html:')) === 0) { // ?
const div = document.createElement('div');
div.insertAdjacentHTML('afterbegin', node.substring(6));
return div;
}
else {
return document.createTextNode(node !== null && node !== void 0 ? node : '');
}
}
function create(node, isSvg) {
// console.assert(node !== null && node !== undefined);
if ((node instanceof HTMLElement) || (node instanceof SVGElement))
return node;
if (typeof node === "string")
return createText(node);
if (!node.tag || (typeof node.tag === 'function'))
return createText(JSON.stringify(node));
isSvg = isSvg || node.tag === "svg";
const element = isSvg
? document.createElementNS("http://www.w3.org/2000/svg", node.tag)
: document.createElement(node.tag);
updateProps(element, node.props, isSvg);
if (node.children)
node.children.forEach(child => element.appendChild(create(child, isSvg)));
return element;
}
function
|
(oldProps, newProps) {
newProps['class'] = newProps['class'] || newProps['className'];
delete newProps['className'];
const props = {};
if (oldProps)
Object.keys(oldProps).forEach(p => props[p] = null);
if (newProps)
Object.keys(newProps).forEach(p => props[p] = newProps[p]);
return props;
}
export function updateProps(element, props, isSvg) {
// console.assert(!!element);
const cached = element[ATTR_PROPS] || {};
props = mergeProps(cached, props || {});
element[ATTR_PROPS] = props;
for (const name in props) {
const value = props[name];
// if (cached[name] === value) continue;
// console.log('updateProps', name, value);
if (name.startsWith('data-')) {
const dname = name.substring(5);
const cname = dname.replace(/-(\w)/g, (match) => match[1].toUpperCase());
if (element.dataset[cname] !== value) {
if (value || value === "")
element.dataset[cname] = value;
else
delete element.dataset[cname];
}
}
else if (name === 'style') {
if (element.style.cssText)
element.style.cssText = '';
if (typeof value === 'string')
element.style.cssText = value;
else {
for (const s in value) {
if (element.style[s] !== value[s])
element.style[s] = value[s];
}
}
}
else if (name.startsWith('xlink')) {
const xname = name.replace('xlink', '').toLowerCase();
if (value == null || value === false) {
element.removeAttributeNS('http://www.w3.org/1999/xlink', xname);
}
else {
element.setAttributeNS('http://www.w3.org/1999/xlink', xname, value);
}
}
else if (name.startsWith('on')) {
if (!value || typeof value === 'function') {
element[name] = value;
}
else if (typeof value === 'string') {
if (value)
element.setAttribute(name, value);
else
element.removeAttribute(name);
}
}
else if (/^id$|^class$|^list$|^readonly$|^contenteditable$|^role|-/g.test(name) || isSvg) {
if (element.getAttribute(name) !== value) {
if (value)
element.setAttribute(name, value);
else
element.removeAttribute(name);
}
}
else if (element[name] !== value) {
element[name] = value;
}
if (name === 'key' && value)
keyCache[value] = element;
}
if (props && typeof props['ref'] === 'function') {
window.requestAnimationFrame(() => props['ref'](element));
}
}
function render_component(node, parent, idx) {
const { tag, props, children } = node;
let key = `_${idx}`;
let id = props && props['id'];
if (!id)
id = `_${idx}${Date.now()}`;
else
key = id;
let asTag = 'section';
if (props && props['as']) {
asTag = props['as'];
delete props['as'];
}
if (!parent.__componentCache)
parent.__componentCache = {};
let component = parent.__componentCache[key];
if (!component || !(component instanceof tag) || !component.element) {
const element = document.createElement(asTag);
component = parent.__componentCache[key] = new tag(Object.assign(Object.assign({}, props), { children })).start(element);
}
if (component.mounted) {
const new_state = component.mounted(props, children, component.state);
(typeof new_state !== 'undefined') && component.setState(new_state);
}
updateProps(component.element, props, false);
return component.element;
}
function createComponent(node, parent, idx = 0) {
var _a;
if (typeof node === 'string')
return node;
if (Array.isArray(node))
return node.map(child => createComponent(child, parent, idx++));
let vdom = node;
if (node && typeof node.tag === 'function' && Object.getPrototypeOf(node.tag).__isAppRunComponent) {
vdom = render_component(node, parent, idx);
}
if (vdom && Array.isArray(vdom.children)) {
const new_parent = (_a = vdom.props) === null || _a === void 0 ? void 0 : _a._component;
if (new_parent) {
let i = 0;
vdom.children = vdom.children.map(child => createComponent(child, new_parent, i++));
}
else {
vdom.children = vdom.children.map(child => createComponent(child, parent, idx++));
}
}
return vdom;
}
//# sourceMappingURL=vdom-my.js.map
|
mergeProps
|
identifier_name
|
vdom-my.js
|
export function Fragment(props, ...children) {
return collect(children);
}
const ATTR_PROPS = '_props';
function collect(children)
|
export function createElement(tag, props, ...children) {
const ch = collect(children);
if (typeof tag === 'string')
return { tag, props, children: ch };
else if (Array.isArray(tag))
return tag; // JSX fragments - babel
else if (tag === undefined && children)
return ch; // JSX fragments - typescript
else if (Object.getPrototypeOf(tag).__isAppRunComponent)
return { tag, props, children: ch }; // createComponent(tag, { ...props, children });
else if (typeof tag === 'function')
return tag(props, ch);
else
throw new Error(`Unknown tag in vdom ${tag}`);
}
;
const keyCache = new WeakMap();
export const updateElement = render;
export function render(element, nodes, parent = {}) {
// console.log('render', element, node);
// tslint:disable-next-line
if (nodes == null || nodes === false)
return;
nodes = createComponent(nodes, parent);
const isSvg = (element === null || element === void 0 ? void 0 : element.nodeName) === "SVG";
if (!element)
return;
if (Array.isArray(nodes)) {
updateChildren(element, nodes, isSvg);
}
else {
updateChildren(element, [nodes], isSvg);
}
}
function same(el, node) {
// if (!el || !node) return false;
const key1 = el.nodeName;
const key2 = `${node.tag || ''}`;
return key1.toUpperCase() === key2.toUpperCase();
}
function update(element, node, isSvg) {
if (node['_op'] === 3)
return;
// console.assert(!!element);
isSvg = isSvg || node.tag === "svg";
if (!same(element, node)) {
element.parentNode.replaceChild(create(node, isSvg), element);
return;
}
!(node['_op'] & 2) && updateChildren(element, node.children, isSvg);
!(node['_op'] & 1) && updateProps(element, node.props, isSvg);
}
function updateChildren(element, children, isSvg) {
var _a;
const old_len = ((_a = element.childNodes) === null || _a === void 0 ? void 0 : _a.length) || 0;
const new_len = (children === null || children === void 0 ? void 0 : children.length) || 0;
const len = Math.min(old_len, new_len);
for (let i = 0; i < len; i++) {
const child = children[i];
if (child['_op'] === 3)
continue;
const el = element.childNodes[i];
if (typeof child === 'string') {
if (el.textContent !== child) {
if (el.nodeType === 3) {
el.nodeValue = child;
}
else {
element.replaceChild(createText(child), el);
}
}
}
else if (child instanceof HTMLElement || child instanceof SVGElement) {
element.insertBefore(child, el);
}
else {
const key = child.props && child.props['key'];
if (key) {
if (el.key === key) {
update(element.childNodes[i], child, isSvg);
}
else {
// console.log(el.key, key);
const old = keyCache[key];
if (old) {
const temp = old.nextSibling;
element.insertBefore(old, el);
temp ? element.insertBefore(el, temp) : element.appendChild(el);
update(element.childNodes[i], child, isSvg);
}
else {
element.replaceChild(create(child, isSvg), el);
}
}
}
else {
update(element.childNodes[i], child, isSvg);
}
}
}
let n = element.childNodes.length;
while (n > len) {
element.removeChild(element.lastChild);
n--;
}
if (new_len > len) {
const d = document.createDocumentFragment();
for (let i = len; i < children.length; i++) {
d.appendChild(create(children[i], isSvg));
}
element.appendChild(d);
}
}
function createText(node) {
if ((node === null || node === void 0 ? void 0 : node.indexOf('_html:')) === 0) { // ?
const div = document.createElement('div');
div.insertAdjacentHTML('afterbegin', node.substring(6));
return div;
}
else {
return document.createTextNode(node !== null && node !== void 0 ? node : '');
}
}
function create(node, isSvg) {
// console.assert(node !== null && node !== undefined);
if ((node instanceof HTMLElement) || (node instanceof SVGElement))
return node;
if (typeof node === "string")
return createText(node);
if (!node.tag || (typeof node.tag === 'function'))
return createText(JSON.stringify(node));
isSvg = isSvg || node.tag === "svg";
const element = isSvg
? document.createElementNS("http://www.w3.org/2000/svg", node.tag)
: document.createElement(node.tag);
updateProps(element, node.props, isSvg);
if (node.children)
node.children.forEach(child => element.appendChild(create(child, isSvg)));
return element;
}
function mergeProps(oldProps, newProps) {
newProps['class'] = newProps['class'] || newProps['className'];
delete newProps['className'];
const props = {};
if (oldProps)
Object.keys(oldProps).forEach(p => props[p] = null);
if (newProps)
Object.keys(newProps).forEach(p => props[p] = newProps[p]);
return props;
}
export function updateProps(element, props, isSvg) {
// console.assert(!!element);
const cached = element[ATTR_PROPS] || {};
props = mergeProps(cached, props || {});
element[ATTR_PROPS] = props;
for (const name in props) {
const value = props[name];
// if (cached[name] === value) continue;
// console.log('updateProps', name, value);
if (name.startsWith('data-')) {
const dname = name.substring(5);
const cname = dname.replace(/-(\w)/g, (match) => match[1].toUpperCase());
if (element.dataset[cname] !== value) {
if (value || value === "")
element.dataset[cname] = value;
else
delete element.dataset[cname];
}
}
else if (name === 'style') {
if (element.style.cssText)
element.style.cssText = '';
if (typeof value === 'string')
element.style.cssText = value;
else {
for (const s in value) {
if (element.style[s] !== value[s])
element.style[s] = value[s];
}
}
}
else if (name.startsWith('xlink')) {
const xname = name.replace('xlink', '').toLowerCase();
if (value == null || value === false) {
element.removeAttributeNS('http://www.w3.org/1999/xlink', xname);
}
else {
element.setAttributeNS('http://www.w3.org/1999/xlink', xname, value);
}
}
else if (name.startsWith('on')) {
if (!value || typeof value === 'function') {
element[name] = value;
}
else if (typeof value === 'string') {
if (value)
element.setAttribute(name, value);
else
element.removeAttribute(name);
}
}
else if (/^id$|^class$|^list$|^readonly$|^contenteditable$|^role|-/g.test(name) || isSvg) {
if (element.getAttribute(name) !== value) {
if (value)
element.setAttribute(name, value);
else
element.removeAttribute(name);
}
}
else if (element[name] !== value) {
element[name] = value;
}
if (name === 'key' && value)
keyCache[value] = element;
}
if (props && typeof props['ref'] === 'function') {
window.requestAnimationFrame(() => props['ref'](element));
}
}
function render_component(node, parent, idx) {
const { tag, props, children } = node;
let key = `_${idx}`;
let id = props && props['id'];
if (!id)
id = `_${idx}${Date.now()}`;
else
key = id;
let asTag = 'section';
if (props && props['as']) {
asTag = props['as'];
delete props['as'];
}
if (!parent.__componentCache)
parent.__componentCache = {};
let component = parent.__componentCache[key];
if (!component || !(component instanceof tag) || !component.element) {
const element = document.createElement(asTag);
component = parent.__componentCache[key] = new tag(Object.assign(Object.assign({}, props), { children })).start(element);
}
if (component.mounted) {
const new_state = component.mounted(props, children, component.state);
(typeof new_state !== 'undefined') && component.setState(new_state);
}
updateProps(component.element, props, false);
return component.element;
}
function createComponent(node, parent, idx = 0) {
var _a;
if (typeof node === 'string')
return node;
if (Array.isArray(node))
return node.map(child => createComponent(child, parent, idx++));
let vdom = node;
if (node && typeof node.tag === 'function' && Object.getPrototypeOf(node.tag).__isAppRunComponent) {
vdom = render_component(node, parent, idx);
}
if (vdom && Array.isArray(vdom.children)) {
const new_parent = (_a = vdom.props) === null || _a === void 0 ? void 0 : _a._component;
if (new_parent) {
let i = 0;
vdom.children = vdom.children.map(child => createComponent(child, new_parent, i++));
}
else {
vdom.children = vdom.children.map(child => createComponent(child, parent, idx++));
}
}
return vdom;
}
//# sourceMappingURL=vdom-my.js.map
|
{
const ch = [];
const push = (c) => {
if (c !== null && c !== undefined && c !== '' && c !== false) {
ch.push((typeof c === 'function' || typeof c === 'object') ? c : `${c}`);
}
};
children && children.forEach(c => {
if (Array.isArray(c)) {
c.forEach(i => push(i));
}
else {
push(c);
}
});
return ch;
}
|
identifier_body
|
vdom-my.js
|
export function Fragment(props, ...children) {
return collect(children);
}
const ATTR_PROPS = '_props';
function collect(children) {
const ch = [];
const push = (c) => {
if (c !== null && c !== undefined && c !== '' && c !== false) {
ch.push((typeof c === 'function' || typeof c === 'object') ? c : `${c}`);
}
};
children && children.forEach(c => {
if (Array.isArray(c)) {
c.forEach(i => push(i));
}
else {
push(c);
}
});
return ch;
}
export function createElement(tag, props, ...children) {
const ch = collect(children);
if (typeof tag === 'string')
return { tag, props, children: ch };
else if (Array.isArray(tag))
return tag; // JSX fragments - babel
else if (tag === undefined && children)
return ch; // JSX fragments - typescript
else if (Object.getPrototypeOf(tag).__isAppRunComponent)
return { tag, props, children: ch }; // createComponent(tag, { ...props, children });
else if (typeof tag === 'function')
return tag(props, ch);
else
throw new Error(`Unknown tag in vdom ${tag}`);
}
;
const keyCache = new WeakMap();
export const updateElement = render;
export function render(element, nodes, parent = {}) {
// console.log('render', element, node);
// tslint:disable-next-line
if (nodes == null || nodes === false)
return;
nodes = createComponent(nodes, parent);
const isSvg = (element === null || element === void 0 ? void 0 : element.nodeName) === "SVG";
if (!element)
return;
if (Array.isArray(nodes)) {
updateChildren(element, nodes, isSvg);
}
else {
updateChildren(element, [nodes], isSvg);
}
}
function same(el, node) {
// if (!el || !node) return false;
const key1 = el.nodeName;
const key2 = `${node.tag || ''}`;
return key1.toUpperCase() === key2.toUpperCase();
}
function update(element, node, isSvg) {
if (node['_op'] === 3)
return;
// console.assert(!!element);
isSvg = isSvg || node.tag === "svg";
if (!same(element, node)) {
element.parentNode.replaceChild(create(node, isSvg), element);
return;
}
!(node['_op'] & 2) && updateChildren(element, node.children, isSvg);
!(node['_op'] & 1) && updateProps(element, node.props, isSvg);
}
function updateChildren(element, children, isSvg) {
var _a;
const old_len = ((_a = element.childNodes) === null || _a === void 0 ? void 0 : _a.length) || 0;
const new_len = (children === null || children === void 0 ? void 0 : children.length) || 0;
const len = Math.min(old_len, new_len);
for (let i = 0; i < len; i++) {
const child = children[i];
if (child['_op'] === 3)
continue;
const el = element.childNodes[i];
if (typeof child === 'string') {
if (el.textContent !== child) {
if (el.nodeType === 3) {
el.nodeValue = child;
}
else {
element.replaceChild(createText(child), el);
}
}
}
else if (child instanceof HTMLElement || child instanceof SVGElement) {
element.insertBefore(child, el);
}
else {
const key = child.props && child.props['key'];
if (key) {
if (el.key === key) {
update(element.childNodes[i], child, isSvg);
}
else {
// console.log(el.key, key);
const old = keyCache[key];
if (old) {
const temp = old.nextSibling;
element.insertBefore(old, el);
temp ? element.insertBefore(el, temp) : element.appendChild(el);
update(element.childNodes[i], child, isSvg);
}
else {
element.replaceChild(create(child, isSvg), el);
}
}
}
else {
update(element.childNodes[i], child, isSvg);
}
}
}
let n = element.childNodes.length;
while (n > len) {
element.removeChild(element.lastChild);
n--;
}
if (new_len > len) {
const d = document.createDocumentFragment();
for (let i = len; i < children.length; i++) {
d.appendChild(create(children[i], isSvg));
}
element.appendChild(d);
}
}
function createText(node) {
if ((node === null || node === void 0 ? void 0 : node.indexOf('_html:')) === 0) { // ?
const div = document.createElement('div');
div.insertAdjacentHTML('afterbegin', node.substring(6));
return div;
}
else {
return document.createTextNode(node !== null && node !== void 0 ? node : '');
}
}
function create(node, isSvg) {
// console.assert(node !== null && node !== undefined);
if ((node instanceof HTMLElement) || (node instanceof SVGElement))
return node;
if (typeof node === "string")
return createText(node);
if (!node.tag || (typeof node.tag === 'function'))
return createText(JSON.stringify(node));
isSvg = isSvg || node.tag === "svg";
const element = isSvg
? document.createElementNS("http://www.w3.org/2000/svg", node.tag)
: document.createElement(node.tag);
updateProps(element, node.props, isSvg);
if (node.children)
node.children.forEach(child => element.appendChild(create(child, isSvg)));
return element;
}
function mergeProps(oldProps, newProps) {
newProps['class'] = newProps['class'] || newProps['className'];
delete newProps['className'];
const props = {};
if (oldProps)
Object.keys(oldProps).forEach(p => props[p] = null);
if (newProps)
Object.keys(newProps).forEach(p => props[p] = newProps[p]);
return props;
}
export function updateProps(element, props, isSvg) {
// console.assert(!!element);
const cached = element[ATTR_PROPS] || {};
props = mergeProps(cached, props || {});
element[ATTR_PROPS] = props;
for (const name in props) {
const value = props[name];
// if (cached[name] === value) continue;
// console.log('updateProps', name, value);
if (name.startsWith('data-')) {
const dname = name.substring(5);
const cname = dname.replace(/-(\w)/g, (match) => match[1].toUpperCase());
if (element.dataset[cname] !== value) {
if (value || value === "")
element.dataset[cname] = value;
else
delete element.dataset[cname];
}
}
else if (name === 'style') {
if (element.style.cssText)
element.style.cssText = '';
if (typeof value === 'string')
element.style.cssText = value;
else {
for (const s in value) {
if (element.style[s] !== value[s])
element.style[s] = value[s];
}
|
}
}
else if (name.startsWith('xlink')) {
const xname = name.replace('xlink', '').toLowerCase();
if (value == null || value === false) {
element.removeAttributeNS('http://www.w3.org/1999/xlink', xname);
}
else {
element.setAttributeNS('http://www.w3.org/1999/xlink', xname, value);
}
}
else if (name.startsWith('on')) {
if (!value || typeof value === 'function') {
element[name] = value;
}
else if (typeof value === 'string') {
if (value)
element.setAttribute(name, value);
else
element.removeAttribute(name);
}
}
else if (/^id$|^class$|^list$|^readonly$|^contenteditable$|^role|-/g.test(name) || isSvg) {
if (element.getAttribute(name) !== value) {
if (value)
element.setAttribute(name, value);
else
element.removeAttribute(name);
}
}
else if (element[name] !== value) {
element[name] = value;
}
if (name === 'key' && value)
keyCache[value] = element;
}
if (props && typeof props['ref'] === 'function') {
window.requestAnimationFrame(() => props['ref'](element));
}
}
function render_component(node, parent, idx) {
const { tag, props, children } = node;
let key = `_${idx}`;
let id = props && props['id'];
if (!id)
id = `_${idx}${Date.now()}`;
else
key = id;
let asTag = 'section';
if (props && props['as']) {
asTag = props['as'];
delete props['as'];
}
if (!parent.__componentCache)
parent.__componentCache = {};
let component = parent.__componentCache[key];
if (!component || !(component instanceof tag) || !component.element) {
const element = document.createElement(asTag);
component = parent.__componentCache[key] = new tag(Object.assign(Object.assign({}, props), { children })).start(element);
}
if (component.mounted) {
const new_state = component.mounted(props, children, component.state);
(typeof new_state !== 'undefined') && component.setState(new_state);
}
updateProps(component.element, props, false);
return component.element;
}
function createComponent(node, parent, idx = 0) {
var _a;
if (typeof node === 'string')
return node;
if (Array.isArray(node))
return node.map(child => createComponent(child, parent, idx++));
let vdom = node;
if (node && typeof node.tag === 'function' && Object.getPrototypeOf(node.tag).__isAppRunComponent) {
vdom = render_component(node, parent, idx);
}
if (vdom && Array.isArray(vdom.children)) {
const new_parent = (_a = vdom.props) === null || _a === void 0 ? void 0 : _a._component;
if (new_parent) {
let i = 0;
vdom.children = vdom.children.map(child => createComponent(child, new_parent, i++));
}
else {
vdom.children = vdom.children.map(child => createComponent(child, parent, idx++));
}
}
return vdom;
}
//# sourceMappingURL=vdom-my.js.map
|
random_line_split
|
|
compress.rs
|
extern crate env_logger;
extern crate handlebars_iron as hbs;
extern crate iron;
extern crate router;
extern crate serde;
extern crate serde_json;
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate maplit;
extern crate flate2;
use hbs::handlebars::{Context, Handlebars, Helper, Output, RenderContext, RenderError};
use hbs::{DirectorySource, HandlebarsEngine, MemorySource, Template};
use iron::headers::{ContentEncoding, Encoding};
use iron::prelude::*;
use iron::{status, AfterMiddleware};
use router::Router;
use flate2::write::GzEncoder;
use flate2::Compression;
mod data {
use hbs::handlebars::to_json;
use serde_json::value::{Map, Value};
#[derive(Serialize, Debug)]
pub struct Team {
name: String,
pts: u16,
}
pub fn make_data() -> Map<String, Value> {
let mut data = Map::new();
data.insert("year".to_string(), to_json(&"2015".to_owned()));
let teams = vec![
Team {
name: "Jiangsu Sainty".to_string(),
pts: 43u16,
},
Team {
name: "Beijing Guoan".to_string(),
pts: 27u16,
},
Team {
name: "Guangzhou Evergrand".to_string(),
pts: 22u16,
},
Team {
name: "Shandong Luneng".to_string(),
pts: 12u16,
},
];
data.insert("teams".to_string(), to_json(&teams));
data.insert("engine".to_string(), to_json(&"serde_json".to_owned()));
data
}
}
use data::*;
/// the handlers
fn index(_: &mut Request) -> IronResult<Response> {
let mut resp = Response::new();
let data = make_data();
resp.set_mut(Template::new("some/path/hello", data))
.set_mut(status::Ok);
Ok(resp)
}
fn memory(_: &mut Request) -> IronResult<Response> {
let mut resp = Response::new();
let data = make_data();
resp.set_mut(Template::new("memory", data))
.set_mut(status::Ok);
Ok(resp)
}
fn temp(_: &mut Request) -> IronResult<Response> {
let mut resp = Response::new();
let data = make_data();
resp.set_mut(Template::with(
include_str!("templates/some/path/hello.hbs"),
data,
))
.set_mut(status::Ok);
Ok(resp)
}
fn plain(_: &mut Request) -> IronResult<Response> {
Ok(Response::with((status::Ok, "It works")))
}
// an example compression middleware
pub struct GzMiddleware;
impl AfterMiddleware for GzMiddleware {
fn after(&self, _: &mut Request, mut resp: Response) -> IronResult<Response> {
let compressed_bytes = resp.body.as_mut().map(|b| {
let mut encoder = GzEncoder::new(Vec::new(), Compression::Best);
{
let _ = b.write_body(&mut encoder);
}
encoder.finish().unwrap()
});
if let Some(b) = compressed_bytes {
resp.headers.set(ContentEncoding(vec![Encoding::Gzip]));
resp.set_mut(b);
}
Ok(resp)
}
}
fn main() {
env_logger::init().unwrap();
let mut hbse = HandlebarsEngine::new();
// add a directory source, all files with .hbs suffix will be loaded as template
hbse.add(Box::new(DirectorySource::new(
"./examples/templates/",
".hbs",
)));
let mem_templates = btreemap! {
"memory".to_owned() => include_str!("templates/some/path/hello.hbs").to_owned()
};
// add a memory based source
hbse.add(Box::new(MemorySource(mem_templates)));
// load templates from all registered sources
if let Err(r) = hbse.reload()
|
hbse.handlebars_mut().register_helper(
"some_helper",
Box::new(
|_: &Helper,
_: &Handlebars,
_: &Context,
_: &mut RenderContext,
_: &mut dyn Output|
-> Result<(), RenderError> { Ok(()) },
),
);
let mut router = Router::new();
router
.get("/", index, "index")
.get("/mem", memory, "memory")
.get("/temp", temp, "temp")
.get("/plain", plain, "plain");
let mut chain = Chain::new(router);
chain.link_after(hbse);
chain.link_after(GzMiddleware);
println!("Server running at http://localhost:3000/");
Iron::new(chain).http("localhost:3000").unwrap();
}
|
{
panic!("{}", r);
}
|
conditional_block
|
compress.rs
|
extern crate env_logger;
extern crate handlebars_iron as hbs;
extern crate iron;
extern crate router;
extern crate serde;
extern crate serde_json;
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate maplit;
extern crate flate2;
use hbs::handlebars::{Context, Handlebars, Helper, Output, RenderContext, RenderError};
use hbs::{DirectorySource, HandlebarsEngine, MemorySource, Template};
use iron::headers::{ContentEncoding, Encoding};
use iron::prelude::*;
use iron::{status, AfterMiddleware};
use router::Router;
use flate2::write::GzEncoder;
use flate2::Compression;
mod data {
use hbs::handlebars::to_json;
use serde_json::value::{Map, Value};
#[derive(Serialize, Debug)]
pub struct Team {
name: String,
pts: u16,
}
pub fn make_data() -> Map<String, Value>
|
}
use data::*;
/// the handlers
fn index(_: &mut Request) -> IronResult<Response> {
let mut resp = Response::new();
let data = make_data();
resp.set_mut(Template::new("some/path/hello", data))
.set_mut(status::Ok);
Ok(resp)
}
fn memory(_: &mut Request) -> IronResult<Response> {
let mut resp = Response::new();
let data = make_data();
resp.set_mut(Template::new("memory", data))
.set_mut(status::Ok);
Ok(resp)
}
fn temp(_: &mut Request) -> IronResult<Response> {
let mut resp = Response::new();
let data = make_data();
resp.set_mut(Template::with(
include_str!("templates/some/path/hello.hbs"),
data,
))
.set_mut(status::Ok);
Ok(resp)
}
fn plain(_: &mut Request) -> IronResult<Response> {
Ok(Response::with((status::Ok, "It works")))
}
// an example compression middleware
pub struct GzMiddleware;
impl AfterMiddleware for GzMiddleware {
fn after(&self, _: &mut Request, mut resp: Response) -> IronResult<Response> {
let compressed_bytes = resp.body.as_mut().map(|b| {
let mut encoder = GzEncoder::new(Vec::new(), Compression::Best);
{
let _ = b.write_body(&mut encoder);
}
encoder.finish().unwrap()
});
if let Some(b) = compressed_bytes {
resp.headers.set(ContentEncoding(vec![Encoding::Gzip]));
resp.set_mut(b);
}
Ok(resp)
}
}
fn main() {
env_logger::init().unwrap();
let mut hbse = HandlebarsEngine::new();
// add a directory source, all files with .hbs suffix will be loaded as template
hbse.add(Box::new(DirectorySource::new(
"./examples/templates/",
".hbs",
)));
let mem_templates = btreemap! {
"memory".to_owned() => include_str!("templates/some/path/hello.hbs").to_owned()
};
// add a memory based source
hbse.add(Box::new(MemorySource(mem_templates)));
// load templates from all registered sources
if let Err(r) = hbse.reload() {
panic!("{}", r);
}
hbse.handlebars_mut().register_helper(
"some_helper",
Box::new(
|_: &Helper,
_: &Handlebars,
_: &Context,
_: &mut RenderContext,
_: &mut dyn Output|
-> Result<(), RenderError> { Ok(()) },
),
);
let mut router = Router::new();
router
.get("/", index, "index")
.get("/mem", memory, "memory")
.get("/temp", temp, "temp")
.get("/plain", plain, "plain");
let mut chain = Chain::new(router);
chain.link_after(hbse);
chain.link_after(GzMiddleware);
println!("Server running at http://localhost:3000/");
Iron::new(chain).http("localhost:3000").unwrap();
}
|
{
let mut data = Map::new();
data.insert("year".to_string(), to_json(&"2015".to_owned()));
let teams = vec![
Team {
name: "Jiangsu Sainty".to_string(),
pts: 43u16,
},
Team {
name: "Beijing Guoan".to_string(),
pts: 27u16,
},
Team {
name: "Guangzhou Evergrand".to_string(),
pts: 22u16,
},
Team {
name: "Shandong Luneng".to_string(),
pts: 12u16,
},
];
data.insert("teams".to_string(), to_json(&teams));
data.insert("engine".to_string(), to_json(&"serde_json".to_owned()));
data
}
|
identifier_body
|
compress.rs
|
extern crate env_logger;
extern crate handlebars_iron as hbs;
extern crate iron;
extern crate router;
extern crate serde;
extern crate serde_json;
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate maplit;
extern crate flate2;
use hbs::handlebars::{Context, Handlebars, Helper, Output, RenderContext, RenderError};
use hbs::{DirectorySource, HandlebarsEngine, MemorySource, Template};
use iron::headers::{ContentEncoding, Encoding};
use iron::prelude::*;
use iron::{status, AfterMiddleware};
use router::Router;
use flate2::write::GzEncoder;
use flate2::Compression;
mod data {
use hbs::handlebars::to_json;
use serde_json::value::{Map, Value};
#[derive(Serialize, Debug)]
pub struct Team {
name: String,
pts: u16,
}
pub fn make_data() -> Map<String, Value> {
let mut data = Map::new();
data.insert("year".to_string(), to_json(&"2015".to_owned()));
let teams = vec![
Team {
name: "Jiangsu Sainty".to_string(),
pts: 43u16,
},
Team {
name: "Beijing Guoan".to_string(),
pts: 27u16,
},
Team {
name: "Guangzhou Evergrand".to_string(),
pts: 22u16,
},
Team {
name: "Shandong Luneng".to_string(),
pts: 12u16,
},
];
data.insert("teams".to_string(), to_json(&teams));
data.insert("engine".to_string(), to_json(&"serde_json".to_owned()));
data
}
}
use data::*;
/// the handlers
fn index(_: &mut Request) -> IronResult<Response> {
let mut resp = Response::new();
let data = make_data();
resp.set_mut(Template::new("some/path/hello", data))
.set_mut(status::Ok);
Ok(resp)
}
fn memory(_: &mut Request) -> IronResult<Response> {
let mut resp = Response::new();
let data = make_data();
resp.set_mut(Template::new("memory", data))
.set_mut(status::Ok);
Ok(resp)
}
fn temp(_: &mut Request) -> IronResult<Response> {
let mut resp = Response::new();
let data = make_data();
resp.set_mut(Template::with(
include_str!("templates/some/path/hello.hbs"),
data,
))
.set_mut(status::Ok);
Ok(resp)
}
fn plain(_: &mut Request) -> IronResult<Response> {
Ok(Response::with((status::Ok, "It works")))
}
|
// an example compression middleware
pub struct GzMiddleware;
impl AfterMiddleware for GzMiddleware {
fn after(&self, _: &mut Request, mut resp: Response) -> IronResult<Response> {
let compressed_bytes = resp.body.as_mut().map(|b| {
let mut encoder = GzEncoder::new(Vec::new(), Compression::Best);
{
let _ = b.write_body(&mut encoder);
}
encoder.finish().unwrap()
});
if let Some(b) = compressed_bytes {
resp.headers.set(ContentEncoding(vec![Encoding::Gzip]));
resp.set_mut(b);
}
Ok(resp)
}
}
fn main() {
env_logger::init().unwrap();
let mut hbse = HandlebarsEngine::new();
// add a directory source, all files with .hbs suffix will be loaded as template
hbse.add(Box::new(DirectorySource::new(
"./examples/templates/",
".hbs",
)));
let mem_templates = btreemap! {
"memory".to_owned() => include_str!("templates/some/path/hello.hbs").to_owned()
};
// add a memory based source
hbse.add(Box::new(MemorySource(mem_templates)));
// load templates from all registered sources
if let Err(r) = hbse.reload() {
panic!("{}", r);
}
hbse.handlebars_mut().register_helper(
"some_helper",
Box::new(
|_: &Helper,
_: &Handlebars,
_: &Context,
_: &mut RenderContext,
_: &mut dyn Output|
-> Result<(), RenderError> { Ok(()) },
),
);
let mut router = Router::new();
router
.get("/", index, "index")
.get("/mem", memory, "memory")
.get("/temp", temp, "temp")
.get("/plain", plain, "plain");
let mut chain = Chain::new(router);
chain.link_after(hbse);
chain.link_after(GzMiddleware);
println!("Server running at http://localhost:3000/");
Iron::new(chain).http("localhost:3000").unwrap();
}
|
random_line_split
|
|
compress.rs
|
extern crate env_logger;
extern crate handlebars_iron as hbs;
extern crate iron;
extern crate router;
extern crate serde;
extern crate serde_json;
#[macro_use]
extern crate serde_derive;
#[macro_use]
extern crate maplit;
extern crate flate2;
use hbs::handlebars::{Context, Handlebars, Helper, Output, RenderContext, RenderError};
use hbs::{DirectorySource, HandlebarsEngine, MemorySource, Template};
use iron::headers::{ContentEncoding, Encoding};
use iron::prelude::*;
use iron::{status, AfterMiddleware};
use router::Router;
use flate2::write::GzEncoder;
use flate2::Compression;
mod data {
use hbs::handlebars::to_json;
use serde_json::value::{Map, Value};
#[derive(Serialize, Debug)]
pub struct Team {
name: String,
pts: u16,
}
pub fn make_data() -> Map<String, Value> {
let mut data = Map::new();
data.insert("year".to_string(), to_json(&"2015".to_owned()));
let teams = vec![
Team {
name: "Jiangsu Sainty".to_string(),
pts: 43u16,
},
Team {
name: "Beijing Guoan".to_string(),
pts: 27u16,
},
Team {
name: "Guangzhou Evergrand".to_string(),
pts: 22u16,
},
Team {
name: "Shandong Luneng".to_string(),
pts: 12u16,
},
];
data.insert("teams".to_string(), to_json(&teams));
data.insert("engine".to_string(), to_json(&"serde_json".to_owned()));
data
}
}
use data::*;
/// the handlers
fn index(_: &mut Request) -> IronResult<Response> {
let mut resp = Response::new();
let data = make_data();
resp.set_mut(Template::new("some/path/hello", data))
.set_mut(status::Ok);
Ok(resp)
}
fn memory(_: &mut Request) -> IronResult<Response> {
let mut resp = Response::new();
let data = make_data();
resp.set_mut(Template::new("memory", data))
.set_mut(status::Ok);
Ok(resp)
}
fn
|
(_: &mut Request) -> IronResult<Response> {
let mut resp = Response::new();
let data = make_data();
resp.set_mut(Template::with(
include_str!("templates/some/path/hello.hbs"),
data,
))
.set_mut(status::Ok);
Ok(resp)
}
fn plain(_: &mut Request) -> IronResult<Response> {
Ok(Response::with((status::Ok, "It works")))
}
// an example compression middleware
pub struct GzMiddleware;
impl AfterMiddleware for GzMiddleware {
fn after(&self, _: &mut Request, mut resp: Response) -> IronResult<Response> {
let compressed_bytes = resp.body.as_mut().map(|b| {
let mut encoder = GzEncoder::new(Vec::new(), Compression::Best);
{
let _ = b.write_body(&mut encoder);
}
encoder.finish().unwrap()
});
if let Some(b) = compressed_bytes {
resp.headers.set(ContentEncoding(vec![Encoding::Gzip]));
resp.set_mut(b);
}
Ok(resp)
}
}
fn main() {
env_logger::init().unwrap();
let mut hbse = HandlebarsEngine::new();
// add a directory source, all files with .hbs suffix will be loaded as template
hbse.add(Box::new(DirectorySource::new(
"./examples/templates/",
".hbs",
)));
let mem_templates = btreemap! {
"memory".to_owned() => include_str!("templates/some/path/hello.hbs").to_owned()
};
// add a memory based source
hbse.add(Box::new(MemorySource(mem_templates)));
// load templates from all registered sources
if let Err(r) = hbse.reload() {
panic!("{}", r);
}
hbse.handlebars_mut().register_helper(
"some_helper",
Box::new(
|_: &Helper,
_: &Handlebars,
_: &Context,
_: &mut RenderContext,
_: &mut dyn Output|
-> Result<(), RenderError> { Ok(()) },
),
);
let mut router = Router::new();
router
.get("/", index, "index")
.get("/mem", memory, "memory")
.get("/temp", temp, "temp")
.get("/plain", plain, "plain");
let mut chain = Chain::new(router);
chain.link_after(hbse);
chain.link_after(GzMiddleware);
println!("Server running at http://localhost:3000/");
Iron::new(chain).http("localhost:3000").unwrap();
}
|
temp
|
identifier_name
|
cedar.js
|
'use strict';
/**
* Cedar
*
* Generic charting / visualization library for the ArcGIS Platform
* that leverages vega + d3 internally.
*/
/**
* Constructor
* @param {object} options Cedar options
*/
var Cedar = function Cedar(options){
//close over this for use in callbacks
var self = this;
//ensure an opts object
var opts = options || {};
/**
* Internals for holding state
*/
// Array to hold event handlers
this._events = [];
//initialize the internal definition hash
this._definition = Cedar._defaultDefinition();
//the vega view aka the chart
this._view = undefined;
//queue to hold methods called while
//xhrs are in progress
this._methodQueue=[];
/**
* Flag used to determine if the library is
* waiting for an xhr to return.
*/
this._pendingXhr = false;
//defintion
if(opts.definition){
//is it an object or string(assumed to be url)
if(typeof opts.definition === 'object'){
//hold onto the definition
this._definition = opts.definition;
}else if(typeof opts.definition === 'string' ){
//assume it's a url (relative or abs) and fetch the definition object
this._pendingXhr = true;
Cedar.getJson(opts.definition, function(err,data){
self._pendingXhr = false;
self._definition = data;
self._purgeMethodQueue();
});
}else{
throw new Error('parameter definition must be an object or string (url)');
}
}
if(opts.override) {
this._definition.override = opts.override;
}
//template
if(opts.specification){
//is it an object or string(assumed to be url)
if(typeof opts.specification === 'object')
|
else if(typeof opts.specification === 'string' ){
//assume it's a url (relative or abs) and fetch the template object
this._pendingXhr = true;
Cedar.getJson(opts.specification, function(err,data){
self._pendingXhr = false;
self._definition.specification = data;
self._purgeMethodQueue();
});
}else{
throw new Error('parameter template must be an object or string (url)');
}
}
//allow a dataset to be passed in...
if(opts.dataset && typeof opts.dataset === 'object'){
var defaultQuery = Cedar._defaultQuery();
if(!opts.dataset.query){
opts.dataset.query = defaultQuery;
}else{
opts.dataset.query = _.defaults(opts.dataset.query, defaultQuery);
}
//assign it
this._definition.dataset = opts.dataset;
}
/**
* Properties
*
* ES 5.1 syntax, so IE 8 & lower won't work
*
* If the val is a url, should we expect
* cedar to fetch the object?
*
* I'd say no... as that violates the principal
* of least suprise. Also - cedar has a .getJSON
* helper method the dev should use.
*
*/
Object.defineProperty(this, 'dataset', {
get: function() {
return this._definition.dataset;
},
set: function(val) {
this._definition.dataset = val;
}
});
Object.defineProperty(this, 'specification', {
get: function() {
return this._definition.specification;
},
set: function(val) {
this._definition.specification = val;
}
});
Object.defineProperty(this, 'override', {
get: function() {
return this._definition.override;
},
set: function(val) {
this._definition.override = val;
}
});
};
/**
* Inspect the current state of the object
* and determine if we have sufficient information
* to render the chart
* @return {object} Hash of the draw state + any missing requirements
*/
Cedar.prototype.canDraw = function(){
//dataset?
//dataset.url || dataset.data?
//dataset.mappings?
//specification?
//specification.template?
//specification.inputs?
//specification.inputs ~ dataset.mappings?
return {drawable:true, errs:[]};
};
/**
* Render a chart in the specified element
* @param {object} options
*
* options.elementId [required] Id of the Dom element into which the chart will be rendered
* options.token [optional] Token to be used if the data or spec are on a secured server
*/
Cedar.prototype.show = function(options){
if(this._pendingXhr){
this._addToMethodQueue('show', [options]);
}else{
var err;
//ensure we got an elementId
if( !options.elementId ){
err= "Cedar.show requires options.elementId";
}
//TODO: check if element exists in the page
if(d3.select(options.elementId)[0][0] === null){
err = "Element " + options.elementId + " is not present in the DOM";
}
//hold onto the id
this._elementId = options.elementId;
//hold onto the token
if(options.token){
this._token = options.token;
}
if( err ){
throw new Error( err );
}
var chk = this.canDraw();
if(chk.drawable){
//update centralizes the spec compilation & drawing
this.update();
}else{
//report the issues
var errs = chk.issues.join(',');
throw new Error('Chart can not be drawn because: ' + errs);
}
}
};
/**
* Render the chart using the internal state
* Should be called after a user modifies the
* of the dataset, query, mappings or template
*/
Cedar.prototype.update = function(){
var self = this;
if(this._pendingXhr){
this._addToMethodQueue('update');
}else{
if(this._view){
//remove handlers
//TODO Remove existing handlers
this._remove(this._view);
}
try{
//extend the mappings w the data
var compiledMappings = Cedar._compileMappings(this._definition.dataset, this._definition.specification.inputs);
//compile the template + dataset --> vega spec
var spec = JSON.parse(Cedar._supplant(JSON.stringify(this._definition.specification.template), compiledMappings));
// merge in user specified style overrides
spec = Cedar._mergeRecursive(spec, this._definition.override);
//use vega to parse the spec
//it will handle the spec as an object or url
vg.parse.spec(spec, function(chartCtor) {
//create the view
self._view = chartCtor({el: self._elementId});
//render into the element
self._view.update();
//attach event proxies
self._attach(self._view);
});
}
catch(ex){
throw(ex);
}
}
};
/**
* Attach the generic proxy handlers to the chart view
*/
Cedar.prototype._attach = function(view){
view.on('mouseover', this._handler('mouseover'));
view.on('mouseout', this._handler('mouseout'));
view.on('click', this._handler("click"));
};
/**
* Remove all event handlers from the view
*/
Cedar.prototype._remove = function(view){
view.off('mouseover');
view.off('mouseout');
view.off('click');
};
/**
* Helper function that validates that the
* mappings hash contains values for all
* the inputs
* @param {array} inputs Array of inputs
* @param {object} mappings Hash of mappings
* @return {array} Missing mappings
*/
Cedar._validateMappings = function(inputs, mappings){
var missingInputs = [], input;
for(var i=0;i<inputs.length;i++){
input = inputs[i];
if(input.required){
if(!mappings[input.name]){
missingInputs.push(input.name);
}
}
}
return missingInputs;
};
/**
* Return a default definition object
*/
Cedar._defaultDefinition = function(){
var defn = {
"dataset": {
"url":"",
"query": this._defaultQuery()
},
"template":{}
};
defn.dataset.query = Cedar._defaultQuery();
return defn;
};
/**
* Default Query Object
*/
Cedar._defaultQuery = function(){
var defaultQuery = {
"where": "1=1",
"returnGeometry": false,
"returnDistinctValues": false,
"returnIdsOnly": false,
"returnCountOnly": false,
"outFields": "*",
"f": "json"
};
return defaultQuery;
};
/**
* Generic event handler proxy
*/
Cedar.prototype._handler = function(evtName) {
var self = this;
//return a handler function w/ the events hash closed over
var handler = function(evt, item){
self._events.forEach( function(registeredHandler){
if(registeredHandler.type === evtName){
//invoke the callback with the data
registeredHandler.callback(item.datum.data.attributes);
}
});
};
return handler;
};
/**
* Add a handler for the named event
*/
Cedar.prototype.on = function(evtName, callback){
this._events.push({"type":evtName, "callback":callback});
};
/**
* Remove a handler for the named event
*/
Cedar.prototype.off = function(evtName /*, callback */){
console.log('Handler for ' + evtName +' removed...');
};
/**
* Creates an entry in the method queue, excuted
* once a pending xhr is completed
*/
Cedar.prototype._addToMethodQueue = function(name, args){
this._methodQueue.push({ method: name, args: args });
};
/**
* empties the method queue by calling the queued methods
* This helps build a more syncronous api, while still
* doing async things in the code
*/
Cedar.prototype._purgeMethodQueue = function(){
var self = this;
if(self._methodQueue.length > 0){
for(var i=0;i<self._methodQueue.length;i++){
var action = self._methodQueue[i];
self[action.method].apply(self, action.args);
}
}
};
/**
* fetch json from a url
* @param {string} url Url to json file
* @param {Function} callback node-style callback function (err, data)
*/
Cedar.getJson = function( url, callback ){
d3.json(url, function(err,data) {
if(err){
callback('Error loading ' + url + ' ' + err.message);
}
callback(null, data);
});
};
/**
* Compile the data url into the mappings
*/
Cedar._compileMappings = function(dataset, inputs){
//clone the query so we don't modifiy it
var mergedQuery;
var defaultQuery = Cedar._defaultQuery();
//make sure that the mappings have all the required fields and/or have defaults applied
dataset.mappings = Cedar._applyDefaultsToMappings(dataset.mappings, inputs);
//ensure that we have a query
if(dataset.query){
mergedQuery = _.clone(dataset.query);
//ensure we have all needed properties on the query
//TODO: use a microlib instead of underscore
_.defaults(mergedQuery, defaultQuery);
}else{
mergedQuery = defaultQuery;
}
//Handle bbox
if(mergedQuery.bbox){
//make sure a geometry was not also passed in
if(mergedQuery.geometry){
throw new Error('Dataset.query can not have both a geometry and a bbox specified');
}
//get the bbox
var bboxArr = mergedQuery.bbox.split(',');
//remove it so it's not serialized as-is
delete mergedQuery.bbox;
//cook it into the json string
mergedQuery.geometry = JSON.stringify({"xmin": bboxArr[0], "ymin": bboxArr[2],"xmax": bboxArr[1], "ymax": bboxArr[3] });
//set the spatial ref as geographic
mergedQuery.inSR = '4326';
}
// add any aggregations
if(dataset.mappings.group) {
mergedQuery.groupByFieldsForStatistics = dataset.mappings.group.field;
}
if(dataset.mappings.count) {
mergedQuery.orderByFields = dataset.mappings.count.field + "_SUM";
mergedQuery.outStatistics = JSON.stringify([{"statisticType": "sum", "onStatisticField": dataset.mappings.count.field, "outStatisticFieldName": dataset.mappings.count.field + "_SUM"}]);
}
//compile the url
var dataUrl = dataset.url + "/query?" + this._serializeQueryParams(mergedQuery);
//clone the mappings and extend it
//TODO: add cloning microlib
var cloneMappings = _.clone(dataset.mappings);
//attach the data node and return
cloneMappings.data = dataUrl;
return cloneMappings;
};
Cedar._applyDefaultsToMappings = function(mappings, inputs){
var errs = [];
//loop over the inputs
for(var i =0; i < inputs.length; i++){
//get the input
var input = inputs[i];
//if it's required and not in the mappings, add an exception
if(input.required && !mappings[input.name] ){
errs.push(input.name);
}
//if it's not required, has a default and not in the mappings
if(!input.required && !mappings[input.name] && input.default){
//add the default
mappings[input.name] = input.default;
}
}
if(errs.length > 0){
throw new Error('Required Mappings Missing: ' + errs.join(','));
}else{
return mappings;
}
};
/**
* Token Replacement on a string
* @param {string} template string template
* @param {object} params object hash that maps to the tokens to be replaced
* @return {string} string with values replaced
*/
Cedar._supplant = function( tmpl, params ){
console.log('Mappings: ', params);
return tmpl.replace(/{([^{}]*)}/g,
function (a, b) {
var r = Cedar._getTokenValue(params, b);
return typeof r === 'string' || typeof r === 'number' ? r : a;
}
);
};
/*
* Recursively merge properties of two objects
*/
Cedar._mergeRecursive = function(obj1, obj2) {
for (var p in obj2) {
try {
// Property in destination object set; update its value.
if ( obj2[p].constructor===Object || obj2[p].constructor===Array) {
obj1[p] = Cedar._mergeRecursive(obj1[p], obj2[p]);
} else {
obj1[p] = obj2[p];
}
} catch(e) {
// Property in destination object not set; create it and set its value.
obj1[p] = obj2[p];
}
}
return obj1;
};
/**
* Get the value of a token from a hash
* @param {[type]} tokens [description]
* @param {[type]} tokenName [description]
* @return {[type]} [description]
* Pulled from gulp-token-replace (MIT license)
* https://github.com/Pictela/gulp-token-replace/blob/master/index.js
*
*/
Cedar._getTokenValue = function(tokens, tokenName) {
var tmpTokens = tokens;
var tokenNameParts = tokenName.split('.');
for (var i = 0; i < tokenNameParts.length; i++) {
if (tmpTokens.hasOwnProperty(tokenNameParts[i])) {
tmpTokens = tmpTokens[tokenNameParts[i]];
} else {
return null;
}
}
return tmpTokens;
};
/**
* Serilize an object into a query string
* @param {object} params Params for the query string
* @return {string} query string
*/
Cedar._serializeQueryParams = function(params) {
var str = [];
for(var p in params){
if (params.hasOwnProperty(p)) {
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(params[p]));
}
}
var queryString = str.join("&");
return queryString;
};
|
{
//hold onto the template
this._definition.specification = opts.specification;
}
|
conditional_block
|
cedar.js
|
'use strict';
/**
* Cedar
*
* Generic charting / visualization library for the ArcGIS Platform
* that leverages vega + d3 internally.
*/
/**
* Constructor
* @param {object} options Cedar options
*/
var Cedar = function Cedar(options){
//close over this for use in callbacks
var self = this;
//ensure an opts object
var opts = options || {};
/**
* Internals for holding state
*/
// Array to hold event handlers
this._events = [];
//initialize the internal definition hash
this._definition = Cedar._defaultDefinition();
//the vega view aka the chart
this._view = undefined;
//queue to hold methods called while
//xhrs are in progress
this._methodQueue=[];
/**
* Flag used to determine if the library is
* waiting for an xhr to return.
*/
this._pendingXhr = false;
//defintion
if(opts.definition){
//is it an object or string(assumed to be url)
if(typeof opts.definition === 'object'){
//hold onto the definition
this._definition = opts.definition;
}else if(typeof opts.definition === 'string' ){
//assume it's a url (relative or abs) and fetch the definition object
this._pendingXhr = true;
Cedar.getJson(opts.definition, function(err,data){
self._pendingXhr = false;
|
}
}
if(opts.override) {
this._definition.override = opts.override;
}
//template
if(opts.specification){
//is it an object or string(assumed to be url)
if(typeof opts.specification === 'object'){
//hold onto the template
this._definition.specification = opts.specification;
}else if(typeof opts.specification === 'string' ){
//assume it's a url (relative or abs) and fetch the template object
this._pendingXhr = true;
Cedar.getJson(opts.specification, function(err,data){
self._pendingXhr = false;
self._definition.specification = data;
self._purgeMethodQueue();
});
}else{
throw new Error('parameter template must be an object or string (url)');
}
}
//allow a dataset to be passed in...
if(opts.dataset && typeof opts.dataset === 'object'){
var defaultQuery = Cedar._defaultQuery();
if(!opts.dataset.query){
opts.dataset.query = defaultQuery;
}else{
opts.dataset.query = _.defaults(opts.dataset.query, defaultQuery);
}
//assign it
this._definition.dataset = opts.dataset;
}
/**
* Properties
*
* ES 5.1 syntax, so IE 8 & lower won't work
*
* If the val is a url, should we expect
* cedar to fetch the object?
*
* I'd say no... as that violates the principal
* of least suprise. Also - cedar has a .getJSON
* helper method the dev should use.
*
*/
Object.defineProperty(this, 'dataset', {
get: function() {
return this._definition.dataset;
},
set: function(val) {
this._definition.dataset = val;
}
});
Object.defineProperty(this, 'specification', {
get: function() {
return this._definition.specification;
},
set: function(val) {
this._definition.specification = val;
}
});
Object.defineProperty(this, 'override', {
get: function() {
return this._definition.override;
},
set: function(val) {
this._definition.override = val;
}
});
};
/**
* Inspect the current state of the object
* and determine if we have sufficient information
* to render the chart
* @return {object} Hash of the draw state + any missing requirements
*/
Cedar.prototype.canDraw = function(){
//dataset?
//dataset.url || dataset.data?
//dataset.mappings?
//specification?
//specification.template?
//specification.inputs?
//specification.inputs ~ dataset.mappings?
return {drawable:true, errs:[]};
};
/**
* Render a chart in the specified element
* @param {object} options
*
* options.elementId [required] Id of the Dom element into which the chart will be rendered
* options.token [optional] Token to be used if the data or spec are on a secured server
*/
Cedar.prototype.show = function(options){
if(this._pendingXhr){
this._addToMethodQueue('show', [options]);
}else{
var err;
//ensure we got an elementId
if( !options.elementId ){
err= "Cedar.show requires options.elementId";
}
//TODO: check if element exists in the page
if(d3.select(options.elementId)[0][0] === null){
err = "Element " + options.elementId + " is not present in the DOM";
}
//hold onto the id
this._elementId = options.elementId;
//hold onto the token
if(options.token){
this._token = options.token;
}
if( err ){
throw new Error( err );
}
var chk = this.canDraw();
if(chk.drawable){
//update centralizes the spec compilation & drawing
this.update();
}else{
//report the issues
var errs = chk.issues.join(',');
throw new Error('Chart can not be drawn because: ' + errs);
}
}
};
/**
* Render the chart using the internal state
* Should be called after a user modifies the
* of the dataset, query, mappings or template
*/
Cedar.prototype.update = function(){
var self = this;
if(this._pendingXhr){
this._addToMethodQueue('update');
}else{
if(this._view){
//remove handlers
//TODO Remove existing handlers
this._remove(this._view);
}
try{
//extend the mappings w the data
var compiledMappings = Cedar._compileMappings(this._definition.dataset, this._definition.specification.inputs);
//compile the template + dataset --> vega spec
var spec = JSON.parse(Cedar._supplant(JSON.stringify(this._definition.specification.template), compiledMappings));
// merge in user specified style overrides
spec = Cedar._mergeRecursive(spec, this._definition.override);
//use vega to parse the spec
//it will handle the spec as an object or url
vg.parse.spec(spec, function(chartCtor) {
//create the view
self._view = chartCtor({el: self._elementId});
//render into the element
self._view.update();
//attach event proxies
self._attach(self._view);
});
}
catch(ex){
throw(ex);
}
}
};
/**
* Attach the generic proxy handlers to the chart view
*/
Cedar.prototype._attach = function(view){
view.on('mouseover', this._handler('mouseover'));
view.on('mouseout', this._handler('mouseout'));
view.on('click', this._handler("click"));
};
/**
* Remove all event handlers from the view
*/
Cedar.prototype._remove = function(view){
view.off('mouseover');
view.off('mouseout');
view.off('click');
};
/**
* Helper function that validates that the
* mappings hash contains values for all
* the inputs
* @param {array} inputs Array of inputs
* @param {object} mappings Hash of mappings
* @return {array} Missing mappings
*/
Cedar._validateMappings = function(inputs, mappings){
var missingInputs = [], input;
for(var i=0;i<inputs.length;i++){
input = inputs[i];
if(input.required){
if(!mappings[input.name]){
missingInputs.push(input.name);
}
}
}
return missingInputs;
};
/**
* Return a default definition object
*/
Cedar._defaultDefinition = function(){
var defn = {
"dataset": {
"url":"",
"query": this._defaultQuery()
},
"template":{}
};
defn.dataset.query = Cedar._defaultQuery();
return defn;
};
/**
* Default Query Object
*/
Cedar._defaultQuery = function(){
var defaultQuery = {
"where": "1=1",
"returnGeometry": false,
"returnDistinctValues": false,
"returnIdsOnly": false,
"returnCountOnly": false,
"outFields": "*",
"f": "json"
};
return defaultQuery;
};
/**
* Generic event handler proxy
*/
Cedar.prototype._handler = function(evtName) {
var self = this;
//return a handler function w/ the events hash closed over
var handler = function(evt, item){
self._events.forEach( function(registeredHandler){
if(registeredHandler.type === evtName){
//invoke the callback with the data
registeredHandler.callback(item.datum.data.attributes);
}
});
};
return handler;
};
/**
* Add a handler for the named event
*/
Cedar.prototype.on = function(evtName, callback){
this._events.push({"type":evtName, "callback":callback});
};
/**
* Remove a handler for the named event
*/
Cedar.prototype.off = function(evtName /*, callback */){
console.log('Handler for ' + evtName +' removed...');
};
/**
* Creates an entry in the method queue, excuted
* once a pending xhr is completed
*/
Cedar.prototype._addToMethodQueue = function(name, args){
this._methodQueue.push({ method: name, args: args });
};
/**
* empties the method queue by calling the queued methods
* This helps build a more syncronous api, while still
* doing async things in the code
*/
Cedar.prototype._purgeMethodQueue = function(){
var self = this;
if(self._methodQueue.length > 0){
for(var i=0;i<self._methodQueue.length;i++){
var action = self._methodQueue[i];
self[action.method].apply(self, action.args);
}
}
};
/**
* fetch json from a url
* @param {string} url Url to json file
* @param {Function} callback node-style callback function (err, data)
*/
Cedar.getJson = function( url, callback ){
d3.json(url, function(err,data) {
if(err){
callback('Error loading ' + url + ' ' + err.message);
}
callback(null, data);
});
};
/**
* Compile the data url into the mappings
*/
Cedar._compileMappings = function(dataset, inputs){
//clone the query so we don't modifiy it
var mergedQuery;
var defaultQuery = Cedar._defaultQuery();
//make sure that the mappings have all the required fields and/or have defaults applied
dataset.mappings = Cedar._applyDefaultsToMappings(dataset.mappings, inputs);
//ensure that we have a query
if(dataset.query){
mergedQuery = _.clone(dataset.query);
//ensure we have all needed properties on the query
//TODO: use a microlib instead of underscore
_.defaults(mergedQuery, defaultQuery);
}else{
mergedQuery = defaultQuery;
}
//Handle bbox
if(mergedQuery.bbox){
//make sure a geometry was not also passed in
if(mergedQuery.geometry){
throw new Error('Dataset.query can not have both a geometry and a bbox specified');
}
//get the bbox
var bboxArr = mergedQuery.bbox.split(',');
//remove it so it's not serialized as-is
delete mergedQuery.bbox;
//cook it into the json string
mergedQuery.geometry = JSON.stringify({"xmin": bboxArr[0], "ymin": bboxArr[2],"xmax": bboxArr[1], "ymax": bboxArr[3] });
//set the spatial ref as geographic
mergedQuery.inSR = '4326';
}
// add any aggregations
if(dataset.mappings.group) {
mergedQuery.groupByFieldsForStatistics = dataset.mappings.group.field;
}
if(dataset.mappings.count) {
mergedQuery.orderByFields = dataset.mappings.count.field + "_SUM";
mergedQuery.outStatistics = JSON.stringify([{"statisticType": "sum", "onStatisticField": dataset.mappings.count.field, "outStatisticFieldName": dataset.mappings.count.field + "_SUM"}]);
}
//compile the url
var dataUrl = dataset.url + "/query?" + this._serializeQueryParams(mergedQuery);
//clone the mappings and extend it
//TODO: add cloning microlib
var cloneMappings = _.clone(dataset.mappings);
//attach the data node and return
cloneMappings.data = dataUrl;
return cloneMappings;
};
Cedar._applyDefaultsToMappings = function(mappings, inputs){
var errs = [];
//loop over the inputs
for(var i =0; i < inputs.length; i++){
//get the input
var input = inputs[i];
//if it's required and not in the mappings, add an exception
if(input.required && !mappings[input.name] ){
errs.push(input.name);
}
//if it's not required, has a default and not in the mappings
if(!input.required && !mappings[input.name] && input.default){
//add the default
mappings[input.name] = input.default;
}
}
if(errs.length > 0){
throw new Error('Required Mappings Missing: ' + errs.join(','));
}else{
return mappings;
}
};
/**
* Token Replacement on a string
* @param {string} template string template
* @param {object} params object hash that maps to the tokens to be replaced
* @return {string} string with values replaced
*/
Cedar._supplant = function( tmpl, params ){
console.log('Mappings: ', params);
return tmpl.replace(/{([^{}]*)}/g,
function (a, b) {
var r = Cedar._getTokenValue(params, b);
return typeof r === 'string' || typeof r === 'number' ? r : a;
}
);
};
/*
* Recursively merge properties of two objects
*/
Cedar._mergeRecursive = function(obj1, obj2) {
for (var p in obj2) {
try {
// Property in destination object set; update its value.
if ( obj2[p].constructor===Object || obj2[p].constructor===Array) {
obj1[p] = Cedar._mergeRecursive(obj1[p], obj2[p]);
} else {
obj1[p] = obj2[p];
}
} catch(e) {
// Property in destination object not set; create it and set its value.
obj1[p] = obj2[p];
}
}
return obj1;
};
/**
* Get the value of a token from a hash
* @param {[type]} tokens [description]
* @param {[type]} tokenName [description]
* @return {[type]} [description]
* Pulled from gulp-token-replace (MIT license)
* https://github.com/Pictela/gulp-token-replace/blob/master/index.js
*
*/
Cedar._getTokenValue = function(tokens, tokenName) {
var tmpTokens = tokens;
var tokenNameParts = tokenName.split('.');
for (var i = 0; i < tokenNameParts.length; i++) {
if (tmpTokens.hasOwnProperty(tokenNameParts[i])) {
tmpTokens = tmpTokens[tokenNameParts[i]];
} else {
return null;
}
}
return tmpTokens;
};
/**
* Serilize an object into a query string
* @param {object} params Params for the query string
* @return {string} query string
*/
Cedar._serializeQueryParams = function(params) {
var str = [];
for(var p in params){
if (params.hasOwnProperty(p)) {
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(params[p]));
}
}
var queryString = str.join("&");
return queryString;
};
|
self._definition = data;
self._purgeMethodQueue();
});
}else{
throw new Error('parameter definition must be an object or string (url)');
|
random_line_split
|
plot_label_foci.py
|
"""
=======================
Generate Surface Labels
=======================
Define a label that is centered on a specific vertex in the surface mesh. Plot
that label and the focus that defines its center.
"""
print __doc__
from surfer import Brain, utils
subject_id = "fsaverage"
"""
Bring up the visualization.
"""
brain = Brain(subject_id, "lh", "inflated")
"""
First we'll identify a stereotaxic focus in the MNI coordinate system. This
might be a peak activations from a volume based analysis.
"""
coord = [-43, 25, 24]
"""
Next we grow a label along the surface around the neareset vertex to this
coordinate in the white surface mesh. The `n_steps` argument controls the size
of the resulting label.
"""
utils.coord_to_label(subject_id, coord, label='example_data/coord',
hemi='lh', n_steps=25, map_surface="white")
brain.add_label('example_data/coord-lh.label', color="darkseagreen", alpha=.8)
"""
Now we plot the focus on the inflated surface at the vertex identified in the
previous step.
"""
brain.add_foci([coord], map_surface="white", color="mediumseagreen")
"""
We can also do this using a vertex index, perhaps defined as the peak
activation in a surface analysis. This will be more accurate than using a
volume-based focus.
"""
coord = 0
utils.coord_to_label(subject_id, coord, label='example_data/coord',
hemi='lh', n_steps=40, map_surface="white",
coord_as_vert=True)
brain.add_label('example_data/coord-lh.label', color='royalblue', alpha=.8)
"""
Now we plot the foci on the inflated surface. We will map the foci onto the
surface by finding the vertex on the "white" mesh that is closest to the
coordinate of the point we want to display.
"""
brain.add_foci([coord], map_surface="white", coords_as_verts=True,
color="mediumblue")
"""
|
Set the camera position to show the extent of the labels.
"""
brain.show_view(dict(elevation=40, distance=430))
|
random_line_split
|
|
hero-search.component.ts
|
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
// Observable class extensions
import 'rxjs/add/observable/of';
// Observable operators
|
@Component({
selector: 'hero-search',
templateUrl: './hero-search.component.html',
styleUrls: [ './hero-search.component.css' ],
providers: [HeroSearchService]
})
export class HeroSearchComponent implements OnInit {
heroes: Observable<Hero[]>;
private searchTerms = new Subject<string>();
constructor(
private heroSearchService: HeroSearchService,
private router: Router) {}
// Push a search term into the observable stream.
search(term: string): void {
this.searchTerms.next(term);
}
ngOnInit(): void {
this.heroes = this.searchTerms
.debounceTime(300) // wait 300ms after each keystroke before considering the term
.distinctUntilChanged() // ignore if next search term is same as previous
.switchMap(term => term // switch to new observable each time the term changes
// return the http search observable
? this.heroSearchService.search(term)
// or the observable of empty heroes if there was no search term
: Observable.of<Hero[]>([]))
.catch(error => {
// TODO: add real error handling
console.log(error);
return Observable.of<Hero[]>([]);
});
}
gotoDetail(hero: Hero): void {
let link = ['/detail', hero.id];
this.router.navigate(link);
}
}
|
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';
import { HeroSearchService } from './hero-search.service';
import { Hero } from './hero';
|
random_line_split
|
hero-search.component.ts
|
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
// Observable class extensions
import 'rxjs/add/observable/of';
// Observable operators
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';
import { HeroSearchService } from './hero-search.service';
import { Hero } from './hero';
@Component({
selector: 'hero-search',
templateUrl: './hero-search.component.html',
styleUrls: [ './hero-search.component.css' ],
providers: [HeroSearchService]
})
export class HeroSearchComponent implements OnInit {
heroes: Observable<Hero[]>;
private searchTerms = new Subject<string>();
constructor(
private heroSearchService: HeroSearchService,
private router: Router) {}
// Push a search term into the observable stream.
|
(term: string): void {
this.searchTerms.next(term);
}
ngOnInit(): void {
this.heroes = this.searchTerms
.debounceTime(300) // wait 300ms after each keystroke before considering the term
.distinctUntilChanged() // ignore if next search term is same as previous
.switchMap(term => term // switch to new observable each time the term changes
// return the http search observable
? this.heroSearchService.search(term)
// or the observable of empty heroes if there was no search term
: Observable.of<Hero[]>([]))
.catch(error => {
// TODO: add real error handling
console.log(error);
return Observable.of<Hero[]>([]);
});
}
gotoDetail(hero: Hero): void {
let link = ['/detail', hero.id];
this.router.navigate(link);
}
}
|
search
|
identifier_name
|
hero-search.component.ts
|
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
// Observable class extensions
import 'rxjs/add/observable/of';
// Observable operators
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';
import { HeroSearchService } from './hero-search.service';
import { Hero } from './hero';
@Component({
selector: 'hero-search',
templateUrl: './hero-search.component.html',
styleUrls: [ './hero-search.component.css' ],
providers: [HeroSearchService]
})
export class HeroSearchComponent implements OnInit {
heroes: Observable<Hero[]>;
private searchTerms = new Subject<string>();
constructor(
private heroSearchService: HeroSearchService,
private router: Router)
|
// Push a search term into the observable stream.
search(term: string): void {
this.searchTerms.next(term);
}
ngOnInit(): void {
this.heroes = this.searchTerms
.debounceTime(300) // wait 300ms after each keystroke before considering the term
.distinctUntilChanged() // ignore if next search term is same as previous
.switchMap(term => term // switch to new observable each time the term changes
// return the http search observable
? this.heroSearchService.search(term)
// or the observable of empty heroes if there was no search term
: Observable.of<Hero[]>([]))
.catch(error => {
// TODO: add real error handling
console.log(error);
return Observable.of<Hero[]>([]);
});
}
gotoDetail(hero: Hero): void {
let link = ['/detail', hero.id];
this.router.navigate(link);
}
}
|
{}
|
identifier_body
|
conftest.py
|
#! /usr/bin/python
# -*- coding: UTF-8 -*-
# Copyright 2018-2019 Luiko Czub, TestLink-API-Python-client developers
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# ------------------------------------------------------------------------
import os.path
import pytest
from testlink import TestlinkAPIClient, TestlinkAPIGeneric, TestLinkHelper
# example text file attachment = this python file
# why not using os.path.realpath(__file__)
# -> cause __file__ could be compiled python file *.pyc, if the test run is
# repeated without changing the test code
ATTACHMENT_EXAMPLE_TEXT= os.path.join(os.path.dirname(__file__),
os.path.basename(__file__))
#attachemantFile = open(ATTACHMENT_EXAMPLE_TEXT, 'r')
@pytest.fixture()
def attachmentFile():
''' open readonly attachment sample before test and close it afterwards '''
aFile = open(ATTACHMENT_EXAMPLE_TEXT, 'r')
yield aFile
aFile.close()
@pytest.fixture(scope='session')
def api_helper_class():
return TestLinkHelper
@pytest.fixture(scope='session')
def api_generic_client(api_helper_class):
''' Init TestlinkAPIGeneric Client with connection parameters defined in
environment variables
TESTLINK_API_PYTHON_DEVKEY and TESTLINK_API_PYTHON_DEVKEY
'''
return api_helper_class().connect(TestlinkAPIGeneric)
@pytest.fixture(scope='session')
def api_general_client(api_helper_class):
''' Init TestlinkAPIClient Client with connection parameters defined in
environment variables
TESTLINK_API_PYTHON_DEVKEY and TESTLINK_API_PYTHON_DEVKEY
'''
return api_helper_class().connect(TestlinkAPIClient)
@pytest.fixture(scope='session', params=[TestlinkAPIGeneric, TestlinkAPIClient])
def api_client_class(request):
|
@pytest.fixture(scope='session')
def api_client(api_client_class, api_helper_class):
''' Init Testlink API Client class defined in fixtures api_client_class with
connection parameters defined in environment variables
TESTLINK_API_PYTHON_DEVKEY and TESTLINK_API_PYTHON_DEVKEY
Tests will be call for each Testlink API Client class, defined in
fixtures parameter list
'''
return api_helper_class().connect(api_client_class)
|
''' all variations of Testlink API Client classes '''
return request.param
|
identifier_body
|
conftest.py
|
#! /usr/bin/python
# -*- coding: UTF-8 -*-
# Copyright 2018-2019 Luiko Czub, TestLink-API-Python-client developers
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# ------------------------------------------------------------------------
import os.path
import pytest
from testlink import TestlinkAPIClient, TestlinkAPIGeneric, TestLinkHelper
# example text file attachment = this python file
# why not using os.path.realpath(__file__)
# -> cause __file__ could be compiled python file *.pyc, if the test run is
# repeated without changing the test code
ATTACHMENT_EXAMPLE_TEXT= os.path.join(os.path.dirname(__file__),
os.path.basename(__file__))
#attachemantFile = open(ATTACHMENT_EXAMPLE_TEXT, 'r')
@pytest.fixture()
def attachmentFile():
''' open readonly attachment sample before test and close it afterwards '''
aFile = open(ATTACHMENT_EXAMPLE_TEXT, 'r')
yield aFile
aFile.close()
@pytest.fixture(scope='session')
def api_helper_class():
return TestLinkHelper
@pytest.fixture(scope='session')
def api_generic_client(api_helper_class):
''' Init TestlinkAPIGeneric Client with connection parameters defined in
environment variables
TESTLINK_API_PYTHON_DEVKEY and TESTLINK_API_PYTHON_DEVKEY
'''
return api_helper_class().connect(TestlinkAPIGeneric)
@pytest.fixture(scope='session')
def api_general_client(api_helper_class):
''' Init TestlinkAPIClient Client with connection parameters defined in
environment variables
TESTLINK_API_PYTHON_DEVKEY and TESTLINK_API_PYTHON_DEVKEY
'''
return api_helper_class().connect(TestlinkAPIClient)
|
def api_client_class(request):
''' all variations of Testlink API Client classes '''
return request.param
@pytest.fixture(scope='session')
def api_client(api_client_class, api_helper_class):
''' Init Testlink API Client class defined in fixtures api_client_class with
connection parameters defined in environment variables
TESTLINK_API_PYTHON_DEVKEY and TESTLINK_API_PYTHON_DEVKEY
Tests will be call for each Testlink API Client class, defined in
fixtures parameter list
'''
return api_helper_class().connect(api_client_class)
|
@pytest.fixture(scope='session', params=[TestlinkAPIGeneric, TestlinkAPIClient])
|
random_line_split
|
conftest.py
|
#! /usr/bin/python
# -*- coding: UTF-8 -*-
# Copyright 2018-2019 Luiko Czub, TestLink-API-Python-client developers
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# ------------------------------------------------------------------------
import os.path
import pytest
from testlink import TestlinkAPIClient, TestlinkAPIGeneric, TestLinkHelper
# example text file attachment = this python file
# why not using os.path.realpath(__file__)
# -> cause __file__ could be compiled python file *.pyc, if the test run is
# repeated without changing the test code
ATTACHMENT_EXAMPLE_TEXT= os.path.join(os.path.dirname(__file__),
os.path.basename(__file__))
#attachemantFile = open(ATTACHMENT_EXAMPLE_TEXT, 'r')
@pytest.fixture()
def attachmentFile():
''' open readonly attachment sample before test and close it afterwards '''
aFile = open(ATTACHMENT_EXAMPLE_TEXT, 'r')
yield aFile
aFile.close()
@pytest.fixture(scope='session')
def api_helper_class():
return TestLinkHelper
@pytest.fixture(scope='session')
def api_generic_client(api_helper_class):
''' Init TestlinkAPIGeneric Client with connection parameters defined in
environment variables
TESTLINK_API_PYTHON_DEVKEY and TESTLINK_API_PYTHON_DEVKEY
'''
return api_helper_class().connect(TestlinkAPIGeneric)
@pytest.fixture(scope='session')
def
|
(api_helper_class):
''' Init TestlinkAPIClient Client with connection parameters defined in
environment variables
TESTLINK_API_PYTHON_DEVKEY and TESTLINK_API_PYTHON_DEVKEY
'''
return api_helper_class().connect(TestlinkAPIClient)
@pytest.fixture(scope='session', params=[TestlinkAPIGeneric, TestlinkAPIClient])
def api_client_class(request):
''' all variations of Testlink API Client classes '''
return request.param
@pytest.fixture(scope='session')
def api_client(api_client_class, api_helper_class):
''' Init Testlink API Client class defined in fixtures api_client_class with
connection parameters defined in environment variables
TESTLINK_API_PYTHON_DEVKEY and TESTLINK_API_PYTHON_DEVKEY
Tests will be call for each Testlink API Client class, defined in
fixtures parameter list
'''
return api_helper_class().connect(api_client_class)
|
api_general_client
|
identifier_name
|
mips.rs
|
// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use target_strs;
use syntax::abi;
pub fn get_target_strs(target_triple: String, target_os: abi::Os) -> target_strs::t
|
{
return target_strs::t {
module_asm: "".to_string(),
data_layout: match target_os {
abi::OsMacos => {
"E-p:32:32:32\
-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64\
-f32:32:32-f64:64:64\
-v64:64:64-v128:64:128\
-a:0:64-n32".to_string()
}
abi::OsiOS => {
"E-p:32:32:32\
-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64\
-f32:32:32-f64:64:64\
-v64:64:64-v128:64:128\
-a:0:64-n32".to_string()
}
abi::OsWindows => {
"E-p:32:32:32\
-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64\
-f32:32:32-f64:64:64\
-v64:64:64-v128:64:128\
-a:0:64-n32".to_string()
}
abi::OsLinux => {
"E-p:32:32:32\
-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64\
-f32:32:32-f64:64:64\
-v64:64:64-v128:64:128\
-a:0:64-n32".to_string()
}
abi::OsAndroid => {
"E-p:32:32:32\
-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64\
-f32:32:32-f64:64:64\
-v64:64:64-v128:64:128\
-a:0:64-n32".to_string()
}
abi::OsFreebsd | abi::OsDragonfly | abi::OsBitrig | abi::OsOpenbsd => {
"E-p:32:32:32\
-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64\
-f32:32:32-f64:64:64\
-v64:64:64-v128:64:128\
-a:0:64-n32".to_string()
}
},
target_triple: target_triple,
cc_args: Vec::new(),
};
}
|
identifier_body
|
|
mips.rs
|
// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use target_strs;
use syntax::abi;
pub fn get_target_strs(target_triple: String, target_os: abi::Os) -> target_strs::t {
return target_strs::t {
module_asm: "".to_string(),
data_layout: match target_os {
abi::OsMacos => {
"E-p:32:32:32\
-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64\
-f32:32:32-f64:64:64\
-v64:64:64-v128:64:128\
-a:0:64-n32".to_string()
}
abi::OsiOS => {
"E-p:32:32:32\
-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64\
-f32:32:32-f64:64:64\
-v64:64:64-v128:64:128\
-a:0:64-n32".to_string()
}
abi::OsWindows => {
"E-p:32:32:32\
-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64\
-f32:32:32-f64:64:64\
-v64:64:64-v128:64:128\
-a:0:64-n32".to_string()
}
abi::OsLinux => {
"E-p:32:32:32\
-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64\
-f32:32:32-f64:64:64\
-v64:64:64-v128:64:128\
-a:0:64-n32".to_string()
}
abi::OsAndroid =>
|
abi::OsFreebsd | abi::OsDragonfly | abi::OsBitrig | abi::OsOpenbsd => {
"E-p:32:32:32\
-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64\
-f32:32:32-f64:64:64\
-v64:64:64-v128:64:128\
-a:0:64-n32".to_string()
}
},
target_triple: target_triple,
cc_args: Vec::new(),
};
}
|
{
"E-p:32:32:32\
-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64\
-f32:32:32-f64:64:64\
-v64:64:64-v128:64:128\
-a:0:64-n32".to_string()
}
|
conditional_block
|
mips.rs
|
// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use target_strs;
use syntax::abi;
pub fn get_target_strs(target_triple: String, target_os: abi::Os) -> target_strs::t {
return target_strs::t {
module_asm: "".to_string(),
data_layout: match target_os {
abi::OsMacos => {
"E-p:32:32:32\
-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64\
-f32:32:32-f64:64:64\
-v64:64:64-v128:64:128\
-a:0:64-n32".to_string()
}
abi::OsiOS => {
"E-p:32:32:32\
-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64\
-f32:32:32-f64:64:64\
-v64:64:64-v128:64:128\
-a:0:64-n32".to_string()
}
abi::OsWindows => {
"E-p:32:32:32\
-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64\
-f32:32:32-f64:64:64\
-v64:64:64-v128:64:128\
-a:0:64-n32".to_string()
}
abi::OsLinux => {
"E-p:32:32:32\
-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64\
-f32:32:32-f64:64:64\
-v64:64:64-v128:64:128\
-a:0:64-n32".to_string()
}
abi::OsAndroid => {
"E-p:32:32:32\
-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64\
-f32:32:32-f64:64:64\
-v64:64:64-v128:64:128\
-a:0:64-n32".to_string()
}
abi::OsFreebsd | abi::OsDragonfly | abi::OsBitrig | abi::OsOpenbsd => {
"E-p:32:32:32\
-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64\
|
},
target_triple: target_triple,
cc_args: Vec::new(),
};
}
|
-f32:32:32-f64:64:64\
-v64:64:64-v128:64:128\
-a:0:64-n32".to_string()
}
|
random_line_split
|
mips.rs
|
// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use target_strs;
use syntax::abi;
pub fn
|
(target_triple: String, target_os: abi::Os) -> target_strs::t {
return target_strs::t {
module_asm: "".to_string(),
data_layout: match target_os {
abi::OsMacos => {
"E-p:32:32:32\
-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64\
-f32:32:32-f64:64:64\
-v64:64:64-v128:64:128\
-a:0:64-n32".to_string()
}
abi::OsiOS => {
"E-p:32:32:32\
-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64\
-f32:32:32-f64:64:64\
-v64:64:64-v128:64:128\
-a:0:64-n32".to_string()
}
abi::OsWindows => {
"E-p:32:32:32\
-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64\
-f32:32:32-f64:64:64\
-v64:64:64-v128:64:128\
-a:0:64-n32".to_string()
}
abi::OsLinux => {
"E-p:32:32:32\
-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64\
-f32:32:32-f64:64:64\
-v64:64:64-v128:64:128\
-a:0:64-n32".to_string()
}
abi::OsAndroid => {
"E-p:32:32:32\
-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64\
-f32:32:32-f64:64:64\
-v64:64:64-v128:64:128\
-a:0:64-n32".to_string()
}
abi::OsFreebsd | abi::OsDragonfly | abi::OsBitrig | abi::OsOpenbsd => {
"E-p:32:32:32\
-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64\
-f32:32:32-f64:64:64\
-v64:64:64-v128:64:128\
-a:0:64-n32".to_string()
}
},
target_triple: target_triple,
cc_args: Vec::new(),
};
}
|
get_target_strs
|
identifier_name
|
app.module.ts
|
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { RouterModule } from '@angular/router';
import { HttpModule } from '@angular/http';
import { StoreModule } from '@ngrx/store';
import { EffectsModule } from '@ngrx/effects';
import { DBModule } from '@ngrx/db';
import {
StoreRouterConnectingModule,
RouterStateSerializer,
} from '@ngrx/router-store';
import { StoreDevtoolsModule } from '@ngrx/store-devtools';
import { CoreModule } from './core/core.module';
import { AuthModule } from './auth/auth.module';
import { routes } from './routes';
import { reducers, metaReducers } from './reducers';
import { schema } from './db';
import { CustomRouterStateSerializer } from './shared/utils';
import { AppComponent } from './core/containers/app';
import { environment } from '../environments/environment';
@NgModule({
imports: [
CommonModule,
BrowserModule,
BrowserAnimationsModule,
HttpModule,
RouterModule.forRoot(routes, { useHash: true }),
/**
* StoreModule.forRoot is imported once in the root module, accepting a reducer
* function or object map of reducer functions. If passed an object of
* reducers, combineReducers will be run creating your application
* meta-reducer. This returns all providers for an @ngrx/store
* based application.
*/
StoreModule.forRoot(reducers, { metaReducers }),
/**
* @ngrx/router-store keeps router state up-to-date in the store.
*/
StoreRouterConnectingModule,
/**
* Store devtools instrument the store retaining past versions of state
* and recalculating new states. This enables powerful time-travel
* debugging.
*
* To use the debugger, install the Redux Devtools extension for either
* Chrome or Firefox
*
* See: https://github.com/zalmoxisus/redux-devtools-extension
*/
!environment.production ? StoreDevtoolsModule.instrument() : [],
/**
* EffectsModule.forRoot() is imported once in the root module and
* sets up the effects class to be initialized immediately when the
* application starts.
*
* See: https://github.com/ngrx/platform/blob/master/docs/effects/api.md#forroot
*/
EffectsModule.forRoot([]),
/**
* `provideDB` sets up @ngrx/db with the provided schema and makes the Database
* service available.
*/
DBModule.provideDB(schema),
CoreModule.forRoot(),
AuthModule.forRoot(),
|
],
providers: [
/**
* The `RouterStateSnapshot` provided by the `Router` is a large complex structure.
* A custom RouterStateSerializer is used to parse the `RouterStateSnapshot` provided
* by `@ngrx/router-store` to include only the desired pieces of the snapshot.
*/
{ provide: RouterStateSerializer, useClass: CustomRouterStateSerializer },
],
bootstrap: [AppComponent],
})
export class AppModule {}
|
random_line_split
|
|
app.module.ts
|
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { RouterModule } from '@angular/router';
import { HttpModule } from '@angular/http';
import { StoreModule } from '@ngrx/store';
import { EffectsModule } from '@ngrx/effects';
import { DBModule } from '@ngrx/db';
import {
StoreRouterConnectingModule,
RouterStateSerializer,
} from '@ngrx/router-store';
import { StoreDevtoolsModule } from '@ngrx/store-devtools';
import { CoreModule } from './core/core.module';
import { AuthModule } from './auth/auth.module';
import { routes } from './routes';
import { reducers, metaReducers } from './reducers';
import { schema } from './db';
import { CustomRouterStateSerializer } from './shared/utils';
import { AppComponent } from './core/containers/app';
import { environment } from '../environments/environment';
@NgModule({
imports: [
CommonModule,
BrowserModule,
BrowserAnimationsModule,
HttpModule,
RouterModule.forRoot(routes, { useHash: true }),
/**
* StoreModule.forRoot is imported once in the root module, accepting a reducer
* function or object map of reducer functions. If passed an object of
* reducers, combineReducers will be run creating your application
* meta-reducer. This returns all providers for an @ngrx/store
* based application.
*/
StoreModule.forRoot(reducers, { metaReducers }),
/**
* @ngrx/router-store keeps router state up-to-date in the store.
*/
StoreRouterConnectingModule,
/**
* Store devtools instrument the store retaining past versions of state
* and recalculating new states. This enables powerful time-travel
* debugging.
*
* To use the debugger, install the Redux Devtools extension for either
* Chrome or Firefox
*
* See: https://github.com/zalmoxisus/redux-devtools-extension
*/
!environment.production ? StoreDevtoolsModule.instrument() : [],
/**
* EffectsModule.forRoot() is imported once in the root module and
* sets up the effects class to be initialized immediately when the
* application starts.
*
* See: https://github.com/ngrx/platform/blob/master/docs/effects/api.md#forroot
*/
EffectsModule.forRoot([]),
/**
* `provideDB` sets up @ngrx/db with the provided schema and makes the Database
* service available.
*/
DBModule.provideDB(schema),
CoreModule.forRoot(),
AuthModule.forRoot(),
],
providers: [
/**
* The `RouterStateSnapshot` provided by the `Router` is a large complex structure.
* A custom RouterStateSerializer is used to parse the `RouterStateSnapshot` provided
* by `@ngrx/router-store` to include only the desired pieces of the snapshot.
*/
{ provide: RouterStateSerializer, useClass: CustomRouterStateSerializer },
],
bootstrap: [AppComponent],
})
export class
|
{}
|
AppModule
|
identifier_name
|
inferno-server.js
|
/*!
* inferno-server vundefined
* (c) 2016 Dominic Gannaway
* Released under the MPL-2.0 License.
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.InfernoServer = factory());
}(this, function () { 'use strict';
var babelHelpers_typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
return typeof obj;
} : function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj;
};
function createStaticNode(html) {
return {
create: function create() {
return html;
}
};
}
var isArray = (function (x) {
return x.constructor === Array;
})
var isStringOrNumber = (function (x) {
return typeof x === 'string' || typeof x === 'number';
})
var noop = (function () {})
var canUseDOM = !!(typeof window !== 'undefined' &&
// Nwjs doesn't add document as a global in their node context, but does have it on window.document,
// As a workaround, check if document is undefined
typeof document !== 'undefined' && window.document.createElement);
var ExecutionEnvironment = {
canUseDOM: canUseDOM,
canUseWorkers: typeof Worker !== 'undefined',
canUseEventListeners: canUseDOM && !!window.addEventListener,
canUseViewport: canUseDOM && !!window.screen,
canUseSymbol: typeof Symbol === 'function' && typeof Symbol['for'] === 'function'
};
var HOOK = {};
var reDash = /\-./g;
/* eslint-disable quote-props */
var unitlessProperties = {
'animation-iteration-count': true,
'box-flex': true,
'box-flex-group': true,
'column-count': true,
'counter-increment': true,
'fill-opacity': true,
'flex': true,
'flex-grow': true,
'flex-order': true,
'flex-positive': true,
'flex-shrink': true,
'float': true,
'font-weight': true,
'grid-column': true,
'line-height': true,
'line-clamp': true,
'opacity': true,
'order': true,
'orphans': true,
'stop-opacity': true,
'stroke-dashoffset': true,
'stroke-opacity': true,
'stroke-width': true,
'tab-size': true,
'transform': true,
'transform-origin': true,
'widows': true,
'z-index': true,
'zoom': true
};
/* eslint-enable quote-props */
var directions = ['Top', 'Right', 'Bottom', 'Left'];
var dirMap = function dirMap(prefix, postfix) {
return directions.map(function (dir) {
return (prefix || '') + dir + (postfix || '');
});
};
var shortCuts = {
// rely on cssText
font: [/*
font-style
font-variant
font-weight
font-size/line-height
font-family|caption|icon|menu|message-box|small-caption|status-bar|initial|inherit;
*/],
padding: dirMap('padding'),
margin: dirMap('margin'),
'border-width': dirMap('border', 'Width'),
'border-style': dirMap('border', 'Style')
};
var cssToJSName = function cssToJSName(cssName) {
return cssName.replace(reDash, function (str) {
return str[1].toUpperCase();
});
};
// Don't execute this in nodejS
if (ExecutionEnvironment.canUseDOM) {
(function () {
// get browser supported CSS properties
var documentElement = document.documentElement;
var computed = window.getComputedStyle(documentElement);
var props = Array.prototype.slice.call(computed, 0);
for (var key in documentElement.style) {
if (!computed[key]) {
props.push(key);
}
}
props.forEach(function (propName) {
var prefix = propName[0] === '-' ? propName.substr(1, propName.indexOf('-', 1) - 1) : null;
var stylePropName = cssToJSName(propName);
HOOK[stylePropName] = {
unPrefixed: prefix ? propName.substr(prefix.length + 2) : propName,
unitless: unitlessProperties[propName] ? true : false,
shorthand: null
};
});
var lenMap = {
1: function _(values, props, style) {
return props.forEach(function (prop) {
return style[prop] = values[0];
});
},
2: function _(values, props, style) {
return values.forEach(function (value, index) {
style[props[index]] = style[props[index + 2]] = value;
});
},
4: function _(values, props, style) {
return props.forEach(function (prop, index) {
style[prop] = values[index];
});
}
};
// normalize property shortcuts
Object.keys(shortCuts).forEach(function (propName) {
var stylePropName = cssToJSName(propName);
HOOK[stylePropName] = {
unPrefixed: propName,
unitless: false,
shorthand: function shorthand(value, style) {
var type = typeof value === 'undefined' ? 'undefined' : babelHelpers_typeof(value);
if (type === 'number') {
value += 'px';
}
if (!value) {
return;
}
if ('cssText' in style) {
// normalize setting complex property across browsers
style.cssText += ';' + propName + ':' + value;
} else {
var values = value.split(' ');
(lenMap[values.length] || noop)(values, shortCuts[propName], style);
}
}
};
});
})();
}
/**
* DOM registry
* */
var PROPERTY = 0x1;
var BOOLEAN = 0x2;
var NUMERIC_VALUE = 0x4;
var POSITIVE_NUMERIC_VALUE = 0x6 | 0x4;
var xlink = 'http://www.w3.org/1999/xlink';
var xml = 'http://www.w3.org/XML/1998/namespace';
var DOMAttributeNamespaces = {
// None-JSX compat
'xlink:actuate': xlink,
'xlink:arcrole': xlink,
'xlink:href': xlink,
'xlink:role': xlink,
'xlink:show': xlink,
'xlink:title': xlink,
'xlink:type': xlink,
'xml:base': xml,
'xml:lang': xml,
'xml:space': xml,
// JSX compat
xlinkActuate: xlink,
xlinkArcrole: xlink,
xlinkHref: xlink,
xlinkRole: xlink,
xlinkShow: xlink,
xlinkTitle: xlink,
xlinkType: xlink
};
var DOMAttributeNames = {
acceptCharset: 'accept-charset',
className: 'class',
htmlFor: 'for',
httpEquiv: 'http-equiv',
// SVG
clipPath: 'clip-path',
fillOpacity: 'fill-opacity',
fontFamily: 'font-family',
fontSize: 'font-size',
markerEnd: 'marker-end',
markerMid: 'marker-mid',
markerStart: 'marker-start',
stopColor: 'stop-color',
stopOpacity: 'stop-opacity',
strokeDasharray: 'stroke-dasharray',
strokeLinecap: 'stroke-linecap',
strokeOpacity: 'stroke-opacity',
strokeWidth: 'stroke-width',
textAnchor: 'text-anchor',
viewBox: 'viewBox', // Edge case. The letter 'b' need to be uppercase
// JSX compat
xlinkActuate: 'xlink:actuate',
xlinkArcrole: 'xlink:arcrole',
xlinkHref: 'xlink:href',
xlinkRole: 'xlink:role',
xlinkShow: 'xlink:show',
xlinkTitle: 'xlink:title',
xlinkType: 'xlink:type',
xmlBase: 'xml:base',
xmlLang: 'xml:lang',
xmlSpace: 'xml:space'
};
var DOMPropertyNames = {
autoComplete: 'autocomplete',
autoFocus: 'autofocus',
autoSave: 'autosave'
};
// This 'whitelist' contains edge cases such as attributes
// that should be seen as a property or boolean property.
// ONLY EDIT THIS IF YOU KNOW WHAT YOU ARE DOING!!
var Whitelist = {
allowFullScreen: BOOLEAN,
async: BOOLEAN,
autoFocus: BOOLEAN,
autoPlay: BOOLEAN,
capture: BOOLEAN,
checked: PROPERTY | BOOLEAN,
controls: BOOLEAN,
currentTime: PROPERTY | POSITIVE_NUMERIC_VALUE,
default: BOOLEAN,
defaultChecked: BOOLEAN,
defaultMuted: BOOLEAN,
defaultSelected: BOOLEAN,
defer: BOOLEAN,
disabled: PROPERTY | BOOLEAN,
download: BOOLEAN,
enabled: BOOLEAN,
formNoValidate: BOOLEAN,
hidden: PROPERTY | BOOLEAN, // 3.2.5 - Global attributes
loop: BOOLEAN,
// Caution; `option.selected` is not updated if `select.multiple` is
// disabled with `removeAttribute`.
multiple: PROPERTY | BOOLEAN,
muted: PROPERTY | BOOLEAN,
mediaGroup: PROPERTY,
noValidate: BOOLEAN,
noShade: PROPERTY | BOOLEAN,
noResize: BOOLEAN,
noWrap: BOOLEAN,
typeMustMatch: BOOLEAN,
open: BOOLEAN,
paused: PROPERTY,
playbackRate: PROPERTY | NUMERIC_VALUE,
readOnly: BOOLEAN,
required: PROPERTY | BOOLEAN,
reversed: BOOLEAN,
radioGroup: PROPERTY,
icon: PROPERTY,
draggable: BOOLEAN, // 3.2.5 - Global attributes
dropzone: null, // 3.2.5 - Global attributes
scoped: PROPERTY | BOOLEAN,
visible: BOOLEAN,
trueSpeed: BOOLEAN,
sandbox: null,
sortable: BOOLEAN,
inert: BOOLEAN,
indeterminate: BOOLEAN,
nohref: BOOLEAN,
compact: BOOLEAN,
declare: BOOLEAN,
ismap: PROPERTY | BOOLEAN,
pauseOnExit: PROPERTY | BOOLEAN,
seamless: BOOLEAN,
translate: BOOLEAN, // 3.2.5 - Global attributes
selected: PROPERTY | BOOLEAN,
srcLang: PROPERTY,
srcObject: PROPERTY,
value: PROPERTY,
volume: PROPERTY | POSITIVE_NUMERIC_VALUE,
itemScope: BOOLEAN, // 3.2.5 - Global attributes
className: null,
tabindex: PROPERTY | NUMERIC_VALUE,
/**
* React compat for non-working JSX namespace support
*/
xlinkActuate: null,
xlinkArcrole: null,
xlinkHref: null,
xlinkRole: null,
xlinkShow: null,
xlinkTitle: null,
xlinkType: null,
xmlBase: null,
xmlLang: null,
xmlSpace: null,
/**
* SVG
*/
clipPath: null,
fillOpacity: null,
fontFamily: null,
fontSize: null,
markerEnd: null,
markerMid: null,
markerStart: null,
stopColor: null,
stopOpacity: null,
strokeDasharray: null,
strokeLinecap: null,
strokeOpacity: null,
strokeWidth: null,
textAnchor: null,
/**
* Numeric attributes
*/
cols: POSITIVE_NUMERIC_VALUE,
rows: NUMERIC_VALUE,
rowspan: NUMERIC_VALUE,
size: POSITIVE_NUMERIC_VALUE,
sizes: NUMERIC_VALUE,
start: NUMERIC_VALUE,
/**
* Namespace attributes
*/
'xlink:actuate': null,
'xlink:arcrole': null,
'xlink:href': null,
'xlink:role': null,
'xlink:show': null,
'xlink:title': null,
'xlink:type': null,
'xml:base': null,
'xml:lang': null,
'xml:space': null,
/**
* 3.2.5 - Global attributes
*/
id: null,
dir: null,
title: null,
/**
* Properties that MUST be set as attributes, due to:
*
* - browser bug
* - strange spec outlier
*
* Nothing bad with this. This properties get a performance boost
* compared to custom attributes because they are skipping the
* validation check.
*/
// Force 'autocorrect' and 'autoCapitalize' to be set as an attribute
// to fix issues with Mobile Safari on iOS devices
autocorrect: null,
// autoCapitalize and autoCorrect are supported in Mobile Safari for
// keyboard hints.
autoCapitalize: null,
// Some version of IE ( like IE9 ) actually throw an exception
// if you set input.type = 'something-unknown'
type: null,
/**
* Form
*/
form: null,
formAction: null,
formEncType: null,
formMethod: null,
formTarget: null,
frameBorder: null,
/**
* Internet Explorer / Edge
*/
// IE-only attribute that controls focus behavior
unselectable: null,
/**
* Firefox
*/
continuous: BOOLEAN,
/**
* Others
*/
srcSet: null,
inlist: null,
minLength: null,
marginWidth: null,
marginHeight: null,
list: null,
keyType: null,
is: null,
inputMode: null,
height: null,
width: null,
dateTime: null,
contenteditable: null, // 3.2.5 - Global attributes
contextMenu: null,
classID: null,
cellPadding: null,
cellSpacing: null,
charSet: null,
allowTransparency: null,
spellcheck: null, // 3.2.5 - Global attributes
srcDoc: PROPERTY
};
var HTMLPropsContainer = {};
function checkBitmask(value, bitmask) {
return bitmask !== null && (value & bitmask) === bitmask;
}
for (var propName in Whitelist) {
var propConfig = Whitelist[propName];
HTMLPropsContainer[propName] = {
attributeName: DOMAttributeNames[propName] || propName.toLowerCase(),
attributeNamespace: DOMAttributeNamespaces[propName] ? DOMAttributeNamespaces[propName] : null,
propertyName: DOMPropertyNames[propName] || propName,
mustUseProperty: checkBitmask(propConfig, PROPERTY),
hasBooleanValue: checkBitmask(propConfig, BOOLEAN),
hasNumericValue: checkBitmask(propConfig, NUMERIC_VALUE),
hasPositiveNumericValue: checkBitmask(propConfig, POSITIVE_NUMERIC_VALUE)
};
}
var isVoid = (function (x) {
return x === null || x === undefined;
})
/* eslint eqeqeq:0 */
function isValidAttribute(strings) {
var i = 0;
var character = undefined;
while (i <= strings.length) {
character = strings[i];
if (!isNaN(character * 1)) {
return false;
} else {
if (character == character.toUpperCase()) {
return false;
}
if (character === character.toLowerCase()) {
return true;
}
}
i++;
}
return false;
}
var ESCAPE_LOOKUP = {
'&': '&',
'>': '>',
'<': '<',
'"': '"',
'`': '`',
"'": '''
};
var ESCAPE_REGEX = /[&><"'`]/g;
/**
* Escapes attribute value to prevent scripting attacks.
*
* @param {*} value Attribute value to escape.
* @return {string} An escaped string.
*/
var quoteAttributeValueForBrowser = (function (value) {
return '"' + ('' + value).replace(ESCAPE_REGEX, function (match) {
return ESCAPE_LOOKUP[match];
}) + '"';
})
var selfClosingTags = {
area: true,
base: true,
basefont: true,
br: true,
col: true,
command: true,
embed: true,
frame: true,
hr: true,
img: true,
input: true,
isindex: true,
keygen: true,
link: true,
meta: true,
param: true,
source: true,
track: true,
wbr: true,
//common self closing svg elements
path: true,
circle: true,
ellipse: true,
line: true,
rect: true,
use: true,
stop: true,
polyline: true,
polygon: true
};
function renderMarkupForSelect(node) {
var value = node.attrs && node.attrs.value;
if (!isVoid(value)) {
var values = {};
if (isArray(value)) {
for (var i = 0, len = value.length; i < len; i++) {
values[value[i]] = value[i];
}
} else {
values[value] = value;
}
populateOptions(node, values);
if (node.attrs && node.attrs.value) {
delete node.attrs.value;
}
}
}
/**
* Populates values to options node.
*
* @param Object node A starting node (generaly a select node).
* @param Object values The selected values to populate.
*/
function populateOptions(node, values) {
if (node.tag !== 'option') {
for (var i = 0, len = node.children.length; i < len; i++)
|
return;
}
var value = node.attrs && node.attrs.value;
if (!values[value]) {
return;
}
node.attrs = node.attrs || {};
node.attrs.selected = "selected";
}
/**
* WORK IN PROGRESS
*
* Need to run tests for this one!!
*
* */
function renderMarkupForStyles(styles, component) {
var serialized = '';
for (var styleName in styles) {
if (isValidAttribute(styleName)) {
var styleValue = styles[styleName];
if (!isVoid(styleValue)) {
if (!unitlessProperties[styleName]) {
if (typeof styleValue !== 'string') {
styleValue = styleValue + 'px';
}
}
serialized += styleName + ':';
serialized += styleValue + ';';
}
}
}
return serialized || null;
}
function renderMarkupForAttributes(name, value) {
if (name === 'data-inferno') {
return '' + name;
}
var propertyInfo = HTMLPropsContainer[name] || null;
if (propertyInfo) {
if (isVoid(value) || propertyInfo.hasBooleanValue && !value || propertyInfo.hasNumericValue && value !== value || propertyInfo.hasPositiveNumericValue && value < 1 || value === 'false' || value.length === 0) {
return '';
}
var attributeName = propertyInfo.attributeName;
return attributeName + '=' + quoteAttributeValueForBrowser(value);
} else {
if (isVoid(value) || !isValidAttribute(name)) {
return '';
}
// custom attributes
return (DOMAttributeNames[name] || name.toLowerCase()) + '=' + quoteAttributeValueForBrowser(value);
}
}
function createStaticAttributes(props, excludeAttrs) {
var HTML = '';
for (var propKey in props) {
var propValue = props[propKey];
if (!isVoid(propValue)) {
if (propKey === 'style') {
propValue = renderMarkupForStyles(propValue);
}
var markup = null;
markup = renderMarkupForAttributes(propKey, propValue);
if (markup) {
HTML += ' ' + markup;
}
}
}
return HTML;
}
function createStaticTreeChildren(children) {
var isLastChildNode = false;
if (isArray(children)) {
return children.map(function (child, i) {
if (isStringOrNumber(child)) {
if (isLastChildNode) {
isLastChildNode = true;
return '<!---->' + child;
} else {
isLastChildNode = true;
return child;
}
}
isLastChildNode = false;
return createStaticTreeNode(false, child);
}).join('');
} else {
if (isStringOrNumber(children)) {
return children;
} else {
return createStaticTreeNode(false, children);
}
}
}
function createStaticTreeNode(isRoot, node) {
var staticNode = undefined;
if (isVoid(node)) {
return '';
}
if (node.tag) {
var tag = node.tag.toLowerCase();
var attrs = node.attrs;
var attributes = {};
for (var key in node.attrs) {
if (key === 'value') {
if (tag === 'select') {
renderMarkupForSelect(node);
continue;
} else if (tag === 'textarea' || attrs.contenteditable) {
node.text = attrs[key];
continue;
}
}
attributes[key] = attrs[key];
}
if (isRoot) {
attributes['data-inferno'] = true;
}
staticNode = '<' + tag;
// In React they can add innerHTML like this, just workaround it
if (attributes.innerHTML) {
node.text = attributes.innerHTML;
} else {
staticNode += createStaticAttributes(attributes, null);
}
if (selfClosingTags[tag]) {
staticNode += ' />';
} else {
staticNode += '>';
if (!isVoid(node.children)) {
staticNode += createStaticTreeChildren(node.children);
} else if (!isVoid(node.text)) {
staticNode += node.text;
}
staticNode += '</' + tag + '>';
}
}
return staticNode;
}
function createHTMLTree(schema, isRoot, dynamicNodeMap) {
var dynamicFlags = dynamicNodeMap.get(schema);
var node = undefined;
// static html
if (!dynamicFlags) {
return createStaticNode(createStaticTreeNode(isRoot, schema));
}
return node;
}
function renderToString(item) {
return item.tree.html.create(item);
}
var global = global || (typeof window !== 'undefined' ? window : null);
// browser
if (global && global.Inferno) {
global.Inferno.addTreeConstructor('html', createHTMLTree);
// nodeJS
// TODO! Find a better way to detect if we are running in Node, and test if this actually works!!!
} else if (global && !global.Inferno) {
var Inferno = undefined;
// TODO! Avoid try / catch
try {
Inferno = require('inferno');
} catch (e) {
Inferno = null;
// TODO Should we throw a warning and inform that the Inferno package is not installed?
}
if (Inferno != null) {
if (typeof Inferno.addTreeConstructor !== 'function') {
throw 'Your package is out-of-date! Upgrade to latest Inferno in order to use the InfernoServer package.';
} else {
Inferno.addTreeConstructor('html', createHTMLTree);
}
}
}
var index = {
renderToString: renderToString
};
return index;
}));
//# sourceMappingURL=inferno-server.js.map
|
{
populateOptions(node.children[i], values);
}
|
conditional_block
|
inferno-server.js
|
/*!
* inferno-server vundefined
* (c) 2016 Dominic Gannaway
* Released under the MPL-2.0 License.
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.InfernoServer = factory());
}(this, function () { 'use strict';
var babelHelpers_typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
return typeof obj;
} : function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj;
};
function createStaticNode(html)
|
var isArray = (function (x) {
return x.constructor === Array;
})
var isStringOrNumber = (function (x) {
return typeof x === 'string' || typeof x === 'number';
})
var noop = (function () {})
var canUseDOM = !!(typeof window !== 'undefined' &&
// Nwjs doesn't add document as a global in their node context, but does have it on window.document,
// As a workaround, check if document is undefined
typeof document !== 'undefined' && window.document.createElement);
var ExecutionEnvironment = {
canUseDOM: canUseDOM,
canUseWorkers: typeof Worker !== 'undefined',
canUseEventListeners: canUseDOM && !!window.addEventListener,
canUseViewport: canUseDOM && !!window.screen,
canUseSymbol: typeof Symbol === 'function' && typeof Symbol['for'] === 'function'
};
var HOOK = {};
var reDash = /\-./g;
/* eslint-disable quote-props */
var unitlessProperties = {
'animation-iteration-count': true,
'box-flex': true,
'box-flex-group': true,
'column-count': true,
'counter-increment': true,
'fill-opacity': true,
'flex': true,
'flex-grow': true,
'flex-order': true,
'flex-positive': true,
'flex-shrink': true,
'float': true,
'font-weight': true,
'grid-column': true,
'line-height': true,
'line-clamp': true,
'opacity': true,
'order': true,
'orphans': true,
'stop-opacity': true,
'stroke-dashoffset': true,
'stroke-opacity': true,
'stroke-width': true,
'tab-size': true,
'transform': true,
'transform-origin': true,
'widows': true,
'z-index': true,
'zoom': true
};
/* eslint-enable quote-props */
var directions = ['Top', 'Right', 'Bottom', 'Left'];
var dirMap = function dirMap(prefix, postfix) {
return directions.map(function (dir) {
return (prefix || '') + dir + (postfix || '');
});
};
var shortCuts = {
// rely on cssText
font: [/*
font-style
font-variant
font-weight
font-size/line-height
font-family|caption|icon|menu|message-box|small-caption|status-bar|initial|inherit;
*/],
padding: dirMap('padding'),
margin: dirMap('margin'),
'border-width': dirMap('border', 'Width'),
'border-style': dirMap('border', 'Style')
};
var cssToJSName = function cssToJSName(cssName) {
return cssName.replace(reDash, function (str) {
return str[1].toUpperCase();
});
};
// Don't execute this in nodejS
if (ExecutionEnvironment.canUseDOM) {
(function () {
// get browser supported CSS properties
var documentElement = document.documentElement;
var computed = window.getComputedStyle(documentElement);
var props = Array.prototype.slice.call(computed, 0);
for (var key in documentElement.style) {
if (!computed[key]) {
props.push(key);
}
}
props.forEach(function (propName) {
var prefix = propName[0] === '-' ? propName.substr(1, propName.indexOf('-', 1) - 1) : null;
var stylePropName = cssToJSName(propName);
HOOK[stylePropName] = {
unPrefixed: prefix ? propName.substr(prefix.length + 2) : propName,
unitless: unitlessProperties[propName] ? true : false,
shorthand: null
};
});
var lenMap = {
1: function _(values, props, style) {
return props.forEach(function (prop) {
return style[prop] = values[0];
});
},
2: function _(values, props, style) {
return values.forEach(function (value, index) {
style[props[index]] = style[props[index + 2]] = value;
});
},
4: function _(values, props, style) {
return props.forEach(function (prop, index) {
style[prop] = values[index];
});
}
};
// normalize property shortcuts
Object.keys(shortCuts).forEach(function (propName) {
var stylePropName = cssToJSName(propName);
HOOK[stylePropName] = {
unPrefixed: propName,
unitless: false,
shorthand: function shorthand(value, style) {
var type = typeof value === 'undefined' ? 'undefined' : babelHelpers_typeof(value);
if (type === 'number') {
value += 'px';
}
if (!value) {
return;
}
if ('cssText' in style) {
// normalize setting complex property across browsers
style.cssText += ';' + propName + ':' + value;
} else {
var values = value.split(' ');
(lenMap[values.length] || noop)(values, shortCuts[propName], style);
}
}
};
});
})();
}
/**
* DOM registry
* */
var PROPERTY = 0x1;
var BOOLEAN = 0x2;
var NUMERIC_VALUE = 0x4;
var POSITIVE_NUMERIC_VALUE = 0x6 | 0x4;
var xlink = 'http://www.w3.org/1999/xlink';
var xml = 'http://www.w3.org/XML/1998/namespace';
var DOMAttributeNamespaces = {
// None-JSX compat
'xlink:actuate': xlink,
'xlink:arcrole': xlink,
'xlink:href': xlink,
'xlink:role': xlink,
'xlink:show': xlink,
'xlink:title': xlink,
'xlink:type': xlink,
'xml:base': xml,
'xml:lang': xml,
'xml:space': xml,
// JSX compat
xlinkActuate: xlink,
xlinkArcrole: xlink,
xlinkHref: xlink,
xlinkRole: xlink,
xlinkShow: xlink,
xlinkTitle: xlink,
xlinkType: xlink
};
var DOMAttributeNames = {
acceptCharset: 'accept-charset',
className: 'class',
htmlFor: 'for',
httpEquiv: 'http-equiv',
// SVG
clipPath: 'clip-path',
fillOpacity: 'fill-opacity',
fontFamily: 'font-family',
fontSize: 'font-size',
markerEnd: 'marker-end',
markerMid: 'marker-mid',
markerStart: 'marker-start',
stopColor: 'stop-color',
stopOpacity: 'stop-opacity',
strokeDasharray: 'stroke-dasharray',
strokeLinecap: 'stroke-linecap',
strokeOpacity: 'stroke-opacity',
strokeWidth: 'stroke-width',
textAnchor: 'text-anchor',
viewBox: 'viewBox', // Edge case. The letter 'b' need to be uppercase
// JSX compat
xlinkActuate: 'xlink:actuate',
xlinkArcrole: 'xlink:arcrole',
xlinkHref: 'xlink:href',
xlinkRole: 'xlink:role',
xlinkShow: 'xlink:show',
xlinkTitle: 'xlink:title',
xlinkType: 'xlink:type',
xmlBase: 'xml:base',
xmlLang: 'xml:lang',
xmlSpace: 'xml:space'
};
var DOMPropertyNames = {
autoComplete: 'autocomplete',
autoFocus: 'autofocus',
autoSave: 'autosave'
};
// This 'whitelist' contains edge cases such as attributes
// that should be seen as a property or boolean property.
// ONLY EDIT THIS IF YOU KNOW WHAT YOU ARE DOING!!
var Whitelist = {
allowFullScreen: BOOLEAN,
async: BOOLEAN,
autoFocus: BOOLEAN,
autoPlay: BOOLEAN,
capture: BOOLEAN,
checked: PROPERTY | BOOLEAN,
controls: BOOLEAN,
currentTime: PROPERTY | POSITIVE_NUMERIC_VALUE,
default: BOOLEAN,
defaultChecked: BOOLEAN,
defaultMuted: BOOLEAN,
defaultSelected: BOOLEAN,
defer: BOOLEAN,
disabled: PROPERTY | BOOLEAN,
download: BOOLEAN,
enabled: BOOLEAN,
formNoValidate: BOOLEAN,
hidden: PROPERTY | BOOLEAN, // 3.2.5 - Global attributes
loop: BOOLEAN,
// Caution; `option.selected` is not updated if `select.multiple` is
// disabled with `removeAttribute`.
multiple: PROPERTY | BOOLEAN,
muted: PROPERTY | BOOLEAN,
mediaGroup: PROPERTY,
noValidate: BOOLEAN,
noShade: PROPERTY | BOOLEAN,
noResize: BOOLEAN,
noWrap: BOOLEAN,
typeMustMatch: BOOLEAN,
open: BOOLEAN,
paused: PROPERTY,
playbackRate: PROPERTY | NUMERIC_VALUE,
readOnly: BOOLEAN,
required: PROPERTY | BOOLEAN,
reversed: BOOLEAN,
radioGroup: PROPERTY,
icon: PROPERTY,
draggable: BOOLEAN, // 3.2.5 - Global attributes
dropzone: null, // 3.2.5 - Global attributes
scoped: PROPERTY | BOOLEAN,
visible: BOOLEAN,
trueSpeed: BOOLEAN,
sandbox: null,
sortable: BOOLEAN,
inert: BOOLEAN,
indeterminate: BOOLEAN,
nohref: BOOLEAN,
compact: BOOLEAN,
declare: BOOLEAN,
ismap: PROPERTY | BOOLEAN,
pauseOnExit: PROPERTY | BOOLEAN,
seamless: BOOLEAN,
translate: BOOLEAN, // 3.2.5 - Global attributes
selected: PROPERTY | BOOLEAN,
srcLang: PROPERTY,
srcObject: PROPERTY,
value: PROPERTY,
volume: PROPERTY | POSITIVE_NUMERIC_VALUE,
itemScope: BOOLEAN, // 3.2.5 - Global attributes
className: null,
tabindex: PROPERTY | NUMERIC_VALUE,
/**
* React compat for non-working JSX namespace support
*/
xlinkActuate: null,
xlinkArcrole: null,
xlinkHref: null,
xlinkRole: null,
xlinkShow: null,
xlinkTitle: null,
xlinkType: null,
xmlBase: null,
xmlLang: null,
xmlSpace: null,
/**
* SVG
*/
clipPath: null,
fillOpacity: null,
fontFamily: null,
fontSize: null,
markerEnd: null,
markerMid: null,
markerStart: null,
stopColor: null,
stopOpacity: null,
strokeDasharray: null,
strokeLinecap: null,
strokeOpacity: null,
strokeWidth: null,
textAnchor: null,
/**
* Numeric attributes
*/
cols: POSITIVE_NUMERIC_VALUE,
rows: NUMERIC_VALUE,
rowspan: NUMERIC_VALUE,
size: POSITIVE_NUMERIC_VALUE,
sizes: NUMERIC_VALUE,
start: NUMERIC_VALUE,
/**
* Namespace attributes
*/
'xlink:actuate': null,
'xlink:arcrole': null,
'xlink:href': null,
'xlink:role': null,
'xlink:show': null,
'xlink:title': null,
'xlink:type': null,
'xml:base': null,
'xml:lang': null,
'xml:space': null,
/**
* 3.2.5 - Global attributes
*/
id: null,
dir: null,
title: null,
/**
* Properties that MUST be set as attributes, due to:
*
* - browser bug
* - strange spec outlier
*
* Nothing bad with this. This properties get a performance boost
* compared to custom attributes because they are skipping the
* validation check.
*/
// Force 'autocorrect' and 'autoCapitalize' to be set as an attribute
// to fix issues with Mobile Safari on iOS devices
autocorrect: null,
// autoCapitalize and autoCorrect are supported in Mobile Safari for
// keyboard hints.
autoCapitalize: null,
// Some version of IE ( like IE9 ) actually throw an exception
// if you set input.type = 'something-unknown'
type: null,
/**
* Form
*/
form: null,
formAction: null,
formEncType: null,
formMethod: null,
formTarget: null,
frameBorder: null,
/**
* Internet Explorer / Edge
*/
// IE-only attribute that controls focus behavior
unselectable: null,
/**
* Firefox
*/
continuous: BOOLEAN,
/**
* Others
*/
srcSet: null,
inlist: null,
minLength: null,
marginWidth: null,
marginHeight: null,
list: null,
keyType: null,
is: null,
inputMode: null,
height: null,
width: null,
dateTime: null,
contenteditable: null, // 3.2.5 - Global attributes
contextMenu: null,
classID: null,
cellPadding: null,
cellSpacing: null,
charSet: null,
allowTransparency: null,
spellcheck: null, // 3.2.5 - Global attributes
srcDoc: PROPERTY
};
var HTMLPropsContainer = {};
function checkBitmask(value, bitmask) {
return bitmask !== null && (value & bitmask) === bitmask;
}
for (var propName in Whitelist) {
var propConfig = Whitelist[propName];
HTMLPropsContainer[propName] = {
attributeName: DOMAttributeNames[propName] || propName.toLowerCase(),
attributeNamespace: DOMAttributeNamespaces[propName] ? DOMAttributeNamespaces[propName] : null,
propertyName: DOMPropertyNames[propName] || propName,
mustUseProperty: checkBitmask(propConfig, PROPERTY),
hasBooleanValue: checkBitmask(propConfig, BOOLEAN),
hasNumericValue: checkBitmask(propConfig, NUMERIC_VALUE),
hasPositiveNumericValue: checkBitmask(propConfig, POSITIVE_NUMERIC_VALUE)
};
}
var isVoid = (function (x) {
return x === null || x === undefined;
})
/* eslint eqeqeq:0 */
function isValidAttribute(strings) {
var i = 0;
var character = undefined;
while (i <= strings.length) {
character = strings[i];
if (!isNaN(character * 1)) {
return false;
} else {
if (character == character.toUpperCase()) {
return false;
}
if (character === character.toLowerCase()) {
return true;
}
}
i++;
}
return false;
}
var ESCAPE_LOOKUP = {
'&': '&',
'>': '>',
'<': '<',
'"': '"',
'`': '`',
"'": '''
};
var ESCAPE_REGEX = /[&><"'`]/g;
/**
* Escapes attribute value to prevent scripting attacks.
*
* @param {*} value Attribute value to escape.
* @return {string} An escaped string.
*/
var quoteAttributeValueForBrowser = (function (value) {
return '"' + ('' + value).replace(ESCAPE_REGEX, function (match) {
return ESCAPE_LOOKUP[match];
}) + '"';
})
var selfClosingTags = {
area: true,
base: true,
basefont: true,
br: true,
col: true,
command: true,
embed: true,
frame: true,
hr: true,
img: true,
input: true,
isindex: true,
keygen: true,
link: true,
meta: true,
param: true,
source: true,
track: true,
wbr: true,
//common self closing svg elements
path: true,
circle: true,
ellipse: true,
line: true,
rect: true,
use: true,
stop: true,
polyline: true,
polygon: true
};
function renderMarkupForSelect(node) {
var value = node.attrs && node.attrs.value;
if (!isVoid(value)) {
var values = {};
if (isArray(value)) {
for (var i = 0, len = value.length; i < len; i++) {
values[value[i]] = value[i];
}
} else {
values[value] = value;
}
populateOptions(node, values);
if (node.attrs && node.attrs.value) {
delete node.attrs.value;
}
}
}
/**
* Populates values to options node.
*
* @param Object node A starting node (generaly a select node).
* @param Object values The selected values to populate.
*/
function populateOptions(node, values) {
if (node.tag !== 'option') {
for (var i = 0, len = node.children.length; i < len; i++) {
populateOptions(node.children[i], values);
}
return;
}
var value = node.attrs && node.attrs.value;
if (!values[value]) {
return;
}
node.attrs = node.attrs || {};
node.attrs.selected = "selected";
}
/**
* WORK IN PROGRESS
*
* Need to run tests for this one!!
*
* */
function renderMarkupForStyles(styles, component) {
var serialized = '';
for (var styleName in styles) {
if (isValidAttribute(styleName)) {
var styleValue = styles[styleName];
if (!isVoid(styleValue)) {
if (!unitlessProperties[styleName]) {
if (typeof styleValue !== 'string') {
styleValue = styleValue + 'px';
}
}
serialized += styleName + ':';
serialized += styleValue + ';';
}
}
}
return serialized || null;
}
function renderMarkupForAttributes(name, value) {
if (name === 'data-inferno') {
return '' + name;
}
var propertyInfo = HTMLPropsContainer[name] || null;
if (propertyInfo) {
if (isVoid(value) || propertyInfo.hasBooleanValue && !value || propertyInfo.hasNumericValue && value !== value || propertyInfo.hasPositiveNumericValue && value < 1 || value === 'false' || value.length === 0) {
return '';
}
var attributeName = propertyInfo.attributeName;
return attributeName + '=' + quoteAttributeValueForBrowser(value);
} else {
if (isVoid(value) || !isValidAttribute(name)) {
return '';
}
// custom attributes
return (DOMAttributeNames[name] || name.toLowerCase()) + '=' + quoteAttributeValueForBrowser(value);
}
}
function createStaticAttributes(props, excludeAttrs) {
var HTML = '';
for (var propKey in props) {
var propValue = props[propKey];
if (!isVoid(propValue)) {
if (propKey === 'style') {
propValue = renderMarkupForStyles(propValue);
}
var markup = null;
markup = renderMarkupForAttributes(propKey, propValue);
if (markup) {
HTML += ' ' + markup;
}
}
}
return HTML;
}
function createStaticTreeChildren(children) {
var isLastChildNode = false;
if (isArray(children)) {
return children.map(function (child, i) {
if (isStringOrNumber(child)) {
if (isLastChildNode) {
isLastChildNode = true;
return '<!---->' + child;
} else {
isLastChildNode = true;
return child;
}
}
isLastChildNode = false;
return createStaticTreeNode(false, child);
}).join('');
} else {
if (isStringOrNumber(children)) {
return children;
} else {
return createStaticTreeNode(false, children);
}
}
}
function createStaticTreeNode(isRoot, node) {
var staticNode = undefined;
if (isVoid(node)) {
return '';
}
if (node.tag) {
var tag = node.tag.toLowerCase();
var attrs = node.attrs;
var attributes = {};
for (var key in node.attrs) {
if (key === 'value') {
if (tag === 'select') {
renderMarkupForSelect(node);
continue;
} else if (tag === 'textarea' || attrs.contenteditable) {
node.text = attrs[key];
continue;
}
}
attributes[key] = attrs[key];
}
if (isRoot) {
attributes['data-inferno'] = true;
}
staticNode = '<' + tag;
// In React they can add innerHTML like this, just workaround it
if (attributes.innerHTML) {
node.text = attributes.innerHTML;
} else {
staticNode += createStaticAttributes(attributes, null);
}
if (selfClosingTags[tag]) {
staticNode += ' />';
} else {
staticNode += '>';
if (!isVoid(node.children)) {
staticNode += createStaticTreeChildren(node.children);
} else if (!isVoid(node.text)) {
staticNode += node.text;
}
staticNode += '</' + tag + '>';
}
}
return staticNode;
}
function createHTMLTree(schema, isRoot, dynamicNodeMap) {
var dynamicFlags = dynamicNodeMap.get(schema);
var node = undefined;
// static html
if (!dynamicFlags) {
return createStaticNode(createStaticTreeNode(isRoot, schema));
}
return node;
}
function renderToString(item) {
return item.tree.html.create(item);
}
var global = global || (typeof window !== 'undefined' ? window : null);
// browser
if (global && global.Inferno) {
global.Inferno.addTreeConstructor('html', createHTMLTree);
// nodeJS
// TODO! Find a better way to detect if we are running in Node, and test if this actually works!!!
} else if (global && !global.Inferno) {
var Inferno = undefined;
// TODO! Avoid try / catch
try {
Inferno = require('inferno');
} catch (e) {
Inferno = null;
// TODO Should we throw a warning and inform that the Inferno package is not installed?
}
if (Inferno != null) {
if (typeof Inferno.addTreeConstructor !== 'function') {
throw 'Your package is out-of-date! Upgrade to latest Inferno in order to use the InfernoServer package.';
} else {
Inferno.addTreeConstructor('html', createHTMLTree);
}
}
}
var index = {
renderToString: renderToString
};
return index;
}));
//# sourceMappingURL=inferno-server.js.map
|
{
return {
create: function create() {
return html;
}
};
}
|
identifier_body
|
inferno-server.js
|
* inferno-server vundefined
* (c) 2016 Dominic Gannaway
* Released under the MPL-2.0 License.
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.InfernoServer = factory());
}(this, function () { 'use strict';
var babelHelpers_typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
return typeof obj;
} : function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj;
};
function createStaticNode(html) {
return {
create: function create() {
return html;
}
};
}
var isArray = (function (x) {
return x.constructor === Array;
})
var isStringOrNumber = (function (x) {
return typeof x === 'string' || typeof x === 'number';
})
var noop = (function () {})
var canUseDOM = !!(typeof window !== 'undefined' &&
// Nwjs doesn't add document as a global in their node context, but does have it on window.document,
// As a workaround, check if document is undefined
typeof document !== 'undefined' && window.document.createElement);
var ExecutionEnvironment = {
canUseDOM: canUseDOM,
canUseWorkers: typeof Worker !== 'undefined',
canUseEventListeners: canUseDOM && !!window.addEventListener,
canUseViewport: canUseDOM && !!window.screen,
canUseSymbol: typeof Symbol === 'function' && typeof Symbol['for'] === 'function'
};
var HOOK = {};
var reDash = /\-./g;
/* eslint-disable quote-props */
var unitlessProperties = {
'animation-iteration-count': true,
'box-flex': true,
'box-flex-group': true,
'column-count': true,
'counter-increment': true,
'fill-opacity': true,
'flex': true,
'flex-grow': true,
'flex-order': true,
'flex-positive': true,
'flex-shrink': true,
'float': true,
'font-weight': true,
'grid-column': true,
'line-height': true,
'line-clamp': true,
'opacity': true,
'order': true,
'orphans': true,
'stop-opacity': true,
'stroke-dashoffset': true,
'stroke-opacity': true,
'stroke-width': true,
'tab-size': true,
'transform': true,
'transform-origin': true,
'widows': true,
'z-index': true,
'zoom': true
};
/* eslint-enable quote-props */
var directions = ['Top', 'Right', 'Bottom', 'Left'];
var dirMap = function dirMap(prefix, postfix) {
return directions.map(function (dir) {
return (prefix || '') + dir + (postfix || '');
});
};
var shortCuts = {
// rely on cssText
font: [/*
font-style
font-variant
font-weight
font-size/line-height
font-family|caption|icon|menu|message-box|small-caption|status-bar|initial|inherit;
*/],
padding: dirMap('padding'),
margin: dirMap('margin'),
'border-width': dirMap('border', 'Width'),
'border-style': dirMap('border', 'Style')
};
var cssToJSName = function cssToJSName(cssName) {
return cssName.replace(reDash, function (str) {
return str[1].toUpperCase();
});
};
// Don't execute this in nodejS
if (ExecutionEnvironment.canUseDOM) {
(function () {
// get browser supported CSS properties
var documentElement = document.documentElement;
var computed = window.getComputedStyle(documentElement);
var props = Array.prototype.slice.call(computed, 0);
for (var key in documentElement.style) {
if (!computed[key]) {
props.push(key);
}
}
props.forEach(function (propName) {
var prefix = propName[0] === '-' ? propName.substr(1, propName.indexOf('-', 1) - 1) : null;
var stylePropName = cssToJSName(propName);
HOOK[stylePropName] = {
unPrefixed: prefix ? propName.substr(prefix.length + 2) : propName,
unitless: unitlessProperties[propName] ? true : false,
shorthand: null
};
});
var lenMap = {
1: function _(values, props, style) {
return props.forEach(function (prop) {
return style[prop] = values[0];
});
},
2: function _(values, props, style) {
return values.forEach(function (value, index) {
style[props[index]] = style[props[index + 2]] = value;
});
},
4: function _(values, props, style) {
return props.forEach(function (prop, index) {
style[prop] = values[index];
});
}
};
// normalize property shortcuts
Object.keys(shortCuts).forEach(function (propName) {
var stylePropName = cssToJSName(propName);
HOOK[stylePropName] = {
unPrefixed: propName,
unitless: false,
shorthand: function shorthand(value, style) {
var type = typeof value === 'undefined' ? 'undefined' : babelHelpers_typeof(value);
if (type === 'number') {
value += 'px';
}
if (!value) {
return;
}
if ('cssText' in style) {
// normalize setting complex property across browsers
style.cssText += ';' + propName + ':' + value;
} else {
var values = value.split(' ');
(lenMap[values.length] || noop)(values, shortCuts[propName], style);
}
}
};
});
})();
}
/**
* DOM registry
* */
var PROPERTY = 0x1;
var BOOLEAN = 0x2;
var NUMERIC_VALUE = 0x4;
var POSITIVE_NUMERIC_VALUE = 0x6 | 0x4;
var xlink = 'http://www.w3.org/1999/xlink';
var xml = 'http://www.w3.org/XML/1998/namespace';
var DOMAttributeNamespaces = {
// None-JSX compat
'xlink:actuate': xlink,
'xlink:arcrole': xlink,
'xlink:href': xlink,
'xlink:role': xlink,
'xlink:show': xlink,
'xlink:title': xlink,
'xlink:type': xlink,
'xml:base': xml,
'xml:lang': xml,
'xml:space': xml,
// JSX compat
xlinkActuate: xlink,
xlinkArcrole: xlink,
xlinkHref: xlink,
xlinkRole: xlink,
xlinkShow: xlink,
xlinkTitle: xlink,
xlinkType: xlink
};
var DOMAttributeNames = {
acceptCharset: 'accept-charset',
className: 'class',
htmlFor: 'for',
httpEquiv: 'http-equiv',
// SVG
clipPath: 'clip-path',
fillOpacity: 'fill-opacity',
fontFamily: 'font-family',
fontSize: 'font-size',
markerEnd: 'marker-end',
markerMid: 'marker-mid',
markerStart: 'marker-start',
stopColor: 'stop-color',
stopOpacity: 'stop-opacity',
strokeDasharray: 'stroke-dasharray',
strokeLinecap: 'stroke-linecap',
strokeOpacity: 'stroke-opacity',
strokeWidth: 'stroke-width',
textAnchor: 'text-anchor',
viewBox: 'viewBox', // Edge case. The letter 'b' need to be uppercase
// JSX compat
xlinkActuate: 'xlink:actuate',
xlinkArcrole: 'xlink:arcrole',
xlinkHref: 'xlink:href',
xlinkRole: 'xlink:role',
xlinkShow: 'xlink:show',
xlinkTitle: 'xlink:title',
xlinkType: 'xlink:type',
xmlBase: 'xml:base',
xmlLang: 'xml:lang',
xmlSpace: 'xml:space'
};
var DOMPropertyNames = {
autoComplete: 'autocomplete',
autoFocus: 'autofocus',
autoSave: 'autosave'
};
// This 'whitelist' contains edge cases such as attributes
// that should be seen as a property or boolean property.
// ONLY EDIT THIS IF YOU KNOW WHAT YOU ARE DOING!!
var Whitelist = {
allowFullScreen: BOOLEAN,
async: BOOLEAN,
autoFocus: BOOLEAN,
autoPlay: BOOLEAN,
capture: BOOLEAN,
checked: PROPERTY | BOOLEAN,
controls: BOOLEAN,
currentTime: PROPERTY | POSITIVE_NUMERIC_VALUE,
default: BOOLEAN,
defaultChecked: BOOLEAN,
defaultMuted: BOOLEAN,
defaultSelected: BOOLEAN,
defer: BOOLEAN,
disabled: PROPERTY | BOOLEAN,
download: BOOLEAN,
enabled: BOOLEAN,
formNoValidate: BOOLEAN,
hidden: PROPERTY | BOOLEAN, // 3.2.5 - Global attributes
loop: BOOLEAN,
// Caution; `option.selected` is not updated if `select.multiple` is
// disabled with `removeAttribute`.
multiple: PROPERTY | BOOLEAN,
muted: PROPERTY | BOOLEAN,
mediaGroup: PROPERTY,
noValidate: BOOLEAN,
noShade: PROPERTY | BOOLEAN,
noResize: BOOLEAN,
noWrap: BOOLEAN,
typeMustMatch: BOOLEAN,
open: BOOLEAN,
paused: PROPERTY,
playbackRate: PROPERTY | NUMERIC_VALUE,
readOnly: BOOLEAN,
required: PROPERTY | BOOLEAN,
reversed: BOOLEAN,
radioGroup: PROPERTY,
icon: PROPERTY,
draggable: BOOLEAN, // 3.2.5 - Global attributes
dropzone: null, // 3.2.5 - Global attributes
scoped: PROPERTY | BOOLEAN,
visible: BOOLEAN,
trueSpeed: BOOLEAN,
sandbox: null,
sortable: BOOLEAN,
inert: BOOLEAN,
indeterminate: BOOLEAN,
nohref: BOOLEAN,
compact: BOOLEAN,
declare: BOOLEAN,
ismap: PROPERTY | BOOLEAN,
pauseOnExit: PROPERTY | BOOLEAN,
seamless: BOOLEAN,
translate: BOOLEAN, // 3.2.5 - Global attributes
selected: PROPERTY | BOOLEAN,
srcLang: PROPERTY,
srcObject: PROPERTY,
value: PROPERTY,
volume: PROPERTY | POSITIVE_NUMERIC_VALUE,
itemScope: BOOLEAN, // 3.2.5 - Global attributes
className: null,
tabindex: PROPERTY | NUMERIC_VALUE,
/**
* React compat for non-working JSX namespace support
*/
xlinkActuate: null,
xlinkArcrole: null,
xlinkHref: null,
xlinkRole: null,
xlinkShow: null,
xlinkTitle: null,
xlinkType: null,
xmlBase: null,
xmlLang: null,
xmlSpace: null,
/**
* SVG
*/
clipPath: null,
fillOpacity: null,
fontFamily: null,
fontSize: null,
markerEnd: null,
markerMid: null,
markerStart: null,
stopColor: null,
stopOpacity: null,
strokeDasharray: null,
strokeLinecap: null,
strokeOpacity: null,
strokeWidth: null,
textAnchor: null,
/**
* Numeric attributes
*/
cols: POSITIVE_NUMERIC_VALUE,
rows: NUMERIC_VALUE,
rowspan: NUMERIC_VALUE,
size: POSITIVE_NUMERIC_VALUE,
sizes: NUMERIC_VALUE,
start: NUMERIC_VALUE,
/**
* Namespace attributes
*/
'xlink:actuate': null,
'xlink:arcrole': null,
'xlink:href': null,
'xlink:role': null,
'xlink:show': null,
'xlink:title': null,
'xlink:type': null,
'xml:base': null,
'xml:lang': null,
'xml:space': null,
/**
* 3.2.5 - Global attributes
*/
id: null,
dir: null,
title: null,
/**
* Properties that MUST be set as attributes, due to:
*
* - browser bug
* - strange spec outlier
*
* Nothing bad with this. This properties get a performance boost
* compared to custom attributes because they are skipping the
* validation check.
*/
// Force 'autocorrect' and 'autoCapitalize' to be set as an attribute
// to fix issues with Mobile Safari on iOS devices
autocorrect: null,
// autoCapitalize and autoCorrect are supported in Mobile Safari for
// keyboard hints.
autoCapitalize: null,
// Some version of IE ( like IE9 ) actually throw an exception
// if you set input.type = 'something-unknown'
type: null,
/**
* Form
*/
form: null,
formAction: null,
formEncType: null,
formMethod: null,
formTarget: null,
frameBorder: null,
/**
* Internet Explorer / Edge
*/
// IE-only attribute that controls focus behavior
unselectable: null,
/**
* Firefox
*/
continuous: BOOLEAN,
/**
* Others
*/
srcSet: null,
inlist: null,
minLength: null,
marginWidth: null,
marginHeight: null,
list: null,
keyType: null,
is: null,
inputMode: null,
height: null,
width: null,
dateTime: null,
contenteditable: null, // 3.2.5 - Global attributes
contextMenu: null,
classID: null,
cellPadding: null,
cellSpacing: null,
charSet: null,
allowTransparency: null,
spellcheck: null, // 3.2.5 - Global attributes
srcDoc: PROPERTY
};
var HTMLPropsContainer = {};
function checkBitmask(value, bitmask) {
return bitmask !== null && (value & bitmask) === bitmask;
}
for (var propName in Whitelist) {
var propConfig = Whitelist[propName];
HTMLPropsContainer[propName] = {
attributeName: DOMAttributeNames[propName] || propName.toLowerCase(),
attributeNamespace: DOMAttributeNamespaces[propName] ? DOMAttributeNamespaces[propName] : null,
propertyName: DOMPropertyNames[propName] || propName,
mustUseProperty: checkBitmask(propConfig, PROPERTY),
hasBooleanValue: checkBitmask(propConfig, BOOLEAN),
hasNumericValue: checkBitmask(propConfig, NUMERIC_VALUE),
hasPositiveNumericValue: checkBitmask(propConfig, POSITIVE_NUMERIC_VALUE)
};
}
var isVoid = (function (x) {
return x === null || x === undefined;
})
/* eslint eqeqeq:0 */
function isValidAttribute(strings) {
var i = 0;
var character = undefined;
while (i <= strings.length) {
character = strings[i];
if (!isNaN(character * 1)) {
return false;
} else {
if (character == character.toUpperCase()) {
return false;
}
if (character === character.toLowerCase()) {
return true;
}
}
i++;
}
return false;
}
var ESCAPE_LOOKUP = {
'&': '&',
'>': '>',
'<': '<',
'"': '"',
'`': '`',
"'": '''
};
var ESCAPE_REGEX = /[&><"'`]/g;
/**
* Escapes attribute value to prevent scripting attacks.
*
* @param {*} value Attribute value to escape.
* @return {string} An escaped string.
*/
var quoteAttributeValueForBrowser = (function (value) {
return '"' + ('' + value).replace(ESCAPE_REGEX, function (match) {
return ESCAPE_LOOKUP[match];
}) + '"';
})
var selfClosingTags = {
area: true,
base: true,
basefont: true,
br: true,
col: true,
command: true,
embed: true,
frame: true,
hr: true,
img: true,
input: true,
isindex: true,
keygen: true,
link: true,
meta: true,
param: true,
source: true,
track: true,
wbr: true,
//common self closing svg elements
path: true,
circle: true,
ellipse: true,
line: true,
rect: true,
use: true,
stop: true,
polyline: true,
polygon: true
};
function renderMarkupForSelect(node) {
var value = node.attrs && node.attrs.value;
if (!isVoid(value)) {
var values = {};
if (isArray(value)) {
for (var i = 0, len = value.length; i < len; i++) {
values[value[i]] = value[i];
}
} else {
values[value] = value;
}
populateOptions(node, values);
if (node.attrs && node.attrs.value) {
delete node.attrs.value;
}
}
}
/**
* Populates values to options node.
*
* @param Object node A starting node (generaly a select node).
* @param Object values The selected values to populate.
*/
function populateOptions(node, values) {
if (node.tag !== 'option') {
for (var i = 0, len = node.children.length; i < len; i++) {
populateOptions(node.children[i], values);
}
return;
}
var value = node.attrs && node.attrs.value;
if (!values[value]) {
return;
}
node.attrs = node.attrs || {};
node.attrs.selected = "selected";
}
/**
* WORK IN PROGRESS
*
* Need to run tests for this one!!
*
* */
function renderMarkupForStyles(styles, component) {
var serialized = '';
for (var styleName in styles) {
if (isValidAttribute(styleName)) {
var styleValue = styles[styleName];
if (!isVoid(styleValue)) {
if (!unitlessProperties[styleName]) {
if (typeof styleValue !== 'string') {
styleValue = styleValue + 'px';
}
}
serialized += styleName + ':';
serialized += styleValue + ';';
}
}
}
return serialized || null;
}
function renderMarkupForAttributes(name, value) {
if (name === 'data-inferno') {
return '' + name;
}
var propertyInfo = HTMLPropsContainer[name] || null;
if (propertyInfo) {
if (isVoid(value) || propertyInfo.hasBooleanValue && !value || propertyInfo.hasNumericValue && value !== value || propertyInfo.hasPositiveNumericValue && value < 1 || value === 'false' || value.length === 0) {
return '';
}
var attributeName = propertyInfo.attributeName;
return attributeName + '=' + quoteAttributeValueForBrowser(value);
} else {
if (isVoid(value) || !isValidAttribute(name)) {
return '';
}
// custom attributes
return (DOMAttributeNames[name] || name.toLowerCase()) + '=' + quoteAttributeValueForBrowser(value);
}
}
function createStaticAttributes(props, excludeAttrs) {
var HTML = '';
for (var propKey in props) {
var propValue = props[propKey];
if (!isVoid(propValue)) {
if (propKey === 'style') {
propValue = renderMarkupForStyles(propValue);
}
var markup = null;
markup = renderMarkupForAttributes(propKey, propValue);
if (markup) {
HTML += ' ' + markup;
}
}
}
return HTML;
}
function createStaticTreeChildren(children) {
var isLastChildNode = false;
if (isArray(children)) {
return children.map(function (child, i) {
if (isStringOrNumber(child)) {
if (isLastChildNode) {
isLastChildNode = true;
return '<!---->' + child;
} else {
isLastChildNode = true;
return child;
}
}
isLastChildNode = false;
return createStaticTreeNode(false, child);
}).join('');
} else {
if (isStringOrNumber(children)) {
return children;
} else {
return createStaticTreeNode(false, children);
}
}
}
function createStaticTreeNode(isRoot, node) {
var staticNode = undefined;
if (isVoid(node)) {
return '';
}
if (node.tag) {
var tag = node.tag.toLowerCase();
var attrs = node.attrs;
var attributes = {};
for (var key in node.attrs) {
if (key === 'value') {
if (tag === 'select') {
renderMarkupForSelect(node);
continue;
} else if (tag === 'textarea' || attrs.contenteditable) {
node.text = attrs[key];
continue;
}
}
attributes[key] = attrs[key];
}
if (isRoot) {
attributes['data-inferno'] = true;
}
staticNode = '<' + tag;
// In React they can add innerHTML like this, just workaround it
if (attributes.innerHTML) {
node.text = attributes.innerHTML;
} else {
staticNode += createStaticAttributes(attributes, null);
}
if (selfClosingTags[tag]) {
staticNode += ' />';
} else {
staticNode += '>';
if (!isVoid(node.children)) {
staticNode += createStaticTreeChildren(node.children);
} else if (!isVoid(node.text)) {
staticNode += node.text;
}
staticNode += '</' + tag + '>';
}
}
return staticNode;
}
function createHTMLTree(schema, isRoot, dynamicNodeMap) {
var dynamicFlags = dynamicNodeMap.get(schema);
var node = undefined;
// static html
if (!dynamicFlags) {
return createStaticNode(createStaticTreeNode(isRoot, schema));
}
return node;
}
function renderToString(item) {
return item.tree.html.create(item);
}
var global = global || (typeof window !== 'undefined' ? window : null);
// browser
if (global && global.Inferno) {
global.Inferno.addTreeConstructor('html', createHTMLTree);
// nodeJS
// TODO! Find a better way to detect if we are running in Node, and test if this actually works!!!
} else if (global && !global.Inferno) {
var Inferno = undefined;
// TODO! Avoid try / catch
try {
Inferno = require('inferno');
} catch (e) {
Inferno = null;
// TODO Should we throw a warning and inform that the Inferno package is not installed?
}
if (Inferno != null) {
if (typeof Inferno.addTreeConstructor !== 'function') {
throw 'Your package is out-of-date! Upgrade to latest Inferno in order to use the InfernoServer package.';
} else {
Inferno.addTreeConstructor('html', createHTMLTree);
}
}
}
var index = {
renderToString: renderToString
};
return index;
}));
//# sourceMappingURL=inferno-server.js.map
|
/*!
|
random_line_split
|
|
inferno-server.js
|
/*!
* inferno-server vundefined
* (c) 2016 Dominic Gannaway
* Released under the MPL-2.0 License.
*/
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.InfernoServer = factory());
}(this, function () { 'use strict';
var babelHelpers_typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
return typeof obj;
} : function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj;
};
function createStaticNode(html) {
return {
create: function create() {
return html;
}
};
}
var isArray = (function (x) {
return x.constructor === Array;
})
var isStringOrNumber = (function (x) {
return typeof x === 'string' || typeof x === 'number';
})
var noop = (function () {})
var canUseDOM = !!(typeof window !== 'undefined' &&
// Nwjs doesn't add document as a global in their node context, but does have it on window.document,
// As a workaround, check if document is undefined
typeof document !== 'undefined' && window.document.createElement);
var ExecutionEnvironment = {
canUseDOM: canUseDOM,
canUseWorkers: typeof Worker !== 'undefined',
canUseEventListeners: canUseDOM && !!window.addEventListener,
canUseViewport: canUseDOM && !!window.screen,
canUseSymbol: typeof Symbol === 'function' && typeof Symbol['for'] === 'function'
};
var HOOK = {};
var reDash = /\-./g;
/* eslint-disable quote-props */
var unitlessProperties = {
'animation-iteration-count': true,
'box-flex': true,
'box-flex-group': true,
'column-count': true,
'counter-increment': true,
'fill-opacity': true,
'flex': true,
'flex-grow': true,
'flex-order': true,
'flex-positive': true,
'flex-shrink': true,
'float': true,
'font-weight': true,
'grid-column': true,
'line-height': true,
'line-clamp': true,
'opacity': true,
'order': true,
'orphans': true,
'stop-opacity': true,
'stroke-dashoffset': true,
'stroke-opacity': true,
'stroke-width': true,
'tab-size': true,
'transform': true,
'transform-origin': true,
'widows': true,
'z-index': true,
'zoom': true
};
/* eslint-enable quote-props */
var directions = ['Top', 'Right', 'Bottom', 'Left'];
var dirMap = function dirMap(prefix, postfix) {
return directions.map(function (dir) {
return (prefix || '') + dir + (postfix || '');
});
};
var shortCuts = {
// rely on cssText
font: [/*
font-style
font-variant
font-weight
font-size/line-height
font-family|caption|icon|menu|message-box|small-caption|status-bar|initial|inherit;
*/],
padding: dirMap('padding'),
margin: dirMap('margin'),
'border-width': dirMap('border', 'Width'),
'border-style': dirMap('border', 'Style')
};
var cssToJSName = function cssToJSName(cssName) {
return cssName.replace(reDash, function (str) {
return str[1].toUpperCase();
});
};
// Don't execute this in nodejS
if (ExecutionEnvironment.canUseDOM) {
(function () {
// get browser supported CSS properties
var documentElement = document.documentElement;
var computed = window.getComputedStyle(documentElement);
var props = Array.prototype.slice.call(computed, 0);
for (var key in documentElement.style) {
if (!computed[key]) {
props.push(key);
}
}
props.forEach(function (propName) {
var prefix = propName[0] === '-' ? propName.substr(1, propName.indexOf('-', 1) - 1) : null;
var stylePropName = cssToJSName(propName);
HOOK[stylePropName] = {
unPrefixed: prefix ? propName.substr(prefix.length + 2) : propName,
unitless: unitlessProperties[propName] ? true : false,
shorthand: null
};
});
var lenMap = {
1: function _(values, props, style) {
return props.forEach(function (prop) {
return style[prop] = values[0];
});
},
2: function _(values, props, style) {
return values.forEach(function (value, index) {
style[props[index]] = style[props[index + 2]] = value;
});
},
4: function _(values, props, style) {
return props.forEach(function (prop, index) {
style[prop] = values[index];
});
}
};
// normalize property shortcuts
Object.keys(shortCuts).forEach(function (propName) {
var stylePropName = cssToJSName(propName);
HOOK[stylePropName] = {
unPrefixed: propName,
unitless: false,
shorthand: function shorthand(value, style) {
var type = typeof value === 'undefined' ? 'undefined' : babelHelpers_typeof(value);
if (type === 'number') {
value += 'px';
}
if (!value) {
return;
}
if ('cssText' in style) {
// normalize setting complex property across browsers
style.cssText += ';' + propName + ':' + value;
} else {
var values = value.split(' ');
(lenMap[values.length] || noop)(values, shortCuts[propName], style);
}
}
};
});
})();
}
/**
* DOM registry
* */
var PROPERTY = 0x1;
var BOOLEAN = 0x2;
var NUMERIC_VALUE = 0x4;
var POSITIVE_NUMERIC_VALUE = 0x6 | 0x4;
var xlink = 'http://www.w3.org/1999/xlink';
var xml = 'http://www.w3.org/XML/1998/namespace';
var DOMAttributeNamespaces = {
// None-JSX compat
'xlink:actuate': xlink,
'xlink:arcrole': xlink,
'xlink:href': xlink,
'xlink:role': xlink,
'xlink:show': xlink,
'xlink:title': xlink,
'xlink:type': xlink,
'xml:base': xml,
'xml:lang': xml,
'xml:space': xml,
// JSX compat
xlinkActuate: xlink,
xlinkArcrole: xlink,
xlinkHref: xlink,
xlinkRole: xlink,
xlinkShow: xlink,
xlinkTitle: xlink,
xlinkType: xlink
};
var DOMAttributeNames = {
acceptCharset: 'accept-charset',
className: 'class',
htmlFor: 'for',
httpEquiv: 'http-equiv',
// SVG
clipPath: 'clip-path',
fillOpacity: 'fill-opacity',
fontFamily: 'font-family',
fontSize: 'font-size',
markerEnd: 'marker-end',
markerMid: 'marker-mid',
markerStart: 'marker-start',
stopColor: 'stop-color',
stopOpacity: 'stop-opacity',
strokeDasharray: 'stroke-dasharray',
strokeLinecap: 'stroke-linecap',
strokeOpacity: 'stroke-opacity',
strokeWidth: 'stroke-width',
textAnchor: 'text-anchor',
viewBox: 'viewBox', // Edge case. The letter 'b' need to be uppercase
// JSX compat
xlinkActuate: 'xlink:actuate',
xlinkArcrole: 'xlink:arcrole',
xlinkHref: 'xlink:href',
xlinkRole: 'xlink:role',
xlinkShow: 'xlink:show',
xlinkTitle: 'xlink:title',
xlinkType: 'xlink:type',
xmlBase: 'xml:base',
xmlLang: 'xml:lang',
xmlSpace: 'xml:space'
};
var DOMPropertyNames = {
autoComplete: 'autocomplete',
autoFocus: 'autofocus',
autoSave: 'autosave'
};
// This 'whitelist' contains edge cases such as attributes
// that should be seen as a property or boolean property.
// ONLY EDIT THIS IF YOU KNOW WHAT YOU ARE DOING!!
var Whitelist = {
allowFullScreen: BOOLEAN,
async: BOOLEAN,
autoFocus: BOOLEAN,
autoPlay: BOOLEAN,
capture: BOOLEAN,
checked: PROPERTY | BOOLEAN,
controls: BOOLEAN,
currentTime: PROPERTY | POSITIVE_NUMERIC_VALUE,
default: BOOLEAN,
defaultChecked: BOOLEAN,
defaultMuted: BOOLEAN,
defaultSelected: BOOLEAN,
defer: BOOLEAN,
disabled: PROPERTY | BOOLEAN,
download: BOOLEAN,
enabled: BOOLEAN,
formNoValidate: BOOLEAN,
hidden: PROPERTY | BOOLEAN, // 3.2.5 - Global attributes
loop: BOOLEAN,
// Caution; `option.selected` is not updated if `select.multiple` is
// disabled with `removeAttribute`.
multiple: PROPERTY | BOOLEAN,
muted: PROPERTY | BOOLEAN,
mediaGroup: PROPERTY,
noValidate: BOOLEAN,
noShade: PROPERTY | BOOLEAN,
noResize: BOOLEAN,
noWrap: BOOLEAN,
typeMustMatch: BOOLEAN,
open: BOOLEAN,
paused: PROPERTY,
playbackRate: PROPERTY | NUMERIC_VALUE,
readOnly: BOOLEAN,
required: PROPERTY | BOOLEAN,
reversed: BOOLEAN,
radioGroup: PROPERTY,
icon: PROPERTY,
draggable: BOOLEAN, // 3.2.5 - Global attributes
dropzone: null, // 3.2.5 - Global attributes
scoped: PROPERTY | BOOLEAN,
visible: BOOLEAN,
trueSpeed: BOOLEAN,
sandbox: null,
sortable: BOOLEAN,
inert: BOOLEAN,
indeterminate: BOOLEAN,
nohref: BOOLEAN,
compact: BOOLEAN,
declare: BOOLEAN,
ismap: PROPERTY | BOOLEAN,
pauseOnExit: PROPERTY | BOOLEAN,
seamless: BOOLEAN,
translate: BOOLEAN, // 3.2.5 - Global attributes
selected: PROPERTY | BOOLEAN,
srcLang: PROPERTY,
srcObject: PROPERTY,
value: PROPERTY,
volume: PROPERTY | POSITIVE_NUMERIC_VALUE,
itemScope: BOOLEAN, // 3.2.5 - Global attributes
className: null,
tabindex: PROPERTY | NUMERIC_VALUE,
/**
* React compat for non-working JSX namespace support
*/
xlinkActuate: null,
xlinkArcrole: null,
xlinkHref: null,
xlinkRole: null,
xlinkShow: null,
xlinkTitle: null,
xlinkType: null,
xmlBase: null,
xmlLang: null,
xmlSpace: null,
/**
* SVG
*/
clipPath: null,
fillOpacity: null,
fontFamily: null,
fontSize: null,
markerEnd: null,
markerMid: null,
markerStart: null,
stopColor: null,
stopOpacity: null,
strokeDasharray: null,
strokeLinecap: null,
strokeOpacity: null,
strokeWidth: null,
textAnchor: null,
/**
* Numeric attributes
*/
cols: POSITIVE_NUMERIC_VALUE,
rows: NUMERIC_VALUE,
rowspan: NUMERIC_VALUE,
size: POSITIVE_NUMERIC_VALUE,
sizes: NUMERIC_VALUE,
start: NUMERIC_VALUE,
/**
* Namespace attributes
*/
'xlink:actuate': null,
'xlink:arcrole': null,
'xlink:href': null,
'xlink:role': null,
'xlink:show': null,
'xlink:title': null,
'xlink:type': null,
'xml:base': null,
'xml:lang': null,
'xml:space': null,
/**
* 3.2.5 - Global attributes
*/
id: null,
dir: null,
title: null,
/**
* Properties that MUST be set as attributes, due to:
*
* - browser bug
* - strange spec outlier
*
* Nothing bad with this. This properties get a performance boost
* compared to custom attributes because they are skipping the
* validation check.
*/
// Force 'autocorrect' and 'autoCapitalize' to be set as an attribute
// to fix issues with Mobile Safari on iOS devices
autocorrect: null,
// autoCapitalize and autoCorrect are supported in Mobile Safari for
// keyboard hints.
autoCapitalize: null,
// Some version of IE ( like IE9 ) actually throw an exception
// if you set input.type = 'something-unknown'
type: null,
/**
* Form
*/
form: null,
formAction: null,
formEncType: null,
formMethod: null,
formTarget: null,
frameBorder: null,
/**
* Internet Explorer / Edge
*/
// IE-only attribute that controls focus behavior
unselectable: null,
/**
* Firefox
*/
continuous: BOOLEAN,
/**
* Others
*/
srcSet: null,
inlist: null,
minLength: null,
marginWidth: null,
marginHeight: null,
list: null,
keyType: null,
is: null,
inputMode: null,
height: null,
width: null,
dateTime: null,
contenteditable: null, // 3.2.5 - Global attributes
contextMenu: null,
classID: null,
cellPadding: null,
cellSpacing: null,
charSet: null,
allowTransparency: null,
spellcheck: null, // 3.2.5 - Global attributes
srcDoc: PROPERTY
};
var HTMLPropsContainer = {};
function checkBitmask(value, bitmask) {
return bitmask !== null && (value & bitmask) === bitmask;
}
for (var propName in Whitelist) {
var propConfig = Whitelist[propName];
HTMLPropsContainer[propName] = {
attributeName: DOMAttributeNames[propName] || propName.toLowerCase(),
attributeNamespace: DOMAttributeNamespaces[propName] ? DOMAttributeNamespaces[propName] : null,
propertyName: DOMPropertyNames[propName] || propName,
mustUseProperty: checkBitmask(propConfig, PROPERTY),
hasBooleanValue: checkBitmask(propConfig, BOOLEAN),
hasNumericValue: checkBitmask(propConfig, NUMERIC_VALUE),
hasPositiveNumericValue: checkBitmask(propConfig, POSITIVE_NUMERIC_VALUE)
};
}
var isVoid = (function (x) {
return x === null || x === undefined;
})
/* eslint eqeqeq:0 */
function
|
(strings) {
var i = 0;
var character = undefined;
while (i <= strings.length) {
character = strings[i];
if (!isNaN(character * 1)) {
return false;
} else {
if (character == character.toUpperCase()) {
return false;
}
if (character === character.toLowerCase()) {
return true;
}
}
i++;
}
return false;
}
var ESCAPE_LOOKUP = {
'&': '&',
'>': '>',
'<': '<',
'"': '"',
'`': '`',
"'": '''
};
var ESCAPE_REGEX = /[&><"'`]/g;
/**
* Escapes attribute value to prevent scripting attacks.
*
* @param {*} value Attribute value to escape.
* @return {string} An escaped string.
*/
var quoteAttributeValueForBrowser = (function (value) {
return '"' + ('' + value).replace(ESCAPE_REGEX, function (match) {
return ESCAPE_LOOKUP[match];
}) + '"';
})
var selfClosingTags = {
area: true,
base: true,
basefont: true,
br: true,
col: true,
command: true,
embed: true,
frame: true,
hr: true,
img: true,
input: true,
isindex: true,
keygen: true,
link: true,
meta: true,
param: true,
source: true,
track: true,
wbr: true,
//common self closing svg elements
path: true,
circle: true,
ellipse: true,
line: true,
rect: true,
use: true,
stop: true,
polyline: true,
polygon: true
};
function renderMarkupForSelect(node) {
var value = node.attrs && node.attrs.value;
if (!isVoid(value)) {
var values = {};
if (isArray(value)) {
for (var i = 0, len = value.length; i < len; i++) {
values[value[i]] = value[i];
}
} else {
values[value] = value;
}
populateOptions(node, values);
if (node.attrs && node.attrs.value) {
delete node.attrs.value;
}
}
}
/**
* Populates values to options node.
*
* @param Object node A starting node (generaly a select node).
* @param Object values The selected values to populate.
*/
function populateOptions(node, values) {
if (node.tag !== 'option') {
for (var i = 0, len = node.children.length; i < len; i++) {
populateOptions(node.children[i], values);
}
return;
}
var value = node.attrs && node.attrs.value;
if (!values[value]) {
return;
}
node.attrs = node.attrs || {};
node.attrs.selected = "selected";
}
/**
* WORK IN PROGRESS
*
* Need to run tests for this one!!
*
* */
function renderMarkupForStyles(styles, component) {
var serialized = '';
for (var styleName in styles) {
if (isValidAttribute(styleName)) {
var styleValue = styles[styleName];
if (!isVoid(styleValue)) {
if (!unitlessProperties[styleName]) {
if (typeof styleValue !== 'string') {
styleValue = styleValue + 'px';
}
}
serialized += styleName + ':';
serialized += styleValue + ';';
}
}
}
return serialized || null;
}
function renderMarkupForAttributes(name, value) {
if (name === 'data-inferno') {
return '' + name;
}
var propertyInfo = HTMLPropsContainer[name] || null;
if (propertyInfo) {
if (isVoid(value) || propertyInfo.hasBooleanValue && !value || propertyInfo.hasNumericValue && value !== value || propertyInfo.hasPositiveNumericValue && value < 1 || value === 'false' || value.length === 0) {
return '';
}
var attributeName = propertyInfo.attributeName;
return attributeName + '=' + quoteAttributeValueForBrowser(value);
} else {
if (isVoid(value) || !isValidAttribute(name)) {
return '';
}
// custom attributes
return (DOMAttributeNames[name] || name.toLowerCase()) + '=' + quoteAttributeValueForBrowser(value);
}
}
function createStaticAttributes(props, excludeAttrs) {
var HTML = '';
for (var propKey in props) {
var propValue = props[propKey];
if (!isVoid(propValue)) {
if (propKey === 'style') {
propValue = renderMarkupForStyles(propValue);
}
var markup = null;
markup = renderMarkupForAttributes(propKey, propValue);
if (markup) {
HTML += ' ' + markup;
}
}
}
return HTML;
}
function createStaticTreeChildren(children) {
var isLastChildNode = false;
if (isArray(children)) {
return children.map(function (child, i) {
if (isStringOrNumber(child)) {
if (isLastChildNode) {
isLastChildNode = true;
return '<!---->' + child;
} else {
isLastChildNode = true;
return child;
}
}
isLastChildNode = false;
return createStaticTreeNode(false, child);
}).join('');
} else {
if (isStringOrNumber(children)) {
return children;
} else {
return createStaticTreeNode(false, children);
}
}
}
function createStaticTreeNode(isRoot, node) {
var staticNode = undefined;
if (isVoid(node)) {
return '';
}
if (node.tag) {
var tag = node.tag.toLowerCase();
var attrs = node.attrs;
var attributes = {};
for (var key in node.attrs) {
if (key === 'value') {
if (tag === 'select') {
renderMarkupForSelect(node);
continue;
} else if (tag === 'textarea' || attrs.contenteditable) {
node.text = attrs[key];
continue;
}
}
attributes[key] = attrs[key];
}
if (isRoot) {
attributes['data-inferno'] = true;
}
staticNode = '<' + tag;
// In React they can add innerHTML like this, just workaround it
if (attributes.innerHTML) {
node.text = attributes.innerHTML;
} else {
staticNode += createStaticAttributes(attributes, null);
}
if (selfClosingTags[tag]) {
staticNode += ' />';
} else {
staticNode += '>';
if (!isVoid(node.children)) {
staticNode += createStaticTreeChildren(node.children);
} else if (!isVoid(node.text)) {
staticNode += node.text;
}
staticNode += '</' + tag + '>';
}
}
return staticNode;
}
function createHTMLTree(schema, isRoot, dynamicNodeMap) {
var dynamicFlags = dynamicNodeMap.get(schema);
var node = undefined;
// static html
if (!dynamicFlags) {
return createStaticNode(createStaticTreeNode(isRoot, schema));
}
return node;
}
function renderToString(item) {
return item.tree.html.create(item);
}
var global = global || (typeof window !== 'undefined' ? window : null);
// browser
if (global && global.Inferno) {
global.Inferno.addTreeConstructor('html', createHTMLTree);
// nodeJS
// TODO! Find a better way to detect if we are running in Node, and test if this actually works!!!
} else if (global && !global.Inferno) {
var Inferno = undefined;
// TODO! Avoid try / catch
try {
Inferno = require('inferno');
} catch (e) {
Inferno = null;
// TODO Should we throw a warning and inform that the Inferno package is not installed?
}
if (Inferno != null) {
if (typeof Inferno.addTreeConstructor !== 'function') {
throw 'Your package is out-of-date! Upgrade to latest Inferno in order to use the InfernoServer package.';
} else {
Inferno.addTreeConstructor('html', createHTMLTree);
}
}
}
var index = {
renderToString: renderToString
};
return index;
}));
//# sourceMappingURL=inferno-server.js.map
|
isValidAttribute
|
identifier_name
|
sksl-constants.ts
|
// CodeMirror likes mode definitions as maps to bools, but a string of space
// separated words is easier to edit, so we convert our strings into a map here.
function
|
(str: string) {
const obj: Record<string, boolean> = {};
str.split(' ').forEach((word: string) => { obj[word] = true; });
return obj;
}
// See the design doc for the list of keywords. http://go/shaders.skia.org
export const keywords = words(
'const attribute uniform varying break continue '
+ 'discard return for while do if else struct in out inout uniform layout');
export const blockKeywords = words('case do else for if switch while struct enum union');
export const defKeywords = words('struct enum union');
export const atoms = words('sk_FragCoord true false');
export const builtins = words(
'radians degrees '
+ 'sin cos tan asin acos atan '
+ 'pow exp log exp2 log2 '
+ 'sqrt inversesqrt '
+ 'abs sign floor ceil fract mod '
+ 'min max clamp saturate '
+ 'mix step smoothstep '
+ 'length distance dot cross normalize '
+ 'faceforward reflect refract '
+ 'matrixCompMult inverse '
+ 'lessThan lessThanEqual greaterThan greaterThanEqual equal notEqual '
+ 'any all not '
+ 'sample unpremul');
export const types = words(
'int long char short double float unsigned '
+ 'signed void bool float float2 float3 float4 '
+ 'float2x2 float3x3 float4x4 '
+ 'half half2 half3 half4 '
+ 'half2x2 half3x3 half4x4 '
+ 'bool bool2 bool3 bool4 '
+ 'int int2 int3 int4 '
+ 'fragmentProcessor shader '
+ 'vec2 vec3 vec4 '
+ 'ivec2 ivec3 ivec4 '
+ 'bvec2 bvec3 bvec4 '
+ 'mat2 mat3 mat4');
|
words
|
identifier_name
|
sksl-constants.ts
|
// CodeMirror likes mode definitions as maps to bools, but a string of space
// separated words is easier to edit, so we convert our strings into a map here.
function words(str: string) {
const obj: Record<string, boolean> = {};
str.split(' ').forEach((word: string) => { obj[word] = true; });
return obj;
}
// See the design doc for the list of keywords. http://go/shaders.skia.org
export const keywords = words(
'const attribute uniform varying break continue '
+ 'discard return for while do if else struct in out inout uniform layout');
export const blockKeywords = words('case do else for if switch while struct enum union');
export const defKeywords = words('struct enum union');
|
export const atoms = words('sk_FragCoord true false');
export const builtins = words(
'radians degrees '
+ 'sin cos tan asin acos atan '
+ 'pow exp log exp2 log2 '
+ 'sqrt inversesqrt '
+ 'abs sign floor ceil fract mod '
+ 'min max clamp saturate '
+ 'mix step smoothstep '
+ 'length distance dot cross normalize '
+ 'faceforward reflect refract '
+ 'matrixCompMult inverse '
+ 'lessThan lessThanEqual greaterThan greaterThanEqual equal notEqual '
+ 'any all not '
+ 'sample unpremul');
export const types = words(
'int long char short double float unsigned '
+ 'signed void bool float float2 float3 float4 '
+ 'float2x2 float3x3 float4x4 '
+ 'half half2 half3 half4 '
+ 'half2x2 half3x3 half4x4 '
+ 'bool bool2 bool3 bool4 '
+ 'int int2 int3 int4 '
+ 'fragmentProcessor shader '
+ 'vec2 vec3 vec4 '
+ 'ivec2 ivec3 ivec4 '
+ 'bvec2 bvec3 bvec4 '
+ 'mat2 mat3 mat4');
|
random_line_split
|
|
sksl-constants.ts
|
// CodeMirror likes mode definitions as maps to bools, but a string of space
// separated words is easier to edit, so we convert our strings into a map here.
function words(str: string)
|
// See the design doc for the list of keywords. http://go/shaders.skia.org
export const keywords = words(
'const attribute uniform varying break continue '
+ 'discard return for while do if else struct in out inout uniform layout');
export const blockKeywords = words('case do else for if switch while struct enum union');
export const defKeywords = words('struct enum union');
export const atoms = words('sk_FragCoord true false');
export const builtins = words(
'radians degrees '
+ 'sin cos tan asin acos atan '
+ 'pow exp log exp2 log2 '
+ 'sqrt inversesqrt '
+ 'abs sign floor ceil fract mod '
+ 'min max clamp saturate '
+ 'mix step smoothstep '
+ 'length distance dot cross normalize '
+ 'faceforward reflect refract '
+ 'matrixCompMult inverse '
+ 'lessThan lessThanEqual greaterThan greaterThanEqual equal notEqual '
+ 'any all not '
+ 'sample unpremul');
export const types = words(
'int long char short double float unsigned '
+ 'signed void bool float float2 float3 float4 '
+ 'float2x2 float3x3 float4x4 '
+ 'half half2 half3 half4 '
+ 'half2x2 half3x3 half4x4 '
+ 'bool bool2 bool3 bool4 '
+ 'int int2 int3 int4 '
+ 'fragmentProcessor shader '
+ 'vec2 vec3 vec4 '
+ 'ivec2 ivec3 ivec4 '
+ 'bvec2 bvec3 bvec4 '
+ 'mat2 mat3 mat4');
|
{
const obj: Record<string, boolean> = {};
str.split(' ').forEach((word: string) => { obj[word] = true; });
return obj;
}
|
identifier_body
|
handlers.rs
|
//! Handlers for the server.
use std::collections::BTreeMap;
use rustc_serialize::json::{Json, ToJson};
use iron::prelude::*;
use iron::{status, headers, middleware};
use iron::modifiers::Header;
use router::Router;
use redis::ConnectionInfo;
use urlencoded;
use ::api;
use ::api::optional::Optional;
use ::sensors;
use ::modifiers;
#[derive(Debug)]
struct ErrorResponse {
reason: String,
}
impl ToJson for ErrorResponse {
/// Serialize an ErrorResponse object into a proper JSON structure.
fn to_json(&self) -> Json {
let mut d = BTreeMap::new();
d.insert("status".to_string(), "error".to_json());
d.insert("reason".to_string(), self.reason.to_json());
Json::Object(d)
}
}
pub struct ReadHandler {
status: api::Status,
redis_connection_info: ConnectionInfo,
sensor_specs: sensors::SafeSensorSpecs,
status_modifiers: Vec<Box<modifiers::StatusModifier>>,
}
impl ReadHandler {
pub fn new(status: api::Status,
redis_connection_info: ConnectionInfo,
sensor_specs: sensors::SafeSensorSpecs,
status_modifiers: Vec<Box<modifiers::StatusModifier>>)
-> ReadHandler {
ReadHandler {
status: status,
redis_connection_info: redis_connection_info,
sensor_specs: sensor_specs,
status_modifiers: status_modifiers,
}
}
fn build_response_json(&self) -> Json {
// Create a mutable copy of the status struct
let mut status_copy = self.status.clone();
// Process registered sensors
for sensor_spec in self.sensor_specs.lock().unwrap().iter() {
match sensor_spec.get_sensor_value(&self.redis_connection_info) {
// Value could be read successfullly
Ok(value) => {
if status_copy.sensors.is_absent() {
status_copy.sensors = Optional::Value(api::Sensors {
people_now_present: Optional::Absent,
temperature: Optional::Absent,
});
}
sensor_spec.template.to_sensor(&value, &mut status_copy.sensors.as_mut().unwrap());
},
// Value could not be read, do error logging
Err(err) => {
match err {
sensors::SensorError::Redis(e) => {
warn!("Could not retrieve key '{}' from Redis, omiting the sensor", &sensor_spec.data_key);
debug!("Error: {:?}", e);
},
_ => error!("Could not retrieve sensor '{}', unknown error.", &sensor_spec.data_key)
}
},
}
}
for status_modifier in self.status_modifiers.iter() {
status_modifier.modify(&mut status_copy);
}
// Serialize to JSON
status_copy.to_json()
}
}
impl middleware::Handler for ReadHandler {
/// Return the current status JSON.
fn handle(&self, req: &mut Request) -> IronResult<Response> {
info!("{} /{} from {}", req.method, req.url.path[0], req.remote_addr);
// Get response body
let body = self.build_response_json().to_string();
// Create response
let response = Response::with((status::Ok, body))
// Set headers
.set(Header(headers::ContentType("application/json; charset=utf-8".parse().unwrap())))
.set(Header(headers::CacheControl(vec![headers::CacheDirective::NoCache])))
.set(Header(headers::AccessControlAllowOrigin::Any));
Ok(response)
}
}
pub struct UpdateHandler {
redis_connection_info: ConnectionInfo,
sensor_specs: sensors::SafeSensorSpecs,
}
impl UpdateHandler {
pub fn new(redis_connection_info: ConnectionInfo, sensor_specs: sensors::SafeSensorSpecs)
-> UpdateHandler {
UpdateHandler {
redis_connection_info: redis_connection_info,
sensor_specs: sensor_specs,
}
}
/// Update sensor value in Redis
fn update_sensor(&self, sensor: &str, value: &str) -> Result<(), sensors::SensorError> {
// Validate sensor
let sensor_specs = self.sensor_specs.lock().unwrap();
let sensor_spec = try!(sensor_specs.iter()
.find(|&spec| spec.data_key == sensor)
.ok_or(sensors::SensorError::UnknownSensor(sensor.to_string())));
// Store data
sensor_spec.set_sensor_value(&self.redis_connection_info, value)
}
/// Build an OK response with the `HTTP 204 No Content` status code.
fn ok_response(&self) -> Response {
Response::with((status::NoContent))
// Set headers
.set(Header(headers::ContentType("application/json; charset=utf-8".parse().unwrap())))
.set(Header(headers::CacheControl(vec![headers::CacheDirective::NoCache])))
.set(Header(headers::AccessControlAllowOrigin::Any))
}
|
// Set headers
.set(Header(headers::ContentType("application/json; charset=utf-8".parse().unwrap())))
.set(Header(headers::CacheControl(vec![headers::CacheDirective::NoCache])))
.set(Header(headers::AccessControlAllowOrigin::Any))
}
}
impl middleware::Handler for UpdateHandler {
/// Update the sensor, return correct status code.
fn handle(&self, req: &mut Request) -> IronResult<Response> {
// TODO: create macro for these info! invocations.
info!("{} /{} from {}", req.method, req.url.path[0], req.remote_addr);
// Get sensor name
let sensor_name;
{
// TODO: Properly propagate errors
let params = req.extensions.get::<Router>().unwrap();
sensor_name = params.find("sensor").unwrap().to_string();
}
// Get sensor value
let sensor_value;
{
let params = req.get_ref::<urlencoded::UrlEncodedBody>().unwrap();
sensor_value = match params.get("value") {
Some(ref values) => match values.len() {
1 => values[0].to_string(),
_ => return Ok(self.err_response(status::BadRequest, "Too many values specified")),
},
None => return Ok(self.err_response(status::BadRequest, "\"value\" parameter not specified")),
}
}
// Update values in Redis
if let Err(e) = self.update_sensor(&sensor_name, &sensor_value) {
error!("Updating sensor value for sensor \"{}\" failed: {:?}", &sensor_name, e);
let response = match e {
sensors::SensorError::UnknownSensor(sensor) =>
self.err_response(status::BadRequest, &format!("Unknown sensor: {}", sensor)),
sensors::SensorError::Redis(_) =>
self.err_response(status::InternalServerError, "Updating values in datastore failed"),
};
return Ok(response)
};
// Create response
Ok(self.ok_response())
}
}
|
/// Build an error response with the specified `error_code` and the specified `reason` text.
fn err_response(&self, error_code: status::Status, reason: &str) -> Response {
let error = ErrorResponse { reason: reason.to_string() };
Response::with((error_code, error.to_json().to_string()))
|
random_line_split
|
handlers.rs
|
//! Handlers for the server.
use std::collections::BTreeMap;
use rustc_serialize::json::{Json, ToJson};
use iron::prelude::*;
use iron::{status, headers, middleware};
use iron::modifiers::Header;
use router::Router;
use redis::ConnectionInfo;
use urlencoded;
use ::api;
use ::api::optional::Optional;
use ::sensors;
use ::modifiers;
#[derive(Debug)]
struct ErrorResponse {
reason: String,
}
impl ToJson for ErrorResponse {
/// Serialize an ErrorResponse object into a proper JSON structure.
fn to_json(&self) -> Json {
let mut d = BTreeMap::new();
d.insert("status".to_string(), "error".to_json());
d.insert("reason".to_string(), self.reason.to_json());
Json::Object(d)
}
}
pub struct ReadHandler {
status: api::Status,
redis_connection_info: ConnectionInfo,
sensor_specs: sensors::SafeSensorSpecs,
status_modifiers: Vec<Box<modifiers::StatusModifier>>,
}
impl ReadHandler {
pub fn new(status: api::Status,
redis_connection_info: ConnectionInfo,
sensor_specs: sensors::SafeSensorSpecs,
status_modifiers: Vec<Box<modifiers::StatusModifier>>)
-> ReadHandler {
ReadHandler {
status: status,
redis_connection_info: redis_connection_info,
sensor_specs: sensor_specs,
status_modifiers: status_modifiers,
}
}
fn build_response_json(&self) -> Json {
// Create a mutable copy of the status struct
let mut status_copy = self.status.clone();
// Process registered sensors
for sensor_spec in self.sensor_specs.lock().unwrap().iter() {
match sensor_spec.get_sensor_value(&self.redis_connection_info) {
// Value could be read successfullly
Ok(value) => {
if status_copy.sensors.is_absent() {
status_copy.sensors = Optional::Value(api::Sensors {
people_now_present: Optional::Absent,
temperature: Optional::Absent,
});
}
sensor_spec.template.to_sensor(&value, &mut status_copy.sensors.as_mut().unwrap());
},
// Value could not be read, do error logging
Err(err) => {
match err {
sensors::SensorError::Redis(e) => {
warn!("Could not retrieve key '{}' from Redis, omiting the sensor", &sensor_spec.data_key);
debug!("Error: {:?}", e);
},
_ => error!("Could not retrieve sensor '{}', unknown error.", &sensor_spec.data_key)
}
},
}
}
for status_modifier in self.status_modifiers.iter() {
status_modifier.modify(&mut status_copy);
}
// Serialize to JSON
status_copy.to_json()
}
}
impl middleware::Handler for ReadHandler {
/// Return the current status JSON.
fn handle(&self, req: &mut Request) -> IronResult<Response> {
info!("{} /{} from {}", req.method, req.url.path[0], req.remote_addr);
// Get response body
let body = self.build_response_json().to_string();
// Create response
let response = Response::with((status::Ok, body))
// Set headers
.set(Header(headers::ContentType("application/json; charset=utf-8".parse().unwrap())))
.set(Header(headers::CacheControl(vec![headers::CacheDirective::NoCache])))
.set(Header(headers::AccessControlAllowOrigin::Any));
Ok(response)
}
}
pub struct UpdateHandler {
redis_connection_info: ConnectionInfo,
sensor_specs: sensors::SafeSensorSpecs,
}
impl UpdateHandler {
pub fn new(redis_connection_info: ConnectionInfo, sensor_specs: sensors::SafeSensorSpecs)
-> UpdateHandler {
UpdateHandler {
redis_connection_info: redis_connection_info,
sensor_specs: sensor_specs,
}
}
/// Update sensor value in Redis
fn update_sensor(&self, sensor: &str, value: &str) -> Result<(), sensors::SensorError> {
// Validate sensor
let sensor_specs = self.sensor_specs.lock().unwrap();
let sensor_spec = try!(sensor_specs.iter()
.find(|&spec| spec.data_key == sensor)
.ok_or(sensors::SensorError::UnknownSensor(sensor.to_string())));
// Store data
sensor_spec.set_sensor_value(&self.redis_connection_info, value)
}
/// Build an OK response with the `HTTP 204 No Content` status code.
fn ok_response(&self) -> Response {
Response::with((status::NoContent))
// Set headers
.set(Header(headers::ContentType("application/json; charset=utf-8".parse().unwrap())))
.set(Header(headers::CacheControl(vec![headers::CacheDirective::NoCache])))
.set(Header(headers::AccessControlAllowOrigin::Any))
}
/// Build an error response with the specified `error_code` and the specified `reason` text.
fn
|
(&self, error_code: status::Status, reason: &str) -> Response {
let error = ErrorResponse { reason: reason.to_string() };
Response::with((error_code, error.to_json().to_string()))
// Set headers
.set(Header(headers::ContentType("application/json; charset=utf-8".parse().unwrap())))
.set(Header(headers::CacheControl(vec![headers::CacheDirective::NoCache])))
.set(Header(headers::AccessControlAllowOrigin::Any))
}
}
impl middleware::Handler for UpdateHandler {
/// Update the sensor, return correct status code.
fn handle(&self, req: &mut Request) -> IronResult<Response> {
// TODO: create macro for these info! invocations.
info!("{} /{} from {}", req.method, req.url.path[0], req.remote_addr);
// Get sensor name
let sensor_name;
{
// TODO: Properly propagate errors
let params = req.extensions.get::<Router>().unwrap();
sensor_name = params.find("sensor").unwrap().to_string();
}
// Get sensor value
let sensor_value;
{
let params = req.get_ref::<urlencoded::UrlEncodedBody>().unwrap();
sensor_value = match params.get("value") {
Some(ref values) => match values.len() {
1 => values[0].to_string(),
_ => return Ok(self.err_response(status::BadRequest, "Too many values specified")),
},
None => return Ok(self.err_response(status::BadRequest, "\"value\" parameter not specified")),
}
}
// Update values in Redis
if let Err(e) = self.update_sensor(&sensor_name, &sensor_value) {
error!("Updating sensor value for sensor \"{}\" failed: {:?}", &sensor_name, e);
let response = match e {
sensors::SensorError::UnknownSensor(sensor) =>
self.err_response(status::BadRequest, &format!("Unknown sensor: {}", sensor)),
sensors::SensorError::Redis(_) =>
self.err_response(status::InternalServerError, "Updating values in datastore failed"),
};
return Ok(response)
};
// Create response
Ok(self.ok_response())
}
}
|
err_response
|
identifier_name
|
dropdown.js
|
angular.module('ai.common.directives.dropdown', [])
.directive('aiDropdown', function() {
return {
restrict: 'EA',
require: 'ngModel',
scope: {
ngModel: '=',
list: '='
},
link: function(scope, elem, attrs, ngModel) {
var data = [];
_.each(scope.list, function (item) {
data.push({
'text': item,
'click': 'setter('+item+')'
});
});
scope.setter = function (val) {
scope.ngModel = val;
};
scope.data = data;
|
}, function() {
scope.selected = scope.ngModel;
});
},
template: '<button type="button" class="btn-dropdown full-width" bs-dropdown="data" html="true"> {{selected}} </button>'
};
})
;
|
scope.$watch(function () {
return ngModel.$modelValue;
|
random_line_split
|
Utils.py
|
#!/usr/bin/env python
# Meran - MERAN UNLP is a ILS (Integrated Library System) wich provides Catalog,
# Circulation and User's Management. It's written in Perl, and uses Apache2
# Web-Server, MySQL database and Sphinx 2 indexing.
# Copyright (C) 2009-2013 Grupo de desarrollo de Meran CeSPI-UNLP
#
# This file is part of Meran.
#
# Meran is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Meran is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Meran. If not, see <http://www.gnu.org/licenses/>.
# encoding: utf-8
# Meran - MERAN UNLP is a ILS (Integrated Library System) wich provides Catalog,
# Circulation and User's Management. It's written in Perl, and uses Apache2
# Web-Server, MySQL database and Sphinx 2 indexing.
# Copyright (C) 2009-2013 Grupo de desarrollo de Meran CeSPI-UNLP
#
# This file is part of Meran.
#
# Meran is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Meran is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Meran. If not, see <http://www.gnu.org/licenses/>.
# Thomas Nagy, 2005 (ita)
"""
Utilities, the stable ones are the following:
* h_file: compute a unique value for a file (hash), it uses
the module fnv if it is installed (see waf/utils/fnv & http://code.google.com/p/waf/wiki/FAQ)
else, md5 (see the python docs)
For large projects (projects with more than 15000 files) or slow hard disks and filesystems (HFS)
it is possible to use a hashing based on the path and the size (may give broken cache results)
The method h_file MUST raise an OSError if the file is a folder
import stat
def h_file(filename):
st = os.stat(filename)
if stat.S_ISDIR(st[stat.ST_MODE]): raise IOError('not a file')
m = Utils.md5()
m.update(str(st.st_mtime))
m.update(str(st.st_size))
m.update(filename)
return m.digest()
To replace the function in your project, use something like this:
import Utils
Utils.h_file = h_file
* h_list
* h_fun
* get_term_cols
* ordered_dict
"""
import os, sys, imp, string, errno, traceback, inspect, re, shutil, datetime, gc
# In python 3.0 we can get rid of all this
try: from UserDict import UserDict
except ImportError: from collections import UserDict
if sys.hexversion >= 0x2060000 or os.name == 'java':
import subprocess as pproc
else:
import pproc
import Logs
from Constants import *
try:
from collections import deque
except ImportError:
class deque(list):
def popleft(self):
return self.pop(0)
is_win32 = sys.platform == 'win32'
try:
# defaultdict in python 2.5
from collections import defaultdict as DefaultDict
except ImportError:
class DefaultDict(dict):
def __init__(self, default_factory):
super(DefaultDict, self).__init__()
self.default_factory = default_factory
def __getitem__(self, key):
try:
return super(DefaultDict, self).__getitem__(key)
except KeyError:
value = self.default_factory()
self[key] = value
return value
class WafError(Exception):
def __init__(self, *args):
self.args = args
try:
self.stack = traceback.extract_stack()
except:
pass
Exception.__init__(self, *args)
def __str__(self):
return str(len(self.args) == 1 and self.args[0] or self.args)
class WscriptError(WafError):
def __init__(self, message, wscript_file=None):
|
def locate_error(self):
stack = traceback.extract_stack()
stack.reverse()
for frame in stack:
file_name = os.path.basename(frame[0])
is_wscript = (file_name == WSCRIPT_FILE or file_name == WSCRIPT_BUILD_FILE)
if is_wscript:
return (frame[0], frame[1])
return (None, None)
indicator = is_win32 and '\x1b[A\x1b[K%s%s%s\r' or '\x1b[K%s%s%s\r'
try:
from fnv import new as md5
import Constants
Constants.SIG_NIL = 'signofnv'
def h_file(filename):
m = md5()
try:
m.hfile(filename)
x = m.digest()
if x is None: raise OSError("not a file")
return x
except SystemError:
raise OSError("not a file" + filename)
except ImportError:
try:
try:
from hashlib import md5
except ImportError:
from md5 import md5
def h_file(filename):
f = open(filename, 'rb')
m = md5()
while (filename):
filename = f.read(100000)
m.update(filename)
f.close()
return m.digest()
except ImportError:
# portability fixes may be added elsewhere (although, md5 should be everywhere by now)
md5 = None
class ordered_dict(UserDict):
def __init__(self, dict = None):
self.allkeys = []
UserDict.__init__(self, dict)
def __delitem__(self, key):
self.allkeys.remove(key)
UserDict.__delitem__(self, key)
def __setitem__(self, key, item):
if key not in self.allkeys: self.allkeys.append(key)
UserDict.__setitem__(self, key, item)
def exec_command(s, **kw):
if 'log' in kw:
kw['stdout'] = kw['stderr'] = kw['log']
del(kw['log'])
kw['shell'] = isinstance(s, str)
try:
proc = pproc.Popen(s, **kw)
return proc.wait()
except OSError:
return -1
if is_win32:
def exec_command(s, **kw):
if 'log' in kw:
kw['stdout'] = kw['stderr'] = kw['log']
del(kw['log'])
kw['shell'] = isinstance(s, str)
if len(s) > 2000:
startupinfo = pproc.STARTUPINFO()
startupinfo.dwFlags |= pproc.STARTF_USESHOWWINDOW
kw['startupinfo'] = startupinfo
try:
if 'stdout' not in kw:
kw['stdout'] = pproc.PIPE
kw['stderr'] = pproc.PIPE
proc = pproc.Popen(s,**kw)
(stdout, stderr) = proc.communicate()
Logs.info(stdout)
if stderr:
Logs.error(stderr)
return proc.returncode
else:
proc = pproc.Popen(s,**kw)
return proc.wait()
except OSError:
return -1
listdir = os.listdir
if is_win32:
def listdir_win32(s):
if re.match('^[A-Za-z]:$', s):
# os.path.isdir fails if s contains only the drive name... (x:)
s += os.sep
if not os.path.isdir(s):
e = OSError()
e.errno = errno.ENOENT
raise e
return os.listdir(s)
listdir = listdir_win32
def waf_version(mini = 0x010000, maxi = 0x100000):
"Halts if the waf version is wrong"
ver = HEXVERSION
try: min_val = mini + 0
except TypeError: min_val = int(mini.replace('.', '0'), 16)
if min_val > ver:
Logs.error("waf version should be at least %s (%s found)" % (mini, ver))
sys.exit(0)
try: max_val = maxi + 0
except TypeError: max_val = int(maxi.replace('.', '0'), 16)
if max_val < ver:
Logs.error("waf version should be at most %s (%s found)" % (maxi, ver))
sys.exit(0)
def python_24_guard():
if sys.hexversion < 0x20400f0 or sys.hexversion >= 0x3000000:
raise ImportError("Waf requires Python >= 2.3 but the raw source requires Python 2.4, 2.5 or 2.6")
def ex_stack():
exc_type, exc_value, tb = sys.exc_info()
if Logs.verbose > 1:
exc_lines = traceback.format_exception(exc_type, exc_value, tb)
return ''.join(exc_lines)
return str(exc_value)
def to_list(sth):
if isinstance(sth, str):
return sth.split()
else:
return sth
g_loaded_modules = {}
"index modules by absolute path"
g_module=None
"the main module is special"
def load_module(file_path, name=WSCRIPT_FILE):
"this function requires an absolute path"
try:
return g_loaded_modules[file_path]
except KeyError:
pass
module = imp.new_module(name)
try:
code = readf(file_path, m='rU')
except (IOError, OSError):
raise WscriptError('Could not read the file %r' % file_path)
module.waf_hash_val = code
sys.path.insert(0, os.path.dirname(file_path))
try:
exec(compile(code, file_path, 'exec'), module.__dict__)
except Exception:
exc_type, exc_value, tb = sys.exc_info()
raise WscriptError("".join(traceback.format_exception(exc_type, exc_value, tb)), file_path)
sys.path.pop(0)
g_loaded_modules[file_path] = module
return module
def set_main_module(file_path):
"Load custom options, if defined"
global g_module
g_module = load_module(file_path, 'wscript_main')
g_module.root_path = file_path
try:
g_module.APPNAME
except:
g_module.APPNAME = 'noname'
try:
g_module.VERSION
except:
g_module.VERSION = '1.0'
# note: to register the module globally, use the following:
# sys.modules['wscript_main'] = g_module
def to_hashtable(s):
"used for importing env files"
tbl = {}
lst = s.split('\n')
for line in lst:
if not line: continue
mems = line.split('=')
tbl[mems[0]] = mems[1]
return tbl
def get_term_cols():
"console width"
return 80
try:
import struct, fcntl, termios
except ImportError:
pass
else:
if Logs.got_tty:
def myfun():
dummy_lines, cols = struct.unpack("HHHH", \
fcntl.ioctl(sys.stderr.fileno(),termios.TIOCGWINSZ , \
struct.pack("HHHH", 0, 0, 0, 0)))[:2]
return cols
# we actually try the function once to see if it is suitable
try:
myfun()
except:
pass
else:
get_term_cols = myfun
rot_idx = 0
rot_chr = ['\\', '|', '/', '-']
"the rotation character in the progress bar"
def split_path(path):
return path.split('/')
def split_path_cygwin(path):
if path.startswith('//'):
ret = path.split('/')[2:]
ret[0] = '/' + ret[0]
return ret
return path.split('/')
re_sp = re.compile('[/\\\\]')
def split_path_win32(path):
if path.startswith('\\\\'):
ret = re.split(re_sp, path)[2:]
ret[0] = '\\' + ret[0]
return ret
return re.split(re_sp, path)
if sys.platform == 'cygwin':
split_path = split_path_cygwin
elif is_win32:
split_path = split_path_win32
def copy_attrs(orig, dest, names, only_if_set=False):
for a in to_list(names):
u = getattr(orig, a, ())
if u or not only_if_set:
setattr(dest, a, u)
def def_attrs(cls, **kw):
'''
set attributes for class.
@param cls [any class]: the class to update the given attributes in.
@param kw [dictionary]: dictionary of attributes names and values.
if the given class hasn't one (or more) of these attributes, add the attribute with its value to the class.
'''
for k, v in kw.iteritems():
if not hasattr(cls, k):
setattr(cls, k, v)
def quote_define_name(path):
fu = re.compile("[^a-zA-Z0-9]").sub("_", path)
fu = fu.upper()
return fu
def quote_whitespace(path):
return (path.strip().find(' ') > 0 and '"%s"' % path or path).replace('""', '"')
def trimquotes(s):
if not s: return ''
s = s.rstrip()
if s[0] == "'" and s[-1] == "'": return s[1:-1]
return s
def h_list(lst):
m = md5()
m.update(str(lst))
return m.digest()
def h_fun(fun):
try:
return fun.code
except AttributeError:
try:
h = inspect.getsource(fun)
except IOError:
h = "nocode"
try:
fun.code = h
except AttributeError:
pass
return h
def pprint(col, str, label='', sep=os.linesep):
"print messages in color"
sys.stderr.write("%s%s%s %s%s" % (Logs.colors(col), str, Logs.colors.NORMAL, label, sep))
def check_dir(dir):
"""If a folder doesn't exists, create it."""
try:
os.stat(dir)
except OSError:
try:
os.makedirs(dir)
except OSError, e:
raise WafError("Cannot create folder '%s' (original error: %s)" % (dir, e))
def cmd_output(cmd, **kw):
silent = False
if 'silent' in kw:
silent = kw['silent']
del(kw['silent'])
if 'e' in kw:
tmp = kw['e']
del(kw['e'])
kw['env'] = tmp
kw['shell'] = isinstance(cmd, str)
kw['stdout'] = pproc.PIPE
if silent:
kw['stderr'] = pproc.PIPE
try:
p = pproc.Popen(cmd, **kw)
output = p.communicate()[0]
except OSError, e:
raise ValueError(str(e))
if p.returncode:
if not silent:
msg = "command execution failed: %s -> %r" % (cmd, str(output))
raise ValueError(msg)
output = ''
return output
reg_subst = re.compile(r"(\\\\)|(\$\$)|\$\{([^}]+)\}")
def subst_vars(expr, params):
"substitute ${PREFIX}/bin in /usr/local/bin"
def repl_var(m):
if m.group(1):
return '\\'
if m.group(2):
return '$'
try:
# environments may contain lists
return params.get_flat(m.group(3))
except AttributeError:
return params[m.group(3)]
return reg_subst.sub(repl_var, expr)
def unversioned_sys_platform_to_binary_format(unversioned_sys_platform):
"infers the binary format from the unversioned_sys_platform name."
if unversioned_sys_platform in ('linux', 'freebsd', 'netbsd', 'openbsd', 'sunos'):
return 'elf'
elif unversioned_sys_platform == 'darwin':
return 'mac-o'
elif unversioned_sys_platform in ('win32', 'cygwin', 'uwin', 'msys'):
return 'pe'
# TODO we assume all other operating systems are elf, which is not true.
# we may set this to 'unknown' and have ccroot and other tools handle the case "gracefully" (whatever that means).
return 'elf'
def unversioned_sys_platform():
"""returns an unversioned name from sys.platform.
sys.plaform is not very well defined and depends directly on the python source tree.
The version appended to the names is unreliable as it's taken from the build environment at the time python was built,
i.e., it's possible to get freebsd7 on a freebsd8 system.
So we remove the version from the name, except for special cases where the os has a stupid name like os2 or win32.
Some possible values of sys.platform are, amongst others:
aix3 aix4 atheos beos5 darwin freebsd2 freebsd3 freebsd4 freebsd5 freebsd6 freebsd7
generic irix5 irix6 linux2 mac netbsd1 next3 os2emx riscos sunos5 unixware7
Investigating the python source tree may reveal more values.
"""
s = sys.platform
if s == 'java':
# The real OS is hidden under the JVM.
from java.lang import System
s = System.getProperty('os.name')
# see http://lopica.sourceforge.net/os.html for a list of possible values
if s == 'Mac OS X':
return 'darwin'
elif s.startswith('Windows '):
return 'win32'
elif s == 'OS/2':
return 'os2'
elif s == 'HP-UX':
return 'hpux'
elif s in ('SunOS', 'Solaris'):
return 'sunos'
else: s = s.lower()
if s == 'win32' or s.endswith('os2') and s != 'sunos2': return s
return re.split('\d+$', s)[0]
#@deprecated('use unversioned_sys_platform instead')
def detect_platform():
"""this function has been in the Utils module for some time.
It's hard to guess what people have used it for.
It seems its goal is to return an unversionned sys.platform, but it's not handling all platforms.
For example, the version is not removed on freebsd and netbsd, amongst others.
"""
s = sys.platform
# known POSIX
for x in 'cygwin linux irix sunos hpux aix darwin'.split():
# sys.platform may be linux2
if s.find(x) >= 0:
return x
# unknown POSIX
if os.name in 'posix java os2'.split():
return os.name
return s
def load_tool(tool, tooldir=None):
'''
load_tool: import a Python module, optionally using several directories.
@param tool [string]: name of tool to import.
@param tooldir [list]: directories to look for the tool.
@return: the loaded module.
Warning: this function is not thread-safe: plays with sys.path,
so must run in sequence.
'''
if tooldir:
assert isinstance(tooldir, list)
sys.path = tooldir + sys.path
try:
try:
return __import__(tool)
except ImportError, e:
Logs.error('Could not load the tool %r in %r:\n%s' % (tool, sys.path, e))
raise
finally:
if tooldir:
sys.path = sys.path[len(tooldir):]
def readf(fname, m='r'):
"get the contents of a file, it is not used anywhere for the moment"
f = open(fname, m)
try:
txt = f.read()
finally:
f.close()
return txt
def nada(*k, **kw):
"""A function that does nothing"""
pass
def diff_path(top, subdir):
"""difference between two absolute paths"""
top = os.path.normpath(top).replace('\\', '/').split('/')
subdir = os.path.normpath(subdir).replace('\\', '/').split('/')
if len(top) == len(subdir): return ''
diff = subdir[len(top) - len(subdir):]
return os.path.join(*diff)
class Context(object):
"""A base class for commands to be executed from Waf scripts"""
def set_curdir(self, dir):
self.curdir_ = dir
def get_curdir(self):
try:
return self.curdir_
except AttributeError:
self.curdir_ = os.getcwd()
return self.get_curdir()
curdir = property(get_curdir, set_curdir)
def recurse(self, dirs, name=''):
"""The function for calling scripts from folders, it tries to call wscript + function_name
and if that file does not exist, it will call the method 'function_name' from a file named wscript
the dirs can be a list of folders or a string containing space-separated folder paths
"""
if not name:
name = inspect.stack()[1][3]
if isinstance(dirs, str):
dirs = to_list(dirs)
for x in dirs:
if os.path.isabs(x):
nexdir = x
else:
nexdir = os.path.join(self.curdir, x)
base = os.path.join(nexdir, WSCRIPT_FILE)
file_path = base + '_' + name
try:
txt = readf(file_path, m='rU')
except (OSError, IOError):
try:
module = load_module(base)
except OSError:
raise WscriptError('No such script %s' % base)
try:
f = module.__dict__[name]
except KeyError:
raise WscriptError('No function %s defined in %s' % (name, base))
if getattr(self.__class__, 'pre_recurse', None):
self.pre_recurse(f, base, nexdir)
old = self.curdir
self.curdir = nexdir
try:
f(self)
finally:
self.curdir = old
if getattr(self.__class__, 'post_recurse', None):
self.post_recurse(module, base, nexdir)
else:
dc = {'ctx': self}
if getattr(self.__class__, 'pre_recurse', None):
dc = self.pre_recurse(txt, file_path, nexdir)
old = self.curdir
self.curdir = nexdir
try:
try:
exec(compile(txt, file_path, 'exec'), dc)
except Exception:
exc_type, exc_value, tb = sys.exc_info()
raise WscriptError("".join(traceback.format_exception(exc_type, exc_value, tb)), base)
finally:
self.curdir = old
if getattr(self.__class__, 'post_recurse', None):
self.post_recurse(txt, file_path, nexdir)
if is_win32:
old = shutil.copy2
def copy2(src, dst):
old(src, dst)
shutil.copystat(src, src)
setattr(shutil, 'copy2', copy2)
def zip_folder(dir, zip_file_name, prefix):
"""
prefix represents the app to add in the archive
"""
import zipfile
zip = zipfile.ZipFile(zip_file_name, 'w', compression=zipfile.ZIP_DEFLATED)
base = os.path.abspath(dir)
if prefix:
if prefix[-1] != os.sep:
prefix += os.sep
n = len(base)
for root, dirs, files in os.walk(base):
for f in files:
archive_name = prefix + root[n:] + os.sep + f
zip.write(root + os.sep + f, archive_name, zipfile.ZIP_DEFLATED)
zip.close()
def get_elapsed_time(start):
"Format a time delta (datetime.timedelta) using the format DdHhMmS.MSs"
delta = datetime.datetime.now() - start
# cast to int necessary for python 3.0
days = int(delta.days)
hours = int(delta.seconds / 3600)
minutes = int((delta.seconds - hours * 3600) / 60)
seconds = delta.seconds - hours * 3600 - minutes * 60 \
+ float(delta.microseconds) / 1000 / 1000
result = ''
if days:
result += '%dd' % days
if days or hours:
result += '%dh' % hours
if days or hours or minutes:
result += '%dm' % minutes
return '%s%.3fs' % (result, seconds)
if os.name == 'java':
# For Jython (they should really fix the inconsistency)
try:
gc.disable()
gc.enable()
except NotImplementedError:
gc.disable = gc.enable
|
if wscript_file:
self.wscript_file = wscript_file
self.wscript_line = None
else:
try:
(self.wscript_file, self.wscript_line) = self.locate_error()
except:
(self.wscript_file, self.wscript_line) = (None, None)
msg_file_line = ''
if self.wscript_file:
msg_file_line = "%s:" % self.wscript_file
if self.wscript_line:
msg_file_line += "%s:" % self.wscript_line
err_message = "%s error: %s" % (msg_file_line, message)
WafError.__init__(self, err_message)
|
identifier_body
|
Utils.py
|
#!/usr/bin/env python
# Meran - MERAN UNLP is a ILS (Integrated Library System) wich provides Catalog,
# Circulation and User's Management. It's written in Perl, and uses Apache2
# Web-Server, MySQL database and Sphinx 2 indexing.
# Copyright (C) 2009-2013 Grupo de desarrollo de Meran CeSPI-UNLP
#
# This file is part of Meran.
#
# Meran is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Meran is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Meran. If not, see <http://www.gnu.org/licenses/>.
# encoding: utf-8
# Meran - MERAN UNLP is a ILS (Integrated Library System) wich provides Catalog,
# Circulation and User's Management. It's written in Perl, and uses Apache2
# Web-Server, MySQL database and Sphinx 2 indexing.
# Copyright (C) 2009-2013 Grupo de desarrollo de Meran CeSPI-UNLP
#
# This file is part of Meran.
#
# Meran is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Meran is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Meran. If not, see <http://www.gnu.org/licenses/>.
# Thomas Nagy, 2005 (ita)
"""
Utilities, the stable ones are the following:
* h_file: compute a unique value for a file (hash), it uses
the module fnv if it is installed (see waf/utils/fnv & http://code.google.com/p/waf/wiki/FAQ)
else, md5 (see the python docs)
For large projects (projects with more than 15000 files) or slow hard disks and filesystems (HFS)
it is possible to use a hashing based on the path and the size (may give broken cache results)
The method h_file MUST raise an OSError if the file is a folder
import stat
def h_file(filename):
st = os.stat(filename)
if stat.S_ISDIR(st[stat.ST_MODE]): raise IOError('not a file')
m = Utils.md5()
m.update(str(st.st_mtime))
m.update(str(st.st_size))
m.update(filename)
return m.digest()
To replace the function in your project, use something like this:
import Utils
Utils.h_file = h_file
* h_list
* h_fun
* get_term_cols
* ordered_dict
"""
import os, sys, imp, string, errno, traceback, inspect, re, shutil, datetime, gc
# In python 3.0 we can get rid of all this
try: from UserDict import UserDict
except ImportError: from collections import UserDict
if sys.hexversion >= 0x2060000 or os.name == 'java':
import subprocess as pproc
else:
import pproc
import Logs
from Constants import *
try:
from collections import deque
except ImportError:
class deque(list):
def popleft(self):
return self.pop(0)
is_win32 = sys.platform == 'win32'
try:
# defaultdict in python 2.5
from collections import defaultdict as DefaultDict
except ImportError:
class DefaultDict(dict):
def __init__(self, default_factory):
super(DefaultDict, self).__init__()
self.default_factory = default_factory
def __getitem__(self, key):
try:
return super(DefaultDict, self).__getitem__(key)
except KeyError:
value = self.default_factory()
self[key] = value
return value
class WafError(Exception):
def __init__(self, *args):
self.args = args
try:
self.stack = traceback.extract_stack()
except:
pass
Exception.__init__(self, *args)
def __str__(self):
return str(len(self.args) == 1 and self.args[0] or self.args)
class WscriptError(WafError):
def __init__(self, message, wscript_file=None):
if wscript_file:
self.wscript_file = wscript_file
self.wscript_line = None
else:
try:
(self.wscript_file, self.wscript_line) = self.locate_error()
except:
(self.wscript_file, self.wscript_line) = (None, None)
msg_file_line = ''
if self.wscript_file:
msg_file_line = "%s:" % self.wscript_file
if self.wscript_line:
msg_file_line += "%s:" % self.wscript_line
err_message = "%s error: %s" % (msg_file_line, message)
WafError.__init__(self, err_message)
def locate_error(self):
stack = traceback.extract_stack()
stack.reverse()
for frame in stack:
file_name = os.path.basename(frame[0])
is_wscript = (file_name == WSCRIPT_FILE or file_name == WSCRIPT_BUILD_FILE)
if is_wscript:
return (frame[0], frame[1])
return (None, None)
indicator = is_win32 and '\x1b[A\x1b[K%s%s%s\r' or '\x1b[K%s%s%s\r'
try:
from fnv import new as md5
import Constants
Constants.SIG_NIL = 'signofnv'
def h_file(filename):
m = md5()
try:
m.hfile(filename)
x = m.digest()
if x is None: raise OSError("not a file")
return x
except SystemError:
raise OSError("not a file" + filename)
except ImportError:
try:
try:
from hashlib import md5
except ImportError:
from md5 import md5
def h_file(filename):
f = open(filename, 'rb')
m = md5()
while (filename):
filename = f.read(100000)
m.update(filename)
f.close()
return m.digest()
except ImportError:
# portability fixes may be added elsewhere (although, md5 should be everywhere by now)
md5 = None
class ordered_dict(UserDict):
def __init__(self, dict = None):
self.allkeys = []
UserDict.__init__(self, dict)
def __delitem__(self, key):
self.allkeys.remove(key)
UserDict.__delitem__(self, key)
def __setitem__(self, key, item):
if key not in self.allkeys: self.allkeys.append(key)
UserDict.__setitem__(self, key, item)
def exec_command(s, **kw):
if 'log' in kw:
kw['stdout'] = kw['stderr'] = kw['log']
del(kw['log'])
kw['shell'] = isinstance(s, str)
try:
proc = pproc.Popen(s, **kw)
return proc.wait()
except OSError:
return -1
if is_win32:
def exec_command(s, **kw):
if 'log' in kw:
kw['stdout'] = kw['stderr'] = kw['log']
del(kw['log'])
kw['shell'] = isinstance(s, str)
if len(s) > 2000:
startupinfo = pproc.STARTUPINFO()
startupinfo.dwFlags |= pproc.STARTF_USESHOWWINDOW
kw['startupinfo'] = startupinfo
try:
if 'stdout' not in kw:
kw['stdout'] = pproc.PIPE
kw['stderr'] = pproc.PIPE
proc = pproc.Popen(s,**kw)
(stdout, stderr) = proc.communicate()
Logs.info(stdout)
if stderr:
Logs.error(stderr)
return proc.returncode
else:
proc = pproc.Popen(s,**kw)
return proc.wait()
except OSError:
return -1
listdir = os.listdir
if is_win32:
def listdir_win32(s):
if re.match('^[A-Za-z]:$', s):
# os.path.isdir fails if s contains only the drive name... (x:)
s += os.sep
if not os.path.isdir(s):
e = OSError()
e.errno = errno.ENOENT
raise e
return os.listdir(s)
listdir = listdir_win32
def waf_version(mini = 0x010000, maxi = 0x100000):
"Halts if the waf version is wrong"
ver = HEXVERSION
try: min_val = mini + 0
except TypeError: min_val = int(mini.replace('.', '0'), 16)
if min_val > ver:
Logs.error("waf version should be at least %s (%s found)" % (mini, ver))
sys.exit(0)
try: max_val = maxi + 0
except TypeError: max_val = int(maxi.replace('.', '0'), 16)
if max_val < ver:
Logs.error("waf version should be at most %s (%s found)" % (maxi, ver))
sys.exit(0)
def python_24_guard():
if sys.hexversion < 0x20400f0 or sys.hexversion >= 0x3000000:
raise ImportError("Waf requires Python >= 2.3 but the raw source requires Python 2.4, 2.5 or 2.6")
def ex_stack():
exc_type, exc_value, tb = sys.exc_info()
if Logs.verbose > 1:
exc_lines = traceback.format_exception(exc_type, exc_value, tb)
return ''.join(exc_lines)
return str(exc_value)
def to_list(sth):
if isinstance(sth, str):
return sth.split()
else:
return sth
g_loaded_modules = {}
"index modules by absolute path"
g_module=None
"the main module is special"
def load_module(file_path, name=WSCRIPT_FILE):
"this function requires an absolute path"
try:
return g_loaded_modules[file_path]
except KeyError:
pass
module = imp.new_module(name)
try:
code = readf(file_path, m='rU')
except (IOError, OSError):
raise WscriptError('Could not read the file %r' % file_path)
module.waf_hash_val = code
sys.path.insert(0, os.path.dirname(file_path))
try:
exec(compile(code, file_path, 'exec'), module.__dict__)
except Exception:
exc_type, exc_value, tb = sys.exc_info()
raise WscriptError("".join(traceback.format_exception(exc_type, exc_value, tb)), file_path)
sys.path.pop(0)
g_loaded_modules[file_path] = module
return module
def set_main_module(file_path):
"Load custom options, if defined"
global g_module
g_module = load_module(file_path, 'wscript_main')
g_module.root_path = file_path
try:
g_module.APPNAME
except:
g_module.APPNAME = 'noname'
try:
g_module.VERSION
except:
g_module.VERSION = '1.0'
# note: to register the module globally, use the following:
# sys.modules['wscript_main'] = g_module
def to_hashtable(s):
"used for importing env files"
tbl = {}
lst = s.split('\n')
for line in lst:
if not line: continue
mems = line.split('=')
tbl[mems[0]] = mems[1]
return tbl
def get_term_cols():
"console width"
return 80
try:
import struct, fcntl, termios
except ImportError:
pass
else:
if Logs.got_tty:
def myfun():
dummy_lines, cols = struct.unpack("HHHH", \
fcntl.ioctl(sys.stderr.fileno(),termios.TIOCGWINSZ , \
struct.pack("HHHH", 0, 0, 0, 0)))[:2]
return cols
# we actually try the function once to see if it is suitable
try:
myfun()
except:
pass
else:
get_term_cols = myfun
rot_idx = 0
rot_chr = ['\\', '|', '/', '-']
"the rotation character in the progress bar"
def split_path(path):
return path.split('/')
def split_path_cygwin(path):
if path.startswith('//'):
ret = path.split('/')[2:]
ret[0] = '/' + ret[0]
return ret
return path.split('/')
re_sp = re.compile('[/\\\\]')
def split_path_win32(path):
if path.startswith('\\\\'):
ret = re.split(re_sp, path)[2:]
ret[0] = '\\' + ret[0]
return ret
return re.split(re_sp, path)
if sys.platform == 'cygwin':
split_path = split_path_cygwin
elif is_win32:
split_path = split_path_win32
def copy_attrs(orig, dest, names, only_if_set=False):
for a in to_list(names):
u = getattr(orig, a, ())
if u or not only_if_set:
setattr(dest, a, u)
def def_attrs(cls, **kw):
'''
set attributes for class.
@param cls [any class]: the class to update the given attributes in.
@param kw [dictionary]: dictionary of attributes names and values.
if the given class hasn't one (or more) of these attributes, add the attribute with its value to the class.
'''
for k, v in kw.iteritems():
if not hasattr(cls, k):
setattr(cls, k, v)
def quote_define_name(path):
fu = re.compile("[^a-zA-Z0-9]").sub("_", path)
fu = fu.upper()
return fu
def quote_whitespace(path):
return (path.strip().find(' ') > 0 and '"%s"' % path or path).replace('""', '"')
def trimquotes(s):
if not s: return ''
s = s.rstrip()
if s[0] == "'" and s[-1] == "'": return s[1:-1]
return s
def h_list(lst):
m = md5()
m.update(str(lst))
return m.digest()
def h_fun(fun):
try:
return fun.code
except AttributeError:
try:
h = inspect.getsource(fun)
except IOError:
h = "nocode"
try:
fun.code = h
except AttributeError:
pass
return h
def pprint(col, str, label='', sep=os.linesep):
"print messages in color"
sys.stderr.write("%s%s%s %s%s" % (Logs.colors(col), str, Logs.colors.NORMAL, label, sep))
def check_dir(dir):
"""If a folder doesn't exists, create it."""
try:
os.stat(dir)
except OSError:
try:
os.makedirs(dir)
except OSError, e:
raise WafError("Cannot create folder '%s' (original error: %s)" % (dir, e))
def cmd_output(cmd, **kw):
silent = False
if 'silent' in kw:
silent = kw['silent']
del(kw['silent'])
if 'e' in kw:
tmp = kw['e']
del(kw['e'])
kw['env'] = tmp
kw['shell'] = isinstance(cmd, str)
kw['stdout'] = pproc.PIPE
if silent:
|
try:
p = pproc.Popen(cmd, **kw)
output = p.communicate()[0]
except OSError, e:
raise ValueError(str(e))
if p.returncode:
if not silent:
msg = "command execution failed: %s -> %r" % (cmd, str(output))
raise ValueError(msg)
output = ''
return output
reg_subst = re.compile(r"(\\\\)|(\$\$)|\$\{([^}]+)\}")
def subst_vars(expr, params):
"substitute ${PREFIX}/bin in /usr/local/bin"
def repl_var(m):
if m.group(1):
return '\\'
if m.group(2):
return '$'
try:
# environments may contain lists
return params.get_flat(m.group(3))
except AttributeError:
return params[m.group(3)]
return reg_subst.sub(repl_var, expr)
def unversioned_sys_platform_to_binary_format(unversioned_sys_platform):
"infers the binary format from the unversioned_sys_platform name."
if unversioned_sys_platform in ('linux', 'freebsd', 'netbsd', 'openbsd', 'sunos'):
return 'elf'
elif unversioned_sys_platform == 'darwin':
return 'mac-o'
elif unversioned_sys_platform in ('win32', 'cygwin', 'uwin', 'msys'):
return 'pe'
# TODO we assume all other operating systems are elf, which is not true.
# we may set this to 'unknown' and have ccroot and other tools handle the case "gracefully" (whatever that means).
return 'elf'
def unversioned_sys_platform():
"""returns an unversioned name from sys.platform.
sys.plaform is not very well defined and depends directly on the python source tree.
The version appended to the names is unreliable as it's taken from the build environment at the time python was built,
i.e., it's possible to get freebsd7 on a freebsd8 system.
So we remove the version from the name, except for special cases where the os has a stupid name like os2 or win32.
Some possible values of sys.platform are, amongst others:
aix3 aix4 atheos beos5 darwin freebsd2 freebsd3 freebsd4 freebsd5 freebsd6 freebsd7
generic irix5 irix6 linux2 mac netbsd1 next3 os2emx riscos sunos5 unixware7
Investigating the python source tree may reveal more values.
"""
s = sys.platform
if s == 'java':
# The real OS is hidden under the JVM.
from java.lang import System
s = System.getProperty('os.name')
# see http://lopica.sourceforge.net/os.html for a list of possible values
if s == 'Mac OS X':
return 'darwin'
elif s.startswith('Windows '):
return 'win32'
elif s == 'OS/2':
return 'os2'
elif s == 'HP-UX':
return 'hpux'
elif s in ('SunOS', 'Solaris'):
return 'sunos'
else: s = s.lower()
if s == 'win32' or s.endswith('os2') and s != 'sunos2': return s
return re.split('\d+$', s)[0]
#@deprecated('use unversioned_sys_platform instead')
def detect_platform():
"""this function has been in the Utils module for some time.
It's hard to guess what people have used it for.
It seems its goal is to return an unversionned sys.platform, but it's not handling all platforms.
For example, the version is not removed on freebsd and netbsd, amongst others.
"""
s = sys.platform
# known POSIX
for x in 'cygwin linux irix sunos hpux aix darwin'.split():
# sys.platform may be linux2
if s.find(x) >= 0:
return x
# unknown POSIX
if os.name in 'posix java os2'.split():
return os.name
return s
def load_tool(tool, tooldir=None):
'''
load_tool: import a Python module, optionally using several directories.
@param tool [string]: name of tool to import.
@param tooldir [list]: directories to look for the tool.
@return: the loaded module.
Warning: this function is not thread-safe: plays with sys.path,
so must run in sequence.
'''
if tooldir:
assert isinstance(tooldir, list)
sys.path = tooldir + sys.path
try:
try:
return __import__(tool)
except ImportError, e:
Logs.error('Could not load the tool %r in %r:\n%s' % (tool, sys.path, e))
raise
finally:
if tooldir:
sys.path = sys.path[len(tooldir):]
def readf(fname, m='r'):
"get the contents of a file, it is not used anywhere for the moment"
f = open(fname, m)
try:
txt = f.read()
finally:
f.close()
return txt
def nada(*k, **kw):
"""A function that does nothing"""
pass
def diff_path(top, subdir):
"""difference between two absolute paths"""
top = os.path.normpath(top).replace('\\', '/').split('/')
subdir = os.path.normpath(subdir).replace('\\', '/').split('/')
if len(top) == len(subdir): return ''
diff = subdir[len(top) - len(subdir):]
return os.path.join(*diff)
class Context(object):
"""A base class for commands to be executed from Waf scripts"""
def set_curdir(self, dir):
self.curdir_ = dir
def get_curdir(self):
try:
return self.curdir_
except AttributeError:
self.curdir_ = os.getcwd()
return self.get_curdir()
curdir = property(get_curdir, set_curdir)
def recurse(self, dirs, name=''):
"""The function for calling scripts from folders, it tries to call wscript + function_name
and if that file does not exist, it will call the method 'function_name' from a file named wscript
the dirs can be a list of folders or a string containing space-separated folder paths
"""
if not name:
name = inspect.stack()[1][3]
if isinstance(dirs, str):
dirs = to_list(dirs)
for x in dirs:
if os.path.isabs(x):
nexdir = x
else:
nexdir = os.path.join(self.curdir, x)
base = os.path.join(nexdir, WSCRIPT_FILE)
file_path = base + '_' + name
try:
txt = readf(file_path, m='rU')
except (OSError, IOError):
try:
module = load_module(base)
except OSError:
raise WscriptError('No such script %s' % base)
try:
f = module.__dict__[name]
except KeyError:
raise WscriptError('No function %s defined in %s' % (name, base))
if getattr(self.__class__, 'pre_recurse', None):
self.pre_recurse(f, base, nexdir)
old = self.curdir
self.curdir = nexdir
try:
f(self)
finally:
self.curdir = old
if getattr(self.__class__, 'post_recurse', None):
self.post_recurse(module, base, nexdir)
else:
dc = {'ctx': self}
if getattr(self.__class__, 'pre_recurse', None):
dc = self.pre_recurse(txt, file_path, nexdir)
old = self.curdir
self.curdir = nexdir
try:
try:
exec(compile(txt, file_path, 'exec'), dc)
except Exception:
exc_type, exc_value, tb = sys.exc_info()
raise WscriptError("".join(traceback.format_exception(exc_type, exc_value, tb)), base)
finally:
self.curdir = old
if getattr(self.__class__, 'post_recurse', None):
self.post_recurse(txt, file_path, nexdir)
if is_win32:
old = shutil.copy2
def copy2(src, dst):
old(src, dst)
shutil.copystat(src, src)
setattr(shutil, 'copy2', copy2)
def zip_folder(dir, zip_file_name, prefix):
"""
prefix represents the app to add in the archive
"""
import zipfile
zip = zipfile.ZipFile(zip_file_name, 'w', compression=zipfile.ZIP_DEFLATED)
base = os.path.abspath(dir)
if prefix:
if prefix[-1] != os.sep:
prefix += os.sep
n = len(base)
for root, dirs, files in os.walk(base):
for f in files:
archive_name = prefix + root[n:] + os.sep + f
zip.write(root + os.sep + f, archive_name, zipfile.ZIP_DEFLATED)
zip.close()
def get_elapsed_time(start):
"Format a time delta (datetime.timedelta) using the format DdHhMmS.MSs"
delta = datetime.datetime.now() - start
# cast to int necessary for python 3.0
days = int(delta.days)
hours = int(delta.seconds / 3600)
minutes = int((delta.seconds - hours * 3600) / 60)
seconds = delta.seconds - hours * 3600 - minutes * 60 \
+ float(delta.microseconds) / 1000 / 1000
result = ''
if days:
result += '%dd' % days
if days or hours:
result += '%dh' % hours
if days or hours or minutes:
result += '%dm' % minutes
return '%s%.3fs' % (result, seconds)
if os.name == 'java':
# For Jython (they should really fix the inconsistency)
try:
gc.disable()
gc.enable()
except NotImplementedError:
gc.disable = gc.enable
|
kw['stderr'] = pproc.PIPE
|
conditional_block
|
Utils.py
|
#!/usr/bin/env python
# Meran - MERAN UNLP is a ILS (Integrated Library System) wich provides Catalog,
# Circulation and User's Management. It's written in Perl, and uses Apache2
# Web-Server, MySQL database and Sphinx 2 indexing.
# Copyright (C) 2009-2013 Grupo de desarrollo de Meran CeSPI-UNLP
#
# This file is part of Meran.
#
# Meran is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Meran is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Meran. If not, see <http://www.gnu.org/licenses/>.
# encoding: utf-8
# Meran - MERAN UNLP is a ILS (Integrated Library System) wich provides Catalog,
# Circulation and User's Management. It's written in Perl, and uses Apache2
# Web-Server, MySQL database and Sphinx 2 indexing.
# Copyright (C) 2009-2013 Grupo de desarrollo de Meran CeSPI-UNLP
#
# This file is part of Meran.
#
# Meran is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Meran is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Meran. If not, see <http://www.gnu.org/licenses/>.
# Thomas Nagy, 2005 (ita)
"""
Utilities, the stable ones are the following:
* h_file: compute a unique value for a file (hash), it uses
the module fnv if it is installed (see waf/utils/fnv & http://code.google.com/p/waf/wiki/FAQ)
else, md5 (see the python docs)
For large projects (projects with more than 15000 files) or slow hard disks and filesystems (HFS)
it is possible to use a hashing based on the path and the size (may give broken cache results)
The method h_file MUST raise an OSError if the file is a folder
import stat
def h_file(filename):
st = os.stat(filename)
if stat.S_ISDIR(st[stat.ST_MODE]): raise IOError('not a file')
m = Utils.md5()
m.update(str(st.st_mtime))
m.update(str(st.st_size))
m.update(filename)
return m.digest()
To replace the function in your project, use something like this:
import Utils
Utils.h_file = h_file
* h_list
* h_fun
* get_term_cols
* ordered_dict
"""
import os, sys, imp, string, errno, traceback, inspect, re, shutil, datetime, gc
# In python 3.0 we can get rid of all this
try: from UserDict import UserDict
except ImportError: from collections import UserDict
if sys.hexversion >= 0x2060000 or os.name == 'java':
import subprocess as pproc
else:
import pproc
import Logs
from Constants import *
try:
from collections import deque
except ImportError:
class deque(list):
def popleft(self):
return self.pop(0)
is_win32 = sys.platform == 'win32'
try:
# defaultdict in python 2.5
from collections import defaultdict as DefaultDict
except ImportError:
class DefaultDict(dict):
def __init__(self, default_factory):
super(DefaultDict, self).__init__()
self.default_factory = default_factory
def __getitem__(self, key):
try:
return super(DefaultDict, self).__getitem__(key)
except KeyError:
value = self.default_factory()
self[key] = value
return value
class WafError(Exception):
def __init__(self, *args):
self.args = args
try:
self.stack = traceback.extract_stack()
except:
pass
Exception.__init__(self, *args)
def __str__(self):
return str(len(self.args) == 1 and self.args[0] or self.args)
class WscriptError(WafError):
def __init__(self, message, wscript_file=None):
if wscript_file:
self.wscript_file = wscript_file
self.wscript_line = None
else:
try:
(self.wscript_file, self.wscript_line) = self.locate_error()
except:
(self.wscript_file, self.wscript_line) = (None, None)
msg_file_line = ''
if self.wscript_file:
msg_file_line = "%s:" % self.wscript_file
if self.wscript_line:
msg_file_line += "%s:" % self.wscript_line
err_message = "%s error: %s" % (msg_file_line, message)
WafError.__init__(self, err_message)
def locate_error(self):
stack = traceback.extract_stack()
stack.reverse()
for frame in stack:
file_name = os.path.basename(frame[0])
is_wscript = (file_name == WSCRIPT_FILE or file_name == WSCRIPT_BUILD_FILE)
if is_wscript:
return (frame[0], frame[1])
return (None, None)
indicator = is_win32 and '\x1b[A\x1b[K%s%s%s\r' or '\x1b[K%s%s%s\r'
try:
from fnv import new as md5
import Constants
Constants.SIG_NIL = 'signofnv'
def h_file(filename):
m = md5()
try:
m.hfile(filename)
x = m.digest()
if x is None: raise OSError("not a file")
return x
except SystemError:
raise OSError("not a file" + filename)
except ImportError:
try:
try:
from hashlib import md5
except ImportError:
from md5 import md5
def h_file(filename):
f = open(filename, 'rb')
m = md5()
while (filename):
filename = f.read(100000)
m.update(filename)
f.close()
return m.digest()
except ImportError:
# portability fixes may be added elsewhere (although, md5 should be everywhere by now)
md5 = None
class ordered_dict(UserDict):
def __init__(self, dict = None):
self.allkeys = []
UserDict.__init__(self, dict)
def __delitem__(self, key):
self.allkeys.remove(key)
UserDict.__delitem__(self, key)
def __setitem__(self, key, item):
if key not in self.allkeys: self.allkeys.append(key)
UserDict.__setitem__(self, key, item)
def exec_command(s, **kw):
if 'log' in kw:
kw['stdout'] = kw['stderr'] = kw['log']
del(kw['log'])
kw['shell'] = isinstance(s, str)
try:
proc = pproc.Popen(s, **kw)
return proc.wait()
except OSError:
return -1
if is_win32:
def exec_command(s, **kw):
if 'log' in kw:
kw['stdout'] = kw['stderr'] = kw['log']
del(kw['log'])
kw['shell'] = isinstance(s, str)
if len(s) > 2000:
startupinfo = pproc.STARTUPINFO()
startupinfo.dwFlags |= pproc.STARTF_USESHOWWINDOW
kw['startupinfo'] = startupinfo
try:
if 'stdout' not in kw:
kw['stdout'] = pproc.PIPE
kw['stderr'] = pproc.PIPE
proc = pproc.Popen(s,**kw)
(stdout, stderr) = proc.communicate()
Logs.info(stdout)
if stderr:
Logs.error(stderr)
return proc.returncode
else:
proc = pproc.Popen(s,**kw)
return proc.wait()
except OSError:
return -1
listdir = os.listdir
if is_win32:
def listdir_win32(s):
if re.match('^[A-Za-z]:$', s):
# os.path.isdir fails if s contains only the drive name... (x:)
s += os.sep
if not os.path.isdir(s):
e = OSError()
e.errno = errno.ENOENT
raise e
return os.listdir(s)
listdir = listdir_win32
def waf_version(mini = 0x010000, maxi = 0x100000):
"Halts if the waf version is wrong"
ver = HEXVERSION
try: min_val = mini + 0
except TypeError: min_val = int(mini.replace('.', '0'), 16)
if min_val > ver:
Logs.error("waf version should be at least %s (%s found)" % (mini, ver))
sys.exit(0)
try: max_val = maxi + 0
except TypeError: max_val = int(maxi.replace('.', '0'), 16)
if max_val < ver:
Logs.error("waf version should be at most %s (%s found)" % (maxi, ver))
sys.exit(0)
def python_24_guard():
if sys.hexversion < 0x20400f0 or sys.hexversion >= 0x3000000:
raise ImportError("Waf requires Python >= 2.3 but the raw source requires Python 2.4, 2.5 or 2.6")
def ex_stack():
exc_type, exc_value, tb = sys.exc_info()
if Logs.verbose > 1:
exc_lines = traceback.format_exception(exc_type, exc_value, tb)
return ''.join(exc_lines)
return str(exc_value)
def to_list(sth):
if isinstance(sth, str):
return sth.split()
else:
return sth
g_loaded_modules = {}
"index modules by absolute path"
g_module=None
"the main module is special"
def load_module(file_path, name=WSCRIPT_FILE):
"this function requires an absolute path"
try:
return g_loaded_modules[file_path]
except KeyError:
pass
module = imp.new_module(name)
try:
code = readf(file_path, m='rU')
except (IOError, OSError):
raise WscriptError('Could not read the file %r' % file_path)
module.waf_hash_val = code
sys.path.insert(0, os.path.dirname(file_path))
try:
exec(compile(code, file_path, 'exec'), module.__dict__)
except Exception:
exc_type, exc_value, tb = sys.exc_info()
raise WscriptError("".join(traceback.format_exception(exc_type, exc_value, tb)), file_path)
sys.path.pop(0)
g_loaded_modules[file_path] = module
return module
def set_main_module(file_path):
"Load custom options, if defined"
global g_module
g_module = load_module(file_path, 'wscript_main')
g_module.root_path = file_path
try:
g_module.APPNAME
except:
g_module.APPNAME = 'noname'
try:
g_module.VERSION
except:
g_module.VERSION = '1.0'
# note: to register the module globally, use the following:
# sys.modules['wscript_main'] = g_module
def to_hashtable(s):
"used for importing env files"
tbl = {}
lst = s.split('\n')
for line in lst:
if not line: continue
mems = line.split('=')
tbl[mems[0]] = mems[1]
return tbl
def get_term_cols():
"console width"
return 80
try:
import struct, fcntl, termios
except ImportError:
pass
else:
if Logs.got_tty:
def myfun():
dummy_lines, cols = struct.unpack("HHHH", \
fcntl.ioctl(sys.stderr.fileno(),termios.TIOCGWINSZ , \
struct.pack("HHHH", 0, 0, 0, 0)))[:2]
return cols
# we actually try the function once to see if it is suitable
try:
myfun()
except:
pass
else:
get_term_cols = myfun
rot_idx = 0
rot_chr = ['\\', '|', '/', '-']
"the rotation character in the progress bar"
def split_path(path):
return path.split('/')
def split_path_cygwin(path):
if path.startswith('//'):
ret = path.split('/')[2:]
ret[0] = '/' + ret[0]
return ret
return path.split('/')
re_sp = re.compile('[/\\\\]')
def split_path_win32(path):
if path.startswith('\\\\'):
ret = re.split(re_sp, path)[2:]
ret[0] = '\\' + ret[0]
return ret
return re.split(re_sp, path)
if sys.platform == 'cygwin':
split_path = split_path_cygwin
elif is_win32:
split_path = split_path_win32
def copy_attrs(orig, dest, names, only_if_set=False):
for a in to_list(names):
u = getattr(orig, a, ())
if u or not only_if_set:
setattr(dest, a, u)
def def_attrs(cls, **kw):
'''
set attributes for class.
@param cls [any class]: the class to update the given attributes in.
@param kw [dictionary]: dictionary of attributes names and values.
if the given class hasn't one (or more) of these attributes, add the attribute with its value to the class.
'''
for k, v in kw.iteritems():
if not hasattr(cls, k):
setattr(cls, k, v)
def quote_define_name(path):
fu = re.compile("[^a-zA-Z0-9]").sub("_", path)
fu = fu.upper()
return fu
def
|
(path):
return (path.strip().find(' ') > 0 and '"%s"' % path or path).replace('""', '"')
def trimquotes(s):
if not s: return ''
s = s.rstrip()
if s[0] == "'" and s[-1] == "'": return s[1:-1]
return s
def h_list(lst):
m = md5()
m.update(str(lst))
return m.digest()
def h_fun(fun):
try:
return fun.code
except AttributeError:
try:
h = inspect.getsource(fun)
except IOError:
h = "nocode"
try:
fun.code = h
except AttributeError:
pass
return h
def pprint(col, str, label='', sep=os.linesep):
"print messages in color"
sys.stderr.write("%s%s%s %s%s" % (Logs.colors(col), str, Logs.colors.NORMAL, label, sep))
def check_dir(dir):
"""If a folder doesn't exists, create it."""
try:
os.stat(dir)
except OSError:
try:
os.makedirs(dir)
except OSError, e:
raise WafError("Cannot create folder '%s' (original error: %s)" % (dir, e))
def cmd_output(cmd, **kw):
silent = False
if 'silent' in kw:
silent = kw['silent']
del(kw['silent'])
if 'e' in kw:
tmp = kw['e']
del(kw['e'])
kw['env'] = tmp
kw['shell'] = isinstance(cmd, str)
kw['stdout'] = pproc.PIPE
if silent:
kw['stderr'] = pproc.PIPE
try:
p = pproc.Popen(cmd, **kw)
output = p.communicate()[0]
except OSError, e:
raise ValueError(str(e))
if p.returncode:
if not silent:
msg = "command execution failed: %s -> %r" % (cmd, str(output))
raise ValueError(msg)
output = ''
return output
reg_subst = re.compile(r"(\\\\)|(\$\$)|\$\{([^}]+)\}")
def subst_vars(expr, params):
"substitute ${PREFIX}/bin in /usr/local/bin"
def repl_var(m):
if m.group(1):
return '\\'
if m.group(2):
return '$'
try:
# environments may contain lists
return params.get_flat(m.group(3))
except AttributeError:
return params[m.group(3)]
return reg_subst.sub(repl_var, expr)
def unversioned_sys_platform_to_binary_format(unversioned_sys_platform):
"infers the binary format from the unversioned_sys_platform name."
if unversioned_sys_platform in ('linux', 'freebsd', 'netbsd', 'openbsd', 'sunos'):
return 'elf'
elif unversioned_sys_platform == 'darwin':
return 'mac-o'
elif unversioned_sys_platform in ('win32', 'cygwin', 'uwin', 'msys'):
return 'pe'
# TODO we assume all other operating systems are elf, which is not true.
# we may set this to 'unknown' and have ccroot and other tools handle the case "gracefully" (whatever that means).
return 'elf'
def unversioned_sys_platform():
"""returns an unversioned name from sys.platform.
sys.plaform is not very well defined and depends directly on the python source tree.
The version appended to the names is unreliable as it's taken from the build environment at the time python was built,
i.e., it's possible to get freebsd7 on a freebsd8 system.
So we remove the version from the name, except for special cases where the os has a stupid name like os2 or win32.
Some possible values of sys.platform are, amongst others:
aix3 aix4 atheos beos5 darwin freebsd2 freebsd3 freebsd4 freebsd5 freebsd6 freebsd7
generic irix5 irix6 linux2 mac netbsd1 next3 os2emx riscos sunos5 unixware7
Investigating the python source tree may reveal more values.
"""
s = sys.platform
if s == 'java':
# The real OS is hidden under the JVM.
from java.lang import System
s = System.getProperty('os.name')
# see http://lopica.sourceforge.net/os.html for a list of possible values
if s == 'Mac OS X':
return 'darwin'
elif s.startswith('Windows '):
return 'win32'
elif s == 'OS/2':
return 'os2'
elif s == 'HP-UX':
return 'hpux'
elif s in ('SunOS', 'Solaris'):
return 'sunos'
else: s = s.lower()
if s == 'win32' or s.endswith('os2') and s != 'sunos2': return s
return re.split('\d+$', s)[0]
#@deprecated('use unversioned_sys_platform instead')
def detect_platform():
"""this function has been in the Utils module for some time.
It's hard to guess what people have used it for.
It seems its goal is to return an unversionned sys.platform, but it's not handling all platforms.
For example, the version is not removed on freebsd and netbsd, amongst others.
"""
s = sys.platform
# known POSIX
for x in 'cygwin linux irix sunos hpux aix darwin'.split():
# sys.platform may be linux2
if s.find(x) >= 0:
return x
# unknown POSIX
if os.name in 'posix java os2'.split():
return os.name
return s
def load_tool(tool, tooldir=None):
'''
load_tool: import a Python module, optionally using several directories.
@param tool [string]: name of tool to import.
@param tooldir [list]: directories to look for the tool.
@return: the loaded module.
Warning: this function is not thread-safe: plays with sys.path,
so must run in sequence.
'''
if tooldir:
assert isinstance(tooldir, list)
sys.path = tooldir + sys.path
try:
try:
return __import__(tool)
except ImportError, e:
Logs.error('Could not load the tool %r in %r:\n%s' % (tool, sys.path, e))
raise
finally:
if tooldir:
sys.path = sys.path[len(tooldir):]
def readf(fname, m='r'):
"get the contents of a file, it is not used anywhere for the moment"
f = open(fname, m)
try:
txt = f.read()
finally:
f.close()
return txt
def nada(*k, **kw):
"""A function that does nothing"""
pass
def diff_path(top, subdir):
"""difference between two absolute paths"""
top = os.path.normpath(top).replace('\\', '/').split('/')
subdir = os.path.normpath(subdir).replace('\\', '/').split('/')
if len(top) == len(subdir): return ''
diff = subdir[len(top) - len(subdir):]
return os.path.join(*diff)
class Context(object):
"""A base class for commands to be executed from Waf scripts"""
def set_curdir(self, dir):
self.curdir_ = dir
def get_curdir(self):
try:
return self.curdir_
except AttributeError:
self.curdir_ = os.getcwd()
return self.get_curdir()
curdir = property(get_curdir, set_curdir)
def recurse(self, dirs, name=''):
"""The function for calling scripts from folders, it tries to call wscript + function_name
and if that file does not exist, it will call the method 'function_name' from a file named wscript
the dirs can be a list of folders or a string containing space-separated folder paths
"""
if not name:
name = inspect.stack()[1][3]
if isinstance(dirs, str):
dirs = to_list(dirs)
for x in dirs:
if os.path.isabs(x):
nexdir = x
else:
nexdir = os.path.join(self.curdir, x)
base = os.path.join(nexdir, WSCRIPT_FILE)
file_path = base + '_' + name
try:
txt = readf(file_path, m='rU')
except (OSError, IOError):
try:
module = load_module(base)
except OSError:
raise WscriptError('No such script %s' % base)
try:
f = module.__dict__[name]
except KeyError:
raise WscriptError('No function %s defined in %s' % (name, base))
if getattr(self.__class__, 'pre_recurse', None):
self.pre_recurse(f, base, nexdir)
old = self.curdir
self.curdir = nexdir
try:
f(self)
finally:
self.curdir = old
if getattr(self.__class__, 'post_recurse', None):
self.post_recurse(module, base, nexdir)
else:
dc = {'ctx': self}
if getattr(self.__class__, 'pre_recurse', None):
dc = self.pre_recurse(txt, file_path, nexdir)
old = self.curdir
self.curdir = nexdir
try:
try:
exec(compile(txt, file_path, 'exec'), dc)
except Exception:
exc_type, exc_value, tb = sys.exc_info()
raise WscriptError("".join(traceback.format_exception(exc_type, exc_value, tb)), base)
finally:
self.curdir = old
if getattr(self.__class__, 'post_recurse', None):
self.post_recurse(txt, file_path, nexdir)
if is_win32:
old = shutil.copy2
def copy2(src, dst):
old(src, dst)
shutil.copystat(src, src)
setattr(shutil, 'copy2', copy2)
def zip_folder(dir, zip_file_name, prefix):
"""
prefix represents the app to add in the archive
"""
import zipfile
zip = zipfile.ZipFile(zip_file_name, 'w', compression=zipfile.ZIP_DEFLATED)
base = os.path.abspath(dir)
if prefix:
if prefix[-1] != os.sep:
prefix += os.sep
n = len(base)
for root, dirs, files in os.walk(base):
for f in files:
archive_name = prefix + root[n:] + os.sep + f
zip.write(root + os.sep + f, archive_name, zipfile.ZIP_DEFLATED)
zip.close()
def get_elapsed_time(start):
"Format a time delta (datetime.timedelta) using the format DdHhMmS.MSs"
delta = datetime.datetime.now() - start
# cast to int necessary for python 3.0
days = int(delta.days)
hours = int(delta.seconds / 3600)
minutes = int((delta.seconds - hours * 3600) / 60)
seconds = delta.seconds - hours * 3600 - minutes * 60 \
+ float(delta.microseconds) / 1000 / 1000
result = ''
if days:
result += '%dd' % days
if days or hours:
result += '%dh' % hours
if days or hours or minutes:
result += '%dm' % minutes
return '%s%.3fs' % (result, seconds)
if os.name == 'java':
# For Jython (they should really fix the inconsistency)
try:
gc.disable()
gc.enable()
except NotImplementedError:
gc.disable = gc.enable
|
quote_whitespace
|
identifier_name
|
Utils.py
|
#!/usr/bin/env python
# Meran - MERAN UNLP is a ILS (Integrated Library System) wich provides Catalog,
# Circulation and User's Management. It's written in Perl, and uses Apache2
# Web-Server, MySQL database and Sphinx 2 indexing.
# Copyright (C) 2009-2013 Grupo de desarrollo de Meran CeSPI-UNLP
#
# This file is part of Meran.
#
# Meran is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Meran is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Meran. If not, see <http://www.gnu.org/licenses/>.
# encoding: utf-8
# Meran - MERAN UNLP is a ILS (Integrated Library System) wich provides Catalog,
# Circulation and User's Management. It's written in Perl, and uses Apache2
# Web-Server, MySQL database and Sphinx 2 indexing.
# Copyright (C) 2009-2013 Grupo de desarrollo de Meran CeSPI-UNLP
#
# This file is part of Meran.
#
# Meran is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Meran is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Meran. If not, see <http://www.gnu.org/licenses/>.
# Thomas Nagy, 2005 (ita)
"""
Utilities, the stable ones are the following:
* h_file: compute a unique value for a file (hash), it uses
the module fnv if it is installed (see waf/utils/fnv & http://code.google.com/p/waf/wiki/FAQ)
else, md5 (see the python docs)
For large projects (projects with more than 15000 files) or slow hard disks and filesystems (HFS)
it is possible to use a hashing based on the path and the size (may give broken cache results)
The method h_file MUST raise an OSError if the file is a folder
import stat
def h_file(filename):
st = os.stat(filename)
if stat.S_ISDIR(st[stat.ST_MODE]): raise IOError('not a file')
m = Utils.md5()
m.update(str(st.st_mtime))
m.update(str(st.st_size))
m.update(filename)
return m.digest()
To replace the function in your project, use something like this:
import Utils
Utils.h_file = h_file
* h_list
* h_fun
* get_term_cols
* ordered_dict
"""
import os, sys, imp, string, errno, traceback, inspect, re, shutil, datetime, gc
# In python 3.0 we can get rid of all this
try: from UserDict import UserDict
except ImportError: from collections import UserDict
if sys.hexversion >= 0x2060000 or os.name == 'java':
import subprocess as pproc
else:
import pproc
import Logs
from Constants import *
try:
from collections import deque
except ImportError:
class deque(list):
def popleft(self):
return self.pop(0)
is_win32 = sys.platform == 'win32'
try:
# defaultdict in python 2.5
from collections import defaultdict as DefaultDict
except ImportError:
class DefaultDict(dict):
def __init__(self, default_factory):
super(DefaultDict, self).__init__()
self.default_factory = default_factory
def __getitem__(self, key):
try:
return super(DefaultDict, self).__getitem__(key)
except KeyError:
value = self.default_factory()
self[key] = value
return value
class WafError(Exception):
def __init__(self, *args):
self.args = args
try:
self.stack = traceback.extract_stack()
except:
pass
Exception.__init__(self, *args)
def __str__(self):
return str(len(self.args) == 1 and self.args[0] or self.args)
class WscriptError(WafError):
def __init__(self, message, wscript_file=None):
if wscript_file:
self.wscript_file = wscript_file
self.wscript_line = None
else:
try:
(self.wscript_file, self.wscript_line) = self.locate_error()
except:
(self.wscript_file, self.wscript_line) = (None, None)
msg_file_line = ''
if self.wscript_file:
msg_file_line = "%s:" % self.wscript_file
if self.wscript_line:
msg_file_line += "%s:" % self.wscript_line
err_message = "%s error: %s" % (msg_file_line, message)
WafError.__init__(self, err_message)
def locate_error(self):
stack = traceback.extract_stack()
stack.reverse()
for frame in stack:
file_name = os.path.basename(frame[0])
is_wscript = (file_name == WSCRIPT_FILE or file_name == WSCRIPT_BUILD_FILE)
if is_wscript:
return (frame[0], frame[1])
return (None, None)
indicator = is_win32 and '\x1b[A\x1b[K%s%s%s\r' or '\x1b[K%s%s%s\r'
try:
from fnv import new as md5
import Constants
Constants.SIG_NIL = 'signofnv'
def h_file(filename):
m = md5()
try:
m.hfile(filename)
x = m.digest()
if x is None: raise OSError("not a file")
return x
except SystemError:
raise OSError("not a file" + filename)
except ImportError:
try:
try:
from hashlib import md5
except ImportError:
from md5 import md5
def h_file(filename):
f = open(filename, 'rb')
m = md5()
while (filename):
filename = f.read(100000)
m.update(filename)
f.close()
return m.digest()
except ImportError:
# portability fixes may be added elsewhere (although, md5 should be everywhere by now)
md5 = None
class ordered_dict(UserDict):
def __init__(self, dict = None):
self.allkeys = []
UserDict.__init__(self, dict)
def __delitem__(self, key):
self.allkeys.remove(key)
UserDict.__delitem__(self, key)
def __setitem__(self, key, item):
|
kw['stdout'] = kw['stderr'] = kw['log']
del(kw['log'])
kw['shell'] = isinstance(s, str)
try:
proc = pproc.Popen(s, **kw)
return proc.wait()
except OSError:
return -1
if is_win32:
def exec_command(s, **kw):
if 'log' in kw:
kw['stdout'] = kw['stderr'] = kw['log']
del(kw['log'])
kw['shell'] = isinstance(s, str)
if len(s) > 2000:
startupinfo = pproc.STARTUPINFO()
startupinfo.dwFlags |= pproc.STARTF_USESHOWWINDOW
kw['startupinfo'] = startupinfo
try:
if 'stdout' not in kw:
kw['stdout'] = pproc.PIPE
kw['stderr'] = pproc.PIPE
proc = pproc.Popen(s,**kw)
(stdout, stderr) = proc.communicate()
Logs.info(stdout)
if stderr:
Logs.error(stderr)
return proc.returncode
else:
proc = pproc.Popen(s,**kw)
return proc.wait()
except OSError:
return -1
listdir = os.listdir
if is_win32:
def listdir_win32(s):
if re.match('^[A-Za-z]:$', s):
# os.path.isdir fails if s contains only the drive name... (x:)
s += os.sep
if not os.path.isdir(s):
e = OSError()
e.errno = errno.ENOENT
raise e
return os.listdir(s)
listdir = listdir_win32
def waf_version(mini = 0x010000, maxi = 0x100000):
"Halts if the waf version is wrong"
ver = HEXVERSION
try: min_val = mini + 0
except TypeError: min_val = int(mini.replace('.', '0'), 16)
if min_val > ver:
Logs.error("waf version should be at least %s (%s found)" % (mini, ver))
sys.exit(0)
try: max_val = maxi + 0
except TypeError: max_val = int(maxi.replace('.', '0'), 16)
if max_val < ver:
Logs.error("waf version should be at most %s (%s found)" % (maxi, ver))
sys.exit(0)
def python_24_guard():
if sys.hexversion < 0x20400f0 or sys.hexversion >= 0x3000000:
raise ImportError("Waf requires Python >= 2.3 but the raw source requires Python 2.4, 2.5 or 2.6")
def ex_stack():
exc_type, exc_value, tb = sys.exc_info()
if Logs.verbose > 1:
exc_lines = traceback.format_exception(exc_type, exc_value, tb)
return ''.join(exc_lines)
return str(exc_value)
def to_list(sth):
if isinstance(sth, str):
return sth.split()
else:
return sth
g_loaded_modules = {}
"index modules by absolute path"
g_module=None
"the main module is special"
def load_module(file_path, name=WSCRIPT_FILE):
"this function requires an absolute path"
try:
return g_loaded_modules[file_path]
except KeyError:
pass
module = imp.new_module(name)
try:
code = readf(file_path, m='rU')
except (IOError, OSError):
raise WscriptError('Could not read the file %r' % file_path)
module.waf_hash_val = code
sys.path.insert(0, os.path.dirname(file_path))
try:
exec(compile(code, file_path, 'exec'), module.__dict__)
except Exception:
exc_type, exc_value, tb = sys.exc_info()
raise WscriptError("".join(traceback.format_exception(exc_type, exc_value, tb)), file_path)
sys.path.pop(0)
g_loaded_modules[file_path] = module
return module
def set_main_module(file_path):
"Load custom options, if defined"
global g_module
g_module = load_module(file_path, 'wscript_main')
g_module.root_path = file_path
try:
g_module.APPNAME
except:
g_module.APPNAME = 'noname'
try:
g_module.VERSION
except:
g_module.VERSION = '1.0'
# note: to register the module globally, use the following:
# sys.modules['wscript_main'] = g_module
def to_hashtable(s):
"used for importing env files"
tbl = {}
lst = s.split('\n')
for line in lst:
if not line: continue
mems = line.split('=')
tbl[mems[0]] = mems[1]
return tbl
def get_term_cols():
"console width"
return 80
try:
import struct, fcntl, termios
except ImportError:
pass
else:
if Logs.got_tty:
def myfun():
dummy_lines, cols = struct.unpack("HHHH", \
fcntl.ioctl(sys.stderr.fileno(),termios.TIOCGWINSZ , \
struct.pack("HHHH", 0, 0, 0, 0)))[:2]
return cols
# we actually try the function once to see if it is suitable
try:
myfun()
except:
pass
else:
get_term_cols = myfun
rot_idx = 0
rot_chr = ['\\', '|', '/', '-']
"the rotation character in the progress bar"
def split_path(path):
return path.split('/')
def split_path_cygwin(path):
if path.startswith('//'):
ret = path.split('/')[2:]
ret[0] = '/' + ret[0]
return ret
return path.split('/')
re_sp = re.compile('[/\\\\]')
def split_path_win32(path):
if path.startswith('\\\\'):
ret = re.split(re_sp, path)[2:]
ret[0] = '\\' + ret[0]
return ret
return re.split(re_sp, path)
if sys.platform == 'cygwin':
split_path = split_path_cygwin
elif is_win32:
split_path = split_path_win32
def copy_attrs(orig, dest, names, only_if_set=False):
for a in to_list(names):
u = getattr(orig, a, ())
if u or not only_if_set:
setattr(dest, a, u)
def def_attrs(cls, **kw):
'''
set attributes for class.
@param cls [any class]: the class to update the given attributes in.
@param kw [dictionary]: dictionary of attributes names and values.
if the given class hasn't one (or more) of these attributes, add the attribute with its value to the class.
'''
for k, v in kw.iteritems():
if not hasattr(cls, k):
setattr(cls, k, v)
def quote_define_name(path):
fu = re.compile("[^a-zA-Z0-9]").sub("_", path)
fu = fu.upper()
return fu
def quote_whitespace(path):
return (path.strip().find(' ') > 0 and '"%s"' % path or path).replace('""', '"')
def trimquotes(s):
if not s: return ''
s = s.rstrip()
if s[0] == "'" and s[-1] == "'": return s[1:-1]
return s
def h_list(lst):
m = md5()
m.update(str(lst))
return m.digest()
def h_fun(fun):
try:
return fun.code
except AttributeError:
try:
h = inspect.getsource(fun)
except IOError:
h = "nocode"
try:
fun.code = h
except AttributeError:
pass
return h
def pprint(col, str, label='', sep=os.linesep):
"print messages in color"
sys.stderr.write("%s%s%s %s%s" % (Logs.colors(col), str, Logs.colors.NORMAL, label, sep))
def check_dir(dir):
"""If a folder doesn't exists, create it."""
try:
os.stat(dir)
except OSError:
try:
os.makedirs(dir)
except OSError, e:
raise WafError("Cannot create folder '%s' (original error: %s)" % (dir, e))
def cmd_output(cmd, **kw):
silent = False
if 'silent' in kw:
silent = kw['silent']
del(kw['silent'])
if 'e' in kw:
tmp = kw['e']
del(kw['e'])
kw['env'] = tmp
kw['shell'] = isinstance(cmd, str)
kw['stdout'] = pproc.PIPE
if silent:
kw['stderr'] = pproc.PIPE
try:
p = pproc.Popen(cmd, **kw)
output = p.communicate()[0]
except OSError, e:
raise ValueError(str(e))
if p.returncode:
if not silent:
msg = "command execution failed: %s -> %r" % (cmd, str(output))
raise ValueError(msg)
output = ''
return output
reg_subst = re.compile(r"(\\\\)|(\$\$)|\$\{([^}]+)\}")
def subst_vars(expr, params):
"substitute ${PREFIX}/bin in /usr/local/bin"
def repl_var(m):
if m.group(1):
return '\\'
if m.group(2):
return '$'
try:
# environments may contain lists
return params.get_flat(m.group(3))
except AttributeError:
return params[m.group(3)]
return reg_subst.sub(repl_var, expr)
def unversioned_sys_platform_to_binary_format(unversioned_sys_platform):
"infers the binary format from the unversioned_sys_platform name."
if unversioned_sys_platform in ('linux', 'freebsd', 'netbsd', 'openbsd', 'sunos'):
return 'elf'
elif unversioned_sys_platform == 'darwin':
return 'mac-o'
elif unversioned_sys_platform in ('win32', 'cygwin', 'uwin', 'msys'):
return 'pe'
# TODO we assume all other operating systems are elf, which is not true.
# we may set this to 'unknown' and have ccroot and other tools handle the case "gracefully" (whatever that means).
return 'elf'
def unversioned_sys_platform():
"""returns an unversioned name from sys.platform.
sys.plaform is not very well defined and depends directly on the python source tree.
The version appended to the names is unreliable as it's taken from the build environment at the time python was built,
i.e., it's possible to get freebsd7 on a freebsd8 system.
So we remove the version from the name, except for special cases where the os has a stupid name like os2 or win32.
Some possible values of sys.platform are, amongst others:
aix3 aix4 atheos beos5 darwin freebsd2 freebsd3 freebsd4 freebsd5 freebsd6 freebsd7
generic irix5 irix6 linux2 mac netbsd1 next3 os2emx riscos sunos5 unixware7
Investigating the python source tree may reveal more values.
"""
s = sys.platform
if s == 'java':
# The real OS is hidden under the JVM.
from java.lang import System
s = System.getProperty('os.name')
# see http://lopica.sourceforge.net/os.html for a list of possible values
if s == 'Mac OS X':
return 'darwin'
elif s.startswith('Windows '):
return 'win32'
elif s == 'OS/2':
return 'os2'
elif s == 'HP-UX':
return 'hpux'
elif s in ('SunOS', 'Solaris'):
return 'sunos'
else: s = s.lower()
if s == 'win32' or s.endswith('os2') and s != 'sunos2': return s
return re.split('\d+$', s)[0]
#@deprecated('use unversioned_sys_platform instead')
def detect_platform():
"""this function has been in the Utils module for some time.
It's hard to guess what people have used it for.
It seems its goal is to return an unversionned sys.platform, but it's not handling all platforms.
For example, the version is not removed on freebsd and netbsd, amongst others.
"""
s = sys.platform
# known POSIX
for x in 'cygwin linux irix sunos hpux aix darwin'.split():
# sys.platform may be linux2
if s.find(x) >= 0:
return x
# unknown POSIX
if os.name in 'posix java os2'.split():
return os.name
return s
def load_tool(tool, tooldir=None):
'''
load_tool: import a Python module, optionally using several directories.
@param tool [string]: name of tool to import.
@param tooldir [list]: directories to look for the tool.
@return: the loaded module.
Warning: this function is not thread-safe: plays with sys.path,
so must run in sequence.
'''
if tooldir:
assert isinstance(tooldir, list)
sys.path = tooldir + sys.path
try:
try:
return __import__(tool)
except ImportError, e:
Logs.error('Could not load the tool %r in %r:\n%s' % (tool, sys.path, e))
raise
finally:
if tooldir:
sys.path = sys.path[len(tooldir):]
def readf(fname, m='r'):
"get the contents of a file, it is not used anywhere for the moment"
f = open(fname, m)
try:
txt = f.read()
finally:
f.close()
return txt
def nada(*k, **kw):
"""A function that does nothing"""
pass
def diff_path(top, subdir):
"""difference between two absolute paths"""
top = os.path.normpath(top).replace('\\', '/').split('/')
subdir = os.path.normpath(subdir).replace('\\', '/').split('/')
if len(top) == len(subdir): return ''
diff = subdir[len(top) - len(subdir):]
return os.path.join(*diff)
class Context(object):
"""A base class for commands to be executed from Waf scripts"""
def set_curdir(self, dir):
self.curdir_ = dir
def get_curdir(self):
try:
return self.curdir_
except AttributeError:
self.curdir_ = os.getcwd()
return self.get_curdir()
curdir = property(get_curdir, set_curdir)
def recurse(self, dirs, name=''):
"""The function for calling scripts from folders, it tries to call wscript + function_name
and if that file does not exist, it will call the method 'function_name' from a file named wscript
the dirs can be a list of folders or a string containing space-separated folder paths
"""
if not name:
name = inspect.stack()[1][3]
if isinstance(dirs, str):
dirs = to_list(dirs)
for x in dirs:
if os.path.isabs(x):
nexdir = x
else:
nexdir = os.path.join(self.curdir, x)
base = os.path.join(nexdir, WSCRIPT_FILE)
file_path = base + '_' + name
try:
txt = readf(file_path, m='rU')
except (OSError, IOError):
try:
module = load_module(base)
except OSError:
raise WscriptError('No such script %s' % base)
try:
f = module.__dict__[name]
except KeyError:
raise WscriptError('No function %s defined in %s' % (name, base))
if getattr(self.__class__, 'pre_recurse', None):
self.pre_recurse(f, base, nexdir)
old = self.curdir
self.curdir = nexdir
try:
f(self)
finally:
self.curdir = old
if getattr(self.__class__, 'post_recurse', None):
self.post_recurse(module, base, nexdir)
else:
dc = {'ctx': self}
if getattr(self.__class__, 'pre_recurse', None):
dc = self.pre_recurse(txt, file_path, nexdir)
old = self.curdir
self.curdir = nexdir
try:
try:
exec(compile(txt, file_path, 'exec'), dc)
except Exception:
exc_type, exc_value, tb = sys.exc_info()
raise WscriptError("".join(traceback.format_exception(exc_type, exc_value, tb)), base)
finally:
self.curdir = old
if getattr(self.__class__, 'post_recurse', None):
self.post_recurse(txt, file_path, nexdir)
if is_win32:
old = shutil.copy2
def copy2(src, dst):
old(src, dst)
shutil.copystat(src, src)
setattr(shutil, 'copy2', copy2)
def zip_folder(dir, zip_file_name, prefix):
"""
prefix represents the app to add in the archive
"""
import zipfile
zip = zipfile.ZipFile(zip_file_name, 'w', compression=zipfile.ZIP_DEFLATED)
base = os.path.abspath(dir)
if prefix:
if prefix[-1] != os.sep:
prefix += os.sep
n = len(base)
for root, dirs, files in os.walk(base):
for f in files:
archive_name = prefix + root[n:] + os.sep + f
zip.write(root + os.sep + f, archive_name, zipfile.ZIP_DEFLATED)
zip.close()
def get_elapsed_time(start):
"Format a time delta (datetime.timedelta) using the format DdHhMmS.MSs"
delta = datetime.datetime.now() - start
# cast to int necessary for python 3.0
days = int(delta.days)
hours = int(delta.seconds / 3600)
minutes = int((delta.seconds - hours * 3600) / 60)
seconds = delta.seconds - hours * 3600 - minutes * 60 \
+ float(delta.microseconds) / 1000 / 1000
result = ''
if days:
result += '%dd' % days
if days or hours:
result += '%dh' % hours
if days or hours or minutes:
result += '%dm' % minutes
return '%s%.3fs' % (result, seconds)
if os.name == 'java':
# For Jython (they should really fix the inconsistency)
try:
gc.disable()
gc.enable()
except NotImplementedError:
gc.disable = gc.enable
|
if key not in self.allkeys: self.allkeys.append(key)
UserDict.__setitem__(self, key, item)
def exec_command(s, **kw):
if 'log' in kw:
|
random_line_split
|
ticker.rs
|
// Copyright (c) 2015-2017 Ivo Wetzel
|
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// STD Dependencies -----------------------------------------------------------
use std::cmp;
use std::thread;
use std::time::{Duration, Instant};
// Internal Dependencies ------------------------------------------------------
use ::shared::config::Config;
// Tick Rate Limiting ---------------------------------------------------------
#[derive(Debug)]
pub struct Ticker {
tick_start: Instant,
tick_overflow: u64,
tick_overflow_recovery: bool,
tick_overflow_recovery_rate: f32,
tick_delay: u64
}
impl Ticker {
pub fn new(config: Config) -> Ticker {
Ticker {
tick_start: Instant::now(),
tick_overflow: 0,
tick_overflow_recovery: config.tick_overflow_recovery,
tick_overflow_recovery_rate: config.tick_overflow_recovery_rate,
tick_delay: 1000000000 / config.send_rate
}
}
pub fn set_config(&mut self, config: Config) {
self.tick_overflow_recovery = config.tick_overflow_recovery;
self.tick_overflow_recovery_rate = config.tick_overflow_recovery_rate;
self.tick_delay = 1000000000 / config.send_rate
}
pub fn begin_tick(&mut self) {
self.tick_start = Instant::now();
}
pub fn reset(&mut self) {
self.tick_start = Instant::now();
self.tick_overflow = 0;
}
pub fn end_tick(&mut self) {
// Actual time taken by the tick
let time_taken = nanos_from_duration(self.tick_start.elapsed());
// Required delay reduction to keep tick rate
let mut reduction = cmp::min(time_taken, self.tick_delay);
if self.tick_overflow_recovery {
// Keep track of how much additional time the current tick required
self.tick_overflow += time_taken - reduction;
// Try to reduce the existing overflow by reducing the reduction time
// for the current frame.
let max_correction = (self.tick_delay - reduction) as i64;
let correction = cmp::min(
(max_correction as f32 * self.tick_overflow_recovery_rate) as i64,
max_correction
);
// This way we'll achieve a speed up effect in an effort to keep the
// desired tick rate stable over a longer period of time
let reduced_overflow = cmp::max(0, self.tick_overflow as i64 - correction) as u64;
// Adjust the reduction amount to speed up
reduction += self.tick_overflow - reduced_overflow;
// Update remaining overflow
self.tick_overflow = reduced_overflow;
}
thread::sleep(Duration::new(0, (self.tick_delay - reduction) as u32));
}
}
// Helpers ---------------------------------------------------------------------
fn nanos_from_duration(d: Duration) -> u64 {
d.as_secs() * 1000 * 1000000 + d.subsec_nanos() as u64
}
|
random_line_split
|
|
ticker.rs
|
// Copyright (c) 2015-2017 Ivo Wetzel
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// STD Dependencies -----------------------------------------------------------
use std::cmp;
use std::thread;
use std::time::{Duration, Instant};
// Internal Dependencies ------------------------------------------------------
use ::shared::config::Config;
// Tick Rate Limiting ---------------------------------------------------------
#[derive(Debug)]
pub struct Ticker {
tick_start: Instant,
tick_overflow: u64,
tick_overflow_recovery: bool,
tick_overflow_recovery_rate: f32,
tick_delay: u64
}
impl Ticker {
pub fn new(config: Config) -> Ticker {
Ticker {
tick_start: Instant::now(),
tick_overflow: 0,
tick_overflow_recovery: config.tick_overflow_recovery,
tick_overflow_recovery_rate: config.tick_overflow_recovery_rate,
tick_delay: 1000000000 / config.send_rate
}
}
pub fn set_config(&mut self, config: Config) {
self.tick_overflow_recovery = config.tick_overflow_recovery;
self.tick_overflow_recovery_rate = config.tick_overflow_recovery_rate;
self.tick_delay = 1000000000 / config.send_rate
}
pub fn begin_tick(&mut self) {
self.tick_start = Instant::now();
}
pub fn reset(&mut self) {
self.tick_start = Instant::now();
self.tick_overflow = 0;
}
pub fn
|
(&mut self) {
// Actual time taken by the tick
let time_taken = nanos_from_duration(self.tick_start.elapsed());
// Required delay reduction to keep tick rate
let mut reduction = cmp::min(time_taken, self.tick_delay);
if self.tick_overflow_recovery {
// Keep track of how much additional time the current tick required
self.tick_overflow += time_taken - reduction;
// Try to reduce the existing overflow by reducing the reduction time
// for the current frame.
let max_correction = (self.tick_delay - reduction) as i64;
let correction = cmp::min(
(max_correction as f32 * self.tick_overflow_recovery_rate) as i64,
max_correction
);
// This way we'll achieve a speed up effect in an effort to keep the
// desired tick rate stable over a longer period of time
let reduced_overflow = cmp::max(0, self.tick_overflow as i64 - correction) as u64;
// Adjust the reduction amount to speed up
reduction += self.tick_overflow - reduced_overflow;
// Update remaining overflow
self.tick_overflow = reduced_overflow;
}
thread::sleep(Duration::new(0, (self.tick_delay - reduction) as u32));
}
}
// Helpers ---------------------------------------------------------------------
fn nanos_from_duration(d: Duration) -> u64 {
d.as_secs() * 1000 * 1000000 + d.subsec_nanos() as u64
}
|
end_tick
|
identifier_name
|
ticker.rs
|
// Copyright (c) 2015-2017 Ivo Wetzel
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// STD Dependencies -----------------------------------------------------------
use std::cmp;
use std::thread;
use std::time::{Duration, Instant};
// Internal Dependencies ------------------------------------------------------
use ::shared::config::Config;
// Tick Rate Limiting ---------------------------------------------------------
#[derive(Debug)]
pub struct Ticker {
tick_start: Instant,
tick_overflow: u64,
tick_overflow_recovery: bool,
tick_overflow_recovery_rate: f32,
tick_delay: u64
}
impl Ticker {
pub fn new(config: Config) -> Ticker
|
pub fn set_config(&mut self, config: Config) {
self.tick_overflow_recovery = config.tick_overflow_recovery;
self.tick_overflow_recovery_rate = config.tick_overflow_recovery_rate;
self.tick_delay = 1000000000 / config.send_rate
}
pub fn begin_tick(&mut self) {
self.tick_start = Instant::now();
}
pub fn reset(&mut self) {
self.tick_start = Instant::now();
self.tick_overflow = 0;
}
pub fn end_tick(&mut self) {
// Actual time taken by the tick
let time_taken = nanos_from_duration(self.tick_start.elapsed());
// Required delay reduction to keep tick rate
let mut reduction = cmp::min(time_taken, self.tick_delay);
if self.tick_overflow_recovery {
// Keep track of how much additional time the current tick required
self.tick_overflow += time_taken - reduction;
// Try to reduce the existing overflow by reducing the reduction time
// for the current frame.
let max_correction = (self.tick_delay - reduction) as i64;
let correction = cmp::min(
(max_correction as f32 * self.tick_overflow_recovery_rate) as i64,
max_correction
);
// This way we'll achieve a speed up effect in an effort to keep the
// desired tick rate stable over a longer period of time
let reduced_overflow = cmp::max(0, self.tick_overflow as i64 - correction) as u64;
// Adjust the reduction amount to speed up
reduction += self.tick_overflow - reduced_overflow;
// Update remaining overflow
self.tick_overflow = reduced_overflow;
}
thread::sleep(Duration::new(0, (self.tick_delay - reduction) as u32));
}
}
// Helpers ---------------------------------------------------------------------
fn nanos_from_duration(d: Duration) -> u64 {
d.as_secs() * 1000 * 1000000 + d.subsec_nanos() as u64
}
|
{
Ticker {
tick_start: Instant::now(),
tick_overflow: 0,
tick_overflow_recovery: config.tick_overflow_recovery,
tick_overflow_recovery_rate: config.tick_overflow_recovery_rate,
tick_delay: 1000000000 / config.send_rate
}
}
|
identifier_body
|
ticker.rs
|
// Copyright (c) 2015-2017 Ivo Wetzel
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
// STD Dependencies -----------------------------------------------------------
use std::cmp;
use std::thread;
use std::time::{Duration, Instant};
// Internal Dependencies ------------------------------------------------------
use ::shared::config::Config;
// Tick Rate Limiting ---------------------------------------------------------
#[derive(Debug)]
pub struct Ticker {
tick_start: Instant,
tick_overflow: u64,
tick_overflow_recovery: bool,
tick_overflow_recovery_rate: f32,
tick_delay: u64
}
impl Ticker {
pub fn new(config: Config) -> Ticker {
Ticker {
tick_start: Instant::now(),
tick_overflow: 0,
tick_overflow_recovery: config.tick_overflow_recovery,
tick_overflow_recovery_rate: config.tick_overflow_recovery_rate,
tick_delay: 1000000000 / config.send_rate
}
}
pub fn set_config(&mut self, config: Config) {
self.tick_overflow_recovery = config.tick_overflow_recovery;
self.tick_overflow_recovery_rate = config.tick_overflow_recovery_rate;
self.tick_delay = 1000000000 / config.send_rate
}
pub fn begin_tick(&mut self) {
self.tick_start = Instant::now();
}
pub fn reset(&mut self) {
self.tick_start = Instant::now();
self.tick_overflow = 0;
}
pub fn end_tick(&mut self) {
// Actual time taken by the tick
let time_taken = nanos_from_duration(self.tick_start.elapsed());
// Required delay reduction to keep tick rate
let mut reduction = cmp::min(time_taken, self.tick_delay);
if self.tick_overflow_recovery
|
thread::sleep(Duration::new(0, (self.tick_delay - reduction) as u32));
}
}
// Helpers ---------------------------------------------------------------------
fn nanos_from_duration(d: Duration) -> u64 {
d.as_secs() * 1000 * 1000000 + d.subsec_nanos() as u64
}
|
{
// Keep track of how much additional time the current tick required
self.tick_overflow += time_taken - reduction;
// Try to reduce the existing overflow by reducing the reduction time
// for the current frame.
let max_correction = (self.tick_delay - reduction) as i64;
let correction = cmp::min(
(max_correction as f32 * self.tick_overflow_recovery_rate) as i64,
max_correction
);
// This way we'll achieve a speed up effect in an effort to keep the
// desired tick rate stable over a longer period of time
let reduced_overflow = cmp::max(0, self.tick_overflow as i64 - correction) as u64;
// Adjust the reduction amount to speed up
reduction += self.tick_overflow - reduced_overflow;
// Update remaining overflow
self.tick_overflow = reduced_overflow;
}
|
conditional_block
|
BulletCtrl.ts
|
const { ccclass, property } = cc._decorator;
import Global from "./Global"
|
export default class NewClass extends cc.Component {
@property({
default: NaN
})
public speed: number = NaN;
public speedX: number = 0;
public speedY: number = 0;
onLoad() {
// init logic
var manager = cc.director.getCollisionManager();
manager.enabled = true;
}
update(dt) {
this.node.x += this.speedX * dt;
this.node.y += this.speedY * dt;
this.checkOffScreen(dt);
}
onCollisionEnter (other, self) {
// this.node.color = cc.Color.RED;
this.node.dispatchEvent(new cc.Event.EventCustom(Global.EventType.BulletHitPlane, true));
}
checkOffScreen(dt) {
if (this.node.x + this.node.getContentSize().width < 0
|| this.node.x - this.node.getContentSize().width > cc.winSize.width
|| this.node.y + this.node.getContentSize().height < 0
|| this.node.y - this.node.getContentSize().height > cc.winSize.height) {
this.node.dispatchEvent(new cc.Event.EventCustom(Global.EventType.BulletOffScreen, true));
}
}
}
|
@ccclass
|
random_line_split
|
BulletCtrl.ts
|
const { ccclass, property } = cc._decorator;
import Global from "./Global"
@ccclass
export default class NewClass extends cc.Component {
@property({
default: NaN
})
public speed: number = NaN;
public speedX: number = 0;
public speedY: number = 0;
|
() {
// init logic
var manager = cc.director.getCollisionManager();
manager.enabled = true;
}
update(dt) {
this.node.x += this.speedX * dt;
this.node.y += this.speedY * dt;
this.checkOffScreen(dt);
}
onCollisionEnter (other, self) {
// this.node.color = cc.Color.RED;
this.node.dispatchEvent(new cc.Event.EventCustom(Global.EventType.BulletHitPlane, true));
}
checkOffScreen(dt) {
if (this.node.x + this.node.getContentSize().width < 0
|| this.node.x - this.node.getContentSize().width > cc.winSize.width
|| this.node.y + this.node.getContentSize().height < 0
|| this.node.y - this.node.getContentSize().height > cc.winSize.height) {
this.node.dispatchEvent(new cc.Event.EventCustom(Global.EventType.BulletOffScreen, true));
}
}
}
|
onLoad
|
identifier_name
|
BulletCtrl.ts
|
const { ccclass, property } = cc._decorator;
import Global from "./Global"
@ccclass
export default class NewClass extends cc.Component {
@property({
default: NaN
})
public speed: number = NaN;
public speedX: number = 0;
public speedY: number = 0;
onLoad() {
// init logic
var manager = cc.director.getCollisionManager();
manager.enabled = true;
}
update(dt) {
this.node.x += this.speedX * dt;
this.node.y += this.speedY * dt;
this.checkOffScreen(dt);
}
onCollisionEnter (other, self) {
// this.node.color = cc.Color.RED;
this.node.dispatchEvent(new cc.Event.EventCustom(Global.EventType.BulletHitPlane, true));
}
checkOffScreen(dt) {
if (this.node.x + this.node.getContentSize().width < 0
|| this.node.x - this.node.getContentSize().width > cc.winSize.width
|| this.node.y + this.node.getContentSize().height < 0
|| this.node.y - this.node.getContentSize().height > cc.winSize.height)
|
}
}
|
{
this.node.dispatchEvent(new cc.Event.EventCustom(Global.EventType.BulletOffScreen, true));
}
|
conditional_block
|
zero_out_3_test.py
|
"""Test for version 3 of the zero_out op."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow.python.platform
import tensorflow as tf
from tensorflow.g3doc.how_tos.adding_an_op import gen_zero_out_op_3
class ZeroOut3Test(tf.test.TestCase):
def test(self):
with self.test_session():
result = gen_zero_out_op_3.zero_out([5, 4, 3, 2, 1])
self.assertAllEqual(result.eval(), [5, 0, 0, 0, 0])
def testAttr(self):
with self.test_session():
result = gen_zero_out_op_3.zero_out([5, 4, 3, 2, 1], preserve_index=3)
self.assertAllEqual(result.eval(), [0, 0, 0, 2, 0])
def testNegative(self):
with self.test_session():
result = gen_zero_out_op_3.zero_out([5, 4, 3, 2, 1], preserve_index=-1)
with self.assertRaisesOpError("Need preserve_index >= 0, got -1"):
result.eval()
def testLarge(self):
with self.test_session():
result = gen_zero_out_op_3.zero_out([5, 4, 3, 2, 1], preserve_index=17)
with self.assertRaisesOpError("preserve_index out of range"):
result.eval()
if __name__ == '__main__':
|
tf.test.main()
|
conditional_block
|
|
zero_out_3_test.py
|
"""Test for version 3 of the zero_out op."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow.python.platform
import tensorflow as tf
from tensorflow.g3doc.how_tos.adding_an_op import gen_zero_out_op_3
class ZeroOut3Test(tf.test.TestCase):
def test(self):
with self.test_session():
result = gen_zero_out_op_3.zero_out([5, 4, 3, 2, 1])
self.assertAllEqual(result.eval(), [5, 0, 0, 0, 0])
def testAttr(self):
with self.test_session():
result = gen_zero_out_op_3.zero_out([5, 4, 3, 2, 1], preserve_index=3)
self.assertAllEqual(result.eval(), [0, 0, 0, 2, 0])
def testNegative(self):
with self.test_session():
result = gen_zero_out_op_3.zero_out([5, 4, 3, 2, 1], preserve_index=-1)
with self.assertRaisesOpError("Need preserve_index >= 0, got -1"):
result.eval()
def testLarge(self):
with self.test_session():
result = gen_zero_out_op_3.zero_out([5, 4, 3, 2, 1], preserve_index=17)
with self.assertRaisesOpError("preserve_index out of range"):
result.eval()
if __name__ == '__main__':
|
tf.test.main()
|
random_line_split
|
|
zero_out_3_test.py
|
"""Test for version 3 of the zero_out op."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow.python.platform
import tensorflow as tf
from tensorflow.g3doc.how_tos.adding_an_op import gen_zero_out_op_3
class ZeroOut3Test(tf.test.TestCase):
def test(self):
with self.test_session():
result = gen_zero_out_op_3.zero_out([5, 4, 3, 2, 1])
self.assertAllEqual(result.eval(), [5, 0, 0, 0, 0])
def testAttr(self):
|
def testNegative(self):
with self.test_session():
result = gen_zero_out_op_3.zero_out([5, 4, 3, 2, 1], preserve_index=-1)
with self.assertRaisesOpError("Need preserve_index >= 0, got -1"):
result.eval()
def testLarge(self):
with self.test_session():
result = gen_zero_out_op_3.zero_out([5, 4, 3, 2, 1], preserve_index=17)
with self.assertRaisesOpError("preserve_index out of range"):
result.eval()
if __name__ == '__main__':
tf.test.main()
|
with self.test_session():
result = gen_zero_out_op_3.zero_out([5, 4, 3, 2, 1], preserve_index=3)
self.assertAllEqual(result.eval(), [0, 0, 0, 2, 0])
|
identifier_body
|
zero_out_3_test.py
|
"""Test for version 3 of the zero_out op."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow.python.platform
import tensorflow as tf
from tensorflow.g3doc.how_tos.adding_an_op import gen_zero_out_op_3
class
|
(tf.test.TestCase):
def test(self):
with self.test_session():
result = gen_zero_out_op_3.zero_out([5, 4, 3, 2, 1])
self.assertAllEqual(result.eval(), [5, 0, 0, 0, 0])
def testAttr(self):
with self.test_session():
result = gen_zero_out_op_3.zero_out([5, 4, 3, 2, 1], preserve_index=3)
self.assertAllEqual(result.eval(), [0, 0, 0, 2, 0])
def testNegative(self):
with self.test_session():
result = gen_zero_out_op_3.zero_out([5, 4, 3, 2, 1], preserve_index=-1)
with self.assertRaisesOpError("Need preserve_index >= 0, got -1"):
result.eval()
def testLarge(self):
with self.test_session():
result = gen_zero_out_op_3.zero_out([5, 4, 3, 2, 1], preserve_index=17)
with self.assertRaisesOpError("preserve_index out of range"):
result.eval()
if __name__ == '__main__':
tf.test.main()
|
ZeroOut3Test
|
identifier_name
|
plugin_xmlio_pl.ts
|
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE TS>
<TS version="2.0" language="pl_PL">
<context>
<name>XmlForms::Internal::XmlFormIO</name>
<message>
<location filename="../../plugins/xmlioplugin/xmlformio.cpp" line="143"/>
<source>Invalid form file detected: %1</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../plugins/xmlioplugin/xmlformio.cpp" line="144"/>
<source>Invalid file detected.</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../plugins/xmlioplugin/xmlformio.cpp" line="145"/>
<source>An invalid file was found. Please contact your software administrator.
Wrong file: %1
Error: %2</source>
<translation type="unfinished"></translation>
</message>
<message>
<location filename="../../plugins/xmlioplugin/xmlformio.cpp" line="316"/>
<source>No form file name</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>XmlForms::Internal::XmlIOBase</name>
<message>
<location filename="../../plugins/xmlioplugin/xmliobase.cpp" line="947"/>
<source>Error while saving PMHxCateogries (%1)</source>
<translation type="unfinished"></translation>
</message>
</context>
<context>
<name>XmlIOBase</name>
<message>
<location filename="../../plugins/xmlioplugin/xmliobase.cpp" line="229"/>
<source>Trying to create empty database.
Location: %1
FileName: %2
Driver: %3</source>
<translation type="unfinished"></translation>
|
</message>
</context>
</TS>
|
random_line_split
|
|
cpuid.rs
|
use std::str;
use std::slice;
use std::mem;
use byteorder::{LittleEndian, WriteBytesExt};
const VENDOR_INFO: u32 = 0x0;
const FEATURE_INFO: u32 = 0x1;
const EXT_FEATURE_INFO: u32 = 0x7;
const EXT_PROCESSOR_INFO: u32 = 0x80000001;
#[cfg(target_arch = "x86_64")]
pub fn cpuid(func: u32) -> CpuIdInfo {
let (rax, rbx, rcx, rdx);
unsafe {
asm!("cpuid"
: // output operands
"={rax}"(rax),
"={rbx}"(rbx),
"={rcx}"(rcx),
"={rdx}"(rdx)
: // input operands
"{rax}"(func),
"{rcx}"(0 as u32)
: // clobbers
: // options
);
}
CpuIdInfo {
rax: rax,
rbx: rbx,
rcx: rcx,
rdx: rdx
}
}
// Rename to something better
pub struct CpuIdInfo {
pub rax: u32,
pub rbx: u32,
pub rcx: u32,
pub rdx: u32,
}
pub struct
|
{
pub highest_func_param: u32,
pub vendor_info: CpuIdInfo,
pub feature_info: CpuIdInfo,
pub ext_feature_info: CpuIdInfo,
pub ext_processor_info: CpuIdInfo
}
impl CpuId {
pub fn detect() -> CpuId {
CpuId {
highest_func_param: cpuid(VENDOR_INFO).rax,
vendor_info: cpuid(VENDOR_INFO),
feature_info: cpuid(FEATURE_INFO),
ext_feature_info: cpuid(EXT_FEATURE_INFO),
ext_processor_info: cpuid(EXT_PROCESSOR_INFO)
}
}
}
#[test]
fn test_usage() {
let v = cpuid(VENDOR_INFO);
let mut wtr: Vec<u8> = vec![];
wtr.write_u32::<LittleEndian>(v.rbx).unwrap();
wtr.write_u32::<LittleEndian>(v.rdx).unwrap();
wtr.write_u32::<LittleEndian>(v.rcx).unwrap();
let string = String::from_utf8(wtr).unwrap();
assert!(string == "AuthenticAMD" || string == "GenuineIntel")
}
|
CpuId
|
identifier_name
|
cpuid.rs
|
use std::str;
use std::slice;
use std::mem;
use byteorder::{LittleEndian, WriteBytesExt};
const VENDOR_INFO: u32 = 0x0;
const FEATURE_INFO: u32 = 0x1;
const EXT_FEATURE_INFO: u32 = 0x7;
const EXT_PROCESSOR_INFO: u32 = 0x80000001;
#[cfg(target_arch = "x86_64")]
pub fn cpuid(func: u32) -> CpuIdInfo {
let (rax, rbx, rcx, rdx);
unsafe {
asm!("cpuid"
: // output operands
"={rax}"(rax),
"={rbx}"(rbx),
"={rcx}"(rcx),
"={rdx}"(rdx)
: // input operands
"{rax}"(func),
"{rcx}"(0 as u32)
: // clobbers
: // options
);
}
CpuIdInfo {
rax: rax,
rbx: rbx,
rcx: rcx,
rdx: rdx
}
}
// Rename to something better
pub struct CpuIdInfo {
pub rax: u32,
pub rbx: u32,
|
pub rcx: u32,
pub rdx: u32,
}
pub struct CpuId {
pub highest_func_param: u32,
pub vendor_info: CpuIdInfo,
pub feature_info: CpuIdInfo,
pub ext_feature_info: CpuIdInfo,
pub ext_processor_info: CpuIdInfo
}
impl CpuId {
pub fn detect() -> CpuId {
CpuId {
highest_func_param: cpuid(VENDOR_INFO).rax,
vendor_info: cpuid(VENDOR_INFO),
feature_info: cpuid(FEATURE_INFO),
ext_feature_info: cpuid(EXT_FEATURE_INFO),
ext_processor_info: cpuid(EXT_PROCESSOR_INFO)
}
}
}
#[test]
fn test_usage() {
let v = cpuid(VENDOR_INFO);
let mut wtr: Vec<u8> = vec![];
wtr.write_u32::<LittleEndian>(v.rbx).unwrap();
wtr.write_u32::<LittleEndian>(v.rdx).unwrap();
wtr.write_u32::<LittleEndian>(v.rcx).unwrap();
let string = String::from_utf8(wtr).unwrap();
assert!(string == "AuthenticAMD" || string == "GenuineIntel")
}
|
random_line_split
|
|
element_binder.ts
|
import {AST} from 'angular2/src/change_detection/change_detection';
import {isBlank, isPresent, BaseException} from 'angular2/src/facade/lang';
import * as eiModule from './element_injector';
import {DirectiveBinding} from './element_injector';
import {List, StringMap} from 'angular2/src/facade/collection';
import * as viewModule from './view';
export class ElementBinder {
// updated later, so we are able to resolve cycles
nestedProtoView: viewModule.AppProtoView = null;
// updated later when events are bound
hostListeners: StringMap<string, Map<number, AST>> = null;
constructor(public index: int, public parent: ElementBinder, public distanceToParent: int,
public protoElementInjector: eiModule.ProtoElementInjector,
public componentDirective: DirectiveBinding) {
if (isBlank(index))
|
}
hasStaticComponent(): boolean {
return isPresent(this.componentDirective) && isPresent(this.nestedProtoView);
}
hasEmbeddedProtoView(): boolean {
return !isPresent(this.componentDirective) && isPresent(this.nestedProtoView);
}
}
|
{
throw new BaseException('null index not allowed.');
}
|
conditional_block
|
element_binder.ts
|
import {AST} from 'angular2/src/change_detection/change_detection';
import {isBlank, isPresent, BaseException} from 'angular2/src/facade/lang';
import * as eiModule from './element_injector';
import {DirectiveBinding} from './element_injector';
import {List, StringMap} from 'angular2/src/facade/collection';
import * as viewModule from './view';
export class ElementBinder {
// updated later, so we are able to resolve cycles
nestedProtoView: viewModule.AppProtoView = null;
// updated later when events are bound
hostListeners: StringMap<string, Map<number, AST>> = null;
constructor(public index: int, public parent: ElementBinder, public distanceToParent: int,
public protoElementInjector: eiModule.ProtoElementInjector,
public componentDirective: DirectiveBinding) {
if (isBlank(index)) {
throw new BaseException('null index not allowed.');
}
}
hasStaticComponent(): boolean {
return isPresent(this.componentDirective) && isPresent(this.nestedProtoView);
}
|
(): boolean {
return !isPresent(this.componentDirective) && isPresent(this.nestedProtoView);
}
}
|
hasEmbeddedProtoView
|
identifier_name
|
element_binder.ts
|
import {AST} from 'angular2/src/change_detection/change_detection';
import {isBlank, isPresent, BaseException} from 'angular2/src/facade/lang';
import * as eiModule from './element_injector';
import {DirectiveBinding} from './element_injector';
import {List, StringMap} from 'angular2/src/facade/collection';
import * as viewModule from './view';
export class ElementBinder {
// updated later, so we are able to resolve cycles
nestedProtoView: viewModule.AppProtoView = null;
// updated later when events are bound
hostListeners: StringMap<string, Map<number, AST>> = null;
constructor(public index: int, public parent: ElementBinder, public distanceToParent: int,
public protoElementInjector: eiModule.ProtoElementInjector,
public componentDirective: DirectiveBinding)
|
hasStaticComponent(): boolean {
return isPresent(this.componentDirective) && isPresent(this.nestedProtoView);
}
hasEmbeddedProtoView(): boolean {
return !isPresent(this.componentDirective) && isPresent(this.nestedProtoView);
}
}
|
{
if (isBlank(index)) {
throw new BaseException('null index not allowed.');
}
}
|
identifier_body
|
element_binder.ts
|
import {AST} from 'angular2/src/change_detection/change_detection';
import {isBlank, isPresent, BaseException} from 'angular2/src/facade/lang';
import * as eiModule from './element_injector';
import {DirectiveBinding} from './element_injector';
import {List, StringMap} from 'angular2/src/facade/collection';
import * as viewModule from './view';
export class ElementBinder {
// updated later, so we are able to resolve cycles
nestedProtoView: viewModule.AppProtoView = null;
// updated later when events are bound
hostListeners: StringMap<string, Map<number, AST>> = null;
constructor(public index: int, public parent: ElementBinder, public distanceToParent: int,
public protoElementInjector: eiModule.ProtoElementInjector,
public componentDirective: DirectiveBinding) {
if (isBlank(index)) {
throw new BaseException('null index not allowed.');
|
return isPresent(this.componentDirective) && isPresent(this.nestedProtoView);
}
hasEmbeddedProtoView(): boolean {
return !isPresent(this.componentDirective) && isPresent(this.nestedProtoView);
}
}
|
}
}
hasStaticComponent(): boolean {
|
random_line_split
|
accessible_views_view.js
|
(function() {
define(function() {
var AccessibleViewItemView, AccessibleViewsView;
AccessibleViewItemView = Backbone.View.extend({
tagName: 'div',
events: {
"click": "clicked",
"mouseover": "mousedover",
"mouseout": "mousedout"
},
render: function() {
this.$el.empty().append("<a href=\"#\" title=\"" + (this.model.getShelleySelector()) + "\">\n <span class=\"viewClass\">" + (this.model.get('class')) + "</span>\n with label\n \"<span class=\"viewLabel\">" + (this.model.get('accessibilityLabel')) + "</span>\"\n</a>");
return this;
},
mousedover: function() {
return this.model.setActive();
},
mousedout: function() {
return this.model.unsetActive();
|
return this.model.trigger('accessible-selected', this.model);
}
});
AccessibleViewsView = Backbone.View.extend({
el: $('#accessible-views'),
initialize: function() {
this.collection = new Backbone.Collection;
return this.collection.on('reset', _.bind(this.render, this));
},
render: function() {
var _this = this;
this.$el.empty();
this.collection.each(function(viewModel) {
return _this.$el.append(new AccessibleViewItemView({
model: viewModel
}).render().el);
});
return this;
}
});
return AccessibleViewsView;
});
}).call(this);
|
},
clicked: function() {
|
random_line_split
|
completer.rs
|
use rustyline;
use rustyline::line_buffer::LineBuffer;
pub struct CustomCompletion {
commands: Vec<&'static str>,
hinter: rustyline::hint::HistoryHinter,
}
impl CustomCompletion {
pub fn new() -> Self {
let commands: Vec<&str> = vec!["help", "items", "projs", "quit"];
Self {
commands,
hinter: rustyline::hint::HistoryHinter {},
}
}
}
impl rustyline::completion::Completer for CustomCompletion {
type Candidate = String;
fn complete(
&self,
line: &str,
pos: usize,
_ctx: &rustyline::Context<'_>,
) -> rustyline::Result<(usize, Vec<String>)> {
let mut completions: Vec<String> = Vec::new();
for command in &self.commands {
if command.starts_with(line)
|
}
Ok((pos, completions))
}
fn update(&self, line: &mut LineBuffer, start: usize, elected: &str) {
line.update(elected, start);
}
}
impl rustyline::hint::Hinter for CustomCompletion {
type Hint = String;
fn hint(&self, line: &str, pos: usize, ctx: &rustyline::Context<'_>) -> Option<String> {
self.hinter.hint(line, pos, ctx)
}
}
impl rustyline::validate::Validator for CustomCompletion {}
impl rustyline::Helper for CustomCompletion {}
impl rustyline::highlight::Highlighter for CustomCompletion {}
// Tests
#[cfg(test)]
use rustyline::completion::Completer;
#[cfg(test)]
fn verify_completion(input: &str, expected_completion: &str) {
let hist = rustyline::history::History::new();
let ctx = rustyline::Context::new(&hist);
let completer = CustomCompletion::new();
assert_eq!(
completer.complete(input, 0, &ctx).unwrap(),
(0, vec![String::from(expected_completion)])
);
}
#[test]
fn completion_test_items() {
// Verify that the completion for i completes to items.
verify_completion("i", "items");
verify_completion("ite", "items");
}
#[test]
fn completion_test_quit() {
// Verify that the completion for q completes to quit.
verify_completion("q", "quit");
verify_completion("qui", "quit");
}
#[test]
fn completion_test_help() {
// Verify that the completion for h completes to help.
verify_completion("h", "help");
verify_completion("he", "help");
}
#[test]
fn completion_test_projects() {
// Verify that the completion for p completes to projs.
verify_completion("p", "projs");
verify_completion("pro", "projs");
}
|
{
completions.push(command.to_string());
}
|
conditional_block
|
completer.rs
|
use rustyline;
use rustyline::line_buffer::LineBuffer;
pub struct CustomCompletion {
commands: Vec<&'static str>,
hinter: rustyline::hint::HistoryHinter,
}
impl CustomCompletion {
pub fn new() -> Self {
|
hinter: rustyline::hint::HistoryHinter {},
}
}
}
impl rustyline::completion::Completer for CustomCompletion {
type Candidate = String;
fn complete(
&self,
line: &str,
pos: usize,
_ctx: &rustyline::Context<'_>,
) -> rustyline::Result<(usize, Vec<String>)> {
let mut completions: Vec<String> = Vec::new();
for command in &self.commands {
if command.starts_with(line) {
completions.push(command.to_string());
}
}
Ok((pos, completions))
}
fn update(&self, line: &mut LineBuffer, start: usize, elected: &str) {
line.update(elected, start);
}
}
impl rustyline::hint::Hinter for CustomCompletion {
type Hint = String;
fn hint(&self, line: &str, pos: usize, ctx: &rustyline::Context<'_>) -> Option<String> {
self.hinter.hint(line, pos, ctx)
}
}
impl rustyline::validate::Validator for CustomCompletion {}
impl rustyline::Helper for CustomCompletion {}
impl rustyline::highlight::Highlighter for CustomCompletion {}
// Tests
#[cfg(test)]
use rustyline::completion::Completer;
#[cfg(test)]
fn verify_completion(input: &str, expected_completion: &str) {
let hist = rustyline::history::History::new();
let ctx = rustyline::Context::new(&hist);
let completer = CustomCompletion::new();
assert_eq!(
completer.complete(input, 0, &ctx).unwrap(),
(0, vec![String::from(expected_completion)])
);
}
#[test]
fn completion_test_items() {
// Verify that the completion for i completes to items.
verify_completion("i", "items");
verify_completion("ite", "items");
}
#[test]
fn completion_test_quit() {
// Verify that the completion for q completes to quit.
verify_completion("q", "quit");
verify_completion("qui", "quit");
}
#[test]
fn completion_test_help() {
// Verify that the completion for h completes to help.
verify_completion("h", "help");
verify_completion("he", "help");
}
#[test]
fn completion_test_projects() {
// Verify that the completion for p completes to projs.
verify_completion("p", "projs");
verify_completion("pro", "projs");
}
|
let commands: Vec<&str> = vec!["help", "items", "projs", "quit"];
Self {
commands,
|
random_line_split
|
completer.rs
|
use rustyline;
use rustyline::line_buffer::LineBuffer;
pub struct CustomCompletion {
commands: Vec<&'static str>,
hinter: rustyline::hint::HistoryHinter,
}
impl CustomCompletion {
pub fn new() -> Self {
let commands: Vec<&str> = vec!["help", "items", "projs", "quit"];
Self {
commands,
hinter: rustyline::hint::HistoryHinter {},
}
}
}
impl rustyline::completion::Completer for CustomCompletion {
type Candidate = String;
fn complete(
&self,
line: &str,
pos: usize,
_ctx: &rustyline::Context<'_>,
) -> rustyline::Result<(usize, Vec<String>)> {
let mut completions: Vec<String> = Vec::new();
for command in &self.commands {
if command.starts_with(line) {
completions.push(command.to_string());
}
}
Ok((pos, completions))
}
fn update(&self, line: &mut LineBuffer, start: usize, elected: &str) {
line.update(elected, start);
}
}
impl rustyline::hint::Hinter for CustomCompletion {
type Hint = String;
fn hint(&self, line: &str, pos: usize, ctx: &rustyline::Context<'_>) -> Option<String> {
self.hinter.hint(line, pos, ctx)
}
}
impl rustyline::validate::Validator for CustomCompletion {}
impl rustyline::Helper for CustomCompletion {}
impl rustyline::highlight::Highlighter for CustomCompletion {}
// Tests
#[cfg(test)]
use rustyline::completion::Completer;
#[cfg(test)]
fn verify_completion(input: &str, expected_completion: &str) {
let hist = rustyline::history::History::new();
let ctx = rustyline::Context::new(&hist);
let completer = CustomCompletion::new();
assert_eq!(
completer.complete(input, 0, &ctx).unwrap(),
(0, vec![String::from(expected_completion)])
);
}
#[test]
fn completion_test_items() {
// Verify that the completion for i completes to items.
verify_completion("i", "items");
verify_completion("ite", "items");
}
#[test]
fn completion_test_quit() {
// Verify that the completion for q completes to quit.
verify_completion("q", "quit");
verify_completion("qui", "quit");
}
#[test]
fn
|
() {
// Verify that the completion for h completes to help.
verify_completion("h", "help");
verify_completion("he", "help");
}
#[test]
fn completion_test_projects() {
// Verify that the completion for p completes to projs.
verify_completion("p", "projs");
verify_completion("pro", "projs");
}
|
completion_test_help
|
identifier_name
|
completer.rs
|
use rustyline;
use rustyline::line_buffer::LineBuffer;
pub struct CustomCompletion {
commands: Vec<&'static str>,
hinter: rustyline::hint::HistoryHinter,
}
impl CustomCompletion {
pub fn new() -> Self {
let commands: Vec<&str> = vec!["help", "items", "projs", "quit"];
Self {
commands,
hinter: rustyline::hint::HistoryHinter {},
}
}
}
impl rustyline::completion::Completer for CustomCompletion {
type Candidate = String;
fn complete(
&self,
line: &str,
pos: usize,
_ctx: &rustyline::Context<'_>,
) -> rustyline::Result<(usize, Vec<String>)> {
let mut completions: Vec<String> = Vec::new();
for command in &self.commands {
if command.starts_with(line) {
completions.push(command.to_string());
}
}
Ok((pos, completions))
}
fn update(&self, line: &mut LineBuffer, start: usize, elected: &str) {
line.update(elected, start);
}
}
impl rustyline::hint::Hinter for CustomCompletion {
type Hint = String;
fn hint(&self, line: &str, pos: usize, ctx: &rustyline::Context<'_>) -> Option<String> {
self.hinter.hint(line, pos, ctx)
}
}
impl rustyline::validate::Validator for CustomCompletion {}
impl rustyline::Helper for CustomCompletion {}
impl rustyline::highlight::Highlighter for CustomCompletion {}
// Tests
#[cfg(test)]
use rustyline::completion::Completer;
#[cfg(test)]
fn verify_completion(input: &str, expected_completion: &str) {
let hist = rustyline::history::History::new();
let ctx = rustyline::Context::new(&hist);
let completer = CustomCompletion::new();
assert_eq!(
completer.complete(input, 0, &ctx).unwrap(),
(0, vec![String::from(expected_completion)])
);
}
#[test]
fn completion_test_items() {
// Verify that the completion for i completes to items.
verify_completion("i", "items");
verify_completion("ite", "items");
}
#[test]
fn completion_test_quit() {
// Verify that the completion for q completes to quit.
verify_completion("q", "quit");
verify_completion("qui", "quit");
}
#[test]
fn completion_test_help()
|
#[test]
fn completion_test_projects() {
// Verify that the completion for p completes to projs.
verify_completion("p", "projs");
verify_completion("pro", "projs");
}
|
{
// Verify that the completion for h completes to help.
verify_completion("h", "help");
verify_completion("he", "help");
}
|
identifier_body
|
test_models.py
|
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
from bedrock.mozorg.tests import TestCase
from bedrock.sitemaps.models import NO_LOCALE, SitemapURL
class TestSitemapsModel(TestCase):
|
def test_absolute_url(self):
obj = SitemapURL(path="/firefox/", locale="de")
assert obj.get_absolute_url() == "https://www.mozilla.org/de/firefox/"
# none locale
obj = SitemapURL(path="/firefox/", locale=NO_LOCALE)
assert obj.get_absolute_url() == "https://www.mozilla.org/firefox/"
def test_all_for_locale(self):
SitemapURL.objects.create(path="/firefox/", locale="de")
SitemapURL.objects.create(path="/firefox/", locale="fr")
SitemapURL.objects.create(path="/", locale="de")
SitemapURL.objects.create(path="/about/", locale="de")
de_paths = [str(o) for o in SitemapURL.objects.all_for_locale("de")]
# should contain no fr URL and be in alphabetical order
assert de_paths == ["/de/", "/de/about/", "/de/firefox/"]
def test_all_locales(self):
SitemapURL.objects.create(path="/firefox/", locale="de")
SitemapURL.objects.create(path="/firefox/", locale="fr")
SitemapURL.objects.create(path="/", locale="de")
SitemapURL.objects.create(path="/firefox/", locale="en-US")
SitemapURL.objects.create(path="/locales/", locale=NO_LOCALE)
assert list(SitemapURL.objects.all_locales()) == [NO_LOCALE, "de", "en-US", "fr"]
|
identifier_body
|
|
test_models.py
|
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
from bedrock.mozorg.tests import TestCase
from bedrock.sitemaps.models import NO_LOCALE, SitemapURL
class TestSitemapsModel(TestCase):
def test_absolute_url(self):
obj = SitemapURL(path="/firefox/", locale="de")
assert obj.get_absolute_url() == "https://www.mozilla.org/de/firefox/"
# none locale
obj = SitemapURL(path="/firefox/", locale=NO_LOCALE)
assert obj.get_absolute_url() == "https://www.mozilla.org/firefox/"
|
de_paths = [str(o) for o in SitemapURL.objects.all_for_locale("de")]
# should contain no fr URL and be in alphabetical order
assert de_paths == ["/de/", "/de/about/", "/de/firefox/"]
def test_all_locales(self):
SitemapURL.objects.create(path="/firefox/", locale="de")
SitemapURL.objects.create(path="/firefox/", locale="fr")
SitemapURL.objects.create(path="/", locale="de")
SitemapURL.objects.create(path="/firefox/", locale="en-US")
SitemapURL.objects.create(path="/locales/", locale=NO_LOCALE)
assert list(SitemapURL.objects.all_locales()) == [NO_LOCALE, "de", "en-US", "fr"]
|
def test_all_for_locale(self):
SitemapURL.objects.create(path="/firefox/", locale="de")
SitemapURL.objects.create(path="/firefox/", locale="fr")
SitemapURL.objects.create(path="/", locale="de")
SitemapURL.objects.create(path="/about/", locale="de")
|
random_line_split
|
test_models.py
|
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at https://mozilla.org/MPL/2.0/.
from bedrock.mozorg.tests import TestCase
from bedrock.sitemaps.models import NO_LOCALE, SitemapURL
class TestSitemapsModel(TestCase):
def
|
(self):
obj = SitemapURL(path="/firefox/", locale="de")
assert obj.get_absolute_url() == "https://www.mozilla.org/de/firefox/"
# none locale
obj = SitemapURL(path="/firefox/", locale=NO_LOCALE)
assert obj.get_absolute_url() == "https://www.mozilla.org/firefox/"
def test_all_for_locale(self):
SitemapURL.objects.create(path="/firefox/", locale="de")
SitemapURL.objects.create(path="/firefox/", locale="fr")
SitemapURL.objects.create(path="/", locale="de")
SitemapURL.objects.create(path="/about/", locale="de")
de_paths = [str(o) for o in SitemapURL.objects.all_for_locale("de")]
# should contain no fr URL and be in alphabetical order
assert de_paths == ["/de/", "/de/about/", "/de/firefox/"]
def test_all_locales(self):
SitemapURL.objects.create(path="/firefox/", locale="de")
SitemapURL.objects.create(path="/firefox/", locale="fr")
SitemapURL.objects.create(path="/", locale="de")
SitemapURL.objects.create(path="/firefox/", locale="en-US")
SitemapURL.objects.create(path="/locales/", locale=NO_LOCALE)
assert list(SitemapURL.objects.all_locales()) == [NO_LOCALE, "de", "en-US", "fr"]
|
test_absolute_url
|
identifier_name
|
types.ts
|
/*
* Copyright 2022 ThoughtWorks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import _ from "lodash";
import Stream from "mithril/stream";
import {applyMixins} from "models/mixins/mixins";
import {ValidatableMixin} from "models/mixins/new_validatable_mixin";
import {Origin, OriginJSON, OriginType} from "models/origin";
import {EncryptedValue} from "views/components/forms/encrypted_value";
export interface EnvironmentVariableJSON {
secure: boolean;
name: string;
value?: string;
encrypted_value?: string;
}
export class EnvironmentVariable extends ValidatableMixin {
secure: Stream<boolean>;
name: Stream<string>;
value: Stream<string | undefined>;
encryptedValue: Stream<EncryptedValue>;
isEditable: Stream<boolean> = Stream<boolean>(true);
nonEditableReason: Stream<string | undefined> = Stream();
constructor(name: string, value?: string, secure?: boolean, encryptedValue?: string) {
super();
this.secure = Stream(secure || false);
this.name = Stream(name);
this.value = Stream(value);
this.encryptedValue = Stream(new EncryptedValue(!_.isEmpty(encryptedValue) ? {cipherText: encryptedValue} : {clearText: value}));
this.validatePresenceOf("name", {condition: () => !_.isEmpty(this.value()) || !_.isEmpty(this.encryptedValue())});
}
static fromJSON(data: EnvironmentVariableJSON) {
return new EnvironmentVariable(data.name, data.value, data.secure, data.encrypted_value);
}
editable() {
return this.isEditable();
}
reasonForNonEditable() {
return this.nonEditableReason();
}
toJSON(): EnvironmentVariableJSON {
// plain text
if (!this.secure()) {
return {
name: this.name(),
value: this.value() || "",
secure: this.secure()
};
}
//secure text
if (this.encryptedValue().isEditing()) {
return {
name: this.name(),
value: this.encryptedValue().value() || "",
secure: this.secure()
};
} else {
return {
name: this.name(),
encrypted_value: this.encryptedValue().value(),
secure: this.secure()
};
}
}
equals(environmentVariable: EnvironmentVariable): boolean {
return this.name() === environmentVariable.name()
&& this.value() === environmentVariable.value()
&& this.encryptedValue().value() === environmentVariable.encryptedValue().value();
}
}
//tslint:disable-next-line
export interface EnvironmentVariables extends ValidatableMixin {
}
export class EnvironmentVariables<T extends EnvironmentVariable = EnvironmentVariable> extends Array<T> implements ValidatableMixin {
constructor(...environmentVariables: T[]) {
super(...environmentVariables);
Object.setPrototypeOf(this, Object.create(EnvironmentVariables.prototype));
ValidatableMixin.call(this);
}
static fromJSON(environmentVariables: EnvironmentVariableJSON[]) {
return new EnvironmentVariables(...environmentVariables.map(EnvironmentVariable.fromJSON));
}
secureVariables(): EnvironmentVariables<T> {
return new EnvironmentVariables<T>(...this.filter((envVar) => envVar.secure()));
}
plainTextVariables(): EnvironmentVariables<T>
|
remove(envVar: T) {
this.splice(this.indexOf(envVar), 1);
}
toJSON() {
return this.map((envVar) => envVar.toJSON());
}
}
applyMixins(EnvironmentVariables, ValidatableMixin);
export interface EnvironmentEnvironmentVariableJSON extends EnvironmentVariableJSON {
origin: OriginJSON;
}
export class EnvironmentVariableWithOrigin extends EnvironmentVariable {
readonly origin: Stream<Origin>;
constructor(name: string, origin: Origin, value?: string, secure?: boolean, encryptedValue?: string) {
super(name, value, secure, encryptedValue);
this.origin = Stream(origin);
}
static fromJSON(data: EnvironmentEnvironmentVariableJSON) {
return new EnvironmentVariableWithOrigin(data.name,
Origin.fromJSON(data.origin),
data.value,
data.secure,
data.encrypted_value);
}
editable() {
return this.origin().type() === OriginType.GoCD;
}
reasonForNonEditable() {
if (this.editable()) {
throw Error("Environment variable is editable");
}
return "Cannot edit this environment variable as it is defined in config repo";
}
clone() {
return new EnvironmentVariableWithOrigin(this.name(),
this.origin().clone(),
this.value(),
this.secure(),
this.encryptedValue().getOriginal());
}
}
export class EnvironmentVariablesWithOrigin extends EnvironmentVariables<EnvironmentVariableWithOrigin> {
static fromJSON(environmentVariables: EnvironmentEnvironmentVariableJSON[]) {
return new EnvironmentVariablesWithOrigin(...environmentVariables.map(EnvironmentVariableWithOrigin.fromJSON));
}
}
|
{
return new EnvironmentVariables<T>(...this.filter((envVar) => !envVar.secure()));
}
|
identifier_body
|
types.ts
|
/*
* Copyright 2022 ThoughtWorks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import _ from "lodash";
import Stream from "mithril/stream";
import {applyMixins} from "models/mixins/mixins";
import {ValidatableMixin} from "models/mixins/new_validatable_mixin";
import {Origin, OriginJSON, OriginType} from "models/origin";
import {EncryptedValue} from "views/components/forms/encrypted_value";
export interface EnvironmentVariableJSON {
secure: boolean;
name: string;
value?: string;
encrypted_value?: string;
}
export class EnvironmentVariable extends ValidatableMixin {
secure: Stream<boolean>;
name: Stream<string>;
value: Stream<string | undefined>;
encryptedValue: Stream<EncryptedValue>;
isEditable: Stream<boolean> = Stream<boolean>(true);
nonEditableReason: Stream<string | undefined> = Stream();
|
this.secure = Stream(secure || false);
this.name = Stream(name);
this.value = Stream(value);
this.encryptedValue = Stream(new EncryptedValue(!_.isEmpty(encryptedValue) ? {cipherText: encryptedValue} : {clearText: value}));
this.validatePresenceOf("name", {condition: () => !_.isEmpty(this.value()) || !_.isEmpty(this.encryptedValue())});
}
static fromJSON(data: EnvironmentVariableJSON) {
return new EnvironmentVariable(data.name, data.value, data.secure, data.encrypted_value);
}
editable() {
return this.isEditable();
}
reasonForNonEditable() {
return this.nonEditableReason();
}
toJSON(): EnvironmentVariableJSON {
// plain text
if (!this.secure()) {
return {
name: this.name(),
value: this.value() || "",
secure: this.secure()
};
}
//secure text
if (this.encryptedValue().isEditing()) {
return {
name: this.name(),
value: this.encryptedValue().value() || "",
secure: this.secure()
};
} else {
return {
name: this.name(),
encrypted_value: this.encryptedValue().value(),
secure: this.secure()
};
}
}
equals(environmentVariable: EnvironmentVariable): boolean {
return this.name() === environmentVariable.name()
&& this.value() === environmentVariable.value()
&& this.encryptedValue().value() === environmentVariable.encryptedValue().value();
}
}
//tslint:disable-next-line
export interface EnvironmentVariables extends ValidatableMixin {
}
export class EnvironmentVariables<T extends EnvironmentVariable = EnvironmentVariable> extends Array<T> implements ValidatableMixin {
constructor(...environmentVariables: T[]) {
super(...environmentVariables);
Object.setPrototypeOf(this, Object.create(EnvironmentVariables.prototype));
ValidatableMixin.call(this);
}
static fromJSON(environmentVariables: EnvironmentVariableJSON[]) {
return new EnvironmentVariables(...environmentVariables.map(EnvironmentVariable.fromJSON));
}
secureVariables(): EnvironmentVariables<T> {
return new EnvironmentVariables<T>(...this.filter((envVar) => envVar.secure()));
}
plainTextVariables(): EnvironmentVariables<T> {
return new EnvironmentVariables<T>(...this.filter((envVar) => !envVar.secure()));
}
remove(envVar: T) {
this.splice(this.indexOf(envVar), 1);
}
toJSON() {
return this.map((envVar) => envVar.toJSON());
}
}
applyMixins(EnvironmentVariables, ValidatableMixin);
export interface EnvironmentEnvironmentVariableJSON extends EnvironmentVariableJSON {
origin: OriginJSON;
}
export class EnvironmentVariableWithOrigin extends EnvironmentVariable {
readonly origin: Stream<Origin>;
constructor(name: string, origin: Origin, value?: string, secure?: boolean, encryptedValue?: string) {
super(name, value, secure, encryptedValue);
this.origin = Stream(origin);
}
static fromJSON(data: EnvironmentEnvironmentVariableJSON) {
return new EnvironmentVariableWithOrigin(data.name,
Origin.fromJSON(data.origin),
data.value,
data.secure,
data.encrypted_value);
}
editable() {
return this.origin().type() === OriginType.GoCD;
}
reasonForNonEditable() {
if (this.editable()) {
throw Error("Environment variable is editable");
}
return "Cannot edit this environment variable as it is defined in config repo";
}
clone() {
return new EnvironmentVariableWithOrigin(this.name(),
this.origin().clone(),
this.value(),
this.secure(),
this.encryptedValue().getOriginal());
}
}
export class EnvironmentVariablesWithOrigin extends EnvironmentVariables<EnvironmentVariableWithOrigin> {
static fromJSON(environmentVariables: EnvironmentEnvironmentVariableJSON[]) {
return new EnvironmentVariablesWithOrigin(...environmentVariables.map(EnvironmentVariableWithOrigin.fromJSON));
}
}
|
constructor(name: string, value?: string, secure?: boolean, encryptedValue?: string) {
super();
|
random_line_split
|
types.ts
|
/*
* Copyright 2022 ThoughtWorks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import _ from "lodash";
import Stream from "mithril/stream";
import {applyMixins} from "models/mixins/mixins";
import {ValidatableMixin} from "models/mixins/new_validatable_mixin";
import {Origin, OriginJSON, OriginType} from "models/origin";
import {EncryptedValue} from "views/components/forms/encrypted_value";
export interface EnvironmentVariableJSON {
secure: boolean;
name: string;
value?: string;
encrypted_value?: string;
}
export class EnvironmentVariable extends ValidatableMixin {
secure: Stream<boolean>;
name: Stream<string>;
value: Stream<string | undefined>;
encryptedValue: Stream<EncryptedValue>;
isEditable: Stream<boolean> = Stream<boolean>(true);
nonEditableReason: Stream<string | undefined> = Stream();
constructor(name: string, value?: string, secure?: boolean, encryptedValue?: string) {
super();
this.secure = Stream(secure || false);
this.name = Stream(name);
this.value = Stream(value);
this.encryptedValue = Stream(new EncryptedValue(!_.isEmpty(encryptedValue) ? {cipherText: encryptedValue} : {clearText: value}));
this.validatePresenceOf("name", {condition: () => !_.isEmpty(this.value()) || !_.isEmpty(this.encryptedValue())});
}
static fromJSON(data: EnvironmentVariableJSON) {
return new EnvironmentVariable(data.name, data.value, data.secure, data.encrypted_value);
}
editable() {
return this.isEditable();
}
reasonForNonEditable() {
return this.nonEditableReason();
}
toJSON(): EnvironmentVariableJSON {
// plain text
if (!this.secure()) {
return {
name: this.name(),
value: this.value() || "",
secure: this.secure()
};
}
//secure text
if (this.encryptedValue().isEditing()) {
return {
name: this.name(),
value: this.encryptedValue().value() || "",
secure: this.secure()
};
} else
|
}
equals(environmentVariable: EnvironmentVariable): boolean {
return this.name() === environmentVariable.name()
&& this.value() === environmentVariable.value()
&& this.encryptedValue().value() === environmentVariable.encryptedValue().value();
}
}
//tslint:disable-next-line
export interface EnvironmentVariables extends ValidatableMixin {
}
export class EnvironmentVariables<T extends EnvironmentVariable = EnvironmentVariable> extends Array<T> implements ValidatableMixin {
constructor(...environmentVariables: T[]) {
super(...environmentVariables);
Object.setPrototypeOf(this, Object.create(EnvironmentVariables.prototype));
ValidatableMixin.call(this);
}
static fromJSON(environmentVariables: EnvironmentVariableJSON[]) {
return new EnvironmentVariables(...environmentVariables.map(EnvironmentVariable.fromJSON));
}
secureVariables(): EnvironmentVariables<T> {
return new EnvironmentVariables<T>(...this.filter((envVar) => envVar.secure()));
}
plainTextVariables(): EnvironmentVariables<T> {
return new EnvironmentVariables<T>(...this.filter((envVar) => !envVar.secure()));
}
remove(envVar: T) {
this.splice(this.indexOf(envVar), 1);
}
toJSON() {
return this.map((envVar) => envVar.toJSON());
}
}
applyMixins(EnvironmentVariables, ValidatableMixin);
export interface EnvironmentEnvironmentVariableJSON extends EnvironmentVariableJSON {
origin: OriginJSON;
}
export class EnvironmentVariableWithOrigin extends EnvironmentVariable {
readonly origin: Stream<Origin>;
constructor(name: string, origin: Origin, value?: string, secure?: boolean, encryptedValue?: string) {
super(name, value, secure, encryptedValue);
this.origin = Stream(origin);
}
static fromJSON(data: EnvironmentEnvironmentVariableJSON) {
return new EnvironmentVariableWithOrigin(data.name,
Origin.fromJSON(data.origin),
data.value,
data.secure,
data.encrypted_value);
}
editable() {
return this.origin().type() === OriginType.GoCD;
}
reasonForNonEditable() {
if (this.editable()) {
throw Error("Environment variable is editable");
}
return "Cannot edit this environment variable as it is defined in config repo";
}
clone() {
return new EnvironmentVariableWithOrigin(this.name(),
this.origin().clone(),
this.value(),
this.secure(),
this.encryptedValue().getOriginal());
}
}
export class EnvironmentVariablesWithOrigin extends EnvironmentVariables<EnvironmentVariableWithOrigin> {
static fromJSON(environmentVariables: EnvironmentEnvironmentVariableJSON[]) {
return new EnvironmentVariablesWithOrigin(...environmentVariables.map(EnvironmentVariableWithOrigin.fromJSON));
}
}
|
{
return {
name: this.name(),
encrypted_value: this.encryptedValue().value(),
secure: this.secure()
};
}
|
conditional_block
|
types.ts
|
/*
* Copyright 2022 ThoughtWorks, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import _ from "lodash";
import Stream from "mithril/stream";
import {applyMixins} from "models/mixins/mixins";
import {ValidatableMixin} from "models/mixins/new_validatable_mixin";
import {Origin, OriginJSON, OriginType} from "models/origin";
import {EncryptedValue} from "views/components/forms/encrypted_value";
export interface EnvironmentVariableJSON {
secure: boolean;
name: string;
value?: string;
encrypted_value?: string;
}
export class EnvironmentVariable extends ValidatableMixin {
secure: Stream<boolean>;
name: Stream<string>;
value: Stream<string | undefined>;
encryptedValue: Stream<EncryptedValue>;
isEditable: Stream<boolean> = Stream<boolean>(true);
nonEditableReason: Stream<string | undefined> = Stream();
constructor(name: string, value?: string, secure?: boolean, encryptedValue?: string) {
super();
this.secure = Stream(secure || false);
this.name = Stream(name);
this.value = Stream(value);
this.encryptedValue = Stream(new EncryptedValue(!_.isEmpty(encryptedValue) ? {cipherText: encryptedValue} : {clearText: value}));
this.validatePresenceOf("name", {condition: () => !_.isEmpty(this.value()) || !_.isEmpty(this.encryptedValue())});
}
static fromJSON(data: EnvironmentVariableJSON) {
return new EnvironmentVariable(data.name, data.value, data.secure, data.encrypted_value);
}
editable() {
return this.isEditable();
}
reasonForNonEditable() {
return this.nonEditableReason();
}
toJSON(): EnvironmentVariableJSON {
// plain text
if (!this.secure()) {
return {
name: this.name(),
value: this.value() || "",
secure: this.secure()
};
}
//secure text
if (this.encryptedValue().isEditing()) {
return {
name: this.name(),
value: this.encryptedValue().value() || "",
secure: this.secure()
};
} else {
return {
name: this.name(),
encrypted_value: this.encryptedValue().value(),
secure: this.secure()
};
}
}
equals(environmentVariable: EnvironmentVariable): boolean {
return this.name() === environmentVariable.name()
&& this.value() === environmentVariable.value()
&& this.encryptedValue().value() === environmentVariable.encryptedValue().value();
}
}
//tslint:disable-next-line
export interface EnvironmentVariables extends ValidatableMixin {
}
export class EnvironmentVariables<T extends EnvironmentVariable = EnvironmentVariable> extends Array<T> implements ValidatableMixin {
constructor(...environmentVariables: T[]) {
super(...environmentVariables);
Object.setPrototypeOf(this, Object.create(EnvironmentVariables.prototype));
ValidatableMixin.call(this);
}
static fromJSON(environmentVariables: EnvironmentVariableJSON[]) {
return new EnvironmentVariables(...environmentVariables.map(EnvironmentVariable.fromJSON));
}
secureVariables(): EnvironmentVariables<T> {
return new EnvironmentVariables<T>(...this.filter((envVar) => envVar.secure()));
}
plainTextVariables(): EnvironmentVariables<T> {
return new EnvironmentVariables<T>(...this.filter((envVar) => !envVar.secure()));
}
remove(envVar: T) {
this.splice(this.indexOf(envVar), 1);
}
toJSON() {
return this.map((envVar) => envVar.toJSON());
}
}
applyMixins(EnvironmentVariables, ValidatableMixin);
export interface EnvironmentEnvironmentVariableJSON extends EnvironmentVariableJSON {
origin: OriginJSON;
}
export class
|
extends EnvironmentVariable {
readonly origin: Stream<Origin>;
constructor(name: string, origin: Origin, value?: string, secure?: boolean, encryptedValue?: string) {
super(name, value, secure, encryptedValue);
this.origin = Stream(origin);
}
static fromJSON(data: EnvironmentEnvironmentVariableJSON) {
return new EnvironmentVariableWithOrigin(data.name,
Origin.fromJSON(data.origin),
data.value,
data.secure,
data.encrypted_value);
}
editable() {
return this.origin().type() === OriginType.GoCD;
}
reasonForNonEditable() {
if (this.editable()) {
throw Error("Environment variable is editable");
}
return "Cannot edit this environment variable as it is defined in config repo";
}
clone() {
return new EnvironmentVariableWithOrigin(this.name(),
this.origin().clone(),
this.value(),
this.secure(),
this.encryptedValue().getOriginal());
}
}
export class EnvironmentVariablesWithOrigin extends EnvironmentVariables<EnvironmentVariableWithOrigin> {
static fromJSON(environmentVariables: EnvironmentEnvironmentVariableJSON[]) {
return new EnvironmentVariablesWithOrigin(...environmentVariables.map(EnvironmentVariableWithOrigin.fromJSON));
}
}
|
EnvironmentVariableWithOrigin
|
identifier_name
|
conference.py
|
#!/usr/bin/env python
"""
conference.py -- Udacity conference server-side Python App Engine API;
uses Google Cloud Endpoints
$Id: conference.py,v 1.25 2014/05/24 23:42:19 wesc Exp wesc $
created by wesc on 2014 apr 21
"""
__author__ = '[email protected] (Wesley Chun)'
from datetime import datetime
import endpoints
from protorpc import messages
from protorpc import message_types
from protorpc import remote
from google.appengine.ext import ndb
from models import Profile
from models import ProfileMiniForm
from models import ProfileForm
from models import TeeShirtSize
from settings import WEB_CLIENT_ID
from utils import getUserId
EMAIL_SCOPE = endpoints.EMAIL_SCOPE
API_EXPLORER_CLIENT_ID = endpoints.API_EXPLORER_CLIENT_ID
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
@endpoints.api( name='conference',
version='v1',
allowed_client_ids=[WEB_CLIENT_ID, API_EXPLORER_CLIENT_ID],
scopes=[EMAIL_SCOPE])
class ConferenceApi(remote.Service):
"""Conference API v0.1"""
# - - - Profile objects - - - - - - - - - - - - - - - - - - -
def _copyProfileToForm(self, prof):
"""Copy relevant fields from Profile to ProfileForm."""
# copy relevant fields from Profile to ProfileForm
pf = ProfileForm()
for field in pf.all_fields():
if hasattr(prof, field.name):
# convert t-shirt string to Enum; just copy others
if field.name == 'teeShirtSize':
setattr(pf, field.name, getattr(TeeShirtSize, getattr(prof, field.name)))
else:
setattr(pf, field.name, getattr(prof, field.name))
pf.check_initialized()
return pf
def _getProfileFromUser(self):
"""Return user Profile from datastore, creating new one if non-existent."""
user = endpoints.get_current_user()
if not user:
raise endpoints.UnauthorizedException('Authorization required')
# TODO 1
# step 1. copy utils.py from additions folder to this folder
# and import getUserId from it
# step 2. get user id by calling getUserId(user)
# step 3. create a new key of kind Profile from the id
user_id = getUserId(user)
p_key = ndb.Key(Profile, user_id)
# TODO 3
# get the entity from datastore by using get() on the key
profile = p_key.get()
if not profile:
profile = Profile(
key = p_key, # TODO 1 step 4. replace with the key from step 3
displayName = user.nickname(),
mainEmail= user.email(),
teeShirtSize = str(TeeShirtSize.NOT_SPECIFIED),
)
# TODO 2
# save the profile to datastore
profile.put()
return profile # return Profile
def
|
(self, save_request=None):
"""Get user Profile and return to user, possibly updating it first."""
# get user Profile
prof = self._getProfileFromUser()
# if saveProfile(), process user-modifyable fields
if save_request:
for field in ('displayName', 'teeShirtSize'):
if hasattr(save_request, field):
val = getattr(save_request, field)
if val:
setattr(prof, field, str(val))
# TODO 4
# put the modified profile to datastore
prof.put()
# return ProfileForm
return self._copyProfileToForm(prof)
@endpoints.method(message_types.VoidMessage, ProfileForm,
path='profile', http_method='GET', name='getProfile')
def getProfile(self, request):
"""Return user profile."""
return self._doProfile()
@endpoints.method(ProfileMiniForm, ProfileForm,
path='profile', http_method='POST', name='saveProfile')
def saveProfile(self, request):
"""Update & return user profile."""
return self._doProfile(request)
# registers API
api = endpoints.api_server([ConferenceApi])
|
_doProfile
|
identifier_name
|
conference.py
|
#!/usr/bin/env python
"""
conference.py -- Udacity conference server-side Python App Engine API;
uses Google Cloud Endpoints
$Id: conference.py,v 1.25 2014/05/24 23:42:19 wesc Exp wesc $
created by wesc on 2014 apr 21
"""
__author__ = '[email protected] (Wesley Chun)'
from datetime import datetime
import endpoints
from protorpc import messages
from protorpc import message_types
from protorpc import remote
from google.appengine.ext import ndb
from models import Profile
from models import ProfileMiniForm
from models import ProfileForm
from models import TeeShirtSize
from settings import WEB_CLIENT_ID
from utils import getUserId
EMAIL_SCOPE = endpoints.EMAIL_SCOPE
API_EXPLORER_CLIENT_ID = endpoints.API_EXPLORER_CLIENT_ID
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
@endpoints.api( name='conference',
version='v1',
allowed_client_ids=[WEB_CLIENT_ID, API_EXPLORER_CLIENT_ID],
scopes=[EMAIL_SCOPE])
class ConferenceApi(remote.Service):
"""Conference API v0.1"""
# - - - Profile objects - - - - - - - - - - - - - - - - - - -
def _copyProfileToForm(self, prof):
"""Copy relevant fields from Profile to ProfileForm."""
# copy relevant fields from Profile to ProfileForm
pf = ProfileForm()
for field in pf.all_fields():
if hasattr(prof, field.name):
# convert t-shirt string to Enum; just copy others
|
pf.check_initialized()
return pf
def _getProfileFromUser(self):
"""Return user Profile from datastore, creating new one if non-existent."""
user = endpoints.get_current_user()
if not user:
raise endpoints.UnauthorizedException('Authorization required')
# TODO 1
# step 1. copy utils.py from additions folder to this folder
# and import getUserId from it
# step 2. get user id by calling getUserId(user)
# step 3. create a new key of kind Profile from the id
user_id = getUserId(user)
p_key = ndb.Key(Profile, user_id)
# TODO 3
# get the entity from datastore by using get() on the key
profile = p_key.get()
if not profile:
profile = Profile(
key = p_key, # TODO 1 step 4. replace with the key from step 3
displayName = user.nickname(),
mainEmail= user.email(),
teeShirtSize = str(TeeShirtSize.NOT_SPECIFIED),
)
# TODO 2
# save the profile to datastore
profile.put()
return profile # return Profile
def _doProfile(self, save_request=None):
"""Get user Profile and return to user, possibly updating it first."""
# get user Profile
prof = self._getProfileFromUser()
# if saveProfile(), process user-modifyable fields
if save_request:
for field in ('displayName', 'teeShirtSize'):
if hasattr(save_request, field):
val = getattr(save_request, field)
if val:
setattr(prof, field, str(val))
# TODO 4
# put the modified profile to datastore
prof.put()
# return ProfileForm
return self._copyProfileToForm(prof)
@endpoints.method(message_types.VoidMessage, ProfileForm,
path='profile', http_method='GET', name='getProfile')
def getProfile(self, request):
"""Return user profile."""
return self._doProfile()
@endpoints.method(ProfileMiniForm, ProfileForm,
path='profile', http_method='POST', name='saveProfile')
def saveProfile(self, request):
"""Update & return user profile."""
return self._doProfile(request)
# registers API
api = endpoints.api_server([ConferenceApi])
|
if field.name == 'teeShirtSize':
setattr(pf, field.name, getattr(TeeShirtSize, getattr(prof, field.name)))
else:
setattr(pf, field.name, getattr(prof, field.name))
|
conditional_block
|
conference.py
|
#!/usr/bin/env python
"""
conference.py -- Udacity conference server-side Python App Engine API;
uses Google Cloud Endpoints
$Id: conference.py,v 1.25 2014/05/24 23:42:19 wesc Exp wesc $
created by wesc on 2014 apr 21
|
"""
__author__ = '[email protected] (Wesley Chun)'
from datetime import datetime
import endpoints
from protorpc import messages
from protorpc import message_types
from protorpc import remote
from google.appengine.ext import ndb
from models import Profile
from models import ProfileMiniForm
from models import ProfileForm
from models import TeeShirtSize
from settings import WEB_CLIENT_ID
from utils import getUserId
EMAIL_SCOPE = endpoints.EMAIL_SCOPE
API_EXPLORER_CLIENT_ID = endpoints.API_EXPLORER_CLIENT_ID
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
@endpoints.api( name='conference',
version='v1',
allowed_client_ids=[WEB_CLIENT_ID, API_EXPLORER_CLIENT_ID],
scopes=[EMAIL_SCOPE])
class ConferenceApi(remote.Service):
"""Conference API v0.1"""
# - - - Profile objects - - - - - - - - - - - - - - - - - - -
def _copyProfileToForm(self, prof):
"""Copy relevant fields from Profile to ProfileForm."""
# copy relevant fields from Profile to ProfileForm
pf = ProfileForm()
for field in pf.all_fields():
if hasattr(prof, field.name):
# convert t-shirt string to Enum; just copy others
if field.name == 'teeShirtSize':
setattr(pf, field.name, getattr(TeeShirtSize, getattr(prof, field.name)))
else:
setattr(pf, field.name, getattr(prof, field.name))
pf.check_initialized()
return pf
def _getProfileFromUser(self):
"""Return user Profile from datastore, creating new one if non-existent."""
user = endpoints.get_current_user()
if not user:
raise endpoints.UnauthorizedException('Authorization required')
# TODO 1
# step 1. copy utils.py from additions folder to this folder
# and import getUserId from it
# step 2. get user id by calling getUserId(user)
# step 3. create a new key of kind Profile from the id
user_id = getUserId(user)
p_key = ndb.Key(Profile, user_id)
# TODO 3
# get the entity from datastore by using get() on the key
profile = p_key.get()
if not profile:
profile = Profile(
key = p_key, # TODO 1 step 4. replace with the key from step 3
displayName = user.nickname(),
mainEmail= user.email(),
teeShirtSize = str(TeeShirtSize.NOT_SPECIFIED),
)
# TODO 2
# save the profile to datastore
profile.put()
return profile # return Profile
def _doProfile(self, save_request=None):
"""Get user Profile and return to user, possibly updating it first."""
# get user Profile
prof = self._getProfileFromUser()
# if saveProfile(), process user-modifyable fields
if save_request:
for field in ('displayName', 'teeShirtSize'):
if hasattr(save_request, field):
val = getattr(save_request, field)
if val:
setattr(prof, field, str(val))
# TODO 4
# put the modified profile to datastore
prof.put()
# return ProfileForm
return self._copyProfileToForm(prof)
@endpoints.method(message_types.VoidMessage, ProfileForm,
path='profile', http_method='GET', name='getProfile')
def getProfile(self, request):
"""Return user profile."""
return self._doProfile()
@endpoints.method(ProfileMiniForm, ProfileForm,
path='profile', http_method='POST', name='saveProfile')
def saveProfile(self, request):
"""Update & return user profile."""
return self._doProfile(request)
# registers API
api = endpoints.api_server([ConferenceApi])
|
random_line_split
|
|
conference.py
|
#!/usr/bin/env python
"""
conference.py -- Udacity conference server-side Python App Engine API;
uses Google Cloud Endpoints
$Id: conference.py,v 1.25 2014/05/24 23:42:19 wesc Exp wesc $
created by wesc on 2014 apr 21
"""
__author__ = '[email protected] (Wesley Chun)'
from datetime import datetime
import endpoints
from protorpc import messages
from protorpc import message_types
from protorpc import remote
from google.appengine.ext import ndb
from models import Profile
from models import ProfileMiniForm
from models import ProfileForm
from models import TeeShirtSize
from settings import WEB_CLIENT_ID
from utils import getUserId
EMAIL_SCOPE = endpoints.EMAIL_SCOPE
API_EXPLORER_CLIENT_ID = endpoints.API_EXPLORER_CLIENT_ID
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
@endpoints.api( name='conference',
version='v1',
allowed_client_ids=[WEB_CLIENT_ID, API_EXPLORER_CLIENT_ID],
scopes=[EMAIL_SCOPE])
class ConferenceApi(remote.Service):
"""Conference API v0.1"""
# - - - Profile objects - - - - - - - - - - - - - - - - - - -
def _copyProfileToForm(self, prof):
"""Copy relevant fields from Profile to ProfileForm."""
# copy relevant fields from Profile to ProfileForm
pf = ProfileForm()
for field in pf.all_fields():
if hasattr(prof, field.name):
# convert t-shirt string to Enum; just copy others
if field.name == 'teeShirtSize':
setattr(pf, field.name, getattr(TeeShirtSize, getattr(prof, field.name)))
else:
setattr(pf, field.name, getattr(prof, field.name))
pf.check_initialized()
return pf
def _getProfileFromUser(self):
"""Return user Profile from datastore, creating new one if non-existent."""
user = endpoints.get_current_user()
if not user:
raise endpoints.UnauthorizedException('Authorization required')
# TODO 1
# step 1. copy utils.py from additions folder to this folder
# and import getUserId from it
# step 2. get user id by calling getUserId(user)
# step 3. create a new key of kind Profile from the id
user_id = getUserId(user)
p_key = ndb.Key(Profile, user_id)
# TODO 3
# get the entity from datastore by using get() on the key
profile = p_key.get()
if not profile:
profile = Profile(
key = p_key, # TODO 1 step 4. replace with the key from step 3
displayName = user.nickname(),
mainEmail= user.email(),
teeShirtSize = str(TeeShirtSize.NOT_SPECIFIED),
)
# TODO 2
# save the profile to datastore
profile.put()
return profile # return Profile
def _doProfile(self, save_request=None):
"""Get user Profile and return to user, possibly updating it first."""
# get user Profile
prof = self._getProfileFromUser()
# if saveProfile(), process user-modifyable fields
if save_request:
for field in ('displayName', 'teeShirtSize'):
if hasattr(save_request, field):
val = getattr(save_request, field)
if val:
setattr(prof, field, str(val))
# TODO 4
# put the modified profile to datastore
prof.put()
# return ProfileForm
return self._copyProfileToForm(prof)
@endpoints.method(message_types.VoidMessage, ProfileForm,
path='profile', http_method='GET', name='getProfile')
def getProfile(self, request):
|
@endpoints.method(ProfileMiniForm, ProfileForm,
path='profile', http_method='POST', name='saveProfile')
def saveProfile(self, request):
"""Update & return user profile."""
return self._doProfile(request)
# registers API
api = endpoints.api_server([ConferenceApi])
|
"""Return user profile."""
return self._doProfile()
|
identifier_body
|
index.d.ts
|
// Generated by typings
// Source: https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/56295f5058cac7ae458540423c50ac2dcf9fc711/gulp-util/gulp-util.d.ts
// Type definitions for gulp-util v3.0.x
// Project: https://github.com/gulpjs/gulp-util
// Definitions by: jedmao <https://github.com/jedmao>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module 'gulp-util' {
import vinyl = require('vinyl');
import chalk = require('chalk');
import through2 = require('through2');
export class File extends vinyl { }
/**
* Replaces a file extension in a path. Returns the new path.
*/
export function replaceExtension(npath: string, ext: string): string;
export var colors: typeof chalk;
|
(now?: Date, mask?: string, convertLocalTimeToUTC?: boolean): any;
(date?: string, mask?: string, convertLocalTimeToUTC?: boolean): any;
masks: any;
};
/**
* Logs stuff. Already prefixed with [gulp] and all that. Use the right colors
* for values. If you pass in multiple arguments it will join them by a space.
*/
export function log(message?: any, ...optionalParams: any[]): void;
/**
* This is a lodash.template function wrapper. You must pass in a valid gulp
* file object so it is available to the user or it will error. You can not
* configure any of the delimiters. Look at the lodash docs for more info.
*/
export function template(tmpl: string): (opt: { file: { path: string } }) => string;
export function template(tmpl: string, opt: { file: { path: string } }): string;
export var env: any;
export function beep(): void;
/**
* Returns a stream that does nothing but pass data straight through.
*/
export var noop: typeof through2;
export function isStream(obj: any): boolean;
export function isBuffer(obj: any): boolean;
export function isNull(obj: any): boolean;
export var linefeed: string;
export function combine(streams: NodeJS.ReadWriteStream[]): () => NodeJS.ReadWriteStream;
export function combine(...streams: NodeJS.ReadWriteStream[]): () => NodeJS.ReadWriteStream;
/**
* This is similar to es.wait but instead of buffering text into one string
* it buffers anything into an array (so very useful for file objects).
*/
export function buffer(cb?: (err: Error, data: any[]) => void): NodeJS.ReadWriteStream;
export class PluginError implements Error, PluginErrorOptions {
constructor(options?: PluginErrorOptions);
constructor(pluginName: string, options?: PluginErrorOptions);
constructor(pluginName: string, message: string, options?: PluginErrorOptions);
constructor(pluginName: string, message: Error, options?: PluginErrorOptions);
/**
* The module name of your plugin.
*/
name: string;
/**
* Can be a string or an existing error.
*/
message: any;
fileName: string;
lineNumber: number;
/**
* You need to include the message along with this stack. If you pass an
* error in as the message the stack will be pulled from that, otherwise one
* will be created.
*/
stack: string;
/**
* By default the stack will not be shown. Set this to true if you think the
* stack is important for your error.
*/
showStack: boolean;
/**
* Error properties will be included in err.toString(). Can be omitted by
* setting this to false.
*/
showProperties: boolean;
plugin: string;
error: Error;
}
}
interface PluginErrorOptions {
/**
* The module name of your plugin.
*/
name?: string;
/**
* Can be a string or an existing error.
*/
message?: any;
fileName?: string;
lineNumber?: number;
/**
* You need to include the message along with this stack. If you pass an
* error in as the message the stack will be pulled from that, otherwise one
* will be created.
*/
stack?: string;
/**
* By default the stack will not be shown. Set this to true if you think the
* stack is important for your error.
*/
showStack?: boolean;
/**
* Error properties will be included in err.toString(). Can be omitted by
* setting this to false.
*/
showProperties?: boolean;
plugin?: string;
error?: Error;
}
|
export var date: {
|
random_line_split
|
index.d.ts
|
// Generated by typings
// Source: https://raw.githubusercontent.com/DefinitelyTyped/DefinitelyTyped/56295f5058cac7ae458540423c50ac2dcf9fc711/gulp-util/gulp-util.d.ts
// Type definitions for gulp-util v3.0.x
// Project: https://github.com/gulpjs/gulp-util
// Definitions by: jedmao <https://github.com/jedmao>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
declare module 'gulp-util' {
import vinyl = require('vinyl');
import chalk = require('chalk');
import through2 = require('through2');
export class File extends vinyl { }
/**
* Replaces a file extension in a path. Returns the new path.
*/
export function replaceExtension(npath: string, ext: string): string;
export var colors: typeof chalk;
export var date: {
(now?: Date, mask?: string, convertLocalTimeToUTC?: boolean): any;
(date?: string, mask?: string, convertLocalTimeToUTC?: boolean): any;
masks: any;
};
/**
* Logs stuff. Already prefixed with [gulp] and all that. Use the right colors
* for values. If you pass in multiple arguments it will join them by a space.
*/
export function log(message?: any, ...optionalParams: any[]): void;
/**
* This is a lodash.template function wrapper. You must pass in a valid gulp
* file object so it is available to the user or it will error. You can not
* configure any of the delimiters. Look at the lodash docs for more info.
*/
export function template(tmpl: string): (opt: { file: { path: string } }) => string;
export function template(tmpl: string, opt: { file: { path: string } }): string;
export var env: any;
export function beep(): void;
/**
* Returns a stream that does nothing but pass data straight through.
*/
export var noop: typeof through2;
export function isStream(obj: any): boolean;
export function isBuffer(obj: any): boolean;
export function isNull(obj: any): boolean;
export var linefeed: string;
export function combine(streams: NodeJS.ReadWriteStream[]): () => NodeJS.ReadWriteStream;
export function combine(...streams: NodeJS.ReadWriteStream[]): () => NodeJS.ReadWriteStream;
/**
* This is similar to es.wait but instead of buffering text into one string
* it buffers anything into an array (so very useful for file objects).
*/
export function buffer(cb?: (err: Error, data: any[]) => void): NodeJS.ReadWriteStream;
export class
|
implements Error, PluginErrorOptions {
constructor(options?: PluginErrorOptions);
constructor(pluginName: string, options?: PluginErrorOptions);
constructor(pluginName: string, message: string, options?: PluginErrorOptions);
constructor(pluginName: string, message: Error, options?: PluginErrorOptions);
/**
* The module name of your plugin.
*/
name: string;
/**
* Can be a string or an existing error.
*/
message: any;
fileName: string;
lineNumber: number;
/**
* You need to include the message along with this stack. If you pass an
* error in as the message the stack will be pulled from that, otherwise one
* will be created.
*/
stack: string;
/**
* By default the stack will not be shown. Set this to true if you think the
* stack is important for your error.
*/
showStack: boolean;
/**
* Error properties will be included in err.toString(). Can be omitted by
* setting this to false.
*/
showProperties: boolean;
plugin: string;
error: Error;
}
}
interface PluginErrorOptions {
/**
* The module name of your plugin.
*/
name?: string;
/**
* Can be a string or an existing error.
*/
message?: any;
fileName?: string;
lineNumber?: number;
/**
* You need to include the message along with this stack. If you pass an
* error in as the message the stack will be pulled from that, otherwise one
* will be created.
*/
stack?: string;
/**
* By default the stack will not be shown. Set this to true if you think the
* stack is important for your error.
*/
showStack?: boolean;
/**
* Error properties will be included in err.toString(). Can be omitted by
* setting this to false.
*/
showProperties?: boolean;
plugin?: string;
error?: Error;
}
|
PluginError
|
identifier_name
|
arrayConfigurationTools.py
|
#!/usr/bin/python
"""
S. Leon @ ALMA
Classes, functions to be used for the array configuration evaluation with CASA
HISTORY:
2011.11.06:
- class to create the Casas pads file from a configuration file
2011.11.09:
- Class to compute statistics on the baselines
2012.03.07L:
- Class to manipulate the visibilities
2012.05.22:
- Change name of ArrayStatistics
- add plotAntPos
2012.11.30:
- Modification of createCasaConfig from a list of Pads (not a file)
2013.03.22:
- Modification of createCasaConfig to read as well from a file
2013.04.19:
- Update Arrayinfo.stats to get the information in the instance.
2013.04.20:
- Put the padPositionfile as a parameter
2013.09.13:
- fix a CASA problem
RUN:
## Create a CASA file
a=ArrayConfigurationCasaFile()
a.createCasaConfig("/home/stephane/alma/ArrayConfig/Cycle1/configurations/cycle1_config.txt")
CASA> :
sys.path.insert(0,'/home/stephane/git/ALMA/ALMA/ArrayConfiguration/')
"""
__version__="[email protected]"
__author__ ="ALMA: SL"
import numpy as np
import os
import pickle
from math import sqrt
import pylab as pl
home = os.environ['WTO']
class ArrayConfigurationCasaFile:
"""
Class to create the CASA configuration file matching the Pads and the positions
"""
def __init__(self, padPositionFile = home + "conf/Pads.cfg"):
self.padPositionFile = padPositionFile
self.pad={}
self.__readPadPosition__()
def __readPadPosition__(self):
"Read the position of all the Pads and put them in a Dictionary"
padFile=open(self.padPositionFile,"r")
dump=padFile.readline()
while(dump != ""):
if dump[0] !="#":
padsplt=dump.split()
self.pad[padsplt[4]]=[padsplt[0],padsplt[1],padsplt[2],padsplt[3]]
dump=padFile.readline()
padFile.close()
def createCasaConfig(self,configurationFile,listPads = []):
"""
If listPads is not empty, it will use configurationFile to create the CASA file.
"""
# Creating the array config files
headerCasa="# observatory=ALMA\n"
headerCasa+="# coordsys=LOC (local tangent plane)\n"
headerCasa+="# x y z diam pad#\n"
## Read the Pads in configurationFile if listPads is empty
if len(listPads) == 0:
listPads = []
fin = open(configurationFile)
for pad in fin:
dat = pad.split()
listPads.append(dat[0])
fin.close
configurationFile +=".cfg"
f = open(configurationFile,"w")
f.write(headerCasa)
for pads in listPads:
line=""
for s in self.pad[pads]:
line += s+" "
line+=pads
line+="\n"
f.write(line)
print "### %s created."%(configurationFile)
f.close()
class ArrayInfo:
"""
Compute the Statistics from a CASA array file.
max baseline, min baseline, rms, etc...
"""
def __init__(self,filename):
self.filename=filename
self.xPos = []
self.yPos = []
self.antName = []
self.__readFileArray__()
def __readFileArray__(self):
"Read the CASA file array and create the self.baseline array"
f=open(self.filename)
dump=f.readline()
while dump[0] == "#":
dump=f.readline()
ant=[]
xMean = 0.
yMean = 0.
while dump != "":
dataAnt=dump.split()
if dataAnt[0][0] != '#':
ant.append([float(dataAnt[0]),float(dataAnt[1])])
self.xPos.append(float(dataAnt[0]))
self.yPos.append(float(dataAnt[1]))
self.antName.append(dataAnt[4])
xMean += float(dataAnt[0])
yMean += float(dataAnt[1])
dump=f.readline()
nAnt=len(ant)
xMean = xMean / nAnt
yMean = yMean / nAnt
self.xMean = xMean
self.yMean = yMean
for i in range(nAnt):
self.xPos[i] -= xMean
self.yPos[i] -= yMean
nBl=(nAnt*(nAnt-1))/2
self.baseline=np.zeros(nBl,np.float32)
indexBl=0
for i in range(0,nAnt):
for j in range(i+1,nAnt):
blij2=(ant[i][0]-ant[j][0])*(ant[i][0]-ant[j][0])+(ant[i][1]-ant[j][1])*(ant[i][1]-ant[j][1])
self.baseline[indexBl]=sqrt(blij2)
indexBl+=1
print "Number of baselines: %d"%(nBl)
def stats(self):
"compute the statistics on self.baseline"
self.minBl=np.amin(self.baseline)
self.maxBl=np.amax(self.baseline)
bl2=self.baseline*self.baseline
self.rms=sqrt(np.average(bl2))
print "Array: %s"%(self.filename)
print "x Pos. Mean:%f"%(self.xMean)
print "y Pos. Mean:%f"%(self.yMean)
print "Min. baseline:%f"%(self.minBl)
print "Max. baseline:%f"%(self.maxBl)
print "RMS of the baselines:%f"%(self.rms)
print "\n"
def plotAntPos(self,xmin=-100,xmax=100,ymin=-100.,ymax=100,title='ALMA',xtitle=75.,ytitle=75.,figure=None):
"plot the positions of the antennas"
fig = pl.figure()
ax = fig.add_subplot('111')
ax.plot(self.xPos,self.yPos,'ro',markersize = 10.)
index = 0
for name in self.antName:
xx = self.xPos[index]
yy = self.yPos[index]
ax.text(xx,yy,name)
index += 1
ax.set_xlabel('X (meter)')
ax.set_ylabel('Y (meter)')
ax.set_xlim((xmin,xmax))
ax.set_ylim((ymin,ymax))
ax.text(xtitle,ytitle,title)
# pl.show()
if figure != None:
pl.savefig(figure)
class visibility:
def __init__(self,visname):
self.visname = visname
|
if __name__=="__main__":
" main program"
## a=ArrayConfigurationCasaFile()
## a.createCasaConfig("/home/stephane/alma/ArrayConfig/Cycle1/configurations/cycle1_config.txt")
|
########################Main program####################################
|
random_line_split
|
arrayConfigurationTools.py
|
#!/usr/bin/python
"""
S. Leon @ ALMA
Classes, functions to be used for the array configuration evaluation with CASA
HISTORY:
2011.11.06:
- class to create the Casas pads file from a configuration file
2011.11.09:
- Class to compute statistics on the baselines
2012.03.07L:
- Class to manipulate the visibilities
2012.05.22:
- Change name of ArrayStatistics
- add plotAntPos
2012.11.30:
- Modification of createCasaConfig from a list of Pads (not a file)
2013.03.22:
- Modification of createCasaConfig to read as well from a file
2013.04.19:
- Update Arrayinfo.stats to get the information in the instance.
2013.04.20:
- Put the padPositionfile as a parameter
2013.09.13:
- fix a CASA problem
RUN:
## Create a CASA file
a=ArrayConfigurationCasaFile()
a.createCasaConfig("/home/stephane/alma/ArrayConfig/Cycle1/configurations/cycle1_config.txt")
CASA> :
sys.path.insert(0,'/home/stephane/git/ALMA/ALMA/ArrayConfiguration/')
"""
__version__="[email protected]"
__author__ ="ALMA: SL"
import numpy as np
import os
import pickle
from math import sqrt
import pylab as pl
home = os.environ['WTO']
class ArrayConfigurationCasaFile:
"""
Class to create the CASA configuration file matching the Pads and the positions
"""
def __init__(self, padPositionFile = home + "conf/Pads.cfg"):
self.padPositionFile = padPositionFile
self.pad={}
self.__readPadPosition__()
def __readPadPosition__(self):
"Read the position of all the Pads and put them in a Dictionary"
padFile=open(self.padPositionFile,"r")
dump=padFile.readline()
while(dump != ""):
if dump[0] !="#":
padsplt=dump.split()
self.pad[padsplt[4]]=[padsplt[0],padsplt[1],padsplt[2],padsplt[3]]
dump=padFile.readline()
padFile.close()
def createCasaConfig(self,configurationFile,listPads = []):
"""
If listPads is not empty, it will use configurationFile to create the CASA file.
"""
# Creating the array config files
headerCasa="# observatory=ALMA\n"
headerCasa+="# coordsys=LOC (local tangent plane)\n"
headerCasa+="# x y z diam pad#\n"
## Read the Pads in configurationFile if listPads is empty
if len(listPads) == 0:
listPads = []
fin = open(configurationFile)
for pad in fin:
dat = pad.split()
listPads.append(dat[0])
fin.close
configurationFile +=".cfg"
f = open(configurationFile,"w")
f.write(headerCasa)
for pads in listPads:
line=""
for s in self.pad[pads]:
line += s+" "
line+=pads
line+="\n"
f.write(line)
print "### %s created."%(configurationFile)
f.close()
class ArrayInfo:
"""
Compute the Statistics from a CASA array file.
max baseline, min baseline, rms, etc...
"""
def __init__(self,filename):
self.filename=filename
self.xPos = []
self.yPos = []
self.antName = []
self.__readFileArray__()
def __readFileArray__(self):
"Read the CASA file array and create the self.baseline array"
f=open(self.filename)
dump=f.readline()
while dump[0] == "#":
dump=f.readline()
ant=[]
xMean = 0.
yMean = 0.
while dump != "":
dataAnt=dump.split()
if dataAnt[0][0] != '#':
ant.append([float(dataAnt[0]),float(dataAnt[1])])
self.xPos.append(float(dataAnt[0]))
self.yPos.append(float(dataAnt[1]))
self.antName.append(dataAnt[4])
xMean += float(dataAnt[0])
yMean += float(dataAnt[1])
dump=f.readline()
nAnt=len(ant)
xMean = xMean / nAnt
yMean = yMean / nAnt
self.xMean = xMean
self.yMean = yMean
for i in range(nAnt):
self.xPos[i] -= xMean
self.yPos[i] -= yMean
nBl=(nAnt*(nAnt-1))/2
self.baseline=np.zeros(nBl,np.float32)
indexBl=0
for i in range(0,nAnt):
for j in range(i+1,nAnt):
blij2=(ant[i][0]-ant[j][0])*(ant[i][0]-ant[j][0])+(ant[i][1]-ant[j][1])*(ant[i][1]-ant[j][1])
self.baseline[indexBl]=sqrt(blij2)
indexBl+=1
print "Number of baselines: %d"%(nBl)
def stats(self):
"compute the statistics on self.baseline"
self.minBl=np.amin(self.baseline)
self.maxBl=np.amax(self.baseline)
bl2=self.baseline*self.baseline
self.rms=sqrt(np.average(bl2))
print "Array: %s"%(self.filename)
print "x Pos. Mean:%f"%(self.xMean)
print "y Pos. Mean:%f"%(self.yMean)
print "Min. baseline:%f"%(self.minBl)
print "Max. baseline:%f"%(self.maxBl)
print "RMS of the baselines:%f"%(self.rms)
print "\n"
def plotAntPos(self,xmin=-100,xmax=100,ymin=-100.,ymax=100,title='ALMA',xtitle=75.,ytitle=75.,figure=None):
"plot the positions of the antennas"
fig = pl.figure()
ax = fig.add_subplot('111')
ax.plot(self.xPos,self.yPos,'ro',markersize = 10.)
index = 0
for name in self.antName:
xx = self.xPos[index]
yy = self.yPos[index]
ax.text(xx,yy,name)
index += 1
ax.set_xlabel('X (meter)')
ax.set_ylabel('Y (meter)')
ax.set_xlim((xmin,xmax))
ax.set_ylim((ymin,ymax))
ax.text(xtitle,ytitle,title)
# pl.show()
if figure != None:
pl.savefig(figure)
class visibility:
def
|
(self,visname):
self.visname = visname
########################Main program####################################
if __name__=="__main__":
" main program"
## a=ArrayConfigurationCasaFile()
## a.createCasaConfig("/home/stephane/alma/ArrayConfig/Cycle1/configurations/cycle1_config.txt")
|
__init__
|
identifier_name
|
arrayConfigurationTools.py
|
#!/usr/bin/python
"""
S. Leon @ ALMA
Classes, functions to be used for the array configuration evaluation with CASA
HISTORY:
2011.11.06:
- class to create the Casas pads file from a configuration file
2011.11.09:
- Class to compute statistics on the baselines
2012.03.07L:
- Class to manipulate the visibilities
2012.05.22:
- Change name of ArrayStatistics
- add plotAntPos
2012.11.30:
- Modification of createCasaConfig from a list of Pads (not a file)
2013.03.22:
- Modification of createCasaConfig to read as well from a file
2013.04.19:
- Update Arrayinfo.stats to get the information in the instance.
2013.04.20:
- Put the padPositionfile as a parameter
2013.09.13:
- fix a CASA problem
RUN:
## Create a CASA file
a=ArrayConfigurationCasaFile()
a.createCasaConfig("/home/stephane/alma/ArrayConfig/Cycle1/configurations/cycle1_config.txt")
CASA> :
sys.path.insert(0,'/home/stephane/git/ALMA/ALMA/ArrayConfiguration/')
"""
__version__="[email protected]"
__author__ ="ALMA: SL"
import numpy as np
import os
import pickle
from math import sqrt
import pylab as pl
home = os.environ['WTO']
class ArrayConfigurationCasaFile:
"""
Class to create the CASA configuration file matching the Pads and the positions
"""
def __init__(self, padPositionFile = home + "conf/Pads.cfg"):
self.padPositionFile = padPositionFile
self.pad={}
self.__readPadPosition__()
def __readPadPosition__(self):
"Read the position of all the Pads and put them in a Dictionary"
padFile=open(self.padPositionFile,"r")
dump=padFile.readline()
while(dump != ""):
if dump[0] !="#":
|
dump=padFile.readline()
padFile.close()
def createCasaConfig(self,configurationFile,listPads = []):
"""
If listPads is not empty, it will use configurationFile to create the CASA file.
"""
# Creating the array config files
headerCasa="# observatory=ALMA\n"
headerCasa+="# coordsys=LOC (local tangent plane)\n"
headerCasa+="# x y z diam pad#\n"
## Read the Pads in configurationFile if listPads is empty
if len(listPads) == 0:
listPads = []
fin = open(configurationFile)
for pad in fin:
dat = pad.split()
listPads.append(dat[0])
fin.close
configurationFile +=".cfg"
f = open(configurationFile,"w")
f.write(headerCasa)
for pads in listPads:
line=""
for s in self.pad[pads]:
line += s+" "
line+=pads
line+="\n"
f.write(line)
print "### %s created."%(configurationFile)
f.close()
class ArrayInfo:
"""
Compute the Statistics from a CASA array file.
max baseline, min baseline, rms, etc...
"""
def __init__(self,filename):
self.filename=filename
self.xPos = []
self.yPos = []
self.antName = []
self.__readFileArray__()
def __readFileArray__(self):
"Read the CASA file array and create the self.baseline array"
f=open(self.filename)
dump=f.readline()
while dump[0] == "#":
dump=f.readline()
ant=[]
xMean = 0.
yMean = 0.
while dump != "":
dataAnt=dump.split()
if dataAnt[0][0] != '#':
ant.append([float(dataAnt[0]),float(dataAnt[1])])
self.xPos.append(float(dataAnt[0]))
self.yPos.append(float(dataAnt[1]))
self.antName.append(dataAnt[4])
xMean += float(dataAnt[0])
yMean += float(dataAnt[1])
dump=f.readline()
nAnt=len(ant)
xMean = xMean / nAnt
yMean = yMean / nAnt
self.xMean = xMean
self.yMean = yMean
for i in range(nAnt):
self.xPos[i] -= xMean
self.yPos[i] -= yMean
nBl=(nAnt*(nAnt-1))/2
self.baseline=np.zeros(nBl,np.float32)
indexBl=0
for i in range(0,nAnt):
for j in range(i+1,nAnt):
blij2=(ant[i][0]-ant[j][0])*(ant[i][0]-ant[j][0])+(ant[i][1]-ant[j][1])*(ant[i][1]-ant[j][1])
self.baseline[indexBl]=sqrt(blij2)
indexBl+=1
print "Number of baselines: %d"%(nBl)
def stats(self):
"compute the statistics on self.baseline"
self.minBl=np.amin(self.baseline)
self.maxBl=np.amax(self.baseline)
bl2=self.baseline*self.baseline
self.rms=sqrt(np.average(bl2))
print "Array: %s"%(self.filename)
print "x Pos. Mean:%f"%(self.xMean)
print "y Pos. Mean:%f"%(self.yMean)
print "Min. baseline:%f"%(self.minBl)
print "Max. baseline:%f"%(self.maxBl)
print "RMS of the baselines:%f"%(self.rms)
print "\n"
def plotAntPos(self,xmin=-100,xmax=100,ymin=-100.,ymax=100,title='ALMA',xtitle=75.,ytitle=75.,figure=None):
"plot the positions of the antennas"
fig = pl.figure()
ax = fig.add_subplot('111')
ax.plot(self.xPos,self.yPos,'ro',markersize = 10.)
index = 0
for name in self.antName:
xx = self.xPos[index]
yy = self.yPos[index]
ax.text(xx,yy,name)
index += 1
ax.set_xlabel('X (meter)')
ax.set_ylabel('Y (meter)')
ax.set_xlim((xmin,xmax))
ax.set_ylim((ymin,ymax))
ax.text(xtitle,ytitle,title)
# pl.show()
if figure != None:
pl.savefig(figure)
class visibility:
def __init__(self,visname):
self.visname = visname
########################Main program####################################
if __name__=="__main__":
" main program"
## a=ArrayConfigurationCasaFile()
## a.createCasaConfig("/home/stephane/alma/ArrayConfig/Cycle1/configurations/cycle1_config.txt")
|
padsplt=dump.split()
self.pad[padsplt[4]]=[padsplt[0],padsplt[1],padsplt[2],padsplt[3]]
|
conditional_block
|
arrayConfigurationTools.py
|
#!/usr/bin/python
"""
S. Leon @ ALMA
Classes, functions to be used for the array configuration evaluation with CASA
HISTORY:
2011.11.06:
- class to create the Casas pads file from a configuration file
2011.11.09:
- Class to compute statistics on the baselines
2012.03.07L:
- Class to manipulate the visibilities
2012.05.22:
- Change name of ArrayStatistics
- add plotAntPos
2012.11.30:
- Modification of createCasaConfig from a list of Pads (not a file)
2013.03.22:
- Modification of createCasaConfig to read as well from a file
2013.04.19:
- Update Arrayinfo.stats to get the information in the instance.
2013.04.20:
- Put the padPositionfile as a parameter
2013.09.13:
- fix a CASA problem
RUN:
## Create a CASA file
a=ArrayConfigurationCasaFile()
a.createCasaConfig("/home/stephane/alma/ArrayConfig/Cycle1/configurations/cycle1_config.txt")
CASA> :
sys.path.insert(0,'/home/stephane/git/ALMA/ALMA/ArrayConfiguration/')
"""
__version__="[email protected]"
__author__ ="ALMA: SL"
import numpy as np
import os
import pickle
from math import sqrt
import pylab as pl
home = os.environ['WTO']
class ArrayConfigurationCasaFile:
"""
Class to create the CASA configuration file matching the Pads and the positions
"""
def __init__(self, padPositionFile = home + "conf/Pads.cfg"):
|
def __readPadPosition__(self):
"Read the position of all the Pads and put them in a Dictionary"
padFile=open(self.padPositionFile,"r")
dump=padFile.readline()
while(dump != ""):
if dump[0] !="#":
padsplt=dump.split()
self.pad[padsplt[4]]=[padsplt[0],padsplt[1],padsplt[2],padsplt[3]]
dump=padFile.readline()
padFile.close()
def createCasaConfig(self,configurationFile,listPads = []):
"""
If listPads is not empty, it will use configurationFile to create the CASA file.
"""
# Creating the array config files
headerCasa="# observatory=ALMA\n"
headerCasa+="# coordsys=LOC (local tangent plane)\n"
headerCasa+="# x y z diam pad#\n"
## Read the Pads in configurationFile if listPads is empty
if len(listPads) == 0:
listPads = []
fin = open(configurationFile)
for pad in fin:
dat = pad.split()
listPads.append(dat[0])
fin.close
configurationFile +=".cfg"
f = open(configurationFile,"w")
f.write(headerCasa)
for pads in listPads:
line=""
for s in self.pad[pads]:
line += s+" "
line+=pads
line+="\n"
f.write(line)
print "### %s created."%(configurationFile)
f.close()
class ArrayInfo:
"""
Compute the Statistics from a CASA array file.
max baseline, min baseline, rms, etc...
"""
def __init__(self,filename):
self.filename=filename
self.xPos = []
self.yPos = []
self.antName = []
self.__readFileArray__()
def __readFileArray__(self):
"Read the CASA file array and create the self.baseline array"
f=open(self.filename)
dump=f.readline()
while dump[0] == "#":
dump=f.readline()
ant=[]
xMean = 0.
yMean = 0.
while dump != "":
dataAnt=dump.split()
if dataAnt[0][0] != '#':
ant.append([float(dataAnt[0]),float(dataAnt[1])])
self.xPos.append(float(dataAnt[0]))
self.yPos.append(float(dataAnt[1]))
self.antName.append(dataAnt[4])
xMean += float(dataAnt[0])
yMean += float(dataAnt[1])
dump=f.readline()
nAnt=len(ant)
xMean = xMean / nAnt
yMean = yMean / nAnt
self.xMean = xMean
self.yMean = yMean
for i in range(nAnt):
self.xPos[i] -= xMean
self.yPos[i] -= yMean
nBl=(nAnt*(nAnt-1))/2
self.baseline=np.zeros(nBl,np.float32)
indexBl=0
for i in range(0,nAnt):
for j in range(i+1,nAnt):
blij2=(ant[i][0]-ant[j][0])*(ant[i][0]-ant[j][0])+(ant[i][1]-ant[j][1])*(ant[i][1]-ant[j][1])
self.baseline[indexBl]=sqrt(blij2)
indexBl+=1
print "Number of baselines: %d"%(nBl)
def stats(self):
"compute the statistics on self.baseline"
self.minBl=np.amin(self.baseline)
self.maxBl=np.amax(self.baseline)
bl2=self.baseline*self.baseline
self.rms=sqrt(np.average(bl2))
print "Array: %s"%(self.filename)
print "x Pos. Mean:%f"%(self.xMean)
print "y Pos. Mean:%f"%(self.yMean)
print "Min. baseline:%f"%(self.minBl)
print "Max. baseline:%f"%(self.maxBl)
print "RMS of the baselines:%f"%(self.rms)
print "\n"
def plotAntPos(self,xmin=-100,xmax=100,ymin=-100.,ymax=100,title='ALMA',xtitle=75.,ytitle=75.,figure=None):
"plot the positions of the antennas"
fig = pl.figure()
ax = fig.add_subplot('111')
ax.plot(self.xPos,self.yPos,'ro',markersize = 10.)
index = 0
for name in self.antName:
xx = self.xPos[index]
yy = self.yPos[index]
ax.text(xx,yy,name)
index += 1
ax.set_xlabel('X (meter)')
ax.set_ylabel('Y (meter)')
ax.set_xlim((xmin,xmax))
ax.set_ylim((ymin,ymax))
ax.text(xtitle,ytitle,title)
# pl.show()
if figure != None:
pl.savefig(figure)
class visibility:
def __init__(self,visname):
self.visname = visname
########################Main program####################################
if __name__=="__main__":
" main program"
## a=ArrayConfigurationCasaFile()
## a.createCasaConfig("/home/stephane/alma/ArrayConfig/Cycle1/configurations/cycle1_config.txt")
|
self.padPositionFile = padPositionFile
self.pad={}
self.__readPadPosition__()
|
identifier_body
|
windows.rs
|
use std::{io, mem, ptr};
use std::ffi::OsStr;
use std::path::Path;
use std::os::windows::ffi::OsStrExt;
use std::os::windows::io::{AsRawHandle, RawHandle};
use winapi::um::fileapi::{CreateFileW, OPEN_EXISTING};
use winapi::um::memoryapi::{CreateFileMappingW, MapViewOfFile, UnmapViewOfFile, VirtualQuery, FILE_MAP_READ, FILE_MAP_COPY};
use winapi::um::handleapi::{CloseHandle, INVALID_HANDLE_VALUE};
use winapi::shared::ntdef::{NULL, HANDLE};
use winapi::shared::minwindef::{LPVOID};
use winapi::um::winnt::{PAGE_READONLY, SEC_IMAGE, GENERIC_READ, FILE_SHARE_READ, FILE_ATTRIBUTE_NORMAL};
//----------------------------------------------------------------
/// Memory mapped image.
pub struct ImageMap {
handle: HANDLE,
bytes: *mut [u8],
}
impl ImageMap {
/// Maps the executable image into memory with correctly aligned sections.
pub fn open<P: AsRef<Path> + ?Sized>(path: &P) -> io::Result<ImageMap> {
unsafe { Self::_open(path.as_ref()) }
}
unsafe fn _open(path: &Path) -> io::Result<ImageMap> {
// Get its file handle
let file = {
// Get the path as a nul terminated wide string
let path: &OsStr = path.as_ref();
let mut wpath: Vec<u16> = path.encode_wide().collect();
wpath.push(0);
CreateFileW(wpath.as_ptr(), GENERIC_READ, FILE_SHARE_READ, ptr::null_mut(), OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL)
};
if file != INVALID_HANDLE_VALUE {
// Create the image file mapping, `SEC_IMAGE` does its magic thing
let map = CreateFileMappingW(file, ptr::null_mut(), PAGE_READONLY | SEC_IMAGE, 0, 0, ptr::null());
CloseHandle(file);
if map != NULL {
// Map view of the file
let view = MapViewOfFile(map, FILE_MAP_COPY, 0, 0, 0);
if view != ptr::null_mut() {
// Trust the OS with correctly mapping the image.
// Trust me to have read and understood the documentation.
// There is no validation and 64bit headers are used because the offsets are the same for PE32.
use crate::image::{IMAGE_DOS_HEADER, IMAGE_NT_HEADERS64};
let dos_header = view as *const IMAGE_DOS_HEADER;
let nt_header = (view as usize + (*dos_header).e_lfanew as usize) as *const IMAGE_NT_HEADERS64;
let size_of = (*nt_header).OptionalHeader.SizeOfImage;
let bytes = ptr::slice_from_raw_parts_mut(view as *mut u8, size_of as usize);
return Ok(ImageMap { handle: map, bytes });
}
let err = io::Error::last_os_error();
CloseHandle(map);
return Err(err);
}
}
Err(io::Error::last_os_error())
}
}
impl AsRawHandle for ImageMap {
fn as_raw_handle(&self) -> RawHandle {
self.handle as RawHandle
}
}
impl AsRef<[u8]> for ImageMap {
fn as_ref(&self) -> &[u8] {
unsafe { &*self.bytes }
}
}
impl Drop for ImageMap {
fn drop(&mut self) {
unsafe {
UnmapViewOfFile((*self.bytes).as_ptr() as LPVOID);
CloseHandle(self.handle);
}
}
}
//----------------------------------------------------------------
/// Memory mapped file.
pub struct FileMap {
handle: HANDLE,
bytes: *mut [u8],
}
impl FileMap {
/// Maps the whole file into memory.
pub fn open<P: AsRef<Path> + ?Sized>(path: &P) -> io::Result<FileMap> {
unsafe { Self::_open(path.as_ref()) }
}
unsafe fn _open(path: &Path) -> io::Result<FileMap> {
// Get its file handle
let file = {
// Get the path as a nul terminated wide string
let path: &OsStr = path.as_ref();
let mut wpath: Vec<u16> = path.encode_wide().collect();
wpath.push(0);
CreateFileW(wpath.as_ptr(), GENERIC_READ, FILE_SHARE_READ, ptr::null_mut(), OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL)
};
if file == INVALID_HANDLE_VALUE {
return Err(io::Error::last_os_error());
}
// Create the memory file mapping
let map = CreateFileMappingW(file, ptr::null_mut(), PAGE_READONLY, 0, 0, ptr::null());
CloseHandle(file);
if map == NULL {
return Err(io::Error::last_os_error());
}
// Map view of the file
let view = MapViewOfFile(map, FILE_MAP_READ, 0, 0, 0);
if view == ptr::null_mut() {
let err = io::Error::last_os_error();
CloseHandle(map);
return Err(err);
}
// Get the size of the file mapping, should never fail...
let mut mem_basic_info = mem::zeroed();
let vq_result = VirtualQuery(view, &mut mem_basic_info, mem::size_of_val(&mem_basic_info));
debug_assert_eq!(vq_result, mem::size_of_val(&mem_basic_info));
// Now have enough information to construct the FileMap
let bytes = ptr::slice_from_raw_parts_mut(view as *mut u8, mem_basic_info.RegionSize as usize);
Ok(FileMap { handle: map, bytes })
}
}
impl AsRawHandle for FileMap {
fn as_raw_handle(&self) -> RawHandle {
self.handle as RawHandle
}
}
impl AsRef<[u8]> for FileMap {
fn
|
(&self) -> &[u8] {
unsafe { &*self.bytes }
}
}
impl Drop for FileMap {
fn drop(&mut self) {
unsafe {
UnmapViewOfFile((*self.bytes).as_ptr() as LPVOID);
CloseHandle(self.handle);
}
}
}
|
as_ref
|
identifier_name
|
windows.rs
|
use std::{io, mem, ptr};
use std::ffi::OsStr;
use std::path::Path;
use std::os::windows::ffi::OsStrExt;
use std::os::windows::io::{AsRawHandle, RawHandle};
use winapi::um::fileapi::{CreateFileW, OPEN_EXISTING};
use winapi::um::memoryapi::{CreateFileMappingW, MapViewOfFile, UnmapViewOfFile, VirtualQuery, FILE_MAP_READ, FILE_MAP_COPY};
use winapi::um::handleapi::{CloseHandle, INVALID_HANDLE_VALUE};
use winapi::shared::ntdef::{NULL, HANDLE};
use winapi::shared::minwindef::{LPVOID};
use winapi::um::winnt::{PAGE_READONLY, SEC_IMAGE, GENERIC_READ, FILE_SHARE_READ, FILE_ATTRIBUTE_NORMAL};
//----------------------------------------------------------------
/// Memory mapped image.
pub struct ImageMap {
handle: HANDLE,
bytes: *mut [u8],
}
impl ImageMap {
/// Maps the executable image into memory with correctly aligned sections.
pub fn open<P: AsRef<Path> + ?Sized>(path: &P) -> io::Result<ImageMap> {
unsafe { Self::_open(path.as_ref()) }
}
unsafe fn _open(path: &Path) -> io::Result<ImageMap> {
// Get its file handle
let file = {
// Get the path as a nul terminated wide string
let path: &OsStr = path.as_ref();
let mut wpath: Vec<u16> = path.encode_wide().collect();
wpath.push(0);
CreateFileW(wpath.as_ptr(), GENERIC_READ, FILE_SHARE_READ, ptr::null_mut(), OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL)
};
if file != INVALID_HANDLE_VALUE {
// Create the image file mapping, `SEC_IMAGE` does its magic thing
let map = CreateFileMappingW(file, ptr::null_mut(), PAGE_READONLY | SEC_IMAGE, 0, 0, ptr::null());
CloseHandle(file);
if map != NULL {
// Map view of the file
let view = MapViewOfFile(map, FILE_MAP_COPY, 0, 0, 0);
if view != ptr::null_mut() {
// Trust the OS with correctly mapping the image.
// Trust me to have read and understood the documentation.
// There is no validation and 64bit headers are used because the offsets are the same for PE32.
use crate::image::{IMAGE_DOS_HEADER, IMAGE_NT_HEADERS64};
let dos_header = view as *const IMAGE_DOS_HEADER;
let nt_header = (view as usize + (*dos_header).e_lfanew as usize) as *const IMAGE_NT_HEADERS64;
let size_of = (*nt_header).OptionalHeader.SizeOfImage;
let bytes = ptr::slice_from_raw_parts_mut(view as *mut u8, size_of as usize);
return Ok(ImageMap { handle: map, bytes });
}
let err = io::Error::last_os_error();
CloseHandle(map);
return Err(err);
}
}
Err(io::Error::last_os_error())
}
}
impl AsRawHandle for ImageMap {
fn as_raw_handle(&self) -> RawHandle {
self.handle as RawHandle
}
}
impl AsRef<[u8]> for ImageMap {
fn as_ref(&self) -> &[u8] {
unsafe { &*self.bytes }
}
}
impl Drop for ImageMap {
fn drop(&mut self) {
unsafe {
UnmapViewOfFile((*self.bytes).as_ptr() as LPVOID);
CloseHandle(self.handle);
}
}
}
//----------------------------------------------------------------
/// Memory mapped file.
pub struct FileMap {
handle: HANDLE,
bytes: *mut [u8],
}
impl FileMap {
/// Maps the whole file into memory.
pub fn open<P: AsRef<Path> + ?Sized>(path: &P) -> io::Result<FileMap> {
unsafe { Self::_open(path.as_ref()) }
}
unsafe fn _open(path: &Path) -> io::Result<FileMap> {
// Get its file handle
let file = {
// Get the path as a nul terminated wide string
let path: &OsStr = path.as_ref();
let mut wpath: Vec<u16> = path.encode_wide().collect();
wpath.push(0);
CreateFileW(wpath.as_ptr(), GENERIC_READ, FILE_SHARE_READ, ptr::null_mut(), OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL)
};
if file == INVALID_HANDLE_VALUE
|
// Create the memory file mapping
let map = CreateFileMappingW(file, ptr::null_mut(), PAGE_READONLY, 0, 0, ptr::null());
CloseHandle(file);
if map == NULL {
return Err(io::Error::last_os_error());
}
// Map view of the file
let view = MapViewOfFile(map, FILE_MAP_READ, 0, 0, 0);
if view == ptr::null_mut() {
let err = io::Error::last_os_error();
CloseHandle(map);
return Err(err);
}
// Get the size of the file mapping, should never fail...
let mut mem_basic_info = mem::zeroed();
let vq_result = VirtualQuery(view, &mut mem_basic_info, mem::size_of_val(&mem_basic_info));
debug_assert_eq!(vq_result, mem::size_of_val(&mem_basic_info));
// Now have enough information to construct the FileMap
let bytes = ptr::slice_from_raw_parts_mut(view as *mut u8, mem_basic_info.RegionSize as usize);
Ok(FileMap { handle: map, bytes })
}
}
impl AsRawHandle for FileMap {
fn as_raw_handle(&self) -> RawHandle {
self.handle as RawHandle
}
}
impl AsRef<[u8]> for FileMap {
fn as_ref(&self) -> &[u8] {
unsafe { &*self.bytes }
}
}
impl Drop for FileMap {
fn drop(&mut self) {
unsafe {
UnmapViewOfFile((*self.bytes).as_ptr() as LPVOID);
CloseHandle(self.handle);
}
}
}
|
{
return Err(io::Error::last_os_error());
}
|
conditional_block
|
windows.rs
|
use std::{io, mem, ptr};
use std::ffi::OsStr;
use std::path::Path;
use std::os::windows::ffi::OsStrExt;
use std::os::windows::io::{AsRawHandle, RawHandle};
use winapi::um::fileapi::{CreateFileW, OPEN_EXISTING};
use winapi::um::memoryapi::{CreateFileMappingW, MapViewOfFile, UnmapViewOfFile, VirtualQuery, FILE_MAP_READ, FILE_MAP_COPY};
use winapi::um::handleapi::{CloseHandle, INVALID_HANDLE_VALUE};
use winapi::shared::ntdef::{NULL, HANDLE};
use winapi::shared::minwindef::{LPVOID};
use winapi::um::winnt::{PAGE_READONLY, SEC_IMAGE, GENERIC_READ, FILE_SHARE_READ, FILE_ATTRIBUTE_NORMAL};
//----------------------------------------------------------------
/// Memory mapped image.
pub struct ImageMap {
handle: HANDLE,
bytes: *mut [u8],
}
impl ImageMap {
/// Maps the executable image into memory with correctly aligned sections.
pub fn open<P: AsRef<Path> + ?Sized>(path: &P) -> io::Result<ImageMap> {
unsafe { Self::_open(path.as_ref()) }
}
unsafe fn _open(path: &Path) -> io::Result<ImageMap> {
// Get its file handle
let file = {
// Get the path as a nul terminated wide string
let path: &OsStr = path.as_ref();
let mut wpath: Vec<u16> = path.encode_wide().collect();
wpath.push(0);
CreateFileW(wpath.as_ptr(), GENERIC_READ, FILE_SHARE_READ, ptr::null_mut(), OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL)
};
if file != INVALID_HANDLE_VALUE {
// Create the image file mapping, `SEC_IMAGE` does its magic thing
let map = CreateFileMappingW(file, ptr::null_mut(), PAGE_READONLY | SEC_IMAGE, 0, 0, ptr::null());
CloseHandle(file);
if map != NULL {
// Map view of the file
let view = MapViewOfFile(map, FILE_MAP_COPY, 0, 0, 0);
if view != ptr::null_mut() {
// Trust the OS with correctly mapping the image.
// Trust me to have read and understood the documentation.
// There is no validation and 64bit headers are used because the offsets are the same for PE32.
use crate::image::{IMAGE_DOS_HEADER, IMAGE_NT_HEADERS64};
let dos_header = view as *const IMAGE_DOS_HEADER;
let nt_header = (view as usize + (*dos_header).e_lfanew as usize) as *const IMAGE_NT_HEADERS64;
let size_of = (*nt_header).OptionalHeader.SizeOfImage;
let bytes = ptr::slice_from_raw_parts_mut(view as *mut u8, size_of as usize);
return Ok(ImageMap { handle: map, bytes });
}
let err = io::Error::last_os_error();
CloseHandle(map);
return Err(err);
}
}
Err(io::Error::last_os_error())
}
}
impl AsRawHandle for ImageMap {
fn as_raw_handle(&self) -> RawHandle {
self.handle as RawHandle
}
}
impl AsRef<[u8]> for ImageMap {
fn as_ref(&self) -> &[u8] {
unsafe { &*self.bytes }
}
|
CloseHandle(self.handle);
}
}
}
//----------------------------------------------------------------
/// Memory mapped file.
pub struct FileMap {
handle: HANDLE,
bytes: *mut [u8],
}
impl FileMap {
/// Maps the whole file into memory.
pub fn open<P: AsRef<Path> + ?Sized>(path: &P) -> io::Result<FileMap> {
unsafe { Self::_open(path.as_ref()) }
}
unsafe fn _open(path: &Path) -> io::Result<FileMap> {
// Get its file handle
let file = {
// Get the path as a nul terminated wide string
let path: &OsStr = path.as_ref();
let mut wpath: Vec<u16> = path.encode_wide().collect();
wpath.push(0);
CreateFileW(wpath.as_ptr(), GENERIC_READ, FILE_SHARE_READ, ptr::null_mut(), OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL)
};
if file == INVALID_HANDLE_VALUE {
return Err(io::Error::last_os_error());
}
// Create the memory file mapping
let map = CreateFileMappingW(file, ptr::null_mut(), PAGE_READONLY, 0, 0, ptr::null());
CloseHandle(file);
if map == NULL {
return Err(io::Error::last_os_error());
}
// Map view of the file
let view = MapViewOfFile(map, FILE_MAP_READ, 0, 0, 0);
if view == ptr::null_mut() {
let err = io::Error::last_os_error();
CloseHandle(map);
return Err(err);
}
// Get the size of the file mapping, should never fail...
let mut mem_basic_info = mem::zeroed();
let vq_result = VirtualQuery(view, &mut mem_basic_info, mem::size_of_val(&mem_basic_info));
debug_assert_eq!(vq_result, mem::size_of_val(&mem_basic_info));
// Now have enough information to construct the FileMap
let bytes = ptr::slice_from_raw_parts_mut(view as *mut u8, mem_basic_info.RegionSize as usize);
Ok(FileMap { handle: map, bytes })
}
}
impl AsRawHandle for FileMap {
fn as_raw_handle(&self) -> RawHandle {
self.handle as RawHandle
}
}
impl AsRef<[u8]> for FileMap {
fn as_ref(&self) -> &[u8] {
unsafe { &*self.bytes }
}
}
impl Drop for FileMap {
fn drop(&mut self) {
unsafe {
UnmapViewOfFile((*self.bytes).as_ptr() as LPVOID);
CloseHandle(self.handle);
}
}
}
|
}
impl Drop for ImageMap {
fn drop(&mut self) {
unsafe {
UnmapViewOfFile((*self.bytes).as_ptr() as LPVOID);
|
random_line_split
|
windows.rs
|
use std::{io, mem, ptr};
use std::ffi::OsStr;
use std::path::Path;
use std::os::windows::ffi::OsStrExt;
use std::os::windows::io::{AsRawHandle, RawHandle};
use winapi::um::fileapi::{CreateFileW, OPEN_EXISTING};
use winapi::um::memoryapi::{CreateFileMappingW, MapViewOfFile, UnmapViewOfFile, VirtualQuery, FILE_MAP_READ, FILE_MAP_COPY};
use winapi::um::handleapi::{CloseHandle, INVALID_HANDLE_VALUE};
use winapi::shared::ntdef::{NULL, HANDLE};
use winapi::shared::minwindef::{LPVOID};
use winapi::um::winnt::{PAGE_READONLY, SEC_IMAGE, GENERIC_READ, FILE_SHARE_READ, FILE_ATTRIBUTE_NORMAL};
//----------------------------------------------------------------
/// Memory mapped image.
pub struct ImageMap {
handle: HANDLE,
bytes: *mut [u8],
}
impl ImageMap {
/// Maps the executable image into memory with correctly aligned sections.
pub fn open<P: AsRef<Path> + ?Sized>(path: &P) -> io::Result<ImageMap> {
unsafe { Self::_open(path.as_ref()) }
}
unsafe fn _open(path: &Path) -> io::Result<ImageMap> {
// Get its file handle
let file = {
// Get the path as a nul terminated wide string
let path: &OsStr = path.as_ref();
let mut wpath: Vec<u16> = path.encode_wide().collect();
wpath.push(0);
CreateFileW(wpath.as_ptr(), GENERIC_READ, FILE_SHARE_READ, ptr::null_mut(), OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL)
};
if file != INVALID_HANDLE_VALUE {
// Create the image file mapping, `SEC_IMAGE` does its magic thing
let map = CreateFileMappingW(file, ptr::null_mut(), PAGE_READONLY | SEC_IMAGE, 0, 0, ptr::null());
CloseHandle(file);
if map != NULL {
// Map view of the file
let view = MapViewOfFile(map, FILE_MAP_COPY, 0, 0, 0);
if view != ptr::null_mut() {
// Trust the OS with correctly mapping the image.
// Trust me to have read and understood the documentation.
// There is no validation and 64bit headers are used because the offsets are the same for PE32.
use crate::image::{IMAGE_DOS_HEADER, IMAGE_NT_HEADERS64};
let dos_header = view as *const IMAGE_DOS_HEADER;
let nt_header = (view as usize + (*dos_header).e_lfanew as usize) as *const IMAGE_NT_HEADERS64;
let size_of = (*nt_header).OptionalHeader.SizeOfImage;
let bytes = ptr::slice_from_raw_parts_mut(view as *mut u8, size_of as usize);
return Ok(ImageMap { handle: map, bytes });
}
let err = io::Error::last_os_error();
CloseHandle(map);
return Err(err);
}
}
Err(io::Error::last_os_error())
}
}
impl AsRawHandle for ImageMap {
fn as_raw_handle(&self) -> RawHandle {
self.handle as RawHandle
}
}
impl AsRef<[u8]> for ImageMap {
fn as_ref(&self) -> &[u8] {
unsafe { &*self.bytes }
}
}
impl Drop for ImageMap {
fn drop(&mut self)
|
}
//----------------------------------------------------------------
/// Memory mapped file.
pub struct FileMap {
handle: HANDLE,
bytes: *mut [u8],
}
impl FileMap {
/// Maps the whole file into memory.
pub fn open<P: AsRef<Path> + ?Sized>(path: &P) -> io::Result<FileMap> {
unsafe { Self::_open(path.as_ref()) }
}
unsafe fn _open(path: &Path) -> io::Result<FileMap> {
// Get its file handle
let file = {
// Get the path as a nul terminated wide string
let path: &OsStr = path.as_ref();
let mut wpath: Vec<u16> = path.encode_wide().collect();
wpath.push(0);
CreateFileW(wpath.as_ptr(), GENERIC_READ, FILE_SHARE_READ, ptr::null_mut(), OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL)
};
if file == INVALID_HANDLE_VALUE {
return Err(io::Error::last_os_error());
}
// Create the memory file mapping
let map = CreateFileMappingW(file, ptr::null_mut(), PAGE_READONLY, 0, 0, ptr::null());
CloseHandle(file);
if map == NULL {
return Err(io::Error::last_os_error());
}
// Map view of the file
let view = MapViewOfFile(map, FILE_MAP_READ, 0, 0, 0);
if view == ptr::null_mut() {
let err = io::Error::last_os_error();
CloseHandle(map);
return Err(err);
}
// Get the size of the file mapping, should never fail...
let mut mem_basic_info = mem::zeroed();
let vq_result = VirtualQuery(view, &mut mem_basic_info, mem::size_of_val(&mem_basic_info));
debug_assert_eq!(vq_result, mem::size_of_val(&mem_basic_info));
// Now have enough information to construct the FileMap
let bytes = ptr::slice_from_raw_parts_mut(view as *mut u8, mem_basic_info.RegionSize as usize);
Ok(FileMap { handle: map, bytes })
}
}
impl AsRawHandle for FileMap {
fn as_raw_handle(&self) -> RawHandle {
self.handle as RawHandle
}
}
impl AsRef<[u8]> for FileMap {
fn as_ref(&self) -> &[u8] {
unsafe { &*self.bytes }
}
}
impl Drop for FileMap {
fn drop(&mut self) {
unsafe {
UnmapViewOfFile((*self.bytes).as_ptr() as LPVOID);
CloseHandle(self.handle);
}
}
}
|
{
unsafe {
UnmapViewOfFile((*self.bytes).as_ptr() as LPVOID);
CloseHandle(self.handle);
}
}
|
identifier_body
|
Connector.js
|
OAUTH_PARMS_CLASS = require('../common/OAuthParameters');
PARSE_STRING = require('xml2js').parseString;
var util = require('util');
var namespaceUtil = require('../common/NamespaceUtil');
AMP = '&';
OAUTH_START_STRING = 'OAuth ';
ERROR_STATUS_BOUNDARY = 300;
USER_AGENT = 'MC API OAuth Framework v1.0-node';
CRYPTO = require('crypto');
HTTPS = require('https');
FS = require('fs');
URL = require('url');
QUERYSTRING = require('querystring');
XML2JS = require('xml2js');
OAUTH_BODY_HASH = 'oauth_body_hash';
OAUTH_CONSUMER_KEY = 'oauth_consumer_key';
OAUTH_NONCE = 'oauth_nonce';
OAUTH_SIGNATURE = 'oauth_signature';
OAUTH_SIGNATURE_METHOD = 'oauth_signature_method';
OAUTH_TIMESTAMP = 'oauth_timestamp';
OAUTH_VERSION = 'oauth_version';
/**
* Constructor
* @param consumerKey - consumer key provided by MasterCard
* @param privateKey - path to private key //TODO UPDATE WHEN REFACTORED
* @constructor -
*/
function Connector(consumerKey, privateKey, callback)
|
// CLASS METHODS
/**
* "private method" to generate the signature base string from the URL, request method, and parameters
* @param url - URL to connect to
* @param requestMethod - HTTP request method
* @param oauthParms - parameters containing authorization information
* @returns {string|*} - signature base string generated
* @private
*/
_generateSignatureBaseString = function(url, requestMethod, oauthParms){
var signatureBaseString = encodeURIComponent(requestMethod.toUpperCase()) +
AMP + encodeURIComponent((_normalizeUrl(url))) + AMP +
encodeURIComponent(_normalizeParameters(url, oauthParms));
return signatureBaseString;
};
/**
* "private" method to sign the signature base string and connect to MasterCard's servers
* @param oauthParms - parameters containing authorization information
* @param privateKey - URSA private key object
* @param requestMethod -
* @param url -
* @param body - request body [optional]
* @private
*/
_signAndMakeRequest = function(oauthParms, privateKey, signatureBaseString, requestMethod, url, body, callback){
var signer = CRYPTO.createSign('RSA-SHA1');
signer = signer.update(new Buffer(signatureBaseString));
oauthParms.signature = signer.sign(privateKey, 'base64');
oauthParms.signature = encodeURIComponent(oauthParms.signature);
oauthParms.signature = oauthParms.signature.replace('+','%20');
oauthParms.signature = oauthParms.signature.replace('*','%2A');
oauthParms.signature = oauthParms.signature.replace('~','%7E');
var authHeader = _buildAuthHeaderString(oauthParms);
_doConnect(url,requestMethod,authHeader, body, callback);
};
/**
* "private" method to build the authorization header from the contents of the oauth parameters
* @param oauthParms - object containing authorization information
* @returns {string} - authorization header
* @private
*/
_buildAuthHeaderString = function(oauthParms){
var header = '';
header = header + 'oauth_consumer_key' + '="' + oauthParms.consumerKey + '",';
header = header + 'oauth_nonce' + '="' + oauthParms.nonce + '",';
header = header + 'oauth_signature' + '="' + oauthParms.signature + '",';
header = header + 'oauth_signature_method' + '="' + oauthParms.signatureMethod + '",';
header = header + 'oauth_timestamp' + '="' + oauthParms.timeStamp + '",';
header = header + 'oauth_version' + '="' + oauthParms.oauthVersion + '"';
if (oauthParms.bodyHash){
header = OAUTH_START_STRING + OAUTH_BODY_HASH
+ '="' + oauthParms.bodyHash + '",' + header;
} else {
header = OAUTH_START_STRING + header;
}
return header;
};
/**
* "private" method to make the connection to MasterCard's servers
* @param url - url to connect to
* @param requestMethod - HTTP request method ('GET','PUT','POST','DELETE'
* @param body - request body [optional]
* @private
*/
_doConnect = function(url, requestMethod, authHeader, body, callback){
requestMethod = requestMethod.toUpperCase();
uri = URL.parse(url);
var options;
if (body) {
options = {
hostname: uri.host.split(':')[0],
path: uri.path,
method: requestMethod,
headers: {
'Authorization': authHeader,
'User-Agent': USER_AGENT,
'content-type' : 'application/xml;charset=UTF-8',
'content-length' : body.length
},
cert: FS.readFileSync(process.env.SSL_CERT_FILE)
};
} else {
options = {
hostname: uri.host.split(':')[0],
path: uri.path,
method: requestMethod,
headers: {
'Authorization': authHeader,
'User-Agent': USER_AGENT
},
cert: FS.readFileSync(process.env.SSL_CERT_FILE)
}
}
options.agent = new HTTPS.Agent(options);
var request = HTTPS.request(options, function(response){
var retBody = '';
var statusCode = response.statusCode;
response.on('data', function(chunk){
retBody += chunk;
}).on('end', function(){
_checkResponse(retBody, statusCode, callback);
});
}).on('error', function(error){
throw new Error(error);
});
if (body) {
request.write(body);
}
request.end();
};
_checkResponse = function(body, statusCode, callback){
if (statusCode > ERROR_STATUS_BOUNDARY){
throw new Error(body);
} else {
body = namespaceUtil.RemoveNamespace(body);
PARSE_STRING(body, function(err, result){
callback(result);
});
}
};
/**
* "private" method to strip off the querystring parameters and port from the URL
* @param url - url to modify
* @returns {*} - normalized URL
* @private
*/
_normalizeUrl = function(url){
var tmp = url;
// strip query portion
var idx = url.indexOf('?');
if (idx){
tmp = url.substr(0, idx);
}
// strip port
if (tmp.lastIndexOf(':') && tmp.lastIndexOf(':') > 5){
// implies port is given
tmp = tmp.substr(0, tmp.lastIndexOf(':'));
}
return tmp;
};
/**
* "private" method to put querystring and oauth parameters in lexical order
* @param url - url containing query string parameters
* @param oauthParms - object containing authorization info
* @returns {string} - normalized parameter string
* @private
*/
_normalizeParameters = function(url, oauthParms){
var uri = URL.parse(url);
// all mastercard services have ?Format=XML
var qstringHash = QUERYSTRING.parse(uri.search.split('?')[1]);
var oauthHash = oauthParms.generateParametersHash();
var nameArr = [];
var idx = 0;
// TODO Does this need to be concatenated into one array qstringhash.concat(oauthHash)
for (var qStringKey in qstringHash){
nameArr[idx] = qStringKey;
idx++;
}
for (var oauthKey in oauthHash){
nameArr[idx] = oauthKey;
idx++;
}
nameArr.sort(); // now parms are in alphabetical order
var parm = '';
var delim = '';
for (var i = 0; i < nameArr.length ; i++){
if (qstringHash[nameArr[i]]){
parm = parm + delim + nameArr[i] + '=' + qstringHash[nameArr[i]];
} else {
parm = parm + delim + nameArr[i] + '=' + oauthHash[nameArr[i]];
}
delim = AMP;
}
return parm;
};
_postProcessSignatureBaseString = function(signatureBaseString){
signatureBaseString = signatureBaseString.replace(/%20/g, '%2520');
return signatureBaseString.replace('!','%21');
};
module.exports.Connector = Connector;
|
{
this.consumerKey = consumerKey;
this.privateKey = privateKey;
this.callback = callback;
this.setCallback = function(callback){
this.callback = callback;
};
/**
* Method that service classes should call in order to execute a request against MasterCard's servers
* @param url - URL including querystring parameters to connect to
* @param requestMethod - GET, PUT, POST, or DELETE
* @param body - request body [optional]
* @param oauth_parms - existing oauth_parameters [optional]
*/
this.doRequest = function(url, requestMethod, bodyObject, oauthParms){
if (!this.callback){
this.callback = function(response){ return response; };
}
if (oauthParms){
//TODO allow for additional parms to be added
} else {
oauthParms = new OAUTH_PARMS_CLASS.OAuthParameters(this.consumerKey);
}
if (bodyObject){
var builder = new XML2JS.Builder();
var body = builder.buildObject(bodyObject);
body = namespaceUtil.AddNamespace(body);
oauthParms.generateBodyHash(body);
}
var signatureBaseString = _generateSignatureBaseString(url, requestMethod, oauthParms);
signatureBaseString = _postProcessSignatureBaseString(signatureBaseString);
_signAndMakeRequest(oauthParms, this.privateKey, signatureBaseString, requestMethod, url, body, this.callback);
};
}
|
identifier_body
|
Connector.js
|
OAUTH_PARMS_CLASS = require('../common/OAuthParameters');
PARSE_STRING = require('xml2js').parseString;
var util = require('util');
var namespaceUtil = require('../common/NamespaceUtil');
AMP = '&';
OAUTH_START_STRING = 'OAuth ';
ERROR_STATUS_BOUNDARY = 300;
USER_AGENT = 'MC API OAuth Framework v1.0-node';
CRYPTO = require('crypto');
HTTPS = require('https');
FS = require('fs');
URL = require('url');
QUERYSTRING = require('querystring');
XML2JS = require('xml2js');
OAUTH_BODY_HASH = 'oauth_body_hash';
OAUTH_CONSUMER_KEY = 'oauth_consumer_key';
OAUTH_NONCE = 'oauth_nonce';
OAUTH_SIGNATURE = 'oauth_signature';
OAUTH_SIGNATURE_METHOD = 'oauth_signature_method';
OAUTH_TIMESTAMP = 'oauth_timestamp';
OAUTH_VERSION = 'oauth_version';
/**
* Constructor
* @param consumerKey - consumer key provided by MasterCard
* @param privateKey - path to private key //TODO UPDATE WHEN REFACTORED
* @constructor -
*/
function Connector(consumerKey, privateKey, callback){
this.consumerKey = consumerKey;
this.privateKey = privateKey;
this.callback = callback;
this.setCallback = function(callback){
this.callback = callback;
};
/**
* Method that service classes should call in order to execute a request against MasterCard's servers
* @param url - URL including querystring parameters to connect to
* @param requestMethod - GET, PUT, POST, or DELETE
* @param body - request body [optional]
* @param oauth_parms - existing oauth_parameters [optional]
*/
this.doRequest = function(url, requestMethod, bodyObject, oauthParms){
if (!this.callback){
this.callback = function(response){ return response; };
}
if (oauthParms){
//TODO allow for additional parms to be added
} else {
oauthParms = new OAUTH_PARMS_CLASS.OAuthParameters(this.consumerKey);
}
if (bodyObject){
var builder = new XML2JS.Builder();
var body = builder.buildObject(bodyObject);
body = namespaceUtil.AddNamespace(body);
oauthParms.generateBodyHash(body);
}
var signatureBaseString = _generateSignatureBaseString(url, requestMethod, oauthParms);
signatureBaseString = _postProcessSignatureBaseString(signatureBaseString);
_signAndMakeRequest(oauthParms, this.privateKey, signatureBaseString, requestMethod, url, body, this.callback);
};
}
// CLASS METHODS
/**
* "private method" to generate the signature base string from the URL, request method, and parameters
* @param url - URL to connect to
* @param requestMethod - HTTP request method
* @param oauthParms - parameters containing authorization information
* @returns {string|*} - signature base string generated
* @private
*/
_generateSignatureBaseString = function(url, requestMethod, oauthParms){
var signatureBaseString = encodeURIComponent(requestMethod.toUpperCase()) +
AMP + encodeURIComponent((_normalizeUrl(url))) + AMP +
encodeURIComponent(_normalizeParameters(url, oauthParms));
return signatureBaseString;
};
/**
* "private" method to sign the signature base string and connect to MasterCard's servers
* @param oauthParms - parameters containing authorization information
* @param privateKey - URSA private key object
* @param requestMethod -
* @param url -
* @param body - request body [optional]
* @private
*/
_signAndMakeRequest = function(oauthParms, privateKey, signatureBaseString, requestMethod, url, body, callback){
var signer = CRYPTO.createSign('RSA-SHA1');
signer = signer.update(new Buffer(signatureBaseString));
oauthParms.signature = signer.sign(privateKey, 'base64');
oauthParms.signature = encodeURIComponent(oauthParms.signature);
oauthParms.signature = oauthParms.signature.replace('+','%20');
oauthParms.signature = oauthParms.signature.replace('*','%2A');
oauthParms.signature = oauthParms.signature.replace('~','%7E');
var authHeader = _buildAuthHeaderString(oauthParms);
_doConnect(url,requestMethod,authHeader, body, callback);
};
/**
* "private" method to build the authorization header from the contents of the oauth parameters
* @param oauthParms - object containing authorization information
* @returns {string} - authorization header
* @private
*/
_buildAuthHeaderString = function(oauthParms){
var header = '';
header = header + 'oauth_consumer_key' + '="' + oauthParms.consumerKey + '",';
header = header + 'oauth_nonce' + '="' + oauthParms.nonce + '",';
header = header + 'oauth_signature' + '="' + oauthParms.signature + '",';
header = header + 'oauth_signature_method' + '="' + oauthParms.signatureMethod + '",';
header = header + 'oauth_timestamp' + '="' + oauthParms.timeStamp + '",';
header = header + 'oauth_version' + '="' + oauthParms.oauthVersion + '"';
if (oauthParms.bodyHash){
header = OAUTH_START_STRING + OAUTH_BODY_HASH
+ '="' + oauthParms.bodyHash + '",' + header;
} else {
header = OAUTH_START_STRING + header;
}
return header;
};
/**
* "private" method to make the connection to MasterCard's servers
* @param url - url to connect to
* @param requestMethod - HTTP request method ('GET','PUT','POST','DELETE'
* @param body - request body [optional]
* @private
*/
_doConnect = function(url, requestMethod, authHeader, body, callback){
requestMethod = requestMethod.toUpperCase();
uri = URL.parse(url);
var options;
if (body) {
options = {
hostname: uri.host.split(':')[0],
path: uri.path,
method: requestMethod,
headers: {
'Authorization': authHeader,
'User-Agent': USER_AGENT,
'content-type' : 'application/xml;charset=UTF-8',
'content-length' : body.length
},
cert: FS.readFileSync(process.env.SSL_CERT_FILE)
};
} else {
options = {
hostname: uri.host.split(':')[0],
path: uri.path,
method: requestMethod,
headers: {
'Authorization': authHeader,
'User-Agent': USER_AGENT
},
cert: FS.readFileSync(process.env.SSL_CERT_FILE)
}
}
options.agent = new HTTPS.Agent(options);
var request = HTTPS.request(options, function(response){
var retBody = '';
var statusCode = response.statusCode;
response.on('data', function(chunk){
retBody += chunk;
}).on('end', function(){
_checkResponse(retBody, statusCode, callback);
});
}).on('error', function(error){
throw new Error(error);
});
if (body) {
request.write(body);
}
request.end();
};
_checkResponse = function(body, statusCode, callback){
if (statusCode > ERROR_STATUS_BOUNDARY){
throw new Error(body);
} else {
body = namespaceUtil.RemoveNamespace(body);
PARSE_STRING(body, function(err, result){
callback(result);
});
}
};
/**
* "private" method to strip off the querystring parameters and port from the URL
* @param url - url to modify
* @returns {*} - normalized URL
* @private
*/
_normalizeUrl = function(url){
var tmp = url;
// strip query portion
var idx = url.indexOf('?');
if (idx){
tmp = url.substr(0, idx);
}
// strip port
if (tmp.lastIndexOf(':') && tmp.lastIndexOf(':') > 5){
// implies port is given
tmp = tmp.substr(0, tmp.lastIndexOf(':'));
}
return tmp;
};
/**
* "private" method to put querystring and oauth parameters in lexical order
* @param url - url containing query string parameters
* @param oauthParms - object containing authorization info
* @returns {string} - normalized parameter string
* @private
*/
_normalizeParameters = function(url, oauthParms){
var uri = URL.parse(url);
// all mastercard services have ?Format=XML
var qstringHash = QUERYSTRING.parse(uri.search.split('?')[1]);
var oauthHash = oauthParms.generateParametersHash();
var nameArr = [];
var idx = 0;
// TODO Does this need to be concatenated into one array qstringhash.concat(oauthHash)
for (var qStringKey in qstringHash){
nameArr[idx] = qStringKey;
idx++;
}
for (var oauthKey in oauthHash){
nameArr[idx] = oauthKey;
idx++;
}
nameArr.sort(); // now parms are in alphabetical order
var parm = '';
var delim = '';
for (var i = 0; i < nameArr.length ; i++){
if (qstringHash[nameArr[i]])
|
else {
parm = parm + delim + nameArr[i] + '=' + oauthHash[nameArr[i]];
}
delim = AMP;
}
return parm;
};
_postProcessSignatureBaseString = function(signatureBaseString){
signatureBaseString = signatureBaseString.replace(/%20/g, '%2520');
return signatureBaseString.replace('!','%21');
};
module.exports.Connector = Connector;
|
{
parm = parm + delim + nameArr[i] + '=' + qstringHash[nameArr[i]];
}
|
conditional_block
|
Connector.js
|
OAUTH_PARMS_CLASS = require('../common/OAuthParameters');
PARSE_STRING = require('xml2js').parseString;
var util = require('util');
var namespaceUtil = require('../common/NamespaceUtil');
AMP = '&';
OAUTH_START_STRING = 'OAuth ';
ERROR_STATUS_BOUNDARY = 300;
USER_AGENT = 'MC API OAuth Framework v1.0-node';
CRYPTO = require('crypto');
HTTPS = require('https');
FS = require('fs');
URL = require('url');
QUERYSTRING = require('querystring');
XML2JS = require('xml2js');
OAUTH_BODY_HASH = 'oauth_body_hash';
OAUTH_CONSUMER_KEY = 'oauth_consumer_key';
OAUTH_NONCE = 'oauth_nonce';
OAUTH_SIGNATURE = 'oauth_signature';
OAUTH_SIGNATURE_METHOD = 'oauth_signature_method';
OAUTH_TIMESTAMP = 'oauth_timestamp';
OAUTH_VERSION = 'oauth_version';
/**
* Constructor
* @param consumerKey - consumer key provided by MasterCard
* @param privateKey - path to private key //TODO UPDATE WHEN REFACTORED
* @constructor -
|
function Connector(consumerKey, privateKey, callback){
this.consumerKey = consumerKey;
this.privateKey = privateKey;
this.callback = callback;
this.setCallback = function(callback){
this.callback = callback;
};
/**
* Method that service classes should call in order to execute a request against MasterCard's servers
* @param url - URL including querystring parameters to connect to
* @param requestMethod - GET, PUT, POST, or DELETE
* @param body - request body [optional]
* @param oauth_parms - existing oauth_parameters [optional]
*/
this.doRequest = function(url, requestMethod, bodyObject, oauthParms){
if (!this.callback){
this.callback = function(response){ return response; };
}
if (oauthParms){
//TODO allow for additional parms to be added
} else {
oauthParms = new OAUTH_PARMS_CLASS.OAuthParameters(this.consumerKey);
}
if (bodyObject){
var builder = new XML2JS.Builder();
var body = builder.buildObject(bodyObject);
body = namespaceUtil.AddNamespace(body);
oauthParms.generateBodyHash(body);
}
var signatureBaseString = _generateSignatureBaseString(url, requestMethod, oauthParms);
signatureBaseString = _postProcessSignatureBaseString(signatureBaseString);
_signAndMakeRequest(oauthParms, this.privateKey, signatureBaseString, requestMethod, url, body, this.callback);
};
}
// CLASS METHODS
/**
* "private method" to generate the signature base string from the URL, request method, and parameters
* @param url - URL to connect to
* @param requestMethod - HTTP request method
* @param oauthParms - parameters containing authorization information
* @returns {string|*} - signature base string generated
* @private
*/
_generateSignatureBaseString = function(url, requestMethod, oauthParms){
var signatureBaseString = encodeURIComponent(requestMethod.toUpperCase()) +
AMP + encodeURIComponent((_normalizeUrl(url))) + AMP +
encodeURIComponent(_normalizeParameters(url, oauthParms));
return signatureBaseString;
};
/**
* "private" method to sign the signature base string and connect to MasterCard's servers
* @param oauthParms - parameters containing authorization information
* @param privateKey - URSA private key object
* @param requestMethod -
* @param url -
* @param body - request body [optional]
* @private
*/
_signAndMakeRequest = function(oauthParms, privateKey, signatureBaseString, requestMethod, url, body, callback){
var signer = CRYPTO.createSign('RSA-SHA1');
signer = signer.update(new Buffer(signatureBaseString));
oauthParms.signature = signer.sign(privateKey, 'base64');
oauthParms.signature = encodeURIComponent(oauthParms.signature);
oauthParms.signature = oauthParms.signature.replace('+','%20');
oauthParms.signature = oauthParms.signature.replace('*','%2A');
oauthParms.signature = oauthParms.signature.replace('~','%7E');
var authHeader = _buildAuthHeaderString(oauthParms);
_doConnect(url,requestMethod,authHeader, body, callback);
};
/**
* "private" method to build the authorization header from the contents of the oauth parameters
* @param oauthParms - object containing authorization information
* @returns {string} - authorization header
* @private
*/
_buildAuthHeaderString = function(oauthParms){
var header = '';
header = header + 'oauth_consumer_key' + '="' + oauthParms.consumerKey + '",';
header = header + 'oauth_nonce' + '="' + oauthParms.nonce + '",';
header = header + 'oauth_signature' + '="' + oauthParms.signature + '",';
header = header + 'oauth_signature_method' + '="' + oauthParms.signatureMethod + '",';
header = header + 'oauth_timestamp' + '="' + oauthParms.timeStamp + '",';
header = header + 'oauth_version' + '="' + oauthParms.oauthVersion + '"';
if (oauthParms.bodyHash){
header = OAUTH_START_STRING + OAUTH_BODY_HASH
+ '="' + oauthParms.bodyHash + '",' + header;
} else {
header = OAUTH_START_STRING + header;
}
return header;
};
/**
* "private" method to make the connection to MasterCard's servers
* @param url - url to connect to
* @param requestMethod - HTTP request method ('GET','PUT','POST','DELETE'
* @param body - request body [optional]
* @private
*/
_doConnect = function(url, requestMethod, authHeader, body, callback){
requestMethod = requestMethod.toUpperCase();
uri = URL.parse(url);
var options;
if (body) {
options = {
hostname: uri.host.split(':')[0],
path: uri.path,
method: requestMethod,
headers: {
'Authorization': authHeader,
'User-Agent': USER_AGENT,
'content-type' : 'application/xml;charset=UTF-8',
'content-length' : body.length
},
cert: FS.readFileSync(process.env.SSL_CERT_FILE)
};
} else {
options = {
hostname: uri.host.split(':')[0],
path: uri.path,
method: requestMethod,
headers: {
'Authorization': authHeader,
'User-Agent': USER_AGENT
},
cert: FS.readFileSync(process.env.SSL_CERT_FILE)
}
}
options.agent = new HTTPS.Agent(options);
var request = HTTPS.request(options, function(response){
var retBody = '';
var statusCode = response.statusCode;
response.on('data', function(chunk){
retBody += chunk;
}).on('end', function(){
_checkResponse(retBody, statusCode, callback);
});
}).on('error', function(error){
throw new Error(error);
});
if (body) {
request.write(body);
}
request.end();
};
_checkResponse = function(body, statusCode, callback){
if (statusCode > ERROR_STATUS_BOUNDARY){
throw new Error(body);
} else {
body = namespaceUtil.RemoveNamespace(body);
PARSE_STRING(body, function(err, result){
callback(result);
});
}
};
/**
* "private" method to strip off the querystring parameters and port from the URL
* @param url - url to modify
* @returns {*} - normalized URL
* @private
*/
_normalizeUrl = function(url){
var tmp = url;
// strip query portion
var idx = url.indexOf('?');
if (idx){
tmp = url.substr(0, idx);
}
// strip port
if (tmp.lastIndexOf(':') && tmp.lastIndexOf(':') > 5){
// implies port is given
tmp = tmp.substr(0, tmp.lastIndexOf(':'));
}
return tmp;
};
/**
* "private" method to put querystring and oauth parameters in lexical order
* @param url - url containing query string parameters
* @param oauthParms - object containing authorization info
* @returns {string} - normalized parameter string
* @private
*/
_normalizeParameters = function(url, oauthParms){
var uri = URL.parse(url);
// all mastercard services have ?Format=XML
var qstringHash = QUERYSTRING.parse(uri.search.split('?')[1]);
var oauthHash = oauthParms.generateParametersHash();
var nameArr = [];
var idx = 0;
// TODO Does this need to be concatenated into one array qstringhash.concat(oauthHash)
for (var qStringKey in qstringHash){
nameArr[idx] = qStringKey;
idx++;
}
for (var oauthKey in oauthHash){
nameArr[idx] = oauthKey;
idx++;
}
nameArr.sort(); // now parms are in alphabetical order
var parm = '';
var delim = '';
for (var i = 0; i < nameArr.length ; i++){
if (qstringHash[nameArr[i]]){
parm = parm + delim + nameArr[i] + '=' + qstringHash[nameArr[i]];
} else {
parm = parm + delim + nameArr[i] + '=' + oauthHash[nameArr[i]];
}
delim = AMP;
}
return parm;
};
_postProcessSignatureBaseString = function(signatureBaseString){
signatureBaseString = signatureBaseString.replace(/%20/g, '%2520');
return signatureBaseString.replace('!','%21');
};
module.exports.Connector = Connector;
|
*/
|
random_line_split
|
Connector.js
|
OAUTH_PARMS_CLASS = require('../common/OAuthParameters');
PARSE_STRING = require('xml2js').parseString;
var util = require('util');
var namespaceUtil = require('../common/NamespaceUtil');
AMP = '&';
OAUTH_START_STRING = 'OAuth ';
ERROR_STATUS_BOUNDARY = 300;
USER_AGENT = 'MC API OAuth Framework v1.0-node';
CRYPTO = require('crypto');
HTTPS = require('https');
FS = require('fs');
URL = require('url');
QUERYSTRING = require('querystring');
XML2JS = require('xml2js');
OAUTH_BODY_HASH = 'oauth_body_hash';
OAUTH_CONSUMER_KEY = 'oauth_consumer_key';
OAUTH_NONCE = 'oauth_nonce';
OAUTH_SIGNATURE = 'oauth_signature';
OAUTH_SIGNATURE_METHOD = 'oauth_signature_method';
OAUTH_TIMESTAMP = 'oauth_timestamp';
OAUTH_VERSION = 'oauth_version';
/**
* Constructor
* @param consumerKey - consumer key provided by MasterCard
* @param privateKey - path to private key //TODO UPDATE WHEN REFACTORED
* @constructor -
*/
function
|
(consumerKey, privateKey, callback){
this.consumerKey = consumerKey;
this.privateKey = privateKey;
this.callback = callback;
this.setCallback = function(callback){
this.callback = callback;
};
/**
* Method that service classes should call in order to execute a request against MasterCard's servers
* @param url - URL including querystring parameters to connect to
* @param requestMethod - GET, PUT, POST, or DELETE
* @param body - request body [optional]
* @param oauth_parms - existing oauth_parameters [optional]
*/
this.doRequest = function(url, requestMethod, bodyObject, oauthParms){
if (!this.callback){
this.callback = function(response){ return response; };
}
if (oauthParms){
//TODO allow for additional parms to be added
} else {
oauthParms = new OAUTH_PARMS_CLASS.OAuthParameters(this.consumerKey);
}
if (bodyObject){
var builder = new XML2JS.Builder();
var body = builder.buildObject(bodyObject);
body = namespaceUtil.AddNamespace(body);
oauthParms.generateBodyHash(body);
}
var signatureBaseString = _generateSignatureBaseString(url, requestMethod, oauthParms);
signatureBaseString = _postProcessSignatureBaseString(signatureBaseString);
_signAndMakeRequest(oauthParms, this.privateKey, signatureBaseString, requestMethod, url, body, this.callback);
};
}
// CLASS METHODS
/**
* "private method" to generate the signature base string from the URL, request method, and parameters
* @param url - URL to connect to
* @param requestMethod - HTTP request method
* @param oauthParms - parameters containing authorization information
* @returns {string|*} - signature base string generated
* @private
*/
_generateSignatureBaseString = function(url, requestMethod, oauthParms){
var signatureBaseString = encodeURIComponent(requestMethod.toUpperCase()) +
AMP + encodeURIComponent((_normalizeUrl(url))) + AMP +
encodeURIComponent(_normalizeParameters(url, oauthParms));
return signatureBaseString;
};
/**
* "private" method to sign the signature base string and connect to MasterCard's servers
* @param oauthParms - parameters containing authorization information
* @param privateKey - URSA private key object
* @param requestMethod -
* @param url -
* @param body - request body [optional]
* @private
*/
_signAndMakeRequest = function(oauthParms, privateKey, signatureBaseString, requestMethod, url, body, callback){
var signer = CRYPTO.createSign('RSA-SHA1');
signer = signer.update(new Buffer(signatureBaseString));
oauthParms.signature = signer.sign(privateKey, 'base64');
oauthParms.signature = encodeURIComponent(oauthParms.signature);
oauthParms.signature = oauthParms.signature.replace('+','%20');
oauthParms.signature = oauthParms.signature.replace('*','%2A');
oauthParms.signature = oauthParms.signature.replace('~','%7E');
var authHeader = _buildAuthHeaderString(oauthParms);
_doConnect(url,requestMethod,authHeader, body, callback);
};
/**
* "private" method to build the authorization header from the contents of the oauth parameters
* @param oauthParms - object containing authorization information
* @returns {string} - authorization header
* @private
*/
_buildAuthHeaderString = function(oauthParms){
var header = '';
header = header + 'oauth_consumer_key' + '="' + oauthParms.consumerKey + '",';
header = header + 'oauth_nonce' + '="' + oauthParms.nonce + '",';
header = header + 'oauth_signature' + '="' + oauthParms.signature + '",';
header = header + 'oauth_signature_method' + '="' + oauthParms.signatureMethod + '",';
header = header + 'oauth_timestamp' + '="' + oauthParms.timeStamp + '",';
header = header + 'oauth_version' + '="' + oauthParms.oauthVersion + '"';
if (oauthParms.bodyHash){
header = OAUTH_START_STRING + OAUTH_BODY_HASH
+ '="' + oauthParms.bodyHash + '",' + header;
} else {
header = OAUTH_START_STRING + header;
}
return header;
};
/**
* "private" method to make the connection to MasterCard's servers
* @param url - url to connect to
* @param requestMethod - HTTP request method ('GET','PUT','POST','DELETE'
* @param body - request body [optional]
* @private
*/
_doConnect = function(url, requestMethod, authHeader, body, callback){
requestMethod = requestMethod.toUpperCase();
uri = URL.parse(url);
var options;
if (body) {
options = {
hostname: uri.host.split(':')[0],
path: uri.path,
method: requestMethod,
headers: {
'Authorization': authHeader,
'User-Agent': USER_AGENT,
'content-type' : 'application/xml;charset=UTF-8',
'content-length' : body.length
},
cert: FS.readFileSync(process.env.SSL_CERT_FILE)
};
} else {
options = {
hostname: uri.host.split(':')[0],
path: uri.path,
method: requestMethod,
headers: {
'Authorization': authHeader,
'User-Agent': USER_AGENT
},
cert: FS.readFileSync(process.env.SSL_CERT_FILE)
}
}
options.agent = new HTTPS.Agent(options);
var request = HTTPS.request(options, function(response){
var retBody = '';
var statusCode = response.statusCode;
response.on('data', function(chunk){
retBody += chunk;
}).on('end', function(){
_checkResponse(retBody, statusCode, callback);
});
}).on('error', function(error){
throw new Error(error);
});
if (body) {
request.write(body);
}
request.end();
};
_checkResponse = function(body, statusCode, callback){
if (statusCode > ERROR_STATUS_BOUNDARY){
throw new Error(body);
} else {
body = namespaceUtil.RemoveNamespace(body);
PARSE_STRING(body, function(err, result){
callback(result);
});
}
};
/**
* "private" method to strip off the querystring parameters and port from the URL
* @param url - url to modify
* @returns {*} - normalized URL
* @private
*/
_normalizeUrl = function(url){
var tmp = url;
// strip query portion
var idx = url.indexOf('?');
if (idx){
tmp = url.substr(0, idx);
}
// strip port
if (tmp.lastIndexOf(':') && tmp.lastIndexOf(':') > 5){
// implies port is given
tmp = tmp.substr(0, tmp.lastIndexOf(':'));
}
return tmp;
};
/**
* "private" method to put querystring and oauth parameters in lexical order
* @param url - url containing query string parameters
* @param oauthParms - object containing authorization info
* @returns {string} - normalized parameter string
* @private
*/
_normalizeParameters = function(url, oauthParms){
var uri = URL.parse(url);
// all mastercard services have ?Format=XML
var qstringHash = QUERYSTRING.parse(uri.search.split('?')[1]);
var oauthHash = oauthParms.generateParametersHash();
var nameArr = [];
var idx = 0;
// TODO Does this need to be concatenated into one array qstringhash.concat(oauthHash)
for (var qStringKey in qstringHash){
nameArr[idx] = qStringKey;
idx++;
}
for (var oauthKey in oauthHash){
nameArr[idx] = oauthKey;
idx++;
}
nameArr.sort(); // now parms are in alphabetical order
var parm = '';
var delim = '';
for (var i = 0; i < nameArr.length ; i++){
if (qstringHash[nameArr[i]]){
parm = parm + delim + nameArr[i] + '=' + qstringHash[nameArr[i]];
} else {
parm = parm + delim + nameArr[i] + '=' + oauthHash[nameArr[i]];
}
delim = AMP;
}
return parm;
};
_postProcessSignatureBaseString = function(signatureBaseString){
signatureBaseString = signatureBaseString.replace(/%20/g, '%2520');
return signatureBaseString.replace('!','%21');
};
module.exports.Connector = Connector;
|
Connector
|
identifier_name
|
player_state.rs
|
use rocket::request::{self, FromRequest};
use rocket::{Request, State, Outcome};
use game_state;
use quest::Quest;
use rocket::http::Cookies;
use thread_safe::Ts;
use battle::Battle;
use enemy::Enemy;
pub struct AcceptedQuest {
quest_id: i32,
enemy_id: i32,
name: String,
enemies_killed: i32,
req_enemies_killed: i32,
}
impl AcceptedQuest {
pub fn new(quest: &Quest) -> AcceptedQuest {
AcceptedQuest{ quest_id: quest.id(), enemy_id: quest.enemy_id(), name: quest.name().clone(), enemies_killed: 0, req_enemies_killed: quest.kill_goal() }
}
pub fn quest_id(&self) -> i32 {
self.quest_id
}
}
pub struct PlayerState {
username: String,
accepted_quests: Vec<AcceptedQuest>,
pub current_battle: Option<Battle>,
}
pub enum BattleState<'a> {
Fight(&'a Battle),
End(BattleReward)
}
pub struct BattleReward {
}
impl PlayerState {
pub fn new(username: String) -> PlayerState {
PlayerState { username: username, accepted_quests: vec![], current_battle: None }
}
pub fn username(&self) -> &String {
return &self.username;
}
pub fn
|
(&mut self, quest: &Quest) {
println!("accepting quest {}", quest.id());
self.accepted_quests.push(AcceptedQuest::new(quest))
}
pub fn accepted_quests(&self) -> &Vec<AcceptedQuest> {
&self.accepted_quests
}
pub fn init_battle(&mut self, enemy: Enemy) -> &Battle {
self.current_battle = Some(Battle::new(enemy));
self.current_battle.as_ref().unwrap()
}
fn on_enemy_killed(&mut self, enemy_id: i32) {
for quest in self.accepted_quests.iter_mut().filter(|quest| {
quest.enemy_id == enemy_id
}) {
quest.enemies_killed += 1;
println!("quest progress! {}/{}", quest.enemies_killed, quest.req_enemies_killed);
}
}
pub fn fight(&mut self) -> BattleState {
let won = {
let battle = self.current_battle.as_mut().unwrap();
battle.do_damage(1);
battle.enemy.current_hp <= 0
};
if won {
let enemy_id = self.current_battle.as_mut().unwrap().enemy.id;
self.on_enemy_killed(enemy_id);
self.current_battle = None;
BattleState::End(BattleReward{})
} else {
BattleState::Fight(self.current_battle.as_ref().unwrap())
}
}
}
pub type TsPlayerState = Ts<PlayerState>;
impl<'a, 'r> FromRequest<'a, 'r> for TsPlayerState {
type Error = ();
fn from_request(request: &'a Request<'r>) -> request::Outcome<TsPlayerState, ()> {
let cookies = request.guard::<Cookies>()?;
match cookies.get("id") {
Some(cookie) => {
let state = request.guard::<State<game_state::TsGameState>>()?;
let lock = state.read();
match lock.get_player(cookie.value()) {
Some(player) => {
Outcome::Success(player)
},
None => Outcome::Forward(())
}
},
None => Outcome::Forward(())
}
}
}
|
accept_quest
|
identifier_name
|
player_state.rs
|
use rocket::request::{self, FromRequest};
use rocket::{Request, State, Outcome};
use game_state;
use quest::Quest;
use rocket::http::Cookies;
use thread_safe::Ts;
use battle::Battle;
use enemy::Enemy;
pub struct AcceptedQuest {
quest_id: i32,
enemy_id: i32,
name: String,
enemies_killed: i32,
req_enemies_killed: i32,
}
impl AcceptedQuest {
pub fn new(quest: &Quest) -> AcceptedQuest {
AcceptedQuest{ quest_id: quest.id(), enemy_id: quest.enemy_id(), name: quest.name().clone(), enemies_killed: 0, req_enemies_killed: quest.kill_goal() }
}
pub fn quest_id(&self) -> i32 {
self.quest_id
}
}
pub struct PlayerState {
username: String,
accepted_quests: Vec<AcceptedQuest>,
pub current_battle: Option<Battle>,
}
pub enum BattleState<'a> {
Fight(&'a Battle),
End(BattleReward)
}
pub struct BattleReward {
}
impl PlayerState {
pub fn new(username: String) -> PlayerState {
|
return &self.username;
}
pub fn accept_quest(&mut self, quest: &Quest) {
println!("accepting quest {}", quest.id());
self.accepted_quests.push(AcceptedQuest::new(quest))
}
pub fn accepted_quests(&self) -> &Vec<AcceptedQuest> {
&self.accepted_quests
}
pub fn init_battle(&mut self, enemy: Enemy) -> &Battle {
self.current_battle = Some(Battle::new(enemy));
self.current_battle.as_ref().unwrap()
}
fn on_enemy_killed(&mut self, enemy_id: i32) {
for quest in self.accepted_quests.iter_mut().filter(|quest| {
quest.enemy_id == enemy_id
}) {
quest.enemies_killed += 1;
println!("quest progress! {}/{}", quest.enemies_killed, quest.req_enemies_killed);
}
}
pub fn fight(&mut self) -> BattleState {
let won = {
let battle = self.current_battle.as_mut().unwrap();
battle.do_damage(1);
battle.enemy.current_hp <= 0
};
if won {
let enemy_id = self.current_battle.as_mut().unwrap().enemy.id;
self.on_enemy_killed(enemy_id);
self.current_battle = None;
BattleState::End(BattleReward{})
} else {
BattleState::Fight(self.current_battle.as_ref().unwrap())
}
}
}
pub type TsPlayerState = Ts<PlayerState>;
impl<'a, 'r> FromRequest<'a, 'r> for TsPlayerState {
type Error = ();
fn from_request(request: &'a Request<'r>) -> request::Outcome<TsPlayerState, ()> {
let cookies = request.guard::<Cookies>()?;
match cookies.get("id") {
Some(cookie) => {
let state = request.guard::<State<game_state::TsGameState>>()?;
let lock = state.read();
match lock.get_player(cookie.value()) {
Some(player) => {
Outcome::Success(player)
},
None => Outcome::Forward(())
}
},
None => Outcome::Forward(())
}
}
}
|
PlayerState { username: username, accepted_quests: vec![], current_battle: None }
}
pub fn username(&self) -> &String {
|
random_line_split
|
player_state.rs
|
use rocket::request::{self, FromRequest};
use rocket::{Request, State, Outcome};
use game_state;
use quest::Quest;
use rocket::http::Cookies;
use thread_safe::Ts;
use battle::Battle;
use enemy::Enemy;
pub struct AcceptedQuest {
quest_id: i32,
enemy_id: i32,
name: String,
enemies_killed: i32,
req_enemies_killed: i32,
}
impl AcceptedQuest {
pub fn new(quest: &Quest) -> AcceptedQuest {
AcceptedQuest{ quest_id: quest.id(), enemy_id: quest.enemy_id(), name: quest.name().clone(), enemies_killed: 0, req_enemies_killed: quest.kill_goal() }
}
pub fn quest_id(&self) -> i32 {
self.quest_id
}
}
pub struct PlayerState {
username: String,
accepted_quests: Vec<AcceptedQuest>,
pub current_battle: Option<Battle>,
}
pub enum BattleState<'a> {
Fight(&'a Battle),
End(BattleReward)
}
pub struct BattleReward {
}
impl PlayerState {
pub fn new(username: String) -> PlayerState {
PlayerState { username: username, accepted_quests: vec![], current_battle: None }
}
pub fn username(&self) -> &String
|
pub fn accept_quest(&mut self, quest: &Quest) {
println!("accepting quest {}", quest.id());
self.accepted_quests.push(AcceptedQuest::new(quest))
}
pub fn accepted_quests(&self) -> &Vec<AcceptedQuest> {
&self.accepted_quests
}
pub fn init_battle(&mut self, enemy: Enemy) -> &Battle {
self.current_battle = Some(Battle::new(enemy));
self.current_battle.as_ref().unwrap()
}
fn on_enemy_killed(&mut self, enemy_id: i32) {
for quest in self.accepted_quests.iter_mut().filter(|quest| {
quest.enemy_id == enemy_id
}) {
quest.enemies_killed += 1;
println!("quest progress! {}/{}", quest.enemies_killed, quest.req_enemies_killed);
}
}
pub fn fight(&mut self) -> BattleState {
let won = {
let battle = self.current_battle.as_mut().unwrap();
battle.do_damage(1);
battle.enemy.current_hp <= 0
};
if won {
let enemy_id = self.current_battle.as_mut().unwrap().enemy.id;
self.on_enemy_killed(enemy_id);
self.current_battle = None;
BattleState::End(BattleReward{})
} else {
BattleState::Fight(self.current_battle.as_ref().unwrap())
}
}
}
pub type TsPlayerState = Ts<PlayerState>;
impl<'a, 'r> FromRequest<'a, 'r> for TsPlayerState {
type Error = ();
fn from_request(request: &'a Request<'r>) -> request::Outcome<TsPlayerState, ()> {
let cookies = request.guard::<Cookies>()?;
match cookies.get("id") {
Some(cookie) => {
let state = request.guard::<State<game_state::TsGameState>>()?;
let lock = state.read();
match lock.get_player(cookie.value()) {
Some(player) => {
Outcome::Success(player)
},
None => Outcome::Forward(())
}
},
None => Outcome::Forward(())
}
}
}
|
{
return &self.username;
}
|
identifier_body
|
player_state.rs
|
use rocket::request::{self, FromRequest};
use rocket::{Request, State, Outcome};
use game_state;
use quest::Quest;
use rocket::http::Cookies;
use thread_safe::Ts;
use battle::Battle;
use enemy::Enemy;
pub struct AcceptedQuest {
quest_id: i32,
enemy_id: i32,
name: String,
enemies_killed: i32,
req_enemies_killed: i32,
}
impl AcceptedQuest {
pub fn new(quest: &Quest) -> AcceptedQuest {
AcceptedQuest{ quest_id: quest.id(), enemy_id: quest.enemy_id(), name: quest.name().clone(), enemies_killed: 0, req_enemies_killed: quest.kill_goal() }
}
pub fn quest_id(&self) -> i32 {
self.quest_id
}
}
pub struct PlayerState {
username: String,
accepted_quests: Vec<AcceptedQuest>,
pub current_battle: Option<Battle>,
}
pub enum BattleState<'a> {
Fight(&'a Battle),
End(BattleReward)
}
pub struct BattleReward {
}
impl PlayerState {
pub fn new(username: String) -> PlayerState {
PlayerState { username: username, accepted_quests: vec![], current_battle: None }
}
pub fn username(&self) -> &String {
return &self.username;
}
pub fn accept_quest(&mut self, quest: &Quest) {
println!("accepting quest {}", quest.id());
self.accepted_quests.push(AcceptedQuest::new(quest))
}
pub fn accepted_quests(&self) -> &Vec<AcceptedQuest> {
&self.accepted_quests
}
pub fn init_battle(&mut self, enemy: Enemy) -> &Battle {
self.current_battle = Some(Battle::new(enemy));
self.current_battle.as_ref().unwrap()
}
fn on_enemy_killed(&mut self, enemy_id: i32) {
for quest in self.accepted_quests.iter_mut().filter(|quest| {
quest.enemy_id == enemy_id
}) {
quest.enemies_killed += 1;
println!("quest progress! {}/{}", quest.enemies_killed, quest.req_enemies_killed);
}
}
pub fn fight(&mut self) -> BattleState {
let won = {
let battle = self.current_battle.as_mut().unwrap();
battle.do_damage(1);
battle.enemy.current_hp <= 0
};
if won
|
else {
BattleState::Fight(self.current_battle.as_ref().unwrap())
}
}
}
pub type TsPlayerState = Ts<PlayerState>;
impl<'a, 'r> FromRequest<'a, 'r> for TsPlayerState {
type Error = ();
fn from_request(request: &'a Request<'r>) -> request::Outcome<TsPlayerState, ()> {
let cookies = request.guard::<Cookies>()?;
match cookies.get("id") {
Some(cookie) => {
let state = request.guard::<State<game_state::TsGameState>>()?;
let lock = state.read();
match lock.get_player(cookie.value()) {
Some(player) => {
Outcome::Success(player)
},
None => Outcome::Forward(())
}
},
None => Outcome::Forward(())
}
}
}
|
{
let enemy_id = self.current_battle.as_mut().unwrap().enemy.id;
self.on_enemy_killed(enemy_id);
self.current_battle = None;
BattleState::End(BattleReward{})
}
|
conditional_block
|
main.rs
|
#![feature(plugin, custom_derive)]
#![plugin(rocket_codegen)]
extern crate rocket;
extern crate rocket_contrib;
extern crate uuid;
#[cfg(test)] mod tests;
use std::collections::HashMap;
use std::sync::Mutex;
use rocket::State;
use rocket_contrib::Template;
use rocket::response::{Failure, Redirect};
use rocket::http::Status;
use rocket::request::Form;
use uuid::Uuid;
static PIZZAS: &'static [&'static str] = &["Margherita", "Pepperoni", "Hawaii"];
#[get("/pizza")]
fn show_menu() -> Template {
let mut context = HashMap::new();
context.insert("pizzas",PIZZAS);
Template::render("pizza_menu", &context)
}
#[get("/pizza/order/<order_id>")]
fn show_pizza_ordered(order_id: String, database: State<PizzaOrderDatabase>) -> Result<Template, Failure> {
match Uuid::parse_str(order_id.as_str()) {
Ok(order_id) => {
match database.lock().unwrap().get(&order_id) {
Some(..) => {
let mut context = HashMap::new();
context.insert("order_id", order_id);
Ok(Template::render("pizza_ordered", &context))
},
None => {
println!("Pizza order id not found: {}", &order_id);
Err(Failure(Status::NotFound))
}
}
},
Err(..) => {
println!("Pizza order id not valid: {}", &order_id);
Err(Failure(Status::NotFound))
},
}
}
#[derive(FromForm)]
struct PizzaOrder {
name: String,
}
type PizzaOrderDatabase = Mutex<HashMap<Uuid, String>>;
#[post("/pizza/order", data = "<pizza_order_form>")]
fn
|
(pizza_order_form: Form<PizzaOrder>, database: State<PizzaOrderDatabase>) -> Result<Redirect, Failure> {
let pizza_order = pizza_order_form.get();
let pizza_name = &pizza_order.name;
let pizzas: Vec<String> = PIZZAS.iter().map(|p| p.to_string().to_lowercase()).collect();
if pizzas.contains(&pizza_name.to_lowercase()){
println!("Pizza ordered: {}", &pizza_name);
let order_id = Uuid::new_v4();
database.lock().unwrap().insert(order_id.clone(), pizza_name.clone().to_lowercase() );
Ok(Redirect::to(format!("/pizza/order/{}",order_id).as_str()))
} else {
println!("Pizza ordered not found: {}", &pizza_name);
Err(Failure(Status::NotFound))
}
}
fn mount_rocket() -> rocket::Rocket {
rocket::ignite()
.manage(Mutex::new(HashMap::<Uuid,String>::new()))
.mount("/", routes![show_menu,order_pizza,show_pizza_ordered])
}
fn main() {
mount_rocket().launch();
}
|
order_pizza
|
identifier_name
|
main.rs
|
#![feature(plugin, custom_derive)]
#![plugin(rocket_codegen)]
extern crate rocket;
extern crate rocket_contrib;
extern crate uuid;
#[cfg(test)] mod tests;
use std::collections::HashMap;
use std::sync::Mutex;
use rocket::State;
use rocket_contrib::Template;
use rocket::response::{Failure, Redirect};
use rocket::http::Status;
use rocket::request::Form;
use uuid::Uuid;
static PIZZAS: &'static [&'static str] = &["Margherita", "Pepperoni", "Hawaii"];
#[get("/pizza")]
fn show_menu() -> Template {
let mut context = HashMap::new();
context.insert("pizzas",PIZZAS);
|
fn show_pizza_ordered(order_id: String, database: State<PizzaOrderDatabase>) -> Result<Template, Failure> {
match Uuid::parse_str(order_id.as_str()) {
Ok(order_id) => {
match database.lock().unwrap().get(&order_id) {
Some(..) => {
let mut context = HashMap::new();
context.insert("order_id", order_id);
Ok(Template::render("pizza_ordered", &context))
},
None => {
println!("Pizza order id not found: {}", &order_id);
Err(Failure(Status::NotFound))
}
}
},
Err(..) => {
println!("Pizza order id not valid: {}", &order_id);
Err(Failure(Status::NotFound))
},
}
}
#[derive(FromForm)]
struct PizzaOrder {
name: String,
}
type PizzaOrderDatabase = Mutex<HashMap<Uuid, String>>;
#[post("/pizza/order", data = "<pizza_order_form>")]
fn order_pizza(pizza_order_form: Form<PizzaOrder>, database: State<PizzaOrderDatabase>) -> Result<Redirect, Failure> {
let pizza_order = pizza_order_form.get();
let pizza_name = &pizza_order.name;
let pizzas: Vec<String> = PIZZAS.iter().map(|p| p.to_string().to_lowercase()).collect();
if pizzas.contains(&pizza_name.to_lowercase()){
println!("Pizza ordered: {}", &pizza_name);
let order_id = Uuid::new_v4();
database.lock().unwrap().insert(order_id.clone(), pizza_name.clone().to_lowercase() );
Ok(Redirect::to(format!("/pizza/order/{}",order_id).as_str()))
} else {
println!("Pizza ordered not found: {}", &pizza_name);
Err(Failure(Status::NotFound))
}
}
fn mount_rocket() -> rocket::Rocket {
rocket::ignite()
.manage(Mutex::new(HashMap::<Uuid,String>::new()))
.mount("/", routes![show_menu,order_pizza,show_pizza_ordered])
}
fn main() {
mount_rocket().launch();
}
|
Template::render("pizza_menu", &context)
}
#[get("/pizza/order/<order_id>")]
|
random_line_split
|
main.rs
|
#![feature(plugin, custom_derive)]
#![plugin(rocket_codegen)]
extern crate rocket;
extern crate rocket_contrib;
extern crate uuid;
#[cfg(test)] mod tests;
use std::collections::HashMap;
use std::sync::Mutex;
use rocket::State;
use rocket_contrib::Template;
use rocket::response::{Failure, Redirect};
use rocket::http::Status;
use rocket::request::Form;
use uuid::Uuid;
static PIZZAS: &'static [&'static str] = &["Margherita", "Pepperoni", "Hawaii"];
#[get("/pizza")]
fn show_menu() -> Template {
let mut context = HashMap::new();
context.insert("pizzas",PIZZAS);
Template::render("pizza_menu", &context)
}
#[get("/pizza/order/<order_id>")]
fn show_pizza_ordered(order_id: String, database: State<PizzaOrderDatabase>) -> Result<Template, Failure> {
match Uuid::parse_str(order_id.as_str()) {
Ok(order_id) => {
match database.lock().unwrap().get(&order_id) {
Some(..) =>
|
,
None => {
println!("Pizza order id not found: {}", &order_id);
Err(Failure(Status::NotFound))
}
}
},
Err(..) => {
println!("Pizza order id not valid: {}", &order_id);
Err(Failure(Status::NotFound))
},
}
}
#[derive(FromForm)]
struct PizzaOrder {
name: String,
}
type PizzaOrderDatabase = Mutex<HashMap<Uuid, String>>;
#[post("/pizza/order", data = "<pizza_order_form>")]
fn order_pizza(pizza_order_form: Form<PizzaOrder>, database: State<PizzaOrderDatabase>) -> Result<Redirect, Failure> {
let pizza_order = pizza_order_form.get();
let pizza_name = &pizza_order.name;
let pizzas: Vec<String> = PIZZAS.iter().map(|p| p.to_string().to_lowercase()).collect();
if pizzas.contains(&pizza_name.to_lowercase()){
println!("Pizza ordered: {}", &pizza_name);
let order_id = Uuid::new_v4();
database.lock().unwrap().insert(order_id.clone(), pizza_name.clone().to_lowercase() );
Ok(Redirect::to(format!("/pizza/order/{}",order_id).as_str()))
} else {
println!("Pizza ordered not found: {}", &pizza_name);
Err(Failure(Status::NotFound))
}
}
fn mount_rocket() -> rocket::Rocket {
rocket::ignite()
.manage(Mutex::new(HashMap::<Uuid,String>::new()))
.mount("/", routes![show_menu,order_pizza,show_pizza_ordered])
}
fn main() {
mount_rocket().launch();
}
|
{
let mut context = HashMap::new();
context.insert("order_id", order_id);
Ok(Template::render("pizza_ordered", &context))
}
|
conditional_block
|
main.rs
|
#![feature(plugin, custom_derive)]
#![plugin(rocket_codegen)]
extern crate rocket;
extern crate rocket_contrib;
extern crate uuid;
#[cfg(test)] mod tests;
use std::collections::HashMap;
use std::sync::Mutex;
use rocket::State;
use rocket_contrib::Template;
use rocket::response::{Failure, Redirect};
use rocket::http::Status;
use rocket::request::Form;
use uuid::Uuid;
static PIZZAS: &'static [&'static str] = &["Margherita", "Pepperoni", "Hawaii"];
#[get("/pizza")]
fn show_menu() -> Template {
let mut context = HashMap::new();
context.insert("pizzas",PIZZAS);
Template::render("pizza_menu", &context)
}
#[get("/pizza/order/<order_id>")]
fn show_pizza_ordered(order_id: String, database: State<PizzaOrderDatabase>) -> Result<Template, Failure> {
match Uuid::parse_str(order_id.as_str()) {
Ok(order_id) => {
match database.lock().unwrap().get(&order_id) {
Some(..) => {
let mut context = HashMap::new();
context.insert("order_id", order_id);
Ok(Template::render("pizza_ordered", &context))
},
None => {
println!("Pizza order id not found: {}", &order_id);
Err(Failure(Status::NotFound))
}
}
},
Err(..) => {
println!("Pizza order id not valid: {}", &order_id);
Err(Failure(Status::NotFound))
},
}
}
#[derive(FromForm)]
struct PizzaOrder {
name: String,
}
type PizzaOrderDatabase = Mutex<HashMap<Uuid, String>>;
#[post("/pizza/order", data = "<pizza_order_form>")]
fn order_pizza(pizza_order_form: Form<PizzaOrder>, database: State<PizzaOrderDatabase>) -> Result<Redirect, Failure> {
let pizza_order = pizza_order_form.get();
let pizza_name = &pizza_order.name;
let pizzas: Vec<String> = PIZZAS.iter().map(|p| p.to_string().to_lowercase()).collect();
if pizzas.contains(&pizza_name.to_lowercase()){
println!("Pizza ordered: {}", &pizza_name);
let order_id = Uuid::new_v4();
database.lock().unwrap().insert(order_id.clone(), pizza_name.clone().to_lowercase() );
Ok(Redirect::to(format!("/pizza/order/{}",order_id).as_str()))
} else {
println!("Pizza ordered not found: {}", &pizza_name);
Err(Failure(Status::NotFound))
}
}
fn mount_rocket() -> rocket::Rocket {
rocket::ignite()
.manage(Mutex::new(HashMap::<Uuid,String>::new()))
.mount("/", routes![show_menu,order_pizza,show_pizza_ordered])
}
fn main()
|
{
mount_rocket().launch();
}
|
identifier_body
|
|
udp-multicast.rs
|
use std::{env, str};
use std::net::{UdpSocket, Ipv4Addr};
fn
|
() {
let mcast_group: Ipv4Addr = "239.0.0.1".parse().unwrap();
let port: u16 = 6000;
let any = "0.0.0.0".parse().unwrap();
let mut buffer = [0u8; 1600];
if env::args().count() > 1 {
let socket = UdpSocket::bind((any, port)).expect("Could not bind client socket");
socket.join_multicast_v4(&mcast_group, &any).expect("Could not join multicast group");
socket.recv_from(&mut buffer).expect("Failed to write to server");
print!("{}", str::from_utf8(&buffer).expect("Could not write buffer as string"));
} else {
let socket = UdpSocket::bind((any, 0)).expect("Could not bind socket");
socket.send_to("Hello world!".as_bytes(), &(mcast_group, port)).expect("Failed to write data");
}
}
|
main
|
identifier_name
|
udp-multicast.rs
|
use std::{env, str};
use std::net::{UdpSocket, Ipv4Addr};
|
let any = "0.0.0.0".parse().unwrap();
let mut buffer = [0u8; 1600];
if env::args().count() > 1 {
let socket = UdpSocket::bind((any, port)).expect("Could not bind client socket");
socket.join_multicast_v4(&mcast_group, &any).expect("Could not join multicast group");
socket.recv_from(&mut buffer).expect("Failed to write to server");
print!("{}", str::from_utf8(&buffer).expect("Could not write buffer as string"));
} else {
let socket = UdpSocket::bind((any, 0)).expect("Could not bind socket");
socket.send_to("Hello world!".as_bytes(), &(mcast_group, port)).expect("Failed to write data");
}
}
|
fn main() {
let mcast_group: Ipv4Addr = "239.0.0.1".parse().unwrap();
let port: u16 = 6000;
|
random_line_split
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.